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 function
11/// calls to use Emscripten's library functions. The pass uses JavaScript's try
12/// and catch mechanism in case of Emscripten EH/SjLj and Wasm EH intrinsics in
13/// case of Emscripten SjLJ.
14///
15/// * Emscripten exception handling
16/// This pass lowers invokes and landingpads into library functions in JS glue
17/// code. Invokes are lowered into function wrappers called invoke wrappers that
18/// exist in JS side, which wraps the original function call with JS try-catch.
19/// If an exception occurred, cxa_throw() function in JS side sets some
20/// variables (see below) so we can check whether an exception occurred from
21/// wasm code and handle it appropriately.
22///
23/// * Emscripten setjmp-longjmp handling
24/// This pass lowers setjmp to a reasonably-performant approach for emscripten.
25/// The idea is that each block with a setjmp is broken up into two parts: the
26/// part containing setjmp and the part right after the setjmp. The latter part
27/// is either reached from the setjmp, or later from a longjmp. To handle the
28/// longjmp, all calls that might longjmp are also called using invoke wrappers
29/// and thus JS / try-catch. JS longjmp() function also sets some variables so
30/// we can check / whether a longjmp occurred from wasm code. Each block with a
31/// function call that might longjmp is also split up after the longjmp call.
32/// After the longjmp call, we check whether a longjmp occurred, and if it did,
33/// which setjmp it corresponds to, and jump to the right post-setjmp block.
34/// We assume setjmp-longjmp handling always run after EH handling, which means
35/// we don't expect any exception-related instructions when SjLj runs.
36/// FIXME Currently this scheme does not support indirect call of setjmp,
37/// because of the limitation of the scheme itself. fastcomp does not support it
38/// either.
39///
40/// In detail, this pass does following things:
41///
42/// 1) Assumes the existence of global variables: __THREW__, __threwValue
43/// __THREW__ and __threwValue are defined in compiler-rt in Emscripten.
44/// These variables are used for both exceptions and setjmp/longjmps.
45/// __THREW__ indicates whether an exception or a longjmp occurred or not. 0
46/// means nothing occurred, 1 means an exception occurred, and other numbers
47/// mean a longjmp occurred. In the case of longjmp, __THREW__ variable
48/// indicates the corresponding setjmp buffer the longjmp corresponds to.
49/// __threwValue is 0 for exceptions, and the argument to longjmp in case of
50/// longjmp.
51///
52/// * Emscripten exception handling
53///
54/// 2) We assume the existence of setThrew and setTempRet0/getTempRet0 functions
55/// at link time. setThrew exists in Emscripten's compiler-rt:
56///
57/// void setThrew(uintptr_t threw, int value) {
58/// if (__THREW__ == 0) {
59/// __THREW__ = threw;
60/// __threwValue = value;
61/// }
62/// }
63//
64/// setTempRet0 is called from __cxa_find_matching_catch() in JS glue code.
65/// In exception handling, getTempRet0 indicates the type of an exception
66/// caught, and in setjmp/longjmp, it means the second argument to longjmp
67/// function.
68///
69/// 3) Lower
70/// invoke @func(arg1, arg2) to label %invoke.cont unwind label %lpad
71/// into
72/// __THREW__ = 0;
73/// call @__invoke_SIG(func, arg1, arg2)
74/// %__THREW__.val = __THREW__;
75/// __THREW__ = 0;
76/// if (%__THREW__.val == 1)
77/// goto %lpad
78/// else
79/// goto %invoke.cont
80/// SIG is a mangled string generated based on the LLVM IR-level function
81/// signature. After LLVM IR types are lowered to the target wasm types,
82/// the names for these wrappers will change based on wasm types as well,
83/// as in invoke_vi (function takes an int and returns void). The bodies of
84/// these wrappers will be generated in JS glue code, and inside those
85/// wrappers we use JS try-catch to generate actual exception effects. It
86/// also calls the original callee function. An example wrapper in JS code
87/// would look like this:
88/// function invoke_vi(index,a1) {
89/// try {
90/// Module["dynCall_vi"](index,a1); // This calls original callee
91/// } catch(e) {
92/// if (typeof e !== 'number' && e !== 'longjmp') throw e;
93/// _setThrew(1, 0); // setThrew is called here
94/// }
95/// }
96/// If an exception is thrown, __THREW__ will be set to true in a wrapper,
97/// so we can jump to the right BB based on this value.
98///
99/// 4) Lower
100/// %val = landingpad catch c1 catch c2 catch c3 ...
101/// ... use %val ...
102/// into
103/// %fmc = call @__cxa_find_matching_catch_N(c1, c2, c3, ...)
104/// %val = {%fmc, getTempRet0()}
105/// ... use %val ...
106/// Here N is a number calculated based on the number of clauses.
107/// setTempRet0 is called from __cxa_find_matching_catch() in JS glue code.
108///
109/// 5) Lower
110/// resume {%a, %b}
111/// into
112/// call @__resumeException(%a)
113/// where __resumeException() is a function in JS glue code.
114///
115/// 6) Lower
116/// call @llvm.eh.typeid.for(type) (intrinsic)
117/// into
118/// call @llvm_eh_typeid_for(type)
119/// llvm_eh_typeid_for function will be generated in JS glue code.
120///
121/// * Emscripten setjmp / longjmp handling
122///
123/// If there are calls to longjmp()
124///
125/// 1) Lower
126/// longjmp(env, val)
127/// into
128/// emscripten_longjmp(env, val)
129///
130/// If there are calls to setjmp()
131///
132/// 2) In the function entry that calls setjmp, initialize
133/// functionInvocationId as follows:
134///
135/// functionInvocationId = alloca(4)
136///
137/// Note: the alloca size is not important as this pointer is
138/// merely used for pointer comparisions.
139///
140/// 3) Lower
141/// setjmp(env)
142/// into
143/// __wasm_setjmp(env, label, functionInvocationId)
144///
145/// __wasm_setjmp records the necessary info (the label and
146/// functionInvocationId) to the "env".
147/// A BB with setjmp is split into two after setjmp call in order to
148/// make the post-setjmp BB the possible destination of longjmp BB.
149///
150/// 4) Lower every call that might longjmp into
151/// __THREW__ = 0;
152/// call @__invoke_SIG(func, arg1, arg2)
153/// %__THREW__.val = __THREW__;
154/// __THREW__ = 0;
155/// %__threwValue.val = __threwValue;
156/// if (%__THREW__.val != 0 & %__threwValue.val != 0) {
157/// %label = __wasm_setjmp_test(%__THREW__.val, functionInvocationId);
158/// if (%label == 0)
159/// emscripten_longjmp(%__THREW__.val, %__threwValue.val);
160/// setTempRet0(%__threwValue.val);
161/// } else {
162/// %label = -1;
163/// }
164/// longjmp_result = getTempRet0();
165/// switch %label {
166/// label 1: goto post-setjmp BB 1
167/// label 2: goto post-setjmp BB 2
168/// ...
169/// default: goto splitted next BB
170/// }
171///
172/// __wasm_setjmp_test examines the jmp buf to see if it was for a matching
173/// setjmp call. After calling an invoke wrapper, if a longjmp occurred,
174/// __THREW__ will be the address of matching jmp_buf buffer and
175/// __threwValue be the second argument to longjmp.
176/// __wasm_setjmp_test returns a setjmp label, a unique ID to each setjmp
177/// callsite. Label 0 means this longjmp buffer does not correspond to one
178/// of the setjmp callsites in this function, so in this case we just chain
179/// the longjmp to the caller. Label -1 means no longjmp occurred.
180/// Otherwise we jump to the right post-setjmp BB based on the label.
181///
182/// * Wasm setjmp / longjmp handling
183/// This mode still uses some Emscripten library functions but not JavaScript's
184/// try-catch mechanism. It instead uses Wasm exception handling intrinsics,
185/// which will be lowered to exception handling instructions.
186///
187/// If there are calls to longjmp()
188///
189/// 1) Lower
190/// longjmp(env, val)
191/// into
192/// __wasm_longjmp(env, val)
193///
194/// If there are calls to setjmp()
195///
196/// 2) and 3): The same as 2) and 3) in Emscripten SjLj.
197/// (functionInvocationId initialization + setjmp callsite transformation)
198///
199/// 4) Create a catchpad with a wasm.catch() intrinsic, which returns the value
200/// thrown by __wasm_longjmp function. In the runtime library, we have an
201/// equivalent of the following struct:
202///
203/// struct __WasmLongjmpArgs {
204/// void *env;
205/// int val;
206/// };
207///
208/// The thrown value here is a pointer to the struct. We use this struct to
209/// transfer two values by throwing a single value. Wasm throw and catch
210/// instructions are capable of throwing and catching multiple values, but
211/// it also requires multivalue support that is currently not very reliable.
212/// TODO Switch to throwing and catching two values without using the struct
213///
214/// All longjmpable function calls will be converted to an invoke that will
215/// unwind to this catchpad in case a longjmp occurs. Within the catchpad, we
216/// test the thrown values using __wasm_setjmp_test function as we do for
217/// Emscripten SjLj. The main difference is, in Emscripten SjLj, we need to
218/// transform every longjmpable callsite into a sequence of code including
219/// __wasm_setjmp_test() call; in Wasm SjLj we do the testing in only one
220/// place, in this catchpad.
221///
222/// After testing calling __wasm_setjmp_test(), if the longjmp does not
223/// correspond to one of the setjmps within the current function, it rethrows
224/// the longjmp by calling __wasm_longjmp(). If it corresponds to one of
225/// setjmps in the function, we jump to the beginning of the function, which
226/// contains a switch to each post-setjmp BB. Again, in Emscripten SjLj, this
227/// switch is added for every longjmpable callsite; in Wasm SjLj we do this
228/// only once at the top of the function. (after functionInvocationId
229/// initialization)
230///
231/// The below is the pseudocode for what we have described
232///
233/// entry:
234/// Initialize functionInvocationId
235///
236/// setjmp.dispatch:
237/// switch %label {
238/// label 1: goto post-setjmp BB 1
239/// label 2: goto post-setjmp BB 2
240/// ...
241/// default: goto splitted next BB
242/// }
243/// ...
244///
245/// bb:
246/// invoke void @foo() ;; foo is a longjmpable function
247/// to label %next unwind label %catch.dispatch.longjmp
248/// ...
249///
250/// catch.dispatch.longjmp:
251/// %0 = catchswitch within none [label %catch.longjmp] unwind to caller
252///
253/// catch.longjmp:
254/// %longjmp.args = wasm.catch() ;; struct __WasmLongjmpArgs
255/// %env = load 'env' field from __WasmLongjmpArgs
256/// %val = load 'val' field from __WasmLongjmpArgs
257/// %label = __wasm_setjmp_test(%env, functionInvocationId);
258/// if (%label == 0)
259/// __wasm_longjmp(%env, %val)
260/// catchret to %setjmp.dispatch
261///
262///===----------------------------------------------------------------------===//
263
264#include "WebAssembly.h"
265#include "WebAssemblyTargetMachine.h"
266#include "llvm/ADT/MapVector.h"
267#include "llvm/ADT/StringExtras.h"
268#include "llvm/CodeGen/MachineModuleInfo.h"
269#include "llvm/CodeGen/WasmEHInfo.h"
270#include "llvm/IR/Analysis.h"
271#include "llvm/IR/DebugInfoMetadata.h"
272#include "llvm/IR/Dominators.h"
273#include "llvm/IR/IRBuilder.h"
274#include "llvm/IR/IntrinsicsWebAssembly.h"
275#include "llvm/IR/Module.h"
276#include "llvm/IR/PassManager.h"
277#include "llvm/Pass.h"
278#include "llvm/Support/CommandLine.h"
279#include "llvm/Transforms/Utils/BasicBlockUtils.h"
280#include "llvm/Transforms/Utils/Local.h"
281#include "llvm/Transforms/Utils/SSAUpdater.h"
282#include "llvm/Transforms/Utils/SSAUpdaterBulk.h"
283#include <set>
284
285using namespace llvm;
286
287#define DEBUG_TYPE "wasm-lower-em-ehsjlj"
288
289static cl::list<std::string>
290 EHAllowlist("emscripten-cxx-exceptions-allowed",
291 cl::desc("The list of function names in which Emscripten-style "
292 "exception handling is enabled (see emscripten "
293 "EMSCRIPTEN_CATCHING_ALLOWED options)"),
294 cl::CommaSeparated);
295
296namespace {
297class WebAssemblyLowerEmscriptenEHSjLjImpl {
298 bool EnableEmEH; // Enable Emscripten exception handling
299 bool EnableEmSjLj; // Enable Emscripten setjmp/longjmp handling
300 bool EnableWasmSjLj; // Enable Wasm setjmp/longjmp handling
301 bool DoSjLj; // Whether we actually perform setjmp/longjmp handling
302
303 GlobalVariable *ThrewGV = nullptr; // __THREW__ (Emscripten)
304 GlobalVariable *ThrewValueGV = nullptr; // __threwValue (Emscripten)
305 Function *GetTempRet0F = nullptr; // getTempRet0() (Emscripten)
306 Function *SetTempRet0F = nullptr; // setTempRet0() (Emscripten)
307 Function *ResumeF = nullptr; // __resumeException() (Emscripten)
308 Function *EHTypeIDF = nullptr; // llvm.eh.typeid.for() (intrinsic)
309 Function *EmLongjmpF = nullptr; // emscripten_longjmp() (Emscripten)
310 Function *WasmSetjmpF = nullptr; // __wasm_setjmp() (Emscripten)
311 Function *WasmSetjmpTestF = nullptr; // __wasm_setjmp_test() (Emscripten)
312 Function *WasmLongjmpF = nullptr; // __wasm_longjmp() (Emscripten)
313 Function *CatchF = nullptr; // wasm.catch() (intrinsic)
314
315 // type of 'struct __WasmLongjmpArgs' defined in emscripten
316 Type *LongjmpArgsTy = nullptr;
317
318 // __cxa_find_matching_catch_N functions.
319 // Indexed by the number of clauses in an original landingpad instruction.
320 DenseMap<int, Function *> FindMatchingCatches;
321 // Map of <function signature string, invoke_ wrappers>
322 StringMap<Function *> InvokeWrappers;
323 // Set of allowed function names for exception handling
324 std::set<std::string, std::less<>> EHAllowlistSet;
325 // Functions that contains calls to setjmp
326 SmallPtrSet<Function *, 8> SetjmpUsers;
327
328 std::function<DominatorTree &(Function &F)> GetDominatorTree;
329
330 using InstVector = SmallVectorImpl<Instruction *>;
331 bool runEHOnFunction(Function &F);
332 bool runSjLjOnFunction(Function &F);
333 void handleLongjmpableCallsForEmscriptenSjLj(
334 Function &F, Instruction *FunctionInvocationId,
335 SmallVectorImpl<PHINode *> &SetjmpRetPHIs);
336 void
337 handleLongjmpableCallsForWasmSjLj(Function &F,
338 Instruction *FunctionInvocationId,
339 SmallVectorImpl<PHINode *> &SetjmpRetPHIs);
340 Function *getFindMatchingCatch(Module &M, unsigned NumClauses);
341
342 Value *wrapInvoke(CallBase *CI);
343 void wrapTestSetjmp(BasicBlock *BB, DebugLoc DL, Value *Threw,
344 Value *FunctionInvocationId, Value *&Label,
345 Value *&LongjmpResult, BasicBlock *&CallEmLongjmpBB,
346 PHINode *&CallEmLongjmpBBThrewPHI,
347 PHINode *&CallEmLongjmpBBThrewValuePHI,
348 BasicBlock *&EndBB);
349 Function *getInvokeWrapper(CallBase *CI);
350
351 bool areAllExceptionsAllowed() const { return EHAllowlistSet.empty(); }
352 bool supportsException(const Function *F) const {
353 return EnableEmEH &&
354 (areAllExceptionsAllowed() || EHAllowlistSet.count(x: F->getName()));
355 }
356 void replaceLongjmpWith(Function *LongjmpF, Function *NewF);
357
358 void rebuildSSA(Function &F);
359
360public:
361 WebAssemblyLowerEmscriptenEHSjLjImpl(
362 std::function<DominatorTree &(Function &F)> GetDominatorTree)
363 : EnableEmEH(WebAssembly::WasmEnableEmEH),
364 EnableEmSjLj(WebAssembly::WasmEnableEmSjLj),
365 EnableWasmSjLj(WebAssembly::WasmEnableSjLj),
366 GetDominatorTree(GetDominatorTree) {
367 assert(!(EnableEmSjLj && EnableWasmSjLj) &&
368 "Two SjLj modes cannot be turned on at the same time");
369 assert(!(EnableEmEH && EnableWasmSjLj) &&
370 "Wasm SjLj should be only used with Wasm EH");
371 EHAllowlistSet.insert(first: EHAllowlist.begin(), last: EHAllowlist.end());
372 }
373
374 bool runOnModule(Module &M);
375};
376
377class WebAssemblyLowerEmscriptenEHSjLjLegacy final : public ModulePass {
378 StringRef getPassName() const override {
379 return "WebAssembly Lower Emscripten Exceptions";
380 }
381
382public:
383 static char ID;
384
385 WebAssemblyLowerEmscriptenEHSjLjLegacy() : ModulePass(ID) {}
386 bool runOnModule(Module &M) override;
387
388 void getAnalysisUsage(AnalysisUsage &AU) const override {
389 AU.addRequired<DominatorTreeWrapperPass>();
390 }
391};
392} // End anonymous namespace
393
394char WebAssemblyLowerEmscriptenEHSjLjLegacy::ID = 0;
395INITIALIZE_PASS(WebAssemblyLowerEmscriptenEHSjLjLegacy, DEBUG_TYPE,
396 "WebAssembly Lower Emscripten Exceptions / Setjmp / Longjmp",
397 false, false)
398
399ModulePass *llvm::createWebAssemblyLowerEmscriptenEHSjLjLegacyPass() {
400 return new WebAssemblyLowerEmscriptenEHSjLjLegacy();
401}
402
403static bool canThrow(const Value *V) {
404 if (const auto *F = dyn_cast<const Function>(Val: V)) {
405 // Intrinsics cannot throw
406 if (F->isIntrinsic())
407 return false;
408 StringRef Name = F->getName();
409 // leave setjmp and longjmp (mostly) alone, we process them properly later
410 if (Name == "setjmp" || Name == "longjmp" || Name == "emscripten_longjmp")
411 return false;
412 return !F->doesNotThrow();
413 }
414 // not a function, so an indirect call - can throw, we can't tell
415 return true;
416}
417
418// Get a thread-local global variable with the given name. If it doesn't exist
419// declare it, which will generate an import and assume that it will exist at
420// link time.
421static GlobalVariable *getGlobalVariable(Module &M, Type *Ty,
422 const char *Name) {
423 auto *GV = dyn_cast<GlobalVariable>(Val: M.getOrInsertGlobal(Name, Ty));
424 if (!GV)
425 report_fatal_error(reason: Twine("unable to create global: ") + Name);
426
427 // Variables created by this function are thread local. If the target does not
428 // support TLS, we depend on CoalesceFeaturesAndStripAtomics to downgrade it
429 // to non-thread-local ones, in which case we don't allow this object to be
430 // linked with other objects using shared memory.
431 GV->setThreadLocalMode(GlobalValue::GeneralDynamicTLSModel);
432 return GV;
433}
434
435// Simple function name mangler.
436// This function simply takes LLVM's string representation of parameter types
437// and concatenate them with '_'. There are non-alphanumeric characters but llc
438// is ok with it, and we need to postprocess these names after the lowering
439// phase anyway.
440static std::string getSignature(FunctionType *FTy) {
441 std::string Sig;
442 raw_string_ostream OS(Sig);
443 OS << *FTy->getReturnType();
444 for (Type *ParamTy : FTy->params())
445 OS << "_" << *ParamTy;
446 if (FTy->isVarArg())
447 OS << "_...";
448 Sig = OS.str();
449 erase_if(C&: Sig, P: isSpace);
450 // When s2wasm parses .s file, a comma means the end of an argument. So a
451 // mangled function name can contain any character but a comma.
452 llvm::replace(Range&: Sig, OldValue: ',', NewValue: '.');
453 return Sig;
454}
455
456static Function *getFunction(FunctionType *Ty, const Twine &Name, Module *M) {
457 return Function::Create(Ty, Linkage: GlobalValue::ExternalLinkage, N: Name, M);
458}
459
460static void markAsImported(Function *F) {
461 // Tell the linker that this function is expected to be imported from the
462 // 'env' module. This is necessary for functions that do not have fixed names
463 // (e.g. __import_xyz). These names cannot be provided by any kind of shared
464 // or static library as instead we mark them explictly as imported.
465 if (!F->hasFnAttribute(Kind: "wasm-import-module")) {
466 llvm::AttrBuilder B(F->getParent()->getContext());
467 B.addAttribute(A: "wasm-import-module", V: "env");
468 F->addFnAttrs(Attrs: B);
469 }
470 if (!F->hasFnAttribute(Kind: "wasm-import-name")) {
471 llvm::AttrBuilder B(F->getParent()->getContext());
472 B.addAttribute(A: "wasm-import-name", V: F->getName());
473 F->addFnAttrs(Attrs: B);
474 }
475}
476
477// Returns an integer type for the target architecture's address space.
478// i32 for wasm32 and i64 for wasm64.
479static Type *getAddrIntType(Module *M) {
480 IRBuilder<> IRB(M->getContext());
481 return IRB.getIntNTy(N: M->getDataLayout().getPointerSizeInBits());
482}
483
484// Returns an integer pointer type for the target architecture's address space.
485// i32* for wasm32 and i64* for wasm64. With opaque pointers this is just a ptr
486// in address space zero.
487static Type *getAddrPtrType(Module *M) {
488 return PointerType::getUnqual(C&: M->getContext());
489}
490
491// Returns an integer whose type is the integer type for the target's address
492// space. Returns (i32 C) for wasm32 and (i64 C) for wasm64, when C is the
493// integer.
494static Value *getAddrSizeInt(Module *M, uint64_t C) {
495 IRBuilder<> IRB(M->getContext());
496 return IRB.getIntN(N: M->getDataLayout().getPointerSizeInBits(), C);
497}
498
499// Returns true if the function has "target-features"="+exception-handling"
500// attribute.
501static bool hasEHTargetFeatureAttr(const Function &F) {
502 Attribute FeaturesAttr = F.getFnAttribute(Kind: "target-features");
503 return FeaturesAttr.isValid() &&
504 FeaturesAttr.getValueAsString().contains(Other: "+exception-handling");
505}
506
507// Returns __cxa_find_matching_catch_N function, where N = NumClauses + 2.
508// This is because a landingpad instruction contains two more arguments, a
509// personality function and a cleanup bit, and __cxa_find_matching_catch_N
510// functions are named after the number of arguments in the original landingpad
511// instruction.
512Function *WebAssemblyLowerEmscriptenEHSjLjImpl::getFindMatchingCatch(
513 Module &M, unsigned NumClauses) {
514 auto [It, Inserted] = FindMatchingCatches.try_emplace(Key: NumClauses);
515 if (!Inserted)
516 return It->second;
517 PointerType *Int8PtrTy = PointerType::getUnqual(C&: M.getContext());
518 SmallVector<Type *, 16> Args(NumClauses, Int8PtrTy);
519 FunctionType *FTy = FunctionType::get(Result: Int8PtrTy, Params: Args, isVarArg: false);
520 Function *F = getFunction(
521 Ty: FTy, Name: "__cxa_find_matching_catch_" + Twine(NumClauses + 2), M: &M);
522 markAsImported(F);
523 It->second = F;
524 return F;
525}
526
527// Generate invoke wrapper seqence with preamble and postamble
528// Preamble:
529// __THREW__ = 0;
530// Postamble:
531// %__THREW__.val = __THREW__; __THREW__ = 0;
532// Returns %__THREW__.val, which indicates whether an exception is thrown (or
533// whether longjmp occurred), for future use.
534Value *WebAssemblyLowerEmscriptenEHSjLjImpl::wrapInvoke(CallBase *CI) {
535 Module *M = CI->getModule();
536 LLVMContext &C = M->getContext();
537
538 IRBuilder<> IRB(C);
539 IRB.SetInsertPoint(CI);
540
541 // Pre-invoke
542 // __THREW__ = 0;
543 IRB.CreateStore(Val: getAddrSizeInt(M, C: 0), Ptr: ThrewGV);
544
545 // Invoke function wrapper in JavaScript
546 SmallVector<Value *, 16> Args;
547 // Put the pointer to the callee as first argument, so it can be called
548 // within the invoke wrapper later
549 Args.push_back(Elt: CI->getCalledOperand());
550 Args.append(in_start: CI->arg_begin(), in_end: CI->arg_end());
551 CallInst *NewCall = IRB.CreateCall(Callee: getInvokeWrapper(CI), Args);
552 NewCall->takeName(V: CI);
553 NewCall->setCallingConv(CallingConv::WASM_EmscriptenInvoke);
554 NewCall->setDebugLoc(CI->getDebugLoc());
555
556 // Because we added the pointer to the callee as first argument, all
557 // argument attribute indices have to be incremented by one.
558 SmallVector<AttributeSet, 8> ArgAttributes;
559 const AttributeList &InvokeAL = CI->getAttributes();
560
561 // No attributes for the callee pointer.
562 ArgAttributes.push_back(Elt: AttributeSet());
563 // Copy the argument attributes from the original
564 for (unsigned I = 0, E = CI->arg_size(); I < E; ++I)
565 ArgAttributes.push_back(Elt: InvokeAL.getParamAttrs(ArgNo: I));
566
567 AttrBuilder FnAttrs(CI->getContext(), InvokeAL.getFnAttrs());
568 if (auto Args = FnAttrs.getAllocSizeArgs()) {
569 // The allocsize attribute (if any) referes to parameters by index and needs
570 // to be adjusted.
571 auto [SizeArg, NEltArg] = *Args;
572 SizeArg += 1;
573 if (NEltArg)
574 NEltArg = *NEltArg + 1;
575 FnAttrs.addAllocSizeAttr(ElemSizeArg: SizeArg, NumElemsArg: NEltArg);
576 }
577 // In case the callee has 'noreturn' attribute, We need to remove it, because
578 // we expect invoke wrappers to return.
579 FnAttrs.removeAttribute(Val: Attribute::NoReturn);
580
581 // Reconstruct the AttributesList based on the vector we constructed.
582 AttributeList NewCallAL = AttributeList::get(
583 C, FnAttrs: AttributeSet::get(C, B: FnAttrs), RetAttrs: InvokeAL.getRetAttrs(), ArgAttrs: ArgAttributes);
584 NewCall->setAttributes(NewCallAL);
585
586 CI->replaceAllUsesWith(V: NewCall);
587
588 // Post-invoke
589 // %__THREW__.val = __THREW__; __THREW__ = 0;
590 Value *Threw =
591 IRB.CreateLoad(Ty: getAddrIntType(M), Ptr: ThrewGV, Name: ThrewGV->getName() + ".val");
592 IRB.CreateStore(Val: getAddrSizeInt(M, C: 0), Ptr: ThrewGV);
593 return Threw;
594}
595
596// Get matching invoke wrapper based on callee signature
597Function *WebAssemblyLowerEmscriptenEHSjLjImpl::getInvokeWrapper(CallBase *CI) {
598 Module *M = CI->getModule();
599 SmallVector<Type *, 16> ArgTys;
600 FunctionType *CalleeFTy = CI->getFunctionType();
601
602 std::string Sig = getSignature(FTy: CalleeFTy);
603 auto It = InvokeWrappers.find(Key: Sig);
604 if (It != InvokeWrappers.end())
605 return It->second;
606
607 // Put the pointer to the callee as first argument
608 ArgTys.push_back(Elt: PointerType::getUnqual(C&: CI->getContext()));
609 // Add argument types
610 ArgTys.append(in_start: CalleeFTy->param_begin(), in_end: CalleeFTy->param_end());
611
612 FunctionType *FTy = FunctionType::get(Result: CalleeFTy->getReturnType(), Params: ArgTys,
613 isVarArg: CalleeFTy->isVarArg());
614 Function *F = getFunction(Ty: FTy, Name: "__invoke_" + Sig, M);
615 markAsImported(F);
616 InvokeWrappers[Sig] = F;
617 return F;
618}
619
620static bool canLongjmp(const Value *Callee) {
621 if (auto *CalleeF = dyn_cast<Function>(Val: Callee))
622 if (CalleeF->isIntrinsic())
623 return false;
624
625 // Attempting to transform inline assembly will result in something like:
626 // call void @__invoke_void(void ()* asm ...)
627 // which is invalid because inline assembly blocks do not have addresses
628 // and can't be passed by pointer. The result is a crash with illegal IR.
629 if (isa<InlineAsm>(Val: Callee))
630 return false;
631 StringRef CalleeName = Callee->getName();
632
633 // TODO Include more functions or consider checking with mangled prefixes
634
635 // The reason we include malloc/free here is to exclude the malloc/free
636 // calls generated in setjmp prep / cleanup routines.
637 if (CalleeName == "setjmp" || CalleeName == "malloc" || CalleeName == "free")
638 return false;
639
640 // There are functions in Emscripten's JS glue code or compiler-rt
641 if (CalleeName == "__resumeException" || CalleeName == "llvm_eh_typeid_for" ||
642 CalleeName == "__wasm_setjmp" || CalleeName == "__wasm_setjmp_test" ||
643 CalleeName == "getTempRet0" || CalleeName == "setTempRet0")
644 return false;
645
646 // __cxa_find_matching_catch_N functions cannot longjmp
647 if (Callee->getName().starts_with(Prefix: "__cxa_find_matching_catch_"))
648 return false;
649
650 // Exception-catching related functions
651 //
652 // We intentionally treat __cxa_end_catch longjmpable in Wasm SjLj even though
653 // it surely cannot longjmp, in order to maintain the unwind relationship from
654 // all existing catchpads (and calls within them) to catch.dispatch.longjmp.
655 //
656 // In Wasm EH + Wasm SjLj, we
657 // 1. Make all catchswitch and cleanuppad that unwind to caller unwind to
658 // catch.dispatch.longjmp instead
659 // 2. Convert all longjmpable calls to invokes that unwind to
660 // catch.dispatch.longjmp
661 // But catchswitch BBs are removed in isel, so if an EH catchswitch (generated
662 // from an exception)'s catchpad does not contain any calls that are converted
663 // into invokes unwinding to catch.dispatch.longjmp, this unwind relationship
664 // (EH catchswitch BB -> catch.dispatch.longjmp BB) is lost and
665 // catch.dispatch.longjmp BB can be placed before the EH catchswitch BB in
666 // CFGSort.
667 // int ret = setjmp(buf);
668 // try {
669 // foo(); // longjmps
670 // } catch (...) {
671 // }
672 // Then in this code, if 'foo' longjmps, it first unwinds to 'catch (...)'
673 // catchswitch, and is not caught by that catchswitch because it is a longjmp,
674 // then it should next unwind to catch.dispatch.longjmp BB. But if this 'catch
675 // (...)' catchswitch -> catch.dispatch.longjmp unwind relationship is lost,
676 // it will not unwind to catch.dispatch.longjmp, producing an incorrect
677 // result.
678 //
679 // Every catchpad generated by Wasm C++ contains __cxa_end_catch, so we
680 // intentionally treat it as longjmpable to work around this problem. This is
681 // a hacky fix but an easy one.
682 if (CalleeName == "__cxa_end_catch")
683 return WebAssembly::WasmEnableSjLj;
684 if (CalleeName == "__cxa_begin_catch" ||
685 CalleeName == "__cxa_allocate_exception" || CalleeName == "__cxa_throw" ||
686 CalleeName == "__clang_call_terminate")
687 return false;
688
689 // std::terminate, which is generated when another exception occurs while
690 // handling an exception, cannot longjmp.
691 if (CalleeName == "_ZSt9terminatev")
692 return false;
693
694 // Otherwise we don't know
695 return true;
696}
697
698static bool isEmAsmCall(const Value *Callee) {
699 StringRef CalleeName = Callee->getName();
700 // This is an exhaustive list from Emscripten's <emscripten/em_asm.h>.
701 return CalleeName == "emscripten_asm_const_int" ||
702 CalleeName == "emscripten_asm_const_double" ||
703 CalleeName == "emscripten_asm_const_int_sync_on_main_thread" ||
704 CalleeName == "emscripten_asm_const_double_sync_on_main_thread" ||
705 CalleeName == "emscripten_asm_const_async_on_main_thread";
706}
707
708// Generate __wasm_setjmp_test function call seqence with preamble and
709// postamble. The code this generates is equivalent to the following
710// JavaScript code:
711// %__threwValue.val = __threwValue;
712// if (%__THREW__.val != 0 & %__threwValue.val != 0) {
713// %label = __wasm_setjmp_test(%__THREW__.val, functionInvocationId);
714// if (%label == 0)
715// emscripten_longjmp(%__THREW__.val, %__threwValue.val);
716// setTempRet0(%__threwValue.val);
717// } else {
718// %label = -1;
719// }
720// %longjmp_result = getTempRet0();
721//
722// As output parameters. returns %label, %longjmp_result, and the BB the last
723// instruction (%longjmp_result = ...) is in.
724void WebAssemblyLowerEmscriptenEHSjLjImpl::wrapTestSetjmp(
725 BasicBlock *BB, DebugLoc DL, Value *Threw, Value *FunctionInvocationId,
726 Value *&Label, Value *&LongjmpResult, BasicBlock *&CallEmLongjmpBB,
727 PHINode *&CallEmLongjmpBBThrewPHI, PHINode *&CallEmLongjmpBBThrewValuePHI,
728 BasicBlock *&EndBB) {
729 Function *F = BB->getParent();
730 Module *M = F->getParent();
731 LLVMContext &C = M->getContext();
732 IRBuilder<> IRB(C);
733 IRB.SetCurrentDebugLocation(DL);
734
735 // if (%__THREW__.val != 0 & %__threwValue.val != 0)
736 IRB.SetInsertPoint(BB);
737 BasicBlock *ThenBB1 = BasicBlock::Create(Context&: C, Name: "if.then1", Parent: F);
738 BasicBlock *ElseBB1 = BasicBlock::Create(Context&: C, Name: "if.else1", Parent: F);
739 BasicBlock *EndBB1 = BasicBlock::Create(Context&: C, Name: "if.end", Parent: F);
740 Value *ThrewCmp = IRB.CreateICmpNE(LHS: Threw, RHS: getAddrSizeInt(M, C: 0));
741 Value *ThrewValue = IRB.CreateLoad(Ty: IRB.getInt32Ty(), Ptr: ThrewValueGV,
742 Name: ThrewValueGV->getName() + ".val");
743 Value *ThrewValueCmp = IRB.CreateICmpNE(LHS: ThrewValue, RHS: IRB.getInt32(C: 0));
744 Value *Cmp1 = IRB.CreateAnd(LHS: ThrewCmp, RHS: ThrewValueCmp, Name: "cmp1");
745 IRB.CreateCondBr(Cond: Cmp1, True: ThenBB1, False: ElseBB1);
746
747 // Generate call.em.longjmp BB once and share it within the function
748 if (!CallEmLongjmpBB) {
749 // emscripten_longjmp(%__THREW__.val, %__threwValue.val);
750 CallEmLongjmpBB = BasicBlock::Create(Context&: C, Name: "call.em.longjmp", Parent: F);
751 IRB.SetInsertPoint(CallEmLongjmpBB);
752 CallEmLongjmpBBThrewPHI = IRB.CreatePHI(Ty: getAddrIntType(M), NumReservedValues: 4, Name: "threw.phi");
753 CallEmLongjmpBBThrewValuePHI =
754 IRB.CreatePHI(Ty: IRB.getInt32Ty(), NumReservedValues: 4, Name: "threwvalue.phi");
755 CallEmLongjmpBBThrewPHI->addIncoming(V: Threw, BB: ThenBB1);
756 CallEmLongjmpBBThrewValuePHI->addIncoming(V: ThrewValue, BB: ThenBB1);
757 IRB.CreateCall(Callee: EmLongjmpF,
758 Args: {CallEmLongjmpBBThrewPHI, CallEmLongjmpBBThrewValuePHI});
759 IRB.CreateUnreachable();
760 } else {
761 CallEmLongjmpBBThrewPHI->addIncoming(V: Threw, BB: ThenBB1);
762 CallEmLongjmpBBThrewValuePHI->addIncoming(V: ThrewValue, BB: ThenBB1);
763 }
764
765 // %label = __wasm_setjmp_test(%__THREW__.val, functionInvocationId);
766 // if (%label == 0)
767 IRB.SetInsertPoint(ThenBB1);
768 BasicBlock *EndBB2 = BasicBlock::Create(Context&: C, Name: "if.end2", Parent: F);
769 Value *ThrewPtr =
770 IRB.CreateIntToPtr(V: Threw, DestTy: getAddrPtrType(M), Name: Threw->getName() + ".p");
771 Value *ThenLabel = IRB.CreateCall(Callee: WasmSetjmpTestF,
772 Args: {ThrewPtr, FunctionInvocationId}, Name: "label");
773 Value *Cmp2 = IRB.CreateICmpEQ(LHS: ThenLabel, RHS: IRB.getInt32(C: 0));
774 IRB.CreateCondBr(Cond: Cmp2, True: CallEmLongjmpBB, False: EndBB2);
775
776 // setTempRet0(%__threwValue.val);
777 IRB.SetInsertPoint(EndBB2);
778 IRB.CreateCall(Callee: SetTempRet0F, Args: ThrewValue);
779 IRB.CreateBr(Dest: EndBB1);
780
781 IRB.SetInsertPoint(ElseBB1);
782 IRB.CreateBr(Dest: EndBB1);
783
784 // longjmp_result = getTempRet0();
785 IRB.SetInsertPoint(EndBB1);
786 PHINode *LabelPHI = IRB.CreatePHI(Ty: IRB.getInt32Ty(), NumReservedValues: 2, Name: "label");
787 LabelPHI->addIncoming(V: ThenLabel, BB: EndBB2);
788
789 LabelPHI->addIncoming(V: IRB.getInt32(C: -1), BB: ElseBB1);
790
791 // Output parameter assignment
792 Label = LabelPHI;
793 EndBB = EndBB1;
794 LongjmpResult = IRB.CreateCall(Callee: GetTempRet0F, Args: {}, Name: "longjmp_result");
795}
796
797void WebAssemblyLowerEmscriptenEHSjLjImpl::rebuildSSA(Function &F) {
798 DominatorTree &DT = GetDominatorTree(F);
799 DT.recalculate(Func&: F); // CFG has been changed
800
801 SSAUpdaterBulk SSA;
802 for (BasicBlock &BB : F) {
803 for (Instruction &I : BB) {
804 if (I.getType()->isVoidTy())
805 continue;
806
807 if (isa<AllocaInst>(Val: &I)) {
808 // If the alloca has any lifetime marker that is no longer dominated
809 // by the alloca, remove all lifetime markers. Lifetime markers must
810 // always work directly on the alloca, and this is no longer possible.
811 bool HasNonDominatedLifetimeMarker = any_of(Range: I.users(), P: [&](User *U) {
812 auto *UserI = cast<Instruction>(Val: U);
813 return UserI->isLifetimeStartOrEnd() && !DT.dominates(Def: &I, User: UserI);
814 });
815 if (HasNonDominatedLifetimeMarker) {
816 for (User *U : make_early_inc_range(Range: I.users())) {
817 auto *UserI = cast<Instruction>(Val: U);
818 if (UserI->isLifetimeStartOrEnd())
819 UserI->eraseFromParent();
820 }
821 }
822 }
823
824 unsigned VarID = SSA.AddVariable(Name: I.getName(), Ty: I.getType());
825 // If a value is defined by an invoke instruction, it is only available in
826 // its normal destination and not in its unwind destination.
827 if (auto *II = dyn_cast<InvokeInst>(Val: &I))
828 SSA.AddAvailableValue(Var: VarID, BB: II->getNormalDest(), V: II);
829 else
830 SSA.AddAvailableValue(Var: VarID, BB: &BB, V: &I);
831 for (auto &U : I.uses()) {
832 auto *User = cast<Instruction>(Val: U.getUser());
833 if (auto *UserPN = dyn_cast<PHINode>(Val: User))
834 if (UserPN->getIncomingBlock(U) == &BB)
835 continue;
836 if (DT.dominates(Def: &I, User))
837 continue;
838 SSA.AddUse(Var: VarID, U: &U);
839 }
840 }
841 }
842 SSA.RewriteAllUses(DT: &DT);
843}
844
845// Replace uses of longjmp with a new longjmp function in Emscripten library.
846// In Emscripten SjLj, the new function is
847// void emscripten_longjmp(uintptr_t, i32)
848// In Wasm SjLj, the new function is
849// void __wasm_longjmp(i8*, i32)
850// Because the original libc longjmp function takes (jmp_buf*, i32), we need a
851// ptrtoint/bitcast instruction here to make the type match. jmp_buf* will
852// eventually be lowered to i32/i64 in the wasm backend.
853void WebAssemblyLowerEmscriptenEHSjLjImpl::replaceLongjmpWith(
854 Function *LongjmpF, Function *NewF) {
855 assert(NewF == EmLongjmpF || NewF == WasmLongjmpF);
856 Module *M = LongjmpF->getParent();
857 SmallVector<CallInst *, 8> ToErase;
858 LLVMContext &C = LongjmpF->getParent()->getContext();
859 IRBuilder<> IRB(C);
860
861 // For calls to longjmp, replace it with emscripten_longjmp/__wasm_longjmp and
862 // cast its first argument (jmp_buf*) appropriately
863 for (User *U : LongjmpF->users()) {
864 auto *CI = dyn_cast<CallInst>(Val: U);
865 if (CI && CI->getCalledFunction() == LongjmpF) {
866 IRB.SetInsertPoint(CI);
867 Value *Env = nullptr;
868 if (NewF == EmLongjmpF)
869 Env =
870 IRB.CreatePtrToInt(V: CI->getArgOperand(i: 0), DestTy: getAddrIntType(M), Name: "env");
871 else // WasmLongjmpF
872 Env = IRB.CreateBitCast(V: CI->getArgOperand(i: 0), DestTy: IRB.getPtrTy(), Name: "env");
873 IRB.CreateCall(Callee: NewF, Args: {Env, CI->getArgOperand(i: 1)});
874 ToErase.push_back(Elt: CI);
875 }
876 }
877 for (auto *I : ToErase)
878 I->eraseFromParent();
879
880 // If we have any remaining uses of longjmp's function pointer, replace it
881 // with (void(*)(jmp_buf*, int))emscripten_longjmp / __wasm_longjmp.
882 if (!LongjmpF->uses().empty()) {
883 Value *NewLongjmp =
884 IRB.CreateBitCast(V: NewF, DestTy: LongjmpF->getType(), Name: "longjmp.cast");
885 LongjmpF->replaceAllUsesWith(V: NewLongjmp);
886 }
887}
888
889static bool containsLongjmpableCalls(const Function *F) {
890 for (const auto &BB : *F)
891 for (const auto &I : BB)
892 if (const auto *CB = dyn_cast<CallBase>(Val: &I))
893 if (canLongjmp(Callee: CB->getCalledOperand()))
894 return true;
895 return false;
896}
897
898// When a function contains a setjmp call but not other calls that can longjmp,
899// we don't do setjmp transformation for that setjmp. But we need to convert the
900// setjmp calls into "i32 0" so they don't cause link time errors. setjmp always
901// returns 0 when called directly.
902static void nullifySetjmp(Function *F) {
903 Module &M = *F->getParent();
904 IRBuilder<> IRB(M.getContext());
905 Function *SetjmpF = M.getFunction(Name: "setjmp");
906 SmallVector<Instruction *, 1> ToErase;
907
908 for (User *U : make_early_inc_range(Range: SetjmpF->users())) {
909 auto *CB = cast<CallBase>(Val: U);
910 BasicBlock *BB = CB->getParent();
911 if (BB->getParent() != F) // in other function
912 continue;
913 CallInst *CI = nullptr;
914 // setjmp cannot throw. So if it is an invoke, lower it to a call
915 if (auto *II = dyn_cast<InvokeInst>(Val: CB))
916 CI = llvm::changeToCall(II);
917 else
918 CI = cast<CallInst>(Val: CB);
919 ToErase.push_back(Elt: CI);
920 CI->replaceAllUsesWith(V: IRB.getInt32(C: 0));
921 }
922 for (auto *I : ToErase)
923 I->eraseFromParent();
924}
925
926bool WebAssemblyLowerEmscriptenEHSjLjImpl::runOnModule(Module &M) {
927 LLVM_DEBUG(dbgs() << "********** Lower Emscripten EH & SjLj **********\n");
928
929 LLVMContext &C = M.getContext();
930 IRBuilder<> IRB(C);
931
932 Function *SetjmpF = M.getFunction(Name: "setjmp");
933 Function *LongjmpF = M.getFunction(Name: "longjmp");
934
935 // In some platforms _setjmp and _longjmp are used instead. Change these to
936 // use setjmp/longjmp instead, because we later detect these functions by
937 // their names.
938 Function *SetjmpF2 = M.getFunction(Name: "_setjmp");
939 Function *LongjmpF2 = M.getFunction(Name: "_longjmp");
940 if (SetjmpF2) {
941 if (SetjmpF) {
942 if (SetjmpF->getFunctionType() != SetjmpF2->getFunctionType())
943 report_fatal_error(reason: "setjmp and _setjmp have different function types");
944 } else {
945 SetjmpF = Function::Create(Ty: SetjmpF2->getFunctionType(),
946 Linkage: GlobalValue::ExternalLinkage, N: "setjmp", M);
947 }
948 SetjmpF2->replaceAllUsesWith(V: SetjmpF);
949 }
950 if (LongjmpF2) {
951 if (LongjmpF) {
952 if (LongjmpF->getFunctionType() != LongjmpF2->getFunctionType())
953 report_fatal_error(
954 reason: "longjmp and _longjmp have different function types");
955 } else {
956 LongjmpF = Function::Create(Ty: LongjmpF2->getFunctionType(),
957 Linkage: GlobalValue::ExternalLinkage, N: "setjmp", M);
958 }
959 LongjmpF2->replaceAllUsesWith(V: LongjmpF);
960 }
961
962 // Declare (or get) global variables __THREW__, __threwValue, and
963 // getTempRet0/setTempRet0 function which are used in common for both
964 // exception handling and setjmp/longjmp handling
965 ThrewGV = getGlobalVariable(M, Ty: getAddrIntType(M: &M), Name: "__THREW__");
966 ThrewValueGV = getGlobalVariable(M, Ty: IRB.getInt32Ty(), Name: "__threwValue");
967 GetTempRet0F = getFunction(Ty: FunctionType::get(Result: IRB.getInt32Ty(), isVarArg: false),
968 Name: "getTempRet0", M: &M);
969 SetTempRet0F =
970 getFunction(Ty: FunctionType::get(Result: IRB.getVoidTy(), Params: IRB.getInt32Ty(), isVarArg: false),
971 Name: "setTempRet0", M: &M);
972 GetTempRet0F->setDoesNotThrow();
973 SetTempRet0F->setDoesNotThrow();
974
975 bool Changed = false;
976
977 // Function registration for exception handling
978 if (EnableEmEH) {
979 // Register __resumeException function
980 FunctionType *ResumeFTy =
981 FunctionType::get(Result: IRB.getVoidTy(), Params: IRB.getPtrTy(), isVarArg: false);
982 ResumeF = getFunction(Ty: ResumeFTy, Name: "__resumeException", M: &M);
983 ResumeF->addFnAttr(Kind: Attribute::NoReturn);
984
985 // Register llvm_eh_typeid_for function
986 FunctionType *EHTypeIDTy =
987 FunctionType::get(Result: IRB.getInt32Ty(), Params: IRB.getPtrTy(), isVarArg: false);
988 EHTypeIDF = getFunction(Ty: EHTypeIDTy, Name: "llvm_eh_typeid_for", M: &M);
989 }
990
991 // Functions that contains calls to setjmp but don't have other longjmpable
992 // calls within them.
993 SmallPtrSet<Function *, 4> SetjmpUsersToNullify;
994
995 if ((EnableEmSjLj || EnableWasmSjLj) && SetjmpF) {
996 // Precompute setjmp users
997 for (User *U : SetjmpF->users()) {
998 if (auto *CB = dyn_cast<CallBase>(Val: U)) {
999 auto *UserF = CB->getFunction();
1000 // If a function that calls setjmp does not contain any other calls that
1001 // can longjmp, we don't need to do any transformation on that function,
1002 // so can ignore it
1003 if (containsLongjmpableCalls(F: UserF))
1004 SetjmpUsers.insert(Ptr: UserF);
1005 else
1006 SetjmpUsersToNullify.insert(Ptr: UserF);
1007 } else {
1008 std::string S;
1009 raw_string_ostream SS(S);
1010 SS << *U;
1011 report_fatal_error(reason: Twine("Indirect use of setjmp is not supported: ") +
1012 SS.str());
1013 }
1014 }
1015 }
1016
1017 bool SetjmpUsed = SetjmpF && !SetjmpUsers.empty();
1018 bool LongjmpUsed = LongjmpF && !LongjmpF->use_empty();
1019 DoSjLj = (EnableEmSjLj | EnableWasmSjLj) && (SetjmpUsed || LongjmpUsed);
1020
1021 // Function registration and data pre-gathering for setjmp/longjmp handling
1022 if (DoSjLj) {
1023 assert(EnableEmSjLj || EnableWasmSjLj);
1024
1025 if (EnableEmSjLj) {
1026 // Register emscripten_longjmp function
1027 FunctionType *FTy = FunctionType::get(
1028 Result: IRB.getVoidTy(), Params: {getAddrIntType(M: &M), IRB.getInt32Ty()}, isVarArg: false);
1029 EmLongjmpF = getFunction(Ty: FTy, Name: "emscripten_longjmp", M: &M);
1030 EmLongjmpF->addFnAttr(Kind: Attribute::NoReturn);
1031 } else { // EnableWasmSjLj
1032 Type *Int8PtrTy = IRB.getPtrTy();
1033 // Register __wasm_longjmp function, which calls __builtin_wasm_longjmp.
1034 FunctionType *FTy = FunctionType::get(
1035 Result: IRB.getVoidTy(), Params: {Int8PtrTy, IRB.getInt32Ty()}, isVarArg: false);
1036 WasmLongjmpF = getFunction(Ty: FTy, Name: "__wasm_longjmp", M: &M);
1037 WasmLongjmpF->addFnAttr(Kind: Attribute::NoReturn);
1038 }
1039
1040 if (EnableWasmSjLj) {
1041 for (auto *SjLjF : {SetjmpF, LongjmpF}) {
1042 if (SjLjF) {
1043 for (User *U : SjLjF->users()) {
1044 if (auto *CI = dyn_cast<CallInst>(Val: U)) {
1045 auto &F = *CI->getFunction();
1046 if (!hasEHTargetFeatureAttr(F))
1047 report_fatal_error(reason: "Function " + F.getName() +
1048 " is using setjmp/longjmp but does not have "
1049 "+exception-handling target feature");
1050 }
1051 }
1052 }
1053 }
1054 }
1055
1056 if (SetjmpF) {
1057 Type *Int8PtrTy = IRB.getPtrTy();
1058 Type *Int32PtrTy = IRB.getPtrTy();
1059 Type *Int32Ty = IRB.getInt32Ty();
1060
1061 // Register __wasm_setjmp function
1062 FunctionType *SetjmpFTy = SetjmpF->getFunctionType();
1063 FunctionType *FTy = FunctionType::get(
1064 Result: IRB.getVoidTy(), Params: {SetjmpFTy->getParamType(i: 0), Int32Ty, Int32PtrTy},
1065 isVarArg: false);
1066 WasmSetjmpF = getFunction(Ty: FTy, Name: "__wasm_setjmp", M: &M);
1067
1068 // Register __wasm_setjmp_test function
1069 FTy = FunctionType::get(Result: Int32Ty, Params: {Int32PtrTy, Int32PtrTy}, isVarArg: false);
1070 WasmSetjmpTestF = getFunction(Ty: FTy, Name: "__wasm_setjmp_test", M: &M);
1071
1072 // wasm.catch() will be lowered down to wasm 'catch' instruction in
1073 // instruction selection.
1074 CatchF = Intrinsic::getOrInsertDeclaration(M: &M, id: Intrinsic::wasm_catch);
1075 // Type for struct __WasmLongjmpArgs
1076 LongjmpArgsTy = StructType::get(elt1: Int8PtrTy, // env
1077 elts: Int32Ty // val
1078 );
1079 }
1080 }
1081
1082 // Exception handling transformation
1083 if (EnableEmEH) {
1084 for (Function &F : M) {
1085 if (F.isDeclaration())
1086 continue;
1087 Changed |= runEHOnFunction(F);
1088 }
1089 }
1090
1091 // Setjmp/longjmp handling transformation
1092 if (DoSjLj) {
1093 Changed = true; // We have setjmp or longjmp somewhere
1094 if (LongjmpF)
1095 replaceLongjmpWith(LongjmpF, NewF: EnableEmSjLj ? EmLongjmpF : WasmLongjmpF);
1096 // Only traverse functions that uses setjmp in order not to insert
1097 // unnecessary prep / cleanup code in every function
1098 if (SetjmpF)
1099 for (Function *F : SetjmpUsers)
1100 runSjLjOnFunction(F&: *F);
1101 }
1102
1103 // Replace unnecessary setjmp calls with 0
1104 if ((EnableEmSjLj || EnableWasmSjLj) && !SetjmpUsersToNullify.empty()) {
1105 Changed = true;
1106 assert(SetjmpF);
1107 for (Function *F : SetjmpUsersToNullify)
1108 nullifySetjmp(F);
1109 }
1110
1111 // Delete unused global variables and functions
1112 for (auto *V : {ThrewGV, ThrewValueGV})
1113 if (V && V->use_empty())
1114 V->eraseFromParent();
1115 for (auto *V : {GetTempRet0F, SetTempRet0F, ResumeF, EHTypeIDF, EmLongjmpF,
1116 WasmSetjmpF, WasmSetjmpTestF, WasmLongjmpF, CatchF})
1117 if (V && V->use_empty())
1118 V->eraseFromParent();
1119
1120 return Changed;
1121}
1122
1123bool WebAssemblyLowerEmscriptenEHSjLjImpl::runEHOnFunction(Function &F) {
1124 Module &M = *F.getParent();
1125 LLVMContext &C = F.getContext();
1126 IRBuilder<> IRB(C);
1127 bool Changed = false;
1128 SmallVector<Instruction *, 64> ToErase;
1129 SmallPtrSet<LandingPadInst *, 32> LandingPads;
1130
1131 // rethrow.longjmp BB that will be shared within the function.
1132 BasicBlock *RethrowLongjmpBB = nullptr;
1133 // PHI node for the loaded value of __THREW__ global variable in
1134 // rethrow.longjmp BB
1135 PHINode *RethrowLongjmpBBThrewPHI = nullptr;
1136
1137 for (BasicBlock &BB : F) {
1138 auto *II = dyn_cast<InvokeInst>(Val: BB.getTerminator());
1139 if (!II)
1140 continue;
1141 Changed = true;
1142 LandingPads.insert(Ptr: II->getLandingPadInst());
1143 IRB.SetInsertPoint(II);
1144
1145 const Value *Callee = II->getCalledOperand();
1146 bool NeedInvoke = supportsException(F: &F) && canThrow(V: Callee);
1147 if (NeedInvoke) {
1148 // Wrap invoke with invoke wrapper and generate preamble/postamble
1149 Value *Threw = wrapInvoke(CI: II);
1150 ToErase.push_back(Elt: II);
1151
1152 // If setjmp/longjmp handling is enabled, the thrown value can be not an
1153 // exception but a longjmp. If the current function contains calls to
1154 // setjmp, it will be appropriately handled in runSjLjOnFunction. But even
1155 // if the function does not contain setjmp calls, we shouldn't silently
1156 // ignore longjmps; we should rethrow them so they can be correctly
1157 // handled in somewhere up the call chain where setjmp is. __THREW__'s
1158 // value is 0 when nothing happened, 1 when an exception is thrown, and
1159 // other values when longjmp is thrown.
1160 //
1161 // if (%__THREW__.val == 0 || %__THREW__.val == 1)
1162 // goto %tail
1163 // else
1164 // goto %longjmp.rethrow
1165 //
1166 // rethrow.longjmp: ;; This is longjmp. Rethrow it
1167 // %__threwValue.val = __threwValue
1168 // emscripten_longjmp(%__THREW__.val, %__threwValue.val);
1169 //
1170 // tail: ;; Nothing happened or an exception is thrown
1171 // ... Continue exception handling ...
1172 if (DoSjLj && EnableEmSjLj && !SetjmpUsers.count(Ptr: &F) &&
1173 canLongjmp(Callee)) {
1174 // Create longjmp.rethrow BB once and share it within the function
1175 if (!RethrowLongjmpBB) {
1176 RethrowLongjmpBB = BasicBlock::Create(Context&: C, Name: "rethrow.longjmp", Parent: &F);
1177 IRB.SetInsertPoint(RethrowLongjmpBB);
1178 RethrowLongjmpBBThrewPHI =
1179 IRB.CreatePHI(Ty: getAddrIntType(M: &M), NumReservedValues: 4, Name: "threw.phi");
1180 RethrowLongjmpBBThrewPHI->addIncoming(V: Threw, BB: &BB);
1181 Value *ThrewValue = IRB.CreateLoad(Ty: IRB.getInt32Ty(), Ptr: ThrewValueGV,
1182 Name: ThrewValueGV->getName() + ".val");
1183 IRB.CreateCall(Callee: EmLongjmpF, Args: {RethrowLongjmpBBThrewPHI, ThrewValue});
1184 IRB.CreateUnreachable();
1185 } else {
1186 RethrowLongjmpBBThrewPHI->addIncoming(V: Threw, BB: &BB);
1187 }
1188
1189 IRB.SetInsertPoint(II); // Restore the insert point back
1190 BasicBlock *Tail = BasicBlock::Create(Context&: C, Name: "tail", Parent: &F);
1191 Value *CmpEqOne =
1192 IRB.CreateICmpEQ(LHS: Threw, RHS: getAddrSizeInt(M: &M, C: 1), Name: "cmp.eq.one");
1193 Value *CmpEqZero =
1194 IRB.CreateICmpEQ(LHS: Threw, RHS: getAddrSizeInt(M: &M, C: 0), Name: "cmp.eq.zero");
1195 Value *Or = IRB.CreateOr(LHS: CmpEqZero, RHS: CmpEqOne, Name: "or");
1196 IRB.CreateCondBr(Cond: Or, True: Tail, False: RethrowLongjmpBB);
1197 IRB.SetInsertPoint(Tail);
1198 BB.replaceSuccessorsPhiUsesWith(Old: &BB, New: Tail);
1199 }
1200
1201 // Insert a branch based on __THREW__ variable
1202 Value *Cmp = IRB.CreateICmpEQ(LHS: Threw, RHS: getAddrSizeInt(M: &M, C: 1), Name: "cmp");
1203 IRB.CreateCondBr(Cond: Cmp, True: II->getUnwindDest(), False: II->getNormalDest());
1204
1205 } else {
1206 // This can't throw, and we don't need this invoke, just replace it with a
1207 // call+branch
1208 changeToCall(II);
1209 }
1210 }
1211
1212 // Process resume instructions
1213 for (BasicBlock &BB : F) {
1214 // Scan the body of the basic block for resumes
1215 for (Instruction &I : BB) {
1216 auto *RI = dyn_cast<ResumeInst>(Val: &I);
1217 if (!RI)
1218 continue;
1219 Changed = true;
1220
1221 // Split the input into legal values
1222 Value *Input = RI->getValue();
1223 IRB.SetInsertPoint(RI);
1224 Value *Low = IRB.CreateExtractValue(Agg: Input, Idxs: 0, Name: "low");
1225 // Create a call to __resumeException function
1226 IRB.CreateCall(Callee: ResumeF, Args: {Low});
1227 // Add a terminator to the block
1228 IRB.CreateUnreachable();
1229 ToErase.push_back(Elt: RI);
1230 }
1231 }
1232
1233 // Process llvm.eh.typeid.for intrinsics
1234 for (BasicBlock &BB : F) {
1235 for (Instruction &I : BB) {
1236 auto *CI = dyn_cast<CallInst>(Val: &I);
1237 if (!CI)
1238 continue;
1239 const Function *Callee = CI->getCalledFunction();
1240 if (!Callee)
1241 continue;
1242 if (Callee->getIntrinsicID() != Intrinsic::eh_typeid_for)
1243 continue;
1244 Changed = true;
1245
1246 IRB.SetInsertPoint(CI);
1247 CallInst *NewCI =
1248 IRB.CreateCall(Callee: EHTypeIDF, Args: CI->getArgOperand(i: 0), Name: "typeid");
1249 CI->replaceAllUsesWith(V: NewCI);
1250 ToErase.push_back(Elt: CI);
1251 }
1252 }
1253
1254 // Look for orphan landingpads, can occur in blocks with no predecessors
1255 for (BasicBlock &BB : F) {
1256 BasicBlock::iterator I = BB.getFirstNonPHIIt();
1257 if (auto *LPI = dyn_cast<LandingPadInst>(Val&: I))
1258 LandingPads.insert(Ptr: LPI);
1259 }
1260 Changed |= !LandingPads.empty();
1261
1262 // Handle all the landingpad for this function together, as multiple invokes
1263 // may share a single lp
1264 for (LandingPadInst *LPI : LandingPads) {
1265 IRB.SetInsertPoint(LPI);
1266 SmallVector<Value *, 16> FMCArgs;
1267 for (unsigned I = 0, E = LPI->getNumClauses(); I < E; ++I) {
1268 Constant *Clause = LPI->getClause(Idx: I);
1269 // TODO Handle filters (= exception specifications).
1270 // https://github.com/llvm/llvm-project/issues/49740
1271 if (LPI->isCatch(Idx: I))
1272 FMCArgs.push_back(Elt: Clause);
1273 }
1274
1275 // Create a call to __cxa_find_matching_catch_N function
1276 Function *FMCF = getFindMatchingCatch(M, NumClauses: FMCArgs.size());
1277 CallInst *FMCI = IRB.CreateCall(Callee: FMCF, Args: FMCArgs, Name: "fmc");
1278 Value *Poison = PoisonValue::get(T: LPI->getType());
1279 Value *Pair0 = IRB.CreateInsertValue(Agg: Poison, Val: FMCI, Idxs: 0, Name: "pair0");
1280 Value *TempRet0 = IRB.CreateCall(Callee: GetTempRet0F, Args: {}, Name: "tempret0");
1281 Value *Pair1 = IRB.CreateInsertValue(Agg: Pair0, Val: TempRet0, Idxs: 1, Name: "pair1");
1282
1283 LPI->replaceAllUsesWith(V: Pair1);
1284 ToErase.push_back(Elt: LPI);
1285 }
1286
1287 // Erase everything we no longer need in this function
1288 for (Instruction *I : ToErase)
1289 I->eraseFromParent();
1290
1291 return Changed;
1292}
1293
1294// This tries to get debug info from the instruction before which a new
1295// instruction will be inserted, and if there's no debug info in that
1296// instruction, tries to get the info instead from the previous instruction (if
1297// any). If none of these has debug info and a DISubprogram is provided, it
1298// creates a dummy debug info with the first line of the function, because IR
1299// verifier requires all inlinable callsites should have debug info when both a
1300// caller and callee have DISubprogram. If none of these conditions are met,
1301// returns empty info.
1302static DebugLoc getOrCreateDebugLoc(const Instruction *InsertBefore,
1303 DISubprogram *SP) {
1304 assert(InsertBefore);
1305 if (InsertBefore->getDebugLoc())
1306 return InsertBefore->getDebugLoc();
1307 const Instruction *Prev = InsertBefore->getPrevNode();
1308 if (Prev && Prev->getDebugLoc())
1309 return Prev->getDebugLoc();
1310 if (SP)
1311 return DILocation::get(Context&: SP->getContext(), Line: SP->getLine(), Column: 1, Scope: SP);
1312 return DebugLoc();
1313}
1314
1315bool WebAssemblyLowerEmscriptenEHSjLjImpl::runSjLjOnFunction(Function &F) {
1316 assert(EnableEmSjLj || EnableWasmSjLj);
1317 Module &M = *F.getParent();
1318 LLVMContext &C = F.getContext();
1319 IRBuilder<> IRB(C);
1320 SmallVector<Instruction *, 64> ToErase;
1321
1322 // Setjmp preparation
1323
1324 SmallVector<AllocaInst *> StaticAllocas;
1325 for (Instruction &I : F.getEntryBlock())
1326 if (auto *AI = dyn_cast<AllocaInst>(Val: &I))
1327 if (AI->isStaticAlloca())
1328 StaticAllocas.push_back(Elt: AI);
1329
1330 BasicBlock *Entry = &F.getEntryBlock();
1331 DebugLoc FirstDL = getOrCreateDebugLoc(InsertBefore: &*Entry->begin(), SP: F.getSubprogram());
1332 SplitBlock(Old: Entry, SplitPt: &*Entry->getFirstInsertionPt());
1333
1334 // Move static allocas back into the entry block, so they stay static.
1335 for (AllocaInst *AI : StaticAllocas)
1336 AI->moveBefore(InsertPos: Entry->getTerminator()->getIterator());
1337
1338 IRB.SetInsertPoint(Entry->getTerminator()->getIterator());
1339 // This alloca'ed pointer is used by the runtime to identify function
1340 // invocations. It's just for pointer comparisons. It will never be
1341 // dereferenced.
1342 Instruction *FunctionInvocationId =
1343 IRB.CreateAlloca(Ty: IRB.getInt32Ty(), ArraySize: nullptr, Name: "functionInvocationId");
1344 FunctionInvocationId->setDebugLoc(FirstDL);
1345
1346 // Setjmp transformation
1347 SmallVector<PHINode *, 4> SetjmpRetPHIs;
1348 Function *SetjmpF = M.getFunction(Name: "setjmp");
1349 for (auto *U : make_early_inc_range(Range: SetjmpF->users())) {
1350 auto *CB = cast<CallBase>(Val: U);
1351 BasicBlock *BB = CB->getParent();
1352 if (BB->getParent() != &F) // in other function
1353 continue;
1354 if (CB->getOperandBundle(ID: LLVMContext::OB_funclet)) {
1355 std::string S;
1356 raw_string_ostream SS(S);
1357 SS << "In function " + F.getName() +
1358 ": setjmp within a catch clause is not supported in Wasm EH:\n";
1359 SS << *CB;
1360 report_fatal_error(reason: StringRef(SS.str()));
1361 }
1362
1363 CallInst *CI = nullptr;
1364 // setjmp cannot throw. So if it is an invoke, lower it to a call
1365 if (auto *II = dyn_cast<InvokeInst>(Val: CB))
1366 CI = llvm::changeToCall(II);
1367 else
1368 CI = cast<CallInst>(Val: CB);
1369
1370 // The tail is everything right after the call, and will be reached once
1371 // when setjmp is called, and later when longjmp returns to the setjmp
1372 BasicBlock *Tail = SplitBlock(Old: BB, SplitPt: CI->getNextNode());
1373 // Add a phi to the tail, which will be the output of setjmp, which
1374 // indicates if this is the first call or a longjmp back. The phi directly
1375 // uses the right value based on where we arrive from
1376 IRB.SetInsertPoint(TheBB: Tail, IP: Tail->getFirstNonPHIIt());
1377 PHINode *SetjmpRet = IRB.CreatePHI(Ty: IRB.getInt32Ty(), NumReservedValues: 2, Name: "setjmp.ret");
1378
1379 // setjmp initial call returns 0
1380 SetjmpRet->addIncoming(V: IRB.getInt32(C: 0), BB);
1381 // The proper output is now this, not the setjmp call itself
1382 CI->replaceAllUsesWith(V: SetjmpRet);
1383 // longjmp returns to the setjmp will add themselves to this phi
1384 SetjmpRetPHIs.push_back(Elt: SetjmpRet);
1385
1386 // Fix call target
1387 // Our index in the function is our place in the array + 1 to avoid index
1388 // 0, because index 0 means the longjmp is not ours to handle.
1389 IRB.SetInsertPoint(CI);
1390 Value *Args[] = {CI->getArgOperand(i: 0), IRB.getInt32(C: SetjmpRetPHIs.size()),
1391 FunctionInvocationId};
1392 IRB.CreateCall(Callee: WasmSetjmpF, Args);
1393 ToErase.push_back(Elt: CI);
1394 }
1395
1396 // Handle longjmpable calls.
1397 if (EnableEmSjLj)
1398 handleLongjmpableCallsForEmscriptenSjLj(F, FunctionInvocationId,
1399 SetjmpRetPHIs);
1400 else // EnableWasmSjLj
1401 handleLongjmpableCallsForWasmSjLj(F, FunctionInvocationId, SetjmpRetPHIs);
1402
1403 // Erase everything we no longer need in this function
1404 for (Instruction *I : ToErase)
1405 I->eraseFromParent();
1406
1407 // Finally, our modifications to the cfg can break dominance of SSA variables.
1408 // For example, in this code,
1409 // if (x()) { .. setjmp() .. }
1410 // if (y()) { .. longjmp() .. }
1411 // We must split the longjmp block, and it can jump into the block splitted
1412 // from setjmp one. But that means that when we split the setjmp block, it's
1413 // first part no longer dominates its second part - there is a theoretically
1414 // possible control flow path where x() is false, then y() is true and we
1415 // reach the second part of the setjmp block, without ever reaching the first
1416 // part. So, we rebuild SSA form here.
1417 rebuildSSA(F);
1418 return true;
1419}
1420
1421// Update each call that can longjmp so it can return to the corresponding
1422// setjmp. Refer to 4) of "Emscripten setjmp/longjmp handling" section in the
1423// comments at top of the file for details.
1424void WebAssemblyLowerEmscriptenEHSjLjImpl::
1425 handleLongjmpableCallsForEmscriptenSjLj(
1426 Function &F, Instruction *FunctionInvocationId,
1427 SmallVectorImpl<PHINode *> &SetjmpRetPHIs) {
1428 Module &M = *F.getParent();
1429 LLVMContext &C = F.getContext();
1430 IRBuilder<> IRB(C);
1431 SmallVector<Instruction *, 64> ToErase;
1432
1433 // call.em.longjmp BB that will be shared within the function.
1434 BasicBlock *CallEmLongjmpBB = nullptr;
1435 // PHI node for the loaded value of __THREW__ global variable in
1436 // call.em.longjmp BB
1437 PHINode *CallEmLongjmpBBThrewPHI = nullptr;
1438 // PHI node for the loaded value of __threwValue global variable in
1439 // call.em.longjmp BB
1440 PHINode *CallEmLongjmpBBThrewValuePHI = nullptr;
1441 // rethrow.exn BB that will be shared within the function.
1442 BasicBlock *RethrowExnBB = nullptr;
1443
1444 // Because we are creating new BBs while processing and don't want to make
1445 // all these newly created BBs candidates again for longjmp processing, we
1446 // first make the vector of candidate BBs.
1447 std::vector<BasicBlock *> BBs;
1448 for (BasicBlock &BB : F)
1449 BBs.push_back(x: &BB);
1450
1451 // BBs.size() will change within the loop, so we query it every time
1452 for (unsigned I = 0; I < BBs.size(); I++) {
1453 BasicBlock *BB = BBs[I];
1454 for (Instruction &I : *BB) {
1455 if (isa<InvokeInst>(Val: &I)) {
1456 std::string S;
1457 raw_string_ostream SS(S);
1458 SS << "In function " << F.getName()
1459 << ": When using Wasm EH with Emscripten SjLj, there is a "
1460 "restriction that `setjmp` function call and exception cannot be "
1461 "used within the same function:\n";
1462 SS << I;
1463 report_fatal_error(reason: StringRef(SS.str()));
1464 }
1465 auto *CI = dyn_cast<CallInst>(Val: &I);
1466 if (!CI)
1467 continue;
1468
1469 const Value *Callee = CI->getCalledOperand();
1470 if (!canLongjmp(Callee))
1471 continue;
1472 if (isEmAsmCall(Callee))
1473 report_fatal_error(reason: "Cannot use EM_ASM* alongside setjmp/longjmp in " +
1474 F.getName() +
1475 ". Please consider using EM_JS, or move the "
1476 "EM_ASM into another function.",
1477 gen_crash_diag: false);
1478
1479 Value *Threw = nullptr;
1480 BasicBlock *Tail;
1481 if (Callee->getName().starts_with(Prefix: "__invoke_")) {
1482 // If invoke wrapper has already been generated for this call in
1483 // previous EH phase, search for the load instruction
1484 // %__THREW__.val = __THREW__;
1485 // in postamble after the invoke wrapper call
1486 LoadInst *ThrewLI = nullptr;
1487 StoreInst *ThrewResetSI = nullptr;
1488 for (auto I = std::next(x: BasicBlock::iterator(CI)), IE = BB->end();
1489 I != IE; ++I) {
1490 if (auto *LI = dyn_cast<LoadInst>(Val&: I))
1491 if (auto *GV = dyn_cast<GlobalVariable>(Val: LI->getPointerOperand()))
1492 if (GV == ThrewGV) {
1493 Threw = ThrewLI = LI;
1494 break;
1495 }
1496 }
1497 // Search for the store instruction after the load above
1498 // __THREW__ = 0;
1499 for (auto I = std::next(x: BasicBlock::iterator(ThrewLI)), IE = BB->end();
1500 I != IE; ++I) {
1501 if (auto *SI = dyn_cast<StoreInst>(Val&: I)) {
1502 if (auto *GV = dyn_cast<GlobalVariable>(Val: SI->getPointerOperand())) {
1503 if (GV == ThrewGV &&
1504 SI->getValueOperand() == getAddrSizeInt(M: &M, C: 0)) {
1505 ThrewResetSI = SI;
1506 break;
1507 }
1508 }
1509 }
1510 }
1511 assert(Threw && ThrewLI && "Cannot find __THREW__ load after invoke");
1512 assert(ThrewResetSI && "Cannot find __THREW__ store after invoke");
1513 Tail = SplitBlock(Old: BB, SplitPt: ThrewResetSI->getNextNode());
1514
1515 } else {
1516 // Wrap call with invoke wrapper and generate preamble/postamble
1517 Threw = wrapInvoke(CI);
1518 ToErase.push_back(Elt: CI);
1519 Tail = SplitBlock(Old: BB, SplitPt: CI->getNextNode());
1520
1521 // If exception handling is enabled, the thrown value can be not a
1522 // longjmp but an exception, in which case we shouldn't silently ignore
1523 // exceptions; we should rethrow them.
1524 // __THREW__'s value is 0 when nothing happened, 1 when an exception is
1525 // thrown, other values when longjmp is thrown.
1526 //
1527 // if (%__THREW__.val == 1)
1528 // goto %eh.rethrow
1529 // else
1530 // goto %normal
1531 //
1532 // eh.rethrow: ;; Rethrow exception
1533 // %exn = call @__cxa_find_matching_catch_2() ;; Retrieve thrown ptr
1534 // __resumeException(%exn)
1535 //
1536 // normal:
1537 // <-- Insertion point. Will insert sjlj handling code from here
1538 // goto %tail
1539 //
1540 // tail:
1541 // ...
1542 if (supportsException(F: &F) && canThrow(V: Callee)) {
1543 // We will add a new conditional branch. So remove the branch created
1544 // when we split the BB
1545 ToErase.push_back(Elt: BB->getTerminator());
1546
1547 // Generate rethrow.exn BB once and share it within the function
1548 if (!RethrowExnBB) {
1549 RethrowExnBB = BasicBlock::Create(Context&: C, Name: "rethrow.exn", Parent: &F);
1550 IRB.SetInsertPoint(RethrowExnBB);
1551 CallInst *Exn =
1552 IRB.CreateCall(Callee: getFindMatchingCatch(M, NumClauses: 0), Args: {}, Name: "exn");
1553 IRB.CreateCall(Callee: ResumeF, Args: {Exn});
1554 IRB.CreateUnreachable();
1555 }
1556
1557 IRB.SetInsertPoint(CI);
1558 BasicBlock *NormalBB = BasicBlock::Create(Context&: C, Name: "normal", Parent: &F);
1559 Value *CmpEqOne =
1560 IRB.CreateICmpEQ(LHS: Threw, RHS: getAddrSizeInt(M: &M, C: 1), Name: "cmp.eq.one");
1561 IRB.CreateCondBr(Cond: CmpEqOne, True: RethrowExnBB, False: NormalBB);
1562
1563 IRB.SetInsertPoint(NormalBB);
1564 IRB.CreateBr(Dest: Tail);
1565 BB = NormalBB; // New insertion point to insert __wasm_setjmp_test()
1566 }
1567 }
1568
1569 // We need to replace the terminator in Tail - SplitBlock makes BB go
1570 // straight to Tail, we need to check if a longjmp occurred, and go to the
1571 // right setjmp-tail if so
1572 ToErase.push_back(Elt: BB->getTerminator());
1573
1574 // Generate a function call to __wasm_setjmp_test function and
1575 // preamble/postamble code to figure out (1) whether longjmp
1576 // occurred (2) if longjmp occurred, which setjmp it corresponds to
1577 Value *Label = nullptr;
1578 Value *LongjmpResult = nullptr;
1579 BasicBlock *EndBB = nullptr;
1580 wrapTestSetjmp(BB, DL: CI->getDebugLoc(), Threw, FunctionInvocationId, Label,
1581 LongjmpResult, CallEmLongjmpBB, CallEmLongjmpBBThrewPHI,
1582 CallEmLongjmpBBThrewValuePHI, EndBB);
1583 assert(Label && LongjmpResult && EndBB);
1584
1585 // Create switch instruction
1586 IRB.SetInsertPoint(EndBB);
1587 IRB.SetCurrentDebugLocation(EndBB->back().getDebugLoc());
1588 SwitchInst *SI = IRB.CreateSwitch(V: Label, Dest: Tail, NumCases: SetjmpRetPHIs.size());
1589 // -1 means no longjmp happened, continue normally (will hit the default
1590 // switch case). 0 means a longjmp that is not ours to handle, needs a
1591 // rethrow. Otherwise the index is the same as the index in P+1 (to avoid
1592 // 0).
1593 for (unsigned I = 0; I < SetjmpRetPHIs.size(); I++) {
1594 SI->addCase(OnVal: IRB.getInt32(C: I + 1), Dest: SetjmpRetPHIs[I]->getParent());
1595 SetjmpRetPHIs[I]->addIncoming(V: LongjmpResult, BB: EndBB);
1596 }
1597
1598 // We are splitting the block here, and must continue to find other calls
1599 // in the block - which is now split. so continue to traverse in the Tail
1600 BBs.push_back(x: Tail);
1601 }
1602 }
1603
1604 for (Instruction *I : ToErase)
1605 I->eraseFromParent();
1606}
1607
1608static BasicBlock *getCleanupRetUnwindDest(const CleanupPadInst *CPI) {
1609 for (const User *U : CPI->users())
1610 if (const auto *CRI = dyn_cast<CleanupReturnInst>(Val: U))
1611 return CRI->getUnwindDest();
1612 return nullptr;
1613}
1614
1615// Create a catchpad in which we catch a longjmp's env and val arguments, test
1616// if the longjmp corresponds to one of setjmps in the current function, and if
1617// so, jump to the setjmp dispatch BB from which we go to one of post-setjmp
1618// BBs. Refer to 4) of "Wasm setjmp/longjmp handling" section in the comments at
1619// top of the file for details.
1620void WebAssemblyLowerEmscriptenEHSjLjImpl::handleLongjmpableCallsForWasmSjLj(
1621 Function &F, Instruction *FunctionInvocationId,
1622 SmallVectorImpl<PHINode *> &SetjmpRetPHIs) {
1623 Module &M = *F.getParent();
1624 LLVMContext &C = F.getContext();
1625 IRBuilder<> IRB(C);
1626
1627 // A function with catchswitch/catchpad instruction should have a personality
1628 // function attached to it. Search for the wasm personality function, and if
1629 // it exists, use it, and if it doesn't, create a dummy personality function.
1630 // (SjLj is not going to call it anyway.)
1631 if (!F.hasPersonalityFn()) {
1632 StringRef PersName = getEHPersonalityName(Pers: EHPersonality::Wasm_CXX);
1633 FunctionType *PersType =
1634 FunctionType::get(Result: IRB.getInt32Ty(), /* isVarArg */ true);
1635 Value *PersF = M.getOrInsertFunction(Name: PersName, T: PersType).getCallee();
1636 F.setPersonalityFn(
1637 cast<Constant>(Val: IRB.CreateBitCast(V: PersF, DestTy: IRB.getPtrTy())));
1638 }
1639
1640 // Use the entry BB's debugloc as a fallback
1641 BasicBlock *Entry = &F.getEntryBlock();
1642 DebugLoc FirstDL = getOrCreateDebugLoc(InsertBefore: &*Entry->begin(), SP: F.getSubprogram());
1643 IRB.SetCurrentDebugLocation(FirstDL);
1644
1645 // Add setjmp.dispatch BB right after the entry block. Because we have
1646 // initialized functionInvocationId in the entry block and split the
1647 // rest into another BB, here 'OrigEntry' is the function's original entry
1648 // block before the transformation.
1649 //
1650 // entry:
1651 // functionInvocationId initialization
1652 // setjmp.dispatch:
1653 // switch will be inserted here later
1654 // entry.split: (OrigEntry)
1655 // the original function starts here
1656 BasicBlock *OrigEntry = Entry->getNextNode();
1657 BasicBlock *SetjmpDispatchBB =
1658 BasicBlock::Create(Context&: C, Name: "setjmp.dispatch", Parent: &F, InsertBefore: OrigEntry);
1659 cast<UncondBrInst>(Val: Entry->getTerminator())->setSuccessor(SetjmpDispatchBB);
1660
1661 // Create catch.dispatch.longjmp BB and a catchswitch instruction
1662 BasicBlock *CatchDispatchLongjmpBB =
1663 BasicBlock::Create(Context&: C, Name: "catch.dispatch.longjmp", Parent: &F);
1664 IRB.SetInsertPoint(CatchDispatchLongjmpBB);
1665 CatchSwitchInst *CatchSwitchLongjmp =
1666 IRB.CreateCatchSwitch(ParentPad: ConstantTokenNone::get(Context&: C), UnwindBB: nullptr, NumHandlers: 1);
1667
1668 // Create catch.longjmp BB and a catchpad instruction
1669 BasicBlock *CatchLongjmpBB = BasicBlock::Create(Context&: C, Name: "catch.longjmp", Parent: &F);
1670 CatchSwitchLongjmp->addHandler(Dest: CatchLongjmpBB);
1671 IRB.SetInsertPoint(CatchLongjmpBB);
1672 CatchPadInst *CatchPad = IRB.CreateCatchPad(ParentPad: CatchSwitchLongjmp, Args: {});
1673
1674 // Wasm throw and catch instructions can throw and catch multiple values, but
1675 // that requires multivalue support in the toolchain, which is currently not
1676 // very reliable. We instead throw and catch a pointer to a struct value of
1677 // type 'struct __WasmLongjmpArgs', which is defined in Emscripten.
1678 Instruction *LongjmpArgs =
1679 IRB.CreateCall(Callee: CatchF, Args: {IRB.getInt32(C: WebAssembly::C_LONGJMP)}, Name: "thrown");
1680 Value *EnvField =
1681 IRB.CreateConstGEP2_32(Ty: LongjmpArgsTy, Ptr: LongjmpArgs, Idx0: 0, Idx1: 0, Name: "env_gep");
1682 Value *ValField =
1683 IRB.CreateConstGEP2_32(Ty: LongjmpArgsTy, Ptr: LongjmpArgs, Idx0: 0, Idx1: 1, Name: "val_gep");
1684 // void *env = __wasm_longjmp_args.env;
1685 Instruction *Env = IRB.CreateLoad(Ty: IRB.getPtrTy(), Ptr: EnvField, Name: "env");
1686 // int val = __wasm_longjmp_args.val;
1687 Instruction *Val = IRB.CreateLoad(Ty: IRB.getInt32Ty(), Ptr: ValField, Name: "val");
1688
1689 // %label = __wasm_setjmp_test(%env, functionInvocatinoId);
1690 // if (%label == 0)
1691 // __wasm_longjmp(%env, %val)
1692 // catchret to %setjmp.dispatch
1693 BasicBlock *ThenBB = BasicBlock::Create(Context&: C, Name: "if.then", Parent: &F);
1694 BasicBlock *EndBB = BasicBlock::Create(Context&: C, Name: "if.end", Parent: &F);
1695 Value *EnvP = IRB.CreateBitCast(V: Env, DestTy: getAddrPtrType(M: &M), Name: "env.p");
1696 Value *Label = IRB.CreateCall(Callee: WasmSetjmpTestF, Args: {EnvP, FunctionInvocationId},
1697 OpBundles: OperandBundleDef("funclet", CatchPad), Name: "label");
1698 Value *Cmp = IRB.CreateICmpEQ(LHS: Label, RHS: IRB.getInt32(C: 0));
1699 IRB.CreateCondBr(Cond: Cmp, True: ThenBB, False: EndBB);
1700
1701 IRB.SetInsertPoint(ThenBB);
1702 CallInst *WasmLongjmpCI = IRB.CreateCall(
1703 Callee: WasmLongjmpF, Args: {Env, Val}, OpBundles: OperandBundleDef("funclet", CatchPad));
1704 IRB.CreateUnreachable();
1705
1706 IRB.SetInsertPoint(EndBB);
1707 // Jump to setjmp.dispatch block
1708 IRB.CreateCatchRet(CatchPad, BB: SetjmpDispatchBB);
1709
1710 // Go back to setjmp.dispatch BB
1711 // setjmp.dispatch:
1712 // switch %label {
1713 // label 1: goto post-setjmp BB 1
1714 // label 2: goto post-setjmp BB 2
1715 // ...
1716 // default: goto splitted next BB
1717 // }
1718 IRB.SetInsertPoint(SetjmpDispatchBB);
1719 PHINode *LabelPHI = IRB.CreatePHI(Ty: IRB.getInt32Ty(), NumReservedValues: 2, Name: "label.phi");
1720 LabelPHI->addIncoming(V: Label, BB: EndBB);
1721 LabelPHI->addIncoming(V: IRB.getInt32(C: -1), BB: Entry);
1722 SwitchInst *SI = IRB.CreateSwitch(V: LabelPHI, Dest: OrigEntry, NumCases: SetjmpRetPHIs.size());
1723 // -1 means no longjmp happened, continue normally (will hit the default
1724 // switch case). 0 means a longjmp that is not ours to handle, needs a
1725 // rethrow. Otherwise the index is the same as the index in P+1 (to avoid
1726 // 0).
1727 for (unsigned I = 0; I < SetjmpRetPHIs.size(); I++) {
1728 SI->addCase(OnVal: IRB.getInt32(C: I + 1), Dest: SetjmpRetPHIs[I]->getParent());
1729 SetjmpRetPHIs[I]->addIncoming(V: Val, BB: SetjmpDispatchBB);
1730 }
1731
1732 // Convert all longjmpable call instructions to invokes that unwind to the
1733 // newly created catch.dispatch.longjmp BB.
1734 SmallVector<CallInst *, 64> LongjmpableCalls;
1735 for (auto *BB = &*F.begin(); BB; BB = BB->getNextNode()) {
1736 for (auto &I : *BB) {
1737 auto *CI = dyn_cast<CallInst>(Val: &I);
1738 if (!CI)
1739 continue;
1740 const Value *Callee = CI->getCalledOperand();
1741 if (!canLongjmp(Callee))
1742 continue;
1743 if (isEmAsmCall(Callee))
1744 report_fatal_error(reason: "Cannot use EM_ASM* alongside setjmp/longjmp in " +
1745 F.getName() +
1746 ". Please consider using EM_JS, or move the "
1747 "EM_ASM into another function.",
1748 gen_crash_diag: false);
1749 // This is __wasm_longjmp() call we inserted in this function, which
1750 // rethrows the longjmp when the longjmp does not correspond to one of
1751 // setjmps in this function. We should not convert this call to an invoke.
1752 if (CI == WasmLongjmpCI)
1753 continue;
1754 LongjmpableCalls.push_back(Elt: CI);
1755 }
1756 }
1757
1758 SmallMapVector<BasicBlock *, SmallSetVector<BasicBlock *, 4>, 4>
1759 UnwindDestToNewPreds;
1760 for (auto *CI : LongjmpableCalls) {
1761 // Even if the callee function has attribute 'nounwind', which is true for
1762 // all C functions, it can longjmp, which means it can throw a Wasm
1763 // exception now.
1764 CI->removeFnAttr(Kind: Attribute::NoUnwind);
1765 if (Function *CalleeF = CI->getCalledFunction())
1766 CalleeF->removeFnAttr(Kind: Attribute::NoUnwind);
1767
1768 // Change it to an invoke and make it unwind to the catch.dispatch.longjmp
1769 // BB. If the call is enclosed in another catchpad/cleanuppad scope, unwind
1770 // to its parent pad's unwind destination instead to preserve the scope
1771 // structure. It will eventually unwind to the catch.dispatch.longjmp.
1772 BasicBlock *UnwindDest = nullptr;
1773 if (auto Bundle = CI->getOperandBundle(ID: LLVMContext::OB_funclet)) {
1774 Instruction *FromPad = cast<Instruction>(Val: Bundle->Inputs[0]);
1775 while (!UnwindDest) {
1776 if (auto *CPI = dyn_cast<CatchPadInst>(Val: FromPad)) {
1777 UnwindDest = CPI->getCatchSwitch()->getUnwindDest();
1778 break;
1779 }
1780 if (auto *CPI = dyn_cast<CleanupPadInst>(Val: FromPad)) {
1781 // getCleanupRetUnwindDest() can return nullptr when
1782 // 1. This cleanuppad's matching cleanupret uwninds to caller
1783 // 2. There is no matching cleanupret because it ends with
1784 // unreachable.
1785 // In case of 2, we need to traverse the parent pad chain.
1786 UnwindDest = getCleanupRetUnwindDest(CPI);
1787 Value *ParentPad = CPI->getParentPad();
1788 if (isa<ConstantTokenNone>(Val: ParentPad))
1789 break;
1790 FromPad = cast<Instruction>(Val: ParentPad);
1791 }
1792 }
1793 }
1794 if (!UnwindDest)
1795 UnwindDest = CatchDispatchLongjmpBB;
1796 // Because we are changing a longjmpable call to an invoke, its unwind
1797 // destination can be an existing EH pad that already have phis, and the BB
1798 // with the newly created invoke will become a new predecessor of that EH
1799 // pad. In this case we need to add the new predecessor to those phis.
1800 UnwindDestToNewPreds[UnwindDest].insert(X: CI->getParent());
1801 changeToInvokeAndSplitBasicBlock(CI, UnwindEdge: UnwindDest);
1802 }
1803
1804 SmallVector<Instruction *, 16> ToErase;
1805 for (auto &BB : F) {
1806 if (auto *CSI = dyn_cast<CatchSwitchInst>(Val: BB.getFirstNonPHIIt())) {
1807 if (CSI != CatchSwitchLongjmp && CSI->unwindsToCaller()) {
1808 IRB.SetInsertPoint(CSI);
1809 ToErase.push_back(Elt: CSI);
1810 auto *NewCSI = IRB.CreateCatchSwitch(ParentPad: CSI->getParentPad(),
1811 UnwindBB: CatchDispatchLongjmpBB, NumHandlers: 1);
1812 NewCSI->addHandler(Dest: *CSI->handler_begin());
1813 NewCSI->takeName(V: CSI);
1814 CSI->replaceAllUsesWith(V: NewCSI);
1815 }
1816 }
1817
1818 if (auto *CRI = dyn_cast<CleanupReturnInst>(Val: BB.getTerminator())) {
1819 if (CRI->unwindsToCaller()) {
1820 IRB.SetInsertPoint(CRI);
1821 ToErase.push_back(Elt: CRI);
1822 IRB.CreateCleanupRet(CleanupPad: CRI->getCleanupPad(), UnwindBB: CatchDispatchLongjmpBB);
1823 }
1824 }
1825 }
1826
1827 for (Instruction *I : ToErase)
1828 I->eraseFromParent();
1829
1830 // Add entries for new predecessors to phis in unwind destinations. We use
1831 // 'poison' as a placeholder value. We should make sure the phis have a valid
1832 // set of predecessors before running SSAUpdater, because SSAUpdater
1833 // internally can use existing phis to gather predecessor info rather than
1834 // scanning the actual CFG (See FindPredecessorBlocks in SSAUpdater.cpp for
1835 // details).
1836 for (auto &[UnwindDest, NewPreds] : UnwindDestToNewPreds) {
1837 for (PHINode &PN : UnwindDest->phis()) {
1838 for (auto *NewPred : NewPreds) {
1839 assert(PN.getBasicBlockIndex(NewPred) == -1);
1840 PN.addIncoming(V: PoisonValue::get(T: PN.getType()), BB: NewPred);
1841 }
1842 }
1843 }
1844
1845 // For unwind destinations for newly added invokes to longjmpable functions,
1846 // calculate incoming values for the newly added predecessors using
1847 // SSAUpdater. We add existing values in the phis to SSAUpdater as available
1848 // values and let it calculate what the value should be at the end of new
1849 // incoming blocks.
1850 for (auto &[UnwindDest, NewPreds] : UnwindDestToNewPreds) {
1851 for (PHINode &PN : UnwindDest->phis()) {
1852 SSAUpdater SSA;
1853 SSA.Initialize(Ty: PN.getType(), Name: PN.getName());
1854 for (unsigned Idx = 0, E = PN.getNumIncomingValues(); Idx != E; ++Idx) {
1855 if (NewPreds.contains(key: PN.getIncomingBlock(i: Idx)))
1856 continue;
1857 Value *V = PN.getIncomingValue(i: Idx);
1858 if (auto *II = dyn_cast<InvokeInst>(Val: V))
1859 SSA.AddAvailableValue(BB: II->getNormalDest(), V: II);
1860 else if (auto *I = dyn_cast<Instruction>(Val: V))
1861 SSA.AddAvailableValue(BB: I->getParent(), V: I);
1862 else
1863 SSA.AddAvailableValue(BB: PN.getIncomingBlock(i: Idx), V);
1864 }
1865 for (auto *NewPred : NewPreds)
1866 PN.setIncomingValueForBlock(BB: NewPred, V: SSA.GetValueAtEndOfBlock(BB: NewPred));
1867 assert(PN.isComplete());
1868 }
1869 }
1870}
1871
1872bool WebAssemblyLowerEmscriptenEHSjLjLegacy::runOnModule(Module &M) {
1873 WebAssemblyLowerEmscriptenEHSjLjImpl Impl(
1874 [&](Function &F) -> DominatorTree & {
1875 return getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
1876 });
1877 return Impl.runOnModule(M);
1878}
1879
1880PreservedAnalyses
1881WebAssemblyLowerEmscriptenEHSjLjPass::run(Module &M,
1882 ModuleAnalysisManager &MAM) {
1883 WebAssemblyLowerEmscriptenEHSjLjImpl Impl(
1884 [&](Function &F) -> DominatorTree & {
1885 return MAM.getResult<FunctionAnalysisManagerModuleProxy>(IR&: M)
1886 .getManager()
1887 .getResult<DominatorTreeAnalysis>(IR&: F);
1888 });
1889 return Impl.runOnModule(M) ? PreservedAnalyses::none()
1890 : PreservedAnalyses::all();
1891}
1892