diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 0a0d58f73..520798ce9 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -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(location, mlir_ts::RefType::get(array.getType()), mlir::Value(), + builder.getBoolAttr(false), builder.getIndexAttr(0)); + auto empty = builder.create(location, array.getType()); + builder.create(location, empty, slot); + auto varOp = slot.getDefiningOp(); + 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(location, array); + builder.create(location, array, slot); + } + + genContext.ownedVars->push_back(slot); + arrayRef = slot; + } + else if (storesArray || calls) { arrayRef = builder.create(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); diff --git a/tslang/lib/TypeScript/OwnershipInferenceKeptParams.cpp b/tslang/lib/TypeScript/OwnershipInferenceKeptParams.cpp index 5c41234e5..25e1b6716 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceKeptParams.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceKeptParams.cpp @@ -201,6 +201,16 @@ namespace own_inference bool OwnershipInferencePass::movesOnExclusivePaths(mlir::Value slot, llvm::ArrayRef receivers, bool released, llvm::SetVector &toErase) { + // two moves into one call (`f2(p, p)` of a callee keeping both): on the same path, whatever reaches what + llvm::SmallPtrSet retains; + for (auto &receiver : receivers) + { + if (!retains.insert(receiver.retain).second) + { + return false; + } + } + auto assignments = slotAssignments(slot); llvm::SmallVector kills(assignments.begin(), assignments.end()); if (auto varOp = slot.getDefiningOp()) diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.cpp b/tslang/lib/TypeScript/OwnershipInferencePass.cpp index b0f7ddc1f..cd8d52d28 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePass.cpp @@ -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(user); + auto propertyRefOp = storeOp && storeOp.getValue() == stored + ? storeOp.getReference().getDefiningOp() + : mlir_ts::PropertyRefOp(); + return propertyRefOp && closureOfBox(propertyRefOp.getObjectRef()) && user->getLoc() == op->getLoc(); + }; + auto retainedRead = value ? value.getDefiningOp() : mlir_ts::LoadOp(); + auto fillsBox = retainedRead && llvm::any_of(retainedRead.getReference().getUsers(), [&](mlir::Operation *user) { + auto loadOp = mlir::dyn_cast(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) { @@ -2555,6 +2572,12 @@ namespace own_inference auto storeOp = mlir::dyn_cast(user); borrows = !(storeOp && storeOp.getValue() == used) && !mlir::isa(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(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) @@ -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(user) && used != value && lender && + isCall(lender) && borrowingCall(used) == lender) + { + return; + } + if (!borrows) { usable = false; @@ -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() && isCall(user)) + { + usable = false; + return; + } + if (user->hasTrait()) { auto branch = mlir::dyn_cast(user); @@ -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(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)) diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.h b/tslang/lib/TypeScript/OwnershipInferencePass.h index 5be6d8c53..22d658917 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.h +++ b/tslang/lib/TypeScript/OwnershipInferencePass.h @@ -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 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 &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 diff --git a/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp b/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp index 4f7898210..ab0e81b6b 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp @@ -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(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); @@ -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 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 &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(lent) >= lenderArgs.size()) + { + return false; + } + + sources.insert(lenderArgs[lent]); + } + } } return true; @@ -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 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 reaches = [&](mlir::Value operand, int depth) { @@ -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) { @@ -1346,7 +1433,7 @@ namespace own_inference return static_cast(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); }); } diff --git a/tslang/test/fuzz/mm_fuzz.py b/tslang/test/fuzz/mm_fuzz.py index 5353c07f7..239036464 100644 --- a/tslang/test/fuzz/mm_fuzz.py +++ b/tslang/test/fuzz/mm_fuzz.py @@ -32,6 +32,14 @@ # callback stored in a field; closures given straight to a call. The shapes of TSLANG 236-240; it found the # lent-`this` crash (`k.self().drain(k.head())`). # +# mm_fuzz.py --deep run [--count N] [--seed S] +# --classes, and DEEP_HEADER too: a subclass KS overriding K's methods to free other fields (`new KS()` and +# `mkk(i)` beside `new K()`, so a call of a K may run either), a getter lending a field and a setter replacing +# it, a call that frees a field and then throws (in try/catch/finally), a generator method yielding a field's +# elements. It found a virtual call through `this` lent back that nothing counted (`k.self().drain(k.arr[0])` +# of an overridden `drain`), the same through a module-level `k`, and a parameter given twice to a call that +# keeps both. +# # mm_fuzz.py replay FILE.ts|DIR ... # Check existing programs (the seeds/ folder by default), without generating or minimizing. # seeds/ holds the probes reviewers wrote by hand against own-raytrace that still failed @@ -314,6 +322,26 @@ def check_program(tc, text, work, models=("rc", "own"), runs=1): "@noinline function kmut(k: K, i: number): void { k.replaceArr(i); }", ] +# --deep (implies --classes): K's methods overridden in a subclass that frees other fields (a call of a K may run +# either), a getter lending a field and a setter replacing it, a call that throws after freeing a field the +# argument came from, and a generator method yielding the elements of a field +DEEP_K_MEMBERS = [ + " get cur(): N { return this.arr[0]; }", + " set cur(x: N) { this.arr = [x, mk(4)]; churn(); }", + " *items() { for (const x of this.arr) { yield x; } }", +] + +DEEP_HEADER = [ + "class KS extends K {", + " drain(x: N): number { this.n = mk(7); this.arr = [mk(7)]; churn(); return x.v.x + 1; }", + " first(): N { this.arr.push(mk(11)); return this.arr[this.arr.length - 1]; }", + " run(x: N): number { this.arr = [mk(12), mk(13)]; churn(); return x.v.x + 2; }", + " resetN(i: number): void { this.arr.length = 0; this.arr.push(mk(i)); churn(); }", + "}", + "@noinline function mkk(i: number): K { if (i % 2 == 0) { return new K(); } return new KS(); }", + "@noinline function kthrow(k: K, x: N, i: number): number { k.replaceArr(i); if (i % 3 == 0) { throw new W(i); } return x.v.x; }", +] + AVOIDABLE = { "arg-assign": "an assignment inside an argument list, f(n, (n = mk(1), m))", "globals": "the module-level G, HG, GS and GA", @@ -386,11 +414,12 @@ def declare(self, ty, mutable, minlen=0): class Gen: - def __init__(self, seed, size=None, avoid=(), extended=False, classes=False): + def __init__(self, seed, size=None, avoid=(), extended=False, classes=False, deep=False): self.r = random.Random(seed) self.seed = seed self.extended = extended # EXTENDED_HEADER's types too - self.classes = classes # CLASSES_HEADER's K and the statements over it + self.classes = classes or deep # CLASSES_HEADER's K and the statements over it + self.deep = deep # DEEP_HEADER's subclass, accessors, throws and generator too self.avoid = set(avoid) # shapes not to generate, once their bugs are known (AVOIDABLE) self.counter = 0 self.globals = [] @@ -466,6 +495,8 @@ def expr(self, ctx, ty, fresh_bias=0.4, depth=0): if ty == "K": if alias and self.chance(0.6): return self.pick(vs).name + if self.deep: + return self.pick(["new K()", "new KS()", "mkk(%s)" % self.num_k(ctx)]) return "new K()" if ty == "V": opts = [] @@ -794,7 +825,7 @@ def kmut(self, ctx): "%s.add(%s);" % (k, self.expr(ctx, "N", 0.4)), "churn();", "%s.swapIn(%s);" % (k, self.expr(ctx, "N", 0.3)), "%s.tag += %s.drain(%s);" % (k, k, self.expr(ctx, "N", 0.3)), - ]) + ] + (["%s.cur = %s;" % (k, self.expr(ctx, "N", 0.4))] if self.deep else [])) def kcallback(self, ctx): """A callback for K.setCb: harmless, reading what it captures, or writing a K's fields.""" @@ -805,10 +836,40 @@ def kcallback(self, ctx): return "(x: N): number => x.v.x + %s" % self.num_read(ctx, no_calls=True) return "(x: N): number => { %s return x.v.x; }" % self.kmut(ctx) + def kdeep(self, ctx, sp, k): + acc = ctx.acc + c = self.r.random() + if c < 0.3: + # a call that frees a field, then throws, given that field's element + body = [sp + "try {", "%s %s += kthrow(%s, %s, %s);" % (sp, acc, k, self.pick( + ["%s.first()" % k, "%s.arr[0]" % k, "%s.cur" % k, "%s.head()" % k, self.expr(ctx, "N", 0.4)]), + self.num_k(ctx)), sp + "} catch (e) {", "%s %s += 1;" % (sp, acc)] + if self.chance(0.4): + body += [sp + "} finally {", "%s %s += %s.arr.length;" % (sp, acc, k)] + return body + [sp + "}"] + if c < 0.55: + # the getter's lent element across a call that replaces it + v = ctx.declare("N", False) + return ["%sconst %s = %s.cur;" % (sp, v.name, k), sp + self.kmut(ctx), + "%s%s += %s;" % (sp, acc, self.pick(READS["N"]).format(v.name))] + if c < 0.7: + return ["%s%s += %s.cur.v.x;" % (sp, acc, k), "%s%s.cur = %s;" % (sp, k, self.pick( + ["%s.head()" % k, "%s.cur" % k, "%s.first()" % k, self.expr(ctx, "N", 0.4)]))] + if c < 0.85: + # the elements a generator yields across calls that free them + x = self.fresh("x") + return ["%sfor (const %s of %s.items()) {" % (sp, x, k), sp + " " + self.kmut(ctx), + "%s %s += %s;" % (sp, acc, self.pick(READS["N"]).format(x)), sp + "}"] + # a call that may run an override that frees what its argument came from + return ["%s%s += %s.%s(%s);" % (sp, acc, k, self.pick(["drain", "run"]), self.pick( + ["%s.first()" % k, "%s.arr[0]" % k, "%s.cur" % k, "%s.n" % k, self.expr(ctx, "N", 0.4)]))] + def kcall(self, ctx, sp): ks = ctx.vars(lambda v: v.ty == "K") k = self.pick(ks).name acc = ctx.acc + if self.deep and self.chance(0.4): + return self.kdeep(ctx, sp, k) c = self.r.random() if c < 0.25: # a borrow of a method's result across a call that may write some field (236, 237) @@ -926,7 +987,12 @@ def gen_globals(self): return lines def program(self): - lines = list(HEADER) + (EXTENDED_HEADER if self.extended else []) + (CLASSES_HEADER if self.classes else []) + klass = list(CLASSES_HEADER) + if self.deep: + end = klass.index("}") + klass[end:end] = DEEP_K_MEMBERS + klass += DEEP_HEADER + lines = list(HEADER) + (EXTENDED_HEADER if self.extended else []) + (klass if self.classes else []) if "literal-temp" in self.avoid: lines += ["@noinline function mna(i: number): N[] { const a: N[] = [mk(i)]; return a; }"] if self.extended: @@ -940,7 +1006,8 @@ def program(self): main = ["function main() {", " let s: number = 0;"] if self.classes: for _ in range(self.r.randint(1, 2)): - main.append(" const %s = new K();" % ctx.declare("K", False).name) + main.append(" const %s%s = %s;" % (ctx.declare("K", False).name, ": K" if self.deep else "", + self.pick(["new K()", "new KS()"]) if self.deep else "new K()")) main += self.stmts(ctx, self.r.randint(1, 2 + self.size // 2), 1) iters = self.pick([1, 3, 20, 100, 300]) ctx.loop_vars.append("i") @@ -1499,7 +1566,7 @@ def cmd_leak_flag_only(args, tc): stats = Stats() def one(seed): - text = Gen(seed, avoid=args.avoid, extended=not args.objects_only, classes=args.classes).program() + text = Gen(seed, avoid=args.avoid, extended=not args.objects_only, classes=args.classes, deep=args.deep).program() name = "s%d" % seed work = os.path.join(work_root, name) if own_accepts(tc, text, work, False): @@ -1569,7 +1636,7 @@ def cmd_leaks(args, tc, recheck): minimized = [0] def one(seed): - text = Gen(seed, avoid=args.avoid, extended=not args.objects_only, classes=args.classes).program() + text = Gen(seed, avoid=args.avoid, extended=not args.objects_only, classes=args.classes, deep=args.deep).program() work = os.path.join(work_root, str(seed)) res = leak_check(tc, text, work, args.low, args.high) if res is None: @@ -1705,7 +1772,7 @@ def variant(label, text, work): return gc.status == "ok" and gc.run_code == 0 and res["own"].status == "rejected" def one(seed): - text = Gen(seed, avoid=args.avoid, classes=args.classes).program() + text = Gen(seed, avoid=args.avoid, classes=args.classes, deep=args.deep).program() if variant(str(seed), text, os.path.join(work_root, str(seed))) and not args.no_repair: # own rejected it: delete what own complains about until it accepts, and check that work = os.path.join(work_root, "%dr" % seed) @@ -1825,6 +1892,9 @@ def main(): ap.add_argument("--classes", action="store_true", help="generate class K too: methods that lend fields back, replace or empty them, and run a stored " "callback (the shapes of TSLANG 236-240)") + ap.add_argument("--deep", action="store_true", + help="--classes, and K's methods overridden in a subclass that frees other fields, a getter and setter, " + "a call that throws after freeing, a generator method (DEEP_HEADER)") sub = ap.add_subparsers(dest="cmd", required=True) r = sub.add_parser("run") r.add_argument("--count", type=int, default=200) @@ -1865,7 +1935,7 @@ def main(): args = ap.parse_args() if args.cmd == "show": - sys.stdout.write(Gen(args.seed, avoid=args.avoid, extended=args.extended, classes=args.classes).program()) + sys.stdout.write(Gen(args.seed, avoid=args.avoid, extended=args.extended, classes=args.classes, deep=args.deep).program()) return 0 own_fallback = args.own_fallback or getattr(args, "own_fallback_here", False) tc = Toolchain(args.tslang, args.tslang_lib_path, args.gc_lib_path, own_fallback) diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index c4fc2b249..2e066e3e1 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -2810,7 +2810,7 @@ set_tests_properties(test-compile-00tslang_issue_234-quiet # TSLANG 236-240: -mm=own borrows end only where what they read is overwritten or freed: a result's places (236), an # `int[]` holds no object (237), a closure given to a call borrows a named const (238), a call's result borrows only # the arguments it says (239), a value given to a call that may free it is counted (240); every model runs them -foreach(issue236_n 236 237 238 239 240 240_temps) +foreach(issue236_n 236 237 238 239 240 240_temps 240_fuzz) foreach(issue236_mm gc rc none own) tslang_add_test(NAME test-jit-00tslang_issue_${issue236_n}-${issue236_mm} COMMAND test-runner -jit -mm=${issue236_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_${issue236_n}.ts") tslang_add_test(NAME test-compile-00tslang_issue_${issue236_n}-${issue236_mm} COMMAND test-runner -mm=${issue236_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_${issue236_n}.ts") @@ -6561,6 +6561,18 @@ add_test(NAME test-rc-argument-place-set-length-ir set_tests_properties(test-rc-argument-place-set-length-ir PROPERTIES PASS_REGULAR_EXPRESSION "\"ts[.]ElementRef\"[^\n]*\n *%[0-9]+ = \"ts[.]Load\"[^\n]*-> !ts[.]class<@N[^\n]*\n *\"ts[.]Retain\"[(]%[0-9]+[)] : [(]!ts[.]class<@N" FAIL_REGULAR_EXPRESSION "error:|Stack dump") +# ...and the array the left side of `k.arr[i] = g(k)` read, which `g` gives the place another one for (mm_fuzz.py +# --classes): held across the call in a slot the scope owns. IR: retained right after its read, stored in that slot. +foreach(store_replaced_mm gc rc none) + tslang_add_test(NAME test-jit-${store_replaced_mm}-rc-element-store-array-replaced-by-call COMMAND test-runner -jit -mm=${store_replaced_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00rc_element_store_array_replaced_by_call.ts") + tslang_add_test(NAME test-compile-${store_replaced_mm}-rc-element-store-array-replaced-by-call COMMAND test-runner -mm=${store_replaced_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00rc_element_store_array_replaced_by_call.ts") +endforeach() +add_test(NAME test-rc-element-store-array-replaced-by-call-ir + COMMAND $ --emit=mlir --no-default-lib -mm=rc + "${PROJECT_SOURCE_DIR}/test/tester/tests/00rc_element_store_array_replaced_by_call.ts") +set_tests_properties(test-rc-element-store-array-replaced-by-call-ir + PROPERTIES PASS_REGULAR_EXPRESSION "-> !ts[.]array number; +class K { arr: W[] = [new W(2)]; cb: Shared | null = null; setCb(f: KF): void { this.cb = new Shared(f); } } +// g returns a borrow of p, and its closure would own p: the caller's (found by mm_fuzz.py --classes) +function g(p: K): W { p.setCb((x: W): number => x.x + p.arr[0].x); return p.arr[0]; } +function main() { + const k = new K(); + for (let i = 0; i < 3; i++) { + g(k); + } + print(k.arr[0].x); +} diff --git a/tslang/test/tester/own/own_err_counted_read_used_in_try.ts b/tslang/test/tester/own/own_err_counted_read_used_in_try.ts new file mode 100644 index 000000000..74b636c02 --- /dev/null +++ b/tslang/test/tester/own/own_err_counted_read_used_in_try.ts @@ -0,0 +1,15 @@ +class W { x: number; constructor(x: number) { this.x = x; } } +class K { arr: W[] = [new W(2)]; replace(): void { this.arr = [new W(9)]; } add(x: W): number { return x.x; } } +// `e` is used again in the `try` after `k.replace()` freed it: a call there ends its block (an invoke), and no count +// is given back after one - refused, as a use in another block is (found by mm_fuzz.py --classes) +function main() { + const k = new K(); + const e = k.arr[0]; + k.replace(); + let s = e.x; + try { + s += k.add(e); + } finally { + } + print(s); +} diff --git a/tslang/test/tester/own/own_err_object_literal_counted_read.ts b/tslang/test/tester/own/own_err_object_literal_counted_read.ts new file mode 100644 index 000000000..431c332a1 --- /dev/null +++ b/tslang/test/tester/own/own_err_object_literal_counted_read.ts @@ -0,0 +1,10 @@ +class V { x: number; constructor(x: number) { this.x = x; } } +class N { items: V[] = [new V(9)]; } +interface IX { v: V; } +let G: N = new N(); +// f frees G.items[0], which the object literal it is given holds: not counted across the call (its uses through +// the literal are f's), refused (found by mm_fuzz.py --deep) +function f(p: IX): number { G.items[0] = new V(2); return p.v.x; } +function main() { + print(f({ v: G.items[0] })); +} diff --git a/tslang/test/tester/own/own_err_param_moved_twice_one_call.ts b/tslang/test/tester/own/own_err_param_moved_twice_one_call.ts new file mode 100644 index 000000000..153378736 --- /dev/null +++ b/tslang/test/tester/own/own_err_param_moved_twice_one_call.ts @@ -0,0 +1,9 @@ +class N { x: number; constructor(x: number) { this.x = x; } } +// f keeps both parameters (it assigns them): `f(p, p)` gives p away twice (found by mm_fuzz.py --deep) +function f(a: N, b: N): number { a = new N(5); b = new N(6); return a.x + b.x; } +function g(p: N): number { + return f(p, p); +} +function main() { + print(g(new N(8))); +} diff --git a/tslang/test/tester/tests/00rc_element_store_array_replaced_by_call.ts b/tslang/test/tester/tests/00rc_element_store_array_replaced_by_call.ts new file mode 100644 index 000000000..12f5aafc9 --- /dev/null +++ b/tslang/test/tester/tests/00rc_element_store_array_replaced_by_call.ts @@ -0,0 +1,58 @@ +// -mm=rc (found by mm_fuzz.py --classes): `k.arr[0] = g(k)`, where `g` gives `k.arr` another array. The store goes into +// the array the left side read, as JavaScript has it; rc released that array inside `g` and then stored into it and +// grew it. It is held across the right side, and given back at the scope's end - or on the unwind when `g` throws. + +class W { x: number; constructor(x: number) { this.x = x; } } +class K { arr: W[] = [new W(1), new W(2)]; } + +function churn() { + const hold: W[][] = []; + for (let i = 0; i < 64; i++) { + hold.push([new W(777), new W(778)]); + } +} + +function replace(k: K, x: number): W { + k.arr = [new W(9), new W(9)]; + churn(); + return new W(x); +} + +function replaceOrThrow(k: K, x: number): W { + k.arr = [new W(9), new W(9)]; + churn(); + if (x % 3 == 0) { + throw x; + } + + return new W(x); +} + +function main() { + let s = 0; + const k = new K(); + for (let i = 0; i < 100; i++) { + const old = k.arr; + k.arr[0] = replace(k, i); + // the old array got the store, the new one did not + s += old[0].x + k.arr[0].x + k.arr.length; + // ...and grown past its end + const before = k.arr; + k.arr[3] = replace(k, i + 1); + s += before.length + before[3].x + k.arr.length; + } + + let caught = 0; + for (let i = 0; i < 100; i++) { + try { + k.arr[1] = replaceOrThrow(k, i); + s += k.arr[1].x; + } catch (e) { + caught++; + } + } + + print(s, caught); + assert(s == 12294 && caught == 34); + print("done."); +} diff --git a/tslang/test/tester/tests/00tslang_issue_240_fuzz.ts b/tslang/test/tester/tests/00tslang_issue_240_fuzz.ts new file mode 100644 index 000000000..58dac117c --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_240_fuzz.ts @@ -0,0 +1,55 @@ +// -mm=own, found by mm_fuzz.py --classes/--deep after TSLANG 240 counted every form of argument given to the call +// that may free it: each borrow below is counted across the call (or the result that borrows it, after it), and +// each program prints what gc prints. + +class W { x: number; constructor(x: number) { this.x = x; } } +class N { v: W; items: W[]; constructor(x: number) { this.v = new W(x); this.items = [new W(x + 1)]; } } +@noinline function mk(i: number): N { return new N(i); } +function churn() { const hold: N[] = []; for (let i = 0; i < 64; i++) { hold.push(new N(777)); } } + +class H { n: N = mk(1); } + +class K { + arr: N[] = [mk(2), mk(3)]; + @lends("this") at(i: number): N { return this.arr[i % this.arr.length]; } + self(): this { return this; } + drain(x: N): number { this.arr.length = 0; this.arr.push(mk(5)); this.arr.push(mk(6)); churn(); return x.v.x; } +} + +// an override: a call of `drain` through a K may run either +class KS extends K { + drain(x: N): number { this.arr = [mk(7)]; churn(); return x.v.x + 100; } +} + +// returns its second argument after freeing what it may have been read from +function g(h: H, p: N): N { + h.n = mk(4); + churn(); + return p; +} + +const HG = new H(); +const KG: K = new K(); + +function main() { + let s = 0; + for (let i = 0; i < 3; i++) { + // the result borrows the counted argument: counted until the result's last use + const r = g(HG, HG.n); + churn(); + s += r.v.x; + + // a virtual call through `this` lent back + const k: K = i % 2 == 0 ? new K() : new KS(); + s += k.self().drain(k.arr[0]); + s += k.self().drain(k.at(i)); + + // a module-level K: each mention a read of its own + s += KG.drain(KG.at(i + 1)); + s += KG.self().drain(KG.arr[0]); + } + + print(s); + assert(s == 261); + print("done."); +}