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