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
Original file line number Diff line number Diff line change
Expand Up @@ -5375,6 +5375,28 @@ and a `Load` of each field: a method bound to the literal) and makes the paramet
object-type parameter, calls a member after, gives the literal again and to an interface, churning
between steps, under own, rc, gc and none.

Not here: a literal whose arrow captures an object (`const b = new Box(5); const q = { w: (x: number) =>
x * b.n }`) moves the object into the literal's `.captured`, so `b` cannot be used after it under own,
where a closure capturing it only borrows it (§16).
Not here: a literal whose arrow captures an object; see spec 67.

## 67. An object literal whose arrows capture an object, 2026-10-29

`const b = new Box(5); const q = { w: (x: number) => x * b.n }; q.w(1); b.n` was `'this value' is used
here after its value was moved`: the literal's `.captured` box took `b` (a copy of a `const`), where a
closure capturing it that does not escape only borrows it (§16). MLIRGen gives the literal no release,
and rc no reference of the box's own for it that the literal gives back: the box only ever borrowed.

- **A literal's box** (`classifyLiteralCaptures`): a capture box (`__capture_box`) filled field by field
and stored once into the `.captured` field of a local the literal is built in, which is read once into
the object `ts.New` made. rc's `ts.RetainCell`/`ts.ReleaseCell` of the box are its own count.
- **Stays here**: `walkBorrowed` from that object finds nothing that keeps it - its members called, the
literal given to calls that keep it not (an object-type parameter, spec 66). Its uses are the box's.
- **Then the box borrows** each copy whose value has an owner of its own (a named value released here, a
parameter, a local's read; not a cell): the store is a borrow (`OWN_CAPTURE_BORROW_ATTR_NAME`, as a
closure's), rc's retain before it goes (`captureRetains`, erased in `decideClosures`), and whatever
uses the literal is a use of the borrowed value.

`own_literal_object_captures` captures a local object and a parameter, calls members, gives the literal
to an object-type parameter and reads the objects after, churning between steps, under own, rc, gc and
none.

Not here: a literal given to an interface (`apply(q)` for `apply(s: Scaler)`): the cast copies it into
the interface's object, which keeps it, and the object stays moved into the box.
157 changes: 157 additions & 0 deletions tslang/lib/TypeScript/OwnershipInferenceClosures.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,158 @@ namespace own_inference
});
}

void OwnershipInferencePass::classifyLiteralCaptures()
{
getFunction().walk([&](mlir_ts::VariableOp boxOp) {
if (!boxOp->hasAttr(CAPTURE_BOX_ATTR_NAME))
{
return;
}

// filled field by field, and stored once into a literal's `.captured`: `{ w: (x) => x * b.n }`
// builds the literal in a local, then copies it into the object `ts.New` made
llvm::SmallVector<mlir_ts::StoreOp> fills;
mlir_ts::VariableOp literalOp;
for (auto &use : boxOp->getUses())
{
auto *user = use.getOwner();
if (auto propertyRefOp = mlir::dyn_cast<mlir_ts::PropertyRefOp>(user))
{
for (auto *fieldUser : propertyRefOp->getUsers())
{
auto storeOp = mlir::dyn_cast<mlir_ts::StoreOp>(fieldUser);
if (!storeOp || storeOp.getReference() != propertyRefOp.getResult())
{
return;
}

fills.push_back(storeOp);
}

continue;
}

// rc's count of the box, for the literal's reference
if (mlir::isa<mlir_ts::RetainCellOp, mlir_ts::ReleaseCellOp>(user))
{
continue;
}

auto storeOp = mlir::dyn_cast<mlir_ts::StoreOp>(user);
auto fieldOp = storeOp && storeOp.getValue() == boxOp.getResult()
? storeOp.getReference().getDefiningOp<mlir_ts::PropertyRefOp>()
: mlir_ts::PropertyRefOp();
auto ownerOp = fieldOp ? fieldOp.getObjectRef().getDefiningOp<mlir_ts::VariableOp>() : mlir_ts::VariableOp();
auto tupleType = ownerOp ? mlir::dyn_cast<mlir_ts::TupleType>(
mlir::cast<mlir_ts::RefType>(ownerOp.getType()).getElementType())
: mlir_ts::TupleType();
auto fieldName = tupleType && fieldOp.getPosition() < tupleType.size()
? mlir::dyn_cast_or_null<mlir::StringAttr>(tupleType.getFieldInfo(fieldOp.getPosition()).id)
: mlir::StringAttr();
if (literalOp || !fieldName || fieldName.getValue() != CAPTURED_NAME)
{
return;
}

literalOp = ownerOp;
}

if (!literalOp)
{
return;
}

// ...read once, into the object it becomes
llvm::SmallVector<mlir::Value> objects;
for (auto *user : literalOp->getUsers())
{
if (mlir::isa<mlir_ts::PropertyRefOp>(user))
{
continue;
}

auto loadOp = mlir::dyn_cast<mlir_ts::LoadOp>(user);
if (!loadOp || !loadOp.getResult().hasOneUse())
{
return;
}

auto storeOp = mlir::dyn_cast<mlir_ts::StoreOp>(*loadOp.getResult().getUsers().begin());
auto newOp = storeOp ? storeOp.getReference().getDefiningOp<mlir_ts::NewOp>() : mlir_ts::NewOp();
if (!newOp)
{
return;
}

objects.push_back(newOp.getResult());
}

if (objects.size() != 1)
{
return;
}

// the literal stays here: nothing stores, returns, captures or keeps it
auto box = std::make_shared<Closure>();
llvm::SmallVector<BorrowUse> uses;
if (walkBorrowed(objects.front(), {}, uses))
{
return;
}

for (auto &use : uses)
{
box->uses.push_back(use.op);
}

// copies of values with an owner of their own: a named value released here, a parameter, a
// local's; not a cell (a captured `let`), and not one rc retained for the box
auto owned = [&](mlir::Value value) {
auto root = rootOf(value);
if (mlir::isa<mlir::BlockArgument>(root) || root.getDefiningOp<mlir_ts::LoadOp>())
{
return true;
}

return isFresh(root) && llvm::any_of(root.getUsers(), [](mlir::Operation *rootUser) {
return mlir::isa<mlir_ts::ReleaseOp>(rootUser);
});
};

llvm::SmallVector<mlir_ts::StoreOp> borrowed;
for (auto storeOp : fills)
{
auto value = storeOp.getValue();
if (mlir::isa<mlir_ts::RefType>(value.getType()) || holdsNoBlock(value))
{
continue;
}

if (!owned(value))
{
return;
}

// rc's reference for the box goes with the borrow (decideClosures)
if (auto *retain = retainBefore(value, storeOp))
{
box->retains.push_back(retain);
}

borrowed.push_back(storeOp);
}

captureRetains.insert(box->retains.begin(), box->retains.end());
for (auto storeOp : borrowed)
{
setAttrTracked(storeOp, OWN_CAPTURE_BORROW_ATTR_NAME);
captureStores[storeOp] = box.get();
}

literalBoxes.push_back(std::move(box));
});
}

llvm::SmallVector<int32_t> OwnershipInferencePass::borrowingFieldsOf(mlir::Type recordType)
{
llvm::SmallVector<int32_t> fields;
Expand Down Expand Up @@ -923,6 +1075,11 @@ namespace own_inference

void OwnershipInferencePass::decideClosures(llvm::SetVector<mlir::Operation *> &toErase)
{
for (auto &box : literalBoxes)
{
toErase.insert(box->retains.begin(), box->retains.end());
}

for (auto &closure : closures)
{
if (!closure->op)
Expand Down
2 changes: 2 additions & 0 deletions tslang/lib/TypeScript/OwnershipInferencePass.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ namespace own_inference

// first: whether a closure borrows what it captures changes what its box's stores are
classifyClosures();
classifyLiteralCaptures();
classifyStateBoxes();
classifyBorrowingFields();
// ...and whether an object literal borrows what its fields hold (spec 32)
Expand Down Expand Up @@ -143,6 +144,7 @@ namespace own_inference
edgeReleases.clear();
derivedCache.clear();
closures.clear();
literalBoxes.clear();
closureOf.clear();
stateBoxes.clear();
fieldBorrowRetains.clear();
Expand Down
6 changes: 6 additions & 0 deletions tslang/lib/TypeScript/OwnershipInferencePass.h
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,9 @@ class OwnershipInferencePass
};

llvm::SmallVector<std::shared_ptr<Closure>> closures;
// the capture boxes of object literals that borrow what they capture (classifyLiteralCaptures):
// `uses` only, what reaches the literal
llvm::SmallVector<std::shared_ptr<Closure>> literalBoxes;
// a copy stored into a borrowing box -> its closure
llvm::DenseMap<mlir::Operation *, Closure *> captureStores;
// rc's references for boxes, which the closures decide
Expand All @@ -250,6 +253,9 @@ class OwnershipInferencePass
// stores are reads or takers depends on it. A closure with copies only keeps what phase 4 does
// with it - its box owns them, and each copy moves in.
void classifyClosures();
// An object literal's `.captured` box (its arrows' captures, spec 67): when the literal stays in
// this function, the box borrows the copies it holds, as a closure that does not escape does
void classifyLiteralCaptures();

// The fields of a generator's state object of this type that borrow from its arguments
// (OWN_BORROWING_FIELDS_ATTR_NAME, the signature pass's), the `.captured` box's first.
Expand Down
4 changes: 2 additions & 2 deletions tslang/test/tester/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4013,7 +4013,7 @@ foreach(own_test own_fresh_string own_fresh_array own_return_new own_try_local o
own_generator_this_param own_copy_within_returned_param own_swap_elements
own_callback_forwarded own_optional_record_read own_param_default_kept own_literal_into_array
own_generator_take own_rest_array_borrows own_string_copies
own_captured_string_callback own_callback_and_call own_callback_captured own_literal_closures own_literal_variable_closures own_temporary_field_take own_union_narrowed_calls own_named_field_take own_let_field_take own_literal_captures
own_captured_string_callback own_callback_and_call own_callback_captured own_literal_closures own_literal_variable_closures own_temporary_field_take own_union_narrowed_calls own_named_field_take own_let_field_take own_literal_captures own_literal_object_captures
own_callback_shapes own_callback_extended own_callback_interface
own_generic_specializations own_callback_cast own_callback_interface_slot)
tslang_add_test(NAME test-jit-own-${own_test} COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/own/${own_test}.ts")
Expand Down Expand Up @@ -4051,7 +4051,7 @@ foreach(keeps_mm rc gc none)
own_copy_within_returned_param own_swap_elements own_callback_forwarded
own_optional_record_read own_param_default_kept own_literal_into_array
own_generator_take own_rest_array_borrows own_string_copies
own_captured_string_callback own_callback_and_call own_callback_captured own_literal_closures own_literal_variable_closures own_temporary_field_take own_union_narrowed_calls own_named_field_take own_let_field_take own_literal_captures
own_captured_string_callback own_callback_and_call own_callback_captured own_literal_closures own_literal_variable_closures own_temporary_field_take own_union_narrowed_calls own_named_field_take own_let_field_take own_literal_captures own_literal_object_captures
own_callback_shapes own_callback_extended own_callback_interface
own_generic_specializations own_callback_cast own_callback_interface_slot)
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")
Expand Down
52 changes: 52 additions & 0 deletions tslang/test/tester/own/own_literal_object_captures.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// An object literal whose arrows capture an object (spec 67): when the literal stays in the function - its
// members called, the literal given to a parameter of an object type - its `.captured` box borrows the
// object, as a closure that does not escape does, and the object is used after. Each step churns, so
// anything freed too early reads garbage; every model runs it.
class Item {
constructor(public n: number) {}
}

function churn() {
const junk: Item[] = [];
for (let i = 0; i < 64; i++) junk.push(new Item(999));
}

function apply(o: { w: (x: number) => number }) {
return o.w(3);
}

function viaParam(item: Item) {
const q = { w: (x: number) => x + item.n };
return q.w(1) + apply(q);
}

function test(i: number) {
let s: number = 0;
const b = new Item(i);
const q = { w: (x: number) => x * b.n };
s += q.w(1);
churn();
s += apply(q);
s += b.n;

const c = new Item(2);
const r = { w: (x: number) => x + b.n + c.n, v: () => c.n };
s += apply(r) + r.v();
churn();
s += c.n + b.n;

s += viaParam(c);
return s;
}

function main() {
let ok = 0;
for (let i = 0; i < 300; i++) {
// i + 3i + i, then (3 + i + 2) + 2, 2 + i, then 3 + 5
if (test(i) == 5 * i + 7 + 2 + i + 8 + i) ok++;
churn();
}

assert(ok == 300, "ok");
print("done.");
}
Loading