@geastack/compiler 1.0.48 → 1.0.62

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/README.md +57 -19
  2. package/dist/cli.js +2 -1
  3. package/dist/compiler.d.ts +1 -1
  4. package/dist/compiler.js +13 -6
  5. package/dist/conversion/derive.js +5 -0
  6. package/dist/conversion/native-field-view.d.ts +7 -0
  7. package/dist/conversion/native-field-view.js +50 -0
  8. package/dist/conversion/native-record-products.js +1 -0
  9. package/dist/conversion/native-view-origins.d.ts +1 -1
  10. package/dist/conversion/native-view-origins.js +5 -4
  11. package/dist/conversion/nodes.d.ts +9 -0
  12. package/dist/conversion/nodes.js +18 -0
  13. package/dist/conversion/record-view.d.ts +25 -1
  14. package/dist/conversion/record-view.js +61 -2
  15. package/dist/conversion/structural-plan.js +7 -6
  16. package/dist/ir/borrowed-field-reads.d.ts +30 -0
  17. package/dist/ir/borrowed-field-reads.js +218 -0
  18. package/dist/ir/borrowed-window-cells.d.ts +35 -0
  19. package/dist/ir/borrowed-window-cells.js +117 -0
  20. package/dist/ir/call-dispatch.js +21 -4
  21. package/dist/ir/callable-class-flow.js +269 -43
  22. package/dist/ir/captures.js +18 -1
  23. package/dist/ir/certify.js +14 -1
  24. package/dist/ir/construction-only-fields.d.ts +15 -1
  25. package/dist/ir/construction-only-fields.js +71 -3
  26. package/dist/ir/dead-logical-merge.d.ts +4 -0
  27. package/dist/ir/dead-logical-merge.js +89 -18
  28. package/dist/ir/dense-loops.d.ts +38 -4
  29. package/dist/ir/dense-loops.js +112 -17
  30. package/dist/ir/dense-read-windows.d.ts +42 -0
  31. package/dist/ir/dense-read-windows.js +137 -0
  32. package/dist/ir/facts.d.ts +12 -0
  33. package/dist/ir/facts.js +18 -2
  34. package/dist/ir/field-read-reuse.d.ts +71 -0
  35. package/dist/ir/field-read-reuse.js +430 -0
  36. package/dist/ir/hoist.d.ts +19 -2
  37. package/dist/ir/hoist.js +143 -24
  38. package/dist/ir/lower-narrow.js +19 -1
  39. package/dist/ir/model.d.ts +19 -0
  40. package/dist/ir/native-field-view-domains.d.ts +12 -2
  41. package/dist/ir/native-field-view-domains.js +51 -15
  42. package/dist/ir/native-field-view-facts.js +5 -2
  43. package/dist/ir/native-method-frames.js +15 -2
  44. package/dist/ir/plain-field-read.d.ts +31 -0
  45. package/dist/ir/plain-field-read.js +51 -0
  46. package/dist/ir/program-facts.d.ts +14 -0
  47. package/dist/ir/program-facts.js +85 -2
  48. package/dist/ir/proven-branches.js +8 -1
  49. package/dist/ir/publish-conversion-recipes.js +5 -1
  50. package/dist/ir/short-circuit-threading.d.ts +12 -4
  51. package/dist/ir/short-circuit-threading.js +124 -12
  52. package/dist/ir/stable-cell-reads.d.ts +24 -1
  53. package/dist/ir/stable-cell-reads.js +65 -42
  54. package/dist/ir/write-effects.d.ts +42 -0
  55. package/dist/ir/write-effects.js +208 -0
  56. package/dist/plugins/gea/contract.d.ts +3 -2
  57. package/dist/plugins/gea/contract.js +3 -1
  58. package/dist/plugins/gea/host.d.ts +7 -2
  59. package/dist/plugins/gea/host.js +25 -5
  60. package/dist/project-preparation.d.ts +11 -0
  61. package/dist/project-preparation.js +44 -0
  62. package/dist/projection/classes.d.ts +8 -0
  63. package/dist/projection/classes.js +112 -12
  64. package/dist/projection/dispatch.d.ts +24 -4
  65. package/dist/projection/dispatch.js +71 -2
  66. package/dist/projection/fields.js +2 -2
  67. package/dist/representation/model.d.ts +3 -0
  68. package/dist/representation/model.js +3 -0
  69. package/dist/representation/value-records.js +22 -0
  70. package/dist/semantics/frontend-timing.d.ts +9 -0
  71. package/dist/semantics/frontend-timing.js +43 -2
  72. package/dist/semantics/frontend.js +103 -7
  73. package/dist/semantics/model/operations.d.ts +7 -0
  74. package/dist/semantics/normalize/binding-fixpoint.js +7 -2
  75. package/dist/semantics/normalize/callable-data-write.js +6 -2
  76. package/dist/semantics/normalize/field-bindings.js +151 -111
  77. package/dist/semantics/normalize/flow/callable-reach.js +27 -0
  78. package/dist/semantics/normalize/flow/component-solver.js +23 -5
  79. package/dist/semantics/normalize/flow/source-record-data.js +6 -2
  80. package/dist/semantics/normalize/flow/source-value-session.d.ts +13 -0
  81. package/dist/semantics/normalize/flow/source-value-session.js +207 -65
  82. package/dist/semantics/normalize/global-host-mutations.js +162 -1
  83. package/dist/semantics/normalize/parameter-bindings.js +16 -1
  84. package/dist/semantics/normalize/producers/class-lifecycle.js +2 -1
  85. package/dist/semantics/normalize/producers/erasure.js +13 -8
  86. package/dist/semantics/subclass-member-overlay-transform.d.ts +3 -2
  87. package/dist/semantics/subclass-member-overlay-transform.js +416 -316
  88. package/dist/semantics/typescript-tsgo.d.ts +20 -0
  89. package/dist/semantics/typescript-tsgo.js +832 -0
  90. package/dist/semantics/typescript.d.ts +0 -9
  91. package/dist/semantics/typescript.js +4 -1
  92. package/dist/targets/cpp/borrowed-call-entry.d.ts +9 -0
  93. package/dist/targets/cpp/borrowed-call-entry.js +12 -2
  94. package/dist/targets/cpp/captures.js +4 -0
  95. package/dist/targets/cpp/class-properties/computed-method-value.d.ts +1 -1
  96. package/dist/targets/cpp/class-properties/computed-method-value.js +17 -7
  97. package/dist/targets/cpp/class-properties/emit-class-properties.d.ts +8 -0
  98. package/dist/targets/cpp/class-properties/emit-class-properties.js +62 -2
  99. package/dist/targets/cpp/class-properties/native-method-read.js +12 -1
  100. package/dist/targets/cpp/conversions.js +1 -0
  101. package/dist/targets/cpp/emit-arrays.d.ts +5 -0
  102. package/dist/targets/cpp/emit-arrays.js +60 -10
  103. package/dist/targets/cpp/emit-binding-reference.d.ts +19 -6
  104. package/dist/targets/cpp/emit-binding-reference.js +26 -8
  105. package/dist/targets/cpp/emit-bindings.js +22 -0
  106. package/dist/targets/cpp/emit-callable.js +133 -16
  107. package/dist/targets/cpp/emit-carrier-members.d.ts +6 -0
  108. package/dist/targets/cpp/emit-carrier-members.js +24 -2
  109. package/dist/targets/cpp/emit-context.d.ts +97 -1
  110. package/dist/targets/cpp/emit-context.js +52 -0
  111. package/dist/targets/cpp/emit-equality.js +3 -0
  112. package/dist/targets/cpp/emit-narrowing.js +9 -0
  113. package/dist/targets/cpp/emit-native-field-view.d.ts +24 -0
  114. package/dist/targets/cpp/emit-native-field-view.js +87 -8
  115. package/dist/targets/cpp/emit-properties.js +139 -16
  116. package/dist/targets/cpp/emit-record-view.js +49 -22
  117. package/dist/targets/cpp/emit-return.js +5 -1
  118. package/dist/targets/cpp/emit-tonumber.js +4 -1
  119. package/dist/targets/cpp/emit-union-properties.js +1 -1
  120. package/dist/targets/cpp/emit.d.ts +4 -1
  121. package/dist/targets/cpp/emit.js +148 -6
  122. package/dist/targets/cpp/reactive-dependencies.js +100 -28
  123. package/dist/targets/cpp/translation-unit.js +71 -17
  124. package/dist/targets/cpp/virtual-methods.d.ts +2 -2
  125. package/dist/targets/cpp/virtual-methods.js +11 -3
  126. package/package.json +1 -1
  127. package/src/targets/cpp/runtime/gea_runtime.h +400 -21
@@ -59,6 +59,8 @@ export interface ProgramFacts {
59
59
  readonly singleEvaluationClasses: ReadonlySet<DeclarationId>;
60
60
  /** Cells the whole program writes once, with a function or class it allocates there -- see `definitionCellsOf`. */
61
61
  readonly definitionCells: ReadonlySet<DeclarationId>;
62
+ /** Cells the whole program writes once, with a record it allocates there -- see `allocationCellsOf`. */
63
+ readonly allocationCells: ReadonlyMap<DeclarationId, AllocationCell>;
62
64
  }
63
65
  /**
64
66
  * The target's own decisions this census needs mid-order, none of them
@@ -89,6 +91,18 @@ export interface ProgramFactsPolicy {
89
91
  /** Whether `receiver.key` is a plain data-field load -- see `borrow-effects.ts`'s `PlainFieldRead`. */
90
92
  readonly plainFieldRead: PlainFieldRead;
91
93
  }
94
+ /** The one allocation an `allocationCells` cell holds. */
95
+ export interface AllocationCell {
96
+ /** The carrier the allocation was written into the cell as. */
97
+ readonly representation: string;
98
+ /**
99
+ * The keys the allocation itself defined before it was written: its
100
+ * `allocate-record` fields and every default data definition on the chain of
101
+ * values the literal threads (`define-own-property` answers the same
102
+ * object). Each set its field's presence bit, and only a `delete` clears one.
103
+ */
104
+ readonly keys: ReadonlySet<string>;
105
+ }
92
106
  /**
93
107
  * Everything a translation unit needs to know about the whole program before
94
108
  * it renders a body, in the one dependency order these questions actually
@@ -5,7 +5,7 @@ import { fixedFieldDeletionsOf, integrityRestrictionsOf } from './integrity-rest
5
5
  import { singleEvaluationClassesOf } from './class-evaluation.js';
6
6
  import { callableMemberCandidatesOf } from './callable-member-candidates.js';
7
7
  import { callableFlowCandidatesOf } from './callable-flow-candidates.js';
8
- import { cyclicBlocksOf } from './dominance.js';
8
+ import { cyclicBlocksOf, dominatorTreeOf } from './dominance.js';
9
9
  import { allOperationsOf } from './model.js';
10
10
  import { operandsOfIrOperation } from './queries.js';
11
11
  import { buildDyingArgumentIndex } from './transfer.js';
@@ -93,6 +93,87 @@ const definitionCellsOf = (bodies) => {
93
93
  definitions.delete(declaration);
94
94
  return definitions;
95
95
  };
96
+ /**
97
+ * Cells the whole program writes exactly once, and with a record or object it
98
+ * allocates at that write: `const gull: Gull = { ... }`, a closure's own state
99
+ * captured by every method it hands out.
100
+ *
101
+ * A field read through such a cell needs no copy of the cell: the cell holds
102
+ * that one allocation from its write on (a read before the write is of
103
+ * `undefined`, which no field read gets past). And the allocation is plain, never
104
+ * a live view a dynamic writer stored, so its declared members are its own.
105
+ * Writes are counted from every body, renewals included, so a cell written
106
+ * anywhere else is not one.
107
+ */
108
+ const allocationCellsOf = (bodies) => {
109
+ // Each allocated value, by the allocation it answers.
110
+ const rootOf = new Map();
111
+ const writeCounts = new Map();
112
+ const allocations = new Map();
113
+ for (const body of bodies) {
114
+ const constants = new Map();
115
+ for (const block of body.blocks.values())
116
+ for (const operation of allOperationsOf(block))
117
+ if (operation.kind === 'constant' && operation.literal === 'string')
118
+ constants.set(operation.result.id, operation.text);
119
+ const definitions = new Map();
120
+ const writes = [];
121
+ const initial = new Map();
122
+ for (const block of body.blocks.values()) {
123
+ allOperationsOf(block).forEach((operation, index) => {
124
+ if (operation.kind === 'allocate-record' || operation.kind === 'allocate-ordinary-object') {
125
+ rootOf.set(operation.result.id, operation.result.id);
126
+ initial.set(operation.result.id, operation.kind === 'allocate-record' ? operation.fields.map((field) => field.key) : []);
127
+ }
128
+ // A literal's own properties are defined one by one, each answering the same object.
129
+ if (operation.kind === 'define-own-property') {
130
+ const root = rootOf.get(operation.receiver.value);
131
+ if (root !== undefined) {
132
+ if (operation.result !== null)
133
+ rootOf.set(operation.result.id, root);
134
+ const key = constants.get(operation.key.value);
135
+ const { writable, enumerable, configurable } = operation.attributes;
136
+ if (key !== undefined && writable && enumerable && configurable && operation.typedComputedWrite === undefined)
137
+ definitions.set(root, [...(definitions.get(root) ?? []), { key, at: { block: block.id, index } }]);
138
+ }
139
+ }
140
+ if (operation.kind === 'binding-renew')
141
+ writeCounts.set(operation.declaration, 2);
142
+ if (operation.kind !== 'binding-write')
143
+ return;
144
+ writeCounts.set(operation.declaration, (writeCounts.get(operation.declaration) ?? 0) + 1);
145
+ const root = rootOf.get(operation.value.value);
146
+ if (root !== undefined)
147
+ writes.push({
148
+ declaration: operation.declaration,
149
+ root,
150
+ representation: representationKey(operation.value.representation),
151
+ at: { block: block.id, index }
152
+ });
153
+ });
154
+ }
155
+ // A definition counts only where every path to the write ran it after
156
+ // the allocation the write stores: earlier in the write's block, or in a
157
+ // block dominating it (the allocation dominates the definition, so no path
158
+ // re-allocates between the two without passing the definition again).
159
+ let dominance = null;
160
+ for (const write of writes) {
161
+ const keys = new Set(initial.get(write.root) ?? []);
162
+ for (const definition of definitions.get(write.root) ?? []) {
163
+ const before = definition.at.block === write.at.block
164
+ ? definition.at.index < write.at.index
165
+ : (dominance ??= dominatorTreeOf(body)).dominates(definition.at.block, write.at.block);
166
+ if (before)
167
+ keys.add(definition.key);
168
+ }
169
+ allocations.set(write.declaration, { representation: write.representation, keys });
170
+ }
171
+ }
172
+ for (const declaration of allocations.keys())
173
+ if (writeCounts.get(declaration) !== 1)
174
+ allocations.delete(declaration);
175
+ return allocations;
176
+ };
96
177
  const buildRepeatedConstructorIndex = (bodies, directCallables) => {
97
178
  const allocated = new Map();
98
179
  const writeCounts = new Map();
@@ -379,6 +460,7 @@ export const programFactsOf = (bodies, directCallables, placements, policy) => {
379
460
  const fixedFieldStateConstant = !nativeIntegrityRestricted.any && !fixedFieldDeletionsOf(bodies);
380
461
  const singleEvaluationClasses = singleEvaluationClassesOf(bodies);
381
462
  const definitionCells = definitionCellsOf(bodies);
463
+ const allocationCells = allocationCellsOf(bodies);
382
464
  return {
383
465
  callableMemberCandidates,
384
466
  callableFlowCandidates,
@@ -390,6 +472,7 @@ export const programFactsOf = (bodies, directCallables, placements, policy) => {
390
472
  nativeIntegrityRestricted,
391
473
  fixedFieldStateConstant,
392
474
  singleEvaluationClasses,
393
- definitionCells
475
+ definitionCells,
476
+ allocationCells
394
477
  };
395
478
  };
@@ -140,9 +140,16 @@ export const provenResultTruthiness = (graph) => {
140
140
  seen.add(type);
141
141
  const shape = graph.structuralTypes?.get(type)?.shape;
142
142
  let tags = null;
143
+ // A declared integer (`int32`, `int64`) is a JS number: tagged apart from
144
+ // `number`, `kind === KIND_ROCK` over an `i32` field was proved false and
145
+ // every `&&` arm built on it was pruned (a game drew none of its props).
143
146
  if (shape?.kind === 'primitive')
144
147
  tags =
145
- shape.primitive === 'never' ? new Set() : ['void', 'unknown', 'any'].includes(shape.primitive) ? null : new Set([shape.primitive]);
148
+ shape.primitive === 'never'
149
+ ? new Set()
150
+ : ['void', 'unknown', 'any'].includes(shape.primitive)
151
+ ? null
152
+ : new Set([shape.primitive === 'int32' || shape.primitive === 'int64' ? 'number' : shape.primitive]);
146
153
  else if (shape?.kind === 'literal')
147
154
  tags = new Set([shape.primitive]);
148
155
  else if (shape?.kind === 'unique-symbol')
@@ -4,6 +4,8 @@ import { abiOfCallee } from '../projection/callee.js';
4
4
  import { classMemberOf, declaredRecordFieldOf, recordFieldsOfShape } from '../projection/fields.js';
5
5
  import { representationKey } from '../representation/model.js';
6
6
  import { publishDenseLoopPlan } from './dense-loops.js';
7
+ import { codeFreeFieldReadOf } from './field-read-reuse.js';
8
+ import { plainFieldReadOf } from './plain-field-read.js';
7
9
  import { hostNamespaceReadsOf } from './host-namespace-reads.js';
8
10
  import { allOperationsOf } from './model.js';
9
11
  import { operationConversionInputsOf, operationConversionsOf } from './operation-conversions.js';
@@ -139,6 +141,8 @@ export const publishConversionRecipes = (input) => {
139
141
  ? nativeCallableFlowOf([...nativeBodies.values()], input.placements, input.classes, input.conversions, undefined, input.deriver)
140
142
  : undefined;
141
143
  const virtualFrames = settledVirtualCallFramesOf(input.bodies.values(), input.classes, input.conversions);
144
+ const plainFieldRead = plainFieldReadOf(input.classes, input.deriver);
145
+ const codeFreeFieldRead = codeFreeFieldReadOf(input.bodies.values(), input.classes, input.deriver);
142
146
  const hostMethodAliases = buildHostMethodAliasIndex([...input.bodies.values()], input.placements, input.hosts);
143
147
  const bodies = new Map();
144
148
  for (const [id, body] of nativeBodies) {
@@ -216,7 +220,7 @@ export const publishConversionRecipes = (input) => {
216
220
  terminator: publish(block.terminator)
217
221
  }
218
222
  ]));
219
- bodies.set(id, publishDenseLoopPlan({ ...body, blocks, hostNamespaceCensus }, input.placements, input.conversions));
223
+ bodies.set(id, publishDenseLoopPlan({ ...body, blocks, hostNamespaceCensus }, input.placements, input.conversions, plainFieldRead, codeFreeFieldRead));
220
224
  }
221
225
  const needsReadProof = [...bodies.values()].some((body) => [...body.blocks.values()].some((block) => block.operations.some((operation) => {
222
226
  if (operation.kind !== 'convert')
@@ -1,4 +1,4 @@
1
- import type { PhysicalBodyId } from '../identity/ids.js';
1
+ import { type PhysicalBodyId } from '../identity/ids.js';
2
2
  import type { IrBody } from './model.js';
3
3
  /**
4
4
  * Thread the edge of a short-circuit join whose value the edge already decides.
@@ -13,11 +13,19 @@ import type { IrBody } from './model.js';
13
13
  * 1.5% slower than the `&&` it came from (an escape-time loop), and
14
14
  * neither unrolls it when the bound is a constant.
15
15
  *
16
+ * Operands of different types merge into a wider carrier, so each edge first
17
+ * widens its own value: `if (engaged && player)` stores `engaged` or `player`
18
+ * into an `Optional<TaggedUnion<bool, Ref<Player>>>` -- a retain, an
19
+ * out-of-line assignment and an arm dispatch -- only to ask whether it is
20
+ * truthy. A widening into an arm keeps the value, so it keeps its truthiness:
21
+ * the decided edge threads past it, and the other edge tests its own value and
22
+ * branches, leaving the merge unbuilt.
23
+ *
16
24
  * Only the exact shape: a join holding one phi (and at most a `to-boolean`
17
25
  * test of it) and nothing else, branching on it, read by nothing else; an
18
26
  * edge from the deciding branch, directly or through a block holding only a
19
- * jump. The threaded target must have no phi of its own, since the new edge
20
- * would owe it an incoming value. Anything else is left as it was, and a body
21
- * the rewrite would leave invalid is kept unchanged.
27
+ * jump (or only that widening). The threaded target must have no phi of its
28
+ * own, since the new edge would owe it an incoming value. Anything else is
29
+ * left as it was, and a body the rewrite would leave invalid is kept unchanged.
22
30
  */
23
31
  export declare const threadShortCircuitJoins: (bodies: ReadonlyMap<PhysicalBodyId, IrBody>) => ReadonlyMap<PhysicalBodyId, IrBody>;
@@ -1,3 +1,5 @@
1
+ import { irValueId } from '../identity/ids.js';
2
+ import { representationKey } from '../representation/model.js';
1
3
  import { allOperationsOf } from './model.js';
2
4
  import { operandsOfIrOperation, successorsOfTerminator } from './queries.js';
3
5
  import { verifyIrBody } from './verify.js';
@@ -14,12 +16,20 @@ import { verifyIrBody } from './verify.js';
14
16
  * 1.5% slower than the `&&` it came from (an escape-time loop), and
15
17
  * neither unrolls it when the bound is a constant.
16
18
  *
19
+ * Operands of different types merge into a wider carrier, so each edge first
20
+ * widens its own value: `if (engaged && player)` stores `engaged` or `player`
21
+ * into an `Optional<TaggedUnion<bool, Ref<Player>>>` -- a retain, an
22
+ * out-of-line assignment and an arm dispatch -- only to ask whether it is
23
+ * truthy. A widening into an arm keeps the value, so it keeps its truthiness:
24
+ * the decided edge threads past it, and the other edge tests its own value and
25
+ * branches, leaving the merge unbuilt.
26
+ *
17
27
  * Only the exact shape: a join holding one phi (and at most a `to-boolean`
18
28
  * test of it) and nothing else, branching on it, read by nothing else; an
19
29
  * edge from the deciding branch, directly or through a block holding only a
20
- * jump. The threaded target must have no phi of its own, since the new edge
21
- * would owe it an incoming value. Anything else is left as it was, and a body
22
- * the rewrite would leave invalid is kept unchanged.
30
+ * jump (or only that widening). The threaded target must have no phi of its
31
+ * own, since the new edge would owe it an incoming value. Anything else is
32
+ * left as it was, and a body the rewrite would leave invalid is kept unchanged.
23
33
  */
24
34
  export const threadShortCircuitJoins = (bodies) => {
25
35
  let output = null;
@@ -32,6 +42,31 @@ export const threadShortCircuitJoins = (bodies) => {
32
42
  }
33
43
  return output ?? bodies;
34
44
  };
45
+ /** Carriers `ir/certify/runtime-helper.ts` admits a `to-boolean` test over (`manifest/capabilities.ts`). */
46
+ const testableKinds = new Set([
47
+ 'scalar',
48
+ 'string',
49
+ 'optional',
50
+ 'tagged-union',
51
+ 'class-ref',
52
+ 'record',
53
+ 'record-with-index',
54
+ 'native-record-ref'
55
+ ]);
56
+ const armsOf = (representation) => representation.kind === 'optional'
57
+ ? armsOf(representation.payload)
58
+ : representation.kind === 'tagged-union'
59
+ ? representation.arms.flatMap((arm) => armsOf(arm.value))
60
+ : [representation];
61
+ /** Every arm of `source` is an arm of `target`: the conversion places the value, and absence stays absence. */
62
+ const widensIntoArm = (source, target) => {
63
+ if (target.kind !== 'optional' && target.kind !== 'tagged-union')
64
+ return false;
65
+ if (source.kind === 'optional' && target.kind !== 'optional')
66
+ return false;
67
+ const targetArms = new Set(armsOf(target).map(representationKey));
68
+ return armsOf(source).every((arm) => targetArms.has(representationKey(arm)));
69
+ };
35
70
  const threadedBody = (body) => {
36
71
  if (body.tryRegions.length > 0 || (body.iteratorCloseRegions?.length ?? 0) > 0 || body.generator || body.generatorPrologueBoundary)
37
72
  return body;
@@ -51,6 +86,9 @@ const threadedBody = (body) => {
51
86
  predecessors.set(target, list);
52
87
  }
53
88
  }
89
+ // A block other facts name by id stays: removing it would leave them pointing nowhere.
90
+ const pinned = new Set([body.entry, ...(body.bindingLifetimeOrigins?.values() ?? [])]);
91
+ const loopPlan = body.denseLoopPlan === undefined ? '' : JSON.stringify(body.denseLoopPlan);
54
92
  // The truthiness `value` is known to have along the edge out of `from`, when
55
93
  // `from` branches on it (or on its `to-boolean` test) and the edge is one arm.
56
94
  const decided = (from, toward, value) => {
@@ -64,7 +102,29 @@ const threadedBody = (body) => {
64
102
  return undefined;
65
103
  return toward === terminator.whenTrue;
66
104
  };
105
+ // The value an edge widened into the merge's carrier as its block's last
106
+ // step, when nothing else reads the widened copy.
107
+ const widenedSource = (via, edge, join) => {
108
+ if (via.terminator.kind !== 'jump' || via.terminator.target !== join)
109
+ return null;
110
+ const last = via.operations[via.operations.length - 1];
111
+ if (last?.kind !== 'convert' || last.result.id !== edge.value.value || uses.get(last.result.id) !== 1)
112
+ return null;
113
+ if (last.rebuild !== undefined || last.presence !== undefined)
114
+ return null;
115
+ return widensIntoArm(last.source.representation, last.result.representation) ? last.source : null;
116
+ };
67
117
  const blocks = new Map(body.blocks);
118
+ const values = new Map(body.values);
119
+ const removed = new Set();
120
+ let ordinal = 0;
121
+ const freshValue = (representation) => {
122
+ while (values.has(irValueId(body.owner, ordinal)))
123
+ ordinal++;
124
+ const id = irValueId(body.owner, ordinal++);
125
+ values.set(id, representation);
126
+ return id;
127
+ };
68
128
  let changed = false;
69
129
  for (const join of body.blocks.values()) {
70
130
  const [phi, test, ...rest] = join.operations;
@@ -77,11 +137,28 @@ const threadedBody = (body) => {
77
137
  if (branchOn !== tested || uses.get(tested) !== 1 || (test !== undefined && uses.get(phi.result.id) !== 1))
78
138
  continue;
79
139
  const { whenTrue, whenFalse } = join.terminator;
140
+ const phiFree = (target) => blocks.get(target)?.operations.some((operation) => operation.kind === 'phi') === false;
80
141
  const threads = [];
81
142
  for (const edge of phi.incoming) {
82
143
  const via = blocks.get(edge.block);
83
144
  if (via === undefined)
84
145
  continue;
146
+ const widened = widenedSource(via, edge, join.id);
147
+ if (widened !== null) {
148
+ const stripped = { ...via, operations: via.operations.slice(0, -1) };
149
+ const only = predecessors.get(via.id);
150
+ const from = only?.length === 1 && stripped.operations.length === 0 ? blocks.get(only[0]) : undefined;
151
+ const truth = from === undefined ? undefined : decided(from, via.id, widened);
152
+ if (truth !== undefined) {
153
+ const target = truth ? whenTrue : whenFalse;
154
+ if (phiFree(target))
155
+ threads.push({ kind: 'retarget', via: stripped, target, edge, strips: true });
156
+ }
157
+ else if (test?.kind === 'test' && testableKinds.has(widened.representation.kind) && phiFree(whenTrue) && phiFree(whenFalse)) {
158
+ threads.push({ kind: 'test', via: stripped, source: widened, edge, strips: true });
159
+ }
160
+ continue;
161
+ }
85
162
  // Directly from the deciding branch, or through a block that only jumps here.
86
163
  let decider = via;
87
164
  let edgeTarget = join.id;
@@ -97,23 +174,58 @@ const threadedBody = (body) => {
97
174
  if (truth === undefined)
98
175
  continue;
99
176
  const target = truth ? whenTrue : whenFalse;
100
- if (blocks.get(target)?.operations.some((operation) => operation.kind === 'phi') !== false)
177
+ if (!phiFree(target))
101
178
  continue;
102
- threads.push({ via, target, edge });
179
+ threads.push({ kind: 'retarget', via, target, edge, strips: false });
103
180
  }
104
- // A join every edge threads past is the whole expression decided by its
105
- // left operand, which is not this shape; leave it for the C++ compiler.
106
- if (threads.length === 0 || threads.length === phi.incoming.length)
181
+ const everyEdge = threads.length === phi.incoming.length;
182
+ // A join every edge threads past by retargeting alone is the whole
183
+ // expression decided by its left operand, which is not this shape; leave
184
+ // it for the C++ compiler. One whose remaining edges each test their own
185
+ // value is left with no predecessor, and goes.
186
+ if (threads.length === 0 || (everyEdge && threads.every((thread) => thread.kind === 'retarget')))
107
187
  continue;
108
- for (const { via, target } of threads)
109
- blocks.set(via.id, retarget(via, join.id, target));
110
- const incoming = phi.incoming.filter((edge) => !threads.some((thread) => thread.edge === edge));
188
+ if (everyEdge && (pinned.has(join.id) || loopPlan.includes(JSON.stringify(join.id))))
189
+ continue;
190
+ if (!everyEdge && threads.some((thread) => thread.kind === 'test'))
191
+ continue;
192
+ for (const thread of threads) {
193
+ // The widening the edge no longer performs.
194
+ if (thread.strips)
195
+ values.delete(thread.edge.value.value);
196
+ if (thread.kind === 'retarget') {
197
+ blocks.set(thread.via.id, retarget(thread.via, join.id, thread.target));
198
+ continue;
199
+ }
200
+ const joinTest = test;
201
+ const result = { id: freshValue(joinTest.result.representation), representation: joinTest.result.representation };
202
+ const own = { kind: 'test', lineage: joinTest.lineage, predicate: 'to-boolean', value: thread.source, result };
203
+ blocks.set(thread.via.id, {
204
+ ...thread.via,
205
+ operations: [...thread.via.operations, own],
206
+ terminator: { ...join.terminator, condition: { value: result.id, representation: result.representation } }
207
+ });
208
+ }
111
209
  changed = true;
210
+ if (everyEdge) {
211
+ blocks.delete(join.id);
212
+ removed.add(join.id);
213
+ values.delete(phi.result.id);
214
+ if (test !== undefined)
215
+ values.delete(tested);
216
+ continue;
217
+ }
218
+ const incoming = phi.incoming.filter((edge) => !threads.some((thread) => thread.edge === edge));
112
219
  blocks.set(join.id, { ...blocks.get(join.id), operations: [{ ...phi, incoming }, ...(test === undefined ? [] : [test])] });
113
220
  }
114
221
  if (!changed)
115
222
  return body;
116
- const rewritten = { ...body, blocks };
223
+ const rewritten = {
224
+ ...body,
225
+ blocks,
226
+ values,
227
+ blockOrder: removed.size === 0 ? body.blockOrder : body.blockOrder.filter((block) => !removed.has(block))
228
+ };
117
229
  return verifyIrBody(rewritten).length === 0 ? rewritten : body;
118
230
  };
119
231
  const retarget = (block, from, to) => {
@@ -1,5 +1,5 @@
1
1
  import type { DeclarationId, IrValueId } from '../identity/ids.js';
2
- import type { IrBody } from './model.js';
2
+ import type { IrBlockId, IrBody, IrNonTerminatorOperation } from './model.js';
3
3
  /**
4
4
  * Cell reads whose every use sees the cell holding exactly what the read saw:
5
5
  * no write to the cell lies on any path from the read to the use. Such a read
@@ -38,3 +38,26 @@ import type { IrBody } from './model.js';
38
38
  * block of its loop and hands control to its dismiss targets.
39
39
  */
40
40
  export declare const stableCellReadsOf: (body: IrBody, admits: (declaration: DeclarationId) => boolean) => ReadonlySet<IrValueId>;
41
+ /** A read `cleanWindowReadsOf` asks about: where it is, and which operations change what it saw. */
42
+ export interface WindowRead {
43
+ readonly value: IrValueId;
44
+ readonly block: IrBlockId;
45
+ readonly index: number;
46
+ readonly clobbers: (operation: IrNonTerminatorOperation) => boolean;
47
+ /** Sites that must see what the read saw besides the uses of `value` itself (the reads of a cell it initializes). */
48
+ readonly extraUses?: readonly WindowSite[];
49
+ }
50
+ export interface WindowSite {
51
+ readonly block: IrBlockId;
52
+ readonly index: number;
53
+ }
54
+ /**
55
+ * The reads no clobbering operation separates from any of their uses, by the
56
+ * flood `stableCellReadsOf` describes. `useAtClobber` admits a use at the
57
+ * clobbering operation itself: right for a cell write, whose value operand is
58
+ * evaluated before the store, and wrong for a call that receives the read and
59
+ * may then overwrite what it names.
60
+ */
61
+ export declare const cleanWindowReadsOf: (body: IrBody, reads: readonly WindowRead[], useAtClobber: boolean) => ReadonlySet<IrValueId>;
62
+ /** Where each value is used; a merge input (`phi`) at the end of its incoming block. */
63
+ export declare const useSitesOf: (body: IrBody) => ReadonlyMap<IrValueId, readonly WindowSite[]>;
@@ -39,60 +39,55 @@ import { operandsOfIrOperation } from './queries.js';
39
39
  * block of its loop and hands control to its dismiss targets.
40
40
  */
41
41
  export const stableCellReadsOf = (body, admits) => {
42
- const stable = new Set();
43
- const uses = new Map();
44
- const record = (value, block, index) => {
45
- const sites = uses.get(value);
46
- if (sites)
47
- sites.push({ block, index });
48
- else
49
- uses.set(value, [{ block, index }]);
50
- };
51
- const writes = new Map();
52
42
  const reads = [];
53
- for (const [blockId, block] of body.blocks) {
54
- const written = [];
55
- for (const [index, operation] of block.operations.entries()) {
56
- if (operation.kind === 'phi') {
57
- for (const incoming of operation.incoming)
58
- record(incoming.value.value, incoming.block, body.blocks.get(incoming.block)?.operations.length ?? 0);
59
- continue;
60
- }
61
- for (const operand of operandsOfIrOperation(operation))
62
- record(operand.value, blockId, index);
63
- if (operation.kind === 'binding-write' || operation.kind === 'binding-renew' || operation.kind === 'allocate-constructor') {
64
- written.push({ index, declaration: operation.declaration });
65
- }
43
+ for (const [blockId, block] of body.blocks)
44
+ for (const [index, operation] of block.operations.entries())
66
45
  if (operation.kind === 'binding-read' && admits(operation.declaration)) {
67
- reads.push({ value: operation.result.id, declaration: operation.declaration, block: blockId, index });
46
+ const declaration = operation.declaration;
47
+ reads.push({
48
+ value: operation.result.id,
49
+ block: blockId,
50
+ index,
51
+ clobbers: (candidate) => (candidate.kind === 'binding-write' || candidate.kind === 'binding-renew' || candidate.kind === 'allocate-constructor') &&
52
+ candidate.declaration === declaration
53
+ });
68
54
  }
69
- }
70
- for (const operand of operandsOfIrOperation(block.terminator))
71
- record(operand.value, blockId, block.operations.length);
72
- writes.set(blockId, written);
73
- }
55
+ return cleanWindowReadsOf(body, reads, true);
56
+ };
57
+ /**
58
+ * The reads no clobbering operation separates from any of their uses, by the
59
+ * flood `stableCellReadsOf` describes. `useAtClobber` admits a use at the
60
+ * clobbering operation itself: right for a cell write, whose value operand is
61
+ * evaluated before the store, and wrong for a call that receives the read and
62
+ * may then overwrite what it names.
63
+ */
64
+ export const cleanWindowReadsOf = (body, reads, useAtClobber) => {
65
+ const stable = new Set();
66
+ if (reads.length === 0)
67
+ return stable;
68
+ const uses = useSitesOf(body);
74
69
  const graph = controlFlowGraphOf(body);
75
70
  const implicit = implicitSuccessorsOf(body, graph);
76
- const finallyWritten = new Set();
77
- for (const block of finallyBlocksOf(body, graph))
78
- for (const write of writes.get(block) ?? [])
79
- finallyWritten.add(write.declaration);
71
+ const finallyBlocks = [...finallyBlocksOf(body, graph)];
80
72
  const successorsOf = (block) => [...(graph.successors.get(block) ?? []), ...(implicit.get(block) ?? [])];
81
73
  for (const read of reads) {
82
- const sites = uses.get(read.value);
83
- if (sites === undefined || finallyWritten.has(read.declaration))
74
+ const sites = [...(uses.get(read.value) ?? []), ...(read.extraUses ?? [])];
75
+ if (sites.length === 0)
76
+ continue;
77
+ if (finallyBlocks.some((block) => body.blocks.get(block)?.operations.some(read.clobbers) === true))
84
78
  continue;
85
- const firstWriteFrom = (block, from) => {
86
- for (const write of writes.get(block) ?? [])
87
- if (write.index >= from && write.declaration === read.declaration)
88
- return write.index;
79
+ const firstClobberFrom = (block, from) => {
80
+ const operations = body.blocks.get(block)?.operations ?? [];
81
+ for (let index = from; index < operations.length; index++)
82
+ if (read.clobbers(operations[index]))
83
+ return index;
89
84
  return Number.POSITIVE_INFINITY;
90
85
  };
91
86
  const limits = new Map();
92
87
  const poisoned = new Set();
93
88
  const pending = [];
94
89
  const enter = (block, from) => {
95
- const limit = firstWriteFrom(block, from);
90
+ const limit = firstClobberFrom(block, from);
96
91
  limits.set(block, limit);
97
92
  const clean = limit === Number.POSITIVE_INFINITY;
98
93
  for (const successor of successorsOf(block))
@@ -115,9 +110,37 @@ export const stableCellReadsOf = (body, admits) => {
115
110
  for (const successor of successorsOf(next.block))
116
111
  pending.push({ block: successor, clean: false });
117
112
  }
118
- if (sites.every((site) => !poisoned.has(site.block) && site.index <= (limits.get(site.block) ?? Number.NEGATIVE_INFINITY))) {
113
+ const before = (site) => {
114
+ const limit = limits.get(site.block) ?? Number.NEGATIVE_INFINITY;
115
+ return useAtClobber ? site.index <= limit : site.index < limit;
116
+ };
117
+ if (sites.every((site) => !poisoned.has(site.block) && before(site)))
119
118
  stable.add(read.value);
120
- }
121
119
  }
122
120
  return stable;
123
121
  };
122
+ /** Where each value is used; a merge input (`phi`) at the end of its incoming block. */
123
+ export const useSitesOf = (body) => {
124
+ const uses = new Map();
125
+ const record = (value, block, index) => {
126
+ const sites = uses.get(value);
127
+ if (sites)
128
+ sites.push({ block, index });
129
+ else
130
+ uses.set(value, [{ block, index }]);
131
+ };
132
+ for (const [blockId, block] of body.blocks) {
133
+ for (const [index, operation] of block.operations.entries()) {
134
+ if (operation.kind === 'phi') {
135
+ for (const incoming of operation.incoming)
136
+ record(incoming.value.value, incoming.block, body.blocks.get(incoming.block)?.operations.length ?? 0);
137
+ continue;
138
+ }
139
+ for (const operand of operandsOfIrOperation(operation))
140
+ record(operand.value, blockId, index);
141
+ }
142
+ for (const operand of operandsOfIrOperation(block.terminator))
143
+ record(operand.value, blockId, block.operations.length);
144
+ }
145
+ return uses;
146
+ };
@@ -0,0 +1,42 @@
1
+ import type { Representation } from '../representation/model.js';
2
+ import { type PlainFieldRead } from './borrow-effects.js';
3
+ import type { IrBody, IrNonTerminatorOperation } from './model.js';
4
+ /**
5
+ * Which property keys running an operation can store into, on any object.
6
+ *
7
+ * A read of `scene.fog` that a later statement uses names the same value at
8
+ * that use only when nothing between the two can store `fog`: then the read
9
+ * can name the field instead of retaining a copy of it (`targets/cpp`'s
10
+ * stable field reads). Construction-only fields (`construction-only-fields.ts`)
11
+ * answer that for the whole program at once; this answers it for one window
12
+ * of one body, so a field the program does rewrite -- a material's map, a
13
+ * scene's fog -- still holds one value across the statements that read it.
14
+ *
15
+ * Keys are matched by name, whatever the receiver: a store of `fog` anywhere
16
+ * in a callee poisons every `fog` read across the call. A call is described
17
+ * by the bodies it can enter (`CallOperation.closedCallee`), summarized to a
18
+ * fixed point over the whole program; anything that can run code this
19
+ * analysis does not see -- an unresolved call, an accessor, a coercion that
20
+ * may call `valueOf`, a suspension -- can store every key.
21
+ */
22
+ export interface WriteEffects {
23
+ /** Whether running `operation` of `body` can store `key` on some object. */
24
+ readonly mayStore: (body: IrBody, operation: IrNonTerminatorOperation, key: string) => boolean;
25
+ /** Whether reading `key` off a value carried as `receiver` loads a data field (`PlainFieldRead`). */
26
+ readonly plainField: PlainFieldRead;
27
+ }
28
+ export declare const primitive: (value: Representation) => boolean;
29
+ export declare const nativeData: (value: Representation) => boolean;
30
+ /**
31
+ * An argument a host function can only read as data: a host method handed one
32
+ * can neither call it back nor coerce it through a method of the program's
33
+ * (`join` on an array of class instances calls their `toString`).
34
+ */
35
+ export declare const inertArgument: (value: Representation) => boolean;
36
+ /**
37
+ * `codeFreeRead` answers whether reading `key` off a carrier runs none of the
38
+ * program's code: a data field, or a method a class installs (no accessor).
39
+ */
40
+ export declare const writeEffectsOf: (bodies: readonly IrBody[], plainFieldRead: PlainFieldRead, codeFreeRead: PlainFieldRead) => WriteEffects;
41
+ /** No window is clean: the answer for a context built without the census. */
42
+ export declare const everyStoreEffects: WriteEffects;