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
50 changes: 50 additions & 0 deletions tslang/lib/TypeScript/LowerToLLVM.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4741,6 +4741,49 @@ struct ArithmeticBinaryOpLowering : public TsLlvmPattern<mlir_ts::ArithmeticBina
return rewriter.create<arith::AndIOp>(loc, shiftAmount, mask);
}

// `base ** exponent` of two integers (a bigint's), by squaring: math.powf is for floats only, and
// through one `2n ** 62n` was rounded. A negative exponent is checked where the op is made; here
// it gives 1.
static mlir::Value integerPower(mlir::Location loc, mlir::Value base, mlir::Value exponent,
ConversionPatternRewriter &rewriter)
{
auto intType = base.getType();

auto *currentBlock = rewriter.getInsertionBlock();
auto *continuationBlock = rewriter.splitBlock(currentBlock, rewriter.getInsertionPoint());
auto result = continuationBlock->addArgument(intType, loc);
auto *bodyBlock = rewriter.createBlock(continuationBlock, {intType, intType, intType}, {loc, loc, loc});
auto *headerBlock = rewriter.createBlock(bodyBlock, {intType, intType, intType}, {loc, loc, loc});

auto zero = [&]() { return rewriter.create<arith::ConstantOp>(loc, intType, rewriter.getIntegerAttr(intType, 0)); };
auto one = [&]() { return rewriter.create<arith::ConstantOp>(loc, intType, rewriter.getIntegerAttr(intType, 1)); };

// header(result, base, exponent): done once the exponent is 0
rewriter.setInsertionPointToEnd(headerBlock);
auto more = rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::sgt, headerBlock->getArgument(2), zero());
rewriter.create<cf::CondBranchOp>(loc, more, bodyBlock, headerBlock->getArguments(), continuationBlock,
ValueRange{headerBlock->getArgument(0)});

// body: multiply the result by the base for a set low bit, square the base, halve the exponent
rewriter.setInsertionPointToEnd(bodyBlock);
auto accumulated = bodyBlock->getArgument(0);
auto factor = bodyBlock->getArgument(1);
auto remaining = bodyBlock->getArgument(2);
auto lowBit = rewriter.create<arith::AndIOp>(loc, remaining, one());
auto isOdd = rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ne, lowBit, zero());
auto multiplied = rewriter.create<arith::MulIOp>(loc, accumulated, factor);
auto nextResult = rewriter.create<arith::SelectOp>(loc, isOdd, multiplied, accumulated);
auto squared = rewriter.create<arith::MulIOp>(loc, factor, factor);
auto halved = rewriter.create<arith::ShRUIOp>(loc, remaining, one());
rewriter.create<cf::BranchOp>(loc, headerBlock, ValueRange{nextResult, squared, halved});

rewriter.setInsertionPointToEnd(currentBlock);
rewriter.create<cf::BranchOp>(loc, headerBlock, ValueRange{one(), base, exponent});

rewriter.setInsertionPointToStart(continuationBlock);
return result;
}

LogicalResult matchAndRewrite(mlir_ts::ArithmeticBinaryOp arithmeticBinaryOp, Adaptor transformed,
ConversionPatternRewriter &rewriter) const final
{
Expand Down Expand Up @@ -4816,6 +4859,13 @@ struct ArithmeticBinaryOpLowering : public TsLlvmPattern<mlir_ts::ArithmeticBina
transformed.getOperand2(), rewriter);

case SyntaxKind::AsteriskAsteriskToken:
if (isa<mlir::IntegerType>(transformed.getOperand1().getType()))
{
rewriter.replaceOp(arithmeticBinaryOp,
integerPower(arithmeticBinaryOp->getLoc(), transformed.getOperand1(), transformed.getOperand2(), rewriter));
return success();
}

return BinOp<mlir_ts::ArithmeticBinaryOp, math::PowFOp, math::PowFOp>(arithmeticBinaryOp, transformed.getOperand1(),
transformed.getOperand2(), rewriter);

Expand Down
22 changes: 21 additions & 1 deletion tslang/lib/TypeScript/MLIRGenImpl.h
Original file line number Diff line number Diff line change
Expand Up @@ -7856,13 +7856,14 @@ class MLIRGenImpl

// A bigint is a 64-bit integer, and so is what `/`, `%`, a shift or a bitwise operator makes of
// two of them: `10n / 3n` is 3n, not 3.33333 through a number, and `1n << 40n` is not shifted by
// 40 mod 32 through an i32.
// 40 mod 32 through an i32. `2n ** 62n` is exact, not rounded through a number.
auto isBigInt = [&](mlir::Value value) { return isa<mlir_ts::BigIntType>(mth.stripLiteralType(value.getType())); };
auto bigIntOperation = false;
switch (opCode)
{
case SyntaxKind::SlashToken:
case SyntaxKind::PercentToken:
case SyntaxKind::AsteriskAsteriskToken:
case SyntaxKind::LessThanLessThanToken:
case SyntaxKind::GreaterThanGreaterThanToken:
case SyntaxKind::AmpersandToken:
Expand All @@ -7885,6 +7886,25 @@ class MLIRGenImpl
{
CAST(rightExpressionValue, location, getBigIntType(), rightExpressionValue, genContext);
}

// TypeScript throws a RangeError for a bigint divided by 0n or raised to a negative power;
// a failed check stops the program as a failing assert does (#483), where the division
// was a hardware fault and a negative power was 1n.
auto checkRight = [&](SyntaxKind checkCode, StringRef message) {
auto zero = builder.create<mlir_ts::ConstantOp>(location, getBigIntType(), builder.getI64IntegerAttr(0));
auto holds = builder.create<mlir_ts::LogicalBinaryOp>(
location, getBooleanType(), builder.getI32IntegerAttr((int)checkCode), rightExpressionValue, zero);
builder.create<mlir_ts::AssertOp>(location, holds, mlir::Value(), builder.getStringAttr(message));
};

if (opCode == SyntaxKind::SlashToken || opCode == SyntaxKind::PercentToken)
{
checkRight(SyntaxKind::ExclamationEqualsToken, "Division by zero");
}
else if (opCode == SyntaxKind::AsteriskAsteriskToken)
{
checkRight(SyntaxKind::GreaterThanEqualsToken, "Exponent must be non-negative");
}
}

// cast step
Expand Down
12 changes: 11 additions & 1 deletion tslang/lib/TypeScript/MLIRGenStatements.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,17 @@ namespace mlirgen
{
SymbolTableScopeT varScope(symbolTable);

clearState(statements);
// What a run before this one did is cleared when it ends, but for the statements a failed run
// of the real pass generated: the run is tried again (a namespace whose function names a class
// declared after it), and what it generated is still in the module, so those are not generated
// twice ("redefinition of symbol"). A dummy run's ops are thrown away; it clears them all.
auto keepGenerated = !genContext.dummyRun && !genContext.allowPartialResolve;
auto clearOnFailure = llvm::make_scope_exit([&]() {
if (!keepGenerated)
{
clearState(statements);
}
});

auto notResolved = 0;
do
Expand Down
22 changes: 22 additions & 0 deletions tslang/test/tester/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -754,6 +754,7 @@ tslang_add_test(NAME test-compile-01-spread COMMAND test-runner "${PROJECT_SOURC
tslang_add_test(NAME test-compile-00-types-unknown1 COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00types_unknown1.ts")
tslang_add_test(NAME test-compile-00-any-to-tuple COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00any_to_tuple.ts")
tslang_add_test(NAME test-compile-00-bigint-ops COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00bigint_ops.ts")
tslang_add_test(NAME test-compile-00-namespace-forward-class COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00namespace_forward_class.ts")
tslang_add_test(NAME test-compile-00-any-literal-to-interface COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00any_literal_to_interface.ts")
tslang_add_test(NAME test-compile-00-interface-method-object-field-type COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00interface_method_object_field_type.ts")
tslang_add_test(NAME test-compile-00-unknown-round-trip COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00unknown_round_trip.ts")
Expand Down Expand Up @@ -1380,6 +1381,7 @@ tslang_add_test(NAME test-jit-01-spread COMMAND test-runner -jit "${PROJECT_SOUR
tslang_add_test(NAME test-jit-00-types-unknown1 COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00types_unknown1.ts")
tslang_add_test(NAME test-jit-00-any-to-tuple COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00any_to_tuple.ts")
tslang_add_test(NAME test-jit-00-bigint-ops COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00bigint_ops.ts")
tslang_add_test(NAME test-jit-00-namespace-forward-class COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00namespace_forward_class.ts")
tslang_add_test(NAME test-jit-00-any-literal-to-interface COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00any_literal_to_interface.ts")
tslang_add_test(NAME test-jit-00-interface-method-object-field-type COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00interface_method_object_field_type.ts")
tslang_add_test(NAME test-jit-00-unknown-round-trip COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00unknown_round_trip.ts")
Expand Down Expand Up @@ -2484,6 +2486,7 @@ set(TSLANG_CORPUS
00types_unknown1.ts
00any_to_tuple.ts
00bigint_ops.ts
00namespace_forward_class.ts
00any_literal_to_interface.ts
00interface_method_object_field_type.ts
00unknown_round_trip.ts
Expand Down Expand Up @@ -5079,6 +5082,25 @@ foreach(array_length_name negative huge fraction negative_integer new_negative)
endforeach()
endforeach()

# A bigint divided by 0n or raised to a negative power stops the program with a message, after the
# output printed before it, under every model: TypeScript throws a RangeError.
foreach(bigint_range_name division remainder power)
if(bigint_range_name STREQUAL "power")
set(bigint_range_message "Exponent must be non-negative")
else()
set(bigint_range_message "Division by zero")
endif()
foreach(bigint_range_model gc rc none own)
add_test(NAME test-jit-${bigint_range_model}-bigint-range-${bigint_range_name}
COMMAND $<TARGET_FILE:tslang> --emit=jit --no-default-lib -mm=${bigint_range_model}
--shared-libs=$<TARGET_FILE:TypeScriptRuntime>
"${PROJECT_SOURCE_DIR}/test/tester/bigint-range/${bigint_range_name}.ts")
set_tests_properties(test-jit-${bigint_range_model}-bigint-range-${bigint_range_name}
PROPERTIES PASS_REGULAR_EXPRESSION "printed before.*assertion failed: ${bigint_range_message}"
FAIL_REGULAR_EXPRESSION "Stack dump|PLEASE submit|result: ")
endforeach()
endforeach()

# A write through an interface to its function-typed field stops the program with a message when
# the object behind it fills the field with a method or is an object literal: only a class field
# holding the function has storage to write. Which object it is is known only at run time.
Expand Down
9 changes: 9 additions & 0 deletions tslang/test/tester/bigint-range/division.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// a bigint divided by 0n stops the program, where TypeScript throws a RangeError
function apply(n: bigint, d: bigint) {
return n / d;
}

function main() {
print("printed before");
print("result: ", apply(10n, 0n));
}
9 changes: 9 additions & 0 deletions tslang/test/tester/bigint-range/power.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// a bigint raised to a negative power stops the program, where TypeScript throws a RangeError
function apply(n: bigint, d: bigint) {
return n ** d;
}

function main() {
print("printed before");
print("result: ", apply(2n, -1n));
}
9 changes: 9 additions & 0 deletions tslang/test/tester/bigint-range/remainder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// the remainder of a bigint by 0n stops the program, where TypeScript throws a RangeError
function apply(n: bigint, d: bigint) {
return n % d;
}

function main() {
print("printed before");
print("result: ", apply(10n, 0n));
}
10 changes: 9 additions & 1 deletion tslang/test/tester/tests/00bigint_ops.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// so `x ?? 7n` of an optional bigint is a bigint (it was `bigint | i64`, and the null test an i64 against a
// pointer), and `5n` given for `bigint | string` is its bigint member (an invalid cast). `/`, `%`, shifts
// and bitwise operators stay 64-bit integers: `10n / 3n` was 3.33333 through a number, and `1n << 40n`
// shifted by 40 mod 32 through an i32.
// shifted by 40 mod 32 through an i32. A division by 0n or a negative power stops the program (RangeError).
function orSeven(x?: bigint) {
return x ?? 7n;
}
Expand Down Expand Up @@ -39,5 +39,13 @@ function main() {
c <<= 33n;
assert(c == 120259084288n, "compound assignments");

// `**` is exact: through a number `2n ** 62n` was rounded
const two = 2n;
assert(two ** 62n == 4611686018427387904n, "a power past 2^53");
assert(3n ** 0n == 1n && (-3n) ** 3n == -27n && 10n ** 18n == 1000000000000000000n, "powers");
let p = 2n;
p **= 5n;
assert(p == 32n, "**=");

print("done.");
}
22 changes: 22 additions & 0 deletions tslang/test/tester/tests/00namespace_forward_class.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// A namespace whose function names a class declared after it is generated again once the class is
// there; the functions the first try had generated were generated twice ("redefinition of symbol").
namespace Forward {
export function first(x: number) {
return x + 1;
}

export function second(x: number) {
return x == Limits.BIG ? 0 : 1;
}
}

class Limits {
public static BIG: number = 5;
}

function main() {
assert(Forward.first(1) == 2, "the function generated on the first try");
assert(Forward.second(5) == 0 && Forward.second(2) == 1, "the function naming the later class");

print("done.");
}
Loading