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: 5 additions & 2 deletions docs/own-memory-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,9 @@ function main() {

A `let` that is only given other locals' values, or fields', and is assigned again (`let cur = a;
... cur = b;`) borrows each value until its next assignment: none of them moves into it. Walking a
list from a local head is that case (`let node = head; while (node) { ...; node = node.next; }`).
list from a local head is that case (`let node = head; while (node) { ...; node = node.next; }`),
from a `const` head too (`const a = new L(0); for (let q: L | null = a; q; q = q.next)`), and so is a
step through a call that gives back the node it is given (`q = nn(q).next`).
Giving the head up, or cutting the list, while the walk still reads it is an error.

A local that borrows out of a container and is still used after a call that may free what it borrows
Expand Down Expand Up @@ -351,7 +353,8 @@ fact: `new Person(p.name)` is an error. Pass a string you give up, or a fresh on

A closure that does not escape borrows what it captures. A closure that escapes - returned,
stored, or given to a function that keeps it - takes its captured variables with it, and the
frame that made it may not use them afterwards.
frame that made it may not use them afterwards. A closure that calls another closure of the same frame (`const step = () =>
part(1)`) captures it as it captures anything else: borrowed while neither escapes.

```typescript
function counter() {
Expand Down
100 changes: 96 additions & 4 deletions tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -421,13 +421,83 @@ namespace own_inference
return slot;
}

mlir::Value OwnershipInferencePass::namedConstValueOf(mlir::Value value)
{
// the mark is on the value, or on the view the declaration made (`const a: L | null = new L(0)`: the cast)
auto named = false;
auto root = value;
while (auto *def = root.getDefiningOp())
{
named = named || def->hasAttr(OWNED_RESULT_NAMED_ATTR_NAME) || def->hasAttr(OWNED_RESULT_NAMED_CALL_ATTR_NAME);
if (!isView(def))
{
break;
}

root = def->getOperand(0);
}

// (a lending call's result, a narrowed read - `nn(q)`, SafeCast - carry the mark too: not fresh)
auto *def = root.getDefiningOp();
if (!named || !def || !isFresh(root) || isRecordResult(def) || isHandle(root) ||
countedValues.contains(countedUnitOf(root)))
{
return {};
}

// ...and never moved away (`h.t = q`: a store into a place, a push, a call keeping it): a `let` borrowing a value
// that moves is decided as before, a borrow of the moved local (own_err_let_borrows_local_moved)
auto released = false;
auto moved = false;
forEachUse(root, [&](mlir::Operation *user, mlir::Value used) {
released = released || mlir::isa<mlir_ts::ReleaseOp>(user);
auto storeOp = mlir::dyn_cast<mlir_ts::StoreOp>(user);
moved = moved ||
(storeOp && storeOp.getValue() == used && !storeOp.getReference().getDefiningOp<mlir_ts::VariableOp>()) ||
mlir::isa<mlir_ts::ArrayPushOp, mlir_ts::ArrayUnshiftOp>(user) ||
(isCall(user) && isKeptArgument(user, used));
});
return released && !moved ? root : mlir::Value();
}

mlir_ts::VariableOp OwnershipInferencePass::localBorrowerGiven(mlir::Operation *user, mlir::Value used, mlir::Operation *&from)
{
mlir_ts::VariableOp varOp;
if (auto declared = mlir::dyn_cast<mlir_ts::VariableOp>(user); declared && declared.getInitializer() == used)
{
varOp = declared;
}
else if (auto storeOp = mlir::dyn_cast<mlir_ts::StoreOp>(user); storeOp && storeOp.getValue() == used)
{
varOp = storeOp.getReference().getDefiningOp<mlir_ts::VariableOp>();
}

// (only a named `const`'s value: a read of a local's slot given to such a `let` is the slot's borrow,
// decided by its receivers - decideSlotReceivers, own_err_let_borrows_local_moved)
if (!varOp || !localBorrowingLets.contains(varOp) || !namedConstValueOf(used))
{
return {};
}

from = user;
return varOp;
}

bool OwnershipInferencePass::readsOwningLocals(mlir::Value value, mlir_ts::VariableOp self)
{
if (auto owner = owningLocalReadOf(value))
{
return owner != self;
}

// ...or the value a named `const` owns (`const a = new L(0); for (let q: L | null = a; q; q = q.next)`,
// TSLANG 235): folded, the name is the value and there is no slot; the const keeps it and releases it where
// its scope ends (checkValueMoves bounds the borrow: borrowedByLocalLets)
if (namedConstValueOf(value))
{
return true;
}

// `qq = r && q`: a merge of reads of owning locals (and of null)
auto argument = mlir::dyn_cast<mlir::BlockArgument>(rootOf(value));
llvm::SmallVector<mlir_ts::LoadOp> loads;
Expand Down Expand Up @@ -911,7 +981,14 @@ namespace own_inference

auto firstOfRead = uses.size();
uses.push_back({user, {kills.begin(), kills.end()}});
if (auto *kept = walkBorrowed(readOp.getResult(), kills, uses))
// rc's release of the temporary a call returns that lends the read back (`const e = nn(c)`, `nn(c).next`)
// keeps nothing of it: the call's own check walks it and erases it with the call's bookkeeping
// (checkPlaceRead) - here it is no keep of what the `let` holds (TSLANG 235). Only for a `let` given only
// borrows and assigned (a walk: borrowsOnly): a local that borrows a place once keeps the call's release as a
// keep, and is refused as before (own_err_result_borrows_argument)
llvm::SmallVector<mlir::Operation *> lentBack;
auto keeping = onlyBorrows ? Keeping{&lentBack, false} : Keeping{nullptr, false};
if (auto *kept = walkBorrowed(readOp.getResult(), kills, uses, nullptr, keeping))
{
return kept;
}
Expand Down Expand Up @@ -1436,9 +1513,24 @@ namespace own_inference
auto getThisOp = use.get().getDefiningOp<mlir_ts::GetThisOp>();
auto getMethodOp = callee.getDefiningOp<mlir_ts::GetMethodOp>();
auto methodField = getThisOp ? getThisOp.getOperand().getDefiningOp<mlir_ts::LoadOp>() : mlir_ts::LoadOp();
return use.getOperandNumber() == 1 && getMethodOp && methodField &&
getThisOp.getOperand() == getMethodOp.getBoundFunc() &&
mlir::isa<mlir_ts::BoundRefType>(methodField.getReference().getType());
if (use.getOperandNumber() != 1 || !getMethodOp || !methodField || getThisOp.getOperand() != getMethodOp.getBoundFunc())
{
return false;
}

if (mlir::isa<mlir_ts::BoundRefType>(methodField.getReference().getType()))
{
return true;
}

// ...or a closure this closure captured, read out of its own box (golden_line_cab's cabLimb: `cap` running
// `ring`): a box's fields are filled once, where the closure is made, and never written again
auto fieldOp = methodField.getReference().getDefiningOp<mlir_ts::PropertyRefOp>();
auto box = fieldOp ? mlir::dyn_cast<mlir::BlockArgument>(fieldOp.getObjectRef()) : mlir::BlockArgument();
auto refType = box ? mlir::dyn_cast<mlir_ts::RefType>(box.getType()) : mlir_ts::RefType();
return refType && box.getArgNumber() == 0 && box.getOwner()->isEntryBlock() &&
mlir::isa<mlir_ts::TupleType>(refType.getElementType()) &&
mlir::isa<mlir_ts::BoundFunctionType>(methodField.getType());
}

} // namespace own_inference
35 changes: 33 additions & 2 deletions tslang/lib/TypeScript/OwnershipInferenceClosures.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -116,12 +116,15 @@ namespace own_inference
return def && isFresh(root) &&
(def->hasAttr(OWNED_RESULT_NAMED_ATTR_NAME) || def->hasAttr(OWNED_RESULT_NAMED_CALL_ATTR_NAME));
};
// ...and another closure that does not escape (cabLimb's `cap` calling its `ring`): its own frees it
auto noneFresh = llvm::none_of(closure->fills, [&](auto &fill) {
auto value = fill.second.getValue();
return !holdsNoBlock(value) && isFresh(rootOf(value)) && !ownedByNamedConst(value);
return !holdsNoBlock(value) && isFresh(rootOf(value)) && !ownedByNamedConst(value) &&
!isNonEscapingClosureValue(value);
});
auto holdsParam = llvm::any_of(closure->fills, [&](auto &fill) {
return isBorrowableCapture(fill.second.getValue()) || ownedByNamedConst(fill.second.getValue());
return isBorrowableCapture(fill.second.getValue()) || ownedByNamedConst(fill.second.getValue()) ||
isNonEscapingClosureValue(fill.second.getValue());
});
closure->borrowsCopies =
!closure->escape && noneFresh &&
Expand Down Expand Up @@ -1983,6 +1986,27 @@ namespace own_inference
}
}

// captured by another closure that does not escape (`const cap = (t) => { ring(t); }` of a local
// closure `ring`, golden_line_cab's cabLimb): what may run it is what may run that closure
if (auto fieldOp = slot ? slot.getDefiningOp<mlir_ts::PropertyRefOp>() : mlir_ts::PropertyRefOp();
fieldOp && followClosureDepth < 8)
{
if (auto outer = closureOfBox(fieldOp.getObjectRef()))
{
llvm::SmallVector<mlir::Operation *> outerUses;
llvm::SmallVector<mlir::Operation *> outerEnds;
auto outerAliased = false;
++followClosureDepth;
auto *outerEscape = followClosure(outer.getResult(), outerUses, outerEnds, outerAliased);
--followClosureDepth;
if (!outerEscape && !outerAliased)
{
uses.append(outerUses.begin(), outerUses.end());
return;
}
}
}

// ...and a record read out of one: the closure's field read, not the others
if (auto extractOp = mlir::dyn_cast<mlir_ts::ExtractPropertyOp>(user))
{
Expand All @@ -2006,6 +2030,13 @@ namespace own_inference
return escape;
}

bool OwnershipInferencePass::isNonEscapingClosureValue(mlir::Value value)
{
auto *def = rootOf(value).getDefiningOp();
auto found = def && mlir::isa<mlir_ts::CreateBoundFunctionOp>(def) ? closureOf.find(def) : closureOf.end();
return found != closureOf.end() && found->second && !found->second->escape;
}

bool OwnershipInferencePass::holdsCaptures(mlir::Value value)
{
if (mlir::isa<mlir_ts::BoundFunctionType, mlir_ts::HybridFunctionType>(value.getType()))
Expand Down
59 changes: 58 additions & 1 deletion tslang/lib/TypeScript/OwnershipInferenceMoves.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1113,6 +1113,48 @@ namespace own_inference
});
}

bool OwnershipInferencePass::borrowedByLocalLets(mlir::Value value, llvm::SetVector<mlir::Operation *> &toErase)
{
if (localBorrowingLets.empty())
{
return true;
}

llvm::SmallVector<std::pair<mlir_ts::VariableOp, mlir::Operation *>> lent;
llvm::SmallVector<mlir::Operation *> ends;
forEachUse(value, [&](mlir::Operation *user, mlir::Value used) {
mlir::Operation *from = nullptr;
if (auto borrower = localBorrowerGiven(user, used, from))
{
lent.push_back({borrower, from});
return;
}

if (mlir::isa<mlir_ts::RetainOp>(user) || onlyDebugged(user))
{
return;
}

// the const's own release, and whatever takes the value away (a store, a push, a call that keeps it, a
// merge): the borrow ends there (one that takes rc's retain of it moves it: namedConstValueOf)
if (mlir::isa<mlir_ts::ReleaseOp>(user) || !isBorrow(user, used))
{
ends.push_back(user);
}
});

auto owner = ownerName(value);
for (auto &[borrower, from] : lent)
{
if (!tryBorrow(borrower, ends, owner, toErase, from))
{
return false;
}
}

return true;
}

bool OwnershipInferencePass::checkValueMoves(mlir::Value value, llvm::SetVector<mlir::Operation *> &toErase)
{
// a counted value (--own-fallback=count) keeps rc's ops: no move of it is checked or erased
Expand All @@ -1139,6 +1181,14 @@ namespace own_inference
return false;
}

// A `let` that only borrows (classifyLocalBorrowingLets) given this value, a named `const`'s, by its
// declaration or an assignment: a borrow of the const each time, never a move. The const's release ends it,
// and so does whatever takes the value (a const moved while the `let` still reads it is refused) (TSLANG 235)
if (!borrowedByLocalLets(value, toErase))
{
return false;
}

if (quietly([&] { return movesOf(value, toErase); }))
{
return true;
Expand All @@ -1149,7 +1199,8 @@ namespace own_inference
llvm::SmallVector<std::pair<mlir::Operation *, mlir::Value>> notReads;
llvm::SmallVector<mlir::Operation *> releases;
forEachUse(value, [&](mlir::Operation *user, mlir::Value used) {
if (mlir::isa<mlir_ts::RetainOp>(user) || onlyDebugged(user))
mlir::Operation *from = nullptr;
if (mlir::isa<mlir_ts::RetainOp>(user) || onlyDebugged(user) || localBorrowerGiven(user, used, from))
{
return;
}
Expand Down Expand Up @@ -1452,10 +1503,16 @@ namespace own_inference
}

llvm::SmallVector<mlir::Operation *> fieldReads;
mlir::Operation *from = nullptr;
if (mlir::isa<mlir_ts::ReleaseOp>(user))
{
releases.push_back(user);
}
// given to a `let` that only borrows it (borrowedByLocalLets bounded its uses): a read, not a taker
else if (localBorrowerGiven(user, used, from))
{
reads.push_back(user);
}
else if (isBorrow(user, used))
{
reads.push_back(user);
Expand Down
18 changes: 18 additions & 0 deletions tslang/lib/TypeScript/OwnershipInferencePass.h
Original file line number Diff line number Diff line change
Expand Up @@ -547,6 +547,18 @@ class OwnershipInferencePass
void countUninitializedLets();
// The owning, uncaptured local whose slot `value` reads, other than a parameter's, or null.
mlir_ts::VariableOp owningLocalReadOf(mlir::Value value);
// The value a named `const` owns that `value` is, seen through its views (`const a = new L(0)`, folded: the name
// is the value - OWNED_RESULT_NAMED_ATTR_NAME on it or on the view its declaration made,
// OWNED_RESULT_NAMED_CALL_ATTR_NAME of a call made direct) - fresh, and released where the const's scope ends;
// else null.
mlir::Value namedConstValueOf(mlir::Value value);
// The `let` of localBorrowingLets that `user` gives `used` to - its declaration, or the store of an assignment -
// and in `from`, that op; else null.
mlir_ts::VariableOp localBorrowerGiven(mlir::Operation *user, mlir::Value used, mlir::Operation *&from);
// The `let`s that only borrow (localBorrowingLets) given `value`, a named `const`'s: each borrows it up to its
// next assignment, bounded by the const's release and by whatever takes the value. False (reported) when one is
// used after that.
bool borrowedByLocalLets(mlir::Value value, llvm::SetVector<mlir::Operation *> &toErase);
// Does `value` read owning locals other than `self` - one, or a merge of several (and of null)?
bool readsOwningLocals(mlir::Value value, mlir_ts::VariableOp self);
// The `let` of localBorrowingLets that an acquisition gives `value` to - its declaration's
Expand Down Expand Up @@ -628,6 +640,12 @@ class OwnershipInferencePass
// not know is such a use.
mlir::Operation *followClosure(mlir::Value closure, llvm::SmallVectorImpl<mlir::Operation *> &uses,
llvm::SmallVectorImpl<mlir::Operation *> &ends, bool &aliased);
// how many closures followClosure is following into, each captured by the next (bounded)
int followClosureDepth = 0;

// A closure that captures this value borrows it rather than owning it: the value is another closure, one
// that does not escape (classifyClosures has decided it: closureOf), whatever captures it.
bool isNonEscapingClosureValue(mlir::Value value);

// Does a call given this value give it a closure, which may run and touch what its box holds?
static bool holdsCaptures(mlir::Value value);
Expand Down
28 changes: 27 additions & 1 deletion tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -875,6 +875,15 @@ namespace own_inference
}

forEachUse(owner, [&](mlir::Operation *use, mlir::Value used) {
// (a `let` that only borrows a named `const`'s value takes nothing, as one that borrows a
// local's below: its declaration, an assignment's store, rc's retain before the store)
mlir::Operation *from = nullptr;
if (localBorrowerGiven(use, used, from) ||
(mlir::isa<mlir_ts::RetainOp>(use) && localBorrowerOf(use, from)))
{
return;
}

if (!mlir::isa<mlir_ts::ReleaseOp, mlir_ts::RetainOp>(use) && !isBorrow(use, used))
{
auto merged = mergedValuesOf(use, used);
Expand Down Expand Up @@ -2109,8 +2118,25 @@ namespace own_inference
return false;
};

// A closure this closure captured, read out of its own box (golden_line_cab's cabLimb: `cap` running `frame`,
// then `ring`): the box is filled once, where the closure is made, and lives while the closure runs - nothing
// the closure calls frees it. What keeps the read is still decided above.
auto ownBoxClosure = [&]() {
auto field = loadOp ? loadOp.getReference().getDefiningOp<mlir_ts::PropertyRefOp>() : mlir_ts::PropertyRefOp();
auto box = field ? mlir::dyn_cast<mlir::BlockArgument>(field.getObjectRef()) : mlir::BlockArgument();
auto boxType = box ? mlir::dyn_cast<mlir_ts::RefType>(box.getType()) : mlir_ts::RefType();
return boxType && box.getArgNumber() == 0 && box.getOwner()->isEntryBlock() &&
mlir::isa<mlir_ts::TupleType>(boxType.getElementType()) && mlir::isa<mlir_ts::BoundFunctionType>(result.getType());
}();
if (ownBoxClosure)
{
toErase.insert(bookkeeping.begin(), bookkeeping.end());
return true;
}

for (auto *end : rootEnds(chain))
{ if (outlives(end))
{
if (outlives(end))
{
return false;
}
Expand Down
Loading
Loading