xref: /freebsd/contrib/llvm-project/llvm/lib/Target/X86/X86WinEHState.cpp (revision 59c8e88e72633afbc47a4ace0d2170d00d51f7dc)
1 //===-- X86WinEHState - Insert EH state updates for win32 exceptions ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // All functions using an MSVC EH personality use an explicitly updated state
10 // number stored in an exception registration stack object. The registration
11 // object is linked into a thread-local chain of registrations stored at fs:00.
12 // This pass adds the registration object and EH state updates.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "X86.h"
17 #include "llvm/ADT/PostOrderIterator.h"
18 #include "llvm/Analysis/CFG.h"
19 #include "llvm/CodeGen/MachineModuleInfo.h"
20 #include "llvm/CodeGen/WinEHFuncInfo.h"
21 #include "llvm/IR/CFG.h"
22 #include "llvm/IR/EHPersonalities.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/IRBuilder.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/Intrinsics.h"
27 #include "llvm/IR/IntrinsicsX86.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Support/Debug.h"
31 #include <deque>
32 
33 using namespace llvm;
34 
35 #define DEBUG_TYPE "winehstate"
36 
37 namespace {
38 const int OverdefinedState = INT_MIN;
39 
40 class WinEHStatePass : public FunctionPass {
41 public:
42   static char ID; // Pass identification, replacement for typeid.
43 
44   WinEHStatePass() : FunctionPass(ID) { }
45 
46   bool runOnFunction(Function &Fn) override;
47 
48   bool doInitialization(Module &M) override;
49 
50   bool doFinalization(Module &M) override;
51 
52   void getAnalysisUsage(AnalysisUsage &AU) const override;
53 
54   StringRef getPassName() const override {
55     return "Windows 32-bit x86 EH state insertion";
56   }
57 
58 private:
59   void emitExceptionRegistrationRecord(Function *F);
60 
61   void linkExceptionRegistration(IRBuilder<> &Builder, Function *Handler);
62   void unlinkExceptionRegistration(IRBuilder<> &Builder);
63   void addStateStores(Function &F, WinEHFuncInfo &FuncInfo);
64   void insertStateNumberStore(Instruction *IP, int State);
65 
66   Value *emitEHLSDA(IRBuilder<> &Builder, Function *F);
67 
68   Function *generateLSDAInEAXThunk(Function *ParentFunc);
69 
70   bool isStateStoreNeeded(EHPersonality Personality, CallBase &Call);
71   void rewriteSetJmpCall(IRBuilder<> &Builder, Function &F, CallBase &Call,
72                          Value *State);
73   int getBaseStateForBB(DenseMap<BasicBlock *, ColorVector> &BlockColors,
74                         WinEHFuncInfo &FuncInfo, BasicBlock *BB);
75   int getStateForCall(DenseMap<BasicBlock *, ColorVector> &BlockColors,
76                       WinEHFuncInfo &FuncInfo, CallBase &Call);
77 
78   // Module-level type getters.
79   Type *getEHLinkRegistrationType();
80   Type *getSEHRegistrationType();
81   Type *getCXXEHRegistrationType();
82 
83   // Per-module data.
84   Module *TheModule = nullptr;
85   StructType *EHLinkRegistrationTy = nullptr;
86   StructType *CXXEHRegistrationTy = nullptr;
87   StructType *SEHRegistrationTy = nullptr;
88   FunctionCallee SetJmp3 = nullptr;
89   FunctionCallee CxxLongjmpUnwind = nullptr;
90 
91   // Per-function state
92   EHPersonality Personality = EHPersonality::Unknown;
93   Function *PersonalityFn = nullptr;
94   bool UseStackGuard = false;
95   int ParentBaseState = 0;
96   FunctionCallee SehLongjmpUnwind = nullptr;
97   Constant *Cookie = 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   // The allocation containing the EH security guard.
104   AllocaInst *EHGuardNode = 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 } // namespace
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   return false;
124 }
125 
126 bool WinEHStatePass::doFinalization(Module &M) {
127   assert(TheModule == &M);
128   TheModule = nullptr;
129   EHLinkRegistrationTy = nullptr;
130   CXXEHRegistrationTy = nullptr;
131   SEHRegistrationTy = nullptr;
132   SetJmp3 = nullptr;
133   CxxLongjmpUnwind = nullptr;
134   SehLongjmpUnwind = nullptr;
135   Cookie = nullptr;
136   return false;
137 }
138 
139 void WinEHStatePass::getAnalysisUsage(AnalysisUsage &AU) const {
140   // This pass should only insert a stack allocation, memory accesses, and
141   // localrecovers.
142   AU.setPreservesCFG();
143 }
144 
145 bool WinEHStatePass::runOnFunction(Function &F) {
146   // Don't insert state stores or exception handler thunks for
147   // available_externally functions. The handler needs to reference the LSDA,
148   // which will not be emitted in this case.
149   if (F.hasAvailableExternallyLinkage())
150     return false;
151 
152   // Check the personality. Do nothing if this personality doesn't use funclets.
153   if (!F.hasPersonalityFn())
154     return false;
155   PersonalityFn =
156       dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
157   if (!PersonalityFn)
158     return false;
159   Personality = classifyEHPersonality(PersonalityFn);
160   if (!isFuncletEHPersonality(Personality))
161     return false;
162 
163   // Skip this function if there are no EH pads and we aren't using IR-level
164   // outlining.
165   bool HasPads = false;
166   for (BasicBlock &BB : F) {
167     if (BB.isEHPad()) {
168       HasPads = true;
169       break;
170     }
171   }
172   if (!HasPads)
173     return false;
174 
175   Type *Int8PtrType = Type::getInt8PtrTy(TheModule->getContext());
176   SetJmp3 = TheModule->getOrInsertFunction(
177       "_setjmp3", FunctionType::get(
178                       Type::getInt32Ty(TheModule->getContext()),
179                       {Int8PtrType, Type::getInt32Ty(TheModule->getContext())},
180                       /*isVarArg=*/true));
181 
182   emitExceptionRegistrationRecord(&F);
183 
184   // The state numbers calculated here in IR must agree with what we calculate
185   // later on for the MachineFunction. In particular, if an IR pass deletes an
186   // unreachable EH pad after this point before machine CFG construction, we
187   // will be in trouble. If this assumption is ever broken, we should turn the
188   // numbers into an immutable analysis pass.
189   WinEHFuncInfo FuncInfo;
190   addStateStores(F, FuncInfo);
191 
192   // Reset per-function state.
193   PersonalityFn = nullptr;
194   Personality = EHPersonality::Unknown;
195   UseStackGuard = false;
196   RegNode = nullptr;
197   EHGuardNode = nullptr;
198 
199   return true;
200 }
201 
202 /// Get the common EH registration subobject:
203 ///   typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
204 ///       _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
205 ///   struct EHRegistrationNode {
206 ///     EHRegistrationNode *Next;
207 ///     PEXCEPTION_ROUTINE Handler;
208 ///   };
209 Type *WinEHStatePass::getEHLinkRegistrationType() {
210   if (EHLinkRegistrationTy)
211     return EHLinkRegistrationTy;
212   LLVMContext &Context = TheModule->getContext();
213   EHLinkRegistrationTy = StructType::create(Context, "EHRegistrationNode");
214   Type *FieldTys[] = {
215       PointerType::getUnqual(
216           EHLinkRegistrationTy->getContext()), // EHRegistrationNode *Next
217       Type::getInt8PtrTy(Context) // EXCEPTION_DISPOSITION (*Handler)(...)
218   };
219   EHLinkRegistrationTy->setBody(FieldTys, false);
220   return EHLinkRegistrationTy;
221 }
222 
223 /// The __CxxFrameHandler3 registration node:
224 ///   struct CXXExceptionRegistration {
225 ///     void *SavedESP;
226 ///     EHRegistrationNode SubRecord;
227 ///     int32_t TryLevel;
228 ///   };
229 Type *WinEHStatePass::getCXXEHRegistrationType() {
230   if (CXXEHRegistrationTy)
231     return CXXEHRegistrationTy;
232   LLVMContext &Context = TheModule->getContext();
233   Type *FieldTys[] = {
234       Type::getInt8PtrTy(Context), // void *SavedESP
235       getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
236       Type::getInt32Ty(Context)    // int32_t TryLevel
237   };
238   CXXEHRegistrationTy =
239       StructType::create(FieldTys, "CXXExceptionRegistration");
240   return CXXEHRegistrationTy;
241 }
242 
243 /// The _except_handler3/4 registration node:
244 ///   struct EH4ExceptionRegistration {
245 ///     void *SavedESP;
246 ///     _EXCEPTION_POINTERS *ExceptionPointers;
247 ///     EHRegistrationNode SubRecord;
248 ///     int32_t EncodedScopeTable;
249 ///     int32_t TryLevel;
250 ///   };
251 Type *WinEHStatePass::getSEHRegistrationType() {
252   if (SEHRegistrationTy)
253     return SEHRegistrationTy;
254   LLVMContext &Context = TheModule->getContext();
255   Type *FieldTys[] = {
256       Type::getInt8PtrTy(Context), // void *SavedESP
257       Type::getInt8PtrTy(Context), // void *ExceptionPointers
258       getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
259       Type::getInt32Ty(Context),   // int32_t EncodedScopeTable
260       Type::getInt32Ty(Context)    // int32_t TryLevel
261   };
262   SEHRegistrationTy = StructType::create(FieldTys, "SEHExceptionRegistration");
263   return SEHRegistrationTy;
264 }
265 
266 // Emit an exception registration record. These are stack allocations with the
267 // common subobject of two pointers: the previous registration record (the old
268 // fs:00) and the personality function for the current frame. The data before
269 // and after that is personality function specific.
270 void WinEHStatePass::emitExceptionRegistrationRecord(Function *F) {
271   assert(Personality == EHPersonality::MSVC_CXX ||
272          Personality == EHPersonality::MSVC_X86SEH);
273 
274   // Struct type of RegNode. Used for GEPing.
275   Type *RegNodeTy;
276 
277   IRBuilder<> Builder(&F->getEntryBlock(), F->getEntryBlock().begin());
278   Type *Int8PtrType = Builder.getInt8PtrTy();
279   Type *Int32Ty = Builder.getInt32Ty();
280   Type *VoidTy = Builder.getVoidTy();
281 
282   if (Personality == EHPersonality::MSVC_CXX) {
283     RegNodeTy = getCXXEHRegistrationType();
284     RegNode = Builder.CreateAlloca(RegNodeTy);
285     // SavedESP = llvm.stacksave()
286     Value *SP = Builder.CreateCall(
287         Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
288     Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
289     // TryLevel = -1
290     StateFieldIndex = 2;
291     ParentBaseState = -1;
292     insertStateNumberStore(&*Builder.GetInsertPoint(), ParentBaseState);
293     // Handler = __ehhandler$F
294     Function *Trampoline = generateLSDAInEAXThunk(F);
295     Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 1);
296     linkExceptionRegistration(Builder, Trampoline);
297 
298     CxxLongjmpUnwind = TheModule->getOrInsertFunction(
299         "__CxxLongjmpUnwind",
300         FunctionType::get(VoidTy, Int8PtrType, /*isVarArg=*/false));
301     cast<Function>(CxxLongjmpUnwind.getCallee()->stripPointerCasts())
302         ->setCallingConv(CallingConv::X86_StdCall);
303   } else if (Personality == EHPersonality::MSVC_X86SEH) {
304     // If _except_handler4 is in use, some additional guard checks and prologue
305     // stuff is required.
306     StringRef PersonalityName = PersonalityFn->getName();
307     UseStackGuard = (PersonalityName == "_except_handler4");
308 
309     // Allocate local structures.
310     RegNodeTy = getSEHRegistrationType();
311     RegNode = Builder.CreateAlloca(RegNodeTy);
312     if (UseStackGuard)
313       EHGuardNode = Builder.CreateAlloca(Int32Ty);
314 
315     // SavedESP = llvm.stacksave()
316     Value *SP = Builder.CreateCall(
317         Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
318     Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
319     // TryLevel = -2 / -1
320     StateFieldIndex = 4;
321     ParentBaseState = UseStackGuard ? -2 : -1;
322     insertStateNumberStore(&*Builder.GetInsertPoint(), ParentBaseState);
323     // ScopeTable = llvm.x86.seh.lsda(F)
324     Value *LSDA = emitEHLSDA(Builder, F);
325     LSDA = Builder.CreatePtrToInt(LSDA, Int32Ty);
326     // If using _except_handler4, xor the address of the table with
327     // __security_cookie.
328     if (UseStackGuard) {
329       Cookie = TheModule->getOrInsertGlobal("__security_cookie", Int32Ty);
330       Value *Val = Builder.CreateLoad(Int32Ty, Cookie, "cookie");
331       LSDA = Builder.CreateXor(LSDA, Val);
332     }
333     Builder.CreateStore(LSDA, Builder.CreateStructGEP(RegNodeTy, RegNode, 3));
334 
335     // If using _except_handler4, the EHGuard contains: FramePtr xor Cookie.
336     if (UseStackGuard) {
337       Value *Val = Builder.CreateLoad(Int32Ty, Cookie);
338       Value *FrameAddr = Builder.CreateCall(
339           Intrinsic::getDeclaration(
340               TheModule, Intrinsic::frameaddress,
341               Builder.getInt8PtrTy(
342                   TheModule->getDataLayout().getAllocaAddrSpace())),
343           Builder.getInt32(0), "frameaddr");
344       Value *FrameAddrI32 = Builder.CreatePtrToInt(FrameAddr, Int32Ty);
345       FrameAddrI32 = Builder.CreateXor(FrameAddrI32, Val);
346       Builder.CreateStore(FrameAddrI32, EHGuardNode);
347     }
348 
349     // Register the exception handler.
350     Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 2);
351     linkExceptionRegistration(Builder, PersonalityFn);
352 
353     SehLongjmpUnwind = TheModule->getOrInsertFunction(
354         UseStackGuard ? "_seh_longjmp_unwind4" : "_seh_longjmp_unwind",
355         FunctionType::get(Type::getVoidTy(TheModule->getContext()), Int8PtrType,
356                           /*isVarArg=*/false));
357     cast<Function>(SehLongjmpUnwind.getCallee()->stripPointerCasts())
358         ->setCallingConv(CallingConv::X86_StdCall);
359   } else {
360     llvm_unreachable("unexpected personality function");
361   }
362 
363   // Insert an unlink before all returns.
364   for (BasicBlock &BB : *F) {
365     Instruction *T = BB.getTerminator();
366     if (!isa<ReturnInst>(T))
367       continue;
368     Builder.SetInsertPoint(T);
369     unlinkExceptionRegistration(Builder);
370   }
371 }
372 
373 Value *WinEHStatePass::emitEHLSDA(IRBuilder<> &Builder, Function *F) {
374   Value *FI8 = Builder.CreateBitCast(F, Type::getInt8PtrTy(F->getContext()));
375   return Builder.CreateCall(
376       Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
377 }
378 
379 /// Generate a thunk that puts the LSDA of ParentFunc in EAX and then calls
380 /// PersonalityFn, forwarding the parameters passed to PEXCEPTION_ROUTINE:
381 ///   typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
382 ///       _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
383 /// We essentially want this code:
384 ///   movl $lsda, %eax
385 ///   jmpl ___CxxFrameHandler3
386 Function *WinEHStatePass::generateLSDAInEAXThunk(Function *ParentFunc) {
387   LLVMContext &Context = ParentFunc->getContext();
388   Type *Int32Ty = Type::getInt32Ty(Context);
389   Type *Int8PtrType = Type::getInt8PtrTy(Context);
390   Type *ArgTys[5] = {Int8PtrType, Int8PtrType, Int8PtrType, Int8PtrType,
391                      Int8PtrType};
392   FunctionType *TrampolineTy =
393       FunctionType::get(Int32Ty, ArrayRef(&ArgTys[0], 4),
394                         /*isVarArg=*/false);
395   FunctionType *TargetFuncTy =
396       FunctionType::get(Int32Ty, ArrayRef(&ArgTys[0], 5),
397                         /*isVarArg=*/false);
398   Function *Trampoline =
399       Function::Create(TrampolineTy, GlobalValue::InternalLinkage,
400                        Twine("__ehhandler$") + GlobalValue::dropLLVMManglingEscape(
401                                                    ParentFunc->getName()),
402                        TheModule);
403   if (auto *C = ParentFunc->getComdat())
404     Trampoline->setComdat(C);
405   BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", Trampoline);
406   IRBuilder<> Builder(EntryBB);
407   Value *LSDA = emitEHLSDA(Builder, ParentFunc);
408   auto AI = Trampoline->arg_begin();
409   Value *Args[5] = {LSDA, &*AI++, &*AI++, &*AI++, &*AI++};
410   CallInst *Call = Builder.CreateCall(TargetFuncTy, PersonalityFn, Args);
411   // Can't use musttail due to prototype mismatch, but we can use tail.
412   Call->setTailCall(true);
413   // Set inreg so we pass it in EAX.
414   Call->addParamAttr(0, Attribute::InReg);
415   Builder.CreateRet(Call);
416   return Trampoline;
417 }
418 
419 void WinEHStatePass::linkExceptionRegistration(IRBuilder<> &Builder,
420                                                Function *Handler) {
421   // Emit the .safeseh directive for this function.
422   Handler->addFnAttr("safeseh");
423 
424   Type *LinkTy = getEHLinkRegistrationType();
425   // Handler = Handler
426   Value *HandlerI8 = Builder.CreateBitCast(Handler, Builder.getInt8PtrTy());
427   Builder.CreateStore(HandlerI8, Builder.CreateStructGEP(LinkTy, Link, 1));
428   // Next = [fs:00]
429   Constant *FSZero =
430       Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
431   Value *Next = Builder.CreateLoad(LinkTy->getPointerTo(), FSZero);
432   Builder.CreateStore(Next, Builder.CreateStructGEP(LinkTy, Link, 0));
433   // [fs:00] = Link
434   Builder.CreateStore(Link, FSZero);
435 }
436 
437 void WinEHStatePass::unlinkExceptionRegistration(IRBuilder<> &Builder) {
438   // Clone Link into the current BB for better address mode folding.
439   if (auto *GEP = dyn_cast<GetElementPtrInst>(Link)) {
440     GEP = cast<GetElementPtrInst>(GEP->clone());
441     Builder.Insert(GEP);
442     Link = GEP;
443   }
444   Type *LinkTy = getEHLinkRegistrationType();
445   // [fs:00] = Link->Next
446   Value *Next = Builder.CreateLoad(LinkTy->getPointerTo(),
447                                    Builder.CreateStructGEP(LinkTy, Link, 0));
448   Constant *FSZero =
449       Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
450   Builder.CreateStore(Next, FSZero);
451 }
452 
453 // Calls to setjmp(p) are lowered to _setjmp3(p, 0) by the frontend.
454 // The idea behind _setjmp3 is that it takes an optional number of personality
455 // specific parameters to indicate how to restore the personality-specific frame
456 // state when longjmp is initiated.  Typically, the current TryLevel is saved.
457 void WinEHStatePass::rewriteSetJmpCall(IRBuilder<> &Builder, Function &F,
458                                        CallBase &Call, Value *State) {
459   // Don't rewrite calls with a weird number of arguments.
460   if (Call.arg_size() != 2)
461     return;
462 
463   SmallVector<OperandBundleDef, 1> OpBundles;
464   Call.getOperandBundlesAsDefs(OpBundles);
465 
466   SmallVector<Value *, 3> OptionalArgs;
467   if (Personality == EHPersonality::MSVC_CXX) {
468     OptionalArgs.push_back(CxxLongjmpUnwind.getCallee());
469     OptionalArgs.push_back(State);
470     OptionalArgs.push_back(emitEHLSDA(Builder, &F));
471   } else if (Personality == EHPersonality::MSVC_X86SEH) {
472     OptionalArgs.push_back(SehLongjmpUnwind.getCallee());
473     OptionalArgs.push_back(State);
474     if (UseStackGuard)
475       OptionalArgs.push_back(Cookie);
476   } else {
477     llvm_unreachable("unhandled personality!");
478   }
479 
480   SmallVector<Value *, 5> Args;
481   Args.push_back(
482       Builder.CreateBitCast(Call.getArgOperand(0), Builder.getInt8PtrTy()));
483   Args.push_back(Builder.getInt32(OptionalArgs.size()));
484   Args.append(OptionalArgs.begin(), OptionalArgs.end());
485 
486   CallBase *NewCall;
487   if (auto *CI = dyn_cast<CallInst>(&Call)) {
488     CallInst *NewCI = Builder.CreateCall(SetJmp3, Args, OpBundles);
489     NewCI->setTailCallKind(CI->getTailCallKind());
490     NewCall = NewCI;
491   } else {
492     auto *II = cast<InvokeInst>(&Call);
493     NewCall = Builder.CreateInvoke(
494         SetJmp3, II->getNormalDest(), II->getUnwindDest(), Args, OpBundles);
495   }
496   NewCall->setCallingConv(Call.getCallingConv());
497   NewCall->setAttributes(Call.getAttributes());
498   NewCall->setDebugLoc(Call.getDebugLoc());
499 
500   NewCall->takeName(&Call);
501   Call.replaceAllUsesWith(NewCall);
502   Call.eraseFromParent();
503 }
504 
505 // Figure out what state we should assign calls in this block.
506 int WinEHStatePass::getBaseStateForBB(
507     DenseMap<BasicBlock *, ColorVector> &BlockColors, WinEHFuncInfo &FuncInfo,
508     BasicBlock *BB) {
509   int BaseState = ParentBaseState;
510   auto &BBColors = BlockColors[BB];
511 
512   assert(BBColors.size() == 1 && "multi-color BB not removed by preparation");
513   BasicBlock *FuncletEntryBB = BBColors.front();
514   if (auto *FuncletPad =
515           dyn_cast<FuncletPadInst>(FuncletEntryBB->getFirstNonPHI())) {
516     auto BaseStateI = FuncInfo.FuncletBaseStateMap.find(FuncletPad);
517     if (BaseStateI != FuncInfo.FuncletBaseStateMap.end())
518       BaseState = BaseStateI->second;
519   }
520 
521   return BaseState;
522 }
523 
524 // Calculate the state a call-site is in.
525 int WinEHStatePass::getStateForCall(
526     DenseMap<BasicBlock *, ColorVector> &BlockColors, WinEHFuncInfo &FuncInfo,
527     CallBase &Call) {
528   if (auto *II = dyn_cast<InvokeInst>(&Call)) {
529     // Look up the state number of the EH pad this unwinds to.
530     assert(FuncInfo.InvokeStateMap.count(II) && "invoke has no state!");
531     return FuncInfo.InvokeStateMap[II];
532   }
533   // Possibly throwing call instructions have no actions to take after
534   // an unwind. Ensure they are in the -1 state.
535   return getBaseStateForBB(BlockColors, FuncInfo, Call.getParent());
536 }
537 
538 // Calculate the intersection of all the FinalStates for a BasicBlock's
539 // predecessors.
540 static int getPredState(DenseMap<BasicBlock *, int> &FinalStates, Function &F,
541                         int ParentBaseState, BasicBlock *BB) {
542   // The entry block has no predecessors but we know that the prologue always
543   // sets us up with a fixed state.
544   if (&F.getEntryBlock() == BB)
545     return ParentBaseState;
546 
547   // This is an EH Pad, conservatively report this basic block as overdefined.
548   if (BB->isEHPad())
549     return OverdefinedState;
550 
551   int CommonState = OverdefinedState;
552   for (BasicBlock *PredBB : predecessors(BB)) {
553     // We didn't manage to get a state for one of these predecessors,
554     // conservatively report this basic block as overdefined.
555     auto PredEndState = FinalStates.find(PredBB);
556     if (PredEndState == FinalStates.end())
557       return OverdefinedState;
558 
559     // This code is reachable via exceptional control flow,
560     // conservatively report this basic block as overdefined.
561     if (isa<CatchReturnInst>(PredBB->getTerminator()))
562       return OverdefinedState;
563 
564     int PredState = PredEndState->second;
565     assert(PredState != OverdefinedState &&
566            "overdefined BBs shouldn't be in FinalStates");
567     if (CommonState == OverdefinedState)
568       CommonState = PredState;
569 
570     // At least two predecessors have different FinalStates,
571     // conservatively report this basic block as overdefined.
572     if (CommonState != PredState)
573       return OverdefinedState;
574   }
575 
576   return CommonState;
577 }
578 
579 // Calculate the intersection of all the InitialStates for a BasicBlock's
580 // successors.
581 static int getSuccState(DenseMap<BasicBlock *, int> &InitialStates, Function &F,
582                         int ParentBaseState, BasicBlock *BB) {
583   // This block rejoins normal control flow,
584   // conservatively report this basic block as overdefined.
585   if (isa<CatchReturnInst>(BB->getTerminator()))
586     return OverdefinedState;
587 
588   int CommonState = OverdefinedState;
589   for (BasicBlock *SuccBB : successors(BB)) {
590     // We didn't manage to get a state for one of these predecessors,
591     // conservatively report this basic block as overdefined.
592     auto SuccStartState = InitialStates.find(SuccBB);
593     if (SuccStartState == InitialStates.end())
594       return OverdefinedState;
595 
596     // This is an EH Pad, conservatively report this basic block as overdefined.
597     if (SuccBB->isEHPad())
598       return OverdefinedState;
599 
600     int SuccState = SuccStartState->second;
601     assert(SuccState != OverdefinedState &&
602            "overdefined BBs shouldn't be in FinalStates");
603     if (CommonState == OverdefinedState)
604       CommonState = SuccState;
605 
606     // At least two successors have different InitialStates,
607     // conservatively report this basic block as overdefined.
608     if (CommonState != SuccState)
609       return OverdefinedState;
610   }
611 
612   return CommonState;
613 }
614 
615 bool WinEHStatePass::isStateStoreNeeded(EHPersonality Personality,
616                                         CallBase &Call) {
617   // If the function touches memory, it needs a state store.
618   if (isAsynchronousEHPersonality(Personality))
619     return !Call.doesNotAccessMemory();
620 
621   // If the function throws, it needs a state store.
622   return !Call.doesNotThrow();
623 }
624 
625 void WinEHStatePass::addStateStores(Function &F, WinEHFuncInfo &FuncInfo) {
626   // Mark the registration node. The backend needs to know which alloca it is so
627   // that it can recover the original frame pointer.
628   IRBuilder<> Builder(RegNode->getNextNode());
629   Value *RegNodeI8 = Builder.CreateBitCast(RegNode, Builder.getInt8PtrTy());
630   Builder.CreateCall(
631       Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_ehregnode),
632       {RegNodeI8});
633 
634   if (EHGuardNode) {
635     IRBuilder<> Builder(EHGuardNode->getNextNode());
636     Value *EHGuardNodeI8 =
637         Builder.CreateBitCast(EHGuardNode, Builder.getInt8PtrTy());
638     Builder.CreateCall(
639         Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_ehguard),
640         {EHGuardNodeI8});
641   }
642 
643   // Calculate state numbers.
644   if (isAsynchronousEHPersonality(Personality))
645     calculateSEHStateNumbers(&F, FuncInfo);
646   else
647     calculateWinCXXEHStateNumbers(&F, FuncInfo);
648 
649   // Iterate all the instructions and emit state number stores.
650   DenseMap<BasicBlock *, ColorVector> BlockColors = colorEHFunclets(F);
651   ReversePostOrderTraversal<Function *> RPOT(&F);
652 
653   // InitialStates yields the state of the first call-site for a BasicBlock.
654   DenseMap<BasicBlock *, int> InitialStates;
655   // FinalStates yields the state of the last call-site for a BasicBlock.
656   DenseMap<BasicBlock *, int> FinalStates;
657   // Worklist used to revisit BasicBlocks with indeterminate
658   // Initial/Final-States.
659   std::deque<BasicBlock *> Worklist;
660   // Fill in InitialStates and FinalStates for BasicBlocks with call-sites.
661   for (BasicBlock *BB : RPOT) {
662     int InitialState = OverdefinedState;
663     int FinalState;
664     if (&F.getEntryBlock() == BB)
665       InitialState = FinalState = ParentBaseState;
666     for (Instruction &I : *BB) {
667       auto *Call = dyn_cast<CallBase>(&I);
668       if (!Call || !isStateStoreNeeded(Personality, *Call))
669         continue;
670 
671       int State = getStateForCall(BlockColors, FuncInfo, *Call);
672       if (InitialState == OverdefinedState)
673         InitialState = State;
674       FinalState = State;
675     }
676     // No call-sites in this basic block? That's OK, we will come back to these
677     // in a later pass.
678     if (InitialState == OverdefinedState) {
679       Worklist.push_back(BB);
680       continue;
681     }
682     LLVM_DEBUG(dbgs() << "X86WinEHState: " << BB->getName()
683                       << " InitialState=" << InitialState << '\n');
684     LLVM_DEBUG(dbgs() << "X86WinEHState: " << BB->getName()
685                       << " FinalState=" << FinalState << '\n');
686     InitialStates.insert({BB, InitialState});
687     FinalStates.insert({BB, FinalState});
688   }
689 
690   // Try to fill-in InitialStates and FinalStates which have no call-sites.
691   while (!Worklist.empty()) {
692     BasicBlock *BB = Worklist.front();
693     Worklist.pop_front();
694     // This BasicBlock has already been figured out, nothing more we can do.
695     if (InitialStates.count(BB) != 0)
696       continue;
697 
698     int PredState = getPredState(FinalStates, F, ParentBaseState, BB);
699     if (PredState == OverdefinedState)
700       continue;
701 
702     // We successfully inferred this BasicBlock's state via it's predecessors;
703     // enqueue it's successors to see if we can infer their states.
704     InitialStates.insert({BB, PredState});
705     FinalStates.insert({BB, PredState});
706     for (BasicBlock *SuccBB : successors(BB))
707       Worklist.push_back(SuccBB);
708   }
709 
710   // Try to hoist stores from successors.
711   for (BasicBlock *BB : RPOT) {
712     int SuccState = getSuccState(InitialStates, F, ParentBaseState, BB);
713     if (SuccState == OverdefinedState)
714       continue;
715 
716     // Update our FinalState to reflect the common InitialState of our
717     // successors.
718     FinalStates.insert({BB, SuccState});
719   }
720 
721   // Finally, insert state stores before call-sites which transition us to a new
722   // state.
723   for (BasicBlock *BB : RPOT) {
724     auto &BBColors = BlockColors[BB];
725     BasicBlock *FuncletEntryBB = BBColors.front();
726     if (isa<CleanupPadInst>(FuncletEntryBB->getFirstNonPHI()))
727       continue;
728 
729     int PrevState = getPredState(FinalStates, F, ParentBaseState, BB);
730     LLVM_DEBUG(dbgs() << "X86WinEHState: " << BB->getName()
731                       << " PrevState=" << PrevState << '\n');
732 
733     for (Instruction &I : *BB) {
734       auto *Call = dyn_cast<CallBase>(&I);
735       if (!Call || !isStateStoreNeeded(Personality, *Call))
736         continue;
737 
738       int State = getStateForCall(BlockColors, FuncInfo, *Call);
739       if (State != PrevState)
740         insertStateNumberStore(&I, State);
741       PrevState = State;
742     }
743 
744     // We might have hoisted a state store into this block, emit it now.
745     auto EndState = FinalStates.find(BB);
746     if (EndState != FinalStates.end())
747       if (EndState->second != PrevState)
748         insertStateNumberStore(BB->getTerminator(), EndState->second);
749   }
750 
751   SmallVector<CallBase *, 1> SetJmp3Calls;
752   for (BasicBlock *BB : RPOT) {
753     for (Instruction &I : *BB) {
754       auto *Call = dyn_cast<CallBase>(&I);
755       if (!Call)
756         continue;
757       if (Call->getCalledOperand()->stripPointerCasts() !=
758           SetJmp3.getCallee()->stripPointerCasts())
759         continue;
760 
761       SetJmp3Calls.push_back(Call);
762     }
763   }
764 
765   for (CallBase *Call : SetJmp3Calls) {
766     auto &BBColors = BlockColors[Call->getParent()];
767     BasicBlock *FuncletEntryBB = BBColors.front();
768     bool InCleanup = isa<CleanupPadInst>(FuncletEntryBB->getFirstNonPHI());
769 
770     IRBuilder<> Builder(Call);
771     Value *State;
772     if (InCleanup) {
773       Value *StateField = Builder.CreateStructGEP(RegNode->getAllocatedType(),
774                                                   RegNode, StateFieldIndex);
775       State = Builder.CreateLoad(Builder.getInt32Ty(), StateField);
776     } else {
777       State = Builder.getInt32(getStateForCall(BlockColors, FuncInfo, *Call));
778     }
779     rewriteSetJmpCall(Builder, F, *Call, State);
780   }
781 }
782 
783 void WinEHStatePass::insertStateNumberStore(Instruction *IP, int State) {
784   IRBuilder<> Builder(IP);
785   Value *StateField = Builder.CreateStructGEP(RegNode->getAllocatedType(),
786                                               RegNode, StateFieldIndex);
787   Builder.CreateStore(Builder.getInt32(State), StateField);
788 }
789