blob: ee2fb6dae9dcadc9215b0dbf69eaee3f0a2ea00a [file] [log] [blame]
Reid Kleckner0738a9c2015-05-05 17:44:16 +00001//===-- 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"
David Majnemer7e5937b2016-02-17 18:37:11 +000018#include "llvm/ADT/PostOrderIterator.h"
19#include "llvm/Analysis/CFG.h"
David Majnemer70497c62015-12-02 23:06:39 +000020#include "llvm/Analysis/EHPersonalities.h"
Reid Klecknerfe4d4912015-05-28 22:00:24 +000021#include "llvm/CodeGen/MachineModuleInfo.h"
Reid Kleckner0738a9c2015-05-05 17:44:16 +000022#include "llvm/CodeGen/WinEHFuncInfo.h"
David Majnemer7e5937b2016-02-17 18:37:11 +000023#include "llvm/IR/CallSite.h"
24#include "llvm/IR/Function.h"
Reid Kleckner0738a9c2015-05-05 17:44:16 +000025#include "llvm/IR/Instructions.h"
26#include "llvm/IR/IntrinsicInst.h"
David Majnemerefb41742016-02-01 04:28:59 +000027#include "llvm/IR/IRBuilder.h"
Reid Kleckner0738a9c2015-05-05 17:44:16 +000028#include "llvm/IR/Module.h"
Reid Kleckner0738a9c2015-05-05 17:44:16 +000029#include "llvm/Pass.h"
David Majnemer7e5937b2016-02-17 18:37:11 +000030#include "llvm/Support/Debug.h"
31#include <deque>
Reid Kleckner0738a9c2015-05-05 17:44:16 +000032
33using namespace llvm;
Reid Kleckner0738a9c2015-05-05 17:44:16 +000034
35#define DEBUG_TYPE "winehstate"
36
David Majnemerefb41742016-02-01 04:28:59 +000037namespace llvm {
38void initializeWinEHStatePassPass(PassRegistry &);
39}
David Majnemer0ad363e2015-08-18 19:07:12 +000040
Reid Kleckner0738a9c2015-05-05 17:44:16 +000041namespace {
David Majnemer7e5937b2016-02-17 18:37:11 +000042const int OverdefinedState = INT_MIN;
43
Reid Kleckner0738a9c2015-05-05 17:44:16 +000044class WinEHStatePass : public FunctionPass {
45public:
46 static char ID; // Pass identification, replacement for typeid.
47
David Majnemer0ad363e2015-08-18 19:07:12 +000048 WinEHStatePass() : FunctionPass(ID) {
49 initializeWinEHStatePassPass(*PassRegistry::getPassRegistry());
50 }
Reid Kleckner0738a9c2015-05-05 17:44:16 +000051
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
64private:
65 void emitExceptionRegistrationRecord(Function *F);
66
Reid Kleckner2bc93ca2015-06-10 01:02:30 +000067 void linkExceptionRegistration(IRBuilder<> &Builder, Function *Handler);
Reid Klecknerfe4d4912015-05-28 22:00:24 +000068 void unlinkExceptionRegistration(IRBuilder<> &Builder);
Reid Klecknerc20276d2015-11-17 21:10:25 +000069 void addStateStores(Function &F, WinEHFuncInfo &FuncInfo);
David Majnemerefb41742016-02-01 04:28:59 +000070 void insertStateNumberStore(Instruction *IP, int State);
Reid Kleckner0738a9c2015-05-05 17:44:16 +000071
Reid Kleckner2632f0d2015-05-20 23:08:04 +000072 Value *emitEHLSDA(IRBuilder<> &Builder, Function *F);
73
74 Function *generateLSDAInEAXThunk(Function *ParentFunc);
75
Reid Kleckner0738a9c2015-05-05 17:44:16 +000076 // Module-level type getters.
Reid Klecknere6531a552015-05-29 22:57:46 +000077 Type *getEHLinkRegistrationType();
78 Type *getSEHRegistrationType();
79 Type *getCXXEHRegistrationType();
Reid Kleckner0738a9c2015-05-05 17:44:16 +000080
81 // Per-module data.
82 Module *TheModule = nullptr;
Reid Klecknere6531a552015-05-29 22:57:46 +000083 StructType *EHLinkRegistrationTy = nullptr;
84 StructType *CXXEHRegistrationTy = nullptr;
85 StructType *SEHRegistrationTy = nullptr;
Reid Klecknerb7403332015-06-08 22:43:32 +000086 Function *FrameRecover = nullptr;
87 Function *FrameAddress = nullptr;
88 Function *FrameEscape = nullptr;
Reid Kleckner0738a9c2015-05-05 17:44:16 +000089
90 // Per-function state
91 EHPersonality Personality = EHPersonality::Unknown;
92 Function *PersonalityFn = nullptr;
David Majnemer7e5937b2016-02-17 18:37:11 +000093 bool UseStackGuard = false;
94 int ParentBaseState;
Reid Klecknerfe4d4912015-05-28 22:00:24 +000095
96 /// The stack allocation containing all EH data, including the link in the
97 /// fs:00 chain and the current state.
98 AllocaInst *RegNode = nullptr;
99
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000100 /// The index of the state field of RegNode.
101 int StateFieldIndex = ~0U;
102
103 /// The linked list node subobject inside of RegNode.
104 Value *Link = nullptr;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000105};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000106}
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000107
108FunctionPass *llvm::createX86WinEHStatePass() { return new WinEHStatePass(); }
109
110char WinEHStatePass::ID = 0;
111
David Majnemer0ad363e2015-08-18 19:07:12 +0000112INITIALIZE_PASS(WinEHStatePass, "x86-winehstate",
113 "Insert stores for EH state numbers", false, false)
114
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000115bool WinEHStatePass::doInitialization(Module &M) {
116 TheModule = &M;
Reid Kleckner60381792015-07-07 22:25:32 +0000117 FrameEscape = Intrinsic::getDeclaration(TheModule, Intrinsic::localescape);
118 FrameRecover = Intrinsic::getDeclaration(TheModule, Intrinsic::localrecover);
Reid Klecknerb7403332015-06-08 22:43:32 +0000119 FrameAddress = Intrinsic::getDeclaration(TheModule, Intrinsic::frameaddress);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000120 return false;
121}
122
123bool WinEHStatePass::doFinalization(Module &M) {
124 assert(TheModule == &M);
125 TheModule = nullptr;
Reid Klecknere6531a552015-05-29 22:57:46 +0000126 EHLinkRegistrationTy = nullptr;
127 CXXEHRegistrationTy = nullptr;
128 SEHRegistrationTy = nullptr;
Reid Klecknerb7403332015-06-08 22:43:32 +0000129 FrameEscape = nullptr;
130 FrameRecover = nullptr;
131 FrameAddress = nullptr;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000132 return false;
133}
134
135void WinEHStatePass::getAnalysisUsage(AnalysisUsage &AU) const {
136 // This pass should only insert a stack allocation, memory accesses, and
Reid Kleckner60381792015-07-07 22:25:32 +0000137 // localrecovers.
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000138 AU.setPreservesCFG();
139}
140
141bool WinEHStatePass::runOnFunction(Function &F) {
Joseph Tremoulet2afea542015-10-06 20:28:16 +0000142 // Check the personality. Do nothing if this personality doesn't use funclets.
David Majnemer7fddecc2015-06-17 20:52:32 +0000143 if (!F.hasPersonalityFn())
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000144 return false;
145 PersonalityFn =
David Majnemer7fddecc2015-06-17 20:52:32 +0000146 dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000147 if (!PersonalityFn)
148 return false;
149 Personality = classifyEHPersonality(PersonalityFn);
Joseph Tremoulet2afea542015-10-06 20:28:16 +0000150 if (!isFuncletEHPersonality(Personality))
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000151 return false;
152
Reid Kleckner84ebff42015-09-16 17:19:44 +0000153 // Skip this function if there are no EH pads and we aren't using IR-level
154 // outlining.
David Majnemerbfa5b982015-10-10 00:04:29 +0000155 bool HasPads = false;
156 for (BasicBlock &BB : F) {
157 if (BB.isEHPad()) {
158 HasPads = true;
159 break;
Reid Kleckner84ebff42015-09-16 17:19:44 +0000160 }
Reid Kleckner84ebff42015-09-16 17:19:44 +0000161 }
David Majnemerbfa5b982015-10-10 00:04:29 +0000162 if (!HasPads)
163 return false;
Reid Kleckner84ebff42015-09-16 17:19:44 +0000164
Reid Kleckner173a7252015-05-29 21:58:11 +0000165 // Disable frame pointer elimination in this function.
166 // FIXME: Do the nested handlers need to keep the parent ebp in ebp, or can we
167 // use an arbitrary register?
168 F.addFnAttr("no-frame-pointer-elim", "true");
169
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000170 emitExceptionRegistrationRecord(&F);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000171
Reid Klecknerc20276d2015-11-17 21:10:25 +0000172 // The state numbers calculated here in IR must agree with what we calculate
173 // later on for the MachineFunction. In particular, if an IR pass deletes an
174 // unreachable EH pad after this point before machine CFG construction, we
175 // will be in trouble. If this assumption is ever broken, we should turn the
176 // numbers into an immutable analysis pass.
177 WinEHFuncInfo FuncInfo;
178 addStateStores(F, FuncInfo);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000179
180 // Reset per-function state.
181 PersonalityFn = nullptr;
182 Personality = EHPersonality::Unknown;
David Majnemer7e5937b2016-02-17 18:37:11 +0000183 UseStackGuard = false;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000184 return true;
185}
186
187/// Get the common EH registration subobject:
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000188/// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
189/// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000190/// struct EHRegistrationNode {
191/// EHRegistrationNode *Next;
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000192/// PEXCEPTION_ROUTINE Handler;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000193/// };
Reid Klecknere6531a552015-05-29 22:57:46 +0000194Type *WinEHStatePass::getEHLinkRegistrationType() {
195 if (EHLinkRegistrationTy)
196 return EHLinkRegistrationTy;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000197 LLVMContext &Context = TheModule->getContext();
Reid Klecknere6531a552015-05-29 22:57:46 +0000198 EHLinkRegistrationTy = StructType::create(Context, "EHRegistrationNode");
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000199 Type *FieldTys[] = {
Reid Klecknere6531a552015-05-29 22:57:46 +0000200 EHLinkRegistrationTy->getPointerTo(0), // EHRegistrationNode *Next
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000201 Type::getInt8PtrTy(Context) // EXCEPTION_DISPOSITION (*Handler)(...)
202 };
Reid Klecknere6531a552015-05-29 22:57:46 +0000203 EHLinkRegistrationTy->setBody(FieldTys, false);
204 return EHLinkRegistrationTy;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000205}
206
207/// The __CxxFrameHandler3 registration node:
208/// struct CXXExceptionRegistration {
209/// void *SavedESP;
210/// EHRegistrationNode SubRecord;
211/// int32_t TryLevel;
212/// };
Reid Klecknere6531a552015-05-29 22:57:46 +0000213Type *WinEHStatePass::getCXXEHRegistrationType() {
214 if (CXXEHRegistrationTy)
215 return CXXEHRegistrationTy;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000216 LLVMContext &Context = TheModule->getContext();
217 Type *FieldTys[] = {
218 Type::getInt8PtrTy(Context), // void *SavedESP
Reid Klecknere6531a552015-05-29 22:57:46 +0000219 getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000220 Type::getInt32Ty(Context) // int32_t TryLevel
221 };
Reid Klecknere6531a552015-05-29 22:57:46 +0000222 CXXEHRegistrationTy =
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000223 StructType::create(FieldTys, "CXXExceptionRegistration");
Reid Klecknere6531a552015-05-29 22:57:46 +0000224 return CXXEHRegistrationTy;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000225}
226
Reid Klecknere6531a552015-05-29 22:57:46 +0000227/// The _except_handler3/4 registration node:
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000228/// struct EH4ExceptionRegistration {
229/// void *SavedESP;
230/// _EXCEPTION_POINTERS *ExceptionPointers;
231/// EHRegistrationNode SubRecord;
232/// int32_t EncodedScopeTable;
233/// int32_t TryLevel;
234/// };
Reid Klecknere6531a552015-05-29 22:57:46 +0000235Type *WinEHStatePass::getSEHRegistrationType() {
236 if (SEHRegistrationTy)
237 return SEHRegistrationTy;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000238 LLVMContext &Context = TheModule->getContext();
239 Type *FieldTys[] = {
240 Type::getInt8PtrTy(Context), // void *SavedESP
241 Type::getInt8PtrTy(Context), // void *ExceptionPointers
Reid Klecknere6531a552015-05-29 22:57:46 +0000242 getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000243 Type::getInt32Ty(Context), // int32_t EncodedScopeTable
244 Type::getInt32Ty(Context) // int32_t TryLevel
245 };
Reid Klecknere6531a552015-05-29 22:57:46 +0000246 SEHRegistrationTy = StructType::create(FieldTys, "SEHExceptionRegistration");
247 return SEHRegistrationTy;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000248}
249
250// Emit an exception registration record. These are stack allocations with the
251// common subobject of two pointers: the previous registration record (the old
252// fs:00) and the personality function for the current frame. The data before
253// and after that is personality function specific.
254void WinEHStatePass::emitExceptionRegistrationRecord(Function *F) {
255 assert(Personality == EHPersonality::MSVC_CXX ||
256 Personality == EHPersonality::MSVC_X86SEH);
257
David Majnemerefb41742016-02-01 04:28:59 +0000258 // Struct type of RegNode. Used for GEPing.
259 Type *RegNodeTy;
260
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000261 IRBuilder<> Builder(&F->getEntryBlock(), F->getEntryBlock().begin());
262 Type *Int8PtrType = Builder.getInt8PtrTy();
Reid Klecknere6531a552015-05-29 22:57:46 +0000263 if (Personality == EHPersonality::MSVC_CXX) {
264 RegNodeTy = getCXXEHRegistrationType();
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000265 RegNode = Builder.CreateAlloca(RegNodeTy);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000266 // SavedESP = llvm.stacksave()
267 Value *SP = Builder.CreateCall(
David Blaikieff6409d2015-05-18 22:13:54 +0000268 Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000269 Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
270 // TryLevel = -1
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000271 StateFieldIndex = 2;
David Majnemer7e5937b2016-02-17 18:37:11 +0000272 ParentBaseState = -1;
273 insertStateNumberStore(&*Builder.GetInsertPoint(), ParentBaseState);
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000274 // Handler = __ehhandler$F
275 Function *Trampoline = generateLSDAInEAXThunk(F);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000276 Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 1);
277 linkExceptionRegistration(Builder, Trampoline);
Reid Klecknere6531a552015-05-29 22:57:46 +0000278 } else if (Personality == EHPersonality::MSVC_X86SEH) {
279 // If _except_handler4 is in use, some additional guard checks and prologue
280 // stuff is required.
Reid Klecknere6531a552015-05-29 22:57:46 +0000281 RegNodeTy = getSEHRegistrationType();
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000282 RegNode = Builder.CreateAlloca(RegNodeTy);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000283 // SavedESP = llvm.stacksave()
284 Value *SP = Builder.CreateCall(
David Blaikieff6409d2015-05-18 22:13:54 +0000285 Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000286 Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
Reid Klecknere6531a552015-05-29 22:57:46 +0000287 // TryLevel = -2 / -1
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000288 StateFieldIndex = 4;
David Majnemer7e5937b2016-02-17 18:37:11 +0000289 StringRef PersonalityName = PersonalityFn->getName();
290 UseStackGuard = (PersonalityName == "_except_handler4");
291 ParentBaseState = UseStackGuard ? -2 : -1;
292 insertStateNumberStore(&*Builder.GetInsertPoint(), ParentBaseState);
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000293 // ScopeTable = llvm.x86.seh.lsda(F)
294 Value *FI8 = Builder.CreateBitCast(F, Int8PtrType);
295 Value *LSDA = Builder.CreateCall(
296 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
Reid Klecknere6531a552015-05-29 22:57:46 +0000297 Type *Int32Ty = Type::getInt32Ty(TheModule->getContext());
298 LSDA = Builder.CreatePtrToInt(LSDA, Int32Ty);
299 // If using _except_handler4, xor the address of the table with
300 // __security_cookie.
301 if (UseStackGuard) {
302 Value *Cookie =
303 TheModule->getOrInsertGlobal("__security_cookie", Int32Ty);
304 Value *Val = Builder.CreateLoad(Int32Ty, Cookie);
305 LSDA = Builder.CreateXor(LSDA, Val);
306 }
307 Builder.CreateStore(LSDA, Builder.CreateStructGEP(RegNodeTy, RegNode, 3));
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000308 Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 2);
309 linkExceptionRegistration(Builder, PersonalityFn);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000310 } else {
311 llvm_unreachable("unexpected personality function");
312 }
313
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000314 // Insert an unlink before all returns.
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000315 for (BasicBlock &BB : *F) {
316 TerminatorInst *T = BB.getTerminator();
317 if (!isa<ReturnInst>(T))
318 continue;
319 Builder.SetInsertPoint(T);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000320 unlinkExceptionRegistration(Builder);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000321 }
322}
323
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000324Value *WinEHStatePass::emitEHLSDA(IRBuilder<> &Builder, Function *F) {
325 Value *FI8 = Builder.CreateBitCast(F, Type::getInt8PtrTy(F->getContext()));
326 return Builder.CreateCall(
327 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
328}
329
330/// Generate a thunk that puts the LSDA of ParentFunc in EAX and then calls
331/// PersonalityFn, forwarding the parameters passed to PEXCEPTION_ROUTINE:
332/// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
333/// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
334/// We essentially want this code:
335/// movl $lsda, %eax
336/// jmpl ___CxxFrameHandler3
337Function *WinEHStatePass::generateLSDAInEAXThunk(Function *ParentFunc) {
338 LLVMContext &Context = ParentFunc->getContext();
339 Type *Int32Ty = Type::getInt32Ty(Context);
340 Type *Int8PtrType = Type::getInt8PtrTy(Context);
341 Type *ArgTys[5] = {Int8PtrType, Int8PtrType, Int8PtrType, Int8PtrType,
342 Int8PtrType};
343 FunctionType *TrampolineTy =
344 FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 4),
345 /*isVarArg=*/false);
346 FunctionType *TargetFuncTy =
347 FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 5),
348 /*isVarArg=*/false);
Reid Kleckner5f4dd922015-07-13 17:55:14 +0000349 Function *Trampoline =
350 Function::Create(TrampolineTy, GlobalValue::InternalLinkage,
351 Twine("__ehhandler$") + GlobalValue::getRealLinkageName(
352 ParentFunc->getName()),
353 TheModule);
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000354 BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", Trampoline);
355 IRBuilder<> Builder(EntryBB);
356 Value *LSDA = emitEHLSDA(Builder, ParentFunc);
357 Value *CastPersonality =
358 Builder.CreateBitCast(PersonalityFn, TargetFuncTy->getPointerTo());
359 auto AI = Trampoline->arg_begin();
Duncan P. N. Exon Smithd77de642015-10-19 21:48:29 +0000360 Value *Args[5] = {LSDA, &*AI++, &*AI++, &*AI++, &*AI++};
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000361 CallInst *Call = Builder.CreateCall(CastPersonality, Args);
362 // Can't use musttail due to prototype mismatch, but we can use tail.
363 Call->setTailCall(true);
364 // Set inreg so we pass it in EAX.
365 Call->addAttribute(1, Attribute::InReg);
366 Builder.CreateRet(Call);
367 return Trampoline;
368}
369
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000370void WinEHStatePass::linkExceptionRegistration(IRBuilder<> &Builder,
Reid Kleckner2bc93ca2015-06-10 01:02:30 +0000371 Function *Handler) {
372 // Emit the .safeseh directive for this function.
373 Handler->addFnAttr("safeseh");
374
Reid Klecknere6531a552015-05-29 22:57:46 +0000375 Type *LinkTy = getEHLinkRegistrationType();
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000376 // Handler = Handler
Reid Kleckner2bc93ca2015-06-10 01:02:30 +0000377 Value *HandlerI8 = Builder.CreateBitCast(Handler, Builder.getInt8PtrTy());
378 Builder.CreateStore(HandlerI8, Builder.CreateStructGEP(LinkTy, Link, 1));
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000379 // Next = [fs:00]
380 Constant *FSZero =
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000381 Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000382 Value *Next = Builder.CreateLoad(FSZero);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000383 Builder.CreateStore(Next, Builder.CreateStructGEP(LinkTy, Link, 0));
384 // [fs:00] = Link
385 Builder.CreateStore(Link, FSZero);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000386}
387
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000388void WinEHStatePass::unlinkExceptionRegistration(IRBuilder<> &Builder) {
389 // Clone Link into the current BB for better address mode folding.
390 if (auto *GEP = dyn_cast<GetElementPtrInst>(Link)) {
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000391 GEP = cast<GetElementPtrInst>(GEP->clone());
392 Builder.Insert(GEP);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000393 Link = GEP;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000394 }
Reid Klecknere6531a552015-05-29 22:57:46 +0000395 Type *LinkTy = getEHLinkRegistrationType();
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000396 // [fs:00] = Link->Next
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000397 Value *Next =
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000398 Builder.CreateLoad(Builder.CreateStructGEP(LinkTy, Link, 0));
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000399 Constant *FSZero =
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000400 Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000401 Builder.CreateStore(Next, FSZero);
402}
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000403
David Majnemer7e5937b2016-02-17 18:37:11 +0000404// Figure out what state we should assign calls in this block.
405static int getBaseStateForBB(DenseMap<BasicBlock *, ColorVector> &BlockColors,
406 WinEHFuncInfo &FuncInfo, BasicBlock *BB) {
407 int BaseState = -1;
408 auto &BBColors = BlockColors[BB];
409
410 assert(BBColors.size() == 1 && "multi-color BB not removed by preparation");
411 BasicBlock *FuncletEntryBB = BBColors.front();
412 if (auto *FuncletPad =
413 dyn_cast<FuncletPadInst>(FuncletEntryBB->getFirstNonPHI())) {
414 auto BaseStateI = FuncInfo.FuncletBaseStateMap.find(FuncletPad);
415 if (BaseStateI != FuncInfo.FuncletBaseStateMap.end())
416 BaseState = BaseStateI->second;
417 }
418
419 return BaseState;
420}
421
422// Calculate the state a call-site is in.
423static int getStateForCallSite(DenseMap<BasicBlock *, ColorVector> &BlockColors,
424 WinEHFuncInfo &FuncInfo, CallSite CS) {
425 if (auto *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
426 // Look up the state number of the EH pad this unwinds to.
427 assert(FuncInfo.InvokeStateMap.count(II) && "invoke has no state!");
428 return FuncInfo.InvokeStateMap[II];
429 }
430 // Possibly throwing call instructions have no actions to take after
431 // an unwind. Ensure they are in the -1 state.
432 return getBaseStateForBB(BlockColors, FuncInfo, CS.getParent());
433}
434
435// Calculate the intersection of all the FinalStates for a BasicBlock's
436// predecessor.
437static int getPredState(DenseMap<BasicBlock *, int> &FinalStates, Function &F,
438 int ParentBaseState, BasicBlock *BB) {
439 // The entry block has no predecessors but we know that the prologue always
440 // sets us up with a fixed state.
441 if (&F.getEntryBlock() == BB)
442 return ParentBaseState;
443
444 // This is an EH Pad, conservatively report this basic block as overdefined.
445 if (BB->isEHPad())
446 return OverdefinedState;
447
448 int CommonState = OverdefinedState;
449 for (BasicBlock *PredBB : predecessors(BB)) {
450 // We didn't manage to get a state for one of these predecessors,
451 // conservatively report this basic block as overdefined.
452 auto PredEndState = FinalStates.find(PredBB);
453 if (PredEndState == FinalStates.end())
454 return OverdefinedState;
455
456 // This code is reachable via exceptional control flow,
457 // conservatively report this basic block as overdefined.
458 if (isa<CatchReturnInst>(PredBB->getTerminator()))
459 return OverdefinedState;
460
461 int PredState = PredEndState->second;
462 assert(PredState != OverdefinedState &&
463 "overdefined BBs shouldn't be in FinalStates");
464 if (CommonState == OverdefinedState)
465 CommonState = PredState;
466
467 // At least two predecessors have different FinalStates,
468 // conservatively report this basic block as overdefined.
469 if (CommonState != PredState)
470 return OverdefinedState;
471 }
472
473 return CommonState;
Nico Weber32ac2732016-02-17 18:48:08 +0000474}
David Majnemer7e5937b2016-02-17 18:37:11 +0000475
476static bool isStateStoreNeeded(EHPersonality Personality, CallSite CS) {
477 if (!CS)
478 return false;
479
480 if (isAsynchronousEHPersonality(Personality))
481 return !CS.doesNotAccessMemory();
482
483 return !CS.doesNotThrow();
484}
485
Reid Klecknerc20276d2015-11-17 21:10:25 +0000486void WinEHStatePass::addStateStores(Function &F, WinEHFuncInfo &FuncInfo) {
487 // Mark the registration node. The backend needs to know which alloca it is so
488 // that it can recover the original frame pointer.
489 IRBuilder<> Builder(RegNode->getParent(), std::next(RegNode->getIterator()));
490 Value *RegNodeI8 = Builder.CreateBitCast(RegNode, Builder.getInt8PtrTy());
491 Builder.CreateCall(
492 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_ehregnode),
493 {RegNodeI8});
Reid Kleckner14e77352015-10-09 23:34:53 +0000494
Reid Klecknerc20276d2015-11-17 21:10:25 +0000495 // Calculate state numbers.
496 if (isAsynchronousEHPersonality(Personality))
497 calculateSEHStateNumbers(&F, FuncInfo);
498 else
499 calculateWinCXXEHStateNumbers(&F, FuncInfo);
Reid Kleckner14e77352015-10-09 23:34:53 +0000500
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000501 // Iterate all the instructions and emit state number stores.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000502 DenseMap<BasicBlock *, ColorVector> BlockColors = colorEHFunclets(F);
David Majnemer7e5937b2016-02-17 18:37:11 +0000503 ReversePostOrderTraversal<Function *> RPOT(&F);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000504
David Majnemer7e5937b2016-02-17 18:37:11 +0000505 // InitialStates yields the state of the first call-site for a BasicBlock.
506 DenseMap<BasicBlock *, int> InitialStates;
507 // FinalStates yields the state of the last call-site for a BasicBlock.
508 DenseMap<BasicBlock *, int> FinalStates;
509 // Worklist used to revisit BasicBlocks with indeterminate
510 // Initial/Final-States.
511 std::deque<BasicBlock *> Worklist;
512 // Fill in InitialStates and FinalStates for BasicBlocks with call-sites.
513 for (BasicBlock *BB : RPOT) {
514 int InitialState = OverdefinedState;
515 int FinalState;
516 if (&F.getEntryBlock() == BB)
517 InitialState = FinalState = ParentBaseState;
518 for (Instruction &I : *BB) {
519 CallSite CS(&I);
520 if (!isStateStoreNeeded(Personality, CS))
David Majnemerf2bb7102016-01-29 05:33:15 +0000521 continue;
522
David Majnemer7e5937b2016-02-17 18:37:11 +0000523 int State = getStateForCallSite(BlockColors, FuncInfo, CS);
524 if (InitialState == OverdefinedState)
525 InitialState = State;
526 FinalState = State;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000527 }
David Majnemer7e5937b2016-02-17 18:37:11 +0000528 // No call-sites in this basic block? That's OK, we will come back to these
529 // in a later pass.
530 if (InitialState == OverdefinedState) {
531 Worklist.push_back(BB);
532 continue;
533 }
534 DEBUG(dbgs() << "X86WinEHState: " << BB->getName()
535 << " InitialState=" << InitialState << '\n');
536 DEBUG(dbgs() << "X86WinEHState: " << BB->getName()
537 << " FinalState=" << FinalState << '\n');
538 InitialStates.insert({BB, InitialState});
539 FinalStates.insert({BB, FinalState});
540 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000541
David Majnemer7e5937b2016-02-17 18:37:11 +0000542 // Try to fill-in InitialStates and FinalStates which have no call-sites.
543 while (!Worklist.empty()) {
544 BasicBlock *BB = Worklist.front();
545 Worklist.pop_front();
546 // This BasicBlock has already been figured out, nothing more we can do.
547 if (InitialStates.count(BB) != 0)
548 continue;
549
550 int PredState = getPredState(FinalStates, F, ParentBaseState, BB);
551 if (PredState == OverdefinedState)
552 continue;
553
554 // We successfully inferred this BasicBlock's state via it's predecessors;
555 // enqueue it's successors to see if we can infer their states.
556 InitialStates.insert({BB, PredState});
557 FinalStates.insert({BB, PredState});
558 for (BasicBlock *SuccBB : successors(BB))
559 Worklist.push_back(SuccBB);
560 }
561
562 // Finally, insert state stores before call-sites which transition us to a new
563 // state.
564 for (BasicBlock *BB : RPOT) {
565 auto &BBColors = BlockColors[BB];
566 BasicBlock *FuncletEntryBB = BBColors.front();
567 if (isa<CleanupPadInst>(FuncletEntryBB->getFirstNonPHI()))
568 continue;
569
570 int PrevState = getPredState(FinalStates, F, ParentBaseState, BB);
571 DEBUG(dbgs() << "X86WinEHState: " << BB->getName()
572 << " PrevState=" << PrevState << '\n');
573
574 for (Instruction &I : *BB) {
575 CallSite CS(&I);
576 if (!isStateStoreNeeded(Personality, CS))
577 continue;
578
579 int State = getStateForCallSite(BlockColors, FuncInfo, CS);
580 if (State != PrevState)
581 insertStateNumberStore(&I, State);
582 PrevState = State;
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000583 }
584 }
585}
586
David Majnemerefb41742016-02-01 04:28:59 +0000587void WinEHStatePass::insertStateNumberStore(Instruction *IP, int State) {
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000588 IRBuilder<> Builder(IP);
589 Value *StateField =
David Majnemerefb41742016-02-01 04:28:59 +0000590 Builder.CreateStructGEP(nullptr, RegNode, StateFieldIndex);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000591 Builder.CreateStore(Builder.getInt32(State), StateField);
592}