clang  6.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  // 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 = getTerminateHandler();
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  CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1338 
1339  // Set up the terminate handler. This block is inserted at the very
1340  // end of the function by FinishFunction.
1341  TerminateHandler = createBasicBlock("terminate.handler");
1342  Builder.SetInsertPoint(TerminateHandler);
1343  llvm::Value *Exn = nullptr;
1344  SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
1345  CurrentFuncletPad);
1346  if (EHPersonality::get(*this).usesFuncletPads()) {
1347  llvm::Value *ParentPad = CurrentFuncletPad;
1348  if (!ParentPad)
1349  ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
1350  CurrentFuncletPad = Builder.CreateCleanupPad(ParentPad);
1351  } else {
1352  if (getLangOpts().CPlusPlus)
1353  Exn = getExceptionFromSlot();
1354  }
1355  llvm::CallInst *terminateCall =
1356  CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
1357  terminateCall->setDoesNotReturn();
1358  Builder.CreateUnreachable();
1359 
1360  // Restore the saved insertion state.
1361  Builder.restoreIP(SavedIP);
1362 
1363  return TerminateHandler;
1364 }
1365 
1366 llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
1367  if (EHResumeBlock) return EHResumeBlock;
1368 
1369  CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1370 
1371  // We emit a jump to a notional label at the outermost unwind state.
1372  EHResumeBlock = createBasicBlock("eh.resume");
1373  Builder.SetInsertPoint(EHResumeBlock);
1374 
1375  const EHPersonality &Personality = EHPersonality::get(*this);
1376 
1377  // This can always be a call because we necessarily didn't find
1378  // anything on the EH stack which needs our help.
1379  const char *RethrowName = Personality.CatchallRethrowFn;
1380  if (RethrowName != nullptr && !isCleanup) {
1381  EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
1382  getExceptionFromSlot())->setDoesNotReturn();
1383  Builder.CreateUnreachable();
1384  Builder.restoreIP(SavedIP);
1385  return EHResumeBlock;
1386  }
1387 
1388  // Recreate the landingpad's return value for the 'resume' instruction.
1389  llvm::Value *Exn = getExceptionFromSlot();
1390  llvm::Value *Sel = getSelectorFromSlot();
1391 
1392  llvm::Type *LPadType = llvm::StructType::get(Exn->getType(), Sel->getType());
1393  llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
1394  LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1395  LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1396 
1397  Builder.CreateResume(LPadVal);
1398  Builder.restoreIP(SavedIP);
1399  return EHResumeBlock;
1400 }
1401 
1403  EnterSEHTryStmt(S);
1404  {
1405  JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
1406 
1407  SEHTryEpilogueStack.push_back(&TryExit);
1408  EmitStmt(S.getTryBlock());
1409  SEHTryEpilogueStack.pop_back();
1410 
1411  if (!TryExit.getBlock()->use_empty())
1412  EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
1413  else
1414  delete TryExit.getBlock();
1415  }
1416  ExitSEHTryStmt(S);
1417 }
1418 
1419 namespace {
1420 struct PerformSEHFinally final : EHScopeStack::Cleanup {
1421  llvm::Function *OutlinedFinally;
1422  PerformSEHFinally(llvm::Function *OutlinedFinally)
1423  : OutlinedFinally(OutlinedFinally) {}
1424 
1425  void Emit(CodeGenFunction &CGF, Flags F) override {
1426  ASTContext &Context = CGF.getContext();
1427  CodeGenModule &CGM = CGF.CGM;
1428 
1429  CallArgList Args;
1430 
1431  // Compute the two argument values.
1432  QualType ArgTys[2] = {Context.UnsignedCharTy, Context.VoidPtrTy};
1433  llvm::Value *LocalAddrFn = CGM.getIntrinsic(llvm::Intrinsic::localaddress);
1434  llvm::Value *FP = CGF.Builder.CreateCall(LocalAddrFn);
1435  llvm::Value *IsForEH =
1436  llvm::ConstantInt::get(CGF.ConvertType(ArgTys[0]), F.isForEHCleanup());
1437  Args.add(RValue::get(IsForEH), ArgTys[0]);
1438  Args.add(RValue::get(FP), ArgTys[1]);
1439 
1440  // Arrange a two-arg function info and type.
1441  const CGFunctionInfo &FnInfo =
1442  CGM.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, Args);
1443 
1444  auto Callee = CGCallee::forDirect(OutlinedFinally);
1445  CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
1446  }
1447 };
1448 } // end anonymous namespace
1449 
1450 namespace {
1451 /// Find all local variable captures in the statement.
1452 struct CaptureFinder : ConstStmtVisitor<CaptureFinder> {
1453  CodeGenFunction &ParentCGF;
1454  const VarDecl *ParentThis;
1456  Address SEHCodeSlot = Address::invalid();
1457  CaptureFinder(CodeGenFunction &ParentCGF, const VarDecl *ParentThis)
1458  : ParentCGF(ParentCGF), ParentThis(ParentThis) {}
1459 
1460  // Return true if we need to do any capturing work.
1461  bool foundCaptures() {
1462  return !Captures.empty() || SEHCodeSlot.isValid();
1463  }
1464 
1465  void Visit(const Stmt *S) {
1466  // See if this is a capture, then recurse.
1468  for (const Stmt *Child : S->children())
1469  if (Child)
1470  Visit(Child);
1471  }
1472 
1473  void VisitDeclRefExpr(const DeclRefExpr *E) {
1474  // If this is already a capture, just make sure we capture 'this'.
1476  Captures.insert(ParentThis);
1477  return;
1478  }
1479 
1480  const auto *D = dyn_cast<VarDecl>(E->getDecl());
1481  if (D && D->isLocalVarDeclOrParm() && D->hasLocalStorage())
1482  Captures.insert(D);
1483  }
1484 
1485  void VisitCXXThisExpr(const CXXThisExpr *E) {
1486  Captures.insert(ParentThis);
1487  }
1488 
1489  void VisitCallExpr(const CallExpr *E) {
1490  // We only need to add parent frame allocations for these builtins in x86.
1491  if (ParentCGF.getTarget().getTriple().getArch() != llvm::Triple::x86)
1492  return;
1493 
1494  unsigned ID = E->getBuiltinCallee();
1495  switch (ID) {
1496  case Builtin::BI__exception_code:
1497  case Builtin::BI_exception_code:
1498  // This is the simple case where we are the outermost finally. All we
1499  // have to do here is make sure we escape this and recover it in the
1500  // outlined handler.
1501  if (!SEHCodeSlot.isValid())
1502  SEHCodeSlot = ParentCGF.SEHCodeSlotStack.back();
1503  break;
1504  }
1505  }
1506 };
1507 } // end anonymous namespace
1508 
1510  Address ParentVar,
1511  llvm::Value *ParentFP) {
1512  llvm::CallInst *RecoverCall = nullptr;
1513  CGBuilderTy Builder(*this, AllocaInsertPt);
1514  if (auto *ParentAlloca = dyn_cast<llvm::AllocaInst>(ParentVar.getPointer())) {
1515  // Mark the variable escaped if nobody else referenced it and compute the
1516  // localescape index.
1517  auto InsertPair = ParentCGF.EscapedLocals.insert(
1518  std::make_pair(ParentAlloca, ParentCGF.EscapedLocals.size()));
1519  int FrameEscapeIdx = InsertPair.first->second;
1520  // call i8* @llvm.localrecover(i8* bitcast(@parentFn), i8* %fp, i32 N)
1521  llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
1522  &CGM.getModule(), llvm::Intrinsic::localrecover);
1523  llvm::Constant *ParentI8Fn =
1524  llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1525  RecoverCall = Builder.CreateCall(
1526  FrameRecoverFn, {ParentI8Fn, ParentFP,
1527  llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)});
1528 
1529  } else {
1530  // If the parent didn't have an alloca, we're doing some nested outlining.
1531  // Just clone the existing localrecover call, but tweak the FP argument to
1532  // use our FP value. All other arguments are constants.
1533  auto *ParentRecover =
1534  cast<llvm::IntrinsicInst>(ParentVar.getPointer()->stripPointerCasts());
1535  assert(ParentRecover->getIntrinsicID() == llvm::Intrinsic::localrecover &&
1536  "expected alloca or localrecover in parent LocalDeclMap");
1537  RecoverCall = cast<llvm::CallInst>(ParentRecover->clone());
1538  RecoverCall->setArgOperand(1, ParentFP);
1539  RecoverCall->insertBefore(AllocaInsertPt);
1540  }
1541 
1542  // Bitcast the variable, rename it, and insert it in the local decl map.
1543  llvm::Value *ChildVar =
1544  Builder.CreateBitCast(RecoverCall, ParentVar.getType());
1545  ChildVar->setName(ParentVar.getName());
1546  return Address(ChildVar, ParentVar.getAlignment());
1547 }
1548 
1550  const Stmt *OutlinedStmt,
1551  bool IsFilter) {
1552  // Find all captures in the Stmt.
1553  CaptureFinder Finder(ParentCGF, ParentCGF.CXXABIThisDecl);
1554  Finder.Visit(OutlinedStmt);
1555 
1556  // We can exit early on x86_64 when there are no captures. We just have to
1557  // save the exception code in filters so that __exception_code() works.
1558  if (!Finder.foundCaptures() &&
1559  CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1560  if (IsFilter)
1561  EmitSEHExceptionCodeSave(ParentCGF, nullptr, nullptr);
1562  return;
1563  }
1564 
1565  llvm::Value *EntryFP = nullptr;
1566  CGBuilderTy Builder(CGM, AllocaInsertPt);
1567  if (IsFilter && CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
1568  // 32-bit SEH filters need to be careful about FP recovery. The end of the
1569  // EH registration is passed in as the EBP physical register. We can
1570  // recover that with llvm.frameaddress(1).
1571  EntryFP = Builder.CreateCall(
1572  CGM.getIntrinsic(llvm::Intrinsic::frameaddress), {Builder.getInt32(1)});
1573  } else {
1574  // Otherwise, for x64 and 32-bit finally functions, the parent FP is the
1575  // second parameter.
1576  auto AI = CurFn->arg_begin();
1577  ++AI;
1578  EntryFP = &*AI;
1579  }
1580 
1581  llvm::Value *ParentFP = EntryFP;
1582  if (IsFilter) {
1583  // Given whatever FP the runtime provided us in EntryFP, recover the true
1584  // frame pointer of the parent function. We only need to do this in filters,
1585  // since finally funclets recover the parent FP for us.
1586  llvm::Function *RecoverFPIntrin =
1587  CGM.getIntrinsic(llvm::Intrinsic::x86_seh_recoverfp);
1588  llvm::Constant *ParentI8Fn =
1589  llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
1590  ParentFP = Builder.CreateCall(RecoverFPIntrin, {ParentI8Fn, EntryFP});
1591  }
1592 
1593  // Create llvm.localrecover calls for all captures.
1594  for (const VarDecl *VD : Finder.Captures) {
1595  if (isa<ImplicitParamDecl>(VD)) {
1596  CGM.ErrorUnsupported(VD, "'this' captured by SEH");
1597  CXXThisValue = llvm::UndefValue::get(ConvertTypeForMem(VD->getType()));
1598  continue;
1599  }
1600  if (VD->getType()->isVariablyModifiedType()) {
1601  CGM.ErrorUnsupported(VD, "VLA captured by SEH");
1602  continue;
1603  }
1604  assert((isa<ImplicitParamDecl>(VD) || VD->isLocalVarDeclOrParm()) &&
1605  "captured non-local variable");
1606 
1607  // If this decl hasn't been declared yet, it will be declared in the
1608  // OutlinedStmt.
1609  auto I = ParentCGF.LocalDeclMap.find(VD);
1610  if (I == ParentCGF.LocalDeclMap.end())
1611  continue;
1612 
1613  Address ParentVar = I->second;
1614  setAddrOfLocalVar(
1615  VD, recoverAddrOfEscapedLocal(ParentCGF, ParentVar, ParentFP));
1616  }
1617 
1618  if (Finder.SEHCodeSlot.isValid()) {
1619  SEHCodeSlotStack.push_back(
1620  recoverAddrOfEscapedLocal(ParentCGF, Finder.SEHCodeSlot, ParentFP));
1621  }
1622 
1623  if (IsFilter)
1624  EmitSEHExceptionCodeSave(ParentCGF, ParentFP, EntryFP);
1625 }
1626 
1627 /// Arrange a function prototype that can be called by Windows exception
1628 /// handling personalities. On Win64, the prototype looks like:
1629 /// RetTy func(void *EHPtrs, void *ParentFP);
1631  bool IsFilter,
1632  const Stmt *OutlinedStmt) {
1633  SourceLocation StartLoc = OutlinedStmt->getLocStart();
1634 
1635  // Get the mangled function name.
1636  SmallString<128> Name;
1637  {
1638  llvm::raw_svector_ostream OS(Name);
1639  const FunctionDecl *ParentSEHFn = ParentCGF.CurSEHParent;
1640  assert(ParentSEHFn && "No CurSEHParent!");
1641  MangleContext &Mangler = CGM.getCXXABI().getMangleContext();
1642  if (IsFilter)
1643  Mangler.mangleSEHFilterExpression(ParentSEHFn, OS);
1644  else
1645  Mangler.mangleSEHFinallyBlock(ParentSEHFn, OS);
1646  }
1647 
1648  FunctionArgList Args;
1649  if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 || !IsFilter) {
1650  // All SEH finally functions take two parameters. Win64 filters take two
1651  // parameters. Win32 filters take no parameters.
1652  if (IsFilter) {
1653  Args.push_back(ImplicitParamDecl::Create(
1654  getContext(), /*DC=*/nullptr, StartLoc,
1655  &getContext().Idents.get("exception_pointers"),
1657  } else {
1658  Args.push_back(ImplicitParamDecl::Create(
1659  getContext(), /*DC=*/nullptr, StartLoc,
1660  &getContext().Idents.get("abnormal_termination"),
1662  }
1663  Args.push_back(ImplicitParamDecl::Create(
1664  getContext(), /*DC=*/nullptr, StartLoc,
1665  &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy,
1667  }
1668 
1669  QualType RetTy = IsFilter ? getContext().LongTy : getContext().VoidTy;
1670 
1671  const CGFunctionInfo &FnInfo =
1672  CGM.getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args);
1673 
1674  llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1675  llvm::Function *Fn = llvm::Function::Create(
1676  FnTy, llvm::GlobalValue::InternalLinkage, Name.str(), &CGM.getModule());
1677 
1678  IsOutlinedSEHHelper = true;
1679 
1680  StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
1681  OutlinedStmt->getLocStart(), OutlinedStmt->getLocStart());
1682  CurSEHParent = ParentCGF.CurSEHParent;
1683 
1684  CGM.SetLLVMFunctionAttributes(nullptr, FnInfo, CurFn);
1685  EmitCapturedLocals(ParentCGF, OutlinedStmt, IsFilter);
1686 }
1687 
1688 /// Create a stub filter function that will ultimately hold the code of the
1689 /// filter expression. The EH preparation passes in LLVM will outline the code
1690 /// from the main function body into this stub.
1691 llvm::Function *
1693  const SEHExceptStmt &Except) {
1694  const Expr *FilterExpr = Except.getFilterExpr();
1695  startOutlinedSEHHelper(ParentCGF, true, FilterExpr);
1696 
1697  // Emit the original filter expression, convert to i32, and return.
1698  llvm::Value *R = EmitScalarExpr(FilterExpr);
1699  R = Builder.CreateIntCast(R, ConvertType(getContext().LongTy),
1700  FilterExpr->getType()->isSignedIntegerType());
1701  Builder.CreateStore(R, ReturnValue);
1702 
1703  FinishFunction(FilterExpr->getLocEnd());
1704 
1705  return CurFn;
1706 }
1707 
1708 llvm::Function *
1710  const SEHFinallyStmt &Finally) {
1711  const Stmt *FinallyBlock = Finally.getBlock();
1712  startOutlinedSEHHelper(ParentCGF, false, FinallyBlock);
1713 
1714  // Emit the original filter expression, convert to i32, and return.
1715  EmitStmt(FinallyBlock);
1716 
1717  FinishFunction(FinallyBlock->getLocEnd());
1718 
1719  return CurFn;
1720 }
1721 
1723  llvm::Value *ParentFP,
1724  llvm::Value *EntryFP) {
1725  // Get the pointer to the EXCEPTION_POINTERS struct. This is returned by the
1726  // __exception_info intrinsic.
1727  if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1728  // On Win64, the info is passed as the first parameter to the filter.
1729  SEHInfo = &*CurFn->arg_begin();
1730  SEHCodeSlotStack.push_back(
1731  CreateMemTemp(getContext().IntTy, "__exception_code"));
1732  } else {
1733  // On Win32, the EBP on entry to the filter points to the end of an
1734  // exception registration object. It contains 6 32-bit fields, and the info
1735  // pointer is stored in the second field. So, GEP 20 bytes backwards and
1736  // load the pointer.
1737  SEHInfo = Builder.CreateConstInBoundsGEP1_32(Int8Ty, EntryFP, -20);
1738  SEHInfo = Builder.CreateBitCast(SEHInfo, Int8PtrTy->getPointerTo());
1739  SEHInfo = Builder.CreateAlignedLoad(Int8PtrTy, SEHInfo, getPointerAlign());
1740  SEHCodeSlotStack.push_back(recoverAddrOfEscapedLocal(
1741  ParentCGF, ParentCGF.SEHCodeSlotStack.back(), ParentFP));
1742  }
1743 
1744  // Save the exception code in the exception slot to unify exception access in
1745  // the filter function and the landing pad.
1746  // struct EXCEPTION_POINTERS {
1747  // EXCEPTION_RECORD *ExceptionRecord;
1748  // CONTEXT *ContextRecord;
1749  // };
1750  // int exceptioncode = exception_pointers->ExceptionRecord->ExceptionCode;
1751  llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
1752  llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy);
1753  llvm::Value *Ptrs = Builder.CreateBitCast(SEHInfo, PtrsTy->getPointerTo());
1754  llvm::Value *Rec = Builder.CreateStructGEP(PtrsTy, Ptrs, 0);
1755  Rec = Builder.CreateAlignedLoad(Rec, getPointerAlign());
1756  llvm::Value *Code = Builder.CreateAlignedLoad(Rec, getIntAlign());
1757  assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
1758  Builder.CreateStore(Code, SEHCodeSlotStack.back());
1759 }
1760 
1762  // Sema should diagnose calling this builtin outside of a filter context, but
1763  // don't crash if we screw up.
1764  if (!SEHInfo)
1765  return llvm::UndefValue::get(Int8PtrTy);
1766  assert(SEHInfo->getType() == Int8PtrTy);
1767  return SEHInfo;
1768 }
1769 
1771  assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
1772  return Builder.CreateLoad(SEHCodeSlotStack.back());
1773 }
1774 
1776  // Abnormal termination is just the first parameter to the outlined finally
1777  // helper.
1778  auto AI = CurFn->arg_begin();
1779  return Builder.CreateZExt(&*AI, Int32Ty);
1780 }
1781 
1783  CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true);
1784  if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
1785  // Outline the finally block.
1786  llvm::Function *FinallyFunc =
1787  HelperCGF.GenerateSEHFinallyFunction(*this, *Finally);
1788 
1789  // Push a cleanup for __finally blocks.
1790  EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, FinallyFunc);
1791  return;
1792  }
1793 
1794  // Otherwise, we must have an __except block.
1795  const SEHExceptStmt *Except = S.getExceptHandler();
1796  assert(Except);
1797  EHCatchScope *CatchScope = EHStack.pushCatch(1);
1798  SEHCodeSlotStack.push_back(
1799  CreateMemTemp(getContext().IntTy, "__exception_code"));
1800 
1801  // If the filter is known to evaluate to 1, then we can use the clause
1802  // "catch i8* null". We can't do this on x86 because the filter has to save
1803  // the exception code.
1804  llvm::Constant *C =
1806  getContext().IntTy);
1807  if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 && C &&
1808  C->isOneValue()) {
1809  CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
1810  return;
1811  }
1812 
1813  // In general, we have to emit an outlined filter function. Use the function
1814  // in place of the RTTI typeinfo global that C++ EH uses.
1815  llvm::Function *FilterFunc =
1816  HelperCGF.GenerateSEHFilterFunction(*this, *Except);
1817  llvm::Constant *OpaqueFunc =
1818  llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
1819  CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except.ret"));
1820 }
1821 
1823  // Just pop the cleanup if it's a __finally block.
1824  if (S.getFinallyHandler()) {
1825  PopCleanupBlock();
1826  return;
1827  }
1828 
1829  // Otherwise, we must have an __except block.
1830  const SEHExceptStmt *Except = S.getExceptHandler();
1831  assert(Except && "__try must have __finally xor __except");
1832  EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1833 
1834  // Don't emit the __except block if the __try block lacked invokes.
1835  // TODO: Model unwind edges from instructions, either with iload / istore or
1836  // a try body function.
1837  if (!CatchScope.hasEHBranches()) {
1838  CatchScope.clearHandlerBlocks();
1839  EHStack.popCatch();
1840  SEHCodeSlotStack.pop_back();
1841  return;
1842  }
1843 
1844  // The fall-through block.
1845  llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
1846 
1847  // We just emitted the body of the __try; jump to the continue block.
1848  if (HaveInsertPoint())
1849  Builder.CreateBr(ContBB);
1850 
1851  // Check if our filter function returned true.
1852  emitCatchDispatchBlock(*this, CatchScope);
1853 
1854  // Grab the block before we pop the handler.
1855  llvm::BasicBlock *CatchPadBB = CatchScope.getHandler(0).Block;
1856  EHStack.popCatch();
1857 
1858  EmitBlockAfterUses(CatchPadBB);
1859 
1860  // __except blocks don't get outlined into funclets, so immediately do a
1861  // catchret.
1862  llvm::CatchPadInst *CPI =
1863  cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
1864  llvm::BasicBlock *ExceptBB = createBasicBlock("__except");
1865  Builder.CreateCatchRet(CPI, ExceptBB);
1866  EmitBlock(ExceptBB);
1867 
1868  // On Win64, the exception code is returned in EAX. Copy it into the slot.
1869  if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1870  llvm::Function *SEHCodeIntrin =
1871  CGM.getIntrinsic(llvm::Intrinsic::eh_exceptioncode);
1872  llvm::Value *Code = Builder.CreateCall(SEHCodeIntrin, {CPI});
1873  Builder.CreateStore(Code, SEHCodeSlotStack.back());
1874  }
1875 
1876  // Emit the __except body.
1877  EmitStmt(Except->getBlock());
1878 
1879  // End the lifetime of the exception code.
1880  SEHCodeSlotStack.pop_back();
1881 
1882  if (HaveInsertPoint())
1883  Builder.CreateBr(ContBB);
1884 
1885  EmitBlock(ContBB);
1886 }
1887 
1889  // If this code is reachable then emit a stop point (if generating
1890  // debug info). We have to do this ourselves because we are on the
1891  // "simple" statement path.
1892  if (HaveInsertPoint())
1893  EmitStopPoint(&S);
1894 
1895  // This must be a __leave from a __finally block, which we warn on and is UB.
1896  // Just emit unreachable.
1897  if (!isSEHTryScope()) {
1898  Builder.CreateUnreachable();
1899  Builder.ClearInsertionPoint();
1900  return;
1901  }
1902 
1903  EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
1904 }
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:281
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1698
llvm::IntegerType * IntTy
int
EHScopeStack::stable_iterator getEnclosingEHScope() const
Definition: CGCleanup.h:138
Other implicit parameter.
Definition: Decl.h:1474
CompoundStmt * getBlock() const
Definition: Stmt.h:1958
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:3572
const Expr * getSubExpr() const
Definition: ExprCXX.h:1007
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:192
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:2029
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:5893
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:2052
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
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:807
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6307
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:48
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:3573
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.
This represents the body of a CapturedStmt, and serves as its DeclContext.
Definition: Decl.h:3860
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:4187
&#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:3270
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:125
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:207
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:117
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:1876
&#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:3666
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:3567
CanQualType VoidTy
Definition: ASTContext.h:996
bool isObjCObjectPointerType() const
Definition: Type.h:6041
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:3526
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:276
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:658
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:945
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:2019
&#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
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:436
void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock=false)
SEHFinallyStmt * getFinallyHandler() const
Definition: Stmt.cpp:949
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:5800
Expr * getFilterExpr() const
Definition: Stmt.h:1920
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:5747
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:2209
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:639
NoexceptResult getNoexceptSpec(const ASTContext &Ctx) const
Get the meaning of the noexcept spec on this function, if any.
Definition: Type.cpp:2837
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:473
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:182
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:1999
CompoundStmt * getBlock() const
Definition: Stmt.h:1924
void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint=true)
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition: Decl.h:1105
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::Instruction **callOrInvoke=nullptr)
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:3717
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