clang  7.0.0svn
CGException.cpp
Go to the documentation of this file.
1 //===--- CGException.cpp - Emit LLVM Code for C++ exceptions ----*- C++ -*-===//
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 // This contains code dealing with C++ exception related code generation.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenFunction.h"
15 #include "CGCXXABI.h"
16 #include "CGCleanup.h"
17 #include "CGObjCRuntime.h"
18 #include "ConstantEmitter.h"
19 #include "TargetInfo.h"
20 #include "clang/AST/Mangle.h"
21 #include "clang/AST/StmtCXX.h"
22 #include "clang/AST/StmtObjC.h"
23 #include "clang/AST/StmtVisitor.h"
25 #include "llvm/IR/CallSite.h"
26 #include "llvm/IR/Intrinsics.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/Support/SaveAndRestore.h"
29 
30 using namespace clang;
31 using namespace CodeGen;
32 
33 static llvm::Constant *getFreeExceptionFn(CodeGenModule &CGM) {
34  // void __cxa_free_exception(void *thrown_exception);
35 
36  llvm::FunctionType *FTy =
37  llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
38 
39  return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
40 }
41 
42 static llvm::Constant *getUnexpectedFn(CodeGenModule &CGM) {
43  // void __cxa_call_unexpected(void *thrown_exception);
44 
45  llvm::FunctionType *FTy =
46  llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
47 
48  return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
49 }
50 
51 llvm::Constant *CodeGenModule::getTerminateFn() {
52  // void __terminate();
53 
54  llvm::FunctionType *FTy =
55  llvm::FunctionType::get(VoidTy, /*IsVarArgs=*/false);
56 
57  StringRef name;
58 
59  // In C++, use std::terminate().
60  if (getLangOpts().CPlusPlus &&
61  getTarget().getCXXABI().isItaniumFamily()) {
62  name = "_ZSt9terminatev";
63  } else if (getLangOpts().CPlusPlus &&
64  getTarget().getCXXABI().isMicrosoft()) {
65  if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
66  name = "__std_terminate";
67  else
68  name = "\01?terminate@@YAXXZ";
69  } else if (getLangOpts().ObjC1 &&
71  name = "objc_terminate";
72  else
73  name = "abort";
74  return CreateRuntimeFunction(FTy, name);
75 }
76 
77 static llvm::Constant *getCatchallRethrowFn(CodeGenModule &CGM,
78  StringRef Name) {
79  llvm::FunctionType *FTy =
80  llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*IsVarArgs=*/false);
81 
82  return CGM.CreateRuntimeFunction(FTy, Name);
83 }
84 
85 const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
86 const EHPersonality
87 EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
88 const EHPersonality
89 EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr };
90 const EHPersonality
91 EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
92 const EHPersonality
93 EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
94 const EHPersonality
95 EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
96 const EHPersonality
97 EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr };
98 const EHPersonality
99 EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
100 const EHPersonality
101 EHPersonality::GNU_ObjC_SJLJ = {"__gnu_objc_personality_sj0", "objc_exception_throw"};
102 const EHPersonality
103 EHPersonality::GNU_ObjC_SEH = {"__gnu_objc_personality_seh0", "objc_exception_throw"};
104 const EHPersonality
105 EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
106 const EHPersonality
107 EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
108 const EHPersonality
109 EHPersonality::MSVC_except_handler = { "_except_handler3", nullptr };
110 const EHPersonality
111 EHPersonality::MSVC_C_specific_handler = { "__C_specific_handler", nullptr };
112 const EHPersonality
113 EHPersonality::MSVC_CxxFrameHandler3 = { "__CxxFrameHandler3", nullptr };
114 
115 static const EHPersonality &getCPersonality(const llvm::Triple &T,
116  const LangOptions &L) {
117  if (L.SjLjExceptions)
119  if (L.SEHExceptions)
121  return EHPersonality::GNU_C;
122 }
123 
124 static const EHPersonality &getObjCPersonality(const llvm::Triple &T,
125  const LangOptions &L) {
126  switch (L.ObjCRuntime.getKind()) {
128  return getCPersonality(T, L);
129  case ObjCRuntime::MacOSX:
130  case ObjCRuntime::iOS:
134  if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
135  return EHPersonality::GNUstep_ObjC;
136  LLVM_FALLTHROUGH;
137  case ObjCRuntime::GCC:
138  case ObjCRuntime::ObjFW:
139  if (L.SjLjExceptions)
141  if (L.SEHExceptions)
144  }
145  llvm_unreachable("bad runtime kind");
146 }
147 
148 static const EHPersonality &getCXXPersonality(const llvm::Triple &T,
149  const LangOptions &L) {
150  if (L.SjLjExceptions)
152  if (L.SEHExceptions)
155 }
156 
157 /// Determines the personality function to use when both C++
158 /// and Objective-C exceptions are being caught.
159 static const EHPersonality &getObjCXXPersonality(const llvm::Triple &T,
160  const LangOptions &L) {
161  switch (L.ObjCRuntime.getKind()) {
162  // In the fragile ABI, just use C++ exception handling and hope
163  // they're not doing crazy exception mixing.
165  return getCXXPersonality(T, L);
166 
167  // The ObjC personality defers to the C++ personality for non-ObjC
168  // handlers. Unlike the C++ case, we use the same personality
169  // function on targets using (backend-driven) SJLJ EH.
170  case ObjCRuntime::MacOSX:
171  case ObjCRuntime::iOS:
173  return getObjCPersonality(T, L);
174 
177 
178  // The GCC runtime's personality function inherently doesn't support
179  // mixed EH. Use the ObjC personality just to avoid returning null.
180  case ObjCRuntime::GCC:
181  case ObjCRuntime::ObjFW:
182  return getObjCPersonality(T, L);
183  }
184  llvm_unreachable("bad runtime kind");
185 }
186 
187 static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
188  if (T.getArch() == llvm::Triple::x86)
189  return EHPersonality::MSVC_except_handler;
191 }
192 
194  const FunctionDecl *FD) {
195  const llvm::Triple &T = CGM.getTarget().getTriple();
196  const LangOptions &L = CGM.getLangOpts();
197 
198  // Functions using SEH get an SEH personality.
199  if (FD && FD->usesSEHTry())
200  return getSEHPersonalityMSVC(T);
201 
202  // Try to pick a personality function that is compatible with MSVC if we're
203  // not compiling Obj-C. Obj-C users better have an Obj-C runtime that supports
204  // the GCC-style personality function.
205  if (T.isWindowsMSVCEnvironment() && !L.ObjC1) {
206  if (L.SjLjExceptions)
208  if (L.DWARFExceptions)
211  }
212 
213  if (L.CPlusPlus && L.ObjC1)
214  return getObjCXXPersonality(T, L);
215  else if (L.CPlusPlus)
216  return getCXXPersonality(T, L);
217  else if (L.ObjC1)
218  return getObjCPersonality(T, L);
219  else
220  return getCPersonality(T, L);
221 }
222 
224  const auto *FD = CGF.CurCodeDecl;
225  // For outlined finallys and filters, use the SEH personality in case they
226  // contain more SEH. This mostly only affects finallys. Filters could
227  // hypothetically use gnu statement expressions to sneak in nested SEH.
228  FD = FD ? FD : CGF.CurSEHParent;
229  return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(FD));
230 }
231 
232 static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
233  const EHPersonality &Personality) {
234  return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
235  Personality.PersonalityFn,
236  llvm::AttributeList(), /*Local=*/true);
237 }
238 
239 static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
240  const EHPersonality &Personality) {
241  llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
242  return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
243 }
244 
245 /// Check whether a landingpad instruction only uses C++ features.
246 static bool LandingPadHasOnlyCXXUses(llvm::LandingPadInst *LPI) {
247  for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
248  // Look for something that would've been returned by the ObjC
249  // runtime's GetEHType() method.
250  llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
251  if (LPI->isCatch(I)) {
252  // Check if the catch value has the ObjC prefix.
253  if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
254  // ObjC EH selector entries are always global variables with
255  // names starting like this.
256  if (GV->getName().startswith("OBJC_EHTYPE"))
257  return false;
258  } else {
259  // Check if any of the filter values have the ObjC prefix.
260  llvm::Constant *CVal = cast<llvm::Constant>(Val);
261  for (llvm::User::op_iterator
262  II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
263  if (llvm::GlobalVariable *GV =
264  cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
265  // ObjC EH selector entries are always global variables with
266  // names starting like this.
267  if (GV->getName().startswith("OBJC_EHTYPE"))
268  return false;
269  }
270  }
271  }
272  return true;
273 }
274 
275 /// Check whether a personality function could reasonably be swapped
276 /// for a C++ personality function.
277 static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
278  for (llvm::User *U : Fn->users()) {
279  // Conditionally white-list bitcasts.
280  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
281  if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
282  if (!PersonalityHasOnlyCXXUses(CE))
283  return false;
284  continue;
285  }
286 
287  // Otherwise it must be a function.
288  llvm::Function *F = dyn_cast<llvm::Function>(U);
289  if (!F) return false;
290 
291  for (auto BB = F->begin(), E = F->end(); BB != E; ++BB) {
292  if (BB->isLandingPad())
293  if (!LandingPadHasOnlyCXXUses(BB->getLandingPadInst()))
294  return false;
295  }
296  }
297 
298  return true;
299 }
300 
301 /// Try to use the C++ personality function in ObjC++. Not doing this
302 /// can cause some incompatibilities with gcc, which is more
303 /// aggressive about only using the ObjC++ personality in a function
304 /// when it really needs it.
305 void CodeGenModule::SimplifyPersonality() {
306  // If we're not in ObjC++ -fexceptions, there's nothing to do.
307  if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
308  return;
309 
310  // Both the problem this endeavors to fix and the way the logic
311  // above works is specific to the NeXT runtime.
312  if (!LangOpts.ObjCRuntime.isNeXTFamily())
313  return;
314 
315  const EHPersonality &ObjCXX = EHPersonality::get(*this, /*FD=*/nullptr);
316  const EHPersonality &CXX =
317  getCXXPersonality(getTarget().getTriple(), LangOpts);
318  if (&ObjCXX == &CXX)
319  return;
320 
321  assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
322  "Different EHPersonalities using the same personality function.");
323 
324  llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
325 
326  // Nothing to do if it's unused.
327  if (!Fn || Fn->use_empty()) return;
328 
329  // Can't do the optimization if it has non-C++ uses.
330  if (!PersonalityHasOnlyCXXUses(Fn)) return;
331 
332  // Create the C++ personality function and kill off the old
333  // function.
334  llvm::Constant *CXXFn = getPersonalityFn(*this, CXX);
335 
336  // This can happen if the user is screwing with us.
337  if (Fn->getType() != CXXFn->getType()) return;
338 
339  Fn->replaceAllUsesWith(CXXFn);
340  Fn->eraseFromParent();
341 }
342 
343 /// Returns the value to inject into a selector to indicate the
344 /// presence of a catch-all.
345 static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
346  // Possibly we should use @llvm.eh.catch.all.value here.
347  return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
348 }
349 
350 namespace {
351  /// A cleanup to free the exception object if its initialization
352  /// throws.
353  struct FreeException final : EHScopeStack::Cleanup {
354  llvm::Value *exn;
355  FreeException(llvm::Value *exn) : exn(exn) {}
356  void Emit(CodeGenFunction &CGF, Flags flags) override {
358  }
359  };
360 } // end anonymous namespace
361 
362 // Emits an exception expression into the given location. This
363 // differs from EmitAnyExprToMem only in that, if a final copy-ctor
364 // call is required, an exception within that copy ctor causes
365 // std::terminate to be invoked.
367  // Make sure the exception object is cleaned up if there's an
368  // exception during initialization.
369  pushFullExprCleanup<FreeException>(EHCleanup, addr.getPointer());
370  EHScopeStack::stable_iterator cleanup = EHStack.stable_begin();
371 
372  // __cxa_allocate_exception returns a void*; we need to cast this
373  // to the appropriate type for the object.
374  llvm::Type *ty = ConvertTypeForMem(e->getType())->getPointerTo();
375  Address typedAddr = Builder.CreateBitCast(addr, ty);
376 
377  // FIXME: this isn't quite right! If there's a final unelided call
378  // to a copy constructor, then according to [except.terminate]p1 we
379  // must call std::terminate() if that constructor throws, because
380  // technically that copy occurs after the exception expression is
381  // evaluated but before the exception is caught. But the best way
382  // to handle that is to teach EmitAggExpr to do the final copy
383  // differently if it can't be elided.
384  EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
385  /*IsInit*/ true);
386 
387  // Deactivate the cleanup block.
388  DeactivateCleanupBlock(cleanup,
389  cast<llvm::Instruction>(typedAddr.getPointer()));
390 }
391 
393  if (!ExceptionSlot)
394  ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
395  return Address(ExceptionSlot, getPointerAlign());
396 }
397 
399  if (!EHSelectorSlot)
400  EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
401  return Address(EHSelectorSlot, CharUnits::fromQuantity(4));
402 }
403 
405  return Builder.CreateLoad(getExceptionSlot(), "exn");
406 }
407 
409  return Builder.CreateLoad(getEHSelectorSlot(), "sel");
410 }
411 
413  bool KeepInsertionPoint) {
414  if (const Expr *SubExpr = E->getSubExpr()) {
415  QualType ThrowType = SubExpr->getType();
416  if (ThrowType->isObjCObjectPointerType()) {
417  const Stmt *ThrowStmt = E->getSubExpr();
418  const ObjCAtThrowStmt S(E->getExprLoc(), const_cast<Stmt *>(ThrowStmt));
419  CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
420  } else {
421  CGM.getCXXABI().emitThrow(*this, E);
422  }
423  } else {
424  CGM.getCXXABI().emitRethrow(*this, /*isNoReturn=*/true);
425  }
426 
427  // throw is an expression, and the expression emitters expect us
428  // to leave ourselves at a valid insertion point.
429  if (KeepInsertionPoint)
430  EmitBlock(createBasicBlock("throw.cont"));
431 }
432 
434  if (!CGM.getLangOpts().CXXExceptions)
435  return;
436 
437  const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
438  if (!FD) {
439  // Check if CapturedDecl is nothrow and create terminate scope for it.
440  if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
441  if (CD->isNothrow())
442  EHStack.pushTerminate();
443  }
444  return;
445  }
446  const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
447  if (!Proto)
448  return;
449 
451  if (isNoexceptExceptionSpec(EST)) {
453  // noexcept functions are simple terminate scopes.
454  EHStack.pushTerminate();
455  }
456  } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
457  // TODO: Revisit exception specifications for the MS ABI. There is a way to
458  // encode these in an object file but MSVC doesn't do anything with it.
459  if (getTarget().getCXXABI().isMicrosoft())
460  return;
461  unsigned NumExceptions = Proto->getNumExceptions();
462  EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
463 
464  for (unsigned I = 0; I != NumExceptions; ++I) {
465  QualType Ty = Proto->getExceptionType(I);
466  QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
467  llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
468  /*ForEH=*/true);
469  Filter->setFilter(I, EHType);
470  }
471  }
472 }
473 
474 /// Emit the dispatch block for a filter scope if necessary.
476  EHFilterScope &filterScope) {
477  llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
478  if (!dispatchBlock) return;
479  if (dispatchBlock->use_empty()) {
480  delete dispatchBlock;
481  return;
482  }
483 
484  CGF.EmitBlockAfterUses(dispatchBlock);
485 
486  // If this isn't a catch-all filter, we need to check whether we got
487  // here because the filter triggered.
488  if (filterScope.getNumFilters()) {
489  // Load the selector value.
490  llvm::Value *selector = CGF.getSelectorFromSlot();
491  llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
492 
493  llvm::Value *zero = CGF.Builder.getInt32(0);
494  llvm::Value *failsFilter =
495  CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
496  CGF.Builder.CreateCondBr(failsFilter, unexpectedBB,
497  CGF.getEHResumeBlock(false));
498 
499  CGF.EmitBlock(unexpectedBB);
500  }
501 
502  // Call __cxa_call_unexpected. This doesn't need to be an invoke
503  // because __cxa_call_unexpected magically filters exceptions
504  // according to the last landing pad the exception was thrown
505  // into. Seriously.
506  llvm::Value *exn = CGF.getExceptionFromSlot();
507  CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
508  ->setDoesNotReturn();
509  CGF.Builder.CreateUnreachable();
510 }
511 
513  if (!CGM.getLangOpts().CXXExceptions)
514  return;
515 
516  const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
517  if (!FD) {
518  // Check if CapturedDecl is nothrow and pop terminate scope for it.
519  if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
520  if (CD->isNothrow())
521  EHStack.popTerminate();
522  }
523  return;
524  }
525  const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
526  if (!Proto)
527  return;
528 
530  if (isNoexceptExceptionSpec(EST)) {
532  EHStack.popTerminate();
533  }
534  } else if (EST == EST_Dynamic || EST == EST_DynamicNone) {
535  // TODO: Revisit exception specifications for the MS ABI. There is a way to
536  // encode these in an object file but MSVC doesn't do anything with it.
537  if (getTarget().getCXXABI().isMicrosoft())
538  return;
539  EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
540  emitFilterDispatchBlock(*this, filterScope);
541  EHStack.popFilter();
542  }
543 }
544 
546  EnterCXXTryStmt(S);
547  EmitStmt(S.getTryBlock());
548  ExitCXXTryStmt(S);
549 }
550 
551 void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
552  unsigned NumHandlers = S.getNumHandlers();
553  EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
554 
555  for (unsigned I = 0; I != NumHandlers; ++I) {
556  const CXXCatchStmt *C = S.getHandler(I);
557 
558  llvm::BasicBlock *Handler = createBasicBlock("catch");
559  if (C->getExceptionDecl()) {
560  // FIXME: Dropping the reference type on the type into makes it
561  // impossible to correctly implement catch-by-reference
562  // semantics for pointers. Unfortunately, this is what all
563  // existing compilers do, and it's not clear that the standard
564  // personality routine is capable of doing this right. See C++ DR 388:
565  // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
566  Qualifiers CaughtTypeQuals;
567  QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
568  C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
569 
570  CatchTypeInfo TypeInfo{nullptr, 0};
571  if (CaughtType->isObjCObjectPointerType())
572  TypeInfo.RTTI = CGM.getObjCRuntime().GetEHType(CaughtType);
573  else
574  TypeInfo = CGM.getCXXABI().getAddrOfCXXCatchHandlerType(
575  CaughtType, C->getCaughtType());
576  CatchScope->setHandler(I, TypeInfo, Handler);
577  } else {
578  // No exception decl indicates '...', a catch-all.
579  CatchScope->setHandler(I, CGM.getCXXABI().getCatchAllTypeInfo(), Handler);
580  }
581  }
582 }
583 
584 llvm::BasicBlock *
586  if (EHPersonality::get(*this).usesFuncletPads())
587  return getMSVCDispatchBlock(si);
588 
589  // The dispatch block for the end of the scope chain is a block that
590  // just resumes unwinding.
591  if (si == EHStack.stable_end())
592  return getEHResumeBlock(true);
593 
594  // Otherwise, we should look at the actual scope.
595  EHScope &scope = *EHStack.find(si);
596 
597  llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
598  if (!dispatchBlock) {
599  switch (scope.getKind()) {
600  case EHScope::Catch: {
601  // Apply a special case to a single catch-all.
602  EHCatchScope &catchScope = cast<EHCatchScope>(scope);
603  if (catchScope.getNumHandlers() == 1 &&
604  catchScope.getHandler(0).isCatchAll()) {
605  dispatchBlock = catchScope.getHandler(0).Block;
606 
607  // Otherwise, make a dispatch block.
608  } else {
609  dispatchBlock = createBasicBlock("catch.dispatch");
610  }
611  break;
612  }
613 
614  case EHScope::Cleanup:
615  dispatchBlock = createBasicBlock("ehcleanup");
616  break;
617 
618  case EHScope::Filter:
619  dispatchBlock = createBasicBlock("filter.dispatch");
620  break;
621 
622  case EHScope::Terminate:
623  dispatchBlock = getTerminateHandler();
624  break;
625 
626  case EHScope::PadEnd:
627  llvm_unreachable("PadEnd unnecessary for Itanium!");
628  }
629  scope.setCachedEHDispatchBlock(dispatchBlock);
630  }
631  return dispatchBlock;
632 }
633 
634 llvm::BasicBlock *
636  // Returning nullptr indicates that the previous dispatch block should unwind
637  // to caller.
638  if (SI == EHStack.stable_end())
639  return nullptr;
640 
641  // Otherwise, we should look at the actual scope.
642  EHScope &EHS = *EHStack.find(SI);
643 
644  llvm::BasicBlock *DispatchBlock = EHS.getCachedEHDispatchBlock();
645  if (DispatchBlock)
646  return DispatchBlock;
647 
648  if (EHS.getKind() == EHScope::Terminate)
649  DispatchBlock = getTerminateFunclet();
650  else
651  DispatchBlock = createBasicBlock();
652  CGBuilderTy Builder(*this, DispatchBlock);
653 
654  switch (EHS.getKind()) {
655  case EHScope::Catch:
656  DispatchBlock->setName("catch.dispatch");
657  break;
658 
659  case EHScope::Cleanup:
660  DispatchBlock->setName("ehcleanup");
661  break;
662 
663  case EHScope::Filter:
664  llvm_unreachable("exception specifications not handled yet!");
665 
666  case EHScope::Terminate:
667  DispatchBlock->setName("terminate");
668  break;
669 
670  case EHScope::PadEnd:
671  llvm_unreachable("PadEnd dispatch block missing!");
672  }
673  EHS.setCachedEHDispatchBlock(DispatchBlock);
674  return DispatchBlock;
675 }
676 
677 /// Check whether this is a non-EH scope, i.e. a scope which doesn't
678 /// affect exception handling. Currently, the only non-EH scopes are
679 /// normal-only cleanup scopes.
680 static bool isNonEHScope(const EHScope &S) {
681  switch (S.getKind()) {
682  case EHScope::Cleanup:
683  return !cast<EHCleanupScope>(S).isEHCleanup();
684  case EHScope::Filter:
685  case EHScope::Catch:
686  case EHScope::Terminate:
687  case EHScope::PadEnd:
688  return false;
689  }
690 
691  llvm_unreachable("Invalid EHScope Kind!");
692 }
693 
695  assert(EHStack.requiresLandingPad());
696  assert(!EHStack.empty());
697 
698  // If exceptions are disabled and SEH is not in use, then there is no invoke
699  // destination. SEH "works" even if exceptions are off. In practice, this
700  // means that C++ destructors and other EH cleanups don't run, which is
701  // consistent with MSVC's behavior.
702  const LangOptions &LO = CGM.getLangOpts();
703  if (!LO.Exceptions) {
704  if (!LO.Borland && !LO.MicrosoftExt)
705  return nullptr;
706  if (!currentFunctionUsesSEHTry())
707  return nullptr;
708  }
709 
710  // CUDA device code doesn't have exceptions.
711  if (LO.CUDA && LO.CUDAIsDevice)
712  return nullptr;
713 
714  // Check the innermost scope for a cached landing pad. If this is
715  // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
716  llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
717  if (LP) return LP;
718 
719  const EHPersonality &Personality = EHPersonality::get(*this);
720 
721  if (!CurFn->hasPersonalityFn())
722  CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
723 
724  if (Personality.usesFuncletPads()) {
725  // We don't need separate landing pads in the funclet model.
726  LP = getEHDispatchBlock(EHStack.getInnermostEHScope());
727  } else {
728  // Build the landing pad for this scope.
729  LP = EmitLandingPad();
730  }
731 
732  assert(LP);
733 
734  // Cache the landing pad on the innermost scope. If this is a
735  // non-EH scope, cache the landing pad on the enclosing scope, too.
736  for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
737  ir->setCachedLandingPad(LP);
738  if (!isNonEHScope(*ir)) break;
739  }
740 
741  return LP;
742 }
743 
744 llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
745  assert(EHStack.requiresLandingPad());
746 
747  EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
748  switch (innermostEHScope.getKind()) {
749  case EHScope::Terminate:
750  return getTerminateLandingPad();
751 
752  case EHScope::PadEnd:
753  llvm_unreachable("PadEnd unnecessary for Itanium!");
754 
755  case EHScope::Catch:
756  case EHScope::Cleanup:
757  case EHScope::Filter:
758  if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
759  return lpad;
760  }
761 
762  // Save the current IR generation state.
763  CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
764  auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
765 
766  // Create and configure the landing pad.
767  llvm::BasicBlock *lpad = createBasicBlock("lpad");
768  EmitBlock(lpad);
769 
770  llvm::LandingPadInst *LPadInst =
771  Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
772 
773  llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
774  Builder.CreateStore(LPadExn, getExceptionSlot());
775  llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
776  Builder.CreateStore(LPadSel, getEHSelectorSlot());
777 
778  // Save the exception pointer. It's safe to use a single exception
779  // pointer per function because EH cleanups can never have nested
780  // try/catches.
781  // Build the landingpad instruction.
782 
783  // Accumulate all the handlers in scope.
784  bool hasCatchAll = false;
785  bool hasCleanup = false;
786  bool hasFilter = false;
787  SmallVector<llvm::Value*, 4> filterTypes;
788  llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
789  for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
790  ++I) {
791 
792  switch (I->getKind()) {
793  case EHScope::Cleanup:
794  // If we have a cleanup, remember that.
795  hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
796  continue;
797 
798  case EHScope::Filter: {
799  assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
800  assert(!hasCatchAll && "EH filter reached after catch-all");
801 
802  // Filter scopes get added to the landingpad in weird ways.
803  EHFilterScope &filter = cast<EHFilterScope>(*I);
804  hasFilter = true;
805 
806  // Add all the filter values.
807  for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
808  filterTypes.push_back(filter.getFilter(i));
809  goto done;
810  }
811 
812  case EHScope::Terminate:
813  // Terminate scopes are basically catch-alls.
814  assert(!hasCatchAll);
815  hasCatchAll = true;
816  goto done;
817 
818  case EHScope::Catch:
819  break;
820 
821  case EHScope::PadEnd:
822  llvm_unreachable("PadEnd unnecessary for Itanium!");
823  }
824 
825  EHCatchScope &catchScope = cast<EHCatchScope>(*I);
826  for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
827  EHCatchScope::Handler handler = catchScope.getHandler(hi);
828  assert(handler.Type.Flags == 0 &&
829  "landingpads do not support catch handler flags");
830 
831  // If this is a catch-all, register that and abort.
832  if (!handler.Type.RTTI) {
833  assert(!hasCatchAll);
834  hasCatchAll = true;
835  goto done;
836  }
837 
838  // Check whether we already have a handler for this type.
839  if (catchTypes.insert(handler.Type.RTTI).second)
840  // If not, add it directly to the landingpad.
841  LPadInst->addClause(handler.Type.RTTI);
842  }
843  }
844 
845  done:
846  // If we have a catch-all, add null to the landingpad.
847  assert(!(hasCatchAll && hasFilter));
848  if (hasCatchAll) {
849  LPadInst->addClause(getCatchAllValue(*this));
850 
851  // If we have an EH filter, we need to add those handlers in the
852  // right place in the landingpad, which is to say, at the end.
853  } else if (hasFilter) {
854  // Create a filter expression: a constant array indicating which filter
855  // types there are. The personality routine only lands here if the filter
856  // doesn't match.
858  llvm::ArrayType *AType =
859  llvm::ArrayType::get(!filterTypes.empty() ?
860  filterTypes[0]->getType() : Int8PtrTy,
861  filterTypes.size());
862 
863  for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
864  Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
865  llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
866  LPadInst->addClause(FilterArray);
867 
868  // Also check whether we need a cleanup.
869  if (hasCleanup)
870  LPadInst->setCleanup(true);
871 
872  // Otherwise, signal that we at least have cleanups.
873  } else if (hasCleanup) {
874  LPadInst->setCleanup(true);
875  }
876 
877  assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
878  "landingpad instruction has no clauses!");
879 
880  // Tell the backend how to generate the landing pad.
881  Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
882 
883  // Restore the old IR generation state.
884  Builder.restoreIP(savedIP);
885 
886  return lpad;
887 }
888 
889 static void emitCatchPadBlock(CodeGenFunction &CGF, EHCatchScope &CatchScope) {
890  llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
891  assert(DispatchBlock);
892 
893  CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveIP();
894  CGF.EmitBlockAfterUses(DispatchBlock);
895 
896  llvm::Value *ParentPad = CGF.CurrentFuncletPad;
897  if (!ParentPad)
898  ParentPad = llvm::ConstantTokenNone::get(CGF.getLLVMContext());
899  llvm::BasicBlock *UnwindBB =
900  CGF.getEHDispatchBlock(CatchScope.getEnclosingEHScope());
901 
902  unsigned NumHandlers = CatchScope.getNumHandlers();
903  llvm::CatchSwitchInst *CatchSwitch =
904  CGF.Builder.CreateCatchSwitch(ParentPad, UnwindBB, NumHandlers);
905 
906  // Test against each of the exception types we claim to catch.
907  for (unsigned I = 0; I < NumHandlers; ++I) {
908  const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
909 
910  CatchTypeInfo TypeInfo = Handler.Type;
911  if (!TypeInfo.RTTI)
912  TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
913 
914  CGF.Builder.SetInsertPoint(Handler.Block);
915 
916  if (EHPersonality::get(CGF).isMSVCXXPersonality()) {
917  CGF.Builder.CreateCatchPad(
918  CatchSwitch, {TypeInfo.RTTI, CGF.Builder.getInt32(TypeInfo.Flags),
919  llvm::Constant::getNullValue(CGF.VoidPtrTy)});
920  } else {
921  CGF.Builder.CreateCatchPad(CatchSwitch, {TypeInfo.RTTI});
922  }
923 
924  CatchSwitch->addHandler(Handler.Block);
925  }
926  CGF.Builder.restoreIP(SavedIP);
927 }
928 
929 /// Emit the structure of the dispatch block for the given catch scope.
930 /// It is an invariant that the dispatch block already exists.
932  EHCatchScope &catchScope) {
933  if (EHPersonality::get(CGF).usesFuncletPads())
934  return emitCatchPadBlock(CGF, catchScope);
935 
936  llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
937  assert(dispatchBlock);
938 
939  // If there's only a single catch-all, getEHDispatchBlock returned
940  // that catch-all as the dispatch block.
941  if (catchScope.getNumHandlers() == 1 &&
942  catchScope.getHandler(0).isCatchAll()) {
943  assert(dispatchBlock == catchScope.getHandler(0).Block);
944  return;
945  }
946 
947  CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
948  CGF.EmitBlockAfterUses(dispatchBlock);
949 
950  // Select the right handler.
951  llvm::Value *llvm_eh_typeid_for =
952  CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
953 
954  // Load the selector value.
955  llvm::Value *selector = CGF.getSelectorFromSlot();
956 
957  // Test against each of the exception types we claim to catch.
958  for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
959  assert(i < e && "ran off end of handlers!");
960  const EHCatchScope::Handler &handler = catchScope.getHandler(i);
961 
962  llvm::Value *typeValue = handler.Type.RTTI;
963  assert(handler.Type.Flags == 0 &&
964  "landingpads do not support catch handler flags");
965  assert(typeValue && "fell into catch-all case!");
966  typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
967 
968  // Figure out the next block.
969  bool nextIsEnd;
970  llvm::BasicBlock *nextBlock;
971 
972  // If this is the last handler, we're at the end, and the next
973  // block is the block for the enclosing EH scope.
974  if (i + 1 == e) {
975  nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
976  nextIsEnd = true;
977 
978  // If the next handler is a catch-all, we're at the end, and the
979  // next block is that handler.
980  } else if (catchScope.getHandler(i+1).isCatchAll()) {
981  nextBlock = catchScope.getHandler(i+1).Block;
982  nextIsEnd = true;
983 
984  // Otherwise, we're not at the end and we need a new block.
985  } else {
986  nextBlock = CGF.createBasicBlock("catch.fallthrough");
987  nextIsEnd = false;
988  }
989 
990  // Figure out the catch type's index in the LSDA's type table.
991  llvm::CallInst *typeIndex =
992  CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
993  typeIndex->setDoesNotThrow();
994 
995  llvm::Value *matchesTypeIndex =
996  CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
997  CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
998 
999  // If the next handler is a catch-all, we're completely done.
1000  if (nextIsEnd) {
1001  CGF.Builder.restoreIP(savedIP);
1002  return;
1003  }
1004  // Otherwise we need to emit and continue at that block.
1005  CGF.EmitBlock(nextBlock);
1006  }
1007 }
1008 
1010  EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1011  if (catchScope.hasEHBranches())
1012  emitCatchDispatchBlock(*this, catchScope);
1013  EHStack.popCatch();
1014 }
1015 
1016 void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
1017  unsigned NumHandlers = S.getNumHandlers();
1018  EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1019  assert(CatchScope.getNumHandlers() == NumHandlers);
1020 
1021  // If the catch was not required, bail out now.
1022  if (!CatchScope.hasEHBranches()) {
1023  CatchScope.clearHandlerBlocks();
1024  EHStack.popCatch();
1025  return;
1026  }
1027 
1028  // Emit the structure of the EH dispatch for this catch.
1029  emitCatchDispatchBlock(*this, CatchScope);
1030 
1031  // Copy the handler blocks off before we pop the EH stack. Emitting
1032  // the handlers might scribble on this memory.
1034  CatchScope.begin(), CatchScope.begin() + NumHandlers);
1035 
1036  EHStack.popCatch();
1037 
1038  // The fall-through block.
1039  llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
1040 
1041  // We just emitted the body of the try; jump to the continue block.
1042  if (HaveInsertPoint())
1043  Builder.CreateBr(ContBB);
1044 
1045  // Determine if we need an implicit rethrow for all these catch handlers;
1046  // see the comment below.
1047  bool doImplicitRethrow = false;
1048  if (IsFnTryBlock)
1049  doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1050  isa<CXXConstructorDecl>(CurCodeDecl);
1051 
1052  // Perversely, we emit the handlers backwards precisely because we
1053  // want them to appear in source order. In all of these cases, the
1054  // catch block will have exactly one predecessor, which will be a
1055  // particular block in the catch dispatch. However, in the case of
1056  // a catch-all, one of the dispatch blocks will branch to two
1057  // different handlers, and EmitBlockAfterUses will cause the second
1058  // handler to be moved before the first.
1059  for (unsigned I = NumHandlers; I != 0; --I) {
1060  llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1061  EmitBlockAfterUses(CatchBlock);
1062 
1063  // Catch the exception if this isn't a catch-all.
1064  const CXXCatchStmt *C = S.getHandler(I-1);
1065 
1066  // Enter a cleanup scope, including the catch variable and the
1067  // end-catch.
1068  RunCleanupsScope CatchScope(*this);
1069 
1070  // Initialize the catch variable and set up the cleanups.
1071  SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
1072  CurrentFuncletPad);
1073  CGM.getCXXABI().emitBeginCatch(*this, C);
1074 
1075  // Emit the PGO counter increment.
1076  incrementProfileCounter(C);
1077 
1078  // Perform the body of the catch.
1079  EmitStmt(C->getHandlerBlock());
1080 
1081  // [except.handle]p11:
1082  // The currently handled exception is rethrown if control
1083  // reaches the end of a handler of the function-try-block of a
1084  // constructor or destructor.
1085 
1086  // It is important that we only do this on fallthrough and not on
1087  // return. Note that it's illegal to put a return in a
1088  // constructor function-try-block's catch handler (p14), so this
1089  // really only applies to destructors.
1090  if (doImplicitRethrow && HaveInsertPoint()) {
1091  CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
1092  Builder.CreateUnreachable();
1093  Builder.ClearInsertionPoint();
1094  }
1095 
1096  // Fall out through the catch cleanups.
1097  CatchScope.ForceCleanup();
1098 
1099  // Branch out of the try.
1100  if (HaveInsertPoint())
1101  Builder.CreateBr(ContBB);
1102  }
1103 
1104  EmitBlock(ContBB);
1105  incrementProfileCounter(&S);
1106 }
1107 
1108 namespace {
1109  struct CallEndCatchForFinally final : EHScopeStack::Cleanup {
1110  llvm::Value *ForEHVar;
1111  llvm::Value *EndCatchFn;
1112  CallEndCatchForFinally(llvm::Value *ForEHVar, llvm::Value *EndCatchFn)
1113  : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1114 
1115  void Emit(CodeGenFunction &CGF, Flags flags) override {
1116  llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1117  llvm::BasicBlock *CleanupContBB =
1118  CGF.createBasicBlock("finally.cleanup.cont");
1119 
1120  llvm::Value *ShouldEndCatch =
1121  CGF.Builder.CreateFlagLoad(ForEHVar, "finally.endcatch");
1122  CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1123  CGF.EmitBlock(EndCatchBB);
1124  CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
1125  CGF.EmitBlock(CleanupContBB);
1126  }
1127  };
1128 
1129  struct PerformFinally final : EHScopeStack::Cleanup {
1130  const Stmt *Body;
1131  llvm::Value *ForEHVar;
1132  llvm::Value *EndCatchFn;
1133  llvm::Value *RethrowFn;
1134  llvm::Value *SavedExnVar;
1135 
1136  PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1137  llvm::Value *EndCatchFn,
1138  llvm::Value *RethrowFn, llvm::Value *SavedExnVar)
1139  : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1140  RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1141 
1142  void Emit(CodeGenFunction &CGF, Flags flags) override {
1143  // Enter a cleanup to call the end-catch function if one was provided.
1144  if (EndCatchFn)
1145  CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1146  ForEHVar, EndCatchFn);
1147 
1148  // Save the current cleanup destination in case there are
1149  // cleanups in the finally block.
1150  llvm::Value *SavedCleanupDest =
1152  "cleanup.dest.saved");
1153 
1154  // Emit the finally block.
1155  CGF.EmitStmt(Body);
1156 
1157  // If the end of the finally is reachable, check whether this was
1158  // for EH. If so, rethrow.
1159  if (CGF.HaveInsertPoint()) {
1160  llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1161  llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1162 
1163  llvm::Value *ShouldRethrow =
1164  CGF.Builder.CreateFlagLoad(ForEHVar, "finally.shouldthrow");
1165  CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1166 
1167  CGF.EmitBlock(RethrowBB);
1168  if (SavedExnVar) {
1169  CGF.EmitRuntimeCallOrInvoke(RethrowFn,
1170  CGF.Builder.CreateAlignedLoad(SavedExnVar, CGF.getPointerAlign()));
1171  } else {
1172  CGF.EmitRuntimeCallOrInvoke(RethrowFn);
1173  }
1174  CGF.Builder.CreateUnreachable();
1175 
1176  CGF.EmitBlock(ContBB);
1177 
1178  // Restore the cleanup destination.
1179  CGF.Builder.CreateStore(SavedCleanupDest,
1180  CGF.getNormalCleanupDestSlot());
1181  }
1182 
1183  // Leave the end-catch cleanup. As an optimization, pretend that
1184  // the fallthrough path was inaccessible; we've dynamically proven
1185  // that we're not in the EH case along that path.
1186  if (EndCatchFn) {
1187  CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1188  CGF.PopCleanupBlock();
1189  CGF.Builder.restoreIP(SavedIP);
1190  }
1191 
1192  // Now make sure we actually have an insertion point or the
1193  // cleanup gods will hate us.
1194  CGF.EnsureInsertPoint();
1195  }
1196  };
1197 } // end anonymous namespace
1198 
1199 /// Enters a finally block for an implementation using zero-cost
1200 /// exceptions. This is mostly general, but hard-codes some
1201 /// language/ABI-specific behavior in the catch-all sections.
1203  const Stmt *body,
1204  llvm::Constant *beginCatchFn,
1205  llvm::Constant *endCatchFn,
1206  llvm::Constant *rethrowFn) {
1207  assert((beginCatchFn != nullptr) == (endCatchFn != nullptr) &&
1208  "begin/end catch functions not paired");
1209  assert(rethrowFn && "rethrow function is required");
1210 
1211  BeginCatchFn = beginCatchFn;
1212 
1213  // The rethrow function has one of the following two types:
1214  // void (*)()
1215  // void (*)(void*)
1216  // In the latter case we need to pass it the exception object.
1217  // But we can't use the exception slot because the @finally might
1218  // have a landing pad (which would overwrite the exception slot).
1219  llvm::FunctionType *rethrowFnTy =
1220  cast<llvm::FunctionType>(
1221  cast<llvm::PointerType>(rethrowFn->getType())->getElementType());
1222  SavedExnVar = nullptr;
1223  if (rethrowFnTy->getNumParams())
1224  SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
1225 
1226  // A finally block is a statement which must be executed on any edge
1227  // out of a given scope. Unlike a cleanup, the finally block may
1228  // contain arbitrary control flow leading out of itself. In
1229  // addition, finally blocks should always be executed, even if there
1230  // are no catch handlers higher on the stack. Therefore, we
1231  // surround the protected scope with a combination of a normal
1232  // cleanup (to catch attempts to break out of the block via normal
1233  // control flow) and an EH catch-all (semantically "outside" any try
1234  // statement to which the finally block might have been attached).
1235  // The finally block itself is generated in the context of a cleanup
1236  // which conditionally leaves the catch-all.
1237 
1238  // Jump destination for performing the finally block on an exception
1239  // edge. We'll never actually reach this block, so unreachable is
1240  // fine.
1241  RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
1242 
1243  // Whether the finally block is being executed for EH purposes.
1244  ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1245  CGF.Builder.CreateFlagStore(false, ForEHVar);
1246 
1247  // Enter a normal cleanup which will perform the @finally block.
1248  CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1249  ForEHVar, endCatchFn,
1250  rethrowFn, SavedExnVar);
1251 
1252  // Enter a catch-all scope.
1253  llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1254  EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1255  catchScope->setCatchAllHandler(0, catchBB);
1256 }
1257 
1259  // Leave the finally catch-all.
1260  EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1261  llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
1262 
1263  CGF.popCatchScope();
1264 
1265  // If there are any references to the catch-all block, emit it.
1266  if (catchBB->use_empty()) {
1267  delete catchBB;
1268  } else {
1269  CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1270  CGF.EmitBlock(catchBB);
1271 
1272  llvm::Value *exn = nullptr;
1273 
1274  // If there's a begin-catch function, call it.
1275  if (BeginCatchFn) {
1276  exn = CGF.getExceptionFromSlot();
1277  CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
1278  }
1279 
1280  // If we need to remember the exception pointer to rethrow later, do so.
1281  if (SavedExnVar) {
1282  if (!exn) exn = CGF.getExceptionFromSlot();
1283  CGF.Builder.CreateAlignedStore(exn, SavedExnVar, CGF.getPointerAlign());
1284  }
1285 
1286  // Tell the cleanups in the finally block that we're do this for EH.
1287  CGF.Builder.CreateFlagStore(true, ForEHVar);
1288 
1289  // Thread a jump through the finally cleanup.
1290  CGF.EmitBranchThroughCleanup(RethrowDest);
1291 
1292  CGF.Builder.restoreIP(savedIP);
1293  }
1294 
1295  // Finally, leave the @finally cleanup.
1296  CGF.PopCleanupBlock();
1297 }
1298 
1300  if (TerminateLandingPad)
1301  return TerminateLandingPad;
1302 
1303  CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1304 
1305  // This will get inserted at the end of the function.
1306  TerminateLandingPad = createBasicBlock("terminate.lpad");
1307  Builder.SetInsertPoint(TerminateLandingPad);
1308 
1309  // Tell the backend that this is a landing pad.
1310  const EHPersonality &Personality = EHPersonality::get(*this);
1311 
1312  if (!CurFn->hasPersonalityFn())
1313  CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
1314 
1315  llvm::LandingPadInst *LPadInst =
1316  Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
1317  LPadInst->addClause(getCatchAllValue(*this));
1318 
1319  llvm::Value *Exn = nullptr;
1320  if (getLangOpts().CPlusPlus)
1321  Exn = Builder.CreateExtractValue(LPadInst, 0);
1322  llvm::CallInst *terminateCall =
1323  CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
1324  terminateCall->setDoesNotReturn();
1325  Builder.CreateUnreachable();
1326 
1327  // Restore the saved insertion state.
1328  Builder.restoreIP(SavedIP);
1329 
1330  return TerminateLandingPad;
1331 }
1332 
1334  if (TerminateHandler)
1335  return TerminateHandler;
1336 
1337  // Set up the terminate handler. This block is inserted at the very
1338  // end of the function by FinishFunction.
1339  TerminateHandler = createBasicBlock("terminate.handler");
1340  CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1341  Builder.SetInsertPoint(TerminateHandler);
1342 
1343  llvm::Value *Exn = nullptr;
1344  if (getLangOpts().CPlusPlus)
1345  Exn = getExceptionFromSlot();
1346  llvm::CallInst *terminateCall =
1347  CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
1348  terminateCall->setDoesNotReturn();
1349  Builder.CreateUnreachable();
1350 
1351  // Restore the saved insertion state.
1352  Builder.restoreIP(SavedIP);
1353 
1354  return TerminateHandler;
1355 }
1356 
1358  assert(EHPersonality::get(*this).usesFuncletPads() &&
1359  "use getTerminateLandingPad for non-funclet EH");
1360 
1361  llvm::BasicBlock *&TerminateFunclet = TerminateFunclets[CurrentFuncletPad];
1362  if (TerminateFunclet)
1363  return TerminateFunclet;
1364 
1365  CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1366 
1367  // Set up the terminate handler. This block is inserted at the very
1368  // end of the function by FinishFunction.
1369  TerminateFunclet = createBasicBlock("terminate.handler");
1370  Builder.SetInsertPoint(TerminateFunclet);
1371 
1372  // Create the cleanuppad using the current parent pad as its token. Use 'none'
1373  // if this is a top-level terminate scope, which is the common case.
1374  SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
1375  CurrentFuncletPad);
1376  llvm::Value *ParentPad = CurrentFuncletPad;
1377  if (!ParentPad)
1378  ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
1379  CurrentFuncletPad = Builder.CreateCleanupPad(ParentPad);
1380 
1381  // Emit the __std_terminate call.
1382  llvm::CallInst *terminateCall =
1383  CGM.getCXXABI().emitTerminateForUnexpectedException(*this, nullptr);
1384  terminateCall->setDoesNotReturn();
1385  Builder.CreateUnreachable();
1386 
1387  // Restore the saved insertion state.
1388  Builder.restoreIP(SavedIP);
1389 
1390  return TerminateFunclet;
1391 }
1392 
1393 llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
1394  if (EHResumeBlock) return EHResumeBlock;
1395 
1396  CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1397 
1398  // We emit a jump to a notional label at the outermost unwind state.
1399  EHResumeBlock = createBasicBlock("eh.resume");
1400  Builder.SetInsertPoint(EHResumeBlock);
1401 
1402  const EHPersonality &Personality = EHPersonality::get(*this);
1403 
1404  // This can always be a call because we necessarily didn't find
1405  // anything on the EH stack which needs our help.
1406  const char *RethrowName = Personality.CatchallRethrowFn;
1407  if (RethrowName != nullptr && !isCleanup) {
1408  EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
1409  getExceptionFromSlot())->setDoesNotReturn();
1410  Builder.CreateUnreachable();
1411  Builder.restoreIP(SavedIP);
1412  return EHResumeBlock;
1413  }
1414 
1415  // Recreate the landingpad's return value for the 'resume' instruction.
1416  llvm::Value *Exn = getExceptionFromSlot();
1417  llvm::Value *Sel = getSelectorFromSlot();
1418 
1419  llvm::Type *LPadType = llvm::StructType::get(Exn->getType(), Sel->getType());
1420  llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1421  LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1422  LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1423 
1424  Builder.CreateResume(LPadVal);
1425  Builder.restoreIP(SavedIP);
1426  return EHResumeBlock;
1427 }
1428 
1430  EnterSEHTryStmt(S);
1431  {
1432  JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
1433 
1434  SEHTryEpilogueStack.push_back(&TryExit);
1435  EmitStmt(S.getTryBlock());
1436  SEHTryEpilogueStack.pop_back();
1437 
1438  if (!TryExit.getBlock()->use_empty())
1439  EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
1440  else
1441  delete TryExit.getBlock();
1442  }
1443  ExitSEHTryStmt(S);
1444 }
1445 
1446 namespace {
1447 struct PerformSEHFinally final : EHScopeStack::Cleanup {
1448  llvm::Function *OutlinedFinally;
1449  PerformSEHFinally(llvm::Function *OutlinedFinally)
1450  : OutlinedFinally(OutlinedFinally) {}
1451 
1452  void Emit(CodeGenFunction &CGF, Flags F) override {
1453  ASTContext &Context = CGF.getContext();
1454  CodeGenModule &CGM = CGF.CGM;
1455 
1456  CallArgList Args;
1457 
1458  // Compute the two argument values.
1459  QualType ArgTys[2] = {Context.UnsignedCharTy, Context.VoidPtrTy};
1460  llvm::Value *LocalAddrFn = CGM.getIntrinsic(llvm::Intrinsic::localaddress);
1461  llvm::Value *FP = CGF.Builder.CreateCall(LocalAddrFn);
1462  llvm::Value *IsForEH =
1463  llvm::ConstantInt::get(CGF.ConvertType(ArgTys[0]), F.isForEHCleanup());
1464  Args.add(RValue::get(IsForEH), ArgTys[0]);
1465  Args.add(RValue::get(FP), ArgTys[1]);
1466 
1467  // Arrange a two-arg function info and type.
1468  const CGFunctionInfo &FnInfo =
1469  CGM.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, Args);
1470 
1471  auto Callee = CGCallee::forDirect(OutlinedFinally);
1472  CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
1473  }
1474 };
1475 } // end anonymous namespace
1476 
1477 namespace {
1478 /// Find all local variable captures in the statement.
1479 struct CaptureFinder : ConstStmtVisitor<CaptureFinder> {
1480  CodeGenFunction &ParentCGF;
1481  const VarDecl *ParentThis;
1483  Address SEHCodeSlot = Address::invalid();
1484  CaptureFinder(CodeGenFunction &ParentCGF, const VarDecl *ParentThis)
1485  : ParentCGF(ParentCGF), ParentThis(ParentThis) {}
1486 
1487  // Return true if we need to do any capturing work.
1488  bool foundCaptures() {
1489  return !Captures.empty() || SEHCodeSlot.isValid();
1490  }
1491 
1492  void Visit(const Stmt *S) {
1493  // See if this is a capture, then recurse.
1495  for (const Stmt *Child : S->children())
1496  if (Child)
1497  Visit(Child);
1498  }
1499 
1500  void VisitDeclRefExpr(const DeclRefExpr *E) {
1501  // If this is already a capture, just make sure we capture 'this'.
1503  Captures.insert(ParentThis);
1504  return;
1505  }
1506 
1507  const auto *D = dyn_cast<VarDecl>(E->getDecl());
1508  if (D && D->isLocalVarDeclOrParm() && D->hasLocalStorage())
1509  Captures.insert(D);
1510  }
1511 
1512  void VisitCXXThisExpr(const CXXThisExpr *E) {
1513  Captures.insert(ParentThis);
1514  }
1515 
1516  void VisitCallExpr(const CallExpr *E) {
1517  // We only need to add parent frame allocations for these builtins in x86.
1518  if (ParentCGF.getTarget().getTriple().getArch() != llvm::Triple::x86)
1519  return;
1520 
1521  unsigned ID = E->getBuiltinCallee();
1522  switch (ID) {
1523  case Builtin::BI__exception_code:
1524  case Builtin::BI_exception_code:
1525  // This is the simple case where we are the outermost finally. All we
1526  // have to do here is make sure we escape this and recover it in the
1527  // outlined handler.
1528  if (!SEHCodeSlot.isValid())
1529  SEHCodeSlot = ParentCGF.SEHCodeSlotStack.back();
1530  break;
1531  }
1532  }
1533 };
1534 } // end anonymous namespace
1535 
1537  Address ParentVar,
1538  llvm::Value *ParentFP) {
1539  llvm::CallInst *RecoverCall = nullptr;
1540  CGBuilderTy Builder(*this, AllocaInsertPt);
1541  if (auto *ParentAlloca = dyn_cast<llvm::AllocaInst>(ParentVar.getPointer())) {
1542  // Mark the variable escaped if nobody else referenced it and compute the
1543  // localescape index.
1544  auto InsertPair = ParentCGF.EscapedLocals.insert(
1545  std::make_pair(ParentAlloca, ParentCGF.EscapedLocals.size()));
1546  int FrameEscapeIdx = InsertPair.first->second;
1547  // call i8* @llvm.localrecover(i8* bitcast(@parentFn), i8* %fp, i32 N)
1548  llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
1549  &CGM.getModule(), llvm::Intrinsic::localrecover);
1550  llvm::Constant *ParentI8Fn =
1551  llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1552  RecoverCall = Builder.CreateCall(
1553  FrameRecoverFn, {ParentI8Fn, ParentFP,
1554  llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)});
1555 
1556  } else {
1557  // If the parent didn't have an alloca, we're doing some nested outlining.
1558  // Just clone the existing localrecover call, but tweak the FP argument to
1559  // use our FP value. All other arguments are constants.
1560  auto *ParentRecover =
1561  cast<llvm::IntrinsicInst>(ParentVar.getPointer()->stripPointerCasts());
1562  assert(ParentRecover->getIntrinsicID() == llvm::Intrinsic::localrecover &&
1563  "expected alloca or localrecover in parent LocalDeclMap");
1564  RecoverCall = cast<llvm::CallInst>(ParentRecover->clone());
1565  RecoverCall->setArgOperand(1, ParentFP);
1566  RecoverCall->insertBefore(AllocaInsertPt);
1567  }
1568 
1569  // Bitcast the variable, rename it, and insert it in the local decl map.
1570  llvm::Value *ChildVar =
1571  Builder.CreateBitCast(RecoverCall, ParentVar.getType());
1572  ChildVar->setName(ParentVar.getName());
1573  return Address(ChildVar, ParentVar.getAlignment());
1574 }
1575 
1577  const Stmt *OutlinedStmt,
1578  bool IsFilter) {
1579  // Find all captures in the Stmt.
1580  CaptureFinder Finder(ParentCGF, ParentCGF.CXXABIThisDecl);
1581  Finder.Visit(OutlinedStmt);
1582 
1583  // We can exit early on x86_64 when there are no captures. We just have to
1584  // save the exception code in filters so that __exception_code() works.
1585  if (!Finder.foundCaptures() &&
1586  CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1587  if (IsFilter)
1588  EmitSEHExceptionCodeSave(ParentCGF, nullptr, nullptr);
1589  return;
1590  }
1591 
1592  llvm::Value *EntryFP = nullptr;
1593  CGBuilderTy Builder(CGM, AllocaInsertPt);
1594  if (IsFilter && CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
1595  // 32-bit SEH filters need to be careful about FP recovery. The end of the
1596  // EH registration is passed in as the EBP physical register. We can
1597  // recover that with llvm.frameaddress(1).
1598  EntryFP = Builder.CreateCall(
1599  CGM.getIntrinsic(llvm::Intrinsic::frameaddress), {Builder.getInt32(1)});
1600  } else {
1601  // Otherwise, for x64 and 32-bit finally functions, the parent FP is the
1602  // second parameter.
1603  auto AI = CurFn->arg_begin();
1604  ++AI;
1605  EntryFP = &*AI;
1606  }
1607 
1608  llvm::Value *ParentFP = EntryFP;
1609  if (IsFilter) {
1610  // Given whatever FP the runtime provided us in EntryFP, recover the true
1611  // frame pointer of the parent function. We only need to do this in filters,
1612  // since finally funclets recover the parent FP for us.
1613  llvm::Function *RecoverFPIntrin =
1614  CGM.getIntrinsic(llvm::Intrinsic::x86_seh_recoverfp);
1615  llvm::Constant *ParentI8Fn =
1616  llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1617  ParentFP = Builder.CreateCall(RecoverFPIntrin, {ParentI8Fn, EntryFP});
1618  }
1619 
1620  // Create llvm.localrecover calls for all captures.
1621  for (const VarDecl *VD : Finder.Captures) {
1622  if (isa<ImplicitParamDecl>(VD)) {
1623  CGM.ErrorUnsupported(VD, "'this' captured by SEH");
1624  CXXThisValue = llvm::UndefValue::get(ConvertTypeForMem(VD->getType()));
1625  continue;
1626  }
1627  if (VD->getType()->isVariablyModifiedType()) {
1628  CGM.ErrorUnsupported(VD, "VLA captured by SEH");
1629  continue;
1630  }
1631  assert((isa<ImplicitParamDecl>(VD) || VD->isLocalVarDeclOrParm()) &&
1632  "captured non-local variable");
1633 
1634  // If this decl hasn't been declared yet, it will be declared in the
1635  // OutlinedStmt.
1636  auto I = ParentCGF.LocalDeclMap.find(VD);
1637  if (I == ParentCGF.LocalDeclMap.end())
1638  continue;
1639 
1640  Address ParentVar = I->second;
1641  setAddrOfLocalVar(
1642  VD, recoverAddrOfEscapedLocal(ParentCGF, ParentVar, ParentFP));
1643  }
1644 
1645  if (Finder.SEHCodeSlot.isValid()) {
1646  SEHCodeSlotStack.push_back(
1647  recoverAddrOfEscapedLocal(ParentCGF, Finder.SEHCodeSlot, ParentFP));
1648  }
1649 
1650  if (IsFilter)
1651  EmitSEHExceptionCodeSave(ParentCGF, ParentFP, EntryFP);
1652 }
1653 
1654 /// Arrange a function prototype that can be called by Windows exception
1655 /// handling personalities. On Win64, the prototype looks like:
1656 /// RetTy func(void *EHPtrs, void *ParentFP);
1658  bool IsFilter,
1659  const Stmt *OutlinedStmt) {
1660  SourceLocation StartLoc = OutlinedStmt->getLocStart();
1661 
1662  // Get the mangled function name.
1663  SmallString<128> Name;
1664  {
1665  llvm::raw_svector_ostream OS(Name);
1666  const FunctionDecl *ParentSEHFn = ParentCGF.CurSEHParent;
1667  assert(ParentSEHFn && "No CurSEHParent!");
1668  MangleContext &Mangler = CGM.getCXXABI().getMangleContext();
1669  if (IsFilter)
1670  Mangler.mangleSEHFilterExpression(ParentSEHFn, OS);
1671  else
1672  Mangler.mangleSEHFinallyBlock(ParentSEHFn, OS);
1673  }
1674 
1675  FunctionArgList Args;
1676  if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 || !IsFilter) {
1677  // All SEH finally functions take two parameters. Win64 filters take two
1678  // parameters. Win32 filters take no parameters.
1679  if (IsFilter) {
1680  Args.push_back(ImplicitParamDecl::Create(
1681  getContext(), /*DC=*/nullptr, StartLoc,
1682  &getContext().Idents.get("exception_pointers"),
1684  } else {
1685  Args.push_back(ImplicitParamDecl::Create(
1686  getContext(), /*DC=*/nullptr, StartLoc,
1687  &getContext().Idents.get("abnormal_termination"),
1689  }
1690  Args.push_back(ImplicitParamDecl::Create(
1691  getContext(), /*DC=*/nullptr, StartLoc,
1692  &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy,
1694  }
1695 
1696  QualType RetTy = IsFilter ? getContext().LongTy : getContext().VoidTy;
1697 
1698  const CGFunctionInfo &FnInfo =
1699  CGM.getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args);
1700 
1701  llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1702  llvm::Function *Fn = llvm::Function::Create(
1703  FnTy, llvm::GlobalValue::InternalLinkage, Name.str(), &CGM.getModule());
1704 
1705  IsOutlinedSEHHelper = true;
1706 
1707  StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
1708  OutlinedStmt->getLocStart(), OutlinedStmt->getLocStart());
1709  CurSEHParent = ParentCGF.CurSEHParent;
1710 
1711  CGM.SetLLVMFunctionAttributes(nullptr, FnInfo, CurFn);
1712  EmitCapturedLocals(ParentCGF, OutlinedStmt, IsFilter);
1713 }
1714 
1715 /// Create a stub filter function that will ultimately hold the code of the
1716 /// filter expression. The EH preparation passes in LLVM will outline the code
1717 /// from the main function body into this stub.
1718 llvm::Function *
1720  const SEHExceptStmt &Except) {
1721  const Expr *FilterExpr = Except.getFilterExpr();
1722  startOutlinedSEHHelper(ParentCGF, true, FilterExpr);
1723 
1724  // Emit the original filter expression, convert to i32, and return.
1725  llvm::Value *R = EmitScalarExpr(FilterExpr);
1726  R = Builder.CreateIntCast(R, ConvertType(getContext().LongTy),
1727  FilterExpr->getType()->isSignedIntegerType());
1728  Builder.CreateStore(R, ReturnValue);
1729 
1730  FinishFunction(FilterExpr->getLocEnd());
1731 
1732  return CurFn;
1733 }
1734 
1735 llvm::Function *
1737  const SEHFinallyStmt &Finally) {
1738  const Stmt *FinallyBlock = Finally.getBlock();
1739  startOutlinedSEHHelper(ParentCGF, false, FinallyBlock);
1740 
1741  // Emit the original filter expression, convert to i32, and return.
1742  EmitStmt(FinallyBlock);
1743 
1744  FinishFunction(FinallyBlock->getLocEnd());
1745 
1746  return CurFn;
1747 }
1748 
1750  llvm::Value *ParentFP,
1751  llvm::Value *EntryFP) {
1752  // Get the pointer to the EXCEPTION_POINTERS struct. This is returned by the
1753  // __exception_info intrinsic.
1754  if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1755  // On Win64, the info is passed as the first parameter to the filter.
1756  SEHInfo = &*CurFn->arg_begin();
1757  SEHCodeSlotStack.push_back(
1758  CreateMemTemp(getContext().IntTy, "__exception_code"));
1759  } else {
1760  // On Win32, the EBP on entry to the filter points to the end of an
1761  // exception registration object. It contains 6 32-bit fields, and the info
1762  // pointer is stored in the second field. So, GEP 20 bytes backwards and
1763  // load the pointer.
1764  SEHInfo = Builder.CreateConstInBoundsGEP1_32(Int8Ty, EntryFP, -20);
1765  SEHInfo = Builder.CreateBitCast(SEHInfo, Int8PtrTy->getPointerTo());
1766  SEHInfo = Builder.CreateAlignedLoad(Int8PtrTy, SEHInfo, getPointerAlign());
1767  SEHCodeSlotStack.push_back(recoverAddrOfEscapedLocal(
1768  ParentCGF, ParentCGF.SEHCodeSlotStack.back(), ParentFP));
1769  }
1770 
1771  // Save the exception code in the exception slot to unify exception access in
1772  // the filter function and the landing pad.
1773  // struct EXCEPTION_POINTERS {
1774  // EXCEPTION_RECORD *ExceptionRecord;
1775  // CONTEXT *ContextRecord;
1776  // };
1777  // int exceptioncode = exception_pointers->ExceptionRecord->ExceptionCode;
1778  llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
1779  llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy);
1780  llvm::Value *Ptrs = Builder.CreateBitCast(SEHInfo, PtrsTy->getPointerTo());
1781  llvm::Value *Rec = Builder.CreateStructGEP(PtrsTy, Ptrs, 0);
1782  Rec = Builder.CreateAlignedLoad(Rec, getPointerAlign());
1783  llvm::Value *Code = Builder.CreateAlignedLoad(Rec, getIntAlign());
1784  assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
1785  Builder.CreateStore(Code, SEHCodeSlotStack.back());
1786 }
1787 
1789  // Sema should diagnose calling this builtin outside of a filter context, but
1790  // don't crash if we screw up.
1791  if (!SEHInfo)
1792  return llvm::UndefValue::get(Int8PtrTy);
1793  assert(SEHInfo->getType() == Int8PtrTy);
1794  return SEHInfo;
1795 }
1796 
1798  assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
1799  return Builder.CreateLoad(SEHCodeSlotStack.back());
1800 }
1801 
1803  // Abnormal termination is just the first parameter to the outlined finally
1804  // helper.
1805  auto AI = CurFn->arg_begin();
1806  return Builder.CreateZExt(&*AI, Int32Ty);
1807 }
1808 
1810  CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true);
1811  if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
1812  // Outline the finally block.
1813  llvm::Function *FinallyFunc =
1814  HelperCGF.GenerateSEHFinallyFunction(*this, *Finally);
1815 
1816  // Push a cleanup for __finally blocks.
1817  EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, FinallyFunc);
1818  return;
1819  }
1820 
1821  // Otherwise, we must have an __except block.
1822  const SEHExceptStmt *Except = S.getExceptHandler();
1823  assert(Except);
1824  EHCatchScope *CatchScope = EHStack.pushCatch(1);
1825  SEHCodeSlotStack.push_back(
1826  CreateMemTemp(getContext().IntTy, "__exception_code"));
1827 
1828  // If the filter is known to evaluate to 1, then we can use the clause
1829  // "catch i8* null". We can't do this on x86 because the filter has to save
1830  // the exception code.
1831  llvm::Constant *C =
1833  getContext().IntTy);
1834  if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 && C &&
1835  C->isOneValue()) {
1836  CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
1837  return;
1838  }
1839 
1840  // In general, we have to emit an outlined filter function. Use the function
1841  // in place of the RTTI typeinfo global that C++ EH uses.
1842  llvm::Function *FilterFunc =
1843  HelperCGF.GenerateSEHFilterFunction(*this, *Except);
1844  llvm::Constant *OpaqueFunc =
1845  llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
1846  CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except.ret"));
1847 }
1848 
1850  // Just pop the cleanup if it's a __finally block.
1851  if (S.getFinallyHandler()) {
1852  PopCleanupBlock();
1853  return;
1854  }
1855 
1856  // Otherwise, we must have an __except block.
1857  const SEHExceptStmt *Except = S.getExceptHandler();
1858  assert(Except && "__try must have __finally xor __except");
1859  EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1860 
1861  // Don't emit the __except block if the __try block lacked invokes.
1862  // TODO: Model unwind edges from instructions, either with iload / istore or
1863  // a try body function.
1864  if (!CatchScope.hasEHBranches()) {
1865  CatchScope.clearHandlerBlocks();
1866  EHStack.popCatch();
1867  SEHCodeSlotStack.pop_back();
1868  return;
1869  }
1870 
1871  // The fall-through block.
1872  llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
1873 
1874  // We just emitted the body of the __try; jump to the continue block.
1875  if (HaveInsertPoint())
1876  Builder.CreateBr(ContBB);
1877 
1878  // Check if our filter function returned true.
1879  emitCatchDispatchBlock(*this, CatchScope);
1880 
1881  // Grab the block before we pop the handler.
1882  llvm::BasicBlock *CatchPadBB = CatchScope.getHandler(0).Block;
1883  EHStack.popCatch();
1884 
1885  EmitBlockAfterUses(CatchPadBB);
1886 
1887  // __except blocks don't get outlined into funclets, so immediately do a
1888  // catchret.
1889  llvm::CatchPadInst *CPI =
1890  cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
1891  llvm::BasicBlock *ExceptBB = createBasicBlock("__except");
1892  Builder.CreateCatchRet(CPI, ExceptBB);
1893  EmitBlock(ExceptBB);
1894 
1895  // On Win64, the exception code is returned in EAX. Copy it into the slot.
1896  if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1897  llvm::Function *SEHCodeIntrin =
1898  CGM.getIntrinsic(llvm::Intrinsic::eh_exceptioncode);
1899  llvm::Value *Code = Builder.CreateCall(SEHCodeIntrin, {CPI});
1900  Builder.CreateStore(Code, SEHCodeSlotStack.back());
1901  }
1902 
1903  // Emit the __except body.
1904  EmitStmt(Except->getBlock());
1905 
1906  // End the lifetime of the exception code.
1907  SEHCodeSlotStack.pop_back();
1908 
1909  if (HaveInsertPoint())
1910  Builder.CreateBr(ContBB);
1911 
1912  EmitBlock(ContBB);
1913 }
1914 
1916  // If this code is reachable then emit a stop point (if generating
1917  // debug info). We have to do this ourselves because we are on the
1918  // "simple" statement path.
1919  if (HaveInsertPoint())
1920  EmitStopPoint(&S);
1921 
1922  // This must be a __leave from a __finally block, which we warn on and is UB.
1923  // Just emit unreachable.
1924  if (!isSEHTryScope()) {
1925  Builder.CreateUnreachable();
1926  Builder.ClearInsertionPoint();
1927  return;
1928  }
1929 
1930  EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
1931 }
virtual void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl, raw_ostream &Out)=0
ReturnValueSlot - Contains the address where the return value of a function can be stored...
Definition: CGCall.h:325
Represents a function declaration or definition.
Definition: Decl.h:1696
llvm::IntegerType * IntTy
int
EHScopeStack::stable_iterator getEnclosingEHScope() const
Definition: CGCleanup.h:138
Other implicit parameter.
Definition: Decl.h:1475
CompoundStmt * getBlock() const
Definition: Stmt.h:1962
void setCatchAllHandler(unsigned I, llvm::BasicBlock *Block)
Definition: CGCleanup.h:193
CanQualType VoidPtrTy
Definition: ASTContext.h:1012
A (possibly-)qualified type.
Definition: Type.h:653
void EmitSEHLeaveStmt(const SEHLeaveStmt &S)
bool usesFuncletPads() const
Does this personality use landingpads or the family of pad instructions designed to form funclets...
Definition: CGCleanup.h:633
Represents a version number in the form major[.minor[.subminor[.build]]].
Definition: VersionTuple.h:26
unsigned getNumExceptions() const
Definition: Type.h:3576
const Expr * getSubExpr() const
Definition: ExprCXX.h:1007
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:195
llvm::BasicBlock * getCachedEHDispatchBlock() const
Definition: CGCleanup.h:124
bool HaveInsertPoint() const
HaveInsertPoint - True if an insertion point is defined.
static const EHPersonality GNU_C_SJLJ
Definition: CGCleanup.h:616
void EmitCXXTryStmt(const CXXTryStmt &S)
Stmt - This represents one statement.
Definition: Stmt.h:66
CXXCatchStmt * getHandler(unsigned i)
Definition: StmtCXX.h:104
static const EHPersonality MSVC_C_specific_handler
Definition: CGCleanup.h:628
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:790
static const EHPersonality MSVC_CxxFrameHandler3
Definition: CGCleanup.h:629
tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
Clean up any erroneous/redundant code in the given Ranges in Code.
Definition: Format.cpp:2206
bool hasEHBranches() const
Definition: CGCleanup.h:132
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Stmt * getHandlerBlock() const
Definition: StmtCXX.h:52
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
static const EHPersonality GNU_C
Definition: CGCleanup.h:615
virtual void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl, raw_ostream &Out)=0
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:5897
Represents Objective-C&#39;s @throw statement.
Definition: StmtObjC.h:313
CanQualType LongTy
Definition: ASTContext.h:1004
static llvm::Constant * getUnexpectedFn(CodeGenModule &CGM)
Definition: CGException.cpp:42
void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF, llvm::Value *ParentFP, llvm::Value *EntryEBP)
bool usesSEHTry() const
Indicates the function uses __try.
Definition: Decl.h:2068
static llvm::Constant * getPersonalityFn(CodeGenModule &CGM, const EHPersonality &Personality)
unsigned getNumFilters() const
Definition: CGCleanup.h:461
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
&#39;gcc&#39; is the Objective-C runtime shipped with GCC, implementing a fragile Objective-C ABI ...
Definition: ObjCRuntime.h:50
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::Instruction **callOrInvoke, SourceLocation Loc)
EmitCall - Generate a call of the given function, expecting the given result type, and using the given argument list which specifies both the LLVM arguments and the types they were derived from.
Definition: CGCall.cpp:3683
Represents a variable declaration or definition.
Definition: Decl.h:812
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6317
unsigned getNumHandlers() const
Definition: CGCleanup.h:189
llvm::Value * getPointer() const
Definition: Address.h:38
iterator begin() const
Returns an iterator pointing to the innermost EH scope.
Definition: CGCleanup.h:567
llvm::BasicBlock * EmitLandingPad()
Emits a landing pad for the current EH stack.
A protected scope for zero-cost EH handling.
Definition: CGCleanup.h:44
Defines the Objective-C statement AST node classes.
A C++ throw-expression (C++ [except.throw]).
Definition: ExprCXX.h:985
A scope which attempts to handle some, possibly all, types of exceptions.
Definition: CGCleanup.h:148
The collection of all-type qualifiers we support.
Definition: Type.h:152
A jump destination is an abstract label, branching to which may require a jump out through normal cle...
bool isNoexceptExceptionSpec(ExceptionSpecificationType ESpecType)
void popCatchScope()
popCatchScope - Pops the catch scope at the top of the EHScope stack, emitting any required code (oth...
const TargetInfo & getTarget() const
llvm::BasicBlock * getTerminateHandler()
getTerminateHandler - Return a handler (not a landing pad, just a catch handler) that just calls term...
&#39;macosx-fragile&#39; is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
Definition: ObjCRuntime.h:37
const char * CatchallRethrowFn
Definition: CGCleanup.h:610
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:149
QualType getCaughtType() const
Definition: StmtCXX.cpp:20
SmallVector< Address, 1 > SEHCodeSlotStack
A stack of exception code slots.
static const EHPersonality GNU_CPlusPlus_SJLJ
Definition: CGCleanup.h:625
const FunctionDecl * CurSEHParent
llvm::CallInst * EmitRuntimeCall(llvm::Value *callee, const Twine &name="")
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
Definition: EHScopeStack.h:81
static const EHPersonality & get(CodeGenModule &CGM, const FunctionDecl *FD)
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:50
Address getExceptionSlot()
Returns a pointer to the function&#39;s exception object and selector slot, which is assigned in every la...
void setFilter(unsigned i, llvm::Value *filterValue)
Definition: CGCleanup.h:463
class EHCatchScope * pushCatch(unsigned NumHandlers)
Push a set of catch handlers on the stack.
Definition: CGCleanup.cpp:251
bool isNeXTFamily() const
Is this runtime basically of the NeXT family of runtimes?
Definition: ObjCRuntime.h:133
static llvm::Constant * getFreeExceptionFn(CodeGenModule &CGM)
Definition: CGException.cpp:33
static llvm::Constant * getCatchAllValue(CodeGenFunction &CGF)
Returns the value to inject into a selector to indicate the presence of a catch-all.
void ExitSEHTryStmt(const SEHTryStmt &S)
QualType getExceptionType(unsigned i) const
Definition: Type.h:3577
iterator begin() const
Definition: CGCleanup.h:224
CharUnits getAlignment() const
Return the alignment of this pointer.
Definition: Address.h:67
child_range children()
Definition: Stmt.cpp:226
const Handler & getHandler(unsigned I) const
Definition: CGCleanup.h:209
static const EHPersonality GNUstep_ObjC
Definition: CGCleanup.h:621
llvm::Constant * getTerminateFn()
Get the declaration of std::terminate for the platform.
Definition: CGException.cpp:51
llvm::BasicBlock * getInvokeDestImpl()
llvm::Function * GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF, const SEHFinallyStmt &Finally)
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
Denotes a cleanup that should run when a scope is exited using normal control flow (falling off the e...
Definition: EHScopeStack.h:85
void ForceCleanup(std::initializer_list< llvm::Value **> ValuesToReload={})
Force the emission of cleanups now, instead of waiting until this object is destroyed.
Represents the body of a CapturedStmt, and serves as its DeclContext.
Definition: Decl.h:3883
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates an alloca and inserts it into the entry block if ArraySize is nullptr...
Definition: CGExpr.cpp:94
CanQualType UnsignedCharTy
Definition: ASTContext.h:1005
Represents the this expression in C++.
Definition: ExprCXX.h:945
llvm::Constant * CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false)
Create a new runtime function with the specified type and name.
static ImplicitParamDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, ImplicitParamKind ParamKind)
Create implicit parameter.
Definition: Decl.cpp:4218
&#39;watchos&#39; is a variant of iOS for Apple&#39;s watchOS.
Definition: ObjCRuntime.h:46
bool isValid() const
Definition: Address.h:36
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3274
llvm::CallInst * EmitNounwindRuntimeCall(llvm::Value *callee, const Twine &name="")
static const EHPersonality MSVC_except_handler
Definition: CGCleanup.h:627
static llvm::Constant * getOpaquePersonalityFn(CodeGenModule &CGM, const EHPersonality &Personality)
SourceLocation getLocEnd() const LLVM_READONLY
Definition: Stmt.cpp:290
CatchTypeInfo Type
A type info value, or null (C++ null, not an LLVM null pointer) for a catch-all.
Definition: CGCleanup.h:158
void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt, bool IsFilter)
Scan the outlined statement for captures from the parent function.
Expr - This represents one expression.
Definition: Expr.h:106
void enter(CodeGenFunction &CGF, const Stmt *Finally, llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn, llvm::Constant *rethrowFn)
Enters a finally block for an implementation using zero-cost exceptions.
static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn)
Check whether a personality function could reasonably be swapped for a C++ personality function...
&#39;macosx&#39; is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the non-fragile AB...
Definition: ObjCRuntime.h:32
static Address invalid()
Definition: Address.h:35
Enters a new scope for capturing cleanups, all of which will be executed once the scope is exited...
const FunctionProtoType * T
llvm::Function * GenerateSEHFilterFunction(CodeGenFunction &ParentCGF, const SEHExceptStmt &Except)
Create a stub filter function that will ultimately hold the code of the filter expression.
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition: CGCall.h:134
VarDecl * getExceptionDecl() const
Definition: StmtCXX.h:50
llvm::PointerType * getType() const
Return the type of the pointer value.
Definition: Address.h:44
void EmitSEHTryStmt(const SEHTryStmt &S)
llvm::BasicBlock * Block
The catch handler for this type.
Definition: CGCleanup.h:161
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
CXXTryStmt - A C++ try block, including all handlers.
Definition: StmtCXX.h:65
void add(RValue rvalue, QualType type, bool needscopy=false)
Definition: CGCall.h:251
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition: Expr.h:1165
llvm::Value * getExceptionFromSlot()
Returns the contents of the function&#39;s exception object and selector slots.
static void emitCatchDispatchBlock(CodeGenFunction &CGF, EHCatchScope &catchScope)
Emit the structure of the dispatch block for the given catch scope.
llvm::LLVMContext & getLLVMContext()
const CGFunctionInfo & arrangeBuiltinFunctionCall(QualType resultType, const CallArgList &args)
Definition: CGCall.cpp:627
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], or an enum decl which has a signed representation.
Definition: Type.cpp:1800
QualType getType() const
Definition: Expr.h:128
static const EHPersonality & getObjCXXPersonality(const llvm::Triple &T, const LangOptions &L)
Determines the personality function to use when both C++ and Objective-C exceptions are being caught...
static const EHPersonality GNU_ObjCXX
Definition: CGCleanup.h:622
bool hasTerminate() const
Does this runtime provide an objc_terminate function?
Definition: ObjCRuntime.h:257
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:134
static const EHPersonality GNU_ObjC_SEH
Definition: CGCleanup.h:620
const TargetInfo & getTarget() const
ValueDecl * getDecl()
Definition: Expr.h:1041
&#39;gnustep&#39; is the modern non-fragile GNUstep runtime.
Definition: ObjCRuntime.h:53
const LangOptions & getLangOpts() const
ASTContext & getContext() const
llvm::StoreInst * CreateFlagStore(bool Value, llvm::Value *Addr)
Emit a store to an i1 flag variable.
Definition: CGBuilder.h:136
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:35
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition: Expr.cpp:1279
llvm::BasicBlock * getEHDispatchBlock(EHScopeStack::stable_iterator scope)
The l-value was considered opaque, so the alignment was determined from a type.
static void emitFilterDispatchBlock(CodeGenFunction &CGF, EHFilterScope &filterScope)
Emit the dispatch block for a filter scope if necessary.
Address recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF, Address ParentVar, llvm::Value *ParentFP)
Recovers the address of a local in a parent function.
Enumerates target-specific builtins in their own namespaces within namespace clang.
Address CreateBitCast(Address Addr, llvm::Type *Ty, const llvm::Twine &Name="")
Definition: CGBuilder.h:142
static const EHPersonality & getObjCPersonality(const llvm::Triple &T, const LangOptions &L)
Encodes a location in the source.
void EnsureInsertPoint()
EnsureInsertPoint - Ensure that an insertion point is defined so that emitted IR has a place to go...
A saved depth on the scope stack.
Definition: EHScopeStack.h:107
unsigned getNumHandlers() const
Definition: StmtCXX.h:103
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:1880
&#39;objfw&#39; is the Objective-C runtime included in ObjFW
Definition: ObjCRuntime.h:56
llvm::BasicBlock * getUnreachableBlock()
llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee, ArrayRef< llvm::Value *> args, const Twine &name="")
Emits a call or invoke instruction to the given runtime function.
Definition: CGCall.cpp:3632
Kind getKind() const
Definition: ObjCRuntime.h:75
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition: Mangle.h:42
void EmitStmt(const Stmt *S, ArrayRef< const Attr *> Attrs=None)
EmitStmt - Emit the code for the statement.
Definition: CGStmt.cpp:48
The noexcept specifier evaluates to true.
Definition: Type.h:3571
CanQualType VoidTy
Definition: ASTContext.h:996
bool isObjCObjectPointerType() const
Definition: Type.h:6045
An aligned address.
Definition: Address.h:25
llvm::BasicBlock * getEHResumeBlock(bool isCleanup)
void setCachedEHDispatchBlock(llvm::BasicBlock *block)
Definition: CGCleanup.h:128
llvm::Instruction * CurrentFuncletPad
llvm::Value * getFilter(unsigned i) const
Definition: CGCleanup.h:468
JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target)
The given basic block lies in the current EH scope, but may be a target of a potentially scope-crossi...
const VersionTuple & getVersion() const
Definition: ObjCRuntime.h:76
void EmitStartEHSpec(const Decl *D)
EmitStartEHSpec - Emit the start of the exception spec.
The MS C++ ABI needs a pointer to RTTI data plus some flags to describe the type of a catch handler...
Definition: CGCleanup.h:38
static const EHPersonality & getCXXPersonality(const llvm::Triple &T, const LangOptions &L)
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:3530
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:216
static const EHPersonality NeXT_ObjC
Definition: CGCleanup.h:623
FunctionArgList - Type for representing both the decl and type of parameters to a function...
Definition: CGCall.h:320
llvm::BasicBlock * getMSVCDispatchBlock(EHScopeStack::stable_iterator scope)
CGFunctionInfo - Class to encapsulate the information about a function definition.
Kind getKind() const
Definition: CGCleanup.h:114
This class organizes the cross-function state that is used while generating LLVM code.
Dataflow Directional Tag Classes.
static ApplyDebugLocation CreateDefaultArtificial(CodeGenFunction &CGF, SourceLocation TemporaryLocation)
Apply TemporaryLocation if it is valid.
Definition: CGDebugInfo.h:675
static bool LandingPadHasOnlyCXXUses(llvm::LandingPadInst *LPI)
Check whether a landingpad instruction only uses C++ features.
static const EHPersonality GNU_CPlusPlus_SEH
Definition: CGCleanup.h:626
The basic abstraction for the target Objective-C runtime.
Definition: ObjCRuntime.h:25
static const EHPersonality GNU_ObjC
Definition: CGCleanup.h:618
static bool isNonEHScope(const EHScope &S)
Check whether this is a non-EH scope, i.e.
void EmitAnyExprToExn(const Expr *E, Address Addr)
llvm::LoadInst * CreateAlignedLoad(llvm::Value *Addr, CharUnits Align, const llvm::Twine &Name="")
Definition: CGBuilder.h:91
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition: CGBuilder.h:70
SEHExceptStmt * getExceptHandler() const
Returns 0 if not defined.
Definition: Stmt.cpp:948
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type *> Tys=None)
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition: CGBuilder.h:108
llvm::Module & getModule() const
Represents a __leave statement.
Definition: Stmt.h:2023
&#39;ios&#39; is the Apple-provided NeXT-derived runtime on iOS or the iOS simulator; it is always non-fragil...
Definition: ObjCRuntime.h:42
llvm::BasicBlock * getTerminateFunclet()
getTerminateLandingPad - Return a cleanup funclet that just calls terminate.
static const EHPersonality GNU_CPlusPlus
Definition: CGCleanup.h:624
llvm::LoadInst * CreateFlagLoad(llvm::Value *Addr, const llvm::Twine &Name="")
Emit a load from an i1 flag variable.
Definition: CGBuilder.h:129
llvm::StringRef getName() const
Return the IR name of the pointer value.
Definition: Address.h:62
static const EHPersonality GNU_ObjC_SJLJ
Definition: CGCleanup.h:619
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition: Linkage.h:33
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition: CGStmt.cpp:445
void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock=false)
SEHFinallyStmt * getFinallyHandler() const
Definition: Stmt.cpp:952
static const EHPersonality & getSEHPersonalityMSVC(const llvm::Triple &T)
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:5804
Expr * getFilterExpr() const
Definition: Stmt.h:1924
llvm::BasicBlock * getTerminateLandingPad()
getTerminateLandingPad - Return a landing pad that just calls terminate.
CXXCatchStmt - This represents a C++ catch block.
Definition: StmtCXX.h:29
llvm::Type * ConvertType(QualType T)
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:5751
static const EHPersonality GNU_C_SEH
Definition: CGCleanup.h:617
static const EHPersonality & getCPersonality(const llvm::Triple &T, const LangOptions &L)
The exceptions personality for a function.
Definition: CGCleanup.h:604
llvm::Constant * RTTI
Definition: CGCleanup.h:39
CompoundStmt * getTryBlock()
Definition: StmtCXX.h:96
llvm::Value * EmitSEHAbnormalTermination()
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2218
llvm::Constant * tryEmitAbstract(const Expr *E, QualType T)
Try to emit the result of the given expression as an abstract constant.
void EnterSEHTryStmt(const SEHTryStmt &S)
void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter, const Stmt *OutlinedStmt)
Arrange a function prototype that can be called by Windows exception handling personalities.
CGCXXABI & getCXXABI() const
CanQualType IntTy
Definition: ASTContext.h:1004
An exceptions scope which filters exceptions thrown through it.
Definition: CGCleanup.h:438
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:956
static RValue get(llvm::Value *V)
Definition: CGValue.h:86
void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock=false)
void EmitBranchThroughCleanup(JumpDest Dest)
EmitBranchThroughCleanup - Emit a branch from the current insert block through the normal cleanup han...
Definition: CGCleanup.cpp:1034
void EmitEndEHSpec(const Decl *D)
EmitEndEHSpec - Emit the end of the exception spec.
static llvm::Constant * getCatchallRethrowFn(CodeGenModule &CGM, StringRef Name)
Definition: CGException.cpp:77
llvm::StoreInst * CreateAlignedStore(llvm::Value *Val, llvm::Value *Addr, CharUnits Align, bool IsVolatile=false)
Definition: CGBuilder.h:115
QualType getType() const
Definition: Decl.h:647
NoexceptResult getNoexceptSpec(const ASTContext &Ctx) const
Get the meaning of the noexcept spec on this function, if any.
Definition: Type.cpp:2838
Information for lazily generating a cleanup.
Definition: EHScopeStack.h:147
A non-stable pointer into the scope stack.
Definition: CGCleanup.h:503
void EmitBlockAfterUses(llvm::BasicBlock *BB)
EmitBlockAfterUses - Emit the given block somewhere hopefully near its uses, and leave the insertion ...
Definition: CGStmt.cpp:482
static void emitCatchPadBlock(CodeGenFunction &CGF, EHCatchScope &CatchScope)
SourceLocation getLocStart() const LLVM_READONLY
Definition: Stmt.cpp:277
CallArgList - Type for representing both the value and type of arguments in a call.
Definition: CGCall.h:226
void PopCleanupBlock(bool FallThroughIsBranchThrough=false)
PopCleanupBlock - Will pop the cleanup entry on the stack and process all branch fixups.
Definition: CGCleanup.cpp:640
void setHandler(unsigned I, llvm::Constant *Type, llvm::BasicBlock *Block)
Definition: CGCleanup.h:197
CompoundStmt * getTryBlock() const
Definition: Stmt.h:2003
CompoundStmt * getBlock() const
Definition: Stmt.h:1928
void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint=true)
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition: Decl.h:1108
static OMPLinearClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind Modifier, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef< Expr *> VL, ArrayRef< Expr *> PL, ArrayRef< Expr *> IL, Expr *Step, Expr *CalcStep, Stmt *PreInit, Expr *PostUpdate)
Creates clause with a list of variables VL and a linear step Step.
const llvm::Triple & getTriple() const