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_jmpbuf(buf, value)
144 ///    emscripten_longjmp_jmpbuf will be lowered to emscripten_longjmp later.
145 ///
146 /// In case calls to setjmp() exists
147 ///
148 /// 2) In the function entry that calls setjmp, initialize setjmpTable and
149 ///    sejmpTableSize as follows:
150 ///      setjmpTableSize = 4;
151 ///      setjmpTable = (int *) malloc(40);
152 ///      setjmpTable[0] = 0;
153 ///    setjmpTable and setjmpTableSize are used in saveSetjmp() function in JS
154 ///    code.
155 ///
156 /// 3) Lower
157 ///      setjmp(buf)
158 ///    into
159 ///      setjmpTable = saveSetjmp(buf, label, setjmpTable, setjmpTableSize);
160 ///      setjmpTableSize = getTempRet0();
161 ///    For each dynamic setjmp call, setjmpTable stores its ID (a number which
162 ///    is incrementally assigned from 0) and its label (a unique number that
163 ///    represents each callsite of setjmp). When we need more entries in
164 ///    setjmpTable, it is reallocated in saveSetjmp() in JS code and it will
165 ///    return the new table address, and assign the new table size in
166 ///    setTempRet0(). saveSetjmp also stores the setjmp's ID into the buffer
167 ///    buf. A BB with setjmp is split into two after setjmp call in order to
168 ///    make the post-setjmp BB the possible destination of longjmp BB.
169 ///
170 ///
171 /// 4) Lower every call that might longjmp into
172 ///      __THREW__ = 0;
173 ///      call @__invoke_SIG(func, arg1, arg2)
174 ///      %__THREW__.val = __THREW__;
175 ///      __THREW__ = 0;
176 ///      if (%__THREW__.val != 0 & __threwValue != 0) {
177 ///        %label = testSetjmp(mem[%__THREW__.val], setjmpTable,
178 ///                            setjmpTableSize);
179 ///        if (%label == 0)
180 ///          emscripten_longjmp(%__THREW__.val, __threwValue);
181 ///        setTempRet0(__threwValue);
182 ///      } else {
183 ///        %label = -1;
184 ///      }
185 ///      longjmp_result = getTempRet0();
186 ///      switch label {
187 ///        label 1: goto post-setjmp BB 1
188 ///        label 2: goto post-setjmp BB 2
189 ///        ...
190 ///        default: goto splitted next BB
191 ///      }
192 ///    testSetjmp examines setjmpTable to see if there is a matching setjmp
193 ///    call. After calling an invoke wrapper, if a longjmp occurred, __THREW__
194 ///    will be the address of matching jmp_buf buffer and __threwValue be the
195 ///    second argument to longjmp. mem[__THREW__.val] is a setjmp ID that is
196 ///    stored in saveSetjmp. testSetjmp returns a setjmp label, a unique ID to
197 ///    each setjmp callsite. Label 0 means this longjmp buffer does not
198 ///    correspond to one of the setjmp callsites in this function, so in this
199 ///    case we just chain the longjmp to the caller. (Here we call
200 ///    emscripten_longjmp, which is different from emscripten_longjmp_jmpbuf.
201 ///    emscripten_longjmp_jmpbuf takes jmp_buf as its first argument, while
202 ///    emscripten_longjmp takes an int. Both of them will eventually be lowered
203 ///    to emscripten_longjmp in s2wasm, but here we need two signatures - we
204 ///    can't translate an int value to a jmp_buf.)
205 ///    Label -1 means no longjmp occurred. Otherwise we jump to the right
206 ///    post-setjmp BB based on the label.
207 ///
208 ///===----------------------------------------------------------------------===//
209 
210 #include "WebAssembly.h"
211 #include "llvm/IR/CallSite.h"
212 #include "llvm/IR/Dominators.h"
213 #include "llvm/IR/IRBuilder.h"
214 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
215 #include "llvm/Transforms/Utils/SSAUpdater.h"
216 
217 using namespace llvm;
218 
219 #define DEBUG_TYPE "wasm-lower-em-ehsjlj"
220 
221 static cl::list<std::string>
222     EHWhitelist("emscripten-cxx-exceptions-whitelist",
223                 cl::desc("The list of function names in which Emscripten-style "
224                          "exception handling is enabled (see emscripten "
225                          "EMSCRIPTEN_CATCHING_WHITELIST options)"),
226                 cl::CommaSeparated);
227 
228 namespace {
229 class WebAssemblyLowerEmscriptenEHSjLj final : public ModulePass {
230   static const char *ResumeFName;
231   static const char *EHTypeIDFName;
232   static const char *EmLongjmpFName;
233   static const char *EmLongjmpJmpbufFName;
234   static const char *SaveSetjmpFName;
235   static const char *TestSetjmpFName;
236   static const char *FindMatchingCatchPrefix;
237   static const char *InvokePrefix;
238 
239   bool EnableEH;   // Enable exception handling
240   bool EnableSjLj; // Enable setjmp/longjmp handling
241 
242   GlobalVariable *ThrewGV = nullptr;
243   GlobalVariable *ThrewValueGV = nullptr;
244   Function *GetTempRet0Func = nullptr;
245   Function *SetTempRet0Func = nullptr;
246   Function *ResumeF = nullptr;
247   Function *EHTypeIDF = nullptr;
248   Function *EmLongjmpF = nullptr;
249   Function *EmLongjmpJmpbufF = nullptr;
250   Function *SaveSetjmpF = nullptr;
251   Function *TestSetjmpF = nullptr;
252 
253   // __cxa_find_matching_catch_N functions.
254   // Indexed by the number of clauses in an original landingpad instruction.
255   DenseMap<int, Function *> FindMatchingCatches;
256   // Map of <function signature string, invoke_ wrappers>
257   StringMap<Function *> InvokeWrappers;
258   // Set of whitelisted function names for exception handling
259   std::set<std::string> EHWhitelistSet;
260 
261   StringRef getPassName() const override {
262     return "WebAssembly Lower Emscripten Exceptions";
263   }
264 
265   bool runEHOnFunction(Function &F);
266   bool runSjLjOnFunction(Function &F);
267   Function *getFindMatchingCatch(Module &M, unsigned NumClauses);
268 
269   template <typename CallOrInvoke> Value *wrapInvoke(CallOrInvoke *CI);
270   void wrapTestSetjmp(BasicBlock *BB, Instruction *InsertPt, Value *Threw,
271                       Value *SetjmpTable, Value *SetjmpTableSize, Value *&Label,
272                       Value *&LongjmpResult, BasicBlock *&EndBB);
273   template <typename CallOrInvoke> Function *getInvokeWrapper(CallOrInvoke *CI);
274 
275   bool areAllExceptionsAllowed() const { return EHWhitelistSet.empty(); }
276   bool canLongjmp(Module &M, const Value *Callee) const;
277 
278   void rebuildSSA(Function &F);
279 
280 public:
281   static char ID;
282 
283   WebAssemblyLowerEmscriptenEHSjLj(bool EnableEH = true, bool EnableSjLj = true)
284       : ModulePass(ID), EnableEH(EnableEH), EnableSjLj(EnableSjLj) {
285     EHWhitelistSet.insert(EHWhitelist.begin(), EHWhitelist.end());
286   }
287   bool runOnModule(Module &M) override;
288 
289   void getAnalysisUsage(AnalysisUsage &AU) const override {
290     AU.addRequired<DominatorTreeWrapperPass>();
291   }
292 };
293 } // End anonymous namespace
294 
295 const char *WebAssemblyLowerEmscriptenEHSjLj::ResumeFName = "__resumeException";
296 const char *WebAssemblyLowerEmscriptenEHSjLj::EHTypeIDFName =
297     "llvm_eh_typeid_for";
298 const char *WebAssemblyLowerEmscriptenEHSjLj::EmLongjmpFName =
299     "emscripten_longjmp";
300 const char *WebAssemblyLowerEmscriptenEHSjLj::EmLongjmpJmpbufFName =
301     "emscripten_longjmp_jmpbuf";
302 const char *WebAssemblyLowerEmscriptenEHSjLj::SaveSetjmpFName = "saveSetjmp";
303 const char *WebAssemblyLowerEmscriptenEHSjLj::TestSetjmpFName = "testSetjmp";
304 const char *WebAssemblyLowerEmscriptenEHSjLj::FindMatchingCatchPrefix =
305     "__cxa_find_matching_catch_";
306 const char *WebAssemblyLowerEmscriptenEHSjLj::InvokePrefix = "__invoke_";
307 
308 char WebAssemblyLowerEmscriptenEHSjLj::ID = 0;
309 INITIALIZE_PASS(WebAssemblyLowerEmscriptenEHSjLj, DEBUG_TYPE,
310                 "WebAssembly Lower Emscripten Exceptions / Setjmp / Longjmp",
311                 false, false)
312 
313 ModulePass *llvm::createWebAssemblyLowerEmscriptenEHSjLj(bool EnableEH,
314                                                          bool EnableSjLj) {
315   return new WebAssemblyLowerEmscriptenEHSjLj(EnableEH, EnableSjLj);
316 }
317 
318 static bool canThrow(const Value *V) {
319   if (const auto *F = dyn_cast<const Function>(V)) {
320     // Intrinsics cannot throw
321     if (F->isIntrinsic())
322       return false;
323     StringRef Name = F->getName();
324     // leave setjmp and longjmp (mostly) alone, we process them properly later
325     if (Name == "setjmp" || Name == "longjmp")
326       return false;
327     return !F->doesNotThrow();
328   }
329   // not a function, so an indirect call - can throw, we can't tell
330   return true;
331 }
332 
333 // Get a global variable with the given name.  If it doesn't exist declare it,
334 // which will generate an import and asssumes that it will exist at link time.
335 static GlobalVariable *getGlobalVariableI32(Module &M, IRBuilder<> &IRB,
336                                             const char *Name) {
337 
338   auto* GV = dyn_cast<GlobalVariable>(M.getOrInsertGlobal(Name, IRB.getInt32Ty()));
339   if (!GV)
340     report_fatal_error(Twine("unable to create global: ") + Name);
341 
342   return GV;
343 }
344 
345 // Simple function name mangler.
346 // This function simply takes LLVM's string representation of parameter types
347 // and concatenate them with '_'. There are non-alphanumeric characters but llc
348 // is ok with it, and we need to postprocess these names after the lowering
349 // phase anyway.
350 static std::string getSignature(FunctionType *FTy) {
351   std::string Sig;
352   raw_string_ostream OS(Sig);
353   OS << *FTy->getReturnType();
354   for (Type *ParamTy : FTy->params())
355     OS << "_" << *ParamTy;
356   if (FTy->isVarArg())
357     OS << "_...";
358   Sig = OS.str();
359   Sig.erase(remove_if(Sig, isspace), Sig.end());
360   // When s2wasm parses .s file, a comma means the end of an argument. So a
361   // mangled function name can contain any character but a comma.
362   std::replace(Sig.begin(), Sig.end(), ',', '.');
363   return Sig;
364 }
365 
366 // Returns __cxa_find_matching_catch_N function, where N = NumClauses + 2.
367 // This is because a landingpad instruction contains two more arguments, a
368 // personality function and a cleanup bit, and __cxa_find_matching_catch_N
369 // functions are named after the number of arguments in the original landingpad
370 // instruction.
371 Function *
372 WebAssemblyLowerEmscriptenEHSjLj::getFindMatchingCatch(Module &M,
373                                                        unsigned NumClauses) {
374   if (FindMatchingCatches.count(NumClauses))
375     return FindMatchingCatches[NumClauses];
376   PointerType *Int8PtrTy = Type::getInt8PtrTy(M.getContext());
377   SmallVector<Type *, 16> Args(NumClauses, Int8PtrTy);
378   FunctionType *FTy = FunctionType::get(Int8PtrTy, Args, false);
379   Function *F =
380       Function::Create(FTy, GlobalValue::ExternalLinkage,
381                        FindMatchingCatchPrefix + Twine(NumClauses + 2), &M);
382   FindMatchingCatches[NumClauses] = F;
383   return F;
384 }
385 
386 // Generate invoke wrapper seqence with preamble and postamble
387 // Preamble:
388 // __THREW__ = 0;
389 // Postamble:
390 // %__THREW__.val = __THREW__; __THREW__ = 0;
391 // Returns %__THREW__.val, which indicates whether an exception is thrown (or
392 // whether longjmp occurred), for future use.
393 template <typename CallOrInvoke>
394 Value *WebAssemblyLowerEmscriptenEHSjLj::wrapInvoke(CallOrInvoke *CI) {
395   LLVMContext &C = CI->getModule()->getContext();
396 
397   // If we are calling a function that is noreturn, we must remove that
398   // attribute. The code we insert here does expect it to return, after we
399   // catch the exception.
400   if (CI->doesNotReturn()) {
401     if (auto *F = dyn_cast<Function>(CI->getCalledValue()))
402       F->removeFnAttr(Attribute::NoReturn);
403     CI->removeAttribute(AttributeList::FunctionIndex, Attribute::NoReturn);
404   }
405 
406   IRBuilder<> IRB(C);
407   IRB.SetInsertPoint(CI);
408 
409   // Pre-invoke
410   // __THREW__ = 0;
411   IRB.CreateStore(IRB.getInt32(0), ThrewGV);
412 
413   // Invoke function wrapper in JavaScript
414   SmallVector<Value *, 16> Args;
415   // Put the pointer to the callee as first argument, so it can be called
416   // within the invoke wrapper later
417   Args.push_back(CI->getCalledValue());
418   Args.append(CI->arg_begin(), CI->arg_end());
419   CallInst *NewCall = IRB.CreateCall(getInvokeWrapper(CI), Args);
420   NewCall->takeName(CI);
421   NewCall->setCallingConv(CI->getCallingConv());
422   NewCall->setDebugLoc(CI->getDebugLoc());
423 
424   // Because we added the pointer to the callee as first argument, all
425   // argument attribute indices have to be incremented by one.
426   SmallVector<AttributeSet, 8> ArgAttributes;
427   const AttributeList &InvokeAL = CI->getAttributes();
428 
429   // No attributes for the callee pointer.
430   ArgAttributes.push_back(AttributeSet());
431   // Copy the argument attributes from the original
432   for (unsigned I = 0, E = CI->getNumArgOperands(); I < E; ++I)
433     ArgAttributes.push_back(InvokeAL.getParamAttributes(I));
434 
435   // Reconstruct the AttributesList based on the vector we constructed.
436   AttributeList NewCallAL =
437       AttributeList::get(C, InvokeAL.getFnAttributes(),
438                          InvokeAL.getRetAttributes(), ArgAttributes);
439   NewCall->setAttributes(NewCallAL);
440 
441   CI->replaceAllUsesWith(NewCall);
442 
443   // Post-invoke
444   // %__THREW__.val = __THREW__; __THREW__ = 0;
445   Value *Threw =
446       IRB.CreateLoad(IRB.getInt32Ty(), ThrewGV, ThrewGV->getName() + ".val");
447   IRB.CreateStore(IRB.getInt32(0), ThrewGV);
448   return Threw;
449 }
450 
451 // Get matching invoke wrapper based on callee signature
452 template <typename CallOrInvoke>
453 Function *WebAssemblyLowerEmscriptenEHSjLj::getInvokeWrapper(CallOrInvoke *CI) {
454   Module *M = CI->getModule();
455   SmallVector<Type *, 16> ArgTys;
456   Value *Callee = CI->getCalledValue();
457   FunctionType *CalleeFTy;
458   if (auto *F = dyn_cast<Function>(Callee))
459     CalleeFTy = F->getFunctionType();
460   else {
461     auto *CalleeTy = cast<PointerType>(Callee->getType())->getElementType();
462     CalleeFTy = dyn_cast<FunctionType>(CalleeTy);
463   }
464 
465   std::string Sig = getSignature(CalleeFTy);
466   if (InvokeWrappers.find(Sig) != InvokeWrappers.end())
467     return InvokeWrappers[Sig];
468 
469   // Put the pointer to the callee as first argument
470   ArgTys.push_back(PointerType::getUnqual(CalleeFTy));
471   // Add argument types
472   ArgTys.append(CalleeFTy->param_begin(), CalleeFTy->param_end());
473 
474   FunctionType *FTy = FunctionType::get(CalleeFTy->getReturnType(), ArgTys,
475                                         CalleeFTy->isVarArg());
476   Function *F = Function::Create(FTy, GlobalValue::ExternalLinkage,
477                                  InvokePrefix + Sig, M);
478   InvokeWrappers[Sig] = F;
479   return F;
480 }
481 
482 bool WebAssemblyLowerEmscriptenEHSjLj::canLongjmp(Module &M,
483                                                   const Value *Callee) const {
484   if (auto *CalleeF = dyn_cast<Function>(Callee))
485     if (CalleeF->isIntrinsic())
486       return false;
487 
488   // The reason we include malloc/free here is to exclude the malloc/free
489   // calls generated in setjmp prep / cleanup routines.
490   Function *SetjmpF = M.getFunction("setjmp");
491   Function *MallocF = M.getFunction("malloc");
492   Function *FreeF = M.getFunction("free");
493   if (Callee == SetjmpF || Callee == MallocF || Callee == FreeF)
494     return false;
495 
496   // There are functions in JS glue code
497   if (Callee == ResumeF || Callee == EHTypeIDF || Callee == SaveSetjmpF ||
498       Callee == TestSetjmpF)
499     return false;
500 
501   // __cxa_find_matching_catch_N functions cannot longjmp
502   if (Callee->getName().startswith(FindMatchingCatchPrefix))
503     return false;
504 
505   // Exception-catching related functions
506   Function *BeginCatchF = M.getFunction("__cxa_begin_catch");
507   Function *EndCatchF = M.getFunction("__cxa_end_catch");
508   Function *AllocExceptionF = M.getFunction("__cxa_allocate_exception");
509   Function *ThrowF = M.getFunction("__cxa_throw");
510   Function *TerminateF = M.getFunction("__clang_call_terminate");
511   if (Callee == BeginCatchF || Callee == EndCatchF ||
512       Callee == AllocExceptionF || Callee == ThrowF || Callee == TerminateF ||
513       Callee == GetTempRet0Func || Callee == SetTempRet0Func)
514     return false;
515 
516   // Otherwise we don't know
517   return true;
518 }
519 
520 // Generate testSetjmp function call seqence with preamble and postamble.
521 // The code this generates is equivalent to the following JavaScript code:
522 // if (%__THREW__.val != 0 & threwValue != 0) {
523 //   %label = _testSetjmp(mem[%__THREW__.val], setjmpTable, setjmpTableSize);
524 //   if (%label == 0)
525 //     emscripten_longjmp(%__THREW__.val, threwValue);
526 //   setTempRet0(threwValue);
527 // } else {
528 //   %label = -1;
529 // }
530 // %longjmp_result = getTempRet0();
531 //
532 // As output parameters. returns %label, %longjmp_result, and the BB the last
533 // instruction (%longjmp_result = ...) is in.
534 void WebAssemblyLowerEmscriptenEHSjLj::wrapTestSetjmp(
535     BasicBlock *BB, Instruction *InsertPt, Value *Threw, Value *SetjmpTable,
536     Value *SetjmpTableSize, Value *&Label, Value *&LongjmpResult,
537     BasicBlock *&EndBB) {
538   Function *F = BB->getParent();
539   LLVMContext &C = BB->getModule()->getContext();
540   IRBuilder<> IRB(C);
541   IRB.SetInsertPoint(InsertPt);
542 
543   // if (%__THREW__.val != 0 & threwValue != 0)
544   IRB.SetInsertPoint(BB);
545   BasicBlock *ThenBB1 = BasicBlock::Create(C, "if.then1", F);
546   BasicBlock *ElseBB1 = BasicBlock::Create(C, "if.else1", F);
547   BasicBlock *EndBB1 = BasicBlock::Create(C, "if.end", F);
548   Value *ThrewCmp = IRB.CreateICmpNE(Threw, IRB.getInt32(0));
549   Value *ThrewValue = IRB.CreateLoad(IRB.getInt32Ty(), ThrewValueGV,
550                                      ThrewValueGV->getName() + ".val");
551   Value *ThrewValueCmp = IRB.CreateICmpNE(ThrewValue, IRB.getInt32(0));
552   Value *Cmp1 = IRB.CreateAnd(ThrewCmp, ThrewValueCmp, "cmp1");
553   IRB.CreateCondBr(Cmp1, ThenBB1, ElseBB1);
554 
555   // %label = _testSetjmp(mem[%__THREW__.val], _setjmpTable, _setjmpTableSize);
556   // if (%label == 0)
557   IRB.SetInsertPoint(ThenBB1);
558   BasicBlock *ThenBB2 = BasicBlock::Create(C, "if.then2", F);
559   BasicBlock *EndBB2 = BasicBlock::Create(C, "if.end2", F);
560   Value *ThrewInt = IRB.CreateIntToPtr(Threw, Type::getInt32PtrTy(C),
561                                        Threw->getName() + ".i32p");
562   Value *LoadedThrew = IRB.CreateLoad(IRB.getInt32Ty(), ThrewInt,
563                                       ThrewInt->getName() + ".loaded");
564   Value *ThenLabel = IRB.CreateCall(
565       TestSetjmpF, {LoadedThrew, SetjmpTable, SetjmpTableSize}, "label");
566   Value *Cmp2 = IRB.CreateICmpEQ(ThenLabel, IRB.getInt32(0));
567   IRB.CreateCondBr(Cmp2, ThenBB2, EndBB2);
568 
569   // emscripten_longjmp(%__THREW__.val, threwValue);
570   IRB.SetInsertPoint(ThenBB2);
571   IRB.CreateCall(EmLongjmpF, {Threw, ThrewValue});
572   IRB.CreateUnreachable();
573 
574   // setTempRet0(threwValue);
575   IRB.SetInsertPoint(EndBB2);
576   IRB.CreateCall(SetTempRet0Func, ThrewValue);
577   IRB.CreateBr(EndBB1);
578 
579   IRB.SetInsertPoint(ElseBB1);
580   IRB.CreateBr(EndBB1);
581 
582   // longjmp_result = getTempRet0();
583   IRB.SetInsertPoint(EndBB1);
584   PHINode *LabelPHI = IRB.CreatePHI(IRB.getInt32Ty(), 2, "label");
585   LabelPHI->addIncoming(ThenLabel, EndBB2);
586 
587   LabelPHI->addIncoming(IRB.getInt32(-1), ElseBB1);
588 
589   // Output parameter assignment
590   Label = LabelPHI;
591   EndBB = EndBB1;
592   LongjmpResult = IRB.CreateCall(GetTempRet0Func, None, "longjmp_result");
593 }
594 
595 void WebAssemblyLowerEmscriptenEHSjLj::rebuildSSA(Function &F) {
596   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
597   DT.recalculate(F); // CFG has been changed
598   SSAUpdater SSA;
599   for (BasicBlock &BB : F) {
600     for (Instruction &I : BB) {
601       for (auto UI = I.use_begin(), UE = I.use_end(); UI != UE;) {
602         Use &U = *UI;
603         ++UI;
604         SSA.Initialize(I.getType(), I.getName());
605         SSA.AddAvailableValue(&BB, &I);
606         auto *User = cast<Instruction>(U.getUser());
607         if (User->getParent() == &BB)
608           continue;
609 
610         if (auto *UserPN = dyn_cast<PHINode>(User))
611           if (UserPN->getIncomingBlock(U) == &BB)
612             continue;
613 
614         if (DT.dominates(&I, User))
615           continue;
616         SSA.RewriteUseAfterInsertions(U);
617       }
618     }
619   }
620 }
621 
622 bool WebAssemblyLowerEmscriptenEHSjLj::runOnModule(Module &M) {
623   LLVM_DEBUG(dbgs() << "********** Lower Emscripten EH & SjLj **********\n");
624 
625   LLVMContext &C = M.getContext();
626   IRBuilder<> IRB(C);
627 
628   Function *SetjmpF = M.getFunction("setjmp");
629   Function *LongjmpF = M.getFunction("longjmp");
630   bool SetjmpUsed = SetjmpF && !SetjmpF->use_empty();
631   bool LongjmpUsed = LongjmpF && !LongjmpF->use_empty();
632   bool DoSjLj = EnableSjLj && (SetjmpUsed || LongjmpUsed);
633 
634   // Declare (or get) global variables __THREW__, __threwValue, and
635   // getTempRet0/setTempRet0 function which are used in common for both
636   // exception handling and setjmp/longjmp handling
637   ThrewGV = getGlobalVariableI32(M, IRB, "__THREW__");
638   ThrewValueGV = getGlobalVariableI32(M, IRB, "__threwValue");
639   GetTempRet0Func =
640       Function::Create(FunctionType::get(IRB.getInt32Ty(), false),
641                        GlobalValue::ExternalLinkage, "getTempRet0", &M);
642   SetTempRet0Func = Function::Create(
643       FunctionType::get(IRB.getVoidTy(), IRB.getInt32Ty(), false),
644       GlobalValue::ExternalLinkage, "setTempRet0", &M);
645   GetTempRet0Func->setDoesNotThrow();
646   SetTempRet0Func->setDoesNotThrow();
647 
648   bool Changed = false;
649 
650   // Exception handling
651   if (EnableEH) {
652     // Register __resumeException function
653     FunctionType *ResumeFTy =
654         FunctionType::get(IRB.getVoidTy(), IRB.getInt8PtrTy(), false);
655     ResumeF = Function::Create(ResumeFTy, GlobalValue::ExternalLinkage,
656                                ResumeFName, &M);
657 
658     // Register llvm_eh_typeid_for function
659     FunctionType *EHTypeIDTy =
660         FunctionType::get(IRB.getInt32Ty(), IRB.getInt8PtrTy(), false);
661     EHTypeIDF = Function::Create(EHTypeIDTy, GlobalValue::ExternalLinkage,
662                                  EHTypeIDFName, &M);
663 
664     for (Function &F : M) {
665       if (F.isDeclaration())
666         continue;
667       Changed |= runEHOnFunction(F);
668     }
669   }
670 
671   // Setjmp/longjmp handling
672   if (DoSjLj) {
673     Changed = true; // We have setjmp or longjmp somewhere
674 
675     if (LongjmpF) {
676       // Replace all uses of longjmp with emscripten_longjmp_jmpbuf, which is
677       // defined in JS code
678       EmLongjmpJmpbufF = Function::Create(LongjmpF->getFunctionType(),
679                                           GlobalValue::ExternalLinkage,
680                                           EmLongjmpJmpbufFName, &M);
681 
682       LongjmpF->replaceAllUsesWith(EmLongjmpJmpbufF);
683     }
684 
685     if (SetjmpF) {
686       // Register saveSetjmp function
687       FunctionType *SetjmpFTy = SetjmpF->getFunctionType();
688       SmallVector<Type *, 4> Params = {SetjmpFTy->getParamType(0),
689                                        IRB.getInt32Ty(), Type::getInt32PtrTy(C),
690                                        IRB.getInt32Ty()};
691       FunctionType *FTy =
692           FunctionType::get(Type::getInt32PtrTy(C), Params, false);
693       SaveSetjmpF = Function::Create(FTy, GlobalValue::ExternalLinkage,
694                                      SaveSetjmpFName, &M);
695 
696       // Register testSetjmp function
697       Params = {IRB.getInt32Ty(), Type::getInt32PtrTy(C), IRB.getInt32Ty()};
698       FTy = FunctionType::get(IRB.getInt32Ty(), Params, false);
699       TestSetjmpF = Function::Create(FTy, GlobalValue::ExternalLinkage,
700                                      TestSetjmpFName, &M);
701 
702       FTy = FunctionType::get(IRB.getVoidTy(),
703                               {IRB.getInt32Ty(), IRB.getInt32Ty()}, false);
704       EmLongjmpF = Function::Create(FTy, GlobalValue::ExternalLinkage,
705                                     EmLongjmpFName, &M);
706 
707       // Only traverse functions that uses setjmp in order not to insert
708       // unnecessary prep / cleanup code in every function
709       SmallPtrSet<Function *, 8> SetjmpUsers;
710       for (User *U : SetjmpF->users()) {
711         auto *UI = cast<Instruction>(U);
712         SetjmpUsers.insert(UI->getFunction());
713       }
714       for (Function *F : SetjmpUsers)
715         runSjLjOnFunction(*F);
716     }
717   }
718 
719   if (!Changed) {
720     // Delete unused global variables and functions
721     if (ResumeF)
722       ResumeF->eraseFromParent();
723     if (EHTypeIDF)
724       EHTypeIDF->eraseFromParent();
725     if (EmLongjmpF)
726       EmLongjmpF->eraseFromParent();
727     if (SaveSetjmpF)
728       SaveSetjmpF->eraseFromParent();
729     if (TestSetjmpF)
730       TestSetjmpF->eraseFromParent();
731     return false;
732   }
733 
734   return true;
735 }
736 
737 bool WebAssemblyLowerEmscriptenEHSjLj::runEHOnFunction(Function &F) {
738   Module &M = *F.getParent();
739   LLVMContext &C = F.getContext();
740   IRBuilder<> IRB(C);
741   bool Changed = false;
742   SmallVector<Instruction *, 64> ToErase;
743   SmallPtrSet<LandingPadInst *, 32> LandingPads;
744   bool AllowExceptions =
745       areAllExceptionsAllowed() || EHWhitelistSet.count(F.getName());
746 
747   for (BasicBlock &BB : F) {
748     auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
749     if (!II)
750       continue;
751     Changed = true;
752     LandingPads.insert(II->getLandingPadInst());
753     IRB.SetInsertPoint(II);
754 
755     bool NeedInvoke = AllowExceptions && canThrow(II->getCalledValue());
756     if (NeedInvoke) {
757       // Wrap invoke with invoke wrapper and generate preamble/postamble
758       Value *Threw = wrapInvoke(II);
759       ToErase.push_back(II);
760 
761       // Insert a branch based on __THREW__ variable
762       Value *Cmp = IRB.CreateICmpEQ(Threw, IRB.getInt32(1), "cmp");
763       IRB.CreateCondBr(Cmp, II->getUnwindDest(), II->getNormalDest());
764 
765     } else {
766       // This can't throw, and we don't need this invoke, just replace it with a
767       // call+branch
768       SmallVector<Value *, 16> Args(II->arg_begin(), II->arg_end());
769       CallInst *NewCall =
770           IRB.CreateCall(II->getFunctionType(), II->getCalledValue(), Args);
771       NewCall->takeName(II);
772       NewCall->setCallingConv(II->getCallingConv());
773       NewCall->setDebugLoc(II->getDebugLoc());
774       NewCall->setAttributes(II->getAttributes());
775       II->replaceAllUsesWith(NewCall);
776       ToErase.push_back(II);
777 
778       IRB.CreateBr(II->getNormalDest());
779 
780       // Remove any PHI node entries from the exception destination
781       II->getUnwindDest()->removePredecessor(&BB);
782     }
783   }
784 
785   // Process resume instructions
786   for (BasicBlock &BB : F) {
787     // Scan the body of the basic block for resumes
788     for (Instruction &I : BB) {
789       auto *RI = dyn_cast<ResumeInst>(&I);
790       if (!RI)
791         continue;
792 
793       // Split the input into legal values
794       Value *Input = RI->getValue();
795       IRB.SetInsertPoint(RI);
796       Value *Low = IRB.CreateExtractValue(Input, 0, "low");
797       // Create a call to __resumeException function
798       IRB.CreateCall(ResumeF, {Low});
799       // Add a terminator to the block
800       IRB.CreateUnreachable();
801       ToErase.push_back(RI);
802     }
803   }
804 
805   // Process llvm.eh.typeid.for intrinsics
806   for (BasicBlock &BB : F) {
807     for (Instruction &I : BB) {
808       auto *CI = dyn_cast<CallInst>(&I);
809       if (!CI)
810         continue;
811       const Function *Callee = CI->getCalledFunction();
812       if (!Callee)
813         continue;
814       if (Callee->getIntrinsicID() != Intrinsic::eh_typeid_for)
815         continue;
816 
817       IRB.SetInsertPoint(CI);
818       CallInst *NewCI =
819           IRB.CreateCall(EHTypeIDF, CI->getArgOperand(0), "typeid");
820       CI->replaceAllUsesWith(NewCI);
821       ToErase.push_back(CI);
822     }
823   }
824 
825   // Look for orphan landingpads, can occur in blocks with no predecessors
826   for (BasicBlock &BB : F) {
827     Instruction *I = BB.getFirstNonPHI();
828     if (auto *LPI = dyn_cast<LandingPadInst>(I))
829       LandingPads.insert(LPI);
830   }
831 
832   // Handle all the landingpad for this function together, as multiple invokes
833   // may share a single lp
834   for (LandingPadInst *LPI : LandingPads) {
835     IRB.SetInsertPoint(LPI);
836     SmallVector<Value *, 16> FMCArgs;
837     for (unsigned I = 0, E = LPI->getNumClauses(); I < E; ++I) {
838       Constant *Clause = LPI->getClause(I);
839       // As a temporary workaround for the lack of aggregate varargs support
840       // in the interface between JS and wasm, break out filter operands into
841       // their component elements.
842       if (LPI->isFilter(I)) {
843         auto *ATy = cast<ArrayType>(Clause->getType());
844         for (unsigned J = 0, E = ATy->getNumElements(); J < E; ++J) {
845           Value *EV = IRB.CreateExtractValue(Clause, makeArrayRef(J), "filter");
846           FMCArgs.push_back(EV);
847         }
848       } else
849         FMCArgs.push_back(Clause);
850     }
851 
852     // Create a call to __cxa_find_matching_catch_N function
853     Function *FMCF = getFindMatchingCatch(M, FMCArgs.size());
854     CallInst *FMCI = IRB.CreateCall(FMCF, FMCArgs, "fmc");
855     Value *Undef = UndefValue::get(LPI->getType());
856     Value *Pair0 = IRB.CreateInsertValue(Undef, FMCI, 0, "pair0");
857     Value *TempRet0 = IRB.CreateCall(GetTempRet0Func, None, "tempret0");
858     Value *Pair1 = IRB.CreateInsertValue(Pair0, TempRet0, 1, "pair1");
859 
860     LPI->replaceAllUsesWith(Pair1);
861     ToErase.push_back(LPI);
862   }
863 
864   // Erase everything we no longer need in this function
865   for (Instruction *I : ToErase)
866     I->eraseFromParent();
867 
868   return Changed;
869 }
870 
871 bool WebAssemblyLowerEmscriptenEHSjLj::runSjLjOnFunction(Function &F) {
872   Module &M = *F.getParent();
873   LLVMContext &C = F.getContext();
874   IRBuilder<> IRB(C);
875   SmallVector<Instruction *, 64> ToErase;
876   // Vector of %setjmpTable values
877   std::vector<Instruction *> SetjmpTableInsts;
878   // Vector of %setjmpTableSize values
879   std::vector<Instruction *> SetjmpTableSizeInsts;
880 
881   // Setjmp preparation
882 
883   // This instruction effectively means %setjmpTableSize = 4.
884   // We create this as an instruction intentionally, and we don't want to fold
885   // this instruction to a constant 4, because this value will be used in
886   // SSAUpdater.AddAvailableValue(...) later.
887   BasicBlock &EntryBB = F.getEntryBlock();
888   BinaryOperator *SetjmpTableSize = BinaryOperator::Create(
889       Instruction::Add, IRB.getInt32(4), IRB.getInt32(0), "setjmpTableSize",
890       &*EntryBB.getFirstInsertionPt());
891   // setjmpTable = (int *) malloc(40);
892   Instruction *SetjmpTable = CallInst::CreateMalloc(
893       SetjmpTableSize, IRB.getInt32Ty(), IRB.getInt32Ty(), IRB.getInt32(40),
894       nullptr, nullptr, "setjmpTable");
895   // setjmpTable[0] = 0;
896   IRB.SetInsertPoint(SetjmpTableSize);
897   IRB.CreateStore(IRB.getInt32(0), SetjmpTable);
898   SetjmpTableInsts.push_back(SetjmpTable);
899   SetjmpTableSizeInsts.push_back(SetjmpTableSize);
900 
901   // Setjmp transformation
902   std::vector<PHINode *> SetjmpRetPHIs;
903   Function *SetjmpF = M.getFunction("setjmp");
904   for (User *U : SetjmpF->users()) {
905     auto *CI = dyn_cast<CallInst>(U);
906     if (!CI)
907       report_fatal_error("Does not support indirect calls to setjmp");
908 
909     BasicBlock *BB = CI->getParent();
910     if (BB->getParent() != &F) // in other function
911       continue;
912 
913     // The tail is everything right after the call, and will be reached once
914     // when setjmp is called, and later when longjmp returns to the setjmp
915     BasicBlock *Tail = SplitBlock(BB, CI->getNextNode());
916     // Add a phi to the tail, which will be the output of setjmp, which
917     // indicates if this is the first call or a longjmp back. The phi directly
918     // uses the right value based on where we arrive from
919     IRB.SetInsertPoint(Tail->getFirstNonPHI());
920     PHINode *SetjmpRet = IRB.CreatePHI(IRB.getInt32Ty(), 2, "setjmp.ret");
921 
922     // setjmp initial call returns 0
923     SetjmpRet->addIncoming(IRB.getInt32(0), BB);
924     // The proper output is now this, not the setjmp call itself
925     CI->replaceAllUsesWith(SetjmpRet);
926     // longjmp returns to the setjmp will add themselves to this phi
927     SetjmpRetPHIs.push_back(SetjmpRet);
928 
929     // Fix call target
930     // Our index in the function is our place in the array + 1 to avoid index
931     // 0, because index 0 means the longjmp is not ours to handle.
932     IRB.SetInsertPoint(CI);
933     Value *Args[] = {CI->getArgOperand(0), IRB.getInt32(SetjmpRetPHIs.size()),
934                      SetjmpTable, SetjmpTableSize};
935     Instruction *NewSetjmpTable =
936         IRB.CreateCall(SaveSetjmpF, Args, "setjmpTable");
937     Instruction *NewSetjmpTableSize =
938         IRB.CreateCall(GetTempRet0Func, None, "setjmpTableSize");
939     SetjmpTableInsts.push_back(NewSetjmpTable);
940     SetjmpTableSizeInsts.push_back(NewSetjmpTableSize);
941     ToErase.push_back(CI);
942   }
943 
944   // Update each call that can longjmp so it can return to a setjmp where
945   // relevant.
946 
947   // Because we are creating new BBs while processing and don't want to make
948   // all these newly created BBs candidates again for longjmp processing, we
949   // first make the vector of candidate BBs.
950   std::vector<BasicBlock *> BBs;
951   for (BasicBlock &BB : F)
952     BBs.push_back(&BB);
953 
954   // BBs.size() will change within the loop, so we query it every time
955   for (unsigned I = 0; I < BBs.size(); I++) {
956     BasicBlock *BB = BBs[I];
957     for (Instruction &I : *BB) {
958       assert(!isa<InvokeInst>(&I));
959       auto *CI = dyn_cast<CallInst>(&I);
960       if (!CI)
961         continue;
962 
963       const Value *Callee = CI->getCalledValue();
964       if (!canLongjmp(M, Callee))
965         continue;
966 
967       Value *Threw = nullptr;
968       BasicBlock *Tail;
969       if (Callee->getName().startswith(InvokePrefix)) {
970         // If invoke wrapper has already been generated for this call in
971         // previous EH phase, search for the load instruction
972         // %__THREW__.val = __THREW__;
973         // in postamble after the invoke wrapper call
974         LoadInst *ThrewLI = nullptr;
975         StoreInst *ThrewResetSI = nullptr;
976         for (auto I = std::next(BasicBlock::iterator(CI)), IE = BB->end();
977              I != IE; ++I) {
978           if (auto *LI = dyn_cast<LoadInst>(I))
979             if (auto *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand()))
980               if (GV == ThrewGV) {
981                 Threw = ThrewLI = LI;
982                 break;
983               }
984         }
985         // Search for the store instruction after the load above
986         // __THREW__ = 0;
987         for (auto I = std::next(BasicBlock::iterator(ThrewLI)), IE = BB->end();
988              I != IE; ++I) {
989           if (auto *SI = dyn_cast<StoreInst>(I))
990             if (auto *GV = dyn_cast<GlobalVariable>(SI->getPointerOperand()))
991               if (GV == ThrewGV && SI->getValueOperand() == IRB.getInt32(0)) {
992                 ThrewResetSI = SI;
993                 break;
994               }
995         }
996         assert(Threw && ThrewLI && "Cannot find __THREW__ load after invoke");
997         assert(ThrewResetSI && "Cannot find __THREW__ store after invoke");
998         Tail = SplitBlock(BB, ThrewResetSI->getNextNode());
999 
1000       } else {
1001         // Wrap call with invoke wrapper and generate preamble/postamble
1002         Threw = wrapInvoke(CI);
1003         ToErase.push_back(CI);
1004         Tail = SplitBlock(BB, CI->getNextNode());
1005       }
1006 
1007       // We need to replace the terminator in Tail - SplitBlock makes BB go
1008       // straight to Tail, we need to check if a longjmp occurred, and go to the
1009       // right setjmp-tail if so
1010       ToErase.push_back(BB->getTerminator());
1011 
1012       // Generate a function call to testSetjmp function and preamble/postamble
1013       // code to figure out (1) whether longjmp occurred (2) if longjmp
1014       // occurred, which setjmp it corresponds to
1015       Value *Label = nullptr;
1016       Value *LongjmpResult = nullptr;
1017       BasicBlock *EndBB = nullptr;
1018       wrapTestSetjmp(BB, CI, Threw, SetjmpTable, SetjmpTableSize, Label,
1019                      LongjmpResult, EndBB);
1020       assert(Label && LongjmpResult && EndBB);
1021 
1022       // Create switch instruction
1023       IRB.SetInsertPoint(EndBB);
1024       SwitchInst *SI = IRB.CreateSwitch(Label, Tail, SetjmpRetPHIs.size());
1025       // -1 means no longjmp happened, continue normally (will hit the default
1026       // switch case). 0 means a longjmp that is not ours to handle, needs a
1027       // rethrow. Otherwise the index is the same as the index in P+1 (to avoid
1028       // 0).
1029       for (unsigned I = 0; I < SetjmpRetPHIs.size(); I++) {
1030         SI->addCase(IRB.getInt32(I + 1), SetjmpRetPHIs[I]->getParent());
1031         SetjmpRetPHIs[I]->addIncoming(LongjmpResult, EndBB);
1032       }
1033 
1034       // We are splitting the block here, and must continue to find other calls
1035       // in the block - which is now split. so continue to traverse in the Tail
1036       BBs.push_back(Tail);
1037     }
1038   }
1039 
1040   // Erase everything we no longer need in this function
1041   for (Instruction *I : ToErase)
1042     I->eraseFromParent();
1043 
1044   // Free setjmpTable buffer before each return instruction
1045   for (BasicBlock &BB : F) {
1046     Instruction *TI = BB.getTerminator();
1047     if (isa<ReturnInst>(TI))
1048       CallInst::CreateFree(SetjmpTable, TI);
1049   }
1050 
1051   // Every call to saveSetjmp can change setjmpTable and setjmpTableSize
1052   // (when buffer reallocation occurs)
1053   // entry:
1054   //   setjmpTableSize = 4;
1055   //   setjmpTable = (int *) malloc(40);
1056   //   setjmpTable[0] = 0;
1057   // ...
1058   // somebb:
1059   //   setjmpTable = saveSetjmp(buf, label, setjmpTable, setjmpTableSize);
1060   //   setjmpTableSize = getTempRet0();
1061   // So we need to make sure the SSA for these variables is valid so that every
1062   // saveSetjmp and testSetjmp calls have the correct arguments.
1063   SSAUpdater SetjmpTableSSA;
1064   SSAUpdater SetjmpTableSizeSSA;
1065   SetjmpTableSSA.Initialize(Type::getInt32PtrTy(C), "setjmpTable");
1066   SetjmpTableSizeSSA.Initialize(Type::getInt32Ty(C), "setjmpTableSize");
1067   for (Instruction *I : SetjmpTableInsts)
1068     SetjmpTableSSA.AddAvailableValue(I->getParent(), I);
1069   for (Instruction *I : SetjmpTableSizeInsts)
1070     SetjmpTableSizeSSA.AddAvailableValue(I->getParent(), I);
1071 
1072   for (auto UI = SetjmpTable->use_begin(), UE = SetjmpTable->use_end();
1073        UI != UE;) {
1074     // Grab the use before incrementing the iterator.
1075     Use &U = *UI;
1076     // Increment the iterator before removing the use from the list.
1077     ++UI;
1078     if (auto *I = dyn_cast<Instruction>(U.getUser()))
1079       if (I->getParent() != &EntryBB)
1080         SetjmpTableSSA.RewriteUse(U);
1081   }
1082   for (auto UI = SetjmpTableSize->use_begin(), UE = SetjmpTableSize->use_end();
1083        UI != UE;) {
1084     Use &U = *UI;
1085     ++UI;
1086     if (auto *I = dyn_cast<Instruction>(U.getUser()))
1087       if (I->getParent() != &EntryBB)
1088         SetjmpTableSizeSSA.RewriteUse(U);
1089   }
1090 
1091   // Finally, our modifications to the cfg can break dominance of SSA variables.
1092   // For example, in this code,
1093   // if (x()) { .. setjmp() .. }
1094   // if (y()) { .. longjmp() .. }
1095   // We must split the longjmp block, and it can jump into the block splitted
1096   // from setjmp one. But that means that when we split the setjmp block, it's
1097   // first part no longer dominates its second part - there is a theoretically
1098   // possible control flow path where x() is false, then y() is true and we
1099   // reach the second part of the setjmp block, without ever reaching the first
1100   // part. So, we rebuild SSA form here.
1101   rebuildSSA(F);
1102   return true;
1103 }
1104