215 using namespace llvm;
217 #define DEBUG_TYPE "wasm-lower-em-ehsjlj" 221 cl::desc(
"The list of function names in which Emscripten-style " 222 "exception handling is enabled (see emscripten " 223 "EMSCRIPTEN_CATCHING_WHITELIST options)"),
227 class WebAssemblyLowerEmscriptenEHSjLj final :
public ModulePass {
228 static const char *ResumeFName;
229 static const char *EHTypeIDFName;
230 static const char *EmLongjmpFName;
231 static const char *EmLongjmpJmpbufFName;
232 static const char *SaveSetjmpFName;
233 static const char *TestSetjmpFName;
234 static const char *FindMatchingCatchPrefix;
235 static const char *InvokePrefix;
256 std::set<std::string> EHWhitelistSet;
259 return "WebAssembly Lower Emscripten Exceptions";
266 template <
typename CallOrInvoke>
Value *wrapInvoke(CallOrInvoke *CI);
270 template <
typename CallOrInvoke>
Function *getInvokeWrapper(CallOrInvoke *CI);
272 bool areAllExceptionsAllowed()
const {
return EHWhitelistSet.empty(); }
275 void createSetThrewFunction(
Module &M);
276 void createSetTempRet0Function(
Module &M);
283 WebAssemblyLowerEmscriptenEHSjLj(
bool EnableEH =
true,
bool EnableSjLj =
true)
284 :
ModulePass(ID), EnableEH(EnableEH), EnableSjLj(EnableSjLj),
285 ThrewGV(nullptr), ThrewValueGV(nullptr), TempRet0GV(nullptr),
286 ResumeF(nullptr), EHTypeIDF(nullptr), EmLongjmpF(nullptr),
287 EmLongjmpJmpbufF(nullptr), SaveSetjmpF(nullptr), TestSetjmpF(nullptr) {
290 bool runOnModule(
Module &M)
override;
298 const char *WebAssemblyLowerEmscriptenEHSjLj::ResumeFName =
"__resumeException";
299 const char *WebAssemblyLowerEmscriptenEHSjLj::EHTypeIDFName =
300 "llvm_eh_typeid_for";
301 const char *WebAssemblyLowerEmscriptenEHSjLj::EmLongjmpFName =
302 "emscripten_longjmp";
303 const char *WebAssemblyLowerEmscriptenEHSjLj::EmLongjmpJmpbufFName =
304 "emscripten_longjmp_jmpbuf";
305 const char *WebAssemblyLowerEmscriptenEHSjLj::SaveSetjmpFName =
"saveSetjmp";
306 const char *WebAssemblyLowerEmscriptenEHSjLj::TestSetjmpFName =
"testSetjmp";
307 const char *WebAssemblyLowerEmscriptenEHSjLj::FindMatchingCatchPrefix =
308 "__cxa_find_matching_catch_";
309 const char *WebAssemblyLowerEmscriptenEHSjLj::InvokePrefix =
"__invoke_";
313 "WebAssembly Lower Emscripten Exceptions / Setjmp / Longjmp",
318 return new WebAssemblyLowerEmscriptenEHSjLj(EnableEH, EnableSjLj);
322 if (
const auto *
F = dyn_cast<const Function>(V)) {
324 if (
F->isIntrinsic())
328 if (Name ==
"setjmp" || Name ==
"longjmp")
330 return !
F->doesNotThrow();
355 OS <<
"_" << *ParamTy;
359 Sig.erase(
remove_if(Sig, isspace), Sig.end());
372 WebAssemblyLowerEmscriptenEHSjLj::getFindMatchingCatch(
Module &M,
373 unsigned NumClauses) {
374 if (FindMatchingCatches.
count(NumClauses))
375 return FindMatchingCatches[NumClauses];
381 FindMatchingCatchPrefix +
Twine(NumClauses + 2), &M);
382 FindMatchingCatches[NumClauses] =
F;
393 template <
typename CallOrInvoke>
394 Value *WebAssemblyLowerEmscriptenEHSjLj::wrapInvoke(CallOrInvoke *CI) {
400 if (CI->doesNotReturn()) {
401 if (
auto *
F = dyn_cast<Function>(CI->getCalledValue()))
402 F->removeFnAttr(Attribute::NoReturn);
418 Args.
append(CI->arg_begin(), CI->arg_end());
432 for (
unsigned i = 0, e = CI->getNumArgOperands(); i < e; ++i)
441 CI->replaceAllUsesWith(NewCall);
451 template <
typename CallOrInvoke>
452 Function *WebAssemblyLowerEmscriptenEHSjLj::getInvokeWrapper(CallOrInvoke *CI) {
453 Module *M = CI->getModule();
457 if (
auto *
F = dyn_cast<Function>(Callee))
458 CalleeFTy =
F->getFunctionType();
460 auto *CalleeTy = cast<PointerType>(Callee->
getType())->getElementType();
465 if (InvokeWrappers.
find(Sig) != InvokeWrappers.
end())
466 return InvokeWrappers[Sig];
476 InvokePrefix + Sig, M);
477 InvokeWrappers[Sig] =
F;
481 bool WebAssemblyLowerEmscriptenEHSjLj::canLongjmp(
Module &M,
483 if (
auto *CalleeF = dyn_cast<Function>(Callee))
484 if (CalleeF->isIntrinsic())
492 if (Callee == SetjmpF || Callee == MallocF || Callee == FreeF)
496 if (Callee == ResumeF || Callee == EHTypeIDF || Callee == SaveSetjmpF ||
497 Callee == TestSetjmpF)
510 if (Callee == BeginCatchF || Callee == EndCatchF ||
511 Callee == AllocExceptionF || Callee == ThrowF || Callee == TerminateF)
532 void WebAssemblyLowerEmscriptenEHSjLj::wrapTestSetjmp(
563 TestSetjmpF, {LoadedThrew, SetjmpTable, SetjmpTableSize},
"label");
569 IRB.
CreateCall(EmLongjmpF, {Threw, ThrewValue});
590 LongjmpResult = IRB.
CreateLoad(TempRet0GV,
"longjmp_result");
600 void WebAssemblyLowerEmscriptenEHSjLj::createSetThrewFunction(
Module &M) {
611 Argument *Arg1 = &*(F->arg_begin());
612 Argument *Arg2 = &*std::next(F->arg_begin());
637 void WebAssemblyLowerEmscriptenEHSjLj::createSetTempRet0Function(
Module &M) {
647 F->arg_begin()->setName(
"value");
654 void WebAssemblyLowerEmscriptenEHSjLj::rebuildSSA(
Function &
F) {
655 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(
F).getDomTree();
660 for (
auto UI =
I.use_begin(), UE =
I.use_end(); UI != UE;) {
669 if (
PHINode *UserPN = dyn_cast<PHINode>(User))
670 if (UserPN->getIncomingBlock(U) == &BB)
681 bool WebAssemblyLowerEmscriptenEHSjLj::runOnModule(
Module &M) {
687 bool SetjmpUsed = SetjmpF && !SetjmpF->
use_empty();
688 bool LongjmpUsed = LongjmpF && !LongjmpF->
use_empty();
689 bool DoSjLj = EnableSjLj && (SetjmpUsed || LongjmpUsed);
697 bool Changed =
false;
716 Changed |= runEHOnFunction(F);
732 SaveSetjmpFName, &M);
738 TestSetjmpFName, &M);
745 EmLongjmpJmpbufFName, &M);
758 auto *UI = cast<Instruction>(U);
759 SetjmpUsers.
insert(UI->getFunction());
762 runSjLjOnFunction(*F);
767 ThrewGV->eraseFromParent();
786 createSetThrewFunction(M);
787 createSetTempRet0Function(M);
792 bool WebAssemblyLowerEmscriptenEHSjLj::runEHOnFunction(
Function &F) {
796 bool Changed =
false;
799 bool AllowExceptions =
800 areAllExceptionsAllowed() || EHWhitelistSet.
count(F.
getName());
807 LandingPads.
insert(II->getLandingPadInst());
810 bool NeedInvoke = AllowExceptions &&
canThrow(II->getCalledValue());
813 Value *Threw = wrapInvoke(II);
818 IRB.
CreateCondBr(Cmp, II->getUnwindDest(), II->getNormalDest());
825 NewCall->takeName(II);
826 NewCall->setCallingConv(II->getCallingConv());
827 NewCall->setDebugLoc(II->getDebugLoc());
828 NewCall->setAttributes(II->getAttributes());
829 II->replaceAllUsesWith(NewCall);
835 II->getUnwindDest()->removePredecessor(&BB);
848 Value *Input = RI->getValue();
865 const Function *Callee = CI->getCalledFunction();
873 IRB.
CreateCall(EHTypeIDF, CI->getArgOperand(0),
"typeid");
882 if (
auto *LPI = dyn_cast<LandingPadInst>(I))
891 for (
unsigned i = 0, e = LPI->getNumClauses(); i < e; ++i) {
892 Constant *Clause = LPI->getClause(i);
896 if (LPI->isFilter(i)) {
897 auto *ATy = cast<ArrayType>(Clause->
getType());
898 for (
unsigned j = 0, e = ATy->getNumElements(); j < e; ++j) {
907 Function *FMCF = getFindMatchingCatch(M, FMCArgs.
size());
921 I->eraseFromParent();
926 bool WebAssemblyLowerEmscriptenEHSjLj::runSjLjOnFunction(
Function &F) {
932 std::vector<Instruction *> SetjmpTableInsts;
934 std::vector<Instruction *> SetjmpTableSizeInsts;
949 nullptr,
nullptr,
"setjmpTable");
953 SetjmpTableInsts.push_back(SetjmpTable);
954 SetjmpTableSizeInsts.push_back(SetjmpTableSize);
957 std::vector<PHINode *> SetjmpRetPHIs;
980 CI->replaceAllUsesWith(SetjmpRet);
982 SetjmpRetPHIs.push_back(SetjmpRet);
989 SetjmpTable, SetjmpTableSize};
991 IRB.
CreateCall(SaveSetjmpF, Args,
"setjmpTable");
993 IRB.
CreateLoad(TempRet0GV,
"setjmpTableSize");
994 SetjmpTableInsts.push_back(NewSetjmpTable);
995 SetjmpTableSizeInsts.push_back(NewSetjmpTableSize);
1005 std::vector<BasicBlock *> BBs;
1010 for (
unsigned i = 0; i < BBs.size(); i++) {
1018 const Value *Callee = CI->getCalledValue();
1019 if (!canLongjmp(M, Callee))
1022 Value *Threw =
nullptr;
1033 if (
auto *LI = dyn_cast<LoadInst>(
I))
1034 if (
auto *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand()))
1035 if (GV == ThrewGV) {
1036 Threw = ThrewLI = LI;
1044 if (
auto *
SI = dyn_cast<StoreInst>(
I))
1045 if (
auto *GV = dyn_cast<GlobalVariable>(
SI->getPointerOperand()))
1046 if (GV == ThrewGV &&
SI->getValueOperand() == IRB.
getInt32(0)) {
1051 assert(Threw && ThrewLI &&
"Cannot find __THREW__ load after invoke");
1052 assert(ThrewResetSI &&
"Cannot find __THREW__ store after invoke");
1057 Threw = wrapInvoke(CI);
1070 Value *Label =
nullptr;
1071 Value *LongjmpResult =
nullptr;
1073 wrapTestSetjmp(BB, CI, Threw, SetjmpTable, SetjmpTableSize, Label,
1074 LongjmpResult, EndBB);
1075 assert(Label && LongjmpResult && EndBB);
1084 for (
unsigned i = 0; i < SetjmpRetPHIs.size(); i++) {
1086 SetjmpRetPHIs[i]->addIncoming(LongjmpResult, EndBB);
1091 BBs.push_back(Tail);
1097 I->eraseFromParent();
1102 if (isa<ReturnInst>(TI))
1127 for (
auto UI = SetjmpTable->use_begin(), UE = SetjmpTable->use_end();
1134 if (
I->getParent() != &EntryBB)
1137 for (
auto UI = SetjmpTableSize->
use_begin(), UE = SetjmpTableSize->
use_end();
1142 if (
I->getParent() != &EntryBB)
void push_back(const T &Elt)
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Helper class for SSA formation on a set of values defined in multiple blocks.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
ModulePass * createWebAssemblyLowerEmscriptenEHSjLj(bool DoEH, bool DoSjLj)
This class represents an incoming formal argument to a Function.
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Compute iterated dominance frontiers using a linear time algorithm.
BasicBlock * SplitBlock(BasicBlock *Old, Instruction *SplitPt, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the specified block at the specified instruction - everything before SplitPt stays in Old and e...
Type * getParamType(unsigned i) const
Parameter type accessors.
void Initialize(Type *Ty, StringRef Name)
Reset this object to get ready for a new set of SSA updates with type 'Ty'.
A Module instance is used to store all the information related to an LLVM module. ...
Same, but only replaced by something equivalent.
void AddAvailableValue(BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value...
void addCase(ConstantInt *OnVal, BasicBlock *Dest)
Add an entry to the switch instruction.
void recalculate(ParentType &Func)
recalculate - compute a dominator tree for the given function
This class represents a function call, abstracting a target machine's calling convention.
static PointerType * getInt32PtrTy(LLVMContext &C, unsigned AS=0)
const GlobalVariable * getNamedGlobal(StringRef Name) const
Return the global variable in the module with the specified name, of arbitrary type.
iterator find(StringRef Key)
Externally visible function.
param_iterator param_end() const
An instruction for reading from memory.
static Instruction * CreateFree(Value *Source, Instruction *InsertBefore)
Generate the IR for a call to the builtin free function.
This file contains the entry points for global functions defined in the LLVM WebAssembly back-end...
static bool canThrow(const Value *V)
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
AnalysisUsage & addRequired()
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
LLVMContext & getContext() const
Get the global data context.
A Use represents the edge between a Value definition and its users.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
AttributeSet getRetAttributes() const
The attributes for the ret value are returned.
void setName(const Twine &Name)
Change the name of the value.
Type * getVoidTy()
Fetch the type representing void.
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
Class to represent function types.
Type * getType() const
All values are typed, get the type of this value.
AttributeSet getParamAttributes(unsigned ArgNo) const
The attributes for the argument or parameter at the given index are returned.
void setAttributes(AttributeList A)
Set the parameter attributes for this call.
An instruction for storing to memory.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
void takeName(Value *V)
Transfer the name from V to this value.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
amdgpu Simplify well known AMD library false Value * Callee
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Class to represent pointers.
AttributeSet getAttributes(unsigned Index) const
The attributes for the specified index are returned.
const BasicBlock & getEntryBlock() const
LoadInst * CreateLoad(Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ptr, "...")' correctly, instead of converting the string to 'bool' fo...
The landingpad instruction holds all of the information necessary to generate correct exception handl...
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
Subclasses of this class are all able to terminate a basic block.
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
This is an important class for using LLVM in a threaded context.
void RewriteUseAfterInsertions(Use &U)
Rewrite a use like RewriteUse but handling in-block definitions.
UnreachableInst * CreateUnreachable()
This is an important base class in LLVM.
Resume the propagation of an exception.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
ArrayRef< Type * > params() const
param_iterator param_begin() const
Represent the analysis usage information of a pass.
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
auto remove_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly...
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
PointerType * getInt8PtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer to an 8-bit integer value.
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
std::string & str()
Flushes the stream contents to the target string and returns the string's reference.
void setCallingConv(CallingConv::ID CC)
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the generic address space (address sp...
static GlobalVariable * createGlobalVariableI32(Module &M, IRBuilder<> &IRB, const char *Name)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Type * getReturnType() const
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
FunctionType * getFunctionType() const
Returns the FunctionType for me.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), Instruction *InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
iterator_range< user_iterator > users()
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
static Instruction * CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy, Type *AllocTy, Value *AllocSize, Value *ArraySize=nullptr, Function *MallocF=nullptr, const Twine &Name="")
Generate the IR for a call to malloc:
SwitchInst * CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases=10, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a switch instruction with the specified value, default dest, and with a hint for the number of...
ReturnInst * CreateRetVoid()
Create a 'ret void' instruction.
static IntegerType * getInt32Ty(LLVMContext &C)
StringRef getName() const
Return a constant reference to the value's name.
const Function * getParent() const
Return the enclosing method, or null if none.
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
INITIALIZE_PASS(WebAssemblyLowerEmscriptenEHSjLj, DEBUG_TYPE, "WebAssembly Lower Emscripten Exceptions / Setjmp / Longjmp", false, false) ModulePass *llvm
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
static cl::list< std::string > EHWhitelist("emscripten-cxx-exceptions-whitelist", cl::desc("The list of function names in which Emscripten-style " "exception handling is enabled (see emscripten " "EMSCRIPTEN_CATCHING_WHITELIST options)"), cl::CommaSeparated)
BranchInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
AttributeSet getFnAttributes() const
The function attributes are returned.
StringRef - Represent a constant reference to a string, i.e.
static Expected< std::string > replace(StringRef S, StringRef From, StringRef To)
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=nullptr)
Legacy analysis pass which computes a DominatorTree.
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
void RewriteUse(Use &U)
Rewrite a use of the symbolic value.
static std::string getSignature(FunctionType *FTy)
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute >> Attrs)
Create an AttributeList with the specified parameters in it.
const BasicBlock * getParent() const
CallInst * CreateCall(Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)