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"
4859d1ed5bSDimitry Andric #include "llvm/IR/CallSite.h"
49139f7f9bSDimitry Andric #include "llvm/IR/CallingConv.h"
50139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h"
51139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h"
52139f7f9bSDimitry Andric #include "llvm/IR/LLVMContext.h"
53139f7f9bSDimitry Andric #include "llvm/IR/Module.h"
5459d1ed5bSDimitry Andric #include "llvm/ProfileData/InstrProfReader.h"
55139f7f9bSDimitry Andric #include "llvm/Support/ConvertUTF.h"
56f22ef01cSRoman Divacky #include "llvm/Support/ErrorHandling.h"
570623d748SDimitry Andric #include "llvm/Support/MD5.h"
58139f7f9bSDimitry Andric 
59f22ef01cSRoman Divacky using namespace clang;
60f22ef01cSRoman Divacky using namespace CodeGen;
61f22ef01cSRoman Divacky 
626122f3e6SDimitry Andric static const char AnnotationSection[] = "llvm.metadata";
636122f3e6SDimitry Andric 
6459d1ed5bSDimitry Andric static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
65284c1978SDimitry Andric   switch (CGM.getTarget().getCXXABI().getKind()) {
66139f7f9bSDimitry Andric   case TargetCXXABI::GenericAArch64:
67139f7f9bSDimitry Andric   case TargetCXXABI::GenericARM:
68139f7f9bSDimitry Andric   case TargetCXXABI::iOS:
6959d1ed5bSDimitry Andric   case TargetCXXABI::iOS64:
700623d748SDimitry Andric   case TargetCXXABI::WatchOS:
71ef6fa9e2SDimitry Andric   case TargetCXXABI::GenericMIPS:
72139f7f9bSDimitry Andric   case TargetCXXABI::GenericItanium:
730623d748SDimitry Andric   case TargetCXXABI::WebAssembly:
7459d1ed5bSDimitry Andric     return CreateItaniumCXXABI(CGM);
75139f7f9bSDimitry Andric   case TargetCXXABI::Microsoft:
7659d1ed5bSDimitry Andric     return CreateMicrosoftCXXABI(CGM);
77e580952dSDimitry Andric   }
78e580952dSDimitry Andric 
79e580952dSDimitry Andric   llvm_unreachable("invalid C++ ABI kind");
80e580952dSDimitry Andric }
81e580952dSDimitry Andric 
823dac3a9bSDimitry Andric CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
833dac3a9bSDimitry Andric                              const PreprocessorOptions &PPO,
843dac3a9bSDimitry Andric                              const CodeGenOptions &CGO, llvm::Module &M,
8539d628a0SDimitry Andric                              DiagnosticsEngine &diags,
8639d628a0SDimitry Andric                              CoverageSourceInfo *CoverageInfo)
873dac3a9bSDimitry Andric     : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
883dac3a9bSDimitry Andric       PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
890623d748SDimitry Andric       Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
90e7145dcbSDimitry Andric       VMContext(M.getContext()), Types(*this), VTables(*this),
91e7145dcbSDimitry Andric       SanitizerMD(new SanitizerMetadata(*this)) {
92dff0c46cSDimitry Andric 
93dff0c46cSDimitry Andric   // Initialize the type cache.
94dff0c46cSDimitry Andric   llvm::LLVMContext &LLVMContext = M.getContext();
95dff0c46cSDimitry Andric   VoidTy = llvm::Type::getVoidTy(LLVMContext);
96dff0c46cSDimitry Andric   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
97dff0c46cSDimitry Andric   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
98dff0c46cSDimitry Andric   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
99dff0c46cSDimitry Andric   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
100dff0c46cSDimitry Andric   FloatTy = llvm::Type::getFloatTy(LLVMContext);
101dff0c46cSDimitry Andric   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
102dff0c46cSDimitry Andric   PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
103dff0c46cSDimitry Andric   PointerAlignInBytes =
104dff0c46cSDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
10544290647SDimitry Andric   SizeSizeInBytes =
10644290647SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
1070623d748SDimitry Andric   IntAlignInBytes =
1080623d748SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
109dff0c46cSDimitry Andric   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
11044290647SDimitry Andric   IntPtrTy = llvm::IntegerType::get(LLVMContext,
11144290647SDimitry Andric     C.getTargetInfo().getMaxPointerWidth());
112dff0c46cSDimitry Andric   Int8PtrTy = Int8Ty->getPointerTo(0);
113dff0c46cSDimitry Andric   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
1146bc11b14SDimitry Andric   AllocaInt8PtrTy = Int8Ty->getPointerTo(
1156bc11b14SDimitry Andric       M.getDataLayout().getAllocaAddrSpace());
116dff0c46cSDimitry Andric 
117139f7f9bSDimitry Andric   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
11839d628a0SDimitry Andric   BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
119139f7f9bSDimitry Andric 
120dff0c46cSDimitry Andric   if (LangOpts.ObjC1)
1213b0f4066SDimitry Andric     createObjCRuntime();
122dff0c46cSDimitry Andric   if (LangOpts.OpenCL)
1236122f3e6SDimitry Andric     createOpenCLRuntime();
12459d1ed5bSDimitry Andric   if (LangOpts.OpenMP)
12559d1ed5bSDimitry Andric     createOpenMPRuntime();
126dff0c46cSDimitry Andric   if (LangOpts.CUDA)
1276122f3e6SDimitry Andric     createCUDARuntime();
128f22ef01cSRoman Divacky 
1297ae0e2c9SDimitry Andric   // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
13039d628a0SDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
1317ae0e2c9SDimitry Andric       (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
132e7145dcbSDimitry Andric     TBAA.reset(new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
133e7145dcbSDimitry Andric                                getCXXABI().getMangleContext()));
1342754fe60SDimitry Andric 
1353b0f4066SDimitry Andric   // If debug info or coverage generation is enabled, create the CGDebugInfo
1363b0f4066SDimitry Andric   // object.
137e7145dcbSDimitry Andric   if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
138e7145dcbSDimitry Andric       CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
139e7145dcbSDimitry Andric     DebugInfo.reset(new CGDebugInfo(*this));
1402754fe60SDimitry Andric 
1412754fe60SDimitry Andric   Block.GlobalUniqueCount = 0;
1422754fe60SDimitry Andric 
1430623d748SDimitry Andric   if (C.getLangOpts().ObjC1)
144e7145dcbSDimitry Andric     ObjCData.reset(new ObjCEntrypoints());
14559d1ed5bSDimitry Andric 
146e7145dcbSDimitry Andric   if (CodeGenOpts.hasProfileClangUse()) {
147e7145dcbSDimitry Andric     auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
148e7145dcbSDimitry Andric         CodeGenOpts.ProfileInstrumentUsePath);
149e7145dcbSDimitry Andric     if (auto E = ReaderOrErr.takeError()) {
15059d1ed5bSDimitry Andric       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1513dac3a9bSDimitry Andric                                               "Could not read profile %0: %1");
152e7145dcbSDimitry Andric       llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
153e7145dcbSDimitry Andric         getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
154e7145dcbSDimitry Andric                                   << EI.message();
155e7145dcbSDimitry Andric       });
15633956c43SDimitry Andric     } else
15733956c43SDimitry Andric       PGOReader = std::move(ReaderOrErr.get());
15859d1ed5bSDimitry Andric   }
15939d628a0SDimitry Andric 
16039d628a0SDimitry Andric   // If coverage mapping generation is enabled, create the
16139d628a0SDimitry Andric   // CoverageMappingModuleGen object.
16239d628a0SDimitry Andric   if (CodeGenOpts.CoverageMapping)
16339d628a0SDimitry Andric     CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
164f22ef01cSRoman Divacky }
165f22ef01cSRoman Divacky 
166e7145dcbSDimitry Andric CodeGenModule::~CodeGenModule() {}
167f22ef01cSRoman Divacky 
168f22ef01cSRoman Divacky void CodeGenModule::createObjCRuntime() {
1697ae0e2c9SDimitry Andric   // This is just isGNUFamily(), but we want to force implementors of
1707ae0e2c9SDimitry Andric   // new ABIs to decide how best to do this.
1717ae0e2c9SDimitry Andric   switch (LangOpts.ObjCRuntime.getKind()) {
1727ae0e2c9SDimitry Andric   case ObjCRuntime::GNUstep:
1737ae0e2c9SDimitry Andric   case ObjCRuntime::GCC:
1747ae0e2c9SDimitry Andric   case ObjCRuntime::ObjFW:
175e7145dcbSDimitry Andric     ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
1767ae0e2c9SDimitry Andric     return;
1777ae0e2c9SDimitry Andric 
1787ae0e2c9SDimitry Andric   case ObjCRuntime::FragileMacOSX:
1797ae0e2c9SDimitry Andric   case ObjCRuntime::MacOSX:
1807ae0e2c9SDimitry Andric   case ObjCRuntime::iOS:
1810623d748SDimitry Andric   case ObjCRuntime::WatchOS:
182e7145dcbSDimitry Andric     ObjCRuntime.reset(CreateMacObjCRuntime(*this));
1837ae0e2c9SDimitry Andric     return;
1847ae0e2c9SDimitry Andric   }
1857ae0e2c9SDimitry Andric   llvm_unreachable("bad runtime kind");
1866122f3e6SDimitry Andric }
1876122f3e6SDimitry Andric 
1886122f3e6SDimitry Andric void CodeGenModule::createOpenCLRuntime() {
189e7145dcbSDimitry Andric   OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
1906122f3e6SDimitry Andric }
1916122f3e6SDimitry Andric 
19259d1ed5bSDimitry Andric void CodeGenModule::createOpenMPRuntime() {
193e7145dcbSDimitry Andric   // Select a specialized code generation class based on the target, if any.
194e7145dcbSDimitry Andric   // If it does not exist use the default implementation.
19544290647SDimitry Andric   switch (getTriple().getArch()) {
196e7145dcbSDimitry Andric   case llvm::Triple::nvptx:
197e7145dcbSDimitry Andric   case llvm::Triple::nvptx64:
198e7145dcbSDimitry Andric     assert(getLangOpts().OpenMPIsDevice &&
199e7145dcbSDimitry Andric            "OpenMP NVPTX is only prepared to deal with device code.");
200e7145dcbSDimitry Andric     OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
201e7145dcbSDimitry Andric     break;
202e7145dcbSDimitry Andric   default:
203e7145dcbSDimitry Andric     OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
204e7145dcbSDimitry Andric     break;
205e7145dcbSDimitry Andric   }
20659d1ed5bSDimitry Andric }
20759d1ed5bSDimitry Andric 
2086122f3e6SDimitry Andric void CodeGenModule::createCUDARuntime() {
209e7145dcbSDimitry Andric   CUDARuntime.reset(CreateNVCUDARuntime(*this));
210f22ef01cSRoman Divacky }
211f22ef01cSRoman Divacky 
21239d628a0SDimitry Andric void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
21339d628a0SDimitry Andric   Replacements[Name] = C;
21439d628a0SDimitry Andric }
21539d628a0SDimitry Andric 
216f785676fSDimitry Andric void CodeGenModule::applyReplacements() {
2178f0fd8f6SDimitry Andric   for (auto &I : Replacements) {
2188f0fd8f6SDimitry Andric     StringRef MangledName = I.first();
2198f0fd8f6SDimitry Andric     llvm::Constant *Replacement = I.second;
220f785676fSDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
221f785676fSDimitry Andric     if (!Entry)
222f785676fSDimitry Andric       continue;
22359d1ed5bSDimitry Andric     auto *OldF = cast<llvm::Function>(Entry);
22459d1ed5bSDimitry Andric     auto *NewF = dyn_cast<llvm::Function>(Replacement);
225f785676fSDimitry Andric     if (!NewF) {
22659d1ed5bSDimitry Andric       if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
22759d1ed5bSDimitry Andric         NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
22859d1ed5bSDimitry Andric       } else {
22959d1ed5bSDimitry Andric         auto *CE = cast<llvm::ConstantExpr>(Replacement);
230f785676fSDimitry Andric         assert(CE->getOpcode() == llvm::Instruction::BitCast ||
231f785676fSDimitry Andric                CE->getOpcode() == llvm::Instruction::GetElementPtr);
232f785676fSDimitry Andric         NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
233f785676fSDimitry Andric       }
23459d1ed5bSDimitry Andric     }
235f785676fSDimitry Andric 
236f785676fSDimitry Andric     // Replace old with new, but keep the old order.
237f785676fSDimitry Andric     OldF->replaceAllUsesWith(Replacement);
238f785676fSDimitry Andric     if (NewF) {
239f785676fSDimitry Andric       NewF->removeFromParent();
2400623d748SDimitry Andric       OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
2410623d748SDimitry Andric                                                        NewF);
242f785676fSDimitry Andric     }
243f785676fSDimitry Andric     OldF->eraseFromParent();
244f785676fSDimitry Andric   }
245f785676fSDimitry Andric }
246f785676fSDimitry Andric 
2470623d748SDimitry Andric void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
2480623d748SDimitry Andric   GlobalValReplacements.push_back(std::make_pair(GV, C));
2490623d748SDimitry Andric }
2500623d748SDimitry Andric 
2510623d748SDimitry Andric void CodeGenModule::applyGlobalValReplacements() {
2520623d748SDimitry Andric   for (auto &I : GlobalValReplacements) {
2530623d748SDimitry Andric     llvm::GlobalValue *GV = I.first;
2540623d748SDimitry Andric     llvm::Constant *C = I.second;
2550623d748SDimitry Andric 
2560623d748SDimitry Andric     GV->replaceAllUsesWith(C);
2570623d748SDimitry Andric     GV->eraseFromParent();
2580623d748SDimitry Andric   }
2590623d748SDimitry Andric }
2600623d748SDimitry Andric 
26159d1ed5bSDimitry Andric // This is only used in aliases that we created and we know they have a
26259d1ed5bSDimitry Andric // linear structure.
263e7145dcbSDimitry Andric static const llvm::GlobalObject *getAliasedGlobal(
264e7145dcbSDimitry Andric     const llvm::GlobalIndirectSymbol &GIS) {
265e7145dcbSDimitry Andric   llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
266e7145dcbSDimitry Andric   const llvm::Constant *C = &GIS;
26759d1ed5bSDimitry Andric   for (;;) {
26859d1ed5bSDimitry Andric     C = C->stripPointerCasts();
26959d1ed5bSDimitry Andric     if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
27059d1ed5bSDimitry Andric       return GO;
27159d1ed5bSDimitry Andric     // stripPointerCasts will not walk over weak aliases.
272e7145dcbSDimitry Andric     auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
273e7145dcbSDimitry Andric     if (!GIS2)
27459d1ed5bSDimitry Andric       return nullptr;
275e7145dcbSDimitry Andric     if (!Visited.insert(GIS2).second)
27659d1ed5bSDimitry Andric       return nullptr;
277e7145dcbSDimitry Andric     C = GIS2->getIndirectSymbol();
27859d1ed5bSDimitry Andric   }
27959d1ed5bSDimitry Andric }
28059d1ed5bSDimitry Andric 
281f785676fSDimitry Andric void CodeGenModule::checkAliases() {
28259d1ed5bSDimitry Andric   // Check if the constructed aliases are well formed. It is really unfortunate
28359d1ed5bSDimitry Andric   // that we have to do this in CodeGen, but we only construct mangled names
28459d1ed5bSDimitry Andric   // and aliases during codegen.
285f785676fSDimitry Andric   bool Error = false;
28659d1ed5bSDimitry Andric   DiagnosticsEngine &Diags = getDiags();
2878f0fd8f6SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
28859d1ed5bSDimitry Andric     const auto *D = cast<ValueDecl>(GD.getDecl());
289e7145dcbSDimitry Andric     SourceLocation Location;
290e7145dcbSDimitry Andric     bool IsIFunc = D->hasAttr<IFuncAttr>();
291e7145dcbSDimitry Andric     if (const Attr *A = D->getDefiningAttr())
292e7145dcbSDimitry Andric       Location = A->getLocation();
293e7145dcbSDimitry Andric     else
294e7145dcbSDimitry Andric       llvm_unreachable("Not an alias or ifunc?");
295f785676fSDimitry Andric     StringRef MangledName = getMangledName(GD);
296f785676fSDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
297e7145dcbSDimitry Andric     auto *Alias  = cast<llvm::GlobalIndirectSymbol>(Entry);
29859d1ed5bSDimitry Andric     const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
29959d1ed5bSDimitry Andric     if (!GV) {
300f785676fSDimitry Andric       Error = true;
301e7145dcbSDimitry Andric       Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
30259d1ed5bSDimitry Andric     } else if (GV->isDeclaration()) {
303f785676fSDimitry Andric       Error = true;
304e7145dcbSDimitry Andric       Diags.Report(Location, diag::err_alias_to_undefined)
305e7145dcbSDimitry Andric           << IsIFunc << IsIFunc;
306e7145dcbSDimitry Andric     } else if (IsIFunc) {
307e7145dcbSDimitry Andric       // Check resolver function type.
308e7145dcbSDimitry Andric       llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
309e7145dcbSDimitry Andric           GV->getType()->getPointerElementType());
310e7145dcbSDimitry Andric       assert(FTy);
311e7145dcbSDimitry Andric       if (!FTy->getReturnType()->isPointerTy())
312e7145dcbSDimitry Andric         Diags.Report(Location, diag::err_ifunc_resolver_return);
313e7145dcbSDimitry Andric       if (FTy->getNumParams())
314e7145dcbSDimitry Andric         Diags.Report(Location, diag::err_ifunc_resolver_params);
31559d1ed5bSDimitry Andric     }
31659d1ed5bSDimitry Andric 
317e7145dcbSDimitry Andric     llvm::Constant *Aliasee = Alias->getIndirectSymbol();
31859d1ed5bSDimitry Andric     llvm::GlobalValue *AliaseeGV;
31959d1ed5bSDimitry Andric     if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
32059d1ed5bSDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
32159d1ed5bSDimitry Andric     else
32259d1ed5bSDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
32359d1ed5bSDimitry Andric 
32459d1ed5bSDimitry Andric     if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
32559d1ed5bSDimitry Andric       StringRef AliasSection = SA->getName();
32659d1ed5bSDimitry Andric       if (AliasSection != AliaseeGV->getSection())
32759d1ed5bSDimitry Andric         Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
328e7145dcbSDimitry Andric             << AliasSection << IsIFunc << IsIFunc;
32959d1ed5bSDimitry Andric     }
33059d1ed5bSDimitry Andric 
33159d1ed5bSDimitry Andric     // We have to handle alias to weak aliases in here. LLVM itself disallows
33259d1ed5bSDimitry Andric     // this since the object semantics would not match the IL one. For
33359d1ed5bSDimitry Andric     // compatibility with gcc we implement it by just pointing the alias
33459d1ed5bSDimitry Andric     // to its aliasee's aliasee. We also warn, since the user is probably
33559d1ed5bSDimitry Andric     // expecting the link to be weak.
336e7145dcbSDimitry Andric     if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
337e7145dcbSDimitry Andric       if (GA->isInterposable()) {
338e7145dcbSDimitry Andric         Diags.Report(Location, diag::warn_alias_to_weak_alias)
339e7145dcbSDimitry Andric             << GV->getName() << GA->getName() << IsIFunc;
34059d1ed5bSDimitry Andric         Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
341e7145dcbSDimitry Andric             GA->getIndirectSymbol(), Alias->getType());
342e7145dcbSDimitry Andric         Alias->setIndirectSymbol(Aliasee);
34359d1ed5bSDimitry Andric       }
344f785676fSDimitry Andric     }
345f785676fSDimitry Andric   }
346f785676fSDimitry Andric   if (!Error)
347f785676fSDimitry Andric     return;
348f785676fSDimitry Andric 
3498f0fd8f6SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
350f785676fSDimitry Andric     StringRef MangledName = getMangledName(GD);
351f785676fSDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
352e7145dcbSDimitry Andric     auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
353f785676fSDimitry Andric     Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
354f785676fSDimitry Andric     Alias->eraseFromParent();
355f785676fSDimitry Andric   }
356f785676fSDimitry Andric }
357f785676fSDimitry Andric 
35859d1ed5bSDimitry Andric void CodeGenModule::clear() {
35959d1ed5bSDimitry Andric   DeferredDeclsToEmit.clear();
36033956c43SDimitry Andric   if (OpenMPRuntime)
36133956c43SDimitry Andric     OpenMPRuntime->clear();
36259d1ed5bSDimitry Andric }
36359d1ed5bSDimitry Andric 
36459d1ed5bSDimitry Andric void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
36559d1ed5bSDimitry Andric                                        StringRef MainFile) {
36659d1ed5bSDimitry Andric   if (!hasDiagnostics())
36759d1ed5bSDimitry Andric     return;
36859d1ed5bSDimitry Andric   if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
36959d1ed5bSDimitry Andric     if (MainFile.empty())
37059d1ed5bSDimitry Andric       MainFile = "<stdin>";
37159d1ed5bSDimitry Andric     Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
37259d1ed5bSDimitry Andric   } else
37359d1ed5bSDimitry Andric     Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Missing
37459d1ed5bSDimitry Andric                                                       << Mismatched;
37559d1ed5bSDimitry Andric }
37659d1ed5bSDimitry Andric 
377f22ef01cSRoman Divacky void CodeGenModule::Release() {
378f22ef01cSRoman Divacky   EmitDeferred();
3790623d748SDimitry Andric   applyGlobalValReplacements();
380f785676fSDimitry Andric   applyReplacements();
381f785676fSDimitry Andric   checkAliases();
382f22ef01cSRoman Divacky   EmitCXXGlobalInitFunc();
383f22ef01cSRoman Divacky   EmitCXXGlobalDtorFunc();
384284c1978SDimitry Andric   EmitCXXThreadLocalInitFunc();
3856122f3e6SDimitry Andric   if (ObjCRuntime)
3866122f3e6SDimitry Andric     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
387f22ef01cSRoman Divacky       AddGlobalCtor(ObjCInitFunction);
38833956c43SDimitry Andric   if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
38933956c43SDimitry Andric       CUDARuntime) {
39033956c43SDimitry Andric     if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
39133956c43SDimitry Andric       AddGlobalCtor(CudaCtorFunction);
39233956c43SDimitry Andric     if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
39333956c43SDimitry Andric       AddGlobalDtor(CudaDtorFunction);
39433956c43SDimitry Andric   }
395ea942507SDimitry Andric   if (OpenMPRuntime)
396ea942507SDimitry Andric     if (llvm::Function *OpenMPRegistrationFunction =
397ea942507SDimitry Andric             OpenMPRuntime->emitRegistrationFunction())
398ea942507SDimitry Andric       AddGlobalCtor(OpenMPRegistrationFunction, 0);
3990623d748SDimitry Andric   if (PGOReader) {
400e7145dcbSDimitry Andric     getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
4010623d748SDimitry Andric     if (PGOStats.hasDiagnostics())
40259d1ed5bSDimitry Andric       PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
4030623d748SDimitry Andric   }
404f22ef01cSRoman Divacky   EmitCtorList(GlobalCtors, "llvm.global_ctors");
405f22ef01cSRoman Divacky   EmitCtorList(GlobalDtors, "llvm.global_dtors");
4066122f3e6SDimitry Andric   EmitGlobalAnnotations();
407284c1978SDimitry Andric   EmitStaticExternCAliases();
40839d628a0SDimitry Andric   EmitDeferredUnusedCoverageMappings();
40939d628a0SDimitry Andric   if (CoverageMapping)
41039d628a0SDimitry Andric     CoverageMapping->emit();
41120e90f04SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
412e7145dcbSDimitry Andric     CodeGenFunction(*this).EmitCfiCheckFail();
41320e90f04SDimitry Andric     CodeGenFunction(*this).EmitCfiCheckStub();
41420e90f04SDimitry Andric   }
41520e90f04SDimitry Andric   emitAtAvailableLinkGuard();
41659d1ed5bSDimitry Andric   emitLLVMUsed();
417e7145dcbSDimitry Andric   if (SanStats)
418e7145dcbSDimitry Andric     SanStats->finish();
419ffd1746dSEd Schouten 
420f785676fSDimitry Andric   if (CodeGenOpts.Autolink &&
421f785676fSDimitry Andric       (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
422139f7f9bSDimitry Andric     EmitModuleLinkOptions();
423139f7f9bSDimitry Andric   }
42420e90f04SDimitry Andric 
42520e90f04SDimitry Andric   // Record mregparm value now so it is visible through rest of codegen.
42620e90f04SDimitry Andric   if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
42720e90f04SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
42820e90f04SDimitry Andric                               CodeGenOpts.NumRegisterParameters);
42920e90f04SDimitry Andric 
4300623d748SDimitry Andric   if (CodeGenOpts.DwarfVersion) {
431f785676fSDimitry Andric     // We actually want the latest version when there are conflicts.
432f785676fSDimitry Andric     // We can change from Warning to Latest if such mode is supported.
433f785676fSDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
434f785676fSDimitry Andric                               CodeGenOpts.DwarfVersion);
4350623d748SDimitry Andric   }
4360623d748SDimitry Andric   if (CodeGenOpts.EmitCodeView) {
4370623d748SDimitry Andric     // Indicate that we want CodeView in the metadata.
4380623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
4390623d748SDimitry Andric   }
4400623d748SDimitry Andric   if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
4410623d748SDimitry Andric     // We don't support LTO with 2 with different StrictVTablePointers
4420623d748SDimitry Andric     // FIXME: we could support it by stripping all the information introduced
4430623d748SDimitry Andric     // by StrictVTablePointers.
4440623d748SDimitry Andric 
4450623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
4460623d748SDimitry Andric 
4470623d748SDimitry Andric     llvm::Metadata *Ops[2] = {
4480623d748SDimitry Andric               llvm::MDString::get(VMContext, "StrictVTablePointers"),
4490623d748SDimitry Andric               llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
4500623d748SDimitry Andric                   llvm::Type::getInt32Ty(VMContext), 1))};
4510623d748SDimitry Andric 
4520623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Require,
4530623d748SDimitry Andric                               "StrictVTablePointersRequirement",
4540623d748SDimitry Andric                               llvm::MDNode::get(VMContext, Ops));
4550623d748SDimitry Andric   }
456f785676fSDimitry Andric   if (DebugInfo)
45759d1ed5bSDimitry Andric     // We support a single version in the linked module. The LLVM
45859d1ed5bSDimitry Andric     // parser will drop debug info with a different version number
45959d1ed5bSDimitry Andric     // (and warn about it, too).
46059d1ed5bSDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
461f785676fSDimitry Andric                               llvm::DEBUG_METADATA_VERSION);
462139f7f9bSDimitry Andric 
46359d1ed5bSDimitry Andric   // We need to record the widths of enums and wchar_t, so that we can generate
46459d1ed5bSDimitry Andric   // the correct build attributes in the ARM backend.
46559d1ed5bSDimitry Andric   llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
46659d1ed5bSDimitry Andric   if (   Arch == llvm::Triple::arm
46759d1ed5bSDimitry Andric       || Arch == llvm::Triple::armeb
46859d1ed5bSDimitry Andric       || Arch == llvm::Triple::thumb
46959d1ed5bSDimitry Andric       || Arch == llvm::Triple::thumbeb) {
47059d1ed5bSDimitry Andric     // Width of wchar_t in bytes
47159d1ed5bSDimitry Andric     uint64_t WCharWidth =
47259d1ed5bSDimitry Andric         Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
47359d1ed5bSDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
47459d1ed5bSDimitry Andric 
47559d1ed5bSDimitry Andric     // The minimum width of an enum in bytes
47659d1ed5bSDimitry Andric     uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
47759d1ed5bSDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
47859d1ed5bSDimitry Andric   }
47959d1ed5bSDimitry Andric 
4800623d748SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
4810623d748SDimitry Andric     // Indicate that we want cross-DSO control flow integrity checks.
4820623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
4830623d748SDimitry Andric   }
4840623d748SDimitry Andric 
48544290647SDimitry Andric   if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
486e7145dcbSDimitry Andric     // Indicate whether __nvvm_reflect should be configured to flush denormal
487e7145dcbSDimitry Andric     // floating point values to 0.  (This corresponds to its "__CUDA_FTZ"
488e7145dcbSDimitry Andric     // property.)
489e7145dcbSDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
490e7145dcbSDimitry Andric                               LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
49139d628a0SDimitry Andric   }
49239d628a0SDimitry Andric 
493e7145dcbSDimitry Andric   if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
494e7145dcbSDimitry Andric     assert(PLevel < 3 && "Invalid PIC Level");
495e7145dcbSDimitry Andric     getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
496e7145dcbSDimitry Andric     if (Context.getLangOpts().PIE)
497e7145dcbSDimitry Andric       getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
49839d628a0SDimitry Andric   }
49939d628a0SDimitry Andric 
5002754fe60SDimitry Andric   SimplifyPersonality();
5012754fe60SDimitry Andric 
502ffd1746dSEd Schouten   if (getCodeGenOpts().EmitDeclMetadata)
503ffd1746dSEd Schouten     EmitDeclMetadata();
504bd5abe19SDimitry Andric 
505bd5abe19SDimitry Andric   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
506bd5abe19SDimitry Andric     EmitCoverageFile();
5076122f3e6SDimitry Andric 
5086122f3e6SDimitry Andric   if (DebugInfo)
5096122f3e6SDimitry Andric     DebugInfo->finalize();
510f785676fSDimitry Andric 
511f785676fSDimitry Andric   EmitVersionIdentMetadata();
51259d1ed5bSDimitry Andric 
51359d1ed5bSDimitry Andric   EmitTargetMetadata();
514f22ef01cSRoman Divacky }
515f22ef01cSRoman Divacky 
5163b0f4066SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
5173b0f4066SDimitry Andric   // Make sure that this type is translated.
5183b0f4066SDimitry Andric   Types.UpdateCompletedType(TD);
5193b0f4066SDimitry Andric }
5203b0f4066SDimitry Andric 
521e7145dcbSDimitry Andric void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
522e7145dcbSDimitry Andric   // Make sure that this type is translated.
523e7145dcbSDimitry Andric   Types.RefreshTypeCacheForClass(RD);
524e7145dcbSDimitry Andric }
525e7145dcbSDimitry Andric 
5262754fe60SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
5272754fe60SDimitry Andric   if (!TBAA)
52859d1ed5bSDimitry Andric     return nullptr;
5292754fe60SDimitry Andric   return TBAA->getTBAAInfo(QTy);
5302754fe60SDimitry Andric }
5312754fe60SDimitry Andric 
532dff0c46cSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
533dff0c46cSDimitry Andric   if (!TBAA)
53459d1ed5bSDimitry Andric     return nullptr;
535dff0c46cSDimitry Andric   return TBAA->getTBAAInfoForVTablePtr();
536dff0c46cSDimitry Andric }
537dff0c46cSDimitry Andric 
5383861d79fSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
5393861d79fSDimitry Andric   if (!TBAA)
54059d1ed5bSDimitry Andric     return nullptr;
5413861d79fSDimitry Andric   return TBAA->getTBAAStructInfo(QTy);
5423861d79fSDimitry Andric }
5433861d79fSDimitry Andric 
544139f7f9bSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
545139f7f9bSDimitry Andric                                                   llvm::MDNode *AccessN,
546139f7f9bSDimitry Andric                                                   uint64_t O) {
547139f7f9bSDimitry Andric   if (!TBAA)
54859d1ed5bSDimitry Andric     return nullptr;
549139f7f9bSDimitry Andric   return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
550139f7f9bSDimitry Andric }
551139f7f9bSDimitry Andric 
552f785676fSDimitry Andric /// Decorate the instruction with a TBAA tag. For both scalar TBAA
553f785676fSDimitry Andric /// and struct-path aware TBAA, the tag has the same format:
554f785676fSDimitry Andric /// base type, access type and offset.
555284c1978SDimitry Andric /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
5560623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
557284c1978SDimitry Andric                                                 llvm::MDNode *TBAAInfo,
558284c1978SDimitry Andric                                                 bool ConvertTypeToTag) {
559f785676fSDimitry Andric   if (ConvertTypeToTag && TBAA)
560284c1978SDimitry Andric     Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
561284c1978SDimitry Andric                       TBAA->getTBAAScalarTagInfo(TBAAInfo));
562284c1978SDimitry Andric   else
5632754fe60SDimitry Andric     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
5642754fe60SDimitry Andric }
5652754fe60SDimitry Andric 
5660623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithInvariantGroup(
5670623d748SDimitry Andric     llvm::Instruction *I, const CXXRecordDecl *RD) {
5680623d748SDimitry Andric   llvm::Metadata *MD = CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
5690623d748SDimitry Andric   auto *MetaDataNode = dyn_cast<llvm::MDNode>(MD);
5700623d748SDimitry Andric   // Check if we have to wrap MDString in MDNode.
5710623d748SDimitry Andric   if (!MetaDataNode)
5720623d748SDimitry Andric     MetaDataNode = llvm::MDNode::get(getLLVMContext(), MD);
5730623d748SDimitry Andric   I->setMetadata(llvm::LLVMContext::MD_invariant_group, MetaDataNode);
5740623d748SDimitry Andric }
5750623d748SDimitry Andric 
57659d1ed5bSDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) {
57759d1ed5bSDimitry Andric   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
57859d1ed5bSDimitry Andric   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
579f22ef01cSRoman Divacky }
580f22ef01cSRoman Divacky 
581f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
582f22ef01cSRoman Divacky /// specified stmt yet.
583f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
5846122f3e6SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
585f22ef01cSRoman Divacky                                                "cannot compile this %0 yet");
586f22ef01cSRoman Divacky   std::string Msg = Type;
587f22ef01cSRoman Divacky   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
588f22ef01cSRoman Divacky     << Msg << S->getSourceRange();
589f22ef01cSRoman Divacky }
590f22ef01cSRoman Divacky 
591f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
592f22ef01cSRoman Divacky /// specified decl yet.
593f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
5946122f3e6SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
595f22ef01cSRoman Divacky                                                "cannot compile this %0 yet");
596f22ef01cSRoman Divacky   std::string Msg = Type;
597f22ef01cSRoman Divacky   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
598f22ef01cSRoman Divacky }
599f22ef01cSRoman Divacky 
60017a519f9SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
60117a519f9SDimitry Andric   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
60217a519f9SDimitry Andric }
60317a519f9SDimitry Andric 
604f22ef01cSRoman Divacky void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
6052754fe60SDimitry Andric                                         const NamedDecl *D) const {
606f22ef01cSRoman Divacky   // Internal definitions always have default visibility.
607f22ef01cSRoman Divacky   if (GV->hasLocalLinkage()) {
608f22ef01cSRoman Divacky     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
609f22ef01cSRoman Divacky     return;
610f22ef01cSRoman Divacky   }
611f22ef01cSRoman Divacky 
6122754fe60SDimitry Andric   // Set visibility for definitions.
613139f7f9bSDimitry Andric   LinkageInfo LV = D->getLinkageAndVisibility();
614139f7f9bSDimitry Andric   if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
615139f7f9bSDimitry Andric     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
616f22ef01cSRoman Divacky }
617f22ef01cSRoman Divacky 
6187ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
6197ae0e2c9SDimitry Andric   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
6207ae0e2c9SDimitry Andric       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
6217ae0e2c9SDimitry Andric       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
6227ae0e2c9SDimitry Andric       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
6237ae0e2c9SDimitry Andric       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
6247ae0e2c9SDimitry Andric }
6257ae0e2c9SDimitry Andric 
6267ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
6277ae0e2c9SDimitry Andric     CodeGenOptions::TLSModel M) {
6287ae0e2c9SDimitry Andric   switch (M) {
6297ae0e2c9SDimitry Andric   case CodeGenOptions::GeneralDynamicTLSModel:
6307ae0e2c9SDimitry Andric     return llvm::GlobalVariable::GeneralDynamicTLSModel;
6317ae0e2c9SDimitry Andric   case CodeGenOptions::LocalDynamicTLSModel:
6327ae0e2c9SDimitry Andric     return llvm::GlobalVariable::LocalDynamicTLSModel;
6337ae0e2c9SDimitry Andric   case CodeGenOptions::InitialExecTLSModel:
6347ae0e2c9SDimitry Andric     return llvm::GlobalVariable::InitialExecTLSModel;
6357ae0e2c9SDimitry Andric   case CodeGenOptions::LocalExecTLSModel:
6367ae0e2c9SDimitry Andric     return llvm::GlobalVariable::LocalExecTLSModel;
6377ae0e2c9SDimitry Andric   }
6387ae0e2c9SDimitry Andric   llvm_unreachable("Invalid TLS model!");
6397ae0e2c9SDimitry Andric }
6407ae0e2c9SDimitry Andric 
64139d628a0SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
642284c1978SDimitry Andric   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
6437ae0e2c9SDimitry Andric 
64439d628a0SDimitry Andric   llvm::GlobalValue::ThreadLocalMode TLM;
6453861d79fSDimitry Andric   TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
6467ae0e2c9SDimitry Andric 
6477ae0e2c9SDimitry Andric   // Override the TLS model if it is explicitly specified.
64859d1ed5bSDimitry Andric   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
6497ae0e2c9SDimitry Andric     TLM = GetLLVMTLSModel(Attr->getModel());
6507ae0e2c9SDimitry Andric   }
6517ae0e2c9SDimitry Andric 
6527ae0e2c9SDimitry Andric   GV->setThreadLocalMode(TLM);
6537ae0e2c9SDimitry Andric }
6547ae0e2c9SDimitry Andric 
6556122f3e6SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
656444ed5c5SDimitry Andric   GlobalDecl CanonicalGD = GD.getCanonicalDecl();
657444ed5c5SDimitry Andric 
658444ed5c5SDimitry Andric   // Some ABIs don't have constructor variants.  Make sure that base and
659444ed5c5SDimitry Andric   // complete constructors get mangled the same.
660444ed5c5SDimitry Andric   if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
661444ed5c5SDimitry Andric     if (!getTarget().getCXXABI().hasConstructorVariants()) {
662444ed5c5SDimitry Andric       CXXCtorType OrigCtorType = GD.getCtorType();
663444ed5c5SDimitry Andric       assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
664444ed5c5SDimitry Andric       if (OrigCtorType == Ctor_Base)
665444ed5c5SDimitry Andric         CanonicalGD = GlobalDecl(CD, Ctor_Complete);
666444ed5c5SDimitry Andric     }
667444ed5c5SDimitry Andric   }
668444ed5c5SDimitry Andric 
669444ed5c5SDimitry Andric   StringRef &FoundStr = MangledDeclNames[CanonicalGD];
67059d1ed5bSDimitry Andric   if (!FoundStr.empty())
67159d1ed5bSDimitry Andric     return FoundStr;
672f22ef01cSRoman Divacky 
67359d1ed5bSDimitry Andric   const auto *ND = cast<NamedDecl>(GD.getDecl());
674dff0c46cSDimitry Andric   SmallString<256> Buffer;
67559d1ed5bSDimitry Andric   StringRef Str;
67659d1ed5bSDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
6772754fe60SDimitry Andric     llvm::raw_svector_ostream Out(Buffer);
67859d1ed5bSDimitry Andric     if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
6792754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
68059d1ed5bSDimitry Andric     else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
6812754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
682ffd1746dSEd Schouten     else
6832754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleName(ND, Out);
68459d1ed5bSDimitry Andric     Str = Out.str();
68559d1ed5bSDimitry Andric   } else {
68659d1ed5bSDimitry Andric     IdentifierInfo *II = ND->getIdentifier();
68759d1ed5bSDimitry Andric     assert(II && "Attempt to mangle unnamed decl.");
68844290647SDimitry Andric     const auto *FD = dyn_cast<FunctionDecl>(ND);
68944290647SDimitry Andric 
69044290647SDimitry Andric     if (FD &&
69144290647SDimitry Andric         FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
69244290647SDimitry Andric       llvm::raw_svector_ostream Out(Buffer);
69344290647SDimitry Andric       Out << "__regcall3__" << II->getName();
69444290647SDimitry Andric       Str = Out.str();
69544290647SDimitry Andric     } else {
69659d1ed5bSDimitry Andric       Str = II->getName();
697ffd1746dSEd Schouten     }
69844290647SDimitry Andric   }
699ffd1746dSEd Schouten 
70039d628a0SDimitry Andric   // Keep the first result in the case of a mangling collision.
70139d628a0SDimitry Andric   auto Result = Manglings.insert(std::make_pair(Str, GD));
70239d628a0SDimitry Andric   return FoundStr = Result.first->first();
70359d1ed5bSDimitry Andric }
70459d1ed5bSDimitry Andric 
70559d1ed5bSDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
706ffd1746dSEd Schouten                                              const BlockDecl *BD) {
7072754fe60SDimitry Andric   MangleContext &MangleCtx = getCXXABI().getMangleContext();
7082754fe60SDimitry Andric   const Decl *D = GD.getDecl();
70959d1ed5bSDimitry Andric 
71059d1ed5bSDimitry Andric   SmallString<256> Buffer;
71159d1ed5bSDimitry Andric   llvm::raw_svector_ostream Out(Buffer);
71259d1ed5bSDimitry Andric   if (!D)
7137ae0e2c9SDimitry Andric     MangleCtx.mangleGlobalBlock(BD,
7147ae0e2c9SDimitry Andric       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
71559d1ed5bSDimitry Andric   else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
7162754fe60SDimitry Andric     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
71759d1ed5bSDimitry Andric   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
7182754fe60SDimitry Andric     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
7192754fe60SDimitry Andric   else
7202754fe60SDimitry Andric     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
72159d1ed5bSDimitry Andric 
72239d628a0SDimitry Andric   auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
72339d628a0SDimitry Andric   return Result.first->first();
724f22ef01cSRoman Divacky }
725f22ef01cSRoman Divacky 
7266122f3e6SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
727f22ef01cSRoman Divacky   return getModule().getNamedValue(Name);
728f22ef01cSRoman Divacky }
729f22ef01cSRoman Divacky 
730f22ef01cSRoman Divacky /// AddGlobalCtor - Add a function to the list that will be called before
731f22ef01cSRoman Divacky /// main() runs.
73259d1ed5bSDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
73359d1ed5bSDimitry Andric                                   llvm::Constant *AssociatedData) {
734f22ef01cSRoman Divacky   // FIXME: Type coercion of void()* types.
73559d1ed5bSDimitry Andric   GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
736f22ef01cSRoman Divacky }
737f22ef01cSRoman Divacky 
738f22ef01cSRoman Divacky /// AddGlobalDtor - Add a function to the list that will be called
739f22ef01cSRoman Divacky /// when the module is unloaded.
740f22ef01cSRoman Divacky void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
741f22ef01cSRoman Divacky   // FIXME: Type coercion of void()* types.
74259d1ed5bSDimitry Andric   GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
743f22ef01cSRoman Divacky }
744f22ef01cSRoman Divacky 
74544290647SDimitry Andric void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
74644290647SDimitry Andric   if (Fns.empty()) return;
74744290647SDimitry Andric 
748f22ef01cSRoman Divacky   // Ctor function type is void()*.
749bd5abe19SDimitry Andric   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
750f22ef01cSRoman Divacky   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
751f22ef01cSRoman Divacky 
75259d1ed5bSDimitry Andric   // Get the type of a ctor entry, { i32, void ()*, i8* }.
75359d1ed5bSDimitry Andric   llvm::StructType *CtorStructTy = llvm::StructType::get(
75439d628a0SDimitry Andric       Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr);
755f22ef01cSRoman Divacky 
756f22ef01cSRoman Divacky   // Construct the constructor and destructor arrays.
75744290647SDimitry Andric   ConstantInitBuilder builder(*this);
75844290647SDimitry Andric   auto ctors = builder.beginArray(CtorStructTy);
7598f0fd8f6SDimitry Andric   for (const auto &I : Fns) {
76044290647SDimitry Andric     auto ctor = ctors.beginStruct(CtorStructTy);
76144290647SDimitry Andric     ctor.addInt(Int32Ty, I.Priority);
76244290647SDimitry Andric     ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
76344290647SDimitry Andric     if (I.AssociatedData)
76444290647SDimitry Andric       ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
76544290647SDimitry Andric     else
76644290647SDimitry Andric       ctor.addNullPointer(VoidPtrTy);
76744290647SDimitry Andric     ctor.finishAndAddTo(ctors);
768f22ef01cSRoman Divacky   }
769f22ef01cSRoman Divacky 
77044290647SDimitry Andric   auto list =
77144290647SDimitry Andric     ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
77244290647SDimitry Andric                                 /*constant*/ false,
77344290647SDimitry Andric                                 llvm::GlobalValue::AppendingLinkage);
77444290647SDimitry Andric 
77544290647SDimitry Andric   // The LTO linker doesn't seem to like it when we set an alignment
77644290647SDimitry Andric   // on appending variables.  Take it off as a workaround.
77744290647SDimitry Andric   list->setAlignment(0);
77844290647SDimitry Andric 
77944290647SDimitry Andric   Fns.clear();
780f22ef01cSRoman Divacky }
781f22ef01cSRoman Divacky 
782f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes
783f785676fSDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
78459d1ed5bSDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
785f785676fSDimitry Andric 
786e580952dSDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
787f22ef01cSRoman Divacky 
78859d1ed5bSDimitry Andric   if (isa<CXXDestructorDecl>(D) &&
78959d1ed5bSDimitry Andric       getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
79059d1ed5bSDimitry Andric                                          GD.getDtorType())) {
79159d1ed5bSDimitry Andric     // Destructor variants in the Microsoft C++ ABI are always internal or
79259d1ed5bSDimitry Andric     // linkonce_odr thunks emitted on an as-needed basis.
79359d1ed5bSDimitry Andric     return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
79459d1ed5bSDimitry Andric                                    : llvm::GlobalValue::LinkOnceODRLinkage;
795f22ef01cSRoman Divacky   }
796f22ef01cSRoman Divacky 
797e7145dcbSDimitry Andric   if (isa<CXXConstructorDecl>(D) &&
798e7145dcbSDimitry Andric       cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
799e7145dcbSDimitry Andric       Context.getTargetInfo().getCXXABI().isMicrosoft()) {
800e7145dcbSDimitry Andric     // Our approach to inheriting constructors is fundamentally different from
801e7145dcbSDimitry Andric     // that used by the MS ABI, so keep our inheriting constructor thunks
802e7145dcbSDimitry Andric     // internal rather than trying to pick an unambiguous mangling for them.
803e7145dcbSDimitry Andric     return llvm::GlobalValue::InternalLinkage;
804e7145dcbSDimitry Andric   }
805e7145dcbSDimitry Andric 
80659d1ed5bSDimitry Andric   return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
80759d1ed5bSDimitry Andric }
808f22ef01cSRoman Divacky 
80997bc6c73SDimitry Andric void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
81097bc6c73SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
81197bc6c73SDimitry Andric 
81297bc6c73SDimitry Andric   if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
81397bc6c73SDimitry Andric     if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
81497bc6c73SDimitry Andric       // Don't dllexport/import destructor thunks.
81597bc6c73SDimitry Andric       F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
81697bc6c73SDimitry Andric       return;
81797bc6c73SDimitry Andric     }
81897bc6c73SDimitry Andric   }
81997bc6c73SDimitry Andric 
82097bc6c73SDimitry Andric   if (FD->hasAttr<DLLImportAttr>())
82197bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
82297bc6c73SDimitry Andric   else if (FD->hasAttr<DLLExportAttr>())
82397bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
82497bc6c73SDimitry Andric   else
82597bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
82697bc6c73SDimitry Andric }
82797bc6c73SDimitry Andric 
828e7145dcbSDimitry Andric llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
8290623d748SDimitry Andric   llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
8300623d748SDimitry Andric   if (!MDS) return nullptr;
8310623d748SDimitry Andric 
83244290647SDimitry Andric   return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
8330623d748SDimitry Andric }
8340623d748SDimitry Andric 
83559d1ed5bSDimitry Andric void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
83659d1ed5bSDimitry Andric                                                     llvm::Function *F) {
83759d1ed5bSDimitry Andric   setNonAliasAttributes(D, F);
838f22ef01cSRoman Divacky }
839f22ef01cSRoman Divacky 
840f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
841f22ef01cSRoman Divacky                                               const CGFunctionInfo &Info,
842f22ef01cSRoman Divacky                                               llvm::Function *F) {
843f22ef01cSRoman Divacky   unsigned CallingConv;
8446bc11b14SDimitry Andric   llvm::AttributeList PAL;
8456bc11b14SDimitry Andric   ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false);
8466bc11b14SDimitry Andric   F->setAttributes(PAL);
847f22ef01cSRoman Divacky   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
848f22ef01cSRoman Divacky }
849f22ef01cSRoman Divacky 
8506122f3e6SDimitry Andric /// Determines whether the language options require us to model
8516122f3e6SDimitry Andric /// unwind exceptions.  We treat -fexceptions as mandating this
8526122f3e6SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions
8536122f3e6SDimitry Andric /// enabled.  This means, for example, that C with -fexceptions
8546122f3e6SDimitry Andric /// enables this.
855dff0c46cSDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) {
8566122f3e6SDimitry Andric   // If exceptions are completely disabled, obviously this is false.
857dff0c46cSDimitry Andric   if (!LangOpts.Exceptions) return false;
8586122f3e6SDimitry Andric 
8596122f3e6SDimitry Andric   // If C++ exceptions are enabled, this is true.
860dff0c46cSDimitry Andric   if (LangOpts.CXXExceptions) return true;
8616122f3e6SDimitry Andric 
8626122f3e6SDimitry Andric   // If ObjC exceptions are enabled, this depends on the ABI.
863dff0c46cSDimitry Andric   if (LangOpts.ObjCExceptions) {
8647ae0e2c9SDimitry Andric     return LangOpts.ObjCRuntime.hasUnwindExceptions();
8656122f3e6SDimitry Andric   }
8666122f3e6SDimitry Andric 
8676122f3e6SDimitry Andric   return true;
8686122f3e6SDimitry Andric }
8696122f3e6SDimitry Andric 
870f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
871f22ef01cSRoman Divacky                                                            llvm::Function *F) {
872f785676fSDimitry Andric   llvm::AttrBuilder B;
873f785676fSDimitry Andric 
874bd5abe19SDimitry Andric   if (CodeGenOpts.UnwindTables)
875f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::UWTable);
876bd5abe19SDimitry Andric 
877dff0c46cSDimitry Andric   if (!hasUnwindExceptions(LangOpts))
878f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoUnwind);
879f22ef01cSRoman Divacky 
8800623d748SDimitry Andric   if (LangOpts.getStackProtector() == LangOptions::SSPOn)
8810623d748SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtect);
8820623d748SDimitry Andric   else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
8830623d748SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtectStrong);
8840623d748SDimitry Andric   else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
8850623d748SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtectReq);
8860623d748SDimitry Andric 
8870623d748SDimitry Andric   if (!D) {
88844290647SDimitry Andric     // If we don't have a declaration to control inlining, the function isn't
88944290647SDimitry Andric     // explicitly marked as alwaysinline for semantic reasons, and inlining is
89044290647SDimitry Andric     // disabled, mark the function as noinline.
89144290647SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
89244290647SDimitry Andric         CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
89344290647SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
89444290647SDimitry Andric 
89520e90f04SDimitry Andric     F->addAttributes(
89620e90f04SDimitry Andric         llvm::AttributeList::FunctionIndex,
89720e90f04SDimitry Andric         llvm::AttributeList::get(F->getContext(),
89820e90f04SDimitry Andric                                  llvm::AttributeList::FunctionIndex, B));
8990623d748SDimitry Andric     return;
9000623d748SDimitry Andric   }
9010623d748SDimitry Andric 
90244290647SDimitry Andric   if (D->hasAttr<OptimizeNoneAttr>()) {
90344290647SDimitry Andric     B.addAttribute(llvm::Attribute::OptimizeNone);
90444290647SDimitry Andric 
90544290647SDimitry Andric     // OptimizeNone implies noinline; we should not be inlining such functions.
90644290647SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
90744290647SDimitry Andric     assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
90844290647SDimitry Andric            "OptimizeNone and AlwaysInline on same function!");
90944290647SDimitry Andric 
91044290647SDimitry Andric     // We still need to handle naked functions even though optnone subsumes
91144290647SDimitry Andric     // much of their semantics.
91244290647SDimitry Andric     if (D->hasAttr<NakedAttr>())
91344290647SDimitry Andric       B.addAttribute(llvm::Attribute::Naked);
91444290647SDimitry Andric 
91544290647SDimitry Andric     // OptimizeNone wins over OptimizeForSize and MinSize.
91644290647SDimitry Andric     F->removeFnAttr(llvm::Attribute::OptimizeForSize);
91744290647SDimitry Andric     F->removeFnAttr(llvm::Attribute::MinSize);
91844290647SDimitry Andric   } else if (D->hasAttr<NakedAttr>()) {
9196122f3e6SDimitry Andric     // Naked implies noinline: we should not be inlining such functions.
920f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::Naked);
921f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
92259d1ed5bSDimitry Andric   } else if (D->hasAttr<NoDuplicateAttr>()) {
92359d1ed5bSDimitry Andric     B.addAttribute(llvm::Attribute::NoDuplicate);
924f785676fSDimitry Andric   } else if (D->hasAttr<NoInlineAttr>()) {
925f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
92659d1ed5bSDimitry Andric   } else if (D->hasAttr<AlwaysInlineAttr>() &&
92744290647SDimitry Andric              !F->hasFnAttribute(llvm::Attribute::NoInline)) {
928f785676fSDimitry Andric     // (noinline wins over always_inline, and we can't specify both in IR)
929f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::AlwaysInline);
93044290647SDimitry Andric   } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
93144290647SDimitry Andric     // If we're not inlining, then force everything that isn't always_inline to
93244290647SDimitry Andric     // carry an explicit noinline attribute.
93344290647SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
93444290647SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
93544290647SDimitry Andric   } else {
93644290647SDimitry Andric     // Otherwise, propagate the inline hint attribute and potentially use its
93744290647SDimitry Andric     // absence to mark things as noinline.
93844290647SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
93944290647SDimitry Andric       if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
94044290647SDimitry Andric             return Redecl->isInlineSpecified();
94144290647SDimitry Andric           })) {
94244290647SDimitry Andric         B.addAttribute(llvm::Attribute::InlineHint);
94344290647SDimitry Andric       } else if (CodeGenOpts.getInlining() ==
94444290647SDimitry Andric                      CodeGenOptions::OnlyHintInlining &&
94544290647SDimitry Andric                  !FD->isInlined() &&
94644290647SDimitry Andric                  !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
94744290647SDimitry Andric         B.addAttribute(llvm::Attribute::NoInline);
94844290647SDimitry Andric       }
94944290647SDimitry Andric     }
9506122f3e6SDimitry Andric   }
9512754fe60SDimitry Andric 
95244290647SDimitry Andric   // Add other optimization related attributes if we are optimizing this
95344290647SDimitry Andric   // function.
95444290647SDimitry Andric   if (!D->hasAttr<OptimizeNoneAttr>()) {
955f785676fSDimitry Andric     if (D->hasAttr<ColdAttr>()) {
956f785676fSDimitry Andric       B.addAttribute(llvm::Attribute::OptimizeForSize);
957f785676fSDimitry Andric       B.addAttribute(llvm::Attribute::Cold);
958f785676fSDimitry Andric     }
9593861d79fSDimitry Andric 
9603861d79fSDimitry Andric     if (D->hasAttr<MinSizeAttr>())
961f785676fSDimitry Andric       B.addAttribute(llvm::Attribute::MinSize);
96244290647SDimitry Andric   }
963f22ef01cSRoman Divacky 
96420e90f04SDimitry Andric   F->addAttributes(llvm::AttributeList::FunctionIndex,
96520e90f04SDimitry Andric                    llvm::AttributeList::get(
96620e90f04SDimitry Andric                        F->getContext(), llvm::AttributeList::FunctionIndex, B));
967f785676fSDimitry Andric 
968e580952dSDimitry Andric   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
969e580952dSDimitry Andric   if (alignment)
970e580952dSDimitry Andric     F->setAlignment(alignment);
971e580952dSDimitry Andric 
9720623d748SDimitry Andric   // Some C++ ABIs require 2-byte alignment for member functions, in order to
9730623d748SDimitry Andric   // reserve a bit for differentiating between virtual and non-virtual member
9740623d748SDimitry Andric   // functions. If the current target's C++ ABI requires this and this is a
9750623d748SDimitry Andric   // member function, set its alignment accordingly.
9760623d748SDimitry Andric   if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
977f22ef01cSRoman Divacky     if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
978f22ef01cSRoman Divacky       F->setAlignment(2);
979f22ef01cSRoman Divacky   }
98044290647SDimitry Andric 
98144290647SDimitry Andric   // In the cross-dso CFI mode, we want !type attributes on definitions only.
98244290647SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
98344290647SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D))
98444290647SDimitry Andric       CreateFunctionTypeMetadata(FD, F);
9850623d748SDimitry Andric }
986f22ef01cSRoman Divacky 
987f22ef01cSRoman Divacky void CodeGenModule::SetCommonAttributes(const Decl *D,
988f22ef01cSRoman Divacky                                         llvm::GlobalValue *GV) {
9890623d748SDimitry Andric   if (const auto *ND = dyn_cast_or_null<NamedDecl>(D))
9902754fe60SDimitry Andric     setGlobalVisibility(GV, ND);
9912754fe60SDimitry Andric   else
9922754fe60SDimitry Andric     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
993f22ef01cSRoman Divacky 
9940623d748SDimitry Andric   if (D && D->hasAttr<UsedAttr>())
99559d1ed5bSDimitry Andric     addUsedGlobal(GV);
99659d1ed5bSDimitry Andric }
99759d1ed5bSDimitry Andric 
99839d628a0SDimitry Andric void CodeGenModule::setAliasAttributes(const Decl *D,
99939d628a0SDimitry Andric                                        llvm::GlobalValue *GV) {
100039d628a0SDimitry Andric   SetCommonAttributes(D, GV);
100139d628a0SDimitry Andric 
100239d628a0SDimitry Andric   // Process the dllexport attribute based on whether the original definition
100339d628a0SDimitry Andric   // (not necessarily the aliasee) was exported.
100439d628a0SDimitry Andric   if (D->hasAttr<DLLExportAttr>())
100539d628a0SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
100639d628a0SDimitry Andric }
100739d628a0SDimitry Andric 
100859d1ed5bSDimitry Andric void CodeGenModule::setNonAliasAttributes(const Decl *D,
100959d1ed5bSDimitry Andric                                           llvm::GlobalObject *GO) {
101059d1ed5bSDimitry Andric   SetCommonAttributes(D, GO);
1011f22ef01cSRoman Divacky 
10120623d748SDimitry Andric   if (D)
1013f22ef01cSRoman Divacky     if (const SectionAttr *SA = D->getAttr<SectionAttr>())
101459d1ed5bSDimitry Andric       GO->setSection(SA->getName());
1015f22ef01cSRoman Divacky 
101697bc6c73SDimitry Andric   getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
1017f22ef01cSRoman Divacky }
1018f22ef01cSRoman Divacky 
1019f22ef01cSRoman Divacky void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
1020f22ef01cSRoman Divacky                                                   llvm::Function *F,
1021f22ef01cSRoman Divacky                                                   const CGFunctionInfo &FI) {
1022f22ef01cSRoman Divacky   SetLLVMFunctionAttributes(D, FI, F);
1023f22ef01cSRoman Divacky   SetLLVMFunctionAttributesForDefinition(D, F);
1024f22ef01cSRoman Divacky 
1025f22ef01cSRoman Divacky   F->setLinkage(llvm::Function::InternalLinkage);
1026f22ef01cSRoman Divacky 
102759d1ed5bSDimitry Andric   setNonAliasAttributes(D, F);
102859d1ed5bSDimitry Andric }
102959d1ed5bSDimitry Andric 
103059d1ed5bSDimitry Andric static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
103159d1ed5bSDimitry Andric                                          const NamedDecl *ND) {
103259d1ed5bSDimitry Andric   // Set linkage and visibility in case we never see a definition.
103359d1ed5bSDimitry Andric   LinkageInfo LV = ND->getLinkageAndVisibility();
103459d1ed5bSDimitry Andric   if (LV.getLinkage() != ExternalLinkage) {
103559d1ed5bSDimitry Andric     // Don't set internal linkage on declarations.
103659d1ed5bSDimitry Andric   } else {
103759d1ed5bSDimitry Andric     if (ND->hasAttr<DLLImportAttr>()) {
103859d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
103959d1ed5bSDimitry Andric       GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
104059d1ed5bSDimitry Andric     } else if (ND->hasAttr<DLLExportAttr>()) {
104159d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
104259d1ed5bSDimitry Andric     } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
104359d1ed5bSDimitry Andric       // "extern_weak" is overloaded in LLVM; we probably should have
104459d1ed5bSDimitry Andric       // separate linkage types for this.
104559d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
104659d1ed5bSDimitry Andric     }
104759d1ed5bSDimitry Andric 
104859d1ed5bSDimitry Andric     // Set visibility on a declaration only if it's explicit.
104959d1ed5bSDimitry Andric     if (LV.isVisibilityExplicit())
105059d1ed5bSDimitry Andric       GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
105159d1ed5bSDimitry Andric   }
1052f22ef01cSRoman Divacky }
1053f22ef01cSRoman Divacky 
1054e7145dcbSDimitry Andric void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD,
10550623d748SDimitry Andric                                                llvm::Function *F) {
10560623d748SDimitry Andric   // Only if we are checking indirect calls.
10570623d748SDimitry Andric   if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
10580623d748SDimitry Andric     return;
10590623d748SDimitry Andric 
10600623d748SDimitry Andric   // Non-static class methods are handled via vtable pointer checks elsewhere.
10610623d748SDimitry Andric   if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
10620623d748SDimitry Andric     return;
10630623d748SDimitry Andric 
10640623d748SDimitry Andric   // Additionally, if building with cross-DSO support...
10650623d748SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
10660623d748SDimitry Andric     // Skip available_externally functions. They won't be codegen'ed in the
10670623d748SDimitry Andric     // current module anyway.
10680623d748SDimitry Andric     if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
10690623d748SDimitry Andric       return;
10700623d748SDimitry Andric   }
10710623d748SDimitry Andric 
10720623d748SDimitry Andric   llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
1073e7145dcbSDimitry Andric   F->addTypeMetadata(0, MD);
10740623d748SDimitry Andric 
10750623d748SDimitry Andric   // Emit a hash-based bit set entry for cross-DSO calls.
1076e7145dcbSDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
1077e7145dcbSDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1078e7145dcbSDimitry Andric       F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
10790623d748SDimitry Andric }
10800623d748SDimitry Andric 
108139d628a0SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
108239d628a0SDimitry Andric                                           bool IsIncompleteFunction,
108339d628a0SDimitry Andric                                           bool IsThunk) {
108433956c43SDimitry Andric   if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
10853b0f4066SDimitry Andric     // If this is an intrinsic function, set the function's attributes
10863b0f4066SDimitry Andric     // to the intrinsic's attributes.
108733956c43SDimitry Andric     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
10883b0f4066SDimitry Andric     return;
10893b0f4066SDimitry Andric   }
10903b0f4066SDimitry Andric 
109159d1ed5bSDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
1092f22ef01cSRoman Divacky 
1093f22ef01cSRoman Divacky   if (!IsIncompleteFunction)
1094dff0c46cSDimitry Andric     SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
1095f22ef01cSRoman Divacky 
109659d1ed5bSDimitry Andric   // Add the Returned attribute for "this", except for iOS 5 and earlier
109759d1ed5bSDimitry Andric   // where substantial code, including the libstdc++ dylib, was compiled with
109859d1ed5bSDimitry Andric   // GCC and does not actually return "this".
109939d628a0SDimitry Andric   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
110044290647SDimitry Andric       !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
1101f785676fSDimitry Andric     assert(!F->arg_empty() &&
1102f785676fSDimitry Andric            F->arg_begin()->getType()
1103f785676fSDimitry Andric              ->canLosslesslyBitCastTo(F->getReturnType()) &&
1104f785676fSDimitry Andric            "unexpected this return");
1105f785676fSDimitry Andric     F->addAttribute(1, llvm::Attribute::Returned);
1106f785676fSDimitry Andric   }
1107f785676fSDimitry Andric 
1108f22ef01cSRoman Divacky   // Only a few attributes are set on declarations; these may later be
1109f22ef01cSRoman Divacky   // overridden by a definition.
1110f22ef01cSRoman Divacky 
111159d1ed5bSDimitry Andric   setLinkageAndVisibilityForGV(F, FD);
11122754fe60SDimitry Andric 
1113f22ef01cSRoman Divacky   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
1114f22ef01cSRoman Divacky     F->setSection(SA->getName());
1115f785676fSDimitry Andric 
1116e7145dcbSDimitry Andric   if (FD->isReplaceableGlobalAllocationFunction()) {
1117f785676fSDimitry Andric     // A replaceable global allocation function does not act like a builtin by
1118f785676fSDimitry Andric     // default, only if it is invoked by a new-expression or delete-expression.
111920e90f04SDimitry Andric     F->addAttribute(llvm::AttributeList::FunctionIndex,
1120f785676fSDimitry Andric                     llvm::Attribute::NoBuiltin);
11210623d748SDimitry Andric 
1122e7145dcbSDimitry Andric     // A sane operator new returns a non-aliasing pointer.
1123e7145dcbSDimitry Andric     // FIXME: Also add NonNull attribute to the return value
1124e7145dcbSDimitry Andric     // for the non-nothrow forms?
1125e7145dcbSDimitry Andric     auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1126e7145dcbSDimitry Andric     if (getCodeGenOpts().AssumeSaneOperatorNew &&
1127e7145dcbSDimitry Andric         (Kind == OO_New || Kind == OO_Array_New))
112820e90f04SDimitry Andric       F->addAttribute(llvm::AttributeList::ReturnIndex,
1129e7145dcbSDimitry Andric                       llvm::Attribute::NoAlias);
1130e7145dcbSDimitry Andric   }
1131e7145dcbSDimitry Andric 
1132e7145dcbSDimitry Andric   if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1133e7145dcbSDimitry Andric     F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1134e7145dcbSDimitry Andric   else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1135e7145dcbSDimitry Andric     if (MD->isVirtual())
1136e7145dcbSDimitry Andric       F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1137e7145dcbSDimitry Andric 
113844290647SDimitry Andric   // Don't emit entries for function declarations in the cross-DSO mode. This
113944290647SDimitry Andric   // is handled with better precision by the receiving DSO.
114044290647SDimitry Andric   if (!CodeGenOpts.SanitizeCfiCrossDso)
1141e7145dcbSDimitry Andric     CreateFunctionTypeMetadata(FD, F);
1142f22ef01cSRoman Divacky }
1143f22ef01cSRoman Divacky 
114459d1ed5bSDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
1145f22ef01cSRoman Divacky   assert(!GV->isDeclaration() &&
1146f22ef01cSRoman Divacky          "Only globals with definition can force usage.");
114797bc6c73SDimitry Andric   LLVMUsed.emplace_back(GV);
1148f22ef01cSRoman Divacky }
1149f22ef01cSRoman Divacky 
115059d1ed5bSDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
115159d1ed5bSDimitry Andric   assert(!GV->isDeclaration() &&
115259d1ed5bSDimitry Andric          "Only globals with definition can force usage.");
115397bc6c73SDimitry Andric   LLVMCompilerUsed.emplace_back(GV);
115459d1ed5bSDimitry Andric }
115559d1ed5bSDimitry Andric 
115659d1ed5bSDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name,
115759d1ed5bSDimitry Andric                      std::vector<llvm::WeakVH> &List) {
1158f22ef01cSRoman Divacky   // Don't create llvm.used if there is no need.
115959d1ed5bSDimitry Andric   if (List.empty())
1160f22ef01cSRoman Divacky     return;
1161f22ef01cSRoman Divacky 
116259d1ed5bSDimitry Andric   // Convert List to what ConstantArray needs.
1163dff0c46cSDimitry Andric   SmallVector<llvm::Constant*, 8> UsedArray;
116459d1ed5bSDimitry Andric   UsedArray.resize(List.size());
116559d1ed5bSDimitry Andric   for (unsigned i = 0, e = List.size(); i != e; ++i) {
1166f22ef01cSRoman Divacky     UsedArray[i] =
116744f7b0dcSDimitry Andric         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
116844f7b0dcSDimitry Andric             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
1169f22ef01cSRoman Divacky   }
1170f22ef01cSRoman Divacky 
1171f22ef01cSRoman Divacky   if (UsedArray.empty())
1172f22ef01cSRoman Divacky     return;
117359d1ed5bSDimitry Andric   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
1174f22ef01cSRoman Divacky 
117559d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
117659d1ed5bSDimitry Andric       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
117759d1ed5bSDimitry Andric       llvm::ConstantArray::get(ATy, UsedArray), Name);
1178f22ef01cSRoman Divacky 
1179f22ef01cSRoman Divacky   GV->setSection("llvm.metadata");
1180f22ef01cSRoman Divacky }
1181f22ef01cSRoman Divacky 
118259d1ed5bSDimitry Andric void CodeGenModule::emitLLVMUsed() {
118359d1ed5bSDimitry Andric   emitUsed(*this, "llvm.used", LLVMUsed);
118459d1ed5bSDimitry Andric   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
118559d1ed5bSDimitry Andric }
118659d1ed5bSDimitry Andric 
1187f785676fSDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
118839d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
1189f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1190f785676fSDimitry Andric }
1191f785676fSDimitry Andric 
1192f785676fSDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1193f785676fSDimitry Andric   llvm::SmallString<32> Opt;
1194f785676fSDimitry Andric   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
119539d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1196f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1197f785676fSDimitry Andric }
1198f785676fSDimitry Andric 
1199f785676fSDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) {
1200f785676fSDimitry Andric   llvm::SmallString<24> Opt;
1201f785676fSDimitry Andric   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
120239d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1203f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1204f785676fSDimitry Andric }
1205f785676fSDimitry Andric 
1206139f7f9bSDimitry Andric /// \brief Add link options implied by the given module, including modules
1207139f7f9bSDimitry Andric /// it depends on, using a postorder walk.
120839d628a0SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
120939d628a0SDimitry Andric                                     SmallVectorImpl<llvm::Metadata *> &Metadata,
1210139f7f9bSDimitry Andric                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
1211139f7f9bSDimitry Andric   // Import this module's parent.
121239d628a0SDimitry Andric   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
1213f785676fSDimitry Andric     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
1214139f7f9bSDimitry Andric   }
1215139f7f9bSDimitry Andric 
1216139f7f9bSDimitry Andric   // Import this module's dependencies.
1217139f7f9bSDimitry Andric   for (unsigned I = Mod->Imports.size(); I > 0; --I) {
121839d628a0SDimitry Andric     if (Visited.insert(Mod->Imports[I - 1]).second)
1219f785676fSDimitry Andric       addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
1220139f7f9bSDimitry Andric   }
1221139f7f9bSDimitry Andric 
1222139f7f9bSDimitry Andric   // Add linker options to link against the libraries/frameworks
1223139f7f9bSDimitry Andric   // described by this module.
1224f785676fSDimitry Andric   llvm::LLVMContext &Context = CGM.getLLVMContext();
1225139f7f9bSDimitry Andric   for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
1226f785676fSDimitry Andric     // Link against a framework.  Frameworks are currently Darwin only, so we
1227f785676fSDimitry Andric     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
1228139f7f9bSDimitry Andric     if (Mod->LinkLibraries[I-1].IsFramework) {
122939d628a0SDimitry Andric       llvm::Metadata *Args[2] = {
1230139f7f9bSDimitry Andric           llvm::MDString::get(Context, "-framework"),
123139d628a0SDimitry Andric           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
1232139f7f9bSDimitry Andric 
1233139f7f9bSDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, Args));
1234139f7f9bSDimitry Andric       continue;
1235139f7f9bSDimitry Andric     }
1236139f7f9bSDimitry Andric 
1237139f7f9bSDimitry Andric     // Link against a library.
1238f785676fSDimitry Andric     llvm::SmallString<24> Opt;
1239f785676fSDimitry Andric     CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1240f785676fSDimitry Andric       Mod->LinkLibraries[I-1].Library, Opt);
124139d628a0SDimitry Andric     auto *OptString = llvm::MDString::get(Context, Opt);
1242139f7f9bSDimitry Andric     Metadata.push_back(llvm::MDNode::get(Context, OptString));
1243139f7f9bSDimitry Andric   }
1244139f7f9bSDimitry Andric }
1245139f7f9bSDimitry Andric 
1246139f7f9bSDimitry Andric void CodeGenModule::EmitModuleLinkOptions() {
1247139f7f9bSDimitry Andric   // Collect the set of all of the modules we want to visit to emit link
1248139f7f9bSDimitry Andric   // options, which is essentially the imported modules and all of their
1249139f7f9bSDimitry Andric   // non-explicit child modules.
1250139f7f9bSDimitry Andric   llvm::SetVector<clang::Module *> LinkModules;
1251139f7f9bSDimitry Andric   llvm::SmallPtrSet<clang::Module *, 16> Visited;
1252139f7f9bSDimitry Andric   SmallVector<clang::Module *, 16> Stack;
1253139f7f9bSDimitry Andric 
1254139f7f9bSDimitry Andric   // Seed the stack with imported modules.
1255f1a29dd3SDimitry Andric   for (Module *M : ImportedModules) {
1256f1a29dd3SDimitry Andric     // Do not add any link flags when an implementation TU of a module imports
1257f1a29dd3SDimitry Andric     // a header of that same module.
1258f1a29dd3SDimitry Andric     if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
1259f1a29dd3SDimitry Andric         !getLangOpts().isCompilingModule())
1260f1a29dd3SDimitry Andric       continue;
12618f0fd8f6SDimitry Andric     if (Visited.insert(M).second)
12628f0fd8f6SDimitry Andric       Stack.push_back(M);
1263f1a29dd3SDimitry Andric   }
1264139f7f9bSDimitry Andric 
1265139f7f9bSDimitry Andric   // Find all of the modules to import, making a little effort to prune
1266139f7f9bSDimitry Andric   // non-leaf modules.
1267139f7f9bSDimitry Andric   while (!Stack.empty()) {
1268f785676fSDimitry Andric     clang::Module *Mod = Stack.pop_back_val();
1269139f7f9bSDimitry Andric 
1270139f7f9bSDimitry Andric     bool AnyChildren = false;
1271139f7f9bSDimitry Andric 
1272139f7f9bSDimitry Andric     // Visit the submodules of this module.
1273139f7f9bSDimitry Andric     for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1274139f7f9bSDimitry Andric                                         SubEnd = Mod->submodule_end();
1275139f7f9bSDimitry Andric          Sub != SubEnd; ++Sub) {
1276139f7f9bSDimitry Andric       // Skip explicit children; they need to be explicitly imported to be
1277139f7f9bSDimitry Andric       // linked against.
1278139f7f9bSDimitry Andric       if ((*Sub)->IsExplicit)
1279139f7f9bSDimitry Andric         continue;
1280139f7f9bSDimitry Andric 
128139d628a0SDimitry Andric       if (Visited.insert(*Sub).second) {
1282139f7f9bSDimitry Andric         Stack.push_back(*Sub);
1283139f7f9bSDimitry Andric         AnyChildren = true;
1284139f7f9bSDimitry Andric       }
1285139f7f9bSDimitry Andric     }
1286139f7f9bSDimitry Andric 
1287139f7f9bSDimitry Andric     // We didn't find any children, so add this module to the list of
1288139f7f9bSDimitry Andric     // modules to link against.
1289139f7f9bSDimitry Andric     if (!AnyChildren) {
1290139f7f9bSDimitry Andric       LinkModules.insert(Mod);
1291139f7f9bSDimitry Andric     }
1292139f7f9bSDimitry Andric   }
1293139f7f9bSDimitry Andric 
1294139f7f9bSDimitry Andric   // Add link options for all of the imported modules in reverse topological
1295f785676fSDimitry Andric   // order.  We don't do anything to try to order import link flags with respect
1296f785676fSDimitry Andric   // to linker options inserted by things like #pragma comment().
129739d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 16> MetadataArgs;
1298139f7f9bSDimitry Andric   Visited.clear();
12998f0fd8f6SDimitry Andric   for (Module *M : LinkModules)
13008f0fd8f6SDimitry Andric     if (Visited.insert(M).second)
13018f0fd8f6SDimitry Andric       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
1302139f7f9bSDimitry Andric   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1303f785676fSDimitry Andric   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1304139f7f9bSDimitry Andric 
1305139f7f9bSDimitry Andric   // Add the linker options metadata flag.
1306139f7f9bSDimitry Andric   getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
1307f785676fSDimitry Andric                             llvm::MDNode::get(getLLVMContext(),
1308f785676fSDimitry Andric                                               LinkerOptionsMetadata));
1309139f7f9bSDimitry Andric }
1310139f7f9bSDimitry Andric 
1311f22ef01cSRoman Divacky void CodeGenModule::EmitDeferred() {
1312f22ef01cSRoman Divacky   // Emit code for any potentially referenced deferred decls.  Since a
1313f22ef01cSRoman Divacky   // previously unused static decl may become used during the generation of code
1314f22ef01cSRoman Divacky   // for a static function, iterate until no changes are made.
1315f22ef01cSRoman Divacky 
1316f22ef01cSRoman Divacky   if (!DeferredVTables.empty()) {
1317139f7f9bSDimitry Andric     EmitDeferredVTables();
1318139f7f9bSDimitry Andric 
1319e7145dcbSDimitry Andric     // Emitting a vtable doesn't directly cause more vtables to
1320139f7f9bSDimitry Andric     // become deferred, although it can cause functions to be
1321e7145dcbSDimitry Andric     // emitted that then need those vtables.
1322139f7f9bSDimitry Andric     assert(DeferredVTables.empty());
1323f22ef01cSRoman Divacky   }
1324f22ef01cSRoman Divacky 
1325e7145dcbSDimitry Andric   // Stop if we're out of both deferred vtables and deferred declarations.
132633956c43SDimitry Andric   if (DeferredDeclsToEmit.empty())
132733956c43SDimitry Andric     return;
1328139f7f9bSDimitry Andric 
132933956c43SDimitry Andric   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
133033956c43SDimitry Andric   // work, it will not interfere with this.
133133956c43SDimitry Andric   std::vector<DeferredGlobal> CurDeclsToEmit;
133233956c43SDimitry Andric   CurDeclsToEmit.swap(DeferredDeclsToEmit);
133333956c43SDimitry Andric 
133433956c43SDimitry Andric   for (DeferredGlobal &G : CurDeclsToEmit) {
133559d1ed5bSDimitry Andric     GlobalDecl D = G.GD;
133633956c43SDimitry Andric     G.GV = nullptr;
1337f22ef01cSRoman Divacky 
13380623d748SDimitry Andric     // We should call GetAddrOfGlobal with IsForDefinition set to true in order
13390623d748SDimitry Andric     // to get GlobalValue with exactly the type we need, not something that
13400623d748SDimitry Andric     // might had been created for another decl with the same mangled name but
13410623d748SDimitry Andric     // different type.
1342e7145dcbSDimitry Andric     llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
134344290647SDimitry Andric         GetAddrOfGlobal(D, ForDefinition));
1344e7145dcbSDimitry Andric 
1345e7145dcbSDimitry Andric     // In case of different address spaces, we may still get a cast, even with
1346e7145dcbSDimitry Andric     // IsForDefinition equal to true. Query mangled names table to get
1347e7145dcbSDimitry Andric     // GlobalValue.
134839d628a0SDimitry Andric     if (!GV)
134939d628a0SDimitry Andric       GV = GetGlobalValue(getMangledName(D));
135039d628a0SDimitry Andric 
1351e7145dcbSDimitry Andric     // Make sure GetGlobalValue returned non-null.
1352e7145dcbSDimitry Andric     assert(GV);
1353e7145dcbSDimitry Andric 
1354f22ef01cSRoman Divacky     // Check to see if we've already emitted this.  This is necessary
1355f22ef01cSRoman Divacky     // for a couple of reasons: first, decls can end up in the
1356f22ef01cSRoman Divacky     // deferred-decls queue multiple times, and second, decls can end
1357f22ef01cSRoman Divacky     // up with definitions in unusual ways (e.g. by an extern inline
1358f22ef01cSRoman Divacky     // function acquiring a strong function redefinition).  Just
1359f22ef01cSRoman Divacky     // ignore these cases.
1360e7145dcbSDimitry Andric     if (!GV->isDeclaration())
1361f22ef01cSRoman Divacky       continue;
1362f22ef01cSRoman Divacky 
1363f22ef01cSRoman Divacky     // Otherwise, emit the definition and move on to the next one.
136459d1ed5bSDimitry Andric     EmitGlobalDefinition(D, GV);
136533956c43SDimitry Andric 
136633956c43SDimitry Andric     // If we found out that we need to emit more decls, do that recursively.
136733956c43SDimitry Andric     // This has the advantage that the decls are emitted in a DFS and related
136833956c43SDimitry Andric     // ones are close together, which is convenient for testing.
136933956c43SDimitry Andric     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
137033956c43SDimitry Andric       EmitDeferred();
137133956c43SDimitry Andric       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
137233956c43SDimitry Andric     }
1373f22ef01cSRoman Divacky   }
1374f22ef01cSRoman Divacky }
1375f22ef01cSRoman Divacky 
13766122f3e6SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() {
13776122f3e6SDimitry Andric   if (Annotations.empty())
13786122f3e6SDimitry Andric     return;
13796122f3e6SDimitry Andric 
13806122f3e6SDimitry Andric   // Create a new global variable for the ConstantStruct in the Module.
13816122f3e6SDimitry Andric   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
13826122f3e6SDimitry Andric     Annotations[0]->getType(), Annotations.size()), Annotations);
138359d1ed5bSDimitry Andric   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
138459d1ed5bSDimitry Andric                                       llvm::GlobalValue::AppendingLinkage,
138559d1ed5bSDimitry Andric                                       Array, "llvm.global.annotations");
13866122f3e6SDimitry Andric   gv->setSection(AnnotationSection);
13876122f3e6SDimitry Andric }
13886122f3e6SDimitry Andric 
1389139f7f9bSDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1390f785676fSDimitry Andric   llvm::Constant *&AStr = AnnotationStrings[Str];
1391f785676fSDimitry Andric   if (AStr)
1392f785676fSDimitry Andric     return AStr;
13936122f3e6SDimitry Andric 
13946122f3e6SDimitry Andric   // Not found yet, create a new global.
1395dff0c46cSDimitry Andric   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
139659d1ed5bSDimitry Andric   auto *gv =
139759d1ed5bSDimitry Andric       new llvm::GlobalVariable(getModule(), s->getType(), true,
139859d1ed5bSDimitry Andric                                llvm::GlobalValue::PrivateLinkage, s, ".str");
13996122f3e6SDimitry Andric   gv->setSection(AnnotationSection);
1400e7145dcbSDimitry Andric   gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1401f785676fSDimitry Andric   AStr = gv;
14026122f3e6SDimitry Andric   return gv;
14036122f3e6SDimitry Andric }
14046122f3e6SDimitry Andric 
14056122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
14066122f3e6SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
14076122f3e6SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
14086122f3e6SDimitry Andric   if (PLoc.isValid())
14096122f3e6SDimitry Andric     return EmitAnnotationString(PLoc.getFilename());
14106122f3e6SDimitry Andric   return EmitAnnotationString(SM.getBufferName(Loc));
14116122f3e6SDimitry Andric }
14126122f3e6SDimitry Andric 
14136122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
14146122f3e6SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
14156122f3e6SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(L);
14166122f3e6SDimitry Andric   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
14176122f3e6SDimitry Andric     SM.getExpansionLineNumber(L);
14186122f3e6SDimitry Andric   return llvm::ConstantInt::get(Int32Ty, LineNo);
14196122f3e6SDimitry Andric }
14206122f3e6SDimitry Andric 
1421f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1422f22ef01cSRoman Divacky                                                 const AnnotateAttr *AA,
14236122f3e6SDimitry Andric                                                 SourceLocation L) {
14246122f3e6SDimitry Andric   // Get the globals for file name, annotation, and the line number.
14256122f3e6SDimitry Andric   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
14266122f3e6SDimitry Andric                  *UnitGV = EmitAnnotationUnit(L),
14276122f3e6SDimitry Andric                  *LineNoCst = EmitAnnotationLineNo(L);
1428f22ef01cSRoman Divacky 
1429f22ef01cSRoman Divacky   // Create the ConstantStruct for the global annotation.
1430f22ef01cSRoman Divacky   llvm::Constant *Fields[4] = {
14316122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
14326122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
14336122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
14346122f3e6SDimitry Andric     LineNoCst
1435f22ef01cSRoman Divacky   };
143617a519f9SDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
1437f22ef01cSRoman Divacky }
1438f22ef01cSRoman Divacky 
14396122f3e6SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
14406122f3e6SDimitry Andric                                          llvm::GlobalValue *GV) {
14416122f3e6SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
14426122f3e6SDimitry Andric   // Get the struct elements for these annotations.
144359d1ed5bSDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>())
144459d1ed5bSDimitry Andric     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
14456122f3e6SDimitry Andric }
14466122f3e6SDimitry Andric 
144739d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
144839d628a0SDimitry Andric                                            SourceLocation Loc) const {
144939d628a0SDimitry Andric   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
145039d628a0SDimitry Andric   // Blacklist by function name.
145139d628a0SDimitry Andric   if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
145239d628a0SDimitry Andric     return true;
145339d628a0SDimitry Andric   // Blacklist by location.
14540623d748SDimitry Andric   if (Loc.isValid())
145539d628a0SDimitry Andric     return SanitizerBL.isBlacklistedLocation(Loc);
145639d628a0SDimitry Andric   // If location is unknown, this may be a compiler-generated function. Assume
145739d628a0SDimitry Andric   // it's located in the main file.
145839d628a0SDimitry Andric   auto &SM = Context.getSourceManager();
145939d628a0SDimitry Andric   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
146039d628a0SDimitry Andric     return SanitizerBL.isBlacklistedFile(MainFile->getName());
146139d628a0SDimitry Andric   }
146239d628a0SDimitry Andric   return false;
146339d628a0SDimitry Andric }
146439d628a0SDimitry Andric 
146539d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
146639d628a0SDimitry Andric                                            SourceLocation Loc, QualType Ty,
146739d628a0SDimitry Andric                                            StringRef Category) const {
14688f0fd8f6SDimitry Andric   // For now globals can be blacklisted only in ASan and KASan.
14698f0fd8f6SDimitry Andric   if (!LangOpts.Sanitize.hasOneOf(
14708f0fd8f6SDimitry Andric           SanitizerKind::Address | SanitizerKind::KernelAddress))
147139d628a0SDimitry Andric     return false;
147239d628a0SDimitry Andric   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
147339d628a0SDimitry Andric   if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
147439d628a0SDimitry Andric     return true;
147539d628a0SDimitry Andric   if (SanitizerBL.isBlacklistedLocation(Loc, Category))
147639d628a0SDimitry Andric     return true;
147739d628a0SDimitry Andric   // Check global type.
147839d628a0SDimitry Andric   if (!Ty.isNull()) {
147939d628a0SDimitry Andric     // Drill down the array types: if global variable of a fixed type is
148039d628a0SDimitry Andric     // blacklisted, we also don't instrument arrays of them.
148139d628a0SDimitry Andric     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
148239d628a0SDimitry Andric       Ty = AT->getElementType();
148339d628a0SDimitry Andric     Ty = Ty.getCanonicalType().getUnqualifiedType();
148439d628a0SDimitry Andric     // We allow to blacklist only record types (classes, structs etc.)
148539d628a0SDimitry Andric     if (Ty->isRecordType()) {
148639d628a0SDimitry Andric       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
148739d628a0SDimitry Andric       if (SanitizerBL.isBlacklistedType(TypeStr, Category))
148839d628a0SDimitry Andric         return true;
148939d628a0SDimitry Andric     }
149039d628a0SDimitry Andric   }
149139d628a0SDimitry Andric   return false;
149239d628a0SDimitry Andric }
149339d628a0SDimitry Andric 
149420e90f04SDimitry Andric bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
149520e90f04SDimitry Andric                                    StringRef Category) const {
149620e90f04SDimitry Andric   if (!LangOpts.XRayInstrument)
149720e90f04SDimitry Andric     return false;
149820e90f04SDimitry Andric   const auto &XRayFilter = getContext().getXRayFilter();
149920e90f04SDimitry Andric   using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
150020e90f04SDimitry Andric   auto Attr = XRayFunctionFilter::ImbueAttribute::NONE;
150120e90f04SDimitry Andric   if (Loc.isValid())
150220e90f04SDimitry Andric     Attr = XRayFilter.shouldImbueLocation(Loc, Category);
150320e90f04SDimitry Andric   if (Attr == ImbueAttr::NONE)
150420e90f04SDimitry Andric     Attr = XRayFilter.shouldImbueFunction(Fn->getName());
150520e90f04SDimitry Andric   switch (Attr) {
150620e90f04SDimitry Andric   case ImbueAttr::NONE:
150720e90f04SDimitry Andric     return false;
150820e90f04SDimitry Andric   case ImbueAttr::ALWAYS:
150920e90f04SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-always");
151020e90f04SDimitry Andric     break;
151120e90f04SDimitry Andric   case ImbueAttr::NEVER:
151220e90f04SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-never");
151320e90f04SDimitry Andric     break;
151420e90f04SDimitry Andric   }
151520e90f04SDimitry Andric   return true;
151620e90f04SDimitry Andric }
151720e90f04SDimitry Andric 
151839d628a0SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
1519e580952dSDimitry Andric   // Never defer when EmitAllDecls is specified.
1520dff0c46cSDimitry Andric   if (LangOpts.EmitAllDecls)
152139d628a0SDimitry Andric     return true;
152239d628a0SDimitry Andric 
152339d628a0SDimitry Andric   return getContext().DeclMustBeEmitted(Global);
152439d628a0SDimitry Andric }
152539d628a0SDimitry Andric 
152639d628a0SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
152739d628a0SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global))
152839d628a0SDimitry Andric     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
152939d628a0SDimitry Andric       // Implicit template instantiations may change linkage if they are later
153039d628a0SDimitry Andric       // explicitly instantiated, so they should not be emitted eagerly.
1531f22ef01cSRoman Divacky       return false;
1532e7145dcbSDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(Global))
1533e7145dcbSDimitry Andric     if (Context.getInlineVariableDefinitionKind(VD) ==
1534e7145dcbSDimitry Andric         ASTContext::InlineVariableDefinitionKind::WeakUnknown)
1535e7145dcbSDimitry Andric       // A definition of an inline constexpr static data member may change
1536e7145dcbSDimitry Andric       // linkage later if it's redeclared outside the class.
1537e7145dcbSDimitry Andric       return false;
1538875ed548SDimitry Andric   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
1539875ed548SDimitry Andric   // codegen for global variables, because they may be marked as threadprivate.
1540875ed548SDimitry Andric   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1541875ed548SDimitry Andric       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
1542875ed548SDimitry Andric     return false;
1543f22ef01cSRoman Divacky 
154439d628a0SDimitry Andric   return true;
1545f22ef01cSRoman Divacky }
1546f22ef01cSRoman Divacky 
15470623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
15483861d79fSDimitry Andric     const CXXUuidofExpr* E) {
15493861d79fSDimitry Andric   // Sema has verified that IIDSource has a __declspec(uuid()), and that its
15503861d79fSDimitry Andric   // well-formed.
1551e7145dcbSDimitry Andric   StringRef Uuid = E->getUuidStr();
1552f785676fSDimitry Andric   std::string Name = "_GUID_" + Uuid.lower();
1553f785676fSDimitry Andric   std::replace(Name.begin(), Name.end(), '-', '_');
15543861d79fSDimitry Andric 
1555e7145dcbSDimitry Andric   // The UUID descriptor should be pointer aligned.
1556e7145dcbSDimitry Andric   CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
15570623d748SDimitry Andric 
15583861d79fSDimitry Andric   // Look for an existing global.
15593861d79fSDimitry Andric   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
15600623d748SDimitry Andric     return ConstantAddress(GV, Alignment);
15613861d79fSDimitry Andric 
156239d628a0SDimitry Andric   llvm::Constant *Init = EmitUuidofInitializer(Uuid);
15633861d79fSDimitry Andric   assert(Init && "failed to initialize as constant");
15643861d79fSDimitry Andric 
156559d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
1566f785676fSDimitry Andric       getModule(), Init->getType(),
1567f785676fSDimitry Andric       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
156833956c43SDimitry Andric   if (supportsCOMDAT())
156933956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
15700623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
15713861d79fSDimitry Andric }
15723861d79fSDimitry Andric 
15730623d748SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1574f22ef01cSRoman Divacky   const AliasAttr *AA = VD->getAttr<AliasAttr>();
1575f22ef01cSRoman Divacky   assert(AA && "No alias?");
1576f22ef01cSRoman Divacky 
15770623d748SDimitry Andric   CharUnits Alignment = getContext().getDeclAlign(VD);
15786122f3e6SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1579f22ef01cSRoman Divacky 
1580f22ef01cSRoman Divacky   // See if there is already something with the target's name in the module.
1581f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
15823861d79fSDimitry Andric   if (Entry) {
15833861d79fSDimitry Andric     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
15840623d748SDimitry Andric     auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
15850623d748SDimitry Andric     return ConstantAddress(Ptr, Alignment);
15863861d79fSDimitry Andric   }
1587f22ef01cSRoman Divacky 
1588f22ef01cSRoman Divacky   llvm::Constant *Aliasee;
1589f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(DeclTy))
15903861d79fSDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
15913861d79fSDimitry Andric                                       GlobalDecl(cast<FunctionDecl>(VD)),
15922754fe60SDimitry Andric                                       /*ForVTable=*/false);
1593f22ef01cSRoman Divacky   else
1594f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
159559d1ed5bSDimitry Andric                                     llvm::PointerType::getUnqual(DeclTy),
159659d1ed5bSDimitry Andric                                     nullptr);
15973861d79fSDimitry Andric 
159859d1ed5bSDimitry Andric   auto *F = cast<llvm::GlobalValue>(Aliasee);
1599f22ef01cSRoman Divacky   F->setLinkage(llvm::Function::ExternalWeakLinkage);
1600f22ef01cSRoman Divacky   WeakRefReferences.insert(F);
1601f22ef01cSRoman Divacky 
16020623d748SDimitry Andric   return ConstantAddress(Aliasee, Alignment);
1603f22ef01cSRoman Divacky }
1604f22ef01cSRoman Divacky 
1605f22ef01cSRoman Divacky void CodeGenModule::EmitGlobal(GlobalDecl GD) {
160659d1ed5bSDimitry Andric   const auto *Global = cast<ValueDecl>(GD.getDecl());
1607f22ef01cSRoman Divacky 
1608f22ef01cSRoman Divacky   // Weak references don't produce any output by themselves.
1609f22ef01cSRoman Divacky   if (Global->hasAttr<WeakRefAttr>())
1610f22ef01cSRoman Divacky     return;
1611f22ef01cSRoman Divacky 
1612f22ef01cSRoman Divacky   // If this is an alias definition (which otherwise looks like a declaration)
1613f22ef01cSRoman Divacky   // emit it now.
1614f22ef01cSRoman Divacky   if (Global->hasAttr<AliasAttr>())
1615f22ef01cSRoman Divacky     return EmitAliasDefinition(GD);
1616f22ef01cSRoman Divacky 
1617e7145dcbSDimitry Andric   // IFunc like an alias whose value is resolved at runtime by calling resolver.
1618e7145dcbSDimitry Andric   if (Global->hasAttr<IFuncAttr>())
1619e7145dcbSDimitry Andric     return emitIFuncDefinition(GD);
1620e7145dcbSDimitry Andric 
16216122f3e6SDimitry Andric   // If this is CUDA, be selective about which declarations we emit.
1622dff0c46cSDimitry Andric   if (LangOpts.CUDA) {
162333956c43SDimitry Andric     if (LangOpts.CUDAIsDevice) {
16246122f3e6SDimitry Andric       if (!Global->hasAttr<CUDADeviceAttr>() &&
16256122f3e6SDimitry Andric           !Global->hasAttr<CUDAGlobalAttr>() &&
16266122f3e6SDimitry Andric           !Global->hasAttr<CUDAConstantAttr>() &&
16276122f3e6SDimitry Andric           !Global->hasAttr<CUDASharedAttr>())
16286122f3e6SDimitry Andric         return;
16296122f3e6SDimitry Andric     } else {
1630e7145dcbSDimitry Andric       // We need to emit host-side 'shadows' for all global
1631e7145dcbSDimitry Andric       // device-side variables because the CUDA runtime needs their
1632e7145dcbSDimitry Andric       // size and host-side address in order to provide access to
1633e7145dcbSDimitry Andric       // their device-side incarnations.
1634e7145dcbSDimitry Andric 
1635e7145dcbSDimitry Andric       // So device-only functions are the only things we skip.
1636e7145dcbSDimitry Andric       if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
1637e7145dcbSDimitry Andric           Global->hasAttr<CUDADeviceAttr>())
16386122f3e6SDimitry Andric         return;
1639e7145dcbSDimitry Andric 
1640e7145dcbSDimitry Andric       assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
1641e7145dcbSDimitry Andric              "Expected Variable or Function");
1642e580952dSDimitry Andric     }
1643e580952dSDimitry Andric   }
1644e580952dSDimitry Andric 
1645e7145dcbSDimitry Andric   if (LangOpts.OpenMP) {
1646ea942507SDimitry Andric     // If this is OpenMP device, check if it is legal to emit this global
1647ea942507SDimitry Andric     // normally.
1648ea942507SDimitry Andric     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
1649ea942507SDimitry Andric       return;
1650e7145dcbSDimitry Andric     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
1651e7145dcbSDimitry Andric       if (MustBeEmitted(Global))
1652e7145dcbSDimitry Andric         EmitOMPDeclareReduction(DRD);
1653e7145dcbSDimitry Andric       return;
1654e7145dcbSDimitry Andric     }
1655e7145dcbSDimitry Andric   }
1656ea942507SDimitry Andric 
16576122f3e6SDimitry Andric   // Ignore declarations, they will be emitted on their first use.
165859d1ed5bSDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
1659f22ef01cSRoman Divacky     // Forward declarations are emitted lazily on first use.
16606122f3e6SDimitry Andric     if (!FD->doesThisDeclarationHaveABody()) {
16616122f3e6SDimitry Andric       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1662f22ef01cSRoman Divacky         return;
16636122f3e6SDimitry Andric 
16646122f3e6SDimitry Andric       StringRef MangledName = getMangledName(GD);
166559d1ed5bSDimitry Andric 
166659d1ed5bSDimitry Andric       // Compute the function info and LLVM type.
166759d1ed5bSDimitry Andric       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
166859d1ed5bSDimitry Andric       llvm::Type *Ty = getTypes().GetFunctionType(FI);
166959d1ed5bSDimitry Andric 
167059d1ed5bSDimitry Andric       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
167159d1ed5bSDimitry Andric                               /*DontDefer=*/false);
16726122f3e6SDimitry Andric       return;
16736122f3e6SDimitry Andric     }
1674f22ef01cSRoman Divacky   } else {
167559d1ed5bSDimitry Andric     const auto *VD = cast<VarDecl>(Global);
1676f22ef01cSRoman Divacky     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1677e7145dcbSDimitry Andric     // We need to emit device-side global CUDA variables even if a
1678e7145dcbSDimitry Andric     // variable does not have a definition -- we still need to define
1679e7145dcbSDimitry Andric     // host-side shadow for it.
1680e7145dcbSDimitry Andric     bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
1681e7145dcbSDimitry Andric                            !VD->hasDefinition() &&
1682e7145dcbSDimitry Andric                            (VD->hasAttr<CUDAConstantAttr>() ||
1683e7145dcbSDimitry Andric                             VD->hasAttr<CUDADeviceAttr>());
1684e7145dcbSDimitry Andric     if (!MustEmitForCuda &&
1685e7145dcbSDimitry Andric         VD->isThisDeclarationADefinition() != VarDecl::Definition &&
1686e7145dcbSDimitry Andric         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
1687e7145dcbSDimitry Andric       // If this declaration may have caused an inline variable definition to
1688e7145dcbSDimitry Andric       // change linkage, make sure that it's emitted.
1689e7145dcbSDimitry Andric       if (Context.getInlineVariableDefinitionKind(VD) ==
1690e7145dcbSDimitry Andric           ASTContext::InlineVariableDefinitionKind::Strong)
1691e7145dcbSDimitry Andric         GetAddrOfGlobalVar(VD);
1692f22ef01cSRoman Divacky       return;
1693f22ef01cSRoman Divacky     }
1694e7145dcbSDimitry Andric   }
1695f22ef01cSRoman Divacky 
169639d628a0SDimitry Andric   // Defer code generation to first use when possible, e.g. if this is an inline
169739d628a0SDimitry Andric   // function. If the global must always be emitted, do it eagerly if possible
169839d628a0SDimitry Andric   // to benefit from cache locality.
169939d628a0SDimitry Andric   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
1700f22ef01cSRoman Divacky     // Emit the definition if it can't be deferred.
1701f22ef01cSRoman Divacky     EmitGlobalDefinition(GD);
1702f22ef01cSRoman Divacky     return;
1703f22ef01cSRoman Divacky   }
1704f22ef01cSRoman Divacky 
1705e580952dSDimitry Andric   // If we're deferring emission of a C++ variable with an
1706e580952dSDimitry Andric   // initializer, remember the order in which it appeared in the file.
1707dff0c46cSDimitry Andric   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1708e580952dSDimitry Andric       cast<VarDecl>(Global)->hasInit()) {
1709e580952dSDimitry Andric     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
171059d1ed5bSDimitry Andric     CXXGlobalInits.push_back(nullptr);
1711e580952dSDimitry Andric   }
1712e580952dSDimitry Andric 
17136122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
171439d628a0SDimitry Andric   if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) {
171539d628a0SDimitry Andric     // The value has already been used and should therefore be emitted.
171659d1ed5bSDimitry Andric     addDeferredDeclToEmit(GV, GD);
171739d628a0SDimitry Andric   } else if (MustBeEmitted(Global)) {
171839d628a0SDimitry Andric     // The value must be emitted, but cannot be emitted eagerly.
171939d628a0SDimitry Andric     assert(!MayBeEmittedEagerly(Global));
172039d628a0SDimitry Andric     addDeferredDeclToEmit(/*GV=*/nullptr, GD);
172139d628a0SDimitry Andric   } else {
1722f22ef01cSRoman Divacky     // Otherwise, remember that we saw a deferred decl with this name.  The
1723f22ef01cSRoman Divacky     // first use of the mangled name will cause it to move into
1724f22ef01cSRoman Divacky     // DeferredDeclsToEmit.
1725f22ef01cSRoman Divacky     DeferredDecls[MangledName] = GD;
1726f22ef01cSRoman Divacky   }
1727f22ef01cSRoman Divacky }
1728f22ef01cSRoman Divacky 
172920e90f04SDimitry Andric // Check if T is a class type with a destructor that's not dllimport.
173020e90f04SDimitry Andric static bool HasNonDllImportDtor(QualType T) {
173120e90f04SDimitry Andric   if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
173220e90f04SDimitry Andric     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
173320e90f04SDimitry Andric       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
173420e90f04SDimitry Andric         return true;
173520e90f04SDimitry Andric 
173620e90f04SDimitry Andric   return false;
173720e90f04SDimitry Andric }
173820e90f04SDimitry Andric 
1739f8254f43SDimitry Andric namespace {
1740f8254f43SDimitry Andric   struct FunctionIsDirectlyRecursive :
1741f8254f43SDimitry Andric     public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1742f8254f43SDimitry Andric     const StringRef Name;
1743dff0c46cSDimitry Andric     const Builtin::Context &BI;
1744f8254f43SDimitry Andric     bool Result;
1745dff0c46cSDimitry Andric     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1746dff0c46cSDimitry Andric       Name(N), BI(C), Result(false) {
1747f8254f43SDimitry Andric     }
1748f8254f43SDimitry Andric     typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1749f8254f43SDimitry Andric 
1750f8254f43SDimitry Andric     bool TraverseCallExpr(CallExpr *E) {
1751dff0c46cSDimitry Andric       const FunctionDecl *FD = E->getDirectCallee();
1752dff0c46cSDimitry Andric       if (!FD)
1753f8254f43SDimitry Andric         return true;
1754dff0c46cSDimitry Andric       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1755dff0c46cSDimitry Andric       if (Attr && Name == Attr->getLabel()) {
1756dff0c46cSDimitry Andric         Result = true;
1757dff0c46cSDimitry Andric         return false;
1758dff0c46cSDimitry Andric       }
1759dff0c46cSDimitry Andric       unsigned BuiltinID = FD->getBuiltinID();
17603dac3a9bSDimitry Andric       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
1761f8254f43SDimitry Andric         return true;
17620623d748SDimitry Andric       StringRef BuiltinName = BI.getName(BuiltinID);
1763dff0c46cSDimitry Andric       if (BuiltinName.startswith("__builtin_") &&
1764dff0c46cSDimitry Andric           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1765f8254f43SDimitry Andric         Result = true;
1766f8254f43SDimitry Andric         return false;
1767f8254f43SDimitry Andric       }
1768f8254f43SDimitry Andric       return true;
1769f8254f43SDimitry Andric     }
1770f8254f43SDimitry Andric   };
17710623d748SDimitry Andric 
177220e90f04SDimitry Andric   // Make sure we're not referencing non-imported vars or functions.
17730623d748SDimitry Andric   struct DLLImportFunctionVisitor
17740623d748SDimitry Andric       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
17750623d748SDimitry Andric     bool SafeToInline = true;
17760623d748SDimitry Andric 
177744290647SDimitry Andric     bool shouldVisitImplicitCode() const { return true; }
177844290647SDimitry Andric 
17790623d748SDimitry Andric     bool VisitVarDecl(VarDecl *VD) {
178020e90f04SDimitry Andric       if (VD->getTLSKind()) {
17810623d748SDimitry Andric         // A thread-local variable cannot be imported.
178220e90f04SDimitry Andric         SafeToInline = false;
17830623d748SDimitry Andric         return SafeToInline;
17840623d748SDimitry Andric       }
17850623d748SDimitry Andric 
178620e90f04SDimitry Andric       // A variable definition might imply a destructor call.
178720e90f04SDimitry Andric       if (VD->isThisDeclarationADefinition())
178820e90f04SDimitry Andric         SafeToInline = !HasNonDllImportDtor(VD->getType());
178920e90f04SDimitry Andric 
179020e90f04SDimitry Andric       return SafeToInline;
179120e90f04SDimitry Andric     }
179220e90f04SDimitry Andric 
179320e90f04SDimitry Andric     bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
179420e90f04SDimitry Andric       if (const auto *D = E->getTemporary()->getDestructor())
179520e90f04SDimitry Andric         SafeToInline = D->hasAttr<DLLImportAttr>();
179620e90f04SDimitry Andric       return SafeToInline;
179720e90f04SDimitry Andric     }
179820e90f04SDimitry Andric 
17990623d748SDimitry Andric     bool VisitDeclRefExpr(DeclRefExpr *E) {
18000623d748SDimitry Andric       ValueDecl *VD = E->getDecl();
18010623d748SDimitry Andric       if (isa<FunctionDecl>(VD))
18020623d748SDimitry Andric         SafeToInline = VD->hasAttr<DLLImportAttr>();
18030623d748SDimitry Andric       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
18040623d748SDimitry Andric         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
18050623d748SDimitry Andric       return SafeToInline;
18060623d748SDimitry Andric     }
180720e90f04SDimitry Andric 
180844290647SDimitry Andric     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
180944290647SDimitry Andric       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
181044290647SDimitry Andric       return SafeToInline;
181144290647SDimitry Andric     }
181220e90f04SDimitry Andric 
181320e90f04SDimitry Andric     bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
181420e90f04SDimitry Andric       CXXMethodDecl *M = E->getMethodDecl();
181520e90f04SDimitry Andric       if (!M) {
181620e90f04SDimitry Andric         // Call through a pointer to member function. This is safe to inline.
181720e90f04SDimitry Andric         SafeToInline = true;
181820e90f04SDimitry Andric       } else {
181920e90f04SDimitry Andric         SafeToInline = M->hasAttr<DLLImportAttr>();
182020e90f04SDimitry Andric       }
182120e90f04SDimitry Andric       return SafeToInline;
182220e90f04SDimitry Andric     }
182320e90f04SDimitry Andric 
18240623d748SDimitry Andric     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
18250623d748SDimitry Andric       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
18260623d748SDimitry Andric       return SafeToInline;
18270623d748SDimitry Andric     }
182820e90f04SDimitry Andric 
18290623d748SDimitry Andric     bool VisitCXXNewExpr(CXXNewExpr *E) {
18300623d748SDimitry Andric       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
18310623d748SDimitry Andric       return SafeToInline;
18320623d748SDimitry Andric     }
18330623d748SDimitry Andric   };
1834f8254f43SDimitry Andric }
1835f8254f43SDimitry Andric 
1836dff0c46cSDimitry Andric // isTriviallyRecursive - Check if this function calls another
1837dff0c46cSDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin,
1838dff0c46cSDimitry Andric // ends up pointing to itself.
1839f8254f43SDimitry Andric bool
1840dff0c46cSDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1841dff0c46cSDimitry Andric   StringRef Name;
1842dff0c46cSDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1843dff0c46cSDimitry Andric     // asm labels are a special kind of mangling we have to support.
1844dff0c46cSDimitry Andric     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1845dff0c46cSDimitry Andric     if (!Attr)
1846f8254f43SDimitry Andric       return false;
1847dff0c46cSDimitry Andric     Name = Attr->getLabel();
1848dff0c46cSDimitry Andric   } else {
1849dff0c46cSDimitry Andric     Name = FD->getName();
1850dff0c46cSDimitry Andric   }
1851f8254f43SDimitry Andric 
1852dff0c46cSDimitry Andric   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1853dff0c46cSDimitry Andric   Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1854f8254f43SDimitry Andric   return Walker.Result;
1855f8254f43SDimitry Andric }
1856f8254f43SDimitry Andric 
185744290647SDimitry Andric bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1858f785676fSDimitry Andric   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1859f8254f43SDimitry Andric     return true;
186059d1ed5bSDimitry Andric   const auto *F = cast<FunctionDecl>(GD.getDecl());
186159d1ed5bSDimitry Andric   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1862f8254f43SDimitry Andric     return false;
18630623d748SDimitry Andric 
18640623d748SDimitry Andric   if (F->hasAttr<DLLImportAttr>()) {
18650623d748SDimitry Andric     // Check whether it would be safe to inline this dllimport function.
18660623d748SDimitry Andric     DLLImportFunctionVisitor Visitor;
18670623d748SDimitry Andric     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
18680623d748SDimitry Andric     if (!Visitor.SafeToInline)
18690623d748SDimitry Andric       return false;
187044290647SDimitry Andric 
187144290647SDimitry Andric     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
187244290647SDimitry Andric       // Implicit destructor invocations aren't captured in the AST, so the
187344290647SDimitry Andric       // check above can't see them. Check for them manually here.
187444290647SDimitry Andric       for (const Decl *Member : Dtor->getParent()->decls())
187544290647SDimitry Andric         if (isa<FieldDecl>(Member))
187644290647SDimitry Andric           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
187744290647SDimitry Andric             return false;
187844290647SDimitry Andric       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
187944290647SDimitry Andric         if (HasNonDllImportDtor(B.getType()))
188044290647SDimitry Andric           return false;
188144290647SDimitry Andric     }
18820623d748SDimitry Andric   }
18830623d748SDimitry Andric 
1884f8254f43SDimitry Andric   // PR9614. Avoid cases where the source code is lying to us. An available
1885f8254f43SDimitry Andric   // externally function should have an equivalent function somewhere else,
1886f8254f43SDimitry Andric   // but a function that calls itself is clearly not equivalent to the real
1887f8254f43SDimitry Andric   // implementation.
1888f8254f43SDimitry Andric   // This happens in glibc's btowc and in some configure checks.
1889dff0c46cSDimitry Andric   return !isTriviallyRecursive(F);
1890f8254f43SDimitry Andric }
1891f8254f43SDimitry Andric 
189259d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
189359d1ed5bSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
1894f22ef01cSRoman Divacky 
1895f22ef01cSRoman Divacky   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1896f22ef01cSRoman Divacky                                  Context.getSourceManager(),
1897f22ef01cSRoman Divacky                                  "Generating code for declaration");
1898f22ef01cSRoman Divacky 
1899f785676fSDimitry Andric   if (isa<FunctionDecl>(D)) {
1900ffd1746dSEd Schouten     // At -O0, don't generate IR for functions with available_externally
1901ffd1746dSEd Schouten     // linkage.
1902f785676fSDimitry Andric     if (!shouldEmitFunction(GD))
1903ffd1746dSEd Schouten       return;
1904ffd1746dSEd Schouten 
190559d1ed5bSDimitry Andric     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
1906bd5abe19SDimitry Andric       // Make sure to emit the definition(s) before we emit the thunks.
1907bd5abe19SDimitry Andric       // This is necessary for the generation of certain thunks.
190859d1ed5bSDimitry Andric       if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
190939d628a0SDimitry Andric         ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
191059d1ed5bSDimitry Andric       else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
191139d628a0SDimitry Andric         ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
1912bd5abe19SDimitry Andric       else
191359d1ed5bSDimitry Andric         EmitGlobalFunctionDefinition(GD, GV);
1914bd5abe19SDimitry Andric 
1915f22ef01cSRoman Divacky       if (Method->isVirtual())
1916f22ef01cSRoman Divacky         getVTables().EmitThunks(GD);
1917f22ef01cSRoman Divacky 
1918bd5abe19SDimitry Andric       return;
1919ffd1746dSEd Schouten     }
1920f22ef01cSRoman Divacky 
192159d1ed5bSDimitry Andric     return EmitGlobalFunctionDefinition(GD, GV);
1922ffd1746dSEd Schouten   }
1923f22ef01cSRoman Divacky 
192459d1ed5bSDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
1925e7145dcbSDimitry Andric     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
1926f22ef01cSRoman Divacky 
19276122f3e6SDimitry Andric   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1928f22ef01cSRoman Divacky }
1929f22ef01cSRoman Divacky 
19300623d748SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
19310623d748SDimitry Andric                                                       llvm::Function *NewFn);
19320623d748SDimitry Andric 
1933f22ef01cSRoman Divacky /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1934f22ef01cSRoman Divacky /// module, create and return an llvm Function with the specified type. If there
1935f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially
1936f22ef01cSRoman Divacky /// bitcasted to the right type.
1937f22ef01cSRoman Divacky ///
1938f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this.  This is used
1939f22ef01cSRoman Divacky /// to set the attributes on the function when it is first created.
194020e90f04SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
194120e90f04SDimitry Andric     StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
194220e90f04SDimitry Andric     bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
194344290647SDimitry Andric     ForDefinition_t IsForDefinition) {
1944f785676fSDimitry Andric   const Decl *D = GD.getDecl();
1945f785676fSDimitry Andric 
1946f22ef01cSRoman Divacky   // Lookup the entry, lazily creating it if necessary.
1947f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1948f22ef01cSRoman Divacky   if (Entry) {
19493861d79fSDimitry Andric     if (WeakRefReferences.erase(Entry)) {
1950f785676fSDimitry Andric       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
1951f22ef01cSRoman Divacky       if (FD && !FD->hasAttr<WeakAttr>())
1952f22ef01cSRoman Divacky         Entry->setLinkage(llvm::Function::ExternalLinkage);
1953f22ef01cSRoman Divacky     }
1954f22ef01cSRoman Divacky 
195539d628a0SDimitry Andric     // Handle dropped DLL attributes.
195639d628a0SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
195739d628a0SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
195839d628a0SDimitry Andric 
19590623d748SDimitry Andric     // If there are two attempts to define the same mangled name, issue an
19600623d748SDimitry Andric     // error.
19610623d748SDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
19620623d748SDimitry Andric       GlobalDecl OtherGD;
1963e7145dcbSDimitry Andric       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
1964e7145dcbSDimitry Andric       // to make sure that we issue an error only once.
19650623d748SDimitry Andric       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
19660623d748SDimitry Andric           (GD.getCanonicalDecl().getDecl() !=
19670623d748SDimitry Andric            OtherGD.getCanonicalDecl().getDecl()) &&
19680623d748SDimitry Andric           DiagnosedConflictingDefinitions.insert(GD).second) {
19690623d748SDimitry Andric         getDiags().Report(D->getLocation(),
19700623d748SDimitry Andric                           diag::err_duplicate_mangled_name);
19710623d748SDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
19720623d748SDimitry Andric                           diag::note_previous_definition);
19730623d748SDimitry Andric       }
19740623d748SDimitry Andric     }
19750623d748SDimitry Andric 
19760623d748SDimitry Andric     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
19770623d748SDimitry Andric         (Entry->getType()->getElementType() == Ty)) {
1978f22ef01cSRoman Divacky       return Entry;
19790623d748SDimitry Andric     }
1980f22ef01cSRoman Divacky 
1981f22ef01cSRoman Divacky     // Make sure the result is of the correct type.
19820623d748SDimitry Andric     // (If function is requested for a definition, we always need to create a new
19830623d748SDimitry Andric     // function, not just return a bitcast.)
19840623d748SDimitry Andric     if (!IsForDefinition)
198517a519f9SDimitry Andric       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1986f22ef01cSRoman Divacky   }
1987f22ef01cSRoman Divacky 
1988f22ef01cSRoman Divacky   // This function doesn't have a complete type (for example, the return
1989f22ef01cSRoman Divacky   // type is an incomplete struct). Use a fake type instead, and make
1990f22ef01cSRoman Divacky   // sure not to try to set attributes.
1991f22ef01cSRoman Divacky   bool IsIncompleteFunction = false;
1992f22ef01cSRoman Divacky 
19936122f3e6SDimitry Andric   llvm::FunctionType *FTy;
1994f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(Ty)) {
1995f22ef01cSRoman Divacky     FTy = cast<llvm::FunctionType>(Ty);
1996f22ef01cSRoman Divacky   } else {
1997bd5abe19SDimitry Andric     FTy = llvm::FunctionType::get(VoidTy, false);
1998f22ef01cSRoman Divacky     IsIncompleteFunction = true;
1999f22ef01cSRoman Divacky   }
2000ffd1746dSEd Schouten 
20010623d748SDimitry Andric   llvm::Function *F =
20020623d748SDimitry Andric       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
20030623d748SDimitry Andric                              Entry ? StringRef() : MangledName, &getModule());
20040623d748SDimitry Andric 
20050623d748SDimitry Andric   // If we already created a function with the same mangled name (but different
20060623d748SDimitry Andric   // type) before, take its name and add it to the list of functions to be
20070623d748SDimitry Andric   // replaced with F at the end of CodeGen.
20080623d748SDimitry Andric   //
20090623d748SDimitry Andric   // This happens if there is a prototype for a function (e.g. "int f()") and
20100623d748SDimitry Andric   // then a definition of a different type (e.g. "int f(int x)").
20110623d748SDimitry Andric   if (Entry) {
20120623d748SDimitry Andric     F->takeName(Entry);
20130623d748SDimitry Andric 
20140623d748SDimitry Andric     // This might be an implementation of a function without a prototype, in
20150623d748SDimitry Andric     // which case, try to do special replacement of calls which match the new
20160623d748SDimitry Andric     // prototype.  The really key thing here is that we also potentially drop
20170623d748SDimitry Andric     // arguments from the call site so as to make a direct call, which makes the
20180623d748SDimitry Andric     // inliner happier and suppresses a number of optimizer warnings (!) about
20190623d748SDimitry Andric     // dropping arguments.
20200623d748SDimitry Andric     if (!Entry->use_empty()) {
20210623d748SDimitry Andric       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
20220623d748SDimitry Andric       Entry->removeDeadConstantUsers();
20230623d748SDimitry Andric     }
20240623d748SDimitry Andric 
20250623d748SDimitry Andric     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
20260623d748SDimitry Andric         F, Entry->getType()->getElementType()->getPointerTo());
20270623d748SDimitry Andric     addGlobalValReplacement(Entry, BC);
20280623d748SDimitry Andric   }
20290623d748SDimitry Andric 
2030f22ef01cSRoman Divacky   assert(F->getName() == MangledName && "name was uniqued!");
2031f785676fSDimitry Andric   if (D)
203239d628a0SDimitry Andric     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
203320e90f04SDimitry Andric   if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
203420e90f04SDimitry Andric     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
203520e90f04SDimitry Andric     F->addAttributes(llvm::AttributeList::FunctionIndex,
203620e90f04SDimitry Andric                      llvm::AttributeList::get(
203720e90f04SDimitry Andric                          VMContext, llvm::AttributeList::FunctionIndex, B));
2038139f7f9bSDimitry Andric   }
2039f22ef01cSRoman Divacky 
204059d1ed5bSDimitry Andric   if (!DontDefer) {
204159d1ed5bSDimitry Andric     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
204259d1ed5bSDimitry Andric     // each other bottoming out with the base dtor.  Therefore we emit non-base
204359d1ed5bSDimitry Andric     // dtors on usage, even if there is no dtor definition in the TU.
204459d1ed5bSDimitry Andric     if (D && isa<CXXDestructorDecl>(D) &&
204559d1ed5bSDimitry Andric         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
204659d1ed5bSDimitry Andric                                            GD.getDtorType()))
204759d1ed5bSDimitry Andric       addDeferredDeclToEmit(F, GD);
204859d1ed5bSDimitry Andric 
2049f22ef01cSRoman Divacky     // This is the first use or definition of a mangled name.  If there is a
2050f22ef01cSRoman Divacky     // deferred decl with this name, remember that we need to emit it at the end
2051f22ef01cSRoman Divacky     // of the file.
205259d1ed5bSDimitry Andric     auto DDI = DeferredDecls.find(MangledName);
2053f22ef01cSRoman Divacky     if (DDI != DeferredDecls.end()) {
205459d1ed5bSDimitry Andric       // Move the potentially referenced deferred decl to the
205559d1ed5bSDimitry Andric       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
205659d1ed5bSDimitry Andric       // don't need it anymore).
205759d1ed5bSDimitry Andric       addDeferredDeclToEmit(F, DDI->second);
2058f22ef01cSRoman Divacky       DeferredDecls.erase(DDI);
20592754fe60SDimitry Andric 
20602754fe60SDimitry Andric       // Otherwise, there are cases we have to worry about where we're
20612754fe60SDimitry Andric       // using a declaration for which we must emit a definition but where
20622754fe60SDimitry Andric       // we might not find a top-level definition:
20632754fe60SDimitry Andric       //   - member functions defined inline in their classes
20642754fe60SDimitry Andric       //   - friend functions defined inline in some class
20652754fe60SDimitry Andric       //   - special member functions with implicit definitions
20662754fe60SDimitry Andric       // If we ever change our AST traversal to walk into class methods,
20672754fe60SDimitry Andric       // this will be unnecessary.
20682754fe60SDimitry Andric       //
206959d1ed5bSDimitry Andric       // We also don't emit a definition for a function if it's going to be an
207039d628a0SDimitry Andric       // entry in a vtable, unless it's already marked as used.
2071f785676fSDimitry Andric     } else if (getLangOpts().CPlusPlus && D) {
20722754fe60SDimitry Andric       // Look for a declaration that's lexically in a record.
207339d628a0SDimitry Andric       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
207439d628a0SDimitry Andric            FD = FD->getPreviousDecl()) {
20752754fe60SDimitry Andric         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
207639d628a0SDimitry Andric           if (FD->doesThisDeclarationHaveABody()) {
207759d1ed5bSDimitry Andric             addDeferredDeclToEmit(F, GD.getWithDecl(FD));
20782754fe60SDimitry Andric             break;
2079f22ef01cSRoman Divacky           }
2080f22ef01cSRoman Divacky         }
208139d628a0SDimitry Andric       }
2082f22ef01cSRoman Divacky     }
208359d1ed5bSDimitry Andric   }
2084f22ef01cSRoman Divacky 
2085f22ef01cSRoman Divacky   // Make sure the result is of the requested type.
2086f22ef01cSRoman Divacky   if (!IsIncompleteFunction) {
2087f22ef01cSRoman Divacky     assert(F->getType()->getElementType() == Ty);
2088f22ef01cSRoman Divacky     return F;
2089f22ef01cSRoman Divacky   }
2090f22ef01cSRoman Divacky 
209117a519f9SDimitry Andric   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2092f22ef01cSRoman Divacky   return llvm::ConstantExpr::getBitCast(F, PTy);
2093f22ef01cSRoman Divacky }
2094f22ef01cSRoman Divacky 
2095f22ef01cSRoman Divacky /// GetAddrOfFunction - Return the address of the given function.  If Ty is
2096f22ef01cSRoman Divacky /// non-null, then this function will use the specified type if it has to
2097f22ef01cSRoman Divacky /// create it (this occurs when we see a definition of the function).
2098f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
20996122f3e6SDimitry Andric                                                  llvm::Type *Ty,
210059d1ed5bSDimitry Andric                                                  bool ForVTable,
21010623d748SDimitry Andric                                                  bool DontDefer,
210244290647SDimitry Andric                                               ForDefinition_t IsForDefinition) {
2103f22ef01cSRoman Divacky   // If there was no specific requested type, just convert it now.
21040623d748SDimitry Andric   if (!Ty) {
21050623d748SDimitry Andric     const auto *FD = cast<FunctionDecl>(GD.getDecl());
21060623d748SDimitry Andric     auto CanonTy = Context.getCanonicalType(FD->getType());
21070623d748SDimitry Andric     Ty = getTypes().ConvertFunctionType(CanonTy, FD);
21080623d748SDimitry Andric   }
2109ffd1746dSEd Schouten 
21106122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
21110623d748SDimitry Andric   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
211220e90f04SDimitry Andric                                  /*IsThunk=*/false, llvm::AttributeList(),
21130623d748SDimitry Andric                                  IsForDefinition);
2114f22ef01cSRoman Divacky }
2115f22ef01cSRoman Divacky 
211644290647SDimitry Andric static const FunctionDecl *
211744290647SDimitry Andric GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
211844290647SDimitry Andric   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
211944290647SDimitry Andric   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
212044290647SDimitry Andric 
212144290647SDimitry Andric   IdentifierInfo &CII = C.Idents.get(Name);
212244290647SDimitry Andric   for (const auto &Result : DC->lookup(&CII))
212344290647SDimitry Andric     if (const auto FD = dyn_cast<FunctionDecl>(Result))
212444290647SDimitry Andric       return FD;
212544290647SDimitry Andric 
212644290647SDimitry Andric   if (!C.getLangOpts().CPlusPlus)
212744290647SDimitry Andric     return nullptr;
212844290647SDimitry Andric 
212944290647SDimitry Andric   // Demangle the premangled name from getTerminateFn()
213044290647SDimitry Andric   IdentifierInfo &CXXII =
213144290647SDimitry Andric       (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ")
213244290647SDimitry Andric           ? C.Idents.get("terminate")
213344290647SDimitry Andric           : C.Idents.get(Name);
213444290647SDimitry Andric 
213544290647SDimitry Andric   for (const auto &N : {"__cxxabiv1", "std"}) {
213644290647SDimitry Andric     IdentifierInfo &NS = C.Idents.get(N);
213744290647SDimitry Andric     for (const auto &Result : DC->lookup(&NS)) {
213844290647SDimitry Andric       NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
213944290647SDimitry Andric       if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
214044290647SDimitry Andric         for (const auto &Result : LSD->lookup(&NS))
214144290647SDimitry Andric           if ((ND = dyn_cast<NamespaceDecl>(Result)))
214244290647SDimitry Andric             break;
214344290647SDimitry Andric 
214444290647SDimitry Andric       if (ND)
214544290647SDimitry Andric         for (const auto &Result : ND->lookup(&CXXII))
214644290647SDimitry Andric           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
214744290647SDimitry Andric             return FD;
214844290647SDimitry Andric     }
214944290647SDimitry Andric   }
215044290647SDimitry Andric 
215144290647SDimitry Andric   return nullptr;
215244290647SDimitry Andric }
215344290647SDimitry Andric 
2154f22ef01cSRoman Divacky /// CreateRuntimeFunction - Create a new runtime function with the specified
2155f22ef01cSRoman Divacky /// type and name.
2156f22ef01cSRoman Divacky llvm::Constant *
215744290647SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
215820e90f04SDimitry Andric                                      llvm::AttributeList ExtraAttrs,
215944290647SDimitry Andric                                      bool Local) {
216059d1ed5bSDimitry Andric   llvm::Constant *C =
216159d1ed5bSDimitry Andric       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
216244290647SDimitry Andric                               /*DontDefer=*/false, /*IsThunk=*/false,
216344290647SDimitry Andric                               ExtraAttrs);
216444290647SDimitry Andric 
216544290647SDimitry Andric   if (auto *F = dyn_cast<llvm::Function>(C)) {
216644290647SDimitry Andric     if (F->empty()) {
2167139f7f9bSDimitry Andric       F->setCallingConv(getRuntimeCC());
216844290647SDimitry Andric 
216944290647SDimitry Andric       if (!Local && getTriple().isOSBinFormatCOFF() &&
217044290647SDimitry Andric           !getCodeGenOpts().LTOVisibilityPublicStd) {
217144290647SDimitry Andric         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
217244290647SDimitry Andric         if (!FD || FD->hasAttr<DLLImportAttr>()) {
217344290647SDimitry Andric           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
217444290647SDimitry Andric           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
217544290647SDimitry Andric         }
217644290647SDimitry Andric       }
217744290647SDimitry Andric     }
217844290647SDimitry Andric   }
217944290647SDimitry Andric 
2180139f7f9bSDimitry Andric   return C;
2181f22ef01cSRoman Divacky }
2182f22ef01cSRoman Divacky 
218339d628a0SDimitry Andric /// CreateBuiltinFunction - Create a new builtin function with the specified
218439d628a0SDimitry Andric /// type and name.
218539d628a0SDimitry Andric llvm::Constant *
218620e90f04SDimitry Andric CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
218720e90f04SDimitry Andric                                      llvm::AttributeList ExtraAttrs) {
218839d628a0SDimitry Andric   llvm::Constant *C =
218939d628a0SDimitry Andric       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
219039d628a0SDimitry Andric                               /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
219139d628a0SDimitry Andric   if (auto *F = dyn_cast<llvm::Function>(C))
219239d628a0SDimitry Andric     if (F->empty())
219339d628a0SDimitry Andric       F->setCallingConv(getBuiltinCC());
219439d628a0SDimitry Andric   return C;
219539d628a0SDimitry Andric }
219639d628a0SDimitry Andric 
2197dff0c46cSDimitry Andric /// isTypeConstant - Determine whether an object of this type can be emitted
2198dff0c46cSDimitry Andric /// as a constant.
2199dff0c46cSDimitry Andric ///
2200dff0c46cSDimitry Andric /// If ExcludeCtor is true, the duration when the object's constructor runs
2201dff0c46cSDimitry Andric /// will not be considered. The caller will need to verify that the object is
2202dff0c46cSDimitry Andric /// not written to during its construction.
2203dff0c46cSDimitry Andric bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2204dff0c46cSDimitry Andric   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
2205f22ef01cSRoman Divacky     return false;
2206bd5abe19SDimitry Andric 
2207dff0c46cSDimitry Andric   if (Context.getLangOpts().CPlusPlus) {
2208dff0c46cSDimitry Andric     if (const CXXRecordDecl *Record
2209dff0c46cSDimitry Andric           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2210dff0c46cSDimitry Andric       return ExcludeCtor && !Record->hasMutableFields() &&
2211dff0c46cSDimitry Andric              Record->hasTrivialDestructor();
2212f22ef01cSRoman Divacky   }
2213bd5abe19SDimitry Andric 
2214f22ef01cSRoman Divacky   return true;
2215f22ef01cSRoman Divacky }
2216f22ef01cSRoman Divacky 
2217f22ef01cSRoman Divacky /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2218f22ef01cSRoman Divacky /// create and return an llvm GlobalVariable with the specified type.  If there
2219f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially
2220f22ef01cSRoman Divacky /// bitcasted to the right type.
2221f22ef01cSRoman Divacky ///
2222f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this.  This is used
2223f22ef01cSRoman Divacky /// to set the attributes on the global when it is first created.
2224e7145dcbSDimitry Andric ///
2225e7145dcbSDimitry Andric /// If IsForDefinition is true, it is guranteed that an actual global with
2226e7145dcbSDimitry Andric /// type Ty will be returned, not conversion of a variable with the same
2227e7145dcbSDimitry Andric /// mangled name but some other type.
2228f22ef01cSRoman Divacky llvm::Constant *
22296122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
22306122f3e6SDimitry Andric                                      llvm::PointerType *Ty,
2231e7145dcbSDimitry Andric                                      const VarDecl *D,
223244290647SDimitry Andric                                      ForDefinition_t IsForDefinition) {
2233f22ef01cSRoman Divacky   // Lookup the entry, lazily creating it if necessary.
2234f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2235f22ef01cSRoman Divacky   if (Entry) {
22363861d79fSDimitry Andric     if (WeakRefReferences.erase(Entry)) {
2237f22ef01cSRoman Divacky       if (D && !D->hasAttr<WeakAttr>())
2238f22ef01cSRoman Divacky         Entry->setLinkage(llvm::Function::ExternalLinkage);
2239f22ef01cSRoman Divacky     }
2240f22ef01cSRoman Divacky 
224139d628a0SDimitry Andric     // Handle dropped DLL attributes.
224239d628a0SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
224339d628a0SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
224439d628a0SDimitry Andric 
2245f22ef01cSRoman Divacky     if (Entry->getType() == Ty)
2246f22ef01cSRoman Divacky       return Entry;
2247f22ef01cSRoman Divacky 
2248e7145dcbSDimitry Andric     // If there are two attempts to define the same mangled name, issue an
2249e7145dcbSDimitry Andric     // error.
2250e7145dcbSDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
2251e7145dcbSDimitry Andric       GlobalDecl OtherGD;
2252e7145dcbSDimitry Andric       const VarDecl *OtherD;
2253e7145dcbSDimitry Andric 
2254e7145dcbSDimitry Andric       // Check that D is not yet in DiagnosedConflictingDefinitions is required
2255e7145dcbSDimitry Andric       // to make sure that we issue an error only once.
2256e7145dcbSDimitry Andric       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
2257e7145dcbSDimitry Andric           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2258e7145dcbSDimitry Andric           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2259e7145dcbSDimitry Andric           OtherD->hasInit() &&
2260e7145dcbSDimitry Andric           DiagnosedConflictingDefinitions.insert(D).second) {
2261e7145dcbSDimitry Andric         getDiags().Report(D->getLocation(),
2262e7145dcbSDimitry Andric                           diag::err_duplicate_mangled_name);
2263e7145dcbSDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
2264e7145dcbSDimitry Andric                           diag::note_previous_definition);
2265e7145dcbSDimitry Andric       }
2266e7145dcbSDimitry Andric     }
2267e7145dcbSDimitry Andric 
2268f22ef01cSRoman Divacky     // Make sure the result is of the correct type.
2269f785676fSDimitry Andric     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2270f785676fSDimitry Andric       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2271f785676fSDimitry Andric 
2272e7145dcbSDimitry Andric     // (If global is requested for a definition, we always need to create a new
2273e7145dcbSDimitry Andric     // global, not just return a bitcast.)
2274e7145dcbSDimitry Andric     if (!IsForDefinition)
2275f22ef01cSRoman Divacky       return llvm::ConstantExpr::getBitCast(Entry, Ty);
2276f22ef01cSRoman Divacky   }
2277f22ef01cSRoman Divacky 
227859d1ed5bSDimitry Andric   unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
227959d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
228059d1ed5bSDimitry Andric       getModule(), Ty->getElementType(), false,
228159d1ed5bSDimitry Andric       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
228259d1ed5bSDimitry Andric       llvm::GlobalVariable::NotThreadLocal, AddrSpace);
228359d1ed5bSDimitry Andric 
2284e7145dcbSDimitry Andric   // If we already created a global with the same mangled name (but different
2285e7145dcbSDimitry Andric   // type) before, take its name and remove it from its parent.
2286e7145dcbSDimitry Andric   if (Entry) {
2287e7145dcbSDimitry Andric     GV->takeName(Entry);
2288e7145dcbSDimitry Andric 
2289e7145dcbSDimitry Andric     if (!Entry->use_empty()) {
2290e7145dcbSDimitry Andric       llvm::Constant *NewPtrForOldDecl =
2291e7145dcbSDimitry Andric           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2292e7145dcbSDimitry Andric       Entry->replaceAllUsesWith(NewPtrForOldDecl);
2293e7145dcbSDimitry Andric     }
2294e7145dcbSDimitry Andric 
2295e7145dcbSDimitry Andric     Entry->eraseFromParent();
2296e7145dcbSDimitry Andric   }
2297e7145dcbSDimitry Andric 
2298f22ef01cSRoman Divacky   // This is the first use or definition of a mangled name.  If there is a
2299f22ef01cSRoman Divacky   // deferred decl with this name, remember that we need to emit it at the end
2300f22ef01cSRoman Divacky   // of the file.
230159d1ed5bSDimitry Andric   auto DDI = DeferredDecls.find(MangledName);
2302f22ef01cSRoman Divacky   if (DDI != DeferredDecls.end()) {
2303f22ef01cSRoman Divacky     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2304f22ef01cSRoman Divacky     // list, and remove it from DeferredDecls (since we don't need it anymore).
230559d1ed5bSDimitry Andric     addDeferredDeclToEmit(GV, DDI->second);
2306f22ef01cSRoman Divacky     DeferredDecls.erase(DDI);
2307f22ef01cSRoman Divacky   }
2308f22ef01cSRoman Divacky 
2309f22ef01cSRoman Divacky   // Handle things which are present even on external declarations.
2310f22ef01cSRoman Divacky   if (D) {
2311f22ef01cSRoman Divacky     // FIXME: This code is overly simple and should be merged with other global
2312f22ef01cSRoman Divacky     // handling.
2313dff0c46cSDimitry Andric     GV->setConstant(isTypeConstant(D->getType(), false));
2314f22ef01cSRoman Divacky 
231533956c43SDimitry Andric     GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
231633956c43SDimitry Andric 
231759d1ed5bSDimitry Andric     setLinkageAndVisibilityForGV(GV, D);
23182754fe60SDimitry Andric 
2319284c1978SDimitry Andric     if (D->getTLSKind()) {
2320284c1978SDimitry Andric       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
23210623d748SDimitry Andric         CXXThreadLocals.push_back(D);
23227ae0e2c9SDimitry Andric       setTLSMode(GV, *D);
2323f22ef01cSRoman Divacky     }
2324f785676fSDimitry Andric 
2325f785676fSDimitry Andric     // If required by the ABI, treat declarations of static data members with
2326f785676fSDimitry Andric     // inline initializers as definitions.
232759d1ed5bSDimitry Andric     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
2328f785676fSDimitry Andric       EmitGlobalVarDefinition(D);
2329284c1978SDimitry Andric     }
2330f22ef01cSRoman Divacky 
233159d1ed5bSDimitry Andric     // Handle XCore specific ABI requirements.
233244290647SDimitry Andric     if (getTriple().getArch() == llvm::Triple::xcore &&
233359d1ed5bSDimitry Andric         D->getLanguageLinkage() == CLanguageLinkage &&
233459d1ed5bSDimitry Andric         D->getType().isConstant(Context) &&
233559d1ed5bSDimitry Andric         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
233659d1ed5bSDimitry Andric       GV->setSection(".cp.rodata");
233759d1ed5bSDimitry Andric   }
233859d1ed5bSDimitry Andric 
23397ae0e2c9SDimitry Andric   if (AddrSpace != Ty->getAddressSpace())
2340f785676fSDimitry Andric     return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
2341f785676fSDimitry Andric 
2342f22ef01cSRoman Divacky   return GV;
2343f22ef01cSRoman Divacky }
2344f22ef01cSRoman Divacky 
23450623d748SDimitry Andric llvm::Constant *
23460623d748SDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
234744290647SDimitry Andric                                ForDefinition_t IsForDefinition) {
234844290647SDimitry Andric   const Decl *D = GD.getDecl();
234944290647SDimitry Andric   if (isa<CXXConstructorDecl>(D))
235044290647SDimitry Andric     return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
23510623d748SDimitry Andric                                 getFromCtorType(GD.getCtorType()),
23520623d748SDimitry Andric                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
23530623d748SDimitry Andric                                 /*DontDefer=*/false, IsForDefinition);
235444290647SDimitry Andric   else if (isa<CXXDestructorDecl>(D))
235544290647SDimitry Andric     return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
23560623d748SDimitry Andric                                 getFromDtorType(GD.getDtorType()),
23570623d748SDimitry Andric                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
23580623d748SDimitry Andric                                 /*DontDefer=*/false, IsForDefinition);
235944290647SDimitry Andric   else if (isa<CXXMethodDecl>(D)) {
23600623d748SDimitry Andric     auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
236144290647SDimitry Andric         cast<CXXMethodDecl>(D));
23620623d748SDimitry Andric     auto Ty = getTypes().GetFunctionType(*FInfo);
23630623d748SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
23640623d748SDimitry Andric                              IsForDefinition);
236544290647SDimitry Andric   } else if (isa<FunctionDecl>(D)) {
23660623d748SDimitry Andric     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
23670623d748SDimitry Andric     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
23680623d748SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
23690623d748SDimitry Andric                              IsForDefinition);
23700623d748SDimitry Andric   } else
237144290647SDimitry Andric     return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
2372e7145dcbSDimitry Andric                               IsForDefinition);
23730623d748SDimitry Andric }
2374f22ef01cSRoman Divacky 
23752754fe60SDimitry Andric llvm::GlobalVariable *
23766122f3e6SDimitry Andric CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
23776122f3e6SDimitry Andric                                       llvm::Type *Ty,
23782754fe60SDimitry Andric                                       llvm::GlobalValue::LinkageTypes Linkage) {
23792754fe60SDimitry Andric   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
238059d1ed5bSDimitry Andric   llvm::GlobalVariable *OldGV = nullptr;
23812754fe60SDimitry Andric 
23822754fe60SDimitry Andric   if (GV) {
23832754fe60SDimitry Andric     // Check if the variable has the right type.
23842754fe60SDimitry Andric     if (GV->getType()->getElementType() == Ty)
23852754fe60SDimitry Andric       return GV;
23862754fe60SDimitry Andric 
23872754fe60SDimitry Andric     // Because C++ name mangling, the only way we can end up with an already
23882754fe60SDimitry Andric     // existing global with the same name is if it has been declared extern "C".
23892754fe60SDimitry Andric     assert(GV->isDeclaration() && "Declaration has wrong type!");
23902754fe60SDimitry Andric     OldGV = GV;
23912754fe60SDimitry Andric   }
23922754fe60SDimitry Andric 
23932754fe60SDimitry Andric   // Create a new variable.
23942754fe60SDimitry Andric   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
239559d1ed5bSDimitry Andric                                 Linkage, nullptr, Name);
23962754fe60SDimitry Andric 
23972754fe60SDimitry Andric   if (OldGV) {
23982754fe60SDimitry Andric     // Replace occurrences of the old variable if needed.
23992754fe60SDimitry Andric     GV->takeName(OldGV);
24002754fe60SDimitry Andric 
24012754fe60SDimitry Andric     if (!OldGV->use_empty()) {
24022754fe60SDimitry Andric       llvm::Constant *NewPtrForOldDecl =
24032754fe60SDimitry Andric       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
24042754fe60SDimitry Andric       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
24052754fe60SDimitry Andric     }
24062754fe60SDimitry Andric 
24072754fe60SDimitry Andric     OldGV->eraseFromParent();
24082754fe60SDimitry Andric   }
24092754fe60SDimitry Andric 
241033956c43SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker() &&
241133956c43SDimitry Andric       !GV->hasAvailableExternallyLinkage())
241233956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
241333956c43SDimitry Andric 
24142754fe60SDimitry Andric   return GV;
24152754fe60SDimitry Andric }
24162754fe60SDimitry Andric 
2417f22ef01cSRoman Divacky /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
2418f22ef01cSRoman Divacky /// given global variable.  If Ty is non-null and if the global doesn't exist,
2419cb4dff85SDimitry Andric /// then it will be created with the specified type instead of whatever the
2420e7145dcbSDimitry Andric /// normal requested type would be. If IsForDefinition is true, it is guranteed
2421e7145dcbSDimitry Andric /// that an actual global with type Ty will be returned, not conversion of a
2422e7145dcbSDimitry Andric /// variable with the same mangled name but some other type.
2423f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
2424e7145dcbSDimitry Andric                                                   llvm::Type *Ty,
242544290647SDimitry Andric                                            ForDefinition_t IsForDefinition) {
2426f22ef01cSRoman Divacky   assert(D->hasGlobalStorage() && "Not a global variable");
2427f22ef01cSRoman Divacky   QualType ASTTy = D->getType();
242859d1ed5bSDimitry Andric   if (!Ty)
2429f22ef01cSRoman Divacky     Ty = getTypes().ConvertTypeForMem(ASTTy);
2430f22ef01cSRoman Divacky 
24316122f3e6SDimitry Andric   llvm::PointerType *PTy =
24323b0f4066SDimitry Andric     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
2433f22ef01cSRoman Divacky 
24346122f3e6SDimitry Andric   StringRef MangledName = getMangledName(D);
2435e7145dcbSDimitry Andric   return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
2436f22ef01cSRoman Divacky }
2437f22ef01cSRoman Divacky 
2438f22ef01cSRoman Divacky /// CreateRuntimeVariable - Create a new runtime global variable with the
2439f22ef01cSRoman Divacky /// specified type and name.
2440f22ef01cSRoman Divacky llvm::Constant *
24416122f3e6SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
24426122f3e6SDimitry Andric                                      StringRef Name) {
244359d1ed5bSDimitry Andric   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
2444f22ef01cSRoman Divacky }
2445f22ef01cSRoman Divacky 
2446f22ef01cSRoman Divacky void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
2447f22ef01cSRoman Divacky   assert(!D->getInit() && "Cannot emit definite definitions here!");
2448f22ef01cSRoman Divacky 
24496122f3e6SDimitry Andric   StringRef MangledName = getMangledName(D);
2450e7145dcbSDimitry Andric   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
2451e7145dcbSDimitry Andric 
2452e7145dcbSDimitry Andric   // We already have a definition, not declaration, with the same mangled name.
2453e7145dcbSDimitry Andric   // Emitting of declaration is not required (and actually overwrites emitted
2454e7145dcbSDimitry Andric   // definition).
2455e7145dcbSDimitry Andric   if (GV && !GV->isDeclaration())
2456e7145dcbSDimitry Andric     return;
2457e7145dcbSDimitry Andric 
2458e7145dcbSDimitry Andric   // If we have not seen a reference to this variable yet, place it into the
2459e7145dcbSDimitry Andric   // deferred declarations table to be emitted if needed later.
2460e7145dcbSDimitry Andric   if (!MustBeEmitted(D) && !GV) {
2461f22ef01cSRoman Divacky       DeferredDecls[MangledName] = D;
2462f22ef01cSRoman Divacky       return;
2463f22ef01cSRoman Divacky   }
2464f22ef01cSRoman Divacky 
2465f22ef01cSRoman Divacky   // The tentative definition is the only definition.
2466f22ef01cSRoman Divacky   EmitGlobalVarDefinition(D);
2467f22ef01cSRoman Divacky }
2468f22ef01cSRoman Divacky 
24696122f3e6SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
24702754fe60SDimitry Andric   return Context.toCharUnitsFromBits(
24710623d748SDimitry Andric       getDataLayout().getTypeStoreSizeInBits(Ty));
2472f22ef01cSRoman Divacky }
2473f22ef01cSRoman Divacky 
24747ae0e2c9SDimitry Andric unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
24757ae0e2c9SDimitry Andric                                                  unsigned AddrSpace) {
2476e7145dcbSDimitry Andric   if (D && LangOpts.CUDA && LangOpts.CUDAIsDevice) {
24777ae0e2c9SDimitry Andric     if (D->hasAttr<CUDAConstantAttr>())
24787ae0e2c9SDimitry Andric       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
24797ae0e2c9SDimitry Andric     else if (D->hasAttr<CUDASharedAttr>())
24807ae0e2c9SDimitry Andric       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
24817ae0e2c9SDimitry Andric     else
24827ae0e2c9SDimitry Andric       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
24837ae0e2c9SDimitry Andric   }
24847ae0e2c9SDimitry Andric 
24857ae0e2c9SDimitry Andric   return AddrSpace;
24867ae0e2c9SDimitry Andric }
24877ae0e2c9SDimitry Andric 
2488284c1978SDimitry Andric template<typename SomeDecl>
2489284c1978SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
2490284c1978SDimitry Andric                                                llvm::GlobalValue *GV) {
2491284c1978SDimitry Andric   if (!getLangOpts().CPlusPlus)
2492284c1978SDimitry Andric     return;
2493284c1978SDimitry Andric 
2494284c1978SDimitry Andric   // Must have 'used' attribute, or else inline assembly can't rely on
2495284c1978SDimitry Andric   // the name existing.
2496284c1978SDimitry Andric   if (!D->template hasAttr<UsedAttr>())
2497284c1978SDimitry Andric     return;
2498284c1978SDimitry Andric 
2499284c1978SDimitry Andric   // Must have internal linkage and an ordinary name.
2500f785676fSDimitry Andric   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
2501284c1978SDimitry Andric     return;
2502284c1978SDimitry Andric 
2503284c1978SDimitry Andric   // Must be in an extern "C" context. Entities declared directly within
2504284c1978SDimitry Andric   // a record are not extern "C" even if the record is in such a context.
2505f785676fSDimitry Andric   const SomeDecl *First = D->getFirstDecl();
2506284c1978SDimitry Andric   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
2507284c1978SDimitry Andric     return;
2508284c1978SDimitry Andric 
2509284c1978SDimitry Andric   // OK, this is an internal linkage entity inside an extern "C" linkage
2510284c1978SDimitry Andric   // specification. Make a note of that so we can give it the "expected"
2511284c1978SDimitry Andric   // mangled name if nothing else is using that name.
2512284c1978SDimitry Andric   std::pair<StaticExternCMap::iterator, bool> R =
2513284c1978SDimitry Andric       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
2514284c1978SDimitry Andric 
2515284c1978SDimitry Andric   // If we have multiple internal linkage entities with the same name
2516284c1978SDimitry Andric   // in extern "C" regions, none of them gets that name.
2517284c1978SDimitry Andric   if (!R.second)
251859d1ed5bSDimitry Andric     R.first->second = nullptr;
2519284c1978SDimitry Andric }
2520284c1978SDimitry Andric 
252133956c43SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
252233956c43SDimitry Andric   if (!CGM.supportsCOMDAT())
252333956c43SDimitry Andric     return false;
252433956c43SDimitry Andric 
252533956c43SDimitry Andric   if (D.hasAttr<SelectAnyAttr>())
252633956c43SDimitry Andric     return true;
252733956c43SDimitry Andric 
252833956c43SDimitry Andric   GVALinkage Linkage;
252933956c43SDimitry Andric   if (auto *VD = dyn_cast<VarDecl>(&D))
253033956c43SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
253133956c43SDimitry Andric   else
253233956c43SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
253333956c43SDimitry Andric 
253433956c43SDimitry Andric   switch (Linkage) {
253533956c43SDimitry Andric   case GVA_Internal:
253633956c43SDimitry Andric   case GVA_AvailableExternally:
253733956c43SDimitry Andric   case GVA_StrongExternal:
253833956c43SDimitry Andric     return false;
253933956c43SDimitry Andric   case GVA_DiscardableODR:
254033956c43SDimitry Andric   case GVA_StrongODR:
254133956c43SDimitry Andric     return true;
254233956c43SDimitry Andric   }
254333956c43SDimitry Andric   llvm_unreachable("No such linkage");
254433956c43SDimitry Andric }
254533956c43SDimitry Andric 
254633956c43SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
254733956c43SDimitry Andric                                           llvm::GlobalObject &GO) {
254833956c43SDimitry Andric   if (!shouldBeInCOMDAT(*this, D))
254933956c43SDimitry Andric     return;
255033956c43SDimitry Andric   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
255133956c43SDimitry Andric }
255233956c43SDimitry Andric 
2553e7145dcbSDimitry Andric /// Pass IsTentative as true if you want to create a tentative definition.
2554e7145dcbSDimitry Andric void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
2555e7145dcbSDimitry Andric                                             bool IsTentative) {
255644290647SDimitry Andric   // OpenCL global variables of sampler type are translated to function calls,
255744290647SDimitry Andric   // therefore no need to be translated.
2558f22ef01cSRoman Divacky   QualType ASTTy = D->getType();
255944290647SDimitry Andric   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
256044290647SDimitry Andric     return;
256144290647SDimitry Andric 
256244290647SDimitry Andric   llvm::Constant *Init = nullptr;
2563dff0c46cSDimitry Andric   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2564dff0c46cSDimitry Andric   bool NeedsGlobalCtor = false;
2565dff0c46cSDimitry Andric   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
2566f22ef01cSRoman Divacky 
2567dff0c46cSDimitry Andric   const VarDecl *InitDecl;
2568dff0c46cSDimitry Andric   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
2569f22ef01cSRoman Divacky 
2570e7145dcbSDimitry Andric   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
2571e7145dcbSDimitry Andric   // as part of their declaration."  Sema has already checked for
2572e7145dcbSDimitry Andric   // error cases, so we just need to set Init to UndefValue.
2573e7145dcbSDimitry Andric   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
2574e7145dcbSDimitry Andric       D->hasAttr<CUDASharedAttr>())
25750623d748SDimitry Andric     Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
2576e7145dcbSDimitry Andric   else if (!InitExpr) {
2577f22ef01cSRoman Divacky     // This is a tentative definition; tentative definitions are
2578f22ef01cSRoman Divacky     // implicitly initialized with { 0 }.
2579f22ef01cSRoman Divacky     //
2580f22ef01cSRoman Divacky     // Note that tentative definitions are only emitted at the end of
2581f22ef01cSRoman Divacky     // a translation unit, so they should never have incomplete
2582f22ef01cSRoman Divacky     // type. In addition, EmitTentativeDefinition makes sure that we
2583f22ef01cSRoman Divacky     // never attempt to emit a tentative definition if a real one
2584f22ef01cSRoman Divacky     // exists. A use may still exists, however, so we still may need
2585f22ef01cSRoman Divacky     // to do a RAUW.
2586f22ef01cSRoman Divacky     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
2587f22ef01cSRoman Divacky     Init = EmitNullConstant(D->getType());
2588f22ef01cSRoman Divacky   } else {
25897ae0e2c9SDimitry Andric     initializedGlobalDecl = GlobalDecl(D);
2590dff0c46cSDimitry Andric     Init = EmitConstantInit(*InitDecl);
2591f785676fSDimitry Andric 
2592f22ef01cSRoman Divacky     if (!Init) {
2593f22ef01cSRoman Divacky       QualType T = InitExpr->getType();
2594f22ef01cSRoman Divacky       if (D->getType()->isReferenceType())
2595f22ef01cSRoman Divacky         T = D->getType();
2596f22ef01cSRoman Divacky 
2597dff0c46cSDimitry Andric       if (getLangOpts().CPlusPlus) {
2598f22ef01cSRoman Divacky         Init = EmitNullConstant(T);
2599dff0c46cSDimitry Andric         NeedsGlobalCtor = true;
2600f22ef01cSRoman Divacky       } else {
2601f22ef01cSRoman Divacky         ErrorUnsupported(D, "static initializer");
2602f22ef01cSRoman Divacky         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
2603f22ef01cSRoman Divacky       }
2604e580952dSDimitry Andric     } else {
2605e580952dSDimitry Andric       // We don't need an initializer, so remove the entry for the delayed
2606dff0c46cSDimitry Andric       // initializer position (just in case this entry was delayed) if we
2607dff0c46cSDimitry Andric       // also don't need to register a destructor.
2608dff0c46cSDimitry Andric       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
2609e580952dSDimitry Andric         DelayedCXXInitPosition.erase(D);
2610f22ef01cSRoman Divacky     }
2611f22ef01cSRoman Divacky   }
2612f22ef01cSRoman Divacky 
26136122f3e6SDimitry Andric   llvm::Type* InitType = Init->getType();
2614e7145dcbSDimitry Andric   llvm::Constant *Entry =
261544290647SDimitry Andric       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
2616f22ef01cSRoman Divacky 
2617f22ef01cSRoman Divacky   // Strip off a bitcast if we got one back.
261859d1ed5bSDimitry Andric   if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2619f22ef01cSRoman Divacky     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2620f785676fSDimitry Andric            CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2621f785676fSDimitry Andric            // All zero index gep.
2622f22ef01cSRoman Divacky            CE->getOpcode() == llvm::Instruction::GetElementPtr);
2623f22ef01cSRoman Divacky     Entry = CE->getOperand(0);
2624f22ef01cSRoman Divacky   }
2625f22ef01cSRoman Divacky 
2626f22ef01cSRoman Divacky   // Entry is now either a Function or GlobalVariable.
262759d1ed5bSDimitry Andric   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
2628f22ef01cSRoman Divacky 
2629f22ef01cSRoman Divacky   // We have a definition after a declaration with the wrong type.
2630f22ef01cSRoman Divacky   // We must make a new GlobalVariable* and update everything that used OldGV
2631f22ef01cSRoman Divacky   // (a declaration or tentative definition) with the new GlobalVariable*
2632f22ef01cSRoman Divacky   // (which will be a definition).
2633f22ef01cSRoman Divacky   //
2634f22ef01cSRoman Divacky   // This happens if there is a prototype for a global (e.g.
2635f22ef01cSRoman Divacky   // "extern int x[];") and then a definition of a different type (e.g.
2636f22ef01cSRoman Divacky   // "int x[10];"). This also happens when an initializer has a different type
2637f22ef01cSRoman Divacky   // from the type of the global (this happens with unions).
263859d1ed5bSDimitry Andric   if (!GV ||
2639f22ef01cSRoman Divacky       GV->getType()->getElementType() != InitType ||
26403b0f4066SDimitry Andric       GV->getType()->getAddressSpace() !=
26417ae0e2c9SDimitry Andric        GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
2642f22ef01cSRoman Divacky 
2643f22ef01cSRoman Divacky     // Move the old entry aside so that we'll create a new one.
26446122f3e6SDimitry Andric     Entry->setName(StringRef());
2645f22ef01cSRoman Divacky 
2646f22ef01cSRoman Divacky     // Make a new global with the correct type, this is now guaranteed to work.
2647e7145dcbSDimitry Andric     GV = cast<llvm::GlobalVariable>(
264844290647SDimitry Andric         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
2649f22ef01cSRoman Divacky 
2650f22ef01cSRoman Divacky     // Replace all uses of the old global with the new global
2651f22ef01cSRoman Divacky     llvm::Constant *NewPtrForOldDecl =
2652f22ef01cSRoman Divacky         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2653f22ef01cSRoman Divacky     Entry->replaceAllUsesWith(NewPtrForOldDecl);
2654f22ef01cSRoman Divacky 
2655f22ef01cSRoman Divacky     // Erase the old global, since it is no longer used.
2656f22ef01cSRoman Divacky     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2657f22ef01cSRoman Divacky   }
2658f22ef01cSRoman Divacky 
2659284c1978SDimitry Andric   MaybeHandleStaticInExternC(D, GV);
2660284c1978SDimitry Andric 
26616122f3e6SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
26626122f3e6SDimitry Andric     AddGlobalAnnotations(D, GV);
2663f22ef01cSRoman Divacky 
2664e7145dcbSDimitry Andric   // Set the llvm linkage type as appropriate.
2665e7145dcbSDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
2666e7145dcbSDimitry Andric       getLLVMLinkageVarDefinition(D, GV->isConstant());
2667e7145dcbSDimitry Andric 
26680623d748SDimitry Andric   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
26690623d748SDimitry Andric   // the device. [...]"
26700623d748SDimitry Andric   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
26710623d748SDimitry Andric   // __device__, declares a variable that: [...]
26720623d748SDimitry Andric   // Is accessible from all the threads within the grid and from the host
26730623d748SDimitry Andric   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
26740623d748SDimitry Andric   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
2675e7145dcbSDimitry Andric   if (GV && LangOpts.CUDA) {
2676e7145dcbSDimitry Andric     if (LangOpts.CUDAIsDevice) {
2677e7145dcbSDimitry Andric       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
26780623d748SDimitry Andric         GV->setExternallyInitialized(true);
2679e7145dcbSDimitry Andric     } else {
2680e7145dcbSDimitry Andric       // Host-side shadows of external declarations of device-side
2681e7145dcbSDimitry Andric       // global variables become internal definitions. These have to
2682e7145dcbSDimitry Andric       // be internal in order to prevent name conflicts with global
2683e7145dcbSDimitry Andric       // host variables with the same name in a different TUs.
2684e7145dcbSDimitry Andric       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
2685e7145dcbSDimitry Andric         Linkage = llvm::GlobalValue::InternalLinkage;
2686e7145dcbSDimitry Andric 
2687e7145dcbSDimitry Andric         // Shadow variables and their properties must be registered
2688e7145dcbSDimitry Andric         // with CUDA runtime.
2689e7145dcbSDimitry Andric         unsigned Flags = 0;
2690e7145dcbSDimitry Andric         if (!D->hasDefinition())
2691e7145dcbSDimitry Andric           Flags |= CGCUDARuntime::ExternDeviceVar;
2692e7145dcbSDimitry Andric         if (D->hasAttr<CUDAConstantAttr>())
2693e7145dcbSDimitry Andric           Flags |= CGCUDARuntime::ConstantDeviceVar;
2694e7145dcbSDimitry Andric         getCUDARuntime().registerDeviceVar(*GV, Flags);
2695e7145dcbSDimitry Andric       } else if (D->hasAttr<CUDASharedAttr>())
2696e7145dcbSDimitry Andric         // __shared__ variables are odd. Shadows do get created, but
2697e7145dcbSDimitry Andric         // they are not registered with the CUDA runtime, so they
2698e7145dcbSDimitry Andric         // can't really be used to access their device-side
2699e7145dcbSDimitry Andric         // counterparts. It's not clear yet whether it's nvcc's bug or
2700e7145dcbSDimitry Andric         // a feature, but we've got to do the same for compatibility.
2701e7145dcbSDimitry Andric         Linkage = llvm::GlobalValue::InternalLinkage;
2702e7145dcbSDimitry Andric     }
27030623d748SDimitry Andric   }
2704f22ef01cSRoman Divacky   GV->setInitializer(Init);
2705f22ef01cSRoman Divacky 
2706f22ef01cSRoman Divacky   // If it is safe to mark the global 'constant', do so now.
2707dff0c46cSDimitry Andric   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2708dff0c46cSDimitry Andric                   isTypeConstant(D->getType(), true));
2709f22ef01cSRoman Divacky 
271039d628a0SDimitry Andric   // If it is in a read-only section, mark it 'constant'.
271139d628a0SDimitry Andric   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
271239d628a0SDimitry Andric     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
271339d628a0SDimitry Andric     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
271439d628a0SDimitry Andric       GV->setConstant(true);
271539d628a0SDimitry Andric   }
271639d628a0SDimitry Andric 
2717f22ef01cSRoman Divacky   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2718f22ef01cSRoman Divacky 
2719f785676fSDimitry Andric 
27200623d748SDimitry Andric   // On Darwin, if the normal linkage of a C++ thread_local variable is
27210623d748SDimitry Andric   // LinkOnce or Weak, we keep the normal linkage to prevent multiple
27220623d748SDimitry Andric   // copies within a linkage unit; otherwise, the backing variable has
27230623d748SDimitry Andric   // internal linkage and all accesses should just be calls to the
272459d1ed5bSDimitry Andric   // Itanium-specified entry point, which has the normal linkage of the
27250623d748SDimitry Andric   // variable. This is to preserve the ability to change the implementation
27260623d748SDimitry Andric   // behind the scenes.
272739d628a0SDimitry Andric   if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
27280623d748SDimitry Andric       Context.getTargetInfo().getTriple().isOSDarwin() &&
27290623d748SDimitry Andric       !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
27300623d748SDimitry Andric       !llvm::GlobalVariable::isWeakLinkage(Linkage))
273159d1ed5bSDimitry Andric     Linkage = llvm::GlobalValue::InternalLinkage;
273259d1ed5bSDimitry Andric 
273359d1ed5bSDimitry Andric   GV->setLinkage(Linkage);
273459d1ed5bSDimitry Andric   if (D->hasAttr<DLLImportAttr>())
273559d1ed5bSDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
273659d1ed5bSDimitry Andric   else if (D->hasAttr<DLLExportAttr>())
273759d1ed5bSDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
273839d628a0SDimitry Andric   else
273939d628a0SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2740f785676fSDimitry Andric 
274144290647SDimitry Andric   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
2742f22ef01cSRoman Divacky     // common vars aren't constant even if declared const.
2743f22ef01cSRoman Divacky     GV->setConstant(false);
274444290647SDimitry Andric     // Tentative definition of global variables may be initialized with
274544290647SDimitry Andric     // non-zero null pointers. In this case they should have weak linkage
274644290647SDimitry Andric     // since common linkage must have zero initializer and must not have
274744290647SDimitry Andric     // explicit section therefore cannot have non-zero initial value.
274844290647SDimitry Andric     if (!GV->getInitializer()->isNullValue())
274944290647SDimitry Andric       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
275044290647SDimitry Andric   }
2751f22ef01cSRoman Divacky 
275259d1ed5bSDimitry Andric   setNonAliasAttributes(D, GV);
2753f22ef01cSRoman Divacky 
275439d628a0SDimitry Andric   if (D->getTLSKind() && !GV->isThreadLocal()) {
275539d628a0SDimitry Andric     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
27560623d748SDimitry Andric       CXXThreadLocals.push_back(D);
275739d628a0SDimitry Andric     setTLSMode(GV, *D);
275839d628a0SDimitry Andric   }
275939d628a0SDimitry Andric 
276033956c43SDimitry Andric   maybeSetTrivialComdat(*D, *GV);
276133956c43SDimitry Andric 
27622754fe60SDimitry Andric   // Emit the initializer function if necessary.
2763dff0c46cSDimitry Andric   if (NeedsGlobalCtor || NeedsGlobalDtor)
2764dff0c46cSDimitry Andric     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
27652754fe60SDimitry Andric 
276639d628a0SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
27673861d79fSDimitry Andric 
2768f22ef01cSRoman Divacky   // Emit global variable debug information.
27696122f3e6SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
2770e7145dcbSDimitry Andric     if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
2771f22ef01cSRoman Divacky       DI->EmitGlobalVariable(GV, D);
2772f22ef01cSRoman Divacky }
2773f22ef01cSRoman Divacky 
277439d628a0SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context,
277533956c43SDimitry Andric                                       CodeGenModule &CGM, const VarDecl *D,
277633956c43SDimitry Andric                                       bool NoCommon) {
277759d1ed5bSDimitry Andric   // Don't give variables common linkage if -fno-common was specified unless it
277859d1ed5bSDimitry Andric   // was overridden by a NoCommon attribute.
277959d1ed5bSDimitry Andric   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
278059d1ed5bSDimitry Andric     return true;
278159d1ed5bSDimitry Andric 
278259d1ed5bSDimitry Andric   // C11 6.9.2/2:
278359d1ed5bSDimitry Andric   //   A declaration of an identifier for an object that has file scope without
278459d1ed5bSDimitry Andric   //   an initializer, and without a storage-class specifier or with the
278559d1ed5bSDimitry Andric   //   storage-class specifier static, constitutes a tentative definition.
278659d1ed5bSDimitry Andric   if (D->getInit() || D->hasExternalStorage())
278759d1ed5bSDimitry Andric     return true;
278859d1ed5bSDimitry Andric 
278959d1ed5bSDimitry Andric   // A variable cannot be both common and exist in a section.
279059d1ed5bSDimitry Andric   if (D->hasAttr<SectionAttr>())
279159d1ed5bSDimitry Andric     return true;
279259d1ed5bSDimitry Andric 
279359d1ed5bSDimitry Andric   // Thread local vars aren't considered common linkage.
279459d1ed5bSDimitry Andric   if (D->getTLSKind())
279559d1ed5bSDimitry Andric     return true;
279659d1ed5bSDimitry Andric 
279759d1ed5bSDimitry Andric   // Tentative definitions marked with WeakImportAttr are true definitions.
279859d1ed5bSDimitry Andric   if (D->hasAttr<WeakImportAttr>())
279959d1ed5bSDimitry Andric     return true;
280059d1ed5bSDimitry Andric 
280133956c43SDimitry Andric   // A variable cannot be both common and exist in a comdat.
280233956c43SDimitry Andric   if (shouldBeInCOMDAT(CGM, *D))
280333956c43SDimitry Andric     return true;
280433956c43SDimitry Andric 
2805e7145dcbSDimitry Andric   // Declarations with a required alignment do not have common linkage in MSVC
280639d628a0SDimitry Andric   // mode.
28070623d748SDimitry Andric   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
280833956c43SDimitry Andric     if (D->hasAttr<AlignedAttr>())
280939d628a0SDimitry Andric       return true;
281033956c43SDimitry Andric     QualType VarType = D->getType();
281133956c43SDimitry Andric     if (Context.isAlignmentRequired(VarType))
281233956c43SDimitry Andric       return true;
281333956c43SDimitry Andric 
281433956c43SDimitry Andric     if (const auto *RT = VarType->getAs<RecordType>()) {
281533956c43SDimitry Andric       const RecordDecl *RD = RT->getDecl();
281633956c43SDimitry Andric       for (const FieldDecl *FD : RD->fields()) {
281733956c43SDimitry Andric         if (FD->isBitField())
281833956c43SDimitry Andric           continue;
281933956c43SDimitry Andric         if (FD->hasAttr<AlignedAttr>())
282033956c43SDimitry Andric           return true;
282133956c43SDimitry Andric         if (Context.isAlignmentRequired(FD->getType()))
282233956c43SDimitry Andric           return true;
282333956c43SDimitry Andric       }
282433956c43SDimitry Andric     }
282533956c43SDimitry Andric   }
282639d628a0SDimitry Andric 
282759d1ed5bSDimitry Andric   return false;
282859d1ed5bSDimitry Andric }
282959d1ed5bSDimitry Andric 
283059d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
283159d1ed5bSDimitry Andric     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
28322754fe60SDimitry Andric   if (Linkage == GVA_Internal)
28332754fe60SDimitry Andric     return llvm::Function::InternalLinkage;
283459d1ed5bSDimitry Andric 
283559d1ed5bSDimitry Andric   if (D->hasAttr<WeakAttr>()) {
283659d1ed5bSDimitry Andric     if (IsConstantVariable)
283759d1ed5bSDimitry Andric       return llvm::GlobalVariable::WeakODRLinkage;
283859d1ed5bSDimitry Andric     else
283959d1ed5bSDimitry Andric       return llvm::GlobalVariable::WeakAnyLinkage;
284059d1ed5bSDimitry Andric   }
284159d1ed5bSDimitry Andric 
284259d1ed5bSDimitry Andric   // We are guaranteed to have a strong definition somewhere else,
284359d1ed5bSDimitry Andric   // so we can use available_externally linkage.
284459d1ed5bSDimitry Andric   if (Linkage == GVA_AvailableExternally)
284520e90f04SDimitry Andric     return llvm::GlobalValue::AvailableExternallyLinkage;
284659d1ed5bSDimitry Andric 
284759d1ed5bSDimitry Andric   // Note that Apple's kernel linker doesn't support symbol
284859d1ed5bSDimitry Andric   // coalescing, so we need to avoid linkonce and weak linkages there.
284959d1ed5bSDimitry Andric   // Normally, this means we just map to internal, but for explicit
285059d1ed5bSDimitry Andric   // instantiations we'll map to external.
285159d1ed5bSDimitry Andric 
285259d1ed5bSDimitry Andric   // In C++, the compiler has to emit a definition in every translation unit
285359d1ed5bSDimitry Andric   // that references the function.  We should use linkonce_odr because
285459d1ed5bSDimitry Andric   // a) if all references in this translation unit are optimized away, we
285559d1ed5bSDimitry Andric   // don't need to codegen it.  b) if the function persists, it needs to be
285659d1ed5bSDimitry Andric   // merged with other definitions. c) C++ has the ODR, so we know the
285759d1ed5bSDimitry Andric   // definition is dependable.
285859d1ed5bSDimitry Andric   if (Linkage == GVA_DiscardableODR)
285959d1ed5bSDimitry Andric     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
286059d1ed5bSDimitry Andric                                             : llvm::Function::InternalLinkage;
286159d1ed5bSDimitry Andric 
286259d1ed5bSDimitry Andric   // An explicit instantiation of a template has weak linkage, since
286359d1ed5bSDimitry Andric   // explicit instantiations can occur in multiple translation units
286459d1ed5bSDimitry Andric   // and must all be equivalent. However, we are not allowed to
286559d1ed5bSDimitry Andric   // throw away these explicit instantiations.
2866e7145dcbSDimitry Andric   //
2867e7145dcbSDimitry Andric   // We don't currently support CUDA device code spread out across multiple TUs,
2868e7145dcbSDimitry Andric   // so say that CUDA templates are either external (for kernels) or internal.
2869e7145dcbSDimitry Andric   // This lets llvm perform aggressive inter-procedural optimizations.
2870e7145dcbSDimitry Andric   if (Linkage == GVA_StrongODR) {
2871e7145dcbSDimitry Andric     if (Context.getLangOpts().AppleKext)
2872e7145dcbSDimitry Andric       return llvm::Function::ExternalLinkage;
2873e7145dcbSDimitry Andric     if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
2874e7145dcbSDimitry Andric       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
2875e7145dcbSDimitry Andric                                           : llvm::Function::InternalLinkage;
2876e7145dcbSDimitry Andric     return llvm::Function::WeakODRLinkage;
2877e7145dcbSDimitry Andric   }
287859d1ed5bSDimitry Andric 
287959d1ed5bSDimitry Andric   // C++ doesn't have tentative definitions and thus cannot have common
288059d1ed5bSDimitry Andric   // linkage.
288159d1ed5bSDimitry Andric   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
288233956c43SDimitry Andric       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
288339d628a0SDimitry Andric                                  CodeGenOpts.NoCommon))
288459d1ed5bSDimitry Andric     return llvm::GlobalVariable::CommonLinkage;
288559d1ed5bSDimitry Andric 
2886f785676fSDimitry Andric   // selectany symbols are externally visible, so use weak instead of
2887f785676fSDimitry Andric   // linkonce.  MSVC optimizes away references to const selectany globals, so
2888f785676fSDimitry Andric   // all definitions should be the same and ODR linkage should be used.
2889f785676fSDimitry Andric   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
289059d1ed5bSDimitry Andric   if (D->hasAttr<SelectAnyAttr>())
2891f785676fSDimitry Andric     return llvm::GlobalVariable::WeakODRLinkage;
289259d1ed5bSDimitry Andric 
289359d1ed5bSDimitry Andric   // Otherwise, we have strong external linkage.
289459d1ed5bSDimitry Andric   assert(Linkage == GVA_StrongExternal);
28952754fe60SDimitry Andric   return llvm::GlobalVariable::ExternalLinkage;
28962754fe60SDimitry Andric }
28972754fe60SDimitry Andric 
289859d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
289959d1ed5bSDimitry Andric     const VarDecl *VD, bool IsConstant) {
290059d1ed5bSDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
290159d1ed5bSDimitry Andric   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
290259d1ed5bSDimitry Andric }
290359d1ed5bSDimitry Andric 
2904139f7f9bSDimitry Andric /// Replace the uses of a function that was declared with a non-proto type.
2905139f7f9bSDimitry Andric /// We want to silently drop extra arguments from call sites
2906139f7f9bSDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2907139f7f9bSDimitry Andric                                           llvm::Function *newFn) {
2908139f7f9bSDimitry Andric   // Fast path.
2909139f7f9bSDimitry Andric   if (old->use_empty()) return;
2910139f7f9bSDimitry Andric 
2911139f7f9bSDimitry Andric   llvm::Type *newRetTy = newFn->getReturnType();
2912139f7f9bSDimitry Andric   SmallVector<llvm::Value*, 4> newArgs;
29130623d748SDimitry Andric   SmallVector<llvm::OperandBundleDef, 1> newBundles;
2914139f7f9bSDimitry Andric 
2915139f7f9bSDimitry Andric   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2916139f7f9bSDimitry Andric          ui != ue; ) {
2917139f7f9bSDimitry Andric     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
291859d1ed5bSDimitry Andric     llvm::User *user = use->getUser();
2919139f7f9bSDimitry Andric 
2920139f7f9bSDimitry Andric     // Recognize and replace uses of bitcasts.  Most calls to
2921139f7f9bSDimitry Andric     // unprototyped functions will use bitcasts.
292259d1ed5bSDimitry Andric     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
2923139f7f9bSDimitry Andric       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2924139f7f9bSDimitry Andric         replaceUsesOfNonProtoConstant(bitcast, newFn);
2925139f7f9bSDimitry Andric       continue;
2926139f7f9bSDimitry Andric     }
2927139f7f9bSDimitry Andric 
2928139f7f9bSDimitry Andric     // Recognize calls to the function.
2929139f7f9bSDimitry Andric     llvm::CallSite callSite(user);
2930139f7f9bSDimitry Andric     if (!callSite) continue;
293159d1ed5bSDimitry Andric     if (!callSite.isCallee(&*use)) continue;
2932139f7f9bSDimitry Andric 
2933139f7f9bSDimitry Andric     // If the return types don't match exactly, then we can't
2934139f7f9bSDimitry Andric     // transform this call unless it's dead.
2935139f7f9bSDimitry Andric     if (callSite->getType() != newRetTy && !callSite->use_empty())
2936139f7f9bSDimitry Andric       continue;
2937139f7f9bSDimitry Andric 
2938139f7f9bSDimitry Andric     // Get the call site's attribute list.
293920e90f04SDimitry Andric     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
294020e90f04SDimitry Andric     llvm::AttributeList oldAttrs = callSite.getAttributes();
2941139f7f9bSDimitry Andric 
2942139f7f9bSDimitry Andric     // If the function was passed too few arguments, don't transform.
2943139f7f9bSDimitry Andric     unsigned newNumArgs = newFn->arg_size();
2944139f7f9bSDimitry Andric     if (callSite.arg_size() < newNumArgs) continue;
2945139f7f9bSDimitry Andric 
2946139f7f9bSDimitry Andric     // If extra arguments were passed, we silently drop them.
2947139f7f9bSDimitry Andric     // If any of the types mismatch, we don't transform.
2948139f7f9bSDimitry Andric     unsigned argNo = 0;
2949139f7f9bSDimitry Andric     bool dontTransform = false;
295020e90f04SDimitry Andric     for (llvm::Argument &A : newFn->args()) {
295120e90f04SDimitry Andric       if (callSite.getArgument(argNo)->getType() != A.getType()) {
2952139f7f9bSDimitry Andric         dontTransform = true;
2953139f7f9bSDimitry Andric         break;
2954139f7f9bSDimitry Andric       }
2955139f7f9bSDimitry Andric 
2956139f7f9bSDimitry Andric       // Add any parameter attributes.
295720e90f04SDimitry Andric       newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
295820e90f04SDimitry Andric       argNo++;
2959139f7f9bSDimitry Andric     }
2960139f7f9bSDimitry Andric     if (dontTransform)
2961139f7f9bSDimitry Andric       continue;
2962139f7f9bSDimitry Andric 
2963139f7f9bSDimitry Andric     // Okay, we can transform this.  Create the new call instruction and copy
2964139f7f9bSDimitry Andric     // over the required information.
2965139f7f9bSDimitry Andric     newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2966139f7f9bSDimitry Andric 
29670623d748SDimitry Andric     // Copy over any operand bundles.
29680623d748SDimitry Andric     callSite.getOperandBundlesAsDefs(newBundles);
29690623d748SDimitry Andric 
2970139f7f9bSDimitry Andric     llvm::CallSite newCall;
2971139f7f9bSDimitry Andric     if (callSite.isCall()) {
29720623d748SDimitry Andric       newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
2973139f7f9bSDimitry Andric                                        callSite.getInstruction());
2974139f7f9bSDimitry Andric     } else {
297559d1ed5bSDimitry Andric       auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
2976139f7f9bSDimitry Andric       newCall = llvm::InvokeInst::Create(newFn,
2977139f7f9bSDimitry Andric                                          oldInvoke->getNormalDest(),
2978139f7f9bSDimitry Andric                                          oldInvoke->getUnwindDest(),
29790623d748SDimitry Andric                                          newArgs, newBundles, "",
2980139f7f9bSDimitry Andric                                          callSite.getInstruction());
2981139f7f9bSDimitry Andric     }
2982139f7f9bSDimitry Andric     newArgs.clear(); // for the next iteration
2983139f7f9bSDimitry Andric 
2984139f7f9bSDimitry Andric     if (!newCall->getType()->isVoidTy())
2985139f7f9bSDimitry Andric       newCall->takeName(callSite.getInstruction());
298620e90f04SDimitry Andric     newCall.setAttributes(llvm::AttributeList::get(
298720e90f04SDimitry Andric         newFn->getContext(), oldAttrs.getFnAttributes(),
298820e90f04SDimitry Andric         oldAttrs.getRetAttributes(), newArgAttrs));
2989139f7f9bSDimitry Andric     newCall.setCallingConv(callSite.getCallingConv());
2990139f7f9bSDimitry Andric 
2991139f7f9bSDimitry Andric     // Finally, remove the old call, replacing any uses with the new one.
2992139f7f9bSDimitry Andric     if (!callSite->use_empty())
2993139f7f9bSDimitry Andric       callSite->replaceAllUsesWith(newCall.getInstruction());
2994139f7f9bSDimitry Andric 
2995139f7f9bSDimitry Andric     // Copy debug location attached to CI.
299633956c43SDimitry Andric     if (callSite->getDebugLoc())
2997139f7f9bSDimitry Andric       newCall->setDebugLoc(callSite->getDebugLoc());
29980623d748SDimitry Andric 
2999139f7f9bSDimitry Andric     callSite->eraseFromParent();
3000139f7f9bSDimitry Andric   }
3001139f7f9bSDimitry Andric }
3002139f7f9bSDimitry Andric 
3003f22ef01cSRoman Divacky /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
3004f22ef01cSRoman Divacky /// implement a function with no prototype, e.g. "int foo() {}".  If there are
3005f22ef01cSRoman Divacky /// existing call uses of the old function in the module, this adjusts them to
3006f22ef01cSRoman Divacky /// call the new function directly.
3007f22ef01cSRoman Divacky ///
3008f22ef01cSRoman Divacky /// This is not just a cleanup: the always_inline pass requires direct calls to
3009f22ef01cSRoman Divacky /// functions to be able to inline them.  If there is a bitcast in the way, it
3010f22ef01cSRoman Divacky /// won't inline them.  Instcombine normally deletes these calls, but it isn't
3011f22ef01cSRoman Divacky /// run at -O0.
3012f22ef01cSRoman Divacky static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3013f22ef01cSRoman Divacky                                                       llvm::Function *NewFn) {
3014f22ef01cSRoman Divacky   // If we're redefining a global as a function, don't transform it.
3015139f7f9bSDimitry Andric   if (!isa<llvm::Function>(Old)) return;
3016f22ef01cSRoman Divacky 
3017139f7f9bSDimitry Andric   replaceUsesOfNonProtoConstant(Old, NewFn);
3018f22ef01cSRoman Divacky }
3019f22ef01cSRoman Divacky 
3020dff0c46cSDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
3021e7145dcbSDimitry Andric   auto DK = VD->isThisDeclarationADefinition();
3022e7145dcbSDimitry Andric   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
3023e7145dcbSDimitry Andric     return;
3024e7145dcbSDimitry Andric 
3025dff0c46cSDimitry Andric   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
3026dff0c46cSDimitry Andric   // If we have a definition, this might be a deferred decl. If the
3027dff0c46cSDimitry Andric   // instantiation is explicit, make sure we emit it at the end.
3028dff0c46cSDimitry Andric   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
3029dff0c46cSDimitry Andric     GetAddrOfGlobalVar(VD);
3030139f7f9bSDimitry Andric 
3031139f7f9bSDimitry Andric   EmitTopLevelDecl(VD);
3032dff0c46cSDimitry Andric }
3033f22ef01cSRoman Divacky 
303459d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
303559d1ed5bSDimitry Andric                                                  llvm::GlobalValue *GV) {
303659d1ed5bSDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
30373b0f4066SDimitry Andric 
30383b0f4066SDimitry Andric   // Compute the function info and LLVM type.
3039dff0c46cSDimitry Andric   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3040dff0c46cSDimitry Andric   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
30413b0f4066SDimitry Andric 
3042f22ef01cSRoman Divacky   // Get or create the prototype for the function.
30430623d748SDimitry Andric   if (!GV || (GV->getType()->getElementType() != Ty))
30440623d748SDimitry Andric     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
30450623d748SDimitry Andric                                                    /*DontDefer=*/true,
304644290647SDimitry Andric                                                    ForDefinition));
3047f22ef01cSRoman Divacky 
30480623d748SDimitry Andric   // Already emitted.
30490623d748SDimitry Andric   if (!GV->isDeclaration())
3050f785676fSDimitry Andric     return;
3051f22ef01cSRoman Divacky 
30522754fe60SDimitry Andric   // We need to set linkage and visibility on the function before
30532754fe60SDimitry Andric   // generating code for it because various parts of IR generation
30542754fe60SDimitry Andric   // want to propagate this information down (e.g. to local static
30552754fe60SDimitry Andric   // declarations).
305659d1ed5bSDimitry Andric   auto *Fn = cast<llvm::Function>(GV);
3057f785676fSDimitry Andric   setFunctionLinkage(GD, Fn);
305897bc6c73SDimitry Andric   setFunctionDLLStorageClass(GD, Fn);
3059f22ef01cSRoman Divacky 
306059d1ed5bSDimitry Andric   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
30612754fe60SDimitry Andric   setGlobalVisibility(Fn, D);
30622754fe60SDimitry Andric 
3063284c1978SDimitry Andric   MaybeHandleStaticInExternC(D, Fn);
3064284c1978SDimitry Andric 
306533956c43SDimitry Andric   maybeSetTrivialComdat(*D, *Fn);
306633956c43SDimitry Andric 
30673b0f4066SDimitry Andric   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
3068f22ef01cSRoman Divacky 
306959d1ed5bSDimitry Andric   setFunctionDefinitionAttributes(D, Fn);
3070f22ef01cSRoman Divacky   SetLLVMFunctionAttributesForDefinition(D, Fn);
3071f22ef01cSRoman Divacky 
3072f22ef01cSRoman Divacky   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
3073f22ef01cSRoman Divacky     AddGlobalCtor(Fn, CA->getPriority());
3074f22ef01cSRoman Divacky   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
3075f22ef01cSRoman Divacky     AddGlobalDtor(Fn, DA->getPriority());
30766122f3e6SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
30776122f3e6SDimitry Andric     AddGlobalAnnotations(D, Fn);
3078f22ef01cSRoman Divacky }
3079f22ef01cSRoman Divacky 
3080f22ef01cSRoman Divacky void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
308159d1ed5bSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
3082f22ef01cSRoman Divacky   const AliasAttr *AA = D->getAttr<AliasAttr>();
3083f22ef01cSRoman Divacky   assert(AA && "Not an alias?");
3084f22ef01cSRoman Divacky 
30856122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
3086f22ef01cSRoman Divacky 
30879a4b3118SDimitry Andric   if (AA->getAliasee() == MangledName) {
3088e7145dcbSDimitry Andric     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
30899a4b3118SDimitry Andric     return;
30909a4b3118SDimitry Andric   }
30919a4b3118SDimitry Andric 
3092f22ef01cSRoman Divacky   // If there is a definition in the module, then it wins over the alias.
3093f22ef01cSRoman Divacky   // This is dubious, but allow it to be safe.  Just ignore the alias.
3094f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3095f22ef01cSRoman Divacky   if (Entry && !Entry->isDeclaration())
3096f22ef01cSRoman Divacky     return;
3097f22ef01cSRoman Divacky 
3098f785676fSDimitry Andric   Aliases.push_back(GD);
3099f785676fSDimitry Andric 
31006122f3e6SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3101f22ef01cSRoman Divacky 
3102f22ef01cSRoman Divacky   // Create a reference to the named value.  This ensures that it is emitted
3103f22ef01cSRoman Divacky   // if a deferred decl.
3104f22ef01cSRoman Divacky   llvm::Constant *Aliasee;
3105f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(DeclTy))
31063861d79fSDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
31072754fe60SDimitry Andric                                       /*ForVTable=*/false);
3108f22ef01cSRoman Divacky   else
3109f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
311059d1ed5bSDimitry Andric                                     llvm::PointerType::getUnqual(DeclTy),
311139d628a0SDimitry Andric                                     /*D=*/nullptr);
3112f22ef01cSRoman Divacky 
3113f22ef01cSRoman Divacky   // Create the new alias itself, but don't set a name yet.
311459d1ed5bSDimitry Andric   auto *GA = llvm::GlobalAlias::create(
31150623d748SDimitry Andric       DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
3116f22ef01cSRoman Divacky 
3117f22ef01cSRoman Divacky   if (Entry) {
311859d1ed5bSDimitry Andric     if (GA->getAliasee() == Entry) {
3119e7145dcbSDimitry Andric       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
312059d1ed5bSDimitry Andric       return;
312159d1ed5bSDimitry Andric     }
312259d1ed5bSDimitry Andric 
3123f22ef01cSRoman Divacky     assert(Entry->isDeclaration());
3124f22ef01cSRoman Divacky 
3125f22ef01cSRoman Divacky     // If there is a declaration in the module, then we had an extern followed
3126f22ef01cSRoman Divacky     // by the alias, as in:
3127f22ef01cSRoman Divacky     //   extern int test6();
3128f22ef01cSRoman Divacky     //   ...
3129f22ef01cSRoman Divacky     //   int test6() __attribute__((alias("test7")));
3130f22ef01cSRoman Divacky     //
3131f22ef01cSRoman Divacky     // Remove it and replace uses of it with the alias.
3132f22ef01cSRoman Divacky     GA->takeName(Entry);
3133f22ef01cSRoman Divacky 
3134f22ef01cSRoman Divacky     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
3135f22ef01cSRoman Divacky                                                           Entry->getType()));
3136f22ef01cSRoman Divacky     Entry->eraseFromParent();
3137f22ef01cSRoman Divacky   } else {
3138ffd1746dSEd Schouten     GA->setName(MangledName);
3139f22ef01cSRoman Divacky   }
3140f22ef01cSRoman Divacky 
3141f22ef01cSRoman Divacky   // Set attributes which are particular to an alias; this is a
3142f22ef01cSRoman Divacky   // specialization of the attributes which may be set on a global
3143f22ef01cSRoman Divacky   // variable/function.
314439d628a0SDimitry Andric   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
31453b0f4066SDimitry Andric       D->isWeakImported()) {
3146f22ef01cSRoman Divacky     GA->setLinkage(llvm::Function::WeakAnyLinkage);
3147f22ef01cSRoman Divacky   }
3148f22ef01cSRoman Divacky 
314939d628a0SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
315039d628a0SDimitry Andric     if (VD->getTLSKind())
315139d628a0SDimitry Andric       setTLSMode(GA, *VD);
315239d628a0SDimitry Andric 
315339d628a0SDimitry Andric   setAliasAttributes(D, GA);
3154f22ef01cSRoman Divacky }
3155f22ef01cSRoman Divacky 
3156e7145dcbSDimitry Andric void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
3157e7145dcbSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
3158e7145dcbSDimitry Andric   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
3159e7145dcbSDimitry Andric   assert(IFA && "Not an ifunc?");
3160e7145dcbSDimitry Andric 
3161e7145dcbSDimitry Andric   StringRef MangledName = getMangledName(GD);
3162e7145dcbSDimitry Andric 
3163e7145dcbSDimitry Andric   if (IFA->getResolver() == MangledName) {
3164e7145dcbSDimitry Andric     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3165e7145dcbSDimitry Andric     return;
3166e7145dcbSDimitry Andric   }
3167e7145dcbSDimitry Andric 
3168e7145dcbSDimitry Andric   // Report an error if some definition overrides ifunc.
3169e7145dcbSDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3170e7145dcbSDimitry Andric   if (Entry && !Entry->isDeclaration()) {
3171e7145dcbSDimitry Andric     GlobalDecl OtherGD;
3172e7145dcbSDimitry Andric     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3173e7145dcbSDimitry Andric         DiagnosedConflictingDefinitions.insert(GD).second) {
3174e7145dcbSDimitry Andric       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
3175e7145dcbSDimitry Andric       Diags.Report(OtherGD.getDecl()->getLocation(),
3176e7145dcbSDimitry Andric                    diag::note_previous_definition);
3177e7145dcbSDimitry Andric     }
3178e7145dcbSDimitry Andric     return;
3179e7145dcbSDimitry Andric   }
3180e7145dcbSDimitry Andric 
3181e7145dcbSDimitry Andric   Aliases.push_back(GD);
3182e7145dcbSDimitry Andric 
3183e7145dcbSDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3184e7145dcbSDimitry Andric   llvm::Constant *Resolver =
3185e7145dcbSDimitry Andric       GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3186e7145dcbSDimitry Andric                               /*ForVTable=*/false);
3187e7145dcbSDimitry Andric   llvm::GlobalIFunc *GIF =
3188e7145dcbSDimitry Andric       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
3189e7145dcbSDimitry Andric                                 "", Resolver, &getModule());
3190e7145dcbSDimitry Andric   if (Entry) {
3191e7145dcbSDimitry Andric     if (GIF->getResolver() == Entry) {
3192e7145dcbSDimitry Andric       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3193e7145dcbSDimitry Andric       return;
3194e7145dcbSDimitry Andric     }
3195e7145dcbSDimitry Andric     assert(Entry->isDeclaration());
3196e7145dcbSDimitry Andric 
3197e7145dcbSDimitry Andric     // If there is a declaration in the module, then we had an extern followed
3198e7145dcbSDimitry Andric     // by the ifunc, as in:
3199e7145dcbSDimitry Andric     //   extern int test();
3200e7145dcbSDimitry Andric     //   ...
3201e7145dcbSDimitry Andric     //   int test() __attribute__((ifunc("resolver")));
3202e7145dcbSDimitry Andric     //
3203e7145dcbSDimitry Andric     // Remove it and replace uses of it with the ifunc.
3204e7145dcbSDimitry Andric     GIF->takeName(Entry);
3205e7145dcbSDimitry Andric 
3206e7145dcbSDimitry Andric     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3207e7145dcbSDimitry Andric                                                           Entry->getType()));
3208e7145dcbSDimitry Andric     Entry->eraseFromParent();
3209e7145dcbSDimitry Andric   } else
3210e7145dcbSDimitry Andric     GIF->setName(MangledName);
3211e7145dcbSDimitry Andric 
3212e7145dcbSDimitry Andric   SetCommonAttributes(D, GIF);
3213e7145dcbSDimitry Andric }
3214e7145dcbSDimitry Andric 
321517a519f9SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
32166122f3e6SDimitry Andric                                             ArrayRef<llvm::Type*> Tys) {
321717a519f9SDimitry Andric   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
321817a519f9SDimitry Andric                                          Tys);
3219f22ef01cSRoman Divacky }
3220f22ef01cSRoman Divacky 
322133956c43SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> &
322233956c43SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
322333956c43SDimitry Andric                          const StringLiteral *Literal, bool TargetIsLSB,
322433956c43SDimitry Andric                          bool &IsUTF16, unsigned &StringLength) {
32256122f3e6SDimitry Andric   StringRef String = Literal->getString();
3226e580952dSDimitry Andric   unsigned NumBytes = String.size();
3227f22ef01cSRoman Divacky 
3228f22ef01cSRoman Divacky   // Check for simple case.
3229f22ef01cSRoman Divacky   if (!Literal->containsNonAsciiOrNull()) {
3230f22ef01cSRoman Divacky     StringLength = NumBytes;
323139d628a0SDimitry Andric     return *Map.insert(std::make_pair(String, nullptr)).first;
3232f22ef01cSRoman Divacky   }
3233f22ef01cSRoman Divacky 
3234dff0c46cSDimitry Andric   // Otherwise, convert the UTF8 literals into a string of shorts.
3235dff0c46cSDimitry Andric   IsUTF16 = true;
3236dff0c46cSDimitry Andric 
323744290647SDimitry Andric   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
323844290647SDimitry Andric   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
323944290647SDimitry Andric   llvm::UTF16 *ToPtr = &ToBuf[0];
3240f22ef01cSRoman Divacky 
324144290647SDimitry Andric   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
324244290647SDimitry Andric                                  ToPtr + NumBytes, llvm::strictConversion);
3243f22ef01cSRoman Divacky 
3244f22ef01cSRoman Divacky   // ConvertUTF8toUTF16 returns the length in ToPtr.
3245f22ef01cSRoman Divacky   StringLength = ToPtr - &ToBuf[0];
3246f22ef01cSRoman Divacky 
3247dff0c46cSDimitry Andric   // Add an explicit null.
3248dff0c46cSDimitry Andric   *ToPtr = 0;
324939d628a0SDimitry Andric   return *Map.insert(std::make_pair(
325039d628a0SDimitry Andric                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
325139d628a0SDimitry Andric                                    (StringLength + 1) * 2),
325239d628a0SDimitry Andric                          nullptr)).first;
3253f22ef01cSRoman Divacky }
3254f22ef01cSRoman Divacky 
32550623d748SDimitry Andric ConstantAddress
3256f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
3257f22ef01cSRoman Divacky   unsigned StringLength = 0;
3258f22ef01cSRoman Divacky   bool isUTF16 = false;
325933956c43SDimitry Andric   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3260f22ef01cSRoman Divacky       GetConstantCFStringEntry(CFConstantStringMap, Literal,
326133956c43SDimitry Andric                                getDataLayout().isLittleEndian(), isUTF16,
326233956c43SDimitry Andric                                StringLength);
3263f22ef01cSRoman Divacky 
326439d628a0SDimitry Andric   if (auto *C = Entry.second)
32650623d748SDimitry Andric     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
3266f22ef01cSRoman Divacky 
3267dff0c46cSDimitry Andric   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
3268f22ef01cSRoman Divacky   llvm::Constant *Zeros[] = { Zero, Zero };
3269f22ef01cSRoman Divacky 
3270f22ef01cSRoman Divacky   // If we don't already have it, get __CFConstantStringClassReference.
3271f22ef01cSRoman Divacky   if (!CFConstantStringClassRef) {
32726122f3e6SDimitry Andric     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
3273f22ef01cSRoman Divacky     Ty = llvm::ArrayType::get(Ty, 0);
3274e7145dcbSDimitry Andric     llvm::Constant *GV =
3275e7145dcbSDimitry Andric         CreateRuntimeVariable(Ty, "__CFConstantStringClassReference");
3276e7145dcbSDimitry Andric 
327744290647SDimitry Andric     if (getTriple().isOSBinFormatCOFF()) {
3278e7145dcbSDimitry Andric       IdentifierInfo &II = getContext().Idents.get(GV->getName());
3279e7145dcbSDimitry Andric       TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
3280e7145dcbSDimitry Andric       DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3281e7145dcbSDimitry Andric       llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
3282e7145dcbSDimitry Andric 
3283e7145dcbSDimitry Andric       const VarDecl *VD = nullptr;
3284e7145dcbSDimitry Andric       for (const auto &Result : DC->lookup(&II))
3285e7145dcbSDimitry Andric         if ((VD = dyn_cast<VarDecl>(Result)))
3286e7145dcbSDimitry Andric           break;
3287e7145dcbSDimitry Andric 
3288e7145dcbSDimitry Andric       if (!VD || !VD->hasAttr<DLLExportAttr>()) {
3289e7145dcbSDimitry Andric         CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3290e7145dcbSDimitry Andric         CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3291e7145dcbSDimitry Andric       } else {
3292e7145dcbSDimitry Andric         CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3293e7145dcbSDimitry Andric         CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3294e7145dcbSDimitry Andric       }
3295e7145dcbSDimitry Andric     }
3296e7145dcbSDimitry Andric 
3297f22ef01cSRoman Divacky     // Decay array -> ptr
329844290647SDimitry Andric     CFConstantStringClassRef =
329944290647SDimitry Andric         llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
3300e7145dcbSDimitry Andric   }
3301f22ef01cSRoman Divacky 
3302f22ef01cSRoman Divacky   QualType CFTy = getContext().getCFConstantStringType();
3303f22ef01cSRoman Divacky 
330459d1ed5bSDimitry Andric   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
3305f22ef01cSRoman Divacky 
330644290647SDimitry Andric   ConstantInitBuilder Builder(*this);
330744290647SDimitry Andric   auto Fields = Builder.beginStruct(STy);
3308f22ef01cSRoman Divacky 
3309f22ef01cSRoman Divacky   // Class pointer.
331044290647SDimitry Andric   Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
3311f22ef01cSRoman Divacky 
3312f22ef01cSRoman Divacky   // Flags.
331344290647SDimitry Andric   Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
3314f22ef01cSRoman Divacky 
3315f22ef01cSRoman Divacky   // String pointer.
331659d1ed5bSDimitry Andric   llvm::Constant *C = nullptr;
3317dff0c46cSDimitry Andric   if (isUTF16) {
33180623d748SDimitry Andric     auto Arr = llvm::makeArrayRef(
331939d628a0SDimitry Andric         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
332039d628a0SDimitry Andric         Entry.first().size() / 2);
3321dff0c46cSDimitry Andric     C = llvm::ConstantDataArray::get(VMContext, Arr);
3322dff0c46cSDimitry Andric   } else {
332339d628a0SDimitry Andric     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
3324dff0c46cSDimitry Andric   }
3325f22ef01cSRoman Divacky 
3326dff0c46cSDimitry Andric   // Note: -fwritable-strings doesn't make the backing store strings of
3327dff0c46cSDimitry Andric   // CFStrings writable. (See <rdar://problem/10657500>)
332859d1ed5bSDimitry Andric   auto *GV =
3329dff0c46cSDimitry Andric       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
333059d1ed5bSDimitry Andric                                llvm::GlobalValue::PrivateLinkage, C, ".str");
3331e7145dcbSDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3332284c1978SDimitry Andric   // Don't enforce the target's minimum global alignment, since the only use
3333284c1978SDimitry Andric   // of the string is via this class initializer.
3334e7145dcbSDimitry Andric   CharUnits Align = isUTF16
3335e7145dcbSDimitry Andric                         ? getContext().getTypeAlignInChars(getContext().ShortTy)
3336e7145dcbSDimitry Andric                         : getContext().getTypeAlignInChars(getContext().CharTy);
3337f22ef01cSRoman Divacky   GV->setAlignment(Align.getQuantity());
3338e7145dcbSDimitry Andric 
3339e7145dcbSDimitry Andric   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
3340e7145dcbSDimitry Andric   // Without it LLVM can merge the string with a non unnamed_addr one during
3341e7145dcbSDimitry Andric   // LTO.  Doing that changes the section it ends in, which surprises ld64.
334244290647SDimitry Andric   if (getTriple().isOSBinFormatMachO())
3343e7145dcbSDimitry Andric     GV->setSection(isUTF16 ? "__TEXT,__ustring"
3344e7145dcbSDimitry Andric                            : "__TEXT,__cstring,cstring_literals");
3345dff0c46cSDimitry Andric 
3346dff0c46cSDimitry Andric   // String.
334744290647SDimitry Andric   llvm::Constant *Str =
334833956c43SDimitry Andric       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3349f22ef01cSRoman Divacky 
3350dff0c46cSDimitry Andric   if (isUTF16)
3351dff0c46cSDimitry Andric     // Cast the UTF16 string to the correct type.
335244290647SDimitry Andric     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
335344290647SDimitry Andric   Fields.add(Str);
3354dff0c46cSDimitry Andric 
3355f22ef01cSRoman Divacky   // String length.
335644290647SDimitry Andric   auto Ty = getTypes().ConvertType(getContext().LongTy);
335744290647SDimitry Andric   Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
3358f22ef01cSRoman Divacky 
33590623d748SDimitry Andric   CharUnits Alignment = getPointerAlign();
33600623d748SDimitry Andric 
3361f22ef01cSRoman Divacky   // The struct.
336244290647SDimitry Andric   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
336344290647SDimitry Andric                                     /*isConstant=*/false,
336444290647SDimitry Andric                                     llvm::GlobalVariable::PrivateLinkage);
336544290647SDimitry Andric   switch (getTriple().getObjectFormat()) {
3366e7145dcbSDimitry Andric   case llvm::Triple::UnknownObjectFormat:
3367e7145dcbSDimitry Andric     llvm_unreachable("unknown file format");
3368e7145dcbSDimitry Andric   case llvm::Triple::COFF:
3369e7145dcbSDimitry Andric   case llvm::Triple::ELF:
337020e90f04SDimitry Andric   case llvm::Triple::Wasm:
3371e7145dcbSDimitry Andric     GV->setSection("cfstring");
3372e7145dcbSDimitry Andric     break;
3373e7145dcbSDimitry Andric   case llvm::Triple::MachO:
3374e7145dcbSDimitry Andric     GV->setSection("__DATA,__cfstring");
3375e7145dcbSDimitry Andric     break;
3376e7145dcbSDimitry Andric   }
337739d628a0SDimitry Andric   Entry.second = GV;
3378f22ef01cSRoman Divacky 
33790623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
3380f22ef01cSRoman Divacky }
3381f22ef01cSRoman Divacky 
33826122f3e6SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() {
33836122f3e6SDimitry Andric   if (ObjCFastEnumerationStateType.isNull()) {
338459d1ed5bSDimitry Andric     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
33856122f3e6SDimitry Andric     D->startDefinition();
33866122f3e6SDimitry Andric 
33876122f3e6SDimitry Andric     QualType FieldTypes[] = {
33886122f3e6SDimitry Andric       Context.UnsignedLongTy,
33896122f3e6SDimitry Andric       Context.getPointerType(Context.getObjCIdType()),
33906122f3e6SDimitry Andric       Context.getPointerType(Context.UnsignedLongTy),
33916122f3e6SDimitry Andric       Context.getConstantArrayType(Context.UnsignedLongTy,
33926122f3e6SDimitry Andric                            llvm::APInt(32, 5), ArrayType::Normal, 0)
33936122f3e6SDimitry Andric     };
33946122f3e6SDimitry Andric 
33956122f3e6SDimitry Andric     for (size_t i = 0; i < 4; ++i) {
33966122f3e6SDimitry Andric       FieldDecl *Field = FieldDecl::Create(Context,
33976122f3e6SDimitry Andric                                            D,
33986122f3e6SDimitry Andric                                            SourceLocation(),
339959d1ed5bSDimitry Andric                                            SourceLocation(), nullptr,
340059d1ed5bSDimitry Andric                                            FieldTypes[i], /*TInfo=*/nullptr,
340159d1ed5bSDimitry Andric                                            /*BitWidth=*/nullptr,
34026122f3e6SDimitry Andric                                            /*Mutable=*/false,
34037ae0e2c9SDimitry Andric                                            ICIS_NoInit);
34046122f3e6SDimitry Andric       Field->setAccess(AS_public);
34056122f3e6SDimitry Andric       D->addDecl(Field);
34066122f3e6SDimitry Andric     }
34076122f3e6SDimitry Andric 
34086122f3e6SDimitry Andric     D->completeDefinition();
34096122f3e6SDimitry Andric     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
34106122f3e6SDimitry Andric   }
34116122f3e6SDimitry Andric 
34126122f3e6SDimitry Andric   return ObjCFastEnumerationStateType;
34136122f3e6SDimitry Andric }
34146122f3e6SDimitry Andric 
3415dff0c46cSDimitry Andric llvm::Constant *
3416dff0c46cSDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
3417dff0c46cSDimitry Andric   assert(!E->getType()->isPointerType() && "Strings are always arrays");
3418f22ef01cSRoman Divacky 
3419dff0c46cSDimitry Andric   // Don't emit it as the address of the string, emit the string data itself
3420dff0c46cSDimitry Andric   // as an inline array.
3421dff0c46cSDimitry Andric   if (E->getCharByteWidth() == 1) {
3422dff0c46cSDimitry Andric     SmallString<64> Str(E->getString());
3423f22ef01cSRoman Divacky 
3424dff0c46cSDimitry Andric     // Resize the string to the right size, which is indicated by its type.
3425dff0c46cSDimitry Andric     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
3426dff0c46cSDimitry Andric     Str.resize(CAT->getSize().getZExtValue());
3427dff0c46cSDimitry Andric     return llvm::ConstantDataArray::getString(VMContext, Str, false);
34286122f3e6SDimitry Andric   }
3429f22ef01cSRoman Divacky 
343059d1ed5bSDimitry Andric   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
3431dff0c46cSDimitry Andric   llvm::Type *ElemTy = AType->getElementType();
3432dff0c46cSDimitry Andric   unsigned NumElements = AType->getNumElements();
3433f22ef01cSRoman Divacky 
3434dff0c46cSDimitry Andric   // Wide strings have either 2-byte or 4-byte elements.
3435dff0c46cSDimitry Andric   if (ElemTy->getPrimitiveSizeInBits() == 16) {
3436dff0c46cSDimitry Andric     SmallVector<uint16_t, 32> Elements;
3437dff0c46cSDimitry Andric     Elements.reserve(NumElements);
3438dff0c46cSDimitry Andric 
3439dff0c46cSDimitry Andric     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3440dff0c46cSDimitry Andric       Elements.push_back(E->getCodeUnit(i));
3441dff0c46cSDimitry Andric     Elements.resize(NumElements);
3442dff0c46cSDimitry Andric     return llvm::ConstantDataArray::get(VMContext, Elements);
3443dff0c46cSDimitry Andric   }
3444dff0c46cSDimitry Andric 
3445dff0c46cSDimitry Andric   assert(ElemTy->getPrimitiveSizeInBits() == 32);
3446dff0c46cSDimitry Andric   SmallVector<uint32_t, 32> Elements;
3447dff0c46cSDimitry Andric   Elements.reserve(NumElements);
3448dff0c46cSDimitry Andric 
3449dff0c46cSDimitry Andric   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3450dff0c46cSDimitry Andric     Elements.push_back(E->getCodeUnit(i));
3451dff0c46cSDimitry Andric   Elements.resize(NumElements);
3452dff0c46cSDimitry Andric   return llvm::ConstantDataArray::get(VMContext, Elements);
3453f22ef01cSRoman Divacky }
3454f22ef01cSRoman Divacky 
345559d1ed5bSDimitry Andric static llvm::GlobalVariable *
345659d1ed5bSDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
345759d1ed5bSDimitry Andric                       CodeGenModule &CGM, StringRef GlobalName,
34580623d748SDimitry Andric                       CharUnits Alignment) {
345959d1ed5bSDimitry Andric   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
346059d1ed5bSDimitry Andric   unsigned AddrSpace = 0;
346159d1ed5bSDimitry Andric   if (CGM.getLangOpts().OpenCL)
346259d1ed5bSDimitry Andric     AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
3463dff0c46cSDimitry Andric 
346433956c43SDimitry Andric   llvm::Module &M = CGM.getModule();
346559d1ed5bSDimitry Andric   // Create a global variable for this string
346659d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
346733956c43SDimitry Andric       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
346833956c43SDimitry Andric       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
34690623d748SDimitry Andric   GV->setAlignment(Alignment.getQuantity());
3470e7145dcbSDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
347133956c43SDimitry Andric   if (GV->isWeakForLinker()) {
347233956c43SDimitry Andric     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
347333956c43SDimitry Andric     GV->setComdat(M.getOrInsertComdat(GV->getName()));
347433956c43SDimitry Andric   }
347533956c43SDimitry Andric 
347659d1ed5bSDimitry Andric   return GV;
3477f22ef01cSRoman Divacky }
3478dff0c46cSDimitry Andric 
347959d1ed5bSDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
348059d1ed5bSDimitry Andric /// constant array for the given string literal.
34810623d748SDimitry Andric ConstantAddress
348239d628a0SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
348339d628a0SDimitry Andric                                                   StringRef Name) {
34840623d748SDimitry Andric   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
3485dff0c46cSDimitry Andric 
348659d1ed5bSDimitry Andric   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
348759d1ed5bSDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
348859d1ed5bSDimitry Andric   if (!LangOpts.WritableStrings) {
348959d1ed5bSDimitry Andric     Entry = &ConstantStringMap[C];
349059d1ed5bSDimitry Andric     if (auto GV = *Entry) {
34910623d748SDimitry Andric       if (Alignment.getQuantity() > GV->getAlignment())
34920623d748SDimitry Andric         GV->setAlignment(Alignment.getQuantity());
34930623d748SDimitry Andric       return ConstantAddress(GV, Alignment);
349459d1ed5bSDimitry Andric     }
349559d1ed5bSDimitry Andric   }
349659d1ed5bSDimitry Andric 
349759d1ed5bSDimitry Andric   SmallString<256> MangledNameBuffer;
349859d1ed5bSDimitry Andric   StringRef GlobalVariableName;
349959d1ed5bSDimitry Andric   llvm::GlobalValue::LinkageTypes LT;
350059d1ed5bSDimitry Andric 
350159d1ed5bSDimitry Andric   // Mangle the string literal if the ABI allows for it.  However, we cannot
350259d1ed5bSDimitry Andric   // do this if  we are compiling with ASan or -fwritable-strings because they
350359d1ed5bSDimitry Andric   // rely on strings having normal linkage.
350439d628a0SDimitry Andric   if (!LangOpts.WritableStrings &&
350539d628a0SDimitry Andric       !LangOpts.Sanitize.has(SanitizerKind::Address) &&
350659d1ed5bSDimitry Andric       getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
350759d1ed5bSDimitry Andric     llvm::raw_svector_ostream Out(MangledNameBuffer);
350859d1ed5bSDimitry Andric     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
350959d1ed5bSDimitry Andric 
351059d1ed5bSDimitry Andric     LT = llvm::GlobalValue::LinkOnceODRLinkage;
351159d1ed5bSDimitry Andric     GlobalVariableName = MangledNameBuffer;
351259d1ed5bSDimitry Andric   } else {
351359d1ed5bSDimitry Andric     LT = llvm::GlobalValue::PrivateLinkage;
351439d628a0SDimitry Andric     GlobalVariableName = Name;
351559d1ed5bSDimitry Andric   }
351659d1ed5bSDimitry Andric 
351759d1ed5bSDimitry Andric   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
351859d1ed5bSDimitry Andric   if (Entry)
351959d1ed5bSDimitry Andric     *Entry = GV;
352059d1ed5bSDimitry Andric 
352139d628a0SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
352239d628a0SDimitry Andric                                   QualType());
35230623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
3524f22ef01cSRoman Divacky }
3525f22ef01cSRoman Divacky 
3526f22ef01cSRoman Divacky /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
3527f22ef01cSRoman Divacky /// array for the given ObjCEncodeExpr node.
35280623d748SDimitry Andric ConstantAddress
3529f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
3530f22ef01cSRoman Divacky   std::string Str;
3531f22ef01cSRoman Divacky   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
3532f22ef01cSRoman Divacky 
3533f22ef01cSRoman Divacky   return GetAddrOfConstantCString(Str);
3534f22ef01cSRoman Divacky }
3535f22ef01cSRoman Divacky 
353659d1ed5bSDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing
353759d1ed5bSDimitry Andric /// the literal and a terminating '\0' character.
353859d1ed5bSDimitry Andric /// The result has pointer to array type.
35390623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString(
35400623d748SDimitry Andric     const std::string &Str, const char *GlobalName) {
354159d1ed5bSDimitry Andric   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
35420623d748SDimitry Andric   CharUnits Alignment =
35430623d748SDimitry Andric     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
3544f22ef01cSRoman Divacky 
354559d1ed5bSDimitry Andric   llvm::Constant *C =
354659d1ed5bSDimitry Andric       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
354759d1ed5bSDimitry Andric 
354859d1ed5bSDimitry Andric   // Don't share any string literals if strings aren't constant.
354959d1ed5bSDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
355059d1ed5bSDimitry Andric   if (!LangOpts.WritableStrings) {
355159d1ed5bSDimitry Andric     Entry = &ConstantStringMap[C];
355259d1ed5bSDimitry Andric     if (auto GV = *Entry) {
35530623d748SDimitry Andric       if (Alignment.getQuantity() > GV->getAlignment())
35540623d748SDimitry Andric         GV->setAlignment(Alignment.getQuantity());
35550623d748SDimitry Andric       return ConstantAddress(GV, Alignment);
355659d1ed5bSDimitry Andric     }
355759d1ed5bSDimitry Andric   }
355859d1ed5bSDimitry Andric 
3559f22ef01cSRoman Divacky   // Get the default prefix if a name wasn't specified.
3560f22ef01cSRoman Divacky   if (!GlobalName)
3561f22ef01cSRoman Divacky     GlobalName = ".str";
3562f22ef01cSRoman Divacky   // Create a global variable for this.
356359d1ed5bSDimitry Andric   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
356459d1ed5bSDimitry Andric                                   GlobalName, Alignment);
356559d1ed5bSDimitry Andric   if (Entry)
356659d1ed5bSDimitry Andric     *Entry = GV;
35670623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
3568f22ef01cSRoman Divacky }
3569f22ef01cSRoman Divacky 
35700623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
3571f785676fSDimitry Andric     const MaterializeTemporaryExpr *E, const Expr *Init) {
3572f785676fSDimitry Andric   assert((E->getStorageDuration() == SD_Static ||
3573f785676fSDimitry Andric           E->getStorageDuration() == SD_Thread) && "not a global temporary");
357459d1ed5bSDimitry Andric   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
3575f785676fSDimitry Andric 
3576f785676fSDimitry Andric   // If we're not materializing a subobject of the temporary, keep the
3577f785676fSDimitry Andric   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
3578f785676fSDimitry Andric   QualType MaterializedType = Init->getType();
3579f785676fSDimitry Andric   if (Init == E->GetTemporaryExpr())
3580f785676fSDimitry Andric     MaterializedType = E->getType();
3581f785676fSDimitry Andric 
35820623d748SDimitry Andric   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
35830623d748SDimitry Andric 
35840623d748SDimitry Andric   if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
35850623d748SDimitry Andric     return ConstantAddress(Slot, Align);
3586f785676fSDimitry Andric 
3587f785676fSDimitry Andric   // FIXME: If an externally-visible declaration extends multiple temporaries,
3588f785676fSDimitry Andric   // we need to give each temporary the same name in every translation unit (and
3589f785676fSDimitry Andric   // we also need to make the temporaries externally-visible).
3590f785676fSDimitry Andric   SmallString<256> Name;
3591f785676fSDimitry Andric   llvm::raw_svector_ostream Out(Name);
359259d1ed5bSDimitry Andric   getCXXABI().getMangleContext().mangleReferenceTemporary(
359359d1ed5bSDimitry Andric       VD, E->getManglingNumber(), Out);
3594f785676fSDimitry Andric 
359559d1ed5bSDimitry Andric   APValue *Value = nullptr;
3596f785676fSDimitry Andric   if (E->getStorageDuration() == SD_Static) {
3597f785676fSDimitry Andric     // We might have a cached constant initializer for this temporary. Note
3598f785676fSDimitry Andric     // that this might have a different value from the value computed by
3599f785676fSDimitry Andric     // evaluating the initializer if the surrounding constant expression
3600f785676fSDimitry Andric     // modifies the temporary.
3601f785676fSDimitry Andric     Value = getContext().getMaterializedTemporaryValue(E, false);
3602f785676fSDimitry Andric     if (Value && Value->isUninit())
360359d1ed5bSDimitry Andric       Value = nullptr;
3604f785676fSDimitry Andric   }
3605f785676fSDimitry Andric 
3606f785676fSDimitry Andric   // Try evaluating it now, it might have a constant initializer.
3607f785676fSDimitry Andric   Expr::EvalResult EvalResult;
3608f785676fSDimitry Andric   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3609f785676fSDimitry Andric       !EvalResult.hasSideEffects())
3610f785676fSDimitry Andric     Value = &EvalResult.Val;
3611f785676fSDimitry Andric 
361259d1ed5bSDimitry Andric   llvm::Constant *InitialValue = nullptr;
3613f785676fSDimitry Andric   bool Constant = false;
3614f785676fSDimitry Andric   llvm::Type *Type;
3615f785676fSDimitry Andric   if (Value) {
3616f785676fSDimitry Andric     // The temporary has a constant initializer, use it.
361759d1ed5bSDimitry Andric     InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
3618f785676fSDimitry Andric     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3619f785676fSDimitry Andric     Type = InitialValue->getType();
3620f785676fSDimitry Andric   } else {
3621f785676fSDimitry Andric     // No initializer, the initialization will be provided when we
3622f785676fSDimitry Andric     // initialize the declaration which performed lifetime extension.
3623f785676fSDimitry Andric     Type = getTypes().ConvertTypeForMem(MaterializedType);
3624f785676fSDimitry Andric   }
3625f785676fSDimitry Andric 
3626f785676fSDimitry Andric   // Create a global variable for this lifetime-extended temporary.
362759d1ed5bSDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
362859d1ed5bSDimitry Andric       getLLVMLinkageVarDefinition(VD, Constant);
362933956c43SDimitry Andric   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
363033956c43SDimitry Andric     const VarDecl *InitVD;
363133956c43SDimitry Andric     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
363233956c43SDimitry Andric         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
363333956c43SDimitry Andric       // Temporaries defined inside a class get linkonce_odr linkage because the
363433956c43SDimitry Andric       // class can be defined in multipe translation units.
363533956c43SDimitry Andric       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
363633956c43SDimitry Andric     } else {
363733956c43SDimitry Andric       // There is no need for this temporary to have external linkage if the
363833956c43SDimitry Andric       // VarDecl has external linkage.
363933956c43SDimitry Andric       Linkage = llvm::GlobalVariable::InternalLinkage;
364033956c43SDimitry Andric     }
364133956c43SDimitry Andric   }
364259d1ed5bSDimitry Andric   unsigned AddrSpace = GetGlobalVarAddressSpace(
364359d1ed5bSDimitry Andric       VD, getContext().getTargetAddressSpace(MaterializedType));
364459d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
364559d1ed5bSDimitry Andric       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
364659d1ed5bSDimitry Andric       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
364759d1ed5bSDimitry Andric       AddrSpace);
364859d1ed5bSDimitry Andric   setGlobalVisibility(GV, VD);
36490623d748SDimitry Andric   GV->setAlignment(Align.getQuantity());
365033956c43SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker())
365133956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3652f785676fSDimitry Andric   if (VD->getTLSKind())
3653f785676fSDimitry Andric     setTLSMode(GV, *VD);
36540623d748SDimitry Andric   MaterializedGlobalTemporaryMap[E] = GV;
36550623d748SDimitry Andric   return ConstantAddress(GV, Align);
3656f785676fSDimitry Andric }
3657f785676fSDimitry Andric 
3658f22ef01cSRoman Divacky /// EmitObjCPropertyImplementations - Emit information for synthesized
3659f22ef01cSRoman Divacky /// properties for an implementation.
3660f22ef01cSRoman Divacky void CodeGenModule::EmitObjCPropertyImplementations(const
3661f22ef01cSRoman Divacky                                                     ObjCImplementationDecl *D) {
366259d1ed5bSDimitry Andric   for (const auto *PID : D->property_impls()) {
3663f22ef01cSRoman Divacky     // Dynamic is just for type-checking.
3664f22ef01cSRoman Divacky     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3665f22ef01cSRoman Divacky       ObjCPropertyDecl *PD = PID->getPropertyDecl();
3666f22ef01cSRoman Divacky 
3667f22ef01cSRoman Divacky       // Determine which methods need to be implemented, some may have
36683861d79fSDimitry Andric       // been overridden. Note that ::isPropertyAccessor is not the method
3669f22ef01cSRoman Divacky       // we want, that just indicates if the decl came from a
3670f22ef01cSRoman Divacky       // property. What we want to know is if the method is defined in
3671f22ef01cSRoman Divacky       // this implementation.
3672f22ef01cSRoman Divacky       if (!D->getInstanceMethod(PD->getGetterName()))
3673f22ef01cSRoman Divacky         CodeGenFunction(*this).GenerateObjCGetter(
3674f22ef01cSRoman Divacky                                  const_cast<ObjCImplementationDecl *>(D), PID);
3675f22ef01cSRoman Divacky       if (!PD->isReadOnly() &&
3676f22ef01cSRoman Divacky           !D->getInstanceMethod(PD->getSetterName()))
3677f22ef01cSRoman Divacky         CodeGenFunction(*this).GenerateObjCSetter(
3678f22ef01cSRoman Divacky                                  const_cast<ObjCImplementationDecl *>(D), PID);
3679f22ef01cSRoman Divacky     }
3680f22ef01cSRoman Divacky   }
3681f22ef01cSRoman Divacky }
3682f22ef01cSRoman Divacky 
36833b0f4066SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) {
36846122f3e6SDimitry Andric   const ObjCInterfaceDecl *iface = impl->getClassInterface();
36856122f3e6SDimitry Andric   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
36863b0f4066SDimitry Andric        ivar; ivar = ivar->getNextIvar())
36873b0f4066SDimitry Andric     if (ivar->getType().isDestructedType())
36883b0f4066SDimitry Andric       return true;
36893b0f4066SDimitry Andric 
36903b0f4066SDimitry Andric   return false;
36913b0f4066SDimitry Andric }
36923b0f4066SDimitry Andric 
369339d628a0SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM,
369439d628a0SDimitry Andric                                    ObjCImplementationDecl *D) {
369539d628a0SDimitry Andric   CodeGenFunction CGF(CGM);
369639d628a0SDimitry Andric   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
369739d628a0SDimitry Andric        E = D->init_end(); B != E; ++B) {
369839d628a0SDimitry Andric     CXXCtorInitializer *CtorInitExp = *B;
369939d628a0SDimitry Andric     Expr *Init = CtorInitExp->getInit();
370039d628a0SDimitry Andric     if (!CGF.isTrivialInitializer(Init))
370139d628a0SDimitry Andric       return false;
370239d628a0SDimitry Andric   }
370339d628a0SDimitry Andric   return true;
370439d628a0SDimitry Andric }
370539d628a0SDimitry Andric 
3706f22ef01cSRoman Divacky /// EmitObjCIvarInitializations - Emit information for ivar initialization
3707f22ef01cSRoman Divacky /// for an implementation.
3708f22ef01cSRoman Divacky void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
37093b0f4066SDimitry Andric   // We might need a .cxx_destruct even if we don't have any ivar initializers.
37103b0f4066SDimitry Andric   if (needsDestructMethod(D)) {
3711f22ef01cSRoman Divacky     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3712f22ef01cSRoman Divacky     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
37133b0f4066SDimitry Andric     ObjCMethodDecl *DTORMethod =
37143b0f4066SDimitry Andric       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
371559d1ed5bSDimitry Andric                              cxxSelector, getContext().VoidTy, nullptr, D,
37166122f3e6SDimitry Andric                              /*isInstance=*/true, /*isVariadic=*/false,
37173861d79fSDimitry Andric                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
37186122f3e6SDimitry Andric                              /*isDefined=*/false, ObjCMethodDecl::Required);
3719f22ef01cSRoman Divacky     D->addInstanceMethod(DTORMethod);
3720f22ef01cSRoman Divacky     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
37213861d79fSDimitry Andric     D->setHasDestructors(true);
37223b0f4066SDimitry Andric   }
3723f22ef01cSRoman Divacky 
37243b0f4066SDimitry Andric   // If the implementation doesn't have any ivar initializers, we don't need
37253b0f4066SDimitry Andric   // a .cxx_construct.
372639d628a0SDimitry Andric   if (D->getNumIvarInitializers() == 0 ||
372739d628a0SDimitry Andric       AllTrivialInitializers(*this, D))
37283b0f4066SDimitry Andric     return;
37293b0f4066SDimitry Andric 
37303b0f4066SDimitry Andric   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
37313b0f4066SDimitry Andric   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3732f22ef01cSRoman Divacky   // The constructor returns 'self'.
3733f22ef01cSRoman Divacky   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3734f22ef01cSRoman Divacky                                                 D->getLocation(),
37356122f3e6SDimitry Andric                                                 D->getLocation(),
37366122f3e6SDimitry Andric                                                 cxxSelector,
373759d1ed5bSDimitry Andric                                                 getContext().getObjCIdType(),
373859d1ed5bSDimitry Andric                                                 nullptr, D, /*isInstance=*/true,
37396122f3e6SDimitry Andric                                                 /*isVariadic=*/false,
37403861d79fSDimitry Andric                                                 /*isPropertyAccessor=*/true,
37416122f3e6SDimitry Andric                                                 /*isImplicitlyDeclared=*/true,
37426122f3e6SDimitry Andric                                                 /*isDefined=*/false,
3743f22ef01cSRoman Divacky                                                 ObjCMethodDecl::Required);
3744f22ef01cSRoman Divacky   D->addInstanceMethod(CTORMethod);
3745f22ef01cSRoman Divacky   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
37463861d79fSDimitry Andric   D->setHasNonZeroConstructors(true);
3747f22ef01cSRoman Divacky }
3748f22ef01cSRoman Divacky 
3749f22ef01cSRoman Divacky // EmitLinkageSpec - Emit all declarations in a linkage spec.
3750f22ef01cSRoman Divacky void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
3751f22ef01cSRoman Divacky   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3752f22ef01cSRoman Divacky       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
3753f22ef01cSRoman Divacky     ErrorUnsupported(LSD, "linkage spec");
3754f22ef01cSRoman Divacky     return;
3755f22ef01cSRoman Divacky   }
3756f22ef01cSRoman Divacky 
375744290647SDimitry Andric   EmitDeclContext(LSD);
375844290647SDimitry Andric }
375944290647SDimitry Andric 
376044290647SDimitry Andric void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
376144290647SDimitry Andric   for (auto *I : DC->decls()) {
376244290647SDimitry Andric     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
376344290647SDimitry Andric     // are themselves considered "top-level", so EmitTopLevelDecl on an
376444290647SDimitry Andric     // ObjCImplDecl does not recursively visit them. We need to do that in
376544290647SDimitry Andric     // case they're nested inside another construct (LinkageSpecDecl /
376644290647SDimitry Andric     // ExportDecl) that does stop them from being considered "top-level".
376759d1ed5bSDimitry Andric     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
376859d1ed5bSDimitry Andric       for (auto *M : OID->methods())
376959d1ed5bSDimitry Andric         EmitTopLevelDecl(M);
37703861d79fSDimitry Andric     }
377144290647SDimitry Andric 
377259d1ed5bSDimitry Andric     EmitTopLevelDecl(I);
3773f22ef01cSRoman Divacky   }
37743861d79fSDimitry Andric }
3775f22ef01cSRoman Divacky 
3776f22ef01cSRoman Divacky /// EmitTopLevelDecl - Emit code for a single top level declaration.
3777f22ef01cSRoman Divacky void CodeGenModule::EmitTopLevelDecl(Decl *D) {
3778f22ef01cSRoman Divacky   // Ignore dependent declarations.
3779f22ef01cSRoman Divacky   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3780f22ef01cSRoman Divacky     return;
3781f22ef01cSRoman Divacky 
3782f22ef01cSRoman Divacky   switch (D->getKind()) {
3783f22ef01cSRoman Divacky   case Decl::CXXConversion:
3784f22ef01cSRoman Divacky   case Decl::CXXMethod:
3785f22ef01cSRoman Divacky   case Decl::Function:
3786f22ef01cSRoman Divacky     // Skip function templates
37873b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
37883b0f4066SDimitry Andric         cast<FunctionDecl>(D)->isLateTemplateParsed())
3789f22ef01cSRoman Divacky       return;
3790f22ef01cSRoman Divacky 
3791f22ef01cSRoman Divacky     EmitGlobal(cast<FunctionDecl>(D));
379239d628a0SDimitry Andric     // Always provide some coverage mapping
379339d628a0SDimitry Andric     // even for the functions that aren't emitted.
379439d628a0SDimitry Andric     AddDeferredUnusedCoverageMapping(D);
3795f22ef01cSRoman Divacky     break;
3796f22ef01cSRoman Divacky 
37976bc11b14SDimitry Andric   case Decl::CXXDeductionGuide:
37986bc11b14SDimitry Andric     // Function-like, but does not result in code emission.
37996bc11b14SDimitry Andric     break;
38006bc11b14SDimitry Andric 
3801f22ef01cSRoman Divacky   case Decl::Var:
380244290647SDimitry Andric   case Decl::Decomposition:
3803f785676fSDimitry Andric     // Skip variable templates
3804f785676fSDimitry Andric     if (cast<VarDecl>(D)->getDescribedVarTemplate())
3805f785676fSDimitry Andric       return;
3806f785676fSDimitry Andric   case Decl::VarTemplateSpecialization:
3807f22ef01cSRoman Divacky     EmitGlobal(cast<VarDecl>(D));
380844290647SDimitry Andric     if (auto *DD = dyn_cast<DecompositionDecl>(D))
380944290647SDimitry Andric       for (auto *B : DD->bindings())
381044290647SDimitry Andric         if (auto *HD = B->getHoldingVar())
381144290647SDimitry Andric           EmitGlobal(HD);
3812f22ef01cSRoman Divacky     break;
3813f22ef01cSRoman Divacky 
38143b0f4066SDimitry Andric   // Indirect fields from global anonymous structs and unions can be
38153b0f4066SDimitry Andric   // ignored; only the actual variable requires IR gen support.
38163b0f4066SDimitry Andric   case Decl::IndirectField:
38173b0f4066SDimitry Andric     break;
38183b0f4066SDimitry Andric 
3819f22ef01cSRoman Divacky   // C++ Decls
3820f22ef01cSRoman Divacky   case Decl::Namespace:
382144290647SDimitry Andric     EmitDeclContext(cast<NamespaceDecl>(D));
3822f22ef01cSRoman Divacky     break;
3823e7145dcbSDimitry Andric   case Decl::CXXRecord:
382420e90f04SDimitry Andric     if (DebugInfo) {
382520e90f04SDimitry Andric       if (auto *ES = D->getASTContext().getExternalSource())
382620e90f04SDimitry Andric         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
382720e90f04SDimitry Andric           DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
382820e90f04SDimitry Andric     }
3829e7145dcbSDimitry Andric     // Emit any static data members, they may be definitions.
3830e7145dcbSDimitry Andric     for (auto *I : cast<CXXRecordDecl>(D)->decls())
3831e7145dcbSDimitry Andric       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
3832e7145dcbSDimitry Andric         EmitTopLevelDecl(I);
3833e7145dcbSDimitry Andric     break;
3834f22ef01cSRoman Divacky     // No code generation needed.
3835f22ef01cSRoman Divacky   case Decl::UsingShadow:
3836f22ef01cSRoman Divacky   case Decl::ClassTemplate:
3837f785676fSDimitry Andric   case Decl::VarTemplate:
3838f785676fSDimitry Andric   case Decl::VarTemplatePartialSpecialization:
3839f22ef01cSRoman Divacky   case Decl::FunctionTemplate:
3840bd5abe19SDimitry Andric   case Decl::TypeAliasTemplate:
3841bd5abe19SDimitry Andric   case Decl::Block:
3842139f7f9bSDimitry Andric   case Decl::Empty:
3843f22ef01cSRoman Divacky     break;
384459d1ed5bSDimitry Andric   case Decl::Using:          // using X; [C++]
384559d1ed5bSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
384659d1ed5bSDimitry Andric         DI->EmitUsingDecl(cast<UsingDecl>(*D));
384759d1ed5bSDimitry Andric     return;
3848f785676fSDimitry Andric   case Decl::NamespaceAlias:
3849f785676fSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
3850f785676fSDimitry Andric         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3851f785676fSDimitry Andric     return;
3852284c1978SDimitry Andric   case Decl::UsingDirective: // using namespace X; [C++]
3853284c1978SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
3854284c1978SDimitry Andric       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3855284c1978SDimitry Andric     return;
3856f22ef01cSRoman Divacky   case Decl::CXXConstructor:
3857f22ef01cSRoman Divacky     // Skip function templates
38583b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
38593b0f4066SDimitry Andric         cast<FunctionDecl>(D)->isLateTemplateParsed())
3860f22ef01cSRoman Divacky       return;
3861f22ef01cSRoman Divacky 
3862f785676fSDimitry Andric     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
3863f22ef01cSRoman Divacky     break;
3864f22ef01cSRoman Divacky   case Decl::CXXDestructor:
38653b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
38663b0f4066SDimitry Andric       return;
3867f785676fSDimitry Andric     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
3868f22ef01cSRoman Divacky     break;
3869f22ef01cSRoman Divacky 
3870f22ef01cSRoman Divacky   case Decl::StaticAssert:
3871f22ef01cSRoman Divacky     // Nothing to do.
3872f22ef01cSRoman Divacky     break;
3873f22ef01cSRoman Divacky 
3874f22ef01cSRoman Divacky   // Objective-C Decls
3875f22ef01cSRoman Divacky 
3876f22ef01cSRoman Divacky   // Forward declarations, no (immediate) code generation.
3877f22ef01cSRoman Divacky   case Decl::ObjCInterface:
38787ae0e2c9SDimitry Andric   case Decl::ObjCCategory:
3879f22ef01cSRoman Divacky     break;
3880f22ef01cSRoman Divacky 
3881dff0c46cSDimitry Andric   case Decl::ObjCProtocol: {
388259d1ed5bSDimitry Andric     auto *Proto = cast<ObjCProtocolDecl>(D);
3883dff0c46cSDimitry Andric     if (Proto->isThisDeclarationADefinition())
3884dff0c46cSDimitry Andric       ObjCRuntime->GenerateProtocol(Proto);
3885f22ef01cSRoman Divacky     break;
3886dff0c46cSDimitry Andric   }
3887f22ef01cSRoman Divacky 
3888f22ef01cSRoman Divacky   case Decl::ObjCCategoryImpl:
3889f22ef01cSRoman Divacky     // Categories have properties but don't support synthesize so we
3890f22ef01cSRoman Divacky     // can ignore them here.
38916122f3e6SDimitry Andric     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
3892f22ef01cSRoman Divacky     break;
3893f22ef01cSRoman Divacky 
3894f22ef01cSRoman Divacky   case Decl::ObjCImplementation: {
389559d1ed5bSDimitry Andric     auto *OMD = cast<ObjCImplementationDecl>(D);
3896f22ef01cSRoman Divacky     EmitObjCPropertyImplementations(OMD);
3897f22ef01cSRoman Divacky     EmitObjCIvarInitializations(OMD);
38986122f3e6SDimitry Andric     ObjCRuntime->GenerateClass(OMD);
3899dff0c46cSDimitry Andric     // Emit global variable debug information.
3900dff0c46cSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
3901e7145dcbSDimitry Andric       if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
3902139f7f9bSDimitry Andric         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3903139f7f9bSDimitry Andric             OMD->getClassInterface()), OMD->getLocation());
3904f22ef01cSRoman Divacky     break;
3905f22ef01cSRoman Divacky   }
3906f22ef01cSRoman Divacky   case Decl::ObjCMethod: {
390759d1ed5bSDimitry Andric     auto *OMD = cast<ObjCMethodDecl>(D);
3908f22ef01cSRoman Divacky     // If this is not a prototype, emit the body.
3909f22ef01cSRoman Divacky     if (OMD->getBody())
3910f22ef01cSRoman Divacky       CodeGenFunction(*this).GenerateObjCMethod(OMD);
3911f22ef01cSRoman Divacky     break;
3912f22ef01cSRoman Divacky   }
3913f22ef01cSRoman Divacky   case Decl::ObjCCompatibleAlias:
3914dff0c46cSDimitry Andric     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3915f22ef01cSRoman Divacky     break;
3916f22ef01cSRoman Divacky 
3917e7145dcbSDimitry Andric   case Decl::PragmaComment: {
3918e7145dcbSDimitry Andric     const auto *PCD = cast<PragmaCommentDecl>(D);
3919e7145dcbSDimitry Andric     switch (PCD->getCommentKind()) {
3920e7145dcbSDimitry Andric     case PCK_Unknown:
3921e7145dcbSDimitry Andric       llvm_unreachable("unexpected pragma comment kind");
3922e7145dcbSDimitry Andric     case PCK_Linker:
3923e7145dcbSDimitry Andric       AppendLinkerOptions(PCD->getArg());
3924e7145dcbSDimitry Andric       break;
3925e7145dcbSDimitry Andric     case PCK_Lib:
3926e7145dcbSDimitry Andric       AddDependentLib(PCD->getArg());
3927e7145dcbSDimitry Andric       break;
3928e7145dcbSDimitry Andric     case PCK_Compiler:
3929e7145dcbSDimitry Andric     case PCK_ExeStr:
3930e7145dcbSDimitry Andric     case PCK_User:
3931e7145dcbSDimitry Andric       break; // We ignore all of these.
3932e7145dcbSDimitry Andric     }
3933e7145dcbSDimitry Andric     break;
3934e7145dcbSDimitry Andric   }
3935e7145dcbSDimitry Andric 
3936e7145dcbSDimitry Andric   case Decl::PragmaDetectMismatch: {
3937e7145dcbSDimitry Andric     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
3938e7145dcbSDimitry Andric     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
3939e7145dcbSDimitry Andric     break;
3940e7145dcbSDimitry Andric   }
3941e7145dcbSDimitry Andric 
3942f22ef01cSRoman Divacky   case Decl::LinkageSpec:
3943f22ef01cSRoman Divacky     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
3944f22ef01cSRoman Divacky     break;
3945f22ef01cSRoman Divacky 
3946f22ef01cSRoman Divacky   case Decl::FileScopeAsm: {
394733956c43SDimitry Andric     // File-scope asm is ignored during device-side CUDA compilation.
394833956c43SDimitry Andric     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
394933956c43SDimitry Andric       break;
3950ea942507SDimitry Andric     // File-scope asm is ignored during device-side OpenMP compilation.
3951ea942507SDimitry Andric     if (LangOpts.OpenMPIsDevice)
3952ea942507SDimitry Andric       break;
395359d1ed5bSDimitry Andric     auto *AD = cast<FileScopeAsmDecl>(D);
395433956c43SDimitry Andric     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
3955f22ef01cSRoman Divacky     break;
3956f22ef01cSRoman Divacky   }
3957f22ef01cSRoman Divacky 
3958139f7f9bSDimitry Andric   case Decl::Import: {
395959d1ed5bSDimitry Andric     auto *Import = cast<ImportDecl>(D);
3960139f7f9bSDimitry Andric 
396144290647SDimitry Andric     // If we've already imported this module, we're done.
396244290647SDimitry Andric     if (!ImportedModules.insert(Import->getImportedModule()))
3963139f7f9bSDimitry Andric       break;
396444290647SDimitry Andric 
396544290647SDimitry Andric     // Emit debug information for direct imports.
396644290647SDimitry Andric     if (!Import->getImportedOwningModule()) {
39673dac3a9bSDimitry Andric       if (CGDebugInfo *DI = getModuleDebugInfo())
39683dac3a9bSDimitry Andric         DI->EmitImportDecl(*Import);
396944290647SDimitry Andric     }
3970139f7f9bSDimitry Andric 
397144290647SDimitry Andric     // Find all of the submodules and emit the module initializers.
397244290647SDimitry Andric     llvm::SmallPtrSet<clang::Module *, 16> Visited;
397344290647SDimitry Andric     SmallVector<clang::Module *, 16> Stack;
397444290647SDimitry Andric     Visited.insert(Import->getImportedModule());
397544290647SDimitry Andric     Stack.push_back(Import->getImportedModule());
397644290647SDimitry Andric 
397744290647SDimitry Andric     while (!Stack.empty()) {
397844290647SDimitry Andric       clang::Module *Mod = Stack.pop_back_val();
397944290647SDimitry Andric       if (!EmittedModuleInitializers.insert(Mod).second)
398044290647SDimitry Andric         continue;
398144290647SDimitry Andric 
398244290647SDimitry Andric       for (auto *D : Context.getModuleInitializers(Mod))
398344290647SDimitry Andric         EmitTopLevelDecl(D);
398444290647SDimitry Andric 
398544290647SDimitry Andric       // Visit the submodules of this module.
398644290647SDimitry Andric       for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
398744290647SDimitry Andric                                              SubEnd = Mod->submodule_end();
398844290647SDimitry Andric            Sub != SubEnd; ++Sub) {
398944290647SDimitry Andric         // Skip explicit children; they need to be explicitly imported to emit
399044290647SDimitry Andric         // the initializers.
399144290647SDimitry Andric         if ((*Sub)->IsExplicit)
399244290647SDimitry Andric           continue;
399344290647SDimitry Andric 
399444290647SDimitry Andric         if (Visited.insert(*Sub).second)
399544290647SDimitry Andric           Stack.push_back(*Sub);
399644290647SDimitry Andric       }
399744290647SDimitry Andric     }
3998139f7f9bSDimitry Andric     break;
3999139f7f9bSDimitry Andric   }
4000139f7f9bSDimitry Andric 
400144290647SDimitry Andric   case Decl::Export:
400244290647SDimitry Andric     EmitDeclContext(cast<ExportDecl>(D));
400344290647SDimitry Andric     break;
400444290647SDimitry Andric 
400539d628a0SDimitry Andric   case Decl::OMPThreadPrivate:
400639d628a0SDimitry Andric     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
400739d628a0SDimitry Andric     break;
400839d628a0SDimitry Andric 
400959d1ed5bSDimitry Andric   case Decl::ClassTemplateSpecialization: {
401059d1ed5bSDimitry Andric     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
401159d1ed5bSDimitry Andric     if (DebugInfo &&
401239d628a0SDimitry Andric         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
401339d628a0SDimitry Andric         Spec->hasDefinition())
401459d1ed5bSDimitry Andric       DebugInfo->completeTemplateDefinition(*Spec);
401539d628a0SDimitry Andric     break;
401659d1ed5bSDimitry Andric   }
401759d1ed5bSDimitry Andric 
4018e7145dcbSDimitry Andric   case Decl::OMPDeclareReduction:
4019e7145dcbSDimitry Andric     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
4020e7145dcbSDimitry Andric     break;
4021e7145dcbSDimitry Andric 
4022f22ef01cSRoman Divacky   default:
4023f22ef01cSRoman Divacky     // Make sure we handled everything we should, every other kind is a
4024f22ef01cSRoman Divacky     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
4025f22ef01cSRoman Divacky     // function. Need to recode Decl::Kind to do that easily.
4026f22ef01cSRoman Divacky     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
402739d628a0SDimitry Andric     break;
402839d628a0SDimitry Andric   }
402939d628a0SDimitry Andric }
403039d628a0SDimitry Andric 
403139d628a0SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
403239d628a0SDimitry Andric   // Do we need to generate coverage mapping?
403339d628a0SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
403439d628a0SDimitry Andric     return;
403539d628a0SDimitry Andric   switch (D->getKind()) {
403639d628a0SDimitry Andric   case Decl::CXXConversion:
403739d628a0SDimitry Andric   case Decl::CXXMethod:
403839d628a0SDimitry Andric   case Decl::Function:
403939d628a0SDimitry Andric   case Decl::ObjCMethod:
404039d628a0SDimitry Andric   case Decl::CXXConstructor:
404139d628a0SDimitry Andric   case Decl::CXXDestructor: {
40420623d748SDimitry Andric     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
404339d628a0SDimitry Andric       return;
404439d628a0SDimitry Andric     auto I = DeferredEmptyCoverageMappingDecls.find(D);
404539d628a0SDimitry Andric     if (I == DeferredEmptyCoverageMappingDecls.end())
404639d628a0SDimitry Andric       DeferredEmptyCoverageMappingDecls[D] = true;
404739d628a0SDimitry Andric     break;
404839d628a0SDimitry Andric   }
404939d628a0SDimitry Andric   default:
405039d628a0SDimitry Andric     break;
405139d628a0SDimitry Andric   };
405239d628a0SDimitry Andric }
405339d628a0SDimitry Andric 
405439d628a0SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
405539d628a0SDimitry Andric   // Do we need to generate coverage mapping?
405639d628a0SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
405739d628a0SDimitry Andric     return;
405839d628a0SDimitry Andric   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
405939d628a0SDimitry Andric     if (Fn->isTemplateInstantiation())
406039d628a0SDimitry Andric       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
406139d628a0SDimitry Andric   }
406239d628a0SDimitry Andric   auto I = DeferredEmptyCoverageMappingDecls.find(D);
406339d628a0SDimitry Andric   if (I == DeferredEmptyCoverageMappingDecls.end())
406439d628a0SDimitry Andric     DeferredEmptyCoverageMappingDecls[D] = false;
406539d628a0SDimitry Andric   else
406639d628a0SDimitry Andric     I->second = false;
406739d628a0SDimitry Andric }
406839d628a0SDimitry Andric 
406939d628a0SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
407039d628a0SDimitry Andric   std::vector<const Decl *> DeferredDecls;
407133956c43SDimitry Andric   for (const auto &I : DeferredEmptyCoverageMappingDecls) {
407239d628a0SDimitry Andric     if (!I.second)
407339d628a0SDimitry Andric       continue;
407439d628a0SDimitry Andric     DeferredDecls.push_back(I.first);
407539d628a0SDimitry Andric   }
407639d628a0SDimitry Andric   // Sort the declarations by their location to make sure that the tests get a
407739d628a0SDimitry Andric   // predictable order for the coverage mapping for the unused declarations.
407839d628a0SDimitry Andric   if (CodeGenOpts.DumpCoverageMapping)
407939d628a0SDimitry Andric     std::sort(DeferredDecls.begin(), DeferredDecls.end(),
408039d628a0SDimitry Andric               [] (const Decl *LHS, const Decl *RHS) {
408139d628a0SDimitry Andric       return LHS->getLocStart() < RHS->getLocStart();
408239d628a0SDimitry Andric     });
408339d628a0SDimitry Andric   for (const auto *D : DeferredDecls) {
408439d628a0SDimitry Andric     switch (D->getKind()) {
408539d628a0SDimitry Andric     case Decl::CXXConversion:
408639d628a0SDimitry Andric     case Decl::CXXMethod:
408739d628a0SDimitry Andric     case Decl::Function:
408839d628a0SDimitry Andric     case Decl::ObjCMethod: {
408939d628a0SDimitry Andric       CodeGenPGO PGO(*this);
409039d628a0SDimitry Andric       GlobalDecl GD(cast<FunctionDecl>(D));
409139d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
409239d628a0SDimitry Andric                                   getFunctionLinkage(GD));
409339d628a0SDimitry Andric       break;
409439d628a0SDimitry Andric     }
409539d628a0SDimitry Andric     case Decl::CXXConstructor: {
409639d628a0SDimitry Andric       CodeGenPGO PGO(*this);
409739d628a0SDimitry Andric       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
409839d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
409939d628a0SDimitry Andric                                   getFunctionLinkage(GD));
410039d628a0SDimitry Andric       break;
410139d628a0SDimitry Andric     }
410239d628a0SDimitry Andric     case Decl::CXXDestructor: {
410339d628a0SDimitry Andric       CodeGenPGO PGO(*this);
410439d628a0SDimitry Andric       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
410539d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
410639d628a0SDimitry Andric                                   getFunctionLinkage(GD));
410739d628a0SDimitry Andric       break;
410839d628a0SDimitry Andric     }
410939d628a0SDimitry Andric     default:
411039d628a0SDimitry Andric       break;
411139d628a0SDimitry Andric     };
4112f22ef01cSRoman Divacky   }
4113f22ef01cSRoman Divacky }
4114ffd1746dSEd Schouten 
4115ffd1746dSEd Schouten /// Turns the given pointer into a constant.
4116ffd1746dSEd Schouten static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
4117ffd1746dSEd Schouten                                           const void *Ptr) {
4118ffd1746dSEd Schouten   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
41196122f3e6SDimitry Andric   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
4120ffd1746dSEd Schouten   return llvm::ConstantInt::get(i64, PtrInt);
4121ffd1746dSEd Schouten }
4122ffd1746dSEd Schouten 
4123ffd1746dSEd Schouten static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
4124ffd1746dSEd Schouten                                    llvm::NamedMDNode *&GlobalMetadata,
4125ffd1746dSEd Schouten                                    GlobalDecl D,
4126ffd1746dSEd Schouten                                    llvm::GlobalValue *Addr) {
4127ffd1746dSEd Schouten   if (!GlobalMetadata)
4128ffd1746dSEd Schouten     GlobalMetadata =
4129ffd1746dSEd Schouten       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
4130ffd1746dSEd Schouten 
4131ffd1746dSEd Schouten   // TODO: should we report variant information for ctors/dtors?
413239d628a0SDimitry Andric   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
413339d628a0SDimitry Andric                            llvm::ConstantAsMetadata::get(GetPointerConstant(
413439d628a0SDimitry Andric                                CGM.getLLVMContext(), D.getDecl()))};
41353b0f4066SDimitry Andric   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
4136ffd1746dSEd Schouten }
4137ffd1746dSEd Schouten 
4138284c1978SDimitry Andric /// For each function which is declared within an extern "C" region and marked
4139284c1978SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled
4140284c1978SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer
4141284c1978SDimitry Andric /// to such functions with an unmangled name from inline assembly within the
4142284c1978SDimitry Andric /// same translation unit.
4143284c1978SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() {
4144e7145dcbSDimitry Andric   // Don't do anything if we're generating CUDA device code -- the NVPTX
4145e7145dcbSDimitry Andric   // assembly target doesn't support aliases.
4146e7145dcbSDimitry Andric   if (Context.getTargetInfo().getTriple().isNVPTX())
4147e7145dcbSDimitry Andric     return;
41488f0fd8f6SDimitry Andric   for (auto &I : StaticExternCValues) {
41498f0fd8f6SDimitry Andric     IdentifierInfo *Name = I.first;
41508f0fd8f6SDimitry Andric     llvm::GlobalValue *Val = I.second;
4151284c1978SDimitry Andric     if (Val && !getModule().getNamedValue(Name->getName()))
415259d1ed5bSDimitry Andric       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
4153284c1978SDimitry Andric   }
4154284c1978SDimitry Andric }
4155284c1978SDimitry Andric 
415659d1ed5bSDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
415759d1ed5bSDimitry Andric                                              GlobalDecl &Result) const {
415859d1ed5bSDimitry Andric   auto Res = Manglings.find(MangledName);
415959d1ed5bSDimitry Andric   if (Res == Manglings.end())
416059d1ed5bSDimitry Andric     return false;
416159d1ed5bSDimitry Andric   Result = Res->getValue();
416259d1ed5bSDimitry Andric   return true;
416359d1ed5bSDimitry Andric }
416459d1ed5bSDimitry Andric 
4165ffd1746dSEd Schouten /// Emits metadata nodes associating all the global values in the
4166ffd1746dSEd Schouten /// current module with the Decls they came from.  This is useful for
4167ffd1746dSEd Schouten /// projects using IR gen as a subroutine.
4168ffd1746dSEd Schouten ///
4169ffd1746dSEd Schouten /// Since there's currently no way to associate an MDNode directly
4170ffd1746dSEd Schouten /// with an llvm::GlobalValue, we create a global named metadata
4171ffd1746dSEd Schouten /// with the name 'clang.global.decl.ptrs'.
4172ffd1746dSEd Schouten void CodeGenModule::EmitDeclMetadata() {
417359d1ed5bSDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
4174ffd1746dSEd Schouten 
417559d1ed5bSDimitry Andric   for (auto &I : MangledDeclNames) {
417659d1ed5bSDimitry Andric     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
41770623d748SDimitry Andric     // Some mangled names don't necessarily have an associated GlobalValue
41780623d748SDimitry Andric     // in this module, e.g. if we mangled it for DebugInfo.
41790623d748SDimitry Andric     if (Addr)
418059d1ed5bSDimitry Andric       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
4181ffd1746dSEd Schouten   }
4182ffd1746dSEd Schouten }
4183ffd1746dSEd Schouten 
4184ffd1746dSEd Schouten /// Emits metadata nodes for all the local variables in the current
4185ffd1746dSEd Schouten /// function.
4186ffd1746dSEd Schouten void CodeGenFunction::EmitDeclMetadata() {
4187ffd1746dSEd Schouten   if (LocalDeclMap.empty()) return;
4188ffd1746dSEd Schouten 
4189ffd1746dSEd Schouten   llvm::LLVMContext &Context = getLLVMContext();
4190ffd1746dSEd Schouten 
4191ffd1746dSEd Schouten   // Find the unique metadata ID for this name.
4192ffd1746dSEd Schouten   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
4193ffd1746dSEd Schouten 
419459d1ed5bSDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
4195ffd1746dSEd Schouten 
419659d1ed5bSDimitry Andric   for (auto &I : LocalDeclMap) {
419759d1ed5bSDimitry Andric     const Decl *D = I.first;
41980623d748SDimitry Andric     llvm::Value *Addr = I.second.getPointer();
419959d1ed5bSDimitry Andric     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
4200ffd1746dSEd Schouten       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
420139d628a0SDimitry Andric       Alloca->setMetadata(
420239d628a0SDimitry Andric           DeclPtrKind, llvm::MDNode::get(
420339d628a0SDimitry Andric                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
420459d1ed5bSDimitry Andric     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
4205ffd1746dSEd Schouten       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
4206ffd1746dSEd Schouten       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
4207ffd1746dSEd Schouten     }
4208ffd1746dSEd Schouten   }
4209ffd1746dSEd Schouten }
4210e580952dSDimitry Andric 
4211f785676fSDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() {
4212f785676fSDimitry Andric   llvm::NamedMDNode *IdentMetadata =
4213f785676fSDimitry Andric     TheModule.getOrInsertNamedMetadata("llvm.ident");
4214f785676fSDimitry Andric   std::string Version = getClangFullVersion();
4215f785676fSDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
4216f785676fSDimitry Andric 
421739d628a0SDimitry Andric   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
4218f785676fSDimitry Andric   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4219f785676fSDimitry Andric }
4220f785676fSDimitry Andric 
422159d1ed5bSDimitry Andric void CodeGenModule::EmitTargetMetadata() {
422239d628a0SDimitry Andric   // Warning, new MangledDeclNames may be appended within this loop.
422339d628a0SDimitry Andric   // We rely on MapVector insertions adding new elements to the end
422439d628a0SDimitry Andric   // of the container.
422539d628a0SDimitry Andric   // FIXME: Move this loop into the one target that needs it, and only
422639d628a0SDimitry Andric   // loop over those declarations for which we couldn't emit the target
422739d628a0SDimitry Andric   // metadata when we emitted the declaration.
422839d628a0SDimitry Andric   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
422939d628a0SDimitry Andric     auto Val = *(MangledDeclNames.begin() + I);
423039d628a0SDimitry Andric     const Decl *D = Val.first.getDecl()->getMostRecentDecl();
423139d628a0SDimitry Andric     llvm::GlobalValue *GV = GetGlobalValue(Val.second);
423259d1ed5bSDimitry Andric     getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
423359d1ed5bSDimitry Andric   }
423459d1ed5bSDimitry Andric }
423559d1ed5bSDimitry Andric 
4236bd5abe19SDimitry Andric void CodeGenModule::EmitCoverageFile() {
423744290647SDimitry Andric   if (getCodeGenOpts().CoverageDataFile.empty() &&
423844290647SDimitry Andric       getCodeGenOpts().CoverageNotesFile.empty())
423944290647SDimitry Andric     return;
424044290647SDimitry Andric 
424144290647SDimitry Andric   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
424244290647SDimitry Andric   if (!CUNode)
424344290647SDimitry Andric     return;
424444290647SDimitry Andric 
4245bd5abe19SDimitry Andric   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
4246bd5abe19SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
424744290647SDimitry Andric   auto *CoverageDataFile =
424844290647SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
424944290647SDimitry Andric   auto *CoverageNotesFile =
425044290647SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
4251bd5abe19SDimitry Andric   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
4252bd5abe19SDimitry Andric     llvm::MDNode *CU = CUNode->getOperand(i);
425344290647SDimitry Andric     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
425439d628a0SDimitry Andric     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
4255bd5abe19SDimitry Andric   }
4256bd5abe19SDimitry Andric }
42573861d79fSDimitry Andric 
425839d628a0SDimitry Andric llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
42593861d79fSDimitry Andric   // Sema has checked that all uuid strings are of the form
42603861d79fSDimitry Andric   // "12345678-1234-1234-1234-1234567890ab".
42613861d79fSDimitry Andric   assert(Uuid.size() == 36);
4262f785676fSDimitry Andric   for (unsigned i = 0; i < 36; ++i) {
4263f785676fSDimitry Andric     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
4264f785676fSDimitry Andric     else                                         assert(isHexDigit(Uuid[i]));
42653861d79fSDimitry Andric   }
42663861d79fSDimitry Andric 
426739d628a0SDimitry Andric   // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
4268f785676fSDimitry Andric   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
42693861d79fSDimitry Andric 
4270f785676fSDimitry Andric   llvm::Constant *Field3[8];
4271f785676fSDimitry Andric   for (unsigned Idx = 0; Idx < 8; ++Idx)
4272f785676fSDimitry Andric     Field3[Idx] = llvm::ConstantInt::get(
4273f785676fSDimitry Andric         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
42743861d79fSDimitry Andric 
4275f785676fSDimitry Andric   llvm::Constant *Fields[4] = {
4276f785676fSDimitry Andric     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
4277f785676fSDimitry Andric     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
4278f785676fSDimitry Andric     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
4279f785676fSDimitry Andric     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
4280f785676fSDimitry Andric   };
4281f785676fSDimitry Andric 
4282f785676fSDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
42833861d79fSDimitry Andric }
428459d1ed5bSDimitry Andric 
428559d1ed5bSDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
428659d1ed5bSDimitry Andric                                                        bool ForEH) {
428759d1ed5bSDimitry Andric   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
428859d1ed5bSDimitry Andric   // FIXME: should we even be calling this method if RTTI is disabled
428959d1ed5bSDimitry Andric   // and it's not for EH?
429059d1ed5bSDimitry Andric   if (!ForEH && !getLangOpts().RTTI)
429159d1ed5bSDimitry Andric     return llvm::Constant::getNullValue(Int8PtrTy);
429259d1ed5bSDimitry Andric 
429359d1ed5bSDimitry Andric   if (ForEH && Ty->isObjCObjectPointerType() &&
429459d1ed5bSDimitry Andric       LangOpts.ObjCRuntime.isGNUFamily())
429559d1ed5bSDimitry Andric     return ObjCRuntime->GetEHType(Ty);
429659d1ed5bSDimitry Andric 
429759d1ed5bSDimitry Andric   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
429859d1ed5bSDimitry Andric }
429959d1ed5bSDimitry Andric 
430039d628a0SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
430139d628a0SDimitry Andric   for (auto RefExpr : D->varlists()) {
430239d628a0SDimitry Andric     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
430339d628a0SDimitry Andric     bool PerformInit =
430439d628a0SDimitry Andric         VD->getAnyInitializer() &&
430539d628a0SDimitry Andric         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
430639d628a0SDimitry Andric                                                         /*ForRef=*/false);
43070623d748SDimitry Andric 
43080623d748SDimitry Andric     Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
430933956c43SDimitry Andric     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
43100623d748SDimitry Andric             VD, Addr, RefExpr->getLocStart(), PerformInit))
431139d628a0SDimitry Andric       CXXGlobalInits.push_back(InitFunction);
431239d628a0SDimitry Andric   }
431339d628a0SDimitry Andric }
43148f0fd8f6SDimitry Andric 
43150623d748SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
43160623d748SDimitry Andric   llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
43170623d748SDimitry Andric   if (InternalId)
43180623d748SDimitry Andric     return InternalId;
43190623d748SDimitry Andric 
43200623d748SDimitry Andric   if (isExternallyVisible(T->getLinkage())) {
43218f0fd8f6SDimitry Andric     std::string OutName;
43228f0fd8f6SDimitry Andric     llvm::raw_string_ostream Out(OutName);
43230623d748SDimitry Andric     getCXXABI().getMangleContext().mangleTypeName(T, Out);
43248f0fd8f6SDimitry Andric 
43250623d748SDimitry Andric     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
43260623d748SDimitry Andric   } else {
43270623d748SDimitry Andric     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
43280623d748SDimitry Andric                                            llvm::ArrayRef<llvm::Metadata *>());
43290623d748SDimitry Andric   }
43300623d748SDimitry Andric 
43310623d748SDimitry Andric   return InternalId;
43320623d748SDimitry Andric }
43330623d748SDimitry Andric 
4334e7145dcbSDimitry Andric /// Returns whether this module needs the "all-vtables" type identifier.
4335e7145dcbSDimitry Andric bool CodeGenModule::NeedAllVtablesTypeId() const {
4336e7145dcbSDimitry Andric   // Returns true if at least one of vtable-based CFI checkers is enabled and
4337e7145dcbSDimitry Andric   // is not in the trapping mode.
4338e7145dcbSDimitry Andric   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
4339e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
4340e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
4341e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
4342e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
4343e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
4344e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
4345e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
4346e7145dcbSDimitry Andric }
4347e7145dcbSDimitry Andric 
4348e7145dcbSDimitry Andric void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
43490623d748SDimitry Andric                                           CharUnits Offset,
43500623d748SDimitry Andric                                           const CXXRecordDecl *RD) {
43510623d748SDimitry Andric   llvm::Metadata *MD =
43520623d748SDimitry Andric       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
4353e7145dcbSDimitry Andric   VTable->addTypeMetadata(Offset.getQuantity(), MD);
43540623d748SDimitry Andric 
4355e7145dcbSDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
4356e7145dcbSDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
4357e7145dcbSDimitry Andric       VTable->addTypeMetadata(Offset.getQuantity(),
4358e7145dcbSDimitry Andric                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
4359e7145dcbSDimitry Andric 
4360e7145dcbSDimitry Andric   if (NeedAllVtablesTypeId()) {
4361e7145dcbSDimitry Andric     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
4362e7145dcbSDimitry Andric     VTable->addTypeMetadata(Offset.getQuantity(), MD);
43630623d748SDimitry Andric   }
43640623d748SDimitry Andric }
43650623d748SDimitry Andric 
43660623d748SDimitry Andric // Fills in the supplied string map with the set of target features for the
43670623d748SDimitry Andric // passed in function.
43680623d748SDimitry Andric void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
43690623d748SDimitry Andric                                           const FunctionDecl *FD) {
43700623d748SDimitry Andric   StringRef TargetCPU = Target.getTargetOpts().CPU;
43710623d748SDimitry Andric   if (const auto *TD = FD->getAttr<TargetAttr>()) {
43720623d748SDimitry Andric     // If we have a TargetAttr build up the feature map based on that.
43730623d748SDimitry Andric     TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
43740623d748SDimitry Andric 
43750623d748SDimitry Andric     // Make a copy of the features as passed on the command line into the
43760623d748SDimitry Andric     // beginning of the additional features from the function to override.
43770623d748SDimitry Andric     ParsedAttr.first.insert(ParsedAttr.first.begin(),
43780623d748SDimitry Andric                             Target.getTargetOpts().FeaturesAsWritten.begin(),
43790623d748SDimitry Andric                             Target.getTargetOpts().FeaturesAsWritten.end());
43800623d748SDimitry Andric 
43810623d748SDimitry Andric     if (ParsedAttr.second != "")
43820623d748SDimitry Andric       TargetCPU = ParsedAttr.second;
43830623d748SDimitry Andric 
43840623d748SDimitry Andric     // Now populate the feature map, first with the TargetCPU which is either
43850623d748SDimitry Andric     // the default or a new one from the target attribute string. Then we'll use
43860623d748SDimitry Andric     // the passed in features (FeaturesAsWritten) along with the new ones from
43870623d748SDimitry Andric     // the attribute.
43880623d748SDimitry Andric     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first);
43890623d748SDimitry Andric   } else {
43900623d748SDimitry Andric     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
43910623d748SDimitry Andric                           Target.getTargetOpts().Features);
43920623d748SDimitry Andric   }
43938f0fd8f6SDimitry Andric }
4394e7145dcbSDimitry Andric 
4395e7145dcbSDimitry Andric llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
4396e7145dcbSDimitry Andric   if (!SanStats)
4397e7145dcbSDimitry Andric     SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
4398e7145dcbSDimitry Andric 
4399e7145dcbSDimitry Andric   return *SanStats;
4400e7145dcbSDimitry Andric }
440144290647SDimitry Andric llvm::Value *
440244290647SDimitry Andric CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
440344290647SDimitry Andric                                                   CodeGenFunction &CGF) {
440444290647SDimitry Andric   llvm::Constant *C = EmitConstantExpr(E, E->getType(), &CGF);
440544290647SDimitry Andric   auto SamplerT = getOpenCLRuntime().getSamplerType();
440644290647SDimitry Andric   auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
440744290647SDimitry Andric   return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
440844290647SDimitry Andric                                 "__translate_sampler_initializer"),
440944290647SDimitry Andric                                 {C});
441044290647SDimitry Andric }
4411