@geastack/compiler 1.0.36 → 1.0.37

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,7 +1,7 @@
1
1
  import type { DeclarationId, FunctionId, IrValueId } from '../identity/ids.js';
2
- import type { Representation } from '../representation/model.js';
2
+ import { type Representation } from '../representation/model.js';
3
3
  import type { ClassConstruction } from './instantiation.js';
4
- import type { IrBody } from './model.js';
4
+ import { type IrBody } from './model.js';
5
5
  import type { ReflectionDemand } from './reflection-demand.js';
6
6
  /**
7
7
  * Class fields the program writes only while constructing the object that
@@ -90,3 +90,36 @@ export declare const stableReceiversOf: (body: IrBody, receivers: ReadonlySet<Ir
90
90
  export declare const stableFieldReadsOf: (body: IrBody, receivers: ReadonlySet<IrValueId>, fields: ConstructionOnlyFields, integrity: {
91
91
  readonly restricts: (representation: Representation) => boolean;
92
92
  }, dying: ReadonlySet<IrValueId>) => ReadonlySet<IrValueId>;
93
+ /**
94
+ * Cells that may name the stable field read they are initialized with,
95
+ * instead of holding a counted copy of it.
96
+ *
97
+ * `const left = node.left` stores the read into `left`'s cell, and the store
98
+ * is the retain the alias of the read itself (`stableFieldReadsOf`) was there
99
+ * to avoid: `count(node)` paid a retain and a release per child per node
100
+ * walked, a quarter of a binary-tree run. The field holds one value for the
101
+ * whole call, so when the cell does too, every read of the cell may spell the
102
+ * field.
103
+ *
104
+ * The cell holds one value when the body writes it exactly once, with that
105
+ * read, and that write comes before every read of the cell -- dominating it,
106
+ * and earlier in `blockOrder`, so the writer has decided before any reader
107
+ * renders. Nothing else may name the cell (`admits`: a cell another frame or a
108
+ * closure reaches is read by code this body does not render), and each read
109
+ * must want the field's own carrier. A body with exception or iterator-close
110
+ * regions keeps its cells: the dominator tree does not carry those edges. A
111
+ * suspending body keeps them too, for the reason `suspensionFreeReadsOf` gives.
112
+ */
113
+ export declare const stableFieldCellsOf: (body: IrBody, stableReads: ReadonlySet<IrValueId>, admits: (declaration: DeclarationId) => boolean) => ReadonlySet<DeclarationId>;
114
+ /**
115
+ * `stableFieldReadsOf` and `stableFieldCellsOf` together. A read whose one use
116
+ * is the write into its cell is dying -- the write moves it in -- and so is no
117
+ * stable read on its own; it becomes one when that cell is admitted, because
118
+ * an admitted cell's write stores nothing and the move never happens.
119
+ */
120
+ export declare const stableFieldReadsAndCellsOf: (body: IrBody, receivers: ReadonlySet<IrValueId>, fields: ConstructionOnlyFields, integrity: {
121
+ readonly restricts: (representation: Representation) => boolean;
122
+ }, dying: ReadonlySet<IrValueId>, admits: (declaration: DeclarationId) => boolean) => {
123
+ readonly reads: ReadonlySet<IrValueId>;
124
+ readonly cells: ReadonlySet<DeclarationId>;
125
+ };
@@ -1,4 +1,7 @@
1
+ import { representationKey } from '../representation/model.js';
1
2
  import { stringConstantsOf } from './dead-values.js';
3
+ import { dominatorTreeOf } from './dominance.js';
4
+ import { allOperationsOf } from './model.js';
2
5
  import { operandsOfIrOperation, resultOfIrOperation } from './queries.js';
3
6
  const everyKey = Symbol('every key');
4
7
  const unkeyableKinds = new Set(['dynamic', 'unresolved', 'native-handle', 'proxy-object', 'carrier']);
@@ -295,3 +298,100 @@ export const stableFieldReadsOf = (body, receivers, fields, integrity, dying) =>
295
298
  }
296
299
  return suspensionFreeReadsOf(body, candidates);
297
300
  };
301
+ /**
302
+ * Cells that may name the stable field read they are initialized with,
303
+ * instead of holding a counted copy of it.
304
+ *
305
+ * `const left = node.left` stores the read into `left`'s cell, and the store
306
+ * is the retain the alias of the read itself (`stableFieldReadsOf`) was there
307
+ * to avoid: `count(node)` paid a retain and a release per child per node
308
+ * walked, a quarter of a binary-tree run. The field holds one value for the
309
+ * whole call, so when the cell does too, every read of the cell may spell the
310
+ * field.
311
+ *
312
+ * The cell holds one value when the body writes it exactly once, with that
313
+ * read, and that write comes before every read of the cell -- dominating it,
314
+ * and earlier in `blockOrder`, so the writer has decided before any reader
315
+ * renders. Nothing else may name the cell (`admits`: a cell another frame or a
316
+ * closure reaches is read by code this body does not render), and each read
317
+ * must want the field's own carrier. A body with exception or iterator-close
318
+ * regions keeps its cells: the dominator tree does not carry those edges. A
319
+ * suspending body keeps them too, for the reason `suspensionFreeReadsOf` gives.
320
+ */
321
+ export const stableFieldCellsOf = (body, stableReads, admits) => {
322
+ if (stableReads.size === 0 || body.tryRegions.length > 0 || (body.iteratorCloseRegions?.length ?? 0) > 0)
323
+ return new Set();
324
+ const writes = new Map();
325
+ const reads = new Map();
326
+ const refused = new Set();
327
+ for (const [block, contents] of body.blocks) {
328
+ for (const [index, operation] of allOperationsOf(contents).entries()) {
329
+ if (operation.kind === 'await' || operation.kind === 'yield')
330
+ return new Set();
331
+ if (operation.kind === 'binding-write') {
332
+ const sites = writes.get(operation.declaration) ?? [];
333
+ sites.push({ block, index, value: operation.value.value, representation: operation.value.representation });
334
+ writes.set(operation.declaration, sites);
335
+ }
336
+ else if (operation.kind === 'binding-read') {
337
+ const sites = reads.get(operation.declaration) ?? [];
338
+ sites.push({ block, index, representation: operation.result.representation });
339
+ reads.set(operation.declaration, sites);
340
+ }
341
+ else if ('declaration' in operation && typeof operation.declaration === 'string') {
342
+ refused.add(operation.declaration);
343
+ }
344
+ }
345
+ }
346
+ const order = new Map(body.blockOrder.map((block, position) => [block, position]));
347
+ const dominance = dominatorTreeOf(body);
348
+ const cells = new Set();
349
+ for (const [declaration, sites] of writes) {
350
+ const write = sites[0];
351
+ if (sites.length !== 1 || write === undefined || refused.has(declaration) || !stableReads.has(write.value))
352
+ continue;
353
+ if (!admits(declaration))
354
+ continue;
355
+ const key = representationKey(write.representation);
356
+ const writeOrder = order.get(write.block);
357
+ if (writeOrder === undefined)
358
+ continue;
359
+ const before = (read) => {
360
+ if (read.block === write.block)
361
+ return write.index < read.index;
362
+ const readOrder = order.get(read.block);
363
+ return readOrder !== undefined && writeOrder < readOrder && dominance.dominates(write.block, read.block);
364
+ };
365
+ if ((reads.get(declaration) ?? []).every((read) => before(read) && representationKey(read.representation) === key))
366
+ cells.add(declaration);
367
+ }
368
+ return cells;
369
+ };
370
+ /**
371
+ * `stableFieldReadsOf` and `stableFieldCellsOf` together. A read whose one use
372
+ * is the write into its cell is dying -- the write moves it in -- and so is no
373
+ * stable read on its own; it becomes one when that cell is admitted, because
374
+ * an admitted cell's write stores nothing and the move never happens.
375
+ */
376
+ export const stableFieldReadsAndCellsOf = (body, receivers, fields, integrity, dying, admits) => {
377
+ const reads = stableFieldReadsOf(body, receivers, fields, integrity, dying);
378
+ const uses = new Map();
379
+ const written = new Map();
380
+ for (const block of body.blocks.values())
381
+ for (const operation of allOperationsOf(block)) {
382
+ for (const operand of operandsOfIrOperation(operation))
383
+ uses.set(operand.value, (uses.get(operand.value) ?? 0) + 1);
384
+ if (operation.kind === 'binding-write')
385
+ written.set(operation.value.value, operation.declaration);
386
+ }
387
+ const intoCell = (value) => written.has(value) && uses.get(value) === 1;
388
+ const candidates = stableFieldReadsOf(body, receivers, fields, integrity, new Set([...dying].filter((value) => !intoCell(value))));
389
+ const cells = stableFieldCellsOf(body, candidates, admits);
390
+ const all = new Set(reads);
391
+ for (const value of candidates) {
392
+ const declaration = written.get(value);
393
+ if (declaration !== undefined && intoCell(value) && cells.has(declaration))
394
+ all.add(value);
395
+ }
396
+ return { reads: all, cells };
397
+ };
@@ -113,6 +113,13 @@ const structuralUnionLoadText = (ctx, held, read, text) => {
113
113
  * knows is wrong.
114
114
  */
115
115
  export const emitBindingRead = (ctx, lines, operation) => {
116
+ // A cell that names a stable field (`EmitContext.stableFieldCells`). Const,
117
+ // so a consumer that moves from it copies instead of emptying the field.
118
+ const fieldCell = ctx.stableFieldCellTexts.get(operation.declaration);
119
+ if (fieldCell !== undefined) {
120
+ defineValueAlias(ctx, operation.result, `std::as_const(${fieldCell})`);
121
+ return;
122
+ }
116
123
  // A char-code buffer is read by naming the string, never by copying it: a push appends to the cell itself.
117
124
  if (ctx.charCodeBuffers.reads.has(operation.result.id)) {
118
125
  defineValueAlias(ctx, operation.result, cellValueText(bindingReference(ctx, operation.declaration, 'a char-code buffer read')));
@@ -435,6 +442,12 @@ export const emitBindingWrite = (ctx, lines, operation) => {
435
442
  // `gea_arg_0 = gea_arg_0` is the copy this exists to remove.
436
443
  if (ctx.formalCells.has(operation.declaration))
437
444
  return;
445
+ // The one write of a cell that names a stable field stores nothing: the
446
+ // field already holds the value for every read that follows.
447
+ if (ctx.stableFieldCells.has(operation.declaration) && ctx.aliasedStableFieldReads.has(operation.value.value)) {
448
+ ctx.stableFieldCellTexts.set(operation.declaration, operandText(ctx, operation.value));
449
+ return;
450
+ }
438
451
  // The one write that makes a cell a host-method alias stores nothing: the
439
452
  // value is a host member with no C++ spelling of its own, and every read of
440
453
  // the cell names that member directly (`emitBindingRead`).
@@ -709,6 +709,8 @@ export interface EmitBodyFacts {
709
709
  readonly stableCellReads: ReadonlySet<IrValueId>;
710
710
  /** See `EmitContext.stableFieldReads`. */
711
711
  readonly stableFieldReads: ReadonlySet<IrValueId>;
712
+ /** See `EmitContext.stableFieldCells`. */
713
+ readonly stableFieldCells: ReadonlySet<DeclarationId>;
712
714
  /** See `EmitContext.constructorOf`. */
713
715
  readonly constructorOf: {
714
716
  readonly layout: ClassLayout;
@@ -1540,6 +1542,17 @@ export interface EmitContext {
1540
1542
  * so the read renders as the field itself rather than a counted copy.
1541
1543
  */
1542
1544
  readonly stableFieldReads: ReadonlySet<IrValueId>;
1545
+ /**
1546
+ * Cells written once with a stable field read and read only after it
1547
+ * (`ir/construction-only-fields.ts`'s `stableFieldCellsOf`). When that read
1548
+ * did render as the field (`aliasedStableFieldReads`), the write stores
1549
+ * nothing and every read names the field (`stableFieldCellTexts`).
1550
+ */
1551
+ readonly stableFieldCells: ReadonlySet<DeclarationId>;
1552
+ /** The stable field reads that rendered as the field itself. Filled as the body renders. */
1553
+ readonly aliasedStableFieldReads: Set<IrValueId>;
1554
+ /** The field text each admitted cell names, set by its one write before any read renders. */
1555
+ readonly stableFieldCellTexts: Map<DeclarationId, string>;
1543
1556
  /** Dominating native length results, selected by the IR reuse proof. Settled the same way as `hoistedResults`. */
1544
1557
  readonly reusedStringLengths: ReadonlyMap<IrValueId, IrOperand>;
1545
1558
  /** Withheld values whose single reader is a call, and which therefore reach exactly one operand position -- see `emit.ts`'s `consumedByCall`. Settled the same way as `hoistedResults`. */
@@ -264,6 +264,9 @@ conversions = null, nativeSelections = undefined, callableIdentityDemand = obser
264
264
  deferrable,
265
265
  stableCellReads: bodyFacts.stableCellReads,
266
266
  stableFieldReads: bodyFacts.stableFieldReads,
267
+ stableFieldCells: bodyFacts.stableFieldCells,
268
+ aliasedStableFieldReads: new Set(),
269
+ stableFieldCellTexts: new Map(),
267
270
  reusedStringLengths,
268
271
  callArgumentOnly,
269
272
  classTableRoots: bodyFacts.classTableRoots,
@@ -1080,6 +1083,12 @@ const renderMutableEmitContextFields = new Set([
1080
1083
  // The local that GetIterator names for its once-only Get(next). IteratorNext
1081
1084
  // reads that name; method identity and frame remain the certified IR's facts.
1082
1085
  'protocolNextMethods',
1086
+ // Text again, by the same test: WHICH cells may name their field is the
1087
+ // prepass's `stableFieldCells`. Whether the one write's value printed as the
1088
+ // field itself is decided where `emitGet` spells it, so the write records
1089
+ // that, and the field text its later reads print in place of the cell.
1090
+ 'aliasedStableFieldReads',
1091
+ 'stableFieldCellTexts',
1083
1092
  // A wrapped dense window's subscript companion, minted and declared beside
1084
1093
  // the read that needed it (`denseRemainderCompanion`). WHICH accesses a
1085
1094
  // window admits is `admitDenseWindows`' prepass answer; this is only what
@@ -1025,6 +1025,7 @@ export const emitGet = (ctx, lines, operation) => {
1025
1025
  operation.result.representation.kind !== 'scalar' &&
1026
1026
  read === plainFieldReadText(ctx, operation, fieldName)) {
1027
1027
  defineValueAlias(ctx, operation.result, read);
1028
+ ctx.aliasedStableFieldReads.add(operation.result.id);
1028
1029
  return;
1029
1030
  }
1030
1031
  const name = defineValue(ctx, operation.result);
@@ -1204,6 +1205,14 @@ const fixedFieldPresenceText = (ctx, receiver, fieldName) => {
1204
1205
  representation.kind !== 'native-record-ref' &&
1205
1206
  representation.kind !== 'class-ref')
1206
1207
  return null;
1208
+ // A required field's bit is a `static` that is always `true` when nothing in
1209
+ // the program can delete, freeze or redefine a field (`records.ts`, on
1210
+ // `ctx.fixedFieldStateConstant`), so testing it only turns a member load into
1211
+ // a fresh value, which a stable field read may not alias. The per-carrier
1212
+ // proof is not enough here: its bit is an instance member a decoder may
1213
+ // leave unset.
1214
+ if (field.required && ctx.fixedFieldStateConstant)
1215
+ return null;
1207
1216
  return `${constructorViewReceiverText(ctx, receiver, fieldName, operandText(ctx, receiver))}${memberAccessOperator(representation.ownership)}${cppRecordFieldPresenceName(fieldName)}`;
1208
1217
  };
1209
1218
  /** A native slot is read through the exact conversion lowering certified. */
@@ -12,7 +12,7 @@ import { redundantPureConversionsOf } from '../../ir/pure-conversion-reuse.js';
12
12
  import { owningConversionInputText } from './owning-conversion-input.js';
13
13
  import { boxedValueText } from './emit-dynamic-properties.js';
14
14
  import { stableCellReadsOf } from '../../ir/stable-cell-reads.js';
15
- import { noConstructionOnlyFields, stableFieldReadsOf, stableReceiversOf } from '../../ir/construction-only-fields.js';
15
+ import { noConstructionOnlyFields, stableFieldReadsAndCellsOf, stableReceiversOf } from '../../ir/construction-only-fields.js';
16
16
  import { DyingArgumentSet, dyingTransferUsesOf, receiverRenamesOf, ownedDyingMergeInputsOf, ownedDyingValuesOf, ownedFormalInputsOf, transfersFormalConversion } from '../../ir/transfer.js';
17
17
  import { classLayoutsConstructedBy, constructedBaseOf } from '../../projection/classes.js';
18
18
  import { recordFieldsOfShape } from '../../projection/fields.js';
@@ -2538,6 +2538,17 @@ virtualDispatch = new Map(), narrowedStorage = { reads: new Map(), integral: new
2538
2538
  // fields below, whose collectors genuinely do need one.
2539
2539
  const functionSources = functionSourceReadsOf(origins.staticKeyTexts, body);
2540
2540
  const directCalleeFacts = directCalleesOf(body, abiOfCallable);
2541
+ // Only a counted handle: a cell of any other carrier is read by renderers
2542
+ // (string appends, array and JSON fills) that name its storage directly.
2543
+ const { reads: stableFieldReads, cells: stableFieldCells } = stableFieldReadsAndCellsOf(body, stableReceiversOf(body, receiverValues, borrowedFormals, bindingWriteCounts, (declaration) => captures.isBoxed(declaration)), constructionOnlyFields, nativeIntegrityRestricted, bodyDyingArguments, (declaration) => {
2544
+ const placement = placements.get(declaration);
2545
+ if (placement?.storage.kind !== 'local' || placement.storage.owner !== body.sourceOwner)
2546
+ return false;
2547
+ if (captures.isBoxed(declaration) || captures.isCaptured(declaration))
2548
+ return false;
2549
+ const held = placement.representation;
2550
+ return held?.kind === 'class-ref' || (held?.kind === 'optional' && held.payload.kind === 'class-ref');
2551
+ });
2541
2552
  const bodyFacts = {
2542
2553
  generatorBody: body.generator === true,
2543
2554
  asyncCoroutineBody: isAsyncCoroutineBody(body),
@@ -2545,7 +2556,8 @@ virtualDispatch = new Map(), narrowedStorage = { reads: new Map(), integral: new
2545
2556
  receiverValues,
2546
2557
  bindingWriteCounts,
2547
2558
  stableCellReads: stableCellReadsOf(body, (declaration) => placements.get(declaration)?.storage.kind === 'local'),
2548
- stableFieldReads: stableFieldReadsOf(body, stableReceiversOf(body, receiverValues, borrowedFormals, bindingWriteCounts, (declaration) => captures.isBoxed(declaration)), constructionOnlyFields, nativeIntegrityRestricted, bodyDyingArguments),
2559
+ stableFieldReads,
2560
+ stableFieldCells,
2549
2561
  constructorOf,
2550
2562
  ownedDyingValues,
2551
2563
  transferDyingValues,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geastack/compiler",
3
- "version": "1.0.36",
3
+ "version": "1.0.37",
4
4
  "description": "The geastack TypeScript-to-C++ compiler: one semantic spine, no source-shaped authority, no boxing of statically typed values.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -5030,10 +5030,18 @@ struct Ref : detail::RefStorage {
5030
5030
  * construction installs and every later one only confirms. A parallel region
5031
5031
  * can make two tasks the first at once, so the confirmation is an acquire
5032
5032
  * load and the install happens once, under a lock.
5033
+ *
5034
+ * Only the confirmation is inline. With the lock in the same body it was a
5035
+ * call per construction -- 5% of a binary-tree build that confirmed the
5036
+ * same pointer 52 million times.
5033
5037
  */
5034
- static void installShared(Ref& slot, T* object) {
5038
+ [[gnu::always_inline]] static void installShared(Ref& slot, T* object) {
5039
+ if (std::atomic_ref<void*>(slot.erased_).load(std::memory_order_acquire) == object) [[likely]] return;
5040
+ installSharedSlow(slot, object);
5041
+ }
5042
+
5043
+ [[gnu::noinline]] static void installSharedSlow(Ref& slot, T* object) {
5035
5044
  std::atomic_ref<void*> cell(slot.erased_);
5036
- if (cell.load(std::memory_order_acquire) == object) return;
5037
5045
  static std::mutex mutex;
5038
5046
  std::lock_guard<std::mutex> lock(mutex);
5039
5047
  if (cell.load(std::memory_order_relaxed) == object) return;