[WinEH] Store pointers to the LSDA in the exception registration object
[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/Passes.h"
20 #include "llvm/CodeGen/WinEHFuncInfo.h"
21 #include "llvm/IR/Dominators.h"
22 #include "llvm/IR/Function.h"
23 #include "llvm/IR/IRBuilder.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/PatternMatch.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
32 #include "llvm/Transforms/Utils/Cloning.h"
33 #include "llvm/Transforms/Utils/Local.h"
34
35 using namespace llvm;
36 using namespace llvm::PatternMatch;
37
38 #define DEBUG_TYPE "winehstate"
39
40 namespace {
41 class WinEHStatePass : public FunctionPass {
42 public:
43   static char ID; // Pass identification, replacement for typeid.
44
45   WinEHStatePass() : FunctionPass(ID) {}
46
47   bool runOnFunction(Function &Fn) override;
48
49   bool doInitialization(Module &M) override;
50
51   bool doFinalization(Module &M) override;
52
53   void getAnalysisUsage(AnalysisUsage &AU) const override;
54
55   const char *getPassName() const override {
56     return "Windows 32-bit x86 EH state insertion";
57   }
58
59 private:
60   void emitExceptionRegistrationRecord(Function *F);
61
62   void linkExceptionRegistration(IRBuilder<> &Builder, Value *RegNode,
63                                  Value *Handler);
64   void unlinkExceptionRegistration(IRBuilder<> &Builder, Value *RegNode);
65
66   Value *emitEHLSDA(IRBuilder<> &Builder, Function *F);
67
68   Function *generateLSDAInEAXThunk(Function *ParentFunc);
69
70   // Module-level type getters.
71   Type *getEHRegistrationType();
72   Type *getSEH3RegistrationType();
73   Type *getSEH4RegistrationType();
74   Type *getCXXEH3RegistrationType();
75
76   // Per-module data.
77   Module *TheModule = nullptr;
78   StructType *EHRegistrationTy = nullptr;
79   StructType *CXXEH3RegistrationTy = nullptr;
80   StructType *SEH3RegistrationTy = nullptr;
81   StructType *SEH4RegistrationTy = nullptr;
82
83   // Per-function state
84   EHPersonality Personality = EHPersonality::Unknown;
85   Function *PersonalityFn = nullptr;
86 };
87 }
88
89 FunctionPass *llvm::createX86WinEHStatePass() { return new WinEHStatePass(); }
90
91 char WinEHStatePass::ID = 0;
92
93 bool WinEHStatePass::doInitialization(Module &M) {
94   TheModule = &M;
95   return false;
96 }
97
98 bool WinEHStatePass::doFinalization(Module &M) {
99   assert(TheModule == &M);
100   TheModule = nullptr;
101   EHRegistrationTy = nullptr;
102   CXXEH3RegistrationTy = nullptr;
103   SEH3RegistrationTy = nullptr;
104   SEH4RegistrationTy = nullptr;
105   return false;
106 }
107
108 void WinEHStatePass::getAnalysisUsage(AnalysisUsage &AU) const {
109   // This pass should only insert a stack allocation, memory accesses, and
110   // framerecovers.
111   AU.setPreservesCFG();
112 }
113
114 bool WinEHStatePass::runOnFunction(Function &F) {
115   // If this is an outlined handler, don't do anything. We'll do state insertion
116   // for it in the parent.
117   StringRef WinEHParentName =
118       F.getFnAttribute("wineh-parent").getValueAsString();
119   if (WinEHParentName != F.getName() && !WinEHParentName.empty())
120     return false;
121
122   // Check the personality. Do nothing if this is not an MSVC personality.
123   LandingPadInst *LP = nullptr;
124   for (BasicBlock &BB : F) {
125     LP = BB.getLandingPadInst();
126     if (LP)
127       break;
128   }
129   if (!LP)
130     return false;
131   PersonalityFn =
132       dyn_cast<Function>(LP->getPersonalityFn()->stripPointerCasts());
133   if (!PersonalityFn)
134     return false;
135   Personality = classifyEHPersonality(PersonalityFn);
136   if (!isMSVCEHPersonality(Personality))
137     return false;
138
139   emitExceptionRegistrationRecord(&F);
140   // FIXME: State insertion.
141
142   // Reset per-function state.
143   PersonalityFn = nullptr;
144   Personality = EHPersonality::Unknown;
145   return true;
146 }
147
148 /// Get the common EH registration subobject:
149 ///   typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
150 ///       _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
151 ///   struct EHRegistrationNode {
152 ///     EHRegistrationNode *Next;
153 ///     PEXCEPTION_ROUTINE Handler;
154 ///   };
155 Type *WinEHStatePass::getEHRegistrationType() {
156   if (EHRegistrationTy)
157     return EHRegistrationTy;
158   LLVMContext &Context = TheModule->getContext();
159   EHRegistrationTy = StructType::create(Context, "EHRegistrationNode");
160   Type *FieldTys[] = {
161       EHRegistrationTy->getPointerTo(0), // EHRegistrationNode *Next
162       Type::getInt8PtrTy(Context) // EXCEPTION_DISPOSITION (*Handler)(...)
163   };
164   EHRegistrationTy->setBody(FieldTys, false);
165   return EHRegistrationTy;
166 }
167
168 /// The __CxxFrameHandler3 registration node:
169 ///   struct CXXExceptionRegistration {
170 ///     void *SavedESP;
171 ///     EHRegistrationNode SubRecord;
172 ///     int32_t TryLevel;
173 ///   };
174 Type *WinEHStatePass::getCXXEH3RegistrationType() {
175   if (CXXEH3RegistrationTy)
176     return CXXEH3RegistrationTy;
177   LLVMContext &Context = TheModule->getContext();
178   Type *FieldTys[] = {
179       Type::getInt8PtrTy(Context), // void *SavedESP
180       getEHRegistrationType(),     // EHRegistrationNode SubRecord
181       Type::getInt32Ty(Context)    // int32_t TryLevel
182   };
183   CXXEH3RegistrationTy =
184       StructType::create(FieldTys, "CXXExceptionRegistration");
185   return CXXEH3RegistrationTy;
186 }
187
188 /// The _except_handler3 registration node:
189 ///   struct EH3ExceptionRegistration {
190 ///     EHRegistrationNode SubRecord;
191 ///     void *ScopeTable;
192 ///     int32_t TryLevel;
193 ///   };
194 Type *WinEHStatePass::getSEH3RegistrationType() {
195   if (SEH3RegistrationTy)
196     return SEH3RegistrationTy;
197   LLVMContext &Context = TheModule->getContext();
198   Type *FieldTys[] = {
199       getEHRegistrationType(),     // EHRegistrationNode SubRecord
200       Type::getInt8PtrTy(Context), // void *ScopeTable
201       Type::getInt32Ty(Context)    // int32_t TryLevel
202   };
203   SEH3RegistrationTy = StructType::create(FieldTys, "EH3ExceptionRegistration");
204   return SEH3RegistrationTy;
205 }
206
207 /// The _except_handler4 registration node:
208 ///   struct EH4ExceptionRegistration {
209 ///     void *SavedESP;
210 ///     _EXCEPTION_POINTERS *ExceptionPointers;
211 ///     EHRegistrationNode SubRecord;
212 ///     int32_t EncodedScopeTable;
213 ///     int32_t TryLevel;
214 ///   };
215 Type *WinEHStatePass::getSEH4RegistrationType() {
216   if (SEH4RegistrationTy)
217     return SEH4RegistrationTy;
218   LLVMContext &Context = TheModule->getContext();
219   Type *FieldTys[] = {
220       Type::getInt8PtrTy(Context), // void *SavedESP
221       Type::getInt8PtrTy(Context), // void *ExceptionPointers
222       getEHRegistrationType(),     // EHRegistrationNode SubRecord
223       Type::getInt32Ty(Context),   // int32_t EncodedScopeTable
224       Type::getInt32Ty(Context)    // int32_t TryLevel
225   };
226   SEH4RegistrationTy = StructType::create(FieldTys, "EH4ExceptionRegistration");
227   return SEH4RegistrationTy;
228 }
229
230 // Emit an exception registration record. These are stack allocations with the
231 // common subobject of two pointers: the previous registration record (the old
232 // fs:00) and the personality function for the current frame. The data before
233 // and after that is personality function specific.
234 void WinEHStatePass::emitExceptionRegistrationRecord(Function *F) {
235   assert(Personality == EHPersonality::MSVC_CXX ||
236          Personality == EHPersonality::MSVC_X86SEH);
237
238   StringRef PersonalityName = PersonalityFn->getName();
239   IRBuilder<> Builder(&F->getEntryBlock(), F->getEntryBlock().begin());
240   Type *Int8PtrType = Builder.getInt8PtrTy();
241   Value *SubRecord = nullptr;
242   if (PersonalityName == "__CxxFrameHandler3") {
243     Type *RegNodeTy = getCXXEH3RegistrationType();
244     Value *RegNode = Builder.CreateAlloca(RegNodeTy);
245     // FIXME: We can skip this in -GS- mode, when we figure that out.
246     // SavedESP = llvm.stacksave()
247     Value *SP = Builder.CreateCall(
248         Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
249     Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
250     // TryLevel = -1
251     Builder.CreateStore(Builder.getInt32(-1),
252                         Builder.CreateStructGEP(RegNodeTy, RegNode, 2));
253     // Handler = __ehhandler$F
254     Function *Trampoline = generateLSDAInEAXThunk(F);
255     SubRecord = Builder.CreateStructGEP(RegNodeTy, RegNode, 1);
256     linkExceptionRegistration(Builder, SubRecord, Trampoline);
257   } else if (PersonalityName == "_except_handler3") {
258     Type *RegNodeTy = getSEH3RegistrationType();
259     Value *RegNode = Builder.CreateAlloca(RegNodeTy);
260     // TryLevel = -1
261     Builder.CreateStore(Builder.getInt32(-1),
262                         Builder.CreateStructGEP(RegNodeTy, RegNode, 2));
263     // ScopeTable = llvm.x86.seh.lsda(F)
264     Value *LSDA = emitEHLSDA(Builder, F);
265     Builder.CreateStore(LSDA, Builder.CreateStructGEP(RegNodeTy, RegNode, 1));
266     SubRecord = Builder.CreateStructGEP(RegNodeTy, RegNode, 0);
267     linkExceptionRegistration(Builder, SubRecord, PersonalityFn);
268   } else if (PersonalityName == "_except_handler4") {
269     Type *RegNodeTy = getSEH4RegistrationType();
270     Value *RegNode = Builder.CreateAlloca(RegNodeTy);
271     // SavedESP = llvm.stacksave()
272     Value *SP = Builder.CreateCall(
273         Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
274     Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
275     // TryLevel = -2
276     Builder.CreateStore(Builder.getInt32(-2),
277                         Builder.CreateStructGEP(RegNodeTy, RegNode, 4));
278     // FIXME: XOR the LSDA with __security_cookie.
279     // ScopeTable = llvm.x86.seh.lsda(F)
280     Value *FI8 = Builder.CreateBitCast(F, Int8PtrType);
281     Value *LSDA = Builder.CreateCall(
282         Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
283     Builder.CreateStore(LSDA, Builder.CreateStructGEP(RegNodeTy, RegNode, 1));
284     SubRecord = Builder.CreateStructGEP(RegNodeTy, RegNode, 2);
285     linkExceptionRegistration(Builder, SubRecord, PersonalityFn);
286   } else {
287     llvm_unreachable("unexpected personality function");
288   }
289
290   // FIXME: Insert an unlink before all returns.
291   for (BasicBlock &BB : *F) {
292     TerminatorInst *T = BB.getTerminator();
293     if (!isa<ReturnInst>(T))
294       continue;
295     Builder.SetInsertPoint(T);
296     unlinkExceptionRegistration(Builder, SubRecord);
297   }
298 }
299
300 Value *WinEHStatePass::emitEHLSDA(IRBuilder<> &Builder, Function *F) {
301   Value *FI8 = Builder.CreateBitCast(F, Type::getInt8PtrTy(F->getContext()));
302   return Builder.CreateCall(
303       Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
304 }
305
306 /// Generate a thunk that puts the LSDA of ParentFunc in EAX and then calls
307 /// PersonalityFn, forwarding the parameters passed to PEXCEPTION_ROUTINE:
308 ///   typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
309 ///       _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
310 /// We essentially want this code:
311 ///   movl $lsda, %eax
312 ///   jmpl ___CxxFrameHandler3
313 Function *WinEHStatePass::generateLSDAInEAXThunk(Function *ParentFunc) {
314   LLVMContext &Context = ParentFunc->getContext();
315   Type *Int32Ty = Type::getInt32Ty(Context);
316   Type *Int8PtrType = Type::getInt8PtrTy(Context);
317   Type *ArgTys[5] = {Int8PtrType, Int8PtrType, Int8PtrType, Int8PtrType,
318                      Int8PtrType};
319   FunctionType *TrampolineTy =
320       FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 4),
321                         /*isVarArg=*/false);
322   FunctionType *TargetFuncTy =
323       FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 5),
324                         /*isVarArg=*/false);
325   Function *Trampoline = Function::Create(
326       TrampolineTy, GlobalValue::InternalLinkage,
327       Twine("__ehhandler$") + ParentFunc->getName(), TheModule);
328   BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", Trampoline);
329   IRBuilder<> Builder(EntryBB);
330   Value *LSDA = emitEHLSDA(Builder, ParentFunc);
331   Value *CastPersonality =
332       Builder.CreateBitCast(PersonalityFn, TargetFuncTy->getPointerTo());
333   auto AI = Trampoline->arg_begin();
334   Value *Args[5] = {LSDA, AI++, AI++, AI++, AI++};
335   CallInst *Call = Builder.CreateCall(CastPersonality, Args);
336   // Can't use musttail due to prototype mismatch, but we can use tail.
337   Call->setTailCall(true);
338   // Set inreg so we pass it in EAX.
339   Call->addAttribute(1, Attribute::InReg);
340   Builder.CreateRet(Call);
341   return Trampoline;
342 }
343
344 void WinEHStatePass::linkExceptionRegistration(IRBuilder<> &Builder,
345                                                Value *RegNode, Value *Handler) {
346   Type *RegNodeTy = getEHRegistrationType();
347   // Handler = Handler
348   Handler = Builder.CreateBitCast(Handler, Builder.getInt8PtrTy());
349   Builder.CreateStore(Handler, Builder.CreateStructGEP(RegNodeTy, RegNode, 1));
350   // Next = [fs:00]
351   Constant *FSZero =
352       Constant::getNullValue(RegNodeTy->getPointerTo()->getPointerTo(257));
353   Value *Next = Builder.CreateLoad(FSZero);
354   Builder.CreateStore(Next, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
355   // [fs:00] = RegNode
356   Builder.CreateStore(RegNode, FSZero);
357 }
358
359 void WinEHStatePass::unlinkExceptionRegistration(IRBuilder<> &Builder,
360                                                  Value *RegNode) {
361   // Clone RegNode into the current BB for better address mode folding.
362   if (auto *GEP = dyn_cast<GetElementPtrInst>(RegNode)) {
363     GEP = cast<GetElementPtrInst>(GEP->clone());
364     Builder.Insert(GEP);
365     RegNode = GEP;
366   }
367   Type *RegNodeTy = getEHRegistrationType();
368   // [fs:00] = RegNode->Next
369   Value *Next =
370       Builder.CreateLoad(Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
371   Constant *FSZero =
372       Constant::getNullValue(RegNodeTy->getPointerTo()->getPointerTo(257));
373   Builder.CreateStore(Next, FSZero);
374 }