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