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
45 changes: 43 additions & 2 deletions tslang/lib/TypeScript/MLIRGenImpl.h
Original file line number Diff line number Diff line change
Expand Up @@ -24151,14 +24151,55 @@ class MLIRGenImpl
});
}

if (storesArray || calls)
// ...a call, under -mm=rc: it may give the place another array and release the one read (`k.arr[0] = g(k)` of a
// `g` that replaces `k.arr`), and the store and the growth went into a freed block. The array is held in a
// slot the scope owns, retained right after the read: given back where the scope ends, and on the unwind
// when the call throws - a release after the store would not run then, and leaked the array once a throw
if (calls && compileOptions.memoryModel == MemoryModelRC && genContext.ownedVars &&
!genContext.generatorSwitchOperation)
{
mlir::Value slot;
{
mlir::OpBuilder::InsertionGuard guard(builder);
if ((genContext.allocateScopeOwnedVarsOutsideOfOperation || genContext.allocateVarsOutsideOfOperation) &&
genContext.currentOperation)
{
builder.setInsertionPoint(genContext.currentOperation);
}
else
{
builder.setInsertionPoint(loadOp);
}

slot = builder.create<mlir_ts::VariableOp>(location, mlir_ts::RefType::get(array.getType()), mlir::Value(),
builder.getBoolAttr(false), builder.getIndexAttr(0));
auto empty = builder.create<mlir_ts::DefaultOp>(location, array.getType());
builder.create<mlir_ts::StoreOp>(location, empty, slot);
auto varOp = slot.getDefiningOp<mlir_ts::VariableOp>();
varOp->setAttr(OWNED_LOCAL_ATTR_NAME, builder.getUnitAttr());
varOp->setAttr(OWNED_LOCAL_CONSUMED_ATTR_NAME, builder.getUnitAttr());
}

{
mlir::OpBuilder::InsertionGuard guard(builder);
builder.setInsertionPointAfter(loadOp);
builder.create<mlir_ts::RetainOp>(location, array);
builder.create<mlir_ts::StoreOp>(location, array, slot);
}

genContext.ownedVars->push_back(slot);
arrayRef = slot;
}
else if (storesArray || calls)
{
arrayRef = builder.create<mlir_ts::VariableOp>(location, mlir_ts::RefType::get(array.getType()), array,
builder.getBoolAttr(false), builder.getIndexAttr(0));
// retained only for a store of an array here: its release after the store is not run when the right
// side throws, and `k.nums[i] = f(i)` of an `f` that throws leaked the array once a throw (a call
// that gives the place another array - and releases the one read - stays open under -mm=rc)
if (compileOptions.memoryModel == MemoryModelRC && storesArray)
// (...and a call where no scope owns slots - module-level code: released after the store, as for a store
// of an array)
if (compileOptions.memoryModel == MemoryModelRC && (storesArray || calls))
{
mlir::OpBuilder::InsertionGuard guard(builder);
builder.setInsertionPointAfter(loadOp);
Expand Down
10 changes: 10 additions & 0 deletions tslang/lib/TypeScript/OwnershipInferenceKeptParams.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,16 @@ namespace own_inference
bool OwnershipInferencePass::movesOnExclusivePaths(mlir::Value slot, llvm::ArrayRef<SlotReceiver> receivers, bool released,
llvm::SetVector<mlir::Operation *> &toErase)
{
// two moves into one call (`f2(p, p)` of a callee keeping both): on the same path, whatever reaches what
llvm::SmallPtrSet<mlir::Operation *, 4> retains;
for (auto &receiver : receivers)
{
if (!retains.insert(receiver.retain).second)
{
return false;
}
}

auto assignments = slotAssignments(slot);
llvm::SmallVector<mlir::Operation *> kills(assignments.begin(), assignments.end());
if (auto varOp = slot.getDefiningOp<mlir_ts::VariableOp>())
Expand Down
53 changes: 52 additions & 1 deletion tslang/lib/TypeScript/OwnershipInferencePass.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1444,7 +1444,24 @@ namespace own_inference
}

// rc's reference for the caller, on a parameter this function returns a borrow of
if (value && returnsBorrowOf >= 0 && borrowedParam(value) == returnsBorrowOf)
// (not the copy put in a closure's box, `p.setCb(() => p.x)` of a function that also returns `p.a`: the
// box owns it, and the parameter's value is the caller's - decided as any other capture of it, below)
// (MLIRGen's mlirGenRetainCaptured reads the slot again for the box's field, at the retain's location)
auto isBoxFill = [&](mlir::Operation *user, mlir::Value stored) {
auto storeOp = mlir::dyn_cast<mlir_ts::StoreOp>(user);
auto propertyRefOp = storeOp && storeOp.getValue() == stored
? storeOp.getReference().getDefiningOp<mlir_ts::PropertyRefOp>()
: mlir_ts::PropertyRefOp();
return propertyRefOp && closureOfBox(propertyRefOp.getObjectRef()) && user->getLoc() == op->getLoc();
};
auto retainedRead = value ? value.getDefiningOp<mlir_ts::LoadOp>() : mlir_ts::LoadOp();
auto fillsBox = retainedRead && llvm::any_of(retainedRead.getReference().getUsers(), [&](mlir::Operation *user) {
auto loadOp = mlir::dyn_cast<mlir_ts::LoadOp>(user);
return loadOp && llvm::any_of(loadOp->getUsers(), [&](mlir::Operation *fill) {
return isBoxFill(fill, loadOp.getResult());
});
});
if (value && !fillsBox && returnsBorrowOf >= 0 && borrowedParam(value) == returnsBorrowOf)
{
if (returnedParams.insert(value).second)
{
Expand Down Expand Up @@ -2555,6 +2572,12 @@ namespace own_inference
auto storeOp = mlir::dyn_cast<mlir_ts::StoreOp>(user);
borrows = !(storeOp && storeOp.getValue() == used) && !mlir::isa<mlir_ts::VariableOp>(user);
}
// ...nor stored into a place, a record's borrowing field among them (`f({ v: g.items[0] })`): the uses
// through what holds it are not read here
else if (auto storeOp = mlir::dyn_cast<mlir_ts::StoreOp>(user); storeOp && storeOp.getValue() == used)
{
borrows = false;
}

// rc's release of a call's result that borrows an argument: not run under own - the result is lent,
// and the counted read's release is erased (checkPlaceReads' counted reads)
Expand All @@ -2563,6 +2586,13 @@ namespace own_inference
return;
}

// ...and of a call's result that borrows it (`const r = g(h, h.n)`, chosen below): lent, as above
if (auto *lender = used.getDefiningOp(); mlir::isa<mlir_ts::ReleaseOp>(user) && used != value && lender &&
isCall(lender) && borrowingCall(used) == lender)
{
return;
}

if (!borrows)
{
usable = false;
Expand All @@ -2577,6 +2607,14 @@ namespace own_inference

// a branch passing it on: its block's argument, used where the read's block dominates (each path
// into it then holds the reference), is live into that block
// (a call in a `try`, `ts.Invoke`, ends its block: the count would go back after it on its successors,
// which are not placed here - not counted, the error stands)
if (user->hasTrait<mlir::OpTrait::IsTerminator>() && isCall(user))
{
usable = false;
return;
}

if (user->hasTrait<mlir::OpTrait::IsTerminator>())
{
auto branch = mlir::dyn_cast<mlir::BranchOpInterface>(user);
Expand Down Expand Up @@ -2626,6 +2664,19 @@ namespace own_inference
chosen.insert(loadOp.getResult());
}

// a call's result its facts say borrows it (`const r = g(h, h.n)` of a `g` returning its argument): the
// same block, lent back - its uses hold it too, the count given back after them, not after the call
if (isCall(user) && user->getNumResults() == 1)
{
auto args = callArgs(user);
if (llvm::any_of(resultBorrowsAll(user), [&](int index) {
return static_cast<size_t>(index) < args.size() && args[index] == used;
}))
{
chosen.insert(user->getResult(0));
}
}

// a place in it, a method of it, its `this`: what is read or called through that uses it too
// (`e.v` is a PropertyRef, then the Load through it)
if (derivesFrom(user))
Expand Down
3 changes: 3 additions & 0 deletions tslang/lib/TypeScript/OwnershipInferencePass.h
Original file line number Diff line number Diff line change
Expand Up @@ -1135,6 +1135,9 @@ class OwnershipInferencePass
// What a call has to be given to reach a root: the root, and where the root is a local
// declared from another (a borrow, or a move that left the other dead), that one too.
static llvm::SmallVector<mlir::Value> rootSources(const Chain &chain);
// rootSources, and what a source lent by a call was read under: the call's arguments it borrows, as far as the
// lenders go (`k.at(0)`: `k` too). False where a lender's facts name no argument given.
bool lentSources(const Chain &chain, llvm::SetVector<mlir::Value> &sources);

// Everything that may point into what `start` points to: the forward closure over users'
// results that may point anywhere. A call's result is not followed: the call hands back a
Expand Down
99 changes: 93 additions & 6 deletions tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1011,6 +1011,32 @@ namespace own_inference
});
}

// The object a method's `this` or the method itself is read off: a virtual call's `GetThis`/`GetMethod` of the
// bound method `ThisVirtualSymbolRef(k.self(), ...)` makes, `k.self()`. (Anything else: itself.)
static mlir::Value objectOfMethod(mlir::Value value)
{
while (auto *def = value.getDefiningOp())
{
if (!mlir::isa<mlir_ts::GetThisOp, mlir_ts::GetMethodOp, mlir_ts::ThisVirtualSymbolRefOp, mlir_ts::ThisSymbolRefOp>(def) ||
def->getNumOperands() == 0)
{
break;
}

value = def->getOperand(0);
}

return value;
}

// Are both reads of the same global (`k.drain(k.at(0))` of a module-level `k`: each mention a load of its own)?
static bool readsSameGlobal(mlir::Value left, mlir::Value right)
{
auto leftGlobal = globalReadOf(left);
auto rightGlobal = globalReadOf(right);
return leftGlobal && rightGlobal && leftGlobal.getGlobalName() == rightGlobal.getGlobalName();
}

bool OwnershipInferencePass::argumentOwnsApart(mlir::Operation *call, int32_t index, const Chain &chain)
{
auto args = callArgs(call);
Expand Down Expand Up @@ -1043,20 +1069,62 @@ namespace own_inference

// ...nor a call's result lent by its arguments (`k.self()`, `k.first()`): what it reads is under them, which
// may be the chain's root (TSLANG 240: `k.self().add2(k.arr[0])` freed `k.arr` under the borrow)
if (borrowingCall(argumentRoot) || borrowingCall(argument))
// (and a virtual call's `this`, read off such a result: `k.self().drain(k.arr[0])` of an overridden `drain`)
auto object = objectOfMethod(argument);
if (borrowingCall(argumentRoot) || borrowingCall(argument) || borrowingCall(object) || borrowingCall(rootOf(object)))
{
return false;
}

// ...and neither made of the other: the argument is no record or view of a root, nor a root read out of it
for (auto source : rootSources(chain))
// (a source lent by a call, `k.at(0)`, is under what the call was given: `k` too - a module-level `k` is a load
// of its own at each mention, so it is matched by its global)
llvm::SetVector<mlir::Value> sources;
if (!lentSources(chain, sources) || (sources.empty() && !madeHere))
{
return false;
}

for (auto source : sources)
{
auto &fromSource = derivedFrom(source);
if (fromSource.contains(argument) || fromSource.contains(argumentRoot) || fromSource.contains(argumentSource) ||
derivedFrom(argumentSource).contains(source))
derivedFrom(argumentSource).contains(source) || readsSameGlobal(source, object))
{
return false;
}
}

return true;
}

bool OwnershipInferencePass::lentSources(const Chain &chain, llvm::SetVector<mlir::Value> &sources)
{
for (auto source : rootSources(chain))
{
sources.insert(source);
}

for (size_t next = 0; next < sources.size(); ++next)
{
if (next >= 32)
{
return false;
}

if (auto *lender = borrowingCall(rootOf(sources[next])))
{
auto lenderArgs = callArgs(lender);
for (auto lent : resultBorrowsAll(lender))
{
if (static_cast<size_t>(lent) >= lenderArgs.size())
{
return false;
}

sources.insert(lenderArgs[lent]);
}
}
}

return true;
Expand Down Expand Up @@ -1320,13 +1388,16 @@ namespace own_inference
auto mayDrop = true;
// A caught value is the exception's until the catch ends: a throw takes what it throws
// (a borrow cannot be thrown), so nothing a call reaches holds it but what it is given
auto caught = llvm::all_of(chain.roots, [&](auto &root) {
// (not a chain with no root known, `k.at(0)` of a module-level `k`: nothing to say it reaches nothing)
auto caught = !chain.roots.empty() && llvm::all_of(chain.roots, [&](auto &root) {
return root.second != Chain::NotOwned || isCaughtValue(root.first);
});
if (caught && !givenClosure)
{
auto &fromRead = derivedFrom(borrowed ? borrowed : read->getResult(0));
auto sources = rootSources(chain);
// (with what a lent source was read under: `k.drain(k.at(0))` reaches `k`'s elements)
llvm::SetVector<mlir::Value> sources;
auto known = lentSources(chain, sources);
// ...an operand made of a source, or a call's result lent by one (`k.self()`, `k.first()`: `this` or
// a field of `k` lent back, which reaches what `k` holds - TSLANG 240, `k.self().add2(k.arr[0])`)
std::function<bool(mlir::Value, int)> reaches = [&](mlir::Value operand, int depth) {
Expand All @@ -1335,6 +1406,22 @@ namespace own_inference
return true;
}

// (a virtual call's `this` and method, `k.self().drain(x)` of an overridden `drain`: the object they
// are read off)
// (not the borrow itself as the `this`: `c.twice()` of `const c = h.c` is given `c`, not `h`)
operand = objectOfMethod(operand);
if (fromRead.contains(operand))
{
return false;
}

if (llvm::any_of(sources, [&](mlir::Value source) {
return derivedFrom(source).contains(operand) || readsSameGlobal(source, operand);
}))
{
return true;
}

auto *lender = depth < 8 ? borrowingCall(rootOf(operand)) : nullptr;
if (!lender)
{
Expand All @@ -1346,7 +1433,7 @@ namespace own_inference
return static_cast<size_t>(index) >= args.size() || reaches(args[index], depth + 1);
});
};
mayDrop = llvm::any_of(drop->getOperands(), [&](mlir::Value operand) {
mayDrop = !known || llvm::any_of(drop->getOperands(), [&](mlir::Value operand) {
return !fromRead.contains(operand) && reaches(operand, 0);
});
}
Expand Down
Loading
Loading