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
34 changes: 29 additions & 5 deletions TSLANG_ISSUES.md
Original file line number Diff line number Diff line change
Expand Up @@ -3758,10 +3758,34 @@ Tests `00tslang_issue_207.ts` (all models) and `00tslang_issue_207_any.ts` (gc,

Not yet:
- Under -mm=own, a value moved in a `try` body that other statements of the body can throw before
(`try { f(); const t = ["b" + i, i]; k.keepOne(t); g(); }`): "moved here on some paths only". The unwind leg reached
before the local is given its value is not known to find it empty. One statement per `try`, or a loop in it, works.
- Under -mm=own, a callee that keeps a parameter and throws before keeping it (`keep(c) { if (...) throw "no";
this.items.push(c); }`) leaks the parameter: 1M throws of `k.keep(new C(i))` grow to about 60 MB. Not new here (a
class instance leaks the same way); the callee's unwind does not give back a kept parameter.
(`try { f(); const t = ["b" + i, i]; k.keepOne(t); g(); }`): "moved here on some paths only". Fixed in 210.
- Under -mm=own, a callee that keeps a parameter and throws before keeping it leaked the parameter: fixed in 209.

Tests `00tslang_issue_208.ts` (all models).

209. Under -mm=own, a method that keeps its parameter on every way it returns by (`this.items.push(c)`) and throws
before keeping it leaked the parameter: the caller gave it up, and the exception took the method out holding it. 1M
throws of `k.keep(new C(i))` grew to about 60 MB, for a `throw` of the method's own (`if (c.n % 3 == 0) throw "no";`)
and for a call that throws (`check(c.n);`, `checkC(c);`). Fixed:
- A `throw` the move cannot have run before releases the parameter first (decideParam), as a parameter the body
releases on the paths that do not move it already was (releaseKeptParamsAtExits) - not where the thrown value is made
of it.
- A call that may throw before the move gives it back on its unwind (UnwindReleasePass): the inference marks the
parameter's slot and the op that moves it (OWN_KEPT_PARAM_ATTR_NAME, OWN_KEPT_PARAM_TAKER_ATTR_NAME), and the call's
cleanup pad releases the slot where no move may have run before the call. Not for the call that is the move, nor
where a handler of the same function the call unwinds to uses the parameter again (`try { check(c.n); } catch {}
this.items.push(c);`, which keeps it).
Each probe now stays at about 5 MB.

Tests `00tslang_issue_209.ts` (all models).

210. Under -mm=own, a value moved into a keeping call in a `try` body with statements that may throw before and after
it (`try { mayFail(i); const t = ["b" + i, i]; k.keepOne(t); mayFail(i + 1); }`, and a literal given straight to the
call): "moved here on some paths only". The `try`'s cleanup releases the local, and is reached from before the move
and after it. The local's slot is made in front of the `try` and starts as null, so the ways before its store find
nothing; the slot is now emptied right before the keeping call, the value already read (clearsOnUnwind), so the ways
past the call find nothing either. A call that keeps its argument has taken it whether it returns or throws (its own
unwind gives it back, 209); the empty slot was refused for a call taker before. 3M turns throwing before, between and
after the moves stay at about 6 MB.

Tests `00tslang_issue_210.ts` (all models).
7 changes: 7 additions & 0 deletions tslang/include/TypeScript/Defines.h
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,13 @@
// the first (own rc fallback design, section 3). A retain left behind without it is an error.
#define OWN_COUNTED_ATTR_NAME "__own_counted"

// -mm=own only, set by OwnershipInferencePass for UnwindReleasePass. On a parameter's slot the function keeps on
// every path it returns by (moved into a field, an array, a keeping call): it owns the value until the move. On the op
// that moves it, OWN_KEPT_PARAM_TAKER_ATTR_NAME. A call that may throw before the move gives it back on its unwind
// (TSLANG 209): the exception leaves the function holding it, and nothing else would.
#define OWN_KEPT_PARAM_ATTR_NAME "__own_kept_param"
#define OWN_KEPT_PARAM_TAKER_ATTR_NAME "__own_kept_param_taker"

// Marks an owned local that took its reference by consuming an OWNED_RESULT_ATTR_NAME value
// instead of by retaining. The slot still releases at every scope exit - that release is what
// gives the consumed reference back - so the pair is still balanced, but there is no
Expand Down
27 changes: 24 additions & 3 deletions tslang/lib/TypeScript/OwnershipInferenceEdgeReleases.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -712,15 +712,36 @@ namespace own_inference
}

// the read, the taker and rc's retain in one block of the body, with nothing between that
// could unwind with the value read but not yet taken: a call that takes it may throw having
// taken it or not
// could unwind with the value read but not yet taken
auto *block = load->getBlock();
if (block->getParent() != &body || taker->getBlock() != block || acquire->getBlock() != block ||
handler.contains(block) || !load->isBeforeInBlock(taker) || isCall(taker))
handler.contains(block) || !load->isBeforeInBlock(taker))
{
return nullptr;
}

// a call that keeps it (`try { f(); const t = [...]; k.keepOne(t); g(); }`) has taken it whether it returns or
// throws - the callee gives it back on its own unwind (TSLANG 209): the slot is emptied right before the call,
// the value already read, so the release on the unwind leg finds nothing on every way past the call, and
// nothing on the ways before the local's store either (it starts as null) (TSLANG 210)
if (isCall(taker))
{
if (acquire != taker)
{
return nullptr;
}

for (auto *op = load->getNextNode(); op && op != taker; op = op->getNextNode())
{
if (isCall(op) || op->hasTrait<mlir::OpTrait::IsTerminator>())
{
return nullptr;
}
}

return taker->getPrevNode();
}

auto *last = taker->isBeforeInBlock(acquire) ? acquire : taker;
for (auto *op = load->getNextNode(); op && op != last->getNextNode(); op = op->getNextNode())
{
Expand Down
24 changes: 24 additions & 0 deletions tslang/lib/TypeScript/OwnershipInferenceKeptParams.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,30 @@ namespace own_inference
}
});

// ...and a `throw` the function is left by before the move (`if (c.n < 0) throw "no"; this.items.push(c);`):
// the exception takes the function out holding what its caller gave it up for, which nothing gave back
// (TSLANG 209). Released there, as releaseKeptParamsAtExits releases one at its throws - unless the move may
// have run on the way (it took the value), or what is thrown is made of it (it goes with the exception)
if (everyPath && moved)
{
// ...and for a call that may throw on the way to the move, UnwindReleasePass gives it back on its unwind
if (auto slotOp = slot.getDefiningOp<mlir_ts::VariableOp>())
{
setAttrTracked(slotOp, OWN_KEPT_PARAM_ATTR_NAME);
setAttrTracked(taker, OWN_KEPT_PARAM_TAKER_ATTR_NAME);
}

getFunction().walk([&](mlir_ts::ThrowCallOp throwOp) {
if (reachableAfter(taker, throwOp, nullptr) || readsSlot(throwOp->getOperand(0), slot))
{
return;
}

mlir::OpBuilder builder(throwOp);
exitReleases.push_back(builder.create<mlir_ts::ReleaseSlotOp>(throwOp->getLoc(), slot));
});
}

// rc's retain goes with the move - a `ts.RetainSlot` too, for an owning local the parameter
// moves into (`let r = init`, spec 33); a call that keeps it is the move itself
if (everyPath && !isCall(receiver.retain))
Expand Down
136 changes: 135 additions & 1 deletion tslang/lib/TypeScript/UnwindReleasePass.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ using namespace ::typescript;
#include "TypeScript/MLIRLogic/MLIRRTTIHelperVC.h"

#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/ScopeExit.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
Expand Down Expand Up @@ -793,6 +794,103 @@ class UnwindReleasePass : public mlir::PassWrapper<UnwindReleasePass, mlir::Oper
return aliases;
}

// ---- kept parameters ----

// Is `value` the value a load of `slot` gives, seen through casts that keep it (a parameter given to a call)?
static bool readOfSlot(mlir::Value value, mlir::Value slot)
{
for (auto depth = 0; depth < 8 && value; ++depth)
{
auto *def = value.getDefiningOp();
if (auto loadOp = mlir::dyn_cast_or_null<mlir_ts::LoadOp>(def))
{
return loadOp.getReference() == slot;
}

if (!mlir::isa_and_nonnull<mlir_ts::CastOp, mlir_ts::ValueOp, mlir_ts::OptionalValueOp>(def))
{
return false;
}

value = def->getOperand(0);
}

return false;
}

// May `to` run after `from`, along any edge (an unwind one too)?
static bool mayRunAfter(mlir::Region &region, mlir::Operation *from, mlir::Operation *to)
{
from = region.findAncestorOpInRegion(*from);
to = region.findAncestorOpInRegion(*to);
if (!from || !to)
{
return true;
}

for (auto *op = from->getNextNode(); op; op = op->getNextNode())
{
if (op == to)
{
return true;
}
}

llvm::SmallPtrSet<mlir::Block *, 16> seen;
llvm::SmallVector<mlir::Block *> work(from->getBlock()->getSuccessors().begin(), from->getBlock()->getSuccessors().end());
while (!work.empty())
{
auto *block = work.pop_back_val();
if (!seen.insert(block).second)
{
continue;
}

if (block == to->getBlock())
{
return true;
}

work.append(block->getSuccessors().begin(), block->getSuccessors().end());
}

return false;
}

// -mm=own: the parameters the function keeps on every path it returns by (OWN_KEPT_PARAM_ATTR_NAME), each with the
// ops that move it (OWN_KEPT_PARAM_TAKER_ATTR_NAME). Until the move the frame holds what the caller gave up for it.
llvm::SmallVector<std::pair<mlir::Value, llvm::SmallVector<mlir::Operation *>>> keptParamsOf(mlir_ts::FuncOp funcOp)
{
llvm::SmallVector<std::pair<mlir::Value, llvm::SmallVector<mlir::Operation *>>> keptParams;
if (compileOptions.memoryModel != MemoryModelOwn)
{
return keptParams;
}

funcOp.walk([&](mlir_ts::VariableOp varOp) {
if (!varOp->hasAttr(OWN_KEPT_PARAM_ATTR_NAME))
{
return;
}

llvm::SmallVector<mlir::Operation *> takers;
funcOp.walk([&](mlir::Operation *op) {
if (op->hasAttr(OWN_KEPT_PARAM_TAKER_ATTR_NAME) &&
llvm::any_of(op->getOperands(), [&](mlir::Value operand) { return readOfSlot(operand, varOp.getResult()); }))
{
takers.push_back(op);
}
});

if (!takers.empty())
{
keptParams.push_back({varOp.getResult(), takers});
}
});

return keptParams;
}

// ---- the ways a handler lets the exception go on ----

// A handler that reads what the frame holds - a `finally` reading a local, its unwind copy -
Expand Down Expand Up @@ -1050,7 +1148,8 @@ class UnwindReleasePass : public mlir::PassWrapper<UnwindReleasePass, mlir::Oper
}
});

if (resources.empty())
auto keptParams = keptParamsOf(funcOp);
if (resources.empty() && keptParams.empty())
{
return;
}
Expand Down Expand Up @@ -1115,6 +1214,14 @@ class UnwindReleasePass : public mlir::PassWrapper<UnwindReleasePass, mlir::Oper
return it->second;
};

llvm::DenseMap<mlir::Value, mlir::Operation *> keptReleases;
auto keptReleasesGone = llvm::make_scope_exit([&]() {
for (auto &entry : keptReleases)
{
entry.second->erase();
}
});

llvm::SmallVector<Plan> plans;
for (auto &site : sites)
{
Expand Down Expand Up @@ -1158,6 +1265,33 @@ class UnwindReleasePass : public mlir::PassWrapper<UnwindReleasePass, mlir::Oper
}
}

// a kept parameter the call may throw before the move of (`check(c.n); this.items.push(c);`): the frame
// still holds it there, and the exception would take the frame out with it (TSLANG 209). Not where the
// call is the move, nor where a move may have run before, nor where the handler the call unwinds to may use
// it again. A call given it that is not the move borrows it (`checkC(c); this.items.push(c);`)
for (auto &[slot, takers] : keptParams)
{
if (llvm::any_of(plan.releases, [&](mlir::Operation *release) { return resourceOf(release) == slot; }) ||
llvm::is_contained(takers, site.call) ||
llvm::any_of(takers, [&](mlir::Operation *taker) { return mayRunAfter(region, taker, site.call); }) ||
(site.dest && llvm::any_of(aliasesOfResource(slot), [&](mlir::Value alias) {
return usedAgainFrom(site.dest, alias);
})))
{
continue;
}

auto &release = keptReleases[slot];
if (!release)
{
// a release to copy into the pad, in no block: what the pad runs, never this function
mlir::OpBuilder detached(funcOp.getContext());
release = detached.create<mlir_ts::ReleaseSlotOp>(slot.getLoc(), slot);
}

plan.releases.push_back(release);
}

if (!plan.releases.empty())
{
plans.push_back(std::move(plan));
Expand Down
10 changes: 10 additions & 0 deletions tslang/test/tester/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2560,6 +2560,16 @@ foreach(issue208_mm gc rc none own)
tslang_add_test(NAME test-jit-00tslang_issue_208-${issue208_mm} COMMAND test-runner -jit -mm=${issue208_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_208.ts")
tslang_add_test(NAME test-compile-00tslang_issue_208-${issue208_mm} COMMAND test-runner -mm=${issue208_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_208.ts")
endforeach()
# TSLANG 209: under own a kept parameter given back when its method throws before keeping it
foreach(issue209_mm gc rc none own)
tslang_add_test(NAME test-jit-00tslang_issue_209-${issue209_mm} COMMAND test-runner -jit -mm=${issue209_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_209.ts")
tslang_add_test(NAME test-compile-00tslang_issue_209-${issue209_mm} COMMAND test-runner -mm=${issue209_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_209.ts")
endforeach()
# TSLANG 210: under own a value moved in a `try` body between statements that may throw
foreach(issue210_mm gc rc none own)
tslang_add_test(NAME test-jit-00tslang_issue_210-${issue210_mm} COMMAND test-runner -jit -mm=${issue210_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_210.ts")
tslang_add_test(NAME test-compile-00tslang_issue_210-${issue210_mm} COMMAND test-runner -mm=${issue210_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_210.ts")
endforeach()
# the array `splice` gives back, kept in a local and returned: under rc its header is born owned (it was freed on
# the way out)
foreach(splice_mm gc rc none)
Expand Down
48 changes: 48 additions & 0 deletions tslang/test/tester/tests/00tslang_issue_209.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// TSLANG 209, every model: under -mm=own a method that keeps its parameter (pushes it) and throws before keeping it - by
// a `throw` of its own or a call that throws - leaked the parameter: 1M throws grew to about 60 MB.

class C {
s: string;
constructor(public n: number) { this.s = "x" + n; }
}
function check(n: number) {
if (n % 3 == 0) throw "no";
}
function checkC(c: C) {
if (c.n % 3 == 0) throw "no";
}
// (each method keeps `c` on every way it returns by)
class K {
items: C[] = [];
keep(c: C) {
check(c.n);
this.items.push(c);
}
keepCaught(c: C) {
try {
check(c.n);
} catch (e) {}
this.items.push(c);
}
keepPassed(c: C) {
checkC(c);
this.items.push(c);
}
keepThrow(c: C) {
if (c.n % 3 == 0) throw "no";
this.items.push(c);
}
}
function main() {
const k = new K();
let thrown = 0;
for (let i = 0; i < 6; i++) {
try { k.keep(new C(i)); } catch (e) { thrown++; }
try { k.keepCaught(new C(i)); } catch (e) { thrown++; }
try { k.keepPassed(new C(i)); } catch (e) { thrown++; }
try { k.keepThrow(new C(i)); } catch (e) { thrown++; }
}
assert(thrown == 6 && k.items.length == 18, "counts");
assert(k.items[17].s == "x5");
print("done.");
}
Loading
Loading