@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/compiler.js CHANGED
@@ -2,7 +2,7 @@ import { readFileSync } from 'fs';
2
2
  import { projectAbis } from './projection/abi.js';
3
3
  import { projectBindingPlacements } from './projection/bindings.js';
4
4
  import { physicalClassInstanceResolverOf, physicalClassLayoutsOf, projectClasses } from './projection/classes.js';
5
- import { buildConversionGraph } from './conversion/build.js';
5
+ import { buildConversionGraph, resetNarrowingMemos } from './conversion/build.js';
6
6
  import { createConversionNodes } from './conversion/nodes.js';
7
7
  import { sweepDiagnostics } from './diagnostics/sweep.js';
8
8
  import { refusalsOf } from './ir/refusal.js';
@@ -174,6 +174,7 @@ export const sourceTransformsFor = (plugins) => [
174
174
  ...plugins.flatMap((plugin) => (plugin.transformSource ? [plugin.transformSource] : []))
175
175
  ];
176
176
  export const compile = (request) => {
177
+ resetNarrowingMemos();
177
178
  // One instance per compilation. A plugin that learns something from a program
178
179
  // and acts on it later has to remember it in between, and a registry of
179
180
  // long-lived instances would let a fact derived from one program be read back
@@ -26,6 +26,18 @@ export interface ConversionGraph {
26
26
  * hidden behind a capability nobody implemented.
27
27
  */
28
28
  export declare const emptyConversionRegistry: ConversionRuntimeRegistry;
29
+ /**
30
+ * Forgets both narrowing memos. "A pure function of the representation" holds
31
+ * only within one program: `representationKey` names a class by its
32
+ * declaration id (`class-ref(decl|f168|20,...)`), and every single-file program
33
+ * numbers its file the same, so the next compile in this process reads another
34
+ * program's class -- with other `ancestors`, which `reaches` tests but the key
35
+ * omits -- under the same key. The emitted-set gate, which compiles hundreds
36
+ * of programs in one process, emitted `native-reflection-virtual-class`'s
37
+ * `instanceof` narrowing differently after `native-default-merge-field-flow`.
38
+ * `compile` calls this first; within one compile the memos stay as measured.
39
+ */
40
+ export declare const resetNarrowingMemos: () => void;
29
41
  export declare const narrowingReachesTarget: (source: Representation, target: Representation) => boolean;
30
42
  /**
31
43
  * A base-class handle read at a UNION of its descendants -- `instanceof Mesh ||
@@ -243,6 +243,21 @@ const buildNarrowingClosure = (source) => {
243
243
  * graph proposal and backend admission so they cannot disagree.
244
244
  */
245
245
  const reachesMemo = new Map();
246
+ /**
247
+ * Forgets both narrowing memos. "A pure function of the representation" holds
248
+ * only within one program: `representationKey` names a class by its
249
+ * declaration id (`class-ref(decl|f168|20,...)`), and every single-file program
250
+ * numbers its file the same, so the next compile in this process reads another
251
+ * program's class -- with other `ancestors`, which `reaches` tests but the key
252
+ * omits -- under the same key. The emitted-set gate, which compiles hundreds
253
+ * of programs in one process, emitted `native-reflection-virtual-class`'s
254
+ * `instanceof` narrowing differently after `native-default-merge-field-flow`.
255
+ * `compile` calls this first; within one compile the memos stay as measured.
256
+ */
257
+ export const resetNarrowingMemos = () => {
258
+ narrowingClosures.clear();
259
+ reachesMemo.clear();
260
+ };
246
261
  export const narrowingReachesTarget = (source, target) => {
247
262
  const targetKey = representationKey(target);
248
263
  if (narrowingClosureKeysOf(source).has(targetKey))
@@ -8,14 +8,66 @@ const primitive = (value) => {
8
8
  return ['scalar', 'string', 'null', 'undefined', 'symbol'].includes(value.kind);
9
9
  };
10
10
  const number = (value) => value.kind === 'scalar' && value.domain === 'number';
11
+ /**
12
+ * `Math` functions that, given only Numbers, compute a Number and run
13
+ * nothing: no `valueOf` to coerce, no callback, no state. A stencil wraps
14
+ * every intermediate in `Math.fround` and clamps with `Math.min`/`Math.max`,
15
+ * so without these no such loop could keep a raw typed-array pointer.
16
+ */
17
+ const pureNumericMath = new Set([
18
+ 'abs',
19
+ 'acos',
20
+ 'acosh',
21
+ 'asin',
22
+ 'asinh',
23
+ 'atan',
24
+ 'atan2',
25
+ 'atanh',
26
+ 'cbrt',
27
+ 'ceil',
28
+ 'clz32',
29
+ 'cos',
30
+ 'cosh',
31
+ 'exp',
32
+ 'expm1',
33
+ 'floor',
34
+ 'fround',
35
+ 'hypot',
36
+ 'imul',
37
+ 'log',
38
+ 'log10',
39
+ 'log1p',
40
+ 'log2',
41
+ 'max',
42
+ 'min',
43
+ 'pow',
44
+ 'round',
45
+ 'sign',
46
+ 'sin',
47
+ 'sinh',
48
+ 'sqrt',
49
+ 'tan',
50
+ 'tanh',
51
+ 'trunc'
52
+ ]);
11
53
  export const borrowSafeOperationsOf = (body, safeCallees = new Set(), plainFieldRead = () => false) => {
12
54
  const keys = stringConstantsOf(body);
13
55
  const nativeCharacterReads = new Set();
56
+ const mathReads = new Set();
14
57
  const safe = new Set();
15
58
  for (const block of body.blocks.values()) {
16
59
  for (const operation of block.operations) {
17
60
  if (operation.kind === 'get' && operation.receiver.representation.kind === 'string' && keys.get(operation.key.value) === 'charCodeAt')
18
61
  nativeCharacterReads.add(operation.result.id);
62
+ // Authenticated by the native protocol, as `ir/floats.ts` authenticates
63
+ // `Math.fround`: a user object named Math has none.
64
+ const receiver = operation.kind === 'get' ? operation.receiver.representation : null;
65
+ if (operation.kind === 'get' &&
66
+ receiver?.kind === 'native-handle' &&
67
+ receiver.native === null &&
68
+ receiver.protocol === 'Math' &&
69
+ pureNumericMath.has(keys.get(operation.key.value) ?? ''))
70
+ mathReads.add(operation.result.id);
19
71
  }
20
72
  }
21
73
  for (const block of body.blocks.values()) {
@@ -51,7 +103,8 @@ export const borrowSafeOperationsOf = (body, safeCallees = new Set(), plainField
51
103
  case 'get': {
52
104
  const receiver = operation.receiver.representation;
53
105
  const key = keys.get(operation.key.value);
54
- if ((receiver.kind === 'string' && (key === 'length' || key === 'charCodeAt')) ||
106
+ if (mathReads.has(operation.result.id) ||
107
+ (receiver.kind === 'string' && (key === 'length' || key === 'charCodeAt')) ||
55
108
  (receiver.kind === 'typed-array' && (key === 'length' || number(operation.key.representation))))
56
109
  safe.add(operation);
57
110
  // A data field of a native object: `node.left` on a class instance
@@ -76,6 +129,7 @@ export const borrowSafeOperationsOf = (body, safeCallees = new Set(), plainField
76
129
  break;
77
130
  case 'call':
78
131
  if (safeCallees.has(operation.callee.value) ||
132
+ (mathReads.has(operation.callee.value) && operation.arguments.every((argument) => number(argument.representation))) ||
79
133
  (nativeCharacterReads.has(operation.callee.value) &&
80
134
  operation.arguments.length === 1 &&
81
135
  operation.arguments.every((argument) => number(argument.representation))))
@@ -20,8 +20,10 @@ export interface NativeCallableFlow {
20
20
  * which that demand needs. Unsupported transports fail closed. In particular,
21
21
  * an arbitrary matching callable signature is never an implementation source.
22
22
  */
23
- export declare const nativeCallableFlowOf: (bodies: readonly IrBody[], placements: ReadonlyMap<DeclarationId, BindingPlacement>, classes: ReadonlyMap<DeclarationId, ClassLayout>, conversions?: Pick<ConversionCensus, "nodeById"> & Partial<Pick<ConversionCensus, "nodeFor">>, trace?: (read: Extract<IrOperation, {
23
+ declare const computeNativeCallableFlow: (bodies: readonly IrBody[], placements: ReadonlyMap<DeclarationId, BindingPlacement>, classes: ReadonlyMap<DeclarationId, ClassLayout>, conversions?: Pick<ConversionCensus, "nodeById"> & Partial<Pick<ConversionCensus, "nodeFor">>, trace?: (read: Extract<IrOperation, {
24
24
  kind: "get";
25
25
  }>, reason: string) => void, deriver?: Pick<RepresentationDeriver, "layoutOf"> | null) => NativeCallableFlow;
26
+ export declare const nativeCallableFlowOf: (...args: Parameters<typeof computeNativeCallableFlow>) => NativeCallableFlow;
26
27
  /** Compatibility view of the same execution/escape census; no second analysis policy. */
27
28
  export declare const closedClassFieldCallablesOf: (...args: Parameters<typeof nativeCallableFlowOf>) => ReadonlyMap<IrValueId, CallCalleeIdentity>;
29
+ export {};
@@ -29,7 +29,7 @@ import { observesNativeCarrierOnly, operandsOfIrOperation, resultOfIrOperation }
29
29
  * which that demand needs. Unsupported transports fail closed. In particular,
30
30
  * an arbitrary matching callable signature is never an implementation source.
31
31
  */
32
- export const nativeCallableFlowOf = (bodies, placements, classes, conversions, trace, deriver) => {
32
+ const computeNativeCallableFlow = (bodies, placements, classes, conversions, trace, deriver) => {
33
33
  const propertyLayoutCache = new Map();
34
34
  const nativePropertyLayoutOf = (representation) => hasNativePropertyLayout(representation, deriver ?? null, classes, new Set(), propertyLayoutCache);
35
35
  const cells = [];
@@ -1392,5 +1392,31 @@ export const nativeCallableFlowOf = (bodies, placements, classes, conversions, t
1392
1392
  }
1393
1393
  return { callables: result, enteredBodies: new Set([...entered].map((body) => body.owner)) };
1394
1394
  };
1395
+ /**
1396
+ * The flow is solved three times per compile over bodies that are, for the
1397
+ * second and third, the very same objects (the reflection census and the first
1398
+ * round of the call-dispatch fixed point both read the dispatched program).
1399
+ * Its answer is a function of those objects alone -- the conversion census it
1400
+ * consults is append-only and `nodeFor` is idempotent per pair -- so the last
1401
+ * answer per class map is reused when every input is identical. A traced run
1402
+ * reports reads as it solves and is always solved.
1403
+ */
1404
+ const rememberedFlows = new WeakMap();
1405
+ export const nativeCallableFlowOf = (...args) => {
1406
+ const [bodies, placements, classes, conversions, trace, deriver] = args;
1407
+ if (trace !== undefined)
1408
+ return computeNativeCallableFlow(...args);
1409
+ const held = rememberedFlows.get(classes);
1410
+ if (held &&
1411
+ held.placements === placements &&
1412
+ held.conversions === conversions &&
1413
+ held.deriver === (deriver ?? null) &&
1414
+ held.bodies.length === bodies.length &&
1415
+ held.bodies.every((body, index) => body === bodies[index]))
1416
+ return held.flow;
1417
+ const flow = computeNativeCallableFlow(...args);
1418
+ rememberedFlows.set(classes, { bodies, placements, conversions, deriver: deriver ?? null, flow });
1419
+ return flow;
1420
+ };
1395
1421
  /** Compatibility view of the same execution/escape census; no second analysis policy. */
1396
1422
  export const closedClassFieldCallablesOf = (...args) => nativeCallableFlowOf(...args).callables;
@@ -10,20 +10,91 @@ const sha256Lines = (lines) => {
10
10
  return hash.digest('hex');
11
11
  };
12
12
  /**
13
- * `Map`/`Set` are not JSON-serializable on their own; this replacer expands
14
- * them structurally so the plan's `selected`/`evidence` maps and the graph's
15
- * `operations`/`edges`/`results` tables actually contribute to the digest
16
- * instead of silently vanishing into `{}`. Functions (`manifest.spellable`)
17
- * are dropped by `JSON.stringify` as they always were; the predicate's
18
- * answers are what the demanded keys already record.
13
+ * The digest of a value, streamed into the hash rather than built as one
14
+ * string: the plan and the semantic graph of a large program stringify to
15
+ * hundreds of megabytes, and holding that (and running a replacer callback
16
+ * per property) cost seconds.
17
+ *
18
+ * `Map`/`Set` are not JSON-serializable on their own; they are expanded
19
+ * structurally so the plan's `selected`/`evidence` maps and the graph's
20
+ * `operations`/`edges`/`results` tables contribute to the digest instead of
21
+ * silently vanishing into `{}`. Functions (`manifest.spellable`) and
22
+ * `undefined` object members are skipped as `JSON.stringify` skips them; the
23
+ * predicate's answers are what the demanded keys already record.
24
+ *
25
+ * The byte stream is a prefix code: every value starts with a tag, every
26
+ * string and key is length-prefixed, every container is closed, so two
27
+ * different values cannot produce the same stream. Insertion order is kept
28
+ * (as `JSON.stringify` kept it); a `Set` is sorted as before.
19
29
  */
20
- const canonicalize = (value) => JSON.stringify(value, (_key, val) => {
21
- if (val instanceof Map)
22
- return { __map__: [...val.entries()] };
23
- if (val instanceof Set)
24
- return { __set__: [...val.values()].sort() };
25
- return val;
26
- });
30
+ const digestOf = (value) => {
31
+ const hash = createHash('sha256');
32
+ let pending = '';
33
+ const write = (text) => {
34
+ pending += text;
35
+ if (pending.length >= 1 << 16) {
36
+ hash.update(pending, 'utf8');
37
+ pending = '';
38
+ }
39
+ };
40
+ const text = (value) => write(`s${value.length}:${value}`);
41
+ const visit = (val) => {
42
+ if (val === null)
43
+ return write('z');
44
+ switch (typeof val) {
45
+ case 'string':
46
+ return text(val);
47
+ case 'number':
48
+ return write(Number.isFinite(val) ? `n${val};` : 'z');
49
+ case 'boolean':
50
+ return write(val ? 't' : 'f');
51
+ case 'bigint':
52
+ return write(`b${val};`);
53
+ case 'object':
54
+ break;
55
+ default:
56
+ // undefined, symbol, function: absent from an object, null in an array.
57
+ return write('z');
58
+ }
59
+ const object = val;
60
+ if (typeof object.toJSON === 'function')
61
+ return visit(object.toJSON());
62
+ if (Array.isArray(val)) {
63
+ write(`A${val.length}[`);
64
+ for (const element of val)
65
+ visit(element);
66
+ return write(']');
67
+ }
68
+ if (val instanceof Map) {
69
+ write(`M${val.size}[`);
70
+ for (const [key, entry] of val) {
71
+ visit(key);
72
+ visit(entry);
73
+ }
74
+ return write(']');
75
+ }
76
+ if (val instanceof Set) {
77
+ const members = [...val.values()].sort();
78
+ write(`S${members.length}[`);
79
+ for (const member of members)
80
+ visit(member);
81
+ return write(']');
82
+ }
83
+ const record = val;
84
+ write('O{');
85
+ for (const key of Object.keys(record)) {
86
+ const member = record[key];
87
+ if (member === undefined || typeof member === 'function' || typeof member === 'symbol')
88
+ continue;
89
+ text(key);
90
+ visit(member);
91
+ }
92
+ write('}');
93
+ };
94
+ visit(value);
95
+ hash.update(pending, 'utf8');
96
+ return hash.digest('hex');
97
+ };
27
98
  /**
28
99
  * Mints a certificate from a clean certification, or returns `null` for one
29
100
  * that refused anything.
@@ -38,9 +109,9 @@ const canonicalize = (value) => JSON.stringify(value, (_key, val) => {
38
109
  export const mintCapabilityCertificate = (certification, subjects) => {
39
110
  if (!certification.certified)
40
111
  return null;
41
- const planDigest = sha256(canonicalize(subjects.plan));
42
- const semanticSnapshotDigest = sha256(canonicalize(subjects.semanticSnapshot));
43
- const manifestDigest = sha256(canonicalize(subjects.manifest));
112
+ const planDigest = digestOf(subjects.plan);
113
+ const semanticSnapshotDigest = digestOf(subjects.semanticSnapshot);
114
+ const manifestDigest = digestOf(subjects.manifest);
44
115
  const certificationDigest = sha256Lines(certification.demanded.map((key) => `${key}\n`));
45
116
  const id = sha256([planDigest, semanticSnapshotDigest, manifestDigest, certificationDigest].join('|'));
46
117
  return Object.freeze({ id, planDigest, semanticSnapshotDigest, manifestDigest, certificationDigest });
@@ -335,7 +335,9 @@ export const spreadSourceCarrierKeyOf = (kind, representation, receiver, deriver
335
335
  ? `dictionary(${candidate.key}->${receiver.key})`
336
336
  : `dictionary(${candidate.key}->${receiver?.kind ?? 'absent'})`;
337
337
  if (representation.kind === 'dynamic') {
338
- return isDynamicCopyableIntoFieldRecord(deriver, receiver) ? 'field-record<-dynamic' : `dynamic->${receiver?.kind ?? 'absent'}`;
338
+ if (isDynamicCopyableIntoFieldRecord(deriver, receiver))
339
+ return 'field-record<-dynamic';
340
+ return receiver?.kind === 'dictionary' ? `dynamic->dictionary(${receiver.key})` : `dynamic->${receiver?.kind ?? 'absent'}`;
339
341
  }
340
342
  if (spreadFieldRecordReceiverOf(deriver, receiver) !== null)
341
343
  return isCopyableIntoFieldRecord(deriver, representation) ? 'field-record<-copyable' : `field-record<-${kind}`;
@@ -1,4 +1,5 @@
1
1
  import type { DeclarationId, IrValueId } from '../identity/ids.js';
2
+ import { type HoistPlan } from './hoist.js';
2
3
  import type { Representation, TypedArrayElementDomain } from '../representation/model.js';
3
4
  import type { IrBlockId, IrBody, IrNonTerminatorOperation, IrOperand } from './model.js';
4
5
  /**
@@ -55,7 +56,7 @@ export interface DenseArray {
55
56
  /** The block the flag and the pointer are computed in. */
56
57
  readonly preheader: IrBlockId;
57
58
  /** Every invariant addend used by an access, with `null` for the bare counter. All ranges must fit before any access is unchecked. */
58
- readonly bases: readonly (IrOperand | null)[];
59
+ readonly bases: readonly DenseOffset[];
59
60
  /** The counter cell, read at the preheader for the lowest index the loop can touch. */
60
61
  readonly counter: DeclarationId;
61
62
  /** The loop's own bound. */
@@ -110,6 +111,19 @@ export interface DenseArray {
110
111
  */
111
112
  readonly widened: boolean;
112
113
  }
114
+ /**
115
+ * What an index adds to the counter: a signed sum of loop invariants, `null`
116
+ * for the bare counter. A stencil names its neighbours by subtracting
117
+ * (`u[c - 1]`, `u[c - PITCH]`) and by chaining (`u[c + up - 1]`), and every
118
+ * one of those is the counter plus a number the preheader can add up and
119
+ * check like any other base.
120
+ */
121
+ export type DenseOffset = {
122
+ readonly terms: readonly {
123
+ readonly operand: IrOperand;
124
+ readonly negated: boolean;
125
+ }[];
126
+ } | null;
113
127
  export type DenseReference = {
114
128
  readonly kind: 'cell';
115
129
  readonly declaration: DeclarationId;
@@ -227,4 +241,4 @@ export interface AdmittedDenseLoopPlan {
227
241
  * chain is needed at all.
228
242
  */
229
243
  export declare const admittedDenseLoopPlanOf: (plan: DenseLoopPlan, integerValues: ReadonlySet<IrValueId>, admitsCell: DenseCellPolicy) => AdmittedDenseLoopPlan;
230
- export declare const denseLoopsOf: (body: IrBody) => DenseLoopPlan;
244
+ export declare const denseLoopsOf: (body: IrBody, hoists?: HoistPlan) => DenseLoopPlan;
@@ -84,7 +84,7 @@ export const admittedDenseLoopPlanOf = (plan, integerValues, admitsCell) => {
84
84
  }
85
85
  return { arrays, groups, accesses, lengths };
86
86
  };
87
- export const denseLoopsOf = (body) => {
87
+ export const denseLoopsOf = (body, hoists = loopInvariantHoistsOf(body)) => {
88
88
  // A try region renders as one assembled chunk, so a preheader inside one has
89
89
  // no single place for the setup to land -- the same restriction `hoist.ts`
90
90
  // takes, and for the same reason.
@@ -141,7 +141,7 @@ export const denseLoopsOf = (body) => {
141
141
  // loop's own body until `ir/hoist.ts` moves them to its preheader, and asking
142
142
  // the raw IR where they are answers "inside the loop" for every one of them.
143
143
  // `emitBody` runs the same plan, and renders it before this setup.
144
- for (const [blockId, operations] of loopInvariantHoistsOf(body).into)
144
+ for (const [blockId, operations] of hoists.into)
145
145
  for (const operation of operations) {
146
146
  blockOfOperation.set(operation, blockId);
147
147
  const result = resultOfIrOperation(operation);
@@ -155,6 +155,29 @@ export const denseLoopsOf = (body) => {
155
155
  const where = location.get(value);
156
156
  return where === undefined || !blocks.has(where);
157
157
  };
158
+ // A `const` local read inside a loop reaches it as a header phi whose
159
+ // incoming values are the one value from before the loop and the phi
160
+ // itself: invariant, but defined in the loop, so every offset Bloom's
161
+ // stencil adds to its counter (`c + up`) looked like an unbounded index.
162
+ // The preheader names what the phi always holds.
163
+ const invariantOperand = (operand, blocks) => {
164
+ const seen = new Set();
165
+ let current = operand;
166
+ while (!definedOutside(current.value, blocks)) {
167
+ if (seen.has(current.value))
168
+ return null;
169
+ seen.add(current.value);
170
+ const phi = operationOf.get(current.value);
171
+ if (phi?.kind !== 'phi')
172
+ return null;
173
+ const sources = phi.incoming.map((incoming) => incoming.value).filter((value) => !seen.has(value.value));
174
+ const first = sources[0];
175
+ if (first === undefined || sources.some((source) => source.value !== first.value))
176
+ return null;
177
+ current = first;
178
+ }
179
+ return current;
180
+ };
158
181
  // A value the preheader may NAME: defined before the loop, so it is both
159
182
  // unchanged by the loop (SSA) and already assigned where the setup renders.
160
183
  // A cell the loop never writes is not enough -- the READ of it can be one of
@@ -168,7 +191,8 @@ export const denseLoopsOf = (body) => {
168
191
  cellWrites,
169
192
  usesOf,
170
193
  operationOf,
171
- definedOutside
194
+ definedOutside,
195
+ invariantOperand
172
196
  }));
173
197
  const groupOfLoop = new Map();
174
198
  for (const [index, loop] of found.entries()) {
@@ -293,7 +317,8 @@ const loopWindowsOf = (loop, body, graph, loops, context) => {
293
317
  if (!left || !right)
294
318
  return null;
295
319
  const counter = context.readsCell.get(left.value);
296
- if (counter === undefined || !context.definedOutside(right.value, loop.blocks))
320
+ const bound = counter === undefined ? null : context.invariantOperand(right, loop.blocks);
321
+ if (counter === undefined || bound === null)
297
322
  return null;
298
323
  // Exactly one advance, by an amount the preheader can name. Several
299
324
  // advances, or a step the loop itself computes, and "the counter never
@@ -309,10 +334,11 @@ const loopWindowsOf = (loop, body, graph, loops, context) => {
309
334
  // of `loops`.
310
335
  if (loops.some((inner) => inner.header !== loop.header && inner.blocks.has(advance.block) && loop.blocks.has(inner.header)))
311
336
  return null;
312
- const step = stepOf(advance.value, counter, context.operationOf, context.readsCell);
313
- if (step === undefined)
337
+ const advanced = stepOf(advance.value, counter, context.operationOf, context.readsCell);
338
+ if (advanced === undefined)
314
339
  return null;
315
- if (step !== null && !context.definedOutside(step.value, loop.blocks))
340
+ const step = advanced === null ? null : context.invariantOperand(advanced, loop.blocks);
341
+ if (advanced !== null && step === null)
316
342
  return null;
317
343
  const candidates = windowsOfLoop(loop.blocks, body, { ...context, counter });
318
344
  if (candidates.length === 0)
@@ -320,7 +346,7 @@ const loopWindowsOf = (loop, body, graph, loops, context) => {
320
346
  return {
321
347
  preheader,
322
348
  counter,
323
- bound: right,
349
+ bound,
324
350
  inclusive: test.operator === '<=',
325
351
  step,
326
352
  widened: advanceReachesAnAccess(loop, body, graph, advance.block, counter),
@@ -506,7 +532,11 @@ const windowsOfLoop = (blocks, body, context) => {
506
532
  if (found.wrapped !== wrapped || found.modulus !== modulus)
507
533
  found.sound = false;
508
534
  else {
509
- if (!found.bases.some((known) => (known?.value ?? null) === (base?.value ?? null)))
535
+ const same = (known) => known === null || base === null
536
+ ? known === base
537
+ : known.terms.length === base.terms.length &&
538
+ known.terms.every((term, at) => term.operand.value === base.terms[at]?.operand.value && term.negated === base.terms[at]?.negated);
539
+ if (!found.bases.some(same))
510
540
  found.bases.push(base);
511
541
  found.operations.push(operation);
512
542
  }
@@ -639,18 +669,33 @@ const indexBaseOf = (key, context, blocks) => {
639
669
  return null;
640
670
  const parallel = parallelCounterBaseOf(key, context, blocks);
641
671
  if (parallel !== undefined)
642
- return parallel;
643
- const compute = context.operationOf.get(key.value);
644
- if (compute?.kind !== 'compute' || compute.form !== 'binary' || compute.operator !== '+')
645
- return undefined;
646
- const [left, right] = compute.operands;
647
- if (!left || !right)
648
- return undefined;
649
- if (context.readsCell.get(left.value) === context.counter && context.definedOutside(right.value, blocks))
650
- return right;
651
- if (context.readsCell.get(right.value) === context.counter && context.definedOutside(left.value, blocks))
652
- return left;
653
- return undefined;
672
+ return { terms: [{ operand: parallel, negated: false }] };
673
+ const terms = [];
674
+ // Exactly one positive counter leaf; every other leaf invariant. Depth is
675
+ // bounded by the expression the program wrote, a handful of terms.
676
+ const walk = (operand, negated, depth) => {
677
+ if (context.readsCell.get(operand.value) === context.counter)
678
+ return negated ? undefined : 1;
679
+ const invariant = context.invariantOperand(operand, blocks);
680
+ if (invariant !== null) {
681
+ terms.push({ operand: invariant, negated });
682
+ return 0;
683
+ }
684
+ const compute = context.operationOf.get(operand.value);
685
+ if (depth > 4 || compute?.kind !== 'compute' || compute.form !== 'binary')
686
+ return undefined;
687
+ if (compute.operator !== '+' && compute.operator !== '-')
688
+ return undefined;
689
+ const [left, right] = compute.operands;
690
+ if (!left || !right)
691
+ return undefined;
692
+ const counted = walk(left, negated, depth + 1);
693
+ if (counted === undefined)
694
+ return undefined;
695
+ const more = walk(right, compute.operator === '-' ? !negated : negated, depth + 1);
696
+ return more === undefined ? undefined : counted + more;
697
+ };
698
+ return walk(key, false, 0) === 1 ? { terms } : undefined;
654
699
  };
655
700
  /** Two counters advanced together by one differ by their initial offset.
656
701
  * Requiring a zero primary seed and adjacent advances avoids synthesizing
@@ -3,39 +3,12 @@ import type { Representation } from '../representation/model.js';
3
3
  import { type DeadValueRules } from './dead-values.js';
4
4
  import type { ForwardedBinding, ForwardingPolicy } from './deferral.js';
5
5
  import { type HoistPlan } from './hoist.js';
6
+ import { type Float32Narrowing } from './floats.js';
6
7
  import { type IntegerStorageFacts } from './integers.js';
7
8
  import { type CallOperation, type ComputeOperation, type GetOperation, type IrBody, type IrOperand, type IrOperation } from './model.js';
8
9
  import { type NumericIntrinsic } from './numeric-intrinsics.js';
9
10
  import { type SharedStringLayout } from './string-layout-reuse.js';
10
11
  import { type TypeQueryComparison } from './type-query-results.js';
11
- /**
12
- * Every per-body census the printer needs before it renders a line, computed
13
- * in one place, in the one order they depend on each other in.
14
- *
15
- * Distinct from `IrBody.facts` (`ir/captures.ts`), which is the whole-program
16
- * capture answer sealed onto the body before rendering starts. These are the
17
- * per-body questions, asked once per body at render entry; the two converge
18
- * when the remaining Phase 3 rows land.
19
- *
20
- * These thirteen analyses used to run inline in `targets/cpp/emit.ts`, each
21
- * copying its answer into the emit context. Nothing about them is C++: they ask
22
- * what a body does -- which results nothing reads, which reads may be deferred
23
- * to their single use, which numbers fit a `long long`, which loop-invariant
24
- * reads may be hoisted -- and the printer only spells the answers. What made
25
- * them live in the target was the ORDER, which is real and subtle and was
26
- * recorded only as comments between the calls: the type-query census removes
27
- * values from the deferral census, the hoists remove more, and the string
28
- * length reuse removes more still, so reading the deferral set at the wrong
29
- * point in the sequence silently answers a question with a set that is about
30
- * to shrink. Here that order is the body of one function, stated once, and a
31
- * reader who needs to know why a step sits where it does finds the reason at
32
- * the step rather than in a comment beside a call site.
33
- *
34
- * The target still owns two decisions inside the sequence, because both are
35
- * about C++ storage rather than about the program, and both are needed
36
- * mid-order. They arrive as `IrBodyCensusPolicy` hooks, invoked exactly where
37
- * the inline pipeline invoked them.
38
- */
39
12
  export interface IrBodyCensus {
40
13
  /** Protocol cursors that never escape their `get-iterator`, so the printer may hold them by value. */
41
14
  readonly localIterators: ReadonlySet<IrValueId>;
@@ -54,6 +27,8 @@ export interface IrBodyCensus {
54
27
  readonly typeQueryComparisons: ReadonlyMap<ComputeOperation, TypeQueryComparison>;
55
28
  readonly integerValues: ReadonlySet<IrValueId>;
56
29
  readonly integerBindings: ReadonlySet<DeclarationId>;
30
+ /** Values, cells and single-precision arithmetic held in `float` -- see `ir/floats.ts`. */
31
+ readonly float32: Float32Narrowing;
57
32
  readonly remainderForms: ReadonlyMap<IrValueId, 'restated' | 'dynamic'>;
58
33
  /** See `IntegerNarrowing.roundingArithmetic`. */
59
34
  readonly roundingArithmetic: ReadonlySet<IrValueId>;
@@ -83,6 +58,8 @@ export interface IrBodyCensusPolicy {
83
58
  readonly deadValues: DeadValueRules;
84
59
  /** Whether this cell is a private local `string` whose `typeof` result may be saved rather than recomputed. */
85
60
  readonly stringQueryCell: (declaration: DeclarationId) => boolean;
61
+ /** Whether a number cell's storage is this body's own to declare `float` -- see `ir/floats.ts`. */
62
+ readonly float32Cell: (declaration: DeclarationId) => boolean;
86
63
  /** What a whole-program census already settled about this body's integer storage. */
87
64
  readonly integerStorage: IntegerStorageFacts;
88
65
  /**
@@ -110,7 +87,7 @@ export interface IrBodyCensusPolicy {
110
87
  readonly formalStorage: (settled: IrBodyCensusBeforeHoists) => ReadonlySet<DeclarationId>;
111
88
  }
112
89
  /** What is known when `formalStorage` runs: everything except the hoists and the two censuses that read them. */
113
- export type IrBodyCensusBeforeHoists = Pick<IrBodyCensus, 'localIterators' | 'deferrable' | 'callArgumentOnly' | 'forwardedBindings' | 'dead' | 'unread' | 'booleanConstants' | 'typeQueryValues' | 'typeQueryBindings' | 'typeQueryComparisons' | 'integerValues' | 'integerBindings' | 'remainderForms' | 'roundingArithmetic' | 'numericCalls' | 'numericCallOnly'>;
90
+ export type IrBodyCensusBeforeHoists = Pick<IrBodyCensus, 'localIterators' | 'deferrable' | 'callArgumentOnly' | 'forwardedBindings' | 'dead' | 'unread' | 'booleanConstants' | 'typeQueryValues' | 'typeQueryBindings' | 'typeQueryComparisons' | 'integerValues' | 'integerBindings' | 'float32' | 'remainderForms' | 'roundingArithmetic' | 'numericCalls' | 'numericCallOnly'>;
114
91
  export declare const irBodyCensusOf: (body: IrBody, policy: IrBodyCensusPolicy) => IrBodyCensus;
115
92
  /**
116
93
  * Where every value in this body came from -- purely syntactic indices over