blob: 90357257b9ef23083a00d862ba740e81e70735ac [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
41namespace {
42class WinEHStatePass : public FunctionPass {
43public:
44 static char ID; // Pass identification, replacement for typeid.
45
46 WinEHStatePass() : FunctionPass(ID) {}
47
48 bool runOnFunction(Function &Fn) override;
49
50 bool doInitialization(Module &M) override;
51
52 bool doFinalization(Module &M) override;
53
54 void getAnalysisUsage(AnalysisUsage &AU) const override;
55
56 const char *getPassName() const override {
57 return "Windows 32-bit x86 EH state insertion";
58 }
59
60private:
61 void emitExceptionRegistrationRecord(Function *F);
62
Reid Kleckner2bc93ca2015-06-10 01:02:30 +000063 void linkExceptionRegistration(IRBuilder<> &Builder, Function *Handler);
Reid Klecknerfe4d4912015-05-28 22:00:24 +000064 void unlinkExceptionRegistration(IRBuilder<> &Builder);
65 void addCXXStateStores(Function &F, MachineModuleInfo &MMI);
Reid Klecknerf12c0302015-06-09 21:42:19 +000066 void addSEHStateStores(Function &F, MachineModuleInfo &MMI);
Reid Klecknerfe4d4912015-05-28 22:00:24 +000067 void addCXXStateStoresToFunclet(Value *ParentRegNode, WinEHFuncInfo &FuncInfo,
68 Function &F, int BaseState);
69 void insertStateNumberStore(Value *ParentRegNode, Instruction *IP, int State);
Reid Kleckner0738a9c2015-05-05 17:44:16 +000070
Reid Kleckner2632f0d2015-05-20 23:08:04 +000071 Value *emitEHLSDA(IRBuilder<> &Builder, Function *F);
72
73 Function *generateLSDAInEAXThunk(Function *ParentFunc);
74
Reid Klecknerfe4d4912015-05-28 22:00:24 +000075 int escapeRegNode(Function &F);
76
Reid Kleckner0738a9c2015-05-05 17:44:16 +000077 // Module-level type getters.
Reid Klecknere6531a552015-05-29 22:57:46 +000078 Type *getEHLinkRegistrationType();
79 Type *getSEHRegistrationType();
80 Type *getCXXEHRegistrationType();
Reid Kleckner0738a9c2015-05-05 17:44:16 +000081
82 // Per-module data.
83 Module *TheModule = nullptr;
Reid Klecknere6531a552015-05-29 22:57:46 +000084 StructType *EHLinkRegistrationTy = nullptr;
85 StructType *CXXEHRegistrationTy = nullptr;
86 StructType *SEHRegistrationTy = nullptr;
Reid Klecknerb7403332015-06-08 22:43:32 +000087 Function *FrameRecover = nullptr;
88 Function *FrameAddress = nullptr;
89 Function *FrameEscape = nullptr;
Reid Kleckner0738a9c2015-05-05 17:44:16 +000090
91 // Per-function state
92 EHPersonality Personality = EHPersonality::Unknown;
93 Function *PersonalityFn = nullptr;
Reid Klecknerfe4d4912015-05-28 22:00:24 +000094
95 /// The stack allocation containing all EH data, including the link in the
96 /// fs:00 chain and the current state.
97 AllocaInst *RegNode = nullptr;
98
99 /// Struct type of RegNode. Used for GEPing.
100 Type *RegNodeTy = nullptr;
101
102 /// The index of the state field of RegNode.
103 int StateFieldIndex = ~0U;
104
105 /// The linked list node subobject inside of RegNode.
106 Value *Link = nullptr;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000107};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000108}
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000109
110FunctionPass *llvm::createX86WinEHStatePass() { return new WinEHStatePass(); }
111
112char WinEHStatePass::ID = 0;
113
114bool WinEHStatePass::doInitialization(Module &M) {
115 TheModule = &M;
Reid Klecknerb7403332015-06-08 22:43:32 +0000116 FrameEscape = Intrinsic::getDeclaration(TheModule, Intrinsic::frameescape);
117 FrameRecover = Intrinsic::getDeclaration(TheModule, Intrinsic::framerecover);
118 FrameAddress = Intrinsic::getDeclaration(TheModule, Intrinsic::frameaddress);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000119 return false;
120}
121
122bool WinEHStatePass::doFinalization(Module &M) {
123 assert(TheModule == &M);
124 TheModule = nullptr;
Reid Klecknere6531a552015-05-29 22:57:46 +0000125 EHLinkRegistrationTy = nullptr;
126 CXXEHRegistrationTy = nullptr;
127 SEHRegistrationTy = nullptr;
Reid Klecknerb7403332015-06-08 22:43:32 +0000128 FrameEscape = nullptr;
129 FrameRecover = nullptr;
130 FrameAddress = nullptr;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000131 return false;
132}
133
134void WinEHStatePass::getAnalysisUsage(AnalysisUsage &AU) const {
135 // This pass should only insert a stack allocation, memory accesses, and
136 // framerecovers.
137 AU.setPreservesCFG();
138}
139
140bool WinEHStatePass::runOnFunction(Function &F) {
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000141 // If this is an outlined handler, don't do anything. We'll do state insertion
142 // for it in the parent.
143 StringRef WinEHParentName =
144 F.getFnAttribute("wineh-parent").getValueAsString();
145 if (WinEHParentName != F.getName() && !WinEHParentName.empty())
146 return false;
147
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000148 // Check the personality. Do nothing if this is not an MSVC personality.
David Majnemer7fddecc2015-06-17 20:52:32 +0000149 if (!F.hasPersonalityFn())
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000150 return false;
151 PersonalityFn =
David Majnemer7fddecc2015-06-17 20:52:32 +0000152 dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000153 if (!PersonalityFn)
154 return false;
155 Personality = classifyEHPersonality(PersonalityFn);
156 if (!isMSVCEHPersonality(Personality))
157 return false;
158
Reid Kleckner173a7252015-05-29 21:58:11 +0000159 // Disable frame pointer elimination in this function.
160 // FIXME: Do the nested handlers need to keep the parent ebp in ebp, or can we
161 // use an arbitrary register?
162 F.addFnAttr("no-frame-pointer-elim", "true");
163
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000164 emitExceptionRegistrationRecord(&F);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000165
166 auto *MMIPtr = getAnalysisIfAvailable<MachineModuleInfo>();
167 assert(MMIPtr && "MachineModuleInfo should always be available");
168 MachineModuleInfo &MMI = *MMIPtr;
Reid Klecknerf12c0302015-06-09 21:42:19 +0000169 switch (Personality) {
170 default: llvm_unreachable("unexpected personality function");
171 case EHPersonality::MSVC_CXX: addCXXStateStores(F, MMI); break;
172 case EHPersonality::MSVC_X86SEH: addSEHStateStores(F, MMI); break;
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000173 }
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000174
175 // Reset per-function state.
176 PersonalityFn = nullptr;
177 Personality = EHPersonality::Unknown;
178 return true;
179}
180
181/// Get the common EH registration subobject:
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000182/// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
183/// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000184/// struct EHRegistrationNode {
185/// EHRegistrationNode *Next;
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000186/// PEXCEPTION_ROUTINE Handler;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000187/// };
Reid Klecknere6531a552015-05-29 22:57:46 +0000188Type *WinEHStatePass::getEHLinkRegistrationType() {
189 if (EHLinkRegistrationTy)
190 return EHLinkRegistrationTy;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000191 LLVMContext &Context = TheModule->getContext();
Reid Klecknere6531a552015-05-29 22:57:46 +0000192 EHLinkRegistrationTy = StructType::create(Context, "EHRegistrationNode");
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000193 Type *FieldTys[] = {
Reid Klecknere6531a552015-05-29 22:57:46 +0000194 EHLinkRegistrationTy->getPointerTo(0), // EHRegistrationNode *Next
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000195 Type::getInt8PtrTy(Context) // EXCEPTION_DISPOSITION (*Handler)(...)
196 };
Reid Klecknere6531a552015-05-29 22:57:46 +0000197 EHLinkRegistrationTy->setBody(FieldTys, false);
198 return EHLinkRegistrationTy;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000199}
200
201/// The __CxxFrameHandler3 registration node:
202/// struct CXXExceptionRegistration {
203/// void *SavedESP;
204/// EHRegistrationNode SubRecord;
205/// int32_t TryLevel;
206/// };
Reid Klecknere6531a552015-05-29 22:57:46 +0000207Type *WinEHStatePass::getCXXEHRegistrationType() {
208 if (CXXEHRegistrationTy)
209 return CXXEHRegistrationTy;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000210 LLVMContext &Context = TheModule->getContext();
211 Type *FieldTys[] = {
212 Type::getInt8PtrTy(Context), // void *SavedESP
Reid Klecknere6531a552015-05-29 22:57:46 +0000213 getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000214 Type::getInt32Ty(Context) // int32_t TryLevel
215 };
Reid Klecknere6531a552015-05-29 22:57:46 +0000216 CXXEHRegistrationTy =
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000217 StructType::create(FieldTys, "CXXExceptionRegistration");
Reid Klecknere6531a552015-05-29 22:57:46 +0000218 return CXXEHRegistrationTy;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000219}
220
Reid Klecknere6531a552015-05-29 22:57:46 +0000221/// The _except_handler3/4 registration node:
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000222/// struct EH4ExceptionRegistration {
223/// void *SavedESP;
224/// _EXCEPTION_POINTERS *ExceptionPointers;
225/// EHRegistrationNode SubRecord;
226/// int32_t EncodedScopeTable;
227/// int32_t TryLevel;
228/// };
Reid Klecknere6531a552015-05-29 22:57:46 +0000229Type *WinEHStatePass::getSEHRegistrationType() {
230 if (SEHRegistrationTy)
231 return SEHRegistrationTy;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000232 LLVMContext &Context = TheModule->getContext();
233 Type *FieldTys[] = {
234 Type::getInt8PtrTy(Context), // void *SavedESP
235 Type::getInt8PtrTy(Context), // void *ExceptionPointers
Reid Klecknere6531a552015-05-29 22:57:46 +0000236 getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000237 Type::getInt32Ty(Context), // int32_t EncodedScopeTable
238 Type::getInt32Ty(Context) // int32_t TryLevel
239 };
Reid Klecknere6531a552015-05-29 22:57:46 +0000240 SEHRegistrationTy = StructType::create(FieldTys, "SEHExceptionRegistration");
241 return SEHRegistrationTy;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000242}
243
244// Emit an exception registration record. These are stack allocations with the
245// common subobject of two pointers: the previous registration record (the old
246// fs:00) and the personality function for the current frame. The data before
247// and after that is personality function specific.
248void WinEHStatePass::emitExceptionRegistrationRecord(Function *F) {
249 assert(Personality == EHPersonality::MSVC_CXX ||
250 Personality == EHPersonality::MSVC_X86SEH);
251
252 StringRef PersonalityName = PersonalityFn->getName();
253 IRBuilder<> Builder(&F->getEntryBlock(), F->getEntryBlock().begin());
254 Type *Int8PtrType = Builder.getInt8PtrTy();
Reid Klecknere6531a552015-05-29 22:57:46 +0000255 if (Personality == EHPersonality::MSVC_CXX) {
256 RegNodeTy = getCXXEHRegistrationType();
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000257 RegNode = Builder.CreateAlloca(RegNodeTy);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000258 // SavedESP = llvm.stacksave()
259 Value *SP = Builder.CreateCall(
David Blaikieff6409d2015-05-18 22:13:54 +0000260 Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000261 Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
262 // TryLevel = -1
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000263 StateFieldIndex = 2;
264 insertStateNumberStore(RegNode, Builder.GetInsertPoint(), -1);
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000265 // Handler = __ehhandler$F
266 Function *Trampoline = generateLSDAInEAXThunk(F);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000267 Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 1);
268 linkExceptionRegistration(Builder, Trampoline);
Reid Klecknere6531a552015-05-29 22:57:46 +0000269 } else if (Personality == EHPersonality::MSVC_X86SEH) {
270 // If _except_handler4 is in use, some additional guard checks and prologue
271 // stuff is required.
272 bool UseStackGuard = (PersonalityName == "_except_handler4");
273 RegNodeTy = getSEHRegistrationType();
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000274 RegNode = Builder.CreateAlloca(RegNodeTy);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000275 // SavedESP = llvm.stacksave()
276 Value *SP = Builder.CreateCall(
David Blaikieff6409d2015-05-18 22:13:54 +0000277 Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000278 Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
Reid Klecknere6531a552015-05-29 22:57:46 +0000279 // TryLevel = -2 / -1
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000280 StateFieldIndex = 4;
Reid Klecknere6531a552015-05-29 22:57:46 +0000281 insertStateNumberStore(RegNode, Builder.GetInsertPoint(),
282 UseStackGuard ? -2 : -1);
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000283 // ScopeTable = llvm.x86.seh.lsda(F)
284 Value *FI8 = Builder.CreateBitCast(F, Int8PtrType);
285 Value *LSDA = Builder.CreateCall(
286 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
Reid Klecknere6531a552015-05-29 22:57:46 +0000287 Type *Int32Ty = Type::getInt32Ty(TheModule->getContext());
288 LSDA = Builder.CreatePtrToInt(LSDA, Int32Ty);
289 // If using _except_handler4, xor the address of the table with
290 // __security_cookie.
291 if (UseStackGuard) {
292 Value *Cookie =
293 TheModule->getOrInsertGlobal("__security_cookie", Int32Ty);
294 Value *Val = Builder.CreateLoad(Int32Ty, Cookie);
295 LSDA = Builder.CreateXor(LSDA, Val);
296 }
297 Builder.CreateStore(LSDA, Builder.CreateStructGEP(RegNodeTy, RegNode, 3));
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000298 Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 2);
299 linkExceptionRegistration(Builder, PersonalityFn);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000300 } else {
301 llvm_unreachable("unexpected personality function");
302 }
303
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000304 // Insert an unlink before all returns.
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000305 for (BasicBlock &BB : *F) {
306 TerminatorInst *T = BB.getTerminator();
307 if (!isa<ReturnInst>(T))
308 continue;
309 Builder.SetInsertPoint(T);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000310 unlinkExceptionRegistration(Builder);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000311 }
312}
313
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000314Value *WinEHStatePass::emitEHLSDA(IRBuilder<> &Builder, Function *F) {
315 Value *FI8 = Builder.CreateBitCast(F, Type::getInt8PtrTy(F->getContext()));
316 return Builder.CreateCall(
317 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
318}
319
320/// Generate a thunk that puts the LSDA of ParentFunc in EAX and then calls
321/// PersonalityFn, forwarding the parameters passed to PEXCEPTION_ROUTINE:
322/// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
323/// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
324/// We essentially want this code:
325/// movl $lsda, %eax
326/// jmpl ___CxxFrameHandler3
327Function *WinEHStatePass::generateLSDAInEAXThunk(Function *ParentFunc) {
328 LLVMContext &Context = ParentFunc->getContext();
329 Type *Int32Ty = Type::getInt32Ty(Context);
330 Type *Int8PtrType = Type::getInt8PtrTy(Context);
331 Type *ArgTys[5] = {Int8PtrType, Int8PtrType, Int8PtrType, Int8PtrType,
332 Int8PtrType};
333 FunctionType *TrampolineTy =
334 FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 4),
335 /*isVarArg=*/false);
336 FunctionType *TargetFuncTy =
337 FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 5),
338 /*isVarArg=*/false);
339 Function *Trampoline = Function::Create(
340 TrampolineTy, GlobalValue::InternalLinkage,
341 Twine("__ehhandler$") + ParentFunc->getName(), TheModule);
342 BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", Trampoline);
343 IRBuilder<> Builder(EntryBB);
344 Value *LSDA = emitEHLSDA(Builder, ParentFunc);
345 Value *CastPersonality =
346 Builder.CreateBitCast(PersonalityFn, TargetFuncTy->getPointerTo());
347 auto AI = Trampoline->arg_begin();
348 Value *Args[5] = {LSDA, AI++, AI++, AI++, AI++};
349 CallInst *Call = Builder.CreateCall(CastPersonality, Args);
350 // Can't use musttail due to prototype mismatch, but we can use tail.
351 Call->setTailCall(true);
352 // Set inreg so we pass it in EAX.
353 Call->addAttribute(1, Attribute::InReg);
354 Builder.CreateRet(Call);
355 return Trampoline;
356}
357
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000358void WinEHStatePass::linkExceptionRegistration(IRBuilder<> &Builder,
Reid Kleckner2bc93ca2015-06-10 01:02:30 +0000359 Function *Handler) {
360 // Emit the .safeseh directive for this function.
361 Handler->addFnAttr("safeseh");
362
Reid Klecknere6531a552015-05-29 22:57:46 +0000363 Type *LinkTy = getEHLinkRegistrationType();
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000364 // Handler = Handler
Reid Kleckner2bc93ca2015-06-10 01:02:30 +0000365 Value *HandlerI8 = Builder.CreateBitCast(Handler, Builder.getInt8PtrTy());
366 Builder.CreateStore(HandlerI8, Builder.CreateStructGEP(LinkTy, Link, 1));
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000367 // Next = [fs:00]
368 Constant *FSZero =
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000369 Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000370 Value *Next = Builder.CreateLoad(FSZero);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000371 Builder.CreateStore(Next, Builder.CreateStructGEP(LinkTy, Link, 0));
372 // [fs:00] = Link
373 Builder.CreateStore(Link, FSZero);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000374}
375
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000376void WinEHStatePass::unlinkExceptionRegistration(IRBuilder<> &Builder) {
377 // Clone Link into the current BB for better address mode folding.
378 if (auto *GEP = dyn_cast<GetElementPtrInst>(Link)) {
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000379 GEP = cast<GetElementPtrInst>(GEP->clone());
380 Builder.Insert(GEP);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000381 Link = GEP;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000382 }
Reid Klecknere6531a552015-05-29 22:57:46 +0000383 Type *LinkTy = getEHLinkRegistrationType();
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000384 // [fs:00] = Link->Next
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000385 Value *Next =
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000386 Builder.CreateLoad(Builder.CreateStructGEP(LinkTy, Link, 0));
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000387 Constant *FSZero =
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000388 Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000389 Builder.CreateStore(Next, FSZero);
390}
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000391
392void WinEHStatePass::addCXXStateStores(Function &F, MachineModuleInfo &MMI) {
393 WinEHFuncInfo &FuncInfo = MMI.getWinEHFuncInfo(&F);
394 calculateWinCXXEHStateNumbers(&F, FuncInfo);
395
396 // The base state for the parent is -1.
397 addCXXStateStoresToFunclet(RegNode, FuncInfo, F, -1);
398
399 // Set up RegNodeEscapeIndex
400 int RegNodeEscapeIndex = escapeRegNode(F);
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000401 FuncInfo.EHRegNodeEscapeIndex = RegNodeEscapeIndex;
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000402
403 // Only insert stores in catch handlers.
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000404 Constant *FI8 =
405 ConstantExpr::getBitCast(&F, Type::getInt8PtrTy(TheModule->getContext()));
406 for (auto P : FuncInfo.HandlerBaseState) {
407 Function *Handler = const_cast<Function *>(P.first);
408 int BaseState = P.second;
409 IRBuilder<> Builder(&Handler->getEntryBlock(),
410 Handler->getEntryBlock().begin());
411 // FIXME: Find and reuse such a call if present.
412 Value *ParentFP = Builder.CreateCall(FrameAddress, {Builder.getInt32(1)});
413 Value *RecoveredRegNode = Builder.CreateCall(
414 FrameRecover, {FI8, ParentFP, Builder.getInt32(RegNodeEscapeIndex)});
415 RecoveredRegNode =
416 Builder.CreateBitCast(RecoveredRegNode, RegNodeTy->getPointerTo(0));
417 addCXXStateStoresToFunclet(RecoveredRegNode, FuncInfo, *Handler, BaseState);
418 }
419}
420
421/// Escape RegNode so that we can access it from child handlers. Find the call
422/// to frameescape, if any, in the entry block and append RegNode to the list
423/// of arguments.
424int WinEHStatePass::escapeRegNode(Function &F) {
425 // Find the call to frameescape and extract its arguments.
426 IntrinsicInst *EscapeCall = nullptr;
427 for (Instruction &I : F.getEntryBlock()) {
428 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
429 if (II && II->getIntrinsicID() == Intrinsic::frameescape) {
430 EscapeCall = II;
431 break;
432 }
433 }
434 SmallVector<Value *, 8> Args;
435 if (EscapeCall) {
436 auto Ops = EscapeCall->arg_operands();
437 Args.append(Ops.begin(), Ops.end());
438 }
439 Args.push_back(RegNode);
440
441 // Replace the call (if it exists) with new one. Otherwise, insert at the end
442 // of the entry block.
443 IRBuilder<> Builder(&F.getEntryBlock(),
444 EscapeCall ? EscapeCall : F.getEntryBlock().end());
Reid Klecknerb7403332015-06-08 22:43:32 +0000445 Builder.CreateCall(FrameEscape, Args);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000446 if (EscapeCall)
447 EscapeCall->eraseFromParent();
448 return Args.size() - 1;
449}
450
451void WinEHStatePass::addCXXStateStoresToFunclet(Value *ParentRegNode,
452 WinEHFuncInfo &FuncInfo,
453 Function &F, int BaseState) {
454 // Iterate all the instructions and emit state number stores.
455 for (BasicBlock &BB : F) {
456 for (Instruction &I : BB) {
457 if (auto *CI = dyn_cast<CallInst>(&I)) {
458 // Possibly throwing call instructions have no actions to take after
459 // an unwind. Ensure they are in the -1 state.
460 if (CI->doesNotThrow())
461 continue;
462 insertStateNumberStore(ParentRegNode, CI, BaseState);
463 } else if (auto *II = dyn_cast<InvokeInst>(&I)) {
464 // Look up the state number of the landingpad this unwinds to.
465 LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst();
466 // FIXME: Why does this assertion fail?
467 //assert(FuncInfo.LandingPadStateMap.count(LPI) && "LP has no state!");
468 int State = FuncInfo.LandingPadStateMap[LPI];
469 insertStateNumberStore(ParentRegNode, II, State);
470 }
471 }
472 }
473}
474
Reid Klecknerf12c0302015-06-09 21:42:19 +0000475/// Assign every distinct landingpad a unique state number for SEH. Unlike C++
476/// EH, we can use this very simple algorithm while C++ EH cannot because catch
477/// handlers aren't outlined and the runtime doesn't have to figure out which
478/// catch handler frame to unwind to.
479/// FIXME: __finally blocks are outlined, so this approach may break down there.
480void WinEHStatePass::addSEHStateStores(Function &F, MachineModuleInfo &MMI) {
481 WinEHFuncInfo &FuncInfo = MMI.getWinEHFuncInfo(&F);
482
Reid Klecknera9d62532015-06-11 22:32:23 +0000483 // Remember and return the index that we used. We save it in WinEHFuncInfo so
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000484 // that we can lower llvm.x86.seh.recoverfp later in filter functions without
485 // too much trouble.
Reid Klecknera9d62532015-06-11 22:32:23 +0000486 int RegNodeEscapeIndex = escapeRegNode(F);
487 FuncInfo.EHRegNodeEscapeIndex = RegNodeEscapeIndex;
488
Reid Klecknerf12c0302015-06-09 21:42:19 +0000489 // Iterate all the instructions and emit state number stores.
490 int CurState = 0;
Reid Kleckner673de152015-06-10 01:34:54 +0000491 SmallPtrSet<BasicBlock *, 4> ExceptBlocks;
Reid Klecknerf12c0302015-06-09 21:42:19 +0000492 for (BasicBlock &BB : F) {
493 for (auto I = BB.begin(), E = BB.end(); I != E; ++I) {
494 if (auto *CI = dyn_cast<CallInst>(I)) {
495 auto *Intrin = dyn_cast<IntrinsicInst>(CI);
496 if (Intrin) {
Reid Klecknerf12c0302015-06-09 21:42:19 +0000497 // Calls that "don't throw" are considered to be able to throw asynch
498 // exceptions, but intrinsics cannot.
499 continue;
500 }
501 insertStateNumberStore(RegNode, CI, -1);
502 } else if (auto *II = dyn_cast<InvokeInst>(I)) {
503 // Look up the state number of the landingpad this unwinds to.
504 LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst();
505 auto InsertionPair =
Reid Kleckner81d1cc02015-06-11 23:37:18 +0000506 FuncInfo.LandingPadStateMap.insert(std::make_pair(LPI, CurState));
Reid Klecknerf12c0302015-06-09 21:42:19 +0000507 auto Iter = InsertionPair.first;
508 int &State = Iter->second;
509 bool Inserted = InsertionPair.second;
510 if (Inserted) {
511 // Each action consumes a state number.
512 auto *EHActions = cast<IntrinsicInst>(LPI->getNextNode());
513 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
514 parseEHActions(EHActions, ActionList);
515 assert(!ActionList.empty());
516 CurState += ActionList.size();
517 State += ActionList.size() - 1;
Reid Kleckner673de152015-06-10 01:34:54 +0000518
519 // Remember all the __except block targets.
520 for (auto &Handler : ActionList) {
521 if (auto *CH = dyn_cast<CatchHandler>(Handler.get())) {
522 auto *BA = cast<BlockAddress>(CH->getHandlerBlockOrFunc());
523 ExceptBlocks.insert(BA->getBasicBlock());
524 }
525 }
Reid Klecknerf12c0302015-06-09 21:42:19 +0000526 }
527 insertStateNumberStore(RegNode, II, State);
528 }
529 }
530 }
Reid Kleckner673de152015-06-10 01:34:54 +0000531
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000532 // Insert llvm.x86.seh.restoreframe() into each __except block.
533 Function *RestoreFrame =
534 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_restoreframe);
Reid Kleckner673de152015-06-10 01:34:54 +0000535 for (BasicBlock *ExceptBB : ExceptBlocks) {
536 IRBuilder<> Builder(ExceptBB->begin());
Reid Kleckner399a2fe2015-06-30 22:46:59 +0000537 Builder.CreateCall(RestoreFrame, {});
Reid Kleckner673de152015-06-10 01:34:54 +0000538 }
Reid Klecknerf12c0302015-06-09 21:42:19 +0000539}
540
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000541void WinEHStatePass::insertStateNumberStore(Value *ParentRegNode,
542 Instruction *IP, int State) {
543 IRBuilder<> Builder(IP);
544 Value *StateField =
545 Builder.CreateStructGEP(RegNodeTy, ParentRegNode, StateFieldIndex);
546 Builder.CreateStore(Builder.getInt32(State), StateField);
547}