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