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 @@ -5277,3 +5277,51 @@ own build fails its count (exit 3).
Not here: the field of a named local of a class type (`const r = next(xs, 0); let v = initial ??
r.value`) is still a borrow that cannot be stored, and a parameter on the other branch (`given ??
pair(n).item`) is kept, which callers cannot give up.

## 64. A field taken out of an object a `const` names, 2026-10-29

`const r = new Holder(); return r.value` was `'this value' borrows a field and cannot be stored,
returned or captured`, and so was `c ? initial : r.value` and `initial ?? r.value`. A `const` whose
value is `new`'s or a call's own result is not a slot: MLIRGen folds the name into the value
(`__owned_result_named`), so `r.value` is a `Load(PropertyRef(%new))` and rc releases `%new` where the
name ends - the shape of spec 63 with an owner that has a name.

- **The take** (`namedFieldTakeOf`, from `temporaryFieldTakeOf`). A read of a field of such an object
(`ts.New` with `__owned_result`, or `callResultIsOwn`), with rc's retain of the read later in its
block, is a move out of the field when:
1. nothing sees the object after the read but its releases: no method, no move of it, no read of
that field; and nothing made of the object before the read (a borrow `const w = same(r)`, followed
through every result made of it in turn) is used after it. Its other fields stay readable;
2. the read is not made again on the same object: no path from the read back to it that does not
make the object anew (a loop around the read but not around `new`);
3. rc's retain of the read is in the read's block, and is it or its taker what keeps the borrow.

rc's retain goes, and a `ts.Default` of the field's type is stored into the field right after the
read - not before the release, which after a `?:` stands on every path, and would leave the field of
a path that did not take it unreleased.
- **rc, a branch retains** (`consumeConditionalResults`). Under own only, a branch of a `ts.If` that
yields a field read out of a named object retains it in the branch, right after the read, so that
the take sees its retain - when a receiver keeps the merge (rc retained it after the `ts.If`), whose
retain then goes, as for spec 63. A merge only read (`const x = c ? a : r.value; return x.n`) is left a
borrow: retained in its branches it would be an owned value, and the parameter on its other branch
kept, which callers cannot give up. Under rc the retain after the merge is left: the object outlives
the `ts.If` either way.

A parameter on the other branch of a merge that is kept (`return c ? initial : r.value`) is moved in, as
for any parameter a function keeps: the caller gives it up.

Between the read and the taker the taken value has no owner but the read: an exception thrown there
leaks it (as in spec 63), it does not free it twice.

`own_err_container_read_stored` (`h2.c = h.c`) is now a move out of `h`'s field when `h` is not read
again: the test reads `h.c` after, which stays an error.

`own_named_field_take` returns, picks with a `?:` and a `??`, uses the read before returning it and
reads another field after, reads a merge it does not keep, pushes it from a `new` in a loop, and takes
from a call's result, churning between steps, under own, rc, gc and none; the ownership verifier is
silent on it. `own_err_named_field_{read_again,method_after,object_moved,borrow_after}` are the four
shapes that must stay borrows; a loop around the read but not around `new`, and a `let h = r` read after,
are rejected too.

Not here: a `let` of a class type (a slot, not a folded name), and a push of the field into a global
array (spec 25's immortal keepers ask for a value made here).
25 changes: 22 additions & 3 deletions tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1588,7 +1588,21 @@ class OwnedReturnConsumptionPass
return false;
};

if (llvm::none_of(yields, carriesOwned) && llvm::none_of(yields, borrowsBranchTemporary))
// ...or, under -mm=own, a field read out of an object a `const` names (`c ? init : r.value`),
// the merge kept by a receiver: a retain in the branch, right after the read, is what own
// takes out of the field (spec 64). A merge only read stays a borrow, as it was. Under rc a
// retain after the `ts.If` does the same, and is left so.
auto mergeKept = !findReceiverRetains(result, /*claim=*/false).empty();
auto readsNamedObjectField = [&](mlir_ts::ResultOp resultOp) {
auto loadOp = producerOf(resultOp->getOperand(0)).getDefiningOp<mlir_ts::LoadOp>();
auto propertyRefOp = loadOp ? loadOp.getReference().getDefiningOp<mlir_ts::PropertyRefOp>() : mlir_ts::PropertyRefOp();
auto *definingOp = propertyRefOp ? propertyRefOp.getObjectRef().getDefiningOp() : nullptr;
return compileOptions.memoryModel == MemoryModelOwn && mergeKept && definingOp &&
definingOp->hasAttr(OWNED_RESULT_NAMED_ATTR_NAME);
};

if (llvm::none_of(yields, carriesOwned) && llvm::none_of(yields, borrowsBranchTemporary) &&
llvm::none_of(yields, readsNamedObjectField))
{
return;
}
Expand Down Expand Up @@ -2731,7 +2745,8 @@ class OwnedReturnConsumptionPass
// back as a temporary like any other nobody took. Every `return` of it takes it over, since
// each is on a path of its own - `if (x) return r; return r;` - and one left retaining would
// hand its caller two references.
static llvm::SmallVector<mlir::Operation *> findReceiverRetains(mlir::Value result)
// (`claim` false only asks: the declaration is not marked as the acquisition)
static llvm::SmallVector<mlir::Operation *> findReceiverRetains(mlir::Value result, bool claim = true)
{
auto *definingOp = result.getDefiningOp();
if (definingOp && definingOp->hasAttr(OWNED_RESULT_NAMED_ATTR_NAME))
Expand Down Expand Up @@ -2775,7 +2790,11 @@ class OwnedReturnConsumptionPass
{
// the declaration becomes the acquisition, which is what keeps the
// ownership verifier able to pair the release still to come
varOp->setAttr(OWNED_LOCAL_CONSUMED_ATTR_NAME, mlir::UnitAttr::get(varOp.getContext()));
if (claim)
{
varOp->setAttr(OWNED_LOCAL_CONSUMED_ATTR_NAME, mlir::UnitAttr::get(varOp.getContext()));
}

return {retainSlotOp.getOperation()};
}
}
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 @@ -819,6 +819,8 @@ class OwnershipInferencePass
mlir_ts::VariableOp slot;
// a field of a temporary (spec 63): the temporary's release, before which the field is emptied
mlir::Operation *release = nullptr;
// a field of an object a `const` names (spec 64): emptied right at the read
bool emptyAtRead = false;
};

// Is `kept`, what keeps the borrow `read` (a read of a field of an owning record local), one
Expand All @@ -831,6 +833,9 @@ class OwnershipInferencePass
// Is `kept` rc's retain of `read`, a read of a field of a call's own result released as a
// temporary right after, with nothing else reading that field (spec 63)?
bool temporaryFieldTakeOf(mlir::Operation *read, mlir::Operation *kept, FieldTake &take);
// ...or of an object a `const` names, `new`'s or a call's own, that nothing sees after the move
// but its releases, and that is not taken from twice (spec 64)?
bool namedFieldTakeOf(mlir::Operation *read, mlir::Operation *retain, mlir_ts::PropertyRefOp field, FieldTake &take);
// Can `call` be given a copy of `value`, a string read out of a place, in its place (callCopies)?
static bool copiesInto(mlir::Operation *call, mlir::Value value);
// Does `store` put `value`, a string read out of a place, into another place with no retain of
Expand Down
129 changes: 121 additions & 8 deletions tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -852,10 +852,12 @@ namespace own_inference
{
if (!dryRun)
{
mlir::OpBuilder builder(take.release);
// (right after the read: rc's retain of it is erased with the bookkeeping)
auto *at = take.emptyAtRead ? read->getNextNode() : take.release;
mlir::OpBuilder builder(at);
auto fieldType = mlir::cast<mlir_ts::RefType>(take.field.getType()).getElementType();
auto empty = builder.create<mlir_ts::DefaultOp>(take.release->getLoc(), fieldType);
builder.create<mlir_ts::StoreOp>(take.release->getLoc(), empty, take.field);
auto empty = builder.create<mlir_ts::DefaultOp>(at->getLoc(), fieldType);
builder.create<mlir_ts::StoreOp>(at->getLoc(), empty, take.field);
}

bookkeeping.push_back(take.retain);
Expand Down Expand Up @@ -1145,7 +1147,33 @@ namespace own_inference
// walk may meet the taker first (`r = next(xs, 0).value`). A string too: it moves, as nothing
// else holds it.
auto loadOp = mlir::dyn_cast<mlir_ts::LoadOp>(read);
auto retainOp = loadOp ? mlir::dyn_cast_or_null<mlir_ts::RetainOp>(read->getNextNode()) : mlir_ts::RetainOp();
auto field = loadOp ? loadOp.getReference().getDefiningOp<mlir_ts::PropertyRefOp>() : mlir_ts::PropertyRefOp();
auto temporary = field ? field.getObjectRef() : mlir::Value();
auto *call = temporary ? temporary.getDefiningOp() : nullptr;
if (!call || !field->hasOneUse())
{
return false;
}

// ...or out of an object a `const` names, `new`'s or a call's own (spec 64): `return r.value`.
// The read may be used before rc's retain of it, later in its block (`const v = r.value;
// print(v.n); return v`): the field is empty from the read on, and the read holds what it held.
if (call->hasAttr(OWNED_RESULT_NAMED_ATTR_NAME))
{
for (auto *user : loadOp->getUsers())
{
auto namedRetain = mlir::dyn_cast<mlir_ts::RetainOp>(user);
if (namedRetain && namedRetain->getBlock() == read->getBlock() &&
(kept == namedRetain || takerOf(namedRetain, loadOp.getResult()) == kept))
{
return namedFieldTakeOf(read, namedRetain, field, take);
}
}

return false;
}

auto retainOp = mlir::dyn_cast_or_null<mlir_ts::RetainOp>(read->getNextNode());
if (!retainOp || retainOp.getReference() != loadOp.getResult() ||
(kept != retainOp && takerOf(retainOp, loadOp.getResult()) != kept))
{
Expand All @@ -1155,10 +1183,8 @@ namespace own_inference
kept = retainOp;

// a field read in place out of a call's own result, not a borrow of what the call was given
auto field = loadOp.getReference().getDefiningOp<mlir_ts::PropertyRefOp>();
auto temporary = field ? field.getObjectRef() : mlir::Value();
auto *call = temporary ? temporary.getDefiningOp() : nullptr;
if (!call || !callResultIsOwn(call) || !field->hasOneUse())

if (!callResultIsOwn(call))
{
return false;
}
Expand Down Expand Up @@ -1199,6 +1225,93 @@ namespace own_inference
return true;
}

bool OwnershipInferencePass::namedFieldTakeOf(mlir::Operation *read, mlir::Operation *retain,
mlir_ts::PropertyRefOp field, FieldTake &take)
{
// The object a `const` names is `new`'s own, or a call's own result: nothing else holds it,
// and its releases end it. The field is left empty right at the read, so each release frees
// nothing of what the taker has, on a path that took it or not (`c ? init : r.value`).
auto object = field.getObjectRef();
auto *producer = object.getDefiningOp();
if (!(mlir::isa<mlir_ts::NewOp>(producer) && producer->hasAttr(OWNED_RESULT_ATTR_NAME)) && !callResultIsOwn(producer))
{
return false;
}

llvm::SmallVector<mlir::Operation *> releases;
for (auto *user : object.getUsers())
{
if (mlir::isa<mlir_ts::ReleaseOp>(user))
{
releases.push_back(user);
}
}

if (releases.empty())
{
return false;
}

// taken once for each object: not again around a loop that does not make it anew
auto *next = read->getNextNode();
if (!next || reachableAfter(next, read, producer))
{
return false;
}

// Nothing sees the object after the move but its releases: no method, no move of it, no read
// of that field, nor anything made of the object before it that is used after (a borrow of it).
// Its other fields are its own still.
auto seenAfter = [&](mlir::Operation *op) { return op != read && op != retain && reachableAfter(read, op, releases); };
for (auto *user : object.getUsers())
{
if (mlir::isa<mlir_ts::ReleaseOp>(user) || user == field.getOperation())
{
continue;
}

if (auto propertyRefOp = mlir::dyn_cast<mlir_ts::PropertyRefOp>(user);
propertyRefOp && propertyRefOp.getPosition() != field.getPosition())
{
continue;
}

// the user, and what is made of its results in turn
llvm::SmallVector<mlir::Operation *> derived{user};
llvm::SmallPtrSet<mlir::Operation *, 8> visited;
while (!derived.empty())
{
auto *op = derived.pop_back_val();
if (!visited.insert(op).second)
{
continue;
}

if (seenAfter(op))
{
return false;
}

for (auto result : op->getResults())
{
derived.append(result.getUsers().begin(), result.getUsers().end());
}
}
}

auto *taker = takerOf(retain, read->getResult(0));
if (!taker)
{
return false;
}

take.retain = retain;
take.taker = taker;
take.field = field.getResult();
take.emptyAtRead = true;
return true;
}

bool OwnershipInferencePass::keptParamOutlives(const Chain &chain, llvm::function_ref<bool(mlir::Operation *)> outlives)
{
for (auto &root : chain.roots)
Expand Down
12 changes: 8 additions & 4 deletions tslang/test/tester/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3992,7 +3992,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_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_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 @@ -4030,7 +4030,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_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_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 Expand Up @@ -4501,7 +4501,7 @@ set(own_error_cases
"own_err_alias_read_popped|:28:9: error: '[^']*' borrows an element but is used here after it may be released or overwritten"
"own_err_alias_read_stale|:31:19: error: '[^']*' borrows a field but is used here after it may be released or overwritten"
"own_err_merge_root_assigned|:36:12: error: '[^']*' borrows a field but is used here after it may be released or overwritten"
"own_err_container_read_stored|:26:5: error: '[^']*' borrows a field and cannot be stored, returned or captured"
"own_err_container_read_stored|:27:5: error: '[^']*' borrows a field and cannot be stored, returned or captured"
"own_err_field_let_overwritten|:28:11: error: '[^']*' borrows a field but is used here after it may be released or overwritten"
"own_err_field_let_assigned|:26:5: error: '[^']*' borrows a field and cannot be assigned"
"own_err_call_drops_indirectly|:24:11: error: '[^']*' borrows a field but is used here after it may be released or overwritten"
Expand Down Expand Up @@ -4739,7 +4739,11 @@ set(own_error_cases
"own_err_callback_cast_field_drops|:16:13: error: '[^']*' borrows an element but is used here after it may be released or overwritten"
"own_err_callback_interface_slot_drops|:41:11: error: a value read out of the global 'pool' is lent to a call that may release or overwrite it"
"own_err_callback_interface_slot_targets|:47:12: error: a value read out of the global 'pool' is lent to a call that may release or overwrite it"
"own_err_union_narrowed_moved|:26:14: error: '[^']*' is used here after its value was moved")
"own_err_union_narrowed_moved|:26:14: error: '[^']*' is used here after its value was moved"
"own_err_named_field_read_again|:28:5: error: '[^']*' borrows a field and cannot be stored, returned or captured"
"own_err_named_field_method_after|:28:5: error: '[^']*' borrows a field and cannot be stored, returned or captured"
"own_err_named_field_object_moved|:28:5: error: '[^']*' borrows a field and cannot be stored, returned or captured"
"own_err_named_field_borrow_after|:29:5: error: '[^']*' borrows a field and cannot be stored, returned or captured")
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)
Expand Down
5 changes: 3 additions & 2 deletions tslang/test/tester/own/own_err_container_read_stored.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// -mm=own, phase 3 rejects: a value read out of a field is borrowed; storing it into another
// field would give it a second owner.
// field would give it a second owner. (With `h` not read again it would be a move out of the field
// of an object a `const` names, spec 64: `h` reads it after.)
class C {
v: number[] = [];
constructor(public x: number) {}
Expand All @@ -24,5 +25,5 @@ function main() {
const h = new H();
const h2 = new H();
h2.c = h.c;
print(h2.c.x);
print(h2.c.x, h.c.x);
}
Loading
Loading