@geastack/compiler 1.0.49 → 1.0.63

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 (125) hide show
  1. package/README.md +57 -19
  2. package/dist/cli.js +2 -1
  3. package/dist/compiler.js +8 -2
  4. package/dist/conversion/derive.js +5 -0
  5. package/dist/conversion/native-field-view.d.ts +7 -0
  6. package/dist/conversion/native-field-view.js +50 -0
  7. package/dist/conversion/native-record-products.js +1 -0
  8. package/dist/conversion/native-view-origins.d.ts +1 -1
  9. package/dist/conversion/native-view-origins.js +5 -4
  10. package/dist/conversion/nodes.d.ts +9 -0
  11. package/dist/conversion/nodes.js +18 -0
  12. package/dist/conversion/record-view.d.ts +25 -1
  13. package/dist/conversion/record-view.js +61 -2
  14. package/dist/conversion/structural-plan.js +7 -6
  15. package/dist/ir/borrowed-field-reads.d.ts +30 -0
  16. package/dist/ir/borrowed-field-reads.js +218 -0
  17. package/dist/ir/borrowed-window-cells.d.ts +35 -0
  18. package/dist/ir/borrowed-window-cells.js +117 -0
  19. package/dist/ir/call-dispatch.js +21 -4
  20. package/dist/ir/callable-class-flow.js +269 -43
  21. package/dist/ir/captures.js +18 -1
  22. package/dist/ir/certify.js +14 -1
  23. package/dist/ir/construction-only-fields.d.ts +15 -1
  24. package/dist/ir/construction-only-fields.js +71 -3
  25. package/dist/ir/dead-logical-merge.d.ts +4 -0
  26. package/dist/ir/dead-logical-merge.js +89 -18
  27. package/dist/ir/dense-loops.d.ts +38 -4
  28. package/dist/ir/dense-loops.js +120 -18
  29. package/dist/ir/dense-read-windows.d.ts +42 -0
  30. package/dist/ir/dense-read-windows.js +137 -0
  31. package/dist/ir/facts.d.ts +12 -0
  32. package/dist/ir/facts.js +18 -2
  33. package/dist/ir/field-read-reuse.d.ts +71 -0
  34. package/dist/ir/field-read-reuse.js +430 -0
  35. package/dist/ir/hoist.d.ts +19 -2
  36. package/dist/ir/hoist.js +143 -24
  37. package/dist/ir/lower-narrow.js +19 -1
  38. package/dist/ir/model.d.ts +19 -0
  39. package/dist/ir/native-field-view-domains.d.ts +12 -2
  40. package/dist/ir/native-field-view-domains.js +51 -15
  41. package/dist/ir/native-field-view-facts.js +5 -2
  42. package/dist/ir/native-method-frames.js +15 -2
  43. package/dist/ir/plain-field-read.d.ts +31 -0
  44. package/dist/ir/plain-field-read.js +51 -0
  45. package/dist/ir/program-facts.d.ts +14 -0
  46. package/dist/ir/program-facts.js +85 -2
  47. package/dist/ir/proven-branches.js +8 -1
  48. package/dist/ir/publish-conversion-recipes.js +5 -1
  49. package/dist/ir/short-circuit-threading.d.ts +12 -4
  50. package/dist/ir/short-circuit-threading.js +124 -12
  51. package/dist/ir/stable-cell-reads.d.ts +24 -1
  52. package/dist/ir/stable-cell-reads.js +65 -42
  53. package/dist/ir/write-effects.d.ts +42 -0
  54. package/dist/ir/write-effects.js +208 -0
  55. package/dist/plugins/gea/contract.d.ts +3 -2
  56. package/dist/plugins/gea/contract.js +3 -1
  57. package/dist/plugins/gea/host.d.ts +7 -2
  58. package/dist/plugins/gea/host.js +25 -5
  59. package/dist/project-preparation.d.ts +11 -0
  60. package/dist/project-preparation.js +44 -0
  61. package/dist/projection/classes.d.ts +8 -0
  62. package/dist/projection/classes.js +112 -12
  63. package/dist/projection/dispatch.d.ts +24 -4
  64. package/dist/projection/dispatch.js +71 -2
  65. package/dist/projection/fields.js +2 -2
  66. package/dist/representation/model.d.ts +3 -0
  67. package/dist/representation/model.js +3 -0
  68. package/dist/representation/value-records.js +22 -0
  69. package/dist/semantics/frontend-timing.d.ts +9 -0
  70. package/dist/semantics/frontend-timing.js +43 -2
  71. package/dist/semantics/frontend.js +103 -7
  72. package/dist/semantics/model/operations.d.ts +7 -0
  73. package/dist/semantics/normalize/binding-fixpoint.js +7 -2
  74. package/dist/semantics/normalize/callable-data-write.js +6 -2
  75. package/dist/semantics/normalize/field-bindings.js +151 -111
  76. package/dist/semantics/normalize/flow/callable-reach.js +27 -0
  77. package/dist/semantics/normalize/flow/component-solver.js +23 -5
  78. package/dist/semantics/normalize/flow/source-record-data.js +6 -2
  79. package/dist/semantics/normalize/flow/source-value-session.d.ts +13 -0
  80. package/dist/semantics/normalize/flow/source-value-session.js +207 -65
  81. package/dist/semantics/normalize/global-host-mutations.js +162 -1
  82. package/dist/semantics/normalize/parameter-bindings.js +16 -1
  83. package/dist/semantics/normalize/producers/class-lifecycle.js +2 -1
  84. package/dist/semantics/normalize/producers/erasure.js +13 -8
  85. package/dist/semantics/subclass-member-overlay-transform.js +17 -4
  86. package/dist/semantics/typescript-tsgo.d.ts +20 -0
  87. package/dist/semantics/typescript-tsgo.js +832 -0
  88. package/dist/semantics/typescript.d.ts +0 -9
  89. package/dist/semantics/typescript.js +4 -1
  90. package/dist/targets/cpp/borrowed-call-entry.d.ts +9 -0
  91. package/dist/targets/cpp/borrowed-call-entry.js +12 -2
  92. package/dist/targets/cpp/captures.js +4 -0
  93. package/dist/targets/cpp/class-properties/computed-method-value.d.ts +1 -1
  94. package/dist/targets/cpp/class-properties/computed-method-value.js +17 -7
  95. package/dist/targets/cpp/class-properties/emit-class-properties.d.ts +8 -0
  96. package/dist/targets/cpp/class-properties/emit-class-properties.js +62 -2
  97. package/dist/targets/cpp/class-properties/native-method-read.js +12 -1
  98. package/dist/targets/cpp/conversions.js +1 -0
  99. package/dist/targets/cpp/emit-arrays.d.ts +5 -0
  100. package/dist/targets/cpp/emit-arrays.js +60 -10
  101. package/dist/targets/cpp/emit-binding-reference.d.ts +19 -6
  102. package/dist/targets/cpp/emit-binding-reference.js +26 -8
  103. package/dist/targets/cpp/emit-bindings.js +22 -0
  104. package/dist/targets/cpp/emit-callable.js +133 -16
  105. package/dist/targets/cpp/emit-carrier-members.d.ts +6 -0
  106. package/dist/targets/cpp/emit-carrier-members.js +24 -2
  107. package/dist/targets/cpp/emit-context.d.ts +97 -1
  108. package/dist/targets/cpp/emit-context.js +52 -0
  109. package/dist/targets/cpp/emit-equality.js +3 -0
  110. package/dist/targets/cpp/emit-narrowing.js +9 -0
  111. package/dist/targets/cpp/emit-native-field-view.d.ts +24 -0
  112. package/dist/targets/cpp/emit-native-field-view.js +87 -8
  113. package/dist/targets/cpp/emit-properties.js +139 -16
  114. package/dist/targets/cpp/emit-record-view.js +49 -22
  115. package/dist/targets/cpp/emit-return.js +5 -1
  116. package/dist/targets/cpp/emit-tonumber.js +4 -1
  117. package/dist/targets/cpp/emit-union-properties.js +1 -1
  118. package/dist/targets/cpp/emit.d.ts +4 -1
  119. package/dist/targets/cpp/emit.js +148 -6
  120. package/dist/targets/cpp/reactive-dependencies.js +100 -28
  121. package/dist/targets/cpp/translation-unit.js +71 -17
  122. package/dist/targets/cpp/virtual-methods.d.ts +2 -2
  123. package/dist/targets/cpp/virtual-methods.js +11 -3
  124. package/package.json +1 -1
  125. package/src/targets/cpp/runtime/gea_runtime.h +400 -21
@@ -3,6 +3,8 @@ import { stringConstantsOf } from './dead-values.js';
3
3
  import { dominatorTreeOf } from './dominance.js';
4
4
  import { allOperationsOf } from './model.js';
5
5
  import { operandsOfIrOperation, resultOfIrOperation } from './queries.js';
6
+ import { cleanWindowReadsOf, useSitesOf } from './stable-cell-reads.js';
7
+ import { everyStoreEffects } from './write-effects.js';
6
8
  const everyKey = Symbol('every key');
7
9
  const unkeyableKinds = new Set(['dynamic', 'unresolved', 'native-handle', 'proxy-object', 'carrier']);
8
10
  export const constructionOnlyFieldsOf = (bodies, classes, reflectiveWrites) => {
@@ -367,14 +369,60 @@ export const stableFieldCellsOf = (body, stableReads, admits) => {
367
369
  }
368
370
  return cells;
369
371
  };
372
+ /**
373
+ * Reads of a data field of a stable receiver (`stableReceiversOf`) that no
374
+ * operation between the read and any of its uses can store (`WriteEffects`),
375
+ * the field the program does rewrite elsewhere included: `const fog =
376
+ * scene.fog` across statements that never assign a `fog` names the field at
377
+ * every use, as a construction-only field's read does. `extraUses` adds the
378
+ * sites a read's value is also seen at -- the reads of the cell it
379
+ * initializes, and their uses -- so the window covers every one.
380
+ */
381
+ export const windowStableFieldReadsOf = (body, receivers, integrity, dying, effects, extraUses = () => []) => {
382
+ const keys = stringConstantsOf(body);
383
+ const reads = [];
384
+ for (const [blockId, block] of body.blocks)
385
+ for (const [index, operation] of block.operations.entries()) {
386
+ if (operation.kind !== 'get' || !receivers.has(operation.receiver.value))
387
+ continue;
388
+ if (dying.has(operation.result.id) || dying.has(operation.receiver.value))
389
+ continue;
390
+ // Only a plain member load can be named in place of its value: a
391
+ // reactive cell, a host member, a class's own prototype and a typed
392
+ // computed read each spell the read as something other than the member,
393
+ // and naming the member handed its consumers the cell itself.
394
+ if (operation.reactive === true ||
395
+ operation.hostMethod !== undefined ||
396
+ operation.callableOwnPrototype === true ||
397
+ operation.typedComputedRead !== undefined)
398
+ continue;
399
+ const key = keys.get(operation.key.value);
400
+ const receiver = operation.receiver.representation;
401
+ if (key === undefined ||
402
+ (receiver.kind !== 'class-ref' && receiver.kind !== 'record' && receiver.kind !== 'native-record-ref') ||
403
+ integrity.restricts(receiver) ||
404
+ !effects.plainField(receiver, key))
405
+ continue;
406
+ reads.push({
407
+ value: operation.result.id,
408
+ block: blockId,
409
+ index,
410
+ clobbers: (candidate) => effects.mayStore(body, candidate, key),
411
+ extraUses: extraUses(operation.result.id)
412
+ });
413
+ }
414
+ return cleanWindowReadsOf(body, reads, false);
415
+ };
370
416
  /**
371
417
  * `stableFieldReadsOf` and `stableFieldCellsOf` together. A read whose one use
372
418
  * is the write into its cell is dying -- the write moves it in -- and so is no
373
419
  * stable read on its own; it becomes one when that cell is admitted, because
374
420
  * an admitted cell's write stores nothing and the move never happens.
375
421
  */
376
- export const stableFieldReadsAndCellsOf = (body, receivers, fields, integrity, dying, admits) => {
377
- const reads = stableFieldReadsOf(body, receivers, fields, integrity, dying);
422
+ export const stableFieldReadsAndCellsOf = (body, receivers, fields, integrity, dying, admits, effects = everyStoreEffects) => {
423
+ const reads = new Set(stableFieldReadsOf(body, receivers, fields, integrity, dying));
424
+ for (const value of windowStableFieldReadsOf(body, receivers, integrity, dying, effects))
425
+ reads.add(value);
378
426
  const uses = new Map();
379
427
  const written = new Map();
380
428
  for (const block of body.blocks.values())
@@ -387,7 +435,27 @@ export const stableFieldReadsAndCellsOf = (body, receivers, fields, integrity, d
387
435
  const intoCell = (value) => written.has(value) && uses.get(value) === 1;
388
436
  // Asked of this body's values only, so the program's whole dying set is
389
437
  // filtered as it is asked, not copied for every body rendered.
390
- const candidates = stableFieldReadsOf(body, receivers, fields, integrity, { has: (value) => dying.has(value) && !intoCell(value) });
438
+ const candidateDying = { has: (value) => dying.has(value) && !intoCell(value) };
439
+ const candidates = new Set(stableFieldReadsOf(body, receivers, fields, integrity, candidateDying));
440
+ if (effects !== everyStoreEffects) {
441
+ // A read stored into a cell is seen wherever the cell is read, and
442
+ // wherever those reads are used.
443
+ const sites = useSitesOf(body);
444
+ const cellSites = new Map();
445
+ for (const [block, contents] of body.blocks)
446
+ for (const [index, operation] of contents.operations.entries())
447
+ if (operation.kind === 'binding-read') {
448
+ const list = cellSites.get(operation.declaration) ?? [];
449
+ list.push({ block, index }, ...(sites.get(operation.result.id) ?? []));
450
+ cellSites.set(operation.declaration, list);
451
+ }
452
+ const intoCellUses = (value) => {
453
+ const declaration = written.get(value);
454
+ return declaration !== undefined && intoCell(value) ? (cellSites.get(declaration) ?? []) : [];
455
+ };
456
+ for (const value of windowStableFieldReadsOf(body, receivers, integrity, candidateDying, effects, intoCellUses))
457
+ candidates.add(value);
458
+ }
391
459
  const cells = stableFieldCellsOf(body, candidates, admits);
392
460
  const all = new Set(reads);
393
461
  for (const value of candidates) {
@@ -3,5 +3,9 @@ import type { SemanticOperation } from '../semantics/model/operations.js';
3
3
  import { type DeadLogicalMergeValueOperation, type IrBody, type IrOperation } from './model.js';
4
4
  /** A source-object fact licenses only the exact && left's falsy control edge,
5
5
  * never an ordinary conversion of a shared reference into the result carrier.
6
+ * The fact is either the semantic one (`logicalLeftObjectTruthy`, every source
7
+ * value an object-producing expression) or this body's own definitions of the
8
+ * left value (`objectValued` below), for a left the source session cannot see
9
+ * through: `x as T` out of an `any` value.
6
10
  */
7
11
  export declare const deadLogicalMergeValueMatches: (operation: DeadLogicalMergeValueOperation, semantic: SemanticOperation | null, body: IrBody, semanticOperationOf?: (lineage: NonNullable<IrOperation["lineage"]>) => SemanticOperation | null, conversions?: Pick<ConversionCensus, "nodeById">) => boolean;
@@ -5,12 +5,15 @@ import { dominatorTreeOf } from './dominance.js';
5
5
  import { allOperationsOf } from './model.js';
6
6
  /** A source-object fact licenses only the exact && left's falsy control edge,
7
7
  * never an ordinary conversion of a shared reference into the result carrier.
8
+ * The fact is either the semantic one (`logicalLeftObjectTruthy`, every source
9
+ * value an object-producing expression) or this body's own definitions of the
10
+ * left value (`objectValued` below), for a left the source session cannot see
11
+ * through: `x as T` out of an `any` value.
8
12
  */
9
13
  export const deadLogicalMergeValueMatches = (operation, semantic, body, semanticOperationOf, conversions) => {
10
14
  if (semantic?.family !== 'computation' ||
11
15
  semantic.form !== 'logical' ||
12
16
  semantic.operator !== '&&' ||
13
- semantic.logicalLeftObjectTruthy !== true ||
14
17
  resultOf(semantic, 'value')?.id !== operation.lineage ||
15
18
  body.sourceOwner !== (semantic.caller.kind === 'function' ? semantic.caller.functionId : semantic.caller.regionId))
16
19
  return false;
@@ -18,36 +21,47 @@ export const deadLogicalMergeValueMatches = (operation, semantic, body, semantic
18
21
  if (left === undefined)
19
22
  return false;
20
23
  const definitions = new Map();
24
+ const positions = new Map();
25
+ const writes = new Map();
21
26
  let blockOf = null;
22
27
  for (const block of body.blocks.values())
23
- for (const item of allOperationsOf(block)) {
28
+ for (const [index, item] of allOperationsOf(block).entries()) {
24
29
  if ('result' in item && item.result !== null)
25
30
  definitions.set(item.result.id, item);
26
31
  if (item === operation)
27
32
  blockOf = block.id;
33
+ positions.set(item, { block: block.id, index });
34
+ if (item.kind === 'binding-write' || item.kind === 'binding-renew' || item.kind === 'allocate-constructor') {
35
+ const bucket = writes.get(item.declaration);
36
+ if (bucket)
37
+ bucket.push(item);
38
+ else
39
+ writes.set(item.declaration, [item]);
40
+ }
28
41
  }
29
42
  if (blockOf === null)
30
43
  return false;
44
+ // A discarded or reconstructed value cannot borrow the source's
45
+ // truthiness merely because the conversion still cites that SSA.
46
+ const transportsIdentity = (producer) => {
47
+ const node = conversions?.nodeById(producer.conversionUse);
48
+ return !(producer.rebuild !== undefined ||
49
+ node === null ||
50
+ node === undefined ||
51
+ representationKey(node.source) !== representationKey(producer.source.representation) ||
52
+ representationKey(node.target) !== representationKey(producer.result.representation) ||
53
+ !recipeIsMaterializableWithoutPriorSourceGuard(node, conversions.nodeById) ||
54
+ (node.capability.kind !== 'identity' &&
55
+ !('materializer' in node.capability &&
56
+ (node.capability.materializer.nativePayloadTransport === 'preserved' ||
57
+ node.capability.materializer.callableIdentityTransport === 'preserved'))));
58
+ };
31
59
  const chain = (value) => {
32
60
  const values = [];
33
61
  while (!values.includes(value)) {
34
62
  values.push(value);
35
63
  const producer = definitions.get(value);
36
- if (producer?.kind !== 'convert')
37
- break;
38
- // A discarded or reconstructed value cannot borrow the source's
39
- // truthiness merely because the conversion still cites that SSA.
40
- const node = conversions?.nodeById(producer.conversionUse);
41
- if (producer.rebuild !== undefined ||
42
- node === null ||
43
- node === undefined ||
44
- representationKey(node.source) !== representationKey(producer.source.representation) ||
45
- representationKey(node.target) !== representationKey(producer.result.representation) ||
46
- !recipeIsMaterializableWithoutPriorSourceGuard(node, conversions.nodeById) ||
47
- (node.capability.kind !== 'identity' &&
48
- !('materializer' in node.capability &&
49
- (node.capability.materializer.nativePayloadTransport === 'preserved' ||
50
- node.capability.materializer.callableIdentityTransport === 'preserved'))))
64
+ if (producer?.kind !== 'convert' || !transportsIdentity(producer))
51
65
  break;
52
66
  value = producer.source.value;
53
67
  }
@@ -72,13 +86,70 @@ export const deadLogicalMergeValueMatches = (operation, semantic, body, semantic
72
86
  }))
73
87
  return false;
74
88
  const dominance = dominatorTreeOf(body);
89
+ /**
90
+ * Every definition of `value` this body can reach is an Object: a fresh
91
+ * allocation, or a checked assertion out of a box -- the conversion from
92
+ * `dynamic` into a named record or a document refuses with a TypeError
93
+ * whatever is not an object, so it never yields `undefined` (the one falsy
94
+ * state of a shared record reference, its strict unbound-receiver lane) or
95
+ * `null`. A `phi` holds what its incomings hold; a cell read holds what this
96
+ * body wrote to it, when no other frame shares the cell and a write
97
+ * dominates the read (a hoisted `var` reads `undefined` before it). A cycle
98
+ * adds no definition of its own.
99
+ */
100
+ const objectValued = (start, open = new Set()) => {
101
+ if (open.has(start))
102
+ return true;
103
+ open.add(start);
104
+ const producer = definitions.get(start);
105
+ if (producer === undefined)
106
+ return false;
107
+ switch (producer.kind) {
108
+ case 'allocate-ordinary-object':
109
+ case 'allocate-array-object':
110
+ case 'allocate-record':
111
+ return true;
112
+ case 'convert':
113
+ if (producer.rebuild === undefined &&
114
+ producer.source.representation.kind === 'dynamic' &&
115
+ checkedObjectAssertion(producer.result.representation))
116
+ return true;
117
+ return transportsIdentity(producer) && objectValued(producer.source.value, open);
118
+ // An object literal's definitions publish the object they installed into
119
+ // (`producers/allocations.ts`), so the literal's value is its receiver.
120
+ case 'define-own-property':
121
+ return (producer.result !== null &&
122
+ representationKey(producer.result.representation) === representationKey(producer.receiver.representation) &&
123
+ objectValued(producer.receiver.value, open));
124
+ case 'phi':
125
+ return producer.incoming.length > 0 && producer.incoming.every((incoming) => objectValued(incoming.value.value, open));
126
+ case 'binding-read': {
127
+ const facts = body.facts;
128
+ if (facts === undefined || facts.boxed.has(producer.declaration) || facts.capturedDeclarations.includes(producer.declaration))
129
+ return false;
130
+ const stores = writes.get(producer.declaration) ?? [];
131
+ const read = positions.get(producer);
132
+ if (read === undefined || stores.length === 0 || !dominance.reachable.has(read.block))
133
+ return false;
134
+ if (stores.some((store) => store.kind !== 'binding-write' || !objectValued(store.value.value, open)))
135
+ return false;
136
+ return stores.some((store) => {
137
+ const at = positions.get(store);
138
+ return at !== undefined && (at.block === read.block ? at.index < read.index : dominance.dominates(at.block, read.block));
139
+ });
140
+ }
141
+ default:
142
+ return false;
143
+ }
144
+ };
75
145
  for (const block of body.blocks.values()) {
76
146
  const branch = block.terminator;
77
147
  if (branch.kind !== 'branch' || !dominance.dominates(branch.whenFalse, blockOf))
78
148
  continue;
79
149
  const test = definitions.get(branch.condition.value);
80
150
  if (test?.kind === 'test' && test.predicate === 'to-boolean' && chain(test.value.value).some((value) => aliases.includes(value)))
81
- return true;
151
+ return semantic.logicalLeftObjectTruthy === true || objectValued(operation.source.value);
82
152
  }
83
153
  return false;
84
154
  };
155
+ const checkedObjectAssertion = (target) => target.kind === 'native-record-ref' && target.native === null;
@@ -3,6 +3,8 @@ import type { ConversionNode } from '../conversion/algebra.js';
3
3
  import type { ConversionCensus } from '../conversion/nodes.js';
4
4
  import type { BindingPlacement } from '../projection/bindings.js';
5
5
  import { type HoistPlan } from './hoist.js';
6
+ import { type PlainFieldRead } from './borrow-effects.js';
7
+ import type { CodeFreeFieldRead } from './field-read-reuse.js';
6
8
  import { type Representation, type TypedArrayElementDomain } from '../representation/model.js';
7
9
  import type { IrBlockId, IrBody, IrNonTerminatorOperation, IrOperand } from './model.js';
8
10
  /**
@@ -75,6 +77,12 @@ export interface DenseArray {
75
77
  * both assigned and invariant.
76
78
  */
77
79
  readonly relocatedReads: readonly IrValueId[];
80
+ /**
81
+ * The cell whose own `length` is the loop's bound, when the bound is one of
82
+ * `relocatedReads`. A window through that cell is the one array whose read
83
+ * the hoist plan already had to prove the loop cannot change.
84
+ */
85
+ readonly lengthCell?: DeclarationId;
78
86
  /** Whether the test admits the bound itself (`<=`), so the window is one wider. */
79
87
  readonly inclusive: boolean;
80
88
  /** The counter's step, checked non-negative at the preheader. */
@@ -143,6 +151,22 @@ export interface DenseArray {
143
151
  * the row for the current turn is taken, behind the folded flag.
144
152
  */
145
153
  readonly rows?: DenseRowRange;
154
+ /**
155
+ * A typed-array window whose indices the loop's own test does not bound --
156
+ * `position[v * 3 + 1]`, a vertex writer's strided store. The preheader
157
+ * takes the view's pointer and length once, and each access compares its
158
+ * index with that length instead of re-reading the view.
159
+ *
160
+ * Worth a window without the proof because a typed element store is a
161
+ * may-alias store: after each one the backend re-reads the view's buffer,
162
+ * length, detach flag and base, so a quad writer paid five loads per float.
163
+ * Measured on Saltline's HUD quad emit: 94 ns a quad, 66 with the six output
164
+ * views taken once (V8 46). A view cannot be resized, and `nativeOnly`
165
+ * already rules out code that could detach its buffer, so the length taken
166
+ * at the preheader holds for the whole loop. `bases` carries no meaning for
167
+ * one of these.
168
+ */
169
+ readonly checked?: true;
146
170
  }
147
171
  /** The enclosing loop's counter range a folded row window's check walks. */
148
172
  export interface DenseRowRange {
@@ -282,8 +306,18 @@ export interface DenseLoopPlan {
282
306
  readonly regions?: readonly DenseRegion[];
283
307
  }
284
308
  export declare const emptyDenseLoopPlan: DenseLoopPlan;
285
- /** Dense preheaders perform real reads; their transport belongs to the lowered body's certificate too. */
286
- export declare const publishDenseLoopPlan: (body: IrBody, placements: ReadonlyMap<DeclarationId, BindingPlacement>, conversions: ConversionCensus) => IrBody;
309
+ /**
310
+ * Dense preheaders perform real reads; their transport belongs to the lowered body's certificate too.
311
+ *
312
+ * `plainFieldRead` and `codeFreeFieldRead` are the target's own answers
313
+ * (`plainFieldReadOf`, `codeFreeFieldReadOf`): the hoists this plan locates
314
+ * values by may be no more optimistic than the ones the target renders, since
315
+ * a window's setup names its bound where these put it. A window admits a loop
316
+ * only when its reads run no program code, and a field of the receiver's own
317
+ * type still runs a getter when the receiver is a live view of a shape that
318
+ * answers the key with one, so admission asks both too.
319
+ */
320
+ export declare const publishDenseLoopPlan: (body: IrBody, placements: ReadonlyMap<DeclarationId, BindingPlacement>, conversions: ConversionCensus, plainFieldRead: PlainFieldRead, codeFreeFieldRead: CodeFreeFieldRead) => IrBody;
287
321
  export declare const denseLoopConversionsOf: (plan: DenseLoopPlan) => readonly ConversionNode[];
288
322
  export declare const denseLoopPlanMatches: (body: IrBody, plan: DenseLoopPlan, placements: ReadonlyMap<DeclarationId, BindingPlacement>, conversions: ConversionCensus) => boolean;
289
323
  /**
@@ -297,7 +331,7 @@ export declare const denseLoopPlanMatches: (body: IrBody, plan: DenseLoopPlan, p
297
331
  * and boxing decision, not a fact of the program. `admitsCell` is that one
298
332
  * hook (`emit-arrays.ts`'s `denseCellName` is its sole implementation).
299
333
  */
300
- export type DenseCellPolicy = (declaration: DeclarationId) => boolean;
334
+ export type DenseCellPolicy = (declaration: DeclarationId, boundsTheLoop: boolean) => boolean;
301
335
  /** The windows a body ends up able to render, once `admittedDenseLoopPlanOf` has trimmed the raw plan. */
302
336
  export interface AdmittedDenseLoopPlan {
303
337
  readonly arrays: readonly DenseArray[];
@@ -339,4 +373,4 @@ export interface AdmittedDenseLoopPlan {
339
373
  * chain is needed at all.
340
374
  */
341
375
  export declare const admittedDenseLoopPlanOf: (plan: DenseLoopPlan, integerValues: ReadonlySet<IrValueId>, admitsCell: DenseCellPolicy, relocated: ReadonlySet<IrValueId>) => AdmittedDenseLoopPlan;
342
- export declare const denseLoopsOf: (body: IrBody, hoists?: HoistPlan) => DenseLoopPlan;
376
+ export declare const denseLoopsOf: (body: IrBody, hoists?: HoistPlan, plainFieldRead?: PlainFieldRead) => DenseLoopPlan;
@@ -3,13 +3,24 @@ import { recipeClosureOf } from '../conversion/recipe-closure.js';
3
3
  import { controlFlowGraphOf, dominatorTreeOf, naturalLoopsOf } from './dominance.js';
4
4
  import { loopInvariantHoistsOf } from './hoist.js';
5
5
  import { borrowSafeOperationsOf } from './borrow-effects.js';
6
+ import { codeFreeGetOf } from './plain-field-read.js';
6
7
  import { representationKey } from '../representation/model.js';
7
8
  import { operandsOfIrOperation, resultOfIrOperation } from './queries.js';
8
9
  export const emptyDenseLoopPlan = { arrays: [], groups: [], accesses: new Map(), lengths: new Map() };
9
10
  const denseStorageConversionIsOrdinary = (node, conversions) => nativeArrayViewPlansOf(recipeClosureOf([node], conversions.nodeById).values()).length === 0;
10
- /** Dense preheaders perform real reads; their transport belongs to the lowered body's certificate too. */
11
- export const publishDenseLoopPlan = (body, placements, conversions) => {
12
- const raw = denseLoopsOf(body);
11
+ /**
12
+ * Dense preheaders perform real reads; their transport belongs to the lowered body's certificate too.
13
+ *
14
+ * `plainFieldRead` and `codeFreeFieldRead` are the target's own answers
15
+ * (`plainFieldReadOf`, `codeFreeFieldReadOf`): the hoists this plan locates
16
+ * values by may be no more optimistic than the ones the target renders, since
17
+ * a window's setup names its bound where these put it. A window admits a loop
18
+ * only when its reads run no program code, and a field of the receiver's own
19
+ * type still runs a getter when the receiver is a live view of a shape that
20
+ * answers the key with one, so admission asks both too.
21
+ */
22
+ export const publishDenseLoopPlan = (body, placements, conversions, plainFieldRead, codeFreeFieldRead) => {
23
+ const raw = denseLoopsOf(body, loopInvariantHoistsOf(body, undefined, undefined, undefined, undefined, codeFreeGetOf(body, plainFieldRead, codeFreeFieldRead)), (receiver, key) => plainFieldRead(receiver, key) && codeFreeFieldRead(receiver, key));
13
24
  const seal = (reference) => {
14
25
  if (reference.kind === 'element') {
15
26
  const holder = seal(reference.holder);
@@ -84,12 +95,12 @@ export const denseLoopPlanMatches = (body, plan, placements, conversions) => {
84
95
  * access at all (`ir/integers.ts`) -- on top of the same question for the
85
96
  * array it is a row of.
86
97
  */
87
- const referenceIsAdmitted = (reference, integerValues, admitsCell) => {
98
+ const referenceIsAdmitted = (reference, integerValues, admitsCell, lengthCell) => {
88
99
  if (reference.kind === 'cell')
89
- return admitsCell(reference.declaration);
100
+ return admitsCell(reference.declaration, reference.declaration === lengthCell);
90
101
  if (reference.kind === 'value')
91
102
  return true;
92
- return integerValues.has(reference.key.value) && referenceIsAdmitted(reference.holder, integerValues, admitsCell);
103
+ return integerValues.has(reference.key.value) && referenceIsAdmitted(reference.holder, integerValues, admitsCell, undefined);
93
104
  };
94
105
  /**
95
106
  * Narrows `denseLoopsOf`'s raw plan to the windows this body may actually
@@ -126,9 +137,9 @@ export const admittedDenseLoopPlanOf = (plan, integerValues, admitsCell, relocat
126
137
  if (plan.arrays.length === 0)
127
138
  return { arrays: [], groups: new Map(), accesses: new Map(), lengths: new Map(), regions: [] };
128
139
  const admitted = new Set(plan.arrays
129
- .filter((array) => admitsCell(array.counter) &&
130
- (array.rows === undefined || admitsCell(array.rows.counter)) &&
131
- referenceIsAdmitted(array.reference, integerValues, admitsCell) &&
140
+ .filter((array) => admitsCell(array.counter, false) &&
141
+ (array.rows === undefined || admitsCell(array.rows.counter, false)) &&
142
+ referenceIsAdmitted(array.reference, integerValues, admitsCell, array.lengthCell) &&
132
143
  array.relocatedReads.every((value) => relocated.has(value)))
133
144
  .map((array) => array.ordinal));
134
145
  for (const [operation, access] of plan.accesses) {
@@ -165,7 +176,7 @@ export const admittedDenseLoopPlanOf = (plan, integerValues, admitsCell, relocat
165
176
  [...plan.accesses].every(([operation, access]) => accesses.has(operation) || access.flag !== region.group));
166
177
  return { arrays, groups, accesses, lengths, regions };
167
178
  };
168
- export const denseLoopsOf = (body, hoists = loopInvariantHoistsOf(body)) => {
179
+ export const denseLoopsOf = (body, hoists = loopInvariantHoistsOf(body), plainFieldRead = () => false) => {
169
180
  // A try region renders as one assembled chunk, so a preheader inside one has
170
181
  // no single place for the setup to land -- the same restriction `hoist.ts`
171
182
  // takes, and for the same reason.
@@ -264,8 +275,13 @@ export const denseLoopsOf = (body, hoists = loopInvariantHoistsOf(body)) => {
264
275
  // A cell the loop never writes is not enough -- the READ of it can be one of
265
276
  // the loop's own operations, and naming that value in the preheader emits a
266
277
  // use of a variable no statement has assigned yet.
278
+ // A typed window holds a raw pointer, so no operation in its loop may run
279
+ // program code; a data field read (`plainFieldRead`, the target's answer)
280
+ // runs none, and a quad writer reads its corners off `this` every turn.
281
+ const nativeOperations = borrowSafeOperationsOf(body, new Set(), plainFieldRead);
267
282
  const found = loops.map((loop) => loopWindowsOf(loop, body, graph, loops, {
268
283
  body,
284
+ nativeOperations,
269
285
  values: body.values,
270
286
  readsCell,
271
287
  constantTexts,
@@ -312,6 +328,7 @@ export const denseLoopsOf = (body, hoists = loopInvariantHoistsOf(body)) => {
312
328
  continue;
313
329
  const windows = foldedWindowsOf(inner, innerLoop, outer, outerLoop, {
314
330
  body,
331
+ nativeOperations,
315
332
  values: body.values,
316
333
  readsCell,
317
334
  constantTexts,
@@ -358,6 +375,13 @@ export const denseLoopsOf = (body, hoists = loopInvariantHoistsOf(body)) => {
358
375
  const fold = folds.get(index);
359
376
  const host = fold === undefined ? undefined : found[fold.host];
360
377
  for (const [at, candidate] of loop.candidates.entries()) {
378
+ // A checked window pays a compare per access, so it must not take an
379
+ // access a nested loop already bounds with its own counter: loops are
380
+ // decided innermost-first, and `a[i * n + k]` in a `k` loop inside a
381
+ // `j` loop is unbounded for `j` but a plain window for `k`.
382
+ const operations = candidate.checked ? candidate.operations.filter((operation) => !accesses.has(operation)) : candidate.operations;
383
+ if (operations.length === 0)
384
+ continue;
361
385
  const ordinal = arrays.length;
362
386
  const blocks = loops[index]?.blocks;
363
387
  if (blocks)
@@ -380,13 +404,15 @@ export const denseLoopsOf = (body, hoists = loopInvariantHoistsOf(body)) => {
380
404
  counter: loop.counter,
381
405
  bound: folded?.bound ?? loop.bound,
382
406
  relocatedReads: rows && host ? host.relocatedReads : loop.relocatedReads,
407
+ ...(!rows && !folded && loop.lengthCell !== undefined ? { lengthCell: loop.lengthCell } : {}),
383
408
  inclusive: loop.inclusive,
384
409
  step: folded ? folded.step : loop.step,
385
410
  widened: loop.widened,
386
411
  ...(folded ? { seed: folded.seed } : {}),
387
- ...(rows ? { rows } : {})
412
+ ...(rows ? { rows } : {}),
413
+ ...(candidate.checked ? { checked: true } : {})
388
414
  });
389
- for (const operation of candidate.operations) {
415
+ for (const operation of operations) {
390
416
  const flag = flagAt(blockOfOperation.get(operation) ?? loop.preheader);
391
417
  if (flag === null)
392
418
  continue;
@@ -550,6 +576,10 @@ const denseRegionsOf = (body, hoists, loops, groupOfLoop, folded, arrays, access
550
576
  const restricted = arrays.filter((array) => array.group === group && stored.has(array.ordinal) && array.rows === undefined);
551
577
  if (restricted.length === 0)
552
578
  continue;
579
+ // A checked access can take its cold half inside the fast version of the
580
+ // loop, which a restricted pointer's region does not allow for.
581
+ if (arrays.some((array) => array.group === group && array.checked === true))
582
+ continue;
553
583
  const named = new Set(arrays.filter((array) => array.group === group).map((array) => array.ordinal));
554
584
  let sound = true;
555
585
  for (const [operation, access] of accesses) {
@@ -605,6 +635,26 @@ const denseRegionsOf = (body, hoists, loops, groupOfLoop, folded, arrays, access
605
635
  }
606
636
  return regions;
607
637
  };
638
+ /**
639
+ * The reads a bound of `captured.length` needs moved out of the loop: the
640
+ * cell read and the length read on it. `for (let i = 0; i < boxes.length; i++)`
641
+ * over an array a closure captured is the commonest loop a collision world
642
+ * runs, and it re-read the capture and its length on every turn. Like a
643
+ * captured bound, whether the read can move is the target's capture layout
644
+ * and its proof that the loop resizes no array, so the window is taken
645
+ * conditionally and admitted only when the target's hoist plan moved both.
646
+ */
647
+ const capturedLengthOf = (bound, context) => {
648
+ const read = context.operationOf.get(bound.value);
649
+ if (read?.kind !== 'get' || read.receiver.representation.kind !== 'array-object')
650
+ return null;
651
+ if (context.constantTexts.get(read.key.value) !== 'length')
652
+ return null;
653
+ const cell = context.readsCell.get(read.receiver.value);
654
+ if (cell === undefined || (context.cellWrites.get(cell) ?? []).length > 0)
655
+ return null;
656
+ return { reads: [read.receiver.value, bound.value], cell };
657
+ };
608
658
  const loopWindowsOf = (loop, body, graph, loops, context) => {
609
659
  const outside = (graph.predecessors.get(loop.header) ?? []).filter((predecessor) => !loop.blocks.has(predecessor));
610
660
  const preheader = outside.length === 1 ? outside[0] : undefined;
@@ -631,7 +681,8 @@ const loopWindowsOf = (loop, body, graph, loops, context) => {
631
681
  // something the IR states. The window takes it conditionally and the
632
682
  // target admits it only when its own hoist plan moved the read out.
633
683
  const boundCell = invariantBound === null ? context.readsCell.get(right.value) : undefined;
634
- const relocatedReads = boundCell !== undefined && (context.cellWrites.get(boundCell) ?? []).length === 0 ? [right.value] : [];
684
+ const capturedLength = invariantBound === null && boundCell === undefined ? capturedLengthOf(right, context) : null;
685
+ const relocatedReads = boundCell !== undefined && (context.cellWrites.get(boundCell) ?? []).length === 0 ? [right.value] : (capturedLength?.reads ?? []);
635
686
  const bound = invariantBound ?? (relocatedReads.length > 0 ? right : null);
636
687
  if (bound === null)
637
688
  return null;
@@ -663,6 +714,7 @@ const loopWindowsOf = (loop, body, graph, loops, context) => {
663
714
  counter,
664
715
  bound,
665
716
  relocatedReads,
717
+ ...(capturedLength ? { lengthCell: capturedLength.cell } : {}),
666
718
  inclusive: test.operator === '<=',
667
719
  step,
668
720
  widened: advanceReachesAnAccess(loop, body, graph, advance.block, counter),
@@ -702,18 +754,32 @@ const stepOf = (written, counter, operationOf, readsCell) => {
702
754
  const compute = operationOf.get(written.value);
703
755
  if (compute?.kind !== 'compute')
704
756
  return undefined;
757
+ // An `i32`/`int` counter's advance reads the cell through the widening view
758
+ // to a plain Number before `++` -- exact, so still the counter itself.
759
+ const readsCounter = (operand) => {
760
+ if (readsCell.get(operand.value) === counter)
761
+ return true;
762
+ const view = operationOf.get(operand.value);
763
+ return (view?.kind === 'convert' &&
764
+ view.source.representation.kind === 'scalar' &&
765
+ view.source.representation.integerWidth !== undefined &&
766
+ view.result.representation.kind === 'scalar' &&
767
+ view.result.representation.domain === 'number' &&
768
+ view.result.representation.integerWidth === undefined &&
769
+ readsCell.get(view.source.value) === counter);
770
+ };
705
771
  if (compute.form === 'update') {
706
772
  const target = compute.operands[0];
707
- return target && readsCell.get(target.value) === counter && compute.operator === '++' ? null : undefined;
773
+ return target && readsCounter(target) && compute.operator === '++' ? null : undefined;
708
774
  }
709
775
  if (compute.form !== 'binary' || compute.operator !== '+')
710
776
  return undefined;
711
777
  const [left, right] = compute.operands;
712
778
  if (!left || !right)
713
779
  return undefined;
714
- if (readsCell.get(left.value) === counter)
780
+ if (readsCounter(left))
715
781
  return right;
716
- if (readsCell.get(right.value) === counter)
782
+ if (readsCounter(right))
717
783
  return left;
718
784
  return undefined;
719
785
  };
@@ -776,7 +842,7 @@ const heldArrayOf = (receiver, context, blocks) => {
776
842
  */
777
843
  const windowsOfLoop = (blocks, body, context) => {
778
844
  const byReference = new Map();
779
- const nativeOperations = borrowSafeOperationsOf(body);
845
+ const nativeOperations = context.nativeOperations;
780
846
  // No pointer may outlive a callback that can replace/detach its storage.
781
847
  // Numeric typed-array writes alias bytes but cannot invalidate geometry.
782
848
  const nativeOnly = [...blocks].every((id) => body.blocks.get(id)?.operations.every((operation) => nativeOperations.has(operation)));
@@ -831,11 +897,46 @@ const windowsOfLoop = (blocks, body, context) => {
831
897
  continue;
832
898
  const base = wrapped ? null : indexBaseOf(operation.key, context, blocks);
833
899
  const found = byReference.get(key);
900
+ // An unbounded index into a typed view still takes the view once; the
901
+ // access checks itself against the length the preheader read.
902
+ if (base === undefined && typed !== null && !wrapped) {
903
+ if (!found)
904
+ byReference.set(key, {
905
+ ...held,
906
+ element,
907
+ typed,
908
+ wrapped,
909
+ modulus,
910
+ bases: [],
911
+ operations: [operation],
912
+ signed: [],
913
+ checked: true,
914
+ sound: true
915
+ });
916
+ else if (found.wrapped)
917
+ found.sound = false;
918
+ else {
919
+ found.checked = true;
920
+ found.operations.push(operation);
921
+ }
922
+ continue;
923
+ }
834
924
  if (base === undefined) {
835
925
  if (found)
836
926
  found.sound = false;
837
927
  else
838
- byReference.set(key, { ...held, element, typed, wrapped, modulus, bases: [], operations: [], signed: [], sound: false });
928
+ byReference.set(key, {
929
+ ...held,
930
+ element,
931
+ typed,
932
+ wrapped,
933
+ modulus,
934
+ bases: [],
935
+ operations: [],
936
+ signed: [],
937
+ checked: false,
938
+ sound: false
939
+ });
839
940
  continue;
840
941
  }
841
942
  if (!found) {
@@ -848,6 +949,7 @@ const windowsOfLoop = (blocks, body, context) => {
848
949
  bases: [base],
849
950
  operations: [operation],
850
951
  signed: signed ? [operation] : [],
952
+ checked: false,
851
953
  sound: true
852
954
  });
853
955
  continue;