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