Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions tslang/include/TypeScript/Defines.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
75 changes: 47 additions & 28 deletions tslang/lib/TypeScript/LowerToLLVM.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -520,34 +520,6 @@ class RetainOpLowering : public TsLlvmPattern<mlir_ts::RetainOp>
}
};

class ReleaseOpLowering : public TsLlvmPattern<mlir_ts::ReleaseOp>
{
public:
using TsLlvmPattern<mlir_ts::ReleaseOp>::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<mlir_ts::ArrayType>(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<mlir_ts::ReleaseContentsOp>
Expand Down Expand Up @@ -680,6 +652,53 @@ struct InterfaceAccessorCell
}
};

class ReleaseOpLowering : public TsLlvmPattern<mlir_ts::ReleaseOp>
{
public:
using TsLlvmPattern<mlir_ts::ReleaseOp>::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<mlir_ts::ArrayType>(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<mlir_ts::LoadOp>();
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<mlir_ts::RetainSlotOp>
Expand Down
8 changes: 8 additions & 0 deletions tslang/lib/TypeScript/MLIRGenImpl.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<mlir_ts::FunctionType>(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
{
Expand Down
126 changes: 125 additions & 1 deletion tslang/lib/TypeScript/OwnershipInferencePass.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// its retains decided and erased, string copies made.

#include "OwnershipInferencePass.h"
#include "TypeScript/TypeScriptPassContext.h"

#define DEBUG_TYPE "own"

Expand Down Expand Up @@ -48,7 +49,130 @@ namespace own_inference
}

llvm::SetVector<mlir::Operation *> 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<mlir_ts::NumberType, mlir_ts::BooleanType, mlir::IntegerType, mlir::IndexType,
mlir::FloatType>(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<mlir_ts::LengthOfOp, mlir_ts::PrintOp>(user))
{
continue;
}

// a field of it: what is read from the field is borrowed from it too
if (mlir::isa<mlir_ts::PropertyRefOp, mlir_ts::InterfaceSymbolRefOp>(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<mlir_ts::LoadOp>(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<mlir_ts::CallIndirectOp>(user);
if ((mlir::isa<mlir_ts::SymbolCallInternalOp>(user) || callIndirectOp) &&
(!callIndirectOp || callIndirectOp.getCallee() != value))
{
for (auto result : user->getResults())
{
if (!follow(result))
{
return false;
}
}

continue;
}

if (mlir::isa<mlir_ts::LogicalBinaryOp, mlir_ts::ArithmeticBinaryOp, mlir_ts::CastOp>(user) &&
user->getNumResults() == 1 && follow(user->getResult(0)))
{
continue;
}

return false;
}

return true;
}

void OwnershipInferencePass::releaseCellReads()
{
llvm::SmallVector<mlir_ts::LoadOp> 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<mlir::OpTrait::IsTerminator>())
{
continue;
}

mlir::OpBuilder builder(last->getContext());
builder.setInsertionPointAfter(last);
auto releaseOp = builder.create<mlir_ts::ReleaseOp>(loadOp.getLoc(), loadOp.getResult());
releaseOp->setAttr(OWN_CELL_READ_ATTR_NAME, builder.getUnitAttr());
}
}

bool OwnershipInferencePass::analyze(llvm::SetVector<mlir::Operation *> &toErase)
Expand Down
5 changes: 5 additions & 0 deletions tslang/lib/TypeScript/OwnershipInferencePass.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<mlir::Operation *> &toErase);
Expand Down
62 changes: 1 addition & 61 deletions tslang/test/.vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
]
]
}
11 changes: 10 additions & 1 deletion tslang/test/tester/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 $<TARGET_FILE:tslang> --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)
Expand Down
Loading
Loading