1 //=== WebAssemblyLowerEmscriptenEHSjLj.cpp - Lower exceptions for Emscripten =//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file lowers exception-related instructions and setjmp/longjmp
11 /// function calls in order to use Emscripten's JavaScript try and catch
12 /// mechanism.
13 ///
14 /// To handle exceptions and setjmp/longjmps, this scheme relies on JavaScript's
15 /// try and catch syntax and relevant exception-related libraries implemented
16 /// in JavaScript glue code that will be produced by Emscripten.
17 ///
18 /// * Exception handling
19 /// This pass lowers invokes and landingpads into library functions in JS glue
20 /// code. Invokes are lowered into function wrappers called invoke wrappers that
21 /// exist in JS side, which wraps the original function call with JS try-catch.
22 /// If an exception occurred, cxa_throw() function in JS side sets some
23 /// variables (see below) so we can check whether an exception occurred from
24 /// wasm code and handle it appropriately.
25 ///
26 /// * Setjmp-longjmp handling
27 /// This pass lowers setjmp to a reasonably-performant approach for emscripten.
28 /// The idea is that each block with a setjmp is broken up into two parts: the
29 /// part containing setjmp and the part right after the setjmp. The latter part
30 /// is either reached from the setjmp, or later from a longjmp. To handle the
31 /// longjmp, all calls that might longjmp are also called using invoke wrappers
32 /// and thus JS / try-catch. JS longjmp() function also sets some variables so
33 /// we can check / whether a longjmp occurred from wasm code. Each block with a
34 /// function call that might longjmp is also split up after the longjmp call.
35 /// After the longjmp call, we check whether a longjmp occurred, and if it did,
36 /// which setjmp it corresponds to, and jump to the right post-setjmp block.
37 /// We assume setjmp-longjmp handling always run after EH handling, which means
38 /// we don't expect any exception-related instructions when SjLj runs.
39 /// FIXME Currently this scheme does not support indirect call of setjmp,
40 /// because of the limitation of the scheme itself. fastcomp does not support it
41 /// either.
42 ///
43 /// In detail, this pass does following things:
44 ///
45 /// 1) Assumes the existence of global variables: __THREW__, __threwValue
46 ///    __THREW__ and __threwValue are defined in compiler-rt in Emscripten.
47 ///    These variables are used for both exceptions and setjmp/longjmps.
48 ///    __THREW__ indicates whether an exception or a longjmp occurred or not. 0
49 ///    means nothing occurred, 1 means an exception occurred, and other numbers
50 ///    mean a longjmp occurred. In the case of longjmp, __THREW__ variable
51 ///    indicates the corresponding setjmp buffer the longjmp corresponds to.
52 ///    __threwValue is 0 for exceptions, and the argument to longjmp in case of
53 ///    longjmp.
54 ///
55 /// * Exception handling
56 ///
57 /// 2) We assume the existence of setThrew and setTempRet0/getTempRet0 functions
58 ///    at link time. setThrew exists in Emscripten's compiler-rt:
59 ///
60 ///    void setThrew(uintptr_t threw, int value) {
61 ///      if (__THREW__ == 0) {
62 ///        __THREW__ = threw;
63 ///        __threwValue = value;
64 ///      }
65 ///    }
66 //
67 ///    setTempRet0 is called from __cxa_find_matching_catch() in JS glue code.
68 ///    In exception handling, getTempRet0 indicates the type of an exception
69 ///    caught, and in setjmp/longjmp, it means the second argument to longjmp
70 ///    function.
71 ///
72 /// 3) Lower
73 ///      invoke @func(arg1, arg2) to label %invoke.cont unwind label %lpad
74 ///    into
75 ///      __THREW__ = 0;
76 ///      call @__invoke_SIG(func, arg1, arg2)
77 ///      %__THREW__.val = __THREW__;
78 ///      __THREW__ = 0;
79 ///      if (%__THREW__.val == 1)
80 ///        goto %lpad
81 ///      else
82 ///         goto %invoke.cont
83 ///    SIG is a mangled string generated based on the LLVM IR-level function
84 ///    signature. After LLVM IR types are lowered to the target wasm types,
85 ///    the names for these wrappers will change based on wasm types as well,
86 ///    as in invoke_vi (function takes an int and returns void). The bodies of
87 ///    these wrappers will be generated in JS glue code, and inside those
88 ///    wrappers we use JS try-catch to generate actual exception effects. It
89 ///    also calls the original callee function. An example wrapper in JS code
90 ///    would look like this:
91 ///      function invoke_vi(index,a1) {
92 ///        try {
93 ///          Module["dynCall_vi"](index,a1); // This calls original callee
94 ///        } catch(e) {
95 ///          if (typeof e !== 'number' && e !== 'longjmp') throw e;
96 ///          _setThrew(1, 0); // setThrew is called here
97 ///        }
98 ///      }
99 ///    If an exception is thrown, __THREW__ will be set to true in a wrapper,
100 ///    so we can jump to the right BB based on this value.
101 ///
102 /// 4) Lower
103 ///      %val = landingpad catch c1 catch c2 catch c3 ...
104 ///      ... use %val ...
105 ///    into
106 ///      %fmc = call @__cxa_find_matching_catch_N(c1, c2, c3, ...)
107 ///      %val = {%fmc, getTempRet0()}
108 ///      ... use %val ...
109 ///    Here N is a number calculated based on the number of clauses.
110 ///    setTempRet0 is called from __cxa_find_matching_catch() in JS glue code.
111 ///
112 /// 5) Lower
113 ///      resume {%a, %b}
114 ///    into
115 ///      call @__resumeException(%a)
116 ///    where __resumeException() is a function in JS glue code.
117 ///
118 /// 6) Lower
119 ///      call @llvm.eh.typeid.for(type) (intrinsic)
120 ///    into
121 ///      call @llvm_eh_typeid_for(type)
122 ///    llvm_eh_typeid_for function will be generated in JS glue code.
123 ///
124 /// * Setjmp / Longjmp handling
125 ///
126 /// In case calls to longjmp() exists
127 ///
128 /// 1) Lower
129 ///      longjmp(env, val)
130 ///    into
131 ///      emscripten_longjmp(env, val)
132 ///
133 /// In case calls to setjmp() exists
134 ///
135 /// 2) In the function entry that calls setjmp, initialize setjmpTable and
136 ///    sejmpTableSize as follows:
137 ///      setjmpTableSize = 4;
138 ///      setjmpTable = (int *) malloc(40);
139 ///      setjmpTable[0] = 0;
140 ///    setjmpTable and setjmpTableSize are used to call saveSetjmp() function in
141 ///    Emscripten compiler-rt.
142 ///
143 /// 3) Lower
144 ///      setjmp(env)
145 ///    into
146 ///      setjmpTable = saveSetjmp(env, label, setjmpTable, setjmpTableSize);
147 ///      setjmpTableSize = getTempRet0();
148 ///    For each dynamic setjmp call, setjmpTable stores its ID (a number which
149 ///    is incrementally assigned from 0) and its label (a unique number that
150 ///    represents each callsite of setjmp). When we need more entries in
151 ///    setjmpTable, it is reallocated in saveSetjmp() in Emscripten's
152 ///    compiler-rt and it will return the new table address, and assign the new
153 ///    table size in setTempRet0(). saveSetjmp also stores the setjmp's ID into
154 ///    the buffer 'env'. A BB with setjmp is split into two after setjmp call in
155 ///    order to make the post-setjmp BB the possible destination of longjmp BB.
156 ///
157 ///
158 /// 4) Lower every call that might longjmp into
159 ///      __THREW__ = 0;
160 ///      call @__invoke_SIG(func, arg1, arg2)
161 ///      %__THREW__.val = __THREW__;
162 ///      __THREW__ = 0;
163 ///      %__threwValue.val = __threwValue;
164 ///      if (%__THREW__.val != 0 & %__threwValue.val != 0) {
165 ///        %label = testSetjmp(mem[%__THREW__.val], setjmpTable,
166 ///                            setjmpTableSize);
167 ///        if (%label == 0)
168 ///          emscripten_longjmp(%__THREW__.val, %__threwValue.val);
169 ///        setTempRet0(%__threwValue.val);
170 ///      } else {
171 ///        %label = -1;
172 ///      }
173 ///      longjmp_result = getTempRet0();
174 ///      switch label {
175 ///        label 1: goto post-setjmp BB 1
176 ///        label 2: goto post-setjmp BB 2
177 ///        ...
178 ///        default: goto splitted next BB
179 ///      }
180 ///    testSetjmp examines setjmpTable to see if there is a matching setjmp
181 ///    call. After calling an invoke wrapper, if a longjmp occurred, __THREW__
182 ///    will be the address of matching jmp_buf buffer and __threwValue be the
183 ///    second argument to longjmp. mem[%__THREW__.val] is a setjmp ID that is
184 ///    stored in saveSetjmp. testSetjmp returns a setjmp label, a unique ID to
185 ///    each setjmp callsite. Label 0 means this longjmp buffer does not
186 ///    correspond to one of the setjmp callsites in this function, so in this
187 ///    case we just chain the longjmp to the caller. Label -1 means no longjmp
188 ///    occurred. Otherwise we jump to the right post-setjmp BB based on the
189 ///    label.
190 ///
191 ///===----------------------------------------------------------------------===//
192 
193 #include "WebAssembly.h"
194 #include "WebAssemblyTargetMachine.h"
195 #include "llvm/ADT/StringExtras.h"
196 #include "llvm/CodeGen/TargetPassConfig.h"
197 #include "llvm/IR/DebugInfoMetadata.h"
198 #include "llvm/IR/Dominators.h"
199 #include "llvm/IR/IRBuilder.h"
200 #include "llvm/Support/CommandLine.h"
201 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
202 #include "llvm/Transforms/Utils/SSAUpdater.h"
203 #include "llvm/Transforms/Utils/SSAUpdaterBulk.h"
204 
205 using namespace llvm;
206 
207 #define DEBUG_TYPE "wasm-lower-em-ehsjlj"
208 
209 // Emscripten's asm.js-style exception handling
210 extern cl::opt<bool> WasmEnableEmEH;
211 // Emscripten's asm.js-style setjmp/longjmp handling
212 extern cl::opt<bool> WasmEnableEmSjLj;
213 // Wasm setjmp/longjmp handling using wasm EH instructions
214 extern cl::opt<bool> WasmEnableSjLj;
215 
216 static cl::list<std::string>
217     EHAllowlist("emscripten-cxx-exceptions-allowed",
218                 cl::desc("The list of function names in which Emscripten-style "
219                          "exception handling is enabled (see emscripten "
220                          "EMSCRIPTEN_CATCHING_ALLOWED options)"),
221                 cl::CommaSeparated);
222 
223 namespace {
224 class WebAssemblyLowerEmscriptenEHSjLj final : public ModulePass {
225   bool EnableEmEH;     // Enable Emscripten exception handling
226   bool EnableEmSjLj;   // Enable Emscripten setjmp/longjmp handling
227   bool EnableWasmSjLj; // Enable Wasm setjmp/longjmp handling
228   bool DoSjLj;         // Whether we actually perform setjmp/longjmp handling
229 
230   GlobalVariable *ThrewGV = nullptr;      // __THREW__ (Emscripten)
231   GlobalVariable *ThrewValueGV = nullptr; // __threwValue (Emscripten)
232   Function *GetTempRet0F = nullptr;       // getTempRet0() (Emscripten)
233   Function *SetTempRet0F = nullptr;       // setTempRet0() (Emscripten)
234   Function *ResumeF = nullptr;            // __resumeException() (Emscripten)
235   Function *EHTypeIDF = nullptr;          // llvm.eh.typeid.for() (intrinsic)
236   Function *EmLongjmpF = nullptr;         // emscripten_longjmp() (Emscripten)
237   Function *SaveSetjmpF = nullptr;        // saveSetjmp() (Emscripten)
238   Function *TestSetjmpF = nullptr;        // testSetjmp() (Emscripten)
239 
240   // __cxa_find_matching_catch_N functions.
241   // Indexed by the number of clauses in an original landingpad instruction.
242   DenseMap<int, Function *> FindMatchingCatches;
243   // Map of <function signature string, invoke_ wrappers>
244   StringMap<Function *> InvokeWrappers;
245   // Set of allowed function names for exception handling
246   std::set<std::string> EHAllowlistSet;
247   // Functions that contains calls to setjmp
248   SmallPtrSet<Function *, 8> SetjmpUsers;
249 
250   StringRef getPassName() const override {
251     return "WebAssembly Lower Emscripten Exceptions";
252   }
253 
254   using InstVector = SmallVectorImpl<Instruction *>;
255   bool runEHOnFunction(Function &F);
256   bool runSjLjOnFunction(Function &F);
257   void handleLongjmpableCallsForEmscriptenSjLj(
258       Function &F, InstVector &SetjmpTableInsts,
259       InstVector &SetjmpTableSizeInsts,
260       SmallVectorImpl<PHINode *> &SetjmpRetPHIs);
261   Function *getFindMatchingCatch(Module &M, unsigned NumClauses);
262 
263   Value *wrapInvoke(CallBase *CI);
264   void wrapTestSetjmp(BasicBlock *BB, DebugLoc DL, Value *Threw,
265                       Value *SetjmpTable, Value *SetjmpTableSize, Value *&Label,
266                       Value *&LongjmpResult, BasicBlock *&EndBB);
267   Function *getInvokeWrapper(CallBase *CI);
268 
269   bool areAllExceptionsAllowed() const { return EHAllowlistSet.empty(); }
270   bool supportsException(const Function *F) const {
271     return EnableEmEH && (areAllExceptionsAllowed() ||
272                           EHAllowlistSet.count(std::string(F->getName())));
273   }
274 
275   void rebuildSSA(Function &F);
276 
277 public:
278   static char ID;
279 
280   WebAssemblyLowerEmscriptenEHSjLj()
281       : ModulePass(ID), EnableEmEH(WasmEnableEmEH),
282         EnableEmSjLj(WasmEnableEmSjLj), EnableWasmSjLj(WasmEnableSjLj) {
283     assert(!(EnableEmSjLj && EnableWasmSjLj) &&
284            "Two SjLj modes cannot be turned on at the same time");
285     assert(!(EnableEmEH && EnableWasmSjLj) &&
286            "Wasm SjLj should be only used with Wasm EH");
287     EHAllowlistSet.insert(EHAllowlist.begin(), EHAllowlist.end());
288   }
289   bool runOnModule(Module &M) override;
290 
291   void getAnalysisUsage(AnalysisUsage &AU) const override {
292     AU.addRequired<DominatorTreeWrapperPass>();
293   }
294 };
295 } // End anonymous namespace
296 
297 char WebAssemblyLowerEmscriptenEHSjLj::ID = 0;
298 INITIALIZE_PASS(WebAssemblyLowerEmscriptenEHSjLj, DEBUG_TYPE,
299                 "WebAssembly Lower Emscripten Exceptions / Setjmp / Longjmp",
300                 false, false)
301 
302 ModulePass *llvm::createWebAssemblyLowerEmscriptenEHSjLj() {
303   return new WebAssemblyLowerEmscriptenEHSjLj();
304 }
305 
306 static bool canThrow(const Value *V) {
307   if (const auto *F = dyn_cast<const Function>(V)) {
308     // Intrinsics cannot throw
309     if (F->isIntrinsic())
310       return false;
311     StringRef Name = F->getName();
312     // leave setjmp and longjmp (mostly) alone, we process them properly later
313     if (Name == "setjmp" || Name == "longjmp" || Name == "emscripten_longjmp")
314       return false;
315     return !F->doesNotThrow();
316   }
317   // not a function, so an indirect call - can throw, we can't tell
318   return true;
319 }
320 
321 // Get a global variable with the given name. If it doesn't exist declare it,
322 // which will generate an import and assume that it will exist at link time.
323 static GlobalVariable *getGlobalVariable(Module &M, Type *Ty,
324                                          WebAssemblyTargetMachine &TM,
325                                          const char *Name) {
326   auto *GV = dyn_cast<GlobalVariable>(M.getOrInsertGlobal(Name, Ty));
327   if (!GV)
328     report_fatal_error(Twine("unable to create global: ") + Name);
329 
330   // If the target supports TLS, make this variable thread-local. We can't just
331   // unconditionally make it thread-local and depend on
332   // CoalesceFeaturesAndStripAtomics to downgrade it, because stripping TLS has
333   // the side effect of disallowing the object from being linked into a
334   // shared-memory module, which we don't want to be responsible for.
335   auto *Subtarget = TM.getSubtargetImpl();
336   auto TLS = Subtarget->hasAtomics() && Subtarget->hasBulkMemory()
337                  ? GlobalValue::LocalExecTLSModel
338                  : GlobalValue::NotThreadLocal;
339   GV->setThreadLocalMode(TLS);
340   return GV;
341 }
342 
343 // Simple function name mangler.
344 // This function simply takes LLVM's string representation of parameter types
345 // and concatenate them with '_'. There are non-alphanumeric characters but llc
346 // is ok with it, and we need to postprocess these names after the lowering
347 // phase anyway.
348 static std::string getSignature(FunctionType *FTy) {
349   std::string Sig;
350   raw_string_ostream OS(Sig);
351   OS << *FTy->getReturnType();
352   for (Type *ParamTy : FTy->params())
353     OS << "_" << *ParamTy;
354   if (FTy->isVarArg())
355     OS << "_...";
356   Sig = OS.str();
357   erase_if(Sig, isSpace);
358   // When s2wasm parses .s file, a comma means the end of an argument. So a
359   // mangled function name can contain any character but a comma.
360   std::replace(Sig.begin(), Sig.end(), ',', '.');
361   return Sig;
362 }
363 
364 static Function *getEmscriptenFunction(FunctionType *Ty, const Twine &Name,
365                                        Module *M) {
366   Function* F = Function::Create(Ty, GlobalValue::ExternalLinkage, Name, M);
367   // Tell the linker that this function is expected to be imported from the
368   // 'env' module.
369   if (!F->hasFnAttribute("wasm-import-module")) {
370     llvm::AttrBuilder B;
371     B.addAttribute("wasm-import-module", "env");
372     F->addFnAttrs(B);
373   }
374   if (!F->hasFnAttribute("wasm-import-name")) {
375     llvm::AttrBuilder B;
376     B.addAttribute("wasm-import-name", F->getName());
377     F->addFnAttrs(B);
378   }
379   return F;
380 }
381 
382 // Returns an integer type for the target architecture's address space.
383 // i32 for wasm32 and i64 for wasm64.
384 static Type *getAddrIntType(Module *M) {
385   IRBuilder<> IRB(M->getContext());
386   return IRB.getIntNTy(M->getDataLayout().getPointerSizeInBits());
387 }
388 
389 // Returns an integer pointer type for the target architecture's address space.
390 // i32* for wasm32 and i64* for wasm64.
391 static Type *getAddrPtrType(Module *M) {
392   return Type::getIntNPtrTy(M->getContext(),
393                             M->getDataLayout().getPointerSizeInBits());
394 }
395 
396 // Returns an integer whose type is the integer type for the target's address
397 // space. Returns (i32 C) for wasm32 and (i64 C) for wasm64, when C is the
398 // integer.
399 static Value *getAddrSizeInt(Module *M, uint64_t C) {
400   IRBuilder<> IRB(M->getContext());
401   return IRB.getIntN(M->getDataLayout().getPointerSizeInBits(), C);
402 }
403 
404 // Returns __cxa_find_matching_catch_N function, where N = NumClauses + 2.
405 // This is because a landingpad instruction contains two more arguments, a
406 // personality function and a cleanup bit, and __cxa_find_matching_catch_N
407 // functions are named after the number of arguments in the original landingpad
408 // instruction.
409 Function *
410 WebAssemblyLowerEmscriptenEHSjLj::getFindMatchingCatch(Module &M,
411                                                        unsigned NumClauses) {
412   if (FindMatchingCatches.count(NumClauses))
413     return FindMatchingCatches[NumClauses];
414   PointerType *Int8PtrTy = Type::getInt8PtrTy(M.getContext());
415   SmallVector<Type *, 16> Args(NumClauses, Int8PtrTy);
416   FunctionType *FTy = FunctionType::get(Int8PtrTy, Args, false);
417   Function *F = getEmscriptenFunction(
418       FTy, "__cxa_find_matching_catch_" + Twine(NumClauses + 2), &M);
419   FindMatchingCatches[NumClauses] = F;
420   return F;
421 }
422 
423 // Generate invoke wrapper seqence with preamble and postamble
424 // Preamble:
425 // __THREW__ = 0;
426 // Postamble:
427 // %__THREW__.val = __THREW__; __THREW__ = 0;
428 // Returns %__THREW__.val, which indicates whether an exception is thrown (or
429 // whether longjmp occurred), for future use.
430 Value *WebAssemblyLowerEmscriptenEHSjLj::wrapInvoke(CallBase *CI) {
431   Module *M = CI->getModule();
432   LLVMContext &C = M->getContext();
433 
434   // If we are calling a function that is noreturn, we must remove that
435   // attribute. The code we insert here does expect it to return, after we
436   // catch the exception.
437   if (CI->doesNotReturn()) {
438     if (auto *F = CI->getCalledFunction())
439       F->removeFnAttr(Attribute::NoReturn);
440     CI->removeFnAttr(Attribute::NoReturn);
441   }
442 
443   IRBuilder<> IRB(C);
444   IRB.SetInsertPoint(CI);
445 
446   // Pre-invoke
447   // __THREW__ = 0;
448   IRB.CreateStore(getAddrSizeInt(M, 0), ThrewGV);
449 
450   // Invoke function wrapper in JavaScript
451   SmallVector<Value *, 16> Args;
452   // Put the pointer to the callee as first argument, so it can be called
453   // within the invoke wrapper later
454   Args.push_back(CI->getCalledOperand());
455   Args.append(CI->arg_begin(), CI->arg_end());
456   CallInst *NewCall = IRB.CreateCall(getInvokeWrapper(CI), Args);
457   NewCall->takeName(CI);
458   NewCall->setCallingConv(CallingConv::WASM_EmscriptenInvoke);
459   NewCall->setDebugLoc(CI->getDebugLoc());
460 
461   // Because we added the pointer to the callee as first argument, all
462   // argument attribute indices have to be incremented by one.
463   SmallVector<AttributeSet, 8> ArgAttributes;
464   const AttributeList &InvokeAL = CI->getAttributes();
465 
466   // No attributes for the callee pointer.
467   ArgAttributes.push_back(AttributeSet());
468   // Copy the argument attributes from the original
469   for (unsigned I = 0, E = CI->getNumArgOperands(); I < E; ++I)
470     ArgAttributes.push_back(InvokeAL.getParamAttrs(I));
471 
472   AttrBuilder FnAttrs(InvokeAL.getFnAttrs());
473   if (FnAttrs.contains(Attribute::AllocSize)) {
474     // The allocsize attribute (if any) referes to parameters by index and needs
475     // to be adjusted.
476     unsigned SizeArg;
477     Optional<unsigned> NEltArg;
478     std::tie(SizeArg, NEltArg) = FnAttrs.getAllocSizeArgs();
479     SizeArg += 1;
480     if (NEltArg.hasValue())
481       NEltArg = NEltArg.getValue() + 1;
482     FnAttrs.addAllocSizeAttr(SizeArg, NEltArg);
483   }
484 
485   // Reconstruct the AttributesList based on the vector we constructed.
486   AttributeList NewCallAL = AttributeList::get(
487       C, AttributeSet::get(C, FnAttrs), InvokeAL.getRetAttrs(), ArgAttributes);
488   NewCall->setAttributes(NewCallAL);
489 
490   CI->replaceAllUsesWith(NewCall);
491 
492   // Post-invoke
493   // %__THREW__.val = __THREW__; __THREW__ = 0;
494   Value *Threw =
495       IRB.CreateLoad(getAddrIntType(M), ThrewGV, ThrewGV->getName() + ".val");
496   IRB.CreateStore(getAddrSizeInt(M, 0), ThrewGV);
497   return Threw;
498 }
499 
500 // Get matching invoke wrapper based on callee signature
501 Function *WebAssemblyLowerEmscriptenEHSjLj::getInvokeWrapper(CallBase *CI) {
502   Module *M = CI->getModule();
503   SmallVector<Type *, 16> ArgTys;
504   FunctionType *CalleeFTy = CI->getFunctionType();
505 
506   std::string Sig = getSignature(CalleeFTy);
507   if (InvokeWrappers.find(Sig) != InvokeWrappers.end())
508     return InvokeWrappers[Sig];
509 
510   // Put the pointer to the callee as first argument
511   ArgTys.push_back(PointerType::getUnqual(CalleeFTy));
512   // Add argument types
513   ArgTys.append(CalleeFTy->param_begin(), CalleeFTy->param_end());
514 
515   FunctionType *FTy = FunctionType::get(CalleeFTy->getReturnType(), ArgTys,
516                                         CalleeFTy->isVarArg());
517   Function *F = getEmscriptenFunction(FTy, "__invoke_" + Sig, M);
518   InvokeWrappers[Sig] = F;
519   return F;
520 }
521 
522 static bool canLongjmp(const Value *Callee) {
523   if (auto *CalleeF = dyn_cast<Function>(Callee))
524     if (CalleeF->isIntrinsic())
525       return false;
526 
527   // Attempting to transform inline assembly will result in something like:
528   //     call void @__invoke_void(void ()* asm ...)
529   // which is invalid because inline assembly blocks do not have addresses
530   // and can't be passed by pointer. The result is a crash with illegal IR.
531   if (isa<InlineAsm>(Callee))
532     return false;
533   StringRef CalleeName = Callee->getName();
534 
535   // The reason we include malloc/free here is to exclude the malloc/free
536   // calls generated in setjmp prep / cleanup routines.
537   if (CalleeName == "setjmp" || CalleeName == "malloc" || CalleeName == "free")
538     return false;
539 
540   // There are functions in Emscripten's JS glue code or compiler-rt
541   if (CalleeName == "__resumeException" || CalleeName == "llvm_eh_typeid_for" ||
542       CalleeName == "saveSetjmp" || CalleeName == "testSetjmp" ||
543       CalleeName == "getTempRet0" || CalleeName == "setTempRet0")
544     return false;
545 
546   // __cxa_find_matching_catch_N functions cannot longjmp
547   if (Callee->getName().startswith("__cxa_find_matching_catch_"))
548     return false;
549 
550   // Exception-catching related functions
551   if (CalleeName == "__cxa_begin_catch" || CalleeName == "__cxa_end_catch" ||
552       CalleeName == "__cxa_allocate_exception" || CalleeName == "__cxa_throw" ||
553       CalleeName == "__clang_call_terminate")
554     return false;
555 
556   // Otherwise we don't know
557   return true;
558 }
559 
560 static bool isEmAsmCall(const Value *Callee) {
561   StringRef CalleeName = Callee->getName();
562   // This is an exhaustive list from Emscripten's <emscripten/em_asm.h>.
563   return CalleeName == "emscripten_asm_const_int" ||
564          CalleeName == "emscripten_asm_const_double" ||
565          CalleeName == "emscripten_asm_const_int_sync_on_main_thread" ||
566          CalleeName == "emscripten_asm_const_double_sync_on_main_thread" ||
567          CalleeName == "emscripten_asm_const_async_on_main_thread";
568 }
569 
570 // Generate testSetjmp function call seqence with preamble and postamble.
571 // The code this generates is equivalent to the following JavaScript code:
572 // %__threwValue.val = __threwValue;
573 // if (%__THREW__.val != 0 & %__threwValue.val != 0) {
574 //   %label = testSetjmp(mem[%__THREW__.val], setjmpTable, setjmpTableSize);
575 //   if (%label == 0)
576 //     emscripten_longjmp(%__THREW__.val, %__threwValue.val);
577 //   setTempRet0(%__threwValue.val);
578 // } else {
579 //   %label = -1;
580 // }
581 // %longjmp_result = getTempRet0();
582 //
583 // As output parameters. returns %label, %longjmp_result, and the BB the last
584 // instruction (%longjmp_result = ...) is in.
585 void WebAssemblyLowerEmscriptenEHSjLj::wrapTestSetjmp(
586     BasicBlock *BB, DebugLoc DL, Value *Threw, Value *SetjmpTable,
587     Value *SetjmpTableSize, Value *&Label, Value *&LongjmpResult,
588     BasicBlock *&EndBB) {
589   Function *F = BB->getParent();
590   Module *M = F->getParent();
591   LLVMContext &C = M->getContext();
592   IRBuilder<> IRB(C);
593   IRB.SetCurrentDebugLocation(DL);
594 
595   // if (%__THREW__.val != 0 & %__threwValue.val != 0)
596   IRB.SetInsertPoint(BB);
597   BasicBlock *ThenBB1 = BasicBlock::Create(C, "if.then1", F);
598   BasicBlock *ElseBB1 = BasicBlock::Create(C, "if.else1", F);
599   BasicBlock *EndBB1 = BasicBlock::Create(C, "if.end", F);
600   Value *ThrewCmp = IRB.CreateICmpNE(Threw, getAddrSizeInt(M, 0));
601   Value *ThrewValue = IRB.CreateLoad(IRB.getInt32Ty(), ThrewValueGV,
602                                      ThrewValueGV->getName() + ".val");
603   Value *ThrewValueCmp = IRB.CreateICmpNE(ThrewValue, IRB.getInt32(0));
604   Value *Cmp1 = IRB.CreateAnd(ThrewCmp, ThrewValueCmp, "cmp1");
605   IRB.CreateCondBr(Cmp1, ThenBB1, ElseBB1);
606 
607   // %label = testSetjmp(mem[%__THREW__.val], setjmpTable, setjmpTableSize);
608   // if (%label == 0)
609   IRB.SetInsertPoint(ThenBB1);
610   BasicBlock *ThenBB2 = BasicBlock::Create(C, "if.then2", F);
611   BasicBlock *EndBB2 = BasicBlock::Create(C, "if.end2", F);
612   Value *ThrewPtr =
613       IRB.CreateIntToPtr(Threw, getAddrPtrType(M), Threw->getName() + ".p");
614   Value *LoadedThrew = IRB.CreateLoad(getAddrIntType(M), ThrewPtr,
615                                       ThrewPtr->getName() + ".loaded");
616   Value *ThenLabel = IRB.CreateCall(
617       TestSetjmpF, {LoadedThrew, SetjmpTable, SetjmpTableSize}, "label");
618   Value *Cmp2 = IRB.CreateICmpEQ(ThenLabel, IRB.getInt32(0));
619   IRB.CreateCondBr(Cmp2, ThenBB2, EndBB2);
620 
621   // emscripten_longjmp(%__THREW__.val, %__threwValue.val);
622   IRB.SetInsertPoint(ThenBB2);
623   IRB.CreateCall(EmLongjmpF, {Threw, ThrewValue});
624   IRB.CreateUnreachable();
625 
626   // setTempRet0(%__threwValue.val);
627   IRB.SetInsertPoint(EndBB2);
628   IRB.CreateCall(SetTempRet0F, ThrewValue);
629   IRB.CreateBr(EndBB1);
630 
631   IRB.SetInsertPoint(ElseBB1);
632   IRB.CreateBr(EndBB1);
633 
634   // longjmp_result = getTempRet0();
635   IRB.SetInsertPoint(EndBB1);
636   PHINode *LabelPHI = IRB.CreatePHI(IRB.getInt32Ty(), 2, "label");
637   LabelPHI->addIncoming(ThenLabel, EndBB2);
638 
639   LabelPHI->addIncoming(IRB.getInt32(-1), ElseBB1);
640 
641   // Output parameter assignment
642   Label = LabelPHI;
643   EndBB = EndBB1;
644   LongjmpResult = IRB.CreateCall(GetTempRet0F, None, "longjmp_result");
645 }
646 
647 void WebAssemblyLowerEmscriptenEHSjLj::rebuildSSA(Function &F) {
648   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
649   DT.recalculate(F); // CFG has been changed
650   SSAUpdaterBulk SSA;
651   for (BasicBlock &BB : F) {
652     for (Instruction &I : BB) {
653       unsigned VarID = SSA.AddVariable(I.getName(), I.getType());
654       SSA.AddAvailableValue(VarID, &BB, &I);
655       for (auto &U : I.uses()) {
656         auto *User = cast<Instruction>(U.getUser());
657         if (auto *UserPN = dyn_cast<PHINode>(User))
658           if (UserPN->getIncomingBlock(U) == &BB)
659             continue;
660         if (DT.dominates(&I, User))
661           continue;
662         SSA.AddUse(VarID, &U);
663       }
664     }
665   }
666   SSA.RewriteAllUses(&DT);
667 }
668 
669 // Replace uses of longjmp with emscripten_longjmp. emscripten_longjmp takes
670 // arguments of type {i32, i32} (wasm32) / {i64, i32} (wasm64) and longjmp takes
671 // {jmp_buf*, i32}, so we need a ptrtoint instruction here to make the type
672 // match. jmp_buf* will eventually be lowered to i32/i64 in the wasm backend.
673 static void replaceLongjmpWithEmscriptenLongjmp(Function *LongjmpF,
674                                                 Function *EmLongjmpF) {
675   Module *M = LongjmpF->getParent();
676   SmallVector<CallInst *, 8> ToErase;
677   LLVMContext &C = LongjmpF->getParent()->getContext();
678   IRBuilder<> IRB(C);
679 
680   // For calls to longjmp, replace it with emscripten_longjmp and cast its first
681   // argument (jmp_buf*) to int
682   for (User *U : LongjmpF->users()) {
683     auto *CI = dyn_cast<CallInst>(U);
684     if (CI && CI->getCalledFunction() == LongjmpF) {
685       IRB.SetInsertPoint(CI);
686       Value *Env =
687           IRB.CreatePtrToInt(CI->getArgOperand(0), getAddrIntType(M), "env");
688       IRB.CreateCall(EmLongjmpF, {Env, CI->getArgOperand(1)});
689       ToErase.push_back(CI);
690     }
691   }
692   for (auto *I : ToErase)
693     I->eraseFromParent();
694 
695   // If we have any remaining uses of longjmp's function pointer, replace it
696   // with (int(*)(jmp_buf*, int))emscripten_longjmp.
697   if (!LongjmpF->uses().empty()) {
698     Value *EmLongjmp =
699         IRB.CreateBitCast(EmLongjmpF, LongjmpF->getType(), "em_longjmp");
700     LongjmpF->replaceAllUsesWith(EmLongjmp);
701   }
702 }
703 
704 static bool containsLongjmpableCalls(const Function *F) {
705   for (const auto &BB : *F)
706     for (const auto &I : BB)
707       if (const auto *CB = dyn_cast<CallBase>(&I))
708         if (canLongjmp(CB->getCalledOperand()))
709           return true;
710   return false;
711 }
712 
713 bool WebAssemblyLowerEmscriptenEHSjLj::runOnModule(Module &M) {
714   LLVM_DEBUG(dbgs() << "********** Lower Emscripten EH & SjLj **********\n");
715 
716   LLVMContext &C = M.getContext();
717   IRBuilder<> IRB(C);
718 
719   Function *SetjmpF = M.getFunction("setjmp");
720   Function *LongjmpF = M.getFunction("longjmp");
721 
722   auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
723   assert(TPC && "Expected a TargetPassConfig");
724   auto &TM = TPC->getTM<WebAssemblyTargetMachine>();
725 
726   // Declare (or get) global variables __THREW__, __threwValue, and
727   // getTempRet0/setTempRet0 function which are used in common for both
728   // exception handling and setjmp/longjmp handling
729   ThrewGV = getGlobalVariable(M, getAddrIntType(&M), TM, "__THREW__");
730   ThrewValueGV = getGlobalVariable(M, IRB.getInt32Ty(), TM, "__threwValue");
731   GetTempRet0F = getEmscriptenFunction(
732       FunctionType::get(IRB.getInt32Ty(), false), "getTempRet0", &M);
733   SetTempRet0F = getEmscriptenFunction(
734       FunctionType::get(IRB.getVoidTy(), IRB.getInt32Ty(), false),
735       "setTempRet0", &M);
736   GetTempRet0F->setDoesNotThrow();
737   SetTempRet0F->setDoesNotThrow();
738 
739   bool Changed = false;
740 
741   // Function registration for exception handling
742   if (EnableEmEH) {
743     // Register __resumeException function
744     FunctionType *ResumeFTy =
745         FunctionType::get(IRB.getVoidTy(), IRB.getInt8PtrTy(), false);
746     ResumeF = getEmscriptenFunction(ResumeFTy, "__resumeException", &M);
747 
748     // Register llvm_eh_typeid_for function
749     FunctionType *EHTypeIDTy =
750         FunctionType::get(IRB.getInt32Ty(), IRB.getInt8PtrTy(), false);
751     EHTypeIDF = getEmscriptenFunction(EHTypeIDTy, "llvm_eh_typeid_for", &M);
752   }
753 
754   if (EnableEmSjLj && SetjmpF) {
755     // Precompute setjmp users
756     for (User *U : SetjmpF->users()) {
757       Function *UserF = cast<Instruction>(U)->getFunction();
758       // If a function that calls setjmp does not contain any other calls that
759       // can longjmp, we don't need to do any transformation on that function,
760       // so can ignore it
761       if (containsLongjmpableCalls(UserF))
762         SetjmpUsers.insert(UserF);
763     }
764   }
765 
766   bool SetjmpUsed = SetjmpF && !SetjmpUsers.empty();
767   bool LongjmpUsed = LongjmpF && !LongjmpF->use_empty();
768   DoSjLj = EnableEmSjLj && (SetjmpUsed || LongjmpUsed);
769 
770   // Function registration and data pre-gathering for setjmp/longjmp handling
771   if (DoSjLj) {
772     assert(EnableEmSjLj || EnableWasmSjLj);
773     // Register emscripten_longjmp function
774     FunctionType *FTy = FunctionType::get(
775         IRB.getVoidTy(), {getAddrIntType(&M), IRB.getInt32Ty()}, false);
776     EmLongjmpF = getEmscriptenFunction(FTy, "emscripten_longjmp", &M);
777 
778     if (SetjmpF) {
779       // Register saveSetjmp function
780       FunctionType *SetjmpFTy = SetjmpF->getFunctionType();
781       FTy = FunctionType::get(Type::getInt32PtrTy(C),
782                               {SetjmpFTy->getParamType(0), IRB.getInt32Ty(),
783                                Type::getInt32PtrTy(C), IRB.getInt32Ty()},
784                               false);
785       SaveSetjmpF = getEmscriptenFunction(FTy, "saveSetjmp", &M);
786 
787       // Register testSetjmp function
788       FTy = FunctionType::get(
789           IRB.getInt32Ty(),
790           {getAddrIntType(&M), Type::getInt32PtrTy(C), IRB.getInt32Ty()},
791           false);
792       TestSetjmpF = getEmscriptenFunction(FTy, "testSetjmp", &M);
793     }
794   }
795 
796   // Exception handling transformation
797   if (EnableEmEH) {
798     for (Function &F : M) {
799       if (F.isDeclaration())
800         continue;
801       Changed |= runEHOnFunction(F);
802     }
803   }
804 
805   // Setjmp/longjmp handling transformation
806   if (DoSjLj) {
807     Changed = true; // We have setjmp or longjmp somewhere
808     if (LongjmpF)
809       replaceLongjmpWithEmscriptenLongjmp(LongjmpF, EmLongjmpF);
810     // Only traverse functions that uses setjmp in order not to insert
811     // unnecessary prep / cleanup code in every function
812     if (SetjmpF)
813       for (Function *F : SetjmpUsers)
814         runSjLjOnFunction(*F);
815   }
816 
817   if (!Changed) {
818     // Delete unused global variables and functions
819     if (ResumeF)
820       ResumeF->eraseFromParent();
821     if (EHTypeIDF)
822       EHTypeIDF->eraseFromParent();
823     if (EmLongjmpF)
824       EmLongjmpF->eraseFromParent();
825     if (SaveSetjmpF)
826       SaveSetjmpF->eraseFromParent();
827     if (TestSetjmpF)
828       TestSetjmpF->eraseFromParent();
829     return false;
830   }
831 
832   return true;
833 }
834 
835 bool WebAssemblyLowerEmscriptenEHSjLj::runEHOnFunction(Function &F) {
836   Module &M = *F.getParent();
837   LLVMContext &C = F.getContext();
838   IRBuilder<> IRB(C);
839   bool Changed = false;
840   SmallVector<Instruction *, 64> ToErase;
841   SmallPtrSet<LandingPadInst *, 32> LandingPads;
842 
843   for (BasicBlock &BB : F) {
844     auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
845     if (!II)
846       continue;
847     Changed = true;
848     LandingPads.insert(II->getLandingPadInst());
849     IRB.SetInsertPoint(II);
850 
851     const Value *Callee = II->getCalledOperand();
852     bool NeedInvoke = supportsException(&F) && canThrow(Callee);
853     if (NeedInvoke) {
854       // Wrap invoke with invoke wrapper and generate preamble/postamble
855       Value *Threw = wrapInvoke(II);
856       ToErase.push_back(II);
857 
858       // If setjmp/longjmp handling is enabled, the thrown value can be not an
859       // exception but a longjmp. If the current function contains calls to
860       // setjmp, it will be appropriately handled in runSjLjOnFunction. But even
861       // if the function does not contain setjmp calls, we shouldn't silently
862       // ignore longjmps; we should rethrow them so they can be correctly
863       // handled in somewhere up the call chain where setjmp is. __THREW__'s
864       // value is 0 when nothing happened, 1 when an exception is thrown, and
865       // other values when longjmp is thrown.
866       //
867       // if (%__THREW__.val == 0 || %__THREW__.val == 1)
868       //   goto %tail
869       // else
870       //   goto %longjmp.rethrow
871       //
872       // longjmp.rethrow: ;; This is longjmp. Rethrow it
873       //   %__threwValue.val = __threwValue
874       //   emscripten_longjmp(%__THREW__.val, %__threwValue.val);
875       //
876       // tail: ;; Nothing happened or an exception is thrown
877       //   ... Continue exception handling ...
878       if (DoSjLj && !SetjmpUsers.count(&F) && canLongjmp(Callee)) {
879         BasicBlock *Tail = BasicBlock::Create(C, "tail", &F);
880         BasicBlock *RethrowBB = BasicBlock::Create(C, "longjmp.rethrow", &F);
881         Value *CmpEqOne =
882             IRB.CreateICmpEQ(Threw, getAddrSizeInt(&M, 1), "cmp.eq.one");
883         Value *CmpEqZero =
884             IRB.CreateICmpEQ(Threw, getAddrSizeInt(&M, 0), "cmp.eq.zero");
885         Value *Or = IRB.CreateOr(CmpEqZero, CmpEqOne, "or");
886         IRB.CreateCondBr(Or, Tail, RethrowBB);
887         IRB.SetInsertPoint(RethrowBB);
888         Value *ThrewValue = IRB.CreateLoad(IRB.getInt32Ty(), ThrewValueGV,
889                                            ThrewValueGV->getName() + ".val");
890         IRB.CreateCall(EmLongjmpF, {Threw, ThrewValue});
891 
892         IRB.CreateUnreachable();
893         IRB.SetInsertPoint(Tail);
894         BB.replaceSuccessorsPhiUsesWith(&BB, Tail);
895       }
896 
897       // Insert a branch based on __THREW__ variable
898       Value *Cmp = IRB.CreateICmpEQ(Threw, getAddrSizeInt(&M, 1), "cmp");
899       IRB.CreateCondBr(Cmp, II->getUnwindDest(), II->getNormalDest());
900 
901     } else {
902       // This can't throw, and we don't need this invoke, just replace it with a
903       // call+branch
904       SmallVector<Value *, 16> Args(II->args());
905       CallInst *NewCall =
906           IRB.CreateCall(II->getFunctionType(), II->getCalledOperand(), Args);
907       NewCall->takeName(II);
908       NewCall->setCallingConv(II->getCallingConv());
909       NewCall->setDebugLoc(II->getDebugLoc());
910       NewCall->setAttributes(II->getAttributes());
911       II->replaceAllUsesWith(NewCall);
912       ToErase.push_back(II);
913 
914       IRB.CreateBr(II->getNormalDest());
915 
916       // Remove any PHI node entries from the exception destination
917       II->getUnwindDest()->removePredecessor(&BB);
918     }
919   }
920 
921   // Process resume instructions
922   for (BasicBlock &BB : F) {
923     // Scan the body of the basic block for resumes
924     for (Instruction &I : BB) {
925       auto *RI = dyn_cast<ResumeInst>(&I);
926       if (!RI)
927         continue;
928       Changed = true;
929 
930       // Split the input into legal values
931       Value *Input = RI->getValue();
932       IRB.SetInsertPoint(RI);
933       Value *Low = IRB.CreateExtractValue(Input, 0, "low");
934       // Create a call to __resumeException function
935       IRB.CreateCall(ResumeF, {Low});
936       // Add a terminator to the block
937       IRB.CreateUnreachable();
938       ToErase.push_back(RI);
939     }
940   }
941 
942   // Process llvm.eh.typeid.for intrinsics
943   for (BasicBlock &BB : F) {
944     for (Instruction &I : BB) {
945       auto *CI = dyn_cast<CallInst>(&I);
946       if (!CI)
947         continue;
948       const Function *Callee = CI->getCalledFunction();
949       if (!Callee)
950         continue;
951       if (Callee->getIntrinsicID() != Intrinsic::eh_typeid_for)
952         continue;
953       Changed = true;
954 
955       IRB.SetInsertPoint(CI);
956       CallInst *NewCI =
957           IRB.CreateCall(EHTypeIDF, CI->getArgOperand(0), "typeid");
958       CI->replaceAllUsesWith(NewCI);
959       ToErase.push_back(CI);
960     }
961   }
962 
963   // Look for orphan landingpads, can occur in blocks with no predecessors
964   for (BasicBlock &BB : F) {
965     Instruction *I = BB.getFirstNonPHI();
966     if (auto *LPI = dyn_cast<LandingPadInst>(I))
967       LandingPads.insert(LPI);
968   }
969   Changed |= !LandingPads.empty();
970 
971   // Handle all the landingpad for this function together, as multiple invokes
972   // may share a single lp
973   for (LandingPadInst *LPI : LandingPads) {
974     IRB.SetInsertPoint(LPI);
975     SmallVector<Value *, 16> FMCArgs;
976     for (unsigned I = 0, E = LPI->getNumClauses(); I < E; ++I) {
977       Constant *Clause = LPI->getClause(I);
978       // TODO Handle filters (= exception specifications).
979       // https://bugs.llvm.org/show_bug.cgi?id=50396
980       if (LPI->isCatch(I))
981         FMCArgs.push_back(Clause);
982     }
983 
984     // Create a call to __cxa_find_matching_catch_N function
985     Function *FMCF = getFindMatchingCatch(M, FMCArgs.size());
986     CallInst *FMCI = IRB.CreateCall(FMCF, FMCArgs, "fmc");
987     Value *Undef = UndefValue::get(LPI->getType());
988     Value *Pair0 = IRB.CreateInsertValue(Undef, FMCI, 0, "pair0");
989     Value *TempRet0 = IRB.CreateCall(GetTempRet0F, None, "tempret0");
990     Value *Pair1 = IRB.CreateInsertValue(Pair0, TempRet0, 1, "pair1");
991 
992     LPI->replaceAllUsesWith(Pair1);
993     ToErase.push_back(LPI);
994   }
995 
996   // Erase everything we no longer need in this function
997   for (Instruction *I : ToErase)
998     I->eraseFromParent();
999 
1000   return Changed;
1001 }
1002 
1003 // This tries to get debug info from the instruction before which a new
1004 // instruction will be inserted, and if there's no debug info in that
1005 // instruction, tries to get the info instead from the previous instruction (if
1006 // any). If none of these has debug info and a DISubprogram is provided, it
1007 // creates a dummy debug info with the first line of the function, because IR
1008 // verifier requires all inlinable callsites should have debug info when both a
1009 // caller and callee have DISubprogram. If none of these conditions are met,
1010 // returns empty info.
1011 static DebugLoc getOrCreateDebugLoc(const Instruction *InsertBefore,
1012                                     DISubprogram *SP) {
1013   assert(InsertBefore);
1014   if (InsertBefore->getDebugLoc())
1015     return InsertBefore->getDebugLoc();
1016   const Instruction *Prev = InsertBefore->getPrevNode();
1017   if (Prev && Prev->getDebugLoc())
1018     return Prev->getDebugLoc();
1019   if (SP)
1020     return DILocation::get(SP->getContext(), SP->getLine(), 1, SP);
1021   return DebugLoc();
1022 }
1023 
1024 bool WebAssemblyLowerEmscriptenEHSjLj::runSjLjOnFunction(Function &F) {
1025   assert(EnableEmSjLj || EnableWasmSjLj);
1026   Module &M = *F.getParent();
1027   LLVMContext &C = F.getContext();
1028   IRBuilder<> IRB(C);
1029   SmallVector<Instruction *, 64> ToErase;
1030   // Vector of %setjmpTable values
1031   SmallVector<Instruction *, 4> SetjmpTableInsts;
1032   // Vector of %setjmpTableSize values
1033   SmallVector<Instruction *, 4> SetjmpTableSizeInsts;
1034 
1035   // Setjmp preparation
1036 
1037   // This instruction effectively means %setjmpTableSize = 4.
1038   // We create this as an instruction intentionally, and we don't want to fold
1039   // this instruction to a constant 4, because this value will be used in
1040   // SSAUpdater.AddAvailableValue(...) later.
1041   BasicBlock *Entry = &F.getEntryBlock();
1042   DebugLoc FirstDL = getOrCreateDebugLoc(&*Entry->begin(), F.getSubprogram());
1043   SplitBlock(Entry, &*Entry->getFirstInsertionPt());
1044 
1045   BinaryOperator *SetjmpTableSize =
1046       BinaryOperator::Create(Instruction::Add, IRB.getInt32(4), IRB.getInt32(0),
1047                              "setjmpTableSize", Entry->getTerminator());
1048   SetjmpTableSize->setDebugLoc(FirstDL);
1049   // setjmpTable = (int *) malloc(40);
1050   Instruction *SetjmpTable = CallInst::CreateMalloc(
1051       SetjmpTableSize, IRB.getInt32Ty(), IRB.getInt32Ty(), IRB.getInt32(40),
1052       nullptr, nullptr, "setjmpTable");
1053   SetjmpTable->setDebugLoc(FirstDL);
1054   // CallInst::CreateMalloc may return a bitcast instruction if the result types
1055   // mismatch. We need to set the debug loc for the original call too.
1056   auto *MallocCall = SetjmpTable->stripPointerCasts();
1057   if (auto *MallocCallI = dyn_cast<Instruction>(MallocCall)) {
1058     MallocCallI->setDebugLoc(FirstDL);
1059   }
1060   // setjmpTable[0] = 0;
1061   IRB.SetInsertPoint(SetjmpTableSize);
1062   IRB.CreateStore(IRB.getInt32(0), SetjmpTable);
1063   SetjmpTableInsts.push_back(SetjmpTable);
1064   SetjmpTableSizeInsts.push_back(SetjmpTableSize);
1065 
1066   // Setjmp transformation
1067   SmallVector<PHINode *, 4> SetjmpRetPHIs;
1068   Function *SetjmpF = M.getFunction("setjmp");
1069   for (User *U : SetjmpF->users()) {
1070     auto *CI = dyn_cast<CallInst>(U);
1071     if (!CI)
1072       report_fatal_error("Does not support indirect calls to setjmp");
1073 
1074     BasicBlock *BB = CI->getParent();
1075     if (BB->getParent() != &F) // in other function
1076       continue;
1077 
1078     // The tail is everything right after the call, and will be reached once
1079     // when setjmp is called, and later when longjmp returns to the setjmp
1080     BasicBlock *Tail = SplitBlock(BB, CI->getNextNode());
1081     // Add a phi to the tail, which will be the output of setjmp, which
1082     // indicates if this is the first call or a longjmp back. The phi directly
1083     // uses the right value based on where we arrive from
1084     IRB.SetInsertPoint(Tail->getFirstNonPHI());
1085     PHINode *SetjmpRet = IRB.CreatePHI(IRB.getInt32Ty(), 2, "setjmp.ret");
1086 
1087     // setjmp initial call returns 0
1088     SetjmpRet->addIncoming(IRB.getInt32(0), BB);
1089     // The proper output is now this, not the setjmp call itself
1090     CI->replaceAllUsesWith(SetjmpRet);
1091     // longjmp returns to the setjmp will add themselves to this phi
1092     SetjmpRetPHIs.push_back(SetjmpRet);
1093 
1094     // Fix call target
1095     // Our index in the function is our place in the array + 1 to avoid index
1096     // 0, because index 0 means the longjmp is not ours to handle.
1097     IRB.SetInsertPoint(CI);
1098     Value *Args[] = {CI->getArgOperand(0), IRB.getInt32(SetjmpRetPHIs.size()),
1099                      SetjmpTable, SetjmpTableSize};
1100     Instruction *NewSetjmpTable =
1101         IRB.CreateCall(SaveSetjmpF, Args, "setjmpTable");
1102     Instruction *NewSetjmpTableSize =
1103         IRB.CreateCall(GetTempRet0F, None, "setjmpTableSize");
1104     SetjmpTableInsts.push_back(NewSetjmpTable);
1105     SetjmpTableSizeInsts.push_back(NewSetjmpTableSize);
1106     ToErase.push_back(CI);
1107   }
1108 
1109   // Handle longjmp calls.
1110   handleLongjmpableCallsForEmscriptenSjLj(F, SetjmpTableInsts,
1111                                           SetjmpTableSizeInsts, SetjmpRetPHIs);
1112 
1113   // Erase everything we no longer need in this function
1114   for (Instruction *I : ToErase)
1115     I->eraseFromParent();
1116 
1117   // Free setjmpTable buffer before each return instruction + function-exiting
1118   // call
1119   SmallVector<Instruction *, 16> ExitingInsts;
1120   for (BasicBlock &BB : F) {
1121     Instruction *TI = BB.getTerminator();
1122     if (isa<ReturnInst>(TI))
1123       ExitingInsts.push_back(TI);
1124     for (auto &I : BB) {
1125       if (auto *CB = dyn_cast<CallBase>(&I)) {
1126         StringRef CalleeName = CB->getCalledOperand()->getName();
1127         if (CalleeName == "__resumeException" ||
1128             CalleeName == "emscripten_longjmp" || CalleeName == "__cxa_throw")
1129           ExitingInsts.push_back(&I);
1130       }
1131     }
1132   }
1133   for (auto *I : ExitingInsts) {
1134     DebugLoc DL = getOrCreateDebugLoc(I, F.getSubprogram());
1135     auto *Free = CallInst::CreateFree(SetjmpTable, I);
1136     Free->setDebugLoc(DL);
1137     // CallInst::CreateFree may create a bitcast instruction if its argument
1138     // types mismatch. We need to set the debug loc for the bitcast too.
1139     if (auto *FreeCallI = dyn_cast<CallInst>(Free)) {
1140       if (auto *BitCastI = dyn_cast<BitCastInst>(FreeCallI->getArgOperand(0)))
1141         BitCastI->setDebugLoc(DL);
1142     }
1143   }
1144 
1145   // Every call to saveSetjmp can change setjmpTable and setjmpTableSize
1146   // (when buffer reallocation occurs)
1147   // entry:
1148   //   setjmpTableSize = 4;
1149   //   setjmpTable = (int *) malloc(40);
1150   //   setjmpTable[0] = 0;
1151   // ...
1152   // somebb:
1153   //   setjmpTable = saveSetjmp(env, label, setjmpTable, setjmpTableSize);
1154   //   setjmpTableSize = getTempRet0();
1155   // So we need to make sure the SSA for these variables is valid so that every
1156   // saveSetjmp and testSetjmp calls have the correct arguments.
1157   SSAUpdater SetjmpTableSSA;
1158   SSAUpdater SetjmpTableSizeSSA;
1159   SetjmpTableSSA.Initialize(Type::getInt32PtrTy(C), "setjmpTable");
1160   SetjmpTableSizeSSA.Initialize(Type::getInt32Ty(C), "setjmpTableSize");
1161   for (Instruction *I : SetjmpTableInsts)
1162     SetjmpTableSSA.AddAvailableValue(I->getParent(), I);
1163   for (Instruction *I : SetjmpTableSizeInsts)
1164     SetjmpTableSizeSSA.AddAvailableValue(I->getParent(), I);
1165 
1166   for (auto &U : make_early_inc_range(SetjmpTable->uses()))
1167     if (auto *I = dyn_cast<Instruction>(U.getUser()))
1168       if (I->getParent() != Entry)
1169         SetjmpTableSSA.RewriteUse(U);
1170   for (auto &U : make_early_inc_range(SetjmpTableSize->uses()))
1171     if (auto *I = dyn_cast<Instruction>(U.getUser()))
1172       if (I->getParent() != Entry)
1173         SetjmpTableSizeSSA.RewriteUse(U);
1174 
1175   // Finally, our modifications to the cfg can break dominance of SSA variables.
1176   // For example, in this code,
1177   // if (x()) { .. setjmp() .. }
1178   // if (y()) { .. longjmp() .. }
1179   // We must split the longjmp block, and it can jump into the block splitted
1180   // from setjmp one. But that means that when we split the setjmp block, it's
1181   // first part no longer dominates its second part - there is a theoretically
1182   // possible control flow path where x() is false, then y() is true and we
1183   // reach the second part of the setjmp block, without ever reaching the first
1184   // part. So, we rebuild SSA form here.
1185   rebuildSSA(F);
1186   return true;
1187 }
1188 
1189 // Update each call that can longjmp so it can return to a setjmp where
1190 // relevant.
1191 void WebAssemblyLowerEmscriptenEHSjLj::handleLongjmpableCallsForEmscriptenSjLj(
1192     Function &F, InstVector &SetjmpTableInsts, InstVector &SetjmpTableSizeInsts,
1193     SmallVectorImpl<PHINode *> &SetjmpRetPHIs) {
1194   Module &M = *F.getParent();
1195   LLVMContext &C = F.getContext();
1196   IRBuilder<> IRB(C);
1197   SmallVector<Instruction *, 64> ToErase;
1198 
1199   // We need to pass setjmpTable and setjmpTableSize to testSetjmp function.
1200   // These values are defined in the beginning of the function and also in each
1201   // setjmp callsite, but we don't know which values we should use at this
1202   // point. So here we arbitraily use the ones defined in the beginning of the
1203   // function, and SSAUpdater will later update them to the correct values.
1204   Instruction *SetjmpTable = *SetjmpTableInsts.begin();
1205   Instruction *SetjmpTableSize = *SetjmpTableSizeInsts.begin();
1206 
1207   // Because we are creating new BBs while processing and don't want to make
1208   // all these newly created BBs candidates again for longjmp processing, we
1209   // first make the vector of candidate BBs.
1210   std::vector<BasicBlock *> BBs;
1211   for (BasicBlock &BB : F)
1212     BBs.push_back(&BB);
1213 
1214   // BBs.size() will change within the loop, so we query it every time
1215   for (unsigned I = 0; I < BBs.size(); I++) {
1216     BasicBlock *BB = BBs[I];
1217     for (Instruction &I : *BB) {
1218       if (isa<InvokeInst>(&I))
1219         report_fatal_error("When using Wasm EH with Emscripten SjLj, there is "
1220                            "a restriction that `setjmp` function call and "
1221                            "exception cannot be used within the same function");
1222       auto *CI = dyn_cast<CallInst>(&I);
1223       if (!CI)
1224         continue;
1225 
1226       const Value *Callee = CI->getCalledOperand();
1227       if (!canLongjmp(Callee))
1228         continue;
1229       if (isEmAsmCall(Callee))
1230         report_fatal_error("Cannot use EM_ASM* alongside setjmp/longjmp in " +
1231                                F.getName() +
1232                                ". Please consider using EM_JS, or move the "
1233                                "EM_ASM into another function.",
1234                            false);
1235 
1236       Value *Threw = nullptr;
1237       BasicBlock *Tail;
1238       if (Callee->getName().startswith("__invoke_")) {
1239         // If invoke wrapper has already been generated for this call in
1240         // previous EH phase, search for the load instruction
1241         // %__THREW__.val = __THREW__;
1242         // in postamble after the invoke wrapper call
1243         LoadInst *ThrewLI = nullptr;
1244         StoreInst *ThrewResetSI = nullptr;
1245         for (auto I = std::next(BasicBlock::iterator(CI)), IE = BB->end();
1246              I != IE; ++I) {
1247           if (auto *LI = dyn_cast<LoadInst>(I))
1248             if (auto *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand()))
1249               if (GV == ThrewGV) {
1250                 Threw = ThrewLI = LI;
1251                 break;
1252               }
1253         }
1254         // Search for the store instruction after the load above
1255         // __THREW__ = 0;
1256         for (auto I = std::next(BasicBlock::iterator(ThrewLI)), IE = BB->end();
1257              I != IE; ++I) {
1258           if (auto *SI = dyn_cast<StoreInst>(I)) {
1259             if (auto *GV = dyn_cast<GlobalVariable>(SI->getPointerOperand())) {
1260               if (GV == ThrewGV &&
1261                   SI->getValueOperand() == getAddrSizeInt(&M, 0)) {
1262                 ThrewResetSI = SI;
1263                 break;
1264               }
1265             }
1266           }
1267         }
1268         assert(Threw && ThrewLI && "Cannot find __THREW__ load after invoke");
1269         assert(ThrewResetSI && "Cannot find __THREW__ store after invoke");
1270         Tail = SplitBlock(BB, ThrewResetSI->getNextNode());
1271 
1272       } else {
1273         // Wrap call with invoke wrapper and generate preamble/postamble
1274         Threw = wrapInvoke(CI);
1275         ToErase.push_back(CI);
1276         Tail = SplitBlock(BB, CI->getNextNode());
1277 
1278         // If exception handling is enabled, the thrown value can be not a
1279         // longjmp but an exception, in which case we shouldn't silently ignore
1280         // exceptions; we should rethrow them.
1281         // __THREW__'s value is 0 when nothing happened, 1 when an exception is
1282         // thrown, other values when longjmp is thrown.
1283         //
1284         // if (%__THREW__.val == 1)
1285         //   goto %eh.rethrow
1286         // else
1287         //   goto %normal
1288         //
1289         // eh.rethrow: ;; Rethrow exception
1290         //   %exn = call @__cxa_find_matching_catch_2() ;; Retrieve thrown ptr
1291         //   __resumeException(%exn)
1292         //
1293         // normal:
1294         //   <-- Insertion point. Will insert sjlj handling code from here
1295         //   goto %tail
1296         //
1297         // tail:
1298         //   ...
1299         if (supportsException(&F) && canThrow(Callee)) {
1300           IRB.SetInsertPoint(CI);
1301           // We will add a new conditional branch. So remove the branch created
1302           // when we split the BB
1303           ToErase.push_back(BB->getTerminator());
1304           BasicBlock *NormalBB = BasicBlock::Create(C, "normal", &F);
1305           BasicBlock *RethrowBB = BasicBlock::Create(C, "eh.rethrow", &F);
1306           Value *CmpEqOne =
1307               IRB.CreateICmpEQ(Threw, getAddrSizeInt(&M, 1), "cmp.eq.one");
1308           IRB.CreateCondBr(CmpEqOne, RethrowBB, NormalBB);
1309           IRB.SetInsertPoint(RethrowBB);
1310           CallInst *Exn = IRB.CreateCall(getFindMatchingCatch(M, 0), {}, "exn");
1311           IRB.CreateCall(ResumeF, {Exn});
1312           IRB.CreateUnreachable();
1313           IRB.SetInsertPoint(NormalBB);
1314           IRB.CreateBr(Tail);
1315           BB = NormalBB; // New insertion point to insert testSetjmp()
1316         }
1317       }
1318 
1319       // We need to replace the terminator in Tail - SplitBlock makes BB go
1320       // straight to Tail, we need to check if a longjmp occurred, and go to the
1321       // right setjmp-tail if so
1322       ToErase.push_back(BB->getTerminator());
1323 
1324       // Generate a function call to testSetjmp function and preamble/postamble
1325       // code to figure out (1) whether longjmp occurred (2) if longjmp
1326       // occurred, which setjmp it corresponds to
1327       Value *Label = nullptr;
1328       Value *LongjmpResult = nullptr;
1329       BasicBlock *EndBB = nullptr;
1330       wrapTestSetjmp(BB, CI->getDebugLoc(), Threw, SetjmpTable, SetjmpTableSize,
1331                      Label, LongjmpResult, EndBB);
1332       assert(Label && LongjmpResult && EndBB);
1333 
1334       // Create switch instruction
1335       IRB.SetInsertPoint(EndBB);
1336       IRB.SetCurrentDebugLocation(EndBB->getInstList().back().getDebugLoc());
1337       SwitchInst *SI = IRB.CreateSwitch(Label, Tail, SetjmpRetPHIs.size());
1338       // -1 means no longjmp happened, continue normally (will hit the default
1339       // switch case). 0 means a longjmp that is not ours to handle, needs a
1340       // rethrow. Otherwise the index is the same as the index in P+1 (to avoid
1341       // 0).
1342       for (unsigned I = 0; I < SetjmpRetPHIs.size(); I++) {
1343         SI->addCase(IRB.getInt32(I + 1), SetjmpRetPHIs[I]->getParent());
1344         SetjmpRetPHIs[I]->addIncoming(LongjmpResult, EndBB);
1345       }
1346 
1347       // We are splitting the block here, and must continue to find other calls
1348       // in the block - which is now split. so continue to traverse in the Tail
1349       BBs.push_back(Tail);
1350     }
1351   }
1352 
1353   for (Instruction *I : ToErase)
1354     I->eraseFromParent();
1355 }
1356