e4bbffcc55a3f2bca26eb7b9aaf8500d1f0c21bb
[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   // Module-level type getters.
67   Type *getEHRegistrationType();
68   Type *getSEH3RegistrationType();
69   Type *getSEH4RegistrationType();
70   Type *getCXXEH3RegistrationType();
71
72   // Per-module data.
73   Module *TheModule = nullptr;
74   StructType *EHRegistrationTy = nullptr;
75   StructType *CXXEH3RegistrationTy = nullptr;
76   StructType *SEH3RegistrationTy = nullptr;
77   StructType *SEH4RegistrationTy = nullptr;
78
79   // Per-function state
80   EHPersonality Personality = EHPersonality::Unknown;
81   Function *PersonalityFn = nullptr;
82 };
83 }
84
85 FunctionPass *llvm::createX86WinEHStatePass() { return new WinEHStatePass(); }
86
87 char WinEHStatePass::ID = 0;
88
89 bool WinEHStatePass::doInitialization(Module &M) {
90   TheModule = &M;
91   return false;
92 }
93
94 bool WinEHStatePass::doFinalization(Module &M) {
95   assert(TheModule == &M);
96   TheModule = nullptr;
97   EHRegistrationTy = nullptr;
98   CXXEH3RegistrationTy = nullptr;
99   SEH3RegistrationTy = nullptr;
100   SEH4RegistrationTy = nullptr;
101   return false;
102 }
103
104 void WinEHStatePass::getAnalysisUsage(AnalysisUsage &AU) const {
105   // This pass should only insert a stack allocation, memory accesses, and
106   // framerecovers.
107   AU.setPreservesCFG();
108 }
109
110 bool WinEHStatePass::runOnFunction(Function &F) {
111   // Check the personality. Do nothing if this is not an MSVC personality.
112   LandingPadInst *LP = nullptr;
113   for (BasicBlock &BB : F) {
114     LP = BB.getLandingPadInst();
115     if (LP)
116       break;
117   }
118   if (!LP)
119     return false;
120   PersonalityFn =
121       dyn_cast<Function>(LP->getPersonalityFn()->stripPointerCasts());
122   if (!PersonalityFn)
123     return false;
124   Personality = classifyEHPersonality(PersonalityFn);
125   if (!isMSVCEHPersonality(Personality))
126     return false;
127
128   emitExceptionRegistrationRecord(&F);
129   // FIXME: State insertion.
130
131   // Reset per-function state.
132   PersonalityFn = nullptr;
133   Personality = EHPersonality::Unknown;
134   return true;
135 }
136
137 /// Get the common EH registration subobject:
138 ///   struct EHRegistrationNode {
139 ///     EHRegistrationNode *Next;
140 ///     EXCEPTION_DISPOSITION (*Handler)(...);
141 ///   };
142 Type *WinEHStatePass::getEHRegistrationType() {
143   if (EHRegistrationTy)
144     return EHRegistrationTy;
145   LLVMContext &Context = TheModule->getContext();
146   EHRegistrationTy = StructType::create(Context, "EHRegistrationNode");
147   Type *FieldTys[] = {
148       EHRegistrationTy->getPointerTo(0), // EHRegistrationNode *Next
149       Type::getInt8PtrTy(Context) // EXCEPTION_DISPOSITION (*Handler)(...)
150   };
151   EHRegistrationTy->setBody(FieldTys, false);
152   return EHRegistrationTy;
153 }
154
155 /// The __CxxFrameHandler3 registration node:
156 ///   struct CXXExceptionRegistration {
157 ///     void *SavedESP;
158 ///     EHRegistrationNode SubRecord;
159 ///     int32_t TryLevel;
160 ///   };
161 Type *WinEHStatePass::getCXXEH3RegistrationType() {
162   if (CXXEH3RegistrationTy)
163     return CXXEH3RegistrationTy;
164   LLVMContext &Context = TheModule->getContext();
165   Type *FieldTys[] = {
166       Type::getInt8PtrTy(Context), // void *SavedESP
167       getEHRegistrationType(),     // EHRegistrationNode SubRecord
168       Type::getInt32Ty(Context)    // int32_t TryLevel
169   };
170   CXXEH3RegistrationTy =
171       StructType::create(FieldTys, "CXXExceptionRegistration");
172   return CXXEH3RegistrationTy;
173 }
174
175 /// The _except_handler3 registration node:
176 ///   struct EH3ExceptionRegistration {
177 ///     EHRegistrationNode SubRecord;
178 ///     void *ScopeTable;
179 ///     int32_t TryLevel;
180 ///   };
181 Type *WinEHStatePass::getSEH3RegistrationType() {
182   if (SEH3RegistrationTy)
183     return SEH3RegistrationTy;
184   LLVMContext &Context = TheModule->getContext();
185   Type *FieldTys[] = {
186       getEHRegistrationType(),     // EHRegistrationNode SubRecord
187       Type::getInt8PtrTy(Context), // void *ScopeTable
188       Type::getInt32Ty(Context)    // int32_t TryLevel
189   };
190   SEH3RegistrationTy = StructType::create(FieldTys, "EH3ExceptionRegistration");
191   return SEH3RegistrationTy;
192 }
193
194 /// The _except_handler4 registration node:
195 ///   struct EH4ExceptionRegistration {
196 ///     void *SavedESP;
197 ///     _EXCEPTION_POINTERS *ExceptionPointers;
198 ///     EHRegistrationNode SubRecord;
199 ///     int32_t EncodedScopeTable;
200 ///     int32_t TryLevel;
201 ///   };
202 Type *WinEHStatePass::getSEH4RegistrationType() {
203   if (SEH4RegistrationTy)
204     return SEH4RegistrationTy;
205   LLVMContext &Context = TheModule->getContext();
206   Type *FieldTys[] = {
207       Type::getInt8PtrTy(Context), // void *SavedESP
208       Type::getInt8PtrTy(Context), // void *ExceptionPointers
209       getEHRegistrationType(),     // EHRegistrationNode SubRecord
210       Type::getInt32Ty(Context),   // int32_t EncodedScopeTable
211       Type::getInt32Ty(Context)    // int32_t TryLevel
212   };
213   SEH4RegistrationTy = StructType::create(FieldTys, "EH4ExceptionRegistration");
214   return SEH4RegistrationTy;
215 }
216
217 // Emit an exception registration record. These are stack allocations with the
218 // common subobject of two pointers: the previous registration record (the old
219 // fs:00) and the personality function for the current frame. The data before
220 // and after that is personality function specific.
221 void WinEHStatePass::emitExceptionRegistrationRecord(Function *F) {
222   assert(Personality == EHPersonality::MSVC_CXX ||
223          Personality == EHPersonality::MSVC_X86SEH);
224
225   StringRef PersonalityName = PersonalityFn->getName();
226   IRBuilder<> Builder(&F->getEntryBlock(), F->getEntryBlock().begin());
227   Type *Int8PtrType = Builder.getInt8PtrTy();
228   Value *SubRecord = nullptr;
229   if (PersonalityName == "__CxxFrameHandler3") {
230     Type *RegNodeTy = getCXXEH3RegistrationType();
231     Value *RegNode = Builder.CreateAlloca(RegNodeTy);
232     // FIXME: We can skip this in -GS- mode, when we figure that out.
233     // SavedESP = llvm.stacksave()
234     Value *SP = Builder.CreateCall(
235         Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave));
236     Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
237     // TryLevel = -1
238     Builder.CreateStore(Builder.getInt32(-1),
239                         Builder.CreateStructGEP(RegNodeTy, RegNode, 2));
240     // FIXME: 'Personality' is incorrect here. We need to generate a trampoline
241     // that effectively gets the LSDA.
242     SubRecord = Builder.CreateStructGEP(RegNodeTy, RegNode, 1);
243     linkExceptionRegistration(Builder, SubRecord, PersonalityFn);
244   } else if (PersonalityName == "_except_handler3") {
245     Type *RegNodeTy = getSEH3RegistrationType();
246     Value *RegNode = Builder.CreateAlloca(RegNodeTy);
247     // TryLevel = -1
248     Builder.CreateStore(Builder.getInt32(-1),
249                         Builder.CreateStructGEP(RegNodeTy, RegNode, 2));
250     // FIXME: Generalize llvm.eh.sjljl.lsda for this.
251     // ScopeTable = nullptr
252     Builder.CreateStore(Constant::getNullValue(Int8PtrType),
253                         Builder.CreateStructGEP(RegNodeTy, RegNode, 1));
254     SubRecord = Builder.CreateStructGEP(RegNodeTy, RegNode, 0);
255     linkExceptionRegistration(Builder, SubRecord, PersonalityFn);
256   } else if (PersonalityName == "_except_handler4") {
257     Type *RegNodeTy = getSEH4RegistrationType();
258     Value *RegNode = Builder.CreateAlloca(RegNodeTy);
259     // SavedESP = llvm.stacksave()
260     Value *SP = Builder.CreateCall(
261         Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave));
262     Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
263     // TryLevel = -2
264     Builder.CreateStore(Builder.getInt32(-2),
265                         Builder.CreateStructGEP(RegNodeTy, RegNode, 4));
266     // FIXME: Generalize llvm.eh.sjljl.lsda for this, and then do the stack
267     // cookie xor.
268     // ScopeTable = nullptr
269     Builder.CreateStore(Builder.getInt32(0),
270                         Builder.CreateStructGEP(RegNodeTy, RegNode, 3));
271     SubRecord = Builder.CreateStructGEP(RegNodeTy, RegNode, 2);
272     linkExceptionRegistration(Builder, SubRecord, PersonalityFn);
273   } else {
274     llvm_unreachable("unexpected personality function");
275   }
276
277   // FIXME: Insert an unlink before all returns.
278   for (BasicBlock &BB : *F) {
279     TerminatorInst *T = BB.getTerminator();
280     if (!isa<ReturnInst>(T))
281       continue;
282     Builder.SetInsertPoint(T);
283     unlinkExceptionRegistration(Builder, SubRecord);
284   }
285 }
286
287 void WinEHStatePass::linkExceptionRegistration(IRBuilder<> &Builder,
288                                                Value *RegNode, Value *Handler) {
289   Type *RegNodeTy = getEHRegistrationType();
290   // Handler = Handler
291   Handler = Builder.CreateBitCast(Handler, Builder.getInt8PtrTy());
292   Builder.CreateStore(Handler, Builder.CreateStructGEP(RegNodeTy, RegNode, 1));
293   // Next = [fs:00]
294   Constant *FSZero =
295       Constant::getNullValue(RegNodeTy->getPointerTo()->getPointerTo(257));
296   Value *Next = Builder.CreateLoad(FSZero);
297   Builder.CreateStore(Next, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
298   // [fs:00] = RegNode
299   Builder.CreateStore(RegNode, FSZero);
300 }
301
302 void WinEHStatePass::unlinkExceptionRegistration(IRBuilder<> &Builder,
303                                                  Value *RegNode) {
304   // Clone RegNode into the current BB for better address mode folding.
305   if (auto *GEP = dyn_cast<GetElementPtrInst>(RegNode)) {
306     GEP = cast<GetElementPtrInst>(GEP->clone());
307     Builder.Insert(GEP);
308     RegNode = GEP;
309   }
310   Type *RegNodeTy = getEHRegistrationType();
311   // [fs:00] = RegNode->Next
312   Value *Next =
313       Builder.CreateLoad(Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
314   Constant *FSZero =
315       Constant::getNullValue(RegNodeTy->getPointerTo()->getPointerTo(257));
316   Builder.CreateStore(Next, FSZero);
317 }