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/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"
36 using namespace llvm::PatternMatch;
38 #define DEBUG_TYPE "winehstate"
41 class WinEHStatePass : public FunctionPass {
43 static char ID; // Pass identification, replacement for typeid.
45 WinEHStatePass() : FunctionPass(ID) {}
47 bool runOnFunction(Function &Fn) override;
49 bool doInitialization(Module &M) override;
51 bool doFinalization(Module &M) override;
53 void getAnalysisUsage(AnalysisUsage &AU) const override;
55 const char *getPassName() const override {
56 return "Windows 32-bit x86 EH state insertion";
60 void emitExceptionRegistrationRecord(Function *F);
62 void linkExceptionRegistration(IRBuilder<> &Builder, Value *RegNode,
64 void unlinkExceptionRegistration(IRBuilder<> &Builder, Value *RegNode);
66 Value *emitEHLSDA(IRBuilder<> &Builder, Function *F);
68 Function *generateLSDAInEAXThunk(Function *ParentFunc);
70 // Module-level type getters.
71 Type *getEHRegistrationType();
72 Type *getSEH3RegistrationType();
73 Type *getSEH4RegistrationType();
74 Type *getCXXEH3RegistrationType();
77 Module *TheModule = nullptr;
78 StructType *EHRegistrationTy = nullptr;
79 StructType *CXXEH3RegistrationTy = nullptr;
80 StructType *SEH3RegistrationTy = nullptr;
81 StructType *SEH4RegistrationTy = nullptr;
84 EHPersonality Personality = EHPersonality::Unknown;
85 Function *PersonalityFn = nullptr;
89 FunctionPass *llvm::createX86WinEHStatePass() { return new WinEHStatePass(); }
91 char WinEHStatePass::ID = 0;
93 bool WinEHStatePass::doInitialization(Module &M) {
98 bool WinEHStatePass::doFinalization(Module &M) {
99 assert(TheModule == &M);
101 EHRegistrationTy = nullptr;
102 CXXEH3RegistrationTy = nullptr;
103 SEH3RegistrationTy = nullptr;
104 SEH4RegistrationTy = nullptr;
108 void WinEHStatePass::getAnalysisUsage(AnalysisUsage &AU) const {
109 // This pass should only insert a stack allocation, memory accesses, and
111 AU.setPreservesCFG();
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())
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();
132 dyn_cast<Function>(LP->getPersonalityFn()->stripPointerCasts());
135 Personality = classifyEHPersonality(PersonalityFn);
136 if (!isMSVCEHPersonality(Personality))
139 emitExceptionRegistrationRecord(&F);
140 // FIXME: State insertion.
142 // Reset per-function state.
143 PersonalityFn = nullptr;
144 Personality = EHPersonality::Unknown;
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;
155 Type *WinEHStatePass::getEHRegistrationType() {
156 if (EHRegistrationTy)
157 return EHRegistrationTy;
158 LLVMContext &Context = TheModule->getContext();
159 EHRegistrationTy = StructType::create(Context, "EHRegistrationNode");
161 EHRegistrationTy->getPointerTo(0), // EHRegistrationNode *Next
162 Type::getInt8PtrTy(Context) // EXCEPTION_DISPOSITION (*Handler)(...)
164 EHRegistrationTy->setBody(FieldTys, false);
165 return EHRegistrationTy;
168 /// The __CxxFrameHandler3 registration node:
169 /// struct CXXExceptionRegistration {
171 /// EHRegistrationNode SubRecord;
172 /// int32_t TryLevel;
174 Type *WinEHStatePass::getCXXEH3RegistrationType() {
175 if (CXXEH3RegistrationTy)
176 return CXXEH3RegistrationTy;
177 LLVMContext &Context = TheModule->getContext();
179 Type::getInt8PtrTy(Context), // void *SavedESP
180 getEHRegistrationType(), // EHRegistrationNode SubRecord
181 Type::getInt32Ty(Context) // int32_t TryLevel
183 CXXEH3RegistrationTy =
184 StructType::create(FieldTys, "CXXExceptionRegistration");
185 return CXXEH3RegistrationTy;
188 /// The _except_handler3 registration node:
189 /// struct EH3ExceptionRegistration {
190 /// EHRegistrationNode SubRecord;
191 /// void *ScopeTable;
192 /// int32_t TryLevel;
194 Type *WinEHStatePass::getSEH3RegistrationType() {
195 if (SEH3RegistrationTy)
196 return SEH3RegistrationTy;
197 LLVMContext &Context = TheModule->getContext();
199 getEHRegistrationType(), // EHRegistrationNode SubRecord
200 Type::getInt8PtrTy(Context), // void *ScopeTable
201 Type::getInt32Ty(Context) // int32_t TryLevel
203 SEH3RegistrationTy = StructType::create(FieldTys, "EH3ExceptionRegistration");
204 return SEH3RegistrationTy;
207 /// The _except_handler4 registration node:
208 /// struct EH4ExceptionRegistration {
210 /// _EXCEPTION_POINTERS *ExceptionPointers;
211 /// EHRegistrationNode SubRecord;
212 /// int32_t EncodedScopeTable;
213 /// int32_t TryLevel;
215 Type *WinEHStatePass::getSEH4RegistrationType() {
216 if (SEH4RegistrationTy)
217 return SEH4RegistrationTy;
218 LLVMContext &Context = TheModule->getContext();
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
226 SEH4RegistrationTy = StructType::create(FieldTys, "EH4ExceptionRegistration");
227 return SEH4RegistrationTy;
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);
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));
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);
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));
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);
287 llvm_unreachable("unexpected personality function");
290 // FIXME: Insert an unlink before all returns.
291 for (BasicBlock &BB : *F) {
292 TerminatorInst *T = BB.getTerminator();
293 if (!isa<ReturnInst>(T))
295 Builder.SetInsertPoint(T);
296 unlinkExceptionRegistration(Builder, SubRecord);
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);
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:
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,
319 FunctionType *TrampolineTy =
320 FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 4),
322 FunctionType *TargetFuncTy =
323 FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 5),
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);
344 void WinEHStatePass::linkExceptionRegistration(IRBuilder<> &Builder,
345 Value *RegNode, Value *Handler) {
346 Type *RegNodeTy = getEHRegistrationType();
348 Handler = Builder.CreateBitCast(Handler, Builder.getInt8PtrTy());
349 Builder.CreateStore(Handler, Builder.CreateStructGEP(RegNodeTy, RegNode, 1));
352 Constant::getNullValue(RegNodeTy->getPointerTo()->getPointerTo(257));
353 Value *Next = Builder.CreateLoad(FSZero);
354 Builder.CreateStore(Next, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
356 Builder.CreateStore(RegNode, FSZero);
359 void WinEHStatePass::unlinkExceptionRegistration(IRBuilder<> &Builder,
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());
367 Type *RegNodeTy = getEHRegistrationType();
368 // [fs:00] = RegNode->Next
370 Builder.CreateLoad(Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
372 Constant::getNullValue(RegNodeTy->getPointerTo()->getPointerTo(257));
373 Builder.CreateStore(Next, FSZero);