@geastack/compiler 1.0.21 → 1.0.23

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 (63) hide show
  1. package/dist/compiler.js +2 -1
  2. package/dist/conversion/build.d.ts +12 -0
  3. package/dist/conversion/build.js +15 -0
  4. package/dist/ir/borrow-effects.js +55 -1
  5. package/dist/ir/callable-class-flow.d.ts +3 -1
  6. package/dist/ir/callable-class-flow.js +27 -1
  7. package/dist/ir/certificate.js +87 -16
  8. package/dist/ir/certify/carrier-keys.js +3 -1
  9. package/dist/ir/dense-loops.d.ts +16 -2
  10. package/dist/ir/dense-loops.js +66 -21
  11. package/dist/ir/facts.d.ts +6 -29
  12. package/dist/ir/facts.js +46 -1
  13. package/dist/ir/floats.d.ts +46 -0
  14. package/dist/ir/floats.js +196 -0
  15. package/dist/ir/hoist.d.ts +11 -2
  16. package/dist/ir/hoist.js +17 -2
  17. package/dist/ir/integer-storage.js +8 -4
  18. package/dist/ir/integers.d.ts +14 -0
  19. package/dist/ir/integers.js +55 -1
  20. package/dist/ir/lower-invocation.js +7 -1
  21. package/dist/ir/numeric-intrinsics.d.ts +1 -1
  22. package/dist/ir/numeric-intrinsics.js +3 -2
  23. package/dist/ir/proven-branches.js +3 -1
  24. package/dist/ir/reflection-demand.js +10 -0
  25. package/dist/project-preparation.js +20 -0
  26. package/dist/semantics/class-alias.d.ts +16 -1
  27. package/dist/semantics/class-alias.js +21 -2
  28. package/dist/semantics/class-heritage.js +2 -2
  29. package/dist/semantics/frontend.js +35 -7
  30. package/dist/semantics/normalize/bivariant-slot-parameter.js +21 -6
  31. package/dist/semantics/normalize/commonjs-require.d.ts +9 -5
  32. package/dist/semantics/normalize/commonjs-require.js +127 -44
  33. package/dist/semantics/normalize/host-mutation-key-reader.js +35 -10
  34. package/dist/semantics/normalize/identities.js +15 -0
  35. package/dist/semantics/normalize/object-bag-bindings.js +16 -2
  36. package/dist/semantics/normalize/omitted-stated-parameter.d.ts +1 -1
  37. package/dist/semantics/normalize/omitted-stated-parameter.js +34 -4
  38. package/dist/semantics/normalize/parameter-bindings.js +33 -7
  39. package/dist/semantics/normalize/structural.js +17 -0
  40. package/dist/semantics/program.js +42 -20
  41. package/dist/semantics/shared-declaration-files.d.ts +44 -0
  42. package/dist/semantics/shared-declaration-files.js +42 -0
  43. package/dist/semantics/subclass-member-overlay-transform.js +95 -53
  44. package/dist/targets/cpp/emit-allocation.js +34 -1
  45. package/dist/targets/cpp/emit-arrays.d.ts +2 -1
  46. package/dist/targets/cpp/emit-arrays.js +7 -3
  47. package/dist/targets/cpp/emit-bindings.js +4 -2
  48. package/dist/targets/cpp/emit-callable.js +13 -0
  49. package/dist/targets/cpp/emit-carrier-members.d.ts +3 -1
  50. package/dist/targets/cpp/emit-carrier-members.js +18 -2
  51. package/dist/targets/cpp/emit-context.d.ts +13 -0
  52. package/dist/targets/cpp/emit-context.js +18 -2
  53. package/dist/targets/cpp/emit-properties.js +16 -3
  54. package/dist/targets/cpp/emit-union-properties.js +16 -3
  55. package/dist/targets/cpp/emit.js +36 -4
  56. package/dist/targets/cpp/host/emit-host-invoke.js +10 -1
  57. package/dist/targets/cpp/host/host-members.js +43 -30
  58. package/dist/targets/cpp/manifest/capabilities.js +10 -1
  59. package/dist/targets/cpp/records.js +8 -1
  60. package/dist/targets/cpp/types.d.ts +2 -0
  61. package/dist/targets/cpp/types.js +2 -0
  62. package/package.json +13 -13
  63. package/src/targets/cpp/runtime/gea_runtime.h +146 -18
package/dist/ir/facts.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { booleanConstantsOf, deadValuesOf, unreadValuesOf } from './dead-values.js';
2
2
  import { deferrableValuesOf } from './deferral.js';
3
3
  import { loopInvariantHoistsOf, loopInvariantValuesOf } from './hoist.js';
4
+ import { narrowableFloatsOf } from './floats.js';
4
5
  import { narrowableIntegersOf, remainderFormGroups } from './integers.js';
5
6
  import { localIteratorValuesOf } from './local-iterators.js';
6
7
  import { allOperationsOf } from './model.js';
@@ -9,6 +10,49 @@ import { operandsOfIrOperation, resultOfIrOperation } from './queries.js';
9
10
  import { sharedStringLayoutsOf, straightLineStringLayoutsOf } from './string-layout-reuse.js';
10
11
  import { stringLengthReuseOf } from './string-length-reuse.js';
11
12
  import { typeQueryResultsOf } from './type-query-results.js';
13
+ /**
14
+ * Every per-body census the printer needs before it renders a line, computed
15
+ * in one place, in the one order they depend on each other in.
16
+ *
17
+ * Distinct from `IrBody.facts` (`ir/captures.ts`), which is the whole-program
18
+ * capture answer sealed onto the body before rendering starts. These are the
19
+ * per-body questions, asked once per body at render entry; the two converge
20
+ * when the remaining Phase 3 rows land.
21
+ *
22
+ * These thirteen analyses used to run inline in `targets/cpp/emit.ts`, each
23
+ * copying its answer into the emit context. Nothing about them is C++: they ask
24
+ * what a body does -- which results nothing reads, which reads may be deferred
25
+ * to their single use, which numbers fit a `long long`, which loop-invariant
26
+ * reads may be hoisted -- and the printer only spells the answers. What made
27
+ * them live in the target was the ORDER, which is real and subtle and was
28
+ * recorded only as comments between the calls: the type-query census removes
29
+ * values from the deferral census, the hoists remove more, and the string
30
+ * length reuse removes more still, so reading the deferral set at the wrong
31
+ * point in the sequence silently answers a question with a set that is about
32
+ * to shrink. Here that order is the body of one function, stated once, and a
33
+ * reader who needs to know why a step sits where it does finds the reason at
34
+ * the step rather than in a comment beside a call site.
35
+ *
36
+ * The target still owns two decisions inside the sequence, because both are
37
+ * about C++ storage rather than about the program, and both are needed
38
+ * mid-order. They arrive as `IrBodyCensusPolicy` hooks, invoked exactly where
39
+ * the inline pipeline invoked them.
40
+ */
41
+ /**
42
+ * Narrowed integers a `float` holds exactly: magnitude at most 2^24, the
43
+ * float32 significand. `rounded[c] = lit + ROUND_MAGIC` adds one to a float32
44
+ * value and stores the sum into a Float32Array, which is single-precision
45
+ * arithmetic only if the integer counts as a float32 operand.
46
+ */
47
+ const float32ExactIntegersOf = (narrowed) => {
48
+ const exact = new Set();
49
+ for (const value of narrowed.values) {
50
+ const magnitude = narrowed.magnitudes.get(value);
51
+ if (magnitude?.kind === 'bounded' && magnitude.limit <= 2 ** 24)
52
+ exact.add(value);
53
+ }
54
+ return exact;
55
+ };
12
56
  export const irBodyCensusOf = (body, policy) => {
13
57
  const localIterators = localIteratorValuesOf(body);
14
58
  const censused = deferrableValuesOf(body, policy.deferrableMemberRead, policy.forwarding);
@@ -54,6 +98,7 @@ export const irBodyCensusOf = (body, policy) => {
54
98
  typeQueryComparisons: typeQueries.comparisons,
55
99
  integerValues: narrowed.values,
56
100
  integerBindings: narrowed.bindings,
101
+ float32: narrowableFloatsOf(body, policy.float32Cell, narrowed.values, float32ExactIntegersOf(narrowed)),
57
102
  remainderForms,
58
103
  roundingArithmetic: narrowed.roundingArithmetic,
59
104
  numericCalls: numericIntrinsics.calls,
@@ -61,7 +106,7 @@ export const irBodyCensusOf = (body, policy) => {
61
106
  };
62
107
  const stableFormals = policy.formalStorage(settled);
63
108
  const loopInvariantValues = loopInvariantValuesOf(body);
64
- const hoists = loopInvariantHoistsOf(body);
109
+ const hoists = loopInvariantHoistsOf(body, policy.integerStorage.cellConstants);
65
110
  const hoistedStringLayouts = sharedStringLayoutsOf(body, hoists, dead);
66
111
  const straightLineStringLayouts = straightLineStringLayoutsOf(body, stableFormals, new Set([...dead, ...hoists.relocated]), Math.max(-1, ...[...hoistedStringLayouts.values()].map((layout) => layout.ordinal)) + 1);
67
112
  const sharedStringLayouts = new Map([...hoistedStringLayouts, ...straightLineStringLayouts]);
@@ -0,0 +1,46 @@
1
+ import type { DeclarationId, IrValueId } from '../identity/ids.js';
2
+ import type { IrBody } from './model.js';
3
+ /**
4
+ * Which `number` values one body may hold in a C++ `float`, and which of its
5
+ * additions, subtractions, multiplications and divisions may be computed in
6
+ * one.
7
+ *
8
+ * A Number is a double, and every value here is still exactly that double: a
9
+ * value joins only when it is a float32 value by construction -- a
10
+ * `Math.fround` result, a `Float32Array` element, a negation of one, or a
11
+ * float32 constant -- so `float` storage holds it without loss and promoting
12
+ * it back to `double` wherever a double is needed is exact.
13
+ *
14
+ * Arithmetic is the one place the representation changes what is computed,
15
+ * and it is admitted on one condition: both operands are float32 values and
16
+ * EVERY use of the result rounds it to float32 straight away (a
17
+ * `Math.fround` argument or a `Float32Array` element store). For `+ - * /`
18
+ * on two float32 operands, rounding the exact double result to float32 gives
19
+ * the same value as the single-precision operation, because a double carries
20
+ * more than twice float32's significand plus two bits (Figueroa, "When is
21
+ * double rounding innocuous?", 1995). So `Math.fround(a * b)` computed as a
22
+ * `float` multiply is the value ECMA-262 asks for, and an unrounded `a * b`
23
+ * stays a double operation.
24
+ *
25
+ * The point is a core with a single-precision FPU and no double one (the
26
+ * ESP32-S31 is `rv32imafc`): there every double operation is a software
27
+ * routine, and a Gray-Scott step written the way such loops are written --
28
+ * every intermediate wrapped in `Math.fround` -- ran forty of them per cell.
29
+ */
30
+ export interface Float32Narrowing {
31
+ /** SSA values whose C++ storage may be `float`. */
32
+ readonly values: ReadonlySet<IrValueId>;
33
+ /** Binding cells whose C++ storage may be `float`. Every read of one is in `values`. */
34
+ readonly bindings: ReadonlySet<DeclarationId>;
35
+ /** Binary compute results evaluated as single-precision arithmetic. */
36
+ readonly arithmetic: ReadonlySet<IrValueId>;
37
+ }
38
+ export declare const emptyFloat32Narrowing: Float32Narrowing;
39
+ /**
40
+ * @param admitsCell whether a cell's storage is this body's to choose -- a
41
+ * cell another frame shares, or one declared outside this body, keeps the
42
+ * double its carrier spells.
43
+ * @param excluded values another census already gave a storage of its own
44
+ * (the integer census's `long long`s).
45
+ */
46
+ export declare const narrowableFloatsOf: (body: IrBody, admitsCell: (declaration: DeclarationId) => boolean, excluded: ReadonlySet<IrValueId>, exactIntegers?: ReadonlySet<IrValueId>) => Float32Narrowing;
@@ -0,0 +1,196 @@
1
+ import { allOperationsOf } from './model.js';
2
+ import { operandsOfIrOperation } from './queries.js';
3
+ export const emptyFloat32Narrowing = { values: new Set(), bindings: new Set(), arithmetic: new Set() };
4
+ const roundedOperators = new Set(['+', '-', '*', '/']);
5
+ const isNumberScalar = (operand) => operand.representation.kind === 'scalar' && operand.representation.domain === 'number';
6
+ /** A number literal that is its own float32 rounding: storing it in a `float` loses nothing. */
7
+ const isFloat32Literal = (text) => {
8
+ const value = Number(text);
9
+ return Number.isFinite(value) && Math.fround(value) === value;
10
+ };
11
+ /**
12
+ * @param admitsCell whether a cell's storage is this body's to choose -- a
13
+ * cell another frame shares, or one declared outside this body, keeps the
14
+ * double its carrier spells.
15
+ * @param excluded values another census already gave a storage of its own
16
+ * (the integer census's `long long`s).
17
+ */
18
+ export const narrowableFloatsOf = (body, admitsCell, excluded, exactIntegers = new Set()) => {
19
+ const stringKeys = new Map();
20
+ const float32Constants = new Set();
21
+ for (const block of body.blocks.values()) {
22
+ for (const operation of block.operations) {
23
+ if (operation.kind !== 'constant')
24
+ continue;
25
+ if (operation.literal === 'string')
26
+ stringKeys.set(operation.result.id, operation.text);
27
+ else if (operation.literal === 'number' && isFloat32Literal(operation.text))
28
+ float32Constants.add(operation.result.id);
29
+ }
30
+ }
31
+ // `Math.fround` authenticated by its native protocol, as `numericIntrinsicsOf`
32
+ // authenticates `Math.imul`: a user object named Math has no such protocol.
33
+ const froundCallees = new Set();
34
+ for (const block of body.blocks.values()) {
35
+ for (const operation of block.operations) {
36
+ if (operation.kind !== 'get')
37
+ continue;
38
+ const receiver = operation.receiver.representation;
39
+ if (receiver.kind === 'native-handle' &&
40
+ receiver.native === null &&
41
+ receiver.protocol === 'Math' &&
42
+ stringKeys.get(operation.key.value) === 'fround')
43
+ froundCallees.add(operation.result.id);
44
+ }
45
+ }
46
+ const isFroundCall = (operation) => froundCallees.has(operation.callee.value) &&
47
+ operation.arguments.length === 1 &&
48
+ operation.arguments.every(isNumberScalar) &&
49
+ operation.result !== null &&
50
+ isNumberScalar(operation.result);
51
+ const definitions = new Map();
52
+ const cellWrites = new Map();
53
+ /** Values every use of which rounds to float32; struck by any other use. */
54
+ const roundedUses = new Map();
55
+ const use = (value, rounds) => {
56
+ roundedUses.set(value, (roundedUses.get(value) ?? true) && rounds);
57
+ };
58
+ for (const block of body.blocks.values()) {
59
+ for (const operation of allOperationsOf(block)) {
60
+ if (operation.kind === 'call' && isFroundCall(operation)) {
61
+ definitions.set(operation.result.id, { kind: 'source' });
62
+ use(operation.arguments[0].value, true);
63
+ use(operation.callee.value, false);
64
+ continue;
65
+ }
66
+ if (operation.kind === 'set' && operation.receiver.representation.kind === 'typed-array') {
67
+ const keyText = stringKeys.get(operation.key.value);
68
+ const elementStore = operation.receiver.representation.element === 'float32' && keyText === undefined && isNumberScalar(operation.value);
69
+ use(operation.value.value, elementStore);
70
+ use(operation.receiver.value, false);
71
+ use(operation.key.value, false);
72
+ continue;
73
+ }
74
+ if (operation.kind === 'get' && operation.receiver.representation.kind === 'typed-array') {
75
+ const keyText = stringKeys.get(operation.key.value);
76
+ if (operation.receiver.representation.element === 'float32' && keyText === undefined && isNumberScalar(operation.result))
77
+ definitions.set(operation.result.id, { kind: 'source' });
78
+ }
79
+ else if (operation.kind === 'compute' && isNumberScalar(operation.result)) {
80
+ const operands = operation.operands;
81
+ if (operation.form === 'unary' && operation.operator === '-' && operands.length === 1 && isNumberScalar(operands[0]))
82
+ definitions.set(operation.result.id, { kind: 'negate', operand: operands[0].value });
83
+ else if (operation.form === 'binary' &&
84
+ roundedOperators.has(operation.operator) &&
85
+ operands.length === 2 &&
86
+ operands.every(isNumberScalar))
87
+ definitions.set(operation.result.id, { kind: 'arithmetic', operands: operands.map((operand) => operand.value) });
88
+ }
89
+ else if (operation.kind === 'phi' && isNumberScalar(operation.result)) {
90
+ definitions.set(operation.result.id, { kind: 'phi', incoming: operation.incoming.map((incoming) => incoming.value.value) });
91
+ }
92
+ else if (operation.kind === 'binding-read' && isNumberScalar(operation.result)) {
93
+ definitions.set(operation.result.id, { kind: 'cell', declaration: operation.declaration });
94
+ }
95
+ else if (operation.kind === 'binding-write') {
96
+ const writes = cellWrites.get(operation.declaration) ?? [];
97
+ writes.push(operation.value.value);
98
+ cellWrites.set(operation.declaration, writes);
99
+ // A cell write is not a rounding: the cell is read back as a Number.
100
+ use(operation.value.value, false);
101
+ continue;
102
+ }
103
+ for (const operand of operandsOfIrOperation(operation))
104
+ use(operand.value, false);
105
+ }
106
+ }
107
+ // Optimistic: every candidate is a float32 value until a premise fails, so a
108
+ // loop-carried phi or a cell written from itself can settle at all.
109
+ const values = new Set([...definitions.keys()].filter((value) => !excluded.has(value)));
110
+ const arithmetic = new Set();
111
+ const cells = new Set();
112
+ for (const [declaration, writes] of cellWrites)
113
+ if (admitsCell(declaration) && writes.length > 0)
114
+ cells.add(declaration);
115
+ const exact = (value) => values.has(value) || float32Constants.has(value) || exactIntegers.has(value);
116
+ const strike = () => {
117
+ let struck = false;
118
+ let changed = true;
119
+ while (changed) {
120
+ changed = false;
121
+ for (const declaration of [...cells]) {
122
+ if ((cellWrites.get(declaration) ?? []).every(exact))
123
+ continue;
124
+ cells.delete(declaration);
125
+ changed = struck = true;
126
+ }
127
+ for (const value of [...values]) {
128
+ const definition = definitions.get(value);
129
+ const holds = definition.kind === 'source'
130
+ ? true
131
+ : definition.kind === 'negate'
132
+ ? exact(definition.operand)
133
+ : definition.kind === 'arithmetic'
134
+ ? definition.operands.every(exact) && roundedUses.get(value) === true
135
+ : definition.kind === 'phi'
136
+ ? definition.incoming.every(exact)
137
+ : cells.has(definition.declaration);
138
+ if (holds)
139
+ continue;
140
+ values.delete(value);
141
+ changed = struck = true;
142
+ }
143
+ }
144
+ return struck;
145
+ };
146
+ // Exact is not enough: a `let x = 0` written only with float32 constants is
147
+ // exact too, and moving every such counter into a `float` would change the
148
+ // storage of programs that never touch single precision. A value keeps
149
+ // `float` storage only when a float32 source reaches it -- the least
150
+ // fixpoint from `fround` results and `Float32Array` reads.
151
+ const ground = () => {
152
+ const grounded = new Set();
153
+ const groundedCells = new Set();
154
+ let changed = true;
155
+ while (changed) {
156
+ changed = false;
157
+ for (const value of values) {
158
+ if (grounded.has(value))
159
+ continue;
160
+ const definition = definitions.get(value);
161
+ const reached = definition.kind === 'source' || definition.kind === 'arithmetic'
162
+ ? true
163
+ : definition.kind === 'negate'
164
+ ? grounded.has(definition.operand)
165
+ : definition.kind === 'phi'
166
+ ? definition.incoming.some((incoming) => grounded.has(incoming))
167
+ : groundedCells.has(definition.declaration);
168
+ if (!reached)
169
+ continue;
170
+ grounded.add(value);
171
+ changed = true;
172
+ }
173
+ for (const declaration of cells) {
174
+ if (groundedCells.has(declaration) || !(cellWrites.get(declaration) ?? []).some((write) => grounded.has(write)))
175
+ continue;
176
+ groundedCells.add(declaration);
177
+ changed = true;
178
+ }
179
+ }
180
+ let removed = false;
181
+ for (const value of [...values])
182
+ if (!grounded.has(value))
183
+ (values.delete(value), (removed = true));
184
+ for (const declaration of [...cells])
185
+ if (!groundedCells.has(declaration))
186
+ (cells.delete(declaration), (removed = true));
187
+ return removed;
188
+ };
189
+ strike();
190
+ while (ground() && strike())
191
+ ;
192
+ for (const value of values)
193
+ if (definitions.get(value)?.kind === 'arithmetic')
194
+ arithmetic.add(value);
195
+ return { values, bindings: cells, arithmetic };
196
+ };
@@ -1,4 +1,4 @@
1
- import type { IrValueId } from '../identity/ids.js';
1
+ import type { DeclarationId, IrValueId } from '../identity/ids.js';
2
2
  import type { IrBlockId, IrBody, IrNonTerminatorOperation } from './model.js';
3
3
  /**
4
4
  * Loop-invariant operations, and the block each one moves to.
@@ -35,7 +35,16 @@ export interface HoistPlan {
35
35
  readonly relocated: ReadonlySet<IrValueId>;
36
36
  }
37
37
  export declare const emptyHoistPlan: HoistPlan;
38
- export declare const loopInvariantHoistsOf: (body: IrBody) => HoistPlan;
38
+ /**
39
+ * @param programConstants cells written exactly once program-wide, with that
40
+ * integer literal (`ir/integers.ts`'s `programCellConstantsOf`). A module
41
+ * `const` is written by the module body, so every OTHER body that reads it
42
+ * sees no write of its own -- and without this, the read could never leave
43
+ * a loop: `for (c = 1; c < LAST - 1; c++)` recomputed its bound every turn,
44
+ * in software doubles on a core with no double FPU, and `dense-loops.ts`
45
+ * refused the window because its bound was defined inside the loop.
46
+ */
47
+ export declare const loopInvariantHoistsOf: (body: IrBody, programConstants?: ReadonlyMap<DeclarationId, number>) => HoistPlan;
39
48
  /**
40
49
  * The values a loop cannot change: what clang's licm would lift, stated here.
41
50
  *
package/dist/ir/hoist.js CHANGED
@@ -46,7 +46,16 @@ const storageNeutralKinds = new Set([
46
46
  'receiver',
47
47
  'get'
48
48
  ]);
49
- export const loopInvariantHoistsOf = (body) => {
49
+ /**
50
+ * @param programConstants cells written exactly once program-wide, with that
51
+ * integer literal (`ir/integers.ts`'s `programCellConstantsOf`). A module
52
+ * `const` is written by the module body, so every OTHER body that reads it
53
+ * sees no write of its own -- and without this, the read could never leave
54
+ * a loop: `for (c = 1; c < LAST - 1; c++)` recomputed its bound every turn,
55
+ * in software doubles on a core with no double FPU, and `dense-loops.ts`
56
+ * refused the window because its bound was defined inside the loop.
57
+ */
58
+ export const loopInvariantHoistsOf = (body, programConstants = new Map()) => {
50
59
  // A try region renders as one `try { } catch { }` chunk assembled from
51
60
  // several blocks at once, so a relocation into or out of one has no single
52
61
  // place to land. Bodies with a region are left alone entirely.
@@ -106,9 +115,13 @@ export const loopInvariantHoistsOf = (body) => {
106
115
  if (cell === undefined)
107
116
  return null;
108
117
  const written = cellWrites.get(cell) ?? [];
118
+ if (written.length === 0)
119
+ return programConstants.get(cell) ?? null;
109
120
  const only = written.length === 1 ? written[0] : undefined;
110
121
  return only ? (constants.get(only.value.value) ?? null) : null;
111
122
  };
123
+ /** A cell this body never writes and the whole program writes once: it holds the same value at every read here. */
124
+ const isProgramConstant = (cell) => programConstants.has(cell) && !cellWrites.has(cell);
112
125
  /**
113
126
  * Whether this loop's first test is known to pass.
114
127
  *
@@ -229,6 +242,8 @@ export const loopInvariantHoistsOf = (body) => {
229
242
  return true;
230
243
  }
231
244
  if (operation.kind === 'binding-read') {
245
+ if (isProgramConstant(operation.declaration))
246
+ return true;
232
247
  if (mayCaptureLocals)
233
248
  return false;
234
249
  // Invariant only while the loop writes the cell nowhere.
@@ -291,7 +306,7 @@ export const loopInvariantHoistsOf = (body) => {
291
306
  // A cell read moved ahead of the loop has to name a cell something
292
307
  // already assigned; a write that only happens AFTER the loop leaves
293
308
  // the variable uninitialized at the new position.
294
- if (operation.kind === 'binding-read') {
309
+ if (operation.kind === 'binding-read' && !isProgramConstant(operation.declaration)) {
295
310
  const written = cellWrites.get(operation.declaration) ?? [];
296
311
  if (!written.some((write) => dominance.dominates(write.block, preheader)))
297
312
  continue;
@@ -1,5 +1,5 @@
1
1
  import { walkRepresentation } from '../representation/model.js';
2
- import { integerLinearMagnitude, narrowableIntegersOf, widenIntegerMagnitude } from './integers.js';
2
+ import { integerLinearMagnitude, narrowableIntegersOf, programCellConstantsOf, widenIntegerMagnitude } from './integers.js';
3
3
  import { callableMemberSlot } from './callable-member-candidates.js';
4
4
  import { operandsOfIrOperation, resultOfIrOperation } from './queries.js';
5
5
  /**
@@ -702,6 +702,10 @@ export const integerStorageCensusOf = (question) => {
702
702
  const scans = new Map();
703
703
  for (const body of question.bodies)
704
704
  scans.set(String(body.sourceOwner), scanBody(body, question, disqualified));
705
+ // Program-wide single-literal cells ride on every facts object handed out,
706
+ // so a body that only READS a module constant still sees its value.
707
+ const cellConstants = programCellConstantsOf(question.bodies);
708
+ const withCells = (facts) => (cellConstants.size > 0 ? { ...facts, cellConstants } : facts);
705
709
  // A box whose payload this census cannot name may hold ANY struct -- a
706
710
  // member read off a boxed record is a box of a struct no conversion named --
707
711
  // so it strikes every field slot, and every method's signature, since a
@@ -803,10 +807,10 @@ export const integerStorageCensusOf = (question) => {
803
807
  // slot at all still asks for, since the premise is the version's own.
804
808
  const censusFrom = (slots, settledSlots, magnitudes, facts) => ({
805
809
  slots,
806
- factsOf: (owner) => facts.get(String(owner)) ?? emptyFacts,
810
+ factsOf: (owner) => withCells(facts.get(String(owner)) ?? emptyFacts),
807
811
  entryCheckedFactsOf: (owner, ordinals) => {
808
812
  const scan = scans.get(String(owner));
809
- const base = facts.get(String(owner)) ?? emptyFacts;
813
+ const base = withCells(facts.get(String(owner)) ?? emptyFacts);
810
814
  if (scan === undefined || ordinals.size === 0)
811
815
  return base;
812
816
  const checked = new Set([...ordinals].map((ordinal) => integerParameterSlot(owner, ordinal)));
@@ -835,7 +839,7 @@ export const integerStorageCensusOf = (question) => {
835
839
  const scan = scans.get(owner);
836
840
  if (scan === undefined || (scan.reads.size === 0 && scan.writes.size === 0 && scan.returns === null))
837
841
  continue;
838
- answers.set(owner, narrowableIntegersOf(body, { reads: scan.reads, integral, magnitudes }));
842
+ answers.set(owner, narrowableIntegersOf(body, withCells({ reads: scan.reads, integral, magnitudes })));
839
843
  }
840
844
  return answers;
841
845
  };
@@ -125,7 +125,21 @@ export interface IntegerStorageFacts {
125
125
  * answers otherwise stops the program instead of being truncated.
126
126
  */
127
127
  readonly guarded?: ReadonlyMap<IrValueId, number>;
128
+ /**
129
+ * Cells the WHOLE program writes exactly once, with an integer literal --
130
+ * `programCellConstantsOf`. A module `const PITCH = 122` is written by the
131
+ * module body and read by every method that indexes with it; the one-write
132
+ * rule below sees only its own body's writes, so without this a method
133
+ * reading the cell had none and every index derived from it was a double.
134
+ */
135
+ readonly cellConstants?: ReadonlyMap<DeclarationId, number>;
128
136
  }
137
+ /**
138
+ * Which cells hold one integer literal at every read, program-wide: exactly
139
+ * one `binding-write` across all `bodies`, and its value a number constant
140
+ * that is a safe integer.
141
+ */
142
+ export declare const programCellConstantsOf: (bodies: readonly IrBody[]) => ReadonlyMap<DeclarationId, number>;
129
143
  export type IntegerMagnitude = {
130
144
  readonly kind: 'bounded';
131
145
  readonly limit: number;
@@ -9,6 +9,42 @@ export const emptyIntegerNarrowing = {
9
9
  dynamicRemainders: new Set(),
10
10
  roundingArithmetic: new Set()
11
11
  };
12
+ /**
13
+ * Which cells hold one integer literal at every read, program-wide: exactly
14
+ * one `binding-write` across all `bodies`, and its value a number constant
15
+ * that is a safe integer.
16
+ */
17
+ export const programCellConstantsOf = (bodies) => {
18
+ const writes = new Map();
19
+ const literal = new Map();
20
+ for (const body of bodies) {
21
+ const constantValues = new Map();
22
+ for (const blockId of body.blockOrder) {
23
+ for (const operation of body.blocks.get(blockId)?.operations ?? []) {
24
+ if (operation.kind === 'constant' && operation.literal === 'number') {
25
+ const value = integerText(operation.text);
26
+ if (value !== null)
27
+ constantValues.set(operation.result.id, value);
28
+ }
29
+ }
30
+ }
31
+ for (const blockId of body.blockOrder) {
32
+ for (const operation of body.blocks.get(blockId)?.operations ?? []) {
33
+ if (operation.kind !== 'binding-write')
34
+ continue;
35
+ writes.set(operation.declaration, (writes.get(operation.declaration) ?? 0) + 1);
36
+ literal.set(operation.declaration, constantValues.get(operation.value.value) ?? null);
37
+ }
38
+ }
39
+ }
40
+ const constants = new Map();
41
+ for (const [cell, count] of writes) {
42
+ const value = literal.get(cell);
43
+ if (count === 1 && value !== undefined && value !== null)
44
+ constants.set(cell, value);
45
+ }
46
+ return constants;
47
+ };
12
48
  const noStorageFacts = { reads: new Map(), integral: new Set(), magnitudes: new Map() };
13
49
  /** 2^53: the last integer a double can hold with every integer below it. */
14
50
  const exactIntegerLimit = 9007199254740992;
@@ -159,9 +195,17 @@ export const narrowableIntegersOf = (body, storage = noStorageFacts) => {
159
195
  // Math.imul always returns a signed int32, including for fractional, NaN,
160
196
  // infinite and overflowing inputs. Its callable ABI alone says only number.
161
197
  const imulResults = new Set();
198
+ // `Math.min`/`Math.max` of two integers is one of them: an integer exactly
199
+ // when both arguments are, no larger than the larger of the two. Without
200
+ // this a clamped row index (`Math.max(cell - 1, 0)`) was a double, and so
201
+ // was every index derived from it -- soft-float on every pixel of Bloom's
202
+ // upscaler.
203
+ const minMaxResults = new Map();
162
204
  for (const [call, intrinsic] of numericIntrinsicsOf(body).calls) {
163
205
  if (intrinsic === 'imul' && call.result)
164
206
  imulResults.add(call.result.id);
207
+ else if (call.result)
208
+ minMaxResults.set(call.result.id, call.arguments);
165
209
  }
166
210
  const definitions = new Map();
167
211
  const computes = new Map();
@@ -246,7 +290,7 @@ export const narrowableIntegersOf = (body, storage = noStorageFacts) => {
246
290
  continue;
247
291
  const written = cellWrites.get(cell) ?? [];
248
292
  const only = written.length === 1 ? written[0] : undefined;
249
- const literal = only === undefined ? undefined : constants.get(only.value.value);
293
+ const literal = only === undefined ? (written.length === 0 ? storage.cellConstants?.get(cell) : undefined) : constants.get(only.value.value);
250
294
  if (literal !== undefined)
251
295
  constants.set(value, literal);
252
296
  }
@@ -290,6 +334,9 @@ export const narrowableIntegersOf = (body, storage = noStorageFacts) => {
290
334
  const producesInteger = (value) => {
291
335
  if (imulResults.has(value))
292
336
  return true;
337
+ const chosen = minMaxResults.get(value);
338
+ if (chosen !== undefined)
339
+ return chosen.every((argument) => integral.has(argument.value));
293
340
  if (constants.has(value))
294
341
  return true;
295
342
  if (lengthReads.has(value))
@@ -505,6 +552,13 @@ export const narrowableIntegersOf = (body, storage = noStorageFacts) => {
505
552
  const computeMagnitude = (operand) => {
506
553
  if (imulResults.has(operand.value))
507
554
  return boundedBy(2 ** 31);
555
+ const chosen = minMaxResults.get(operand.value);
556
+ if (chosen !== undefined) {
557
+ let answer = { kind: 'bounded', limit: 0 };
558
+ for (const argument of chosen)
559
+ answer = widen(answer, magnitudeOfValue(argument));
560
+ return answer;
561
+ }
508
562
  const constant = constants.get(operand.value);
509
563
  if (constant !== undefined)
510
564
  return boundedBy(Math.abs(constant));
@@ -470,7 +470,13 @@ export const lowerInvocation = (ctx, block, operation) => {
470
470
  // A host may additionally publish a borrowed numeric rest spelling, proved
471
471
  // separately below. Merely seeing number[] does not authorize skipping the
472
472
  // array: ordinary rest functions and first-class builtin values observe it.
473
- const calleeAbi = abiOfCallee(callee.representation);
473
+ // A callee that may be absent is invoked through its payload: emission
474
+ // presence-checks it and calls what it holds (`unwrapPresentValue`), so the
475
+ // payload's convention is the frame these arguments fill. Packing against
476
+ // the optional itself states no convention and hands a rest function its
477
+ // loose arguments -- three's `...arguments` shims read off a dynamic key.
478
+ const invoked = callee.representation.kind === 'optional' ? callee.representation.payload : callee.representation;
479
+ const calleeAbi = abiOfCallee(invoked);
474
480
  const restElement = calleeAbi?.restFrom === null || calleeAbi === null ? null : (calleeAbi.parameters[calleeAbi.restFrom]?.value ?? null);
475
481
  const textJoined = restElement?.kind === 'array-object' && restElement.element.kind === 'dynamic';
476
482
  // Only numeric operands use the borrowed host frame. Unknown values still
@@ -1,6 +1,6 @@
1
1
  import type { IrValueId } from '../identity/ids.js';
2
2
  import type { CallOperation, IrBody } from './model.js';
3
- export type NumericIntrinsic = 'imul';
3
+ export type NumericIntrinsic = 'imul' | 'min' | 'max';
4
4
  /**
5
5
  * Language builtin calls authenticated by their native protocol, never by a
6
6
  * source identifier spelling. A user object named Math has no such protocol.
@@ -1,5 +1,6 @@
1
1
  import { allOperationsOf } from './model.js';
2
2
  import { operandsOfIrOperation } from './queries.js';
3
+ const twoArgumentIntrinsics = new Set(['imul', 'min', 'max']);
3
4
  /**
4
5
  * Language builtin calls authenticated by their native protocol, never by a
5
6
  * source identifier spelling. A user object named Math has no such protocol.
@@ -25,8 +26,8 @@ export const numericIntrinsicsOf = (body) => {
25
26
  if (receiver.kind === 'native-handle' &&
26
27
  receiver.native === null &&
27
28
  receiver.protocol === 'Math' &&
28
- keys.get(operation.key.value) === 'imul') {
29
- callees.set(operation.result.id, 'imul');
29
+ twoArgumentIntrinsics.has(keys.get(operation.key.value) ?? '')) {
30
+ callees.set(operation.result.id, keys.get(operation.key.value));
30
31
  }
31
32
  }
32
33
  }
@@ -271,7 +271,9 @@ export const pruneProvenBranches = (bodies, graph, slotDrift = []) => {
271
271
  // condition itself, a `compute` carrying the equality's own lineage.
272
272
  if (operation.kind === 'compute' && operation.form === 'equality') {
273
273
  const truth = semantic.get(operation.lineage);
274
- if (truth !== undefined && operation.operands.length === 2 && operation.operands.every((operand) => operand.representation.kind === 'string'))
274
+ if (truth !== undefined &&
275
+ operation.operands.length === 2 &&
276
+ operation.operands.every((operand) => operand.representation.kind === 'string'))
275
277
  facts.set(operation.result.id, truth);
276
278
  continue;
277
279
  }
@@ -184,9 +184,18 @@ const directChildrenOf = (representation, classes, deriver) => {
184
184
  return [...representation.fields.map((field) => field.value), ...representation.indexes.map((index) => index.value)];
185
185
  case 'class-ref': {
186
186
  const layout = classes.get(representation.declaration);
187
+ // A boxed instance answers a dynamic read of a prototype method with the
188
+ // method itself (the class's `gea_getPrototypeProperty` boxes it), so a
189
+ // dynamic caller can invoke it and receive its result. The method's
190
+ // convention is therefore one of the instance's published values; its
191
+ // result is what `publishedChildrenOf` keeps of it. Without this a record
192
+ // returned by such a method had no own-field protocol, the box adapter
193
+ // could not carry it, and the boxed method was not callable at all.
194
+ const methods = layout?.methods.flatMap((method) => (method.representation ? [method.representation] : [])) ?? [];
187
195
  if (layout?.nativeStorage !== undefined) {
188
196
  const raw = deriver?.layoutOf(representation.shapeId);
189
197
  return [
198
+ ...methods,
190
199
  ...layout.nativeStorage.fields.map((field) => field.value),
191
200
  ...layout.staticFields.flatMap((field) => (field.representation ? [field.representation] : [])),
192
201
  ...(raw?.kind === 'record' ? raw.accessors.map((accessor) => accessor.value) : []),
@@ -194,6 +203,7 @@ const directChildrenOf = (representation, classes, deriver) => {
194
203
  ];
195
204
  }
196
205
  return [
206
+ ...methods,
197
207
  ...(layout?.fields.flatMap((field) => (field.representation ? [field.representation] : [])) ?? []),
198
208
  ...(layout?.staticFields.flatMap((field) => (field.representation ? [field.representation] : [])) ?? []),
199
209
  ...(deriver ? [deriver.layoutOf(representation.shapeId)] : [])