1 //===-- X86WinEHState - Insert EH state updates for win32 exceptions ------===// 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 // All functions using an MSVC EH personality use an explicitly updated state 10 // number stored in an exception registration stack object. The registration 11 // object is linked into a thread-local chain of registrations stored at fs:00. 12 // This pass adds the registration object and EH state updates. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "X86.h" 17 #include "llvm/ADT/PostOrderIterator.h" 18 #include "llvm/Analysis/CFG.h" 19 #include "llvm/Analysis/EHPersonalities.h" 20 #include "llvm/CodeGen/MachineModuleInfo.h" 21 #include "llvm/CodeGen/WinEHFuncInfo.h" 22 #include "llvm/IR/Function.h" 23 #include "llvm/IR/IRBuilder.h" 24 #include "llvm/IR/Instructions.h" 25 #include "llvm/IR/Intrinsics.h" 26 #include "llvm/IR/IntrinsicsX86.h" 27 #include "llvm/IR/Module.h" 28 #include "llvm/Pass.h" 29 #include "llvm/Support/Debug.h" 30 #include <deque> 31 32 using namespace llvm; 33 34 #define DEBUG_TYPE "winehstate" 35 36 namespace { 37 const int OverdefinedState = INT_MIN; 38 39 class WinEHStatePass : public FunctionPass { 40 public: 41 static char ID; // Pass identification, replacement for typeid. 42 43 WinEHStatePass() : FunctionPass(ID) { } 44 45 bool runOnFunction(Function &Fn) override; 46 47 bool doInitialization(Module &M) override; 48 49 bool doFinalization(Module &M) override; 50 51 void getAnalysisUsage(AnalysisUsage &AU) const override; 52 53 StringRef getPassName() const override { 54 return "Windows 32-bit x86 EH state insertion"; 55 } 56 57 private: 58 void emitExceptionRegistrationRecord(Function *F); 59 60 void linkExceptionRegistration(IRBuilder<> &Builder, Function *Handler); 61 void unlinkExceptionRegistration(IRBuilder<> &Builder); 62 void addStateStores(Function &F, WinEHFuncInfo &FuncInfo); 63 void insertStateNumberStore(Instruction *IP, int State); 64 65 Value *emitEHLSDA(IRBuilder<> &Builder, Function *F); 66 67 Function *generateLSDAInEAXThunk(Function *ParentFunc); 68 69 bool isStateStoreNeeded(EHPersonality Personality, CallBase &Call); 70 void rewriteSetJmpCall(IRBuilder<> &Builder, Function &F, CallBase &Call, 71 Value *State); 72 int getBaseStateForBB(DenseMap<BasicBlock *, ColorVector> &BlockColors, 73 WinEHFuncInfo &FuncInfo, BasicBlock *BB); 74 int getStateForCall(DenseMap<BasicBlock *, ColorVector> &BlockColors, 75 WinEHFuncInfo &FuncInfo, CallBase &Call); 76 77 // Module-level type getters. 78 Type *getEHLinkRegistrationType(); 79 Type *getSEHRegistrationType(); 80 Type *getCXXEHRegistrationType(); 81 82 // Per-module data. 83 Module *TheModule = nullptr; 84 StructType *EHLinkRegistrationTy = nullptr; 85 StructType *CXXEHRegistrationTy = nullptr; 86 StructType *SEHRegistrationTy = nullptr; 87 FunctionCallee SetJmp3 = nullptr; 88 FunctionCallee CxxLongjmpUnwind = nullptr; 89 90 // Per-function state 91 EHPersonality Personality = EHPersonality::Unknown; 92 Function *PersonalityFn = nullptr; 93 bool UseStackGuard = false; 94 int ParentBaseState = 0; 95 FunctionCallee SehLongjmpUnwind = nullptr; 96 Constant *Cookie = nullptr; 97 98 /// The stack allocation containing all EH data, including the link in the 99 /// fs:00 chain and the current state. 100 AllocaInst *RegNode = nullptr; 101 102 // The allocation containing the EH security guard. 103 AllocaInst *EHGuardNode = nullptr; 104 105 /// The index of the state field of RegNode. 106 int StateFieldIndex = ~0U; 107 108 /// The linked list node subobject inside of RegNode. 109 Value *Link = nullptr; 110 }; 111 } 112 113 FunctionPass *llvm::createX86WinEHStatePass() { return new WinEHStatePass(); } 114 115 char WinEHStatePass::ID = 0; 116 117 INITIALIZE_PASS(WinEHStatePass, "x86-winehstate", 118 "Insert stores for EH state numbers", false, false) 119 120 bool WinEHStatePass::doInitialization(Module &M) { 121 TheModule = &M; 122 return false; 123 } 124 125 bool WinEHStatePass::doFinalization(Module &M) { 126 assert(TheModule == &M); 127 TheModule = nullptr; 128 EHLinkRegistrationTy = nullptr; 129 CXXEHRegistrationTy = nullptr; 130 SEHRegistrationTy = nullptr; 131 SetJmp3 = nullptr; 132 CxxLongjmpUnwind = nullptr; 133 SehLongjmpUnwind = nullptr; 134 Cookie = nullptr; 135 return false; 136 } 137 138 void WinEHStatePass::getAnalysisUsage(AnalysisUsage &AU) const { 139 // This pass should only insert a stack allocation, memory accesses, and 140 // localrecovers. 141 AU.setPreservesCFG(); 142 } 143 144 bool WinEHStatePass::runOnFunction(Function &F) { 145 // Don't insert state stores or exception handler thunks for 146 // available_externally functions. The handler needs to reference the LSDA, 147 // which will not be emitted in this case. 148 if (F.hasAvailableExternallyLinkage()) 149 return false; 150 151 // Check the personality. Do nothing if this personality doesn't use funclets. 152 if (!F.hasPersonalityFn()) 153 return false; 154 PersonalityFn = 155 dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts()); 156 if (!PersonalityFn) 157 return false; 158 Personality = classifyEHPersonality(PersonalityFn); 159 if (!isFuncletEHPersonality(Personality)) 160 return false; 161 162 // Skip this function if there are no EH pads and we aren't using IR-level 163 // outlining. 164 bool HasPads = false; 165 for (BasicBlock &BB : F) { 166 if (BB.isEHPad()) { 167 HasPads = true; 168 break; 169 } 170 } 171 if (!HasPads) 172 return false; 173 174 Type *Int8PtrType = Type::getInt8PtrTy(TheModule->getContext()); 175 SetJmp3 = TheModule->getOrInsertFunction( 176 "_setjmp3", FunctionType::get( 177 Type::getInt32Ty(TheModule->getContext()), 178 {Int8PtrType, Type::getInt32Ty(TheModule->getContext())}, 179 /*isVarArg=*/true)); 180 181 emitExceptionRegistrationRecord(&F); 182 183 // The state numbers calculated here in IR must agree with what we calculate 184 // later on for the MachineFunction. In particular, if an IR pass deletes an 185 // unreachable EH pad after this point before machine CFG construction, we 186 // will be in trouble. If this assumption is ever broken, we should turn the 187 // numbers into an immutable analysis pass. 188 WinEHFuncInfo FuncInfo; 189 addStateStores(F, FuncInfo); 190 191 // Reset per-function state. 192 PersonalityFn = nullptr; 193 Personality = EHPersonality::Unknown; 194 UseStackGuard = false; 195 RegNode = nullptr; 196 EHGuardNode = nullptr; 197 198 return true; 199 } 200 201 /// Get the common EH registration subobject: 202 /// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)( 203 /// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *); 204 /// struct EHRegistrationNode { 205 /// EHRegistrationNode *Next; 206 /// PEXCEPTION_ROUTINE Handler; 207 /// }; 208 Type *WinEHStatePass::getEHLinkRegistrationType() { 209 if (EHLinkRegistrationTy) 210 return EHLinkRegistrationTy; 211 LLVMContext &Context = TheModule->getContext(); 212 EHLinkRegistrationTy = StructType::create(Context, "EHRegistrationNode"); 213 Type *FieldTys[] = { 214 EHLinkRegistrationTy->getPointerTo(0), // EHRegistrationNode *Next 215 Type::getInt8PtrTy(Context) // EXCEPTION_DISPOSITION (*Handler)(...) 216 }; 217 EHLinkRegistrationTy->setBody(FieldTys, false); 218 return EHLinkRegistrationTy; 219 } 220 221 /// The __CxxFrameHandler3 registration node: 222 /// struct CXXExceptionRegistration { 223 /// void *SavedESP; 224 /// EHRegistrationNode SubRecord; 225 /// int32_t TryLevel; 226 /// }; 227 Type *WinEHStatePass::getCXXEHRegistrationType() { 228 if (CXXEHRegistrationTy) 229 return CXXEHRegistrationTy; 230 LLVMContext &Context = TheModule->getContext(); 231 Type *FieldTys[] = { 232 Type::getInt8PtrTy(Context), // void *SavedESP 233 getEHLinkRegistrationType(), // EHRegistrationNode SubRecord 234 Type::getInt32Ty(Context) // int32_t TryLevel 235 }; 236 CXXEHRegistrationTy = 237 StructType::create(FieldTys, "CXXExceptionRegistration"); 238 return CXXEHRegistrationTy; 239 } 240 241 /// The _except_handler3/4 registration node: 242 /// struct EH4ExceptionRegistration { 243 /// void *SavedESP; 244 /// _EXCEPTION_POINTERS *ExceptionPointers; 245 /// EHRegistrationNode SubRecord; 246 /// int32_t EncodedScopeTable; 247 /// int32_t TryLevel; 248 /// }; 249 Type *WinEHStatePass::getSEHRegistrationType() { 250 if (SEHRegistrationTy) 251 return SEHRegistrationTy; 252 LLVMContext &Context = TheModule->getContext(); 253 Type *FieldTys[] = { 254 Type::getInt8PtrTy(Context), // void *SavedESP 255 Type::getInt8PtrTy(Context), // void *ExceptionPointers 256 getEHLinkRegistrationType(), // EHRegistrationNode SubRecord 257 Type::getInt32Ty(Context), // int32_t EncodedScopeTable 258 Type::getInt32Ty(Context) // int32_t TryLevel 259 }; 260 SEHRegistrationTy = StructType::create(FieldTys, "SEHExceptionRegistration"); 261 return SEHRegistrationTy; 262 } 263 264 // Emit an exception registration record. These are stack allocations with the 265 // common subobject of two pointers: the previous registration record (the old 266 // fs:00) and the personality function for the current frame. The data before 267 // and after that is personality function specific. 268 void WinEHStatePass::emitExceptionRegistrationRecord(Function *F) { 269 assert(Personality == EHPersonality::MSVC_CXX || 270 Personality == EHPersonality::MSVC_X86SEH); 271 272 // Struct type of RegNode. Used for GEPing. 273 Type *RegNodeTy; 274 275 IRBuilder<> Builder(&F->getEntryBlock(), F->getEntryBlock().begin()); 276 Type *Int8PtrType = Builder.getInt8PtrTy(); 277 Type *Int32Ty = Builder.getInt32Ty(); 278 Type *VoidTy = Builder.getVoidTy(); 279 280 if (Personality == EHPersonality::MSVC_CXX) { 281 RegNodeTy = getCXXEHRegistrationType(); 282 RegNode = Builder.CreateAlloca(RegNodeTy); 283 // SavedESP = llvm.stacksave() 284 Value *SP = Builder.CreateCall( 285 Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {}); 286 Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0)); 287 // TryLevel = -1 288 StateFieldIndex = 2; 289 ParentBaseState = -1; 290 insertStateNumberStore(&*Builder.GetInsertPoint(), ParentBaseState); 291 // Handler = __ehhandler$F 292 Function *Trampoline = generateLSDAInEAXThunk(F); 293 Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 1); 294 linkExceptionRegistration(Builder, Trampoline); 295 296 CxxLongjmpUnwind = TheModule->getOrInsertFunction( 297 "__CxxLongjmpUnwind", 298 FunctionType::get(VoidTy, Int8PtrType, /*isVarArg=*/false)); 299 cast<Function>(CxxLongjmpUnwind.getCallee()->stripPointerCasts()) 300 ->setCallingConv(CallingConv::X86_StdCall); 301 } else if (Personality == EHPersonality::MSVC_X86SEH) { 302 // If _except_handler4 is in use, some additional guard checks and prologue 303 // stuff is required. 304 StringRef PersonalityName = PersonalityFn->getName(); 305 UseStackGuard = (PersonalityName == "_except_handler4"); 306 307 // Allocate local structures. 308 RegNodeTy = getSEHRegistrationType(); 309 RegNode = Builder.CreateAlloca(RegNodeTy); 310 if (UseStackGuard) 311 EHGuardNode = Builder.CreateAlloca(Int32Ty); 312 313 // SavedESP = llvm.stacksave() 314 Value *SP = Builder.CreateCall( 315 Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {}); 316 Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0)); 317 // TryLevel = -2 / -1 318 StateFieldIndex = 4; 319 ParentBaseState = UseStackGuard ? -2 : -1; 320 insertStateNumberStore(&*Builder.GetInsertPoint(), ParentBaseState); 321 // ScopeTable = llvm.x86.seh.lsda(F) 322 Value *LSDA = emitEHLSDA(Builder, F); 323 LSDA = Builder.CreatePtrToInt(LSDA, Int32Ty); 324 // If using _except_handler4, xor the address of the table with 325 // __security_cookie. 326 if (UseStackGuard) { 327 Cookie = TheModule->getOrInsertGlobal("__security_cookie", Int32Ty); 328 Value *Val = Builder.CreateLoad(Int32Ty, Cookie, "cookie"); 329 LSDA = Builder.CreateXor(LSDA, Val); 330 } 331 Builder.CreateStore(LSDA, Builder.CreateStructGEP(RegNodeTy, RegNode, 3)); 332 333 // If using _except_handler4, the EHGuard contains: FramePtr xor Cookie. 334 if (UseStackGuard) { 335 Value *Val = Builder.CreateLoad(Int32Ty, Cookie); 336 Value *FrameAddr = Builder.CreateCall( 337 Intrinsic::getDeclaration( 338 TheModule, Intrinsic::frameaddress, 339 Builder.getInt8PtrTy( 340 TheModule->getDataLayout().getAllocaAddrSpace())), 341 Builder.getInt32(0), "frameaddr"); 342 Value *FrameAddrI32 = Builder.CreatePtrToInt(FrameAddr, Int32Ty); 343 FrameAddrI32 = Builder.CreateXor(FrameAddrI32, Val); 344 Builder.CreateStore(FrameAddrI32, EHGuardNode); 345 } 346 347 // Register the exception handler. 348 Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 2); 349 linkExceptionRegistration(Builder, PersonalityFn); 350 351 SehLongjmpUnwind = TheModule->getOrInsertFunction( 352 UseStackGuard ? "_seh_longjmp_unwind4" : "_seh_longjmp_unwind", 353 FunctionType::get(Type::getVoidTy(TheModule->getContext()), Int8PtrType, 354 /*isVarArg=*/false)); 355 cast<Function>(SehLongjmpUnwind.getCallee()->stripPointerCasts()) 356 ->setCallingConv(CallingConv::X86_StdCall); 357 } else { 358 llvm_unreachable("unexpected personality function"); 359 } 360 361 // Insert an unlink before all returns. 362 for (BasicBlock &BB : *F) { 363 Instruction *T = BB.getTerminator(); 364 if (!isa<ReturnInst>(T)) 365 continue; 366 Builder.SetInsertPoint(T); 367 unlinkExceptionRegistration(Builder); 368 } 369 } 370 371 Value *WinEHStatePass::emitEHLSDA(IRBuilder<> &Builder, Function *F) { 372 Value *FI8 = Builder.CreateBitCast(F, Type::getInt8PtrTy(F->getContext())); 373 return Builder.CreateCall( 374 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8); 375 } 376 377 /// Generate a thunk that puts the LSDA of ParentFunc in EAX and then calls 378 /// PersonalityFn, forwarding the parameters passed to PEXCEPTION_ROUTINE: 379 /// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)( 380 /// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *); 381 /// We essentially want this code: 382 /// movl $lsda, %eax 383 /// jmpl ___CxxFrameHandler3 384 Function *WinEHStatePass::generateLSDAInEAXThunk(Function *ParentFunc) { 385 LLVMContext &Context = ParentFunc->getContext(); 386 Type *Int32Ty = Type::getInt32Ty(Context); 387 Type *Int8PtrType = Type::getInt8PtrTy(Context); 388 Type *ArgTys[5] = {Int8PtrType, Int8PtrType, Int8PtrType, Int8PtrType, 389 Int8PtrType}; 390 FunctionType *TrampolineTy = 391 FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 4), 392 /*isVarArg=*/false); 393 FunctionType *TargetFuncTy = 394 FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 5), 395 /*isVarArg=*/false); 396 Function *Trampoline = 397 Function::Create(TrampolineTy, GlobalValue::InternalLinkage, 398 Twine("__ehhandler$") + GlobalValue::dropLLVMManglingEscape( 399 ParentFunc->getName()), 400 TheModule); 401 if (auto *C = ParentFunc->getComdat()) 402 Trampoline->setComdat(C); 403 BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", Trampoline); 404 IRBuilder<> Builder(EntryBB); 405 Value *LSDA = emitEHLSDA(Builder, ParentFunc); 406 Value *CastPersonality = 407 Builder.CreateBitCast(PersonalityFn, TargetFuncTy->getPointerTo()); 408 auto AI = Trampoline->arg_begin(); 409 Value *Args[5] = {LSDA, &*AI++, &*AI++, &*AI++, &*AI++}; 410 CallInst *Call = Builder.CreateCall(TargetFuncTy, CastPersonality, Args); 411 // Can't use musttail due to prototype mismatch, but we can use tail. 412 Call->setTailCall(true); 413 // Set inreg so we pass it in EAX. 414 Call->addParamAttr(0, Attribute::InReg); 415 Builder.CreateRet(Call); 416 return Trampoline; 417 } 418 419 void WinEHStatePass::linkExceptionRegistration(IRBuilder<> &Builder, 420 Function *Handler) { 421 // Emit the .safeseh directive for this function. 422 Handler->addFnAttr("safeseh"); 423 424 Type *LinkTy = getEHLinkRegistrationType(); 425 // Handler = Handler 426 Value *HandlerI8 = Builder.CreateBitCast(Handler, Builder.getInt8PtrTy()); 427 Builder.CreateStore(HandlerI8, Builder.CreateStructGEP(LinkTy, Link, 1)); 428 // Next = [fs:00] 429 Constant *FSZero = 430 Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257)); 431 Value *Next = Builder.CreateLoad(LinkTy->getPointerTo(), FSZero); 432 Builder.CreateStore(Next, Builder.CreateStructGEP(LinkTy, Link, 0)); 433 // [fs:00] = Link 434 Builder.CreateStore(Link, FSZero); 435 } 436 437 void WinEHStatePass::unlinkExceptionRegistration(IRBuilder<> &Builder) { 438 // Clone Link into the current BB for better address mode folding. 439 if (auto *GEP = dyn_cast<GetElementPtrInst>(Link)) { 440 GEP = cast<GetElementPtrInst>(GEP->clone()); 441 Builder.Insert(GEP); 442 Link = GEP; 443 } 444 Type *LinkTy = getEHLinkRegistrationType(); 445 // [fs:00] = Link->Next 446 Value *Next = Builder.CreateLoad(LinkTy->getPointerTo(), 447 Builder.CreateStructGEP(LinkTy, Link, 0)); 448 Constant *FSZero = 449 Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257)); 450 Builder.CreateStore(Next, FSZero); 451 } 452 453 // Calls to setjmp(p) are lowered to _setjmp3(p, 0) by the frontend. 454 // The idea behind _setjmp3 is that it takes an optional number of personality 455 // specific parameters to indicate how to restore the personality-specific frame 456 // state when longjmp is initiated. Typically, the current TryLevel is saved. 457 void WinEHStatePass::rewriteSetJmpCall(IRBuilder<> &Builder, Function &F, 458 CallBase &Call, Value *State) { 459 // Don't rewrite calls with a weird number of arguments. 460 if (Call.getNumArgOperands() != 2) 461 return; 462 463 SmallVector<OperandBundleDef, 1> OpBundles; 464 Call.getOperandBundlesAsDefs(OpBundles); 465 466 SmallVector<Value *, 3> OptionalArgs; 467 if (Personality == EHPersonality::MSVC_CXX) { 468 OptionalArgs.push_back(CxxLongjmpUnwind.getCallee()); 469 OptionalArgs.push_back(State); 470 OptionalArgs.push_back(emitEHLSDA(Builder, &F)); 471 } else if (Personality == EHPersonality::MSVC_X86SEH) { 472 OptionalArgs.push_back(SehLongjmpUnwind.getCallee()); 473 OptionalArgs.push_back(State); 474 if (UseStackGuard) 475 OptionalArgs.push_back(Cookie); 476 } else { 477 llvm_unreachable("unhandled personality!"); 478 } 479 480 SmallVector<Value *, 5> Args; 481 Args.push_back( 482 Builder.CreateBitCast(Call.getArgOperand(0), Builder.getInt8PtrTy())); 483 Args.push_back(Builder.getInt32(OptionalArgs.size())); 484 Args.append(OptionalArgs.begin(), OptionalArgs.end()); 485 486 CallBase *NewCall; 487 if (auto *CI = dyn_cast<CallInst>(&Call)) { 488 CallInst *NewCI = Builder.CreateCall(SetJmp3, Args, OpBundles); 489 NewCI->setTailCallKind(CI->getTailCallKind()); 490 NewCall = NewCI; 491 } else { 492 auto *II = cast<InvokeInst>(&Call); 493 NewCall = Builder.CreateInvoke( 494 SetJmp3, II->getNormalDest(), II->getUnwindDest(), Args, OpBundles); 495 } 496 NewCall->setCallingConv(Call.getCallingConv()); 497 NewCall->setAttributes(Call.getAttributes()); 498 NewCall->setDebugLoc(Call.getDebugLoc()); 499 500 NewCall->takeName(&Call); 501 Call.replaceAllUsesWith(NewCall); 502 Call.eraseFromParent(); 503 } 504 505 // Figure out what state we should assign calls in this block. 506 int WinEHStatePass::getBaseStateForBB( 507 DenseMap<BasicBlock *, ColorVector> &BlockColors, WinEHFuncInfo &FuncInfo, 508 BasicBlock *BB) { 509 int BaseState = ParentBaseState; 510 auto &BBColors = BlockColors[BB]; 511 512 assert(BBColors.size() == 1 && "multi-color BB not removed by preparation"); 513 BasicBlock *FuncletEntryBB = BBColors.front(); 514 if (auto *FuncletPad = 515 dyn_cast<FuncletPadInst>(FuncletEntryBB->getFirstNonPHI())) { 516 auto BaseStateI = FuncInfo.FuncletBaseStateMap.find(FuncletPad); 517 if (BaseStateI != FuncInfo.FuncletBaseStateMap.end()) 518 BaseState = BaseStateI->second; 519 } 520 521 return BaseState; 522 } 523 524 // Calculate the state a call-site is in. 525 int WinEHStatePass::getStateForCall( 526 DenseMap<BasicBlock *, ColorVector> &BlockColors, WinEHFuncInfo &FuncInfo, 527 CallBase &Call) { 528 if (auto *II = dyn_cast<InvokeInst>(&Call)) { 529 // Look up the state number of the EH pad this unwinds to. 530 assert(FuncInfo.InvokeStateMap.count(II) && "invoke has no state!"); 531 return FuncInfo.InvokeStateMap[II]; 532 } 533 // Possibly throwing call instructions have no actions to take after 534 // an unwind. Ensure they are in the -1 state. 535 return getBaseStateForBB(BlockColors, FuncInfo, Call.getParent()); 536 } 537 538 // Calculate the intersection of all the FinalStates for a BasicBlock's 539 // predecessors. 540 static int getPredState(DenseMap<BasicBlock *, int> &FinalStates, Function &F, 541 int ParentBaseState, BasicBlock *BB) { 542 // The entry block has no predecessors but we know that the prologue always 543 // sets us up with a fixed state. 544 if (&F.getEntryBlock() == BB) 545 return ParentBaseState; 546 547 // This is an EH Pad, conservatively report this basic block as overdefined. 548 if (BB->isEHPad()) 549 return OverdefinedState; 550 551 int CommonState = OverdefinedState; 552 for (BasicBlock *PredBB : predecessors(BB)) { 553 // We didn't manage to get a state for one of these predecessors, 554 // conservatively report this basic block as overdefined. 555 auto PredEndState = FinalStates.find(PredBB); 556 if (PredEndState == FinalStates.end()) 557 return OverdefinedState; 558 559 // This code is reachable via exceptional control flow, 560 // conservatively report this basic block as overdefined. 561 if (isa<CatchReturnInst>(PredBB->getTerminator())) 562 return OverdefinedState; 563 564 int PredState = PredEndState->second; 565 assert(PredState != OverdefinedState && 566 "overdefined BBs shouldn't be in FinalStates"); 567 if (CommonState == OverdefinedState) 568 CommonState = PredState; 569 570 // At least two predecessors have different FinalStates, 571 // conservatively report this basic block as overdefined. 572 if (CommonState != PredState) 573 return OverdefinedState; 574 } 575 576 return CommonState; 577 } 578 579 // Calculate the intersection of all the InitialStates for a BasicBlock's 580 // successors. 581 static int getSuccState(DenseMap<BasicBlock *, int> &InitialStates, Function &F, 582 int ParentBaseState, BasicBlock *BB) { 583 // This block rejoins normal control flow, 584 // conservatively report this basic block as overdefined. 585 if (isa<CatchReturnInst>(BB->getTerminator())) 586 return OverdefinedState; 587 588 int CommonState = OverdefinedState; 589 for (BasicBlock *SuccBB : successors(BB)) { 590 // We didn't manage to get a state for one of these predecessors, 591 // conservatively report this basic block as overdefined. 592 auto SuccStartState = InitialStates.find(SuccBB); 593 if (SuccStartState == InitialStates.end()) 594 return OverdefinedState; 595 596 // This is an EH Pad, conservatively report this basic block as overdefined. 597 if (SuccBB->isEHPad()) 598 return OverdefinedState; 599 600 int SuccState = SuccStartState->second; 601 assert(SuccState != OverdefinedState && 602 "overdefined BBs shouldn't be in FinalStates"); 603 if (CommonState == OverdefinedState) 604 CommonState = SuccState; 605 606 // At least two successors have different InitialStates, 607 // conservatively report this basic block as overdefined. 608 if (CommonState != SuccState) 609 return OverdefinedState; 610 } 611 612 return CommonState; 613 } 614 615 bool WinEHStatePass::isStateStoreNeeded(EHPersonality Personality, 616 CallBase &Call) { 617 // If the function touches memory, it needs a state store. 618 if (isAsynchronousEHPersonality(Personality)) 619 return !Call.doesNotAccessMemory(); 620 621 // If the function throws, it needs a state store. 622 return !Call.doesNotThrow(); 623 } 624 625 void WinEHStatePass::addStateStores(Function &F, WinEHFuncInfo &FuncInfo) { 626 // Mark the registration node. The backend needs to know which alloca it is so 627 // that it can recover the original frame pointer. 628 IRBuilder<> Builder(RegNode->getNextNode()); 629 Value *RegNodeI8 = Builder.CreateBitCast(RegNode, Builder.getInt8PtrTy()); 630 Builder.CreateCall( 631 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_ehregnode), 632 {RegNodeI8}); 633 634 if (EHGuardNode) { 635 IRBuilder<> Builder(EHGuardNode->getNextNode()); 636 Value *EHGuardNodeI8 = 637 Builder.CreateBitCast(EHGuardNode, Builder.getInt8PtrTy()); 638 Builder.CreateCall( 639 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_ehguard), 640 {EHGuardNodeI8}); 641 } 642 643 // Calculate state numbers. 644 if (isAsynchronousEHPersonality(Personality)) 645 calculateSEHStateNumbers(&F, FuncInfo); 646 else 647 calculateWinCXXEHStateNumbers(&F, FuncInfo); 648 649 // Iterate all the instructions and emit state number stores. 650 DenseMap<BasicBlock *, ColorVector> BlockColors = colorEHFunclets(F); 651 ReversePostOrderTraversal<Function *> RPOT(&F); 652 653 // InitialStates yields the state of the first call-site for a BasicBlock. 654 DenseMap<BasicBlock *, int> InitialStates; 655 // FinalStates yields the state of the last call-site for a BasicBlock. 656 DenseMap<BasicBlock *, int> FinalStates; 657 // Worklist used to revisit BasicBlocks with indeterminate 658 // Initial/Final-States. 659 std::deque<BasicBlock *> Worklist; 660 // Fill in InitialStates and FinalStates for BasicBlocks with call-sites. 661 for (BasicBlock *BB : RPOT) { 662 int InitialState = OverdefinedState; 663 int FinalState; 664 if (&F.getEntryBlock() == BB) 665 InitialState = FinalState = ParentBaseState; 666 for (Instruction &I : *BB) { 667 auto *Call = dyn_cast<CallBase>(&I); 668 if (!Call || !isStateStoreNeeded(Personality, *Call)) 669 continue; 670 671 int State = getStateForCall(BlockColors, FuncInfo, *Call); 672 if (InitialState == OverdefinedState) 673 InitialState = State; 674 FinalState = State; 675 } 676 // No call-sites in this basic block? That's OK, we will come back to these 677 // in a later pass. 678 if (InitialState == OverdefinedState) { 679 Worklist.push_back(BB); 680 continue; 681 } 682 LLVM_DEBUG(dbgs() << "X86WinEHState: " << BB->getName() 683 << " InitialState=" << InitialState << '\n'); 684 LLVM_DEBUG(dbgs() << "X86WinEHState: " << BB->getName() 685 << " FinalState=" << FinalState << '\n'); 686 InitialStates.insert({BB, InitialState}); 687 FinalStates.insert({BB, FinalState}); 688 } 689 690 // Try to fill-in InitialStates and FinalStates which have no call-sites. 691 while (!Worklist.empty()) { 692 BasicBlock *BB = Worklist.front(); 693 Worklist.pop_front(); 694 // This BasicBlock has already been figured out, nothing more we can do. 695 if (InitialStates.count(BB) != 0) 696 continue; 697 698 int PredState = getPredState(FinalStates, F, ParentBaseState, BB); 699 if (PredState == OverdefinedState) 700 continue; 701 702 // We successfully inferred this BasicBlock's state via it's predecessors; 703 // enqueue it's successors to see if we can infer their states. 704 InitialStates.insert({BB, PredState}); 705 FinalStates.insert({BB, PredState}); 706 for (BasicBlock *SuccBB : successors(BB)) 707 Worklist.push_back(SuccBB); 708 } 709 710 // Try to hoist stores from successors. 711 for (BasicBlock *BB : RPOT) { 712 int SuccState = getSuccState(InitialStates, F, ParentBaseState, BB); 713 if (SuccState == OverdefinedState) 714 continue; 715 716 // Update our FinalState to reflect the common InitialState of our 717 // successors. 718 FinalStates.insert({BB, SuccState}); 719 } 720 721 // Finally, insert state stores before call-sites which transition us to a new 722 // state. 723 for (BasicBlock *BB : RPOT) { 724 auto &BBColors = BlockColors[BB]; 725 BasicBlock *FuncletEntryBB = BBColors.front(); 726 if (isa<CleanupPadInst>(FuncletEntryBB->getFirstNonPHI())) 727 continue; 728 729 int PrevState = getPredState(FinalStates, F, ParentBaseState, BB); 730 LLVM_DEBUG(dbgs() << "X86WinEHState: " << BB->getName() 731 << " PrevState=" << PrevState << '\n'); 732 733 for (Instruction &I : *BB) { 734 auto *Call = dyn_cast<CallBase>(&I); 735 if (!Call || !isStateStoreNeeded(Personality, *Call)) 736 continue; 737 738 int State = getStateForCall(BlockColors, FuncInfo, *Call); 739 if (State != PrevState) 740 insertStateNumberStore(&I, State); 741 PrevState = State; 742 } 743 744 // We might have hoisted a state store into this block, emit it now. 745 auto EndState = FinalStates.find(BB); 746 if (EndState != FinalStates.end()) 747 if (EndState->second != PrevState) 748 insertStateNumberStore(BB->getTerminator(), EndState->second); 749 } 750 751 SmallVector<CallBase *, 1> SetJmp3Calls; 752 for (BasicBlock *BB : RPOT) { 753 for (Instruction &I : *BB) { 754 auto *Call = dyn_cast<CallBase>(&I); 755 if (!Call) 756 continue; 757 if (Call->getCalledOperand()->stripPointerCasts() != 758 SetJmp3.getCallee()->stripPointerCasts()) 759 continue; 760 761 SetJmp3Calls.push_back(Call); 762 } 763 } 764 765 for (CallBase *Call : SetJmp3Calls) { 766 auto &BBColors = BlockColors[Call->getParent()]; 767 BasicBlock *FuncletEntryBB = BBColors.front(); 768 bool InCleanup = isa<CleanupPadInst>(FuncletEntryBB->getFirstNonPHI()); 769 770 IRBuilder<> Builder(Call); 771 Value *State; 772 if (InCleanup) { 773 Value *StateField = Builder.CreateStructGEP(RegNode->getAllocatedType(), 774 RegNode, StateFieldIndex); 775 State = Builder.CreateLoad(Builder.getInt32Ty(), StateField); 776 } else { 777 State = Builder.getInt32(getStateForCall(BlockColors, FuncInfo, *Call)); 778 } 779 rewriteSetJmpCall(Builder, F, *Call, State); 780 } 781 } 782 783 void WinEHStatePass::insertStateNumberStore(Instruction *IP, int State) { 784 IRBuilder<> Builder(IP); 785 Value *StateField = Builder.CreateStructGEP(RegNode->getAllocatedType(), 786 RegNode, StateFieldIndex); 787 Builder.CreateStore(Builder.getInt32(State), StateField); 788 } 789