LLVM  8.0.1
X86WinEHState.cpp
Go to the documentation of this file.
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"
19 #include "llvm/Analysis/CFG.h"
23 #include "llvm/IR/CallSite.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/IRBuilder.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/IntrinsicInst.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) {
46  }
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  StringRef 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 addStateStores(Function &F, WinEHFuncInfo &FuncInfo);
66  void insertStateNumberStore(Instruction *IP, int State);
67 
68  Value *emitEHLSDA(IRBuilder<> &Builder, Function *F);
69 
70  Function *generateLSDAInEAXThunk(Function *ParentFunc);
71 
72  bool isStateStoreNeeded(EHPersonality Personality, CallSite CS);
73  void rewriteSetJmpCallSite(IRBuilder<> &Builder, Function &F, CallSite CS,
74  Value *State);
75  int getBaseStateForBB(DenseMap<BasicBlock *, ColorVector> &BlockColors,
76  WinEHFuncInfo &FuncInfo, BasicBlock *BB);
77  int getStateForCallSite(DenseMap<BasicBlock *, ColorVector> &BlockColors,
78  WinEHFuncInfo &FuncInfo, CallSite CS);
79 
80  // Module-level type getters.
81  Type *getEHLinkRegistrationType();
82  Type *getSEHRegistrationType();
83  Type *getCXXEHRegistrationType();
84 
85  // Per-module data.
86  Module *TheModule = nullptr;
87  StructType *EHLinkRegistrationTy = nullptr;
88  StructType *CXXEHRegistrationTy = nullptr;
89  StructType *SEHRegistrationTy = nullptr;
90  Constant *SetJmp3 = nullptr;
91  Constant *CxxLongjmpUnwind = nullptr;
92 
93  // Per-function state
95  Function *PersonalityFn = nullptr;
96  bool UseStackGuard = false;
97  int ParentBaseState;
98  Constant *SehLongjmpUnwind = nullptr;
99  Constant *Cookie = nullptr;
100 
101  /// The stack allocation containing all EH data, including the link in the
102  /// fs:00 chain and the current state.
103  AllocaInst *RegNode = nullptr;
104 
105  // The allocation containing the EH security guard.
106  AllocaInst *EHGuardNode = nullptr;
107 
108  /// The index of the state field of RegNode.
109  int StateFieldIndex = ~0U;
110 
111  /// The linked list node subobject inside of RegNode.
112  Value *Link = nullptr;
113 };
114 }
115 
116 FunctionPass *llvm::createX86WinEHStatePass() { return new WinEHStatePass(); }
117 
118 char WinEHStatePass::ID = 0;
119 
120 INITIALIZE_PASS(WinEHStatePass, "x86-winehstate",
121  "Insert stores for EH state numbers", false, false)
122 
123 bool WinEHStatePass::doInitialization(Module &M) {
124  TheModule = &M;
125  return false;
126 }
127 
128 bool WinEHStatePass::doFinalization(Module &M) {
129  assert(TheModule == &M);
130  TheModule = nullptr;
131  EHLinkRegistrationTy = nullptr;
132  CXXEHRegistrationTy = nullptr;
133  SEHRegistrationTy = nullptr;
134  SetJmp3 = nullptr;
135  CxxLongjmpUnwind = nullptr;
136  SehLongjmpUnwind = nullptr;
137  Cookie = 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 
148  // Don't insert state stores or exception handler thunks for
149  // available_externally functions. The handler needs to reference the LSDA,
150  // which will not be emitted in this case.
152  return false;
153 
154  // Check the personality. Do nothing if this personality doesn't use funclets.
155  if (!F.hasPersonalityFn())
156  return false;
157  PersonalityFn =
159  if (!PersonalityFn)
160  return false;
161  Personality = classifyEHPersonality(PersonalityFn);
162  if (!isFuncletEHPersonality(Personality))
163  return false;
164 
165  // Skip this function if there are no EH pads and we aren't using IR-level
166  // outlining.
167  bool HasPads = false;
168  for (BasicBlock &BB : F) {
169  if (BB.isEHPad()) {
170  HasPads = true;
171  break;
172  }
173  }
174  if (!HasPads)
175  return false;
176 
177  Type *Int8PtrType = Type::getInt8PtrTy(TheModule->getContext());
178  SetJmp3 = TheModule->getOrInsertFunction(
179  "_setjmp3", FunctionType::get(
180  Type::getInt32Ty(TheModule->getContext()),
181  {Int8PtrType, Type::getInt32Ty(TheModule->getContext())},
182  /*isVarArg=*/true));
183 
184  // Disable frame pointer elimination in this function.
185  // FIXME: Do the nested handlers need to keep the parent ebp in ebp, or can we
186  // use an arbitrary register?
187  F.addFnAttr("no-frame-pointer-elim", "true");
188 
189  emitExceptionRegistrationRecord(&F);
190 
191  // The state numbers calculated here in IR must agree with what we calculate
192  // later on for the MachineFunction. In particular, if an IR pass deletes an
193  // unreachable EH pad after this point before machine CFG construction, we
194  // will be in trouble. If this assumption is ever broken, we should turn the
195  // numbers into an immutable analysis pass.
196  WinEHFuncInfo FuncInfo;
197  addStateStores(F, FuncInfo);
198 
199  // Reset per-function state.
200  PersonalityFn = nullptr;
201  Personality = EHPersonality::Unknown;
202  UseStackGuard = false;
203  RegNode = nullptr;
204  EHGuardNode = nullptr;
205 
206  return true;
207 }
208 
209 /// Get the common EH registration subobject:
210 /// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
211 /// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
212 /// struct EHRegistrationNode {
213 /// EHRegistrationNode *Next;
214 /// PEXCEPTION_ROUTINE Handler;
215 /// };
216 Type *WinEHStatePass::getEHLinkRegistrationType() {
217  if (EHLinkRegistrationTy)
218  return EHLinkRegistrationTy;
219  LLVMContext &Context = TheModule->getContext();
220  EHLinkRegistrationTy = StructType::create(Context, "EHRegistrationNode");
221  Type *FieldTys[] = {
222  EHLinkRegistrationTy->getPointerTo(0), // EHRegistrationNode *Next
223  Type::getInt8PtrTy(Context) // EXCEPTION_DISPOSITION (*Handler)(...)
224  };
225  EHLinkRegistrationTy->setBody(FieldTys, false);
226  return EHLinkRegistrationTy;
227 }
228 
229 /// The __CxxFrameHandler3 registration node:
230 /// struct CXXExceptionRegistration {
231 /// void *SavedESP;
232 /// EHRegistrationNode SubRecord;
233 /// int32_t TryLevel;
234 /// };
235 Type *WinEHStatePass::getCXXEHRegistrationType() {
236  if (CXXEHRegistrationTy)
237  return CXXEHRegistrationTy;
238  LLVMContext &Context = TheModule->getContext();
239  Type *FieldTys[] = {
240  Type::getInt8PtrTy(Context), // void *SavedESP
241  getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
242  Type::getInt32Ty(Context) // int32_t TryLevel
243  };
244  CXXEHRegistrationTy =
245  StructType::create(FieldTys, "CXXExceptionRegistration");
246  return CXXEHRegistrationTy;
247 }
248 
249 /// The _except_handler3/4 registration node:
250 /// struct EH4ExceptionRegistration {
251 /// void *SavedESP;
252 /// _EXCEPTION_POINTERS *ExceptionPointers;
253 /// EHRegistrationNode SubRecord;
254 /// int32_t EncodedScopeTable;
255 /// int32_t TryLevel;
256 /// };
257 Type *WinEHStatePass::getSEHRegistrationType() {
258  if (SEHRegistrationTy)
259  return SEHRegistrationTy;
260  LLVMContext &Context = TheModule->getContext();
261  Type *FieldTys[] = {
262  Type::getInt8PtrTy(Context), // void *SavedESP
263  Type::getInt8PtrTy(Context), // void *ExceptionPointers
264  getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
265  Type::getInt32Ty(Context), // int32_t EncodedScopeTable
266  Type::getInt32Ty(Context) // int32_t TryLevel
267  };
268  SEHRegistrationTy = StructType::create(FieldTys, "SEHExceptionRegistration");
269  return SEHRegistrationTy;
270 }
271 
272 // Emit an exception registration record. These are stack allocations with the
273 // common subobject of two pointers: the previous registration record (the old
274 // fs:00) and the personality function for the current frame. The data before
275 // and after that is personality function specific.
276 void WinEHStatePass::emitExceptionRegistrationRecord(Function *F) {
277  assert(Personality == EHPersonality::MSVC_CXX ||
278  Personality == EHPersonality::MSVC_X86SEH);
279 
280  // Struct type of RegNode. Used for GEPing.
281  Type *RegNodeTy;
282 
283  IRBuilder<> Builder(&F->getEntryBlock(), F->getEntryBlock().begin());
284  Type *Int8PtrType = Builder.getInt8PtrTy();
285  Type *Int32Ty = Builder.getInt32Ty();
286  Type *VoidTy = Builder.getVoidTy();
287 
288  if (Personality == EHPersonality::MSVC_CXX) {
289  RegNodeTy = getCXXEHRegistrationType();
290  RegNode = Builder.CreateAlloca(RegNodeTy);
291  // SavedESP = llvm.stacksave()
292  Value *SP = Builder.CreateCall(
294  Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
295  // TryLevel = -1
296  StateFieldIndex = 2;
297  ParentBaseState = -1;
298  insertStateNumberStore(&*Builder.GetInsertPoint(), ParentBaseState);
299  // Handler = __ehhandler$F
300  Function *Trampoline = generateLSDAInEAXThunk(F);
301  Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 1);
302  linkExceptionRegistration(Builder, Trampoline);
303 
304  CxxLongjmpUnwind = TheModule->getOrInsertFunction(
305  "__CxxLongjmpUnwind",
306  FunctionType::get(VoidTy, Int8PtrType, /*isVarArg=*/false));
307  cast<Function>(CxxLongjmpUnwind->stripPointerCasts())
308  ->setCallingConv(CallingConv::X86_StdCall);
309  } else if (Personality == EHPersonality::MSVC_X86SEH) {
310  // If _except_handler4 is in use, some additional guard checks and prologue
311  // stuff is required.
312  StringRef PersonalityName = PersonalityFn->getName();
313  UseStackGuard = (PersonalityName == "_except_handler4");
314 
315  // Allocate local structures.
316  RegNodeTy = getSEHRegistrationType();
317  RegNode = Builder.CreateAlloca(RegNodeTy);
318  if (UseStackGuard)
319  EHGuardNode = Builder.CreateAlloca(Int32Ty);
320 
321  // SavedESP = llvm.stacksave()
322  Value *SP = Builder.CreateCall(
324  Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
325  // TryLevel = -2 / -1
326  StateFieldIndex = 4;
327  ParentBaseState = UseStackGuard ? -2 : -1;
328  insertStateNumberStore(&*Builder.GetInsertPoint(), ParentBaseState);
329  // ScopeTable = llvm.x86.seh.lsda(F)
330  Value *LSDA = emitEHLSDA(Builder, F);
331  LSDA = Builder.CreatePtrToInt(LSDA, Int32Ty);
332  // If using _except_handler4, xor the address of the table with
333  // __security_cookie.
334  if (UseStackGuard) {
335  Cookie = TheModule->getOrInsertGlobal("__security_cookie", Int32Ty);
336  Value *Val = Builder.CreateLoad(Int32Ty, Cookie, "cookie");
337  LSDA = Builder.CreateXor(LSDA, Val);
338  }
339  Builder.CreateStore(LSDA, Builder.CreateStructGEP(RegNodeTy, RegNode, 3));
340 
341  // If using _except_handler4, the EHGuard contains: FramePtr xor Cookie.
342  if (UseStackGuard) {
343  Value *Val = Builder.CreateLoad(Int32Ty, Cookie);
344  Value *FrameAddr = Builder.CreateCall(
346  Builder.getInt32(0), "frameaddr");
347  Value *FrameAddrI32 = Builder.CreatePtrToInt(FrameAddr, Int32Ty);
348  FrameAddrI32 = Builder.CreateXor(FrameAddrI32, Val);
349  Builder.CreateStore(FrameAddrI32, EHGuardNode);
350  }
351 
352  // Register the exception handler.
353  Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 2);
354  linkExceptionRegistration(Builder, PersonalityFn);
355 
356  SehLongjmpUnwind = TheModule->getOrInsertFunction(
357  UseStackGuard ? "_seh_longjmp_unwind4" : "_seh_longjmp_unwind",
358  FunctionType::get(Type::getVoidTy(TheModule->getContext()), Int8PtrType,
359  /*isVarArg=*/false));
360  cast<Function>(SehLongjmpUnwind->stripPointerCasts())
361  ->setCallingConv(CallingConv::X86_StdCall);
362  } else {
363  llvm_unreachable("unexpected personality function");
364  }
365 
366  // Insert an unlink before all returns.
367  for (BasicBlock &BB : *F) {
368  Instruction *T = BB.getTerminator();
369  if (!isa<ReturnInst>(T))
370  continue;
371  Builder.SetInsertPoint(T);
372  unlinkExceptionRegistration(Builder);
373  }
374 }
375 
376 Value *WinEHStatePass::emitEHLSDA(IRBuilder<> &Builder, Function *F) {
377  Value *FI8 = Builder.CreateBitCast(F, Type::getInt8PtrTy(F->getContext()));
378  return Builder.CreateCall(
380 }
381 
382 /// Generate a thunk that puts the LSDA of ParentFunc in EAX and then calls
383 /// PersonalityFn, forwarding the parameters passed to PEXCEPTION_ROUTINE:
384 /// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
385 /// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
386 /// We essentially want this code:
387 /// movl $lsda, %eax
388 /// jmpl ___CxxFrameHandler3
389 Function *WinEHStatePass::generateLSDAInEAXThunk(Function *ParentFunc) {
390  LLVMContext &Context = ParentFunc->getContext();
391  Type *Int32Ty = Type::getInt32Ty(Context);
392  Type *Int8PtrType = Type::getInt8PtrTy(Context);
393  Type *ArgTys[5] = {Int8PtrType, Int8PtrType, Int8PtrType, Int8PtrType,
394  Int8PtrType};
395  FunctionType *TrampolineTy =
396  FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 4),
397  /*isVarArg=*/false);
398  FunctionType *TargetFuncTy =
399  FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 5),
400  /*isVarArg=*/false);
401  Function *Trampoline =
403  Twine("__ehhandler$") + GlobalValue::dropLLVMManglingEscape(
404  ParentFunc->getName()),
405  TheModule);
406  if (auto *C = ParentFunc->getComdat())
407  Trampoline->setComdat(C);
408  BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", Trampoline);
409  IRBuilder<> Builder(EntryBB);
410  Value *LSDA = emitEHLSDA(Builder, ParentFunc);
411  Value *CastPersonality =
412  Builder.CreateBitCast(PersonalityFn, TargetFuncTy->getPointerTo());
413  auto AI = Trampoline->arg_begin();
414  Value *Args[5] = {LSDA, &*AI++, &*AI++, &*AI++, &*AI++};
415  CallInst *Call = Builder.CreateCall(CastPersonality, Args);
416  // Can't use musttail due to prototype mismatch, but we can use tail.
417  Call->setTailCall(true);
418  // Set inreg so we pass it in EAX.
419  Call->addParamAttr(0, Attribute::InReg);
420  Builder.CreateRet(Call);
421  return Trampoline;
422 }
423 
424 void WinEHStatePass::linkExceptionRegistration(IRBuilder<> &Builder,
425  Function *Handler) {
426  // Emit the .safeseh directive for this function.
427  Handler->addFnAttr("safeseh");
428 
429  Type *LinkTy = getEHLinkRegistrationType();
430  // Handler = Handler
431  Value *HandlerI8 = Builder.CreateBitCast(Handler, Builder.getInt8PtrTy());
432  Builder.CreateStore(HandlerI8, Builder.CreateStructGEP(LinkTy, Link, 1));
433  // Next = [fs:00]
434  Constant *FSZero =
436  Value *Next = Builder.CreateLoad(FSZero);
437  Builder.CreateStore(Next, Builder.CreateStructGEP(LinkTy, Link, 0));
438  // [fs:00] = Link
439  Builder.CreateStore(Link, FSZero);
440 }
441 
442 void WinEHStatePass::unlinkExceptionRegistration(IRBuilder<> &Builder) {
443  // Clone Link into the current BB for better address mode folding.
444  if (auto *GEP = dyn_cast<GetElementPtrInst>(Link)) {
445  GEP = cast<GetElementPtrInst>(GEP->clone());
446  Builder.Insert(GEP);
447  Link = GEP;
448  }
449  Type *LinkTy = getEHLinkRegistrationType();
450  // [fs:00] = Link->Next
451  Value *Next =
452  Builder.CreateLoad(Builder.CreateStructGEP(LinkTy, Link, 0));
453  Constant *FSZero =
455  Builder.CreateStore(Next, FSZero);
456 }
457 
458 // Calls to setjmp(p) are lowered to _setjmp3(p, 0) by the frontend.
459 // The idea behind _setjmp3 is that it takes an optional number of personality
460 // specific parameters to indicate how to restore the personality-specific frame
461 // state when longjmp is initiated. Typically, the current TryLevel is saved.
462 void WinEHStatePass::rewriteSetJmpCallSite(IRBuilder<> &Builder, Function &F,
463  CallSite CS, Value *State) {
464  // Don't rewrite calls with a weird number of arguments.
465  if (CS.getNumArgOperands() != 2)
466  return;
467 
468  Instruction *Inst = CS.getInstruction();
469 
471  CS.getOperandBundlesAsDefs(OpBundles);
472 
473  SmallVector<Value *, 3> OptionalArgs;
474  if (Personality == EHPersonality::MSVC_CXX) {
475  OptionalArgs.push_back(CxxLongjmpUnwind);
476  OptionalArgs.push_back(State);
477  OptionalArgs.push_back(emitEHLSDA(Builder, &F));
478  } else if (Personality == EHPersonality::MSVC_X86SEH) {
479  OptionalArgs.push_back(SehLongjmpUnwind);
480  OptionalArgs.push_back(State);
481  if (UseStackGuard)
482  OptionalArgs.push_back(Cookie);
483  } else {
484  llvm_unreachable("unhandled personality!");
485  }
486 
488  Args.push_back(
489  Builder.CreateBitCast(CS.getArgOperand(0), Builder.getInt8PtrTy()));
490  Args.push_back(Builder.getInt32(OptionalArgs.size()));
491  Args.append(OptionalArgs.begin(), OptionalArgs.end());
492 
493  CallSite NewCS;
494  if (CS.isCall()) {
495  auto *CI = cast<CallInst>(Inst);
496  CallInst *NewCI = Builder.CreateCall(SetJmp3, Args, OpBundles);
497  NewCI->setTailCallKind(CI->getTailCallKind());
498  NewCS = NewCI;
499  } else {
500  auto *II = cast<InvokeInst>(Inst);
501  NewCS = Builder.CreateInvoke(
502  SetJmp3, II->getNormalDest(), II->getUnwindDest(), Args, OpBundles);
503  }
504  NewCS.setCallingConv(CS.getCallingConv());
505  NewCS.setAttributes(CS.getAttributes());
506  NewCS->setDebugLoc(CS->getDebugLoc());
507 
508  Instruction *NewInst = NewCS.getInstruction();
509  NewInst->takeName(Inst);
510  Inst->replaceAllUsesWith(NewInst);
511  Inst->eraseFromParent();
512 }
513 
514 // Figure out what state we should assign calls in this block.
515 int WinEHStatePass::getBaseStateForBB(
516  DenseMap<BasicBlock *, ColorVector> &BlockColors, WinEHFuncInfo &FuncInfo,
517  BasicBlock *BB) {
518  int BaseState = ParentBaseState;
519  auto &BBColors = BlockColors[BB];
520 
521  assert(BBColors.size() == 1 && "multi-color BB not removed by preparation");
522  BasicBlock *FuncletEntryBB = BBColors.front();
523  if (auto *FuncletPad =
524  dyn_cast<FuncletPadInst>(FuncletEntryBB->getFirstNonPHI())) {
525  auto BaseStateI = FuncInfo.FuncletBaseStateMap.find(FuncletPad);
526  if (BaseStateI != FuncInfo.FuncletBaseStateMap.end())
527  BaseState = BaseStateI->second;
528  }
529 
530  return BaseState;
531 }
532 
533 // Calculate the state a call-site is in.
534 int WinEHStatePass::getStateForCallSite(
535  DenseMap<BasicBlock *, ColorVector> &BlockColors, WinEHFuncInfo &FuncInfo,
536  CallSite CS) {
537  if (auto *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
538  // Look up the state number of the EH pad this unwinds to.
539  assert(FuncInfo.InvokeStateMap.count(II) && "invoke has no state!");
540  return FuncInfo.InvokeStateMap[II];
541  }
542  // Possibly throwing call instructions have no actions to take after
543  // an unwind. Ensure they are in the -1 state.
544  return getBaseStateForBB(BlockColors, FuncInfo, CS.getParent());
545 }
546 
547 // Calculate the intersection of all the FinalStates for a BasicBlock's
548 // predecessors.
550  int ParentBaseState, BasicBlock *BB) {
551  // The entry block has no predecessors but we know that the prologue always
552  // sets us up with a fixed state.
553  if (&F.getEntryBlock() == BB)
554  return ParentBaseState;
555 
556  // This is an EH Pad, conservatively report this basic block as overdefined.
557  if (BB->isEHPad())
558  return OverdefinedState;
559 
560  int CommonState = OverdefinedState;
561  for (BasicBlock *PredBB : predecessors(BB)) {
562  // We didn't manage to get a state for one of these predecessors,
563  // conservatively report this basic block as overdefined.
564  auto PredEndState = FinalStates.find(PredBB);
565  if (PredEndState == FinalStates.end())
566  return OverdefinedState;
567 
568  // This code is reachable via exceptional control flow,
569  // conservatively report this basic block as overdefined.
570  if (isa<CatchReturnInst>(PredBB->getTerminator()))
571  return OverdefinedState;
572 
573  int PredState = PredEndState->second;
574  assert(PredState != OverdefinedState &&
575  "overdefined BBs shouldn't be in FinalStates");
576  if (CommonState == OverdefinedState)
577  CommonState = PredState;
578 
579  // At least two predecessors have different FinalStates,
580  // conservatively report this basic block as overdefined.
581  if (CommonState != PredState)
582  return OverdefinedState;
583  }
584 
585  return CommonState;
586 }
587 
588 // Calculate the intersection of all the InitialStates for a BasicBlock's
589 // successors.
590 static int getSuccState(DenseMap<BasicBlock *, int> &InitialStates, Function &F,
591  int ParentBaseState, BasicBlock *BB) {
592  // This block rejoins normal control flow,
593  // conservatively report this basic block as overdefined.
594  if (isa<CatchReturnInst>(BB->getTerminator()))
595  return OverdefinedState;
596 
597  int CommonState = OverdefinedState;
598  for (BasicBlock *SuccBB : successors(BB)) {
599  // We didn't manage to get a state for one of these predecessors,
600  // conservatively report this basic block as overdefined.
601  auto SuccStartState = InitialStates.find(SuccBB);
602  if (SuccStartState == InitialStates.end())
603  return OverdefinedState;
604 
605  // This is an EH Pad, conservatively report this basic block as overdefined.
606  if (SuccBB->isEHPad())
607  return OverdefinedState;
608 
609  int SuccState = SuccStartState->second;
610  assert(SuccState != OverdefinedState &&
611  "overdefined BBs shouldn't be in FinalStates");
612  if (CommonState == OverdefinedState)
613  CommonState = SuccState;
614 
615  // At least two successors have different InitialStates,
616  // conservatively report this basic block as overdefined.
617  if (CommonState != SuccState)
618  return OverdefinedState;
619  }
620 
621  return CommonState;
622 }
623 
624 bool WinEHStatePass::isStateStoreNeeded(EHPersonality Personality,
625  CallSite CS) {
626  if (!CS)
627  return false;
628 
629  // If the function touches memory, it needs a state store.
630  if (isAsynchronousEHPersonality(Personality))
631  return !CS.doesNotAccessMemory();
632 
633  // If the function throws, it needs a state store.
634  return !CS.doesNotThrow();
635 }
636 
637 void WinEHStatePass::addStateStores(Function &F, WinEHFuncInfo &FuncInfo) {
638  // Mark the registration node. The backend needs to know which alloca it is so
639  // that it can recover the original frame pointer.
640  IRBuilder<> Builder(RegNode->getNextNode());
641  Value *RegNodeI8 = Builder.CreateBitCast(RegNode, Builder.getInt8PtrTy());
642  Builder.CreateCall(
644  {RegNodeI8});
645 
646  if (EHGuardNode) {
647  IRBuilder<> Builder(EHGuardNode->getNextNode());
648  Value *EHGuardNodeI8 =
649  Builder.CreateBitCast(EHGuardNode, Builder.getInt8PtrTy());
650  Builder.CreateCall(
652  {EHGuardNodeI8});
653  }
654 
655  // Calculate state numbers.
656  if (isAsynchronousEHPersonality(Personality))
657  calculateSEHStateNumbers(&F, FuncInfo);
658  else
659  calculateWinCXXEHStateNumbers(&F, FuncInfo);
660 
661  // Iterate all the instructions and emit state number stores.
664 
665  // InitialStates yields the state of the first call-site for a BasicBlock.
666  DenseMap<BasicBlock *, int> InitialStates;
667  // FinalStates yields the state of the last call-site for a BasicBlock.
668  DenseMap<BasicBlock *, int> FinalStates;
669  // Worklist used to revisit BasicBlocks with indeterminate
670  // Initial/Final-States.
671  std::deque<BasicBlock *> Worklist;
672  // Fill in InitialStates and FinalStates for BasicBlocks with call-sites.
673  for (BasicBlock *BB : RPOT) {
674  int InitialState = OverdefinedState;
675  int FinalState;
676  if (&F.getEntryBlock() == BB)
677  InitialState = FinalState = ParentBaseState;
678  for (Instruction &I : *BB) {
679  CallSite CS(&I);
680  if (!isStateStoreNeeded(Personality, CS))
681  continue;
682 
683  int State = getStateForCallSite(BlockColors, FuncInfo, CS);
684  if (InitialState == OverdefinedState)
685  InitialState = State;
686  FinalState = State;
687  }
688  // No call-sites in this basic block? That's OK, we will come back to these
689  // in a later pass.
690  if (InitialState == OverdefinedState) {
691  Worklist.push_back(BB);
692  continue;
693  }
694  LLVM_DEBUG(dbgs() << "X86WinEHState: " << BB->getName()
695  << " InitialState=" << InitialState << '\n');
696  LLVM_DEBUG(dbgs() << "X86WinEHState: " << BB->getName()
697  << " FinalState=" << FinalState << '\n');
698  InitialStates.insert({BB, InitialState});
699  FinalStates.insert({BB, FinalState});
700  }
701 
702  // Try to fill-in InitialStates and FinalStates which have no call-sites.
703  while (!Worklist.empty()) {
704  BasicBlock *BB = Worklist.front();
705  Worklist.pop_front();
706  // This BasicBlock has already been figured out, nothing more we can do.
707  if (InitialStates.count(BB) != 0)
708  continue;
709 
710  int PredState = getPredState(FinalStates, F, ParentBaseState, BB);
711  if (PredState == OverdefinedState)
712  continue;
713 
714  // We successfully inferred this BasicBlock's state via it's predecessors;
715  // enqueue it's successors to see if we can infer their states.
716  InitialStates.insert({BB, PredState});
717  FinalStates.insert({BB, PredState});
718  for (BasicBlock *SuccBB : successors(BB))
719  Worklist.push_back(SuccBB);
720  }
721 
722  // Try to hoist stores from successors.
723  for (BasicBlock *BB : RPOT) {
724  int SuccState = getSuccState(InitialStates, F, ParentBaseState, BB);
725  if (SuccState == OverdefinedState)
726  continue;
727 
728  // Update our FinalState to reflect the common InitialState of our
729  // successors.
730  FinalStates.insert({BB, SuccState});
731  }
732 
733  // Finally, insert state stores before call-sites which transition us to a new
734  // state.
735  for (BasicBlock *BB : RPOT) {
736  auto &BBColors = BlockColors[BB];
737  BasicBlock *FuncletEntryBB = BBColors.front();
738  if (isa<CleanupPadInst>(FuncletEntryBB->getFirstNonPHI()))
739  continue;
740 
741  int PrevState = getPredState(FinalStates, F, ParentBaseState, BB);
742  LLVM_DEBUG(dbgs() << "X86WinEHState: " << BB->getName()
743  << " PrevState=" << PrevState << '\n');
744 
745  for (Instruction &I : *BB) {
746  CallSite CS(&I);
747  if (!isStateStoreNeeded(Personality, CS))
748  continue;
749 
750  int State = getStateForCallSite(BlockColors, FuncInfo, CS);
751  if (State != PrevState)
752  insertStateNumberStore(&I, State);
753  PrevState = State;
754  }
755 
756  // We might have hoisted a state store into this block, emit it now.
757  auto EndState = FinalStates.find(BB);
758  if (EndState != FinalStates.end())
759  if (EndState->second != PrevState)
760  insertStateNumberStore(BB->getTerminator(), EndState->second);
761  }
762 
763  SmallVector<CallSite, 1> SetJmp3CallSites;
764  for (BasicBlock *BB : RPOT) {
765  for (Instruction &I : *BB) {
766  CallSite CS(&I);
767  if (!CS)
768  continue;
769  if (CS.getCalledValue()->stripPointerCasts() !=
770  SetJmp3->stripPointerCasts())
771  continue;
772 
773  SetJmp3CallSites.push_back(CS);
774  }
775  }
776 
777  for (CallSite CS : SetJmp3CallSites) {
778  auto &BBColors = BlockColors[CS->getParent()];
779  BasicBlock *FuncletEntryBB = BBColors.front();
780  bool InCleanup = isa<CleanupPadInst>(FuncletEntryBB->getFirstNonPHI());
781 
782  IRBuilder<> Builder(CS.getInstruction());
783  Value *State;
784  if (InCleanup) {
785  Value *StateField =
786  Builder.CreateStructGEP(nullptr, RegNode, StateFieldIndex);
787  State = Builder.CreateLoad(StateField);
788  } else {
789  State = Builder.getInt32(getStateForCallSite(BlockColors, FuncInfo, CS));
790  }
791  rewriteSetJmpCallSite(Builder, F, CS, State);
792  }
793 }
794 
795 void WinEHStatePass::insertStateNumberStore(Instruction *IP, int State) {
796  IRBuilder<> Builder(IP);
797  Value *StateField =
798  Builder.CreateStructGEP(nullptr, RegNode, StateFieldIndex);
799  Builder.CreateStore(Builder.getInt32(State), StateField);
800 }
uint64_t CallInst * C
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks &#39;this&#39; from the containing basic block and deletes it.
Definition: Instruction.cpp:68
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
LLVMContext & Context
CallingConv::ID getCallingConv() const
Get the calling convention of the call.
Definition: CallSite.h:312
This class represents lattice values for constants.
Definition: AllocatorList.h:24
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve &#39;CreateLoad(Ty, Ptr, "...")&#39; correctly, instead of converting the string to &#39;bool...
Definition: IRBuilder.h:1357
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
DenseMap< const FuncletPadInst *, int > FuncletBaseStateMap
Definition: WinEHFuncInfo.h:93
This class represents a function call, abstracting a target machine&#39;s calling convention.
bool hasAvailableExternallyLinkage() const
Definition: GlobalValue.h:423
F(f)
Hexagon Common GEP
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:138
static int getPredState(DenseMap< BasicBlock *, int > &FinalStates, Function &F, int ParentBaseState, BasicBlock *BB)
static Constant * getNullValue(Type *Ty)
Constructor to create a &#39;0&#39; constant of arbitrary type.
Definition: Constants.cpp:265
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:269
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:221
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
void calculateSEHStateNumbers(const Function *ParentFn, WinEHFuncInfo &FuncInfo)
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Definition: ArrayRef.h:451
Class to represent struct types.
Definition: DerivedTypes.h:201
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
Definition: Type.cpp:652
ReturnInst * CreateRet(Value *V)
Create a &#39;ret <val>&#39; instruction.
Definition: IRBuilder.h:829
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:743
InstrTy * getInstruction() const
Definition: CallSite.h:92
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition: IRBuilder.h:1386
ValTy * getCalledValue() const
Return the pointer to function that is being called.
Definition: CallSite.h:100
Class to represent function types.
Definition: DerivedTypes.h:103
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1732
ValTy * getArgOperand(unsigned i) const
Definition: CallSite.h:297
void setComdat(Comdat *C)
Definition: GlobalObject.h:103
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition: Function.h:702
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:429
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:291
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1020
bool isCall() const
Return true if a CallInst is enclosed.
Definition: CallSite.h:87
const BasicBlock & getEntryBlock() const
Definition: Function.h:640
void setAttributes(AttributeList PAL)
Set the parameter attributes of the call.
Definition: CallSite.h:333
static bool runOnFunction(Function &F, bool PostInlining)
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:136
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
Definition: BasicBlock.cpp:190
LLVM Basic Block Representation.
Definition: BasicBlock.h:58
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:69
This is an important base class in LLVM.
Definition: Constant.h:42
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:129
const Instruction & front() const
Definition: BasicBlock.h:281
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
Represent the analysis usage information of a pass.
static Type * getVoidTy(LLVMContext &C)
Definition: Type.cpp:161
void setCallingConv(CallingConv::ID CC)
Set the calling convention of the call.
Definition: CallSite.h:316
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:285
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
Definition: Type.cpp:297
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:100
arg_iterator arg_begin()
Definition: Function.h:671
DenseMap< const InvokeInst *, int > InvokeStateMap
Definition: WinEHFuncInfo.h:94
void setTailCallKind(TailCallKind TCK)
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:193
void setTailCall(bool isTC=true)
const Constant * stripPointerCasts() const
Definition: Constant.h:174
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs, and aliases.
Definition: Value.cpp:529
unsigned getNumArgOperands() const
Definition: CallSite.h:293
size_t size() const
Definition: SmallVector.h:53
PointerType * getInt8PtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer to an 8-bit integer value.
Definition: IRBuilder.h:385
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:220
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
InvokeInst * CreateInvoke(FunctionType *Ty, Value *Callee, BasicBlock *NormalDest, BasicBlock *UnwindDest, ArrayRef< Value *> Args, ArrayRef< OperandBundleDef > OpBundles, const Twine &Name="")
Create an invoke instruction.
Definition: IRBuilder.h:892
void calculateWinCXXEHStateNumbers(const Function *ParentFn, WinEHFuncInfo &FuncInfo)
Analyze the IR in ParentFn and it&#39;s handlers to build WinEHFuncInfo, which describes the state number...
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
Definition: InstrTypes.h:1275
bool isFuncletEHPersonality(EHPersonality Pers)
Returns true if this is a personality function that invokes handler funclets (which must return to it...
static int getSuccState(DenseMap< BasicBlock *, int > &InitialStates, Function &F, int ParentBaseState, BasicBlock *BB)
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
Module.h This file contains the declarations for the Module class.
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition: IRBuilder.h:307
pred_range predecessors(BasicBlock *BB)
Definition: CFG.h:125
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:286
BBTy * getParent() const
Get the basic block containing the call site.
Definition: CallSite.h:97
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:133
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character &#39;\1&#39;, drop it.
Definition: GlobalValue.h:472
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:394
bool doesNotAccessMemory() const
Determine if the call does not access memory.
Definition: CallSite.h:446
const Comdat * getComdat() const
Definition: GlobalObject.h:101
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:133
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:176
void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Definition: CallSite.h:582
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:214
#define I(x, y, z)
Definition: MD5.cpp:58
bool doesNotThrow() const
Determine if the call cannot unwind.
Definition: CallSite.h:505
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
Rename collisions when linking (static functions).
Definition: GlobalValue.h:56
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1974
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: DenseMap.h:171
INITIALIZE_PASS(WinEHStatePass, "x86-winehstate", "Insert stores for EH state numbers", false, false) bool WinEHStatePass
void initializeWinEHStatePassPass(PassRegistry &)
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
Definition: IRBuilder.h:794
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
X86_StdCall - stdcall is the calling conventions mostly used by the Win32 API.
Definition: CallingConv.h:87
bool isAsynchronousEHPersonality(EHPersonality Pers)
Returns true if this personality function catches asynchronous exceptions.
bool isEHPad() const
Return true if this basic block is an exception handling block.
Definition: BasicBlock.h:399
LLVM Value Representation.
Definition: Value.h:73
Constant * getPersonalityFn() const
Get the personality function associated with this function.
Definition: Function.cpp:1299
succ_range successors(Instruction *I)
Definition: CFG.h:264
static StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition: Type.cpp:437
Value * CreateStructGEP(Type *Ty, Value *Ptr, unsigned Idx, const Twine &Name="")
Definition: IRBuilder.h:1631
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
Definition: Function.h:230
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
AttributeList getAttributes() const
Get the parameter attributes of the call.
Definition: CallSite.h:329
FunctionPass * createX86WinEHStatePass()
Return an IR pass that inserts EH registration stack objects and explicit EH state updates...
DenseMap< BasicBlock *, ColorVector > colorEHFunclets(Function &F)
If an EH funclet personality is in use (see isFuncletEHPersonality), this will recompute which blocks...
#define LLVM_DEBUG(X)
Definition: Debug.h:123
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
IntegerType * Int32Ty
an instruction to allocate memory on the stack
Definition: Instructions.h:60