#include "CGBlocks.h"
#include "CGCXXABI.h"
#include "CGCleanup.h"
#include "CGDebugInfo.h"
#include "CGOpenCLRuntime.h"
#include "CGOpenMPRuntime.h"
#include "CodeGenFunction.h"
#include "CodeGenModule.h"
#include "ConstantEmitter.h"
#include "PatternInit.h"
#include "TargetInfo.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Attr.h"
#include "clang/AST/CharUnits.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DeclOpenMP.h"
#include "clang/Basic/CodeGenOptions.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/CodeGen/CGFunctionInfo.h"
#include "clang/Sema/Sema.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Type.h"
using namespace clang;
using namespace CodeGen;
static_assert(clang::Sema::MaximumAlignment <= llvm::Value::MaximumAlignment,
"Clang max alignment greater than what LLVM supports?");
void CodeGenFunction::EmitDecl(const Decl &D) {
switch (D.getKind()) {
case Decl::BuiltinTemplate:
case Decl::TranslationUnit:
case Decl::ExternCContext:
case Decl::Namespace:
case Decl::UnresolvedUsingTypename:
case Decl::ClassTemplateSpecialization:
case Decl::ClassTemplatePartialSpecialization:
case Decl::VarTemplateSpecialization:
case Decl::VarTemplatePartialSpecialization:
case Decl::TemplateTypeParm:
case Decl::UnresolvedUsingValue:
case Decl::NonTypeTemplateParm:
case Decl::CXXDeductionGuide:
case Decl::CXXMethod:
case Decl::CXXConstructor:
case Decl::CXXDestructor:
case Decl::CXXConversion:
case Decl::Field:
case Decl::MSProperty:
case Decl::IndirectField:
case Decl::ObjCIvar:
case Decl::ObjCAtDefsField:
case Decl::ParmVar:
case Decl::ImplicitParam:
case Decl::ClassTemplate:
case Decl::VarTemplate:
case Decl::FunctionTemplate:
case Decl::TypeAliasTemplate:
case Decl::TemplateTemplateParm:
case Decl::ObjCMethod:
case Decl::ObjCCategory:
case Decl::ObjCProtocol:
case Decl::ObjCInterface:
case Decl::ObjCCategoryImpl:
case Decl::ObjCImplementation:
case Decl::ObjCProperty:
case Decl::ObjCCompatibleAlias:
case Decl::PragmaComment:
case Decl::PragmaDetectMismatch:
case Decl::AccessSpec:
case Decl::LinkageSpec:
case Decl::Export:
case Decl::ObjCPropertyImpl:
case Decl::FileScopeAsm:
case Decl::Friend:
case Decl::FriendTemplate:
case Decl::Block:
case Decl::Captured:
case Decl::ClassScopeFunctionSpecialization:
case Decl::UsingShadow:
case Decl::ConstructorUsingShadow:
case Decl::ObjCTypeParam:
case Decl::Binding:
case Decl::UnresolvedUsingIfExists:
llvm_unreachable("Declaration should not be in declstmts!");
case Decl::Record: case Decl::CXXRecord: if (CGDebugInfo *DI = getDebugInfo())
if (cast<RecordDecl>(D).getDefinition())
DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(&D)));
return;
case Decl::Enum: if (CGDebugInfo *DI = getDebugInfo())
if (cast<EnumDecl>(D).getDefinition())
DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(&D)));
return;
case Decl::Function: case Decl::EnumConstant: case Decl::StaticAssert: case Decl::Label: case Decl::Import:
case Decl::MSGuid: case Decl::UnnamedGlobalConstant:
case Decl::TemplateParamObject:
case Decl::OMPThreadPrivate:
case Decl::OMPAllocate:
case Decl::OMPCapturedExpr:
case Decl::OMPRequires:
case Decl::Empty:
case Decl::Concept:
case Decl::LifetimeExtendedTemporary:
case Decl::RequiresExprBody:
return;
case Decl::NamespaceAlias:
if (CGDebugInfo *DI = getDebugInfo())
DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
return;
case Decl::Using: if (CGDebugInfo *DI = getDebugInfo())
DI->EmitUsingDecl(cast<UsingDecl>(D));
return;
case Decl::UsingEnum: if (CGDebugInfo *DI = getDebugInfo())
DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(D));
return;
case Decl::UsingPack:
for (auto *Using : cast<UsingPackDecl>(D).expansions())
EmitDecl(*Using);
return;
case Decl::UsingDirective: if (CGDebugInfo *DI = getDebugInfo())
DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
return;
case Decl::Var:
case Decl::Decomposition: {
const VarDecl &VD = cast<VarDecl>(D);
assert(VD.isLocalVarDecl() &&
"Should not see file-scope variables inside a function!");
EmitVarDecl(VD);
if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
for (auto *B : DD->bindings())
if (auto *HD = B->getHoldingVar())
EmitVarDecl(*HD);
return;
}
case Decl::OMPDeclareReduction:
return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
case Decl::OMPDeclareMapper:
return CGM.EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(&D), this);
case Decl::Typedef: case Decl::TypeAlias: { QualType Ty = cast<TypedefNameDecl>(D).getUnderlyingType();
if (CGDebugInfo *DI = getDebugInfo())
DI->EmitAndRetainType(Ty);
if (Ty->isVariablyModifiedType())
EmitVariablyModifiedType(Ty);
return;
}
}
}
void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
if (D.hasExternalStorage())
return;
if (D.getStorageDuration() != SD_Automatic) {
if (D.getType()->isSamplerT())
return;
llvm::GlobalValue::LinkageTypes Linkage =
CGM.getLLVMLinkageVarDefinition(&D, false);
return EmitStaticVarDecl(D, Linkage);
}
if (D.getType().getAddressSpace() == LangAS::opencl_local)
return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
assert(D.hasLocalStorage());
return EmitAutoVarDecl(D);
}
static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
if (CGM.getLangOpts().CPlusPlus)
return CGM.getMangledName(&D).str();
assert(!D.isExternallyVisible() && "name shouldn't matter");
std::string ContextName;
const DeclContext *DC = D.getDeclContext();
if (auto *CD = dyn_cast<CapturedDecl>(DC))
DC = cast<DeclContext>(CD->getNonClosureContext());
if (const auto *FD = dyn_cast<FunctionDecl>(DC))
ContextName = std::string(CGM.getMangledName(FD));
else if (const auto *BD = dyn_cast<BlockDecl>(DC))
ContextName = std::string(CGM.getBlockMangledName(GlobalDecl(), BD));
else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
ContextName = OMD->getSelector().getAsString();
else
llvm_unreachable("Unknown context for static var decl");
ContextName += "." + D.getNameAsString();
return ContextName;
}
llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
return ExistingGV;
QualType Ty = D.getType();
assert(Ty->isConstantSizeType() && "VLAs can't be static");
std::string Name;
if (D.hasAttr<AsmLabelAttr>())
Name = std::string(getMangledName(&D));
else
Name = getStaticDeclName(*this, D);
llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
LangAS AS = GetGlobalVarAddressSpace(&D);
unsigned TargetAS = getContext().getTargetAddressSpace(AS);
llvm::Constant *Init = nullptr;
if (Ty.getAddressSpace() == LangAS::opencl_local ||
D.hasAttr<CUDASharedAttr>() || D.hasAttr<LoaderUninitializedAttr>())
Init = llvm::UndefValue::get(LTy);
else
Init = EmitNullConstant(Ty);
llvm::GlobalVariable *GV = new llvm::GlobalVariable(
getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name,
nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
GV->setAlignment(getContext().getDeclAlign(&D).getAsAlign());
if (supportsCOMDAT() && GV->isWeakForLinker())
GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
if (D.getTLSKind())
setTLSMode(GV, D);
setGVProperties(GV, &D);
LangAS ExpectedAS = Ty.getAddressSpace();
llvm::Constant *Addr = GV;
if (AS != ExpectedAS) {
Addr = getTargetCodeGenInfo().performAddrSpaceCast(
*this, GV, AS, ExpectedAS,
LTy->getPointerTo(getContext().getTargetAddressSpace(ExpectedAS)));
}
setStaticLocalDeclAddress(&D, Addr);
const Decl *DC = cast<Decl>(D.getDeclContext());
if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
DC = DC->getNonClosureContext();
if (!DC)
return Addr;
}
GlobalDecl GD;
if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
GD = GlobalDecl(CD, Ctor_Base);
else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
GD = GlobalDecl(DD, Dtor_Base);
else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
GD = GlobalDecl(FD);
else {
assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
}
if (GD.getDecl()) {
CGOpenMPRuntime::DisableAutoDeclareTargetRAII NoDeclTarget(*this);
(void)GetAddrOfGlobal(GD);
}
return Addr;
}
llvm::GlobalVariable *
CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
llvm::GlobalVariable *GV) {
ConstantEmitter emitter(*this);
llvm::Constant *Init = emitter.tryEmitForInitializer(D);
if (!Init) {
if (!getLangOpts().CPlusPlus)
CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
else if (D.hasFlexibleArrayInit(getContext()))
CGM.ErrorUnsupported(D.getInit(), "flexible array initializer");
else if (HaveInsertPoint()) {
GV->setConstant(false);
EmitCXXGuardedInit(D, GV, true);
}
return GV;
}
#ifndef NDEBUG
CharUnits VarSize = CGM.getContext().getTypeSizeInChars(D.getType()) +
D.getFlexibleArrayInitChars(getContext());
CharUnits CstSize = CharUnits::fromQuantity(
CGM.getDataLayout().getTypeAllocSize(Init->getType()));
assert(VarSize == CstSize && "Emitted constant has unexpected size");
#endif
if (GV->getValueType() != Init->getType()) {
llvm::GlobalVariable *OldGV = GV;
GV = new llvm::GlobalVariable(
CGM.getModule(), Init->getType(), OldGV->isConstant(),
OldGV->getLinkage(), Init, "",
OldGV, OldGV->getThreadLocalMode(),
OldGV->getType()->getPointerAddressSpace());
GV->setVisibility(OldGV->getVisibility());
GV->setDSOLocal(OldGV->isDSOLocal());
GV->setComdat(OldGV->getComdat());
GV->takeName(OldGV);
llvm::Constant *NewPtrForOldDecl =
llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
OldGV->replaceAllUsesWith(NewPtrForOldDecl);
OldGV->eraseFromParent();
}
GV->setConstant(CGM.isTypeConstant(D.getType(), true));
GV->setInitializer(Init);
emitter.finalize(GV);
if (D.needsDestruction(getContext()) == QualType::DK_cxx_destructor &&
HaveInsertPoint()) {
EmitCXXGuardedInit(D, GV, false);
}
return GV;
}
void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
llvm::GlobalValue::LinkageTypes Linkage) {
llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
CharUnits alignment = getContext().getDeclAlign(&D);
llvm::Type *elemTy = ConvertTypeForMem(D.getType());
setAddrOfLocalVar(&D, Address(addr, elemTy, alignment));
if (D.getType()->isVariablyModifiedType())
EmitVariablyModifiedType(D.getType());
llvm::Type *expectedType = addr->getType();
llvm::GlobalVariable *var =
cast<llvm::GlobalVariable>(addr->stripPointerCasts());
bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
D.hasAttr<CUDASharedAttr>();
if (D.getInit() && !isCudaSharedVar)
var = AddInitializerToStaticVarDecl(D, var);
var->setAlignment(alignment.getAsAlign());
if (D.hasAttr<AnnotateAttr>())
CGM.AddGlobalAnnotations(&D, var);
if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>())
var->addAttribute("bss-section", SA->getName());
if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>())
var->addAttribute("data-section", SA->getName());
if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>())
var->addAttribute("rodata-section", SA->getName());
if (auto *SA = D.getAttr<PragmaClangRelroSectionAttr>())
var->addAttribute("relro-section", SA->getName());
if (const SectionAttr *SA = D.getAttr<SectionAttr>())
var->setSection(SA->getName());
if (D.hasAttr<RetainAttr>())
CGM.addUsedGlobal(var);
else if (D.hasAttr<UsedAttr>())
CGM.addUsedOrCompilerUsedGlobal(var);
llvm::Constant *castedAddr =
llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
LocalDeclMap.find(&D)->second = Address(castedAddr, elemTy, alignment);
CGM.setStaticLocalDeclAddress(&D, castedAddr);
CGM.getSanitizerMetadata()->reportGlobal(var, D);
CGDebugInfo *DI = getDebugInfo();
if (DI && CGM.getCodeGenOpts().hasReducedDebugInfo()) {
DI->setLocation(D.getLocation());
DI->EmitGlobalVariable(var, &D);
}
}
namespace {
struct DestroyObject final : EHScopeStack::Cleanup {
DestroyObject(Address addr, QualType type,
CodeGenFunction::Destroyer *destroyer,
bool useEHCleanupForArray)
: addr(addr), type(type), destroyer(destroyer),
useEHCleanupForArray(useEHCleanupForArray) {}
Address addr;
QualType type;
CodeGenFunction::Destroyer *destroyer;
bool useEHCleanupForArray;
void Emit(CodeGenFunction &CGF, Flags flags) override {
bool useEHCleanupForArray =
flags.isForNormalCleanup() && this->useEHCleanupForArray;
CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
}
};
template <class Derived>
struct DestroyNRVOVariable : EHScopeStack::Cleanup {
DestroyNRVOVariable(Address addr, QualType type, llvm::Value *NRVOFlag)
: NRVOFlag(NRVOFlag), Loc(addr), Ty(type) {}
llvm::Value *NRVOFlag;
Address Loc;
QualType Ty;
void Emit(CodeGenFunction &CGF, Flags flags) override {
bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
llvm::BasicBlock *SkipDtorBB = nullptr;
if (NRVO) {
llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
llvm::Value *DidNRVO =
CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
CGF.EmitBlock(RunDtorBB);
}
static_cast<Derived *>(this)->emitDestructorCall(CGF);
if (NRVO) CGF.EmitBlock(SkipDtorBB);
}
virtual ~DestroyNRVOVariable() = default;
};
struct DestroyNRVOVariableCXX final
: DestroyNRVOVariable<DestroyNRVOVariableCXX> {
DestroyNRVOVariableCXX(Address addr, QualType type,
const CXXDestructorDecl *Dtor, llvm::Value *NRVOFlag)
: DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, type, NRVOFlag),
Dtor(Dtor) {}
const CXXDestructorDecl *Dtor;
void emitDestructorCall(CodeGenFunction &CGF) {
CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
false,
false, Loc, Ty);
}
};
struct DestroyNRVOVariableC final
: DestroyNRVOVariable<DestroyNRVOVariableC> {
DestroyNRVOVariableC(Address addr, llvm::Value *NRVOFlag, QualType Ty)
: DestroyNRVOVariable<DestroyNRVOVariableC>(addr, Ty, NRVOFlag) {}
void emitDestructorCall(CodeGenFunction &CGF) {
CGF.destroyNonTrivialCStruct(CGF, Loc, Ty);
}
};
struct CallStackRestore final : EHScopeStack::Cleanup {
Address Stack;
CallStackRestore(Address Stack) : Stack(Stack) {}
bool isRedundantBeforeReturn() override { return true; }
void Emit(CodeGenFunction &CGF, Flags flags) override {
llvm::Value *V = CGF.Builder.CreateLoad(Stack);
llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
CGF.Builder.CreateCall(F, V);
}
};
struct ExtendGCLifetime final : EHScopeStack::Cleanup {
const VarDecl &Var;
ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
void Emit(CodeGenFunction &CGF, Flags flags) override {
DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
Var.getType(), VK_LValue, SourceLocation());
llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
SourceLocation());
CGF.EmitExtendGCLifetime(value);
}
};
struct CallCleanupFunction final : EHScopeStack::Cleanup {
llvm::Constant *CleanupFn;
const CGFunctionInfo &FnInfo;
const VarDecl &Var;
CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
const VarDecl *Var)
: CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
void Emit(CodeGenFunction &CGF, Flags flags) override {
DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
Var.getType(), VK_LValue, SourceLocation());
llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer(CGF);
QualType ArgTy = FnInfo.arg_begin()->type;
llvm::Value *Arg =
CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
CallArgList Args;
Args.add(RValue::get(Arg),
CGF.getContext().getPointerType(Var.getType()));
auto Callee = CGCallee::forDirect(CleanupFn);
CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
}
};
}
static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
Address addr,
Qualifiers::ObjCLifetime lifetime) {
switch (lifetime) {
case Qualifiers::OCL_None:
llvm_unreachable("present but none");
case Qualifiers::OCL_ExplicitNone:
break;
case Qualifiers::OCL_Strong: {
CodeGenFunction::Destroyer *destroyer =
(var.hasAttr<ObjCPreciseLifetimeAttr>()
? CodeGenFunction::destroyARCStrongPrecise
: CodeGenFunction::destroyARCStrongImprecise);
CleanupKind cleanupKind = CGF.getARCCleanupKind();
CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
cleanupKind & EHCleanup);
break;
}
case Qualifiers::OCL_Autoreleasing:
break;
case Qualifiers::OCL_Weak:
CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
CodeGenFunction::destroyARCWeak,
true);
break;
}
}
static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
if (const Expr *e = dyn_cast<Expr>(s)) {
s = e = e->IgnoreParenCasts();
if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
return (ref->getDecl() == &var);
if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
const BlockDecl *block = be->getBlockDecl();
for (const auto &I : block->captures()) {
if (I.getVariable() == &var)
return true;
}
}
}
for (const Stmt *SubStmt : s->children())
if (SubStmt && isAccessedBy(var, SubStmt))
return true;
return false;
}
static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
if (!decl) return false;
if (!isa<VarDecl>(decl)) return false;
const VarDecl *var = cast<VarDecl>(decl);
return isAccessedBy(*var, e);
}
static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
const LValue &destLV, const Expr *init) {
bool needsCast = false;
while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
switch (castExpr->getCastKind()) {
case CK_NoOp:
case CK_BitCast:
case CK_BlockPointerToObjCPointerCast:
needsCast = true;
break;
case CK_LValueToRValue: {
const Expr *srcExpr = castExpr->getSubExpr();
if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
return false;
LValue srcLV = CGF.EmitLValue(srcExpr);
auto srcAddr = srcLV.getAddress(CGF);
if (needsCast) {
srcAddr = CGF.Builder.CreateElementBitCast(
srcAddr, destLV.getAddress(CGF).getElementType());
}
if (srcExpr->isLValue()) {
CGF.EmitARCCopyWeak(destLV.getAddress(CGF), srcAddr);
} else {
assert(srcExpr->isXValue());
CGF.EmitARCMoveWeak(destLV.getAddress(CGF), srcAddr);
}
return true;
}
default:
return false;
}
init = castExpr->getSubExpr();
}
return false;
}
static void drillIntoBlockVariable(CodeGenFunction &CGF,
LValue &lvalue,
const VarDecl *var) {
lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(CGF), var));
}
void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
SourceLocation Loc) {
if (!SanOpts.has(SanitizerKind::NullabilityAssign))
return;
auto Nullability = LHS.getType()->getNullability(getContext());
if (!Nullability || *Nullability != NullabilityKind::NonNull)
return;
SanitizerScope SanScope(this);
llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);
llvm::Constant *StaticData[] = {
EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()),
llvm::ConstantInt::get(Int8Ty, 0), llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};
EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}},
SanitizerHandler::TypeMismatch, StaticData, RHS);
}
void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
LValue lvalue, bool capturedByInit) {
Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
if (!lifetime) {
llvm::Value *value = EmitScalarExpr(init);
if (capturedByInit)
drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
EmitNullabilityCheck(lvalue, value, init->getExprLoc());
EmitStoreThroughLValue(RValue::get(value), lvalue, true);
return;
}
if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
init = DIE->getExpr();
if (auto *EWC = dyn_cast<ExprWithCleanups>(init)) {
CodeGenFunction::RunCleanupsScope Scope(*this);
return EmitScalarInit(EWC->getSubExpr(), D, lvalue, capturedByInit);
}
bool accessedByInit = false;
if (lifetime != Qualifiers::OCL_ExplicitNone)
accessedByInit = (capturedByInit || isAccessedBy(D, init));
if (accessedByInit) {
LValue tempLV = lvalue;
if (capturedByInit) {
tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(*this),
cast<VarDecl>(D),
false));
}
auto ty =
cast<llvm::PointerType>(tempLV.getAddress(*this).getElementType());
llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
if (lifetime == Qualifiers::OCL_Weak)
EmitARCInitWeak(tempLV.getAddress(*this), zero);
else
EmitStoreOfScalar(zero, tempLV, true);
}
llvm::Value *value = nullptr;
switch (lifetime) {
case Qualifiers::OCL_None:
llvm_unreachable("present but none");
case Qualifiers::OCL_Strong: {
if (!D || !isa<VarDecl>(D) || !cast<VarDecl>(D)->isARCPseudoStrong()) {
value = EmitARCRetainScalarExpr(init);
break;
}
LLVM_FALLTHROUGH;
}
case Qualifiers::OCL_ExplicitNone:
value = EmitARCUnsafeUnretainedScalarExpr(init);
break;
case Qualifiers::OCL_Weak: {
if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
return;
}
value = EmitScalarExpr(init);
if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
if (accessedByInit)
EmitARCStoreWeak(lvalue.getAddress(*this), value, true);
else
EmitARCInitWeak(lvalue.getAddress(*this), value);
return;
}
case Qualifiers::OCL_Autoreleasing:
value = EmitARCRetainAutoreleaseScalarExpr(init);
break;
}
if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
EmitNullabilityCheck(lvalue, value, init->getExprLoc());
if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
EmitStoreOfScalar(value, lvalue, true);
EmitARCRelease(oldValue, ARCImpreciseLifetime);
return;
}
EmitStoreOfScalar(value, lvalue, true);
}
static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init,
unsigned &NumStores) {
if (isa<llvm::ConstantAggregateZero>(Init) ||
isa<llvm::ConstantPointerNull>(Init) ||
isa<llvm::UndefValue>(Init))
return true;
if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
isa<llvm::ConstantExpr>(Init))
return Init->isNullValue() || NumStores--;
if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
return false;
}
return true;
}
if (llvm::ConstantDataSequential *CDS =
dyn_cast<llvm::ConstantDataSequential>(Init)) {
for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
llvm::Constant *Elt = CDS->getElementAsConstant(i);
if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
return false;
}
return true;
}
return false;
}
static void emitStoresForInitAfterBZero(CodeGenModule &CGM,
llvm::Constant *Init, Address Loc,
bool isVolatile, CGBuilderTy &Builder,
bool IsAutoInit) {
assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
"called emitStoresForInitAfterBZero for zero or undef value.");
if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
isa<llvm::ConstantExpr>(Init)) {
auto *I = Builder.CreateStore(Init, Loc, isVolatile);
if (IsAutoInit)
I->addAnnotationMetadata("auto-init");
return;
}
if (llvm::ConstantDataSequential *CDS =
dyn_cast<llvm::ConstantDataSequential>(Init)) {
for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
llvm::Constant *Elt = CDS->getElementAsConstant(i);
if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
emitStoresForInitAfterBZero(
CGM, Elt, Builder.CreateConstInBoundsGEP2_32(Loc, 0, i), isVolatile,
Builder, IsAutoInit);
}
return;
}
assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
"Unknown value type!");
for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
emitStoresForInitAfterBZero(CGM, Elt,
Builder.CreateConstInBoundsGEP2_32(Loc, 0, i),
isVolatile, Builder, IsAutoInit);
}
}
static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init,
uint64_t GlobalSize) {
if (isa<llvm::ConstantAggregateZero>(Init)) return true;
unsigned StoreBudget = 6;
uint64_t SizeLimit = 32;
return GlobalSize > SizeLimit &&
canEmitInitWithFewStoresAfterBZero(Init, StoreBudget);
}
static llvm::Value *shouldUseMemSetToInitialize(llvm::Constant *Init,
uint64_t GlobalSize,
const llvm::DataLayout &DL) {
uint64_t SizeLimit = 32;
if (GlobalSize <= SizeLimit)
return nullptr;
return llvm::isBytewiseValue(Init, DL);
}
static bool shouldSplitConstantStore(CodeGenModule &CGM,
uint64_t GlobalByteSize) {
uint64_t ByteSizeLimit = 64;
if (CGM.getCodeGenOpts().OptimizationLevel == 0)
return false;
if (GlobalByteSize <= ByteSizeLimit)
return true;
return false;
}
enum class IsPattern { No, Yes };
static llvm::Constant *patternOrZeroFor(CodeGenModule &CGM, IsPattern isPattern,
llvm::Type *Ty) {
if (isPattern == IsPattern::Yes)
return initializationPatternFor(CGM, Ty);
else
return llvm::Constant::getNullValue(Ty);
}
static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
llvm::Constant *constant);
static llvm::Constant *constStructWithPadding(CodeGenModule &CGM,
IsPattern isPattern,
llvm::StructType *STy,
llvm::Constant *constant) {
const llvm::DataLayout &DL = CGM.getDataLayout();
const llvm::StructLayout *Layout = DL.getStructLayout(STy);
llvm::Type *Int8Ty = llvm::IntegerType::getInt8Ty(CGM.getLLVMContext());
unsigned SizeSoFar = 0;
SmallVector<llvm::Constant *, 8> Values;
bool NestedIntact = true;
for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
unsigned CurOff = Layout->getElementOffset(i);
if (SizeSoFar < CurOff) {
assert(!STy->isPacked());
auto *PadTy = llvm::ArrayType::get(Int8Ty, CurOff - SizeSoFar);
Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
}
llvm::Constant *CurOp;
if (constant->isZeroValue())
CurOp = llvm::Constant::getNullValue(STy->getElementType(i));
else
CurOp = cast<llvm::Constant>(constant->getAggregateElement(i));
auto *NewOp = constWithPadding(CGM, isPattern, CurOp);
if (CurOp != NewOp)
NestedIntact = false;
Values.push_back(NewOp);
SizeSoFar = CurOff + DL.getTypeAllocSize(CurOp->getType());
}
unsigned TotalSize = Layout->getSizeInBytes();
if (SizeSoFar < TotalSize) {
auto *PadTy = llvm::ArrayType::get(Int8Ty, TotalSize - SizeSoFar);
Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
}
if (NestedIntact && Values.size() == STy->getNumElements())
return constant;
return llvm::ConstantStruct::getAnon(Values, STy->isPacked());
}
static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
llvm::Constant *constant) {
llvm::Type *OrigTy = constant->getType();
if (const auto STy = dyn_cast<llvm::StructType>(OrigTy))
return constStructWithPadding(CGM, isPattern, STy, constant);
if (auto *ArrayTy = dyn_cast<llvm::ArrayType>(OrigTy)) {
llvm::SmallVector<llvm::Constant *, 8> Values;
uint64_t Size = ArrayTy->getNumElements();
if (!Size)
return constant;
llvm::Type *ElemTy = ArrayTy->getElementType();
bool ZeroInitializer = constant->isNullValue();
llvm::Constant *OpValue, *PaddedOp;
if (ZeroInitializer) {
OpValue = llvm::Constant::getNullValue(ElemTy);
PaddedOp = constWithPadding(CGM, isPattern, OpValue);
}
for (unsigned Op = 0; Op != Size; ++Op) {
if (!ZeroInitializer) {
OpValue = constant->getAggregateElement(Op);
PaddedOp = constWithPadding(CGM, isPattern, OpValue);
}
Values.push_back(PaddedOp);
}
auto *NewElemTy = Values[0]->getType();
if (NewElemTy == ElemTy)
return constant;
auto *NewArrayTy = llvm::ArrayType::get(NewElemTy, Size);
return llvm::ConstantArray::get(NewArrayTy, Values);
}
return constant;
}
Address CodeGenModule::createUnnamedGlobalFrom(const VarDecl &D,
llvm::Constant *Constant,
CharUnits Align) {
auto FunctionName = [&](const DeclContext *DC) -> std::string {
if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
if (const auto *CC = dyn_cast<CXXConstructorDecl>(FD))
return CC->getNameAsString();
if (const auto *CD = dyn_cast<CXXDestructorDecl>(FD))
return CD->getNameAsString();
return std::string(getMangledName(FD));
} else if (const auto *OM = dyn_cast<ObjCMethodDecl>(DC)) {
return OM->getNameAsString();
} else if (isa<BlockDecl>(DC)) {
return "<block>";
} else if (isa<CapturedDecl>(DC)) {
return "<captured>";
} else {
llvm_unreachable("expected a function or method");
}
};
llvm::GlobalVariable *&CacheEntry = InitializerConstants[&D];
if (!CacheEntry || CacheEntry->getInitializer() != Constant) {
auto *Ty = Constant->getType();
bool isConstant = true;
llvm::GlobalVariable *InsertBefore = nullptr;
unsigned AS =
getContext().getTargetAddressSpace(GetGlobalConstantAddressSpace());
std::string Name;
if (D.hasGlobalStorage())
Name = getMangledName(&D).str() + ".const";
else if (const DeclContext *DC = D.getParentFunctionOrMethod())
Name = ("__const." + FunctionName(DC) + "." + D.getName()).str();
else
llvm_unreachable("local variable has no parent function or method");
llvm::GlobalVariable *GV = new llvm::GlobalVariable(
getModule(), Ty, isConstant, llvm::GlobalValue::PrivateLinkage,
Constant, Name, InsertBefore, llvm::GlobalValue::NotThreadLocal, AS);
GV->setAlignment(Align.getAsAlign());
GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
CacheEntry = GV;
} else if (CacheEntry->getAlignment() < uint64_t(Align.getQuantity())) {
CacheEntry->setAlignment(Align.getAsAlign());
}
return Address(CacheEntry, CacheEntry->getValueType(), Align);
}
static Address createUnnamedGlobalForMemcpyFrom(CodeGenModule &CGM,
const VarDecl &D,
CGBuilderTy &Builder,
llvm::Constant *Constant,
CharUnits Align) {
Address SrcPtr = CGM.createUnnamedGlobalFrom(D, Constant, Align);
return Builder.CreateElementBitCast(SrcPtr, CGM.Int8Ty);
}
static void emitStoresForConstant(CodeGenModule &CGM, const VarDecl &D,
Address Loc, bool isVolatile,
CGBuilderTy &Builder,
llvm::Constant *constant, bool IsAutoInit) {
auto *Ty = constant->getType();
uint64_t ConstantSize = CGM.getDataLayout().getTypeAllocSize(Ty);
if (!ConstantSize)
return;
bool canDoSingleStore = Ty->isIntOrIntVectorTy() ||
Ty->isPtrOrPtrVectorTy() || Ty->isFPOrFPVectorTy();
if (canDoSingleStore) {
auto *I = Builder.CreateStore(constant, Loc, isVolatile);
if (IsAutoInit)
I->addAnnotationMetadata("auto-init");
return;
}
auto *SizeVal = llvm::ConstantInt::get(CGM.IntPtrTy, ConstantSize);
if (shouldUseBZeroPlusStoresToInitialize(constant, ConstantSize)) {
auto *I = Builder.CreateMemSet(Loc, llvm::ConstantInt::get(CGM.Int8Ty, 0),
SizeVal, isVolatile);
if (IsAutoInit)
I->addAnnotationMetadata("auto-init");
bool valueAlreadyCorrect =
constant->isNullValue() || isa<llvm::UndefValue>(constant);
if (!valueAlreadyCorrect) {
Loc = Builder.CreateElementBitCast(Loc, Ty);
emitStoresForInitAfterBZero(CGM, constant, Loc, isVolatile, Builder,
IsAutoInit);
}
return;
}
llvm::Value *Pattern =
shouldUseMemSetToInitialize(constant, ConstantSize, CGM.getDataLayout());
if (Pattern) {
uint64_t Value = 0x00;
if (!isa<llvm::UndefValue>(Pattern)) {
const llvm::APInt &AP = cast<llvm::ConstantInt>(Pattern)->getValue();
assert(AP.getBitWidth() <= 8);
Value = AP.getLimitedValue();
}
auto *I = Builder.CreateMemSet(
Loc, llvm::ConstantInt::get(CGM.Int8Ty, Value), SizeVal, isVolatile);
if (IsAutoInit)
I->addAnnotationMetadata("auto-init");
return;
}
if (shouldSplitConstantStore(CGM, ConstantSize)) {
if (auto *STy = dyn_cast<llvm::StructType>(Ty)) {
if (STy == Loc.getElementType()) {
for (unsigned i = 0; i != constant->getNumOperands(); i++) {
Address EltPtr = Builder.CreateStructGEP(Loc, i);
emitStoresForConstant(
CGM, D, EltPtr, isVolatile, Builder,
cast<llvm::Constant>(Builder.CreateExtractValue(constant, i)),
IsAutoInit);
}
return;
}
} else if (auto *ATy = dyn_cast<llvm::ArrayType>(Ty)) {
if (ATy == Loc.getElementType()) {
for (unsigned i = 0; i != ATy->getNumElements(); i++) {
Address EltPtr = Builder.CreateConstArrayGEP(Loc, i);
emitStoresForConstant(
CGM, D, EltPtr, isVolatile, Builder,
cast<llvm::Constant>(Builder.CreateExtractValue(constant, i)),
IsAutoInit);
}
return;
}
}
}
auto *I =
Builder.CreateMemCpy(Loc,
createUnnamedGlobalForMemcpyFrom(
CGM, D, Builder, constant, Loc.getAlignment()),
SizeVal, isVolatile);
if (IsAutoInit)
I->addAnnotationMetadata("auto-init");
}
static void emitStoresForZeroInit(CodeGenModule &CGM, const VarDecl &D,
Address Loc, bool isVolatile,
CGBuilderTy &Builder) {
llvm::Type *ElTy = Loc.getElementType();
llvm::Constant *constant =
constWithPadding(CGM, IsPattern::No, llvm::Constant::getNullValue(ElTy));
emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant,
true);
}
static void emitStoresForPatternInit(CodeGenModule &CGM, const VarDecl &D,
Address Loc, bool isVolatile,
CGBuilderTy &Builder) {
llvm::Type *ElTy = Loc.getElementType();
llvm::Constant *constant = constWithPadding(
CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
assert(!isa<llvm::UndefValue>(constant));
emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant,
true);
}
static bool containsUndef(llvm::Constant *constant) {
auto *Ty = constant->getType();
if (isa<llvm::UndefValue>(constant))
return true;
if (Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy())
for (llvm::Use &Op : constant->operands())
if (containsUndef(cast<llvm::Constant>(Op)))
return true;
return false;
}
static llvm::Constant *replaceUndef(CodeGenModule &CGM, IsPattern isPattern,
llvm::Constant *constant) {
auto *Ty = constant->getType();
if (isa<llvm::UndefValue>(constant))
return patternOrZeroFor(CGM, isPattern, Ty);
if (!(Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()))
return constant;
if (!containsUndef(constant))
return constant;
llvm::SmallVector<llvm::Constant *, 8> Values(constant->getNumOperands());
for (unsigned Op = 0, NumOp = constant->getNumOperands(); Op != NumOp; ++Op) {
auto *OpValue = cast<llvm::Constant>(constant->getOperand(Op));
Values[Op] = replaceUndef(CGM, isPattern, OpValue);
}
if (Ty->isStructTy())
return llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Values);
if (Ty->isArrayTy())
return llvm::ConstantArray::get(cast<llvm::ArrayType>(Ty), Values);
assert(Ty->isVectorTy());
return llvm::ConstantVector::get(Values);
}
void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
AutoVarEmission emission = EmitAutoVarAlloca(D);
EmitAutoVarInit(emission);
EmitAutoVarCleanups(emission);
}
llvm::Value *CodeGenFunction::EmitLifetimeStart(llvm::TypeSize Size,
llvm::Value *Addr) {
if (!ShouldEmitLifetimeMarkers)
return nullptr;
assert(Addr->getType()->getPointerAddressSpace() ==
CGM.getDataLayout().getAllocaAddrSpace() &&
"Pointer should be in alloca address space");
llvm::Value *SizeV = llvm::ConstantInt::get(
Int64Ty, Size.isScalable() ? -1 : Size.getFixedValue());
Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
llvm::CallInst *C =
Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
C->setDoesNotThrow();
return SizeV;
}
void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
assert(Addr->getType()->getPointerAddressSpace() ==
CGM.getDataLayout().getAllocaAddrSpace() &&
"Pointer should be in alloca address space");
Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
llvm::CallInst *C =
Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
C->setDoesNotThrow();
}
void CodeGenFunction::EmitAndRegisterVariableArrayDimensions(
CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) {
SmallVector<CodeGenFunction::VlaSizePair, 4> Dimensions;
SmallVector<IdentifierInfo *, 4> VLAExprNames;
QualType Type1D = D.getType();
while (getContext().getAsVariableArrayType(Type1D)) {
auto VlaSize = getVLAElements1D(Type1D);
if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
Dimensions.emplace_back(C, Type1D.getUnqualifiedType());
else {
Twine Name = Twine("__vla_expr") + Twine(VLAExprCounter++);
SmallString<12> Buffer;
StringRef NameRef = Name.toStringRef(Buffer);
auto &Ident = getContext().Idents.getOwn(NameRef);
VLAExprNames.push_back(&Ident);
auto SizeExprAddr =
CreateDefaultAlignTempAlloca(VlaSize.NumElts->getType(), NameRef);
Builder.CreateStore(VlaSize.NumElts, SizeExprAddr);
Dimensions.emplace_back(SizeExprAddr.getPointer(),
Type1D.getUnqualifiedType());
}
Type1D = VlaSize.Type;
}
if (!EmitDebugInfo)
return;
unsigned NameIdx = 0;
for (auto &VlaSize : Dimensions) {
llvm::Metadata *MD;
if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
MD = llvm::ConstantAsMetadata::get(C);
else {
IdentifierInfo *NameIdent = VLAExprNames[NameIdx++];
assert(cast<llvm::PointerType>(VlaSize.NumElts->getType())
->isOpaqueOrPointeeTypeMatches(SizeTy) &&
"Number of VLA elements must be SizeTy");
auto QT = getContext().getIntTypeForBitwidth(
SizeTy->getScalarSizeInBits(), false);
auto *ArtificialDecl = VarDecl::Create(
getContext(), const_cast<DeclContext *>(D.getDeclContext()),
D.getLocation(), D.getLocation(), NameIdent, QT,
getContext().CreateTypeSourceInfo(QT), SC_Auto);
ArtificialDecl->setImplicit();
MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts,
Builder);
}
assert(MD && "No Size expression debug node created");
DI->registerVLASizeExpression(VlaSize.Type, MD);
}
}
CodeGenFunction::AutoVarEmission
CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
QualType Ty = D.getType();
assert(
Ty.getAddressSpace() == LangAS::Default ||
(Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL));
AutoVarEmission emission(D);
bool isEscapingByRef = D.isEscapingByref();
emission.IsEscapingByRef = isEscapingByRef;
CharUnits alignment = getContext().getDeclAlign(&D);
if (Ty->isVariablyModifiedType())
EmitVariablyModifiedType(Ty);
auto *DI = getDebugInfo();
bool EmitDebugInfo = DI && CGM.getCodeGenOpts().hasReducedDebugInfo();
Address address = Address::invalid();
Address AllocaAddr = Address::invalid();
Address OpenMPLocalAddr = Address::invalid();
if (CGM.getLangOpts().OpenMPIRBuilder)
OpenMPLocalAddr = OMPBuilderCBHelpers::getAddressOfLocalVariable(*this, &D);
else
OpenMPLocalAddr =
getLangOpts().OpenMP
? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
: Address::invalid();
bool NRVO = getLangOpts().ElideConstructors && D.isNRVOVariable();
if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
address = OpenMPLocalAddr;
AllocaAddr = OpenMPLocalAddr;
} else if (Ty->isConstantSizeType()) {
if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
(D.isConstexpr() ||
((Ty.isPODType(getContext()) ||
getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
D.getInit()->isConstantInitializer(getContext(), false)))) {
if ((!getLangOpts().OpenCL ||
Ty.getAddressSpace() == LangAS::opencl_constant) &&
(CGM.getCodeGenOpts().MergeAllConstants && !NRVO &&
!isEscapingByRef && CGM.isTypeConstant(Ty, true))) {
EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
emission.Addr = Address::invalid();
assert(emission.wasEmittedAsGlobal());
return emission;
}
emission.IsConstantAggregate = true;
}
if (NRVO) {
address = ReturnValue;
AllocaAddr = ReturnValue;
if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
const auto *RD = RecordTy->getDecl();
const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
if ((CXXRD && !CXXRD->hasTrivialDestructor()) ||
RD->isNonTrivialToPrimitiveDestroy()) {
llvm::Value *Zero = Builder.getFalse();
Address NRVOFlag =
CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo",
nullptr, &AllocaAddr);
EnsureInsertPoint();
Builder.CreateStore(Zero, NRVOFlag);
NRVOFlags[&D] = NRVOFlag.getPointer();
emission.NRVOFlag = NRVOFlag.getPointer();
}
}
} else {
CharUnits allocaAlignment;
llvm::Type *allocaTy;
if (isEscapingByRef) {
auto &byrefInfo = getBlockByrefInfo(&D);
allocaTy = byrefInfo.Type;
allocaAlignment = byrefInfo.ByrefAlignment;
} else {
allocaTy = ConvertTypeForMem(Ty);
allocaAlignment = alignment;
}
address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName(),
nullptr, &AllocaAddr);
bool IsMSCatchParam =
D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
if (HaveInsertPoint() && !IsMSCatchParam) {
if (!Bypasses.IsBypassed(&D) &&
!(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
llvm::TypeSize Size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
emission.SizeForLifetimeMarkers =
EmitLifetimeStart(Size, AllocaAddr.getPointer());
}
} else {
assert(!emission.useLifetimeMarkers());
}
}
} else {
EnsureInsertPoint();
if (!DidCallStackSave) {
Address Stack =
CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
llvm::Value *V = Builder.CreateCall(F);
Builder.CreateStore(V, Stack);
DidCallStackSave = true;
pushStackRestore(NormalCleanup, Stack);
}
auto VlaSize = getVLASize(Ty);
llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type);
address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts,
&AllocaAddr);
EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo);
}
setAddrOfLocalVar(&D, address);
emission.Addr = address;
emission.AllocaAddr = AllocaAddr;
if (EmitDebugInfo && HaveInsertPoint()) {
Address DebugAddr = address;
bool UsePointerValue = NRVO && ReturnValuePointer.isValid();
DI->setLocation(D.getLocation());
if (UsePointerValue) {
DebugAddr = ReturnValuePointer;
AllocaAddr = ReturnValuePointer;
}
(void)DI->EmitDeclareOfAutoVariable(&D, AllocaAddr.getPointer(), Builder,
UsePointerValue);
}
if (D.hasAttr<AnnotateAttr>() && HaveInsertPoint())
EmitVarAnnotations(&D, address.getPointer());
if (emission.useLifetimeMarkers())
EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
emission.getOriginalAllocatedAddress(),
emission.getSizeForLifetimeMarkers());
return emission;
}
static bool isCapturedBy(const VarDecl &, const Expr *);
static bool isCapturedBy(const VarDecl &Var, const Stmt *S) {
if (const Expr *E = dyn_cast<Expr>(S))
return isCapturedBy(Var, E);
for (const Stmt *SubStmt : S->children())
if (isCapturedBy(Var, SubStmt))
return true;
return false;
}
static bool isCapturedBy(const VarDecl &Var, const Expr *E) {
E = E->IgnoreParenCasts();
if (const BlockExpr *BE = dyn_cast<BlockExpr>(E)) {
const BlockDecl *Block = BE->getBlockDecl();
for (const auto &I : Block->captures()) {
if (I.getVariable() == &Var)
return true;
}
return false;
}
if (const StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
const CompoundStmt *CS = SE->getSubStmt();
for (const auto *BI : CS->body())
if (const auto *BIE = dyn_cast<Expr>(BI)) {
if (isCapturedBy(Var, BIE))
return true;
}
else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
for (const auto *I : DS->decls()) {
if (const auto *VD = dyn_cast<VarDecl>((I))) {
const Expr *Init = VD->getInit();
if (Init && isCapturedBy(Var, Init))
return true;
}
}
}
else
return true;
return false;
}
for (const Stmt *SubStmt : E->children())
if (isCapturedBy(Var, SubStmt))
return true;
return false;
}
bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
if (!Init)
return true;
if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
if (CXXConstructorDecl *Constructor = Construct->getConstructor())
if (Constructor->isTrivial() &&
Constructor->isDefaultConstructor() &&
!Construct->requiresZeroInitialization())
return true;
return false;
}
void CodeGenFunction::emitZeroOrPatternForAutoVarInit(QualType type,
const VarDecl &D,
Address Loc) {
auto trivialAutoVarInit = getContext().getLangOpts().getTrivialAutoVarInit();
CharUnits Size = getContext().getTypeSizeInChars(type);
bool isVolatile = type.isVolatileQualified();
if (!Size.isZero()) {
switch (trivialAutoVarInit) {
case LangOptions::TrivialAutoVarInitKind::Uninitialized:
llvm_unreachable("Uninitialized handled by caller");
case LangOptions::TrivialAutoVarInitKind::Zero:
if (CGM.stopAutoInit())
return;
emitStoresForZeroInit(CGM, D, Loc, isVolatile, Builder);
break;
case LangOptions::TrivialAutoVarInitKind::Pattern:
if (CGM.stopAutoInit())
return;
emitStoresForPatternInit(CGM, D, Loc, isVolatile, Builder);
break;
}
return;
}
const auto *VlaType = getContext().getAsVariableArrayType(type);
if (!VlaType)
return;
auto VlaSize = getVLASize(VlaType);
auto SizeVal = VlaSize.NumElts;
CharUnits EltSize = getContext().getTypeSizeInChars(VlaSize.Type);
switch (trivialAutoVarInit) {
case LangOptions::TrivialAutoVarInitKind::Uninitialized:
llvm_unreachable("Uninitialized handled by caller");
case LangOptions::TrivialAutoVarInitKind::Zero: {
if (CGM.stopAutoInit())
return;
if (!EltSize.isOne())
SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
auto *I = Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0),
SizeVal, isVolatile);
I->addAnnotationMetadata("auto-init");
break;
}
case LangOptions::TrivialAutoVarInitKind::Pattern: {
if (CGM.stopAutoInit())
return;
llvm::Type *ElTy = Loc.getElementType();
llvm::Constant *Constant = constWithPadding(
CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
CharUnits ConstantAlign = getContext().getTypeAlignInChars(VlaSize.Type);
llvm::BasicBlock *SetupBB = createBasicBlock("vla-setup.loop");
llvm::BasicBlock *LoopBB = createBasicBlock("vla-init.loop");
llvm::BasicBlock *ContBB = createBasicBlock("vla-init.cont");
llvm::Value *IsZeroSizedVLA = Builder.CreateICmpEQ(
SizeVal, llvm::ConstantInt::get(SizeVal->getType(), 0),
"vla.iszerosized");
Builder.CreateCondBr(IsZeroSizedVLA, ContBB, SetupBB);
EmitBlock(SetupBB);
if (!EltSize.isOne())
SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
llvm::Value *BaseSizeInChars =
llvm::ConstantInt::get(IntPtrTy, EltSize.getQuantity());
Address Begin = Builder.CreateElementBitCast(Loc, Int8Ty, "vla.begin");
llvm::Value *End = Builder.CreateInBoundsGEP(
Begin.getElementType(), Begin.getPointer(), SizeVal, "vla.end");
llvm::BasicBlock *OriginBB = Builder.GetInsertBlock();
EmitBlock(LoopBB);
llvm::PHINode *Cur = Builder.CreatePHI(Begin.getType(), 2, "vla.cur");
Cur->addIncoming(Begin.getPointer(), OriginBB);
CharUnits CurAlign = Loc.getAlignment().alignmentOfArrayElement(EltSize);
auto *I =
Builder.CreateMemCpy(Address(Cur, Int8Ty, CurAlign),
createUnnamedGlobalForMemcpyFrom(
CGM, D, Builder, Constant, ConstantAlign),
BaseSizeInChars, isVolatile);
I->addAnnotationMetadata("auto-init");
llvm::Value *Next =
Builder.CreateInBoundsGEP(Int8Ty, Cur, BaseSizeInChars, "vla.next");
llvm::Value *Done = Builder.CreateICmpEQ(Next, End, "vla-init.isdone");
Builder.CreateCondBr(Done, ContBB, LoopBB);
Cur->addIncoming(Next, LoopBB);
EmitBlock(ContBB);
} break;
}
}
void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
assert(emission.Variable && "emission was not valid!");
if (emission.wasEmittedAsGlobal()) return;
const VarDecl &D = *emission.Variable;
auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
QualType type = D.getType();
const Expr *Init = D.getInit();
if (!HaveInsertPoint()) {
if (!Init || !ContainsLabel(Init)) return;
EnsureInsertPoint();
}
if (emission.IsEscapingByRef)
emitByrefStructureInit(emission);
if (!Init &&
type.isNonTrivialToPrimitiveDefaultInitialize() ==
QualType::PDIK_Struct) {
LValue Dst = MakeAddrLValue(emission.getAllocatedAddress(), type);
if (emission.IsEscapingByRef)
drillIntoBlockVariable(*this, Dst, &D);
defaultInitNonTrivialCStructVar(Dst);
return;
}
bool capturedByInit =
Init && emission.IsEscapingByRef && isCapturedBy(D, Init);
bool locIsByrefHeader = !capturedByInit;
const Address Loc =
locIsByrefHeader ? emission.getObjectAddress(*this) : emission.Addr;
LangOptions::TrivialAutoVarInitKind trivialAutoVarInit =
(D.isConstexpr()
? LangOptions::TrivialAutoVarInitKind::Uninitialized
: (D.getAttr<UninitializedAttr>()
? LangOptions::TrivialAutoVarInitKind::Uninitialized
: getContext().getLangOpts().getTrivialAutoVarInit()));
auto initializeWhatIsTechnicallyUninitialized = [&](Address Loc) {
if (trivialAutoVarInit ==
LangOptions::TrivialAutoVarInitKind::Uninitialized)
return;
if (emission.IsEscapingByRef && !locIsByrefHeader)
Loc = emitBlockByrefAddress(Loc, &D, false);
return emitZeroOrPatternForAutoVarInit(type, D, Loc);
};
if (isTrivialInitializer(Init))
return initializeWhatIsTechnicallyUninitialized(Loc);
llvm::Constant *constant = nullptr;
if (emission.IsConstantAggregate ||
D.mightBeUsableInConstantExpressions(getContext())) {
assert(!capturedByInit && "constant init contains a capturing block?");
constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D);
if (constant && !constant->isZeroValue() &&
(trivialAutoVarInit !=
LangOptions::TrivialAutoVarInitKind::Uninitialized)) {
IsPattern isPattern =
(trivialAutoVarInit == LangOptions::TrivialAutoVarInitKind::Pattern)
? IsPattern::Yes
: IsPattern::No;
constant = constWithPadding(CGM, IsPattern::No,
replaceUndef(CGM, isPattern, constant));
}
}
if (!constant) {
initializeWhatIsTechnicallyUninitialized(Loc);
LValue lv = MakeAddrLValue(Loc, type);
lv.setNonGC(true);
return EmitExprAsInit(Init, &D, lv, capturedByInit);
}
if (!emission.IsConstantAggregate) {
LValue lv = MakeAddrLValue(Loc, type);
lv.setNonGC(true);
return EmitStoreThroughLValue(RValue::get(constant), lv, true);
}
emitStoresForConstant(CGM, D, Builder.CreateElementBitCast(Loc, CGM.Int8Ty),
type.isVolatileQualified(), Builder, constant,
false);
}
void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
LValue lvalue, bool capturedByInit) {
QualType type = D->getType();
if (type->isReferenceType()) {
RValue rvalue = EmitReferenceBindingToExpr(init);
if (capturedByInit)
drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
EmitStoreThroughLValue(rvalue, lvalue, true);
return;
}
switch (getEvaluationKind(type)) {
case TEK_Scalar:
EmitScalarInit(init, D, lvalue, capturedByInit);
return;
case TEK_Complex: {
ComplexPairTy complex = EmitComplexExpr(init);
if (capturedByInit)
drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
EmitStoreOfComplex(complex, lvalue, true);
return;
}
case TEK_Aggregate:
if (type->isAtomicType()) {
EmitAtomicInit(const_cast<Expr*>(init), lvalue);
} else {
AggValueSlot::Overlap_t Overlap = AggValueSlot::MayOverlap;
if (isa<VarDecl>(D))
Overlap = AggValueSlot::DoesNotOverlap;
else if (auto *FD = dyn_cast<FieldDecl>(D))
Overlap = getOverlapForFieldInit(FD);
EmitAggExpr(init, AggValueSlot::forLValue(
lvalue, *this, AggValueSlot::IsDestructed,
AggValueSlot::DoesNotNeedGCBarriers,
AggValueSlot::IsNotAliased, Overlap));
}
return;
}
llvm_unreachable("bad evaluation kind");
}
void CodeGenFunction::emitAutoVarTypeCleanup(
const CodeGenFunction::AutoVarEmission &emission,
QualType::DestructionKind dtorKind) {
assert(dtorKind != QualType::DK_none);
Address addr = emission.getObjectAddress(*this);
const VarDecl *var = emission.Variable;
QualType type = var->getType();
CleanupKind cleanupKind = NormalAndEHCleanup;
CodeGenFunction::Destroyer *destroyer = nullptr;
switch (dtorKind) {
case QualType::DK_none:
llvm_unreachable("no cleanup for trivially-destructible variable");
case QualType::DK_cxx_destructor:
if (emission.NRVOFlag) {
assert(!type->isArrayType());
CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
EHStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, type, dtor,
emission.NRVOFlag);
return;
}
break;
case QualType::DK_objc_strong_lifetime:
if (var->isARCPseudoStrong()) return;
cleanupKind = getARCCleanupKind();
if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
destroyer = CodeGenFunction::destroyARCStrongImprecise;
break;
case QualType::DK_objc_weak_lifetime:
break;
case QualType::DK_nontrivial_c_struct:
destroyer = CodeGenFunction::destroyNonTrivialCStruct;
if (emission.NRVOFlag) {
assert(!type->isArrayType());
EHStack.pushCleanup<DestroyNRVOVariableC>(cleanupKind, addr,
emission.NRVOFlag, type);
return;
}
break;
}
if (!destroyer) destroyer = getDestroyer(dtorKind);
bool useEHCleanup = (cleanupKind & EHCleanup);
EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
useEHCleanup);
}
void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
assert(emission.Variable && "emission was not valid!");
if (emission.wasEmittedAsGlobal()) return;
if (!HaveInsertPoint()) return;
const VarDecl &D = *emission.Variable;
if (QualType::DestructionKind dtorKind = D.needsDestruction(getContext()))
emitAutoVarTypeCleanup(emission, dtorKind);
if (getLangOpts().getGC() != LangOptions::NonGC &&
D.hasAttr<ObjCPreciseLifetimeAttr>()) {
EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
}
if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
const FunctionDecl *FD = CA->getFunctionDecl();
llvm::Constant *F = CGM.GetAddrOfFunction(FD);
assert(F && "Could not find function!");
const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
}
if (emission.IsEscapingByRef &&
CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
if (emission.Variable->getType().isObjCGCWeak())
Flags |= BLOCK_FIELD_IS_WEAK;
enterByrefCleanup(NormalAndEHCleanup, emission.Addr, Flags,
false,
cxxDestructorCanThrow(emission.Variable->getType()));
}
}
CodeGenFunction::Destroyer *
CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
switch (kind) {
case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
case QualType::DK_cxx_destructor:
return destroyCXXObject;
case QualType::DK_objc_strong_lifetime:
return destroyARCStrongPrecise;
case QualType::DK_objc_weak_lifetime:
return destroyARCWeak;
case QualType::DK_nontrivial_c_struct:
return destroyNonTrivialCStruct;
}
llvm_unreachable("Unknown DestructionKind");
}
void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
Address addr, QualType type) {
assert(dtorKind && "cannot push destructor for trivial type");
assert(needsEHCleanup(dtorKind));
pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
}
void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
Address addr, QualType type) {
assert(dtorKind && "cannot push destructor for trivial type");
CleanupKind cleanupKind = getCleanupKind(dtorKind);
pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
cleanupKind & EHCleanup);
}
void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
QualType type, Destroyer *destroyer,
bool useEHCleanupForArray) {
pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
destroyer, useEHCleanupForArray);
}
void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
}
void CodeGenFunction::pushLifetimeExtendedDestroy(CleanupKind cleanupKind,
Address addr, QualType type,
Destroyer *destroyer,
bool useEHCleanupForArray) {
if (!isInConditionalBranch()) {
if (cleanupKind & EHCleanup)
EHStack.pushCleanup<DestroyObject>(
static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
destroyer, useEHCleanupForArray);
return pushCleanupAfterFullExprWithActiveFlag<DestroyObject>(
cleanupKind, Address::invalid(), addr, type, destroyer, useEHCleanupForArray);
}
using SavedType = typename DominatingValue<Address>::saved_type;
using ConditionalCleanupType =
EHScopeStack::ConditionalCleanup<DestroyObject, Address, QualType,
Destroyer *, bool>;
Address ActiveFlag = createCleanupActiveFlag();
SavedType SavedAddr = saveValueInCond(addr);
if (cleanupKind & EHCleanup) {
EHStack.pushCleanup<ConditionalCleanupType>(
static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), SavedAddr, type,
destroyer, useEHCleanupForArray);
initFullExprCleanupWithFlag(ActiveFlag);
}
pushCleanupAfterFullExprWithActiveFlag<ConditionalCleanupType>(
cleanupKind, ActiveFlag, SavedAddr, type, destroyer,
useEHCleanupForArray);
}
void CodeGenFunction::emitDestroy(Address addr, QualType type,
Destroyer *destroyer,
bool useEHCleanupForArray) {
const ArrayType *arrayType = getContext().getAsArrayType(type);
if (!arrayType)
return destroyer(*this, addr, type);
llvm::Value *length = emitArrayLength(arrayType, type, addr);
CharUnits elementAlign =
addr.getAlignment()
.alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
bool checkZeroLength = true;
if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
if (constLength->isZero()) return;
checkZeroLength = false;
}
llvm::Value *begin = addr.getPointer();
llvm::Value *end =
Builder.CreateInBoundsGEP(addr.getElementType(), begin, length);
emitArrayDestroy(begin, end, type, elementAlign, destroyer,
checkZeroLength, useEHCleanupForArray);
}
void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
llvm::Value *end,
QualType elementType,
CharUnits elementAlign,
Destroyer *destroyer,
bool checkZeroLength,
bool useEHCleanup) {
assert(!elementType->isArrayType());
llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
if (checkZeroLength) {
llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
"arraydestroy.isempty");
Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
}
llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
EmitBlock(bodyBB);
llvm::PHINode *elementPast =
Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
elementPast->addIncoming(end, entryBB);
llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
llvm::Type *llvmElementType = ConvertTypeForMem(elementType);
llvm::Value *element = Builder.CreateInBoundsGEP(
llvmElementType, elementPast, negativeOne, "arraydestroy.element");
if (useEHCleanup)
pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
destroyer);
destroyer(*this, Address(element, llvmElementType, elementAlign),
elementType);
if (useEHCleanup)
PopCleanupBlock();
llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
Builder.CreateCondBr(done, doneBB, bodyBB);
elementPast->addIncoming(element, Builder.GetInsertBlock());
EmitBlock(doneBB);
}
static void emitPartialArrayDestroy(CodeGenFunction &CGF,
llvm::Value *begin, llvm::Value *end,
QualType type, CharUnits elementAlign,
CodeGenFunction::Destroyer *destroyer) {
llvm::Type *elemTy = CGF.ConvertTypeForMem(type);
unsigned arrayDepth = 0;
while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
if (!isa<VariableArrayType>(arrayType))
arrayDepth++;
type = arrayType->getElementType();
}
if (arrayDepth) {
llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
begin = CGF.Builder.CreateInBoundsGEP(
elemTy, begin, gepIndices, "pad.arraybegin");
end = CGF.Builder.CreateInBoundsGEP(
elemTy, end, gepIndices, "pad.arrayend");
}
CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
true, false);
}
namespace {
class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
llvm::Value *ArrayBegin;
llvm::Value *ArrayEnd;
QualType ElementType;
CodeGenFunction::Destroyer *Destroyer;
CharUnits ElementAlign;
public:
RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
QualType elementType, CharUnits elementAlign,
CodeGenFunction::Destroyer *destroyer)
: ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
ElementType(elementType), Destroyer(destroyer),
ElementAlign(elementAlign) {}
void Emit(CodeGenFunction &CGF, Flags flags) override {
emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
ElementType, ElementAlign, Destroyer);
}
};
class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
llvm::Value *ArrayBegin;
Address ArrayEndPointer;
QualType ElementType;
CodeGenFunction::Destroyer *Destroyer;
CharUnits ElementAlign;
public:
IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
Address arrayEndPointer,
QualType elementType,
CharUnits elementAlign,
CodeGenFunction::Destroyer *destroyer)
: ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
ElementType(elementType), Destroyer(destroyer),
ElementAlign(elementAlign) {}
void Emit(CodeGenFunction &CGF, Flags flags) override {
llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
ElementType, ElementAlign, Destroyer);
}
};
}
void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
Address arrayEndPointer,
QualType elementType,
CharUnits elementAlign,
Destroyer *destroyer) {
pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
arrayBegin, arrayEndPointer,
elementType, elementAlign,
destroyer);
}
void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
llvm::Value *arrayEnd,
QualType elementType,
CharUnits elementAlign,
Destroyer *destroyer) {
pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
arrayBegin, arrayEnd,
elementType, elementAlign,
destroyer);
}
llvm::Function *CodeGenModule::getLLVMLifetimeStartFn() {
if (LifetimeStartFn)
return LifetimeStartFn;
LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
return LifetimeStartFn;
}
llvm::Function *CodeGenModule::getLLVMLifetimeEndFn() {
if (LifetimeEndFn)
return LifetimeEndFn;
LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
return LifetimeEndFn;
}
namespace {
struct ConsumeARCParameter final : EHScopeStack::Cleanup {
ConsumeARCParameter(llvm::Value *param,
ARCPreciseLifetime_t precise)
: Param(param), Precise(precise) {}
llvm::Value *Param;
ARCPreciseLifetime_t Precise;
void Emit(CodeGenFunction &CGF, Flags flags) override {
CGF.EmitARCRelease(Param, Precise);
}
};
}
void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
unsigned ArgNo) {
bool NoDebugInfo = false;
assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
"Invalid argument to EmitParmDecl");
Arg.getAnyValue()->setName(D.getName());
QualType Ty = D.getType();
if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
if (BlockInfo) {
llvm::Value *V = Arg.isIndirect()
? Builder.CreateLoad(Arg.getIndirectAddress())
: Arg.getDirectValue();
setBlockContextParameter(IPD, ArgNo, V);
return;
}
NoDebugInfo =
(IPD->getParameterKind() == ImplicitParamDecl::ThreadPrivateVar);
}
Address DeclPtr = Address::invalid();
Address AllocaPtr = Address::invalid();
bool DoStore = false;
bool IsScalar = hasScalarEvaluationKind(Ty);
if (Arg.isIndirect()) {
DeclPtr = Arg.getIndirectAddress();
DeclPtr = Builder.CreateElementBitCast(DeclPtr, ConvertTypeForMem(Ty),
D.getName());
auto AllocaAS = CGM.getASTAllocaAddressSpace();
auto *V = DeclPtr.getPointer();
AllocaPtr = DeclPtr;
auto SrcLangAS = getLangOpts().OpenCL ? LangAS::opencl_private : AllocaAS;
auto DestLangAS =
getLangOpts().OpenCL ? LangAS::opencl_private : LangAS::Default;
if (SrcLangAS != DestLangAS) {
assert(getContext().getTargetAddressSpace(SrcLangAS) ==
CGM.getDataLayout().getAllocaAddrSpace());
auto DestAS = getContext().getTargetAddressSpace(DestLangAS);
auto *T = DeclPtr.getElementType()->getPointerTo(DestAS);
DeclPtr = DeclPtr.withPointer(getTargetHooks().performAddrSpaceCast(
*this, V, SrcLangAS, DestLangAS, T, true));
}
if (Ty->isRecordType() && !CurFuncIsThunk &&
Ty->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
if (QualType::DestructionKind DtorKind =
D.needsDestruction(getContext())) {
assert((DtorKind == QualType::DK_cxx_destructor ||
DtorKind == QualType::DK_nontrivial_c_struct) &&
"unexpected destructor type");
pushDestroy(DtorKind, DeclPtr, Ty);
CalleeDestructedParamCleanups[cast<ParmVarDecl>(&D)] =
EHStack.stable_begin();
}
}
} else {
Address OpenMPLocalAddr =
getLangOpts().OpenMP
? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
: Address::invalid();
if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
DeclPtr = OpenMPLocalAddr;
AllocaPtr = DeclPtr;
} else {
DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
D.getName() + ".addr", &AllocaPtr);
}
DoStore = true;
}
llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
LValue lv = MakeAddrLValue(DeclPtr, Ty);
if (IsScalar) {
Qualifiers qs = Ty.getQualifiers();
if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
bool isConsumed = D.hasAttr<NSConsumedAttr>();
if (D.isARCPseudoStrong()) {
assert(lt == Qualifiers::OCL_Strong &&
"pseudo-strong variable isn't strong?");
assert(qs.hasConst() && "pseudo-strong variable should be const!");
lt = Qualifiers::OCL_ExplicitNone;
}
if (Arg.isIndirect() && !ArgVal)
ArgVal = Builder.CreateLoad(DeclPtr);
if (lt == Qualifiers::OCL_Strong) {
if (!isConsumed) {
if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
llvm::Value *Null = CGM.EmitNullConstant(D.getType());
EmitStoreOfScalar(Null, lv, true);
EmitARCStoreStrongCall(lv.getAddress(*this), ArgVal, true);
DoStore = false;
}
else
ArgVal = EmitARCRetainNonBlock(ArgVal);
}
} else {
if (isConsumed) {
ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
? ARCPreciseLifetime : ARCImpreciseLifetime);
EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
precise);
}
if (lt == Qualifiers::OCL_Weak) {
EmitARCInitWeak(DeclPtr, ArgVal);
DoStore = false; }
}
EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
}
}
if (DoStore)
EmitStoreOfScalar(ArgVal, lv, true);
setAddrOfLocalVar(&D, DeclPtr);
if (CGDebugInfo *DI = getDebugInfo()) {
if (CGM.getCodeGenOpts().hasReducedDebugInfo() && !CurFuncIsThunk &&
!NoDebugInfo) {
llvm::DILocalVariable *DILocalVar = DI->EmitDeclareOfArgVariable(
&D, AllocaPtr.getPointer(), ArgNo, Builder);
if (const auto *Var = dyn_cast_or_null<ParmVarDecl>(&D))
DI->getParamDbgMappings().insert({Var, DILocalVar});
}
}
if (D.hasAttr<AnnotateAttr>())
EmitVarAnnotations(&D, DeclPtr.getPointer());
if (requiresReturnValueNullabilityCheck()) {
auto Nullability = Ty->getNullability(getContext());
if (Nullability && *Nullability == NullabilityKind::NonNull) {
SanitizerScope SanScope(this);
RetValNullabilityPrecondition =
Builder.CreateAnd(RetValNullabilityPrecondition,
Builder.CreateIsNotNull(Arg.getAnyValue()));
}
}
}
void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
CodeGenFunction *CGF) {
if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
return;
getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
}
void CodeGenModule::EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,
CodeGenFunction *CGF) {
if (!LangOpts.OpenMP || LangOpts.OpenMPSimd ||
(!LangOpts.EmitAllDecls && !D->isUsed()))
return;
getOpenMPRuntime().emitUserDefinedMapper(D, CGF);
}
void CodeGenModule::EmitOMPRequiresDecl(const OMPRequiresDecl *D) {
getOpenMPRuntime().processRequiresDirective(D);
}
void CodeGenModule::EmitOMPAllocateDecl(const OMPAllocateDecl *D) {
for (const Expr *E : D->varlists()) {
const auto *DE = cast<DeclRefExpr>(E);
const auto *VD = cast<VarDecl>(DE->getDecl());
if (!VD->hasGlobalStorage())
continue;
StringRef MangledName = getMangledName(VD);
llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
if (!Entry)
continue;
QualType ASTTy = VD->getType();
clang::LangAS GVAS = GetGlobalVarAddressSpace(VD);
auto TargetAS = getContext().getTargetAddressSpace(GVAS);
if (Entry->getType()->getAddressSpace() == TargetAS)
continue;
llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
llvm::PointerType *PTy = llvm::PointerType::get(Ty, TargetAS);
llvm::GlobalVariable *DummyGV = new llvm::GlobalVariable(
getModule(), Entry->getValueType(), false,
llvm::GlobalValue::CommonLinkage, nullptr, "dummy", nullptr,
llvm::GlobalVariable::NotThreadLocal, Entry->getAddressSpace());
Entry->replaceAllUsesWith(DummyGV);
Entry->mutateType(PTy);
llvm::Constant *NewPtrForOldDecl =
llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
Entry, DummyGV->getType());
DummyGV->replaceAllUsesWith(NewPtrForOldDecl);
DummyGV->eraseFromParent();
}
}
llvm::Optional<CharUnits>
CodeGenModule::getOMPAllocateAlignment(const VarDecl *VD) {
if (const auto *AA = VD->getAttr<OMPAllocateDeclAttr>()) {
if (Expr *Alignment = AA->getAlignment()) {
unsigned UserAlign =
Alignment->EvaluateKnownConstInt(getContext()).getExtValue();
CharUnits NaturalAlign =
getNaturalTypeAlignment(VD->getType().getNonReferenceType());
return CharUnits::fromQuantity(
std::max<unsigned>(UserAlign, NaturalAlign.getQuantity()));
}
}
return llvm::None;
}