Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions tslang/include/TypeScript/LowerToLLVM/LLVMRTTIHelperVCWin32.h
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,9 @@ class LLVMRTTIHelperVCWin32

types.push_back({ClassType::typeName2, ClassType::typeInfoRef2, ClassType::catchableTypeInfoRef2, pointerSize()});

catchableTypeInfoArrayRef = ClassType::catchableTypeInfoArrayRef;
throwInfoRef = ClassType::throwInfoRef;
// per class, not shared - see MLIRRTTIHelperVCWin32::setClassThrowInfoNames
catchableTypeInfoArrayRef = join(name, ClassType::catchableTypeInfoArrayRef, ClassType::catchableTypeInfoArrayRefSuffix);
throwInfoRef = join(name, ClassType::throwInfoRef, ClassType::throwInfoRefSuffix);
}

// A pointer-shaped catchable type (a string, an opaque pointer, a class reference) is as
Expand Down
22 changes: 19 additions & 3 deletions tslang/include/TypeScript/LowerToLLVM/ThrowLogic.h
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,16 @@ class ThrowLogic

auto i8PtrTy = th.getPtrType();

// a `null` operand is a rethrow of the exception being handled: _CxxThrowException(0, 0)
auto isRethrow = isa<mlir_ts::NullType>(exceptionType);

// variable
mlir::Value value;
if (isRethrow)
{
value = rewriter.create<LLVM::ZeroOp>(loc, i8PtrTy);
}
else
{
OpBuilder::InsertionGuard guard(rewriter);

Expand All @@ -84,10 +92,18 @@ class ThrowLogic
value = rewriter.create<mlir_ts::DialectCastOp>(loc, typeConverter->convertType(value.getType()), value);
}

rewriter.create<mlir_ts::StoreOp>(loc, exceptionValue, value);
mlir::Value throwInfoPtr;
if (isRethrow)
{
throwInfoPtr = rewriter.create<LLVM::ZeroOp>(loc, throwInfoPtrTy);
}
else
{
rewriter.create<mlir_ts::StoreOp>(loc, exceptionValue, value);

// throw
auto throwInfoPtr = rttih.throwInfoPtrValue(loc);
// throw
throwInfoPtr = rttih.throwInfoPtrValue(loc);
}

auto throwFuncName = "_CxxThrowException";
auto cxxThrowException = ch.getOrInsertFunction(throwFuncName, th.getFunctionType(th.getVoidType(), {i8PtrTy, throwInfoPtrTy}));
Expand Down
19 changes: 15 additions & 4 deletions tslang/include/TypeScript/MLIRLogic/MLIRRTTIHelperVCWin32.h
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,7 @@ class MLIRRTTIHelperVCWin32
types.push_back({windows::ClassType::typeName2, windows::ClassType::typeInfoRef2, windows::ClassType::catchableTypeInfoRef2,
pointerSize()});

catchableTypeInfoArrayRef = windows::ClassType::catchableTypeInfoArrayRef;
throwInfoRef = windows::ClassType::throwInfoRef;
setClassThrowInfoNames(names.front());
}

void setClassTypeAsCatchType(StringRef name)
Expand All @@ -140,8 +139,20 @@ class MLIRRTTIHelperVCWin32
types.push_back({windows::ClassType::typeName2, windows::ClassType::typeInfoRef2, windows::ClassType::catchableTypeInfoRef2,
pointerSize()});

catchableTypeInfoArrayRef = windows::ClassType::catchableTypeInfoArrayRef;
throwInfoRef = windows::ClassType::throwInfoRef;
setClassThrowInfoNames(name);
}

// Each class needs its own CatchableTypeArray and ThrowInfo: they list that class's own
// descriptors (and its bases'), and both are linkonce_odr globals keyed only by name. A
// shared name let the first class a module threw fix the descriptors for every other class
// thrown from it - `throw new B()` then went out as an `A`, and `catch (e: B)` never matched.
// Must agree with LLVMRTTIHelperVCWin32::setClassTypeAsCatchType, which names the ThrowInfo
// a throw site passes to _CxxThrowException.
void setClassThrowInfoNames(StringRef name)
{
catchableTypeInfoArrayRef =
join(name, windows::ClassType::catchableTypeInfoArrayRef, windows::ClassType::catchableTypeInfoArrayRefSuffix);
throwInfoRef = join(name, windows::ClassType::throwInfoRef, windows::ClassType::throwInfoRefSuffix);
}

// A pointer-shaped catchable type (a string, an opaque pointer, a class reference) is as
Expand Down
5 changes: 5 additions & 0 deletions tslang/include/TypeScript/TypeScriptPassContext.h
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ struct TSContext
unwind.beginRun();
cleanup.beginRun();
parentTryOp.beginRun();
inParentTryBody.beginRun();
landingBlockOf.beginRun();
leavesCatch.beginRun();
}
Expand All @@ -138,6 +139,10 @@ struct TSContext
OpSideTable<mlir::Block *> unwind{"unwind"};
OpSideTable<mlir::Block *> cleanup{"cleanup"};
OpSideTable<Operation *> parentTryOp{"parentTryOp"};
// Whether a try sits in its parentTryOp's *body*, where an exception leaving it is the
// parent's to catch - as opposed to the parent's catch or finally, where unwinding to the
// parent's landing pad would loop back into the handler it is already running.
OpSideTable<bool> inParentTryBody{"inParentTryBody"};
OpSideTable<mlir::Block *> landingBlockOf{"landingBlockOf"};
// Throws that sit inside a catch clause and therefore have to end the active catch before
// they leave it. `return`, `break` and `continue` carry the same meaning in `unwind`, but
Expand Down
60 changes: 56 additions & 4 deletions tslang/lib/TypeScript/LowerToAffineLoops.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1296,6 +1296,7 @@ struct TryOpLowering : public TsPattern<mlir_ts::TryOp>
auto module = tryOp->getParentOfType<mlir::ModuleOp>();
auto parentTryOp = tsContext->parentTryOp.lookup(tryOp.getOperation());
mlir::Block *parentTryOpLandingPad = parentTryOp ? tsContext->landingBlockOf.lookup(parentTryOp) : nullptr;
auto parentCatchesThis = parentTryOpLandingPad && tsContext->inParentTryBody.lookup(tryOp.getOperation());

MLIRRTTIHelperVC rttih(rewriter, module, tsContext->compileOptions);
auto i8PtrTy = mth.getOpaqueType();
Expand Down Expand Up @@ -1331,13 +1332,17 @@ struct TryOpLowering : public TsPattern<mlir_ts::TryOp>
tryOp.getCatches().walk<mlir::WalkOrder::PreOrder>(visitorCatchContinue);

// set TryOp -> child TryOp
auto inBody = false;
auto visitorTryOps = [&](Operation *op) {
if (auto childTryOp = dyn_cast_or_null<mlir_ts::TryOp>(op))
{
tsContext->parentTryOp[op] = tryOp.getOperation();
tsContext->inParentTryBody[op] = inBody;
}
};
inBody = true;
tryOp.getBody().walk(visitorTryOps);
inBody = false;
tryOp.getCatches().walk(visitorTryOps);
tryOp.getFinally().walk(visitorTryOps);

Expand Down Expand Up @@ -1495,6 +1500,7 @@ struct TryOpLowering : public TsPattern<mlir_ts::TryOp>
if (auto parent = tsContext->parentTryOp.lookup(oldOp))
{
tsContext->parentTryOp[newOp] = parent;
tsContext->inParentTryBody[newOp] = tsContext->inParentTryBody.lookup(oldOp);
}
}
};
Expand Down Expand Up @@ -1630,9 +1636,20 @@ struct TryOpLowering : public TsPattern<mlir_ts::TryOp>
auto linuxCleanupOnlyChainsToParent =
linuxHasCleanups && !catchHasOps && !finallyHasOps && parentTryOpLandingPad;

// A typed catch whose exception may belong to someone else in this same function - the
// try's own finally, or the try around it - has to be entered for every exception, not
// only a matching one. An Itanium landingpad that lists just the typed clause is skipped
// by the personality for any other type, and since nothing in this frame unwinds to the
// finally or the enclosing try's pad, the exception is not handled here at all:
// std::terminate. So add a catch-all clause, and let the mismatch path below rethrow to
// where the exception belongs (the same catch-all-and-rethrow the nested finally and
// cleanup cases here already use). linuxHasCleanups adds the clause on its own.
auto linuxTypedCatchChains = !tsContext->compileOptions.isWindows && catchHasOps && rttih.hasType() &&
!linuxHasCleanups && (parentCatchesThis || finallyHasOps);

mlir::Value catchAll;
if (parentTryOpLandingPad && finallyHasOps || linuxHasCleanups && rttih.hasType() ||
linuxCleanupOnlyChainsToParent)
linuxCleanupOnlyChainsToParent || linuxTypedCatchChains)
{
catchAll = (mlir::Value)rewriter.create<mlir_ts::NullOp>(loc, mth.getNullType());
}
Expand Down Expand Up @@ -1698,7 +1715,7 @@ struct TryOpLowering : public TsPattern<mlir_ts::TryOp>
rewriter.setInsertionPointToStart(linuxHasCleanups ? cleanupBlock : catchesBlock);

SmallVector<mlir::Value> catchTypes{catch1};
if (linuxHasCleanups && rttih.hasType())
if (linuxHasCleanups && rttih.hasType() || linuxTypedCatchChains)
{
// we need to catch all exceptions for cleanup code
catchTypes.push_back(catchAll);
Expand All @@ -1707,7 +1724,23 @@ struct TryOpLowering : public TsPattern<mlir_ts::TryOp>
auto landingPadOp = rewriter.create<mlir_ts::LandingPadOp>(loc, rttih.getLandingPadType(),
rewriter.getBoolAttr(false), catchTypes);

if (!tsContext->compileOptions.isWindows && rttih.hasType())
// On Windows a typed catch that does not match is left by the runtime, through the
// catchswitch's unwind edge - but Win32ExceptionPass can only point that edge at the
// enclosing try's pad if something inside the catch region already unwinds there.
// A catch body with no call has nothing that does, so the enclosing pad has no
// predecessor left, is deleted as unreachable, and an exception the outer try was
// meant to catch leaves the function instead. The mismatch rethrow below is that
// edge: CompareCatchTypeOp is always true on Windows (the filter has already
// matched by the time the catch body runs), so the rethrow never executes, but it
// keeps the enclosing pad alive until the funclet pass has wired it up.
//
// The same goes for this try's own `finally`, which a mismatched exception has to
// run on its way out: without the edge the catchswitch unwinds straight past it.
//
// Only a try in its parent's body has an edge to add (parentCatchesThis): one in the
// parent's catch or finally is already inside the handler that pad leads to.
auto windowsNeedsParentEdge = tsContext->compileOptions.isWindows && (parentCatchesThis || finallyHasOps);
if (rttih.hasType() && (!tsContext->compileOptions.isWindows || windowsNeedsParentEdge))
{
if (linuxHasCleanups)
{
Expand Down Expand Up @@ -1865,9 +1898,28 @@ struct TryOpLowering : public TsPattern<mlir_ts::TryOp>
// instead of falling through to normal post-try control flow.
auto *rethrowBlock = rewriter.createBlock(continuationBrCmp);
rewriter.setInsertionPointToStart(rethrowBlock);
if (linuxTypedCatchChains)
{
// __cxa_rethrow needs the exception to have been caught first
rewriter.create<mlir_ts::BeginCatchOp>(loc, mth.getOpaqueType(), cmpValue.getDefiningOp()->getOperand(0));
}

auto rethrowVal = rewriter.create<mlir_ts::NullOp>(loc, mth.getNullType());
auto rethrowOp = rewriter.create<mlir_ts::ThrowOp>(loc, rethrowVal);
if (parentTryOpLandingPad)
if (tsContext->compileOptions.isWindows || linuxTypedCatchChains)
{
// see windowsNeedsParentEdge / linuxTypedCatchChains: the finally's pad comes
// before any enclosing try's
if (finallyHasOps)
{
tsContext->unwind[rethrowOp] = finallyBlock;
}
else if (parentCatchesThis)
{
tsContext->unwind[rethrowOp] = parentTryOpLandingPad;
}
}
else if (parentTryOpLandingPad)
{
tsContext->unwind[rethrowOp] = parentTryOpLandingPad;
}
Expand Down
7 changes: 4 additions & 3 deletions tslang/lib/TypeScript/LowerToLLVM.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4923,10 +4923,11 @@ struct LandingPadOpLowering : public TsLlvmPattern<mlir_ts::LandingPadOp>

TypeHelper th(rewriter);

auto catch1 = transformed.getCatches().front();

// every clause TryOpLowering attached, not just the first: a typed catch's catch-all
// clause comes second (linuxHasCleanups, linuxTypedCatchChains), and dropping it left
// the pad unentered for any other exception type
mlir::Type llvmLandingPadTy = getTypeConverter()->convertType(landingPadOp.getType());
rewriter.replaceOpWithNewOp<LLVM::LandingpadOp>(landingPadOp, llvmLandingPadTy, false, ValueRange{catch1});
rewriter.replaceOpWithNewOp<LLVM::LandingpadOp>(landingPadOp, llvmLandingPadTy, false, transformed.getCatches());

return success();
}
Expand Down
4 changes: 4 additions & 0 deletions tslang/lib/TypeScript/MLIRGenStatements.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1075,6 +1075,10 @@ namespace mlirgen
{
auto location = loc(tryStatementAST);

// the catch binding belongs to its clause, not the enclosing block: without its own scope
// a second `catch (e)` in the same block was reported as a redeclaration of the first
SymbolTableScopeT catchVarScope(symbolTable);

std::string varName;
auto catchClause = tryStatementAST->catchClause;
if (catchClause)
Expand Down
32 changes: 29 additions & 3 deletions tslang/lib/TypeScriptExceptionPass/Win32ExceptionPass.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,20 @@ struct Win32ExceptionPassCode
CI->getCalledFunction()->getName() == "__cxa_end_catch";
}

// The two invokes a catch region can legitimately end on: its own end-of-catch marker, or a
// throw out of it. Either way nothing follows inside the funclet, so it needs no catchret.
static bool isCatchEndingInvoke(llvm::Instruction *I)
{
auto *II = dyn_cast<InvokeInst>(I);
if (!II || II->getCalledFunction() == nullptr || !II->getCalledFunction()->hasName())
{
return false;
}

auto name = II->getCalledFunction()->getName();
return name == "__cxa_end_catch" || name == "_CxxThrowException";
}

bool runOnFunction(Function &F)
{
auto MadeChange = false;
Expand Down Expand Up @@ -408,14 +422,26 @@ struct Win32ExceptionPassCode
llvm::IRBuilder<> Builder(I);
llvm::LLVMContext &Ctx = Builder.getContext();

// A catch region's `end` is otherwise just the first instruction after its
// end-of-catch marker, and that can be an ordinary invoke: once the canonicalizer
// merges a catch block into what follows it, a second try's first call comes
// straight after the first catch. Treated like the end marker, that invoke got no
// catchret, so the second try ran inside the first catch's funclet and crashed.
// It has to be split off like any other instruction instead.
auto *endInvoke = dyn_cast<InvokeInst>(I);
if (endInvoke && catchRegion.isCatch() && !isCatchEndingInvoke(endInvoke))
{
endInvoke = nullptr;
}

auto *BI = dyn_cast<BranchInst>(I);
if (BI)
{
retBlock = BI->getSuccessor(0);
}
else if (auto *II = dyn_cast<InvokeInst>(I))
else if (endInvoke)
{
retBlock = II->getNormalDest();
retBlock = endInvoke->getNormalDest();
}
else if (dyn_cast<ResumeInst>(I))
{
Expand Down Expand Up @@ -448,7 +474,7 @@ struct Win32ExceptionPassCode

if (catchRegion.isCatch())
{
if (!dyn_cast<InvokeInst>(I))
if (!endInvoke)
{
assert(catchRegion.catchPad);
auto CR = CatchReturnInst::Create(catchRegion.catchPad, retBlock, BI ? BI->getParent() : I->getParent());
Expand Down
3 changes: 3 additions & 0 deletions tslang/test/tester/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,7 @@ tslang_add_test(NAME test-compile-00-owned-locals COMMAND test-runner "${PROJECT
tslang_add_test(NAME test-compile-00-try-using-catch COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_using_catch.ts")
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.
Expand Down Expand Up @@ -815,6 +816,7 @@ tslang_add_test(NAME test-jit-00-new-delete COMMAND test-runner -jit "${PROJECT_
tslang_add_test(NAME test-jit-00-owned-locals COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00owned_locals.ts")
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")
Expand Down Expand Up @@ -1717,6 +1719,7 @@ set(TSLANG_CORPUS
00try_catch_rethrow.ts
00try_catch_return_dispose.ts
00try_catch_return.ts
00try_catch_sequence_and_nesting.ts
00try_catch.ts
00try_finally_break_continue.ts
00try_finally_return.ts
Expand Down
Loading
Loading