#include "CGCXXABI.h"
#include "CGCleanup.h"
#include "CGObjCRuntime.h"
#include "CodeGenFunction.h"
#include "ConstantEmitter.h"
#include "TargetInfo.h"
#include "clang/AST/Mangle.h"
#include "clang/AST/StmtCXX.h"
#include "clang/AST/StmtObjC.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/Basic/DiagnosticSema.h"
#include "clang/Basic/TargetBuiltins.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/IntrinsicsWebAssembly.h"
#include "llvm/Support/SaveAndRestore.h"
using namespace clang;
using namespace CodeGen;
static llvm::FunctionCallee getFreeExceptionFn(CodeGenModule &CGM) {
llvm::FunctionType *FTy =
llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, false);
return CGM.CreateRuntimeFunction(FTy, "__cxa_free_exception");
}
static llvm::FunctionCallee getSehTryBeginFn(CodeGenModule &CGM) {
llvm::FunctionType *FTy =
llvm::FunctionType::get(CGM.VoidTy, false);
return CGM.CreateRuntimeFunction(FTy, "llvm.seh.try.begin");
}
static llvm::FunctionCallee getSehTryEndFn(CodeGenModule &CGM) {
llvm::FunctionType *FTy =
llvm::FunctionType::get(CGM.VoidTy, false);
return CGM.CreateRuntimeFunction(FTy, "llvm.seh.try.end");
}
static llvm::FunctionCallee getUnexpectedFn(CodeGenModule &CGM) {
llvm::FunctionType *FTy =
llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, false);
return CGM.CreateRuntimeFunction(FTy, "__cxa_call_unexpected");
}
llvm::FunctionCallee CodeGenModule::getTerminateFn() {
llvm::FunctionType *FTy =
llvm::FunctionType::get(VoidTy, false);
StringRef name;
if (getLangOpts().CPlusPlus &&
getTarget().getCXXABI().isItaniumFamily()) {
name = "_ZSt9terminatev";
} else if (getLangOpts().CPlusPlus &&
getTarget().getCXXABI().isMicrosoft()) {
if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
name = "__std_terminate";
else
name = "?terminate@@YAXXZ";
} else if (getLangOpts().ObjC &&
getLangOpts().ObjCRuntime.hasTerminate())
name = "objc_terminate";
else
name = "abort";
return CreateRuntimeFunction(FTy, name);
}
static llvm::FunctionCallee getCatchallRethrowFn(CodeGenModule &CGM,
StringRef Name) {
llvm::FunctionType *FTy =
llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, false);
return CGM.CreateRuntimeFunction(FTy, Name);
}
const EHPersonality EHPersonality::GNU_C = { "__gcc_personality_v0", nullptr };
const EHPersonality
EHPersonality::GNU_C_SJLJ = { "__gcc_personality_sj0", nullptr };
const EHPersonality
EHPersonality::GNU_C_SEH = { "__gcc_personality_seh0", nullptr };
const EHPersonality
EHPersonality::NeXT_ObjC = { "__objc_personality_v0", nullptr };
const EHPersonality
EHPersonality::GNU_CPlusPlus = { "__gxx_personality_v0", nullptr };
const EHPersonality
EHPersonality::GNU_CPlusPlus_SJLJ = { "__gxx_personality_sj0", nullptr };
const EHPersonality
EHPersonality::GNU_CPlusPlus_SEH = { "__gxx_personality_seh0", nullptr };
const EHPersonality
EHPersonality::GNU_ObjC = {"__gnu_objc_personality_v0", "objc_exception_throw"};
const EHPersonality
EHPersonality::GNU_ObjC_SJLJ = {"__gnu_objc_personality_sj0", "objc_exception_throw"};
const EHPersonality
EHPersonality::GNU_ObjC_SEH = {"__gnu_objc_personality_seh0", "objc_exception_throw"};
const EHPersonality
EHPersonality::GNU_ObjCXX = { "__gnustep_objcxx_personality_v0", nullptr };
const EHPersonality
EHPersonality::GNUstep_ObjC = { "__gnustep_objc_personality_v0", nullptr };
const EHPersonality
EHPersonality::MSVC_except_handler = { "_except_handler3", nullptr };
const EHPersonality
EHPersonality::MSVC_C_specific_handler = { "__C_specific_handler", nullptr };
const EHPersonality
EHPersonality::MSVC_CxxFrameHandler3 = { "__CxxFrameHandler3", nullptr };
const EHPersonality
EHPersonality::GNU_Wasm_CPlusPlus = { "__gxx_wasm_personality_v0", nullptr };
const EHPersonality EHPersonality::XL_CPlusPlus = {"__xlcxx_personality_v1",
nullptr};
static const EHPersonality &getCPersonality(const TargetInfo &Target,
const LangOptions &L) {
const llvm::Triple &T = Target.getTriple();
if (T.isWindowsMSVCEnvironment())
return EHPersonality::MSVC_CxxFrameHandler3;
if (L.hasSjLjExceptions())
return EHPersonality::GNU_C_SJLJ;
if (L.hasDWARFExceptions())
return EHPersonality::GNU_C;
if (L.hasSEHExceptions())
return EHPersonality::GNU_C_SEH;
return EHPersonality::GNU_C;
}
static const EHPersonality &getObjCPersonality(const TargetInfo &Target,
const LangOptions &L) {
const llvm::Triple &T = Target.getTriple();
if (T.isWindowsMSVCEnvironment())
return EHPersonality::MSVC_CxxFrameHandler3;
switch (L.ObjCRuntime.getKind()) {
case ObjCRuntime::FragileMacOSX:
return getCPersonality(Target, L);
case ObjCRuntime::MacOSX:
case ObjCRuntime::iOS:
case ObjCRuntime::WatchOS:
return EHPersonality::NeXT_ObjC;
case ObjCRuntime::GNUstep:
if (L.ObjCRuntime.getVersion() >= VersionTuple(1, 7))
return EHPersonality::GNUstep_ObjC;
LLVM_FALLTHROUGH;
case ObjCRuntime::GCC:
case ObjCRuntime::ObjFW:
if (L.hasSjLjExceptions())
return EHPersonality::GNU_ObjC_SJLJ;
if (L.hasSEHExceptions())
return EHPersonality::GNU_ObjC_SEH;
return EHPersonality::GNU_ObjC;
}
llvm_unreachable("bad runtime kind");
}
static const EHPersonality &getCXXPersonality(const TargetInfo &Target,
const LangOptions &L) {
const llvm::Triple &T = Target.getTriple();
if (T.isWindowsMSVCEnvironment())
return EHPersonality::MSVC_CxxFrameHandler3;
if (T.isOSAIX())
return EHPersonality::XL_CPlusPlus;
if (L.hasSjLjExceptions())
return EHPersonality::GNU_CPlusPlus_SJLJ;
if (L.hasDWARFExceptions())
return EHPersonality::GNU_CPlusPlus;
if (L.hasSEHExceptions())
return EHPersonality::GNU_CPlusPlus_SEH;
if (L.hasWasmExceptions())
return EHPersonality::GNU_Wasm_CPlusPlus;
return EHPersonality::GNU_CPlusPlus;
}
static const EHPersonality &getObjCXXPersonality(const TargetInfo &Target,
const LangOptions &L) {
if (Target.getTriple().isWindowsMSVCEnvironment())
return EHPersonality::MSVC_CxxFrameHandler3;
switch (L.ObjCRuntime.getKind()) {
case ObjCRuntime::FragileMacOSX:
return getCXXPersonality(Target, L);
case ObjCRuntime::MacOSX:
case ObjCRuntime::iOS:
case ObjCRuntime::WatchOS:
return getObjCPersonality(Target, L);
case ObjCRuntime::GNUstep:
return EHPersonality::GNU_ObjCXX;
case ObjCRuntime::GCC:
case ObjCRuntime::ObjFW:
return getObjCPersonality(Target, L);
}
llvm_unreachable("bad runtime kind");
}
static const EHPersonality &getSEHPersonalityMSVC(const llvm::Triple &T) {
if (T.getArch() == llvm::Triple::x86)
return EHPersonality::MSVC_except_handler;
return EHPersonality::MSVC_C_specific_handler;
}
const EHPersonality &EHPersonality::get(CodeGenModule &CGM,
const FunctionDecl *FD) {
const llvm::Triple &T = CGM.getTarget().getTriple();
const LangOptions &L = CGM.getLangOpts();
const TargetInfo &Target = CGM.getTarget();
if (FD && FD->usesSEHTry())
return getSEHPersonalityMSVC(T);
if (L.ObjC)
return L.CPlusPlus ? getObjCXXPersonality(Target, L)
: getObjCPersonality(Target, L);
return L.CPlusPlus ? getCXXPersonality(Target, L)
: getCPersonality(Target, L);
}
const EHPersonality &EHPersonality::get(CodeGenFunction &CGF) {
const auto *FD = CGF.CurCodeDecl;
FD = FD ? FD : CGF.CurSEHParent;
return get(CGF.CGM, dyn_cast_or_null<FunctionDecl>(FD));
}
static llvm::FunctionCallee getPersonalityFn(CodeGenModule &CGM,
const EHPersonality &Personality) {
return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
Personality.PersonalityFn,
llvm::AttributeList(), true);
}
static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
const EHPersonality &Personality) {
llvm::FunctionCallee Fn = getPersonalityFn(CGM, Personality);
llvm::PointerType* Int8PtrTy = llvm::PointerType::get(
llvm::Type::getInt8Ty(CGM.getLLVMContext()),
CGM.getDataLayout().getProgramAddressSpace());
return llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(Fn.getCallee()),
Int8PtrTy);
}
static bool LandingPadHasOnlyCXXUses(llvm::LandingPadInst *LPI) {
for (unsigned I = 0, E = LPI->getNumClauses(); I != E; ++I) {
llvm::Value *Val = LPI->getClause(I)->stripPointerCasts();
if (LPI->isCatch(I)) {
if (llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Val))
if (GV->getName().startswith("OBJC_EHTYPE"))
return false;
} else {
llvm::Constant *CVal = cast<llvm::Constant>(Val);
for (llvm::User::op_iterator
II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) {
if (llvm::GlobalVariable *GV =
cast<llvm::GlobalVariable>((*II)->stripPointerCasts()))
if (GV->getName().startswith("OBJC_EHTYPE"))
return false;
}
}
}
return true;
}
static bool PersonalityHasOnlyCXXUses(llvm::Constant *Fn) {
for (llvm::User *U : Fn->users()) {
if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(U)) {
if (CE->getOpcode() != llvm::Instruction::BitCast) return false;
if (!PersonalityHasOnlyCXXUses(CE))
return false;
continue;
}
llvm::Function *F = dyn_cast<llvm::Function>(U);
if (!F) return false;
for (auto BB = F->begin(), E = F->end(); BB != E; ++BB) {
if (BB->isLandingPad())
if (!LandingPadHasOnlyCXXUses(BB->getLandingPadInst()))
return false;
}
}
return true;
}
void CodeGenModule::SimplifyPersonality() {
if (!LangOpts.CPlusPlus || !LangOpts.ObjC || !LangOpts.Exceptions)
return;
if (!LangOpts.ObjCRuntime.isNeXTFamily())
return;
const EHPersonality &ObjCXX = EHPersonality::get(*this, nullptr);
const EHPersonality &CXX = getCXXPersonality(getTarget(), LangOpts);
if (&ObjCXX == &CXX)
return;
assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) != 0 &&
"Different EHPersonalities using the same personality function.");
llvm::Function *Fn = getModule().getFunction(ObjCXX.PersonalityFn);
if (!Fn || Fn->use_empty()) return;
if (!PersonalityHasOnlyCXXUses(Fn)) return;
llvm::FunctionCallee CXXFn = getPersonalityFn(*this, CXX);
if (Fn->getType() != CXXFn.getCallee()->getType())
return;
Fn->replaceAllUsesWith(CXXFn.getCallee());
Fn->eraseFromParent();
}
static llvm::Constant *getCatchAllValue(CodeGenFunction &CGF) {
return llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
}
namespace {
struct FreeException final : EHScopeStack::Cleanup {
llvm::Value *exn;
FreeException(llvm::Value *exn) : exn(exn) {}
void Emit(CodeGenFunction &CGF, Flags flags) override {
CGF.EmitNounwindRuntimeCall(getFreeExceptionFn(CGF.CGM), exn);
}
};
}
void CodeGenFunction::EmitAnyExprToExn(const Expr *e, Address addr) {
pushFullExprCleanup<FreeException>(EHCleanup, addr.getPointer());
EHScopeStack::stable_iterator cleanup = EHStack.stable_begin();
llvm::Type *ty = ConvertTypeForMem(e->getType());
Address typedAddr = Builder.CreateElementBitCast(addr, ty);
EmitAnyExprToMem(e, typedAddr, e->getType().getQualifiers(),
true);
DeactivateCleanupBlock(cleanup,
cast<llvm::Instruction>(typedAddr.getPointer()));
}
Address CodeGenFunction::getExceptionSlot() {
if (!ExceptionSlot)
ExceptionSlot = CreateTempAlloca(Int8PtrTy, "exn.slot");
return Address(ExceptionSlot, Int8PtrTy, getPointerAlign());
}
Address CodeGenFunction::getEHSelectorSlot() {
if (!EHSelectorSlot)
EHSelectorSlot = CreateTempAlloca(Int32Ty, "ehselector.slot");
return Address(EHSelectorSlot, Int32Ty, CharUnits::fromQuantity(4));
}
llvm::Value *CodeGenFunction::getExceptionFromSlot() {
return Builder.CreateLoad(getExceptionSlot(), "exn");
}
llvm::Value *CodeGenFunction::getSelectorFromSlot() {
return Builder.CreateLoad(getEHSelectorSlot(), "sel");
}
void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
bool KeepInsertionPoint) {
if (const Expr *SubExpr = E->getSubExpr()) {
QualType ThrowType = SubExpr->getType();
if (ThrowType->isObjCObjectPointerType()) {
const Stmt *ThrowStmt = E->getSubExpr();
const ObjCAtThrowStmt S(E->getExprLoc(), const_cast<Stmt *>(ThrowStmt));
CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
} else {
CGM.getCXXABI().emitThrow(*this, E);
}
} else {
CGM.getCXXABI().emitRethrow(*this, true);
}
if (KeepInsertionPoint)
EmitBlock(createBasicBlock("throw.cont"));
}
void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
if (!CGM.getLangOpts().CXXExceptions)
return;
const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
if (!FD) {
if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
if (CD->isNothrow())
EHStack.pushTerminate();
}
return;
}
const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
if (!Proto)
return;
ExceptionSpecificationType EST = Proto->getExceptionSpecType();
if (EST == EST_Dynamic ||
(EST == EST_DynamicNone && !getLangOpts().CPlusPlus17)) {
if (getTarget().getCXXABI().isMicrosoft())
return;
if (CGM.getLangOpts().hasWasmExceptions()) {
if (EST == EST_DynamicNone)
EHStack.pushTerminate();
else
CGM.getDiags().Report(D->getLocation(),
diag::warn_wasm_dynamic_exception_spec_ignored)
<< FD->getExceptionSpecSourceRange();
return;
}
if (getTarget().getCXXABI() == TargetCXXABI::WebAssembly &&
CGM.getLangOpts().getExceptionHandling() ==
LangOptions::ExceptionHandlingKind::None &&
EST == EST_Dynamic)
CGM.getDiags().Report(D->getLocation(),
diag::warn_wasm_dynamic_exception_spec_ignored)
<< FD->getExceptionSpecSourceRange();
unsigned NumExceptions = Proto->getNumExceptions();
EHFilterScope *Filter = EHStack.pushFilter(NumExceptions);
for (unsigned I = 0; I != NumExceptions; ++I) {
QualType Ty = Proto->getExceptionType(I);
QualType ExceptType = Ty.getNonReferenceType().getUnqualifiedType();
llvm::Value *EHType = CGM.GetAddrOfRTTIDescriptor(ExceptType,
true);
Filter->setFilter(I, EHType);
}
} else if (Proto->canThrow() == CT_Cannot) {
if (!getLangOpts().EHAsynch) EHStack.pushTerminate();
}
}
static void emitFilterDispatchBlock(CodeGenFunction &CGF,
EHFilterScope &filterScope) {
llvm::BasicBlock *dispatchBlock = filterScope.getCachedEHDispatchBlock();
if (!dispatchBlock) return;
if (dispatchBlock->use_empty()) {
delete dispatchBlock;
return;
}
CGF.EmitBlockAfterUses(dispatchBlock);
if (filterScope.getNumFilters()) {
llvm::Value *selector = CGF.getSelectorFromSlot();
llvm::BasicBlock *unexpectedBB = CGF.createBasicBlock("ehspec.unexpected");
llvm::Value *zero = CGF.Builder.getInt32(0);
llvm::Value *failsFilter =
CGF.Builder.CreateICmpSLT(selector, zero, "ehspec.fails");
CGF.Builder.CreateCondBr(failsFilter, unexpectedBB,
CGF.getEHResumeBlock(false));
CGF.EmitBlock(unexpectedBB);
}
llvm::Value *exn = CGF.getExceptionFromSlot();
CGF.EmitRuntimeCall(getUnexpectedFn(CGF.CGM), exn)
->setDoesNotReturn();
CGF.Builder.CreateUnreachable();
}
void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
if (!CGM.getLangOpts().CXXExceptions)
return;
const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(D);
if (!FD) {
if (const CapturedDecl* CD = dyn_cast_or_null<CapturedDecl>(D)) {
if (CD->isNothrow() && !EHStack.empty())
EHStack.popTerminate();
}
return;
}
const FunctionProtoType *Proto = FD->getType()->getAs<FunctionProtoType>();
if (!Proto)
return;
ExceptionSpecificationType EST = Proto->getExceptionSpecType();
if (EST == EST_Dynamic ||
(EST == EST_DynamicNone && !getLangOpts().CPlusPlus17)) {
if (getTarget().getCXXABI().isMicrosoft())
return;
if (CGM.getLangOpts().hasWasmExceptions()) {
if (EST == EST_DynamicNone)
EHStack.popTerminate();
return;
}
EHFilterScope &filterScope = cast<EHFilterScope>(*EHStack.begin());
emitFilterDispatchBlock(*this, filterScope);
EHStack.popFilter();
} else if (Proto->canThrow() == CT_Cannot &&
!EHStack.empty()) {
EHStack.popTerminate();
}
}
void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
EnterCXXTryStmt(S);
EmitStmt(S.getTryBlock());
ExitCXXTryStmt(S);
}
void CodeGenFunction::EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
unsigned NumHandlers = S.getNumHandlers();
EHCatchScope *CatchScope = EHStack.pushCatch(NumHandlers);
for (unsigned I = 0; I != NumHandlers; ++I) {
const CXXCatchStmt *C = S.getHandler(I);
llvm::BasicBlock *Handler = createBasicBlock("catch");
if (C->getExceptionDecl()) {
Qualifiers CaughtTypeQuals;
QualType CaughtType = CGM.getContext().getUnqualifiedArrayType(
C->getCaughtType().getNonReferenceType(), CaughtTypeQuals);
CatchTypeInfo TypeInfo{nullptr, 0};
if (CaughtType->isObjCObjectPointerType())
TypeInfo.RTTI = CGM.getObjCRuntime().GetEHType(CaughtType);
else
TypeInfo = CGM.getCXXABI().getAddrOfCXXCatchHandlerType(
CaughtType, C->getCaughtType());
CatchScope->setHandler(I, TypeInfo, Handler);
} else {
CatchScope->setHandler(I, CGM.getCXXABI().getCatchAllTypeInfo(), Handler);
if (getLangOpts().EHAsynch)
EmitRuntimeCallOrInvoke(getSehTryBeginFn(CGM));
}
}
}
llvm::BasicBlock *
CodeGenFunction::getEHDispatchBlock(EHScopeStack::stable_iterator si) {
if (EHPersonality::get(*this).usesFuncletPads())
return getFuncletEHDispatchBlock(si);
if (si == EHStack.stable_end())
return getEHResumeBlock(true);
EHScope &scope = *EHStack.find(si);
llvm::BasicBlock *dispatchBlock = scope.getCachedEHDispatchBlock();
if (!dispatchBlock) {
switch (scope.getKind()) {
case EHScope::Catch: {
EHCatchScope &catchScope = cast<EHCatchScope>(scope);
if (catchScope.getNumHandlers() == 1 &&
catchScope.getHandler(0).isCatchAll()) {
dispatchBlock = catchScope.getHandler(0).Block;
} else {
dispatchBlock = createBasicBlock("catch.dispatch");
}
break;
}
case EHScope::Cleanup:
dispatchBlock = createBasicBlock("ehcleanup");
break;
case EHScope::Filter:
dispatchBlock = createBasicBlock("filter.dispatch");
break;
case EHScope::Terminate:
dispatchBlock = getTerminateHandler();
break;
}
scope.setCachedEHDispatchBlock(dispatchBlock);
}
return dispatchBlock;
}
llvm::BasicBlock *
CodeGenFunction::getFuncletEHDispatchBlock(EHScopeStack::stable_iterator SI) {
if (SI == EHStack.stable_end())
return nullptr;
EHScope &EHS = *EHStack.find(SI);
llvm::BasicBlock *DispatchBlock = EHS.getCachedEHDispatchBlock();
if (DispatchBlock)
return DispatchBlock;
if (EHS.getKind() == EHScope::Terminate)
DispatchBlock = getTerminateFunclet();
else
DispatchBlock = createBasicBlock();
CGBuilderTy Builder(*this, DispatchBlock);
switch (EHS.getKind()) {
case EHScope::Catch:
DispatchBlock->setName("catch.dispatch");
break;
case EHScope::Cleanup:
DispatchBlock->setName("ehcleanup");
break;
case EHScope::Filter:
llvm_unreachable("exception specifications not handled yet!");
case EHScope::Terminate:
DispatchBlock->setName("terminate");
break;
}
EHS.setCachedEHDispatchBlock(DispatchBlock);
return DispatchBlock;
}
static bool isNonEHScope(const EHScope &S) {
switch (S.getKind()) {
case EHScope::Cleanup:
return !cast<EHCleanupScope>(S).isEHCleanup();
case EHScope::Filter:
case EHScope::Catch:
case EHScope::Terminate:
return false;
}
llvm_unreachable("Invalid EHScope Kind!");
}
llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
assert(EHStack.requiresLandingPad());
assert(!EHStack.empty());
const LangOptions &LO = CGM.getLangOpts();
if (!LO.Exceptions || LO.IgnoreExceptions) {
if (!LO.Borland && !LO.MicrosoftExt)
return nullptr;
if (!currentFunctionUsesSEHTry())
return nullptr;
}
if (LO.CUDA && LO.CUDAIsDevice)
return nullptr;
llvm::BasicBlock *LP = EHStack.begin()->getCachedLandingPad();
if (LP) return LP;
const EHPersonality &Personality = EHPersonality::get(*this);
if (!CurFn->hasPersonalityFn())
CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
if (Personality.usesFuncletPads()) {
LP = getEHDispatchBlock(EHStack.getInnermostEHScope());
} else {
LP = EmitLandingPad();
}
assert(LP);
for (EHScopeStack::iterator ir = EHStack.begin(); true; ++ir) {
ir->setCachedLandingPad(LP);
if (!isNonEHScope(*ir)) break;
}
return LP;
}
llvm::BasicBlock *CodeGenFunction::EmitLandingPad() {
assert(EHStack.requiresLandingPad());
assert(!CGM.getLangOpts().IgnoreExceptions &&
"LandingPad should not be emitted when -fignore-exceptions are in "
"effect.");
EHScope &innermostEHScope = *EHStack.find(EHStack.getInnermostEHScope());
switch (innermostEHScope.getKind()) {
case EHScope::Terminate:
return getTerminateLandingPad();
case EHScope::Catch:
case EHScope::Cleanup:
case EHScope::Filter:
if (llvm::BasicBlock *lpad = innermostEHScope.getCachedLandingPad())
return lpad;
}
CGBuilderTy::InsertPoint savedIP = Builder.saveAndClearIP();
auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, CurEHLocation);
llvm::BasicBlock *lpad = createBasicBlock("lpad");
EmitBlock(lpad);
llvm::LandingPadInst *LPadInst =
Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
llvm::Value *LPadExn = Builder.CreateExtractValue(LPadInst, 0);
Builder.CreateStore(LPadExn, getExceptionSlot());
llvm::Value *LPadSel = Builder.CreateExtractValue(LPadInst, 1);
Builder.CreateStore(LPadSel, getEHSelectorSlot());
bool hasCatchAll = false;
bool hasCleanup = false;
bool hasFilter = false;
SmallVector<llvm::Value*, 4> filterTypes;
llvm::SmallPtrSet<llvm::Value*, 4> catchTypes;
for (EHScopeStack::iterator I = EHStack.begin(), E = EHStack.end(); I != E;
++I) {
switch (I->getKind()) {
case EHScope::Cleanup:
hasCleanup = (hasCleanup || cast<EHCleanupScope>(*I).isEHCleanup());
continue;
case EHScope::Filter: {
assert(I.next() == EHStack.end() && "EH filter is not end of EH stack");
assert(!hasCatchAll && "EH filter reached after catch-all");
EHFilterScope &filter = cast<EHFilterScope>(*I);
hasFilter = true;
for (unsigned i = 0, e = filter.getNumFilters(); i != e; ++i)
filterTypes.push_back(filter.getFilter(i));
goto done;
}
case EHScope::Terminate:
assert(!hasCatchAll);
hasCatchAll = true;
goto done;
case EHScope::Catch:
break;
}
EHCatchScope &catchScope = cast<EHCatchScope>(*I);
for (unsigned hi = 0, he = catchScope.getNumHandlers(); hi != he; ++hi) {
EHCatchScope::Handler handler = catchScope.getHandler(hi);
assert(handler.Type.Flags == 0 &&
"landingpads do not support catch handler flags");
if (!handler.Type.RTTI) {
assert(!hasCatchAll);
hasCatchAll = true;
goto done;
}
if (catchTypes.insert(handler.Type.RTTI).second)
LPadInst->addClause(handler.Type.RTTI);
}
}
done:
assert(!(hasCatchAll && hasFilter));
if (hasCatchAll) {
LPadInst->addClause(getCatchAllValue(*this));
} else if (hasFilter) {
SmallVector<llvm::Constant*, 8> Filters;
llvm::ArrayType *AType =
llvm::ArrayType::get(!filterTypes.empty() ?
filterTypes[0]->getType() : Int8PtrTy,
filterTypes.size());
for (unsigned i = 0, e = filterTypes.size(); i != e; ++i)
Filters.push_back(cast<llvm::Constant>(filterTypes[i]));
llvm::Constant *FilterArray = llvm::ConstantArray::get(AType, Filters);
LPadInst->addClause(FilterArray);
if (hasCleanup)
LPadInst->setCleanup(true);
} else if (hasCleanup) {
LPadInst->setCleanup(true);
}
assert((LPadInst->getNumClauses() > 0 || LPadInst->isCleanup()) &&
"landingpad instruction has no clauses!");
Builder.CreateBr(getEHDispatchBlock(EHStack.getInnermostEHScope()));
Builder.restoreIP(savedIP);
return lpad;
}
static void emitCatchPadBlock(CodeGenFunction &CGF, EHCatchScope &CatchScope) {
llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
assert(DispatchBlock);
CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveIP();
CGF.EmitBlockAfterUses(DispatchBlock);
llvm::Value *ParentPad = CGF.CurrentFuncletPad;
if (!ParentPad)
ParentPad = llvm::ConstantTokenNone::get(CGF.getLLVMContext());
llvm::BasicBlock *UnwindBB =
CGF.getEHDispatchBlock(CatchScope.getEnclosingEHScope());
unsigned NumHandlers = CatchScope.getNumHandlers();
llvm::CatchSwitchInst *CatchSwitch =
CGF.Builder.CreateCatchSwitch(ParentPad, UnwindBB, NumHandlers);
for (unsigned I = 0; I < NumHandlers; ++I) {
const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
CatchTypeInfo TypeInfo = Handler.Type;
if (!TypeInfo.RTTI)
TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
CGF.Builder.SetInsertPoint(Handler.Block);
if (EHPersonality::get(CGF).isMSVCXXPersonality()) {
CGF.Builder.CreateCatchPad(
CatchSwitch, {TypeInfo.RTTI, CGF.Builder.getInt32(TypeInfo.Flags),
llvm::Constant::getNullValue(CGF.VoidPtrTy)});
} else {
CGF.Builder.CreateCatchPad(CatchSwitch, {TypeInfo.RTTI});
}
CatchSwitch->addHandler(Handler.Block);
}
CGF.Builder.restoreIP(SavedIP);
}
static void emitWasmCatchPadBlock(CodeGenFunction &CGF,
EHCatchScope &CatchScope) {
llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
assert(DispatchBlock);
CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveIP();
CGF.EmitBlockAfterUses(DispatchBlock);
llvm::Value *ParentPad = CGF.CurrentFuncletPad;
if (!ParentPad)
ParentPad = llvm::ConstantTokenNone::get(CGF.getLLVMContext());
llvm::BasicBlock *UnwindBB =
CGF.getEHDispatchBlock(CatchScope.getEnclosingEHScope());
unsigned NumHandlers = CatchScope.getNumHandlers();
llvm::CatchSwitchInst *CatchSwitch =
CGF.Builder.CreateCatchSwitch(ParentPad, UnwindBB, NumHandlers);
llvm::BasicBlock *WasmCatchStartBlock = CGF.createBasicBlock("catch.start");
CatchSwitch->addHandler(WasmCatchStartBlock);
CGF.EmitBlockAfterUses(WasmCatchStartBlock);
SmallVector<llvm::Value *, 4> CatchTypes;
for (unsigned I = 0, E = NumHandlers; I < E; ++I) {
const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
CatchTypeInfo TypeInfo = Handler.Type;
if (!TypeInfo.RTTI)
TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
CatchTypes.push_back(TypeInfo.RTTI);
}
auto *CPI = CGF.Builder.CreateCatchPad(CatchSwitch, CatchTypes);
llvm::Function *GetExnFn =
CGF.CGM.getIntrinsic(llvm::Intrinsic::wasm_get_exception);
llvm::Function *GetSelectorFn =
CGF.CGM.getIntrinsic(llvm::Intrinsic::wasm_get_ehselector);
llvm::CallInst *Exn = CGF.Builder.CreateCall(GetExnFn, CPI);
CGF.Builder.CreateStore(Exn, CGF.getExceptionSlot());
llvm::CallInst *Selector = CGF.Builder.CreateCall(GetSelectorFn, CPI);
llvm::Function *TypeIDFn = CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
if (CatchScope.getNumHandlers() == 1 &&
CatchScope.getHandler(0).isCatchAll()) {
CGF.Builder.CreateBr(CatchScope.getHandler(0).Block);
CGF.Builder.restoreIP(SavedIP);
return;
}
for (unsigned I = 0, E = NumHandlers;; ++I) {
assert(I < E && "ran off end of handlers!");
const EHCatchScope::Handler &Handler = CatchScope.getHandler(I);
CatchTypeInfo TypeInfo = Handler.Type;
if (!TypeInfo.RTTI)
TypeInfo.RTTI = llvm::Constant::getNullValue(CGF.VoidPtrTy);
llvm::BasicBlock *NextBlock;
bool EmitNextBlock = false, NextIsEnd = false;
if (I + 1 == E) {
NextBlock = CGF.createBasicBlock("rethrow");
EmitNextBlock = true;
NextIsEnd = true;
} else if (CatchScope.getHandler(I + 1).isCatchAll()) {
NextBlock = CatchScope.getHandler(I + 1).Block;
NextIsEnd = true;
} else {
NextBlock = CGF.createBasicBlock("catch.fallthrough");
EmitNextBlock = true;
}
llvm::CallInst *TypeIndex = CGF.Builder.CreateCall(TypeIDFn, TypeInfo.RTTI);
TypeIndex->setDoesNotThrow();
llvm::Value *MatchesTypeIndex =
CGF.Builder.CreateICmpEQ(Selector, TypeIndex, "matches");
CGF.Builder.CreateCondBr(MatchesTypeIndex, Handler.Block, NextBlock);
if (EmitNextBlock)
CGF.EmitBlock(NextBlock);
if (NextIsEnd)
break;
}
CGF.Builder.restoreIP(SavedIP);
}
static void emitCatchDispatchBlock(CodeGenFunction &CGF,
EHCatchScope &catchScope) {
if (EHPersonality::get(CGF).isWasmPersonality())
return emitWasmCatchPadBlock(CGF, catchScope);
if (EHPersonality::get(CGF).usesFuncletPads())
return emitCatchPadBlock(CGF, catchScope);
llvm::BasicBlock *dispatchBlock = catchScope.getCachedEHDispatchBlock();
assert(dispatchBlock);
if (catchScope.getNumHandlers() == 1 &&
catchScope.getHandler(0).isCatchAll()) {
assert(dispatchBlock == catchScope.getHandler(0).Block);
return;
}
CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveIP();
CGF.EmitBlockAfterUses(dispatchBlock);
llvm::Function *llvm_eh_typeid_for =
CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for);
llvm::Value *selector = CGF.getSelectorFromSlot();
for (unsigned i = 0, e = catchScope.getNumHandlers(); ; ++i) {
assert(i < e && "ran off end of handlers!");
const EHCatchScope::Handler &handler = catchScope.getHandler(i);
llvm::Value *typeValue = handler.Type.RTTI;
assert(handler.Type.Flags == 0 &&
"landingpads do not support catch handler flags");
assert(typeValue && "fell into catch-all case!");
typeValue = CGF.Builder.CreateBitCast(typeValue, CGF.Int8PtrTy);
bool nextIsEnd;
llvm::BasicBlock *nextBlock;
if (i + 1 == e) {
nextBlock = CGF.getEHDispatchBlock(catchScope.getEnclosingEHScope());
nextIsEnd = true;
} else if (catchScope.getHandler(i+1).isCatchAll()) {
nextBlock = catchScope.getHandler(i+1).Block;
nextIsEnd = true;
} else {
nextBlock = CGF.createBasicBlock("catch.fallthrough");
nextIsEnd = false;
}
llvm::CallInst *typeIndex =
CGF.Builder.CreateCall(llvm_eh_typeid_for, typeValue);
typeIndex->setDoesNotThrow();
llvm::Value *matchesTypeIndex =
CGF.Builder.CreateICmpEQ(selector, typeIndex, "matches");
CGF.Builder.CreateCondBr(matchesTypeIndex, handler.Block, nextBlock);
if (nextIsEnd) {
CGF.Builder.restoreIP(savedIP);
return;
}
CGF.EmitBlock(nextBlock);
}
}
void CodeGenFunction::popCatchScope() {
EHCatchScope &catchScope = cast<EHCatchScope>(*EHStack.begin());
if (catchScope.hasEHBranches())
emitCatchDispatchBlock(*this, catchScope);
EHStack.popCatch();
}
void CodeGenFunction::ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock) {
unsigned NumHandlers = S.getNumHandlers();
EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
assert(CatchScope.getNumHandlers() == NumHandlers);
llvm::BasicBlock *DispatchBlock = CatchScope.getCachedEHDispatchBlock();
if (!CatchScope.hasEHBranches()) {
CatchScope.clearHandlerBlocks();
EHStack.popCatch();
return;
}
emitCatchDispatchBlock(*this, CatchScope);
SmallVector<EHCatchScope::Handler, 8> Handlers(
CatchScope.begin(), CatchScope.begin() + NumHandlers);
EHStack.popCatch();
llvm::BasicBlock *ContBB = createBasicBlock("try.cont");
if (HaveInsertPoint())
Builder.CreateBr(ContBB);
bool doImplicitRethrow = false;
if (IsFnTryBlock)
doImplicitRethrow = isa<CXXDestructorDecl>(CurCodeDecl) ||
isa<CXXConstructorDecl>(CurCodeDecl);
SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
CurrentFuncletPad);
llvm::BasicBlock *WasmCatchStartBlock = nullptr;
if (EHPersonality::get(*this).isWasmPersonality()) {
auto *CatchSwitch =
cast<llvm::CatchSwitchInst>(DispatchBlock->getFirstNonPHI());
WasmCatchStartBlock = CatchSwitch->hasUnwindDest()
? CatchSwitch->getSuccessor(1)
: CatchSwitch->getSuccessor(0);
auto *CPI = cast<llvm::CatchPadInst>(WasmCatchStartBlock->getFirstNonPHI());
CurrentFuncletPad = CPI;
}
bool HasCatchAll = false;
for (unsigned I = NumHandlers; I != 0; --I) {
HasCatchAll |= Handlers[I - 1].isCatchAll();
llvm::BasicBlock *CatchBlock = Handlers[I-1].Block;
EmitBlockAfterUses(CatchBlock);
const CXXCatchStmt *C = S.getHandler(I-1);
RunCleanupsScope CatchScope(*this);
SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
CurrentFuncletPad);
CGM.getCXXABI().emitBeginCatch(*this, C);
incrementProfileCounter(C);
EmitStmt(C->getHandlerBlock());
if (doImplicitRethrow && HaveInsertPoint()) {
CGM.getCXXABI().emitRethrow(*this, false);
Builder.CreateUnreachable();
Builder.ClearInsertionPoint();
}
CatchScope.ForceCleanup();
if (HaveInsertPoint())
Builder.CreateBr(ContBB);
}
if (EHPersonality::get(*this).isWasmPersonality() && !HasCatchAll) {
assert(WasmCatchStartBlock);
llvm::BasicBlock *RethrowBlock = WasmCatchStartBlock;
while (llvm::Instruction *TI = RethrowBlock->getTerminator()) {
auto *BI = cast<llvm::BranchInst>(TI);
assert(BI->isConditional());
RethrowBlock = BI->getSuccessor(1);
}
assert(RethrowBlock != WasmCatchStartBlock && RethrowBlock->empty());
Builder.SetInsertPoint(RethrowBlock);
llvm::Function *RethrowInCatchFn =
CGM.getIntrinsic(llvm::Intrinsic::wasm_rethrow);
EmitNoreturnRuntimeCallOrInvoke(RethrowInCatchFn, {});
}
EmitBlock(ContBB);
incrementProfileCounter(&S);
}
namespace {
struct CallEndCatchForFinally final : EHScopeStack::Cleanup {
llvm::Value *ForEHVar;
llvm::FunctionCallee EndCatchFn;
CallEndCatchForFinally(llvm::Value *ForEHVar,
llvm::FunctionCallee EndCatchFn)
: ForEHVar(ForEHVar), EndCatchFn(EndCatchFn) {}
void Emit(CodeGenFunction &CGF, Flags flags) override {
llvm::BasicBlock *EndCatchBB = CGF.createBasicBlock("finally.endcatch");
llvm::BasicBlock *CleanupContBB =
CGF.createBasicBlock("finally.cleanup.cont");
llvm::Value *ShouldEndCatch =
CGF.Builder.CreateFlagLoad(ForEHVar, "finally.endcatch");
CGF.Builder.CreateCondBr(ShouldEndCatch, EndCatchBB, CleanupContBB);
CGF.EmitBlock(EndCatchBB);
CGF.EmitRuntimeCallOrInvoke(EndCatchFn); CGF.EmitBlock(CleanupContBB);
}
};
struct PerformFinally final : EHScopeStack::Cleanup {
const Stmt *Body;
llvm::Value *ForEHVar;
llvm::FunctionCallee EndCatchFn;
llvm::FunctionCallee RethrowFn;
llvm::Value *SavedExnVar;
PerformFinally(const Stmt *Body, llvm::Value *ForEHVar,
llvm::FunctionCallee EndCatchFn,
llvm::FunctionCallee RethrowFn, llvm::Value *SavedExnVar)
: Body(Body), ForEHVar(ForEHVar), EndCatchFn(EndCatchFn),
RethrowFn(RethrowFn), SavedExnVar(SavedExnVar) {}
void Emit(CodeGenFunction &CGF, Flags flags) override {
if (EndCatchFn)
CGF.EHStack.pushCleanup<CallEndCatchForFinally>(NormalAndEHCleanup,
ForEHVar, EndCatchFn);
llvm::Value *SavedCleanupDest =
CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot(),
"cleanup.dest.saved");
CGF.EmitStmt(Body);
if (CGF.HaveInsertPoint()) {
llvm::BasicBlock *RethrowBB = CGF.createBasicBlock("finally.rethrow");
llvm::BasicBlock *ContBB = CGF.createBasicBlock("finally.cont");
llvm::Value *ShouldRethrow =
CGF.Builder.CreateFlagLoad(ForEHVar, "finally.shouldthrow");
CGF.Builder.CreateCondBr(ShouldRethrow, RethrowBB, ContBB);
CGF.EmitBlock(RethrowBB);
if (SavedExnVar) {
CGF.EmitRuntimeCallOrInvoke(RethrowFn,
CGF.Builder.CreateAlignedLoad(CGF.Int8PtrTy, SavedExnVar,
CGF.getPointerAlign()));
} else {
CGF.EmitRuntimeCallOrInvoke(RethrowFn);
}
CGF.Builder.CreateUnreachable();
CGF.EmitBlock(ContBB);
CGF.Builder.CreateStore(SavedCleanupDest,
CGF.getNormalCleanupDestSlot());
}
if (EndCatchFn) {
CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
CGF.PopCleanupBlock();
CGF.Builder.restoreIP(SavedIP);
}
CGF.EnsureInsertPoint();
}
};
}
void CodeGenFunction::FinallyInfo::enter(CodeGenFunction &CGF, const Stmt *body,
llvm::FunctionCallee beginCatchFn,
llvm::FunctionCallee endCatchFn,
llvm::FunctionCallee rethrowFn) {
assert((!!beginCatchFn) == (!!endCatchFn) &&
"begin/end catch functions not paired");
assert(rethrowFn && "rethrow function is required");
BeginCatchFn = beginCatchFn;
llvm::FunctionType *rethrowFnTy = rethrowFn.getFunctionType();
SavedExnVar = nullptr;
if (rethrowFnTy->getNumParams())
SavedExnVar = CGF.CreateTempAlloca(CGF.Int8PtrTy, "finally.exn");
RethrowDest = CGF.getJumpDestInCurrentScope(CGF.getUnreachableBlock());
ForEHVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "finally.for-eh");
CGF.Builder.CreateFlagStore(false, ForEHVar);
CGF.EHStack.pushCleanup<PerformFinally>(NormalCleanup, body,
ForEHVar, endCatchFn,
rethrowFn, SavedExnVar);
llvm::BasicBlock *catchBB = CGF.createBasicBlock("finally.catchall");
EHCatchScope *catchScope = CGF.EHStack.pushCatch(1);
catchScope->setCatchAllHandler(0, catchBB);
}
void CodeGenFunction::FinallyInfo::exit(CodeGenFunction &CGF) {
EHCatchScope &catchScope = cast<EHCatchScope>(*CGF.EHStack.begin());
llvm::BasicBlock *catchBB = catchScope.getHandler(0).Block;
CGF.popCatchScope();
if (catchBB->use_empty()) {
delete catchBB;
} else {
CGBuilderTy::InsertPoint savedIP = CGF.Builder.saveAndClearIP();
CGF.EmitBlock(catchBB);
llvm::Value *exn = nullptr;
if (BeginCatchFn) {
exn = CGF.getExceptionFromSlot();
CGF.EmitNounwindRuntimeCall(BeginCatchFn, exn);
}
if (SavedExnVar) {
if (!exn) exn = CGF.getExceptionFromSlot();
CGF.Builder.CreateAlignedStore(exn, SavedExnVar, CGF.getPointerAlign());
}
CGF.Builder.CreateFlagStore(true, ForEHVar);
CGF.EmitBranchThroughCleanup(RethrowDest);
CGF.Builder.restoreIP(savedIP);
}
CGF.PopCleanupBlock();
}
llvm::BasicBlock *CodeGenFunction::getTerminateLandingPad() {
if (TerminateLandingPad)
return TerminateLandingPad;
CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
TerminateLandingPad = createBasicBlock("terminate.lpad");
Builder.SetInsertPoint(TerminateLandingPad);
const EHPersonality &Personality = EHPersonality::get(*this);
if (!CurFn->hasPersonalityFn())
CurFn->setPersonalityFn(getOpaquePersonalityFn(CGM, Personality));
llvm::LandingPadInst *LPadInst =
Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty), 0);
LPadInst->addClause(getCatchAllValue(*this));
llvm::Value *Exn = nullptr;
if (getLangOpts().CPlusPlus)
Exn = Builder.CreateExtractValue(LPadInst, 0);
llvm::CallInst *terminateCall =
CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
terminateCall->setDoesNotReturn();
Builder.CreateUnreachable();
Builder.restoreIP(SavedIP);
return TerminateLandingPad;
}
llvm::BasicBlock *CodeGenFunction::getTerminateHandler() {
if (TerminateHandler)
return TerminateHandler;
TerminateHandler = createBasicBlock("terminate.handler");
CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
Builder.SetInsertPoint(TerminateHandler);
llvm::Value *Exn = nullptr;
if (getLangOpts().CPlusPlus)
Exn = getExceptionFromSlot();
llvm::CallInst *terminateCall =
CGM.getCXXABI().emitTerminateForUnexpectedException(*this, Exn);
terminateCall->setDoesNotReturn();
Builder.CreateUnreachable();
Builder.restoreIP(SavedIP);
return TerminateHandler;
}
llvm::BasicBlock *CodeGenFunction::getTerminateFunclet() {
assert(EHPersonality::get(*this).usesFuncletPads() &&
"use getTerminateLandingPad for non-funclet EH");
llvm::BasicBlock *&TerminateFunclet = TerminateFunclets[CurrentFuncletPad];
if (TerminateFunclet)
return TerminateFunclet;
CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
TerminateFunclet = createBasicBlock("terminate.handler");
Builder.SetInsertPoint(TerminateFunclet);
SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
CurrentFuncletPad);
llvm::Value *ParentPad = CurrentFuncletPad;
if (!ParentPad)
ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
CurrentFuncletPad = Builder.CreateCleanupPad(ParentPad);
llvm::CallInst *terminateCall =
CGM.getCXXABI().emitTerminateForUnexpectedException(*this, nullptr);
terminateCall->setDoesNotReturn();
Builder.CreateUnreachable();
Builder.restoreIP(SavedIP);
return TerminateFunclet;
}
llvm::BasicBlock *CodeGenFunction::getEHResumeBlock(bool isCleanup) {
if (EHResumeBlock) return EHResumeBlock;
CGBuilderTy::InsertPoint SavedIP = Builder.saveIP();
EHResumeBlock = createBasicBlock("eh.resume");
Builder.SetInsertPoint(EHResumeBlock);
const EHPersonality &Personality = EHPersonality::get(*this);
const char *RethrowName = Personality.CatchallRethrowFn;
if (RethrowName != nullptr && !isCleanup) {
EmitRuntimeCall(getCatchallRethrowFn(CGM, RethrowName),
getExceptionFromSlot())->setDoesNotReturn();
Builder.CreateUnreachable();
Builder.restoreIP(SavedIP);
return EHResumeBlock;
}
llvm::Value *Exn = getExceptionFromSlot();
llvm::Value *Sel = getSelectorFromSlot();
llvm::Type *LPadType = llvm::StructType::get(Exn->getType(), Sel->getType());
llvm::Value *LPadVal = llvm::UndefValue::get(LPadType);
LPadVal = Builder.CreateInsertValue(LPadVal, Exn, 0, "lpad.val");
LPadVal = Builder.CreateInsertValue(LPadVal, Sel, 1, "lpad.val");
Builder.CreateResume(LPadVal);
Builder.restoreIP(SavedIP);
return EHResumeBlock;
}
void CodeGenFunction::EmitSEHTryStmt(const SEHTryStmt &S) {
EnterSEHTryStmt(S);
{
JumpDest TryExit = getJumpDestInCurrentScope("__try.__leave");
SEHTryEpilogueStack.push_back(&TryExit);
llvm::BasicBlock *TryBB = nullptr;
if (getLangOpts().EHAsynch) {
EmitRuntimeCallOrInvoke(getSehTryBeginFn(CGM));
if (SEHTryEpilogueStack.size() == 1) TryBB = Builder.GetInsertBlock();
}
EmitStmt(S.getTryBlock());
if (TryBB) {
llvm::SmallPtrSet<llvm::BasicBlock *, 10> Visited;
VolatilizeTryBlocks(TryBB, Visited);
}
SEHTryEpilogueStack.pop_back();
if (!TryExit.getBlock()->use_empty())
EmitBlock(TryExit.getBlock(), true);
else
delete TryExit.getBlock();
}
ExitSEHTryStmt(S);
}
void CodeGenFunction::VolatilizeTryBlocks(
llvm::BasicBlock *BB, llvm::SmallPtrSet<llvm::BasicBlock *, 10> &V) {
if (BB == SEHTryEpilogueStack.back()->getBlock() ||
!V.insert(BB).second ||
!BB->getParent() || BB->empty())
return;
if (!BB->isEHPad()) {
for (llvm::BasicBlock::iterator J = BB->begin(), JE = BB->end(); J != JE;
++J) {
if (auto LI = dyn_cast<llvm::LoadInst>(J)) {
LI->setVolatile(true);
} else if (auto SI = dyn_cast<llvm::StoreInst>(J)) {
SI->setVolatile(true);
} else if (auto* MCI = dyn_cast<llvm::MemIntrinsic>(J)) {
MCI->setVolatile(llvm::ConstantInt::get(Builder.getInt1Ty(), 1));
}
}
}
const llvm::Instruction *TI = BB->getTerminator();
if (TI) {
unsigned N = TI->getNumSuccessors();
for (unsigned I = 0; I < N; I++)
VolatilizeTryBlocks(TI->getSuccessor(I), V);
}
}
namespace {
struct PerformSEHFinally final : EHScopeStack::Cleanup {
llvm::Function *OutlinedFinally;
PerformSEHFinally(llvm::Function *OutlinedFinally)
: OutlinedFinally(OutlinedFinally) {}
void Emit(CodeGenFunction &CGF, Flags F) override {
ASTContext &Context = CGF.getContext();
CodeGenModule &CGM = CGF.CGM;
CallArgList Args;
QualType ArgTys[2] = {Context.UnsignedCharTy, Context.VoidPtrTy};
llvm::Value *FP = nullptr;
if (CGF.IsOutlinedSEHHelper) {
FP = &CGF.CurFn->arg_begin()[1];
} else {
llvm::Function *LocalAddrFn =
CGM.getIntrinsic(llvm::Intrinsic::localaddress);
FP = CGF.Builder.CreateCall(LocalAddrFn);
}
llvm::Value *IsForEH =
llvm::ConstantInt::get(CGF.ConvertType(ArgTys[0]), F.isForEHCleanup());
if (!F.isForEHCleanup() && F.hasExitSwitch()) {
Address Addr = CGF.getNormalCleanupDestSlot();
llvm::Value *Load = CGF.Builder.CreateLoad(Addr, "cleanup.dest");
llvm::Value *Zero = llvm::Constant::getNullValue(CGM.Int32Ty);
IsForEH = CGF.Builder.CreateICmpNE(Load, Zero);
}
Args.add(RValue::get(IsForEH), ArgTys[0]);
Args.add(RValue::get(FP), ArgTys[1]);
const CGFunctionInfo &FnInfo =
CGM.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, Args);
auto Callee = CGCallee::forDirect(OutlinedFinally);
CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
}
};
}
namespace {
struct CaptureFinder : ConstStmtVisitor<CaptureFinder> {
CodeGenFunction &ParentCGF;
const VarDecl *ParentThis;
llvm::SmallSetVector<const VarDecl *, 4> Captures;
Address SEHCodeSlot = Address::invalid();
CaptureFinder(CodeGenFunction &ParentCGF, const VarDecl *ParentThis)
: ParentCGF(ParentCGF), ParentThis(ParentThis) {}
bool foundCaptures() {
return !Captures.empty() || SEHCodeSlot.isValid();
}
void Visit(const Stmt *S) {
ConstStmtVisitor<CaptureFinder>::Visit(S);
for (const Stmt *Child : S->children())
if (Child)
Visit(Child);
}
void VisitDeclRefExpr(const DeclRefExpr *E) {
if (E->refersToEnclosingVariableOrCapture())
Captures.insert(ParentThis);
const auto *D = dyn_cast<VarDecl>(E->getDecl());
if (D && D->isLocalVarDeclOrParm() && D->hasLocalStorage())
Captures.insert(D);
}
void VisitCXXThisExpr(const CXXThisExpr *E) {
Captures.insert(ParentThis);
}
void VisitCallExpr(const CallExpr *E) {
if (ParentCGF.getTarget().getTriple().getArch() != llvm::Triple::x86)
return;
unsigned ID = E->getBuiltinCallee();
switch (ID) {
case Builtin::BI__exception_code:
case Builtin::BI_exception_code:
if (!SEHCodeSlot.isValid())
SEHCodeSlot = ParentCGF.SEHCodeSlotStack.back();
break;
}
}
};
}
Address CodeGenFunction::recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
Address ParentVar,
llvm::Value *ParentFP) {
llvm::CallInst *RecoverCall = nullptr;
CGBuilderTy Builder(*this, AllocaInsertPt);
if (auto *ParentAlloca = dyn_cast<llvm::AllocaInst>(ParentVar.getPointer())) {
auto InsertPair = ParentCGF.EscapedLocals.insert(
std::make_pair(ParentAlloca, ParentCGF.EscapedLocals.size()));
int FrameEscapeIdx = InsertPair.first->second;
llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
&CGM.getModule(), llvm::Intrinsic::localrecover);
llvm::Constant *ParentI8Fn =
llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
RecoverCall = Builder.CreateCall(
FrameRecoverFn, {ParentI8Fn, ParentFP,
llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)});
} else {
auto *ParentRecover =
cast<llvm::IntrinsicInst>(ParentVar.getPointer()->stripPointerCasts());
assert(ParentRecover->getIntrinsicID() == llvm::Intrinsic::localrecover &&
"expected alloca or localrecover in parent LocalDeclMap");
RecoverCall = cast<llvm::CallInst>(ParentRecover->clone());
RecoverCall->setArgOperand(1, ParentFP);
RecoverCall->insertBefore(AllocaInsertPt);
}
llvm::Value *ChildVar =
Builder.CreateBitCast(RecoverCall, ParentVar.getType());
ChildVar->setName(ParentVar.getName());
return ParentVar.withPointer(ChildVar);
}
void CodeGenFunction::EmitCapturedLocals(CodeGenFunction &ParentCGF,
const Stmt *OutlinedStmt,
bool IsFilter) {
CaptureFinder Finder(ParentCGF, ParentCGF.CXXABIThisDecl);
Finder.Visit(OutlinedStmt);
if (!Finder.foundCaptures() &&
CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
if (IsFilter)
EmitSEHExceptionCodeSave(ParentCGF, nullptr, nullptr);
return;
}
llvm::Value *EntryFP = nullptr;
CGBuilderTy Builder(CGM, AllocaInsertPt);
if (IsFilter && CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
EntryFP = Builder.CreateCall(
CGM.getIntrinsic(llvm::Intrinsic::frameaddress, AllocaInt8PtrTy),
{Builder.getInt32(1)});
} else {
auto AI = CurFn->arg_begin();
++AI;
EntryFP = &*AI;
}
llvm::Value *ParentFP = EntryFP;
if (IsFilter) {
llvm::Function *RecoverFPIntrin =
CGM.getIntrinsic(llvm::Intrinsic::eh_recoverfp);
llvm::Constant *ParentI8Fn =
llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
ParentFP = Builder.CreateCall(RecoverFPIntrin, {ParentI8Fn, EntryFP});
if (ParentCGF.ParentCGF != nullptr) {
llvm::AllocaInst *FramePtrAddrAlloca = nullptr;
for (auto &I : ParentCGF.LocalDeclMap) {
const VarDecl *D = cast<VarDecl>(I.first);
if (isa<ImplicitParamDecl>(D) &&
D->getType() == getContext().VoidPtrTy) {
assert(D->getName().startswith("frame_pointer"));
FramePtrAddrAlloca = cast<llvm::AllocaInst>(I.second.getPointer());
break;
}
}
assert(FramePtrAddrAlloca);
auto InsertPair = ParentCGF.EscapedLocals.insert(
std::make_pair(FramePtrAddrAlloca, ParentCGF.EscapedLocals.size()));
int FrameEscapeIdx = InsertPair.first->second;
llvm::Function *FrameRecoverFn = llvm::Intrinsic::getDeclaration(
&CGM.getModule(), llvm::Intrinsic::localrecover);
llvm::Constant *ParentI8Fn =
llvm::ConstantExpr::getBitCast(ParentCGF.CurFn, Int8PtrTy);
ParentFP = Builder.CreateCall(
FrameRecoverFn, {ParentI8Fn, ParentFP,
llvm::ConstantInt::get(Int32Ty, FrameEscapeIdx)});
ParentFP = Builder.CreateBitCast(ParentFP, CGM.VoidPtrPtrTy);
ParentFP = Builder.CreateLoad(
Address(ParentFP, CGM.VoidPtrTy, getPointerAlign()));
}
}
for (const VarDecl *VD : Finder.Captures) {
if (VD->getType()->isVariablyModifiedType()) {
CGM.ErrorUnsupported(VD, "VLA captured by SEH");
continue;
}
assert((isa<ImplicitParamDecl>(VD) || VD->isLocalVarDeclOrParm()) &&
"captured non-local variable");
auto L = ParentCGF.LambdaCaptureFields.find(VD);
if (L != ParentCGF.LambdaCaptureFields.end()) {
LambdaCaptureFields[VD] = L->second;
continue;
}
auto I = ParentCGF.LocalDeclMap.find(VD);
if (I == ParentCGF.LocalDeclMap.end())
continue;
Address ParentVar = I->second;
Address Recovered =
recoverAddrOfEscapedLocal(ParentCGF, ParentVar, ParentFP);
setAddrOfLocalVar(VD, Recovered);
if (isa<ImplicitParamDecl>(VD)) {
CXXABIThisAlignment = ParentCGF.CXXABIThisAlignment;
CXXThisAlignment = ParentCGF.CXXThisAlignment;
CXXABIThisValue = Builder.CreateLoad(Recovered, "this");
if (ParentCGF.LambdaThisCaptureField) {
LambdaThisCaptureField = ParentCGF.LambdaThisCaptureField;
LValue ThisFieldLValue =
EmitLValueForLambdaField(LambdaThisCaptureField);
if (!LambdaThisCaptureField->getType()->isPointerType()) {
CXXThisValue = ThisFieldLValue.getAddress(*this).getPointer();
} else {
CXXThisValue = EmitLoadOfLValue(ThisFieldLValue, SourceLocation())
.getScalarVal();
}
} else {
CXXThisValue = CXXABIThisValue;
}
}
}
if (Finder.SEHCodeSlot.isValid()) {
SEHCodeSlotStack.push_back(
recoverAddrOfEscapedLocal(ParentCGF, Finder.SEHCodeSlot, ParentFP));
}
if (IsFilter)
EmitSEHExceptionCodeSave(ParentCGF, ParentFP, EntryFP);
}
void CodeGenFunction::startOutlinedSEHHelper(CodeGenFunction &ParentCGF,
bool IsFilter,
const Stmt *OutlinedStmt) {
SourceLocation StartLoc = OutlinedStmt->getBeginLoc();
SmallString<128> Name;
{
llvm::raw_svector_ostream OS(Name);
const NamedDecl *ParentSEHFn = ParentCGF.CurSEHParent;
assert(ParentSEHFn && "No CurSEHParent!");
MangleContext &Mangler = CGM.getCXXABI().getMangleContext();
if (IsFilter)
Mangler.mangleSEHFilterExpression(ParentSEHFn, OS);
else
Mangler.mangleSEHFinallyBlock(ParentSEHFn, OS);
}
FunctionArgList Args;
if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 || !IsFilter) {
if (IsFilter) {
Args.push_back(ImplicitParamDecl::Create(
getContext(), nullptr, StartLoc,
&getContext().Idents.get("exception_pointers"),
getContext().VoidPtrTy, ImplicitParamDecl::Other));
} else {
Args.push_back(ImplicitParamDecl::Create(
getContext(), nullptr, StartLoc,
&getContext().Idents.get("abnormal_termination"),
getContext().UnsignedCharTy, ImplicitParamDecl::Other));
}
Args.push_back(ImplicitParamDecl::Create(
getContext(), nullptr, StartLoc,
&getContext().Idents.get("frame_pointer"), getContext().VoidPtrTy,
ImplicitParamDecl::Other));
}
QualType RetTy = IsFilter ? getContext().LongTy : getContext().VoidTy;
const CGFunctionInfo &FnInfo =
CGM.getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args);
llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
llvm::Function *Fn = llvm::Function::Create(
FnTy, llvm::GlobalValue::InternalLinkage, Name.str(), &CGM.getModule());
IsOutlinedSEHHelper = true;
StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
OutlinedStmt->getBeginLoc(), OutlinedStmt->getBeginLoc());
CurSEHParent = ParentCGF.CurSEHParent;
CGM.SetInternalFunctionAttributes(GlobalDecl(), CurFn, FnInfo);
EmitCapturedLocals(ParentCGF, OutlinedStmt, IsFilter);
}
llvm::Function *
CodeGenFunction::GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
const SEHExceptStmt &Except) {
const Expr *FilterExpr = Except.getFilterExpr();
startOutlinedSEHHelper(ParentCGF, true, FilterExpr);
llvm::Value *R = EmitScalarExpr(FilterExpr);
R = Builder.CreateIntCast(R, ConvertType(getContext().LongTy),
FilterExpr->getType()->isSignedIntegerType());
Builder.CreateStore(R, ReturnValue);
FinishFunction(FilterExpr->getEndLoc());
return CurFn;
}
llvm::Function *
CodeGenFunction::GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
const SEHFinallyStmt &Finally) {
const Stmt *FinallyBlock = Finally.getBlock();
startOutlinedSEHHelper(ParentCGF, false, FinallyBlock);
EmitStmt(FinallyBlock);
FinishFunction(FinallyBlock->getEndLoc());
return CurFn;
}
void CodeGenFunction::EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
llvm::Value *ParentFP,
llvm::Value *EntryFP) {
if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
SEHInfo = &*CurFn->arg_begin();
SEHCodeSlotStack.push_back(
CreateMemTemp(getContext().IntTy, "__exception_code"));
} else {
SEHInfo = Builder.CreateConstInBoundsGEP1_32(Int8Ty, EntryFP, -20);
SEHInfo = Builder.CreateBitCast(SEHInfo, Int8PtrTy->getPointerTo());
SEHInfo = Builder.CreateAlignedLoad(Int8PtrTy, SEHInfo, getPointerAlign());
SEHCodeSlotStack.push_back(recoverAddrOfEscapedLocal(
ParentCGF, ParentCGF.SEHCodeSlotStack.back(), ParentFP));
}
llvm::Type *RecordTy = CGM.Int32Ty->getPointerTo();
llvm::Type *PtrsTy = llvm::StructType::get(RecordTy, CGM.VoidPtrTy);
llvm::Value *Ptrs = Builder.CreateBitCast(SEHInfo, PtrsTy->getPointerTo());
llvm::Value *Rec = Builder.CreateStructGEP(PtrsTy, Ptrs, 0);
Rec = Builder.CreateAlignedLoad(RecordTy, Rec, getPointerAlign());
llvm::Value *Code = Builder.CreateAlignedLoad(Int32Ty, Rec, getIntAlign());
assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
Builder.CreateStore(Code, SEHCodeSlotStack.back());
}
llvm::Value *CodeGenFunction::EmitSEHExceptionInfo() {
if (!SEHInfo)
return llvm::UndefValue::get(Int8PtrTy);
assert(SEHInfo->getType() == Int8PtrTy);
return SEHInfo;
}
llvm::Value *CodeGenFunction::EmitSEHExceptionCode() {
assert(!SEHCodeSlotStack.empty() && "emitting EH code outside of __except");
return Builder.CreateLoad(SEHCodeSlotStack.back());
}
llvm::Value *CodeGenFunction::EmitSEHAbnormalTermination() {
auto AI = CurFn->arg_begin();
return Builder.CreateZExt(&*AI, Int32Ty);
}
void CodeGenFunction::pushSEHCleanup(CleanupKind Kind,
llvm::Function *FinallyFunc) {
EHStack.pushCleanup<PerformSEHFinally>(Kind, FinallyFunc);
}
void CodeGenFunction::EnterSEHTryStmt(const SEHTryStmt &S) {
CodeGenFunction HelperCGF(CGM, true);
HelperCGF.ParentCGF = this;
if (const SEHFinallyStmt *Finally = S.getFinallyHandler()) {
llvm::Function *FinallyFunc =
HelperCGF.GenerateSEHFinallyFunction(*this, *Finally);
EHStack.pushCleanup<PerformSEHFinally>(NormalAndEHCleanup, FinallyFunc);
return;
}
const SEHExceptStmt *Except = S.getExceptHandler();
assert(Except);
EHCatchScope *CatchScope = EHStack.pushCatch(1);
SEHCodeSlotStack.push_back(
CreateMemTemp(getContext().IntTy, "__exception_code"));
llvm::Constant *C =
ConstantEmitter(*this).tryEmitAbstract(Except->getFilterExpr(),
getContext().IntTy);
if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86 && C &&
C->isOneValue()) {
CatchScope->setCatchAllHandler(0, createBasicBlock("__except"));
return;
}
llvm::Function *FilterFunc =
HelperCGF.GenerateSEHFilterFunction(*this, *Except);
llvm::Constant *OpaqueFunc =
llvm::ConstantExpr::getBitCast(FilterFunc, Int8PtrTy);
CatchScope->setHandler(0, OpaqueFunc, createBasicBlock("__except.ret"));
}
void CodeGenFunction::ExitSEHTryStmt(const SEHTryStmt &S) {
if (S.getFinallyHandler()) {
PopCleanupBlock();
return;
}
if (getLangOpts().EHAsynch && Builder.GetInsertBlock()) {
llvm::FunctionCallee SehTryEnd = getSehTryEndFn(CGM);
EmitRuntimeCallOrInvoke(SehTryEnd);
}
const SEHExceptStmt *Except = S.getExceptHandler();
assert(Except && "__try must have __finally xor __except");
EHCatchScope &CatchScope = cast<EHCatchScope>(*EHStack.begin());
if (!CatchScope.hasEHBranches()) {
CatchScope.clearHandlerBlocks();
EHStack.popCatch();
SEHCodeSlotStack.pop_back();
return;
}
llvm::BasicBlock *ContBB = createBasicBlock("__try.cont");
if (HaveInsertPoint())
Builder.CreateBr(ContBB);
emitCatchDispatchBlock(*this, CatchScope);
llvm::BasicBlock *CatchPadBB = CatchScope.getHandler(0).Block;
EHStack.popCatch();
EmitBlockAfterUses(CatchPadBB);
llvm::CatchPadInst *CPI =
cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
llvm::BasicBlock *ExceptBB = createBasicBlock("__except");
Builder.CreateCatchRet(CPI, ExceptBB);
EmitBlock(ExceptBB);
if (CGM.getTarget().getTriple().getArch() != llvm::Triple::x86) {
llvm::Function *SEHCodeIntrin =
CGM.getIntrinsic(llvm::Intrinsic::eh_exceptioncode);
llvm::Value *Code = Builder.CreateCall(SEHCodeIntrin, {CPI});
Builder.CreateStore(Code, SEHCodeSlotStack.back());
}
EmitStmt(Except->getBlock());
SEHCodeSlotStack.pop_back();
if (HaveInsertPoint())
Builder.CreateBr(ContBB);
EmitBlock(ContBB);
}
void CodeGenFunction::EmitSEHLeaveStmt(const SEHLeaveStmt &S) {
if (HaveInsertPoint())
EmitStopPoint(&S);
if (!isSEHTryScope()) {
Builder.CreateUnreachable();
Builder.ClearInsertionPoint();
return;
}
EmitBranchThroughCleanup(*SEHTryEpilogueStack.back());
}