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