From 130ee7163978fa22abdb4f6e5fbd58353e82af62 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Fri, 30 Oct 2026 16:21:58 +0000 Subject: [PATCH 1/2] -mm=own: a read through an interface field filled by a getter is freed Under own a read through an interface field is a borrow (spec 28). When a class fills the field with a getter, the read is instead the getter's result, a fresh value nothing else holds, and it was never freed: two million reads kept two million objects (617 MB). Own already rejects a getter that returns a field, so every getter read there was a leak. - MLIRGen marks such a read (__own_cell_read) plus an id of its own, so CSE cannot fold two reads into one freed twice. - After own's inference (releaseCellReads), a read whose value, and what is borrowed from it, stays in its block gets a ts.Release after its last use. An unused read, which an assignment `i.f = v` leaves, is erased. - ReleaseOpLowering frees it only when the slot names a cell of accessors; through a plain field the read stays a borrow and nothing is freed. A read that escapes (returned, stored, put in a `let`) gets no release and still leaks on the getter's path. Co-Authored-By: Claude Opus 5.5 --- tslang/include/TypeScript/Defines.h | 7 + tslang/lib/TypeScript/LowerToLLVM.cpp | 75 +++++++---- tslang/lib/TypeScript/MLIRGenImpl.h | 8 ++ .../lib/TypeScript/OwnershipInferencePass.cpp | 126 +++++++++++++++++- .../lib/TypeScript/OwnershipInferencePass.h | 5 + tslang/test/tester/CMakeLists.txt | 11 +- .../tester/own/own_interface_getter_read.ts | 102 ++++++++++++++ 7 files changed, 304 insertions(+), 30 deletions(-) create mode 100644 tslang/test/tester/own/own_interface_getter_read.ts diff --git a/tslang/include/TypeScript/Defines.h b/tslang/include/TypeScript/Defines.h index d7692621b..d1cfec7e7 100644 --- a/tslang/include/TypeScript/Defines.h +++ b/tslang/include/TypeScript/Defines.h @@ -74,6 +74,13 @@ // reference taken, two given back. The number makes no two of them alike. #define OWNED_READ_ID_ATTR_NAME "__owned_read" +// -mm=own. On a read through an interface's field that may be filled by a getter (MLIRGenImpl::InterfaceFieldAccess), +// and on the `ts.Release` OwnershipInferencePass gives it when nothing it read escapes its block +// (releaseCellReads). Through a plain slot the read is a borrow, as any field read is (spec 28); through a cell of +// accessors it is the getter's result, a value of its own that nothing else holds. The release frees it on that +// path only (ReleaseOpLowering). A read that escapes is not given one, and leaks on the getter's path. +#define OWN_CELL_READ_ATTR_NAME "__own_cell_read" + // Marks a release MLIRGen put at the end of a hand-written `finally` for the exceptional leg only: // what the scopes around the `try` owe once the exception carries on past it. The finally region // is one region in MLIRGen but several copies after TryOpLowering - the copy the landing pad runs diff --git a/tslang/lib/TypeScript/LowerToLLVM.cpp b/tslang/lib/TypeScript/LowerToLLVM.cpp index 4839df2a4..5bd985971 100644 --- a/tslang/lib/TypeScript/LowerToLLVM.cpp +++ b/tslang/lib/TypeScript/LowerToLLVM.cpp @@ -520,34 +520,6 @@ class RetainOpLowering : public TsLlvmPattern } }; -class ReleaseOpLowering : public TsLlvmPattern -{ - public: - using TsLlvmPattern::TsLlvmPattern; - - LogicalResult matchAndRewrite(mlir_ts::ReleaseOp op, Adaptor transformed, - ConversionPatternRewriter &rewriter) const final - { - if (tsLlvmContext->compileOptions.tracksOwnership()) - { - OwnershipRoutineLogic orl(op, rewriter, getTypeConverter(), tsLlvmContext->compileOptions); - // an array that only borrowed its elements (-mm=own's classifyArgumentArrays) - auto arrayType = dyn_cast(op.getReference().getType()); - if (arrayType && op->hasAttr(OWN_SHALLOW_RELEASE_ATTR_NAME)) - { - orl.emitReleaseArrayShallow(arrayType, transformed.getReference()); - } - else - { - orl.emitReleaseValue(op.getReference().getType(), transformed.getReference()); - } - } - - rewriter.eraseOp(op); - return mlir::success(); - } -}; - // A promoted object's fields given back without freeing the object, and with `reset` the object // zeroed - a fresh one where its allocation was. class ReleaseContentsOpLowering : public TsLlvmPattern @@ -680,6 +652,53 @@ struct InterfaceAccessorCell } }; +class ReleaseOpLowering : public TsLlvmPattern +{ + public: + using TsLlvmPattern::TsLlvmPattern; + + LogicalResult matchAndRewrite(mlir_ts::ReleaseOp op, Adaptor transformed, + ConversionPatternRewriter &rewriter) const final + { + if (tsLlvmContext->compileOptions.tracksOwnership()) + { + OwnershipRoutineLogic orl(op, rewriter, getTypeConverter(), tsLlvmContext->compileOptions); + // an array that only borrowed its elements (-mm=own's classifyArgumentArrays) + auto arrayType = dyn_cast(op.getReference().getType()); + if (arrayType && op->hasAttr(OWN_SHALLOW_RELEASE_ATTR_NAME)) + { + orl.emitReleaseArrayShallow(arrayType, transformed.getReference()); + } + else if (op->hasAttr(OWN_CELL_READ_ATTR_NAME)) + { + // -mm=own: a read through an interface's field is freed only when a getter made it + auto loadOp = op.getReference().getDefiningOp(); + if (auto accessorCell = loadOp ? InterfaceAccessorCell::of(loadOp.getReference(), rewriter, + tsLlvmContext->compileOptions) + : std::nullopt) + { + CodeLogicHelper clh(op, rewriter); + clh.conditionalBlocksLowering( + accessorCell->isCell, + [&](OpBuilder &, Location) -> ValueRange { + orl.emitReleaseValue(op.getReference().getType(), transformed.getReference()); + return ValueRange{}; + }, + [&](OpBuilder &, Location) -> ValueRange { return ValueRange{}; }); + } + } + else + { + orl.emitReleaseValue(op.getReference().getType(), transformed.getReference()); + } + } + + rewriter.eraseOp(op); + return mlir::success(); + } +}; + + // The slot-addressed forms. Same erasure rule, and erasing one of these takes the whole // access with it - there is no load to leave behind in a collected build. class RetainSlotOpLowering : public TsLlvmPattern diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 498525646..4a0659688 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -9404,6 +9404,14 @@ class MLIRGenImpl value.getDefiningOp()->setAttr(OWNED_RESULT_ATTR_NAME, builder.getUnitAttr()); value.getDefiningOp()->setAttr(OWNED_READ_ID_ATTR_NAME, builder.getI32IntegerAttr(++ownedReads)); } + + // under own the read stays a borrow, and is freed afterwards only if a getter made it (OWN_CELL_READ_ATTR_NAME) + if (compileOptions.memoryModel == MemoryModelOwn && !isa(fieldInfo->type) && + mth.ownsHeapMemory(location, fieldInfo->type)) + { + value.getDefiningOp()->setAttr(OWN_CELL_READ_ATTR_NAME, builder.getUnitAttr()); + value.getDefiningOp()->setAttr(OWNED_READ_ID_ATTR_NAME, builder.getI32IntegerAttr(++ownedReads)); + } } else { diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.cpp b/tslang/lib/TypeScript/OwnershipInferencePass.cpp index a4ccb6f77..7dcf70123 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePass.cpp @@ -2,6 +2,7 @@ // its retains decided and erased, string copies made. #include "OwnershipInferencePass.h" +#include "TypeScript/TypeScriptPassContext.h" #define DEBUG_TYPE "own" @@ -48,7 +49,130 @@ namespace own_inference } llvm::SetVector toErase; - analyze(toErase); + if (analyze(toErase)) + { + releaseCellReads(); + } + } + + // Does nothing `value` gives - its own value, a field read out of it, a call's result that may be it - leave + // `block`? Then the last of them that uses it is collected into `last`. A scalar is not followed: it is a copy. + static bool staysInBlock(mlir::Value value, mlir::Block *block, mlir::Operation *&last, int depth = 0) + { + auto isScalar = [](mlir::Type type) { + return mlir::isa(type); + }; + + auto follow = [&](mlir::Value result) { + return isScalar(result.getType()) || staysInBlock(result, block, last, depth + 1); + }; + + if (depth > 8) + { + return false; + } + + for (auto *user : value.getUsers()) + { + if (user->getBlock() != block) + { + return false; + } + + if (!last || last->isBeforeInBlock(user)) + { + last = user; + } + + if (mlir::isa(user)) + { + continue; + } + + // a field of it: what is read from the field is borrowed from it too + if (mlir::isa(user)) + { + for (auto *refUser : user->getResult(0).getUsers()) + { + if (refUser->getBlock() != block) + { + return false; + } + + if (last->isBeforeInBlock(refUser)) + { + last = refUser; + } + + auto loadOp = mlir::dyn_cast(refUser); + if (!loadOp || !follow(loadOp.getResult())) + { + return false; + } + } + + continue; + } + + // an argument: the result may be it, or borrowed from it + auto callIndirectOp = mlir::dyn_cast(user); + if ((mlir::isa(user) || callIndirectOp) && + (!callIndirectOp || callIndirectOp.getCallee() != value)) + { + for (auto result : user->getResults()) + { + if (!follow(result)) + { + return false; + } + } + + continue; + } + + if (mlir::isa(user) && + user->getNumResults() == 1 && follow(user->getResult(0))) + { + continue; + } + + return false; + } + + return true; + } + + void OwnershipInferencePass::releaseCellReads() + { + llvm::SmallVector reads; + getFunction()->walk([&](mlir_ts::LoadOp loadOp) { + if (loadOp->hasAttr(OWN_CELL_READ_ATTR_NAME) && isInterfaceAccessorCellRef(loadOp.getReference())) + { + reads.push_back(loadOp); + } + }); + + for (auto loadOp : reads) + { + if (loadOp->use_empty()) + { + loadOp->erase(); + continue; + } + + mlir::Operation *last = nullptr; + if (!staysInBlock(loadOp.getResult(), loadOp->getBlock(), last) || !last || + last->hasTrait()) + { + continue; + } + + mlir::OpBuilder builder(last->getContext()); + builder.setInsertionPointAfter(last); + auto releaseOp = builder.create(loadOp.getLoc(), loadOp.getResult()); + releaseOp->setAttr(OWN_CELL_READ_ATTR_NAME, builder.getUnitAttr()); + } } bool OwnershipInferencePass::analyze(llvm::SetVector &toErase) diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.h b/tslang/lib/TypeScript/OwnershipInferencePass.h index 7eeae7a77..922b73434 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.h +++ b/tslang/lib/TypeScript/OwnershipInferencePass.h @@ -80,6 +80,11 @@ class OwnershipInferencePass void runOnFunction(); + // A read through an interface's field that a getter may have made (OWN_CELL_READ_ATTR_NAME), whose value and + // what is borrowed from it stay in its block: a release after their last use, for the getter's path only. One + // nothing uses - what an assignment `i.f = v` leaves of the place it wrote - goes. + void releaseCellReads(); + // The analysis of one function; true when it passed. In a dry run it erases nothing and strips // no facts. bool analyze(llvm::SetVector &toErase); diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 574e5964b..0c38f3bc2 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -4071,7 +4071,7 @@ foreach(own_test own_fresh_string own_fresh_array own_return_new own_try_local o own_param_markers own_generator_locals own_string_param_assigned own_lends own_immortal_global own_immortal_global_region own_global_loop_store own_literal_moves own_record_literal_given - own_field_chain_let own_read_after_move own_conditional_move + own_field_chain_let own_interface_getter_read own_read_after_move own_conditional_move own_interface_facts own_declared_scalar_no_drops own_borrowing_record own_borrowing_record_arg own_reduce own_fresh_call_result own_ternary_outer_loop own_destructure_elements @@ -4189,6 +4189,15 @@ add_test(NAME test-own-caught-value-call set_tests_properties(test-own-caught-value-call PROPERTIES PASS_REGULAR_EXPRESSION "ts.Func" FAIL_REGULAR_EXPRESSION "error|Stack dump") +# A read through an interface field a getter may fill is freed after its last use under own, on the +# getter's path only (own_interface_getter_read.ts): the release is placed by inference. +add_test(NAME test-own-interface-getter-read-released + COMMAND $ --emit=mlir-affine --no-default-lib -mm=own + "${PROJECT_SOURCE_DIR}/test/tester/own/own_interface_getter_read.ts") +set_tests_properties(test-own-interface-getter-read-released + PROPERTIES PASS_REGULAR_EXPRESSION "\"ts[.]Release\"[(]%[0-9]+[)] {__own_cell_read}" + FAIL_REGULAR_EXPRESSION "error|Stack dump") + # A field read through an interface is a place read under own (spec 28); the same program under # every other model. foreach(field_chain_mm rc gc none) diff --git a/tslang/test/tester/own/own_interface_getter_read.ts b/tslang/test/tester/own/own_interface_getter_read.ts new file mode 100644 index 000000000..e517f9633 --- /dev/null +++ b/tslang/test/tester/own/own_interface_getter_read.ts @@ -0,0 +1,102 @@ +// -mm=own: a read through an interface's field a class fills with a getter is the getter's result, a value +// nothing else holds; through a plain field the same read is a borrow (spec 28). It was never freed: reading +// `i.item` two million times kept two million Boxes (617 MB). Now a read whose value - and what is borrowed +// from it - stays in its block is released after its last use, on the getter's path only +// (OwnershipInferencePass::releaseCellReads, ReleaseOpLowering). A read that escapes - returned, stored, put +// in a `let` - is not, and still leaks on the getter's path. A getter returning a field is rejected under own, +// so only fresh values come through a getter here. Values are read after churn() has reused anything freed +// too early. +class Box { + data: number[] = [1, 2, 3]; + constructor(public n: number) {} +} + +interface I { + item: Box; +} + +class Fresh implements I { + private k = 0; + get item() { this.k = this.k + 1; return new Box(10 * this.k); } + set item(x: Box) { this.k = x.n; } +} + +class Plain implements I { + item = new Box(2); +} + +function churn() { + const junk: Box[] = []; + for (let i = 0; i < 64; i++) { + junk.push(new Box(999)); + } +} + +function asTemporary(i: I) { + return i.item.n + i.item.data.length; +} + +function folded(i: I) { + const x = i.item; + churn(); + return x.n + x.data.length; +} + +function use(b: Box) { + churn(); + return b.n; +} + +function asArgument(i: I) { + return use(i.item); +} + +function both(a: Box, b: Box) { + return a.n + b.n; +} + +// the same field read twice, alike: CSE must not make them one read freed twice +function readTwice(i: I) { + let total: number = 0; + for (let k = 0; k < 1000; k++) { + total = total + both(i.item, i.item); + } + + return total; +} + +function inLoop(i: I) { + let total: number = 0; + for (let k = 0; k < 100; k++) { + total = total + i.item.data.length; + } + + return total; +} + +function main() { + const f: I = new Fresh(); + const p: I = new Plain(); + + assert(asTemporary(f) == 13, "fresh objects read as temporaries"); + assert(asTemporary(p) == 5, "a plain field read as a temporary"); + + assert(folded(f) == 33, "a fresh object read into a const"); + assert(folded(p) == 5, "a plain field read into a const"); + + assert(asArgument(f) == 40, "a fresh object passed on"); + assert(asArgument(p) == 2, "a plain field passed on"); + + assert(inLoop(f) == 300, "fresh objects read in a loop"); + assert(inLoop(p) == 300, "a plain field read in a loop"); + + assert(readTwice(p) == 4000, "a plain field read twice"); + churn(); + assert(p.item.n == 2, "the plain field is still there"); + + // an assignment calls the setter only, not the getter: the next read is 10 * (7 + 1) + f.item = new Box(7); + assert(f.item.n == 80, "an assignment does not read the field"); + + print("done."); +} From eae14ddbaec325d9fb39fc04503d1b73f197853f Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Fri, 30 Oct 2026 16:26:10 +0000 Subject: [PATCH 2/2] VS Code launch configurations: run the selected CMake target; drop stale test entries Co-Authored-By: Claude Opus 5.5 --- tslang/test/.vscode/launch.json | 62 +------------------------------ tslang/tslang/.vscode/launch.json | 10 +++++ 2 files changed, 11 insertions(+), 61 deletions(-) diff --git a/tslang/test/.vscode/launch.json b/tslang/test/.vscode/launch.json index faa9e7e01..b8d2d8476 100644 --- a/tslang/test/.vscode/launch.json +++ b/tslang/test/.vscode/launch.json @@ -4,65 +4,5 @@ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ - { - "name": "(Windows) test-runner.exe - Launch (JIT - Shared)", - "type": "cppvsdbg", - "request": "launch", - "program": "${workspaceFolder}/../../__build/tslang/windows-msbuild-2026-debug/test/tester/Debug/test-runner.exe", - "args": ["-shared", "-jit", "${workspaceFolder}/../../tslang/test/tester/tests/use_shared.ts", "${workspaceFolder}/../../tslang/test/tester/tests/shared.ts"], - "stopAtEntry": false, - "cwd": "${workspaceFolder}/../../__build/tslang/windows-msbuild-2026-debug/test/tester/Debug/", - "environment": [], - "externalConsole": true, - "visualizerFile": "${workspaceFolder}/../tslang.natvis" - }, - { - "name": "(Windows) test-runner.exe - Launch (Compile - Shared)", - "type": "cppvsdbg", - "request": "launch", - "program": "${workspaceFolder}/../../__build/tslang/windows-msbuild-2026-debug/test/tester/Debug/test-runner.exe", - "args": ["-shared", "${workspaceFolder}/../../tslang/test/tester/tests/emit_class.ts", "${workspaceFolder}/../../tslang/test/tester/tests/decl_class.ts"], - "stopAtEntry": false, - "cwd": "${workspaceFolder}/../../__build/tslang/windows-msbuild-2026-debug/test/tester/Debug/", - "environment": [], - "externalConsole": true, - "visualizerFile": "${workspaceFolder}/../tslang.natvis" - }, - { - "name": "(Windows) test-runner.exe - Launch (Compile - Shared - Gctors-as-method)", - "type": "cppvsdbg", - "request": "launch", - "program": "${workspaceFolder}/../../__build/tslang/windows-msbuild-2026-debug/test/tester/Debug/test-runner.exe", - "args": ["-shared", "-gctors-as-method", "${workspaceFolder}/../../tslang/test/tester/tests/import_object_literal_with_interface.ts ", "${workspaceFolder}/../../tslang/test/tester/tests/export_object_literal_with_interface.ts"], - "stopAtEntry": false, - "cwd": "${workspaceFolder}/../../__build/tslang/windows-msbuild-2026-debug/test/tester/Debug/", - "environment": [], - "externalConsole": true, - "visualizerFile": "${workspaceFolder}/../tslang.natvis" - }, - { - "name": "(Windows) test-runner.exe - Launch (Compile-Time)", - "type": "cppvsdbg", - "request": "launch", - "program": "${workspaceFolder}/../../__build/tslang/windows-msbuild-2026-debug/test/tester/Debug/test-runner.exe", - "args": ["-shared", "-compile-time", "${workspaceFolder}/../../tslang/test/tester/tests/emit_compiletime_class.ts", "${workspaceFolder}/../../tslang/test/tester/tests/decl_class.ts"], - "stopAtEntry": false, - "cwd": "${workspaceFolder}/../../__build/tslang/windows-msbuild-2026-debug/test/tester/Debug/", - "environment": [], - "externalConsole": true, - "visualizerFile": "${workspaceFolder}/../tslang.natvis" - }, - { - "name": "(Windows) printer-tester.exe - Launch", - "type": "cppvsdbg", - "request": "launch", - "program": "${workspaceFolder}/../../__build/tslang/windows-msbuild-2026-debug/test/print-tester/Debug/printer-tester.exe", - "args": ["c:\\temp\\dll.ts", "declare"], - "stopAtEntry": false, - "cwd": "${workspaceFolder}", - "environment": [], - "externalConsole": true, - "visualizerFile": "${workspaceFolder}/../tslang.natvis" - } - ] + ] } \ No newline at end of file diff --git a/tslang/tslang/.vscode/launch.json b/tslang/tslang/.vscode/launch.json index 2fe523650..1683137b7 100644 --- a/tslang/tslang/.vscode/launch.json +++ b/tslang/tslang/.vscode/launch.json @@ -4,6 +4,16 @@ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ + { + "name": "Run selected CMake target", + "type": "cppvsdbg", // MSVC debugger; use "cppdbg" for gdb/lldb + "request": "launch", + "program": "${command:cmake.launchTargetPath}", + "args": [ + ], + "cwd": "${command:cmake.launchTargetDirectory}", + "environment": [] + }, { "name": "(Windows) tslang.exe - DUMP", "type": "cppvsdbg",