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
6 changes: 3 additions & 3 deletions tslang/lib/TypeScript/MLIRGenImpl.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
28 changes: 24 additions & 4 deletions tslang/lib/TypeScript/MLIRGenVariables.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<ArrayElement> 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)
Expand Down Expand Up @@ -884,6 +901,7 @@ namespace mlirgen
mlir::Value arrayLikeLengthValue;
mlir::Type arrayLikeElementType;
auto isIterator = false;
mlir::Value iteratorSource;
auto isSourceArrayLike = false;
auto isArrayOrTuple = isa<mlir_ts::ArrayType>(typeRef)
|| isa<mlir_ts::TupleType>(typeRef)
Expand All @@ -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))
Expand All @@ -914,6 +933,7 @@ namespace mlirgen
location, init, ITERATOR_NEXT, false, genContext);
if (nextProperty)
{
iteratorSource = init;
init = V(nextProperty);
isIterator = true;
}
Expand Down Expand Up @@ -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);
Expand Down
107 changes: 104 additions & 3 deletions tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<mlir_ts::TupleType>(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<mlir_ts::RetainOp>(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<mlir_ts::CastOp>(storedOp); castOp && castOp.getIn().getDefiningOp<mlir_ts::ConstantOp>())
{
return true;
}

return storedOp->hasAttr(OWNED_RESULT_ATTR_NAME) && llvm::all_of(stored.getUsers(), [&](mlir::Operation *user) {
return mlir::isa<mlir_ts::StoreOp, mlir_ts::RetainOp, mlir_ts::ReleaseOp>(user) &&
(!mlir::isa<mlir_ts::StoreOp>(user) || user->getOperand(0) == stored);
});
};

// `["a", 1]` of values only: one `ts.CreateTuple`
if (auto createTupleOp = element.getDefiningOp<mlir_ts::CreateTupleOp>())
{
return createTupleOp->getBlock() == arrayOp->getBlock() && llvm::all_of(createTupleOp->getOperands(), isNewField);
}

auto loadOp = element.getDefiningOp<mlir_ts::LoadOp>();
auto varOp = loadOp ? loadOp.getReference().getDefiningOp<mlir_ts::VariableOp>() : mlir_ts::VariableOp();
if (!varOp || varOp->hasAttr(OWNED_LOCAL_ATTR_NAME) || varOp.getCaptured().value_or(false) || !varOp.getInitializer() ||
!varOp.getInitializer().getDefiningOp<mlir_ts::ConstantOp>())
{
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<mlir_ts::PropertyRefOp>(varUser);
return fieldOp && fieldOp->getBlock() == arrayOp->getBlock() && fieldOp->isBeforeInBlock(loadOp) &&
llvm::all_of(fieldOp->getUsers(), [&](mlir::Operation *fieldUser) {
if (auto storeOp = mlir::dyn_cast<mlir_ts::StoreOp>(fieldUser))
{
return storeOp.getReference() == fieldOp.getResult() && isNewField(storeOp.getValue());
}

return mlir::isa<mlir_ts::LoadOp>(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,
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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<mlir_ts::RetainOp>(user))
{
user->erase();
}
}

continue;
}

if (!isNestedLiteral(mth, arrayOp, element))
{
continue;
}
Expand Down
70 changes: 70 additions & 0 deletions tslang/lib/TypeScript/OwnershipInferenceMoves.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<mlir_ts::StoreOp>(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<mlir_ts::ArrayPushOp>(user))
{
Expand Down Expand Up @@ -896,6 +908,64 @@ namespace own_inference
return false;
}

bool OwnershipInferencePass::isBorrowedTupleLiteralField(mlir::Value fieldRef)
{
auto propertyRefOp = fieldRef.getDefiningOp<mlir_ts::PropertyRefOp>();
auto varOp = propertyRefOp ? propertyRefOp->getOperand(0).getDefiningOp<mlir_ts::VariableOp>() : 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_ts::TupleType>(mlir::cast<mlir_ts::RefType>(varOp.getType()).getElementType())
: mlir_ts::TupleType();
if (!tupleType || isOwningVariable(varOp) || varOp.getCaptured().value_or(false) || !varOp.getInitializer() ||
!varOp.getInitializer().getDefiningOp<mlir_ts::ConstantOp>() ||
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<mlir_ts::RetainOp>(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<mlir_ts::PropertyRefOp>(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<mlir_ts::StoreOp>(use.getOwner()))
{
return fieldStore.getReference() == fieldOp.getResult();
}

auto fieldLoad = mlir::dyn_cast<mlir_ts::LoadOp>(use.getOwner());
return fieldLoad && fieldLoad->use_empty();
});
}

if (auto loadOp = mlir::dyn_cast<mlir_ts::LoadOp>(varUser))
{
wholeReads++;
return readsOnly(loadOp.getResult());
}

return false;
});

return onlyBorrowed && wholeReads > 0;
}

bool OwnershipInferencePass::isBoundForCall(mlir::Operation *thisOp)
{
if (thisOp->getNumResults() != 1 || !mlir::isa<mlir_ts::OpaqueType>(thisOp->getResult(0).getType()) ||
Expand Down
4 changes: 4 additions & 0 deletions tslang/lib/TypeScript/OwnershipInferencePass.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
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 @@ -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")
Expand Down
44 changes: 44 additions & 0 deletions tslang/test/tester/tests/00array_pattern_rest_of_iterator.ts
Original file line number Diff line number Diff line change
@@ -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.");
}
Loading
Loading