diff --git a/tslang/include/TypeScript/Defines.h b/tslang/include/TypeScript/Defines.h index baf19af8f..8c6957760 100644 --- a/tslang/include/TypeScript/Defines.h +++ b/tslang/include/TypeScript/Defines.h @@ -124,6 +124,10 @@ #define DLL_IMPORT "dllimport" #define DLL_NAME "dllname" +// module attribute: the class types the module throws, for binding an untyped catch on the +// Itanium path (linux::SaveCatchVarOpLowering) +#define THROWN_CLASSES_ATTR_NAME "ts.thrown_classes" + #if __LP64__ #define TRAMPOLINE_SIZE 48 #else diff --git a/tslang/include/TypeScript/LowerToLLVM/LLVMRTTIHelperVCWin32Const.h b/tslang/include/TypeScript/LowerToLLVM/LLVMRTTIHelperVCWin32Const.h index 12414afbb..04052a9b7 100644 --- a/tslang/include/TypeScript/LowerToLLVM/LLVMRTTIHelperVCWin32Const.h +++ b/tslang/include/TypeScript/LowerToLLVM/LLVMRTTIHelperVCWin32Const.h @@ -42,6 +42,24 @@ constexpr const auto *imageBaseRef = "__ImageBase"; // throws both an `int` and a `string` (say) from having one of them silently take on the // other's copy size. +// Copy-function records. A CatchableType whose properties do not say "simple type" and that +// names a copyFunction is not memcpy'd into the catch variable: the CRT calls +// copyFunction(catchVariable, thrownObject) instead (`__thiscall` on x86 - CxxThrowCallingConvPass +// gives every function named with copyThunkPrefix that convention). That is what lets a thrown +// value reach a handler of a different shape: +// - the `.PEAX` entry of an int/double/string/class throw boxes the value into an `any`, which +// is what an untyped `catch (e)` or `catch (e: any)` binds (they filter on `??_R0PEAX@8`). +// It used to be a plain copy, so the catch variable held the raw value and the first read of +// it as an `any` crashed; +// - an int throw also lists `.N` with a thunk widening it to a double, so `catch (e: number)` +// catches `throw 1` (an integer literal is an `int` here). +// These records, and the arrays and ThrowInfos that list them, have names of their own: an +// object built before them carries linkonce_odr records under the old names with the old +// contents, and the linker keeps whichever copy it sees first. +constexpr const auto *copyThunkPrefix = ".eh.copy."; +constexpr int copyFunctionProperties = 0; +constexpr int simpleTypeProperties = 1; + namespace F32Type { constexpr const auto *typeName = ".N"; @@ -50,9 +68,10 @@ constexpr const auto *typeInfoRef = "??_R0N@8"; constexpr const auto *typeInfoRef2 = "??_R0PEAX@8"; constexpr const auto *catchableTypeInfoRef = "_CT??_R0N@88"; // own record, not the pointer-shaped `_CT??_R0PEAX@88` - see the block comment above -constexpr const auto *catchableTypeInfoRef2 = "_CT??_R0PEAX@N88"; -constexpr const auto *catchableTypeInfoArrayRef = "_CTA2N"; -constexpr const auto *throwInfoRef = "_TI2N"; +constexpr const auto *catchableTypeInfoRef2 = "_CT??_R0PEAX@N88.box"; +constexpr const auto *copyThunk2 = ".eh.copy.box.N"; +constexpr const auto *catchableTypeInfoArrayRef = "_CTA2N.box"; +constexpr const auto *throwInfoRef = "_TI2N.box"; // describes `.N` (double), like F64Type - see setF32AsCatchType constexpr int catchableTypeSize = 8; } // namespace F32Type @@ -65,9 +84,10 @@ constexpr const auto *typeInfoRef = "??_R0N@8"; constexpr const auto *typeInfoRef2 = "??_R0PEAX@8"; constexpr const auto *catchableTypeInfoRef = "_CT??_R0N@88"; // own record, not the pointer-shaped `_CT??_R0PEAX@88` - see the block comment above -constexpr const auto *catchableTypeInfoRef2 = "_CT??_R0PEAX@N88"; -constexpr const auto *catchableTypeInfoArrayRef = "_CTA2N"; -constexpr const auto *throwInfoRef = "_TI2N"; +constexpr const auto *catchableTypeInfoRef2 = "_CT??_R0PEAX@N88.box"; +constexpr const auto *copyThunk2 = ".eh.copy.box.N"; +constexpr const auto *catchableTypeInfoArrayRef = "_CTA2N.box"; +constexpr const auto *throwInfoRef = "_TI2N.box"; constexpr int catchableTypeSize = 8; } // namespace F64Type @@ -79,9 +99,15 @@ constexpr const auto *typeInfoRef = "??_R0H@8"; constexpr const auto *typeInfoRef2 = "??_R0PEAX@8"; constexpr const auto *catchableTypeInfoRef = "_CT??_R0H@84"; // own record, not the pointer-shaped `_CT??_R0PEAX@88` - see the block comment above -constexpr const auto *catchableTypeInfoRef2 = "_CT??_R0PEAX@84"; -constexpr const auto *catchableTypeInfoArrayRef = "_CTA2H"; -constexpr const auto *throwInfoRef = "_TI2H"; +constexpr const auto *catchableTypeInfoRef2 = "_CT??_R0PEAX@84.box"; +constexpr const auto *copyThunk2 = ".eh.copy.box.H"; +// the third entry: `.N` (double), reached through a widening thunk +constexpr const auto *typeName3 = ".N"; +constexpr const auto *typeInfoRef3 = "??_R0N@8"; +constexpr const auto *catchableTypeInfoRef3 = "_CT??_R0N@88.fromH"; +constexpr const auto *copyThunk3 = ".eh.copy.num.H"; +constexpr const auto *catchableTypeInfoArrayRef = "_CTA3H"; +constexpr const auto *throwInfoRef = "_TI3H"; // 4, not the pointer size: `int` is 4 bytes on every target, and the `4` at the end of // `_CT??_R0H@84` says so too constexpr int catchableTypeSize = 4; @@ -94,9 +120,10 @@ constexpr const auto *typeName2 = ".PEAX"; constexpr const auto *typeInfoRef = "??_R0PEAD@8"; constexpr const auto *typeInfoRef2 = "??_R0PEAX@8"; constexpr const auto *catchableTypeInfoRef = "_CT??_R0PEAD@88"; -constexpr const auto *catchableTypeInfoRef2 = "_CT??_R0PEAX@88"; -constexpr const auto *catchableTypeInfoArrayRef = "_CTA2PEAD"; -constexpr const auto *throwInfoRef = "_TIC2PEAD"; +constexpr const auto *catchableTypeInfoRef2 = "_CT??_R0PEAX@88.box.PEAD"; +constexpr const auto *copyThunk2 = ".eh.copy.box.PEAD"; +constexpr const auto *catchableTypeInfoArrayRef = "_CTA2PEAD.box"; +constexpr const auto *throwInfoRef = "_TIC2PEAD.box"; } // namespace StringType namespace I8PtrType @@ -118,11 +145,15 @@ constexpr const auto *typeInfoRefSuffix = "@@@8"; constexpr const auto *typeInfoRef2 = "??_R0PEAX@8"; constexpr const auto *catchableTypeInfoRef = "_CT??_R0PEAV"; constexpr const auto *catchableTypeInfoRefSuffix = "@@@88"; -constexpr const auto *catchableTypeInfoRef2 = "_CT??_R0PEAX@88"; +// per class, like the thunk it names: catchableTypeInfoRef2 + name + suffix +constexpr const auto *catchableTypeInfoRef2 = "_CT??_R0PEAX@88.box.PEAV"; +constexpr const auto *catchableTypeInfoRef2Suffix = "@@"; +constexpr const auto *copyThunk2 = ".eh.copy.box.PEAV"; +constexpr const auto *copyThunk2Suffix = "@@"; constexpr const auto *catchableTypeInfoArrayRef = "_CTA2PEAV"; -constexpr const auto *catchableTypeInfoArrayRefSuffix = "@@"; +constexpr const auto *catchableTypeInfoArrayRefSuffix = "@@.box"; constexpr const auto *throwInfoRef = "_TI2PEAV"; -constexpr const auto *throwInfoRefSuffix = "@@"; +constexpr const auto *throwInfoRefSuffix = "@@.box"; } // namespace ClassType } // namespace windows diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRRTTIHelperVC.h b/tslang/include/TypeScript/MLIRLogic/MLIRRTTIHelperVC.h index 2db3332c8..8cfd028b0 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRRTTIHelperVC.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRRTTIHelperVC.h @@ -24,6 +24,12 @@ class MLIRRTTIHelperVC { } + // Windows only: the Itanium path has no copy functions to point at a thunk + void setCopyThunkBuilder(MLIRRTTIHelperVCWin32::CopyThunkBuilder builder) + { + rttiWin.setCopyThunkBuilder(builder); + } + bool setRTTIForType(mlir::Location loc, mlir::Type type, std::function resolveClassInfo) { if (isWindows) diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRRTTIHelperVCLinux.h b/tslang/include/TypeScript/MLIRLogic/MLIRRTTIHelperVCLinux.h index b16c997e6..cc077a9b4 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRRTTIHelperVCLinux.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRRTTIHelperVCLinux.h @@ -170,6 +170,9 @@ class MLIRRTTIHelperVCLinux #else setF32AsCatchType(); #endif + // a `catch (e: number)` also takes a thrown int (`throw 1`), and binding it + // compares against the int type_info - see TryOpLowering, SaveCatchVarOpLowering + setI32AsCatchType(); }) .Case([&](auto stringType) { setStringTypeAsCatchType(); }) .Case([&](auto classType) { @@ -181,7 +184,17 @@ class MLIRRTTIHelperVCLinux setClassTypeAsCatchType(classAndBases); }) - .Case([&](auto anyType) { setI8PtrAsCatchType(); }) + .Case([&](auto anyType) { + // This overload only declares the RTTI globals a catch may reference. An + // untyped/`any` catch is a catch-all (see the other overload), and binding its + // variable compares the caught exception's type_info against each of these - + // see linux::SaveCatchVarOpLowering. `_ZTIPv` is also what a `throw e` of the + // caught value throws again. + setI32AsCatchType(); + setF64AsCatchType(); + setStringTypeAsCatchType(); + setI8PtrAsCatchType(); + }) .Default([&](auto type) { LLVM_DEBUG(llvm::dbgs() << "...unsupported throw/catch type: " << type << "\n";); result = false; @@ -242,7 +255,11 @@ class MLIRRTTIHelperVCLinux }) .Case([&](auto stringType) { setStringTypeAsCatchType(); }) .Case([&](auto classType) { setClassTypeAsCatchType(classType.getName().getValue()); }) - .Case([&](auto anyType) { setI8PtrAsCatchType(); }) + // An untyped `catch (e)` / `catch (e: any)` has to catch everything, and on the + // Itanium path that is a clause-less `catch ptr null`, which is what TryOpLowering + // emits when no type is set. A `_ZTIPv` (void*) clause is not a catch-all: it + // matches pointer-typed exceptions only, so a thrown number left the program. + .Case([&](auto anyType) {}) .Default([&](auto type) { LLVM_DEBUG(llvm::dbgs() << "...unsupported throw/catch type: " << type << "\n";); result = false; diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRRTTIHelperVCWin32.h b/tslang/include/TypeScript/MLIRLogic/MLIRRTTIHelperVCWin32.h index d9b9eceda..464f2e344 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRRTTIHelperVCWin32.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRRTTIHelperVCWin32.h @@ -37,8 +37,21 @@ class MLIRRTTIHelperVCWin32 // bytes the CRT copies into the catch variable's slot - see catchableTypeSize in // LLVMRTTIHelperVCWin32Const.h for why getting this wrong corrupts the frame int catchableTypeSize; + // when set, the CRT calls this function to build the catch variable instead of copying + // catchableTypeSize bytes - see copyThunkPrefix in LLVMRTTIHelperVCWin32Const.h + std::string copyThunk = ""; + // what the thunk converts the thrown value to (`any`, or `number` for an int) + mlir::Type copyThunkTarget = mlir::Type(); }; + public: + // Builds the copy thunk `name`: void name(ref dest, ref src), storing `src` + // converted to `target` into `dest`. Supplied by MLIRGen, which can generate the conversion. + using CopyThunkBuilder = std::function; + + private: + mlir::OpBuilder &rewriter; mlir::ModuleOp &parentModule; MLIRTypeHelper mth; @@ -48,6 +61,10 @@ class MLIRRTTIHelperVCWin32 CompileOptions& compileOptions; + // the thrown value's own type, which every copy thunk reads its source as + mlir::Type thrownType; + CopyThunkBuilder copyThunkBuilder; + public: std::string catchableTypeInfoArrayRef; std::string throwInfoRef; @@ -58,14 +75,34 @@ class MLIRRTTIHelperVCWin32 // setI32AsCatchType(); } + void setCopyThunkBuilder(CopyThunkBuilder builder) + { + copyThunkBuilder = builder; + } + + // the `.PEAX` entry of a primitive, string or class throw: boxes the value into the `any` an + // untyped or `any` catch binds + TypeNames boxEntry(std::string catchableTypeInfoRef, std::string copyThunk) + { + TypeNames entry{windows::I8PtrType::typeName, windows::I8PtrType::typeInfoRef, catchableTypeInfoRef, pointerSize()}; + entry.copyThunk = copyThunk; + entry.copyThunkTarget = mlir_ts::AnyType::get(rewriter.getContext()); + return entry; + } + + TypeNames classBoxEntry(StringRef name) + { + return boxEntry(join(name, windows::ClassType::catchableTypeInfoRef2, windows::ClassType::catchableTypeInfoRef2Suffix), + join(name, windows::ClassType::copyThunk2, windows::ClassType::copyThunk2Suffix)); + } + void setF32AsCatchType() { types.push_back({windows::F32Type::typeName, windows::F32Type::typeInfoRef, windows::F32Type::catchableTypeInfoRef, windows::F32Type::catchableTypeSize}); // Same catchableTypeSize as the primary entry, not pointerSize() - see the equivalent // comment in LLVMRTTIHelperVCWin32.h::setF32AsCatchType. - types.push_back({windows::F32Type::typeName2, windows::F32Type::typeInfoRef2, windows::F32Type::catchableTypeInfoRef2, - windows::F32Type::catchableTypeSize}); + types.push_back(boxEntry(windows::F32Type::catchableTypeInfoRef2, windows::F32Type::copyThunk2)); catchableTypeInfoArrayRef = windows::F32Type::catchableTypeInfoArrayRef; throwInfoRef = windows::F32Type::throwInfoRef; @@ -75,8 +112,7 @@ class MLIRRTTIHelperVCWin32 { types.push_back({windows::F64Type::typeName, windows::F64Type::typeInfoRef, windows::F64Type::catchableTypeInfoRef, windows::F64Type::catchableTypeSize}); - types.push_back({windows::F64Type::typeName2, windows::F64Type::typeInfoRef2, windows::F64Type::catchableTypeInfoRef2, - windows::F64Type::catchableTypeSize}); + types.push_back(boxEntry(windows::F64Type::catchableTypeInfoRef2, windows::F64Type::copyThunk2)); catchableTypeInfoArrayRef = windows::F64Type::catchableTypeInfoArrayRef; throwInfoRef = windows::F64Type::throwInfoRef; @@ -86,8 +122,13 @@ class MLIRRTTIHelperVCWin32 { types.push_back({windows::I32Type::typeName, windows::I32Type::typeInfoRef, windows::I32Type::catchableTypeInfoRef, windows::I32Type::catchableTypeSize}); - types.push_back({windows::I32Type::typeName2, windows::I32Type::typeInfoRef2, windows::I32Type::catchableTypeInfoRef2, - windows::I32Type::catchableTypeSize}); + types.push_back(boxEntry(windows::I32Type::catchableTypeInfoRef2, windows::I32Type::copyThunk2)); + + TypeNames toNumber{windows::I32Type::typeName3, windows::I32Type::typeInfoRef3, windows::I32Type::catchableTypeInfoRef3, + windows::F64Type::catchableTypeSize}; + toNumber.copyThunk = windows::I32Type::copyThunk3; + toNumber.copyThunkTarget = mlir_ts::NumberType::get(rewriter.getContext()); + types.push_back(toNumber); catchableTypeInfoArrayRef = windows::I32Type::catchableTypeInfoArrayRef; throwInfoRef = windows::I32Type::throwInfoRef; @@ -97,8 +138,7 @@ class MLIRRTTIHelperVCWin32 { types.push_back({windows::StringType::typeName, windows::StringType::typeInfoRef, windows::StringType::catchableTypeInfoRef, pointerSize()}); - types.push_back({windows::StringType::typeName2, windows::StringType::typeInfoRef2, windows::StringType::catchableTypeInfoRef2, - pointerSize()}); + types.push_back(boxEntry(windows::StringType::catchableTypeInfoRef2, windows::StringType::copyThunk2)); catchableTypeInfoArrayRef = windows::StringType::catchableTypeInfoArrayRef; throwInfoRef = windows::StringType::throwInfoRef; @@ -123,8 +163,7 @@ class MLIRRTTIHelperVCWin32 pointerSize()}); } - types.push_back({windows::ClassType::typeName2, windows::ClassType::typeInfoRef2, windows::ClassType::catchableTypeInfoRef2, - pointerSize()}); + types.push_back(classBoxEntry(names.front())); setClassThrowInfoNames(names.front()); } @@ -136,8 +175,7 @@ class MLIRRTTIHelperVCWin32 join(name, windows::ClassType::catchableTypeInfoRef, windows::ClassType::catchableTypeInfoRefSuffix), pointerSize()}); - types.push_back({windows::ClassType::typeName2, windows::ClassType::typeInfoRef2, windows::ClassType::catchableTypeInfoRef2, - pointerSize()}); + types.push_back(classBoxEntry(name)); setClassThrowInfoNames(name); } @@ -184,6 +222,8 @@ class MLIRRTTIHelperVCWin32 normalizedType = enumType.getElementType(); } + thrownType = normalizedType; + auto result = true; llvm::TypeSwitch(normalizedType) .Case([&](auto intType) { @@ -325,8 +365,11 @@ class MLIRRTTIHelperVCWin32 // __ImageBase imageBase(loc); - // _CT??_R0N@88 - catchableTypes(loc); + // _CT??_R0N@88 - and the copy thunks they name + if (mlir::failed(catchableTypes(loc))) + { + return false; + } // _CTA1N catchableArrayType(loc); @@ -463,19 +506,46 @@ class MLIRRTTIHelperVCWin32 { for (auto type : types) { - catchableType(loc, type.catchableTypeInfoRef, type.typeInfoRef, type.typeName, type.catchableTypeSize); + if (mlir::failed(catchableType(loc, type))) + { + return mlir::failure(); + } } return mlir::success(); } - mlir::LogicalResult catchableType(mlir::Location loc, StringRef catchableTypeInfoRefName, StringRef typeInfoRefName, StringRef typeName, - int catchableTypeSize) + mlir::LogicalResult catchableType(mlir::Location loc, const TypeNames &type) { + StringRef catchableTypeInfoRefName = type.catchableTypeInfoRef; + StringRef typeInfoRefName = type.typeInfoRef; + StringRef typeName = type.typeName; + auto catchableTypeSize = type.catchableTypeSize; + auto name = catchableTypeInfoRefName; if (parentModule.lookupSymbol(name)) { - return mlir::failure(); + // already emitted for an earlier throw or catch of the same type + return mlir::success(); + } + + auto hasCopyThunk = !type.copyThunk.empty(); + if (hasCopyThunk && !parentModule.lookupSymbol(type.copyThunk)) + { + if (!copyThunkBuilder || !thrownType) + { + // nothing here can build the conversion; the record still has to exist for the + // array that lists it, so it stays the plain copy it used to be + hasCopyThunk = false; + } + else + { + mlir::OpBuilder::InsertionGuard guard(rewriter); + if (mlir::failed(copyThunkBuilder(loc, type.copyThunk, thrownType, type.copyThunkTarget))) + { + return mlir::failure(); + } + } } // _CT??_R0N@88 @@ -489,7 +559,8 @@ class MLIRRTTIHelperVCWin32 // begin mlir::Value structVal = rewriter.create(loc, ehCatchableTypeTy); - auto itemValue1 = rewriter.create(loc, mth.getI32Type(), rewriter.getI32IntegerAttr(1)); + auto properties = hasCopyThunk ? windows::copyFunctionProperties : windows::simpleTypeProperties; + auto itemValue1 = rewriter.create(loc, mth.getI32Type(), rewriter.getI32IntegerAttr(properties)); setStructValue(loc, structVal, itemValue1, 0); // value 2 @@ -511,7 +582,19 @@ class MLIRRTTIHelperVCWin32 auto itemValue6 = rewriter.create(loc, mth.getI32Type(), rewriter.getI32IntegerAttr(catchableTypeSize)); setStructValue(loc, structVal, itemValue6, 5); - auto itemValue7 = rewriter.create(loc, mth.getI32Type(), rewriter.getI32IntegerAttr(0)); + // copyFunction + mlir::Value itemValue7; + if (hasCopyThunk) + { + auto thunkPtr = rewriter.create( + loc, mth.getOpaqueType(), mlir::FlatSymbolRefAttr::get(rewriter.getContext(), type.copyThunk)); + itemValue7 = ehReference(loc, thunkPtr); + } + else + { + itemValue7 = rewriter.create(loc, mth.getI32Type(), rewriter.getI32IntegerAttr(0)); + } + setStructValue(loc, structVal, itemValue7, 6); // end diff --git a/tslang/lib/TypeScript/LowerToAffineLoops.cpp b/tslang/lib/TypeScript/LowerToAffineLoops.cpp index 4f7733bbb..3d87fe935 100644 --- a/tslang/lib/TypeScript/LowerToAffineLoops.cpp +++ b/tslang/lib/TypeScript/LowerToAffineLoops.cpp @@ -1314,6 +1314,7 @@ struct TryOpLowering : public TsPattern // Pre-order, because `skip()` only prunes the regions still to come - a post-order walk // has already visited them by the time the callback sees the TryOp. Operation *catchOpPtr = nullptr; + mlir::Type catchVarType; auto visitorCatchContinue = [&](Operation *op) { if (op != tryOp.getOperation() && isa(op)) { @@ -1322,7 +1323,8 @@ struct TryOpLowering : public TsPattern if (auto catchOp = dyn_cast_or_null(op)) { - rttih.setType(cast(catchOp.getCatchArg().getType()).getElementType()); + catchVarType = cast(catchOp.getCatchArg().getType()).getElementType(); + rttih.setType(catchVarType); assert(!catchOpPtr); catchOpPtr = op; } @@ -1628,6 +1630,18 @@ struct TryOpLowering : public TsPattern ? (mlir::Value)rttih.typeInfoPtrValue(loc) : /*catch all*/ (mlir::Value)rewriter.create(loc, mth.getNullType()); + // `catch (e: number)` has to take `throw 1` too - an integer literal is an int here. On + // Windows the int's ThrowInfo lists a `.N` entry that converts it (see copyThunkPrefix in + // LLVMRTTIHelperVCWin32Const.h); on the Itanium path the catch lists the int type_info as + // a second clause, accepts either, and linux::SaveCatchVarOpLowering converts. + mlir::Value intTypeInfo; + if (!tsContext->compileOptions.isWindows && catchVarType && isa(catchVarType)) + { + intTypeInfo = rewriter.create( + loc, mth.getRefType(mth.getOpaqueType()), + mlir::FlatSymbolRefAttr::get(rewriter.getContext(), ::typescript::linux::I32Type::typeName)); + } + // A cleanup-only try (a `using` scope) nested inside another try in the same function // has to hand the exception on to that enclosing landing pad once it has disposed, and // on the Itanium path that is done by rethrowing rather than resuming - see the @@ -1709,12 +1723,18 @@ struct TryOpLowering : public TsPattern } mlir::Value cmpValue; + mlir::Value cmpIntValue; if (catchHasOps) { // catches:landingpad rewriter.setInsertionPointToStart(linuxHasCleanups ? cleanupBlock : catchesBlock); SmallVector catchTypes{catch1}; + if (intTypeInfo) + { + catchTypes.push_back(intTypeInfo); + } + if (linuxHasCleanups && rttih.hasType() || linuxTypedCatchChains) { // we need to catch all exceptions for cleanup code @@ -1750,6 +1770,11 @@ struct TryOpLowering : public TsPattern cmpValue = rewriter.create(loc, mth.getBooleanType(), landingPadOp, rttih.throwInfoPtrValue(loc)); + if (intTypeInfo) + { + cmpIntValue = + rewriter.create(loc, mth.getBooleanType(), landingPadOp, intTypeInfo); + } } // catch: begin catch @@ -1889,7 +1914,8 @@ struct TryOpLowering : public TsPattern if (cmpValue) { // condbr - rewriter.setInsertionPointAfterValue(cmpValue); + auto lastCmpValue = cmpIntValue ? cmpIntValue : cmpValue; + rewriter.setInsertionPointAfterValue(lastCmpValue); mlir::Block *currentBlockBrCmp = rewriter.getInsertionBlock(); mlir::Block *continuationBrCmp = rewriter.splitBlock(currentBlockBrCmp, rewriter.getInsertionPoint()); @@ -1924,8 +1950,15 @@ struct TryOpLowering : public TsPattern tsContext->unwind[rethrowOp] = parentTryOpLandingPad; } - rewriter.setInsertionPointAfterValue(cmpValue); - auto castToI1 = rewriter.create(loc, rewriter.getI1Type(), cmpValue); + rewriter.setInsertionPointAfterValue(lastCmpValue); + mlir::Value castToI1 = rewriter.create(loc, rewriter.getI1Type(), cmpValue); + if (cmpIntValue) + { + auto intToI1 = rewriter.create(loc, rewriter.getI1Type(), cmpIntValue); + castToI1 = rewriter.create( + loc, rewriter.getI1Type(), rewriter.getI32IntegerAttr((int)SyntaxKind::BarToken), castToI1, intToI1); + } + rewriter.create(loc, castToI1, continuationBrCmp, rethrowBlock); // end of condbr } diff --git a/tslang/lib/TypeScript/LowerToLLVM.cpp b/tslang/lib/TypeScript/LowerToLLVM.cpp index bbb391400..4cda19283 100644 --- a/tslang/lib/TypeScript/LowerToLLVM.cpp +++ b/tslang/lib/TypeScript/LowerToLLVM.cpp @@ -5016,7 +5016,15 @@ struct SaveCatchVarOpLowering : public TsLlvmPattern auto llvmCatchType = getTypeConverter()->convertType(catchType); mlir::Value catchVal; - if (!isa(llvmCatchType)) + if (isa(catchType)) + { + catchVal = boxCaughtException(saveCatchVarOp, transformed.getExceptionInfo(), rewriter); + } + else if (isa(catchType)) + { + catchVal = loadCaughtNumber(saveCatchVarOp, transformed.getExceptionInfo(), llvmCatchType, rewriter); + } + else if (!isa(llvmCatchType)) { auto ptrVal = rewriter.create(loc, th.getPtrType(), transformed.getExceptionInfo()); @@ -5031,6 +5039,119 @@ struct SaveCatchVarOpLowering : public TsLlvmPattern return success(); } + + // A `catch (e: number)` also catches a thrown int (TryOpLowering lists its type_info as a + // second clause), which has to be widened rather than read as a double. + mlir::Value loadCaughtNumber(mlir_ts::SaveCatchVarOp saveCatchVarOp, mlir::Value exceptionInfo, mlir::Type llvmNumberType, + ConversionPatternRewriter &rewriter) const + { + auto loc = saveCatchVarOp.getLoc(); + + TypeHelper th(rewriter); + LLVMCodeHelper ch(saveCatchVarOp, rewriter, getTypeConverter(), tsLlvmContext->compileOptions); + CodeLogicHelper clh(saveCatchVarOp, rewriter); + + auto ptrTy = th.getPtrType(); + auto typeFunc = ch.getOrInsertFunction("__cxa_current_exception_type", th.getFunctionType(ptrTy, ArrayRef{})); + auto typeInfo = rewriter.create(loc, typeFunc, ValueRange{}).getResult(); + auto intTypeInfo = rewriter.create(loc, ptrTy, ::typescript::linux::I32Type::typeName); + auto isInt = rewriter.create(loc, LLVM::ICmpPredicate::eq, typeInfo, intTypeInfo); + + return clh.conditionalExpressionLowering( + loc, llvmNumberType, isInt, + [&](OpBuilder &, Location) -> mlir::Value { + auto intValue = rewriter.create(loc, th.getI32Type(), exceptionInfo); + return rewriter.create(loc, llvmNumberType, intValue); + }, + [&](OpBuilder &, Location) -> mlir::Value { + return rewriter.create(loc, llvmNumberType, exceptionInfo); + }); + } + + // The value an untyped `catch (e)` / `catch (e: any)` binds, boxed into an `any`. Such a + // catch is a catch-all, so the exception's type is only known at run time: compare its + // type_info with each type tslang throws and box the thrown object accordingly. + // `exceptionInfo` is __cxa_begin_catch's result, which for a catch-all is the address of + // the thrown object. (The Win64 equivalent is done by the CRT, through the copy thunks in + // the `.PEAX` CatchableType records - see copyThunkPrefix in LLVMRTTIHelperVCWin32Const.h.) + mlir::Value boxCaughtException(mlir_ts::SaveCatchVarOp saveCatchVarOp, mlir::Value exceptionInfo, + ConversionPatternRewriter &rewriter) const + { + auto loc = saveCatchVarOp.getLoc(); + auto &compileOptions = tsLlvmContext->compileOptions; + + TypeHelper th(rewriter); + TypeConverterHelper tch(getTypeConverter()); + LLVMCodeHelper ch(saveCatchVarOp, rewriter, getTypeConverter(), compileOptions); + CodeLogicHelper clh(saveCatchVarOp, rewriter); + + auto ptrTy = th.getPtrType(); + auto ctx = rewriter.getContext(); + + auto typeFuncName = "__cxa_current_exception_type"; + auto typeFunc = ch.getOrInsertFunction(typeFuncName, th.getFunctionType(ptrTy, ArrayRef{})); + auto typeInfo = rewriter.create(loc, typeFunc, ValueRange{}).getResult(); + + auto isThrownType = [&](const char *typeInfoName) -> mlir::Value { + auto typeInfoAddress = rewriter.create(loc, ptrTy, typeInfoName); + return rewriter.create(loc, LLVM::ICmpPredicate::eq, typeInfo, typeInfoAddress); + }; + + auto boxThrown = [&](mlir::Type type) -> mlir::Value { + auto llvmType = tch.convertType(type); + auto value = rewriter.create(loc, llvmType, exceptionInfo); + TypeOfOpHelper toh(rewriter); + auto boxed = rewriter.create(loc, mlir_ts::AnyType::get(ctx), value, toh.typeOfLogic(loc, type)); + return rewriter.create(loc, ptrTy, boxed); + }; + + // each type tslang throws, by the type_info a throw of it carries + SmallVector> candidates{ + {::typescript::linux::I32Type::typeName, mlir::IntegerType::get(ctx, 32, mlir::IntegerType::Signed)}, + {::typescript::linux::F64Type::typeName, mlir_ts::NumberType::get(ctx)}, + {::typescript::linux::StringType::typeName, mlir_ts::StringType::get(ctx)}, + // a thrown `any` is already a box + {::typescript::linux::I8PtrType::typeName, mlir_ts::AnyType::get(ctx)}}; + + // A class needs its own type descriptor in the box - unboxing checks for a class tag, + // and the descriptor carries the class's release routine - so only the classes this + // module throws can be recognised (MLIRGen lists them, see recordThrownClass). A class + // thrown from another module falls through to the plain-object box below. + if (auto thrownClasses = saveCatchVarOp->getParentOfType()->getAttrOfType( + THROWN_CLASSES_ATTR_NAME)) + { + for (auto thrownClass : thrownClasses.getAsValueRange()) + { + auto classType = cast(thrownClass); + auto name = classType.getName().getValue(); + std::string typeInfoName = "_ZTIP" + std::to_string(name.size()) + name.str(); + candidates.push_back({typeInfoName, classType}); + } + } + + std::function dispatch = [&](size_t index) -> mlir::Value { + if (index == candidates.size()) + { + // not a type tslang throws from this module; box the pointer as a plain object + return boxThrown(mlir_ts::OpaqueType::get(ctx)); + } + + auto [typeInfoName, type] = candidates[index]; + return clh.conditionalExpressionLowering( + loc, ptrTy, isThrownType(typeInfoName.c_str()), + [&, type = type](OpBuilder &, Location) -> mlir::Value { + if (isa(type)) + { + return rewriter.create(loc, ptrTy, exceptionInfo); + } + + return boxThrown(type); + }, + [&, index = index](OpBuilder &, Location) { return dispatch(index + 1); }); + }; + + return dispatch(0); + } }; struct EndCatchOpLowering : public TsLlvmPattern diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index dcf944a23..d5b399ee5 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -92,6 +92,8 @@ void setCompileOptions(CompileOptions &compileOptions); namespace typescript { +class MLIRRTTIHelperVC; + namespace mlirgen { @@ -2993,6 +2995,12 @@ class MLIRGenImpl const GenContext &genContext, int firstParam = 0, bool isPublic = false); + mlir::LogicalResult mlirGenCatchCopyThunk(mlir::Location location, StringRef name, mlir::Type source, mlir::Type target); + + void setCatchCopyThunkBuilder(MLIRRTTIHelperVC &rtti); + + void recordThrownClass(mlir::Type thrownType); + ValueOrLogicalResult mlirGen(TypeAssertion typeAssertionAST, const GenContext &genContext); ValueOrLogicalResult mlirGen(AsExpression asExpressionAST, const GenContext &genContext); diff --git a/tslang/lib/TypeScript/MLIRGenStatements.cpp b/tslang/lib/TypeScript/MLIRGenStatements.cpp index 6be91ff70..9413c8c28 100644 --- a/tslang/lib/TypeScript/MLIRGenStatements.cpp +++ b/tslang/lib/TypeScript/MLIRGenStatements.cpp @@ -1046,6 +1046,88 @@ namespace mlirgen return mlir::success(); } + // void name(ref dest, ref src) { *dest = *src; } - the copy function + // of a Windows CatchableType, which the CRT calls to build a catch variable of a different + // shape from the thrown value. See copyThunkPrefix in LLVMRTTIHelperVCWin32Const.h. + mlir::LogicalResult MLIRGenImpl::mlirGenCatchCopyThunk(mlir::Location location, StringRef name, mlir::Type source, + mlir::Type target) + { + if (theModule.lookupSymbol(name)) + { + return mlir::success(); + } + + mlir::OpBuilder::InsertionGuard guard(builder); + + auto funcType = getFunctionType({mlir_ts::RefType::get(target), mlir_ts::RefType::get(source)}, {}, false); + + // Built directly rather than through mlirGenFunctionBody: a throw is usually generated + // from inside another function, whose own return variable that helper would find in the + // symbol table and wire into this thunk's exit. + auto funcOp = mlir_ts::FuncOp::create(location, name, funcType); + funcOp.setPrivate(); + + // its own context: the thunk is a function of its own, and has to be emitted even when + // the throw or catch that needs it is only being generated speculatively + GenContext thunkGenContext{}; + thunkGenContext.funcOp = funcOp; + + auto &entryBlock = *funcOp.addEntryBlock(); + builder.setInsertionPointToStart(&entryBlock); + + // no return value: the Entry/Exit pair every function body is lowered from + builder.create(location, mlir::Type()); + + auto arguments = entryBlock.getArguments(); + auto value = builder.create(location, source, arguments[1]); + auto result = cast(location, target, value, thunkGenContext); + if (result.failed_or_no_value()) + { + funcOp.erase(); + return mlir::failure(); + } + + builder.create(location, V(result), arguments[0]); + builder.create(location, mlir::Value()); + + theModule.push_back(funcOp); + return mlir::success(); + } + + void MLIRGenImpl::setCatchCopyThunkBuilder(MLIRRTTIHelperVC &rtti) + { + rtti.setCopyThunkBuilder([&](mlir::Location location, StringRef name, mlir::Type source, mlir::Type target) { + return mlirGenCatchCopyThunk(location, name, source, target); + }); + } + + // An untyped catch on the Itanium path is a catch-all that finds out what it caught from the + // exception's type_info, and a class needs its own descriptor in the `any` box it binds - so + // the lowering needs to know which classes can arrive. See linux::SaveCatchVarOpLowering. + void MLIRGenImpl::recordThrownClass(mlir::Type thrownType) + { + auto classType = dyn_cast(mth.stripLiteralType(thrownType)); + if (!classType) + { + return; + } + + SmallVector thrownClasses; + if (auto existing = theModule->getAttrOfType(THROWN_CLASSES_ATTR_NAME)) + { + thrownClasses.append(existing.begin(), existing.end()); + } + + auto classTypeAttr = mlir::TypeAttr::get(classType); + if (llvm::is_contained(thrownClasses, classTypeAttr)) + { + return; + } + + thrownClasses.push_back(classTypeAttr); + theModule->setAttr(THROWN_CLASSES_ATTR_NAME, builder.getArrayAttr(thrownClasses)); + } + mlir::LogicalResult MLIRGenImpl::mlirGen(ThrowStatement throwStatementAST, const GenContext &genContext) { auto location = loc(throwStatementAST); @@ -1059,6 +1141,7 @@ namespace mlirgen if (!genContext.allowPartialResolve) { MLIRRTTIHelperVC rtti(builder, theModule, compileOptions); + setCatchCopyThunkBuilder(rtti); if (!rtti.setRTTIForType( location, exception.getType(), [&](StringRef classFullName) { return getClassInfoByFullName(classFullName); })) @@ -1066,6 +1149,11 @@ namespace mlirgen emitError(location, "Not supported type in throw"); return mlir::failure(); } + + if (!compileOptions.isWindows) + { + recordThrownClass(exception.getType()); + } } return mlir::success(); @@ -1168,6 +1256,7 @@ namespace mlirgen if (!genContext.allowPartialResolve) { MLIRRTTIHelperVC rtti(builder, theModule, compileOptions); + setCatchCopyThunkBuilder(rtti); if (!rtti.setRTTIForType( location, varInfo.getType(), diff --git a/tslang/lib/TypeScriptExceptionPass/CxxThrowCallingConvPass.cpp b/tslang/lib/TypeScriptExceptionPass/CxxThrowCallingConvPass.cpp index 80271d8a2..279c21795 100644 --- a/tslang/lib/TypeScriptExceptionPass/CxxThrowCallingConvPass.cpp +++ b/tslang/lib/TypeScriptExceptionPass/CxxThrowCallingConvPass.cpp @@ -1,4 +1,5 @@ #include "TypeScript/Pass/CxxThrowCallingConvPass.h" +#include "TypeScript/LowerToLLVM/LLVMRTTIHelperVCWin32Const.h" #include "llvm/IR/InstrTypes.h" #include "llvm/IR/Module.h" @@ -12,10 +13,24 @@ namespace ts { llvm::PreservedAnalyses CxxThrowCallingConvPass::run(llvm::Module &M, llvm::ModuleAnalysisManager &AM) { + auto changed = false; + + // The CRT calls a CatchableType's copy function as a member function - `__thiscall` on + // x86: the catch variable in ECX, the thrown object on the stack. Nothing in the module + // calls these thunks; the EH tables only hold their addresses. + for (auto &F : M) + { + if (F.getName().starts_with(typescript::windows::copyThunkPrefix)) + { + F.setCallingConv(CallingConv::X86_ThisCall); + changed = true; + } + } + auto *throwFn = M.getFunction("_CxxThrowException"); if (!throwFn) { - return llvm::PreservedAnalyses::all(); + return changed ? llvm::PreservedAnalyses::none() : llvm::PreservedAnalyses::all(); } throwFn->setCallingConv(CallingConv::X86_StdCall); diff --git a/tslang/test/check-x86-eh.sh b/tslang/test/check-x86-eh.sh index b5ffdbac8..31a6352b3 100755 --- a/tslang/test/check-x86-eh.sh +++ b/tslang/test/check-x86-eh.sh @@ -59,7 +59,7 @@ if "$TSLANG" --emit=obj --opt -mm=none --no-default-lib -mtriple=i686-pc-windows "$READOBJ" --relocations "$x86obj" > "$x86obj.rel" grep -q "DIR32NB" "$x86obj.rel" && bad "x86 obj: no image-relative (DIR32NB) relocations" \ || ok "x86 obj: no image-relative (DIR32NB) relocations" - grep -Eq "IMAGE_REL_I386_DIR32 __CTA1H " "$x86obj.rel" && ok "x86 obj: absolute (DIR32) EH relocations" \ + grep -Eq "IMAGE_REL_I386_DIR32 __CTA3H " "$x86obj.rel" && ok "x86 obj: absolute (DIR32) EH relocations" \ || bad "x86 obj: absolute (DIR32) EH relocations" else bad "x86 obj: 00try_catch compiles"; cat "$x86obj.err" diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 8b64a0870..1a33dcabd 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -388,12 +388,8 @@ tslang_add_test(NAME test-compile-00-try-using-catch COMMAND test-runner "${PROJ tslang_add_test(NAME test-compile-00-throw-in-catch COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00throw_in_catch.ts") tslang_add_test(NAME test-compile-00-throw-inlined COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00throw_inlined.ts") tslang_add_test(NAME test-compile-00-try-catch-sequence-and-nesting COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_catch_sequence_and_nesting.ts") -# Windows only: the fix this pins down is in the Win32 RTTI tables. On Linux an untyped catch -# still does not match a thrown number (the clause is a void* pointer type, which the Itanium ABI -# matches only against pointer exceptions), so this test fails there. See the Linux catch issue. -if (WIN32) tslang_add_test(NAME test-compile-00-throw-number-untyped-catch COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00throw_number_untyped_catch.ts") -endif() +tslang_add_test(NAME test-compile-00-catch-untyped-value COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00catch_untyped_value.ts") tslang_add_test(NAME test-compile-00-using-nested-scopes COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00using_nested_scopes.ts") tslang_add_test(NAME test-compile-00-using-unwind-progress COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00using_unwind_progress.ts") tslang_add_test(NAME test-compile-00-break-continue-scope-exit COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00break_continue_scope_exit.ts") @@ -817,10 +813,8 @@ tslang_add_test(NAME test-jit-00-owned-locals COMMAND test-runner -jit "${PROJEC tslang_add_test(NAME test-jit-00-throw-in-catch COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00throw_in_catch.ts") tslang_add_test(NAME test-jit-00-throw-inlined COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00throw_inlined.ts") tslang_add_test(NAME test-jit-00-try-catch-sequence-and-nesting COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_catch_sequence_and_nesting.ts") -# Windows only, for the reason given at the compile registration above. -if (WIN32) tslang_add_test(NAME test-jit-00-throw-number-untyped-catch COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00throw_number_untyped_catch.ts") -endif() +tslang_add_test(NAME test-jit-00-catch-untyped-value COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00catch_untyped_value.ts") tslang_add_test(NAME test-jit-00-using-nested-scopes COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00using_nested_scopes.ts") tslang_add_test(NAME test-jit-00-using-unwind-progress COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00using_unwind_progress.ts") tslang_add_test(NAME test-jit-00-break-continue-scope-exit COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00break_continue_scope_exit.ts") @@ -1504,6 +1498,7 @@ set(TSLANG_CORPUS 00break_continue_scope_exit.ts 00break_continue.ts 00capture_in_new_arguments.ts + 00catch_untyped_value.ts 00catch_value.ts 00catch_value_minimal.ts 00class_abstract.ts @@ -2014,14 +2009,6 @@ set(TSLANG_CORPUS_BROKEN_AOT_RC set(TSLANG_CORPUS_BROKEN_AOT_NONE ) -# Windows-only corpus entries. 00throw_number_untyped_catch.ts pins down a Win32 RTTI fix; the -# same bug is still open on Linux (an untyped catch's clause is a void* pointer type there, which -# the Itanium ABI matches only against pointer exceptions), so the file would fail its rc/none -# corpus variants on Linux. Its explicit registrations are guarded the same way. -if (NOT WIN32) - list(REMOVE_ITEM TSLANG_CORPUS 00throw_number_untyped_catch.ts) -endif() - foreach(corpus_file ${TSLANG_CORPUS}) string(REGEX REPLACE "\\.ts$" "" corpus_slug "${corpus_file}") string(REGEX REPLACE "[_.]" "-" corpus_slug "${corpus_slug}") diff --git a/tslang/test/tester/tests/00catch_untyped_value.ts b/tslang/test/tester/tests/00catch_untyped_value.ts new file mode 100644 index 000000000..9cf795d2e --- /dev/null +++ b/tslang/test/tester/tests/00catch_untyped_value.ts @@ -0,0 +1,147 @@ +// Reading the value an untyped `catch (e)` or a `catch (e: any)` binds. +// +// Such a catch binds an `any`, but a thrown number, string or class instance is not one, and the +// catch variable used to receive the raw value: the first read of it as an `any` crashed, even +// for `throw "message"`. Now the value is boxed on its way in: +// - Windows: the thrown value's `.PEAX` CatchableType names a copy function that boxes it, and +// the CRT calls that instead of copying bytes (copyThunkPrefix, LLVMRTTIHelperVCWin32Const.h); +// - Linux: the catch is a real catch-all, and binding it compares the exception's type_info with +// each type tslang throws (linux::SaveCatchVarOpLowering). The `_ZTIPv` clause it used was not +// a catch-all at all, so a thrown number was never caught. +// +// Also here: `catch (e: number)` takes `throw 1`. An integer literal is an int, so the int's +// throw lists a converting entry for `.N` on Windows, and the catch lists the int type_info on +// Linux. + +class Failure { + code = 42; +} + +class Derived extends Failure { + extra = 1; +} + +function untypedNumber() { + let r: number = 0; + try { + throw 2.5; + } catch (e) { + r = e; + } + + return r; +} + +function untypedInt() { + let r = 0; + try { + throw 7; + } catch (e) { + r = e; + } + + return r; +} + +function untypedString() { + let r = ""; + try { + throw "boom"; + } catch (e) { + r = e; + } + + return r; +} + +function untypedClass() { + let r = 0; + try { + throw new Failure(); + } catch (e) { + r = (e).code; + } + + return r; +} + +function untypedDerivedAsBase() { + let r = 0; + try { + throw new Derived(); + } catch (e) { + r = (e).code + (e).extra; + } + + return r; +} + +function anyTyped() { + let r = 0; + try { + throw 11; + } catch (e: any) { + r = e; + } + + return r; +} + +function alreadyAny() { + let r = 0; + try { + throw 123; + } catch (e) { + r = e; + } + + return r; +} + +function numberCatchesInt() { + let r: number = 0; + try { + throw 5; + } catch (e: number) { + r = e + 0.5; + } + + return r; +} + +function typedCatchesUnchanged() { + let sum: number = 0; + try { + throw 3; + } catch (e: int) { + sum += e; + } + + try { + throw 1.5; + } catch (e: number) { + sum += e * 2; + } + + try { + throw "x"; + } catch (e: string) { + sum += e == "x" ? 10 : 0; + } + + return sum; +} + +function main() { + assert(untypedNumber() == 2.5, "an untyped catch reads a thrown number"); + assert(untypedInt() == 7, "an untyped catch reads a thrown int"); + assert(untypedString() == "boom", "an untyped catch reads a thrown string"); + assert(untypedClass() == 42, "an untyped catch reads a thrown class instance"); + assert(untypedDerivedAsBase() == 43, "an untyped catch reads a thrown derived instance as either class"); + assert(anyTyped() == 11, "a catch (e: any) reads a thrown int"); + assert(alreadyAny() == 123, "a thrown any is bound as it is"); + assert(numberCatchesInt() == 5.5, "catch (e: number) catches a thrown integer literal"); + assert(typedCatchesUnchanged() == 16, "typed catches still bind their own types"); + + print("done."); +} diff --git a/tslang/test/tester/tests/00throw_number_untyped_catch.ts b/tslang/test/tester/tests/00throw_number_untyped_catch.ts index 08b43e435..9a07468f4 100644 --- a/tslang/test/tester/tests/00throw_number_untyped_catch.ts +++ b/tslang/test/tester/tests/00throw_number_untyped_catch.ts @@ -11,10 +11,9 @@ // generic filter never found a match, __CxxFrameHandler3 walked past `main` with nothing left // to catch it, and the process quietly ended instead of running the catch body. // -// Do NOT assert on the caught value here - see 00catch_value.ts's note (item 5am) on why -// reading a `catch` binding is a separate, already-tracked, back-end-dependent question. This -// file only asserts control flow: the catch body runs, and the statement after the try/catch -// still runs too. +// This file asserts control flow only: the catch body runs, and the statement after the +// try/catch still runs too. Reading the caught value is 00catch_untyped_value.ts. On Linux the +// same catch used a `void*` clause, which never matches a number; it is a catch-all now. function untypedCatchesInt() { let ran = 0;