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