diff --git a/docs/own-readiness.md b/docs/own-readiness.md index 73809b082..97c3542cd 100644 --- a/docs/own-readiness.md +++ b/docs/own-readiness.md @@ -84,6 +84,10 @@ The rejections, by message: | 5 | a global's value lent to a call that may release it | Conservative | | 42 | 22 other messages, one to five files each | Mixed | +Measured again on 2026-11-16 after spec 86 (values merged by `?:`, constant merges, an optional record's +field read): of 890 files that compile under gc, 724 compile under own; "takes a second reference" +dropped from 24 files to 19 and "merged from several branches" from 7 to 5. No file went the other way. + About 50 of the 175 say in the message that the compiler cannot prove something yet. The rest are the model's rules; some of those are the single-owner design working as intended, and some are the analysis being more careful than the program needs. @@ -109,6 +113,10 @@ Probed one by one under the JIT: | `new Map()`, `filter` over class instances | Rejected by design; `Shared` | | Swap through a local: `let t = a[i]; a[i] = a[j]; a[j] = t` | Rejected by design; `[a[i], a[j]] = [a[j], a[i]]` | | `x ??= new B()` on a parameter | Rejected ("merged from several branches") | +| `return set ? n : undefined`, `h.n = set ? n : null` of an owned local | Compiles and runs: `n` moves on the way that chooses it, and is released on the other | +| `return first ? shared : other` of globals never reassigned, `c ? 1 : "one"` | Compiles and runs: the merge owns nothing | +| `let p: Node \| null = on() ? mk(3) : null` at the top level | Compiles and runs | +| `return set ? n : m` of two owned locals | Rejected ("takes a second reference"): an `arith.select` has no edge to release the other on | | A closure that assigns a parameter it captures | Rejected | | `m.forEach((v, k) => { total += v; })` on a `Map` or a `Set` | Compiles and runs | | `m.forEach((v, k) => { names.push(k); })` | Compiles and runs: a callback declaring fewer parameters than `forEach` passes is given a copy of a string it keeps | diff --git a/tslang/docs/superpowers/specs/2026-09-24-own-memory-model-design.md b/tslang/docs/superpowers/specs/2026-09-24-own-memory-model-design.md index 029202cab..95fc9cc96 100644 --- a/tslang/docs/superpowers/specs/2026-09-24-own-memory-model-design.md +++ b/tslang/docs/superpowers/specs/2026-09-24-own-memory-model-design.md @@ -5985,3 +5985,30 @@ later cast failed to verify. With no type argument `T` is now the target's type target makes a WeakRef whose `deref()` gives undefined (copy, release and deref test for null). Tests: `own_callback_fewer_params` (own, rc, gc, none), `00weakref_narrowed` (own, gc, none). + +## 86. Merges: a moved local, constants, an optional record's field, 2026-11-16 + +Readiness item 3, "not yet" messages; four shapes of the corpus. + +**A local moved through a merge.** `return set ? n : undefined` (or a store of it) of an owned local: +the branch that carries `n` into the merge's block argument is its taker, and rc's one retain of the +merged value in its block is the reference it moves into (`mergeRetainOf`, which `takerAcquires` +accepts and `movesOf` erases). The release of `n` on the way that does not choose it goes on that edge +(TSLANG 81, `valueUnmovedEdges`). Only when every way into the merge brings null, undefined or a fresh +value: a borrow brought in (`set ? n : h.k`) would be given an owner, and stays refused. A use of `n` +after the merge is a use after a move. An `arith.select` (`set ? n : m` of two locals) has no edge to +release the other on, and stays refused. + +**A merge of what nothing owns.** Every way in brings a literal, null, an immortal global's read +(spec 25) or such a merge: the merged value owns nothing, and a retain of it takes nothing +(`mergeOwnsNothing`): `return first ? shared : other`, `typeof text === "string" ? 1 : "one"`. + +**An optional record's field read.** `object(true)?.v == "x"`: the field of the record merged with +undefined and only read is a read of the record (`fieldOnlyRead` follows the merge), not a taker of +the field, which had made it "a second reference". + +**A global initializer.** `let pick: Node | null = on() ? mk(3) : null`: null seen through its cast is +constant data (`isConstantData`), and a global initializer's retain of constant data takes nothing. + +Tests: `own_merge_moves_local`, `own_merge_of_constants`, `own_optional_literal_result`, +`own_global_merge_initializer` (own, rc, gc, none). Corpus: 717 -> 724 of 890 compile under own. diff --git a/tslang/lib/TypeScript/OwnershipFacts.h b/tslang/lib/TypeScript/OwnershipFacts.h index fdd61eea6..ddc065f3f 100644 --- a/tslang/lib/TypeScript/OwnershipFacts.h +++ b/tslang/lib/TypeScript/OwnershipFacts.h @@ -1893,6 +1893,20 @@ inline bool isConstantData(mlir::Value value) return true; } + // null or undefined seen as what may hold a block (`on() ? mk(3) : null` as a `Node | null`): + // it holds none + auto root = value; + while (auto castOp = root.getDefiningOp()) + { + root = castOp.getIn(); + } + + if (root.getDefiningOp() || root.getDefiningOp() || + root.getDefiningOp()) + { + return true; + } + // a function, which a `ts.SymbolRef` names, seen as a function value: it has no capture box. // Seen through its views too - that function value given as a `(() => void) | null` if (auto castOp = mlir::dyn_cast(def)) diff --git a/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp b/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp index f03183b9e..952a7c5d6 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp @@ -879,21 +879,43 @@ namespace own_inference return true; } - forEachUse(extract->getResult(0), [&](mlir::Operation *user, mlir::Value used) { - if (mlir::isa(user)) - { - onlyRead = fieldOnlyRead(user, reads) && onlyRead; - return; - } + // ...and through a merge of branches that is only read: `o?.v == "x"` merges the field with + // undefined, and what reads the merge reads the field + llvm::SmallVector values{extract->getResult(0)}; + llvm::SmallPtrSet seen{extract->getResult(0)}; + while (!values.empty() && onlyRead) + { + forEachUse(values.pop_back_val(), [&](mlir::Operation *user, mlir::Value used) { + if (mlir::isa(user)) + { + onlyRead = fieldOnlyRead(user, reads) && onlyRead; + return; + } - if (!isBorrow(user, used)) - { - onlyRead = false; - return; - } + auto merged = mergedValuesOf(user, used); + if (!merged.empty()) + { + reads.push_back(user); + for (auto value : merged) + { + if (seen.insert(value).second) + { + values.push_back(value); + } + } - reads.push_back(user); - }); + return; + } + + if (!isBorrow(user, used)) + { + onlyRead = false; + return; + } + + reads.push_back(user); + }); + } return onlyRead; } @@ -1035,6 +1057,12 @@ namespace own_inference return false; } + // moved into a merge: rc's retain of the merged value is the reference it moves into + if (auto *mergeRetain = mergeRetainOf(taker, value)) + { + moved.push_back(mergeRetain); + } + auto *acquire = acquirePoint(taker, value); for (auto *release : releases) { diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.cpp b/tslang/lib/TypeScript/OwnershipInferencePass.cpp index 0d7cb7a5b..414efc8c3 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePass.cpp @@ -809,6 +809,14 @@ namespace own_inference continue; } + // a merge of what nothing owns (`first ? shared : other` of immortal globals, + // `c ? 1 : "one"`): it owns nothing either + if (value && (mlir::isa(op) || slotHoldsInitializerAt(op)) && mergeOwnsNothing(value)) + { + toErase.insert(op); + continue; + } + // an array a spread builds, read into the owning local it is made for, or returned if (value && mlir::isa(op) && isBuiltArrayRead(op, value)) { @@ -898,6 +906,55 @@ namespace own_inference }); } + bool OwnershipInferencePass::mergeOwnsNothing(mlir::Value value, unsigned depth) + { + auto argument = mlir::dyn_cast(rootOf(value)); + if (!argument || argument.getOwner()->isEntryBlock() || depth > 8) + { + return false; + } + + auto *block = argument.getOwner(); + for (auto predecessor = block->pred_begin(); predecessor != block->pred_end(); ++predecessor) + { + auto branchOp = mlir::dyn_cast((*predecessor)->getTerminator()); + if (!branchOp) + { + return false; + } + + auto operands = branchOp.getSuccessorOperands(predecessor.getSuccessorIndex()); + if (argument.getArgNumber() < operands.getProducedOperandCount()) + { + return false; + } + + auto incoming = operands[argument.getArgNumber()]; + if (!incoming) + { + return false; + } + + auto root = rootOf(incoming); + if (mlir::isa(root)) + { + if (!mergeOwnsNothing(root, depth + 1)) + { + return false; + } + + continue; + } + + if (!(isConstantData(incoming) || isConstantData(root) || isImmortalGlobalRead(root) || isImmortalLiteral(root))) + { + return false; + } + } + + return true; + } + bool OwnershipInferencePass::reporting() { if (quiet) diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.h b/tslang/lib/TypeScript/OwnershipInferencePass.h index b537ab558..26480c6bc 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.h +++ b/tslang/lib/TypeScript/OwnershipInferencePass.h @@ -1370,6 +1370,17 @@ class OwnershipInferencePass // release; moving the instance into it would leave nothing to release it at all. static bool takerAcquires(mlir::Operation *taker, mlir::Value value); + // A branch into a merge (`return set ? n : undefined`) that carries `value`, where rc retains the + // merged value in its block: that retain is the reference the merge takes, and `value` moves into + // it on this way in. Only when every way into the merge brings null, undefined, or a fresh value + // (each moved as this one is): a borrow brought in would be given an owner. The retain, or null. + static mlir::Operation *mergeRetainOf(mlir::Operation *taker, mlir::Value value); + + // A value merged from branches (a block argument, through its views) where every way in brings + // what nothing owns: data (a literal, null), an immortal global's read, or such a merge. It owns + // nothing either, so a retain of it takes nothing. + static bool mergeOwnsNothing(mlir::Value value, unsigned depth = 0); + // The declaration's name survives only as debug metadata (`--di`). At this level MLIRGen's // form of it is a NameLoc first inside the location fused with the scope - what LowerToLLVM's // preserveTypesForDebugInfo reads - and after that pass it is a DILocalVariable. Without diff --git a/tslang/lib/TypeScript/OwnershipInferenceReadsAfterMove.cpp b/tslang/lib/TypeScript/OwnershipInferenceReadsAfterMove.cpp index 25813b56b..07c699bc5 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceReadsAfterMove.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceReadsAfterMove.cpp @@ -221,6 +221,11 @@ namespace own_inference return true; } + if (mergeRetainOf(taker, value)) + { + return true; + } + auto acquires = false; forEachUse(value, [&](mlir::Operation *user, mlir::Value) { acquires = acquires || (mlir::isa(user) && user->getBlock() == taker->getBlock() && @@ -230,4 +235,96 @@ namespace own_inference return acquires; } + mlir::Operation *OwnershipInferencePass::mergeRetainOf(mlir::Operation *taker, mlir::Value value) + { + auto branchOp = mlir::dyn_cast(taker); + if (!branchOp) + { + return nullptr; + } + + // the block argument this branch passes the value (or a view of it) as + auto root = rootOf(value); + mlir::BlockArgument merged; + for (auto &operand : taker->getOpOperands()) + { + if (rootOf(operand.get()) != root) + { + continue; + } + + auto arguments = mergedValuesOf(taker, operand.get()); + if (arguments.size() != 1 || merged) + { + return nullptr; + } + + merged = mlir::dyn_cast(arguments.front()); + } + + if (!merged) + { + return nullptr; + } + + // rc's one retain of the merged value, in its block + mlir::Operation *retain = nullptr; + auto other = false; + forEachUse(merged, [&](mlir::Operation *user, mlir::Value) { + if (mlir::isa(user)) + { + other = other || retain || user->getBlock() != merged.getOwner(); + retain = user; + } + }); + + if (!retain || other) + { + return nullptr; + } + + // every way in: null or undefined, or a fresh value - not a loop's back edge + auto *block = merged.getOwner(); + mlir::DominanceInfo dominance(block->getParentOp()); + for (auto predecessor = block->pred_begin(); predecessor != block->pred_end(); ++predecessor) + { + auto predecessorBranch = mlir::dyn_cast((*predecessor)->getTerminator()); + if (!predecessorBranch || dominance.dominates(block, *predecessor)) + { + return nullptr; + } + + auto operands = predecessorBranch.getSuccessorOperands(predecessor.getSuccessorIndex()); + if (merged.getArgNumber() < operands.getProducedOperandCount()) + { + return nullptr; + } + + auto incoming = operands[merged.getArgNumber()]; + if (!incoming) + { + return nullptr; + } + + auto constant = incoming; + while (auto castOp = constant.getDefiningOp()) + { + constant = castOp.getIn(); + } + + if (constant.getDefiningOp() || constant.getDefiningOp() || + constant.getDefiningOp()) + { + continue; + } + + if (mlir::isa(rootOf(incoming)) || !isFresh(rootOf(incoming))) + { + return nullptr; + } + } + + return retain; + } + } // namespace own_inference diff --git a/tslang/lib/TypeScript/OwnershipSignatureGlobals.cpp b/tslang/lib/TypeScript/OwnershipSignatureGlobals.cpp index 7c57880b8..711eb2521 100644 --- a/tslang/lib/TypeScript/OwnershipSignatureGlobals.cpp +++ b/tslang/lib/TypeScript/OwnershipSignatureGlobals.cpp @@ -317,6 +317,14 @@ namespace own_signature continue; } + // data nothing owns - null on the way of `c ? mk() : null` that does not make one, + // wherever it goes - takes nothing + if (isConstantData(value) && !mlir::isa(value)) + { + retainOp.erase(); + continue; + } + // nothing in the region gives the block back, or takes a second reference to it: // the global is its one owner auto released = false; diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index d8c1b6282..ef61981fa 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -4662,7 +4662,8 @@ foreach(own_test own_fresh_string own_fresh_array own_return_new own_try_local o own_generic_specializations own_callback_cast own_callback_interface_slot own_equal_strings_into_any own_any_copies own_array_copies own_string_pushed_twice own_rest_takes own_shares_elements own_rest_keeps_declared own_interface_getter_let own_callback_assigns_capture - own_param_capture_copies own_swap_local_field own_closure_keeps_param own_chain_returns_this own_callback_fewer_params) + own_param_capture_copies own_swap_local_field own_closure_keeps_param own_chain_returns_this own_callback_fewer_params + own_optional_literal_result own_merge_moves_local own_global_merge_initializer own_merge_of_constants) tslang_add_test(NAME test-jit-own-${own_test} COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/own/${own_test}.ts") tslang_add_test(NAME test-compile-own-${own_test} COMMAND test-runner -mm=own "${PROJECT_SOURCE_DIR}/test/tester/own/${own_test}.ts") # The promise: no counting at all in what own emits. @@ -4702,7 +4703,8 @@ foreach(keeps_mm rc gc none) own_callback_shapes own_callback_extended own_callback_interface own_generic_specializations own_callback_cast own_callback_interface_slot own_equal_strings_into_any own_rest_keeps_declared own_interface_getter_let own_callback_assigns_capture - own_param_capture_copies own_swap_local_field own_closure_keeps_param own_chain_returns_this own_callback_fewer_params) + own_param_capture_copies own_swap_local_field own_closure_keeps_param own_chain_returns_this own_callback_fewer_params + own_optional_literal_result own_merge_moves_local own_global_merge_initializer own_merge_of_constants) tslang_add_test(NAME test-jit-${keeps_mm}-${keeps_test} COMMAND test-runner -jit -mm=${keeps_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/${keeps_test}.ts") tslang_add_test(NAME test-compile-${keeps_mm}-${keeps_test} COMMAND test-runner -mm=${keeps_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/${keeps_test}.ts") endforeach() diff --git a/tslang/test/tester/own/own_global_merge_initializer.ts b/tslang/test/tester/own/own_global_merge_initializer.ts new file mode 100644 index 000000000..bf1d82921 --- /dev/null +++ b/tslang/test/tester/own/own_global_merge_initializer.ts @@ -0,0 +1,30 @@ +// A global initialized by `?:` of a fresh object and null or undefined: the global owns what the way +// taken makes; the other way gives null, which owns nothing. +class Node { + constructor(public v: number) {} +} + +function on() { + return true; +} + +function off() { + return false; +} + +function mk(n: number) { + return new Node(n); +} + +let pick: Node | null = on() ? mk(3) : null; +let none: Node | null = off() ? mk(4) : null; +let maybe: Node | undefined = on() ? mk(5) : undefined; + +function main() { + assert(pick !== null && pick.v == 3, "pick"); + assert(none === null, "none"); + assert(maybe !== undefined && maybe.v == 5, "maybe"); + pick = mk(6); + assert(pick.v == 6, "reassigned"); + print("done."); +} diff --git a/tslang/test/tester/own/own_merge_moves_local.ts b/tslang/test/tester/own/own_merge_moves_local.ts new file mode 100644 index 000000000..669b16b02 --- /dev/null +++ b/tslang/test/tester/own/own_merge_moves_local.ts @@ -0,0 +1,41 @@ +// An owned local chosen by `?:` against null or undefined, and returned or stored: it moves on the way +// that chooses it, and is released on the way that does not (`return set ? n : undefined`). +class Node { + name = ""; +} + +class Holder { + n: Node | null = null; +} + +function named(set: boolean, name: string): Node | undefined { + const n = new Node(); + n.name = name; + return set ? n : undefined; +} + +function orNull(set: boolean, name: string): Node | null { + const n = new Node(); + n.name = name; + return set ? n : null; +} + +function store(h: Holder, set: boolean, name: string) { + const n = new Node(); + n.name = name; + h.n = set ? n : null; +} + +function main() { + const h = new Holder(); + for (let i = 0; i < 200; i++) { + const a = named(i % 2 == 0, "a" + i); + assert(i % 2 == 0 ? a?.name == "a" + i : a === undefined, "named"); + const b = orNull(i % 3 == 0, "b" + i); + assert(i % 3 == 0 ? b?.name == "b" + i : b === null, "orNull"); + store(h, i % 2 == 1, "h" + i); + assert(i % 2 == 1 ? h.n?.name == "h" + i : h.n === null, "store"); + } + + print("done."); +} diff --git a/tslang/test/tester/own/own_merge_of_constants.ts b/tslang/test/tester/own/own_merge_of_constants.ts new file mode 100644 index 000000000..5170793c1 --- /dev/null +++ b/tslang/test/tester/own/own_merge_of_constants.ts @@ -0,0 +1,35 @@ +// A value merged from branches that each bring what nothing owns - a literal, null, a global never given +// another value (immortal, spec 25) - owns nothing itself: keeping it takes no reference. +class Box { + constructor(public v: number) {} +} + +const shared = new Box(1); +const other = new Box(2); + +function pick(first: boolean): Box { + return first ? shared : other; +} + +function folded() { + const text = "abc"; + let v = typeof text === "string" ? 1 : "one"; + return [v]; +} + +function label(c: boolean) { + let w = c ? "yes" : "no"; + return w; +} + +function main() { + for (let i = 0; i < 100; i++) { + assert(pick(i % 2 == 0).v == (i % 2 == 0 ? 1 : 2), "pick"); + const kept = pick(true); + assert(kept === shared, "the global itself"); + } + + assert(folded()[0] == 1, "folded"); + assert(label(true) == "yes" && label(false) == "no", "labels"); + print("done."); +} diff --git a/tslang/test/tester/own/own_optional_literal_result.ts b/tslang/test/tester/own/own_optional_literal_result.ts new file mode 100644 index 000000000..5241173d7 --- /dev/null +++ b/tslang/test/tester/own/own_optional_literal_result.ts @@ -0,0 +1,26 @@ +// A function that returns an object literal on some paths and undefined on others: the literal of +// constants owns nothing (immortal strings), so returning it as an optional takes no reference; one +// that holds a string made at run time owns it, and the caller releases it. +function object(c: boolean) { + if (c) return { v: "x" }; + return undefined; +} + +function made(c: boolean, n: number) { + if (c) return { v: "made" + n }; + return undefined; +} + +function main() { + for (let i = 0; i < 200; i++) { + assert(object(true)?.v == "x", "literal"); + assert(object(false) === undefined, "undefined"); + const o = object(true); + assert(o?.v == "x", "through a local"); + const m = made(true, i); + assert(m?.v == "made" + i, "made"); + assert(made(false, i) === undefined, "made: undefined"); + } + + print("done."); +}