diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 30010600b..184ed0a97 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -3697,11 +3697,11 @@ class MLIRGenImpl mlir::LogicalResult mlirGenFunctionVar(VariableDeclaration item, VariableClass varClass, const GenContext &genContext); - // TODO: to support '...' u need to use 'processOperandSpreadElement' and instead of "index" param use "next" logic + // (`iteratorSource`: the iterator `init` is the `next` of, which a rest element `...rest` reads on to its end) ValueOrLogicalResult processDeclarationArrayBindingPatternSubPath( - mlir::Location location, int index, mlir::Type type, mlir::Value init, + mlir::Location location, int index, mlir::Type type, mlir::Value init, bool isDotDotDot, bool isIterator, bool isArrayLike, mlir::Value arrayLikeLengthValue, mlir::Type arrayLikeElementType, - Expression defaultValue, bool bindsName, const GenContext &genContext); + Expression defaultValue, bool bindsName, mlir::Value iteratorSource, const GenContext &genContext); // An element of an array value past its end is undefined (`const [a, b] = [mk(5)] as N[]`: b, as node has it). // A reference element type (a class, an interface, an object, an array, a tuple, a union with one of those or diff --git a/tslang/lib/TypeScript/MLIRGenVariables.cpp b/tslang/lib/TypeScript/MLIRGenVariables.cpp index 85c1c32fc..cba8b8e06 100644 --- a/tslang/lib/TypeScript/MLIRGenVariables.cpp +++ b/tslang/lib/TypeScript/MLIRGenVariables.cpp @@ -508,7 +508,7 @@ namespace mlirgen ValueOrLogicalResult MLIRGenImpl::processDeclarationArrayBindingPatternSubPath( mlir::Location location, int index, mlir::Type type, mlir::Value init, bool isDotDotDot, bool isIterator, bool isArrayLike, mlir::Value arrayLikeLengthValue, mlir::Type arrayLikeElementType, - Expression defaultValue, bool bindsName, const GenContext &genContext) + Expression defaultValue, bool bindsName, mlir::Value iteratorSource, const GenContext &genContext) { // An element's default (`const [a = mk(1), b = mk(2)] = [mk(i)]`) is its value where the element is missing - past // the end of the source, or undefined there - as in TypeScript. It was not applied: an element past the end of a @@ -788,10 +788,27 @@ namespace mlirgen }) .Default([&](auto type) { + // `const [first, ...rest] = m.entries()`: the rest is an array of what the iterator gives from + // here on, made as `[...iterator]` is (the elements before took theirs with `next()` already) + if (isDotDotDot && isIterator && iteratorSource) + { + SmallVector values; + ArrayInfo arrayInfo; + if (mlir::failed(processArrayValuesSpreadElement(location, iteratorSource, values, arrayInfo, genContext))) + { + return mlir::Value(); + } + + arrayInfo.adjustArrayType(getAnyType()); + arrayInfo.isConst = false; + auto restArray = createArrayFromArrayInfo(location, values, arrayInfo, genContext); + return restArray.failed_or_no_value() ? mlir::Value() : V(restArray); + } + if (isDotDotDot) { emitError(location) << "Array Binding Pattern: spread is not implemented for type: " << to_print(type); - return mlir::Value(); + return mlir::Value(); } if (isIterator) @@ -884,6 +901,7 @@ namespace mlirgen mlir::Value arrayLikeLengthValue; mlir::Type arrayLikeElementType; auto isIterator = false; + mlir::Value iteratorSource; auto isSourceArrayLike = false; auto isArrayOrTuple = isa(typeRef) || isa(typeRef) @@ -902,9 +920,10 @@ namespace mlirgen location, iteratorValue, ITERATOR_NEXT, false, genContext); if (nextProperty) { + iteratorSource = iteratorValue; init = V(nextProperty); isIterator = true; - } + } } } else if (hasIterator(location, init, genContext)) @@ -914,6 +933,7 @@ namespace mlirgen location, init, ITERATOR_NEXT, false, genContext); if (nextProperty) { + iteratorSource = init; init = V(nextProperty); isIterator = true; } @@ -957,7 +977,7 @@ namespace mlirgen auto subValueFunc = [&](mlir::Location location, const GenContext &genContext) { auto result = processDeclarationArrayBindingPatternSubPath( location, index, type, init, !!arrayBindingElement->dotDotDotToken, isIterator, isSourceArrayLike, arrayLikeLengthValue, arrayLikeElementType, - arrayBindingElement->initializer, arrayBindingElement->name == SyntaxKind::Identifier, genContext); + arrayBindingElement->initializer, arrayBindingElement->name == SyntaxKind::Identifier, iteratorSource, genContext); if (result.failed_or_no_value()) { return std::make_tuple(mlir::Type(), mlir::Value(), TypeProvided::No); diff --git a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp index 6f8d558e6..67e56ad21 100644 --- a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp +++ b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp @@ -362,6 +362,89 @@ class OwnedReturnConsumptionPass holdsWhatItIsGiven(mth, innerOp, /*givenToCall=*/false); } + // ...or a tuple literal built in place (`[["a" + i, 1]]`, `new Map([["a" + i, 1]])`): a local nothing releases, + // filled field by field, read whole once into this literal (and the retain the literal took of it). Each field + // that owns memory is given a new value no one else keeps (`"a" + i`) or a string constant, so the tuple is a + // new value moved in as `[mk(i)]` is, and goes with the literal. Before, the literal looked as if it borrowed the + // tuple, was given back by nothing, and each call leaked it and what its fields held. + static bool isInPlaceTupleLiteral(MLIRTypeHelper &mth, mlir_ts::CreateArrayOp arrayOp, mlir::Value element) + { + // (a tuple's fields have no names; an object literal's do, and is a record of its own: classifyRecords) + auto tupleType = mlir::dyn_cast(element.getType()); + if (!tupleType || llvm::any_of(tupleType.getFields(), [](mlir_ts::FieldInfo field) { return !!field.id; }) || + llvm::count(arrayOp->getOperands(), element) != 1) + { + return false; + } + + auto onlyThisLiteral = llvm::all_of(element.getUsers(), [&](mlir::Operation *user) { + return user == arrayOp.getOperation() || + (mlir::isa(user) && user->getBlock() == arrayOp->getBlock() && user->isBeforeInBlock(arrayOp)); + }); + if (!onlyThisLiteral) + { + return false; + } + + // a new value, or a string constant: nothing else owns either + auto isNewField = [&](mlir::Value stored) { + if (!mth.ownsHeapMemory(arrayOp->getLoc(), stored.getType())) + { + return true; + } + + auto *storedOp = stored.getDefiningOp(); + if (!storedOp) + { + return false; + } + + if (auto castOp = mlir::dyn_cast(storedOp); castOp && castOp.getIn().getDefiningOp()) + { + return true; + } + + return storedOp->hasAttr(OWNED_RESULT_ATTR_NAME) && llvm::all_of(stored.getUsers(), [&](mlir::Operation *user) { + return mlir::isa(user) && + (!mlir::isa(user) || user->getOperand(0) == stored); + }); + }; + + // `["a", 1]` of values only: one `ts.CreateTuple` + if (auto createTupleOp = element.getDefiningOp()) + { + return createTupleOp->getBlock() == arrayOp->getBlock() && llvm::all_of(createTupleOp->getOperands(), isNewField); + } + + auto loadOp = element.getDefiningOp(); + auto varOp = loadOp ? loadOp.getReference().getDefiningOp() : mlir_ts::VariableOp(); + if (!varOp || varOp->hasAttr(OWNED_LOCAL_ATTR_NAME) || varOp.getCaptured().value_or(false) || !varOp.getInitializer() || + !varOp.getInitializer().getDefiningOp()) + { + return false; + } + + auto reads = 0; + return llvm::all_of(varOp->getUsers(), [&](mlir::Operation *varUser) { + if (varUser == loadOp.getOperation()) + { + return ++reads == 1; + } + + auto fieldOp = mlir::dyn_cast(varUser); + return fieldOp && fieldOp->getBlock() == arrayOp->getBlock() && fieldOp->isBeforeInBlock(loadOp) && + llvm::all_of(fieldOp->getUsers(), [&](mlir::Operation *fieldUser) { + if (auto storeOp = mlir::dyn_cast(fieldUser)) + { + return storeOp.getReference() == fieldOp.getResult() && isNewField(storeOp.getValue()); + } + + return mlir::isa(fieldUser) && fieldUser->use_empty(); + }); + }) && + reads == 1; + } + // ...or, under -mm=own, a value something else had, which the literal took a retain of (`[mk(i + 4), o]` of a local // `o`, `[mk(i), GA[0]]`). A literal that does not borrow takes every item it is given (callGivenAgain): the // inference moves the value in (`o`'s own release goes), counts it with --own-fallback=count (the retain stays, @@ -434,7 +517,7 @@ class OwnedReturnConsumptionPass onlyNoValues = false; - if (isMovedIn(arrayOp, element) || isNestedLiteral(mth, arrayOp, element)) + if (isMovedIn(arrayOp, element) || isNestedLiteral(mth, arrayOp, element) || isInPlaceTupleLiteral(mth, arrayOp, element)) { anyNew = true; continue; @@ -497,8 +580,26 @@ class OwnedReturnConsumptionPass for (auto element : arrayOp->getOperands()) { - if (!mth.ownsHeapMemory(arrayOp->getLoc(), element.getType()) || isBorrowedText(element) || isMovedIn(arrayOp, element) || - !isNestedLiteral(mth, arrayOp, element)) + if (!mth.ownsHeapMemory(arrayOp->getLoc(), element.getType()) || isBorrowedText(element) || isMovedIn(arrayOp, element)) + { + continue; + } + + // a tuple literal built in place moves in whole: the retain the literal took of it goes + if (isInPlaceTupleLiteral(mth, arrayOp, element)) + { + for (auto *user : llvm::make_early_inc_range(element.getUsers())) + { + if (mlir::isa(user)) + { + user->erase(); + } + } + + continue; + } + + if (!isNestedLiteral(mth, arrayOp, element)) { continue; } diff --git a/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp b/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp index ebaa7215c..28e102c46 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp @@ -857,6 +857,18 @@ namespace own_inference }); } + // ...and so is a field of a tuple literal built in place (`g(["a" + i, 1])`: a local nothing + // releases, filled field by field) when the tuple is only read whole into what borrows it - + // a call that keeps none of it, an array a call borrows. Taken, the value went with the + // local, which has no release of its own: every such call leaked it. + if (auto storeOp = mlir::dyn_cast(user); storeOp && storeOp.getValue() == value) + { + if (isBorrowedTupleLiteralField(storeOp.getReference())) + { + return true; + } + } + // the array being pushed onto is written, not taken; what is inserted is taken if (auto pushOp = mlir::dyn_cast(user)) { @@ -896,6 +908,64 @@ namespace own_inference return false; } + bool OwnershipInferencePass::isBorrowedTupleLiteralField(mlir::Value fieldRef) + { + auto propertyRefOp = fieldRef.getDefiningOp(); + auto varOp = propertyRefOp ? propertyRefOp->getOperand(0).getDefiningOp() : mlir_ts::VariableOp(); + // (a tuple's fields have no names; an object literal's do, and is a record of its own: classifyRecords) + auto tupleType = varOp ? mlir::dyn_cast(mlir::cast(varOp.getType()).getElementType()) + : mlir_ts::TupleType(); + if (!tupleType || isOwningVariable(varOp) || varOp.getCaptured().value_or(false) || !varOp.getInitializer() || + !varOp.getInitializer().getDefiningOp() || + llvm::any_of(tupleType.getFields(), [](mlir_ts::FieldInfo field) { return !!field.id; })) + { + return false; + } + + // rc's retain of the tuple for an array it goes into is that array's count, which an array + // that borrows its elements drops (classifyArgumentArrays) + auto readsOnly = [](mlir::Value read) { + auto reads = 0; + auto borrowed = llvm::all_of(read.getUses(), [&](mlir::OpOperand &use) { + if (mlir::isa(use.getOwner())) + { + return true; + } + + reads++; + return isBorrow(use.getOwner(), use.get()); + }); + return borrowed && reads > 0; + }; + + auto wholeReads = 0; + auto onlyBorrowed = llvm::all_of(varOp->getUsers(), [&](mlir::Operation *varUser) { + if (auto fieldOp = mlir::dyn_cast(varUser)) + { + // the literal's fields, each filled once (and MLIRGen's unused read of the old value) + return llvm::all_of(fieldOp->getUses(), [&](mlir::OpOperand &use) { + if (auto fieldStore = mlir::dyn_cast(use.getOwner())) + { + return fieldStore.getReference() == fieldOp.getResult(); + } + + auto fieldLoad = mlir::dyn_cast(use.getOwner()); + return fieldLoad && fieldLoad->use_empty(); + }); + } + + if (auto loadOp = mlir::dyn_cast(varUser)) + { + wholeReads++; + return readsOnly(loadOp.getResult()); + } + + return false; + }); + + return onlyBorrowed && wholeReads > 0; + } + bool OwnershipInferencePass::isBoundForCall(mlir::Operation *thisOp) { if (thisOp->getNumResults() != 1 || !mlir::isa(thisOp->getResult(0).getType()) || diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.h b/tslang/lib/TypeScript/OwnershipInferencePass.h index bace45fc4..0a3044dd0 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.h +++ b/tslang/lib/TypeScript/OwnershipInferencePass.h @@ -1279,6 +1279,10 @@ class OwnershipInferencePass // is treated as taking the value, which can only turn a program into an error. static bool isBorrow(mlir::Operation *user, mlir::Value value); + // A field of a tuple literal built in place (a local with no owner of its own, filled field by + // field) whose tuple is only read whole into uses that borrow it. + static bool isBorrowedTupleLiteralField(mlir::Value fieldRef); + // `ts.CreateBoundFunction(ts.Cast(object), method)` split straight back into `ts.GetThis` and // `ts.GetMethod` for a call: a method of another module's class - its constructor, when it is // built with `new` - called on an object here. It reads the object as `ts.ThisSymbolRef` does diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 56f62d5f6..6ebbe7031 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -1472,6 +1472,16 @@ tslang_add_test(NAME test-jit-rc-00-own-rest-argument-field COMMAND test-runner tslang_add_test(NAME test-jit-own-00-own-rest-argument-field COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_rest_argument_field.ts") tslang_add_test(NAME test-compile-00-own-rest-argument-field COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_rest_argument_field.ts") tslang_add_test(NAME test-compile-own-00-own-rest-argument-field COMMAND test-runner -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_rest_argument_field.ts") +tslang_add_test(NAME test-jit-00-own-tuple-literal-arguments COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_tuple_literal_arguments.ts") +tslang_add_test(NAME test-jit-rc-00-own-tuple-literal-arguments COMMAND test-runner -jit -mm=rc "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_tuple_literal_arguments.ts") +tslang_add_test(NAME test-jit-own-00-own-tuple-literal-arguments COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_tuple_literal_arguments.ts") +tslang_add_test(NAME test-compile-00-own-tuple-literal-arguments COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_tuple_literal_arguments.ts") +tslang_add_test(NAME test-compile-own-00-own-tuple-literal-arguments COMMAND test-runner -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_tuple_literal_arguments.ts") +tslang_add_test(NAME test-jit-00-array-pattern-rest-of-iterator COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00array_pattern_rest_of_iterator.ts") +tslang_add_test(NAME test-jit-rc-00-array-pattern-rest-of-iterator COMMAND test-runner -jit -mm=rc "${PROJECT_SOURCE_DIR}/test/tester/tests/00array_pattern_rest_of_iterator.ts") +tslang_add_test(NAME test-jit-own-00-array-pattern-rest-of-iterator COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00array_pattern_rest_of_iterator.ts") +tslang_add_test(NAME test-compile-00-array-pattern-rest-of-iterator COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00array_pattern_rest_of_iterator.ts") +tslang_add_test(NAME test-compile-own-00-array-pattern-rest-of-iterator COMMAND test-runner -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00array_pattern_rest_of_iterator.ts") tslang_add_test(NAME test-jit-00-nested-iterable-array-pattern COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00nested_iterable_array_pattern.ts") tslang_add_test(NAME test-jit-rc-00-nested-iterable-array-pattern COMMAND test-runner -jit -mm=rc "${PROJECT_SOURCE_DIR}/test/tester/tests/00nested_iterable_array_pattern.ts") tslang_add_test(NAME test-jit-own-00-nested-iterable-array-pattern COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00nested_iterable_array_pattern.ts") diff --git a/tslang/test/tester/tests/00array_pattern_rest_of_iterator.ts b/tslang/test/tester/tests/00array_pattern_rest_of_iterator.ts new file mode 100644 index 000000000..eeecfdef5 --- /dev/null +++ b/tslang/test/tester/tests/00array_pattern_rest_of_iterator.ts @@ -0,0 +1,44 @@ +// A rest element in an array pattern of an iterable (`const [first, ...rest] = gen()`): the rest is an +// array of what the iterator gives after the elements before it. It was refused ("spread is not +// implemented"). Runtime strings, so -mm=own's counts are checked too. +function* strings(k: number) { + yield "g" + k; + yield "h" + k; + yield "i" + k; +} + +function* none() { + if (false) yield "never"; +} + +function restOf(k: number): number { + const [first, ...rest] = strings(k); + assert(first == "g" + k, "first"); + assert(rest.length == 2, "rest length"); + assert(rest[0] == "h" + k && rest[1] == "i" + k, "rest elements"); + return rest.length; +} + +function main() { + const [a, b, ...tail] = strings(1); + assert(a == "g1" && b == "h1", "a, b"); + assert(tail.length == 1 && tail[0] == "i1", "tail"); + + const [...all] = strings(2); + assert(all.length == 3 && all[2] == "i2", "all"); + + const [x, y, z, ...empty] = strings(3); + assert(empty.length == 0, "nothing left"); + + const [...nothing] = none(); + assert(nothing.length == 0, "an empty iterator"); + + let n: number = 0; + for (let i = 0; i < 20000; i++) { + n += restOf(i); + } + + assert(n == 40000, "many times"); + + print("done."); +} diff --git a/tslang/test/tester/tests/00own_tuple_literal_arguments.ts b/tslang/test/tester/tests/00own_tuple_literal_arguments.ts new file mode 100644 index 000000000..9bb27d7d0 --- /dev/null +++ b/tslang/test/tester/tests/00own_tuple_literal_arguments.ts @@ -0,0 +1,47 @@ +// A tuple literal given to a call (`h(["a" + i, 1])`), or in an array literal given to one (`g([["a" + i, 1]])`): +// under -mm=own the new string went into the tuple, which nothing gave back - each call leaked the string +// (and the array of tuples when it went to an optional parameter, as `new Map([["a" + i, 1]])` does). +// Runtime strings, not literals: a literal is immortal and hides a leak or a wrong count. +function g(a: [string, number][]): number { + let n: number = 0; + for (const t of a) { + n += t[0].length + t[1]; + } + + return n; +} + +function h(t: [string, number]): number { + return t[0].length + t[1]; +} + +function opt(a?: [string, number][]): number { + return a ? g(a) : -1; +} + +function fromParam(s: string): number { + // the tuple borrows a string its caller owns: nothing may be given back here + return g([[s, 1]]) + h([s, 2]); +} + +function main() { + assert(h(["ab", 1]) == 3, "constant tuple"); + assert(g([["ab", 1], ["c", 2]]) == 6, "constant tuples"); + assert(opt([["abc", 1]]) == 4, "constant tuples to an optional parameter"); + + let n: number = 0; + for (let i = 0; i < 20000; i++) { + const s = "k" + i; + n += h(["a" + i, 1]); + n += g([["a" + i, 1], ["b" + i, 2]]); + n += opt([["c" + i, 3]]); + n += opt([["d", 4]]); + n += fromParam(s); + n += s.length > 0 ? 1 : 0; + } + + assert(n > 0, "many times"); + print(h(["x" + n, 0])); + + print("done."); +}