diff --git a/tslang/include/TypeScript/TypeScriptOps.td b/tslang/include/TypeScript/TypeScriptOps.td index 37bb7874c..6c1fc336e 100644 --- a/tslang/include/TypeScript/TypeScriptOps.td +++ b/tslang/include/TypeScript/TypeScriptOps.td @@ -942,6 +942,18 @@ def TypeScript_InvokeOp : TypeScript_Op<"Invoke", [ let hasVerifier = 1; } +// Ends the block of a load or a store through an interface's field inside a `try` (mayCallInterfaceAccessor): +// the slot may name a cell, whose getter or setter the access calls once lowered to LLVM, where it is an invoke +// unwinding to `unwindDest`. Until then this edge keeps the landing block, which may have no other predecessor, +// and shows the analyses that the access may leave for it. Lowered to a branch to `normalDest`. +def TypeScript_AccessorUnwindEdgeOp : TypeScript_Op<"AccessorUnwindEdge", [ + DeclareOpInterfaceMethods, + Terminator + ]> { + let successors = (successor AnySuccessor:$normalDest, + AnySuccessor:$unwindDest); +} + def TypeScript_InvokeHybridOp : TypeScript_Op<"InvokeHybrid", [ AttrSizedOperandSegments, DeclareOpInterfaceMethods, diff --git a/tslang/include/TypeScript/TypeScriptPassContext.h b/tslang/include/TypeScript/TypeScriptPassContext.h index 118520341..f63deca4e 100644 --- a/tslang/include/TypeScript/TypeScriptPassContext.h +++ b/tslang/include/TypeScript/TypeScriptPassContext.h @@ -1,3 +1,4 @@ +#include "TypeScript/Defines.h" #include "TypeScript/TypeScriptDialect.h" #include "TypeScript/TypeScriptOps.h" #include "TypeScript/DataStructs.h" @@ -180,8 +181,44 @@ struct TSFunctionContext TSFunctionContext() = default; mlir::SmallVector stateLabels; + + // the loads and stores through an interface's field inside a `try`, and the blocks their accessor calls unwind + // to (the innermost try's, which comes last): AccessorUnwindEdgeOps once the function is lowered + mlir::SmallVector> accessorUnwinds; }; +// A reference through an interface's field whose slot may name a cell of accessors (INTERFACE_ACCESSOR_CELL_TAG) +// instead of an offset: a field not optional, not function-typed, not a write of either kind. +inline bool isInterfaceAccessorCellRef(mlir::Value reference) +{ + auto interfaceSymbolRefOp = reference.getDefiningOp(); + if (!interfaceSymbolRefOp || interfaceSymbolRefOp.getOptional().value_or(false) + || interfaceSymbolRefOp->hasAttr(INTERFACE_FUNCTION_FIELD_WRITE_ATTR) + || interfaceSymbolRefOp->hasAttr(INTERFACE_OPTIONAL_WRITE_ATTR)) + { + return false; + } + + auto refType = dyn_cast(interfaceSymbolRefOp.getType()); + return refType && !isa(refType.getElementType()); +} + +// a load or a store that may call an interface field's getter or setter +inline bool mayCallInterfaceAccessor(Operation *op) +{ + if (auto loadOp = dyn_cast(op)) + { + return isInterfaceAccessorCellRef(loadOp.getReference()); + } + + if (auto storeOp = dyn_cast(op)) + { + return isInterfaceAccessorCellRef(storeOp.getReference()); + } + + return false; +} + template class TsPattern : public OpRewritePattern { public: diff --git a/tslang/lib/TypeScript/LowerToAffineLoops.cpp b/tslang/lib/TypeScript/LowerToAffineLoops.cpp index 38c2bf85b..4e8cb80ba 100644 --- a/tslang/lib/TypeScript/LowerToAffineLoops.cpp +++ b/tslang/lib/TypeScript/LowerToAffineLoops.cpp @@ -1889,6 +1889,7 @@ struct TryOpLowering : public TsPattern auto exitBlock = finallyHasOps ? exitBlockLast : continuation; auto landingBlock = cleanupHasOps ? cleanupBlock : catchHasOps ? catchesBlock : finallyBlock; tsContext->landingBlockOf[tryOp.getOperation()] = landingBlock; + if (landingBlock) { // TODO: check for nested ops for example in if block @@ -1902,6 +1903,10 @@ struct TryOpLowering : public TsPattern { tsContext->unwind[op] = landingBlock; } + else if (mayCallInterfaceAccessor(op)) + { + tsFuncContext->accessorUnwinds.push_back({op, landingBlock}); + } }; auto it = bodyBlock; do @@ -2101,6 +2106,10 @@ struct TryOpLowering : public TsPattern { tsContext->unwind[op] = finallyBlock; } + else if (mayCallInterfaceAccessor(op)) + { + tsFuncContext->accessorUnwinds.push_back({op, finallyBlock}); + } }; if (catchesBlock) @@ -2929,7 +2938,7 @@ void AddTsAffineLegalOps(ConversionTarget &target) mlir_ts::LoadOp, mlir_ts::LoadSaveOp, mlir_ts::NewOp, mlir_ts::CreateTupleOp, mlir_ts::DeconstructTupleOp, mlir_ts::CreateArrayOp, mlir_ts::NewEmptyArrayOp, mlir_ts::NewArrayOp, mlir_ts::DeleteOp, mlir_ts::PropertyRefOp, mlir_ts::InsertPropertyOp, mlir_ts::ExtractPropertyOp, mlir_ts::LogicalBinaryOp, mlir_ts::UndefOp, mlir_ts::VariableOp, mlir_ts::DebugVariableOp, mlir_ts::AllocaOp, - mlir_ts::InvokeOp, /*mlir_ts::ResultOp,*/ mlir_ts::VirtualSymbolRefOp, mlir_ts::ThisVirtualSymbolRefOp, mlir_ts::ThisSymbolRefOp, mlir_ts::InterfaceSymbolRefOp, + mlir_ts::InvokeOp, mlir_ts::AccessorUnwindEdgeOp, /*mlir_ts::ResultOp,*/ mlir_ts::VirtualSymbolRefOp, mlir_ts::ThisVirtualSymbolRefOp, mlir_ts::ThisSymbolRefOp, mlir_ts::InterfaceSymbolRefOp, mlir_ts::ExtractInterfaceThisOp, mlir_ts::ExtractInterfaceVTableOp, mlir_ts::ArrayPushOp, mlir_ts::ArrayPopOp, mlir_ts::ArrayUnshiftOp, mlir_ts::ArrayShiftOp, mlir_ts::ArraySpliceOp, mlir_ts::ArrayViewOp, mlir_ts::NewInterfaceOp, mlir_ts::VTableOffsetRefOp, mlir_ts::GetThisOp, mlir_ts::GetMethodOp, mlir_ts::DebuggerOp, @@ -2968,6 +2977,8 @@ void AddTsAffinePatterns(MLIRContext &context, ConversionTarget &target, Rewrite &context, &tsContext, &tsFuncContext); } +static void addAccessorUnwindEdges(TSFunctionContext &tsFuncContext); + void TypeScriptToAffineLoweringTSFuncPass::runOnFunction() { auto function = getFunction(); @@ -3034,6 +3045,8 @@ void TypeScriptToAffineLoweringTSFuncPass::runOnFunction() signalPassFailure(); } + addAccessorUnwindEdges(tsFuncContext); + LLVM_DEBUG(llvm::dbgs() << "\n!! Processing function: \n" << function.getName() << "\n";); cleanupEmptyBlocksWithoutPredecessors(function); @@ -3043,6 +3056,32 @@ void TypeScriptToAffineLoweringTSFuncPass::runOnFunction() LLVM_DEBUG(verifyFunction(function);); } +// Each load or store through an interface's field inside a `try` ends its block with an AccessorUnwindEdgeOp to the +// block its getter or setter call unwinds to - now that the function is one CFG, the try and every region around +// the access lowered into it. +static void addAccessorUnwindEdges(TSFunctionContext &tsFuncContext) +{ + llvm::MapVector unwindOf; + for (auto [op, unwindBlock] : tsFuncContext.accessorUnwinds) + { + unwindOf[op] = unwindBlock; + } + + for (auto [op, unwindBlock] : unwindOf) + { + if (!unwindBlock || !unwindBlock->getParent() || op->getParentRegion() != unwindBlock->getParent()) + { + continue; + } + + auto *block = op->getBlock(); + auto *continuation = block->splitBlock(std::next(op->getIterator())); + OpBuilder builder(op->getContext()); + builder.setInsertionPointToEnd(block); + builder.create(op->getLoc(), continuation, unwindBlock); + } +} + void TypeScriptToAffineLoweringFuncPass::runOnOperation() { auto function = getOperation(); diff --git a/tslang/lib/TypeScript/LowerToLLVM.cpp b/tslang/lib/TypeScript/LowerToLLVM.cpp index 3cec91240..ae6f78a0a 100644 --- a/tslang/lib/TypeScript/LowerToLLVM.cpp +++ b/tslang/lib/TypeScript/LowerToLLVM.cpp @@ -162,6 +162,27 @@ static mlir::Value nullStringAsText(mlir::Location loc, mlir::Value text, Conver return rewriter.create(loc, isNull, nullText, text); } +static bool isInsidePresplitCoroutine(mlir::Operation *op); + +// A function with Windows exception funclets: a variable-size alloca in it moves the stack, and an exception +// thrown by a call in a catch and caught by a typed catch of the same function then has the CRT write its catch +// object at the wrong address (a crash, or the wrong value). +static bool isInsideFunctionWithFunclets(mlir::Operation *op, const CompileOptions &compileOptions) +{ + if (!compileOptions.isWindows) + { + return false; + } + + if (auto llvmFuncOp = op->getParentOfType()) + { + return llvmFuncOp.getPersonality().has_value(); + } + + auto funcOp = op->getParentOfType(); + return funcOp && funcOp.getPersonality().value_or(false); +} + class PrintOpLowering : public TsLlvmPattern { public: @@ -207,7 +228,20 @@ class PrintOpLowering : public TsLlvmPattern } auto size = values.size(); - if (size > 1) + if (size > 1 && (isInsidePresplitCoroutine(op) || isInsideFunctionWithFunclets(op, tsLlvmContext->compileOptions))) + { + // the line on the heap, let go once written: no variable-size alloca where one breaks (see above) + mlir::Value result = + rewriter.create(loc, strType, values, rewriter.getBoolAttr(false)); + + mlir::Value valueAsLLVMType = rewriter.create(loc, tch.convertType(strType), result); + mlir::Value valueAsPtr = rewriter.create(loc, ptrType, valueAsLLVMType); + + rewriter.create(loc, putsFuncOp, valueAsPtr); + + ch.MemoryFree(valueAsPtr); + } + else if (size > 1) { // TODO: review, why we need stack recovery here auto stack = rewriter.create(loc, i8PtrType); @@ -571,20 +605,12 @@ struct InterfaceAccessorCell static std::optional of(mlir::Value reference, ConversionPatternRewriter &rewriter, const CompileOptions &compileOptions) { - auto interfaceSymbolRefOp = reference.getDefiningOp(); - if (!interfaceSymbolRefOp || interfaceSymbolRefOp.getOptional().value_or(false) - || interfaceSymbolRefOp->hasAttr(INTERFACE_FUNCTION_FIELD_WRITE_ATTR) - || interfaceSymbolRefOp->hasAttr(INTERFACE_OPTIONAL_WRITE_ATTR)) - { - return std::nullopt; - } - - auto refType = dyn_cast(interfaceSymbolRefOp.getType()); - if (!refType || isa(refType.getElementType())) + if (!isInterfaceAccessorCellRef(reference)) { return std::nullopt; } + auto interfaceSymbolRefOp = reference.getDefiningOp(); TypeHelper th(rewriter); auto loc = interfaceSymbolRefOp.getLoc(); auto interfaceVal = rewriter.getRemappedValue(interfaceSymbolRefOp.getInterfaceVal()); @@ -603,6 +629,41 @@ struct InterfaceAccessorCell return InterfaceAccessorCell{isCell, thisVal, slotValue, intPtrType, static_cast(sizeBits)}; } + // the block a load or a store in a `try` unwinds to: the AccessorUnwindEdgeOp after it says + static mlir::Block *unwindBlockOf(mlir::Operation *op) + { + auto edgeOp = dyn_cast_or_null(op->getNextNode()); + return edgeOp ? edgeOp.getUnwindDest() : nullptr; + } + + // a call of the getter or the setter, as an invoke unwinding to `unwindBlock` in a `try` + static mlir::Value call(mlir::Location loc, ConversionPatternRewriter &rewriter, mlir::Type resultType, + ValueRange operands, mlir::Block *unwindBlock) + { + TypeHelper th(rewriter); + auto isVoid = isa(resultType); + if (!unwindBlock) + { + SmallVector argTypes; + for (auto operand : operands.drop_front()) + { + argTypes.push_back(operand.getType()); + } + + auto callOp = rewriter.create(loc, LLVM::LLVMFunctionType::get(resultType, argTypes), operands); + return isVoid ? mlir::Value() : callOp.getResult(); + } + + auto *block = rewriter.getInsertionBlock(); + auto *normalBlock = rewriter.splitBlock(block, rewriter.getInsertionPoint()); + rewriter.setInsertionPointToEnd(block); + auto invokeOp = rewriter.create(loc, isVoid ? TypeRange{} : TypeRange{resultType}, + mlir::FlatSymbolRefAttr(), operands, normalBlock, ValueRange{}, + unwindBlock, ValueRange{}); + rewriter.setInsertionPointToStart(normalBlock); + return isVoid ? mlir::Value() : invokeOp.getResult(); + } + // the getter (index 0) or the setter (1) out of the cell mlir::Value accessor(mlir::Location loc, ConversionPatternRewriter &rewriter, int index) { @@ -2833,6 +2894,19 @@ struct CallHybridInternalOpLowering : public TsLlvmPattern +{ + using TsLlvmPattern::TsLlvmPattern; + + LogicalResult matchAndRewrite(mlir_ts::AccessorUnwindEdgeOp op, Adaptor transformed, + ConversionPatternRewriter &rewriter) const final + { + // the access before it unwinds there by an invoke of its own, when the slot is a cell + rewriter.replaceOpWithNewOp(op, ValueRange{}, op.getNormalDest()); + return success(); + } +}; + struct InvokeOpLowering : public TsLlvmPattern { using TsLlvmPattern::TsLlvmPattern; @@ -5163,10 +5237,9 @@ struct LoadOpLowering : public TsLlvmPattern { // the field filled by a getter: call it auto getterCallFunc = [&](OpBuilder &builder, Location location) -> mlir::Value { - TypeHelper th(rewriter); auto getter = accessorCell->accessor(loc, rewriter, 0); - auto getterType = LLVM::LLVMFunctionType::get(elementTypeConverted, {th.getPtrType()}); - return rewriter.create(loc, getterType, ValueRange{getter, accessorCell->thisVal}).getResult(); + return InterfaceAccessorCell::call(loc, rewriter, elementTypeConverted, ValueRange{getter, accessorCell->thisVal}, + InterfaceAccessorCell::unwindBlockOf(loadOp)); }; loadedValue = clh.conditionalExpressionLowering(loc, elementTypeConverted, accessorCell->isCell, getterCallFunc, @@ -5303,10 +5376,9 @@ struct StoreOpLowering : public TsLlvmPattern clh.conditionalBlocksLowering( hasSetter, [&](OpBuilder &builder, Location location) -> ValueRange { - auto setterType = LLVM::LLVMFunctionType::get( - th.getVoidType(), {th.getPtrType(), transformed.getValue().getType()}); - rewriter.create(loc, setterType, - ValueRange{setter, accessorCell->thisVal, transformed.getValue()}); + InterfaceAccessorCell::call(loc, rewriter, th.getVoidType(), + ValueRange{setter, accessorCell->thisVal, transformed.getValue()}, + InterfaceAccessorCell::unwindBlockOf(storeOp)); return ValueRange{}; }, [&](OpBuilder &builder, Location location) -> ValueRange { return ValueRange{}; }); @@ -9419,7 +9491,7 @@ void TypeScriptToLLVMLoweringPass::runOnOperation() InsertPropertyOpLowering, LengthOfOpLowering, SetLengthOfOpLowering, StringLengthOpLowering, StringResizeOpLowering, StringConcatOpLowering, StringCopyOpLowering, SharedNewOpLowering, SharedValueRefOpLowering, SharedCountOpLowering, StringCompareOpLowering, AnyCompareOpLowering, CharToStringOpLowering, UndefOpLowering, CopyStructOpLowering, MemoryCopyOpLowering, MemoryMoveOpLowering, - LoadSaveValueLowering, ThrowUnwindOpLowering, ThrowCallOpLowering, VariableOpLowering, DebugVariableOpLowering, AllocaOpLowering, InvokeOpLowering, + LoadSaveValueLowering, ThrowUnwindOpLowering, ThrowCallOpLowering, VariableOpLowering, DebugVariableOpLowering, AllocaOpLowering, InvokeOpLowering, AccessorUnwindEdgeOpLowering, InvokeHybridOpLowering, VirtualSymbolRefOpLowering, ThisVirtualSymbolRefOpLowering, ThisSymbolRefOpLowering, InterfaceSymbolRefOpLowering, NewInterfaceOpLowering, VTableOffsetRefOpLowering, LoadBoundRefOpLowering, StoreBoundRefOpLowering, CreateBoundRefOpLowering, CreateBoundFunctionOpLowering, GetThisOpLowering, GetMethodOpLowering, TypeOfOpLowering, TypeOfAnyOpLowering, DebuggerOpLowering, diff --git a/tslang/lib/TypeScript/MLIRGenExpressions.cpp b/tslang/lib/TypeScript/MLIRGenExpressions.cpp index b7c23fd3b..0e952dfbc 100644 --- a/tslang/lib/TypeScript/MLIRGenExpressions.cpp +++ b/tslang/lib/TypeScript/MLIRGenExpressions.cpp @@ -563,6 +563,37 @@ namespace mlirgen return mlirGen(leftHandSideExpressionAST.as(), genContext); } + // `++`/`--` on a get/set property (`o.prop++`): no reference to store back to, so the setter is called with the + // getter's value plus or minus one, as `o.prop += 1` does. The value is the new one for a prefix operator, and + // the old one for a postfix operator. + ValueOrLogicalResult MLIRGenImpl::mlirGenAccessorIncrement(mlir::Location location, SyntaxKind opCode, mlir::Value accessorValue, + bool prefix, const GenContext &genContext) + { + auto one = builder.create(location, builder.getI32Type(), builder.getI32IntegerAttr(1)); + mlir::Value step = one; + if (accessorValue.getType() != step.getType()) + { + CAST(step, location, accessorValue.getType(), one, genContext); + } + + auto binaryOpCode = opCode == SyntaxKind::PlusPlusToken ? SyntaxKind::PlusToken : SyntaxKind::MinusToken; + auto newValue = builder.create( + location, accessorValue.getType(), builder.getI32IntegerAttr(static_cast(binaryOpCode)), accessorValue, step); + + auto saved = mlirGenSaveLogicOneItem(location, accessorValue, newValue, genContext); + EXIT_IF_FAILED(saved) + + return prefix ? mlir::Value(newValue) : accessorValue; + } + + static bool isAccessorValue(mlir::Value value) + { + auto *defOp = value.getDefiningOp(); + return defOp && mlir::isa(defOp); + } + ValueOrLogicalResult MLIRGenImpl::mlirGen(PrefixUnaryExpression prefixUnaryExpressionAST, const GenContext &genContext) { auto location = loc(prefixUnaryExpressionAST); @@ -636,6 +667,11 @@ namespace mlirgen return mlir::failure(); } + if (isAccessorValue(expressionValue) && mth.isNumericType(expressionValue.getType())) + { + return mlirGenAccessorIncrement(location, opCode, expressionValue, true, genContext); + } + return V(builder.create(location, expressionValue.getType(), builder.getI32IntegerAttr((int)opCode), expressionValue)); default: @@ -667,6 +703,11 @@ namespace mlirgen return mlir::failure(); } + if (isAccessorValue(expressionValue) && mth.isNumericType(expressionValue.getType())) + { + return mlirGenAccessorIncrement(location, opCode, expressionValue, false, genContext); + } + return V(builder.create(location, expressionValue.getType(), builder.getI32IntegerAttr((int)opCode), expressionValue)); default: diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 8d58a77dc..1099653c8 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -5634,6 +5634,9 @@ class MLIRGenImpl return value; } + ValueOrLogicalResult mlirGenAccessorIncrement(mlir::Location location, SyntaxKind opCode, mlir::Value accessorValue, + bool prefix, const GenContext &genContext); + ValueOrLogicalResult mlirGen(PrefixUnaryExpression prefixUnaryExpressionAST, const GenContext &genContext); ValueOrLogicalResult mlirGen(PostfixUnaryExpression postfixUnaryExpressionAST, const GenContext &genContext); diff --git a/tslang/lib/TypeScript/TypeScriptOps.cpp b/tslang/lib/TypeScript/TypeScriptOps.cpp index dcfa872c8..a569b9101 100644 --- a/tslang/lib/TypeScript/TypeScriptOps.cpp +++ b/tslang/lib/TypeScript/TypeScriptOps.cpp @@ -1137,6 +1137,16 @@ SuccessorOperands mlir_ts::InvokeOp::getSuccessorOperands(unsigned index) return SuccessorOperands(getUnwindDestOperandsMutable()); } +//===----------------------------------------------------------------------===// +// AccessorUnwindEdgeOp +//===----------------------------------------------------------------------===// + +SuccessorOperands mlir_ts::AccessorUnwindEdgeOp::getSuccessorOperands(unsigned index) +{ + assert(index <= 1 && "invalid successor index"); + return SuccessorOperands(MutableOperandRange(getOperation(), 0, 0)); +} + //===----------------------------------------------------------------------===// // InvokeHybridOp //===----------------------------------------------------------------------===// diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 582d0a510..2b21cc6c2 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -606,6 +606,7 @@ tslang_add_test(NAME test-compile-00-class-discover-types COMMAND test-runner "$ tslang_add_test(NAME test-compile-00-class-accessor COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_accessor.ts") tslang_add_test(NAME test-compile-00-class-accessor-2 COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_accessor2.ts") tslang_add_test(NAME test-compile-00-class-accessor-super COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_accessor_super.ts") +tslang_add_test(NAME test-compile-00-class-accessor-increment COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_accessor_increment.ts") tslang_add_test(NAME test-compile-00-class-accessor-getter-only-abstract COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_accessor_getter_only_abstract.ts") tslang_add_test(NAME test-compile-00-class-accessor-virtual COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_accessor_virtual.ts") tslang_add_test(NAME test-compile-00-class-accessor-implements-field COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_accessor_implements_field.ts") @@ -742,6 +743,7 @@ tslang_add_test(NAME test-compile-00-try-finally-funclet COMMAND test-runner "${ tslang_add_test(NAME test-compile-00-try-finally-break-continue COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_finally_break_continue.ts") tslang_add_test(NAME test-compile-00-try-catch-rethrow COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_catch_rethrow.ts") tslang_add_test(NAME test-compile-00-try-catch-accessor COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_catch_accessor.ts") +tslang_add_test(NAME test-compile-00-try-catch-call-in-catch COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_catch_call_in_catch.ts") tslang_add_test(NAME test-compile-00-try-catch-mismatch-rethrow COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_catch_mismatch_rethrow.ts") tslang_add_test(NAME test-compile-00-try-catch-return-dispose COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_catch_return_dispose.ts") tslang_add_test(NAME test-compile-01-try-catch-return-dispose COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/01try_catch_return_dispose.ts") @@ -1231,6 +1233,7 @@ tslang_add_test(NAME test-jit-00-class-discover-types COMMAND test-runner -jit " tslang_add_test(NAME test-jit-00-class-accessor COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_accessor.ts") tslang_add_test(NAME test-jit-00-class-accessor-2 COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_accessor2.ts") tslang_add_test(NAME test-jit-00-class-accessor-super COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_accessor_super.ts") +tslang_add_test(NAME test-jit-00-class-accessor-increment COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_accessor_increment.ts") tslang_add_test(NAME test-jit-00-class-accessor-getter-only-abstract COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_accessor_getter_only_abstract.ts") tslang_add_test(NAME test-jit-00-class-accessor-virtual COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_accessor_virtual.ts") tslang_add_test(NAME test-jit-00-class-accessor-implements-field COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00class_accessor_implements_field.ts") @@ -1365,6 +1368,7 @@ tslang_add_test(NAME test-jit-00-try-finally-funclet COMMAND test-runner -jit "$ tslang_add_test(NAME test-jit-00-try-finally-break-continue COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_finally_break_continue.ts") tslang_add_test(NAME test-jit-00-try-catch-rethrow COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_catch_rethrow.ts") tslang_add_test(NAME test-jit-00-try-catch-accessor COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_catch_accessor.ts") +tslang_add_test(NAME test-jit-00-try-catch-call-in-catch COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_catch_call_in_catch.ts") # pre-existing JIT limitation (reproduces on unmodified main too): the JIT's # Windows SEH landing pad/personality plumbing exits with code 3 and no # output on a typed-catch mismatch that must unwind past a function boundary, @@ -2196,6 +2200,7 @@ set(TSLANG_CORPUS 00class_override_inferred_return.ts 00class_access_control.ts 00class_accessor_super.ts + 00class_accessor_increment.ts 00class_accessor_getter_only_abstract.ts 00class_accessor_virtual.ts 00class_accessor_implements_field.ts @@ -2466,6 +2471,7 @@ set(TSLANG_CORPUS 00try_catch_mismatch_rethrow.ts 00try_catch_rethrow.ts 00try_catch_accessor.ts + 00try_catch_call_in_catch.ts 00try_catch_return_dispose.ts 00try_catch_return.ts 00try_catch_sequence_and_nesting.ts @@ -5453,17 +5459,21 @@ if (NOT WIN32) FAIL_REGULAR_EXPRESSION "Stack dump|Segmentation|assertion failed") endif() -# An exception nothing catches ends a JIT run with an error, not with LLVM's crash handler -# reporting a crash of the compiler. Windows only: that is where the JIT catches it. +# An exception nothing catches ends a JIT run with an error that says what was thrown (a class by its +# name), not with LLVM's crash handler reporting a crash of the compiler. Windows only: that is where +# the JIT catches it. if (WIN32) - foreach(uncaught_name throw_string throw_class) + set(uncaught_expected_throw_string "error: uncaught exception: not caught") + set(uncaught_expected_throw_class "error: uncaught exception: Failure") + set(uncaught_expected_throw_number "error: uncaught exception: 2.5") + foreach(uncaught_name throw_string throw_class throw_number) foreach(uncaught_model gc rc none) add_test(NAME test-jit-${uncaught_model}-uncaught-${uncaught_name} COMMAND $ --emit=jit --no-default-lib -mm=${uncaught_model} --shared-libs=$ "${PROJECT_SOURCE_DIR}/test/tester/uncaught/${uncaught_name}.ts") set_tests_properties(test-jit-${uncaught_model}-uncaught-${uncaught_name} - PROPERTIES PASS_REGULAR_EXPRESSION "error: uncaught exception" + PROPERTIES PASS_REGULAR_EXPRESSION "${uncaught_expected_${uncaught_name}}" FAIL_REGULAR_EXPRESSION "Stack dump|PLEASE submit") endforeach() endforeach() diff --git a/tslang/test/tester/tests/00class_accessor_increment.ts b/tslang/test/tester/tests/00class_accessor_increment.ts new file mode 100644 index 000000000..02ffafdac --- /dev/null +++ b/tslang/test/tester/tests/00class_accessor_increment.ts @@ -0,0 +1,60 @@ +// `++` and `--` on a get/set property call the setter with the getter's value plus or minus one, as `+= 1` does: +// a prefix operator gives the new value, a postfix one the old. It was an error, "'++'/'--' on a get/set accessor +// property is not supported". +class Counter { + private n: number = 1; + sets = 0; + get v() { return this.n; } + set v(x: number) { this.sets++; this.n = x; } + + static total: number = 10; + static get all() { return Counter.total; } + static set all(x: number) { Counter.total = x; } + + bump() { + return this.v++; + } +} + +class Big extends Counter { + override get v() { return super.v; } + override set v(x: number) { super.v = x * 10; } +} + +interface Valued { + v: number; +} + +function main() { + const c = new Counter(); + const post = c.v++; + assert(post == 1 && c.v == 2, "postfix gives the old value"); + const pre = ++c.v; + assert(pre == 3 && c.v == 3, "prefix gives the new value"); + c.v--; + --c.v; + assert(c.v == 1 && c.sets == 4, "decrement, once through the setter each"); + + Counter.all++; + assert(Counter.all == 11, "static"); + + assert(c.bump() == 1 && c.v == 2, "through this"); + + const b: Counter = new Big(); + b.v++; + assert(b.v == 20, "virtual setter"); + + const valued: Valued = c; + valued.v++; + assert(c.v == 3, "through an interface"); + + const o = { + h: 5.0, + get x() { return this.h; }, + set x(value: number) { this.h = value; } + }; + o.x++; + assert(o.h == 6, "object literal"); + + print("done."); +} diff --git a/tslang/test/tester/tests/00try_catch_accessor.ts b/tslang/test/tester/tests/00try_catch_accessor.ts index c02d0f437..778fb4a85 100644 --- a/tslang/test/tester/tests/00try_catch_accessor.ts +++ b/tslang/test/tester/tests/00try_catch_accessor.ts @@ -1,5 +1,7 @@ // An accessor that throws inside `try` is caught there: its call is lowered after the `try`, which recorded only -// the calls and throws already in its body, so a get or set reached the caller uncaught. +// the calls and throws already in its body, so a get or set reached the caller uncaught. Through an interface's +// field the call is made by the load or the store of a slot naming a cell of accessors, as late as LLVM: the access +// ends its block with an edge to the handler, and calls the accessor by an invoke unwinding there. class Fail { constructor(public where: string) {} } @@ -18,6 +20,20 @@ class B extends A { override set v(x: number) { super.v = x; } } +interface Named { + name: string; +} + +class Box implements Named { + private n = "box"; + get name() { if (this.n == "bad") throw new Fail("interface get"); return this.n; } + set name(v: string) { if (v == "") throw new Fail("interface set"); this.n = v; } +} + +class Plain implements Named { + name = "plain"; +} + abstract class Shape { abstract size: number; } @@ -63,6 +79,36 @@ function main() { try { b.v = -1; } catch (e: Fail) { where = e.where; } assert(where == "set", "virtual set"); + const box: Named = new Box(); + where = ""; + try { box.name = ""; } catch (e: Fail) { where = e.where; } + assert(where == "interface set", "set through an interface"); + + box.name = "bad"; + where = ""; + try { print(box.name); } catch (e: Fail) { where = e.where; } + assert(where == "interface get", "get through an interface"); + + box.name = "ok"; + where = ""; + try { where = box.name; } catch (e: Fail) { where = "wrong"; } + assert(where == "ok", "get through an interface that does not throw"); + + let boxFinally = false; + where = ""; + try { + try { box.name = ""; } finally { boxFinally = true; } + } catch (e: Fail) { + where = e.where; + } + assert(boxFinally && where == "interface set", "set through an interface, finally"); + + // a plain field behind the interface: the slot is no cell + const plain: Named = new Plain(); + where = ""; + try { plain.name = "plain2"; where = plain.name; } catch (e: Fail) { where = "wrong"; } + assert(where == "plain2", "a field through an interface"); + const shape: Shape = new Square(); where = ""; try { print(shape.size); } catch (e: Fail) { where = e.where; } diff --git a/tslang/test/tester/tests/00try_catch_call_in_catch.ts b/tslang/test/tester/tests/00try_catch_call_in_catch.ts new file mode 100644 index 000000000..71bfc091e --- /dev/null +++ b/tslang/test/tester/tests/00try_catch_call_in_catch.ts @@ -0,0 +1,50 @@ +// An exception a call in a catch throws, taken by a typed catch of the same function: its catch variable reads what +// was thrown. A print of several values in the function was a variable-size alloca, which on Windows moves the stack +// of a function with exception funclets, and the CRT wrote the outer catch's object at the wrong address - a crash, +// or a stack overflow. +class Fail { + constructor(public where: string) {} +} + +function throwNumber(n: number) { throw n; } +function throwFail(where: string) { throw new Fail(where); } +function throwString(s: string) { throw s; } + +function main() { + let n = 0.0; + try { + try { throw 1; } catch (e: number) { print("inner", e); throwNumber(2.5); } + } catch (e: number) { + n = e; + } + assert(n == 2.5, "a number"); + + let where = ""; + try { + try { throwFail("first"); } catch (e: Fail) { print("inner", e.where); throwFail("second"); } + } catch (e: Fail) { + where = e.where; + } + assert(where == "second", "a class"); + + let s = ""; + try { + try { throw "a"; } catch (e: string) { throwString("b"); } + } catch (e: string) { + print("outer", e); + s = e; + } + assert(s == "b", "a string"); + + // through a finally on the way out + let ran = false; + n = 0; + try { + try { throw 1; } catch (e: number) { throwNumber(3); } finally { ran = true; } + } catch (e: number) { + n = e; + } + assert(ran && n == 3, "finally"); + + print("done."); +} diff --git a/tslang/test/tester/uncaught/throw_number.ts b/tslang/test/tester/uncaught/throw_number.ts new file mode 100644 index 000000000..ead509524 --- /dev/null +++ b/tslang/test/tester/uncaught/throw_number.ts @@ -0,0 +1,5 @@ +// nothing catches it: the run ends with an error that says what was thrown +function main() { + print("before"); + throw 2.5; +} diff --git a/tslang/tslang/jit.cpp b/tslang/tslang/jit.cpp index 96c0b8599..388e9873b 100644 --- a/tslang/tslang/jit.cpp +++ b/tslang/tslang/jit.cpp @@ -454,6 +454,103 @@ static void *jitTypeInfoVftable() using JitEntryThunkFn = int (*)(int, char **); +#ifdef _WIN32 +// What an uncaught exception threw, said after "uncaught exception: ", or empty +static char uncaughtDescription[512]; + +// The thrown value, read from the exception record of a throw (_CxxThrowException's): the object, and its +// ThrowInfo, whose first catchable type names its type (`.N` a number, `.PEAD` a string, `.PEAVName@@` a class). +// Read while the object is alive, in the filter; a record not shaped so is left undescribed. +static void describeUncaught(EXCEPTION_POINTERS *pointers) +{ + uncaughtDescription[0] = '\0'; + __try + { + auto *record = pointers->ExceptionRecord; + if (record->NumberParameters < 4) + { + return; + } + + auto *object = reinterpret_cast(record->ExceptionInformation[1]); + auto *throwInfo = reinterpret_cast(record->ExceptionInformation[2]); + auto *imageBase = reinterpret_cast(record->ExceptionInformation[3]); + if (!object || !throwInfo || !imageBase) + { + return; + } + + auto *catchableTypes = reinterpret_cast(imageBase + throwInfo[3]); + auto count = catchableTypes[0]; + if (count < 1) + { + return; + } + + // a type descriptor: the type_info vtable, a spare pointer, then the name + auto typeName = [&](int index) { + auto *catchableType = reinterpret_cast(imageBase + catchableTypes[1 + index]); + return reinterpret_cast(imageBase + catchableType[1] + 2 * sizeof(void *)); + }; + + auto *name = typeName(0); + auto size = sizeof(uncaughtDescription); + if (strcmp(name, ".PEAD") == 0) + { + auto *text = *reinterpret_cast(object); + snprintf(uncaughtDescription, size, "%s", text ? text : "null"); + } + else if (strcmp(name, ".N") == 0) + { + snprintf(uncaughtDescription, size, "%.17g", *reinterpret_cast(object)); + } + else if (strcmp(name, ".H") == 0) + { + snprintf(uncaughtDescription, size, "%d", *reinterpret_cast(object)); + } + else if (strcmp(name, "._N") == 0) + { + snprintf(uncaughtDescription, size, "%s", *reinterpret_cast(object) ? "true" : "false"); + } + else if (strcmp(name, "._J") == 0) + { + snprintf(uncaughtDescription, size, "%lldn", *reinterpret_cast(object)); + } + else if (strncmp(name, ".PEAV", 5) == 0) + { + // a class: its name, up to the `@@` that ends it + auto *className = name + 5; + auto *end = strstr(className, "@@"); + auto length = end ? static_cast(end - className) : static_cast(strlen(className)); + snprintf(uncaughtDescription, size, "%.*s", length, className); + // an Error (core.ts): after the vtable, `message?: string` - the text, and whether it is set + for (int i = 0; i < count; i++) + { + if (strcmp(typeName(i), ".PEAVError@@") != 0) + { + continue; + } + + auto *instance = *reinterpret_cast(object); + auto *message = instance ? *reinterpret_cast(instance + sizeof(void *)) : nullptr; + auto isSet = instance && *reinterpret_cast(instance + 2 * sizeof(void *)); + if (isSet && message) + { + auto used = strlen(uncaughtDescription); + snprintf(uncaughtDescription + used, size - used, ": %s", message); + } + + break; + } + } + } + __except (EXCEPTION_EXECUTE_HANDLER) + { + uncaughtDescription[0] = '\0'; + } +} +#endif + // Calls the program's entry point; false when an exception nothing in the program catches came // out of it. Left alone, that exception reaches LLVM's crash handler, which reports it as a crash // of the compiler, with a stack dump and a request for a bug report. Windows only: SEH rather @@ -468,7 +565,8 @@ static bool callEntryThunk(JitEntryThunkFn entryThunk, int argc, char **argv, in exitCode = entryThunk(argc, argv); return true; } - __except (GetExceptionCode() == cxxExceptionCode ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) + __except (GetExceptionCode() == cxxExceptionCode ? (describeUncaught(GetExceptionInformation()), EXCEPTION_EXECUTE_HANDLER) + : EXCEPTION_CONTINUE_SEARCH) { return false; } @@ -1002,7 +1100,14 @@ static int runProgram(ProgramSymbolLookup lookup, llvm::ArrayRef in if (!finished) { fflush(stdout); - llvm::WithColor::error(llvm::errs(), "tslang") << "uncaught exception\n"; + auto &os = llvm::WithColor::error(llvm::errs(), "tslang") << "uncaught exception"; +#ifdef _WIN32 + if (uncaughtDescription[0]) + { + os << ": " << uncaughtDescription; + } +#endif + os << "\n"; exitCode = 1; }