From f00b7b93a6f89889d69ff14c79a897888bb56ef3 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Sat, 14 Nov 2026 11:28:43 +0000 Subject: [PATCH 1/3] own: a value moved into a field and used after is a borrow of the field; warn on a missing --own-facts file (TSLANG 50, 51) Co-Authored-By: Claude Opus 5.5 --- TSLANG_ISSUES.md | 44 +++++++++ .../OwnershipSignatureFieldLocals.cpp | 68 +++++++++++++ tslang/test/tester/CMakeLists.txt | 18 +++- .../own/own_err_moved_field_overwritten.ts | 19 ++++ .../own/own_err_moved_param_field_dropped.ts | 16 +++ tslang/test/tester/tests/00tslang_issue_50.ts | 98 +++++++++++++++++++ tslang/tslang/borrowfacts.cpp | 17 +++- 7 files changed, 276 insertions(+), 4 deletions(-) create mode 100644 tslang/test/tester/own/own_err_moved_field_overwritten.ts create mode 100644 tslang/test/tester/own/own_err_moved_param_field_dropped.ts create mode 100644 tslang/test/tester/tests/00tslang_issue_50.ts diff --git a/TSLANG_ISSUES.md b/TSLANG_ISSUES.md index f4fd4604b..5c85cd47e 100644 --- a/TSLANG_ISSUES.md +++ b/TSLANG_ISSUES.md @@ -228,3 +228,47 @@ export class App { Regression tests `tslang/test/tester/tests/00tslang_issue_49.ts` (every model), `own/own_err_moved_when_tested_other.ts`, `own_err_field_moved_call_between.ts` and `own_err_override_lends.ts`. powder_sandbox's exchange workaround still works. + +Items 50 and 51, found on 2026-11-14 by compiling every module of powder_sandbox's `-mm=own` build +(native_ts_graphics fc6fe6c as its submodule) with the compiler from main, are fixed. + +50 (a value of the function's own moved into a field, then used: `const layout = +device.createPipelineLayoutFromDesc(desc); this.layout = layout; if (!layout) return false; +device.createPipelineFromDesc(layout, ...)`, in native_ts_graphics' `core/nri_donut_blit.ts`, was +refused, "'this value' is used here after its value was moved"). Item 47 read a local as the field it +was moved into, but a `const` given a call's result is that result itself, with no local to read. Now +each use the store dominates reads the field instead, read right after the store, so it is a borrow +of the field. The checks then follow that borrow through the calls in between with their facts. This +also covers a store inside an `if`, and an object (`new Layout()`) stored into a `Layout | null` +field, which is read back narrowed. A string stored into a field is a copy and a `Shared` handle a +count, so those stay the function's own, as before. A call in between that may overwrite the field is +still an error, now "borrows a field but is used here after it may be released or overwritten". +`nri_donut_blit.ts` compiles under own now. It also closes a hole: with a value moved into a field of +a parameter (`h.c = c`), and `h` then given away into a field that is cleared, alpha127 took the later +`c.x` and printed 0 from freed memory. That is refused now. Still open: a value merged from a `?:` +(`const l = ok ? make() : null; this.f = l; use(l)`) stays "merged from several branches", as before. + +51 (`--own-facts=` naming a file that does not exist was passed over in silence): every call into +that module was then taken to release or overwrite anything, so the errors that followed read as the +program's own. powder_sandbox's `build-own` had 27 of the 58 facts objects its compile lines name +(`own-facts/core/donut.ts.obj` was never built there). With them all built, the sweep's own failures +went from 210 files to 149, and "borrows a field but is used here after it may be released or +overwritten" from 724 errors to 275. A missing file still gives no facts, but tslang warns now: +"--own-facts: '' does not exist; calls into its module are taken to release or overwrite +anything". + +Regression tests `tslang/test/tester/tests/00tslang_issue_50.ts` (every model), +`own/own_err_moved_field_overwritten.ts`, `own/own_err_moved_param_field_dropped.ts` and the ctest +`test-own-facts-missing-file`. `own/own_err_read_after_move_global.ts` is still refused at all three +sites, now as a borrow of the field that the global's assignment ends. + +For native_ts_graphics, from the same sweep (its code, not the compiler): +- `examples/dynamic_primitive_clipping.ts:223`, `desc.setDepthClip(clip)` with `clip` the loop's `int`, + fails under every model since #846 (a number is not a `boolean` argument, TS2345). alpha127 still + takes it; the next release won't. `desc.setDepthClip(clip != 0)` fixes it. +- Under `-mm=own`, 7 `core/` modules do not compile yet (`directx_math.ts`, `donut_first_person_camera.ts`, + `nri_donut_textures.ts`, `octomap_common.ts`, `ray_tracing_extended_scene.ts`, `simple_camera.ts`, + `rtxpt_game.ts`), and nor do most examples, which #310 did not port: with every facts object built, + 149 of the 276 sources fail. Most use-after-move errors left are a constructor keeping its argument + (`const r = new X(sample)`, then `sample` used: about 96) or a value used after `push` into an array + (about 91). diff --git a/tslang/lib/TypeScript/OwnershipSignatureFieldLocals.cpp b/tslang/lib/TypeScript/OwnershipSignatureFieldLocals.cpp index cce9245d8..c0b64bda7 100644 --- a/tslang/lib/TypeScript/OwnershipSignatureFieldLocals.cpp +++ b/tslang/lib/TypeScript/OwnershipSignatureFieldLocals.cpp @@ -363,6 +363,74 @@ namespace own_signature } } + // A value of the function's own moved into a field and used after (TSLANG 50): `const + // layout = device.create(); this.layout = layout; if (!layout) return false; + // use(layout);`. The `const` is the call's result itself, with no local to pair with a + // field. After the store it is what the field holds, so each use the store dominates + // reads the field instead, read right after the store: a borrow of the field, which the + // checks then follow through the calls between with their facts. Its release stays: the + // move takes it over. + // The stores in nested regions count too (`if (ok) { this.f = v; use(v); }`). + mlir::DominanceInfo dominance(body->getParentOp()); + llvm::SmallVector movedStores; + body->walk([&](mlir_ts::StoreOp storeOp) { + auto field = storeOp.getReference().getDefiningOp(); + if (field && objectReadable(field)) + { + movedStores.push_back(storeOp); + } + }); + + for (auto fieldStore : movedStores) + { + auto root = stripViews(fieldStore.getValue()); + auto *def = root.getDefiningOp(); + auto field = fieldStore.getReference().getDefiningOp(); + // an object stored into a field that may also be null or hold another type + // (`new Layout()` into `Layout | null`): read back, the field is narrowed to it + auto fieldType = mlir::cast(field.getType()).getElementType(); + auto narrowed = !fieldReadsAs(field, root.getType()) && + mlir::isa(root.getType()) && + mlir::isa(fieldType); + // a string and the like are copied into the field, and a Shared handle counted: + // the value stays the function's own, not moved + if (!def || mlir::isa(def) || !own_facts::ownsHeap(root) || + own_facts::isCopyableValueAt(fieldStore, root.getType()) || + MLIRTypeHelper::isSharedHandleType(root.getType()) || (!narrowed && !fieldReadsAs(field, root.getType()))) + { + continue; + } + + llvm::SmallVector uses; + for (auto &use : root.getUses()) + { + auto *user = use.getOwner(); + if (user != fieldStore.getOperation() && !mlir::isa(user) && + dominance.properlyDominates(fieldStore.getOperation(), user)) + { + uses.push_back(&use); + } + } + + if (uses.empty()) + { + continue; + } + + mlir::OpBuilder builder(fieldStore->getContext()); + builder.setInsertionPointAfter(fieldStore); + auto read = readFieldAt(builder, fieldStore.getLoc(), narrowed ? fieldType : root.getType(), field); + if (narrowed) + { + read = builder.create(fieldStore.getLoc(), root.getType(), read); + } + + for (auto *use : uses) + { + use->set(read); + } + } + // the pairs: a local not captured, and a field it is declared from or that is given it llvm::SmallVector pairs; body->walk([&](mlir_ts::VariableOp varOp) { diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index d37c10372..dc8e5c592 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -1904,8 +1904,9 @@ endforeach() # TSLANG_ISSUES 47: a lazily cached field returned through a local; a fill of an empty field frees nothing # TSLANG_ISSUES 48: a @final method of an exported class is called directly, by its own facts # TSLANG_ISSUES 49: a nullable local moved when not null, a virtual call's own result, a field moved into another +# TSLANG_ISSUES 50: a value moved into a field and used after is a borrow of the field foreach(issues_mm gc rc none own) - foreach(issues_test 00tslang_issue_44 00tslang_issue_45 00tslang_issue_46 00tslang_issue_47 00tslang_issue_48 00tslang_issue_49) + foreach(issues_test 00tslang_issue_44 00tslang_issue_45 00tslang_issue_46 00tslang_issue_47 00tslang_issue_48 00tslang_issue_49 00tslang_issue_50) tslang_add_test(NAME test-jit-${issues_test}-${issues_mm} COMMAND test-runner -jit -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/${issues_test}.ts") tslang_add_test(NAME test-compile-${issues_test}-${issues_mm} COMMAND test-runner -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/${issues_test}.ts") endforeach() @@ -5357,7 +5358,7 @@ set(own_error_cases "own_err_read_after_move_call|:11:11: error: '[^']*' is used here after its value was moved" "own_err_read_after_move_loop|:25:14: error: '[^']*' is used here after its value was moved" "own_err_read_after_move_after_loop|:14:11: error: '[^']*' is used here after its value was moved" - "own_err_read_after_move_global|:42:15: error: '[^']*' is used here after its value was moved" + "own_err_read_after_move_global|:42:15: error: '[^']*' borrows a field but is used here after it may be released or overwritten" "own_err_field_let_global_overwritten|:42:11: error: '[^']*' borrows a field but is used here after it may be released or overwritten" "own_err_conditional_move_read|:20:11: error: '[^']*' is used here after its value was moved" "own_err_conditional_move_outer|:19:13: error: '[^']*' is moved inside a loop but was made outside it" @@ -5447,7 +5448,9 @@ set(own_error_cases "own_err_fill_after_fill_call|:19:20: error: '[^']*' borrows the result of 'Dev.fill' but is used here after it may be released or overwritten" "own_err_moved_when_tested_other|:13:13: error: '[^']*' is moved here on some paths only" "own_err_field_moved_call_between|:12:9: error: '[^']*' borrows a field and cannot be stored, returned or captured" - "own_err_override_lends|:13:5: error: method 'read' returns a borrow .* but the method of 'Base' it overrides does not") + "own_err_override_lends|:13:5: error: method 'read' returns a borrow .* but the method of 'Base' it overrides does not" + "own_err_moved_field_overwritten|:15:25: error: '[^']*' borrows a field but is used here after it may be released or overwritten" + "own_err_moved_param_field_dropped|:13:15: error: '[^']*' borrows a field but is used here after it may be released or overwritten") foreach(own_error_case ${own_error_cases}) string(FIND "${own_error_case}" "|" own_error_sep) string(SUBSTRING "${own_error_case}" 0 ${own_error_sep} own_error_name) @@ -5461,6 +5464,15 @@ foreach(own_error_case ${own_error_cases}) PROPERTIES PASS_REGULAR_EXPRESSION "${own_error_message}" FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed") endforeach() +# TSLANG_ISSUES 51: a file --own-facts names that does not exist is said, not passed over in silence +add_test(NAME test-own-facts-missing-file + COMMAND $ --emit=obj --no-default-lib -mm=own + "--own-facts=${CMAKE_CURRENT_BINARY_DIR}/no-such-facts.obj" + "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_50.ts" + -o "${CMAKE_CURRENT_BINARY_DIR}/own-facts-missing-file.obj") +set_tests_properties(test-own-facts-missing-file + PROPERTIES PASS_REGULAR_EXPRESSION "warning: --own-facts: '[^']*no-such-facts.obj' does not exist" + FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed") # @dllname and @linkname are one decorator under two names, and a symbol is bound once: each # case is a program the compiler must reject with the given message instead of binding diff --git a/tslang/test/tester/own/own_err_moved_field_overwritten.ts b/tslang/test/tester/own/own_err_moved_field_overwritten.ts new file mode 100644 index 000000000..327206296 --- /dev/null +++ b/tslang/test/tester/own/own_err_moved_field_overwritten.ts @@ -0,0 +1,19 @@ +// TSLANG_ISSUES 50: a value moved into a field is read as the field after the move - but a call in +// between overwrites the field, which frees the value, so its use after the call is refused. +class Layout { + id: int = 1; +} + +class Blit { + layout: Layout | null = null; + make(): Layout | null { return new Layout(); } + reset() { this.layout = new Layout(); } + init(): int { + const layout = this.make(); + this.layout = layout; + this.reset(); + return layout ? layout.id : 0; + } +} + +function main() { print(new Blit().init()); } diff --git a/tslang/test/tester/own/own_err_moved_param_field_dropped.ts b/tslang/test/tester/own/own_err_moved_param_field_dropped.ts new file mode 100644 index 000000000..7a4fa5e8e --- /dev/null +++ b/tslang/test/tester/own/own_err_moved_param_field_dropped.ts @@ -0,0 +1,16 @@ +// TSLANG_ISSUES 50: a value moved into a field of a parameter is a borrow of that field after the +// move; the parameter given away into a field that is then cleared frees it, and the value with +// it, so the use after is refused (v0.0-pre-alpha127 took it and printed 0). +class C { x: int = 5; } +class H { c: C | null = null; } +class K { + h: H | null = null; + run(h: H) { + const c = new C(); + h.c = c; + this.h = h; + this.h = null; + print(c.x); + } +} +function main() { new K().run(new H()); } diff --git a/tslang/test/tester/tests/00tslang_issue_50.ts b/tslang/test/tester/tests/00tslang_issue_50.ts new file mode 100644 index 000000000..b65242236 --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_50.ts @@ -0,0 +1,98 @@ +// TSLANG_ISSUES 50 (-mm=own), from native_ts_graphics' core/nri_donut_blit.ts: a value of the +// function's own (a call's result, a `new`) kept in a `const`, moved into a field, and then used - +// tested, passed to a call, read in a `?:`. After the move the `const` is what the field holds, a +// borrow of it; the calls between write no field of `this`. + +class Layout { + id: int = 1; +} + +@final +class Device { + made = 0; + make(fail: boolean): Layout | null { + this.made++; + return fail ? null : new Layout(); + } + use(l: Layout): int { + return l.id + 10; + } +} + +export class Blit { + private layout: Layout | null = null; + private kept: Layout | null = null; + n = 0; + + init(device: Device, fail: boolean): boolean { + const layout = device.make(fail); + this.layout = layout; + if (!layout) { + return false; + } + + device.make(true); + this.n = layout ? device.use(layout) : -1; + return true; + } + + // a `new` object moved into a field that may be null: read back narrowed to the object + keep(device: Device) { + const l = new Layout(); + l.id = 5; + this.kept = l; + this.n += device.use(l) + l.id; + } + + // the store in an `if` + nested(device: Device, ok: boolean): int { + if (ok) { + const layout = device.make(this.n < 0); + this.layout = layout; + if (!layout) { + return -1; + } + + return device.use(layout); + } + + return 0; + } +} + +// a string is copied into a field and a Shared handle counted, not moved: the function's own +// value stays usable after a call that overwrites the field +function mkText(): string { + return "a" + "b"; +} + +class Copies { + name: string = ""; + shared: Shared | null = null; + clear() { + this.name = "z"; + this.shared = null; + } + run(): string { + const s = mkText(); + this.name = s; + const h = new Shared(new Layout()); + this.shared = h; + this.clear(); + return `${s}${h.value.id}`; + } +} + +function main() { + assert(new Copies().run() == "ab1"); + const device = new Device(); + const b = new Blit(); + assert(b.init(device, false)); + assert(b.n == 11); + assert(!b.init(device, true)); + b.keep(device); + print(b.n, device.made); + assert(b.n == 11 + 15 + 5 && device.made == 3); + assert(b.nested(device, true) == 11 && b.nested(device, false) == 0); + print("done."); +} diff --git a/tslang/tslang/borrowfacts.cpp b/tslang/tslang/borrowfacts.cpp index 4239ee7b4..891566bb3 100644 --- a/tslang/tslang/borrowfacts.cpp +++ b/tslang/tslang/borrowfacts.cpp @@ -10,6 +10,7 @@ #include "llvm/Support/FileSystem.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" +#include "llvm/Support/WithColor.h" #include "llvm/TargetParser/Host.h" #include "llvm/TargetParser/Triple.h" @@ -222,7 +223,8 @@ void readBorrowFacts(CompileOptions &compileOptions) // Called before the module is compiled: the ownership signature pass reads them (MLIRGen puts // them on the module). Only under own, and only from the files --own-facts names: the objects of // the modules this one imports, which the build links with it - so, like a library's borrow facts, -// they describe the code that runs. A file that is missing or holds none gives no facts. +// they describe the code that runs. A file that is missing (with a warning) or holds none gives no +// facts. void readOwnFacts(CompileOptions &compileOptions) { if (compileOptions.memoryModel != MemoryModelOwn) @@ -236,6 +238,19 @@ void readOwnFacts(CompileOptions &compileOptions) // its facts are read from its file, as its borrow facts are (readBorrowFacts). Without them // every call into the library may destroy anything. std::vector files(ownFacts.begin(), ownFacts.end()); + + // a file --own-facts names that is not there (not built yet, a wrong path) still gives no facts, + // but says so: every call into its module may then destroy anything, and the errors that follow + // read as the program's own (TSLANG 51) + for (auto &file : files) + { + if (!llvm::sys::fs::is_regular_file(file)) + { + llvm::WithColor::warning(llvm::errs(), "tslang") + << "--own-facts: '" << file << "' does not exist; calls into its module are taken to release or overwrite anything\n"; + } + } + std::string jitDefaultLib; if (!compileOptions.noDefaultLib) { From 979f55972f47f3eddde102da1be4450e06f4bfa6 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Sat, 14 Nov 2026 11:33:37 +0000 Subject: [PATCH 2/3] own: a value pushed into a field array and used after is a borrow of its last element (TSLANG 52) Co-Authored-By: Claude Opus 5.5 --- TSLANG_ISSUES.md | 12 ++++ .../OwnershipSignatureFieldLocals.cpp | 69 +++++++++++++++++++ tslang/test/tester/CMakeLists.txt | 7 +- .../tester/own/own_err_pushed_then_popped.ts | 18 +++++ tslang/test/tester/tests/00tslang_issue_52.ts | 66 ++++++++++++++++++ 5 files changed, 170 insertions(+), 2 deletions(-) create mode 100644 tslang/test/tester/own/own_err_pushed_then_popped.ts create mode 100644 tslang/test/tester/tests/00tslang_issue_52.ts diff --git a/TSLANG_ISSUES.md b/TSLANG_ISSUES.md index 5c85cd47e..595b2489c 100644 --- a/TSLANG_ISSUES.md +++ b/TSLANG_ISSUES.md @@ -262,6 +262,18 @@ Regression tests `tslang/test/tester/tests/00tslang_issue_50.ts` (every model), `test-own-facts-missing-file`. `own/own_err_read_after_move_global.ts` is still refused at all three sites, now as a borrow of the field that the global's assignment ends. +52 (a value of the function's own pushed into an array that is a field, then used: `this.textures.push( +texture); this.srgb.push(srgb); this.views.push(texture.createView(...))` in `core/nri_donut_textures.ts`, +refused "used here after its value was moved") is fixed the same way. After the push the value is the +array's last element, so each use the push dominates reads `array[newLength - 1]`, read right after the +push: a borrow of the element. Pushing into other arrays, or more into the same one, keeps it. A `pop`, +an element stored, the array replaced, or a call that may do any of these between the push and the use +is still refused ("borrows an element but is used here after it may be released or overwritten"). In +the sweep, push-then-use sites went from 91 to 72. The rest move the value into a constructor whose +result is pushed (`this.queuedFrames.push(new QueuedFrame(viewSet, ...))`, then `viewSet` used): the +constructor case below, still open. Regression tests `tslang/test/tester/tests/00tslang_issue_52.ts` +(every model) and `own/own_err_pushed_then_popped.ts`. + For native_ts_graphics, from the same sweep (its code, not the compiler): - `examples/dynamic_primitive_clipping.ts:223`, `desc.setDepthClip(clip)` with `clip` the loop's `int`, fails under every model since #846 (a number is not a `boolean` argument, TS2345). alpha127 still diff --git a/tslang/lib/TypeScript/OwnershipSignatureFieldLocals.cpp b/tslang/lib/TypeScript/OwnershipSignatureFieldLocals.cpp index c0b64bda7..1927bee45 100644 --- a/tslang/lib/TypeScript/OwnershipSignatureFieldLocals.cpp +++ b/tslang/lib/TypeScript/OwnershipSignatureFieldLocals.cpp @@ -431,6 +431,75 @@ namespace own_signature } } + // The same for a value pushed into an array that is a field (TSLANG 52): `this.textures.push( + // texture); this.views.push(texture.createView(...))`. After the push the value is the + // array's last element, so each use the push dominates reads `array[newLength - 1]`, + // read right after the push: a borrow of the element, followed through the calls between. + llvm::SmallVector pushes; + body->walk([&](mlir_ts::ArrayPushOp pushOp) { pushes.push_back(pushOp); }); + for (auto pushOp : pushes) + { + auto field = pushOp.getOp().getDefiningOp(); + if (pushOp.getItems().size() != 1 || !field || !objectReadable(field)) + { + continue; + } + + auto arrayType = mlir::dyn_cast(mlir::cast(field.getType()).getElementType()); + auto root = stripViews(pushOp.getItems().front()); + auto *def = root.getDefiningOp(); + if (!arrayType || !def || mlir::isa(def) || !own_facts::ownsHeap(root) || + own_facts::isCopyableValueAt(pushOp, root.getType()) || MLIRTypeHelper::isSharedHandleType(root.getType())) + { + continue; + } + + // the element read back as the value's type: itself, or widened back to it + auto elementType = arrayType.getElementType(); + if (elementType != root.getType() && !(mlir::isa(elementType) && + mlir::isa(root.getType()))) + { + continue; + } + + llvm::SmallVector uses; + for (auto &use : root.getUses()) + { + auto *user = use.getOwner(); + if (!mlir::isa(user) && dominance.properlyDominates(pushOp.getOperation(), user)) + { + uses.push_back(&use); + } + } + + if (uses.empty()) + { + continue; + } + + auto location = pushOp.getLoc(); + mlir::OpBuilder builder(pushOp->getContext()); + builder.setInsertionPointAfter(pushOp); + auto array = readFieldAt(builder, location, arrayType, field); + mlir::Value one = builder.create(location, builder.getI32IntegerAttr(1)); + one = builder.create(location, builder.getIndexType(), one); + mlir::Value last = builder.create( + location, builder.getIndexType(), builder.getI32IntegerAttr(static_cast(SyntaxKind::MinusToken)), + pushOp.getNewSize(), one); + last = builder.create(location, builder.getI32Type(), last); + auto elementRef = builder.create(location, mlir_ts::RefType::get(elementType), array, last); + mlir::Value read = builder.create(location, elementType, elementRef); + if (elementType != root.getType()) + { + read = builder.create(location, root.getType(), read); + } + + for (auto *use : uses) + { + use->set(read); + } + } + // the pairs: a local not captured, and a field it is declared from or that is given it llvm::SmallVector pairs; body->walk([&](mlir_ts::VariableOp varOp) { diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index dc8e5c592..30b08ee32 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -1905,8 +1905,10 @@ endforeach() # TSLANG_ISSUES 48: a @final method of an exported class is called directly, by its own facts # TSLANG_ISSUES 49: a nullable local moved when not null, a virtual call's own result, a field moved into another # TSLANG_ISSUES 50: a value moved into a field and used after is a borrow of the field +# TSLANG_ISSUES 52: a value pushed into a field array and used after is a borrow of its last element foreach(issues_mm gc rc none own) - foreach(issues_test 00tslang_issue_44 00tslang_issue_45 00tslang_issue_46 00tslang_issue_47 00tslang_issue_48 00tslang_issue_49 00tslang_issue_50) + foreach(issues_test 00tslang_issue_44 00tslang_issue_45 00tslang_issue_46 00tslang_issue_47 00tslang_issue_48 00tslang_issue_49 00tslang_issue_50 + 00tslang_issue_52) tslang_add_test(NAME test-jit-${issues_test}-${issues_mm} COMMAND test-runner -jit -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/${issues_test}.ts") tslang_add_test(NAME test-compile-${issues_test}-${issues_mm} COMMAND test-runner -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/${issues_test}.ts") endforeach() @@ -5450,7 +5452,8 @@ set(own_error_cases "own_err_field_moved_call_between|:12:9: error: '[^']*' borrows a field and cannot be stored, returned or captured" "own_err_override_lends|:13:5: error: method 'read' returns a borrow .* but the method of 'Base' it overrides does not" "own_err_moved_field_overwritten|:15:25: error: '[^']*' borrows a field but is used here after it may be released or overwritten" - "own_err_moved_param_field_dropped|:13:15: error: '[^']*' borrows a field but is used here after it may be released or overwritten") + "own_err_moved_param_field_dropped|:13:15: error: '[^']*' borrows a field but is used here after it may be released or overwritten" + "own_err_pushed_then_popped|:14:16: error: '[^']*' borrows an element but is used here after it may be released or overwritten") foreach(own_error_case ${own_error_cases}) string(FIND "${own_error_case}" "|" own_error_sep) string(SUBSTRING "${own_error_case}" 0 ${own_error_sep} own_error_name) diff --git a/tslang/test/tester/own/own_err_pushed_then_popped.ts b/tslang/test/tester/own/own_err_pushed_then_popped.ts new file mode 100644 index 000000000..3ef61eddd --- /dev/null +++ b/tslang/test/tester/own/own_err_pushed_then_popped.ts @@ -0,0 +1,18 @@ +// TSLANG_ISSUES 52: a value pushed into an array that is a field is a borrow of its last element +// after the push - but `pop` releases that element, and the value with it, so the use after is +// refused. +class Tex { + id: int = 7; +} + +class K { + texs: Tex[] = []; + run(): int { + const t = new Tex(); + this.texs.push(t); + this.texs.pop(); + return t.id; + } +} + +function main() { print(new K().run()); } diff --git a/tslang/test/tester/tests/00tslang_issue_52.ts b/tslang/test/tester/tests/00tslang_issue_52.ts new file mode 100644 index 000000000..837ebc4e0 --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_52.ts @@ -0,0 +1,66 @@ +// TSLANG_ISSUES 52 (-mm=own), from native_ts_graphics' core/nri_donut_textures.ts: a value of the +// function's own pushed into an array that is a field, then used - `this.textures.push(texture); +// this.views.push(texture.createView(...))`. After the push the value is the array's last element, a +// borrow of it; pushing into other arrays, or more into the same one, keeps it. + +class Tex { + id: int = 1; + view(): int { + return this.id + 100; + } +} + +@final +class Device { + load(fail: boolean): Tex | null { + return fail ? null : new Tex(); + } +} + +export class Textures { + private textures: Tex[] = []; + private srgb: boolean[] = []; + private views: int[] = []; + + load(device: Device, n: int): boolean { + for (let i = 0; i < n; i++) { + const texture = device.load(false); + if (!texture) { + return false; + } + + this.textures.push(texture); + this.srgb.push(i > 0); + this.views.push(texture.view()); + } + + return true; + } + + // a `new` object, the same array pushed into again before the use + twice(): int { + const t = new Tex(); + t.id = 7; + this.textures.push(t); + this.textures.push(new Tex()); + return t.id + this.textures.length; + } + + sum(): int { + let total = 0; + for (const v of this.views) { + total += v; + } + + return total; + } +} + +function main() { + const t = new Textures(); + assert(t.load(new Device(), 3)); + print(t.sum()); + assert(t.sum() == 303); + assert(t.twice() == 12); + print("done."); +} From 2f64027fffb40d65b359af710969c354b7ea17a5 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Sat, 14 Nov 2026 11:50:23 +0000 Subject: [PATCH 3/3] own: a value a constructor keeps in a field, used after, is a borrow of that field (TSLANG 53) Co-Authored-By: Claude Opus 5.5 --- TSLANG_ISSUES.md | 26 +- .../OwnershipSignatureFieldLocals.cpp | 281 +++++++++++++++++- tslang/test/tester/CMakeLists.txt | 6 +- .../own/own_err_kept_by_constructor_reset.ts | 17 ++ tslang/test/tester/tests/00tslang_issue_53.ts | 79 +++++ 5 files changed, 391 insertions(+), 18 deletions(-) create mode 100644 tslang/test/tester/own/own_err_kept_by_constructor_reset.ts create mode 100644 tslang/test/tester/tests/00tslang_issue_53.ts diff --git a/TSLANG_ISSUES.md b/TSLANG_ISSUES.md index 595b2489c..5efd85439 100644 --- a/TSLANG_ISSUES.md +++ b/TSLANG_ISSUES.md @@ -270,17 +270,31 @@ push: a borrow of the element. Pushing into other arrays, or more into the same an element stored, the array replaced, or a call that may do any of these between the push and the use is still refused ("borrows an element but is used here after it may be released or overwritten"). In the sweep, push-then-use sites went from 91 to 72. The rest move the value into a constructor whose -result is pushed (`this.queuedFrames.push(new QueuedFrame(viewSet, ...))`, then `viewSet` used): the -constructor case below, still open. Regression tests `tslang/test/tester/tests/00tslang_issue_52.ts` +result is pushed (`this.queuedFrames.push(new QueuedFrame(viewSet, ...))`, then `viewSet` used): 53. Regression tests `tslang/test/tester/tests/00tslang_issue_52.ts` (every model) and `own/own_err_pushed_then_popped.ts`. +53 (a value of the function's own given to a constructor that keeps it in a field, then used: each +NRI example's `main`, `const sample = NriSample.create(); const app = new App(sample); +sample.addExampleOption(...)`, and `this.queuedFrames.push(new QueuedFrame(viewSet, ...)); viewSet.update(...)`, +refused "used here after its value was moved") is fixed. A constructor defined in the module keeps a +parameter when it stores it, as it is, into a field nothing else in it writes, and `this` does not +escape it: it is only read for its fields, or has an array field pushed into or popped. After the call, +each use of the value reads that field of the object. If the object was moved on, the read goes through +the place it was moved to last, as 50 and 52 made it (`this.queuedFrames[newLength - 1].viewSet`). A +borrow of a field, so a method that overwrites it, the object given away, or the object replaced before +the use is still refused. A constructor that writes the field again, or passes `this` on (a method +call, `super(...)`), keeps the old error. In the sweep, use-after-move errors went from 178 to 94: those +of a constructor's argument from 93 to 11, and push-then-use from 72 to 13. Six examples compile under +own now (`bokeh`, `calibrated_timestamps`, `shader_debugprintf`, `simple_compute`, `simple_hdr`, +`simple_pbr`), 143 of the 276 sources still fail. Regression tests `tslang/test/tester/tests/00tslang_issue_53.ts` +(every model) and `own/own_err_kept_by_constructor_reset.ts`. + For native_ts_graphics, from the same sweep (its code, not the compiler): - `examples/dynamic_primitive_clipping.ts:223`, `desc.setDepthClip(clip)` with `clip` the loop's `int`, fails under every model since #846 (a number is not a `boolean` argument, TS2345). alpha127 still takes it; the next release won't. `desc.setDepthClip(clip != 0)` fixes it. - Under `-mm=own`, 7 `core/` modules do not compile yet (`directx_math.ts`, `donut_first_person_camera.ts`, `nri_donut_textures.ts`, `octomap_common.ts`, `ray_tracing_extended_scene.ts`, `simple_camera.ts`, - `rtxpt_game.ts`), and nor do most examples, which #310 did not port: with every facts object built, - 149 of the 276 sources fail. Most use-after-move errors left are a constructor keeping its argument - (`const r = new X(sample)`, then `sample` used: about 96) or a value used after `push` into an array - (about 91). + `rtxpt_game.ts`), and nor do most examples, which #310 did not port: with every facts object built + and 50-53 in, 143 of the 276 sources fail. The largest group left is "borrows a field but is used + here after it may be released or overwritten" (about 280 sites). diff --git a/tslang/lib/TypeScript/OwnershipSignatureFieldLocals.cpp b/tslang/lib/TypeScript/OwnershipSignatureFieldLocals.cpp index 1927bee45..3f40e3ccb 100644 --- a/tslang/lib/TypeScript/OwnershipSignatureFieldLocals.cpp +++ b/tslang/lib/TypeScript/OwnershipSignatureFieldLocals.cpp @@ -188,6 +188,111 @@ namespace own_signature return run(at->getBlock(), in[at->getBlock()], at); } + // The fields a constructor keeps its parameters in (TSLANG 53): a parameter stored as it is into a + // field of `this` that nothing else in the constructor writes, where `this` never escapes - it + // is only read for its fields, so no call the constructor makes can reach the field. By the + // parameter's number (`this` is 0): the field's position and its reference type. + llvm::DenseMap> keptParameters(mlir_ts::FuncOp ctor) + { + llvm::DenseMap> kept; + if (ctor.isExternal()) + { + return kept; + } + + auto &entry = ctor.getFunctionBody().front(); + llvm::DenseMap parameters; + mlir::Value thisSlot; + // a parameter's slot: `ts.Param(%arg)`, or `ts.Variable(%arg)` once the slots are made + for (auto &op : entry) + { + if (!mlir::isa(&op) || op.getNumOperands() != 1) + { + continue; + } + + if (auto argument = mlir::dyn_cast(op.getOperand(0)); argument && argument.getOwner() == &entry) + { + parameters[op.getResult(0)] = argument.getArgNumber(); + if (argument.getArgNumber() == 0) + { + thisSlot = op.getResult(0); + } + } + } + + if (!thisSlot) + { + return kept; + } + + // `this` only read, and only for its fields, which are only read or written + llvm::DenseMap stores; + llvm::SmallVector candidates; + for (auto *user : thisSlot.getUsers()) + { + auto loadOp = mlir::dyn_cast(user); + if (!loadOp) + { + return kept; + } + + for (auto *loadUser : loadOp->getUsers()) + { + auto propertyRefOp = mlir::dyn_cast(loadUser); + if (!propertyRefOp) + { + return kept; + } + + for (auto *refUser : propertyRefOp->getUsers()) + { + auto storeOp = mlir::dyn_cast(refUser); + auto releaseSlotOp = mlir::dyn_cast(refUser); + if (storeOp && storeOp.getReference() == propertyRefOp.getResult()) + { + stores[propertyRefOp.getPosition()]++; + candidates.push_back(storeOp); + continue; + } + + // `this.values.push(0.0)`: a write of that array field, and of nothing else + if (mlir::isa(refUser) && refUser->getOperand(0) == propertyRefOp.getResult()) + { + stores[propertyRefOp.getPosition()]++; + continue; + } + + if (!mlir::isa(refUser) && !(releaseSlotOp && releaseSlotOp.getSlot() == propertyRefOp.getResult())) + { + return kept; + } + } + } + } + + for (auto storeOp : candidates) + { + auto propertyRefOp = storeOp.getReference().getDefiningOp(); + auto loadOp = stripViews(storeOp.getValue()).getDefiningOp(); + if (storeOp->getBlock() != &entry || stores[propertyRefOp.getPosition()] != 1 || !loadOp) + { + continue; + } + + auto parameter = parameters.find(loadOp.getReference()); + if (parameter == parameters.end() || parameter->second == 0 || + llvm::any_of(loadOp.getReference().getUsers(), [](mlir::Operation *user) { return mlir::isa(user); })) + { + continue; + } + + kept[parameter->second] = {static_cast(propertyRefOp.getPosition()), propertyRefOp.getType()}; + } + + return kept; + } + // One local and one field: where the local holds what the field holds, a must-analysis over // the function's blocks. It starts to hold where the local is declared from a read of the // field, or where the field is given a read of the local; it stops at a store into the local, @@ -372,6 +477,9 @@ namespace own_signature // move takes it over. // The stores in nested regions count too (`if (ok) { this.f = v; use(v); }`). mlir::DominanceInfo dominance(body->getParentOp()); + // where each value moved by the steps below lives after the move: the move, and the read + // of its new place made right after it + llvm::DenseMap>> movedTo; llvm::SmallVector movedStores; body->walk([&](mlir_ts::StoreOp storeOp) { auto field = storeOp.getReference().getDefiningOp(); @@ -412,11 +520,8 @@ namespace own_signature } } - if (uses.empty()) - { - continue; - } - + // made even with no use left: an argument kept by this object may read through it + // (below); unused, it goes at the end mlir::OpBuilder builder(fieldStore->getContext()); builder.setInsertionPointAfter(fieldStore); auto read = readFieldAt(builder, fieldStore.getLoc(), narrowed ? fieldType : root.getType(), field); @@ -429,6 +534,8 @@ namespace own_signature { use->set(read); } + + movedTo[root].push_back({fieldStore.getOperation(), read}); } // The same for a value pushed into an array that is a field (TSLANG 52): `this.textures.push( @@ -472,11 +579,6 @@ namespace own_signature } } - if (uses.empty()) - { - continue; - } - auto location = pushOp.getLoc(); mlir::OpBuilder builder(pushOp->getContext()); builder.setInsertionPointAfter(pushOp); @@ -498,6 +600,165 @@ namespace own_signature { use->set(read); } + + movedTo[root].push_back({pushOp.getOperation(), read}); + } + + // A value of the function's own given to a constructor that keeps it in a field + // (TSLANG 53): `const app = new App(sample); sample.use();`, or the object pushed on + // (`this.frames.push(new Frame(viewSet)); viewSet.update(...)`). After the call the + // value is the object's field, so each use the call dominates reads that field - through + // the object itself, or through the place it was moved to last, as the steps above made + // it: a borrow of the field, followed through the calls between. + // the constructor calls: `ts.SymbolCallInternal(object, args...)` naming it, or a call of + // the method bound to the object; their operands are the object, then the parameters + struct Construction + { + mlir::Operation *call; + llvm::StringRef callee; + llvm::SmallVector operands; + }; + llvm::SmallVector constructions; + body->walk([&](mlir::Operation *op) { + if (auto callOp = mlir::dyn_cast(op)) + { + constructions.push_back({op, callOp.getCallee(), llvm::to_vector(callOp.getCallOperands())}); + } + else if (auto callOp = mlir::dyn_cast(op)) + { + auto getMethodOp = callOp.getCallee().getDefiningOp(); + auto symbolRefOp = getMethodOp ? getMethodOp.getBoundFunc().getDefiningOp() : mlir_ts::ThisSymbolRefOp(); + if (symbolRefOp && callOp.getCallOperands().size() >= 1) + { + llvm::SmallVector operands{symbolRefOp.getThisVal()}; + operands.append(callOp.getCallOperands().begin() + 1, callOp.getCallOperands().end()); + constructions.push_back({op, symbolRefOp.getIdentifier(), operands}); + } + } + }); + + for (auto &construction : constructions) + { + auto *callOp = construction.call; + auto object = construction.operands.empty() ? mlir::Value() : construction.operands.front(); + if (!object || !object.getDefiningOp() || !construction.callee.ends_with(".constructor")) + { + continue; + } + + auto ctor = module.lookupSymbol(construction.callee); + if (!ctor) + { + continue; + } + + auto &operands = construction.operands; + for (auto &[number, kept] : keptParameters(ctor)) + { + if (number >= operands.size()) + { + continue; + } + + auto root = stripViews(operands[number]); + auto *def = root.getDefiningOp(); + auto fieldRefType = mlir::cast(kept.second); + auto fieldType = fieldRefType.getElementType(); + auto narrowed = fieldType != root.getType() && mlir::isa(root.getType()) && + mlir::isa(fieldType); + if (!def || mlir::isa(def) || !own_facts::ownsHeap(root) || + own_facts::isCopyableValueAt(callOp, root.getType()) || MLIRTypeHelper::isSharedHandleType(root.getType()) || + (fieldType != root.getType() && !narrowed)) + { + continue; + } + + // each use read through the object's latest place before it: the last move + // of the object that the use comes after, else the object right after the call + llvm::DenseMap reads; + llvm::SmallVector uses; + // the object's own releases: a use after one, in its block, would read a freed field + llvm::SmallVector releases; + for (auto *user : object.getUsers()) + { + if (mlir::isa(user)) + { + releases.push_back(user); + } + } + + auto afterRelease = [&](mlir::Operation *user) { + return llvm::any_of(releases, [&](mlir::Operation *release) { + auto *ancestor = release->getBlock()->findAncestorOpInBlock(*user); + return ancestor && release->isBeforeInBlock(ancestor); + }); + }; + + for (auto &use : root.getUses()) + { + if (!mlir::isa(use.getOwner()) && dominance.properlyDominates(callOp, use.getOwner()) && + !afterRelease(use.getOwner())) + { + uses.push_back(&use); + } + } + + for (auto *use : uses) + { + auto *user = use->getOwner(); + mlir::Operation *after = callOp; + mlir::Value place = object; + for (auto &[move, read] : movedTo.lookup(object)) + { + if (dominance.properlyDominates(move, user) && dominance.properlyDominates(after, move)) + { + after = read.getDefiningOp(); + place = read; + } + } + + auto &fieldRead = reads[place]; + if (!fieldRead) + { + mlir::OpBuilder builder(callOp->getContext()); + builder.setInsertionPointAfter(after); + auto ref = builder.create(callOp->getLoc(), fieldRefType, place, + builder.getI32IntegerAttr(kept.first)); + fieldRead = builder.create(callOp->getLoc(), fieldType, ref); + if (narrowed) + { + fieldRead = builder.create(callOp->getLoc(), root.getType(), fieldRead); + } + } + + use->set(fieldRead); + } + } + } + + // the reads of a moved value's new place nothing uses + for (auto &[value, moves] : movedTo) + { + for (auto &[move, read] : moves) + { + llvm::SmallVector dead{read.getDefiningOp()}; + while (!dead.empty()) + { + auto *op = dead.pop_back_val(); + if (!op || !op->use_empty() || !mlir::isa(op)) + { + continue; + } + + for (auto operand : op->getOperands()) + { + dead.push_back(operand.getDefiningOp()); + } + + op->erase(); + } + } } // the pairs: a local not captured, and a field it is declared from or that is given it diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 30b08ee32..ee8f62ea1 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -1906,9 +1906,10 @@ endforeach() # TSLANG_ISSUES 49: a nullable local moved when not null, a virtual call's own result, a field moved into another # TSLANG_ISSUES 50: a value moved into a field and used after is a borrow of the field # TSLANG_ISSUES 52: a value pushed into a field array and used after is a borrow of its last element +# TSLANG_ISSUES 53: a value a constructor keeps in a field, used after, is a borrow of that field foreach(issues_mm gc rc none own) foreach(issues_test 00tslang_issue_44 00tslang_issue_45 00tslang_issue_46 00tslang_issue_47 00tslang_issue_48 00tslang_issue_49 00tslang_issue_50 - 00tslang_issue_52) + 00tslang_issue_52 00tslang_issue_53) tslang_add_test(NAME test-jit-${issues_test}-${issues_mm} COMMAND test-runner -jit -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/${issues_test}.ts") tslang_add_test(NAME test-compile-${issues_test}-${issues_mm} COMMAND test-runner -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/${issues_test}.ts") endforeach() @@ -5453,7 +5454,8 @@ set(own_error_cases "own_err_override_lends|:13:5: error: method 'read' returns a borrow .* but the method of 'Base' it overrides does not" "own_err_moved_field_overwritten|:15:25: error: '[^']*' borrows a field but is used here after it may be released or overwritten" "own_err_moved_param_field_dropped|:13:15: error: '[^']*' borrows a field but is used here after it may be released or overwritten" - "own_err_pushed_then_popped|:14:16: error: '[^']*' borrows an element but is used here after it may be released or overwritten") + "own_err_pushed_then_popped|:14:16: error: '[^']*' borrows an element but is used here after it may be released or overwritten" + "own_err_kept_by_constructor_reset|:16:11: error: '[^']*' borrows a field but is used here after it may be released or overwritten") foreach(own_error_case ${own_error_cases}) string(FIND "${own_error_case}" "|" own_error_sep) string(SUBSTRING "${own_error_case}" 0 ${own_error_sep} own_error_name) diff --git a/tslang/test/tester/own/own_err_kept_by_constructor_reset.ts b/tslang/test/tester/own/own_err_kept_by_constructor_reset.ts new file mode 100644 index 000000000..a5d5f7c5c --- /dev/null +++ b/tslang/test/tester/own/own_err_kept_by_constructor_reset.ts @@ -0,0 +1,17 @@ +// TSLANG_ISSUES 53: a value given to a constructor that keeps it in a field is that field after the +// call - but a method of the object that overwrites the field frees it, so the use after is refused. +class S { + n: int = 4; +} + +class App { + constructor(public s: S) {} + reset() { this.s = new S(); } +} + +function main() { + const s = new S(); + const app = new App(s); + app.reset(); + print(s.n); +} diff --git a/tslang/test/tester/tests/00tslang_issue_53.ts b/tslang/test/tester/tests/00tslang_issue_53.ts new file mode 100644 index 000000000..6ba2fd1b1 --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_53.ts @@ -0,0 +1,79 @@ +// TSLANG_ISSUES 53 (-mm=own), from native_ts_graphics' examples: a value of the function's own +// given to a constructor that keeps it in a field, then used. +// - `const sample = new Sample(); const app = new App(sample); sample.add(10);` (each example's main) +// - the object pushed on: `this.frames.push(new Frame(a, b)); a.update(...)` (deferred_shading_nri) +// After the call the value is the object's field, read through the object or the place it was moved +// to last. + +class Sample { + n: int = 0; + add(k: int) { + this.n += k; + } +} + +class App { + items: int[] = []; + // pushing into another field of its own keeps `sample` where it is + constructor(private sample: Sample) { + for (let i = 0; i < 3; i++) { + this.items.push(i); + } + } + run(): int { + this.sample.add(1); + return this.sample.n; + } +} + +class Set1 { + k: int = 0; + update(v: int) { + this.k = v; + } +} + +class Frame { + constructor(public a: Set1 | null, public b: Set1 | null) {} +} + +@final +class Pool { + alloc(fail: boolean): Set1 | null { + return fail ? null : new Set1(); + } +} + +export class Renderer { + frames: Frame[] = []; + init(pool: Pool): boolean { + for (let i = 0; i < 2; i++) { + const a = pool.alloc(false); + const b = pool.alloc(false); + this.frames.push(new Frame(a, b)); + if (!a || !b) { + return false; + } + + a.update(i + 1); + b.update(i + 10); + } + + return true; + } +} + +function main() { + const sample = new Sample(); + const app = new App(sample); + sample.add(10); + const n = app.run(); + print(n, sample.n); + assert(n == 11 && sample.n == 11); + + const r = new Renderer(); + assert(r.init(new Pool())); + print(r.frames[1].a!.k, r.frames[1].b!.k); + assert(r.frames[0].a!.k == 1 && r.frames[1].b!.k == 11); + print("done."); +}