db717385da62ced19e3ba09e2cef806391db76ba
[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 llvm { void initializeWinEHStatePassPass(PassRegistry &); }
42
43 namespace {
44 class WinEHStatePass : public FunctionPass {
45 public:
46   static char ID; // Pass identification, replacement for typeid.
47
48   WinEHStatePass() : FunctionPass(ID) {
49     initializeWinEHStatePassPass(*PassRegistry::getPassRegistry());
50   }
51
52   bool runOnFunction(Function &Fn) override;
53
54   bool doInitialization(Module &M) override;
55
56   bool doFinalization(Module &M) override;
57
58   void getAnalysisUsage(AnalysisUsage &AU) const override;
59
60   const char *getPassName() const override {
61     return "Windows 32-bit x86 EH state insertion";
62   }
63
64 private:
65   void emitExceptionRegistrationRecord(Function *F);
66
67   void linkExceptionRegistration(IRBuilder<> &Builder, Function *Handler);
68   void unlinkExceptionRegistration(IRBuilder<> &Builder);
69   void addCXXStateStores(Function &F, WinEHFuncInfo &FuncInfo);
70   void addSEHStateStores(Function &F, WinEHFuncInfo &FuncInfo);
71   void addStateStoresToFunclet(Value *ParentRegNode, WinEHFuncInfo &FuncInfo,
72                                Function &F, int BaseState);
73   void insertStateNumberStore(Value *ParentRegNode, Instruction *IP, int State);
74
75   Value *emitEHLSDA(IRBuilder<> &Builder, Function *F);
76
77   Function *generateLSDAInEAXThunk(Function *ParentFunc);
78
79   int escapeRegNode(Function &F);
80
81   // Module-level type getters.
82   Type *getEHLinkRegistrationType();
83   Type *getSEHRegistrationType();
84   Type *getCXXEHRegistrationType();
85
86   // Per-module data.
87   Module *TheModule = nullptr;
88   StructType *EHLinkRegistrationTy = nullptr;
89   StructType *CXXEHRegistrationTy = nullptr;
90   StructType *SEHRegistrationTy = nullptr;
91   Function *FrameRecover = nullptr;
92   Function *FrameAddress = nullptr;
93   Function *FrameEscape = nullptr;
94   Function *RestoreFrame = nullptr;
95
96   // Per-function state
97   EHPersonality Personality = EHPersonality::Unknown;
98   Function *PersonalityFn = nullptr;
99
100   /// The stack allocation containing all EH data, including the link in the
101   /// fs:00 chain and the current state.
102   AllocaInst *RegNode = nullptr;
103
104   /// Struct type of RegNode. Used for GEPing.
105   Type *RegNodeTy = nullptr;
106
107   /// The index of the state field of RegNode.
108   int StateFieldIndex = ~0U;
109
110   /// The linked list node subobject inside of RegNode.
111   Value *Link = nullptr;
112 };
113 }
114
115 FunctionPass *llvm::createX86WinEHStatePass() { return new WinEHStatePass(); }
116
117 char WinEHStatePass::ID = 0;
118
119 INITIALIZE_PASS(WinEHStatePass, "x86-winehstate",
120                 "Insert stores for EH state numbers", false, false)
121
122 bool WinEHStatePass::doInitialization(Module &M) {
123   TheModule = &M;
124   FrameEscape = Intrinsic::getDeclaration(TheModule, Intrinsic::localescape);
125   FrameRecover = Intrinsic::getDeclaration(TheModule, Intrinsic::localrecover);
126   FrameAddress = Intrinsic::getDeclaration(TheModule, Intrinsic::frameaddress);
127   RestoreFrame =
128       Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_restoreframe);
129   return false;
130 }
131
132 bool WinEHStatePass::doFinalization(Module &M) {
133   assert(TheModule == &M);
134   TheModule = nullptr;
135   EHLinkRegistrationTy = nullptr;
136   CXXEHRegistrationTy = nullptr;
137   SEHRegistrationTy = nullptr;
138   FrameEscape = nullptr;
139   FrameRecover = nullptr;
140   FrameAddress = nullptr;
141   return false;
142 }
143
144 void WinEHStatePass::getAnalysisUsage(AnalysisUsage &AU) const {
145   // This pass should only insert a stack allocation, memory accesses, and
146   // localrecovers.
147   AU.setPreservesCFG();
148 }
149
150 bool WinEHStatePass::runOnFunction(Function &F) {
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   // Disable frame pointer elimination in this function.
175   // FIXME: Do the nested handlers need to keep the parent ebp in ebp, or can we
176   // use an arbitrary register?
177   F.addFnAttr("no-frame-pointer-elim", "true");
178
179   emitExceptionRegistrationRecord(&F);
180
181   auto *MMI = getAnalysisIfAvailable<MachineModuleInfo>();
182   // If MMI is null, create our own WinEHFuncInfo.  This only happens in opt
183   // tests.
184   std::unique_ptr<WinEHFuncInfo> FuncInfoPtr;
185   if (!MMI)
186     FuncInfoPtr.reset(new WinEHFuncInfo());
187   WinEHFuncInfo &FuncInfo =
188       *(MMI ? &MMI->getWinEHFuncInfo(&F) : FuncInfoPtr.get());
189
190   FuncInfo.EHRegNode = RegNode;
191
192   switch (Personality) {
193   default: llvm_unreachable("unexpected personality function");
194   case EHPersonality::MSVC_CXX:
195     addCXXStateStores(F, FuncInfo);
196     break;
197   case EHPersonality::MSVC_X86SEH:
198     addSEHStateStores(F, FuncInfo);
199     break;
200   }
201
202   // Reset per-function state.
203   PersonalityFn = nullptr;
204   Personality = EHPersonality::Unknown;
205   return true;
206 }
207
208 /// Get the common EH registration subobject:
209 ///   typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
210 ///       _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
211 ///   struct EHRegistrationNode {
212 ///     EHRegistrationNode *Next;
213 ///     PEXCEPTION_ROUTINE Handler;
214 ///   };
215 Type *WinEHStatePass::getEHLinkRegistrationType() {
216   if (EHLinkRegistrationTy)
217     return EHLinkRegistrationTy;
218   LLVMContext &Context = TheModule->getContext();
219   EHLinkRegistrationTy = StructType::create(Context, "EHRegistrationNode");
220   Type *FieldTys[] = {
221       EHLinkRegistrationTy->getPointerTo(0), // EHRegistrationNode *Next
222       Type::getInt8PtrTy(Context) // EXCEPTION_DISPOSITION (*Handler)(...)
223   };
224   EHLinkRegistrationTy->setBody(FieldTys, false);
225   return EHLinkRegistrationTy;
226 }
227
228 /// The __CxxFrameHandler3 registration node:
229 ///   struct CXXExceptionRegistration {
230 ///     void *SavedESP;
231 ///     EHRegistrationNode SubRecord;
232 ///     int32_t TryLevel;
233 ///   };
234 Type *WinEHStatePass::getCXXEHRegistrationType() {
235   if (CXXEHRegistrationTy)
236     return CXXEHRegistrationTy;
237   LLVMContext &Context = TheModule->getContext();
238   Type *FieldTys[] = {
239       Type::getInt8PtrTy(Context), // void *SavedESP
240       getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
241       Type::getInt32Ty(Context)    // int32_t TryLevel
242   };
243   CXXEHRegistrationTy =
244       StructType::create(FieldTys, "CXXExceptionRegistration");
245   return CXXEHRegistrationTy;
246 }
247
248 /// The _except_handler3/4 registration node:
249 ///   struct EH4ExceptionRegistration {
250 ///     void *SavedESP;
251 ///     _EXCEPTION_POINTERS *ExceptionPointers;
252 ///     EHRegistrationNode SubRecord;
253 ///     int32_t EncodedScopeTable;
254 ///     int32_t TryLevel;
255 ///   };
256 Type *WinEHStatePass::getSEHRegistrationType() {
257   if (SEHRegistrationTy)
258     return SEHRegistrationTy;
259   LLVMContext &Context = TheModule->getContext();
260   Type *FieldTys[] = {
261       Type::getInt8PtrTy(Context), // void *SavedESP
262       Type::getInt8PtrTy(Context), // void *ExceptionPointers
263       getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
264       Type::getInt32Ty(Context),   // int32_t EncodedScopeTable
265       Type::getInt32Ty(Context)    // int32_t TryLevel
266   };
267   SEHRegistrationTy = StructType::create(FieldTys, "SEHExceptionRegistration");
268   return SEHRegistrationTy;
269 }
270
271 // Emit an exception registration record. These are stack allocations with the
272 // common subobject of two pointers: the previous registration record (the old
273 // fs:00) and the personality function for the current frame. The data before
274 // and after that is personality function specific.
275 void WinEHStatePass::emitExceptionRegistrationRecord(Function *F) {
276   assert(Personality == EHPersonality::MSVC_CXX ||
277          Personality == EHPersonality::MSVC_X86SEH);
278
279   StringRef PersonalityName = PersonalityFn->getName();
280   IRBuilder<> Builder(&F->getEntryBlock(), F->getEntryBlock().begin());
281   Type *Int8PtrType = Builder.getInt8PtrTy();
282   if (Personality == EHPersonality::MSVC_CXX) {
283     RegNodeTy = getCXXEHRegistrationType();
284     RegNode = Builder.CreateAlloca(RegNodeTy);
285     // SavedESP = llvm.stacksave()
286     Value *SP = Builder.CreateCall(
287         Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
288     Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
289     // TryLevel = -1
290     StateFieldIndex = 2;
291     insertStateNumberStore(RegNode, &*Builder.GetInsertPoint(), -1);
292     // Handler = __ehhandler$F
293     Function *Trampoline = generateLSDAInEAXThunk(F);
294     Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 1);
295     linkExceptionRegistration(Builder, Trampoline);
296   } else if (Personality == EHPersonality::MSVC_X86SEH) {
297     // If _except_handler4 is in use, some additional guard checks and prologue
298     // stuff is required.
299     bool UseStackGuard = (PersonalityName == "_except_handler4");
300     RegNodeTy = getSEHRegistrationType();
301     RegNode = Builder.CreateAlloca(RegNodeTy);
302     // SavedESP = llvm.stacksave()
303     Value *SP = Builder.CreateCall(
304         Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
305     Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
306     // TryLevel = -2 / -1
307     StateFieldIndex = 4;
308     insertStateNumberStore(RegNode, &*Builder.GetInsertPoint(),
309                            UseStackGuard ? -2 : -1);
310     // ScopeTable = llvm.x86.seh.lsda(F)
311     Value *FI8 = Builder.CreateBitCast(F, Int8PtrType);
312     Value *LSDA = Builder.CreateCall(
313         Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
314     Type *Int32Ty = Type::getInt32Ty(TheModule->getContext());
315     LSDA = Builder.CreatePtrToInt(LSDA, Int32Ty);
316     // If using _except_handler4, xor the address of the table with
317     // __security_cookie.
318     if (UseStackGuard) {
319       Value *Cookie =
320           TheModule->getOrInsertGlobal("__security_cookie", Int32Ty);
321       Value *Val = Builder.CreateLoad(Int32Ty, Cookie);
322       LSDA = Builder.CreateXor(LSDA, Val);
323     }
324     Builder.CreateStore(LSDA, Builder.CreateStructGEP(RegNodeTy, RegNode, 3));
325     Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 2);
326     linkExceptionRegistration(Builder, PersonalityFn);
327   } else {
328     llvm_unreachable("unexpected personality function");
329   }
330
331   // Insert an unlink before all returns.
332   for (BasicBlock &BB : *F) {
333     TerminatorInst *T = BB.getTerminator();
334     if (!isa<ReturnInst>(T))
335       continue;
336     Builder.SetInsertPoint(T);
337     unlinkExceptionRegistration(Builder);
338   }
339 }
340
341 Value *WinEHStatePass::emitEHLSDA(IRBuilder<> &Builder, Function *F) {
342   Value *FI8 = Builder.CreateBitCast(F, Type::getInt8PtrTy(F->getContext()));
343   return Builder.CreateCall(
344       Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
345 }
346
347 /// Generate a thunk that puts the LSDA of ParentFunc in EAX and then calls
348 /// PersonalityFn, forwarding the parameters passed to PEXCEPTION_ROUTINE:
349 ///   typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
350 ///       _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
351 /// We essentially want this code:
352 ///   movl $lsda, %eax
353 ///   jmpl ___CxxFrameHandler3
354 Function *WinEHStatePass::generateLSDAInEAXThunk(Function *ParentFunc) {
355   LLVMContext &Context = ParentFunc->getContext();
356   Type *Int32Ty = Type::getInt32Ty(Context);
357   Type *Int8PtrType = Type::getInt8PtrTy(Context);
358   Type *ArgTys[5] = {Int8PtrType, Int8PtrType, Int8PtrType, Int8PtrType,
359                      Int8PtrType};
360   FunctionType *TrampolineTy =
361       FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 4),
362                         /*isVarArg=*/false);
363   FunctionType *TargetFuncTy =
364       FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 5),
365                         /*isVarArg=*/false);
366   Function *Trampoline =
367       Function::Create(TrampolineTy, GlobalValue::InternalLinkage,
368                        Twine("__ehhandler$") + GlobalValue::getRealLinkageName(
369                                                    ParentFunc->getName()),
370                        TheModule);
371   BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", Trampoline);
372   IRBuilder<> Builder(EntryBB);
373   Value *LSDA = emitEHLSDA(Builder, ParentFunc);
374   Value *CastPersonality =
375       Builder.CreateBitCast(PersonalityFn, TargetFuncTy->getPointerTo());
376   auto AI = Trampoline->arg_begin();
377   Value *Args[5] = {LSDA, &*AI++, &*AI++, &*AI++, &*AI++};
378   CallInst *Call = Builder.CreateCall(CastPersonality, Args);
379   // Can't use musttail due to prototype mismatch, but we can use tail.
380   Call->setTailCall(true);
381   // Set inreg so we pass it in EAX.
382   Call->addAttribute(1, Attribute::InReg);
383   Builder.CreateRet(Call);
384   return Trampoline;
385 }
386
387 void WinEHStatePass::linkExceptionRegistration(IRBuilder<> &Builder,
388                                                Function *Handler) {
389   // Emit the .safeseh directive for this function.
390   Handler->addFnAttr("safeseh");
391
392   Type *LinkTy = getEHLinkRegistrationType();
393   // Handler = Handler
394   Value *HandlerI8 = Builder.CreateBitCast(Handler, Builder.getInt8PtrTy());
395   Builder.CreateStore(HandlerI8, Builder.CreateStructGEP(LinkTy, Link, 1));
396   // Next = [fs:00]
397   Constant *FSZero =
398       Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
399   Value *Next = Builder.CreateLoad(FSZero);
400   Builder.CreateStore(Next, Builder.CreateStructGEP(LinkTy, Link, 0));
401   // [fs:00] = Link
402   Builder.CreateStore(Link, FSZero);
403 }
404
405 void WinEHStatePass::unlinkExceptionRegistration(IRBuilder<> &Builder) {
406   // Clone Link into the current BB for better address mode folding.
407   if (auto *GEP = dyn_cast<GetElementPtrInst>(Link)) {
408     GEP = cast<GetElementPtrInst>(GEP->clone());
409     Builder.Insert(GEP);
410     Link = GEP;
411   }
412   Type *LinkTy = getEHLinkRegistrationType();
413   // [fs:00] = Link->Next
414   Value *Next =
415       Builder.CreateLoad(Builder.CreateStructGEP(LinkTy, Link, 0));
416   Constant *FSZero =
417       Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
418   Builder.CreateStore(Next, FSZero);
419 }
420
421 void WinEHStatePass::addCXXStateStores(Function &F, WinEHFuncInfo &FuncInfo) {
422   // Set up RegNodeEscapeIndex
423   int RegNodeEscapeIndex = escapeRegNode(F);
424   FuncInfo.EHRegNodeEscapeIndex = RegNodeEscapeIndex;
425
426   calculateWinCXXEHStateNumbers(&F, FuncInfo);
427   addStateStoresToFunclet(RegNode, FuncInfo, F, -1);
428 }
429
430 /// Assign every distinct landingpad a unique state number for SEH. Unlike C++
431 /// EH, we can use this very simple algorithm while C++ EH cannot because catch
432 /// handlers aren't outlined and the runtime doesn't have to figure out which
433 /// catch handler frame to unwind to.
434 void WinEHStatePass::addSEHStateStores(Function &F, WinEHFuncInfo &FuncInfo) {
435   // Remember and return the index that we used. We save it in WinEHFuncInfo so
436   // that we can lower llvm.x86.seh.recoverfp later in filter functions without
437   // too much trouble.
438   int RegNodeEscapeIndex = escapeRegNode(F);
439   FuncInfo.EHRegNodeEscapeIndex = RegNodeEscapeIndex;
440
441   calculateSEHStateNumbers(&F, FuncInfo);
442   addStateStoresToFunclet(RegNode, FuncInfo, F, -1);
443 }
444
445 /// Escape RegNode so that we can access it from child handlers. Find the call
446 /// to localescape, if any, in the entry block and append RegNode to the list
447 /// of arguments.
448 int WinEHStatePass::escapeRegNode(Function &F) {
449   // Find the call to localescape and extract its arguments.
450   IntrinsicInst *EscapeCall = nullptr;
451   for (Instruction &I : F.getEntryBlock()) {
452     IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
453     if (II && II->getIntrinsicID() == Intrinsic::localescape) {
454       EscapeCall = II;
455       break;
456     }
457   }
458   SmallVector<Value *, 8> Args;
459   if (EscapeCall) {
460     auto Ops = EscapeCall->arg_operands();
461     Args.append(Ops.begin(), Ops.end());
462   }
463   Args.push_back(RegNode);
464
465   // Replace the call (if it exists) with new one. Otherwise, insert at the end
466   // of the entry block.
467   Instruction *InsertPt = EscapeCall;
468   if (!EscapeCall)
469     InsertPt = F.getEntryBlock().getTerminator();
470   IRBuilder<> Builder(InsertPt);
471   Builder.CreateCall(FrameEscape, Args);
472   if (EscapeCall)
473     EscapeCall->eraseFromParent();
474   return Args.size() - 1;
475 }
476
477 void WinEHStatePass::addStateStoresToFunclet(Value *ParentRegNode,
478                                              WinEHFuncInfo &FuncInfo,
479                                              Function &F, int BaseState) {
480   // Iterate all the instructions and emit state number stores.
481   for (BasicBlock &BB : F) {
482     for (Instruction &I : BB) {
483       if (auto *CI = dyn_cast<CallInst>(&I)) {
484         // Possibly throwing call instructions have no actions to take after
485         // an unwind. Ensure they are in the -1 state.
486         if (CI->doesNotThrow())
487           continue;
488         insertStateNumberStore(ParentRegNode, CI, BaseState);
489       } else if (auto *II = dyn_cast<InvokeInst>(&I)) {
490         // Look up the state number of the landingpad this unwinds to.
491         Instruction *PadInst = II->getUnwindDest()->getFirstNonPHI();
492         // FIXME: Why does this assertion fail?
493         //assert(FuncInfo.EHPadStateMap.count(PadInst) && "EH Pad has no state!");
494         int State = FuncInfo.EHPadStateMap[PadInst];
495         insertStateNumberStore(ParentRegNode, II, State);
496       }
497     }
498   }
499 }
500
501 void WinEHStatePass::insertStateNumberStore(Value *ParentRegNode,
502                                             Instruction *IP, int State) {
503   IRBuilder<> Builder(IP);
504   Value *StateField =
505       Builder.CreateStructGEP(RegNodeTy, ParentRegNode, StateFieldIndex);
506   Builder.CreateStore(Builder.getInt32(State), StateField);
507 }