274#include "llvm/IR/IntrinsicsWebAssembly.h"
285#define DEBUG_TYPE "wasm-lower-em-ehsjlj"
288class WebAssemblyLowerEmscriptenEHSjLjImpl {
289 bool EnableEmEH =
false;
290 bool EnableEmSjLj =
false;
291 bool EnableWasmSjLj =
false;
302 Function *WasmSetjmpTestF =
nullptr;
307 Type *LongjmpArgsTy =
nullptr;
324 void handleLongjmpableCallsForEmscriptenSjLj(
328 handleLongjmpableCallsForWasmSjLj(
Function &
F,
337 PHINode *&CallEmLongjmpBBThrewPHI,
338 PHINode *&CallEmLongjmpBBThrewValuePHI,
342 bool canLongjmp(
const Value *Callee)
const;
343 bool containsLongjmpableCalls(
const Function *
F)
const;
344 bool areAllExceptionsAllowed()
const {
return EHAllowlistSet.
empty(); }
345 bool supportsException(
const Function *
F)
const {
347 (areAllExceptionsAllowed() || EHAllowlistSet.
count(
F->getName()));
354 WebAssemblyLowerEmscriptenEHSjLjImpl(
355 const WebAssemblyOptions &CLOpts,
357 : EnableEmSjLj(CLOpts.enable_emscripten_sjlj),
358 EnableWasmSjLj(CLOpts.enable_sjlj), GetDominatorTree(GetDominatorTree) {
359 assert(!(EnableEmSjLj && EnableWasmSjLj) &&
360 "Two SjLj modes cannot be turned on at the same time");
361 EHAllowlistSet.
insert_range(CLOpts.emscripten_cxx_exceptions_allowed);
364 bool runOnModule(
Module &M);
367class WebAssemblyLowerEmscriptenEHSjLjLegacy final :
public ModulePass {
369 return "WebAssembly Lower Emscripten Exceptions";
375 WebAssemblyLowerEmscriptenEHSjLjLegacy() :
ModulePass(ID) {}
376 bool runOnModule(
Module &M)
override;
384char WebAssemblyLowerEmscriptenEHSjLjLegacy::ID = 0;
386 "WebAssembly Lower Emscripten Exceptions / Setjmp / Longjmp",
390 return new WebAssemblyLowerEmscriptenEHSjLjLegacy();
397 if (Name ==
"setjmp" || Name ==
"longjmp" || Name ==
"emscripten_longjmp")
399 return !
F->doesNotThrow();
414 return M.getOrInsertGlobal(Name, Ty, [&]() {
430 OS << *FTy->getReturnType();
431 for (
Type *ParamTy : FTy->params())
432 OS <<
"_" << *ParamTy;
452 if (!
F->hasFnAttribute(
"wasm-import-module")) {
453 llvm::AttrBuilder
B(
F->getParent()->getContext());
454 B.addAttribute(
"wasm-import-module",
"env");
457 if (!
F->hasFnAttribute(
"wasm-import-name")) {
458 llvm::AttrBuilder
B(
F->getParent()->getContext());
459 B.addAttribute(
"wasm-import-name",
F->getName());
468 return IRB.
getIntNTy(M->getDataLayout().getPointerSizeInBits());
483 return IRB.
getIntN(M->getDataLayout().getPointerSizeInBits(),
C);
489 Attribute FeaturesAttr =
F.getFnAttribute(
"target-features");
490 return FeaturesAttr.
isValid() &&
499Function *WebAssemblyLowerEmscriptenEHSjLjImpl::getFindMatchingCatch(
500 Module &M,
unsigned NumClauses) {
501 auto [It,
Inserted] = FindMatchingCatches.try_emplace(NumClauses);
504 PointerType *Int8PtrTy = PointerType::getUnqual(
M.getContext());
506 FunctionType *FTy = FunctionType::get(Int8PtrTy, Args,
false);
508 FTy,
"__cxa_find_matching_catch_" + Twine(NumClauses + 2), &M);
521Value *WebAssemblyLowerEmscriptenEHSjLjImpl::wrapInvoke(CallBase *CI) {
523 LLVMContext &
C =
M->getContext();
532 SmallVector<Value *, 16>
Args;
537 CallInst *NewCall = IRB.CreateCall(getInvokeWrapper(CI), Args);
551 ArgAttributes.
push_back(InvokeAL.getParamAttrs(
I));
553 AttrBuilder FnAttrs(CI->
getContext(), InvokeAL.getFnAttrs());
554 if (
auto Args = FnAttrs.getAllocSizeArgs()) {
557 auto [SizeArg, NEltArg] = *
Args;
560 NEltArg = *NEltArg + 1;
561 FnAttrs.addAllocSizeAttr(SizeArg, NEltArg);
565 FnAttrs.removeAttribute(Attribute::NoReturn);
568 AttributeList NewCallAL = AttributeList::get(
583Function *WebAssemblyLowerEmscriptenEHSjLjImpl::getInvokeWrapper(CallBase *CI) {
589 auto It = InvokeWrappers.find(Sig);
590 if (It != InvokeWrappers.end())
596 ArgTys.
append(CalleeFTy->param_begin(), CalleeFTy->param_end());
598 FunctionType *FTy = FunctionType::get(CalleeFTy->getReturnType(), ArgTys,
599 CalleeFTy->isVarArg());
602 InvokeWrappers[Sig] =
F;
606bool WebAssemblyLowerEmscriptenEHSjLjImpl::canLongjmp(
607 const Value *Callee)
const {
609 if (CalleeF->isIntrinsic())
618 StringRef CalleeName =
Callee->getName();
624 if (CalleeName ==
"setjmp" || CalleeName ==
"malloc" || CalleeName ==
"free")
628 if (CalleeName ==
"__resumeException" || CalleeName ==
"llvm_eh_typeid_for" ||
629 CalleeName ==
"__wasm_setjmp" || CalleeName ==
"__wasm_setjmp_test" ||
630 CalleeName ==
"getTempRet0" || CalleeName ==
"setTempRet0")
634 if (
Callee->getName().starts_with(
"__cxa_find_matching_catch_"))
669 if (CalleeName ==
"__cxa_end_catch")
670 return EnableWasmSjLj;
671 if (CalleeName ==
"__cxa_begin_catch" ||
672 CalleeName ==
"__cxa_allocate_exception" || CalleeName ==
"__cxa_throw" ||
673 CalleeName ==
"__clang_call_terminate")
678 if (CalleeName ==
"_ZSt9terminatev")
686 StringRef CalleeName = Callee->getName();
688 return CalleeName ==
"emscripten_asm_const_int" ||
689 CalleeName ==
"emscripten_asm_const_double" ||
690 CalleeName ==
"emscripten_asm_const_int_sync_on_main_thread" ||
691 CalleeName ==
"emscripten_asm_const_double_sync_on_main_thread" ||
692 CalleeName ==
"emscripten_asm_const_async_on_main_thread";
711void WebAssemblyLowerEmscriptenEHSjLjImpl::wrapTestSetjmp(
713 Value *&Label,
Value *&LongjmpResult, BasicBlock *&CallEmLongjmpBB,
714 PHINode *&CallEmLongjmpBBThrewPHI, PHINode *&CallEmLongjmpBBThrewValuePHI,
715 BasicBlock *&EndBB) {
718 LLVMContext &
C =
M->getContext();
720 IRB.SetCurrentDebugLocation(
DL);
727 Value *ThrewValue = IRB.CreateLoad(IRB.getInt32Ty(), ThrewValueGV,
728 ThrewValueGV->
getName() +
".val");
729 Value *ThrewValueCmp = IRB.CreateICmpNE(ThrewValue, IRB.getInt32(0));
730 Value *Cmp1 = IRB.CreateAnd(ThrewCmp, ThrewValueCmp,
"cmp1");
731 IRB.CreateCondBr(Cmp1, ThenBB1, ElseBB1);
734 if (!CallEmLongjmpBB) {
737 IRB.SetInsertPoint(CallEmLongjmpBB);
738 CallEmLongjmpBBThrewPHI = IRB.CreatePHI(
getAddrIntType(M), 4,
"threw.phi");
739 CallEmLongjmpBBThrewValuePHI =
740 IRB.CreatePHI(IRB.getInt32Ty(), 4,
"threwvalue.phi");
741 CallEmLongjmpBBThrewPHI->
addIncoming(Threw, ThenBB1);
742 CallEmLongjmpBBThrewValuePHI->
addIncoming(ThrewValue, ThenBB1);
743 IRB.CreateCall(EmLongjmpF,
744 {CallEmLongjmpBBThrewPHI, CallEmLongjmpBBThrewValuePHI});
745 IRB.CreateUnreachable();
747 CallEmLongjmpBBThrewPHI->
addIncoming(Threw, ThenBB1);
748 CallEmLongjmpBBThrewValuePHI->
addIncoming(ThrewValue, ThenBB1);
753 IRB.SetInsertPoint(ThenBB1);
757 Value *ThenLabel = IRB.CreateCall(WasmSetjmpTestF,
758 {ThrewPtr, FunctionInvocationId},
"label");
759 Value *Cmp2 = IRB.CreateICmpEQ(ThenLabel, IRB.getInt32(0));
760 IRB.CreateCondBr(Cmp2, CallEmLongjmpBB, EndBB2);
763 IRB.SetInsertPoint(EndBB2);
764 IRB.CreateCall(SetTempRet0F, ThrewValue);
765 IRB.CreateBr(EndBB1);
767 IRB.SetInsertPoint(ElseBB1);
768 IRB.CreateBr(EndBB1);
771 IRB.SetInsertPoint(EndBB1);
772 PHINode *LabelPHI = IRB.CreatePHI(IRB.getInt32Ty(), 2,
"label");
780 LongjmpResult = IRB.CreateCall(GetTempRet0F, {},
"longjmp_result");
783void WebAssemblyLowerEmscriptenEHSjLjImpl::rebuildSSA(
Function &
F) {
784 DominatorTree &DT = GetDominatorTree(
F);
788 for (BasicBlock &BB :
F) {
789 for (Instruction &
I : BB) {
790 if (
I.getType()->isVoidTy())
797 bool HasNonDominatedLifetimeMarker =
any_of(
I.users(), [&](User *U) {
798 auto *UserI = cast<Instruction>(U);
799 return UserI->isLifetimeStartOrEnd() && !DT.dominates(&I, UserI);
801 if (HasNonDominatedLifetimeMarker) {
803 if (UserI->isLifetimeStartOrEnd())
804 UserI->eraseFromParent();
809 unsigned VarID =
SSA.AddVariable(
I.getName(),
I.getType());
816 for (
auto &U :
I.uses()) {
819 if (UserPN->getIncomingBlock(U) == &BB)
827 SSA.RewriteAllUses(&DT);
838void WebAssemblyLowerEmscriptenEHSjLjImpl::replaceLongjmpWith(
840 assert(NewF == EmLongjmpF || NewF == WasmLongjmpF);
847 for (User *U : LongjmpF->
users()) {
850 IRB.SetInsertPoint(CI);
851 Value *Env =
nullptr;
852 if (NewF == EmLongjmpF)
856 Env = IRB.CreateBitCast(CI->
getArgOperand(0), IRB.getPtrTy(),
"env");
861 for (
auto *
I : ToErase)
862 I->eraseFromParent();
866 if (!LongjmpF->
uses().empty()) {
868 IRB.CreateBitCast(NewF, LongjmpF->
getType(),
"longjmp.cast");
873bool WebAssemblyLowerEmscriptenEHSjLjImpl::containsLongjmpableCalls(
875 for (
const auto &BB : *
F)
876 for (
const auto &
I : BB)
878 if (canLongjmp(CB->getCalledOperand()))
907 for (
auto *
I : ToErase)
908 I->eraseFromParent();
911bool WebAssemblyLowerEmscriptenEHSjLjImpl::runOnModule(
Module &M) {
912 LLVM_DEBUG(
dbgs() <<
"********** Lower Emscripten EH & SjLj **********\n");
915 if (EH != ExceptionHandling::None && EH != ExceptionHandling::Wasm &&
916 EH != ExceptionHandling::Emscripten)
918 "exception model should be 'none', 'wasm', or 'emscripten'");
920 EnableEmEH = EH == ExceptionHandling::Emscripten;
922 if (EnableEmEH && EnableWasmSjLj)
924 "'emscripten' exception model is not allowed with -wasm-enable-sjlj");
926 if (EH == ExceptionHandling::Wasm && EnableEmSjLj)
928 "'wasm' exception model is not allowed with -wasm-enable-sjlj");
935 if (EH != ExceptionHandling::Wasm && !EnableEmEH) {
937 bool LoweredInvoke =
false;
938 for (BasicBlock &BB :
F) {
941 LoweredInvoke =
true;
952 if (!EnableEmEH && !EnableEmSjLj && !EnableWasmSjLj)
957 Function *SetjmpF =
M.getFunction(
"setjmp");
958 Function *LongjmpF =
M.getFunction(
"longjmp");
963 Function *SetjmpF2 =
M.getFunction(
"_setjmp");
964 Function *LongjmpF2 =
M.getFunction(
"_longjmp");
979 "longjmp and _longjmp have different function types");
992 GetTempRet0F =
getFunction(FunctionType::get(IRB.getInt32Ty(),
false),
995 getFunction(FunctionType::get(IRB.getVoidTy(), IRB.getInt32Ty(),
false),
1003 FunctionType *ResumeFTy =
1004 FunctionType::get(IRB.getVoidTy(), IRB.getPtrTy(),
false);
1005 ResumeF =
getFunction(ResumeFTy,
"__resumeException", &M);
1006 ResumeF->
addFnAttr(Attribute::NoReturn);
1009 FunctionType *EHTypeIDTy =
1010 FunctionType::get(IRB.getInt32Ty(), IRB.getPtrTy(),
false);
1011 EHTypeIDF =
getFunction(EHTypeIDTy,
"llvm_eh_typeid_for", &M);
1016 SmallPtrSet<Function *, 4> SetjmpUsersToNullify;
1018 if ((EnableEmSjLj || EnableWasmSjLj) && SetjmpF) {
1020 for (User *U : SetjmpF->
users()) {
1022 auto *UserF = CB->getFunction();
1026 if (containsLongjmpableCalls(UserF))
1027 SetjmpUsers.insert(UserF);
1029 SetjmpUsersToNullify.
insert(UserF);
1032 raw_string_ostream
SS(S);
1040 bool SetjmpUsed = SetjmpF && !SetjmpUsers.empty();
1041 bool LongjmpUsed = LongjmpF && !LongjmpF->
use_empty();
1042 DoSjLj = (EnableEmSjLj | EnableWasmSjLj) && (SetjmpUsed || LongjmpUsed);
1046 assert(EnableEmSjLj || EnableWasmSjLj);
1050 FunctionType *FTy = FunctionType::get(
1051 IRB.getVoidTy(), {getAddrIntType(&M), IRB.getInt32Ty()},
false);
1052 EmLongjmpF =
getFunction(FTy,
"emscripten_longjmp", &M);
1053 EmLongjmpF->
addFnAttr(Attribute::NoReturn);
1055 Type *Int8PtrTy = IRB.getPtrTy();
1057 FunctionType *FTy = FunctionType::get(
1058 IRB.getVoidTy(), {Int8PtrTy, IRB.getInt32Ty()},
false);
1059 WasmLongjmpF =
getFunction(FTy,
"__wasm_longjmp", &M);
1060 WasmLongjmpF->
addFnAttr(Attribute::NoReturn);
1063 if (EnableWasmSjLj) {
1064 for (
auto *SjLjF : {SetjmpF, LongjmpF}) {
1066 for (User *U : SjLjF->users()) {
1071 " is using setjmp/longjmp but does not have "
1072 "+exception-handling target feature");
1080 Type *Int8PtrTy = IRB.getPtrTy();
1081 Type *Int32PtrTy = IRB.getPtrTy();
1086 FunctionType *FTy = FunctionType::get(
1087 IRB.getVoidTy(), {SetjmpFTy->getParamType(0), Int32Ty, Int32PtrTy},
1089 WasmSetjmpF =
getFunction(FTy,
"__wasm_setjmp", &M);
1092 FTy = FunctionType::get(Int32Ty, {Int32PtrTy, Int32PtrTy},
false);
1093 WasmSetjmpTestF =
getFunction(FTy,
"__wasm_setjmp_test", &M);
1108 if (
F.isDeclaration())
1118 replaceLongjmpWith(LongjmpF, EnableEmSjLj ? EmLongjmpF : WasmLongjmpF);
1123 runSjLjOnFunction(*
F);
1127 if ((EnableEmSjLj || EnableWasmSjLj) && !SetjmpUsersToNullify.
empty()) {
1130 for (
Function *
F : SetjmpUsersToNullify)
1135 for (
auto *
V : {ThrewGV, ThrewValueGV})
1136 if (
V &&
V->use_empty())
1137 V->eraseFromParent();
1138 for (
auto *
V : {GetTempRet0F, SetTempRet0F, ResumeF, EHTypeIDF, EmLongjmpF,
1139 WasmSetjmpF, WasmSetjmpTestF, WasmLongjmpF, CatchF})
1140 if (
V &&
V->use_empty())
1141 V->eraseFromParent();
1146bool WebAssemblyLowerEmscriptenEHSjLjImpl::runEHOnFunction(
Function &
F) {
1148 LLVMContext &
C =
F.getContext();
1152 SmallPtrSet<LandingPadInst *, 32> LandingPads;
1158 PHINode *RethrowLongjmpBBThrewPHI =
nullptr;
1160 for (BasicBlock &BB :
F) {
1165 LandingPads.
insert(
II->getLandingPadInst());
1166 IRB.SetInsertPoint(
II);
1169 bool NeedInvoke = supportsException(&
F) &&
canThrow(Callee);
1172 Value *Threw = wrapInvoke(
II);
1195 if (DoSjLj && EnableEmSjLj && !SetjmpUsers.count(&
F) &&
1196 canLongjmp(Callee)) {
1198 if (!RethrowLongjmpBB) {
1200 IRB.SetInsertPoint(RethrowLongjmpBB);
1201 RethrowLongjmpBBThrewPHI =
1203 RethrowLongjmpBBThrewPHI->
addIncoming(Threw, &BB);
1204 Value *ThrewValue = IRB.CreateLoad(IRB.getInt32Ty(), ThrewValueGV,
1205 ThrewValueGV->
getName() +
".val");
1206 IRB.CreateCall(EmLongjmpF, {RethrowLongjmpBBThrewPHI, ThrewValue});
1207 IRB.CreateUnreachable();
1209 RethrowLongjmpBBThrewPHI->
addIncoming(Threw, &BB);
1212 IRB.SetInsertPoint(
II);
1218 Value *
Or = IRB.CreateOr(CmpEqZero, CmpEqOne,
"or");
1219 IRB.CreateCondBr(
Or, Tail, RethrowLongjmpBB);
1220 IRB.SetInsertPoint(Tail);
1221 BB.replaceSuccessorsPhiUsesWith(&BB, Tail);
1226 IRB.CreateCondBr(Cmp,
II->getUnwindDest(),
II->getNormalDest());
1236 for (BasicBlock &BB :
F) {
1238 for (Instruction &
I : BB) {
1246 IRB.SetInsertPoint(RI);
1247 Value *
Low = IRB.CreateExtractValue(Input, 0,
"low");
1249 IRB.CreateCall(ResumeF, {
Low});
1251 IRB.CreateUnreachable();
1257 for (BasicBlock &BB :
F) {
1258 for (Instruction &
I : BB) {
1265 if (
Callee->getIntrinsicID() != Intrinsic::eh_typeid_for)
1269 IRB.SetInsertPoint(CI);
1278 for (BasicBlock &BB :
F) {
1287 for (LandingPadInst *LPI : LandingPads) {
1288 IRB.SetInsertPoint(LPI);
1289 SmallVector<Value *, 16> FMCArgs;
1290 for (
unsigned I = 0,
E = LPI->getNumClauses();
I <
E; ++
I) {
1294 if (LPI->isCatch(
I))
1299 Function *FMCF = getFindMatchingCatch(M, FMCArgs.
size());
1300 CallInst *FMCI = IRB.CreateCall(FMCF, FMCArgs,
"fmc");
1302 Value *Pair0 = IRB.CreateInsertValue(Poison, FMCI, 0,
"pair0");
1303 Value *TempRet0 = IRB.CreateCall(GetTempRet0F, {},
"tempret0");
1304 Value *Pair1 = IRB.CreateInsertValue(Pair0, TempRet0, 1,
"pair1");
1306 LPI->replaceAllUsesWith(Pair1);
1311 for (Instruction *
I : ToErase)
1312 I->eraseFromParent();
1338bool WebAssemblyLowerEmscriptenEHSjLjImpl::runSjLjOnFunction(
Function &
F) {
1339 assert(EnableEmSjLj || EnableWasmSjLj);
1346 SmallVector<AllocaInst *> StaticAllocas;
1347 for (Instruction &
I :
F.getEntryBlock())
1349 if (AI->isStaticAlloca())
1357 for (AllocaInst *AI : StaticAllocas)
1358 AI->moveBefore(
Entry->getTerminator()->getIterator());
1360 IRB.SetInsertPoint(
Entry->getTerminator()->getIterator());
1365 IRB.CreateAlloca(IRB.getInt32Ty(),
nullptr,
"functionInvocationId");
1370 Function *SetjmpF =
M.getFunction(
"setjmp");
1378 raw_string_ostream
SS(S);
1379 SS <<
"In function " +
F.getName() +
1380 ": setjmp within a catch clause is not supported in Wasm EH:\n";
1385 CallInst *CI =
nullptr;
1398 IRB.SetInsertPoint(
Tail->getFirstNonPHIIt());
1399 PHINode *SetjmpRet = IRB.CreatePHI(IRB.getInt32Ty(), 2,
"setjmp.ret");
1411 IRB.SetInsertPoint(CI);
1413 FunctionInvocationId};
1414 IRB.CreateCall(WasmSetjmpF, Args);
1420 handleLongjmpableCallsForEmscriptenSjLj(
F, FunctionInvocationId,
1423 handleLongjmpableCallsForWasmSjLj(
F, FunctionInvocationId, SetjmpRetPHIs);
1426 for (Instruction *
I : ToErase)
1427 I->eraseFromParent();
1446void WebAssemblyLowerEmscriptenEHSjLjImpl::
1447 handleLongjmpableCallsForEmscriptenSjLj(
1448 Function &
F, Instruction *FunctionInvocationId,
1449 SmallVectorImpl<PHINode *> &SetjmpRetPHIs) {
1451 LLVMContext &
C =
F.getContext();
1459 PHINode *CallEmLongjmpBBThrewPHI =
nullptr;
1462 PHINode *CallEmLongjmpBBThrewValuePHI =
nullptr;
1469 std::vector<BasicBlock *> BBs;
1470 for (BasicBlock &BB :
F)
1474 for (
unsigned I = 0;
I < BBs.size();
I++) {
1476 for (Instruction &
I : *BB) {
1483 if (!canLongjmp(Callee))
1488 ". Please consider using EM_JS, or move the "
1489 "EM_ASM into another function.",
1492 Value *Threw =
nullptr;
1494 if (
Callee->getName().starts_with(
"__invoke_")) {
1499 LoadInst *ThrewLI =
nullptr;
1500 StoreInst *ThrewResetSI =
nullptr;
1505 if (GV == ThrewGV) {
1506 Threw = ThrewLI = LI;
1516 if (GV == ThrewGV &&
1524 assert(Threw && ThrewLI &&
"Cannot find __THREW__ load after invoke");
1525 assert(ThrewResetSI &&
"Cannot find __THREW__ store after invoke");
1530 Threw = wrapInvoke(CI);
1555 if (supportsException(&
F) &&
canThrow(Callee)) {
1561 if (!RethrowExnBB) {
1563 IRB.SetInsertPoint(RethrowExnBB);
1565 IRB.CreateCall(getFindMatchingCatch(M, 0), {},
"exn");
1566 IRB.CreateCall(ResumeF, {Exn});
1567 IRB.CreateUnreachable();
1570 IRB.SetInsertPoint(CI);
1574 IRB.CreateCondBr(CmpEqOne, RethrowExnBB, NormalBB);
1576 IRB.SetInsertPoint(NormalBB);
1591 Value *LongjmpResult =
nullptr;
1593 wrapTestSetjmp(BB, CI->
getDebugLoc(), Threw, FunctionInvocationId, Label,
1594 LongjmpResult, CallEmLongjmpBB, CallEmLongjmpBBThrewPHI,
1595 CallEmLongjmpBBThrewValuePHI, EndBB);
1596 assert(Label && LongjmpResult && EndBB);
1599 IRB.SetInsertPoint(EndBB);
1601 SwitchInst *
SI = IRB.CreateSwitch(Label, Tail, SetjmpRetPHIs.
size());
1606 for (
unsigned I = 0;
I < SetjmpRetPHIs.
size();
I++) {
1607 SI->addCase(IRB.getInt32(
I + 1), SetjmpRetPHIs[
I]->getParent());
1608 SetjmpRetPHIs[
I]->addIncoming(LongjmpResult, EndBB);
1613 BBs.push_back(Tail);
1617 for (Instruction *
I : ToErase)
1618 I->eraseFromParent();
1624 return CRI->getUnwindDest();
1633void WebAssemblyLowerEmscriptenEHSjLjImpl::handleLongjmpableCallsForWasmSjLj(
1634 Function &
F, Instruction *FunctionInvocationId,
1635 SmallVectorImpl<PHINode *> &SetjmpRetPHIs) {
1637 LLVMContext &
C =
F.getContext();
1639 IRB.disableGEPCanonicalization();
1645 if (!
F.hasPersonalityFn()) {
1647 FunctionType *PersType =
1648 FunctionType::get(IRB.getInt32Ty(),
true);
1649 Value *PersF =
M.getOrInsertFunction(PersName, PersType).getCallee();
1657 IRB.SetCurrentDebugLocation(FirstDL);
1678 IRB.SetInsertPoint(CatchDispatchLongjmpBB);
1679 CatchSwitchInst *CatchSwitchLongjmp =
1684 CatchSwitchLongjmp->
addHandler(CatchLongjmpBB);
1685 IRB.SetInsertPoint(CatchLongjmpBB);
1686 CatchPadInst *CatchPad = IRB.CreateCatchPad(CatchSwitchLongjmp, {});
1695 IRB.CreateConstGEP2_32(LongjmpArgsTy, LongjmpArgs, 0, 0,
"env_gep");
1697 IRB.CreateConstGEP2_32(LongjmpArgsTy, LongjmpArgs, 0, 1,
"val_gep");
1699 Instruction *Env = IRB.CreateLoad(IRB.getPtrTy(), EnvField,
"env");
1701 Instruction *Val = IRB.CreateLoad(IRB.getInt32Ty(), ValField,
"val");
1710 Value *
Label = IRB.CreateCall(WasmSetjmpTestF, {EnvP, FunctionInvocationId},
1712 Value *
Cmp = IRB.CreateICmpEQ(Label, IRB.getInt32(0));
1713 IRB.CreateCondBr(Cmp, ThenBB, EndBB);
1715 IRB.SetInsertPoint(ThenBB);
1716 CallInst *WasmLongjmpCI = IRB.CreateCall(
1718 IRB.CreateUnreachable();
1720 IRB.SetInsertPoint(EndBB);
1722 IRB.CreateCatchRet(CatchPad, SetjmpDispatchBB);
1732 IRB.SetInsertPoint(SetjmpDispatchBB);
1733 PHINode *LabelPHI = IRB.CreatePHI(IRB.getInt32Ty(), 2,
"label.phi");
1736 SwitchInst *
SI = IRB.CreateSwitch(LabelPHI, OrigEntry, SetjmpRetPHIs.
size());
1741 for (
unsigned I = 0;
I < SetjmpRetPHIs.
size();
I++) {
1742 SI->addCase(IRB.getInt32(
I + 1), SetjmpRetPHIs[
I]->getParent());
1743 SetjmpRetPHIs[
I]->addIncoming(Val, SetjmpDispatchBB);
1749 for (
auto *BB = &*
F.begin(); BB; BB = BB->getNextNode()) {
1750 for (
auto &
I : *BB) {
1755 if (!canLongjmp(Callee))
1760 ". Please consider using EM_JS, or move the "
1761 "EM_ASM into another function.",
1766 if (CI == WasmLongjmpCI)
1772 SmallMapVector<BasicBlock *, SmallSetVector<BasicBlock *, 4>, 4>
1773 UnwindDestToNewPreds;
1774 for (
auto *CI : LongjmpableCalls) {
1780 CalleeF->removeFnAttr(Attribute::NoUnwind);
1789 while (!UnwindDest) {
1791 UnwindDest = CPI->getCatchSwitch()->getUnwindDest();
1801 Value *ParentPad = CPI->getParentPad();
1809 UnwindDest = CatchDispatchLongjmpBB;
1818 SmallVector<Instruction *, 16> ToErase;
1819 for (
auto &BB :
F) {
1821 if (CSI != CatchSwitchLongjmp && CSI->unwindsToCaller()) {
1822 IRB.SetInsertPoint(CSI);
1824 auto *NewCSI = IRB.CreateCatchSwitch(CSI->getParentPad(),
1825 CatchDispatchLongjmpBB, 1);
1826 NewCSI->addHandler(*CSI->handler_begin());
1827 NewCSI->takeName(CSI);
1828 CSI->replaceAllUsesWith(NewCSI);
1833 if (CRI->unwindsToCaller()) {
1834 IRB.SetInsertPoint(CRI);
1836 IRB.CreateCleanupRet(CRI->getCleanupPad(), CatchDispatchLongjmpBB);
1841 for (Instruction *
I : ToErase)
1842 I->eraseFromParent();
1850 for (
auto &[UnwindDest, NewPreds] : UnwindDestToNewPreds) {
1851 for (PHINode &PN : UnwindDest->
phis()) {
1852 for (
auto *NewPred : NewPreds) {
1853 assert(PN.getBasicBlockIndex(NewPred) == -1);
1864 for (
auto &[UnwindDest, NewPreds] : UnwindDestToNewPreds) {
1865 for (PHINode &PN : UnwindDest->
phis()) {
1867 SSA.Initialize(PN.getType(), PN.getName());
1868 for (
unsigned Idx = 0,
E = PN.getNumIncomingValues(); Idx !=
E; ++Idx) {
1869 if (NewPreds.contains(PN.getIncomingBlock(Idx)))
1871 Value *
V = PN.getIncomingValue(Idx);
1873 SSA.AddAvailableValue(
II->getNormalDest(),
II);
1875 SSA.AddAvailableValue(
I->getParent(),
I);
1877 SSA.AddAvailableValue(PN.getIncomingBlock(Idx),
V);
1879 for (
auto *NewPred : NewPreds)
1880 PN.setIncomingValueForBlock(NewPred,
SSA.GetValueAtEndOfBlock(NewPred));
1886bool WebAssemblyLowerEmscriptenEHSjLjLegacy::runOnModule(
Module &M) {
1887 WebAssemblyLowerEmscriptenEHSjLjImpl Impl(
1889 return getAnalysis<DominatorTreeWrapperPass>(
F).getDomTree();
1891 return Impl.runOnModule(M);
1897 WebAssemblyLowerEmscriptenEHSjLjImpl Impl(
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file defines the DenseSet and SmallDenseSet classes.
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
uint64_t IntrinsicInst * II
ModuleAnalysisManager MAM
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
static void nullifySetjmp(Function *F)
static void markAsImported(Function *F)
static bool hasEHTargetFeatureAttr(const Function &F)
static Type * getAddrPtrType(Module *M)
static std::string getSignature(FunctionType *FTy)
static Type * getAddrIntType(Module *M)
static bool canThrow(const Value *V)
static Function * getFunction(FunctionType *Ty, const Twine &Name, Module *M)
static DebugLoc getOrCreateDebugLoc(const Instruction *InsertBefore, DISubprogram *SP)
static GlobalVariable * getGlobalVariable(Module &M, Type *Ty, const char *Name)
static Value * getAddrSizeInt(Module *M, uint64_t C)
static bool isEmAsmCall(const Value *Callee)
This file contains the entry points for global functions defined in the LLVM WebAssembly back-end.
static BasicBlock * getCleanupRetUnwindDest(const CleanupPadInst *CleanupPad)
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
static LLVM_ABI AttributeSet get(LLVMContext &C, const AttrBuilder &B)
Functions, function parameters, and return types can have attributes to indicate how they should be t...
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
bool isValid() const
Return true if the attribute is any kind of attribute.
LLVM Basic Block Representation.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
const Function * getParent() const
Return the enclosing method, or null if none.
const Instruction & back() const
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
InstListType::iterator iterator
Instruction iterators...
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
void setCallingConv(CallingConv::ID CC)
std::optional< OperandBundleUse > getOperandBundle(StringRef Name) const
Return an operand bundle by name, if present.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
Value * getCalledOperand() const
void setAttributes(AttributeList A)
Set the attributes for this call.
Value * getArgOperand(unsigned i) const
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
FunctionType * getFunctionType() const
void removeFnAttr(Attribute::AttrKind Kind)
Removes the attribute from the function.
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
This class represents a function call, abstracting a target machine's calling convention.
LLVM_ABI void addHandler(BasicBlock *Dest)
Add an entry to the switch instruction... Note: This action invalidates handler_end().
static LLVM_ABI ConstantTokenNone * get(LLVMContext &Context)
Return the ConstantTokenNone.
Subprogram description. Uses SubclassData1.
Implements a dense probed hash-table based set.
Analysis pass which computes a DominatorTree.
void recalculate(ParentType &Func)
recalculate - compute a dominator tree for the given function
Legacy analysis pass which computes a DominatorTree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
FunctionType * getFunctionType() const
Returns the FunctionType for me.
const Function & getFunction() const
Module * getParent()
Get the module that this global value is contained inside of...
PointerType * getType() const
Global values are always pointers.
@ ExternalLinkage
Externally visible function.
IntegerType * getIntNTy(unsigned N)
Fetch the type representing an N-bit integer.
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
ConstantInt * getIntN(unsigned N, uint64_t C)
Get a constant N-bit value, zero extended from a 64-bit value.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
iterator_range< user_iterator > users()
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
A Module instance is used to store all the information related to an LLVM module.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Represent a constant reference to a string, i.e.
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
LLVM Value Representation.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVMContext & getContext() const
All values hold a context through their type.
iterator_range< user_iterator > users()
iterator_range< use_iterator > uses()
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
void insert_range(Range &&R)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
const ParentTy * getParent() const
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
Pass manager infrastructure for declaring and invalidating analyses.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
@ BasicBlock
Various leaf nodes.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
@ User
could "use" a pointer
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
LLVM_ABI StringRef getEHPersonalityName(EHPersonality Pers)
LLVM_ABI BasicBlock * changeToInvokeAndSplitBasicBlock(CallInst *CI, BasicBlock *UnwindEdge, DomTreeUpdater *DTU=nullptr)
Convert the CallInst to InvokeInst with the specified unwind edge basic block.
const WebAssemblyOptions & getWebAssemblyOptions(const LLVMContext &C)
DebugVariableAggregate VarID
A unique key that represents one instance of a debug variable.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI CallInst * changeToCall(InvokeInst *II, DomTreeUpdater *DTU=nullptr)
This function converts the specified invoke into a normal call.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI bool EliminateUnreachableBlocks(Function &F, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete all basic blocks from F that are not reachable from its entry node.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
OperandBundleDefT< Value * > OperandBundleDef
void replace(R &&Range, const T &OldValue, const T &NewValue)
Provide wrappers to std::replace which take ranges instead of having to pass begin/end explicitly.
@ Or
Bitwise or logical OR of integers.
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
ModulePass * createWebAssemblyLowerEmscriptenEHSjLjLegacyPass()
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
bool isSpace(char C)
Checks whether character C is whitespace in the "C" locale.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.