blob: 1a205e8aec4a93932457a097defc3e726afa6044 [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);
66 void addCXXStateStoresToFunclet(Value *ParentRegNode, WinEHFuncInfo &FuncInfo,
67 Function &F, int BaseState);
68 void insertStateNumberStore(Value *ParentRegNode, Instruction *IP, int State);
Reid Kleckner0738a9c2015-05-05 17:44:16 +000069
Reid Kleckner2632f0d2015-05-20 23:08:04 +000070 Value *emitEHLSDA(IRBuilder<> &Builder, Function *F);
71
72 Function *generateLSDAInEAXThunk(Function *ParentFunc);
73
Reid Klecknerfe4d4912015-05-28 22:00:24 +000074 int escapeRegNode(Function &F);
75
Reid Kleckner0738a9c2015-05-05 17:44:16 +000076 // Module-level type getters.
77 Type *getEHRegistrationType();
78 Type *getSEH3RegistrationType();
79 Type *getSEH4RegistrationType();
80 Type *getCXXEH3RegistrationType();
81
82 // Per-module data.
83 Module *TheModule = nullptr;
84 StructType *EHRegistrationTy = nullptr;
85 StructType *CXXEH3RegistrationTy = nullptr;
86 StructType *SEH3RegistrationTy = nullptr;
87 StructType *SEH4RegistrationTy = nullptr;
88
89 // Per-function state
90 EHPersonality Personality = EHPersonality::Unknown;
91 Function *PersonalityFn = nullptr;
Reid Klecknerfe4d4912015-05-28 22:00:24 +000092
93 /// The stack allocation containing all EH data, including the link in the
94 /// fs:00 chain and the current state.
95 AllocaInst *RegNode = nullptr;
96
97 /// Struct type of RegNode. Used for GEPing.
98 Type *RegNodeTy = nullptr;
99
100 /// The index of the state field of RegNode.
101 int StateFieldIndex = ~0U;
102
103 /// The linked list node subobject inside of RegNode.
104 Value *Link = nullptr;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000105};
106}
107
108FunctionPass *llvm::createX86WinEHStatePass() { return new WinEHStatePass(); }
109
110char WinEHStatePass::ID = 0;
111
112bool WinEHStatePass::doInitialization(Module &M) {
113 TheModule = &M;
114 return false;
115}
116
117bool WinEHStatePass::doFinalization(Module &M) {
118 assert(TheModule == &M);
119 TheModule = nullptr;
120 EHRegistrationTy = nullptr;
121 CXXEH3RegistrationTy = nullptr;
122 SEH3RegistrationTy = nullptr;
123 SEH4RegistrationTy = nullptr;
124 return false;
125}
126
127void WinEHStatePass::getAnalysisUsage(AnalysisUsage &AU) const {
128 // This pass should only insert a stack allocation, memory accesses, and
129 // framerecovers.
130 AU.setPreservesCFG();
131}
132
133bool WinEHStatePass::runOnFunction(Function &F) {
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000134 // If this is an outlined handler, don't do anything. We'll do state insertion
135 // for it in the parent.
136 StringRef WinEHParentName =
137 F.getFnAttribute("wineh-parent").getValueAsString();
138 if (WinEHParentName != F.getName() && !WinEHParentName.empty())
139 return false;
140
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000141 // Check the personality. Do nothing if this is not an MSVC personality.
142 LandingPadInst *LP = nullptr;
143 for (BasicBlock &BB : F) {
144 LP = BB.getLandingPadInst();
145 if (LP)
146 break;
147 }
148 if (!LP)
149 return false;
150 PersonalityFn =
151 dyn_cast<Function>(LP->getPersonalityFn()->stripPointerCasts());
152 if (!PersonalityFn)
153 return false;
154 Personality = classifyEHPersonality(PersonalityFn);
155 if (!isMSVCEHPersonality(Personality))
156 return false;
157
158 emitExceptionRegistrationRecord(&F);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000159
160 auto *MMIPtr = getAnalysisIfAvailable<MachineModuleInfo>();
161 assert(MMIPtr && "MachineModuleInfo should always be available");
162 MachineModuleInfo &MMI = *MMIPtr;
163 if (Personality == EHPersonality::MSVC_CXX) {
164 addCXXStateStores(F, MMI);
165 }
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000166
167 // Reset per-function state.
168 PersonalityFn = nullptr;
169 Personality = EHPersonality::Unknown;
170 return true;
171}
172
173/// Get the common EH registration subobject:
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000174/// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
175/// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000176/// struct EHRegistrationNode {
177/// EHRegistrationNode *Next;
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000178/// PEXCEPTION_ROUTINE Handler;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000179/// };
180Type *WinEHStatePass::getEHRegistrationType() {
181 if (EHRegistrationTy)
182 return EHRegistrationTy;
183 LLVMContext &Context = TheModule->getContext();
184 EHRegistrationTy = StructType::create(Context, "EHRegistrationNode");
185 Type *FieldTys[] = {
186 EHRegistrationTy->getPointerTo(0), // EHRegistrationNode *Next
187 Type::getInt8PtrTy(Context) // EXCEPTION_DISPOSITION (*Handler)(...)
188 };
189 EHRegistrationTy->setBody(FieldTys, false);
190 return EHRegistrationTy;
191}
192
193/// The __CxxFrameHandler3 registration node:
194/// struct CXXExceptionRegistration {
195/// void *SavedESP;
196/// EHRegistrationNode SubRecord;
197/// int32_t TryLevel;
198/// };
199Type *WinEHStatePass::getCXXEH3RegistrationType() {
200 if (CXXEH3RegistrationTy)
201 return CXXEH3RegistrationTy;
202 LLVMContext &Context = TheModule->getContext();
203 Type *FieldTys[] = {
204 Type::getInt8PtrTy(Context), // void *SavedESP
205 getEHRegistrationType(), // EHRegistrationNode SubRecord
206 Type::getInt32Ty(Context) // int32_t TryLevel
207 };
208 CXXEH3RegistrationTy =
209 StructType::create(FieldTys, "CXXExceptionRegistration");
210 return CXXEH3RegistrationTy;
211}
212
213/// The _except_handler3 registration node:
214/// struct EH3ExceptionRegistration {
215/// EHRegistrationNode SubRecord;
216/// void *ScopeTable;
217/// int32_t TryLevel;
218/// };
219Type *WinEHStatePass::getSEH3RegistrationType() {
220 if (SEH3RegistrationTy)
221 return SEH3RegistrationTy;
222 LLVMContext &Context = TheModule->getContext();
223 Type *FieldTys[] = {
224 getEHRegistrationType(), // EHRegistrationNode SubRecord
225 Type::getInt8PtrTy(Context), // void *ScopeTable
226 Type::getInt32Ty(Context) // int32_t TryLevel
227 };
228 SEH3RegistrationTy = StructType::create(FieldTys, "EH3ExceptionRegistration");
229 return SEH3RegistrationTy;
230}
231
232/// The _except_handler4 registration node:
233/// struct EH4ExceptionRegistration {
234/// void *SavedESP;
235/// _EXCEPTION_POINTERS *ExceptionPointers;
236/// EHRegistrationNode SubRecord;
237/// int32_t EncodedScopeTable;
238/// int32_t TryLevel;
239/// };
240Type *WinEHStatePass::getSEH4RegistrationType() {
241 if (SEH4RegistrationTy)
242 return SEH4RegistrationTy;
243 LLVMContext &Context = TheModule->getContext();
244 Type *FieldTys[] = {
245 Type::getInt8PtrTy(Context), // void *SavedESP
246 Type::getInt8PtrTy(Context), // void *ExceptionPointers
247 getEHRegistrationType(), // EHRegistrationNode SubRecord
248 Type::getInt32Ty(Context), // int32_t EncodedScopeTable
249 Type::getInt32Ty(Context) // int32_t TryLevel
250 };
251 SEH4RegistrationTy = StructType::create(FieldTys, "EH4ExceptionRegistration");
252 return SEH4RegistrationTy;
253}
254
255// Emit an exception registration record. These are stack allocations with the
256// common subobject of two pointers: the previous registration record (the old
257// fs:00) and the personality function for the current frame. The data before
258// and after that is personality function specific.
259void WinEHStatePass::emitExceptionRegistrationRecord(Function *F) {
260 assert(Personality == EHPersonality::MSVC_CXX ||
261 Personality == EHPersonality::MSVC_X86SEH);
262
263 StringRef PersonalityName = PersonalityFn->getName();
264 IRBuilder<> Builder(&F->getEntryBlock(), F->getEntryBlock().begin());
265 Type *Int8PtrType = Builder.getInt8PtrTy();
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000266 if (PersonalityName == "__CxxFrameHandler3") {
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000267 RegNodeTy = getCXXEH3RegistrationType();
268 RegNode = Builder.CreateAlloca(RegNodeTy);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000269 // FIXME: We can skip this in -GS- mode, when we figure that out.
270 // SavedESP = llvm.stacksave()
271 Value *SP = Builder.CreateCall(
David Blaikieff6409d2015-05-18 22:13:54 +0000272 Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000273 Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
274 // TryLevel = -1
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000275 StateFieldIndex = 2;
276 insertStateNumberStore(RegNode, Builder.GetInsertPoint(), -1);
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000277 // Handler = __ehhandler$F
278 Function *Trampoline = generateLSDAInEAXThunk(F);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000279 Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 1);
280 linkExceptionRegistration(Builder, Trampoline);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000281 } else if (PersonalityName == "_except_handler3") {
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000282 RegNodeTy = getSEH3RegistrationType();
283 RegNode = Builder.CreateAlloca(RegNodeTy);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000284 // TryLevel = -1
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000285 StateFieldIndex = 2;
286 insertStateNumberStore(RegNode, Builder.GetInsertPoint(), -1);
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000287 // ScopeTable = llvm.x86.seh.lsda(F)
288 Value *LSDA = emitEHLSDA(Builder, F);
289 Builder.CreateStore(LSDA, Builder.CreateStructGEP(RegNodeTy, RegNode, 1));
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000290 Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 0);
291 linkExceptionRegistration(Builder, PersonalityFn);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000292 } else if (PersonalityName == "_except_handler4") {
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000293 RegNodeTy = getSEH4RegistrationType();
294 RegNode = Builder.CreateAlloca(RegNodeTy);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000295 // SavedESP = llvm.stacksave()
296 Value *SP = Builder.CreateCall(
David Blaikieff6409d2015-05-18 22:13:54 +0000297 Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000298 Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000299 // TryLevel = -1
300 StateFieldIndex = 4;
301 insertStateNumberStore(RegNode, Builder.GetInsertPoint(), -1);
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000302 // FIXME: XOR the LSDA with __security_cookie.
303 // ScopeTable = llvm.x86.seh.lsda(F)
304 Value *FI8 = Builder.CreateBitCast(F, Int8PtrType);
305 Value *LSDA = Builder.CreateCall(
306 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
307 Builder.CreateStore(LSDA, Builder.CreateStructGEP(RegNodeTy, RegNode, 1));
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000308 Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 2);
309 linkExceptionRegistration(Builder, PersonalityFn);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000310 } else {
311 llvm_unreachable("unexpected personality function");
312 }
313
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000314 // Insert an unlink before all returns.
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000315 for (BasicBlock &BB : *F) {
316 TerminatorInst *T = BB.getTerminator();
317 if (!isa<ReturnInst>(T))
318 continue;
319 Builder.SetInsertPoint(T);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000320 unlinkExceptionRegistration(Builder);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000321 }
322}
323
Reid Kleckner2632f0d2015-05-20 23:08:04 +0000324Value *WinEHStatePass::emitEHLSDA(IRBuilder<> &Builder, Function *F) {
325 Value *FI8 = Builder.CreateBitCast(F, Type::getInt8PtrTy(F->getContext()));
326 return Builder.CreateCall(
327 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
328}
329
330/// Generate a thunk that puts the LSDA of ParentFunc in EAX and then calls
331/// PersonalityFn, forwarding the parameters passed to PEXCEPTION_ROUTINE:
332/// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
333/// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
334/// We essentially want this code:
335/// movl $lsda, %eax
336/// jmpl ___CxxFrameHandler3
337Function *WinEHStatePass::generateLSDAInEAXThunk(Function *ParentFunc) {
338 LLVMContext &Context = ParentFunc->getContext();
339 Type *Int32Ty = Type::getInt32Ty(Context);
340 Type *Int8PtrType = Type::getInt8PtrTy(Context);
341 Type *ArgTys[5] = {Int8PtrType, Int8PtrType, Int8PtrType, Int8PtrType,
342 Int8PtrType};
343 FunctionType *TrampolineTy =
344 FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 4),
345 /*isVarArg=*/false);
346 FunctionType *TargetFuncTy =
347 FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 5),
348 /*isVarArg=*/false);
349 Function *Trampoline = Function::Create(
350 TrampolineTy, GlobalValue::InternalLinkage,
351 Twine("__ehhandler$") + ParentFunc->getName(), TheModule);
352 BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", Trampoline);
353 IRBuilder<> Builder(EntryBB);
354 Value *LSDA = emitEHLSDA(Builder, ParentFunc);
355 Value *CastPersonality =
356 Builder.CreateBitCast(PersonalityFn, TargetFuncTy->getPointerTo());
357 auto AI = Trampoline->arg_begin();
358 Value *Args[5] = {LSDA, AI++, AI++, AI++, AI++};
359 CallInst *Call = Builder.CreateCall(CastPersonality, Args);
360 // Can't use musttail due to prototype mismatch, but we can use tail.
361 Call->setTailCall(true);
362 // Set inreg so we pass it in EAX.
363 Call->addAttribute(1, Attribute::InReg);
364 Builder.CreateRet(Call);
365 return Trampoline;
366}
367
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000368void WinEHStatePass::linkExceptionRegistration(IRBuilder<> &Builder,
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000369 Value *Handler) {
370 Type *LinkTy = getEHRegistrationType();
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000371 // Handler = Handler
372 Handler = Builder.CreateBitCast(Handler, Builder.getInt8PtrTy());
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000373 Builder.CreateStore(Handler, Builder.CreateStructGEP(LinkTy, Link, 1));
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000374 // Next = [fs:00]
375 Constant *FSZero =
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000376 Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000377 Value *Next = Builder.CreateLoad(FSZero);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000378 Builder.CreateStore(Next, Builder.CreateStructGEP(LinkTy, Link, 0));
379 // [fs:00] = Link
380 Builder.CreateStore(Link, FSZero);
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000381}
382
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000383void WinEHStatePass::unlinkExceptionRegistration(IRBuilder<> &Builder) {
384 // Clone Link into the current BB for better address mode folding.
385 if (auto *GEP = dyn_cast<GetElementPtrInst>(Link)) {
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000386 GEP = cast<GetElementPtrInst>(GEP->clone());
387 Builder.Insert(GEP);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000388 Link = GEP;
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000389 }
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000390 Type *LinkTy = getEHRegistrationType();
391 // [fs:00] = Link->Next
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000392 Value *Next =
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000393 Builder.CreateLoad(Builder.CreateStructGEP(LinkTy, Link, 0));
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000394 Constant *FSZero =
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000395 Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000396 Builder.CreateStore(Next, FSZero);
397}
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000398
399void WinEHStatePass::addCXXStateStores(Function &F, MachineModuleInfo &MMI) {
400 WinEHFuncInfo &FuncInfo = MMI.getWinEHFuncInfo(&F);
401 calculateWinCXXEHStateNumbers(&F, FuncInfo);
402
403 // The base state for the parent is -1.
404 addCXXStateStoresToFunclet(RegNode, FuncInfo, F, -1);
405
406 // Set up RegNodeEscapeIndex
407 int RegNodeEscapeIndex = escapeRegNode(F);
408
409 // Only insert stores in catch handlers.
410 Function *FrameRecover =
411 Intrinsic::getDeclaration(TheModule, Intrinsic::framerecover);
412 Function *FrameAddress =
413 Intrinsic::getDeclaration(TheModule, Intrinsic::frameaddress);
414 Constant *FI8 =
415 ConstantExpr::getBitCast(&F, Type::getInt8PtrTy(TheModule->getContext()));
416 for (auto P : FuncInfo.HandlerBaseState) {
417 Function *Handler = const_cast<Function *>(P.first);
418 int BaseState = P.second;
419 IRBuilder<> Builder(&Handler->getEntryBlock(),
420 Handler->getEntryBlock().begin());
421 // FIXME: Find and reuse such a call if present.
422 Value *ParentFP = Builder.CreateCall(FrameAddress, {Builder.getInt32(1)});
423 Value *RecoveredRegNode = Builder.CreateCall(
424 FrameRecover, {FI8, ParentFP, Builder.getInt32(RegNodeEscapeIndex)});
425 RecoveredRegNode =
426 Builder.CreateBitCast(RecoveredRegNode, RegNodeTy->getPointerTo(0));
427 addCXXStateStoresToFunclet(RecoveredRegNode, FuncInfo, *Handler, BaseState);
428 }
429}
430
431/// Escape RegNode so that we can access it from child handlers. Find the call
432/// to frameescape, if any, in the entry block and append RegNode to the list
433/// of arguments.
434int WinEHStatePass::escapeRegNode(Function &F) {
435 // Find the call to frameescape and extract its arguments.
436 IntrinsicInst *EscapeCall = nullptr;
437 for (Instruction &I : F.getEntryBlock()) {
438 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
439 if (II && II->getIntrinsicID() == Intrinsic::frameescape) {
440 EscapeCall = II;
441 break;
442 }
443 }
444 SmallVector<Value *, 8> Args;
445 if (EscapeCall) {
446 auto Ops = EscapeCall->arg_operands();
447 Args.append(Ops.begin(), Ops.end());
448 }
449 Args.push_back(RegNode);
450
451 // Replace the call (if it exists) with new one. Otherwise, insert at the end
452 // of the entry block.
453 IRBuilder<> Builder(&F.getEntryBlock(),
454 EscapeCall ? EscapeCall : F.getEntryBlock().end());
455 Builder.CreateCall(
456 Intrinsic::getDeclaration(TheModule, Intrinsic::frameescape), Args);
457 if (EscapeCall)
458 EscapeCall->eraseFromParent();
459 return Args.size() - 1;
460}
461
462void WinEHStatePass::addCXXStateStoresToFunclet(Value *ParentRegNode,
463 WinEHFuncInfo &FuncInfo,
464 Function &F, int BaseState) {
465 // Iterate all the instructions and emit state number stores.
466 for (BasicBlock &BB : F) {
467 for (Instruction &I : BB) {
468 if (auto *CI = dyn_cast<CallInst>(&I)) {
469 // Possibly throwing call instructions have no actions to take after
470 // an unwind. Ensure they are in the -1 state.
471 if (CI->doesNotThrow())
472 continue;
473 insertStateNumberStore(ParentRegNode, CI, BaseState);
474 } else if (auto *II = dyn_cast<InvokeInst>(&I)) {
475 // Look up the state number of the landingpad this unwinds to.
476 LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst();
477 // FIXME: Why does this assertion fail?
478 //assert(FuncInfo.LandingPadStateMap.count(LPI) && "LP has no state!");
479 int State = FuncInfo.LandingPadStateMap[LPI];
480 insertStateNumberStore(ParentRegNode, II, State);
481 }
482 }
483 }
484}
485
486void WinEHStatePass::insertStateNumberStore(Value *ParentRegNode,
487 Instruction *IP, int State) {
488 IRBuilder<> Builder(IP);
489 Value *StateField =
490 Builder.CreateStructGEP(RegNodeTy, ParentRegNode, StateFieldIndex);
491 Builder.CreateStore(Builder.getInt32(State), StateField);
492}