blob: ba82006511754d5b3c310d84c1bfe6624ded24b9 [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
David Majnemere60ee3b2016-02-29 19:16:03 +000076 bool isStateStoreNeeded(EHPersonality Personality, CallSite CS);
77 void rewriteSetJmpCallSite(IRBuilder<> &Builder, Function &F, CallSite CS,
78 Value *State);
79 int getBaseStateForBB(DenseMap<BasicBlock *, ColorVector> &BlockColors,
80 WinEHFuncInfo &FuncInfo, BasicBlock *BB);
81 int getStateForCallSite(DenseMap<BasicBlock *, ColorVector> &BlockColors,
82 WinEHFuncInfo &FuncInfo, CallSite CS);
83
Reid Kleckner0738a9c2015-05-05 17:44:16 +000084 // Module-level type getters.
Reid Klecknere6531a552015-05-29 22:57:46 +000085 Type *getEHLinkRegistrationType();
86 Type *getSEHRegistrationType();
87 Type *getCXXEHRegistrationType();
Reid Kleckner0738a9c2015-05-05 17:44:16 +000088
89 // Per-module data.
90 Module *TheModule = nullptr;
Reid Klecknere6531a552015-05-29 22:57:46 +000091 StructType *EHLinkRegistrationTy = nullptr;
92 StructType *CXXEHRegistrationTy = nullptr;
93 StructType *SEHRegistrationTy = nullptr;
David Majnemere60ee3b2016-02-29 19:16:03 +000094 Constant *SetJmp3 = nullptr;
95 Constant *CxxLongjmpUnwind = nullptr;
Reid Kleckner0738a9c2015-05-05 17:44:16 +000096
97 // Per-function state
98 EHPersonality Personality = EHPersonality::Unknown;
99 Function *PersonalityFn = nullptr;
David Majnemer7e5937b2016-02-17 18:37:11 +0000100 bool UseStackGuard = false;
101 int ParentBaseState;
David Majnemere60ee3b2016-02-29 19:16:03 +0000102 Constant *SehLongjmpUnwind = nullptr;
103 Constant *Cookie = nullptr;
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000104
105 /// The stack allocation containing all EH data, including the link in the
106 /// fs:00 chain and the current state.
107 AllocaInst *RegNode = nullptr;
108
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000109 /// The index of the state field of RegNode.
110 int StateFieldIndex = ~0U;
111
112 /// The linked list node subobject inside of RegNode.
113 Value *Link = nullptr;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000114};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000115}
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000116
117FunctionPass *llvm::createX86WinEHStatePass() { return new WinEHStatePass(); }
118
119char WinEHStatePass::ID = 0;
120
David Majnemer0ad363e2015-08-18 19:07:12 +0000121INITIALIZE_PASS(WinEHStatePass, "x86-winehstate",
122 "Insert stores for EH state numbers", false, false)
123
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000124bool WinEHStatePass::doInitialization(Module &M) {
125 TheModule = &M;
126 return false;
127}
128
129bool WinEHStatePass::doFinalization(Module &M) {
130 assert(TheModule == &M);
131 TheModule = nullptr;
Reid Klecknere6531a552015-05-29 22:57:46 +0000132 EHLinkRegistrationTy = nullptr;
133 CXXEHRegistrationTy = nullptr;
134 SEHRegistrationTy = nullptr;
David Majnemere60ee3b2016-02-29 19:16:03 +0000135 SetJmp3 = nullptr;
136 CxxLongjmpUnwind = nullptr;
137 SehLongjmpUnwind = nullptr;
138 Cookie = nullptr;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000139 return false;
140}
141
142void WinEHStatePass::getAnalysisUsage(AnalysisUsage &AU) const {
143 // This pass should only insert a stack allocation, memory accesses, and
Reid Kleckner60381792015-07-07 22:25:32 +0000144 // localrecovers.
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000145 AU.setPreservesCFG();
146}
147
148bool WinEHStatePass::runOnFunction(Function &F) {
Joseph Tremoulet2afea542015-10-06 20:28:16 +0000149 // Check the personality. Do nothing if this personality doesn't use funclets.
David Majnemer7fddecc2015-06-17 20:52:32 +0000150 if (!F.hasPersonalityFn())
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000151 return false;
152 PersonalityFn =
David Majnemer7fddecc2015-06-17 20:52:32 +0000153 dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000154 if (!PersonalityFn)
155 return false;
156 Personality = classifyEHPersonality(PersonalityFn);
Joseph Tremoulet2afea542015-10-06 20:28:16 +0000157 if (!isFuncletEHPersonality(Personality))
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000158 return false;
159
Reid Kleckner84ebff42015-09-16 17:19:44 +0000160 // Skip this function if there are no EH pads and we aren't using IR-level
161 // outlining.
David Majnemerbfa5b982015-10-10 00:04:29 +0000162 bool HasPads = false;
163 for (BasicBlock &BB : F) {
164 if (BB.isEHPad()) {
165 HasPads = true;
166 break;
Reid Kleckner84ebff42015-09-16 17:19:44 +0000167 }
Reid Kleckner84ebff42015-09-16 17:19:44 +0000168 }
David Majnemerbfa5b982015-10-10 00:04:29 +0000169 if (!HasPads)
170 return false;
Reid Kleckner84ebff42015-09-16 17:19:44 +0000171
David Majnemere60ee3b2016-02-29 19:16:03 +0000172 Type *Int8PtrType = Type::getInt8PtrTy(TheModule->getContext());
173 SetJmp3 = TheModule->getOrInsertFunction(
174 "_setjmp3", FunctionType::get(
175 Type::getInt32Ty(TheModule->getContext()),
176 {Int8PtrType, Type::getInt32Ty(TheModule->getContext())},
177 /*isVarArg=*/true));
David Majnemer862c5ba32016-02-20 07:34:21 +0000178
Reid Kleckner173a7252015-05-29 21:58:11 +0000179 // Disable frame pointer elimination in this function.
180 // FIXME: Do the nested handlers need to keep the parent ebp in ebp, or can we
181 // use an arbitrary register?
182 F.addFnAttr("no-frame-pointer-elim", "true");
183
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000184 emitExceptionRegistrationRecord(&F);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000185
Reid Klecknerc20276d2015-11-17 21:10:25 +0000186 // The state numbers calculated here in IR must agree with what we calculate
187 // later on for the MachineFunction. In particular, if an IR pass deletes an
188 // unreachable EH pad after this point before machine CFG construction, we
189 // will be in trouble. If this assumption is ever broken, we should turn the
190 // numbers into an immutable analysis pass.
191 WinEHFuncInfo FuncInfo;
192 addStateStores(F, FuncInfo);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000193
194 // Reset per-function state.
195 PersonalityFn = nullptr;
196 Personality = EHPersonality::Unknown;
David Majnemer7e5937b2016-02-17 18:37:11 +0000197 UseStackGuard = false;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000198 return true;
199}
200
201/// Get the common EH registration subobject:
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000202/// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
203/// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000204/// struct EHRegistrationNode {
205/// EHRegistrationNode *Next;
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000206/// PEXCEPTION_ROUTINE Handler;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000207/// };
Reid Klecknere6531a552015-05-29 22:57:46 +0000208Type *WinEHStatePass::getEHLinkRegistrationType() {
209 if (EHLinkRegistrationTy)
210 return EHLinkRegistrationTy;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000211 LLVMContext &Context = TheModule->getContext();
Reid Klecknere6531a552015-05-29 22:57:46 +0000212 EHLinkRegistrationTy = StructType::create(Context, "EHRegistrationNode");
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000213 Type *FieldTys[] = {
Reid Klecknere6531a552015-05-29 22:57:46 +0000214 EHLinkRegistrationTy->getPointerTo(0), // EHRegistrationNode *Next
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000215 Type::getInt8PtrTy(Context) // EXCEPTION_DISPOSITION (*Handler)(...)
216 };
Reid Klecknere6531a552015-05-29 22:57:46 +0000217 EHLinkRegistrationTy->setBody(FieldTys, false);
218 return EHLinkRegistrationTy;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000219}
220
221/// The __CxxFrameHandler3 registration node:
222/// struct CXXExceptionRegistration {
223/// void *SavedESP;
224/// EHRegistrationNode SubRecord;
225/// int32_t TryLevel;
226/// };
Reid Klecknere6531a552015-05-29 22:57:46 +0000227Type *WinEHStatePass::getCXXEHRegistrationType() {
228 if (CXXEHRegistrationTy)
229 return CXXEHRegistrationTy;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000230 LLVMContext &Context = TheModule->getContext();
231 Type *FieldTys[] = {
232 Type::getInt8PtrTy(Context), // void *SavedESP
Reid Klecknere6531a552015-05-29 22:57:46 +0000233 getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000234 Type::getInt32Ty(Context) // int32_t TryLevel
235 };
Reid Klecknere6531a552015-05-29 22:57:46 +0000236 CXXEHRegistrationTy =
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000237 StructType::create(FieldTys, "CXXExceptionRegistration");
Reid Klecknere6531a552015-05-29 22:57:46 +0000238 return CXXEHRegistrationTy;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000239}
240
Reid Klecknere6531a552015-05-29 22:57:46 +0000241/// The _except_handler3/4 registration node:
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000242/// struct EH4ExceptionRegistration {
243/// void *SavedESP;
244/// _EXCEPTION_POINTERS *ExceptionPointers;
245/// EHRegistrationNode SubRecord;
246/// int32_t EncodedScopeTable;
247/// int32_t TryLevel;
248/// };
Reid Klecknere6531a552015-05-29 22:57:46 +0000249Type *WinEHStatePass::getSEHRegistrationType() {
250 if (SEHRegistrationTy)
251 return SEHRegistrationTy;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000252 LLVMContext &Context = TheModule->getContext();
253 Type *FieldTys[] = {
254 Type::getInt8PtrTy(Context), // void *SavedESP
255 Type::getInt8PtrTy(Context), // void *ExceptionPointers
Reid Klecknere6531a552015-05-29 22:57:46 +0000256 getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000257 Type::getInt32Ty(Context), // int32_t EncodedScopeTable
258 Type::getInt32Ty(Context) // int32_t TryLevel
259 };
Reid Klecknere6531a552015-05-29 22:57:46 +0000260 SEHRegistrationTy = StructType::create(FieldTys, "SEHExceptionRegistration");
261 return SEHRegistrationTy;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000262}
263
264// Emit an exception registration record. These are stack allocations with the
265// common subobject of two pointers: the previous registration record (the old
266// fs:00) and the personality function for the current frame. The data before
267// and after that is personality function specific.
268void WinEHStatePass::emitExceptionRegistrationRecord(Function *F) {
269 assert(Personality == EHPersonality::MSVC_CXX ||
270 Personality == EHPersonality::MSVC_X86SEH);
271
David Majnemerefb41742016-02-01 04:28:59 +0000272 // Struct type of RegNode. Used for GEPing.
273 Type *RegNodeTy;
274
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000275 IRBuilder<> Builder(&F->getEntryBlock(), F->getEntryBlock().begin());
276 Type *Int8PtrType = Builder.getInt8PtrTy();
Reid Klecknere6531a552015-05-29 22:57:46 +0000277 if (Personality == EHPersonality::MSVC_CXX) {
278 RegNodeTy = getCXXEHRegistrationType();
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000279 RegNode = Builder.CreateAlloca(RegNodeTy);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000280 // SavedESP = llvm.stacksave()
281 Value *SP = Builder.CreateCall(
David Blaikieff6409d2015-05-18 22:13:54 +0000282 Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000283 Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
284 // TryLevel = -1
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000285 StateFieldIndex = 2;
David Majnemer7e5937b2016-02-17 18:37:11 +0000286 ParentBaseState = -1;
287 insertStateNumberStore(&*Builder.GetInsertPoint(), ParentBaseState);
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000288 // Handler = __ehhandler$F
289 Function *Trampoline = generateLSDAInEAXThunk(F);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000290 Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 1);
291 linkExceptionRegistration(Builder, Trampoline);
David Majnemere60ee3b2016-02-29 19:16:03 +0000292
293 CxxLongjmpUnwind = TheModule->getOrInsertFunction(
294 "__CxxLongjmpUnwind",
295 FunctionType::get(Type::getVoidTy(TheModule->getContext()), Int8PtrType,
296 /*isVarArg=*/false));
297 cast<Function>(CxxLongjmpUnwind->stripPointerCasts())
298 ->setCallingConv(CallingConv::X86_StdCall);
Reid Klecknere6531a552015-05-29 22:57:46 +0000299 } else if (Personality == EHPersonality::MSVC_X86SEH) {
300 // If _except_handler4 is in use, some additional guard checks and prologue
301 // stuff is required.
Reid Klecknere6531a552015-05-29 22:57:46 +0000302 RegNodeTy = getSEHRegistrationType();
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000303 RegNode = Builder.CreateAlloca(RegNodeTy);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000304 // SavedESP = llvm.stacksave()
305 Value *SP = Builder.CreateCall(
David Blaikieff6409d2015-05-18 22:13:54 +0000306 Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000307 Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
Reid Klecknere6531a552015-05-29 22:57:46 +0000308 // TryLevel = -2 / -1
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000309 StateFieldIndex = 4;
David Majnemer7e5937b2016-02-17 18:37:11 +0000310 StringRef PersonalityName = PersonalityFn->getName();
311 UseStackGuard = (PersonalityName == "_except_handler4");
312 ParentBaseState = UseStackGuard ? -2 : -1;
313 insertStateNumberStore(&*Builder.GetInsertPoint(), ParentBaseState);
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000314 // ScopeTable = llvm.x86.seh.lsda(F)
David Majnemere60ee3b2016-02-29 19:16:03 +0000315 Value *LSDA = emitEHLSDA(Builder, F);
Reid Klecknere6531a552015-05-29 22:57:46 +0000316 Type *Int32Ty = Type::getInt32Ty(TheModule->getContext());
317 LSDA = Builder.CreatePtrToInt(LSDA, Int32Ty);
318 // If using _except_handler4, xor the address of the table with
319 // __security_cookie.
320 if (UseStackGuard) {
David Majnemere60ee3b2016-02-29 19:16:03 +0000321 Cookie = TheModule->getOrInsertGlobal("__security_cookie", Int32Ty);
Reid Klecknere6531a552015-05-29 22:57:46 +0000322 Value *Val = Builder.CreateLoad(Int32Ty, Cookie);
323 LSDA = Builder.CreateXor(LSDA, Val);
324 }
325 Builder.CreateStore(LSDA, Builder.CreateStructGEP(RegNodeTy, RegNode, 3));
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000326 Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 2);
327 linkExceptionRegistration(Builder, PersonalityFn);
David Majnemere60ee3b2016-02-29 19:16:03 +0000328
329 SehLongjmpUnwind = TheModule->getOrInsertFunction(
330 UseStackGuard ? "_seh_longjmp_unwind4" : "_seh_longjmp_unwind",
331 FunctionType::get(Type::getVoidTy(TheModule->getContext()), Int8PtrType,
332 /*isVarArg=*/false));
333 cast<Function>(SehLongjmpUnwind->stripPointerCasts())
334 ->setCallingConv(CallingConv::X86_StdCall);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000335 } else {
336 llvm_unreachable("unexpected personality function");
337 }
338
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000339 // Insert an unlink before all returns.
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000340 for (BasicBlock &BB : *F) {
341 TerminatorInst *T = BB.getTerminator();
342 if (!isa<ReturnInst>(T))
343 continue;
344 Builder.SetInsertPoint(T);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000345 unlinkExceptionRegistration(Builder);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000346 }
347}
348
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000349Value *WinEHStatePass::emitEHLSDA(IRBuilder<> &Builder, Function *F) {
350 Value *FI8 = Builder.CreateBitCast(F, Type::getInt8PtrTy(F->getContext()));
351 return Builder.CreateCall(
352 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
353}
354
355/// Generate a thunk that puts the LSDA of ParentFunc in EAX and then calls
356/// PersonalityFn, forwarding the parameters passed to PEXCEPTION_ROUTINE:
357/// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
358/// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
359/// We essentially want this code:
360/// movl $lsda, %eax
361/// jmpl ___CxxFrameHandler3
362Function *WinEHStatePass::generateLSDAInEAXThunk(Function *ParentFunc) {
363 LLVMContext &Context = ParentFunc->getContext();
364 Type *Int32Ty = Type::getInt32Ty(Context);
365 Type *Int8PtrType = Type::getInt8PtrTy(Context);
366 Type *ArgTys[5] = {Int8PtrType, Int8PtrType, Int8PtrType, Int8PtrType,
367 Int8PtrType};
368 FunctionType *TrampolineTy =
369 FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 4),
370 /*isVarArg=*/false);
371 FunctionType *TargetFuncTy =
372 FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 5),
373 /*isVarArg=*/false);
Reid Kleckner5f4dd922015-07-13 17:55:14 +0000374 Function *Trampoline =
375 Function::Create(TrampolineTy, GlobalValue::InternalLinkage,
376 Twine("__ehhandler$") + GlobalValue::getRealLinkageName(
377 ParentFunc->getName()),
378 TheModule);
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000379 BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", Trampoline);
380 IRBuilder<> Builder(EntryBB);
381 Value *LSDA = emitEHLSDA(Builder, ParentFunc);
382 Value *CastPersonality =
383 Builder.CreateBitCast(PersonalityFn, TargetFuncTy->getPointerTo());
384 auto AI = Trampoline->arg_begin();
Duncan P. N. Exon Smithd77de642015-10-19 21:48:29 +0000385 Value *Args[5] = {LSDA, &*AI++, &*AI++, &*AI++, &*AI++};
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000386 CallInst *Call = Builder.CreateCall(CastPersonality, Args);
387 // Can't use musttail due to prototype mismatch, but we can use tail.
388 Call->setTailCall(true);
389 // Set inreg so we pass it in EAX.
390 Call->addAttribute(1, Attribute::InReg);
391 Builder.CreateRet(Call);
392 return Trampoline;
393}
394
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000395void WinEHStatePass::linkExceptionRegistration(IRBuilder<> &Builder,
Reid Kleckner2bc93ca2015-06-10 01:02:30 +0000396 Function *Handler) {
397 // Emit the .safeseh directive for this function.
398 Handler->addFnAttr("safeseh");
399
Reid Klecknere6531a552015-05-29 22:57:46 +0000400 Type *LinkTy = getEHLinkRegistrationType();
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000401 // Handler = Handler
Reid Kleckner2bc93ca2015-06-10 01:02:30 +0000402 Value *HandlerI8 = Builder.CreateBitCast(Handler, Builder.getInt8PtrTy());
403 Builder.CreateStore(HandlerI8, Builder.CreateStructGEP(LinkTy, Link, 1));
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000404 // Next = [fs:00]
405 Constant *FSZero =
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000406 Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000407 Value *Next = Builder.CreateLoad(FSZero);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000408 Builder.CreateStore(Next, Builder.CreateStructGEP(LinkTy, Link, 0));
409 // [fs:00] = Link
410 Builder.CreateStore(Link, FSZero);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000411}
412
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000413void WinEHStatePass::unlinkExceptionRegistration(IRBuilder<> &Builder) {
414 // Clone Link into the current BB for better address mode folding.
415 if (auto *GEP = dyn_cast<GetElementPtrInst>(Link)) {
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000416 GEP = cast<GetElementPtrInst>(GEP->clone());
417 Builder.Insert(GEP);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000418 Link = GEP;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000419 }
Reid Klecknere6531a552015-05-29 22:57:46 +0000420 Type *LinkTy = getEHLinkRegistrationType();
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000421 // [fs:00] = Link->Next
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000422 Value *Next =
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000423 Builder.CreateLoad(Builder.CreateStructGEP(LinkTy, Link, 0));
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000424 Constant *FSZero =
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000425 Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000426 Builder.CreateStore(Next, FSZero);
427}
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000428
David Majnemere60ee3b2016-02-29 19:16:03 +0000429// Calls to setjmp(p) are lowered to _setjmp3(p, 0) by the frontend.
430// The idea behind _setjmp3 is that it takes an optional number of personality
431// specific parameters to indicate how to restore the personality-specific frame
432// state when longjmp is initiated. Typically, the current TryLevel is saved.
433void WinEHStatePass::rewriteSetJmpCallSite(IRBuilder<> &Builder, Function &F,
434 CallSite CS, Value *State) {
435 // Don't rewrite calls with a weird number of arguments.
436 if (CS.getNumArgOperands() != 2)
437 return;
438
439 Instruction *Inst = CS.getInstruction();
440
441 SmallVector<OperandBundleDef, 1> OpBundles;
442 CS.getOperandBundlesAsDefs(OpBundles);
443
444 SmallVector<Value *, 3> OptionalArgs;
445 if (Personality == EHPersonality::MSVC_CXX) {
446 OptionalArgs.push_back(CxxLongjmpUnwind);
447 OptionalArgs.push_back(State);
448 OptionalArgs.push_back(emitEHLSDA(Builder, &F));
449 } else if (Personality == EHPersonality::MSVC_X86SEH) {
450 OptionalArgs.push_back(SehLongjmpUnwind);
451 OptionalArgs.push_back(State);
452 if (UseStackGuard)
453 OptionalArgs.push_back(Cookie);
454 } else {
455 llvm_unreachable("unhandled personality!");
456 }
457
458 SmallVector<Value *, 5> Args;
459 Args.push_back(
460 Builder.CreateBitCast(CS.getArgOperand(0), Builder.getInt8PtrTy()));
461 Args.push_back(Builder.getInt32(OptionalArgs.size()));
462 Args.append(OptionalArgs.begin(), OptionalArgs.end());
463
464 CallSite NewCS;
465 if (CS.isCall()) {
466 auto *CI = cast<CallInst>(Inst);
467 CallInst *NewCI = Builder.CreateCall(SetJmp3, Args, OpBundles);
468 NewCI->setTailCallKind(CI->getTailCallKind());
469 NewCS = NewCI;
470 } else {
471 auto *II = cast<InvokeInst>(Inst);
472 NewCS = Builder.CreateInvoke(
473 SetJmp3, II->getNormalDest(), II->getUnwindDest(), Args, OpBundles);
474 }
475 NewCS.setCallingConv(CS.getCallingConv());
476 NewCS.setAttributes(CS.getAttributes());
477 NewCS->setDebugLoc(CS->getDebugLoc());
478
479 Instruction *NewInst = NewCS.getInstruction();
480 NewInst->takeName(Inst);
481 Inst->replaceAllUsesWith(NewInst);
482 Inst->eraseFromParent();
483}
484
David Majnemer7e5937b2016-02-17 18:37:11 +0000485// Figure out what state we should assign calls in this block.
David Majnemere60ee3b2016-02-29 19:16:03 +0000486int WinEHStatePass::getBaseStateForBB(
487 DenseMap<BasicBlock *, ColorVector> &BlockColors, WinEHFuncInfo &FuncInfo,
488 BasicBlock *BB) {
489 int BaseState = ParentBaseState;
David Majnemer7e5937b2016-02-17 18:37:11 +0000490 auto &BBColors = BlockColors[BB];
491
492 assert(BBColors.size() == 1 && "multi-color BB not removed by preparation");
493 BasicBlock *FuncletEntryBB = BBColors.front();
494 if (auto *FuncletPad =
495 dyn_cast<FuncletPadInst>(FuncletEntryBB->getFirstNonPHI())) {
496 auto BaseStateI = FuncInfo.FuncletBaseStateMap.find(FuncletPad);
497 if (BaseStateI != FuncInfo.FuncletBaseStateMap.end())
498 BaseState = BaseStateI->second;
499 }
500
501 return BaseState;
502}
503
504// Calculate the state a call-site is in.
David Majnemere60ee3b2016-02-29 19:16:03 +0000505int WinEHStatePass::getStateForCallSite(
506 DenseMap<BasicBlock *, ColorVector> &BlockColors, WinEHFuncInfo &FuncInfo,
507 CallSite CS) {
David Majnemer7e5937b2016-02-17 18:37:11 +0000508 if (auto *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
509 // Look up the state number of the EH pad this unwinds to.
510 assert(FuncInfo.InvokeStateMap.count(II) && "invoke has no state!");
511 return FuncInfo.InvokeStateMap[II];
512 }
513 // Possibly throwing call instructions have no actions to take after
514 // an unwind. Ensure they are in the -1 state.
515 return getBaseStateForBB(BlockColors, FuncInfo, CS.getParent());
516}
517
518// Calculate the intersection of all the FinalStates for a BasicBlock's
David Majnemera822c882016-02-18 21:13:35 +0000519// predecessors.
David Majnemer7e5937b2016-02-17 18:37:11 +0000520static int getPredState(DenseMap<BasicBlock *, int> &FinalStates, Function &F,
521 int ParentBaseState, BasicBlock *BB) {
522 // The entry block has no predecessors but we know that the prologue always
523 // sets us up with a fixed state.
524 if (&F.getEntryBlock() == BB)
525 return ParentBaseState;
526
527 // This is an EH Pad, conservatively report this basic block as overdefined.
528 if (BB->isEHPad())
529 return OverdefinedState;
530
531 int CommonState = OverdefinedState;
532 for (BasicBlock *PredBB : predecessors(BB)) {
533 // We didn't manage to get a state for one of these predecessors,
534 // conservatively report this basic block as overdefined.
535 auto PredEndState = FinalStates.find(PredBB);
536 if (PredEndState == FinalStates.end())
537 return OverdefinedState;
538
539 // This code is reachable via exceptional control flow,
540 // conservatively report this basic block as overdefined.
541 if (isa<CatchReturnInst>(PredBB->getTerminator()))
542 return OverdefinedState;
543
544 int PredState = PredEndState->second;
545 assert(PredState != OverdefinedState &&
546 "overdefined BBs shouldn't be in FinalStates");
547 if (CommonState == OverdefinedState)
548 CommonState = PredState;
549
550 // At least two predecessors have different FinalStates,
551 // conservatively report this basic block as overdefined.
552 if (CommonState != PredState)
553 return OverdefinedState;
554 }
555
556 return CommonState;
Nico Weber32ac2732016-02-17 18:48:08 +0000557}
David Majnemer7e5937b2016-02-17 18:37:11 +0000558
David Majnemera822c882016-02-18 21:13:35 +0000559// Calculate the intersection of all the InitialStates for a BasicBlock's
560// successors.
561static int getSuccState(DenseMap<BasicBlock *, int> &InitialStates, Function &F,
562 int ParentBaseState, BasicBlock *BB) {
563 // This block rejoins normal control flow,
564 // conservatively report this basic block as overdefined.
565 if (isa<CatchReturnInst>(BB->getTerminator()))
566 return OverdefinedState;
567
568 int CommonState = OverdefinedState;
569 for (BasicBlock *SuccBB : successors(BB)) {
570 // We didn't manage to get a state for one of these predecessors,
571 // conservatively report this basic block as overdefined.
572 auto SuccStartState = InitialStates.find(SuccBB);
573 if (SuccStartState == InitialStates.end())
574 return OverdefinedState;
575
576 // This is an EH Pad, conservatively report this basic block as overdefined.
577 if (SuccBB->isEHPad())
578 return OverdefinedState;
579
580 int SuccState = SuccStartState->second;
581 assert(SuccState != OverdefinedState &&
582 "overdefined BBs shouldn't be in FinalStates");
583 if (CommonState == OverdefinedState)
584 CommonState = SuccState;
585
586 // At least two successors have different InitialStates,
587 // conservatively report this basic block as overdefined.
588 if (CommonState != SuccState)
589 return OverdefinedState;
590 }
591
592 return CommonState;
593}
594
David Majnemere60ee3b2016-02-29 19:16:03 +0000595bool WinEHStatePass::isStateStoreNeeded(EHPersonality Personality,
596 CallSite CS) {
David Majnemer7e5937b2016-02-17 18:37:11 +0000597 if (!CS)
598 return false;
599
David Majnemere60ee3b2016-02-29 19:16:03 +0000600 // If the function touches memory, it needs a state store.
David Majnemer7e5937b2016-02-17 18:37:11 +0000601 if (isAsynchronousEHPersonality(Personality))
602 return !CS.doesNotAccessMemory();
603
David Majnemere60ee3b2016-02-29 19:16:03 +0000604 // If the function throws, it needs a state store.
David Majnemer7e5937b2016-02-17 18:37:11 +0000605 return !CS.doesNotThrow();
606}
607
Reid Klecknerc20276d2015-11-17 21:10:25 +0000608void WinEHStatePass::addStateStores(Function &F, WinEHFuncInfo &FuncInfo) {
609 // Mark the registration node. The backend needs to know which alloca it is so
610 // that it can recover the original frame pointer.
611 IRBuilder<> Builder(RegNode->getParent(), std::next(RegNode->getIterator()));
612 Value *RegNodeI8 = Builder.CreateBitCast(RegNode, Builder.getInt8PtrTy());
613 Builder.CreateCall(
614 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_ehregnode),
615 {RegNodeI8});
Reid Kleckner14e77352015-10-09 23:34:53 +0000616
Reid Klecknerc20276d2015-11-17 21:10:25 +0000617 // Calculate state numbers.
618 if (isAsynchronousEHPersonality(Personality))
619 calculateSEHStateNumbers(&F, FuncInfo);
620 else
621 calculateWinCXXEHStateNumbers(&F, FuncInfo);
Reid Kleckner14e77352015-10-09 23:34:53 +0000622
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000623 // Iterate all the instructions and emit state number stores.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000624 DenseMap<BasicBlock *, ColorVector> BlockColors = colorEHFunclets(F);
David Majnemer7e5937b2016-02-17 18:37:11 +0000625 ReversePostOrderTraversal<Function *> RPOT(&F);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000626
David Majnemer7e5937b2016-02-17 18:37:11 +0000627 // InitialStates yields the state of the first call-site for a BasicBlock.
628 DenseMap<BasicBlock *, int> InitialStates;
629 // FinalStates yields the state of the last call-site for a BasicBlock.
630 DenseMap<BasicBlock *, int> FinalStates;
631 // Worklist used to revisit BasicBlocks with indeterminate
632 // Initial/Final-States.
633 std::deque<BasicBlock *> Worklist;
634 // Fill in InitialStates and FinalStates for BasicBlocks with call-sites.
635 for (BasicBlock *BB : RPOT) {
636 int InitialState = OverdefinedState;
637 int FinalState;
638 if (&F.getEntryBlock() == BB)
639 InitialState = FinalState = ParentBaseState;
640 for (Instruction &I : *BB) {
641 CallSite CS(&I);
642 if (!isStateStoreNeeded(Personality, CS))
David Majnemerf2bb7102016-01-29 05:33:15 +0000643 continue;
644
David Majnemer7e5937b2016-02-17 18:37:11 +0000645 int State = getStateForCallSite(BlockColors, FuncInfo, CS);
646 if (InitialState == OverdefinedState)
647 InitialState = State;
648 FinalState = State;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000649 }
David Majnemer7e5937b2016-02-17 18:37:11 +0000650 // No call-sites in this basic block? That's OK, we will come back to these
651 // in a later pass.
652 if (InitialState == OverdefinedState) {
653 Worklist.push_back(BB);
654 continue;
655 }
656 DEBUG(dbgs() << "X86WinEHState: " << BB->getName()
657 << " InitialState=" << InitialState << '\n');
658 DEBUG(dbgs() << "X86WinEHState: " << BB->getName()
659 << " FinalState=" << FinalState << '\n');
660 InitialStates.insert({BB, InitialState});
661 FinalStates.insert({BB, FinalState});
662 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000663
David Majnemer7e5937b2016-02-17 18:37:11 +0000664 // Try to fill-in InitialStates and FinalStates which have no call-sites.
665 while (!Worklist.empty()) {
666 BasicBlock *BB = Worklist.front();
667 Worklist.pop_front();
668 // This BasicBlock has already been figured out, nothing more we can do.
669 if (InitialStates.count(BB) != 0)
670 continue;
671
672 int PredState = getPredState(FinalStates, F, ParentBaseState, BB);
673 if (PredState == OverdefinedState)
674 continue;
675
676 // We successfully inferred this BasicBlock's state via it's predecessors;
677 // enqueue it's successors to see if we can infer their states.
678 InitialStates.insert({BB, PredState});
679 FinalStates.insert({BB, PredState});
680 for (BasicBlock *SuccBB : successors(BB))
681 Worklist.push_back(SuccBB);
682 }
683
David Majnemera822c882016-02-18 21:13:35 +0000684 // Try to hoist stores from successors.
685 for (BasicBlock *BB : RPOT) {
686 int SuccState = getSuccState(InitialStates, F, ParentBaseState, BB);
687 if (SuccState == OverdefinedState)
688 continue;
689
690 // Update our FinalState to reflect the common InitialState of our
691 // successors.
692 FinalStates.insert({BB, SuccState});
693 }
694
David Majnemer7e5937b2016-02-17 18:37:11 +0000695 // Finally, insert state stores before call-sites which transition us to a new
696 // state.
697 for (BasicBlock *BB : RPOT) {
698 auto &BBColors = BlockColors[BB];
699 BasicBlock *FuncletEntryBB = BBColors.front();
700 if (isa<CleanupPadInst>(FuncletEntryBB->getFirstNonPHI()))
701 continue;
702
703 int PrevState = getPredState(FinalStates, F, ParentBaseState, BB);
704 DEBUG(dbgs() << "X86WinEHState: " << BB->getName()
705 << " PrevState=" << PrevState << '\n');
706
707 for (Instruction &I : *BB) {
708 CallSite CS(&I);
709 if (!isStateStoreNeeded(Personality, CS))
710 continue;
711
712 int State = getStateForCallSite(BlockColors, FuncInfo, CS);
713 if (State != PrevState)
714 insertStateNumberStore(&I, State);
715 PrevState = State;
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000716 }
David Majnemera822c882016-02-18 21:13:35 +0000717
718 // We might have hoisted a state store into this block, emit it now.
719 auto EndState = FinalStates.find(BB);
720 if (EndState != FinalStates.end())
721 if (EndState->second != PrevState)
722 insertStateNumberStore(BB->getTerminator(), EndState->second);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000723 }
David Majnemere60ee3b2016-02-29 19:16:03 +0000724
725 SmallVector<CallSite, 1> SetJmp3CallSites;
726 for (BasicBlock *BB : RPOT) {
727 for (Instruction &I : *BB) {
728 CallSite CS(&I);
729 if (!CS)
730 continue;
731 if (CS.getCalledValue()->stripPointerCasts() !=
732 SetJmp3->stripPointerCasts())
733 continue;
734
735 SetJmp3CallSites.push_back(CS);
736 }
737 }
738
739 for (CallSite CS : SetJmp3CallSites) {
740 auto &BBColors = BlockColors[CS->getParent()];
741 BasicBlock *FuncletEntryBB = BBColors.front();
742 bool InCleanup = isa<CleanupPadInst>(FuncletEntryBB->getFirstNonPHI());
743
744 IRBuilder<> Builder(CS.getInstruction());
745 Value *State;
746 if (InCleanup) {
747 Value *StateField =
748 Builder.CreateStructGEP(nullptr, RegNode, StateFieldIndex);
749 State = Builder.CreateLoad(StateField);
750 } else {
751 State = Builder.getInt32(getStateForCallSite(BlockColors, FuncInfo, CS));
752 }
753 rewriteSetJmpCallSite(Builder, F, CS, State);
754 }
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000755}
756
David Majnemerefb41742016-02-01 04:28:59 +0000757void WinEHStatePass::insertStateNumberStore(Instruction *IP, int State) {
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000758 IRBuilder<> Builder(IP);
759 Value *StateField =
David Majnemerefb41742016-02-01 04:28:59 +0000760 Builder.CreateStructGEP(nullptr, RegNode, StateFieldIndex);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000761 Builder.CreateStore(Builder.getInt32(State), StateField);
762}