blob: db717385da62ced19e3ba09e2cef806391db76ba [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"
18#include "llvm/Analysis/LibCallSemantics.h"
Reid Klecknerfe4d4912015-05-28 22:00:24 +000019#include "llvm/CodeGen/MachineModuleInfo.h"
Reid Kleckner0738a9c2015-05-05 17:44:16 +000020#include "llvm/CodeGen/Passes.h"
21#include "llvm/CodeGen/WinEHFuncInfo.h"
22#include "llvm/IR/Dominators.h"
23#include "llvm/IR/Function.h"
24#include "llvm/IR/IRBuilder.h"
25#include "llvm/IR/Instructions.h"
26#include "llvm/IR/IntrinsicInst.h"
27#include "llvm/IR/Module.h"
28#include "llvm/IR/PatternMatch.h"
29#include "llvm/Pass.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/Support/raw_ostream.h"
32#include "llvm/Transforms/Utils/BasicBlockUtils.h"
33#include "llvm/Transforms/Utils/Cloning.h"
34#include "llvm/Transforms/Utils/Local.h"
35
36using namespace llvm;
37using namespace llvm::PatternMatch;
38
39#define DEBUG_TYPE "winehstate"
40
David Majnemer0ad363e2015-08-18 19:07:12 +000041namespace llvm { void initializeWinEHStatePassPass(PassRegistry &); }
42
Reid Kleckner0738a9c2015-05-05 17:44:16 +000043namespace {
44class 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);
David Majnemer0ad363e2015-08-18 19:07:12 +000069 void addCXXStateStores(Function &F, WinEHFuncInfo &FuncInfo);
70 void addSEHStateStores(Function &F, WinEHFuncInfo &FuncInfo);
Reid Kleckner94b704c2015-09-09 21:10:03 +000071 void addStateStoresToFunclet(Value *ParentRegNode, WinEHFuncInfo &FuncInfo,
72 Function &F, int BaseState);
Reid Klecknerfe4d4912015-05-28 22:00:24 +000073 void insertStateNumberStore(Value *ParentRegNode, Instruction *IP, int State);
Reid Kleckner0738a9c2015-05-05 17:44:16 +000074
Reid Kleckner2632f0d2015-05-20 23:08:04 +000075 Value *emitEHLSDA(IRBuilder<> &Builder, Function *F);
76
77 Function *generateLSDAInEAXThunk(Function *ParentFunc);
78
Reid Klecknerfe4d4912015-05-28 22:00:24 +000079 int escapeRegNode(Function &F);
80
Reid Kleckner0738a9c2015-05-05 17:44:16 +000081 // Module-level type getters.
Reid Klecknere6531a552015-05-29 22:57:46 +000082 Type *getEHLinkRegistrationType();
83 Type *getSEHRegistrationType();
84 Type *getCXXEHRegistrationType();
Reid Kleckner0738a9c2015-05-05 17:44:16 +000085
86 // Per-module data.
87 Module *TheModule = nullptr;
Reid Klecknere6531a552015-05-29 22:57:46 +000088 StructType *EHLinkRegistrationTy = nullptr;
89 StructType *CXXEHRegistrationTy = nullptr;
90 StructType *SEHRegistrationTy = nullptr;
Reid Klecknerb7403332015-06-08 22:43:32 +000091 Function *FrameRecover = nullptr;
92 Function *FrameAddress = nullptr;
93 Function *FrameEscape = nullptr;
Reid Kleckner94b704c2015-09-09 21:10:03 +000094 Function *RestoreFrame = nullptr;
Reid Kleckner0738a9c2015-05-05 17:44:16 +000095
96 // Per-function state
97 EHPersonality Personality = EHPersonality::Unknown;
98 Function *PersonalityFn = nullptr;
Reid Klecknerfe4d4912015-05-28 22:00:24 +000099
100 /// The stack allocation containing all EH data, including the link in the
101 /// fs:00 chain and the current state.
102 AllocaInst *RegNode = nullptr;
103
104 /// Struct type of RegNode. Used for GEPing.
105 Type *RegNodeTy = nullptr;
106
107 /// The index of the state field of RegNode.
108 int StateFieldIndex = ~0U;
109
110 /// The linked list node subobject inside of RegNode.
111 Value *Link = nullptr;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000112};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000113}
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000114
115FunctionPass *llvm::createX86WinEHStatePass() { return new WinEHStatePass(); }
116
117char WinEHStatePass::ID = 0;
118
David Majnemer0ad363e2015-08-18 19:07:12 +0000119INITIALIZE_PASS(WinEHStatePass, "x86-winehstate",
120 "Insert stores for EH state numbers", false, false)
121
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000122bool WinEHStatePass::doInitialization(Module &M) {
123 TheModule = &M;
Reid Kleckner60381792015-07-07 22:25:32 +0000124 FrameEscape = Intrinsic::getDeclaration(TheModule, Intrinsic::localescape);
125 FrameRecover = Intrinsic::getDeclaration(TheModule, Intrinsic::localrecover);
Reid Klecknerb7403332015-06-08 22:43:32 +0000126 FrameAddress = Intrinsic::getDeclaration(TheModule, Intrinsic::frameaddress);
Reid Kleckner94b704c2015-09-09 21:10:03 +0000127 RestoreFrame =
128 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_restoreframe);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000129 return false;
130}
131
132bool WinEHStatePass::doFinalization(Module &M) {
133 assert(TheModule == &M);
134 TheModule = nullptr;
Reid Klecknere6531a552015-05-29 22:57:46 +0000135 EHLinkRegistrationTy = nullptr;
136 CXXEHRegistrationTy = nullptr;
137 SEHRegistrationTy = nullptr;
Reid Klecknerb7403332015-06-08 22:43:32 +0000138 FrameEscape = nullptr;
139 FrameRecover = nullptr;
140 FrameAddress = nullptr;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000141 return false;
142}
143
144void WinEHStatePass::getAnalysisUsage(AnalysisUsage &AU) const {
145 // This pass should only insert a stack allocation, memory accesses, and
Reid Kleckner60381792015-07-07 22:25:32 +0000146 // localrecovers.
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000147 AU.setPreservesCFG();
148}
149
150bool WinEHStatePass::runOnFunction(Function &F) {
Joseph Tremoulet2afea542015-10-06 20:28:16 +0000151 // Check the personality. Do nothing if this personality doesn't use funclets.
David Majnemer7fddecc2015-06-17 20:52:32 +0000152 if (!F.hasPersonalityFn())
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000153 return false;
154 PersonalityFn =
David Majnemer7fddecc2015-06-17 20:52:32 +0000155 dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000156 if (!PersonalityFn)
157 return false;
158 Personality = classifyEHPersonality(PersonalityFn);
Joseph Tremoulet2afea542015-10-06 20:28:16 +0000159 if (!isFuncletEHPersonality(Personality))
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000160 return false;
161
Reid Kleckner84ebff42015-09-16 17:19:44 +0000162 // Skip this function if there are no EH pads and we aren't using IR-level
163 // outlining.
David Majnemerbfa5b982015-10-10 00:04:29 +0000164 bool HasPads = false;
165 for (BasicBlock &BB : F) {
166 if (BB.isEHPad()) {
167 HasPads = true;
168 break;
Reid Kleckner84ebff42015-09-16 17:19:44 +0000169 }
Reid Kleckner84ebff42015-09-16 17:19:44 +0000170 }
David Majnemerbfa5b982015-10-10 00:04:29 +0000171 if (!HasPads)
172 return false;
Reid Kleckner84ebff42015-09-16 17:19:44 +0000173
Reid Kleckner173a7252015-05-29 21:58:11 +0000174 // Disable frame pointer elimination in this function.
175 // FIXME: Do the nested handlers need to keep the parent ebp in ebp, or can we
176 // use an arbitrary register?
177 F.addFnAttr("no-frame-pointer-elim", "true");
178
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000179 emitExceptionRegistrationRecord(&F);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000180
David Majnemer0ad363e2015-08-18 19:07:12 +0000181 auto *MMI = getAnalysisIfAvailable<MachineModuleInfo>();
182 // If MMI is null, create our own WinEHFuncInfo. This only happens in opt
183 // tests.
184 std::unique_ptr<WinEHFuncInfo> FuncInfoPtr;
185 if (!MMI)
186 FuncInfoPtr.reset(new WinEHFuncInfo());
187 WinEHFuncInfo &FuncInfo =
188 *(MMI ? &MMI->getWinEHFuncInfo(&F) : FuncInfoPtr.get());
189
Reid Klecknerdf129512015-09-08 22:44:41 +0000190 FuncInfo.EHRegNode = RegNode;
191
Reid Klecknerf12c0302015-06-09 21:42:19 +0000192 switch (Personality) {
193 default: llvm_unreachable("unexpected personality function");
David Majnemer0ad363e2015-08-18 19:07:12 +0000194 case EHPersonality::MSVC_CXX:
195 addCXXStateStores(F, FuncInfo);
196 break;
197 case EHPersonality::MSVC_X86SEH:
198 addSEHStateStores(F, FuncInfo);
199 break;
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000200 }
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000201
202 // Reset per-function state.
203 PersonalityFn = nullptr;
204 Personality = EHPersonality::Unknown;
205 return true;
206}
207
208/// Get the common EH registration subobject:
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000209/// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
210/// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000211/// struct EHRegistrationNode {
212/// EHRegistrationNode *Next;
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000213/// PEXCEPTION_ROUTINE Handler;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000214/// };
Reid Klecknere6531a552015-05-29 22:57:46 +0000215Type *WinEHStatePass::getEHLinkRegistrationType() {
216 if (EHLinkRegistrationTy)
217 return EHLinkRegistrationTy;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000218 LLVMContext &Context = TheModule->getContext();
Reid Klecknere6531a552015-05-29 22:57:46 +0000219 EHLinkRegistrationTy = StructType::create(Context, "EHRegistrationNode");
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000220 Type *FieldTys[] = {
Reid Klecknere6531a552015-05-29 22:57:46 +0000221 EHLinkRegistrationTy->getPointerTo(0), // EHRegistrationNode *Next
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000222 Type::getInt8PtrTy(Context) // EXCEPTION_DISPOSITION (*Handler)(...)
223 };
Reid Klecknere6531a552015-05-29 22:57:46 +0000224 EHLinkRegistrationTy->setBody(FieldTys, false);
225 return EHLinkRegistrationTy;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000226}
227
228/// The __CxxFrameHandler3 registration node:
229/// struct CXXExceptionRegistration {
230/// void *SavedESP;
231/// EHRegistrationNode SubRecord;
232/// int32_t TryLevel;
233/// };
Reid Klecknere6531a552015-05-29 22:57:46 +0000234Type *WinEHStatePass::getCXXEHRegistrationType() {
235 if (CXXEHRegistrationTy)
236 return CXXEHRegistrationTy;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000237 LLVMContext &Context = TheModule->getContext();
238 Type *FieldTys[] = {
239 Type::getInt8PtrTy(Context), // void *SavedESP
Reid Klecknere6531a552015-05-29 22:57:46 +0000240 getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000241 Type::getInt32Ty(Context) // int32_t TryLevel
242 };
Reid Klecknere6531a552015-05-29 22:57:46 +0000243 CXXEHRegistrationTy =
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000244 StructType::create(FieldTys, "CXXExceptionRegistration");
Reid Klecknere6531a552015-05-29 22:57:46 +0000245 return CXXEHRegistrationTy;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000246}
247
Reid Klecknere6531a552015-05-29 22:57:46 +0000248/// The _except_handler3/4 registration node:
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000249/// struct EH4ExceptionRegistration {
250/// void *SavedESP;
251/// _EXCEPTION_POINTERS *ExceptionPointers;
252/// EHRegistrationNode SubRecord;
253/// int32_t EncodedScopeTable;
254/// int32_t TryLevel;
255/// };
Reid Klecknere6531a552015-05-29 22:57:46 +0000256Type *WinEHStatePass::getSEHRegistrationType() {
257 if (SEHRegistrationTy)
258 return SEHRegistrationTy;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000259 LLVMContext &Context = TheModule->getContext();
260 Type *FieldTys[] = {
261 Type::getInt8PtrTy(Context), // void *SavedESP
262 Type::getInt8PtrTy(Context), // void *ExceptionPointers
Reid Klecknere6531a552015-05-29 22:57:46 +0000263 getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000264 Type::getInt32Ty(Context), // int32_t EncodedScopeTable
265 Type::getInt32Ty(Context) // int32_t TryLevel
266 };
Reid Klecknere6531a552015-05-29 22:57:46 +0000267 SEHRegistrationTy = StructType::create(FieldTys, "SEHExceptionRegistration");
268 return SEHRegistrationTy;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000269}
270
271// Emit an exception registration record. These are stack allocations with the
272// common subobject of two pointers: the previous registration record (the old
273// fs:00) and the personality function for the current frame. The data before
274// and after that is personality function specific.
275void WinEHStatePass::emitExceptionRegistrationRecord(Function *F) {
276 assert(Personality == EHPersonality::MSVC_CXX ||
277 Personality == EHPersonality::MSVC_X86SEH);
278
279 StringRef PersonalityName = PersonalityFn->getName();
280 IRBuilder<> Builder(&F->getEntryBlock(), F->getEntryBlock().begin());
281 Type *Int8PtrType = Builder.getInt8PtrTy();
Reid Klecknere6531a552015-05-29 22:57:46 +0000282 if (Personality == EHPersonality::MSVC_CXX) {
283 RegNodeTy = getCXXEHRegistrationType();
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000284 RegNode = Builder.CreateAlloca(RegNodeTy);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000285 // SavedESP = llvm.stacksave()
286 Value *SP = Builder.CreateCall(
David Blaikieff6409d2015-05-18 22:13:54 +0000287 Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000288 Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
289 // TryLevel = -1
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000290 StateFieldIndex = 2;
Duncan P. N. Exon Smithd77de642015-10-19 21:48:29 +0000291 insertStateNumberStore(RegNode, &*Builder.GetInsertPoint(), -1);
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000292 // Handler = __ehhandler$F
293 Function *Trampoline = generateLSDAInEAXThunk(F);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000294 Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 1);
295 linkExceptionRegistration(Builder, Trampoline);
Reid Klecknere6531a552015-05-29 22:57:46 +0000296 } else if (Personality == EHPersonality::MSVC_X86SEH) {
297 // If _except_handler4 is in use, some additional guard checks and prologue
298 // stuff is required.
299 bool UseStackGuard = (PersonalityName == "_except_handler4");
300 RegNodeTy = getSEHRegistrationType();
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000301 RegNode = Builder.CreateAlloca(RegNodeTy);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000302 // SavedESP = llvm.stacksave()
303 Value *SP = Builder.CreateCall(
David Blaikieff6409d2015-05-18 22:13:54 +0000304 Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000305 Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
Reid Klecknere6531a552015-05-29 22:57:46 +0000306 // TryLevel = -2 / -1
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000307 StateFieldIndex = 4;
Duncan P. N. Exon Smithd77de642015-10-19 21:48:29 +0000308 insertStateNumberStore(RegNode, &*Builder.GetInsertPoint(),
Reid Klecknere6531a552015-05-29 22:57:46 +0000309 UseStackGuard ? -2 : -1);
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000310 // ScopeTable = llvm.x86.seh.lsda(F)
311 Value *FI8 = Builder.CreateBitCast(F, Int8PtrType);
312 Value *LSDA = Builder.CreateCall(
313 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
Reid Klecknere6531a552015-05-29 22:57:46 +0000314 Type *Int32Ty = Type::getInt32Ty(TheModule->getContext());
315 LSDA = Builder.CreatePtrToInt(LSDA, Int32Ty);
316 // If using _except_handler4, xor the address of the table with
317 // __security_cookie.
318 if (UseStackGuard) {
319 Value *Cookie =
320 TheModule->getOrInsertGlobal("__security_cookie", Int32Ty);
321 Value *Val = Builder.CreateLoad(Int32Ty, Cookie);
322 LSDA = Builder.CreateXor(LSDA, Val);
323 }
324 Builder.CreateStore(LSDA, Builder.CreateStructGEP(RegNodeTy, RegNode, 3));
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000325 Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 2);
326 linkExceptionRegistration(Builder, PersonalityFn);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000327 } else {
328 llvm_unreachable("unexpected personality function");
329 }
330
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000331 // Insert an unlink before all returns.
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000332 for (BasicBlock &BB : *F) {
333 TerminatorInst *T = BB.getTerminator();
334 if (!isa<ReturnInst>(T))
335 continue;
336 Builder.SetInsertPoint(T);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000337 unlinkExceptionRegistration(Builder);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000338 }
339}
340
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000341Value *WinEHStatePass::emitEHLSDA(IRBuilder<> &Builder, Function *F) {
342 Value *FI8 = Builder.CreateBitCast(F, Type::getInt8PtrTy(F->getContext()));
343 return Builder.CreateCall(
344 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
345}
346
347/// Generate a thunk that puts the LSDA of ParentFunc in EAX and then calls
348/// PersonalityFn, forwarding the parameters passed to PEXCEPTION_ROUTINE:
349/// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
350/// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
351/// We essentially want this code:
352/// movl $lsda, %eax
353/// jmpl ___CxxFrameHandler3
354Function *WinEHStatePass::generateLSDAInEAXThunk(Function *ParentFunc) {
355 LLVMContext &Context = ParentFunc->getContext();
356 Type *Int32Ty = Type::getInt32Ty(Context);
357 Type *Int8PtrType = Type::getInt8PtrTy(Context);
358 Type *ArgTys[5] = {Int8PtrType, Int8PtrType, Int8PtrType, Int8PtrType,
359 Int8PtrType};
360 FunctionType *TrampolineTy =
361 FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 4),
362 /*isVarArg=*/false);
363 FunctionType *TargetFuncTy =
364 FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 5),
365 /*isVarArg=*/false);
Reid Kleckner5f4dd922015-07-13 17:55:14 +0000366 Function *Trampoline =
367 Function::Create(TrampolineTy, GlobalValue::InternalLinkage,
368 Twine("__ehhandler$") + GlobalValue::getRealLinkageName(
369 ParentFunc->getName()),
370 TheModule);
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000371 BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", Trampoline);
372 IRBuilder<> Builder(EntryBB);
373 Value *LSDA = emitEHLSDA(Builder, ParentFunc);
374 Value *CastPersonality =
375 Builder.CreateBitCast(PersonalityFn, TargetFuncTy->getPointerTo());
376 auto AI = Trampoline->arg_begin();
Duncan P. N. Exon Smithd77de642015-10-19 21:48:29 +0000377 Value *Args[5] = {LSDA, &*AI++, &*AI++, &*AI++, &*AI++};
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000378 CallInst *Call = Builder.CreateCall(CastPersonality, Args);
379 // Can't use musttail due to prototype mismatch, but we can use tail.
380 Call->setTailCall(true);
381 // Set inreg so we pass it in EAX.
382 Call->addAttribute(1, Attribute::InReg);
383 Builder.CreateRet(Call);
384 return Trampoline;
385}
386
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000387void WinEHStatePass::linkExceptionRegistration(IRBuilder<> &Builder,
Reid Kleckner2bc93ca2015-06-10 01:02:30 +0000388 Function *Handler) {
389 // Emit the .safeseh directive for this function.
390 Handler->addFnAttr("safeseh");
391
Reid Klecknere6531a552015-05-29 22:57:46 +0000392 Type *LinkTy = getEHLinkRegistrationType();
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000393 // Handler = Handler
Reid Kleckner2bc93ca2015-06-10 01:02:30 +0000394 Value *HandlerI8 = Builder.CreateBitCast(Handler, Builder.getInt8PtrTy());
395 Builder.CreateStore(HandlerI8, Builder.CreateStructGEP(LinkTy, Link, 1));
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000396 // Next = [fs:00]
397 Constant *FSZero =
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000398 Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000399 Value *Next = Builder.CreateLoad(FSZero);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000400 Builder.CreateStore(Next, Builder.CreateStructGEP(LinkTy, Link, 0));
401 // [fs:00] = Link
402 Builder.CreateStore(Link, FSZero);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000403}
404
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000405void WinEHStatePass::unlinkExceptionRegistration(IRBuilder<> &Builder) {
406 // Clone Link into the current BB for better address mode folding.
407 if (auto *GEP = dyn_cast<GetElementPtrInst>(Link)) {
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000408 GEP = cast<GetElementPtrInst>(GEP->clone());
409 Builder.Insert(GEP);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000410 Link = GEP;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000411 }
Reid Klecknere6531a552015-05-29 22:57:46 +0000412 Type *LinkTy = getEHLinkRegistrationType();
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000413 // [fs:00] = Link->Next
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000414 Value *Next =
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000415 Builder.CreateLoad(Builder.CreateStructGEP(LinkTy, Link, 0));
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000416 Constant *FSZero =
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000417 Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000418 Builder.CreateStore(Next, FSZero);
419}
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000420
David Majnemer0ad363e2015-08-18 19:07:12 +0000421void WinEHStatePass::addCXXStateStores(Function &F, WinEHFuncInfo &FuncInfo) {
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000422 // Set up RegNodeEscapeIndex
423 int RegNodeEscapeIndex = escapeRegNode(F);
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000424 FuncInfo.EHRegNodeEscapeIndex = RegNodeEscapeIndex;
Reid Kleckner14e77352015-10-09 23:34:53 +0000425
426 calculateWinCXXEHStateNumbers(&F, FuncInfo);
427 addStateStoresToFunclet(RegNode, FuncInfo, F, -1);
428}
429
430/// Assign every distinct landingpad a unique state number for SEH. Unlike C++
431/// EH, we can use this very simple algorithm while C++ EH cannot because catch
432/// handlers aren't outlined and the runtime doesn't have to figure out which
433/// catch handler frame to unwind to.
434void WinEHStatePass::addSEHStateStores(Function &F, WinEHFuncInfo &FuncInfo) {
435 // Remember and return the index that we used. We save it in WinEHFuncInfo so
436 // that we can lower llvm.x86.seh.recoverfp later in filter functions without
437 // too much trouble.
438 int RegNodeEscapeIndex = escapeRegNode(F);
439 FuncInfo.EHRegNodeEscapeIndex = RegNodeEscapeIndex;
440
441 calculateSEHStateNumbers(&F, FuncInfo);
442 addStateStoresToFunclet(RegNode, FuncInfo, F, -1);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000443}
444
445/// Escape RegNode so that we can access it from child handlers. Find the call
Reid Kleckner60381792015-07-07 22:25:32 +0000446/// to localescape, if any, in the entry block and append RegNode to the list
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000447/// of arguments.
448int WinEHStatePass::escapeRegNode(Function &F) {
Reid Kleckner60381792015-07-07 22:25:32 +0000449 // Find the call to localescape and extract its arguments.
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000450 IntrinsicInst *EscapeCall = nullptr;
451 for (Instruction &I : F.getEntryBlock()) {
452 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
Reid Kleckner60381792015-07-07 22:25:32 +0000453 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000454 EscapeCall = II;
455 break;
456 }
457 }
458 SmallVector<Value *, 8> Args;
459 if (EscapeCall) {
460 auto Ops = EscapeCall->arg_operands();
461 Args.append(Ops.begin(), Ops.end());
462 }
463 Args.push_back(RegNode);
464
465 // Replace the call (if it exists) with new one. Otherwise, insert at the end
466 // of the entry block.
Reid Kleckner85a24502015-07-10 00:08:49 +0000467 Instruction *InsertPt = EscapeCall;
468 if (!EscapeCall)
469 InsertPt = F.getEntryBlock().getTerminator();
Duncan P. N. Exon Smithd77de642015-10-19 21:48:29 +0000470 IRBuilder<> Builder(InsertPt);
Reid Klecknerb7403332015-06-08 22:43:32 +0000471 Builder.CreateCall(FrameEscape, Args);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000472 if (EscapeCall)
473 EscapeCall->eraseFromParent();
474 return Args.size() - 1;
475}
476
Reid Kleckner94b704c2015-09-09 21:10:03 +0000477void WinEHStatePass::addStateStoresToFunclet(Value *ParentRegNode,
478 WinEHFuncInfo &FuncInfo,
479 Function &F, int BaseState) {
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000480 // Iterate all the instructions and emit state number stores.
481 for (BasicBlock &BB : F) {
482 for (Instruction &I : BB) {
483 if (auto *CI = dyn_cast<CallInst>(&I)) {
484 // Possibly throwing call instructions have no actions to take after
485 // an unwind. Ensure they are in the -1 state.
486 if (CI->doesNotThrow())
487 continue;
488 insertStateNumberStore(ParentRegNode, CI, BaseState);
489 } else if (auto *II = dyn_cast<InvokeInst>(&I)) {
490 // Look up the state number of the landingpad this unwinds to.
David Majnemer0ad363e2015-08-18 19:07:12 +0000491 Instruction *PadInst = II->getUnwindDest()->getFirstNonPHI();
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000492 // FIXME: Why does this assertion fail?
David Majnemer0ad363e2015-08-18 19:07:12 +0000493 //assert(FuncInfo.EHPadStateMap.count(PadInst) && "EH Pad has no state!");
494 int State = FuncInfo.EHPadStateMap[PadInst];
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000495 insertStateNumberStore(ParentRegNode, II, State);
496 }
497 }
498 }
499}
500
501void WinEHStatePass::insertStateNumberStore(Value *ParentRegNode,
502 Instruction *IP, int State) {
503 IRBuilder<> Builder(IP);
504 Value *StateField =
505 Builder.CreateStructGEP(RegNodeTy, ParentRegNode, StateFieldIndex);
506 Builder.CreateStore(Builder.getInt32(State), StateField);
507}