@geastack/compiler 1.0.22 → 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.
@@ -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));
@@ -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
  }
@@ -1,3 +1,4 @@
1
+ import type { HoistPlan } from '../../ir/hoist.js';
1
2
  import type { IrValueId } from '../../identity/ids.js';
2
3
  import type { AllocateArrayObjectOperation, IrBlockId, IrBody } from '../../ir/model.js';
3
4
  import { type Representation } from '../../representation/model.js';
@@ -68,7 +69,7 @@ export declare const emitFillLoop: (ctx: EmitContext, lines: string[], fill: Fil
68
69
  * until a `%` compute actually renders (`emit.ts`'s `emitBinaryOperation`),
69
70
  * which is why that one field, alone of this group, is on the whitelist.
70
71
  */
71
- export declare const admitDenseWindows: (ctx: EmitContext, prepass: EmitBodyPrepassFacts, body: IrBody) => void;
72
+ export declare const admitDenseWindows: (ctx: EmitContext, prepass: EmitBodyPrepassFacts, body: IrBody, hoists: HoistPlan) => void;
72
73
  /**
73
74
  * The preheader statements one loop's dense windows need: an element pointer
74
75
  * per array, and the one loop-invariant condition that makes indexing it sound.
@@ -924,8 +924,8 @@ const denseIntegerText = (ctx, operand) => ctx.integerValues.has(operand.value)
924
924
  * until a `%` compute actually renders (`emit.ts`'s `emitBinaryOperation`),
925
925
  * which is why that one field, alone of this group, is on the whitelist.
926
926
  */
927
- export const admitDenseWindows = (ctx, prepass, body) => {
928
- const plan = denseLoopsOf(body);
927
+ export const admitDenseWindows = (ctx, prepass, body, hoists) => {
928
+ const plan = denseLoopsOf(body, hoists);
929
929
  if (plan.arrays.length === 0)
930
930
  return;
931
931
  const admitted = admittedDenseLoopPlanOf(plan, ctx.integerValues, (declaration) => denseCellName(ctx, declaration) !== null);
@@ -1061,7 +1061,11 @@ export const emitDenseSetup = (ctx, lines, blockId) => {
1061
1061
  // this may dereference it.
1062
1062
  said.push(...holder.guard, ...shape, ...writable);
1063
1063
  for (const offset of array.bases) {
1064
- const base = offset === null ? '0' : operandText(ctx, offset);
1064
+ const base = offset === null
1065
+ ? '0'
1066
+ : offset.terms.length === 1 && !offset.terms[0].negated
1067
+ ? operandText(ctx, offset.terms[0].operand)
1068
+ : `(${offset.terms.map((term, at) => `${term.negated ? '-' : at === 0 ? '' : '+'} (${operandText(ctx, term.operand)})`).join(' ')})`;
1065
1069
  said.push(`gea::denseIndexWindow(${size}, ${seed}, ${base}, ${operandText(ctx, array.bound)}, ${step}, ${array.inclusive}, ${array.widened})`);
1066
1070
  }
1067
1071
  }
@@ -5,7 +5,7 @@ import { carrierDifference, shortCarrierText } from '../../representation/differ
5
5
  import { bindingReference, createCppEmitBlockedError, cppFormalName, cppFrameLocalName, cppFrameStructName, cppReceiverName, declareCell, defineValue, defineValueAlias, isCppEmitBlockedError, operandText } from './emit-context.js';
6
6
  import { alignedValueText, classFamilyLoadText, emptyArraySentinelText, movedValueText } from './emit-narrowing.js';
7
7
  import { stringAppendStatement } from './emit-tostring.js';
8
- import { cppAbiParameterType, cppBoxedType, cppNarrowedIntegerType, cppStringLiteral, cppTypeOf } from './types.js';
8
+ import { cppAbiParameterType, cppBoxedType, cppNarrowedFloatType, cppNarrowedIntegerType, cppStringLiteral, cppTypeOf } from './types.js';
9
9
  import { receiverBoundCallableText } from './emit-callable.js';
10
10
  import { structuralRecordViewText } from './emit-record-view.js';
11
11
  import { owningConversionInputText } from './owning-conversion-input.js';
@@ -582,7 +582,9 @@ export const emitBindingWrite = (ctx, lines, operation) => {
582
582
  ? 'gea::Value::Tag'
583
583
  : ctx.integerBindings.has(operation.declaration) && !cell.boxed
584
584
  ? cppNarrowedIntegerType
585
- : cppTypeOf(held ?? operation.value.representation);
585
+ : ctx.float32.bindings.has(operation.declaration) && !cell.boxed
586
+ ? cppNarrowedFloatType
587
+ : cppTypeOf(held ?? operation.value.representation);
586
588
  if (cell.boxed) {
587
589
  // The box itself, not its pointee, is what gets declared and allocated: a
588
590
  // shared cell is born already holding this first value, so every other
@@ -918,6 +918,19 @@ const emitCharCodeBufferPush = (ctx, lines, operation) => {
918
918
  return true;
919
919
  };
920
920
  export const emitCall = (ctx, lines, operation) => {
921
+ const minMax = ctx.numericCalls.get(operation);
922
+ if (minMax === 'min' || minMax === 'max') {
923
+ // An integer result (`ir/integers.ts`) is the smaller or larger integer;
924
+ // anything else is the host's own double answer, NaN and -0 included.
925
+ const integer = operation.result !== null && isIntegerStorageValue(ctx, operation.result.id);
926
+ const args = operation.arguments.map((argument) => integer ? `static_cast<long long>(${operandText(ctx, argument)})` : `static_cast<double>(${operandText(ctx, argument)})`);
927
+ const expression = integer ? `std::${minMax}<long long>(${args.join(', ')})` : `gea::host::Math::${minMax}Direct({${args.join(', ')}})`;
928
+ if (operation.result && !ctx.unreadValues.has(operation.result.id))
929
+ lines.push(`${defineValue(ctx, operation.result)} = ${expression};`);
930
+ else
931
+ lines.push(`${expression};`);
932
+ return;
933
+ }
921
934
  if (ctx.numericCalls.get(operation) === 'imul') {
922
935
  const args = operation.arguments.map((argument) => {
923
936
  const text = operandText(ctx, argument);
@@ -1,7 +1,7 @@
1
1
  import type { DefineOwnPropertyOperation, GetOperation, IrOperand, IrResult, SetOperation } from '../../ir/model.js';
2
2
  import type { IrValueId } from '../../identity/ids.js';
3
3
  import { type ReactiveRevisionOrigin, type EmitContext, type PrototypeMethodRead } from './emit-context.js';
4
- import type { Ownership, Representation } from '../../representation/model.js';
4
+ import type { Ownership, Representation, TypedArrayElementDomain } from '../../representation/model.js';
5
5
  import { type ConversionSite } from './emit-narrowing.js';
6
6
  import { type RecordIndexSidecar } from './records.js';
7
7
  /**
@@ -64,6 +64,8 @@ export declare const arrayAccessText: (ctx: EmitContext, receiver: IrOperand, ke
64
64
  * index, and the three block-shaped members `emit-buffers.ts` owns.
65
65
  */
66
66
  export declare const deferredTypedArrayMethodClaim: (staticKeyTexts: ReadonlyMap<IrValueId, string>, receiver: IrOperand, key: IrOperand) => PrototypeMethodRead | null;
67
+ /** The views whose every element is an integer, read and written in integer registers when the census holds the value as one. */
68
+ export declare const integerTypedArrayElements: ReadonlySet<TypedArrayElementDomain>;
67
69
  export declare const typedArrayAccessText: (ctx: EmitContext, receiver: IrOperand, key: IrOperand, result: IrResult | null) => string | null;
68
70
  /**
69
71
  * `absentCapableElementText` for the typed-array reader.
@@ -336,6 +336,16 @@ export const deferredTypedArrayMethodClaim = (staticKeyTexts, receiver, key) =>
336
336
  receiverElement: typedArrayElementSpelling(carrier)
337
337
  };
338
338
  };
339
+ /** The views whose every element is an integer, read and written in integer registers when the census holds the value as one. */
340
+ export const integerTypedArrayElements = new Set([
341
+ 'int8',
342
+ 'uint8',
343
+ 'uint8-clamped',
344
+ 'int16',
345
+ 'uint16',
346
+ 'int32',
347
+ 'uint32'
348
+ ]);
339
349
  export const typedArrayAccessText = (ctx, receiver, key, result) => {
340
350
  if (receiver.representation.kind !== 'typed-array')
341
351
  return null;
@@ -394,8 +404,14 @@ export const typedArrayAccessText = (ctx, receiver, key, result) => {
394
404
  const integerKey = isIntegerStorageValue(ctx, key.value);
395
405
  const reader = integerKey ? 'elementAtIndex' : 'elementAt';
396
406
  const keyText = operandText(ctx, key);
397
- return (absentCapableNumericElementText(receiverText, keyText, result, integerKey ? 'hasElementAtIndex' : 'hasElement', reader) ??
398
- `${receiverText}->${reader}(${keyText})`);
407
+ const absentCapable = absentCapableNumericElementText(receiverText, keyText, result, integerKey ? 'hasElementAtIndex' : 'hasElement', reader);
408
+ if (absentCapable !== null)
409
+ return absentCapable;
410
+ // An integer element read into a `long long` the integer census chose is
411
+ // that integer: no conversion to `double` and back.
412
+ if (integerKey && result !== null && integerTypedArrayElements.has(receiver.representation.element) && ctx.integerValues.has(result.id))
413
+ return `${receiverText}->elementIntegerAtIndex(${keyText})`;
414
+ return `${receiverText}->${reader}(${keyText})`;
399
415
  };
400
416
  /**
401
417
  * `absentCapableElementText` for the typed-array reader.
@@ -1650,6 +1650,12 @@ export interface EmitContext {
1650
1650
  readonly integerValues: ReadonlySet<IrValueId>;
1651
1651
  /** Settled the same way as `hoistedResults`. */
1652
1652
  readonly integerBindings: ReadonlySet<DeclarationId>;
1653
+ /** `ir/floats.ts`'s answer for this body. Settled the same way as `hoistedResults`. */
1654
+ readonly float32: {
1655
+ readonly values: ReadonlySet<IrValueId>;
1656
+ readonly bindings: ReadonlySet<DeclarationId>;
1657
+ readonly arithmetic: ReadonlySet<IrValueId>;
1658
+ };
1653
1659
  /** Finite typeof snapshots proved by the IR, confined to comparison-only uses. Settled the same way as `hoistedResults`. */
1654
1660
  readonly typeQueryValues: ReadonlySet<IrValueId>;
1655
1661
  /** Settled the same way as `hoistedResults`. */
@@ -1881,6 +1887,11 @@ export interface EmitBodyPrepassFacts {
1881
1887
  readonly numericCallOnly: Set<IrValueId>;
1882
1888
  readonly integerValues: Set<IrValueId>;
1883
1889
  readonly integerBindings: Set<DeclarationId>;
1890
+ readonly float32: {
1891
+ readonly values: Set<IrValueId>;
1892
+ readonly bindings: Set<DeclarationId>;
1893
+ readonly arithmetic: Set<IrValueId>;
1894
+ };
1884
1895
  readonly typeQueryValues: Set<IrValueId>;
1885
1896
  readonly typeQueryBindings: Set<DeclarationId>;
1886
1897
  readonly typeQueryComparisons: Map<ComputeOperation, TypeQueryComparison>;
@@ -1939,6 +1950,8 @@ export declare const createEmitContext: (abi: CallableAbi | null, owner: Functio
1939
1950
  * something this does not.
1940
1951
  */
1941
1952
  export declare const storageTypeOf: (ctx: EmitContext, value: IrValueId, representation: Representation) => string;
1953
+ /** Whether a value's rendered text is a `float` -- the float32 census's twin of `isIntegerStorageValue`. */
1954
+ export declare const isFloatStorageValue: (ctx: EmitContext, value: IrValueId) => boolean;
1942
1955
  /**
1943
1956
  * Whether a value's rendered text is a `long long`, from every storage that
1944
1957
  * can make it one: the value census (`integerValues`), the cell a read names
@@ -5,7 +5,7 @@ import { noInstantiationFacts } from '../../ir/instantiation.js';
5
5
  import { observesEveryCallableIdentity } from '../../ir/callable-identity-demand.js';
6
6
  import { hostCallName, hostMemberOf, statedHostIntrinsicLength } from './host/host-members.js';
7
7
  import { representationKey } from '../../representation/model.js';
8
- import { cppBodyName, cppConstructName, cppNarrowedIntegerType, cppStringLiteral, cppStringViewLiteral, cppTypeOf, cppUndefinedIn, unitFunctionName } from './types.js';
8
+ import { cppBodyName, cppConstructName, cppNarrowedFloatType, cppNarrowedIntegerType, cppStringLiteral, cppStringViewLiteral, cppTypeOf, cppUndefinedIn, unitFunctionName } from './types.js';
9
9
  import { hostBuiltinFunctionIdentityText, hostClassValueText, hostFunctionValueText, hostJsonMemberValueText, hostMemberValueText } from './host/emit-host-value.js';
10
10
  import { createConversionNodes } from '../../conversion/nodes.js';
11
11
  import { createCppConversionRegistry } from './conversions.js';
@@ -103,6 +103,7 @@ conversions = null, nativeSelections = undefined, callableIdentityDemand = obser
103
103
  const numericCallOnly = new Set();
104
104
  const integerValues = new Set();
105
105
  const integerBindings = new Set();
106
+ const float32 = { values: new Set(), bindings: new Set(), arithmetic: new Set() };
106
107
  const typeQueryValues = new Set();
107
108
  const typeQueryBindings = new Set();
108
109
  const typeQueryComparisons = new Map();
@@ -244,6 +245,7 @@ conversions = null, nativeSelections = undefined, callableIdentityDemand = obser
244
245
  numericCallOnly,
245
246
  integerValues,
246
247
  integerBindings,
248
+ float32,
247
249
  typeQueryValues,
248
250
  typeQueryBindings,
249
251
  typeQueryComparisons,
@@ -285,6 +287,7 @@ conversions = null, nativeSelections = undefined, callableIdentityDemand = obser
285
287
  numericCallOnly,
286
288
  integerValues,
287
289
  integerBindings,
290
+ float32,
288
291
  typeQueryValues,
289
292
  typeQueryBindings,
290
293
  typeQueryComparisons,
@@ -335,7 +338,20 @@ conversions = null, nativeSelections = undefined, callableIdentityDemand = obser
335
338
  * An explicit spelling always wins: a caller that named the type knows
336
339
  * something this does not.
337
340
  */
338
- export const storageTypeOf = (ctx, value, representation) => ctx.typeQueryValues.has(value) ? 'gea::Value::Tag' : ctx.integerValues.has(value) ? cppNarrowedIntegerType : cppTypeOf(representation);
341
+ export const storageTypeOf = (ctx, value, representation) => ctx.typeQueryValues.has(value)
342
+ ? 'gea::Value::Tag'
343
+ : ctx.integerValues.has(value)
344
+ ? cppNarrowedIntegerType
345
+ : ctx.float32.values.has(value)
346
+ ? cppNarrowedFloatType
347
+ : cppTypeOf(representation);
348
+ /** Whether a value's rendered text is a `float` -- the float32 census's twin of `isIntegerStorageValue`. */
349
+ export const isFloatStorageValue = (ctx, value) => {
350
+ if (ctx.float32.values.has(value))
351
+ return true;
352
+ const declaration = ctx.bindingReadDeclarations.get(value);
353
+ return declaration !== undefined && ctx.float32.bindings.has(declaration) && !ctx.captures.isBoxed(declaration);
354
+ };
339
355
  /**
340
356
  * Whether a value's rendered text is a `long long`, from every storage that
341
357
  * can make it one: the value census (`integerValues`), the cell a read names
@@ -66,7 +66,7 @@ export const staticKeyTextOf = (ctx, key, contextDescription) => {
66
66
  throw createCppEmitBlockedError(`runtime-helper:computation:to-property-key:${contextDescription}`, `${contextDescription} has a key that was not produced by a "constant" operation in this body; this emitter has no dynamic-key path`);
67
67
  };
68
68
  import { dateMemberText } from './prototype/emit-prototype-date.js';
69
- import { arrayAccessText, presentElementText, keyedCollectionMemberText, iteratorMemberText, canonicalIndexLiteral, dictionaryPrototypeMemberRead, memberAccessOperator, positionalRecordArityText, promiseMemberText, keyedTableKeyText, emitRecordIndexSidecarStore, recordIndexSidecarReadText, reactiveRevisionText, scalarMemberText, stringMemberText, symbolMemberText, typedArrayAccessText } from './emit-carrier-members.js';
69
+ import { arrayAccessText, presentElementText, keyedCollectionMemberText, iteratorMemberText, canonicalIndexLiteral, dictionaryPrototypeMemberRead, memberAccessOperator, positionalRecordArityText, promiseMemberText, keyedTableKeyText, emitRecordIndexSidecarStore, recordIndexSidecarReadText, reactiveRevisionText, scalarMemberText, stringMemberText, symbolMemberText, typedArrayAccessText, integerTypedArrayElements } from './emit-carrier-members.js';
70
70
  import { arrayBufferAccessText, dataViewAccessText, sharedArrayBufferAccessText } from './emit-buffers.js';
71
71
  import { functionSourceReadClaimOf } from './function-source-reads.js';
72
72
  import { deferredCallableBuiltinReadClaimOf, recordWithIndexFieldClaimOf } from './property-read-claims.js';
@@ -411,6 +411,15 @@ const denseElementText = (ctx, operation) => {
411
411
  : arrayAccessText(ctx, operation.receiver, operation.key, operation.result);
412
412
  if (general === null || general === '')
413
413
  return null;
414
+ // A `float` result (`ir/floats.ts`) reads a float32 element as the `float`
415
+ // it is: both halves in `float`, so the fast half is a load and no
416
+ // conversion through `double` -- a software routine on a core whose FPU is
417
+ // single-precision only.
418
+ const receiver = operation.receiver.representation;
419
+ if (receiver.kind === 'typed-array' && receiver.element === 'float32' && ctx.float32.values.has(operation.result.id))
420
+ return `(${dense.flag} ? gea::TypedArray<float>::readInBounds(${dense.pointer}, ${dense.index}) : static_cast<float>(${general}))`;
421
+ if (receiver.kind === 'typed-array' && integerTypedArrayElements.has(receiver.element) && ctx.integerValues.has(operation.result.id))
422
+ return `(${dense.flag} ? gea::TypedArray<${cppScalarType(receiver.element)}>::readIntegerInBounds(${dense.pointer}, ${dense.index}) : static_cast<long long>(${general}))`;
414
423
  // The window's flag is a proof of presence, so the fast half is written in
415
424
  // the result's carrier the same way the general half's guarded arm is --
416
425
  // see `presentElementText`. Without it the two arms are a bare element and
@@ -1589,11 +1598,15 @@ const emitFieldStoreLines = (ctx, lines, operation, label) => {
1589
1598
  }
1590
1599
  const dense = denseCellText(ctx, operation);
1591
1600
  const value = operandText(ctx, operation.value);
1592
- const writer = isIntegerStorageValue(ctx, operation.key.value) ? 'setElementAtIndex' : 'setElement';
1601
+ const integerKey = isIntegerStorageValue(ctx, operation.key.value);
1602
+ // An integer value stores its low bits (or itself, rounded once, into a
1603
+ // float view) without the `double` modulo `setElementAtIndex` performs.
1604
+ const integerValue = isIntegerStorageValue(ctx, operation.value.value);
1605
+ const writer = integerKey ? (integerValue ? 'setElementIntegerAtIndex' : 'setElementAtIndex') : 'setElement';
1593
1606
  const general = `${typedArrayReceiver}->${writer}(${operandText(ctx, operation.key)}, ${value});`;
1594
1607
  lines.push(dense === null
1595
1608
  ? general
1596
- : `if (${dense.flag}) gea::TypedArray<${cppScalarType(operation.receiver.representation.element)}>::writeInBounds(${dense.pointer}, ${dense.index}, ${value}); else ${general}`);
1609
+ : `if (${dense.flag}) gea::TypedArray<${cppScalarType(operation.receiver.representation.element)}>::${integerValue ? 'writeIntegerInBounds' : 'writeInBounds'}(${dense.pointer}, ${dense.index}, ${value}); else ${general}`);
1597
1610
  finishTypedArrayStore();
1598
1611
  return;
1599
1612
  }
@@ -17,7 +17,7 @@ import { allOperationsOf } from '../../ir/model.js';
17
17
  import { operandsOfIrOperation, resultOfIrOperation } from '../../ir/queries.js';
18
18
  import { namesMoreThanOnce } from './evaluated-once.js';
19
19
  import { isOpenDocument, representationKey } from '../../representation/model.js';
20
- import { cppFormalName, cppReceiverName, createCppEmitBlockedError, createEmitContext, defineValue, defineValueAlias, directCalleesOf, emptyCaptureIndex, isIntegerStorageValue, isCppEmitBlockedError, operandText, storageTypeOf, cppThunkEntryText, sealFactFieldsForRender, suspendsInPlace } from './emit-context.js';
20
+ import { cppFormalName, cppReceiverName, createCppEmitBlockedError, createEmitContext, defineValue, defineValueAlias, directCalleesOf, emptyCaptureIndex, isFloatStorageValue, isIntegerStorageValue, isCppEmitBlockedError, operandText, storageTypeOf, cppThunkEntryText, sealFactFieldsForRender, suspendsInPlace } from './emit-context.js';
21
21
  import { hostMemberReadsOf } from './host/emit-host-properties.js';
22
22
  import { hostNamespaceReadsOf } from './host-namespace-reads.js';
23
23
  import { functionSourceReadsOf } from './function-source-reads.js';
@@ -833,6 +833,23 @@ const emitCompute = (ctx, lines, operation) => {
833
833
  throw createCppEmitBlockedError(`runtime-helper:computation:binary:${operation.operator}:${first.representation.kind}`, `binary "${operation.operator}" on a "${first.representation.kind}" carrier has no C++ spelling in this emitter`);
834
834
  }
835
835
  const name = defineValue(ctx, operation.result);
836
+ // `ir/floats.ts`: an operation every use of which rounds to float32 is the
837
+ // single-precision operation itself; every other operator promotes a `float`
838
+ // operand back to the double the Number is, or two of them would compute in
839
+ // single precision where ECMA-262 computes in double.
840
+ if (ctx.float32.arithmetic.has(operation.result.id) && spelling.kind === 'infix') {
841
+ // A narrowed integer operand is one `ir/floats.ts` bounded by 2^24, so it
842
+ // fits an int32: converting from that is one instruction, from a
843
+ // `long long` a library call on a 32-bit core.
844
+ const single = (operand) => isIntegerStorageValue(ctx, operand.value)
845
+ ? `static_cast<float>(static_cast<std::int32_t>(${operandText(ctx, operand)}))`
846
+ : `static_cast<float>(${operandText(ctx, operand)})`;
847
+ const computed = `(${single(first)} ${spelling.text} ${single(second)})`;
848
+ // A product is the half of a multiply-add GCC would fuse (`float32Product`).
849
+ lines.push(`${name} = ${spelling.text === '*' ? `gea::float32Product${computed}` : computed};`);
850
+ return;
851
+ }
852
+ const promotedText = (operand) => isFloatStorageValue(ctx, operand.value) ? `static_cast<double>(${operandText(ctx, operand)})` : operandText(ctx, operand);
836
853
  const integral = ctx.integerValues.has(first.value) && ctx.integerValues.has(second.value);
837
854
  // `/` is the one arithmetic operator whose C++ meaning CHANGES when both
838
855
  // operands are integers: `7 / 2` would become 3 rather than 3.5, so two
@@ -841,8 +858,8 @@ const emitCompute = (ctx, lines, operation) => {
841
858
  // remainder is the same answer without the fmod round trip, under its own
842
859
  // name rather than an overload (a mixed call would make a pair ambiguous).
843
860
  const widenForDivision = integral && operation.operator === '/';
844
- const left = widenForDivision ? `static_cast<double>(${operandText(ctx, first)})` : operandText(ctx, first);
845
- const right = widenForDivision ? `static_cast<double>(${operandText(ctx, second)})` : operandText(ctx, second);
861
+ const left = widenForDivision ? `static_cast<double>(${operandText(ctx, first)})` : promotedText(first);
862
+ const right = widenForDivision ? `static_cast<double>(${operandText(ctx, second)})` : promotedText(second);
846
863
  const bounded = integerBoundedComparison(ctx.integerValues, ctx.loopInvariantValues, operation, first, second, left, right);
847
864
  if (bounded !== null) {
848
865
  lines.push(`${name} = ${bounded};`);
@@ -2536,6 +2553,15 @@ virtualDispatch = new Map(), narrowedStorage = { reads: new Map(), integral: new
2536
2553
  !ctx.captures.isBoxed(declaration) &&
2537
2554
  !capturedQueryCells.has(declaration));
2538
2555
  },
2556
+ float32Cell: (declaration) => {
2557
+ const placement = ctx.placements.get(declaration);
2558
+ return (placement?.storage.kind === 'local' &&
2559
+ placement.storage.owner === body.sourceOwner &&
2560
+ placement.representation?.kind === 'scalar' &&
2561
+ placement.representation.domain === 'number' &&
2562
+ !ctx.captures.isBoxed(declaration) &&
2563
+ !capturedQueryCells.has(declaration));
2564
+ },
2539
2565
  spellConstants: () => spellConstants(ctx, body),
2540
2566
  formalStorage: (settled) => {
2541
2567
  // The collectors below read these off the context, so they are published
@@ -2570,6 +2596,12 @@ virtualDispatch = new Map(), narrowedStorage = { reads: new Map(), integral: new
2570
2596
  prepass.integerValues.add(value);
2571
2597
  for (const declaration of settled.integerBindings)
2572
2598
  prepass.integerBindings.add(declaration);
2599
+ for (const value of settled.float32.values)
2600
+ prepass.float32.values.add(value);
2601
+ for (const declaration of settled.float32.bindings)
2602
+ prepass.float32.bindings.add(declaration);
2603
+ for (const value of settled.float32.arithmetic)
2604
+ prepass.float32.arithmetic.add(value);
2573
2605
  for (const [value, form] of settled.remainderForms)
2574
2606
  prepass.remainderForms.set(value, form);
2575
2607
  for (const value of settled.roundingArithmetic)
@@ -2610,7 +2642,7 @@ virtualDispatch = new Map(), narrowedStorage = { reads: new Map(), integral: new
2610
2642
  collectDirectBindingSinks(prepass, body, hoists.relocated);
2611
2643
  // After the hoists, because a window's own bound is often the loop-invariant
2612
2644
  // read they relocate, and a relocated value is one this may name.
2613
- admitDenseWindows(ctx, prepass, body);
2645
+ admitDenseWindows(ctx, prepass, body, hoists);
2614
2646
  const isSingleBlock = body.blockOrder.length === 1;
2615
2647
  const orderLabels = isSingleBlock ? new Map() : blockLabelsOf(body.blockOrder);
2616
2648
  const owner = sectionOwnerOf(body);
@@ -1,7 +1,7 @@
1
1
  import { usesRealmStorage } from '../realm-storage.js';
2
2
  import { isOpenDocument, representationKey } from '../../../representation/model.js';
3
3
  import { hostMemberTemplateOf, isArrayConstantOf } from '../../../representation/host-templates.js';
4
- import { createCppEmitBlockedError, internSymbolKey, operandText, paddedArguments } from '../emit-context.js';
4
+ import { createCppEmitBlockedError, internSymbolKey, isFloatStorageValue, operandText, paddedArguments } from '../emit-context.js';
5
5
  import { consoleArgumentsText, toStringRefusal, toStringText, toStringTextOver } from '../emit-tostring.js';
6
6
  import { classToNumberText, classToPrimitiveOf, toNumberRefusal, toNumberText } from '../emit-tonumber.js';
7
7
  import { booleanTestText } from '../emit-presence.js';
@@ -1432,6 +1432,15 @@ export const hostCallText = (ctx, operation) => {
1432
1432
  !operation.arguments.every((argument) => argument.representation.kind === 'scalar' && argument.representation.domain === 'number')) {
1433
1433
  throw createCppEmitBlockedError(`host-invocation:${read.protocol}.${read.member}`, 'a deferred numeric host call disagrees with its fixed numeric argument frame');
1434
1434
  }
1435
+ // `Math.fround` of a value `ir/floats.ts` already holds in `float` is that
1436
+ // value: no double to round, and no software double conversion on a core
1437
+ // whose FPU is single-precision only.
1438
+ const only = operation.arguments[0];
1439
+ if (read.protocol === 'Math' &&
1440
+ read.member === 'fround' &&
1441
+ only !== undefined &&
1442
+ (isFloatStorageValue(ctx, only.value) || ctx.float32.arithmetic.has(only.value)))
1443
+ return `static_cast<float>(${operandText(ctx, only)})`;
1435
1444
  return fillHostTemplate(host.numericDirectCall.emit, receiverText, operation.arguments.map((argument) => `static_cast<double>(${operandText(ctx, argument)})`));
1436
1445
  }
1437
1446
  if (!host || host.kind !== 'method') {