blob: 0c4aabab880ecd241f95fe668394424d8928fa6d [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 Klecknerfe4d4912015-05-28 22:00:24 +000063 void linkExceptionRegistration(IRBuilder<> &Builder, Value *Handler);
64 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 Klecknerf12c0302015-06-09 21:42:19 +000070 iplist<Instruction>::iterator
71 rewriteExceptionInfoIntrinsics(IntrinsicInst *Intrin);
Reid Kleckner0738a9c2015-05-05 17:44:16 +000072
Reid Kleckner2632f0d2015-05-20 23:08:04 +000073 Value *emitEHLSDA(IRBuilder<> &Builder, Function *F);
74
75 Function *generateLSDAInEAXThunk(Function *ParentFunc);
76
Reid Klecknerfe4d4912015-05-28 22:00:24 +000077 int escapeRegNode(Function &F);
78
Reid Kleckner0738a9c2015-05-05 17:44:16 +000079 // Module-level type getters.
Reid Klecknere6531a552015-05-29 22:57:46 +000080 Type *getEHLinkRegistrationType();
81 Type *getSEHRegistrationType();
82 Type *getCXXEHRegistrationType();
Reid Kleckner0738a9c2015-05-05 17:44:16 +000083
84 // Per-module data.
85 Module *TheModule = nullptr;
Reid Klecknere6531a552015-05-29 22:57:46 +000086 StructType *EHLinkRegistrationTy = nullptr;
87 StructType *CXXEHRegistrationTy = nullptr;
88 StructType *SEHRegistrationTy = nullptr;
Reid Klecknerb7403332015-06-08 22:43:32 +000089 Function *FrameRecover = nullptr;
90 Function *FrameAddress = nullptr;
91 Function *FrameEscape = nullptr;
Reid Kleckner0738a9c2015-05-05 17:44:16 +000092
93 // Per-function state
94 EHPersonality Personality = EHPersonality::Unknown;
95 Function *PersonalityFn = nullptr;
Reid Klecknerfe4d4912015-05-28 22:00:24 +000096
97 /// The stack allocation containing all EH data, including the link in the
98 /// fs:00 chain and the current state.
99 AllocaInst *RegNode = nullptr;
100
101 /// Struct type of RegNode. Used for GEPing.
102 Type *RegNodeTy = nullptr;
103
104 /// The index of the state field of RegNode.
105 int StateFieldIndex = ~0U;
106
107 /// The linked list node subobject inside of RegNode.
108 Value *Link = nullptr;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000109};
110}
111
112FunctionPass *llvm::createX86WinEHStatePass() { return new WinEHStatePass(); }
113
114char WinEHStatePass::ID = 0;
115
116bool WinEHStatePass::doInitialization(Module &M) {
117 TheModule = &M;
Reid Klecknerb7403332015-06-08 22:43:32 +0000118 FrameEscape = Intrinsic::getDeclaration(TheModule, Intrinsic::frameescape);
119 FrameRecover = Intrinsic::getDeclaration(TheModule, Intrinsic::framerecover);
120 FrameAddress = Intrinsic::getDeclaration(TheModule, Intrinsic::frameaddress);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000121 return false;
122}
123
124bool WinEHStatePass::doFinalization(Module &M) {
125 assert(TheModule == &M);
126 TheModule = nullptr;
Reid Klecknere6531a552015-05-29 22:57:46 +0000127 EHLinkRegistrationTy = nullptr;
128 CXXEHRegistrationTy = nullptr;
129 SEHRegistrationTy = nullptr;
Reid Klecknerb7403332015-06-08 22:43:32 +0000130 FrameEscape = nullptr;
131 FrameRecover = nullptr;
132 FrameAddress = nullptr;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000133 return false;
134}
135
136void WinEHStatePass::getAnalysisUsage(AnalysisUsage &AU) const {
137 // This pass should only insert a stack allocation, memory accesses, and
138 // framerecovers.
139 AU.setPreservesCFG();
140}
141
142bool WinEHStatePass::runOnFunction(Function &F) {
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000143 // If this is an outlined handler, don't do anything. We'll do state insertion
144 // for it in the parent.
145 StringRef WinEHParentName =
146 F.getFnAttribute("wineh-parent").getValueAsString();
147 if (WinEHParentName != F.getName() && !WinEHParentName.empty())
148 return false;
149
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000150 // Check the personality. Do nothing if this is not an MSVC personality.
151 LandingPadInst *LP = nullptr;
152 for (BasicBlock &BB : F) {
153 LP = BB.getLandingPadInst();
154 if (LP)
155 break;
156 }
157 if (!LP)
158 return false;
159 PersonalityFn =
160 dyn_cast<Function>(LP->getPersonalityFn()->stripPointerCasts());
161 if (!PersonalityFn)
162 return false;
163 Personality = classifyEHPersonality(PersonalityFn);
164 if (!isMSVCEHPersonality(Personality))
165 return false;
166
Reid Kleckner173a7252015-05-29 21:58:11 +0000167 // Disable frame pointer elimination in this function.
168 // FIXME: Do the nested handlers need to keep the parent ebp in ebp, or can we
169 // use an arbitrary register?
170 F.addFnAttr("no-frame-pointer-elim", "true");
171
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000172 emitExceptionRegistrationRecord(&F);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000173
174 auto *MMIPtr = getAnalysisIfAvailable<MachineModuleInfo>();
175 assert(MMIPtr && "MachineModuleInfo should always be available");
176 MachineModuleInfo &MMI = *MMIPtr;
Reid Klecknerf12c0302015-06-09 21:42:19 +0000177 switch (Personality) {
178 default: llvm_unreachable("unexpected personality function");
179 case EHPersonality::MSVC_CXX: addCXXStateStores(F, MMI); break;
180 case EHPersonality::MSVC_X86SEH: addSEHStateStores(F, MMI); break;
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000181 }
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000182
183 // Reset per-function state.
184 PersonalityFn = nullptr;
185 Personality = EHPersonality::Unknown;
186 return true;
187}
188
189/// Get the common EH registration subobject:
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000190/// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
191/// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000192/// struct EHRegistrationNode {
193/// EHRegistrationNode *Next;
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000194/// PEXCEPTION_ROUTINE Handler;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000195/// };
Reid Klecknere6531a552015-05-29 22:57:46 +0000196Type *WinEHStatePass::getEHLinkRegistrationType() {
197 if (EHLinkRegistrationTy)
198 return EHLinkRegistrationTy;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000199 LLVMContext &Context = TheModule->getContext();
Reid Klecknere6531a552015-05-29 22:57:46 +0000200 EHLinkRegistrationTy = StructType::create(Context, "EHRegistrationNode");
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000201 Type *FieldTys[] = {
Reid Klecknere6531a552015-05-29 22:57:46 +0000202 EHLinkRegistrationTy->getPointerTo(0), // EHRegistrationNode *Next
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000203 Type::getInt8PtrTy(Context) // EXCEPTION_DISPOSITION (*Handler)(...)
204 };
Reid Klecknere6531a552015-05-29 22:57:46 +0000205 EHLinkRegistrationTy->setBody(FieldTys, false);
206 return EHLinkRegistrationTy;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000207}
208
209/// The __CxxFrameHandler3 registration node:
210/// struct CXXExceptionRegistration {
211/// void *SavedESP;
212/// EHRegistrationNode SubRecord;
213/// int32_t TryLevel;
214/// };
Reid Klecknere6531a552015-05-29 22:57:46 +0000215Type *WinEHStatePass::getCXXEHRegistrationType() {
216 if (CXXEHRegistrationTy)
217 return CXXEHRegistrationTy;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000218 LLVMContext &Context = TheModule->getContext();
219 Type *FieldTys[] = {
220 Type::getInt8PtrTy(Context), // void *SavedESP
Reid Klecknere6531a552015-05-29 22:57:46 +0000221 getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000222 Type::getInt32Ty(Context) // int32_t TryLevel
223 };
Reid Klecknere6531a552015-05-29 22:57:46 +0000224 CXXEHRegistrationTy =
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000225 StructType::create(FieldTys, "CXXExceptionRegistration");
Reid Klecknere6531a552015-05-29 22:57:46 +0000226 return CXXEHRegistrationTy;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000227}
228
Reid Klecknere6531a552015-05-29 22:57:46 +0000229/// The _except_handler3/4 registration node:
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000230/// struct EH4ExceptionRegistration {
231/// void *SavedESP;
232/// _EXCEPTION_POINTERS *ExceptionPointers;
233/// EHRegistrationNode SubRecord;
234/// int32_t EncodedScopeTable;
235/// int32_t TryLevel;
236/// };
Reid Klecknere6531a552015-05-29 22:57:46 +0000237Type *WinEHStatePass::getSEHRegistrationType() {
238 if (SEHRegistrationTy)
239 return SEHRegistrationTy;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000240 LLVMContext &Context = TheModule->getContext();
241 Type *FieldTys[] = {
242 Type::getInt8PtrTy(Context), // void *SavedESP
243 Type::getInt8PtrTy(Context), // void *ExceptionPointers
Reid Klecknere6531a552015-05-29 22:57:46 +0000244 getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000245 Type::getInt32Ty(Context), // int32_t EncodedScopeTable
246 Type::getInt32Ty(Context) // int32_t TryLevel
247 };
Reid Klecknere6531a552015-05-29 22:57:46 +0000248 SEHRegistrationTy = StructType::create(FieldTys, "SEHExceptionRegistration");
249 return SEHRegistrationTy;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000250}
251
252// Emit an exception registration record. These are stack allocations with the
253// common subobject of two pointers: the previous registration record (the old
254// fs:00) and the personality function for the current frame. The data before
255// and after that is personality function specific.
256void WinEHStatePass::emitExceptionRegistrationRecord(Function *F) {
257 assert(Personality == EHPersonality::MSVC_CXX ||
258 Personality == EHPersonality::MSVC_X86SEH);
259
260 StringRef PersonalityName = PersonalityFn->getName();
261 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 // FIXME: We can skip this in -GS- mode, when we figure that out.
267 // SavedESP = llvm.stacksave()
268 Value *SP = Builder.CreateCall(
David Blaikieff6409d2015-05-18 22:13:54 +0000269 Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000270 Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
271 // TryLevel = -1
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000272 StateFieldIndex = 2;
273 insertStateNumberStore(RegNode, Builder.GetInsertPoint(), -1);
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.
281 bool UseStackGuard = (PersonalityName == "_except_handler4");
282 RegNodeTy = getSEHRegistrationType();
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000283 RegNode = Builder.CreateAlloca(RegNodeTy);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000284 // SavedESP = llvm.stacksave()
285 Value *SP = Builder.CreateCall(
David Blaikieff6409d2015-05-18 22:13:54 +0000286 Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000287 Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
Reid Klecknere6531a552015-05-29 22:57:46 +0000288 // TryLevel = -2 / -1
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000289 StateFieldIndex = 4;
Reid Klecknere6531a552015-05-29 22:57:46 +0000290 insertStateNumberStore(RegNode, Builder.GetInsertPoint(),
291 UseStackGuard ? -2 : -1);
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000292 // ScopeTable = llvm.x86.seh.lsda(F)
293 Value *FI8 = Builder.CreateBitCast(F, Int8PtrType);
294 Value *LSDA = Builder.CreateCall(
295 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
Reid Klecknere6531a552015-05-29 22:57:46 +0000296 Type *Int32Ty = Type::getInt32Ty(TheModule->getContext());
297 LSDA = Builder.CreatePtrToInt(LSDA, Int32Ty);
298 // If using _except_handler4, xor the address of the table with
299 // __security_cookie.
300 if (UseStackGuard) {
301 Value *Cookie =
302 TheModule->getOrInsertGlobal("__security_cookie", Int32Ty);
303 Value *Val = Builder.CreateLoad(Int32Ty, Cookie);
304 LSDA = Builder.CreateXor(LSDA, Val);
305 }
306 Builder.CreateStore(LSDA, Builder.CreateStructGEP(RegNodeTy, RegNode, 3));
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000307 Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 2);
308 linkExceptionRegistration(Builder, PersonalityFn);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000309 } else {
310 llvm_unreachable("unexpected personality function");
311 }
312
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000313 // Insert an unlink before all returns.
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000314 for (BasicBlock &BB : *F) {
315 TerminatorInst *T = BB.getTerminator();
316 if (!isa<ReturnInst>(T))
317 continue;
318 Builder.SetInsertPoint(T);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000319 unlinkExceptionRegistration(Builder);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000320 }
321}
322
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000323Value *WinEHStatePass::emitEHLSDA(IRBuilder<> &Builder, Function *F) {
324 Value *FI8 = Builder.CreateBitCast(F, Type::getInt8PtrTy(F->getContext()));
325 return Builder.CreateCall(
326 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
327}
328
329/// Generate a thunk that puts the LSDA of ParentFunc in EAX and then calls
330/// PersonalityFn, forwarding the parameters passed to PEXCEPTION_ROUTINE:
331/// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
332/// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
333/// We essentially want this code:
334/// movl $lsda, %eax
335/// jmpl ___CxxFrameHandler3
336Function *WinEHStatePass::generateLSDAInEAXThunk(Function *ParentFunc) {
337 LLVMContext &Context = ParentFunc->getContext();
338 Type *Int32Ty = Type::getInt32Ty(Context);
339 Type *Int8PtrType = Type::getInt8PtrTy(Context);
340 Type *ArgTys[5] = {Int8PtrType, Int8PtrType, Int8PtrType, Int8PtrType,
341 Int8PtrType};
342 FunctionType *TrampolineTy =
343 FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 4),
344 /*isVarArg=*/false);
345 FunctionType *TargetFuncTy =
346 FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 5),
347 /*isVarArg=*/false);
348 Function *Trampoline = Function::Create(
349 TrampolineTy, GlobalValue::InternalLinkage,
350 Twine("__ehhandler$") + ParentFunc->getName(), TheModule);
351 BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", Trampoline);
352 IRBuilder<> Builder(EntryBB);
353 Value *LSDA = emitEHLSDA(Builder, ParentFunc);
354 Value *CastPersonality =
355 Builder.CreateBitCast(PersonalityFn, TargetFuncTy->getPointerTo());
356 auto AI = Trampoline->arg_begin();
357 Value *Args[5] = {LSDA, AI++, AI++, AI++, AI++};
358 CallInst *Call = Builder.CreateCall(CastPersonality, Args);
359 // Can't use musttail due to prototype mismatch, but we can use tail.
360 Call->setTailCall(true);
361 // Set inreg so we pass it in EAX.
362 Call->addAttribute(1, Attribute::InReg);
363 Builder.CreateRet(Call);
364 return Trampoline;
365}
366
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000367void WinEHStatePass::linkExceptionRegistration(IRBuilder<> &Builder,
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000368 Value *Handler) {
Reid Klecknere6531a552015-05-29 22:57:46 +0000369 Type *LinkTy = getEHLinkRegistrationType();
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000370 // Handler = Handler
371 Handler = Builder.CreateBitCast(Handler, Builder.getInt8PtrTy());
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000372 Builder.CreateStore(Handler, Builder.CreateStructGEP(LinkTy, Link, 1));
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000373 // Next = [fs:00]
374 Constant *FSZero =
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000375 Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000376 Value *Next = Builder.CreateLoad(FSZero);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000377 Builder.CreateStore(Next, Builder.CreateStructGEP(LinkTy, Link, 0));
378 // [fs:00] = Link
379 Builder.CreateStore(Link, FSZero);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000380}
381
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000382void WinEHStatePass::unlinkExceptionRegistration(IRBuilder<> &Builder) {
383 // Clone Link into the current BB for better address mode folding.
384 if (auto *GEP = dyn_cast<GetElementPtrInst>(Link)) {
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000385 GEP = cast<GetElementPtrInst>(GEP->clone());
386 Builder.Insert(GEP);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000387 Link = GEP;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000388 }
Reid Klecknere6531a552015-05-29 22:57:46 +0000389 Type *LinkTy = getEHLinkRegistrationType();
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000390 // [fs:00] = Link->Next
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000391 Value *Next =
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000392 Builder.CreateLoad(Builder.CreateStructGEP(LinkTy, Link, 0));
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000393 Constant *FSZero =
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000394 Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000395 Builder.CreateStore(Next, FSZero);
396}
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000397
398void WinEHStatePass::addCXXStateStores(Function &F, MachineModuleInfo &MMI) {
399 WinEHFuncInfo &FuncInfo = MMI.getWinEHFuncInfo(&F);
400 calculateWinCXXEHStateNumbers(&F, FuncInfo);
401
402 // The base state for the parent is -1.
403 addCXXStateStoresToFunclet(RegNode, FuncInfo, F, -1);
404
405 // Set up RegNodeEscapeIndex
406 int RegNodeEscapeIndex = escapeRegNode(F);
407
408 // Only insert stores in catch handlers.
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000409 Constant *FI8 =
410 ConstantExpr::getBitCast(&F, Type::getInt8PtrTy(TheModule->getContext()));
411 for (auto P : FuncInfo.HandlerBaseState) {
412 Function *Handler = const_cast<Function *>(P.first);
413 int BaseState = P.second;
414 IRBuilder<> Builder(&Handler->getEntryBlock(),
415 Handler->getEntryBlock().begin());
416 // FIXME: Find and reuse such a call if present.
417 Value *ParentFP = Builder.CreateCall(FrameAddress, {Builder.getInt32(1)});
418 Value *RecoveredRegNode = Builder.CreateCall(
419 FrameRecover, {FI8, ParentFP, Builder.getInt32(RegNodeEscapeIndex)});
420 RecoveredRegNode =
421 Builder.CreateBitCast(RecoveredRegNode, RegNodeTy->getPointerTo(0));
422 addCXXStateStoresToFunclet(RecoveredRegNode, FuncInfo, *Handler, BaseState);
423 }
424}
425
426/// Escape RegNode so that we can access it from child handlers. Find the call
427/// to frameescape, if any, in the entry block and append RegNode to the list
428/// of arguments.
429int WinEHStatePass::escapeRegNode(Function &F) {
430 // Find the call to frameescape and extract its arguments.
431 IntrinsicInst *EscapeCall = nullptr;
432 for (Instruction &I : F.getEntryBlock()) {
433 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
434 if (II && II->getIntrinsicID() == Intrinsic::frameescape) {
435 EscapeCall = II;
436 break;
437 }
438 }
439 SmallVector<Value *, 8> Args;
440 if (EscapeCall) {
441 auto Ops = EscapeCall->arg_operands();
442 Args.append(Ops.begin(), Ops.end());
443 }
444 Args.push_back(RegNode);
445
446 // Replace the call (if it exists) with new one. Otherwise, insert at the end
447 // of the entry block.
448 IRBuilder<> Builder(&F.getEntryBlock(),
449 EscapeCall ? EscapeCall : F.getEntryBlock().end());
Reid Klecknerb7403332015-06-08 22:43:32 +0000450 Builder.CreateCall(FrameEscape, Args);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000451 if (EscapeCall)
452 EscapeCall->eraseFromParent();
453 return Args.size() - 1;
454}
455
456void WinEHStatePass::addCXXStateStoresToFunclet(Value *ParentRegNode,
457 WinEHFuncInfo &FuncInfo,
458 Function &F, int BaseState) {
459 // Iterate all the instructions and emit state number stores.
460 for (BasicBlock &BB : F) {
461 for (Instruction &I : BB) {
462 if (auto *CI = dyn_cast<CallInst>(&I)) {
463 // Possibly throwing call instructions have no actions to take after
464 // an unwind. Ensure they are in the -1 state.
465 if (CI->doesNotThrow())
466 continue;
467 insertStateNumberStore(ParentRegNode, CI, BaseState);
468 } else if (auto *II = dyn_cast<InvokeInst>(&I)) {
469 // Look up the state number of the landingpad this unwinds to.
470 LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst();
471 // FIXME: Why does this assertion fail?
472 //assert(FuncInfo.LandingPadStateMap.count(LPI) && "LP has no state!");
473 int State = FuncInfo.LandingPadStateMap[LPI];
474 insertStateNumberStore(ParentRegNode, II, State);
475 }
476 }
477 }
478}
479
Reid Klecknerf12c0302015-06-09 21:42:19 +0000480/// Assign every distinct landingpad a unique state number for SEH. Unlike C++
481/// EH, we can use this very simple algorithm while C++ EH cannot because catch
482/// handlers aren't outlined and the runtime doesn't have to figure out which
483/// catch handler frame to unwind to.
484/// FIXME: __finally blocks are outlined, so this approach may break down there.
485void WinEHStatePass::addSEHStateStores(Function &F, MachineModuleInfo &MMI) {
486 WinEHFuncInfo &FuncInfo = MMI.getWinEHFuncInfo(&F);
487
488 // Iterate all the instructions and emit state number stores.
489 int CurState = 0;
490 for (BasicBlock &BB : F) {
491 for (auto I = BB.begin(), E = BB.end(); I != E; ++I) {
492 if (auto *CI = dyn_cast<CallInst>(I)) {
493 auto *Intrin = dyn_cast<IntrinsicInst>(CI);
494 if (Intrin) {
495 I = rewriteExceptionInfoIntrinsics(Intrin);
496 // Calls that "don't throw" are considered to be able to throw asynch
497 // exceptions, but intrinsics cannot.
498 continue;
499 }
500 insertStateNumberStore(RegNode, CI, -1);
501 } else if (auto *II = dyn_cast<InvokeInst>(I)) {
502 // Look up the state number of the landingpad this unwinds to.
503 LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst();
504 auto InsertionPair =
505 FuncInfo.LandingPadStateMap.insert(std::make_pair(LPI, 0));
506 auto Iter = InsertionPair.first;
507 int &State = Iter->second;
508 bool Inserted = InsertionPair.second;
509 if (Inserted) {
510 // Each action consumes a state number.
511 auto *EHActions = cast<IntrinsicInst>(LPI->getNextNode());
512 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
513 parseEHActions(EHActions, ActionList);
514 assert(!ActionList.empty());
515 CurState += ActionList.size();
516 State += ActionList.size() - 1;
517 }
518 insertStateNumberStore(RegNode, II, State);
519 }
520 }
521 }
522}
523
524/// Rewrite llvm.eh.exceptioncode and llvm.eh.exceptioninfo to memory loads in
525/// IR.
526iplist<Instruction>::iterator
527WinEHStatePass::rewriteExceptionInfoIntrinsics(IntrinsicInst *Intrin) {
528 Intrinsic::ID ID = Intrin->getIntrinsicID();
529 if (ID != Intrinsic::eh_exceptioncode && ID != Intrinsic::eh_exceptioninfo)
530 return Intrin;
531
532 // RegNode->ExceptionPointers
533 IRBuilder<> Builder(Intrin);
534 Value *Ptrs =
535 Builder.CreateLoad(Builder.CreateStructGEP(RegNodeTy, RegNode, 1));
536 Value *Res;
537 if (ID == Intrinsic::eh_exceptioncode) {
538 // Ptrs->ExceptionRecord->Code
539 Ptrs = Builder.CreateBitCast(
540 Ptrs, Builder.getInt32Ty()->getPointerTo()->getPointerTo());
541 Value *Rec = Builder.CreateLoad(Ptrs);
542 Res = Builder.CreateLoad(Rec);
543 } else {
544 Res = Ptrs;
545 }
546 Intrin->replaceAllUsesWith(Res);
547 return Intrin->eraseFromParent();
548}
549
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000550void WinEHStatePass::insertStateNumberStore(Value *ParentRegNode,
551 Instruction *IP, int State) {
552 IRBuilder<> Builder(IP);
553 Value *StateField =
554 Builder.CreateStructGEP(RegNodeTy, ParentRegNode, StateFieldIndex);
555 Builder.CreateStore(Builder.getInt32(State), StateField);
556}