#include "CodeGenModule.h"
#include "CGDebugInfo.h"
#include "CodeGenFunction.h"
#include "CodeGenTBAA.h"
#include "CGCall.h"
#include "CGCUDARuntime.h"
#include "CGCXXABI.h"
#include "CGObjCRuntime.h"
#include "CGOpenCLRuntime.h"
#include "TargetInfo.h"
#include "clang/Frontend/CodeGenOptions.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/CharUnits.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/Mangle.h"
#include "clang/AST/RecordLayout.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Basic/Builtins.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/ConvertUTF.h"
#include "llvm/CallingConv.h"
#include "llvm/Module.h"
#include "llvm/Intrinsics.h"
#include "llvm/LLVMContext.h"
#include "llvm/ADT/APSInt.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Target/Mangler.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Support/CallSite.h"
#include "llvm/Support/ErrorHandling.h"
using namespace clang;
using namespace CodeGen;
static const char AnnotationSection[] = "llvm.metadata";
static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
switch (CGM.getContext().getTargetInfo().getCXXABI()) {
case CXXABI_ARM: return *CreateARMCXXABI(CGM);
case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
}
llvm_unreachable("invalid C++ ABI kind");
}
CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
llvm::Module &M, const llvm::TargetData &TD,
DiagnosticsEngine &diags)
: Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
ABI(createCXXABI(*this)),
Types(*this),
TBAA(0),
VTables(*this), ObjCRuntime(0), OpenCLRuntime(0), CUDARuntime(0),
DebugInfo(0), ARCData(0), NoObjCARCExceptionsMetadata(0),
RRData(0), CFConstantStringClassRef(0),
ConstantStringClassRef(0), NSConstantStringType(0),
VMContext(M.getContext()),
NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
BlockObjectAssign(0), BlockObjectDispose(0),
BlockDescriptorType(0), GenericBlockLiteralType(0) {
llvm::LLVMContext &LLVMContext = M.getContext();
VoidTy = llvm::Type::getVoidTy(LLVMContext);
Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
FloatTy = llvm::Type::getFloatTy(LLVMContext);
DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
PointerAlignInBytes =
C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
Int8PtrTy = Int8Ty->getPointerTo(0);
Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
if (LangOpts.ObjC1)
createObjCRuntime();
if (LangOpts.OpenCL)
createOpenCLRuntime();
if (LangOpts.CUDA)
createCUDARuntime();
if (LangOpts.ThreadSanitizer ||
(!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
ABI.getMangleContext());
if (CodeGenOpts.DebugInfo != CodeGenOptions::NoDebugInfo ||
CodeGenOpts.EmitGcovArcs ||
CodeGenOpts.EmitGcovNotes)
DebugInfo = new CGDebugInfo(*this);
Block.GlobalUniqueCount = 0;
if (C.getLangOpts().ObjCAutoRefCount)
ARCData = new ARCEntrypoints();
RRData = new RREntrypoints();
}
CodeGenModule::~CodeGenModule() {
delete ObjCRuntime;
delete OpenCLRuntime;
delete CUDARuntime;
delete TheTargetCodeGenInfo;
delete &ABI;
delete TBAA;
delete DebugInfo;
delete ARCData;
delete RRData;
}
void CodeGenModule::createObjCRuntime() {
switch (LangOpts.ObjCRuntime.getKind()) {
case ObjCRuntime::GNUstep:
case ObjCRuntime::GCC:
case ObjCRuntime::ObjFW:
ObjCRuntime = CreateGNUObjCRuntime(*this);
return;
case ObjCRuntime::FragileMacOSX:
case ObjCRuntime::MacOSX:
case ObjCRuntime::iOS:
ObjCRuntime = CreateMacObjCRuntime(*this);
return;
}
llvm_unreachable("bad runtime kind");
}
void CodeGenModule::createOpenCLRuntime() {
OpenCLRuntime = new CGOpenCLRuntime(*this);
}
void CodeGenModule::createCUDARuntime() {
CUDARuntime = CreateNVCUDARuntime(*this);
}
void CodeGenModule::Release() {
EmitDeferred();
EmitCXXGlobalInitFunc();
EmitCXXGlobalDtorFunc();
if (ObjCRuntime)
if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
AddGlobalCtor(ObjCInitFunction);
EmitCtorList(GlobalCtors, "llvm.global_ctors");
EmitCtorList(GlobalDtors, "llvm.global_dtors");
EmitGlobalAnnotations();
EmitLLVMUsed();
SimplifyPersonality();
if (getCodeGenOpts().EmitDeclMetadata)
EmitDeclMetadata();
if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
EmitCoverageFile();
if (DebugInfo)
DebugInfo->finalize();
}
void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
Types.UpdateCompletedType(TD);
}
llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
if (!TBAA)
return 0;
return TBAA->getTBAAInfo(QTy);
}
llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
if (!TBAA)
return 0;
return TBAA->getTBAAInfoForVTablePtr();
}
llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
if (!TBAA)
return 0;
return TBAA->getTBAAStructInfo(QTy);
}
void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
llvm::MDNode *TBAAInfo) {
Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
}
bool CodeGenModule::isTargetDarwin() const {
return getContext().getTargetInfo().getTriple().isOSDarwin();
}
void CodeGenModule::Error(SourceLocation loc, StringRef error) {
unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error);
getDiags().Report(Context.getFullLoc(loc), diagID);
}
void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
bool OmitOnError) {
if (OmitOnError && getDiags().hasErrorOccurred())
return;
unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
"cannot compile this %0 yet");
std::string Msg = Type;
getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
<< Msg << S->getSourceRange();
}
void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
bool OmitOnError) {
if (OmitOnError && getDiags().hasErrorOccurred())
return;
unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
"cannot compile this %0 yet");
std::string Msg = Type;
getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
}
llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
return llvm::ConstantInt::get(SizeTy, size.getQuantity());
}
void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
const NamedDecl *D) const {
if (GV->hasLocalLinkage()) {
GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
return;
}
NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
GV->setVisibility(GetLLVMVisibility(LV.visibility()));
}
static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
.Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
.Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
.Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
.Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
}
static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
CodeGenOptions::TLSModel M) {
switch (M) {
case CodeGenOptions::GeneralDynamicTLSModel:
return llvm::GlobalVariable::GeneralDynamicTLSModel;
case CodeGenOptions::LocalDynamicTLSModel:
return llvm::GlobalVariable::LocalDynamicTLSModel;
case CodeGenOptions::InitialExecTLSModel:
return llvm::GlobalVariable::InitialExecTLSModel;
case CodeGenOptions::LocalExecTLSModel:
return llvm::GlobalVariable::LocalExecTLSModel;
}
llvm_unreachable("Invalid TLS model!");
}
void CodeGenModule::setTLSMode(llvm::GlobalVariable *GV,
const VarDecl &D) const {
assert(D.isThreadSpecified() && "setting TLS mode on non-TLS var!");
llvm::GlobalVariable::ThreadLocalMode TLM;
TLM = GetLLVMTLSModel(CodeGenOpts.DefaultTLSModel);
if (D.hasAttr<TLSModelAttr>()) {
const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>();
TLM = GetLLVMTLSModel(Attr->getModel());
}
GV->setThreadLocalMode(TLM);
}
void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
const CXXRecordDecl *RD,
TypeVisibilityKind TVK) const {
setGlobalVisibility(GV, RD);
if (!CodeGenOpts.HiddenWeakVTables)
return;
if (TVK == TVK_ForRTTIName)
return;
if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
return;
if (RD->getExplicitVisibility())
return;
switch (RD->getTemplateSpecializationKind()) {
case TSK_ExplicitInstantiationDefinition:
case TSK_ExplicitInstantiationDeclaration:
return;
case TSK_Undeclared:
break;
case TSK_ExplicitSpecialization:
case TSK_ImplicitInstantiation:
if (!CodeGenOpts.HiddenWeakTemplateVTables)
return;
break;
}
if (!(TVK != TVK_ForRTTI) || LangOpts.RTTI) {
if (Context.getKeyFunction(RD))
return;
}
GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
GV->setUnnamedAddr(true);
}
StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
if (!Str.empty())
return Str;
if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
IdentifierInfo *II = ND->getIdentifier();
assert(II && "Attempt to mangle unnamed decl.");
Str = II->getName();
return Str;
}
SmallString<256> Buffer;
llvm::raw_svector_ostream Out(Buffer);
if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
getCXXABI().getMangleContext().mangleBlock(BD, Out,
dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()));
else
getCXXABI().getMangleContext().mangleName(ND, Out);
Out.flush();
size_t Length = Buffer.size();
char *Name = MangledNamesAllocator.Allocate<char>(Length);
std::copy(Buffer.begin(), Buffer.end(), Name);
Str = StringRef(Name, Length);
return Str;
}
void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
const BlockDecl *BD) {
MangleContext &MangleCtx = getCXXABI().getMangleContext();
const Decl *D = GD.getDecl();
llvm::raw_svector_ostream Out(Buffer.getBuffer());
if (D == 0)
MangleCtx.mangleGlobalBlock(BD,
dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
else
MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
}
llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
return getModule().getNamedValue(Name);
}
void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
GlobalCtors.push_back(std::make_pair(Ctor, Priority));
}
void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
GlobalDtors.push_back(std::make_pair(Dtor, Priority));
}
void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
llvm::StructType *CtorStructTy =
llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL);
SmallVector<llvm::Constant*, 8> Ctors;
for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
llvm::Constant *S[] = {
llvm::ConstantInt::get(Int32Ty, I->second, false),
llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)
};
Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
}
if (!Ctors.empty()) {
llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
new llvm::GlobalVariable(TheModule, AT, false,
llvm::GlobalValue::AppendingLinkage,
llvm::ConstantArray::get(AT, Ctors),
GlobalName);
}
}
llvm::GlobalValue::LinkageTypes
CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
if (Linkage == GVA_Internal)
return llvm::Function::InternalLinkage;
if (D->hasAttr<DLLExportAttr>())
return llvm::Function::DLLExportLinkage;
if (D->hasAttr<WeakAttr>())
return llvm::Function::WeakAnyLinkage;
if (Linkage == GVA_C99Inline)
return llvm::Function::AvailableExternallyLinkage;
if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
return !Context.getLangOpts().AppleKext
? llvm::Function::LinkOnceODRLinkage
: llvm::Function::InternalLinkage;
if (Linkage == GVA_ExplicitTemplateInstantiation)
return !Context.getLangOpts().AppleKext
? llvm::Function::WeakODRLinkage
: llvm::Function::ExternalLinkage;
assert(Linkage == GVA_StrongExternal);
return llvm::Function::ExternalLinkage;
}
void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
llvm::GlobalValue *GV) {
SetCommonAttributes(D, GV);
}
void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
const CGFunctionInfo &Info,
llvm::Function *F) {
unsigned CallingConv;
AttributeListType AttributeList;
ConstructAttributeList(Info, D, AttributeList, CallingConv);
F->setAttributes(llvm::AttrListPtr::get(AttributeList));
F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
}
static bool hasUnwindExceptions(const LangOptions &LangOpts) {
if (!LangOpts.Exceptions) return false;
if (LangOpts.CXXExceptions) return true;
if (LangOpts.ObjCExceptions) {
return LangOpts.ObjCRuntime.hasUnwindExceptions();
}
return true;
}
void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
llvm::Function *F) {
if (CodeGenOpts.UnwindTables)
F->setHasUWTable();
if (!hasUnwindExceptions(LangOpts))
F->addFnAttr(llvm::Attribute::NoUnwind);
if (D->hasAttr<NakedAttr>()) {
F->addFnAttr(llvm::Attribute::Naked);
F->addFnAttr(llvm::Attribute::NoInline);
}
if (D->hasAttr<NoInlineAttr>())
F->addFnAttr(llvm::Attribute::NoInline);
if ((D->hasAttr<AlwaysInlineAttr>() || D->hasAttr<ForceInlineAttr>()) &&
!F->getFnAttributes().hasNoInlineAttr())
F->addFnAttr(llvm::Attribute::AlwaysInline);
if (D->hasAttr<ColdAttr>())
F->addFnAttr(llvm::Attribute::OptimizeForSize);
if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
F->setUnnamedAddr(true);
if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
if (MD->isVirtual())
F->setUnnamedAddr(true);
if (LangOpts.getStackProtector() == LangOptions::SSPOn)
F->addFnAttr(llvm::Attribute::StackProtect);
else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
F->addFnAttr(llvm::Attribute::StackProtectReq);
if (LangOpts.AddressSanitizer) {
if (!D->hasAttr<NoAddressSafetyAnalysisAttr>())
F->addFnAttr(llvm::Attribute::AddressSafety);
}
unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
if (alignment)
F->setAlignment(alignment);
if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
F->setAlignment(2);
}
void CodeGenModule::SetCommonAttributes(const Decl *D,
llvm::GlobalValue *GV) {
if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
setGlobalVisibility(GV, ND);
else
GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
if (D->hasAttr<UsedAttr>())
AddUsedGlobal(GV);
if (const SectionAttr *SA = D->getAttr<SectionAttr>())
GV->setSection(SA->getName());
getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
}
void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
llvm::Function *F,
const CGFunctionInfo &FI) {
SetLLVMFunctionAttributes(D, FI, F);
SetLLVMFunctionAttributesForDefinition(D, F);
F->setLinkage(llvm::Function::InternalLinkage);
SetCommonAttributes(D, F);
}
void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
llvm::Function *F,
bool IsIncompleteFunction) {
if (unsigned IID = F->getIntrinsicID()) {
F->setAttributes(llvm::Intrinsic::getAttributes((llvm::Intrinsic::ID)IID));
return;
}
const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
if (!IsIncompleteFunction)
SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
if (FD->hasAttr<DLLImportAttr>()) {
F->setLinkage(llvm::Function::DLLImportLinkage);
} else if (FD->hasAttr<WeakAttr>() ||
FD->isWeakImported()) {
F->setLinkage(llvm::Function::ExternalWeakLinkage);
} else {
F->setLinkage(llvm::Function::ExternalLinkage);
NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
F->setVisibility(GetLLVMVisibility(LV.visibility()));
}
}
if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
F->setSection(SA->getName());
}
void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
assert(!GV->isDeclaration() &&
"Only globals with definition can force usage.");
LLVMUsed.push_back(GV);
}
void CodeGenModule::EmitLLVMUsed() {
if (LLVMUsed.empty())
return;
SmallVector<llvm::Constant*, 8> UsedArray;
UsedArray.resize(LLVMUsed.size());
for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
UsedArray[i] =
llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
Int8PtrTy);
}
if (UsedArray.empty())
return;
llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
llvm::GlobalVariable *GV =
new llvm::GlobalVariable(getModule(), ATy, false,
llvm::GlobalValue::AppendingLinkage,
llvm::ConstantArray::get(ATy, UsedArray),
"llvm.used");
GV->setSection("llvm.metadata");
}
void CodeGenModule::EmitDeferred() {
while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
if (!DeferredVTables.empty()) {
const CXXRecordDecl *RD = DeferredVTables.back();
DeferredVTables.pop_back();
getCXXABI().EmitVTables(RD);
continue;
}
GlobalDecl D = DeferredDeclsToEmit.back();
DeferredDeclsToEmit.pop_back();
StringRef Name = getMangledName(D);
llvm::GlobalValue *CGRef = GetGlobalValue(Name);
assert(CGRef && "Deferred decl wasn't referenced?");
if (!CGRef->isDeclaration())
continue;
if (isa<llvm::GlobalAlias>(CGRef))
continue;
EmitGlobalDefinition(D);
}
}
void CodeGenModule::EmitGlobalAnnotations() {
if (Annotations.empty())
return;
llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
Annotations[0]->getType(), Annotations.size()), Annotations);
llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
"llvm.global.annotations");
gv->setSection(AnnotationSection);
}
llvm::Constant *CodeGenModule::EmitAnnotationString(llvm::StringRef Str) {
llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str);
if (i != AnnotationStrings.end())
return i->second;
llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
true, llvm::GlobalValue::PrivateLinkage, s, ".str");
gv->setSection(AnnotationSection);
gv->setUnnamedAddr(true);
AnnotationStrings[Str] = gv;
return gv;
}
llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
SourceManager &SM = getContext().getSourceManager();
PresumedLoc PLoc = SM.getPresumedLoc(Loc);
if (PLoc.isValid())
return EmitAnnotationString(PLoc.getFilename());
return EmitAnnotationString(SM.getBufferName(Loc));
}
llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
SourceManager &SM = getContext().getSourceManager();
PresumedLoc PLoc = SM.getPresumedLoc(L);
unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
SM.getExpansionLineNumber(L);
return llvm::ConstantInt::get(Int32Ty, LineNo);
}
llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
const AnnotateAttr *AA,
SourceLocation L) {
llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
*UnitGV = EmitAnnotationUnit(L),
*LineNoCst = EmitAnnotationLineNo(L);
llvm::Constant *Fields[4] = {
llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
LineNoCst
};
return llvm::ConstantStruct::getAnon(Fields);
}
void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
llvm::GlobalValue *GV) {
assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
for (specific_attr_iterator<AnnotateAttr>
ai = D->specific_attr_begin<AnnotateAttr>(),
ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
}
bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
if (LangOpts.EmitAllDecls)
return false;
return !getContext().DeclMustBeEmitted(Global);
}
llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
const AliasAttr *AA = VD->getAttr<AliasAttr>();
assert(AA && "No alias?");
llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
llvm::Constant *Aliasee;
if (isa<llvm::FunctionType>(DeclTy))
Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
false);
else
Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
llvm::PointerType::getUnqual(DeclTy), 0);
if (!Entry) {
llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
F->setLinkage(llvm::Function::ExternalWeakLinkage);
WeakRefReferences.insert(F);
}
return Aliasee;
}
void CodeGenModule::EmitGlobal(GlobalDecl GD) {
const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
if (Global->hasAttr<WeakRefAttr>())
return;
if (Global->hasAttr<AliasAttr>())
return EmitAliasDefinition(GD);
if (LangOpts.CUDA) {
if (CodeGenOpts.CUDAIsDevice) {
if (!Global->hasAttr<CUDADeviceAttr>() &&
!Global->hasAttr<CUDAGlobalAttr>() &&
!Global->hasAttr<CUDAConstantAttr>() &&
!Global->hasAttr<CUDASharedAttr>())
return;
} else {
if (!Global->hasAttr<CUDAHostAttr>() && (
Global->hasAttr<CUDADeviceAttr>() ||
Global->hasAttr<CUDAConstantAttr>() ||
Global->hasAttr<CUDASharedAttr>()))
return;
}
}
if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
if (!FD->doesThisDeclarationHaveABody()) {
if (!FD->doesDeclarationForceExternallyVisibleDefinition())
return;
const FunctionDecl *InlineDefinition = 0;
FD->getBody(InlineDefinition);
StringRef MangledName = getMangledName(GD);
DeferredDecls.erase(MangledName);
EmitGlobalDefinition(InlineDefinition);
return;
}
} else {
const VarDecl *VD = cast<VarDecl>(Global);
assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
return;
}
if (!MayDeferGeneration(Global)) {
EmitGlobalDefinition(GD);
return;
}
if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
cast<VarDecl>(Global)->hasInit()) {
DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
CXXGlobalInits.push_back(0);
}
StringRef MangledName = getMangledName(GD);
if (GetGlobalValue(MangledName))
DeferredDeclsToEmit.push_back(GD);
else {
DeferredDecls[MangledName] = GD;
}
}
namespace {
struct FunctionIsDirectlyRecursive :
public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
const StringRef Name;
const Builtin::Context &BI;
bool Result;
FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
Name(N), BI(C), Result(false) {
}
typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
bool TraverseCallExpr(CallExpr *E) {
const FunctionDecl *FD = E->getDirectCallee();
if (!FD)
return true;
AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
if (Attr && Name == Attr->getLabel()) {
Result = true;
return false;
}
unsigned BuiltinID = FD->getBuiltinID();
if (!BuiltinID)
return true;
StringRef BuiltinName = BI.GetName(BuiltinID);
if (BuiltinName.startswith("__builtin_") &&
Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
Result = true;
return false;
}
return true;
}
};
}
bool
CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
StringRef Name;
if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
if (!Attr)
return false;
Name = Attr->getLabel();
} else {
Name = FD->getName();
}
FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
return Walker.Result;
}
bool
CodeGenModule::shouldEmitFunction(const FunctionDecl *F) {
if (getFunctionLinkage(F) != llvm::Function::AvailableExternallyLinkage)
return true;
if (CodeGenOpts.OptimizationLevel == 0 &&
!F->hasAttr<AlwaysInlineAttr>() && !F->hasAttr<ForceInlineAttr>())
return false;
return !isTriviallyRecursive(F);
}
void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Context.getSourceManager(),
"Generating code for declaration");
if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
if (!shouldEmitFunction(Function))
return;
if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
EmitCXXConstructor(CD, GD.getCtorType());
else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
EmitCXXDestructor(DD, GD.getDtorType());
else
EmitGlobalFunctionDefinition(GD);
if (Method->isVirtual())
getVTables().EmitThunks(GD);
return;
}
return EmitGlobalFunctionDefinition(GD);
}
if (const VarDecl *VD = dyn_cast<VarDecl>(D))
return EmitGlobalVarDefinition(VD);
llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
}
llvm::Constant *
CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
llvm::Type *Ty,
GlobalDecl D, bool ForVTable,
llvm::Attributes ExtraAttrs) {
llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
if (Entry) {
if (WeakRefReferences.erase(Entry)) {
const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
if (FD && !FD->hasAttr<WeakAttr>())
Entry->setLinkage(llvm::Function::ExternalLinkage);
}
if (Entry->getType()->getElementType() == Ty)
return Entry;
return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
}
bool IsIncompleteFunction = false;
llvm::FunctionType *FTy;
if (isa<llvm::FunctionType>(Ty)) {
FTy = cast<llvm::FunctionType>(Ty);
} else {
FTy = llvm::FunctionType::get(VoidTy, false);
IsIncompleteFunction = true;
}
llvm::Function *F = llvm::Function::Create(FTy,
llvm::Function::ExternalLinkage,
MangledName, &getModule());
assert(F->getName() == MangledName && "name was uniqued!");
if (D.getDecl())
SetFunctionAttributes(D, F, IsIncompleteFunction);
if (ExtraAttrs != llvm::Attribute::None)
F->addFnAttr(ExtraAttrs);
llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
if (DDI != DeferredDecls.end()) {
DeferredDeclsToEmit.push_back(DDI->second);
DeferredDecls.erase(DDI);
} else if (getLangOpts().CPlusPlus && D.getDecl()) {
const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
FD = FD->getMostRecentDecl();
do {
if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
if (FD->isImplicit() && !ForVTable) {
assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
break;
} else if (FD->doesThisDeclarationHaveABody()) {
DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
break;
}
}
FD = FD->getPreviousDecl();
} while (FD);
}
if (!IsIncompleteFunction) {
assert(F->getType()->getElementType() == Ty);
return F;
}
llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
return llvm::ConstantExpr::getBitCast(F, PTy);
}
llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
llvm::Type *Ty,
bool ForVTable) {
if (!Ty)
Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
StringRef MangledName = getMangledName(GD);
return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
}
llvm::Constant *
CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
StringRef Name,
llvm::Attributes ExtraAttrs) {
return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), false,
ExtraAttrs);
}
bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
if (!Ty.isConstant(Context) && !Ty->isReferenceType())
return false;
if (Context.getLangOpts().CPlusPlus) {
if (const CXXRecordDecl *Record
= Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
return ExcludeCtor && !Record->hasMutableFields() &&
Record->hasTrivialDestructor();
}
return true;
}
llvm::Constant *
CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
llvm::PointerType *Ty,
const VarDecl *D,
bool UnnamedAddr) {
llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
if (Entry) {
if (WeakRefReferences.erase(Entry)) {
if (D && !D->hasAttr<WeakAttr>())
Entry->setLinkage(llvm::Function::ExternalLinkage);
}
if (UnnamedAddr)
Entry->setUnnamedAddr(true);
if (Entry->getType() == Ty)
return Entry;
return llvm::ConstantExpr::getBitCast(Entry, Ty);
}
llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
if (DDI != DeferredDecls.end()) {
DeferredDeclsToEmit.push_back(DDI->second);
DeferredDecls.erase(DDI);
}
unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
llvm::GlobalVariable *GV =
new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
llvm::GlobalValue::ExternalLinkage,
0, MangledName, 0,
llvm::GlobalVariable::NotThreadLocal, AddrSpace);
if (D) {
GV->setConstant(isTypeConstant(D->getType(), false));
NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
if (LV.linkage() != ExternalLinkage) {
} else {
if (D->hasAttr<DLLImportAttr>())
GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
if (LV.visibilityExplicit())
GV->setVisibility(GetLLVMVisibility(LV.visibility()));
}
if (D->isThreadSpecified())
setTLSMode(GV, *D);
}
if (AddrSpace != Ty->getAddressSpace())
return llvm::ConstantExpr::getBitCast(GV, Ty);
else
return GV;
}
llvm::GlobalVariable *
CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
llvm::Type *Ty,
llvm::GlobalValue::LinkageTypes Linkage) {
llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
llvm::GlobalVariable *OldGV = 0;
if (GV) {
if (GV->getType()->getElementType() == Ty)
return GV;
assert(GV->isDeclaration() && "Declaration has wrong type!");
OldGV = GV;
}
GV = new llvm::GlobalVariable(getModule(), Ty, true,
Linkage, 0, Name);
if (OldGV) {
GV->takeName(OldGV);
if (!OldGV->use_empty()) {
llvm::Constant *NewPtrForOldDecl =
llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
OldGV->replaceAllUsesWith(NewPtrForOldDecl);
}
OldGV->eraseFromParent();
}
return GV;
}
llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
llvm::Type *Ty) {
assert(D->hasGlobalStorage() && "Not a global variable");
QualType ASTTy = D->getType();
if (Ty == 0)
Ty = getTypes().ConvertTypeForMem(ASTTy);
llvm::PointerType *PTy =
llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
StringRef MangledName = getMangledName(D);
return GetOrCreateLLVMGlobal(MangledName, PTy, D);
}
llvm::Constant *
CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
StringRef Name) {
return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
true);
}
void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
assert(!D->getInit() && "Cannot emit definite definitions here!");
if (MayDeferGeneration(D)) {
StringRef MangledName = getMangledName(D);
if (!GetGlobalValue(MangledName)) {
DeferredDecls[MangledName] = D;
return;
}
}
EmitGlobalVarDefinition(D);
}
void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
if (DefinitionRequired)
getCXXABI().EmitVTables(Class);
}
llvm::GlobalVariable::LinkageTypes
CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
if (RD->getLinkage() != ExternalLinkage)
return llvm::GlobalVariable::InternalLinkage;
if (const CXXMethodDecl *KeyFunction
= RD->getASTContext().getKeyFunction(RD)) {
const FunctionDecl *Def = 0;
if (KeyFunction->hasBody(Def))
KeyFunction = cast<CXXMethodDecl>(Def);
switch (KeyFunction->getTemplateSpecializationKind()) {
case TSK_Undeclared:
case TSK_ExplicitSpecialization:
if (!Def && CodeGenOpts.OptimizationLevel)
return llvm::GlobalVariable::AvailableExternallyLinkage;
if (KeyFunction->isInlined())
return !Context.getLangOpts().AppleKext ?
llvm::GlobalVariable::LinkOnceODRLinkage :
llvm::Function::InternalLinkage;
return llvm::GlobalVariable::ExternalLinkage;
case TSK_ImplicitInstantiation:
return !Context.getLangOpts().AppleKext ?
llvm::GlobalVariable::LinkOnceODRLinkage :
llvm::Function::InternalLinkage;
case TSK_ExplicitInstantiationDefinition:
return !Context.getLangOpts().AppleKext ?
llvm::GlobalVariable::WeakODRLinkage :
llvm::Function::InternalLinkage;
case TSK_ExplicitInstantiationDeclaration:
return !Context.getLangOpts().AppleKext ?
llvm::GlobalVariable::LinkOnceODRLinkage :
llvm::Function::InternalLinkage;
}
}
if (Context.getLangOpts().AppleKext)
return llvm::Function::InternalLinkage;
switch (RD->getTemplateSpecializationKind()) {
case TSK_Undeclared:
case TSK_ExplicitSpecialization:
case TSK_ImplicitInstantiation:
case TSK_ExplicitInstantiationDeclaration:
return llvm::GlobalVariable::LinkOnceODRLinkage;
case TSK_ExplicitInstantiationDefinition:
return llvm::GlobalVariable::WeakODRLinkage;
}
llvm_unreachable("Invalid TemplateSpecializationKind!");
}
CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
return Context.toCharUnitsFromBits(
TheTargetData.getTypeStoreSizeInBits(Ty));
}
llvm::Constant *
CodeGenModule::MaybeEmitGlobalStdInitializerListInitializer(const VarDecl *D,
const Expr *rawInit) {
ArrayRef<ExprWithCleanups::CleanupObject> cleanups;
if (const ExprWithCleanups *withCleanups =
dyn_cast<ExprWithCleanups>(rawInit)) {
cleanups = withCleanups->getObjects();
rawInit = withCleanups->getSubExpr();
}
const InitListExpr *init = dyn_cast<InitListExpr>(rawInit);
if (!init || !init->initializesStdInitializerList() ||
init->getNumInits() == 0)
return 0;
ASTContext &ctx = getContext();
unsigned numInits = init->getNumInits();
for (unsigned i = 0; i < numInits; ++i) {
const InitListExpr *inner = dyn_cast<InitListExpr>(init->getInit(i));
if (inner && inner->initializesStdInitializerList()) {
ErrorUnsupported(inner, "nested global std::initializer_list");
return 0;
}
}
QualType elementType = init->getInit(0)->getType();
llvm::APInt numElements(ctx.getTypeSize(ctx.getSizeType()), numInits);
QualType arrayType = ctx.getConstantArrayType(elementType, numElements,
ArrayType::Normal, 0);
IdentifierInfo *name = &ctx.Idents.get(D->getNameAsString() + "__initlist");
TypeSourceInfo *sourceInfo = ctx.getTrivialTypeSourceInfo(
arrayType, D->getLocation());
VarDecl *backingArray = VarDecl::Create(ctx, const_cast<DeclContext*>(
D->getDeclContext()),
D->getLocStart(), D->getLocation(),
name, arrayType, sourceInfo,
SC_Static, SC_Static);
ArrayRef<Expr*> Inits(const_cast<InitListExpr*>(init)->getInits(),
init->getNumInits());
Expr *arrayInit = new (ctx) InitListExpr(ctx, init->getLBraceLoc(), Inits,
init->getRBraceLoc());
arrayInit->setType(arrayType);
if (!cleanups.empty())
arrayInit = ExprWithCleanups::Create(ctx, arrayInit, cleanups);
backingArray->setInit(arrayInit);
EmitGlobalVarDefinition(backingArray);
RecordDecl *record = init->getType()->castAs<RecordType>()->getDecl();
RecordDecl::field_iterator field = record->field_begin();
if (field == record->field_end()) {
ErrorUnsupported(D, "weird std::initializer_list");
return 0;
}
QualType elementPtr = ctx.getPointerType(elementType.withConst());
if (!ctx.hasSameType(field->getType(), elementPtr)) {
ErrorUnsupported(D, "weird std::initializer_list");
return 0;
}
++field;
if (field == record->field_end()) {
ErrorUnsupported(D, "weird std::initializer_list");
return 0;
}
bool isStartEnd = false;
if (ctx.hasSameType(field->getType(), elementPtr)) {
isStartEnd = true;
} else if(!ctx.hasSameType(field->getType(), ctx.getSizeType())) {
ErrorUnsupported(D, "weird std::initializer_list");
return 0;
}
APValue initListValue(APValue::UninitStruct(), 0, 2);
APValue &startField = initListValue.getStructField(0);
APValue::LValuePathEntry startOffsetPathEntry;
startOffsetPathEntry.ArrayIndex = 0;
startField = APValue(APValue::LValueBase(backingArray),
CharUnits::fromQuantity(0),
llvm::makeArrayRef(startOffsetPathEntry),
false, 0);
if (isStartEnd) {
APValue &endField = initListValue.getStructField(1);
APValue::LValuePathEntry endOffsetPathEntry;
endOffsetPathEntry.ArrayIndex = numInits;
endField = APValue(APValue::LValueBase(backingArray),
ctx.getTypeSizeInChars(elementType) * numInits,
llvm::makeArrayRef(endOffsetPathEntry),
true, 0);
} else {
APValue &sizeField = initListValue.getStructField(1);
sizeField = APValue(llvm::APSInt(numElements));
}
llvm::Constant *llvmInit =
EmitConstantValueForMemory(initListValue, D->getType());
assert(llvmInit && "failed to initialize as constant");
return llvmInit;
}
unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
unsigned AddrSpace) {
if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
if (D->hasAttr<CUDAConstantAttr>())
AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
else if (D->hasAttr<CUDASharedAttr>())
AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
else
AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
}
return AddrSpace;
}
void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
llvm::Constant *Init = 0;
QualType ASTTy = D->getType();
CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
bool NeedsGlobalCtor = false;
bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
const VarDecl *InitDecl;
const Expr *InitExpr = D->getAnyInitializer(InitDecl);
if (!InitExpr) {
assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Init = EmitNullConstant(D->getType());
} else {
Init = MaybeEmitGlobalStdInitializerListInitializer(D, InitExpr);
if (!Init) {
initializedGlobalDecl = GlobalDecl(D);
Init = EmitConstantInit(*InitDecl);
}
if (!Init) {
QualType T = InitExpr->getType();
if (D->getType()->isReferenceType())
T = D->getType();
if (getLangOpts().CPlusPlus) {
Init = EmitNullConstant(T);
NeedsGlobalCtor = true;
} else {
ErrorUnsupported(D, "static initializer");
Init = llvm::UndefValue::get(getTypes().ConvertType(T));
}
} else {
if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
DelayedCXXInitPosition.erase(D);
}
}
llvm::Type* InitType = Init->getType();
llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
assert(CE->getOpcode() == llvm::Instruction::BitCast ||
CE->getOpcode() == llvm::Instruction::GetElementPtr);
Entry = CE->getOperand(0);
}
llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
if (GV == 0 ||
GV->getType()->getElementType() != InitType ||
GV->getType()->getAddressSpace() !=
GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
Entry->setName(StringRef());
GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
llvm::Constant *NewPtrForOldDecl =
llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Entry->replaceAllUsesWith(NewPtrForOldDecl);
cast<llvm::GlobalValue>(Entry)->eraseFromParent();
}
if (D->hasAttr<AnnotateAttr>())
AddGlobalAnnotations(D, GV);
GV->setInitializer(Init);
GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
isTypeConstant(D->getType(), true));
GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
llvm::GlobalValue::LinkageTypes Linkage =
GetLLVMLinkageVarDefinition(D, GV);
GV->setLinkage(Linkage);
if (Linkage == llvm::GlobalVariable::CommonLinkage)
GV->setConstant(false);
SetCommonAttributes(D, GV);
if (NeedsGlobalCtor || NeedsGlobalDtor)
EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
if (LangOpts.AddressSanitizer && NeedsGlobalCtor) {
llvm::Module &M = getModule();
llvm::NamedMDNode *DynamicInitializers =
M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals");
llvm::Value *GlobalToAdd[] = { GV };
llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd);
DynamicInitializers->addOperand(ThisGlobal);
}
if (CGDebugInfo *DI = getModuleDebugInfo())
if (getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo)
DI->EmitGlobalVariable(GV, D);
}
llvm::GlobalValue::LinkageTypes
CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
llvm::GlobalVariable *GV) {
GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
if (Linkage == GVA_Internal)
return llvm::Function::InternalLinkage;
else if (D->hasAttr<DLLImportAttr>())
return llvm::Function::DLLImportLinkage;
else if (D->hasAttr<DLLExportAttr>())
return llvm::Function::DLLExportLinkage;
else if (D->hasAttr<WeakAttr>()) {
if (GV->isConstant())
return llvm::GlobalVariable::WeakODRLinkage;
else
return llvm::GlobalVariable::WeakAnyLinkage;
} else if (Linkage == GVA_TemplateInstantiation ||
Linkage == GVA_ExplicitTemplateInstantiation)
return llvm::GlobalVariable::WeakODRLinkage;
else if (!getLangOpts().CPlusPlus &&
((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
D->getAttr<CommonAttr>()) &&
!D->hasExternalStorage() && !D->getInit() &&
!D->getAttr<SectionAttr>() && !D->isThreadSpecified() &&
!D->getAttr<WeakImportAttr>()) {
return llvm::GlobalVariable::CommonLinkage;
}
return llvm::GlobalVariable::ExternalLinkage;
}
static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
llvm::Function *NewFn) {
llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
if (OldFn == 0) return;
llvm::Type *NewRetTy = NewFn->getReturnType();
SmallVector<llvm::Value*, 4> ArgList;
for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
UI != E; ) {
llvm::Value::use_iterator I = UI++; llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
if (!CI) continue; llvm::CallSite CS(CI);
if (!CI || !CS.isCallee(I)) continue;
if (CI->getType() != NewRetTy && !CI->use_empty())
continue;
llvm::SmallVector<llvm::AttributeWithIndex, 8> AttrVec;
llvm::AttrListPtr AttrList = CI->getAttributes();
llvm::Attributes RAttrs = AttrList.getRetAttributes();
if (RAttrs)
AttrVec.push_back(llvm::AttributeWithIndex::get(0, RAttrs));
unsigned ArgNo = 0;
bool DontTransform = false;
for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
if (CS.arg_size() == ArgNo ||
CS.getArgument(ArgNo)->getType() != AI->getType()) {
DontTransform = true;
break;
}
if (llvm::Attributes PAttrs = AttrList.getParamAttributes(ArgNo + 1))
AttrVec.push_back(llvm::AttributeWithIndex::get(ArgNo + 1, PAttrs));
}
if (DontTransform)
continue;
if (llvm::Attributes FnAttrs = AttrList.getFnAttributes())
AttrVec.push_back(llvm::AttributeWithIndex::get(~0, FnAttrs));
ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList, "", CI);
ArgList.clear();
if (!NewCall->getType()->isVoidTy())
NewCall->takeName(CI);
NewCall->setAttributes(llvm::AttrListPtr::get(AttrVec));
NewCall->setCallingConv(CI->getCallingConv());
if (!CI->use_empty())
CI->replaceAllUsesWith(NewCall);
if (!CI->getDebugLoc().isUnknown())
NewCall->setDebugLoc(CI->getDebugLoc());
CI->eraseFromParent();
}
}
void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
GetAddrOfGlobalVar(VD);
}
void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
assert(CE->getOpcode() == llvm::Instruction::BitCast);
Entry = CE->getOperand(0);
}
if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
assert(OldFn->isDeclaration() &&
"Shouldn't replace non-declaration");
OldFn->setName(StringRef());
llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
if (D->getType()->isFunctionNoProtoType()) {
ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
OldFn->removeDeadConstantUsers();
}
if (!Entry->use_empty()) {
llvm::Constant *NewPtrForOldDecl =
llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
Entry->replaceAllUsesWith(NewPtrForOldDecl);
}
OldFn->eraseFromParent();
Entry = NewFn;
}
llvm::Function *Fn = cast<llvm::Function>(Entry);
setFunctionLinkage(D, Fn);
setGlobalVisibility(Fn, D);
CodeGenFunction(*this).GenerateCode(D, Fn, FI);
SetFunctionDefinitionAttributes(D, Fn);
SetLLVMFunctionAttributesForDefinition(D, Fn);
if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
AddGlobalCtor(Fn, CA->getPriority());
if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
AddGlobalDtor(Fn, DA->getPriority());
if (D->hasAttr<AnnotateAttr>())
AddGlobalAnnotations(D, Fn);
}
void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
const AliasAttr *AA = D->getAttr<AliasAttr>();
assert(AA && "Not an alias?");
StringRef MangledName = getMangledName(GD);
llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
if (Entry && !Entry->isDeclaration())
return;
llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
llvm::Constant *Aliasee;
if (isa<llvm::FunctionType>(DeclTy))
Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
false);
else
Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
llvm::PointerType::getUnqual(DeclTy), 0);
llvm::GlobalValue *GA =
new llvm::GlobalAlias(Aliasee->getType(),
llvm::Function::ExternalLinkage,
"", Aliasee, &getModule());
if (Entry) {
assert(Entry->isDeclaration());
GA->takeName(Entry);
Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Entry->getType()));
Entry->eraseFromParent();
} else {
GA->setName(MangledName);
}
if (D->hasAttr<DLLExportAttr>()) {
if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
if (FD->hasBody())
GA->setLinkage(llvm::Function::DLLExportLinkage);
} else {
GA->setLinkage(llvm::Function::DLLExportLinkage);
}
} else if (D->hasAttr<WeakAttr>() ||
D->hasAttr<WeakRefAttr>() ||
D->isWeakImported()) {
GA->setLinkage(llvm::Function::WeakAnyLinkage);
}
SetCommonAttributes(D, GA);
}
llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
ArrayRef<llvm::Type*> Tys) {
return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
Tys);
}
static llvm::StringMapEntry<llvm::Constant*> &
GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
const StringLiteral *Literal,
bool TargetIsLSB,
bool &IsUTF16,
unsigned &StringLength) {
StringRef String = Literal->getString();
unsigned NumBytes = String.size();
if (!Literal->containsNonAsciiOrNull()) {
StringLength = NumBytes;
return Map.GetOrCreateValue(String);
}
IsUTF16 = true;
SmallVector<UTF16, 128> ToBuf(NumBytes + 1); const UTF8 *FromPtr = (const UTF8 *)String.data();
UTF16 *ToPtr = &ToBuf[0];
(void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
&ToPtr, ToPtr + NumBytes,
strictConversion);
StringLength = ToPtr - &ToBuf[0];
*ToPtr = 0;
return Map.
GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
(StringLength + 1) * 2));
}
static llvm::StringMapEntry<llvm::Constant*> &
GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
const StringLiteral *Literal,
unsigned &StringLength) {
StringRef String = Literal->getString();
StringLength = String.size();
return Map.GetOrCreateValue(String);
}
llvm::Constant *
CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
unsigned StringLength = 0;
bool isUTF16 = false;
llvm::StringMapEntry<llvm::Constant*> &Entry =
GetConstantCFStringEntry(CFConstantStringMap, Literal,
getTargetData().isLittleEndian(),
isUTF16, StringLength);
if (llvm::Constant *C = Entry.getValue())
return C;
llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
llvm::Constant *Zeros[] = { Zero, Zero };
if (!CFConstantStringClassRef) {
llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Ty = llvm::ArrayType::get(Ty, 0);
llvm::Constant *GV = CreateRuntimeVariable(Ty,
"__CFConstantStringClassReference");
CFConstantStringClassRef =
llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
}
QualType CFTy = getContext().getCFConstantStringType();
llvm::StructType *STy =
cast<llvm::StructType>(getTypes().ConvertType(CFTy));
llvm::Constant *Fields[4];
Fields[0] = CFConstantStringClassRef;
llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
llvm::ConstantInt::get(Ty, 0x07C8);
llvm::Constant *C = 0;
if (isUTF16) {
ArrayRef<uint16_t> Arr =
llvm::makeArrayRef<uint16_t>((uint16_t*)Entry.getKey().data(),
Entry.getKey().size() / 2);
C = llvm::ConstantDataArray::get(VMContext, Arr);
} else {
C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
}
llvm::GlobalValue::LinkageTypes Linkage;
if (isUTF16)
Linkage = llvm::GlobalValue::InternalLinkage;
else
Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
llvm::GlobalVariable *GV =
new llvm::GlobalVariable(getModule(), C->getType(), true,
Linkage, C, ".str");
GV->setUnnamedAddr(true);
if (isUTF16) {
CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
GV->setAlignment(Align.getQuantity());
} else {
CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
GV->setAlignment(Align.getQuantity());
}
Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
if (isUTF16)
Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
Ty = getTypes().ConvertType(getContext().LongTy);
Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
C = llvm::ConstantStruct::get(STy, Fields);
GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
llvm::GlobalVariable::PrivateLinkage, C,
"_unnamed_cfstring_");
if (const char *Sect = getContext().getTargetInfo().getCFStringSection())
GV->setSection(Sect);
Entry.setValue(GV);
return GV;
}
static RecordDecl *
CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
DeclContext *DC, IdentifierInfo *Id) {
SourceLocation Loc;
if (Ctx.getLangOpts().CPlusPlus)
return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
else
return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
}
llvm::Constant *
CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
unsigned StringLength = 0;
llvm::StringMapEntry<llvm::Constant*> &Entry =
GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
if (llvm::Constant *C = Entry.getValue())
return C;
llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
llvm::Constant *Zeros[] = { Zero, Zero };
if (!ConstantStringClassRef) {
std::string StringClass(getLangOpts().ObjCConstantStringClass);
llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
llvm::Constant *GV;
if (LangOpts.ObjCRuntime.isNonFragile()) {
std::string str =
StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
: "OBJC_CLASS_$_" + StringClass;
GV = getObjCRuntime().GetClassGlobal(str);
llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
ConstantStringClassRef =
llvm::ConstantExpr::getBitCast(GV, PTy);
} else {
std::string str =
StringClass.empty() ? "_NSConstantStringClassReference"
: "_" + StringClass + "ClassReference";
llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
GV = CreateRuntimeVariable(PTy, str);
ConstantStringClassRef =
llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
}
}
if (!NSConstantStringType) {
RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
Context.getTranslationUnitDecl(),
&Context.Idents.get("__builtin_NSString"));
D->startDefinition();
QualType FieldTypes[3];
FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
FieldTypes[2] = Context.UnsignedIntTy;
for (unsigned i = 0; i < 3; ++i) {
FieldDecl *Field = FieldDecl::Create(Context, D,
SourceLocation(),
SourceLocation(), 0,
FieldTypes[i], 0,
0,
false,
ICIS_NoInit);
Field->setAccess(AS_public);
D->addDecl(Field);
}
D->completeDefinition();
QualType NSTy = Context.getTagDeclType(D);
NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
}
llvm::Constant *Fields[3];
Fields[0] = ConstantStringClassRef;
llvm::Constant *C =
llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
llvm::GlobalValue::LinkageTypes Linkage;
bool isConstant;
Linkage = llvm::GlobalValue::PrivateLinkage;
isConstant = !LangOpts.WritableStrings;
llvm::GlobalVariable *GV =
new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
".str");
GV->setUnnamedAddr(true);
CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
GV->setAlignment(Align.getQuantity());
Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
llvm::GlobalVariable::PrivateLinkage, C,
"_unnamed_nsstring_");
if (const char *Sect =
LangOpts.ObjCRuntime.isNonFragile()
? getContext().getTargetInfo().getNSStringNonFragileABISection()
: getContext().getTargetInfo().getNSStringSection())
GV->setSection(Sect);
Entry.setValue(GV);
return GV;
}
QualType CodeGenModule::getObjCFastEnumerationStateType() {
if (ObjCFastEnumerationStateType.isNull()) {
RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
Context.getTranslationUnitDecl(),
&Context.Idents.get("__objcFastEnumerationState"));
D->startDefinition();
QualType FieldTypes[] = {
Context.UnsignedLongTy,
Context.getPointerType(Context.getObjCIdType()),
Context.getPointerType(Context.UnsignedLongTy),
Context.getConstantArrayType(Context.UnsignedLongTy,
llvm::APInt(32, 5), ArrayType::Normal, 0)
};
for (size_t i = 0; i < 4; ++i) {
FieldDecl *Field = FieldDecl::Create(Context,
D,
SourceLocation(),
SourceLocation(), 0,
FieldTypes[i], 0,
0,
false,
ICIS_NoInit);
Field->setAccess(AS_public);
D->addDecl(Field);
}
D->completeDefinition();
ObjCFastEnumerationStateType = Context.getTagDeclType(D);
}
return ObjCFastEnumerationStateType;
}
llvm::Constant *
CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
assert(!E->getType()->isPointerType() && "Strings are always arrays");
if (E->getCharByteWidth() == 1) {
SmallString<64> Str(E->getString());
const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
Str.resize(CAT->getSize().getZExtValue());
return llvm::ConstantDataArray::getString(VMContext, Str, false);
}
llvm::ArrayType *AType =
cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
llvm::Type *ElemTy = AType->getElementType();
unsigned NumElements = AType->getNumElements();
if (ElemTy->getPrimitiveSizeInBits() == 16) {
SmallVector<uint16_t, 32> Elements;
Elements.reserve(NumElements);
for(unsigned i = 0, e = E->getLength(); i != e; ++i)
Elements.push_back(E->getCodeUnit(i));
Elements.resize(NumElements);
return llvm::ConstantDataArray::get(VMContext, Elements);
}
assert(ElemTy->getPrimitiveSizeInBits() == 32);
SmallVector<uint32_t, 32> Elements;
Elements.reserve(NumElements);
for(unsigned i = 0, e = E->getLength(); i != e; ++i)
Elements.push_back(E->getCodeUnit(i));
Elements.resize(NumElements);
return llvm::ConstantDataArray::get(VMContext, Elements);
}
llvm::Constant *
CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
CharUnits Align = getContext().getTypeAlignInChars(S->getType());
if (S->isAscii() || S->isUTF8()) {
SmallString<64> Str(S->getString());
const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
Str.resize(CAT->getSize().getZExtValue());
return GetAddrOfConstantString(Str, 0, Align.getQuantity());
}
llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
llvm::GlobalVariable *GV =
new llvm::GlobalVariable(getModule(),C->getType(),
!LangOpts.WritableStrings,
llvm::GlobalValue::PrivateLinkage,
C,".str");
GV->setAlignment(Align.getQuantity());
GV->setUnnamedAddr(true);
return GV;
}
llvm::Constant *
CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
std::string Str;
getContext().getObjCEncodingForType(E->getEncodedType(), Str);
return GetAddrOfConstantCString(Str);
}
static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
bool constant,
CodeGenModule &CGM,
const char *GlobalName,
unsigned Alignment) {
llvm::Constant *C =
llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
llvm::GlobalVariable *GV =
new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
llvm::GlobalValue::PrivateLinkage,
C, GlobalName);
GV->setAlignment(Alignment);
GV->setUnnamedAddr(true);
return GV;
}
llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
const char *GlobalName,
unsigned Alignment) {
if (!GlobalName)
GlobalName = ".str";
if (LangOpts.WritableStrings)
return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
ConstantStringMap.GetOrCreateValue(Str);
if (llvm::GlobalVariable *GV = Entry.getValue()) {
if (Alignment > GV->getAlignment()) {
GV->setAlignment(Alignment);
}
return GV;
}
llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
Alignment);
Entry.setValue(GV);
return GV;
}
llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
const char *GlobalName,
unsigned Alignment) {
StringRef StrWithNull(Str.c_str(), Str.size() + 1);
return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
}
void CodeGenModule::EmitObjCPropertyImplementations(const
ObjCImplementationDecl *D) {
for (ObjCImplementationDecl::propimpl_iterator
i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
ObjCPropertyImplDecl *PID = *i;
if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
ObjCPropertyDecl *PD = PID->getPropertyDecl();
if (!D->getInstanceMethod(PD->getGetterName()))
CodeGenFunction(*this).GenerateObjCGetter(
const_cast<ObjCImplementationDecl *>(D), PID);
if (!PD->isReadOnly() &&
!D->getInstanceMethod(PD->getSetterName()))
CodeGenFunction(*this).GenerateObjCSetter(
const_cast<ObjCImplementationDecl *>(D), PID);
}
}
}
static bool needsDestructMethod(ObjCImplementationDecl *impl) {
const ObjCInterfaceDecl *iface = impl->getClassInterface();
for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
ivar; ivar = ivar->getNextIvar())
if (ivar->getType().isDestructedType())
return true;
return false;
}
void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
if (needsDestructMethod(D)) {
IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
ObjCMethodDecl *DTORMethod =
ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
cxxSelector, getContext().VoidTy, 0, D,
true, false,
true, true,
false, ObjCMethodDecl::Required);
D->addInstanceMethod(DTORMethod);
CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
D->setHasDestructors(true);
}
if (D->getNumIvarInitializers() == 0)
return;
IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
D->getLocation(),
D->getLocation(),
cxxSelector,
getContext().getObjCIdType(), 0,
D, true,
false,
true,
true,
false,
ObjCMethodDecl::Required);
D->addInstanceMethod(CTORMethod);
CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
D->setHasNonZeroConstructors(true);
}
void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
I != E; ++I)
EmitTopLevelDecl(*I);
}
void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
ErrorUnsupported(LSD, "linkage spec");
return;
}
for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
I != E; ++I) {
if (ObjCImplDecl *OID = dyn_cast<ObjCImplDecl>(*I)) {
for (ObjCContainerDecl::method_iterator M = OID->meth_begin(),
MEnd = OID->meth_end();
M != MEnd; ++M)
EmitTopLevelDecl(*M);
}
EmitTopLevelDecl(*I);
}
}
void CodeGenModule::EmitTopLevelDecl(Decl *D) {
if (Diags.hasErrorOccurred())
return;
if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
return;
switch (D->getKind()) {
case Decl::CXXConversion:
case Decl::CXXMethod:
case Decl::Function:
if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
cast<FunctionDecl>(D)->isLateTemplateParsed())
return;
EmitGlobal(cast<FunctionDecl>(D));
break;
case Decl::Var:
EmitGlobal(cast<VarDecl>(D));
break;
case Decl::IndirectField:
break;
case Decl::Namespace:
EmitNamespace(cast<NamespaceDecl>(D));
break;
case Decl::UsingShadow:
case Decl::Using:
case Decl::UsingDirective:
case Decl::ClassTemplate:
case Decl::FunctionTemplate:
case Decl::TypeAliasTemplate:
case Decl::NamespaceAlias:
case Decl::Block:
case Decl::Import:
break;
case Decl::CXXConstructor:
if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
cast<FunctionDecl>(D)->isLateTemplateParsed())
return;
EmitCXXConstructors(cast<CXXConstructorDecl>(D));
break;
case Decl::CXXDestructor:
if (cast<FunctionDecl>(D)->isLateTemplateParsed())
return;
EmitCXXDestructors(cast<CXXDestructorDecl>(D));
break;
case Decl::StaticAssert:
break;
case Decl::ObjCInterface:
case Decl::ObjCCategory:
break;
case Decl::ObjCProtocol: {
ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
if (Proto->isThisDeclarationADefinition())
ObjCRuntime->GenerateProtocol(Proto);
break;
}
case Decl::ObjCCategoryImpl:
ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
break;
case Decl::ObjCImplementation: {
ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
EmitObjCPropertyImplementations(OMD);
EmitObjCIvarInitializations(OMD);
ObjCRuntime->GenerateClass(OMD);
if (CGDebugInfo *DI = getModuleDebugInfo())
DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(OMD->getClassInterface()),
OMD->getLocation());
break;
}
case Decl::ObjCMethod: {
ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
if (OMD->getBody())
CodeGenFunction(*this).GenerateObjCMethod(OMD);
break;
}
case Decl::ObjCCompatibleAlias:
ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
break;
case Decl::LinkageSpec:
EmitLinkageSpec(cast<LinkageSpecDecl>(D));
break;
case Decl::FileScopeAsm: {
FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
StringRef AsmString = AD->getAsmString()->getString();
const std::string &S = getModule().getModuleInlineAsm();
if (S.empty())
getModule().setModuleInlineAsm(AsmString);
else if (S.end()[-1] == '\n')
getModule().setModuleInlineAsm(S + AsmString.str());
else
getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
break;
}
default:
assert(isa<TypeDecl>(D) && "Unsupported decl kind");
}
}
static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
const void *Ptr) {
uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
return llvm::ConstantInt::get(i64, PtrInt);
}
static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
llvm::NamedMDNode *&GlobalMetadata,
GlobalDecl D,
llvm::GlobalValue *Addr) {
if (!GlobalMetadata)
GlobalMetadata =
CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
llvm::Value *Ops[] = {
Addr,
GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
};
GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
}
void CodeGenModule::EmitDeclMetadata() {
llvm::NamedMDNode *GlobalMetadata = 0;
for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
I = MangledDeclNames.begin(), E = MangledDeclNames.end();
I != E; ++I) {
llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
}
}
void CodeGenFunction::EmitDeclMetadata() {
if (LocalDeclMap.empty()) return;
llvm::LLVMContext &Context = getLLVMContext();
unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
llvm::NamedMDNode *GlobalMetadata = 0;
for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
const Decl *D = I->first;
llvm::Value *Addr = I->second;
if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
} else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
}
}
}
void CodeGenModule::EmitCoverageFile() {
if (!getCodeGenOpts().CoverageFile.empty()) {
if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
llvm::LLVMContext &Ctx = TheModule.getContext();
llvm::MDString *CoverageFile =
llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
llvm::MDNode *CU = CUNode->getOperand(i);
llvm::Value *node[] = { CoverageFile, CU };
llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
GCov->addOperand(N);
}
}
}
}