1f22ef01cSRoman Divacky //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This coordinates the per-module state used while generating code.
11f22ef01cSRoman Divacky //
12f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
13f22ef01cSRoman Divacky 
14f22ef01cSRoman Divacky #include "CodeGenModule.h"
150623d748SDimitry Andric #include "CGBlocks.h"
166122f3e6SDimitry Andric #include "CGCUDARuntime.h"
17e580952dSDimitry Andric #include "CGCXXABI.h"
18139f7f9bSDimitry Andric #include "CGCall.h"
19139f7f9bSDimitry Andric #include "CGDebugInfo.h"
20f22ef01cSRoman Divacky #include "CGObjCRuntime.h"
216122f3e6SDimitry Andric #include "CGOpenCLRuntime.h"
2259d1ed5bSDimitry Andric #include "CGOpenMPRuntime.h"
23e7145dcbSDimitry Andric #include "CGOpenMPRuntimeNVPTX.h"
24139f7f9bSDimitry Andric #include "CodeGenFunction.h"
2559d1ed5bSDimitry Andric #include "CodeGenPGO.h"
269a199699SDimitry Andric #include "ConstantEmitter.h"
2739d628a0SDimitry Andric #include "CoverageMappingGen.h"
28f22ef01cSRoman Divacky #include "TargetInfo.h"
29f22ef01cSRoman Divacky #include "clang/AST/ASTContext.h"
30f22ef01cSRoman Divacky #include "clang/AST/CharUnits.h"
31f22ef01cSRoman Divacky #include "clang/AST/DeclCXX.h"
32139f7f9bSDimitry Andric #include "clang/AST/DeclObjC.h"
33ffd1746dSEd Schouten #include "clang/AST/DeclTemplate.h"
342754fe60SDimitry Andric #include "clang/AST/Mangle.h"
35f22ef01cSRoman Divacky #include "clang/AST/RecordLayout.h"
36f8254f43SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h"
37dff0c46cSDimitry Andric #include "clang/Basic/Builtins.h"
38139f7f9bSDimitry Andric #include "clang/Basic/CharInfo.h"
39*b5893f02SDimitry Andric #include "clang/Basic/CodeGenOptions.h"
40f22ef01cSRoman Divacky #include "clang/Basic/Diagnostic.h"
41139f7f9bSDimitry Andric #include "clang/Basic/Module.h"
42f22ef01cSRoman Divacky #include "clang/Basic/SourceManager.h"
43f22ef01cSRoman Divacky #include "clang/Basic/TargetInfo.h"
44f785676fSDimitry Andric #include "clang/Basic/Version.h"
4520e90f04SDimitry Andric #include "clang/CodeGen/ConstantInitBuilder.h"
46*b5893f02SDimitry Andric #include "clang/Frontend/FrontendDiagnostic.h"
47*b5893f02SDimitry Andric #include "llvm/ADT/StringSwitch.h"
48f22ef01cSRoman Divacky #include "llvm/ADT/Triple.h"
49d8866befSDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
5059d1ed5bSDimitry Andric #include "llvm/IR/CallSite.h"
51139f7f9bSDimitry Andric #include "llvm/IR/CallingConv.h"
52139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h"
53139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h"
54139f7f9bSDimitry Andric #include "llvm/IR/LLVMContext.h"
55139f7f9bSDimitry Andric #include "llvm/IR/Module.h"
5659d1ed5bSDimitry Andric #include "llvm/ProfileData/InstrProfReader.h"
57*b5893f02SDimitry Andric #include "llvm/Support/CodeGen.h"
58139f7f9bSDimitry Andric #include "llvm/Support/ConvertUTF.h"
59f22ef01cSRoman Divacky #include "llvm/Support/ErrorHandling.h"
600623d748SDimitry Andric #include "llvm/Support/MD5.h"
61139f7f9bSDimitry Andric 
62f22ef01cSRoman Divacky using namespace clang;
63f22ef01cSRoman Divacky using namespace CodeGen;
64f22ef01cSRoman Divacky 
659a199699SDimitry Andric static llvm::cl::opt<bool> LimitedCoverage(
669a199699SDimitry Andric     "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
679a199699SDimitry Andric     llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
689a199699SDimitry Andric     llvm::cl::init(false));
699a199699SDimitry Andric 
706122f3e6SDimitry Andric static const char AnnotationSection[] = "llvm.metadata";
716122f3e6SDimitry Andric 
createCXXABI(CodeGenModule & CGM)7259d1ed5bSDimitry Andric static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
73284c1978SDimitry Andric   switch (CGM.getTarget().getCXXABI().getKind()) {
74139f7f9bSDimitry Andric   case TargetCXXABI::GenericAArch64:
75139f7f9bSDimitry Andric   case TargetCXXABI::GenericARM:
76139f7f9bSDimitry Andric   case TargetCXXABI::iOS:
7759d1ed5bSDimitry Andric   case TargetCXXABI::iOS64:
780623d748SDimitry Andric   case TargetCXXABI::WatchOS:
79ef6fa9e2SDimitry Andric   case TargetCXXABI::GenericMIPS:
80139f7f9bSDimitry Andric   case TargetCXXABI::GenericItanium:
810623d748SDimitry Andric   case TargetCXXABI::WebAssembly:
8259d1ed5bSDimitry Andric     return CreateItaniumCXXABI(CGM);
83139f7f9bSDimitry Andric   case TargetCXXABI::Microsoft:
8459d1ed5bSDimitry Andric     return CreateMicrosoftCXXABI(CGM);
85e580952dSDimitry Andric   }
86e580952dSDimitry Andric 
87e580952dSDimitry Andric   llvm_unreachable("invalid C++ ABI kind");
88e580952dSDimitry Andric }
89e580952dSDimitry Andric 
CodeGenModule(ASTContext & C,const HeaderSearchOptions & HSO,const PreprocessorOptions & PPO,const CodeGenOptions & CGO,llvm::Module & M,DiagnosticsEngine & diags,CoverageSourceInfo * CoverageInfo)903dac3a9bSDimitry Andric CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
913dac3a9bSDimitry Andric                              const PreprocessorOptions &PPO,
923dac3a9bSDimitry Andric                              const CodeGenOptions &CGO, llvm::Module &M,
9339d628a0SDimitry Andric                              DiagnosticsEngine &diags,
9439d628a0SDimitry Andric                              CoverageSourceInfo *CoverageInfo)
953dac3a9bSDimitry Andric     : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
963dac3a9bSDimitry Andric       PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
970623d748SDimitry Andric       Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
98e7145dcbSDimitry Andric       VMContext(M.getContext()), Types(*this), VTables(*this),
99e7145dcbSDimitry Andric       SanitizerMD(new SanitizerMetadata(*this)) {
100dff0c46cSDimitry Andric 
101dff0c46cSDimitry Andric   // Initialize the type cache.
102dff0c46cSDimitry Andric   llvm::LLVMContext &LLVMContext = M.getContext();
103dff0c46cSDimitry Andric   VoidTy = llvm::Type::getVoidTy(LLVMContext);
104dff0c46cSDimitry Andric   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
105dff0c46cSDimitry Andric   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
106dff0c46cSDimitry Andric   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
107dff0c46cSDimitry Andric   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
10813ddaa84SDimitry Andric   HalfTy = llvm::Type::getHalfTy(LLVMContext);
109dff0c46cSDimitry Andric   FloatTy = llvm::Type::getFloatTy(LLVMContext);
110dff0c46cSDimitry Andric   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
111dff0c46cSDimitry Andric   PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
112dff0c46cSDimitry Andric   PointerAlignInBytes =
113dff0c46cSDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
11444290647SDimitry Andric   SizeSizeInBytes =
11544290647SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
1160623d748SDimitry Andric   IntAlignInBytes =
1170623d748SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
118dff0c46cSDimitry Andric   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
11944290647SDimitry Andric   IntPtrTy = llvm::IntegerType::get(LLVMContext,
12044290647SDimitry Andric     C.getTargetInfo().getMaxPointerWidth());
121dff0c46cSDimitry Andric   Int8PtrTy = Int8Ty->getPointerTo(0);
122dff0c46cSDimitry Andric   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
1236bc11b14SDimitry Andric   AllocaInt8PtrTy = Int8Ty->getPointerTo(
1246bc11b14SDimitry Andric       M.getDataLayout().getAllocaAddrSpace());
125d8866befSDimitry Andric   ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
126dff0c46cSDimitry Andric 
127139f7f9bSDimitry Andric   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
128139f7f9bSDimitry Andric 
129*b5893f02SDimitry Andric   if (LangOpts.ObjC)
1303b0f4066SDimitry Andric     createObjCRuntime();
131dff0c46cSDimitry Andric   if (LangOpts.OpenCL)
1326122f3e6SDimitry Andric     createOpenCLRuntime();
13359d1ed5bSDimitry Andric   if (LangOpts.OpenMP)
13459d1ed5bSDimitry Andric     createOpenMPRuntime();
135dff0c46cSDimitry Andric   if (LangOpts.CUDA)
1366122f3e6SDimitry Andric     createCUDARuntime();
137f22ef01cSRoman Divacky 
1387ae0e2c9SDimitry Andric   // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
13939d628a0SDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
1407ae0e2c9SDimitry Andric       (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
1419a199699SDimitry Andric     TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
142e7145dcbSDimitry Andric                                getCXXABI().getMangleContext()));
1432754fe60SDimitry Andric 
1443b0f4066SDimitry Andric   // If debug info or coverage generation is enabled, create the CGDebugInfo
1453b0f4066SDimitry Andric   // object.
146e7145dcbSDimitry Andric   if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
147e7145dcbSDimitry Andric       CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
148e7145dcbSDimitry Andric     DebugInfo.reset(new CGDebugInfo(*this));
1492754fe60SDimitry Andric 
1502754fe60SDimitry Andric   Block.GlobalUniqueCount = 0;
1512754fe60SDimitry Andric 
152*b5893f02SDimitry Andric   if (C.getLangOpts().ObjC)
153e7145dcbSDimitry Andric     ObjCData.reset(new ObjCEntrypoints());
15459d1ed5bSDimitry Andric 
155e7145dcbSDimitry Andric   if (CodeGenOpts.hasProfileClangUse()) {
156e7145dcbSDimitry Andric     auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
157*b5893f02SDimitry Andric         CodeGenOpts.ProfileInstrumentUsePath, CodeGenOpts.ProfileRemappingFile);
158e7145dcbSDimitry Andric     if (auto E = ReaderOrErr.takeError()) {
15959d1ed5bSDimitry Andric       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1603dac3a9bSDimitry Andric                                               "Could not read profile %0: %1");
161e7145dcbSDimitry Andric       llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
162e7145dcbSDimitry Andric         getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
163e7145dcbSDimitry Andric                                   << EI.message();
164e7145dcbSDimitry Andric       });
16533956c43SDimitry Andric     } else
16633956c43SDimitry Andric       PGOReader = std::move(ReaderOrErr.get());
16759d1ed5bSDimitry Andric   }
16839d628a0SDimitry Andric 
16939d628a0SDimitry Andric   // If coverage mapping generation is enabled, create the
17039d628a0SDimitry Andric   // CoverageMappingModuleGen object.
17139d628a0SDimitry Andric   if (CodeGenOpts.CoverageMapping)
17239d628a0SDimitry Andric     CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
173f22ef01cSRoman Divacky }
174f22ef01cSRoman Divacky 
~CodeGenModule()175e7145dcbSDimitry Andric CodeGenModule::~CodeGenModule() {}
176f22ef01cSRoman Divacky 
createObjCRuntime()177f22ef01cSRoman Divacky void CodeGenModule::createObjCRuntime() {
1787ae0e2c9SDimitry Andric   // This is just isGNUFamily(), but we want to force implementors of
1797ae0e2c9SDimitry Andric   // new ABIs to decide how best to do this.
1807ae0e2c9SDimitry Andric   switch (LangOpts.ObjCRuntime.getKind()) {
1817ae0e2c9SDimitry Andric   case ObjCRuntime::GNUstep:
1827ae0e2c9SDimitry Andric   case ObjCRuntime::GCC:
1837ae0e2c9SDimitry Andric   case ObjCRuntime::ObjFW:
184e7145dcbSDimitry Andric     ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
1857ae0e2c9SDimitry Andric     return;
1867ae0e2c9SDimitry Andric 
1877ae0e2c9SDimitry Andric   case ObjCRuntime::FragileMacOSX:
1887ae0e2c9SDimitry Andric   case ObjCRuntime::MacOSX:
1897ae0e2c9SDimitry Andric   case ObjCRuntime::iOS:
1900623d748SDimitry Andric   case ObjCRuntime::WatchOS:
191e7145dcbSDimitry Andric     ObjCRuntime.reset(CreateMacObjCRuntime(*this));
1927ae0e2c9SDimitry Andric     return;
1937ae0e2c9SDimitry Andric   }
1947ae0e2c9SDimitry Andric   llvm_unreachable("bad runtime kind");
1956122f3e6SDimitry Andric }
1966122f3e6SDimitry Andric 
createOpenCLRuntime()1976122f3e6SDimitry Andric void CodeGenModule::createOpenCLRuntime() {
198e7145dcbSDimitry Andric   OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
1996122f3e6SDimitry Andric }
2006122f3e6SDimitry Andric 
createOpenMPRuntime()20159d1ed5bSDimitry Andric void CodeGenModule::createOpenMPRuntime() {
202e7145dcbSDimitry Andric   // Select a specialized code generation class based on the target, if any.
203e7145dcbSDimitry Andric   // If it does not exist use the default implementation.
20444290647SDimitry Andric   switch (getTriple().getArch()) {
205e7145dcbSDimitry Andric   case llvm::Triple::nvptx:
206e7145dcbSDimitry Andric   case llvm::Triple::nvptx64:
207e7145dcbSDimitry Andric     assert(getLangOpts().OpenMPIsDevice &&
208e7145dcbSDimitry Andric            "OpenMP NVPTX is only prepared to deal with device code.");
209e7145dcbSDimitry Andric     OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
210e7145dcbSDimitry Andric     break;
211e7145dcbSDimitry Andric   default:
21230785c0eSDimitry Andric     if (LangOpts.OpenMPSimd)
21330785c0eSDimitry Andric       OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
21430785c0eSDimitry Andric     else
215e7145dcbSDimitry Andric       OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
216e7145dcbSDimitry Andric     break;
217e7145dcbSDimitry Andric   }
21859d1ed5bSDimitry Andric }
21959d1ed5bSDimitry Andric 
createCUDARuntime()2206122f3e6SDimitry Andric void CodeGenModule::createCUDARuntime() {
221e7145dcbSDimitry Andric   CUDARuntime.reset(CreateNVCUDARuntime(*this));
222f22ef01cSRoman Divacky }
223f22ef01cSRoman Divacky 
addReplacement(StringRef Name,llvm::Constant * C)22439d628a0SDimitry Andric void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
22539d628a0SDimitry Andric   Replacements[Name] = C;
22639d628a0SDimitry Andric }
22739d628a0SDimitry Andric 
applyReplacements()228f785676fSDimitry Andric void CodeGenModule::applyReplacements() {
2298f0fd8f6SDimitry Andric   for (auto &I : Replacements) {
2308f0fd8f6SDimitry Andric     StringRef MangledName = I.first();
2318f0fd8f6SDimitry Andric     llvm::Constant *Replacement = I.second;
232f785676fSDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
233f785676fSDimitry Andric     if (!Entry)
234f785676fSDimitry Andric       continue;
23559d1ed5bSDimitry Andric     auto *OldF = cast<llvm::Function>(Entry);
23659d1ed5bSDimitry Andric     auto *NewF = dyn_cast<llvm::Function>(Replacement);
237f785676fSDimitry Andric     if (!NewF) {
23859d1ed5bSDimitry Andric       if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
23959d1ed5bSDimitry Andric         NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
24059d1ed5bSDimitry Andric       } else {
24159d1ed5bSDimitry Andric         auto *CE = cast<llvm::ConstantExpr>(Replacement);
242f785676fSDimitry Andric         assert(CE->getOpcode() == llvm::Instruction::BitCast ||
243f785676fSDimitry Andric                CE->getOpcode() == llvm::Instruction::GetElementPtr);
244f785676fSDimitry Andric         NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
245f785676fSDimitry Andric       }
24659d1ed5bSDimitry Andric     }
247f785676fSDimitry Andric 
248f785676fSDimitry Andric     // Replace old with new, but keep the old order.
249f785676fSDimitry Andric     OldF->replaceAllUsesWith(Replacement);
250f785676fSDimitry Andric     if (NewF) {
251f785676fSDimitry Andric       NewF->removeFromParent();
2520623d748SDimitry Andric       OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
2530623d748SDimitry Andric                                                        NewF);
254f785676fSDimitry Andric     }
255f785676fSDimitry Andric     OldF->eraseFromParent();
256f785676fSDimitry Andric   }
257f785676fSDimitry Andric }
258f785676fSDimitry Andric 
addGlobalValReplacement(llvm::GlobalValue * GV,llvm::Constant * C)2590623d748SDimitry Andric void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
2600623d748SDimitry Andric   GlobalValReplacements.push_back(std::make_pair(GV, C));
2610623d748SDimitry Andric }
2620623d748SDimitry Andric 
applyGlobalValReplacements()2630623d748SDimitry Andric void CodeGenModule::applyGlobalValReplacements() {
2640623d748SDimitry Andric   for (auto &I : GlobalValReplacements) {
2650623d748SDimitry Andric     llvm::GlobalValue *GV = I.first;
2660623d748SDimitry Andric     llvm::Constant *C = I.second;
2670623d748SDimitry Andric 
2680623d748SDimitry Andric     GV->replaceAllUsesWith(C);
2690623d748SDimitry Andric     GV->eraseFromParent();
2700623d748SDimitry Andric   }
2710623d748SDimitry Andric }
2720623d748SDimitry Andric 
27359d1ed5bSDimitry Andric // This is only used in aliases that we created and we know they have a
27459d1ed5bSDimitry Andric // linear structure.
getAliasedGlobal(const llvm::GlobalIndirectSymbol & GIS)275e7145dcbSDimitry Andric static const llvm::GlobalObject *getAliasedGlobal(
276e7145dcbSDimitry Andric     const llvm::GlobalIndirectSymbol &GIS) {
277e7145dcbSDimitry Andric   llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
278e7145dcbSDimitry Andric   const llvm::Constant *C = &GIS;
27959d1ed5bSDimitry Andric   for (;;) {
28059d1ed5bSDimitry Andric     C = C->stripPointerCasts();
28159d1ed5bSDimitry Andric     if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
28259d1ed5bSDimitry Andric       return GO;
28359d1ed5bSDimitry Andric     // stripPointerCasts will not walk over weak aliases.
284e7145dcbSDimitry Andric     auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
285e7145dcbSDimitry Andric     if (!GIS2)
28659d1ed5bSDimitry Andric       return nullptr;
287e7145dcbSDimitry Andric     if (!Visited.insert(GIS2).second)
28859d1ed5bSDimitry Andric       return nullptr;
289e7145dcbSDimitry Andric     C = GIS2->getIndirectSymbol();
29059d1ed5bSDimitry Andric   }
29159d1ed5bSDimitry Andric }
29259d1ed5bSDimitry Andric 
checkAliases()293f785676fSDimitry Andric void CodeGenModule::checkAliases() {
29459d1ed5bSDimitry Andric   // Check if the constructed aliases are well formed. It is really unfortunate
29559d1ed5bSDimitry Andric   // that we have to do this in CodeGen, but we only construct mangled names
29659d1ed5bSDimitry Andric   // and aliases during codegen.
297f785676fSDimitry Andric   bool Error = false;
29859d1ed5bSDimitry Andric   DiagnosticsEngine &Diags = getDiags();
2998f0fd8f6SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
30059d1ed5bSDimitry Andric     const auto *D = cast<ValueDecl>(GD.getDecl());
301e7145dcbSDimitry Andric     SourceLocation Location;
302e7145dcbSDimitry Andric     bool IsIFunc = D->hasAttr<IFuncAttr>();
303e7145dcbSDimitry Andric     if (const Attr *A = D->getDefiningAttr())
304e7145dcbSDimitry Andric       Location = A->getLocation();
305e7145dcbSDimitry Andric     else
306e7145dcbSDimitry Andric       llvm_unreachable("Not an alias or ifunc?");
307f785676fSDimitry Andric     StringRef MangledName = getMangledName(GD);
308f785676fSDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
309e7145dcbSDimitry Andric     auto *Alias  = cast<llvm::GlobalIndirectSymbol>(Entry);
31059d1ed5bSDimitry Andric     const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
31159d1ed5bSDimitry Andric     if (!GV) {
312f785676fSDimitry Andric       Error = true;
313e7145dcbSDimitry Andric       Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
31459d1ed5bSDimitry Andric     } else if (GV->isDeclaration()) {
315f785676fSDimitry Andric       Error = true;
316e7145dcbSDimitry Andric       Diags.Report(Location, diag::err_alias_to_undefined)
317e7145dcbSDimitry Andric           << IsIFunc << IsIFunc;
318e7145dcbSDimitry Andric     } else if (IsIFunc) {
319e7145dcbSDimitry Andric       // Check resolver function type.
320e7145dcbSDimitry Andric       llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
321e7145dcbSDimitry Andric           GV->getType()->getPointerElementType());
322e7145dcbSDimitry Andric       assert(FTy);
323e7145dcbSDimitry Andric       if (!FTy->getReturnType()->isPointerTy())
324e7145dcbSDimitry Andric         Diags.Report(Location, diag::err_ifunc_resolver_return);
32559d1ed5bSDimitry Andric     }
32659d1ed5bSDimitry Andric 
327e7145dcbSDimitry Andric     llvm::Constant *Aliasee = Alias->getIndirectSymbol();
32859d1ed5bSDimitry Andric     llvm::GlobalValue *AliaseeGV;
32959d1ed5bSDimitry Andric     if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
33059d1ed5bSDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
33159d1ed5bSDimitry Andric     else
33259d1ed5bSDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
33359d1ed5bSDimitry Andric 
33459d1ed5bSDimitry Andric     if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
33559d1ed5bSDimitry Andric       StringRef AliasSection = SA->getName();
33659d1ed5bSDimitry Andric       if (AliasSection != AliaseeGV->getSection())
33759d1ed5bSDimitry Andric         Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
338e7145dcbSDimitry Andric             << AliasSection << IsIFunc << IsIFunc;
33959d1ed5bSDimitry Andric     }
34059d1ed5bSDimitry Andric 
34159d1ed5bSDimitry Andric     // We have to handle alias to weak aliases in here. LLVM itself disallows
34259d1ed5bSDimitry Andric     // this since the object semantics would not match the IL one. For
34359d1ed5bSDimitry Andric     // compatibility with gcc we implement it by just pointing the alias
34459d1ed5bSDimitry Andric     // to its aliasee's aliasee. We also warn, since the user is probably
34559d1ed5bSDimitry Andric     // expecting the link to be weak.
346e7145dcbSDimitry Andric     if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
347e7145dcbSDimitry Andric       if (GA->isInterposable()) {
348e7145dcbSDimitry Andric         Diags.Report(Location, diag::warn_alias_to_weak_alias)
349e7145dcbSDimitry Andric             << GV->getName() << GA->getName() << IsIFunc;
35059d1ed5bSDimitry Andric         Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
351e7145dcbSDimitry Andric             GA->getIndirectSymbol(), Alias->getType());
352e7145dcbSDimitry Andric         Alias->setIndirectSymbol(Aliasee);
35359d1ed5bSDimitry Andric       }
354f785676fSDimitry Andric     }
355f785676fSDimitry Andric   }
356f785676fSDimitry Andric   if (!Error)
357f785676fSDimitry Andric     return;
358f785676fSDimitry Andric 
3598f0fd8f6SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
360f785676fSDimitry Andric     StringRef MangledName = getMangledName(GD);
361f785676fSDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
362e7145dcbSDimitry Andric     auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
363f785676fSDimitry Andric     Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
364f785676fSDimitry Andric     Alias->eraseFromParent();
365f785676fSDimitry Andric   }
366f785676fSDimitry Andric }
367f785676fSDimitry Andric 
clear()36859d1ed5bSDimitry Andric void CodeGenModule::clear() {
36959d1ed5bSDimitry Andric   DeferredDeclsToEmit.clear();
37033956c43SDimitry Andric   if (OpenMPRuntime)
37133956c43SDimitry Andric     OpenMPRuntime->clear();
37259d1ed5bSDimitry Andric }
37359d1ed5bSDimitry Andric 
reportDiagnostics(DiagnosticsEngine & Diags,StringRef MainFile)37459d1ed5bSDimitry Andric void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
37559d1ed5bSDimitry Andric                                        StringRef MainFile) {
37659d1ed5bSDimitry Andric   if (!hasDiagnostics())
37759d1ed5bSDimitry Andric     return;
37859d1ed5bSDimitry Andric   if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
37959d1ed5bSDimitry Andric     if (MainFile.empty())
38059d1ed5bSDimitry Andric       MainFile = "<stdin>";
38159d1ed5bSDimitry Andric     Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
382f37b6182SDimitry Andric   } else {
383f37b6182SDimitry Andric     if (Mismatched > 0)
384f37b6182SDimitry Andric       Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
385f37b6182SDimitry Andric 
386f37b6182SDimitry Andric     if (Missing > 0)
387f37b6182SDimitry Andric       Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
388f37b6182SDimitry Andric   }
38959d1ed5bSDimitry Andric }
39059d1ed5bSDimitry Andric 
Release()391f22ef01cSRoman Divacky void CodeGenModule::Release() {
392f22ef01cSRoman Divacky   EmitDeferred();
393f9448bf3SDimitry Andric   EmitVTablesOpportunistically();
3940623d748SDimitry Andric   applyGlobalValReplacements();
395f785676fSDimitry Andric   applyReplacements();
396f785676fSDimitry Andric   checkAliases();
3974ba319b5SDimitry Andric   emitMultiVersionFunctions();
398f22ef01cSRoman Divacky   EmitCXXGlobalInitFunc();
399f22ef01cSRoman Divacky   EmitCXXGlobalDtorFunc();
4004ba319b5SDimitry Andric   registerGlobalDtorsWithAtExit();
401284c1978SDimitry Andric   EmitCXXThreadLocalInitFunc();
4026122f3e6SDimitry Andric   if (ObjCRuntime)
4036122f3e6SDimitry Andric     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
404f22ef01cSRoman Divacky       AddGlobalCtor(ObjCInitFunction);
40533956c43SDimitry Andric   if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
40633956c43SDimitry Andric       CUDARuntime) {
4074ba319b5SDimitry Andric     if (llvm::Function *CudaCtorFunction =
4084ba319b5SDimitry Andric             CUDARuntime->makeModuleCtorFunction())
40933956c43SDimitry Andric       AddGlobalCtor(CudaCtorFunction);
41033956c43SDimitry Andric   }
4114ba319b5SDimitry Andric   if (OpenMPRuntime) {
412ea942507SDimitry Andric     if (llvm::Function *OpenMPRegistrationFunction =
413302affcbSDimitry Andric             OpenMPRuntime->emitRegistrationFunction()) {
414302affcbSDimitry Andric       auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
415302affcbSDimitry Andric         OpenMPRegistrationFunction : nullptr;
416302affcbSDimitry Andric       AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
417302affcbSDimitry Andric     }
4184ba319b5SDimitry Andric     OpenMPRuntime->clear();
4194ba319b5SDimitry Andric   }
4200623d748SDimitry Andric   if (PGOReader) {
421e7145dcbSDimitry Andric     getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
4220623d748SDimitry Andric     if (PGOStats.hasDiagnostics())
42359d1ed5bSDimitry Andric       PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
4240623d748SDimitry Andric   }
425f22ef01cSRoman Divacky   EmitCtorList(GlobalCtors, "llvm.global_ctors");
426f22ef01cSRoman Divacky   EmitCtorList(GlobalDtors, "llvm.global_dtors");
4276122f3e6SDimitry Andric   EmitGlobalAnnotations();
428284c1978SDimitry Andric   EmitStaticExternCAliases();
42939d628a0SDimitry Andric   EmitDeferredUnusedCoverageMappings();
43039d628a0SDimitry Andric   if (CoverageMapping)
43139d628a0SDimitry Andric     CoverageMapping->emit();
43220e90f04SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
433e7145dcbSDimitry Andric     CodeGenFunction(*this).EmitCfiCheckFail();
43420e90f04SDimitry Andric     CodeGenFunction(*this).EmitCfiCheckStub();
43520e90f04SDimitry Andric   }
43620e90f04SDimitry Andric   emitAtAvailableLinkGuard();
43759d1ed5bSDimitry Andric   emitLLVMUsed();
438e7145dcbSDimitry Andric   if (SanStats)
439e7145dcbSDimitry Andric     SanStats->finish();
440ffd1746dSEd Schouten 
441f785676fSDimitry Andric   if (CodeGenOpts.Autolink &&
442f785676fSDimitry Andric       (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
443139f7f9bSDimitry Andric     EmitModuleLinkOptions();
444139f7f9bSDimitry Andric   }
44520e90f04SDimitry Andric 
44620e90f04SDimitry Andric   // Record mregparm value now so it is visible through rest of codegen.
44720e90f04SDimitry Andric   if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
44820e90f04SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
44920e90f04SDimitry Andric                               CodeGenOpts.NumRegisterParameters);
45020e90f04SDimitry Andric 
4510623d748SDimitry Andric   if (CodeGenOpts.DwarfVersion) {
452f785676fSDimitry Andric     // We actually want the latest version when there are conflicts.
453f785676fSDimitry Andric     // We can change from Warning to Latest if such mode is supported.
454f785676fSDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
455f785676fSDimitry Andric                               CodeGenOpts.DwarfVersion);
4560623d748SDimitry Andric   }
4570623d748SDimitry Andric   if (CodeGenOpts.EmitCodeView) {
4580623d748SDimitry Andric     // Indicate that we want CodeView in the metadata.
4590623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
4600623d748SDimitry Andric   }
461*b5893f02SDimitry Andric   if (CodeGenOpts.CodeViewGHash) {
462*b5893f02SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
463*b5893f02SDimitry Andric   }
4644ba319b5SDimitry Andric   if (CodeGenOpts.ControlFlowGuard) {
4654ba319b5SDimitry Andric     // We want function ID tables for Control Flow Guard.
466*b5893f02SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "cfguardtable", 1);
4674ba319b5SDimitry Andric   }
4680623d748SDimitry Andric   if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
4690623d748SDimitry Andric     // We don't support LTO with 2 with different StrictVTablePointers
4700623d748SDimitry Andric     // FIXME: we could support it by stripping all the information introduced
4710623d748SDimitry Andric     // by StrictVTablePointers.
4720623d748SDimitry Andric 
4730623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
4740623d748SDimitry Andric 
4750623d748SDimitry Andric     llvm::Metadata *Ops[2] = {
4760623d748SDimitry Andric               llvm::MDString::get(VMContext, "StrictVTablePointers"),
4770623d748SDimitry Andric               llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
4780623d748SDimitry Andric                   llvm::Type::getInt32Ty(VMContext), 1))};
4790623d748SDimitry Andric 
4800623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Require,
4810623d748SDimitry Andric                               "StrictVTablePointersRequirement",
4820623d748SDimitry Andric                               llvm::MDNode::get(VMContext, Ops));
4830623d748SDimitry Andric   }
484f785676fSDimitry Andric   if (DebugInfo)
48559d1ed5bSDimitry Andric     // We support a single version in the linked module. The LLVM
48659d1ed5bSDimitry Andric     // parser will drop debug info with a different version number
48759d1ed5bSDimitry Andric     // (and warn about it, too).
48859d1ed5bSDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
489f785676fSDimitry Andric                               llvm::DEBUG_METADATA_VERSION);
490139f7f9bSDimitry Andric 
49159d1ed5bSDimitry Andric   // We need to record the widths of enums and wchar_t, so that we can generate
492d8866befSDimitry Andric   // the correct build attributes in the ARM backend. wchar_size is also used by
493d8866befSDimitry Andric   // TargetLibraryInfo.
4949a199699SDimitry Andric   uint64_t WCharWidth =
4959a199699SDimitry Andric       Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
496d8866befSDimitry Andric   getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
497d8866befSDimitry Andric 
49859d1ed5bSDimitry Andric   llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
49959d1ed5bSDimitry Andric   if (   Arch == llvm::Triple::arm
50059d1ed5bSDimitry Andric       || Arch == llvm::Triple::armeb
50159d1ed5bSDimitry Andric       || Arch == llvm::Triple::thumb
50259d1ed5bSDimitry Andric       || Arch == llvm::Triple::thumbeb) {
50359d1ed5bSDimitry Andric     // The minimum width of an enum in bytes
50459d1ed5bSDimitry Andric     uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
50559d1ed5bSDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
50659d1ed5bSDimitry Andric   }
50759d1ed5bSDimitry Andric 
5080623d748SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
5090623d748SDimitry Andric     // Indicate that we want cross-DSO control flow integrity checks.
5100623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
5110623d748SDimitry Andric   }
5120623d748SDimitry Andric 
5134ba319b5SDimitry Andric   if (CodeGenOpts.CFProtectionReturn &&
5144ba319b5SDimitry Andric       Target.checkCFProtectionReturnSupported(getDiags())) {
5154ba319b5SDimitry Andric     // Indicate that we want to instrument return control flow protection.
5164ba319b5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
5174ba319b5SDimitry Andric                               1);
5184ba319b5SDimitry Andric   }
5194ba319b5SDimitry Andric 
5204ba319b5SDimitry Andric   if (CodeGenOpts.CFProtectionBranch &&
5214ba319b5SDimitry Andric       Target.checkCFProtectionBranchSupported(getDiags())) {
5224ba319b5SDimitry Andric     // Indicate that we want to instrument branch control flow protection.
5234ba319b5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
5244ba319b5SDimitry Andric                               1);
5254ba319b5SDimitry Andric   }
5264ba319b5SDimitry Andric 
52744290647SDimitry Andric   if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
528e7145dcbSDimitry Andric     // Indicate whether __nvvm_reflect should be configured to flush denormal
529e7145dcbSDimitry Andric     // floating point values to 0.  (This corresponds to its "__CUDA_FTZ"
530e7145dcbSDimitry Andric     // property.)
531e7145dcbSDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
5324ba319b5SDimitry Andric                               CodeGenOpts.FlushDenorm ? 1 : 0);
53339d628a0SDimitry Andric   }
53439d628a0SDimitry Andric 
535edd7eaddSDimitry Andric   // Emit OpenCL specific module metadata: OpenCL/SPIR version.
536edd7eaddSDimitry Andric   if (LangOpts.OpenCL) {
537edd7eaddSDimitry Andric     EmitOpenCLMetadata();
538edd7eaddSDimitry Andric     // Emit SPIR version.
539edd7eaddSDimitry Andric     if (getTriple().getArch() == llvm::Triple::spir ||
540edd7eaddSDimitry Andric         getTriple().getArch() == llvm::Triple::spir64) {
541edd7eaddSDimitry Andric       // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
542edd7eaddSDimitry Andric       // opencl.spir.version named metadata.
543edd7eaddSDimitry Andric       llvm::Metadata *SPIRVerElts[] = {
544edd7eaddSDimitry Andric           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
545edd7eaddSDimitry Andric               Int32Ty, LangOpts.OpenCLVersion / 100)),
546edd7eaddSDimitry Andric           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
547edd7eaddSDimitry Andric               Int32Ty, (LangOpts.OpenCLVersion / 100 > 1) ? 0 : 2))};
548edd7eaddSDimitry Andric       llvm::NamedMDNode *SPIRVerMD =
549edd7eaddSDimitry Andric           TheModule.getOrInsertNamedMetadata("opencl.spir.version");
550edd7eaddSDimitry Andric       llvm::LLVMContext &Ctx = TheModule.getContext();
551edd7eaddSDimitry Andric       SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
552edd7eaddSDimitry Andric     }
553edd7eaddSDimitry Andric   }
554edd7eaddSDimitry Andric 
555e7145dcbSDimitry Andric   if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
556e7145dcbSDimitry Andric     assert(PLevel < 3 && "Invalid PIC Level");
557e7145dcbSDimitry Andric     getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
558e7145dcbSDimitry Andric     if (Context.getLangOpts().PIE)
559e7145dcbSDimitry Andric       getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
56039d628a0SDimitry Andric   }
56139d628a0SDimitry Andric 
562*b5893f02SDimitry Andric   if (getCodeGenOpts().CodeModel.size() > 0) {
563*b5893f02SDimitry Andric     unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
564*b5893f02SDimitry Andric                   .Case("tiny", llvm::CodeModel::Tiny)
565*b5893f02SDimitry Andric                   .Case("small", llvm::CodeModel::Small)
566*b5893f02SDimitry Andric                   .Case("kernel", llvm::CodeModel::Kernel)
567*b5893f02SDimitry Andric                   .Case("medium", llvm::CodeModel::Medium)
568*b5893f02SDimitry Andric                   .Case("large", llvm::CodeModel::Large)
569*b5893f02SDimitry Andric                   .Default(~0u);
570*b5893f02SDimitry Andric     if (CM != ~0u) {
571*b5893f02SDimitry Andric       llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
572*b5893f02SDimitry Andric       getModule().setCodeModel(codeModel);
573*b5893f02SDimitry Andric     }
574*b5893f02SDimitry Andric   }
575*b5893f02SDimitry Andric 
5764ba319b5SDimitry Andric   if (CodeGenOpts.NoPLT)
5774ba319b5SDimitry Andric     getModule().setRtLibUseGOT();
5784ba319b5SDimitry Andric 
5792754fe60SDimitry Andric   SimplifyPersonality();
5802754fe60SDimitry Andric 
581ffd1746dSEd Schouten   if (getCodeGenOpts().EmitDeclMetadata)
582ffd1746dSEd Schouten     EmitDeclMetadata();
583bd5abe19SDimitry Andric 
584bd5abe19SDimitry Andric   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
585bd5abe19SDimitry Andric     EmitCoverageFile();
5866122f3e6SDimitry Andric 
5876122f3e6SDimitry Andric   if (DebugInfo)
5886122f3e6SDimitry Andric     DebugInfo->finalize();
589f785676fSDimitry Andric 
5904ba319b5SDimitry Andric   if (getCodeGenOpts().EmitVersionIdentMetadata)
591f785676fSDimitry Andric     EmitVersionIdentMetadata();
59259d1ed5bSDimitry Andric 
593*b5893f02SDimitry Andric   if (!getCodeGenOpts().RecordCommandLine.empty())
594*b5893f02SDimitry Andric     EmitCommandLineMetadata();
595*b5893f02SDimitry Andric 
59659d1ed5bSDimitry Andric   EmitTargetMetadata();
597f22ef01cSRoman Divacky }
598f22ef01cSRoman Divacky 
EmitOpenCLMetadata()599edd7eaddSDimitry Andric void CodeGenModule::EmitOpenCLMetadata() {
600edd7eaddSDimitry Andric   // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
601edd7eaddSDimitry Andric   // opencl.ocl.version named metadata node.
602edd7eaddSDimitry Andric   llvm::Metadata *OCLVerElts[] = {
603edd7eaddSDimitry Andric       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
604edd7eaddSDimitry Andric           Int32Ty, LangOpts.OpenCLVersion / 100)),
605edd7eaddSDimitry Andric       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
606edd7eaddSDimitry Andric           Int32Ty, (LangOpts.OpenCLVersion % 100) / 10))};
607edd7eaddSDimitry Andric   llvm::NamedMDNode *OCLVerMD =
608edd7eaddSDimitry Andric       TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
609edd7eaddSDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
610edd7eaddSDimitry Andric   OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
611edd7eaddSDimitry Andric }
612edd7eaddSDimitry Andric 
UpdateCompletedType(const TagDecl * TD)6133b0f4066SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
6143b0f4066SDimitry Andric   // Make sure that this type is translated.
6153b0f4066SDimitry Andric   Types.UpdateCompletedType(TD);
6163b0f4066SDimitry Andric }
6173b0f4066SDimitry Andric 
RefreshTypeCacheForClass(const CXXRecordDecl * RD)618e7145dcbSDimitry Andric void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
619e7145dcbSDimitry Andric   // Make sure that this type is translated.
620e7145dcbSDimitry Andric   Types.RefreshTypeCacheForClass(RD);
621e7145dcbSDimitry Andric }
622e7145dcbSDimitry Andric 
getTBAATypeInfo(QualType QTy)6239a199699SDimitry Andric llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
6242754fe60SDimitry Andric   if (!TBAA)
62559d1ed5bSDimitry Andric     return nullptr;
6269a199699SDimitry Andric   return TBAA->getTypeInfo(QTy);
6272754fe60SDimitry Andric }
6282754fe60SDimitry Andric 
getTBAAAccessInfo(QualType AccessType)6299a199699SDimitry Andric TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
6304ba319b5SDimitry Andric   if (!TBAA)
6314ba319b5SDimitry Andric     return TBAAAccessInfo();
6324ba319b5SDimitry Andric   return TBAA->getAccessInfo(AccessType);
6339a199699SDimitry Andric }
6349a199699SDimitry Andric 
6359a199699SDimitry Andric TBAAAccessInfo
getTBAAVTablePtrAccessInfo(llvm::Type * VTablePtrType)6369a199699SDimitry Andric CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
637dff0c46cSDimitry Andric   if (!TBAA)
6389a199699SDimitry Andric     return TBAAAccessInfo();
6399a199699SDimitry Andric   return TBAA->getVTablePtrAccessInfo(VTablePtrType);
640dff0c46cSDimitry Andric }
641dff0c46cSDimitry Andric 
getTBAAStructInfo(QualType QTy)6423861d79fSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
6433861d79fSDimitry Andric   if (!TBAA)
64459d1ed5bSDimitry Andric     return nullptr;
6453861d79fSDimitry Andric   return TBAA->getTBAAStructInfo(QTy);
6463861d79fSDimitry Andric }
6473861d79fSDimitry Andric 
getTBAABaseTypeInfo(QualType QTy)6489a199699SDimitry Andric llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
649139f7f9bSDimitry Andric   if (!TBAA)
65059d1ed5bSDimitry Andric     return nullptr;
6519a199699SDimitry Andric   return TBAA->getBaseTypeInfo(QTy);
652139f7f9bSDimitry Andric }
653139f7f9bSDimitry Andric 
getTBAAAccessTagInfo(TBAAAccessInfo Info)6549a199699SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
6559a199699SDimitry Andric   if (!TBAA)
6569a199699SDimitry Andric     return nullptr;
6579a199699SDimitry Andric   return TBAA->getAccessTagInfo(Info);
6589a199699SDimitry Andric }
6599a199699SDimitry Andric 
mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,TBAAAccessInfo TargetInfo)6609a199699SDimitry Andric TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
6619a199699SDimitry Andric                                                    TBAAAccessInfo TargetInfo) {
6629a199699SDimitry Andric   if (!TBAA)
6639a199699SDimitry Andric     return TBAAAccessInfo();
6649a199699SDimitry Andric   return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
6659a199699SDimitry Andric }
6669a199699SDimitry Andric 
6679a199699SDimitry Andric TBAAAccessInfo
mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,TBAAAccessInfo InfoB)6689a199699SDimitry Andric CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
6699a199699SDimitry Andric                                                    TBAAAccessInfo InfoB) {
6709a199699SDimitry Andric   if (!TBAA)
6719a199699SDimitry Andric     return TBAAAccessInfo();
6729a199699SDimitry Andric   return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
6739a199699SDimitry Andric }
6749a199699SDimitry Andric 
6754ba319b5SDimitry Andric TBAAAccessInfo
mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,TBAAAccessInfo SrcInfo)6764ba319b5SDimitry Andric CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
6774ba319b5SDimitry Andric                                               TBAAAccessInfo SrcInfo) {
6784ba319b5SDimitry Andric   if (!TBAA)
6794ba319b5SDimitry Andric     return TBAAAccessInfo();
6804ba319b5SDimitry Andric   return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
6814ba319b5SDimitry Andric }
6824ba319b5SDimitry Andric 
DecorateInstructionWithTBAA(llvm::Instruction * Inst,TBAAAccessInfo TBAAInfo)6830623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
6849a199699SDimitry Andric                                                 TBAAAccessInfo TBAAInfo) {
6859a199699SDimitry Andric   if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
6869a199699SDimitry Andric     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
6872754fe60SDimitry Andric }
6882754fe60SDimitry Andric 
DecorateInstructionWithInvariantGroup(llvm::Instruction * I,const CXXRecordDecl * RD)6890623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithInvariantGroup(
6900623d748SDimitry Andric     llvm::Instruction *I, const CXXRecordDecl *RD) {
69151690af2SDimitry Andric   I->setMetadata(llvm::LLVMContext::MD_invariant_group,
69251690af2SDimitry Andric                  llvm::MDNode::get(getLLVMContext(), {}));
6930623d748SDimitry Andric }
6940623d748SDimitry Andric 
Error(SourceLocation loc,StringRef message)69559d1ed5bSDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) {
69659d1ed5bSDimitry Andric   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
69759d1ed5bSDimitry Andric   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
698f22ef01cSRoman Divacky }
699f22ef01cSRoman Divacky 
700f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
701f22ef01cSRoman Divacky /// specified stmt yet.
ErrorUnsupported(const Stmt * S,const char * Type)702f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
7036122f3e6SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
704f22ef01cSRoman Divacky                                                "cannot compile this %0 yet");
705f22ef01cSRoman Divacky   std::string Msg = Type;
706*b5893f02SDimitry Andric   getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
707f22ef01cSRoman Divacky       << Msg << S->getSourceRange();
708f22ef01cSRoman Divacky }
709f22ef01cSRoman Divacky 
710f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
711f22ef01cSRoman Divacky /// specified decl yet.
ErrorUnsupported(const Decl * D,const char * Type)712f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
7136122f3e6SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
714f22ef01cSRoman Divacky                                                "cannot compile this %0 yet");
715f22ef01cSRoman Divacky   std::string Msg = Type;
716f22ef01cSRoman Divacky   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
717f22ef01cSRoman Divacky }
718f22ef01cSRoman Divacky 
getSize(CharUnits size)71917a519f9SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
72017a519f9SDimitry Andric   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
72117a519f9SDimitry Andric }
72217a519f9SDimitry Andric 
setGlobalVisibility(llvm::GlobalValue * GV,const NamedDecl * D) const723f22ef01cSRoman Divacky void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
7244ba319b5SDimitry Andric                                         const NamedDecl *D) const {
7254ba319b5SDimitry Andric   if (GV->hasDLLImportStorageClass())
7264ba319b5SDimitry Andric     return;
727f22ef01cSRoman Divacky   // Internal definitions always have default visibility.
728f22ef01cSRoman Divacky   if (GV->hasLocalLinkage()) {
729f22ef01cSRoman Divacky     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
730f22ef01cSRoman Divacky     return;
731f22ef01cSRoman Divacky   }
7324ba319b5SDimitry Andric   if (!D)
7334ba319b5SDimitry Andric     return;
7342754fe60SDimitry Andric   // Set visibility for definitions.
735139f7f9bSDimitry Andric   LinkageInfo LV = D->getLinkageAndVisibility();
7364ba319b5SDimitry Andric   if (LV.isVisibilityExplicit() || !GV->isDeclarationForLinker())
737139f7f9bSDimitry Andric     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
738f22ef01cSRoman Divacky }
739f22ef01cSRoman Divacky 
shouldAssumeDSOLocal(const CodeGenModule & CGM,llvm::GlobalValue * GV)7404ba319b5SDimitry Andric static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
7414ba319b5SDimitry Andric                                  llvm::GlobalValue *GV) {
7424ba319b5SDimitry Andric   if (GV->hasLocalLinkage())
7434ba319b5SDimitry Andric     return true;
7444ba319b5SDimitry Andric 
7454ba319b5SDimitry Andric   if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
7464ba319b5SDimitry Andric     return true;
7474ba319b5SDimitry Andric 
7484ba319b5SDimitry Andric   // DLLImport explicitly marks the GV as external.
7494ba319b5SDimitry Andric   if (GV->hasDLLImportStorageClass())
7504ba319b5SDimitry Andric     return false;
7514ba319b5SDimitry Andric 
7524ba319b5SDimitry Andric   const llvm::Triple &TT = CGM.getTriple();
753*b5893f02SDimitry Andric   if (TT.isWindowsGNUEnvironment()) {
754*b5893f02SDimitry Andric     // In MinGW, variables without DLLImport can still be automatically
755*b5893f02SDimitry Andric     // imported from a DLL by the linker; don't mark variables that
756*b5893f02SDimitry Andric     // potentially could come from another DLL as DSO local.
757*b5893f02SDimitry Andric     if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
758*b5893f02SDimitry Andric         !GV->isThreadLocal())
759*b5893f02SDimitry Andric       return false;
760*b5893f02SDimitry Andric   }
7614ba319b5SDimitry Andric   // Every other GV is local on COFF.
7624ba319b5SDimitry Andric   // Make an exception for windows OS in the triple: Some firmware builds use
7634ba319b5SDimitry Andric   // *-win32-macho triples. This (accidentally?) produced windows relocations
7644ba319b5SDimitry Andric   // without GOT tables in older clang versions; Keep this behaviour.
7654ba319b5SDimitry Andric   // FIXME: even thread local variables?
7664ba319b5SDimitry Andric   if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
7674ba319b5SDimitry Andric     return true;
7684ba319b5SDimitry Andric 
7694ba319b5SDimitry Andric   // Only handle COFF and ELF for now.
7704ba319b5SDimitry Andric   if (!TT.isOSBinFormatELF())
7714ba319b5SDimitry Andric     return false;
7724ba319b5SDimitry Andric 
7734ba319b5SDimitry Andric   // If this is not an executable, don't assume anything is local.
7744ba319b5SDimitry Andric   const auto &CGOpts = CGM.getCodeGenOpts();
7754ba319b5SDimitry Andric   llvm::Reloc::Model RM = CGOpts.RelocationModel;
7764ba319b5SDimitry Andric   const auto &LOpts = CGM.getLangOpts();
7774ba319b5SDimitry Andric   if (RM != llvm::Reloc::Static && !LOpts.PIE)
7784ba319b5SDimitry Andric     return false;
7794ba319b5SDimitry Andric 
7804ba319b5SDimitry Andric   // A definition cannot be preempted from an executable.
7814ba319b5SDimitry Andric   if (!GV->isDeclarationForLinker())
7824ba319b5SDimitry Andric     return true;
7834ba319b5SDimitry Andric 
7844ba319b5SDimitry Andric   // Most PIC code sequences that assume that a symbol is local cannot produce a
7854ba319b5SDimitry Andric   // 0 if it turns out the symbol is undefined. While this is ABI and relocation
7864ba319b5SDimitry Andric   // depended, it seems worth it to handle it here.
7874ba319b5SDimitry Andric   if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
7884ba319b5SDimitry Andric     return false;
7894ba319b5SDimitry Andric 
7904ba319b5SDimitry Andric   // PPC has no copy relocations and cannot use a plt entry as a symbol address.
7914ba319b5SDimitry Andric   llvm::Triple::ArchType Arch = TT.getArch();
7924ba319b5SDimitry Andric   if (Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
7934ba319b5SDimitry Andric       Arch == llvm::Triple::ppc64le)
7944ba319b5SDimitry Andric     return false;
7954ba319b5SDimitry Andric 
7964ba319b5SDimitry Andric   // If we can use copy relocations we can assume it is local.
7974ba319b5SDimitry Andric   if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
7984ba319b5SDimitry Andric     if (!Var->isThreadLocal() &&
7994ba319b5SDimitry Andric         (RM == llvm::Reloc::Static || CGOpts.PIECopyRelocations))
8004ba319b5SDimitry Andric       return true;
8014ba319b5SDimitry Andric 
8024ba319b5SDimitry Andric   // If we can use a plt entry as the symbol address we can assume it
8034ba319b5SDimitry Andric   // is local.
8044ba319b5SDimitry Andric   // FIXME: This should work for PIE, but the gold linker doesn't support it.
8054ba319b5SDimitry Andric   if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
8064ba319b5SDimitry Andric     return true;
8074ba319b5SDimitry Andric 
8084ba319b5SDimitry Andric   // Otherwise don't assue it is local.
8094ba319b5SDimitry Andric   return false;
8104ba319b5SDimitry Andric }
8114ba319b5SDimitry Andric 
setDSOLocal(llvm::GlobalValue * GV) const8124ba319b5SDimitry Andric void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
8134ba319b5SDimitry Andric   GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
8144ba319b5SDimitry Andric }
8154ba319b5SDimitry Andric 
setDLLImportDLLExport(llvm::GlobalValue * GV,GlobalDecl GD) const8164ba319b5SDimitry Andric void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
8174ba319b5SDimitry Andric                                           GlobalDecl GD) const {
8184ba319b5SDimitry Andric   const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
8194ba319b5SDimitry Andric   // C++ destructors have a few C++ ABI specific special cases.
8204ba319b5SDimitry Andric   if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
8214ba319b5SDimitry Andric     getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
8224ba319b5SDimitry Andric     return;
8234ba319b5SDimitry Andric   }
8244ba319b5SDimitry Andric   setDLLImportDLLExport(GV, D);
8254ba319b5SDimitry Andric }
8264ba319b5SDimitry Andric 
setDLLImportDLLExport(llvm::GlobalValue * GV,const NamedDecl * D) const8274ba319b5SDimitry Andric void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
8284ba319b5SDimitry Andric                                           const NamedDecl *D) const {
8294ba319b5SDimitry Andric   if (D && D->isExternallyVisible()) {
8304ba319b5SDimitry Andric     if (D->hasAttr<DLLImportAttr>())
8314ba319b5SDimitry Andric       GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
8324ba319b5SDimitry Andric     else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
8334ba319b5SDimitry Andric       GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
8344ba319b5SDimitry Andric   }
8354ba319b5SDimitry Andric }
8364ba319b5SDimitry Andric 
setGVProperties(llvm::GlobalValue * GV,GlobalDecl GD) const8374ba319b5SDimitry Andric void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
8384ba319b5SDimitry Andric                                     GlobalDecl GD) const {
8394ba319b5SDimitry Andric   setDLLImportDLLExport(GV, GD);
8404ba319b5SDimitry Andric   setGlobalVisibilityAndLocal(GV, dyn_cast<NamedDecl>(GD.getDecl()));
8414ba319b5SDimitry Andric }
8424ba319b5SDimitry Andric 
setGVProperties(llvm::GlobalValue * GV,const NamedDecl * D) const8434ba319b5SDimitry Andric void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
8444ba319b5SDimitry Andric                                     const NamedDecl *D) const {
8454ba319b5SDimitry Andric   setDLLImportDLLExport(GV, D);
8464ba319b5SDimitry Andric   setGlobalVisibilityAndLocal(GV, D);
8474ba319b5SDimitry Andric }
8484ba319b5SDimitry Andric 
setGlobalVisibilityAndLocal(llvm::GlobalValue * GV,const NamedDecl * D) const8494ba319b5SDimitry Andric void CodeGenModule::setGlobalVisibilityAndLocal(llvm::GlobalValue *GV,
8504ba319b5SDimitry Andric                                                 const NamedDecl *D) const {
8514ba319b5SDimitry Andric   setGlobalVisibility(GV, D);
8524ba319b5SDimitry Andric   setDSOLocal(GV);
8534ba319b5SDimitry Andric }
8544ba319b5SDimitry Andric 
GetLLVMTLSModel(StringRef S)8557ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
8567ae0e2c9SDimitry Andric   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
8577ae0e2c9SDimitry Andric       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
8587ae0e2c9SDimitry Andric       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
8597ae0e2c9SDimitry Andric       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
8607ae0e2c9SDimitry Andric       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
8617ae0e2c9SDimitry Andric }
8627ae0e2c9SDimitry Andric 
GetLLVMTLSModel(CodeGenOptions::TLSModel M)8637ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
8647ae0e2c9SDimitry Andric     CodeGenOptions::TLSModel M) {
8657ae0e2c9SDimitry Andric   switch (M) {
8667ae0e2c9SDimitry Andric   case CodeGenOptions::GeneralDynamicTLSModel:
8677ae0e2c9SDimitry Andric     return llvm::GlobalVariable::GeneralDynamicTLSModel;
8687ae0e2c9SDimitry Andric   case CodeGenOptions::LocalDynamicTLSModel:
8697ae0e2c9SDimitry Andric     return llvm::GlobalVariable::LocalDynamicTLSModel;
8707ae0e2c9SDimitry Andric   case CodeGenOptions::InitialExecTLSModel:
8717ae0e2c9SDimitry Andric     return llvm::GlobalVariable::InitialExecTLSModel;
8727ae0e2c9SDimitry Andric   case CodeGenOptions::LocalExecTLSModel:
8737ae0e2c9SDimitry Andric     return llvm::GlobalVariable::LocalExecTLSModel;
8747ae0e2c9SDimitry Andric   }
8757ae0e2c9SDimitry Andric   llvm_unreachable("Invalid TLS model!");
8767ae0e2c9SDimitry Andric }
8777ae0e2c9SDimitry Andric 
setTLSMode(llvm::GlobalValue * GV,const VarDecl & D) const87839d628a0SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
879284c1978SDimitry Andric   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
8807ae0e2c9SDimitry Andric 
88139d628a0SDimitry Andric   llvm::GlobalValue::ThreadLocalMode TLM;
8823861d79fSDimitry Andric   TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
8837ae0e2c9SDimitry Andric 
8847ae0e2c9SDimitry Andric   // Override the TLS model if it is explicitly specified.
88559d1ed5bSDimitry Andric   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
8867ae0e2c9SDimitry Andric     TLM = GetLLVMTLSModel(Attr->getModel());
8877ae0e2c9SDimitry Andric   }
8887ae0e2c9SDimitry Andric 
8897ae0e2c9SDimitry Andric   GV->setThreadLocalMode(TLM);
8907ae0e2c9SDimitry Andric }
8917ae0e2c9SDimitry Andric 
getCPUSpecificMangling(const CodeGenModule & CGM,StringRef Name)8924ba319b5SDimitry Andric static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
8934ba319b5SDimitry Andric                                           StringRef Name) {
8944ba319b5SDimitry Andric   const TargetInfo &Target = CGM.getTarget();
8954ba319b5SDimitry Andric   return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
8964ba319b5SDimitry Andric }
8974ba319b5SDimitry Andric 
AppendCPUSpecificCPUDispatchMangling(const CodeGenModule & CGM,const CPUSpecificAttr * Attr,unsigned CPUIndex,raw_ostream & Out)8984ba319b5SDimitry Andric static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
8994ba319b5SDimitry Andric                                                  const CPUSpecificAttr *Attr,
900*b5893f02SDimitry Andric                                                  unsigned CPUIndex,
9014ba319b5SDimitry Andric                                                  raw_ostream &Out) {
902*b5893f02SDimitry Andric   // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
903*b5893f02SDimitry Andric   // supported.
9044ba319b5SDimitry Andric   if (Attr)
905*b5893f02SDimitry Andric     Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName());
906*b5893f02SDimitry Andric   else if (CGM.getTarget().supportsIFunc())
9074ba319b5SDimitry Andric     Out << ".resolver";
9084ba319b5SDimitry Andric }
9094ba319b5SDimitry Andric 
AppendTargetMangling(const CodeGenModule & CGM,const TargetAttr * Attr,raw_ostream & Out)9104ba319b5SDimitry Andric static void AppendTargetMangling(const CodeGenModule &CGM,
9114ba319b5SDimitry Andric                                  const TargetAttr *Attr, raw_ostream &Out) {
9124ba319b5SDimitry Andric   if (Attr->isDefaultVersion())
9134ba319b5SDimitry Andric     return;
9144ba319b5SDimitry Andric 
9154ba319b5SDimitry Andric   Out << '.';
9164ba319b5SDimitry Andric   const TargetInfo &Target = CGM.getTarget();
9174ba319b5SDimitry Andric   TargetAttr::ParsedTargetAttr Info =
9184ba319b5SDimitry Andric       Attr->parse([&Target](StringRef LHS, StringRef RHS) {
9194ba319b5SDimitry Andric         // Multiversioning doesn't allow "no-${feature}", so we can
9204ba319b5SDimitry Andric         // only have "+" prefixes here.
9214ba319b5SDimitry Andric         assert(LHS.startswith("+") && RHS.startswith("+") &&
9224ba319b5SDimitry Andric                "Features should always have a prefix.");
9234ba319b5SDimitry Andric         return Target.multiVersionSortPriority(LHS.substr(1)) >
9244ba319b5SDimitry Andric                Target.multiVersionSortPriority(RHS.substr(1));
9254ba319b5SDimitry Andric       });
9264ba319b5SDimitry Andric 
9274ba319b5SDimitry Andric   bool IsFirst = true;
9284ba319b5SDimitry Andric 
9294ba319b5SDimitry Andric   if (!Info.Architecture.empty()) {
9304ba319b5SDimitry Andric     IsFirst = false;
9314ba319b5SDimitry Andric     Out << "arch_" << Info.Architecture;
9324ba319b5SDimitry Andric   }
9334ba319b5SDimitry Andric 
9344ba319b5SDimitry Andric   for (StringRef Feat : Info.Features) {
9354ba319b5SDimitry Andric     if (!IsFirst)
9364ba319b5SDimitry Andric       Out << '_';
9374ba319b5SDimitry Andric     IsFirst = false;
9384ba319b5SDimitry Andric     Out << Feat.substr(1);
9394ba319b5SDimitry Andric   }
9404ba319b5SDimitry Andric }
9414ba319b5SDimitry Andric 
getMangledNameImpl(const CodeGenModule & CGM,GlobalDecl GD,const NamedDecl * ND,bool OmitMultiVersionMangling=false)9424ba319b5SDimitry Andric static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD,
9434ba319b5SDimitry Andric                                       const NamedDecl *ND,
9444ba319b5SDimitry Andric                                       bool OmitMultiVersionMangling = false) {
9454ba319b5SDimitry Andric   SmallString<256> Buffer;
9464ba319b5SDimitry Andric   llvm::raw_svector_ostream Out(Buffer);
9474ba319b5SDimitry Andric   MangleContext &MC = CGM.getCXXABI().getMangleContext();
9484ba319b5SDimitry Andric   if (MC.shouldMangleDeclName(ND)) {
9494ba319b5SDimitry Andric     llvm::raw_svector_ostream Out(Buffer);
9504ba319b5SDimitry Andric     if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
9514ba319b5SDimitry Andric       MC.mangleCXXCtor(D, GD.getCtorType(), Out);
9524ba319b5SDimitry Andric     else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
9534ba319b5SDimitry Andric       MC.mangleCXXDtor(D, GD.getDtorType(), Out);
9544ba319b5SDimitry Andric     else
9554ba319b5SDimitry Andric       MC.mangleName(ND, Out);
9564ba319b5SDimitry Andric   } else {
9574ba319b5SDimitry Andric     IdentifierInfo *II = ND->getIdentifier();
9584ba319b5SDimitry Andric     assert(II && "Attempt to mangle unnamed decl.");
9594ba319b5SDimitry Andric     const auto *FD = dyn_cast<FunctionDecl>(ND);
9604ba319b5SDimitry Andric 
9614ba319b5SDimitry Andric     if (FD &&
9624ba319b5SDimitry Andric         FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
9634ba319b5SDimitry Andric       llvm::raw_svector_ostream Out(Buffer);
9644ba319b5SDimitry Andric       Out << "__regcall3__" << II->getName();
9654ba319b5SDimitry Andric     } else {
9664ba319b5SDimitry Andric       Out << II->getName();
9674ba319b5SDimitry Andric     }
9684ba319b5SDimitry Andric   }
9694ba319b5SDimitry Andric 
9704ba319b5SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(ND))
9714ba319b5SDimitry Andric     if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
972*b5893f02SDimitry Andric       switch (FD->getMultiVersionKind()) {
973*b5893f02SDimitry Andric       case MultiVersionKind::CPUDispatch:
974*b5893f02SDimitry Andric       case MultiVersionKind::CPUSpecific:
975*b5893f02SDimitry Andric         AppendCPUSpecificCPUDispatchMangling(CGM,
976*b5893f02SDimitry Andric                                              FD->getAttr<CPUSpecificAttr>(),
977*b5893f02SDimitry Andric                                              GD.getMultiVersionIndex(), Out);
978*b5893f02SDimitry Andric         break;
979*b5893f02SDimitry Andric       case MultiVersionKind::Target:
9804ba319b5SDimitry Andric         AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
981*b5893f02SDimitry Andric         break;
982*b5893f02SDimitry Andric       case MultiVersionKind::None:
983*b5893f02SDimitry Andric         llvm_unreachable("None multiversion type isn't valid here");
984*b5893f02SDimitry Andric       }
9854ba319b5SDimitry Andric     }
9864ba319b5SDimitry Andric 
9874ba319b5SDimitry Andric   return Out.str();
9884ba319b5SDimitry Andric }
9894ba319b5SDimitry Andric 
UpdateMultiVersionNames(GlobalDecl GD,const FunctionDecl * FD)9904ba319b5SDimitry Andric void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
9914ba319b5SDimitry Andric                                             const FunctionDecl *FD) {
9924ba319b5SDimitry Andric   if (!FD->isMultiVersion())
9934ba319b5SDimitry Andric     return;
9944ba319b5SDimitry Andric 
9954ba319b5SDimitry Andric   // Get the name of what this would be without the 'target' attribute.  This
9964ba319b5SDimitry Andric   // allows us to lookup the version that was emitted when this wasn't a
9974ba319b5SDimitry Andric   // multiversion function.
9984ba319b5SDimitry Andric   std::string NonTargetName =
9994ba319b5SDimitry Andric       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
10004ba319b5SDimitry Andric   GlobalDecl OtherGD;
10014ba319b5SDimitry Andric   if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
10024ba319b5SDimitry Andric     assert(OtherGD.getCanonicalDecl()
10034ba319b5SDimitry Andric                .getDecl()
10044ba319b5SDimitry Andric                ->getAsFunction()
10054ba319b5SDimitry Andric                ->isMultiVersion() &&
10064ba319b5SDimitry Andric            "Other GD should now be a multiversioned function");
10074ba319b5SDimitry Andric     // OtherFD is the version of this function that was mangled BEFORE
10084ba319b5SDimitry Andric     // becoming a MultiVersion function.  It potentially needs to be updated.
1009*b5893f02SDimitry Andric     const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
1010*b5893f02SDimitry Andric                                       .getDecl()
1011*b5893f02SDimitry Andric                                       ->getAsFunction()
1012*b5893f02SDimitry Andric                                       ->getMostRecentDecl();
10134ba319b5SDimitry Andric     std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
10144ba319b5SDimitry Andric     // This is so that if the initial version was already the 'default'
10154ba319b5SDimitry Andric     // version, we don't try to update it.
10164ba319b5SDimitry Andric     if (OtherName != NonTargetName) {
10174ba319b5SDimitry Andric       // Remove instead of erase, since others may have stored the StringRef
10184ba319b5SDimitry Andric       // to this.
10194ba319b5SDimitry Andric       const auto ExistingRecord = Manglings.find(NonTargetName);
10204ba319b5SDimitry Andric       if (ExistingRecord != std::end(Manglings))
10214ba319b5SDimitry Andric         Manglings.remove(&(*ExistingRecord));
10224ba319b5SDimitry Andric       auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
10234ba319b5SDimitry Andric       MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first();
10244ba319b5SDimitry Andric       if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
10254ba319b5SDimitry Andric         Entry->setName(OtherName);
10264ba319b5SDimitry Andric     }
10274ba319b5SDimitry Andric   }
10284ba319b5SDimitry Andric }
10294ba319b5SDimitry Andric 
getMangledName(GlobalDecl GD)10306122f3e6SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
1031444ed5c5SDimitry Andric   GlobalDecl CanonicalGD = GD.getCanonicalDecl();
1032444ed5c5SDimitry Andric 
1033444ed5c5SDimitry Andric   // Some ABIs don't have constructor variants.  Make sure that base and
1034444ed5c5SDimitry Andric   // complete constructors get mangled the same.
1035444ed5c5SDimitry Andric   if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
1036444ed5c5SDimitry Andric     if (!getTarget().getCXXABI().hasConstructorVariants()) {
1037444ed5c5SDimitry Andric       CXXCtorType OrigCtorType = GD.getCtorType();
1038444ed5c5SDimitry Andric       assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
1039444ed5c5SDimitry Andric       if (OrigCtorType == Ctor_Base)
1040444ed5c5SDimitry Andric         CanonicalGD = GlobalDecl(CD, Ctor_Complete);
1041444ed5c5SDimitry Andric     }
1042444ed5c5SDimitry Andric   }
1043444ed5c5SDimitry Andric 
10449a199699SDimitry Andric   auto FoundName = MangledDeclNames.find(CanonicalGD);
10459a199699SDimitry Andric   if (FoundName != MangledDeclNames.end())
10469a199699SDimitry Andric     return FoundName->second;
1047f22ef01cSRoman Divacky 
104839d628a0SDimitry Andric   // Keep the first result in the case of a mangling collision.
10494ba319b5SDimitry Andric   const auto *ND = cast<NamedDecl>(GD.getDecl());
10504ba319b5SDimitry Andric   auto Result =
10514ba319b5SDimitry Andric       Manglings.insert(std::make_pair(getMangledNameImpl(*this, GD, ND), GD));
10529a199699SDimitry Andric   return MangledDeclNames[CanonicalGD] = Result.first->first();
105359d1ed5bSDimitry Andric }
105459d1ed5bSDimitry Andric 
getBlockMangledName(GlobalDecl GD,const BlockDecl * BD)105559d1ed5bSDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
1056ffd1746dSEd Schouten                                              const BlockDecl *BD) {
10572754fe60SDimitry Andric   MangleContext &MangleCtx = getCXXABI().getMangleContext();
10582754fe60SDimitry Andric   const Decl *D = GD.getDecl();
105959d1ed5bSDimitry Andric 
106059d1ed5bSDimitry Andric   SmallString<256> Buffer;
106159d1ed5bSDimitry Andric   llvm::raw_svector_ostream Out(Buffer);
106259d1ed5bSDimitry Andric   if (!D)
10637ae0e2c9SDimitry Andric     MangleCtx.mangleGlobalBlock(BD,
10647ae0e2c9SDimitry Andric       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
106559d1ed5bSDimitry Andric   else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
10662754fe60SDimitry Andric     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
106759d1ed5bSDimitry Andric   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
10682754fe60SDimitry Andric     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
10692754fe60SDimitry Andric   else
10702754fe60SDimitry Andric     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
107159d1ed5bSDimitry Andric 
107239d628a0SDimitry Andric   auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
107339d628a0SDimitry Andric   return Result.first->first();
1074f22ef01cSRoman Divacky }
1075f22ef01cSRoman Divacky 
GetGlobalValue(StringRef Name)10766122f3e6SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
1077f22ef01cSRoman Divacky   return getModule().getNamedValue(Name);
1078f22ef01cSRoman Divacky }
1079f22ef01cSRoman Divacky 
1080f22ef01cSRoman Divacky /// AddGlobalCtor - Add a function to the list that will be called before
1081f22ef01cSRoman Divacky /// main() runs.
AddGlobalCtor(llvm::Function * Ctor,int Priority,llvm::Constant * AssociatedData)108259d1ed5bSDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
108359d1ed5bSDimitry Andric                                   llvm::Constant *AssociatedData) {
1084f22ef01cSRoman Divacky   // FIXME: Type coercion of void()* types.
108559d1ed5bSDimitry Andric   GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
1086f22ef01cSRoman Divacky }
1087f22ef01cSRoman Divacky 
1088f22ef01cSRoman Divacky /// AddGlobalDtor - Add a function to the list that will be called
1089f22ef01cSRoman Divacky /// when the module is unloaded.
AddGlobalDtor(llvm::Function * Dtor,int Priority)1090f22ef01cSRoman Divacky void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
10914ba319b5SDimitry Andric   if (CodeGenOpts.RegisterGlobalDtorsWithAtExit) {
10924ba319b5SDimitry Andric     DtorsUsingAtExit[Priority].push_back(Dtor);
10934ba319b5SDimitry Andric     return;
10944ba319b5SDimitry Andric   }
10954ba319b5SDimitry Andric 
1096f22ef01cSRoman Divacky   // FIXME: Type coercion of void()* types.
109759d1ed5bSDimitry Andric   GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
1098f22ef01cSRoman Divacky }
1099f22ef01cSRoman Divacky 
EmitCtorList(CtorList & Fns,const char * GlobalName)110044290647SDimitry Andric void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
110144290647SDimitry Andric   if (Fns.empty()) return;
110244290647SDimitry Andric 
1103f22ef01cSRoman Divacky   // Ctor function type is void()*.
1104bd5abe19SDimitry Andric   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
1105*b5893f02SDimitry Andric   llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
1106*b5893f02SDimitry Andric       TheModule.getDataLayout().getProgramAddressSpace());
1107f22ef01cSRoman Divacky 
110859d1ed5bSDimitry Andric   // Get the type of a ctor entry, { i32, void ()*, i8* }.
110959d1ed5bSDimitry Andric   llvm::StructType *CtorStructTy = llvm::StructType::get(
1110*b5893f02SDimitry Andric       Int32Ty, CtorPFTy, VoidPtrTy);
1111f22ef01cSRoman Divacky 
1112f22ef01cSRoman Divacky   // Construct the constructor and destructor arrays.
111344290647SDimitry Andric   ConstantInitBuilder builder(*this);
111444290647SDimitry Andric   auto ctors = builder.beginArray(CtorStructTy);
11158f0fd8f6SDimitry Andric   for (const auto &I : Fns) {
111644290647SDimitry Andric     auto ctor = ctors.beginStruct(CtorStructTy);
111744290647SDimitry Andric     ctor.addInt(Int32Ty, I.Priority);
111844290647SDimitry Andric     ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
111944290647SDimitry Andric     if (I.AssociatedData)
112044290647SDimitry Andric       ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
112144290647SDimitry Andric     else
112244290647SDimitry Andric       ctor.addNullPointer(VoidPtrTy);
112344290647SDimitry Andric     ctor.finishAndAddTo(ctors);
1124f22ef01cSRoman Divacky   }
1125f22ef01cSRoman Divacky 
112644290647SDimitry Andric   auto list =
112744290647SDimitry Andric     ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
112844290647SDimitry Andric                                 /*constant*/ false,
112944290647SDimitry Andric                                 llvm::GlobalValue::AppendingLinkage);
113044290647SDimitry Andric 
113144290647SDimitry Andric   // The LTO linker doesn't seem to like it when we set an alignment
113244290647SDimitry Andric   // on appending variables.  Take it off as a workaround.
113344290647SDimitry Andric   list->setAlignment(0);
113444290647SDimitry Andric 
113544290647SDimitry Andric   Fns.clear();
1136f22ef01cSRoman Divacky }
1137f22ef01cSRoman Divacky 
1138f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes
getFunctionLinkage(GlobalDecl GD)1139f785676fSDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
114059d1ed5bSDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
1141f785676fSDimitry Andric 
1142e580952dSDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
1143f22ef01cSRoman Divacky 
11444ba319b5SDimitry Andric   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
11454ba319b5SDimitry Andric     return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
1146f22ef01cSRoman Divacky 
1147e7145dcbSDimitry Andric   if (isa<CXXConstructorDecl>(D) &&
1148e7145dcbSDimitry Andric       cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
1149e7145dcbSDimitry Andric       Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1150e7145dcbSDimitry Andric     // Our approach to inheriting constructors is fundamentally different from
1151e7145dcbSDimitry Andric     // that used by the MS ABI, so keep our inheriting constructor thunks
1152e7145dcbSDimitry Andric     // internal rather than trying to pick an unambiguous mangling for them.
1153e7145dcbSDimitry Andric     return llvm::GlobalValue::InternalLinkage;
1154e7145dcbSDimitry Andric   }
1155e7145dcbSDimitry Andric 
115659d1ed5bSDimitry Andric   return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
115759d1ed5bSDimitry Andric }
1158f22ef01cSRoman Divacky 
CreateCrossDsoCfiTypeId(llvm::Metadata * MD)1159e7145dcbSDimitry Andric llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
11600623d748SDimitry Andric   llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
11610623d748SDimitry Andric   if (!MDS) return nullptr;
11620623d748SDimitry Andric 
116344290647SDimitry Andric   return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
11640623d748SDimitry Andric }
11650623d748SDimitry Andric 
SetLLVMFunctionAttributes(GlobalDecl GD,const CGFunctionInfo & Info,llvm::Function * F)1166*b5893f02SDimitry Andric void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
1167f22ef01cSRoman Divacky                                               const CGFunctionInfo &Info,
1168f22ef01cSRoman Divacky                                               llvm::Function *F) {
1169f22ef01cSRoman Divacky   unsigned CallingConv;
11706bc11b14SDimitry Andric   llvm::AttributeList PAL;
1171*b5893f02SDimitry Andric   ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv, false);
11726bc11b14SDimitry Andric   F->setAttributes(PAL);
1173f22ef01cSRoman Divacky   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
1174f22ef01cSRoman Divacky }
1175f22ef01cSRoman Divacky 
11766122f3e6SDimitry Andric /// Determines whether the language options require us to model
11776122f3e6SDimitry Andric /// unwind exceptions.  We treat -fexceptions as mandating this
11786122f3e6SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions
11796122f3e6SDimitry Andric /// enabled.  This means, for example, that C with -fexceptions
11806122f3e6SDimitry Andric /// enables this.
hasUnwindExceptions(const LangOptions & LangOpts)1181dff0c46cSDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) {
11826122f3e6SDimitry Andric   // If exceptions are completely disabled, obviously this is false.
1183dff0c46cSDimitry Andric   if (!LangOpts.Exceptions) return false;
11846122f3e6SDimitry Andric 
11856122f3e6SDimitry Andric   // If C++ exceptions are enabled, this is true.
1186dff0c46cSDimitry Andric   if (LangOpts.CXXExceptions) return true;
11876122f3e6SDimitry Andric 
11886122f3e6SDimitry Andric   // If ObjC exceptions are enabled, this depends on the ABI.
1189dff0c46cSDimitry Andric   if (LangOpts.ObjCExceptions) {
11907ae0e2c9SDimitry Andric     return LangOpts.ObjCRuntime.hasUnwindExceptions();
11916122f3e6SDimitry Andric   }
11926122f3e6SDimitry Andric 
11936122f3e6SDimitry Andric   return true;
11946122f3e6SDimitry Andric }
11956122f3e6SDimitry Andric 
requiresMemberFunctionPointerTypeMetadata(CodeGenModule & CGM,const CXXMethodDecl * MD)11964ba319b5SDimitry Andric static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
11974ba319b5SDimitry Andric                                                       const CXXMethodDecl *MD) {
11984ba319b5SDimitry Andric   // Check that the type metadata can ever actually be used by a call.
11994ba319b5SDimitry Andric   if (!CGM.getCodeGenOpts().LTOUnit ||
12004ba319b5SDimitry Andric       !CGM.HasHiddenLTOVisibility(MD->getParent()))
12014ba319b5SDimitry Andric     return false;
12024ba319b5SDimitry Andric 
12034ba319b5SDimitry Andric   // Only functions whose address can be taken with a member function pointer
12044ba319b5SDimitry Andric   // need this sort of type metadata.
12054ba319b5SDimitry Andric   return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
12064ba319b5SDimitry Andric          !isa<CXXDestructorDecl>(MD);
12074ba319b5SDimitry Andric }
12084ba319b5SDimitry Andric 
12094ba319b5SDimitry Andric std::vector<const CXXRecordDecl *>
getMostBaseClasses(const CXXRecordDecl * RD)12104ba319b5SDimitry Andric CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
12114ba319b5SDimitry Andric   llvm::SetVector<const CXXRecordDecl *> MostBases;
12124ba319b5SDimitry Andric 
12134ba319b5SDimitry Andric   std::function<void (const CXXRecordDecl *)> CollectMostBases;
12144ba319b5SDimitry Andric   CollectMostBases = [&](const CXXRecordDecl *RD) {
12154ba319b5SDimitry Andric     if (RD->getNumBases() == 0)
12164ba319b5SDimitry Andric       MostBases.insert(RD);
12174ba319b5SDimitry Andric     for (const CXXBaseSpecifier &B : RD->bases())
12184ba319b5SDimitry Andric       CollectMostBases(B.getType()->getAsCXXRecordDecl());
12194ba319b5SDimitry Andric   };
12204ba319b5SDimitry Andric   CollectMostBases(RD);
12214ba319b5SDimitry Andric   return MostBases.takeVector();
12224ba319b5SDimitry Andric }
12234ba319b5SDimitry Andric 
SetLLVMFunctionAttributesForDefinition(const Decl * D,llvm::Function * F)1224f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
1225f22ef01cSRoman Divacky                                                            llvm::Function *F) {
1226f785676fSDimitry Andric   llvm::AttrBuilder B;
1227f785676fSDimitry Andric 
1228bd5abe19SDimitry Andric   if (CodeGenOpts.UnwindTables)
1229f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::UWTable);
1230bd5abe19SDimitry Andric 
1231dff0c46cSDimitry Andric   if (!hasUnwindExceptions(LangOpts))
1232f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoUnwind);
1233f22ef01cSRoman Divacky 
12344ba319b5SDimitry Andric   if (!D || !D->hasAttr<NoStackProtectorAttr>()) {
12350623d748SDimitry Andric     if (LangOpts.getStackProtector() == LangOptions::SSPOn)
12360623d748SDimitry Andric       B.addAttribute(llvm::Attribute::StackProtect);
12370623d748SDimitry Andric     else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
12380623d748SDimitry Andric       B.addAttribute(llvm::Attribute::StackProtectStrong);
12390623d748SDimitry Andric     else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
12400623d748SDimitry Andric       B.addAttribute(llvm::Attribute::StackProtectReq);
12414ba319b5SDimitry Andric   }
12420623d748SDimitry Andric 
12430623d748SDimitry Andric   if (!D) {
124444290647SDimitry Andric     // If we don't have a declaration to control inlining, the function isn't
124544290647SDimitry Andric     // explicitly marked as alwaysinline for semantic reasons, and inlining is
124644290647SDimitry Andric     // disabled, mark the function as noinline.
124744290647SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
124844290647SDimitry Andric         CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
124944290647SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
125044290647SDimitry Andric 
1251f37b6182SDimitry Andric     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
12520623d748SDimitry Andric     return;
12530623d748SDimitry Andric   }
12540623d748SDimitry Andric 
1255302affcbSDimitry Andric   // Track whether we need to add the optnone LLVM attribute,
1256302affcbSDimitry Andric   // starting with the default for this optimization level.
1257302affcbSDimitry Andric   bool ShouldAddOptNone =
1258302affcbSDimitry Andric       !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
1259302affcbSDimitry Andric   // We can't add optnone in the following cases, it won't pass the verifier.
1260302affcbSDimitry Andric   ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
1261302affcbSDimitry Andric   ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
1262302affcbSDimitry Andric   ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
1263302affcbSDimitry Andric 
1264302affcbSDimitry Andric   if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) {
126544290647SDimitry Andric     B.addAttribute(llvm::Attribute::OptimizeNone);
126644290647SDimitry Andric 
126744290647SDimitry Andric     // OptimizeNone implies noinline; we should not be inlining such functions.
126844290647SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
126944290647SDimitry Andric     assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
127044290647SDimitry Andric            "OptimizeNone and AlwaysInline on same function!");
127144290647SDimitry Andric 
127244290647SDimitry Andric     // We still need to handle naked functions even though optnone subsumes
127344290647SDimitry Andric     // much of their semantics.
127444290647SDimitry Andric     if (D->hasAttr<NakedAttr>())
127544290647SDimitry Andric       B.addAttribute(llvm::Attribute::Naked);
127644290647SDimitry Andric 
127744290647SDimitry Andric     // OptimizeNone wins over OptimizeForSize and MinSize.
127844290647SDimitry Andric     F->removeFnAttr(llvm::Attribute::OptimizeForSize);
127944290647SDimitry Andric     F->removeFnAttr(llvm::Attribute::MinSize);
128044290647SDimitry Andric   } else if (D->hasAttr<NakedAttr>()) {
12816122f3e6SDimitry Andric     // Naked implies noinline: we should not be inlining such functions.
1282f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::Naked);
1283f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
128459d1ed5bSDimitry Andric   } else if (D->hasAttr<NoDuplicateAttr>()) {
128559d1ed5bSDimitry Andric     B.addAttribute(llvm::Attribute::NoDuplicate);
1286f785676fSDimitry Andric   } else if (D->hasAttr<NoInlineAttr>()) {
1287f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
128859d1ed5bSDimitry Andric   } else if (D->hasAttr<AlwaysInlineAttr>() &&
128944290647SDimitry Andric              !F->hasFnAttribute(llvm::Attribute::NoInline)) {
1290f785676fSDimitry Andric     // (noinline wins over always_inline, and we can't specify both in IR)
1291f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::AlwaysInline);
129244290647SDimitry Andric   } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
129344290647SDimitry Andric     // If we're not inlining, then force everything that isn't always_inline to
129444290647SDimitry Andric     // carry an explicit noinline attribute.
129544290647SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
129644290647SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
129744290647SDimitry Andric   } else {
129844290647SDimitry Andric     // Otherwise, propagate the inline hint attribute and potentially use its
129944290647SDimitry Andric     // absence to mark things as noinline.
130044290647SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1301*b5893f02SDimitry Andric       // Search function and template pattern redeclarations for inline.
1302*b5893f02SDimitry Andric       auto CheckForInline = [](const FunctionDecl *FD) {
1303*b5893f02SDimitry Andric         auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
130444290647SDimitry Andric           return Redecl->isInlineSpecified();
1305*b5893f02SDimitry Andric         };
1306*b5893f02SDimitry Andric         if (any_of(FD->redecls(), CheckRedeclForInline))
1307*b5893f02SDimitry Andric           return true;
1308*b5893f02SDimitry Andric         const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
1309*b5893f02SDimitry Andric         if (!Pattern)
1310*b5893f02SDimitry Andric           return false;
1311*b5893f02SDimitry Andric         return any_of(Pattern->redecls(), CheckRedeclForInline);
1312*b5893f02SDimitry Andric       };
1313*b5893f02SDimitry Andric       if (CheckForInline(FD)) {
131444290647SDimitry Andric         B.addAttribute(llvm::Attribute::InlineHint);
131544290647SDimitry Andric       } else if (CodeGenOpts.getInlining() ==
131644290647SDimitry Andric                      CodeGenOptions::OnlyHintInlining &&
131744290647SDimitry Andric                  !FD->isInlined() &&
131844290647SDimitry Andric                  !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
131944290647SDimitry Andric         B.addAttribute(llvm::Attribute::NoInline);
132044290647SDimitry Andric       }
132144290647SDimitry Andric     }
13226122f3e6SDimitry Andric   }
13232754fe60SDimitry Andric 
132444290647SDimitry Andric   // Add other optimization related attributes if we are optimizing this
132544290647SDimitry Andric   // function.
132644290647SDimitry Andric   if (!D->hasAttr<OptimizeNoneAttr>()) {
1327f785676fSDimitry Andric     if (D->hasAttr<ColdAttr>()) {
1328302affcbSDimitry Andric       if (!ShouldAddOptNone)
1329f785676fSDimitry Andric         B.addAttribute(llvm::Attribute::OptimizeForSize);
1330f785676fSDimitry Andric       B.addAttribute(llvm::Attribute::Cold);
1331f785676fSDimitry Andric     }
13323861d79fSDimitry Andric 
13333861d79fSDimitry Andric     if (D->hasAttr<MinSizeAttr>())
1334f785676fSDimitry Andric       B.addAttribute(llvm::Attribute::MinSize);
133544290647SDimitry Andric   }
1336f22ef01cSRoman Divacky 
1337f37b6182SDimitry Andric   F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1338f785676fSDimitry Andric 
1339e580952dSDimitry Andric   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
1340e580952dSDimitry Andric   if (alignment)
1341e580952dSDimitry Andric     F->setAlignment(alignment);
1342e580952dSDimitry Andric 
13434ba319b5SDimitry Andric   if (!D->hasAttr<AlignedAttr>())
13444ba319b5SDimitry Andric     if (LangOpts.FunctionAlignment)
13454ba319b5SDimitry Andric       F->setAlignment(1 << LangOpts.FunctionAlignment);
13464ba319b5SDimitry Andric 
13470623d748SDimitry Andric   // Some C++ ABIs require 2-byte alignment for member functions, in order to
13480623d748SDimitry Andric   // reserve a bit for differentiating between virtual and non-virtual member
13490623d748SDimitry Andric   // functions. If the current target's C++ ABI requires this and this is a
13500623d748SDimitry Andric   // member function, set its alignment accordingly.
13510623d748SDimitry Andric   if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
1352f22ef01cSRoman Divacky     if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1353f22ef01cSRoman Divacky       F->setAlignment(2);
1354f22ef01cSRoman Divacky   }
135544290647SDimitry Andric 
135644290647SDimitry Andric   // In the cross-dso CFI mode, we want !type attributes on definitions only.
135744290647SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
135844290647SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D))
13594ba319b5SDimitry Andric       CreateFunctionTypeMetadataForIcall(FD, F);
13604ba319b5SDimitry Andric 
13614ba319b5SDimitry Andric   // Emit type metadata on member functions for member function pointer checks.
13624ba319b5SDimitry Andric   // These are only ever necessary on definitions; we're guaranteed that the
13634ba319b5SDimitry Andric   // definition will be present in the LTO unit as a result of LTO visibility.
13644ba319b5SDimitry Andric   auto *MD = dyn_cast<CXXMethodDecl>(D);
13654ba319b5SDimitry Andric   if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
13664ba319b5SDimitry Andric     for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
13674ba319b5SDimitry Andric       llvm::Metadata *Id =
13684ba319b5SDimitry Andric           CreateMetadataIdentifierForType(Context.getMemberPointerType(
13694ba319b5SDimitry Andric               MD->getType(), Context.getRecordType(Base).getTypePtr()));
13704ba319b5SDimitry Andric       F->addTypeMetadata(0, Id);
13714ba319b5SDimitry Andric     }
13724ba319b5SDimitry Andric   }
13730623d748SDimitry Andric }
1374f22ef01cSRoman Divacky 
SetCommonAttributes(GlobalDecl GD,llvm::GlobalValue * GV)13754ba319b5SDimitry Andric void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
13764ba319b5SDimitry Andric   const Decl *D = GD.getDecl();
13774ba319b5SDimitry Andric   if (dyn_cast_or_null<NamedDecl>(D))
13784ba319b5SDimitry Andric     setGVProperties(GV, GD);
13792754fe60SDimitry Andric   else
13802754fe60SDimitry Andric     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1381f22ef01cSRoman Divacky 
13820623d748SDimitry Andric   if (D && D->hasAttr<UsedAttr>())
138359d1ed5bSDimitry Andric     addUsedGlobal(GV);
1384*b5893f02SDimitry Andric 
1385*b5893f02SDimitry Andric   if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) {
1386*b5893f02SDimitry Andric     const auto *VD = cast<VarDecl>(D);
1387*b5893f02SDimitry Andric     if (VD->getType().isConstQualified() &&
1388*b5893f02SDimitry Andric         VD->getStorageDuration() == SD_Static)
1389*b5893f02SDimitry Andric       addUsedGlobal(GV);
1390*b5893f02SDimitry Andric   }
139159d1ed5bSDimitry Andric }
139259d1ed5bSDimitry Andric 
GetCPUAndFeaturesAttributes(GlobalDecl GD,llvm::AttrBuilder & Attrs)1393*b5893f02SDimitry Andric bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
13944ba319b5SDimitry Andric                                                 llvm::AttrBuilder &Attrs) {
13954ba319b5SDimitry Andric   // Add target-cpu and target-features attributes to functions. If
13964ba319b5SDimitry Andric   // we have a decl for the function and it has a target attribute then
13974ba319b5SDimitry Andric   // parse that and add it to the feature set.
13984ba319b5SDimitry Andric   StringRef TargetCPU = getTarget().getTargetOpts().CPU;
13994ba319b5SDimitry Andric   std::vector<std::string> Features;
1400*b5893f02SDimitry Andric   const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
14014ba319b5SDimitry Andric   FD = FD ? FD->getMostRecentDecl() : FD;
14024ba319b5SDimitry Andric   const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
14034ba319b5SDimitry Andric   const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
14044ba319b5SDimitry Andric   bool AddedAttr = false;
14054ba319b5SDimitry Andric   if (TD || SD) {
14064ba319b5SDimitry Andric     llvm::StringMap<bool> FeatureMap;
1407*b5893f02SDimitry Andric     getFunctionFeatureMap(FeatureMap, GD);
140839d628a0SDimitry Andric 
14094ba319b5SDimitry Andric     // Produce the canonical string for this set of features.
14104ba319b5SDimitry Andric     for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
14114ba319b5SDimitry Andric       Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
14124ba319b5SDimitry Andric 
14134ba319b5SDimitry Andric     // Now add the target-cpu and target-features to the function.
14144ba319b5SDimitry Andric     // While we populated the feature map above, we still need to
14154ba319b5SDimitry Andric     // get and parse the target attribute so we can get the cpu for
14164ba319b5SDimitry Andric     // the function.
14174ba319b5SDimitry Andric     if (TD) {
14184ba319b5SDimitry Andric       TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
14194ba319b5SDimitry Andric       if (ParsedAttr.Architecture != "" &&
14204ba319b5SDimitry Andric           getTarget().isValidCPUName(ParsedAttr.Architecture))
14214ba319b5SDimitry Andric         TargetCPU = ParsedAttr.Architecture;
14224ba319b5SDimitry Andric     }
14234ba319b5SDimitry Andric   } else {
14244ba319b5SDimitry Andric     // Otherwise just add the existing target cpu and target features to the
14254ba319b5SDimitry Andric     // function.
14264ba319b5SDimitry Andric     Features = getTarget().getTargetOpts().Features;
142739d628a0SDimitry Andric   }
142839d628a0SDimitry Andric 
14294ba319b5SDimitry Andric   if (TargetCPU != "") {
14304ba319b5SDimitry Andric     Attrs.addAttribute("target-cpu", TargetCPU);
14314ba319b5SDimitry Andric     AddedAttr = true;
14324ba319b5SDimitry Andric   }
14334ba319b5SDimitry Andric   if (!Features.empty()) {
1434*b5893f02SDimitry Andric     llvm::sort(Features);
14354ba319b5SDimitry Andric     Attrs.addAttribute("target-features", llvm::join(Features, ","));
14364ba319b5SDimitry Andric     AddedAttr = true;
14374ba319b5SDimitry Andric   }
14384ba319b5SDimitry Andric 
14394ba319b5SDimitry Andric   return AddedAttr;
14404ba319b5SDimitry Andric }
14414ba319b5SDimitry Andric 
setNonAliasAttributes(GlobalDecl GD,llvm::GlobalObject * GO)14424ba319b5SDimitry Andric void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
144359d1ed5bSDimitry Andric                                           llvm::GlobalObject *GO) {
14444ba319b5SDimitry Andric   const Decl *D = GD.getDecl();
14454ba319b5SDimitry Andric   SetCommonAttributes(GD, GO);
1446f22ef01cSRoman Divacky 
1447db17bf38SDimitry Andric   if (D) {
1448db17bf38SDimitry Andric     if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
1449db17bf38SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
1450db17bf38SDimitry Andric         GV->addAttribute("bss-section", SA->getName());
1451db17bf38SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
1452db17bf38SDimitry Andric         GV->addAttribute("data-section", SA->getName());
1453db17bf38SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
1454db17bf38SDimitry Andric         GV->addAttribute("rodata-section", SA->getName());
1455db17bf38SDimitry Andric     }
1456db17bf38SDimitry Andric 
1457db17bf38SDimitry Andric     if (auto *F = dyn_cast<llvm::Function>(GO)) {
1458db17bf38SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
1459db17bf38SDimitry Andric         if (!D->getAttr<SectionAttr>())
1460db17bf38SDimitry Andric           F->addFnAttr("implicit-section-name", SA->getName());
14614ba319b5SDimitry Andric 
14624ba319b5SDimitry Andric       llvm::AttrBuilder Attrs;
1463*b5893f02SDimitry Andric       if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
14644ba319b5SDimitry Andric         // We know that GetCPUAndFeaturesAttributes will always have the
14654ba319b5SDimitry Andric         // newest set, since it has the newest possible FunctionDecl, so the
14664ba319b5SDimitry Andric         // new ones should replace the old.
14674ba319b5SDimitry Andric         F->removeFnAttr("target-cpu");
14684ba319b5SDimitry Andric         F->removeFnAttr("target-features");
14694ba319b5SDimitry Andric         F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
14704ba319b5SDimitry Andric       }
1471db17bf38SDimitry Andric     }
1472db17bf38SDimitry Andric 
14734ba319b5SDimitry Andric     if (const auto *CSA = D->getAttr<CodeSegAttr>())
14744ba319b5SDimitry Andric       GO->setSection(CSA->getName());
14754ba319b5SDimitry Andric     else if (const auto *SA = D->getAttr<SectionAttr>())
147659d1ed5bSDimitry Andric       GO->setSection(SA->getName());
1477db17bf38SDimitry Andric   }
1478f22ef01cSRoman Divacky 
14794ba319b5SDimitry Andric   getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
1480f22ef01cSRoman Divacky }
1481f22ef01cSRoman Divacky 
SetInternalFunctionAttributes(GlobalDecl GD,llvm::Function * F,const CGFunctionInfo & FI)14824ba319b5SDimitry Andric void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
1483f22ef01cSRoman Divacky                                                   llvm::Function *F,
1484f22ef01cSRoman Divacky                                                   const CGFunctionInfo &FI) {
14854ba319b5SDimitry Andric   const Decl *D = GD.getDecl();
1486*b5893f02SDimitry Andric   SetLLVMFunctionAttributes(GD, FI, F);
1487f22ef01cSRoman Divacky   SetLLVMFunctionAttributesForDefinition(D, F);
1488f22ef01cSRoman Divacky 
1489f22ef01cSRoman Divacky   F->setLinkage(llvm::Function::InternalLinkage);
1490f22ef01cSRoman Divacky 
14914ba319b5SDimitry Andric   setNonAliasAttributes(GD, F);
149259d1ed5bSDimitry Andric }
149359d1ed5bSDimitry Andric 
setLinkageForGV(llvm::GlobalValue * GV,const NamedDecl * ND)14944ba319b5SDimitry Andric static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
149559d1ed5bSDimitry Andric   // Set linkage and visibility in case we never see a definition.
149659d1ed5bSDimitry Andric   LinkageInfo LV = ND->getLinkageAndVisibility();
149759d1ed5bSDimitry Andric   // Don't set internal linkage on declarations.
149859d1ed5bSDimitry Andric   // "extern_weak" is overloaded in LLVM; we probably should have
149959d1ed5bSDimitry Andric   // separate linkage types for this.
15004ba319b5SDimitry Andric   if (isExternallyVisible(LV.getLinkage()) &&
15014ba319b5SDimitry Andric       (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
150259d1ed5bSDimitry Andric     GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
150359d1ed5bSDimitry Andric }
1504f22ef01cSRoman Divacky 
CreateFunctionTypeMetadataForIcall(const FunctionDecl * FD,llvm::Function * F)15054ba319b5SDimitry Andric void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
15060623d748SDimitry Andric                                                        llvm::Function *F) {
15070623d748SDimitry Andric   // Only if we are checking indirect calls.
15080623d748SDimitry Andric   if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
15090623d748SDimitry Andric     return;
15100623d748SDimitry Andric 
15114ba319b5SDimitry Andric   // Non-static class methods are handled via vtable or member function pointer
15124ba319b5SDimitry Andric   // checks elsewhere.
15130623d748SDimitry Andric   if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
15140623d748SDimitry Andric     return;
15150623d748SDimitry Andric 
15160623d748SDimitry Andric   // Additionally, if building with cross-DSO support...
15170623d748SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
15180623d748SDimitry Andric     // Skip available_externally functions. They won't be codegen'ed in the
15190623d748SDimitry Andric     // current module anyway.
15200623d748SDimitry Andric     if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
15210623d748SDimitry Andric       return;
15220623d748SDimitry Andric   }
15230623d748SDimitry Andric 
15240623d748SDimitry Andric   llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
1525e7145dcbSDimitry Andric   F->addTypeMetadata(0, MD);
15269a199699SDimitry Andric   F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
15270623d748SDimitry Andric 
15280623d748SDimitry Andric   // Emit a hash-based bit set entry for cross-DSO calls.
1529e7145dcbSDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
1530e7145dcbSDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1531e7145dcbSDimitry Andric       F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
15320623d748SDimitry Andric }
15330623d748SDimitry Andric 
SetFunctionAttributes(GlobalDecl GD,llvm::Function * F,bool IsIncompleteFunction,bool IsThunk)153439d628a0SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
153539d628a0SDimitry Andric                                           bool IsIncompleteFunction,
15364ba319b5SDimitry Andric                                           bool IsThunk) {
15379a199699SDimitry Andric 
153833956c43SDimitry Andric   if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
15393b0f4066SDimitry Andric     // If this is an intrinsic function, set the function's attributes
15403b0f4066SDimitry Andric     // to the intrinsic's attributes.
154133956c43SDimitry Andric     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
15423b0f4066SDimitry Andric     return;
15433b0f4066SDimitry Andric   }
15443b0f4066SDimitry Andric 
154559d1ed5bSDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
1546f22ef01cSRoman Divacky 
15479a199699SDimitry Andric   if (!IsIncompleteFunction) {
1548*b5893f02SDimitry Andric     SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F);
15499a199699SDimitry Andric     // Setup target-specific attributes.
15504ba319b5SDimitry Andric     if (F->isDeclaration())
15514ba319b5SDimitry Andric       getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
15529a199699SDimitry Andric   }
1553f22ef01cSRoman Divacky 
155459d1ed5bSDimitry Andric   // Add the Returned attribute for "this", except for iOS 5 and earlier
155559d1ed5bSDimitry Andric   // where substantial code, including the libstdc++ dylib, was compiled with
155659d1ed5bSDimitry Andric   // GCC and does not actually return "this".
155739d628a0SDimitry Andric   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
155844290647SDimitry Andric       !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
1559f785676fSDimitry Andric     assert(!F->arg_empty() &&
1560f785676fSDimitry Andric            F->arg_begin()->getType()
1561f785676fSDimitry Andric              ->canLosslesslyBitCastTo(F->getReturnType()) &&
1562f785676fSDimitry Andric            "unexpected this return");
1563f785676fSDimitry Andric     F->addAttribute(1, llvm::Attribute::Returned);
1564f785676fSDimitry Andric   }
1565f785676fSDimitry Andric 
1566f22ef01cSRoman Divacky   // Only a few attributes are set on declarations; these may later be
1567f22ef01cSRoman Divacky   // overridden by a definition.
1568f22ef01cSRoman Divacky 
15699a199699SDimitry Andric   setLinkageForGV(F, FD);
15704ba319b5SDimitry Andric   setGVProperties(F, FD);
15712754fe60SDimitry Andric 
15724ba319b5SDimitry Andric   if (const auto *CSA = FD->getAttr<CodeSegAttr>())
15734ba319b5SDimitry Andric     F->setSection(CSA->getName());
15744ba319b5SDimitry Andric   else if (const auto *SA = FD->getAttr<SectionAttr>())
1575f22ef01cSRoman Divacky      F->setSection(SA->getName());
1576f785676fSDimitry Andric 
1577e7145dcbSDimitry Andric   if (FD->isReplaceableGlobalAllocationFunction()) {
1578f785676fSDimitry Andric     // A replaceable global allocation function does not act like a builtin by
1579f785676fSDimitry Andric     // default, only if it is invoked by a new-expression or delete-expression.
158020e90f04SDimitry Andric     F->addAttribute(llvm::AttributeList::FunctionIndex,
1581f785676fSDimitry Andric                     llvm::Attribute::NoBuiltin);
15820623d748SDimitry Andric 
1583e7145dcbSDimitry Andric     // A sane operator new returns a non-aliasing pointer.
1584e7145dcbSDimitry Andric     // FIXME: Also add NonNull attribute to the return value
1585e7145dcbSDimitry Andric     // for the non-nothrow forms?
1586e7145dcbSDimitry Andric     auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1587e7145dcbSDimitry Andric     if (getCodeGenOpts().AssumeSaneOperatorNew &&
1588e7145dcbSDimitry Andric         (Kind == OO_New || Kind == OO_Array_New))
158920e90f04SDimitry Andric       F->addAttribute(llvm::AttributeList::ReturnIndex,
1590e7145dcbSDimitry Andric                       llvm::Attribute::NoAlias);
1591e7145dcbSDimitry Andric   }
1592e7145dcbSDimitry Andric 
1593e7145dcbSDimitry Andric   if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1594e7145dcbSDimitry Andric     F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1595e7145dcbSDimitry Andric   else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1596e7145dcbSDimitry Andric     if (MD->isVirtual())
1597e7145dcbSDimitry Andric       F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1598e7145dcbSDimitry Andric 
159944290647SDimitry Andric   // Don't emit entries for function declarations in the cross-DSO mode. This
160044290647SDimitry Andric   // is handled with better precision by the receiving DSO.
160144290647SDimitry Andric   if (!CodeGenOpts.SanitizeCfiCrossDso)
16024ba319b5SDimitry Andric     CreateFunctionTypeMetadataForIcall(FD, F);
16039a199699SDimitry Andric 
16049a199699SDimitry Andric   if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
16059a199699SDimitry Andric     getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
1606f22ef01cSRoman Divacky }
1607f22ef01cSRoman Divacky 
addUsedGlobal(llvm::GlobalValue * GV)160859d1ed5bSDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
1609f22ef01cSRoman Divacky   assert(!GV->isDeclaration() &&
1610f22ef01cSRoman Divacky          "Only globals with definition can force usage.");
161197bc6c73SDimitry Andric   LLVMUsed.emplace_back(GV);
1612f22ef01cSRoman Divacky }
1613f22ef01cSRoman Divacky 
addCompilerUsedGlobal(llvm::GlobalValue * GV)161459d1ed5bSDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
161559d1ed5bSDimitry Andric   assert(!GV->isDeclaration() &&
161659d1ed5bSDimitry Andric          "Only globals with definition can force usage.");
161797bc6c73SDimitry Andric   LLVMCompilerUsed.emplace_back(GV);
161859d1ed5bSDimitry Andric }
161959d1ed5bSDimitry Andric 
emitUsed(CodeGenModule & CGM,StringRef Name,std::vector<llvm::WeakTrackingVH> & List)162059d1ed5bSDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name,
1621f37b6182SDimitry Andric                      std::vector<llvm::WeakTrackingVH> &List) {
1622f22ef01cSRoman Divacky   // Don't create llvm.used if there is no need.
162359d1ed5bSDimitry Andric   if (List.empty())
1624f22ef01cSRoman Divacky     return;
1625f22ef01cSRoman Divacky 
162659d1ed5bSDimitry Andric   // Convert List to what ConstantArray needs.
1627dff0c46cSDimitry Andric   SmallVector<llvm::Constant*, 8> UsedArray;
162859d1ed5bSDimitry Andric   UsedArray.resize(List.size());
162959d1ed5bSDimitry Andric   for (unsigned i = 0, e = List.size(); i != e; ++i) {
1630f22ef01cSRoman Divacky     UsedArray[i] =
163144f7b0dcSDimitry Andric         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
163244f7b0dcSDimitry Andric             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
1633f22ef01cSRoman Divacky   }
1634f22ef01cSRoman Divacky 
1635f22ef01cSRoman Divacky   if (UsedArray.empty())
1636f22ef01cSRoman Divacky     return;
163759d1ed5bSDimitry Andric   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
1638f22ef01cSRoman Divacky 
163959d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
164059d1ed5bSDimitry Andric       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
164159d1ed5bSDimitry Andric       llvm::ConstantArray::get(ATy, UsedArray), Name);
1642f22ef01cSRoman Divacky 
1643f22ef01cSRoman Divacky   GV->setSection("llvm.metadata");
1644f22ef01cSRoman Divacky }
1645f22ef01cSRoman Divacky 
emitLLVMUsed()164659d1ed5bSDimitry Andric void CodeGenModule::emitLLVMUsed() {
164759d1ed5bSDimitry Andric   emitUsed(*this, "llvm.used", LLVMUsed);
164859d1ed5bSDimitry Andric   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
164959d1ed5bSDimitry Andric }
165059d1ed5bSDimitry Andric 
AppendLinkerOptions(StringRef Opts)1651f785676fSDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
165239d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
1653f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1654f785676fSDimitry Andric }
1655f785676fSDimitry Andric 
AddDetectMismatch(StringRef Name,StringRef Value)1656f785676fSDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1657f785676fSDimitry Andric   llvm::SmallString<32> Opt;
1658f785676fSDimitry Andric   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
165939d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1660f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1661f785676fSDimitry Andric }
1662f785676fSDimitry Andric 
AddELFLibDirective(StringRef Lib)16634ba319b5SDimitry Andric void CodeGenModule::AddELFLibDirective(StringRef Lib) {
16644ba319b5SDimitry Andric   auto &C = getLLVMContext();
16654ba319b5SDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(
16664ba319b5SDimitry Andric       C, {llvm::MDString::get(C, "lib"), llvm::MDString::get(C, Lib)}));
16674ba319b5SDimitry Andric }
16684ba319b5SDimitry Andric 
AddDependentLib(StringRef Lib)1669f785676fSDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) {
1670f785676fSDimitry Andric   llvm::SmallString<24> Opt;
1671f785676fSDimitry Andric   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
167239d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1673f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1674f785676fSDimitry Andric }
1675f785676fSDimitry Andric 
16764ba319b5SDimitry Andric /// Add link options implied by the given module, including modules
1677139f7f9bSDimitry Andric /// it depends on, using a postorder walk.
addLinkOptionsPostorder(CodeGenModule & CGM,Module * Mod,SmallVectorImpl<llvm::MDNode * > & Metadata,llvm::SmallPtrSet<Module *,16> & Visited)167839d628a0SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
167924d58133SDimitry Andric                                     SmallVectorImpl<llvm::MDNode *> &Metadata,
1680139f7f9bSDimitry Andric                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
1681139f7f9bSDimitry Andric   // Import this module's parent.
168239d628a0SDimitry Andric   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
1683f785676fSDimitry Andric     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
1684139f7f9bSDimitry Andric   }
1685139f7f9bSDimitry Andric 
1686139f7f9bSDimitry Andric   // Import this module's dependencies.
1687139f7f9bSDimitry Andric   for (unsigned I = Mod->Imports.size(); I > 0; --I) {
168839d628a0SDimitry Andric     if (Visited.insert(Mod->Imports[I - 1]).second)
1689f785676fSDimitry Andric       addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
1690139f7f9bSDimitry Andric   }
1691139f7f9bSDimitry Andric 
1692139f7f9bSDimitry Andric   // Add linker options to link against the libraries/frameworks
1693139f7f9bSDimitry Andric   // described by this module.
1694f785676fSDimitry Andric   llvm::LLVMContext &Context = CGM.getLLVMContext();
1695*b5893f02SDimitry Andric   bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
1696*b5893f02SDimitry Andric   bool IsPS4 = CGM.getTarget().getTriple().isPS4();
16974ba319b5SDimitry Andric 
16984ba319b5SDimitry Andric   // For modules that use export_as for linking, use that module
16994ba319b5SDimitry Andric   // name instead.
17004ba319b5SDimitry Andric   if (Mod->UseExportAsModuleLinkName)
17014ba319b5SDimitry Andric     return;
17024ba319b5SDimitry Andric 
1703139f7f9bSDimitry Andric   for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
1704f785676fSDimitry Andric     // Link against a framework.  Frameworks are currently Darwin only, so we
1705f785676fSDimitry Andric     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
1706139f7f9bSDimitry Andric     if (Mod->LinkLibraries[I-1].IsFramework) {
170739d628a0SDimitry Andric       llvm::Metadata *Args[2] = {
1708139f7f9bSDimitry Andric           llvm::MDString::get(Context, "-framework"),
170939d628a0SDimitry Andric           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
1710139f7f9bSDimitry Andric 
1711139f7f9bSDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, Args));
1712139f7f9bSDimitry Andric       continue;
1713139f7f9bSDimitry Andric     }
1714139f7f9bSDimitry Andric 
1715139f7f9bSDimitry Andric     // Link against a library.
1716*b5893f02SDimitry Andric     if (IsELF && !IsPS4) {
1717*b5893f02SDimitry Andric       llvm::Metadata *Args[2] = {
1718*b5893f02SDimitry Andric           llvm::MDString::get(Context, "lib"),
1719*b5893f02SDimitry Andric           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library),
1720*b5893f02SDimitry Andric       };
1721*b5893f02SDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, Args));
1722*b5893f02SDimitry Andric     } else {
1723f785676fSDimitry Andric       llvm::SmallString<24> Opt;
1724f785676fSDimitry Andric       CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1725f785676fSDimitry Andric           Mod->LinkLibraries[I - 1].Library, Opt);
172639d628a0SDimitry Andric       auto *OptString = llvm::MDString::get(Context, Opt);
1727139f7f9bSDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, OptString));
1728139f7f9bSDimitry Andric     }
1729139f7f9bSDimitry Andric   }
1730*b5893f02SDimitry Andric }
1731139f7f9bSDimitry Andric 
EmitModuleLinkOptions()1732139f7f9bSDimitry Andric void CodeGenModule::EmitModuleLinkOptions() {
1733139f7f9bSDimitry Andric   // Collect the set of all of the modules we want to visit to emit link
1734139f7f9bSDimitry Andric   // options, which is essentially the imported modules and all of their
1735139f7f9bSDimitry Andric   // non-explicit child modules.
1736139f7f9bSDimitry Andric   llvm::SetVector<clang::Module *> LinkModules;
1737139f7f9bSDimitry Andric   llvm::SmallPtrSet<clang::Module *, 16> Visited;
1738139f7f9bSDimitry Andric   SmallVector<clang::Module *, 16> Stack;
1739139f7f9bSDimitry Andric 
1740139f7f9bSDimitry Andric   // Seed the stack with imported modules.
1741f1a29dd3SDimitry Andric   for (Module *M : ImportedModules) {
1742f1a29dd3SDimitry Andric     // Do not add any link flags when an implementation TU of a module imports
1743f1a29dd3SDimitry Andric     // a header of that same module.
1744f1a29dd3SDimitry Andric     if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
1745f1a29dd3SDimitry Andric         !getLangOpts().isCompilingModule())
1746f1a29dd3SDimitry Andric       continue;
17478f0fd8f6SDimitry Andric     if (Visited.insert(M).second)
17488f0fd8f6SDimitry Andric       Stack.push_back(M);
1749f1a29dd3SDimitry Andric   }
1750139f7f9bSDimitry Andric 
1751139f7f9bSDimitry Andric   // Find all of the modules to import, making a little effort to prune
1752139f7f9bSDimitry Andric   // non-leaf modules.
1753139f7f9bSDimitry Andric   while (!Stack.empty()) {
1754f785676fSDimitry Andric     clang::Module *Mod = Stack.pop_back_val();
1755139f7f9bSDimitry Andric 
1756139f7f9bSDimitry Andric     bool AnyChildren = false;
1757139f7f9bSDimitry Andric 
1758139f7f9bSDimitry Andric     // Visit the submodules of this module.
1759*b5893f02SDimitry Andric     for (const auto &SM : Mod->submodules()) {
1760139f7f9bSDimitry Andric       // Skip explicit children; they need to be explicitly imported to be
1761139f7f9bSDimitry Andric       // linked against.
1762*b5893f02SDimitry Andric       if (SM->IsExplicit)
1763139f7f9bSDimitry Andric         continue;
1764139f7f9bSDimitry Andric 
1765*b5893f02SDimitry Andric       if (Visited.insert(SM).second) {
1766*b5893f02SDimitry Andric         Stack.push_back(SM);
1767139f7f9bSDimitry Andric         AnyChildren = true;
1768139f7f9bSDimitry Andric       }
1769139f7f9bSDimitry Andric     }
1770139f7f9bSDimitry Andric 
1771139f7f9bSDimitry Andric     // We didn't find any children, so add this module to the list of
1772139f7f9bSDimitry Andric     // modules to link against.
1773139f7f9bSDimitry Andric     if (!AnyChildren) {
1774139f7f9bSDimitry Andric       LinkModules.insert(Mod);
1775139f7f9bSDimitry Andric     }
1776139f7f9bSDimitry Andric   }
1777139f7f9bSDimitry Andric 
1778139f7f9bSDimitry Andric   // Add link options for all of the imported modules in reverse topological
1779f785676fSDimitry Andric   // order.  We don't do anything to try to order import link flags with respect
1780f785676fSDimitry Andric   // to linker options inserted by things like #pragma comment().
178124d58133SDimitry Andric   SmallVector<llvm::MDNode *, 16> MetadataArgs;
1782139f7f9bSDimitry Andric   Visited.clear();
17838f0fd8f6SDimitry Andric   for (Module *M : LinkModules)
17848f0fd8f6SDimitry Andric     if (Visited.insert(M).second)
17858f0fd8f6SDimitry Andric       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
1786139f7f9bSDimitry Andric   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1787f785676fSDimitry Andric   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1788139f7f9bSDimitry Andric 
1789139f7f9bSDimitry Andric   // Add the linker options metadata flag.
179024d58133SDimitry Andric   auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
179124d58133SDimitry Andric   for (auto *MD : LinkerOptionsMetadata)
179224d58133SDimitry Andric     NMD->addOperand(MD);
1793139f7f9bSDimitry Andric }
1794139f7f9bSDimitry Andric 
EmitDeferred()1795f22ef01cSRoman Divacky void CodeGenModule::EmitDeferred() {
1796*b5893f02SDimitry Andric   // Emit deferred declare target declarations.
1797*b5893f02SDimitry Andric   if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
1798*b5893f02SDimitry Andric     getOpenMPRuntime().emitDeferredTargetDecls();
1799*b5893f02SDimitry Andric 
1800f22ef01cSRoman Divacky   // Emit code for any potentially referenced deferred decls.  Since a
1801f22ef01cSRoman Divacky   // previously unused static decl may become used during the generation of code
1802f22ef01cSRoman Divacky   // for a static function, iterate until no changes are made.
1803f22ef01cSRoman Divacky 
1804f22ef01cSRoman Divacky   if (!DeferredVTables.empty()) {
1805139f7f9bSDimitry Andric     EmitDeferredVTables();
1806139f7f9bSDimitry Andric 
1807e7145dcbSDimitry Andric     // Emitting a vtable doesn't directly cause more vtables to
1808139f7f9bSDimitry Andric     // become deferred, although it can cause functions to be
1809e7145dcbSDimitry Andric     // emitted that then need those vtables.
1810139f7f9bSDimitry Andric     assert(DeferredVTables.empty());
1811f22ef01cSRoman Divacky   }
1812f22ef01cSRoman Divacky 
1813e7145dcbSDimitry Andric   // Stop if we're out of both deferred vtables and deferred declarations.
181433956c43SDimitry Andric   if (DeferredDeclsToEmit.empty())
181533956c43SDimitry Andric     return;
1816139f7f9bSDimitry Andric 
181733956c43SDimitry Andric   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
181833956c43SDimitry Andric   // work, it will not interfere with this.
1819f37b6182SDimitry Andric   std::vector<GlobalDecl> CurDeclsToEmit;
182033956c43SDimitry Andric   CurDeclsToEmit.swap(DeferredDeclsToEmit);
182133956c43SDimitry Andric 
1822f37b6182SDimitry Andric   for (GlobalDecl &D : CurDeclsToEmit) {
18230623d748SDimitry Andric     // We should call GetAddrOfGlobal with IsForDefinition set to true in order
18240623d748SDimitry Andric     // to get GlobalValue with exactly the type we need, not something that
18250623d748SDimitry Andric     // might had been created for another decl with the same mangled name but
18260623d748SDimitry Andric     // different type.
1827e7145dcbSDimitry Andric     llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
182844290647SDimitry Andric         GetAddrOfGlobal(D, ForDefinition));
1829e7145dcbSDimitry Andric 
1830e7145dcbSDimitry Andric     // In case of different address spaces, we may still get a cast, even with
1831e7145dcbSDimitry Andric     // IsForDefinition equal to true. Query mangled names table to get
1832e7145dcbSDimitry Andric     // GlobalValue.
183339d628a0SDimitry Andric     if (!GV)
183439d628a0SDimitry Andric       GV = GetGlobalValue(getMangledName(D));
183539d628a0SDimitry Andric 
1836e7145dcbSDimitry Andric     // Make sure GetGlobalValue returned non-null.
1837e7145dcbSDimitry Andric     assert(GV);
1838e7145dcbSDimitry Andric 
1839f22ef01cSRoman Divacky     // Check to see if we've already emitted this.  This is necessary
1840f22ef01cSRoman Divacky     // for a couple of reasons: first, decls can end up in the
1841f22ef01cSRoman Divacky     // deferred-decls queue multiple times, and second, decls can end
1842f22ef01cSRoman Divacky     // up with definitions in unusual ways (e.g. by an extern inline
1843f22ef01cSRoman Divacky     // function acquiring a strong function redefinition).  Just
1844f22ef01cSRoman Divacky     // ignore these cases.
1845e7145dcbSDimitry Andric     if (!GV->isDeclaration())
1846f22ef01cSRoman Divacky       continue;
1847f22ef01cSRoman Divacky 
1848f22ef01cSRoman Divacky     // Otherwise, emit the definition and move on to the next one.
184959d1ed5bSDimitry Andric     EmitGlobalDefinition(D, GV);
185033956c43SDimitry Andric 
185133956c43SDimitry Andric     // If we found out that we need to emit more decls, do that recursively.
185233956c43SDimitry Andric     // This has the advantage that the decls are emitted in a DFS and related
185333956c43SDimitry Andric     // ones are close together, which is convenient for testing.
185433956c43SDimitry Andric     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
185533956c43SDimitry Andric       EmitDeferred();
185633956c43SDimitry Andric       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
185733956c43SDimitry Andric     }
1858f22ef01cSRoman Divacky   }
1859f22ef01cSRoman Divacky }
1860f22ef01cSRoman Divacky 
EmitVTablesOpportunistically()1861f9448bf3SDimitry Andric void CodeGenModule::EmitVTablesOpportunistically() {
1862f9448bf3SDimitry Andric   // Try to emit external vtables as available_externally if they have emitted
1863f9448bf3SDimitry Andric   // all inlined virtual functions.  It runs after EmitDeferred() and therefore
1864f9448bf3SDimitry Andric   // is not allowed to create new references to things that need to be emitted
1865f9448bf3SDimitry Andric   // lazily. Note that it also uses fact that we eagerly emitting RTTI.
1866f9448bf3SDimitry Andric 
1867f9448bf3SDimitry Andric   assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
1868f9448bf3SDimitry Andric          && "Only emit opportunistic vtables with optimizations");
1869f9448bf3SDimitry Andric 
1870f9448bf3SDimitry Andric   for (const CXXRecordDecl *RD : OpportunisticVTables) {
1871f9448bf3SDimitry Andric     assert(getVTables().isVTableExternal(RD) &&
1872f9448bf3SDimitry Andric            "This queue should only contain external vtables");
1873f9448bf3SDimitry Andric     if (getCXXABI().canSpeculativelyEmitVTable(RD))
1874f9448bf3SDimitry Andric       VTables.GenerateClassData(RD);
1875f9448bf3SDimitry Andric   }
1876f9448bf3SDimitry Andric   OpportunisticVTables.clear();
1877f9448bf3SDimitry Andric }
1878f9448bf3SDimitry Andric 
EmitGlobalAnnotations()18796122f3e6SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() {
18806122f3e6SDimitry Andric   if (Annotations.empty())
18816122f3e6SDimitry Andric     return;
18826122f3e6SDimitry Andric 
18836122f3e6SDimitry Andric   // Create a new global variable for the ConstantStruct in the Module.
18846122f3e6SDimitry Andric   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
18856122f3e6SDimitry Andric     Annotations[0]->getType(), Annotations.size()), Annotations);
188659d1ed5bSDimitry Andric   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
188759d1ed5bSDimitry Andric                                       llvm::GlobalValue::AppendingLinkage,
188859d1ed5bSDimitry Andric                                       Array, "llvm.global.annotations");
18896122f3e6SDimitry Andric   gv->setSection(AnnotationSection);
18906122f3e6SDimitry Andric }
18916122f3e6SDimitry Andric 
EmitAnnotationString(StringRef Str)1892139f7f9bSDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1893f785676fSDimitry Andric   llvm::Constant *&AStr = AnnotationStrings[Str];
1894f785676fSDimitry Andric   if (AStr)
1895f785676fSDimitry Andric     return AStr;
18966122f3e6SDimitry Andric 
18976122f3e6SDimitry Andric   // Not found yet, create a new global.
1898dff0c46cSDimitry Andric   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
189959d1ed5bSDimitry Andric   auto *gv =
190059d1ed5bSDimitry Andric       new llvm::GlobalVariable(getModule(), s->getType(), true,
190159d1ed5bSDimitry Andric                                llvm::GlobalValue::PrivateLinkage, s, ".str");
19026122f3e6SDimitry Andric   gv->setSection(AnnotationSection);
1903e7145dcbSDimitry Andric   gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1904f785676fSDimitry Andric   AStr = gv;
19056122f3e6SDimitry Andric   return gv;
19066122f3e6SDimitry Andric }
19076122f3e6SDimitry Andric 
EmitAnnotationUnit(SourceLocation Loc)19086122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
19096122f3e6SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
19106122f3e6SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
19116122f3e6SDimitry Andric   if (PLoc.isValid())
19126122f3e6SDimitry Andric     return EmitAnnotationString(PLoc.getFilename());
19136122f3e6SDimitry Andric   return EmitAnnotationString(SM.getBufferName(Loc));
19146122f3e6SDimitry Andric }
19156122f3e6SDimitry Andric 
EmitAnnotationLineNo(SourceLocation L)19166122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
19176122f3e6SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
19186122f3e6SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(L);
19196122f3e6SDimitry Andric   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
19206122f3e6SDimitry Andric     SM.getExpansionLineNumber(L);
19216122f3e6SDimitry Andric   return llvm::ConstantInt::get(Int32Ty, LineNo);
19226122f3e6SDimitry Andric }
19236122f3e6SDimitry Andric 
EmitAnnotateAttr(llvm::GlobalValue * GV,const AnnotateAttr * AA,SourceLocation L)1924f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1925f22ef01cSRoman Divacky                                                 const AnnotateAttr *AA,
19266122f3e6SDimitry Andric                                                 SourceLocation L) {
19276122f3e6SDimitry Andric   // Get the globals for file name, annotation, and the line number.
19286122f3e6SDimitry Andric   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
19296122f3e6SDimitry Andric                  *UnitGV = EmitAnnotationUnit(L),
19306122f3e6SDimitry Andric                  *LineNoCst = EmitAnnotationLineNo(L);
1931f22ef01cSRoman Divacky 
1932f22ef01cSRoman Divacky   // Create the ConstantStruct for the global annotation.
1933f22ef01cSRoman Divacky   llvm::Constant *Fields[4] = {
19346122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
19356122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
19366122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
19376122f3e6SDimitry Andric     LineNoCst
1938f22ef01cSRoman Divacky   };
193917a519f9SDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
1940f22ef01cSRoman Divacky }
1941f22ef01cSRoman Divacky 
AddGlobalAnnotations(const ValueDecl * D,llvm::GlobalValue * GV)19426122f3e6SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
19436122f3e6SDimitry Andric                                          llvm::GlobalValue *GV) {
19446122f3e6SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
19456122f3e6SDimitry Andric   // Get the struct elements for these annotations.
194659d1ed5bSDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>())
194759d1ed5bSDimitry Andric     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
19486122f3e6SDimitry Andric }
19496122f3e6SDimitry Andric 
isInSanitizerBlacklist(SanitizerMask Kind,llvm::Function * Fn,SourceLocation Loc) const19509a199699SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind,
19519a199699SDimitry Andric                                            llvm::Function *Fn,
195239d628a0SDimitry Andric                                            SourceLocation Loc) const {
195339d628a0SDimitry Andric   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
195439d628a0SDimitry Andric   // Blacklist by function name.
19559a199699SDimitry Andric   if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
195639d628a0SDimitry Andric     return true;
195739d628a0SDimitry Andric   // Blacklist by location.
19580623d748SDimitry Andric   if (Loc.isValid())
19599a199699SDimitry Andric     return SanitizerBL.isBlacklistedLocation(Kind, Loc);
196039d628a0SDimitry Andric   // If location is unknown, this may be a compiler-generated function. Assume
196139d628a0SDimitry Andric   // it's located in the main file.
196239d628a0SDimitry Andric   auto &SM = Context.getSourceManager();
196339d628a0SDimitry Andric   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
19649a199699SDimitry Andric     return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
196539d628a0SDimitry Andric   }
196639d628a0SDimitry Andric   return false;
196739d628a0SDimitry Andric }
196839d628a0SDimitry Andric 
isInSanitizerBlacklist(llvm::GlobalVariable * GV,SourceLocation Loc,QualType Ty,StringRef Category) const196939d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
197039d628a0SDimitry Andric                                            SourceLocation Loc, QualType Ty,
197139d628a0SDimitry Andric                                            StringRef Category) const {
19728f0fd8f6SDimitry Andric   // For now globals can be blacklisted only in ASan and KASan.
19739a199699SDimitry Andric   const SanitizerMask EnabledAsanMask = LangOpts.Sanitize.Mask &
19744ba319b5SDimitry Andric       (SanitizerKind::Address | SanitizerKind::KernelAddress |
19754ba319b5SDimitry Andric        SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress);
19769a199699SDimitry Andric   if (!EnabledAsanMask)
197739d628a0SDimitry Andric     return false;
197839d628a0SDimitry Andric   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
19799a199699SDimitry Andric   if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
198039d628a0SDimitry Andric     return true;
19819a199699SDimitry Andric   if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
198239d628a0SDimitry Andric     return true;
198339d628a0SDimitry Andric   // Check global type.
198439d628a0SDimitry Andric   if (!Ty.isNull()) {
198539d628a0SDimitry Andric     // Drill down the array types: if global variable of a fixed type is
198639d628a0SDimitry Andric     // blacklisted, we also don't instrument arrays of them.
198739d628a0SDimitry Andric     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
198839d628a0SDimitry Andric       Ty = AT->getElementType();
198939d628a0SDimitry Andric     Ty = Ty.getCanonicalType().getUnqualifiedType();
199039d628a0SDimitry Andric     // We allow to blacklist only record types (classes, structs etc.)
199139d628a0SDimitry Andric     if (Ty->isRecordType()) {
199239d628a0SDimitry Andric       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
19939a199699SDimitry Andric       if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
199439d628a0SDimitry Andric         return true;
199539d628a0SDimitry Andric     }
199639d628a0SDimitry Andric   }
199739d628a0SDimitry Andric   return false;
199839d628a0SDimitry Andric }
199939d628a0SDimitry Andric 
imbueXRayAttrs(llvm::Function * Fn,SourceLocation Loc,StringRef Category) const200020e90f04SDimitry Andric bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
200120e90f04SDimitry Andric                                    StringRef Category) const {
200220e90f04SDimitry Andric   const auto &XRayFilter = getContext().getXRayFilter();
200320e90f04SDimitry Andric   using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
20044ba319b5SDimitry Andric   auto Attr = ImbueAttr::NONE;
200520e90f04SDimitry Andric   if (Loc.isValid())
200620e90f04SDimitry Andric     Attr = XRayFilter.shouldImbueLocation(Loc, Category);
200720e90f04SDimitry Andric   if (Attr == ImbueAttr::NONE)
200820e90f04SDimitry Andric     Attr = XRayFilter.shouldImbueFunction(Fn->getName());
200920e90f04SDimitry Andric   switch (Attr) {
201020e90f04SDimitry Andric   case ImbueAttr::NONE:
201120e90f04SDimitry Andric     return false;
201220e90f04SDimitry Andric   case ImbueAttr::ALWAYS:
201320e90f04SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-always");
201420e90f04SDimitry Andric     break;
2015302affcbSDimitry Andric   case ImbueAttr::ALWAYS_ARG1:
2016302affcbSDimitry Andric     Fn->addFnAttr("function-instrument", "xray-always");
2017302affcbSDimitry Andric     Fn->addFnAttr("xray-log-args", "1");
2018302affcbSDimitry Andric     break;
201920e90f04SDimitry Andric   case ImbueAttr::NEVER:
202020e90f04SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-never");
202120e90f04SDimitry Andric     break;
202220e90f04SDimitry Andric   }
202320e90f04SDimitry Andric   return true;
202420e90f04SDimitry Andric }
202520e90f04SDimitry Andric 
MustBeEmitted(const ValueDecl * Global)202639d628a0SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
2027e580952dSDimitry Andric   // Never defer when EmitAllDecls is specified.
2028dff0c46cSDimitry Andric   if (LangOpts.EmitAllDecls)
202939d628a0SDimitry Andric     return true;
203039d628a0SDimitry Andric 
2031*b5893f02SDimitry Andric   if (CodeGenOpts.KeepStaticConsts) {
2032*b5893f02SDimitry Andric     const auto *VD = dyn_cast<VarDecl>(Global);
2033*b5893f02SDimitry Andric     if (VD && VD->getType().isConstQualified() &&
2034*b5893f02SDimitry Andric         VD->getStorageDuration() == SD_Static)
2035*b5893f02SDimitry Andric       return true;
2036*b5893f02SDimitry Andric   }
2037*b5893f02SDimitry Andric 
203839d628a0SDimitry Andric   return getContext().DeclMustBeEmitted(Global);
203939d628a0SDimitry Andric }
204039d628a0SDimitry Andric 
MayBeEmittedEagerly(const ValueDecl * Global)204139d628a0SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
204239d628a0SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global))
204339d628a0SDimitry Andric     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
204439d628a0SDimitry Andric       // Implicit template instantiations may change linkage if they are later
204539d628a0SDimitry Andric       // explicitly instantiated, so they should not be emitted eagerly.
2046f22ef01cSRoman Divacky       return false;
2047e7145dcbSDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(Global))
2048e7145dcbSDimitry Andric     if (Context.getInlineVariableDefinitionKind(VD) ==
2049e7145dcbSDimitry Andric         ASTContext::InlineVariableDefinitionKind::WeakUnknown)
2050e7145dcbSDimitry Andric       // A definition of an inline constexpr static data member may change
2051e7145dcbSDimitry Andric       // linkage later if it's redeclared outside the class.
2052e7145dcbSDimitry Andric       return false;
2053875ed548SDimitry Andric   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
2054875ed548SDimitry Andric   // codegen for global variables, because they may be marked as threadprivate.
2055875ed548SDimitry Andric   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
20564ba319b5SDimitry Andric       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
2057*b5893f02SDimitry Andric       !isTypeConstant(Global->getType(), false) &&
2058*b5893f02SDimitry Andric       !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
2059875ed548SDimitry Andric     return false;
2060f22ef01cSRoman Divacky 
206139d628a0SDimitry Andric   return true;
2062f22ef01cSRoman Divacky }
2063f22ef01cSRoman Divacky 
GetAddrOfUuidDescriptor(const CXXUuidofExpr * E)20640623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
20653861d79fSDimitry Andric     const CXXUuidofExpr* E) {
20663861d79fSDimitry Andric   // Sema has verified that IIDSource has a __declspec(uuid()), and that its
20673861d79fSDimitry Andric   // well-formed.
2068e7145dcbSDimitry Andric   StringRef Uuid = E->getUuidStr();
2069f785676fSDimitry Andric   std::string Name = "_GUID_" + Uuid.lower();
2070f785676fSDimitry Andric   std::replace(Name.begin(), Name.end(), '-', '_');
20713861d79fSDimitry Andric 
2072e7145dcbSDimitry Andric   // The UUID descriptor should be pointer aligned.
2073e7145dcbSDimitry Andric   CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
20740623d748SDimitry Andric 
20753861d79fSDimitry Andric   // Look for an existing global.
20763861d79fSDimitry Andric   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
20770623d748SDimitry Andric     return ConstantAddress(GV, Alignment);
20783861d79fSDimitry Andric 
207939d628a0SDimitry Andric   llvm::Constant *Init = EmitUuidofInitializer(Uuid);
20803861d79fSDimitry Andric   assert(Init && "failed to initialize as constant");
20813861d79fSDimitry Andric 
208259d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
2083f785676fSDimitry Andric       getModule(), Init->getType(),
2084f785676fSDimitry Andric       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
208533956c43SDimitry Andric   if (supportsCOMDAT())
208633956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
20874ba319b5SDimitry Andric   setDSOLocal(GV);
20880623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
20893861d79fSDimitry Andric }
20903861d79fSDimitry Andric 
GetWeakRefReference(const ValueDecl * VD)20910623d748SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
2092f22ef01cSRoman Divacky   const AliasAttr *AA = VD->getAttr<AliasAttr>();
2093f22ef01cSRoman Divacky   assert(AA && "No alias?");
2094f22ef01cSRoman Divacky 
20950623d748SDimitry Andric   CharUnits Alignment = getContext().getDeclAlign(VD);
20966122f3e6SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
2097f22ef01cSRoman Divacky 
2098f22ef01cSRoman Divacky   // See if there is already something with the target's name in the module.
2099f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
21003861d79fSDimitry Andric   if (Entry) {
21013861d79fSDimitry Andric     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
21020623d748SDimitry Andric     auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
21030623d748SDimitry Andric     return ConstantAddress(Ptr, Alignment);
21043861d79fSDimitry Andric   }
2105f22ef01cSRoman Divacky 
2106f22ef01cSRoman Divacky   llvm::Constant *Aliasee;
2107f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(DeclTy))
21083861d79fSDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
21093861d79fSDimitry Andric                                       GlobalDecl(cast<FunctionDecl>(VD)),
21102754fe60SDimitry Andric                                       /*ForVTable=*/false);
2111f22ef01cSRoman Divacky   else
2112f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
211359d1ed5bSDimitry Andric                                     llvm::PointerType::getUnqual(DeclTy),
211459d1ed5bSDimitry Andric                                     nullptr);
21153861d79fSDimitry Andric 
211659d1ed5bSDimitry Andric   auto *F = cast<llvm::GlobalValue>(Aliasee);
2117f22ef01cSRoman Divacky   F->setLinkage(llvm::Function::ExternalWeakLinkage);
2118f22ef01cSRoman Divacky   WeakRefReferences.insert(F);
2119f22ef01cSRoman Divacky 
21200623d748SDimitry Andric   return ConstantAddress(Aliasee, Alignment);
2121f22ef01cSRoman Divacky }
2122f22ef01cSRoman Divacky 
EmitGlobal(GlobalDecl GD)2123f22ef01cSRoman Divacky void CodeGenModule::EmitGlobal(GlobalDecl GD) {
212459d1ed5bSDimitry Andric   const auto *Global = cast<ValueDecl>(GD.getDecl());
2125f22ef01cSRoman Divacky 
2126f22ef01cSRoman Divacky   // Weak references don't produce any output by themselves.
2127f22ef01cSRoman Divacky   if (Global->hasAttr<WeakRefAttr>())
2128f22ef01cSRoman Divacky     return;
2129f22ef01cSRoman Divacky 
2130f22ef01cSRoman Divacky   // If this is an alias definition (which otherwise looks like a declaration)
2131f22ef01cSRoman Divacky   // emit it now.
2132f22ef01cSRoman Divacky   if (Global->hasAttr<AliasAttr>())
2133f22ef01cSRoman Divacky     return EmitAliasDefinition(GD);
2134f22ef01cSRoman Divacky 
2135e7145dcbSDimitry Andric   // IFunc like an alias whose value is resolved at runtime by calling resolver.
2136e7145dcbSDimitry Andric   if (Global->hasAttr<IFuncAttr>())
2137e7145dcbSDimitry Andric     return emitIFuncDefinition(GD);
2138e7145dcbSDimitry Andric 
21394ba319b5SDimitry Andric   // If this is a cpu_dispatch multiversion function, emit the resolver.
21404ba319b5SDimitry Andric   if (Global->hasAttr<CPUDispatchAttr>())
21414ba319b5SDimitry Andric     return emitCPUDispatchDefinition(GD);
21424ba319b5SDimitry Andric 
21436122f3e6SDimitry Andric   // If this is CUDA, be selective about which declarations we emit.
2144dff0c46cSDimitry Andric   if (LangOpts.CUDA) {
214533956c43SDimitry Andric     if (LangOpts.CUDAIsDevice) {
21466122f3e6SDimitry Andric       if (!Global->hasAttr<CUDADeviceAttr>() &&
21476122f3e6SDimitry Andric           !Global->hasAttr<CUDAGlobalAttr>() &&
21486122f3e6SDimitry Andric           !Global->hasAttr<CUDAConstantAttr>() &&
21496122f3e6SDimitry Andric           !Global->hasAttr<CUDASharedAttr>())
21506122f3e6SDimitry Andric         return;
21516122f3e6SDimitry Andric     } else {
2152e7145dcbSDimitry Andric       // We need to emit host-side 'shadows' for all global
2153e7145dcbSDimitry Andric       // device-side variables because the CUDA runtime needs their
2154e7145dcbSDimitry Andric       // size and host-side address in order to provide access to
2155e7145dcbSDimitry Andric       // their device-side incarnations.
2156e7145dcbSDimitry Andric 
2157e7145dcbSDimitry Andric       // So device-only functions are the only things we skip.
2158e7145dcbSDimitry Andric       if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
2159e7145dcbSDimitry Andric           Global->hasAttr<CUDADeviceAttr>())
21606122f3e6SDimitry Andric         return;
2161e7145dcbSDimitry Andric 
2162e7145dcbSDimitry Andric       assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
2163e7145dcbSDimitry Andric              "Expected Variable or Function");
2164e580952dSDimitry Andric     }
2165e580952dSDimitry Andric   }
2166e580952dSDimitry Andric 
2167e7145dcbSDimitry Andric   if (LangOpts.OpenMP) {
2168ea942507SDimitry Andric     // If this is OpenMP device, check if it is legal to emit this global
2169ea942507SDimitry Andric     // normally.
2170ea942507SDimitry Andric     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
2171ea942507SDimitry Andric       return;
2172e7145dcbSDimitry Andric     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
2173e7145dcbSDimitry Andric       if (MustBeEmitted(Global))
2174e7145dcbSDimitry Andric         EmitOMPDeclareReduction(DRD);
2175e7145dcbSDimitry Andric       return;
2176e7145dcbSDimitry Andric     }
2177e7145dcbSDimitry Andric   }
2178ea942507SDimitry Andric 
21796122f3e6SDimitry Andric   // Ignore declarations, they will be emitted on their first use.
218059d1ed5bSDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
2181f22ef01cSRoman Divacky     // Forward declarations are emitted lazily on first use.
21826122f3e6SDimitry Andric     if (!FD->doesThisDeclarationHaveABody()) {
21836122f3e6SDimitry Andric       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
2184f22ef01cSRoman Divacky         return;
21856122f3e6SDimitry Andric 
21866122f3e6SDimitry Andric       StringRef MangledName = getMangledName(GD);
218759d1ed5bSDimitry Andric 
218859d1ed5bSDimitry Andric       // Compute the function info and LLVM type.
218959d1ed5bSDimitry Andric       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
219059d1ed5bSDimitry Andric       llvm::Type *Ty = getTypes().GetFunctionType(FI);
219159d1ed5bSDimitry Andric 
219259d1ed5bSDimitry Andric       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
219359d1ed5bSDimitry Andric                               /*DontDefer=*/false);
21946122f3e6SDimitry Andric       return;
21956122f3e6SDimitry Andric     }
2196f22ef01cSRoman Divacky   } else {
219759d1ed5bSDimitry Andric     const auto *VD = cast<VarDecl>(Global);
2198f22ef01cSRoman Divacky     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
2199*b5893f02SDimitry Andric     if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
2200e7145dcbSDimitry Andric         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
2201*b5893f02SDimitry Andric       if (LangOpts.OpenMP) {
2202*b5893f02SDimitry Andric         // Emit declaration of the must-be-emitted declare target variable.
2203*b5893f02SDimitry Andric         if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2204*b5893f02SDimitry Andric                 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
2205*b5893f02SDimitry Andric           if (*Res == OMPDeclareTargetDeclAttr::MT_To) {
2206*b5893f02SDimitry Andric             (void)GetAddrOfGlobalVar(VD);
2207*b5893f02SDimitry Andric           } else {
2208*b5893f02SDimitry Andric             assert(*Res == OMPDeclareTargetDeclAttr::MT_Link &&
2209*b5893f02SDimitry Andric                    "link claue expected.");
2210*b5893f02SDimitry Andric             (void)getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
2211*b5893f02SDimitry Andric           }
2212*b5893f02SDimitry Andric           return;
2213*b5893f02SDimitry Andric         }
2214*b5893f02SDimitry Andric       }
2215e7145dcbSDimitry Andric       // If this declaration may have caused an inline variable definition to
2216e7145dcbSDimitry Andric       // change linkage, make sure that it's emitted.
2217e7145dcbSDimitry Andric       if (Context.getInlineVariableDefinitionKind(VD) ==
2218e7145dcbSDimitry Andric           ASTContext::InlineVariableDefinitionKind::Strong)
2219e7145dcbSDimitry Andric         GetAddrOfGlobalVar(VD);
2220f22ef01cSRoman Divacky       return;
2221f22ef01cSRoman Divacky     }
2222e7145dcbSDimitry Andric   }
2223f22ef01cSRoman Divacky 
222439d628a0SDimitry Andric   // Defer code generation to first use when possible, e.g. if this is an inline
222539d628a0SDimitry Andric   // function. If the global must always be emitted, do it eagerly if possible
222639d628a0SDimitry Andric   // to benefit from cache locality.
222739d628a0SDimitry Andric   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
2228f22ef01cSRoman Divacky     // Emit the definition if it can't be deferred.
2229f22ef01cSRoman Divacky     EmitGlobalDefinition(GD);
2230f22ef01cSRoman Divacky     return;
2231f22ef01cSRoman Divacky   }
2232f22ef01cSRoman Divacky 
2233e580952dSDimitry Andric   // If we're deferring emission of a C++ variable with an
2234e580952dSDimitry Andric   // initializer, remember the order in which it appeared in the file.
2235dff0c46cSDimitry Andric   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
2236e580952dSDimitry Andric       cast<VarDecl>(Global)->hasInit()) {
2237e580952dSDimitry Andric     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
223859d1ed5bSDimitry Andric     CXXGlobalInits.push_back(nullptr);
2239e580952dSDimitry Andric   }
2240e580952dSDimitry Andric 
22416122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
2242f37b6182SDimitry Andric   if (GetGlobalValue(MangledName) != nullptr) {
224339d628a0SDimitry Andric     // The value has already been used and should therefore be emitted.
2244f37b6182SDimitry Andric     addDeferredDeclToEmit(GD);
224539d628a0SDimitry Andric   } else if (MustBeEmitted(Global)) {
224639d628a0SDimitry Andric     // The value must be emitted, but cannot be emitted eagerly.
224739d628a0SDimitry Andric     assert(!MayBeEmittedEagerly(Global));
2248f37b6182SDimitry Andric     addDeferredDeclToEmit(GD);
224939d628a0SDimitry Andric   } else {
2250f22ef01cSRoman Divacky     // Otherwise, remember that we saw a deferred decl with this name.  The
2251f22ef01cSRoman Divacky     // first use of the mangled name will cause it to move into
2252f22ef01cSRoman Divacky     // DeferredDeclsToEmit.
2253f22ef01cSRoman Divacky     DeferredDecls[MangledName] = GD;
2254f22ef01cSRoman Divacky   }
2255f22ef01cSRoman Divacky }
2256f22ef01cSRoman Divacky 
225720e90f04SDimitry Andric // Check if T is a class type with a destructor that's not dllimport.
HasNonDllImportDtor(QualType T)225820e90f04SDimitry Andric static bool HasNonDllImportDtor(QualType T) {
225920e90f04SDimitry Andric   if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
226020e90f04SDimitry Andric     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
226120e90f04SDimitry Andric       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
226220e90f04SDimitry Andric         return true;
226320e90f04SDimitry Andric 
226420e90f04SDimitry Andric   return false;
226520e90f04SDimitry Andric }
226620e90f04SDimitry Andric 
2267f8254f43SDimitry Andric namespace {
2268f8254f43SDimitry Andric   struct FunctionIsDirectlyRecursive :
2269f8254f43SDimitry Andric     public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
2270f8254f43SDimitry Andric     const StringRef Name;
2271dff0c46cSDimitry Andric     const Builtin::Context &BI;
2272f8254f43SDimitry Andric     bool Result;
FunctionIsDirectlyRecursive__anon8d0e3c080611::FunctionIsDirectlyRecursive2273dff0c46cSDimitry Andric     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
2274dff0c46cSDimitry Andric       Name(N), BI(C), Result(false) {
2275f8254f43SDimitry Andric     }
2276f8254f43SDimitry Andric     typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
2277f8254f43SDimitry Andric 
TraverseCallExpr__anon8d0e3c080611::FunctionIsDirectlyRecursive2278f8254f43SDimitry Andric     bool TraverseCallExpr(CallExpr *E) {
2279dff0c46cSDimitry Andric       const FunctionDecl *FD = E->getDirectCallee();
2280dff0c46cSDimitry Andric       if (!FD)
2281f8254f43SDimitry Andric         return true;
2282dff0c46cSDimitry Andric       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2283dff0c46cSDimitry Andric       if (Attr && Name == Attr->getLabel()) {
2284dff0c46cSDimitry Andric         Result = true;
2285dff0c46cSDimitry Andric         return false;
2286dff0c46cSDimitry Andric       }
2287dff0c46cSDimitry Andric       unsigned BuiltinID = FD->getBuiltinID();
22883dac3a9bSDimitry Andric       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
2289f8254f43SDimitry Andric         return true;
22900623d748SDimitry Andric       StringRef BuiltinName = BI.getName(BuiltinID);
2291dff0c46cSDimitry Andric       if (BuiltinName.startswith("__builtin_") &&
2292dff0c46cSDimitry Andric           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
2293f8254f43SDimitry Andric         Result = true;
2294f8254f43SDimitry Andric         return false;
2295f8254f43SDimitry Andric       }
2296f8254f43SDimitry Andric       return true;
2297f8254f43SDimitry Andric     }
2298f8254f43SDimitry Andric   };
22990623d748SDimitry Andric 
230020e90f04SDimitry Andric   // Make sure we're not referencing non-imported vars or functions.
23010623d748SDimitry Andric   struct DLLImportFunctionVisitor
23020623d748SDimitry Andric       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
23030623d748SDimitry Andric     bool SafeToInline = true;
23040623d748SDimitry Andric 
shouldVisitImplicitCode__anon8d0e3c080611::DLLImportFunctionVisitor230544290647SDimitry Andric     bool shouldVisitImplicitCode() const { return true; }
230644290647SDimitry Andric 
VisitVarDecl__anon8d0e3c080611::DLLImportFunctionVisitor23070623d748SDimitry Andric     bool VisitVarDecl(VarDecl *VD) {
230820e90f04SDimitry Andric       if (VD->getTLSKind()) {
23090623d748SDimitry Andric         // A thread-local variable cannot be imported.
231020e90f04SDimitry Andric         SafeToInline = false;
23110623d748SDimitry Andric         return SafeToInline;
23120623d748SDimitry Andric       }
23130623d748SDimitry Andric 
231420e90f04SDimitry Andric       // A variable definition might imply a destructor call.
231520e90f04SDimitry Andric       if (VD->isThisDeclarationADefinition())
231620e90f04SDimitry Andric         SafeToInline = !HasNonDllImportDtor(VD->getType());
231720e90f04SDimitry Andric 
231820e90f04SDimitry Andric       return SafeToInline;
231920e90f04SDimitry Andric     }
232020e90f04SDimitry Andric 
VisitCXXBindTemporaryExpr__anon8d0e3c080611::DLLImportFunctionVisitor232120e90f04SDimitry Andric     bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
232220e90f04SDimitry Andric       if (const auto *D = E->getTemporary()->getDestructor())
232320e90f04SDimitry Andric         SafeToInline = D->hasAttr<DLLImportAttr>();
232420e90f04SDimitry Andric       return SafeToInline;
232520e90f04SDimitry Andric     }
232620e90f04SDimitry Andric 
VisitDeclRefExpr__anon8d0e3c080611::DLLImportFunctionVisitor23270623d748SDimitry Andric     bool VisitDeclRefExpr(DeclRefExpr *E) {
23280623d748SDimitry Andric       ValueDecl *VD = E->getDecl();
23290623d748SDimitry Andric       if (isa<FunctionDecl>(VD))
23300623d748SDimitry Andric         SafeToInline = VD->hasAttr<DLLImportAttr>();
23310623d748SDimitry Andric       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
23320623d748SDimitry Andric         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
23330623d748SDimitry Andric       return SafeToInline;
23340623d748SDimitry Andric     }
233520e90f04SDimitry Andric 
VisitCXXConstructExpr__anon8d0e3c080611::DLLImportFunctionVisitor233644290647SDimitry Andric     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
233744290647SDimitry Andric       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
233844290647SDimitry Andric       return SafeToInline;
233944290647SDimitry Andric     }
234020e90f04SDimitry Andric 
VisitCXXMemberCallExpr__anon8d0e3c080611::DLLImportFunctionVisitor234120e90f04SDimitry Andric     bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
234220e90f04SDimitry Andric       CXXMethodDecl *M = E->getMethodDecl();
234320e90f04SDimitry Andric       if (!M) {
234420e90f04SDimitry Andric         // Call through a pointer to member function. This is safe to inline.
234520e90f04SDimitry Andric         SafeToInline = true;
234620e90f04SDimitry Andric       } else {
234720e90f04SDimitry Andric         SafeToInline = M->hasAttr<DLLImportAttr>();
234820e90f04SDimitry Andric       }
234920e90f04SDimitry Andric       return SafeToInline;
235020e90f04SDimitry Andric     }
235120e90f04SDimitry Andric 
VisitCXXDeleteExpr__anon8d0e3c080611::DLLImportFunctionVisitor23520623d748SDimitry Andric     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
23530623d748SDimitry Andric       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
23540623d748SDimitry Andric       return SafeToInline;
23550623d748SDimitry Andric     }
235620e90f04SDimitry Andric 
VisitCXXNewExpr__anon8d0e3c080611::DLLImportFunctionVisitor23570623d748SDimitry Andric     bool VisitCXXNewExpr(CXXNewExpr *E) {
23580623d748SDimitry Andric       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
23590623d748SDimitry Andric       return SafeToInline;
23600623d748SDimitry Andric     }
23610623d748SDimitry Andric   };
2362f8254f43SDimitry Andric }
2363f8254f43SDimitry Andric 
2364dff0c46cSDimitry Andric // isTriviallyRecursive - Check if this function calls another
2365dff0c46cSDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin,
2366dff0c46cSDimitry Andric // ends up pointing to itself.
2367f8254f43SDimitry Andric bool
isTriviallyRecursive(const FunctionDecl * FD)2368dff0c46cSDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
2369dff0c46cSDimitry Andric   StringRef Name;
2370dff0c46cSDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
2371dff0c46cSDimitry Andric     // asm labels are a special kind of mangling we have to support.
2372dff0c46cSDimitry Andric     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2373dff0c46cSDimitry Andric     if (!Attr)
2374f8254f43SDimitry Andric       return false;
2375dff0c46cSDimitry Andric     Name = Attr->getLabel();
2376dff0c46cSDimitry Andric   } else {
2377dff0c46cSDimitry Andric     Name = FD->getName();
2378dff0c46cSDimitry Andric   }
2379f8254f43SDimitry Andric 
2380dff0c46cSDimitry Andric   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
2381dff0c46cSDimitry Andric   Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
2382f8254f43SDimitry Andric   return Walker.Result;
2383f8254f43SDimitry Andric }
2384f8254f43SDimitry Andric 
shouldEmitFunction(GlobalDecl GD)238544290647SDimitry Andric bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
2386f785676fSDimitry Andric   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
2387f8254f43SDimitry Andric     return true;
238859d1ed5bSDimitry Andric   const auto *F = cast<FunctionDecl>(GD.getDecl());
238959d1ed5bSDimitry Andric   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
2390f8254f43SDimitry Andric     return false;
23910623d748SDimitry Andric 
23920623d748SDimitry Andric   if (F->hasAttr<DLLImportAttr>()) {
23930623d748SDimitry Andric     // Check whether it would be safe to inline this dllimport function.
23940623d748SDimitry Andric     DLLImportFunctionVisitor Visitor;
23950623d748SDimitry Andric     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
23960623d748SDimitry Andric     if (!Visitor.SafeToInline)
23970623d748SDimitry Andric       return false;
239844290647SDimitry Andric 
239944290647SDimitry Andric     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
240044290647SDimitry Andric       // Implicit destructor invocations aren't captured in the AST, so the
240144290647SDimitry Andric       // check above can't see them. Check for them manually here.
240244290647SDimitry Andric       for (const Decl *Member : Dtor->getParent()->decls())
240344290647SDimitry Andric         if (isa<FieldDecl>(Member))
240444290647SDimitry Andric           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
240544290647SDimitry Andric             return false;
240644290647SDimitry Andric       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
240744290647SDimitry Andric         if (HasNonDllImportDtor(B.getType()))
240844290647SDimitry Andric           return false;
240944290647SDimitry Andric     }
24100623d748SDimitry Andric   }
24110623d748SDimitry Andric 
2412f8254f43SDimitry Andric   // PR9614. Avoid cases where the source code is lying to us. An available
2413f8254f43SDimitry Andric   // externally function should have an equivalent function somewhere else,
2414f8254f43SDimitry Andric   // but a function that calls itself is clearly not equivalent to the real
2415f8254f43SDimitry Andric   // implementation.
2416f8254f43SDimitry Andric   // This happens in glibc's btowc and in some configure checks.
2417dff0c46cSDimitry Andric   return !isTriviallyRecursive(F);
2418f8254f43SDimitry Andric }
2419f8254f43SDimitry Andric 
shouldOpportunisticallyEmitVTables()2420f9448bf3SDimitry Andric bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
2421f9448bf3SDimitry Andric   return CodeGenOpts.OptimizationLevel > 0;
2422f9448bf3SDimitry Andric }
2423f9448bf3SDimitry Andric 
EmitMultiVersionFunctionDefinition(GlobalDecl GD,llvm::GlobalValue * GV)2424*b5893f02SDimitry Andric void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
2425*b5893f02SDimitry Andric                                                        llvm::GlobalValue *GV) {
2426*b5893f02SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
2427*b5893f02SDimitry Andric 
2428*b5893f02SDimitry Andric   if (FD->isCPUSpecificMultiVersion()) {
2429*b5893f02SDimitry Andric     auto *Spec = FD->getAttr<CPUSpecificAttr>();
2430*b5893f02SDimitry Andric     for (unsigned I = 0; I < Spec->cpus_size(); ++I)
2431*b5893f02SDimitry Andric       EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
2432*b5893f02SDimitry Andric     // Requires multiple emits.
2433*b5893f02SDimitry Andric   } else
2434*b5893f02SDimitry Andric     EmitGlobalFunctionDefinition(GD, GV);
2435*b5893f02SDimitry Andric }
2436*b5893f02SDimitry Andric 
EmitGlobalDefinition(GlobalDecl GD,llvm::GlobalValue * GV)243759d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
243859d1ed5bSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
2439f22ef01cSRoman Divacky 
2440f22ef01cSRoman Divacky   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
2441f22ef01cSRoman Divacky                                  Context.getSourceManager(),
2442f22ef01cSRoman Divacky                                  "Generating code for declaration");
2443f22ef01cSRoman Divacky 
2444*b5893f02SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2445ffd1746dSEd Schouten     // At -O0, don't generate IR for functions with available_externally
2446ffd1746dSEd Schouten     // linkage.
2447f785676fSDimitry Andric     if (!shouldEmitFunction(GD))
2448ffd1746dSEd Schouten       return;
2449ffd1746dSEd Schouten 
245059d1ed5bSDimitry Andric     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
2451bd5abe19SDimitry Andric       // Make sure to emit the definition(s) before we emit the thunks.
2452bd5abe19SDimitry Andric       // This is necessary for the generation of certain thunks.
245359d1ed5bSDimitry Andric       if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
245439d628a0SDimitry Andric         ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
245559d1ed5bSDimitry Andric       else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
245639d628a0SDimitry Andric         ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
2457*b5893f02SDimitry Andric       else if (FD->isMultiVersion())
2458*b5893f02SDimitry Andric         EmitMultiVersionFunctionDefinition(GD, GV);
2459bd5abe19SDimitry Andric       else
246059d1ed5bSDimitry Andric         EmitGlobalFunctionDefinition(GD, GV);
2461bd5abe19SDimitry Andric 
2462f22ef01cSRoman Divacky       if (Method->isVirtual())
2463f22ef01cSRoman Divacky         getVTables().EmitThunks(GD);
2464f22ef01cSRoman Divacky 
2465bd5abe19SDimitry Andric       return;
2466ffd1746dSEd Schouten     }
2467f22ef01cSRoman Divacky 
2468*b5893f02SDimitry Andric     if (FD->isMultiVersion())
2469*b5893f02SDimitry Andric       return EmitMultiVersionFunctionDefinition(GD, GV);
247059d1ed5bSDimitry Andric     return EmitGlobalFunctionDefinition(GD, GV);
2471ffd1746dSEd Schouten   }
2472f22ef01cSRoman Divacky 
247359d1ed5bSDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
2474e7145dcbSDimitry Andric     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
2475f22ef01cSRoman Divacky 
24766122f3e6SDimitry Andric   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
2477f22ef01cSRoman Divacky }
2478f22ef01cSRoman Divacky 
24790623d748SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
24800623d748SDimitry Andric                                                       llvm::Function *NewFn);
24810623d748SDimitry Andric 
24824ba319b5SDimitry Andric static unsigned
TargetMVPriority(const TargetInfo & TI,const CodeGenFunction::MultiVersionResolverOption & RO)24834ba319b5SDimitry Andric TargetMVPriority(const TargetInfo &TI,
24844ba319b5SDimitry Andric                  const CodeGenFunction::MultiVersionResolverOption &RO) {
24854ba319b5SDimitry Andric   unsigned Priority = 0;
24864ba319b5SDimitry Andric   for (StringRef Feat : RO.Conditions.Features)
24874ba319b5SDimitry Andric     Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
24884ba319b5SDimitry Andric 
24894ba319b5SDimitry Andric   if (!RO.Conditions.Architecture.empty())
24904ba319b5SDimitry Andric     Priority = std::max(
24914ba319b5SDimitry Andric         Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
24924ba319b5SDimitry Andric   return Priority;
24934ba319b5SDimitry Andric }
24944ba319b5SDimitry Andric 
emitMultiVersionFunctions()24954ba319b5SDimitry Andric void CodeGenModule::emitMultiVersionFunctions() {
24964ba319b5SDimitry Andric   for (GlobalDecl GD : MultiVersionFuncs) {
24974ba319b5SDimitry Andric     SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
24984ba319b5SDimitry Andric     const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
24994ba319b5SDimitry Andric     getContext().forEachMultiversionedFunctionVersion(
25004ba319b5SDimitry Andric         FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
25014ba319b5SDimitry Andric           GlobalDecl CurGD{
25024ba319b5SDimitry Andric               (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
25034ba319b5SDimitry Andric           StringRef MangledName = getMangledName(CurGD);
25044ba319b5SDimitry Andric           llvm::Constant *Func = GetGlobalValue(MangledName);
25054ba319b5SDimitry Andric           if (!Func) {
25064ba319b5SDimitry Andric             if (CurFD->isDefined()) {
25074ba319b5SDimitry Andric               EmitGlobalFunctionDefinition(CurGD, nullptr);
25084ba319b5SDimitry Andric               Func = GetGlobalValue(MangledName);
25094ba319b5SDimitry Andric             } else {
25104ba319b5SDimitry Andric               const CGFunctionInfo &FI =
25114ba319b5SDimitry Andric                   getTypes().arrangeGlobalDeclaration(GD);
25124ba319b5SDimitry Andric               llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
25134ba319b5SDimitry Andric               Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
25144ba319b5SDimitry Andric                                        /*DontDefer=*/false, ForDefinition);
25154ba319b5SDimitry Andric             }
25164ba319b5SDimitry Andric             assert(Func && "This should have just been created");
25174ba319b5SDimitry Andric           }
25184ba319b5SDimitry Andric 
25194ba319b5SDimitry Andric           const auto *TA = CurFD->getAttr<TargetAttr>();
25204ba319b5SDimitry Andric           llvm::SmallVector<StringRef, 8> Feats;
25214ba319b5SDimitry Andric           TA->getAddedFeatures(Feats);
25224ba319b5SDimitry Andric 
25234ba319b5SDimitry Andric           Options.emplace_back(cast<llvm::Function>(Func),
25244ba319b5SDimitry Andric                                TA->getArchitecture(), Feats);
25254ba319b5SDimitry Andric         });
25264ba319b5SDimitry Andric 
2527*b5893f02SDimitry Andric     llvm::Function *ResolverFunc;
2528*b5893f02SDimitry Andric     const TargetInfo &TI = getTarget();
2529*b5893f02SDimitry Andric 
2530*b5893f02SDimitry Andric     if (TI.supportsIFunc() || FD->isTargetMultiVersion())
2531*b5893f02SDimitry Andric       ResolverFunc = cast<llvm::Function>(
25324ba319b5SDimitry Andric           GetGlobalValue((getMangledName(GD) + ".resolver").str()));
2533*b5893f02SDimitry Andric     else
2534*b5893f02SDimitry Andric       ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD)));
2535*b5893f02SDimitry Andric 
25364ba319b5SDimitry Andric     if (supportsCOMDAT())
25374ba319b5SDimitry Andric       ResolverFunc->setComdat(
25384ba319b5SDimitry Andric           getModule().getOrInsertComdat(ResolverFunc->getName()));
25394ba319b5SDimitry Andric 
25404ba319b5SDimitry Andric     std::stable_sort(
25414ba319b5SDimitry Andric         Options.begin(), Options.end(),
25424ba319b5SDimitry Andric         [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
25434ba319b5SDimitry Andric               const CodeGenFunction::MultiVersionResolverOption &RHS) {
25444ba319b5SDimitry Andric           return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
25454ba319b5SDimitry Andric         });
25464ba319b5SDimitry Andric     CodeGenFunction CGF(*this);
25474ba319b5SDimitry Andric     CGF.EmitMultiVersionResolver(ResolverFunc, Options);
25484ba319b5SDimitry Andric   }
25494ba319b5SDimitry Andric }
25504ba319b5SDimitry Andric 
emitCPUDispatchDefinition(GlobalDecl GD)25514ba319b5SDimitry Andric void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
25524ba319b5SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
25534ba319b5SDimitry Andric   assert(FD && "Not a FunctionDecl?");
25544ba319b5SDimitry Andric   const auto *DD = FD->getAttr<CPUDispatchAttr>();
25554ba319b5SDimitry Andric   assert(DD && "Not a cpu_dispatch Function?");
25564ba319b5SDimitry Andric   QualType CanonTy = Context.getCanonicalType(FD->getType());
25574ba319b5SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertFunctionType(CanonTy, FD);
25584ba319b5SDimitry Andric 
25594ba319b5SDimitry Andric   if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
25604ba319b5SDimitry Andric     const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD);
25614ba319b5SDimitry Andric     DeclTy = getTypes().GetFunctionType(FInfo);
25624ba319b5SDimitry Andric   }
25634ba319b5SDimitry Andric 
25644ba319b5SDimitry Andric   StringRef ResolverName = getMangledName(GD);
2565*b5893f02SDimitry Andric 
2566*b5893f02SDimitry Andric   llvm::Type *ResolverType;
2567*b5893f02SDimitry Andric   GlobalDecl ResolverGD;
2568*b5893f02SDimitry Andric   if (getTarget().supportsIFunc())
2569*b5893f02SDimitry Andric     ResolverType = llvm::FunctionType::get(
25704ba319b5SDimitry Andric         llvm::PointerType::get(DeclTy,
25714ba319b5SDimitry Andric                                Context.getTargetAddressSpace(FD->getType())),
25724ba319b5SDimitry Andric         false);
2573*b5893f02SDimitry Andric   else {
2574*b5893f02SDimitry Andric     ResolverType = DeclTy;
2575*b5893f02SDimitry Andric     ResolverGD = GD;
2576*b5893f02SDimitry Andric   }
2577*b5893f02SDimitry Andric 
2578*b5893f02SDimitry Andric   auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
2579*b5893f02SDimitry Andric       ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
25804ba319b5SDimitry Andric 
25814ba319b5SDimitry Andric   SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
25824ba319b5SDimitry Andric   const TargetInfo &Target = getTarget();
2583*b5893f02SDimitry Andric   unsigned Index = 0;
25844ba319b5SDimitry Andric   for (const IdentifierInfo *II : DD->cpus()) {
25854ba319b5SDimitry Andric     // Get the name of the target function so we can look it up/create it.
25864ba319b5SDimitry Andric     std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
25874ba319b5SDimitry Andric                               getCPUSpecificMangling(*this, II->getName());
2588*b5893f02SDimitry Andric 
2589*b5893f02SDimitry Andric     llvm::Constant *Func = GetGlobalValue(MangledName);
2590*b5893f02SDimitry Andric 
2591*b5893f02SDimitry Andric     if (!Func) {
2592*b5893f02SDimitry Andric       GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
2593*b5893f02SDimitry Andric       if (ExistingDecl.getDecl() &&
2594*b5893f02SDimitry Andric           ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
2595*b5893f02SDimitry Andric         EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
2596*b5893f02SDimitry Andric         Func = GetGlobalValue(MangledName);
2597*b5893f02SDimitry Andric       } else {
2598*b5893f02SDimitry Andric         if (!ExistingDecl.getDecl())
2599*b5893f02SDimitry Andric           ExistingDecl = GD.getWithMultiVersionIndex(Index);
2600*b5893f02SDimitry Andric 
2601*b5893f02SDimitry Andric       Func = GetOrCreateLLVMFunction(
2602*b5893f02SDimitry Andric           MangledName, DeclTy, ExistingDecl,
2603*b5893f02SDimitry Andric           /*ForVTable=*/false, /*DontDefer=*/true,
26044ba319b5SDimitry Andric           /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
2605*b5893f02SDimitry Andric       }
2606*b5893f02SDimitry Andric     }
2607*b5893f02SDimitry Andric 
26084ba319b5SDimitry Andric     llvm::SmallVector<StringRef, 32> Features;
26094ba319b5SDimitry Andric     Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
26104ba319b5SDimitry Andric     llvm::transform(Features, Features.begin(),
26114ba319b5SDimitry Andric                     [](StringRef Str) { return Str.substr(1); });
26124ba319b5SDimitry Andric     Features.erase(std::remove_if(
26134ba319b5SDimitry Andric         Features.begin(), Features.end(), [&Target](StringRef Feat) {
26144ba319b5SDimitry Andric           return !Target.validateCpuSupports(Feat);
26154ba319b5SDimitry Andric         }), Features.end());
26164ba319b5SDimitry Andric     Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
2617*b5893f02SDimitry Andric     ++Index;
26184ba319b5SDimitry Andric   }
26194ba319b5SDimitry Andric 
26204ba319b5SDimitry Andric   llvm::sort(
2621*b5893f02SDimitry Andric       Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
26224ba319b5SDimitry Andric                   const CodeGenFunction::MultiVersionResolverOption &RHS) {
26234ba319b5SDimitry Andric         return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) >
26244ba319b5SDimitry Andric                CodeGenFunction::GetX86CpuSupportsMask(RHS.Conditions.Features);
26254ba319b5SDimitry Andric       });
26264ba319b5SDimitry Andric 
26274ba319b5SDimitry Andric   // If the list contains multiple 'default' versions, such as when it contains
26284ba319b5SDimitry Andric   // 'pentium' and 'generic', don't emit the call to the generic one (since we
26294ba319b5SDimitry Andric   // always run on at least a 'pentium'). We do this by deleting the 'least
26304ba319b5SDimitry Andric   // advanced' (read, lowest mangling letter).
26314ba319b5SDimitry Andric   while (Options.size() > 1 &&
26324ba319b5SDimitry Andric          CodeGenFunction::GetX86CpuSupportsMask(
26334ba319b5SDimitry Andric              (Options.end() - 2)->Conditions.Features) == 0) {
26344ba319b5SDimitry Andric     StringRef LHSName = (Options.end() - 2)->Function->getName();
26354ba319b5SDimitry Andric     StringRef RHSName = (Options.end() - 1)->Function->getName();
26364ba319b5SDimitry Andric     if (LHSName.compare(RHSName) < 0)
26374ba319b5SDimitry Andric       Options.erase(Options.end() - 2);
26384ba319b5SDimitry Andric     else
26394ba319b5SDimitry Andric       Options.erase(Options.end() - 1);
26404ba319b5SDimitry Andric   }
26414ba319b5SDimitry Andric 
26424ba319b5SDimitry Andric   CodeGenFunction CGF(*this);
26434ba319b5SDimitry Andric   CGF.EmitMultiVersionResolver(ResolverFunc, Options);
26444ba319b5SDimitry Andric }
26454ba319b5SDimitry Andric 
2646*b5893f02SDimitry Andric /// If a dispatcher for the specified mangled name is not in the module, create
2647*b5893f02SDimitry Andric /// and return an llvm Function with the specified type.
GetOrCreateMultiVersionResolver(GlobalDecl GD,llvm::Type * DeclTy,const FunctionDecl * FD)2648*b5893f02SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
2649*b5893f02SDimitry Andric     GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) {
26504ba319b5SDimitry Andric   std::string MangledName =
26514ba319b5SDimitry Andric       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
2652*b5893f02SDimitry Andric 
2653*b5893f02SDimitry Andric   // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
2654*b5893f02SDimitry Andric   // a separate resolver).
2655*b5893f02SDimitry Andric   std::string ResolverName = MangledName;
2656*b5893f02SDimitry Andric   if (getTarget().supportsIFunc())
2657*b5893f02SDimitry Andric     ResolverName += ".ifunc";
2658*b5893f02SDimitry Andric   else if (FD->isTargetMultiVersion())
2659*b5893f02SDimitry Andric     ResolverName += ".resolver";
2660*b5893f02SDimitry Andric 
2661*b5893f02SDimitry Andric   // If this already exists, just return that one.
2662*b5893f02SDimitry Andric   if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
2663*b5893f02SDimitry Andric     return ResolverGV;
26644ba319b5SDimitry Andric 
26654ba319b5SDimitry Andric   // Since this is the first time we've created this IFunc, make sure
26664ba319b5SDimitry Andric   // that we put this multiversioned function into the list to be
26674ba319b5SDimitry Andric   // replaced later if necessary (target multiversioning only).
26684ba319b5SDimitry Andric   if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion())
26694ba319b5SDimitry Andric     MultiVersionFuncs.push_back(GD);
26704ba319b5SDimitry Andric 
2671*b5893f02SDimitry Andric   if (getTarget().supportsIFunc()) {
26724ba319b5SDimitry Andric     llvm::Type *ResolverType = llvm::FunctionType::get(
2673*b5893f02SDimitry Andric         llvm::PointerType::get(
2674*b5893f02SDimitry Andric             DeclTy, getContext().getTargetAddressSpace(FD->getType())),
26754ba319b5SDimitry Andric         false);
2676*b5893f02SDimitry Andric     llvm::Constant *Resolver = GetOrCreateLLVMFunction(
2677*b5893f02SDimitry Andric         MangledName + ".resolver", ResolverType, GlobalDecl{},
26784ba319b5SDimitry Andric         /*ForVTable=*/false);
26794ba319b5SDimitry Andric     llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
26804ba319b5SDimitry Andric         DeclTy, 0, llvm::Function::ExternalLinkage, "", Resolver, &getModule());
2681*b5893f02SDimitry Andric     GIF->setName(ResolverName);
26824ba319b5SDimitry Andric     SetCommonAttributes(FD, GIF);
26834ba319b5SDimitry Andric 
26844ba319b5SDimitry Andric     return GIF;
26854ba319b5SDimitry Andric   }
26864ba319b5SDimitry Andric 
2687*b5893f02SDimitry Andric   llvm::Constant *Resolver = GetOrCreateLLVMFunction(
2688*b5893f02SDimitry Andric       ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
2689*b5893f02SDimitry Andric   assert(isa<llvm::GlobalValue>(Resolver) &&
2690*b5893f02SDimitry Andric          "Resolver should be created for the first time");
2691*b5893f02SDimitry Andric   SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
2692*b5893f02SDimitry Andric   return Resolver;
2693*b5893f02SDimitry Andric }
2694*b5893f02SDimitry Andric 
2695f22ef01cSRoman Divacky /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
2696f22ef01cSRoman Divacky /// module, create and return an llvm Function with the specified type. If there
2697f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially
2698f22ef01cSRoman Divacky /// bitcasted to the right type.
2699f22ef01cSRoman Divacky ///
2700f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this.  This is used
2701f22ef01cSRoman Divacky /// to set the attributes on the function when it is first created.
GetOrCreateLLVMFunction(StringRef MangledName,llvm::Type * Ty,GlobalDecl GD,bool ForVTable,bool DontDefer,bool IsThunk,llvm::AttributeList ExtraAttrs,ForDefinition_t IsForDefinition)270220e90f04SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
270320e90f04SDimitry Andric     StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
270420e90f04SDimitry Andric     bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
270544290647SDimitry Andric     ForDefinition_t IsForDefinition) {
2706f785676fSDimitry Andric   const Decl *D = GD.getDecl();
2707f785676fSDimitry Andric 
27084ba319b5SDimitry Andric   // Any attempts to use a MultiVersion function should result in retrieving
27094ba319b5SDimitry Andric   // the iFunc instead. Name Mangling will handle the rest of the changes.
27104ba319b5SDimitry Andric   if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
27114ba319b5SDimitry Andric     // For the device mark the function as one that should be emitted.
27124ba319b5SDimitry Andric     if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
27134ba319b5SDimitry Andric         !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
27144ba319b5SDimitry Andric         !DontDefer && !IsForDefinition) {
2715*b5893f02SDimitry Andric       if (const FunctionDecl *FDDef = FD->getDefinition()) {
27164ba319b5SDimitry Andric         GlobalDecl GDDef;
27174ba319b5SDimitry Andric         if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
27184ba319b5SDimitry Andric           GDDef = GlobalDecl(CD, GD.getCtorType());
27194ba319b5SDimitry Andric         else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
27204ba319b5SDimitry Andric           GDDef = GlobalDecl(DD, GD.getDtorType());
27214ba319b5SDimitry Andric         else
27224ba319b5SDimitry Andric           GDDef = GlobalDecl(FDDef);
2723*b5893f02SDimitry Andric         EmitGlobal(GDDef);
27244ba319b5SDimitry Andric       }
27254ba319b5SDimitry Andric     }
27264ba319b5SDimitry Andric 
27274ba319b5SDimitry Andric     if (FD->isMultiVersion()) {
27284ba319b5SDimitry Andric       const auto *TA = FD->getAttr<TargetAttr>();
27294ba319b5SDimitry Andric       if (TA && TA->isDefaultVersion())
27304ba319b5SDimitry Andric         UpdateMultiVersionNames(GD, FD);
27314ba319b5SDimitry Andric       if (!IsForDefinition)
2732*b5893f02SDimitry Andric         return GetOrCreateMultiVersionResolver(GD, Ty, FD);
27334ba319b5SDimitry Andric     }
27344ba319b5SDimitry Andric   }
27354ba319b5SDimitry Andric 
2736f22ef01cSRoman Divacky   // Lookup the entry, lazily creating it if necessary.
2737f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2738f22ef01cSRoman Divacky   if (Entry) {
27393861d79fSDimitry Andric     if (WeakRefReferences.erase(Entry)) {
2740f785676fSDimitry Andric       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
2741f22ef01cSRoman Divacky       if (FD && !FD->hasAttr<WeakAttr>())
2742f22ef01cSRoman Divacky         Entry->setLinkage(llvm::Function::ExternalLinkage);
2743f22ef01cSRoman Divacky     }
2744f22ef01cSRoman Divacky 
274539d628a0SDimitry Andric     // Handle dropped DLL attributes.
27464ba319b5SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
274739d628a0SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
27484ba319b5SDimitry Andric       setDSOLocal(Entry);
27494ba319b5SDimitry Andric     }
275039d628a0SDimitry Andric 
27510623d748SDimitry Andric     // If there are two attempts to define the same mangled name, issue an
27520623d748SDimitry Andric     // error.
27530623d748SDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
27540623d748SDimitry Andric       GlobalDecl OtherGD;
2755e7145dcbSDimitry Andric       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
2756e7145dcbSDimitry Andric       // to make sure that we issue an error only once.
27570623d748SDimitry Andric       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
27580623d748SDimitry Andric           (GD.getCanonicalDecl().getDecl() !=
27590623d748SDimitry Andric            OtherGD.getCanonicalDecl().getDecl()) &&
27600623d748SDimitry Andric           DiagnosedConflictingDefinitions.insert(GD).second) {
27614ba319b5SDimitry Andric         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
27624ba319b5SDimitry Andric             << MangledName;
27630623d748SDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
27640623d748SDimitry Andric                           diag::note_previous_definition);
27650623d748SDimitry Andric       }
27660623d748SDimitry Andric     }
27670623d748SDimitry Andric 
27680623d748SDimitry Andric     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
27690623d748SDimitry Andric         (Entry->getType()->getElementType() == Ty)) {
2770f22ef01cSRoman Divacky       return Entry;
27710623d748SDimitry Andric     }
2772f22ef01cSRoman Divacky 
2773f22ef01cSRoman Divacky     // Make sure the result is of the correct type.
27740623d748SDimitry Andric     // (If function is requested for a definition, we always need to create a new
27750623d748SDimitry Andric     // function, not just return a bitcast.)
27760623d748SDimitry Andric     if (!IsForDefinition)
277717a519f9SDimitry Andric       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
2778f22ef01cSRoman Divacky   }
2779f22ef01cSRoman Divacky 
2780f22ef01cSRoman Divacky   // This function doesn't have a complete type (for example, the return
2781f22ef01cSRoman Divacky   // type is an incomplete struct). Use a fake type instead, and make
2782f22ef01cSRoman Divacky   // sure not to try to set attributes.
2783f22ef01cSRoman Divacky   bool IsIncompleteFunction = false;
2784f22ef01cSRoman Divacky 
27856122f3e6SDimitry Andric   llvm::FunctionType *FTy;
2786f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(Ty)) {
2787f22ef01cSRoman Divacky     FTy = cast<llvm::FunctionType>(Ty);
2788f22ef01cSRoman Divacky   } else {
2789bd5abe19SDimitry Andric     FTy = llvm::FunctionType::get(VoidTy, false);
2790f22ef01cSRoman Divacky     IsIncompleteFunction = true;
2791f22ef01cSRoman Divacky   }
2792ffd1746dSEd Schouten 
27930623d748SDimitry Andric   llvm::Function *F =
27940623d748SDimitry Andric       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
27950623d748SDimitry Andric                              Entry ? StringRef() : MangledName, &getModule());
27960623d748SDimitry Andric 
27970623d748SDimitry Andric   // If we already created a function with the same mangled name (but different
27980623d748SDimitry Andric   // type) before, take its name and add it to the list of functions to be
27990623d748SDimitry Andric   // replaced with F at the end of CodeGen.
28000623d748SDimitry Andric   //
28010623d748SDimitry Andric   // This happens if there is a prototype for a function (e.g. "int f()") and
28020623d748SDimitry Andric   // then a definition of a different type (e.g. "int f(int x)").
28030623d748SDimitry Andric   if (Entry) {
28040623d748SDimitry Andric     F->takeName(Entry);
28050623d748SDimitry Andric 
28060623d748SDimitry Andric     // This might be an implementation of a function without a prototype, in
28070623d748SDimitry Andric     // which case, try to do special replacement of calls which match the new
28080623d748SDimitry Andric     // prototype.  The really key thing here is that we also potentially drop
28090623d748SDimitry Andric     // arguments from the call site so as to make a direct call, which makes the
28100623d748SDimitry Andric     // inliner happier and suppresses a number of optimizer warnings (!) about
28110623d748SDimitry Andric     // dropping arguments.
28120623d748SDimitry Andric     if (!Entry->use_empty()) {
28130623d748SDimitry Andric       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
28140623d748SDimitry Andric       Entry->removeDeadConstantUsers();
28150623d748SDimitry Andric     }
28160623d748SDimitry Andric 
28170623d748SDimitry Andric     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
28180623d748SDimitry Andric         F, Entry->getType()->getElementType()->getPointerTo());
28190623d748SDimitry Andric     addGlobalValReplacement(Entry, BC);
28200623d748SDimitry Andric   }
28210623d748SDimitry Andric 
2822f22ef01cSRoman Divacky   assert(F->getName() == MangledName && "name was uniqued!");
2823f785676fSDimitry Andric   if (D)
28244ba319b5SDimitry Andric     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
282520e90f04SDimitry Andric   if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
282620e90f04SDimitry Andric     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
2827f37b6182SDimitry Andric     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
2828139f7f9bSDimitry Andric   }
2829f22ef01cSRoman Divacky 
283059d1ed5bSDimitry Andric   if (!DontDefer) {
283159d1ed5bSDimitry Andric     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
283259d1ed5bSDimitry Andric     // each other bottoming out with the base dtor.  Therefore we emit non-base
283359d1ed5bSDimitry Andric     // dtors on usage, even if there is no dtor definition in the TU.
283459d1ed5bSDimitry Andric     if (D && isa<CXXDestructorDecl>(D) &&
283559d1ed5bSDimitry Andric         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
283659d1ed5bSDimitry Andric                                            GD.getDtorType()))
2837f37b6182SDimitry Andric       addDeferredDeclToEmit(GD);
283859d1ed5bSDimitry Andric 
2839f22ef01cSRoman Divacky     // This is the first use or definition of a mangled name.  If there is a
2840f22ef01cSRoman Divacky     // deferred decl with this name, remember that we need to emit it at the end
2841f22ef01cSRoman Divacky     // of the file.
284259d1ed5bSDimitry Andric     auto DDI = DeferredDecls.find(MangledName);
2843f22ef01cSRoman Divacky     if (DDI != DeferredDecls.end()) {
284459d1ed5bSDimitry Andric       // Move the potentially referenced deferred decl to the
284559d1ed5bSDimitry Andric       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
284659d1ed5bSDimitry Andric       // don't need it anymore).
2847f37b6182SDimitry Andric       addDeferredDeclToEmit(DDI->second);
2848f22ef01cSRoman Divacky       DeferredDecls.erase(DDI);
28492754fe60SDimitry Andric 
28502754fe60SDimitry Andric       // Otherwise, there are cases we have to worry about where we're
28512754fe60SDimitry Andric       // using a declaration for which we must emit a definition but where
28522754fe60SDimitry Andric       // we might not find a top-level definition:
28532754fe60SDimitry Andric       //   - member functions defined inline in their classes
28542754fe60SDimitry Andric       //   - friend functions defined inline in some class
28552754fe60SDimitry Andric       //   - special member functions with implicit definitions
28562754fe60SDimitry Andric       // If we ever change our AST traversal to walk into class methods,
28572754fe60SDimitry Andric       // this will be unnecessary.
28582754fe60SDimitry Andric       //
285959d1ed5bSDimitry Andric       // We also don't emit a definition for a function if it's going to be an
286039d628a0SDimitry Andric       // entry in a vtable, unless it's already marked as used.
2861f785676fSDimitry Andric     } else if (getLangOpts().CPlusPlus && D) {
28622754fe60SDimitry Andric       // Look for a declaration that's lexically in a record.
286339d628a0SDimitry Andric       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
286439d628a0SDimitry Andric            FD = FD->getPreviousDecl()) {
28652754fe60SDimitry Andric         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
286639d628a0SDimitry Andric           if (FD->doesThisDeclarationHaveABody()) {
2867f37b6182SDimitry Andric             addDeferredDeclToEmit(GD.getWithDecl(FD));
28682754fe60SDimitry Andric             break;
2869f22ef01cSRoman Divacky           }
2870f22ef01cSRoman Divacky         }
287139d628a0SDimitry Andric       }
2872f22ef01cSRoman Divacky     }
287359d1ed5bSDimitry Andric   }
2874f22ef01cSRoman Divacky 
2875f22ef01cSRoman Divacky   // Make sure the result is of the requested type.
2876f22ef01cSRoman Divacky   if (!IsIncompleteFunction) {
2877f22ef01cSRoman Divacky     assert(F->getType()->getElementType() == Ty);
2878f22ef01cSRoman Divacky     return F;
2879f22ef01cSRoman Divacky   }
2880f22ef01cSRoman Divacky 
288117a519f9SDimitry Andric   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2882f22ef01cSRoman Divacky   return llvm::ConstantExpr::getBitCast(F, PTy);
2883f22ef01cSRoman Divacky }
2884f22ef01cSRoman Divacky 
2885f22ef01cSRoman Divacky /// GetAddrOfFunction - Return the address of the given function.  If Ty is
2886f22ef01cSRoman Divacky /// non-null, then this function will use the specified type if it has to
2887f22ef01cSRoman Divacky /// create it (this occurs when we see a definition of the function).
GetAddrOfFunction(GlobalDecl GD,llvm::Type * Ty,bool ForVTable,bool DontDefer,ForDefinition_t IsForDefinition)2888f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
28896122f3e6SDimitry Andric                                                  llvm::Type *Ty,
289059d1ed5bSDimitry Andric                                                  bool ForVTable,
28910623d748SDimitry Andric                                                  bool DontDefer,
289244290647SDimitry Andric                                               ForDefinition_t IsForDefinition) {
2893f22ef01cSRoman Divacky   // If there was no specific requested type, just convert it now.
28940623d748SDimitry Andric   if (!Ty) {
28950623d748SDimitry Andric     const auto *FD = cast<FunctionDecl>(GD.getDecl());
28960623d748SDimitry Andric     auto CanonTy = Context.getCanonicalType(FD->getType());
28970623d748SDimitry Andric     Ty = getTypes().ConvertFunctionType(CanonTy, FD);
28980623d748SDimitry Andric   }
2899ffd1746dSEd Schouten 
29004ba319b5SDimitry Andric   // Devirtualized destructor calls may come through here instead of via
29014ba319b5SDimitry Andric   // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
29024ba319b5SDimitry Andric   // of the complete destructor when necessary.
29034ba319b5SDimitry Andric   if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
29044ba319b5SDimitry Andric     if (getTarget().getCXXABI().isMicrosoft() &&
29054ba319b5SDimitry Andric         GD.getDtorType() == Dtor_Complete &&
29064ba319b5SDimitry Andric         DD->getParent()->getNumVBases() == 0)
29074ba319b5SDimitry Andric       GD = GlobalDecl(DD, Dtor_Base);
29084ba319b5SDimitry Andric   }
29094ba319b5SDimitry Andric 
29106122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
29110623d748SDimitry Andric   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
291220e90f04SDimitry Andric                                  /*IsThunk=*/false, llvm::AttributeList(),
29130623d748SDimitry Andric                                  IsForDefinition);
2914f22ef01cSRoman Divacky }
2915f22ef01cSRoman Divacky 
291644290647SDimitry Andric static const FunctionDecl *
GetRuntimeFunctionDecl(ASTContext & C,StringRef Name)291744290647SDimitry Andric GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
291844290647SDimitry Andric   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
291944290647SDimitry Andric   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
292044290647SDimitry Andric 
292144290647SDimitry Andric   IdentifierInfo &CII = C.Idents.get(Name);
292244290647SDimitry Andric   for (const auto &Result : DC->lookup(&CII))
292344290647SDimitry Andric     if (const auto FD = dyn_cast<FunctionDecl>(Result))
292444290647SDimitry Andric       return FD;
292544290647SDimitry Andric 
292644290647SDimitry Andric   if (!C.getLangOpts().CPlusPlus)
292744290647SDimitry Andric     return nullptr;
292844290647SDimitry Andric 
292944290647SDimitry Andric   // Demangle the premangled name from getTerminateFn()
293044290647SDimitry Andric   IdentifierInfo &CXXII =
29314ba319b5SDimitry Andric       (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
293244290647SDimitry Andric           ? C.Idents.get("terminate")
293344290647SDimitry Andric           : C.Idents.get(Name);
293444290647SDimitry Andric 
293544290647SDimitry Andric   for (const auto &N : {"__cxxabiv1", "std"}) {
293644290647SDimitry Andric     IdentifierInfo &NS = C.Idents.get(N);
293744290647SDimitry Andric     for (const auto &Result : DC->lookup(&NS)) {
293844290647SDimitry Andric       NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
293944290647SDimitry Andric       if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
294044290647SDimitry Andric         for (const auto &Result : LSD->lookup(&NS))
294144290647SDimitry Andric           if ((ND = dyn_cast<NamespaceDecl>(Result)))
294244290647SDimitry Andric             break;
294344290647SDimitry Andric 
294444290647SDimitry Andric       if (ND)
294544290647SDimitry Andric         for (const auto &Result : ND->lookup(&CXXII))
294644290647SDimitry Andric           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
294744290647SDimitry Andric             return FD;
294844290647SDimitry Andric     }
294944290647SDimitry Andric   }
295044290647SDimitry Andric 
295144290647SDimitry Andric   return nullptr;
295244290647SDimitry Andric }
295344290647SDimitry Andric 
2954f22ef01cSRoman Divacky /// CreateRuntimeFunction - Create a new runtime function with the specified
2955f22ef01cSRoman Divacky /// type and name.
2956f22ef01cSRoman Divacky llvm::Constant *
CreateRuntimeFunction(llvm::FunctionType * FTy,StringRef Name,llvm::AttributeList ExtraAttrs,bool Local)295744290647SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
295820e90f04SDimitry Andric                                      llvm::AttributeList ExtraAttrs,
295944290647SDimitry Andric                                      bool Local) {
296059d1ed5bSDimitry Andric   llvm::Constant *C =
296159d1ed5bSDimitry Andric       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
296244290647SDimitry Andric                               /*DontDefer=*/false, /*IsThunk=*/false,
296344290647SDimitry Andric                               ExtraAttrs);
296444290647SDimitry Andric 
296544290647SDimitry Andric   if (auto *F = dyn_cast<llvm::Function>(C)) {
296644290647SDimitry Andric     if (F->empty()) {
2967139f7f9bSDimitry Andric       F->setCallingConv(getRuntimeCC());
296844290647SDimitry Andric 
296944290647SDimitry Andric       if (!Local && getTriple().isOSBinFormatCOFF() &&
29709a199699SDimitry Andric           !getCodeGenOpts().LTOVisibilityPublicStd &&
29719a199699SDimitry Andric           !getTriple().isWindowsGNUEnvironment()) {
297244290647SDimitry Andric         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
297344290647SDimitry Andric         if (!FD || FD->hasAttr<DLLImportAttr>()) {
297444290647SDimitry Andric           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
297544290647SDimitry Andric           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
297644290647SDimitry Andric         }
297744290647SDimitry Andric       }
29784ba319b5SDimitry Andric       setDSOLocal(F);
297944290647SDimitry Andric     }
298044290647SDimitry Andric   }
298144290647SDimitry Andric 
2982139f7f9bSDimitry Andric   return C;
2983f22ef01cSRoman Divacky }
2984f22ef01cSRoman Divacky 
298539d628a0SDimitry Andric /// CreateBuiltinFunction - Create a new builtin function with the specified
298639d628a0SDimitry Andric /// type and name.
298739d628a0SDimitry Andric llvm::Constant *
CreateBuiltinFunction(llvm::FunctionType * FTy,StringRef Name,llvm::AttributeList ExtraAttrs)298820e90f04SDimitry Andric CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
298920e90f04SDimitry Andric                                      llvm::AttributeList ExtraAttrs) {
29904ba319b5SDimitry Andric   return CreateRuntimeFunction(FTy, Name, ExtraAttrs, true);
299139d628a0SDimitry Andric }
299239d628a0SDimitry Andric 
2993dff0c46cSDimitry Andric /// isTypeConstant - Determine whether an object of this type can be emitted
2994dff0c46cSDimitry Andric /// as a constant.
2995dff0c46cSDimitry Andric ///
2996dff0c46cSDimitry Andric /// If ExcludeCtor is true, the duration when the object's constructor runs
2997dff0c46cSDimitry Andric /// will not be considered. The caller will need to verify that the object is
2998dff0c46cSDimitry Andric /// not written to during its construction.
isTypeConstant(QualType Ty,bool ExcludeCtor)2999dff0c46cSDimitry Andric bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
3000dff0c46cSDimitry Andric   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
3001f22ef01cSRoman Divacky     return false;
3002bd5abe19SDimitry Andric 
3003dff0c46cSDimitry Andric   if (Context.getLangOpts().CPlusPlus) {
3004dff0c46cSDimitry Andric     if (const CXXRecordDecl *Record
3005dff0c46cSDimitry Andric           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
3006dff0c46cSDimitry Andric       return ExcludeCtor && !Record->hasMutableFields() &&
3007dff0c46cSDimitry Andric              Record->hasTrivialDestructor();
3008f22ef01cSRoman Divacky   }
3009bd5abe19SDimitry Andric 
3010f22ef01cSRoman Divacky   return true;
3011f22ef01cSRoman Divacky }
3012f22ef01cSRoman Divacky 
3013f22ef01cSRoman Divacky /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
3014f22ef01cSRoman Divacky /// create and return an llvm GlobalVariable with the specified type.  If there
3015f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially
3016f22ef01cSRoman Divacky /// bitcasted to the right type.
3017f22ef01cSRoman Divacky ///
3018f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this.  This is used
3019f22ef01cSRoman Divacky /// to set the attributes on the global when it is first created.
3020e7145dcbSDimitry Andric ///
30214ba319b5SDimitry Andric /// If IsForDefinition is true, it is guaranteed that an actual global with
3022e7145dcbSDimitry Andric /// type Ty will be returned, not conversion of a variable with the same
3023e7145dcbSDimitry Andric /// mangled name but some other type.
3024f22ef01cSRoman Divacky llvm::Constant *
GetOrCreateLLVMGlobal(StringRef MangledName,llvm::PointerType * Ty,const VarDecl * D,ForDefinition_t IsForDefinition)30256122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
30266122f3e6SDimitry Andric                                      llvm::PointerType *Ty,
3027e7145dcbSDimitry Andric                                      const VarDecl *D,
302844290647SDimitry Andric                                      ForDefinition_t IsForDefinition) {
3029f22ef01cSRoman Divacky   // Lookup the entry, lazily creating it if necessary.
3030f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3031f22ef01cSRoman Divacky   if (Entry) {
30323861d79fSDimitry Andric     if (WeakRefReferences.erase(Entry)) {
3033f22ef01cSRoman Divacky       if (D && !D->hasAttr<WeakAttr>())
3034f22ef01cSRoman Divacky         Entry->setLinkage(llvm::Function::ExternalLinkage);
3035f22ef01cSRoman Divacky     }
3036f22ef01cSRoman Divacky 
303739d628a0SDimitry Andric     // Handle dropped DLL attributes.
303839d628a0SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
303939d628a0SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
304039d628a0SDimitry Andric 
30414ba319b5SDimitry Andric     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
30424ba319b5SDimitry Andric       getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
30434ba319b5SDimitry Andric 
3044f22ef01cSRoman Divacky     if (Entry->getType() == Ty)
3045f22ef01cSRoman Divacky       return Entry;
3046f22ef01cSRoman Divacky 
3047e7145dcbSDimitry Andric     // If there are two attempts to define the same mangled name, issue an
3048e7145dcbSDimitry Andric     // error.
3049e7145dcbSDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
3050e7145dcbSDimitry Andric       GlobalDecl OtherGD;
3051e7145dcbSDimitry Andric       const VarDecl *OtherD;
3052e7145dcbSDimitry Andric 
3053e7145dcbSDimitry Andric       // Check that D is not yet in DiagnosedConflictingDefinitions is required
3054e7145dcbSDimitry Andric       // to make sure that we issue an error only once.
3055e7145dcbSDimitry Andric       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
3056e7145dcbSDimitry Andric           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
3057e7145dcbSDimitry Andric           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
3058e7145dcbSDimitry Andric           OtherD->hasInit() &&
3059e7145dcbSDimitry Andric           DiagnosedConflictingDefinitions.insert(D).second) {
30604ba319b5SDimitry Andric         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
30614ba319b5SDimitry Andric             << MangledName;
3062e7145dcbSDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
3063e7145dcbSDimitry Andric                           diag::note_previous_definition);
3064e7145dcbSDimitry Andric       }
3065e7145dcbSDimitry Andric     }
3066e7145dcbSDimitry Andric 
3067f22ef01cSRoman Divacky     // Make sure the result is of the correct type.
3068f785676fSDimitry Andric     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
3069f785676fSDimitry Andric       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
3070f785676fSDimitry Andric 
3071e7145dcbSDimitry Andric     // (If global is requested for a definition, we always need to create a new
3072e7145dcbSDimitry Andric     // global, not just return a bitcast.)
3073e7145dcbSDimitry Andric     if (!IsForDefinition)
3074f22ef01cSRoman Divacky       return llvm::ConstantExpr::getBitCast(Entry, Ty);
3075f22ef01cSRoman Divacky   }
3076f22ef01cSRoman Divacky 
3077c4394386SDimitry Andric   auto AddrSpace = GetGlobalVarAddressSpace(D);
3078c4394386SDimitry Andric   auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
3079c4394386SDimitry Andric 
308059d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
308159d1ed5bSDimitry Andric       getModule(), Ty->getElementType(), false,
308259d1ed5bSDimitry Andric       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
3083c4394386SDimitry Andric       llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
308459d1ed5bSDimitry Andric 
3085e7145dcbSDimitry Andric   // If we already created a global with the same mangled name (but different
3086e7145dcbSDimitry Andric   // type) before, take its name and remove it from its parent.
3087e7145dcbSDimitry Andric   if (Entry) {
3088e7145dcbSDimitry Andric     GV->takeName(Entry);
3089e7145dcbSDimitry Andric 
3090e7145dcbSDimitry Andric     if (!Entry->use_empty()) {
3091e7145dcbSDimitry Andric       llvm::Constant *NewPtrForOldDecl =
3092e7145dcbSDimitry Andric           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
3093e7145dcbSDimitry Andric       Entry->replaceAllUsesWith(NewPtrForOldDecl);
3094e7145dcbSDimitry Andric     }
3095e7145dcbSDimitry Andric 
3096e7145dcbSDimitry Andric     Entry->eraseFromParent();
3097e7145dcbSDimitry Andric   }
3098e7145dcbSDimitry Andric 
3099f22ef01cSRoman Divacky   // This is the first use or definition of a mangled name.  If there is a
3100f22ef01cSRoman Divacky   // deferred decl with this name, remember that we need to emit it at the end
3101f22ef01cSRoman Divacky   // of the file.
310259d1ed5bSDimitry Andric   auto DDI = DeferredDecls.find(MangledName);
3103f22ef01cSRoman Divacky   if (DDI != DeferredDecls.end()) {
3104f22ef01cSRoman Divacky     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
3105f22ef01cSRoman Divacky     // list, and remove it from DeferredDecls (since we don't need it anymore).
3106f37b6182SDimitry Andric     addDeferredDeclToEmit(DDI->second);
3107f22ef01cSRoman Divacky     DeferredDecls.erase(DDI);
3108f22ef01cSRoman Divacky   }
3109f22ef01cSRoman Divacky 
3110f22ef01cSRoman Divacky   // Handle things which are present even on external declarations.
3111f22ef01cSRoman Divacky   if (D) {
31124ba319b5SDimitry Andric     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
31134ba319b5SDimitry Andric       getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
31144ba319b5SDimitry Andric 
3115f22ef01cSRoman Divacky     // FIXME: This code is overly simple and should be merged with other global
3116f22ef01cSRoman Divacky     // handling.
3117dff0c46cSDimitry Andric     GV->setConstant(isTypeConstant(D->getType(), false));
3118f22ef01cSRoman Divacky 
311933956c43SDimitry Andric     GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
312033956c43SDimitry Andric 
31219a199699SDimitry Andric     setLinkageForGV(GV, D);
31222754fe60SDimitry Andric 
3123284c1978SDimitry Andric     if (D->getTLSKind()) {
3124284c1978SDimitry Andric       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
31250623d748SDimitry Andric         CXXThreadLocals.push_back(D);
31267ae0e2c9SDimitry Andric       setTLSMode(GV, *D);
3127f22ef01cSRoman Divacky     }
3128f785676fSDimitry Andric 
31294ba319b5SDimitry Andric     setGVProperties(GV, D);
31304ba319b5SDimitry Andric 
3131f785676fSDimitry Andric     // If required by the ABI, treat declarations of static data members with
3132f785676fSDimitry Andric     // inline initializers as definitions.
313359d1ed5bSDimitry Andric     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
3134f785676fSDimitry Andric       EmitGlobalVarDefinition(D);
3135284c1978SDimitry Andric     }
3136f22ef01cSRoman Divacky 
31379a199699SDimitry Andric     // Emit section information for extern variables.
31389a199699SDimitry Andric     if (D->hasExternalStorage()) {
31399a199699SDimitry Andric       if (const SectionAttr *SA = D->getAttr<SectionAttr>())
31409a199699SDimitry Andric         GV->setSection(SA->getName());
31419a199699SDimitry Andric     }
31429a199699SDimitry Andric 
314359d1ed5bSDimitry Andric     // Handle XCore specific ABI requirements.
314444290647SDimitry Andric     if (getTriple().getArch() == llvm::Triple::xcore &&
314559d1ed5bSDimitry Andric         D->getLanguageLinkage() == CLanguageLinkage &&
314659d1ed5bSDimitry Andric         D->getType().isConstant(Context) &&
314759d1ed5bSDimitry Andric         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
314859d1ed5bSDimitry Andric       GV->setSection(".cp.rodata");
31499a199699SDimitry Andric 
31509a199699SDimitry Andric     // Check if we a have a const declaration with an initializer, we may be
31519a199699SDimitry Andric     // able to emit it as available_externally to expose it's value to the
31529a199699SDimitry Andric     // optimizer.
31539a199699SDimitry Andric     if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
31549a199699SDimitry Andric         D->getType().isConstQualified() && !GV->hasInitializer() &&
31559a199699SDimitry Andric         !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
31569a199699SDimitry Andric       const auto *Record =
31579a199699SDimitry Andric           Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
31589a199699SDimitry Andric       bool HasMutableFields = Record && Record->hasMutableFields();
31599a199699SDimitry Andric       if (!HasMutableFields) {
31609a199699SDimitry Andric         const VarDecl *InitDecl;
31619a199699SDimitry Andric         const Expr *InitExpr = D->getAnyInitializer(InitDecl);
31629a199699SDimitry Andric         if (InitExpr) {
31639a199699SDimitry Andric           ConstantEmitter emitter(*this);
31649a199699SDimitry Andric           llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
31659a199699SDimitry Andric           if (Init) {
31669a199699SDimitry Andric             auto *InitType = Init->getType();
31679a199699SDimitry Andric             if (GV->getType()->getElementType() != InitType) {
31689a199699SDimitry Andric               // The type of the initializer does not match the definition.
31699a199699SDimitry Andric               // This happens when an initializer has a different type from
31709a199699SDimitry Andric               // the type of the global (because of padding at the end of a
31719a199699SDimitry Andric               // structure for instance).
31729a199699SDimitry Andric               GV->setName(StringRef());
31739a199699SDimitry Andric               // Make a new global with the correct type, this is now guaranteed
31749a199699SDimitry Andric               // to work.
31759a199699SDimitry Andric               auto *NewGV = cast<llvm::GlobalVariable>(
31769a199699SDimitry Andric                   GetAddrOfGlobalVar(D, InitType, IsForDefinition));
31779a199699SDimitry Andric 
31789a199699SDimitry Andric               // Erase the old global, since it is no longer used.
31794ba319b5SDimitry Andric               GV->eraseFromParent();
31809a199699SDimitry Andric               GV = NewGV;
31819a199699SDimitry Andric             } else {
31829a199699SDimitry Andric               GV->setInitializer(Init);
31839a199699SDimitry Andric               GV->setConstant(true);
31849a199699SDimitry Andric               GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
31859a199699SDimitry Andric             }
31869a199699SDimitry Andric             emitter.finalize(GV);
31879a199699SDimitry Andric           }
31889a199699SDimitry Andric         }
31899a199699SDimitry Andric       }
31909a199699SDimitry Andric     }
319159d1ed5bSDimitry Andric   }
319259d1ed5bSDimitry Andric 
31939a199699SDimitry Andric   LangAS ExpectedAS =
3194c4394386SDimitry Andric       D ? D->getType().getAddressSpace()
31959a199699SDimitry Andric         : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
3196c4394386SDimitry Andric   assert(getContext().getTargetAddressSpace(ExpectedAS) ==
3197c4394386SDimitry Andric          Ty->getPointerAddressSpace());
3198c4394386SDimitry Andric   if (AddrSpace != ExpectedAS)
3199c4394386SDimitry Andric     return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
3200c4394386SDimitry Andric                                                        ExpectedAS, Ty);
3201f785676fSDimitry Andric 
3202f22ef01cSRoman Divacky   return GV;
3203f22ef01cSRoman Divacky }
3204f22ef01cSRoman Divacky 
32050623d748SDimitry Andric llvm::Constant *
GetAddrOfGlobal(GlobalDecl GD,ForDefinition_t IsForDefinition)32060623d748SDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
320744290647SDimitry Andric                                ForDefinition_t IsForDefinition) {
320844290647SDimitry Andric   const Decl *D = GD.getDecl();
320944290647SDimitry Andric   if (isa<CXXConstructorDecl>(D))
321044290647SDimitry Andric     return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
32110623d748SDimitry Andric                                 getFromCtorType(GD.getCtorType()),
32120623d748SDimitry Andric                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
32130623d748SDimitry Andric                                 /*DontDefer=*/false, IsForDefinition);
321444290647SDimitry Andric   else if (isa<CXXDestructorDecl>(D))
321544290647SDimitry Andric     return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
32160623d748SDimitry Andric                                 getFromDtorType(GD.getDtorType()),
32170623d748SDimitry Andric                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
32180623d748SDimitry Andric                                 /*DontDefer=*/false, IsForDefinition);
321944290647SDimitry Andric   else if (isa<CXXMethodDecl>(D)) {
32200623d748SDimitry Andric     auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
322144290647SDimitry Andric         cast<CXXMethodDecl>(D));
32220623d748SDimitry Andric     auto Ty = getTypes().GetFunctionType(*FInfo);
32230623d748SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
32240623d748SDimitry Andric                              IsForDefinition);
322544290647SDimitry Andric   } else if (isa<FunctionDecl>(D)) {
32260623d748SDimitry Andric     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
32270623d748SDimitry Andric     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
32280623d748SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
32290623d748SDimitry Andric                              IsForDefinition);
32300623d748SDimitry Andric   } else
323144290647SDimitry Andric     return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
3232e7145dcbSDimitry Andric                               IsForDefinition);
32330623d748SDimitry Andric }
3234f22ef01cSRoman Divacky 
CreateOrReplaceCXXRuntimeVariable(StringRef Name,llvm::Type * Ty,llvm::GlobalValue::LinkageTypes Linkage,unsigned Alignment)3235*b5893f02SDimitry Andric llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
3236*b5893f02SDimitry Andric     StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
3237*b5893f02SDimitry Andric     unsigned Alignment) {
32382754fe60SDimitry Andric   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
323959d1ed5bSDimitry Andric   llvm::GlobalVariable *OldGV = nullptr;
32402754fe60SDimitry Andric 
32412754fe60SDimitry Andric   if (GV) {
32422754fe60SDimitry Andric     // Check if the variable has the right type.
32432754fe60SDimitry Andric     if (GV->getType()->getElementType() == Ty)
32442754fe60SDimitry Andric       return GV;
32452754fe60SDimitry Andric 
32462754fe60SDimitry Andric     // Because C++ name mangling, the only way we can end up with an already
32472754fe60SDimitry Andric     // existing global with the same name is if it has been declared extern "C".
32482754fe60SDimitry Andric     assert(GV->isDeclaration() && "Declaration has wrong type!");
32492754fe60SDimitry Andric     OldGV = GV;
32502754fe60SDimitry Andric   }
32512754fe60SDimitry Andric 
32522754fe60SDimitry Andric   // Create a new variable.
32532754fe60SDimitry Andric   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
325459d1ed5bSDimitry Andric                                 Linkage, nullptr, Name);
32552754fe60SDimitry Andric 
32562754fe60SDimitry Andric   if (OldGV) {
32572754fe60SDimitry Andric     // Replace occurrences of the old variable if needed.
32582754fe60SDimitry Andric     GV->takeName(OldGV);
32592754fe60SDimitry Andric 
32602754fe60SDimitry Andric     if (!OldGV->use_empty()) {
32612754fe60SDimitry Andric       llvm::Constant *NewPtrForOldDecl =
32622754fe60SDimitry Andric       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
32632754fe60SDimitry Andric       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
32642754fe60SDimitry Andric     }
32652754fe60SDimitry Andric 
32662754fe60SDimitry Andric     OldGV->eraseFromParent();
32672754fe60SDimitry Andric   }
32682754fe60SDimitry Andric 
326933956c43SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker() &&
327033956c43SDimitry Andric       !GV->hasAvailableExternallyLinkage())
327133956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
327233956c43SDimitry Andric 
3273*b5893f02SDimitry Andric   GV->setAlignment(Alignment);
3274*b5893f02SDimitry Andric 
32752754fe60SDimitry Andric   return GV;
32762754fe60SDimitry Andric }
32772754fe60SDimitry Andric 
3278f22ef01cSRoman Divacky /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
3279f22ef01cSRoman Divacky /// given global variable.  If Ty is non-null and if the global doesn't exist,
3280cb4dff85SDimitry Andric /// then it will be created with the specified type instead of whatever the
32814ba319b5SDimitry Andric /// normal requested type would be. If IsForDefinition is true, it is guaranteed
3282e7145dcbSDimitry Andric /// that an actual global with type Ty will be returned, not conversion of a
3283e7145dcbSDimitry Andric /// variable with the same mangled name but some other type.
GetAddrOfGlobalVar(const VarDecl * D,llvm::Type * Ty,ForDefinition_t IsForDefinition)3284f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
3285e7145dcbSDimitry Andric                                                   llvm::Type *Ty,
328644290647SDimitry Andric                                            ForDefinition_t IsForDefinition) {
3287f22ef01cSRoman Divacky   assert(D->hasGlobalStorage() && "Not a global variable");
3288f22ef01cSRoman Divacky   QualType ASTTy = D->getType();
328959d1ed5bSDimitry Andric   if (!Ty)
3290f22ef01cSRoman Divacky     Ty = getTypes().ConvertTypeForMem(ASTTy);
3291f22ef01cSRoman Divacky 
32926122f3e6SDimitry Andric   llvm::PointerType *PTy =
32933b0f4066SDimitry Andric     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
3294f22ef01cSRoman Divacky 
32956122f3e6SDimitry Andric   StringRef MangledName = getMangledName(D);
3296e7145dcbSDimitry Andric   return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
3297f22ef01cSRoman Divacky }
3298f22ef01cSRoman Divacky 
3299f22ef01cSRoman Divacky /// CreateRuntimeVariable - Create a new runtime global variable with the
3300f22ef01cSRoman Divacky /// specified type and name.
3301f22ef01cSRoman Divacky llvm::Constant *
CreateRuntimeVariable(llvm::Type * Ty,StringRef Name)33026122f3e6SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
33036122f3e6SDimitry Andric                                      StringRef Name) {
33044ba319b5SDimitry Andric   auto *Ret =
33054ba319b5SDimitry Andric       GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
33064ba319b5SDimitry Andric   setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
33074ba319b5SDimitry Andric   return Ret;
3308f22ef01cSRoman Divacky }
3309f22ef01cSRoman Divacky 
EmitTentativeDefinition(const VarDecl * D)3310f22ef01cSRoman Divacky void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
3311f22ef01cSRoman Divacky   assert(!D->getInit() && "Cannot emit definite definitions here!");
3312f22ef01cSRoman Divacky 
33136122f3e6SDimitry Andric   StringRef MangledName = getMangledName(D);
3314e7145dcbSDimitry Andric   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
3315e7145dcbSDimitry Andric 
3316e7145dcbSDimitry Andric   // We already have a definition, not declaration, with the same mangled name.
3317e7145dcbSDimitry Andric   // Emitting of declaration is not required (and actually overwrites emitted
3318e7145dcbSDimitry Andric   // definition).
3319e7145dcbSDimitry Andric   if (GV && !GV->isDeclaration())
3320e7145dcbSDimitry Andric     return;
3321e7145dcbSDimitry Andric 
3322e7145dcbSDimitry Andric   // If we have not seen a reference to this variable yet, place it into the
3323e7145dcbSDimitry Andric   // deferred declarations table to be emitted if needed later.
3324e7145dcbSDimitry Andric   if (!MustBeEmitted(D) && !GV) {
3325f22ef01cSRoman Divacky       DeferredDecls[MangledName] = D;
3326f22ef01cSRoman Divacky       return;
3327f22ef01cSRoman Divacky   }
3328f22ef01cSRoman Divacky 
3329f22ef01cSRoman Divacky   // The tentative definition is the only definition.
3330f22ef01cSRoman Divacky   EmitGlobalVarDefinition(D);
3331f22ef01cSRoman Divacky }
3332f22ef01cSRoman Divacky 
GetTargetTypeStoreSize(llvm::Type * Ty) const33336122f3e6SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
33342754fe60SDimitry Andric   return Context.toCharUnitsFromBits(
33350623d748SDimitry Andric       getDataLayout().getTypeStoreSizeInBits(Ty));
3336f22ef01cSRoman Divacky }
3337f22ef01cSRoman Divacky 
GetGlobalVarAddressSpace(const VarDecl * D)33389a199699SDimitry Andric LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
33399a199699SDimitry Andric   LangAS AddrSpace = LangAS::Default;
3340c4394386SDimitry Andric   if (LangOpts.OpenCL) {
33419a199699SDimitry Andric     AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
3342c4394386SDimitry Andric     assert(AddrSpace == LangAS::opencl_global ||
3343c4394386SDimitry Andric            AddrSpace == LangAS::opencl_constant ||
3344c4394386SDimitry Andric            AddrSpace == LangAS::opencl_local ||
3345c4394386SDimitry Andric            AddrSpace >= LangAS::FirstTargetAddressSpace);
3346c4394386SDimitry Andric     return AddrSpace;
33477ae0e2c9SDimitry Andric   }
33487ae0e2c9SDimitry Andric 
3349c4394386SDimitry Andric   if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
3350c4394386SDimitry Andric     if (D && D->hasAttr<CUDAConstantAttr>())
3351c4394386SDimitry Andric       return LangAS::cuda_constant;
3352c4394386SDimitry Andric     else if (D && D->hasAttr<CUDASharedAttr>())
3353c4394386SDimitry Andric       return LangAS::cuda_shared;
33544ba319b5SDimitry Andric     else if (D && D->hasAttr<CUDADeviceAttr>())
33554ba319b5SDimitry Andric       return LangAS::cuda_device;
33564ba319b5SDimitry Andric     else if (D && D->getType().isConstQualified())
33574ba319b5SDimitry Andric       return LangAS::cuda_constant;
3358c4394386SDimitry Andric     else
3359c4394386SDimitry Andric       return LangAS::cuda_device;
3360c4394386SDimitry Andric   }
3361c4394386SDimitry Andric 
3362c4394386SDimitry Andric   return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
33637ae0e2c9SDimitry Andric }
33647ae0e2c9SDimitry Andric 
getStringLiteralAddressSpace() const33654ba319b5SDimitry Andric LangAS CodeGenModule::getStringLiteralAddressSpace() const {
33664ba319b5SDimitry Andric   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
33674ba319b5SDimitry Andric   if (LangOpts.OpenCL)
33684ba319b5SDimitry Andric     return LangAS::opencl_constant;
33694ba319b5SDimitry Andric   if (auto AS = getTarget().getConstantAddressSpace())
33704ba319b5SDimitry Andric     return AS.getValue();
33714ba319b5SDimitry Andric   return LangAS::Default;
33724ba319b5SDimitry Andric }
33734ba319b5SDimitry Andric 
33744ba319b5SDimitry Andric // In address space agnostic languages, string literals are in default address
33754ba319b5SDimitry Andric // space in AST. However, certain targets (e.g. amdgcn) request them to be
33764ba319b5SDimitry Andric // emitted in constant address space in LLVM IR. To be consistent with other
33774ba319b5SDimitry Andric // parts of AST, string literal global variables in constant address space
33784ba319b5SDimitry Andric // need to be casted to default address space before being put into address
33794ba319b5SDimitry Andric // map and referenced by other part of CodeGen.
33804ba319b5SDimitry Andric // In OpenCL, string literals are in constant address space in AST, therefore
33814ba319b5SDimitry Andric // they should not be casted to default address space.
33824ba319b5SDimitry Andric static llvm::Constant *
castStringLiteralToDefaultAddressSpace(CodeGenModule & CGM,llvm::GlobalVariable * GV)33834ba319b5SDimitry Andric castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
33844ba319b5SDimitry Andric                                        llvm::GlobalVariable *GV) {
33854ba319b5SDimitry Andric   llvm::Constant *Cast = GV;
33864ba319b5SDimitry Andric   if (!CGM.getLangOpts().OpenCL) {
33874ba319b5SDimitry Andric     if (auto AS = CGM.getTarget().getConstantAddressSpace()) {
33884ba319b5SDimitry Andric       if (AS != LangAS::Default)
33894ba319b5SDimitry Andric         Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
33904ba319b5SDimitry Andric             CGM, GV, AS.getValue(), LangAS::Default,
33914ba319b5SDimitry Andric             GV->getValueType()->getPointerTo(
33924ba319b5SDimitry Andric                 CGM.getContext().getTargetAddressSpace(LangAS::Default)));
33934ba319b5SDimitry Andric     }
33944ba319b5SDimitry Andric   }
33954ba319b5SDimitry Andric   return Cast;
33964ba319b5SDimitry Andric }
33974ba319b5SDimitry Andric 
3398284c1978SDimitry Andric template<typename SomeDecl>
MaybeHandleStaticInExternC(const SomeDecl * D,llvm::GlobalValue * GV)3399284c1978SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
3400284c1978SDimitry Andric                                                llvm::GlobalValue *GV) {
3401284c1978SDimitry Andric   if (!getLangOpts().CPlusPlus)
3402284c1978SDimitry Andric     return;
3403284c1978SDimitry Andric 
3404284c1978SDimitry Andric   // Must have 'used' attribute, or else inline assembly can't rely on
3405284c1978SDimitry Andric   // the name existing.
3406284c1978SDimitry Andric   if (!D->template hasAttr<UsedAttr>())
3407284c1978SDimitry Andric     return;
3408284c1978SDimitry Andric 
3409284c1978SDimitry Andric   // Must have internal linkage and an ordinary name.
3410f785676fSDimitry Andric   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
3411284c1978SDimitry Andric     return;
3412284c1978SDimitry Andric 
3413284c1978SDimitry Andric   // Must be in an extern "C" context. Entities declared directly within
3414284c1978SDimitry Andric   // a record are not extern "C" even if the record is in such a context.
3415f785676fSDimitry Andric   const SomeDecl *First = D->getFirstDecl();
3416284c1978SDimitry Andric   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
3417284c1978SDimitry Andric     return;
3418284c1978SDimitry Andric 
3419284c1978SDimitry Andric   // OK, this is an internal linkage entity inside an extern "C" linkage
3420284c1978SDimitry Andric   // specification. Make a note of that so we can give it the "expected"
3421284c1978SDimitry Andric   // mangled name if nothing else is using that name.
3422284c1978SDimitry Andric   std::pair<StaticExternCMap::iterator, bool> R =
3423284c1978SDimitry Andric       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
3424284c1978SDimitry Andric 
3425284c1978SDimitry Andric   // If we have multiple internal linkage entities with the same name
3426284c1978SDimitry Andric   // in extern "C" regions, none of them gets that name.
3427284c1978SDimitry Andric   if (!R.second)
342859d1ed5bSDimitry Andric     R.first->second = nullptr;
3429284c1978SDimitry Andric }
3430284c1978SDimitry Andric 
shouldBeInCOMDAT(CodeGenModule & CGM,const Decl & D)343133956c43SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
343233956c43SDimitry Andric   if (!CGM.supportsCOMDAT())
343333956c43SDimitry Andric     return false;
343433956c43SDimitry Andric 
343533956c43SDimitry Andric   if (D.hasAttr<SelectAnyAttr>())
343633956c43SDimitry Andric     return true;
343733956c43SDimitry Andric 
343833956c43SDimitry Andric   GVALinkage Linkage;
343933956c43SDimitry Andric   if (auto *VD = dyn_cast<VarDecl>(&D))
344033956c43SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
344133956c43SDimitry Andric   else
344233956c43SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
344333956c43SDimitry Andric 
344433956c43SDimitry Andric   switch (Linkage) {
344533956c43SDimitry Andric   case GVA_Internal:
344633956c43SDimitry Andric   case GVA_AvailableExternally:
344733956c43SDimitry Andric   case GVA_StrongExternal:
344833956c43SDimitry Andric     return false;
344933956c43SDimitry Andric   case GVA_DiscardableODR:
345033956c43SDimitry Andric   case GVA_StrongODR:
345133956c43SDimitry Andric     return true;
345233956c43SDimitry Andric   }
345333956c43SDimitry Andric   llvm_unreachable("No such linkage");
345433956c43SDimitry Andric }
345533956c43SDimitry Andric 
maybeSetTrivialComdat(const Decl & D,llvm::GlobalObject & GO)345633956c43SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
345733956c43SDimitry Andric                                           llvm::GlobalObject &GO) {
345833956c43SDimitry Andric   if (!shouldBeInCOMDAT(*this, D))
345933956c43SDimitry Andric     return;
346033956c43SDimitry Andric   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
346133956c43SDimitry Andric }
346233956c43SDimitry Andric 
3463e7145dcbSDimitry Andric /// Pass IsTentative as true if you want to create a tentative definition.
EmitGlobalVarDefinition(const VarDecl * D,bool IsTentative)3464e7145dcbSDimitry Andric void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
3465e7145dcbSDimitry Andric                                             bool IsTentative) {
346644290647SDimitry Andric   // OpenCL global variables of sampler type are translated to function calls,
346744290647SDimitry Andric   // therefore no need to be translated.
3468f22ef01cSRoman Divacky   QualType ASTTy = D->getType();
346944290647SDimitry Andric   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
347044290647SDimitry Andric     return;
347144290647SDimitry Andric 
34724ba319b5SDimitry Andric   // If this is OpenMP device, check if it is legal to emit this global
34734ba319b5SDimitry Andric   // normally.
34744ba319b5SDimitry Andric   if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
34754ba319b5SDimitry Andric       OpenMPRuntime->emitTargetGlobalVariable(D))
34764ba319b5SDimitry Andric     return;
34774ba319b5SDimitry Andric 
347844290647SDimitry Andric   llvm::Constant *Init = nullptr;
3479dff0c46cSDimitry Andric   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3480dff0c46cSDimitry Andric   bool NeedsGlobalCtor = false;
3481dff0c46cSDimitry Andric   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
3482f22ef01cSRoman Divacky 
3483dff0c46cSDimitry Andric   const VarDecl *InitDecl;
3484dff0c46cSDimitry Andric   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
3485f22ef01cSRoman Divacky 
34869a199699SDimitry Andric   Optional<ConstantEmitter> emitter;
34879a199699SDimitry Andric 
3488e7145dcbSDimitry Andric   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
3489e7145dcbSDimitry Andric   // as part of their declaration."  Sema has already checked for
3490e7145dcbSDimitry Andric   // error cases, so we just need to set Init to UndefValue.
3491*b5893f02SDimitry Andric   bool IsCUDASharedVar =
3492*b5893f02SDimitry Andric       getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
3493*b5893f02SDimitry Andric   // Shadows of initialized device-side global variables are also left
3494*b5893f02SDimitry Andric   // undefined.
3495*b5893f02SDimitry Andric   bool IsCUDAShadowVar =
3496*b5893f02SDimitry Andric       !getLangOpts().CUDAIsDevice &&
3497*b5893f02SDimitry Andric       (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
3498*b5893f02SDimitry Andric        D->hasAttr<CUDASharedAttr>());
3499*b5893f02SDimitry Andric   if (getLangOpts().CUDA && (IsCUDASharedVar || IsCUDAShadowVar))
35000623d748SDimitry Andric     Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
3501e7145dcbSDimitry Andric   else if (!InitExpr) {
3502f22ef01cSRoman Divacky     // This is a tentative definition; tentative definitions are
3503f22ef01cSRoman Divacky     // implicitly initialized with { 0 }.
3504f22ef01cSRoman Divacky     //
3505f22ef01cSRoman Divacky     // Note that tentative definitions are only emitted at the end of
3506f22ef01cSRoman Divacky     // a translation unit, so they should never have incomplete
3507f22ef01cSRoman Divacky     // type. In addition, EmitTentativeDefinition makes sure that we
3508f22ef01cSRoman Divacky     // never attempt to emit a tentative definition if a real one
3509f22ef01cSRoman Divacky     // exists. A use may still exists, however, so we still may need
3510f22ef01cSRoman Divacky     // to do a RAUW.
3511f22ef01cSRoman Divacky     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
3512f22ef01cSRoman Divacky     Init = EmitNullConstant(D->getType());
3513f22ef01cSRoman Divacky   } else {
35147ae0e2c9SDimitry Andric     initializedGlobalDecl = GlobalDecl(D);
35159a199699SDimitry Andric     emitter.emplace(*this);
35169a199699SDimitry Andric     Init = emitter->tryEmitForInitializer(*InitDecl);
3517f785676fSDimitry Andric 
3518f22ef01cSRoman Divacky     if (!Init) {
3519f22ef01cSRoman Divacky       QualType T = InitExpr->getType();
3520f22ef01cSRoman Divacky       if (D->getType()->isReferenceType())
3521f22ef01cSRoman Divacky         T = D->getType();
3522f22ef01cSRoman Divacky 
3523dff0c46cSDimitry Andric       if (getLangOpts().CPlusPlus) {
3524f22ef01cSRoman Divacky         Init = EmitNullConstant(T);
3525dff0c46cSDimitry Andric         NeedsGlobalCtor = true;
3526f22ef01cSRoman Divacky       } else {
3527f22ef01cSRoman Divacky         ErrorUnsupported(D, "static initializer");
3528f22ef01cSRoman Divacky         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
3529f22ef01cSRoman Divacky       }
3530e580952dSDimitry Andric     } else {
3531e580952dSDimitry Andric       // We don't need an initializer, so remove the entry for the delayed
3532dff0c46cSDimitry Andric       // initializer position (just in case this entry was delayed) if we
3533dff0c46cSDimitry Andric       // also don't need to register a destructor.
3534dff0c46cSDimitry Andric       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
3535e580952dSDimitry Andric         DelayedCXXInitPosition.erase(D);
3536f22ef01cSRoman Divacky     }
3537f22ef01cSRoman Divacky   }
3538f22ef01cSRoman Divacky 
35396122f3e6SDimitry Andric   llvm::Type* InitType = Init->getType();
3540e7145dcbSDimitry Andric   llvm::Constant *Entry =
354144290647SDimitry Andric       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
3542f22ef01cSRoman Divacky 
3543f22ef01cSRoman Divacky   // Strip off a bitcast if we got one back.
354459d1ed5bSDimitry Andric   if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
3545f22ef01cSRoman Divacky     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
3546f785676fSDimitry Andric            CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
3547f785676fSDimitry Andric            // All zero index gep.
3548f22ef01cSRoman Divacky            CE->getOpcode() == llvm::Instruction::GetElementPtr);
3549f22ef01cSRoman Divacky     Entry = CE->getOperand(0);
3550f22ef01cSRoman Divacky   }
3551f22ef01cSRoman Divacky 
3552f22ef01cSRoman Divacky   // Entry is now either a Function or GlobalVariable.
355359d1ed5bSDimitry Andric   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
3554f22ef01cSRoman Divacky 
3555f22ef01cSRoman Divacky   // We have a definition after a declaration with the wrong type.
3556f22ef01cSRoman Divacky   // We must make a new GlobalVariable* and update everything that used OldGV
3557f22ef01cSRoman Divacky   // (a declaration or tentative definition) with the new GlobalVariable*
3558f22ef01cSRoman Divacky   // (which will be a definition).
3559f22ef01cSRoman Divacky   //
3560f22ef01cSRoman Divacky   // This happens if there is a prototype for a global (e.g.
3561f22ef01cSRoman Divacky   // "extern int x[];") and then a definition of a different type (e.g.
3562f22ef01cSRoman Divacky   // "int x[10];"). This also happens when an initializer has a different type
3563f22ef01cSRoman Divacky   // from the type of the global (this happens with unions).
3564c4394386SDimitry Andric   if (!GV || GV->getType()->getElementType() != InitType ||
35653b0f4066SDimitry Andric       GV->getType()->getAddressSpace() !=
3566c4394386SDimitry Andric           getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
3567f22ef01cSRoman Divacky 
3568f22ef01cSRoman Divacky     // Move the old entry aside so that we'll create a new one.
35696122f3e6SDimitry Andric     Entry->setName(StringRef());
3570f22ef01cSRoman Divacky 
3571f22ef01cSRoman Divacky     // Make a new global with the correct type, this is now guaranteed to work.
3572e7145dcbSDimitry Andric     GV = cast<llvm::GlobalVariable>(
357344290647SDimitry Andric         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
3574f22ef01cSRoman Divacky 
3575f22ef01cSRoman Divacky     // Replace all uses of the old global with the new global
3576f22ef01cSRoman Divacky     llvm::Constant *NewPtrForOldDecl =
3577f22ef01cSRoman Divacky         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
3578f22ef01cSRoman Divacky     Entry->replaceAllUsesWith(NewPtrForOldDecl);
3579f22ef01cSRoman Divacky 
3580f22ef01cSRoman Divacky     // Erase the old global, since it is no longer used.
3581f22ef01cSRoman Divacky     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
3582f22ef01cSRoman Divacky   }
3583f22ef01cSRoman Divacky 
3584284c1978SDimitry Andric   MaybeHandleStaticInExternC(D, GV);
3585284c1978SDimitry Andric 
35866122f3e6SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
35876122f3e6SDimitry Andric     AddGlobalAnnotations(D, GV);
3588f22ef01cSRoman Divacky 
3589e7145dcbSDimitry Andric   // Set the llvm linkage type as appropriate.
3590e7145dcbSDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
3591e7145dcbSDimitry Andric       getLLVMLinkageVarDefinition(D, GV->isConstant());
3592e7145dcbSDimitry Andric 
35930623d748SDimitry Andric   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
35940623d748SDimitry Andric   // the device. [...]"
35950623d748SDimitry Andric   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
35960623d748SDimitry Andric   // __device__, declares a variable that: [...]
35970623d748SDimitry Andric   // Is accessible from all the threads within the grid and from the host
35980623d748SDimitry Andric   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
35990623d748SDimitry Andric   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
3600e7145dcbSDimitry Andric   if (GV && LangOpts.CUDA) {
3601e7145dcbSDimitry Andric     if (LangOpts.CUDAIsDevice) {
3602e7145dcbSDimitry Andric       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
36030623d748SDimitry Andric         GV->setExternallyInitialized(true);
3604e7145dcbSDimitry Andric     } else {
3605e7145dcbSDimitry Andric       // Host-side shadows of external declarations of device-side
3606e7145dcbSDimitry Andric       // global variables become internal definitions. These have to
3607e7145dcbSDimitry Andric       // be internal in order to prevent name conflicts with global
3608e7145dcbSDimitry Andric       // host variables with the same name in a different TUs.
3609e7145dcbSDimitry Andric       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
3610e7145dcbSDimitry Andric         Linkage = llvm::GlobalValue::InternalLinkage;
3611e7145dcbSDimitry Andric 
3612e7145dcbSDimitry Andric         // Shadow variables and their properties must be registered
3613e7145dcbSDimitry Andric         // with CUDA runtime.
3614e7145dcbSDimitry Andric         unsigned Flags = 0;
3615e7145dcbSDimitry Andric         if (!D->hasDefinition())
3616e7145dcbSDimitry Andric           Flags |= CGCUDARuntime::ExternDeviceVar;
3617e7145dcbSDimitry Andric         if (D->hasAttr<CUDAConstantAttr>())
3618e7145dcbSDimitry Andric           Flags |= CGCUDARuntime::ConstantDeviceVar;
3619*b5893f02SDimitry Andric         // Extern global variables will be registered in the TU where they are
3620*b5893f02SDimitry Andric         // defined.
3621*b5893f02SDimitry Andric         if (!D->hasExternalStorage())
3622e7145dcbSDimitry Andric           getCUDARuntime().registerDeviceVar(*GV, Flags);
3623e7145dcbSDimitry Andric       } else if (D->hasAttr<CUDASharedAttr>())
3624e7145dcbSDimitry Andric         // __shared__ variables are odd. Shadows do get created, but
3625e7145dcbSDimitry Andric         // they are not registered with the CUDA runtime, so they
3626e7145dcbSDimitry Andric         // can't really be used to access their device-side
3627e7145dcbSDimitry Andric         // counterparts. It's not clear yet whether it's nvcc's bug or
3628e7145dcbSDimitry Andric         // a feature, but we've got to do the same for compatibility.
3629e7145dcbSDimitry Andric         Linkage = llvm::GlobalValue::InternalLinkage;
3630e7145dcbSDimitry Andric     }
36310623d748SDimitry Andric   }
36329a199699SDimitry Andric 
3633f22ef01cSRoman Divacky   GV->setInitializer(Init);
36349a199699SDimitry Andric   if (emitter) emitter->finalize(GV);
3635f22ef01cSRoman Divacky 
3636f22ef01cSRoman Divacky   // If it is safe to mark the global 'constant', do so now.
3637dff0c46cSDimitry Andric   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
3638dff0c46cSDimitry Andric                   isTypeConstant(D->getType(), true));
3639f22ef01cSRoman Divacky 
364039d628a0SDimitry Andric   // If it is in a read-only section, mark it 'constant'.
364139d628a0SDimitry Andric   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
364239d628a0SDimitry Andric     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
364339d628a0SDimitry Andric     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
364439d628a0SDimitry Andric       GV->setConstant(true);
364539d628a0SDimitry Andric   }
364639d628a0SDimitry Andric 
3647f22ef01cSRoman Divacky   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
3648f22ef01cSRoman Divacky 
3649f785676fSDimitry Andric 
36500623d748SDimitry Andric   // On Darwin, if the normal linkage of a C++ thread_local variable is
36510623d748SDimitry Andric   // LinkOnce or Weak, we keep the normal linkage to prevent multiple
36520623d748SDimitry Andric   // copies within a linkage unit; otherwise, the backing variable has
36530623d748SDimitry Andric   // internal linkage and all accesses should just be calls to the
365459d1ed5bSDimitry Andric   // Itanium-specified entry point, which has the normal linkage of the
36550623d748SDimitry Andric   // variable. This is to preserve the ability to change the implementation
36560623d748SDimitry Andric   // behind the scenes.
365739d628a0SDimitry Andric   if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
36580623d748SDimitry Andric       Context.getTargetInfo().getTriple().isOSDarwin() &&
36590623d748SDimitry Andric       !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
36600623d748SDimitry Andric       !llvm::GlobalVariable::isWeakLinkage(Linkage))
366159d1ed5bSDimitry Andric     Linkage = llvm::GlobalValue::InternalLinkage;
366259d1ed5bSDimitry Andric 
366359d1ed5bSDimitry Andric   GV->setLinkage(Linkage);
366459d1ed5bSDimitry Andric   if (D->hasAttr<DLLImportAttr>())
366559d1ed5bSDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
366659d1ed5bSDimitry Andric   else if (D->hasAttr<DLLExportAttr>())
366759d1ed5bSDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
366839d628a0SDimitry Andric   else
366939d628a0SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
3670f785676fSDimitry Andric 
367144290647SDimitry Andric   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
3672f22ef01cSRoman Divacky     // common vars aren't constant even if declared const.
3673f22ef01cSRoman Divacky     GV->setConstant(false);
367444290647SDimitry Andric     // Tentative definition of global variables may be initialized with
367544290647SDimitry Andric     // non-zero null pointers. In this case they should have weak linkage
367644290647SDimitry Andric     // since common linkage must have zero initializer and must not have
367744290647SDimitry Andric     // explicit section therefore cannot have non-zero initial value.
367844290647SDimitry Andric     if (!GV->getInitializer()->isNullValue())
367944290647SDimitry Andric       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
368044290647SDimitry Andric   }
3681f22ef01cSRoman Divacky 
368259d1ed5bSDimitry Andric   setNonAliasAttributes(D, GV);
3683f22ef01cSRoman Divacky 
368439d628a0SDimitry Andric   if (D->getTLSKind() && !GV->isThreadLocal()) {
368539d628a0SDimitry Andric     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
36860623d748SDimitry Andric       CXXThreadLocals.push_back(D);
368739d628a0SDimitry Andric     setTLSMode(GV, *D);
368839d628a0SDimitry Andric   }
368939d628a0SDimitry Andric 
369033956c43SDimitry Andric   maybeSetTrivialComdat(*D, *GV);
369133956c43SDimitry Andric 
36922754fe60SDimitry Andric   // Emit the initializer function if necessary.
3693dff0c46cSDimitry Andric   if (NeedsGlobalCtor || NeedsGlobalDtor)
3694dff0c46cSDimitry Andric     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
36952754fe60SDimitry Andric 
369639d628a0SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
36973861d79fSDimitry Andric 
3698f22ef01cSRoman Divacky   // Emit global variable debug information.
36996122f3e6SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
3700e7145dcbSDimitry Andric     if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
3701f22ef01cSRoman Divacky       DI->EmitGlobalVariable(GV, D);
3702f22ef01cSRoman Divacky }
3703f22ef01cSRoman Divacky 
isVarDeclStrongDefinition(const ASTContext & Context,CodeGenModule & CGM,const VarDecl * D,bool NoCommon)370439d628a0SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context,
370533956c43SDimitry Andric                                       CodeGenModule &CGM, const VarDecl *D,
370633956c43SDimitry Andric                                       bool NoCommon) {
370759d1ed5bSDimitry Andric   // Don't give variables common linkage if -fno-common was specified unless it
370859d1ed5bSDimitry Andric   // was overridden by a NoCommon attribute.
370959d1ed5bSDimitry Andric   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
371059d1ed5bSDimitry Andric     return true;
371159d1ed5bSDimitry Andric 
371259d1ed5bSDimitry Andric   // C11 6.9.2/2:
371359d1ed5bSDimitry Andric   //   A declaration of an identifier for an object that has file scope without
371459d1ed5bSDimitry Andric   //   an initializer, and without a storage-class specifier or with the
371559d1ed5bSDimitry Andric   //   storage-class specifier static, constitutes a tentative definition.
371659d1ed5bSDimitry Andric   if (D->getInit() || D->hasExternalStorage())
371759d1ed5bSDimitry Andric     return true;
371859d1ed5bSDimitry Andric 
371959d1ed5bSDimitry Andric   // A variable cannot be both common and exist in a section.
372059d1ed5bSDimitry Andric   if (D->hasAttr<SectionAttr>())
372159d1ed5bSDimitry Andric     return true;
372259d1ed5bSDimitry Andric 
3723db17bf38SDimitry Andric   // A variable cannot be both common and exist in a section.
37244ba319b5SDimitry Andric   // We don't try to determine which is the right section in the front-end.
3725db17bf38SDimitry Andric   // If no specialized section name is applicable, it will resort to default.
3726db17bf38SDimitry Andric   if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
3727db17bf38SDimitry Andric       D->hasAttr<PragmaClangDataSectionAttr>() ||
3728db17bf38SDimitry Andric       D->hasAttr<PragmaClangRodataSectionAttr>())
3729db17bf38SDimitry Andric     return true;
3730db17bf38SDimitry Andric 
373159d1ed5bSDimitry Andric   // Thread local vars aren't considered common linkage.
373259d1ed5bSDimitry Andric   if (D->getTLSKind())
373359d1ed5bSDimitry Andric     return true;
373459d1ed5bSDimitry Andric 
373559d1ed5bSDimitry Andric   // Tentative definitions marked with WeakImportAttr are true definitions.
373659d1ed5bSDimitry Andric   if (D->hasAttr<WeakImportAttr>())
373759d1ed5bSDimitry Andric     return true;
373859d1ed5bSDimitry Andric 
373933956c43SDimitry Andric   // A variable cannot be both common and exist in a comdat.
374033956c43SDimitry Andric   if (shouldBeInCOMDAT(CGM, *D))
374133956c43SDimitry Andric     return true;
374233956c43SDimitry Andric 
3743e7145dcbSDimitry Andric   // Declarations with a required alignment do not have common linkage in MSVC
374439d628a0SDimitry Andric   // mode.
37450623d748SDimitry Andric   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
374633956c43SDimitry Andric     if (D->hasAttr<AlignedAttr>())
374739d628a0SDimitry Andric       return true;
374833956c43SDimitry Andric     QualType VarType = D->getType();
374933956c43SDimitry Andric     if (Context.isAlignmentRequired(VarType))
375033956c43SDimitry Andric       return true;
375133956c43SDimitry Andric 
375233956c43SDimitry Andric     if (const auto *RT = VarType->getAs<RecordType>()) {
375333956c43SDimitry Andric       const RecordDecl *RD = RT->getDecl();
375433956c43SDimitry Andric       for (const FieldDecl *FD : RD->fields()) {
375533956c43SDimitry Andric         if (FD->isBitField())
375633956c43SDimitry Andric           continue;
375733956c43SDimitry Andric         if (FD->hasAttr<AlignedAttr>())
375833956c43SDimitry Andric           return true;
375933956c43SDimitry Andric         if (Context.isAlignmentRequired(FD->getType()))
376033956c43SDimitry Andric           return true;
376133956c43SDimitry Andric       }
376233956c43SDimitry Andric     }
376333956c43SDimitry Andric   }
376439d628a0SDimitry Andric 
3765*b5893f02SDimitry Andric   // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
3766*b5893f02SDimitry Andric   // common symbols, so symbols with greater alignment requirements cannot be
3767*b5893f02SDimitry Andric   // common.
3768*b5893f02SDimitry Andric   // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
3769*b5893f02SDimitry Andric   // alignments for common symbols via the aligncomm directive, so this
3770*b5893f02SDimitry Andric   // restriction only applies to MSVC environments.
3771*b5893f02SDimitry Andric   if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
3772*b5893f02SDimitry Andric       Context.getTypeAlignIfKnown(D->getType()) >
3773*b5893f02SDimitry Andric           Context.toBits(CharUnits::fromQuantity(32)))
3774*b5893f02SDimitry Andric     return true;
3775*b5893f02SDimitry Andric 
377659d1ed5bSDimitry Andric   return false;
377759d1ed5bSDimitry Andric }
377859d1ed5bSDimitry Andric 
getLLVMLinkageForDeclarator(const DeclaratorDecl * D,GVALinkage Linkage,bool IsConstantVariable)377959d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
378059d1ed5bSDimitry Andric     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
37812754fe60SDimitry Andric   if (Linkage == GVA_Internal)
37822754fe60SDimitry Andric     return llvm::Function::InternalLinkage;
378359d1ed5bSDimitry Andric 
378459d1ed5bSDimitry Andric   if (D->hasAttr<WeakAttr>()) {
378559d1ed5bSDimitry Andric     if (IsConstantVariable)
378659d1ed5bSDimitry Andric       return llvm::GlobalVariable::WeakODRLinkage;
378759d1ed5bSDimitry Andric     else
378859d1ed5bSDimitry Andric       return llvm::GlobalVariable::WeakAnyLinkage;
378959d1ed5bSDimitry Andric   }
379059d1ed5bSDimitry Andric 
3791*b5893f02SDimitry Andric   if (const auto *FD = D->getAsFunction())
3792*b5893f02SDimitry Andric     if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
3793*b5893f02SDimitry Andric       return llvm::GlobalVariable::LinkOnceAnyLinkage;
3794*b5893f02SDimitry Andric 
379559d1ed5bSDimitry Andric   // We are guaranteed to have a strong definition somewhere else,
379659d1ed5bSDimitry Andric   // so we can use available_externally linkage.
379759d1ed5bSDimitry Andric   if (Linkage == GVA_AvailableExternally)
379820e90f04SDimitry Andric     return llvm::GlobalValue::AvailableExternallyLinkage;
379959d1ed5bSDimitry Andric 
380059d1ed5bSDimitry Andric   // Note that Apple's kernel linker doesn't support symbol
380159d1ed5bSDimitry Andric   // coalescing, so we need to avoid linkonce and weak linkages there.
380259d1ed5bSDimitry Andric   // Normally, this means we just map to internal, but for explicit
380359d1ed5bSDimitry Andric   // instantiations we'll map to external.
380459d1ed5bSDimitry Andric 
380559d1ed5bSDimitry Andric   // In C++, the compiler has to emit a definition in every translation unit
380659d1ed5bSDimitry Andric   // that references the function.  We should use linkonce_odr because
380759d1ed5bSDimitry Andric   // a) if all references in this translation unit are optimized away, we
380859d1ed5bSDimitry Andric   // don't need to codegen it.  b) if the function persists, it needs to be
380959d1ed5bSDimitry Andric   // merged with other definitions. c) C++ has the ODR, so we know the
381059d1ed5bSDimitry Andric   // definition is dependable.
381159d1ed5bSDimitry Andric   if (Linkage == GVA_DiscardableODR)
381259d1ed5bSDimitry Andric     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
381359d1ed5bSDimitry Andric                                             : llvm::Function::InternalLinkage;
381459d1ed5bSDimitry Andric 
381559d1ed5bSDimitry Andric   // An explicit instantiation of a template has weak linkage, since
381659d1ed5bSDimitry Andric   // explicit instantiations can occur in multiple translation units
381759d1ed5bSDimitry Andric   // and must all be equivalent. However, we are not allowed to
381859d1ed5bSDimitry Andric   // throw away these explicit instantiations.
3819e7145dcbSDimitry Andric   //
3820e7145dcbSDimitry Andric   // We don't currently support CUDA device code spread out across multiple TUs,
3821e7145dcbSDimitry Andric   // so say that CUDA templates are either external (for kernels) or internal.
3822e7145dcbSDimitry Andric   // This lets llvm perform aggressive inter-procedural optimizations.
3823e7145dcbSDimitry Andric   if (Linkage == GVA_StrongODR) {
3824e7145dcbSDimitry Andric     if (Context.getLangOpts().AppleKext)
3825e7145dcbSDimitry Andric       return llvm::Function::ExternalLinkage;
3826e7145dcbSDimitry Andric     if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
3827e7145dcbSDimitry Andric       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
3828e7145dcbSDimitry Andric                                           : llvm::Function::InternalLinkage;
3829e7145dcbSDimitry Andric     return llvm::Function::WeakODRLinkage;
3830e7145dcbSDimitry Andric   }
383159d1ed5bSDimitry Andric 
383259d1ed5bSDimitry Andric   // C++ doesn't have tentative definitions and thus cannot have common
383359d1ed5bSDimitry Andric   // linkage.
383459d1ed5bSDimitry Andric   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
383533956c43SDimitry Andric       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
383639d628a0SDimitry Andric                                  CodeGenOpts.NoCommon))
383759d1ed5bSDimitry Andric     return llvm::GlobalVariable::CommonLinkage;
383859d1ed5bSDimitry Andric 
3839f785676fSDimitry Andric   // selectany symbols are externally visible, so use weak instead of
3840f785676fSDimitry Andric   // linkonce.  MSVC optimizes away references to const selectany globals, so
3841f785676fSDimitry Andric   // all definitions should be the same and ODR linkage should be used.
3842f785676fSDimitry Andric   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
384359d1ed5bSDimitry Andric   if (D->hasAttr<SelectAnyAttr>())
3844f785676fSDimitry Andric     return llvm::GlobalVariable::WeakODRLinkage;
384559d1ed5bSDimitry Andric 
384659d1ed5bSDimitry Andric   // Otherwise, we have strong external linkage.
384759d1ed5bSDimitry Andric   assert(Linkage == GVA_StrongExternal);
38482754fe60SDimitry Andric   return llvm::GlobalVariable::ExternalLinkage;
38492754fe60SDimitry Andric }
38502754fe60SDimitry Andric 
getLLVMLinkageVarDefinition(const VarDecl * VD,bool IsConstant)385159d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
385259d1ed5bSDimitry Andric     const VarDecl *VD, bool IsConstant) {
385359d1ed5bSDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
385459d1ed5bSDimitry Andric   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
385559d1ed5bSDimitry Andric }
385659d1ed5bSDimitry Andric 
3857139f7f9bSDimitry Andric /// Replace the uses of a function that was declared with a non-proto type.
3858139f7f9bSDimitry Andric /// We want to silently drop extra arguments from call sites
replaceUsesOfNonProtoConstant(llvm::Constant * old,llvm::Function * newFn)3859139f7f9bSDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
3860139f7f9bSDimitry Andric                                           llvm::Function *newFn) {
3861139f7f9bSDimitry Andric   // Fast path.
3862139f7f9bSDimitry Andric   if (old->use_empty()) return;
3863139f7f9bSDimitry Andric 
3864139f7f9bSDimitry Andric   llvm::Type *newRetTy = newFn->getReturnType();
3865139f7f9bSDimitry Andric   SmallVector<llvm::Value*, 4> newArgs;
38660623d748SDimitry Andric   SmallVector<llvm::OperandBundleDef, 1> newBundles;
3867139f7f9bSDimitry Andric 
3868139f7f9bSDimitry Andric   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
3869139f7f9bSDimitry Andric          ui != ue; ) {
3870139f7f9bSDimitry Andric     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
387159d1ed5bSDimitry Andric     llvm::User *user = use->getUser();
3872139f7f9bSDimitry Andric 
3873139f7f9bSDimitry Andric     // Recognize and replace uses of bitcasts.  Most calls to
3874139f7f9bSDimitry Andric     // unprototyped functions will use bitcasts.
387559d1ed5bSDimitry Andric     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
3876139f7f9bSDimitry Andric       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
3877139f7f9bSDimitry Andric         replaceUsesOfNonProtoConstant(bitcast, newFn);
3878139f7f9bSDimitry Andric       continue;
3879139f7f9bSDimitry Andric     }
3880139f7f9bSDimitry Andric 
3881139f7f9bSDimitry Andric     // Recognize calls to the function.
3882139f7f9bSDimitry Andric     llvm::CallSite callSite(user);
3883139f7f9bSDimitry Andric     if (!callSite) continue;
388459d1ed5bSDimitry Andric     if (!callSite.isCallee(&*use)) continue;
3885139f7f9bSDimitry Andric 
3886139f7f9bSDimitry Andric     // If the return types don't match exactly, then we can't
3887139f7f9bSDimitry Andric     // transform this call unless it's dead.
3888139f7f9bSDimitry Andric     if (callSite->getType() != newRetTy && !callSite->use_empty())
3889139f7f9bSDimitry Andric       continue;
3890139f7f9bSDimitry Andric 
3891139f7f9bSDimitry Andric     // Get the call site's attribute list.
389220e90f04SDimitry Andric     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
389320e90f04SDimitry Andric     llvm::AttributeList oldAttrs = callSite.getAttributes();
3894139f7f9bSDimitry Andric 
3895139f7f9bSDimitry Andric     // If the function was passed too few arguments, don't transform.
3896139f7f9bSDimitry Andric     unsigned newNumArgs = newFn->arg_size();
3897139f7f9bSDimitry Andric     if (callSite.arg_size() < newNumArgs) continue;
3898139f7f9bSDimitry Andric 
3899139f7f9bSDimitry Andric     // If extra arguments were passed, we silently drop them.
3900139f7f9bSDimitry Andric     // If any of the types mismatch, we don't transform.
3901139f7f9bSDimitry Andric     unsigned argNo = 0;
3902139f7f9bSDimitry Andric     bool dontTransform = false;
390320e90f04SDimitry Andric     for (llvm::Argument &A : newFn->args()) {
390420e90f04SDimitry Andric       if (callSite.getArgument(argNo)->getType() != A.getType()) {
3905139f7f9bSDimitry Andric         dontTransform = true;
3906139f7f9bSDimitry Andric         break;
3907139f7f9bSDimitry Andric       }
3908139f7f9bSDimitry Andric 
3909139f7f9bSDimitry Andric       // Add any parameter attributes.
391020e90f04SDimitry Andric       newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
391120e90f04SDimitry Andric       argNo++;
3912139f7f9bSDimitry Andric     }
3913139f7f9bSDimitry Andric     if (dontTransform)
3914139f7f9bSDimitry Andric       continue;
3915139f7f9bSDimitry Andric 
3916139f7f9bSDimitry Andric     // Okay, we can transform this.  Create the new call instruction and copy
3917139f7f9bSDimitry Andric     // over the required information.
3918139f7f9bSDimitry Andric     newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
3919139f7f9bSDimitry Andric 
39200623d748SDimitry Andric     // Copy over any operand bundles.
39210623d748SDimitry Andric     callSite.getOperandBundlesAsDefs(newBundles);
39220623d748SDimitry Andric 
3923139f7f9bSDimitry Andric     llvm::CallSite newCall;
3924139f7f9bSDimitry Andric     if (callSite.isCall()) {
39250623d748SDimitry Andric       newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
3926139f7f9bSDimitry Andric                                        callSite.getInstruction());
3927139f7f9bSDimitry Andric     } else {
392859d1ed5bSDimitry Andric       auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
3929139f7f9bSDimitry Andric       newCall = llvm::InvokeInst::Create(newFn,
3930139f7f9bSDimitry Andric                                          oldInvoke->getNormalDest(),
3931139f7f9bSDimitry Andric                                          oldInvoke->getUnwindDest(),
39320623d748SDimitry Andric                                          newArgs, newBundles, "",
3933139f7f9bSDimitry Andric                                          callSite.getInstruction());
3934139f7f9bSDimitry Andric     }
3935139f7f9bSDimitry Andric     newArgs.clear(); // for the next iteration
3936139f7f9bSDimitry Andric 
3937139f7f9bSDimitry Andric     if (!newCall->getType()->isVoidTy())
3938139f7f9bSDimitry Andric       newCall->takeName(callSite.getInstruction());
393920e90f04SDimitry Andric     newCall.setAttributes(llvm::AttributeList::get(
394020e90f04SDimitry Andric         newFn->getContext(), oldAttrs.getFnAttributes(),
394120e90f04SDimitry Andric         oldAttrs.getRetAttributes(), newArgAttrs));
3942139f7f9bSDimitry Andric     newCall.setCallingConv(callSite.getCallingConv());
3943139f7f9bSDimitry Andric 
3944139f7f9bSDimitry Andric     // Finally, remove the old call, replacing any uses with the new one.
3945139f7f9bSDimitry Andric     if (!callSite->use_empty())
3946139f7f9bSDimitry Andric       callSite->replaceAllUsesWith(newCall.getInstruction());
3947139f7f9bSDimitry Andric 
3948139f7f9bSDimitry Andric     // Copy debug location attached to CI.
394933956c43SDimitry Andric     if (callSite->getDebugLoc())
3950139f7f9bSDimitry Andric       newCall->setDebugLoc(callSite->getDebugLoc());
39510623d748SDimitry Andric 
3952139f7f9bSDimitry Andric     callSite->eraseFromParent();
3953139f7f9bSDimitry Andric   }
3954139f7f9bSDimitry Andric }
3955139f7f9bSDimitry Andric 
3956f22ef01cSRoman Divacky /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
3957f22ef01cSRoman Divacky /// implement a function with no prototype, e.g. "int foo() {}".  If there are
3958f22ef01cSRoman Divacky /// existing call uses of the old function in the module, this adjusts them to
3959f22ef01cSRoman Divacky /// call the new function directly.
3960f22ef01cSRoman Divacky ///
3961f22ef01cSRoman Divacky /// This is not just a cleanup: the always_inline pass requires direct calls to
3962f22ef01cSRoman Divacky /// functions to be able to inline them.  If there is a bitcast in the way, it
3963f22ef01cSRoman Divacky /// won't inline them.  Instcombine normally deletes these calls, but it isn't
3964f22ef01cSRoman Divacky /// run at -O0.
ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue * Old,llvm::Function * NewFn)3965f22ef01cSRoman Divacky static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3966f22ef01cSRoman Divacky                                                       llvm::Function *NewFn) {
3967f22ef01cSRoman Divacky   // If we're redefining a global as a function, don't transform it.
3968139f7f9bSDimitry Andric   if (!isa<llvm::Function>(Old)) return;
3969f22ef01cSRoman Divacky 
3970139f7f9bSDimitry Andric   replaceUsesOfNonProtoConstant(Old, NewFn);
3971f22ef01cSRoman Divacky }
3972f22ef01cSRoman Divacky 
HandleCXXStaticMemberVarInstantiation(VarDecl * VD)3973dff0c46cSDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
3974e7145dcbSDimitry Andric   auto DK = VD->isThisDeclarationADefinition();
3975e7145dcbSDimitry Andric   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
3976e7145dcbSDimitry Andric     return;
3977e7145dcbSDimitry Andric 
3978dff0c46cSDimitry Andric   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
3979dff0c46cSDimitry Andric   // If we have a definition, this might be a deferred decl. If the
3980dff0c46cSDimitry Andric   // instantiation is explicit, make sure we emit it at the end.
3981dff0c46cSDimitry Andric   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
3982dff0c46cSDimitry Andric     GetAddrOfGlobalVar(VD);
3983139f7f9bSDimitry Andric 
3984139f7f9bSDimitry Andric   EmitTopLevelDecl(VD);
3985dff0c46cSDimitry Andric }
3986f22ef01cSRoman Divacky 
EmitGlobalFunctionDefinition(GlobalDecl GD,llvm::GlobalValue * GV)398759d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
398859d1ed5bSDimitry Andric                                                  llvm::GlobalValue *GV) {
398959d1ed5bSDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
39903b0f4066SDimitry Andric 
39913b0f4066SDimitry Andric   // Compute the function info and LLVM type.
3992dff0c46cSDimitry Andric   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3993dff0c46cSDimitry Andric   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
39943b0f4066SDimitry Andric 
3995f22ef01cSRoman Divacky   // Get or create the prototype for the function.
39960623d748SDimitry Andric   if (!GV || (GV->getType()->getElementType() != Ty))
39970623d748SDimitry Andric     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
39980623d748SDimitry Andric                                                    /*DontDefer=*/true,
399944290647SDimitry Andric                                                    ForDefinition));
4000f22ef01cSRoman Divacky 
40010623d748SDimitry Andric   // Already emitted.
40020623d748SDimitry Andric   if (!GV->isDeclaration())
4003f785676fSDimitry Andric     return;
4004f22ef01cSRoman Divacky 
40052754fe60SDimitry Andric   // We need to set linkage and visibility on the function before
40062754fe60SDimitry Andric   // generating code for it because various parts of IR generation
40072754fe60SDimitry Andric   // want to propagate this information down (e.g. to local static
40082754fe60SDimitry Andric   // declarations).
400959d1ed5bSDimitry Andric   auto *Fn = cast<llvm::Function>(GV);
4010f785676fSDimitry Andric   setFunctionLinkage(GD, Fn);
4011f22ef01cSRoman Divacky 
401259d1ed5bSDimitry Andric   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
40134ba319b5SDimitry Andric   setGVProperties(Fn, GD);
40142754fe60SDimitry Andric 
4015284c1978SDimitry Andric   MaybeHandleStaticInExternC(D, Fn);
4016284c1978SDimitry Andric 
40174ba319b5SDimitry Andric 
401833956c43SDimitry Andric   maybeSetTrivialComdat(*D, *Fn);
401933956c43SDimitry Andric 
40203b0f4066SDimitry Andric   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
4021f22ef01cSRoman Divacky 
40224ba319b5SDimitry Andric   setNonAliasAttributes(GD, Fn);
4023f22ef01cSRoman Divacky   SetLLVMFunctionAttributesForDefinition(D, Fn);
4024f22ef01cSRoman Divacky 
4025f22ef01cSRoman Divacky   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
4026f22ef01cSRoman Divacky     AddGlobalCtor(Fn, CA->getPriority());
4027f22ef01cSRoman Divacky   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
4028f22ef01cSRoman Divacky     AddGlobalDtor(Fn, DA->getPriority());
40296122f3e6SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
40306122f3e6SDimitry Andric     AddGlobalAnnotations(D, Fn);
4031f22ef01cSRoman Divacky }
4032f22ef01cSRoman Divacky 
EmitAliasDefinition(GlobalDecl GD)4033f22ef01cSRoman Divacky void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
403459d1ed5bSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
4035f22ef01cSRoman Divacky   const AliasAttr *AA = D->getAttr<AliasAttr>();
4036f22ef01cSRoman Divacky   assert(AA && "Not an alias?");
4037f22ef01cSRoman Divacky 
40386122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
4039f22ef01cSRoman Divacky 
40409a4b3118SDimitry Andric   if (AA->getAliasee() == MangledName) {
4041e7145dcbSDimitry Andric     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
40429a4b3118SDimitry Andric     return;
40439a4b3118SDimitry Andric   }
40449a4b3118SDimitry Andric 
4045f22ef01cSRoman Divacky   // If there is a definition in the module, then it wins over the alias.
4046f22ef01cSRoman Divacky   // This is dubious, but allow it to be safe.  Just ignore the alias.
4047f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4048f22ef01cSRoman Divacky   if (Entry && !Entry->isDeclaration())
4049f22ef01cSRoman Divacky     return;
4050f22ef01cSRoman Divacky 
4051f785676fSDimitry Andric   Aliases.push_back(GD);
4052f785676fSDimitry Andric 
40536122f3e6SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
4054f22ef01cSRoman Divacky 
4055f22ef01cSRoman Divacky   // Create a reference to the named value.  This ensures that it is emitted
4056f22ef01cSRoman Divacky   // if a deferred decl.
4057f22ef01cSRoman Divacky   llvm::Constant *Aliasee;
4058f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(DeclTy))
40593861d79fSDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
40602754fe60SDimitry Andric                                       /*ForVTable=*/false);
4061f22ef01cSRoman Divacky   else
4062f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
406359d1ed5bSDimitry Andric                                     llvm::PointerType::getUnqual(DeclTy),
406439d628a0SDimitry Andric                                     /*D=*/nullptr);
4065f22ef01cSRoman Divacky 
4066f22ef01cSRoman Divacky   // Create the new alias itself, but don't set a name yet.
406759d1ed5bSDimitry Andric   auto *GA = llvm::GlobalAlias::create(
40680623d748SDimitry Andric       DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
4069f22ef01cSRoman Divacky 
4070f22ef01cSRoman Divacky   if (Entry) {
407159d1ed5bSDimitry Andric     if (GA->getAliasee() == Entry) {
4072e7145dcbSDimitry Andric       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
407359d1ed5bSDimitry Andric       return;
407459d1ed5bSDimitry Andric     }
407559d1ed5bSDimitry Andric 
4076f22ef01cSRoman Divacky     assert(Entry->isDeclaration());
4077f22ef01cSRoman Divacky 
4078f22ef01cSRoman Divacky     // If there is a declaration in the module, then we had an extern followed
4079f22ef01cSRoman Divacky     // by the alias, as in:
4080f22ef01cSRoman Divacky     //   extern int test6();
4081f22ef01cSRoman Divacky     //   ...
4082f22ef01cSRoman Divacky     //   int test6() __attribute__((alias("test7")));
4083f22ef01cSRoman Divacky     //
4084f22ef01cSRoman Divacky     // Remove it and replace uses of it with the alias.
4085f22ef01cSRoman Divacky     GA->takeName(Entry);
4086f22ef01cSRoman Divacky 
4087f22ef01cSRoman Divacky     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
4088f22ef01cSRoman Divacky                                                           Entry->getType()));
4089f22ef01cSRoman Divacky     Entry->eraseFromParent();
4090f22ef01cSRoman Divacky   } else {
4091ffd1746dSEd Schouten     GA->setName(MangledName);
4092f22ef01cSRoman Divacky   }
4093f22ef01cSRoman Divacky 
4094f22ef01cSRoman Divacky   // Set attributes which are particular to an alias; this is a
4095f22ef01cSRoman Divacky   // specialization of the attributes which may be set on a global
4096f22ef01cSRoman Divacky   // variable/function.
409739d628a0SDimitry Andric   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
40983b0f4066SDimitry Andric       D->isWeakImported()) {
4099f22ef01cSRoman Divacky     GA->setLinkage(llvm::Function::WeakAnyLinkage);
4100f22ef01cSRoman Divacky   }
4101f22ef01cSRoman Divacky 
410239d628a0SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
410339d628a0SDimitry Andric     if (VD->getTLSKind())
410439d628a0SDimitry Andric       setTLSMode(GA, *VD);
410539d628a0SDimitry Andric 
41064ba319b5SDimitry Andric   SetCommonAttributes(GD, GA);
4107f22ef01cSRoman Divacky }
4108f22ef01cSRoman Divacky 
emitIFuncDefinition(GlobalDecl GD)4109e7145dcbSDimitry Andric void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
4110e7145dcbSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
4111e7145dcbSDimitry Andric   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
4112e7145dcbSDimitry Andric   assert(IFA && "Not an ifunc?");
4113e7145dcbSDimitry Andric 
4114e7145dcbSDimitry Andric   StringRef MangledName = getMangledName(GD);
4115e7145dcbSDimitry Andric 
4116e7145dcbSDimitry Andric   if (IFA->getResolver() == MangledName) {
4117e7145dcbSDimitry Andric     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4118e7145dcbSDimitry Andric     return;
4119e7145dcbSDimitry Andric   }
4120e7145dcbSDimitry Andric 
4121e7145dcbSDimitry Andric   // Report an error if some definition overrides ifunc.
4122e7145dcbSDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4123e7145dcbSDimitry Andric   if (Entry && !Entry->isDeclaration()) {
4124e7145dcbSDimitry Andric     GlobalDecl OtherGD;
4125e7145dcbSDimitry Andric     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
4126e7145dcbSDimitry Andric         DiagnosedConflictingDefinitions.insert(GD).second) {
41274ba319b5SDimitry Andric       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
41284ba319b5SDimitry Andric           << MangledName;
4129e7145dcbSDimitry Andric       Diags.Report(OtherGD.getDecl()->getLocation(),
4130e7145dcbSDimitry Andric                    diag::note_previous_definition);
4131e7145dcbSDimitry Andric     }
4132e7145dcbSDimitry Andric     return;
4133e7145dcbSDimitry Andric   }
4134e7145dcbSDimitry Andric 
4135e7145dcbSDimitry Andric   Aliases.push_back(GD);
4136e7145dcbSDimitry Andric 
4137e7145dcbSDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
4138e7145dcbSDimitry Andric   llvm::Constant *Resolver =
4139e7145dcbSDimitry Andric       GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
4140e7145dcbSDimitry Andric                               /*ForVTable=*/false);
4141e7145dcbSDimitry Andric   llvm::GlobalIFunc *GIF =
4142e7145dcbSDimitry Andric       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
4143e7145dcbSDimitry Andric                                 "", Resolver, &getModule());
4144e7145dcbSDimitry Andric   if (Entry) {
4145e7145dcbSDimitry Andric     if (GIF->getResolver() == Entry) {
4146e7145dcbSDimitry Andric       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4147e7145dcbSDimitry Andric       return;
4148e7145dcbSDimitry Andric     }
4149e7145dcbSDimitry Andric     assert(Entry->isDeclaration());
4150e7145dcbSDimitry Andric 
4151e7145dcbSDimitry Andric     // If there is a declaration in the module, then we had an extern followed
4152e7145dcbSDimitry Andric     // by the ifunc, as in:
4153e7145dcbSDimitry Andric     //   extern int test();
4154e7145dcbSDimitry Andric     //   ...
4155e7145dcbSDimitry Andric     //   int test() __attribute__((ifunc("resolver")));
4156e7145dcbSDimitry Andric     //
4157e7145dcbSDimitry Andric     // Remove it and replace uses of it with the ifunc.
4158e7145dcbSDimitry Andric     GIF->takeName(Entry);
4159e7145dcbSDimitry Andric 
4160e7145dcbSDimitry Andric     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
4161e7145dcbSDimitry Andric                                                           Entry->getType()));
4162e7145dcbSDimitry Andric     Entry->eraseFromParent();
4163e7145dcbSDimitry Andric   } else
4164e7145dcbSDimitry Andric     GIF->setName(MangledName);
4165e7145dcbSDimitry Andric 
41664ba319b5SDimitry Andric   SetCommonAttributes(GD, GIF);
4167e7145dcbSDimitry Andric }
4168e7145dcbSDimitry Andric 
getIntrinsic(unsigned IID,ArrayRef<llvm::Type * > Tys)416917a519f9SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
41706122f3e6SDimitry Andric                                             ArrayRef<llvm::Type*> Tys) {
417117a519f9SDimitry Andric   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
417217a519f9SDimitry Andric                                          Tys);
4173f22ef01cSRoman Divacky }
4174f22ef01cSRoman Divacky 
417533956c43SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> &
GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable * > & Map,const StringLiteral * Literal,bool TargetIsLSB,bool & IsUTF16,unsigned & StringLength)417633956c43SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
417733956c43SDimitry Andric                          const StringLiteral *Literal, bool TargetIsLSB,
417833956c43SDimitry Andric                          bool &IsUTF16, unsigned &StringLength) {
41796122f3e6SDimitry Andric   StringRef String = Literal->getString();
4180e580952dSDimitry Andric   unsigned NumBytes = String.size();
4181f22ef01cSRoman Divacky 
4182f22ef01cSRoman Divacky   // Check for simple case.
4183f22ef01cSRoman Divacky   if (!Literal->containsNonAsciiOrNull()) {
4184f22ef01cSRoman Divacky     StringLength = NumBytes;
418539d628a0SDimitry Andric     return *Map.insert(std::make_pair(String, nullptr)).first;
4186f22ef01cSRoman Divacky   }
4187f22ef01cSRoman Divacky 
4188dff0c46cSDimitry Andric   // Otherwise, convert the UTF8 literals into a string of shorts.
4189dff0c46cSDimitry Andric   IsUTF16 = true;
4190dff0c46cSDimitry Andric 
419144290647SDimitry Andric   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
419244290647SDimitry Andric   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
419344290647SDimitry Andric   llvm::UTF16 *ToPtr = &ToBuf[0];
4194f22ef01cSRoman Divacky 
419544290647SDimitry Andric   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
419644290647SDimitry Andric                                  ToPtr + NumBytes, llvm::strictConversion);
4197f22ef01cSRoman Divacky 
4198f22ef01cSRoman Divacky   // ConvertUTF8toUTF16 returns the length in ToPtr.
4199f22ef01cSRoman Divacky   StringLength = ToPtr - &ToBuf[0];
4200f22ef01cSRoman Divacky 
4201dff0c46cSDimitry Andric   // Add an explicit null.
4202dff0c46cSDimitry Andric   *ToPtr = 0;
420339d628a0SDimitry Andric   return *Map.insert(std::make_pair(
420439d628a0SDimitry Andric                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
420539d628a0SDimitry Andric                                    (StringLength + 1) * 2),
420639d628a0SDimitry Andric                          nullptr)).first;
4207f22ef01cSRoman Divacky }
4208f22ef01cSRoman Divacky 
42090623d748SDimitry Andric ConstantAddress
GetAddrOfConstantCFString(const StringLiteral * Literal)4210f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
4211f22ef01cSRoman Divacky   unsigned StringLength = 0;
4212f22ef01cSRoman Divacky   bool isUTF16 = false;
421333956c43SDimitry Andric   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
4214f22ef01cSRoman Divacky       GetConstantCFStringEntry(CFConstantStringMap, Literal,
421533956c43SDimitry Andric                                getDataLayout().isLittleEndian(), isUTF16,
421633956c43SDimitry Andric                                StringLength);
4217f22ef01cSRoman Divacky 
421839d628a0SDimitry Andric   if (auto *C = Entry.second)
42190623d748SDimitry Andric     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
4220f22ef01cSRoman Divacky 
4221dff0c46cSDimitry Andric   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
4222f22ef01cSRoman Divacky   llvm::Constant *Zeros[] = { Zero, Zero };
4223f22ef01cSRoman Divacky 
4224*b5893f02SDimitry Andric   const ASTContext &Context = getContext();
4225*b5893f02SDimitry Andric   const llvm::Triple &Triple = getTriple();
4226*b5893f02SDimitry Andric 
4227*b5893f02SDimitry Andric   const auto CFRuntime = getLangOpts().CFRuntime;
4228*b5893f02SDimitry Andric   const bool IsSwiftABI =
4229*b5893f02SDimitry Andric       static_cast<unsigned>(CFRuntime) >=
4230*b5893f02SDimitry Andric       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
4231*b5893f02SDimitry Andric   const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
4232*b5893f02SDimitry Andric 
4233f22ef01cSRoman Divacky   // If we don't already have it, get __CFConstantStringClassReference.
4234f22ef01cSRoman Divacky   if (!CFConstantStringClassRef) {
4235*b5893f02SDimitry Andric     const char *CFConstantStringClassName = "__CFConstantStringClassReference";
42366122f3e6SDimitry Andric     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
4237f22ef01cSRoman Divacky     Ty = llvm::ArrayType::get(Ty, 0);
4238e7145dcbSDimitry Andric 
4239*b5893f02SDimitry Andric     switch (CFRuntime) {
4240*b5893f02SDimitry Andric     default: break;
4241*b5893f02SDimitry Andric     case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH;
4242*b5893f02SDimitry Andric     case LangOptions::CoreFoundationABI::Swift5_0:
4243*b5893f02SDimitry Andric       CFConstantStringClassName =
4244*b5893f02SDimitry Andric           Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
4245*b5893f02SDimitry Andric                               : "$s10Foundation19_NSCFConstantStringCN";
4246*b5893f02SDimitry Andric       Ty = IntPtrTy;
4247*b5893f02SDimitry Andric       break;
4248*b5893f02SDimitry Andric     case LangOptions::CoreFoundationABI::Swift4_2:
4249*b5893f02SDimitry Andric       CFConstantStringClassName =
4250*b5893f02SDimitry Andric           Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
4251*b5893f02SDimitry Andric                               : "$S10Foundation19_NSCFConstantStringCN";
4252*b5893f02SDimitry Andric       Ty = IntPtrTy;
4253*b5893f02SDimitry Andric       break;
4254*b5893f02SDimitry Andric     case LangOptions::CoreFoundationABI::Swift4_1:
4255*b5893f02SDimitry Andric       CFConstantStringClassName =
4256*b5893f02SDimitry Andric           Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
4257*b5893f02SDimitry Andric                               : "__T010Foundation19_NSCFConstantStringCN";
4258*b5893f02SDimitry Andric       Ty = IntPtrTy;
4259*b5893f02SDimitry Andric       break;
4260*b5893f02SDimitry Andric     }
4261*b5893f02SDimitry Andric 
4262*b5893f02SDimitry Andric     llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
4263*b5893f02SDimitry Andric 
4264*b5893f02SDimitry Andric     if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
4265*b5893f02SDimitry Andric       llvm::GlobalValue *GV = nullptr;
4266*b5893f02SDimitry Andric 
4267*b5893f02SDimitry Andric       if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
4268*b5893f02SDimitry Andric         IdentifierInfo &II = Context.Idents.get(GV->getName());
4269*b5893f02SDimitry Andric         TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
4270e7145dcbSDimitry Andric         DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
4271e7145dcbSDimitry Andric 
4272e7145dcbSDimitry Andric         const VarDecl *VD = nullptr;
4273e7145dcbSDimitry Andric         for (const auto &Result : DC->lookup(&II))
4274e7145dcbSDimitry Andric           if ((VD = dyn_cast<VarDecl>(Result)))
4275e7145dcbSDimitry Andric             break;
4276e7145dcbSDimitry Andric 
4277*b5893f02SDimitry Andric         if (Triple.isOSBinFormatELF()) {
4278*b5893f02SDimitry Andric           if (!VD)
42794ba319b5SDimitry Andric             GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4280e7145dcbSDimitry Andric         } else {
42814ba319b5SDimitry Andric           GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4282*b5893f02SDimitry Andric           if (!VD || !VD->hasAttr<DLLExportAttr>())
4283*b5893f02SDimitry Andric             GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
4284*b5893f02SDimitry Andric           else
4285*b5893f02SDimitry Andric             GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
4286e7145dcbSDimitry Andric         }
4287*b5893f02SDimitry Andric 
42884ba319b5SDimitry Andric         setDSOLocal(GV);
4289*b5893f02SDimitry Andric       }
4290*b5893f02SDimitry Andric     }
4291e7145dcbSDimitry Andric 
4292f22ef01cSRoman Divacky     // Decay array -> ptr
429344290647SDimitry Andric     CFConstantStringClassRef =
4294*b5893f02SDimitry Andric         IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
4295*b5893f02SDimitry Andric                    : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
4296e7145dcbSDimitry Andric   }
4297f22ef01cSRoman Divacky 
4298*b5893f02SDimitry Andric   QualType CFTy = Context.getCFConstantStringType();
4299f22ef01cSRoman Divacky 
430059d1ed5bSDimitry Andric   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
4301f22ef01cSRoman Divacky 
430244290647SDimitry Andric   ConstantInitBuilder Builder(*this);
430344290647SDimitry Andric   auto Fields = Builder.beginStruct(STy);
4304f22ef01cSRoman Divacky 
4305f22ef01cSRoman Divacky   // Class pointer.
430644290647SDimitry Andric   Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
4307f22ef01cSRoman Divacky 
4308f22ef01cSRoman Divacky   // Flags.
4309*b5893f02SDimitry Andric   if (IsSwiftABI) {
4310*b5893f02SDimitry Andric     Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
4311*b5893f02SDimitry Andric     Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
4312*b5893f02SDimitry Andric   } else {
431344290647SDimitry Andric     Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
4314*b5893f02SDimitry Andric   }
4315f22ef01cSRoman Divacky 
4316f22ef01cSRoman Divacky   // String pointer.
431759d1ed5bSDimitry Andric   llvm::Constant *C = nullptr;
4318dff0c46cSDimitry Andric   if (isUTF16) {
43190623d748SDimitry Andric     auto Arr = llvm::makeArrayRef(
432039d628a0SDimitry Andric         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
432139d628a0SDimitry Andric         Entry.first().size() / 2);
4322dff0c46cSDimitry Andric     C = llvm::ConstantDataArray::get(VMContext, Arr);
4323dff0c46cSDimitry Andric   } else {
432439d628a0SDimitry Andric     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
4325dff0c46cSDimitry Andric   }
4326f22ef01cSRoman Divacky 
4327dff0c46cSDimitry Andric   // Note: -fwritable-strings doesn't make the backing store strings of
4328dff0c46cSDimitry Andric   // CFStrings writable. (See <rdar://problem/10657500>)
432959d1ed5bSDimitry Andric   auto *GV =
4330dff0c46cSDimitry Andric       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
433159d1ed5bSDimitry Andric                                llvm::GlobalValue::PrivateLinkage, C, ".str");
4332e7145dcbSDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4333284c1978SDimitry Andric   // Don't enforce the target's minimum global alignment, since the only use
4334284c1978SDimitry Andric   // of the string is via this class initializer.
4335*b5893f02SDimitry Andric   CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
4336*b5893f02SDimitry Andric                             : Context.getTypeAlignInChars(Context.CharTy);
4337f22ef01cSRoman Divacky   GV->setAlignment(Align.getQuantity());
4338e7145dcbSDimitry Andric 
4339e7145dcbSDimitry Andric   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
4340e7145dcbSDimitry Andric   // Without it LLVM can merge the string with a non unnamed_addr one during
4341e7145dcbSDimitry Andric   // LTO.  Doing that changes the section it ends in, which surprises ld64.
4342*b5893f02SDimitry Andric   if (Triple.isOSBinFormatMachO())
4343e7145dcbSDimitry Andric     GV->setSection(isUTF16 ? "__TEXT,__ustring"
4344e7145dcbSDimitry Andric                            : "__TEXT,__cstring,cstring_literals");
4345*b5893f02SDimitry Andric   // Make sure the literal ends up in .rodata to allow for safe ICF and for
4346*b5893f02SDimitry Andric   // the static linker to adjust permissions to read-only later on.
4347*b5893f02SDimitry Andric   else if (Triple.isOSBinFormatELF())
4348*b5893f02SDimitry Andric     GV->setSection(".rodata");
4349dff0c46cSDimitry Andric 
4350dff0c46cSDimitry Andric   // String.
435144290647SDimitry Andric   llvm::Constant *Str =
435233956c43SDimitry Andric       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
4353f22ef01cSRoman Divacky 
4354dff0c46cSDimitry Andric   if (isUTF16)
4355dff0c46cSDimitry Andric     // Cast the UTF16 string to the correct type.
435644290647SDimitry Andric     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
435744290647SDimitry Andric   Fields.add(Str);
4358dff0c46cSDimitry Andric 
4359f22ef01cSRoman Divacky   // String length.
4360*b5893f02SDimitry Andric   llvm::IntegerType *LengthTy =
4361*b5893f02SDimitry Andric       llvm::IntegerType::get(getModule().getContext(),
4362*b5893f02SDimitry Andric                              Context.getTargetInfo().getLongWidth());
4363*b5893f02SDimitry Andric   if (IsSwiftABI) {
4364*b5893f02SDimitry Andric     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
4365*b5893f02SDimitry Andric         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
4366*b5893f02SDimitry Andric       LengthTy = Int32Ty;
4367*b5893f02SDimitry Andric     else
4368*b5893f02SDimitry Andric       LengthTy = IntPtrTy;
4369*b5893f02SDimitry Andric   }
4370*b5893f02SDimitry Andric   Fields.addInt(LengthTy, StringLength);
4371f22ef01cSRoman Divacky 
43720623d748SDimitry Andric   CharUnits Alignment = getPointerAlign();
43730623d748SDimitry Andric 
4374f22ef01cSRoman Divacky   // The struct.
437544290647SDimitry Andric   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
437644290647SDimitry Andric                                     /*isConstant=*/false,
437744290647SDimitry Andric                                     llvm::GlobalVariable::PrivateLinkage);
4378*b5893f02SDimitry Andric   switch (Triple.getObjectFormat()) {
4379e7145dcbSDimitry Andric   case llvm::Triple::UnknownObjectFormat:
4380e7145dcbSDimitry Andric     llvm_unreachable("unknown file format");
4381e7145dcbSDimitry Andric   case llvm::Triple::COFF:
4382e7145dcbSDimitry Andric   case llvm::Triple::ELF:
438320e90f04SDimitry Andric   case llvm::Triple::Wasm:
4384e7145dcbSDimitry Andric     GV->setSection("cfstring");
4385e7145dcbSDimitry Andric     break;
4386e7145dcbSDimitry Andric   case llvm::Triple::MachO:
4387e7145dcbSDimitry Andric     GV->setSection("__DATA,__cfstring");
4388e7145dcbSDimitry Andric     break;
4389e7145dcbSDimitry Andric   }
439039d628a0SDimitry Andric   Entry.second = GV;
4391f22ef01cSRoman Divacky 
43920623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
4393f22ef01cSRoman Divacky }
4394f22ef01cSRoman Divacky 
getExpressionLocationsEnabled() const43959a199699SDimitry Andric bool CodeGenModule::getExpressionLocationsEnabled() const {
43969a199699SDimitry Andric   return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
43979a199699SDimitry Andric }
43989a199699SDimitry Andric 
getObjCFastEnumerationStateType()43996122f3e6SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() {
44006122f3e6SDimitry Andric   if (ObjCFastEnumerationStateType.isNull()) {
440159d1ed5bSDimitry Andric     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
44026122f3e6SDimitry Andric     D->startDefinition();
44036122f3e6SDimitry Andric 
44046122f3e6SDimitry Andric     QualType FieldTypes[] = {
44056122f3e6SDimitry Andric       Context.UnsignedLongTy,
44066122f3e6SDimitry Andric       Context.getPointerType(Context.getObjCIdType()),
44076122f3e6SDimitry Andric       Context.getPointerType(Context.UnsignedLongTy),
44086122f3e6SDimitry Andric       Context.getConstantArrayType(Context.UnsignedLongTy,
44096122f3e6SDimitry Andric                            llvm::APInt(32, 5), ArrayType::Normal, 0)
44106122f3e6SDimitry Andric     };
44116122f3e6SDimitry Andric 
44126122f3e6SDimitry Andric     for (size_t i = 0; i < 4; ++i) {
44136122f3e6SDimitry Andric       FieldDecl *Field = FieldDecl::Create(Context,
44146122f3e6SDimitry Andric                                            D,
44156122f3e6SDimitry Andric                                            SourceLocation(),
441659d1ed5bSDimitry Andric                                            SourceLocation(), nullptr,
441759d1ed5bSDimitry Andric                                            FieldTypes[i], /*TInfo=*/nullptr,
441859d1ed5bSDimitry Andric                                            /*BitWidth=*/nullptr,
44196122f3e6SDimitry Andric                                            /*Mutable=*/false,
44207ae0e2c9SDimitry Andric                                            ICIS_NoInit);
44216122f3e6SDimitry Andric       Field->setAccess(AS_public);
44226122f3e6SDimitry Andric       D->addDecl(Field);
44236122f3e6SDimitry Andric     }
44246122f3e6SDimitry Andric 
44256122f3e6SDimitry Andric     D->completeDefinition();
44266122f3e6SDimitry Andric     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
44276122f3e6SDimitry Andric   }
44286122f3e6SDimitry Andric 
44296122f3e6SDimitry Andric   return ObjCFastEnumerationStateType;
44306122f3e6SDimitry Andric }
44316122f3e6SDimitry Andric 
4432dff0c46cSDimitry Andric llvm::Constant *
GetConstantArrayFromStringLiteral(const StringLiteral * E)4433dff0c46cSDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
4434dff0c46cSDimitry Andric   assert(!E->getType()->isPointerType() && "Strings are always arrays");
4435f22ef01cSRoman Divacky 
4436dff0c46cSDimitry Andric   // Don't emit it as the address of the string, emit the string data itself
4437dff0c46cSDimitry Andric   // as an inline array.
4438dff0c46cSDimitry Andric   if (E->getCharByteWidth() == 1) {
4439dff0c46cSDimitry Andric     SmallString<64> Str(E->getString());
4440f22ef01cSRoman Divacky 
4441dff0c46cSDimitry Andric     // Resize the string to the right size, which is indicated by its type.
4442dff0c46cSDimitry Andric     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
4443dff0c46cSDimitry Andric     Str.resize(CAT->getSize().getZExtValue());
4444dff0c46cSDimitry Andric     return llvm::ConstantDataArray::getString(VMContext, Str, false);
44456122f3e6SDimitry Andric   }
4446f22ef01cSRoman Divacky 
444759d1ed5bSDimitry Andric   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
4448dff0c46cSDimitry Andric   llvm::Type *ElemTy = AType->getElementType();
4449dff0c46cSDimitry Andric   unsigned NumElements = AType->getNumElements();
4450f22ef01cSRoman Divacky 
4451dff0c46cSDimitry Andric   // Wide strings have either 2-byte or 4-byte elements.
4452dff0c46cSDimitry Andric   if (ElemTy->getPrimitiveSizeInBits() == 16) {
4453dff0c46cSDimitry Andric     SmallVector<uint16_t, 32> Elements;
4454dff0c46cSDimitry Andric     Elements.reserve(NumElements);
4455dff0c46cSDimitry Andric 
4456dff0c46cSDimitry Andric     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4457dff0c46cSDimitry Andric       Elements.push_back(E->getCodeUnit(i));
4458dff0c46cSDimitry Andric     Elements.resize(NumElements);
4459dff0c46cSDimitry Andric     return llvm::ConstantDataArray::get(VMContext, Elements);
4460dff0c46cSDimitry Andric   }
4461dff0c46cSDimitry Andric 
4462dff0c46cSDimitry Andric   assert(ElemTy->getPrimitiveSizeInBits() == 32);
4463dff0c46cSDimitry Andric   SmallVector<uint32_t, 32> Elements;
4464dff0c46cSDimitry Andric   Elements.reserve(NumElements);
4465dff0c46cSDimitry Andric 
4466dff0c46cSDimitry Andric   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4467dff0c46cSDimitry Andric     Elements.push_back(E->getCodeUnit(i));
4468dff0c46cSDimitry Andric   Elements.resize(NumElements);
4469dff0c46cSDimitry Andric   return llvm::ConstantDataArray::get(VMContext, Elements);
4470f22ef01cSRoman Divacky }
4471f22ef01cSRoman Divacky 
447259d1ed5bSDimitry Andric static llvm::GlobalVariable *
GenerateStringLiteral(llvm::Constant * C,llvm::GlobalValue::LinkageTypes LT,CodeGenModule & CGM,StringRef GlobalName,CharUnits Alignment)447359d1ed5bSDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
447459d1ed5bSDimitry Andric                       CodeGenModule &CGM, StringRef GlobalName,
44750623d748SDimitry Andric                       CharUnits Alignment) {
44764ba319b5SDimitry Andric   unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
44774ba319b5SDimitry Andric       CGM.getStringLiteralAddressSpace());
4478dff0c46cSDimitry Andric 
447933956c43SDimitry Andric   llvm::Module &M = CGM.getModule();
448059d1ed5bSDimitry Andric   // Create a global variable for this string
448159d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
448233956c43SDimitry Andric       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
448333956c43SDimitry Andric       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
44840623d748SDimitry Andric   GV->setAlignment(Alignment.getQuantity());
4485e7145dcbSDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
448633956c43SDimitry Andric   if (GV->isWeakForLinker()) {
448733956c43SDimitry Andric     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
448833956c43SDimitry Andric     GV->setComdat(M.getOrInsertComdat(GV->getName()));
448933956c43SDimitry Andric   }
44904ba319b5SDimitry Andric   CGM.setDSOLocal(GV);
449133956c43SDimitry Andric 
449259d1ed5bSDimitry Andric   return GV;
4493f22ef01cSRoman Divacky }
4494dff0c46cSDimitry Andric 
449559d1ed5bSDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
449659d1ed5bSDimitry Andric /// constant array for the given string literal.
44970623d748SDimitry Andric ConstantAddress
GetAddrOfConstantStringFromLiteral(const StringLiteral * S,StringRef Name)449839d628a0SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
449939d628a0SDimitry Andric                                                   StringRef Name) {
45000623d748SDimitry Andric   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
4501dff0c46cSDimitry Andric 
450259d1ed5bSDimitry Andric   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
450359d1ed5bSDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
450459d1ed5bSDimitry Andric   if (!LangOpts.WritableStrings) {
450559d1ed5bSDimitry Andric     Entry = &ConstantStringMap[C];
450659d1ed5bSDimitry Andric     if (auto GV = *Entry) {
45070623d748SDimitry Andric       if (Alignment.getQuantity() > GV->getAlignment())
45080623d748SDimitry Andric         GV->setAlignment(Alignment.getQuantity());
45090623d748SDimitry Andric       return ConstantAddress(GV, Alignment);
451059d1ed5bSDimitry Andric     }
451159d1ed5bSDimitry Andric   }
451259d1ed5bSDimitry Andric 
451359d1ed5bSDimitry Andric   SmallString<256> MangledNameBuffer;
451459d1ed5bSDimitry Andric   StringRef GlobalVariableName;
451559d1ed5bSDimitry Andric   llvm::GlobalValue::LinkageTypes LT;
451659d1ed5bSDimitry Andric 
4517*b5893f02SDimitry Andric   // Mangle the string literal if that's how the ABI merges duplicate strings.
4518*b5893f02SDimitry Andric   // Don't do it if they are writable, since we don't want writes in one TU to
4519*b5893f02SDimitry Andric   // affect strings in another.
4520*b5893f02SDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
4521*b5893f02SDimitry Andric       !LangOpts.WritableStrings) {
452259d1ed5bSDimitry Andric     llvm::raw_svector_ostream Out(MangledNameBuffer);
452359d1ed5bSDimitry Andric     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
452459d1ed5bSDimitry Andric     LT = llvm::GlobalValue::LinkOnceODRLinkage;
452559d1ed5bSDimitry Andric     GlobalVariableName = MangledNameBuffer;
452659d1ed5bSDimitry Andric   } else {
452759d1ed5bSDimitry Andric     LT = llvm::GlobalValue::PrivateLinkage;
452839d628a0SDimitry Andric     GlobalVariableName = Name;
452959d1ed5bSDimitry Andric   }
453059d1ed5bSDimitry Andric 
453159d1ed5bSDimitry Andric   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
453259d1ed5bSDimitry Andric   if (Entry)
453359d1ed5bSDimitry Andric     *Entry = GV;
453459d1ed5bSDimitry Andric 
453539d628a0SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
453639d628a0SDimitry Andric                                   QualType());
45374ba319b5SDimitry Andric 
45384ba319b5SDimitry Andric   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
45394ba319b5SDimitry Andric                          Alignment);
4540f22ef01cSRoman Divacky }
4541f22ef01cSRoman Divacky 
4542f22ef01cSRoman Divacky /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
4543f22ef01cSRoman Divacky /// array for the given ObjCEncodeExpr node.
45440623d748SDimitry Andric ConstantAddress
GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr * E)4545f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
4546f22ef01cSRoman Divacky   std::string Str;
4547f22ef01cSRoman Divacky   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
4548f22ef01cSRoman Divacky 
4549f22ef01cSRoman Divacky   return GetAddrOfConstantCString(Str);
4550f22ef01cSRoman Divacky }
4551f22ef01cSRoman Divacky 
455259d1ed5bSDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing
455359d1ed5bSDimitry Andric /// the literal and a terminating '\0' character.
455459d1ed5bSDimitry Andric /// The result has pointer to array type.
GetAddrOfConstantCString(const std::string & Str,const char * GlobalName)45550623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString(
45560623d748SDimitry Andric     const std::string &Str, const char *GlobalName) {
455759d1ed5bSDimitry Andric   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
45580623d748SDimitry Andric   CharUnits Alignment =
45590623d748SDimitry Andric     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
4560f22ef01cSRoman Divacky 
456159d1ed5bSDimitry Andric   llvm::Constant *C =
456259d1ed5bSDimitry Andric       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
456359d1ed5bSDimitry Andric 
456459d1ed5bSDimitry Andric   // Don't share any string literals if strings aren't constant.
456559d1ed5bSDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
456659d1ed5bSDimitry Andric   if (!LangOpts.WritableStrings) {
456759d1ed5bSDimitry Andric     Entry = &ConstantStringMap[C];
456859d1ed5bSDimitry Andric     if (auto GV = *Entry) {
45690623d748SDimitry Andric       if (Alignment.getQuantity() > GV->getAlignment())
45700623d748SDimitry Andric         GV->setAlignment(Alignment.getQuantity());
45710623d748SDimitry Andric       return ConstantAddress(GV, Alignment);
457259d1ed5bSDimitry Andric     }
457359d1ed5bSDimitry Andric   }
457459d1ed5bSDimitry Andric 
4575f22ef01cSRoman Divacky   // Get the default prefix if a name wasn't specified.
4576f22ef01cSRoman Divacky   if (!GlobalName)
4577f22ef01cSRoman Divacky     GlobalName = ".str";
4578f22ef01cSRoman Divacky   // Create a global variable for this.
457959d1ed5bSDimitry Andric   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
458059d1ed5bSDimitry Andric                                   GlobalName, Alignment);
458159d1ed5bSDimitry Andric   if (Entry)
458259d1ed5bSDimitry Andric     *Entry = GV;
45834ba319b5SDimitry Andric 
45844ba319b5SDimitry Andric   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
45854ba319b5SDimitry Andric                          Alignment);
4586f22ef01cSRoman Divacky }
4587f22ef01cSRoman Divacky 
GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr * E,const Expr * Init)45880623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
4589f785676fSDimitry Andric     const MaterializeTemporaryExpr *E, const Expr *Init) {
4590f785676fSDimitry Andric   assert((E->getStorageDuration() == SD_Static ||
4591f785676fSDimitry Andric           E->getStorageDuration() == SD_Thread) && "not a global temporary");
459259d1ed5bSDimitry Andric   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
4593f785676fSDimitry Andric 
4594f785676fSDimitry Andric   // If we're not materializing a subobject of the temporary, keep the
4595f785676fSDimitry Andric   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
4596f785676fSDimitry Andric   QualType MaterializedType = Init->getType();
4597f785676fSDimitry Andric   if (Init == E->GetTemporaryExpr())
4598f785676fSDimitry Andric     MaterializedType = E->getType();
4599f785676fSDimitry Andric 
46000623d748SDimitry Andric   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
46010623d748SDimitry Andric 
46020623d748SDimitry Andric   if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
46030623d748SDimitry Andric     return ConstantAddress(Slot, Align);
4604f785676fSDimitry Andric 
4605f785676fSDimitry Andric   // FIXME: If an externally-visible declaration extends multiple temporaries,
4606f785676fSDimitry Andric   // we need to give each temporary the same name in every translation unit (and
4607f785676fSDimitry Andric   // we also need to make the temporaries externally-visible).
4608f785676fSDimitry Andric   SmallString<256> Name;
4609f785676fSDimitry Andric   llvm::raw_svector_ostream Out(Name);
461059d1ed5bSDimitry Andric   getCXXABI().getMangleContext().mangleReferenceTemporary(
461159d1ed5bSDimitry Andric       VD, E->getManglingNumber(), Out);
4612f785676fSDimitry Andric 
461359d1ed5bSDimitry Andric   APValue *Value = nullptr;
4614f785676fSDimitry Andric   if (E->getStorageDuration() == SD_Static) {
4615f785676fSDimitry Andric     // We might have a cached constant initializer for this temporary. Note
4616f785676fSDimitry Andric     // that this might have a different value from the value computed by
4617f785676fSDimitry Andric     // evaluating the initializer if the surrounding constant expression
4618f785676fSDimitry Andric     // modifies the temporary.
4619f785676fSDimitry Andric     Value = getContext().getMaterializedTemporaryValue(E, false);
4620f785676fSDimitry Andric     if (Value && Value->isUninit())
462159d1ed5bSDimitry Andric       Value = nullptr;
4622f785676fSDimitry Andric   }
4623f785676fSDimitry Andric 
4624f785676fSDimitry Andric   // Try evaluating it now, it might have a constant initializer.
4625f785676fSDimitry Andric   Expr::EvalResult EvalResult;
4626f785676fSDimitry Andric   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
4627f785676fSDimitry Andric       !EvalResult.hasSideEffects())
4628f785676fSDimitry Andric     Value = &EvalResult.Val;
4629f785676fSDimitry Andric 
46309a199699SDimitry Andric   LangAS AddrSpace =
46319a199699SDimitry Andric       VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
46329a199699SDimitry Andric 
46339a199699SDimitry Andric   Optional<ConstantEmitter> emitter;
463459d1ed5bSDimitry Andric   llvm::Constant *InitialValue = nullptr;
4635f785676fSDimitry Andric   bool Constant = false;
4636f785676fSDimitry Andric   llvm::Type *Type;
4637f785676fSDimitry Andric   if (Value) {
4638f785676fSDimitry Andric     // The temporary has a constant initializer, use it.
46399a199699SDimitry Andric     emitter.emplace(*this);
46409a199699SDimitry Andric     InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
46419a199699SDimitry Andric                                                MaterializedType);
4642f785676fSDimitry Andric     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
4643f785676fSDimitry Andric     Type = InitialValue->getType();
4644f785676fSDimitry Andric   } else {
4645f785676fSDimitry Andric     // No initializer, the initialization will be provided when we
4646f785676fSDimitry Andric     // initialize the declaration which performed lifetime extension.
4647f785676fSDimitry Andric     Type = getTypes().ConvertTypeForMem(MaterializedType);
4648f785676fSDimitry Andric   }
4649f785676fSDimitry Andric 
4650f785676fSDimitry Andric   // Create a global variable for this lifetime-extended temporary.
465159d1ed5bSDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
465259d1ed5bSDimitry Andric       getLLVMLinkageVarDefinition(VD, Constant);
465333956c43SDimitry Andric   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
465433956c43SDimitry Andric     const VarDecl *InitVD;
465533956c43SDimitry Andric     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
465633956c43SDimitry Andric         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
465733956c43SDimitry Andric       // Temporaries defined inside a class get linkonce_odr linkage because the
46584ba319b5SDimitry Andric       // class can be defined in multiple translation units.
465933956c43SDimitry Andric       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
466033956c43SDimitry Andric     } else {
466133956c43SDimitry Andric       // There is no need for this temporary to have external linkage if the
466233956c43SDimitry Andric       // VarDecl has external linkage.
466333956c43SDimitry Andric       Linkage = llvm::GlobalVariable::InternalLinkage;
466433956c43SDimitry Andric     }
466533956c43SDimitry Andric   }
4666c4394386SDimitry Andric   auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
466759d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
466859d1ed5bSDimitry Andric       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
4669c4394386SDimitry Andric       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
46709a199699SDimitry Andric   if (emitter) emitter->finalize(GV);
46714ba319b5SDimitry Andric   setGVProperties(GV, VD);
46720623d748SDimitry Andric   GV->setAlignment(Align.getQuantity());
467333956c43SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker())
467433956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4675f785676fSDimitry Andric   if (VD->getTLSKind())
4676f785676fSDimitry Andric     setTLSMode(GV, *VD);
4677c4394386SDimitry Andric   llvm::Constant *CV = GV;
4678c4394386SDimitry Andric   if (AddrSpace != LangAS::Default)
4679c4394386SDimitry Andric     CV = getTargetCodeGenInfo().performAddrSpaceCast(
4680c4394386SDimitry Andric         *this, GV, AddrSpace, LangAS::Default,
4681c4394386SDimitry Andric         Type->getPointerTo(
4682c4394386SDimitry Andric             getContext().getTargetAddressSpace(LangAS::Default)));
4683c4394386SDimitry Andric   MaterializedGlobalTemporaryMap[E] = CV;
4684c4394386SDimitry Andric   return ConstantAddress(CV, Align);
4685f785676fSDimitry Andric }
4686f785676fSDimitry Andric 
4687f22ef01cSRoman Divacky /// EmitObjCPropertyImplementations - Emit information for synthesized
4688f22ef01cSRoman Divacky /// properties for an implementation.
EmitObjCPropertyImplementations(const ObjCImplementationDecl * D)4689f22ef01cSRoman Divacky void CodeGenModule::EmitObjCPropertyImplementations(const
4690f22ef01cSRoman Divacky                                                     ObjCImplementationDecl *D) {
469159d1ed5bSDimitry Andric   for (const auto *PID : D->property_impls()) {
4692f22ef01cSRoman Divacky     // Dynamic is just for type-checking.
4693f22ef01cSRoman Divacky     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
4694f22ef01cSRoman Divacky       ObjCPropertyDecl *PD = PID->getPropertyDecl();
4695f22ef01cSRoman Divacky 
4696f22ef01cSRoman Divacky       // Determine which methods need to be implemented, some may have
46973861d79fSDimitry Andric       // been overridden. Note that ::isPropertyAccessor is not the method
4698f22ef01cSRoman Divacky       // we want, that just indicates if the decl came from a
4699f22ef01cSRoman Divacky       // property. What we want to know is if the method is defined in
4700f22ef01cSRoman Divacky       // this implementation.
4701f22ef01cSRoman Divacky       if (!D->getInstanceMethod(PD->getGetterName()))
4702f22ef01cSRoman Divacky         CodeGenFunction(*this).GenerateObjCGetter(
4703f22ef01cSRoman Divacky                                  const_cast<ObjCImplementationDecl *>(D), PID);
4704f22ef01cSRoman Divacky       if (!PD->isReadOnly() &&
4705f22ef01cSRoman Divacky           !D->getInstanceMethod(PD->getSetterName()))
4706f22ef01cSRoman Divacky         CodeGenFunction(*this).GenerateObjCSetter(
4707f22ef01cSRoman Divacky                                  const_cast<ObjCImplementationDecl *>(D), PID);
4708f22ef01cSRoman Divacky     }
4709f22ef01cSRoman Divacky   }
4710f22ef01cSRoman Divacky }
4711f22ef01cSRoman Divacky 
needsDestructMethod(ObjCImplementationDecl * impl)47123b0f4066SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) {
47136122f3e6SDimitry Andric   const ObjCInterfaceDecl *iface = impl->getClassInterface();
47146122f3e6SDimitry Andric   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
47153b0f4066SDimitry Andric        ivar; ivar = ivar->getNextIvar())
47163b0f4066SDimitry Andric     if (ivar->getType().isDestructedType())
47173b0f4066SDimitry Andric       return true;
47183b0f4066SDimitry Andric 
47193b0f4066SDimitry Andric   return false;
47203b0f4066SDimitry Andric }
47213b0f4066SDimitry Andric 
AllTrivialInitializers(CodeGenModule & CGM,ObjCImplementationDecl * D)472239d628a0SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM,
472339d628a0SDimitry Andric                                    ObjCImplementationDecl *D) {
472439d628a0SDimitry Andric   CodeGenFunction CGF(CGM);
472539d628a0SDimitry Andric   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
472639d628a0SDimitry Andric        E = D->init_end(); B != E; ++B) {
472739d628a0SDimitry Andric     CXXCtorInitializer *CtorInitExp = *B;
472839d628a0SDimitry Andric     Expr *Init = CtorInitExp->getInit();
472939d628a0SDimitry Andric     if (!CGF.isTrivialInitializer(Init))
473039d628a0SDimitry Andric       return false;
473139d628a0SDimitry Andric   }
473239d628a0SDimitry Andric   return true;
473339d628a0SDimitry Andric }
473439d628a0SDimitry Andric 
4735f22ef01cSRoman Divacky /// EmitObjCIvarInitializations - Emit information for ivar initialization
4736f22ef01cSRoman Divacky /// for an implementation.
EmitObjCIvarInitializations(ObjCImplementationDecl * D)4737f22ef01cSRoman Divacky void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
47383b0f4066SDimitry Andric   // We might need a .cxx_destruct even if we don't have any ivar initializers.
47393b0f4066SDimitry Andric   if (needsDestructMethod(D)) {
4740f22ef01cSRoman Divacky     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
4741f22ef01cSRoman Divacky     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
47423b0f4066SDimitry Andric     ObjCMethodDecl *DTORMethod =
47433b0f4066SDimitry Andric       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
474459d1ed5bSDimitry Andric                              cxxSelector, getContext().VoidTy, nullptr, D,
47456122f3e6SDimitry Andric                              /*isInstance=*/true, /*isVariadic=*/false,
47463861d79fSDimitry Andric                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
47476122f3e6SDimitry Andric                              /*isDefined=*/false, ObjCMethodDecl::Required);
4748f22ef01cSRoman Divacky     D->addInstanceMethod(DTORMethod);
4749f22ef01cSRoman Divacky     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
47503861d79fSDimitry Andric     D->setHasDestructors(true);
47513b0f4066SDimitry Andric   }
4752f22ef01cSRoman Divacky 
47533b0f4066SDimitry Andric   // If the implementation doesn't have any ivar initializers, we don't need
47543b0f4066SDimitry Andric   // a .cxx_construct.
475539d628a0SDimitry Andric   if (D->getNumIvarInitializers() == 0 ||
475639d628a0SDimitry Andric       AllTrivialInitializers(*this, D))
47573b0f4066SDimitry Andric     return;
47583b0f4066SDimitry Andric 
47593b0f4066SDimitry Andric   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
47603b0f4066SDimitry Andric   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
4761f22ef01cSRoman Divacky   // The constructor returns 'self'.
4762f22ef01cSRoman Divacky   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
4763f22ef01cSRoman Divacky                                                 D->getLocation(),
47646122f3e6SDimitry Andric                                                 D->getLocation(),
47656122f3e6SDimitry Andric                                                 cxxSelector,
476659d1ed5bSDimitry Andric                                                 getContext().getObjCIdType(),
476759d1ed5bSDimitry Andric                                                 nullptr, D, /*isInstance=*/true,
47686122f3e6SDimitry Andric                                                 /*isVariadic=*/false,
47693861d79fSDimitry Andric                                                 /*isPropertyAccessor=*/true,
47706122f3e6SDimitry Andric                                                 /*isImplicitlyDeclared=*/true,
47716122f3e6SDimitry Andric                                                 /*isDefined=*/false,
4772f22ef01cSRoman Divacky                                                 ObjCMethodDecl::Required);
4773f22ef01cSRoman Divacky   D->addInstanceMethod(CTORMethod);
4774f22ef01cSRoman Divacky   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
47753861d79fSDimitry Andric   D->setHasNonZeroConstructors(true);
4776f22ef01cSRoman Divacky }
4777f22ef01cSRoman Divacky 
4778f22ef01cSRoman Divacky // EmitLinkageSpec - Emit all declarations in a linkage spec.
EmitLinkageSpec(const LinkageSpecDecl * LSD)4779f22ef01cSRoman Divacky void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
4780f22ef01cSRoman Divacky   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
4781f22ef01cSRoman Divacky       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
4782f22ef01cSRoman Divacky     ErrorUnsupported(LSD, "linkage spec");
4783f22ef01cSRoman Divacky     return;
4784f22ef01cSRoman Divacky   }
4785f22ef01cSRoman Divacky 
478644290647SDimitry Andric   EmitDeclContext(LSD);
478744290647SDimitry Andric }
478844290647SDimitry Andric 
EmitDeclContext(const DeclContext * DC)478944290647SDimitry Andric void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
479044290647SDimitry Andric   for (auto *I : DC->decls()) {
479144290647SDimitry Andric     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
479244290647SDimitry Andric     // are themselves considered "top-level", so EmitTopLevelDecl on an
479344290647SDimitry Andric     // ObjCImplDecl does not recursively visit them. We need to do that in
479444290647SDimitry Andric     // case they're nested inside another construct (LinkageSpecDecl /
479544290647SDimitry Andric     // ExportDecl) that does stop them from being considered "top-level".
479659d1ed5bSDimitry Andric     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
479759d1ed5bSDimitry Andric       for (auto *M : OID->methods())
479859d1ed5bSDimitry Andric         EmitTopLevelDecl(M);
47993861d79fSDimitry Andric     }
480044290647SDimitry Andric 
480159d1ed5bSDimitry Andric     EmitTopLevelDecl(I);
4802f22ef01cSRoman Divacky   }
48033861d79fSDimitry Andric }
4804f22ef01cSRoman Divacky 
4805f22ef01cSRoman Divacky /// EmitTopLevelDecl - Emit code for a single top level declaration.
EmitTopLevelDecl(Decl * D)4806f22ef01cSRoman Divacky void CodeGenModule::EmitTopLevelDecl(Decl *D) {
4807f22ef01cSRoman Divacky   // Ignore dependent declarations.
4808954b921dSDimitry Andric   if (D->isTemplated())
4809f22ef01cSRoman Divacky     return;
4810f22ef01cSRoman Divacky 
4811f22ef01cSRoman Divacky   switch (D->getKind()) {
4812f22ef01cSRoman Divacky   case Decl::CXXConversion:
4813f22ef01cSRoman Divacky   case Decl::CXXMethod:
4814f22ef01cSRoman Divacky   case Decl::Function:
4815f22ef01cSRoman Divacky     EmitGlobal(cast<FunctionDecl>(D));
481639d628a0SDimitry Andric     // Always provide some coverage mapping
481739d628a0SDimitry Andric     // even for the functions that aren't emitted.
481839d628a0SDimitry Andric     AddDeferredUnusedCoverageMapping(D);
4819f22ef01cSRoman Divacky     break;
4820f22ef01cSRoman Divacky 
48216bc11b14SDimitry Andric   case Decl::CXXDeductionGuide:
48226bc11b14SDimitry Andric     // Function-like, but does not result in code emission.
48236bc11b14SDimitry Andric     break;
48246bc11b14SDimitry Andric 
4825f22ef01cSRoman Divacky   case Decl::Var:
482644290647SDimitry Andric   case Decl::Decomposition:
4827f785676fSDimitry Andric   case Decl::VarTemplateSpecialization:
4828f22ef01cSRoman Divacky     EmitGlobal(cast<VarDecl>(D));
482944290647SDimitry Andric     if (auto *DD = dyn_cast<DecompositionDecl>(D))
483044290647SDimitry Andric       for (auto *B : DD->bindings())
483144290647SDimitry Andric         if (auto *HD = B->getHoldingVar())
483244290647SDimitry Andric           EmitGlobal(HD);
4833f22ef01cSRoman Divacky     break;
4834f22ef01cSRoman Divacky 
48353b0f4066SDimitry Andric   // Indirect fields from global anonymous structs and unions can be
48363b0f4066SDimitry Andric   // ignored; only the actual variable requires IR gen support.
48373b0f4066SDimitry Andric   case Decl::IndirectField:
48383b0f4066SDimitry Andric     break;
48393b0f4066SDimitry Andric 
4840f22ef01cSRoman Divacky   // C++ Decls
4841f22ef01cSRoman Divacky   case Decl::Namespace:
484244290647SDimitry Andric     EmitDeclContext(cast<NamespaceDecl>(D));
4843f22ef01cSRoman Divacky     break;
48449a199699SDimitry Andric   case Decl::ClassTemplateSpecialization: {
48459a199699SDimitry Andric     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
48469a199699SDimitry Andric     if (DebugInfo &&
48479a199699SDimitry Andric         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
48489a199699SDimitry Andric         Spec->hasDefinition())
48499a199699SDimitry Andric       DebugInfo->completeTemplateDefinition(*Spec);
48509a199699SDimitry Andric   } LLVM_FALLTHROUGH;
4851e7145dcbSDimitry Andric   case Decl::CXXRecord:
485220e90f04SDimitry Andric     if (DebugInfo) {
485320e90f04SDimitry Andric       if (auto *ES = D->getASTContext().getExternalSource())
485420e90f04SDimitry Andric         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
485520e90f04SDimitry Andric           DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
485620e90f04SDimitry Andric     }
4857e7145dcbSDimitry Andric     // Emit any static data members, they may be definitions.
4858e7145dcbSDimitry Andric     for (auto *I : cast<CXXRecordDecl>(D)->decls())
4859e7145dcbSDimitry Andric       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
4860e7145dcbSDimitry Andric         EmitTopLevelDecl(I);
4861e7145dcbSDimitry Andric     break;
4862f22ef01cSRoman Divacky     // No code generation needed.
4863f22ef01cSRoman Divacky   case Decl::UsingShadow:
4864f22ef01cSRoman Divacky   case Decl::ClassTemplate:
4865f785676fSDimitry Andric   case Decl::VarTemplate:
4866f785676fSDimitry Andric   case Decl::VarTemplatePartialSpecialization:
4867f22ef01cSRoman Divacky   case Decl::FunctionTemplate:
4868bd5abe19SDimitry Andric   case Decl::TypeAliasTemplate:
4869bd5abe19SDimitry Andric   case Decl::Block:
4870139f7f9bSDimitry Andric   case Decl::Empty:
4871*b5893f02SDimitry Andric   case Decl::Binding:
4872f22ef01cSRoman Divacky     break;
487359d1ed5bSDimitry Andric   case Decl::Using:          // using X; [C++]
487459d1ed5bSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
487559d1ed5bSDimitry Andric         DI->EmitUsingDecl(cast<UsingDecl>(*D));
487659d1ed5bSDimitry Andric     return;
4877f785676fSDimitry Andric   case Decl::NamespaceAlias:
4878f785676fSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
4879f785676fSDimitry Andric         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
4880f785676fSDimitry Andric     return;
4881284c1978SDimitry Andric   case Decl::UsingDirective: // using namespace X; [C++]
4882284c1978SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
4883284c1978SDimitry Andric       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
4884284c1978SDimitry Andric     return;
4885f22ef01cSRoman Divacky   case Decl::CXXConstructor:
4886f785676fSDimitry Andric     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
4887f22ef01cSRoman Divacky     break;
4888f22ef01cSRoman Divacky   case Decl::CXXDestructor:
4889f785676fSDimitry Andric     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
4890f22ef01cSRoman Divacky     break;
4891f22ef01cSRoman Divacky 
4892f22ef01cSRoman Divacky   case Decl::StaticAssert:
4893f22ef01cSRoman Divacky     // Nothing to do.
4894f22ef01cSRoman Divacky     break;
4895f22ef01cSRoman Divacky 
4896f22ef01cSRoman Divacky   // Objective-C Decls
4897f22ef01cSRoman Divacky 
4898f22ef01cSRoman Divacky   // Forward declarations, no (immediate) code generation.
4899f22ef01cSRoman Divacky   case Decl::ObjCInterface:
49007ae0e2c9SDimitry Andric   case Decl::ObjCCategory:
4901f22ef01cSRoman Divacky     break;
4902f22ef01cSRoman Divacky 
4903dff0c46cSDimitry Andric   case Decl::ObjCProtocol: {
490459d1ed5bSDimitry Andric     auto *Proto = cast<ObjCProtocolDecl>(D);
4905dff0c46cSDimitry Andric     if (Proto->isThisDeclarationADefinition())
4906dff0c46cSDimitry Andric       ObjCRuntime->GenerateProtocol(Proto);
4907f22ef01cSRoman Divacky     break;
4908dff0c46cSDimitry Andric   }
4909f22ef01cSRoman Divacky 
4910f22ef01cSRoman Divacky   case Decl::ObjCCategoryImpl:
4911f22ef01cSRoman Divacky     // Categories have properties but don't support synthesize so we
4912f22ef01cSRoman Divacky     // can ignore them here.
49136122f3e6SDimitry Andric     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
4914f22ef01cSRoman Divacky     break;
4915f22ef01cSRoman Divacky 
4916f22ef01cSRoman Divacky   case Decl::ObjCImplementation: {
491759d1ed5bSDimitry Andric     auto *OMD = cast<ObjCImplementationDecl>(D);
4918f22ef01cSRoman Divacky     EmitObjCPropertyImplementations(OMD);
4919f22ef01cSRoman Divacky     EmitObjCIvarInitializations(OMD);
49206122f3e6SDimitry Andric     ObjCRuntime->GenerateClass(OMD);
4921dff0c46cSDimitry Andric     // Emit global variable debug information.
4922dff0c46cSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
4923e7145dcbSDimitry Andric       if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
4924139f7f9bSDimitry Andric         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
4925139f7f9bSDimitry Andric             OMD->getClassInterface()), OMD->getLocation());
4926f22ef01cSRoman Divacky     break;
4927f22ef01cSRoman Divacky   }
4928f22ef01cSRoman Divacky   case Decl::ObjCMethod: {
492959d1ed5bSDimitry Andric     auto *OMD = cast<ObjCMethodDecl>(D);
4930f22ef01cSRoman Divacky     // If this is not a prototype, emit the body.
4931f22ef01cSRoman Divacky     if (OMD->getBody())
4932f22ef01cSRoman Divacky       CodeGenFunction(*this).GenerateObjCMethod(OMD);
4933f22ef01cSRoman Divacky     break;
4934f22ef01cSRoman Divacky   }
4935f22ef01cSRoman Divacky   case Decl::ObjCCompatibleAlias:
4936dff0c46cSDimitry Andric     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
4937f22ef01cSRoman Divacky     break;
4938f22ef01cSRoman Divacky 
4939e7145dcbSDimitry Andric   case Decl::PragmaComment: {
4940e7145dcbSDimitry Andric     const auto *PCD = cast<PragmaCommentDecl>(D);
4941e7145dcbSDimitry Andric     switch (PCD->getCommentKind()) {
4942e7145dcbSDimitry Andric     case PCK_Unknown:
4943e7145dcbSDimitry Andric       llvm_unreachable("unexpected pragma comment kind");
4944e7145dcbSDimitry Andric     case PCK_Linker:
4945e7145dcbSDimitry Andric       AppendLinkerOptions(PCD->getArg());
4946e7145dcbSDimitry Andric       break;
4947e7145dcbSDimitry Andric     case PCK_Lib:
49484ba319b5SDimitry Andric       if (getTarget().getTriple().isOSBinFormatELF() &&
49494ba319b5SDimitry Andric           !getTarget().getTriple().isPS4())
49504ba319b5SDimitry Andric         AddELFLibDirective(PCD->getArg());
49514ba319b5SDimitry Andric       else
4952e7145dcbSDimitry Andric         AddDependentLib(PCD->getArg());
4953e7145dcbSDimitry Andric       break;
4954e7145dcbSDimitry Andric     case PCK_Compiler:
4955e7145dcbSDimitry Andric     case PCK_ExeStr:
4956e7145dcbSDimitry Andric     case PCK_User:
4957e7145dcbSDimitry Andric       break; // We ignore all of these.
4958e7145dcbSDimitry Andric     }
4959e7145dcbSDimitry Andric     break;
4960e7145dcbSDimitry Andric   }
4961e7145dcbSDimitry Andric 
4962e7145dcbSDimitry Andric   case Decl::PragmaDetectMismatch: {
4963e7145dcbSDimitry Andric     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
4964e7145dcbSDimitry Andric     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
4965e7145dcbSDimitry Andric     break;
4966e7145dcbSDimitry Andric   }
4967e7145dcbSDimitry Andric 
4968f22ef01cSRoman Divacky   case Decl::LinkageSpec:
4969f22ef01cSRoman Divacky     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
4970f22ef01cSRoman Divacky     break;
4971f22ef01cSRoman Divacky 
4972f22ef01cSRoman Divacky   case Decl::FileScopeAsm: {
497333956c43SDimitry Andric     // File-scope asm is ignored during device-side CUDA compilation.
497433956c43SDimitry Andric     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
497533956c43SDimitry Andric       break;
4976ea942507SDimitry Andric     // File-scope asm is ignored during device-side OpenMP compilation.
4977ea942507SDimitry Andric     if (LangOpts.OpenMPIsDevice)
4978ea942507SDimitry Andric       break;
497959d1ed5bSDimitry Andric     auto *AD = cast<FileScopeAsmDecl>(D);
498033956c43SDimitry Andric     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
4981f22ef01cSRoman Divacky     break;
4982f22ef01cSRoman Divacky   }
4983f22ef01cSRoman Divacky 
4984139f7f9bSDimitry Andric   case Decl::Import: {
498559d1ed5bSDimitry Andric     auto *Import = cast<ImportDecl>(D);
4986139f7f9bSDimitry Andric 
498744290647SDimitry Andric     // If we've already imported this module, we're done.
498844290647SDimitry Andric     if (!ImportedModules.insert(Import->getImportedModule()))
4989139f7f9bSDimitry Andric       break;
499044290647SDimitry Andric 
499144290647SDimitry Andric     // Emit debug information for direct imports.
499244290647SDimitry Andric     if (!Import->getImportedOwningModule()) {
49933dac3a9bSDimitry Andric       if (CGDebugInfo *DI = getModuleDebugInfo())
49943dac3a9bSDimitry Andric         DI->EmitImportDecl(*Import);
499544290647SDimitry Andric     }
4996139f7f9bSDimitry Andric 
499744290647SDimitry Andric     // Find all of the submodules and emit the module initializers.
499844290647SDimitry Andric     llvm::SmallPtrSet<clang::Module *, 16> Visited;
499944290647SDimitry Andric     SmallVector<clang::Module *, 16> Stack;
500044290647SDimitry Andric     Visited.insert(Import->getImportedModule());
500144290647SDimitry Andric     Stack.push_back(Import->getImportedModule());
500244290647SDimitry Andric 
500344290647SDimitry Andric     while (!Stack.empty()) {
500444290647SDimitry Andric       clang::Module *Mod = Stack.pop_back_val();
500544290647SDimitry Andric       if (!EmittedModuleInitializers.insert(Mod).second)
500644290647SDimitry Andric         continue;
500744290647SDimitry Andric 
500844290647SDimitry Andric       for (auto *D : Context.getModuleInitializers(Mod))
500944290647SDimitry Andric         EmitTopLevelDecl(D);
501044290647SDimitry Andric 
501144290647SDimitry Andric       // Visit the submodules of this module.
501244290647SDimitry Andric       for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
501344290647SDimitry Andric                                              SubEnd = Mod->submodule_end();
501444290647SDimitry Andric            Sub != SubEnd; ++Sub) {
501544290647SDimitry Andric         // Skip explicit children; they need to be explicitly imported to emit
501644290647SDimitry Andric         // the initializers.
501744290647SDimitry Andric         if ((*Sub)->IsExplicit)
501844290647SDimitry Andric           continue;
501944290647SDimitry Andric 
502044290647SDimitry Andric         if (Visited.insert(*Sub).second)
502144290647SDimitry Andric           Stack.push_back(*Sub);
502244290647SDimitry Andric       }
502344290647SDimitry Andric     }
5024139f7f9bSDimitry Andric     break;
5025139f7f9bSDimitry Andric   }
5026139f7f9bSDimitry Andric 
502744290647SDimitry Andric   case Decl::Export:
502844290647SDimitry Andric     EmitDeclContext(cast<ExportDecl>(D));
502944290647SDimitry Andric     break;
503044290647SDimitry Andric 
503139d628a0SDimitry Andric   case Decl::OMPThreadPrivate:
503239d628a0SDimitry Andric     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
503339d628a0SDimitry Andric     break;
503439d628a0SDimitry Andric 
5035e7145dcbSDimitry Andric   case Decl::OMPDeclareReduction:
5036e7145dcbSDimitry Andric     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
5037e7145dcbSDimitry Andric     break;
5038e7145dcbSDimitry Andric 
5039*b5893f02SDimitry Andric   case Decl::OMPRequires:
5040*b5893f02SDimitry Andric     EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
5041*b5893f02SDimitry Andric     break;
5042*b5893f02SDimitry Andric 
5043f22ef01cSRoman Divacky   default:
5044f22ef01cSRoman Divacky     // Make sure we handled everything we should, every other kind is a
5045f22ef01cSRoman Divacky     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
5046f22ef01cSRoman Divacky     // function. Need to recode Decl::Kind to do that easily.
5047f22ef01cSRoman Divacky     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
504839d628a0SDimitry Andric     break;
504939d628a0SDimitry Andric   }
505039d628a0SDimitry Andric }
505139d628a0SDimitry Andric 
AddDeferredUnusedCoverageMapping(Decl * D)505239d628a0SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
505339d628a0SDimitry Andric   // Do we need to generate coverage mapping?
505439d628a0SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
505539d628a0SDimitry Andric     return;
505639d628a0SDimitry Andric   switch (D->getKind()) {
505739d628a0SDimitry Andric   case Decl::CXXConversion:
505839d628a0SDimitry Andric   case Decl::CXXMethod:
505939d628a0SDimitry Andric   case Decl::Function:
506039d628a0SDimitry Andric   case Decl::ObjCMethod:
506139d628a0SDimitry Andric   case Decl::CXXConstructor:
506239d628a0SDimitry Andric   case Decl::CXXDestructor: {
50630623d748SDimitry Andric     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
506439d628a0SDimitry Andric       return;
50659a199699SDimitry Andric     SourceManager &SM = getContext().getSourceManager();
5066*b5893f02SDimitry Andric     if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
50679a199699SDimitry Andric       return;
506839d628a0SDimitry Andric     auto I = DeferredEmptyCoverageMappingDecls.find(D);
506939d628a0SDimitry Andric     if (I == DeferredEmptyCoverageMappingDecls.end())
507039d628a0SDimitry Andric       DeferredEmptyCoverageMappingDecls[D] = true;
507139d628a0SDimitry Andric     break;
507239d628a0SDimitry Andric   }
507339d628a0SDimitry Andric   default:
507439d628a0SDimitry Andric     break;
507539d628a0SDimitry Andric   };
507639d628a0SDimitry Andric }
507739d628a0SDimitry Andric 
ClearUnusedCoverageMapping(const Decl * D)507839d628a0SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
507939d628a0SDimitry Andric   // Do we need to generate coverage mapping?
508039d628a0SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
508139d628a0SDimitry Andric     return;
508239d628a0SDimitry Andric   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
508339d628a0SDimitry Andric     if (Fn->isTemplateInstantiation())
508439d628a0SDimitry Andric       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
508539d628a0SDimitry Andric   }
508639d628a0SDimitry Andric   auto I = DeferredEmptyCoverageMappingDecls.find(D);
508739d628a0SDimitry Andric   if (I == DeferredEmptyCoverageMappingDecls.end())
508839d628a0SDimitry Andric     DeferredEmptyCoverageMappingDecls[D] = false;
508939d628a0SDimitry Andric   else
509039d628a0SDimitry Andric     I->second = false;
509139d628a0SDimitry Andric }
509239d628a0SDimitry Andric 
EmitDeferredUnusedCoverageMappings()509339d628a0SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
509413ddaa84SDimitry Andric   // We call takeVector() here to avoid use-after-free.
509513ddaa84SDimitry Andric   // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
509613ddaa84SDimitry Andric   // we deserialize function bodies to emit coverage info for them, and that
509713ddaa84SDimitry Andric   // deserializes more declarations. How should we handle that case?
509813ddaa84SDimitry Andric   for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
50999a199699SDimitry Andric     if (!Entry.second)
510039d628a0SDimitry Andric       continue;
51019a199699SDimitry Andric     const Decl *D = Entry.first;
510239d628a0SDimitry Andric     switch (D->getKind()) {
510339d628a0SDimitry Andric     case Decl::CXXConversion:
510439d628a0SDimitry Andric     case Decl::CXXMethod:
510539d628a0SDimitry Andric     case Decl::Function:
510639d628a0SDimitry Andric     case Decl::ObjCMethod: {
510739d628a0SDimitry Andric       CodeGenPGO PGO(*this);
510839d628a0SDimitry Andric       GlobalDecl GD(cast<FunctionDecl>(D));
510939d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
511039d628a0SDimitry Andric                                   getFunctionLinkage(GD));
511139d628a0SDimitry Andric       break;
511239d628a0SDimitry Andric     }
511339d628a0SDimitry Andric     case Decl::CXXConstructor: {
511439d628a0SDimitry Andric       CodeGenPGO PGO(*this);
511539d628a0SDimitry Andric       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
511639d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
511739d628a0SDimitry Andric                                   getFunctionLinkage(GD));
511839d628a0SDimitry Andric       break;
511939d628a0SDimitry Andric     }
512039d628a0SDimitry Andric     case Decl::CXXDestructor: {
512139d628a0SDimitry Andric       CodeGenPGO PGO(*this);
512239d628a0SDimitry Andric       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
512339d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
512439d628a0SDimitry Andric                                   getFunctionLinkage(GD));
512539d628a0SDimitry Andric       break;
512639d628a0SDimitry Andric     }
512739d628a0SDimitry Andric     default:
512839d628a0SDimitry Andric       break;
512939d628a0SDimitry Andric     };
5130f22ef01cSRoman Divacky   }
5131f22ef01cSRoman Divacky }
5132ffd1746dSEd Schouten 
5133ffd1746dSEd Schouten /// Turns the given pointer into a constant.
GetPointerConstant(llvm::LLVMContext & Context,const void * Ptr)5134ffd1746dSEd Schouten static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
5135ffd1746dSEd Schouten                                           const void *Ptr) {
5136ffd1746dSEd Schouten   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
51376122f3e6SDimitry Andric   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
5138ffd1746dSEd Schouten   return llvm::ConstantInt::get(i64, PtrInt);
5139ffd1746dSEd Schouten }
5140ffd1746dSEd Schouten 
EmitGlobalDeclMetadata(CodeGenModule & CGM,llvm::NamedMDNode * & GlobalMetadata,GlobalDecl D,llvm::GlobalValue * Addr)5141ffd1746dSEd Schouten static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
5142ffd1746dSEd Schouten                                    llvm::NamedMDNode *&GlobalMetadata,
5143ffd1746dSEd Schouten                                    GlobalDecl D,
5144ffd1746dSEd Schouten                                    llvm::GlobalValue *Addr) {
5145ffd1746dSEd Schouten   if (!GlobalMetadata)
5146ffd1746dSEd Schouten     GlobalMetadata =
5147ffd1746dSEd Schouten       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
5148ffd1746dSEd Schouten 
5149ffd1746dSEd Schouten   // TODO: should we report variant information for ctors/dtors?
515039d628a0SDimitry Andric   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
515139d628a0SDimitry Andric                            llvm::ConstantAsMetadata::get(GetPointerConstant(
515239d628a0SDimitry Andric                                CGM.getLLVMContext(), D.getDecl()))};
51533b0f4066SDimitry Andric   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
5154ffd1746dSEd Schouten }
5155ffd1746dSEd Schouten 
5156284c1978SDimitry Andric /// For each function which is declared within an extern "C" region and marked
5157284c1978SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled
5158284c1978SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer
5159284c1978SDimitry Andric /// to such functions with an unmangled name from inline assembly within the
5160284c1978SDimitry Andric /// same translation unit.
EmitStaticExternCAliases()5161284c1978SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() {
51624ba319b5SDimitry Andric   if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
5163e7145dcbSDimitry Andric     return;
51648f0fd8f6SDimitry Andric   for (auto &I : StaticExternCValues) {
51658f0fd8f6SDimitry Andric     IdentifierInfo *Name = I.first;
51668f0fd8f6SDimitry Andric     llvm::GlobalValue *Val = I.second;
5167284c1978SDimitry Andric     if (Val && !getModule().getNamedValue(Name->getName()))
516859d1ed5bSDimitry Andric       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
5169284c1978SDimitry Andric   }
5170284c1978SDimitry Andric }
5171284c1978SDimitry Andric 
lookupRepresentativeDecl(StringRef MangledName,GlobalDecl & Result) const517259d1ed5bSDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
517359d1ed5bSDimitry Andric                                              GlobalDecl &Result) const {
517459d1ed5bSDimitry Andric   auto Res = Manglings.find(MangledName);
517559d1ed5bSDimitry Andric   if (Res == Manglings.end())
517659d1ed5bSDimitry Andric     return false;
517759d1ed5bSDimitry Andric   Result = Res->getValue();
517859d1ed5bSDimitry Andric   return true;
517959d1ed5bSDimitry Andric }
518059d1ed5bSDimitry Andric 
5181ffd1746dSEd Schouten /// Emits metadata nodes associating all the global values in the
5182ffd1746dSEd Schouten /// current module with the Decls they came from.  This is useful for
5183ffd1746dSEd Schouten /// projects using IR gen as a subroutine.
5184ffd1746dSEd Schouten ///
5185ffd1746dSEd Schouten /// Since there's currently no way to associate an MDNode directly
5186ffd1746dSEd Schouten /// with an llvm::GlobalValue, we create a global named metadata
5187ffd1746dSEd Schouten /// with the name 'clang.global.decl.ptrs'.
EmitDeclMetadata()5188ffd1746dSEd Schouten void CodeGenModule::EmitDeclMetadata() {
518959d1ed5bSDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
5190ffd1746dSEd Schouten 
519159d1ed5bSDimitry Andric   for (auto &I : MangledDeclNames) {
519259d1ed5bSDimitry Andric     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
51930623d748SDimitry Andric     // Some mangled names don't necessarily have an associated GlobalValue
51940623d748SDimitry Andric     // in this module, e.g. if we mangled it for DebugInfo.
51950623d748SDimitry Andric     if (Addr)
519659d1ed5bSDimitry Andric       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
5197ffd1746dSEd Schouten   }
5198ffd1746dSEd Schouten }
5199ffd1746dSEd Schouten 
5200ffd1746dSEd Schouten /// Emits metadata nodes for all the local variables in the current
5201ffd1746dSEd Schouten /// function.
EmitDeclMetadata()5202ffd1746dSEd Schouten void CodeGenFunction::EmitDeclMetadata() {
5203ffd1746dSEd Schouten   if (LocalDeclMap.empty()) return;
5204ffd1746dSEd Schouten 
5205ffd1746dSEd Schouten   llvm::LLVMContext &Context = getLLVMContext();
5206ffd1746dSEd Schouten 
5207ffd1746dSEd Schouten   // Find the unique metadata ID for this name.
5208ffd1746dSEd Schouten   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
5209ffd1746dSEd Schouten 
521059d1ed5bSDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
5211ffd1746dSEd Schouten 
521259d1ed5bSDimitry Andric   for (auto &I : LocalDeclMap) {
521359d1ed5bSDimitry Andric     const Decl *D = I.first;
52140623d748SDimitry Andric     llvm::Value *Addr = I.second.getPointer();
521559d1ed5bSDimitry Andric     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
5216ffd1746dSEd Schouten       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
521739d628a0SDimitry Andric       Alloca->setMetadata(
521839d628a0SDimitry Andric           DeclPtrKind, llvm::MDNode::get(
521939d628a0SDimitry Andric                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
522059d1ed5bSDimitry Andric     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
5221ffd1746dSEd Schouten       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
5222ffd1746dSEd Schouten       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
5223ffd1746dSEd Schouten     }
5224ffd1746dSEd Schouten   }
5225ffd1746dSEd Schouten }
5226e580952dSDimitry Andric 
EmitVersionIdentMetadata()5227f785676fSDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() {
5228f785676fSDimitry Andric   llvm::NamedMDNode *IdentMetadata =
5229f785676fSDimitry Andric     TheModule.getOrInsertNamedMetadata("llvm.ident");
5230f785676fSDimitry Andric   std::string Version = getClangFullVersion();
5231f785676fSDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
5232f785676fSDimitry Andric 
523339d628a0SDimitry Andric   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
5234f785676fSDimitry Andric   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
5235f785676fSDimitry Andric }
5236f785676fSDimitry Andric 
EmitCommandLineMetadata()5237*b5893f02SDimitry Andric void CodeGenModule::EmitCommandLineMetadata() {
5238*b5893f02SDimitry Andric   llvm::NamedMDNode *CommandLineMetadata =
5239*b5893f02SDimitry Andric     TheModule.getOrInsertNamedMetadata("llvm.commandline");
5240*b5893f02SDimitry Andric   std::string CommandLine = getCodeGenOpts().RecordCommandLine;
5241*b5893f02SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
5242*b5893f02SDimitry Andric 
5243*b5893f02SDimitry Andric   llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
5244*b5893f02SDimitry Andric   CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
5245*b5893f02SDimitry Andric }
5246*b5893f02SDimitry Andric 
EmitTargetMetadata()524759d1ed5bSDimitry Andric void CodeGenModule::EmitTargetMetadata() {
524839d628a0SDimitry Andric   // Warning, new MangledDeclNames may be appended within this loop.
524939d628a0SDimitry Andric   // We rely on MapVector insertions adding new elements to the end
525039d628a0SDimitry Andric   // of the container.
525139d628a0SDimitry Andric   // FIXME: Move this loop into the one target that needs it, and only
525239d628a0SDimitry Andric   // loop over those declarations for which we couldn't emit the target
525339d628a0SDimitry Andric   // metadata when we emitted the declaration.
525439d628a0SDimitry Andric   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
525539d628a0SDimitry Andric     auto Val = *(MangledDeclNames.begin() + I);
525639d628a0SDimitry Andric     const Decl *D = Val.first.getDecl()->getMostRecentDecl();
525739d628a0SDimitry Andric     llvm::GlobalValue *GV = GetGlobalValue(Val.second);
525859d1ed5bSDimitry Andric     getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
525959d1ed5bSDimitry Andric   }
526059d1ed5bSDimitry Andric }
526159d1ed5bSDimitry Andric 
EmitCoverageFile()5262bd5abe19SDimitry Andric void CodeGenModule::EmitCoverageFile() {
526344290647SDimitry Andric   if (getCodeGenOpts().CoverageDataFile.empty() &&
526444290647SDimitry Andric       getCodeGenOpts().CoverageNotesFile.empty())
526544290647SDimitry Andric     return;
526644290647SDimitry Andric 
526744290647SDimitry Andric   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
526844290647SDimitry Andric   if (!CUNode)
526944290647SDimitry Andric     return;
527044290647SDimitry Andric 
5271bd5abe19SDimitry Andric   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
5272bd5abe19SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
527344290647SDimitry Andric   auto *CoverageDataFile =
527444290647SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
527544290647SDimitry Andric   auto *CoverageNotesFile =
527644290647SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
5277bd5abe19SDimitry Andric   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
5278bd5abe19SDimitry Andric     llvm::MDNode *CU = CUNode->getOperand(i);
527944290647SDimitry Andric     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
528039d628a0SDimitry Andric     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
5281bd5abe19SDimitry Andric   }
5282bd5abe19SDimitry Andric }
52833861d79fSDimitry Andric 
EmitUuidofInitializer(StringRef Uuid)528439d628a0SDimitry Andric llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
52853861d79fSDimitry Andric   // Sema has checked that all uuid strings are of the form
52863861d79fSDimitry Andric   // "12345678-1234-1234-1234-1234567890ab".
52873861d79fSDimitry Andric   assert(Uuid.size() == 36);
5288f785676fSDimitry Andric   for (unsigned i = 0; i < 36; ++i) {
5289f785676fSDimitry Andric     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
5290f785676fSDimitry Andric     else                                         assert(isHexDigit(Uuid[i]));
52913861d79fSDimitry Andric   }
52923861d79fSDimitry Andric 
529339d628a0SDimitry Andric   // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
5294f785676fSDimitry Andric   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
52953861d79fSDimitry Andric 
5296f785676fSDimitry Andric   llvm::Constant *Field3[8];
5297f785676fSDimitry Andric   for (unsigned Idx = 0; Idx < 8; ++Idx)
5298f785676fSDimitry Andric     Field3[Idx] = llvm::ConstantInt::get(
5299f785676fSDimitry Andric         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
53003861d79fSDimitry Andric 
5301f785676fSDimitry Andric   llvm::Constant *Fields[4] = {
5302f785676fSDimitry Andric     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
5303f785676fSDimitry Andric     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
5304f785676fSDimitry Andric     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
5305f785676fSDimitry Andric     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
5306f785676fSDimitry Andric   };
5307f785676fSDimitry Andric 
5308f785676fSDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
53093861d79fSDimitry Andric }
531059d1ed5bSDimitry Andric 
GetAddrOfRTTIDescriptor(QualType Ty,bool ForEH)531159d1ed5bSDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
531259d1ed5bSDimitry Andric                                                        bool ForEH) {
531359d1ed5bSDimitry Andric   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
531459d1ed5bSDimitry Andric   // FIXME: should we even be calling this method if RTTI is disabled
531559d1ed5bSDimitry Andric   // and it's not for EH?
53164ba319b5SDimitry Andric   if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice)
531759d1ed5bSDimitry Andric     return llvm::Constant::getNullValue(Int8PtrTy);
531859d1ed5bSDimitry Andric 
531959d1ed5bSDimitry Andric   if (ForEH && Ty->isObjCObjectPointerType() &&
532059d1ed5bSDimitry Andric       LangOpts.ObjCRuntime.isGNUFamily())
532159d1ed5bSDimitry Andric     return ObjCRuntime->GetEHType(Ty);
532259d1ed5bSDimitry Andric 
532359d1ed5bSDimitry Andric   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
532459d1ed5bSDimitry Andric }
532559d1ed5bSDimitry Andric 
EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl * D)532639d628a0SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
532730785c0eSDimitry Andric   // Do not emit threadprivates in simd-only mode.
532830785c0eSDimitry Andric   if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
532930785c0eSDimitry Andric     return;
533039d628a0SDimitry Andric   for (auto RefExpr : D->varlists()) {
533139d628a0SDimitry Andric     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
533239d628a0SDimitry Andric     bool PerformInit =
533339d628a0SDimitry Andric         VD->getAnyInitializer() &&
533439d628a0SDimitry Andric         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
533539d628a0SDimitry Andric                                                         /*ForRef=*/false);
53360623d748SDimitry Andric 
53370623d748SDimitry Andric     Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
533833956c43SDimitry Andric     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
5339*b5893f02SDimitry Andric             VD, Addr, RefExpr->getBeginLoc(), PerformInit))
534039d628a0SDimitry Andric       CXXGlobalInits.push_back(InitFunction);
534139d628a0SDimitry Andric   }
534239d628a0SDimitry Andric }
53438f0fd8f6SDimitry Andric 
53444ba319b5SDimitry Andric llvm::Metadata *
CreateMetadataIdentifierImpl(QualType T,MetadataTypeMap & Map,StringRef Suffix)53454ba319b5SDimitry Andric CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
53464ba319b5SDimitry Andric                                             StringRef Suffix) {
53474ba319b5SDimitry Andric   llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
53480623d748SDimitry Andric   if (InternalId)
53490623d748SDimitry Andric     return InternalId;
53500623d748SDimitry Andric 
53510623d748SDimitry Andric   if (isExternallyVisible(T->getLinkage())) {
53528f0fd8f6SDimitry Andric     std::string OutName;
53538f0fd8f6SDimitry Andric     llvm::raw_string_ostream Out(OutName);
53540623d748SDimitry Andric     getCXXABI().getMangleContext().mangleTypeName(T, Out);
53554ba319b5SDimitry Andric     Out << Suffix;
53568f0fd8f6SDimitry Andric 
53570623d748SDimitry Andric     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
53580623d748SDimitry Andric   } else {
53590623d748SDimitry Andric     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
53600623d748SDimitry Andric                                            llvm::ArrayRef<llvm::Metadata *>());
53610623d748SDimitry Andric   }
53620623d748SDimitry Andric 
53630623d748SDimitry Andric   return InternalId;
53640623d748SDimitry Andric }
53650623d748SDimitry Andric 
CreateMetadataIdentifierForType(QualType T)53664ba319b5SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
53674ba319b5SDimitry Andric   return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
53684ba319b5SDimitry Andric }
53694ba319b5SDimitry Andric 
53704ba319b5SDimitry Andric llvm::Metadata *
CreateMetadataIdentifierForVirtualMemPtrType(QualType T)53714ba319b5SDimitry Andric CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
53724ba319b5SDimitry Andric   return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
53734ba319b5SDimitry Andric }
53744ba319b5SDimitry Andric 
53759a199699SDimitry Andric // Generalize pointer types to a void pointer with the qualifiers of the
53769a199699SDimitry Andric // originally pointed-to type, e.g. 'const char *' and 'char * const *'
53779a199699SDimitry Andric // generalize to 'const void *' while 'char *' and 'const char **' generalize to
53789a199699SDimitry Andric // 'void *'.
GeneralizeType(ASTContext & Ctx,QualType Ty)53799a199699SDimitry Andric static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
53809a199699SDimitry Andric   if (!Ty->isPointerType())
53819a199699SDimitry Andric     return Ty;
53829a199699SDimitry Andric 
53839a199699SDimitry Andric   return Ctx.getPointerType(
53849a199699SDimitry Andric       QualType(Ctx.VoidTy).withCVRQualifiers(
53859a199699SDimitry Andric           Ty->getPointeeType().getCVRQualifiers()));
53869a199699SDimitry Andric }
53879a199699SDimitry Andric 
53889a199699SDimitry Andric // Apply type generalization to a FunctionType's return and argument types
GeneralizeFunctionType(ASTContext & Ctx,QualType Ty)53899a199699SDimitry Andric static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
53909a199699SDimitry Andric   if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
53919a199699SDimitry Andric     SmallVector<QualType, 8> GeneralizedParams;
53929a199699SDimitry Andric     for (auto &Param : FnType->param_types())
53939a199699SDimitry Andric       GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
53949a199699SDimitry Andric 
53959a199699SDimitry Andric     return Ctx.getFunctionType(
53969a199699SDimitry Andric         GeneralizeType(Ctx, FnType->getReturnType()),
53979a199699SDimitry Andric         GeneralizedParams, FnType->getExtProtoInfo());
53989a199699SDimitry Andric   }
53999a199699SDimitry Andric 
54009a199699SDimitry Andric   if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
54019a199699SDimitry Andric     return Ctx.getFunctionNoProtoType(
54029a199699SDimitry Andric         GeneralizeType(Ctx, FnType->getReturnType()));
54039a199699SDimitry Andric 
54049a199699SDimitry Andric   llvm_unreachable("Encountered unknown FunctionType");
54059a199699SDimitry Andric }
54069a199699SDimitry Andric 
CreateMetadataIdentifierGeneralized(QualType T)54079a199699SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
54084ba319b5SDimitry Andric   return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
54094ba319b5SDimitry Andric                                       GeneralizedMetadataIdMap, ".generalized");
54109a199699SDimitry Andric }
54119a199699SDimitry Andric 
5412e7145dcbSDimitry Andric /// Returns whether this module needs the "all-vtables" type identifier.
NeedAllVtablesTypeId() const5413e7145dcbSDimitry Andric bool CodeGenModule::NeedAllVtablesTypeId() const {
5414e7145dcbSDimitry Andric   // Returns true if at least one of vtable-based CFI checkers is enabled and
5415e7145dcbSDimitry Andric   // is not in the trapping mode.
5416e7145dcbSDimitry Andric   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
5417e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
5418e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
5419e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
5420e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
5421e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
5422e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
5423e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
5424e7145dcbSDimitry Andric }
5425e7145dcbSDimitry Andric 
AddVTableTypeMetadata(llvm::GlobalVariable * VTable,CharUnits Offset,const CXXRecordDecl * RD)5426e7145dcbSDimitry Andric void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
54270623d748SDimitry Andric                                           CharUnits Offset,
54280623d748SDimitry Andric                                           const CXXRecordDecl *RD) {
54290623d748SDimitry Andric   llvm::Metadata *MD =
54300623d748SDimitry Andric       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
5431e7145dcbSDimitry Andric   VTable->addTypeMetadata(Offset.getQuantity(), MD);
54320623d748SDimitry Andric 
5433e7145dcbSDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
5434e7145dcbSDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
5435e7145dcbSDimitry Andric       VTable->addTypeMetadata(Offset.getQuantity(),
5436e7145dcbSDimitry Andric                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
5437e7145dcbSDimitry Andric 
5438e7145dcbSDimitry Andric   if (NeedAllVtablesTypeId()) {
5439e7145dcbSDimitry Andric     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
5440e7145dcbSDimitry Andric     VTable->addTypeMetadata(Offset.getQuantity(), MD);
54410623d748SDimitry Andric   }
54420623d748SDimitry Andric }
54430623d748SDimitry Andric 
filterFunctionTargetAttrs(const TargetAttr * TD)54444ba319b5SDimitry Andric TargetAttr::ParsedTargetAttr CodeGenModule::filterFunctionTargetAttrs(const TargetAttr *TD) {
54454ba319b5SDimitry Andric   assert(TD != nullptr);
54460623d748SDimitry Andric   TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
54470623d748SDimitry Andric 
54489a199699SDimitry Andric   ParsedAttr.Features.erase(
54499a199699SDimitry Andric       llvm::remove_if(ParsedAttr.Features,
54509a199699SDimitry Andric                       [&](const std::string &Feat) {
54519a199699SDimitry Andric                         return !Target.isValidFeatureName(
54529a199699SDimitry Andric                             StringRef{Feat}.substr(1));
54539a199699SDimitry Andric                       }),
54549a199699SDimitry Andric       ParsedAttr.Features.end());
54554ba319b5SDimitry Andric   return ParsedAttr;
54564ba319b5SDimitry Andric }
54574ba319b5SDimitry Andric 
54584ba319b5SDimitry Andric 
54594ba319b5SDimitry Andric // Fills in the supplied string map with the set of target features for the
54604ba319b5SDimitry Andric // passed in function.
getFunctionFeatureMap(llvm::StringMap<bool> & FeatureMap,GlobalDecl GD)54614ba319b5SDimitry Andric void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
5462*b5893f02SDimitry Andric                                           GlobalDecl GD) {
54634ba319b5SDimitry Andric   StringRef TargetCPU = Target.getTargetOpts().CPU;
5464*b5893f02SDimitry Andric   const FunctionDecl *FD = GD.getDecl()->getAsFunction();
54654ba319b5SDimitry Andric   if (const auto *TD = FD->getAttr<TargetAttr>()) {
54664ba319b5SDimitry Andric     TargetAttr::ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
54679a199699SDimitry Andric 
54680623d748SDimitry Andric     // Make a copy of the features as passed on the command line into the
54690623d748SDimitry Andric     // beginning of the additional features from the function to override.
5470b40b48b8SDimitry Andric     ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
54710623d748SDimitry Andric                             Target.getTargetOpts().FeaturesAsWritten.begin(),
54720623d748SDimitry Andric                             Target.getTargetOpts().FeaturesAsWritten.end());
54730623d748SDimitry Andric 
54749a199699SDimitry Andric     if (ParsedAttr.Architecture != "" &&
54759a199699SDimitry Andric         Target.isValidCPUName(ParsedAttr.Architecture))
5476b40b48b8SDimitry Andric       TargetCPU = ParsedAttr.Architecture;
54770623d748SDimitry Andric 
54780623d748SDimitry Andric     // Now populate the feature map, first with the TargetCPU which is either
54790623d748SDimitry Andric     // the default or a new one from the target attribute string. Then we'll use
54800623d748SDimitry Andric     // the passed in features (FeaturesAsWritten) along with the new ones from
54810623d748SDimitry Andric     // the attribute.
5482b40b48b8SDimitry Andric     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
5483b40b48b8SDimitry Andric                           ParsedAttr.Features);
54844ba319b5SDimitry Andric   } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
54854ba319b5SDimitry Andric     llvm::SmallVector<StringRef, 32> FeaturesTmp;
5486*b5893f02SDimitry Andric     Target.getCPUSpecificCPUDispatchFeatures(
5487*b5893f02SDimitry Andric         SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
54884ba319b5SDimitry Andric     std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
54894ba319b5SDimitry Andric     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, Features);
54900623d748SDimitry Andric   } else {
54910623d748SDimitry Andric     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
54920623d748SDimitry Andric                           Target.getTargetOpts().Features);
54930623d748SDimitry Andric   }
54948f0fd8f6SDimitry Andric }
5495e7145dcbSDimitry Andric 
getSanStats()5496e7145dcbSDimitry Andric llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
5497e7145dcbSDimitry Andric   if (!SanStats)
5498e7145dcbSDimitry Andric     SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
5499e7145dcbSDimitry Andric 
5500e7145dcbSDimitry Andric   return *SanStats;
5501e7145dcbSDimitry Andric }
550244290647SDimitry Andric llvm::Value *
createOpenCLIntToSamplerConversion(const Expr * E,CodeGenFunction & CGF)550344290647SDimitry Andric CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
550444290647SDimitry Andric                                                   CodeGenFunction &CGF) {
55059a199699SDimitry Andric   llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
55069a199699SDimitry Andric   auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
550744290647SDimitry Andric   auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
550844290647SDimitry Andric   return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
550944290647SDimitry Andric                                 "__translate_sampler_initializer"),
551044290647SDimitry Andric                                 {C});
551144290647SDimitry Andric }
5512