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"
2739d628a0SDimitry Andric #include "CoverageMappingGen.h"
28f22ef01cSRoman Divacky #include "TargetInfo.h"
29f22ef01cSRoman Divacky #include "clang/AST/ASTContext.h"
30f22ef01cSRoman Divacky #include "clang/AST/CharUnits.h"
31f22ef01cSRoman Divacky #include "clang/AST/DeclCXX.h"
32139f7f9bSDimitry Andric #include "clang/AST/DeclObjC.h"
33ffd1746dSEd Schouten #include "clang/AST/DeclTemplate.h"
342754fe60SDimitry Andric #include "clang/AST/Mangle.h"
35f22ef01cSRoman Divacky #include "clang/AST/RecordLayout.h"
36f8254f43SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h"
37dff0c46cSDimitry Andric #include "clang/Basic/Builtins.h"
38139f7f9bSDimitry Andric #include "clang/Basic/CharInfo.h"
39f22ef01cSRoman Divacky #include "clang/Basic/Diagnostic.h"
40139f7f9bSDimitry Andric #include "clang/Basic/Module.h"
41f22ef01cSRoman Divacky #include "clang/Basic/SourceManager.h"
42f22ef01cSRoman Divacky #include "clang/Basic/TargetInfo.h"
43f785676fSDimitry Andric #include "clang/Basic/Version.h"
4420e90f04SDimitry Andric #include "clang/CodeGen/ConstantInitBuilder.h"
45139f7f9bSDimitry Andric #include "clang/Frontend/CodeGenOptions.h"
46f785676fSDimitry Andric #include "clang/Sema/SemaDiagnostic.h"
47f22ef01cSRoman Divacky #include "llvm/ADT/Triple.h"
48d8866befSDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
4959d1ed5bSDimitry Andric #include "llvm/IR/CallSite.h"
50139f7f9bSDimitry Andric #include "llvm/IR/CallingConv.h"
51139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h"
52139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h"
53139f7f9bSDimitry Andric #include "llvm/IR/LLVMContext.h"
54139f7f9bSDimitry Andric #include "llvm/IR/Module.h"
5559d1ed5bSDimitry Andric #include "llvm/ProfileData/InstrProfReader.h"
56139f7f9bSDimitry Andric #include "llvm/Support/ConvertUTF.h"
57f22ef01cSRoman Divacky #include "llvm/Support/ErrorHandling.h"
580623d748SDimitry Andric #include "llvm/Support/MD5.h"
59139f7f9bSDimitry Andric 
60f22ef01cSRoman Divacky using namespace clang;
61f22ef01cSRoman Divacky using namespace CodeGen;
62f22ef01cSRoman Divacky 
636122f3e6SDimitry Andric static const char AnnotationSection[] = "llvm.metadata";
646122f3e6SDimitry Andric 
6559d1ed5bSDimitry Andric static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
66284c1978SDimitry Andric   switch (CGM.getTarget().getCXXABI().getKind()) {
67139f7f9bSDimitry Andric   case TargetCXXABI::GenericAArch64:
68139f7f9bSDimitry Andric   case TargetCXXABI::GenericARM:
69139f7f9bSDimitry Andric   case TargetCXXABI::iOS:
7059d1ed5bSDimitry Andric   case TargetCXXABI::iOS64:
710623d748SDimitry Andric   case TargetCXXABI::WatchOS:
72ef6fa9e2SDimitry Andric   case TargetCXXABI::GenericMIPS:
73139f7f9bSDimitry Andric   case TargetCXXABI::GenericItanium:
740623d748SDimitry Andric   case TargetCXXABI::WebAssembly:
7559d1ed5bSDimitry Andric     return CreateItaniumCXXABI(CGM);
76139f7f9bSDimitry Andric   case TargetCXXABI::Microsoft:
7759d1ed5bSDimitry Andric     return CreateMicrosoftCXXABI(CGM);
78e580952dSDimitry Andric   }
79e580952dSDimitry Andric 
80e580952dSDimitry Andric   llvm_unreachable("invalid C++ ABI kind");
81e580952dSDimitry Andric }
82e580952dSDimitry Andric 
833dac3a9bSDimitry Andric CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
843dac3a9bSDimitry Andric                              const PreprocessorOptions &PPO,
853dac3a9bSDimitry Andric                              const CodeGenOptions &CGO, llvm::Module &M,
8639d628a0SDimitry Andric                              DiagnosticsEngine &diags,
8739d628a0SDimitry Andric                              CoverageSourceInfo *CoverageInfo)
883dac3a9bSDimitry Andric     : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
893dac3a9bSDimitry Andric       PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
900623d748SDimitry Andric       Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
91e7145dcbSDimitry Andric       VMContext(M.getContext()), Types(*this), VTables(*this),
92e7145dcbSDimitry Andric       SanitizerMD(new SanitizerMetadata(*this)) {
93dff0c46cSDimitry Andric 
94dff0c46cSDimitry Andric   // Initialize the type cache.
95dff0c46cSDimitry Andric   llvm::LLVMContext &LLVMContext = M.getContext();
96dff0c46cSDimitry Andric   VoidTy = llvm::Type::getVoidTy(LLVMContext);
97dff0c46cSDimitry Andric   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
98dff0c46cSDimitry Andric   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
99dff0c46cSDimitry Andric   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
100dff0c46cSDimitry Andric   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
101dff0c46cSDimitry Andric   FloatTy = llvm::Type::getFloatTy(LLVMContext);
102dff0c46cSDimitry Andric   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
103dff0c46cSDimitry Andric   PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
104dff0c46cSDimitry Andric   PointerAlignInBytes =
105dff0c46cSDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
10644290647SDimitry Andric   SizeSizeInBytes =
10744290647SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
1080623d748SDimitry Andric   IntAlignInBytes =
1090623d748SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
110dff0c46cSDimitry Andric   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
11144290647SDimitry Andric   IntPtrTy = llvm::IntegerType::get(LLVMContext,
11244290647SDimitry Andric     C.getTargetInfo().getMaxPointerWidth());
113dff0c46cSDimitry Andric   Int8PtrTy = Int8Ty->getPointerTo(0);
114dff0c46cSDimitry Andric   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
1156bc11b14SDimitry Andric   AllocaInt8PtrTy = Int8Ty->getPointerTo(
1166bc11b14SDimitry Andric       M.getDataLayout().getAllocaAddrSpace());
117d8866befSDimitry Andric   ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
118dff0c46cSDimitry Andric 
119139f7f9bSDimitry Andric   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
12039d628a0SDimitry Andric   BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
121139f7f9bSDimitry Andric 
122dff0c46cSDimitry Andric   if (LangOpts.ObjC1)
1233b0f4066SDimitry Andric     createObjCRuntime();
124dff0c46cSDimitry Andric   if (LangOpts.OpenCL)
1256122f3e6SDimitry Andric     createOpenCLRuntime();
12659d1ed5bSDimitry Andric   if (LangOpts.OpenMP)
12759d1ed5bSDimitry Andric     createOpenMPRuntime();
128dff0c46cSDimitry Andric   if (LangOpts.CUDA)
1296122f3e6SDimitry Andric     createCUDARuntime();
130f22ef01cSRoman Divacky 
1317ae0e2c9SDimitry Andric   // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
13239d628a0SDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
1337ae0e2c9SDimitry Andric       (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
134e7145dcbSDimitry Andric     TBAA.reset(new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
135e7145dcbSDimitry Andric                                getCXXABI().getMangleContext()));
1362754fe60SDimitry Andric 
1373b0f4066SDimitry Andric   // If debug info or coverage generation is enabled, create the CGDebugInfo
1383b0f4066SDimitry Andric   // object.
139e7145dcbSDimitry Andric   if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
140e7145dcbSDimitry Andric       CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
141e7145dcbSDimitry Andric     DebugInfo.reset(new CGDebugInfo(*this));
1422754fe60SDimitry Andric 
1432754fe60SDimitry Andric   Block.GlobalUniqueCount = 0;
1442754fe60SDimitry Andric 
1450623d748SDimitry Andric   if (C.getLangOpts().ObjC1)
146e7145dcbSDimitry Andric     ObjCData.reset(new ObjCEntrypoints());
14759d1ed5bSDimitry Andric 
148e7145dcbSDimitry Andric   if (CodeGenOpts.hasProfileClangUse()) {
149e7145dcbSDimitry Andric     auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
150e7145dcbSDimitry Andric         CodeGenOpts.ProfileInstrumentUsePath);
151e7145dcbSDimitry Andric     if (auto E = ReaderOrErr.takeError()) {
15259d1ed5bSDimitry Andric       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1533dac3a9bSDimitry Andric                                               "Could not read profile %0: %1");
154e7145dcbSDimitry Andric       llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
155e7145dcbSDimitry Andric         getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
156e7145dcbSDimitry Andric                                   << EI.message();
157e7145dcbSDimitry Andric       });
15833956c43SDimitry Andric     } else
15933956c43SDimitry Andric       PGOReader = std::move(ReaderOrErr.get());
16059d1ed5bSDimitry Andric   }
16139d628a0SDimitry Andric 
16239d628a0SDimitry Andric   // If coverage mapping generation is enabled, create the
16339d628a0SDimitry Andric   // CoverageMappingModuleGen object.
16439d628a0SDimitry Andric   if (CodeGenOpts.CoverageMapping)
16539d628a0SDimitry Andric     CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
166f22ef01cSRoman Divacky }
167f22ef01cSRoman Divacky 
168e7145dcbSDimitry Andric CodeGenModule::~CodeGenModule() {}
169f22ef01cSRoman Divacky 
170f22ef01cSRoman Divacky void CodeGenModule::createObjCRuntime() {
1717ae0e2c9SDimitry Andric   // This is just isGNUFamily(), but we want to force implementors of
1727ae0e2c9SDimitry Andric   // new ABIs to decide how best to do this.
1737ae0e2c9SDimitry Andric   switch (LangOpts.ObjCRuntime.getKind()) {
1747ae0e2c9SDimitry Andric   case ObjCRuntime::GNUstep:
1757ae0e2c9SDimitry Andric   case ObjCRuntime::GCC:
1767ae0e2c9SDimitry Andric   case ObjCRuntime::ObjFW:
177e7145dcbSDimitry Andric     ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
1787ae0e2c9SDimitry Andric     return;
1797ae0e2c9SDimitry Andric 
1807ae0e2c9SDimitry Andric   case ObjCRuntime::FragileMacOSX:
1817ae0e2c9SDimitry Andric   case ObjCRuntime::MacOSX:
1827ae0e2c9SDimitry Andric   case ObjCRuntime::iOS:
1830623d748SDimitry Andric   case ObjCRuntime::WatchOS:
184e7145dcbSDimitry Andric     ObjCRuntime.reset(CreateMacObjCRuntime(*this));
1857ae0e2c9SDimitry Andric     return;
1867ae0e2c9SDimitry Andric   }
1877ae0e2c9SDimitry Andric   llvm_unreachable("bad runtime kind");
1886122f3e6SDimitry Andric }
1896122f3e6SDimitry Andric 
1906122f3e6SDimitry Andric void CodeGenModule::createOpenCLRuntime() {
191e7145dcbSDimitry Andric   OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
1926122f3e6SDimitry Andric }
1936122f3e6SDimitry Andric 
19459d1ed5bSDimitry Andric void CodeGenModule::createOpenMPRuntime() {
195e7145dcbSDimitry Andric   // Select a specialized code generation class based on the target, if any.
196e7145dcbSDimitry Andric   // If it does not exist use the default implementation.
19744290647SDimitry Andric   switch (getTriple().getArch()) {
198e7145dcbSDimitry Andric   case llvm::Triple::nvptx:
199e7145dcbSDimitry Andric   case llvm::Triple::nvptx64:
200e7145dcbSDimitry Andric     assert(getLangOpts().OpenMPIsDevice &&
201e7145dcbSDimitry Andric            "OpenMP NVPTX is only prepared to deal with device code.");
202e7145dcbSDimitry Andric     OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
203e7145dcbSDimitry Andric     break;
204e7145dcbSDimitry Andric   default:
205e7145dcbSDimitry Andric     OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
206e7145dcbSDimitry Andric     break;
207e7145dcbSDimitry Andric   }
20859d1ed5bSDimitry Andric }
20959d1ed5bSDimitry Andric 
2106122f3e6SDimitry Andric void CodeGenModule::createCUDARuntime() {
211e7145dcbSDimitry Andric   CUDARuntime.reset(CreateNVCUDARuntime(*this));
212f22ef01cSRoman Divacky }
213f22ef01cSRoman Divacky 
21439d628a0SDimitry Andric void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
21539d628a0SDimitry Andric   Replacements[Name] = C;
21639d628a0SDimitry Andric }
21739d628a0SDimitry Andric 
218f785676fSDimitry Andric void CodeGenModule::applyReplacements() {
2198f0fd8f6SDimitry Andric   for (auto &I : Replacements) {
2208f0fd8f6SDimitry Andric     StringRef MangledName = I.first();
2218f0fd8f6SDimitry Andric     llvm::Constant *Replacement = I.second;
222f785676fSDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
223f785676fSDimitry Andric     if (!Entry)
224f785676fSDimitry Andric       continue;
22559d1ed5bSDimitry Andric     auto *OldF = cast<llvm::Function>(Entry);
22659d1ed5bSDimitry Andric     auto *NewF = dyn_cast<llvm::Function>(Replacement);
227f785676fSDimitry Andric     if (!NewF) {
22859d1ed5bSDimitry Andric       if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
22959d1ed5bSDimitry Andric         NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
23059d1ed5bSDimitry Andric       } else {
23159d1ed5bSDimitry Andric         auto *CE = cast<llvm::ConstantExpr>(Replacement);
232f785676fSDimitry Andric         assert(CE->getOpcode() == llvm::Instruction::BitCast ||
233f785676fSDimitry Andric                CE->getOpcode() == llvm::Instruction::GetElementPtr);
234f785676fSDimitry Andric         NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
235f785676fSDimitry Andric       }
23659d1ed5bSDimitry Andric     }
237f785676fSDimitry Andric 
238f785676fSDimitry Andric     // Replace old with new, but keep the old order.
239f785676fSDimitry Andric     OldF->replaceAllUsesWith(Replacement);
240f785676fSDimitry Andric     if (NewF) {
241f785676fSDimitry Andric       NewF->removeFromParent();
2420623d748SDimitry Andric       OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
2430623d748SDimitry Andric                                                        NewF);
244f785676fSDimitry Andric     }
245f785676fSDimitry Andric     OldF->eraseFromParent();
246f785676fSDimitry Andric   }
247f785676fSDimitry Andric }
248f785676fSDimitry Andric 
2490623d748SDimitry Andric void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
2500623d748SDimitry Andric   GlobalValReplacements.push_back(std::make_pair(GV, C));
2510623d748SDimitry Andric }
2520623d748SDimitry Andric 
2530623d748SDimitry Andric void CodeGenModule::applyGlobalValReplacements() {
2540623d748SDimitry Andric   for (auto &I : GlobalValReplacements) {
2550623d748SDimitry Andric     llvm::GlobalValue *GV = I.first;
2560623d748SDimitry Andric     llvm::Constant *C = I.second;
2570623d748SDimitry Andric 
2580623d748SDimitry Andric     GV->replaceAllUsesWith(C);
2590623d748SDimitry Andric     GV->eraseFromParent();
2600623d748SDimitry Andric   }
2610623d748SDimitry Andric }
2620623d748SDimitry Andric 
26359d1ed5bSDimitry Andric // This is only used in aliases that we created and we know they have a
26459d1ed5bSDimitry Andric // linear structure.
265e7145dcbSDimitry Andric static const llvm::GlobalObject *getAliasedGlobal(
266e7145dcbSDimitry Andric     const llvm::GlobalIndirectSymbol &GIS) {
267e7145dcbSDimitry Andric   llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
268e7145dcbSDimitry Andric   const llvm::Constant *C = &GIS;
26959d1ed5bSDimitry Andric   for (;;) {
27059d1ed5bSDimitry Andric     C = C->stripPointerCasts();
27159d1ed5bSDimitry Andric     if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
27259d1ed5bSDimitry Andric       return GO;
27359d1ed5bSDimitry Andric     // stripPointerCasts will not walk over weak aliases.
274e7145dcbSDimitry Andric     auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
275e7145dcbSDimitry Andric     if (!GIS2)
27659d1ed5bSDimitry Andric       return nullptr;
277e7145dcbSDimitry Andric     if (!Visited.insert(GIS2).second)
27859d1ed5bSDimitry Andric       return nullptr;
279e7145dcbSDimitry Andric     C = GIS2->getIndirectSymbol();
28059d1ed5bSDimitry Andric   }
28159d1ed5bSDimitry Andric }
28259d1ed5bSDimitry Andric 
283f785676fSDimitry Andric void CodeGenModule::checkAliases() {
28459d1ed5bSDimitry Andric   // Check if the constructed aliases are well formed. It is really unfortunate
28559d1ed5bSDimitry Andric   // that we have to do this in CodeGen, but we only construct mangled names
28659d1ed5bSDimitry Andric   // and aliases during codegen.
287f785676fSDimitry Andric   bool Error = false;
28859d1ed5bSDimitry Andric   DiagnosticsEngine &Diags = getDiags();
2898f0fd8f6SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
29059d1ed5bSDimitry Andric     const auto *D = cast<ValueDecl>(GD.getDecl());
291e7145dcbSDimitry Andric     SourceLocation Location;
292e7145dcbSDimitry Andric     bool IsIFunc = D->hasAttr<IFuncAttr>();
293e7145dcbSDimitry Andric     if (const Attr *A = D->getDefiningAttr())
294e7145dcbSDimitry Andric       Location = A->getLocation();
295e7145dcbSDimitry Andric     else
296e7145dcbSDimitry Andric       llvm_unreachable("Not an alias or ifunc?");
297f785676fSDimitry Andric     StringRef MangledName = getMangledName(GD);
298f785676fSDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
299e7145dcbSDimitry Andric     auto *Alias  = cast<llvm::GlobalIndirectSymbol>(Entry);
30059d1ed5bSDimitry Andric     const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
30159d1ed5bSDimitry Andric     if (!GV) {
302f785676fSDimitry Andric       Error = true;
303e7145dcbSDimitry Andric       Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
30459d1ed5bSDimitry Andric     } else if (GV->isDeclaration()) {
305f785676fSDimitry Andric       Error = true;
306e7145dcbSDimitry Andric       Diags.Report(Location, diag::err_alias_to_undefined)
307e7145dcbSDimitry Andric           << IsIFunc << IsIFunc;
308e7145dcbSDimitry Andric     } else if (IsIFunc) {
309e7145dcbSDimitry Andric       // Check resolver function type.
310e7145dcbSDimitry Andric       llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
311e7145dcbSDimitry Andric           GV->getType()->getPointerElementType());
312e7145dcbSDimitry Andric       assert(FTy);
313e7145dcbSDimitry Andric       if (!FTy->getReturnType()->isPointerTy())
314e7145dcbSDimitry Andric         Diags.Report(Location, diag::err_ifunc_resolver_return);
315e7145dcbSDimitry Andric       if (FTy->getNumParams())
316e7145dcbSDimitry Andric         Diags.Report(Location, diag::err_ifunc_resolver_params);
31759d1ed5bSDimitry Andric     }
31859d1ed5bSDimitry Andric 
319e7145dcbSDimitry Andric     llvm::Constant *Aliasee = Alias->getIndirectSymbol();
32059d1ed5bSDimitry Andric     llvm::GlobalValue *AliaseeGV;
32159d1ed5bSDimitry Andric     if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
32259d1ed5bSDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
32359d1ed5bSDimitry Andric     else
32459d1ed5bSDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
32559d1ed5bSDimitry Andric 
32659d1ed5bSDimitry Andric     if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
32759d1ed5bSDimitry Andric       StringRef AliasSection = SA->getName();
32859d1ed5bSDimitry Andric       if (AliasSection != AliaseeGV->getSection())
32959d1ed5bSDimitry Andric         Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
330e7145dcbSDimitry Andric             << AliasSection << IsIFunc << IsIFunc;
33159d1ed5bSDimitry Andric     }
33259d1ed5bSDimitry Andric 
33359d1ed5bSDimitry Andric     // We have to handle alias to weak aliases in here. LLVM itself disallows
33459d1ed5bSDimitry Andric     // this since the object semantics would not match the IL one. For
33559d1ed5bSDimitry Andric     // compatibility with gcc we implement it by just pointing the alias
33659d1ed5bSDimitry Andric     // to its aliasee's aliasee. We also warn, since the user is probably
33759d1ed5bSDimitry Andric     // expecting the link to be weak.
338e7145dcbSDimitry Andric     if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
339e7145dcbSDimitry Andric       if (GA->isInterposable()) {
340e7145dcbSDimitry Andric         Diags.Report(Location, diag::warn_alias_to_weak_alias)
341e7145dcbSDimitry Andric             << GV->getName() << GA->getName() << IsIFunc;
34259d1ed5bSDimitry Andric         Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
343e7145dcbSDimitry Andric             GA->getIndirectSymbol(), Alias->getType());
344e7145dcbSDimitry Andric         Alias->setIndirectSymbol(Aliasee);
34559d1ed5bSDimitry Andric       }
346f785676fSDimitry Andric     }
347f785676fSDimitry Andric   }
348f785676fSDimitry Andric   if (!Error)
349f785676fSDimitry Andric     return;
350f785676fSDimitry Andric 
3518f0fd8f6SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
352f785676fSDimitry Andric     StringRef MangledName = getMangledName(GD);
353f785676fSDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
354e7145dcbSDimitry Andric     auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
355f785676fSDimitry Andric     Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
356f785676fSDimitry Andric     Alias->eraseFromParent();
357f785676fSDimitry Andric   }
358f785676fSDimitry Andric }
359f785676fSDimitry Andric 
36059d1ed5bSDimitry Andric void CodeGenModule::clear() {
36159d1ed5bSDimitry Andric   DeferredDeclsToEmit.clear();
36233956c43SDimitry Andric   if (OpenMPRuntime)
36333956c43SDimitry Andric     OpenMPRuntime->clear();
36459d1ed5bSDimitry Andric }
36559d1ed5bSDimitry Andric 
36659d1ed5bSDimitry Andric void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
36759d1ed5bSDimitry Andric                                        StringRef MainFile) {
36859d1ed5bSDimitry Andric   if (!hasDiagnostics())
36959d1ed5bSDimitry Andric     return;
37059d1ed5bSDimitry Andric   if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
37159d1ed5bSDimitry Andric     if (MainFile.empty())
37259d1ed5bSDimitry Andric       MainFile = "<stdin>";
37359d1ed5bSDimitry Andric     Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
374f37b6182SDimitry Andric   } else {
375f37b6182SDimitry Andric     if (Mismatched > 0)
376f37b6182SDimitry Andric       Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
377f37b6182SDimitry Andric 
378f37b6182SDimitry Andric     if (Missing > 0)
379f37b6182SDimitry Andric       Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
380f37b6182SDimitry Andric   }
38159d1ed5bSDimitry Andric }
38259d1ed5bSDimitry Andric 
383f22ef01cSRoman Divacky void CodeGenModule::Release() {
384f22ef01cSRoman Divacky   EmitDeferred();
3850623d748SDimitry Andric   applyGlobalValReplacements();
386f785676fSDimitry Andric   applyReplacements();
387f785676fSDimitry Andric   checkAliases();
388f22ef01cSRoman Divacky   EmitCXXGlobalInitFunc();
389f22ef01cSRoman Divacky   EmitCXXGlobalDtorFunc();
390284c1978SDimitry Andric   EmitCXXThreadLocalInitFunc();
3916122f3e6SDimitry Andric   if (ObjCRuntime)
3926122f3e6SDimitry Andric     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
393f22ef01cSRoman Divacky       AddGlobalCtor(ObjCInitFunction);
39433956c43SDimitry Andric   if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
39533956c43SDimitry Andric       CUDARuntime) {
39633956c43SDimitry Andric     if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
39733956c43SDimitry Andric       AddGlobalCtor(CudaCtorFunction);
39833956c43SDimitry Andric     if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
39933956c43SDimitry Andric       AddGlobalDtor(CudaDtorFunction);
40033956c43SDimitry Andric   }
401ea942507SDimitry Andric   if (OpenMPRuntime)
402ea942507SDimitry Andric     if (llvm::Function *OpenMPRegistrationFunction =
403302affcbSDimitry Andric             OpenMPRuntime->emitRegistrationFunction()) {
404302affcbSDimitry Andric       auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
405302affcbSDimitry Andric         OpenMPRegistrationFunction : nullptr;
406302affcbSDimitry Andric       AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
407302affcbSDimitry Andric     }
4080623d748SDimitry Andric   if (PGOReader) {
409e7145dcbSDimitry Andric     getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
4100623d748SDimitry Andric     if (PGOStats.hasDiagnostics())
41159d1ed5bSDimitry Andric       PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
4120623d748SDimitry Andric   }
413f22ef01cSRoman Divacky   EmitCtorList(GlobalCtors, "llvm.global_ctors");
414f22ef01cSRoman Divacky   EmitCtorList(GlobalDtors, "llvm.global_dtors");
4156122f3e6SDimitry Andric   EmitGlobalAnnotations();
416284c1978SDimitry Andric   EmitStaticExternCAliases();
41739d628a0SDimitry Andric   EmitDeferredUnusedCoverageMappings();
41839d628a0SDimitry Andric   if (CoverageMapping)
41939d628a0SDimitry Andric     CoverageMapping->emit();
42020e90f04SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
421e7145dcbSDimitry Andric     CodeGenFunction(*this).EmitCfiCheckFail();
42220e90f04SDimitry Andric     CodeGenFunction(*this).EmitCfiCheckStub();
42320e90f04SDimitry Andric   }
42420e90f04SDimitry Andric   emitAtAvailableLinkGuard();
42559d1ed5bSDimitry Andric   emitLLVMUsed();
426e7145dcbSDimitry Andric   if (SanStats)
427e7145dcbSDimitry Andric     SanStats->finish();
428ffd1746dSEd Schouten 
429f785676fSDimitry Andric   if (CodeGenOpts.Autolink &&
430f785676fSDimitry Andric       (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
431139f7f9bSDimitry Andric     EmitModuleLinkOptions();
432139f7f9bSDimitry Andric   }
43320e90f04SDimitry Andric 
43420e90f04SDimitry Andric   // Record mregparm value now so it is visible through rest of codegen.
43520e90f04SDimitry Andric   if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
43620e90f04SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
43720e90f04SDimitry Andric                               CodeGenOpts.NumRegisterParameters);
43820e90f04SDimitry Andric 
4390623d748SDimitry Andric   if (CodeGenOpts.DwarfVersion) {
440f785676fSDimitry Andric     // We actually want the latest version when there are conflicts.
441f785676fSDimitry Andric     // We can change from Warning to Latest if such mode is supported.
442f785676fSDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
443f785676fSDimitry Andric                               CodeGenOpts.DwarfVersion);
4440623d748SDimitry Andric   }
4450623d748SDimitry Andric   if (CodeGenOpts.EmitCodeView) {
4460623d748SDimitry Andric     // Indicate that we want CodeView in the metadata.
4470623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
4480623d748SDimitry Andric   }
4490623d748SDimitry Andric   if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
4500623d748SDimitry Andric     // We don't support LTO with 2 with different StrictVTablePointers
4510623d748SDimitry Andric     // FIXME: we could support it by stripping all the information introduced
4520623d748SDimitry Andric     // by StrictVTablePointers.
4530623d748SDimitry Andric 
4540623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
4550623d748SDimitry Andric 
4560623d748SDimitry Andric     llvm::Metadata *Ops[2] = {
4570623d748SDimitry Andric               llvm::MDString::get(VMContext, "StrictVTablePointers"),
4580623d748SDimitry Andric               llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
4590623d748SDimitry Andric                   llvm::Type::getInt32Ty(VMContext), 1))};
4600623d748SDimitry Andric 
4610623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Require,
4620623d748SDimitry Andric                               "StrictVTablePointersRequirement",
4630623d748SDimitry Andric                               llvm::MDNode::get(VMContext, Ops));
4640623d748SDimitry Andric   }
465f785676fSDimitry Andric   if (DebugInfo)
46659d1ed5bSDimitry Andric     // We support a single version in the linked module. The LLVM
46759d1ed5bSDimitry Andric     // parser will drop debug info with a different version number
46859d1ed5bSDimitry Andric     // (and warn about it, too).
46959d1ed5bSDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
470f785676fSDimitry Andric                               llvm::DEBUG_METADATA_VERSION);
471139f7f9bSDimitry Andric 
472d8866befSDimitry Andric   // Width of wchar_t in bytes
473d8866befSDimitry Andric   uint64_t WCharWidth =
474d8866befSDimitry Andric       Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
475d8866befSDimitry Andric   assert(LangOpts.ShortWChar ||
476d8866befSDimitry Andric          llvm::TargetLibraryInfoImpl::getTargetWCharSize(Target.getTriple()) ==
477d8866befSDimitry Andric                  Target.getWCharWidth() / 8 &&
478d8866befSDimitry Andric              "LLVM wchar_t size out of sync");
479d8866befSDimitry Andric 
48059d1ed5bSDimitry Andric   // We need to record the widths of enums and wchar_t, so that we can generate
481d8866befSDimitry Andric   // the correct build attributes in the ARM backend. wchar_size is also used by
482d8866befSDimitry Andric   // TargetLibraryInfo.
483d8866befSDimitry Andric   getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
484d8866befSDimitry Andric 
48559d1ed5bSDimitry Andric   llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
48659d1ed5bSDimitry Andric   if (   Arch == llvm::Triple::arm
48759d1ed5bSDimitry Andric       || Arch == llvm::Triple::armeb
48859d1ed5bSDimitry Andric       || Arch == llvm::Triple::thumb
48959d1ed5bSDimitry Andric       || Arch == llvm::Triple::thumbeb) {
49059d1ed5bSDimitry Andric     // The minimum width of an enum in bytes
49159d1ed5bSDimitry Andric     uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
49259d1ed5bSDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
49359d1ed5bSDimitry Andric   }
49459d1ed5bSDimitry Andric 
4950623d748SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
4960623d748SDimitry Andric     // Indicate that we want cross-DSO control flow integrity checks.
4970623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
4980623d748SDimitry Andric   }
4990623d748SDimitry Andric 
50044290647SDimitry Andric   if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
501e7145dcbSDimitry Andric     // Indicate whether __nvvm_reflect should be configured to flush denormal
502e7145dcbSDimitry Andric     // floating point values to 0.  (This corresponds to its "__CUDA_FTZ"
503e7145dcbSDimitry Andric     // property.)
504e7145dcbSDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
505e7145dcbSDimitry Andric                               LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
50639d628a0SDimitry Andric   }
50739d628a0SDimitry Andric 
508e7145dcbSDimitry Andric   if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
509e7145dcbSDimitry Andric     assert(PLevel < 3 && "Invalid PIC Level");
510e7145dcbSDimitry Andric     getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
511e7145dcbSDimitry Andric     if (Context.getLangOpts().PIE)
512e7145dcbSDimitry Andric       getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
51339d628a0SDimitry Andric   }
51439d628a0SDimitry Andric 
5152754fe60SDimitry Andric   SimplifyPersonality();
5162754fe60SDimitry Andric 
517ffd1746dSEd Schouten   if (getCodeGenOpts().EmitDeclMetadata)
518ffd1746dSEd Schouten     EmitDeclMetadata();
519bd5abe19SDimitry Andric 
520bd5abe19SDimitry Andric   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
521bd5abe19SDimitry Andric     EmitCoverageFile();
5226122f3e6SDimitry Andric 
5236122f3e6SDimitry Andric   if (DebugInfo)
5246122f3e6SDimitry Andric     DebugInfo->finalize();
525f785676fSDimitry Andric 
526f785676fSDimitry Andric   EmitVersionIdentMetadata();
52759d1ed5bSDimitry Andric 
52859d1ed5bSDimitry Andric   EmitTargetMetadata();
529f22ef01cSRoman Divacky }
530f22ef01cSRoman Divacky 
5313b0f4066SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
5323b0f4066SDimitry Andric   // Make sure that this type is translated.
5333b0f4066SDimitry Andric   Types.UpdateCompletedType(TD);
5343b0f4066SDimitry Andric }
5353b0f4066SDimitry Andric 
536e7145dcbSDimitry Andric void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
537e7145dcbSDimitry Andric   // Make sure that this type is translated.
538e7145dcbSDimitry Andric   Types.RefreshTypeCacheForClass(RD);
539e7145dcbSDimitry Andric }
540e7145dcbSDimitry Andric 
5412754fe60SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
5422754fe60SDimitry Andric   if (!TBAA)
54359d1ed5bSDimitry Andric     return nullptr;
5442754fe60SDimitry Andric   return TBAA->getTBAAInfo(QTy);
5452754fe60SDimitry Andric }
5462754fe60SDimitry Andric 
547dff0c46cSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
548dff0c46cSDimitry Andric   if (!TBAA)
54959d1ed5bSDimitry Andric     return nullptr;
550dff0c46cSDimitry Andric   return TBAA->getTBAAInfoForVTablePtr();
551dff0c46cSDimitry Andric }
552dff0c46cSDimitry Andric 
5533861d79fSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
5543861d79fSDimitry Andric   if (!TBAA)
55559d1ed5bSDimitry Andric     return nullptr;
5563861d79fSDimitry Andric   return TBAA->getTBAAStructInfo(QTy);
5573861d79fSDimitry Andric }
5583861d79fSDimitry Andric 
559139f7f9bSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
560139f7f9bSDimitry Andric                                                   llvm::MDNode *AccessN,
561139f7f9bSDimitry Andric                                                   uint64_t O) {
562139f7f9bSDimitry Andric   if (!TBAA)
56359d1ed5bSDimitry Andric     return nullptr;
564139f7f9bSDimitry Andric   return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
565139f7f9bSDimitry Andric }
566139f7f9bSDimitry Andric 
567f785676fSDimitry Andric /// Decorate the instruction with a TBAA tag. For both scalar TBAA
568f785676fSDimitry Andric /// and struct-path aware TBAA, the tag has the same format:
569f785676fSDimitry Andric /// base type, access type and offset.
570284c1978SDimitry Andric /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
5710623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
572284c1978SDimitry Andric                                                 llvm::MDNode *TBAAInfo,
573284c1978SDimitry Andric                                                 bool ConvertTypeToTag) {
574f785676fSDimitry Andric   if (ConvertTypeToTag && TBAA)
575284c1978SDimitry Andric     Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
576284c1978SDimitry Andric                       TBAA->getTBAAScalarTagInfo(TBAAInfo));
577284c1978SDimitry Andric   else
5782754fe60SDimitry Andric     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
5792754fe60SDimitry Andric }
5802754fe60SDimitry Andric 
5810623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithInvariantGroup(
5820623d748SDimitry Andric     llvm::Instruction *I, const CXXRecordDecl *RD) {
58351690af2SDimitry Andric   I->setMetadata(llvm::LLVMContext::MD_invariant_group,
58451690af2SDimitry Andric                  llvm::MDNode::get(getLLVMContext(), {}));
5850623d748SDimitry Andric }
5860623d748SDimitry Andric 
58759d1ed5bSDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) {
58859d1ed5bSDimitry Andric   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
58959d1ed5bSDimitry Andric   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
590f22ef01cSRoman Divacky }
591f22ef01cSRoman Divacky 
592f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
593f22ef01cSRoman Divacky /// specified stmt yet.
594f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
5956122f3e6SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
596f22ef01cSRoman Divacky                                                "cannot compile this %0 yet");
597f22ef01cSRoman Divacky   std::string Msg = Type;
598f22ef01cSRoman Divacky   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
599f22ef01cSRoman Divacky     << Msg << S->getSourceRange();
600f22ef01cSRoman Divacky }
601f22ef01cSRoman Divacky 
602f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
603f22ef01cSRoman Divacky /// specified decl yet.
604f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
6056122f3e6SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
606f22ef01cSRoman Divacky                                                "cannot compile this %0 yet");
607f22ef01cSRoman Divacky   std::string Msg = Type;
608f22ef01cSRoman Divacky   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
609f22ef01cSRoman Divacky }
610f22ef01cSRoman Divacky 
61117a519f9SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
61217a519f9SDimitry Andric   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
61317a519f9SDimitry Andric }
61417a519f9SDimitry Andric 
615f22ef01cSRoman Divacky void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
6162754fe60SDimitry Andric                                         const NamedDecl *D) const {
617f22ef01cSRoman Divacky   // Internal definitions always have default visibility.
618f22ef01cSRoman Divacky   if (GV->hasLocalLinkage()) {
619f22ef01cSRoman Divacky     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
620f22ef01cSRoman Divacky     return;
621f22ef01cSRoman Divacky   }
622f22ef01cSRoman Divacky 
6232754fe60SDimitry Andric   // Set visibility for definitions.
624139f7f9bSDimitry Andric   LinkageInfo LV = D->getLinkageAndVisibility();
625139f7f9bSDimitry Andric   if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
626139f7f9bSDimitry Andric     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
627f22ef01cSRoman Divacky }
628f22ef01cSRoman Divacky 
6297ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
6307ae0e2c9SDimitry Andric   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
6317ae0e2c9SDimitry Andric       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
6327ae0e2c9SDimitry Andric       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
6337ae0e2c9SDimitry Andric       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
6347ae0e2c9SDimitry Andric       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
6357ae0e2c9SDimitry Andric }
6367ae0e2c9SDimitry Andric 
6377ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
6387ae0e2c9SDimitry Andric     CodeGenOptions::TLSModel M) {
6397ae0e2c9SDimitry Andric   switch (M) {
6407ae0e2c9SDimitry Andric   case CodeGenOptions::GeneralDynamicTLSModel:
6417ae0e2c9SDimitry Andric     return llvm::GlobalVariable::GeneralDynamicTLSModel;
6427ae0e2c9SDimitry Andric   case CodeGenOptions::LocalDynamicTLSModel:
6437ae0e2c9SDimitry Andric     return llvm::GlobalVariable::LocalDynamicTLSModel;
6447ae0e2c9SDimitry Andric   case CodeGenOptions::InitialExecTLSModel:
6457ae0e2c9SDimitry Andric     return llvm::GlobalVariable::InitialExecTLSModel;
6467ae0e2c9SDimitry Andric   case CodeGenOptions::LocalExecTLSModel:
6477ae0e2c9SDimitry Andric     return llvm::GlobalVariable::LocalExecTLSModel;
6487ae0e2c9SDimitry Andric   }
6497ae0e2c9SDimitry Andric   llvm_unreachable("Invalid TLS model!");
6507ae0e2c9SDimitry Andric }
6517ae0e2c9SDimitry Andric 
65239d628a0SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
653284c1978SDimitry Andric   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
6547ae0e2c9SDimitry Andric 
65539d628a0SDimitry Andric   llvm::GlobalValue::ThreadLocalMode TLM;
6563861d79fSDimitry Andric   TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
6577ae0e2c9SDimitry Andric 
6587ae0e2c9SDimitry Andric   // Override the TLS model if it is explicitly specified.
65959d1ed5bSDimitry Andric   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
6607ae0e2c9SDimitry Andric     TLM = GetLLVMTLSModel(Attr->getModel());
6617ae0e2c9SDimitry Andric   }
6627ae0e2c9SDimitry Andric 
6637ae0e2c9SDimitry Andric   GV->setThreadLocalMode(TLM);
6647ae0e2c9SDimitry Andric }
6657ae0e2c9SDimitry Andric 
6666122f3e6SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
667444ed5c5SDimitry Andric   GlobalDecl CanonicalGD = GD.getCanonicalDecl();
668444ed5c5SDimitry Andric 
669444ed5c5SDimitry Andric   // Some ABIs don't have constructor variants.  Make sure that base and
670444ed5c5SDimitry Andric   // complete constructors get mangled the same.
671444ed5c5SDimitry Andric   if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
672444ed5c5SDimitry Andric     if (!getTarget().getCXXABI().hasConstructorVariants()) {
673444ed5c5SDimitry Andric       CXXCtorType OrigCtorType = GD.getCtorType();
674444ed5c5SDimitry Andric       assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
675444ed5c5SDimitry Andric       if (OrigCtorType == Ctor_Base)
676444ed5c5SDimitry Andric         CanonicalGD = GlobalDecl(CD, Ctor_Complete);
677444ed5c5SDimitry Andric     }
678444ed5c5SDimitry Andric   }
679444ed5c5SDimitry Andric 
680444ed5c5SDimitry Andric   StringRef &FoundStr = MangledDeclNames[CanonicalGD];
68159d1ed5bSDimitry Andric   if (!FoundStr.empty())
68259d1ed5bSDimitry Andric     return FoundStr;
683f22ef01cSRoman Divacky 
68459d1ed5bSDimitry Andric   const auto *ND = cast<NamedDecl>(GD.getDecl());
685dff0c46cSDimitry Andric   SmallString<256> Buffer;
68659d1ed5bSDimitry Andric   StringRef Str;
68759d1ed5bSDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
6882754fe60SDimitry Andric     llvm::raw_svector_ostream Out(Buffer);
68959d1ed5bSDimitry Andric     if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
6902754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
69159d1ed5bSDimitry Andric     else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
6922754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
693ffd1746dSEd Schouten     else
6942754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleName(ND, Out);
69559d1ed5bSDimitry Andric     Str = Out.str();
69659d1ed5bSDimitry Andric   } else {
69759d1ed5bSDimitry Andric     IdentifierInfo *II = ND->getIdentifier();
69859d1ed5bSDimitry Andric     assert(II && "Attempt to mangle unnamed decl.");
69944290647SDimitry Andric     const auto *FD = dyn_cast<FunctionDecl>(ND);
70044290647SDimitry Andric 
70144290647SDimitry Andric     if (FD &&
70244290647SDimitry Andric         FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
70344290647SDimitry Andric       llvm::raw_svector_ostream Out(Buffer);
70444290647SDimitry Andric       Out << "__regcall3__" << II->getName();
70544290647SDimitry Andric       Str = Out.str();
70644290647SDimitry Andric     } else {
70759d1ed5bSDimitry Andric       Str = II->getName();
708ffd1746dSEd Schouten     }
70944290647SDimitry Andric   }
710ffd1746dSEd Schouten 
71139d628a0SDimitry Andric   // Keep the first result in the case of a mangling collision.
71239d628a0SDimitry Andric   auto Result = Manglings.insert(std::make_pair(Str, GD));
71339d628a0SDimitry Andric   return FoundStr = Result.first->first();
71459d1ed5bSDimitry Andric }
71559d1ed5bSDimitry Andric 
71659d1ed5bSDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
717ffd1746dSEd Schouten                                              const BlockDecl *BD) {
7182754fe60SDimitry Andric   MangleContext &MangleCtx = getCXXABI().getMangleContext();
7192754fe60SDimitry Andric   const Decl *D = GD.getDecl();
72059d1ed5bSDimitry Andric 
72159d1ed5bSDimitry Andric   SmallString<256> Buffer;
72259d1ed5bSDimitry Andric   llvm::raw_svector_ostream Out(Buffer);
72359d1ed5bSDimitry Andric   if (!D)
7247ae0e2c9SDimitry Andric     MangleCtx.mangleGlobalBlock(BD,
7257ae0e2c9SDimitry Andric       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
72659d1ed5bSDimitry Andric   else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
7272754fe60SDimitry Andric     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
72859d1ed5bSDimitry Andric   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
7292754fe60SDimitry Andric     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
7302754fe60SDimitry Andric   else
7312754fe60SDimitry Andric     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
73259d1ed5bSDimitry Andric 
73339d628a0SDimitry Andric   auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
73439d628a0SDimitry Andric   return Result.first->first();
735f22ef01cSRoman Divacky }
736f22ef01cSRoman Divacky 
7376122f3e6SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
738f22ef01cSRoman Divacky   return getModule().getNamedValue(Name);
739f22ef01cSRoman Divacky }
740f22ef01cSRoman Divacky 
741f22ef01cSRoman Divacky /// AddGlobalCtor - Add a function to the list that will be called before
742f22ef01cSRoman Divacky /// main() runs.
74359d1ed5bSDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
74459d1ed5bSDimitry Andric                                   llvm::Constant *AssociatedData) {
745f22ef01cSRoman Divacky   // FIXME: Type coercion of void()* types.
74659d1ed5bSDimitry Andric   GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
747f22ef01cSRoman Divacky }
748f22ef01cSRoman Divacky 
749f22ef01cSRoman Divacky /// AddGlobalDtor - Add a function to the list that will be called
750f22ef01cSRoman Divacky /// when the module is unloaded.
751f22ef01cSRoman Divacky void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
752f22ef01cSRoman Divacky   // FIXME: Type coercion of void()* types.
75359d1ed5bSDimitry Andric   GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
754f22ef01cSRoman Divacky }
755f22ef01cSRoman Divacky 
75644290647SDimitry Andric void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
75744290647SDimitry Andric   if (Fns.empty()) return;
75844290647SDimitry Andric 
759f22ef01cSRoman Divacky   // Ctor function type is void()*.
760bd5abe19SDimitry Andric   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
761f22ef01cSRoman Divacky   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
762f22ef01cSRoman Divacky 
76359d1ed5bSDimitry Andric   // Get the type of a ctor entry, { i32, void ()*, i8* }.
76459d1ed5bSDimitry Andric   llvm::StructType *CtorStructTy = llvm::StructType::get(
7655517e702SDimitry Andric       Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy);
766f22ef01cSRoman Divacky 
767f22ef01cSRoman Divacky   // Construct the constructor and destructor arrays.
76844290647SDimitry Andric   ConstantInitBuilder builder(*this);
76944290647SDimitry Andric   auto ctors = builder.beginArray(CtorStructTy);
7708f0fd8f6SDimitry Andric   for (const auto &I : Fns) {
77144290647SDimitry Andric     auto ctor = ctors.beginStruct(CtorStructTy);
77244290647SDimitry Andric     ctor.addInt(Int32Ty, I.Priority);
77344290647SDimitry Andric     ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
77444290647SDimitry Andric     if (I.AssociatedData)
77544290647SDimitry Andric       ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
77644290647SDimitry Andric     else
77744290647SDimitry Andric       ctor.addNullPointer(VoidPtrTy);
77844290647SDimitry Andric     ctor.finishAndAddTo(ctors);
779f22ef01cSRoman Divacky   }
780f22ef01cSRoman Divacky 
78144290647SDimitry Andric   auto list =
78244290647SDimitry Andric     ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
78344290647SDimitry Andric                                 /*constant*/ false,
78444290647SDimitry Andric                                 llvm::GlobalValue::AppendingLinkage);
78544290647SDimitry Andric 
78644290647SDimitry Andric   // The LTO linker doesn't seem to like it when we set an alignment
78744290647SDimitry Andric   // on appending variables.  Take it off as a workaround.
78844290647SDimitry Andric   list->setAlignment(0);
78944290647SDimitry Andric 
79044290647SDimitry Andric   Fns.clear();
791f22ef01cSRoman Divacky }
792f22ef01cSRoman Divacky 
793f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes
794f785676fSDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
79559d1ed5bSDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
796f785676fSDimitry Andric 
797e580952dSDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
798f22ef01cSRoman Divacky 
79959d1ed5bSDimitry Andric   if (isa<CXXDestructorDecl>(D) &&
80059d1ed5bSDimitry Andric       getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
80159d1ed5bSDimitry Andric                                          GD.getDtorType())) {
80259d1ed5bSDimitry Andric     // Destructor variants in the Microsoft C++ ABI are always internal or
80359d1ed5bSDimitry Andric     // linkonce_odr thunks emitted on an as-needed basis.
80459d1ed5bSDimitry Andric     return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
80559d1ed5bSDimitry Andric                                    : llvm::GlobalValue::LinkOnceODRLinkage;
806f22ef01cSRoman Divacky   }
807f22ef01cSRoman Divacky 
808e7145dcbSDimitry Andric   if (isa<CXXConstructorDecl>(D) &&
809e7145dcbSDimitry Andric       cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
810e7145dcbSDimitry Andric       Context.getTargetInfo().getCXXABI().isMicrosoft()) {
811e7145dcbSDimitry Andric     // Our approach to inheriting constructors is fundamentally different from
812e7145dcbSDimitry Andric     // that used by the MS ABI, so keep our inheriting constructor thunks
813e7145dcbSDimitry Andric     // internal rather than trying to pick an unambiguous mangling for them.
814e7145dcbSDimitry Andric     return llvm::GlobalValue::InternalLinkage;
815e7145dcbSDimitry Andric   }
816e7145dcbSDimitry Andric 
81759d1ed5bSDimitry Andric   return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
81859d1ed5bSDimitry Andric }
819f22ef01cSRoman Divacky 
82097bc6c73SDimitry Andric void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
82197bc6c73SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
82297bc6c73SDimitry Andric 
82397bc6c73SDimitry Andric   if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
82497bc6c73SDimitry Andric     if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
82597bc6c73SDimitry Andric       // Don't dllexport/import destructor thunks.
82697bc6c73SDimitry Andric       F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
82797bc6c73SDimitry Andric       return;
82897bc6c73SDimitry Andric     }
82997bc6c73SDimitry Andric   }
83097bc6c73SDimitry Andric 
83197bc6c73SDimitry Andric   if (FD->hasAttr<DLLImportAttr>())
83297bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
83397bc6c73SDimitry Andric   else if (FD->hasAttr<DLLExportAttr>())
83497bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
83597bc6c73SDimitry Andric   else
83697bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
83797bc6c73SDimitry Andric }
83897bc6c73SDimitry Andric 
839e7145dcbSDimitry Andric llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
8400623d748SDimitry Andric   llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
8410623d748SDimitry Andric   if (!MDS) return nullptr;
8420623d748SDimitry Andric 
84344290647SDimitry Andric   return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
8440623d748SDimitry Andric }
8450623d748SDimitry Andric 
84659d1ed5bSDimitry Andric void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
84759d1ed5bSDimitry Andric                                                     llvm::Function *F) {
84859d1ed5bSDimitry Andric   setNonAliasAttributes(D, F);
849f22ef01cSRoman Divacky }
850f22ef01cSRoman Divacky 
851f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
852f22ef01cSRoman Divacky                                               const CGFunctionInfo &Info,
853f22ef01cSRoman Divacky                                               llvm::Function *F) {
854f22ef01cSRoman Divacky   unsigned CallingConv;
8556bc11b14SDimitry Andric   llvm::AttributeList PAL;
8566bc11b14SDimitry Andric   ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false);
8576bc11b14SDimitry Andric   F->setAttributes(PAL);
858f22ef01cSRoman Divacky   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
859f22ef01cSRoman Divacky }
860f22ef01cSRoman Divacky 
8616122f3e6SDimitry Andric /// Determines whether the language options require us to model
8626122f3e6SDimitry Andric /// unwind exceptions.  We treat -fexceptions as mandating this
8636122f3e6SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions
8646122f3e6SDimitry Andric /// enabled.  This means, for example, that C with -fexceptions
8656122f3e6SDimitry Andric /// enables this.
866dff0c46cSDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) {
8676122f3e6SDimitry Andric   // If exceptions are completely disabled, obviously this is false.
868dff0c46cSDimitry Andric   if (!LangOpts.Exceptions) return false;
8696122f3e6SDimitry Andric 
8706122f3e6SDimitry Andric   // If C++ exceptions are enabled, this is true.
871dff0c46cSDimitry Andric   if (LangOpts.CXXExceptions) return true;
8726122f3e6SDimitry Andric 
8736122f3e6SDimitry Andric   // If ObjC exceptions are enabled, this depends on the ABI.
874dff0c46cSDimitry Andric   if (LangOpts.ObjCExceptions) {
8757ae0e2c9SDimitry Andric     return LangOpts.ObjCRuntime.hasUnwindExceptions();
8766122f3e6SDimitry Andric   }
8776122f3e6SDimitry Andric 
8786122f3e6SDimitry Andric   return true;
8796122f3e6SDimitry Andric }
8806122f3e6SDimitry Andric 
881f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
882f22ef01cSRoman Divacky                                                            llvm::Function *F) {
883f785676fSDimitry Andric   llvm::AttrBuilder B;
884f785676fSDimitry Andric 
885bd5abe19SDimitry Andric   if (CodeGenOpts.UnwindTables)
886f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::UWTable);
887bd5abe19SDimitry Andric 
888dff0c46cSDimitry Andric   if (!hasUnwindExceptions(LangOpts))
889f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoUnwind);
890f22ef01cSRoman Divacky 
8910623d748SDimitry Andric   if (LangOpts.getStackProtector() == LangOptions::SSPOn)
8920623d748SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtect);
8930623d748SDimitry Andric   else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
8940623d748SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtectStrong);
8950623d748SDimitry Andric   else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
8960623d748SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtectReq);
8970623d748SDimitry Andric 
8980623d748SDimitry Andric   if (!D) {
89944290647SDimitry Andric     // If we don't have a declaration to control inlining, the function isn't
90044290647SDimitry Andric     // explicitly marked as alwaysinline for semantic reasons, and inlining is
90144290647SDimitry Andric     // disabled, mark the function as noinline.
90244290647SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
90344290647SDimitry Andric         CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
90444290647SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
90544290647SDimitry Andric 
906f37b6182SDimitry Andric     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
9070623d748SDimitry Andric     return;
9080623d748SDimitry Andric   }
9090623d748SDimitry Andric 
910302affcbSDimitry Andric   // Track whether we need to add the optnone LLVM attribute,
911302affcbSDimitry Andric   // starting with the default for this optimization level.
912302affcbSDimitry Andric   bool ShouldAddOptNone =
913302affcbSDimitry Andric       !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
914302affcbSDimitry Andric   // We can't add optnone in the following cases, it won't pass the verifier.
915302affcbSDimitry Andric   ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
916302affcbSDimitry Andric   ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
917302affcbSDimitry Andric   ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
918302affcbSDimitry Andric 
919302affcbSDimitry Andric   if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) {
92044290647SDimitry Andric     B.addAttribute(llvm::Attribute::OptimizeNone);
92144290647SDimitry Andric 
92244290647SDimitry Andric     // OptimizeNone implies noinline; we should not be inlining such functions.
92344290647SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
92444290647SDimitry Andric     assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
92544290647SDimitry Andric            "OptimizeNone and AlwaysInline on same function!");
92644290647SDimitry Andric 
92744290647SDimitry Andric     // We still need to handle naked functions even though optnone subsumes
92844290647SDimitry Andric     // much of their semantics.
92944290647SDimitry Andric     if (D->hasAttr<NakedAttr>())
93044290647SDimitry Andric       B.addAttribute(llvm::Attribute::Naked);
93144290647SDimitry Andric 
93244290647SDimitry Andric     // OptimizeNone wins over OptimizeForSize and MinSize.
93344290647SDimitry Andric     F->removeFnAttr(llvm::Attribute::OptimizeForSize);
93444290647SDimitry Andric     F->removeFnAttr(llvm::Attribute::MinSize);
93544290647SDimitry Andric   } else if (D->hasAttr<NakedAttr>()) {
9366122f3e6SDimitry Andric     // Naked implies noinline: we should not be inlining such functions.
937f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::Naked);
938f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
93959d1ed5bSDimitry Andric   } else if (D->hasAttr<NoDuplicateAttr>()) {
94059d1ed5bSDimitry Andric     B.addAttribute(llvm::Attribute::NoDuplicate);
941f785676fSDimitry Andric   } else if (D->hasAttr<NoInlineAttr>()) {
942f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
94359d1ed5bSDimitry Andric   } else if (D->hasAttr<AlwaysInlineAttr>() &&
94444290647SDimitry Andric              !F->hasFnAttribute(llvm::Attribute::NoInline)) {
945f785676fSDimitry Andric     // (noinline wins over always_inline, and we can't specify both in IR)
946f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::AlwaysInline);
94744290647SDimitry Andric   } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
94844290647SDimitry Andric     // If we're not inlining, then force everything that isn't always_inline to
94944290647SDimitry Andric     // carry an explicit noinline attribute.
95044290647SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
95144290647SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
95244290647SDimitry Andric   } else {
95344290647SDimitry Andric     // Otherwise, propagate the inline hint attribute and potentially use its
95444290647SDimitry Andric     // absence to mark things as noinline.
95544290647SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
95644290647SDimitry Andric       if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
95744290647SDimitry Andric             return Redecl->isInlineSpecified();
95844290647SDimitry Andric           })) {
95944290647SDimitry Andric         B.addAttribute(llvm::Attribute::InlineHint);
96044290647SDimitry Andric       } else if (CodeGenOpts.getInlining() ==
96144290647SDimitry Andric                      CodeGenOptions::OnlyHintInlining &&
96244290647SDimitry Andric                  !FD->isInlined() &&
96344290647SDimitry Andric                  !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
96444290647SDimitry Andric         B.addAttribute(llvm::Attribute::NoInline);
96544290647SDimitry Andric       }
96644290647SDimitry Andric     }
9676122f3e6SDimitry Andric   }
9682754fe60SDimitry Andric 
96944290647SDimitry Andric   // Add other optimization related attributes if we are optimizing this
97044290647SDimitry Andric   // function.
97144290647SDimitry Andric   if (!D->hasAttr<OptimizeNoneAttr>()) {
972f785676fSDimitry Andric     if (D->hasAttr<ColdAttr>()) {
973302affcbSDimitry Andric       if (!ShouldAddOptNone)
974f785676fSDimitry Andric         B.addAttribute(llvm::Attribute::OptimizeForSize);
975f785676fSDimitry Andric       B.addAttribute(llvm::Attribute::Cold);
976f785676fSDimitry Andric     }
9773861d79fSDimitry Andric 
9783861d79fSDimitry Andric     if (D->hasAttr<MinSizeAttr>())
979f785676fSDimitry Andric       B.addAttribute(llvm::Attribute::MinSize);
98044290647SDimitry Andric   }
981f22ef01cSRoman Divacky 
982f37b6182SDimitry Andric   F->addAttributes(llvm::AttributeList::FunctionIndex, B);
983f785676fSDimitry Andric 
984e580952dSDimitry Andric   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
985e580952dSDimitry Andric   if (alignment)
986e580952dSDimitry Andric     F->setAlignment(alignment);
987e580952dSDimitry Andric 
9880623d748SDimitry Andric   // Some C++ ABIs require 2-byte alignment for member functions, in order to
9890623d748SDimitry Andric   // reserve a bit for differentiating between virtual and non-virtual member
9900623d748SDimitry Andric   // functions. If the current target's C++ ABI requires this and this is a
9910623d748SDimitry Andric   // member function, set its alignment accordingly.
9920623d748SDimitry Andric   if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
993f22ef01cSRoman Divacky     if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
994f22ef01cSRoman Divacky       F->setAlignment(2);
995f22ef01cSRoman Divacky   }
99644290647SDimitry Andric 
99744290647SDimitry Andric   // In the cross-dso CFI mode, we want !type attributes on definitions only.
99844290647SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
99944290647SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D))
100044290647SDimitry Andric       CreateFunctionTypeMetadata(FD, F);
10010623d748SDimitry Andric }
1002f22ef01cSRoman Divacky 
1003f22ef01cSRoman Divacky void CodeGenModule::SetCommonAttributes(const Decl *D,
1004f22ef01cSRoman Divacky                                         llvm::GlobalValue *GV) {
10050623d748SDimitry Andric   if (const auto *ND = dyn_cast_or_null<NamedDecl>(D))
10062754fe60SDimitry Andric     setGlobalVisibility(GV, ND);
10072754fe60SDimitry Andric   else
10082754fe60SDimitry Andric     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1009f22ef01cSRoman Divacky 
10100623d748SDimitry Andric   if (D && D->hasAttr<UsedAttr>())
101159d1ed5bSDimitry Andric     addUsedGlobal(GV);
101259d1ed5bSDimitry Andric }
101359d1ed5bSDimitry Andric 
101439d628a0SDimitry Andric void CodeGenModule::setAliasAttributes(const Decl *D,
101539d628a0SDimitry Andric                                        llvm::GlobalValue *GV) {
101639d628a0SDimitry Andric   SetCommonAttributes(D, GV);
101739d628a0SDimitry Andric 
101839d628a0SDimitry Andric   // Process the dllexport attribute based on whether the original definition
101939d628a0SDimitry Andric   // (not necessarily the aliasee) was exported.
102039d628a0SDimitry Andric   if (D->hasAttr<DLLExportAttr>())
102139d628a0SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
102239d628a0SDimitry Andric }
102339d628a0SDimitry Andric 
102459d1ed5bSDimitry Andric void CodeGenModule::setNonAliasAttributes(const Decl *D,
102559d1ed5bSDimitry Andric                                           llvm::GlobalObject *GO) {
102659d1ed5bSDimitry Andric   SetCommonAttributes(D, GO);
1027f22ef01cSRoman Divacky 
10280623d748SDimitry Andric   if (D)
1029f22ef01cSRoman Divacky     if (const SectionAttr *SA = D->getAttr<SectionAttr>())
103059d1ed5bSDimitry Andric       GO->setSection(SA->getName());
1031f22ef01cSRoman Divacky 
103297bc6c73SDimitry Andric   getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
1033f22ef01cSRoman Divacky }
1034f22ef01cSRoman Divacky 
1035f22ef01cSRoman Divacky void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
1036f22ef01cSRoman Divacky                                                   llvm::Function *F,
1037f22ef01cSRoman Divacky                                                   const CGFunctionInfo &FI) {
1038f22ef01cSRoman Divacky   SetLLVMFunctionAttributes(D, FI, F);
1039f22ef01cSRoman Divacky   SetLLVMFunctionAttributesForDefinition(D, F);
1040f22ef01cSRoman Divacky 
1041f22ef01cSRoman Divacky   F->setLinkage(llvm::Function::InternalLinkage);
1042f22ef01cSRoman Divacky 
104359d1ed5bSDimitry Andric   setNonAliasAttributes(D, F);
104459d1ed5bSDimitry Andric }
104559d1ed5bSDimitry Andric 
104659d1ed5bSDimitry Andric static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
104759d1ed5bSDimitry Andric                                          const NamedDecl *ND) {
104859d1ed5bSDimitry Andric   // Set linkage and visibility in case we never see a definition.
104959d1ed5bSDimitry Andric   LinkageInfo LV = ND->getLinkageAndVisibility();
105059d1ed5bSDimitry Andric   if (LV.getLinkage() != ExternalLinkage) {
105159d1ed5bSDimitry Andric     // Don't set internal linkage on declarations.
105259d1ed5bSDimitry Andric   } else {
105359d1ed5bSDimitry Andric     if (ND->hasAttr<DLLImportAttr>()) {
105459d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
105559d1ed5bSDimitry Andric       GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
105659d1ed5bSDimitry Andric     } else if (ND->hasAttr<DLLExportAttr>()) {
105759d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
105859d1ed5bSDimitry Andric     } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
105959d1ed5bSDimitry Andric       // "extern_weak" is overloaded in LLVM; we probably should have
106059d1ed5bSDimitry Andric       // separate linkage types for this.
106159d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
106259d1ed5bSDimitry Andric     }
106359d1ed5bSDimitry Andric 
106459d1ed5bSDimitry Andric     // Set visibility on a declaration only if it's explicit.
106559d1ed5bSDimitry Andric     if (LV.isVisibilityExplicit())
106659d1ed5bSDimitry Andric       GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
106759d1ed5bSDimitry Andric   }
1068f22ef01cSRoman Divacky }
1069f22ef01cSRoman Divacky 
1070e7145dcbSDimitry Andric void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD,
10710623d748SDimitry Andric                                                llvm::Function *F) {
10720623d748SDimitry Andric   // Only if we are checking indirect calls.
10730623d748SDimitry Andric   if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
10740623d748SDimitry Andric     return;
10750623d748SDimitry Andric 
10760623d748SDimitry Andric   // Non-static class methods are handled via vtable pointer checks elsewhere.
10770623d748SDimitry Andric   if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
10780623d748SDimitry Andric     return;
10790623d748SDimitry Andric 
10800623d748SDimitry Andric   // Additionally, if building with cross-DSO support...
10810623d748SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
10820623d748SDimitry Andric     // Skip available_externally functions. They won't be codegen'ed in the
10830623d748SDimitry Andric     // current module anyway.
10840623d748SDimitry Andric     if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
10850623d748SDimitry Andric       return;
10860623d748SDimitry Andric   }
10870623d748SDimitry Andric 
10880623d748SDimitry Andric   llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
1089e7145dcbSDimitry Andric   F->addTypeMetadata(0, MD);
10900623d748SDimitry Andric 
10910623d748SDimitry Andric   // Emit a hash-based bit set entry for cross-DSO calls.
1092e7145dcbSDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
1093e7145dcbSDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1094e7145dcbSDimitry Andric       F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
10950623d748SDimitry Andric }
10960623d748SDimitry Andric 
109739d628a0SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
109839d628a0SDimitry Andric                                           bool IsIncompleteFunction,
109939d628a0SDimitry Andric                                           bool IsThunk) {
110033956c43SDimitry Andric   if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
11013b0f4066SDimitry Andric     // If this is an intrinsic function, set the function's attributes
11023b0f4066SDimitry Andric     // to the intrinsic's attributes.
110333956c43SDimitry Andric     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
11043b0f4066SDimitry Andric     return;
11053b0f4066SDimitry Andric   }
11063b0f4066SDimitry Andric 
110759d1ed5bSDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
1108f22ef01cSRoman Divacky 
1109f22ef01cSRoman Divacky   if (!IsIncompleteFunction)
1110dff0c46cSDimitry Andric     SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
1111f22ef01cSRoman Divacky 
111259d1ed5bSDimitry Andric   // Add the Returned attribute for "this", except for iOS 5 and earlier
111359d1ed5bSDimitry Andric   // where substantial code, including the libstdc++ dylib, was compiled with
111459d1ed5bSDimitry Andric   // GCC and does not actually return "this".
111539d628a0SDimitry Andric   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
111644290647SDimitry Andric       !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
1117f785676fSDimitry Andric     assert(!F->arg_empty() &&
1118f785676fSDimitry Andric            F->arg_begin()->getType()
1119f785676fSDimitry Andric              ->canLosslesslyBitCastTo(F->getReturnType()) &&
1120f785676fSDimitry Andric            "unexpected this return");
1121f785676fSDimitry Andric     F->addAttribute(1, llvm::Attribute::Returned);
1122f785676fSDimitry Andric   }
1123f785676fSDimitry Andric 
1124f22ef01cSRoman Divacky   // Only a few attributes are set on declarations; these may later be
1125f22ef01cSRoman Divacky   // overridden by a definition.
1126f22ef01cSRoman Divacky 
112759d1ed5bSDimitry Andric   setLinkageAndVisibilityForGV(F, FD);
11282754fe60SDimitry Andric 
1129f22ef01cSRoman Divacky   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
1130f22ef01cSRoman Divacky     F->setSection(SA->getName());
1131f785676fSDimitry Andric 
1132e7145dcbSDimitry Andric   if (FD->isReplaceableGlobalAllocationFunction()) {
1133f785676fSDimitry Andric     // A replaceable global allocation function does not act like a builtin by
1134f785676fSDimitry Andric     // default, only if it is invoked by a new-expression or delete-expression.
113520e90f04SDimitry Andric     F->addAttribute(llvm::AttributeList::FunctionIndex,
1136f785676fSDimitry Andric                     llvm::Attribute::NoBuiltin);
11370623d748SDimitry Andric 
1138e7145dcbSDimitry Andric     // A sane operator new returns a non-aliasing pointer.
1139e7145dcbSDimitry Andric     // FIXME: Also add NonNull attribute to the return value
1140e7145dcbSDimitry Andric     // for the non-nothrow forms?
1141e7145dcbSDimitry Andric     auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1142e7145dcbSDimitry Andric     if (getCodeGenOpts().AssumeSaneOperatorNew &&
1143e7145dcbSDimitry Andric         (Kind == OO_New || Kind == OO_Array_New))
114420e90f04SDimitry Andric       F->addAttribute(llvm::AttributeList::ReturnIndex,
1145e7145dcbSDimitry Andric                       llvm::Attribute::NoAlias);
1146e7145dcbSDimitry Andric   }
1147e7145dcbSDimitry Andric 
1148e7145dcbSDimitry Andric   if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1149e7145dcbSDimitry Andric     F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1150e7145dcbSDimitry Andric   else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1151e7145dcbSDimitry Andric     if (MD->isVirtual())
1152e7145dcbSDimitry Andric       F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1153e7145dcbSDimitry Andric 
115444290647SDimitry Andric   // Don't emit entries for function declarations in the cross-DSO mode. This
115544290647SDimitry Andric   // is handled with better precision by the receiving DSO.
115644290647SDimitry Andric   if (!CodeGenOpts.SanitizeCfiCrossDso)
1157e7145dcbSDimitry Andric     CreateFunctionTypeMetadata(FD, F);
1158f22ef01cSRoman Divacky }
1159f22ef01cSRoman Divacky 
116059d1ed5bSDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
1161f22ef01cSRoman Divacky   assert(!GV->isDeclaration() &&
1162f22ef01cSRoman Divacky          "Only globals with definition can force usage.");
116397bc6c73SDimitry Andric   LLVMUsed.emplace_back(GV);
1164f22ef01cSRoman Divacky }
1165f22ef01cSRoman Divacky 
116659d1ed5bSDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
116759d1ed5bSDimitry Andric   assert(!GV->isDeclaration() &&
116859d1ed5bSDimitry Andric          "Only globals with definition can force usage.");
116997bc6c73SDimitry Andric   LLVMCompilerUsed.emplace_back(GV);
117059d1ed5bSDimitry Andric }
117159d1ed5bSDimitry Andric 
117259d1ed5bSDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name,
1173f37b6182SDimitry Andric                      std::vector<llvm::WeakTrackingVH> &List) {
1174f22ef01cSRoman Divacky   // Don't create llvm.used if there is no need.
117559d1ed5bSDimitry Andric   if (List.empty())
1176f22ef01cSRoman Divacky     return;
1177f22ef01cSRoman Divacky 
117859d1ed5bSDimitry Andric   // Convert List to what ConstantArray needs.
1179dff0c46cSDimitry Andric   SmallVector<llvm::Constant*, 8> UsedArray;
118059d1ed5bSDimitry Andric   UsedArray.resize(List.size());
118159d1ed5bSDimitry Andric   for (unsigned i = 0, e = List.size(); i != e; ++i) {
1182f22ef01cSRoman Divacky     UsedArray[i] =
118344f7b0dcSDimitry Andric         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
118444f7b0dcSDimitry Andric             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
1185f22ef01cSRoman Divacky   }
1186f22ef01cSRoman Divacky 
1187f22ef01cSRoman Divacky   if (UsedArray.empty())
1188f22ef01cSRoman Divacky     return;
118959d1ed5bSDimitry Andric   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
1190f22ef01cSRoman Divacky 
119159d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
119259d1ed5bSDimitry Andric       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
119359d1ed5bSDimitry Andric       llvm::ConstantArray::get(ATy, UsedArray), Name);
1194f22ef01cSRoman Divacky 
1195f22ef01cSRoman Divacky   GV->setSection("llvm.metadata");
1196f22ef01cSRoman Divacky }
1197f22ef01cSRoman Divacky 
119859d1ed5bSDimitry Andric void CodeGenModule::emitLLVMUsed() {
119959d1ed5bSDimitry Andric   emitUsed(*this, "llvm.used", LLVMUsed);
120059d1ed5bSDimitry Andric   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
120159d1ed5bSDimitry Andric }
120259d1ed5bSDimitry Andric 
1203f785676fSDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
120439d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
1205f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1206f785676fSDimitry Andric }
1207f785676fSDimitry Andric 
1208f785676fSDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1209f785676fSDimitry Andric   llvm::SmallString<32> Opt;
1210f785676fSDimitry Andric   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
121139d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1212f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1213f785676fSDimitry Andric }
1214f785676fSDimitry Andric 
1215f785676fSDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) {
1216f785676fSDimitry Andric   llvm::SmallString<24> Opt;
1217f785676fSDimitry Andric   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
121839d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1219f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1220f785676fSDimitry Andric }
1221f785676fSDimitry Andric 
1222139f7f9bSDimitry Andric /// \brief Add link options implied by the given module, including modules
1223139f7f9bSDimitry Andric /// it depends on, using a postorder walk.
122439d628a0SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
122539d628a0SDimitry Andric                                     SmallVectorImpl<llvm::Metadata *> &Metadata,
1226139f7f9bSDimitry Andric                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
1227139f7f9bSDimitry Andric   // Import this module's parent.
122839d628a0SDimitry Andric   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
1229f785676fSDimitry Andric     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
1230139f7f9bSDimitry Andric   }
1231139f7f9bSDimitry Andric 
1232139f7f9bSDimitry Andric   // Import this module's dependencies.
1233139f7f9bSDimitry Andric   for (unsigned I = Mod->Imports.size(); I > 0; --I) {
123439d628a0SDimitry Andric     if (Visited.insert(Mod->Imports[I - 1]).second)
1235f785676fSDimitry Andric       addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
1236139f7f9bSDimitry Andric   }
1237139f7f9bSDimitry Andric 
1238139f7f9bSDimitry Andric   // Add linker options to link against the libraries/frameworks
1239139f7f9bSDimitry Andric   // described by this module.
1240f785676fSDimitry Andric   llvm::LLVMContext &Context = CGM.getLLVMContext();
1241139f7f9bSDimitry Andric   for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
1242f785676fSDimitry Andric     // Link against a framework.  Frameworks are currently Darwin only, so we
1243f785676fSDimitry Andric     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
1244139f7f9bSDimitry Andric     if (Mod->LinkLibraries[I-1].IsFramework) {
124539d628a0SDimitry Andric       llvm::Metadata *Args[2] = {
1246139f7f9bSDimitry Andric           llvm::MDString::get(Context, "-framework"),
124739d628a0SDimitry Andric           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
1248139f7f9bSDimitry Andric 
1249139f7f9bSDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, Args));
1250139f7f9bSDimitry Andric       continue;
1251139f7f9bSDimitry Andric     }
1252139f7f9bSDimitry Andric 
1253139f7f9bSDimitry Andric     // Link against a library.
1254f785676fSDimitry Andric     llvm::SmallString<24> Opt;
1255f785676fSDimitry Andric     CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1256f785676fSDimitry Andric       Mod->LinkLibraries[I-1].Library, Opt);
125739d628a0SDimitry Andric     auto *OptString = llvm::MDString::get(Context, Opt);
1258139f7f9bSDimitry Andric     Metadata.push_back(llvm::MDNode::get(Context, OptString));
1259139f7f9bSDimitry Andric   }
1260139f7f9bSDimitry Andric }
1261139f7f9bSDimitry Andric 
1262139f7f9bSDimitry Andric void CodeGenModule::EmitModuleLinkOptions() {
1263139f7f9bSDimitry Andric   // Collect the set of all of the modules we want to visit to emit link
1264139f7f9bSDimitry Andric   // options, which is essentially the imported modules and all of their
1265139f7f9bSDimitry Andric   // non-explicit child modules.
1266139f7f9bSDimitry Andric   llvm::SetVector<clang::Module *> LinkModules;
1267139f7f9bSDimitry Andric   llvm::SmallPtrSet<clang::Module *, 16> Visited;
1268139f7f9bSDimitry Andric   SmallVector<clang::Module *, 16> Stack;
1269139f7f9bSDimitry Andric 
1270139f7f9bSDimitry Andric   // Seed the stack with imported modules.
1271f1a29dd3SDimitry Andric   for (Module *M : ImportedModules) {
1272f1a29dd3SDimitry Andric     // Do not add any link flags when an implementation TU of a module imports
1273f1a29dd3SDimitry Andric     // a header of that same module.
1274f1a29dd3SDimitry Andric     if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
1275f1a29dd3SDimitry Andric         !getLangOpts().isCompilingModule())
1276f1a29dd3SDimitry Andric       continue;
12778f0fd8f6SDimitry Andric     if (Visited.insert(M).second)
12788f0fd8f6SDimitry Andric       Stack.push_back(M);
1279f1a29dd3SDimitry Andric   }
1280139f7f9bSDimitry Andric 
1281139f7f9bSDimitry Andric   // Find all of the modules to import, making a little effort to prune
1282139f7f9bSDimitry Andric   // non-leaf modules.
1283139f7f9bSDimitry Andric   while (!Stack.empty()) {
1284f785676fSDimitry Andric     clang::Module *Mod = Stack.pop_back_val();
1285139f7f9bSDimitry Andric 
1286139f7f9bSDimitry Andric     bool AnyChildren = false;
1287139f7f9bSDimitry Andric 
1288139f7f9bSDimitry Andric     // Visit the submodules of this module.
1289139f7f9bSDimitry Andric     for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1290139f7f9bSDimitry Andric                                         SubEnd = Mod->submodule_end();
1291139f7f9bSDimitry Andric          Sub != SubEnd; ++Sub) {
1292139f7f9bSDimitry Andric       // Skip explicit children; they need to be explicitly imported to be
1293139f7f9bSDimitry Andric       // linked against.
1294139f7f9bSDimitry Andric       if ((*Sub)->IsExplicit)
1295139f7f9bSDimitry Andric         continue;
1296139f7f9bSDimitry Andric 
129739d628a0SDimitry Andric       if (Visited.insert(*Sub).second) {
1298139f7f9bSDimitry Andric         Stack.push_back(*Sub);
1299139f7f9bSDimitry Andric         AnyChildren = true;
1300139f7f9bSDimitry Andric       }
1301139f7f9bSDimitry Andric     }
1302139f7f9bSDimitry Andric 
1303139f7f9bSDimitry Andric     // We didn't find any children, so add this module to the list of
1304139f7f9bSDimitry Andric     // modules to link against.
1305139f7f9bSDimitry Andric     if (!AnyChildren) {
1306139f7f9bSDimitry Andric       LinkModules.insert(Mod);
1307139f7f9bSDimitry Andric     }
1308139f7f9bSDimitry Andric   }
1309139f7f9bSDimitry Andric 
1310139f7f9bSDimitry Andric   // Add link options for all of the imported modules in reverse topological
1311f785676fSDimitry Andric   // order.  We don't do anything to try to order import link flags with respect
1312f785676fSDimitry Andric   // to linker options inserted by things like #pragma comment().
131339d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 16> MetadataArgs;
1314139f7f9bSDimitry Andric   Visited.clear();
13158f0fd8f6SDimitry Andric   for (Module *M : LinkModules)
13168f0fd8f6SDimitry Andric     if (Visited.insert(M).second)
13178f0fd8f6SDimitry Andric       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
1318139f7f9bSDimitry Andric   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1319f785676fSDimitry Andric   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1320139f7f9bSDimitry Andric 
1321139f7f9bSDimitry Andric   // Add the linker options metadata flag.
1322139f7f9bSDimitry Andric   getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
1323f785676fSDimitry Andric                             llvm::MDNode::get(getLLVMContext(),
1324f785676fSDimitry Andric                                               LinkerOptionsMetadata));
1325139f7f9bSDimitry Andric }
1326139f7f9bSDimitry Andric 
1327f22ef01cSRoman Divacky void CodeGenModule::EmitDeferred() {
1328f22ef01cSRoman Divacky   // Emit code for any potentially referenced deferred decls.  Since a
1329f22ef01cSRoman Divacky   // previously unused static decl may become used during the generation of code
1330f22ef01cSRoman Divacky   // for a static function, iterate until no changes are made.
1331f22ef01cSRoman Divacky 
1332f22ef01cSRoman Divacky   if (!DeferredVTables.empty()) {
1333139f7f9bSDimitry Andric     EmitDeferredVTables();
1334139f7f9bSDimitry Andric 
1335e7145dcbSDimitry Andric     // Emitting a vtable doesn't directly cause more vtables to
1336139f7f9bSDimitry Andric     // become deferred, although it can cause functions to be
1337e7145dcbSDimitry Andric     // emitted that then need those vtables.
1338139f7f9bSDimitry Andric     assert(DeferredVTables.empty());
1339f22ef01cSRoman Divacky   }
1340f22ef01cSRoman Divacky 
1341e7145dcbSDimitry Andric   // Stop if we're out of both deferred vtables and deferred declarations.
134233956c43SDimitry Andric   if (DeferredDeclsToEmit.empty())
134333956c43SDimitry Andric     return;
1344139f7f9bSDimitry Andric 
134533956c43SDimitry Andric   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
134633956c43SDimitry Andric   // work, it will not interfere with this.
1347f37b6182SDimitry Andric   std::vector<GlobalDecl> CurDeclsToEmit;
134833956c43SDimitry Andric   CurDeclsToEmit.swap(DeferredDeclsToEmit);
134933956c43SDimitry Andric 
1350f37b6182SDimitry Andric   for (GlobalDecl &D : CurDeclsToEmit) {
13510623d748SDimitry Andric     // We should call GetAddrOfGlobal with IsForDefinition set to true in order
13520623d748SDimitry Andric     // to get GlobalValue with exactly the type we need, not something that
13530623d748SDimitry Andric     // might had been created for another decl with the same mangled name but
13540623d748SDimitry Andric     // different type.
1355e7145dcbSDimitry Andric     llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
135644290647SDimitry Andric         GetAddrOfGlobal(D, ForDefinition));
1357e7145dcbSDimitry Andric 
1358e7145dcbSDimitry Andric     // In case of different address spaces, we may still get a cast, even with
1359e7145dcbSDimitry Andric     // IsForDefinition equal to true. Query mangled names table to get
1360e7145dcbSDimitry Andric     // GlobalValue.
136139d628a0SDimitry Andric     if (!GV)
136239d628a0SDimitry Andric       GV = GetGlobalValue(getMangledName(D));
136339d628a0SDimitry Andric 
1364e7145dcbSDimitry Andric     // Make sure GetGlobalValue returned non-null.
1365e7145dcbSDimitry Andric     assert(GV);
1366e7145dcbSDimitry Andric 
1367f22ef01cSRoman Divacky     // Check to see if we've already emitted this.  This is necessary
1368f22ef01cSRoman Divacky     // for a couple of reasons: first, decls can end up in the
1369f22ef01cSRoman Divacky     // deferred-decls queue multiple times, and second, decls can end
1370f22ef01cSRoman Divacky     // up with definitions in unusual ways (e.g. by an extern inline
1371f22ef01cSRoman Divacky     // function acquiring a strong function redefinition).  Just
1372f22ef01cSRoman Divacky     // ignore these cases.
1373e7145dcbSDimitry Andric     if (!GV->isDeclaration())
1374f22ef01cSRoman Divacky       continue;
1375f22ef01cSRoman Divacky 
1376f22ef01cSRoman Divacky     // Otherwise, emit the definition and move on to the next one.
137759d1ed5bSDimitry Andric     EmitGlobalDefinition(D, GV);
137833956c43SDimitry Andric 
137933956c43SDimitry Andric     // If we found out that we need to emit more decls, do that recursively.
138033956c43SDimitry Andric     // This has the advantage that the decls are emitted in a DFS and related
138133956c43SDimitry Andric     // ones are close together, which is convenient for testing.
138233956c43SDimitry Andric     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
138333956c43SDimitry Andric       EmitDeferred();
138433956c43SDimitry Andric       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
138533956c43SDimitry Andric     }
1386f22ef01cSRoman Divacky   }
1387f22ef01cSRoman Divacky }
1388f22ef01cSRoman Divacky 
13896122f3e6SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() {
13906122f3e6SDimitry Andric   if (Annotations.empty())
13916122f3e6SDimitry Andric     return;
13926122f3e6SDimitry Andric 
13936122f3e6SDimitry Andric   // Create a new global variable for the ConstantStruct in the Module.
13946122f3e6SDimitry Andric   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
13956122f3e6SDimitry Andric     Annotations[0]->getType(), Annotations.size()), Annotations);
139659d1ed5bSDimitry Andric   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
139759d1ed5bSDimitry Andric                                       llvm::GlobalValue::AppendingLinkage,
139859d1ed5bSDimitry Andric                                       Array, "llvm.global.annotations");
13996122f3e6SDimitry Andric   gv->setSection(AnnotationSection);
14006122f3e6SDimitry Andric }
14016122f3e6SDimitry Andric 
1402139f7f9bSDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1403f785676fSDimitry Andric   llvm::Constant *&AStr = AnnotationStrings[Str];
1404f785676fSDimitry Andric   if (AStr)
1405f785676fSDimitry Andric     return AStr;
14066122f3e6SDimitry Andric 
14076122f3e6SDimitry Andric   // Not found yet, create a new global.
1408dff0c46cSDimitry Andric   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
140959d1ed5bSDimitry Andric   auto *gv =
141059d1ed5bSDimitry Andric       new llvm::GlobalVariable(getModule(), s->getType(), true,
141159d1ed5bSDimitry Andric                                llvm::GlobalValue::PrivateLinkage, s, ".str");
14126122f3e6SDimitry Andric   gv->setSection(AnnotationSection);
1413e7145dcbSDimitry Andric   gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1414f785676fSDimitry Andric   AStr = gv;
14156122f3e6SDimitry Andric   return gv;
14166122f3e6SDimitry Andric }
14176122f3e6SDimitry Andric 
14186122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
14196122f3e6SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
14206122f3e6SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
14216122f3e6SDimitry Andric   if (PLoc.isValid())
14226122f3e6SDimitry Andric     return EmitAnnotationString(PLoc.getFilename());
14236122f3e6SDimitry Andric   return EmitAnnotationString(SM.getBufferName(Loc));
14246122f3e6SDimitry Andric }
14256122f3e6SDimitry Andric 
14266122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
14276122f3e6SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
14286122f3e6SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(L);
14296122f3e6SDimitry Andric   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
14306122f3e6SDimitry Andric     SM.getExpansionLineNumber(L);
14316122f3e6SDimitry Andric   return llvm::ConstantInt::get(Int32Ty, LineNo);
14326122f3e6SDimitry Andric }
14336122f3e6SDimitry Andric 
1434f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1435f22ef01cSRoman Divacky                                                 const AnnotateAttr *AA,
14366122f3e6SDimitry Andric                                                 SourceLocation L) {
14376122f3e6SDimitry Andric   // Get the globals for file name, annotation, and the line number.
14386122f3e6SDimitry Andric   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
14396122f3e6SDimitry Andric                  *UnitGV = EmitAnnotationUnit(L),
14406122f3e6SDimitry Andric                  *LineNoCst = EmitAnnotationLineNo(L);
1441f22ef01cSRoman Divacky 
1442f22ef01cSRoman Divacky   // Create the ConstantStruct for the global annotation.
1443f22ef01cSRoman Divacky   llvm::Constant *Fields[4] = {
14446122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
14456122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
14466122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
14476122f3e6SDimitry Andric     LineNoCst
1448f22ef01cSRoman Divacky   };
144917a519f9SDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
1450f22ef01cSRoman Divacky }
1451f22ef01cSRoman Divacky 
14526122f3e6SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
14536122f3e6SDimitry Andric                                          llvm::GlobalValue *GV) {
14546122f3e6SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
14556122f3e6SDimitry Andric   // Get the struct elements for these annotations.
145659d1ed5bSDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>())
145759d1ed5bSDimitry Andric     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
14586122f3e6SDimitry Andric }
14596122f3e6SDimitry Andric 
146039d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
146139d628a0SDimitry Andric                                            SourceLocation Loc) const {
146239d628a0SDimitry Andric   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
146339d628a0SDimitry Andric   // Blacklist by function name.
146439d628a0SDimitry Andric   if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
146539d628a0SDimitry Andric     return true;
146639d628a0SDimitry Andric   // Blacklist by location.
14670623d748SDimitry Andric   if (Loc.isValid())
146839d628a0SDimitry Andric     return SanitizerBL.isBlacklistedLocation(Loc);
146939d628a0SDimitry Andric   // If location is unknown, this may be a compiler-generated function. Assume
147039d628a0SDimitry Andric   // it's located in the main file.
147139d628a0SDimitry Andric   auto &SM = Context.getSourceManager();
147239d628a0SDimitry Andric   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
147339d628a0SDimitry Andric     return SanitizerBL.isBlacklistedFile(MainFile->getName());
147439d628a0SDimitry Andric   }
147539d628a0SDimitry Andric   return false;
147639d628a0SDimitry Andric }
147739d628a0SDimitry Andric 
147839d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
147939d628a0SDimitry Andric                                            SourceLocation Loc, QualType Ty,
148039d628a0SDimitry Andric                                            StringRef Category) const {
14818f0fd8f6SDimitry Andric   // For now globals can be blacklisted only in ASan and KASan.
14828f0fd8f6SDimitry Andric   if (!LangOpts.Sanitize.hasOneOf(
14838f0fd8f6SDimitry Andric           SanitizerKind::Address | SanitizerKind::KernelAddress))
148439d628a0SDimitry Andric     return false;
148539d628a0SDimitry Andric   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
148639d628a0SDimitry Andric   if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
148739d628a0SDimitry Andric     return true;
148839d628a0SDimitry Andric   if (SanitizerBL.isBlacklistedLocation(Loc, Category))
148939d628a0SDimitry Andric     return true;
149039d628a0SDimitry Andric   // Check global type.
149139d628a0SDimitry Andric   if (!Ty.isNull()) {
149239d628a0SDimitry Andric     // Drill down the array types: if global variable of a fixed type is
149339d628a0SDimitry Andric     // blacklisted, we also don't instrument arrays of them.
149439d628a0SDimitry Andric     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
149539d628a0SDimitry Andric       Ty = AT->getElementType();
149639d628a0SDimitry Andric     Ty = Ty.getCanonicalType().getUnqualifiedType();
149739d628a0SDimitry Andric     // We allow to blacklist only record types (classes, structs etc.)
149839d628a0SDimitry Andric     if (Ty->isRecordType()) {
149939d628a0SDimitry Andric       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
150039d628a0SDimitry Andric       if (SanitizerBL.isBlacklistedType(TypeStr, Category))
150139d628a0SDimitry Andric         return true;
150239d628a0SDimitry Andric     }
150339d628a0SDimitry Andric   }
150439d628a0SDimitry Andric   return false;
150539d628a0SDimitry Andric }
150639d628a0SDimitry Andric 
150720e90f04SDimitry Andric bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
150820e90f04SDimitry Andric                                    StringRef Category) const {
150920e90f04SDimitry Andric   if (!LangOpts.XRayInstrument)
151020e90f04SDimitry Andric     return false;
151120e90f04SDimitry Andric   const auto &XRayFilter = getContext().getXRayFilter();
151220e90f04SDimitry Andric   using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
151320e90f04SDimitry Andric   auto Attr = XRayFunctionFilter::ImbueAttribute::NONE;
151420e90f04SDimitry Andric   if (Loc.isValid())
151520e90f04SDimitry Andric     Attr = XRayFilter.shouldImbueLocation(Loc, Category);
151620e90f04SDimitry Andric   if (Attr == ImbueAttr::NONE)
151720e90f04SDimitry Andric     Attr = XRayFilter.shouldImbueFunction(Fn->getName());
151820e90f04SDimitry Andric   switch (Attr) {
151920e90f04SDimitry Andric   case ImbueAttr::NONE:
152020e90f04SDimitry Andric     return false;
152120e90f04SDimitry Andric   case ImbueAttr::ALWAYS:
152220e90f04SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-always");
152320e90f04SDimitry Andric     break;
1524302affcbSDimitry Andric   case ImbueAttr::ALWAYS_ARG1:
1525302affcbSDimitry Andric     Fn->addFnAttr("function-instrument", "xray-always");
1526302affcbSDimitry Andric     Fn->addFnAttr("xray-log-args", "1");
1527302affcbSDimitry Andric     break;
152820e90f04SDimitry Andric   case ImbueAttr::NEVER:
152920e90f04SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-never");
153020e90f04SDimitry Andric     break;
153120e90f04SDimitry Andric   }
153220e90f04SDimitry Andric   return true;
153320e90f04SDimitry Andric }
153420e90f04SDimitry Andric 
153539d628a0SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
1536e580952dSDimitry Andric   // Never defer when EmitAllDecls is specified.
1537dff0c46cSDimitry Andric   if (LangOpts.EmitAllDecls)
153839d628a0SDimitry Andric     return true;
153939d628a0SDimitry Andric 
154039d628a0SDimitry Andric   return getContext().DeclMustBeEmitted(Global);
154139d628a0SDimitry Andric }
154239d628a0SDimitry Andric 
154339d628a0SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
154439d628a0SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global))
154539d628a0SDimitry Andric     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
154639d628a0SDimitry Andric       // Implicit template instantiations may change linkage if they are later
154739d628a0SDimitry Andric       // explicitly instantiated, so they should not be emitted eagerly.
1548f22ef01cSRoman Divacky       return false;
1549e7145dcbSDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(Global))
1550e7145dcbSDimitry Andric     if (Context.getInlineVariableDefinitionKind(VD) ==
1551e7145dcbSDimitry Andric         ASTContext::InlineVariableDefinitionKind::WeakUnknown)
1552e7145dcbSDimitry Andric       // A definition of an inline constexpr static data member may change
1553e7145dcbSDimitry Andric       // linkage later if it's redeclared outside the class.
1554e7145dcbSDimitry Andric       return false;
1555875ed548SDimitry Andric   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
1556875ed548SDimitry Andric   // codegen for global variables, because they may be marked as threadprivate.
1557875ed548SDimitry Andric   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1558875ed548SDimitry Andric       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
1559875ed548SDimitry Andric     return false;
1560f22ef01cSRoman Divacky 
156139d628a0SDimitry Andric   return true;
1562f22ef01cSRoman Divacky }
1563f22ef01cSRoman Divacky 
15640623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
15653861d79fSDimitry Andric     const CXXUuidofExpr* E) {
15663861d79fSDimitry Andric   // Sema has verified that IIDSource has a __declspec(uuid()), and that its
15673861d79fSDimitry Andric   // well-formed.
1568e7145dcbSDimitry Andric   StringRef Uuid = E->getUuidStr();
1569f785676fSDimitry Andric   std::string Name = "_GUID_" + Uuid.lower();
1570f785676fSDimitry Andric   std::replace(Name.begin(), Name.end(), '-', '_');
15713861d79fSDimitry Andric 
1572e7145dcbSDimitry Andric   // The UUID descriptor should be pointer aligned.
1573e7145dcbSDimitry Andric   CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
15740623d748SDimitry Andric 
15753861d79fSDimitry Andric   // Look for an existing global.
15763861d79fSDimitry Andric   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
15770623d748SDimitry Andric     return ConstantAddress(GV, Alignment);
15783861d79fSDimitry Andric 
157939d628a0SDimitry Andric   llvm::Constant *Init = EmitUuidofInitializer(Uuid);
15803861d79fSDimitry Andric   assert(Init && "failed to initialize as constant");
15813861d79fSDimitry Andric 
158259d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
1583f785676fSDimitry Andric       getModule(), Init->getType(),
1584f785676fSDimitry Andric       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
158533956c43SDimitry Andric   if (supportsCOMDAT())
158633956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
15870623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
15883861d79fSDimitry Andric }
15893861d79fSDimitry Andric 
15900623d748SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1591f22ef01cSRoman Divacky   const AliasAttr *AA = VD->getAttr<AliasAttr>();
1592f22ef01cSRoman Divacky   assert(AA && "No alias?");
1593f22ef01cSRoman Divacky 
15940623d748SDimitry Andric   CharUnits Alignment = getContext().getDeclAlign(VD);
15956122f3e6SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1596f22ef01cSRoman Divacky 
1597f22ef01cSRoman Divacky   // See if there is already something with the target's name in the module.
1598f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
15993861d79fSDimitry Andric   if (Entry) {
16003861d79fSDimitry Andric     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
16010623d748SDimitry Andric     auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
16020623d748SDimitry Andric     return ConstantAddress(Ptr, Alignment);
16033861d79fSDimitry Andric   }
1604f22ef01cSRoman Divacky 
1605f22ef01cSRoman Divacky   llvm::Constant *Aliasee;
1606f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(DeclTy))
16073861d79fSDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
16083861d79fSDimitry Andric                                       GlobalDecl(cast<FunctionDecl>(VD)),
16092754fe60SDimitry Andric                                       /*ForVTable=*/false);
1610f22ef01cSRoman Divacky   else
1611f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
161259d1ed5bSDimitry Andric                                     llvm::PointerType::getUnqual(DeclTy),
161359d1ed5bSDimitry Andric                                     nullptr);
16143861d79fSDimitry Andric 
161559d1ed5bSDimitry Andric   auto *F = cast<llvm::GlobalValue>(Aliasee);
1616f22ef01cSRoman Divacky   F->setLinkage(llvm::Function::ExternalWeakLinkage);
1617f22ef01cSRoman Divacky   WeakRefReferences.insert(F);
1618f22ef01cSRoman Divacky 
16190623d748SDimitry Andric   return ConstantAddress(Aliasee, Alignment);
1620f22ef01cSRoman Divacky }
1621f22ef01cSRoman Divacky 
1622f22ef01cSRoman Divacky void CodeGenModule::EmitGlobal(GlobalDecl GD) {
162359d1ed5bSDimitry Andric   const auto *Global = cast<ValueDecl>(GD.getDecl());
1624f22ef01cSRoman Divacky 
1625f22ef01cSRoman Divacky   // Weak references don't produce any output by themselves.
1626f22ef01cSRoman Divacky   if (Global->hasAttr<WeakRefAttr>())
1627f22ef01cSRoman Divacky     return;
1628f22ef01cSRoman Divacky 
1629f22ef01cSRoman Divacky   // If this is an alias definition (which otherwise looks like a declaration)
1630f22ef01cSRoman Divacky   // emit it now.
1631f22ef01cSRoman Divacky   if (Global->hasAttr<AliasAttr>())
1632f22ef01cSRoman Divacky     return EmitAliasDefinition(GD);
1633f22ef01cSRoman Divacky 
1634e7145dcbSDimitry Andric   // IFunc like an alias whose value is resolved at runtime by calling resolver.
1635e7145dcbSDimitry Andric   if (Global->hasAttr<IFuncAttr>())
1636e7145dcbSDimitry Andric     return emitIFuncDefinition(GD);
1637e7145dcbSDimitry Andric 
16386122f3e6SDimitry Andric   // If this is CUDA, be selective about which declarations we emit.
1639dff0c46cSDimitry Andric   if (LangOpts.CUDA) {
164033956c43SDimitry Andric     if (LangOpts.CUDAIsDevice) {
16416122f3e6SDimitry Andric       if (!Global->hasAttr<CUDADeviceAttr>() &&
16426122f3e6SDimitry Andric           !Global->hasAttr<CUDAGlobalAttr>() &&
16436122f3e6SDimitry Andric           !Global->hasAttr<CUDAConstantAttr>() &&
16446122f3e6SDimitry Andric           !Global->hasAttr<CUDASharedAttr>())
16456122f3e6SDimitry Andric         return;
16466122f3e6SDimitry Andric     } else {
1647e7145dcbSDimitry Andric       // We need to emit host-side 'shadows' for all global
1648e7145dcbSDimitry Andric       // device-side variables because the CUDA runtime needs their
1649e7145dcbSDimitry Andric       // size and host-side address in order to provide access to
1650e7145dcbSDimitry Andric       // their device-side incarnations.
1651e7145dcbSDimitry Andric 
1652e7145dcbSDimitry Andric       // So device-only functions are the only things we skip.
1653e7145dcbSDimitry Andric       if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
1654e7145dcbSDimitry Andric           Global->hasAttr<CUDADeviceAttr>())
16556122f3e6SDimitry Andric         return;
1656e7145dcbSDimitry Andric 
1657e7145dcbSDimitry Andric       assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
1658e7145dcbSDimitry Andric              "Expected Variable or Function");
1659e580952dSDimitry Andric     }
1660e580952dSDimitry Andric   }
1661e580952dSDimitry Andric 
1662e7145dcbSDimitry Andric   if (LangOpts.OpenMP) {
1663ea942507SDimitry Andric     // If this is OpenMP device, check if it is legal to emit this global
1664ea942507SDimitry Andric     // normally.
1665ea942507SDimitry Andric     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
1666ea942507SDimitry Andric       return;
1667e7145dcbSDimitry Andric     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
1668e7145dcbSDimitry Andric       if (MustBeEmitted(Global))
1669e7145dcbSDimitry Andric         EmitOMPDeclareReduction(DRD);
1670e7145dcbSDimitry Andric       return;
1671e7145dcbSDimitry Andric     }
1672e7145dcbSDimitry Andric   }
1673ea942507SDimitry Andric 
16746122f3e6SDimitry Andric   // Ignore declarations, they will be emitted on their first use.
167559d1ed5bSDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
1676f22ef01cSRoman Divacky     // Forward declarations are emitted lazily on first use.
16776122f3e6SDimitry Andric     if (!FD->doesThisDeclarationHaveABody()) {
16786122f3e6SDimitry Andric       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1679f22ef01cSRoman Divacky         return;
16806122f3e6SDimitry Andric 
16816122f3e6SDimitry Andric       StringRef MangledName = getMangledName(GD);
168259d1ed5bSDimitry Andric 
168359d1ed5bSDimitry Andric       // Compute the function info and LLVM type.
168459d1ed5bSDimitry Andric       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
168559d1ed5bSDimitry Andric       llvm::Type *Ty = getTypes().GetFunctionType(FI);
168659d1ed5bSDimitry Andric 
168759d1ed5bSDimitry Andric       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
168859d1ed5bSDimitry Andric                               /*DontDefer=*/false);
16896122f3e6SDimitry Andric       return;
16906122f3e6SDimitry Andric     }
1691f22ef01cSRoman Divacky   } else {
169259d1ed5bSDimitry Andric     const auto *VD = cast<VarDecl>(Global);
1693f22ef01cSRoman Divacky     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1694e7145dcbSDimitry Andric     // We need to emit device-side global CUDA variables even if a
1695e7145dcbSDimitry Andric     // variable does not have a definition -- we still need to define
1696e7145dcbSDimitry Andric     // host-side shadow for it.
1697e7145dcbSDimitry Andric     bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
1698e7145dcbSDimitry Andric                            !VD->hasDefinition() &&
1699e7145dcbSDimitry Andric                            (VD->hasAttr<CUDAConstantAttr>() ||
1700e7145dcbSDimitry Andric                             VD->hasAttr<CUDADeviceAttr>());
1701e7145dcbSDimitry Andric     if (!MustEmitForCuda &&
1702e7145dcbSDimitry Andric         VD->isThisDeclarationADefinition() != VarDecl::Definition &&
1703e7145dcbSDimitry Andric         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
1704e7145dcbSDimitry Andric       // If this declaration may have caused an inline variable definition to
1705e7145dcbSDimitry Andric       // change linkage, make sure that it's emitted.
1706e7145dcbSDimitry Andric       if (Context.getInlineVariableDefinitionKind(VD) ==
1707e7145dcbSDimitry Andric           ASTContext::InlineVariableDefinitionKind::Strong)
1708e7145dcbSDimitry Andric         GetAddrOfGlobalVar(VD);
1709f22ef01cSRoman Divacky       return;
1710f22ef01cSRoman Divacky     }
1711e7145dcbSDimitry Andric   }
1712f22ef01cSRoman Divacky 
171339d628a0SDimitry Andric   // Defer code generation to first use when possible, e.g. if this is an inline
171439d628a0SDimitry Andric   // function. If the global must always be emitted, do it eagerly if possible
171539d628a0SDimitry Andric   // to benefit from cache locality.
171639d628a0SDimitry Andric   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
1717f22ef01cSRoman Divacky     // Emit the definition if it can't be deferred.
1718f22ef01cSRoman Divacky     EmitGlobalDefinition(GD);
1719f22ef01cSRoman Divacky     return;
1720f22ef01cSRoman Divacky   }
1721f22ef01cSRoman Divacky 
1722e580952dSDimitry Andric   // If we're deferring emission of a C++ variable with an
1723e580952dSDimitry Andric   // initializer, remember the order in which it appeared in the file.
1724dff0c46cSDimitry Andric   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1725e580952dSDimitry Andric       cast<VarDecl>(Global)->hasInit()) {
1726e580952dSDimitry Andric     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
172759d1ed5bSDimitry Andric     CXXGlobalInits.push_back(nullptr);
1728e580952dSDimitry Andric   }
1729e580952dSDimitry Andric 
17306122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
1731f37b6182SDimitry Andric   if (GetGlobalValue(MangledName) != nullptr) {
173239d628a0SDimitry Andric     // The value has already been used and should therefore be emitted.
1733f37b6182SDimitry Andric     addDeferredDeclToEmit(GD);
173439d628a0SDimitry Andric   } else if (MustBeEmitted(Global)) {
173539d628a0SDimitry Andric     // The value must be emitted, but cannot be emitted eagerly.
173639d628a0SDimitry Andric     assert(!MayBeEmittedEagerly(Global));
1737f37b6182SDimitry Andric     addDeferredDeclToEmit(GD);
173839d628a0SDimitry Andric   } else {
1739f22ef01cSRoman Divacky     // Otherwise, remember that we saw a deferred decl with this name.  The
1740f22ef01cSRoman Divacky     // first use of the mangled name will cause it to move into
1741f22ef01cSRoman Divacky     // DeferredDeclsToEmit.
1742f22ef01cSRoman Divacky     DeferredDecls[MangledName] = GD;
1743f22ef01cSRoman Divacky   }
1744f22ef01cSRoman Divacky }
1745f22ef01cSRoman Divacky 
174620e90f04SDimitry Andric // Check if T is a class type with a destructor that's not dllimport.
174720e90f04SDimitry Andric static bool HasNonDllImportDtor(QualType T) {
174820e90f04SDimitry Andric   if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
174920e90f04SDimitry Andric     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
175020e90f04SDimitry Andric       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
175120e90f04SDimitry Andric         return true;
175220e90f04SDimitry Andric 
175320e90f04SDimitry Andric   return false;
175420e90f04SDimitry Andric }
175520e90f04SDimitry Andric 
1756f8254f43SDimitry Andric namespace {
1757f8254f43SDimitry Andric   struct FunctionIsDirectlyRecursive :
1758f8254f43SDimitry Andric     public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1759f8254f43SDimitry Andric     const StringRef Name;
1760dff0c46cSDimitry Andric     const Builtin::Context &BI;
1761f8254f43SDimitry Andric     bool Result;
1762dff0c46cSDimitry Andric     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1763dff0c46cSDimitry Andric       Name(N), BI(C), Result(false) {
1764f8254f43SDimitry Andric     }
1765f8254f43SDimitry Andric     typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1766f8254f43SDimitry Andric 
1767f8254f43SDimitry Andric     bool TraverseCallExpr(CallExpr *E) {
1768dff0c46cSDimitry Andric       const FunctionDecl *FD = E->getDirectCallee();
1769dff0c46cSDimitry Andric       if (!FD)
1770f8254f43SDimitry Andric         return true;
1771dff0c46cSDimitry Andric       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1772dff0c46cSDimitry Andric       if (Attr && Name == Attr->getLabel()) {
1773dff0c46cSDimitry Andric         Result = true;
1774dff0c46cSDimitry Andric         return false;
1775dff0c46cSDimitry Andric       }
1776dff0c46cSDimitry Andric       unsigned BuiltinID = FD->getBuiltinID();
17773dac3a9bSDimitry Andric       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
1778f8254f43SDimitry Andric         return true;
17790623d748SDimitry Andric       StringRef BuiltinName = BI.getName(BuiltinID);
1780dff0c46cSDimitry Andric       if (BuiltinName.startswith("__builtin_") &&
1781dff0c46cSDimitry Andric           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1782f8254f43SDimitry Andric         Result = true;
1783f8254f43SDimitry Andric         return false;
1784f8254f43SDimitry Andric       }
1785f8254f43SDimitry Andric       return true;
1786f8254f43SDimitry Andric     }
1787f8254f43SDimitry Andric   };
17880623d748SDimitry Andric 
178920e90f04SDimitry Andric   // Make sure we're not referencing non-imported vars or functions.
17900623d748SDimitry Andric   struct DLLImportFunctionVisitor
17910623d748SDimitry Andric       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
17920623d748SDimitry Andric     bool SafeToInline = true;
17930623d748SDimitry Andric 
179444290647SDimitry Andric     bool shouldVisitImplicitCode() const { return true; }
179544290647SDimitry Andric 
17960623d748SDimitry Andric     bool VisitVarDecl(VarDecl *VD) {
179720e90f04SDimitry Andric       if (VD->getTLSKind()) {
17980623d748SDimitry Andric         // A thread-local variable cannot be imported.
179920e90f04SDimitry Andric         SafeToInline = false;
18000623d748SDimitry Andric         return SafeToInline;
18010623d748SDimitry Andric       }
18020623d748SDimitry Andric 
180320e90f04SDimitry Andric       // A variable definition might imply a destructor call.
180420e90f04SDimitry Andric       if (VD->isThisDeclarationADefinition())
180520e90f04SDimitry Andric         SafeToInline = !HasNonDllImportDtor(VD->getType());
180620e90f04SDimitry Andric 
180720e90f04SDimitry Andric       return SafeToInline;
180820e90f04SDimitry Andric     }
180920e90f04SDimitry Andric 
181020e90f04SDimitry Andric     bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
181120e90f04SDimitry Andric       if (const auto *D = E->getTemporary()->getDestructor())
181220e90f04SDimitry Andric         SafeToInline = D->hasAttr<DLLImportAttr>();
181320e90f04SDimitry Andric       return SafeToInline;
181420e90f04SDimitry Andric     }
181520e90f04SDimitry Andric 
18160623d748SDimitry Andric     bool VisitDeclRefExpr(DeclRefExpr *E) {
18170623d748SDimitry Andric       ValueDecl *VD = E->getDecl();
18180623d748SDimitry Andric       if (isa<FunctionDecl>(VD))
18190623d748SDimitry Andric         SafeToInline = VD->hasAttr<DLLImportAttr>();
18200623d748SDimitry Andric       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
18210623d748SDimitry Andric         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
18220623d748SDimitry Andric       return SafeToInline;
18230623d748SDimitry Andric     }
182420e90f04SDimitry Andric 
182544290647SDimitry Andric     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
182644290647SDimitry Andric       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
182744290647SDimitry Andric       return SafeToInline;
182844290647SDimitry Andric     }
182920e90f04SDimitry Andric 
183020e90f04SDimitry Andric     bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
183120e90f04SDimitry Andric       CXXMethodDecl *M = E->getMethodDecl();
183220e90f04SDimitry Andric       if (!M) {
183320e90f04SDimitry Andric         // Call through a pointer to member function. This is safe to inline.
183420e90f04SDimitry Andric         SafeToInline = true;
183520e90f04SDimitry Andric       } else {
183620e90f04SDimitry Andric         SafeToInline = M->hasAttr<DLLImportAttr>();
183720e90f04SDimitry Andric       }
183820e90f04SDimitry Andric       return SafeToInline;
183920e90f04SDimitry Andric     }
184020e90f04SDimitry Andric 
18410623d748SDimitry Andric     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
18420623d748SDimitry Andric       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
18430623d748SDimitry Andric       return SafeToInline;
18440623d748SDimitry Andric     }
184520e90f04SDimitry Andric 
18460623d748SDimitry Andric     bool VisitCXXNewExpr(CXXNewExpr *E) {
18470623d748SDimitry Andric       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
18480623d748SDimitry Andric       return SafeToInline;
18490623d748SDimitry Andric     }
18500623d748SDimitry Andric   };
1851f8254f43SDimitry Andric }
1852f8254f43SDimitry Andric 
1853dff0c46cSDimitry Andric // isTriviallyRecursive - Check if this function calls another
1854dff0c46cSDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin,
1855dff0c46cSDimitry Andric // ends up pointing to itself.
1856f8254f43SDimitry Andric bool
1857dff0c46cSDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1858dff0c46cSDimitry Andric   StringRef Name;
1859dff0c46cSDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1860dff0c46cSDimitry Andric     // asm labels are a special kind of mangling we have to support.
1861dff0c46cSDimitry Andric     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1862dff0c46cSDimitry Andric     if (!Attr)
1863f8254f43SDimitry Andric       return false;
1864dff0c46cSDimitry Andric     Name = Attr->getLabel();
1865dff0c46cSDimitry Andric   } else {
1866dff0c46cSDimitry Andric     Name = FD->getName();
1867dff0c46cSDimitry Andric   }
1868f8254f43SDimitry Andric 
1869dff0c46cSDimitry Andric   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1870dff0c46cSDimitry Andric   Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1871f8254f43SDimitry Andric   return Walker.Result;
1872f8254f43SDimitry Andric }
1873f8254f43SDimitry Andric 
187444290647SDimitry Andric bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1875f785676fSDimitry Andric   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1876f8254f43SDimitry Andric     return true;
187759d1ed5bSDimitry Andric   const auto *F = cast<FunctionDecl>(GD.getDecl());
187859d1ed5bSDimitry Andric   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1879f8254f43SDimitry Andric     return false;
18800623d748SDimitry Andric 
18810623d748SDimitry Andric   if (F->hasAttr<DLLImportAttr>()) {
18820623d748SDimitry Andric     // Check whether it would be safe to inline this dllimport function.
18830623d748SDimitry Andric     DLLImportFunctionVisitor Visitor;
18840623d748SDimitry Andric     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
18850623d748SDimitry Andric     if (!Visitor.SafeToInline)
18860623d748SDimitry Andric       return false;
188744290647SDimitry Andric 
188844290647SDimitry Andric     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
188944290647SDimitry Andric       // Implicit destructor invocations aren't captured in the AST, so the
189044290647SDimitry Andric       // check above can't see them. Check for them manually here.
189144290647SDimitry Andric       for (const Decl *Member : Dtor->getParent()->decls())
189244290647SDimitry Andric         if (isa<FieldDecl>(Member))
189344290647SDimitry Andric           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
189444290647SDimitry Andric             return false;
189544290647SDimitry Andric       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
189644290647SDimitry Andric         if (HasNonDllImportDtor(B.getType()))
189744290647SDimitry Andric           return false;
189844290647SDimitry Andric     }
18990623d748SDimitry Andric   }
19000623d748SDimitry Andric 
1901f8254f43SDimitry Andric   // PR9614. Avoid cases where the source code is lying to us. An available
1902f8254f43SDimitry Andric   // externally function should have an equivalent function somewhere else,
1903f8254f43SDimitry Andric   // but a function that calls itself is clearly not equivalent to the real
1904f8254f43SDimitry Andric   // implementation.
1905f8254f43SDimitry Andric   // This happens in glibc's btowc and in some configure checks.
1906dff0c46cSDimitry Andric   return !isTriviallyRecursive(F);
1907f8254f43SDimitry Andric }
1908f8254f43SDimitry Andric 
190959d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
191059d1ed5bSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
1911f22ef01cSRoman Divacky 
1912f22ef01cSRoman Divacky   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1913f22ef01cSRoman Divacky                                  Context.getSourceManager(),
1914f22ef01cSRoman Divacky                                  "Generating code for declaration");
1915f22ef01cSRoman Divacky 
1916f785676fSDimitry Andric   if (isa<FunctionDecl>(D)) {
1917ffd1746dSEd Schouten     // At -O0, don't generate IR for functions with available_externally
1918ffd1746dSEd Schouten     // linkage.
1919f785676fSDimitry Andric     if (!shouldEmitFunction(GD))
1920ffd1746dSEd Schouten       return;
1921ffd1746dSEd Schouten 
192259d1ed5bSDimitry Andric     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
1923bd5abe19SDimitry Andric       // Make sure to emit the definition(s) before we emit the thunks.
1924bd5abe19SDimitry Andric       // This is necessary for the generation of certain thunks.
192559d1ed5bSDimitry Andric       if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
192639d628a0SDimitry Andric         ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
192759d1ed5bSDimitry Andric       else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
192839d628a0SDimitry Andric         ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
1929bd5abe19SDimitry Andric       else
193059d1ed5bSDimitry Andric         EmitGlobalFunctionDefinition(GD, GV);
1931bd5abe19SDimitry Andric 
1932f22ef01cSRoman Divacky       if (Method->isVirtual())
1933f22ef01cSRoman Divacky         getVTables().EmitThunks(GD);
1934f22ef01cSRoman Divacky 
1935bd5abe19SDimitry Andric       return;
1936ffd1746dSEd Schouten     }
1937f22ef01cSRoman Divacky 
193859d1ed5bSDimitry Andric     return EmitGlobalFunctionDefinition(GD, GV);
1939ffd1746dSEd Schouten   }
1940f22ef01cSRoman Divacky 
194159d1ed5bSDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
1942e7145dcbSDimitry Andric     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
1943f22ef01cSRoman Divacky 
19446122f3e6SDimitry Andric   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1945f22ef01cSRoman Divacky }
1946f22ef01cSRoman Divacky 
19470623d748SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
19480623d748SDimitry Andric                                                       llvm::Function *NewFn);
19490623d748SDimitry Andric 
1950f22ef01cSRoman Divacky /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1951f22ef01cSRoman Divacky /// module, create and return an llvm Function with the specified type. If there
1952f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially
1953f22ef01cSRoman Divacky /// bitcasted to the right type.
1954f22ef01cSRoman Divacky ///
1955f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this.  This is used
1956f22ef01cSRoman Divacky /// to set the attributes on the function when it is first created.
195720e90f04SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
195820e90f04SDimitry Andric     StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
195920e90f04SDimitry Andric     bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
196044290647SDimitry Andric     ForDefinition_t IsForDefinition) {
1961f785676fSDimitry Andric   const Decl *D = GD.getDecl();
1962f785676fSDimitry Andric 
1963f22ef01cSRoman Divacky   // Lookup the entry, lazily creating it if necessary.
1964f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1965f22ef01cSRoman Divacky   if (Entry) {
19663861d79fSDimitry Andric     if (WeakRefReferences.erase(Entry)) {
1967f785676fSDimitry Andric       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
1968f22ef01cSRoman Divacky       if (FD && !FD->hasAttr<WeakAttr>())
1969f22ef01cSRoman Divacky         Entry->setLinkage(llvm::Function::ExternalLinkage);
1970f22ef01cSRoman Divacky     }
1971f22ef01cSRoman Divacky 
197239d628a0SDimitry Andric     // Handle dropped DLL attributes.
197339d628a0SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
197439d628a0SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
197539d628a0SDimitry Andric 
19760623d748SDimitry Andric     // If there are two attempts to define the same mangled name, issue an
19770623d748SDimitry Andric     // error.
19780623d748SDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
19790623d748SDimitry Andric       GlobalDecl OtherGD;
1980e7145dcbSDimitry Andric       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
1981e7145dcbSDimitry Andric       // to make sure that we issue an error only once.
19820623d748SDimitry Andric       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
19830623d748SDimitry Andric           (GD.getCanonicalDecl().getDecl() !=
19840623d748SDimitry Andric            OtherGD.getCanonicalDecl().getDecl()) &&
19850623d748SDimitry Andric           DiagnosedConflictingDefinitions.insert(GD).second) {
19860623d748SDimitry Andric         getDiags().Report(D->getLocation(),
19870623d748SDimitry Andric                           diag::err_duplicate_mangled_name);
19880623d748SDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
19890623d748SDimitry Andric                           diag::note_previous_definition);
19900623d748SDimitry Andric       }
19910623d748SDimitry Andric     }
19920623d748SDimitry Andric 
19930623d748SDimitry Andric     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
19940623d748SDimitry Andric         (Entry->getType()->getElementType() == Ty)) {
1995f22ef01cSRoman Divacky       return Entry;
19960623d748SDimitry Andric     }
1997f22ef01cSRoman Divacky 
1998f22ef01cSRoman Divacky     // Make sure the result is of the correct type.
19990623d748SDimitry Andric     // (If function is requested for a definition, we always need to create a new
20000623d748SDimitry Andric     // function, not just return a bitcast.)
20010623d748SDimitry Andric     if (!IsForDefinition)
200217a519f9SDimitry Andric       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
2003f22ef01cSRoman Divacky   }
2004f22ef01cSRoman Divacky 
2005f22ef01cSRoman Divacky   // This function doesn't have a complete type (for example, the return
2006f22ef01cSRoman Divacky   // type is an incomplete struct). Use a fake type instead, and make
2007f22ef01cSRoman Divacky   // sure not to try to set attributes.
2008f22ef01cSRoman Divacky   bool IsIncompleteFunction = false;
2009f22ef01cSRoman Divacky 
20106122f3e6SDimitry Andric   llvm::FunctionType *FTy;
2011f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(Ty)) {
2012f22ef01cSRoman Divacky     FTy = cast<llvm::FunctionType>(Ty);
2013f22ef01cSRoman Divacky   } else {
2014bd5abe19SDimitry Andric     FTy = llvm::FunctionType::get(VoidTy, false);
2015f22ef01cSRoman Divacky     IsIncompleteFunction = true;
2016f22ef01cSRoman Divacky   }
2017ffd1746dSEd Schouten 
20180623d748SDimitry Andric   llvm::Function *F =
20190623d748SDimitry Andric       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
20200623d748SDimitry Andric                              Entry ? StringRef() : MangledName, &getModule());
20210623d748SDimitry Andric 
20220623d748SDimitry Andric   // If we already created a function with the same mangled name (but different
20230623d748SDimitry Andric   // type) before, take its name and add it to the list of functions to be
20240623d748SDimitry Andric   // replaced with F at the end of CodeGen.
20250623d748SDimitry Andric   //
20260623d748SDimitry Andric   // This happens if there is a prototype for a function (e.g. "int f()") and
20270623d748SDimitry Andric   // then a definition of a different type (e.g. "int f(int x)").
20280623d748SDimitry Andric   if (Entry) {
20290623d748SDimitry Andric     F->takeName(Entry);
20300623d748SDimitry Andric 
20310623d748SDimitry Andric     // This might be an implementation of a function without a prototype, in
20320623d748SDimitry Andric     // which case, try to do special replacement of calls which match the new
20330623d748SDimitry Andric     // prototype.  The really key thing here is that we also potentially drop
20340623d748SDimitry Andric     // arguments from the call site so as to make a direct call, which makes the
20350623d748SDimitry Andric     // inliner happier and suppresses a number of optimizer warnings (!) about
20360623d748SDimitry Andric     // dropping arguments.
20370623d748SDimitry Andric     if (!Entry->use_empty()) {
20380623d748SDimitry Andric       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
20390623d748SDimitry Andric       Entry->removeDeadConstantUsers();
20400623d748SDimitry Andric     }
20410623d748SDimitry Andric 
20420623d748SDimitry Andric     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
20430623d748SDimitry Andric         F, Entry->getType()->getElementType()->getPointerTo());
20440623d748SDimitry Andric     addGlobalValReplacement(Entry, BC);
20450623d748SDimitry Andric   }
20460623d748SDimitry Andric 
2047f22ef01cSRoman Divacky   assert(F->getName() == MangledName && "name was uniqued!");
2048f785676fSDimitry Andric   if (D)
204939d628a0SDimitry Andric     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
205020e90f04SDimitry Andric   if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
205120e90f04SDimitry Andric     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
2052f37b6182SDimitry Andric     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
2053139f7f9bSDimitry Andric   }
2054f22ef01cSRoman Divacky 
205559d1ed5bSDimitry Andric   if (!DontDefer) {
205659d1ed5bSDimitry Andric     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
205759d1ed5bSDimitry Andric     // each other bottoming out with the base dtor.  Therefore we emit non-base
205859d1ed5bSDimitry Andric     // dtors on usage, even if there is no dtor definition in the TU.
205959d1ed5bSDimitry Andric     if (D && isa<CXXDestructorDecl>(D) &&
206059d1ed5bSDimitry Andric         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
206159d1ed5bSDimitry Andric                                            GD.getDtorType()))
2062f37b6182SDimitry Andric       addDeferredDeclToEmit(GD);
206359d1ed5bSDimitry Andric 
2064f22ef01cSRoman Divacky     // This is the first use or definition of a mangled name.  If there is a
2065f22ef01cSRoman Divacky     // deferred decl with this name, remember that we need to emit it at the end
2066f22ef01cSRoman Divacky     // of the file.
206759d1ed5bSDimitry Andric     auto DDI = DeferredDecls.find(MangledName);
2068f22ef01cSRoman Divacky     if (DDI != DeferredDecls.end()) {
206959d1ed5bSDimitry Andric       // Move the potentially referenced deferred decl to the
207059d1ed5bSDimitry Andric       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
207159d1ed5bSDimitry Andric       // don't need it anymore).
2072f37b6182SDimitry Andric       addDeferredDeclToEmit(DDI->second);
2073f22ef01cSRoman Divacky       DeferredDecls.erase(DDI);
20742754fe60SDimitry Andric 
20752754fe60SDimitry Andric       // Otherwise, there are cases we have to worry about where we're
20762754fe60SDimitry Andric       // using a declaration for which we must emit a definition but where
20772754fe60SDimitry Andric       // we might not find a top-level definition:
20782754fe60SDimitry Andric       //   - member functions defined inline in their classes
20792754fe60SDimitry Andric       //   - friend functions defined inline in some class
20802754fe60SDimitry Andric       //   - special member functions with implicit definitions
20812754fe60SDimitry Andric       // If we ever change our AST traversal to walk into class methods,
20822754fe60SDimitry Andric       // this will be unnecessary.
20832754fe60SDimitry Andric       //
208459d1ed5bSDimitry Andric       // We also don't emit a definition for a function if it's going to be an
208539d628a0SDimitry Andric       // entry in a vtable, unless it's already marked as used.
2086f785676fSDimitry Andric     } else if (getLangOpts().CPlusPlus && D) {
20872754fe60SDimitry Andric       // Look for a declaration that's lexically in a record.
208839d628a0SDimitry Andric       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
208939d628a0SDimitry Andric            FD = FD->getPreviousDecl()) {
20902754fe60SDimitry Andric         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
209139d628a0SDimitry Andric           if (FD->doesThisDeclarationHaveABody()) {
2092f37b6182SDimitry Andric             addDeferredDeclToEmit(GD.getWithDecl(FD));
20932754fe60SDimitry Andric             break;
2094f22ef01cSRoman Divacky           }
2095f22ef01cSRoman Divacky         }
209639d628a0SDimitry Andric       }
2097f22ef01cSRoman Divacky     }
209859d1ed5bSDimitry Andric   }
2099f22ef01cSRoman Divacky 
2100f22ef01cSRoman Divacky   // Make sure the result is of the requested type.
2101f22ef01cSRoman Divacky   if (!IsIncompleteFunction) {
2102f22ef01cSRoman Divacky     assert(F->getType()->getElementType() == Ty);
2103f22ef01cSRoman Divacky     return F;
2104f22ef01cSRoman Divacky   }
2105f22ef01cSRoman Divacky 
210617a519f9SDimitry Andric   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2107f22ef01cSRoman Divacky   return llvm::ConstantExpr::getBitCast(F, PTy);
2108f22ef01cSRoman Divacky }
2109f22ef01cSRoman Divacky 
2110f22ef01cSRoman Divacky /// GetAddrOfFunction - Return the address of the given function.  If Ty is
2111f22ef01cSRoman Divacky /// non-null, then this function will use the specified type if it has to
2112f22ef01cSRoman Divacky /// create it (this occurs when we see a definition of the function).
2113f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
21146122f3e6SDimitry Andric                                                  llvm::Type *Ty,
211559d1ed5bSDimitry Andric                                                  bool ForVTable,
21160623d748SDimitry Andric                                                  bool DontDefer,
211744290647SDimitry Andric                                               ForDefinition_t IsForDefinition) {
2118f22ef01cSRoman Divacky   // If there was no specific requested type, just convert it now.
21190623d748SDimitry Andric   if (!Ty) {
21200623d748SDimitry Andric     const auto *FD = cast<FunctionDecl>(GD.getDecl());
21210623d748SDimitry Andric     auto CanonTy = Context.getCanonicalType(FD->getType());
21220623d748SDimitry Andric     Ty = getTypes().ConvertFunctionType(CanonTy, FD);
21230623d748SDimitry Andric   }
2124ffd1746dSEd Schouten 
21256122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
21260623d748SDimitry Andric   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
212720e90f04SDimitry Andric                                  /*IsThunk=*/false, llvm::AttributeList(),
21280623d748SDimitry Andric                                  IsForDefinition);
2129f22ef01cSRoman Divacky }
2130f22ef01cSRoman Divacky 
213144290647SDimitry Andric static const FunctionDecl *
213244290647SDimitry Andric GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
213344290647SDimitry Andric   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
213444290647SDimitry Andric   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
213544290647SDimitry Andric 
213644290647SDimitry Andric   IdentifierInfo &CII = C.Idents.get(Name);
213744290647SDimitry Andric   for (const auto &Result : DC->lookup(&CII))
213844290647SDimitry Andric     if (const auto FD = dyn_cast<FunctionDecl>(Result))
213944290647SDimitry Andric       return FD;
214044290647SDimitry Andric 
214144290647SDimitry Andric   if (!C.getLangOpts().CPlusPlus)
214244290647SDimitry Andric     return nullptr;
214344290647SDimitry Andric 
214444290647SDimitry Andric   // Demangle the premangled name from getTerminateFn()
214544290647SDimitry Andric   IdentifierInfo &CXXII =
214644290647SDimitry Andric       (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ")
214744290647SDimitry Andric           ? C.Idents.get("terminate")
214844290647SDimitry Andric           : C.Idents.get(Name);
214944290647SDimitry Andric 
215044290647SDimitry Andric   for (const auto &N : {"__cxxabiv1", "std"}) {
215144290647SDimitry Andric     IdentifierInfo &NS = C.Idents.get(N);
215244290647SDimitry Andric     for (const auto &Result : DC->lookup(&NS)) {
215344290647SDimitry Andric       NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
215444290647SDimitry Andric       if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
215544290647SDimitry Andric         for (const auto &Result : LSD->lookup(&NS))
215644290647SDimitry Andric           if ((ND = dyn_cast<NamespaceDecl>(Result)))
215744290647SDimitry Andric             break;
215844290647SDimitry Andric 
215944290647SDimitry Andric       if (ND)
216044290647SDimitry Andric         for (const auto &Result : ND->lookup(&CXXII))
216144290647SDimitry Andric           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
216244290647SDimitry Andric             return FD;
216344290647SDimitry Andric     }
216444290647SDimitry Andric   }
216544290647SDimitry Andric 
216644290647SDimitry Andric   return nullptr;
216744290647SDimitry Andric }
216844290647SDimitry Andric 
2169f22ef01cSRoman Divacky /// CreateRuntimeFunction - Create a new runtime function with the specified
2170f22ef01cSRoman Divacky /// type and name.
2171f22ef01cSRoman Divacky llvm::Constant *
217244290647SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
217320e90f04SDimitry Andric                                      llvm::AttributeList ExtraAttrs,
217444290647SDimitry Andric                                      bool Local) {
217559d1ed5bSDimitry Andric   llvm::Constant *C =
217659d1ed5bSDimitry Andric       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
217744290647SDimitry Andric                               /*DontDefer=*/false, /*IsThunk=*/false,
217844290647SDimitry Andric                               ExtraAttrs);
217944290647SDimitry Andric 
218044290647SDimitry Andric   if (auto *F = dyn_cast<llvm::Function>(C)) {
218144290647SDimitry Andric     if (F->empty()) {
2182139f7f9bSDimitry Andric       F->setCallingConv(getRuntimeCC());
218344290647SDimitry Andric 
218444290647SDimitry Andric       if (!Local && getTriple().isOSBinFormatCOFF() &&
218544290647SDimitry Andric           !getCodeGenOpts().LTOVisibilityPublicStd) {
218644290647SDimitry Andric         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
218744290647SDimitry Andric         if (!FD || FD->hasAttr<DLLImportAttr>()) {
218844290647SDimitry Andric           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
218944290647SDimitry Andric           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
219044290647SDimitry Andric         }
219144290647SDimitry Andric       }
219244290647SDimitry Andric     }
219344290647SDimitry Andric   }
219444290647SDimitry Andric 
2195139f7f9bSDimitry Andric   return C;
2196f22ef01cSRoman Divacky }
2197f22ef01cSRoman Divacky 
219839d628a0SDimitry Andric /// CreateBuiltinFunction - Create a new builtin function with the specified
219939d628a0SDimitry Andric /// type and name.
220039d628a0SDimitry Andric llvm::Constant *
220120e90f04SDimitry Andric CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
220220e90f04SDimitry Andric                                      llvm::AttributeList ExtraAttrs) {
220339d628a0SDimitry Andric   llvm::Constant *C =
220439d628a0SDimitry Andric       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
220539d628a0SDimitry Andric                               /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
220639d628a0SDimitry Andric   if (auto *F = dyn_cast<llvm::Function>(C))
220739d628a0SDimitry Andric     if (F->empty())
220839d628a0SDimitry Andric       F->setCallingConv(getBuiltinCC());
220939d628a0SDimitry Andric   return C;
221039d628a0SDimitry Andric }
221139d628a0SDimitry Andric 
2212dff0c46cSDimitry Andric /// isTypeConstant - Determine whether an object of this type can be emitted
2213dff0c46cSDimitry Andric /// as a constant.
2214dff0c46cSDimitry Andric ///
2215dff0c46cSDimitry Andric /// If ExcludeCtor is true, the duration when the object's constructor runs
2216dff0c46cSDimitry Andric /// will not be considered. The caller will need to verify that the object is
2217dff0c46cSDimitry Andric /// not written to during its construction.
2218dff0c46cSDimitry Andric bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2219dff0c46cSDimitry Andric   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
2220f22ef01cSRoman Divacky     return false;
2221bd5abe19SDimitry Andric 
2222dff0c46cSDimitry Andric   if (Context.getLangOpts().CPlusPlus) {
2223dff0c46cSDimitry Andric     if (const CXXRecordDecl *Record
2224dff0c46cSDimitry Andric           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2225dff0c46cSDimitry Andric       return ExcludeCtor && !Record->hasMutableFields() &&
2226dff0c46cSDimitry Andric              Record->hasTrivialDestructor();
2227f22ef01cSRoman Divacky   }
2228bd5abe19SDimitry Andric 
2229f22ef01cSRoman Divacky   return true;
2230f22ef01cSRoman Divacky }
2231f22ef01cSRoman Divacky 
2232f22ef01cSRoman Divacky /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2233f22ef01cSRoman Divacky /// create and return an llvm GlobalVariable with the specified type.  If there
2234f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially
2235f22ef01cSRoman Divacky /// bitcasted to the right type.
2236f22ef01cSRoman Divacky ///
2237f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this.  This is used
2238f22ef01cSRoman Divacky /// to set the attributes on the global when it is first created.
2239e7145dcbSDimitry Andric ///
2240e7145dcbSDimitry Andric /// If IsForDefinition is true, it is guranteed that an actual global with
2241e7145dcbSDimitry Andric /// type Ty will be returned, not conversion of a variable with the same
2242e7145dcbSDimitry Andric /// mangled name but some other type.
2243f22ef01cSRoman Divacky llvm::Constant *
22446122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
22456122f3e6SDimitry Andric                                      llvm::PointerType *Ty,
2246e7145dcbSDimitry Andric                                      const VarDecl *D,
224744290647SDimitry Andric                                      ForDefinition_t IsForDefinition) {
2248f22ef01cSRoman Divacky   // Lookup the entry, lazily creating it if necessary.
2249f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2250f22ef01cSRoman Divacky   if (Entry) {
22513861d79fSDimitry Andric     if (WeakRefReferences.erase(Entry)) {
2252f22ef01cSRoman Divacky       if (D && !D->hasAttr<WeakAttr>())
2253f22ef01cSRoman Divacky         Entry->setLinkage(llvm::Function::ExternalLinkage);
2254f22ef01cSRoman Divacky     }
2255f22ef01cSRoman Divacky 
225639d628a0SDimitry Andric     // Handle dropped DLL attributes.
225739d628a0SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
225839d628a0SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
225939d628a0SDimitry Andric 
2260f22ef01cSRoman Divacky     if (Entry->getType() == Ty)
2261f22ef01cSRoman Divacky       return Entry;
2262f22ef01cSRoman Divacky 
2263e7145dcbSDimitry Andric     // If there are two attempts to define the same mangled name, issue an
2264e7145dcbSDimitry Andric     // error.
2265e7145dcbSDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
2266e7145dcbSDimitry Andric       GlobalDecl OtherGD;
2267e7145dcbSDimitry Andric       const VarDecl *OtherD;
2268e7145dcbSDimitry Andric 
2269e7145dcbSDimitry Andric       // Check that D is not yet in DiagnosedConflictingDefinitions is required
2270e7145dcbSDimitry Andric       // to make sure that we issue an error only once.
2271e7145dcbSDimitry Andric       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
2272e7145dcbSDimitry Andric           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2273e7145dcbSDimitry Andric           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2274e7145dcbSDimitry Andric           OtherD->hasInit() &&
2275e7145dcbSDimitry Andric           DiagnosedConflictingDefinitions.insert(D).second) {
2276e7145dcbSDimitry Andric         getDiags().Report(D->getLocation(),
2277e7145dcbSDimitry Andric                           diag::err_duplicate_mangled_name);
2278e7145dcbSDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
2279e7145dcbSDimitry Andric                           diag::note_previous_definition);
2280e7145dcbSDimitry Andric       }
2281e7145dcbSDimitry Andric     }
2282e7145dcbSDimitry Andric 
2283f22ef01cSRoman Divacky     // Make sure the result is of the correct type.
2284f785676fSDimitry Andric     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2285f785676fSDimitry Andric       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2286f785676fSDimitry Andric 
2287e7145dcbSDimitry Andric     // (If global is requested for a definition, we always need to create a new
2288e7145dcbSDimitry Andric     // global, not just return a bitcast.)
2289e7145dcbSDimitry Andric     if (!IsForDefinition)
2290f22ef01cSRoman Divacky       return llvm::ConstantExpr::getBitCast(Entry, Ty);
2291f22ef01cSRoman Divacky   }
2292f22ef01cSRoman Divacky 
229359d1ed5bSDimitry Andric   unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
229459d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
229559d1ed5bSDimitry Andric       getModule(), Ty->getElementType(), false,
229659d1ed5bSDimitry Andric       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
229759d1ed5bSDimitry Andric       llvm::GlobalVariable::NotThreadLocal, AddrSpace);
229859d1ed5bSDimitry Andric 
2299e7145dcbSDimitry Andric   // If we already created a global with the same mangled name (but different
2300e7145dcbSDimitry Andric   // type) before, take its name and remove it from its parent.
2301e7145dcbSDimitry Andric   if (Entry) {
2302e7145dcbSDimitry Andric     GV->takeName(Entry);
2303e7145dcbSDimitry Andric 
2304e7145dcbSDimitry Andric     if (!Entry->use_empty()) {
2305e7145dcbSDimitry Andric       llvm::Constant *NewPtrForOldDecl =
2306e7145dcbSDimitry Andric           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2307e7145dcbSDimitry Andric       Entry->replaceAllUsesWith(NewPtrForOldDecl);
2308e7145dcbSDimitry Andric     }
2309e7145dcbSDimitry Andric 
2310e7145dcbSDimitry Andric     Entry->eraseFromParent();
2311e7145dcbSDimitry Andric   }
2312e7145dcbSDimitry Andric 
2313f22ef01cSRoman Divacky   // This is the first use or definition of a mangled name.  If there is a
2314f22ef01cSRoman Divacky   // deferred decl with this name, remember that we need to emit it at the end
2315f22ef01cSRoman Divacky   // of the file.
231659d1ed5bSDimitry Andric   auto DDI = DeferredDecls.find(MangledName);
2317f22ef01cSRoman Divacky   if (DDI != DeferredDecls.end()) {
2318f22ef01cSRoman Divacky     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2319f22ef01cSRoman Divacky     // list, and remove it from DeferredDecls (since we don't need it anymore).
2320f37b6182SDimitry Andric     addDeferredDeclToEmit(DDI->second);
2321f22ef01cSRoman Divacky     DeferredDecls.erase(DDI);
2322f22ef01cSRoman Divacky   }
2323f22ef01cSRoman Divacky 
2324f22ef01cSRoman Divacky   // Handle things which are present even on external declarations.
2325f22ef01cSRoman Divacky   if (D) {
2326f22ef01cSRoman Divacky     // FIXME: This code is overly simple and should be merged with other global
2327f22ef01cSRoman Divacky     // handling.
2328dff0c46cSDimitry Andric     GV->setConstant(isTypeConstant(D->getType(), false));
2329f22ef01cSRoman Divacky 
233033956c43SDimitry Andric     GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
233133956c43SDimitry Andric 
233259d1ed5bSDimitry Andric     setLinkageAndVisibilityForGV(GV, D);
23332754fe60SDimitry Andric 
2334284c1978SDimitry Andric     if (D->getTLSKind()) {
2335284c1978SDimitry Andric       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
23360623d748SDimitry Andric         CXXThreadLocals.push_back(D);
23377ae0e2c9SDimitry Andric       setTLSMode(GV, *D);
2338f22ef01cSRoman Divacky     }
2339f785676fSDimitry Andric 
2340f785676fSDimitry Andric     // If required by the ABI, treat declarations of static data members with
2341f785676fSDimitry Andric     // inline initializers as definitions.
234259d1ed5bSDimitry Andric     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
2343f785676fSDimitry Andric       EmitGlobalVarDefinition(D);
2344284c1978SDimitry Andric     }
2345f22ef01cSRoman Divacky 
234659d1ed5bSDimitry Andric     // Handle XCore specific ABI requirements.
234744290647SDimitry Andric     if (getTriple().getArch() == llvm::Triple::xcore &&
234859d1ed5bSDimitry Andric         D->getLanguageLinkage() == CLanguageLinkage &&
234959d1ed5bSDimitry Andric         D->getType().isConstant(Context) &&
235059d1ed5bSDimitry Andric         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
235159d1ed5bSDimitry Andric       GV->setSection(".cp.rodata");
235259d1ed5bSDimitry Andric   }
235359d1ed5bSDimitry Andric 
23547ae0e2c9SDimitry Andric   if (AddrSpace != Ty->getAddressSpace())
2355f785676fSDimitry Andric     return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
2356f785676fSDimitry Andric 
2357f22ef01cSRoman Divacky   return GV;
2358f22ef01cSRoman Divacky }
2359f22ef01cSRoman Divacky 
23600623d748SDimitry Andric llvm::Constant *
23610623d748SDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
236244290647SDimitry Andric                                ForDefinition_t IsForDefinition) {
236344290647SDimitry Andric   const Decl *D = GD.getDecl();
236444290647SDimitry Andric   if (isa<CXXConstructorDecl>(D))
236544290647SDimitry Andric     return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
23660623d748SDimitry Andric                                 getFromCtorType(GD.getCtorType()),
23670623d748SDimitry Andric                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
23680623d748SDimitry Andric                                 /*DontDefer=*/false, IsForDefinition);
236944290647SDimitry Andric   else if (isa<CXXDestructorDecl>(D))
237044290647SDimitry Andric     return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
23710623d748SDimitry Andric                                 getFromDtorType(GD.getDtorType()),
23720623d748SDimitry Andric                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
23730623d748SDimitry Andric                                 /*DontDefer=*/false, IsForDefinition);
237444290647SDimitry Andric   else if (isa<CXXMethodDecl>(D)) {
23750623d748SDimitry Andric     auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
237644290647SDimitry Andric         cast<CXXMethodDecl>(D));
23770623d748SDimitry Andric     auto Ty = getTypes().GetFunctionType(*FInfo);
23780623d748SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
23790623d748SDimitry Andric                              IsForDefinition);
238044290647SDimitry Andric   } else if (isa<FunctionDecl>(D)) {
23810623d748SDimitry Andric     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
23820623d748SDimitry Andric     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
23830623d748SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
23840623d748SDimitry Andric                              IsForDefinition);
23850623d748SDimitry Andric   } else
238644290647SDimitry Andric     return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
2387e7145dcbSDimitry Andric                               IsForDefinition);
23880623d748SDimitry Andric }
2389f22ef01cSRoman Divacky 
23902754fe60SDimitry Andric llvm::GlobalVariable *
23916122f3e6SDimitry Andric CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
23926122f3e6SDimitry Andric                                       llvm::Type *Ty,
23932754fe60SDimitry Andric                                       llvm::GlobalValue::LinkageTypes Linkage) {
23942754fe60SDimitry Andric   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
239559d1ed5bSDimitry Andric   llvm::GlobalVariable *OldGV = nullptr;
23962754fe60SDimitry Andric 
23972754fe60SDimitry Andric   if (GV) {
23982754fe60SDimitry Andric     // Check if the variable has the right type.
23992754fe60SDimitry Andric     if (GV->getType()->getElementType() == Ty)
24002754fe60SDimitry Andric       return GV;
24012754fe60SDimitry Andric 
24022754fe60SDimitry Andric     // Because C++ name mangling, the only way we can end up with an already
24032754fe60SDimitry Andric     // existing global with the same name is if it has been declared extern "C".
24042754fe60SDimitry Andric     assert(GV->isDeclaration() && "Declaration has wrong type!");
24052754fe60SDimitry Andric     OldGV = GV;
24062754fe60SDimitry Andric   }
24072754fe60SDimitry Andric 
24082754fe60SDimitry Andric   // Create a new variable.
24092754fe60SDimitry Andric   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
241059d1ed5bSDimitry Andric                                 Linkage, nullptr, Name);
24112754fe60SDimitry Andric 
24122754fe60SDimitry Andric   if (OldGV) {
24132754fe60SDimitry Andric     // Replace occurrences of the old variable if needed.
24142754fe60SDimitry Andric     GV->takeName(OldGV);
24152754fe60SDimitry Andric 
24162754fe60SDimitry Andric     if (!OldGV->use_empty()) {
24172754fe60SDimitry Andric       llvm::Constant *NewPtrForOldDecl =
24182754fe60SDimitry Andric       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
24192754fe60SDimitry Andric       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
24202754fe60SDimitry Andric     }
24212754fe60SDimitry Andric 
24222754fe60SDimitry Andric     OldGV->eraseFromParent();
24232754fe60SDimitry Andric   }
24242754fe60SDimitry Andric 
242533956c43SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker() &&
242633956c43SDimitry Andric       !GV->hasAvailableExternallyLinkage())
242733956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
242833956c43SDimitry Andric 
24292754fe60SDimitry Andric   return GV;
24302754fe60SDimitry Andric }
24312754fe60SDimitry Andric 
2432f22ef01cSRoman Divacky /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
2433f22ef01cSRoman Divacky /// given global variable.  If Ty is non-null and if the global doesn't exist,
2434cb4dff85SDimitry Andric /// then it will be created with the specified type instead of whatever the
2435e7145dcbSDimitry Andric /// normal requested type would be. If IsForDefinition is true, it is guranteed
2436e7145dcbSDimitry Andric /// that an actual global with type Ty will be returned, not conversion of a
2437e7145dcbSDimitry Andric /// variable with the same mangled name but some other type.
2438f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
2439e7145dcbSDimitry Andric                                                   llvm::Type *Ty,
244044290647SDimitry Andric                                            ForDefinition_t IsForDefinition) {
2441f22ef01cSRoman Divacky   assert(D->hasGlobalStorage() && "Not a global variable");
2442f22ef01cSRoman Divacky   QualType ASTTy = D->getType();
244359d1ed5bSDimitry Andric   if (!Ty)
2444f22ef01cSRoman Divacky     Ty = getTypes().ConvertTypeForMem(ASTTy);
2445f22ef01cSRoman Divacky 
24466122f3e6SDimitry Andric   llvm::PointerType *PTy =
24473b0f4066SDimitry Andric     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
2448f22ef01cSRoman Divacky 
24496122f3e6SDimitry Andric   StringRef MangledName = getMangledName(D);
2450e7145dcbSDimitry Andric   return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
2451f22ef01cSRoman Divacky }
2452f22ef01cSRoman Divacky 
2453f22ef01cSRoman Divacky /// CreateRuntimeVariable - Create a new runtime global variable with the
2454f22ef01cSRoman Divacky /// specified type and name.
2455f22ef01cSRoman Divacky llvm::Constant *
24566122f3e6SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
24576122f3e6SDimitry Andric                                      StringRef Name) {
245859d1ed5bSDimitry Andric   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
2459f22ef01cSRoman Divacky }
2460f22ef01cSRoman Divacky 
2461f22ef01cSRoman Divacky void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
2462f22ef01cSRoman Divacky   assert(!D->getInit() && "Cannot emit definite definitions here!");
2463f22ef01cSRoman Divacky 
24646122f3e6SDimitry Andric   StringRef MangledName = getMangledName(D);
2465e7145dcbSDimitry Andric   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
2466e7145dcbSDimitry Andric 
2467e7145dcbSDimitry Andric   // We already have a definition, not declaration, with the same mangled name.
2468e7145dcbSDimitry Andric   // Emitting of declaration is not required (and actually overwrites emitted
2469e7145dcbSDimitry Andric   // definition).
2470e7145dcbSDimitry Andric   if (GV && !GV->isDeclaration())
2471e7145dcbSDimitry Andric     return;
2472e7145dcbSDimitry Andric 
2473e7145dcbSDimitry Andric   // If we have not seen a reference to this variable yet, place it into the
2474e7145dcbSDimitry Andric   // deferred declarations table to be emitted if needed later.
2475e7145dcbSDimitry Andric   if (!MustBeEmitted(D) && !GV) {
2476f22ef01cSRoman Divacky       DeferredDecls[MangledName] = D;
2477f22ef01cSRoman Divacky       return;
2478f22ef01cSRoman Divacky   }
2479f22ef01cSRoman Divacky 
2480f22ef01cSRoman Divacky   // The tentative definition is the only definition.
2481f22ef01cSRoman Divacky   EmitGlobalVarDefinition(D);
2482f22ef01cSRoman Divacky }
2483f22ef01cSRoman Divacky 
24846122f3e6SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
24852754fe60SDimitry Andric   return Context.toCharUnitsFromBits(
24860623d748SDimitry Andric       getDataLayout().getTypeStoreSizeInBits(Ty));
2487f22ef01cSRoman Divacky }
2488f22ef01cSRoman Divacky 
24897ae0e2c9SDimitry Andric unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
24907ae0e2c9SDimitry Andric                                                  unsigned AddrSpace) {
2491e7145dcbSDimitry Andric   if (D && LangOpts.CUDA && LangOpts.CUDAIsDevice) {
24927ae0e2c9SDimitry Andric     if (D->hasAttr<CUDAConstantAttr>())
24937ae0e2c9SDimitry Andric       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
24947ae0e2c9SDimitry Andric     else if (D->hasAttr<CUDASharedAttr>())
24957ae0e2c9SDimitry Andric       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
24967ae0e2c9SDimitry Andric     else
24977ae0e2c9SDimitry Andric       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
24987ae0e2c9SDimitry Andric   }
24997ae0e2c9SDimitry Andric 
25007ae0e2c9SDimitry Andric   return AddrSpace;
25017ae0e2c9SDimitry Andric }
25027ae0e2c9SDimitry Andric 
2503284c1978SDimitry Andric template<typename SomeDecl>
2504284c1978SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
2505284c1978SDimitry Andric                                                llvm::GlobalValue *GV) {
2506284c1978SDimitry Andric   if (!getLangOpts().CPlusPlus)
2507284c1978SDimitry Andric     return;
2508284c1978SDimitry Andric 
2509284c1978SDimitry Andric   // Must have 'used' attribute, or else inline assembly can't rely on
2510284c1978SDimitry Andric   // the name existing.
2511284c1978SDimitry Andric   if (!D->template hasAttr<UsedAttr>())
2512284c1978SDimitry Andric     return;
2513284c1978SDimitry Andric 
2514284c1978SDimitry Andric   // Must have internal linkage and an ordinary name.
2515f785676fSDimitry Andric   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
2516284c1978SDimitry Andric     return;
2517284c1978SDimitry Andric 
2518284c1978SDimitry Andric   // Must be in an extern "C" context. Entities declared directly within
2519284c1978SDimitry Andric   // a record are not extern "C" even if the record is in such a context.
2520f785676fSDimitry Andric   const SomeDecl *First = D->getFirstDecl();
2521284c1978SDimitry Andric   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
2522284c1978SDimitry Andric     return;
2523284c1978SDimitry Andric 
2524284c1978SDimitry Andric   // OK, this is an internal linkage entity inside an extern "C" linkage
2525284c1978SDimitry Andric   // specification. Make a note of that so we can give it the "expected"
2526284c1978SDimitry Andric   // mangled name if nothing else is using that name.
2527284c1978SDimitry Andric   std::pair<StaticExternCMap::iterator, bool> R =
2528284c1978SDimitry Andric       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
2529284c1978SDimitry Andric 
2530284c1978SDimitry Andric   // If we have multiple internal linkage entities with the same name
2531284c1978SDimitry Andric   // in extern "C" regions, none of them gets that name.
2532284c1978SDimitry Andric   if (!R.second)
253359d1ed5bSDimitry Andric     R.first->second = nullptr;
2534284c1978SDimitry Andric }
2535284c1978SDimitry Andric 
253633956c43SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
253733956c43SDimitry Andric   if (!CGM.supportsCOMDAT())
253833956c43SDimitry Andric     return false;
253933956c43SDimitry Andric 
254033956c43SDimitry Andric   if (D.hasAttr<SelectAnyAttr>())
254133956c43SDimitry Andric     return true;
254233956c43SDimitry Andric 
254333956c43SDimitry Andric   GVALinkage Linkage;
254433956c43SDimitry Andric   if (auto *VD = dyn_cast<VarDecl>(&D))
254533956c43SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
254633956c43SDimitry Andric   else
254733956c43SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
254833956c43SDimitry Andric 
254933956c43SDimitry Andric   switch (Linkage) {
255033956c43SDimitry Andric   case GVA_Internal:
255133956c43SDimitry Andric   case GVA_AvailableExternally:
255233956c43SDimitry Andric   case GVA_StrongExternal:
255333956c43SDimitry Andric     return false;
255433956c43SDimitry Andric   case GVA_DiscardableODR:
255533956c43SDimitry Andric   case GVA_StrongODR:
255633956c43SDimitry Andric     return true;
255733956c43SDimitry Andric   }
255833956c43SDimitry Andric   llvm_unreachable("No such linkage");
255933956c43SDimitry Andric }
256033956c43SDimitry Andric 
256133956c43SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
256233956c43SDimitry Andric                                           llvm::GlobalObject &GO) {
256333956c43SDimitry Andric   if (!shouldBeInCOMDAT(*this, D))
256433956c43SDimitry Andric     return;
256533956c43SDimitry Andric   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
256633956c43SDimitry Andric }
256733956c43SDimitry Andric 
2568e7145dcbSDimitry Andric /// Pass IsTentative as true if you want to create a tentative definition.
2569e7145dcbSDimitry Andric void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
2570e7145dcbSDimitry Andric                                             bool IsTentative) {
257144290647SDimitry Andric   // OpenCL global variables of sampler type are translated to function calls,
257244290647SDimitry Andric   // therefore no need to be translated.
2573f22ef01cSRoman Divacky   QualType ASTTy = D->getType();
257444290647SDimitry Andric   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
257544290647SDimitry Andric     return;
257644290647SDimitry Andric 
257744290647SDimitry Andric   llvm::Constant *Init = nullptr;
2578dff0c46cSDimitry Andric   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2579dff0c46cSDimitry Andric   bool NeedsGlobalCtor = false;
2580dff0c46cSDimitry Andric   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
2581f22ef01cSRoman Divacky 
2582dff0c46cSDimitry Andric   const VarDecl *InitDecl;
2583dff0c46cSDimitry Andric   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
2584f22ef01cSRoman Divacky 
2585e7145dcbSDimitry Andric   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
2586e7145dcbSDimitry Andric   // as part of their declaration."  Sema has already checked for
2587e7145dcbSDimitry Andric   // error cases, so we just need to set Init to UndefValue.
2588e7145dcbSDimitry Andric   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
2589e7145dcbSDimitry Andric       D->hasAttr<CUDASharedAttr>())
25900623d748SDimitry Andric     Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
2591e7145dcbSDimitry Andric   else if (!InitExpr) {
2592f22ef01cSRoman Divacky     // This is a tentative definition; tentative definitions are
2593f22ef01cSRoman Divacky     // implicitly initialized with { 0 }.
2594f22ef01cSRoman Divacky     //
2595f22ef01cSRoman Divacky     // Note that tentative definitions are only emitted at the end of
2596f22ef01cSRoman Divacky     // a translation unit, so they should never have incomplete
2597f22ef01cSRoman Divacky     // type. In addition, EmitTentativeDefinition makes sure that we
2598f22ef01cSRoman Divacky     // never attempt to emit a tentative definition if a real one
2599f22ef01cSRoman Divacky     // exists. A use may still exists, however, so we still may need
2600f22ef01cSRoman Divacky     // to do a RAUW.
2601f22ef01cSRoman Divacky     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
2602f22ef01cSRoman Divacky     Init = EmitNullConstant(D->getType());
2603f22ef01cSRoman Divacky   } else {
26047ae0e2c9SDimitry Andric     initializedGlobalDecl = GlobalDecl(D);
2605dff0c46cSDimitry Andric     Init = EmitConstantInit(*InitDecl);
2606f785676fSDimitry Andric 
2607f22ef01cSRoman Divacky     if (!Init) {
2608f22ef01cSRoman Divacky       QualType T = InitExpr->getType();
2609f22ef01cSRoman Divacky       if (D->getType()->isReferenceType())
2610f22ef01cSRoman Divacky         T = D->getType();
2611f22ef01cSRoman Divacky 
2612dff0c46cSDimitry Andric       if (getLangOpts().CPlusPlus) {
2613f22ef01cSRoman Divacky         Init = EmitNullConstant(T);
2614dff0c46cSDimitry Andric         NeedsGlobalCtor = true;
2615f22ef01cSRoman Divacky       } else {
2616f22ef01cSRoman Divacky         ErrorUnsupported(D, "static initializer");
2617f22ef01cSRoman Divacky         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
2618f22ef01cSRoman Divacky       }
2619e580952dSDimitry Andric     } else {
2620e580952dSDimitry Andric       // We don't need an initializer, so remove the entry for the delayed
2621dff0c46cSDimitry Andric       // initializer position (just in case this entry was delayed) if we
2622dff0c46cSDimitry Andric       // also don't need to register a destructor.
2623dff0c46cSDimitry Andric       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
2624e580952dSDimitry Andric         DelayedCXXInitPosition.erase(D);
2625f22ef01cSRoman Divacky     }
2626f22ef01cSRoman Divacky   }
2627f22ef01cSRoman Divacky 
26286122f3e6SDimitry Andric   llvm::Type* InitType = Init->getType();
2629e7145dcbSDimitry Andric   llvm::Constant *Entry =
263044290647SDimitry Andric       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
2631f22ef01cSRoman Divacky 
2632f22ef01cSRoman Divacky   // Strip off a bitcast if we got one back.
263359d1ed5bSDimitry Andric   if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2634f22ef01cSRoman Divacky     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2635f785676fSDimitry Andric            CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2636f785676fSDimitry Andric            // All zero index gep.
2637f22ef01cSRoman Divacky            CE->getOpcode() == llvm::Instruction::GetElementPtr);
2638f22ef01cSRoman Divacky     Entry = CE->getOperand(0);
2639f22ef01cSRoman Divacky   }
2640f22ef01cSRoman Divacky 
2641f22ef01cSRoman Divacky   // Entry is now either a Function or GlobalVariable.
264259d1ed5bSDimitry Andric   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
2643f22ef01cSRoman Divacky 
2644f22ef01cSRoman Divacky   // We have a definition after a declaration with the wrong type.
2645f22ef01cSRoman Divacky   // We must make a new GlobalVariable* and update everything that used OldGV
2646f22ef01cSRoman Divacky   // (a declaration or tentative definition) with the new GlobalVariable*
2647f22ef01cSRoman Divacky   // (which will be a definition).
2648f22ef01cSRoman Divacky   //
2649f22ef01cSRoman Divacky   // This happens if there is a prototype for a global (e.g.
2650f22ef01cSRoman Divacky   // "extern int x[];") and then a definition of a different type (e.g.
2651f22ef01cSRoman Divacky   // "int x[10];"). This also happens when an initializer has a different type
2652f22ef01cSRoman Divacky   // from the type of the global (this happens with unions).
265359d1ed5bSDimitry Andric   if (!GV ||
2654f22ef01cSRoman Divacky       GV->getType()->getElementType() != InitType ||
26553b0f4066SDimitry Andric       GV->getType()->getAddressSpace() !=
26567ae0e2c9SDimitry Andric        GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
2657f22ef01cSRoman Divacky 
2658f22ef01cSRoman Divacky     // Move the old entry aside so that we'll create a new one.
26596122f3e6SDimitry Andric     Entry->setName(StringRef());
2660f22ef01cSRoman Divacky 
2661f22ef01cSRoman Divacky     // Make a new global with the correct type, this is now guaranteed to work.
2662e7145dcbSDimitry Andric     GV = cast<llvm::GlobalVariable>(
266344290647SDimitry Andric         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
2664f22ef01cSRoman Divacky 
2665f22ef01cSRoman Divacky     // Replace all uses of the old global with the new global
2666f22ef01cSRoman Divacky     llvm::Constant *NewPtrForOldDecl =
2667f22ef01cSRoman Divacky         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2668f22ef01cSRoman Divacky     Entry->replaceAllUsesWith(NewPtrForOldDecl);
2669f22ef01cSRoman Divacky 
2670f22ef01cSRoman Divacky     // Erase the old global, since it is no longer used.
2671f22ef01cSRoman Divacky     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2672f22ef01cSRoman Divacky   }
2673f22ef01cSRoman Divacky 
2674284c1978SDimitry Andric   MaybeHandleStaticInExternC(D, GV);
2675284c1978SDimitry Andric 
26766122f3e6SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
26776122f3e6SDimitry Andric     AddGlobalAnnotations(D, GV);
2678f22ef01cSRoman Divacky 
2679e7145dcbSDimitry Andric   // Set the llvm linkage type as appropriate.
2680e7145dcbSDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
2681e7145dcbSDimitry Andric       getLLVMLinkageVarDefinition(D, GV->isConstant());
2682e7145dcbSDimitry Andric 
26830623d748SDimitry Andric   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
26840623d748SDimitry Andric   // the device. [...]"
26850623d748SDimitry Andric   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
26860623d748SDimitry Andric   // __device__, declares a variable that: [...]
26870623d748SDimitry Andric   // Is accessible from all the threads within the grid and from the host
26880623d748SDimitry Andric   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
26890623d748SDimitry Andric   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
2690e7145dcbSDimitry Andric   if (GV && LangOpts.CUDA) {
2691e7145dcbSDimitry Andric     if (LangOpts.CUDAIsDevice) {
2692e7145dcbSDimitry Andric       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
26930623d748SDimitry Andric         GV->setExternallyInitialized(true);
2694e7145dcbSDimitry Andric     } else {
2695e7145dcbSDimitry Andric       // Host-side shadows of external declarations of device-side
2696e7145dcbSDimitry Andric       // global variables become internal definitions. These have to
2697e7145dcbSDimitry Andric       // be internal in order to prevent name conflicts with global
2698e7145dcbSDimitry Andric       // host variables with the same name in a different TUs.
2699e7145dcbSDimitry Andric       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
2700e7145dcbSDimitry Andric         Linkage = llvm::GlobalValue::InternalLinkage;
2701e7145dcbSDimitry Andric 
2702e7145dcbSDimitry Andric         // Shadow variables and their properties must be registered
2703e7145dcbSDimitry Andric         // with CUDA runtime.
2704e7145dcbSDimitry Andric         unsigned Flags = 0;
2705e7145dcbSDimitry Andric         if (!D->hasDefinition())
2706e7145dcbSDimitry Andric           Flags |= CGCUDARuntime::ExternDeviceVar;
2707e7145dcbSDimitry Andric         if (D->hasAttr<CUDAConstantAttr>())
2708e7145dcbSDimitry Andric           Flags |= CGCUDARuntime::ConstantDeviceVar;
2709e7145dcbSDimitry Andric         getCUDARuntime().registerDeviceVar(*GV, Flags);
2710e7145dcbSDimitry Andric       } else if (D->hasAttr<CUDASharedAttr>())
2711e7145dcbSDimitry Andric         // __shared__ variables are odd. Shadows do get created, but
2712e7145dcbSDimitry Andric         // they are not registered with the CUDA runtime, so they
2713e7145dcbSDimitry Andric         // can't really be used to access their device-side
2714e7145dcbSDimitry Andric         // counterparts. It's not clear yet whether it's nvcc's bug or
2715e7145dcbSDimitry Andric         // a feature, but we've got to do the same for compatibility.
2716e7145dcbSDimitry Andric         Linkage = llvm::GlobalValue::InternalLinkage;
2717e7145dcbSDimitry Andric     }
27180623d748SDimitry Andric   }
2719f22ef01cSRoman Divacky   GV->setInitializer(Init);
2720f22ef01cSRoman Divacky 
2721f22ef01cSRoman Divacky   // If it is safe to mark the global 'constant', do so now.
2722dff0c46cSDimitry Andric   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2723dff0c46cSDimitry Andric                   isTypeConstant(D->getType(), true));
2724f22ef01cSRoman Divacky 
272539d628a0SDimitry Andric   // If it is in a read-only section, mark it 'constant'.
272639d628a0SDimitry Andric   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
272739d628a0SDimitry Andric     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
272839d628a0SDimitry Andric     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
272939d628a0SDimitry Andric       GV->setConstant(true);
273039d628a0SDimitry Andric   }
273139d628a0SDimitry Andric 
2732f22ef01cSRoman Divacky   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2733f22ef01cSRoman Divacky 
2734f785676fSDimitry Andric 
27350623d748SDimitry Andric   // On Darwin, if the normal linkage of a C++ thread_local variable is
27360623d748SDimitry Andric   // LinkOnce or Weak, we keep the normal linkage to prevent multiple
27370623d748SDimitry Andric   // copies within a linkage unit; otherwise, the backing variable has
27380623d748SDimitry Andric   // internal linkage and all accesses should just be calls to the
273959d1ed5bSDimitry Andric   // Itanium-specified entry point, which has the normal linkage of the
27400623d748SDimitry Andric   // variable. This is to preserve the ability to change the implementation
27410623d748SDimitry Andric   // behind the scenes.
274239d628a0SDimitry Andric   if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
27430623d748SDimitry Andric       Context.getTargetInfo().getTriple().isOSDarwin() &&
27440623d748SDimitry Andric       !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
27450623d748SDimitry Andric       !llvm::GlobalVariable::isWeakLinkage(Linkage))
274659d1ed5bSDimitry Andric     Linkage = llvm::GlobalValue::InternalLinkage;
274759d1ed5bSDimitry Andric 
274859d1ed5bSDimitry Andric   GV->setLinkage(Linkage);
274959d1ed5bSDimitry Andric   if (D->hasAttr<DLLImportAttr>())
275059d1ed5bSDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
275159d1ed5bSDimitry Andric   else if (D->hasAttr<DLLExportAttr>())
275259d1ed5bSDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
275339d628a0SDimitry Andric   else
275439d628a0SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2755f785676fSDimitry Andric 
275644290647SDimitry Andric   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
2757f22ef01cSRoman Divacky     // common vars aren't constant even if declared const.
2758f22ef01cSRoman Divacky     GV->setConstant(false);
275944290647SDimitry Andric     // Tentative definition of global variables may be initialized with
276044290647SDimitry Andric     // non-zero null pointers. In this case they should have weak linkage
276144290647SDimitry Andric     // since common linkage must have zero initializer and must not have
276244290647SDimitry Andric     // explicit section therefore cannot have non-zero initial value.
276344290647SDimitry Andric     if (!GV->getInitializer()->isNullValue())
276444290647SDimitry Andric       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
276544290647SDimitry Andric   }
2766f22ef01cSRoman Divacky 
276759d1ed5bSDimitry Andric   setNonAliasAttributes(D, GV);
2768f22ef01cSRoman Divacky 
276939d628a0SDimitry Andric   if (D->getTLSKind() && !GV->isThreadLocal()) {
277039d628a0SDimitry Andric     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
27710623d748SDimitry Andric       CXXThreadLocals.push_back(D);
277239d628a0SDimitry Andric     setTLSMode(GV, *D);
277339d628a0SDimitry Andric   }
277439d628a0SDimitry Andric 
277533956c43SDimitry Andric   maybeSetTrivialComdat(*D, *GV);
277633956c43SDimitry Andric 
27772754fe60SDimitry Andric   // Emit the initializer function if necessary.
2778dff0c46cSDimitry Andric   if (NeedsGlobalCtor || NeedsGlobalDtor)
2779dff0c46cSDimitry Andric     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
27802754fe60SDimitry Andric 
278139d628a0SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
27823861d79fSDimitry Andric 
2783f22ef01cSRoman Divacky   // Emit global variable debug information.
27846122f3e6SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
2785e7145dcbSDimitry Andric     if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
2786f22ef01cSRoman Divacky       DI->EmitGlobalVariable(GV, D);
2787f22ef01cSRoman Divacky }
2788f22ef01cSRoman Divacky 
278939d628a0SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context,
279033956c43SDimitry Andric                                       CodeGenModule &CGM, const VarDecl *D,
279133956c43SDimitry Andric                                       bool NoCommon) {
279259d1ed5bSDimitry Andric   // Don't give variables common linkage if -fno-common was specified unless it
279359d1ed5bSDimitry Andric   // was overridden by a NoCommon attribute.
279459d1ed5bSDimitry Andric   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
279559d1ed5bSDimitry Andric     return true;
279659d1ed5bSDimitry Andric 
279759d1ed5bSDimitry Andric   // C11 6.9.2/2:
279859d1ed5bSDimitry Andric   //   A declaration of an identifier for an object that has file scope without
279959d1ed5bSDimitry Andric   //   an initializer, and without a storage-class specifier or with the
280059d1ed5bSDimitry Andric   //   storage-class specifier static, constitutes a tentative definition.
280159d1ed5bSDimitry Andric   if (D->getInit() || D->hasExternalStorage())
280259d1ed5bSDimitry Andric     return true;
280359d1ed5bSDimitry Andric 
280459d1ed5bSDimitry Andric   // A variable cannot be both common and exist in a section.
280559d1ed5bSDimitry Andric   if (D->hasAttr<SectionAttr>())
280659d1ed5bSDimitry Andric     return true;
280759d1ed5bSDimitry Andric 
280859d1ed5bSDimitry Andric   // Thread local vars aren't considered common linkage.
280959d1ed5bSDimitry Andric   if (D->getTLSKind())
281059d1ed5bSDimitry Andric     return true;
281159d1ed5bSDimitry Andric 
281259d1ed5bSDimitry Andric   // Tentative definitions marked with WeakImportAttr are true definitions.
281359d1ed5bSDimitry Andric   if (D->hasAttr<WeakImportAttr>())
281459d1ed5bSDimitry Andric     return true;
281559d1ed5bSDimitry Andric 
281633956c43SDimitry Andric   // A variable cannot be both common and exist in a comdat.
281733956c43SDimitry Andric   if (shouldBeInCOMDAT(CGM, *D))
281833956c43SDimitry Andric     return true;
281933956c43SDimitry Andric 
2820e7145dcbSDimitry Andric   // Declarations with a required alignment do not have common linkage in MSVC
282139d628a0SDimitry Andric   // mode.
28220623d748SDimitry Andric   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
282333956c43SDimitry Andric     if (D->hasAttr<AlignedAttr>())
282439d628a0SDimitry Andric       return true;
282533956c43SDimitry Andric     QualType VarType = D->getType();
282633956c43SDimitry Andric     if (Context.isAlignmentRequired(VarType))
282733956c43SDimitry Andric       return true;
282833956c43SDimitry Andric 
282933956c43SDimitry Andric     if (const auto *RT = VarType->getAs<RecordType>()) {
283033956c43SDimitry Andric       const RecordDecl *RD = RT->getDecl();
283133956c43SDimitry Andric       for (const FieldDecl *FD : RD->fields()) {
283233956c43SDimitry Andric         if (FD->isBitField())
283333956c43SDimitry Andric           continue;
283433956c43SDimitry Andric         if (FD->hasAttr<AlignedAttr>())
283533956c43SDimitry Andric           return true;
283633956c43SDimitry Andric         if (Context.isAlignmentRequired(FD->getType()))
283733956c43SDimitry Andric           return true;
283833956c43SDimitry Andric       }
283933956c43SDimitry Andric     }
284033956c43SDimitry Andric   }
284139d628a0SDimitry Andric 
284259d1ed5bSDimitry Andric   return false;
284359d1ed5bSDimitry Andric }
284459d1ed5bSDimitry Andric 
284559d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
284659d1ed5bSDimitry Andric     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
28472754fe60SDimitry Andric   if (Linkage == GVA_Internal)
28482754fe60SDimitry Andric     return llvm::Function::InternalLinkage;
284959d1ed5bSDimitry Andric 
285059d1ed5bSDimitry Andric   if (D->hasAttr<WeakAttr>()) {
285159d1ed5bSDimitry Andric     if (IsConstantVariable)
285259d1ed5bSDimitry Andric       return llvm::GlobalVariable::WeakODRLinkage;
285359d1ed5bSDimitry Andric     else
285459d1ed5bSDimitry Andric       return llvm::GlobalVariable::WeakAnyLinkage;
285559d1ed5bSDimitry Andric   }
285659d1ed5bSDimitry Andric 
285759d1ed5bSDimitry Andric   // We are guaranteed to have a strong definition somewhere else,
285859d1ed5bSDimitry Andric   // so we can use available_externally linkage.
285959d1ed5bSDimitry Andric   if (Linkage == GVA_AvailableExternally)
286020e90f04SDimitry Andric     return llvm::GlobalValue::AvailableExternallyLinkage;
286159d1ed5bSDimitry Andric 
286259d1ed5bSDimitry Andric   // Note that Apple's kernel linker doesn't support symbol
286359d1ed5bSDimitry Andric   // coalescing, so we need to avoid linkonce and weak linkages there.
286459d1ed5bSDimitry Andric   // Normally, this means we just map to internal, but for explicit
286559d1ed5bSDimitry Andric   // instantiations we'll map to external.
286659d1ed5bSDimitry Andric 
286759d1ed5bSDimitry Andric   // In C++, the compiler has to emit a definition in every translation unit
286859d1ed5bSDimitry Andric   // that references the function.  We should use linkonce_odr because
286959d1ed5bSDimitry Andric   // a) if all references in this translation unit are optimized away, we
287059d1ed5bSDimitry Andric   // don't need to codegen it.  b) if the function persists, it needs to be
287159d1ed5bSDimitry Andric   // merged with other definitions. c) C++ has the ODR, so we know the
287259d1ed5bSDimitry Andric   // definition is dependable.
287359d1ed5bSDimitry Andric   if (Linkage == GVA_DiscardableODR)
287459d1ed5bSDimitry Andric     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
287559d1ed5bSDimitry Andric                                             : llvm::Function::InternalLinkage;
287659d1ed5bSDimitry Andric 
287759d1ed5bSDimitry Andric   // An explicit instantiation of a template has weak linkage, since
287859d1ed5bSDimitry Andric   // explicit instantiations can occur in multiple translation units
287959d1ed5bSDimitry Andric   // and must all be equivalent. However, we are not allowed to
288059d1ed5bSDimitry Andric   // throw away these explicit instantiations.
2881e7145dcbSDimitry Andric   //
2882e7145dcbSDimitry Andric   // We don't currently support CUDA device code spread out across multiple TUs,
2883e7145dcbSDimitry Andric   // so say that CUDA templates are either external (for kernels) or internal.
2884e7145dcbSDimitry Andric   // This lets llvm perform aggressive inter-procedural optimizations.
2885e7145dcbSDimitry Andric   if (Linkage == GVA_StrongODR) {
2886e7145dcbSDimitry Andric     if (Context.getLangOpts().AppleKext)
2887e7145dcbSDimitry Andric       return llvm::Function::ExternalLinkage;
2888e7145dcbSDimitry Andric     if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
2889e7145dcbSDimitry Andric       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
2890e7145dcbSDimitry Andric                                           : llvm::Function::InternalLinkage;
2891e7145dcbSDimitry Andric     return llvm::Function::WeakODRLinkage;
2892e7145dcbSDimitry Andric   }
289359d1ed5bSDimitry Andric 
289459d1ed5bSDimitry Andric   // C++ doesn't have tentative definitions and thus cannot have common
289559d1ed5bSDimitry Andric   // linkage.
289659d1ed5bSDimitry Andric   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
289733956c43SDimitry Andric       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
289839d628a0SDimitry Andric                                  CodeGenOpts.NoCommon))
289959d1ed5bSDimitry Andric     return llvm::GlobalVariable::CommonLinkage;
290059d1ed5bSDimitry Andric 
2901f785676fSDimitry Andric   // selectany symbols are externally visible, so use weak instead of
2902f785676fSDimitry Andric   // linkonce.  MSVC optimizes away references to const selectany globals, so
2903f785676fSDimitry Andric   // all definitions should be the same and ODR linkage should be used.
2904f785676fSDimitry Andric   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
290559d1ed5bSDimitry Andric   if (D->hasAttr<SelectAnyAttr>())
2906f785676fSDimitry Andric     return llvm::GlobalVariable::WeakODRLinkage;
290759d1ed5bSDimitry Andric 
290859d1ed5bSDimitry Andric   // Otherwise, we have strong external linkage.
290959d1ed5bSDimitry Andric   assert(Linkage == GVA_StrongExternal);
29102754fe60SDimitry Andric   return llvm::GlobalVariable::ExternalLinkage;
29112754fe60SDimitry Andric }
29122754fe60SDimitry Andric 
291359d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
291459d1ed5bSDimitry Andric     const VarDecl *VD, bool IsConstant) {
291559d1ed5bSDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
291659d1ed5bSDimitry Andric   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
291759d1ed5bSDimitry Andric }
291859d1ed5bSDimitry Andric 
2919139f7f9bSDimitry Andric /// Replace the uses of a function that was declared with a non-proto type.
2920139f7f9bSDimitry Andric /// We want to silently drop extra arguments from call sites
2921139f7f9bSDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2922139f7f9bSDimitry Andric                                           llvm::Function *newFn) {
2923139f7f9bSDimitry Andric   // Fast path.
2924139f7f9bSDimitry Andric   if (old->use_empty()) return;
2925139f7f9bSDimitry Andric 
2926139f7f9bSDimitry Andric   llvm::Type *newRetTy = newFn->getReturnType();
2927139f7f9bSDimitry Andric   SmallVector<llvm::Value*, 4> newArgs;
29280623d748SDimitry Andric   SmallVector<llvm::OperandBundleDef, 1> newBundles;
2929139f7f9bSDimitry Andric 
2930139f7f9bSDimitry Andric   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2931139f7f9bSDimitry Andric          ui != ue; ) {
2932139f7f9bSDimitry Andric     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
293359d1ed5bSDimitry Andric     llvm::User *user = use->getUser();
2934139f7f9bSDimitry Andric 
2935139f7f9bSDimitry Andric     // Recognize and replace uses of bitcasts.  Most calls to
2936139f7f9bSDimitry Andric     // unprototyped functions will use bitcasts.
293759d1ed5bSDimitry Andric     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
2938139f7f9bSDimitry Andric       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2939139f7f9bSDimitry Andric         replaceUsesOfNonProtoConstant(bitcast, newFn);
2940139f7f9bSDimitry Andric       continue;
2941139f7f9bSDimitry Andric     }
2942139f7f9bSDimitry Andric 
2943139f7f9bSDimitry Andric     // Recognize calls to the function.
2944139f7f9bSDimitry Andric     llvm::CallSite callSite(user);
2945139f7f9bSDimitry Andric     if (!callSite) continue;
294659d1ed5bSDimitry Andric     if (!callSite.isCallee(&*use)) continue;
2947139f7f9bSDimitry Andric 
2948139f7f9bSDimitry Andric     // If the return types don't match exactly, then we can't
2949139f7f9bSDimitry Andric     // transform this call unless it's dead.
2950139f7f9bSDimitry Andric     if (callSite->getType() != newRetTy && !callSite->use_empty())
2951139f7f9bSDimitry Andric       continue;
2952139f7f9bSDimitry Andric 
2953139f7f9bSDimitry Andric     // Get the call site's attribute list.
295420e90f04SDimitry Andric     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
295520e90f04SDimitry Andric     llvm::AttributeList oldAttrs = callSite.getAttributes();
2956139f7f9bSDimitry Andric 
2957139f7f9bSDimitry Andric     // If the function was passed too few arguments, don't transform.
2958139f7f9bSDimitry Andric     unsigned newNumArgs = newFn->arg_size();
2959139f7f9bSDimitry Andric     if (callSite.arg_size() < newNumArgs) continue;
2960139f7f9bSDimitry Andric 
2961139f7f9bSDimitry Andric     // If extra arguments were passed, we silently drop them.
2962139f7f9bSDimitry Andric     // If any of the types mismatch, we don't transform.
2963139f7f9bSDimitry Andric     unsigned argNo = 0;
2964139f7f9bSDimitry Andric     bool dontTransform = false;
296520e90f04SDimitry Andric     for (llvm::Argument &A : newFn->args()) {
296620e90f04SDimitry Andric       if (callSite.getArgument(argNo)->getType() != A.getType()) {
2967139f7f9bSDimitry Andric         dontTransform = true;
2968139f7f9bSDimitry Andric         break;
2969139f7f9bSDimitry Andric       }
2970139f7f9bSDimitry Andric 
2971139f7f9bSDimitry Andric       // Add any parameter attributes.
297220e90f04SDimitry Andric       newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
297320e90f04SDimitry Andric       argNo++;
2974139f7f9bSDimitry Andric     }
2975139f7f9bSDimitry Andric     if (dontTransform)
2976139f7f9bSDimitry Andric       continue;
2977139f7f9bSDimitry Andric 
2978139f7f9bSDimitry Andric     // Okay, we can transform this.  Create the new call instruction and copy
2979139f7f9bSDimitry Andric     // over the required information.
2980139f7f9bSDimitry Andric     newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2981139f7f9bSDimitry Andric 
29820623d748SDimitry Andric     // Copy over any operand bundles.
29830623d748SDimitry Andric     callSite.getOperandBundlesAsDefs(newBundles);
29840623d748SDimitry Andric 
2985139f7f9bSDimitry Andric     llvm::CallSite newCall;
2986139f7f9bSDimitry Andric     if (callSite.isCall()) {
29870623d748SDimitry Andric       newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
2988139f7f9bSDimitry Andric                                        callSite.getInstruction());
2989139f7f9bSDimitry Andric     } else {
299059d1ed5bSDimitry Andric       auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
2991139f7f9bSDimitry Andric       newCall = llvm::InvokeInst::Create(newFn,
2992139f7f9bSDimitry Andric                                          oldInvoke->getNormalDest(),
2993139f7f9bSDimitry Andric                                          oldInvoke->getUnwindDest(),
29940623d748SDimitry Andric                                          newArgs, newBundles, "",
2995139f7f9bSDimitry Andric                                          callSite.getInstruction());
2996139f7f9bSDimitry Andric     }
2997139f7f9bSDimitry Andric     newArgs.clear(); // for the next iteration
2998139f7f9bSDimitry Andric 
2999139f7f9bSDimitry Andric     if (!newCall->getType()->isVoidTy())
3000139f7f9bSDimitry Andric       newCall->takeName(callSite.getInstruction());
300120e90f04SDimitry Andric     newCall.setAttributes(llvm::AttributeList::get(
300220e90f04SDimitry Andric         newFn->getContext(), oldAttrs.getFnAttributes(),
300320e90f04SDimitry Andric         oldAttrs.getRetAttributes(), newArgAttrs));
3004139f7f9bSDimitry Andric     newCall.setCallingConv(callSite.getCallingConv());
3005139f7f9bSDimitry Andric 
3006139f7f9bSDimitry Andric     // Finally, remove the old call, replacing any uses with the new one.
3007139f7f9bSDimitry Andric     if (!callSite->use_empty())
3008139f7f9bSDimitry Andric       callSite->replaceAllUsesWith(newCall.getInstruction());
3009139f7f9bSDimitry Andric 
3010139f7f9bSDimitry Andric     // Copy debug location attached to CI.
301133956c43SDimitry Andric     if (callSite->getDebugLoc())
3012139f7f9bSDimitry Andric       newCall->setDebugLoc(callSite->getDebugLoc());
30130623d748SDimitry Andric 
3014139f7f9bSDimitry Andric     callSite->eraseFromParent();
3015139f7f9bSDimitry Andric   }
3016139f7f9bSDimitry Andric }
3017139f7f9bSDimitry Andric 
3018f22ef01cSRoman Divacky /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
3019f22ef01cSRoman Divacky /// implement a function with no prototype, e.g. "int foo() {}".  If there are
3020f22ef01cSRoman Divacky /// existing call uses of the old function in the module, this adjusts them to
3021f22ef01cSRoman Divacky /// call the new function directly.
3022f22ef01cSRoman Divacky ///
3023f22ef01cSRoman Divacky /// This is not just a cleanup: the always_inline pass requires direct calls to
3024f22ef01cSRoman Divacky /// functions to be able to inline them.  If there is a bitcast in the way, it
3025f22ef01cSRoman Divacky /// won't inline them.  Instcombine normally deletes these calls, but it isn't
3026f22ef01cSRoman Divacky /// run at -O0.
3027f22ef01cSRoman Divacky static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3028f22ef01cSRoman Divacky                                                       llvm::Function *NewFn) {
3029f22ef01cSRoman Divacky   // If we're redefining a global as a function, don't transform it.
3030139f7f9bSDimitry Andric   if (!isa<llvm::Function>(Old)) return;
3031f22ef01cSRoman Divacky 
3032139f7f9bSDimitry Andric   replaceUsesOfNonProtoConstant(Old, NewFn);
3033f22ef01cSRoman Divacky }
3034f22ef01cSRoman Divacky 
3035dff0c46cSDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
3036e7145dcbSDimitry Andric   auto DK = VD->isThisDeclarationADefinition();
3037e7145dcbSDimitry Andric   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
3038e7145dcbSDimitry Andric     return;
3039e7145dcbSDimitry Andric 
3040dff0c46cSDimitry Andric   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
3041dff0c46cSDimitry Andric   // If we have a definition, this might be a deferred decl. If the
3042dff0c46cSDimitry Andric   // instantiation is explicit, make sure we emit it at the end.
3043dff0c46cSDimitry Andric   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
3044dff0c46cSDimitry Andric     GetAddrOfGlobalVar(VD);
3045139f7f9bSDimitry Andric 
3046139f7f9bSDimitry Andric   EmitTopLevelDecl(VD);
3047dff0c46cSDimitry Andric }
3048f22ef01cSRoman Divacky 
304959d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
305059d1ed5bSDimitry Andric                                                  llvm::GlobalValue *GV) {
305159d1ed5bSDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
30523b0f4066SDimitry Andric 
30533b0f4066SDimitry Andric   // Compute the function info and LLVM type.
3054dff0c46cSDimitry Andric   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3055dff0c46cSDimitry Andric   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
30563b0f4066SDimitry Andric 
3057f22ef01cSRoman Divacky   // Get or create the prototype for the function.
30580623d748SDimitry Andric   if (!GV || (GV->getType()->getElementType() != Ty))
30590623d748SDimitry Andric     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
30600623d748SDimitry Andric                                                    /*DontDefer=*/true,
306144290647SDimitry Andric                                                    ForDefinition));
3062f22ef01cSRoman Divacky 
30630623d748SDimitry Andric   // Already emitted.
30640623d748SDimitry Andric   if (!GV->isDeclaration())
3065f785676fSDimitry Andric     return;
3066f22ef01cSRoman Divacky 
30672754fe60SDimitry Andric   // We need to set linkage and visibility on the function before
30682754fe60SDimitry Andric   // generating code for it because various parts of IR generation
30692754fe60SDimitry Andric   // want to propagate this information down (e.g. to local static
30702754fe60SDimitry Andric   // declarations).
307159d1ed5bSDimitry Andric   auto *Fn = cast<llvm::Function>(GV);
3072f785676fSDimitry Andric   setFunctionLinkage(GD, Fn);
307397bc6c73SDimitry Andric   setFunctionDLLStorageClass(GD, Fn);
3074f22ef01cSRoman Divacky 
307559d1ed5bSDimitry Andric   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
30762754fe60SDimitry Andric   setGlobalVisibility(Fn, D);
30772754fe60SDimitry Andric 
3078284c1978SDimitry Andric   MaybeHandleStaticInExternC(D, Fn);
3079284c1978SDimitry Andric 
308033956c43SDimitry Andric   maybeSetTrivialComdat(*D, *Fn);
308133956c43SDimitry Andric 
30823b0f4066SDimitry Andric   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
3083f22ef01cSRoman Divacky 
308459d1ed5bSDimitry Andric   setFunctionDefinitionAttributes(D, Fn);
3085f22ef01cSRoman Divacky   SetLLVMFunctionAttributesForDefinition(D, Fn);
3086f22ef01cSRoman Divacky 
3087f22ef01cSRoman Divacky   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
3088f22ef01cSRoman Divacky     AddGlobalCtor(Fn, CA->getPriority());
3089f22ef01cSRoman Divacky   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
3090f22ef01cSRoman Divacky     AddGlobalDtor(Fn, DA->getPriority());
30916122f3e6SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
30926122f3e6SDimitry Andric     AddGlobalAnnotations(D, Fn);
3093f22ef01cSRoman Divacky }
3094f22ef01cSRoman Divacky 
3095f22ef01cSRoman Divacky void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
309659d1ed5bSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
3097f22ef01cSRoman Divacky   const AliasAttr *AA = D->getAttr<AliasAttr>();
3098f22ef01cSRoman Divacky   assert(AA && "Not an alias?");
3099f22ef01cSRoman Divacky 
31006122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
3101f22ef01cSRoman Divacky 
31029a4b3118SDimitry Andric   if (AA->getAliasee() == MangledName) {
3103e7145dcbSDimitry Andric     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
31049a4b3118SDimitry Andric     return;
31059a4b3118SDimitry Andric   }
31069a4b3118SDimitry Andric 
3107f22ef01cSRoman Divacky   // If there is a definition in the module, then it wins over the alias.
3108f22ef01cSRoman Divacky   // This is dubious, but allow it to be safe.  Just ignore the alias.
3109f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3110f22ef01cSRoman Divacky   if (Entry && !Entry->isDeclaration())
3111f22ef01cSRoman Divacky     return;
3112f22ef01cSRoman Divacky 
3113f785676fSDimitry Andric   Aliases.push_back(GD);
3114f785676fSDimitry Andric 
31156122f3e6SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3116f22ef01cSRoman Divacky 
3117f22ef01cSRoman Divacky   // Create a reference to the named value.  This ensures that it is emitted
3118f22ef01cSRoman Divacky   // if a deferred decl.
3119f22ef01cSRoman Divacky   llvm::Constant *Aliasee;
3120f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(DeclTy))
31213861d79fSDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
31222754fe60SDimitry Andric                                       /*ForVTable=*/false);
3123f22ef01cSRoman Divacky   else
3124f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
312559d1ed5bSDimitry Andric                                     llvm::PointerType::getUnqual(DeclTy),
312639d628a0SDimitry Andric                                     /*D=*/nullptr);
3127f22ef01cSRoman Divacky 
3128f22ef01cSRoman Divacky   // Create the new alias itself, but don't set a name yet.
312959d1ed5bSDimitry Andric   auto *GA = llvm::GlobalAlias::create(
31300623d748SDimitry Andric       DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
3131f22ef01cSRoman Divacky 
3132f22ef01cSRoman Divacky   if (Entry) {
313359d1ed5bSDimitry Andric     if (GA->getAliasee() == Entry) {
3134e7145dcbSDimitry Andric       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
313559d1ed5bSDimitry Andric       return;
313659d1ed5bSDimitry Andric     }
313759d1ed5bSDimitry Andric 
3138f22ef01cSRoman Divacky     assert(Entry->isDeclaration());
3139f22ef01cSRoman Divacky 
3140f22ef01cSRoman Divacky     // If there is a declaration in the module, then we had an extern followed
3141f22ef01cSRoman Divacky     // by the alias, as in:
3142f22ef01cSRoman Divacky     //   extern int test6();
3143f22ef01cSRoman Divacky     //   ...
3144f22ef01cSRoman Divacky     //   int test6() __attribute__((alias("test7")));
3145f22ef01cSRoman Divacky     //
3146f22ef01cSRoman Divacky     // Remove it and replace uses of it with the alias.
3147f22ef01cSRoman Divacky     GA->takeName(Entry);
3148f22ef01cSRoman Divacky 
3149f22ef01cSRoman Divacky     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
3150f22ef01cSRoman Divacky                                                           Entry->getType()));
3151f22ef01cSRoman Divacky     Entry->eraseFromParent();
3152f22ef01cSRoman Divacky   } else {
3153ffd1746dSEd Schouten     GA->setName(MangledName);
3154f22ef01cSRoman Divacky   }
3155f22ef01cSRoman Divacky 
3156f22ef01cSRoman Divacky   // Set attributes which are particular to an alias; this is a
3157f22ef01cSRoman Divacky   // specialization of the attributes which may be set on a global
3158f22ef01cSRoman Divacky   // variable/function.
315939d628a0SDimitry Andric   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
31603b0f4066SDimitry Andric       D->isWeakImported()) {
3161f22ef01cSRoman Divacky     GA->setLinkage(llvm::Function::WeakAnyLinkage);
3162f22ef01cSRoman Divacky   }
3163f22ef01cSRoman Divacky 
316439d628a0SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
316539d628a0SDimitry Andric     if (VD->getTLSKind())
316639d628a0SDimitry Andric       setTLSMode(GA, *VD);
316739d628a0SDimitry Andric 
316839d628a0SDimitry Andric   setAliasAttributes(D, GA);
3169f22ef01cSRoman Divacky }
3170f22ef01cSRoman Divacky 
3171e7145dcbSDimitry Andric void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
3172e7145dcbSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
3173e7145dcbSDimitry Andric   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
3174e7145dcbSDimitry Andric   assert(IFA && "Not an ifunc?");
3175e7145dcbSDimitry Andric 
3176e7145dcbSDimitry Andric   StringRef MangledName = getMangledName(GD);
3177e7145dcbSDimitry Andric 
3178e7145dcbSDimitry Andric   if (IFA->getResolver() == MangledName) {
3179e7145dcbSDimitry Andric     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3180e7145dcbSDimitry Andric     return;
3181e7145dcbSDimitry Andric   }
3182e7145dcbSDimitry Andric 
3183e7145dcbSDimitry Andric   // Report an error if some definition overrides ifunc.
3184e7145dcbSDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3185e7145dcbSDimitry Andric   if (Entry && !Entry->isDeclaration()) {
3186e7145dcbSDimitry Andric     GlobalDecl OtherGD;
3187e7145dcbSDimitry Andric     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3188e7145dcbSDimitry Andric         DiagnosedConflictingDefinitions.insert(GD).second) {
3189e7145dcbSDimitry Andric       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
3190e7145dcbSDimitry Andric       Diags.Report(OtherGD.getDecl()->getLocation(),
3191e7145dcbSDimitry Andric                    diag::note_previous_definition);
3192e7145dcbSDimitry Andric     }
3193e7145dcbSDimitry Andric     return;
3194e7145dcbSDimitry Andric   }
3195e7145dcbSDimitry Andric 
3196e7145dcbSDimitry Andric   Aliases.push_back(GD);
3197e7145dcbSDimitry Andric 
3198e7145dcbSDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3199e7145dcbSDimitry Andric   llvm::Constant *Resolver =
3200e7145dcbSDimitry Andric       GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3201e7145dcbSDimitry Andric                               /*ForVTable=*/false);
3202e7145dcbSDimitry Andric   llvm::GlobalIFunc *GIF =
3203e7145dcbSDimitry Andric       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
3204e7145dcbSDimitry Andric                                 "", Resolver, &getModule());
3205e7145dcbSDimitry Andric   if (Entry) {
3206e7145dcbSDimitry Andric     if (GIF->getResolver() == Entry) {
3207e7145dcbSDimitry Andric       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3208e7145dcbSDimitry Andric       return;
3209e7145dcbSDimitry Andric     }
3210e7145dcbSDimitry Andric     assert(Entry->isDeclaration());
3211e7145dcbSDimitry Andric 
3212e7145dcbSDimitry Andric     // If there is a declaration in the module, then we had an extern followed
3213e7145dcbSDimitry Andric     // by the ifunc, as in:
3214e7145dcbSDimitry Andric     //   extern int test();
3215e7145dcbSDimitry Andric     //   ...
3216e7145dcbSDimitry Andric     //   int test() __attribute__((ifunc("resolver")));
3217e7145dcbSDimitry Andric     //
3218e7145dcbSDimitry Andric     // Remove it and replace uses of it with the ifunc.
3219e7145dcbSDimitry Andric     GIF->takeName(Entry);
3220e7145dcbSDimitry Andric 
3221e7145dcbSDimitry Andric     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3222e7145dcbSDimitry Andric                                                           Entry->getType()));
3223e7145dcbSDimitry Andric     Entry->eraseFromParent();
3224e7145dcbSDimitry Andric   } else
3225e7145dcbSDimitry Andric     GIF->setName(MangledName);
3226e7145dcbSDimitry Andric 
3227e7145dcbSDimitry Andric   SetCommonAttributes(D, GIF);
3228e7145dcbSDimitry Andric }
3229e7145dcbSDimitry Andric 
323017a519f9SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
32316122f3e6SDimitry Andric                                             ArrayRef<llvm::Type*> Tys) {
323217a519f9SDimitry Andric   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
323317a519f9SDimitry Andric                                          Tys);
3234f22ef01cSRoman Divacky }
3235f22ef01cSRoman Divacky 
323633956c43SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> &
323733956c43SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
323833956c43SDimitry Andric                          const StringLiteral *Literal, bool TargetIsLSB,
323933956c43SDimitry Andric                          bool &IsUTF16, unsigned &StringLength) {
32406122f3e6SDimitry Andric   StringRef String = Literal->getString();
3241e580952dSDimitry Andric   unsigned NumBytes = String.size();
3242f22ef01cSRoman Divacky 
3243f22ef01cSRoman Divacky   // Check for simple case.
3244f22ef01cSRoman Divacky   if (!Literal->containsNonAsciiOrNull()) {
3245f22ef01cSRoman Divacky     StringLength = NumBytes;
324639d628a0SDimitry Andric     return *Map.insert(std::make_pair(String, nullptr)).first;
3247f22ef01cSRoman Divacky   }
3248f22ef01cSRoman Divacky 
3249dff0c46cSDimitry Andric   // Otherwise, convert the UTF8 literals into a string of shorts.
3250dff0c46cSDimitry Andric   IsUTF16 = true;
3251dff0c46cSDimitry Andric 
325244290647SDimitry Andric   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
325344290647SDimitry Andric   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
325444290647SDimitry Andric   llvm::UTF16 *ToPtr = &ToBuf[0];
3255f22ef01cSRoman Divacky 
325644290647SDimitry Andric   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
325744290647SDimitry Andric                                  ToPtr + NumBytes, llvm::strictConversion);
3258f22ef01cSRoman Divacky 
3259f22ef01cSRoman Divacky   // ConvertUTF8toUTF16 returns the length in ToPtr.
3260f22ef01cSRoman Divacky   StringLength = ToPtr - &ToBuf[0];
3261f22ef01cSRoman Divacky 
3262dff0c46cSDimitry Andric   // Add an explicit null.
3263dff0c46cSDimitry Andric   *ToPtr = 0;
326439d628a0SDimitry Andric   return *Map.insert(std::make_pair(
326539d628a0SDimitry Andric                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
326639d628a0SDimitry Andric                                    (StringLength + 1) * 2),
326739d628a0SDimitry Andric                          nullptr)).first;
3268f22ef01cSRoman Divacky }
3269f22ef01cSRoman Divacky 
32700623d748SDimitry Andric ConstantAddress
3271f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
3272f22ef01cSRoman Divacky   unsigned StringLength = 0;
3273f22ef01cSRoman Divacky   bool isUTF16 = false;
327433956c43SDimitry Andric   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3275f22ef01cSRoman Divacky       GetConstantCFStringEntry(CFConstantStringMap, Literal,
327633956c43SDimitry Andric                                getDataLayout().isLittleEndian(), isUTF16,
327733956c43SDimitry Andric                                StringLength);
3278f22ef01cSRoman Divacky 
327939d628a0SDimitry Andric   if (auto *C = Entry.second)
32800623d748SDimitry Andric     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
3281f22ef01cSRoman Divacky 
3282dff0c46cSDimitry Andric   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
3283f22ef01cSRoman Divacky   llvm::Constant *Zeros[] = { Zero, Zero };
3284f22ef01cSRoman Divacky 
3285f22ef01cSRoman Divacky   // If we don't already have it, get __CFConstantStringClassReference.
3286f22ef01cSRoman Divacky   if (!CFConstantStringClassRef) {
32876122f3e6SDimitry Andric     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
3288f22ef01cSRoman Divacky     Ty = llvm::ArrayType::get(Ty, 0);
3289e7145dcbSDimitry Andric     llvm::Constant *GV =
3290e7145dcbSDimitry Andric         CreateRuntimeVariable(Ty, "__CFConstantStringClassReference");
3291e7145dcbSDimitry Andric 
329244290647SDimitry Andric     if (getTriple().isOSBinFormatCOFF()) {
3293e7145dcbSDimitry Andric       IdentifierInfo &II = getContext().Idents.get(GV->getName());
3294e7145dcbSDimitry Andric       TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
3295e7145dcbSDimitry Andric       DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3296e7145dcbSDimitry Andric       llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
3297e7145dcbSDimitry Andric 
3298e7145dcbSDimitry Andric       const VarDecl *VD = nullptr;
3299e7145dcbSDimitry Andric       for (const auto &Result : DC->lookup(&II))
3300e7145dcbSDimitry Andric         if ((VD = dyn_cast<VarDecl>(Result)))
3301e7145dcbSDimitry Andric           break;
3302e7145dcbSDimitry Andric 
3303e7145dcbSDimitry Andric       if (!VD || !VD->hasAttr<DLLExportAttr>()) {
3304e7145dcbSDimitry Andric         CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3305e7145dcbSDimitry Andric         CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3306e7145dcbSDimitry Andric       } else {
3307e7145dcbSDimitry Andric         CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3308e7145dcbSDimitry Andric         CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3309e7145dcbSDimitry Andric       }
3310e7145dcbSDimitry Andric     }
3311e7145dcbSDimitry Andric 
3312f22ef01cSRoman Divacky     // Decay array -> ptr
331344290647SDimitry Andric     CFConstantStringClassRef =
331444290647SDimitry Andric         llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
3315e7145dcbSDimitry Andric   }
3316f22ef01cSRoman Divacky 
3317f22ef01cSRoman Divacky   QualType CFTy = getContext().getCFConstantStringType();
3318f22ef01cSRoman Divacky 
331959d1ed5bSDimitry Andric   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
3320f22ef01cSRoman Divacky 
332144290647SDimitry Andric   ConstantInitBuilder Builder(*this);
332244290647SDimitry Andric   auto Fields = Builder.beginStruct(STy);
3323f22ef01cSRoman Divacky 
3324f22ef01cSRoman Divacky   // Class pointer.
332544290647SDimitry Andric   Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
3326f22ef01cSRoman Divacky 
3327f22ef01cSRoman Divacky   // Flags.
332844290647SDimitry Andric   Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
3329f22ef01cSRoman Divacky 
3330f22ef01cSRoman Divacky   // String pointer.
333159d1ed5bSDimitry Andric   llvm::Constant *C = nullptr;
3332dff0c46cSDimitry Andric   if (isUTF16) {
33330623d748SDimitry Andric     auto Arr = llvm::makeArrayRef(
333439d628a0SDimitry Andric         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
333539d628a0SDimitry Andric         Entry.first().size() / 2);
3336dff0c46cSDimitry Andric     C = llvm::ConstantDataArray::get(VMContext, Arr);
3337dff0c46cSDimitry Andric   } else {
333839d628a0SDimitry Andric     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
3339dff0c46cSDimitry Andric   }
3340f22ef01cSRoman Divacky 
3341dff0c46cSDimitry Andric   // Note: -fwritable-strings doesn't make the backing store strings of
3342dff0c46cSDimitry Andric   // CFStrings writable. (See <rdar://problem/10657500>)
334359d1ed5bSDimitry Andric   auto *GV =
3344dff0c46cSDimitry Andric       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
334559d1ed5bSDimitry Andric                                llvm::GlobalValue::PrivateLinkage, C, ".str");
3346e7145dcbSDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3347284c1978SDimitry Andric   // Don't enforce the target's minimum global alignment, since the only use
3348284c1978SDimitry Andric   // of the string is via this class initializer.
3349e7145dcbSDimitry Andric   CharUnits Align = isUTF16
3350e7145dcbSDimitry Andric                         ? getContext().getTypeAlignInChars(getContext().ShortTy)
3351e7145dcbSDimitry Andric                         : getContext().getTypeAlignInChars(getContext().CharTy);
3352f22ef01cSRoman Divacky   GV->setAlignment(Align.getQuantity());
3353e7145dcbSDimitry Andric 
3354e7145dcbSDimitry Andric   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
3355e7145dcbSDimitry Andric   // Without it LLVM can merge the string with a non unnamed_addr one during
3356e7145dcbSDimitry Andric   // LTO.  Doing that changes the section it ends in, which surprises ld64.
335744290647SDimitry Andric   if (getTriple().isOSBinFormatMachO())
3358e7145dcbSDimitry Andric     GV->setSection(isUTF16 ? "__TEXT,__ustring"
3359e7145dcbSDimitry Andric                            : "__TEXT,__cstring,cstring_literals");
3360dff0c46cSDimitry Andric 
3361dff0c46cSDimitry Andric   // String.
336244290647SDimitry Andric   llvm::Constant *Str =
336333956c43SDimitry Andric       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3364f22ef01cSRoman Divacky 
3365dff0c46cSDimitry Andric   if (isUTF16)
3366dff0c46cSDimitry Andric     // Cast the UTF16 string to the correct type.
336744290647SDimitry Andric     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
336844290647SDimitry Andric   Fields.add(Str);
3369dff0c46cSDimitry Andric 
3370f22ef01cSRoman Divacky   // String length.
337144290647SDimitry Andric   auto Ty = getTypes().ConvertType(getContext().LongTy);
337244290647SDimitry Andric   Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
3373f22ef01cSRoman Divacky 
33740623d748SDimitry Andric   CharUnits Alignment = getPointerAlign();
33750623d748SDimitry Andric 
3376f22ef01cSRoman Divacky   // The struct.
337744290647SDimitry Andric   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
337844290647SDimitry Andric                                     /*isConstant=*/false,
337944290647SDimitry Andric                                     llvm::GlobalVariable::PrivateLinkage);
338044290647SDimitry Andric   switch (getTriple().getObjectFormat()) {
3381e7145dcbSDimitry Andric   case llvm::Triple::UnknownObjectFormat:
3382e7145dcbSDimitry Andric     llvm_unreachable("unknown file format");
3383e7145dcbSDimitry Andric   case llvm::Triple::COFF:
3384e7145dcbSDimitry Andric   case llvm::Triple::ELF:
338520e90f04SDimitry Andric   case llvm::Triple::Wasm:
3386e7145dcbSDimitry Andric     GV->setSection("cfstring");
3387e7145dcbSDimitry Andric     break;
3388e7145dcbSDimitry Andric   case llvm::Triple::MachO:
3389e7145dcbSDimitry Andric     GV->setSection("__DATA,__cfstring");
3390e7145dcbSDimitry Andric     break;
3391e7145dcbSDimitry Andric   }
339239d628a0SDimitry Andric   Entry.second = GV;
3393f22ef01cSRoman Divacky 
33940623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
3395f22ef01cSRoman Divacky }
3396f22ef01cSRoman Divacky 
33976122f3e6SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() {
33986122f3e6SDimitry Andric   if (ObjCFastEnumerationStateType.isNull()) {
339959d1ed5bSDimitry Andric     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
34006122f3e6SDimitry Andric     D->startDefinition();
34016122f3e6SDimitry Andric 
34026122f3e6SDimitry Andric     QualType FieldTypes[] = {
34036122f3e6SDimitry Andric       Context.UnsignedLongTy,
34046122f3e6SDimitry Andric       Context.getPointerType(Context.getObjCIdType()),
34056122f3e6SDimitry Andric       Context.getPointerType(Context.UnsignedLongTy),
34066122f3e6SDimitry Andric       Context.getConstantArrayType(Context.UnsignedLongTy,
34076122f3e6SDimitry Andric                            llvm::APInt(32, 5), ArrayType::Normal, 0)
34086122f3e6SDimitry Andric     };
34096122f3e6SDimitry Andric 
34106122f3e6SDimitry Andric     for (size_t i = 0; i < 4; ++i) {
34116122f3e6SDimitry Andric       FieldDecl *Field = FieldDecl::Create(Context,
34126122f3e6SDimitry Andric                                            D,
34136122f3e6SDimitry Andric                                            SourceLocation(),
341459d1ed5bSDimitry Andric                                            SourceLocation(), nullptr,
341559d1ed5bSDimitry Andric                                            FieldTypes[i], /*TInfo=*/nullptr,
341659d1ed5bSDimitry Andric                                            /*BitWidth=*/nullptr,
34176122f3e6SDimitry Andric                                            /*Mutable=*/false,
34187ae0e2c9SDimitry Andric                                            ICIS_NoInit);
34196122f3e6SDimitry Andric       Field->setAccess(AS_public);
34206122f3e6SDimitry Andric       D->addDecl(Field);
34216122f3e6SDimitry Andric     }
34226122f3e6SDimitry Andric 
34236122f3e6SDimitry Andric     D->completeDefinition();
34246122f3e6SDimitry Andric     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
34256122f3e6SDimitry Andric   }
34266122f3e6SDimitry Andric 
34276122f3e6SDimitry Andric   return ObjCFastEnumerationStateType;
34286122f3e6SDimitry Andric }
34296122f3e6SDimitry Andric 
3430dff0c46cSDimitry Andric llvm::Constant *
3431dff0c46cSDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
3432dff0c46cSDimitry Andric   assert(!E->getType()->isPointerType() && "Strings are always arrays");
3433f22ef01cSRoman Divacky 
3434dff0c46cSDimitry Andric   // Don't emit it as the address of the string, emit the string data itself
3435dff0c46cSDimitry Andric   // as an inline array.
3436dff0c46cSDimitry Andric   if (E->getCharByteWidth() == 1) {
3437dff0c46cSDimitry Andric     SmallString<64> Str(E->getString());
3438f22ef01cSRoman Divacky 
3439dff0c46cSDimitry Andric     // Resize the string to the right size, which is indicated by its type.
3440dff0c46cSDimitry Andric     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
3441dff0c46cSDimitry Andric     Str.resize(CAT->getSize().getZExtValue());
3442dff0c46cSDimitry Andric     return llvm::ConstantDataArray::getString(VMContext, Str, false);
34436122f3e6SDimitry Andric   }
3444f22ef01cSRoman Divacky 
344559d1ed5bSDimitry Andric   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
3446dff0c46cSDimitry Andric   llvm::Type *ElemTy = AType->getElementType();
3447dff0c46cSDimitry Andric   unsigned NumElements = AType->getNumElements();
3448f22ef01cSRoman Divacky 
3449dff0c46cSDimitry Andric   // Wide strings have either 2-byte or 4-byte elements.
3450dff0c46cSDimitry Andric   if (ElemTy->getPrimitiveSizeInBits() == 16) {
3451dff0c46cSDimitry Andric     SmallVector<uint16_t, 32> Elements;
3452dff0c46cSDimitry Andric     Elements.reserve(NumElements);
3453dff0c46cSDimitry Andric 
3454dff0c46cSDimitry Andric     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3455dff0c46cSDimitry Andric       Elements.push_back(E->getCodeUnit(i));
3456dff0c46cSDimitry Andric     Elements.resize(NumElements);
3457dff0c46cSDimitry Andric     return llvm::ConstantDataArray::get(VMContext, Elements);
3458dff0c46cSDimitry Andric   }
3459dff0c46cSDimitry Andric 
3460dff0c46cSDimitry Andric   assert(ElemTy->getPrimitiveSizeInBits() == 32);
3461dff0c46cSDimitry Andric   SmallVector<uint32_t, 32> Elements;
3462dff0c46cSDimitry Andric   Elements.reserve(NumElements);
3463dff0c46cSDimitry Andric 
3464dff0c46cSDimitry Andric   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3465dff0c46cSDimitry Andric     Elements.push_back(E->getCodeUnit(i));
3466dff0c46cSDimitry Andric   Elements.resize(NumElements);
3467dff0c46cSDimitry Andric   return llvm::ConstantDataArray::get(VMContext, Elements);
3468f22ef01cSRoman Divacky }
3469f22ef01cSRoman Divacky 
347059d1ed5bSDimitry Andric static llvm::GlobalVariable *
347159d1ed5bSDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
347259d1ed5bSDimitry Andric                       CodeGenModule &CGM, StringRef GlobalName,
34730623d748SDimitry Andric                       CharUnits Alignment) {
347459d1ed5bSDimitry Andric   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
347559d1ed5bSDimitry Andric   unsigned AddrSpace = 0;
347659d1ed5bSDimitry Andric   if (CGM.getLangOpts().OpenCL)
347759d1ed5bSDimitry Andric     AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
3478dff0c46cSDimitry Andric 
347933956c43SDimitry Andric   llvm::Module &M = CGM.getModule();
348059d1ed5bSDimitry Andric   // Create a global variable for this string
348159d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
348233956c43SDimitry Andric       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
348333956c43SDimitry Andric       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
34840623d748SDimitry Andric   GV->setAlignment(Alignment.getQuantity());
3485e7145dcbSDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
348633956c43SDimitry Andric   if (GV->isWeakForLinker()) {
348733956c43SDimitry Andric     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
348833956c43SDimitry Andric     GV->setComdat(M.getOrInsertComdat(GV->getName()));
348933956c43SDimitry Andric   }
349033956c43SDimitry Andric 
349159d1ed5bSDimitry Andric   return GV;
3492f22ef01cSRoman Divacky }
3493dff0c46cSDimitry Andric 
349459d1ed5bSDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
349559d1ed5bSDimitry Andric /// constant array for the given string literal.
34960623d748SDimitry Andric ConstantAddress
349739d628a0SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
349839d628a0SDimitry Andric                                                   StringRef Name) {
34990623d748SDimitry Andric   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
3500dff0c46cSDimitry Andric 
350159d1ed5bSDimitry Andric   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
350259d1ed5bSDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
350359d1ed5bSDimitry Andric   if (!LangOpts.WritableStrings) {
350459d1ed5bSDimitry Andric     Entry = &ConstantStringMap[C];
350559d1ed5bSDimitry Andric     if (auto GV = *Entry) {
35060623d748SDimitry Andric       if (Alignment.getQuantity() > GV->getAlignment())
35070623d748SDimitry Andric         GV->setAlignment(Alignment.getQuantity());
35080623d748SDimitry Andric       return ConstantAddress(GV, Alignment);
350959d1ed5bSDimitry Andric     }
351059d1ed5bSDimitry Andric   }
351159d1ed5bSDimitry Andric 
351259d1ed5bSDimitry Andric   SmallString<256> MangledNameBuffer;
351359d1ed5bSDimitry Andric   StringRef GlobalVariableName;
351459d1ed5bSDimitry Andric   llvm::GlobalValue::LinkageTypes LT;
351559d1ed5bSDimitry Andric 
351659d1ed5bSDimitry Andric   // Mangle the string literal if the ABI allows for it.  However, we cannot
351759d1ed5bSDimitry Andric   // do this if  we are compiling with ASan or -fwritable-strings because they
351859d1ed5bSDimitry Andric   // rely on strings having normal linkage.
351939d628a0SDimitry Andric   if (!LangOpts.WritableStrings &&
352039d628a0SDimitry Andric       !LangOpts.Sanitize.has(SanitizerKind::Address) &&
352159d1ed5bSDimitry Andric       getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
352259d1ed5bSDimitry Andric     llvm::raw_svector_ostream Out(MangledNameBuffer);
352359d1ed5bSDimitry Andric     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
352459d1ed5bSDimitry Andric 
352559d1ed5bSDimitry Andric     LT = llvm::GlobalValue::LinkOnceODRLinkage;
352659d1ed5bSDimitry Andric     GlobalVariableName = MangledNameBuffer;
352759d1ed5bSDimitry Andric   } else {
352859d1ed5bSDimitry Andric     LT = llvm::GlobalValue::PrivateLinkage;
352939d628a0SDimitry Andric     GlobalVariableName = Name;
353059d1ed5bSDimitry Andric   }
353159d1ed5bSDimitry Andric 
353259d1ed5bSDimitry Andric   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
353359d1ed5bSDimitry Andric   if (Entry)
353459d1ed5bSDimitry Andric     *Entry = GV;
353559d1ed5bSDimitry Andric 
353639d628a0SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
353739d628a0SDimitry Andric                                   QualType());
35380623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
3539f22ef01cSRoman Divacky }
3540f22ef01cSRoman Divacky 
3541f22ef01cSRoman Divacky /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
3542f22ef01cSRoman Divacky /// array for the given ObjCEncodeExpr node.
35430623d748SDimitry Andric ConstantAddress
3544f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
3545f22ef01cSRoman Divacky   std::string Str;
3546f22ef01cSRoman Divacky   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
3547f22ef01cSRoman Divacky 
3548f22ef01cSRoman Divacky   return GetAddrOfConstantCString(Str);
3549f22ef01cSRoman Divacky }
3550f22ef01cSRoman Divacky 
355159d1ed5bSDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing
355259d1ed5bSDimitry Andric /// the literal and a terminating '\0' character.
355359d1ed5bSDimitry Andric /// The result has pointer to array type.
35540623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString(
35550623d748SDimitry Andric     const std::string &Str, const char *GlobalName) {
355659d1ed5bSDimitry Andric   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
35570623d748SDimitry Andric   CharUnits Alignment =
35580623d748SDimitry Andric     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
3559f22ef01cSRoman Divacky 
356059d1ed5bSDimitry Andric   llvm::Constant *C =
356159d1ed5bSDimitry Andric       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
356259d1ed5bSDimitry Andric 
356359d1ed5bSDimitry Andric   // Don't share any string literals if strings aren't constant.
356459d1ed5bSDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
356559d1ed5bSDimitry Andric   if (!LangOpts.WritableStrings) {
356659d1ed5bSDimitry Andric     Entry = &ConstantStringMap[C];
356759d1ed5bSDimitry Andric     if (auto GV = *Entry) {
35680623d748SDimitry Andric       if (Alignment.getQuantity() > GV->getAlignment())
35690623d748SDimitry Andric         GV->setAlignment(Alignment.getQuantity());
35700623d748SDimitry Andric       return ConstantAddress(GV, Alignment);
357159d1ed5bSDimitry Andric     }
357259d1ed5bSDimitry Andric   }
357359d1ed5bSDimitry Andric 
3574f22ef01cSRoman Divacky   // Get the default prefix if a name wasn't specified.
3575f22ef01cSRoman Divacky   if (!GlobalName)
3576f22ef01cSRoman Divacky     GlobalName = ".str";
3577f22ef01cSRoman Divacky   // Create a global variable for this.
357859d1ed5bSDimitry Andric   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
357959d1ed5bSDimitry Andric                                   GlobalName, Alignment);
358059d1ed5bSDimitry Andric   if (Entry)
358159d1ed5bSDimitry Andric     *Entry = GV;
35820623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
3583f22ef01cSRoman Divacky }
3584f22ef01cSRoman Divacky 
35850623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
3586f785676fSDimitry Andric     const MaterializeTemporaryExpr *E, const Expr *Init) {
3587f785676fSDimitry Andric   assert((E->getStorageDuration() == SD_Static ||
3588f785676fSDimitry Andric           E->getStorageDuration() == SD_Thread) && "not a global temporary");
358959d1ed5bSDimitry Andric   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
3590f785676fSDimitry Andric 
3591f785676fSDimitry Andric   // If we're not materializing a subobject of the temporary, keep the
3592f785676fSDimitry Andric   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
3593f785676fSDimitry Andric   QualType MaterializedType = Init->getType();
3594f785676fSDimitry Andric   if (Init == E->GetTemporaryExpr())
3595f785676fSDimitry Andric     MaterializedType = E->getType();
3596f785676fSDimitry Andric 
35970623d748SDimitry Andric   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
35980623d748SDimitry Andric 
35990623d748SDimitry Andric   if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
36000623d748SDimitry Andric     return ConstantAddress(Slot, Align);
3601f785676fSDimitry Andric 
3602f785676fSDimitry Andric   // FIXME: If an externally-visible declaration extends multiple temporaries,
3603f785676fSDimitry Andric   // we need to give each temporary the same name in every translation unit (and
3604f785676fSDimitry Andric   // we also need to make the temporaries externally-visible).
3605f785676fSDimitry Andric   SmallString<256> Name;
3606f785676fSDimitry Andric   llvm::raw_svector_ostream Out(Name);
360759d1ed5bSDimitry Andric   getCXXABI().getMangleContext().mangleReferenceTemporary(
360859d1ed5bSDimitry Andric       VD, E->getManglingNumber(), Out);
3609f785676fSDimitry Andric 
361059d1ed5bSDimitry Andric   APValue *Value = nullptr;
3611f785676fSDimitry Andric   if (E->getStorageDuration() == SD_Static) {
3612f785676fSDimitry Andric     // We might have a cached constant initializer for this temporary. Note
3613f785676fSDimitry Andric     // that this might have a different value from the value computed by
3614f785676fSDimitry Andric     // evaluating the initializer if the surrounding constant expression
3615f785676fSDimitry Andric     // modifies the temporary.
3616f785676fSDimitry Andric     Value = getContext().getMaterializedTemporaryValue(E, false);
3617f785676fSDimitry Andric     if (Value && Value->isUninit())
361859d1ed5bSDimitry Andric       Value = nullptr;
3619f785676fSDimitry Andric   }
3620f785676fSDimitry Andric 
3621f785676fSDimitry Andric   // Try evaluating it now, it might have a constant initializer.
3622f785676fSDimitry Andric   Expr::EvalResult EvalResult;
3623f785676fSDimitry Andric   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3624f785676fSDimitry Andric       !EvalResult.hasSideEffects())
3625f785676fSDimitry Andric     Value = &EvalResult.Val;
3626f785676fSDimitry Andric 
362759d1ed5bSDimitry Andric   llvm::Constant *InitialValue = nullptr;
3628f785676fSDimitry Andric   bool Constant = false;
3629f785676fSDimitry Andric   llvm::Type *Type;
3630f785676fSDimitry Andric   if (Value) {
3631f785676fSDimitry Andric     // The temporary has a constant initializer, use it.
363259d1ed5bSDimitry Andric     InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
3633f785676fSDimitry Andric     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3634f785676fSDimitry Andric     Type = InitialValue->getType();
3635f785676fSDimitry Andric   } else {
3636f785676fSDimitry Andric     // No initializer, the initialization will be provided when we
3637f785676fSDimitry Andric     // initialize the declaration which performed lifetime extension.
3638f785676fSDimitry Andric     Type = getTypes().ConvertTypeForMem(MaterializedType);
3639f785676fSDimitry Andric   }
3640f785676fSDimitry Andric 
3641f785676fSDimitry Andric   // Create a global variable for this lifetime-extended temporary.
364259d1ed5bSDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
364359d1ed5bSDimitry Andric       getLLVMLinkageVarDefinition(VD, Constant);
364433956c43SDimitry Andric   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
364533956c43SDimitry Andric     const VarDecl *InitVD;
364633956c43SDimitry Andric     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
364733956c43SDimitry Andric         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
364833956c43SDimitry Andric       // Temporaries defined inside a class get linkonce_odr linkage because the
364933956c43SDimitry Andric       // class can be defined in multipe translation units.
365033956c43SDimitry Andric       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
365133956c43SDimitry Andric     } else {
365233956c43SDimitry Andric       // There is no need for this temporary to have external linkage if the
365333956c43SDimitry Andric       // VarDecl has external linkage.
365433956c43SDimitry Andric       Linkage = llvm::GlobalVariable::InternalLinkage;
365533956c43SDimitry Andric     }
365633956c43SDimitry Andric   }
365759d1ed5bSDimitry Andric   unsigned AddrSpace = GetGlobalVarAddressSpace(
365859d1ed5bSDimitry Andric       VD, getContext().getTargetAddressSpace(MaterializedType));
365959d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
366059d1ed5bSDimitry Andric       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
366159d1ed5bSDimitry Andric       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
366259d1ed5bSDimitry Andric       AddrSpace);
366359d1ed5bSDimitry Andric   setGlobalVisibility(GV, VD);
36640623d748SDimitry Andric   GV->setAlignment(Align.getQuantity());
366533956c43SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker())
366633956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3667f785676fSDimitry Andric   if (VD->getTLSKind())
3668f785676fSDimitry Andric     setTLSMode(GV, *VD);
36690623d748SDimitry Andric   MaterializedGlobalTemporaryMap[E] = GV;
36700623d748SDimitry Andric   return ConstantAddress(GV, Align);
3671f785676fSDimitry Andric }
3672f785676fSDimitry Andric 
3673f22ef01cSRoman Divacky /// EmitObjCPropertyImplementations - Emit information for synthesized
3674f22ef01cSRoman Divacky /// properties for an implementation.
3675f22ef01cSRoman Divacky void CodeGenModule::EmitObjCPropertyImplementations(const
3676f22ef01cSRoman Divacky                                                     ObjCImplementationDecl *D) {
367759d1ed5bSDimitry Andric   for (const auto *PID : D->property_impls()) {
3678f22ef01cSRoman Divacky     // Dynamic is just for type-checking.
3679f22ef01cSRoman Divacky     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3680f22ef01cSRoman Divacky       ObjCPropertyDecl *PD = PID->getPropertyDecl();
3681f22ef01cSRoman Divacky 
3682f22ef01cSRoman Divacky       // Determine which methods need to be implemented, some may have
36833861d79fSDimitry Andric       // been overridden. Note that ::isPropertyAccessor is not the method
3684f22ef01cSRoman Divacky       // we want, that just indicates if the decl came from a
3685f22ef01cSRoman Divacky       // property. What we want to know is if the method is defined in
3686f22ef01cSRoman Divacky       // this implementation.
3687f22ef01cSRoman Divacky       if (!D->getInstanceMethod(PD->getGetterName()))
3688f22ef01cSRoman Divacky         CodeGenFunction(*this).GenerateObjCGetter(
3689f22ef01cSRoman Divacky                                  const_cast<ObjCImplementationDecl *>(D), PID);
3690f22ef01cSRoman Divacky       if (!PD->isReadOnly() &&
3691f22ef01cSRoman Divacky           !D->getInstanceMethod(PD->getSetterName()))
3692f22ef01cSRoman Divacky         CodeGenFunction(*this).GenerateObjCSetter(
3693f22ef01cSRoman Divacky                                  const_cast<ObjCImplementationDecl *>(D), PID);
3694f22ef01cSRoman Divacky     }
3695f22ef01cSRoman Divacky   }
3696f22ef01cSRoman Divacky }
3697f22ef01cSRoman Divacky 
36983b0f4066SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) {
36996122f3e6SDimitry Andric   const ObjCInterfaceDecl *iface = impl->getClassInterface();
37006122f3e6SDimitry Andric   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
37013b0f4066SDimitry Andric        ivar; ivar = ivar->getNextIvar())
37023b0f4066SDimitry Andric     if (ivar->getType().isDestructedType())
37033b0f4066SDimitry Andric       return true;
37043b0f4066SDimitry Andric 
37053b0f4066SDimitry Andric   return false;
37063b0f4066SDimitry Andric }
37073b0f4066SDimitry Andric 
370839d628a0SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM,
370939d628a0SDimitry Andric                                    ObjCImplementationDecl *D) {
371039d628a0SDimitry Andric   CodeGenFunction CGF(CGM);
371139d628a0SDimitry Andric   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
371239d628a0SDimitry Andric        E = D->init_end(); B != E; ++B) {
371339d628a0SDimitry Andric     CXXCtorInitializer *CtorInitExp = *B;
371439d628a0SDimitry Andric     Expr *Init = CtorInitExp->getInit();
371539d628a0SDimitry Andric     if (!CGF.isTrivialInitializer(Init))
371639d628a0SDimitry Andric       return false;
371739d628a0SDimitry Andric   }
371839d628a0SDimitry Andric   return true;
371939d628a0SDimitry Andric }
372039d628a0SDimitry Andric 
3721f22ef01cSRoman Divacky /// EmitObjCIvarInitializations - Emit information for ivar initialization
3722f22ef01cSRoman Divacky /// for an implementation.
3723f22ef01cSRoman Divacky void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
37243b0f4066SDimitry Andric   // We might need a .cxx_destruct even if we don't have any ivar initializers.
37253b0f4066SDimitry Andric   if (needsDestructMethod(D)) {
3726f22ef01cSRoman Divacky     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3727f22ef01cSRoman Divacky     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
37283b0f4066SDimitry Andric     ObjCMethodDecl *DTORMethod =
37293b0f4066SDimitry Andric       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
373059d1ed5bSDimitry Andric                              cxxSelector, getContext().VoidTy, nullptr, D,
37316122f3e6SDimitry Andric                              /*isInstance=*/true, /*isVariadic=*/false,
37323861d79fSDimitry Andric                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
37336122f3e6SDimitry Andric                              /*isDefined=*/false, ObjCMethodDecl::Required);
3734f22ef01cSRoman Divacky     D->addInstanceMethod(DTORMethod);
3735f22ef01cSRoman Divacky     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
37363861d79fSDimitry Andric     D->setHasDestructors(true);
37373b0f4066SDimitry Andric   }
3738f22ef01cSRoman Divacky 
37393b0f4066SDimitry Andric   // If the implementation doesn't have any ivar initializers, we don't need
37403b0f4066SDimitry Andric   // a .cxx_construct.
374139d628a0SDimitry Andric   if (D->getNumIvarInitializers() == 0 ||
374239d628a0SDimitry Andric       AllTrivialInitializers(*this, D))
37433b0f4066SDimitry Andric     return;
37443b0f4066SDimitry Andric 
37453b0f4066SDimitry Andric   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
37463b0f4066SDimitry Andric   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3747f22ef01cSRoman Divacky   // The constructor returns 'self'.
3748f22ef01cSRoman Divacky   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3749f22ef01cSRoman Divacky                                                 D->getLocation(),
37506122f3e6SDimitry Andric                                                 D->getLocation(),
37516122f3e6SDimitry Andric                                                 cxxSelector,
375259d1ed5bSDimitry Andric                                                 getContext().getObjCIdType(),
375359d1ed5bSDimitry Andric                                                 nullptr, D, /*isInstance=*/true,
37546122f3e6SDimitry Andric                                                 /*isVariadic=*/false,
37553861d79fSDimitry Andric                                                 /*isPropertyAccessor=*/true,
37566122f3e6SDimitry Andric                                                 /*isImplicitlyDeclared=*/true,
37576122f3e6SDimitry Andric                                                 /*isDefined=*/false,
3758f22ef01cSRoman Divacky                                                 ObjCMethodDecl::Required);
3759f22ef01cSRoman Divacky   D->addInstanceMethod(CTORMethod);
3760f22ef01cSRoman Divacky   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
37613861d79fSDimitry Andric   D->setHasNonZeroConstructors(true);
3762f22ef01cSRoman Divacky }
3763f22ef01cSRoman Divacky 
3764f22ef01cSRoman Divacky // EmitLinkageSpec - Emit all declarations in a linkage spec.
3765f22ef01cSRoman Divacky void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
3766f22ef01cSRoman Divacky   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3767f22ef01cSRoman Divacky       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
3768f22ef01cSRoman Divacky     ErrorUnsupported(LSD, "linkage spec");
3769f22ef01cSRoman Divacky     return;
3770f22ef01cSRoman Divacky   }
3771f22ef01cSRoman Divacky 
377244290647SDimitry Andric   EmitDeclContext(LSD);
377344290647SDimitry Andric }
377444290647SDimitry Andric 
377544290647SDimitry Andric void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
377644290647SDimitry Andric   for (auto *I : DC->decls()) {
377744290647SDimitry Andric     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
377844290647SDimitry Andric     // are themselves considered "top-level", so EmitTopLevelDecl on an
377944290647SDimitry Andric     // ObjCImplDecl does not recursively visit them. We need to do that in
378044290647SDimitry Andric     // case they're nested inside another construct (LinkageSpecDecl /
378144290647SDimitry Andric     // ExportDecl) that does stop them from being considered "top-level".
378259d1ed5bSDimitry Andric     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
378359d1ed5bSDimitry Andric       for (auto *M : OID->methods())
378459d1ed5bSDimitry Andric         EmitTopLevelDecl(M);
37853861d79fSDimitry Andric     }
378644290647SDimitry Andric 
378759d1ed5bSDimitry Andric     EmitTopLevelDecl(I);
3788f22ef01cSRoman Divacky   }
37893861d79fSDimitry Andric }
3790f22ef01cSRoman Divacky 
3791f22ef01cSRoman Divacky /// EmitTopLevelDecl - Emit code for a single top level declaration.
3792f22ef01cSRoman Divacky void CodeGenModule::EmitTopLevelDecl(Decl *D) {
3793f22ef01cSRoman Divacky   // Ignore dependent declarations.
3794f22ef01cSRoman Divacky   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3795f22ef01cSRoman Divacky     return;
3796f22ef01cSRoman Divacky 
3797f22ef01cSRoman Divacky   switch (D->getKind()) {
3798f22ef01cSRoman Divacky   case Decl::CXXConversion:
3799f22ef01cSRoman Divacky   case Decl::CXXMethod:
3800f22ef01cSRoman Divacky   case Decl::Function:
3801f22ef01cSRoman Divacky     // Skip function templates
38023b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
38033b0f4066SDimitry Andric         cast<FunctionDecl>(D)->isLateTemplateParsed())
3804f22ef01cSRoman Divacky       return;
3805f22ef01cSRoman Divacky 
3806f22ef01cSRoman Divacky     EmitGlobal(cast<FunctionDecl>(D));
380739d628a0SDimitry Andric     // Always provide some coverage mapping
380839d628a0SDimitry Andric     // even for the functions that aren't emitted.
380939d628a0SDimitry Andric     AddDeferredUnusedCoverageMapping(D);
3810f22ef01cSRoman Divacky     break;
3811f22ef01cSRoman Divacky 
38126bc11b14SDimitry Andric   case Decl::CXXDeductionGuide:
38136bc11b14SDimitry Andric     // Function-like, but does not result in code emission.
38146bc11b14SDimitry Andric     break;
38156bc11b14SDimitry Andric 
3816f22ef01cSRoman Divacky   case Decl::Var:
381744290647SDimitry Andric   case Decl::Decomposition:
3818f785676fSDimitry Andric     // Skip variable templates
3819f785676fSDimitry Andric     if (cast<VarDecl>(D)->getDescribedVarTemplate())
3820f785676fSDimitry Andric       return;
3821f785676fSDimitry Andric   case Decl::VarTemplateSpecialization:
3822f22ef01cSRoman Divacky     EmitGlobal(cast<VarDecl>(D));
382344290647SDimitry Andric     if (auto *DD = dyn_cast<DecompositionDecl>(D))
382444290647SDimitry Andric       for (auto *B : DD->bindings())
382544290647SDimitry Andric         if (auto *HD = B->getHoldingVar())
382644290647SDimitry Andric           EmitGlobal(HD);
3827f22ef01cSRoman Divacky     break;
3828f22ef01cSRoman Divacky 
38293b0f4066SDimitry Andric   // Indirect fields from global anonymous structs and unions can be
38303b0f4066SDimitry Andric   // ignored; only the actual variable requires IR gen support.
38313b0f4066SDimitry Andric   case Decl::IndirectField:
38323b0f4066SDimitry Andric     break;
38333b0f4066SDimitry Andric 
3834f22ef01cSRoman Divacky   // C++ Decls
3835f22ef01cSRoman Divacky   case Decl::Namespace:
383644290647SDimitry Andric     EmitDeclContext(cast<NamespaceDecl>(D));
3837f22ef01cSRoman Divacky     break;
3838e7145dcbSDimitry Andric   case Decl::CXXRecord:
383920e90f04SDimitry Andric     if (DebugInfo) {
384020e90f04SDimitry Andric       if (auto *ES = D->getASTContext().getExternalSource())
384120e90f04SDimitry Andric         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
384220e90f04SDimitry Andric           DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
384320e90f04SDimitry Andric     }
3844e7145dcbSDimitry Andric     // Emit any static data members, they may be definitions.
3845e7145dcbSDimitry Andric     for (auto *I : cast<CXXRecordDecl>(D)->decls())
3846e7145dcbSDimitry Andric       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
3847e7145dcbSDimitry Andric         EmitTopLevelDecl(I);
3848e7145dcbSDimitry Andric     break;
3849f22ef01cSRoman Divacky     // No code generation needed.
3850f22ef01cSRoman Divacky   case Decl::UsingShadow:
3851f22ef01cSRoman Divacky   case Decl::ClassTemplate:
3852f785676fSDimitry Andric   case Decl::VarTemplate:
3853f785676fSDimitry Andric   case Decl::VarTemplatePartialSpecialization:
3854f22ef01cSRoman Divacky   case Decl::FunctionTemplate:
3855bd5abe19SDimitry Andric   case Decl::TypeAliasTemplate:
3856bd5abe19SDimitry Andric   case Decl::Block:
3857139f7f9bSDimitry Andric   case Decl::Empty:
3858f22ef01cSRoman Divacky     break;
385959d1ed5bSDimitry Andric   case Decl::Using:          // using X; [C++]
386059d1ed5bSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
386159d1ed5bSDimitry Andric         DI->EmitUsingDecl(cast<UsingDecl>(*D));
386259d1ed5bSDimitry Andric     return;
3863f785676fSDimitry Andric   case Decl::NamespaceAlias:
3864f785676fSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
3865f785676fSDimitry Andric         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3866f785676fSDimitry Andric     return;
3867284c1978SDimitry Andric   case Decl::UsingDirective: // using namespace X; [C++]
3868284c1978SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
3869284c1978SDimitry Andric       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3870284c1978SDimitry Andric     return;
3871f22ef01cSRoman Divacky   case Decl::CXXConstructor:
3872f22ef01cSRoman Divacky     // Skip function templates
38733b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
38743b0f4066SDimitry Andric         cast<FunctionDecl>(D)->isLateTemplateParsed())
3875f22ef01cSRoman Divacky       return;
3876f22ef01cSRoman Divacky 
3877f785676fSDimitry Andric     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
3878f22ef01cSRoman Divacky     break;
3879f22ef01cSRoman Divacky   case Decl::CXXDestructor:
38803b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
38813b0f4066SDimitry Andric       return;
3882f785676fSDimitry Andric     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
3883f22ef01cSRoman Divacky     break;
3884f22ef01cSRoman Divacky 
3885f22ef01cSRoman Divacky   case Decl::StaticAssert:
3886f22ef01cSRoman Divacky     // Nothing to do.
3887f22ef01cSRoman Divacky     break;
3888f22ef01cSRoman Divacky 
3889f22ef01cSRoman Divacky   // Objective-C Decls
3890f22ef01cSRoman Divacky 
3891f22ef01cSRoman Divacky   // Forward declarations, no (immediate) code generation.
3892f22ef01cSRoman Divacky   case Decl::ObjCInterface:
38937ae0e2c9SDimitry Andric   case Decl::ObjCCategory:
3894f22ef01cSRoman Divacky     break;
3895f22ef01cSRoman Divacky 
3896dff0c46cSDimitry Andric   case Decl::ObjCProtocol: {
389759d1ed5bSDimitry Andric     auto *Proto = cast<ObjCProtocolDecl>(D);
3898dff0c46cSDimitry Andric     if (Proto->isThisDeclarationADefinition())
3899dff0c46cSDimitry Andric       ObjCRuntime->GenerateProtocol(Proto);
3900f22ef01cSRoman Divacky     break;
3901dff0c46cSDimitry Andric   }
3902f22ef01cSRoman Divacky 
3903f22ef01cSRoman Divacky   case Decl::ObjCCategoryImpl:
3904f22ef01cSRoman Divacky     // Categories have properties but don't support synthesize so we
3905f22ef01cSRoman Divacky     // can ignore them here.
39066122f3e6SDimitry Andric     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
3907f22ef01cSRoman Divacky     break;
3908f22ef01cSRoman Divacky 
3909f22ef01cSRoman Divacky   case Decl::ObjCImplementation: {
391059d1ed5bSDimitry Andric     auto *OMD = cast<ObjCImplementationDecl>(D);
3911f22ef01cSRoman Divacky     EmitObjCPropertyImplementations(OMD);
3912f22ef01cSRoman Divacky     EmitObjCIvarInitializations(OMD);
39136122f3e6SDimitry Andric     ObjCRuntime->GenerateClass(OMD);
3914dff0c46cSDimitry Andric     // Emit global variable debug information.
3915dff0c46cSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
3916e7145dcbSDimitry Andric       if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
3917139f7f9bSDimitry Andric         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3918139f7f9bSDimitry Andric             OMD->getClassInterface()), OMD->getLocation());
3919f22ef01cSRoman Divacky     break;
3920f22ef01cSRoman Divacky   }
3921f22ef01cSRoman Divacky   case Decl::ObjCMethod: {
392259d1ed5bSDimitry Andric     auto *OMD = cast<ObjCMethodDecl>(D);
3923f22ef01cSRoman Divacky     // If this is not a prototype, emit the body.
3924f22ef01cSRoman Divacky     if (OMD->getBody())
3925f22ef01cSRoman Divacky       CodeGenFunction(*this).GenerateObjCMethod(OMD);
3926f22ef01cSRoman Divacky     break;
3927f22ef01cSRoman Divacky   }
3928f22ef01cSRoman Divacky   case Decl::ObjCCompatibleAlias:
3929dff0c46cSDimitry Andric     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3930f22ef01cSRoman Divacky     break;
3931f22ef01cSRoman Divacky 
3932e7145dcbSDimitry Andric   case Decl::PragmaComment: {
3933e7145dcbSDimitry Andric     const auto *PCD = cast<PragmaCommentDecl>(D);
3934e7145dcbSDimitry Andric     switch (PCD->getCommentKind()) {
3935e7145dcbSDimitry Andric     case PCK_Unknown:
3936e7145dcbSDimitry Andric       llvm_unreachable("unexpected pragma comment kind");
3937e7145dcbSDimitry Andric     case PCK_Linker:
3938e7145dcbSDimitry Andric       AppendLinkerOptions(PCD->getArg());
3939e7145dcbSDimitry Andric       break;
3940e7145dcbSDimitry Andric     case PCK_Lib:
3941e7145dcbSDimitry Andric       AddDependentLib(PCD->getArg());
3942e7145dcbSDimitry Andric       break;
3943e7145dcbSDimitry Andric     case PCK_Compiler:
3944e7145dcbSDimitry Andric     case PCK_ExeStr:
3945e7145dcbSDimitry Andric     case PCK_User:
3946e7145dcbSDimitry Andric       break; // We ignore all of these.
3947e7145dcbSDimitry Andric     }
3948e7145dcbSDimitry Andric     break;
3949e7145dcbSDimitry Andric   }
3950e7145dcbSDimitry Andric 
3951e7145dcbSDimitry Andric   case Decl::PragmaDetectMismatch: {
3952e7145dcbSDimitry Andric     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
3953e7145dcbSDimitry Andric     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
3954e7145dcbSDimitry Andric     break;
3955e7145dcbSDimitry Andric   }
3956e7145dcbSDimitry Andric 
3957f22ef01cSRoman Divacky   case Decl::LinkageSpec:
3958f22ef01cSRoman Divacky     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
3959f22ef01cSRoman Divacky     break;
3960f22ef01cSRoman Divacky 
3961f22ef01cSRoman Divacky   case Decl::FileScopeAsm: {
396233956c43SDimitry Andric     // File-scope asm is ignored during device-side CUDA compilation.
396333956c43SDimitry Andric     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
396433956c43SDimitry Andric       break;
3965ea942507SDimitry Andric     // File-scope asm is ignored during device-side OpenMP compilation.
3966ea942507SDimitry Andric     if (LangOpts.OpenMPIsDevice)
3967ea942507SDimitry Andric       break;
396859d1ed5bSDimitry Andric     auto *AD = cast<FileScopeAsmDecl>(D);
396933956c43SDimitry Andric     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
3970f22ef01cSRoman Divacky     break;
3971f22ef01cSRoman Divacky   }
3972f22ef01cSRoman Divacky 
3973139f7f9bSDimitry Andric   case Decl::Import: {
397459d1ed5bSDimitry Andric     auto *Import = cast<ImportDecl>(D);
3975139f7f9bSDimitry Andric 
397644290647SDimitry Andric     // If we've already imported this module, we're done.
397744290647SDimitry Andric     if (!ImportedModules.insert(Import->getImportedModule()))
3978139f7f9bSDimitry Andric       break;
397944290647SDimitry Andric 
398044290647SDimitry Andric     // Emit debug information for direct imports.
398144290647SDimitry Andric     if (!Import->getImportedOwningModule()) {
39823dac3a9bSDimitry Andric       if (CGDebugInfo *DI = getModuleDebugInfo())
39833dac3a9bSDimitry Andric         DI->EmitImportDecl(*Import);
398444290647SDimitry Andric     }
3985139f7f9bSDimitry Andric 
398644290647SDimitry Andric     // Find all of the submodules and emit the module initializers.
398744290647SDimitry Andric     llvm::SmallPtrSet<clang::Module *, 16> Visited;
398844290647SDimitry Andric     SmallVector<clang::Module *, 16> Stack;
398944290647SDimitry Andric     Visited.insert(Import->getImportedModule());
399044290647SDimitry Andric     Stack.push_back(Import->getImportedModule());
399144290647SDimitry Andric 
399244290647SDimitry Andric     while (!Stack.empty()) {
399344290647SDimitry Andric       clang::Module *Mod = Stack.pop_back_val();
399444290647SDimitry Andric       if (!EmittedModuleInitializers.insert(Mod).second)
399544290647SDimitry Andric         continue;
399644290647SDimitry Andric 
399744290647SDimitry Andric       for (auto *D : Context.getModuleInitializers(Mod))
399844290647SDimitry Andric         EmitTopLevelDecl(D);
399944290647SDimitry Andric 
400044290647SDimitry Andric       // Visit the submodules of this module.
400144290647SDimitry Andric       for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
400244290647SDimitry Andric                                              SubEnd = Mod->submodule_end();
400344290647SDimitry Andric            Sub != SubEnd; ++Sub) {
400444290647SDimitry Andric         // Skip explicit children; they need to be explicitly imported to emit
400544290647SDimitry Andric         // the initializers.
400644290647SDimitry Andric         if ((*Sub)->IsExplicit)
400744290647SDimitry Andric           continue;
400844290647SDimitry Andric 
400944290647SDimitry Andric         if (Visited.insert(*Sub).second)
401044290647SDimitry Andric           Stack.push_back(*Sub);
401144290647SDimitry Andric       }
401244290647SDimitry Andric     }
4013139f7f9bSDimitry Andric     break;
4014139f7f9bSDimitry Andric   }
4015139f7f9bSDimitry Andric 
401644290647SDimitry Andric   case Decl::Export:
401744290647SDimitry Andric     EmitDeclContext(cast<ExportDecl>(D));
401844290647SDimitry Andric     break;
401944290647SDimitry Andric 
402039d628a0SDimitry Andric   case Decl::OMPThreadPrivate:
402139d628a0SDimitry Andric     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
402239d628a0SDimitry Andric     break;
402339d628a0SDimitry Andric 
402459d1ed5bSDimitry Andric   case Decl::ClassTemplateSpecialization: {
402559d1ed5bSDimitry Andric     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
402659d1ed5bSDimitry Andric     if (DebugInfo &&
402739d628a0SDimitry Andric         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
402839d628a0SDimitry Andric         Spec->hasDefinition())
402959d1ed5bSDimitry Andric       DebugInfo->completeTemplateDefinition(*Spec);
403039d628a0SDimitry Andric     break;
403159d1ed5bSDimitry Andric   }
403259d1ed5bSDimitry Andric 
4033e7145dcbSDimitry Andric   case Decl::OMPDeclareReduction:
4034e7145dcbSDimitry Andric     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
4035e7145dcbSDimitry Andric     break;
4036e7145dcbSDimitry Andric 
4037f22ef01cSRoman Divacky   default:
4038f22ef01cSRoman Divacky     // Make sure we handled everything we should, every other kind is a
4039f22ef01cSRoman Divacky     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
4040f22ef01cSRoman Divacky     // function. Need to recode Decl::Kind to do that easily.
4041f22ef01cSRoman Divacky     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
404239d628a0SDimitry Andric     break;
404339d628a0SDimitry Andric   }
404439d628a0SDimitry Andric }
404539d628a0SDimitry Andric 
404639d628a0SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
404739d628a0SDimitry Andric   // Do we need to generate coverage mapping?
404839d628a0SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
404939d628a0SDimitry Andric     return;
405039d628a0SDimitry Andric   switch (D->getKind()) {
405139d628a0SDimitry Andric   case Decl::CXXConversion:
405239d628a0SDimitry Andric   case Decl::CXXMethod:
405339d628a0SDimitry Andric   case Decl::Function:
405439d628a0SDimitry Andric   case Decl::ObjCMethod:
405539d628a0SDimitry Andric   case Decl::CXXConstructor:
405639d628a0SDimitry Andric   case Decl::CXXDestructor: {
40570623d748SDimitry Andric     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
405839d628a0SDimitry Andric       return;
405939d628a0SDimitry Andric     auto I = DeferredEmptyCoverageMappingDecls.find(D);
406039d628a0SDimitry Andric     if (I == DeferredEmptyCoverageMappingDecls.end())
406139d628a0SDimitry Andric       DeferredEmptyCoverageMappingDecls[D] = true;
406239d628a0SDimitry Andric     break;
406339d628a0SDimitry Andric   }
406439d628a0SDimitry Andric   default:
406539d628a0SDimitry Andric     break;
406639d628a0SDimitry Andric   };
406739d628a0SDimitry Andric }
406839d628a0SDimitry Andric 
406939d628a0SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
407039d628a0SDimitry Andric   // Do we need to generate coverage mapping?
407139d628a0SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
407239d628a0SDimitry Andric     return;
407339d628a0SDimitry Andric   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
407439d628a0SDimitry Andric     if (Fn->isTemplateInstantiation())
407539d628a0SDimitry Andric       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
407639d628a0SDimitry Andric   }
407739d628a0SDimitry Andric   auto I = DeferredEmptyCoverageMappingDecls.find(D);
407839d628a0SDimitry Andric   if (I == DeferredEmptyCoverageMappingDecls.end())
407939d628a0SDimitry Andric     DeferredEmptyCoverageMappingDecls[D] = false;
408039d628a0SDimitry Andric   else
408139d628a0SDimitry Andric     I->second = false;
408239d628a0SDimitry Andric }
408339d628a0SDimitry Andric 
408439d628a0SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
408539d628a0SDimitry Andric   std::vector<const Decl *> DeferredDecls;
408633956c43SDimitry Andric   for (const auto &I : DeferredEmptyCoverageMappingDecls) {
408739d628a0SDimitry Andric     if (!I.second)
408839d628a0SDimitry Andric       continue;
408939d628a0SDimitry Andric     DeferredDecls.push_back(I.first);
409039d628a0SDimitry Andric   }
409139d628a0SDimitry Andric   // Sort the declarations by their location to make sure that the tests get a
409239d628a0SDimitry Andric   // predictable order for the coverage mapping for the unused declarations.
409339d628a0SDimitry Andric   if (CodeGenOpts.DumpCoverageMapping)
409439d628a0SDimitry Andric     std::sort(DeferredDecls.begin(), DeferredDecls.end(),
409539d628a0SDimitry Andric               [] (const Decl *LHS, const Decl *RHS) {
409639d628a0SDimitry Andric       return LHS->getLocStart() < RHS->getLocStart();
409739d628a0SDimitry Andric     });
409839d628a0SDimitry Andric   for (const auto *D : DeferredDecls) {
409939d628a0SDimitry Andric     switch (D->getKind()) {
410039d628a0SDimitry Andric     case Decl::CXXConversion:
410139d628a0SDimitry Andric     case Decl::CXXMethod:
410239d628a0SDimitry Andric     case Decl::Function:
410339d628a0SDimitry Andric     case Decl::ObjCMethod: {
410439d628a0SDimitry Andric       CodeGenPGO PGO(*this);
410539d628a0SDimitry Andric       GlobalDecl GD(cast<FunctionDecl>(D));
410639d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
410739d628a0SDimitry Andric                                   getFunctionLinkage(GD));
410839d628a0SDimitry Andric       break;
410939d628a0SDimitry Andric     }
411039d628a0SDimitry Andric     case Decl::CXXConstructor: {
411139d628a0SDimitry Andric       CodeGenPGO PGO(*this);
411239d628a0SDimitry Andric       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
411339d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
411439d628a0SDimitry Andric                                   getFunctionLinkage(GD));
411539d628a0SDimitry Andric       break;
411639d628a0SDimitry Andric     }
411739d628a0SDimitry Andric     case Decl::CXXDestructor: {
411839d628a0SDimitry Andric       CodeGenPGO PGO(*this);
411939d628a0SDimitry Andric       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
412039d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
412139d628a0SDimitry Andric                                   getFunctionLinkage(GD));
412239d628a0SDimitry Andric       break;
412339d628a0SDimitry Andric     }
412439d628a0SDimitry Andric     default:
412539d628a0SDimitry Andric       break;
412639d628a0SDimitry Andric     };
4127f22ef01cSRoman Divacky   }
4128f22ef01cSRoman Divacky }
4129ffd1746dSEd Schouten 
4130ffd1746dSEd Schouten /// Turns the given pointer into a constant.
4131ffd1746dSEd Schouten static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
4132ffd1746dSEd Schouten                                           const void *Ptr) {
4133ffd1746dSEd Schouten   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
41346122f3e6SDimitry Andric   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
4135ffd1746dSEd Schouten   return llvm::ConstantInt::get(i64, PtrInt);
4136ffd1746dSEd Schouten }
4137ffd1746dSEd Schouten 
4138ffd1746dSEd Schouten static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
4139ffd1746dSEd Schouten                                    llvm::NamedMDNode *&GlobalMetadata,
4140ffd1746dSEd Schouten                                    GlobalDecl D,
4141ffd1746dSEd Schouten                                    llvm::GlobalValue *Addr) {
4142ffd1746dSEd Schouten   if (!GlobalMetadata)
4143ffd1746dSEd Schouten     GlobalMetadata =
4144ffd1746dSEd Schouten       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
4145ffd1746dSEd Schouten 
4146ffd1746dSEd Schouten   // TODO: should we report variant information for ctors/dtors?
414739d628a0SDimitry Andric   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
414839d628a0SDimitry Andric                            llvm::ConstantAsMetadata::get(GetPointerConstant(
414939d628a0SDimitry Andric                                CGM.getLLVMContext(), D.getDecl()))};
41503b0f4066SDimitry Andric   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
4151ffd1746dSEd Schouten }
4152ffd1746dSEd Schouten 
4153284c1978SDimitry Andric /// For each function which is declared within an extern "C" region and marked
4154284c1978SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled
4155284c1978SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer
4156284c1978SDimitry Andric /// to such functions with an unmangled name from inline assembly within the
4157284c1978SDimitry Andric /// same translation unit.
4158284c1978SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() {
4159e7145dcbSDimitry Andric   // Don't do anything if we're generating CUDA device code -- the NVPTX
4160e7145dcbSDimitry Andric   // assembly target doesn't support aliases.
4161e7145dcbSDimitry Andric   if (Context.getTargetInfo().getTriple().isNVPTX())
4162e7145dcbSDimitry Andric     return;
41638f0fd8f6SDimitry Andric   for (auto &I : StaticExternCValues) {
41648f0fd8f6SDimitry Andric     IdentifierInfo *Name = I.first;
41658f0fd8f6SDimitry Andric     llvm::GlobalValue *Val = I.second;
4166284c1978SDimitry Andric     if (Val && !getModule().getNamedValue(Name->getName()))
416759d1ed5bSDimitry Andric       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
4168284c1978SDimitry Andric   }
4169284c1978SDimitry Andric }
4170284c1978SDimitry Andric 
417159d1ed5bSDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
417259d1ed5bSDimitry Andric                                              GlobalDecl &Result) const {
417359d1ed5bSDimitry Andric   auto Res = Manglings.find(MangledName);
417459d1ed5bSDimitry Andric   if (Res == Manglings.end())
417559d1ed5bSDimitry Andric     return false;
417659d1ed5bSDimitry Andric   Result = Res->getValue();
417759d1ed5bSDimitry Andric   return true;
417859d1ed5bSDimitry Andric }
417959d1ed5bSDimitry Andric 
4180ffd1746dSEd Schouten /// Emits metadata nodes associating all the global values in the
4181ffd1746dSEd Schouten /// current module with the Decls they came from.  This is useful for
4182ffd1746dSEd Schouten /// projects using IR gen as a subroutine.
4183ffd1746dSEd Schouten ///
4184ffd1746dSEd Schouten /// Since there's currently no way to associate an MDNode directly
4185ffd1746dSEd Schouten /// with an llvm::GlobalValue, we create a global named metadata
4186ffd1746dSEd Schouten /// with the name 'clang.global.decl.ptrs'.
4187ffd1746dSEd Schouten void CodeGenModule::EmitDeclMetadata() {
418859d1ed5bSDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
4189ffd1746dSEd Schouten 
419059d1ed5bSDimitry Andric   for (auto &I : MangledDeclNames) {
419159d1ed5bSDimitry Andric     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
41920623d748SDimitry Andric     // Some mangled names don't necessarily have an associated GlobalValue
41930623d748SDimitry Andric     // in this module, e.g. if we mangled it for DebugInfo.
41940623d748SDimitry Andric     if (Addr)
419559d1ed5bSDimitry Andric       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
4196ffd1746dSEd Schouten   }
4197ffd1746dSEd Schouten }
4198ffd1746dSEd Schouten 
4199ffd1746dSEd Schouten /// Emits metadata nodes for all the local variables in the current
4200ffd1746dSEd Schouten /// function.
4201ffd1746dSEd Schouten void CodeGenFunction::EmitDeclMetadata() {
4202ffd1746dSEd Schouten   if (LocalDeclMap.empty()) return;
4203ffd1746dSEd Schouten 
4204ffd1746dSEd Schouten   llvm::LLVMContext &Context = getLLVMContext();
4205ffd1746dSEd Schouten 
4206ffd1746dSEd Schouten   // Find the unique metadata ID for this name.
4207ffd1746dSEd Schouten   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
4208ffd1746dSEd Schouten 
420959d1ed5bSDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
4210ffd1746dSEd Schouten 
421159d1ed5bSDimitry Andric   for (auto &I : LocalDeclMap) {
421259d1ed5bSDimitry Andric     const Decl *D = I.first;
42130623d748SDimitry Andric     llvm::Value *Addr = I.second.getPointer();
421459d1ed5bSDimitry Andric     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
4215ffd1746dSEd Schouten       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
421639d628a0SDimitry Andric       Alloca->setMetadata(
421739d628a0SDimitry Andric           DeclPtrKind, llvm::MDNode::get(
421839d628a0SDimitry Andric                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
421959d1ed5bSDimitry Andric     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
4220ffd1746dSEd Schouten       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
4221ffd1746dSEd Schouten       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
4222ffd1746dSEd Schouten     }
4223ffd1746dSEd Schouten   }
4224ffd1746dSEd Schouten }
4225e580952dSDimitry Andric 
4226f785676fSDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() {
4227f785676fSDimitry Andric   llvm::NamedMDNode *IdentMetadata =
4228f785676fSDimitry Andric     TheModule.getOrInsertNamedMetadata("llvm.ident");
4229f785676fSDimitry Andric   std::string Version = getClangFullVersion();
4230f785676fSDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
4231f785676fSDimitry Andric 
423239d628a0SDimitry Andric   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
4233f785676fSDimitry Andric   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4234f785676fSDimitry Andric }
4235f785676fSDimitry Andric 
423659d1ed5bSDimitry Andric void CodeGenModule::EmitTargetMetadata() {
423739d628a0SDimitry Andric   // Warning, new MangledDeclNames may be appended within this loop.
423839d628a0SDimitry Andric   // We rely on MapVector insertions adding new elements to the end
423939d628a0SDimitry Andric   // of the container.
424039d628a0SDimitry Andric   // FIXME: Move this loop into the one target that needs it, and only
424139d628a0SDimitry Andric   // loop over those declarations for which we couldn't emit the target
424239d628a0SDimitry Andric   // metadata when we emitted the declaration.
424339d628a0SDimitry Andric   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
424439d628a0SDimitry Andric     auto Val = *(MangledDeclNames.begin() + I);
424539d628a0SDimitry Andric     const Decl *D = Val.first.getDecl()->getMostRecentDecl();
424639d628a0SDimitry Andric     llvm::GlobalValue *GV = GetGlobalValue(Val.second);
424759d1ed5bSDimitry Andric     getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
424859d1ed5bSDimitry Andric   }
424959d1ed5bSDimitry Andric }
425059d1ed5bSDimitry Andric 
4251bd5abe19SDimitry Andric void CodeGenModule::EmitCoverageFile() {
425244290647SDimitry Andric   if (getCodeGenOpts().CoverageDataFile.empty() &&
425344290647SDimitry Andric       getCodeGenOpts().CoverageNotesFile.empty())
425444290647SDimitry Andric     return;
425544290647SDimitry Andric 
425644290647SDimitry Andric   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
425744290647SDimitry Andric   if (!CUNode)
425844290647SDimitry Andric     return;
425944290647SDimitry Andric 
4260bd5abe19SDimitry Andric   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
4261bd5abe19SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
426244290647SDimitry Andric   auto *CoverageDataFile =
426344290647SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
426444290647SDimitry Andric   auto *CoverageNotesFile =
426544290647SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
4266bd5abe19SDimitry Andric   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
4267bd5abe19SDimitry Andric     llvm::MDNode *CU = CUNode->getOperand(i);
426844290647SDimitry Andric     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
426939d628a0SDimitry Andric     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
4270bd5abe19SDimitry Andric   }
4271bd5abe19SDimitry Andric }
42723861d79fSDimitry Andric 
427339d628a0SDimitry Andric llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
42743861d79fSDimitry Andric   // Sema has checked that all uuid strings are of the form
42753861d79fSDimitry Andric   // "12345678-1234-1234-1234-1234567890ab".
42763861d79fSDimitry Andric   assert(Uuid.size() == 36);
4277f785676fSDimitry Andric   for (unsigned i = 0; i < 36; ++i) {
4278f785676fSDimitry Andric     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
4279f785676fSDimitry Andric     else                                         assert(isHexDigit(Uuid[i]));
42803861d79fSDimitry Andric   }
42813861d79fSDimitry Andric 
428239d628a0SDimitry Andric   // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
4283f785676fSDimitry Andric   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
42843861d79fSDimitry Andric 
4285f785676fSDimitry Andric   llvm::Constant *Field3[8];
4286f785676fSDimitry Andric   for (unsigned Idx = 0; Idx < 8; ++Idx)
4287f785676fSDimitry Andric     Field3[Idx] = llvm::ConstantInt::get(
4288f785676fSDimitry Andric         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
42893861d79fSDimitry Andric 
4290f785676fSDimitry Andric   llvm::Constant *Fields[4] = {
4291f785676fSDimitry Andric     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
4292f785676fSDimitry Andric     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
4293f785676fSDimitry Andric     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
4294f785676fSDimitry Andric     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
4295f785676fSDimitry Andric   };
4296f785676fSDimitry Andric 
4297f785676fSDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
42983861d79fSDimitry Andric }
429959d1ed5bSDimitry Andric 
430059d1ed5bSDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
430159d1ed5bSDimitry Andric                                                        bool ForEH) {
430259d1ed5bSDimitry Andric   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
430359d1ed5bSDimitry Andric   // FIXME: should we even be calling this method if RTTI is disabled
430459d1ed5bSDimitry Andric   // and it's not for EH?
430559d1ed5bSDimitry Andric   if (!ForEH && !getLangOpts().RTTI)
430659d1ed5bSDimitry Andric     return llvm::Constant::getNullValue(Int8PtrTy);
430759d1ed5bSDimitry Andric 
430859d1ed5bSDimitry Andric   if (ForEH && Ty->isObjCObjectPointerType() &&
430959d1ed5bSDimitry Andric       LangOpts.ObjCRuntime.isGNUFamily())
431059d1ed5bSDimitry Andric     return ObjCRuntime->GetEHType(Ty);
431159d1ed5bSDimitry Andric 
431259d1ed5bSDimitry Andric   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
431359d1ed5bSDimitry Andric }
431459d1ed5bSDimitry Andric 
431539d628a0SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
431639d628a0SDimitry Andric   for (auto RefExpr : D->varlists()) {
431739d628a0SDimitry Andric     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
431839d628a0SDimitry Andric     bool PerformInit =
431939d628a0SDimitry Andric         VD->getAnyInitializer() &&
432039d628a0SDimitry Andric         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
432139d628a0SDimitry Andric                                                         /*ForRef=*/false);
43220623d748SDimitry Andric 
43230623d748SDimitry Andric     Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
432433956c43SDimitry Andric     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
43250623d748SDimitry Andric             VD, Addr, RefExpr->getLocStart(), PerformInit))
432639d628a0SDimitry Andric       CXXGlobalInits.push_back(InitFunction);
432739d628a0SDimitry Andric   }
432839d628a0SDimitry Andric }
43298f0fd8f6SDimitry Andric 
43300623d748SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
43310623d748SDimitry Andric   llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
43320623d748SDimitry Andric   if (InternalId)
43330623d748SDimitry Andric     return InternalId;
43340623d748SDimitry Andric 
43350623d748SDimitry Andric   if (isExternallyVisible(T->getLinkage())) {
43368f0fd8f6SDimitry Andric     std::string OutName;
43378f0fd8f6SDimitry Andric     llvm::raw_string_ostream Out(OutName);
43380623d748SDimitry Andric     getCXXABI().getMangleContext().mangleTypeName(T, Out);
43398f0fd8f6SDimitry Andric 
43400623d748SDimitry Andric     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
43410623d748SDimitry Andric   } else {
43420623d748SDimitry Andric     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
43430623d748SDimitry Andric                                            llvm::ArrayRef<llvm::Metadata *>());
43440623d748SDimitry Andric   }
43450623d748SDimitry Andric 
43460623d748SDimitry Andric   return InternalId;
43470623d748SDimitry Andric }
43480623d748SDimitry Andric 
4349e7145dcbSDimitry Andric /// Returns whether this module needs the "all-vtables" type identifier.
4350e7145dcbSDimitry Andric bool CodeGenModule::NeedAllVtablesTypeId() const {
4351e7145dcbSDimitry Andric   // Returns true if at least one of vtable-based CFI checkers is enabled and
4352e7145dcbSDimitry Andric   // is not in the trapping mode.
4353e7145dcbSDimitry Andric   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
4354e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
4355e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
4356e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
4357e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
4358e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
4359e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
4360e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
4361e7145dcbSDimitry Andric }
4362e7145dcbSDimitry Andric 
4363e7145dcbSDimitry Andric void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
43640623d748SDimitry Andric                                           CharUnits Offset,
43650623d748SDimitry Andric                                           const CXXRecordDecl *RD) {
43660623d748SDimitry Andric   llvm::Metadata *MD =
43670623d748SDimitry Andric       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
4368e7145dcbSDimitry Andric   VTable->addTypeMetadata(Offset.getQuantity(), MD);
43690623d748SDimitry Andric 
4370e7145dcbSDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
4371e7145dcbSDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
4372e7145dcbSDimitry Andric       VTable->addTypeMetadata(Offset.getQuantity(),
4373e7145dcbSDimitry Andric                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
4374e7145dcbSDimitry Andric 
4375e7145dcbSDimitry Andric   if (NeedAllVtablesTypeId()) {
4376e7145dcbSDimitry Andric     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
4377e7145dcbSDimitry Andric     VTable->addTypeMetadata(Offset.getQuantity(), MD);
43780623d748SDimitry Andric   }
43790623d748SDimitry Andric }
43800623d748SDimitry Andric 
43810623d748SDimitry Andric // Fills in the supplied string map with the set of target features for the
43820623d748SDimitry Andric // passed in function.
43830623d748SDimitry Andric void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
43840623d748SDimitry Andric                                           const FunctionDecl *FD) {
43850623d748SDimitry Andric   StringRef TargetCPU = Target.getTargetOpts().CPU;
43860623d748SDimitry Andric   if (const auto *TD = FD->getAttr<TargetAttr>()) {
43870623d748SDimitry Andric     // If we have a TargetAttr build up the feature map based on that.
43880623d748SDimitry Andric     TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
43890623d748SDimitry Andric 
43900623d748SDimitry Andric     // Make a copy of the features as passed on the command line into the
43910623d748SDimitry Andric     // beginning of the additional features from the function to override.
43920623d748SDimitry Andric     ParsedAttr.first.insert(ParsedAttr.first.begin(),
43930623d748SDimitry Andric                             Target.getTargetOpts().FeaturesAsWritten.begin(),
43940623d748SDimitry Andric                             Target.getTargetOpts().FeaturesAsWritten.end());
43950623d748SDimitry Andric 
43960623d748SDimitry Andric     if (ParsedAttr.second != "")
43970623d748SDimitry Andric       TargetCPU = ParsedAttr.second;
43980623d748SDimitry Andric 
43990623d748SDimitry Andric     // Now populate the feature map, first with the TargetCPU which is either
44000623d748SDimitry Andric     // the default or a new one from the target attribute string. Then we'll use
44010623d748SDimitry Andric     // the passed in features (FeaturesAsWritten) along with the new ones from
44020623d748SDimitry Andric     // the attribute.
44030623d748SDimitry Andric     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first);
44040623d748SDimitry Andric   } else {
44050623d748SDimitry Andric     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
44060623d748SDimitry Andric                           Target.getTargetOpts().Features);
44070623d748SDimitry Andric   }
44088f0fd8f6SDimitry Andric }
4409e7145dcbSDimitry Andric 
4410e7145dcbSDimitry Andric llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
4411e7145dcbSDimitry Andric   if (!SanStats)
4412e7145dcbSDimitry Andric     SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
4413e7145dcbSDimitry Andric 
4414e7145dcbSDimitry Andric   return *SanStats;
4415e7145dcbSDimitry Andric }
441644290647SDimitry Andric llvm::Value *
441744290647SDimitry Andric CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
441844290647SDimitry Andric                                                   CodeGenFunction &CGF) {
441944290647SDimitry Andric   llvm::Constant *C = EmitConstantExpr(E, E->getType(), &CGF);
442044290647SDimitry Andric   auto SamplerT = getOpenCLRuntime().getSamplerType();
442144290647SDimitry Andric   auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
442244290647SDimitry Andric   return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
442344290647SDimitry Andric                                 "__translate_sampler_initializer"),
442444290647SDimitry Andric                                 {C});
442544290647SDimitry Andric }
4426