diff --git a/tslang/lib/TypeScript/LowerToLLVM.cpp b/tslang/lib/TypeScript/LowerToLLVM.cpp index 310c49ff1..3cec91240 100644 --- a/tslang/lib/TypeScript/LowerToLLVM.cpp +++ b/tslang/lib/TypeScript/LowerToLLVM.cpp @@ -4741,6 +4741,49 @@ struct ArithmeticBinaryOpLowering : public TsLlvmPattern(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(loc, intType, rewriter.getIntegerAttr(intType, 0)); }; + auto one = [&]() { return rewriter.create(loc, intType, rewriter.getIntegerAttr(intType, 1)); }; + + // header(result, base, exponent): done once the exponent is 0 + rewriter.setInsertionPointToEnd(headerBlock); + auto more = rewriter.create(loc, arith::CmpIPredicate::sgt, headerBlock->getArgument(2), zero()); + rewriter.create(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(loc, remaining, one()); + auto isOdd = rewriter.create(loc, arith::CmpIPredicate::ne, lowBit, zero()); + auto multiplied = rewriter.create(loc, accumulated, factor); + auto nextResult = rewriter.create(loc, isOdd, multiplied, accumulated); + auto squared = rewriter.create(loc, factor, factor); + auto halved = rewriter.create(loc, remaining, one()); + rewriter.create(loc, headerBlock, ValueRange{nextResult, squared, halved}); + + rewriter.setInsertionPointToEnd(currentBlock); + rewriter.create(loc, headerBlock, ValueRange{one(), base, exponent}); + + rewriter.setInsertionPointToStart(continuationBlock); + return result; + } + LogicalResult matchAndRewrite(mlir_ts::ArithmeticBinaryOp arithmeticBinaryOp, Adaptor transformed, ConversionPatternRewriter &rewriter) const final { @@ -4816,6 +4859,13 @@ struct ArithmeticBinaryOpLowering : public TsLlvmPattern(transformed.getOperand1().getType())) + { + rewriter.replaceOp(arithmeticBinaryOp, + integerPower(arithmeticBinaryOp->getLoc(), transformed.getOperand1(), transformed.getOperand2(), rewriter)); + return success(); + } + return BinOp(arithmeticBinaryOp, transformed.getOperand1(), transformed.getOperand2(), rewriter); diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 82c57ba40..041b90bb0 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -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(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: @@ -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(location, getBigIntType(), builder.getI64IntegerAttr(0)); + auto holds = builder.create( + location, getBooleanType(), builder.getI32IntegerAttr((int)checkCode), rightExpressionValue, zero); + builder.create(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 diff --git a/tslang/lib/TypeScript/MLIRGenStatements.cpp b/tslang/lib/TypeScript/MLIRGenStatements.cpp index ab5150efa..3d1118727 100644 --- a/tslang/lib/TypeScript/MLIRGenStatements.cpp +++ b/tslang/lib/TypeScript/MLIRGenStatements.cpp @@ -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 diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 201e5c363..88a6d6baa 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -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") @@ -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") @@ -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 @@ -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 $ --emit=jit --no-default-lib -mm=${bigint_range_model} + --shared-libs=$ + "${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. diff --git a/tslang/test/tester/bigint-range/division.ts b/tslang/test/tester/bigint-range/division.ts new file mode 100644 index 000000000..8a8f6fab0 --- /dev/null +++ b/tslang/test/tester/bigint-range/division.ts @@ -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)); +} diff --git a/tslang/test/tester/bigint-range/power.ts b/tslang/test/tester/bigint-range/power.ts new file mode 100644 index 000000000..5a1725274 --- /dev/null +++ b/tslang/test/tester/bigint-range/power.ts @@ -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)); +} diff --git a/tslang/test/tester/bigint-range/remainder.ts b/tslang/test/tester/bigint-range/remainder.ts new file mode 100644 index 000000000..5006989d5 --- /dev/null +++ b/tslang/test/tester/bigint-range/remainder.ts @@ -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)); +} diff --git a/tslang/test/tester/tests/00bigint_ops.ts b/tslang/test/tester/tests/00bigint_ops.ts index 520345b4e..dcaf19bb0 100644 --- a/tslang/test/tester/tests/00bigint_ops.ts +++ b/tslang/test/tester/tests/00bigint_ops.ts @@ -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; } @@ -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."); } diff --git a/tslang/test/tester/tests/00namespace_forward_class.ts b/tslang/test/tester/tests/00namespace_forward_class.ts new file mode 100644 index 000000000..0f8109a12 --- /dev/null +++ b/tslang/test/tester/tests/00namespace_forward_class.ts @@ -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."); +}