LLVM 23.0.0git
WebAssemblyLowerEmscriptenEHSjLj.cpp
Go to the documentation of this file.
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"
270#include "llvm/IR/Dominators.h"
271#include "llvm/IR/IRBuilder.h"
272#include "llvm/IR/IntrinsicsWebAssembly.h"
273#include "llvm/IR/Module.h"
279#include <set>
280
281using namespace llvm;
282
283#define DEBUG_TYPE "wasm-lower-em-ehsjlj"
284
286 EHAllowlist("emscripten-cxx-exceptions-allowed",
287 cl::desc("The list of function names in which Emscripten-style "
288 "exception handling is enabled (see emscripten "
289 "EMSCRIPTEN_CATCHING_ALLOWED options)"),
291
292namespace {
293class WebAssemblyLowerEmscriptenEHSjLj final : public ModulePass {
294 bool EnableEmEH; // Enable Emscripten exception handling
295 bool EnableEmSjLj; // Enable Emscripten setjmp/longjmp handling
296 bool EnableWasmSjLj; // Enable Wasm setjmp/longjmp handling
297 bool DoSjLj; // Whether we actually perform setjmp/longjmp handling
298
299 GlobalVariable *ThrewGV = nullptr; // __THREW__ (Emscripten)
300 GlobalVariable *ThrewValueGV = nullptr; // __threwValue (Emscripten)
301 Function *GetTempRet0F = nullptr; // getTempRet0() (Emscripten)
302 Function *SetTempRet0F = nullptr; // setTempRet0() (Emscripten)
303 Function *ResumeF = nullptr; // __resumeException() (Emscripten)
304 Function *EHTypeIDF = nullptr; // llvm.eh.typeid.for() (intrinsic)
305 Function *EmLongjmpF = nullptr; // emscripten_longjmp() (Emscripten)
306 Function *WasmSetjmpF = nullptr; // __wasm_setjmp() (Emscripten)
307 Function *WasmSetjmpTestF = nullptr; // __wasm_setjmp_test() (Emscripten)
308 Function *WasmLongjmpF = nullptr; // __wasm_longjmp() (Emscripten)
309 Function *CatchF = nullptr; // wasm.catch() (intrinsic)
310
311 // type of 'struct __WasmLongjmpArgs' defined in emscripten
312 Type *LongjmpArgsTy = nullptr;
313
314 // __cxa_find_matching_catch_N functions.
315 // Indexed by the number of clauses in an original landingpad instruction.
316 DenseMap<int, Function *> FindMatchingCatches;
317 // Map of <function signature string, invoke_ wrappers>
318 StringMap<Function *> InvokeWrappers;
319 // Set of allowed function names for exception handling
320 std::set<std::string, std::less<>> EHAllowlistSet;
321 // Functions that contains calls to setjmp
322 SmallPtrSet<Function *, 8> SetjmpUsers;
323
324 StringRef getPassName() const override {
325 return "WebAssembly Lower Emscripten Exceptions";
326 }
327
328 using InstVector = SmallVectorImpl<Instruction *>;
329 bool runEHOnFunction(Function &F);
330 bool runSjLjOnFunction(Function &F);
331 void handleLongjmpableCallsForEmscriptenSjLj(
332 Function &F, Instruction *FunctionInvocationId,
333 SmallVectorImpl<PHINode *> &SetjmpRetPHIs);
334 void
335 handleLongjmpableCallsForWasmSjLj(Function &F,
336 Instruction *FunctionInvocationId,
337 SmallVectorImpl<PHINode *> &SetjmpRetPHIs);
338 Function *getFindMatchingCatch(Module &M, unsigned NumClauses);
339
340 Value *wrapInvoke(CallBase *CI);
341 void wrapTestSetjmp(BasicBlock *BB, DebugLoc DL, Value *Threw,
342 Value *FunctionInvocationId, Value *&Label,
343 Value *&LongjmpResult, BasicBlock *&CallEmLongjmpBB,
344 PHINode *&CallEmLongjmpBBThrewPHI,
345 PHINode *&CallEmLongjmpBBThrewValuePHI,
346 BasicBlock *&EndBB);
347 Function *getInvokeWrapper(CallBase *CI);
348
349 bool areAllExceptionsAllowed() const { return EHAllowlistSet.empty(); }
350 bool supportsException(const Function *F) const {
351 return EnableEmEH &&
352 (areAllExceptionsAllowed() || EHAllowlistSet.count(F->getName()));
353 }
354 void replaceLongjmpWith(Function *LongjmpF, Function *NewF);
355
356 void rebuildSSA(Function &F);
357
358public:
359 static char ID;
360
361 WebAssemblyLowerEmscriptenEHSjLj()
362 : ModulePass(ID), EnableEmEH(WebAssembly::WasmEnableEmEH),
363 EnableEmSjLj(WebAssembly::WasmEnableEmSjLj),
364 EnableWasmSjLj(WebAssembly::WasmEnableSjLj) {
365 assert(!(EnableEmSjLj && EnableWasmSjLj) &&
366 "Two SjLj modes cannot be turned on at the same time");
367 assert(!(EnableEmEH && EnableWasmSjLj) &&
368 "Wasm SjLj should be only used with Wasm EH");
369 EHAllowlistSet.insert(EHAllowlist.begin(), EHAllowlist.end());
370 }
371 bool runOnModule(Module &M) override;
372
373 void getAnalysisUsage(AnalysisUsage &AU) const override {
374 AU.addRequired<DominatorTreeWrapperPass>();
375 }
376};
377} // End anonymous namespace
378
379char WebAssemblyLowerEmscriptenEHSjLj::ID = 0;
380INITIALIZE_PASS(WebAssemblyLowerEmscriptenEHSjLj, DEBUG_TYPE,
381 "WebAssembly Lower Emscripten Exceptions / Setjmp / Longjmp",
382 false, false)
383
385 return new WebAssemblyLowerEmscriptenEHSjLj();
386}
387
388static bool canThrow(const Value *V) {
389 if (const auto *F = dyn_cast<const Function>(V)) {
390 // Intrinsics cannot throw
391 if (F->isIntrinsic())
392 return false;
393 StringRef Name = F->getName();
394 // leave setjmp and longjmp (mostly) alone, we process them properly later
395 if (Name == "setjmp" || Name == "longjmp" || Name == "emscripten_longjmp")
396 return false;
397 return !F->doesNotThrow();
398 }
399 // not a function, so an indirect call - can throw, we can't tell
400 return true;
401}
402
403// Get a thread-local global variable with the given name. If it doesn't exist
404// declare it, which will generate an import and assume that it will exist at
405// link time.
408 const char *Name) {
409 auto *GV = dyn_cast<GlobalVariable>(M.getOrInsertGlobal(Name, Ty));
410 if (!GV)
411 report_fatal_error(Twine("unable to create global: ") + Name);
412
413 // Variables created by this function are thread local. If the target does not
414 // support TLS, we depend on CoalesceFeaturesAndStripAtomics to downgrade it
415 // to non-thread-local ones, in which case we don't allow this object to be
416 // linked with other objects using shared memory.
417 GV->setThreadLocalMode(GlobalValue::GeneralDynamicTLSModel);
418 return GV;
419}
420
421// Simple function name mangler.
422// This function simply takes LLVM's string representation of parameter types
423// and concatenate them with '_'. There are non-alphanumeric characters but llc
424// is ok with it, and we need to postprocess these names after the lowering
425// phase anyway.
426static std::string getSignature(FunctionType *FTy) {
427 std::string Sig;
428 raw_string_ostream OS(Sig);
429 OS << *FTy->getReturnType();
430 for (Type *ParamTy : FTy->params())
431 OS << "_" << *ParamTy;
432 if (FTy->isVarArg())
433 OS << "_...";
434 Sig = OS.str();
435 erase_if(Sig, isSpace);
436 // When s2wasm parses .s file, a comma means the end of an argument. So a
437 // mangled function name can contain any character but a comma.
438 llvm::replace(Sig, ',', '.');
439 return Sig;
440}
441
442static Function *getFunction(FunctionType *Ty, const Twine &Name, Module *M) {
444}
445
446static void markAsImported(Function *F) {
447 // Tell the linker that this function is expected to be imported from the
448 // 'env' module. This is necessary for functions that do not have fixed names
449 // (e.g. __import_xyz). These names cannot be provided by any kind of shared
450 // or static library as instead we mark them explictly as imported.
451 if (!F->hasFnAttribute("wasm-import-module")) {
452 llvm::AttrBuilder B(F->getParent()->getContext());
453 B.addAttribute("wasm-import-module", "env");
454 F->addFnAttrs(B);
455 }
456 if (!F->hasFnAttribute("wasm-import-name")) {
457 llvm::AttrBuilder B(F->getParent()->getContext());
458 B.addAttribute("wasm-import-name", F->getName());
459 F->addFnAttrs(B);
460 }
461}
462
463// Returns an integer type for the target architecture's address space.
464// i32 for wasm32 and i64 for wasm64.
466 IRBuilder<> IRB(M->getContext());
467 return IRB.getIntNTy(M->getDataLayout().getPointerSizeInBits());
468}
469
470// Returns an integer pointer type for the target architecture's address space.
471// i32* for wasm32 and i64* for wasm64. With opaque pointers this is just a ptr
472// in address space zero.
474 return PointerType::getUnqual(M->getContext());
475}
476
477// Returns an integer whose type is the integer type for the target's address
478// space. Returns (i32 C) for wasm32 and (i64 C) for wasm64, when C is the
479// integer.
481 IRBuilder<> IRB(M->getContext());
482 return IRB.getIntN(M->getDataLayout().getPointerSizeInBits(), C);
483}
484
485// Returns true if the function has "target-features"="+exception-handling"
486// attribute.
487static bool hasEHTargetFeatureAttr(const Function &F) {
488 Attribute FeaturesAttr = F.getFnAttribute("target-features");
489 return FeaturesAttr.isValid() &&
490 FeaturesAttr.getValueAsString().contains("+exception-handling");
491}
492
493// Returns __cxa_find_matching_catch_N function, where N = NumClauses + 2.
494// This is because a landingpad instruction contains two more arguments, a
495// personality function and a cleanup bit, and __cxa_find_matching_catch_N
496// functions are named after the number of arguments in the original landingpad
497// instruction.
498Function *
499WebAssemblyLowerEmscriptenEHSjLj::getFindMatchingCatch(Module &M,
500 unsigned NumClauses) {
501 auto [It, Inserted] = FindMatchingCatches.try_emplace(NumClauses);
502 if (!Inserted)
503 return It->second;
504 PointerType *Int8PtrTy = PointerType::getUnqual(M.getContext());
505 SmallVector<Type *, 16> Args(NumClauses, Int8PtrTy);
506 FunctionType *FTy = FunctionType::get(Int8PtrTy, Args, false);
508 FTy, "__cxa_find_matching_catch_" + Twine(NumClauses + 2), &M);
510 It->second = F;
511 return F;
512}
513
514// Generate invoke wrapper seqence with preamble and postamble
515// Preamble:
516// __THREW__ = 0;
517// Postamble:
518// %__THREW__.val = __THREW__; __THREW__ = 0;
519// Returns %__THREW__.val, which indicates whether an exception is thrown (or
520// whether longjmp occurred), for future use.
521Value *WebAssemblyLowerEmscriptenEHSjLj::wrapInvoke(CallBase *CI) {
522 Module *M = CI->getModule();
523 LLVMContext &C = M->getContext();
524
525 IRBuilder<> IRB(C);
526 IRB.SetInsertPoint(CI);
527
528 // Pre-invoke
529 // __THREW__ = 0;
530 IRB.CreateStore(getAddrSizeInt(M, 0), ThrewGV);
531
532 // Invoke function wrapper in JavaScript
533 SmallVector<Value *, 16> Args;
534 // Put the pointer to the callee as first argument, so it can be called
535 // within the invoke wrapper later
536 Args.push_back(CI->getCalledOperand());
537 Args.append(CI->arg_begin(), CI->arg_end());
538 CallInst *NewCall = IRB.CreateCall(getInvokeWrapper(CI), Args);
539 NewCall->takeName(CI);
540 NewCall->setCallingConv(CallingConv::WASM_EmscriptenInvoke);
541 NewCall->setDebugLoc(CI->getDebugLoc());
542
543 // Because we added the pointer to the callee as first argument, all
544 // argument attribute indices have to be incremented by one.
545 SmallVector<AttributeSet, 8> ArgAttributes;
546 const AttributeList &InvokeAL = CI->getAttributes();
547
548 // No attributes for the callee pointer.
549 ArgAttributes.push_back(AttributeSet());
550 // Copy the argument attributes from the original
551 for (unsigned I = 0, E = CI->arg_size(); I < E; ++I)
552 ArgAttributes.push_back(InvokeAL.getParamAttrs(I));
553
554 AttrBuilder FnAttrs(CI->getContext(), InvokeAL.getFnAttrs());
555 if (auto Args = FnAttrs.getAllocSizeArgs()) {
556 // The allocsize attribute (if any) referes to parameters by index and needs
557 // to be adjusted.
558 auto [SizeArg, NEltArg] = *Args;
559 SizeArg += 1;
560 if (NEltArg)
561 NEltArg = *NEltArg + 1;
562 FnAttrs.addAllocSizeAttr(SizeArg, NEltArg);
563 }
564 // In case the callee has 'noreturn' attribute, We need to remove it, because
565 // we expect invoke wrappers to return.
566 FnAttrs.removeAttribute(Attribute::NoReturn);
567
568 // Reconstruct the AttributesList based on the vector we constructed.
569 AttributeList NewCallAL = AttributeList::get(
570 C, AttributeSet::get(C, FnAttrs), InvokeAL.getRetAttrs(), ArgAttributes);
571 NewCall->setAttributes(NewCallAL);
572
573 CI->replaceAllUsesWith(NewCall);
574
575 // Post-invoke
576 // %__THREW__.val = __THREW__; __THREW__ = 0;
577 Value *Threw =
578 IRB.CreateLoad(getAddrIntType(M), ThrewGV, ThrewGV->getName() + ".val");
579 IRB.CreateStore(getAddrSizeInt(M, 0), ThrewGV);
580 return Threw;
581}
582
583// Get matching invoke wrapper based on callee signature
584Function *WebAssemblyLowerEmscriptenEHSjLj::getInvokeWrapper(CallBase *CI) {
585 Module *M = CI->getModule();
587 FunctionType *CalleeFTy = CI->getFunctionType();
588
589 std::string Sig = getSignature(CalleeFTy);
590 auto It = InvokeWrappers.find(Sig);
591 if (It != InvokeWrappers.end())
592 return It->second;
593
594 // Put the pointer to the callee as first argument
595 ArgTys.push_back(PointerType::getUnqual(CI->getContext()));
596 // Add argument types
597 ArgTys.append(CalleeFTy->param_begin(), CalleeFTy->param_end());
598
599 FunctionType *FTy = FunctionType::get(CalleeFTy->getReturnType(), ArgTys,
600 CalleeFTy->isVarArg());
601 Function *F = getFunction(FTy, "__invoke_" + Sig, M);
603 InvokeWrappers[Sig] = F;
604 return F;
605}
606
607static bool canLongjmp(const Value *Callee) {
608 if (auto *CalleeF = dyn_cast<Function>(Callee))
609 if (CalleeF->isIntrinsic())
610 return false;
611
612 // Attempting to transform inline assembly will result in something like:
613 // call void @__invoke_void(void ()* asm ...)
614 // which is invalid because inline assembly blocks do not have addresses
615 // and can't be passed by pointer. The result is a crash with illegal IR.
616 if (isa<InlineAsm>(Callee))
617 return false;
618 StringRef CalleeName = Callee->getName();
619
620 // TODO Include more functions or consider checking with mangled prefixes
621
622 // The reason we include malloc/free here is to exclude the malloc/free
623 // calls generated in setjmp prep / cleanup routines.
624 if (CalleeName == "setjmp" || CalleeName == "malloc" || CalleeName == "free")
625 return false;
626
627 // There are functions in Emscripten's JS glue code or compiler-rt
628 if (CalleeName == "__resumeException" || CalleeName == "llvm_eh_typeid_for" ||
629 CalleeName == "__wasm_setjmp" || CalleeName == "__wasm_setjmp_test" ||
630 CalleeName == "getTempRet0" || CalleeName == "setTempRet0")
631 return false;
632
633 // __cxa_find_matching_catch_N functions cannot longjmp
634 if (Callee->getName().starts_with("__cxa_find_matching_catch_"))
635 return false;
636
637 // Exception-catching related functions
638 //
639 // We intentionally treat __cxa_end_catch longjmpable in Wasm SjLj even though
640 // it surely cannot longjmp, in order to maintain the unwind relationship from
641 // all existing catchpads (and calls within them) to catch.dispatch.longjmp.
642 //
643 // In Wasm EH + Wasm SjLj, we
644 // 1. Make all catchswitch and cleanuppad that unwind to caller unwind to
645 // catch.dispatch.longjmp instead
646 // 2. Convert all longjmpable calls to invokes that unwind to
647 // catch.dispatch.longjmp
648 // But catchswitch BBs are removed in isel, so if an EH catchswitch (generated
649 // from an exception)'s catchpad does not contain any calls that are converted
650 // into invokes unwinding to catch.dispatch.longjmp, this unwind relationship
651 // (EH catchswitch BB -> catch.dispatch.longjmp BB) is lost and
652 // catch.dispatch.longjmp BB can be placed before the EH catchswitch BB in
653 // CFGSort.
654 // int ret = setjmp(buf);
655 // try {
656 // foo(); // longjmps
657 // } catch (...) {
658 // }
659 // Then in this code, if 'foo' longjmps, it first unwinds to 'catch (...)'
660 // catchswitch, and is not caught by that catchswitch because it is a longjmp,
661 // then it should next unwind to catch.dispatch.longjmp BB. But if this 'catch
662 // (...)' catchswitch -> catch.dispatch.longjmp unwind relationship is lost,
663 // it will not unwind to catch.dispatch.longjmp, producing an incorrect
664 // result.
665 //
666 // Every catchpad generated by Wasm C++ contains __cxa_end_catch, so we
667 // intentionally treat it as longjmpable to work around this problem. This is
668 // a hacky fix but an easy one.
669 if (CalleeName == "__cxa_end_catch")
671 if (CalleeName == "__cxa_begin_catch" ||
672 CalleeName == "__cxa_allocate_exception" || CalleeName == "__cxa_throw" ||
673 CalleeName == "__clang_call_terminate")
674 return false;
675
676 // std::terminate, which is generated when another exception occurs while
677 // handling an exception, cannot longjmp.
678 if (CalleeName == "_ZSt9terminatev")
679 return false;
680
681 // Otherwise we don't know
682 return true;
683}
684
685static bool isEmAsmCall(const Value *Callee) {
686 StringRef CalleeName = Callee->getName();
687 // This is an exhaustive list from Emscripten's <emscripten/em_asm.h>.
688 return CalleeName == "emscripten_asm_const_int" ||
689 CalleeName == "emscripten_asm_const_double" ||
690 CalleeName == "emscripten_asm_const_int_sync_on_main_thread" ||
691 CalleeName == "emscripten_asm_const_double_sync_on_main_thread" ||
692 CalleeName == "emscripten_asm_const_async_on_main_thread";
693}
694
695// Generate __wasm_setjmp_test function call seqence with preamble and
696// postamble. The code this generates is equivalent to the following
697// JavaScript code:
698// %__threwValue.val = __threwValue;
699// if (%__THREW__.val != 0 & %__threwValue.val != 0) {
700// %label = __wasm_setjmp_test(%__THREW__.val, functionInvocationId);
701// if (%label == 0)
702// emscripten_longjmp(%__THREW__.val, %__threwValue.val);
703// setTempRet0(%__threwValue.val);
704// } else {
705// %label = -1;
706// }
707// %longjmp_result = getTempRet0();
708//
709// As output parameters. returns %label, %longjmp_result, and the BB the last
710// instruction (%longjmp_result = ...) is in.
711void WebAssemblyLowerEmscriptenEHSjLj::wrapTestSetjmp(
712 BasicBlock *BB, DebugLoc DL, Value *Threw, Value *FunctionInvocationId,
713 Value *&Label, Value *&LongjmpResult, BasicBlock *&CallEmLongjmpBB,
714 PHINode *&CallEmLongjmpBBThrewPHI, PHINode *&CallEmLongjmpBBThrewValuePHI,
715 BasicBlock *&EndBB) {
716 Function *F = BB->getParent();
717 Module *M = F->getParent();
718 LLVMContext &C = M->getContext();
719 IRBuilder<> IRB(C);
720 IRB.SetCurrentDebugLocation(DL);
721
722 // if (%__THREW__.val != 0 & %__threwValue.val != 0)
723 IRB.SetInsertPoint(BB);
724 BasicBlock *ThenBB1 = BasicBlock::Create(C, "if.then1", F);
725 BasicBlock *ElseBB1 = BasicBlock::Create(C, "if.else1", F);
726 BasicBlock *EndBB1 = BasicBlock::Create(C, "if.end", F);
727 Value *ThrewCmp = IRB.CreateICmpNE(Threw, getAddrSizeInt(M, 0));
728 Value *ThrewValue = IRB.CreateLoad(IRB.getInt32Ty(), ThrewValueGV,
729 ThrewValueGV->getName() + ".val");
730 Value *ThrewValueCmp = IRB.CreateICmpNE(ThrewValue, IRB.getInt32(0));
731 Value *Cmp1 = IRB.CreateAnd(ThrewCmp, ThrewValueCmp, "cmp1");
732 IRB.CreateCondBr(Cmp1, ThenBB1, ElseBB1);
733
734 // Generate call.em.longjmp BB once and share it within the function
735 if (!CallEmLongjmpBB) {
736 // emscripten_longjmp(%__THREW__.val, %__threwValue.val);
737 CallEmLongjmpBB = BasicBlock::Create(C, "call.em.longjmp", F);
738 IRB.SetInsertPoint(CallEmLongjmpBB);
739 CallEmLongjmpBBThrewPHI = IRB.CreatePHI(getAddrIntType(M), 4, "threw.phi");
740 CallEmLongjmpBBThrewValuePHI =
741 IRB.CreatePHI(IRB.getInt32Ty(), 4, "threwvalue.phi");
742 CallEmLongjmpBBThrewPHI->addIncoming(Threw, ThenBB1);
743 CallEmLongjmpBBThrewValuePHI->addIncoming(ThrewValue, ThenBB1);
744 IRB.CreateCall(EmLongjmpF,
745 {CallEmLongjmpBBThrewPHI, CallEmLongjmpBBThrewValuePHI});
746 IRB.CreateUnreachable();
747 } else {
748 CallEmLongjmpBBThrewPHI->addIncoming(Threw, ThenBB1);
749 CallEmLongjmpBBThrewValuePHI->addIncoming(ThrewValue, ThenBB1);
750 }
751
752 // %label = __wasm_setjmp_test(%__THREW__.val, functionInvocationId);
753 // if (%label == 0)
754 IRB.SetInsertPoint(ThenBB1);
755 BasicBlock *EndBB2 = BasicBlock::Create(C, "if.end2", F);
756 Value *ThrewPtr =
757 IRB.CreateIntToPtr(Threw, getAddrPtrType(M), Threw->getName() + ".p");
758 Value *ThenLabel = IRB.CreateCall(WasmSetjmpTestF,
759 {ThrewPtr, FunctionInvocationId}, "label");
760 Value *Cmp2 = IRB.CreateICmpEQ(ThenLabel, IRB.getInt32(0));
761 IRB.CreateCondBr(Cmp2, CallEmLongjmpBB, EndBB2);
762
763 // setTempRet0(%__threwValue.val);
764 IRB.SetInsertPoint(EndBB2);
765 IRB.CreateCall(SetTempRet0F, ThrewValue);
766 IRB.CreateBr(EndBB1);
767
768 IRB.SetInsertPoint(ElseBB1);
769 IRB.CreateBr(EndBB1);
770
771 // longjmp_result = getTempRet0();
772 IRB.SetInsertPoint(EndBB1);
773 PHINode *LabelPHI = IRB.CreatePHI(IRB.getInt32Ty(), 2, "label");
774 LabelPHI->addIncoming(ThenLabel, EndBB2);
775
776 LabelPHI->addIncoming(IRB.getInt32(-1), ElseBB1);
777
778 // Output parameter assignment
779 Label = LabelPHI;
780 EndBB = EndBB1;
781 LongjmpResult = IRB.CreateCall(GetTempRet0F, {}, "longjmp_result");
782}
783
784void WebAssemblyLowerEmscriptenEHSjLj::rebuildSSA(Function &F) {
785 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
786 DT.recalculate(F); // CFG has been changed
787
788 SSAUpdaterBulk SSA;
789 for (BasicBlock &BB : F) {
790 for (Instruction &I : BB) {
791 if (I.getType()->isVoidTy())
792 continue;
793
794 if (isa<AllocaInst>(&I)) {
795 // If the alloca has any lifetime marker that is no longer dominated
796 // by the alloca, remove all lifetime markers. Lifetime markers must
797 // always work directly on the alloca, and this is no longer possible.
798 bool HasNonDominatedLifetimeMarker = any_of(I.users(), [&](User *U) {
799 auto *UserI = cast<Instruction>(U);
800 return UserI->isLifetimeStartOrEnd() && !DT.dominates(&I, UserI);
801 });
802 if (HasNonDominatedLifetimeMarker) {
803 for (User *U : make_early_inc_range(I.users())) {
804 auto *UserI = cast<Instruction>(U);
805 if (UserI->isLifetimeStartOrEnd())
806 UserI->eraseFromParent();
807 }
808 }
809 }
810
811 unsigned VarID = SSA.AddVariable(I.getName(), I.getType());
812 // If a value is defined by an invoke instruction, it is only available in
813 // its normal destination and not in its unwind destination.
814 if (auto *II = dyn_cast<InvokeInst>(&I))
815 SSA.AddAvailableValue(VarID, II->getNormalDest(), II);
816 else
817 SSA.AddAvailableValue(VarID, &BB, &I);
818 for (auto &U : I.uses()) {
819 auto *User = cast<Instruction>(U.getUser());
820 if (auto *UserPN = dyn_cast<PHINode>(User))
821 if (UserPN->getIncomingBlock(U) == &BB)
822 continue;
823 if (DT.dominates(&I, User))
824 continue;
825 SSA.AddUse(VarID, &U);
826 }
827 }
828 }
829 SSA.RewriteAllUses(&DT);
830}
831
832// Replace uses of longjmp with a new longjmp function in Emscripten library.
833// In Emscripten SjLj, the new function is
834// void emscripten_longjmp(uintptr_t, i32)
835// In Wasm SjLj, the new function is
836// void __wasm_longjmp(i8*, i32)
837// Because the original libc longjmp function takes (jmp_buf*, i32), we need a
838// ptrtoint/bitcast instruction here to make the type match. jmp_buf* will
839// eventually be lowered to i32/i64 in the wasm backend.
840void WebAssemblyLowerEmscriptenEHSjLj::replaceLongjmpWith(Function *LongjmpF,
841 Function *NewF) {
842 assert(NewF == EmLongjmpF || NewF == WasmLongjmpF);
843 Module *M = LongjmpF->getParent();
845 LLVMContext &C = LongjmpF->getParent()->getContext();
846 IRBuilder<> IRB(C);
847
848 // For calls to longjmp, replace it with emscripten_longjmp/__wasm_longjmp and
849 // cast its first argument (jmp_buf*) appropriately
850 for (User *U : LongjmpF->users()) {
851 auto *CI = dyn_cast<CallInst>(U);
852 if (CI && CI->getCalledFunction() == LongjmpF) {
853 IRB.SetInsertPoint(CI);
854 Value *Env = nullptr;
855 if (NewF == EmLongjmpF)
856 Env =
857 IRB.CreatePtrToInt(CI->getArgOperand(0), getAddrIntType(M), "env");
858 else // WasmLongjmpF
859 Env = IRB.CreateBitCast(CI->getArgOperand(0), IRB.getPtrTy(), "env");
860 IRB.CreateCall(NewF, {Env, CI->getArgOperand(1)});
861 ToErase.push_back(CI);
862 }
863 }
864 for (auto *I : ToErase)
865 I->eraseFromParent();
866
867 // If we have any remaining uses of longjmp's function pointer, replace it
868 // with (void(*)(jmp_buf*, int))emscripten_longjmp / __wasm_longjmp.
869 if (!LongjmpF->uses().empty()) {
870 Value *NewLongjmp =
871 IRB.CreateBitCast(NewF, LongjmpF->getType(), "longjmp.cast");
872 LongjmpF->replaceAllUsesWith(NewLongjmp);
873 }
874}
875
877 for (const auto &BB : *F)
878 for (const auto &I : BB)
879 if (const auto *CB = dyn_cast<CallBase>(&I))
880 if (canLongjmp(CB->getCalledOperand()))
881 return true;
882 return false;
883}
884
885// When a function contains a setjmp call but not other calls that can longjmp,
886// we don't do setjmp transformation for that setjmp. But we need to convert the
887// setjmp calls into "i32 0" so they don't cause link time errors. setjmp always
888// returns 0 when called directly.
889static void nullifySetjmp(Function *F) {
890 Module &M = *F->getParent();
891 IRBuilder<> IRB(M.getContext());
892 Function *SetjmpF = M.getFunction("setjmp");
894
895 for (User *U : make_early_inc_range(SetjmpF->users())) {
896 auto *CB = cast<CallBase>(U);
897 BasicBlock *BB = CB->getParent();
898 if (BB->getParent() != F) // in other function
899 continue;
900 CallInst *CI = nullptr;
901 // setjmp cannot throw. So if it is an invoke, lower it to a call
902 if (auto *II = dyn_cast<InvokeInst>(CB))
904 else
905 CI = cast<CallInst>(CB);
906 ToErase.push_back(CI);
907 CI->replaceAllUsesWith(IRB.getInt32(0));
908 }
909 for (auto *I : ToErase)
910 I->eraseFromParent();
911}
912
913bool WebAssemblyLowerEmscriptenEHSjLj::runOnModule(Module &M) {
914 LLVM_DEBUG(dbgs() << "********** Lower Emscripten EH & SjLj **********\n");
915
916 LLVMContext &C = M.getContext();
917 IRBuilder<> IRB(C);
918
919 Function *SetjmpF = M.getFunction("setjmp");
920 Function *LongjmpF = M.getFunction("longjmp");
921
922 // In some platforms _setjmp and _longjmp are used instead. Change these to
923 // use setjmp/longjmp instead, because we later detect these functions by
924 // their names.
925 Function *SetjmpF2 = M.getFunction("_setjmp");
926 Function *LongjmpF2 = M.getFunction("_longjmp");
927 if (SetjmpF2) {
928 if (SetjmpF) {
929 if (SetjmpF->getFunctionType() != SetjmpF2->getFunctionType())
930 report_fatal_error("setjmp and _setjmp have different function types");
931 } else {
932 SetjmpF = Function::Create(SetjmpF2->getFunctionType(),
933 GlobalValue::ExternalLinkage, "setjmp", M);
934 }
935 SetjmpF2->replaceAllUsesWith(SetjmpF);
936 }
937 if (LongjmpF2) {
938 if (LongjmpF) {
939 if (LongjmpF->getFunctionType() != LongjmpF2->getFunctionType())
941 "longjmp and _longjmp have different function types");
942 } else {
943 LongjmpF = Function::Create(LongjmpF2->getFunctionType(),
944 GlobalValue::ExternalLinkage, "setjmp", M);
945 }
946 LongjmpF2->replaceAllUsesWith(LongjmpF);
947 }
948
949 auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
950 assert(TPC && "Expected a TargetPassConfig");
951 auto &TM = TPC->getTM<WebAssemblyTargetMachine>();
952
953 // Declare (or get) global variables __THREW__, __threwValue, and
954 // getTempRet0/setTempRet0 function which are used in common for both
955 // exception handling and setjmp/longjmp handling
956 ThrewGV = getGlobalVariable(M, getAddrIntType(&M), TM, "__THREW__");
957 ThrewValueGV = getGlobalVariable(M, IRB.getInt32Ty(), TM, "__threwValue");
958 GetTempRet0F = getFunction(FunctionType::get(IRB.getInt32Ty(), false),
959 "getTempRet0", &M);
960 SetTempRet0F =
961 getFunction(FunctionType::get(IRB.getVoidTy(), IRB.getInt32Ty(), false),
962 "setTempRet0", &M);
963 GetTempRet0F->setDoesNotThrow();
964 SetTempRet0F->setDoesNotThrow();
965
966 bool Changed = false;
967
968 // Function registration for exception handling
969 if (EnableEmEH) {
970 // Register __resumeException function
971 FunctionType *ResumeFTy =
972 FunctionType::get(IRB.getVoidTy(), IRB.getPtrTy(), false);
973 ResumeF = getFunction(ResumeFTy, "__resumeException", &M);
974 ResumeF->addFnAttr(Attribute::NoReturn);
975
976 // Register llvm_eh_typeid_for function
977 FunctionType *EHTypeIDTy =
978 FunctionType::get(IRB.getInt32Ty(), IRB.getPtrTy(), false);
979 EHTypeIDF = getFunction(EHTypeIDTy, "llvm_eh_typeid_for", &M);
980 }
981
982 // Functions that contains calls to setjmp but don't have other longjmpable
983 // calls within them.
984 SmallPtrSet<Function *, 4> SetjmpUsersToNullify;
985
986 if ((EnableEmSjLj || EnableWasmSjLj) && SetjmpF) {
987 // Precompute setjmp users
988 for (User *U : SetjmpF->users()) {
989 if (auto *CB = dyn_cast<CallBase>(U)) {
990 auto *UserF = CB->getFunction();
991 // If a function that calls setjmp does not contain any other calls that
992 // can longjmp, we don't need to do any transformation on that function,
993 // so can ignore it
994 if (containsLongjmpableCalls(UserF))
995 SetjmpUsers.insert(UserF);
996 else
997 SetjmpUsersToNullify.insert(UserF);
998 } else {
999 std::string S;
1000 raw_string_ostream SS(S);
1001 SS << *U;
1002 report_fatal_error(Twine("Indirect use of setjmp is not supported: ") +
1003 SS.str());
1004 }
1005 }
1006 }
1007
1008 bool SetjmpUsed = SetjmpF && !SetjmpUsers.empty();
1009 bool LongjmpUsed = LongjmpF && !LongjmpF->use_empty();
1010 DoSjLj = (EnableEmSjLj | EnableWasmSjLj) && (SetjmpUsed || LongjmpUsed);
1011
1012 // Function registration and data pre-gathering for setjmp/longjmp handling
1013 if (DoSjLj) {
1014 assert(EnableEmSjLj || EnableWasmSjLj);
1015
1016 if (EnableEmSjLj) {
1017 // Register emscripten_longjmp function
1018 FunctionType *FTy = FunctionType::get(
1019 IRB.getVoidTy(), {getAddrIntType(&M), IRB.getInt32Ty()}, false);
1020 EmLongjmpF = getFunction(FTy, "emscripten_longjmp", &M);
1021 EmLongjmpF->addFnAttr(Attribute::NoReturn);
1022 } else { // EnableWasmSjLj
1023 Type *Int8PtrTy = IRB.getPtrTy();
1024 // Register __wasm_longjmp function, which calls __builtin_wasm_longjmp.
1025 FunctionType *FTy = FunctionType::get(
1026 IRB.getVoidTy(), {Int8PtrTy, IRB.getInt32Ty()}, false);
1027 WasmLongjmpF = getFunction(FTy, "__wasm_longjmp", &M);
1028 WasmLongjmpF->addFnAttr(Attribute::NoReturn);
1029 }
1030
1031 if (EnableWasmSjLj) {
1032 for (auto *SjLjF : {SetjmpF, LongjmpF}) {
1033 if (SjLjF) {
1034 for (User *U : SjLjF->users()) {
1035 if (auto *CI = dyn_cast<CallInst>(U)) {
1036 auto &F = *CI->getFunction();
1038 report_fatal_error("Function " + F.getName() +
1039 " is using setjmp/longjmp but does not have "
1040 "+exception-handling target feature");
1041 }
1042 }
1043 }
1044 }
1045 }
1046
1047 if (SetjmpF) {
1048 Type *Int8PtrTy = IRB.getPtrTy();
1049 Type *Int32PtrTy = IRB.getPtrTy();
1050 Type *Int32Ty = IRB.getInt32Ty();
1051
1052 // Register __wasm_setjmp function
1053 FunctionType *SetjmpFTy = SetjmpF->getFunctionType();
1054 FunctionType *FTy = FunctionType::get(
1055 IRB.getVoidTy(), {SetjmpFTy->getParamType(0), Int32Ty, Int32PtrTy},
1056 false);
1057 WasmSetjmpF = getFunction(FTy, "__wasm_setjmp", &M);
1058
1059 // Register __wasm_setjmp_test function
1060 FTy = FunctionType::get(Int32Ty, {Int32PtrTy, Int32PtrTy}, false);
1061 WasmSetjmpTestF = getFunction(FTy, "__wasm_setjmp_test", &M);
1062
1063 // wasm.catch() will be lowered down to wasm 'catch' instruction in
1064 // instruction selection.
1065 CatchF = Intrinsic::getOrInsertDeclaration(&M, Intrinsic::wasm_catch);
1066 // Type for struct __WasmLongjmpArgs
1067 LongjmpArgsTy = StructType::get(Int8PtrTy, // env
1068 Int32Ty // val
1069 );
1070 }
1071 }
1072
1073 // Exception handling transformation
1074 if (EnableEmEH) {
1075 for (Function &F : M) {
1076 if (F.isDeclaration())
1077 continue;
1078 Changed |= runEHOnFunction(F);
1079 }
1080 }
1081
1082 // Setjmp/longjmp handling transformation
1083 if (DoSjLj) {
1084 Changed = true; // We have setjmp or longjmp somewhere
1085 if (LongjmpF)
1086 replaceLongjmpWith(LongjmpF, EnableEmSjLj ? EmLongjmpF : WasmLongjmpF);
1087 // Only traverse functions that uses setjmp in order not to insert
1088 // unnecessary prep / cleanup code in every function
1089 if (SetjmpF)
1090 for (Function *F : SetjmpUsers)
1091 runSjLjOnFunction(*F);
1092 }
1093
1094 // Replace unnecessary setjmp calls with 0
1095 if ((EnableEmSjLj || EnableWasmSjLj) && !SetjmpUsersToNullify.empty()) {
1096 Changed = true;
1097 assert(SetjmpF);
1098 for (Function *F : SetjmpUsersToNullify)
1100 }
1101
1102 // Delete unused global variables and functions
1103 for (auto *V : {ThrewGV, ThrewValueGV})
1104 if (V && V->use_empty())
1105 V->eraseFromParent();
1106 for (auto *V : {GetTempRet0F, SetTempRet0F, ResumeF, EHTypeIDF, EmLongjmpF,
1107 WasmSetjmpF, WasmSetjmpTestF, WasmLongjmpF, CatchF})
1108 if (V && V->use_empty())
1109 V->eraseFromParent();
1110
1111 return Changed;
1112}
1113
1114bool WebAssemblyLowerEmscriptenEHSjLj::runEHOnFunction(Function &F) {
1115 Module &M = *F.getParent();
1116 LLVMContext &C = F.getContext();
1117 IRBuilder<> IRB(C);
1118 bool Changed = false;
1120 SmallPtrSet<LandingPadInst *, 32> LandingPads;
1121
1122 // rethrow.longjmp BB that will be shared within the function.
1123 BasicBlock *RethrowLongjmpBB = nullptr;
1124 // PHI node for the loaded value of __THREW__ global variable in
1125 // rethrow.longjmp BB
1126 PHINode *RethrowLongjmpBBThrewPHI = nullptr;
1127
1128 for (BasicBlock &BB : F) {
1129 auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
1130 if (!II)
1131 continue;
1132 Changed = true;
1133 LandingPads.insert(II->getLandingPadInst());
1134 IRB.SetInsertPoint(II);
1135
1136 const Value *Callee = II->getCalledOperand();
1137 bool NeedInvoke = supportsException(&F) && canThrow(Callee);
1138 if (NeedInvoke) {
1139 // Wrap invoke with invoke wrapper and generate preamble/postamble
1140 Value *Threw = wrapInvoke(II);
1141 ToErase.push_back(II);
1142
1143 // If setjmp/longjmp handling is enabled, the thrown value can be not an
1144 // exception but a longjmp. If the current function contains calls to
1145 // setjmp, it will be appropriately handled in runSjLjOnFunction. But even
1146 // if the function does not contain setjmp calls, we shouldn't silently
1147 // ignore longjmps; we should rethrow them so they can be correctly
1148 // handled in somewhere up the call chain where setjmp is. __THREW__'s
1149 // value is 0 when nothing happened, 1 when an exception is thrown, and
1150 // other values when longjmp is thrown.
1151 //
1152 // if (%__THREW__.val == 0 || %__THREW__.val == 1)
1153 // goto %tail
1154 // else
1155 // goto %longjmp.rethrow
1156 //
1157 // rethrow.longjmp: ;; This is longjmp. Rethrow it
1158 // %__threwValue.val = __threwValue
1159 // emscripten_longjmp(%__THREW__.val, %__threwValue.val);
1160 //
1161 // tail: ;; Nothing happened or an exception is thrown
1162 // ... Continue exception handling ...
1163 if (DoSjLj && EnableEmSjLj && !SetjmpUsers.count(&F) &&
1164 canLongjmp(Callee)) {
1165 // Create longjmp.rethrow BB once and share it within the function
1166 if (!RethrowLongjmpBB) {
1167 RethrowLongjmpBB = BasicBlock::Create(C, "rethrow.longjmp", &F);
1168 IRB.SetInsertPoint(RethrowLongjmpBB);
1169 RethrowLongjmpBBThrewPHI =
1170 IRB.CreatePHI(getAddrIntType(&M), 4, "threw.phi");
1171 RethrowLongjmpBBThrewPHI->addIncoming(Threw, &BB);
1172 Value *ThrewValue = IRB.CreateLoad(IRB.getInt32Ty(), ThrewValueGV,
1173 ThrewValueGV->getName() + ".val");
1174 IRB.CreateCall(EmLongjmpF, {RethrowLongjmpBBThrewPHI, ThrewValue});
1175 IRB.CreateUnreachable();
1176 } else {
1177 RethrowLongjmpBBThrewPHI->addIncoming(Threw, &BB);
1178 }
1179
1180 IRB.SetInsertPoint(II); // Restore the insert point back
1181 BasicBlock *Tail = BasicBlock::Create(C, "tail", &F);
1182 Value *CmpEqOne =
1183 IRB.CreateICmpEQ(Threw, getAddrSizeInt(&M, 1), "cmp.eq.one");
1184 Value *CmpEqZero =
1185 IRB.CreateICmpEQ(Threw, getAddrSizeInt(&M, 0), "cmp.eq.zero");
1186 Value *Or = IRB.CreateOr(CmpEqZero, CmpEqOne, "or");
1187 IRB.CreateCondBr(Or, Tail, RethrowLongjmpBB);
1188 IRB.SetInsertPoint(Tail);
1189 BB.replaceSuccessorsPhiUsesWith(&BB, Tail);
1190 }
1191
1192 // Insert a branch based on __THREW__ variable
1193 Value *Cmp = IRB.CreateICmpEQ(Threw, getAddrSizeInt(&M, 1), "cmp");
1194 IRB.CreateCondBr(Cmp, II->getUnwindDest(), II->getNormalDest());
1195
1196 } else {
1197 // This can't throw, and we don't need this invoke, just replace it with a
1198 // call+branch
1200 }
1201 }
1202
1203 // Process resume instructions
1204 for (BasicBlock &BB : F) {
1205 // Scan the body of the basic block for resumes
1206 for (Instruction &I : BB) {
1207 auto *RI = dyn_cast<ResumeInst>(&I);
1208 if (!RI)
1209 continue;
1210 Changed = true;
1211
1212 // Split the input into legal values
1213 Value *Input = RI->getValue();
1214 IRB.SetInsertPoint(RI);
1215 Value *Low = IRB.CreateExtractValue(Input, 0, "low");
1216 // Create a call to __resumeException function
1217 IRB.CreateCall(ResumeF, {Low});
1218 // Add a terminator to the block
1219 IRB.CreateUnreachable();
1220 ToErase.push_back(RI);
1221 }
1222 }
1223
1224 // Process llvm.eh.typeid.for intrinsics
1225 for (BasicBlock &BB : F) {
1226 for (Instruction &I : BB) {
1227 auto *CI = dyn_cast<CallInst>(&I);
1228 if (!CI)
1229 continue;
1230 const Function *Callee = CI->getCalledFunction();
1231 if (!Callee)
1232 continue;
1233 if (Callee->getIntrinsicID() != Intrinsic::eh_typeid_for)
1234 continue;
1235 Changed = true;
1236
1237 IRB.SetInsertPoint(CI);
1238 CallInst *NewCI =
1239 IRB.CreateCall(EHTypeIDF, CI->getArgOperand(0), "typeid");
1240 CI->replaceAllUsesWith(NewCI);
1241 ToErase.push_back(CI);
1242 }
1243 }
1244
1245 // Look for orphan landingpads, can occur in blocks with no predecessors
1246 for (BasicBlock &BB : F) {
1247 BasicBlock::iterator I = BB.getFirstNonPHIIt();
1248 if (auto *LPI = dyn_cast<LandingPadInst>(I))
1249 LandingPads.insert(LPI);
1250 }
1251 Changed |= !LandingPads.empty();
1252
1253 // Handle all the landingpad for this function together, as multiple invokes
1254 // may share a single lp
1255 for (LandingPadInst *LPI : LandingPads) {
1256 IRB.SetInsertPoint(LPI);
1257 SmallVector<Value *, 16> FMCArgs;
1258 for (unsigned I = 0, E = LPI->getNumClauses(); I < E; ++I) {
1259 Constant *Clause = LPI->getClause(I);
1260 // TODO Handle filters (= exception specifications).
1261 // https://github.com/llvm/llvm-project/issues/49740
1262 if (LPI->isCatch(I))
1263 FMCArgs.push_back(Clause);
1264 }
1265
1266 // Create a call to __cxa_find_matching_catch_N function
1267 Function *FMCF = getFindMatchingCatch(M, FMCArgs.size());
1268 CallInst *FMCI = IRB.CreateCall(FMCF, FMCArgs, "fmc");
1269 Value *Poison = PoisonValue::get(LPI->getType());
1270 Value *Pair0 = IRB.CreateInsertValue(Poison, FMCI, 0, "pair0");
1271 Value *TempRet0 = IRB.CreateCall(GetTempRet0F, {}, "tempret0");
1272 Value *Pair1 = IRB.CreateInsertValue(Pair0, TempRet0, 1, "pair1");
1273
1274 LPI->replaceAllUsesWith(Pair1);
1275 ToErase.push_back(LPI);
1276 }
1277
1278 // Erase everything we no longer need in this function
1279 for (Instruction *I : ToErase)
1280 I->eraseFromParent();
1281
1282 return Changed;
1283}
1284
1285// This tries to get debug info from the instruction before which a new
1286// instruction will be inserted, and if there's no debug info in that
1287// instruction, tries to get the info instead from the previous instruction (if
1288// any). If none of these has debug info and a DISubprogram is provided, it
1289// creates a dummy debug info with the first line of the function, because IR
1290// verifier requires all inlinable callsites should have debug info when both a
1291// caller and callee have DISubprogram. If none of these conditions are met,
1292// returns empty info.
1293static DebugLoc getOrCreateDebugLoc(const Instruction *InsertBefore,
1294 DISubprogram *SP) {
1295 assert(InsertBefore);
1296 if (InsertBefore->getDebugLoc())
1297 return InsertBefore->getDebugLoc();
1298 const Instruction *Prev = InsertBefore->getPrevNode();
1299 if (Prev && Prev->getDebugLoc())
1300 return Prev->getDebugLoc();
1301 if (SP)
1302 return DILocation::get(SP->getContext(), SP->getLine(), 1, SP);
1303 return DebugLoc();
1304}
1305
1306bool WebAssemblyLowerEmscriptenEHSjLj::runSjLjOnFunction(Function &F) {
1307 assert(EnableEmSjLj || EnableWasmSjLj);
1308 Module &M = *F.getParent();
1309 LLVMContext &C = F.getContext();
1310 IRBuilder<> IRB(C);
1312
1313 // Setjmp preparation
1314
1315 SmallVector<AllocaInst *> StaticAllocas;
1316 for (Instruction &I : F.getEntryBlock())
1317 if (auto *AI = dyn_cast<AllocaInst>(&I))
1318 if (AI->isStaticAlloca())
1319 StaticAllocas.push_back(AI);
1320
1321 BasicBlock *Entry = &F.getEntryBlock();
1322 DebugLoc FirstDL = getOrCreateDebugLoc(&*Entry->begin(), F.getSubprogram());
1323 SplitBlock(Entry, &*Entry->getFirstInsertionPt());
1324
1325 // Move static allocas back into the entry block, so they stay static.
1326 for (AllocaInst *AI : StaticAllocas)
1327 AI->moveBefore(Entry->getTerminator()->getIterator());
1328
1329 IRB.SetInsertPoint(Entry->getTerminator()->getIterator());
1330 // This alloca'ed pointer is used by the runtime to identify function
1331 // invocations. It's just for pointer comparisons. It will never be
1332 // dereferenced.
1333 Instruction *FunctionInvocationId =
1334 IRB.CreateAlloca(IRB.getInt32Ty(), nullptr, "functionInvocationId");
1335 FunctionInvocationId->setDebugLoc(FirstDL);
1336
1337 // Setjmp transformation
1338 SmallVector<PHINode *, 4> SetjmpRetPHIs;
1339 Function *SetjmpF = M.getFunction("setjmp");
1340 for (auto *U : make_early_inc_range(SetjmpF->users())) {
1341 auto *CB = cast<CallBase>(U);
1342 BasicBlock *BB = CB->getParent();
1343 if (BB->getParent() != &F) // in other function
1344 continue;
1345 if (CB->getOperandBundle(LLVMContext::OB_funclet)) {
1346 std::string S;
1347 raw_string_ostream SS(S);
1348 SS << "In function " + F.getName() +
1349 ": setjmp within a catch clause is not supported in Wasm EH:\n";
1350 SS << *CB;
1351 report_fatal_error(StringRef(SS.str()));
1352 }
1353
1354 CallInst *CI = nullptr;
1355 // setjmp cannot throw. So if it is an invoke, lower it to a call
1356 if (auto *II = dyn_cast<InvokeInst>(CB))
1357 CI = llvm::changeToCall(II);
1358 else
1359 CI = cast<CallInst>(CB);
1360
1361 // The tail is everything right after the call, and will be reached once
1362 // when setjmp is called, and later when longjmp returns to the setjmp
1363 BasicBlock *Tail = SplitBlock(BB, CI->getNextNode());
1364 // Add a phi to the tail, which will be the output of setjmp, which
1365 // indicates if this is the first call or a longjmp back. The phi directly
1366 // uses the right value based on where we arrive from
1367 IRB.SetInsertPoint(Tail, Tail->getFirstNonPHIIt());
1368 PHINode *SetjmpRet = IRB.CreatePHI(IRB.getInt32Ty(), 2, "setjmp.ret");
1369
1370 // setjmp initial call returns 0
1371 SetjmpRet->addIncoming(IRB.getInt32(0), BB);
1372 // The proper output is now this, not the setjmp call itself
1373 CI->replaceAllUsesWith(SetjmpRet);
1374 // longjmp returns to the setjmp will add themselves to this phi
1375 SetjmpRetPHIs.push_back(SetjmpRet);
1376
1377 // Fix call target
1378 // Our index in the function is our place in the array + 1 to avoid index
1379 // 0, because index 0 means the longjmp is not ours to handle.
1380 IRB.SetInsertPoint(CI);
1381 Value *Args[] = {CI->getArgOperand(0), IRB.getInt32(SetjmpRetPHIs.size()),
1382 FunctionInvocationId};
1383 IRB.CreateCall(WasmSetjmpF, Args);
1384 ToErase.push_back(CI);
1385 }
1386
1387 // Handle longjmpable calls.
1388 if (EnableEmSjLj)
1389 handleLongjmpableCallsForEmscriptenSjLj(F, FunctionInvocationId,
1390 SetjmpRetPHIs);
1391 else // EnableWasmSjLj
1392 handleLongjmpableCallsForWasmSjLj(F, FunctionInvocationId, SetjmpRetPHIs);
1393
1394 // Erase everything we no longer need in this function
1395 for (Instruction *I : ToErase)
1396 I->eraseFromParent();
1397
1398 // Finally, our modifications to the cfg can break dominance of SSA variables.
1399 // For example, in this code,
1400 // if (x()) { .. setjmp() .. }
1401 // if (y()) { .. longjmp() .. }
1402 // We must split the longjmp block, and it can jump into the block splitted
1403 // from setjmp one. But that means that when we split the setjmp block, it's
1404 // first part no longer dominates its second part - there is a theoretically
1405 // possible control flow path where x() is false, then y() is true and we
1406 // reach the second part of the setjmp block, without ever reaching the first
1407 // part. So, we rebuild SSA form here.
1408 rebuildSSA(F);
1409 return true;
1410}
1411
1412// Update each call that can longjmp so it can return to the corresponding
1413// setjmp. Refer to 4) of "Emscripten setjmp/longjmp handling" section in the
1414// comments at top of the file for details.
1415void WebAssemblyLowerEmscriptenEHSjLj::handleLongjmpableCallsForEmscriptenSjLj(
1416 Function &F, Instruction *FunctionInvocationId,
1417 SmallVectorImpl<PHINode *> &SetjmpRetPHIs) {
1418 Module &M = *F.getParent();
1419 LLVMContext &C = F.getContext();
1420 IRBuilder<> IRB(C);
1422
1423 // call.em.longjmp BB that will be shared within the function.
1424 BasicBlock *CallEmLongjmpBB = nullptr;
1425 // PHI node for the loaded value of __THREW__ global variable in
1426 // call.em.longjmp BB
1427 PHINode *CallEmLongjmpBBThrewPHI = nullptr;
1428 // PHI node for the loaded value of __threwValue global variable in
1429 // call.em.longjmp BB
1430 PHINode *CallEmLongjmpBBThrewValuePHI = nullptr;
1431 // rethrow.exn BB that will be shared within the function.
1432 BasicBlock *RethrowExnBB = nullptr;
1433
1434 // Because we are creating new BBs while processing and don't want to make
1435 // all these newly created BBs candidates again for longjmp processing, we
1436 // first make the vector of candidate BBs.
1437 std::vector<BasicBlock *> BBs;
1438 for (BasicBlock &BB : F)
1439 BBs.push_back(&BB);
1440
1441 // BBs.size() will change within the loop, so we query it every time
1442 for (unsigned I = 0; I < BBs.size(); I++) {
1443 BasicBlock *BB = BBs[I];
1444 for (Instruction &I : *BB) {
1445 if (isa<InvokeInst>(&I)) {
1446 std::string S;
1447 raw_string_ostream SS(S);
1448 SS << "In function " << F.getName()
1449 << ": When using Wasm EH with Emscripten SjLj, there is a "
1450 "restriction that `setjmp` function call and exception cannot be "
1451 "used within the same function:\n";
1452 SS << I;
1453 report_fatal_error(StringRef(SS.str()));
1454 }
1455 auto *CI = dyn_cast<CallInst>(&I);
1456 if (!CI)
1457 continue;
1458
1459 const Value *Callee = CI->getCalledOperand();
1460 if (!canLongjmp(Callee))
1461 continue;
1462 if (isEmAsmCall(Callee))
1463 report_fatal_error("Cannot use EM_ASM* alongside setjmp/longjmp in " +
1464 F.getName() +
1465 ". Please consider using EM_JS, or move the "
1466 "EM_ASM into another function.",
1467 false);
1468
1469 Value *Threw = nullptr;
1471 if (Callee->getName().starts_with("__invoke_")) {
1472 // If invoke wrapper has already been generated for this call in
1473 // previous EH phase, search for the load instruction
1474 // %__THREW__.val = __THREW__;
1475 // in postamble after the invoke wrapper call
1476 LoadInst *ThrewLI = nullptr;
1477 StoreInst *ThrewResetSI = nullptr;
1478 for (auto I = std::next(BasicBlock::iterator(CI)), IE = BB->end();
1479 I != IE; ++I) {
1480 if (auto *LI = dyn_cast<LoadInst>(I))
1481 if (auto *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand()))
1482 if (GV == ThrewGV) {
1483 Threw = ThrewLI = LI;
1484 break;
1485 }
1486 }
1487 // Search for the store instruction after the load above
1488 // __THREW__ = 0;
1489 for (auto I = std::next(BasicBlock::iterator(ThrewLI)), IE = BB->end();
1490 I != IE; ++I) {
1491 if (auto *SI = dyn_cast<StoreInst>(I)) {
1492 if (auto *GV = dyn_cast<GlobalVariable>(SI->getPointerOperand())) {
1493 if (GV == ThrewGV &&
1494 SI->getValueOperand() == getAddrSizeInt(&M, 0)) {
1495 ThrewResetSI = SI;
1496 break;
1497 }
1498 }
1499 }
1500 }
1501 assert(Threw && ThrewLI && "Cannot find __THREW__ load after invoke");
1502 assert(ThrewResetSI && "Cannot find __THREW__ store after invoke");
1503 Tail = SplitBlock(BB, ThrewResetSI->getNextNode());
1504
1505 } else {
1506 // Wrap call with invoke wrapper and generate preamble/postamble
1507 Threw = wrapInvoke(CI);
1508 ToErase.push_back(CI);
1509 Tail = SplitBlock(BB, CI->getNextNode());
1510
1511 // If exception handling is enabled, the thrown value can be not a
1512 // longjmp but an exception, in which case we shouldn't silently ignore
1513 // exceptions; we should rethrow them.
1514 // __THREW__'s value is 0 when nothing happened, 1 when an exception is
1515 // thrown, other values when longjmp is thrown.
1516 //
1517 // if (%__THREW__.val == 1)
1518 // goto %eh.rethrow
1519 // else
1520 // goto %normal
1521 //
1522 // eh.rethrow: ;; Rethrow exception
1523 // %exn = call @__cxa_find_matching_catch_2() ;; Retrieve thrown ptr
1524 // __resumeException(%exn)
1525 //
1526 // normal:
1527 // <-- Insertion point. Will insert sjlj handling code from here
1528 // goto %tail
1529 //
1530 // tail:
1531 // ...
1532 if (supportsException(&F) && canThrow(Callee)) {
1533 // We will add a new conditional branch. So remove the branch created
1534 // when we split the BB
1535 ToErase.push_back(BB->getTerminator());
1536
1537 // Generate rethrow.exn BB once and share it within the function
1538 if (!RethrowExnBB) {
1539 RethrowExnBB = BasicBlock::Create(C, "rethrow.exn", &F);
1540 IRB.SetInsertPoint(RethrowExnBB);
1541 CallInst *Exn =
1542 IRB.CreateCall(getFindMatchingCatch(M, 0), {}, "exn");
1543 IRB.CreateCall(ResumeF, {Exn});
1544 IRB.CreateUnreachable();
1545 }
1546
1547 IRB.SetInsertPoint(CI);
1548 BasicBlock *NormalBB = BasicBlock::Create(C, "normal", &F);
1549 Value *CmpEqOne =
1550 IRB.CreateICmpEQ(Threw, getAddrSizeInt(&M, 1), "cmp.eq.one");
1551 IRB.CreateCondBr(CmpEqOne, RethrowExnBB, NormalBB);
1552
1553 IRB.SetInsertPoint(NormalBB);
1554 IRB.CreateBr(Tail);
1555 BB = NormalBB; // New insertion point to insert __wasm_setjmp_test()
1556 }
1557 }
1558
1559 // We need to replace the terminator in Tail - SplitBlock makes BB go
1560 // straight to Tail, we need to check if a longjmp occurred, and go to the
1561 // right setjmp-tail if so
1562 ToErase.push_back(BB->getTerminator());
1563
1564 // Generate a function call to __wasm_setjmp_test function and
1565 // preamble/postamble code to figure out (1) whether longjmp
1566 // occurred (2) if longjmp occurred, which setjmp it corresponds to
1567 Value *Label = nullptr;
1568 Value *LongjmpResult = nullptr;
1569 BasicBlock *EndBB = nullptr;
1570 wrapTestSetjmp(BB, CI->getDebugLoc(), Threw, FunctionInvocationId, Label,
1571 LongjmpResult, CallEmLongjmpBB, CallEmLongjmpBBThrewPHI,
1572 CallEmLongjmpBBThrewValuePHI, EndBB);
1573 assert(Label && LongjmpResult && EndBB);
1574
1575 // Create switch instruction
1576 IRB.SetInsertPoint(EndBB);
1577 IRB.SetCurrentDebugLocation(EndBB->back().getDebugLoc());
1578 SwitchInst *SI = IRB.CreateSwitch(Label, Tail, SetjmpRetPHIs.size());
1579 // -1 means no longjmp happened, continue normally (will hit the default
1580 // switch case). 0 means a longjmp that is not ours to handle, needs a
1581 // rethrow. Otherwise the index is the same as the index in P+1 (to avoid
1582 // 0).
1583 for (unsigned I = 0; I < SetjmpRetPHIs.size(); I++) {
1584 SI->addCase(IRB.getInt32(I + 1), SetjmpRetPHIs[I]->getParent());
1585 SetjmpRetPHIs[I]->addIncoming(LongjmpResult, EndBB);
1586 }
1587
1588 // We are splitting the block here, and must continue to find other calls
1589 // in the block - which is now split. so continue to traverse in the Tail
1590 BBs.push_back(Tail);
1591 }
1592 }
1593
1594 for (Instruction *I : ToErase)
1595 I->eraseFromParent();
1596}
1597
1599 for (const User *U : CPI->users())
1600 if (const auto *CRI = dyn_cast<CleanupReturnInst>(U))
1601 return CRI->getUnwindDest();
1602 return nullptr;
1603}
1604
1605// Create a catchpad in which we catch a longjmp's env and val arguments, test
1606// if the longjmp corresponds to one of setjmps in the current function, and if
1607// so, jump to the setjmp dispatch BB from which we go to one of post-setjmp
1608// BBs. Refer to 4) of "Wasm setjmp/longjmp handling" section in the comments at
1609// top of the file for details.
1610void WebAssemblyLowerEmscriptenEHSjLj::handleLongjmpableCallsForWasmSjLj(
1611 Function &F, Instruction *FunctionInvocationId,
1612 SmallVectorImpl<PHINode *> &SetjmpRetPHIs) {
1613 Module &M = *F.getParent();
1614 LLVMContext &C = F.getContext();
1615 IRBuilder<> IRB(C);
1616
1617 // A function with catchswitch/catchpad instruction should have a personality
1618 // function attached to it. Search for the wasm personality function, and if
1619 // it exists, use it, and if it doesn't, create a dummy personality function.
1620 // (SjLj is not going to call it anyway.)
1621 if (!F.hasPersonalityFn()) {
1622 StringRef PersName = getEHPersonalityName(EHPersonality::Wasm_CXX);
1623 FunctionType *PersType =
1624 FunctionType::get(IRB.getInt32Ty(), /* isVarArg */ true);
1625 Value *PersF = M.getOrInsertFunction(PersName, PersType).getCallee();
1626 F.setPersonalityFn(
1627 cast<Constant>(IRB.CreateBitCast(PersF, IRB.getPtrTy())));
1628 }
1629
1630 // Use the entry BB's debugloc as a fallback
1631 BasicBlock *Entry = &F.getEntryBlock();
1632 DebugLoc FirstDL = getOrCreateDebugLoc(&*Entry->begin(), F.getSubprogram());
1633 IRB.SetCurrentDebugLocation(FirstDL);
1634
1635 // Add setjmp.dispatch BB right after the entry block. Because we have
1636 // initialized functionInvocationId in the entry block and split the
1637 // rest into another BB, here 'OrigEntry' is the function's original entry
1638 // block before the transformation.
1639 //
1640 // entry:
1641 // functionInvocationId initialization
1642 // setjmp.dispatch:
1643 // switch will be inserted here later
1644 // entry.split: (OrigEntry)
1645 // the original function starts here
1646 BasicBlock *OrigEntry = Entry->getNextNode();
1647 BasicBlock *SetjmpDispatchBB =
1648 BasicBlock::Create(C, "setjmp.dispatch", &F, OrigEntry);
1649 cast<BranchInst>(Entry->getTerminator())->setSuccessor(0, SetjmpDispatchBB);
1650
1651 // Create catch.dispatch.longjmp BB and a catchswitch instruction
1652 BasicBlock *CatchDispatchLongjmpBB =
1653 BasicBlock::Create(C, "catch.dispatch.longjmp", &F);
1654 IRB.SetInsertPoint(CatchDispatchLongjmpBB);
1655 CatchSwitchInst *CatchSwitchLongjmp =
1656 IRB.CreateCatchSwitch(ConstantTokenNone::get(C), nullptr, 1);
1657
1658 // Create catch.longjmp BB and a catchpad instruction
1659 BasicBlock *CatchLongjmpBB = BasicBlock::Create(C, "catch.longjmp", &F);
1660 CatchSwitchLongjmp->addHandler(CatchLongjmpBB);
1661 IRB.SetInsertPoint(CatchLongjmpBB);
1662 CatchPadInst *CatchPad = IRB.CreateCatchPad(CatchSwitchLongjmp, {});
1663
1664 // Wasm throw and catch instructions can throw and catch multiple values, but
1665 // that requires multivalue support in the toolchain, which is currently not
1666 // very reliable. We instead throw and catch a pointer to a struct value of
1667 // type 'struct __WasmLongjmpArgs', which is defined in Emscripten.
1668 Instruction *LongjmpArgs =
1669 IRB.CreateCall(CatchF, {IRB.getInt32(WebAssembly::C_LONGJMP)}, "thrown");
1670 Value *EnvField =
1671 IRB.CreateConstGEP2_32(LongjmpArgsTy, LongjmpArgs, 0, 0, "env_gep");
1672 Value *ValField =
1673 IRB.CreateConstGEP2_32(LongjmpArgsTy, LongjmpArgs, 0, 1, "val_gep");
1674 // void *env = __wasm_longjmp_args.env;
1675 Instruction *Env = IRB.CreateLoad(IRB.getPtrTy(), EnvField, "env");
1676 // int val = __wasm_longjmp_args.val;
1677 Instruction *Val = IRB.CreateLoad(IRB.getInt32Ty(), ValField, "val");
1678
1679 // %label = __wasm_setjmp_test(%env, functionInvocatinoId);
1680 // if (%label == 0)
1681 // __wasm_longjmp(%env, %val)
1682 // catchret to %setjmp.dispatch
1683 BasicBlock *ThenBB = BasicBlock::Create(C, "if.then", &F);
1684 BasicBlock *EndBB = BasicBlock::Create(C, "if.end", &F);
1685 Value *EnvP = IRB.CreateBitCast(Env, getAddrPtrType(&M), "env.p");
1686 Value *Label = IRB.CreateCall(WasmSetjmpTestF, {EnvP, FunctionInvocationId},
1687 OperandBundleDef("funclet", CatchPad), "label");
1688 Value *Cmp = IRB.CreateICmpEQ(Label, IRB.getInt32(0));
1689 IRB.CreateCondBr(Cmp, ThenBB, EndBB);
1690
1691 IRB.SetInsertPoint(ThenBB);
1692 CallInst *WasmLongjmpCI = IRB.CreateCall(
1693 WasmLongjmpF, {Env, Val}, OperandBundleDef("funclet", CatchPad));
1694 IRB.CreateUnreachable();
1695
1696 IRB.SetInsertPoint(EndBB);
1697 // Jump to setjmp.dispatch block
1698 IRB.CreateCatchRet(CatchPad, SetjmpDispatchBB);
1699
1700 // Go back to setjmp.dispatch BB
1701 // setjmp.dispatch:
1702 // switch %label {
1703 // label 1: goto post-setjmp BB 1
1704 // label 2: goto post-setjmp BB 2
1705 // ...
1706 // default: goto splitted next BB
1707 // }
1708 IRB.SetInsertPoint(SetjmpDispatchBB);
1709 PHINode *LabelPHI = IRB.CreatePHI(IRB.getInt32Ty(), 2, "label.phi");
1710 LabelPHI->addIncoming(Label, EndBB);
1711 LabelPHI->addIncoming(IRB.getInt32(-1), Entry);
1712 SwitchInst *SI = IRB.CreateSwitch(LabelPHI, OrigEntry, SetjmpRetPHIs.size());
1713 // -1 means no longjmp happened, continue normally (will hit the default
1714 // switch case). 0 means a longjmp that is not ours to handle, needs a
1715 // rethrow. Otherwise the index is the same as the index in P+1 (to avoid
1716 // 0).
1717 for (unsigned I = 0; I < SetjmpRetPHIs.size(); I++) {
1718 SI->addCase(IRB.getInt32(I + 1), SetjmpRetPHIs[I]->getParent());
1719 SetjmpRetPHIs[I]->addIncoming(Val, SetjmpDispatchBB);
1720 }
1721
1722 // Convert all longjmpable call instructions to invokes that unwind to the
1723 // newly created catch.dispatch.longjmp BB.
1724 SmallVector<CallInst *, 64> LongjmpableCalls;
1725 for (auto *BB = &*F.begin(); BB; BB = BB->getNextNode()) {
1726 for (auto &I : *BB) {
1727 auto *CI = dyn_cast<CallInst>(&I);
1728 if (!CI)
1729 continue;
1730 const Value *Callee = CI->getCalledOperand();
1731 if (!canLongjmp(Callee))
1732 continue;
1733 if (isEmAsmCall(Callee))
1734 report_fatal_error("Cannot use EM_ASM* alongside setjmp/longjmp in " +
1735 F.getName() +
1736 ". Please consider using EM_JS, or move the "
1737 "EM_ASM into another function.",
1738 false);
1739 // This is __wasm_longjmp() call we inserted in this function, which
1740 // rethrows the longjmp when the longjmp does not correspond to one of
1741 // setjmps in this function. We should not convert this call to an invoke.
1742 if (CI == WasmLongjmpCI)
1743 continue;
1744 LongjmpableCalls.push_back(CI);
1745 }
1746 }
1747
1748 SmallDenseMap<BasicBlock *, SmallSetVector<BasicBlock *, 4>, 4>
1749 UnwindDestToNewPreds;
1750 for (auto *CI : LongjmpableCalls) {
1751 // Even if the callee function has attribute 'nounwind', which is true for
1752 // all C functions, it can longjmp, which means it can throw a Wasm
1753 // exception now.
1754 CI->removeFnAttr(Attribute::NoUnwind);
1755 if (Function *CalleeF = CI->getCalledFunction())
1756 CalleeF->removeFnAttr(Attribute::NoUnwind);
1757
1758 // Change it to an invoke and make it unwind to the catch.dispatch.longjmp
1759 // BB. If the call is enclosed in another catchpad/cleanuppad scope, unwind
1760 // to its parent pad's unwind destination instead to preserve the scope
1761 // structure. It will eventually unwind to the catch.dispatch.longjmp.
1762 BasicBlock *UnwindDest = nullptr;
1763 if (auto Bundle = CI->getOperandBundle(LLVMContext::OB_funclet)) {
1764 Instruction *FromPad = cast<Instruction>(Bundle->Inputs[0]);
1765 while (!UnwindDest) {
1766 if (auto *CPI = dyn_cast<CatchPadInst>(FromPad)) {
1767 UnwindDest = CPI->getCatchSwitch()->getUnwindDest();
1768 break;
1769 }
1770 if (auto *CPI = dyn_cast<CleanupPadInst>(FromPad)) {
1771 // getCleanupRetUnwindDest() can return nullptr when
1772 // 1. This cleanuppad's matching cleanupret uwninds to caller
1773 // 2. There is no matching cleanupret because it ends with
1774 // unreachable.
1775 // In case of 2, we need to traverse the parent pad chain.
1776 UnwindDest = getCleanupRetUnwindDest(CPI);
1777 Value *ParentPad = CPI->getParentPad();
1778 if (isa<ConstantTokenNone>(ParentPad))
1779 break;
1780 FromPad = cast<Instruction>(ParentPad);
1781 }
1782 }
1783 }
1784 if (!UnwindDest)
1785 UnwindDest = CatchDispatchLongjmpBB;
1786 // Because we are changing a longjmpable call to an invoke, its unwind
1787 // destination can be an existing EH pad that already have phis, and the BB
1788 // with the newly created invoke will become a new predecessor of that EH
1789 // pad. In this case we need to add the new predecessor to those phis.
1790 UnwindDestToNewPreds[UnwindDest].insert(CI->getParent());
1791 changeToInvokeAndSplitBasicBlock(CI, UnwindDest);
1792 }
1793
1794 SmallVector<Instruction *, 16> ToErase;
1795 for (auto &BB : F) {
1796 if (auto *CSI = dyn_cast<CatchSwitchInst>(BB.getFirstNonPHIIt())) {
1797 if (CSI != CatchSwitchLongjmp && CSI->unwindsToCaller()) {
1798 IRB.SetInsertPoint(CSI);
1799 ToErase.push_back(CSI);
1800 auto *NewCSI = IRB.CreateCatchSwitch(CSI->getParentPad(),
1801 CatchDispatchLongjmpBB, 1);
1802 NewCSI->addHandler(*CSI->handler_begin());
1803 NewCSI->takeName(CSI);
1804 CSI->replaceAllUsesWith(NewCSI);
1805 }
1806 }
1807
1808 if (auto *CRI = dyn_cast<CleanupReturnInst>(BB.getTerminator())) {
1809 if (CRI->unwindsToCaller()) {
1810 IRB.SetInsertPoint(CRI);
1811 ToErase.push_back(CRI);
1812 IRB.CreateCleanupRet(CRI->getCleanupPad(), CatchDispatchLongjmpBB);
1813 }
1814 }
1815 }
1816
1817 for (Instruction *I : ToErase)
1818 I->eraseFromParent();
1819
1820 // Add entries for new predecessors to phis in unwind destinations. We use
1821 // 'poison' as a placeholder value. We should make sure the phis have a valid
1822 // set of predecessors before running SSAUpdater, because SSAUpdater
1823 // internally can use existing phis to gather predecessor info rather than
1824 // scanning the actual CFG (See FindPredecessorBlocks in SSAUpdater.cpp for
1825 // details).
1826 for (auto &[UnwindDest, NewPreds] : UnwindDestToNewPreds) {
1827 for (PHINode &PN : UnwindDest->phis()) {
1828 for (auto *NewPred : NewPreds) {
1829 assert(PN.getBasicBlockIndex(NewPred) == -1);
1830 PN.addIncoming(PoisonValue::get(PN.getType()), NewPred);
1831 }
1832 }
1833 }
1834
1835 // For unwind destinations for newly added invokes to longjmpable functions,
1836 // calculate incoming values for the newly added predecessors using
1837 // SSAUpdater. We add existing values in the phis to SSAUpdater as available
1838 // values and let it calculate what the value should be at the end of new
1839 // incoming blocks.
1840 for (auto &[UnwindDest, NewPreds] : UnwindDestToNewPreds) {
1841 for (PHINode &PN : UnwindDest->phis()) {
1842 SSAUpdater SSA;
1843 SSA.Initialize(PN.getType(), PN.getName());
1844 for (unsigned Idx = 0, E = PN.getNumIncomingValues(); Idx != E; ++Idx) {
1845 if (NewPreds.contains(PN.getIncomingBlock(Idx)))
1846 continue;
1847 Value *V = PN.getIncomingValue(Idx);
1848 if (auto *II = dyn_cast<InvokeInst>(V))
1849 SSA.AddAvailableValue(II->getNormalDest(), II);
1850 else if (auto *I = dyn_cast<Instruction>(V))
1851 SSA.AddAvailableValue(I->getParent(), I);
1852 else
1853 SSA.AddAvailableValue(PN.getIncomingBlock(Idx), V);
1854 }
1855 for (auto *NewPred : NewPreds)
1856 PN.setIncomingValueForBlock(NewPred, SSA.GetValueAtEndOfBlock(NewPred));
1857 assert(PN.isComplete());
1858 }
1859 }
1860}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define DEBUG_TYPE
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
Memory SSA
Definition MemorySSA.cpp:72
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:114
Target-Independent Code Generator Pass Configuration Options pass.
static void nullifySetjmp(Function *F)
static void markAsImported(Function *F)
static bool canLongjmp(const Value *Callee)
static cl::list< std::string > EHAllowlist("emscripten-cxx-exceptions-allowed", cl::desc("The list of function names in which Emscripten-style " "exception handling is enabled (see emscripten " "EMSCRIPTEN_CATCHING_ALLOWED options)"), cl::CommaSeparated)
static bool hasEHTargetFeatureAttr(const Function &F)
static Type * getAddrPtrType(Module *M)
static std::string getSignature(FunctionType *FTy)
static Type * getAddrIntType(Module *M)
static bool canThrow(const Value *V)
static Function * getFunction(FunctionType *Ty, const Twine &Name, Module *M)
static DebugLoc getOrCreateDebugLoc(const Instruction *InsertBefore, DISubprogram *SP)
static bool containsLongjmpableCalls(const Function *F)
static Value * getAddrSizeInt(Module *M, uint64_t C)
static GlobalVariable * getGlobalVariable(Module &M, Type *Ty, WebAssemblyTargetMachine &TM, const char *Name)
static bool isEmAsmCall(const Value *Callee)
This file declares the WebAssembly-specific subclass of TargetMachine.
This file contains the entry points for global functions defined in the LLVM WebAssembly back-end.
static BasicBlock * getCleanupRetUnwindDest(const CleanupPadInst *CleanupPad)
AnalysisUsage & addRequired()
static LLVM_ABI AttributeSet get(LLVMContext &C, const AttrBuilder &B)
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:105
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:261
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:539
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
const Instruction & back() const
Definition BasicBlock.h:495
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
void setCallingConv(CallingConv::ID CC)
std::optional< OperandBundleUse > getOperandBundle(StringRef Name) const
Return an operand bundle by name, if present.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
Value * getCalledOperand() const
void setAttributes(AttributeList A)
Set the attributes for this call.
Value * getArgOperand(unsigned i) const
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
FunctionType * getFunctionType() const
void removeFnAttr(Attribute::AttrKind Kind)
Removes the attribute from the function.
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
This class represents a function call, abstracting a target machine's calling convention.
LLVM_ABI void addHandler(BasicBlock *Dest)
Add an entry to the switch instruction... Note: This action invalidates handler_end().
static LLVM_ABI ConstantTokenNone * get(LLVMContext &Context)
Return the ConstantTokenNone.
Subprogram description. Uses SubclassData1.
A debug info location.
Definition DebugLoc.h:123
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:256
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:241
void recalculate(ParentType &Func)
recalculate - compute a dominator tree for the given function
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
Definition Function.cpp:639
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:168
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:211
const Function & getFunction() const
Definition Function.h:166
void setDoesNotThrow()
Definition Function.h:605
Module * getParent()
Get the module that this global value is contained inside of...
PointerType * getType() const
Global values are always pointers.
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
IntegerType * getIntNTy(unsigned N)
Fetch the type representing an N-bit integer.
Definition IRBuilder.h:574
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition IRBuilder.h:522
ConstantInt * getIntN(unsigned N, uint64_t C)
Get a constant N-bit value, zero extended from a 64-bit value.
Definition IRBuilder.h:532
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2787
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1572
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:255
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
LLVMContext & getContext() const
Get the global data context.
Definition Module.h:285
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:133
iterator end()
Definition StringMap.h:224
iterator find(StringRef Key)
Definition StringMap.h:237
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
Definition StringRef.h:446
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:413
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:259
iterator_range< user_iterator > users()
Definition Value.h:426
bool use_empty() const
Definition Value.h:346
iterator_range< use_iterator > uses()
Definition Value.h:380
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:403
const ParentTy * getParent() const
Definition ilist_node.h:34
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
Changed
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
@ Entry
Definition COFF.h:862
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
Definition CallingConv.h:76
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
cl::opt< bool > WasmEnableSjLj
cl::opt< bool > WasmEnableEmEH
cl::opt< bool > WasmEnableEmSjLj
@ User
could "use" a pointer
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
std::tuple< const DIScope *, const DIScope *, const DILocalVariable * > VarID
A unique key that represents a debug variable.
LLVM_ABI StringRef getEHPersonalityName(EHPersonality Pers)
LLVM_ABI BasicBlock * changeToInvokeAndSplitBasicBlock(CallInst *CI, BasicBlock *UnwindEdge, DomTreeUpdater *DTU=nullptr)
Convert the CallInst to InvokeInst with the specified unwind edge basic block.
Definition Local.cpp:2621
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
FunctionAddr VTableAddr uintptr_t uintptr_t Int32Ty
Definition InstrProf.h:296
LLVM_ABI CallInst * changeToCall(InvokeInst *II, DomTreeUpdater *DTU=nullptr)
This function converts the specified invoke into a normal call.
Definition Local.cpp:2597
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:634
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
ModulePass * createWebAssemblyLowerEmscriptenEHSjLj()
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
OperandBundleDefT< Value * > OperandBundleDef
Definition AutoUpgrade.h:34
void replace(R &&Range, const T &OldValue, const T &NewValue)
Provide wrappers to std::replace which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1910
@ Or
Bitwise or logical OR of integers.
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2192
bool isSpace(char C)
Checks whether character C is whitespace in the "C" locale.