[WinEH] Adjust the 32-bit SEH prologue to better match reality
[oota-llvm.git] / lib / Target / X86 / X86WinEHState.cpp
1 //===-- X86WinEHState - Insert EH state updates for win32 exceptions ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "X86.h"
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"
35
36 using namespace llvm;
37 using namespace llvm::PatternMatch;
38
39 #define DEBUG_TYPE "winehstate"
40
41 namespace {
42 class WinEHStatePass : public FunctionPass {
43 public:
44   static char ID; // Pass identification, replacement for typeid.
45
46   WinEHStatePass() : FunctionPass(ID) {}
47
48   bool runOnFunction(Function &Fn) override;
49
50   bool doInitialization(Module &M) override;
51
52   bool doFinalization(Module &M) override;
53
54   void getAnalysisUsage(AnalysisUsage &AU) const override;
55
56   const char *getPassName() const override {
57     return "Windows 32-bit x86 EH state insertion";
58   }
59
60 private:
61   void emitExceptionRegistrationRecord(Function *F);
62
63   void linkExceptionRegistration(IRBuilder<> &Builder, Value *Handler);
64   void unlinkExceptionRegistration(IRBuilder<> &Builder);
65   void addCXXStateStores(Function &F, MachineModuleInfo &MMI);
66   void addCXXStateStoresToFunclet(Value *ParentRegNode, WinEHFuncInfo &FuncInfo,
67                                   Function &F, int BaseState);
68   void insertStateNumberStore(Value *ParentRegNode, Instruction *IP, int State);
69
70   Value *emitEHLSDA(IRBuilder<> &Builder, Function *F);
71
72   Function *generateLSDAInEAXThunk(Function *ParentFunc);
73
74   int escapeRegNode(Function &F);
75
76   // Module-level type getters.
77   Type *getEHLinkRegistrationType();
78   Type *getSEHRegistrationType();
79   Type *getCXXEHRegistrationType();
80
81   // Per-module data.
82   Module *TheModule = nullptr;
83   StructType *EHLinkRegistrationTy = nullptr;
84   StructType *CXXEHRegistrationTy = nullptr;
85   StructType *SEHRegistrationTy = nullptr;
86
87   // Per-function state
88   EHPersonality Personality = EHPersonality::Unknown;
89   Function *PersonalityFn = nullptr;
90
91   /// The stack allocation containing all EH data, including the link in the
92   /// fs:00 chain and the current state.
93   AllocaInst *RegNode = nullptr;
94
95   /// Struct type of RegNode. Used for GEPing.
96   Type *RegNodeTy = nullptr;
97
98   /// The index of the state field of RegNode.
99   int StateFieldIndex = ~0U;
100
101   /// The linked list node subobject inside of RegNode.
102   Value *Link = nullptr;
103 };
104 }
105
106 FunctionPass *llvm::createX86WinEHStatePass() { return new WinEHStatePass(); }
107
108 char WinEHStatePass::ID = 0;
109
110 bool WinEHStatePass::doInitialization(Module &M) {
111   TheModule = &M;
112   return false;
113 }
114
115 bool WinEHStatePass::doFinalization(Module &M) {
116   assert(TheModule == &M);
117   TheModule = nullptr;
118   EHLinkRegistrationTy = nullptr;
119   CXXEHRegistrationTy = nullptr;
120   SEHRegistrationTy = nullptr;
121   return false;
122 }
123
124 void WinEHStatePass::getAnalysisUsage(AnalysisUsage &AU) const {
125   // This pass should only insert a stack allocation, memory accesses, and
126   // framerecovers.
127   AU.setPreservesCFG();
128 }
129
130 bool WinEHStatePass::runOnFunction(Function &F) {
131   // If this is an outlined handler, don't do anything. We'll do state insertion
132   // for it in the parent.
133   StringRef WinEHParentName =
134       F.getFnAttribute("wineh-parent").getValueAsString();
135   if (WinEHParentName != F.getName() && !WinEHParentName.empty())
136     return false;
137
138   // Check the personality. Do nothing if this is not an MSVC personality.
139   LandingPadInst *LP = nullptr;
140   for (BasicBlock &BB : F) {
141     LP = BB.getLandingPadInst();
142     if (LP)
143       break;
144   }
145   if (!LP)
146     return false;
147   PersonalityFn =
148       dyn_cast<Function>(LP->getPersonalityFn()->stripPointerCasts());
149   if (!PersonalityFn)
150     return false;
151   Personality = classifyEHPersonality(PersonalityFn);
152   if (!isMSVCEHPersonality(Personality))
153     return false;
154
155   // Disable frame pointer elimination in this function.
156   // FIXME: Do the nested handlers need to keep the parent ebp in ebp, or can we
157   // use an arbitrary register?
158   F.addFnAttr("no-frame-pointer-elim", "true");
159
160   emitExceptionRegistrationRecord(&F);
161
162   auto *MMIPtr = getAnalysisIfAvailable<MachineModuleInfo>();
163   assert(MMIPtr && "MachineModuleInfo should always be available");
164   MachineModuleInfo &MMI = *MMIPtr;
165   if (Personality == EHPersonality::MSVC_CXX) {
166     addCXXStateStores(F, MMI);
167   }
168
169   // Reset per-function state.
170   PersonalityFn = nullptr;
171   Personality = EHPersonality::Unknown;
172   return true;
173 }
174
175 /// Get the common EH registration subobject:
176 ///   typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
177 ///       _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
178 ///   struct EHRegistrationNode {
179 ///     EHRegistrationNode *Next;
180 ///     PEXCEPTION_ROUTINE Handler;
181 ///   };
182 Type *WinEHStatePass::getEHLinkRegistrationType() {
183   if (EHLinkRegistrationTy)
184     return EHLinkRegistrationTy;
185   LLVMContext &Context = TheModule->getContext();
186   EHLinkRegistrationTy = StructType::create(Context, "EHRegistrationNode");
187   Type *FieldTys[] = {
188       EHLinkRegistrationTy->getPointerTo(0), // EHRegistrationNode *Next
189       Type::getInt8PtrTy(Context) // EXCEPTION_DISPOSITION (*Handler)(...)
190   };
191   EHLinkRegistrationTy->setBody(FieldTys, false);
192   return EHLinkRegistrationTy;
193 }
194
195 /// The __CxxFrameHandler3 registration node:
196 ///   struct CXXExceptionRegistration {
197 ///     void *SavedESP;
198 ///     EHRegistrationNode SubRecord;
199 ///     int32_t TryLevel;
200 ///   };
201 Type *WinEHStatePass::getCXXEHRegistrationType() {
202   if (CXXEHRegistrationTy)
203     return CXXEHRegistrationTy;
204   LLVMContext &Context = TheModule->getContext();
205   Type *FieldTys[] = {
206       Type::getInt8PtrTy(Context), // void *SavedESP
207       getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
208       Type::getInt32Ty(Context)    // int32_t TryLevel
209   };
210   CXXEHRegistrationTy =
211       StructType::create(FieldTys, "CXXExceptionRegistration");
212   return CXXEHRegistrationTy;
213 }
214
215 /// The _except_handler3/4 registration node:
216 ///   struct EH4ExceptionRegistration {
217 ///     void *SavedESP;
218 ///     _EXCEPTION_POINTERS *ExceptionPointers;
219 ///     EHRegistrationNode SubRecord;
220 ///     int32_t EncodedScopeTable;
221 ///     int32_t TryLevel;
222 ///   };
223 Type *WinEHStatePass::getSEHRegistrationType() {
224   if (SEHRegistrationTy)
225     return SEHRegistrationTy;
226   LLVMContext &Context = TheModule->getContext();
227   Type *FieldTys[] = {
228       Type::getInt8PtrTy(Context), // void *SavedESP
229       Type::getInt8PtrTy(Context), // void *ExceptionPointers
230       getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
231       Type::getInt32Ty(Context),   // int32_t EncodedScopeTable
232       Type::getInt32Ty(Context)    // int32_t TryLevel
233   };
234   SEHRegistrationTy = StructType::create(FieldTys, "SEHExceptionRegistration");
235   return SEHRegistrationTy;
236 }
237
238 // Emit an exception registration record. These are stack allocations with the
239 // common subobject of two pointers: the previous registration record (the old
240 // fs:00) and the personality function for the current frame. The data before
241 // and after that is personality function specific.
242 void WinEHStatePass::emitExceptionRegistrationRecord(Function *F) {
243   assert(Personality == EHPersonality::MSVC_CXX ||
244          Personality == EHPersonality::MSVC_X86SEH);
245
246   StringRef PersonalityName = PersonalityFn->getName();
247   IRBuilder<> Builder(&F->getEntryBlock(), F->getEntryBlock().begin());
248   Type *Int8PtrType = Builder.getInt8PtrTy();
249   if (Personality == EHPersonality::MSVC_CXX) {
250     RegNodeTy = getCXXEHRegistrationType();
251     RegNode = Builder.CreateAlloca(RegNodeTy);
252     // FIXME: We can skip this in -GS- mode, when we figure that out.
253     // SavedESP = llvm.stacksave()
254     Value *SP = Builder.CreateCall(
255         Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
256     Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
257     // TryLevel = -1
258     StateFieldIndex = 2;
259     insertStateNumberStore(RegNode, Builder.GetInsertPoint(), -1);
260     // Handler = __ehhandler$F
261     Function *Trampoline = generateLSDAInEAXThunk(F);
262     Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 1);
263     linkExceptionRegistration(Builder, Trampoline);
264   } else if (Personality == EHPersonality::MSVC_X86SEH) {
265     // If _except_handler4 is in use, some additional guard checks and prologue
266     // stuff is required.
267     bool UseStackGuard = (PersonalityName == "_except_handler4");
268     RegNodeTy = getSEHRegistrationType();
269     RegNode = Builder.CreateAlloca(RegNodeTy);
270     // SavedESP = llvm.stacksave()
271     Value *SP = Builder.CreateCall(
272         Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
273     Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
274     // TryLevel = -2 / -1
275     StateFieldIndex = 4;
276     insertStateNumberStore(RegNode, Builder.GetInsertPoint(),
277                            UseStackGuard ? -2 : -1);
278     // ScopeTable = llvm.x86.seh.lsda(F)
279     Value *FI8 = Builder.CreateBitCast(F, Int8PtrType);
280     Value *LSDA = Builder.CreateCall(
281         Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
282     Type *Int32Ty = Type::getInt32Ty(TheModule->getContext());
283     LSDA = Builder.CreatePtrToInt(LSDA, Int32Ty);
284     // If using _except_handler4, xor the address of the table with
285     // __security_cookie.
286     if (UseStackGuard) {
287       Value *Cookie =
288           TheModule->getOrInsertGlobal("__security_cookie", Int32Ty);
289       Value *Val = Builder.CreateLoad(Int32Ty, Cookie);
290       LSDA = Builder.CreateXor(LSDA, Val);
291     }
292     Builder.CreateStore(LSDA, Builder.CreateStructGEP(RegNodeTy, RegNode, 3));
293     Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 2);
294     linkExceptionRegistration(Builder, PersonalityFn);
295   } else {
296     llvm_unreachable("unexpected personality function");
297   }
298
299   // Insert an unlink before all returns.
300   for (BasicBlock &BB : *F) {
301     TerminatorInst *T = BB.getTerminator();
302     if (!isa<ReturnInst>(T))
303       continue;
304     Builder.SetInsertPoint(T);
305     unlinkExceptionRegistration(Builder);
306   }
307 }
308
309 Value *WinEHStatePass::emitEHLSDA(IRBuilder<> &Builder, Function *F) {
310   Value *FI8 = Builder.CreateBitCast(F, Type::getInt8PtrTy(F->getContext()));
311   return Builder.CreateCall(
312       Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
313 }
314
315 /// Generate a thunk that puts the LSDA of ParentFunc in EAX and then calls
316 /// PersonalityFn, forwarding the parameters passed to PEXCEPTION_ROUTINE:
317 ///   typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
318 ///       _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
319 /// We essentially want this code:
320 ///   movl $lsda, %eax
321 ///   jmpl ___CxxFrameHandler3
322 Function *WinEHStatePass::generateLSDAInEAXThunk(Function *ParentFunc) {
323   LLVMContext &Context = ParentFunc->getContext();
324   Type *Int32Ty = Type::getInt32Ty(Context);
325   Type *Int8PtrType = Type::getInt8PtrTy(Context);
326   Type *ArgTys[5] = {Int8PtrType, Int8PtrType, Int8PtrType, Int8PtrType,
327                      Int8PtrType};
328   FunctionType *TrampolineTy =
329       FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 4),
330                         /*isVarArg=*/false);
331   FunctionType *TargetFuncTy =
332       FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 5),
333                         /*isVarArg=*/false);
334   Function *Trampoline = Function::Create(
335       TrampolineTy, GlobalValue::InternalLinkage,
336       Twine("__ehhandler$") + ParentFunc->getName(), TheModule);
337   BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", Trampoline);
338   IRBuilder<> Builder(EntryBB);
339   Value *LSDA = emitEHLSDA(Builder, ParentFunc);
340   Value *CastPersonality =
341       Builder.CreateBitCast(PersonalityFn, TargetFuncTy->getPointerTo());
342   auto AI = Trampoline->arg_begin();
343   Value *Args[5] = {LSDA, AI++, AI++, AI++, AI++};
344   CallInst *Call = Builder.CreateCall(CastPersonality, Args);
345   // Can't use musttail due to prototype mismatch, but we can use tail.
346   Call->setTailCall(true);
347   // Set inreg so we pass it in EAX.
348   Call->addAttribute(1, Attribute::InReg);
349   Builder.CreateRet(Call);
350   return Trampoline;
351 }
352
353 void WinEHStatePass::linkExceptionRegistration(IRBuilder<> &Builder,
354                                                Value *Handler) {
355   Type *LinkTy = getEHLinkRegistrationType();
356   // Handler = Handler
357   Handler = Builder.CreateBitCast(Handler, Builder.getInt8PtrTy());
358   Builder.CreateStore(Handler, Builder.CreateStructGEP(LinkTy, Link, 1));
359   // Next = [fs:00]
360   Constant *FSZero =
361       Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
362   Value *Next = Builder.CreateLoad(FSZero);
363   Builder.CreateStore(Next, Builder.CreateStructGEP(LinkTy, Link, 0));
364   // [fs:00] = Link
365   Builder.CreateStore(Link, FSZero);
366 }
367
368 void WinEHStatePass::unlinkExceptionRegistration(IRBuilder<> &Builder) {
369   // Clone Link into the current BB for better address mode folding.
370   if (auto *GEP = dyn_cast<GetElementPtrInst>(Link)) {
371     GEP = cast<GetElementPtrInst>(GEP->clone());
372     Builder.Insert(GEP);
373     Link = GEP;
374   }
375   Type *LinkTy = getEHLinkRegistrationType();
376   // [fs:00] = Link->Next
377   Value *Next =
378       Builder.CreateLoad(Builder.CreateStructGEP(LinkTy, Link, 0));
379   Constant *FSZero =
380       Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
381   Builder.CreateStore(Next, FSZero);
382 }
383
384 void WinEHStatePass::addCXXStateStores(Function &F, MachineModuleInfo &MMI) {
385   WinEHFuncInfo &FuncInfo = MMI.getWinEHFuncInfo(&F);
386   calculateWinCXXEHStateNumbers(&F, FuncInfo);
387
388   // The base state for the parent is -1.
389   addCXXStateStoresToFunclet(RegNode, FuncInfo, F, -1);
390
391   // Set up RegNodeEscapeIndex
392   int RegNodeEscapeIndex = escapeRegNode(F);
393
394   // Only insert stores in catch handlers.
395   Function *FrameRecover =
396       Intrinsic::getDeclaration(TheModule, Intrinsic::framerecover);
397   Function *FrameAddress =
398       Intrinsic::getDeclaration(TheModule, Intrinsic::frameaddress);
399   Constant *FI8 =
400       ConstantExpr::getBitCast(&F, Type::getInt8PtrTy(TheModule->getContext()));
401   for (auto P : FuncInfo.HandlerBaseState) {
402     Function *Handler = const_cast<Function *>(P.first);
403     int BaseState = P.second;
404     IRBuilder<> Builder(&Handler->getEntryBlock(),
405                         Handler->getEntryBlock().begin());
406     // FIXME: Find and reuse such a call if present.
407     Value *ParentFP = Builder.CreateCall(FrameAddress, {Builder.getInt32(1)});
408     Value *RecoveredRegNode = Builder.CreateCall(
409         FrameRecover, {FI8, ParentFP, Builder.getInt32(RegNodeEscapeIndex)});
410     RecoveredRegNode =
411         Builder.CreateBitCast(RecoveredRegNode, RegNodeTy->getPointerTo(0));
412     addCXXStateStoresToFunclet(RecoveredRegNode, FuncInfo, *Handler, BaseState);
413   }
414 }
415
416 /// Escape RegNode so that we can access it from child handlers. Find the call
417 /// to frameescape, if any, in the entry block and append RegNode to the list
418 /// of arguments.
419 int WinEHStatePass::escapeRegNode(Function &F) {
420   // Find the call to frameescape and extract its arguments.
421   IntrinsicInst *EscapeCall = nullptr;
422   for (Instruction &I : F.getEntryBlock()) {
423     IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
424     if (II && II->getIntrinsicID() == Intrinsic::frameescape) {
425       EscapeCall = II;
426       break;
427     }
428   }
429   SmallVector<Value *, 8> Args;
430   if (EscapeCall) {
431     auto Ops = EscapeCall->arg_operands();
432     Args.append(Ops.begin(), Ops.end());
433   }
434   Args.push_back(RegNode);
435
436   // Replace the call (if it exists) with new one. Otherwise, insert at the end
437   // of the entry block.
438   IRBuilder<> Builder(&F.getEntryBlock(),
439                       EscapeCall ? EscapeCall : F.getEntryBlock().end());
440   Builder.CreateCall(
441       Intrinsic::getDeclaration(TheModule, Intrinsic::frameescape), Args);
442   if (EscapeCall)
443     EscapeCall->eraseFromParent();
444   return Args.size() - 1;
445 }
446
447 void WinEHStatePass::addCXXStateStoresToFunclet(Value *ParentRegNode,
448                                                 WinEHFuncInfo &FuncInfo,
449                                                 Function &F, int BaseState) {
450   // Iterate all the instructions and emit state number stores.
451   for (BasicBlock &BB : F) {
452     for (Instruction &I : BB) {
453       if (auto *CI = dyn_cast<CallInst>(&I)) {
454         // Possibly throwing call instructions have no actions to take after
455         // an unwind. Ensure they are in the -1 state.
456         if (CI->doesNotThrow())
457           continue;
458         insertStateNumberStore(ParentRegNode, CI, BaseState);
459       } else if (auto *II = dyn_cast<InvokeInst>(&I)) {
460         // Look up the state number of the landingpad this unwinds to.
461         LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst();
462         // FIXME: Why does this assertion fail?
463         //assert(FuncInfo.LandingPadStateMap.count(LPI) && "LP has no state!");
464         int State = FuncInfo.LandingPadStateMap[LPI];
465         insertStateNumberStore(ParentRegNode, II, State);
466       }
467     }
468   }
469 }
470
471 void WinEHStatePass::insertStateNumberStore(Value *ParentRegNode,
472                                             Instruction *IP, int State) {
473   IRBuilder<> Builder(IP);
474   Value *StateField =
475       Builder.CreateStructGEP(RegNodeTy, ParentRegNode, StateFieldIndex);
476   Builder.CreateStore(Builder.getInt32(State), StateField);
477 }