@geastack/compiler 1.0.49 → 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 (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 +112 -17
  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,
@@ -380,11 +397,13 @@ export const denseLoopsOf = (body, hoists = loopInvariantHoistsOf(body)) => {
380
397
  counter: loop.counter,
381
398
  bound: folded?.bound ?? loop.bound,
382
399
  relocatedReads: rows && host ? host.relocatedReads : loop.relocatedReads,
400
+ ...(!rows && !folded && loop.lengthCell !== undefined ? { lengthCell: loop.lengthCell } : {}),
383
401
  inclusive: loop.inclusive,
384
402
  step: folded ? folded.step : loop.step,
385
403
  widened: loop.widened,
386
404
  ...(folded ? { seed: folded.seed } : {}),
387
- ...(rows ? { rows } : {})
405
+ ...(rows ? { rows } : {}),
406
+ ...(candidate.checked ? { checked: true } : {})
388
407
  });
389
408
  for (const operation of candidate.operations) {
390
409
  const flag = flagAt(blockOfOperation.get(operation) ?? loop.preheader);
@@ -550,6 +569,10 @@ const denseRegionsOf = (body, hoists, loops, groupOfLoop, folded, arrays, access
550
569
  const restricted = arrays.filter((array) => array.group === group && stored.has(array.ordinal) && array.rows === undefined);
551
570
  if (restricted.length === 0)
552
571
  continue;
572
+ // A checked access can take its cold half inside the fast version of the
573
+ // loop, which a restricted pointer's region does not allow for.
574
+ if (arrays.some((array) => array.group === group && array.checked === true))
575
+ continue;
553
576
  const named = new Set(arrays.filter((array) => array.group === group).map((array) => array.ordinal));
554
577
  let sound = true;
555
578
  for (const [operation, access] of accesses) {
@@ -605,6 +628,26 @@ const denseRegionsOf = (body, hoists, loops, groupOfLoop, folded, arrays, access
605
628
  }
606
629
  return regions;
607
630
  };
631
+ /**
632
+ * The reads a bound of `captured.length` needs moved out of the loop: the
633
+ * cell read and the length read on it. `for (let i = 0; i < boxes.length; i++)`
634
+ * over an array a closure captured is the commonest loop a collision world
635
+ * runs, and it re-read the capture and its length on every turn. Like a
636
+ * captured bound, whether the read can move is the target's capture layout
637
+ * and its proof that the loop resizes no array, so the window is taken
638
+ * conditionally and admitted only when the target's hoist plan moved both.
639
+ */
640
+ const capturedLengthOf = (bound, context) => {
641
+ const read = context.operationOf.get(bound.value);
642
+ if (read?.kind !== 'get' || read.receiver.representation.kind !== 'array-object')
643
+ return null;
644
+ if (context.constantTexts.get(read.key.value) !== 'length')
645
+ return null;
646
+ const cell = context.readsCell.get(read.receiver.value);
647
+ if (cell === undefined || (context.cellWrites.get(cell) ?? []).length > 0)
648
+ return null;
649
+ return { reads: [read.receiver.value, bound.value], cell };
650
+ };
608
651
  const loopWindowsOf = (loop, body, graph, loops, context) => {
609
652
  const outside = (graph.predecessors.get(loop.header) ?? []).filter((predecessor) => !loop.blocks.has(predecessor));
610
653
  const preheader = outside.length === 1 ? outside[0] : undefined;
@@ -631,7 +674,8 @@ const loopWindowsOf = (loop, body, graph, loops, context) => {
631
674
  // something the IR states. The window takes it conditionally and the
632
675
  // target admits it only when its own hoist plan moved the read out.
633
676
  const boundCell = invariantBound === null ? context.readsCell.get(right.value) : undefined;
634
- const relocatedReads = boundCell !== undefined && (context.cellWrites.get(boundCell) ?? []).length === 0 ? [right.value] : [];
677
+ const capturedLength = invariantBound === null && boundCell === undefined ? capturedLengthOf(right, context) : null;
678
+ const relocatedReads = boundCell !== undefined && (context.cellWrites.get(boundCell) ?? []).length === 0 ? [right.value] : (capturedLength?.reads ?? []);
635
679
  const bound = invariantBound ?? (relocatedReads.length > 0 ? right : null);
636
680
  if (bound === null)
637
681
  return null;
@@ -663,6 +707,7 @@ const loopWindowsOf = (loop, body, graph, loops, context) => {
663
707
  counter,
664
708
  bound,
665
709
  relocatedReads,
710
+ ...(capturedLength ? { lengthCell: capturedLength.cell } : {}),
666
711
  inclusive: test.operator === '<=',
667
712
  step,
668
713
  widened: advanceReachesAnAccess(loop, body, graph, advance.block, counter),
@@ -702,18 +747,32 @@ const stepOf = (written, counter, operationOf, readsCell) => {
702
747
  const compute = operationOf.get(written.value);
703
748
  if (compute?.kind !== 'compute')
704
749
  return undefined;
750
+ // An `i32`/`int` counter's advance reads the cell through the widening view
751
+ // to a plain Number before `++` -- exact, so still the counter itself.
752
+ const readsCounter = (operand) => {
753
+ if (readsCell.get(operand.value) === counter)
754
+ return true;
755
+ const view = operationOf.get(operand.value);
756
+ return (view?.kind === 'convert' &&
757
+ view.source.representation.kind === 'scalar' &&
758
+ view.source.representation.integerWidth !== undefined &&
759
+ view.result.representation.kind === 'scalar' &&
760
+ view.result.representation.domain === 'number' &&
761
+ view.result.representation.integerWidth === undefined &&
762
+ readsCell.get(view.source.value) === counter);
763
+ };
705
764
  if (compute.form === 'update') {
706
765
  const target = compute.operands[0];
707
- return target && readsCell.get(target.value) === counter && compute.operator === '++' ? null : undefined;
766
+ return target && readsCounter(target) && compute.operator === '++' ? null : undefined;
708
767
  }
709
768
  if (compute.form !== 'binary' || compute.operator !== '+')
710
769
  return undefined;
711
770
  const [left, right] = compute.operands;
712
771
  if (!left || !right)
713
772
  return undefined;
714
- if (readsCell.get(left.value) === counter)
773
+ if (readsCounter(left))
715
774
  return right;
716
- if (readsCell.get(right.value) === counter)
775
+ if (readsCounter(right))
717
776
  return left;
718
777
  return undefined;
719
778
  };
@@ -776,7 +835,7 @@ const heldArrayOf = (receiver, context, blocks) => {
776
835
  */
777
836
  const windowsOfLoop = (blocks, body, context) => {
778
837
  const byReference = new Map();
779
- const nativeOperations = borrowSafeOperationsOf(body);
838
+ const nativeOperations = context.nativeOperations;
780
839
  // No pointer may outlive a callback that can replace/detach its storage.
781
840
  // Numeric typed-array writes alias bytes but cannot invalidate geometry.
782
841
  const nativeOnly = [...blocks].every((id) => body.blocks.get(id)?.operations.every((operation) => nativeOperations.has(operation)));
@@ -831,11 +890,46 @@ const windowsOfLoop = (blocks, body, context) => {
831
890
  continue;
832
891
  const base = wrapped ? null : indexBaseOf(operation.key, context, blocks);
833
892
  const found = byReference.get(key);
893
+ // An unbounded index into a typed view still takes the view once; the
894
+ // access checks itself against the length the preheader read.
895
+ if (base === undefined && typed !== null && !wrapped) {
896
+ if (!found)
897
+ byReference.set(key, {
898
+ ...held,
899
+ element,
900
+ typed,
901
+ wrapped,
902
+ modulus,
903
+ bases: [],
904
+ operations: [operation],
905
+ signed: [],
906
+ checked: true,
907
+ sound: true
908
+ });
909
+ else if (found.wrapped)
910
+ found.sound = false;
911
+ else {
912
+ found.checked = true;
913
+ found.operations.push(operation);
914
+ }
915
+ continue;
916
+ }
834
917
  if (base === undefined) {
835
918
  if (found)
836
919
  found.sound = false;
837
920
  else
838
- byReference.set(key, { ...held, element, typed, wrapped, modulus, bases: [], operations: [], signed: [], sound: false });
921
+ byReference.set(key, {
922
+ ...held,
923
+ element,
924
+ typed,
925
+ wrapped,
926
+ modulus,
927
+ bases: [],
928
+ operations: [],
929
+ signed: [],
930
+ checked: false,
931
+ sound: false
932
+ });
839
933
  continue;
840
934
  }
841
935
  if (!found) {
@@ -848,6 +942,7 @@ const windowsOfLoop = (blocks, body, context) => {
848
942
  bases: [base],
849
943
  operations: [operation],
850
944
  signed: signed ? [operation] : [],
945
+ checked: false,
851
946
  sound: true
852
947
  });
853
948
  continue;
@@ -0,0 +1,42 @@
1
+ import type { IrValueId } from '../identity/ids.js';
2
+ import type { IrBody, SetOperation } from './model.js';
3
+ /**
4
+ * One member of a run of constant-index accesses of one array in one block.
5
+ * `initialize` marks the run's first access, which takes the window; `last` is
6
+ * the highest index any member names, so the window is checked once for all;
7
+ * `mutable` says the run stores, so its window also proves the array writable.
8
+ */
9
+ export interface DenseReadWindow {
10
+ readonly ordinal: number;
11
+ readonly initialize: boolean;
12
+ readonly last: number;
13
+ readonly mutable: boolean;
14
+ }
15
+ /** Reads keyed by their result; stores, which have none, by the operation. */
16
+ export interface DenseWindows {
17
+ readonly reads: ReadonlyMap<IrValueId, DenseReadWindow>;
18
+ readonly writes: ReadonlyMap<SetOperation, DenseReadWindow>;
19
+ }
20
+ /**
21
+ * Runs of constant-index accesses of one array with nothing between them that
22
+ * can change the array's storage.
23
+ *
24
+ * A matrix multiply reads sixteen elements of each operand in a row
25
+ * (`const a11 = ae[0], a12 = ae[4], ...`) and stores sixteen into its own,
26
+ * and every access checked the array's live source, descriptors, integrity,
27
+ * bounds, holes and undefined marks again: the check's cold path is a call,
28
+ * after which the backend must reload every field it tested, so it re-tested
29
+ * them all for the next access. Loops already take a dense window once
30
+ * (`dense-loops.ts`); a run in straight-line code takes it at its first access,
31
+ * sized for its highest index, and the rest use the cells.
32
+ *
33
+ * A run is one block's accesses of one receiver -- one SSA value, or one cell
34
+ * that nothing writes in between -- with only operations that run no program
35
+ * code and store nothing between them: constants, cell reads and writes,
36
+ * primitive arithmetic and conversions, tests, and further element reads. A
37
+ * store into a run's array keeps that run open and ends every other: the other
38
+ * array may be the same object, and a store whose window failed takes the
39
+ * plain path, which may grow and so move the cells. Anything else ends every
40
+ * open run, since a call may resize, reshape or replace any array.
41
+ */
42
+ export declare const straightLineArrayWindowsOf: (body: IrBody, excluded: ReadonlySet<IrValueId>, firstOrdinal?: number) => DenseWindows;