[WinEH] Emit prologues and epilogues for funclets
[oota-llvm.git] / lib / Target / X86 / X86WinEHState.cpp
1 //===-- 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"
19 #include "llvm/CodeGen/MachineModuleInfo.h"
20 #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
36 using namespace llvm;
37 using namespace llvm::PatternMatch;
38
39 #define DEBUG_TYPE "winehstate"
40
41 namespace llvm { void initializeWinEHStatePassPass(PassRegistry &); }
42
43 namespace {
44 class WinEHStatePass : public FunctionPass {
45 public:
46   static char ID; // Pass identification, replacement for typeid.
47
48   WinEHStatePass() : FunctionPass(ID) {
49     initializeWinEHStatePassPass(*PassRegistry::getPassRegistry());
50   }
51
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
64 private:
65   void emitExceptionRegistrationRecord(Function *F);
66
67   void linkExceptionRegistration(IRBuilder<> &Builder, Function *Handler);
68   void unlinkExceptionRegistration(IRBuilder<> &Builder);
69   void addCXXStateStores(Function &F, WinEHFuncInfo &FuncInfo);
70   void addSEHStateStores(Function &F, WinEHFuncInfo &FuncInfo);
71   void addCXXStateStoresToFunclet(Value *ParentRegNode, WinEHFuncInfo &FuncInfo,
72                                   Function &F, int BaseState);
73   void insertStateNumberStore(Value *ParentRegNode, Instruction *IP, int State);
74
75   Value *emitEHLSDA(IRBuilder<> &Builder, Function *F);
76
77   Function *generateLSDAInEAXThunk(Function *ParentFunc);
78
79   int escapeRegNode(Function &F);
80
81   // Module-level type getters.
82   Type *getEHLinkRegistrationType();
83   Type *getSEHRegistrationType();
84   Type *getCXXEHRegistrationType();
85
86   // Per-module data.
87   Module *TheModule = nullptr;
88   StructType *EHLinkRegistrationTy = nullptr;
89   StructType *CXXEHRegistrationTy = nullptr;
90   StructType *SEHRegistrationTy = nullptr;
91   Function *FrameRecover = nullptr;
92   Function *FrameAddress = nullptr;
93   Function *FrameEscape = nullptr;
94
95   // Per-function state
96   EHPersonality Personality = EHPersonality::Unknown;
97   Function *PersonalityFn = nullptr;
98
99   /// The stack allocation containing all EH data, including the link in the
100   /// fs:00 chain and the current state.
101   AllocaInst *RegNode = nullptr;
102
103   /// Struct type of RegNode. Used for GEPing.
104   Type *RegNodeTy = nullptr;
105
106   /// The index of the state field of RegNode.
107   int StateFieldIndex = ~0U;
108
109   /// The linked list node subobject inside of RegNode.
110   Value *Link = nullptr;
111 };
112 }
113
114 FunctionPass *llvm::createX86WinEHStatePass() { return new WinEHStatePass(); }
115
116 char WinEHStatePass::ID = 0;
117
118 INITIALIZE_PASS(WinEHStatePass, "x86-winehstate",
119                 "Insert stores for EH state numbers", false, false)
120
121 bool WinEHStatePass::doInitialization(Module &M) {
122   TheModule = &M;
123   FrameEscape = Intrinsic::getDeclaration(TheModule, Intrinsic::localescape);
124   FrameRecover = Intrinsic::getDeclaration(TheModule, Intrinsic::localrecover);
125   FrameAddress = Intrinsic::getDeclaration(TheModule, Intrinsic::frameaddress);
126   return false;
127 }
128
129 bool WinEHStatePass::doFinalization(Module &M) {
130   assert(TheModule == &M);
131   TheModule = nullptr;
132   EHLinkRegistrationTy = nullptr;
133   CXXEHRegistrationTy = nullptr;
134   SEHRegistrationTy = nullptr;
135   FrameEscape = nullptr;
136   FrameRecover = nullptr;
137   FrameAddress = nullptr;
138   return false;
139 }
140
141 void WinEHStatePass::getAnalysisUsage(AnalysisUsage &AU) const {
142   // This pass should only insert a stack allocation, memory accesses, and
143   // localrecovers.
144   AU.setPreservesCFG();
145 }
146
147 bool WinEHStatePass::runOnFunction(Function &F) {
148   // If this is an outlined handler, don't do anything. We'll do state insertion
149   // for it in the parent.
150   StringRef WinEHParentName =
151       F.getFnAttribute("wineh-parent").getValueAsString();
152   if (WinEHParentName != F.getName() && !WinEHParentName.empty())
153     return false;
154
155   // Check the personality. Do nothing if this is not an MSVC personality.
156   if (!F.hasPersonalityFn())
157     return false;
158   PersonalityFn =
159       dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
160   if (!PersonalityFn)
161     return false;
162   Personality = classifyEHPersonality(PersonalityFn);
163   if (!isMSVCEHPersonality(Personality))
164     return false;
165
166   // Disable frame pointer elimination in this function.
167   // FIXME: Do the nested handlers need to keep the parent ebp in ebp, or can we
168   // use an arbitrary register?
169   F.addFnAttr("no-frame-pointer-elim", "true");
170
171   emitExceptionRegistrationRecord(&F);
172
173   auto *MMI = getAnalysisIfAvailable<MachineModuleInfo>();
174   // If MMI is null, create our own WinEHFuncInfo.  This only happens in opt
175   // tests.
176   std::unique_ptr<WinEHFuncInfo> FuncInfoPtr;
177   if (!MMI)
178     FuncInfoPtr.reset(new WinEHFuncInfo());
179   WinEHFuncInfo &FuncInfo =
180       *(MMI ? &MMI->getWinEHFuncInfo(&F) : FuncInfoPtr.get());
181
182   FuncInfo.EHRegNode = RegNode;
183
184   switch (Personality) {
185   default: llvm_unreachable("unexpected personality function");
186   case EHPersonality::MSVC_CXX:
187     addCXXStateStores(F, FuncInfo);
188     break;
189   case EHPersonality::MSVC_X86SEH:
190     addSEHStateStores(F, FuncInfo);
191     break;
192   }
193
194   // Reset per-function state.
195   PersonalityFn = nullptr;
196   Personality = EHPersonality::Unknown;
197   return true;
198 }
199
200 /// Get the common EH registration subobject:
201 ///   typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
202 ///       _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
203 ///   struct EHRegistrationNode {
204 ///     EHRegistrationNode *Next;
205 ///     PEXCEPTION_ROUTINE Handler;
206 ///   };
207 Type *WinEHStatePass::getEHLinkRegistrationType() {
208   if (EHLinkRegistrationTy)
209     return EHLinkRegistrationTy;
210   LLVMContext &Context = TheModule->getContext();
211   EHLinkRegistrationTy = StructType::create(Context, "EHRegistrationNode");
212   Type *FieldTys[] = {
213       EHLinkRegistrationTy->getPointerTo(0), // EHRegistrationNode *Next
214       Type::getInt8PtrTy(Context) // EXCEPTION_DISPOSITION (*Handler)(...)
215   };
216   EHLinkRegistrationTy->setBody(FieldTys, false);
217   return EHLinkRegistrationTy;
218 }
219
220 /// The __CxxFrameHandler3 registration node:
221 ///   struct CXXExceptionRegistration {
222 ///     void *SavedESP;
223 ///     EHRegistrationNode SubRecord;
224 ///     int32_t TryLevel;
225 ///   };
226 Type *WinEHStatePass::getCXXEHRegistrationType() {
227   if (CXXEHRegistrationTy)
228     return CXXEHRegistrationTy;
229   LLVMContext &Context = TheModule->getContext();
230   Type *FieldTys[] = {
231       Type::getInt8PtrTy(Context), // void *SavedESP
232       getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
233       Type::getInt32Ty(Context)    // int32_t TryLevel
234   };
235   CXXEHRegistrationTy =
236       StructType::create(FieldTys, "CXXExceptionRegistration");
237   return CXXEHRegistrationTy;
238 }
239
240 /// The _except_handler3/4 registration node:
241 ///   struct EH4ExceptionRegistration {
242 ///     void *SavedESP;
243 ///     _EXCEPTION_POINTERS *ExceptionPointers;
244 ///     EHRegistrationNode SubRecord;
245 ///     int32_t EncodedScopeTable;
246 ///     int32_t TryLevel;
247 ///   };
248 Type *WinEHStatePass::getSEHRegistrationType() {
249   if (SEHRegistrationTy)
250     return SEHRegistrationTy;
251   LLVMContext &Context = TheModule->getContext();
252   Type *FieldTys[] = {
253       Type::getInt8PtrTy(Context), // void *SavedESP
254       Type::getInt8PtrTy(Context), // void *ExceptionPointers
255       getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
256       Type::getInt32Ty(Context),   // int32_t EncodedScopeTable
257       Type::getInt32Ty(Context)    // int32_t TryLevel
258   };
259   SEHRegistrationTy = StructType::create(FieldTys, "SEHExceptionRegistration");
260   return SEHRegistrationTy;
261 }
262
263 // Emit an exception registration record. These are stack allocations with the
264 // common subobject of two pointers: the previous registration record (the old
265 // fs:00) and the personality function for the current frame. The data before
266 // and after that is personality function specific.
267 void WinEHStatePass::emitExceptionRegistrationRecord(Function *F) {
268   assert(Personality == EHPersonality::MSVC_CXX ||
269          Personality == EHPersonality::MSVC_X86SEH);
270
271   StringRef PersonalityName = PersonalityFn->getName();
272   IRBuilder<> Builder(&F->getEntryBlock(), F->getEntryBlock().begin());
273   Type *Int8PtrType = Builder.getInt8PtrTy();
274   if (Personality == EHPersonality::MSVC_CXX) {
275     RegNodeTy = getCXXEHRegistrationType();
276     RegNode = Builder.CreateAlloca(RegNodeTy);
277     // SavedESP = llvm.stacksave()
278     Value *SP = Builder.CreateCall(
279         Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
280     Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
281     // TryLevel = -1
282     StateFieldIndex = 2;
283     insertStateNumberStore(RegNode, Builder.GetInsertPoint(), -1);
284     // Handler = __ehhandler$F
285     Function *Trampoline = generateLSDAInEAXThunk(F);
286     Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 1);
287     linkExceptionRegistration(Builder, Trampoline);
288   } else if (Personality == EHPersonality::MSVC_X86SEH) {
289     // If _except_handler4 is in use, some additional guard checks and prologue
290     // stuff is required.
291     bool UseStackGuard = (PersonalityName == "_except_handler4");
292     RegNodeTy = getSEHRegistrationType();
293     RegNode = Builder.CreateAlloca(RegNodeTy);
294     // SavedESP = llvm.stacksave()
295     Value *SP = Builder.CreateCall(
296         Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
297     Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
298     // TryLevel = -2 / -1
299     StateFieldIndex = 4;
300     insertStateNumberStore(RegNode, Builder.GetInsertPoint(),
301                            UseStackGuard ? -2 : -1);
302     // ScopeTable = llvm.x86.seh.lsda(F)
303     Value *FI8 = Builder.CreateBitCast(F, Int8PtrType);
304     Value *LSDA = Builder.CreateCall(
305         Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
306     Type *Int32Ty = Type::getInt32Ty(TheModule->getContext());
307     LSDA = Builder.CreatePtrToInt(LSDA, Int32Ty);
308     // If using _except_handler4, xor the address of the table with
309     // __security_cookie.
310     if (UseStackGuard) {
311       Value *Cookie =
312           TheModule->getOrInsertGlobal("__security_cookie", Int32Ty);
313       Value *Val = Builder.CreateLoad(Int32Ty, Cookie);
314       LSDA = Builder.CreateXor(LSDA, Val);
315     }
316     Builder.CreateStore(LSDA, Builder.CreateStructGEP(RegNodeTy, RegNode, 3));
317     Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 2);
318     linkExceptionRegistration(Builder, PersonalityFn);
319   } else {
320     llvm_unreachable("unexpected personality function");
321   }
322
323   // Insert an unlink before all returns.
324   for (BasicBlock &BB : *F) {
325     TerminatorInst *T = BB.getTerminator();
326     if (!isa<ReturnInst>(T))
327       continue;
328     Builder.SetInsertPoint(T);
329     unlinkExceptionRegistration(Builder);
330   }
331 }
332
333 Value *WinEHStatePass::emitEHLSDA(IRBuilder<> &Builder, Function *F) {
334   Value *FI8 = Builder.CreateBitCast(F, Type::getInt8PtrTy(F->getContext()));
335   return Builder.CreateCall(
336       Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
337 }
338
339 /// Generate a thunk that puts the LSDA of ParentFunc in EAX and then calls
340 /// PersonalityFn, forwarding the parameters passed to PEXCEPTION_ROUTINE:
341 ///   typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
342 ///       _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
343 /// We essentially want this code:
344 ///   movl $lsda, %eax
345 ///   jmpl ___CxxFrameHandler3
346 Function *WinEHStatePass::generateLSDAInEAXThunk(Function *ParentFunc) {
347   LLVMContext &Context = ParentFunc->getContext();
348   Type *Int32Ty = Type::getInt32Ty(Context);
349   Type *Int8PtrType = Type::getInt8PtrTy(Context);
350   Type *ArgTys[5] = {Int8PtrType, Int8PtrType, Int8PtrType, Int8PtrType,
351                      Int8PtrType};
352   FunctionType *TrampolineTy =
353       FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 4),
354                         /*isVarArg=*/false);
355   FunctionType *TargetFuncTy =
356       FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 5),
357                         /*isVarArg=*/false);
358   Function *Trampoline =
359       Function::Create(TrampolineTy, GlobalValue::InternalLinkage,
360                        Twine("__ehhandler$") + GlobalValue::getRealLinkageName(
361                                                    ParentFunc->getName()),
362                        TheModule);
363   BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", Trampoline);
364   IRBuilder<> Builder(EntryBB);
365   Value *LSDA = emitEHLSDA(Builder, ParentFunc);
366   Value *CastPersonality =
367       Builder.CreateBitCast(PersonalityFn, TargetFuncTy->getPointerTo());
368   auto AI = Trampoline->arg_begin();
369   Value *Args[5] = {LSDA, AI++, AI++, AI++, AI++};
370   CallInst *Call = Builder.CreateCall(CastPersonality, Args);
371   // Can't use musttail due to prototype mismatch, but we can use tail.
372   Call->setTailCall(true);
373   // Set inreg so we pass it in EAX.
374   Call->addAttribute(1, Attribute::InReg);
375   Builder.CreateRet(Call);
376   return Trampoline;
377 }
378
379 void WinEHStatePass::linkExceptionRegistration(IRBuilder<> &Builder,
380                                                Function *Handler) {
381   // Emit the .safeseh directive for this function.
382   Handler->addFnAttr("safeseh");
383
384   Type *LinkTy = getEHLinkRegistrationType();
385   // Handler = Handler
386   Value *HandlerI8 = Builder.CreateBitCast(Handler, Builder.getInt8PtrTy());
387   Builder.CreateStore(HandlerI8, Builder.CreateStructGEP(LinkTy, Link, 1));
388   // Next = [fs:00]
389   Constant *FSZero =
390       Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
391   Value *Next = Builder.CreateLoad(FSZero);
392   Builder.CreateStore(Next, Builder.CreateStructGEP(LinkTy, Link, 0));
393   // [fs:00] = Link
394   Builder.CreateStore(Link, FSZero);
395 }
396
397 void WinEHStatePass::unlinkExceptionRegistration(IRBuilder<> &Builder) {
398   // Clone Link into the current BB for better address mode folding.
399   if (auto *GEP = dyn_cast<GetElementPtrInst>(Link)) {
400     GEP = cast<GetElementPtrInst>(GEP->clone());
401     Builder.Insert(GEP);
402     Link = GEP;
403   }
404   Type *LinkTy = getEHLinkRegistrationType();
405   // [fs:00] = Link->Next
406   Value *Next =
407       Builder.CreateLoad(Builder.CreateStructGEP(LinkTy, Link, 0));
408   Constant *FSZero =
409       Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
410   Builder.CreateStore(Next, FSZero);
411 }
412
413 void WinEHStatePass::addCXXStateStores(Function &F, WinEHFuncInfo &FuncInfo) {
414   calculateWinCXXEHStateNumbers(&F, FuncInfo);
415
416   // The base state for the parent is -1.
417   addCXXStateStoresToFunclet(RegNode, FuncInfo, F, -1);
418
419   // Set up RegNodeEscapeIndex
420   int RegNodeEscapeIndex = escapeRegNode(F);
421   FuncInfo.EHRegNodeEscapeIndex = RegNodeEscapeIndex;
422
423   // Only insert stores in catch handlers.
424   Constant *FI8 =
425       ConstantExpr::getBitCast(&F, Type::getInt8PtrTy(TheModule->getContext()));
426   for (auto P : FuncInfo.HandlerBaseState) {
427     Function *Handler = const_cast<Function *>(P.first);
428     int BaseState = P.second;
429     IRBuilder<> Builder(&Handler->getEntryBlock(),
430                         Handler->getEntryBlock().begin());
431     // FIXME: Find and reuse such a call if present.
432     Value *ParentFP = Builder.CreateCall(FrameAddress, {Builder.getInt32(1)});
433     Value *RecoveredRegNode = Builder.CreateCall(
434         FrameRecover, {FI8, ParentFP, Builder.getInt32(RegNodeEscapeIndex)});
435     RecoveredRegNode =
436         Builder.CreateBitCast(RecoveredRegNode, RegNodeTy->getPointerTo(0));
437     addCXXStateStoresToFunclet(RecoveredRegNode, FuncInfo, *Handler, BaseState);
438   }
439 }
440
441 /// Escape RegNode so that we can access it from child handlers. Find the call
442 /// to localescape, if any, in the entry block and append RegNode to the list
443 /// of arguments.
444 int WinEHStatePass::escapeRegNode(Function &F) {
445   // Find the call to localescape and extract its arguments.
446   IntrinsicInst *EscapeCall = nullptr;
447   for (Instruction &I : F.getEntryBlock()) {
448     IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
449     if (II && II->getIntrinsicID() == Intrinsic::localescape) {
450       EscapeCall = II;
451       break;
452     }
453   }
454   SmallVector<Value *, 8> Args;
455   if (EscapeCall) {
456     auto Ops = EscapeCall->arg_operands();
457     Args.append(Ops.begin(), Ops.end());
458   }
459   Args.push_back(RegNode);
460
461   // Replace the call (if it exists) with new one. Otherwise, insert at the end
462   // of the entry block.
463   Instruction *InsertPt = EscapeCall;
464   if (!EscapeCall)
465     InsertPt = F.getEntryBlock().getTerminator();
466   IRBuilder<> Builder(&F.getEntryBlock(), InsertPt);
467   Builder.CreateCall(FrameEscape, Args);
468   if (EscapeCall)
469     EscapeCall->eraseFromParent();
470   return Args.size() - 1;
471 }
472
473 void WinEHStatePass::addCXXStateStoresToFunclet(Value *ParentRegNode,
474                                                 WinEHFuncInfo &FuncInfo,
475                                                 Function &F, int BaseState) {
476   Function *RestoreFrame =
477       Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_restoreframe);
478   // Iterate all the instructions and emit state number stores.
479   for (BasicBlock &BB : F) {
480     for (Instruction &I : BB) {
481       if (auto *CI = dyn_cast<CallInst>(&I)) {
482         // Possibly throwing call instructions have no actions to take after
483         // an unwind. Ensure they are in the -1 state.
484         if (CI->doesNotThrow())
485           continue;
486         insertStateNumberStore(ParentRegNode, CI, BaseState);
487       } else if (auto *II = dyn_cast<InvokeInst>(&I)) {
488         // Look up the state number of the landingpad this unwinds to.
489         Instruction *PadInst = II->getUnwindDest()->getFirstNonPHI();
490         // FIXME: Why does this assertion fail?
491         //assert(FuncInfo.EHPadStateMap.count(PadInst) && "EH Pad has no state!");
492         int State = FuncInfo.EHPadStateMap[PadInst];
493         insertStateNumberStore(ParentRegNode, II, State);
494       }
495     }
496
497     // Insert calls to llvm.x86.seh.restoreframe at catchret destinations.
498     if (auto *CR = dyn_cast<CatchReturnInst>(BB.getTerminator())) {
499       Instruction *Start = CR->getSuccessor()->begin();
500       assert(!isa<PHINode>(Start) &&
501              "winehprepare failed to demote phi after catchret");
502       if (match(Start, m_Intrinsic<Intrinsic::x86_seh_restoreframe>()))
503         continue;
504       IRBuilder<> Builder(Start);
505       Builder.CreateCall(RestoreFrame, {});
506     }
507   }
508 }
509
510 /// Assign every distinct landingpad a unique state number for SEH. Unlike C++
511 /// EH, we can use this very simple algorithm while C++ EH cannot because catch
512 /// handlers aren't outlined and the runtime doesn't have to figure out which
513 /// catch handler frame to unwind to.
514 /// FIXME: __finally blocks are outlined, so this approach may break down there.
515 void WinEHStatePass::addSEHStateStores(Function &F, WinEHFuncInfo &FuncInfo) {
516   // Remember and return the index that we used. We save it in WinEHFuncInfo so
517   // that we can lower llvm.x86.seh.recoverfp later in filter functions without
518   // too much trouble.
519   int RegNodeEscapeIndex = escapeRegNode(F);
520   FuncInfo.EHRegNodeEscapeIndex = RegNodeEscapeIndex;
521
522   // Iterate all the instructions and emit state number stores.
523   int CurState = 0;
524   SmallPtrSet<BasicBlock *, 4> ExceptBlocks;
525   for (BasicBlock &BB : F) {
526     for (auto I = BB.begin(), E = BB.end(); I != E; ++I) {
527       if (auto *CI = dyn_cast<CallInst>(I)) {
528         auto *Intrin = dyn_cast<IntrinsicInst>(CI);
529         if (Intrin) {
530           // Calls that "don't throw" are considered to be able to throw asynch
531           // exceptions, but intrinsics cannot.
532           continue;
533         }
534         insertStateNumberStore(RegNode, CI, -1);
535       } else if (auto *II = dyn_cast<InvokeInst>(I)) {
536         // Look up the state number of the landingpad this unwinds to.
537         LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst();
538         auto InsertionPair =
539             FuncInfo.EHPadStateMap.insert(std::make_pair(LPI, CurState));
540         auto Iter = InsertionPair.first;
541         int &State = Iter->second;
542         bool Inserted = InsertionPair.second;
543         if (Inserted) {
544           // Each action consumes a state number.
545           auto *EHActions = cast<IntrinsicInst>(LPI->getNextNode());
546           SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
547           parseEHActions(EHActions, ActionList);
548           assert(!ActionList.empty());
549           CurState += ActionList.size();
550           State += ActionList.size() - 1;
551
552           // Remember all the __except block targets.
553           for (auto &Handler : ActionList) {
554             if (auto *CH = dyn_cast<CatchHandler>(Handler.get())) {
555               auto *BA = cast<BlockAddress>(CH->getHandlerBlockOrFunc());
556 #ifndef NDEBUG
557               for (BasicBlock *Pred : predecessors(BA->getBasicBlock()))
558                 assert(Pred->isLandingPad() &&
559                        "WinEHPrepare failed to split block");
560 #endif
561               ExceptBlocks.insert(BA->getBasicBlock());
562             }
563           }
564         }
565         insertStateNumberStore(RegNode, II, State);
566       }
567     }
568   }
569
570   // Insert llvm.x86.seh.restoreframe() into each __except block.
571   Function *RestoreFrame =
572       Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_restoreframe);
573   for (BasicBlock *ExceptBB : ExceptBlocks) {
574     IRBuilder<> Builder(ExceptBB->begin());
575     Builder.CreateCall(RestoreFrame, {});
576   }
577 }
578
579 void WinEHStatePass::insertStateNumberStore(Value *ParentRegNode,
580                                             Instruction *IP, int State) {
581   IRBuilder<> Builder(IP);
582   Value *StateField =
583       Builder.CreateStructGEP(RegNodeTy, ParentRegNode, StateFieldIndex);
584   Builder.CreateStore(Builder.getInt32(State), StateField);
585 }