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
62 changes: 59 additions & 3 deletions tslang/lib/TypeScript/MLIRGenImpl.h
Original file line number Diff line number Diff line change
Expand Up @@ -7849,6 +7849,7 @@ class MLIRGenImpl
llvm::SmallVector<std::pair<std::string, Expression>> assignedOnceInBranch(Statement branch);
void mergedAfterIf(mlir::Location location, StringRef name, mlir::Type thenType, const ElseSafeCases &elseSafeCases,
const GenContext &genContext);
void unnarrowWrittenInLoop(mlir::Location location, std::initializer_list<Node> loopParts, const GenContext &genContext);
mlir::LogicalResult mlirGenBranchStatement(Statement statement, const GenContext &genContext);

mlir::LogicalResult mlirGen(DoStatement doStatementAST, const GenContext &genContext);
Expand Down Expand Up @@ -10515,6 +10516,18 @@ class MLIRGenImpl
leftExpressionValueBeforeCast = loaded;
}

// a name narrowed by a test inside another's (`x !== null`, then `typeof x === "number"`), or an optional's value
// narrowed (`x?: number | string`): the variable is read under the narrowings (narrowedVariableLoad)
if (auto safeCastOp = leftExpressionValueBeforeCast.getDefiningOp<mlir_ts::SafeCastOp>();
safeCastOp && !safeCastOp->hasAttr(DECLARED_FIELD_VIEW_ATTR_NAME) &&
!safeCastOp.getValue().getDefiningOp<mlir_ts::LoadOp>())
{
if (auto loadOp = narrowedVariableLoad(leftExpressionValueBeforeCast))
{
leftExpressionValueBeforeCast = loadOp;
}
}

// TODO: logic to support safe cast
if (auto safeCastOp = leftExpressionValueBeforeCast.getDefiningOp<mlir_ts::SafeCastOp>())
{
Expand Down Expand Up @@ -10967,7 +10980,8 @@ class MLIRGenImpl
safeCastOp && !safeCastOp->hasAttr(DECLARED_FIELD_VIEW_ATTR_NAME) &&
!safeCastOp->hasAttr(WEAK_FIELD_VIEW_ATTR_NAME))
{
receiverType = safeCastOp.getValue().getType();
auto loadOp = narrowedVariableLoad(leftExpressionValue);
receiverType = loadOp ? loadOp.getType() : safeCastOp.getValue().getType();
}

rightExprGenContext.receiverType = receiverType;
Expand All @@ -10992,16 +11006,51 @@ class MLIRGenImpl
// (typeof x === "number") { x = "s" + x; print(x); }` printed the number). It is narrowed again, to the type of
// what it was given when that is one of its declared union's members, else to its declared type - read again
// from its place. In the scope of the assignment.
// The read of the variable a narrowed name is (addSafeCastStatement): under each narrowing - one inside another's
// (`x !== null`, then `typeof x === "number"`) - and under the value taken out of an optional (`x?: number |
// string`). None for a field's view, or a value that is not a variable's.
mlir_ts::LoadOp narrowedVariableLoad(mlir::Value value)
{
while (value)
{
if (auto loadOp = value.getDefiningOp<mlir_ts::LoadOp>())
{
return loadOp;
}

if (auto safeCastOp = value.getDefiningOp<mlir_ts::SafeCastOp>())
{
if (safeCastOp->hasAttr(DECLARED_FIELD_VIEW_ATTR_NAME) || safeCastOp->hasAttr(WEAK_FIELD_VIEW_ATTR_NAME))
{
return mlir_ts::LoadOp();
}

value = safeCastOp.getValue();
continue;
}

if (auto valueOp = value.getDefiningOp<mlir_ts::ValueOp>())
{
value = valueOp.getIn();
continue;
}

break;
}

return mlir_ts::LoadOp();
}

void renarrowAfterAssignment(mlir::Location location, StringRef name, mlir::Value narrowedValue, mlir::Type assignedType,
const GenContext &genContext)
{
auto safeCastOp = narrowedValue.getDefiningOp<mlir_ts::SafeCastOp>();
if (!safeCastOp || safeCastOp->hasAttr(DECLARED_FIELD_VIEW_ATTR_NAME) || safeCastOp->hasAttr(WEAK_FIELD_VIEW_ATTR_NAME))
if (!safeCastOp)
{
return;
}

auto loadOp = safeCastOp.getValue().getDefiningOp<mlir_ts::LoadOp>();
auto loadOp = narrowedVariableLoad(narrowedValue);
if (!loadOp)
{
return;
Expand All @@ -11020,6 +11069,13 @@ class MLIRGenImpl
{
narrowedType = givenType;
}
// `x?: number | string` given a string: a string (addSafeCastStatement takes the union out of the optional)
else if (auto optType = dyn_cast<mlir_ts::OptionalType>(declaredType);
optType && isa<mlir_ts::UnionType>(optType.getElementType()) &&
llvm::is_contained(mlir::cast<mlir_ts::UnionType>(optType.getElementType()).getTypes(), givenType))
{
narrowedType = givenType;
}

if (narrowedType != declaredType)
{
Expand Down
212 changes: 212 additions & 0 deletions tslang/lib/TypeScript/MLIRGenStatements.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2042,6 +2042,202 @@ namespace mlirgen
return mlir::success();
}

// A write of a name in a loop (unnarrowWrittenInLoop): the expression whose type is what the name holds after it -
// the value of `x = e`, the whole of `x += e` - or none: `x++` keeps a number's type, a destructuring gives one not
// looked for.
struct LoopWrite
{
Expression value;
bool keepsType = false;
};

// The names `node` writes: `x = e`, `x += e`, `x++`, `[x, y] = ...`, `({ x } = ...)` - in a nested loop or function
// too. A name in a destructuring target is taken whatever it is there (`{ k: x }` gives `k` as well): taking one too
// many only reads that variable again.
static void collectLoopWrites(Node node, llvm::StringMap<llvm::SmallVector<LoopWrite>> &writes)
{
if (!node)
{
return;
}

auto stripped = [](Node target) {
while (target == SyntaxKind::ParenthesizedExpression)
{
target = target.as<ParenthesizedExpression>()->expression;
}

return target;
};

auto addTarget = [&](Node target, LoopWrite write) {
target = stripped(target);
if (target == SyntaxKind::Identifier)
{
writes[MLIRHelper::getName(target.as<Identifier>())].push_back(write);
}
else if (target == SyntaxKind::ArrayLiteralExpression || target == SyntaxKind::ObjectLiteralExpression)
{
FilterVisitorAST<Node> identifiers(SyntaxKind::Identifier, [&](auto identifier) {
writes[MLIRHelper::getName(identifier.template as<Identifier>())].push_back(LoopWrite());
});
identifiers.visit(target);
}
};

FilterVisitorAST<Node> binaryVisitor(SyntaxKind::BinaryExpression, [&](auto binary) {
auto binExpr = binary.template as<BinaryExpression>();
auto op = (SyntaxKind)binExpr->operatorToken;
if (isAssignmentOperator(op))
{
auto value = op == SyntaxKind::EqualsToken ? binExpr->right : Expression(binExpr);
addTarget(binExpr->left, stripped(binExpr->left) == SyntaxKind::Identifier ? LoopWrite{value} : LoopWrite());
}
});
binaryVisitor.visit(node);

FilterVisitorAST<Node> prefixVisitor(SyntaxKind::PrefixUnaryExpression, [&](auto unary) {
auto unaryExpr = unary.template as<PrefixUnaryExpression>();
if (unaryExpr->_operator == SyntaxKind::PlusPlusToken || unaryExpr->_operator == SyntaxKind::MinusMinusToken)
{
addTarget(unaryExpr->operand, LoopWrite{Expression(), true});
}
});
prefixVisitor.visit(node);

FilterVisitorAST<Node> postfixVisitor(SyntaxKind::PostfixUnaryExpression, [&](auto unary) {
auto unaryExpr = unary.template as<PostfixUnaryExpression>();
if (unaryExpr->_operator == SyntaxKind::PlusPlusToken || unaryExpr->_operator == SyntaxKind::MinusMinusToken)
{
addTarget(unaryExpr->operand, LoopWrite{Expression(), true});
}
});
postfixVisitor.visit(node);
}

// A loop that writes a variable a test before it narrowed (addSafeCastStatement: `if (p !== null)`, the body of a
// `while (p !== null)` around it, ...): the narrowed name was the value the test read, once, before the loop, and
// the loop's next turns - its condition too - read that value again, not what the turn before left in the variable
// (`p = p.next` never moved on, TSLANG 235). In the loop and after it the name is the variable, read at each use.
// Its type is what it is narrowed to here and what the loop writes, as tsc takes it at the loop's head: `x = x + 1`
// keeps a `number` one, `p = p.next` makes `L` an `L | null`. A write whose type can't be told (a value made of
// the loop's own locals, a destructuring) leaves it the type it is declared with. Not in a generator, whose
// narrowed local is a view read at each use already.
void MLIRGenImpl::unnarrowWrittenInLoop(mlir::Location location, std::initializer_list<Node> loopParts,
const GenContext &genContext)
{
if (genContext.allocateVarsInContextThis)
{
return;
}

llvm::StringMap<llvm::SmallVector<LoopWrite>> writes;
for (auto part : loopParts)
{
collectLoopWrites(part, writes);
}

for (auto &entry : writes)
{
auto name = entry.getKey();
if (!symbolTable.count(name))
{
continue;
}

auto current = symbolTable.lookup(name).first;
auto safeCastOp = current ? current.getDefiningOp<mlir_ts::SafeCastOp>() : mlir_ts::SafeCastOp();
if (!safeCastOp)
{
continue;
}

// (under each narrowing: one inside another's, an optional's value)
auto loadOp = narrowedVariableLoad(current);
if (!loadOp)
{
continue;
}

auto declaredType = loadOp.getType();
auto narrowedType = safeCastOp.getType();

// the members it may have at the loop's head: those it is narrowed to and those the loop writes, each a
// member of the union it is declared with
auto declaredUnion = dyn_cast<mlir_ts::UnionType>(declaredType);
llvm::SmallVector<mlir::Type> members;
auto known = !!declaredUnion;
auto add = [&](mlir::Type type) {
auto typeUnion = dyn_cast<mlir_ts::UnionType>(type);
auto typeMembers = typeUnion ? typeUnion.getTypes() : llvm::ArrayRef<mlir::Type>(type);
for (auto member : typeMembers)
{
if (!llvm::is_contained(declaredUnion.getTypes(), member))
{
known = false;
return;
}

if (!llvm::is_contained(members, member))
{
members.push_back(member);
}
}
};

if (known)
{
add(narrowedType);
}

for (auto &write : entry.getValue())
{
if (!known)
{
break;
}

if (write.keepsType)
{
continue;
}

mlir::Type writtenType;
if (write.value)
{
// (a value the loop's own locals make is not resolved here: no error of it)
mlir::ScopedDiagnosticHandler diagHandler(builder.getContext(), [&](mlir::Diagnostic &) {});
writtenType = evaluate(write.value, genContext);
}

if (!writtenType)
{
known = false;
break;
}

add(mth.wideStorageType(writtenType));
}

mlir::Type loopType = declaredType;
if (known && members.size() < declaredUnion.getTypes().size())
{
loopType = members.size() == 1 ? members.front() : getUnionType(members);
}

// (declared into the symbol table as it is: declare() would give the variable's op the loop's debug scope)
auto ownName = StringRef(name).copy(stringAllocator);
auto view = std::make_shared<VariableDeclarationDOM>(ownName, loopType, location);
view->setReadWriteAccess();
if (loopType != declaredType)
{
view->setNarrowedType(loopType);
}

symbolTable.insert(ownName, {loadOp.getReference(), view});
}
}

// A branch written without braces (`else for (const c of gen()) ...`) is a scope all the same:
// what it registers to give back at the end of its block - an owned local such as a
// generator's iterator, a `using` - belongs to the branch, whose region it is defined in, not
Expand Down Expand Up @@ -2084,6 +2280,9 @@ namespace mlirgen

mlir::LogicalResult MLIRGenImpl::mlirGen(DoStatement doStatementAST, const GenContext &genContext)
{
// (before the loop's scope: the name is the variable after the loop too)
unnarrowWrittenInLoop(loc(doStatementAST), {doStatementAST->statement, doStatementAST->expression}, genContext);

SymbolTableScopeT varScope(symbolTable);

auto location = loc(doStatementAST);
Expand Down Expand Up @@ -2133,6 +2332,9 @@ namespace mlirgen

mlir::LogicalResult MLIRGenImpl::mlirGen(WhileStatement whileStatementAST, const GenContext &genContext)
{
// (before the loop's scope: the name is the variable after the loop too)
unnarrowWrittenInLoop(loc(whileStatementAST), {whileStatementAST->expression, whileStatementAST->statement}, genContext);

SymbolTableScopeT varScope(symbolTable);

auto location = loc(whileStatementAST);
Expand Down Expand Up @@ -2319,6 +2521,13 @@ namespace mlirgen

mlir::LogicalResult MLIRGenImpl::mlirGen(ForStatement forStatementAST, const GenContext &genContext)
{
// (before the loop's scope: the name is the variable after the loop too; again after the initializer below,
// which may narrow it again - `for (p = head; ...)`)
unnarrowWrittenInLoop(loc(forStatementAST),
{forStatementAST->initializer, forStatementAST->condition, forStatementAST->incrementor,
forStatementAST->statement},
genContext);

SymbolTableScopeT varScope(symbolTable);

auto location = loc(forStatementAST);
Expand Down Expand Up @@ -2349,6 +2558,9 @@ namespace mlirgen
}
}

unnarrowWrittenInLoop(location, {forStatementAST->condition, forStatementAST->incrementor, forStatementAST->statement},
genContext);

SmallVector<mlir::Type, 0> types;
SmallVector<mlir::Value, 0> operands;

Expand Down
11 changes: 11 additions & 0 deletions tslang/test/tester/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2784,6 +2784,17 @@ set_tests_properties(test-compile-own-rest-kept-through-class-value-error PROPER
foreach(issue233_mm gc rc none own)
tslang_add_test(NAME test-compile-import-declared-method-overloads-${issue233_mm} COMMAND test-runner -mm=${issue233_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/import_declared_method_overloads.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_declared_method_overloads.ts")
endforeach()
# TSLANG 235: a variable narrowed before a loop and written in it is read again on each turn and after the loop
# (not -mm=own: walking a linked list by the references its links hold is a borrow own refuses to store)
foreach(issue235_mm gc rc none)
tslang_add_test(NAME test-jit-00tslang_issue_235-${issue235_mm} COMMAND test-runner -jit -mm=${issue235_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_235.ts")
tslang_add_test(NAME test-compile-00tslang_issue_235-${issue235_mm} COMMAND test-runner -mm=${issue235_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_235.ts")
endforeach()
# ...and its type in the loop: what it is narrowed to and what the loop writes
foreach(issue235_mm gc rc none own)
tslang_add_test(NAME test-jit-00tslang_issue_235_types-${issue235_mm} COMMAND test-runner -jit -mm=${issue235_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_235_types.ts")
tslang_add_test(NAME test-compile-00tslang_issue_235_types-${issue235_mm} COMMAND test-runner -mm=${issue235_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_235_types.ts")
endforeach()
add_test(NAME test-compile-declared-method-overloads-warning
COMMAND $<TARGET_FILE:tslang> --emit=obj --no-default-lib -mm=none
"${PROJECT_SOURCE_DIR}/test/tester/tests/declared_method_overloads_warning.ts"
Expand Down
Loading
Loading