1 //===-- X86WinEHState - Insert EH state updates for win32 exceptions ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // All functions using an MSVC EH personality use an explicitly updated state
11 // number stored in an exception registration stack object. The registration
12 // object is linked into a thread-local chain of registrations stored at fs:00.
13 // This pass adds the registration object and EH state updates.
15 //===----------------------------------------------------------------------===//
18 #include "llvm/Analysis/LibCallSemantics.h"
19 #include "llvm/CodeGen/MachineModuleInfo.h"
20 #include "llvm/CodeGen/Passes.h"
21 #include "llvm/CodeGen/WinEHFuncInfo.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/IRBuilder.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/PatternMatch.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
33 #include "llvm/Transforms/Utils/Cloning.h"
34 #include "llvm/Transforms/Utils/Local.h"
37 using namespace llvm::PatternMatch;
39 #define DEBUG_TYPE "winehstate"
42 class WinEHStatePass : public FunctionPass {
44 static char ID; // Pass identification, replacement for typeid.
46 WinEHStatePass() : FunctionPass(ID) {}
48 bool runOnFunction(Function &Fn) override;
50 bool doInitialization(Module &M) override;
52 bool doFinalization(Module &M) override;
54 void getAnalysisUsage(AnalysisUsage &AU) const override;
56 const char *getPassName() const override {
57 return "Windows 32-bit x86 EH state insertion";
61 void emitExceptionRegistrationRecord(Function *F);
63 void linkExceptionRegistration(IRBuilder<> &Builder, Function *Handler);
64 void unlinkExceptionRegistration(IRBuilder<> &Builder);
65 void addCXXStateStores(Function &F, MachineModuleInfo &MMI);
66 void addSEHStateStores(Function &F, MachineModuleInfo &MMI);
67 void addCXXStateStoresToFunclet(Value *ParentRegNode, WinEHFuncInfo &FuncInfo,
68 Function &F, int BaseState);
69 void insertStateNumberStore(Value *ParentRegNode, Instruction *IP, int State);
71 Value *emitEHLSDA(IRBuilder<> &Builder, Function *F);
73 Function *generateLSDAInEAXThunk(Function *ParentFunc);
75 int escapeRegNode(Function &F);
77 // Module-level type getters.
78 Type *getEHLinkRegistrationType();
79 Type *getSEHRegistrationType();
80 Type *getCXXEHRegistrationType();
83 Module *TheModule = nullptr;
84 StructType *EHLinkRegistrationTy = nullptr;
85 StructType *CXXEHRegistrationTy = nullptr;
86 StructType *SEHRegistrationTy = nullptr;
87 Function *FrameRecover = nullptr;
88 Function *FrameAddress = nullptr;
89 Function *FrameEscape = nullptr;
92 EHPersonality Personality = EHPersonality::Unknown;
93 Function *PersonalityFn = nullptr;
95 /// The stack allocation containing all EH data, including the link in the
96 /// fs:00 chain and the current state.
97 AllocaInst *RegNode = nullptr;
99 /// Struct type of RegNode. Used for GEPing.
100 Type *RegNodeTy = nullptr;
102 /// The index of the state field of RegNode.
103 int StateFieldIndex = ~0U;
105 /// The linked list node subobject inside of RegNode.
106 Value *Link = nullptr;
110 FunctionPass *llvm::createX86WinEHStatePass() { return new WinEHStatePass(); }
112 char WinEHStatePass::ID = 0;
114 bool WinEHStatePass::doInitialization(Module &M) {
116 FrameEscape = Intrinsic::getDeclaration(TheModule, Intrinsic::frameescape);
117 FrameRecover = Intrinsic::getDeclaration(TheModule, Intrinsic::framerecover);
118 FrameAddress = Intrinsic::getDeclaration(TheModule, Intrinsic::frameaddress);
122 bool WinEHStatePass::doFinalization(Module &M) {
123 assert(TheModule == &M);
125 EHLinkRegistrationTy = nullptr;
126 CXXEHRegistrationTy = nullptr;
127 SEHRegistrationTy = nullptr;
128 FrameEscape = nullptr;
129 FrameRecover = nullptr;
130 FrameAddress = nullptr;
134 void WinEHStatePass::getAnalysisUsage(AnalysisUsage &AU) const {
135 // This pass should only insert a stack allocation, memory accesses, and
137 AU.setPreservesCFG();
140 bool WinEHStatePass::runOnFunction(Function &F) {
141 // If this is an outlined handler, don't do anything. We'll do state insertion
142 // for it in the parent.
143 StringRef WinEHParentName =
144 F.getFnAttribute("wineh-parent").getValueAsString();
145 if (WinEHParentName != F.getName() && !WinEHParentName.empty())
148 // Check the personality. Do nothing if this is not an MSVC personality.
149 if (!F.hasPersonalityFn())
152 dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
155 Personality = classifyEHPersonality(PersonalityFn);
156 if (!isMSVCEHPersonality(Personality))
159 // Disable frame pointer elimination in this function.
160 // FIXME: Do the nested handlers need to keep the parent ebp in ebp, or can we
161 // use an arbitrary register?
162 F.addFnAttr("no-frame-pointer-elim", "true");
164 emitExceptionRegistrationRecord(&F);
166 auto *MMIPtr = getAnalysisIfAvailable<MachineModuleInfo>();
167 assert(MMIPtr && "MachineModuleInfo should always be available");
168 MachineModuleInfo &MMI = *MMIPtr;
169 switch (Personality) {
170 default: llvm_unreachable("unexpected personality function");
171 case EHPersonality::MSVC_CXX: addCXXStateStores(F, MMI); break;
172 case EHPersonality::MSVC_X86SEH: addSEHStateStores(F, MMI); break;
175 // Reset per-function state.
176 PersonalityFn = nullptr;
177 Personality = EHPersonality::Unknown;
181 /// Get the common EH registration subobject:
182 /// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
183 /// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
184 /// struct EHRegistrationNode {
185 /// EHRegistrationNode *Next;
186 /// PEXCEPTION_ROUTINE Handler;
188 Type *WinEHStatePass::getEHLinkRegistrationType() {
189 if (EHLinkRegistrationTy)
190 return EHLinkRegistrationTy;
191 LLVMContext &Context = TheModule->getContext();
192 EHLinkRegistrationTy = StructType::create(Context, "EHRegistrationNode");
194 EHLinkRegistrationTy->getPointerTo(0), // EHRegistrationNode *Next
195 Type::getInt8PtrTy(Context) // EXCEPTION_DISPOSITION (*Handler)(...)
197 EHLinkRegistrationTy->setBody(FieldTys, false);
198 return EHLinkRegistrationTy;
201 /// The __CxxFrameHandler3 registration node:
202 /// struct CXXExceptionRegistration {
204 /// EHRegistrationNode SubRecord;
205 /// int32_t TryLevel;
207 Type *WinEHStatePass::getCXXEHRegistrationType() {
208 if (CXXEHRegistrationTy)
209 return CXXEHRegistrationTy;
210 LLVMContext &Context = TheModule->getContext();
212 Type::getInt8PtrTy(Context), // void *SavedESP
213 getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
214 Type::getInt32Ty(Context) // int32_t TryLevel
216 CXXEHRegistrationTy =
217 StructType::create(FieldTys, "CXXExceptionRegistration");
218 return CXXEHRegistrationTy;
221 /// The _except_handler3/4 registration node:
222 /// struct EH4ExceptionRegistration {
224 /// _EXCEPTION_POINTERS *ExceptionPointers;
225 /// EHRegistrationNode SubRecord;
226 /// int32_t EncodedScopeTable;
227 /// int32_t TryLevel;
229 Type *WinEHStatePass::getSEHRegistrationType() {
230 if (SEHRegistrationTy)
231 return SEHRegistrationTy;
232 LLVMContext &Context = TheModule->getContext();
234 Type::getInt8PtrTy(Context), // void *SavedESP
235 Type::getInt8PtrTy(Context), // void *ExceptionPointers
236 getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
237 Type::getInt32Ty(Context), // int32_t EncodedScopeTable
238 Type::getInt32Ty(Context) // int32_t TryLevel
240 SEHRegistrationTy = StructType::create(FieldTys, "SEHExceptionRegistration");
241 return SEHRegistrationTy;
244 // Emit an exception registration record. These are stack allocations with the
245 // common subobject of two pointers: the previous registration record (the old
246 // fs:00) and the personality function for the current frame. The data before
247 // and after that is personality function specific.
248 void WinEHStatePass::emitExceptionRegistrationRecord(Function *F) {
249 assert(Personality == EHPersonality::MSVC_CXX ||
250 Personality == EHPersonality::MSVC_X86SEH);
252 StringRef PersonalityName = PersonalityFn->getName();
253 IRBuilder<> Builder(&F->getEntryBlock(), F->getEntryBlock().begin());
254 Type *Int8PtrType = Builder.getInt8PtrTy();
255 if (Personality == EHPersonality::MSVC_CXX) {
256 RegNodeTy = getCXXEHRegistrationType();
257 RegNode = Builder.CreateAlloca(RegNodeTy);
258 // SavedESP = llvm.stacksave()
259 Value *SP = Builder.CreateCall(
260 Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
261 Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
264 insertStateNumberStore(RegNode, Builder.GetInsertPoint(), -1);
265 // Handler = __ehhandler$F
266 Function *Trampoline = generateLSDAInEAXThunk(F);
267 Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 1);
268 linkExceptionRegistration(Builder, Trampoline);
269 } else if (Personality == EHPersonality::MSVC_X86SEH) {
270 // If _except_handler4 is in use, some additional guard checks and prologue
271 // stuff is required.
272 bool UseStackGuard = (PersonalityName == "_except_handler4");
273 RegNodeTy = getSEHRegistrationType();
274 RegNode = Builder.CreateAlloca(RegNodeTy);
275 // SavedESP = llvm.stacksave()
276 Value *SP = Builder.CreateCall(
277 Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
278 Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
279 // TryLevel = -2 / -1
281 insertStateNumberStore(RegNode, Builder.GetInsertPoint(),
282 UseStackGuard ? -2 : -1);
283 // ScopeTable = llvm.x86.seh.lsda(F)
284 Value *FI8 = Builder.CreateBitCast(F, Int8PtrType);
285 Value *LSDA = Builder.CreateCall(
286 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
287 Type *Int32Ty = Type::getInt32Ty(TheModule->getContext());
288 LSDA = Builder.CreatePtrToInt(LSDA, Int32Ty);
289 // If using _except_handler4, xor the address of the table with
290 // __security_cookie.
293 TheModule->getOrInsertGlobal("__security_cookie", Int32Ty);
294 Value *Val = Builder.CreateLoad(Int32Ty, Cookie);
295 LSDA = Builder.CreateXor(LSDA, Val);
297 Builder.CreateStore(LSDA, Builder.CreateStructGEP(RegNodeTy, RegNode, 3));
298 Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 2);
299 linkExceptionRegistration(Builder, PersonalityFn);
301 llvm_unreachable("unexpected personality function");
304 // Insert an unlink before all returns.
305 for (BasicBlock &BB : *F) {
306 TerminatorInst *T = BB.getTerminator();
307 if (!isa<ReturnInst>(T))
309 Builder.SetInsertPoint(T);
310 unlinkExceptionRegistration(Builder);
314 Value *WinEHStatePass::emitEHLSDA(IRBuilder<> &Builder, Function *F) {
315 Value *FI8 = Builder.CreateBitCast(F, Type::getInt8PtrTy(F->getContext()));
316 return Builder.CreateCall(
317 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
320 /// Generate a thunk that puts the LSDA of ParentFunc in EAX and then calls
321 /// PersonalityFn, forwarding the parameters passed to PEXCEPTION_ROUTINE:
322 /// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
323 /// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
324 /// We essentially want this code:
326 /// jmpl ___CxxFrameHandler3
327 Function *WinEHStatePass::generateLSDAInEAXThunk(Function *ParentFunc) {
328 LLVMContext &Context = ParentFunc->getContext();
329 Type *Int32Ty = Type::getInt32Ty(Context);
330 Type *Int8PtrType = Type::getInt8PtrTy(Context);
331 Type *ArgTys[5] = {Int8PtrType, Int8PtrType, Int8PtrType, Int8PtrType,
333 FunctionType *TrampolineTy =
334 FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 4),
336 FunctionType *TargetFuncTy =
337 FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 5),
339 Function *Trampoline = Function::Create(
340 TrampolineTy, GlobalValue::InternalLinkage,
341 Twine("__ehhandler$") + ParentFunc->getName(), TheModule);
342 BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", Trampoline);
343 IRBuilder<> Builder(EntryBB);
344 Value *LSDA = emitEHLSDA(Builder, ParentFunc);
345 Value *CastPersonality =
346 Builder.CreateBitCast(PersonalityFn, TargetFuncTy->getPointerTo());
347 auto AI = Trampoline->arg_begin();
348 Value *Args[5] = {LSDA, AI++, AI++, AI++, AI++};
349 CallInst *Call = Builder.CreateCall(CastPersonality, Args);
350 // Can't use musttail due to prototype mismatch, but we can use tail.
351 Call->setTailCall(true);
352 // Set inreg so we pass it in EAX.
353 Call->addAttribute(1, Attribute::InReg);
354 Builder.CreateRet(Call);
358 void WinEHStatePass::linkExceptionRegistration(IRBuilder<> &Builder,
360 // Emit the .safeseh directive for this function.
361 Handler->addFnAttr("safeseh");
363 Type *LinkTy = getEHLinkRegistrationType();
365 Value *HandlerI8 = Builder.CreateBitCast(Handler, Builder.getInt8PtrTy());
366 Builder.CreateStore(HandlerI8, Builder.CreateStructGEP(LinkTy, Link, 1));
369 Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
370 Value *Next = Builder.CreateLoad(FSZero);
371 Builder.CreateStore(Next, Builder.CreateStructGEP(LinkTy, Link, 0));
373 Builder.CreateStore(Link, FSZero);
376 void WinEHStatePass::unlinkExceptionRegistration(IRBuilder<> &Builder) {
377 // Clone Link into the current BB for better address mode folding.
378 if (auto *GEP = dyn_cast<GetElementPtrInst>(Link)) {
379 GEP = cast<GetElementPtrInst>(GEP->clone());
383 Type *LinkTy = getEHLinkRegistrationType();
384 // [fs:00] = Link->Next
386 Builder.CreateLoad(Builder.CreateStructGEP(LinkTy, Link, 0));
388 Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
389 Builder.CreateStore(Next, FSZero);
392 void WinEHStatePass::addCXXStateStores(Function &F, MachineModuleInfo &MMI) {
393 WinEHFuncInfo &FuncInfo = MMI.getWinEHFuncInfo(&F);
394 calculateWinCXXEHStateNumbers(&F, FuncInfo);
396 // The base state for the parent is -1.
397 addCXXStateStoresToFunclet(RegNode, FuncInfo, F, -1);
399 // Set up RegNodeEscapeIndex
400 int RegNodeEscapeIndex = escapeRegNode(F);
402 // Only insert stores in catch handlers.
404 ConstantExpr::getBitCast(&F, Type::getInt8PtrTy(TheModule->getContext()));
405 for (auto P : FuncInfo.HandlerBaseState) {
406 Function *Handler = const_cast<Function *>(P.first);
407 int BaseState = P.second;
408 IRBuilder<> Builder(&Handler->getEntryBlock(),
409 Handler->getEntryBlock().begin());
410 // FIXME: Find and reuse such a call if present.
411 Value *ParentFP = Builder.CreateCall(FrameAddress, {Builder.getInt32(1)});
412 Value *RecoveredRegNode = Builder.CreateCall(
413 FrameRecover, {FI8, ParentFP, Builder.getInt32(RegNodeEscapeIndex)});
415 Builder.CreateBitCast(RecoveredRegNode, RegNodeTy->getPointerTo(0));
416 addCXXStateStoresToFunclet(RecoveredRegNode, FuncInfo, *Handler, BaseState);
420 /// Escape RegNode so that we can access it from child handlers. Find the call
421 /// to frameescape, if any, in the entry block and append RegNode to the list
423 int WinEHStatePass::escapeRegNode(Function &F) {
424 // Find the call to frameescape and extract its arguments.
425 IntrinsicInst *EscapeCall = nullptr;
426 for (Instruction &I : F.getEntryBlock()) {
427 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
428 if (II && II->getIntrinsicID() == Intrinsic::frameescape) {
433 SmallVector<Value *, 8> Args;
435 auto Ops = EscapeCall->arg_operands();
436 Args.append(Ops.begin(), Ops.end());
438 Args.push_back(RegNode);
440 // Replace the call (if it exists) with new one. Otherwise, insert at the end
441 // of the entry block.
442 IRBuilder<> Builder(&F.getEntryBlock(),
443 EscapeCall ? EscapeCall : F.getEntryBlock().end());
444 Builder.CreateCall(FrameEscape, Args);
446 EscapeCall->eraseFromParent();
447 return Args.size() - 1;
450 void WinEHStatePass::addCXXStateStoresToFunclet(Value *ParentRegNode,
451 WinEHFuncInfo &FuncInfo,
452 Function &F, int BaseState) {
453 // Iterate all the instructions and emit state number stores.
454 for (BasicBlock &BB : F) {
455 for (Instruction &I : BB) {
456 if (auto *CI = dyn_cast<CallInst>(&I)) {
457 // Possibly throwing call instructions have no actions to take after
458 // an unwind. Ensure they are in the -1 state.
459 if (CI->doesNotThrow())
461 insertStateNumberStore(ParentRegNode, CI, BaseState);
462 } else if (auto *II = dyn_cast<InvokeInst>(&I)) {
463 // Look up the state number of the landingpad this unwinds to.
464 LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst();
465 // FIXME: Why does this assertion fail?
466 //assert(FuncInfo.LandingPadStateMap.count(LPI) && "LP has no state!");
467 int State = FuncInfo.LandingPadStateMap[LPI];
468 insertStateNumberStore(ParentRegNode, II, State);
474 /// Assign every distinct landingpad a unique state number for SEH. Unlike C++
475 /// EH, we can use this very simple algorithm while C++ EH cannot because catch
476 /// handlers aren't outlined and the runtime doesn't have to figure out which
477 /// catch handler frame to unwind to.
478 /// FIXME: __finally blocks are outlined, so this approach may break down there.
479 void WinEHStatePass::addSEHStateStores(Function &F, MachineModuleInfo &MMI) {
480 WinEHFuncInfo &FuncInfo = MMI.getWinEHFuncInfo(&F);
482 // Remember and return the index that we used. We save it in WinEHFuncInfo so
483 // that we can lower llvm.x86.seh.exceptioninfo later in filter functions
484 // without too much trouble.
485 int RegNodeEscapeIndex = escapeRegNode(F);
486 FuncInfo.EHRegNodeEscapeIndex = RegNodeEscapeIndex;
488 // Iterate all the instructions and emit state number stores.
490 SmallPtrSet<BasicBlock *, 4> ExceptBlocks;
491 for (BasicBlock &BB : F) {
492 for (auto I = BB.begin(), E = BB.end(); I != E; ++I) {
493 if (auto *CI = dyn_cast<CallInst>(I)) {
494 auto *Intrin = dyn_cast<IntrinsicInst>(CI);
496 // Calls that "don't throw" are considered to be able to throw asynch
497 // exceptions, but intrinsics cannot.
500 insertStateNumberStore(RegNode, CI, -1);
501 } else if (auto *II = dyn_cast<InvokeInst>(I)) {
502 // Look up the state number of the landingpad this unwinds to.
503 LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst();
505 FuncInfo.LandingPadStateMap.insert(std::make_pair(LPI, CurState));
506 auto Iter = InsertionPair.first;
507 int &State = Iter->second;
508 bool Inserted = InsertionPair.second;
510 // Each action consumes a state number.
511 auto *EHActions = cast<IntrinsicInst>(LPI->getNextNode());
512 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
513 parseEHActions(EHActions, ActionList);
514 assert(!ActionList.empty());
515 CurState += ActionList.size();
516 State += ActionList.size() - 1;
518 // Remember all the __except block targets.
519 for (auto &Handler : ActionList) {
520 if (auto *CH = dyn_cast<CatchHandler>(Handler.get())) {
521 auto *BA = cast<BlockAddress>(CH->getHandlerBlockOrFunc());
522 ExceptBlocks.insert(BA->getBasicBlock());
526 insertStateNumberStore(RegNode, II, State);
531 // Insert llvm.stackrestore into each __except block.
532 Function *StackRestore =
533 Intrinsic::getDeclaration(TheModule, Intrinsic::stackrestore);
534 for (BasicBlock *ExceptBB : ExceptBlocks) {
535 IRBuilder<> Builder(ExceptBB->begin());
537 Builder.CreateLoad(Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
538 Builder.CreateCall(StackRestore, {SP});
542 void WinEHStatePass::insertStateNumberStore(Value *ParentRegNode,
543 Instruction *IP, int State) {
544 IRBuilder<> Builder(IP);
546 Builder.CreateStructGEP(RegNodeTy, ParentRegNode, StateFieldIndex);
547 Builder.CreateStore(Builder.getInt32(State), StateField);