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"
26139f7f9bSDimitry Andric #include "CodeGenTBAA.h"
2744290647SDimitry Andric #include "ConstantBuilder.h"
2839d628a0SDimitry Andric #include "CoverageMappingGen.h"
29f22ef01cSRoman Divacky #include "TargetInfo.h"
30f22ef01cSRoman Divacky #include "clang/AST/ASTContext.h"
31f22ef01cSRoman Divacky #include "clang/AST/CharUnits.h"
32f22ef01cSRoman Divacky #include "clang/AST/DeclCXX.h"
33139f7f9bSDimitry Andric #include "clang/AST/DeclObjC.h"
34ffd1746dSEd Schouten #include "clang/AST/DeclTemplate.h"
352754fe60SDimitry Andric #include "clang/AST/Mangle.h"
36f22ef01cSRoman Divacky #include "clang/AST/RecordLayout.h"
37f8254f43SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h"
38dff0c46cSDimitry Andric #include "clang/Basic/Builtins.h"
39139f7f9bSDimitry Andric #include "clang/Basic/CharInfo.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"
45139f7f9bSDimitry Andric #include "clang/Frontend/CodeGenOptions.h"
46f785676fSDimitry Andric #include "clang/Sema/SemaDiagnostic.h"
47f22ef01cSRoman Divacky #include "llvm/ADT/Triple.h"
4859d1ed5bSDimitry Andric #include "llvm/IR/CallSite.h"
49139f7f9bSDimitry Andric #include "llvm/IR/CallingConv.h"
50139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h"
51139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h"
52139f7f9bSDimitry Andric #include "llvm/IR/LLVMContext.h"
53139f7f9bSDimitry Andric #include "llvm/IR/Module.h"
5459d1ed5bSDimitry Andric #include "llvm/ProfileData/InstrProfReader.h"
55139f7f9bSDimitry Andric #include "llvm/Support/ConvertUTF.h"
56f22ef01cSRoman Divacky #include "llvm/Support/ErrorHandling.h"
570623d748SDimitry Andric #include "llvm/Support/MD5.h"
58139f7f9bSDimitry Andric 
59f22ef01cSRoman Divacky using namespace clang;
60f22ef01cSRoman Divacky using namespace CodeGen;
61f22ef01cSRoman Divacky 
626122f3e6SDimitry Andric static const char AnnotationSection[] = "llvm.metadata";
636122f3e6SDimitry Andric 
6459d1ed5bSDimitry Andric static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
65284c1978SDimitry Andric   switch (CGM.getTarget().getCXXABI().getKind()) {
66139f7f9bSDimitry Andric   case TargetCXXABI::GenericAArch64:
67139f7f9bSDimitry Andric   case TargetCXXABI::GenericARM:
68139f7f9bSDimitry Andric   case TargetCXXABI::iOS:
6959d1ed5bSDimitry Andric   case TargetCXXABI::iOS64:
700623d748SDimitry Andric   case TargetCXXABI::WatchOS:
71ef6fa9e2SDimitry Andric   case TargetCXXABI::GenericMIPS:
72139f7f9bSDimitry Andric   case TargetCXXABI::GenericItanium:
730623d748SDimitry Andric   case TargetCXXABI::WebAssembly:
7459d1ed5bSDimitry Andric     return CreateItaniumCXXABI(CGM);
75139f7f9bSDimitry Andric   case TargetCXXABI::Microsoft:
7659d1ed5bSDimitry Andric     return CreateMicrosoftCXXABI(CGM);
77e580952dSDimitry Andric   }
78e580952dSDimitry Andric 
79e580952dSDimitry Andric   llvm_unreachable("invalid C++ ABI kind");
80e580952dSDimitry Andric }
81e580952dSDimitry Andric 
823dac3a9bSDimitry Andric CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
833dac3a9bSDimitry Andric                              const PreprocessorOptions &PPO,
843dac3a9bSDimitry Andric                              const CodeGenOptions &CGO, llvm::Module &M,
8539d628a0SDimitry Andric                              DiagnosticsEngine &diags,
8639d628a0SDimitry Andric                              CoverageSourceInfo *CoverageInfo)
873dac3a9bSDimitry Andric     : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
883dac3a9bSDimitry Andric       PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
890623d748SDimitry Andric       Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
90e7145dcbSDimitry Andric       VMContext(M.getContext()), Types(*this), VTables(*this),
91e7145dcbSDimitry Andric       SanitizerMD(new SanitizerMetadata(*this)) {
92dff0c46cSDimitry Andric 
93dff0c46cSDimitry Andric   // Initialize the type cache.
94dff0c46cSDimitry Andric   llvm::LLVMContext &LLVMContext = M.getContext();
95dff0c46cSDimitry Andric   VoidTy = llvm::Type::getVoidTy(LLVMContext);
96dff0c46cSDimitry Andric   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
97dff0c46cSDimitry Andric   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
98dff0c46cSDimitry Andric   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
99dff0c46cSDimitry Andric   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
100dff0c46cSDimitry Andric   FloatTy = llvm::Type::getFloatTy(LLVMContext);
101dff0c46cSDimitry Andric   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
102dff0c46cSDimitry Andric   PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
103dff0c46cSDimitry Andric   PointerAlignInBytes =
104dff0c46cSDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
10544290647SDimitry Andric   SizeSizeInBytes =
10644290647SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
1070623d748SDimitry Andric   IntAlignInBytes =
1080623d748SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
109dff0c46cSDimitry Andric   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
11044290647SDimitry Andric   IntPtrTy = llvm::IntegerType::get(LLVMContext,
11144290647SDimitry Andric     C.getTargetInfo().getMaxPointerWidth());
112dff0c46cSDimitry Andric   Int8PtrTy = Int8Ty->getPointerTo(0);
113dff0c46cSDimitry Andric   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
114dff0c46cSDimitry Andric 
115139f7f9bSDimitry Andric   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
11639d628a0SDimitry Andric   BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
117139f7f9bSDimitry Andric 
118dff0c46cSDimitry Andric   if (LangOpts.ObjC1)
1193b0f4066SDimitry Andric     createObjCRuntime();
120dff0c46cSDimitry Andric   if (LangOpts.OpenCL)
1216122f3e6SDimitry Andric     createOpenCLRuntime();
12259d1ed5bSDimitry Andric   if (LangOpts.OpenMP)
12359d1ed5bSDimitry Andric     createOpenMPRuntime();
124dff0c46cSDimitry Andric   if (LangOpts.CUDA)
1256122f3e6SDimitry Andric     createCUDARuntime();
126f22ef01cSRoman Divacky 
1277ae0e2c9SDimitry Andric   // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
12839d628a0SDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
1297ae0e2c9SDimitry Andric       (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
130e7145dcbSDimitry Andric     TBAA.reset(new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
131e7145dcbSDimitry Andric                                getCXXABI().getMangleContext()));
1322754fe60SDimitry Andric 
1333b0f4066SDimitry Andric   // If debug info or coverage generation is enabled, create the CGDebugInfo
1343b0f4066SDimitry Andric   // object.
135e7145dcbSDimitry Andric   if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
136e7145dcbSDimitry Andric       CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
137e7145dcbSDimitry Andric     DebugInfo.reset(new CGDebugInfo(*this));
1382754fe60SDimitry Andric 
1392754fe60SDimitry Andric   Block.GlobalUniqueCount = 0;
1402754fe60SDimitry Andric 
1410623d748SDimitry Andric   if (C.getLangOpts().ObjC1)
142e7145dcbSDimitry Andric     ObjCData.reset(new ObjCEntrypoints());
14359d1ed5bSDimitry Andric 
144e7145dcbSDimitry Andric   if (CodeGenOpts.hasProfileClangUse()) {
145e7145dcbSDimitry Andric     auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
146e7145dcbSDimitry Andric         CodeGenOpts.ProfileInstrumentUsePath);
147e7145dcbSDimitry Andric     if (auto E = ReaderOrErr.takeError()) {
14859d1ed5bSDimitry Andric       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1493dac3a9bSDimitry Andric                                               "Could not read profile %0: %1");
150e7145dcbSDimitry Andric       llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
151e7145dcbSDimitry Andric         getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
152e7145dcbSDimitry Andric                                   << EI.message();
153e7145dcbSDimitry Andric       });
15433956c43SDimitry Andric     } else
15533956c43SDimitry Andric       PGOReader = std::move(ReaderOrErr.get());
15659d1ed5bSDimitry Andric   }
15739d628a0SDimitry Andric 
15839d628a0SDimitry Andric   // If coverage mapping generation is enabled, create the
15939d628a0SDimitry Andric   // CoverageMappingModuleGen object.
16039d628a0SDimitry Andric   if (CodeGenOpts.CoverageMapping)
16139d628a0SDimitry Andric     CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
162f22ef01cSRoman Divacky }
163f22ef01cSRoman Divacky 
164e7145dcbSDimitry Andric CodeGenModule::~CodeGenModule() {}
165f22ef01cSRoman Divacky 
166f22ef01cSRoman Divacky void CodeGenModule::createObjCRuntime() {
1677ae0e2c9SDimitry Andric   // This is just isGNUFamily(), but we want to force implementors of
1687ae0e2c9SDimitry Andric   // new ABIs to decide how best to do this.
1697ae0e2c9SDimitry Andric   switch (LangOpts.ObjCRuntime.getKind()) {
1707ae0e2c9SDimitry Andric   case ObjCRuntime::GNUstep:
1717ae0e2c9SDimitry Andric   case ObjCRuntime::GCC:
1727ae0e2c9SDimitry Andric   case ObjCRuntime::ObjFW:
173e7145dcbSDimitry Andric     ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
1747ae0e2c9SDimitry Andric     return;
1757ae0e2c9SDimitry Andric 
1767ae0e2c9SDimitry Andric   case ObjCRuntime::FragileMacOSX:
1777ae0e2c9SDimitry Andric   case ObjCRuntime::MacOSX:
1787ae0e2c9SDimitry Andric   case ObjCRuntime::iOS:
1790623d748SDimitry Andric   case ObjCRuntime::WatchOS:
180e7145dcbSDimitry Andric     ObjCRuntime.reset(CreateMacObjCRuntime(*this));
1817ae0e2c9SDimitry Andric     return;
1827ae0e2c9SDimitry Andric   }
1837ae0e2c9SDimitry Andric   llvm_unreachable("bad runtime kind");
1846122f3e6SDimitry Andric }
1856122f3e6SDimitry Andric 
1866122f3e6SDimitry Andric void CodeGenModule::createOpenCLRuntime() {
187e7145dcbSDimitry Andric   OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
1886122f3e6SDimitry Andric }
1896122f3e6SDimitry Andric 
19059d1ed5bSDimitry Andric void CodeGenModule::createOpenMPRuntime() {
191e7145dcbSDimitry Andric   // Select a specialized code generation class based on the target, if any.
192e7145dcbSDimitry Andric   // If it does not exist use the default implementation.
19344290647SDimitry Andric   switch (getTriple().getArch()) {
194e7145dcbSDimitry Andric   case llvm::Triple::nvptx:
195e7145dcbSDimitry Andric   case llvm::Triple::nvptx64:
196e7145dcbSDimitry Andric     assert(getLangOpts().OpenMPIsDevice &&
197e7145dcbSDimitry Andric            "OpenMP NVPTX is only prepared to deal with device code.");
198e7145dcbSDimitry Andric     OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
199e7145dcbSDimitry Andric     break;
200e7145dcbSDimitry Andric   default:
201e7145dcbSDimitry Andric     OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
202e7145dcbSDimitry Andric     break;
203e7145dcbSDimitry Andric   }
20459d1ed5bSDimitry Andric }
20559d1ed5bSDimitry Andric 
2066122f3e6SDimitry Andric void CodeGenModule::createCUDARuntime() {
207e7145dcbSDimitry Andric   CUDARuntime.reset(CreateNVCUDARuntime(*this));
208f22ef01cSRoman Divacky }
209f22ef01cSRoman Divacky 
21039d628a0SDimitry Andric void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
21139d628a0SDimitry Andric   Replacements[Name] = C;
21239d628a0SDimitry Andric }
21339d628a0SDimitry Andric 
214f785676fSDimitry Andric void CodeGenModule::applyReplacements() {
2158f0fd8f6SDimitry Andric   for (auto &I : Replacements) {
2168f0fd8f6SDimitry Andric     StringRef MangledName = I.first();
2178f0fd8f6SDimitry Andric     llvm::Constant *Replacement = I.second;
218f785676fSDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
219f785676fSDimitry Andric     if (!Entry)
220f785676fSDimitry Andric       continue;
22159d1ed5bSDimitry Andric     auto *OldF = cast<llvm::Function>(Entry);
22259d1ed5bSDimitry Andric     auto *NewF = dyn_cast<llvm::Function>(Replacement);
223f785676fSDimitry Andric     if (!NewF) {
22459d1ed5bSDimitry Andric       if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
22559d1ed5bSDimitry Andric         NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
22659d1ed5bSDimitry Andric       } else {
22759d1ed5bSDimitry Andric         auto *CE = cast<llvm::ConstantExpr>(Replacement);
228f785676fSDimitry Andric         assert(CE->getOpcode() == llvm::Instruction::BitCast ||
229f785676fSDimitry Andric                CE->getOpcode() == llvm::Instruction::GetElementPtr);
230f785676fSDimitry Andric         NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
231f785676fSDimitry Andric       }
23259d1ed5bSDimitry Andric     }
233f785676fSDimitry Andric 
234f785676fSDimitry Andric     // Replace old with new, but keep the old order.
235f785676fSDimitry Andric     OldF->replaceAllUsesWith(Replacement);
236f785676fSDimitry Andric     if (NewF) {
237f785676fSDimitry Andric       NewF->removeFromParent();
2380623d748SDimitry Andric       OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
2390623d748SDimitry Andric                                                        NewF);
240f785676fSDimitry Andric     }
241f785676fSDimitry Andric     OldF->eraseFromParent();
242f785676fSDimitry Andric   }
243f785676fSDimitry Andric }
244f785676fSDimitry Andric 
2450623d748SDimitry Andric void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
2460623d748SDimitry Andric   GlobalValReplacements.push_back(std::make_pair(GV, C));
2470623d748SDimitry Andric }
2480623d748SDimitry Andric 
2490623d748SDimitry Andric void CodeGenModule::applyGlobalValReplacements() {
2500623d748SDimitry Andric   for (auto &I : GlobalValReplacements) {
2510623d748SDimitry Andric     llvm::GlobalValue *GV = I.first;
2520623d748SDimitry Andric     llvm::Constant *C = I.second;
2530623d748SDimitry Andric 
2540623d748SDimitry Andric     GV->replaceAllUsesWith(C);
2550623d748SDimitry Andric     GV->eraseFromParent();
2560623d748SDimitry Andric   }
2570623d748SDimitry Andric }
2580623d748SDimitry Andric 
25959d1ed5bSDimitry Andric // This is only used in aliases that we created and we know they have a
26059d1ed5bSDimitry Andric // linear structure.
261e7145dcbSDimitry Andric static const llvm::GlobalObject *getAliasedGlobal(
262e7145dcbSDimitry Andric     const llvm::GlobalIndirectSymbol &GIS) {
263e7145dcbSDimitry Andric   llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
264e7145dcbSDimitry Andric   const llvm::Constant *C = &GIS;
26559d1ed5bSDimitry Andric   for (;;) {
26659d1ed5bSDimitry Andric     C = C->stripPointerCasts();
26759d1ed5bSDimitry Andric     if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
26859d1ed5bSDimitry Andric       return GO;
26959d1ed5bSDimitry Andric     // stripPointerCasts will not walk over weak aliases.
270e7145dcbSDimitry Andric     auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
271e7145dcbSDimitry Andric     if (!GIS2)
27259d1ed5bSDimitry Andric       return nullptr;
273e7145dcbSDimitry Andric     if (!Visited.insert(GIS2).second)
27459d1ed5bSDimitry Andric       return nullptr;
275e7145dcbSDimitry Andric     C = GIS2->getIndirectSymbol();
27659d1ed5bSDimitry Andric   }
27759d1ed5bSDimitry Andric }
27859d1ed5bSDimitry Andric 
279f785676fSDimitry Andric void CodeGenModule::checkAliases() {
28059d1ed5bSDimitry Andric   // Check if the constructed aliases are well formed. It is really unfortunate
28159d1ed5bSDimitry Andric   // that we have to do this in CodeGen, but we only construct mangled names
28259d1ed5bSDimitry Andric   // and aliases during codegen.
283f785676fSDimitry Andric   bool Error = false;
28459d1ed5bSDimitry Andric   DiagnosticsEngine &Diags = getDiags();
2858f0fd8f6SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
28659d1ed5bSDimitry Andric     const auto *D = cast<ValueDecl>(GD.getDecl());
287e7145dcbSDimitry Andric     SourceLocation Location;
288e7145dcbSDimitry Andric     bool IsIFunc = D->hasAttr<IFuncAttr>();
289e7145dcbSDimitry Andric     if (const Attr *A = D->getDefiningAttr())
290e7145dcbSDimitry Andric       Location = A->getLocation();
291e7145dcbSDimitry Andric     else
292e7145dcbSDimitry Andric       llvm_unreachable("Not an alias or ifunc?");
293f785676fSDimitry Andric     StringRef MangledName = getMangledName(GD);
294f785676fSDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
295e7145dcbSDimitry Andric     auto *Alias  = cast<llvm::GlobalIndirectSymbol>(Entry);
29659d1ed5bSDimitry Andric     const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
29759d1ed5bSDimitry Andric     if (!GV) {
298f785676fSDimitry Andric       Error = true;
299e7145dcbSDimitry Andric       Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
30059d1ed5bSDimitry Andric     } else if (GV->isDeclaration()) {
301f785676fSDimitry Andric       Error = true;
302e7145dcbSDimitry Andric       Diags.Report(Location, diag::err_alias_to_undefined)
303e7145dcbSDimitry Andric           << IsIFunc << IsIFunc;
304e7145dcbSDimitry Andric     } else if (IsIFunc) {
305e7145dcbSDimitry Andric       // Check resolver function type.
306e7145dcbSDimitry Andric       llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
307e7145dcbSDimitry Andric           GV->getType()->getPointerElementType());
308e7145dcbSDimitry Andric       assert(FTy);
309e7145dcbSDimitry Andric       if (!FTy->getReturnType()->isPointerTy())
310e7145dcbSDimitry Andric         Diags.Report(Location, diag::err_ifunc_resolver_return);
311e7145dcbSDimitry Andric       if (FTy->getNumParams())
312e7145dcbSDimitry Andric         Diags.Report(Location, diag::err_ifunc_resolver_params);
31359d1ed5bSDimitry Andric     }
31459d1ed5bSDimitry Andric 
315e7145dcbSDimitry Andric     llvm::Constant *Aliasee = Alias->getIndirectSymbol();
31659d1ed5bSDimitry Andric     llvm::GlobalValue *AliaseeGV;
31759d1ed5bSDimitry Andric     if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
31859d1ed5bSDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
31959d1ed5bSDimitry Andric     else
32059d1ed5bSDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
32159d1ed5bSDimitry Andric 
32259d1ed5bSDimitry Andric     if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
32359d1ed5bSDimitry Andric       StringRef AliasSection = SA->getName();
32459d1ed5bSDimitry Andric       if (AliasSection != AliaseeGV->getSection())
32559d1ed5bSDimitry Andric         Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
326e7145dcbSDimitry Andric             << AliasSection << IsIFunc << IsIFunc;
32759d1ed5bSDimitry Andric     }
32859d1ed5bSDimitry Andric 
32959d1ed5bSDimitry Andric     // We have to handle alias to weak aliases in here. LLVM itself disallows
33059d1ed5bSDimitry Andric     // this since the object semantics would not match the IL one. For
33159d1ed5bSDimitry Andric     // compatibility with gcc we implement it by just pointing the alias
33259d1ed5bSDimitry Andric     // to its aliasee's aliasee. We also warn, since the user is probably
33359d1ed5bSDimitry Andric     // expecting the link to be weak.
334e7145dcbSDimitry Andric     if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
335e7145dcbSDimitry Andric       if (GA->isInterposable()) {
336e7145dcbSDimitry Andric         Diags.Report(Location, diag::warn_alias_to_weak_alias)
337e7145dcbSDimitry Andric             << GV->getName() << GA->getName() << IsIFunc;
33859d1ed5bSDimitry Andric         Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
339e7145dcbSDimitry Andric             GA->getIndirectSymbol(), Alias->getType());
340e7145dcbSDimitry Andric         Alias->setIndirectSymbol(Aliasee);
34159d1ed5bSDimitry Andric       }
342f785676fSDimitry Andric     }
343f785676fSDimitry Andric   }
344f785676fSDimitry Andric   if (!Error)
345f785676fSDimitry Andric     return;
346f785676fSDimitry Andric 
3478f0fd8f6SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
348f785676fSDimitry Andric     StringRef MangledName = getMangledName(GD);
349f785676fSDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
350e7145dcbSDimitry Andric     auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
351f785676fSDimitry Andric     Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
352f785676fSDimitry Andric     Alias->eraseFromParent();
353f785676fSDimitry Andric   }
354f785676fSDimitry Andric }
355f785676fSDimitry Andric 
35659d1ed5bSDimitry Andric void CodeGenModule::clear() {
35759d1ed5bSDimitry Andric   DeferredDeclsToEmit.clear();
35833956c43SDimitry Andric   if (OpenMPRuntime)
35933956c43SDimitry Andric     OpenMPRuntime->clear();
36059d1ed5bSDimitry Andric }
36159d1ed5bSDimitry Andric 
36259d1ed5bSDimitry Andric void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
36359d1ed5bSDimitry Andric                                        StringRef MainFile) {
36459d1ed5bSDimitry Andric   if (!hasDiagnostics())
36559d1ed5bSDimitry Andric     return;
36659d1ed5bSDimitry Andric   if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
36759d1ed5bSDimitry Andric     if (MainFile.empty())
36859d1ed5bSDimitry Andric       MainFile = "<stdin>";
36959d1ed5bSDimitry Andric     Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
37059d1ed5bSDimitry Andric   } else
37159d1ed5bSDimitry Andric     Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Missing
37259d1ed5bSDimitry Andric                                                       << Mismatched;
37359d1ed5bSDimitry Andric }
37459d1ed5bSDimitry Andric 
375f22ef01cSRoman Divacky void CodeGenModule::Release() {
376f22ef01cSRoman Divacky   EmitDeferred();
3770623d748SDimitry Andric   applyGlobalValReplacements();
378f785676fSDimitry Andric   applyReplacements();
379f785676fSDimitry Andric   checkAliases();
380f22ef01cSRoman Divacky   EmitCXXGlobalInitFunc();
381f22ef01cSRoman Divacky   EmitCXXGlobalDtorFunc();
382284c1978SDimitry Andric   EmitCXXThreadLocalInitFunc();
3836122f3e6SDimitry Andric   if (ObjCRuntime)
3846122f3e6SDimitry Andric     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
385f22ef01cSRoman Divacky       AddGlobalCtor(ObjCInitFunction);
38633956c43SDimitry Andric   if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
38733956c43SDimitry Andric       CUDARuntime) {
38833956c43SDimitry Andric     if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
38933956c43SDimitry Andric       AddGlobalCtor(CudaCtorFunction);
39033956c43SDimitry Andric     if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
39133956c43SDimitry Andric       AddGlobalDtor(CudaDtorFunction);
39233956c43SDimitry Andric   }
393ea942507SDimitry Andric   if (OpenMPRuntime)
394ea942507SDimitry Andric     if (llvm::Function *OpenMPRegistrationFunction =
395ea942507SDimitry Andric             OpenMPRuntime->emitRegistrationFunction())
396ea942507SDimitry Andric       AddGlobalCtor(OpenMPRegistrationFunction, 0);
3970623d748SDimitry Andric   if (PGOReader) {
398e7145dcbSDimitry Andric     getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
3990623d748SDimitry Andric     if (PGOStats.hasDiagnostics())
40059d1ed5bSDimitry Andric       PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
4010623d748SDimitry Andric   }
402f22ef01cSRoman Divacky   EmitCtorList(GlobalCtors, "llvm.global_ctors");
403f22ef01cSRoman Divacky   EmitCtorList(GlobalDtors, "llvm.global_dtors");
4046122f3e6SDimitry Andric   EmitGlobalAnnotations();
405284c1978SDimitry Andric   EmitStaticExternCAliases();
40639d628a0SDimitry Andric   EmitDeferredUnusedCoverageMappings();
40739d628a0SDimitry Andric   if (CoverageMapping)
40839d628a0SDimitry Andric     CoverageMapping->emit();
409e7145dcbSDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
410e7145dcbSDimitry Andric     CodeGenFunction(*this).EmitCfiCheckFail();
41159d1ed5bSDimitry Andric   emitLLVMUsed();
412e7145dcbSDimitry Andric   if (SanStats)
413e7145dcbSDimitry Andric     SanStats->finish();
414ffd1746dSEd Schouten 
415f785676fSDimitry Andric   if (CodeGenOpts.Autolink &&
416f785676fSDimitry Andric       (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
417139f7f9bSDimitry Andric     EmitModuleLinkOptions();
418139f7f9bSDimitry Andric   }
4190623d748SDimitry Andric   if (CodeGenOpts.DwarfVersion) {
420f785676fSDimitry Andric     // We actually want the latest version when there are conflicts.
421f785676fSDimitry Andric     // We can change from Warning to Latest if such mode is supported.
422f785676fSDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
423f785676fSDimitry Andric                               CodeGenOpts.DwarfVersion);
4240623d748SDimitry Andric   }
4250623d748SDimitry Andric   if (CodeGenOpts.EmitCodeView) {
4260623d748SDimitry Andric     // Indicate that we want CodeView in the metadata.
4270623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
4280623d748SDimitry Andric   }
4290623d748SDimitry Andric   if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
4300623d748SDimitry Andric     // We don't support LTO with 2 with different StrictVTablePointers
4310623d748SDimitry Andric     // FIXME: we could support it by stripping all the information introduced
4320623d748SDimitry Andric     // by StrictVTablePointers.
4330623d748SDimitry Andric 
4340623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
4350623d748SDimitry Andric 
4360623d748SDimitry Andric     llvm::Metadata *Ops[2] = {
4370623d748SDimitry Andric               llvm::MDString::get(VMContext, "StrictVTablePointers"),
4380623d748SDimitry Andric               llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
4390623d748SDimitry Andric                   llvm::Type::getInt32Ty(VMContext), 1))};
4400623d748SDimitry Andric 
4410623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Require,
4420623d748SDimitry Andric                               "StrictVTablePointersRequirement",
4430623d748SDimitry Andric                               llvm::MDNode::get(VMContext, Ops));
4440623d748SDimitry Andric   }
445f785676fSDimitry Andric   if (DebugInfo)
44659d1ed5bSDimitry Andric     // We support a single version in the linked module. The LLVM
44759d1ed5bSDimitry Andric     // parser will drop debug info with a different version number
44859d1ed5bSDimitry Andric     // (and warn about it, too).
44959d1ed5bSDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
450f785676fSDimitry Andric                               llvm::DEBUG_METADATA_VERSION);
451139f7f9bSDimitry Andric 
45259d1ed5bSDimitry Andric   // We need to record the widths of enums and wchar_t, so that we can generate
45359d1ed5bSDimitry Andric   // the correct build attributes in the ARM backend.
45459d1ed5bSDimitry Andric   llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
45559d1ed5bSDimitry Andric   if (   Arch == llvm::Triple::arm
45659d1ed5bSDimitry Andric       || Arch == llvm::Triple::armeb
45759d1ed5bSDimitry Andric       || Arch == llvm::Triple::thumb
45859d1ed5bSDimitry Andric       || Arch == llvm::Triple::thumbeb) {
45959d1ed5bSDimitry Andric     // Width of wchar_t in bytes
46059d1ed5bSDimitry Andric     uint64_t WCharWidth =
46159d1ed5bSDimitry Andric         Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
46259d1ed5bSDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
46359d1ed5bSDimitry Andric 
46459d1ed5bSDimitry Andric     // The minimum width of an enum in bytes
46559d1ed5bSDimitry Andric     uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
46659d1ed5bSDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
46759d1ed5bSDimitry Andric   }
46859d1ed5bSDimitry Andric 
4690623d748SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
4700623d748SDimitry Andric     // Indicate that we want cross-DSO control flow integrity checks.
4710623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
4720623d748SDimitry Andric   }
4730623d748SDimitry Andric 
47444290647SDimitry Andric   if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
475e7145dcbSDimitry Andric     // Indicate whether __nvvm_reflect should be configured to flush denormal
476e7145dcbSDimitry Andric     // floating point values to 0.  (This corresponds to its "__CUDA_FTZ"
477e7145dcbSDimitry Andric     // property.)
478e7145dcbSDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
479e7145dcbSDimitry Andric                               LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
48039d628a0SDimitry Andric   }
48139d628a0SDimitry Andric 
482e7145dcbSDimitry Andric   if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
483e7145dcbSDimitry Andric     assert(PLevel < 3 && "Invalid PIC Level");
484e7145dcbSDimitry Andric     getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
485e7145dcbSDimitry Andric     if (Context.getLangOpts().PIE)
486e7145dcbSDimitry Andric       getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
48739d628a0SDimitry Andric   }
48839d628a0SDimitry Andric 
4892754fe60SDimitry Andric   SimplifyPersonality();
4902754fe60SDimitry Andric 
491ffd1746dSEd Schouten   if (getCodeGenOpts().EmitDeclMetadata)
492ffd1746dSEd Schouten     EmitDeclMetadata();
493bd5abe19SDimitry Andric 
494bd5abe19SDimitry Andric   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
495bd5abe19SDimitry Andric     EmitCoverageFile();
4966122f3e6SDimitry Andric 
4976122f3e6SDimitry Andric   if (DebugInfo)
4986122f3e6SDimitry Andric     DebugInfo->finalize();
499f785676fSDimitry Andric 
500f785676fSDimitry Andric   EmitVersionIdentMetadata();
50159d1ed5bSDimitry Andric 
50259d1ed5bSDimitry Andric   EmitTargetMetadata();
503f22ef01cSRoman Divacky }
504f22ef01cSRoman Divacky 
5053b0f4066SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
5063b0f4066SDimitry Andric   // Make sure that this type is translated.
5073b0f4066SDimitry Andric   Types.UpdateCompletedType(TD);
5083b0f4066SDimitry Andric }
5093b0f4066SDimitry Andric 
510e7145dcbSDimitry Andric void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
511e7145dcbSDimitry Andric   // Make sure that this type is translated.
512e7145dcbSDimitry Andric   Types.RefreshTypeCacheForClass(RD);
513e7145dcbSDimitry Andric }
514e7145dcbSDimitry Andric 
5152754fe60SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
5162754fe60SDimitry Andric   if (!TBAA)
51759d1ed5bSDimitry Andric     return nullptr;
5182754fe60SDimitry Andric   return TBAA->getTBAAInfo(QTy);
5192754fe60SDimitry Andric }
5202754fe60SDimitry Andric 
521dff0c46cSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
522dff0c46cSDimitry Andric   if (!TBAA)
52359d1ed5bSDimitry Andric     return nullptr;
524dff0c46cSDimitry Andric   return TBAA->getTBAAInfoForVTablePtr();
525dff0c46cSDimitry Andric }
526dff0c46cSDimitry Andric 
5273861d79fSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
5283861d79fSDimitry Andric   if (!TBAA)
52959d1ed5bSDimitry Andric     return nullptr;
5303861d79fSDimitry Andric   return TBAA->getTBAAStructInfo(QTy);
5313861d79fSDimitry Andric }
5323861d79fSDimitry Andric 
533139f7f9bSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
534139f7f9bSDimitry Andric                                                   llvm::MDNode *AccessN,
535139f7f9bSDimitry Andric                                                   uint64_t O) {
536139f7f9bSDimitry Andric   if (!TBAA)
53759d1ed5bSDimitry Andric     return nullptr;
538139f7f9bSDimitry Andric   return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
539139f7f9bSDimitry Andric }
540139f7f9bSDimitry Andric 
541f785676fSDimitry Andric /// Decorate the instruction with a TBAA tag. For both scalar TBAA
542f785676fSDimitry Andric /// and struct-path aware TBAA, the tag has the same format:
543f785676fSDimitry Andric /// base type, access type and offset.
544284c1978SDimitry Andric /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
5450623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
546284c1978SDimitry Andric                                                 llvm::MDNode *TBAAInfo,
547284c1978SDimitry Andric                                                 bool ConvertTypeToTag) {
548f785676fSDimitry Andric   if (ConvertTypeToTag && TBAA)
549284c1978SDimitry Andric     Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
550284c1978SDimitry Andric                       TBAA->getTBAAScalarTagInfo(TBAAInfo));
551284c1978SDimitry Andric   else
5522754fe60SDimitry Andric     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
5532754fe60SDimitry Andric }
5542754fe60SDimitry Andric 
5550623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithInvariantGroup(
5560623d748SDimitry Andric     llvm::Instruction *I, const CXXRecordDecl *RD) {
5570623d748SDimitry Andric   llvm::Metadata *MD = CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
5580623d748SDimitry Andric   auto *MetaDataNode = dyn_cast<llvm::MDNode>(MD);
5590623d748SDimitry Andric   // Check if we have to wrap MDString in MDNode.
5600623d748SDimitry Andric   if (!MetaDataNode)
5610623d748SDimitry Andric     MetaDataNode = llvm::MDNode::get(getLLVMContext(), MD);
5620623d748SDimitry Andric   I->setMetadata(llvm::LLVMContext::MD_invariant_group, MetaDataNode);
5630623d748SDimitry Andric }
5640623d748SDimitry Andric 
56559d1ed5bSDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) {
56659d1ed5bSDimitry Andric   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
56759d1ed5bSDimitry Andric   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
568f22ef01cSRoman Divacky }
569f22ef01cSRoman Divacky 
570f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
571f22ef01cSRoman Divacky /// specified stmt yet.
572f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
5736122f3e6SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
574f22ef01cSRoman Divacky                                                "cannot compile this %0 yet");
575f22ef01cSRoman Divacky   std::string Msg = Type;
576f22ef01cSRoman Divacky   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
577f22ef01cSRoman Divacky     << Msg << S->getSourceRange();
578f22ef01cSRoman Divacky }
579f22ef01cSRoman Divacky 
580f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
581f22ef01cSRoman Divacky /// specified decl yet.
582f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
5836122f3e6SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
584f22ef01cSRoman Divacky                                                "cannot compile this %0 yet");
585f22ef01cSRoman Divacky   std::string Msg = Type;
586f22ef01cSRoman Divacky   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
587f22ef01cSRoman Divacky }
588f22ef01cSRoman Divacky 
58917a519f9SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
59017a519f9SDimitry Andric   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
59117a519f9SDimitry Andric }
59217a519f9SDimitry Andric 
593f22ef01cSRoman Divacky void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
5942754fe60SDimitry Andric                                         const NamedDecl *D) const {
595f22ef01cSRoman Divacky   // Internal definitions always have default visibility.
596f22ef01cSRoman Divacky   if (GV->hasLocalLinkage()) {
597f22ef01cSRoman Divacky     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
598f22ef01cSRoman Divacky     return;
599f22ef01cSRoman Divacky   }
600f22ef01cSRoman Divacky 
6012754fe60SDimitry Andric   // Set visibility for definitions.
602139f7f9bSDimitry Andric   LinkageInfo LV = D->getLinkageAndVisibility();
603139f7f9bSDimitry Andric   if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
604139f7f9bSDimitry Andric     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
605f22ef01cSRoman Divacky }
606f22ef01cSRoman Divacky 
6077ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
6087ae0e2c9SDimitry Andric   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
6097ae0e2c9SDimitry Andric       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
6107ae0e2c9SDimitry Andric       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
6117ae0e2c9SDimitry Andric       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
6127ae0e2c9SDimitry Andric       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
6137ae0e2c9SDimitry Andric }
6147ae0e2c9SDimitry Andric 
6157ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
6167ae0e2c9SDimitry Andric     CodeGenOptions::TLSModel M) {
6177ae0e2c9SDimitry Andric   switch (M) {
6187ae0e2c9SDimitry Andric   case CodeGenOptions::GeneralDynamicTLSModel:
6197ae0e2c9SDimitry Andric     return llvm::GlobalVariable::GeneralDynamicTLSModel;
6207ae0e2c9SDimitry Andric   case CodeGenOptions::LocalDynamicTLSModel:
6217ae0e2c9SDimitry Andric     return llvm::GlobalVariable::LocalDynamicTLSModel;
6227ae0e2c9SDimitry Andric   case CodeGenOptions::InitialExecTLSModel:
6237ae0e2c9SDimitry Andric     return llvm::GlobalVariable::InitialExecTLSModel;
6247ae0e2c9SDimitry Andric   case CodeGenOptions::LocalExecTLSModel:
6257ae0e2c9SDimitry Andric     return llvm::GlobalVariable::LocalExecTLSModel;
6267ae0e2c9SDimitry Andric   }
6277ae0e2c9SDimitry Andric   llvm_unreachable("Invalid TLS model!");
6287ae0e2c9SDimitry Andric }
6297ae0e2c9SDimitry Andric 
63039d628a0SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
631284c1978SDimitry Andric   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
6327ae0e2c9SDimitry Andric 
63339d628a0SDimitry Andric   llvm::GlobalValue::ThreadLocalMode TLM;
6343861d79fSDimitry Andric   TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
6357ae0e2c9SDimitry Andric 
6367ae0e2c9SDimitry Andric   // Override the TLS model if it is explicitly specified.
63759d1ed5bSDimitry Andric   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
6387ae0e2c9SDimitry Andric     TLM = GetLLVMTLSModel(Attr->getModel());
6397ae0e2c9SDimitry Andric   }
6407ae0e2c9SDimitry Andric 
6417ae0e2c9SDimitry Andric   GV->setThreadLocalMode(TLM);
6427ae0e2c9SDimitry Andric }
6437ae0e2c9SDimitry Andric 
6446122f3e6SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
645444ed5c5SDimitry Andric   GlobalDecl CanonicalGD = GD.getCanonicalDecl();
646444ed5c5SDimitry Andric 
647444ed5c5SDimitry Andric   // Some ABIs don't have constructor variants.  Make sure that base and
648444ed5c5SDimitry Andric   // complete constructors get mangled the same.
649444ed5c5SDimitry Andric   if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
650444ed5c5SDimitry Andric     if (!getTarget().getCXXABI().hasConstructorVariants()) {
651444ed5c5SDimitry Andric       CXXCtorType OrigCtorType = GD.getCtorType();
652444ed5c5SDimitry Andric       assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
653444ed5c5SDimitry Andric       if (OrigCtorType == Ctor_Base)
654444ed5c5SDimitry Andric         CanonicalGD = GlobalDecl(CD, Ctor_Complete);
655444ed5c5SDimitry Andric     }
656444ed5c5SDimitry Andric   }
657444ed5c5SDimitry Andric 
658444ed5c5SDimitry Andric   StringRef &FoundStr = MangledDeclNames[CanonicalGD];
65959d1ed5bSDimitry Andric   if (!FoundStr.empty())
66059d1ed5bSDimitry Andric     return FoundStr;
661f22ef01cSRoman Divacky 
66259d1ed5bSDimitry Andric   const auto *ND = cast<NamedDecl>(GD.getDecl());
663dff0c46cSDimitry Andric   SmallString<256> Buffer;
66459d1ed5bSDimitry Andric   StringRef Str;
66559d1ed5bSDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
6662754fe60SDimitry Andric     llvm::raw_svector_ostream Out(Buffer);
66759d1ed5bSDimitry Andric     if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
6682754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
66959d1ed5bSDimitry Andric     else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
6702754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
671ffd1746dSEd Schouten     else
6722754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleName(ND, Out);
67359d1ed5bSDimitry Andric     Str = Out.str();
67459d1ed5bSDimitry Andric   } else {
67559d1ed5bSDimitry Andric     IdentifierInfo *II = ND->getIdentifier();
67659d1ed5bSDimitry Andric     assert(II && "Attempt to mangle unnamed decl.");
67744290647SDimitry Andric     const auto *FD = dyn_cast<FunctionDecl>(ND);
67844290647SDimitry Andric 
67944290647SDimitry Andric     if (FD &&
68044290647SDimitry Andric         FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
68144290647SDimitry Andric       llvm::raw_svector_ostream Out(Buffer);
68244290647SDimitry Andric       Out << "__regcall3__" << II->getName();
68344290647SDimitry Andric       Str = Out.str();
68444290647SDimitry Andric     } else {
68559d1ed5bSDimitry Andric       Str = II->getName();
686ffd1746dSEd Schouten     }
68744290647SDimitry Andric   }
688ffd1746dSEd Schouten 
68939d628a0SDimitry Andric   // Keep the first result in the case of a mangling collision.
69039d628a0SDimitry Andric   auto Result = Manglings.insert(std::make_pair(Str, GD));
69139d628a0SDimitry Andric   return FoundStr = Result.first->first();
69259d1ed5bSDimitry Andric }
69359d1ed5bSDimitry Andric 
69459d1ed5bSDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
695ffd1746dSEd Schouten                                              const BlockDecl *BD) {
6962754fe60SDimitry Andric   MangleContext &MangleCtx = getCXXABI().getMangleContext();
6972754fe60SDimitry Andric   const Decl *D = GD.getDecl();
69859d1ed5bSDimitry Andric 
69959d1ed5bSDimitry Andric   SmallString<256> Buffer;
70059d1ed5bSDimitry Andric   llvm::raw_svector_ostream Out(Buffer);
70159d1ed5bSDimitry Andric   if (!D)
7027ae0e2c9SDimitry Andric     MangleCtx.mangleGlobalBlock(BD,
7037ae0e2c9SDimitry Andric       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
70459d1ed5bSDimitry Andric   else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
7052754fe60SDimitry Andric     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
70659d1ed5bSDimitry Andric   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
7072754fe60SDimitry Andric     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
7082754fe60SDimitry Andric   else
7092754fe60SDimitry Andric     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
71059d1ed5bSDimitry Andric 
71139d628a0SDimitry Andric   auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
71239d628a0SDimitry Andric   return Result.first->first();
713f22ef01cSRoman Divacky }
714f22ef01cSRoman Divacky 
7156122f3e6SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
716f22ef01cSRoman Divacky   return getModule().getNamedValue(Name);
717f22ef01cSRoman Divacky }
718f22ef01cSRoman Divacky 
719f22ef01cSRoman Divacky /// AddGlobalCtor - Add a function to the list that will be called before
720f22ef01cSRoman Divacky /// main() runs.
72159d1ed5bSDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
72259d1ed5bSDimitry Andric                                   llvm::Constant *AssociatedData) {
723f22ef01cSRoman Divacky   // FIXME: Type coercion of void()* types.
72459d1ed5bSDimitry Andric   GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
725f22ef01cSRoman Divacky }
726f22ef01cSRoman Divacky 
727f22ef01cSRoman Divacky /// AddGlobalDtor - Add a function to the list that will be called
728f22ef01cSRoman Divacky /// when the module is unloaded.
729f22ef01cSRoman Divacky void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
730f22ef01cSRoman Divacky   // FIXME: Type coercion of void()* types.
73159d1ed5bSDimitry Andric   GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
732f22ef01cSRoman Divacky }
733f22ef01cSRoman Divacky 
73444290647SDimitry Andric void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
73544290647SDimitry Andric   if (Fns.empty()) return;
73644290647SDimitry Andric 
737f22ef01cSRoman Divacky   // Ctor function type is void()*.
738bd5abe19SDimitry Andric   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
739f22ef01cSRoman Divacky   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
740f22ef01cSRoman Divacky 
74159d1ed5bSDimitry Andric   // Get the type of a ctor entry, { i32, void ()*, i8* }.
74259d1ed5bSDimitry Andric   llvm::StructType *CtorStructTy = llvm::StructType::get(
74339d628a0SDimitry Andric       Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr);
744f22ef01cSRoman Divacky 
745f22ef01cSRoman Divacky   // Construct the constructor and destructor arrays.
74644290647SDimitry Andric   ConstantInitBuilder builder(*this);
74744290647SDimitry Andric   auto ctors = builder.beginArray(CtorStructTy);
7488f0fd8f6SDimitry Andric   for (const auto &I : Fns) {
74944290647SDimitry Andric     auto ctor = ctors.beginStruct(CtorStructTy);
75044290647SDimitry Andric     ctor.addInt(Int32Ty, I.Priority);
75144290647SDimitry Andric     ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
75244290647SDimitry Andric     if (I.AssociatedData)
75344290647SDimitry Andric       ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
75444290647SDimitry Andric     else
75544290647SDimitry Andric       ctor.addNullPointer(VoidPtrTy);
75644290647SDimitry Andric     ctor.finishAndAddTo(ctors);
757f22ef01cSRoman Divacky   }
758f22ef01cSRoman Divacky 
75944290647SDimitry Andric   auto list =
76044290647SDimitry Andric     ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
76144290647SDimitry Andric                                 /*constant*/ false,
76244290647SDimitry Andric                                 llvm::GlobalValue::AppendingLinkage);
76344290647SDimitry Andric 
76444290647SDimitry Andric   // The LTO linker doesn't seem to like it when we set an alignment
76544290647SDimitry Andric   // on appending variables.  Take it off as a workaround.
76644290647SDimitry Andric   list->setAlignment(0);
76744290647SDimitry Andric 
76844290647SDimitry Andric   Fns.clear();
769f22ef01cSRoman Divacky }
770f22ef01cSRoman Divacky 
771f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes
772f785676fSDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
77359d1ed5bSDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
774f785676fSDimitry Andric 
775e580952dSDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
776f22ef01cSRoman Divacky 
77759d1ed5bSDimitry Andric   if (isa<CXXDestructorDecl>(D) &&
77859d1ed5bSDimitry Andric       getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
77959d1ed5bSDimitry Andric                                          GD.getDtorType())) {
78059d1ed5bSDimitry Andric     // Destructor variants in the Microsoft C++ ABI are always internal or
78159d1ed5bSDimitry Andric     // linkonce_odr thunks emitted on an as-needed basis.
78259d1ed5bSDimitry Andric     return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
78359d1ed5bSDimitry Andric                                    : llvm::GlobalValue::LinkOnceODRLinkage;
784f22ef01cSRoman Divacky   }
785f22ef01cSRoman Divacky 
786e7145dcbSDimitry Andric   if (isa<CXXConstructorDecl>(D) &&
787e7145dcbSDimitry Andric       cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
788e7145dcbSDimitry Andric       Context.getTargetInfo().getCXXABI().isMicrosoft()) {
789e7145dcbSDimitry Andric     // Our approach to inheriting constructors is fundamentally different from
790e7145dcbSDimitry Andric     // that used by the MS ABI, so keep our inheriting constructor thunks
791e7145dcbSDimitry Andric     // internal rather than trying to pick an unambiguous mangling for them.
792e7145dcbSDimitry Andric     return llvm::GlobalValue::InternalLinkage;
793e7145dcbSDimitry Andric   }
794e7145dcbSDimitry Andric 
79559d1ed5bSDimitry Andric   return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
79659d1ed5bSDimitry Andric }
797f22ef01cSRoman Divacky 
79897bc6c73SDimitry Andric void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
79997bc6c73SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
80097bc6c73SDimitry Andric 
80197bc6c73SDimitry Andric   if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
80297bc6c73SDimitry Andric     if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
80397bc6c73SDimitry Andric       // Don't dllexport/import destructor thunks.
80497bc6c73SDimitry Andric       F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
80597bc6c73SDimitry Andric       return;
80697bc6c73SDimitry Andric     }
80797bc6c73SDimitry Andric   }
80897bc6c73SDimitry Andric 
80997bc6c73SDimitry Andric   if (FD->hasAttr<DLLImportAttr>())
81097bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
81197bc6c73SDimitry Andric   else if (FD->hasAttr<DLLExportAttr>())
81297bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
81397bc6c73SDimitry Andric   else
81497bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
81597bc6c73SDimitry Andric }
81697bc6c73SDimitry Andric 
817e7145dcbSDimitry Andric llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
8180623d748SDimitry Andric   llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
8190623d748SDimitry Andric   if (!MDS) return nullptr;
8200623d748SDimitry Andric 
82144290647SDimitry Andric   return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
8220623d748SDimitry Andric }
8230623d748SDimitry Andric 
82459d1ed5bSDimitry Andric void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
82559d1ed5bSDimitry Andric                                                     llvm::Function *F) {
82659d1ed5bSDimitry Andric   setNonAliasAttributes(D, F);
827f22ef01cSRoman Divacky }
828f22ef01cSRoman Divacky 
829f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
830f22ef01cSRoman Divacky                                               const CGFunctionInfo &Info,
831f22ef01cSRoman Divacky                                               llvm::Function *F) {
832f22ef01cSRoman Divacky   unsigned CallingConv;
833f22ef01cSRoman Divacky   AttributeListType AttributeList;
834ea942507SDimitry Andric   ConstructAttributeList(F->getName(), Info, D, AttributeList, CallingConv,
835ea942507SDimitry Andric                          false);
836139f7f9bSDimitry Andric   F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
837f22ef01cSRoman Divacky   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
838f22ef01cSRoman Divacky }
839f22ef01cSRoman Divacky 
8406122f3e6SDimitry Andric /// Determines whether the language options require us to model
8416122f3e6SDimitry Andric /// unwind exceptions.  We treat -fexceptions as mandating this
8426122f3e6SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions
8436122f3e6SDimitry Andric /// enabled.  This means, for example, that C with -fexceptions
8446122f3e6SDimitry Andric /// enables this.
845dff0c46cSDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) {
8466122f3e6SDimitry Andric   // If exceptions are completely disabled, obviously this is false.
847dff0c46cSDimitry Andric   if (!LangOpts.Exceptions) return false;
8486122f3e6SDimitry Andric 
8496122f3e6SDimitry Andric   // If C++ exceptions are enabled, this is true.
850dff0c46cSDimitry Andric   if (LangOpts.CXXExceptions) return true;
8516122f3e6SDimitry Andric 
8526122f3e6SDimitry Andric   // If ObjC exceptions are enabled, this depends on the ABI.
853dff0c46cSDimitry Andric   if (LangOpts.ObjCExceptions) {
8547ae0e2c9SDimitry Andric     return LangOpts.ObjCRuntime.hasUnwindExceptions();
8556122f3e6SDimitry Andric   }
8566122f3e6SDimitry Andric 
8576122f3e6SDimitry Andric   return true;
8586122f3e6SDimitry Andric }
8596122f3e6SDimitry Andric 
860f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
861f22ef01cSRoman Divacky                                                            llvm::Function *F) {
862f785676fSDimitry Andric   llvm::AttrBuilder B;
863f785676fSDimitry Andric 
864bd5abe19SDimitry Andric   if (CodeGenOpts.UnwindTables)
865f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::UWTable);
866bd5abe19SDimitry Andric 
867dff0c46cSDimitry Andric   if (!hasUnwindExceptions(LangOpts))
868f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoUnwind);
869f22ef01cSRoman Divacky 
8700623d748SDimitry Andric   if (LangOpts.getStackProtector() == LangOptions::SSPOn)
8710623d748SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtect);
8720623d748SDimitry Andric   else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
8730623d748SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtectStrong);
8740623d748SDimitry Andric   else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
8750623d748SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtectReq);
8760623d748SDimitry Andric 
8770623d748SDimitry Andric   if (!D) {
87844290647SDimitry Andric     // If we don't have a declaration to control inlining, the function isn't
87944290647SDimitry Andric     // explicitly marked as alwaysinline for semantic reasons, and inlining is
88044290647SDimitry Andric     // disabled, mark the function as noinline.
88144290647SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
88244290647SDimitry Andric         CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
88344290647SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
88444290647SDimitry Andric 
8850623d748SDimitry Andric     F->addAttributes(llvm::AttributeSet::FunctionIndex,
8860623d748SDimitry Andric                      llvm::AttributeSet::get(
8870623d748SDimitry Andric                          F->getContext(),
8880623d748SDimitry Andric                          llvm::AttributeSet::FunctionIndex, B));
8890623d748SDimitry Andric     return;
8900623d748SDimitry Andric   }
8910623d748SDimitry Andric 
89244290647SDimitry Andric   if (D->hasAttr<OptimizeNoneAttr>()) {
89344290647SDimitry Andric     B.addAttribute(llvm::Attribute::OptimizeNone);
89444290647SDimitry Andric 
89544290647SDimitry Andric     // OptimizeNone implies noinline; we should not be inlining such functions.
89644290647SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
89744290647SDimitry Andric     assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
89844290647SDimitry Andric            "OptimizeNone and AlwaysInline on same function!");
89944290647SDimitry Andric 
90044290647SDimitry Andric     // We still need to handle naked functions even though optnone subsumes
90144290647SDimitry Andric     // much of their semantics.
90244290647SDimitry Andric     if (D->hasAttr<NakedAttr>())
90344290647SDimitry Andric       B.addAttribute(llvm::Attribute::Naked);
90444290647SDimitry Andric 
90544290647SDimitry Andric     // OptimizeNone wins over OptimizeForSize and MinSize.
90644290647SDimitry Andric     F->removeFnAttr(llvm::Attribute::OptimizeForSize);
90744290647SDimitry Andric     F->removeFnAttr(llvm::Attribute::MinSize);
90844290647SDimitry Andric   } else if (D->hasAttr<NakedAttr>()) {
9096122f3e6SDimitry Andric     // Naked implies noinline: we should not be inlining such functions.
910f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::Naked);
911f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
91259d1ed5bSDimitry Andric   } else if (D->hasAttr<NoDuplicateAttr>()) {
91359d1ed5bSDimitry Andric     B.addAttribute(llvm::Attribute::NoDuplicate);
914f785676fSDimitry Andric   } else if (D->hasAttr<NoInlineAttr>()) {
915f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
91659d1ed5bSDimitry Andric   } else if (D->hasAttr<AlwaysInlineAttr>() &&
91744290647SDimitry Andric              !F->hasFnAttribute(llvm::Attribute::NoInline)) {
918f785676fSDimitry Andric     // (noinline wins over always_inline, and we can't specify both in IR)
919f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::AlwaysInline);
92044290647SDimitry Andric   } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
92144290647SDimitry Andric     // If we're not inlining, then force everything that isn't always_inline to
92244290647SDimitry Andric     // carry an explicit noinline attribute.
92344290647SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
92444290647SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
92544290647SDimitry Andric   } else {
92644290647SDimitry Andric     // Otherwise, propagate the inline hint attribute and potentially use its
92744290647SDimitry Andric     // absence to mark things as noinline.
92844290647SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
92944290647SDimitry Andric       if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
93044290647SDimitry Andric             return Redecl->isInlineSpecified();
93144290647SDimitry Andric           })) {
93244290647SDimitry Andric         B.addAttribute(llvm::Attribute::InlineHint);
93344290647SDimitry Andric       } else if (CodeGenOpts.getInlining() ==
93444290647SDimitry Andric                      CodeGenOptions::OnlyHintInlining &&
93544290647SDimitry Andric                  !FD->isInlined() &&
93644290647SDimitry Andric                  !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
93744290647SDimitry Andric         B.addAttribute(llvm::Attribute::NoInline);
93844290647SDimitry Andric       }
93944290647SDimitry Andric     }
9406122f3e6SDimitry Andric   }
9412754fe60SDimitry Andric 
94244290647SDimitry Andric   // Add other optimization related attributes if we are optimizing this
94344290647SDimitry Andric   // function.
94444290647SDimitry Andric   if (!D->hasAttr<OptimizeNoneAttr>()) {
945f785676fSDimitry Andric     if (D->hasAttr<ColdAttr>()) {
946f785676fSDimitry Andric       B.addAttribute(llvm::Attribute::OptimizeForSize);
947f785676fSDimitry Andric       B.addAttribute(llvm::Attribute::Cold);
948f785676fSDimitry Andric     }
9493861d79fSDimitry Andric 
9503861d79fSDimitry Andric     if (D->hasAttr<MinSizeAttr>())
951f785676fSDimitry Andric       B.addAttribute(llvm::Attribute::MinSize);
95244290647SDimitry Andric   }
953f22ef01cSRoman Divacky 
954f785676fSDimitry Andric   F->addAttributes(llvm::AttributeSet::FunctionIndex,
955f785676fSDimitry Andric                    llvm::AttributeSet::get(
956f785676fSDimitry Andric                        F->getContext(), llvm::AttributeSet::FunctionIndex, B));
957f785676fSDimitry Andric 
958e580952dSDimitry Andric   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
959e580952dSDimitry Andric   if (alignment)
960e580952dSDimitry Andric     F->setAlignment(alignment);
961e580952dSDimitry Andric 
9620623d748SDimitry Andric   // Some C++ ABIs require 2-byte alignment for member functions, in order to
9630623d748SDimitry Andric   // reserve a bit for differentiating between virtual and non-virtual member
9640623d748SDimitry Andric   // functions. If the current target's C++ ABI requires this and this is a
9650623d748SDimitry Andric   // member function, set its alignment accordingly.
9660623d748SDimitry Andric   if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
967f22ef01cSRoman Divacky     if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
968f22ef01cSRoman Divacky       F->setAlignment(2);
969f22ef01cSRoman Divacky   }
97044290647SDimitry Andric 
97144290647SDimitry Andric   // In the cross-dso CFI mode, we want !type attributes on definitions only.
97244290647SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
97344290647SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D))
97444290647SDimitry Andric       CreateFunctionTypeMetadata(FD, F);
9750623d748SDimitry Andric }
976f22ef01cSRoman Divacky 
977f22ef01cSRoman Divacky void CodeGenModule::SetCommonAttributes(const Decl *D,
978f22ef01cSRoman Divacky                                         llvm::GlobalValue *GV) {
9790623d748SDimitry Andric   if (const auto *ND = dyn_cast_or_null<NamedDecl>(D))
9802754fe60SDimitry Andric     setGlobalVisibility(GV, ND);
9812754fe60SDimitry Andric   else
9822754fe60SDimitry Andric     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
983f22ef01cSRoman Divacky 
9840623d748SDimitry Andric   if (D && D->hasAttr<UsedAttr>())
98559d1ed5bSDimitry Andric     addUsedGlobal(GV);
98659d1ed5bSDimitry Andric }
98759d1ed5bSDimitry Andric 
98839d628a0SDimitry Andric void CodeGenModule::setAliasAttributes(const Decl *D,
98939d628a0SDimitry Andric                                        llvm::GlobalValue *GV) {
99039d628a0SDimitry Andric   SetCommonAttributes(D, GV);
99139d628a0SDimitry Andric 
99239d628a0SDimitry Andric   // Process the dllexport attribute based on whether the original definition
99339d628a0SDimitry Andric   // (not necessarily the aliasee) was exported.
99439d628a0SDimitry Andric   if (D->hasAttr<DLLExportAttr>())
99539d628a0SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
99639d628a0SDimitry Andric }
99739d628a0SDimitry Andric 
99859d1ed5bSDimitry Andric void CodeGenModule::setNonAliasAttributes(const Decl *D,
99959d1ed5bSDimitry Andric                                           llvm::GlobalObject *GO) {
100059d1ed5bSDimitry Andric   SetCommonAttributes(D, GO);
1001f22ef01cSRoman Divacky 
10020623d748SDimitry Andric   if (D)
1003f22ef01cSRoman Divacky     if (const SectionAttr *SA = D->getAttr<SectionAttr>())
100459d1ed5bSDimitry Andric       GO->setSection(SA->getName());
1005f22ef01cSRoman Divacky 
100697bc6c73SDimitry Andric   getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
1007f22ef01cSRoman Divacky }
1008f22ef01cSRoman Divacky 
1009f22ef01cSRoman Divacky void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
1010f22ef01cSRoman Divacky                                                   llvm::Function *F,
1011f22ef01cSRoman Divacky                                                   const CGFunctionInfo &FI) {
1012f22ef01cSRoman Divacky   SetLLVMFunctionAttributes(D, FI, F);
1013f22ef01cSRoman Divacky   SetLLVMFunctionAttributesForDefinition(D, F);
1014f22ef01cSRoman Divacky 
1015f22ef01cSRoman Divacky   F->setLinkage(llvm::Function::InternalLinkage);
1016f22ef01cSRoman Divacky 
101759d1ed5bSDimitry Andric   setNonAliasAttributes(D, F);
101859d1ed5bSDimitry Andric }
101959d1ed5bSDimitry Andric 
102059d1ed5bSDimitry Andric static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
102159d1ed5bSDimitry Andric                                          const NamedDecl *ND) {
102259d1ed5bSDimitry Andric   // Set linkage and visibility in case we never see a definition.
102359d1ed5bSDimitry Andric   LinkageInfo LV = ND->getLinkageAndVisibility();
102459d1ed5bSDimitry Andric   if (LV.getLinkage() != ExternalLinkage) {
102559d1ed5bSDimitry Andric     // Don't set internal linkage on declarations.
102659d1ed5bSDimitry Andric   } else {
102759d1ed5bSDimitry Andric     if (ND->hasAttr<DLLImportAttr>()) {
102859d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
102959d1ed5bSDimitry Andric       GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
103059d1ed5bSDimitry Andric     } else if (ND->hasAttr<DLLExportAttr>()) {
103159d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
103259d1ed5bSDimitry Andric       GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
103359d1ed5bSDimitry Andric     } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
103459d1ed5bSDimitry Andric       // "extern_weak" is overloaded in LLVM; we probably should have
103559d1ed5bSDimitry Andric       // separate linkage types for this.
103659d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
103759d1ed5bSDimitry Andric     }
103859d1ed5bSDimitry Andric 
103959d1ed5bSDimitry Andric     // Set visibility on a declaration only if it's explicit.
104059d1ed5bSDimitry Andric     if (LV.isVisibilityExplicit())
104159d1ed5bSDimitry Andric       GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
104259d1ed5bSDimitry Andric   }
1043f22ef01cSRoman Divacky }
1044f22ef01cSRoman Divacky 
1045e7145dcbSDimitry Andric void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD,
10460623d748SDimitry Andric                                                llvm::Function *F) {
10470623d748SDimitry Andric   // Only if we are checking indirect calls.
10480623d748SDimitry Andric   if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
10490623d748SDimitry Andric     return;
10500623d748SDimitry Andric 
10510623d748SDimitry Andric   // Non-static class methods are handled via vtable pointer checks elsewhere.
10520623d748SDimitry Andric   if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
10530623d748SDimitry Andric     return;
10540623d748SDimitry Andric 
10550623d748SDimitry Andric   // Additionally, if building with cross-DSO support...
10560623d748SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
10570623d748SDimitry Andric     // Skip available_externally functions. They won't be codegen'ed in the
10580623d748SDimitry Andric     // current module anyway.
10590623d748SDimitry Andric     if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
10600623d748SDimitry Andric       return;
10610623d748SDimitry Andric   }
10620623d748SDimitry Andric 
10630623d748SDimitry Andric   llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
1064e7145dcbSDimitry Andric   F->addTypeMetadata(0, MD);
10650623d748SDimitry Andric 
10660623d748SDimitry Andric   // Emit a hash-based bit set entry for cross-DSO calls.
1067e7145dcbSDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
1068e7145dcbSDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1069e7145dcbSDimitry Andric       F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
10700623d748SDimitry Andric }
10710623d748SDimitry Andric 
107239d628a0SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
107339d628a0SDimitry Andric                                           bool IsIncompleteFunction,
107439d628a0SDimitry Andric                                           bool IsThunk) {
107533956c43SDimitry Andric   if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
10763b0f4066SDimitry Andric     // If this is an intrinsic function, set the function's attributes
10773b0f4066SDimitry Andric     // to the intrinsic's attributes.
107833956c43SDimitry Andric     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
10793b0f4066SDimitry Andric     return;
10803b0f4066SDimitry Andric   }
10813b0f4066SDimitry Andric 
108259d1ed5bSDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
1083f22ef01cSRoman Divacky 
1084f22ef01cSRoman Divacky   if (!IsIncompleteFunction)
1085dff0c46cSDimitry Andric     SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
1086f22ef01cSRoman Divacky 
108759d1ed5bSDimitry Andric   // Add the Returned attribute for "this", except for iOS 5 and earlier
108859d1ed5bSDimitry Andric   // where substantial code, including the libstdc++ dylib, was compiled with
108959d1ed5bSDimitry Andric   // GCC and does not actually return "this".
109039d628a0SDimitry Andric   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
109144290647SDimitry Andric       !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
1092f785676fSDimitry Andric     assert(!F->arg_empty() &&
1093f785676fSDimitry Andric            F->arg_begin()->getType()
1094f785676fSDimitry Andric              ->canLosslesslyBitCastTo(F->getReturnType()) &&
1095f785676fSDimitry Andric            "unexpected this return");
1096f785676fSDimitry Andric     F->addAttribute(1, llvm::Attribute::Returned);
1097f785676fSDimitry Andric   }
1098f785676fSDimitry Andric 
1099f22ef01cSRoman Divacky   // Only a few attributes are set on declarations; these may later be
1100f22ef01cSRoman Divacky   // overridden by a definition.
1101f22ef01cSRoman Divacky 
110259d1ed5bSDimitry Andric   setLinkageAndVisibilityForGV(F, FD);
11032754fe60SDimitry Andric 
1104f22ef01cSRoman Divacky   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
1105f22ef01cSRoman Divacky     F->setSection(SA->getName());
1106f785676fSDimitry Andric 
1107e7145dcbSDimitry Andric   if (FD->isReplaceableGlobalAllocationFunction()) {
1108f785676fSDimitry Andric     // A replaceable global allocation function does not act like a builtin by
1109f785676fSDimitry Andric     // default, only if it is invoked by a new-expression or delete-expression.
1110f785676fSDimitry Andric     F->addAttribute(llvm::AttributeSet::FunctionIndex,
1111f785676fSDimitry Andric                     llvm::Attribute::NoBuiltin);
11120623d748SDimitry Andric 
1113e7145dcbSDimitry Andric     // A sane operator new returns a non-aliasing pointer.
1114e7145dcbSDimitry Andric     // FIXME: Also add NonNull attribute to the return value
1115e7145dcbSDimitry Andric     // for the non-nothrow forms?
1116e7145dcbSDimitry Andric     auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1117e7145dcbSDimitry Andric     if (getCodeGenOpts().AssumeSaneOperatorNew &&
1118e7145dcbSDimitry Andric         (Kind == OO_New || Kind == OO_Array_New))
1119e7145dcbSDimitry Andric       F->addAttribute(llvm::AttributeSet::ReturnIndex,
1120e7145dcbSDimitry Andric                       llvm::Attribute::NoAlias);
1121e7145dcbSDimitry Andric   }
1122e7145dcbSDimitry Andric 
1123e7145dcbSDimitry Andric   if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1124e7145dcbSDimitry Andric     F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1125e7145dcbSDimitry Andric   else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1126e7145dcbSDimitry Andric     if (MD->isVirtual())
1127e7145dcbSDimitry Andric       F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1128e7145dcbSDimitry Andric 
112944290647SDimitry Andric   // Don't emit entries for function declarations in the cross-DSO mode. This
113044290647SDimitry Andric   // is handled with better precision by the receiving DSO.
113144290647SDimitry Andric   if (!CodeGenOpts.SanitizeCfiCrossDso)
1132e7145dcbSDimitry Andric     CreateFunctionTypeMetadata(FD, F);
1133f22ef01cSRoman Divacky }
1134f22ef01cSRoman Divacky 
113559d1ed5bSDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
1136f22ef01cSRoman Divacky   assert(!GV->isDeclaration() &&
1137f22ef01cSRoman Divacky          "Only globals with definition can force usage.");
113897bc6c73SDimitry Andric   LLVMUsed.emplace_back(GV);
1139f22ef01cSRoman Divacky }
1140f22ef01cSRoman Divacky 
114159d1ed5bSDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
114259d1ed5bSDimitry Andric   assert(!GV->isDeclaration() &&
114359d1ed5bSDimitry Andric          "Only globals with definition can force usage.");
114497bc6c73SDimitry Andric   LLVMCompilerUsed.emplace_back(GV);
114559d1ed5bSDimitry Andric }
114659d1ed5bSDimitry Andric 
114759d1ed5bSDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name,
114859d1ed5bSDimitry Andric                      std::vector<llvm::WeakVH> &List) {
1149f22ef01cSRoman Divacky   // Don't create llvm.used if there is no need.
115059d1ed5bSDimitry Andric   if (List.empty())
1151f22ef01cSRoman Divacky     return;
1152f22ef01cSRoman Divacky 
115359d1ed5bSDimitry Andric   // Convert List to what ConstantArray needs.
1154dff0c46cSDimitry Andric   SmallVector<llvm::Constant*, 8> UsedArray;
115559d1ed5bSDimitry Andric   UsedArray.resize(List.size());
115659d1ed5bSDimitry Andric   for (unsigned i = 0, e = List.size(); i != e; ++i) {
1157f22ef01cSRoman Divacky     UsedArray[i] =
115844f7b0dcSDimitry Andric         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
115944f7b0dcSDimitry Andric             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
1160f22ef01cSRoman Divacky   }
1161f22ef01cSRoman Divacky 
1162f22ef01cSRoman Divacky   if (UsedArray.empty())
1163f22ef01cSRoman Divacky     return;
116459d1ed5bSDimitry Andric   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
1165f22ef01cSRoman Divacky 
116659d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
116759d1ed5bSDimitry Andric       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
116859d1ed5bSDimitry Andric       llvm::ConstantArray::get(ATy, UsedArray), Name);
1169f22ef01cSRoman Divacky 
1170f22ef01cSRoman Divacky   GV->setSection("llvm.metadata");
1171f22ef01cSRoman Divacky }
1172f22ef01cSRoman Divacky 
117359d1ed5bSDimitry Andric void CodeGenModule::emitLLVMUsed() {
117459d1ed5bSDimitry Andric   emitUsed(*this, "llvm.used", LLVMUsed);
117559d1ed5bSDimitry Andric   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
117659d1ed5bSDimitry Andric }
117759d1ed5bSDimitry Andric 
1178f785676fSDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
117939d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
1180f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1181f785676fSDimitry Andric }
1182f785676fSDimitry Andric 
1183f785676fSDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1184f785676fSDimitry Andric   llvm::SmallString<32> Opt;
1185f785676fSDimitry Andric   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
118639d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1187f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1188f785676fSDimitry Andric }
1189f785676fSDimitry Andric 
1190f785676fSDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) {
1191f785676fSDimitry Andric   llvm::SmallString<24> Opt;
1192f785676fSDimitry Andric   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
119339d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1194f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1195f785676fSDimitry Andric }
1196f785676fSDimitry Andric 
1197139f7f9bSDimitry Andric /// \brief Add link options implied by the given module, including modules
1198139f7f9bSDimitry Andric /// it depends on, using a postorder walk.
119939d628a0SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
120039d628a0SDimitry Andric                                     SmallVectorImpl<llvm::Metadata *> &Metadata,
1201139f7f9bSDimitry Andric                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
1202139f7f9bSDimitry Andric   // Import this module's parent.
120339d628a0SDimitry Andric   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
1204f785676fSDimitry Andric     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
1205139f7f9bSDimitry Andric   }
1206139f7f9bSDimitry Andric 
1207139f7f9bSDimitry Andric   // Import this module's dependencies.
1208139f7f9bSDimitry Andric   for (unsigned I = Mod->Imports.size(); I > 0; --I) {
120939d628a0SDimitry Andric     if (Visited.insert(Mod->Imports[I - 1]).second)
1210f785676fSDimitry Andric       addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
1211139f7f9bSDimitry Andric   }
1212139f7f9bSDimitry Andric 
1213139f7f9bSDimitry Andric   // Add linker options to link against the libraries/frameworks
1214139f7f9bSDimitry Andric   // described by this module.
1215f785676fSDimitry Andric   llvm::LLVMContext &Context = CGM.getLLVMContext();
1216139f7f9bSDimitry Andric   for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
1217f785676fSDimitry Andric     // Link against a framework.  Frameworks are currently Darwin only, so we
1218f785676fSDimitry Andric     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
1219139f7f9bSDimitry Andric     if (Mod->LinkLibraries[I-1].IsFramework) {
122039d628a0SDimitry Andric       llvm::Metadata *Args[2] = {
1221139f7f9bSDimitry Andric           llvm::MDString::get(Context, "-framework"),
122239d628a0SDimitry Andric           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
1223139f7f9bSDimitry Andric 
1224139f7f9bSDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, Args));
1225139f7f9bSDimitry Andric       continue;
1226139f7f9bSDimitry Andric     }
1227139f7f9bSDimitry Andric 
1228139f7f9bSDimitry Andric     // Link against a library.
1229f785676fSDimitry Andric     llvm::SmallString<24> Opt;
1230f785676fSDimitry Andric     CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1231f785676fSDimitry Andric       Mod->LinkLibraries[I-1].Library, Opt);
123239d628a0SDimitry Andric     auto *OptString = llvm::MDString::get(Context, Opt);
1233139f7f9bSDimitry Andric     Metadata.push_back(llvm::MDNode::get(Context, OptString));
1234139f7f9bSDimitry Andric   }
1235139f7f9bSDimitry Andric }
1236139f7f9bSDimitry Andric 
1237139f7f9bSDimitry Andric void CodeGenModule::EmitModuleLinkOptions() {
1238139f7f9bSDimitry Andric   // Collect the set of all of the modules we want to visit to emit link
1239139f7f9bSDimitry Andric   // options, which is essentially the imported modules and all of their
1240139f7f9bSDimitry Andric   // non-explicit child modules.
1241139f7f9bSDimitry Andric   llvm::SetVector<clang::Module *> LinkModules;
1242139f7f9bSDimitry Andric   llvm::SmallPtrSet<clang::Module *, 16> Visited;
1243139f7f9bSDimitry Andric   SmallVector<clang::Module *, 16> Stack;
1244139f7f9bSDimitry Andric 
1245139f7f9bSDimitry Andric   // Seed the stack with imported modules.
1246f1a29dd3SDimitry Andric   for (Module *M : ImportedModules) {
1247f1a29dd3SDimitry Andric     // Do not add any link flags when an implementation TU of a module imports
1248f1a29dd3SDimitry Andric     // a header of that same module.
1249f1a29dd3SDimitry Andric     if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
1250f1a29dd3SDimitry Andric         !getLangOpts().isCompilingModule())
1251f1a29dd3SDimitry Andric       continue;
12528f0fd8f6SDimitry Andric     if (Visited.insert(M).second)
12538f0fd8f6SDimitry Andric       Stack.push_back(M);
1254f1a29dd3SDimitry Andric   }
1255139f7f9bSDimitry Andric 
1256139f7f9bSDimitry Andric   // Find all of the modules to import, making a little effort to prune
1257139f7f9bSDimitry Andric   // non-leaf modules.
1258139f7f9bSDimitry Andric   while (!Stack.empty()) {
1259f785676fSDimitry Andric     clang::Module *Mod = Stack.pop_back_val();
1260139f7f9bSDimitry Andric 
1261139f7f9bSDimitry Andric     bool AnyChildren = false;
1262139f7f9bSDimitry Andric 
1263139f7f9bSDimitry Andric     // Visit the submodules of this module.
1264139f7f9bSDimitry Andric     for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1265139f7f9bSDimitry Andric                                         SubEnd = Mod->submodule_end();
1266139f7f9bSDimitry Andric          Sub != SubEnd; ++Sub) {
1267139f7f9bSDimitry Andric       // Skip explicit children; they need to be explicitly imported to be
1268139f7f9bSDimitry Andric       // linked against.
1269139f7f9bSDimitry Andric       if ((*Sub)->IsExplicit)
1270139f7f9bSDimitry Andric         continue;
1271139f7f9bSDimitry Andric 
127239d628a0SDimitry Andric       if (Visited.insert(*Sub).second) {
1273139f7f9bSDimitry Andric         Stack.push_back(*Sub);
1274139f7f9bSDimitry Andric         AnyChildren = true;
1275139f7f9bSDimitry Andric       }
1276139f7f9bSDimitry Andric     }
1277139f7f9bSDimitry Andric 
1278139f7f9bSDimitry Andric     // We didn't find any children, so add this module to the list of
1279139f7f9bSDimitry Andric     // modules to link against.
1280139f7f9bSDimitry Andric     if (!AnyChildren) {
1281139f7f9bSDimitry Andric       LinkModules.insert(Mod);
1282139f7f9bSDimitry Andric     }
1283139f7f9bSDimitry Andric   }
1284139f7f9bSDimitry Andric 
1285139f7f9bSDimitry Andric   // Add link options for all of the imported modules in reverse topological
1286f785676fSDimitry Andric   // order.  We don't do anything to try to order import link flags with respect
1287f785676fSDimitry Andric   // to linker options inserted by things like #pragma comment().
128839d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 16> MetadataArgs;
1289139f7f9bSDimitry Andric   Visited.clear();
12908f0fd8f6SDimitry Andric   for (Module *M : LinkModules)
12918f0fd8f6SDimitry Andric     if (Visited.insert(M).second)
12928f0fd8f6SDimitry Andric       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
1293139f7f9bSDimitry Andric   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1294f785676fSDimitry Andric   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1295139f7f9bSDimitry Andric 
1296139f7f9bSDimitry Andric   // Add the linker options metadata flag.
1297139f7f9bSDimitry Andric   getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
1298f785676fSDimitry Andric                             llvm::MDNode::get(getLLVMContext(),
1299f785676fSDimitry Andric                                               LinkerOptionsMetadata));
1300139f7f9bSDimitry Andric }
1301139f7f9bSDimitry Andric 
1302f22ef01cSRoman Divacky void CodeGenModule::EmitDeferred() {
1303f22ef01cSRoman Divacky   // Emit code for any potentially referenced deferred decls.  Since a
1304f22ef01cSRoman Divacky   // previously unused static decl may become used during the generation of code
1305f22ef01cSRoman Divacky   // for a static function, iterate until no changes are made.
1306f22ef01cSRoman Divacky 
1307f22ef01cSRoman Divacky   if (!DeferredVTables.empty()) {
1308139f7f9bSDimitry Andric     EmitDeferredVTables();
1309139f7f9bSDimitry Andric 
1310e7145dcbSDimitry Andric     // Emitting a vtable doesn't directly cause more vtables to
1311139f7f9bSDimitry Andric     // become deferred, although it can cause functions to be
1312e7145dcbSDimitry Andric     // emitted that then need those vtables.
1313139f7f9bSDimitry Andric     assert(DeferredVTables.empty());
1314f22ef01cSRoman Divacky   }
1315f22ef01cSRoman Divacky 
1316e7145dcbSDimitry Andric   // Stop if we're out of both deferred vtables and deferred declarations.
131733956c43SDimitry Andric   if (DeferredDeclsToEmit.empty())
131833956c43SDimitry Andric     return;
1319139f7f9bSDimitry Andric 
132033956c43SDimitry Andric   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
132133956c43SDimitry Andric   // work, it will not interfere with this.
132233956c43SDimitry Andric   std::vector<DeferredGlobal> CurDeclsToEmit;
132333956c43SDimitry Andric   CurDeclsToEmit.swap(DeferredDeclsToEmit);
132433956c43SDimitry Andric 
132533956c43SDimitry Andric   for (DeferredGlobal &G : CurDeclsToEmit) {
132659d1ed5bSDimitry Andric     GlobalDecl D = G.GD;
132733956c43SDimitry Andric     G.GV = nullptr;
1328f22ef01cSRoman Divacky 
13290623d748SDimitry Andric     // We should call GetAddrOfGlobal with IsForDefinition set to true in order
13300623d748SDimitry Andric     // to get GlobalValue with exactly the type we need, not something that
13310623d748SDimitry Andric     // might had been created for another decl with the same mangled name but
13320623d748SDimitry Andric     // different type.
1333e7145dcbSDimitry Andric     llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
133444290647SDimitry Andric         GetAddrOfGlobal(D, ForDefinition));
1335e7145dcbSDimitry Andric 
1336e7145dcbSDimitry Andric     // In case of different address spaces, we may still get a cast, even with
1337e7145dcbSDimitry Andric     // IsForDefinition equal to true. Query mangled names table to get
1338e7145dcbSDimitry Andric     // GlobalValue.
133939d628a0SDimitry Andric     if (!GV)
134039d628a0SDimitry Andric       GV = GetGlobalValue(getMangledName(D));
134139d628a0SDimitry Andric 
1342e7145dcbSDimitry Andric     // Make sure GetGlobalValue returned non-null.
1343e7145dcbSDimitry Andric     assert(GV);
1344e7145dcbSDimitry Andric 
1345f22ef01cSRoman Divacky     // Check to see if we've already emitted this.  This is necessary
1346f22ef01cSRoman Divacky     // for a couple of reasons: first, decls can end up in the
1347f22ef01cSRoman Divacky     // deferred-decls queue multiple times, and second, decls can end
1348f22ef01cSRoman Divacky     // up with definitions in unusual ways (e.g. by an extern inline
1349f22ef01cSRoman Divacky     // function acquiring a strong function redefinition).  Just
1350f22ef01cSRoman Divacky     // ignore these cases.
1351e7145dcbSDimitry Andric     if (!GV->isDeclaration())
1352f22ef01cSRoman Divacky       continue;
1353f22ef01cSRoman Divacky 
1354f22ef01cSRoman Divacky     // Otherwise, emit the definition and move on to the next one.
135559d1ed5bSDimitry Andric     EmitGlobalDefinition(D, GV);
135633956c43SDimitry Andric 
135733956c43SDimitry Andric     // If we found out that we need to emit more decls, do that recursively.
135833956c43SDimitry Andric     // This has the advantage that the decls are emitted in a DFS and related
135933956c43SDimitry Andric     // ones are close together, which is convenient for testing.
136033956c43SDimitry Andric     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
136133956c43SDimitry Andric       EmitDeferred();
136233956c43SDimitry Andric       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
136333956c43SDimitry Andric     }
1364f22ef01cSRoman Divacky   }
1365f22ef01cSRoman Divacky }
1366f22ef01cSRoman Divacky 
13676122f3e6SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() {
13686122f3e6SDimitry Andric   if (Annotations.empty())
13696122f3e6SDimitry Andric     return;
13706122f3e6SDimitry Andric 
13716122f3e6SDimitry Andric   // Create a new global variable for the ConstantStruct in the Module.
13726122f3e6SDimitry Andric   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
13736122f3e6SDimitry Andric     Annotations[0]->getType(), Annotations.size()), Annotations);
137459d1ed5bSDimitry Andric   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
137559d1ed5bSDimitry Andric                                       llvm::GlobalValue::AppendingLinkage,
137659d1ed5bSDimitry Andric                                       Array, "llvm.global.annotations");
13776122f3e6SDimitry Andric   gv->setSection(AnnotationSection);
13786122f3e6SDimitry Andric }
13796122f3e6SDimitry Andric 
1380139f7f9bSDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1381f785676fSDimitry Andric   llvm::Constant *&AStr = AnnotationStrings[Str];
1382f785676fSDimitry Andric   if (AStr)
1383f785676fSDimitry Andric     return AStr;
13846122f3e6SDimitry Andric 
13856122f3e6SDimitry Andric   // Not found yet, create a new global.
1386dff0c46cSDimitry Andric   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
138759d1ed5bSDimitry Andric   auto *gv =
138859d1ed5bSDimitry Andric       new llvm::GlobalVariable(getModule(), s->getType(), true,
138959d1ed5bSDimitry Andric                                llvm::GlobalValue::PrivateLinkage, s, ".str");
13906122f3e6SDimitry Andric   gv->setSection(AnnotationSection);
1391e7145dcbSDimitry Andric   gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1392f785676fSDimitry Andric   AStr = gv;
13936122f3e6SDimitry Andric   return gv;
13946122f3e6SDimitry Andric }
13956122f3e6SDimitry Andric 
13966122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
13976122f3e6SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
13986122f3e6SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
13996122f3e6SDimitry Andric   if (PLoc.isValid())
14006122f3e6SDimitry Andric     return EmitAnnotationString(PLoc.getFilename());
14016122f3e6SDimitry Andric   return EmitAnnotationString(SM.getBufferName(Loc));
14026122f3e6SDimitry Andric }
14036122f3e6SDimitry Andric 
14046122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
14056122f3e6SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
14066122f3e6SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(L);
14076122f3e6SDimitry Andric   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
14086122f3e6SDimitry Andric     SM.getExpansionLineNumber(L);
14096122f3e6SDimitry Andric   return llvm::ConstantInt::get(Int32Ty, LineNo);
14106122f3e6SDimitry Andric }
14116122f3e6SDimitry Andric 
1412f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1413f22ef01cSRoman Divacky                                                 const AnnotateAttr *AA,
14146122f3e6SDimitry Andric                                                 SourceLocation L) {
14156122f3e6SDimitry Andric   // Get the globals for file name, annotation, and the line number.
14166122f3e6SDimitry Andric   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
14176122f3e6SDimitry Andric                  *UnitGV = EmitAnnotationUnit(L),
14186122f3e6SDimitry Andric                  *LineNoCst = EmitAnnotationLineNo(L);
1419f22ef01cSRoman Divacky 
1420f22ef01cSRoman Divacky   // Create the ConstantStruct for the global annotation.
1421f22ef01cSRoman Divacky   llvm::Constant *Fields[4] = {
14226122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
14236122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
14246122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
14256122f3e6SDimitry Andric     LineNoCst
1426f22ef01cSRoman Divacky   };
142717a519f9SDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
1428f22ef01cSRoman Divacky }
1429f22ef01cSRoman Divacky 
14306122f3e6SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
14316122f3e6SDimitry Andric                                          llvm::GlobalValue *GV) {
14326122f3e6SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
14336122f3e6SDimitry Andric   // Get the struct elements for these annotations.
143459d1ed5bSDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>())
143559d1ed5bSDimitry Andric     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
14366122f3e6SDimitry Andric }
14376122f3e6SDimitry Andric 
143839d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
143939d628a0SDimitry Andric                                            SourceLocation Loc) const {
144039d628a0SDimitry Andric   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
144139d628a0SDimitry Andric   // Blacklist by function name.
144239d628a0SDimitry Andric   if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
144339d628a0SDimitry Andric     return true;
144439d628a0SDimitry Andric   // Blacklist by location.
14450623d748SDimitry Andric   if (Loc.isValid())
144639d628a0SDimitry Andric     return SanitizerBL.isBlacklistedLocation(Loc);
144739d628a0SDimitry Andric   // If location is unknown, this may be a compiler-generated function. Assume
144839d628a0SDimitry Andric   // it's located in the main file.
144939d628a0SDimitry Andric   auto &SM = Context.getSourceManager();
145039d628a0SDimitry Andric   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
145139d628a0SDimitry Andric     return SanitizerBL.isBlacklistedFile(MainFile->getName());
145239d628a0SDimitry Andric   }
145339d628a0SDimitry Andric   return false;
145439d628a0SDimitry Andric }
145539d628a0SDimitry Andric 
145639d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
145739d628a0SDimitry Andric                                            SourceLocation Loc, QualType Ty,
145839d628a0SDimitry Andric                                            StringRef Category) const {
14598f0fd8f6SDimitry Andric   // For now globals can be blacklisted only in ASan and KASan.
14608f0fd8f6SDimitry Andric   if (!LangOpts.Sanitize.hasOneOf(
14618f0fd8f6SDimitry Andric           SanitizerKind::Address | SanitizerKind::KernelAddress))
146239d628a0SDimitry Andric     return false;
146339d628a0SDimitry Andric   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
146439d628a0SDimitry Andric   if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
146539d628a0SDimitry Andric     return true;
146639d628a0SDimitry Andric   if (SanitizerBL.isBlacklistedLocation(Loc, Category))
146739d628a0SDimitry Andric     return true;
146839d628a0SDimitry Andric   // Check global type.
146939d628a0SDimitry Andric   if (!Ty.isNull()) {
147039d628a0SDimitry Andric     // Drill down the array types: if global variable of a fixed type is
147139d628a0SDimitry Andric     // blacklisted, we also don't instrument arrays of them.
147239d628a0SDimitry Andric     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
147339d628a0SDimitry Andric       Ty = AT->getElementType();
147439d628a0SDimitry Andric     Ty = Ty.getCanonicalType().getUnqualifiedType();
147539d628a0SDimitry Andric     // We allow to blacklist only record types (classes, structs etc.)
147639d628a0SDimitry Andric     if (Ty->isRecordType()) {
147739d628a0SDimitry Andric       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
147839d628a0SDimitry Andric       if (SanitizerBL.isBlacklistedType(TypeStr, Category))
147939d628a0SDimitry Andric         return true;
148039d628a0SDimitry Andric     }
148139d628a0SDimitry Andric   }
148239d628a0SDimitry Andric   return false;
148339d628a0SDimitry Andric }
148439d628a0SDimitry Andric 
148539d628a0SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
1486e580952dSDimitry Andric   // Never defer when EmitAllDecls is specified.
1487dff0c46cSDimitry Andric   if (LangOpts.EmitAllDecls)
148839d628a0SDimitry Andric     return true;
148939d628a0SDimitry Andric 
149039d628a0SDimitry Andric   return getContext().DeclMustBeEmitted(Global);
149139d628a0SDimitry Andric }
149239d628a0SDimitry Andric 
149339d628a0SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
149439d628a0SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global))
149539d628a0SDimitry Andric     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
149639d628a0SDimitry Andric       // Implicit template instantiations may change linkage if they are later
149739d628a0SDimitry Andric       // explicitly instantiated, so they should not be emitted eagerly.
1498f22ef01cSRoman Divacky       return false;
1499e7145dcbSDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(Global))
1500e7145dcbSDimitry Andric     if (Context.getInlineVariableDefinitionKind(VD) ==
1501e7145dcbSDimitry Andric         ASTContext::InlineVariableDefinitionKind::WeakUnknown)
1502e7145dcbSDimitry Andric       // A definition of an inline constexpr static data member may change
1503e7145dcbSDimitry Andric       // linkage later if it's redeclared outside the class.
1504e7145dcbSDimitry Andric       return false;
1505875ed548SDimitry Andric   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
1506875ed548SDimitry Andric   // codegen for global variables, because they may be marked as threadprivate.
1507875ed548SDimitry Andric   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1508875ed548SDimitry Andric       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
1509875ed548SDimitry Andric     return false;
1510f22ef01cSRoman Divacky 
151139d628a0SDimitry Andric   return true;
1512f22ef01cSRoman Divacky }
1513f22ef01cSRoman Divacky 
15140623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
15153861d79fSDimitry Andric     const CXXUuidofExpr* E) {
15163861d79fSDimitry Andric   // Sema has verified that IIDSource has a __declspec(uuid()), and that its
15173861d79fSDimitry Andric   // well-formed.
1518e7145dcbSDimitry Andric   StringRef Uuid = E->getUuidStr();
1519f785676fSDimitry Andric   std::string Name = "_GUID_" + Uuid.lower();
1520f785676fSDimitry Andric   std::replace(Name.begin(), Name.end(), '-', '_');
15213861d79fSDimitry Andric 
1522e7145dcbSDimitry Andric   // The UUID descriptor should be pointer aligned.
1523e7145dcbSDimitry Andric   CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
15240623d748SDimitry Andric 
15253861d79fSDimitry Andric   // Look for an existing global.
15263861d79fSDimitry Andric   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
15270623d748SDimitry Andric     return ConstantAddress(GV, Alignment);
15283861d79fSDimitry Andric 
152939d628a0SDimitry Andric   llvm::Constant *Init = EmitUuidofInitializer(Uuid);
15303861d79fSDimitry Andric   assert(Init && "failed to initialize as constant");
15313861d79fSDimitry Andric 
153259d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
1533f785676fSDimitry Andric       getModule(), Init->getType(),
1534f785676fSDimitry Andric       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
153533956c43SDimitry Andric   if (supportsCOMDAT())
153633956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
15370623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
15383861d79fSDimitry Andric }
15393861d79fSDimitry Andric 
15400623d748SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1541f22ef01cSRoman Divacky   const AliasAttr *AA = VD->getAttr<AliasAttr>();
1542f22ef01cSRoman Divacky   assert(AA && "No alias?");
1543f22ef01cSRoman Divacky 
15440623d748SDimitry Andric   CharUnits Alignment = getContext().getDeclAlign(VD);
15456122f3e6SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1546f22ef01cSRoman Divacky 
1547f22ef01cSRoman Divacky   // See if there is already something with the target's name in the module.
1548f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
15493861d79fSDimitry Andric   if (Entry) {
15503861d79fSDimitry Andric     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
15510623d748SDimitry Andric     auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
15520623d748SDimitry Andric     return ConstantAddress(Ptr, Alignment);
15533861d79fSDimitry Andric   }
1554f22ef01cSRoman Divacky 
1555f22ef01cSRoman Divacky   llvm::Constant *Aliasee;
1556f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(DeclTy))
15573861d79fSDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
15583861d79fSDimitry Andric                                       GlobalDecl(cast<FunctionDecl>(VD)),
15592754fe60SDimitry Andric                                       /*ForVTable=*/false);
1560f22ef01cSRoman Divacky   else
1561f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
156259d1ed5bSDimitry Andric                                     llvm::PointerType::getUnqual(DeclTy),
156359d1ed5bSDimitry Andric                                     nullptr);
15643861d79fSDimitry Andric 
156559d1ed5bSDimitry Andric   auto *F = cast<llvm::GlobalValue>(Aliasee);
1566f22ef01cSRoman Divacky   F->setLinkage(llvm::Function::ExternalWeakLinkage);
1567f22ef01cSRoman Divacky   WeakRefReferences.insert(F);
1568f22ef01cSRoman Divacky 
15690623d748SDimitry Andric   return ConstantAddress(Aliasee, Alignment);
1570f22ef01cSRoman Divacky }
1571f22ef01cSRoman Divacky 
1572f22ef01cSRoman Divacky void CodeGenModule::EmitGlobal(GlobalDecl GD) {
157359d1ed5bSDimitry Andric   const auto *Global = cast<ValueDecl>(GD.getDecl());
1574f22ef01cSRoman Divacky 
1575f22ef01cSRoman Divacky   // Weak references don't produce any output by themselves.
1576f22ef01cSRoman Divacky   if (Global->hasAttr<WeakRefAttr>())
1577f22ef01cSRoman Divacky     return;
1578f22ef01cSRoman Divacky 
1579f22ef01cSRoman Divacky   // If this is an alias definition (which otherwise looks like a declaration)
1580f22ef01cSRoman Divacky   // emit it now.
1581f22ef01cSRoman Divacky   if (Global->hasAttr<AliasAttr>())
1582f22ef01cSRoman Divacky     return EmitAliasDefinition(GD);
1583f22ef01cSRoman Divacky 
1584e7145dcbSDimitry Andric   // IFunc like an alias whose value is resolved at runtime by calling resolver.
1585e7145dcbSDimitry Andric   if (Global->hasAttr<IFuncAttr>())
1586e7145dcbSDimitry Andric     return emitIFuncDefinition(GD);
1587e7145dcbSDimitry Andric 
15886122f3e6SDimitry Andric   // If this is CUDA, be selective about which declarations we emit.
1589dff0c46cSDimitry Andric   if (LangOpts.CUDA) {
159033956c43SDimitry Andric     if (LangOpts.CUDAIsDevice) {
15916122f3e6SDimitry Andric       if (!Global->hasAttr<CUDADeviceAttr>() &&
15926122f3e6SDimitry Andric           !Global->hasAttr<CUDAGlobalAttr>() &&
15936122f3e6SDimitry Andric           !Global->hasAttr<CUDAConstantAttr>() &&
15946122f3e6SDimitry Andric           !Global->hasAttr<CUDASharedAttr>())
15956122f3e6SDimitry Andric         return;
15966122f3e6SDimitry Andric     } else {
1597e7145dcbSDimitry Andric       // We need to emit host-side 'shadows' for all global
1598e7145dcbSDimitry Andric       // device-side variables because the CUDA runtime needs their
1599e7145dcbSDimitry Andric       // size and host-side address in order to provide access to
1600e7145dcbSDimitry Andric       // their device-side incarnations.
1601e7145dcbSDimitry Andric 
1602e7145dcbSDimitry Andric       // So device-only functions are the only things we skip.
1603e7145dcbSDimitry Andric       if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
1604e7145dcbSDimitry Andric           Global->hasAttr<CUDADeviceAttr>())
16056122f3e6SDimitry Andric         return;
1606e7145dcbSDimitry Andric 
1607e7145dcbSDimitry Andric       assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
1608e7145dcbSDimitry Andric              "Expected Variable or Function");
1609e580952dSDimitry Andric     }
1610e580952dSDimitry Andric   }
1611e580952dSDimitry Andric 
1612e7145dcbSDimitry Andric   if (LangOpts.OpenMP) {
1613ea942507SDimitry Andric     // If this is OpenMP device, check if it is legal to emit this global
1614ea942507SDimitry Andric     // normally.
1615ea942507SDimitry Andric     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
1616ea942507SDimitry Andric       return;
1617e7145dcbSDimitry Andric     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
1618e7145dcbSDimitry Andric       if (MustBeEmitted(Global))
1619e7145dcbSDimitry Andric         EmitOMPDeclareReduction(DRD);
1620e7145dcbSDimitry Andric       return;
1621e7145dcbSDimitry Andric     }
1622e7145dcbSDimitry Andric   }
1623ea942507SDimitry Andric 
16246122f3e6SDimitry Andric   // Ignore declarations, they will be emitted on their first use.
162559d1ed5bSDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
1626f22ef01cSRoman Divacky     // Forward declarations are emitted lazily on first use.
16276122f3e6SDimitry Andric     if (!FD->doesThisDeclarationHaveABody()) {
16286122f3e6SDimitry Andric       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1629f22ef01cSRoman Divacky         return;
16306122f3e6SDimitry Andric 
16316122f3e6SDimitry Andric       StringRef MangledName = getMangledName(GD);
163259d1ed5bSDimitry Andric 
163359d1ed5bSDimitry Andric       // Compute the function info and LLVM type.
163459d1ed5bSDimitry Andric       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
163559d1ed5bSDimitry Andric       llvm::Type *Ty = getTypes().GetFunctionType(FI);
163659d1ed5bSDimitry Andric 
163759d1ed5bSDimitry Andric       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
163859d1ed5bSDimitry Andric                               /*DontDefer=*/false);
16396122f3e6SDimitry Andric       return;
16406122f3e6SDimitry Andric     }
1641f22ef01cSRoman Divacky   } else {
164259d1ed5bSDimitry Andric     const auto *VD = cast<VarDecl>(Global);
1643f22ef01cSRoman Divacky     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1644e7145dcbSDimitry Andric     // We need to emit device-side global CUDA variables even if a
1645e7145dcbSDimitry Andric     // variable does not have a definition -- we still need to define
1646e7145dcbSDimitry Andric     // host-side shadow for it.
1647e7145dcbSDimitry Andric     bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
1648e7145dcbSDimitry Andric                            !VD->hasDefinition() &&
1649e7145dcbSDimitry Andric                            (VD->hasAttr<CUDAConstantAttr>() ||
1650e7145dcbSDimitry Andric                             VD->hasAttr<CUDADeviceAttr>());
1651e7145dcbSDimitry Andric     if (!MustEmitForCuda &&
1652e7145dcbSDimitry Andric         VD->isThisDeclarationADefinition() != VarDecl::Definition &&
1653e7145dcbSDimitry Andric         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
1654e7145dcbSDimitry Andric       // If this declaration may have caused an inline variable definition to
1655e7145dcbSDimitry Andric       // change linkage, make sure that it's emitted.
1656e7145dcbSDimitry Andric       if (Context.getInlineVariableDefinitionKind(VD) ==
1657e7145dcbSDimitry Andric           ASTContext::InlineVariableDefinitionKind::Strong)
1658e7145dcbSDimitry Andric         GetAddrOfGlobalVar(VD);
1659f22ef01cSRoman Divacky       return;
1660f22ef01cSRoman Divacky     }
1661e7145dcbSDimitry Andric   }
1662f22ef01cSRoman Divacky 
166339d628a0SDimitry Andric   // Defer code generation to first use when possible, e.g. if this is an inline
166439d628a0SDimitry Andric   // function. If the global must always be emitted, do it eagerly if possible
166539d628a0SDimitry Andric   // to benefit from cache locality.
166639d628a0SDimitry Andric   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
1667f22ef01cSRoman Divacky     // Emit the definition if it can't be deferred.
1668f22ef01cSRoman Divacky     EmitGlobalDefinition(GD);
1669f22ef01cSRoman Divacky     return;
1670f22ef01cSRoman Divacky   }
1671f22ef01cSRoman Divacky 
1672e580952dSDimitry Andric   // If we're deferring emission of a C++ variable with an
1673e580952dSDimitry Andric   // initializer, remember the order in which it appeared in the file.
1674dff0c46cSDimitry Andric   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1675e580952dSDimitry Andric       cast<VarDecl>(Global)->hasInit()) {
1676e580952dSDimitry Andric     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
167759d1ed5bSDimitry Andric     CXXGlobalInits.push_back(nullptr);
1678e580952dSDimitry Andric   }
1679e580952dSDimitry Andric 
16806122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
168139d628a0SDimitry Andric   if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) {
168239d628a0SDimitry Andric     // The value has already been used and should therefore be emitted.
168359d1ed5bSDimitry Andric     addDeferredDeclToEmit(GV, GD);
168439d628a0SDimitry Andric   } else if (MustBeEmitted(Global)) {
168539d628a0SDimitry Andric     // The value must be emitted, but cannot be emitted eagerly.
168639d628a0SDimitry Andric     assert(!MayBeEmittedEagerly(Global));
168739d628a0SDimitry Andric     addDeferredDeclToEmit(/*GV=*/nullptr, GD);
168839d628a0SDimitry Andric   } else {
1689f22ef01cSRoman Divacky     // Otherwise, remember that we saw a deferred decl with this name.  The
1690f22ef01cSRoman Divacky     // first use of the mangled name will cause it to move into
1691f22ef01cSRoman Divacky     // DeferredDeclsToEmit.
1692f22ef01cSRoman Divacky     DeferredDecls[MangledName] = GD;
1693f22ef01cSRoman Divacky   }
1694f22ef01cSRoman Divacky }
1695f22ef01cSRoman Divacky 
1696f8254f43SDimitry Andric namespace {
1697f8254f43SDimitry Andric   struct FunctionIsDirectlyRecursive :
1698f8254f43SDimitry Andric     public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1699f8254f43SDimitry Andric     const StringRef Name;
1700dff0c46cSDimitry Andric     const Builtin::Context &BI;
1701f8254f43SDimitry Andric     bool Result;
1702dff0c46cSDimitry Andric     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1703dff0c46cSDimitry Andric       Name(N), BI(C), Result(false) {
1704f8254f43SDimitry Andric     }
1705f8254f43SDimitry Andric     typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1706f8254f43SDimitry Andric 
1707f8254f43SDimitry Andric     bool TraverseCallExpr(CallExpr *E) {
1708dff0c46cSDimitry Andric       const FunctionDecl *FD = E->getDirectCallee();
1709dff0c46cSDimitry Andric       if (!FD)
1710f8254f43SDimitry Andric         return true;
1711dff0c46cSDimitry Andric       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1712dff0c46cSDimitry Andric       if (Attr && Name == Attr->getLabel()) {
1713dff0c46cSDimitry Andric         Result = true;
1714dff0c46cSDimitry Andric         return false;
1715dff0c46cSDimitry Andric       }
1716dff0c46cSDimitry Andric       unsigned BuiltinID = FD->getBuiltinID();
17173dac3a9bSDimitry Andric       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
1718f8254f43SDimitry Andric         return true;
17190623d748SDimitry Andric       StringRef BuiltinName = BI.getName(BuiltinID);
1720dff0c46cSDimitry Andric       if (BuiltinName.startswith("__builtin_") &&
1721dff0c46cSDimitry Andric           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1722f8254f43SDimitry Andric         Result = true;
1723f8254f43SDimitry Andric         return false;
1724f8254f43SDimitry Andric       }
1725f8254f43SDimitry Andric       return true;
1726f8254f43SDimitry Andric     }
1727f8254f43SDimitry Andric   };
17280623d748SDimitry Andric 
17290623d748SDimitry Andric   struct DLLImportFunctionVisitor
17300623d748SDimitry Andric       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
17310623d748SDimitry Andric     bool SafeToInline = true;
17320623d748SDimitry Andric 
173344290647SDimitry Andric     bool shouldVisitImplicitCode() const { return true; }
173444290647SDimitry Andric 
17350623d748SDimitry Andric     bool VisitVarDecl(VarDecl *VD) {
17360623d748SDimitry Andric       // A thread-local variable cannot be imported.
17370623d748SDimitry Andric       SafeToInline = !VD->getTLSKind();
17380623d748SDimitry Andric       return SafeToInline;
17390623d748SDimitry Andric     }
17400623d748SDimitry Andric 
17410623d748SDimitry Andric     // Make sure we're not referencing non-imported vars or functions.
17420623d748SDimitry Andric     bool VisitDeclRefExpr(DeclRefExpr *E) {
17430623d748SDimitry Andric       ValueDecl *VD = E->getDecl();
17440623d748SDimitry Andric       if (isa<FunctionDecl>(VD))
17450623d748SDimitry Andric         SafeToInline = VD->hasAttr<DLLImportAttr>();
17460623d748SDimitry Andric       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
17470623d748SDimitry Andric         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
17480623d748SDimitry Andric       return SafeToInline;
17490623d748SDimitry Andric     }
175044290647SDimitry Andric     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
175144290647SDimitry Andric       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
175244290647SDimitry Andric       return SafeToInline;
175344290647SDimitry Andric     }
17540623d748SDimitry Andric     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
17550623d748SDimitry Andric       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
17560623d748SDimitry Andric       return SafeToInline;
17570623d748SDimitry Andric     }
17580623d748SDimitry Andric     bool VisitCXXNewExpr(CXXNewExpr *E) {
17590623d748SDimitry Andric       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
17600623d748SDimitry Andric       return SafeToInline;
17610623d748SDimitry Andric     }
17620623d748SDimitry Andric   };
1763f8254f43SDimitry Andric }
1764f8254f43SDimitry Andric 
1765dff0c46cSDimitry Andric // isTriviallyRecursive - Check if this function calls another
1766dff0c46cSDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin,
1767dff0c46cSDimitry Andric // ends up pointing to itself.
1768f8254f43SDimitry Andric bool
1769dff0c46cSDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1770dff0c46cSDimitry Andric   StringRef Name;
1771dff0c46cSDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1772dff0c46cSDimitry Andric     // asm labels are a special kind of mangling we have to support.
1773dff0c46cSDimitry Andric     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1774dff0c46cSDimitry Andric     if (!Attr)
1775f8254f43SDimitry Andric       return false;
1776dff0c46cSDimitry Andric     Name = Attr->getLabel();
1777dff0c46cSDimitry Andric   } else {
1778dff0c46cSDimitry Andric     Name = FD->getName();
1779dff0c46cSDimitry Andric   }
1780f8254f43SDimitry Andric 
1781dff0c46cSDimitry Andric   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1782dff0c46cSDimitry Andric   Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1783f8254f43SDimitry Andric   return Walker.Result;
1784f8254f43SDimitry Andric }
1785f8254f43SDimitry Andric 
178644290647SDimitry Andric // Check if T is a class type with a destructor that's not dllimport.
178744290647SDimitry Andric static bool HasNonDllImportDtor(QualType T) {
178844290647SDimitry Andric   if (const RecordType *RT = dyn_cast<RecordType>(T))
178944290647SDimitry Andric     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
179044290647SDimitry Andric       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
179144290647SDimitry Andric         return true;
179244290647SDimitry Andric 
179344290647SDimitry Andric   return false;
179444290647SDimitry Andric }
179544290647SDimitry Andric 
179644290647SDimitry Andric bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1797f785676fSDimitry Andric   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1798f8254f43SDimitry Andric     return true;
179959d1ed5bSDimitry Andric   const auto *F = cast<FunctionDecl>(GD.getDecl());
180059d1ed5bSDimitry Andric   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1801f8254f43SDimitry Andric     return false;
18020623d748SDimitry Andric 
18030623d748SDimitry Andric   if (F->hasAttr<DLLImportAttr>()) {
18040623d748SDimitry Andric     // Check whether it would be safe to inline this dllimport function.
18050623d748SDimitry Andric     DLLImportFunctionVisitor Visitor;
18060623d748SDimitry Andric     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
18070623d748SDimitry Andric     if (!Visitor.SafeToInline)
18080623d748SDimitry Andric       return false;
180944290647SDimitry Andric 
181044290647SDimitry Andric     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
181144290647SDimitry Andric       // Implicit destructor invocations aren't captured in the AST, so the
181244290647SDimitry Andric       // check above can't see them. Check for them manually here.
181344290647SDimitry Andric       for (const Decl *Member : Dtor->getParent()->decls())
181444290647SDimitry Andric         if (isa<FieldDecl>(Member))
181544290647SDimitry Andric           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
181644290647SDimitry Andric             return false;
181744290647SDimitry Andric       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
181844290647SDimitry Andric         if (HasNonDllImportDtor(B.getType()))
181944290647SDimitry Andric           return false;
182044290647SDimitry Andric     }
18210623d748SDimitry Andric   }
18220623d748SDimitry Andric 
1823f8254f43SDimitry Andric   // PR9614. Avoid cases where the source code is lying to us. An available
1824f8254f43SDimitry Andric   // externally function should have an equivalent function somewhere else,
1825f8254f43SDimitry Andric   // but a function that calls itself is clearly not equivalent to the real
1826f8254f43SDimitry Andric   // implementation.
1827f8254f43SDimitry Andric   // This happens in glibc's btowc and in some configure checks.
1828dff0c46cSDimitry Andric   return !isTriviallyRecursive(F);
1829f8254f43SDimitry Andric }
1830f8254f43SDimitry Andric 
1831f785676fSDimitry Andric /// If the type for the method's class was generated by
1832f785676fSDimitry Andric /// CGDebugInfo::createContextChain(), the cache contains only a
1833f785676fSDimitry Andric /// limited DIType without any declarations. Since EmitFunctionStart()
1834f785676fSDimitry Andric /// needs to find the canonical declaration for each method, we need
1835f785676fSDimitry Andric /// to construct the complete type prior to emitting the method.
1836f785676fSDimitry Andric void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
1837f785676fSDimitry Andric   if (!D->isInstance())
1838f785676fSDimitry Andric     return;
1839f785676fSDimitry Andric 
1840f785676fSDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
1841e7145dcbSDimitry Andric     if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
184259d1ed5bSDimitry Andric       const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext()));
1843f785676fSDimitry Andric       DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
1844f785676fSDimitry Andric     }
1845f785676fSDimitry Andric }
1846f785676fSDimitry Andric 
184759d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
184859d1ed5bSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
1849f22ef01cSRoman Divacky 
1850f22ef01cSRoman Divacky   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1851f22ef01cSRoman Divacky                                  Context.getSourceManager(),
1852f22ef01cSRoman Divacky                                  "Generating code for declaration");
1853f22ef01cSRoman Divacky 
1854f785676fSDimitry Andric   if (isa<FunctionDecl>(D)) {
1855ffd1746dSEd Schouten     // At -O0, don't generate IR for functions with available_externally
1856ffd1746dSEd Schouten     // linkage.
1857f785676fSDimitry Andric     if (!shouldEmitFunction(GD))
1858ffd1746dSEd Schouten       return;
1859ffd1746dSEd Schouten 
186059d1ed5bSDimitry Andric     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
1861f785676fSDimitry Andric       CompleteDIClassType(Method);
1862bd5abe19SDimitry Andric       // Make sure to emit the definition(s) before we emit the thunks.
1863bd5abe19SDimitry Andric       // This is necessary for the generation of certain thunks.
186459d1ed5bSDimitry Andric       if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
186539d628a0SDimitry Andric         ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
186659d1ed5bSDimitry Andric       else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
186739d628a0SDimitry Andric         ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
1868bd5abe19SDimitry Andric       else
186959d1ed5bSDimitry Andric         EmitGlobalFunctionDefinition(GD, GV);
1870bd5abe19SDimitry Andric 
1871f22ef01cSRoman Divacky       if (Method->isVirtual())
1872f22ef01cSRoman Divacky         getVTables().EmitThunks(GD);
1873f22ef01cSRoman Divacky 
1874bd5abe19SDimitry Andric       return;
1875ffd1746dSEd Schouten     }
1876f22ef01cSRoman Divacky 
187759d1ed5bSDimitry Andric     return EmitGlobalFunctionDefinition(GD, GV);
1878ffd1746dSEd Schouten   }
1879f22ef01cSRoman Divacky 
188059d1ed5bSDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
1881e7145dcbSDimitry Andric     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
1882f22ef01cSRoman Divacky 
18836122f3e6SDimitry Andric   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1884f22ef01cSRoman Divacky }
1885f22ef01cSRoman Divacky 
18860623d748SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
18870623d748SDimitry Andric                                                       llvm::Function *NewFn);
18880623d748SDimitry Andric 
1889f22ef01cSRoman Divacky /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1890f22ef01cSRoman Divacky /// module, create and return an llvm Function with the specified type. If there
1891f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially
1892f22ef01cSRoman Divacky /// bitcasted to the right type.
1893f22ef01cSRoman Divacky ///
1894f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this.  This is used
1895f22ef01cSRoman Divacky /// to set the attributes on the function when it is first created.
1896f22ef01cSRoman Divacky llvm::Constant *
18976122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
18986122f3e6SDimitry Andric                                        llvm::Type *Ty,
1899f785676fSDimitry Andric                                        GlobalDecl GD, bool ForVTable,
190039d628a0SDimitry Andric                                        bool DontDefer, bool IsThunk,
19010623d748SDimitry Andric                                        llvm::AttributeSet ExtraAttrs,
190244290647SDimitry Andric                                        ForDefinition_t IsForDefinition) {
1903f785676fSDimitry Andric   const Decl *D = GD.getDecl();
1904f785676fSDimitry Andric 
1905f22ef01cSRoman Divacky   // Lookup the entry, lazily creating it if necessary.
1906f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1907f22ef01cSRoman Divacky   if (Entry) {
19083861d79fSDimitry Andric     if (WeakRefReferences.erase(Entry)) {
1909f785676fSDimitry Andric       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
1910f22ef01cSRoman Divacky       if (FD && !FD->hasAttr<WeakAttr>())
1911f22ef01cSRoman Divacky         Entry->setLinkage(llvm::Function::ExternalLinkage);
1912f22ef01cSRoman Divacky     }
1913f22ef01cSRoman Divacky 
191439d628a0SDimitry Andric     // Handle dropped DLL attributes.
191539d628a0SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
191639d628a0SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
191739d628a0SDimitry Andric 
19180623d748SDimitry Andric     // If there are two attempts to define the same mangled name, issue an
19190623d748SDimitry Andric     // error.
19200623d748SDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
19210623d748SDimitry Andric       GlobalDecl OtherGD;
1922e7145dcbSDimitry Andric       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
1923e7145dcbSDimitry Andric       // to make sure that we issue an error only once.
19240623d748SDimitry Andric       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
19250623d748SDimitry Andric           (GD.getCanonicalDecl().getDecl() !=
19260623d748SDimitry Andric            OtherGD.getCanonicalDecl().getDecl()) &&
19270623d748SDimitry Andric           DiagnosedConflictingDefinitions.insert(GD).second) {
19280623d748SDimitry Andric         getDiags().Report(D->getLocation(),
19290623d748SDimitry Andric                           diag::err_duplicate_mangled_name);
19300623d748SDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
19310623d748SDimitry Andric                           diag::note_previous_definition);
19320623d748SDimitry Andric       }
19330623d748SDimitry Andric     }
19340623d748SDimitry Andric 
19350623d748SDimitry Andric     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
19360623d748SDimitry Andric         (Entry->getType()->getElementType() == Ty)) {
1937f22ef01cSRoman Divacky       return Entry;
19380623d748SDimitry Andric     }
1939f22ef01cSRoman Divacky 
1940f22ef01cSRoman Divacky     // Make sure the result is of the correct type.
19410623d748SDimitry Andric     // (If function is requested for a definition, we always need to create a new
19420623d748SDimitry Andric     // function, not just return a bitcast.)
19430623d748SDimitry Andric     if (!IsForDefinition)
194417a519f9SDimitry Andric       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1945f22ef01cSRoman Divacky   }
1946f22ef01cSRoman Divacky 
1947f22ef01cSRoman Divacky   // This function doesn't have a complete type (for example, the return
1948f22ef01cSRoman Divacky   // type is an incomplete struct). Use a fake type instead, and make
1949f22ef01cSRoman Divacky   // sure not to try to set attributes.
1950f22ef01cSRoman Divacky   bool IsIncompleteFunction = false;
1951f22ef01cSRoman Divacky 
19526122f3e6SDimitry Andric   llvm::FunctionType *FTy;
1953f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(Ty)) {
1954f22ef01cSRoman Divacky     FTy = cast<llvm::FunctionType>(Ty);
1955f22ef01cSRoman Divacky   } else {
1956bd5abe19SDimitry Andric     FTy = llvm::FunctionType::get(VoidTy, false);
1957f22ef01cSRoman Divacky     IsIncompleteFunction = true;
1958f22ef01cSRoman Divacky   }
1959ffd1746dSEd Schouten 
19600623d748SDimitry Andric   llvm::Function *F =
19610623d748SDimitry Andric       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
19620623d748SDimitry Andric                              Entry ? StringRef() : MangledName, &getModule());
19630623d748SDimitry Andric 
19640623d748SDimitry Andric   // If we already created a function with the same mangled name (but different
19650623d748SDimitry Andric   // type) before, take its name and add it to the list of functions to be
19660623d748SDimitry Andric   // replaced with F at the end of CodeGen.
19670623d748SDimitry Andric   //
19680623d748SDimitry Andric   // This happens if there is a prototype for a function (e.g. "int f()") and
19690623d748SDimitry Andric   // then a definition of a different type (e.g. "int f(int x)").
19700623d748SDimitry Andric   if (Entry) {
19710623d748SDimitry Andric     F->takeName(Entry);
19720623d748SDimitry Andric 
19730623d748SDimitry Andric     // This might be an implementation of a function without a prototype, in
19740623d748SDimitry Andric     // which case, try to do special replacement of calls which match the new
19750623d748SDimitry Andric     // prototype.  The really key thing here is that we also potentially drop
19760623d748SDimitry Andric     // arguments from the call site so as to make a direct call, which makes the
19770623d748SDimitry Andric     // inliner happier and suppresses a number of optimizer warnings (!) about
19780623d748SDimitry Andric     // dropping arguments.
19790623d748SDimitry Andric     if (!Entry->use_empty()) {
19800623d748SDimitry Andric       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
19810623d748SDimitry Andric       Entry->removeDeadConstantUsers();
19820623d748SDimitry Andric     }
19830623d748SDimitry Andric 
19840623d748SDimitry Andric     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
19850623d748SDimitry Andric         F, Entry->getType()->getElementType()->getPointerTo());
19860623d748SDimitry Andric     addGlobalValReplacement(Entry, BC);
19870623d748SDimitry Andric   }
19880623d748SDimitry Andric 
1989f22ef01cSRoman Divacky   assert(F->getName() == MangledName && "name was uniqued!");
1990f785676fSDimitry Andric   if (D)
199139d628a0SDimitry Andric     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
1992139f7f9bSDimitry Andric   if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1993139f7f9bSDimitry Andric     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
1994139f7f9bSDimitry Andric     F->addAttributes(llvm::AttributeSet::FunctionIndex,
1995139f7f9bSDimitry Andric                      llvm::AttributeSet::get(VMContext,
1996139f7f9bSDimitry Andric                                              llvm::AttributeSet::FunctionIndex,
1997139f7f9bSDimitry Andric                                              B));
1998139f7f9bSDimitry Andric   }
1999f22ef01cSRoman Divacky 
200059d1ed5bSDimitry Andric   if (!DontDefer) {
200159d1ed5bSDimitry Andric     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
200259d1ed5bSDimitry Andric     // each other bottoming out with the base dtor.  Therefore we emit non-base
200359d1ed5bSDimitry Andric     // dtors on usage, even if there is no dtor definition in the TU.
200459d1ed5bSDimitry Andric     if (D && isa<CXXDestructorDecl>(D) &&
200559d1ed5bSDimitry Andric         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
200659d1ed5bSDimitry Andric                                            GD.getDtorType()))
200759d1ed5bSDimitry Andric       addDeferredDeclToEmit(F, GD);
200859d1ed5bSDimitry Andric 
2009f22ef01cSRoman Divacky     // This is the first use or definition of a mangled name.  If there is a
2010f22ef01cSRoman Divacky     // deferred decl with this name, remember that we need to emit it at the end
2011f22ef01cSRoman Divacky     // of the file.
201259d1ed5bSDimitry Andric     auto DDI = DeferredDecls.find(MangledName);
2013f22ef01cSRoman Divacky     if (DDI != DeferredDecls.end()) {
201459d1ed5bSDimitry Andric       // Move the potentially referenced deferred decl to the
201559d1ed5bSDimitry Andric       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
201659d1ed5bSDimitry Andric       // don't need it anymore).
201759d1ed5bSDimitry Andric       addDeferredDeclToEmit(F, DDI->second);
2018f22ef01cSRoman Divacky       DeferredDecls.erase(DDI);
20192754fe60SDimitry Andric 
20202754fe60SDimitry Andric       // Otherwise, there are cases we have to worry about where we're
20212754fe60SDimitry Andric       // using a declaration for which we must emit a definition but where
20222754fe60SDimitry Andric       // we might not find a top-level definition:
20232754fe60SDimitry Andric       //   - member functions defined inline in their classes
20242754fe60SDimitry Andric       //   - friend functions defined inline in some class
20252754fe60SDimitry Andric       //   - special member functions with implicit definitions
20262754fe60SDimitry Andric       // If we ever change our AST traversal to walk into class methods,
20272754fe60SDimitry Andric       // this will be unnecessary.
20282754fe60SDimitry Andric       //
202959d1ed5bSDimitry Andric       // We also don't emit a definition for a function if it's going to be an
203039d628a0SDimitry Andric       // entry in a vtable, unless it's already marked as used.
2031f785676fSDimitry Andric     } else if (getLangOpts().CPlusPlus && D) {
20322754fe60SDimitry Andric       // Look for a declaration that's lexically in a record.
203339d628a0SDimitry Andric       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
203439d628a0SDimitry Andric            FD = FD->getPreviousDecl()) {
20352754fe60SDimitry Andric         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
203639d628a0SDimitry Andric           if (FD->doesThisDeclarationHaveABody()) {
203759d1ed5bSDimitry Andric             addDeferredDeclToEmit(F, GD.getWithDecl(FD));
20382754fe60SDimitry Andric             break;
2039f22ef01cSRoman Divacky           }
2040f22ef01cSRoman Divacky         }
204139d628a0SDimitry Andric       }
2042f22ef01cSRoman Divacky     }
204359d1ed5bSDimitry Andric   }
2044f22ef01cSRoman Divacky 
2045f22ef01cSRoman Divacky   // Make sure the result is of the requested type.
2046f22ef01cSRoman Divacky   if (!IsIncompleteFunction) {
2047f22ef01cSRoman Divacky     assert(F->getType()->getElementType() == Ty);
2048f22ef01cSRoman Divacky     return F;
2049f22ef01cSRoman Divacky   }
2050f22ef01cSRoman Divacky 
205117a519f9SDimitry Andric   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2052f22ef01cSRoman Divacky   return llvm::ConstantExpr::getBitCast(F, PTy);
2053f22ef01cSRoman Divacky }
2054f22ef01cSRoman Divacky 
2055f22ef01cSRoman Divacky /// GetAddrOfFunction - Return the address of the given function.  If Ty is
2056f22ef01cSRoman Divacky /// non-null, then this function will use the specified type if it has to
2057f22ef01cSRoman Divacky /// create it (this occurs when we see a definition of the function).
2058f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
20596122f3e6SDimitry Andric                                                  llvm::Type *Ty,
206059d1ed5bSDimitry Andric                                                  bool ForVTable,
20610623d748SDimitry Andric                                                  bool DontDefer,
206244290647SDimitry Andric                                               ForDefinition_t IsForDefinition) {
2063f22ef01cSRoman Divacky   // If there was no specific requested type, just convert it now.
20640623d748SDimitry Andric   if (!Ty) {
20650623d748SDimitry Andric     const auto *FD = cast<FunctionDecl>(GD.getDecl());
20660623d748SDimitry Andric     auto CanonTy = Context.getCanonicalType(FD->getType());
20670623d748SDimitry Andric     Ty = getTypes().ConvertFunctionType(CanonTy, FD);
20680623d748SDimitry Andric   }
2069ffd1746dSEd Schouten 
20706122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
20710623d748SDimitry Andric   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
20720623d748SDimitry Andric                                  /*IsThunk=*/false, llvm::AttributeSet(),
20730623d748SDimitry Andric                                  IsForDefinition);
2074f22ef01cSRoman Divacky }
2075f22ef01cSRoman Divacky 
207644290647SDimitry Andric static const FunctionDecl *
207744290647SDimitry Andric GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
207844290647SDimitry Andric   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
207944290647SDimitry Andric   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
208044290647SDimitry Andric 
208144290647SDimitry Andric   IdentifierInfo &CII = C.Idents.get(Name);
208244290647SDimitry Andric   for (const auto &Result : DC->lookup(&CII))
208344290647SDimitry Andric     if (const auto FD = dyn_cast<FunctionDecl>(Result))
208444290647SDimitry Andric       return FD;
208544290647SDimitry Andric 
208644290647SDimitry Andric   if (!C.getLangOpts().CPlusPlus)
208744290647SDimitry Andric     return nullptr;
208844290647SDimitry Andric 
208944290647SDimitry Andric   // Demangle the premangled name from getTerminateFn()
209044290647SDimitry Andric   IdentifierInfo &CXXII =
209144290647SDimitry Andric       (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ")
209244290647SDimitry Andric           ? C.Idents.get("terminate")
209344290647SDimitry Andric           : C.Idents.get(Name);
209444290647SDimitry Andric 
209544290647SDimitry Andric   for (const auto &N : {"__cxxabiv1", "std"}) {
209644290647SDimitry Andric     IdentifierInfo &NS = C.Idents.get(N);
209744290647SDimitry Andric     for (const auto &Result : DC->lookup(&NS)) {
209844290647SDimitry Andric       NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
209944290647SDimitry Andric       if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
210044290647SDimitry Andric         for (const auto &Result : LSD->lookup(&NS))
210144290647SDimitry Andric           if ((ND = dyn_cast<NamespaceDecl>(Result)))
210244290647SDimitry Andric             break;
210344290647SDimitry Andric 
210444290647SDimitry Andric       if (ND)
210544290647SDimitry Andric         for (const auto &Result : ND->lookup(&CXXII))
210644290647SDimitry Andric           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
210744290647SDimitry Andric             return FD;
210844290647SDimitry Andric     }
210944290647SDimitry Andric   }
211044290647SDimitry Andric 
211144290647SDimitry Andric   return nullptr;
211244290647SDimitry Andric }
211344290647SDimitry Andric 
2114f22ef01cSRoman Divacky /// CreateRuntimeFunction - Create a new runtime function with the specified
2115f22ef01cSRoman Divacky /// type and name.
2116f22ef01cSRoman Divacky llvm::Constant *
211744290647SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
211844290647SDimitry Andric                                      llvm::AttributeSet ExtraAttrs,
211944290647SDimitry Andric                                      bool Local) {
212059d1ed5bSDimitry Andric   llvm::Constant *C =
212159d1ed5bSDimitry Andric       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
212244290647SDimitry Andric                               /*DontDefer=*/false, /*IsThunk=*/false,
212344290647SDimitry Andric                               ExtraAttrs);
212444290647SDimitry Andric 
212544290647SDimitry Andric   if (auto *F = dyn_cast<llvm::Function>(C)) {
212644290647SDimitry Andric     if (F->empty()) {
2127139f7f9bSDimitry Andric       F->setCallingConv(getRuntimeCC());
212844290647SDimitry Andric 
212944290647SDimitry Andric       if (!Local && getTriple().isOSBinFormatCOFF() &&
213044290647SDimitry Andric           !getCodeGenOpts().LTOVisibilityPublicStd) {
213144290647SDimitry Andric         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
213244290647SDimitry Andric         if (!FD || FD->hasAttr<DLLImportAttr>()) {
213344290647SDimitry Andric           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
213444290647SDimitry Andric           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
213544290647SDimitry Andric         }
213644290647SDimitry Andric       }
213744290647SDimitry Andric     }
213844290647SDimitry Andric   }
213944290647SDimitry Andric 
2140139f7f9bSDimitry Andric   return C;
2141f22ef01cSRoman Divacky }
2142f22ef01cSRoman Divacky 
214339d628a0SDimitry Andric /// CreateBuiltinFunction - Create a new builtin function with the specified
214439d628a0SDimitry Andric /// type and name.
214539d628a0SDimitry Andric llvm::Constant *
214639d628a0SDimitry Andric CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy,
214739d628a0SDimitry Andric                                      StringRef Name,
214839d628a0SDimitry Andric                                      llvm::AttributeSet ExtraAttrs) {
214939d628a0SDimitry Andric   llvm::Constant *C =
215039d628a0SDimitry Andric       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
215139d628a0SDimitry Andric                               /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
215239d628a0SDimitry Andric   if (auto *F = dyn_cast<llvm::Function>(C))
215339d628a0SDimitry Andric     if (F->empty())
215439d628a0SDimitry Andric       F->setCallingConv(getBuiltinCC());
215539d628a0SDimitry Andric   return C;
215639d628a0SDimitry Andric }
215739d628a0SDimitry Andric 
2158dff0c46cSDimitry Andric /// isTypeConstant - Determine whether an object of this type can be emitted
2159dff0c46cSDimitry Andric /// as a constant.
2160dff0c46cSDimitry Andric ///
2161dff0c46cSDimitry Andric /// If ExcludeCtor is true, the duration when the object's constructor runs
2162dff0c46cSDimitry Andric /// will not be considered. The caller will need to verify that the object is
2163dff0c46cSDimitry Andric /// not written to during its construction.
2164dff0c46cSDimitry Andric bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2165dff0c46cSDimitry Andric   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
2166f22ef01cSRoman Divacky     return false;
2167bd5abe19SDimitry Andric 
2168dff0c46cSDimitry Andric   if (Context.getLangOpts().CPlusPlus) {
2169dff0c46cSDimitry Andric     if (const CXXRecordDecl *Record
2170dff0c46cSDimitry Andric           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2171dff0c46cSDimitry Andric       return ExcludeCtor && !Record->hasMutableFields() &&
2172dff0c46cSDimitry Andric              Record->hasTrivialDestructor();
2173f22ef01cSRoman Divacky   }
2174bd5abe19SDimitry Andric 
2175f22ef01cSRoman Divacky   return true;
2176f22ef01cSRoman Divacky }
2177f22ef01cSRoman Divacky 
2178f22ef01cSRoman Divacky /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2179f22ef01cSRoman Divacky /// create and return an llvm GlobalVariable with the specified type.  If there
2180f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially
2181f22ef01cSRoman Divacky /// bitcasted to the right type.
2182f22ef01cSRoman Divacky ///
2183f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this.  This is used
2184f22ef01cSRoman Divacky /// to set the attributes on the global when it is first created.
2185e7145dcbSDimitry Andric ///
2186e7145dcbSDimitry Andric /// If IsForDefinition is true, it is guranteed that an actual global with
2187e7145dcbSDimitry Andric /// type Ty will be returned, not conversion of a variable with the same
2188e7145dcbSDimitry Andric /// mangled name but some other type.
2189f22ef01cSRoman Divacky llvm::Constant *
21906122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
21916122f3e6SDimitry Andric                                      llvm::PointerType *Ty,
2192e7145dcbSDimitry Andric                                      const VarDecl *D,
219344290647SDimitry Andric                                      ForDefinition_t IsForDefinition) {
2194f22ef01cSRoman Divacky   // Lookup the entry, lazily creating it if necessary.
2195f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2196f22ef01cSRoman Divacky   if (Entry) {
21973861d79fSDimitry Andric     if (WeakRefReferences.erase(Entry)) {
2198f22ef01cSRoman Divacky       if (D && !D->hasAttr<WeakAttr>())
2199f22ef01cSRoman Divacky         Entry->setLinkage(llvm::Function::ExternalLinkage);
2200f22ef01cSRoman Divacky     }
2201f22ef01cSRoman Divacky 
220239d628a0SDimitry Andric     // Handle dropped DLL attributes.
220339d628a0SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
220439d628a0SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
220539d628a0SDimitry Andric 
2206f22ef01cSRoman Divacky     if (Entry->getType() == Ty)
2207f22ef01cSRoman Divacky       return Entry;
2208f22ef01cSRoman Divacky 
2209e7145dcbSDimitry Andric     // If there are two attempts to define the same mangled name, issue an
2210e7145dcbSDimitry Andric     // error.
2211e7145dcbSDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
2212e7145dcbSDimitry Andric       GlobalDecl OtherGD;
2213e7145dcbSDimitry Andric       const VarDecl *OtherD;
2214e7145dcbSDimitry Andric 
2215e7145dcbSDimitry Andric       // Check that D is not yet in DiagnosedConflictingDefinitions is required
2216e7145dcbSDimitry Andric       // to make sure that we issue an error only once.
2217e7145dcbSDimitry Andric       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
2218e7145dcbSDimitry Andric           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2219e7145dcbSDimitry Andric           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2220e7145dcbSDimitry Andric           OtherD->hasInit() &&
2221e7145dcbSDimitry Andric           DiagnosedConflictingDefinitions.insert(D).second) {
2222e7145dcbSDimitry Andric         getDiags().Report(D->getLocation(),
2223e7145dcbSDimitry Andric                           diag::err_duplicate_mangled_name);
2224e7145dcbSDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
2225e7145dcbSDimitry Andric                           diag::note_previous_definition);
2226e7145dcbSDimitry Andric       }
2227e7145dcbSDimitry Andric     }
2228e7145dcbSDimitry Andric 
2229f22ef01cSRoman Divacky     // Make sure the result is of the correct type.
2230f785676fSDimitry Andric     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2231f785676fSDimitry Andric       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2232f785676fSDimitry Andric 
2233e7145dcbSDimitry Andric     // (If global is requested for a definition, we always need to create a new
2234e7145dcbSDimitry Andric     // global, not just return a bitcast.)
2235e7145dcbSDimitry Andric     if (!IsForDefinition)
2236f22ef01cSRoman Divacky       return llvm::ConstantExpr::getBitCast(Entry, Ty);
2237f22ef01cSRoman Divacky   }
2238f22ef01cSRoman Divacky 
223959d1ed5bSDimitry Andric   unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
224059d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
224159d1ed5bSDimitry Andric       getModule(), Ty->getElementType(), false,
224259d1ed5bSDimitry Andric       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
224359d1ed5bSDimitry Andric       llvm::GlobalVariable::NotThreadLocal, AddrSpace);
224459d1ed5bSDimitry Andric 
2245e7145dcbSDimitry Andric   // If we already created a global with the same mangled name (but different
2246e7145dcbSDimitry Andric   // type) before, take its name and remove it from its parent.
2247e7145dcbSDimitry Andric   if (Entry) {
2248e7145dcbSDimitry Andric     GV->takeName(Entry);
2249e7145dcbSDimitry Andric 
2250e7145dcbSDimitry Andric     if (!Entry->use_empty()) {
2251e7145dcbSDimitry Andric       llvm::Constant *NewPtrForOldDecl =
2252e7145dcbSDimitry Andric           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2253e7145dcbSDimitry Andric       Entry->replaceAllUsesWith(NewPtrForOldDecl);
2254e7145dcbSDimitry Andric     }
2255e7145dcbSDimitry Andric 
2256e7145dcbSDimitry Andric     Entry->eraseFromParent();
2257e7145dcbSDimitry Andric   }
2258e7145dcbSDimitry Andric 
2259f22ef01cSRoman Divacky   // This is the first use or definition of a mangled name.  If there is a
2260f22ef01cSRoman Divacky   // deferred decl with this name, remember that we need to emit it at the end
2261f22ef01cSRoman Divacky   // of the file.
226259d1ed5bSDimitry Andric   auto DDI = DeferredDecls.find(MangledName);
2263f22ef01cSRoman Divacky   if (DDI != DeferredDecls.end()) {
2264f22ef01cSRoman Divacky     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2265f22ef01cSRoman Divacky     // list, and remove it from DeferredDecls (since we don't need it anymore).
226659d1ed5bSDimitry Andric     addDeferredDeclToEmit(GV, DDI->second);
2267f22ef01cSRoman Divacky     DeferredDecls.erase(DDI);
2268f22ef01cSRoman Divacky   }
2269f22ef01cSRoman Divacky 
2270f22ef01cSRoman Divacky   // Handle things which are present even on external declarations.
2271f22ef01cSRoman Divacky   if (D) {
2272f22ef01cSRoman Divacky     // FIXME: This code is overly simple and should be merged with other global
2273f22ef01cSRoman Divacky     // handling.
2274dff0c46cSDimitry Andric     GV->setConstant(isTypeConstant(D->getType(), false));
2275f22ef01cSRoman Divacky 
227633956c43SDimitry Andric     GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
227733956c43SDimitry Andric 
227859d1ed5bSDimitry Andric     setLinkageAndVisibilityForGV(GV, D);
22792754fe60SDimitry Andric 
2280284c1978SDimitry Andric     if (D->getTLSKind()) {
2281284c1978SDimitry Andric       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
22820623d748SDimitry Andric         CXXThreadLocals.push_back(D);
22837ae0e2c9SDimitry Andric       setTLSMode(GV, *D);
2284f22ef01cSRoman Divacky     }
2285f785676fSDimitry Andric 
2286f785676fSDimitry Andric     // If required by the ABI, treat declarations of static data members with
2287f785676fSDimitry Andric     // inline initializers as definitions.
228859d1ed5bSDimitry Andric     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
2289f785676fSDimitry Andric       EmitGlobalVarDefinition(D);
2290284c1978SDimitry Andric     }
2291f22ef01cSRoman Divacky 
229259d1ed5bSDimitry Andric     // Handle XCore specific ABI requirements.
229344290647SDimitry Andric     if (getTriple().getArch() == llvm::Triple::xcore &&
229459d1ed5bSDimitry Andric         D->getLanguageLinkage() == CLanguageLinkage &&
229559d1ed5bSDimitry Andric         D->getType().isConstant(Context) &&
229659d1ed5bSDimitry Andric         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
229759d1ed5bSDimitry Andric       GV->setSection(".cp.rodata");
229859d1ed5bSDimitry Andric   }
229959d1ed5bSDimitry Andric 
23007ae0e2c9SDimitry Andric   if (AddrSpace != Ty->getAddressSpace())
2301f785676fSDimitry Andric     return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
2302f785676fSDimitry Andric 
2303f22ef01cSRoman Divacky   return GV;
2304f22ef01cSRoman Divacky }
2305f22ef01cSRoman Divacky 
23060623d748SDimitry Andric llvm::Constant *
23070623d748SDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
230844290647SDimitry Andric                                ForDefinition_t IsForDefinition) {
230944290647SDimitry Andric   const Decl *D = GD.getDecl();
231044290647SDimitry Andric   if (isa<CXXConstructorDecl>(D))
231144290647SDimitry Andric     return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
23120623d748SDimitry Andric                                 getFromCtorType(GD.getCtorType()),
23130623d748SDimitry Andric                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
23140623d748SDimitry Andric                                 /*DontDefer=*/false, IsForDefinition);
231544290647SDimitry Andric   else if (isa<CXXDestructorDecl>(D))
231644290647SDimitry Andric     return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
23170623d748SDimitry Andric                                 getFromDtorType(GD.getDtorType()),
23180623d748SDimitry Andric                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
23190623d748SDimitry Andric                                 /*DontDefer=*/false, IsForDefinition);
232044290647SDimitry Andric   else if (isa<CXXMethodDecl>(D)) {
23210623d748SDimitry Andric     auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
232244290647SDimitry Andric         cast<CXXMethodDecl>(D));
23230623d748SDimitry Andric     auto Ty = getTypes().GetFunctionType(*FInfo);
23240623d748SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
23250623d748SDimitry Andric                              IsForDefinition);
232644290647SDimitry Andric   } else if (isa<FunctionDecl>(D)) {
23270623d748SDimitry Andric     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
23280623d748SDimitry Andric     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
23290623d748SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
23300623d748SDimitry Andric                              IsForDefinition);
23310623d748SDimitry Andric   } else
233244290647SDimitry Andric     return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
2333e7145dcbSDimitry Andric                               IsForDefinition);
23340623d748SDimitry Andric }
2335f22ef01cSRoman Divacky 
23362754fe60SDimitry Andric llvm::GlobalVariable *
23376122f3e6SDimitry Andric CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
23386122f3e6SDimitry Andric                                       llvm::Type *Ty,
23392754fe60SDimitry Andric                                       llvm::GlobalValue::LinkageTypes Linkage) {
23402754fe60SDimitry Andric   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
234159d1ed5bSDimitry Andric   llvm::GlobalVariable *OldGV = nullptr;
23422754fe60SDimitry Andric 
23432754fe60SDimitry Andric   if (GV) {
23442754fe60SDimitry Andric     // Check if the variable has the right type.
23452754fe60SDimitry Andric     if (GV->getType()->getElementType() == Ty)
23462754fe60SDimitry Andric       return GV;
23472754fe60SDimitry Andric 
23482754fe60SDimitry Andric     // Because C++ name mangling, the only way we can end up with an already
23492754fe60SDimitry Andric     // existing global with the same name is if it has been declared extern "C".
23502754fe60SDimitry Andric     assert(GV->isDeclaration() && "Declaration has wrong type!");
23512754fe60SDimitry Andric     OldGV = GV;
23522754fe60SDimitry Andric   }
23532754fe60SDimitry Andric 
23542754fe60SDimitry Andric   // Create a new variable.
23552754fe60SDimitry Andric   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
235659d1ed5bSDimitry Andric                                 Linkage, nullptr, Name);
23572754fe60SDimitry Andric 
23582754fe60SDimitry Andric   if (OldGV) {
23592754fe60SDimitry Andric     // Replace occurrences of the old variable if needed.
23602754fe60SDimitry Andric     GV->takeName(OldGV);
23612754fe60SDimitry Andric 
23622754fe60SDimitry Andric     if (!OldGV->use_empty()) {
23632754fe60SDimitry Andric       llvm::Constant *NewPtrForOldDecl =
23642754fe60SDimitry Andric       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
23652754fe60SDimitry Andric       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
23662754fe60SDimitry Andric     }
23672754fe60SDimitry Andric 
23682754fe60SDimitry Andric     OldGV->eraseFromParent();
23692754fe60SDimitry Andric   }
23702754fe60SDimitry Andric 
237133956c43SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker() &&
237233956c43SDimitry Andric       !GV->hasAvailableExternallyLinkage())
237333956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
237433956c43SDimitry Andric 
23752754fe60SDimitry Andric   return GV;
23762754fe60SDimitry Andric }
23772754fe60SDimitry Andric 
2378f22ef01cSRoman Divacky /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
2379f22ef01cSRoman Divacky /// given global variable.  If Ty is non-null and if the global doesn't exist,
2380cb4dff85SDimitry Andric /// then it will be created with the specified type instead of whatever the
2381e7145dcbSDimitry Andric /// normal requested type would be. If IsForDefinition is true, it is guranteed
2382e7145dcbSDimitry Andric /// that an actual global with type Ty will be returned, not conversion of a
2383e7145dcbSDimitry Andric /// variable with the same mangled name but some other type.
2384f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
2385e7145dcbSDimitry Andric                                                   llvm::Type *Ty,
238644290647SDimitry Andric                                            ForDefinition_t IsForDefinition) {
2387f22ef01cSRoman Divacky   assert(D->hasGlobalStorage() && "Not a global variable");
2388f22ef01cSRoman Divacky   QualType ASTTy = D->getType();
238959d1ed5bSDimitry Andric   if (!Ty)
2390f22ef01cSRoman Divacky     Ty = getTypes().ConvertTypeForMem(ASTTy);
2391f22ef01cSRoman Divacky 
23926122f3e6SDimitry Andric   llvm::PointerType *PTy =
23933b0f4066SDimitry Andric     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
2394f22ef01cSRoman Divacky 
23956122f3e6SDimitry Andric   StringRef MangledName = getMangledName(D);
2396e7145dcbSDimitry Andric   return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
2397f22ef01cSRoman Divacky }
2398f22ef01cSRoman Divacky 
2399f22ef01cSRoman Divacky /// CreateRuntimeVariable - Create a new runtime global variable with the
2400f22ef01cSRoman Divacky /// specified type and name.
2401f22ef01cSRoman Divacky llvm::Constant *
24026122f3e6SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
24036122f3e6SDimitry Andric                                      StringRef Name) {
240459d1ed5bSDimitry Andric   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
2405f22ef01cSRoman Divacky }
2406f22ef01cSRoman Divacky 
2407f22ef01cSRoman Divacky void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
2408f22ef01cSRoman Divacky   assert(!D->getInit() && "Cannot emit definite definitions here!");
2409f22ef01cSRoman Divacky 
24106122f3e6SDimitry Andric   StringRef MangledName = getMangledName(D);
2411e7145dcbSDimitry Andric   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
2412e7145dcbSDimitry Andric 
2413e7145dcbSDimitry Andric   // We already have a definition, not declaration, with the same mangled name.
2414e7145dcbSDimitry Andric   // Emitting of declaration is not required (and actually overwrites emitted
2415e7145dcbSDimitry Andric   // definition).
2416e7145dcbSDimitry Andric   if (GV && !GV->isDeclaration())
2417e7145dcbSDimitry Andric     return;
2418e7145dcbSDimitry Andric 
2419e7145dcbSDimitry Andric   // If we have not seen a reference to this variable yet, place it into the
2420e7145dcbSDimitry Andric   // deferred declarations table to be emitted if needed later.
2421e7145dcbSDimitry Andric   if (!MustBeEmitted(D) && !GV) {
2422f22ef01cSRoman Divacky       DeferredDecls[MangledName] = D;
2423f22ef01cSRoman Divacky       return;
2424f22ef01cSRoman Divacky   }
2425f22ef01cSRoman Divacky 
2426f22ef01cSRoman Divacky   // The tentative definition is the only definition.
2427f22ef01cSRoman Divacky   EmitGlobalVarDefinition(D);
2428f22ef01cSRoman Divacky }
2429f22ef01cSRoman Divacky 
24306122f3e6SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
24312754fe60SDimitry Andric   return Context.toCharUnitsFromBits(
24320623d748SDimitry Andric       getDataLayout().getTypeStoreSizeInBits(Ty));
2433f22ef01cSRoman Divacky }
2434f22ef01cSRoman Divacky 
24357ae0e2c9SDimitry Andric unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
24367ae0e2c9SDimitry Andric                                                  unsigned AddrSpace) {
2437e7145dcbSDimitry Andric   if (D && LangOpts.CUDA && LangOpts.CUDAIsDevice) {
24387ae0e2c9SDimitry Andric     if (D->hasAttr<CUDAConstantAttr>())
24397ae0e2c9SDimitry Andric       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
24407ae0e2c9SDimitry Andric     else if (D->hasAttr<CUDASharedAttr>())
24417ae0e2c9SDimitry Andric       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
24427ae0e2c9SDimitry Andric     else
24437ae0e2c9SDimitry Andric       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
24447ae0e2c9SDimitry Andric   }
24457ae0e2c9SDimitry Andric 
24467ae0e2c9SDimitry Andric   return AddrSpace;
24477ae0e2c9SDimitry Andric }
24487ae0e2c9SDimitry Andric 
2449284c1978SDimitry Andric template<typename SomeDecl>
2450284c1978SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
2451284c1978SDimitry Andric                                                llvm::GlobalValue *GV) {
2452284c1978SDimitry Andric   if (!getLangOpts().CPlusPlus)
2453284c1978SDimitry Andric     return;
2454284c1978SDimitry Andric 
2455284c1978SDimitry Andric   // Must have 'used' attribute, or else inline assembly can't rely on
2456284c1978SDimitry Andric   // the name existing.
2457284c1978SDimitry Andric   if (!D->template hasAttr<UsedAttr>())
2458284c1978SDimitry Andric     return;
2459284c1978SDimitry Andric 
2460284c1978SDimitry Andric   // Must have internal linkage and an ordinary name.
2461f785676fSDimitry Andric   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
2462284c1978SDimitry Andric     return;
2463284c1978SDimitry Andric 
2464284c1978SDimitry Andric   // Must be in an extern "C" context. Entities declared directly within
2465284c1978SDimitry Andric   // a record are not extern "C" even if the record is in such a context.
2466f785676fSDimitry Andric   const SomeDecl *First = D->getFirstDecl();
2467284c1978SDimitry Andric   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
2468284c1978SDimitry Andric     return;
2469284c1978SDimitry Andric 
2470284c1978SDimitry Andric   // OK, this is an internal linkage entity inside an extern "C" linkage
2471284c1978SDimitry Andric   // specification. Make a note of that so we can give it the "expected"
2472284c1978SDimitry Andric   // mangled name if nothing else is using that name.
2473284c1978SDimitry Andric   std::pair<StaticExternCMap::iterator, bool> R =
2474284c1978SDimitry Andric       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
2475284c1978SDimitry Andric 
2476284c1978SDimitry Andric   // If we have multiple internal linkage entities with the same name
2477284c1978SDimitry Andric   // in extern "C" regions, none of them gets that name.
2478284c1978SDimitry Andric   if (!R.second)
247959d1ed5bSDimitry Andric     R.first->second = nullptr;
2480284c1978SDimitry Andric }
2481284c1978SDimitry Andric 
248233956c43SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
248333956c43SDimitry Andric   if (!CGM.supportsCOMDAT())
248433956c43SDimitry Andric     return false;
248533956c43SDimitry Andric 
248633956c43SDimitry Andric   if (D.hasAttr<SelectAnyAttr>())
248733956c43SDimitry Andric     return true;
248833956c43SDimitry Andric 
248933956c43SDimitry Andric   GVALinkage Linkage;
249033956c43SDimitry Andric   if (auto *VD = dyn_cast<VarDecl>(&D))
249133956c43SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
249233956c43SDimitry Andric   else
249333956c43SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
249433956c43SDimitry Andric 
249533956c43SDimitry Andric   switch (Linkage) {
249633956c43SDimitry Andric   case GVA_Internal:
249733956c43SDimitry Andric   case GVA_AvailableExternally:
249833956c43SDimitry Andric   case GVA_StrongExternal:
249933956c43SDimitry Andric     return false;
250033956c43SDimitry Andric   case GVA_DiscardableODR:
250133956c43SDimitry Andric   case GVA_StrongODR:
250233956c43SDimitry Andric     return true;
250333956c43SDimitry Andric   }
250433956c43SDimitry Andric   llvm_unreachable("No such linkage");
250533956c43SDimitry Andric }
250633956c43SDimitry Andric 
250733956c43SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
250833956c43SDimitry Andric                                           llvm::GlobalObject &GO) {
250933956c43SDimitry Andric   if (!shouldBeInCOMDAT(*this, D))
251033956c43SDimitry Andric     return;
251133956c43SDimitry Andric   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
251233956c43SDimitry Andric }
251333956c43SDimitry Andric 
2514e7145dcbSDimitry Andric /// Pass IsTentative as true if you want to create a tentative definition.
2515e7145dcbSDimitry Andric void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
2516e7145dcbSDimitry Andric                                             bool IsTentative) {
251744290647SDimitry Andric   // OpenCL global variables of sampler type are translated to function calls,
251844290647SDimitry Andric   // therefore no need to be translated.
2519f22ef01cSRoman Divacky   QualType ASTTy = D->getType();
252044290647SDimitry Andric   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
252144290647SDimitry Andric     return;
252244290647SDimitry Andric 
252344290647SDimitry Andric   llvm::Constant *Init = nullptr;
2524dff0c46cSDimitry Andric   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2525dff0c46cSDimitry Andric   bool NeedsGlobalCtor = false;
2526dff0c46cSDimitry Andric   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
2527f22ef01cSRoman Divacky 
2528dff0c46cSDimitry Andric   const VarDecl *InitDecl;
2529dff0c46cSDimitry Andric   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
2530f22ef01cSRoman Divacky 
2531e7145dcbSDimitry Andric   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
2532e7145dcbSDimitry Andric   // as part of their declaration."  Sema has already checked for
2533e7145dcbSDimitry Andric   // error cases, so we just need to set Init to UndefValue.
2534e7145dcbSDimitry Andric   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
2535e7145dcbSDimitry Andric       D->hasAttr<CUDASharedAttr>())
25360623d748SDimitry Andric     Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
2537e7145dcbSDimitry Andric   else if (!InitExpr) {
2538f22ef01cSRoman Divacky     // This is a tentative definition; tentative definitions are
2539f22ef01cSRoman Divacky     // implicitly initialized with { 0 }.
2540f22ef01cSRoman Divacky     //
2541f22ef01cSRoman Divacky     // Note that tentative definitions are only emitted at the end of
2542f22ef01cSRoman Divacky     // a translation unit, so they should never have incomplete
2543f22ef01cSRoman Divacky     // type. In addition, EmitTentativeDefinition makes sure that we
2544f22ef01cSRoman Divacky     // never attempt to emit a tentative definition if a real one
2545f22ef01cSRoman Divacky     // exists. A use may still exists, however, so we still may need
2546f22ef01cSRoman Divacky     // to do a RAUW.
2547f22ef01cSRoman Divacky     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
2548f22ef01cSRoman Divacky     Init = EmitNullConstant(D->getType());
2549f22ef01cSRoman Divacky   } else {
25507ae0e2c9SDimitry Andric     initializedGlobalDecl = GlobalDecl(D);
2551dff0c46cSDimitry Andric     Init = EmitConstantInit(*InitDecl);
2552f785676fSDimitry Andric 
2553f22ef01cSRoman Divacky     if (!Init) {
2554f22ef01cSRoman Divacky       QualType T = InitExpr->getType();
2555f22ef01cSRoman Divacky       if (D->getType()->isReferenceType())
2556f22ef01cSRoman Divacky         T = D->getType();
2557f22ef01cSRoman Divacky 
2558dff0c46cSDimitry Andric       if (getLangOpts().CPlusPlus) {
2559f22ef01cSRoman Divacky         Init = EmitNullConstant(T);
2560dff0c46cSDimitry Andric         NeedsGlobalCtor = true;
2561f22ef01cSRoman Divacky       } else {
2562f22ef01cSRoman Divacky         ErrorUnsupported(D, "static initializer");
2563f22ef01cSRoman Divacky         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
2564f22ef01cSRoman Divacky       }
2565e580952dSDimitry Andric     } else {
2566e580952dSDimitry Andric       // We don't need an initializer, so remove the entry for the delayed
2567dff0c46cSDimitry Andric       // initializer position (just in case this entry was delayed) if we
2568dff0c46cSDimitry Andric       // also don't need to register a destructor.
2569dff0c46cSDimitry Andric       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
2570e580952dSDimitry Andric         DelayedCXXInitPosition.erase(D);
2571f22ef01cSRoman Divacky     }
2572f22ef01cSRoman Divacky   }
2573f22ef01cSRoman Divacky 
25746122f3e6SDimitry Andric   llvm::Type* InitType = Init->getType();
2575e7145dcbSDimitry Andric   llvm::Constant *Entry =
257644290647SDimitry Andric       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
2577f22ef01cSRoman Divacky 
2578f22ef01cSRoman Divacky   // Strip off a bitcast if we got one back.
257959d1ed5bSDimitry Andric   if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2580f22ef01cSRoman Divacky     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2581f785676fSDimitry Andric            CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2582f785676fSDimitry Andric            // All zero index gep.
2583f22ef01cSRoman Divacky            CE->getOpcode() == llvm::Instruction::GetElementPtr);
2584f22ef01cSRoman Divacky     Entry = CE->getOperand(0);
2585f22ef01cSRoman Divacky   }
2586f22ef01cSRoman Divacky 
2587f22ef01cSRoman Divacky   // Entry is now either a Function or GlobalVariable.
258859d1ed5bSDimitry Andric   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
2589f22ef01cSRoman Divacky 
2590f22ef01cSRoman Divacky   // We have a definition after a declaration with the wrong type.
2591f22ef01cSRoman Divacky   // We must make a new GlobalVariable* and update everything that used OldGV
2592f22ef01cSRoman Divacky   // (a declaration or tentative definition) with the new GlobalVariable*
2593f22ef01cSRoman Divacky   // (which will be a definition).
2594f22ef01cSRoman Divacky   //
2595f22ef01cSRoman Divacky   // This happens if there is a prototype for a global (e.g.
2596f22ef01cSRoman Divacky   // "extern int x[];") and then a definition of a different type (e.g.
2597f22ef01cSRoman Divacky   // "int x[10];"). This also happens when an initializer has a different type
2598f22ef01cSRoman Divacky   // from the type of the global (this happens with unions).
259959d1ed5bSDimitry Andric   if (!GV ||
2600f22ef01cSRoman Divacky       GV->getType()->getElementType() != InitType ||
26013b0f4066SDimitry Andric       GV->getType()->getAddressSpace() !=
26027ae0e2c9SDimitry Andric        GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
2603f22ef01cSRoman Divacky 
2604f22ef01cSRoman Divacky     // Move the old entry aside so that we'll create a new one.
26056122f3e6SDimitry Andric     Entry->setName(StringRef());
2606f22ef01cSRoman Divacky 
2607f22ef01cSRoman Divacky     // Make a new global with the correct type, this is now guaranteed to work.
2608e7145dcbSDimitry Andric     GV = cast<llvm::GlobalVariable>(
260944290647SDimitry Andric         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
2610f22ef01cSRoman Divacky 
2611f22ef01cSRoman Divacky     // Replace all uses of the old global with the new global
2612f22ef01cSRoman Divacky     llvm::Constant *NewPtrForOldDecl =
2613f22ef01cSRoman Divacky         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2614f22ef01cSRoman Divacky     Entry->replaceAllUsesWith(NewPtrForOldDecl);
2615f22ef01cSRoman Divacky 
2616f22ef01cSRoman Divacky     // Erase the old global, since it is no longer used.
2617f22ef01cSRoman Divacky     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2618f22ef01cSRoman Divacky   }
2619f22ef01cSRoman Divacky 
2620284c1978SDimitry Andric   MaybeHandleStaticInExternC(D, GV);
2621284c1978SDimitry Andric 
26226122f3e6SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
26236122f3e6SDimitry Andric     AddGlobalAnnotations(D, GV);
2624f22ef01cSRoman Divacky 
2625e7145dcbSDimitry Andric   // Set the llvm linkage type as appropriate.
2626e7145dcbSDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
2627e7145dcbSDimitry Andric       getLLVMLinkageVarDefinition(D, GV->isConstant());
2628e7145dcbSDimitry Andric 
26290623d748SDimitry Andric   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
26300623d748SDimitry Andric   // the device. [...]"
26310623d748SDimitry Andric   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
26320623d748SDimitry Andric   // __device__, declares a variable that: [...]
26330623d748SDimitry Andric   // Is accessible from all the threads within the grid and from the host
26340623d748SDimitry Andric   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
26350623d748SDimitry Andric   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
2636e7145dcbSDimitry Andric   if (GV && LangOpts.CUDA) {
2637e7145dcbSDimitry Andric     if (LangOpts.CUDAIsDevice) {
2638e7145dcbSDimitry Andric       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
26390623d748SDimitry Andric         GV->setExternallyInitialized(true);
2640e7145dcbSDimitry Andric     } else {
2641e7145dcbSDimitry Andric       // Host-side shadows of external declarations of device-side
2642e7145dcbSDimitry Andric       // global variables become internal definitions. These have to
2643e7145dcbSDimitry Andric       // be internal in order to prevent name conflicts with global
2644e7145dcbSDimitry Andric       // host variables with the same name in a different TUs.
2645e7145dcbSDimitry Andric       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
2646e7145dcbSDimitry Andric         Linkage = llvm::GlobalValue::InternalLinkage;
2647e7145dcbSDimitry Andric 
2648e7145dcbSDimitry Andric         // Shadow variables and their properties must be registered
2649e7145dcbSDimitry Andric         // with CUDA runtime.
2650e7145dcbSDimitry Andric         unsigned Flags = 0;
2651e7145dcbSDimitry Andric         if (!D->hasDefinition())
2652e7145dcbSDimitry Andric           Flags |= CGCUDARuntime::ExternDeviceVar;
2653e7145dcbSDimitry Andric         if (D->hasAttr<CUDAConstantAttr>())
2654e7145dcbSDimitry Andric           Flags |= CGCUDARuntime::ConstantDeviceVar;
2655e7145dcbSDimitry Andric         getCUDARuntime().registerDeviceVar(*GV, Flags);
2656e7145dcbSDimitry Andric       } else if (D->hasAttr<CUDASharedAttr>())
2657e7145dcbSDimitry Andric         // __shared__ variables are odd. Shadows do get created, but
2658e7145dcbSDimitry Andric         // they are not registered with the CUDA runtime, so they
2659e7145dcbSDimitry Andric         // can't really be used to access their device-side
2660e7145dcbSDimitry Andric         // counterparts. It's not clear yet whether it's nvcc's bug or
2661e7145dcbSDimitry Andric         // a feature, but we've got to do the same for compatibility.
2662e7145dcbSDimitry Andric         Linkage = llvm::GlobalValue::InternalLinkage;
2663e7145dcbSDimitry Andric     }
26640623d748SDimitry Andric   }
2665f22ef01cSRoman Divacky   GV->setInitializer(Init);
2666f22ef01cSRoman Divacky 
2667f22ef01cSRoman Divacky   // If it is safe to mark the global 'constant', do so now.
2668dff0c46cSDimitry Andric   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2669dff0c46cSDimitry Andric                   isTypeConstant(D->getType(), true));
2670f22ef01cSRoman Divacky 
267139d628a0SDimitry Andric   // If it is in a read-only section, mark it 'constant'.
267239d628a0SDimitry Andric   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
267339d628a0SDimitry Andric     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
267439d628a0SDimitry Andric     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
267539d628a0SDimitry Andric       GV->setConstant(true);
267639d628a0SDimitry Andric   }
267739d628a0SDimitry Andric 
2678f22ef01cSRoman Divacky   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2679f22ef01cSRoman Divacky 
2680f785676fSDimitry Andric 
26810623d748SDimitry Andric   // On Darwin, if the normal linkage of a C++ thread_local variable is
26820623d748SDimitry Andric   // LinkOnce or Weak, we keep the normal linkage to prevent multiple
26830623d748SDimitry Andric   // copies within a linkage unit; otherwise, the backing variable has
26840623d748SDimitry Andric   // internal linkage and all accesses should just be calls to the
268559d1ed5bSDimitry Andric   // Itanium-specified entry point, which has the normal linkage of the
26860623d748SDimitry Andric   // variable. This is to preserve the ability to change the implementation
26870623d748SDimitry Andric   // behind the scenes.
268839d628a0SDimitry Andric   if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
26890623d748SDimitry Andric       Context.getTargetInfo().getTriple().isOSDarwin() &&
26900623d748SDimitry Andric       !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
26910623d748SDimitry Andric       !llvm::GlobalVariable::isWeakLinkage(Linkage))
269259d1ed5bSDimitry Andric     Linkage = llvm::GlobalValue::InternalLinkage;
269359d1ed5bSDimitry Andric 
269459d1ed5bSDimitry Andric   GV->setLinkage(Linkage);
269559d1ed5bSDimitry Andric   if (D->hasAttr<DLLImportAttr>())
269659d1ed5bSDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
269759d1ed5bSDimitry Andric   else if (D->hasAttr<DLLExportAttr>())
269859d1ed5bSDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
269939d628a0SDimitry Andric   else
270039d628a0SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2701f785676fSDimitry Andric 
270244290647SDimitry Andric   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
2703f22ef01cSRoman Divacky     // common vars aren't constant even if declared const.
2704f22ef01cSRoman Divacky     GV->setConstant(false);
270544290647SDimitry Andric     // Tentative definition of global variables may be initialized with
270644290647SDimitry Andric     // non-zero null pointers. In this case they should have weak linkage
270744290647SDimitry Andric     // since common linkage must have zero initializer and must not have
270844290647SDimitry Andric     // explicit section therefore cannot have non-zero initial value.
270944290647SDimitry Andric     if (!GV->getInitializer()->isNullValue())
271044290647SDimitry Andric       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
271144290647SDimitry Andric   }
2712f22ef01cSRoman Divacky 
271359d1ed5bSDimitry Andric   setNonAliasAttributes(D, GV);
2714f22ef01cSRoman Divacky 
271539d628a0SDimitry Andric   if (D->getTLSKind() && !GV->isThreadLocal()) {
271639d628a0SDimitry Andric     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
27170623d748SDimitry Andric       CXXThreadLocals.push_back(D);
271839d628a0SDimitry Andric     setTLSMode(GV, *D);
271939d628a0SDimitry Andric   }
272039d628a0SDimitry Andric 
272133956c43SDimitry Andric   maybeSetTrivialComdat(*D, *GV);
272233956c43SDimitry Andric 
27232754fe60SDimitry Andric   // Emit the initializer function if necessary.
2724dff0c46cSDimitry Andric   if (NeedsGlobalCtor || NeedsGlobalDtor)
2725dff0c46cSDimitry Andric     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
27262754fe60SDimitry Andric 
272739d628a0SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
27283861d79fSDimitry Andric 
2729f22ef01cSRoman Divacky   // Emit global variable debug information.
27306122f3e6SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
2731e7145dcbSDimitry Andric     if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
2732f22ef01cSRoman Divacky       DI->EmitGlobalVariable(GV, D);
2733f22ef01cSRoman Divacky }
2734f22ef01cSRoman Divacky 
273539d628a0SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context,
273633956c43SDimitry Andric                                       CodeGenModule &CGM, const VarDecl *D,
273733956c43SDimitry Andric                                       bool NoCommon) {
273859d1ed5bSDimitry Andric   // Don't give variables common linkage if -fno-common was specified unless it
273959d1ed5bSDimitry Andric   // was overridden by a NoCommon attribute.
274059d1ed5bSDimitry Andric   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
274159d1ed5bSDimitry Andric     return true;
274259d1ed5bSDimitry Andric 
274359d1ed5bSDimitry Andric   // C11 6.9.2/2:
274459d1ed5bSDimitry Andric   //   A declaration of an identifier for an object that has file scope without
274559d1ed5bSDimitry Andric   //   an initializer, and without a storage-class specifier or with the
274659d1ed5bSDimitry Andric   //   storage-class specifier static, constitutes a tentative definition.
274759d1ed5bSDimitry Andric   if (D->getInit() || D->hasExternalStorage())
274859d1ed5bSDimitry Andric     return true;
274959d1ed5bSDimitry Andric 
275059d1ed5bSDimitry Andric   // A variable cannot be both common and exist in a section.
275159d1ed5bSDimitry Andric   if (D->hasAttr<SectionAttr>())
275259d1ed5bSDimitry Andric     return true;
275359d1ed5bSDimitry Andric 
275459d1ed5bSDimitry Andric   // Thread local vars aren't considered common linkage.
275559d1ed5bSDimitry Andric   if (D->getTLSKind())
275659d1ed5bSDimitry Andric     return true;
275759d1ed5bSDimitry Andric 
275859d1ed5bSDimitry Andric   // Tentative definitions marked with WeakImportAttr are true definitions.
275959d1ed5bSDimitry Andric   if (D->hasAttr<WeakImportAttr>())
276059d1ed5bSDimitry Andric     return true;
276159d1ed5bSDimitry Andric 
276233956c43SDimitry Andric   // A variable cannot be both common and exist in a comdat.
276333956c43SDimitry Andric   if (shouldBeInCOMDAT(CGM, *D))
276433956c43SDimitry Andric     return true;
276533956c43SDimitry Andric 
2766e7145dcbSDimitry Andric   // Declarations with a required alignment do not have common linkage in MSVC
276739d628a0SDimitry Andric   // mode.
27680623d748SDimitry Andric   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
276933956c43SDimitry Andric     if (D->hasAttr<AlignedAttr>())
277039d628a0SDimitry Andric       return true;
277133956c43SDimitry Andric     QualType VarType = D->getType();
277233956c43SDimitry Andric     if (Context.isAlignmentRequired(VarType))
277333956c43SDimitry Andric       return true;
277433956c43SDimitry Andric 
277533956c43SDimitry Andric     if (const auto *RT = VarType->getAs<RecordType>()) {
277633956c43SDimitry Andric       const RecordDecl *RD = RT->getDecl();
277733956c43SDimitry Andric       for (const FieldDecl *FD : RD->fields()) {
277833956c43SDimitry Andric         if (FD->isBitField())
277933956c43SDimitry Andric           continue;
278033956c43SDimitry Andric         if (FD->hasAttr<AlignedAttr>())
278133956c43SDimitry Andric           return true;
278233956c43SDimitry Andric         if (Context.isAlignmentRequired(FD->getType()))
278333956c43SDimitry Andric           return true;
278433956c43SDimitry Andric       }
278533956c43SDimitry Andric     }
278633956c43SDimitry Andric   }
278739d628a0SDimitry Andric 
278859d1ed5bSDimitry Andric   return false;
278959d1ed5bSDimitry Andric }
279059d1ed5bSDimitry Andric 
279159d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
279259d1ed5bSDimitry Andric     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
27932754fe60SDimitry Andric   if (Linkage == GVA_Internal)
27942754fe60SDimitry Andric     return llvm::Function::InternalLinkage;
279559d1ed5bSDimitry Andric 
279659d1ed5bSDimitry Andric   if (D->hasAttr<WeakAttr>()) {
279759d1ed5bSDimitry Andric     if (IsConstantVariable)
279859d1ed5bSDimitry Andric       return llvm::GlobalVariable::WeakODRLinkage;
279959d1ed5bSDimitry Andric     else
280059d1ed5bSDimitry Andric       return llvm::GlobalVariable::WeakAnyLinkage;
280159d1ed5bSDimitry Andric   }
280259d1ed5bSDimitry Andric 
280359d1ed5bSDimitry Andric   // We are guaranteed to have a strong definition somewhere else,
280459d1ed5bSDimitry Andric   // so we can use available_externally linkage.
280559d1ed5bSDimitry Andric   if (Linkage == GVA_AvailableExternally)
280659d1ed5bSDimitry Andric     return llvm::Function::AvailableExternallyLinkage;
280759d1ed5bSDimitry Andric 
280859d1ed5bSDimitry Andric   // Note that Apple's kernel linker doesn't support symbol
280959d1ed5bSDimitry Andric   // coalescing, so we need to avoid linkonce and weak linkages there.
281059d1ed5bSDimitry Andric   // Normally, this means we just map to internal, but for explicit
281159d1ed5bSDimitry Andric   // instantiations we'll map to external.
281259d1ed5bSDimitry Andric 
281359d1ed5bSDimitry Andric   // In C++, the compiler has to emit a definition in every translation unit
281459d1ed5bSDimitry Andric   // that references the function.  We should use linkonce_odr because
281559d1ed5bSDimitry Andric   // a) if all references in this translation unit are optimized away, we
281659d1ed5bSDimitry Andric   // don't need to codegen it.  b) if the function persists, it needs to be
281759d1ed5bSDimitry Andric   // merged with other definitions. c) C++ has the ODR, so we know the
281859d1ed5bSDimitry Andric   // definition is dependable.
281959d1ed5bSDimitry Andric   if (Linkage == GVA_DiscardableODR)
282059d1ed5bSDimitry Andric     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
282159d1ed5bSDimitry Andric                                             : llvm::Function::InternalLinkage;
282259d1ed5bSDimitry Andric 
282359d1ed5bSDimitry Andric   // An explicit instantiation of a template has weak linkage, since
282459d1ed5bSDimitry Andric   // explicit instantiations can occur in multiple translation units
282559d1ed5bSDimitry Andric   // and must all be equivalent. However, we are not allowed to
282659d1ed5bSDimitry Andric   // throw away these explicit instantiations.
2827e7145dcbSDimitry Andric   //
2828e7145dcbSDimitry Andric   // We don't currently support CUDA device code spread out across multiple TUs,
2829e7145dcbSDimitry Andric   // so say that CUDA templates are either external (for kernels) or internal.
2830e7145dcbSDimitry Andric   // This lets llvm perform aggressive inter-procedural optimizations.
2831e7145dcbSDimitry Andric   if (Linkage == GVA_StrongODR) {
2832e7145dcbSDimitry Andric     if (Context.getLangOpts().AppleKext)
2833e7145dcbSDimitry Andric       return llvm::Function::ExternalLinkage;
2834e7145dcbSDimitry Andric     if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
2835e7145dcbSDimitry Andric       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
2836e7145dcbSDimitry Andric                                           : llvm::Function::InternalLinkage;
2837e7145dcbSDimitry Andric     return llvm::Function::WeakODRLinkage;
2838e7145dcbSDimitry Andric   }
283959d1ed5bSDimitry Andric 
284059d1ed5bSDimitry Andric   // C++ doesn't have tentative definitions and thus cannot have common
284159d1ed5bSDimitry Andric   // linkage.
284259d1ed5bSDimitry Andric   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
284333956c43SDimitry Andric       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
284439d628a0SDimitry Andric                                  CodeGenOpts.NoCommon))
284559d1ed5bSDimitry Andric     return llvm::GlobalVariable::CommonLinkage;
284659d1ed5bSDimitry Andric 
2847f785676fSDimitry Andric   // selectany symbols are externally visible, so use weak instead of
2848f785676fSDimitry Andric   // linkonce.  MSVC optimizes away references to const selectany globals, so
2849f785676fSDimitry Andric   // all definitions should be the same and ODR linkage should be used.
2850f785676fSDimitry Andric   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
285159d1ed5bSDimitry Andric   if (D->hasAttr<SelectAnyAttr>())
2852f785676fSDimitry Andric     return llvm::GlobalVariable::WeakODRLinkage;
285359d1ed5bSDimitry Andric 
285459d1ed5bSDimitry Andric   // Otherwise, we have strong external linkage.
285559d1ed5bSDimitry Andric   assert(Linkage == GVA_StrongExternal);
28562754fe60SDimitry Andric   return llvm::GlobalVariable::ExternalLinkage;
28572754fe60SDimitry Andric }
28582754fe60SDimitry Andric 
285959d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
286059d1ed5bSDimitry Andric     const VarDecl *VD, bool IsConstant) {
286159d1ed5bSDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
286259d1ed5bSDimitry Andric   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
286359d1ed5bSDimitry Andric }
286459d1ed5bSDimitry Andric 
2865139f7f9bSDimitry Andric /// Replace the uses of a function that was declared with a non-proto type.
2866139f7f9bSDimitry Andric /// We want to silently drop extra arguments from call sites
2867139f7f9bSDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2868139f7f9bSDimitry Andric                                           llvm::Function *newFn) {
2869139f7f9bSDimitry Andric   // Fast path.
2870139f7f9bSDimitry Andric   if (old->use_empty()) return;
2871139f7f9bSDimitry Andric 
2872139f7f9bSDimitry Andric   llvm::Type *newRetTy = newFn->getReturnType();
2873139f7f9bSDimitry Andric   SmallVector<llvm::Value*, 4> newArgs;
28740623d748SDimitry Andric   SmallVector<llvm::OperandBundleDef, 1> newBundles;
2875139f7f9bSDimitry Andric 
2876139f7f9bSDimitry Andric   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2877139f7f9bSDimitry Andric          ui != ue; ) {
2878139f7f9bSDimitry Andric     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
287959d1ed5bSDimitry Andric     llvm::User *user = use->getUser();
2880139f7f9bSDimitry Andric 
2881139f7f9bSDimitry Andric     // Recognize and replace uses of bitcasts.  Most calls to
2882139f7f9bSDimitry Andric     // unprototyped functions will use bitcasts.
288359d1ed5bSDimitry Andric     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
2884139f7f9bSDimitry Andric       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2885139f7f9bSDimitry Andric         replaceUsesOfNonProtoConstant(bitcast, newFn);
2886139f7f9bSDimitry Andric       continue;
2887139f7f9bSDimitry Andric     }
2888139f7f9bSDimitry Andric 
2889139f7f9bSDimitry Andric     // Recognize calls to the function.
2890139f7f9bSDimitry Andric     llvm::CallSite callSite(user);
2891139f7f9bSDimitry Andric     if (!callSite) continue;
289259d1ed5bSDimitry Andric     if (!callSite.isCallee(&*use)) continue;
2893139f7f9bSDimitry Andric 
2894139f7f9bSDimitry Andric     // If the return types don't match exactly, then we can't
2895139f7f9bSDimitry Andric     // transform this call unless it's dead.
2896139f7f9bSDimitry Andric     if (callSite->getType() != newRetTy && !callSite->use_empty())
2897139f7f9bSDimitry Andric       continue;
2898139f7f9bSDimitry Andric 
2899139f7f9bSDimitry Andric     // Get the call site's attribute list.
2900139f7f9bSDimitry Andric     SmallVector<llvm::AttributeSet, 8> newAttrs;
2901139f7f9bSDimitry Andric     llvm::AttributeSet oldAttrs = callSite.getAttributes();
2902139f7f9bSDimitry Andric 
2903139f7f9bSDimitry Andric     // Collect any return attributes from the call.
2904139f7f9bSDimitry Andric     if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
2905139f7f9bSDimitry Andric       newAttrs.push_back(
2906139f7f9bSDimitry Andric         llvm::AttributeSet::get(newFn->getContext(),
2907139f7f9bSDimitry Andric                                 oldAttrs.getRetAttributes()));
2908139f7f9bSDimitry Andric 
2909139f7f9bSDimitry Andric     // If the function was passed too few arguments, don't transform.
2910139f7f9bSDimitry Andric     unsigned newNumArgs = newFn->arg_size();
2911139f7f9bSDimitry Andric     if (callSite.arg_size() < newNumArgs) continue;
2912139f7f9bSDimitry Andric 
2913139f7f9bSDimitry Andric     // If extra arguments were passed, we silently drop them.
2914139f7f9bSDimitry Andric     // If any of the types mismatch, we don't transform.
2915139f7f9bSDimitry Andric     unsigned argNo = 0;
2916139f7f9bSDimitry Andric     bool dontTransform = false;
2917139f7f9bSDimitry Andric     for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
2918139f7f9bSDimitry Andric            ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
2919139f7f9bSDimitry Andric       if (callSite.getArgument(argNo)->getType() != ai->getType()) {
2920139f7f9bSDimitry Andric         dontTransform = true;
2921139f7f9bSDimitry Andric         break;
2922139f7f9bSDimitry Andric       }
2923139f7f9bSDimitry Andric 
2924139f7f9bSDimitry Andric       // Add any parameter attributes.
2925139f7f9bSDimitry Andric       if (oldAttrs.hasAttributes(argNo + 1))
2926139f7f9bSDimitry Andric         newAttrs.
2927139f7f9bSDimitry Andric           push_back(llvm::
2928139f7f9bSDimitry Andric                     AttributeSet::get(newFn->getContext(),
2929139f7f9bSDimitry Andric                                       oldAttrs.getParamAttributes(argNo + 1)));
2930139f7f9bSDimitry Andric     }
2931139f7f9bSDimitry Andric     if (dontTransform)
2932139f7f9bSDimitry Andric       continue;
2933139f7f9bSDimitry Andric 
2934139f7f9bSDimitry Andric     if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
2935139f7f9bSDimitry Andric       newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
2936139f7f9bSDimitry Andric                                                  oldAttrs.getFnAttributes()));
2937139f7f9bSDimitry Andric 
2938139f7f9bSDimitry Andric     // Okay, we can transform this.  Create the new call instruction and copy
2939139f7f9bSDimitry Andric     // over the required information.
2940139f7f9bSDimitry Andric     newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2941139f7f9bSDimitry Andric 
29420623d748SDimitry Andric     // Copy over any operand bundles.
29430623d748SDimitry Andric     callSite.getOperandBundlesAsDefs(newBundles);
29440623d748SDimitry Andric 
2945139f7f9bSDimitry Andric     llvm::CallSite newCall;
2946139f7f9bSDimitry Andric     if (callSite.isCall()) {
29470623d748SDimitry Andric       newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
2948139f7f9bSDimitry Andric                                        callSite.getInstruction());
2949139f7f9bSDimitry Andric     } else {
295059d1ed5bSDimitry Andric       auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
2951139f7f9bSDimitry Andric       newCall = llvm::InvokeInst::Create(newFn,
2952139f7f9bSDimitry Andric                                          oldInvoke->getNormalDest(),
2953139f7f9bSDimitry Andric                                          oldInvoke->getUnwindDest(),
29540623d748SDimitry Andric                                          newArgs, newBundles, "",
2955139f7f9bSDimitry Andric                                          callSite.getInstruction());
2956139f7f9bSDimitry Andric     }
2957139f7f9bSDimitry Andric     newArgs.clear(); // for the next iteration
2958139f7f9bSDimitry Andric 
2959139f7f9bSDimitry Andric     if (!newCall->getType()->isVoidTy())
2960139f7f9bSDimitry Andric       newCall->takeName(callSite.getInstruction());
2961139f7f9bSDimitry Andric     newCall.setAttributes(
2962139f7f9bSDimitry Andric                      llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2963139f7f9bSDimitry Andric     newCall.setCallingConv(callSite.getCallingConv());
2964139f7f9bSDimitry Andric 
2965139f7f9bSDimitry Andric     // Finally, remove the old call, replacing any uses with the new one.
2966139f7f9bSDimitry Andric     if (!callSite->use_empty())
2967139f7f9bSDimitry Andric       callSite->replaceAllUsesWith(newCall.getInstruction());
2968139f7f9bSDimitry Andric 
2969139f7f9bSDimitry Andric     // Copy debug location attached to CI.
297033956c43SDimitry Andric     if (callSite->getDebugLoc())
2971139f7f9bSDimitry Andric       newCall->setDebugLoc(callSite->getDebugLoc());
29720623d748SDimitry Andric 
2973139f7f9bSDimitry Andric     callSite->eraseFromParent();
2974139f7f9bSDimitry Andric   }
2975139f7f9bSDimitry Andric }
2976139f7f9bSDimitry Andric 
2977f22ef01cSRoman Divacky /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2978f22ef01cSRoman Divacky /// implement a function with no prototype, e.g. "int foo() {}".  If there are
2979f22ef01cSRoman Divacky /// existing call uses of the old function in the module, this adjusts them to
2980f22ef01cSRoman Divacky /// call the new function directly.
2981f22ef01cSRoman Divacky ///
2982f22ef01cSRoman Divacky /// This is not just a cleanup: the always_inline pass requires direct calls to
2983f22ef01cSRoman Divacky /// functions to be able to inline them.  If there is a bitcast in the way, it
2984f22ef01cSRoman Divacky /// won't inline them.  Instcombine normally deletes these calls, but it isn't
2985f22ef01cSRoman Divacky /// run at -O0.
2986f22ef01cSRoman Divacky static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2987f22ef01cSRoman Divacky                                                       llvm::Function *NewFn) {
2988f22ef01cSRoman Divacky   // If we're redefining a global as a function, don't transform it.
2989139f7f9bSDimitry Andric   if (!isa<llvm::Function>(Old)) return;
2990f22ef01cSRoman Divacky 
2991139f7f9bSDimitry Andric   replaceUsesOfNonProtoConstant(Old, NewFn);
2992f22ef01cSRoman Divacky }
2993f22ef01cSRoman Divacky 
2994dff0c46cSDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2995e7145dcbSDimitry Andric   auto DK = VD->isThisDeclarationADefinition();
2996e7145dcbSDimitry Andric   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
2997e7145dcbSDimitry Andric     return;
2998e7145dcbSDimitry Andric 
2999dff0c46cSDimitry Andric   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
3000dff0c46cSDimitry Andric   // If we have a definition, this might be a deferred decl. If the
3001dff0c46cSDimitry Andric   // instantiation is explicit, make sure we emit it at the end.
3002dff0c46cSDimitry Andric   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
3003dff0c46cSDimitry Andric     GetAddrOfGlobalVar(VD);
3004139f7f9bSDimitry Andric 
3005139f7f9bSDimitry Andric   EmitTopLevelDecl(VD);
3006dff0c46cSDimitry Andric }
3007f22ef01cSRoman Divacky 
300859d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
300959d1ed5bSDimitry Andric                                                  llvm::GlobalValue *GV) {
301059d1ed5bSDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
30113b0f4066SDimitry Andric 
30123b0f4066SDimitry Andric   // Compute the function info and LLVM type.
3013dff0c46cSDimitry Andric   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3014dff0c46cSDimitry Andric   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
30153b0f4066SDimitry Andric 
3016f22ef01cSRoman Divacky   // Get or create the prototype for the function.
30170623d748SDimitry Andric   if (!GV || (GV->getType()->getElementType() != Ty))
30180623d748SDimitry Andric     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
30190623d748SDimitry Andric                                                    /*DontDefer=*/true,
302044290647SDimitry Andric                                                    ForDefinition));
3021f22ef01cSRoman Divacky 
30220623d748SDimitry Andric   // Already emitted.
30230623d748SDimitry Andric   if (!GV->isDeclaration())
3024f785676fSDimitry Andric     return;
3025f22ef01cSRoman Divacky 
30262754fe60SDimitry Andric   // We need to set linkage and visibility on the function before
30272754fe60SDimitry Andric   // generating code for it because various parts of IR generation
30282754fe60SDimitry Andric   // want to propagate this information down (e.g. to local static
30292754fe60SDimitry Andric   // declarations).
303059d1ed5bSDimitry Andric   auto *Fn = cast<llvm::Function>(GV);
3031f785676fSDimitry Andric   setFunctionLinkage(GD, Fn);
303297bc6c73SDimitry Andric   setFunctionDLLStorageClass(GD, Fn);
3033f22ef01cSRoman Divacky 
303459d1ed5bSDimitry Andric   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
30352754fe60SDimitry Andric   setGlobalVisibility(Fn, D);
30362754fe60SDimitry Andric 
3037284c1978SDimitry Andric   MaybeHandleStaticInExternC(D, Fn);
3038284c1978SDimitry Andric 
303933956c43SDimitry Andric   maybeSetTrivialComdat(*D, *Fn);
304033956c43SDimitry Andric 
30413b0f4066SDimitry Andric   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
3042f22ef01cSRoman Divacky 
304359d1ed5bSDimitry Andric   setFunctionDefinitionAttributes(D, Fn);
3044f22ef01cSRoman Divacky   SetLLVMFunctionAttributesForDefinition(D, Fn);
3045f22ef01cSRoman Divacky 
3046f22ef01cSRoman Divacky   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
3047f22ef01cSRoman Divacky     AddGlobalCtor(Fn, CA->getPriority());
3048f22ef01cSRoman Divacky   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
3049f22ef01cSRoman Divacky     AddGlobalDtor(Fn, DA->getPriority());
30506122f3e6SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
30516122f3e6SDimitry Andric     AddGlobalAnnotations(D, Fn);
3052f22ef01cSRoman Divacky }
3053f22ef01cSRoman Divacky 
3054f22ef01cSRoman Divacky void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
305559d1ed5bSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
3056f22ef01cSRoman Divacky   const AliasAttr *AA = D->getAttr<AliasAttr>();
3057f22ef01cSRoman Divacky   assert(AA && "Not an alias?");
3058f22ef01cSRoman Divacky 
30596122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
3060f22ef01cSRoman Divacky 
30619a4b3118SDimitry Andric   if (AA->getAliasee() == MangledName) {
3062e7145dcbSDimitry Andric     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
30639a4b3118SDimitry Andric     return;
30649a4b3118SDimitry Andric   }
30659a4b3118SDimitry Andric 
3066f22ef01cSRoman Divacky   // If there is a definition in the module, then it wins over the alias.
3067f22ef01cSRoman Divacky   // This is dubious, but allow it to be safe.  Just ignore the alias.
3068f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3069f22ef01cSRoman Divacky   if (Entry && !Entry->isDeclaration())
3070f22ef01cSRoman Divacky     return;
3071f22ef01cSRoman Divacky 
3072f785676fSDimitry Andric   Aliases.push_back(GD);
3073f785676fSDimitry Andric 
30746122f3e6SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3075f22ef01cSRoman Divacky 
3076f22ef01cSRoman Divacky   // Create a reference to the named value.  This ensures that it is emitted
3077f22ef01cSRoman Divacky   // if a deferred decl.
3078f22ef01cSRoman Divacky   llvm::Constant *Aliasee;
3079f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(DeclTy))
30803861d79fSDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
30812754fe60SDimitry Andric                                       /*ForVTable=*/false);
3082f22ef01cSRoman Divacky   else
3083f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
308459d1ed5bSDimitry Andric                                     llvm::PointerType::getUnqual(DeclTy),
308539d628a0SDimitry Andric                                     /*D=*/nullptr);
3086f22ef01cSRoman Divacky 
3087f22ef01cSRoman Divacky   // Create the new alias itself, but don't set a name yet.
308859d1ed5bSDimitry Andric   auto *GA = llvm::GlobalAlias::create(
30890623d748SDimitry Andric       DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
3090f22ef01cSRoman Divacky 
3091f22ef01cSRoman Divacky   if (Entry) {
309259d1ed5bSDimitry Andric     if (GA->getAliasee() == Entry) {
3093e7145dcbSDimitry Andric       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
309459d1ed5bSDimitry Andric       return;
309559d1ed5bSDimitry Andric     }
309659d1ed5bSDimitry Andric 
3097f22ef01cSRoman Divacky     assert(Entry->isDeclaration());
3098f22ef01cSRoman Divacky 
3099f22ef01cSRoman Divacky     // If there is a declaration in the module, then we had an extern followed
3100f22ef01cSRoman Divacky     // by the alias, as in:
3101f22ef01cSRoman Divacky     //   extern int test6();
3102f22ef01cSRoman Divacky     //   ...
3103f22ef01cSRoman Divacky     //   int test6() __attribute__((alias("test7")));
3104f22ef01cSRoman Divacky     //
3105f22ef01cSRoman Divacky     // Remove it and replace uses of it with the alias.
3106f22ef01cSRoman Divacky     GA->takeName(Entry);
3107f22ef01cSRoman Divacky 
3108f22ef01cSRoman Divacky     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
3109f22ef01cSRoman Divacky                                                           Entry->getType()));
3110f22ef01cSRoman Divacky     Entry->eraseFromParent();
3111f22ef01cSRoman Divacky   } else {
3112ffd1746dSEd Schouten     GA->setName(MangledName);
3113f22ef01cSRoman Divacky   }
3114f22ef01cSRoman Divacky 
3115f22ef01cSRoman Divacky   // Set attributes which are particular to an alias; this is a
3116f22ef01cSRoman Divacky   // specialization of the attributes which may be set on a global
3117f22ef01cSRoman Divacky   // variable/function.
311839d628a0SDimitry Andric   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
31193b0f4066SDimitry Andric       D->isWeakImported()) {
3120f22ef01cSRoman Divacky     GA->setLinkage(llvm::Function::WeakAnyLinkage);
3121f22ef01cSRoman Divacky   }
3122f22ef01cSRoman Divacky 
312339d628a0SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
312439d628a0SDimitry Andric     if (VD->getTLSKind())
312539d628a0SDimitry Andric       setTLSMode(GA, *VD);
312639d628a0SDimitry Andric 
312739d628a0SDimitry Andric   setAliasAttributes(D, GA);
3128f22ef01cSRoman Divacky }
3129f22ef01cSRoman Divacky 
3130e7145dcbSDimitry Andric void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
3131e7145dcbSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
3132e7145dcbSDimitry Andric   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
3133e7145dcbSDimitry Andric   assert(IFA && "Not an ifunc?");
3134e7145dcbSDimitry Andric 
3135e7145dcbSDimitry Andric   StringRef MangledName = getMangledName(GD);
3136e7145dcbSDimitry Andric 
3137e7145dcbSDimitry Andric   if (IFA->getResolver() == MangledName) {
3138e7145dcbSDimitry Andric     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3139e7145dcbSDimitry Andric     return;
3140e7145dcbSDimitry Andric   }
3141e7145dcbSDimitry Andric 
3142e7145dcbSDimitry Andric   // Report an error if some definition overrides ifunc.
3143e7145dcbSDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3144e7145dcbSDimitry Andric   if (Entry && !Entry->isDeclaration()) {
3145e7145dcbSDimitry Andric     GlobalDecl OtherGD;
3146e7145dcbSDimitry Andric     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3147e7145dcbSDimitry Andric         DiagnosedConflictingDefinitions.insert(GD).second) {
3148e7145dcbSDimitry Andric       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
3149e7145dcbSDimitry Andric       Diags.Report(OtherGD.getDecl()->getLocation(),
3150e7145dcbSDimitry Andric                    diag::note_previous_definition);
3151e7145dcbSDimitry Andric     }
3152e7145dcbSDimitry Andric     return;
3153e7145dcbSDimitry Andric   }
3154e7145dcbSDimitry Andric 
3155e7145dcbSDimitry Andric   Aliases.push_back(GD);
3156e7145dcbSDimitry Andric 
3157e7145dcbSDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3158e7145dcbSDimitry Andric   llvm::Constant *Resolver =
3159e7145dcbSDimitry Andric       GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3160e7145dcbSDimitry Andric                               /*ForVTable=*/false);
3161e7145dcbSDimitry Andric   llvm::GlobalIFunc *GIF =
3162e7145dcbSDimitry Andric       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
3163e7145dcbSDimitry Andric                                 "", Resolver, &getModule());
3164e7145dcbSDimitry Andric   if (Entry) {
3165e7145dcbSDimitry Andric     if (GIF->getResolver() == Entry) {
3166e7145dcbSDimitry Andric       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3167e7145dcbSDimitry Andric       return;
3168e7145dcbSDimitry Andric     }
3169e7145dcbSDimitry Andric     assert(Entry->isDeclaration());
3170e7145dcbSDimitry Andric 
3171e7145dcbSDimitry Andric     // If there is a declaration in the module, then we had an extern followed
3172e7145dcbSDimitry Andric     // by the ifunc, as in:
3173e7145dcbSDimitry Andric     //   extern int test();
3174e7145dcbSDimitry Andric     //   ...
3175e7145dcbSDimitry Andric     //   int test() __attribute__((ifunc("resolver")));
3176e7145dcbSDimitry Andric     //
3177e7145dcbSDimitry Andric     // Remove it and replace uses of it with the ifunc.
3178e7145dcbSDimitry Andric     GIF->takeName(Entry);
3179e7145dcbSDimitry Andric 
3180e7145dcbSDimitry Andric     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3181e7145dcbSDimitry Andric                                                           Entry->getType()));
3182e7145dcbSDimitry Andric     Entry->eraseFromParent();
3183e7145dcbSDimitry Andric   } else
3184e7145dcbSDimitry Andric     GIF->setName(MangledName);
3185e7145dcbSDimitry Andric 
3186e7145dcbSDimitry Andric   SetCommonAttributes(D, GIF);
3187e7145dcbSDimitry Andric }
3188e7145dcbSDimitry Andric 
318917a519f9SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
31906122f3e6SDimitry Andric                                             ArrayRef<llvm::Type*> Tys) {
319117a519f9SDimitry Andric   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
319217a519f9SDimitry Andric                                          Tys);
3193f22ef01cSRoman Divacky }
3194f22ef01cSRoman Divacky 
319533956c43SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> &
319633956c43SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
319733956c43SDimitry Andric                          const StringLiteral *Literal, bool TargetIsLSB,
319833956c43SDimitry Andric                          bool &IsUTF16, unsigned &StringLength) {
31996122f3e6SDimitry Andric   StringRef String = Literal->getString();
3200e580952dSDimitry Andric   unsigned NumBytes = String.size();
3201f22ef01cSRoman Divacky 
3202f22ef01cSRoman Divacky   // Check for simple case.
3203f22ef01cSRoman Divacky   if (!Literal->containsNonAsciiOrNull()) {
3204f22ef01cSRoman Divacky     StringLength = NumBytes;
320539d628a0SDimitry Andric     return *Map.insert(std::make_pair(String, nullptr)).first;
3206f22ef01cSRoman Divacky   }
3207f22ef01cSRoman Divacky 
3208dff0c46cSDimitry Andric   // Otherwise, convert the UTF8 literals into a string of shorts.
3209dff0c46cSDimitry Andric   IsUTF16 = true;
3210dff0c46cSDimitry Andric 
321144290647SDimitry Andric   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
321244290647SDimitry Andric   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
321344290647SDimitry Andric   llvm::UTF16 *ToPtr = &ToBuf[0];
3214f22ef01cSRoman Divacky 
321544290647SDimitry Andric   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
321644290647SDimitry Andric                                  ToPtr + NumBytes, llvm::strictConversion);
3217f22ef01cSRoman Divacky 
3218f22ef01cSRoman Divacky   // ConvertUTF8toUTF16 returns the length in ToPtr.
3219f22ef01cSRoman Divacky   StringLength = ToPtr - &ToBuf[0];
3220f22ef01cSRoman Divacky 
3221dff0c46cSDimitry Andric   // Add an explicit null.
3222dff0c46cSDimitry Andric   *ToPtr = 0;
322339d628a0SDimitry Andric   return *Map.insert(std::make_pair(
322439d628a0SDimitry Andric                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
322539d628a0SDimitry Andric                                    (StringLength + 1) * 2),
322639d628a0SDimitry Andric                          nullptr)).first;
3227f22ef01cSRoman Divacky }
3228f22ef01cSRoman Divacky 
32290623d748SDimitry Andric ConstantAddress
3230f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
3231f22ef01cSRoman Divacky   unsigned StringLength = 0;
3232f22ef01cSRoman Divacky   bool isUTF16 = false;
323333956c43SDimitry Andric   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3234f22ef01cSRoman Divacky       GetConstantCFStringEntry(CFConstantStringMap, Literal,
323533956c43SDimitry Andric                                getDataLayout().isLittleEndian(), isUTF16,
323633956c43SDimitry Andric                                StringLength);
3237f22ef01cSRoman Divacky 
323839d628a0SDimitry Andric   if (auto *C = Entry.second)
32390623d748SDimitry Andric     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
3240f22ef01cSRoman Divacky 
3241dff0c46cSDimitry Andric   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
3242f22ef01cSRoman Divacky   llvm::Constant *Zeros[] = { Zero, Zero };
3243f22ef01cSRoman Divacky 
3244f22ef01cSRoman Divacky   // If we don't already have it, get __CFConstantStringClassReference.
3245f22ef01cSRoman Divacky   if (!CFConstantStringClassRef) {
32466122f3e6SDimitry Andric     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
3247f22ef01cSRoman Divacky     Ty = llvm::ArrayType::get(Ty, 0);
3248e7145dcbSDimitry Andric     llvm::Constant *GV =
3249e7145dcbSDimitry Andric         CreateRuntimeVariable(Ty, "__CFConstantStringClassReference");
3250e7145dcbSDimitry Andric 
325144290647SDimitry Andric     if (getTriple().isOSBinFormatCOFF()) {
3252e7145dcbSDimitry Andric       IdentifierInfo &II = getContext().Idents.get(GV->getName());
3253e7145dcbSDimitry Andric       TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
3254e7145dcbSDimitry Andric       DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3255e7145dcbSDimitry Andric       llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
3256e7145dcbSDimitry Andric 
3257e7145dcbSDimitry Andric       const VarDecl *VD = nullptr;
3258e7145dcbSDimitry Andric       for (const auto &Result : DC->lookup(&II))
3259e7145dcbSDimitry Andric         if ((VD = dyn_cast<VarDecl>(Result)))
3260e7145dcbSDimitry Andric           break;
3261e7145dcbSDimitry Andric 
3262e7145dcbSDimitry Andric       if (!VD || !VD->hasAttr<DLLExportAttr>()) {
3263e7145dcbSDimitry Andric         CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3264e7145dcbSDimitry Andric         CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3265e7145dcbSDimitry Andric       } else {
3266e7145dcbSDimitry Andric         CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3267e7145dcbSDimitry Andric         CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3268e7145dcbSDimitry Andric       }
3269e7145dcbSDimitry Andric     }
3270e7145dcbSDimitry Andric 
3271f22ef01cSRoman Divacky     // Decay array -> ptr
327244290647SDimitry Andric     CFConstantStringClassRef =
327344290647SDimitry Andric         llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
3274e7145dcbSDimitry Andric   }
3275f22ef01cSRoman Divacky 
3276f22ef01cSRoman Divacky   QualType CFTy = getContext().getCFConstantStringType();
3277f22ef01cSRoman Divacky 
327859d1ed5bSDimitry Andric   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
3279f22ef01cSRoman Divacky 
328044290647SDimitry Andric   ConstantInitBuilder Builder(*this);
328144290647SDimitry Andric   auto Fields = Builder.beginStruct(STy);
3282f22ef01cSRoman Divacky 
3283f22ef01cSRoman Divacky   // Class pointer.
328444290647SDimitry Andric   Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
3285f22ef01cSRoman Divacky 
3286f22ef01cSRoman Divacky   // Flags.
328744290647SDimitry Andric   Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
3288f22ef01cSRoman Divacky 
3289f22ef01cSRoman Divacky   // String pointer.
329059d1ed5bSDimitry Andric   llvm::Constant *C = nullptr;
3291dff0c46cSDimitry Andric   if (isUTF16) {
32920623d748SDimitry Andric     auto Arr = llvm::makeArrayRef(
329339d628a0SDimitry Andric         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
329439d628a0SDimitry Andric         Entry.first().size() / 2);
3295dff0c46cSDimitry Andric     C = llvm::ConstantDataArray::get(VMContext, Arr);
3296dff0c46cSDimitry Andric   } else {
329739d628a0SDimitry Andric     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
3298dff0c46cSDimitry Andric   }
3299f22ef01cSRoman Divacky 
3300dff0c46cSDimitry Andric   // Note: -fwritable-strings doesn't make the backing store strings of
3301dff0c46cSDimitry Andric   // CFStrings writable. (See <rdar://problem/10657500>)
330259d1ed5bSDimitry Andric   auto *GV =
3303dff0c46cSDimitry Andric       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
330459d1ed5bSDimitry Andric                                llvm::GlobalValue::PrivateLinkage, C, ".str");
3305e7145dcbSDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3306284c1978SDimitry Andric   // Don't enforce the target's minimum global alignment, since the only use
3307284c1978SDimitry Andric   // of the string is via this class initializer.
3308e7145dcbSDimitry Andric   CharUnits Align = isUTF16
3309e7145dcbSDimitry Andric                         ? getContext().getTypeAlignInChars(getContext().ShortTy)
3310e7145dcbSDimitry Andric                         : getContext().getTypeAlignInChars(getContext().CharTy);
3311f22ef01cSRoman Divacky   GV->setAlignment(Align.getQuantity());
3312e7145dcbSDimitry Andric 
3313e7145dcbSDimitry Andric   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
3314e7145dcbSDimitry Andric   // Without it LLVM can merge the string with a non unnamed_addr one during
3315e7145dcbSDimitry Andric   // LTO.  Doing that changes the section it ends in, which surprises ld64.
331644290647SDimitry Andric   if (getTriple().isOSBinFormatMachO())
3317e7145dcbSDimitry Andric     GV->setSection(isUTF16 ? "__TEXT,__ustring"
3318e7145dcbSDimitry Andric                            : "__TEXT,__cstring,cstring_literals");
3319dff0c46cSDimitry Andric 
3320dff0c46cSDimitry Andric   // String.
332144290647SDimitry Andric   llvm::Constant *Str =
332233956c43SDimitry Andric       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3323f22ef01cSRoman Divacky 
3324dff0c46cSDimitry Andric   if (isUTF16)
3325dff0c46cSDimitry Andric     // Cast the UTF16 string to the correct type.
332644290647SDimitry Andric     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
332744290647SDimitry Andric   Fields.add(Str);
3328dff0c46cSDimitry Andric 
3329f22ef01cSRoman Divacky   // String length.
333044290647SDimitry Andric   auto Ty = getTypes().ConvertType(getContext().LongTy);
333144290647SDimitry Andric   Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
3332f22ef01cSRoman Divacky 
33330623d748SDimitry Andric   CharUnits Alignment = getPointerAlign();
33340623d748SDimitry Andric 
3335f22ef01cSRoman Divacky   // The struct.
333644290647SDimitry Andric   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
333744290647SDimitry Andric                                     /*isConstant=*/false,
333844290647SDimitry Andric                                     llvm::GlobalVariable::PrivateLinkage);
333944290647SDimitry Andric   switch (getTriple().getObjectFormat()) {
3340e7145dcbSDimitry Andric   case llvm::Triple::UnknownObjectFormat:
3341e7145dcbSDimitry Andric     llvm_unreachable("unknown file format");
3342e7145dcbSDimitry Andric   case llvm::Triple::COFF:
3343e7145dcbSDimitry Andric   case llvm::Triple::ELF:
3344e7145dcbSDimitry Andric     GV->setSection("cfstring");
3345e7145dcbSDimitry Andric     break;
3346e7145dcbSDimitry Andric   case llvm::Triple::MachO:
3347e7145dcbSDimitry Andric     GV->setSection("__DATA,__cfstring");
3348e7145dcbSDimitry Andric     break;
3349e7145dcbSDimitry Andric   }
335039d628a0SDimitry Andric   Entry.second = GV;
3351f22ef01cSRoman Divacky 
33520623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
3353f22ef01cSRoman Divacky }
3354f22ef01cSRoman Divacky 
33556122f3e6SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() {
33566122f3e6SDimitry Andric   if (ObjCFastEnumerationStateType.isNull()) {
335759d1ed5bSDimitry Andric     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
33586122f3e6SDimitry Andric     D->startDefinition();
33596122f3e6SDimitry Andric 
33606122f3e6SDimitry Andric     QualType FieldTypes[] = {
33616122f3e6SDimitry Andric       Context.UnsignedLongTy,
33626122f3e6SDimitry Andric       Context.getPointerType(Context.getObjCIdType()),
33636122f3e6SDimitry Andric       Context.getPointerType(Context.UnsignedLongTy),
33646122f3e6SDimitry Andric       Context.getConstantArrayType(Context.UnsignedLongTy,
33656122f3e6SDimitry Andric                            llvm::APInt(32, 5), ArrayType::Normal, 0)
33666122f3e6SDimitry Andric     };
33676122f3e6SDimitry Andric 
33686122f3e6SDimitry Andric     for (size_t i = 0; i < 4; ++i) {
33696122f3e6SDimitry Andric       FieldDecl *Field = FieldDecl::Create(Context,
33706122f3e6SDimitry Andric                                            D,
33716122f3e6SDimitry Andric                                            SourceLocation(),
337259d1ed5bSDimitry Andric                                            SourceLocation(), nullptr,
337359d1ed5bSDimitry Andric                                            FieldTypes[i], /*TInfo=*/nullptr,
337459d1ed5bSDimitry Andric                                            /*BitWidth=*/nullptr,
33756122f3e6SDimitry Andric                                            /*Mutable=*/false,
33767ae0e2c9SDimitry Andric                                            ICIS_NoInit);
33776122f3e6SDimitry Andric       Field->setAccess(AS_public);
33786122f3e6SDimitry Andric       D->addDecl(Field);
33796122f3e6SDimitry Andric     }
33806122f3e6SDimitry Andric 
33816122f3e6SDimitry Andric     D->completeDefinition();
33826122f3e6SDimitry Andric     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
33836122f3e6SDimitry Andric   }
33846122f3e6SDimitry Andric 
33856122f3e6SDimitry Andric   return ObjCFastEnumerationStateType;
33866122f3e6SDimitry Andric }
33876122f3e6SDimitry Andric 
3388dff0c46cSDimitry Andric llvm::Constant *
3389dff0c46cSDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
3390dff0c46cSDimitry Andric   assert(!E->getType()->isPointerType() && "Strings are always arrays");
3391f22ef01cSRoman Divacky 
3392dff0c46cSDimitry Andric   // Don't emit it as the address of the string, emit the string data itself
3393dff0c46cSDimitry Andric   // as an inline array.
3394dff0c46cSDimitry Andric   if (E->getCharByteWidth() == 1) {
3395dff0c46cSDimitry Andric     SmallString<64> Str(E->getString());
3396f22ef01cSRoman Divacky 
3397dff0c46cSDimitry Andric     // Resize the string to the right size, which is indicated by its type.
3398dff0c46cSDimitry Andric     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
3399dff0c46cSDimitry Andric     Str.resize(CAT->getSize().getZExtValue());
3400dff0c46cSDimitry Andric     return llvm::ConstantDataArray::getString(VMContext, Str, false);
34016122f3e6SDimitry Andric   }
3402f22ef01cSRoman Divacky 
340359d1ed5bSDimitry Andric   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
3404dff0c46cSDimitry Andric   llvm::Type *ElemTy = AType->getElementType();
3405dff0c46cSDimitry Andric   unsigned NumElements = AType->getNumElements();
3406f22ef01cSRoman Divacky 
3407dff0c46cSDimitry Andric   // Wide strings have either 2-byte or 4-byte elements.
3408dff0c46cSDimitry Andric   if (ElemTy->getPrimitiveSizeInBits() == 16) {
3409dff0c46cSDimitry Andric     SmallVector<uint16_t, 32> Elements;
3410dff0c46cSDimitry Andric     Elements.reserve(NumElements);
3411dff0c46cSDimitry Andric 
3412dff0c46cSDimitry Andric     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3413dff0c46cSDimitry Andric       Elements.push_back(E->getCodeUnit(i));
3414dff0c46cSDimitry Andric     Elements.resize(NumElements);
3415dff0c46cSDimitry Andric     return llvm::ConstantDataArray::get(VMContext, Elements);
3416dff0c46cSDimitry Andric   }
3417dff0c46cSDimitry Andric 
3418dff0c46cSDimitry Andric   assert(ElemTy->getPrimitiveSizeInBits() == 32);
3419dff0c46cSDimitry Andric   SmallVector<uint32_t, 32> Elements;
3420dff0c46cSDimitry Andric   Elements.reserve(NumElements);
3421dff0c46cSDimitry Andric 
3422dff0c46cSDimitry Andric   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3423dff0c46cSDimitry Andric     Elements.push_back(E->getCodeUnit(i));
3424dff0c46cSDimitry Andric   Elements.resize(NumElements);
3425dff0c46cSDimitry Andric   return llvm::ConstantDataArray::get(VMContext, Elements);
3426f22ef01cSRoman Divacky }
3427f22ef01cSRoman Divacky 
342859d1ed5bSDimitry Andric static llvm::GlobalVariable *
342959d1ed5bSDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
343059d1ed5bSDimitry Andric                       CodeGenModule &CGM, StringRef GlobalName,
34310623d748SDimitry Andric                       CharUnits Alignment) {
343259d1ed5bSDimitry Andric   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
343359d1ed5bSDimitry Andric   unsigned AddrSpace = 0;
343459d1ed5bSDimitry Andric   if (CGM.getLangOpts().OpenCL)
343559d1ed5bSDimitry Andric     AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
3436dff0c46cSDimitry Andric 
343733956c43SDimitry Andric   llvm::Module &M = CGM.getModule();
343859d1ed5bSDimitry Andric   // Create a global variable for this string
343959d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
344033956c43SDimitry Andric       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
344133956c43SDimitry Andric       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
34420623d748SDimitry Andric   GV->setAlignment(Alignment.getQuantity());
3443e7145dcbSDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
344433956c43SDimitry Andric   if (GV->isWeakForLinker()) {
344533956c43SDimitry Andric     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
344633956c43SDimitry Andric     GV->setComdat(M.getOrInsertComdat(GV->getName()));
344733956c43SDimitry Andric   }
344833956c43SDimitry Andric 
344959d1ed5bSDimitry Andric   return GV;
3450f22ef01cSRoman Divacky }
3451dff0c46cSDimitry Andric 
345259d1ed5bSDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
345359d1ed5bSDimitry Andric /// constant array for the given string literal.
34540623d748SDimitry Andric ConstantAddress
345539d628a0SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
345639d628a0SDimitry Andric                                                   StringRef Name) {
34570623d748SDimitry Andric   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
3458dff0c46cSDimitry Andric 
345959d1ed5bSDimitry Andric   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
346059d1ed5bSDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
346159d1ed5bSDimitry Andric   if (!LangOpts.WritableStrings) {
346259d1ed5bSDimitry Andric     Entry = &ConstantStringMap[C];
346359d1ed5bSDimitry Andric     if (auto GV = *Entry) {
34640623d748SDimitry Andric       if (Alignment.getQuantity() > GV->getAlignment())
34650623d748SDimitry Andric         GV->setAlignment(Alignment.getQuantity());
34660623d748SDimitry Andric       return ConstantAddress(GV, Alignment);
346759d1ed5bSDimitry Andric     }
346859d1ed5bSDimitry Andric   }
346959d1ed5bSDimitry Andric 
347059d1ed5bSDimitry Andric   SmallString<256> MangledNameBuffer;
347159d1ed5bSDimitry Andric   StringRef GlobalVariableName;
347259d1ed5bSDimitry Andric   llvm::GlobalValue::LinkageTypes LT;
347359d1ed5bSDimitry Andric 
347459d1ed5bSDimitry Andric   // Mangle the string literal if the ABI allows for it.  However, we cannot
347559d1ed5bSDimitry Andric   // do this if  we are compiling with ASan or -fwritable-strings because they
347659d1ed5bSDimitry Andric   // rely on strings having normal linkage.
347739d628a0SDimitry Andric   if (!LangOpts.WritableStrings &&
347839d628a0SDimitry Andric       !LangOpts.Sanitize.has(SanitizerKind::Address) &&
347959d1ed5bSDimitry Andric       getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
348059d1ed5bSDimitry Andric     llvm::raw_svector_ostream Out(MangledNameBuffer);
348159d1ed5bSDimitry Andric     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
348259d1ed5bSDimitry Andric 
348359d1ed5bSDimitry Andric     LT = llvm::GlobalValue::LinkOnceODRLinkage;
348459d1ed5bSDimitry Andric     GlobalVariableName = MangledNameBuffer;
348559d1ed5bSDimitry Andric   } else {
348659d1ed5bSDimitry Andric     LT = llvm::GlobalValue::PrivateLinkage;
348739d628a0SDimitry Andric     GlobalVariableName = Name;
348859d1ed5bSDimitry Andric   }
348959d1ed5bSDimitry Andric 
349059d1ed5bSDimitry Andric   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
349159d1ed5bSDimitry Andric   if (Entry)
349259d1ed5bSDimitry Andric     *Entry = GV;
349359d1ed5bSDimitry Andric 
349439d628a0SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
349539d628a0SDimitry Andric                                   QualType());
34960623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
3497f22ef01cSRoman Divacky }
3498f22ef01cSRoman Divacky 
3499f22ef01cSRoman Divacky /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
3500f22ef01cSRoman Divacky /// array for the given ObjCEncodeExpr node.
35010623d748SDimitry Andric ConstantAddress
3502f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
3503f22ef01cSRoman Divacky   std::string Str;
3504f22ef01cSRoman Divacky   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
3505f22ef01cSRoman Divacky 
3506f22ef01cSRoman Divacky   return GetAddrOfConstantCString(Str);
3507f22ef01cSRoman Divacky }
3508f22ef01cSRoman Divacky 
350959d1ed5bSDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing
351059d1ed5bSDimitry Andric /// the literal and a terminating '\0' character.
351159d1ed5bSDimitry Andric /// The result has pointer to array type.
35120623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString(
35130623d748SDimitry Andric     const std::string &Str, const char *GlobalName) {
351459d1ed5bSDimitry Andric   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
35150623d748SDimitry Andric   CharUnits Alignment =
35160623d748SDimitry Andric     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
3517f22ef01cSRoman Divacky 
351859d1ed5bSDimitry Andric   llvm::Constant *C =
351959d1ed5bSDimitry Andric       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
352059d1ed5bSDimitry Andric 
352159d1ed5bSDimitry Andric   // Don't share any string literals if strings aren't constant.
352259d1ed5bSDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
352359d1ed5bSDimitry Andric   if (!LangOpts.WritableStrings) {
352459d1ed5bSDimitry Andric     Entry = &ConstantStringMap[C];
352559d1ed5bSDimitry Andric     if (auto GV = *Entry) {
35260623d748SDimitry Andric       if (Alignment.getQuantity() > GV->getAlignment())
35270623d748SDimitry Andric         GV->setAlignment(Alignment.getQuantity());
35280623d748SDimitry Andric       return ConstantAddress(GV, Alignment);
352959d1ed5bSDimitry Andric     }
353059d1ed5bSDimitry Andric   }
353159d1ed5bSDimitry Andric 
3532f22ef01cSRoman Divacky   // Get the default prefix if a name wasn't specified.
3533f22ef01cSRoman Divacky   if (!GlobalName)
3534f22ef01cSRoman Divacky     GlobalName = ".str";
3535f22ef01cSRoman Divacky   // Create a global variable for this.
353659d1ed5bSDimitry Andric   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
353759d1ed5bSDimitry Andric                                   GlobalName, Alignment);
353859d1ed5bSDimitry Andric   if (Entry)
353959d1ed5bSDimitry Andric     *Entry = GV;
35400623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
3541f22ef01cSRoman Divacky }
3542f22ef01cSRoman Divacky 
35430623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
3544f785676fSDimitry Andric     const MaterializeTemporaryExpr *E, const Expr *Init) {
3545f785676fSDimitry Andric   assert((E->getStorageDuration() == SD_Static ||
3546f785676fSDimitry Andric           E->getStorageDuration() == SD_Thread) && "not a global temporary");
354759d1ed5bSDimitry Andric   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
3548f785676fSDimitry Andric 
3549f785676fSDimitry Andric   // If we're not materializing a subobject of the temporary, keep the
3550f785676fSDimitry Andric   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
3551f785676fSDimitry Andric   QualType MaterializedType = Init->getType();
3552f785676fSDimitry Andric   if (Init == E->GetTemporaryExpr())
3553f785676fSDimitry Andric     MaterializedType = E->getType();
3554f785676fSDimitry Andric 
35550623d748SDimitry Andric   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
35560623d748SDimitry Andric 
35570623d748SDimitry Andric   if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
35580623d748SDimitry Andric     return ConstantAddress(Slot, Align);
3559f785676fSDimitry Andric 
3560f785676fSDimitry Andric   // FIXME: If an externally-visible declaration extends multiple temporaries,
3561f785676fSDimitry Andric   // we need to give each temporary the same name in every translation unit (and
3562f785676fSDimitry Andric   // we also need to make the temporaries externally-visible).
3563f785676fSDimitry Andric   SmallString<256> Name;
3564f785676fSDimitry Andric   llvm::raw_svector_ostream Out(Name);
356559d1ed5bSDimitry Andric   getCXXABI().getMangleContext().mangleReferenceTemporary(
356659d1ed5bSDimitry Andric       VD, E->getManglingNumber(), Out);
3567f785676fSDimitry Andric 
356859d1ed5bSDimitry Andric   APValue *Value = nullptr;
3569f785676fSDimitry Andric   if (E->getStorageDuration() == SD_Static) {
3570f785676fSDimitry Andric     // We might have a cached constant initializer for this temporary. Note
3571f785676fSDimitry Andric     // that this might have a different value from the value computed by
3572f785676fSDimitry Andric     // evaluating the initializer if the surrounding constant expression
3573f785676fSDimitry Andric     // modifies the temporary.
3574f785676fSDimitry Andric     Value = getContext().getMaterializedTemporaryValue(E, false);
3575f785676fSDimitry Andric     if (Value && Value->isUninit())
357659d1ed5bSDimitry Andric       Value = nullptr;
3577f785676fSDimitry Andric   }
3578f785676fSDimitry Andric 
3579f785676fSDimitry Andric   // Try evaluating it now, it might have a constant initializer.
3580f785676fSDimitry Andric   Expr::EvalResult EvalResult;
3581f785676fSDimitry Andric   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3582f785676fSDimitry Andric       !EvalResult.hasSideEffects())
3583f785676fSDimitry Andric     Value = &EvalResult.Val;
3584f785676fSDimitry Andric 
358559d1ed5bSDimitry Andric   llvm::Constant *InitialValue = nullptr;
3586f785676fSDimitry Andric   bool Constant = false;
3587f785676fSDimitry Andric   llvm::Type *Type;
3588f785676fSDimitry Andric   if (Value) {
3589f785676fSDimitry Andric     // The temporary has a constant initializer, use it.
359059d1ed5bSDimitry Andric     InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
3591f785676fSDimitry Andric     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3592f785676fSDimitry Andric     Type = InitialValue->getType();
3593f785676fSDimitry Andric   } else {
3594f785676fSDimitry Andric     // No initializer, the initialization will be provided when we
3595f785676fSDimitry Andric     // initialize the declaration which performed lifetime extension.
3596f785676fSDimitry Andric     Type = getTypes().ConvertTypeForMem(MaterializedType);
3597f785676fSDimitry Andric   }
3598f785676fSDimitry Andric 
3599f785676fSDimitry Andric   // Create a global variable for this lifetime-extended temporary.
360059d1ed5bSDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
360159d1ed5bSDimitry Andric       getLLVMLinkageVarDefinition(VD, Constant);
360233956c43SDimitry Andric   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
360333956c43SDimitry Andric     const VarDecl *InitVD;
360433956c43SDimitry Andric     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
360533956c43SDimitry Andric         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
360633956c43SDimitry Andric       // Temporaries defined inside a class get linkonce_odr linkage because the
360733956c43SDimitry Andric       // class can be defined in multipe translation units.
360833956c43SDimitry Andric       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
360933956c43SDimitry Andric     } else {
361033956c43SDimitry Andric       // There is no need for this temporary to have external linkage if the
361133956c43SDimitry Andric       // VarDecl has external linkage.
361233956c43SDimitry Andric       Linkage = llvm::GlobalVariable::InternalLinkage;
361333956c43SDimitry Andric     }
361433956c43SDimitry Andric   }
361559d1ed5bSDimitry Andric   unsigned AddrSpace = GetGlobalVarAddressSpace(
361659d1ed5bSDimitry Andric       VD, getContext().getTargetAddressSpace(MaterializedType));
361759d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
361859d1ed5bSDimitry Andric       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
361959d1ed5bSDimitry Andric       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
362059d1ed5bSDimitry Andric       AddrSpace);
362159d1ed5bSDimitry Andric   setGlobalVisibility(GV, VD);
36220623d748SDimitry Andric   GV->setAlignment(Align.getQuantity());
362333956c43SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker())
362433956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3625f785676fSDimitry Andric   if (VD->getTLSKind())
3626f785676fSDimitry Andric     setTLSMode(GV, *VD);
36270623d748SDimitry Andric   MaterializedGlobalTemporaryMap[E] = GV;
36280623d748SDimitry Andric   return ConstantAddress(GV, Align);
3629f785676fSDimitry Andric }
3630f785676fSDimitry Andric 
3631f22ef01cSRoman Divacky /// EmitObjCPropertyImplementations - Emit information for synthesized
3632f22ef01cSRoman Divacky /// properties for an implementation.
3633f22ef01cSRoman Divacky void CodeGenModule::EmitObjCPropertyImplementations(const
3634f22ef01cSRoman Divacky                                                     ObjCImplementationDecl *D) {
363559d1ed5bSDimitry Andric   for (const auto *PID : D->property_impls()) {
3636f22ef01cSRoman Divacky     // Dynamic is just for type-checking.
3637f22ef01cSRoman Divacky     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3638f22ef01cSRoman Divacky       ObjCPropertyDecl *PD = PID->getPropertyDecl();
3639f22ef01cSRoman Divacky 
3640f22ef01cSRoman Divacky       // Determine which methods need to be implemented, some may have
36413861d79fSDimitry Andric       // been overridden. Note that ::isPropertyAccessor is not the method
3642f22ef01cSRoman Divacky       // we want, that just indicates if the decl came from a
3643f22ef01cSRoman Divacky       // property. What we want to know is if the method is defined in
3644f22ef01cSRoman Divacky       // this implementation.
3645f22ef01cSRoman Divacky       if (!D->getInstanceMethod(PD->getGetterName()))
3646f22ef01cSRoman Divacky         CodeGenFunction(*this).GenerateObjCGetter(
3647f22ef01cSRoman Divacky                                  const_cast<ObjCImplementationDecl *>(D), PID);
3648f22ef01cSRoman Divacky       if (!PD->isReadOnly() &&
3649f22ef01cSRoman Divacky           !D->getInstanceMethod(PD->getSetterName()))
3650f22ef01cSRoman Divacky         CodeGenFunction(*this).GenerateObjCSetter(
3651f22ef01cSRoman Divacky                                  const_cast<ObjCImplementationDecl *>(D), PID);
3652f22ef01cSRoman Divacky     }
3653f22ef01cSRoman Divacky   }
3654f22ef01cSRoman Divacky }
3655f22ef01cSRoman Divacky 
36563b0f4066SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) {
36576122f3e6SDimitry Andric   const ObjCInterfaceDecl *iface = impl->getClassInterface();
36586122f3e6SDimitry Andric   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
36593b0f4066SDimitry Andric        ivar; ivar = ivar->getNextIvar())
36603b0f4066SDimitry Andric     if (ivar->getType().isDestructedType())
36613b0f4066SDimitry Andric       return true;
36623b0f4066SDimitry Andric 
36633b0f4066SDimitry Andric   return false;
36643b0f4066SDimitry Andric }
36653b0f4066SDimitry Andric 
366639d628a0SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM,
366739d628a0SDimitry Andric                                    ObjCImplementationDecl *D) {
366839d628a0SDimitry Andric   CodeGenFunction CGF(CGM);
366939d628a0SDimitry Andric   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
367039d628a0SDimitry Andric        E = D->init_end(); B != E; ++B) {
367139d628a0SDimitry Andric     CXXCtorInitializer *CtorInitExp = *B;
367239d628a0SDimitry Andric     Expr *Init = CtorInitExp->getInit();
367339d628a0SDimitry Andric     if (!CGF.isTrivialInitializer(Init))
367439d628a0SDimitry Andric       return false;
367539d628a0SDimitry Andric   }
367639d628a0SDimitry Andric   return true;
367739d628a0SDimitry Andric }
367839d628a0SDimitry Andric 
3679f22ef01cSRoman Divacky /// EmitObjCIvarInitializations - Emit information for ivar initialization
3680f22ef01cSRoman Divacky /// for an implementation.
3681f22ef01cSRoman Divacky void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
36823b0f4066SDimitry Andric   // We might need a .cxx_destruct even if we don't have any ivar initializers.
36833b0f4066SDimitry Andric   if (needsDestructMethod(D)) {
3684f22ef01cSRoman Divacky     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3685f22ef01cSRoman Divacky     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
36863b0f4066SDimitry Andric     ObjCMethodDecl *DTORMethod =
36873b0f4066SDimitry Andric       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
368859d1ed5bSDimitry Andric                              cxxSelector, getContext().VoidTy, nullptr, D,
36896122f3e6SDimitry Andric                              /*isInstance=*/true, /*isVariadic=*/false,
36903861d79fSDimitry Andric                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
36916122f3e6SDimitry Andric                              /*isDefined=*/false, ObjCMethodDecl::Required);
3692f22ef01cSRoman Divacky     D->addInstanceMethod(DTORMethod);
3693f22ef01cSRoman Divacky     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
36943861d79fSDimitry Andric     D->setHasDestructors(true);
36953b0f4066SDimitry Andric   }
3696f22ef01cSRoman Divacky 
36973b0f4066SDimitry Andric   // If the implementation doesn't have any ivar initializers, we don't need
36983b0f4066SDimitry Andric   // a .cxx_construct.
369939d628a0SDimitry Andric   if (D->getNumIvarInitializers() == 0 ||
370039d628a0SDimitry Andric       AllTrivialInitializers(*this, D))
37013b0f4066SDimitry Andric     return;
37023b0f4066SDimitry Andric 
37033b0f4066SDimitry Andric   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
37043b0f4066SDimitry Andric   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3705f22ef01cSRoman Divacky   // The constructor returns 'self'.
3706f22ef01cSRoman Divacky   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3707f22ef01cSRoman Divacky                                                 D->getLocation(),
37086122f3e6SDimitry Andric                                                 D->getLocation(),
37096122f3e6SDimitry Andric                                                 cxxSelector,
371059d1ed5bSDimitry Andric                                                 getContext().getObjCIdType(),
371159d1ed5bSDimitry Andric                                                 nullptr, D, /*isInstance=*/true,
37126122f3e6SDimitry Andric                                                 /*isVariadic=*/false,
37133861d79fSDimitry Andric                                                 /*isPropertyAccessor=*/true,
37146122f3e6SDimitry Andric                                                 /*isImplicitlyDeclared=*/true,
37156122f3e6SDimitry Andric                                                 /*isDefined=*/false,
3716f22ef01cSRoman Divacky                                                 ObjCMethodDecl::Required);
3717f22ef01cSRoman Divacky   D->addInstanceMethod(CTORMethod);
3718f22ef01cSRoman Divacky   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
37193861d79fSDimitry Andric   D->setHasNonZeroConstructors(true);
3720f22ef01cSRoman Divacky }
3721f22ef01cSRoman Divacky 
3722f22ef01cSRoman Divacky // EmitLinkageSpec - Emit all declarations in a linkage spec.
3723f22ef01cSRoman Divacky void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
3724f22ef01cSRoman Divacky   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3725f22ef01cSRoman Divacky       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
3726f22ef01cSRoman Divacky     ErrorUnsupported(LSD, "linkage spec");
3727f22ef01cSRoman Divacky     return;
3728f22ef01cSRoman Divacky   }
3729f22ef01cSRoman Divacky 
373044290647SDimitry Andric   EmitDeclContext(LSD);
373144290647SDimitry Andric }
373244290647SDimitry Andric 
373344290647SDimitry Andric void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
373444290647SDimitry Andric   for (auto *I : DC->decls()) {
373544290647SDimitry Andric     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
373644290647SDimitry Andric     // are themselves considered "top-level", so EmitTopLevelDecl on an
373744290647SDimitry Andric     // ObjCImplDecl does not recursively visit them. We need to do that in
373844290647SDimitry Andric     // case they're nested inside another construct (LinkageSpecDecl /
373944290647SDimitry Andric     // ExportDecl) that does stop them from being considered "top-level".
374059d1ed5bSDimitry Andric     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
374159d1ed5bSDimitry Andric       for (auto *M : OID->methods())
374259d1ed5bSDimitry Andric         EmitTopLevelDecl(M);
37433861d79fSDimitry Andric     }
374444290647SDimitry Andric 
374559d1ed5bSDimitry Andric     EmitTopLevelDecl(I);
3746f22ef01cSRoman Divacky   }
37473861d79fSDimitry Andric }
3748f22ef01cSRoman Divacky 
3749f22ef01cSRoman Divacky /// EmitTopLevelDecl - Emit code for a single top level declaration.
3750f22ef01cSRoman Divacky void CodeGenModule::EmitTopLevelDecl(Decl *D) {
3751f22ef01cSRoman Divacky   // Ignore dependent declarations.
3752f22ef01cSRoman Divacky   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3753f22ef01cSRoman Divacky     return;
3754f22ef01cSRoman Divacky 
3755f22ef01cSRoman Divacky   switch (D->getKind()) {
3756f22ef01cSRoman Divacky   case Decl::CXXConversion:
3757f22ef01cSRoman Divacky   case Decl::CXXMethod:
3758f22ef01cSRoman Divacky   case Decl::Function:
3759f22ef01cSRoman Divacky     // Skip function templates
37603b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
37613b0f4066SDimitry Andric         cast<FunctionDecl>(D)->isLateTemplateParsed())
3762f22ef01cSRoman Divacky       return;
3763f22ef01cSRoman Divacky 
3764f22ef01cSRoman Divacky     EmitGlobal(cast<FunctionDecl>(D));
376539d628a0SDimitry Andric     // Always provide some coverage mapping
376639d628a0SDimitry Andric     // even for the functions that aren't emitted.
376739d628a0SDimitry Andric     AddDeferredUnusedCoverageMapping(D);
3768f22ef01cSRoman Divacky     break;
3769f22ef01cSRoman Divacky 
3770f22ef01cSRoman Divacky   case Decl::Var:
377144290647SDimitry Andric   case Decl::Decomposition:
3772f785676fSDimitry Andric     // Skip variable templates
3773f785676fSDimitry Andric     if (cast<VarDecl>(D)->getDescribedVarTemplate())
3774f785676fSDimitry Andric       return;
3775f785676fSDimitry Andric   case Decl::VarTemplateSpecialization:
3776f22ef01cSRoman Divacky     EmitGlobal(cast<VarDecl>(D));
377744290647SDimitry Andric     if (auto *DD = dyn_cast<DecompositionDecl>(D))
377844290647SDimitry Andric       for (auto *B : DD->bindings())
377944290647SDimitry Andric         if (auto *HD = B->getHoldingVar())
378044290647SDimitry Andric           EmitGlobal(HD);
3781f22ef01cSRoman Divacky     break;
3782f22ef01cSRoman Divacky 
37833b0f4066SDimitry Andric   // Indirect fields from global anonymous structs and unions can be
37843b0f4066SDimitry Andric   // ignored; only the actual variable requires IR gen support.
37853b0f4066SDimitry Andric   case Decl::IndirectField:
37863b0f4066SDimitry Andric     break;
37873b0f4066SDimitry Andric 
3788f22ef01cSRoman Divacky   // C++ Decls
3789f22ef01cSRoman Divacky   case Decl::Namespace:
379044290647SDimitry Andric     EmitDeclContext(cast<NamespaceDecl>(D));
3791f22ef01cSRoman Divacky     break;
3792e7145dcbSDimitry Andric   case Decl::CXXRecord:
3793e7145dcbSDimitry Andric     // Emit any static data members, they may be definitions.
3794e7145dcbSDimitry Andric     for (auto *I : cast<CXXRecordDecl>(D)->decls())
3795e7145dcbSDimitry Andric       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
3796e7145dcbSDimitry Andric         EmitTopLevelDecl(I);
3797e7145dcbSDimitry Andric     break;
3798f22ef01cSRoman Divacky     // No code generation needed.
3799f22ef01cSRoman Divacky   case Decl::UsingShadow:
3800f22ef01cSRoman Divacky   case Decl::ClassTemplate:
3801f785676fSDimitry Andric   case Decl::VarTemplate:
3802f785676fSDimitry Andric   case Decl::VarTemplatePartialSpecialization:
3803f22ef01cSRoman Divacky   case Decl::FunctionTemplate:
3804bd5abe19SDimitry Andric   case Decl::TypeAliasTemplate:
3805bd5abe19SDimitry Andric   case Decl::Block:
3806139f7f9bSDimitry Andric   case Decl::Empty:
3807f22ef01cSRoman Divacky     break;
380859d1ed5bSDimitry Andric   case Decl::Using:          // using X; [C++]
380959d1ed5bSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
381059d1ed5bSDimitry Andric         DI->EmitUsingDecl(cast<UsingDecl>(*D));
381159d1ed5bSDimitry Andric     return;
3812f785676fSDimitry Andric   case Decl::NamespaceAlias:
3813f785676fSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
3814f785676fSDimitry Andric         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3815f785676fSDimitry Andric     return;
3816284c1978SDimitry Andric   case Decl::UsingDirective: // using namespace X; [C++]
3817284c1978SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
3818284c1978SDimitry Andric       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3819284c1978SDimitry Andric     return;
3820f22ef01cSRoman Divacky   case Decl::CXXConstructor:
3821f22ef01cSRoman Divacky     // Skip function templates
38223b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
38233b0f4066SDimitry Andric         cast<FunctionDecl>(D)->isLateTemplateParsed())
3824f22ef01cSRoman Divacky       return;
3825f22ef01cSRoman Divacky 
3826f785676fSDimitry Andric     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
3827f22ef01cSRoman Divacky     break;
3828f22ef01cSRoman Divacky   case Decl::CXXDestructor:
38293b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
38303b0f4066SDimitry Andric       return;
3831f785676fSDimitry Andric     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
3832f22ef01cSRoman Divacky     break;
3833f22ef01cSRoman Divacky 
3834f22ef01cSRoman Divacky   case Decl::StaticAssert:
3835f22ef01cSRoman Divacky     // Nothing to do.
3836f22ef01cSRoman Divacky     break;
3837f22ef01cSRoman Divacky 
3838f22ef01cSRoman Divacky   // Objective-C Decls
3839f22ef01cSRoman Divacky 
3840f22ef01cSRoman Divacky   // Forward declarations, no (immediate) code generation.
3841f22ef01cSRoman Divacky   case Decl::ObjCInterface:
38427ae0e2c9SDimitry Andric   case Decl::ObjCCategory:
3843f22ef01cSRoman Divacky     break;
3844f22ef01cSRoman Divacky 
3845dff0c46cSDimitry Andric   case Decl::ObjCProtocol: {
384659d1ed5bSDimitry Andric     auto *Proto = cast<ObjCProtocolDecl>(D);
3847dff0c46cSDimitry Andric     if (Proto->isThisDeclarationADefinition())
3848dff0c46cSDimitry Andric       ObjCRuntime->GenerateProtocol(Proto);
3849f22ef01cSRoman Divacky     break;
3850dff0c46cSDimitry Andric   }
3851f22ef01cSRoman Divacky 
3852f22ef01cSRoman Divacky   case Decl::ObjCCategoryImpl:
3853f22ef01cSRoman Divacky     // Categories have properties but don't support synthesize so we
3854f22ef01cSRoman Divacky     // can ignore them here.
38556122f3e6SDimitry Andric     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
3856f22ef01cSRoman Divacky     break;
3857f22ef01cSRoman Divacky 
3858f22ef01cSRoman Divacky   case Decl::ObjCImplementation: {
385959d1ed5bSDimitry Andric     auto *OMD = cast<ObjCImplementationDecl>(D);
3860f22ef01cSRoman Divacky     EmitObjCPropertyImplementations(OMD);
3861f22ef01cSRoman Divacky     EmitObjCIvarInitializations(OMD);
38626122f3e6SDimitry Andric     ObjCRuntime->GenerateClass(OMD);
3863dff0c46cSDimitry Andric     // Emit global variable debug information.
3864dff0c46cSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
3865e7145dcbSDimitry Andric       if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
3866139f7f9bSDimitry Andric         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3867139f7f9bSDimitry Andric             OMD->getClassInterface()), OMD->getLocation());
3868f22ef01cSRoman Divacky     break;
3869f22ef01cSRoman Divacky   }
3870f22ef01cSRoman Divacky   case Decl::ObjCMethod: {
387159d1ed5bSDimitry Andric     auto *OMD = cast<ObjCMethodDecl>(D);
3872f22ef01cSRoman Divacky     // If this is not a prototype, emit the body.
3873f22ef01cSRoman Divacky     if (OMD->getBody())
3874f22ef01cSRoman Divacky       CodeGenFunction(*this).GenerateObjCMethod(OMD);
3875f22ef01cSRoman Divacky     break;
3876f22ef01cSRoman Divacky   }
3877f22ef01cSRoman Divacky   case Decl::ObjCCompatibleAlias:
3878dff0c46cSDimitry Andric     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3879f22ef01cSRoman Divacky     break;
3880f22ef01cSRoman Divacky 
3881e7145dcbSDimitry Andric   case Decl::PragmaComment: {
3882e7145dcbSDimitry Andric     const auto *PCD = cast<PragmaCommentDecl>(D);
3883e7145dcbSDimitry Andric     switch (PCD->getCommentKind()) {
3884e7145dcbSDimitry Andric     case PCK_Unknown:
3885e7145dcbSDimitry Andric       llvm_unreachable("unexpected pragma comment kind");
3886e7145dcbSDimitry Andric     case PCK_Linker:
3887e7145dcbSDimitry Andric       AppendLinkerOptions(PCD->getArg());
3888e7145dcbSDimitry Andric       break;
3889e7145dcbSDimitry Andric     case PCK_Lib:
3890e7145dcbSDimitry Andric       AddDependentLib(PCD->getArg());
3891e7145dcbSDimitry Andric       break;
3892e7145dcbSDimitry Andric     case PCK_Compiler:
3893e7145dcbSDimitry Andric     case PCK_ExeStr:
3894e7145dcbSDimitry Andric     case PCK_User:
3895e7145dcbSDimitry Andric       break; // We ignore all of these.
3896e7145dcbSDimitry Andric     }
3897e7145dcbSDimitry Andric     break;
3898e7145dcbSDimitry Andric   }
3899e7145dcbSDimitry Andric 
3900e7145dcbSDimitry Andric   case Decl::PragmaDetectMismatch: {
3901e7145dcbSDimitry Andric     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
3902e7145dcbSDimitry Andric     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
3903e7145dcbSDimitry Andric     break;
3904e7145dcbSDimitry Andric   }
3905e7145dcbSDimitry Andric 
3906f22ef01cSRoman Divacky   case Decl::LinkageSpec:
3907f22ef01cSRoman Divacky     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
3908f22ef01cSRoman Divacky     break;
3909f22ef01cSRoman Divacky 
3910f22ef01cSRoman Divacky   case Decl::FileScopeAsm: {
391133956c43SDimitry Andric     // File-scope asm is ignored during device-side CUDA compilation.
391233956c43SDimitry Andric     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
391333956c43SDimitry Andric       break;
3914ea942507SDimitry Andric     // File-scope asm is ignored during device-side OpenMP compilation.
3915ea942507SDimitry Andric     if (LangOpts.OpenMPIsDevice)
3916ea942507SDimitry Andric       break;
391759d1ed5bSDimitry Andric     auto *AD = cast<FileScopeAsmDecl>(D);
391833956c43SDimitry Andric     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
3919f22ef01cSRoman Divacky     break;
3920f22ef01cSRoman Divacky   }
3921f22ef01cSRoman Divacky 
3922139f7f9bSDimitry Andric   case Decl::Import: {
392359d1ed5bSDimitry Andric     auto *Import = cast<ImportDecl>(D);
3924139f7f9bSDimitry Andric 
392544290647SDimitry Andric     // If we've already imported this module, we're done.
392644290647SDimitry Andric     if (!ImportedModules.insert(Import->getImportedModule()))
3927139f7f9bSDimitry Andric       break;
392844290647SDimitry Andric 
392944290647SDimitry Andric     // Emit debug information for direct imports.
393044290647SDimitry Andric     if (!Import->getImportedOwningModule()) {
39313dac3a9bSDimitry Andric       if (CGDebugInfo *DI = getModuleDebugInfo())
39323dac3a9bSDimitry Andric         DI->EmitImportDecl(*Import);
393344290647SDimitry Andric     }
3934139f7f9bSDimitry Andric 
393544290647SDimitry Andric     // Find all of the submodules and emit the module initializers.
393644290647SDimitry Andric     llvm::SmallPtrSet<clang::Module *, 16> Visited;
393744290647SDimitry Andric     SmallVector<clang::Module *, 16> Stack;
393844290647SDimitry Andric     Visited.insert(Import->getImportedModule());
393944290647SDimitry Andric     Stack.push_back(Import->getImportedModule());
394044290647SDimitry Andric 
394144290647SDimitry Andric     while (!Stack.empty()) {
394244290647SDimitry Andric       clang::Module *Mod = Stack.pop_back_val();
394344290647SDimitry Andric       if (!EmittedModuleInitializers.insert(Mod).second)
394444290647SDimitry Andric         continue;
394544290647SDimitry Andric 
394644290647SDimitry Andric       for (auto *D : Context.getModuleInitializers(Mod))
394744290647SDimitry Andric         EmitTopLevelDecl(D);
394844290647SDimitry Andric 
394944290647SDimitry Andric       // Visit the submodules of this module.
395044290647SDimitry Andric       for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
395144290647SDimitry Andric                                              SubEnd = Mod->submodule_end();
395244290647SDimitry Andric            Sub != SubEnd; ++Sub) {
395344290647SDimitry Andric         // Skip explicit children; they need to be explicitly imported to emit
395444290647SDimitry Andric         // the initializers.
395544290647SDimitry Andric         if ((*Sub)->IsExplicit)
395644290647SDimitry Andric           continue;
395744290647SDimitry Andric 
395844290647SDimitry Andric         if (Visited.insert(*Sub).second)
395944290647SDimitry Andric           Stack.push_back(*Sub);
396044290647SDimitry Andric       }
396144290647SDimitry Andric     }
3962139f7f9bSDimitry Andric     break;
3963139f7f9bSDimitry Andric   }
3964139f7f9bSDimitry Andric 
396544290647SDimitry Andric   case Decl::Export:
396644290647SDimitry Andric     EmitDeclContext(cast<ExportDecl>(D));
396744290647SDimitry Andric     break;
396844290647SDimitry Andric 
396939d628a0SDimitry Andric   case Decl::OMPThreadPrivate:
397039d628a0SDimitry Andric     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
397139d628a0SDimitry Andric     break;
397239d628a0SDimitry Andric 
397359d1ed5bSDimitry Andric   case Decl::ClassTemplateSpecialization: {
397459d1ed5bSDimitry Andric     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
397559d1ed5bSDimitry Andric     if (DebugInfo &&
397639d628a0SDimitry Andric         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
397739d628a0SDimitry Andric         Spec->hasDefinition())
397859d1ed5bSDimitry Andric       DebugInfo->completeTemplateDefinition(*Spec);
397939d628a0SDimitry Andric     break;
398059d1ed5bSDimitry Andric   }
398159d1ed5bSDimitry Andric 
3982e7145dcbSDimitry Andric   case Decl::OMPDeclareReduction:
3983e7145dcbSDimitry Andric     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
3984e7145dcbSDimitry Andric     break;
3985e7145dcbSDimitry Andric 
3986f22ef01cSRoman Divacky   default:
3987f22ef01cSRoman Divacky     // Make sure we handled everything we should, every other kind is a
3988f22ef01cSRoman Divacky     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
3989f22ef01cSRoman Divacky     // function. Need to recode Decl::Kind to do that easily.
3990f22ef01cSRoman Divacky     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
399139d628a0SDimitry Andric     break;
399239d628a0SDimitry Andric   }
399339d628a0SDimitry Andric }
399439d628a0SDimitry Andric 
399539d628a0SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
399639d628a0SDimitry Andric   // Do we need to generate coverage mapping?
399739d628a0SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
399839d628a0SDimitry Andric     return;
399939d628a0SDimitry Andric   switch (D->getKind()) {
400039d628a0SDimitry Andric   case Decl::CXXConversion:
400139d628a0SDimitry Andric   case Decl::CXXMethod:
400239d628a0SDimitry Andric   case Decl::Function:
400339d628a0SDimitry Andric   case Decl::ObjCMethod:
400439d628a0SDimitry Andric   case Decl::CXXConstructor:
400539d628a0SDimitry Andric   case Decl::CXXDestructor: {
40060623d748SDimitry Andric     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
400739d628a0SDimitry Andric       return;
400839d628a0SDimitry Andric     auto I = DeferredEmptyCoverageMappingDecls.find(D);
400939d628a0SDimitry Andric     if (I == DeferredEmptyCoverageMappingDecls.end())
401039d628a0SDimitry Andric       DeferredEmptyCoverageMappingDecls[D] = true;
401139d628a0SDimitry Andric     break;
401239d628a0SDimitry Andric   }
401339d628a0SDimitry Andric   default:
401439d628a0SDimitry Andric     break;
401539d628a0SDimitry Andric   };
401639d628a0SDimitry Andric }
401739d628a0SDimitry Andric 
401839d628a0SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
401939d628a0SDimitry Andric   // Do we need to generate coverage mapping?
402039d628a0SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
402139d628a0SDimitry Andric     return;
402239d628a0SDimitry Andric   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
402339d628a0SDimitry Andric     if (Fn->isTemplateInstantiation())
402439d628a0SDimitry Andric       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
402539d628a0SDimitry Andric   }
402639d628a0SDimitry Andric   auto I = DeferredEmptyCoverageMappingDecls.find(D);
402739d628a0SDimitry Andric   if (I == DeferredEmptyCoverageMappingDecls.end())
402839d628a0SDimitry Andric     DeferredEmptyCoverageMappingDecls[D] = false;
402939d628a0SDimitry Andric   else
403039d628a0SDimitry Andric     I->second = false;
403139d628a0SDimitry Andric }
403239d628a0SDimitry Andric 
403339d628a0SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
403439d628a0SDimitry Andric   std::vector<const Decl *> DeferredDecls;
403533956c43SDimitry Andric   for (const auto &I : DeferredEmptyCoverageMappingDecls) {
403639d628a0SDimitry Andric     if (!I.second)
403739d628a0SDimitry Andric       continue;
403839d628a0SDimitry Andric     DeferredDecls.push_back(I.first);
403939d628a0SDimitry Andric   }
404039d628a0SDimitry Andric   // Sort the declarations by their location to make sure that the tests get a
404139d628a0SDimitry Andric   // predictable order for the coverage mapping for the unused declarations.
404239d628a0SDimitry Andric   if (CodeGenOpts.DumpCoverageMapping)
404339d628a0SDimitry Andric     std::sort(DeferredDecls.begin(), DeferredDecls.end(),
404439d628a0SDimitry Andric               [] (const Decl *LHS, const Decl *RHS) {
404539d628a0SDimitry Andric       return LHS->getLocStart() < RHS->getLocStart();
404639d628a0SDimitry Andric     });
404739d628a0SDimitry Andric   for (const auto *D : DeferredDecls) {
404839d628a0SDimitry Andric     switch (D->getKind()) {
404939d628a0SDimitry Andric     case Decl::CXXConversion:
405039d628a0SDimitry Andric     case Decl::CXXMethod:
405139d628a0SDimitry Andric     case Decl::Function:
405239d628a0SDimitry Andric     case Decl::ObjCMethod: {
405339d628a0SDimitry Andric       CodeGenPGO PGO(*this);
405439d628a0SDimitry Andric       GlobalDecl GD(cast<FunctionDecl>(D));
405539d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
405639d628a0SDimitry Andric                                   getFunctionLinkage(GD));
405739d628a0SDimitry Andric       break;
405839d628a0SDimitry Andric     }
405939d628a0SDimitry Andric     case Decl::CXXConstructor: {
406039d628a0SDimitry Andric       CodeGenPGO PGO(*this);
406139d628a0SDimitry Andric       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
406239d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
406339d628a0SDimitry Andric                                   getFunctionLinkage(GD));
406439d628a0SDimitry Andric       break;
406539d628a0SDimitry Andric     }
406639d628a0SDimitry Andric     case Decl::CXXDestructor: {
406739d628a0SDimitry Andric       CodeGenPGO PGO(*this);
406839d628a0SDimitry Andric       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
406939d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
407039d628a0SDimitry Andric                                   getFunctionLinkage(GD));
407139d628a0SDimitry Andric       break;
407239d628a0SDimitry Andric     }
407339d628a0SDimitry Andric     default:
407439d628a0SDimitry Andric       break;
407539d628a0SDimitry Andric     };
4076f22ef01cSRoman Divacky   }
4077f22ef01cSRoman Divacky }
4078ffd1746dSEd Schouten 
4079ffd1746dSEd Schouten /// Turns the given pointer into a constant.
4080ffd1746dSEd Schouten static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
4081ffd1746dSEd Schouten                                           const void *Ptr) {
4082ffd1746dSEd Schouten   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
40836122f3e6SDimitry Andric   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
4084ffd1746dSEd Schouten   return llvm::ConstantInt::get(i64, PtrInt);
4085ffd1746dSEd Schouten }
4086ffd1746dSEd Schouten 
4087ffd1746dSEd Schouten static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
4088ffd1746dSEd Schouten                                    llvm::NamedMDNode *&GlobalMetadata,
4089ffd1746dSEd Schouten                                    GlobalDecl D,
4090ffd1746dSEd Schouten                                    llvm::GlobalValue *Addr) {
4091ffd1746dSEd Schouten   if (!GlobalMetadata)
4092ffd1746dSEd Schouten     GlobalMetadata =
4093ffd1746dSEd Schouten       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
4094ffd1746dSEd Schouten 
4095ffd1746dSEd Schouten   // TODO: should we report variant information for ctors/dtors?
409639d628a0SDimitry Andric   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
409739d628a0SDimitry Andric                            llvm::ConstantAsMetadata::get(GetPointerConstant(
409839d628a0SDimitry Andric                                CGM.getLLVMContext(), D.getDecl()))};
40993b0f4066SDimitry Andric   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
4100ffd1746dSEd Schouten }
4101ffd1746dSEd Schouten 
4102284c1978SDimitry Andric /// For each function which is declared within an extern "C" region and marked
4103284c1978SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled
4104284c1978SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer
4105284c1978SDimitry Andric /// to such functions with an unmangled name from inline assembly within the
4106284c1978SDimitry Andric /// same translation unit.
4107284c1978SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() {
4108e7145dcbSDimitry Andric   // Don't do anything if we're generating CUDA device code -- the NVPTX
4109e7145dcbSDimitry Andric   // assembly target doesn't support aliases.
4110e7145dcbSDimitry Andric   if (Context.getTargetInfo().getTriple().isNVPTX())
4111e7145dcbSDimitry Andric     return;
41128f0fd8f6SDimitry Andric   for (auto &I : StaticExternCValues) {
41138f0fd8f6SDimitry Andric     IdentifierInfo *Name = I.first;
41148f0fd8f6SDimitry Andric     llvm::GlobalValue *Val = I.second;
4115284c1978SDimitry Andric     if (Val && !getModule().getNamedValue(Name->getName()))
411659d1ed5bSDimitry Andric       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
4117284c1978SDimitry Andric   }
4118284c1978SDimitry Andric }
4119284c1978SDimitry Andric 
412059d1ed5bSDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
412159d1ed5bSDimitry Andric                                              GlobalDecl &Result) const {
412259d1ed5bSDimitry Andric   auto Res = Manglings.find(MangledName);
412359d1ed5bSDimitry Andric   if (Res == Manglings.end())
412459d1ed5bSDimitry Andric     return false;
412559d1ed5bSDimitry Andric   Result = Res->getValue();
412659d1ed5bSDimitry Andric   return true;
412759d1ed5bSDimitry Andric }
412859d1ed5bSDimitry Andric 
4129ffd1746dSEd Schouten /// Emits metadata nodes associating all the global values in the
4130ffd1746dSEd Schouten /// current module with the Decls they came from.  This is useful for
4131ffd1746dSEd Schouten /// projects using IR gen as a subroutine.
4132ffd1746dSEd Schouten ///
4133ffd1746dSEd Schouten /// Since there's currently no way to associate an MDNode directly
4134ffd1746dSEd Schouten /// with an llvm::GlobalValue, we create a global named metadata
4135ffd1746dSEd Schouten /// with the name 'clang.global.decl.ptrs'.
4136ffd1746dSEd Schouten void CodeGenModule::EmitDeclMetadata() {
413759d1ed5bSDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
4138ffd1746dSEd Schouten 
413959d1ed5bSDimitry Andric   for (auto &I : MangledDeclNames) {
414059d1ed5bSDimitry Andric     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
41410623d748SDimitry Andric     // Some mangled names don't necessarily have an associated GlobalValue
41420623d748SDimitry Andric     // in this module, e.g. if we mangled it for DebugInfo.
41430623d748SDimitry Andric     if (Addr)
414459d1ed5bSDimitry Andric       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
4145ffd1746dSEd Schouten   }
4146ffd1746dSEd Schouten }
4147ffd1746dSEd Schouten 
4148ffd1746dSEd Schouten /// Emits metadata nodes for all the local variables in the current
4149ffd1746dSEd Schouten /// function.
4150ffd1746dSEd Schouten void CodeGenFunction::EmitDeclMetadata() {
4151ffd1746dSEd Schouten   if (LocalDeclMap.empty()) return;
4152ffd1746dSEd Schouten 
4153ffd1746dSEd Schouten   llvm::LLVMContext &Context = getLLVMContext();
4154ffd1746dSEd Schouten 
4155ffd1746dSEd Schouten   // Find the unique metadata ID for this name.
4156ffd1746dSEd Schouten   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
4157ffd1746dSEd Schouten 
415859d1ed5bSDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
4159ffd1746dSEd Schouten 
416059d1ed5bSDimitry Andric   for (auto &I : LocalDeclMap) {
416159d1ed5bSDimitry Andric     const Decl *D = I.first;
41620623d748SDimitry Andric     llvm::Value *Addr = I.second.getPointer();
416359d1ed5bSDimitry Andric     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
4164ffd1746dSEd Schouten       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
416539d628a0SDimitry Andric       Alloca->setMetadata(
416639d628a0SDimitry Andric           DeclPtrKind, llvm::MDNode::get(
416739d628a0SDimitry Andric                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
416859d1ed5bSDimitry Andric     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
4169ffd1746dSEd Schouten       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
4170ffd1746dSEd Schouten       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
4171ffd1746dSEd Schouten     }
4172ffd1746dSEd Schouten   }
4173ffd1746dSEd Schouten }
4174e580952dSDimitry Andric 
4175f785676fSDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() {
4176f785676fSDimitry Andric   llvm::NamedMDNode *IdentMetadata =
4177f785676fSDimitry Andric     TheModule.getOrInsertNamedMetadata("llvm.ident");
4178f785676fSDimitry Andric   std::string Version = getClangFullVersion();
4179f785676fSDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
4180f785676fSDimitry Andric 
418139d628a0SDimitry Andric   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
4182f785676fSDimitry Andric   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4183f785676fSDimitry Andric }
4184f785676fSDimitry Andric 
418559d1ed5bSDimitry Andric void CodeGenModule::EmitTargetMetadata() {
418639d628a0SDimitry Andric   // Warning, new MangledDeclNames may be appended within this loop.
418739d628a0SDimitry Andric   // We rely on MapVector insertions adding new elements to the end
418839d628a0SDimitry Andric   // of the container.
418939d628a0SDimitry Andric   // FIXME: Move this loop into the one target that needs it, and only
419039d628a0SDimitry Andric   // loop over those declarations for which we couldn't emit the target
419139d628a0SDimitry Andric   // metadata when we emitted the declaration.
419239d628a0SDimitry Andric   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
419339d628a0SDimitry Andric     auto Val = *(MangledDeclNames.begin() + I);
419439d628a0SDimitry Andric     const Decl *D = Val.first.getDecl()->getMostRecentDecl();
419539d628a0SDimitry Andric     llvm::GlobalValue *GV = GetGlobalValue(Val.second);
419659d1ed5bSDimitry Andric     getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
419759d1ed5bSDimitry Andric   }
419859d1ed5bSDimitry Andric }
419959d1ed5bSDimitry Andric 
4200bd5abe19SDimitry Andric void CodeGenModule::EmitCoverageFile() {
420144290647SDimitry Andric   if (getCodeGenOpts().CoverageDataFile.empty() &&
420244290647SDimitry Andric       getCodeGenOpts().CoverageNotesFile.empty())
420344290647SDimitry Andric     return;
420444290647SDimitry Andric 
420544290647SDimitry Andric   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
420644290647SDimitry Andric   if (!CUNode)
420744290647SDimitry Andric     return;
420844290647SDimitry Andric 
4209bd5abe19SDimitry Andric   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
4210bd5abe19SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
421144290647SDimitry Andric   auto *CoverageDataFile =
421244290647SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
421344290647SDimitry Andric   auto *CoverageNotesFile =
421444290647SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
4215bd5abe19SDimitry Andric   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
4216bd5abe19SDimitry Andric     llvm::MDNode *CU = CUNode->getOperand(i);
421744290647SDimitry Andric     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
421839d628a0SDimitry Andric     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
4219bd5abe19SDimitry Andric   }
4220bd5abe19SDimitry Andric }
42213861d79fSDimitry Andric 
422239d628a0SDimitry Andric llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
42233861d79fSDimitry Andric   // Sema has checked that all uuid strings are of the form
42243861d79fSDimitry Andric   // "12345678-1234-1234-1234-1234567890ab".
42253861d79fSDimitry Andric   assert(Uuid.size() == 36);
4226f785676fSDimitry Andric   for (unsigned i = 0; i < 36; ++i) {
4227f785676fSDimitry Andric     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
4228f785676fSDimitry Andric     else                                         assert(isHexDigit(Uuid[i]));
42293861d79fSDimitry Andric   }
42303861d79fSDimitry Andric 
423139d628a0SDimitry Andric   // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
4232f785676fSDimitry Andric   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
42333861d79fSDimitry Andric 
4234f785676fSDimitry Andric   llvm::Constant *Field3[8];
4235f785676fSDimitry Andric   for (unsigned Idx = 0; Idx < 8; ++Idx)
4236f785676fSDimitry Andric     Field3[Idx] = llvm::ConstantInt::get(
4237f785676fSDimitry Andric         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
42383861d79fSDimitry Andric 
4239f785676fSDimitry Andric   llvm::Constant *Fields[4] = {
4240f785676fSDimitry Andric     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
4241f785676fSDimitry Andric     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
4242f785676fSDimitry Andric     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
4243f785676fSDimitry Andric     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
4244f785676fSDimitry Andric   };
4245f785676fSDimitry Andric 
4246f785676fSDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
42473861d79fSDimitry Andric }
424859d1ed5bSDimitry Andric 
424959d1ed5bSDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
425059d1ed5bSDimitry Andric                                                        bool ForEH) {
425159d1ed5bSDimitry Andric   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
425259d1ed5bSDimitry Andric   // FIXME: should we even be calling this method if RTTI is disabled
425359d1ed5bSDimitry Andric   // and it's not for EH?
425459d1ed5bSDimitry Andric   if (!ForEH && !getLangOpts().RTTI)
425559d1ed5bSDimitry Andric     return llvm::Constant::getNullValue(Int8PtrTy);
425659d1ed5bSDimitry Andric 
425759d1ed5bSDimitry Andric   if (ForEH && Ty->isObjCObjectPointerType() &&
425859d1ed5bSDimitry Andric       LangOpts.ObjCRuntime.isGNUFamily())
425959d1ed5bSDimitry Andric     return ObjCRuntime->GetEHType(Ty);
426059d1ed5bSDimitry Andric 
426159d1ed5bSDimitry Andric   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
426259d1ed5bSDimitry Andric }
426359d1ed5bSDimitry Andric 
426439d628a0SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
426539d628a0SDimitry Andric   for (auto RefExpr : D->varlists()) {
426639d628a0SDimitry Andric     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
426739d628a0SDimitry Andric     bool PerformInit =
426839d628a0SDimitry Andric         VD->getAnyInitializer() &&
426939d628a0SDimitry Andric         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
427039d628a0SDimitry Andric                                                         /*ForRef=*/false);
42710623d748SDimitry Andric 
42720623d748SDimitry Andric     Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
427333956c43SDimitry Andric     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
42740623d748SDimitry Andric             VD, Addr, RefExpr->getLocStart(), PerformInit))
427539d628a0SDimitry Andric       CXXGlobalInits.push_back(InitFunction);
427639d628a0SDimitry Andric   }
427739d628a0SDimitry Andric }
42788f0fd8f6SDimitry Andric 
42790623d748SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
42800623d748SDimitry Andric   llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
42810623d748SDimitry Andric   if (InternalId)
42820623d748SDimitry Andric     return InternalId;
42830623d748SDimitry Andric 
42840623d748SDimitry Andric   if (isExternallyVisible(T->getLinkage())) {
42858f0fd8f6SDimitry Andric     std::string OutName;
42868f0fd8f6SDimitry Andric     llvm::raw_string_ostream Out(OutName);
42870623d748SDimitry Andric     getCXXABI().getMangleContext().mangleTypeName(T, Out);
42888f0fd8f6SDimitry Andric 
42890623d748SDimitry Andric     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
42900623d748SDimitry Andric   } else {
42910623d748SDimitry Andric     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
42920623d748SDimitry Andric                                            llvm::ArrayRef<llvm::Metadata *>());
42930623d748SDimitry Andric   }
42940623d748SDimitry Andric 
42950623d748SDimitry Andric   return InternalId;
42960623d748SDimitry Andric }
42970623d748SDimitry Andric 
4298e7145dcbSDimitry Andric /// Returns whether this module needs the "all-vtables" type identifier.
4299e7145dcbSDimitry Andric bool CodeGenModule::NeedAllVtablesTypeId() const {
4300e7145dcbSDimitry Andric   // Returns true if at least one of vtable-based CFI checkers is enabled and
4301e7145dcbSDimitry Andric   // is not in the trapping mode.
4302e7145dcbSDimitry Andric   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
4303e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
4304e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
4305e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
4306e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
4307e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
4308e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
4309e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
4310e7145dcbSDimitry Andric }
4311e7145dcbSDimitry Andric 
4312e7145dcbSDimitry Andric void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
43130623d748SDimitry Andric                                           CharUnits Offset,
43140623d748SDimitry Andric                                           const CXXRecordDecl *RD) {
43150623d748SDimitry Andric   llvm::Metadata *MD =
43160623d748SDimitry Andric       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
4317e7145dcbSDimitry Andric   VTable->addTypeMetadata(Offset.getQuantity(), MD);
43180623d748SDimitry Andric 
4319e7145dcbSDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
4320e7145dcbSDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
4321e7145dcbSDimitry Andric       VTable->addTypeMetadata(Offset.getQuantity(),
4322e7145dcbSDimitry Andric                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
4323e7145dcbSDimitry Andric 
4324e7145dcbSDimitry Andric   if (NeedAllVtablesTypeId()) {
4325e7145dcbSDimitry Andric     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
4326e7145dcbSDimitry Andric     VTable->addTypeMetadata(Offset.getQuantity(), MD);
43270623d748SDimitry Andric   }
43280623d748SDimitry Andric }
43290623d748SDimitry Andric 
43300623d748SDimitry Andric // Fills in the supplied string map with the set of target features for the
43310623d748SDimitry Andric // passed in function.
43320623d748SDimitry Andric void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
43330623d748SDimitry Andric                                           const FunctionDecl *FD) {
43340623d748SDimitry Andric   StringRef TargetCPU = Target.getTargetOpts().CPU;
43350623d748SDimitry Andric   if (const auto *TD = FD->getAttr<TargetAttr>()) {
43360623d748SDimitry Andric     // If we have a TargetAttr build up the feature map based on that.
43370623d748SDimitry Andric     TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
43380623d748SDimitry Andric 
43390623d748SDimitry Andric     // Make a copy of the features as passed on the command line into the
43400623d748SDimitry Andric     // beginning of the additional features from the function to override.
43410623d748SDimitry Andric     ParsedAttr.first.insert(ParsedAttr.first.begin(),
43420623d748SDimitry Andric                             Target.getTargetOpts().FeaturesAsWritten.begin(),
43430623d748SDimitry Andric                             Target.getTargetOpts().FeaturesAsWritten.end());
43440623d748SDimitry Andric 
43450623d748SDimitry Andric     if (ParsedAttr.second != "")
43460623d748SDimitry Andric       TargetCPU = ParsedAttr.second;
43470623d748SDimitry Andric 
43480623d748SDimitry Andric     // Now populate the feature map, first with the TargetCPU which is either
43490623d748SDimitry Andric     // the default or a new one from the target attribute string. Then we'll use
43500623d748SDimitry Andric     // the passed in features (FeaturesAsWritten) along with the new ones from
43510623d748SDimitry Andric     // the attribute.
43520623d748SDimitry Andric     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first);
43530623d748SDimitry Andric   } else {
43540623d748SDimitry Andric     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
43550623d748SDimitry Andric                           Target.getTargetOpts().Features);
43560623d748SDimitry Andric   }
43578f0fd8f6SDimitry Andric }
4358e7145dcbSDimitry Andric 
4359e7145dcbSDimitry Andric llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
4360e7145dcbSDimitry Andric   if (!SanStats)
4361e7145dcbSDimitry Andric     SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
4362e7145dcbSDimitry Andric 
4363e7145dcbSDimitry Andric   return *SanStats;
4364e7145dcbSDimitry Andric }
436544290647SDimitry Andric llvm::Value *
436644290647SDimitry Andric CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
436744290647SDimitry Andric                                                   CodeGenFunction &CGF) {
436844290647SDimitry Andric   llvm::Constant *C = EmitConstantExpr(E, E->getType(), &CGF);
436944290647SDimitry Andric   auto SamplerT = getOpenCLRuntime().getSamplerType();
437044290647SDimitry Andric   auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
437144290647SDimitry Andric   return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
437244290647SDimitry Andric                                 "__translate_sampler_initializer"),
437344290647SDimitry Andric                                 {C});
437444290647SDimitry Andric }
4375