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