clang 20.0.0git
CGException.cpp
Go to the documentation of this file.
1//===--- CGException.cpp - Emit LLVM Code for C++ exceptions ----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This contains code dealing with C++ exception related code generation.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGCXXABI.h"
14#include "CGCleanup.h"
15#include "CGObjCRuntime.h"
16#include "CodeGenFunction.h"
17#include "ConstantEmitter.h"
18#include "TargetInfo.h"
19#include "clang/AST/Mangle.h"
20#include "clang/AST/StmtCXX.h"
21#include "clang/AST/StmtObjC.h"
24#include "llvm/IR/IntrinsicInst.h"
25#include "llvm/IR/Intrinsics.h"
26#include "llvm/IR/IntrinsicsWebAssembly.h"
27#include "llvm/Support/SaveAndRestore.h"
28
29using namespace clang;
30using namespace CodeGen;
31
32static llvm::FunctionCallee getFreeExceptionFn(CodeGenModule &CGM) {
33 // void __cxa_free_exception(void *thrown_exception);
34
35 llvm::FunctionType *FTy =
36 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/false);
37
38 return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
39}
40
41static llvm::FunctionCallee getSehTryBeginFn(CodeGenModule &CGM) {
42 llvm::FunctionType *FTy =
43 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
44 return CGM.CreateRuntimeFunction(FTy, "llvm.seh.try.begin");
45}
46
47static llvm::FunctionCallee getSehTryEndFn(CodeGenModule &CGM) {
48 llvm::FunctionType *FTy =
49 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
50 return CGM.CreateRuntimeFunction(FTy, "llvm.seh.try.end");
51}
52
53static llvm::FunctionCallee getUnexpectedFn(CodeGenModule &CGM) {
54 // void __cxa_call_unexpected(void *thrown_exception);
55
56 llvm::FunctionType *FTy =
57 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/false);
58
59 return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
60}
61
62llvm::FunctionCallee CodeGenModule::getTerminateFn() {
63 // void __terminate();
64
65 llvm::FunctionType *FTy =
66 llvm::FunctionType::get(VoidTy, /*isVarArg=*/false);
67
68 StringRef name;
69
70 // In C++, use std::terminate().
71 if (getLangOpts().CPlusPlus &&
72 getTarget().getCXXABI().isItaniumFamily()) {
73 name = "_ZSt9terminatev";
74 } else if (getLangOpts().CPlusPlus &&
75 getTarget().getCXXABI().isMicrosoft()) {
76 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
77 name = "__std_terminate";
78 else
79 name = "?terminate@@YAXXZ";
80 } else if (getLangOpts().ObjC &&
82 name = "objc_terminate";
83 else
84 name = "abort";
85 return CreateRuntimeFunction(FTy, name);
86}
87
88static llvm::FunctionCallee getCatchallRethrowFn(CodeGenModule &CGM,
89 StringRef Name) {
90 llvm::FunctionType *FTy =
91 llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/false);
92
93 return CGM.CreateRuntimeFunction(FTy, Name);
94}
95
96const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
97const EHPersonality
98EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
99const EHPersonality
100EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr };
101const EHPersonality
102EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
103const EHPersonality
104EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
105const EHPersonality
106EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
107const EHPersonality
108EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr };
109const EHPersonality
110EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
111const EHPersonality
112EHPersonality::GNU_ObjC_SJLJ = {"__gnu_objc_personality_sj0", "objc_exception_throw"};
113const EHPersonality
114EHPersonality::GNU_ObjC_SEH = {"__gnu_objc_personality_seh0", "objc_exception_throw"};
115const EHPersonality
116EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
117const EHPersonality
118EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
119const EHPersonality
120EHPersonality::MSVC_except_handler = { "_except_handler3", nullptr };
121const EHPersonality
122EHPersonality::MSVC_C_specific_handler = { "__C_specific_handler", nullptr };
123const EHPersonality
124EHPersonality::MSVC_CxxFrameHandler3 = { "__CxxFrameHandler3", nullptr };
125const EHPersonality
126EHPersonality::GNU_Wasm_CPlusPlus = { "__gxx_wasm_personality_v0", nullptr };
127const EHPersonality EHPersonality::XL_CPlusPlus = {"__xlcxx_personality_v1",
128 nullptr};
129const EHPersonality EHPersonality::ZOS_CPlusPlus = {"__zos_cxx_personality_v2",
130 nullptr};
131
133 const LangOptions &L) {
134 const llvm::Triple &T = Target.getTriple();
135 if (T.isWindowsMSVCEnvironment())
137 if (L.hasSjLjExceptions())
139 if (L.hasDWARFExceptions())
141 if (L.hasSEHExceptions())
144}
145
147 const LangOptions &L) {
148 const llvm::Triple &T = Target.getTriple();
149 if (T.isWindowsMSVCEnvironment())
151
152 switch (L.ObjCRuntime.getKind()) {
154 return getCPersonality(Target, L);
156 case ObjCRuntime::iOS:
160 if (T.isOSCygMing())
162 else if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
164 [[fallthrough]];
165 case ObjCRuntime::GCC:
167 if (L.hasSjLjExceptions())
169 if (L.hasSEHExceptions())
172 }
173 llvm_unreachable("bad runtime kind");
174}
175
177 const LangOptions &L) {
178 const llvm::Triple &T = Target.getTriple();
179 if (T.isWindowsMSVCEnvironment())
181 if (T.isOSAIX())
183 if (L.hasSjLjExceptions())
185 if (L.hasDWARFExceptions())
187 if (L.hasSEHExceptions())
189 if (L.hasWasmExceptions())
191 if (T.isOSzOS())
194}
195
196/// Determines the personality function to use when both C++
197/// and Objective-C exceptions are being caught.
199 const LangOptions &L) {
200 if (Target.getTriple().isWindowsMSVCEnvironment())
202
203 switch (L.ObjCRuntime.getKind()) {
204 // In the fragile ABI, just use C++ exception handling and hope
205 // they're not doing crazy exception mixing.
207 return getCXXPersonality(Target, L);
208
209 // The ObjC personality defers to the C++ personality for non-ObjC
210 // handlers. Unlike the C++ case, we use the same personality
211 // function on targets using (backend-driven) SJLJ EH.
213 case ObjCRuntime::iOS:
215 return getObjCPersonality(Target, L);
216
218 return Target.getTriple().isOSCygMing() ? EHPersonality::GNU_CPlusPlus_SEH
220
221 // The GCC runtime's personality function inherently doesn't support
222 // mixed EH. Use the ObjC personality just to avoid returning null.
223 case ObjCRuntime::GCC:
225 return getObjCPersonality(Target, L);
226 }
227 llvm_unreachable("bad runtime kind");
228}
229
230static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
231 if (T.getArch() == llvm::Triple::x86)
234}
235
237 const FunctionDecl *FD) {
238 const llvm::Triple &T = CGM.getTarget().getTriple();
239 const LangOptions &L = CGM.getLangOpts();
240 const TargetInfo &Target = CGM.getTarget();
241
242 // Functions using SEH get an SEH personality.
243 if (FD && FD->usesSEHTry())
244 return getSEHPersonalityMSVC(T);
245
246 if (L.ObjC)
247 return L.CPlusPlus ? getObjCXXPersonality(Target, L)
249 return L.CPlusPlus ? getCXXPersonality(Target, L)
251}
252
254 const auto *FD = CGF.CurCodeDecl;
255 // For outlined finallys and filters, use the SEH personality in case they
256 // contain more SEH. This mostly only affects finallys. Filters could
257 // hypothetically use gnu statement expressions to sneak in nested SEH.
258 FD = FD ? FD : CGF.CurSEHParent.getDecl();
259 return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(FD));
260}
261
262static llvm::FunctionCallee getPersonalityFn(CodeGenModule &CGM,
263 const EHPersonality &Personality) {
264 return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
265 Personality.PersonalityFn,
266 llvm::AttributeList(), /*Local=*/true);
267}
268
269static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
270 const EHPersonality &Personality) {
271 llvm::FunctionCallee Fn = getPersonalityFn(CGM, Personality);
272 return cast<llvm::Constant>(Fn.getCallee());
273}
274
275/// Check whether a landingpad instruction only uses C++ features.
276static bool LandingPadHasOnlyCXXUses(llvm::LandingPadInst *LPI) {
277 for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
278 // Look for something that would've been returned by the ObjC
279 // runtime's GetEHType() method.
280 llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
281 if (LPI->isCatch(I)) {
282 // Check if the catch value has the ObjC prefix.
283 if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
284 // ObjC EH selector entries are always global variables with
285 // names starting like this.
286 if (GV->getName().starts_with("OBJC_EHTYPE"))
287 return false;
288 } else {
289 // Check if any of the filter values have the ObjC prefix.
290 llvm::Constant *CVal = cast<llvm::Constant>(Val);
291 for (llvm::User::op_iterator
292 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
293 if (llvm::GlobalVariable *GV =
294 cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
295 // ObjC EH selector entries are always global variables with
296 // names starting like this.
297 if (GV->getName().starts_with("OBJC_EHTYPE"))
298 return false;
299 }
300 }
301 }
302 return true;
303}
304
305/// Check whether a personality function could reasonably be swapped
306/// for a C++ personality function.
307static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
308 for (llvm::User *U : Fn->users()) {
309 // Conditionally white-list bitcasts.
310 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
311 if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
313 return false;
314 continue;
315 }
316
317 // Otherwise it must be a function.
318 llvm::Function *F = dyn_cast<llvm::Function>(U);
319 if (!F) return false;
320
321 for (auto BB = F->begin(), E = F->end(); BB != E; ++BB) {
322 if (BB->isLandingPad())
323 if (!LandingPadHasOnlyCXXUses(BB->getLandingPadInst()))
324 return false;
325 }
326 }
327
328 return true;
329}
330
331/// Try to use the C++ personality function in ObjC++. Not doing this
332/// can cause some incompatibilities with gcc, which is more
333/// aggressive about only using the ObjC++ personality in a function
334/// when it really needs it.
335void CodeGenModule::SimplifyPersonality() {
336 // If we're not in ObjC++ -fexceptions, there's nothing to do.
337 if (!LangOpts.CPlusPlus || !LangOpts.ObjC || !LangOpts.Exceptions)
338 return;
339
340 // Both the problem this endeavors to fix and the way the logic
341 // above works is specific to the NeXT runtime.
342 if (!LangOpts.ObjCRuntime.isNeXTFamily())
343 return;
344
345 const EHPersonality &ObjCXX = EHPersonality::get(*this, /*FD=*/nullptr);
346 const EHPersonality &CXX = getCXXPersonality(getTarget(), LangOpts);
347 if (&ObjCXX == &CXX)
348 return;
349
350 assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
351 "Different EHPersonalities using the same personality function.");
352
353 llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
354
355 // Nothing to do if it's unused.
356 if (!Fn || Fn->use_empty()) return;
357
358 // Can't do the optimization if it has non-C++ uses.
359 if (!PersonalityHasOnlyCXXUses(Fn)) return;
360
361 // Create the C++ personality function and kill off the old
362 // function.
363 llvm::FunctionCallee CXXFn = getPersonalityFn(*this, CXX);
364
365 // This can happen if the user is screwing with us.
366 if (Fn->getType() != CXXFn.getCallee()->getType())
367 return;
368
369 Fn->replaceAllUsesWith(CXXFn.getCallee());
370 Fn->eraseFromParent();
371}
372
373/// Returns the value to inject into a selector to indicate the
374/// presence of a catch-all.
375static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
376 // Possibly we should use @llvm.eh.catch.all.value here.
377 return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
378}
379
380namespace {
381 /// A cleanup to free the exception object if its initialization
382 /// throws.
383 struct FreeException final : EHScopeStack::Cleanup {
384 llvm::Value *exn;
385 FreeException(llvm::Value *exn) : exn(exn) {}
386 void Emit(CodeGenFunction &CGF, Flags flags) override {
388 }
389 };
390} // end anonymous namespace
391
392// Emits an exception expression into the given location. This
393// differs from EmitAnyExprToMem only in that, if a final copy-ctor
394// call is required, an exception within that copy ctor causes
395// std::terminate to be invoked.
397 // Make sure the exception object is cleaned up if there's an
398 // exception during initialization.
399 pushFullExprCleanup<FreeException>(EHCleanup, addr.emitRawPointer(*this));
401
402 // __cxa_allocate_exception returns a void*; we need to cast this
403 // to the appropriate type for the object.
404 llvm::Type *ty = ConvertTypeForMem(e->getType());
405 Address typedAddr = addr.withElementType(ty);
406
407 // FIXME: this isn't quite right! If there's a final unelided call
408 // to a copy constructor, then according to [except.terminate]p1 we
409 // must call std::terminate() if that constructor throws, because
410 // technically that copy occurs after the exception expression is
411 // evaluated but before the exception is caught. But the best way
412 // to handle that is to teach EmitAggExpr to do the final copy
413 // differently if it can't be elided.
414 EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
415 /*IsInit*/ true);
416
417 // Deactivate the cleanup block.
419 cleanup, cast<llvm::Instruction>(typedAddr.emitRawPointer(*this)));
420}
421
423 if (!ExceptionSlot)
426}
427
429 if (!EHSelectorSlot)
430 EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
432}
433
435 return Builder.CreateLoad(getExceptionSlot(), "exn");
436}
437
439 return Builder.CreateLoad(getEHSelectorSlot(), "sel");
440}
441
443 bool KeepInsertionPoint) {
444 // If the exception is being emitted in an OpenMP target region,
445 // and the target is a GPU, we do not support exception handling.
446 // Therefore, we emit a trap which will abort the program, and
447 // prompt a warning indicating that a trap will be emitted.
448 const llvm::Triple &T = Target.getTriple();
449 if (CGM.getLangOpts().OpenMPIsTargetDevice && (T.isNVPTX() || T.isAMDGCN())) {
450 EmitTrapCall(llvm::Intrinsic::trap);
451 return;
452 }
453 if (const Expr *SubExpr = E->getSubExpr()) {
454 QualType ThrowType = SubExpr->getType();
455 if (ThrowType->isObjCObjectPointerType()) {
456 const Stmt *ThrowStmt = E->getSubExpr();
457 const ObjCAtThrowStmt S(E->getExprLoc(), const_cast<Stmt *>(ThrowStmt));
458 CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
459 } else {
460 CGM.getCXXABI().emitThrow(*this, E);
461 }
462 } else {
463 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn=*/true);
464 }
465
466 // throw is an expression, and the expression emitters expect us
467 // to leave ourselves at a valid insertion point.
468 if (KeepInsertionPoint)
469 EmitBlock(createBasicBlock("throw.cont"));
470}
471
473 if (!CGM.getLangOpts().CXXExceptions)
474 return;
475
476 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
477 if (!FD) {
478 // Check if CapturedDecl is nothrow and create terminate scope for it.
479 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
480 if (CD->isNothrow())
482 }
483 return;
484 }
485 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
486 if (!Proto)
487 return;
488
490 // In C++17 and later, 'throw()' aka EST_DynamicNone is treated the same way
491 // as noexcept. In earlier standards, it is handled in this block, along with
492 // 'throw(X...)'.
493 if (EST == EST_Dynamic ||
494 (EST == EST_DynamicNone && !getLangOpts().CPlusPlus17)) {
495 // TODO: Revisit exception specifications for the MS ABI. There is a way to
496 // encode these in an object file but MSVC doesn't do anything with it.
498 return;
499 // In Wasm EH we currently treat 'throw()' in the same way as 'noexcept'. In
500 // case of throw with types, we ignore it and print a warning for now.
501 // TODO Correctly handle exception specification in Wasm EH
503 if (EST == EST_DynamicNone)
505 else
507 diag::warn_wasm_dynamic_exception_spec_ignored)
509 return;
510 }
511 // Currently Emscripten EH only handles 'throw()' but not 'throw' with
512 // types. 'throw()' handling will be done in JS glue code so we don't need
513 // to do anything in that case. Just print a warning message in case of
514 // throw with types.
515 // TODO Correctly handle exception specification in Emscripten EH
516 if (getTarget().getCXXABI() == TargetCXXABI::WebAssembly &&
517 CGM.getLangOpts().getExceptionHandling() ==
519 EST == EST_Dynamic)
521 diag::warn_wasm_dynamic_exception_spec_ignored)
523
524 unsigned NumExceptions = Proto->getNumExceptions();
525 EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
526
527 for (unsigned I = 0; I != NumExceptions; ++I) {
528 QualType Ty = Proto->getExceptionType(I);
530 llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
531 /*ForEH=*/true);
532 Filter->setFilter(I, EHType);
533 }
534 } else if (Proto->canThrow() == CT_Cannot) {
535 // noexcept functions are simple terminate scopes.
536 if (!getLangOpts().EHAsynch) // -EHa: HW exception still can occur
538 }
539}
540
541/// Emit the dispatch block for a filter scope if necessary.
543 EHFilterScope &filterScope) {
544 llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
545 if (!dispatchBlock) return;
546 if (dispatchBlock->use_empty()) {
547 delete dispatchBlock;
548 return;
549 }
550
551 CGF.EmitBlockAfterUses(dispatchBlock);
552
553 // If this isn't a catch-all filter, we need to check whether we got
554 // here because the filter triggered.
555 if (filterScope.getNumFilters()) {
556 // Load the selector value.
557 llvm::Value *selector = CGF.getSelectorFromSlot();
558 llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
559
560 llvm::Value *zero = CGF.Builder.getInt32(0);
561 llvm::Value *failsFilter =
562 CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
563 CGF.Builder.CreateCondBr(failsFilter, unexpectedBB,
564 CGF.getEHResumeBlock(false));
565
566 CGF.EmitBlock(unexpectedBB);
567 }
568
569 // Call __cxa_call_unexpected. This doesn't need to be an invoke
570 // because __cxa_call_unexpected magically filters exceptions
571 // according to the last landing pad the exception was thrown
572 // into. Seriously.
573 llvm::Value *exn = CGF.getExceptionFromSlot();
574 CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
575 ->setDoesNotReturn();
576 CGF.Builder.CreateUnreachable();
577}
578
580 if (!CGM.getLangOpts().CXXExceptions)
581 return;
582
583 const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
584 if (!FD) {
585 // Check if CapturedDecl is nothrow and pop terminate scope for it.
586 if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
587 if (CD->isNothrow() && !EHStack.empty())
589 }
590 return;
591 }
592 const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
593 if (!Proto)
594 return;
595
597 if (EST == EST_Dynamic ||
598 (EST == EST_DynamicNone && !getLangOpts().CPlusPlus17)) {
599 // TODO: Revisit exception specifications for the MS ABI. There is a way to
600 // encode these in an object file but MSVC doesn't do anything with it.
602 return;
603 // In wasm we currently treat 'throw()' in the same way as 'noexcept'. In
604 // case of throw with types, we ignore it and print a warning for now.
605 // TODO Correctly handle exception specification in wasm
607 if (EST == EST_DynamicNone)
609 return;
610 }
611 EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
612 emitFilterDispatchBlock(*this, filterScope);
614 } else if (Proto->canThrow() == CT_Cannot &&
615 /* possible empty when under async exceptions */
616 !EHStack.empty()) {
618 }
619}
620
622 const llvm::Triple &T = Target.getTriple();
623 // If we encounter a try statement on in an OpenMP target region offloaded to
624 // a GPU, we treat it as a basic block.
625 const bool IsTargetDevice =
626 (CGM.getLangOpts().OpenMPIsTargetDevice && (T.isNVPTX() || T.isAMDGCN()));
627 if (!IsTargetDevice)
629 EmitStmt(S.getTryBlock());
630 if (!IsTargetDevice)
632}
633
634void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
635 unsigned NumHandlers = S.getNumHandlers();
636 EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
637
638 for (unsigned I = 0; I != NumHandlers; ++I) {
639 const CXXCatchStmt *C = S.getHandler(I);
640
641 llvm::BasicBlock *Handler = createBasicBlock("catch");
642 if (C->getExceptionDecl()) {
643 // FIXME: Dropping the reference type on the type into makes it
644 // impossible to correctly implement catch-by-reference
645 // semantics for pointers. Unfortunately, this is what all
646 // existing compilers do, and it's not clear that the standard
647 // personality routine is capable of doing this right. See C++ DR 388:
648 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#388
649 Qualifiers CaughtTypeQuals;
651 C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
652
653 CatchTypeInfo TypeInfo{nullptr, 0};
654 if (CaughtType->isObjCObjectPointerType())
655 TypeInfo.RTTI = CGM.getObjCRuntime().GetEHType(CaughtType);
656 else
658 CaughtType, C->getCaughtType());
659 CatchScope->setHandler(I, TypeInfo, Handler);
660 } else {
661 // No exception decl indicates '...', a catch-all.
662 CatchScope->setHandler(I, CGM.getCXXABI().getCatchAllTypeInfo(), Handler);
663 // Under async exceptions, catch(...) need to catch HW exception too
664 // Mark scope with SehTryBegin as a SEH __try scope
665 if (getLangOpts().EHAsynch)
667 }
668 }
669}
670
671llvm::BasicBlock *
674 return getFuncletEHDispatchBlock(si);
675
676 // The dispatch block for the end of the scope chain is a block that
677 // just resumes unwinding.
678 if (si == EHStack.stable_end())
679 return getEHResumeBlock(true);
680
681 // Otherwise, we should look at the actual scope.
682 EHScope &scope = *EHStack.find(si);
683
684 llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
685 if (!dispatchBlock) {
686 switch (scope.getKind()) {
687 case EHScope::Catch: {
688 // Apply a special case to a single catch-all.
689 EHCatchScope &catchScope = cast<EHCatchScope>(scope);
690 if (catchScope.getNumHandlers() == 1 &&
691 catchScope.getHandler(0).isCatchAll()) {
692 dispatchBlock = catchScope.getHandler(0).Block;
693
694 // Otherwise, make a dispatch block.
695 } else {
696 dispatchBlock = createBasicBlock("catch.dispatch");
697 }
698 break;
699 }
700
701 case EHScope::Cleanup:
702 dispatchBlock = createBasicBlock("ehcleanup");
703 break;
704
705 case EHScope::Filter:
706 dispatchBlock = createBasicBlock("filter.dispatch");
707 break;
708
710 dispatchBlock = getTerminateHandler();
711 break;
712 }
713 scope.setCachedEHDispatchBlock(dispatchBlock);
714 }
715 return dispatchBlock;
716}
717
718llvm::BasicBlock *
720 // Returning nullptr indicates that the previous dispatch block should unwind
721 // to caller.
722 if (SI == EHStack.stable_end())
723 return nullptr;
724
725 // Otherwise, we should look at the actual scope.
726 EHScope &EHS = *EHStack.find(SI);
727
728 llvm::BasicBlock *DispatchBlock = EHS.getCachedEHDispatchBlock();
729 if (DispatchBlock)
730 return DispatchBlock;
731
732 if (EHS.getKind() == EHScope::Terminate)
733 DispatchBlock = getTerminateFunclet();
734 else
735 DispatchBlock = createBasicBlock();
736 CGBuilderTy Builder(*this, DispatchBlock);
737
738 switch (EHS.getKind()) {
739 case EHScope::Catch:
740 DispatchBlock->setName("catch.dispatch");
741 break;
742
743 case EHScope::Cleanup:
744 DispatchBlock->setName("ehcleanup");
745 break;
746
747 case EHScope::Filter:
748 llvm_unreachable("exception specifications not handled yet!");
749
751 DispatchBlock->setName("terminate");
752 break;
753 }
754 EHS.setCachedEHDispatchBlock(DispatchBlock);
755 return DispatchBlock;
756}
757
758/// Check whether this is a non-EH scope, i.e. a scope which doesn't
759/// affect exception handling. Currently, the only non-EH scopes are
760/// normal-only cleanup scopes.
761static bool isNonEHScope(const EHScope &S) {
762 switch (S.getKind()) {
763 case EHScope::Cleanup:
764 return !cast<EHCleanupScope>(S).isEHCleanup();
765 case EHScope::Filter:
766 case EHScope::Catch:
768 return false;
769 }
770
771 llvm_unreachable("Invalid EHScope Kind!");
772}
773
774llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
775 assert(EHStack.requiresLandingPad());
776 assert(!EHStack.empty());
777
778 // If exceptions are disabled/ignored and SEH is not in use, then there is no
779 // invoke destination. SEH "works" even if exceptions are off. In practice,
780 // this means that C++ destructors and other EH cleanups don't run, which is
781 // consistent with MSVC's behavior, except in the presence of -EHa
782 const LangOptions &LO = CGM.getLangOpts();
783 if (!LO.Exceptions || LO.IgnoreExceptions) {
784 if (!LO.Borland && !LO.MicrosoftExt)
785 return nullptr;
787 return nullptr;
788 }
789
790 // CUDA device code doesn't have exceptions.
791 if (LO.CUDA && LO.CUDAIsDevice)
792 return nullptr;
793
794 // Check the innermost scope for a cached landing pad. If this is
795 // a non-EH cleanup, we'll check enclosing scopes in EmitLandingPad.
796 llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
797 if (LP) return LP;
798
799 const EHPersonality &Personality = EHPersonality::get(*this);
800
801 if (!CurFn->hasPersonalityFn())
802 CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
803
804 if (Personality.usesFuncletPads()) {
805 // We don't need separate landing pads in the funclet model.
807 } else {
808 // Build the landing pad for this scope.
809 LP = EmitLandingPad();
810 }
811
812 assert(LP);
813
814 // Cache the landing pad on the innermost scope. If this is a
815 // non-EH scope, cache the landing pad on the enclosing scope, too.
816 for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
817 ir->setCachedLandingPad(LP);
818 if (!isNonEHScope(*ir)) break;
819 }
820
821 return LP;
822}
823
824llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
825 assert(EHStack.requiresLandingPad());
826 assert(!CGM.getLangOpts().IgnoreExceptions &&
827 "LandingPad should not be emitted when -fignore-exceptions are in "
828 "effect.");
829 EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
830 switch (innermostEHScope.getKind()) {
832 return getTerminateLandingPad();
833
834 case EHScope::Catch:
835 case EHScope::Cleanup:
836 case EHScope::Filter:
837 if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
838 return lpad;
839 }
840
841 // Save the current IR generation state.
842 CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
843 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
844
845 // Create and configure the landing pad.
846 llvm::BasicBlock *lpad = createBasicBlock("lpad");
847 EmitBlock(lpad);
848
849 llvm::LandingPadInst *LPadInst =
850 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
851
852 llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
854 llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
856
857 // Save the exception pointer. It's safe to use a single exception
858 // pointer per function because EH cleanups can never have nested
859 // try/catches.
860 // Build the landingpad instruction.
861
862 // Accumulate all the handlers in scope.
863 bool hasCatchAll = false;
864 bool hasCleanup = false;
865 bool hasFilter = false;
868 for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
869 ++I) {
870
871 switch (I->getKind()) {
872 case EHScope::Cleanup:
873 // If we have a cleanup, remember that.
874 hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
875 continue;
876
877 case EHScope::Filter: {
878 assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
879 assert(!hasCatchAll && "EH filter reached after catch-all");
880
881 // Filter scopes get added to the landingpad in weird ways.
882 EHFilterScope &filter = cast<EHFilterScope>(*I);
883 hasFilter = true;
884
885 // Add all the filter values.
886 for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
887 filterTypes.push_back(filter.getFilter(i));
888 goto done;
889 }
890
892 // Terminate scopes are basically catch-alls.
893 assert(!hasCatchAll);
894 hasCatchAll = true;
895 goto done;
896
897 case EHScope::Catch:
898 break;
899 }
900
901 EHCatchScope &catchScope = cast<EHCatchScope>(*I);
902 for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
903 EHCatchScope::Handler handler = catchScope.getHandler(hi);
904 assert(handler.Type.Flags == 0 &&
905 "landingpads do not support catch handler flags");
906
907 // If this is a catch-all, register that and abort.
908 if (!handler.Type.RTTI) {
909 assert(!hasCatchAll);
910 hasCatchAll = true;
911 goto done;
912 }
913
914 // Check whether we already have a handler for this type.
915 if (catchTypes.insert(handler.Type.RTTI).second)
916 // If not, add it directly to the landingpad.
917 LPadInst->addClause(handler.Type.RTTI);
918 }
919 }
920
921 done:
922 // If we have a catch-all, add null to the landingpad.
923 assert(!(hasCatchAll && hasFilter));
924 if (hasCatchAll) {
925 LPadInst->addClause(getCatchAllValue(*this));
926
927 // If we have an EH filter, we need to add those handlers in the
928 // right place in the landingpad, which is to say, at the end.
929 } else if (hasFilter) {
930 // Create a filter expression: a constant array indicating which filter
931 // types there are. The personality routine only lands here if the filter
932 // doesn't match.
934 llvm::ArrayType *AType =
935 llvm::ArrayType::get(!filterTypes.empty() ?
936 filterTypes[0]->getType() : Int8PtrTy,
937 filterTypes.size());
938
939 for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
940 Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
941 llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
942 LPadInst->addClause(FilterArray);
943
944 // Also check whether we need a cleanup.
945 if (hasCleanup)
946 LPadInst->setCleanup(true);
947
948 // Otherwise, signal that we at least have cleanups.
949 } else if (hasCleanup) {
950 LPadInst->setCleanup(true);
951 }
952
953 assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
954 "landingpad instruction has no clauses!");
955
956 // Tell the backend how to generate the landing pad.
958
959 // Restore the old IR generation state.
960 Builder.restoreIP(savedIP);
961
962 return lpad;
963}
964
965static void emitCatchPadBlock(CodeGenFunction &CGF, EHCatchScope &CatchScope) {
966 llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
967 assert(DispatchBlock);
968
969 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveIP();
970 CGF.EmitBlockAfterUses(DispatchBlock);
971
972 llvm::Value *ParentPad = CGF.CurrentFuncletPad;
973 if (!ParentPad)
974 ParentPad = llvm::ConstantTokenNone::get(CGF.getLLVMContext());
975 llvm::BasicBlock *UnwindBB =
976 CGF.getEHDispatchBlock(CatchScope.getEnclosingEHScope());
977
978 unsigned NumHandlers = CatchScope.getNumHandlers();
979 llvm::CatchSwitchInst *CatchSwitch =
980 CGF.Builder.CreateCatchSwitch(ParentPad, UnwindBB, NumHandlers);
981
982 // Test against each of the exception types we claim to catch.
983 for (unsigned I = 0; I < NumHandlers; ++I) {
984 const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
985
986 CatchTypeInfo TypeInfo = Handler.Type;
987 if (!TypeInfo.RTTI)
988 TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
989
990 CGF.Builder.SetInsertPoint(Handler.Block);
991
992 if (EHPersonality::get(CGF).isMSVCXXPersonality()) {
993 CGF.Builder.CreateCatchPad(
994 CatchSwitch, {TypeInfo.RTTI, CGF.Builder.getInt32(TypeInfo.Flags),
995 llvm::Constant::getNullValue(CGF.VoidPtrTy)});
996 } else {
997 CGF.Builder.CreateCatchPad(CatchSwitch, {TypeInfo.RTTI});
998 }
999
1000 CatchSwitch->addHandler(Handler.Block);
1001 }
1002 CGF.Builder.restoreIP(SavedIP);
1003}
1004
1005// Wasm uses Windows-style EH instructions, but it merges all catch clauses into
1006// one big catchpad, within which we use Itanium's landingpad-style selector
1007// comparison instructions.
1009 EHCatchScope &CatchScope) {
1010 llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
1011 assert(DispatchBlock);
1012
1013 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveIP();
1014 CGF.EmitBlockAfterUses(DispatchBlock);
1015
1016 llvm::Value *ParentPad = CGF.CurrentFuncletPad;
1017 if (!ParentPad)
1018 ParentPad = llvm::ConstantTokenNone::get(CGF.getLLVMContext());
1019 llvm::BasicBlock *UnwindBB =
1020 CGF.getEHDispatchBlock(CatchScope.getEnclosingEHScope());
1021
1022 unsigned NumHandlers = CatchScope.getNumHandlers();
1023 llvm::CatchSwitchInst *CatchSwitch =
1024 CGF.Builder.CreateCatchSwitch(ParentPad, UnwindBB, NumHandlers);
1025
1026 // We don't use a landingpad instruction, so generate intrinsic calls to
1027 // provide exception and selector values.
1028 llvm::BasicBlock *WasmCatchStartBlock = CGF.createBasicBlock("catch.start");
1029 CatchSwitch->addHandler(WasmCatchStartBlock);
1030 CGF.EmitBlockAfterUses(WasmCatchStartBlock);
1031
1032 // Create a catchpad instruction.
1034 for (unsigned I = 0, E = NumHandlers; I < E; ++I) {
1035 const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
1036 CatchTypeInfo TypeInfo = Handler.Type;
1037 if (!TypeInfo.RTTI)
1038 TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
1039 CatchTypes.push_back(TypeInfo.RTTI);
1040 }
1041 auto *CPI = CGF.Builder.CreateCatchPad(CatchSwitch, CatchTypes);
1042
1043 // Create calls to wasm.get.exception and wasm.get.ehselector intrinsics.
1044 // Before they are lowered appropriately later, they provide values for the
1045 // exception and selector.
1046 llvm::Function *GetExnFn =
1047 CGF.CGM.getIntrinsic(llvm::Intrinsic::wasm_get_exception);
1048 llvm::Function *GetSelectorFn =
1049 CGF.CGM.getIntrinsic(llvm::Intrinsic::wasm_get_ehselector);
1050 llvm::CallInst *Exn = CGF.Builder.CreateCall(GetExnFn, CPI);
1051 CGF.Builder.CreateStore(Exn, CGF.getExceptionSlot());
1052 llvm::CallInst *Selector = CGF.Builder.CreateCall(GetSelectorFn, CPI);
1053
1054 llvm::Function *TypeIDFn =
1055 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for, {CGF.VoidPtrTy});
1056
1057 // If there's only a single catch-all, branch directly to its handler.
1058 if (CatchScope.getNumHandlers() == 1 &&
1059 CatchScope.getHandler(0).isCatchAll()) {
1060 CGF.Builder.CreateBr(CatchScope.getHandler(0).Block);
1061 CGF.Builder.restoreIP(SavedIP);
1062 return;
1063 }
1064
1065 // Test against each of the exception types we claim to catch.
1066 for (unsigned I = 0, E = NumHandlers;; ++I) {
1067 assert(I < E && "ran off end of handlers!");
1068 const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
1069 CatchTypeInfo TypeInfo = Handler.Type;
1070 if (!TypeInfo.RTTI)
1071 TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
1072
1073 // Figure out the next block.
1074 llvm::BasicBlock *NextBlock;
1075
1076 bool EmitNextBlock = false, NextIsEnd = false;
1077
1078 // If this is the last handler, we're at the end, and the next block is a
1079 // block that contains a call to the rethrow function, so we can unwind to
1080 // the enclosing EH scope. The call itself will be generated later.
1081 if (I + 1 == E) {
1082 NextBlock = CGF.createBasicBlock("rethrow");
1083 EmitNextBlock = true;
1084 NextIsEnd = true;
1085
1086 // If the next handler is a catch-all, we're at the end, and the
1087 // next block is that handler.
1088 } else if (CatchScope.getHandler(I + 1).isCatchAll()) {
1089 NextBlock = CatchScope.getHandler(I + 1).Block;
1090 NextIsEnd = true;
1091
1092 // Otherwise, we're not at the end and we need a new block.
1093 } else {
1094 NextBlock = CGF.createBasicBlock("catch.fallthrough");
1095 EmitNextBlock = true;
1096 }
1097
1098 // Figure out the catch type's index in the LSDA's type table.
1099 llvm::CallInst *TypeIndex = CGF.Builder.CreateCall(TypeIDFn, TypeInfo.RTTI);
1100 TypeIndex->setDoesNotThrow();
1101
1102 llvm::Value *MatchesTypeIndex =
1103 CGF.Builder.CreateICmpEQ(Selector, TypeIndex, "matches");
1104 CGF.Builder.CreateCondBr(MatchesTypeIndex, Handler.Block, NextBlock);
1105
1106 if (EmitNextBlock)
1107 CGF.EmitBlock(NextBlock);
1108 if (NextIsEnd)
1109 break;
1110 }
1111
1112 CGF.Builder.restoreIP(SavedIP);
1113}
1114
1115/// Emit the structure of the dispatch block for the given catch scope.
1116/// It is an invariant that the dispatch block already exists.
1118 EHCatchScope &catchScope) {
1119 if (EHPersonality::get(CGF).isWasmPersonality())
1120 return emitWasmCatchPadBlock(CGF, catchScope);
1121 if (EHPersonality::get(CGF).usesFuncletPads())
1122 return emitCatchPadBlock(CGF, catchScope);
1123
1124 llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
1125 assert(dispatchBlock);
1126
1127 // If there's only a single catch-all, getEHDispatchBlock returned
1128 // that catch-all as the dispatch block.
1129 if (catchScope.getNumHandlers() == 1 &&
1130 catchScope.getHandler(0).isCatchAll()) {
1131 assert(dispatchBlock == catchScope.getHandler(0).Block);
1132 return;
1133 }
1134
1135 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
1136 CGF.EmitBlockAfterUses(dispatchBlock);
1137
1138 // Select the right handler.
1139 llvm::Function *llvm_eh_typeid_for =
1140 CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for, {CGF.VoidPtrTy});
1141 llvm::Type *argTy = llvm_eh_typeid_for->getArg(0)->getType();
1142 LangAS globAS = CGF.CGM.GetGlobalVarAddressSpace(nullptr);
1143
1144 // Load the selector value.
1145 llvm::Value *selector = CGF.getSelectorFromSlot();
1146
1147 // Test against each of the exception types we claim to catch.
1148 for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
1149 assert(i < e && "ran off end of handlers!");
1150 const EHCatchScope::Handler &handler = catchScope.getHandler(i);
1151
1152 llvm::Value *typeValue = handler.Type.RTTI;
1153 assert(handler.Type.Flags == 0 &&
1154 "landingpads do not support catch handler flags");
1155 assert(typeValue && "fell into catch-all case!");
1156 // With opaque ptrs, only the address space can be a mismatch.
1157 if (typeValue->getType() != argTy)
1158 typeValue =
1159 CGF.getTargetHooks().performAddrSpaceCast(CGF, typeValue, globAS,
1160 LangAS::Default, argTy);
1161
1162 // Figure out the next block.
1163 bool nextIsEnd;
1164 llvm::BasicBlock *nextBlock;
1165
1166 // If this is the last handler, we're at the end, and the next
1167 // block is the block for the enclosing EH scope.
1168 if (i + 1 == e) {
1169 nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
1170 nextIsEnd = true;
1171
1172 // If the next handler is a catch-all, we're at the end, and the
1173 // next block is that handler.
1174 } else if (catchScope.getHandler(i+1).isCatchAll()) {
1175 nextBlock = catchScope.getHandler(i+1).Block;
1176 nextIsEnd = true;
1177
1178 // Otherwise, we're not at the end and we need a new block.
1179 } else {
1180 nextBlock = CGF.createBasicBlock("catch.fallthrough");
1181 nextIsEnd = false;
1182 }
1183
1184 // Figure out the catch type's index in the LSDA's type table.
1185 llvm::CallInst *typeIndex =
1186 CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
1187 typeIndex->setDoesNotThrow();
1188
1189 llvm::Value *matchesTypeIndex =
1190 CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
1191 CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
1192
1193 // If the next handler is a catch-all, we're completely done.
1194 if (nextIsEnd) {
1195 CGF.Builder.restoreIP(savedIP);
1196 return;
1197 }
1198 // Otherwise we need to emit and continue at that block.
1199 CGF.EmitBlock(nextBlock);
1200 }
1201}
1202
1204 EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
1205 if (catchScope.hasEHBranches())
1206 emitCatchDispatchBlock(*this, catchScope);
1207 EHStack.popCatch();
1208}
1209
1210void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
1211 unsigned NumHandlers = S.getNumHandlers();
1212 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
1213 assert(CatchScope.getNumHandlers() == NumHandlers);
1214 llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
1215
1216 // If the catch was not required, bail out now.
1217 if (!CatchScope.hasEHBranches()) {
1218 CatchScope.clearHandlerBlocks();
1219 EHStack.popCatch();
1220 return;
1221 }
1222
1223 // Emit the structure of the EH dispatch for this catch.
1224 emitCatchDispatchBlock(*this, CatchScope);
1225
1226 // Copy the handler blocks off before we pop the EH stack. Emitting
1227 // the handlers might scribble on this memory.
1229 CatchScope.begin(), CatchScope.begin() + NumHandlers);
1230
1231 EHStack.popCatch();
1232
1233 // The fall-through block.
1234 llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
1235
1236 // We just emitted the body of the try; jump to the continue block.
1237 if (HaveInsertPoint())
1238 Builder.CreateBr(ContBB);
1239
1240 // Determine if we need an implicit rethrow for all these catch handlers;
1241 // see the comment below.
1242 bool doImplicitRethrow = false;
1243 if (IsFnTryBlock)
1244 doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
1245 isa<CXXConstructorDecl>(CurCodeDecl);
1246
1247 // Wasm uses Windows-style EH instructions, but merges all catch clauses into
1248 // one big catchpad. So we save the old funclet pad here before we traverse
1249 // each catch handler.
1250 SaveAndRestore RestoreCurrentFuncletPad(CurrentFuncletPad);
1251 llvm::BasicBlock *WasmCatchStartBlock = nullptr;
1253 auto *CatchSwitch =
1254 cast<llvm::CatchSwitchInst>(DispatchBlock->getFirstNonPHI());
1255 WasmCatchStartBlock = CatchSwitch->hasUnwindDest()
1256 ? CatchSwitch->getSuccessor(1)
1257 : CatchSwitch->getSuccessor(0);
1258 auto *CPI = cast<llvm::CatchPadInst>(WasmCatchStartBlock->getFirstNonPHI());
1259 CurrentFuncletPad = CPI;
1260 }
1261
1262 // Perversely, we emit the handlers backwards precisely because we
1263 // want them to appear in source order. In all of these cases, the
1264 // catch block will have exactly one predecessor, which will be a
1265 // particular block in the catch dispatch. However, in the case of
1266 // a catch-all, one of the dispatch blocks will branch to two
1267 // different handlers, and EmitBlockAfterUses will cause the second
1268 // handler to be moved before the first.
1269 bool HasCatchAll = false;
1270 for (unsigned I = NumHandlers; I != 0; --I) {
1271 HasCatchAll |= Handlers[I - 1].isCatchAll();
1272 llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
1273 EmitBlockAfterUses(CatchBlock);
1274
1275 // Catch the exception if this isn't a catch-all.
1276 const CXXCatchStmt *C = S.getHandler(I-1);
1277
1278 // Enter a cleanup scope, including the catch variable and the
1279 // end-catch.
1280 RunCleanupsScope CatchScope(*this);
1281
1282 // Initialize the catch variable and set up the cleanups.
1283 SaveAndRestore RestoreCurrentFuncletPad(CurrentFuncletPad);
1284 CGM.getCXXABI().emitBeginCatch(*this, C);
1285
1286 // Emit the PGO counter increment.
1288
1289 // Perform the body of the catch.
1290 EmitStmt(C->getHandlerBlock());
1291
1292 // [except.handle]p11:
1293 // The currently handled exception is rethrown if control
1294 // reaches the end of a handler of the function-try-block of a
1295 // constructor or destructor.
1296
1297 // It is important that we only do this on fallthrough and not on
1298 // return. Note that it's illegal to put a return in a
1299 // constructor function-try-block's catch handler (p14), so this
1300 // really only applies to destructors.
1301 if (doImplicitRethrow && HaveInsertPoint()) {
1302 CGM.getCXXABI().emitRethrow(*this, /*isNoReturn*/false);
1303 Builder.CreateUnreachable();
1304 Builder.ClearInsertionPoint();
1305 }
1306
1307 // Fall out through the catch cleanups.
1308 CatchScope.ForceCleanup();
1309
1310 // Branch out of the try.
1311 if (HaveInsertPoint())
1312 Builder.CreateBr(ContBB);
1313 }
1314
1315 // Because in wasm we merge all catch clauses into one big catchpad, in case
1316 // none of the types in catch handlers matches after we test against each of
1317 // them, we should unwind to the next EH enclosing scope. We generate a call
1318 // to rethrow function here to do that.
1319 if (EHPersonality::get(*this).isWasmPersonality() && !HasCatchAll) {
1320 assert(WasmCatchStartBlock);
1321 // Navigate for the "rethrow" block we created in emitWasmCatchPadBlock().
1322 // Wasm uses landingpad-style conditional branches to compare selectors, so
1323 // we follow the false destination for each of the cond branches to reach
1324 // the rethrow block.
1325 llvm::BasicBlock *RethrowBlock = WasmCatchStartBlock;
1326 while (llvm::Instruction *TI = RethrowBlock->getTerminator()) {
1327 auto *BI = cast<llvm::BranchInst>(TI);
1328 assert(BI->isConditional());
1329 RethrowBlock = BI->getSuccessor(1);
1330 }
1331 assert(RethrowBlock != WasmCatchStartBlock && RethrowBlock->empty());
1332 Builder.SetInsertPoint(RethrowBlock);
1333 llvm::Function *RethrowInCatchFn =
1334 CGM.getIntrinsic(llvm::Intrinsic::wasm_rethrow);
1335 EmitNoreturnRuntimeCallOrInvoke(RethrowInCatchFn, {});
1336 }
1337
1338 EmitBlock(ContBB);
1340}
1341
1342namespace {
1343 struct CallEndCatchForFinally final : EHScopeStack::Cleanup {
1344 llvm::Value *ForEHVar;
1345 llvm::FunctionCallee EndCatchFn;
1346 CallEndCatchForFinally(llvm::Value *ForEHVar,
1347 llvm::FunctionCallee EndCatchFn)
1348 : ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
1349
1350 void Emit(CodeGenFunction &CGF, Flags flags) override {
1351 llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
1352 llvm::BasicBlock *CleanupContBB =
1353 CGF.createBasicBlock("finally.cleanup.cont");
1354
1355 llvm::Value *ShouldEndCatch =
1356 CGF.Builder.CreateFlagLoad(ForEHVar, "finally.endcatch");
1357 CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
1358 CGF.EmitBlock(EndCatchBB);
1359 CGF.EmitRuntimeCallOrInvoke(EndCatchFn); // catch-all, so might throw
1360 CGF.EmitBlock(CleanupContBB);
1361 }
1362 };
1363
1364 struct PerformFinally final : EHScopeStack::Cleanup {
1365 const Stmt *Body;
1366 llvm::Value *ForEHVar;
1367 llvm::FunctionCallee EndCatchFn;
1368 llvm::FunctionCallee RethrowFn;
1369 llvm::Value *SavedExnVar;
1370
1371 PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
1372 llvm::FunctionCallee EndCatchFn,
1373 llvm::FunctionCallee RethrowFn, llvm::Value *SavedExnVar)
1374 : Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
1375 RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
1376
1377 void Emit(CodeGenFunction &CGF, Flags flags) override {
1378 // Enter a cleanup to call the end-catch function if one was provided.
1379 if (EndCatchFn)
1380 CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
1381 ForEHVar, EndCatchFn);
1382
1383 // Save the current cleanup destination in case there are
1384 // cleanups in the finally block.
1385 llvm::Value *SavedCleanupDest =
1387 "cleanup.dest.saved");
1388
1389 // Emit the finally block.
1390 CGF.EmitStmt(Body);
1391
1392 // If the end of the finally is reachable, check whether this was
1393 // for EH. If so, rethrow.
1394 if (CGF.HaveInsertPoint()) {
1395 llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
1396 llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
1397
1398 llvm::Value *ShouldRethrow =
1399 CGF.Builder.CreateFlagLoad(ForEHVar, "finally.shouldthrow");
1400 CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
1401
1402 CGF.EmitBlock(RethrowBB);
1403 if (SavedExnVar) {
1404 CGF.EmitRuntimeCallOrInvoke(RethrowFn,
1405 CGF.Builder.CreateAlignedLoad(CGF.Int8PtrTy, SavedExnVar,
1406 CGF.getPointerAlign()));
1407 } else {
1408 CGF.EmitRuntimeCallOrInvoke(RethrowFn);
1409 }
1410 CGF.Builder.CreateUnreachable();
1411
1412 CGF.EmitBlock(ContBB);
1413
1414 // Restore the cleanup destination.
1415 CGF.Builder.CreateStore(SavedCleanupDest,
1417 }
1418
1419 // Leave the end-catch cleanup. As an optimization, pretend that
1420 // the fallthrough path was inaccessible; we've dynamically proven
1421 // that we're not in the EH case along that path.
1422 if (EndCatchFn) {
1423 CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
1424 CGF.PopCleanupBlock();
1425 CGF.Builder.restoreIP(SavedIP);
1426 }
1427
1428 // Now make sure we actually have an insertion point or the
1429 // cleanup gods will hate us.
1430 CGF.EnsureInsertPoint();
1431 }
1432 };
1433} // end anonymous namespace
1434
1435/// Enters a finally block for an implementation using zero-cost
1436/// exceptions. This is mostly general, but hard-codes some
1437/// language/ABI-specific behavior in the catch-all sections.
1439 llvm::FunctionCallee beginCatchFn,
1440 llvm::FunctionCallee endCatchFn,
1441 llvm::FunctionCallee rethrowFn) {
1442 assert((!!beginCatchFn) == (!!endCatchFn) &&
1443 "begin/end catch functions not paired");
1444 assert(rethrowFn && "rethrow function is required");
1445
1446 BeginCatchFn = beginCatchFn;
1447
1448 // The rethrow function has one of the following two types:
1449 // void (*)()
1450 // void (*)(void*)
1451 // In the latter case we need to pass it the exception object.
1452 // But we can't use the exception slot because the @finally might
1453 // have a landing pad (which would overwrite the exception slot).
1454 llvm::FunctionType *rethrowFnTy = rethrowFn.getFunctionType();
1455 SavedExnVar = nullptr;
1456 if (rethrowFnTy->getNumParams())
1457 SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
1458
1459 // A finally block is a statement which must be executed on any edge
1460 // out of a given scope. Unlike a cleanup, the finally block may
1461 // contain arbitrary control flow leading out of itself. In
1462 // addition, finally blocks should always be executed, even if there
1463 // are no catch handlers higher on the stack. Therefore, we
1464 // surround the protected scope with a combination of a normal
1465 // cleanup (to catch attempts to break out of the block via normal
1466 // control flow) and an EH catch-all (semantically "outside" any try
1467 // statement to which the finally block might have been attached).
1468 // The finally block itself is generated in the context of a cleanup
1469 // which conditionally leaves the catch-all.
1470
1471 // Jump destination for performing the finally block on an exception
1472 // edge. We'll never actually reach this block, so unreachable is
1473 // fine.
1474 RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
1475
1476 // Whether the finally block is being executed for EH purposes.
1477 ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
1478 CGF.Builder.CreateFlagStore(false, ForEHVar);
1479
1480 // Enter a normal cleanup which will perform the @finally block.
1481 CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
1482 ForEHVar, endCatchFn,
1483 rethrowFn, SavedExnVar);
1484
1485 // Enter a catch-all scope.
1486 llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
1487 EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
1488 catchScope->setCatchAllHandler(0, catchBB);
1489}
1490
1492 // Leave the finally catch-all.
1493 EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
1494 llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
1495
1496 CGF.popCatchScope();
1497
1498 // If there are any references to the catch-all block, emit it.
1499 if (catchBB->use_empty()) {
1500 delete catchBB;
1501 } else {
1502 CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
1503 CGF.EmitBlock(catchBB);
1504
1505 llvm::Value *exn = nullptr;
1506
1507 // If there's a begin-catch function, call it.
1508 if (BeginCatchFn) {
1509 exn = CGF.getExceptionFromSlot();
1510 CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
1511 }
1512
1513 // If we need to remember the exception pointer to rethrow later, do so.
1514 if (SavedExnVar) {
1515 if (!exn) exn = CGF.getExceptionFromSlot();
1516 CGF.Builder.CreateAlignedStore(exn, SavedExnVar, CGF.getPointerAlign());
1517 }
1518
1519 // Tell the cleanups in the finally block that we're do this for EH.
1520 CGF.Builder.CreateFlagStore(true, ForEHVar);
1521
1522 // Thread a jump through the finally cleanup.
1523 CGF.EmitBranchThroughCleanup(RethrowDest);
1524
1525 CGF.Builder.restoreIP(savedIP);
1526 }
1527
1528 // Finally, leave the @finally cleanup.
1529 CGF.PopCleanupBlock();
1530}
1531
1532llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
1533 if (TerminateLandingPad)
1534 return TerminateLandingPad;
1535
1536 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1537
1538 // This will get inserted at the end of the function.
1539 TerminateLandingPad = createBasicBlock("terminate.lpad");
1540 Builder.SetInsertPoint(TerminateLandingPad);
1541
1542 // Tell the backend that this is a landing pad.
1543 const EHPersonality &Personality = EHPersonality::get(*this);
1544
1545 if (!CurFn->hasPersonalityFn())
1546 CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
1547
1548 llvm::LandingPadInst *LPadInst =
1549 Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
1550 LPadInst->addClause(getCatchAllValue(*this));
1551
1552 llvm::Value *Exn = nullptr;
1553 if (getLangOpts().CPlusPlus)
1554 Exn = Builder.CreateExtractValue(LPadInst, 0);
1555 llvm::CallInst *terminateCall =
1557 terminateCall->setDoesNotReturn();
1558 Builder.CreateUnreachable();
1559
1560 // Restore the saved insertion state.
1561 Builder.restoreIP(SavedIP);
1562
1563 return TerminateLandingPad;
1564}
1565
1566llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
1567 if (TerminateHandler)
1568 return TerminateHandler;
1569
1570 // Set up the terminate handler. This block is inserted at the very
1571 // end of the function by FinishFunction.
1572 TerminateHandler = createBasicBlock("terminate.handler");
1573 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1574 Builder.SetInsertPoint(TerminateHandler);
1575
1576 llvm::Value *Exn = nullptr;
1577 if (getLangOpts().CPlusPlus)
1578 Exn = getExceptionFromSlot();
1579 llvm::CallInst *terminateCall =
1581 terminateCall->setDoesNotReturn();
1582 Builder.CreateUnreachable();
1583
1584 // Restore the saved insertion state.
1585 Builder.restoreIP(SavedIP);
1586
1587 return TerminateHandler;
1588}
1589
1590llvm::BasicBlock *CodeGenFunction::getTerminateFunclet() {
1591 assert(EHPersonality::get(*this).usesFuncletPads() &&
1592 "use getTerminateLandingPad for non-funclet EH");
1593
1594 llvm::BasicBlock *&TerminateFunclet = TerminateFunclets[CurrentFuncletPad];
1595 if (TerminateFunclet)
1596 return TerminateFunclet;
1597
1598 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1599
1600 // Set up the terminate handler. This block is inserted at the very
1601 // end of the function by FinishFunction.
1602 TerminateFunclet = createBasicBlock("terminate.handler");
1603 Builder.SetInsertPoint(TerminateFunclet);
1604
1605 // Create the cleanuppad using the current parent pad as its token. Use 'none'
1606 // if this is a top-level terminate scope, which is the common case.
1607 SaveAndRestore RestoreCurrentFuncletPad(CurrentFuncletPad);
1608 llvm::Value *ParentPad = CurrentFuncletPad;
1609 if (!ParentPad)
1610 ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
1611 CurrentFuncletPad = Builder.CreateCleanupPad(ParentPad);
1612
1613 // Emit the __std_terminate call.
1614 llvm::CallInst *terminateCall =
1616 terminateCall->setDoesNotReturn();
1617 Builder.CreateUnreachable();
1618
1619 // Restore the saved insertion state.
1620 Builder.restoreIP(SavedIP);
1621
1622 return TerminateFunclet;
1623}
1624
1625llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
1626 if (EHResumeBlock) return EHResumeBlock;
1627
1628 CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
1629
1630 // We emit a jump to a notional label at the outermost unwind state.
1631 EHResumeBlock = createBasicBlock("eh.resume");
1632 Builder.SetInsertPoint(EHResumeBlock);
1633
1634 const EHPersonality &Personality = EHPersonality::get(*this);
1635
1636 // This can always be a call because we necessarily didn't find
1637 // anything on the EH stack which needs our help.
1638 const char *RethrowName = Personality.CatchallRethrowFn;
1639 if (RethrowName != nullptr && !isCleanup) {
1641 getExceptionFromSlot())->setDoesNotReturn();
1642 Builder.CreateUnreachable();
1643 Builder.restoreIP(SavedIP);
1644 return EHResumeBlock;
1645 }
1646
1647 // Recreate the landingpad's return value for the 'resume' instruction.
1648 llvm::Value *Exn = getExceptionFromSlot();
1649 llvm::Value *Sel = getSelectorFromSlot();
1650
1651 llvm::Type *LPadType = llvm::StructType::get(Exn->getType(), Sel->getType());
1652 llvm::Value *LPadVal = llvm::PoisonValue::get(LPadType);
1653 LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
1654 LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
1655
1656 Builder.CreateResume(LPadVal);
1657 Builder.restoreIP(SavedIP);
1658 return EHResumeBlock;
1659}
1660
1662 EnterSEHTryStmt(S);
1663 {
1664 JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
1665
1666 SEHTryEpilogueStack.push_back(&TryExit);
1667
1668 llvm::BasicBlock *TryBB = nullptr;
1669 // IsEHa: emit an invoke to _seh_try_begin() runtime for -EHa
1670 if (getLangOpts().EHAsynch) {
1672 if (SEHTryEpilogueStack.size() == 1) // outermost only
1673 TryBB = Builder.GetInsertBlock();
1674 }
1675
1676 EmitStmt(S.getTryBlock());
1677
1678 // Volatilize all blocks in Try, till current insert point
1679 if (TryBB) {
1682 }
1683
1684 SEHTryEpilogueStack.pop_back();
1685
1686 if (!TryExit.getBlock()->use_empty())
1687 EmitBlock(TryExit.getBlock(), /*IsFinished=*/true);
1688 else
1689 delete TryExit.getBlock();
1690 }
1691 ExitSEHTryStmt(S);
1692}
1693
1694// Recursively walk through blocks in a _try
1695// and make all memory instructions volatile
1697 llvm::BasicBlock *BB, llvm::SmallPtrSet<llvm::BasicBlock *, 10> &V) {
1698 if (BB == SEHTryEpilogueStack.back()->getBlock() /* end of Try */ ||
1699 !V.insert(BB).second /* already visited */ ||
1700 !BB->getParent() /* not emitted */ || BB->empty())
1701 return;
1702
1703 if (!BB->isEHPad()) {
1704 for (llvm::BasicBlock::iterator J = BB->begin(), JE = BB->end(); J != JE;
1705 ++J) {
1706 if (auto LI = dyn_cast<llvm::LoadInst>(J)) {
1707 LI->setVolatile(true);
1708 } else if (auto SI = dyn_cast<llvm::StoreInst>(J)) {
1709 SI->setVolatile(true);
1710 } else if (auto* MCI = dyn_cast<llvm::MemIntrinsic>(J)) {
1711 MCI->setVolatile(llvm::ConstantInt::get(Builder.getInt1Ty(), 1));
1712 }
1713 }
1714 }
1715 const llvm::Instruction *TI = BB->getTerminator();
1716 if (TI) {
1717 unsigned N = TI->getNumSuccessors();
1718 for (unsigned I = 0; I < N; I++)
1719 VolatilizeTryBlocks(TI->getSuccessor(I), V);
1720 }
1721}
1722
1723namespace {
1724struct PerformSEHFinally final : EHScopeStack::Cleanup {
1725 llvm::Function *OutlinedFinally;
1726 PerformSEHFinally(llvm::Function *OutlinedFinally)
1727 : OutlinedFinally(OutlinedFinally) {}
1728
1729 void Emit(CodeGenFunction &CGF, Flags F) override {
1730 ASTContext &Context = CGF.getContext();
1731 CodeGenModule &CGM = CGF.CGM;
1732
1733 CallArgList Args;
1734
1735 // Compute the two argument values.
1736 QualType ArgTys[2] = {Context.UnsignedCharTy, Context.VoidPtrTy};
1737 llvm::Value *FP = nullptr;
1738 // If CFG.IsOutlinedSEHHelper is true, then we are within a finally block.
1739 if (CGF.IsOutlinedSEHHelper) {
1740 FP = &CGF.CurFn->arg_begin()[1];
1741 } else {
1742 llvm::Function *LocalAddrFn =
1743 CGM.getIntrinsic(llvm::Intrinsic::localaddress);
1744 FP = CGF.Builder.CreateCall(LocalAddrFn);
1745 }
1746
1747 llvm::Value *IsForEH =
1748 llvm::ConstantInt::get(CGF.ConvertType(ArgTys[0]), F.isForEHCleanup());
1749
1750 // Except _leave and fall-through at the end, all other exits in a _try
1751 // (return/goto/continue/break) are considered as abnormal terminations
1752 // since _leave/fall-through is always Indexed 0,
1753 // just use NormalCleanupDestSlot (>= 1 for goto/return/..),
1754 // as 1st Arg to indicate abnormal termination
1755 if (!F.isForEHCleanup() && F.hasExitSwitch()) {
1756 Address Addr = CGF.getNormalCleanupDestSlot();
1757 llvm::Value *Load = CGF.Builder.CreateLoad(Addr, "cleanup.dest");
1758 llvm::Value *Zero = llvm::Constant::getNullValue(CGM.Int32Ty);
1759 IsForEH = CGF.Builder.CreateICmpNE(Load, Zero);
1760 }
1761
1762 Args.add(RValue::get(IsForEH), ArgTys[0]);
1763 Args.add(RValue::get(FP), ArgTys[1]);
1764
1765 // Arrange a two-arg function info and type.
1766 const CGFunctionInfo &FnInfo =
1767 CGM.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, Args);
1768
1769 auto Callee = CGCallee::forDirect(OutlinedFinally);
1770 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
1771 }
1772};
1773} // end anonymous namespace
1774
1775namespace {
1776/// Find all local variable captures in the statement.
1777struct CaptureFinder : ConstStmtVisitor<CaptureFinder> {
1778 CodeGenFunction &ParentCGF;
1779 const VarDecl *ParentThis;
1781 Address SEHCodeSlot = Address::invalid();
1782 CaptureFinder(CodeGenFunction &ParentCGF, const VarDecl *ParentThis)
1783 : ParentCGF(ParentCGF), ParentThis(ParentThis) {}
1784
1785 // Return true if we need to do any capturing work.
1786 bool foundCaptures() {
1787 return !Captures.empty() || SEHCodeSlot.isValid();
1788 }
1789
1790 void Visit(const Stmt *S) {
1791 // See if this is a capture, then recurse.
1793 for (const Stmt *Child : S->children())
1794 if (Child)
1795 Visit(Child);
1796 }
1797
1798 void VisitDeclRefExpr(const DeclRefExpr *E) {
1799 // If this is already a capture, just make sure we capture 'this'.
1800 if (E->refersToEnclosingVariableOrCapture())
1801 Captures.insert(ParentThis);
1802
1803 const auto *D = dyn_cast<VarDecl>(E->getDecl());
1804 if (D && D->isLocalVarDeclOrParm() && D->hasLocalStorage())
1805 Captures.insert(D);
1806 }
1807
1808 void VisitCXXThisExpr(const CXXThisExpr *E) {
1809 Captures.insert(ParentThis);
1810 }
1811
1812 void VisitCallExpr(const CallExpr *E) {
1813 // We only need to add parent frame allocations for these builtins in x86.
1814 if (ParentCGF.getTarget().getTriple().getArch() != llvm::Triple::x86)
1815 return;
1816
1817 unsigned ID = E->getBuiltinCallee();
1818 switch (ID) {
1819 case Builtin::BI__exception_code:
1820 case Builtin::BI_exception_code:
1821 // This is the simple case where we are the outermost finally. All we
1822 // have to do here is make sure we escape this and recover it in the
1823 // outlined handler.
1824 if (!SEHCodeSlot.isValid())
1825 SEHCodeSlot = ParentCGF.SEHCodeSlotStack.back();
1826 break;
1827 }
1828 }
1829};
1830} // end anonymous namespace
1831
1833 Address ParentVar,
1834 llvm::Value *ParentFP) {
1835 llvm::CallInst *RecoverCall = nullptr;
1837 if (auto *ParentAlloca =
1838 dyn_cast_or_null<llvm::AllocaInst>(ParentVar.getBasePointer())) {
1839 // Mark the variable escaped if nobody else referenced it and compute the
1840 // localescape index.
1841 auto InsertPair = ParentCGF.EscapedLocals.insert(
1842 std::make_pair(ParentAlloca, ParentCGF.EscapedLocals.size()));
1843 int FrameEscapeIdx = InsertPair.first->second;
1844 // call ptr @llvm.localrecover(ptr @parentFn, ptr %fp, i32 N)
1845 llvm::Function *FrameRecoverFn = llvm::Intrinsic::getOrInsertDeclaration(
1846 &CGM.getModule(), llvm::Intrinsic::localrecover);
1847 RecoverCall = Builder.CreateCall(
1848 FrameRecoverFn, {ParentCGF.CurFn, ParentFP,
1849 llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)});
1850
1851 } else {
1852 // If the parent didn't have an alloca, we're doing some nested outlining.
1853 // Just clone the existing localrecover call, but tweak the FP argument to
1854 // use our FP value. All other arguments are constants.
1855 auto *ParentRecover = cast<llvm::IntrinsicInst>(
1856 ParentVar.emitRawPointer(*this)->stripPointerCasts());
1857 assert(ParentRecover->getIntrinsicID() == llvm::Intrinsic::localrecover &&
1858 "expected alloca or localrecover in parent LocalDeclMap");
1859 RecoverCall = cast<llvm::CallInst>(ParentRecover->clone());
1860 RecoverCall->setArgOperand(1, ParentFP);
1861 RecoverCall->insertBefore(AllocaInsertPt);
1862 }
1863
1864 // Bitcast the variable, rename it, and insert it in the local decl map.
1865 llvm::Value *ChildVar =
1866 Builder.CreateBitCast(RecoverCall, ParentVar.getType());
1867 ChildVar->setName(ParentVar.getName());
1868 return ParentVar.withPointer(ChildVar, KnownNonNull);
1869}
1870
1872 const Stmt *OutlinedStmt,
1873 bool IsFilter) {
1874 // Find all captures in the Stmt.
1875 CaptureFinder Finder(ParentCGF, ParentCGF.CXXABIThisDecl);
1876 Finder.Visit(OutlinedStmt);
1877
1878 // We can exit early on x86_64 when there are no captures. We just have to
1879 // save the exception code in filters so that __exception_code() works.
1880 if (!Finder.foundCaptures() &&
1881 CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
1882 if (IsFilter)
1883 EmitSEHExceptionCodeSave(ParentCGF, nullptr, nullptr);
1884 return;
1885 }
1886
1887 llvm::Value *EntryFP = nullptr;
1889 if (IsFilter && CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
1890 // 32-bit SEH filters need to be careful about FP recovery. The end of the
1891 // EH registration is passed in as the EBP physical register. We can
1892 // recover that with llvm.frameaddress(1).
1893 EntryFP = Builder.CreateCall(
1894 CGM.getIntrinsic(llvm::Intrinsic::frameaddress, AllocaInt8PtrTy),
1895 {Builder.getInt32(1)});
1896 } else {
1897 // Otherwise, for x64 and 32-bit finally functions, the parent FP is the
1898 // second parameter.
1899 auto AI = CurFn->arg_begin();
1900 ++AI;
1901 EntryFP = &*AI;
1902 }
1903
1904 llvm::Value *ParentFP = EntryFP;
1905 if (IsFilter) {
1906 // Given whatever FP the runtime provided us in EntryFP, recover the true
1907 // frame pointer of the parent function. We only need to do this in filters,
1908 // since finally funclets recover the parent FP for us.
1909 llvm::Function *RecoverFPIntrin =
1910 CGM.getIntrinsic(llvm::Intrinsic::eh_recoverfp);
1911 ParentFP = Builder.CreateCall(RecoverFPIntrin, {ParentCGF.CurFn, EntryFP});
1912
1913 // if the parent is a _finally, the passed-in ParentFP is the FP
1914 // of parent _finally, not Establisher's FP (FP of outermost function).
1915 // Establkisher FP is 2nd paramenter passed into parent _finally.
1916 // Fortunately, it's always saved in parent's frame. The following
1917 // code retrieves it, and escapes it so that spill instruction won't be
1918 // optimized away.
1919 if (ParentCGF.ParentCGF != nullptr) {
1920 // Locate and escape Parent's frame_pointer.addr alloca
1921 // Depending on target, should be 1st/2nd one in LocalDeclMap.
1922 // Let's just scan for ImplicitParamDecl with VoidPtrTy.
1923 llvm::AllocaInst *FramePtrAddrAlloca = nullptr;
1924 for (auto &I : ParentCGF.LocalDeclMap) {
1925 const VarDecl *D = cast<VarDecl>(I.first);
1926 if (isa<ImplicitParamDecl>(D) &&
1927 D->getType() == getContext().VoidPtrTy) {
1928 assert(D->getName().starts_with("frame_pointer"));
1929 FramePtrAddrAlloca =
1930 cast<llvm::AllocaInst>(I.second.getBasePointer());
1931 break;
1932 }
1933 }
1934 assert(FramePtrAddrAlloca);
1935 auto InsertPair = ParentCGF.EscapedLocals.insert(
1936 std::make_pair(FramePtrAddrAlloca, ParentCGF.EscapedLocals.size()));
1937 int FrameEscapeIdx = InsertPair.first->second;
1938
1939 // an example of a filter's prolog::
1940 // %0 = call ptr @llvm.eh.recoverfp(@"?fin$0@0@main@@",..)
1941 // %1 = call ptr @llvm.localrecover(@"?fin$0@0@main@@",..)
1942 // %2 = load ptr, ptr %1, align 8
1943 // ==> %2 is the frame-pointer of outermost host function
1944 llvm::Function *FrameRecoverFn = llvm::Intrinsic::getOrInsertDeclaration(
1945 &CGM.getModule(), llvm::Intrinsic::localrecover);
1946 ParentFP = Builder.CreateCall(
1947 FrameRecoverFn, {ParentCGF.CurFn, ParentFP,
1948 llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)});
1949 ParentFP = Builder.CreateLoad(
1950 Address(ParentFP, CGM.VoidPtrTy, getPointerAlign()));
1951 }
1952 }
1953
1954 // Create llvm.localrecover calls for all captures.
1955 for (const VarDecl *VD : Finder.Captures) {
1956 if (VD->getType()->isVariablyModifiedType()) {
1957 CGM.ErrorUnsupported(VD, "VLA captured by SEH");
1958 continue;
1959 }
1960 assert((isa<ImplicitParamDecl>(VD) || VD->isLocalVarDeclOrParm()) &&
1961 "captured non-local variable");
1962
1963 auto L = ParentCGF.LambdaCaptureFields.find(VD);
1964 if (L != ParentCGF.LambdaCaptureFields.end()) {
1965 LambdaCaptureFields[VD] = L->second;
1966 continue;
1967 }
1968
1969 // If this decl hasn't been declared yet, it will be declared in the
1970 // OutlinedStmt.
1971 auto I = ParentCGF.LocalDeclMap.find(VD);
1972 if (I == ParentCGF.LocalDeclMap.end())
1973 continue;
1974
1975 Address ParentVar = I->second;
1976 Address Recovered =
1977 recoverAddrOfEscapedLocal(ParentCGF, ParentVar, ParentFP);
1978 setAddrOfLocalVar(VD, Recovered);
1979
1980 if (isa<ImplicitParamDecl>(VD)) {
1981 CXXABIThisAlignment = ParentCGF.CXXABIThisAlignment;
1982 CXXThisAlignment = ParentCGF.CXXThisAlignment;
1983 CXXABIThisValue = Builder.CreateLoad(Recovered, "this");
1986 // We are in a lambda function where "this" is captured so the
1987 // CXXThisValue need to be loaded from the lambda capture
1988 LValue ThisFieldLValue =
1991 CXXThisValue = ThisFieldLValue.getAddress().emitRawPointer(*this);
1992 } else {
1993 CXXThisValue = EmitLoadOfLValue(ThisFieldLValue, SourceLocation())
1994 .getScalarVal();
1995 }
1996 } else {
1997 CXXThisValue = CXXABIThisValue;
1998 }
1999 }
2000 }
2001
2002 if (Finder.SEHCodeSlot.isValid()) {
2003 SEHCodeSlotStack.push_back(
2004 recoverAddrOfEscapedLocal(ParentCGF, Finder.SEHCodeSlot, ParentFP));
2005 }
2006
2007 if (IsFilter)
2008 EmitSEHExceptionCodeSave(ParentCGF, ParentFP, EntryFP);
2009}
2010
2011/// Arrange a function prototype that can be called by Windows exception
2012/// handling personalities. On Win64, the prototype looks like:
2013/// RetTy func(void *EHPtrs, void *ParentFP);
2015 bool IsFilter,
2016 const Stmt *OutlinedStmt) {
2017 SourceLocation StartLoc = OutlinedStmt->getBeginLoc();
2018
2019 // Get the mangled function name.
2020 SmallString<128> Name;
2021 {
2022 llvm::raw_svector_ostream OS(Name);
2023 GlobalDecl ParentSEHFn = ParentCGF.CurSEHParent;
2024 assert(ParentSEHFn && "No CurSEHParent!");
2026 if (IsFilter)
2027 Mangler.mangleSEHFilterExpression(ParentSEHFn, OS);
2028 else
2029 Mangler.mangleSEHFinallyBlock(ParentSEHFn, OS);
2030 }
2031
2032 FunctionArgList Args;
2033 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 || !IsFilter) {
2034 // All SEH finally functions take two parameters. Win64 filters take two
2035 // parameters. Win32 filters take no parameters.
2036 if (IsFilter) {
2037 Args.push_back(ImplicitParamDecl::Create(
2038 getContext(), /*DC=*/nullptr, StartLoc,
2039 &getContext().Idents.get("exception_pointers"),
2041 } else {
2042 Args.push_back(ImplicitParamDecl::Create(
2043 getContext(), /*DC=*/nullptr, StartLoc,
2044 &getContext().Idents.get("abnormal_termination"),
2045 getContext().UnsignedCharTy, ImplicitParamKind::Other));
2046 }
2047 Args.push_back(ImplicitParamDecl::Create(
2048 getContext(), /*DC=*/nullptr, StartLoc,
2049 &getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy,
2051 }
2052
2053 QualType RetTy = IsFilter ? getContext().LongTy : getContext().VoidTy;
2054
2055 const CGFunctionInfo &FnInfo =
2057
2058 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
2059 llvm::Function *Fn = llvm::Function::Create(
2060 FnTy, llvm::GlobalValue::InternalLinkage, Name.str(), &CGM.getModule());
2061
2062 IsOutlinedSEHHelper = true;
2063
2064 StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
2065 OutlinedStmt->getBeginLoc(), OutlinedStmt->getBeginLoc());
2067
2069 EmitCapturedLocals(ParentCGF, OutlinedStmt, IsFilter);
2070}
2071
2072/// Create a stub filter function that will ultimately hold the code of the
2073/// filter expression. The EH preparation passes in LLVM will outline the code
2074/// from the main function body into this stub.
2075llvm::Function *
2077 const SEHExceptStmt &Except) {
2078 const Expr *FilterExpr = Except.getFilterExpr();
2079 startOutlinedSEHHelper(ParentCGF, true, FilterExpr);
2080
2081 // Emit the original filter expression, convert to i32, and return.
2082 llvm::Value *R = EmitScalarExpr(FilterExpr);
2083 R = Builder.CreateIntCast(R, ConvertType(getContext().LongTy),
2084 FilterExpr->getType()->isSignedIntegerType());
2086
2087 FinishFunction(FilterExpr->getEndLoc());
2088
2089 return CurFn;
2090}
2091
2092llvm::Function *
2094 const SEHFinallyStmt &Finally) {
2095 const Stmt *FinallyBlock = Finally.getBlock();
2096 startOutlinedSEHHelper(ParentCGF, false, FinallyBlock);
2097
2098 // Emit the original filter expression, convert to i32, and return.
2099 EmitStmt(FinallyBlock);
2100
2101 FinishFunction(FinallyBlock->getEndLoc());
2102
2103 return CurFn;
2104}
2105
2107 llvm::Value *ParentFP,
2108 llvm::Value *EntryFP) {
2109 // Get the pointer to the EXCEPTION_POINTERS struct. This is returned by the
2110 // __exception_info intrinsic.
2111 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
2112 // On Win64, the info is passed as the first parameter to the filter.
2113 SEHInfo = &*CurFn->arg_begin();
2114 SEHCodeSlotStack.push_back(
2115 CreateMemTemp(getContext().IntTy, "__exception_code"));
2116 } else {
2117 // On Win32, the EBP on entry to the filter points to the end of an
2118 // exception registration object. It contains 6 32-bit fields, and the info
2119 // pointer is stored in the second field. So, GEP 20 bytes backwards and
2120 // load the pointer.
2121 SEHInfo = Builder.CreateConstInBoundsGEP1_32(Int8Ty, EntryFP, -20);
2124 ParentCGF, ParentCGF.SEHCodeSlotStack.back(), ParentFP));
2125 }
2126
2127 // Save the exception code in the exception slot to unify exception access in
2128 // the filter function and the landing pad.
2129 // struct EXCEPTION_POINTERS {
2130 // EXCEPTION_RECORD *ExceptionRecord;
2131 // CONTEXT *ContextRecord;
2132 // };
2133 // int exceptioncode = exception_pointers->ExceptionRecord->ExceptionCode;
2134 llvm::Type *RecordTy = llvm::PointerType::getUnqual(getLLVMContext());
2135 llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy);
2136 llvm::Value *Rec = Builder.CreateStructGEP(PtrsTy, SEHInfo, 0);
2137 Rec = Builder.CreateAlignedLoad(RecordTy, Rec, getPointerAlign());
2138 llvm::Value *Code = Builder.CreateAlignedLoad(Int32Ty, Rec, getIntAlign());
2139 assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
2140 Builder.CreateStore(Code, SEHCodeSlotStack.back());
2141}
2142
2144 // Sema should diagnose calling this builtin outside of a filter context, but
2145 // don't crash if we screw up.
2146 if (!SEHInfo)
2147 return llvm::UndefValue::get(Int8PtrTy);
2148 assert(SEHInfo->getType() == Int8PtrTy);
2149 return SEHInfo;
2150}
2151
2153 assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
2154 return Builder.CreateLoad(SEHCodeSlotStack.back());
2155}
2156
2158 // Abnormal termination is just the first parameter to the outlined finally
2159 // helper.
2160 auto AI = CurFn->arg_begin();
2161 return Builder.CreateZExt(&*AI, Int32Ty);
2162}
2163
2165 llvm::Function *FinallyFunc) {
2166 EHStack.pushCleanup<PerformSEHFinally>(Kind, FinallyFunc);
2167}
2168
2170 CodeGenFunction HelperCGF(CGM, /*suppressNewContext=*/true);
2171 HelperCGF.ParentCGF = this;
2172 if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
2173 // Outline the finally block.
2174 llvm::Function *FinallyFunc =
2175 HelperCGF.GenerateSEHFinallyFunction(*this, *Finally);
2176
2177 // Push a cleanup for __finally blocks.
2178 EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, FinallyFunc);
2179 return;
2180 }
2181
2182 // Otherwise, we must have an __except block.
2183 const SEHExceptStmt *Except = S.getExceptHandler();
2184 assert(Except);
2185 EHCatchScope *CatchScope = EHStack.pushCatch(1);
2186 SEHCodeSlotStack.push_back(
2187 CreateMemTemp(getContext().IntTy, "__exception_code"));
2188
2189 // If the filter is known to evaluate to 1, then we can use the clause
2190 // "catch i8* null". We can't do this on x86 because the filter has to save
2191 // the exception code.
2192 llvm::Constant *C =
2194 getContext().IntTy);
2195 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 && C &&
2196 C->isOneValue()) {
2197 CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
2198 return;
2199 }
2200
2201 // In general, we have to emit an outlined filter function. Use the function
2202 // in place of the RTTI typeinfo global that C++ EH uses.
2203 llvm::Function *FilterFunc =
2204 HelperCGF.GenerateSEHFilterFunction(*this, *Except);
2205 CatchScope->setHandler(0, FilterFunc, createBasicBlock("__except.ret"));
2206}
2207
2209 // Just pop the cleanup if it's a __finally block.
2210 if (S.getFinallyHandler()) {
2212 return;
2213 }
2214
2215 // IsEHa: emit an invoke _seh_try_end() to mark end of FT flow
2216 if (getLangOpts().EHAsynch && Builder.GetInsertBlock()) {
2217 llvm::FunctionCallee SehTryEnd = getSehTryEndFn(CGM);
2218 EmitRuntimeCallOrInvoke(SehTryEnd);
2219 }
2220
2221 // Otherwise, we must have an __except block.
2222 const SEHExceptStmt *Except = S.getExceptHandler();
2223 assert(Except && "__try must have __finally xor __except");
2224 EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
2225
2226 // Don't emit the __except block if the __try block lacked invokes.
2227 // TODO: Model unwind edges from instructions, either with iload / istore or
2228 // a try body function.
2229 if (!CatchScope.hasEHBranches()) {
2230 CatchScope.clearHandlerBlocks();
2231 EHStack.popCatch();
2232 SEHCodeSlotStack.pop_back();
2233 return;
2234 }
2235
2236 // The fall-through block.
2237 llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
2238
2239 // We just emitted the body of the __try; jump to the continue block.
2240 if (HaveInsertPoint())
2241 Builder.CreateBr(ContBB);
2242
2243 // Check if our filter function returned true.
2244 emitCatchDispatchBlock(*this, CatchScope);
2245
2246 // Grab the block before we pop the handler.
2247 llvm::BasicBlock *CatchPadBB = CatchScope.getHandler(0).Block;
2248 EHStack.popCatch();
2249
2250 EmitBlockAfterUses(CatchPadBB);
2251
2252 // __except blocks don't get outlined into funclets, so immediately do a
2253 // catchret.
2254 llvm::CatchPadInst *CPI =
2255 cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
2256 llvm::BasicBlock *ExceptBB = createBasicBlock("__except");
2257 Builder.CreateCatchRet(CPI, ExceptBB);
2258 EmitBlock(ExceptBB);
2259
2260 // On Win64, the exception code is returned in EAX. Copy it into the slot.
2261 if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
2262 llvm::Function *SEHCodeIntrin =
2263 CGM.getIntrinsic(llvm::Intrinsic::eh_exceptioncode);
2264 llvm::Value *Code = Builder.CreateCall(SEHCodeIntrin, {CPI});
2265 Builder.CreateStore(Code, SEHCodeSlotStack.back());
2266 }
2267
2268 // Emit the __except body.
2269 EmitStmt(Except->getBlock());
2270
2271 // End the lifetime of the exception code.
2272 SEHCodeSlotStack.pop_back();
2273
2274 if (HaveInsertPoint())
2275 Builder.CreateBr(ContBB);
2276
2277 EmitBlock(ContBB);
2278}
2279
2281 // If this code is reachable then emit a stop point (if generating
2282 // debug info). We have to do this ourselves because we are on the
2283 // "simple" statement path.
2284 if (HaveInsertPoint())
2285 EmitStopPoint(&S);
2286
2287 // This must be a __leave from a __finally block, which we warn on and is UB.
2288 // Just emit unreachable.
2289 if (!isSEHTryScope()) {
2290 Builder.CreateUnreachable();
2291 Builder.ClearInsertionPoint();
2292 return;
2293 }
2294
2296}
#define V(N, I)
Definition: ASTContext.h:3443
static char ID
Definition: Arena.cpp:183
static llvm::FunctionCallee getUnexpectedFn(CodeGenModule &CGM)
Definition: CGException.cpp:53
static const EHPersonality & getObjCPersonality(const TargetInfo &Target, const LangOptions &L)
static const EHPersonality & getSEHPersonalityMSVC(const llvm::Triple &T)
static const EHPersonality & getCXXPersonality(const TargetInfo &Target, const LangOptions &L)
static llvm::FunctionCallee getPersonalityFn(CodeGenModule &CGM, const EHPersonality &Personality)
static void emitFilterDispatchBlock(CodeGenFunction &CGF, EHFilterScope &filterScope)
Emit the dispatch block for a filter scope if necessary.
static void emitCatchPadBlock(CodeGenFunction &CGF, EHCatchScope &CatchScope)
static llvm::FunctionCallee getFreeExceptionFn(CodeGenModule &CGM)
Definition: CGException.cpp:32
static llvm::FunctionCallee getSehTryEndFn(CodeGenModule &CGM)
Definition: CGException.cpp:47
static bool LandingPadHasOnlyCXXUses(llvm::LandingPadInst *LPI)
Check whether a landingpad instruction only uses C++ features.
static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn)
Check whether a personality function could reasonably be swapped for a C++ personality function.
static void emitCatchDispatchBlock(CodeGenFunction &CGF, EHCatchScope &catchScope)
Emit the structure of the dispatch block for the given catch scope.
static llvm::Constant * getOpaquePersonalityFn(CodeGenModule &CGM, const EHPersonality &Personality)
static bool isNonEHScope(const EHScope &S)
Check whether this is a non-EH scope, i.e.
static llvm::FunctionCallee getCatchallRethrowFn(CodeGenModule &CGM, StringRef Name)
Definition: CGException.cpp:88
static llvm::FunctionCallee getSehTryBeginFn(CodeGenModule &CGM)
Definition: CGException.cpp:41
static llvm::Constant * getCatchAllValue(CodeGenFunction &CGF)
Returns the value to inject into a selector to indicate the presence of a catch-all.
static const EHPersonality & getObjCXXPersonality(const TargetInfo &Target, const LangOptions &L)
Determines the personality function to use when both C++ and Objective-C exceptions are being caught.
static void emitWasmCatchPadBlock(CodeGenFunction &CGF, EHCatchScope &CatchScope)
static const EHPersonality & getCPersonality(const TargetInfo &Target, const LangOptions &L)
const Decl * D
Expr * E
llvm::DenseSet< const void * > Visited
Definition: HTMLLogger.cpp:145
llvm::MachO::Target Target
Definition: MachO.h:51
Defines the Objective-C statement AST node classes.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
CanQualType LongTy
Definition: ASTContext.h:1169
CanQualType VoidPtrTy
Definition: ASTContext.h:1187
CanQualType VoidTy
Definition: ASTContext.h:1160
CanQualType UnsignedCharTy
Definition: ASTContext.h:1170
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
CXXCatchStmt - This represents a C++ catch block.
Definition: StmtCXX.h:28
Represents the this expression in C++.
Definition: ExprCXX.h:1152
A C++ throw-expression (C++ [except.throw]).
Definition: ExprCXX.h:1206
CXXTryStmt - A C++ try block, including all handlers.
Definition: StmtCXX.h:69
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2874
Represents the body of a CapturedStmt, and serves as its DeclContext.
Definition: Decl.h:4673
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition: Address.h:128
llvm::Value * getBasePointer() const
Definition: Address.h:193
static Address invalid()
Definition: Address.h:176
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition: Address.h:251
Address withPointer(llvm::Value *NewPointer, KnownNonNull_t IsKnownNonNull) const
Return address with different pointer, but same element type and alignment.
Definition: Address.h:259
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
Definition: Address.h:274
llvm::StringRef getName() const
Return the IR name of the pointer value.
Definition: Address.h:216
bool isValid() const
Definition: Address.h:177
llvm::PointerType * getType() const
Return the type of the pointer value.
Definition: Address.h:199
static ApplyDebugLocation CreateDefaultArtificial(CodeGenFunction &CGF, SourceLocation TemporaryLocation)
Apply TemporaryLocation if it is valid.
Definition: CGDebugInfo.h:903
llvm::StoreInst * CreateFlagStore(bool Value, llvm::Value *Addr)
Emit a store to an i1 flag variable.
Definition: CGBuilder.h:164
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition: CGBuilder.h:136
llvm::StoreInst * CreateAlignedStore(llvm::Value *Val, llvm::Value *Addr, CharUnits Align, bool IsVolatile=false)
Definition: CGBuilder.h:143
Address CreateStructGEP(Address Addr, unsigned Index, const llvm::Twine &Name="")
Definition: CGBuilder.h:219
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition: CGBuilder.h:108
llvm::LoadInst * CreateFlagLoad(llvm::Value *Addr, const llvm::Twine &Name="")
Emit a load from an i1 flag variable.
Definition: CGBuilder.h:158
llvm::LoadInst * CreateAlignedLoad(llvm::Type *Ty, llvm::Value *Addr, CharUnits Align, const llvm::Twine &Name="")
Definition: CGBuilder.h:128
virtual void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C)=0
virtual void emitRethrow(CodeGenFunction &CGF, bool isNoReturn)=0
virtual llvm::CallInst * emitTerminateForUnexpectedException(CodeGenFunction &CGF, llvm::Value *Exn)
Definition: CGCXXABI.cpp:332
virtual CatchTypeInfo getCatchAllTypeInfo()
Definition: CGCXXABI.cpp:338
virtual void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E)=0
virtual CatchTypeInfo getAddrOfCXXCatchHandlerType(QualType Ty, QualType CatchHandlerType)=0
MangleContext & getMangleContext()
Gets the mangle context.
Definition: CGCXXABI.h:113
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition: CGCall.h:137
CGFunctionInfo - Class to encapsulate the information about a function definition.
virtual llvm::Constant * GetEHType(QualType T)=0
Get the type constant to catch for the given ObjC pointer type.
virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S, bool ClearInsertionPoint=true)=0
CallArgList - Type for representing both the value and type of arguments in a call.
Definition: CGCall.h:274
void add(RValue rvalue, QualType type)
Definition: CGCall.h:305
void enter(CodeGenFunction &CGF, const Stmt *Finally, llvm::FunctionCallee beginCatchFn, llvm::FunctionCallee endCatchFn, llvm::FunctionCallee rethrowFn)
Enters a finally block for an implementation using zero-cost exceptions.
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
llvm::BasicBlock * getEHDispatchBlock(EHScopeStack::stable_iterator scope)
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, llvm::Instruction *DominatingIP)
DeactivateCleanupBlock - Deactivates the given cleanup block.
void EnterSEHTryStmt(const SEHTryStmt &S)
Address getExceptionSlot()
Returns a pointer to the function's exception object and selector slot, which is assigned in every la...
void VolatilizeTryBlocks(llvm::BasicBlock *BB, llvm::SmallPtrSet< llvm::BasicBlock *, 10 > &V)
llvm::Function * GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF, const SEHFinallyStmt &Finally)
llvm::CallInst * EmitTrapCall(llvm::Intrinsic::ID IntrID)
Emit a call to trap or debugtrap and attach function attribute "trap-func-name" if specified.
llvm::Function * GenerateSEHFilterFunction(CodeGenFunction &ParentCGF, const SEHExceptStmt &Except)
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...
llvm::BasicBlock * getInvokeDestImpl()
bool IsOutlinedSEHHelper
True if the current function is an outlined SEH helper.
void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter, const Stmt *OutlinedStmt)
SmallVector< Address, 1 > SEHCodeSlotStack
A stack of exception code slots.
void EmitCXXTryStmt(const CXXTryStmt &S)
void popCatchScope()
popCatchScope - Pops the catch scope at the top of the EHScope stack, emitting any required code (oth...
void EmitEndEHSpec(const Decl *D)
EmitEndEHSpec - Emit the end of the exception spec.
void EmitAnyExprToExn(const Expr *E, Address Addr)
bool isSEHTryScope() const
Returns true inside SEH __try blocks.
void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF, llvm::Value *ParentFP, llvm::Value *EntryEBP)
llvm::BasicBlock * getEHResumeBlock(bool isCleanup)
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
llvm::Value * EmitSEHExceptionInfo()
const LangOptions & getLangOpts() const
llvm::BasicBlock * EHResumeBlock
EHResumeBlock - Unified block containing a call to llvm.eh.resume.
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
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...
llvm::AllocaInst * EHSelectorSlot
The selector slot.
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
void EmitAnyExprToMem(const Expr *E, Address Location, Qualifiers Quals, bool IsInitializer)
EmitAnyExprToMem - Emits the code necessary to evaluate an arbitrary expression into the given memory...
void EmitBlockAfterUses(llvm::BasicBlock *BB)
EmitBlockAfterUses - Emit the given block somewhere hopefully near its uses, and leave the insertion ...
llvm::BasicBlock * getTerminateFunclet()
getTerminateLandingPad - Return a cleanup funclet that just calls terminate.
llvm::Type * ConvertTypeForMem(QualType T)
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
llvm::BasicBlock * getUnreachableBlock()
llvm::AssertingVH< llvm::Instruction > AllocaInsertPt
AllocaInsertPoint - This is an instruction in the entry block before which we prefer to insert alloca...
llvm::SmallVector< const JumpDest *, 2 > SEHTryEpilogueStack
llvm::Value * ExceptionSlot
The exception slot.
RawAddress CreateMemTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen and cas...
void EmitSEHLeaveStmt(const SEHLeaveStmt &S)
const TargetInfo & getTarget() const
llvm::Value * EmitSEHExceptionCode()
void pushSEHCleanup(CleanupKind kind, llvm::Function *FinallyFunc)
void StartFunction(GlobalDecl GD, QualType RetTy, llvm::Function *Fn, const CGFunctionInfo &FnInfo, const FunctionArgList &Args, SourceLocation Loc=SourceLocation(), SourceLocation StartLoc=SourceLocation())
Emit code for the start of a function.
bool HaveInsertPoint() const
HaveInsertPoint - True if an insertion point is defined.
Address recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF, Address ParentVar, llvm::Value *ParentFP)
Recovers the address of a local in a parent function.
void EmitSEHTryStmt(const SEHTryStmt &S)
void ExitSEHTryStmt(const SEHTryStmt &S)
llvm::BasicBlock * getTerminateLandingPad()
getTerminateLandingPad - Return a landing pad that just calls terminate.
llvm::BasicBlock * getTerminateHandler()
getTerminateHandler - Return a handler (not a landing pad, just a catch handler) that just calls term...
const TargetCodeGenInfo & getTargetHooks() const
void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock=false)
void EmitStartEHSpec(const Decl *D)
EmitStartEHSpec - Emit the start of the exception spec.
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::CallBase **CallOrInvoke, bool IsMustTail, SourceLocation Loc, bool IsVirtualFunctionPointerThunk=false)
EmitCall - Generate a call of the given function, expecting the given result type,...
llvm::CallInst * EmitNounwindRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint=true)
void EmitBranchThroughCleanup(JumpDest Dest)
EmitBranchThroughCleanup - Emit a branch from the current insert block through the normal cleanup han...
llvm::Value * SEHInfo
Value returned by __exception_info intrinsic.
void EmitStmt(const Stmt *S, ArrayRef< const Attr * > Attrs={})
EmitStmt - Emit the code for the statement.
void PopCleanupBlock(bool FallThroughIsBranchThrough=false, bool ForDeactivation=false)
PopCleanupBlock - Will pop the cleanup entry on the stack and process all branch fixups.
llvm::BasicBlock * EmitLandingPad()
Emits a landing pad for the current EH stack.
llvm::DenseMap< const ValueDecl *, FieldDecl * > LambdaCaptureFields
llvm::CallInst * EmitRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
llvm::Type * ConvertType(QualType T)
void EmitNoreturnRuntimeCallOrInvoke(llvm::FunctionCallee callee, ArrayRef< llvm::Value * > args)
llvm::CallBase * EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee, ArrayRef< llvm::Value * > args, const Twine &name="")
void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt, bool IsFilter)
Scan the outlined statement for captures from the parent function.
llvm::BasicBlock * getFuncletEHDispatchBlock(EHScopeStack::stable_iterator scope)
llvm::Value * EmitSEHAbnormalTermination()
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
void EmitStopPoint(const Stmt *S)
EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock=false)
llvm::Instruction * CurrentFuncletPad
void EnsureInsertPoint()
EnsureInsertPoint - Ensure that an insertion point is defined so that emitted IR has a place to go.
llvm::LLVMContext & getLLVMContext()
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
void incrementProfileCounter(const Stmt *S, llvm::Value *StepV=nullptr)
Increment the profiler's counter for the given statement by StepV.
llvm::Value * getSelectorFromSlot()
llvm::Value * getExceptionFromSlot()
Returns the contents of the function's exception object and selector slots.
LValue EmitLValueForLambdaField(const FieldDecl *Field)
This class organizes the cross-function state that is used while generating LLVM code.
void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F, const CGFunctionInfo &FI)
Set the attributes on the LLVM function for the given decl and function info.
llvm::Module & getModule() const
llvm::FunctionCallee CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false, bool AssumeConvergent=false)
Create or return a runtime function declaration with the specified type and name.
llvm::Constant * GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH=false)
Get the address of the RTTI descriptor for the given type.
DiagnosticsEngine & getDiags() const
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn't support the specified stmt yet.
const LangOptions & getLangOpts() const
const TargetInfo & getTarget() const
CGCXXABI & getCXXABI() const
ASTContext & getContext() const
llvm::FunctionCallee getTerminateFn()
Get the declaration of std::terminate for the platform.
Definition: CGException.cpp:62
llvm::LLVMContext & getLLVMContext()
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys={})
CGObjCRuntime & getObjCRuntime()
Return a reference to the configured Objective-C runtime.
LangAS GetGlobalVarAddressSpace(const VarDecl *D)
Return the AST address space of the underlying global variable for D, as determined by its declaratio...
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition: CGCall.cpp:1630
const CGFunctionInfo & arrangeBuiltinFunctionDeclaration(QualType resultType, const FunctionArgList &args)
A builtin function is a freestanding function using the default C conventions.
Definition: CGCall.cpp:679
const CGFunctionInfo & arrangeBuiltinFunctionCall(QualType resultType, const CallArgList &args)
Definition: CGCall.cpp:667
llvm::Constant * tryEmitAbstract(const Expr *E, QualType T)
Try to emit the result of the given expression as an abstract constant.
A scope which attempts to handle some, possibly all, types of exceptions.
Definition: CGCleanup.h:158
iterator begin() const
Definition: CGCleanup.h:234
const Handler & getHandler(unsigned I) const
Definition: CGCleanup.h:219
void setHandler(unsigned I, llvm::Constant *Type, llvm::BasicBlock *Block)
Definition: CGCleanup.h:207
void setCatchAllHandler(unsigned I, llvm::BasicBlock *Block)
Definition: CGCleanup.h:203
unsigned getNumHandlers() const
Definition: CGCleanup.h:199
An exceptions scope which filters exceptions thrown through it.
Definition: CGCleanup.h:501
llvm::Value * getFilter(unsigned i) const
Definition: CGCleanup.h:531
unsigned getNumFilters() const
Definition: CGCleanup.h:524
Information for lazily generating a cleanup.
Definition: EHScopeStack.h:141
A non-stable pointer into the scope stack.
Definition: CGCleanup.h:555
A saved depth on the scope stack.
Definition: EHScopeStack.h:101
class EHFilterScope * pushFilter(unsigned NumFilters)
Push an exceptions filter on the stack.
Definition: CGCleanup.cpp:218
stable_iterator stable_begin() const
Create a stable reference to the top of the EH stack.
Definition: EHScopeStack.h:393
stable_iterator getInnermostEHScope() const
Definition: EHScopeStack.h:375
bool empty() const
Determines whether the exception-scopes stack is empty.
Definition: EHScopeStack.h:359
iterator end() const
Returns an iterator pointing to the outermost EH scope.
Definition: CGCleanup.h:619
void popFilter()
Pops an exceptions filter off the stack.
Definition: CGCleanup.cpp:226
iterator begin() const
Returns an iterator pointing to the innermost EH scope.
Definition: CGCleanup.h:615
void popCatch()
Pops a catch scope off the stack. This is private to CGException.cpp.
Definition: CGCleanup.h:623
class EHCatchScope * pushCatch(unsigned NumHandlers)
Push a set of catch handlers on the stack.
Definition: CGCleanup.cpp:235
iterator find(stable_iterator save) const
Turn a stable reference to a scope depth into a unstable pointer to the EH stack.
Definition: CGCleanup.h:639
static stable_iterator stable_end()
Create a stable reference to the bottom of the EH stack.
Definition: EHScopeStack.h:398
void popTerminate()
Pops a terminate handler off the stack.
Definition: CGCleanup.h:631
void pushTerminate()
Push a terminate handler on the stack.
Definition: CGCleanup.cpp:243
A protected scope for zero-cost EH handling.
Definition: CGCleanup.h:45
llvm::BasicBlock * getCachedLandingPad() const
Definition: CGCleanup.h:126
Kind getKind() const
Definition: CGCleanup.h:124
EHScopeStack::stable_iterator getEnclosingEHScope() const
Definition: CGCleanup.h:148
llvm::BasicBlock * getCachedEHDispatchBlock() const
Definition: CGCleanup.h:134
void setCachedEHDispatchBlock(llvm::BasicBlock *block)
Definition: CGCleanup.h:138
bool hasEHBranches() const
Definition: CGCleanup.h:142
FunctionArgList - Type for representing both the decl and type of parameters to a function.
Definition: CGCall.h:382
LValue - This represents an lvalue references.
Definition: CGValue.h:182
Address getAddress() const
Definition: CGValue.h:361
static RValue get(llvm::Value *V)
Definition: CGValue.h:98
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition: CGValue.h:71
ReturnValueSlot - Contains the address where the return value of a function can be stored,...
Definition: CGCall.h:386
Address performAddrSpaceCast(CodeGen::CodeGenFunction &CGF, Address Addr, LangAS SrcAddr, LangAS DestAddr, llvm::Type *DestTy, bool IsNonNull=false) const
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:195
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
SourceLocation getLocation() const
Definition: DeclBase.h:442
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1493
This represents one expression.
Definition: Expr.h:110
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
QualType getType() const
Definition: Expr.h:142
Represents a function declaration or definition.
Definition: Decl.h:1935
bool usesSEHTry() const
Indicates the function uses __try.
Definition: Decl.h:2446
SourceRange getExceptionSpecSourceRange() const
Attempt to compute an informative source range covering the function exception specification,...
Definition: Decl.cpp:3915
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5102
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:5382
QualType getExceptionType(unsigned i) const
Return the ith exception type, where 0 <= i < getNumExceptions().
Definition: Type.h:5433
unsigned getNumExceptions() const
Return the number of types in the exception specification.
Definition: Type.h:5425
CanThrowResult canThrow() const
Determine whether this function type has a non-throwing exception specification.
Definition: Type.cpp:3758
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:56
const Decl * getDecl() const
Definition: GlobalDecl.h:103
static ImplicitParamDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, ImplicitParamKind ParamKind)
Create implicit parameter.
Definition: Decl.cpp:5402
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:499
bool hasWasmExceptions() const
Definition: LangOptions.h:767
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:534
bool hasSjLjExceptions() const
Definition: LangOptions.h:755
bool hasDWARFExceptions() const
Definition: LangOptions.h:763
bool hasSEHExceptions() const
Definition: LangOptions.h:759
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition: Mangle.h:45
virtual void mangleSEHFilterExpression(GlobalDecl EnclosingDecl, raw_ostream &Out)=0
virtual void mangleSEHFinallyBlock(GlobalDecl EnclosingDecl, raw_ostream &Out)=0
Represents Objective-C's @throw statement.
Definition: StmtObjC.h:358
The basic abstraction for the target Objective-C runtime.
Definition: ObjCRuntime.h:28
bool hasTerminate() const
Does this runtime provide an objc_terminate function?
Definition: ObjCRuntime.h:364
Kind getKind() const
Definition: ObjCRuntime.h:77
bool isNeXTFamily() const
Is this runtime basically of the NeXT family of runtimes?
Definition: ObjCRuntime.h:143
const VersionTuple & getVersion() const
Definition: ObjCRuntime.h:78
@ MacOSX
'macosx' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the non-fragile AB...
Definition: ObjCRuntime.h:35
@ FragileMacOSX
'macosx-fragile' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
Definition: ObjCRuntime.h:40
@ GNUstep
'gnustep' is the modern non-fragile GNUstep runtime.
Definition: ObjCRuntime.h:56
@ ObjFW
'objfw' is the Objective-C runtime included in ObjFW
Definition: ObjCRuntime.h:59
@ iOS
'ios' is the Apple-provided NeXT-derived runtime on iOS or the iOS simulator; it is always non-fragil...
Definition: ObjCRuntime.h:45
@ GCC
'gcc' is the Objective-C runtime shipped with GCC, implementing a fragile Objective-C ABI
Definition: ObjCRuntime.h:53
@ WatchOS
'watchos' is a variant of iOS for Apple's watchOS.
Definition: ObjCRuntime.h:49
A (possibly-)qualified type.
Definition: Type.h:929
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7971
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:8134
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:8025
The collection of all-type qualifiers we support.
Definition: Type.h:324
CompoundStmt * getBlock() const
Definition: Stmt.h:3640
Expr * getFilterExpr() const
Definition: Stmt.h:3636
CompoundStmt * getBlock() const
Definition: Stmt.h:3677
Represents a __leave statement.
Definition: Stmt.h:3745
Smart pointer class that efficiently represents Objective-C method names.
Encodes a location in the source.
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:357
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:345
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
Exposes information about the current target.
Definition: TargetInfo.h:220
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1262
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1333
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2180
bool isPointerType() const
Definition: Type.h:8186
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2724
bool isObjCObjectPointerType() const
Definition: Type.h:8328
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8731
QualType getType() const
Definition: Decl.h:682
Represents a variable declaration or definition.
Definition: Decl.h:882
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition: Decl.h:1213
@ NormalCleanup
Denotes a cleanup that should run when a scope is exited using normal control flow (falling off the e...
Definition: EHScopeStack.h:84
@ EHCleanup
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
Definition: EHScopeStack.h:80
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:3869
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2408
bool Load(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1748
llvm::cl::opt< std::string > Filter
The JSON file list parser is used to communicate input to InstallAPI.
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus17
Definition: LangStandard.h:58
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
const FunctionProtoType * T
@ Other
Other implicit parameter.
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DynamicNone
throw()
@ EST_Dynamic
throw(T1, T2)
The MS C++ ABI needs a pointer to RTTI data plus some flags to describe the type of a catch handler,...
Definition: CGCleanup.h:39
llvm::Constant * RTTI
Definition: CGCleanup.h:40
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
llvm::IntegerType * IntTy
int
llvm::PointerType * AllocaInt8PtrTy
CatchTypeInfo Type
A type info value, or null (C++ null, not an LLVM null pointer) for a catch-all.
Definition: CGCleanup.h:168
llvm::BasicBlock * Block
The catch handler for this type.
Definition: CGCleanup.h:171
The exceptions personality for a function.
Definition: CGCleanup.h:652
static const EHPersonality & get(CodeGenModule &CGM, const FunctionDecl *FD)
static const EHPersonality XL_CPlusPlus
Definition: CGCleanup.h:679
static const EHPersonality GNU_ObjC_SJLJ
Definition: CGCleanup.h:667
bool isWasmPersonality() const
Definition: CGCleanup.h:693
static const EHPersonality ZOS_CPlusPlus
Definition: CGCleanup.h:680
static const EHPersonality GNUstep_ObjC
Definition: CGCleanup.h:669
static const EHPersonality MSVC_CxxFrameHandler3
Definition: CGCleanup.h:677
bool usesFuncletPads() const
Does this personality use landingpads or the family of pad instructions designed to form funclets?
Definition: CGCleanup.h:684
static const EHPersonality MSVC_C_specific_handler
Definition: CGCleanup.h:676
static const EHPersonality GNU_CPlusPlus_SEH
Definition: CGCleanup.h:674
static const EHPersonality GNU_ObjC
Definition: CGCleanup.h:666
static const EHPersonality GNU_CPlusPlus_SJLJ
Definition: CGCleanup.h:673
static const EHPersonality GNU_C_SJLJ
Definition: CGCleanup.h:664
static const EHPersonality GNU_C
Definition: CGCleanup.h:663
static const EHPersonality NeXT_ObjC
Definition: CGCleanup.h:671
const char * CatchallRethrowFn
Definition: CGCleanup.h:658
static const EHPersonality GNU_CPlusPlus
Definition: CGCleanup.h:672
static const EHPersonality GNU_ObjCXX
Definition: CGCleanup.h:670
static const EHPersonality GNU_C_SEH
Definition: CGCleanup.h:665
static const EHPersonality MSVC_except_handler
Definition: CGCleanup.h:675
static const EHPersonality GNU_ObjC_SEH
Definition: CGCleanup.h:668
static const EHPersonality GNU_Wasm_CPlusPlus
Definition: CGCleanup.h:678