356d0a7713213d9a952d93f5ef017030bbfe607a
[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 {
42 class WinEHStatePass : public FunctionPass {
43 public:
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
60 private:
61   void emitExceptionRegistrationRecord(Function *F);
62
63   void linkExceptionRegistration(IRBuilder<> &Builder, Function *Handler);
64   void unlinkExceptionRegistration(IRBuilder<> &Builder);
65   void addCXXStateStores(Function &F, MachineModuleInfo &MMI);
66   void addSEHStateStores(Function &F, MachineModuleInfo &MMI);
67   void addCXXStateStoresToFunclet(Value *ParentRegNode, WinEHFuncInfo &FuncInfo,
68                                   Function &F, int BaseState);
69   void insertStateNumberStore(Value *ParentRegNode, Instruction *IP, int State);
70
71   Value *emitEHLSDA(IRBuilder<> &Builder, Function *F);
72
73   Function *generateLSDAInEAXThunk(Function *ParentFunc);
74
75   int escapeRegNode(Function &F);
76
77   // Module-level type getters.
78   Type *getEHLinkRegistrationType();
79   Type *getSEHRegistrationType();
80   Type *getCXXEHRegistrationType();
81
82   // Per-module data.
83   Module *TheModule = nullptr;
84   StructType *EHLinkRegistrationTy = nullptr;
85   StructType *CXXEHRegistrationTy = nullptr;
86   StructType *SEHRegistrationTy = nullptr;
87   Function *FrameRecover = nullptr;
88   Function *FrameAddress = nullptr;
89   Function *FrameEscape = nullptr;
90
91   // Per-function state
92   EHPersonality Personality = EHPersonality::Unknown;
93   Function *PersonalityFn = nullptr;
94
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;
107 };
108 }
109
110 FunctionPass *llvm::createX86WinEHStatePass() { return new WinEHStatePass(); }
111
112 char WinEHStatePass::ID = 0;
113
114 bool WinEHStatePass::doInitialization(Module &M) {
115   TheModule = &M;
116   FrameEscape = Intrinsic::getDeclaration(TheModule, Intrinsic::frameescape);
117   FrameRecover = Intrinsic::getDeclaration(TheModule, Intrinsic::framerecover);
118   FrameAddress = Intrinsic::getDeclaration(TheModule, Intrinsic::frameaddress);
119   return false;
120 }
121
122 bool WinEHStatePass::doFinalization(Module &M) {
123   assert(TheModule == &M);
124   TheModule = nullptr;
125   EHLinkRegistrationTy = nullptr;
126   CXXEHRegistrationTy = nullptr;
127   SEHRegistrationTy = nullptr;
128   FrameEscape = nullptr;
129   FrameRecover = nullptr;
130   FrameAddress = nullptr;
131   return false;
132 }
133
134 void WinEHStatePass::getAnalysisUsage(AnalysisUsage &AU) const {
135   // This pass should only insert a stack allocation, memory accesses, and
136   // framerecovers.
137   AU.setPreservesCFG();
138 }
139
140 bool WinEHStatePass::runOnFunction(Function &F) {
141   // 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
148   // Check the personality. Do nothing if this is not an MSVC personality.
149   LandingPadInst *LP = nullptr;
150   for (BasicBlock &BB : F) {
151     LP = BB.getLandingPadInst();
152     if (LP)
153       break;
154   }
155   if (!LP)
156     return false;
157   PersonalityFn =
158       dyn_cast<Function>(LP->getPersonalityFn()->stripPointerCasts());
159   if (!PersonalityFn)
160     return false;
161   Personality = classifyEHPersonality(PersonalityFn);
162   if (!isMSVCEHPersonality(Personality))
163     return false;
164
165   // Disable frame pointer elimination in this function.
166   // FIXME: Do the nested handlers need to keep the parent ebp in ebp, or can we
167   // use an arbitrary register?
168   F.addFnAttr("no-frame-pointer-elim", "true");
169
170   emitExceptionRegistrationRecord(&F);
171
172   auto *MMIPtr = getAnalysisIfAvailable<MachineModuleInfo>();
173   assert(MMIPtr && "MachineModuleInfo should always be available");
174   MachineModuleInfo &MMI = *MMIPtr;
175   switch (Personality) {
176   default: llvm_unreachable("unexpected personality function");
177   case EHPersonality::MSVC_CXX:    addCXXStateStores(F, MMI); break;
178   case EHPersonality::MSVC_X86SEH: addSEHStateStores(F, MMI); break;
179   }
180
181   // Reset per-function state.
182   PersonalityFn = nullptr;
183   Personality = EHPersonality::Unknown;
184   return true;
185 }
186
187 /// Get the common EH registration subobject:
188 ///   typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
189 ///       _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
190 ///   struct EHRegistrationNode {
191 ///     EHRegistrationNode *Next;
192 ///     PEXCEPTION_ROUTINE Handler;
193 ///   };
194 Type *WinEHStatePass::getEHLinkRegistrationType() {
195   if (EHLinkRegistrationTy)
196     return EHLinkRegistrationTy;
197   LLVMContext &Context = TheModule->getContext();
198   EHLinkRegistrationTy = StructType::create(Context, "EHRegistrationNode");
199   Type *FieldTys[] = {
200       EHLinkRegistrationTy->getPointerTo(0), // EHRegistrationNode *Next
201       Type::getInt8PtrTy(Context) // EXCEPTION_DISPOSITION (*Handler)(...)
202   };
203   EHLinkRegistrationTy->setBody(FieldTys, false);
204   return EHLinkRegistrationTy;
205 }
206
207 /// The __CxxFrameHandler3 registration node:
208 ///   struct CXXExceptionRegistration {
209 ///     void *SavedESP;
210 ///     EHRegistrationNode SubRecord;
211 ///     int32_t TryLevel;
212 ///   };
213 Type *WinEHStatePass::getCXXEHRegistrationType() {
214   if (CXXEHRegistrationTy)
215     return CXXEHRegistrationTy;
216   LLVMContext &Context = TheModule->getContext();
217   Type *FieldTys[] = {
218       Type::getInt8PtrTy(Context), // void *SavedESP
219       getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
220       Type::getInt32Ty(Context)    // int32_t TryLevel
221   };
222   CXXEHRegistrationTy =
223       StructType::create(FieldTys, "CXXExceptionRegistration");
224   return CXXEHRegistrationTy;
225 }
226
227 /// The _except_handler3/4 registration node:
228 ///   struct EH4ExceptionRegistration {
229 ///     void *SavedESP;
230 ///     _EXCEPTION_POINTERS *ExceptionPointers;
231 ///     EHRegistrationNode SubRecord;
232 ///     int32_t EncodedScopeTable;
233 ///     int32_t TryLevel;
234 ///   };
235 Type *WinEHStatePass::getSEHRegistrationType() {
236   if (SEHRegistrationTy)
237     return SEHRegistrationTy;
238   LLVMContext &Context = TheModule->getContext();
239   Type *FieldTys[] = {
240       Type::getInt8PtrTy(Context), // void *SavedESP
241       Type::getInt8PtrTy(Context), // void *ExceptionPointers
242       getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
243       Type::getInt32Ty(Context),   // int32_t EncodedScopeTable
244       Type::getInt32Ty(Context)    // int32_t TryLevel
245   };
246   SEHRegistrationTy = StructType::create(FieldTys, "SEHExceptionRegistration");
247   return SEHRegistrationTy;
248 }
249
250 // Emit an exception registration record. These are stack allocations with the
251 // common subobject of two pointers: the previous registration record (the old
252 // fs:00) and the personality function for the current frame. The data before
253 // and after that is personality function specific.
254 void WinEHStatePass::emitExceptionRegistrationRecord(Function *F) {
255   assert(Personality == EHPersonality::MSVC_CXX ||
256          Personality == EHPersonality::MSVC_X86SEH);
257
258   StringRef PersonalityName = PersonalityFn->getName();
259   IRBuilder<> Builder(&F->getEntryBlock(), F->getEntryBlock().begin());
260   Type *Int8PtrType = Builder.getInt8PtrTy();
261   if (Personality == EHPersonality::MSVC_CXX) {
262     RegNodeTy = getCXXEHRegistrationType();
263     RegNode = Builder.CreateAlloca(RegNodeTy);
264     // SavedESP = llvm.stacksave()
265     Value *SP = Builder.CreateCall(
266         Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
267     Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
268     // TryLevel = -1
269     StateFieldIndex = 2;
270     insertStateNumberStore(RegNode, Builder.GetInsertPoint(), -1);
271     // Handler = __ehhandler$F
272     Function *Trampoline = generateLSDAInEAXThunk(F);
273     Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 1);
274     linkExceptionRegistration(Builder, Trampoline);
275   } else if (Personality == EHPersonality::MSVC_X86SEH) {
276     // If _except_handler4 is in use, some additional guard checks and prologue
277     // stuff is required.
278     bool UseStackGuard = (PersonalityName == "_except_handler4");
279     RegNodeTy = getSEHRegistrationType();
280     RegNode = Builder.CreateAlloca(RegNodeTy);
281     // SavedESP = llvm.stacksave()
282     Value *SP = Builder.CreateCall(
283         Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
284     Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
285     // TryLevel = -2 / -1
286     StateFieldIndex = 4;
287     insertStateNumberStore(RegNode, Builder.GetInsertPoint(),
288                            UseStackGuard ? -2 : -1);
289     // ScopeTable = llvm.x86.seh.lsda(F)
290     Value *FI8 = Builder.CreateBitCast(F, Int8PtrType);
291     Value *LSDA = Builder.CreateCall(
292         Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
293     Type *Int32Ty = Type::getInt32Ty(TheModule->getContext());
294     LSDA = Builder.CreatePtrToInt(LSDA, Int32Ty);
295     // If using _except_handler4, xor the address of the table with
296     // __security_cookie.
297     if (UseStackGuard) {
298       Value *Cookie =
299           TheModule->getOrInsertGlobal("__security_cookie", Int32Ty);
300       Value *Val = Builder.CreateLoad(Int32Ty, Cookie);
301       LSDA = Builder.CreateXor(LSDA, Val);
302     }
303     Builder.CreateStore(LSDA, Builder.CreateStructGEP(RegNodeTy, RegNode, 3));
304     Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 2);
305     linkExceptionRegistration(Builder, PersonalityFn);
306   } else {
307     llvm_unreachable("unexpected personality function");
308   }
309
310   // Insert an unlink before all returns.
311   for (BasicBlock &BB : *F) {
312     TerminatorInst *T = BB.getTerminator();
313     if (!isa<ReturnInst>(T))
314       continue;
315     Builder.SetInsertPoint(T);
316     unlinkExceptionRegistration(Builder);
317   }
318 }
319
320 Value *WinEHStatePass::emitEHLSDA(IRBuilder<> &Builder, Function *F) {
321   Value *FI8 = Builder.CreateBitCast(F, Type::getInt8PtrTy(F->getContext()));
322   return Builder.CreateCall(
323       Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
324 }
325
326 /// Generate a thunk that puts the LSDA of ParentFunc in EAX and then calls
327 /// PersonalityFn, forwarding the parameters passed to PEXCEPTION_ROUTINE:
328 ///   typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
329 ///       _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
330 /// We essentially want this code:
331 ///   movl $lsda, %eax
332 ///   jmpl ___CxxFrameHandler3
333 Function *WinEHStatePass::generateLSDAInEAXThunk(Function *ParentFunc) {
334   LLVMContext &Context = ParentFunc->getContext();
335   Type *Int32Ty = Type::getInt32Ty(Context);
336   Type *Int8PtrType = Type::getInt8PtrTy(Context);
337   Type *ArgTys[5] = {Int8PtrType, Int8PtrType, Int8PtrType, Int8PtrType,
338                      Int8PtrType};
339   FunctionType *TrampolineTy =
340       FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 4),
341                         /*isVarArg=*/false);
342   FunctionType *TargetFuncTy =
343       FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 5),
344                         /*isVarArg=*/false);
345   Function *Trampoline = Function::Create(
346       TrampolineTy, GlobalValue::InternalLinkage,
347       Twine("__ehhandler$") + ParentFunc->getName(), TheModule);
348   BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", Trampoline);
349   IRBuilder<> Builder(EntryBB);
350   Value *LSDA = emitEHLSDA(Builder, ParentFunc);
351   Value *CastPersonality =
352       Builder.CreateBitCast(PersonalityFn, TargetFuncTy->getPointerTo());
353   auto AI = Trampoline->arg_begin();
354   Value *Args[5] = {LSDA, AI++, AI++, AI++, AI++};
355   CallInst *Call = Builder.CreateCall(CastPersonality, Args);
356   // Can't use musttail due to prototype mismatch, but we can use tail.
357   Call->setTailCall(true);
358   // Set inreg so we pass it in EAX.
359   Call->addAttribute(1, Attribute::InReg);
360   Builder.CreateRet(Call);
361   return Trampoline;
362 }
363
364 void WinEHStatePass::linkExceptionRegistration(IRBuilder<> &Builder,
365                                                Function *Handler) {
366   // Emit the .safeseh directive for this function.
367   Handler->addFnAttr("safeseh");
368
369   Type *LinkTy = getEHLinkRegistrationType();
370   // Handler = Handler
371   Value *HandlerI8 = Builder.CreateBitCast(Handler, Builder.getInt8PtrTy());
372   Builder.CreateStore(HandlerI8, Builder.CreateStructGEP(LinkTy, Link, 1));
373   // Next = [fs:00]
374   Constant *FSZero =
375       Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
376   Value *Next = Builder.CreateLoad(FSZero);
377   Builder.CreateStore(Next, Builder.CreateStructGEP(LinkTy, Link, 0));
378   // [fs:00] = Link
379   Builder.CreateStore(Link, FSZero);
380 }
381
382 void WinEHStatePass::unlinkExceptionRegistration(IRBuilder<> &Builder) {
383   // Clone Link into the current BB for better address mode folding.
384   if (auto *GEP = dyn_cast<GetElementPtrInst>(Link)) {
385     GEP = cast<GetElementPtrInst>(GEP->clone());
386     Builder.Insert(GEP);
387     Link = GEP;
388   }
389   Type *LinkTy = getEHLinkRegistrationType();
390   // [fs:00] = Link->Next
391   Value *Next =
392       Builder.CreateLoad(Builder.CreateStructGEP(LinkTy, Link, 0));
393   Constant *FSZero =
394       Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
395   Builder.CreateStore(Next, FSZero);
396 }
397
398 void 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.
409   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.
429 int 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());
450   Builder.CreateCall(FrameEscape, Args);
451   if (EscapeCall)
452     EscapeCall->eraseFromParent();
453   return Args.size() - 1;
454 }
455
456 void 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
480 /// 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.
485 void WinEHStatePass::addSEHStateStores(Function &F, MachineModuleInfo &MMI) {
486   WinEHFuncInfo &FuncInfo = MMI.getWinEHFuncInfo(&F);
487
488   // Remember and return the index that we used. We save it in WinEHFuncInfo so
489   // that we can lower llvm.x86.seh.exceptioninfo later in filter functions
490   // without too much trouble.
491   int RegNodeEscapeIndex = escapeRegNode(F);
492   FuncInfo.EHRegNodeEscapeIndex = RegNodeEscapeIndex;
493
494   // Iterate all the instructions and emit state number stores.
495   int CurState = 0;
496   SmallPtrSet<BasicBlock *, 4> ExceptBlocks;
497   for (BasicBlock &BB : F) {
498     for (auto I = BB.begin(), E = BB.end(); I != E; ++I) {
499       if (auto *CI = dyn_cast<CallInst>(I)) {
500         auto *Intrin = dyn_cast<IntrinsicInst>(CI);
501         if (Intrin) {
502           // Calls that "don't throw" are considered to be able to throw asynch
503           // exceptions, but intrinsics cannot.
504           continue;
505         }
506         insertStateNumberStore(RegNode, CI, -1);
507       } else if (auto *II = dyn_cast<InvokeInst>(I)) {
508         // Look up the state number of the landingpad this unwinds to.
509         LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst();
510         auto InsertionPair =
511             FuncInfo.LandingPadStateMap.insert(std::make_pair(LPI, CurState));
512         auto Iter = InsertionPair.first;
513         int &State = Iter->second;
514         bool Inserted = InsertionPair.second;
515         if (Inserted) {
516           // Each action consumes a state number.
517           auto *EHActions = cast<IntrinsicInst>(LPI->getNextNode());
518           SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
519           parseEHActions(EHActions, ActionList);
520           assert(!ActionList.empty());
521           CurState += ActionList.size();
522           State += ActionList.size() - 1;
523
524           // Remember all the __except block targets.
525           for (auto &Handler : ActionList) {
526             if (auto *CH = dyn_cast<CatchHandler>(Handler.get())) {
527               auto *BA = cast<BlockAddress>(CH->getHandlerBlockOrFunc());
528               ExceptBlocks.insert(BA->getBasicBlock());
529             }
530           }
531         }
532         insertStateNumberStore(RegNode, II, State);
533       }
534     }
535   }
536
537   // Insert llvm.stackrestore into each __except block.
538   Function *StackRestore =
539       Intrinsic::getDeclaration(TheModule, Intrinsic::stackrestore);
540   for (BasicBlock *ExceptBB : ExceptBlocks) {
541     IRBuilder<> Builder(ExceptBB->begin());
542     Value *SP =
543         Builder.CreateLoad(Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
544     Builder.CreateCall(StackRestore, {SP});
545   }
546 }
547
548 void WinEHStatePass::insertStateNumberStore(Value *ParentRegNode,
549                                             Instruction *IP, int State) {
550   IRBuilder<> Builder(IP);
551   Value *StateField =
552       Builder.CreateStructGEP(RegNodeTy, ParentRegNode, StateFieldIndex);
553   Builder.CreateStore(Builder.getInt32(State), StateField);
554 }