#include "Utils/WebAssemblyUtilities.h"
#include "WebAssembly.h"
#include "WebAssemblyTargetMachine.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/CodeGen/TargetPassConfig.h"
#include "llvm/CodeGen/WasmEHFuncInfo.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/IntrinsicsWebAssembly.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Transforms/Utils/SSAUpdater.h"
#include "llvm/Transforms/Utils/SSAUpdaterBulk.h"
using namespace llvm;
#define DEBUG_TYPE "wasm-lower-em-ehsjlj"
static cl::list<std::string>
EHAllowlist("emscripten-cxx-exceptions-allowed",
cl::desc("The list of function names in which Emscripten-style "
"exception handling is enabled (see emscripten "
"EMSCRIPTEN_CATCHING_ALLOWED options)"),
cl::CommaSeparated);
namespace {
class WebAssemblyLowerEmscriptenEHSjLj final : public ModulePass {
bool EnableEmEH; bool EnableEmSjLj; bool EnableWasmSjLj; bool DoSjLj;
GlobalVariable *ThrewGV = nullptr; GlobalVariable *ThrewValueGV = nullptr; Function *GetTempRet0F = nullptr; Function *SetTempRet0F = nullptr; Function *ResumeF = nullptr; Function *EHTypeIDF = nullptr; Function *EmLongjmpF = nullptr; Function *SaveSetjmpF = nullptr; Function *TestSetjmpF = nullptr; Function *WasmLongjmpF = nullptr; Function *CatchF = nullptr;
Type *LongjmpArgsTy = nullptr;
DenseMap<int, Function *> FindMatchingCatches;
StringMap<Function *> InvokeWrappers;
std::set<std::string> EHAllowlistSet;
SmallPtrSet<Function *, 8> SetjmpUsers;
StringRef getPassName() const override {
return "WebAssembly Lower Emscripten Exceptions";
}
using InstVector = SmallVectorImpl<Instruction *>;
bool runEHOnFunction(Function &F);
bool runSjLjOnFunction(Function &F);
void handleLongjmpableCallsForEmscriptenSjLj(
Function &F, InstVector &SetjmpTableInsts,
InstVector &SetjmpTableSizeInsts,
SmallVectorImpl<PHINode *> &SetjmpRetPHIs);
void
handleLongjmpableCallsForWasmSjLj(Function &F, InstVector &SetjmpTableInsts,
InstVector &SetjmpTableSizeInsts,
SmallVectorImpl<PHINode *> &SetjmpRetPHIs);
Function *getFindMatchingCatch(Module &M, unsigned NumClauses);
Value *wrapInvoke(CallBase *CI);
void wrapTestSetjmp(BasicBlock *BB, DebugLoc DL, Value *Threw,
Value *SetjmpTable, Value *SetjmpTableSize, Value *&Label,
Value *&LongjmpResult, BasicBlock *&CallEmLongjmpBB,
PHINode *&CallEmLongjmpBBThrewPHI,
PHINode *&CallEmLongjmpBBThrewValuePHI,
BasicBlock *&EndBB);
Function *getInvokeWrapper(CallBase *CI);
bool areAllExceptionsAllowed() const { return EHAllowlistSet.empty(); }
bool supportsException(const Function *F) const {
return EnableEmEH && (areAllExceptionsAllowed() ||
EHAllowlistSet.count(std::string(F->getName())));
}
void replaceLongjmpWith(Function *LongjmpF, Function *NewF);
void rebuildSSA(Function &F);
public:
static char ID;
WebAssemblyLowerEmscriptenEHSjLj()
: ModulePass(ID), EnableEmEH(WebAssembly::WasmEnableEmEH),
EnableEmSjLj(WebAssembly::WasmEnableEmSjLj),
EnableWasmSjLj(WebAssembly::WasmEnableSjLj) {
assert(!(EnableEmSjLj && EnableWasmSjLj) &&
"Two SjLj modes cannot be turned on at the same time");
assert(!(EnableEmEH && EnableWasmSjLj) &&
"Wasm SjLj should be only used with Wasm EH");
EHAllowlistSet.insert(EHAllowlist.begin(), EHAllowlist.end());
}
bool runOnModule(Module &M) override;
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<DominatorTreeWrapperPass>();
}
};
}
char WebAssemblyLowerEmscriptenEHSjLj::ID = 0;
INITIALIZE_PASS(WebAssemblyLowerEmscriptenEHSjLj, DEBUG_TYPE,
"WebAssembly Lower Emscripten Exceptions / Setjmp / Longjmp",
false, false)
ModulePass *llvm::createWebAssemblyLowerEmscriptenEHSjLj() {
return new WebAssemblyLowerEmscriptenEHSjLj();
}
static bool canThrow(const Value *V) {
if (const auto *F = dyn_cast<const Function>(V)) {
if (F->isIntrinsic())
return false;
StringRef Name = F->getName();
if (Name == "setjmp" || Name == "longjmp" || Name == "emscripten_longjmp")
return false;
return !F->doesNotThrow();
}
return true;
}
static GlobalVariable *getGlobalVariable(Module &M, Type *Ty,
WebAssemblyTargetMachine &TM,
const char *Name) {
auto *GV = dyn_cast<GlobalVariable>(M.getOrInsertGlobal(Name, Ty));
if (!GV)
report_fatal_error(Twine("unable to create global: ") + Name);
GV->setThreadLocalMode(GlobalValue::GeneralDynamicTLSModel);
return GV;
}
static std::string getSignature(FunctionType *FTy) {
std::string Sig;
raw_string_ostream OS(Sig);
OS << *FTy->getReturnType();
for (Type *ParamTy : FTy->params())
OS << "_" << *ParamTy;
if (FTy->isVarArg())
OS << "_...";
Sig = OS.str();
erase_if(Sig, isSpace);
std::replace(Sig.begin(), Sig.end(), ',', '.');
return Sig;
}
static Function *getEmscriptenFunction(FunctionType *Ty, const Twine &Name,
Module *M) {
Function* F = Function::Create(Ty, GlobalValue::ExternalLinkage, Name, M);
if (!F->hasFnAttribute("wasm-import-module")) {
llvm::AttrBuilder B(M->getContext());
B.addAttribute("wasm-import-module", "env");
F->addFnAttrs(B);
}
if (!F->hasFnAttribute("wasm-import-name")) {
llvm::AttrBuilder B(M->getContext());
B.addAttribute("wasm-import-name", F->getName());
F->addFnAttrs(B);
}
return F;
}
static Type *getAddrIntType(Module *M) {
IRBuilder<> IRB(M->getContext());
return IRB.getIntNTy(M->getDataLayout().getPointerSizeInBits());
}
static Type *getAddrPtrType(Module *M) {
return Type::getIntNPtrTy(M->getContext(),
M->getDataLayout().getPointerSizeInBits());
}
static Value *getAddrSizeInt(Module *M, uint64_t C) {
IRBuilder<> IRB(M->getContext());
return IRB.getIntN(M->getDataLayout().getPointerSizeInBits(), C);
}
Function *
WebAssemblyLowerEmscriptenEHSjLj::getFindMatchingCatch(Module &M,
unsigned NumClauses) {
if (FindMatchingCatches.count(NumClauses))
return FindMatchingCatches[NumClauses];
PointerType *Int8PtrTy = Type::getInt8PtrTy(M.getContext());
SmallVector<Type *, 16> Args(NumClauses, Int8PtrTy);
FunctionType *FTy = FunctionType::get(Int8PtrTy, Args, false);
Function *F = getEmscriptenFunction(
FTy, "__cxa_find_matching_catch_" + Twine(NumClauses + 2), &M);
FindMatchingCatches[NumClauses] = F;
return F;
}
Value *WebAssemblyLowerEmscriptenEHSjLj::wrapInvoke(CallBase *CI) {
Module *M = CI->getModule();
LLVMContext &C = M->getContext();
IRBuilder<> IRB(C);
IRB.SetInsertPoint(CI);
IRB.CreateStore(getAddrSizeInt(M, 0), ThrewGV);
SmallVector<Value *, 16> Args;
Args.push_back(CI->getCalledOperand());
Args.append(CI->arg_begin(), CI->arg_end());
CallInst *NewCall = IRB.CreateCall(getInvokeWrapper(CI), Args);
NewCall->takeName(CI);
NewCall->setCallingConv(CallingConv::WASM_EmscriptenInvoke);
NewCall->setDebugLoc(CI->getDebugLoc());
SmallVector<AttributeSet, 8> ArgAttributes;
const AttributeList &InvokeAL = CI->getAttributes();
ArgAttributes.push_back(AttributeSet());
for (unsigned I = 0, E = CI->arg_size(); I < E; ++I)
ArgAttributes.push_back(InvokeAL.getParamAttrs(I));
AttrBuilder FnAttrs(CI->getContext(), InvokeAL.getFnAttrs());
if (FnAttrs.contains(Attribute::AllocSize)) {
unsigned SizeArg;
Optional<unsigned> NEltArg;
std::tie(SizeArg, NEltArg) = FnAttrs.getAllocSizeArgs();
SizeArg += 1;
if (NEltArg)
NEltArg = NEltArg.value() + 1;
FnAttrs.addAllocSizeAttr(SizeArg, NEltArg);
}
FnAttrs.removeAttribute(Attribute::NoReturn);
AttributeList NewCallAL = AttributeList::get(
C, AttributeSet::get(C, FnAttrs), InvokeAL.getRetAttrs(), ArgAttributes);
NewCall->setAttributes(NewCallAL);
CI->replaceAllUsesWith(NewCall);
Value *Threw =
IRB.CreateLoad(getAddrIntType(M), ThrewGV, ThrewGV->getName() + ".val");
IRB.CreateStore(getAddrSizeInt(M, 0), ThrewGV);
return Threw;
}
Function *WebAssemblyLowerEmscriptenEHSjLj::getInvokeWrapper(CallBase *CI) {
Module *M = CI->getModule();
SmallVector<Type *, 16> ArgTys;
FunctionType *CalleeFTy = CI->getFunctionType();
std::string Sig = getSignature(CalleeFTy);
if (InvokeWrappers.find(Sig) != InvokeWrappers.end())
return InvokeWrappers[Sig];
ArgTys.push_back(PointerType::getUnqual(CalleeFTy));
ArgTys.append(CalleeFTy->param_begin(), CalleeFTy->param_end());
FunctionType *FTy = FunctionType::get(CalleeFTy->getReturnType(), ArgTys,
CalleeFTy->isVarArg());
Function *F = getEmscriptenFunction(FTy, "__invoke_" + Sig, M);
InvokeWrappers[Sig] = F;
return F;
}
static bool canLongjmp(const Value *Callee) {
if (auto *CalleeF = dyn_cast<Function>(Callee))
if (CalleeF->isIntrinsic())
return false;
if (isa<InlineAsm>(Callee))
return false;
StringRef CalleeName = Callee->getName();
if (CalleeName == "setjmp" || CalleeName == "malloc" || CalleeName == "free")
return false;
if (CalleeName == "__resumeException" || CalleeName == "llvm_eh_typeid_for" ||
CalleeName == "saveSetjmp" || CalleeName == "testSetjmp" ||
CalleeName == "getTempRet0" || CalleeName == "setTempRet0")
return false;
if (Callee->getName().startswith("__cxa_find_matching_catch_"))
return false;
if (CalleeName == "__cxa_end_catch")
return WebAssembly::WasmEnableSjLj;
if (CalleeName == "__cxa_begin_catch" ||
CalleeName == "__cxa_allocate_exception" || CalleeName == "__cxa_throw" ||
CalleeName == "__clang_call_terminate")
return false;
if (CalleeName == "_ZSt9terminatev")
return false;
return true;
}
static bool isEmAsmCall(const Value *Callee) {
StringRef CalleeName = Callee->getName();
return CalleeName == "emscripten_asm_const_int" ||
CalleeName == "emscripten_asm_const_double" ||
CalleeName == "emscripten_asm_const_int_sync_on_main_thread" ||
CalleeName == "emscripten_asm_const_double_sync_on_main_thread" ||
CalleeName == "emscripten_asm_const_async_on_main_thread";
}
void WebAssemblyLowerEmscriptenEHSjLj::wrapTestSetjmp(
BasicBlock *BB, DebugLoc DL, Value *Threw, Value *SetjmpTable,
Value *SetjmpTableSize, Value *&Label, Value *&LongjmpResult,
BasicBlock *&CallEmLongjmpBB, PHINode *&CallEmLongjmpBBThrewPHI,
PHINode *&CallEmLongjmpBBThrewValuePHI, BasicBlock *&EndBB) {
Function *F = BB->getParent();
Module *M = F->getParent();
LLVMContext &C = M->getContext();
IRBuilder<> IRB(C);
IRB.SetCurrentDebugLocation(DL);
IRB.SetInsertPoint(BB);
BasicBlock *ThenBB1 = BasicBlock::Create(C, "if.then1", F);
BasicBlock *ElseBB1 = BasicBlock::Create(C, "if.else1", F);
BasicBlock *EndBB1 = BasicBlock::Create(C, "if.end", F);
Value *ThrewCmp = IRB.CreateICmpNE(Threw, getAddrSizeInt(M, 0));
Value *ThrewValue = IRB.CreateLoad(IRB.getInt32Ty(), ThrewValueGV,
ThrewValueGV->getName() + ".val");
Value *ThrewValueCmp = IRB.CreateICmpNE(ThrewValue, IRB.getInt32(0));
Value *Cmp1 = IRB.CreateAnd(ThrewCmp, ThrewValueCmp, "cmp1");
IRB.CreateCondBr(Cmp1, ThenBB1, ElseBB1);
if (!CallEmLongjmpBB) {
CallEmLongjmpBB = BasicBlock::Create(C, "call.em.longjmp", F);
IRB.SetInsertPoint(CallEmLongjmpBB);
CallEmLongjmpBBThrewPHI = IRB.CreatePHI(getAddrIntType(M), 4, "threw.phi");
CallEmLongjmpBBThrewValuePHI =
IRB.CreatePHI(IRB.getInt32Ty(), 4, "threwvalue.phi");
CallEmLongjmpBBThrewPHI->addIncoming(Threw, ThenBB1);
CallEmLongjmpBBThrewValuePHI->addIncoming(ThrewValue, ThenBB1);
IRB.CreateCall(EmLongjmpF,
{CallEmLongjmpBBThrewPHI, CallEmLongjmpBBThrewValuePHI});
IRB.CreateUnreachable();
} else {
CallEmLongjmpBBThrewPHI->addIncoming(Threw, ThenBB1);
CallEmLongjmpBBThrewValuePHI->addIncoming(ThrewValue, ThenBB1);
}
IRB.SetInsertPoint(ThenBB1);
BasicBlock *EndBB2 = BasicBlock::Create(C, "if.end2", F);
Value *ThrewPtr =
IRB.CreateIntToPtr(Threw, getAddrPtrType(M), Threw->getName() + ".p");
Value *LoadedThrew = IRB.CreateLoad(getAddrIntType(M), ThrewPtr,
ThrewPtr->getName() + ".loaded");
Value *ThenLabel = IRB.CreateCall(
TestSetjmpF, {LoadedThrew, SetjmpTable, SetjmpTableSize}, "label");
Value *Cmp2 = IRB.CreateICmpEQ(ThenLabel, IRB.getInt32(0));
IRB.CreateCondBr(Cmp2, CallEmLongjmpBB, EndBB2);
IRB.SetInsertPoint(EndBB2);
IRB.CreateCall(SetTempRet0F, ThrewValue);
IRB.CreateBr(EndBB1);
IRB.SetInsertPoint(ElseBB1);
IRB.CreateBr(EndBB1);
IRB.SetInsertPoint(EndBB1);
PHINode *LabelPHI = IRB.CreatePHI(IRB.getInt32Ty(), 2, "label");
LabelPHI->addIncoming(ThenLabel, EndBB2);
LabelPHI->addIncoming(IRB.getInt32(-1), ElseBB1);
Label = LabelPHI;
EndBB = EndBB1;
LongjmpResult = IRB.CreateCall(GetTempRet0F, None, "longjmp_result");
}
void WebAssemblyLowerEmscriptenEHSjLj::rebuildSSA(Function &F) {
DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
DT.recalculate(F);
SSAUpdaterBulk SSA;
for (BasicBlock &BB : F) {
for (Instruction &I : BB) {
unsigned VarID = SSA.AddVariable(I.getName(), I.getType());
if (auto *II = dyn_cast<InvokeInst>(&I))
SSA.AddAvailableValue(VarID, II->getNormalDest(), II);
else
SSA.AddAvailableValue(VarID, &BB, &I);
for (auto &U : I.uses()) {
auto *User = cast<Instruction>(U.getUser());
if (auto *UserPN = dyn_cast<PHINode>(User))
if (UserPN->getIncomingBlock(U) == &BB)
continue;
if (DT.dominates(&I, User))
continue;
SSA.AddUse(VarID, &U);
}
}
}
SSA.RewriteAllUses(&DT);
}
void WebAssemblyLowerEmscriptenEHSjLj::replaceLongjmpWith(Function *LongjmpF,
Function *NewF) {
assert(NewF == EmLongjmpF || NewF == WasmLongjmpF);
Module *M = LongjmpF->getParent();
SmallVector<CallInst *, 8> ToErase;
LLVMContext &C = LongjmpF->getParent()->getContext();
IRBuilder<> IRB(C);
for (User *U : LongjmpF->users()) {
auto *CI = dyn_cast<CallInst>(U);
if (CI && CI->getCalledFunction() == LongjmpF) {
IRB.SetInsertPoint(CI);
Value *Env = nullptr;
if (NewF == EmLongjmpF)
Env =
IRB.CreatePtrToInt(CI->getArgOperand(0), getAddrIntType(M), "env");
else Env =
IRB.CreateBitCast(CI->getArgOperand(0), IRB.getInt8PtrTy(), "env");
IRB.CreateCall(NewF, {Env, CI->getArgOperand(1)});
ToErase.push_back(CI);
}
}
for (auto *I : ToErase)
I->eraseFromParent();
if (!LongjmpF->uses().empty()) {
Value *NewLongjmp =
IRB.CreateBitCast(NewF, LongjmpF->getType(), "longjmp.cast");
LongjmpF->replaceAllUsesWith(NewLongjmp);
}
}
static bool containsLongjmpableCalls(const Function *F) {
for (const auto &BB : *F)
for (const auto &I : BB)
if (const auto *CB = dyn_cast<CallBase>(&I))
if (canLongjmp(CB->getCalledOperand()))
return true;
return false;
}
static void nullifySetjmp(Function *F) {
Module &M = *F->getParent();
IRBuilder<> IRB(M.getContext());
Function *SetjmpF = M.getFunction("setjmp");
SmallVector<Instruction *, 1> ToErase;
for (User *U : make_early_inc_range(SetjmpF->users())) {
auto *CB = cast<CallBase>(U);
BasicBlock *BB = CB->getParent();
if (BB->getParent() != F) continue;
CallInst *CI = nullptr;
if (auto *II = dyn_cast<InvokeInst>(CB))
CI = llvm::changeToCall(II);
else
CI = cast<CallInst>(CB);
ToErase.push_back(CI);
CI->replaceAllUsesWith(IRB.getInt32(0));
}
for (auto *I : ToErase)
I->eraseFromParent();
}
bool WebAssemblyLowerEmscriptenEHSjLj::runOnModule(Module &M) {
LLVM_DEBUG(dbgs() << "********** Lower Emscripten EH & SjLj **********\n");
LLVMContext &C = M.getContext();
IRBuilder<> IRB(C);
Function *SetjmpF = M.getFunction("setjmp");
Function *LongjmpF = M.getFunction("longjmp");
Function *SetjmpF2 = M.getFunction("_setjmp");
Function *LongjmpF2 = M.getFunction("_longjmp");
if (SetjmpF2) {
if (SetjmpF) {
if (SetjmpF->getFunctionType() != SetjmpF2->getFunctionType())
report_fatal_error("setjmp and _setjmp have different function types");
} else {
SetjmpF = Function::Create(SetjmpF2->getFunctionType(),
GlobalValue::ExternalLinkage, "setjmp", M);
}
SetjmpF2->replaceAllUsesWith(SetjmpF);
}
if (LongjmpF2) {
if (LongjmpF) {
if (LongjmpF->getFunctionType() != LongjmpF2->getFunctionType())
report_fatal_error(
"longjmp and _longjmp have different function types");
} else {
LongjmpF = Function::Create(LongjmpF2->getFunctionType(),
GlobalValue::ExternalLinkage, "setjmp", M);
}
LongjmpF2->replaceAllUsesWith(LongjmpF);
}
auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
assert(TPC && "Expected a TargetPassConfig");
auto &TM = TPC->getTM<WebAssemblyTargetMachine>();
ThrewGV = getGlobalVariable(M, getAddrIntType(&M), TM, "__THREW__");
ThrewValueGV = getGlobalVariable(M, IRB.getInt32Ty(), TM, "__threwValue");
GetTempRet0F = getEmscriptenFunction(
FunctionType::get(IRB.getInt32Ty(), false), "getTempRet0", &M);
SetTempRet0F = getEmscriptenFunction(
FunctionType::get(IRB.getVoidTy(), IRB.getInt32Ty(), false),
"setTempRet0", &M);
GetTempRet0F->setDoesNotThrow();
SetTempRet0F->setDoesNotThrow();
bool Changed = false;
if (EnableEmEH) {
FunctionType *ResumeFTy =
FunctionType::get(IRB.getVoidTy(), IRB.getInt8PtrTy(), false);
ResumeF = getEmscriptenFunction(ResumeFTy, "__resumeException", &M);
ResumeF->addFnAttr(Attribute::NoReturn);
FunctionType *EHTypeIDTy =
FunctionType::get(IRB.getInt32Ty(), IRB.getInt8PtrTy(), false);
EHTypeIDF = getEmscriptenFunction(EHTypeIDTy, "llvm_eh_typeid_for", &M);
}
SmallPtrSet<Function *, 4> SetjmpUsersToNullify;
if ((EnableEmSjLj || EnableWasmSjLj) && SetjmpF) {
for (User *U : SetjmpF->users()) {
if (auto *CB = dyn_cast<CallBase>(U)) {
auto *UserF = CB->getFunction();
if (containsLongjmpableCalls(UserF))
SetjmpUsers.insert(UserF);
else
SetjmpUsersToNullify.insert(UserF);
} else {
std::string S;
raw_string_ostream SS(S);
SS << *U;
report_fatal_error(Twine("Indirect use of setjmp is not supported: ") +
SS.str());
}
}
}
bool SetjmpUsed = SetjmpF && !SetjmpUsers.empty();
bool LongjmpUsed = LongjmpF && !LongjmpF->use_empty();
DoSjLj = (EnableEmSjLj | EnableWasmSjLj) && (SetjmpUsed || LongjmpUsed);
if (DoSjLj) {
assert(EnableEmSjLj || EnableWasmSjLj);
if (EnableEmSjLj) {
FunctionType *FTy = FunctionType::get(
IRB.getVoidTy(), {getAddrIntType(&M), IRB.getInt32Ty()}, false);
EmLongjmpF = getEmscriptenFunction(FTy, "emscripten_longjmp", &M);
EmLongjmpF->addFnAttr(Attribute::NoReturn);
} else { FunctionType *FTy = FunctionType::get(
IRB.getVoidTy(), {IRB.getInt8PtrTy(), IRB.getInt32Ty()}, false);
WasmLongjmpF = getEmscriptenFunction(FTy, "__wasm_longjmp", &M);
WasmLongjmpF->addFnAttr(Attribute::NoReturn);
}
if (SetjmpF) {
FunctionType *SetjmpFTy = SetjmpF->getFunctionType();
FunctionType *FTy =
FunctionType::get(Type::getInt32PtrTy(C),
{SetjmpFTy->getParamType(0), IRB.getInt32Ty(),
Type::getInt32PtrTy(C), IRB.getInt32Ty()},
false);
SaveSetjmpF = getEmscriptenFunction(FTy, "saveSetjmp", &M);
FTy = FunctionType::get(
IRB.getInt32Ty(),
{getAddrIntType(&M), Type::getInt32PtrTy(C), IRB.getInt32Ty()},
false);
TestSetjmpF = getEmscriptenFunction(FTy, "testSetjmp", &M);
CatchF = Intrinsic::getDeclaration(&M, Intrinsic::wasm_catch);
LongjmpArgsTy = StructType::get(IRB.getInt8PtrTy(), IRB.getInt32Ty() );
}
}
if (EnableEmEH) {
for (Function &F : M) {
if (F.isDeclaration())
continue;
Changed |= runEHOnFunction(F);
}
}
if (DoSjLj) {
Changed = true; if (LongjmpF)
replaceLongjmpWith(LongjmpF, EnableEmSjLj ? EmLongjmpF : WasmLongjmpF);
if (SetjmpF)
for (Function *F : SetjmpUsers)
runSjLjOnFunction(*F);
}
if ((EnableEmSjLj || EnableWasmSjLj) && !SetjmpUsersToNullify.empty()) {
Changed = true;
assert(SetjmpF);
for (Function *F : SetjmpUsersToNullify)
nullifySetjmp(F);
}
for (auto *V : {ThrewGV, ThrewValueGV})
if (V && V->use_empty())
V->eraseFromParent();
for (auto *V : {GetTempRet0F, SetTempRet0F, ResumeF, EHTypeIDF, EmLongjmpF,
SaveSetjmpF, TestSetjmpF, WasmLongjmpF, CatchF})
if (V && V->use_empty())
V->eraseFromParent();
return Changed;
}
bool WebAssemblyLowerEmscriptenEHSjLj::runEHOnFunction(Function &F) {
Module &M = *F.getParent();
LLVMContext &C = F.getContext();
IRBuilder<> IRB(C);
bool Changed = false;
SmallVector<Instruction *, 64> ToErase;
SmallPtrSet<LandingPadInst *, 32> LandingPads;
BasicBlock *RethrowLongjmpBB = nullptr;
PHINode *RethrowLongjmpBBThrewPHI = nullptr;
for (BasicBlock &BB : F) {
auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
if (!II)
continue;
Changed = true;
LandingPads.insert(II->getLandingPadInst());
IRB.SetInsertPoint(II);
const Value *Callee = II->getCalledOperand();
bool NeedInvoke = supportsException(&F) && canThrow(Callee);
if (NeedInvoke) {
Value *Threw = wrapInvoke(II);
ToErase.push_back(II);
if (DoSjLj && EnableEmSjLj && !SetjmpUsers.count(&F) &&
canLongjmp(Callee)) {
if (!RethrowLongjmpBB) {
RethrowLongjmpBB = BasicBlock::Create(C, "rethrow.longjmp", &F);
IRB.SetInsertPoint(RethrowLongjmpBB);
RethrowLongjmpBBThrewPHI =
IRB.CreatePHI(getAddrIntType(&M), 4, "threw.phi");
RethrowLongjmpBBThrewPHI->addIncoming(Threw, &BB);
Value *ThrewValue = IRB.CreateLoad(IRB.getInt32Ty(), ThrewValueGV,
ThrewValueGV->getName() + ".val");
IRB.CreateCall(EmLongjmpF, {RethrowLongjmpBBThrewPHI, ThrewValue});
IRB.CreateUnreachable();
} else {
RethrowLongjmpBBThrewPHI->addIncoming(Threw, &BB);
}
IRB.SetInsertPoint(II); BasicBlock *Tail = BasicBlock::Create(C, "tail", &F);
Value *CmpEqOne =
IRB.CreateICmpEQ(Threw, getAddrSizeInt(&M, 1), "cmp.eq.one");
Value *CmpEqZero =
IRB.CreateICmpEQ(Threw, getAddrSizeInt(&M, 0), "cmp.eq.zero");
Value *Or = IRB.CreateOr(CmpEqZero, CmpEqOne, "or");
IRB.CreateCondBr(Or, Tail, RethrowLongjmpBB);
IRB.SetInsertPoint(Tail);
BB.replaceSuccessorsPhiUsesWith(&BB, Tail);
}
Value *Cmp = IRB.CreateICmpEQ(Threw, getAddrSizeInt(&M, 1), "cmp");
IRB.CreateCondBr(Cmp, II->getUnwindDest(), II->getNormalDest());
} else {
changeToCall(II);
}
}
for (BasicBlock &BB : F) {
for (Instruction &I : BB) {
auto *RI = dyn_cast<ResumeInst>(&I);
if (!RI)
continue;
Changed = true;
Value *Input = RI->getValue();
IRB.SetInsertPoint(RI);
Value *Low = IRB.CreateExtractValue(Input, 0, "low");
IRB.CreateCall(ResumeF, {Low});
IRB.CreateUnreachable();
ToErase.push_back(RI);
}
}
for (BasicBlock &BB : F) {
for (Instruction &I : BB) {
auto *CI = dyn_cast<CallInst>(&I);
if (!CI)
continue;
const Function *Callee = CI->getCalledFunction();
if (!Callee)
continue;
if (Callee->getIntrinsicID() != Intrinsic::eh_typeid_for)
continue;
Changed = true;
IRB.SetInsertPoint(CI);
CallInst *NewCI =
IRB.CreateCall(EHTypeIDF, CI->getArgOperand(0), "typeid");
CI->replaceAllUsesWith(NewCI);
ToErase.push_back(CI);
}
}
for (BasicBlock &BB : F) {
Instruction *I = BB.getFirstNonPHI();
if (auto *LPI = dyn_cast<LandingPadInst>(I))
LandingPads.insert(LPI);
}
Changed |= !LandingPads.empty();
for (LandingPadInst *LPI : LandingPads) {
IRB.SetInsertPoint(LPI);
SmallVector<Value *, 16> FMCArgs;
for (unsigned I = 0, E = LPI->getNumClauses(); I < E; ++I) {
Constant *Clause = LPI->getClause(I);
if (LPI->isCatch(I))
FMCArgs.push_back(Clause);
}
Function *FMCF = getFindMatchingCatch(M, FMCArgs.size());
CallInst *FMCI = IRB.CreateCall(FMCF, FMCArgs, "fmc");
Value *Undef = UndefValue::get(LPI->getType());
Value *Pair0 = IRB.CreateInsertValue(Undef, FMCI, 0, "pair0");
Value *TempRet0 = IRB.CreateCall(GetTempRet0F, None, "tempret0");
Value *Pair1 = IRB.CreateInsertValue(Pair0, TempRet0, 1, "pair1");
LPI->replaceAllUsesWith(Pair1);
ToErase.push_back(LPI);
}
for (Instruction *I : ToErase)
I->eraseFromParent();
return Changed;
}
static DebugLoc getOrCreateDebugLoc(const Instruction *InsertBefore,
DISubprogram *SP) {
assert(InsertBefore);
if (InsertBefore->getDebugLoc())
return InsertBefore->getDebugLoc();
const Instruction *Prev = InsertBefore->getPrevNode();
if (Prev && Prev->getDebugLoc())
return Prev->getDebugLoc();
if (SP)
return DILocation::get(SP->getContext(), SP->getLine(), 1, SP);
return DebugLoc();
}
bool WebAssemblyLowerEmscriptenEHSjLj::runSjLjOnFunction(Function &F) {
assert(EnableEmSjLj || EnableWasmSjLj);
Module &M = *F.getParent();
LLVMContext &C = F.getContext();
IRBuilder<> IRB(C);
SmallVector<Instruction *, 64> ToErase;
SmallVector<Instruction *, 4> SetjmpTableInsts;
SmallVector<Instruction *, 4> SetjmpTableSizeInsts;
BasicBlock *Entry = &F.getEntryBlock();
DebugLoc FirstDL = getOrCreateDebugLoc(&*Entry->begin(), F.getSubprogram());
SplitBlock(Entry, &*Entry->getFirstInsertionPt());
BinaryOperator *SetjmpTableSize =
BinaryOperator::Create(Instruction::Add, IRB.getInt32(4), IRB.getInt32(0),
"setjmpTableSize", Entry->getTerminator());
SetjmpTableSize->setDebugLoc(FirstDL);
Instruction *SetjmpTable = CallInst::CreateMalloc(
SetjmpTableSize, IRB.getInt32Ty(), IRB.getInt32Ty(), IRB.getInt32(40),
nullptr, nullptr, "setjmpTable");
SetjmpTable->setDebugLoc(FirstDL);
auto *MallocCall = SetjmpTable->stripPointerCasts();
if (auto *MallocCallI = dyn_cast<Instruction>(MallocCall)) {
MallocCallI->setDebugLoc(FirstDL);
}
IRB.SetInsertPoint(SetjmpTableSize);
IRB.CreateStore(IRB.getInt32(0), SetjmpTable);
SetjmpTableInsts.push_back(SetjmpTable);
SetjmpTableSizeInsts.push_back(SetjmpTableSize);
SmallVector<PHINode *, 4> SetjmpRetPHIs;
Function *SetjmpF = M.getFunction("setjmp");
for (auto *U : make_early_inc_range(SetjmpF->users())) {
auto *CB = cast<CallBase>(U);
BasicBlock *BB = CB->getParent();
if (BB->getParent() != &F) continue;
if (CB->getOperandBundle(LLVMContext::OB_funclet)) {
std::string S;
raw_string_ostream SS(S);
SS << "In function " + F.getName() +
": setjmp within a catch clause is not supported in Wasm EH:\n";
SS << *CB;
report_fatal_error(StringRef(SS.str()));
}
CallInst *CI = nullptr;
if (auto *II = dyn_cast<InvokeInst>(CB))
CI = llvm::changeToCall(II);
else
CI = cast<CallInst>(CB);
BasicBlock *Tail = SplitBlock(BB, CI->getNextNode());
IRB.SetInsertPoint(Tail->getFirstNonPHI());
PHINode *SetjmpRet = IRB.CreatePHI(IRB.getInt32Ty(), 2, "setjmp.ret");
SetjmpRet->addIncoming(IRB.getInt32(0), BB);
CI->replaceAllUsesWith(SetjmpRet);
SetjmpRetPHIs.push_back(SetjmpRet);
IRB.SetInsertPoint(CI);
Value *Args[] = {CI->getArgOperand(0), IRB.getInt32(SetjmpRetPHIs.size()),
SetjmpTable, SetjmpTableSize};
Instruction *NewSetjmpTable =
IRB.CreateCall(SaveSetjmpF, Args, "setjmpTable");
Instruction *NewSetjmpTableSize =
IRB.CreateCall(GetTempRet0F, None, "setjmpTableSize");
SetjmpTableInsts.push_back(NewSetjmpTable);
SetjmpTableSizeInsts.push_back(NewSetjmpTableSize);
ToErase.push_back(CI);
}
if (EnableEmSjLj)
handleLongjmpableCallsForEmscriptenSjLj(
F, SetjmpTableInsts, SetjmpTableSizeInsts, SetjmpRetPHIs);
else handleLongjmpableCallsForWasmSjLj(F, SetjmpTableInsts, SetjmpTableSizeInsts,
SetjmpRetPHIs);
for (Instruction *I : ToErase)
I->eraseFromParent();
SmallVector<Instruction *, 16> ExitingInsts;
for (BasicBlock &BB : F) {
Instruction *TI = BB.getTerminator();
if (isa<ReturnInst>(TI))
ExitingInsts.push_back(TI);
for (auto &I : BB) {
if (auto *CI = dyn_cast<CallInst>(&I)) {
bool IsNoReturn = CI->hasFnAttr(Attribute::NoReturn);
if (Function *CalleeF = CI->getCalledFunction())
IsNoReturn |= CalleeF->hasFnAttribute(Attribute::NoReturn);
if (IsNoReturn)
ExitingInsts.push_back(&I);
}
}
}
for (auto *I : ExitingInsts) {
DebugLoc DL = getOrCreateDebugLoc(I, F.getSubprogram());
SmallVector<OperandBundleDef, 1> Bundles;
if (auto *CB = dyn_cast<CallBase>(I))
if (auto Bundle = CB->getOperandBundle(LLVMContext::OB_funclet))
Bundles.push_back(OperandBundleDef(*Bundle));
auto *Free = CallInst::CreateFree(SetjmpTable, Bundles, I);
Free->setDebugLoc(DL);
if (auto *FreeCallI = dyn_cast<CallInst>(Free)) {
if (auto *BitCastI = dyn_cast<BitCastInst>(FreeCallI->getArgOperand(0)))
BitCastI->setDebugLoc(DL);
}
}
SSAUpdater SetjmpTableSSA;
SSAUpdater SetjmpTableSizeSSA;
SetjmpTableSSA.Initialize(Type::getInt32PtrTy(C), "setjmpTable");
SetjmpTableSizeSSA.Initialize(Type::getInt32Ty(C), "setjmpTableSize");
for (Instruction *I : SetjmpTableInsts)
SetjmpTableSSA.AddAvailableValue(I->getParent(), I);
for (Instruction *I : SetjmpTableSizeInsts)
SetjmpTableSizeSSA.AddAvailableValue(I->getParent(), I);
for (auto &U : make_early_inc_range(SetjmpTable->uses()))
if (auto *I = dyn_cast<Instruction>(U.getUser()))
if (I->getParent() != Entry)
SetjmpTableSSA.RewriteUse(U);
for (auto &U : make_early_inc_range(SetjmpTableSize->uses()))
if (auto *I = dyn_cast<Instruction>(U.getUser()))
if (I->getParent() != Entry)
SetjmpTableSizeSSA.RewriteUse(U);
rebuildSSA(F);
return true;
}
void WebAssemblyLowerEmscriptenEHSjLj::handleLongjmpableCallsForEmscriptenSjLj(
Function &F, InstVector &SetjmpTableInsts, InstVector &SetjmpTableSizeInsts,
SmallVectorImpl<PHINode *> &SetjmpRetPHIs) {
Module &M = *F.getParent();
LLVMContext &C = F.getContext();
IRBuilder<> IRB(C);
SmallVector<Instruction *, 64> ToErase;
Instruction *SetjmpTable = *SetjmpTableInsts.begin();
Instruction *SetjmpTableSize = *SetjmpTableSizeInsts.begin();
BasicBlock *CallEmLongjmpBB = nullptr;
PHINode *CallEmLongjmpBBThrewPHI = nullptr;
PHINode *CallEmLongjmpBBThrewValuePHI = nullptr;
BasicBlock *RethrowExnBB = nullptr;
std::vector<BasicBlock *> BBs;
for (BasicBlock &BB : F)
BBs.push_back(&BB);
for (unsigned I = 0; I < BBs.size(); I++) {
BasicBlock *BB = BBs[I];
for (Instruction &I : *BB) {
if (isa<InvokeInst>(&I)) {
std::string S;
raw_string_ostream SS(S);
SS << "In function " << F.getName()
<< ": When using Wasm EH with Emscripten SjLj, there is a "
"restriction that `setjmp` function call and exception cannot be "
"used within the same function:\n";
SS << I;
report_fatal_error(StringRef(SS.str()));
}
auto *CI = dyn_cast<CallInst>(&I);
if (!CI)
continue;
const Value *Callee = CI->getCalledOperand();
if (!canLongjmp(Callee))
continue;
if (isEmAsmCall(Callee))
report_fatal_error("Cannot use EM_ASM* alongside setjmp/longjmp in " +
F.getName() +
". Please consider using EM_JS, or move the "
"EM_ASM into another function.",
false);
Value *Threw = nullptr;
BasicBlock *Tail;
if (Callee->getName().startswith("__invoke_")) {
LoadInst *ThrewLI = nullptr;
StoreInst *ThrewResetSI = nullptr;
for (auto I = std::next(BasicBlock::iterator(CI)), IE = BB->end();
I != IE; ++I) {
if (auto *LI = dyn_cast<LoadInst>(I))
if (auto *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand()))
if (GV == ThrewGV) {
Threw = ThrewLI = LI;
break;
}
}
for (auto I = std::next(BasicBlock::iterator(ThrewLI)), IE = BB->end();
I != IE; ++I) {
if (auto *SI = dyn_cast<StoreInst>(I)) {
if (auto *GV = dyn_cast<GlobalVariable>(SI->getPointerOperand())) {
if (GV == ThrewGV &&
SI->getValueOperand() == getAddrSizeInt(&M, 0)) {
ThrewResetSI = SI;
break;
}
}
}
}
assert(Threw && ThrewLI && "Cannot find __THREW__ load after invoke");
assert(ThrewResetSI && "Cannot find __THREW__ store after invoke");
Tail = SplitBlock(BB, ThrewResetSI->getNextNode());
} else {
Threw = wrapInvoke(CI);
ToErase.push_back(CI);
Tail = SplitBlock(BB, CI->getNextNode());
if (supportsException(&F) && canThrow(Callee)) {
ToErase.push_back(BB->getTerminator());
if (!RethrowExnBB) {
RethrowExnBB = BasicBlock::Create(C, "rethrow.exn", &F);
IRB.SetInsertPoint(RethrowExnBB);
CallInst *Exn =
IRB.CreateCall(getFindMatchingCatch(M, 0), {}, "exn");
IRB.CreateCall(ResumeF, {Exn});
IRB.CreateUnreachable();
}
IRB.SetInsertPoint(CI);
BasicBlock *NormalBB = BasicBlock::Create(C, "normal", &F);
Value *CmpEqOne =
IRB.CreateICmpEQ(Threw, getAddrSizeInt(&M, 1), "cmp.eq.one");
IRB.CreateCondBr(CmpEqOne, RethrowExnBB, NormalBB);
IRB.SetInsertPoint(NormalBB);
IRB.CreateBr(Tail);
BB = NormalBB; }
}
ToErase.push_back(BB->getTerminator());
Value *Label = nullptr;
Value *LongjmpResult = nullptr;
BasicBlock *EndBB = nullptr;
wrapTestSetjmp(BB, CI->getDebugLoc(), Threw, SetjmpTable, SetjmpTableSize,
Label, LongjmpResult, CallEmLongjmpBB,
CallEmLongjmpBBThrewPHI, CallEmLongjmpBBThrewValuePHI,
EndBB);
assert(Label && LongjmpResult && EndBB);
IRB.SetInsertPoint(EndBB);
IRB.SetCurrentDebugLocation(EndBB->getInstList().back().getDebugLoc());
SwitchInst *SI = IRB.CreateSwitch(Label, Tail, SetjmpRetPHIs.size());
for (unsigned I = 0; I < SetjmpRetPHIs.size(); I++) {
SI->addCase(IRB.getInt32(I + 1), SetjmpRetPHIs[I]->getParent());
SetjmpRetPHIs[I]->addIncoming(LongjmpResult, EndBB);
}
BBs.push_back(Tail);
}
}
for (Instruction *I : ToErase)
I->eraseFromParent();
}
static BasicBlock *getCleanupRetUnwindDest(const CleanupPadInst *CPI) {
for (const User *U : CPI->users())
if (const auto *CRI = dyn_cast<CleanupReturnInst>(U))
return CRI->getUnwindDest();
return nullptr;
}
void WebAssemblyLowerEmscriptenEHSjLj::handleLongjmpableCallsForWasmSjLj(
Function &F, InstVector &SetjmpTableInsts, InstVector &SetjmpTableSizeInsts,
SmallVectorImpl<PHINode *> &SetjmpRetPHIs) {
Module &M = *F.getParent();
LLVMContext &C = F.getContext();
IRBuilder<> IRB(C);
if (!F.hasPersonalityFn()) {
StringRef PersName = getEHPersonalityName(EHPersonality::Wasm_CXX);
FunctionType *PersType =
FunctionType::get(IRB.getInt32Ty(), true);
Value *PersF = M.getOrInsertFunction(PersName, PersType).getCallee();
F.setPersonalityFn(
cast<Constant>(IRB.CreateBitCast(PersF, IRB.getInt8PtrTy())));
}
BasicBlock *Entry = &F.getEntryBlock();
DebugLoc FirstDL = getOrCreateDebugLoc(&*Entry->begin(), F.getSubprogram());
IRB.SetCurrentDebugLocation(FirstDL);
Instruction *SetjmpTable = *SetjmpTableInsts.begin();
Instruction *SetjmpTableSize = *SetjmpTableSizeInsts.begin();
BasicBlock *OrigEntry = Entry->getNextNode();
BasicBlock *SetjmpDispatchBB =
BasicBlock::Create(C, "setjmp.dispatch", &F, OrigEntry);
cast<BranchInst>(Entry->getTerminator())->setSuccessor(0, SetjmpDispatchBB);
BasicBlock *CatchDispatchLongjmpBB =
BasicBlock::Create(C, "catch.dispatch.longjmp", &F);
IRB.SetInsertPoint(CatchDispatchLongjmpBB);
CatchSwitchInst *CatchSwitchLongjmp =
IRB.CreateCatchSwitch(ConstantTokenNone::get(C), nullptr, 1);
BasicBlock *CatchLongjmpBB = BasicBlock::Create(C, "catch.longjmp", &F);
CatchSwitchLongjmp->addHandler(CatchLongjmpBB);
IRB.SetInsertPoint(CatchLongjmpBB);
CatchPadInst *CatchPad = IRB.CreateCatchPad(CatchSwitchLongjmp, {});
Instruction *CatchCI =
IRB.CreateCall(CatchF, {IRB.getInt32(WebAssembly::C_LONGJMP)}, "thrown");
Value *LongjmpArgs =
IRB.CreateBitCast(CatchCI, LongjmpArgsTy->getPointerTo(), "longjmp.args");
Value *EnvField =
IRB.CreateConstGEP2_32(LongjmpArgsTy, LongjmpArgs, 0, 0, "env_gep");
Value *ValField =
IRB.CreateConstGEP2_32(LongjmpArgsTy, LongjmpArgs, 0, 1, "val_gep");
Instruction *Env = IRB.CreateLoad(IRB.getInt8PtrTy(), EnvField, "env");
Instruction *Val = IRB.CreateLoad(IRB.getInt32Ty(), ValField, "val");
BasicBlock *ThenBB = BasicBlock::Create(C, "if.then", &F);
BasicBlock *EndBB = BasicBlock::Create(C, "if.end", &F);
Value *EnvP = IRB.CreateBitCast(Env, getAddrPtrType(&M), "env.p");
Value *SetjmpID = IRB.CreateLoad(getAddrIntType(&M), EnvP, "setjmp.id");
Value *Label =
IRB.CreateCall(TestSetjmpF, {SetjmpID, SetjmpTable, SetjmpTableSize},
OperandBundleDef("funclet", CatchPad), "label");
Value *Cmp = IRB.CreateICmpEQ(Label, IRB.getInt32(0));
IRB.CreateCondBr(Cmp, ThenBB, EndBB);
IRB.SetInsertPoint(ThenBB);
CallInst *WasmLongjmpCI = IRB.CreateCall(
WasmLongjmpF, {Env, Val}, OperandBundleDef("funclet", CatchPad));
IRB.CreateUnreachable();
IRB.SetInsertPoint(EndBB);
IRB.CreateCatchRet(CatchPad, SetjmpDispatchBB);
IRB.SetInsertPoint(SetjmpDispatchBB);
PHINode *LabelPHI = IRB.CreatePHI(IRB.getInt32Ty(), 2, "label.phi");
LabelPHI->addIncoming(Label, EndBB);
LabelPHI->addIncoming(IRB.getInt32(-1), Entry);
SwitchInst *SI = IRB.CreateSwitch(LabelPHI, OrigEntry, SetjmpRetPHIs.size());
for (unsigned I = 0; I < SetjmpRetPHIs.size(); I++) {
SI->addCase(IRB.getInt32(I + 1), SetjmpRetPHIs[I]->getParent());
SetjmpRetPHIs[I]->addIncoming(Val, SetjmpDispatchBB);
}
SmallVector<CallInst *, 64> LongjmpableCalls;
for (auto *BB = &*F.begin(); BB; BB = BB->getNextNode()) {
for (auto &I : *BB) {
auto *CI = dyn_cast<CallInst>(&I);
if (!CI)
continue;
const Value *Callee = CI->getCalledOperand();
if (!canLongjmp(Callee))
continue;
if (isEmAsmCall(Callee))
report_fatal_error("Cannot use EM_ASM* alongside setjmp/longjmp in " +
F.getName() +
". Please consider using EM_JS, or move the "
"EM_ASM into another function.",
false);
if (CI == WasmLongjmpCI)
continue;
LongjmpableCalls.push_back(CI);
}
}
for (auto *CI : LongjmpableCalls) {
CI->removeFnAttr(Attribute::NoUnwind);
if (Function *CalleeF = CI->getCalledFunction())
CalleeF->removeFnAttr(Attribute::NoUnwind);
SmallVector<OperandBundleDef, 1> Bundles;
BasicBlock *UnwindDest = nullptr;
if (auto Bundle = CI->getOperandBundle(LLVMContext::OB_funclet)) {
Instruction *FromPad = cast<Instruction>(Bundle->Inputs[0]);
while (!UnwindDest) {
if (auto *CPI = dyn_cast<CatchPadInst>(FromPad)) {
UnwindDest = CPI->getCatchSwitch()->getUnwindDest();
break;
}
if (auto *CPI = dyn_cast<CleanupPadInst>(FromPad)) {
UnwindDest = getCleanupRetUnwindDest(CPI);
Value *ParentPad = CPI->getParentPad();
if (isa<ConstantTokenNone>(ParentPad))
break;
FromPad = cast<Instruction>(ParentPad);
}
}
}
if (!UnwindDest)
UnwindDest = CatchDispatchLongjmpBB;
changeToInvokeAndSplitBasicBlock(CI, UnwindDest);
}
SmallVector<Instruction *, 16> ToErase;
for (auto &BB : F) {
if (auto *CSI = dyn_cast<CatchSwitchInst>(BB.getFirstNonPHI())) {
if (CSI != CatchSwitchLongjmp && CSI->unwindsToCaller()) {
IRB.SetInsertPoint(CSI);
ToErase.push_back(CSI);
auto *NewCSI = IRB.CreateCatchSwitch(CSI->getParentPad(),
CatchDispatchLongjmpBB, 1);
NewCSI->addHandler(*CSI->handler_begin());
NewCSI->takeName(CSI);
CSI->replaceAllUsesWith(NewCSI);
}
}
if (auto *CRI = dyn_cast<CleanupReturnInst>(BB.getTerminator())) {
if (CRI->unwindsToCaller()) {
IRB.SetInsertPoint(CRI);
ToErase.push_back(CRI);
IRB.CreateCleanupRet(CRI->getCleanupPad(), CatchDispatchLongjmpBB);
}
}
}
for (Instruction *I : ToErase)
I->eraseFromParent();
}