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