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) {
56851690af2SDimitry Andric   I->setMetadata(llvm::LLVMContext::MD_invariant_group,
56951690af2SDimitry Andric                  llvm::MDNode::get(getLLVMContext(), {}));
5700623d748SDimitry Andric }
5710623d748SDimitry Andric 
57259d1ed5bSDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) {
57359d1ed5bSDimitry Andric   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
57459d1ed5bSDimitry Andric   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
575f22ef01cSRoman Divacky }
576f22ef01cSRoman Divacky 
577f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
578f22ef01cSRoman Divacky /// specified stmt yet.
579f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
5806122f3e6SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
581f22ef01cSRoman Divacky                                                "cannot compile this %0 yet");
582f22ef01cSRoman Divacky   std::string Msg = Type;
583f22ef01cSRoman Divacky   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
584f22ef01cSRoman Divacky     << Msg << S->getSourceRange();
585f22ef01cSRoman Divacky }
586f22ef01cSRoman Divacky 
587f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
588f22ef01cSRoman Divacky /// specified decl yet.
589f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
5906122f3e6SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
591f22ef01cSRoman Divacky                                                "cannot compile this %0 yet");
592f22ef01cSRoman Divacky   std::string Msg = Type;
593f22ef01cSRoman Divacky   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
594f22ef01cSRoman Divacky }
595f22ef01cSRoman Divacky 
59617a519f9SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
59717a519f9SDimitry Andric   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
59817a519f9SDimitry Andric }
59917a519f9SDimitry Andric 
600f22ef01cSRoman Divacky void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
6012754fe60SDimitry Andric                                         const NamedDecl *D) const {
602f22ef01cSRoman Divacky   // Internal definitions always have default visibility.
603f22ef01cSRoman Divacky   if (GV->hasLocalLinkage()) {
604f22ef01cSRoman Divacky     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
605f22ef01cSRoman Divacky     return;
606f22ef01cSRoman Divacky   }
607f22ef01cSRoman Divacky 
6082754fe60SDimitry Andric   // Set visibility for definitions.
609139f7f9bSDimitry Andric   LinkageInfo LV = D->getLinkageAndVisibility();
610139f7f9bSDimitry Andric   if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
611139f7f9bSDimitry Andric     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
612f22ef01cSRoman Divacky }
613f22ef01cSRoman Divacky 
6147ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
6157ae0e2c9SDimitry Andric   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
6167ae0e2c9SDimitry Andric       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
6177ae0e2c9SDimitry Andric       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
6187ae0e2c9SDimitry Andric       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
6197ae0e2c9SDimitry Andric       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
6207ae0e2c9SDimitry Andric }
6217ae0e2c9SDimitry Andric 
6227ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
6237ae0e2c9SDimitry Andric     CodeGenOptions::TLSModel M) {
6247ae0e2c9SDimitry Andric   switch (M) {
6257ae0e2c9SDimitry Andric   case CodeGenOptions::GeneralDynamicTLSModel:
6267ae0e2c9SDimitry Andric     return llvm::GlobalVariable::GeneralDynamicTLSModel;
6277ae0e2c9SDimitry Andric   case CodeGenOptions::LocalDynamicTLSModel:
6287ae0e2c9SDimitry Andric     return llvm::GlobalVariable::LocalDynamicTLSModel;
6297ae0e2c9SDimitry Andric   case CodeGenOptions::InitialExecTLSModel:
6307ae0e2c9SDimitry Andric     return llvm::GlobalVariable::InitialExecTLSModel;
6317ae0e2c9SDimitry Andric   case CodeGenOptions::LocalExecTLSModel:
6327ae0e2c9SDimitry Andric     return llvm::GlobalVariable::LocalExecTLSModel;
6337ae0e2c9SDimitry Andric   }
6347ae0e2c9SDimitry Andric   llvm_unreachable("Invalid TLS model!");
6357ae0e2c9SDimitry Andric }
6367ae0e2c9SDimitry Andric 
63739d628a0SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
638284c1978SDimitry Andric   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
6397ae0e2c9SDimitry Andric 
64039d628a0SDimitry Andric   llvm::GlobalValue::ThreadLocalMode TLM;
6413861d79fSDimitry Andric   TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
6427ae0e2c9SDimitry Andric 
6437ae0e2c9SDimitry Andric   // Override the TLS model if it is explicitly specified.
64459d1ed5bSDimitry Andric   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
6457ae0e2c9SDimitry Andric     TLM = GetLLVMTLSModel(Attr->getModel());
6467ae0e2c9SDimitry Andric   }
6477ae0e2c9SDimitry Andric 
6487ae0e2c9SDimitry Andric   GV->setThreadLocalMode(TLM);
6497ae0e2c9SDimitry Andric }
6507ae0e2c9SDimitry Andric 
6516122f3e6SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
652444ed5c5SDimitry Andric   GlobalDecl CanonicalGD = GD.getCanonicalDecl();
653444ed5c5SDimitry Andric 
654444ed5c5SDimitry Andric   // Some ABIs don't have constructor variants.  Make sure that base and
655444ed5c5SDimitry Andric   // complete constructors get mangled the same.
656444ed5c5SDimitry Andric   if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
657444ed5c5SDimitry Andric     if (!getTarget().getCXXABI().hasConstructorVariants()) {
658444ed5c5SDimitry Andric       CXXCtorType OrigCtorType = GD.getCtorType();
659444ed5c5SDimitry Andric       assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
660444ed5c5SDimitry Andric       if (OrigCtorType == Ctor_Base)
661444ed5c5SDimitry Andric         CanonicalGD = GlobalDecl(CD, Ctor_Complete);
662444ed5c5SDimitry Andric     }
663444ed5c5SDimitry Andric   }
664444ed5c5SDimitry Andric 
665444ed5c5SDimitry Andric   StringRef &FoundStr = MangledDeclNames[CanonicalGD];
66659d1ed5bSDimitry Andric   if (!FoundStr.empty())
66759d1ed5bSDimitry Andric     return FoundStr;
668f22ef01cSRoman Divacky 
66959d1ed5bSDimitry Andric   const auto *ND = cast<NamedDecl>(GD.getDecl());
670dff0c46cSDimitry Andric   SmallString<256> Buffer;
67159d1ed5bSDimitry Andric   StringRef Str;
67259d1ed5bSDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
6732754fe60SDimitry Andric     llvm::raw_svector_ostream Out(Buffer);
67459d1ed5bSDimitry Andric     if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
6752754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
67659d1ed5bSDimitry Andric     else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
6772754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
678ffd1746dSEd Schouten     else
6792754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleName(ND, Out);
68059d1ed5bSDimitry Andric     Str = Out.str();
68159d1ed5bSDimitry Andric   } else {
68259d1ed5bSDimitry Andric     IdentifierInfo *II = ND->getIdentifier();
68359d1ed5bSDimitry Andric     assert(II && "Attempt to mangle unnamed decl.");
68444290647SDimitry Andric     const auto *FD = dyn_cast<FunctionDecl>(ND);
68544290647SDimitry Andric 
68644290647SDimitry Andric     if (FD &&
68744290647SDimitry Andric         FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
68844290647SDimitry Andric       llvm::raw_svector_ostream Out(Buffer);
68944290647SDimitry Andric       Out << "__regcall3__" << II->getName();
69044290647SDimitry Andric       Str = Out.str();
69144290647SDimitry Andric     } else {
69259d1ed5bSDimitry Andric       Str = II->getName();
693ffd1746dSEd Schouten     }
69444290647SDimitry Andric   }
695ffd1746dSEd Schouten 
69639d628a0SDimitry Andric   // Keep the first result in the case of a mangling collision.
69739d628a0SDimitry Andric   auto Result = Manglings.insert(std::make_pair(Str, GD));
69839d628a0SDimitry Andric   return FoundStr = Result.first->first();
69959d1ed5bSDimitry Andric }
70059d1ed5bSDimitry Andric 
70159d1ed5bSDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
702ffd1746dSEd Schouten                                              const BlockDecl *BD) {
7032754fe60SDimitry Andric   MangleContext &MangleCtx = getCXXABI().getMangleContext();
7042754fe60SDimitry Andric   const Decl *D = GD.getDecl();
70559d1ed5bSDimitry Andric 
70659d1ed5bSDimitry Andric   SmallString<256> Buffer;
70759d1ed5bSDimitry Andric   llvm::raw_svector_ostream Out(Buffer);
70859d1ed5bSDimitry Andric   if (!D)
7097ae0e2c9SDimitry Andric     MangleCtx.mangleGlobalBlock(BD,
7107ae0e2c9SDimitry Andric       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
71159d1ed5bSDimitry Andric   else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
7122754fe60SDimitry Andric     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
71359d1ed5bSDimitry Andric   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
7142754fe60SDimitry Andric     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
7152754fe60SDimitry Andric   else
7162754fe60SDimitry Andric     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
71759d1ed5bSDimitry Andric 
71839d628a0SDimitry Andric   auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
71939d628a0SDimitry Andric   return Result.first->first();
720f22ef01cSRoman Divacky }
721f22ef01cSRoman Divacky 
7226122f3e6SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
723f22ef01cSRoman Divacky   return getModule().getNamedValue(Name);
724f22ef01cSRoman Divacky }
725f22ef01cSRoman Divacky 
726f22ef01cSRoman Divacky /// AddGlobalCtor - Add a function to the list that will be called before
727f22ef01cSRoman Divacky /// main() runs.
72859d1ed5bSDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
72959d1ed5bSDimitry Andric                                   llvm::Constant *AssociatedData) {
730f22ef01cSRoman Divacky   // FIXME: Type coercion of void()* types.
73159d1ed5bSDimitry Andric   GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
732f22ef01cSRoman Divacky }
733f22ef01cSRoman Divacky 
734f22ef01cSRoman Divacky /// AddGlobalDtor - Add a function to the list that will be called
735f22ef01cSRoman Divacky /// when the module is unloaded.
736f22ef01cSRoman Divacky void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
737f22ef01cSRoman Divacky   // FIXME: Type coercion of void()* types.
73859d1ed5bSDimitry Andric   GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
739f22ef01cSRoman Divacky }
740f22ef01cSRoman Divacky 
74144290647SDimitry Andric void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
74244290647SDimitry Andric   if (Fns.empty()) return;
74344290647SDimitry Andric 
744f22ef01cSRoman Divacky   // Ctor function type is void()*.
745bd5abe19SDimitry Andric   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
746f22ef01cSRoman Divacky   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
747f22ef01cSRoman Divacky 
74859d1ed5bSDimitry Andric   // Get the type of a ctor entry, { i32, void ()*, i8* }.
74959d1ed5bSDimitry Andric   llvm::StructType *CtorStructTy = llvm::StructType::get(
75039d628a0SDimitry Andric       Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr);
751f22ef01cSRoman Divacky 
752f22ef01cSRoman Divacky   // Construct the constructor and destructor arrays.
75344290647SDimitry Andric   ConstantInitBuilder builder(*this);
75444290647SDimitry Andric   auto ctors = builder.beginArray(CtorStructTy);
7558f0fd8f6SDimitry Andric   for (const auto &I : Fns) {
75644290647SDimitry Andric     auto ctor = ctors.beginStruct(CtorStructTy);
75744290647SDimitry Andric     ctor.addInt(Int32Ty, I.Priority);
75844290647SDimitry Andric     ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
75944290647SDimitry Andric     if (I.AssociatedData)
76044290647SDimitry Andric       ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
76144290647SDimitry Andric     else
76244290647SDimitry Andric       ctor.addNullPointer(VoidPtrTy);
76344290647SDimitry Andric     ctor.finishAndAddTo(ctors);
764f22ef01cSRoman Divacky   }
765f22ef01cSRoman Divacky 
76644290647SDimitry Andric   auto list =
76744290647SDimitry Andric     ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
76844290647SDimitry Andric                                 /*constant*/ false,
76944290647SDimitry Andric                                 llvm::GlobalValue::AppendingLinkage);
77044290647SDimitry Andric 
77144290647SDimitry Andric   // The LTO linker doesn't seem to like it when we set an alignment
77244290647SDimitry Andric   // on appending variables.  Take it off as a workaround.
77344290647SDimitry Andric   list->setAlignment(0);
77444290647SDimitry Andric 
77544290647SDimitry Andric   Fns.clear();
776f22ef01cSRoman Divacky }
777f22ef01cSRoman Divacky 
778f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes
779f785676fSDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
78059d1ed5bSDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
781f785676fSDimitry Andric 
782e580952dSDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
783f22ef01cSRoman Divacky 
78459d1ed5bSDimitry Andric   if (isa<CXXDestructorDecl>(D) &&
78559d1ed5bSDimitry Andric       getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
78659d1ed5bSDimitry Andric                                          GD.getDtorType())) {
78759d1ed5bSDimitry Andric     // Destructor variants in the Microsoft C++ ABI are always internal or
78859d1ed5bSDimitry Andric     // linkonce_odr thunks emitted on an as-needed basis.
78959d1ed5bSDimitry Andric     return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
79059d1ed5bSDimitry Andric                                    : llvm::GlobalValue::LinkOnceODRLinkage;
791f22ef01cSRoman Divacky   }
792f22ef01cSRoman Divacky 
793e7145dcbSDimitry Andric   if (isa<CXXConstructorDecl>(D) &&
794e7145dcbSDimitry Andric       cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
795e7145dcbSDimitry Andric       Context.getTargetInfo().getCXXABI().isMicrosoft()) {
796e7145dcbSDimitry Andric     // Our approach to inheriting constructors is fundamentally different from
797e7145dcbSDimitry Andric     // that used by the MS ABI, so keep our inheriting constructor thunks
798e7145dcbSDimitry Andric     // internal rather than trying to pick an unambiguous mangling for them.
799e7145dcbSDimitry Andric     return llvm::GlobalValue::InternalLinkage;
800e7145dcbSDimitry Andric   }
801e7145dcbSDimitry Andric 
80259d1ed5bSDimitry Andric   return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
80359d1ed5bSDimitry Andric }
804f22ef01cSRoman Divacky 
80597bc6c73SDimitry Andric void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
80697bc6c73SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
80797bc6c73SDimitry Andric 
80897bc6c73SDimitry Andric   if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
80997bc6c73SDimitry Andric     if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
81097bc6c73SDimitry Andric       // Don't dllexport/import destructor thunks.
81197bc6c73SDimitry Andric       F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
81297bc6c73SDimitry Andric       return;
81397bc6c73SDimitry Andric     }
81497bc6c73SDimitry Andric   }
81597bc6c73SDimitry Andric 
81697bc6c73SDimitry Andric   if (FD->hasAttr<DLLImportAttr>())
81797bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
81897bc6c73SDimitry Andric   else if (FD->hasAttr<DLLExportAttr>())
81997bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
82097bc6c73SDimitry Andric   else
82197bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
82297bc6c73SDimitry Andric }
82397bc6c73SDimitry Andric 
824e7145dcbSDimitry Andric llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
8250623d748SDimitry Andric   llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
8260623d748SDimitry Andric   if (!MDS) return nullptr;
8270623d748SDimitry Andric 
82844290647SDimitry Andric   return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
8290623d748SDimitry Andric }
8300623d748SDimitry Andric 
83159d1ed5bSDimitry Andric void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
83259d1ed5bSDimitry Andric                                                     llvm::Function *F) {
83359d1ed5bSDimitry Andric   setNonAliasAttributes(D, F);
834f22ef01cSRoman Divacky }
835f22ef01cSRoman Divacky 
836f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
837f22ef01cSRoman Divacky                                               const CGFunctionInfo &Info,
838f22ef01cSRoman Divacky                                               llvm::Function *F) {
839f22ef01cSRoman Divacky   unsigned CallingConv;
8406bc11b14SDimitry Andric   llvm::AttributeList PAL;
8416bc11b14SDimitry Andric   ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false);
8426bc11b14SDimitry Andric   F->setAttributes(PAL);
843f22ef01cSRoman Divacky   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
844f22ef01cSRoman Divacky }
845f22ef01cSRoman Divacky 
8466122f3e6SDimitry Andric /// Determines whether the language options require us to model
8476122f3e6SDimitry Andric /// unwind exceptions.  We treat -fexceptions as mandating this
8486122f3e6SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions
8496122f3e6SDimitry Andric /// enabled.  This means, for example, that C with -fexceptions
8506122f3e6SDimitry Andric /// enables this.
851dff0c46cSDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) {
8526122f3e6SDimitry Andric   // If exceptions are completely disabled, obviously this is false.
853dff0c46cSDimitry Andric   if (!LangOpts.Exceptions) return false;
8546122f3e6SDimitry Andric 
8556122f3e6SDimitry Andric   // If C++ exceptions are enabled, this is true.
856dff0c46cSDimitry Andric   if (LangOpts.CXXExceptions) return true;
8576122f3e6SDimitry Andric 
8586122f3e6SDimitry Andric   // If ObjC exceptions are enabled, this depends on the ABI.
859dff0c46cSDimitry Andric   if (LangOpts.ObjCExceptions) {
8607ae0e2c9SDimitry Andric     return LangOpts.ObjCRuntime.hasUnwindExceptions();
8616122f3e6SDimitry Andric   }
8626122f3e6SDimitry Andric 
8636122f3e6SDimitry Andric   return true;
8646122f3e6SDimitry Andric }
8656122f3e6SDimitry Andric 
866f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
867f22ef01cSRoman Divacky                                                            llvm::Function *F) {
868f785676fSDimitry Andric   llvm::AttrBuilder B;
869f785676fSDimitry Andric 
870bd5abe19SDimitry Andric   if (CodeGenOpts.UnwindTables)
871f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::UWTable);
872bd5abe19SDimitry Andric 
873dff0c46cSDimitry Andric   if (!hasUnwindExceptions(LangOpts))
874f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoUnwind);
875f22ef01cSRoman Divacky 
8760623d748SDimitry Andric   if (LangOpts.getStackProtector() == LangOptions::SSPOn)
8770623d748SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtect);
8780623d748SDimitry Andric   else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
8790623d748SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtectStrong);
8800623d748SDimitry Andric   else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
8810623d748SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtectReq);
8820623d748SDimitry Andric 
8830623d748SDimitry Andric   if (!D) {
88444290647SDimitry Andric     // If we don't have a declaration to control inlining, the function isn't
88544290647SDimitry Andric     // explicitly marked as alwaysinline for semantic reasons, and inlining is
88644290647SDimitry Andric     // disabled, mark the function as noinline.
88744290647SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
88844290647SDimitry Andric         CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
88944290647SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
89044290647SDimitry Andric 
89120e90f04SDimitry Andric     F->addAttributes(
89220e90f04SDimitry Andric         llvm::AttributeList::FunctionIndex,
89320e90f04SDimitry Andric         llvm::AttributeList::get(F->getContext(),
89420e90f04SDimitry Andric                                  llvm::AttributeList::FunctionIndex, B));
8950623d748SDimitry Andric     return;
8960623d748SDimitry Andric   }
8970623d748SDimitry Andric 
89844290647SDimitry Andric   if (D->hasAttr<OptimizeNoneAttr>()) {
89944290647SDimitry Andric     B.addAttribute(llvm::Attribute::OptimizeNone);
90044290647SDimitry Andric 
90144290647SDimitry Andric     // OptimizeNone implies noinline; we should not be inlining such functions.
90244290647SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
90344290647SDimitry Andric     assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
90444290647SDimitry Andric            "OptimizeNone and AlwaysInline on same function!");
90544290647SDimitry Andric 
90644290647SDimitry Andric     // We still need to handle naked functions even though optnone subsumes
90744290647SDimitry Andric     // much of their semantics.
90844290647SDimitry Andric     if (D->hasAttr<NakedAttr>())
90944290647SDimitry Andric       B.addAttribute(llvm::Attribute::Naked);
91044290647SDimitry Andric 
91144290647SDimitry Andric     // OptimizeNone wins over OptimizeForSize and MinSize.
91244290647SDimitry Andric     F->removeFnAttr(llvm::Attribute::OptimizeForSize);
91344290647SDimitry Andric     F->removeFnAttr(llvm::Attribute::MinSize);
91444290647SDimitry Andric   } else if (D->hasAttr<NakedAttr>()) {
9156122f3e6SDimitry Andric     // Naked implies noinline: we should not be inlining such functions.
916f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::Naked);
917f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
91859d1ed5bSDimitry Andric   } else if (D->hasAttr<NoDuplicateAttr>()) {
91959d1ed5bSDimitry Andric     B.addAttribute(llvm::Attribute::NoDuplicate);
920f785676fSDimitry Andric   } else if (D->hasAttr<NoInlineAttr>()) {
921f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
92259d1ed5bSDimitry Andric   } else if (D->hasAttr<AlwaysInlineAttr>() &&
92344290647SDimitry Andric              !F->hasFnAttribute(llvm::Attribute::NoInline)) {
924f785676fSDimitry Andric     // (noinline wins over always_inline, and we can't specify both in IR)
925f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::AlwaysInline);
92644290647SDimitry Andric   } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
92744290647SDimitry Andric     // If we're not inlining, then force everything that isn't always_inline to
92844290647SDimitry Andric     // carry an explicit noinline attribute.
92944290647SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
93044290647SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
93144290647SDimitry Andric   } else {
93244290647SDimitry Andric     // Otherwise, propagate the inline hint attribute and potentially use its
93344290647SDimitry Andric     // absence to mark things as noinline.
93444290647SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
93544290647SDimitry Andric       if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
93644290647SDimitry Andric             return Redecl->isInlineSpecified();
93744290647SDimitry Andric           })) {
93844290647SDimitry Andric         B.addAttribute(llvm::Attribute::InlineHint);
93944290647SDimitry Andric       } else if (CodeGenOpts.getInlining() ==
94044290647SDimitry Andric                      CodeGenOptions::OnlyHintInlining &&
94144290647SDimitry Andric                  !FD->isInlined() &&
94244290647SDimitry Andric                  !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
94344290647SDimitry Andric         B.addAttribute(llvm::Attribute::NoInline);
94444290647SDimitry Andric       }
94544290647SDimitry Andric     }
9466122f3e6SDimitry Andric   }
9472754fe60SDimitry Andric 
94844290647SDimitry Andric   // Add other optimization related attributes if we are optimizing this
94944290647SDimitry Andric   // function.
95044290647SDimitry Andric   if (!D->hasAttr<OptimizeNoneAttr>()) {
951f785676fSDimitry Andric     if (D->hasAttr<ColdAttr>()) {
952f785676fSDimitry Andric       B.addAttribute(llvm::Attribute::OptimizeForSize);
953f785676fSDimitry Andric       B.addAttribute(llvm::Attribute::Cold);
954f785676fSDimitry Andric     }
9553861d79fSDimitry Andric 
9563861d79fSDimitry Andric     if (D->hasAttr<MinSizeAttr>())
957f785676fSDimitry Andric       B.addAttribute(llvm::Attribute::MinSize);
95844290647SDimitry Andric   }
959f22ef01cSRoman Divacky 
96020e90f04SDimitry Andric   F->addAttributes(llvm::AttributeList::FunctionIndex,
96120e90f04SDimitry Andric                    llvm::AttributeList::get(
96220e90f04SDimitry Andric                        F->getContext(), llvm::AttributeList::FunctionIndex, B));
963f785676fSDimitry Andric 
964e580952dSDimitry Andric   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
965e580952dSDimitry Andric   if (alignment)
966e580952dSDimitry Andric     F->setAlignment(alignment);
967e580952dSDimitry Andric 
9680623d748SDimitry Andric   // Some C++ ABIs require 2-byte alignment for member functions, in order to
9690623d748SDimitry Andric   // reserve a bit for differentiating between virtual and non-virtual member
9700623d748SDimitry Andric   // functions. If the current target's C++ ABI requires this and this is a
9710623d748SDimitry Andric   // member function, set its alignment accordingly.
9720623d748SDimitry Andric   if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
973f22ef01cSRoman Divacky     if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
974f22ef01cSRoman Divacky       F->setAlignment(2);
975f22ef01cSRoman Divacky   }
97644290647SDimitry Andric 
97744290647SDimitry Andric   // In the cross-dso CFI mode, we want !type attributes on definitions only.
97844290647SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
97944290647SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D))
98044290647SDimitry Andric       CreateFunctionTypeMetadata(FD, F);
9810623d748SDimitry Andric }
982f22ef01cSRoman Divacky 
983f22ef01cSRoman Divacky void CodeGenModule::SetCommonAttributes(const Decl *D,
984f22ef01cSRoman Divacky                                         llvm::GlobalValue *GV) {
9850623d748SDimitry Andric   if (const auto *ND = dyn_cast_or_null<NamedDecl>(D))
9862754fe60SDimitry Andric     setGlobalVisibility(GV, ND);
9872754fe60SDimitry Andric   else
9882754fe60SDimitry Andric     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
989f22ef01cSRoman Divacky 
9900623d748SDimitry Andric   if (D && D->hasAttr<UsedAttr>())
99159d1ed5bSDimitry Andric     addUsedGlobal(GV);
99259d1ed5bSDimitry Andric }
99359d1ed5bSDimitry Andric 
99439d628a0SDimitry Andric void CodeGenModule::setAliasAttributes(const Decl *D,
99539d628a0SDimitry Andric                                        llvm::GlobalValue *GV) {
99639d628a0SDimitry Andric   SetCommonAttributes(D, GV);
99739d628a0SDimitry Andric 
99839d628a0SDimitry Andric   // Process the dllexport attribute based on whether the original definition
99939d628a0SDimitry Andric   // (not necessarily the aliasee) was exported.
100039d628a0SDimitry Andric   if (D->hasAttr<DLLExportAttr>())
100139d628a0SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
100239d628a0SDimitry Andric }
100339d628a0SDimitry Andric 
100459d1ed5bSDimitry Andric void CodeGenModule::setNonAliasAttributes(const Decl *D,
100559d1ed5bSDimitry Andric                                           llvm::GlobalObject *GO) {
100659d1ed5bSDimitry Andric   SetCommonAttributes(D, GO);
1007f22ef01cSRoman Divacky 
10080623d748SDimitry Andric   if (D)
1009f22ef01cSRoman Divacky     if (const SectionAttr *SA = D->getAttr<SectionAttr>())
101059d1ed5bSDimitry Andric       GO->setSection(SA->getName());
1011f22ef01cSRoman Divacky 
101297bc6c73SDimitry Andric   getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
1013f22ef01cSRoman Divacky }
1014f22ef01cSRoman Divacky 
1015f22ef01cSRoman Divacky void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
1016f22ef01cSRoman Divacky                                                   llvm::Function *F,
1017f22ef01cSRoman Divacky                                                   const CGFunctionInfo &FI) {
1018f22ef01cSRoman Divacky   SetLLVMFunctionAttributes(D, FI, F);
1019f22ef01cSRoman Divacky   SetLLVMFunctionAttributesForDefinition(D, F);
1020f22ef01cSRoman Divacky 
1021f22ef01cSRoman Divacky   F->setLinkage(llvm::Function::InternalLinkage);
1022f22ef01cSRoman Divacky 
102359d1ed5bSDimitry Andric   setNonAliasAttributes(D, F);
102459d1ed5bSDimitry Andric }
102559d1ed5bSDimitry Andric 
102659d1ed5bSDimitry Andric static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
102759d1ed5bSDimitry Andric                                          const NamedDecl *ND) {
102859d1ed5bSDimitry Andric   // Set linkage and visibility in case we never see a definition.
102959d1ed5bSDimitry Andric   LinkageInfo LV = ND->getLinkageAndVisibility();
103059d1ed5bSDimitry Andric   if (LV.getLinkage() != ExternalLinkage) {
103159d1ed5bSDimitry Andric     // Don't set internal linkage on declarations.
103259d1ed5bSDimitry Andric   } else {
103359d1ed5bSDimitry Andric     if (ND->hasAttr<DLLImportAttr>()) {
103459d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
103559d1ed5bSDimitry Andric       GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
103659d1ed5bSDimitry Andric     } else if (ND->hasAttr<DLLExportAttr>()) {
103759d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
103859d1ed5bSDimitry Andric     } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
103959d1ed5bSDimitry Andric       // "extern_weak" is overloaded in LLVM; we probably should have
104059d1ed5bSDimitry Andric       // separate linkage types for this.
104159d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
104259d1ed5bSDimitry Andric     }
104359d1ed5bSDimitry Andric 
104459d1ed5bSDimitry Andric     // Set visibility on a declaration only if it's explicit.
104559d1ed5bSDimitry Andric     if (LV.isVisibilityExplicit())
104659d1ed5bSDimitry Andric       GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
104759d1ed5bSDimitry Andric   }
1048f22ef01cSRoman Divacky }
1049f22ef01cSRoman Divacky 
1050e7145dcbSDimitry Andric void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD,
10510623d748SDimitry Andric                                                llvm::Function *F) {
10520623d748SDimitry Andric   // Only if we are checking indirect calls.
10530623d748SDimitry Andric   if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
10540623d748SDimitry Andric     return;
10550623d748SDimitry Andric 
10560623d748SDimitry Andric   // Non-static class methods are handled via vtable pointer checks elsewhere.
10570623d748SDimitry Andric   if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
10580623d748SDimitry Andric     return;
10590623d748SDimitry Andric 
10600623d748SDimitry Andric   // Additionally, if building with cross-DSO support...
10610623d748SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
10620623d748SDimitry Andric     // Skip available_externally functions. They won't be codegen'ed in the
10630623d748SDimitry Andric     // current module anyway.
10640623d748SDimitry Andric     if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
10650623d748SDimitry Andric       return;
10660623d748SDimitry Andric   }
10670623d748SDimitry Andric 
10680623d748SDimitry Andric   llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
1069e7145dcbSDimitry Andric   F->addTypeMetadata(0, MD);
10700623d748SDimitry Andric 
10710623d748SDimitry Andric   // Emit a hash-based bit set entry for cross-DSO calls.
1072e7145dcbSDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
1073e7145dcbSDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1074e7145dcbSDimitry Andric       F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
10750623d748SDimitry Andric }
10760623d748SDimitry Andric 
107739d628a0SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
107839d628a0SDimitry Andric                                           bool IsIncompleteFunction,
107939d628a0SDimitry Andric                                           bool IsThunk) {
108033956c43SDimitry Andric   if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
10813b0f4066SDimitry Andric     // If this is an intrinsic function, set the function's attributes
10823b0f4066SDimitry Andric     // to the intrinsic's attributes.
108333956c43SDimitry Andric     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
10843b0f4066SDimitry Andric     return;
10853b0f4066SDimitry Andric   }
10863b0f4066SDimitry Andric 
108759d1ed5bSDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
1088f22ef01cSRoman Divacky 
1089f22ef01cSRoman Divacky   if (!IsIncompleteFunction)
1090dff0c46cSDimitry Andric     SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
1091f22ef01cSRoman Divacky 
109259d1ed5bSDimitry Andric   // Add the Returned attribute for "this", except for iOS 5 and earlier
109359d1ed5bSDimitry Andric   // where substantial code, including the libstdc++ dylib, was compiled with
109459d1ed5bSDimitry Andric   // GCC and does not actually return "this".
109539d628a0SDimitry Andric   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
109644290647SDimitry Andric       !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
1097f785676fSDimitry Andric     assert(!F->arg_empty() &&
1098f785676fSDimitry Andric            F->arg_begin()->getType()
1099f785676fSDimitry Andric              ->canLosslesslyBitCastTo(F->getReturnType()) &&
1100f785676fSDimitry Andric            "unexpected this return");
1101f785676fSDimitry Andric     F->addAttribute(1, llvm::Attribute::Returned);
1102f785676fSDimitry Andric   }
1103f785676fSDimitry Andric 
1104f22ef01cSRoman Divacky   // Only a few attributes are set on declarations; these may later be
1105f22ef01cSRoman Divacky   // overridden by a definition.
1106f22ef01cSRoman Divacky 
110759d1ed5bSDimitry Andric   setLinkageAndVisibilityForGV(F, FD);
11082754fe60SDimitry Andric 
1109f22ef01cSRoman Divacky   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
1110f22ef01cSRoman Divacky     F->setSection(SA->getName());
1111f785676fSDimitry Andric 
1112e7145dcbSDimitry Andric   if (FD->isReplaceableGlobalAllocationFunction()) {
1113f785676fSDimitry Andric     // A replaceable global allocation function does not act like a builtin by
1114f785676fSDimitry Andric     // default, only if it is invoked by a new-expression or delete-expression.
111520e90f04SDimitry Andric     F->addAttribute(llvm::AttributeList::FunctionIndex,
1116f785676fSDimitry Andric                     llvm::Attribute::NoBuiltin);
11170623d748SDimitry Andric 
1118e7145dcbSDimitry Andric     // A sane operator new returns a non-aliasing pointer.
1119e7145dcbSDimitry Andric     // FIXME: Also add NonNull attribute to the return value
1120e7145dcbSDimitry Andric     // for the non-nothrow forms?
1121e7145dcbSDimitry Andric     auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1122e7145dcbSDimitry Andric     if (getCodeGenOpts().AssumeSaneOperatorNew &&
1123e7145dcbSDimitry Andric         (Kind == OO_New || Kind == OO_Array_New))
112420e90f04SDimitry Andric       F->addAttribute(llvm::AttributeList::ReturnIndex,
1125e7145dcbSDimitry Andric                       llvm::Attribute::NoAlias);
1126e7145dcbSDimitry Andric   }
1127e7145dcbSDimitry Andric 
1128e7145dcbSDimitry Andric   if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1129e7145dcbSDimitry Andric     F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1130e7145dcbSDimitry Andric   else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1131e7145dcbSDimitry Andric     if (MD->isVirtual())
1132e7145dcbSDimitry Andric       F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1133e7145dcbSDimitry Andric 
113444290647SDimitry Andric   // Don't emit entries for function declarations in the cross-DSO mode. This
113544290647SDimitry Andric   // is handled with better precision by the receiving DSO.
113644290647SDimitry Andric   if (!CodeGenOpts.SanitizeCfiCrossDso)
1137e7145dcbSDimitry Andric     CreateFunctionTypeMetadata(FD, F);
1138f22ef01cSRoman Divacky }
1139f22ef01cSRoman Divacky 
114059d1ed5bSDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
1141f22ef01cSRoman Divacky   assert(!GV->isDeclaration() &&
1142f22ef01cSRoman Divacky          "Only globals with definition can force usage.");
114397bc6c73SDimitry Andric   LLVMUsed.emplace_back(GV);
1144f22ef01cSRoman Divacky }
1145f22ef01cSRoman Divacky 
114659d1ed5bSDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
114759d1ed5bSDimitry Andric   assert(!GV->isDeclaration() &&
114859d1ed5bSDimitry Andric          "Only globals with definition can force usage.");
114997bc6c73SDimitry Andric   LLVMCompilerUsed.emplace_back(GV);
115059d1ed5bSDimitry Andric }
115159d1ed5bSDimitry Andric 
115259d1ed5bSDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name,
115359d1ed5bSDimitry Andric                      std::vector<llvm::WeakVH> &List) {
1154f22ef01cSRoman Divacky   // Don't create llvm.used if there is no need.
115559d1ed5bSDimitry Andric   if (List.empty())
1156f22ef01cSRoman Divacky     return;
1157f22ef01cSRoman Divacky 
115859d1ed5bSDimitry Andric   // Convert List to what ConstantArray needs.
1159dff0c46cSDimitry Andric   SmallVector<llvm::Constant*, 8> UsedArray;
116059d1ed5bSDimitry Andric   UsedArray.resize(List.size());
116159d1ed5bSDimitry Andric   for (unsigned i = 0, e = List.size(); i != e; ++i) {
1162f22ef01cSRoman Divacky     UsedArray[i] =
116344f7b0dcSDimitry Andric         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
116444f7b0dcSDimitry Andric             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
1165f22ef01cSRoman Divacky   }
1166f22ef01cSRoman Divacky 
1167f22ef01cSRoman Divacky   if (UsedArray.empty())
1168f22ef01cSRoman Divacky     return;
116959d1ed5bSDimitry Andric   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
1170f22ef01cSRoman Divacky 
117159d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
117259d1ed5bSDimitry Andric       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
117359d1ed5bSDimitry Andric       llvm::ConstantArray::get(ATy, UsedArray), Name);
1174f22ef01cSRoman Divacky 
1175f22ef01cSRoman Divacky   GV->setSection("llvm.metadata");
1176f22ef01cSRoman Divacky }
1177f22ef01cSRoman Divacky 
117859d1ed5bSDimitry Andric void CodeGenModule::emitLLVMUsed() {
117959d1ed5bSDimitry Andric   emitUsed(*this, "llvm.used", LLVMUsed);
118059d1ed5bSDimitry Andric   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
118159d1ed5bSDimitry Andric }
118259d1ed5bSDimitry Andric 
1183f785676fSDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
118439d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
1185f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1186f785676fSDimitry Andric }
1187f785676fSDimitry Andric 
1188f785676fSDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1189f785676fSDimitry Andric   llvm::SmallString<32> Opt;
1190f785676fSDimitry Andric   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
119139d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1192f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1193f785676fSDimitry Andric }
1194f785676fSDimitry Andric 
1195f785676fSDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) {
1196f785676fSDimitry Andric   llvm::SmallString<24> Opt;
1197f785676fSDimitry Andric   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
119839d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1199f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1200f785676fSDimitry Andric }
1201f785676fSDimitry Andric 
1202139f7f9bSDimitry Andric /// \brief Add link options implied by the given module, including modules
1203139f7f9bSDimitry Andric /// it depends on, using a postorder walk.
120439d628a0SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
120539d628a0SDimitry Andric                                     SmallVectorImpl<llvm::Metadata *> &Metadata,
1206139f7f9bSDimitry Andric                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
1207139f7f9bSDimitry Andric   // Import this module's parent.
120839d628a0SDimitry Andric   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
1209f785676fSDimitry Andric     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
1210139f7f9bSDimitry Andric   }
1211139f7f9bSDimitry Andric 
1212139f7f9bSDimitry Andric   // Import this module's dependencies.
1213139f7f9bSDimitry Andric   for (unsigned I = Mod->Imports.size(); I > 0; --I) {
121439d628a0SDimitry Andric     if (Visited.insert(Mod->Imports[I - 1]).second)
1215f785676fSDimitry Andric       addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
1216139f7f9bSDimitry Andric   }
1217139f7f9bSDimitry Andric 
1218139f7f9bSDimitry Andric   // Add linker options to link against the libraries/frameworks
1219139f7f9bSDimitry Andric   // described by this module.
1220f785676fSDimitry Andric   llvm::LLVMContext &Context = CGM.getLLVMContext();
1221139f7f9bSDimitry Andric   for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
1222f785676fSDimitry Andric     // Link against a framework.  Frameworks are currently Darwin only, so we
1223f785676fSDimitry Andric     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
1224139f7f9bSDimitry Andric     if (Mod->LinkLibraries[I-1].IsFramework) {
122539d628a0SDimitry Andric       llvm::Metadata *Args[2] = {
1226139f7f9bSDimitry Andric           llvm::MDString::get(Context, "-framework"),
122739d628a0SDimitry Andric           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
1228139f7f9bSDimitry Andric 
1229139f7f9bSDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, Args));
1230139f7f9bSDimitry Andric       continue;
1231139f7f9bSDimitry Andric     }
1232139f7f9bSDimitry Andric 
1233139f7f9bSDimitry Andric     // Link against a library.
1234f785676fSDimitry Andric     llvm::SmallString<24> Opt;
1235f785676fSDimitry Andric     CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1236f785676fSDimitry Andric       Mod->LinkLibraries[I-1].Library, Opt);
123739d628a0SDimitry Andric     auto *OptString = llvm::MDString::get(Context, Opt);
1238139f7f9bSDimitry Andric     Metadata.push_back(llvm::MDNode::get(Context, OptString));
1239139f7f9bSDimitry Andric   }
1240139f7f9bSDimitry Andric }
1241139f7f9bSDimitry Andric 
1242139f7f9bSDimitry Andric void CodeGenModule::EmitModuleLinkOptions() {
1243139f7f9bSDimitry Andric   // Collect the set of all of the modules we want to visit to emit link
1244139f7f9bSDimitry Andric   // options, which is essentially the imported modules and all of their
1245139f7f9bSDimitry Andric   // non-explicit child modules.
1246139f7f9bSDimitry Andric   llvm::SetVector<clang::Module *> LinkModules;
1247139f7f9bSDimitry Andric   llvm::SmallPtrSet<clang::Module *, 16> Visited;
1248139f7f9bSDimitry Andric   SmallVector<clang::Module *, 16> Stack;
1249139f7f9bSDimitry Andric 
1250139f7f9bSDimitry Andric   // Seed the stack with imported modules.
1251f1a29dd3SDimitry Andric   for (Module *M : ImportedModules) {
1252f1a29dd3SDimitry Andric     // Do not add any link flags when an implementation TU of a module imports
1253f1a29dd3SDimitry Andric     // a header of that same module.
1254f1a29dd3SDimitry Andric     if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
1255f1a29dd3SDimitry Andric         !getLangOpts().isCompilingModule())
1256f1a29dd3SDimitry Andric       continue;
12578f0fd8f6SDimitry Andric     if (Visited.insert(M).second)
12588f0fd8f6SDimitry Andric       Stack.push_back(M);
1259f1a29dd3SDimitry Andric   }
1260139f7f9bSDimitry Andric 
1261139f7f9bSDimitry Andric   // Find all of the modules to import, making a little effort to prune
1262139f7f9bSDimitry Andric   // non-leaf modules.
1263139f7f9bSDimitry Andric   while (!Stack.empty()) {
1264f785676fSDimitry Andric     clang::Module *Mod = Stack.pop_back_val();
1265139f7f9bSDimitry Andric 
1266139f7f9bSDimitry Andric     bool AnyChildren = false;
1267139f7f9bSDimitry Andric 
1268139f7f9bSDimitry Andric     // Visit the submodules of this module.
1269139f7f9bSDimitry Andric     for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1270139f7f9bSDimitry Andric                                         SubEnd = Mod->submodule_end();
1271139f7f9bSDimitry Andric          Sub != SubEnd; ++Sub) {
1272139f7f9bSDimitry Andric       // Skip explicit children; they need to be explicitly imported to be
1273139f7f9bSDimitry Andric       // linked against.
1274139f7f9bSDimitry Andric       if ((*Sub)->IsExplicit)
1275139f7f9bSDimitry Andric         continue;
1276139f7f9bSDimitry Andric 
127739d628a0SDimitry Andric       if (Visited.insert(*Sub).second) {
1278139f7f9bSDimitry Andric         Stack.push_back(*Sub);
1279139f7f9bSDimitry Andric         AnyChildren = true;
1280139f7f9bSDimitry Andric       }
1281139f7f9bSDimitry Andric     }
1282139f7f9bSDimitry Andric 
1283139f7f9bSDimitry Andric     // We didn't find any children, so add this module to the list of
1284139f7f9bSDimitry Andric     // modules to link against.
1285139f7f9bSDimitry Andric     if (!AnyChildren) {
1286139f7f9bSDimitry Andric       LinkModules.insert(Mod);
1287139f7f9bSDimitry Andric     }
1288139f7f9bSDimitry Andric   }
1289139f7f9bSDimitry Andric 
1290139f7f9bSDimitry Andric   // Add link options for all of the imported modules in reverse topological
1291f785676fSDimitry Andric   // order.  We don't do anything to try to order import link flags with respect
1292f785676fSDimitry Andric   // to linker options inserted by things like #pragma comment().
129339d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 16> MetadataArgs;
1294139f7f9bSDimitry Andric   Visited.clear();
12958f0fd8f6SDimitry Andric   for (Module *M : LinkModules)
12968f0fd8f6SDimitry Andric     if (Visited.insert(M).second)
12978f0fd8f6SDimitry Andric       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
1298139f7f9bSDimitry Andric   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1299f785676fSDimitry Andric   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1300139f7f9bSDimitry Andric 
1301139f7f9bSDimitry Andric   // Add the linker options metadata flag.
1302139f7f9bSDimitry Andric   getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
1303f785676fSDimitry Andric                             llvm::MDNode::get(getLLVMContext(),
1304f785676fSDimitry Andric                                               LinkerOptionsMetadata));
1305139f7f9bSDimitry Andric }
1306139f7f9bSDimitry Andric 
1307f22ef01cSRoman Divacky void CodeGenModule::EmitDeferred() {
1308f22ef01cSRoman Divacky   // Emit code for any potentially referenced deferred decls.  Since a
1309f22ef01cSRoman Divacky   // previously unused static decl may become used during the generation of code
1310f22ef01cSRoman Divacky   // for a static function, iterate until no changes are made.
1311f22ef01cSRoman Divacky 
1312f22ef01cSRoman Divacky   if (!DeferredVTables.empty()) {
1313139f7f9bSDimitry Andric     EmitDeferredVTables();
1314139f7f9bSDimitry Andric 
1315e7145dcbSDimitry Andric     // Emitting a vtable doesn't directly cause more vtables to
1316139f7f9bSDimitry Andric     // become deferred, although it can cause functions to be
1317e7145dcbSDimitry Andric     // emitted that then need those vtables.
1318139f7f9bSDimitry Andric     assert(DeferredVTables.empty());
1319f22ef01cSRoman Divacky   }
1320f22ef01cSRoman Divacky 
1321e7145dcbSDimitry Andric   // Stop if we're out of both deferred vtables and deferred declarations.
132233956c43SDimitry Andric   if (DeferredDeclsToEmit.empty())
132333956c43SDimitry Andric     return;
1324139f7f9bSDimitry Andric 
132533956c43SDimitry Andric   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
132633956c43SDimitry Andric   // work, it will not interfere with this.
132733956c43SDimitry Andric   std::vector<DeferredGlobal> CurDeclsToEmit;
132833956c43SDimitry Andric   CurDeclsToEmit.swap(DeferredDeclsToEmit);
132933956c43SDimitry Andric 
133033956c43SDimitry Andric   for (DeferredGlobal &G : CurDeclsToEmit) {
133159d1ed5bSDimitry Andric     GlobalDecl D = G.GD;
133233956c43SDimitry Andric     G.GV = nullptr;
1333f22ef01cSRoman Divacky 
13340623d748SDimitry Andric     // We should call GetAddrOfGlobal with IsForDefinition set to true in order
13350623d748SDimitry Andric     // to get GlobalValue with exactly the type we need, not something that
13360623d748SDimitry Andric     // might had been created for another decl with the same mangled name but
13370623d748SDimitry Andric     // different type.
1338e7145dcbSDimitry Andric     llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
133944290647SDimitry Andric         GetAddrOfGlobal(D, ForDefinition));
1340e7145dcbSDimitry Andric 
1341e7145dcbSDimitry Andric     // In case of different address spaces, we may still get a cast, even with
1342e7145dcbSDimitry Andric     // IsForDefinition equal to true. Query mangled names table to get
1343e7145dcbSDimitry Andric     // GlobalValue.
134439d628a0SDimitry Andric     if (!GV)
134539d628a0SDimitry Andric       GV = GetGlobalValue(getMangledName(D));
134639d628a0SDimitry Andric 
1347e7145dcbSDimitry Andric     // Make sure GetGlobalValue returned non-null.
1348e7145dcbSDimitry Andric     assert(GV);
1349e7145dcbSDimitry Andric 
1350f22ef01cSRoman Divacky     // Check to see if we've already emitted this.  This is necessary
1351f22ef01cSRoman Divacky     // for a couple of reasons: first, decls can end up in the
1352f22ef01cSRoman Divacky     // deferred-decls queue multiple times, and second, decls can end
1353f22ef01cSRoman Divacky     // up with definitions in unusual ways (e.g. by an extern inline
1354f22ef01cSRoman Divacky     // function acquiring a strong function redefinition).  Just
1355f22ef01cSRoman Divacky     // ignore these cases.
1356e7145dcbSDimitry Andric     if (!GV->isDeclaration())
1357f22ef01cSRoman Divacky       continue;
1358f22ef01cSRoman Divacky 
1359f22ef01cSRoman Divacky     // Otherwise, emit the definition and move on to the next one.
136059d1ed5bSDimitry Andric     EmitGlobalDefinition(D, GV);
136133956c43SDimitry Andric 
136233956c43SDimitry Andric     // If we found out that we need to emit more decls, do that recursively.
136333956c43SDimitry Andric     // This has the advantage that the decls are emitted in a DFS and related
136433956c43SDimitry Andric     // ones are close together, which is convenient for testing.
136533956c43SDimitry Andric     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
136633956c43SDimitry Andric       EmitDeferred();
136733956c43SDimitry Andric       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
136833956c43SDimitry Andric     }
1369f22ef01cSRoman Divacky   }
1370f22ef01cSRoman Divacky }
1371f22ef01cSRoman Divacky 
13726122f3e6SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() {
13736122f3e6SDimitry Andric   if (Annotations.empty())
13746122f3e6SDimitry Andric     return;
13756122f3e6SDimitry Andric 
13766122f3e6SDimitry Andric   // Create a new global variable for the ConstantStruct in the Module.
13776122f3e6SDimitry Andric   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
13786122f3e6SDimitry Andric     Annotations[0]->getType(), Annotations.size()), Annotations);
137959d1ed5bSDimitry Andric   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
138059d1ed5bSDimitry Andric                                       llvm::GlobalValue::AppendingLinkage,
138159d1ed5bSDimitry Andric                                       Array, "llvm.global.annotations");
13826122f3e6SDimitry Andric   gv->setSection(AnnotationSection);
13836122f3e6SDimitry Andric }
13846122f3e6SDimitry Andric 
1385139f7f9bSDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1386f785676fSDimitry Andric   llvm::Constant *&AStr = AnnotationStrings[Str];
1387f785676fSDimitry Andric   if (AStr)
1388f785676fSDimitry Andric     return AStr;
13896122f3e6SDimitry Andric 
13906122f3e6SDimitry Andric   // Not found yet, create a new global.
1391dff0c46cSDimitry Andric   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
139259d1ed5bSDimitry Andric   auto *gv =
139359d1ed5bSDimitry Andric       new llvm::GlobalVariable(getModule(), s->getType(), true,
139459d1ed5bSDimitry Andric                                llvm::GlobalValue::PrivateLinkage, s, ".str");
13956122f3e6SDimitry Andric   gv->setSection(AnnotationSection);
1396e7145dcbSDimitry Andric   gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1397f785676fSDimitry Andric   AStr = gv;
13986122f3e6SDimitry Andric   return gv;
13996122f3e6SDimitry Andric }
14006122f3e6SDimitry Andric 
14016122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
14026122f3e6SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
14036122f3e6SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
14046122f3e6SDimitry Andric   if (PLoc.isValid())
14056122f3e6SDimitry Andric     return EmitAnnotationString(PLoc.getFilename());
14066122f3e6SDimitry Andric   return EmitAnnotationString(SM.getBufferName(Loc));
14076122f3e6SDimitry Andric }
14086122f3e6SDimitry Andric 
14096122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
14106122f3e6SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
14116122f3e6SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(L);
14126122f3e6SDimitry Andric   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
14136122f3e6SDimitry Andric     SM.getExpansionLineNumber(L);
14146122f3e6SDimitry Andric   return llvm::ConstantInt::get(Int32Ty, LineNo);
14156122f3e6SDimitry Andric }
14166122f3e6SDimitry Andric 
1417f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1418f22ef01cSRoman Divacky                                                 const AnnotateAttr *AA,
14196122f3e6SDimitry Andric                                                 SourceLocation L) {
14206122f3e6SDimitry Andric   // Get the globals for file name, annotation, and the line number.
14216122f3e6SDimitry Andric   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
14226122f3e6SDimitry Andric                  *UnitGV = EmitAnnotationUnit(L),
14236122f3e6SDimitry Andric                  *LineNoCst = EmitAnnotationLineNo(L);
1424f22ef01cSRoman Divacky 
1425f22ef01cSRoman Divacky   // Create the ConstantStruct for the global annotation.
1426f22ef01cSRoman Divacky   llvm::Constant *Fields[4] = {
14276122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
14286122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
14296122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
14306122f3e6SDimitry Andric     LineNoCst
1431f22ef01cSRoman Divacky   };
143217a519f9SDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
1433f22ef01cSRoman Divacky }
1434f22ef01cSRoman Divacky 
14356122f3e6SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
14366122f3e6SDimitry Andric                                          llvm::GlobalValue *GV) {
14376122f3e6SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
14386122f3e6SDimitry Andric   // Get the struct elements for these annotations.
143959d1ed5bSDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>())
144059d1ed5bSDimitry Andric     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
14416122f3e6SDimitry Andric }
14426122f3e6SDimitry Andric 
144339d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
144439d628a0SDimitry Andric                                            SourceLocation Loc) const {
144539d628a0SDimitry Andric   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
144639d628a0SDimitry Andric   // Blacklist by function name.
144739d628a0SDimitry Andric   if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
144839d628a0SDimitry Andric     return true;
144939d628a0SDimitry Andric   // Blacklist by location.
14500623d748SDimitry Andric   if (Loc.isValid())
145139d628a0SDimitry Andric     return SanitizerBL.isBlacklistedLocation(Loc);
145239d628a0SDimitry Andric   // If location is unknown, this may be a compiler-generated function. Assume
145339d628a0SDimitry Andric   // it's located in the main file.
145439d628a0SDimitry Andric   auto &SM = Context.getSourceManager();
145539d628a0SDimitry Andric   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
145639d628a0SDimitry Andric     return SanitizerBL.isBlacklistedFile(MainFile->getName());
145739d628a0SDimitry Andric   }
145839d628a0SDimitry Andric   return false;
145939d628a0SDimitry Andric }
146039d628a0SDimitry Andric 
146139d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
146239d628a0SDimitry Andric                                            SourceLocation Loc, QualType Ty,
146339d628a0SDimitry Andric                                            StringRef Category) const {
14648f0fd8f6SDimitry Andric   // For now globals can be blacklisted only in ASan and KASan.
14658f0fd8f6SDimitry Andric   if (!LangOpts.Sanitize.hasOneOf(
14668f0fd8f6SDimitry Andric           SanitizerKind::Address | SanitizerKind::KernelAddress))
146739d628a0SDimitry Andric     return false;
146839d628a0SDimitry Andric   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
146939d628a0SDimitry Andric   if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
147039d628a0SDimitry Andric     return true;
147139d628a0SDimitry Andric   if (SanitizerBL.isBlacklistedLocation(Loc, Category))
147239d628a0SDimitry Andric     return true;
147339d628a0SDimitry Andric   // Check global type.
147439d628a0SDimitry Andric   if (!Ty.isNull()) {
147539d628a0SDimitry Andric     // Drill down the array types: if global variable of a fixed type is
147639d628a0SDimitry Andric     // blacklisted, we also don't instrument arrays of them.
147739d628a0SDimitry Andric     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
147839d628a0SDimitry Andric       Ty = AT->getElementType();
147939d628a0SDimitry Andric     Ty = Ty.getCanonicalType().getUnqualifiedType();
148039d628a0SDimitry Andric     // We allow to blacklist only record types (classes, structs etc.)
148139d628a0SDimitry Andric     if (Ty->isRecordType()) {
148239d628a0SDimitry Andric       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
148339d628a0SDimitry Andric       if (SanitizerBL.isBlacklistedType(TypeStr, Category))
148439d628a0SDimitry Andric         return true;
148539d628a0SDimitry Andric     }
148639d628a0SDimitry Andric   }
148739d628a0SDimitry Andric   return false;
148839d628a0SDimitry Andric }
148939d628a0SDimitry Andric 
149020e90f04SDimitry Andric bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
149120e90f04SDimitry Andric                                    StringRef Category) const {
149220e90f04SDimitry Andric   if (!LangOpts.XRayInstrument)
149320e90f04SDimitry Andric     return false;
149420e90f04SDimitry Andric   const auto &XRayFilter = getContext().getXRayFilter();
149520e90f04SDimitry Andric   using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
149620e90f04SDimitry Andric   auto Attr = XRayFunctionFilter::ImbueAttribute::NONE;
149720e90f04SDimitry Andric   if (Loc.isValid())
149820e90f04SDimitry Andric     Attr = XRayFilter.shouldImbueLocation(Loc, Category);
149920e90f04SDimitry Andric   if (Attr == ImbueAttr::NONE)
150020e90f04SDimitry Andric     Attr = XRayFilter.shouldImbueFunction(Fn->getName());
150120e90f04SDimitry Andric   switch (Attr) {
150220e90f04SDimitry Andric   case ImbueAttr::NONE:
150320e90f04SDimitry Andric     return false;
150420e90f04SDimitry Andric   case ImbueAttr::ALWAYS:
150520e90f04SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-always");
150620e90f04SDimitry Andric     break;
150720e90f04SDimitry Andric   case ImbueAttr::NEVER:
150820e90f04SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-never");
150920e90f04SDimitry Andric     break;
151020e90f04SDimitry Andric   }
151120e90f04SDimitry Andric   return true;
151220e90f04SDimitry Andric }
151320e90f04SDimitry Andric 
151439d628a0SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
1515e580952dSDimitry Andric   // Never defer when EmitAllDecls is specified.
1516dff0c46cSDimitry Andric   if (LangOpts.EmitAllDecls)
151739d628a0SDimitry Andric     return true;
151839d628a0SDimitry Andric 
151939d628a0SDimitry Andric   return getContext().DeclMustBeEmitted(Global);
152039d628a0SDimitry Andric }
152139d628a0SDimitry Andric 
152239d628a0SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
152339d628a0SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global))
152439d628a0SDimitry Andric     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
152539d628a0SDimitry Andric       // Implicit template instantiations may change linkage if they are later
152639d628a0SDimitry Andric       // explicitly instantiated, so they should not be emitted eagerly.
1527f22ef01cSRoman Divacky       return false;
1528e7145dcbSDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(Global))
1529e7145dcbSDimitry Andric     if (Context.getInlineVariableDefinitionKind(VD) ==
1530e7145dcbSDimitry Andric         ASTContext::InlineVariableDefinitionKind::WeakUnknown)
1531e7145dcbSDimitry Andric       // A definition of an inline constexpr static data member may change
1532e7145dcbSDimitry Andric       // linkage later if it's redeclared outside the class.
1533e7145dcbSDimitry Andric       return false;
1534875ed548SDimitry Andric   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
1535875ed548SDimitry Andric   // codegen for global variables, because they may be marked as threadprivate.
1536875ed548SDimitry Andric   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1537875ed548SDimitry Andric       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
1538875ed548SDimitry Andric     return false;
1539f22ef01cSRoman Divacky 
154039d628a0SDimitry Andric   return true;
1541f22ef01cSRoman Divacky }
1542f22ef01cSRoman Divacky 
15430623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
15443861d79fSDimitry Andric     const CXXUuidofExpr* E) {
15453861d79fSDimitry Andric   // Sema has verified that IIDSource has a __declspec(uuid()), and that its
15463861d79fSDimitry Andric   // well-formed.
1547e7145dcbSDimitry Andric   StringRef Uuid = E->getUuidStr();
1548f785676fSDimitry Andric   std::string Name = "_GUID_" + Uuid.lower();
1549f785676fSDimitry Andric   std::replace(Name.begin(), Name.end(), '-', '_');
15503861d79fSDimitry Andric 
1551e7145dcbSDimitry Andric   // The UUID descriptor should be pointer aligned.
1552e7145dcbSDimitry Andric   CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
15530623d748SDimitry Andric 
15543861d79fSDimitry Andric   // Look for an existing global.
15553861d79fSDimitry Andric   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
15560623d748SDimitry Andric     return ConstantAddress(GV, Alignment);
15573861d79fSDimitry Andric 
155839d628a0SDimitry Andric   llvm::Constant *Init = EmitUuidofInitializer(Uuid);
15593861d79fSDimitry Andric   assert(Init && "failed to initialize as constant");
15603861d79fSDimitry Andric 
156159d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
1562f785676fSDimitry Andric       getModule(), Init->getType(),
1563f785676fSDimitry Andric       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
156433956c43SDimitry Andric   if (supportsCOMDAT())
156533956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
15660623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
15673861d79fSDimitry Andric }
15683861d79fSDimitry Andric 
15690623d748SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1570f22ef01cSRoman Divacky   const AliasAttr *AA = VD->getAttr<AliasAttr>();
1571f22ef01cSRoman Divacky   assert(AA && "No alias?");
1572f22ef01cSRoman Divacky 
15730623d748SDimitry Andric   CharUnits Alignment = getContext().getDeclAlign(VD);
15746122f3e6SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1575f22ef01cSRoman Divacky 
1576f22ef01cSRoman Divacky   // See if there is already something with the target's name in the module.
1577f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
15783861d79fSDimitry Andric   if (Entry) {
15793861d79fSDimitry Andric     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
15800623d748SDimitry Andric     auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
15810623d748SDimitry Andric     return ConstantAddress(Ptr, Alignment);
15823861d79fSDimitry Andric   }
1583f22ef01cSRoman Divacky 
1584f22ef01cSRoman Divacky   llvm::Constant *Aliasee;
1585f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(DeclTy))
15863861d79fSDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
15873861d79fSDimitry Andric                                       GlobalDecl(cast<FunctionDecl>(VD)),
15882754fe60SDimitry Andric                                       /*ForVTable=*/false);
1589f22ef01cSRoman Divacky   else
1590f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
159159d1ed5bSDimitry Andric                                     llvm::PointerType::getUnqual(DeclTy),
159259d1ed5bSDimitry Andric                                     nullptr);
15933861d79fSDimitry Andric 
159459d1ed5bSDimitry Andric   auto *F = cast<llvm::GlobalValue>(Aliasee);
1595f22ef01cSRoman Divacky   F->setLinkage(llvm::Function::ExternalWeakLinkage);
1596f22ef01cSRoman Divacky   WeakRefReferences.insert(F);
1597f22ef01cSRoman Divacky 
15980623d748SDimitry Andric   return ConstantAddress(Aliasee, Alignment);
1599f22ef01cSRoman Divacky }
1600f22ef01cSRoman Divacky 
1601f22ef01cSRoman Divacky void CodeGenModule::EmitGlobal(GlobalDecl GD) {
160259d1ed5bSDimitry Andric   const auto *Global = cast<ValueDecl>(GD.getDecl());
1603f22ef01cSRoman Divacky 
1604f22ef01cSRoman Divacky   // Weak references don't produce any output by themselves.
1605f22ef01cSRoman Divacky   if (Global->hasAttr<WeakRefAttr>())
1606f22ef01cSRoman Divacky     return;
1607f22ef01cSRoman Divacky 
1608f22ef01cSRoman Divacky   // If this is an alias definition (which otherwise looks like a declaration)
1609f22ef01cSRoman Divacky   // emit it now.
1610f22ef01cSRoman Divacky   if (Global->hasAttr<AliasAttr>())
1611f22ef01cSRoman Divacky     return EmitAliasDefinition(GD);
1612f22ef01cSRoman Divacky 
1613e7145dcbSDimitry Andric   // IFunc like an alias whose value is resolved at runtime by calling resolver.
1614e7145dcbSDimitry Andric   if (Global->hasAttr<IFuncAttr>())
1615e7145dcbSDimitry Andric     return emitIFuncDefinition(GD);
1616e7145dcbSDimitry Andric 
16176122f3e6SDimitry Andric   // If this is CUDA, be selective about which declarations we emit.
1618dff0c46cSDimitry Andric   if (LangOpts.CUDA) {
161933956c43SDimitry Andric     if (LangOpts.CUDAIsDevice) {
16206122f3e6SDimitry Andric       if (!Global->hasAttr<CUDADeviceAttr>() &&
16216122f3e6SDimitry Andric           !Global->hasAttr<CUDAGlobalAttr>() &&
16226122f3e6SDimitry Andric           !Global->hasAttr<CUDAConstantAttr>() &&
16236122f3e6SDimitry Andric           !Global->hasAttr<CUDASharedAttr>())
16246122f3e6SDimitry Andric         return;
16256122f3e6SDimitry Andric     } else {
1626e7145dcbSDimitry Andric       // We need to emit host-side 'shadows' for all global
1627e7145dcbSDimitry Andric       // device-side variables because the CUDA runtime needs their
1628e7145dcbSDimitry Andric       // size and host-side address in order to provide access to
1629e7145dcbSDimitry Andric       // their device-side incarnations.
1630e7145dcbSDimitry Andric 
1631e7145dcbSDimitry Andric       // So device-only functions are the only things we skip.
1632e7145dcbSDimitry Andric       if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
1633e7145dcbSDimitry Andric           Global->hasAttr<CUDADeviceAttr>())
16346122f3e6SDimitry Andric         return;
1635e7145dcbSDimitry Andric 
1636e7145dcbSDimitry Andric       assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
1637e7145dcbSDimitry Andric              "Expected Variable or Function");
1638e580952dSDimitry Andric     }
1639e580952dSDimitry Andric   }
1640e580952dSDimitry Andric 
1641e7145dcbSDimitry Andric   if (LangOpts.OpenMP) {
1642ea942507SDimitry Andric     // If this is OpenMP device, check if it is legal to emit this global
1643ea942507SDimitry Andric     // normally.
1644ea942507SDimitry Andric     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
1645ea942507SDimitry Andric       return;
1646e7145dcbSDimitry Andric     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
1647e7145dcbSDimitry Andric       if (MustBeEmitted(Global))
1648e7145dcbSDimitry Andric         EmitOMPDeclareReduction(DRD);
1649e7145dcbSDimitry Andric       return;
1650e7145dcbSDimitry Andric     }
1651e7145dcbSDimitry Andric   }
1652ea942507SDimitry Andric 
16536122f3e6SDimitry Andric   // Ignore declarations, they will be emitted on their first use.
165459d1ed5bSDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
1655f22ef01cSRoman Divacky     // Forward declarations are emitted lazily on first use.
16566122f3e6SDimitry Andric     if (!FD->doesThisDeclarationHaveABody()) {
16576122f3e6SDimitry Andric       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1658f22ef01cSRoman Divacky         return;
16596122f3e6SDimitry Andric 
16606122f3e6SDimitry Andric       StringRef MangledName = getMangledName(GD);
166159d1ed5bSDimitry Andric 
166259d1ed5bSDimitry Andric       // Compute the function info and LLVM type.
166359d1ed5bSDimitry Andric       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
166459d1ed5bSDimitry Andric       llvm::Type *Ty = getTypes().GetFunctionType(FI);
166559d1ed5bSDimitry Andric 
166659d1ed5bSDimitry Andric       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
166759d1ed5bSDimitry Andric                               /*DontDefer=*/false);
16686122f3e6SDimitry Andric       return;
16696122f3e6SDimitry Andric     }
1670f22ef01cSRoman Divacky   } else {
167159d1ed5bSDimitry Andric     const auto *VD = cast<VarDecl>(Global);
1672f22ef01cSRoman Divacky     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1673e7145dcbSDimitry Andric     // We need to emit device-side global CUDA variables even if a
1674e7145dcbSDimitry Andric     // variable does not have a definition -- we still need to define
1675e7145dcbSDimitry Andric     // host-side shadow for it.
1676e7145dcbSDimitry Andric     bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
1677e7145dcbSDimitry Andric                            !VD->hasDefinition() &&
1678e7145dcbSDimitry Andric                            (VD->hasAttr<CUDAConstantAttr>() ||
1679e7145dcbSDimitry Andric                             VD->hasAttr<CUDADeviceAttr>());
1680e7145dcbSDimitry Andric     if (!MustEmitForCuda &&
1681e7145dcbSDimitry Andric         VD->isThisDeclarationADefinition() != VarDecl::Definition &&
1682e7145dcbSDimitry Andric         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
1683e7145dcbSDimitry Andric       // If this declaration may have caused an inline variable definition to
1684e7145dcbSDimitry Andric       // change linkage, make sure that it's emitted.
1685e7145dcbSDimitry Andric       if (Context.getInlineVariableDefinitionKind(VD) ==
1686e7145dcbSDimitry Andric           ASTContext::InlineVariableDefinitionKind::Strong)
1687e7145dcbSDimitry Andric         GetAddrOfGlobalVar(VD);
1688f22ef01cSRoman Divacky       return;
1689f22ef01cSRoman Divacky     }
1690e7145dcbSDimitry Andric   }
1691f22ef01cSRoman Divacky 
169239d628a0SDimitry Andric   // Defer code generation to first use when possible, e.g. if this is an inline
169339d628a0SDimitry Andric   // function. If the global must always be emitted, do it eagerly if possible
169439d628a0SDimitry Andric   // to benefit from cache locality.
169539d628a0SDimitry Andric   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
1696f22ef01cSRoman Divacky     // Emit the definition if it can't be deferred.
1697f22ef01cSRoman Divacky     EmitGlobalDefinition(GD);
1698f22ef01cSRoman Divacky     return;
1699f22ef01cSRoman Divacky   }
1700f22ef01cSRoman Divacky 
1701e580952dSDimitry Andric   // If we're deferring emission of a C++ variable with an
1702e580952dSDimitry Andric   // initializer, remember the order in which it appeared in the file.
1703dff0c46cSDimitry Andric   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1704e580952dSDimitry Andric       cast<VarDecl>(Global)->hasInit()) {
1705e580952dSDimitry Andric     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
170659d1ed5bSDimitry Andric     CXXGlobalInits.push_back(nullptr);
1707e580952dSDimitry Andric   }
1708e580952dSDimitry Andric 
17096122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
171039d628a0SDimitry Andric   if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) {
171139d628a0SDimitry Andric     // The value has already been used and should therefore be emitted.
171259d1ed5bSDimitry Andric     addDeferredDeclToEmit(GV, GD);
171339d628a0SDimitry Andric   } else if (MustBeEmitted(Global)) {
171439d628a0SDimitry Andric     // The value must be emitted, but cannot be emitted eagerly.
171539d628a0SDimitry Andric     assert(!MayBeEmittedEagerly(Global));
171639d628a0SDimitry Andric     addDeferredDeclToEmit(/*GV=*/nullptr, GD);
171739d628a0SDimitry Andric   } else {
1718f22ef01cSRoman Divacky     // Otherwise, remember that we saw a deferred decl with this name.  The
1719f22ef01cSRoman Divacky     // first use of the mangled name will cause it to move into
1720f22ef01cSRoman Divacky     // DeferredDeclsToEmit.
1721f22ef01cSRoman Divacky     DeferredDecls[MangledName] = GD;
1722f22ef01cSRoman Divacky   }
1723f22ef01cSRoman Divacky }
1724f22ef01cSRoman Divacky 
172520e90f04SDimitry Andric // Check if T is a class type with a destructor that's not dllimport.
172620e90f04SDimitry Andric static bool HasNonDllImportDtor(QualType T) {
172720e90f04SDimitry Andric   if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
172820e90f04SDimitry Andric     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
172920e90f04SDimitry Andric       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
173020e90f04SDimitry Andric         return true;
173120e90f04SDimitry Andric 
173220e90f04SDimitry Andric   return false;
173320e90f04SDimitry Andric }
173420e90f04SDimitry Andric 
1735f8254f43SDimitry Andric namespace {
1736f8254f43SDimitry Andric   struct FunctionIsDirectlyRecursive :
1737f8254f43SDimitry Andric     public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1738f8254f43SDimitry Andric     const StringRef Name;
1739dff0c46cSDimitry Andric     const Builtin::Context &BI;
1740f8254f43SDimitry Andric     bool Result;
1741dff0c46cSDimitry Andric     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1742dff0c46cSDimitry Andric       Name(N), BI(C), Result(false) {
1743f8254f43SDimitry Andric     }
1744f8254f43SDimitry Andric     typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1745f8254f43SDimitry Andric 
1746f8254f43SDimitry Andric     bool TraverseCallExpr(CallExpr *E) {
1747dff0c46cSDimitry Andric       const FunctionDecl *FD = E->getDirectCallee();
1748dff0c46cSDimitry Andric       if (!FD)
1749f8254f43SDimitry Andric         return true;
1750dff0c46cSDimitry Andric       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1751dff0c46cSDimitry Andric       if (Attr && Name == Attr->getLabel()) {
1752dff0c46cSDimitry Andric         Result = true;
1753dff0c46cSDimitry Andric         return false;
1754dff0c46cSDimitry Andric       }
1755dff0c46cSDimitry Andric       unsigned BuiltinID = FD->getBuiltinID();
17563dac3a9bSDimitry Andric       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
1757f8254f43SDimitry Andric         return true;
17580623d748SDimitry Andric       StringRef BuiltinName = BI.getName(BuiltinID);
1759dff0c46cSDimitry Andric       if (BuiltinName.startswith("__builtin_") &&
1760dff0c46cSDimitry Andric           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1761f8254f43SDimitry Andric         Result = true;
1762f8254f43SDimitry Andric         return false;
1763f8254f43SDimitry Andric       }
1764f8254f43SDimitry Andric       return true;
1765f8254f43SDimitry Andric     }
1766f8254f43SDimitry Andric   };
17670623d748SDimitry Andric 
176820e90f04SDimitry Andric   // Make sure we're not referencing non-imported vars or functions.
17690623d748SDimitry Andric   struct DLLImportFunctionVisitor
17700623d748SDimitry Andric       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
17710623d748SDimitry Andric     bool SafeToInline = true;
17720623d748SDimitry Andric 
177344290647SDimitry Andric     bool shouldVisitImplicitCode() const { return true; }
177444290647SDimitry Andric 
17750623d748SDimitry Andric     bool VisitVarDecl(VarDecl *VD) {
177620e90f04SDimitry Andric       if (VD->getTLSKind()) {
17770623d748SDimitry Andric         // A thread-local variable cannot be imported.
177820e90f04SDimitry Andric         SafeToInline = false;
17790623d748SDimitry Andric         return SafeToInline;
17800623d748SDimitry Andric       }
17810623d748SDimitry Andric 
178220e90f04SDimitry Andric       // A variable definition might imply a destructor call.
178320e90f04SDimitry Andric       if (VD->isThisDeclarationADefinition())
178420e90f04SDimitry Andric         SafeToInline = !HasNonDllImportDtor(VD->getType());
178520e90f04SDimitry Andric 
178620e90f04SDimitry Andric       return SafeToInline;
178720e90f04SDimitry Andric     }
178820e90f04SDimitry Andric 
178920e90f04SDimitry Andric     bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
179020e90f04SDimitry Andric       if (const auto *D = E->getTemporary()->getDestructor())
179120e90f04SDimitry Andric         SafeToInline = D->hasAttr<DLLImportAttr>();
179220e90f04SDimitry Andric       return SafeToInline;
179320e90f04SDimitry Andric     }
179420e90f04SDimitry Andric 
17950623d748SDimitry Andric     bool VisitDeclRefExpr(DeclRefExpr *E) {
17960623d748SDimitry Andric       ValueDecl *VD = E->getDecl();
17970623d748SDimitry Andric       if (isa<FunctionDecl>(VD))
17980623d748SDimitry Andric         SafeToInline = VD->hasAttr<DLLImportAttr>();
17990623d748SDimitry Andric       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
18000623d748SDimitry Andric         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
18010623d748SDimitry Andric       return SafeToInline;
18020623d748SDimitry Andric     }
180320e90f04SDimitry Andric 
180444290647SDimitry Andric     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
180544290647SDimitry Andric       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
180644290647SDimitry Andric       return SafeToInline;
180744290647SDimitry Andric     }
180820e90f04SDimitry Andric 
180920e90f04SDimitry Andric     bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
181020e90f04SDimitry Andric       CXXMethodDecl *M = E->getMethodDecl();
181120e90f04SDimitry Andric       if (!M) {
181220e90f04SDimitry Andric         // Call through a pointer to member function. This is safe to inline.
181320e90f04SDimitry Andric         SafeToInline = true;
181420e90f04SDimitry Andric       } else {
181520e90f04SDimitry Andric         SafeToInline = M->hasAttr<DLLImportAttr>();
181620e90f04SDimitry Andric       }
181720e90f04SDimitry Andric       return SafeToInline;
181820e90f04SDimitry Andric     }
181920e90f04SDimitry Andric 
18200623d748SDimitry Andric     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
18210623d748SDimitry Andric       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
18220623d748SDimitry Andric       return SafeToInline;
18230623d748SDimitry Andric     }
182420e90f04SDimitry Andric 
18250623d748SDimitry Andric     bool VisitCXXNewExpr(CXXNewExpr *E) {
18260623d748SDimitry Andric       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
18270623d748SDimitry Andric       return SafeToInline;
18280623d748SDimitry Andric     }
18290623d748SDimitry Andric   };
1830f8254f43SDimitry Andric }
1831f8254f43SDimitry Andric 
1832dff0c46cSDimitry Andric // isTriviallyRecursive - Check if this function calls another
1833dff0c46cSDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin,
1834dff0c46cSDimitry Andric // ends up pointing to itself.
1835f8254f43SDimitry Andric bool
1836dff0c46cSDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1837dff0c46cSDimitry Andric   StringRef Name;
1838dff0c46cSDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1839dff0c46cSDimitry Andric     // asm labels are a special kind of mangling we have to support.
1840dff0c46cSDimitry Andric     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1841dff0c46cSDimitry Andric     if (!Attr)
1842f8254f43SDimitry Andric       return false;
1843dff0c46cSDimitry Andric     Name = Attr->getLabel();
1844dff0c46cSDimitry Andric   } else {
1845dff0c46cSDimitry Andric     Name = FD->getName();
1846dff0c46cSDimitry Andric   }
1847f8254f43SDimitry Andric 
1848dff0c46cSDimitry Andric   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1849dff0c46cSDimitry Andric   Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1850f8254f43SDimitry Andric   return Walker.Result;
1851f8254f43SDimitry Andric }
1852f8254f43SDimitry Andric 
185344290647SDimitry Andric bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1854f785676fSDimitry Andric   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1855f8254f43SDimitry Andric     return true;
185659d1ed5bSDimitry Andric   const auto *F = cast<FunctionDecl>(GD.getDecl());
185759d1ed5bSDimitry Andric   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1858f8254f43SDimitry Andric     return false;
18590623d748SDimitry Andric 
18600623d748SDimitry Andric   if (F->hasAttr<DLLImportAttr>()) {
18610623d748SDimitry Andric     // Check whether it would be safe to inline this dllimport function.
18620623d748SDimitry Andric     DLLImportFunctionVisitor Visitor;
18630623d748SDimitry Andric     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
18640623d748SDimitry Andric     if (!Visitor.SafeToInline)
18650623d748SDimitry Andric       return false;
186644290647SDimitry Andric 
186744290647SDimitry Andric     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
186844290647SDimitry Andric       // Implicit destructor invocations aren't captured in the AST, so the
186944290647SDimitry Andric       // check above can't see them. Check for them manually here.
187044290647SDimitry Andric       for (const Decl *Member : Dtor->getParent()->decls())
187144290647SDimitry Andric         if (isa<FieldDecl>(Member))
187244290647SDimitry Andric           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
187344290647SDimitry Andric             return false;
187444290647SDimitry Andric       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
187544290647SDimitry Andric         if (HasNonDllImportDtor(B.getType()))
187644290647SDimitry Andric           return false;
187744290647SDimitry Andric     }
18780623d748SDimitry Andric   }
18790623d748SDimitry Andric 
1880f8254f43SDimitry Andric   // PR9614. Avoid cases where the source code is lying to us. An available
1881f8254f43SDimitry Andric   // externally function should have an equivalent function somewhere else,
1882f8254f43SDimitry Andric   // but a function that calls itself is clearly not equivalent to the real
1883f8254f43SDimitry Andric   // implementation.
1884f8254f43SDimitry Andric   // This happens in glibc's btowc and in some configure checks.
1885dff0c46cSDimitry Andric   return !isTriviallyRecursive(F);
1886f8254f43SDimitry Andric }
1887f8254f43SDimitry Andric 
188859d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
188959d1ed5bSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
1890f22ef01cSRoman Divacky 
1891f22ef01cSRoman Divacky   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1892f22ef01cSRoman Divacky                                  Context.getSourceManager(),
1893f22ef01cSRoman Divacky                                  "Generating code for declaration");
1894f22ef01cSRoman Divacky 
1895f785676fSDimitry Andric   if (isa<FunctionDecl>(D)) {
1896ffd1746dSEd Schouten     // At -O0, don't generate IR for functions with available_externally
1897ffd1746dSEd Schouten     // linkage.
1898f785676fSDimitry Andric     if (!shouldEmitFunction(GD))
1899ffd1746dSEd Schouten       return;
1900ffd1746dSEd Schouten 
190159d1ed5bSDimitry Andric     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
1902bd5abe19SDimitry Andric       // Make sure to emit the definition(s) before we emit the thunks.
1903bd5abe19SDimitry Andric       // This is necessary for the generation of certain thunks.
190459d1ed5bSDimitry Andric       if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
190539d628a0SDimitry Andric         ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
190659d1ed5bSDimitry Andric       else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
190739d628a0SDimitry Andric         ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
1908bd5abe19SDimitry Andric       else
190959d1ed5bSDimitry Andric         EmitGlobalFunctionDefinition(GD, GV);
1910bd5abe19SDimitry Andric 
1911f22ef01cSRoman Divacky       if (Method->isVirtual())
1912f22ef01cSRoman Divacky         getVTables().EmitThunks(GD);
1913f22ef01cSRoman Divacky 
1914bd5abe19SDimitry Andric       return;
1915ffd1746dSEd Schouten     }
1916f22ef01cSRoman Divacky 
191759d1ed5bSDimitry Andric     return EmitGlobalFunctionDefinition(GD, GV);
1918ffd1746dSEd Schouten   }
1919f22ef01cSRoman Divacky 
192059d1ed5bSDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
1921e7145dcbSDimitry Andric     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
1922f22ef01cSRoman Divacky 
19236122f3e6SDimitry Andric   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1924f22ef01cSRoman Divacky }
1925f22ef01cSRoman Divacky 
19260623d748SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
19270623d748SDimitry Andric                                                       llvm::Function *NewFn);
19280623d748SDimitry Andric 
1929f22ef01cSRoman Divacky /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1930f22ef01cSRoman Divacky /// module, create and return an llvm Function with the specified type. If there
1931f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially
1932f22ef01cSRoman Divacky /// bitcasted to the right type.
1933f22ef01cSRoman Divacky ///
1934f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this.  This is used
1935f22ef01cSRoman Divacky /// to set the attributes on the function when it is first created.
193620e90f04SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
193720e90f04SDimitry Andric     StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
193820e90f04SDimitry Andric     bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
193944290647SDimitry Andric     ForDefinition_t IsForDefinition) {
1940f785676fSDimitry Andric   const Decl *D = GD.getDecl();
1941f785676fSDimitry Andric 
1942f22ef01cSRoman Divacky   // Lookup the entry, lazily creating it if necessary.
1943f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1944f22ef01cSRoman Divacky   if (Entry) {
19453861d79fSDimitry Andric     if (WeakRefReferences.erase(Entry)) {
1946f785676fSDimitry Andric       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
1947f22ef01cSRoman Divacky       if (FD && !FD->hasAttr<WeakAttr>())
1948f22ef01cSRoman Divacky         Entry->setLinkage(llvm::Function::ExternalLinkage);
1949f22ef01cSRoman Divacky     }
1950f22ef01cSRoman Divacky 
195139d628a0SDimitry Andric     // Handle dropped DLL attributes.
195239d628a0SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
195339d628a0SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
195439d628a0SDimitry Andric 
19550623d748SDimitry Andric     // If there are two attempts to define the same mangled name, issue an
19560623d748SDimitry Andric     // error.
19570623d748SDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
19580623d748SDimitry Andric       GlobalDecl OtherGD;
1959e7145dcbSDimitry Andric       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
1960e7145dcbSDimitry Andric       // to make sure that we issue an error only once.
19610623d748SDimitry Andric       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
19620623d748SDimitry Andric           (GD.getCanonicalDecl().getDecl() !=
19630623d748SDimitry Andric            OtherGD.getCanonicalDecl().getDecl()) &&
19640623d748SDimitry Andric           DiagnosedConflictingDefinitions.insert(GD).second) {
19650623d748SDimitry Andric         getDiags().Report(D->getLocation(),
19660623d748SDimitry Andric                           diag::err_duplicate_mangled_name);
19670623d748SDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
19680623d748SDimitry Andric                           diag::note_previous_definition);
19690623d748SDimitry Andric       }
19700623d748SDimitry Andric     }
19710623d748SDimitry Andric 
19720623d748SDimitry Andric     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
19730623d748SDimitry Andric         (Entry->getType()->getElementType() == Ty)) {
1974f22ef01cSRoman Divacky       return Entry;
19750623d748SDimitry Andric     }
1976f22ef01cSRoman Divacky 
1977f22ef01cSRoman Divacky     // Make sure the result is of the correct type.
19780623d748SDimitry Andric     // (If function is requested for a definition, we always need to create a new
19790623d748SDimitry Andric     // function, not just return a bitcast.)
19800623d748SDimitry Andric     if (!IsForDefinition)
198117a519f9SDimitry Andric       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1982f22ef01cSRoman Divacky   }
1983f22ef01cSRoman Divacky 
1984f22ef01cSRoman Divacky   // This function doesn't have a complete type (for example, the return
1985f22ef01cSRoman Divacky   // type is an incomplete struct). Use a fake type instead, and make
1986f22ef01cSRoman Divacky   // sure not to try to set attributes.
1987f22ef01cSRoman Divacky   bool IsIncompleteFunction = false;
1988f22ef01cSRoman Divacky 
19896122f3e6SDimitry Andric   llvm::FunctionType *FTy;
1990f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(Ty)) {
1991f22ef01cSRoman Divacky     FTy = cast<llvm::FunctionType>(Ty);
1992f22ef01cSRoman Divacky   } else {
1993bd5abe19SDimitry Andric     FTy = llvm::FunctionType::get(VoidTy, false);
1994f22ef01cSRoman Divacky     IsIncompleteFunction = true;
1995f22ef01cSRoman Divacky   }
1996ffd1746dSEd Schouten 
19970623d748SDimitry Andric   llvm::Function *F =
19980623d748SDimitry Andric       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
19990623d748SDimitry Andric                              Entry ? StringRef() : MangledName, &getModule());
20000623d748SDimitry Andric 
20010623d748SDimitry Andric   // If we already created a function with the same mangled name (but different
20020623d748SDimitry Andric   // type) before, take its name and add it to the list of functions to be
20030623d748SDimitry Andric   // replaced with F at the end of CodeGen.
20040623d748SDimitry Andric   //
20050623d748SDimitry Andric   // This happens if there is a prototype for a function (e.g. "int f()") and
20060623d748SDimitry Andric   // then a definition of a different type (e.g. "int f(int x)").
20070623d748SDimitry Andric   if (Entry) {
20080623d748SDimitry Andric     F->takeName(Entry);
20090623d748SDimitry Andric 
20100623d748SDimitry Andric     // This might be an implementation of a function without a prototype, in
20110623d748SDimitry Andric     // which case, try to do special replacement of calls which match the new
20120623d748SDimitry Andric     // prototype.  The really key thing here is that we also potentially drop
20130623d748SDimitry Andric     // arguments from the call site so as to make a direct call, which makes the
20140623d748SDimitry Andric     // inliner happier and suppresses a number of optimizer warnings (!) about
20150623d748SDimitry Andric     // dropping arguments.
20160623d748SDimitry Andric     if (!Entry->use_empty()) {
20170623d748SDimitry Andric       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
20180623d748SDimitry Andric       Entry->removeDeadConstantUsers();
20190623d748SDimitry Andric     }
20200623d748SDimitry Andric 
20210623d748SDimitry Andric     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
20220623d748SDimitry Andric         F, Entry->getType()->getElementType()->getPointerTo());
20230623d748SDimitry Andric     addGlobalValReplacement(Entry, BC);
20240623d748SDimitry Andric   }
20250623d748SDimitry Andric 
2026f22ef01cSRoman Divacky   assert(F->getName() == MangledName && "name was uniqued!");
2027f785676fSDimitry Andric   if (D)
202839d628a0SDimitry Andric     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
202920e90f04SDimitry Andric   if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
203020e90f04SDimitry Andric     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
203120e90f04SDimitry Andric     F->addAttributes(llvm::AttributeList::FunctionIndex,
203220e90f04SDimitry Andric                      llvm::AttributeList::get(
203320e90f04SDimitry Andric                          VMContext, llvm::AttributeList::FunctionIndex, B));
2034139f7f9bSDimitry Andric   }
2035f22ef01cSRoman Divacky 
203659d1ed5bSDimitry Andric   if (!DontDefer) {
203759d1ed5bSDimitry Andric     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
203859d1ed5bSDimitry Andric     // each other bottoming out with the base dtor.  Therefore we emit non-base
203959d1ed5bSDimitry Andric     // dtors on usage, even if there is no dtor definition in the TU.
204059d1ed5bSDimitry Andric     if (D && isa<CXXDestructorDecl>(D) &&
204159d1ed5bSDimitry Andric         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
204259d1ed5bSDimitry Andric                                            GD.getDtorType()))
204359d1ed5bSDimitry Andric       addDeferredDeclToEmit(F, GD);
204459d1ed5bSDimitry Andric 
2045f22ef01cSRoman Divacky     // This is the first use or definition of a mangled name.  If there is a
2046f22ef01cSRoman Divacky     // deferred decl with this name, remember that we need to emit it at the end
2047f22ef01cSRoman Divacky     // of the file.
204859d1ed5bSDimitry Andric     auto DDI = DeferredDecls.find(MangledName);
2049f22ef01cSRoman Divacky     if (DDI != DeferredDecls.end()) {
205059d1ed5bSDimitry Andric       // Move the potentially referenced deferred decl to the
205159d1ed5bSDimitry Andric       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
205259d1ed5bSDimitry Andric       // don't need it anymore).
205359d1ed5bSDimitry Andric       addDeferredDeclToEmit(F, DDI->second);
2054f22ef01cSRoman Divacky       DeferredDecls.erase(DDI);
20552754fe60SDimitry Andric 
20562754fe60SDimitry Andric       // Otherwise, there are cases we have to worry about where we're
20572754fe60SDimitry Andric       // using a declaration for which we must emit a definition but where
20582754fe60SDimitry Andric       // we might not find a top-level definition:
20592754fe60SDimitry Andric       //   - member functions defined inline in their classes
20602754fe60SDimitry Andric       //   - friend functions defined inline in some class
20612754fe60SDimitry Andric       //   - special member functions with implicit definitions
20622754fe60SDimitry Andric       // If we ever change our AST traversal to walk into class methods,
20632754fe60SDimitry Andric       // this will be unnecessary.
20642754fe60SDimitry Andric       //
206559d1ed5bSDimitry Andric       // We also don't emit a definition for a function if it's going to be an
206639d628a0SDimitry Andric       // entry in a vtable, unless it's already marked as used.
2067f785676fSDimitry Andric     } else if (getLangOpts().CPlusPlus && D) {
20682754fe60SDimitry Andric       // Look for a declaration that's lexically in a record.
206939d628a0SDimitry Andric       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
207039d628a0SDimitry Andric            FD = FD->getPreviousDecl()) {
20712754fe60SDimitry Andric         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
207239d628a0SDimitry Andric           if (FD->doesThisDeclarationHaveABody()) {
207359d1ed5bSDimitry Andric             addDeferredDeclToEmit(F, GD.getWithDecl(FD));
20742754fe60SDimitry Andric             break;
2075f22ef01cSRoman Divacky           }
2076f22ef01cSRoman Divacky         }
207739d628a0SDimitry Andric       }
2078f22ef01cSRoman Divacky     }
207959d1ed5bSDimitry Andric   }
2080f22ef01cSRoman Divacky 
2081f22ef01cSRoman Divacky   // Make sure the result is of the requested type.
2082f22ef01cSRoman Divacky   if (!IsIncompleteFunction) {
2083f22ef01cSRoman Divacky     assert(F->getType()->getElementType() == Ty);
2084f22ef01cSRoman Divacky     return F;
2085f22ef01cSRoman Divacky   }
2086f22ef01cSRoman Divacky 
208717a519f9SDimitry Andric   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2088f22ef01cSRoman Divacky   return llvm::ConstantExpr::getBitCast(F, PTy);
2089f22ef01cSRoman Divacky }
2090f22ef01cSRoman Divacky 
2091f22ef01cSRoman Divacky /// GetAddrOfFunction - Return the address of the given function.  If Ty is
2092f22ef01cSRoman Divacky /// non-null, then this function will use the specified type if it has to
2093f22ef01cSRoman Divacky /// create it (this occurs when we see a definition of the function).
2094f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
20956122f3e6SDimitry Andric                                                  llvm::Type *Ty,
209659d1ed5bSDimitry Andric                                                  bool ForVTable,
20970623d748SDimitry Andric                                                  bool DontDefer,
209844290647SDimitry Andric                                               ForDefinition_t IsForDefinition) {
2099f22ef01cSRoman Divacky   // If there was no specific requested type, just convert it now.
21000623d748SDimitry Andric   if (!Ty) {
21010623d748SDimitry Andric     const auto *FD = cast<FunctionDecl>(GD.getDecl());
21020623d748SDimitry Andric     auto CanonTy = Context.getCanonicalType(FD->getType());
21030623d748SDimitry Andric     Ty = getTypes().ConvertFunctionType(CanonTy, FD);
21040623d748SDimitry Andric   }
2105ffd1746dSEd Schouten 
21066122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
21070623d748SDimitry Andric   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
210820e90f04SDimitry Andric                                  /*IsThunk=*/false, llvm::AttributeList(),
21090623d748SDimitry Andric                                  IsForDefinition);
2110f22ef01cSRoman Divacky }
2111f22ef01cSRoman Divacky 
211244290647SDimitry Andric static const FunctionDecl *
211344290647SDimitry Andric GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
211444290647SDimitry Andric   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
211544290647SDimitry Andric   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
211644290647SDimitry Andric 
211744290647SDimitry Andric   IdentifierInfo &CII = C.Idents.get(Name);
211844290647SDimitry Andric   for (const auto &Result : DC->lookup(&CII))
211944290647SDimitry Andric     if (const auto FD = dyn_cast<FunctionDecl>(Result))
212044290647SDimitry Andric       return FD;
212144290647SDimitry Andric 
212244290647SDimitry Andric   if (!C.getLangOpts().CPlusPlus)
212344290647SDimitry Andric     return nullptr;
212444290647SDimitry Andric 
212544290647SDimitry Andric   // Demangle the premangled name from getTerminateFn()
212644290647SDimitry Andric   IdentifierInfo &CXXII =
212744290647SDimitry Andric       (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ")
212844290647SDimitry Andric           ? C.Idents.get("terminate")
212944290647SDimitry Andric           : C.Idents.get(Name);
213044290647SDimitry Andric 
213144290647SDimitry Andric   for (const auto &N : {"__cxxabiv1", "std"}) {
213244290647SDimitry Andric     IdentifierInfo &NS = C.Idents.get(N);
213344290647SDimitry Andric     for (const auto &Result : DC->lookup(&NS)) {
213444290647SDimitry Andric       NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
213544290647SDimitry Andric       if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
213644290647SDimitry Andric         for (const auto &Result : LSD->lookup(&NS))
213744290647SDimitry Andric           if ((ND = dyn_cast<NamespaceDecl>(Result)))
213844290647SDimitry Andric             break;
213944290647SDimitry Andric 
214044290647SDimitry Andric       if (ND)
214144290647SDimitry Andric         for (const auto &Result : ND->lookup(&CXXII))
214244290647SDimitry Andric           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
214344290647SDimitry Andric             return FD;
214444290647SDimitry Andric     }
214544290647SDimitry Andric   }
214644290647SDimitry Andric 
214744290647SDimitry Andric   return nullptr;
214844290647SDimitry Andric }
214944290647SDimitry Andric 
2150f22ef01cSRoman Divacky /// CreateRuntimeFunction - Create a new runtime function with the specified
2151f22ef01cSRoman Divacky /// type and name.
2152f22ef01cSRoman Divacky llvm::Constant *
215344290647SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
215420e90f04SDimitry Andric                                      llvm::AttributeList ExtraAttrs,
215544290647SDimitry Andric                                      bool Local) {
215659d1ed5bSDimitry Andric   llvm::Constant *C =
215759d1ed5bSDimitry Andric       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
215844290647SDimitry Andric                               /*DontDefer=*/false, /*IsThunk=*/false,
215944290647SDimitry Andric                               ExtraAttrs);
216044290647SDimitry Andric 
216144290647SDimitry Andric   if (auto *F = dyn_cast<llvm::Function>(C)) {
216244290647SDimitry Andric     if (F->empty()) {
2163139f7f9bSDimitry Andric       F->setCallingConv(getRuntimeCC());
216444290647SDimitry Andric 
216544290647SDimitry Andric       if (!Local && getTriple().isOSBinFormatCOFF() &&
216644290647SDimitry Andric           !getCodeGenOpts().LTOVisibilityPublicStd) {
216744290647SDimitry Andric         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
216844290647SDimitry Andric         if (!FD || FD->hasAttr<DLLImportAttr>()) {
216944290647SDimitry Andric           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
217044290647SDimitry Andric           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
217144290647SDimitry Andric         }
217244290647SDimitry Andric       }
217344290647SDimitry Andric     }
217444290647SDimitry Andric   }
217544290647SDimitry Andric 
2176139f7f9bSDimitry Andric   return C;
2177f22ef01cSRoman Divacky }
2178f22ef01cSRoman Divacky 
217939d628a0SDimitry Andric /// CreateBuiltinFunction - Create a new builtin function with the specified
218039d628a0SDimitry Andric /// type and name.
218139d628a0SDimitry Andric llvm::Constant *
218220e90f04SDimitry Andric CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
218320e90f04SDimitry Andric                                      llvm::AttributeList ExtraAttrs) {
218439d628a0SDimitry Andric   llvm::Constant *C =
218539d628a0SDimitry Andric       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
218639d628a0SDimitry Andric                               /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
218739d628a0SDimitry Andric   if (auto *F = dyn_cast<llvm::Function>(C))
218839d628a0SDimitry Andric     if (F->empty())
218939d628a0SDimitry Andric       F->setCallingConv(getBuiltinCC());
219039d628a0SDimitry Andric   return C;
219139d628a0SDimitry Andric }
219239d628a0SDimitry Andric 
2193dff0c46cSDimitry Andric /// isTypeConstant - Determine whether an object of this type can be emitted
2194dff0c46cSDimitry Andric /// as a constant.
2195dff0c46cSDimitry Andric ///
2196dff0c46cSDimitry Andric /// If ExcludeCtor is true, the duration when the object's constructor runs
2197dff0c46cSDimitry Andric /// will not be considered. The caller will need to verify that the object is
2198dff0c46cSDimitry Andric /// not written to during its construction.
2199dff0c46cSDimitry Andric bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2200dff0c46cSDimitry Andric   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
2201f22ef01cSRoman Divacky     return false;
2202bd5abe19SDimitry Andric 
2203dff0c46cSDimitry Andric   if (Context.getLangOpts().CPlusPlus) {
2204dff0c46cSDimitry Andric     if (const CXXRecordDecl *Record
2205dff0c46cSDimitry Andric           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2206dff0c46cSDimitry Andric       return ExcludeCtor && !Record->hasMutableFields() &&
2207dff0c46cSDimitry Andric              Record->hasTrivialDestructor();
2208f22ef01cSRoman Divacky   }
2209bd5abe19SDimitry Andric 
2210f22ef01cSRoman Divacky   return true;
2211f22ef01cSRoman Divacky }
2212f22ef01cSRoman Divacky 
2213f22ef01cSRoman Divacky /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2214f22ef01cSRoman Divacky /// create and return an llvm GlobalVariable with the specified type.  If there
2215f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially
2216f22ef01cSRoman Divacky /// bitcasted to the right type.
2217f22ef01cSRoman Divacky ///
2218f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this.  This is used
2219f22ef01cSRoman Divacky /// to set the attributes on the global when it is first created.
2220e7145dcbSDimitry Andric ///
2221e7145dcbSDimitry Andric /// If IsForDefinition is true, it is guranteed that an actual global with
2222e7145dcbSDimitry Andric /// type Ty will be returned, not conversion of a variable with the same
2223e7145dcbSDimitry Andric /// mangled name but some other type.
2224f22ef01cSRoman Divacky llvm::Constant *
22256122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
22266122f3e6SDimitry Andric                                      llvm::PointerType *Ty,
2227e7145dcbSDimitry Andric                                      const VarDecl *D,
222844290647SDimitry Andric                                      ForDefinition_t IsForDefinition) {
2229f22ef01cSRoman Divacky   // Lookup the entry, lazily creating it if necessary.
2230f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2231f22ef01cSRoman Divacky   if (Entry) {
22323861d79fSDimitry Andric     if (WeakRefReferences.erase(Entry)) {
2233f22ef01cSRoman Divacky       if (D && !D->hasAttr<WeakAttr>())
2234f22ef01cSRoman Divacky         Entry->setLinkage(llvm::Function::ExternalLinkage);
2235f22ef01cSRoman Divacky     }
2236f22ef01cSRoman Divacky 
223739d628a0SDimitry Andric     // Handle dropped DLL attributes.
223839d628a0SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
223939d628a0SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
224039d628a0SDimitry Andric 
2241f22ef01cSRoman Divacky     if (Entry->getType() == Ty)
2242f22ef01cSRoman Divacky       return Entry;
2243f22ef01cSRoman Divacky 
2244e7145dcbSDimitry Andric     // If there are two attempts to define the same mangled name, issue an
2245e7145dcbSDimitry Andric     // error.
2246e7145dcbSDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
2247e7145dcbSDimitry Andric       GlobalDecl OtherGD;
2248e7145dcbSDimitry Andric       const VarDecl *OtherD;
2249e7145dcbSDimitry Andric 
2250e7145dcbSDimitry Andric       // Check that D is not yet in DiagnosedConflictingDefinitions is required
2251e7145dcbSDimitry Andric       // to make sure that we issue an error only once.
2252e7145dcbSDimitry Andric       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
2253e7145dcbSDimitry Andric           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2254e7145dcbSDimitry Andric           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2255e7145dcbSDimitry Andric           OtherD->hasInit() &&
2256e7145dcbSDimitry Andric           DiagnosedConflictingDefinitions.insert(D).second) {
2257e7145dcbSDimitry Andric         getDiags().Report(D->getLocation(),
2258e7145dcbSDimitry Andric                           diag::err_duplicate_mangled_name);
2259e7145dcbSDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
2260e7145dcbSDimitry Andric                           diag::note_previous_definition);
2261e7145dcbSDimitry Andric       }
2262e7145dcbSDimitry Andric     }
2263e7145dcbSDimitry Andric 
2264f22ef01cSRoman Divacky     // Make sure the result is of the correct type.
2265f785676fSDimitry Andric     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2266f785676fSDimitry Andric       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2267f785676fSDimitry Andric 
2268e7145dcbSDimitry Andric     // (If global is requested for a definition, we always need to create a new
2269e7145dcbSDimitry Andric     // global, not just return a bitcast.)
2270e7145dcbSDimitry Andric     if (!IsForDefinition)
2271f22ef01cSRoman Divacky       return llvm::ConstantExpr::getBitCast(Entry, Ty);
2272f22ef01cSRoman Divacky   }
2273f22ef01cSRoman Divacky 
227459d1ed5bSDimitry Andric   unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
227559d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
227659d1ed5bSDimitry Andric       getModule(), Ty->getElementType(), false,
227759d1ed5bSDimitry Andric       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
227859d1ed5bSDimitry Andric       llvm::GlobalVariable::NotThreadLocal, AddrSpace);
227959d1ed5bSDimitry Andric 
2280e7145dcbSDimitry Andric   // If we already created a global with the same mangled name (but different
2281e7145dcbSDimitry Andric   // type) before, take its name and remove it from its parent.
2282e7145dcbSDimitry Andric   if (Entry) {
2283e7145dcbSDimitry Andric     GV->takeName(Entry);
2284e7145dcbSDimitry Andric 
2285e7145dcbSDimitry Andric     if (!Entry->use_empty()) {
2286e7145dcbSDimitry Andric       llvm::Constant *NewPtrForOldDecl =
2287e7145dcbSDimitry Andric           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2288e7145dcbSDimitry Andric       Entry->replaceAllUsesWith(NewPtrForOldDecl);
2289e7145dcbSDimitry Andric     }
2290e7145dcbSDimitry Andric 
2291e7145dcbSDimitry Andric     Entry->eraseFromParent();
2292e7145dcbSDimitry Andric   }
2293e7145dcbSDimitry Andric 
2294f22ef01cSRoman Divacky   // This is the first use or definition of a mangled name.  If there is a
2295f22ef01cSRoman Divacky   // deferred decl with this name, remember that we need to emit it at the end
2296f22ef01cSRoman Divacky   // of the file.
229759d1ed5bSDimitry Andric   auto DDI = DeferredDecls.find(MangledName);
2298f22ef01cSRoman Divacky   if (DDI != DeferredDecls.end()) {
2299f22ef01cSRoman Divacky     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2300f22ef01cSRoman Divacky     // list, and remove it from DeferredDecls (since we don't need it anymore).
230159d1ed5bSDimitry Andric     addDeferredDeclToEmit(GV, DDI->second);
2302f22ef01cSRoman Divacky     DeferredDecls.erase(DDI);
2303f22ef01cSRoman Divacky   }
2304f22ef01cSRoman Divacky 
2305f22ef01cSRoman Divacky   // Handle things which are present even on external declarations.
2306f22ef01cSRoman Divacky   if (D) {
2307f22ef01cSRoman Divacky     // FIXME: This code is overly simple and should be merged with other global
2308f22ef01cSRoman Divacky     // handling.
2309dff0c46cSDimitry Andric     GV->setConstant(isTypeConstant(D->getType(), false));
2310f22ef01cSRoman Divacky 
231133956c43SDimitry Andric     GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
231233956c43SDimitry Andric 
231359d1ed5bSDimitry Andric     setLinkageAndVisibilityForGV(GV, D);
23142754fe60SDimitry Andric 
2315284c1978SDimitry Andric     if (D->getTLSKind()) {
2316284c1978SDimitry Andric       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
23170623d748SDimitry Andric         CXXThreadLocals.push_back(D);
23187ae0e2c9SDimitry Andric       setTLSMode(GV, *D);
2319f22ef01cSRoman Divacky     }
2320f785676fSDimitry Andric 
2321f785676fSDimitry Andric     // If required by the ABI, treat declarations of static data members with
2322f785676fSDimitry Andric     // inline initializers as definitions.
232359d1ed5bSDimitry Andric     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
2324f785676fSDimitry Andric       EmitGlobalVarDefinition(D);
2325284c1978SDimitry Andric     }
2326f22ef01cSRoman Divacky 
232759d1ed5bSDimitry Andric     // Handle XCore specific ABI requirements.
232844290647SDimitry Andric     if (getTriple().getArch() == llvm::Triple::xcore &&
232959d1ed5bSDimitry Andric         D->getLanguageLinkage() == CLanguageLinkage &&
233059d1ed5bSDimitry Andric         D->getType().isConstant(Context) &&
233159d1ed5bSDimitry Andric         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
233259d1ed5bSDimitry Andric       GV->setSection(".cp.rodata");
233359d1ed5bSDimitry Andric   }
233459d1ed5bSDimitry Andric 
23357ae0e2c9SDimitry Andric   if (AddrSpace != Ty->getAddressSpace())
2336f785676fSDimitry Andric     return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
2337f785676fSDimitry Andric 
2338f22ef01cSRoman Divacky   return GV;
2339f22ef01cSRoman Divacky }
2340f22ef01cSRoman Divacky 
23410623d748SDimitry Andric llvm::Constant *
23420623d748SDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
234344290647SDimitry Andric                                ForDefinition_t IsForDefinition) {
234444290647SDimitry Andric   const Decl *D = GD.getDecl();
234544290647SDimitry Andric   if (isa<CXXConstructorDecl>(D))
234644290647SDimitry Andric     return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
23470623d748SDimitry Andric                                 getFromCtorType(GD.getCtorType()),
23480623d748SDimitry Andric                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
23490623d748SDimitry Andric                                 /*DontDefer=*/false, IsForDefinition);
235044290647SDimitry Andric   else if (isa<CXXDestructorDecl>(D))
235144290647SDimitry Andric     return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
23520623d748SDimitry Andric                                 getFromDtorType(GD.getDtorType()),
23530623d748SDimitry Andric                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
23540623d748SDimitry Andric                                 /*DontDefer=*/false, IsForDefinition);
235544290647SDimitry Andric   else if (isa<CXXMethodDecl>(D)) {
23560623d748SDimitry Andric     auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
235744290647SDimitry Andric         cast<CXXMethodDecl>(D));
23580623d748SDimitry Andric     auto Ty = getTypes().GetFunctionType(*FInfo);
23590623d748SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
23600623d748SDimitry Andric                              IsForDefinition);
236144290647SDimitry Andric   } else if (isa<FunctionDecl>(D)) {
23620623d748SDimitry Andric     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
23630623d748SDimitry Andric     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
23640623d748SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
23650623d748SDimitry Andric                              IsForDefinition);
23660623d748SDimitry Andric   } else
236744290647SDimitry Andric     return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
2368e7145dcbSDimitry Andric                               IsForDefinition);
23690623d748SDimitry Andric }
2370f22ef01cSRoman Divacky 
23712754fe60SDimitry Andric llvm::GlobalVariable *
23726122f3e6SDimitry Andric CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
23736122f3e6SDimitry Andric                                       llvm::Type *Ty,
23742754fe60SDimitry Andric                                       llvm::GlobalValue::LinkageTypes Linkage) {
23752754fe60SDimitry Andric   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
237659d1ed5bSDimitry Andric   llvm::GlobalVariable *OldGV = nullptr;
23772754fe60SDimitry Andric 
23782754fe60SDimitry Andric   if (GV) {
23792754fe60SDimitry Andric     // Check if the variable has the right type.
23802754fe60SDimitry Andric     if (GV->getType()->getElementType() == Ty)
23812754fe60SDimitry Andric       return GV;
23822754fe60SDimitry Andric 
23832754fe60SDimitry Andric     // Because C++ name mangling, the only way we can end up with an already
23842754fe60SDimitry Andric     // existing global with the same name is if it has been declared extern "C".
23852754fe60SDimitry Andric     assert(GV->isDeclaration() && "Declaration has wrong type!");
23862754fe60SDimitry Andric     OldGV = GV;
23872754fe60SDimitry Andric   }
23882754fe60SDimitry Andric 
23892754fe60SDimitry Andric   // Create a new variable.
23902754fe60SDimitry Andric   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
239159d1ed5bSDimitry Andric                                 Linkage, nullptr, Name);
23922754fe60SDimitry Andric 
23932754fe60SDimitry Andric   if (OldGV) {
23942754fe60SDimitry Andric     // Replace occurrences of the old variable if needed.
23952754fe60SDimitry Andric     GV->takeName(OldGV);
23962754fe60SDimitry Andric 
23972754fe60SDimitry Andric     if (!OldGV->use_empty()) {
23982754fe60SDimitry Andric       llvm::Constant *NewPtrForOldDecl =
23992754fe60SDimitry Andric       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
24002754fe60SDimitry Andric       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
24012754fe60SDimitry Andric     }
24022754fe60SDimitry Andric 
24032754fe60SDimitry Andric     OldGV->eraseFromParent();
24042754fe60SDimitry Andric   }
24052754fe60SDimitry Andric 
240633956c43SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker() &&
240733956c43SDimitry Andric       !GV->hasAvailableExternallyLinkage())
240833956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
240933956c43SDimitry Andric 
24102754fe60SDimitry Andric   return GV;
24112754fe60SDimitry Andric }
24122754fe60SDimitry Andric 
2413f22ef01cSRoman Divacky /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
2414f22ef01cSRoman Divacky /// given global variable.  If Ty is non-null and if the global doesn't exist,
2415cb4dff85SDimitry Andric /// then it will be created with the specified type instead of whatever the
2416e7145dcbSDimitry Andric /// normal requested type would be. If IsForDefinition is true, it is guranteed
2417e7145dcbSDimitry Andric /// that an actual global with type Ty will be returned, not conversion of a
2418e7145dcbSDimitry Andric /// variable with the same mangled name but some other type.
2419f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
2420e7145dcbSDimitry Andric                                                   llvm::Type *Ty,
242144290647SDimitry Andric                                            ForDefinition_t IsForDefinition) {
2422f22ef01cSRoman Divacky   assert(D->hasGlobalStorage() && "Not a global variable");
2423f22ef01cSRoman Divacky   QualType ASTTy = D->getType();
242459d1ed5bSDimitry Andric   if (!Ty)
2425f22ef01cSRoman Divacky     Ty = getTypes().ConvertTypeForMem(ASTTy);
2426f22ef01cSRoman Divacky 
24276122f3e6SDimitry Andric   llvm::PointerType *PTy =
24283b0f4066SDimitry Andric     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
2429f22ef01cSRoman Divacky 
24306122f3e6SDimitry Andric   StringRef MangledName = getMangledName(D);
2431e7145dcbSDimitry Andric   return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
2432f22ef01cSRoman Divacky }
2433f22ef01cSRoman Divacky 
2434f22ef01cSRoman Divacky /// CreateRuntimeVariable - Create a new runtime global variable with the
2435f22ef01cSRoman Divacky /// specified type and name.
2436f22ef01cSRoman Divacky llvm::Constant *
24376122f3e6SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
24386122f3e6SDimitry Andric                                      StringRef Name) {
243959d1ed5bSDimitry Andric   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
2440f22ef01cSRoman Divacky }
2441f22ef01cSRoman Divacky 
2442f22ef01cSRoman Divacky void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
2443f22ef01cSRoman Divacky   assert(!D->getInit() && "Cannot emit definite definitions here!");
2444f22ef01cSRoman Divacky 
24456122f3e6SDimitry Andric   StringRef MangledName = getMangledName(D);
2446e7145dcbSDimitry Andric   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
2447e7145dcbSDimitry Andric 
2448e7145dcbSDimitry Andric   // We already have a definition, not declaration, with the same mangled name.
2449e7145dcbSDimitry Andric   // Emitting of declaration is not required (and actually overwrites emitted
2450e7145dcbSDimitry Andric   // definition).
2451e7145dcbSDimitry Andric   if (GV && !GV->isDeclaration())
2452e7145dcbSDimitry Andric     return;
2453e7145dcbSDimitry Andric 
2454e7145dcbSDimitry Andric   // If we have not seen a reference to this variable yet, place it into the
2455e7145dcbSDimitry Andric   // deferred declarations table to be emitted if needed later.
2456e7145dcbSDimitry Andric   if (!MustBeEmitted(D) && !GV) {
2457f22ef01cSRoman Divacky       DeferredDecls[MangledName] = D;
2458f22ef01cSRoman Divacky       return;
2459f22ef01cSRoman Divacky   }
2460f22ef01cSRoman Divacky 
2461f22ef01cSRoman Divacky   // The tentative definition is the only definition.
2462f22ef01cSRoman Divacky   EmitGlobalVarDefinition(D);
2463f22ef01cSRoman Divacky }
2464f22ef01cSRoman Divacky 
24656122f3e6SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
24662754fe60SDimitry Andric   return Context.toCharUnitsFromBits(
24670623d748SDimitry Andric       getDataLayout().getTypeStoreSizeInBits(Ty));
2468f22ef01cSRoman Divacky }
2469f22ef01cSRoman Divacky 
24707ae0e2c9SDimitry Andric unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
24717ae0e2c9SDimitry Andric                                                  unsigned AddrSpace) {
2472e7145dcbSDimitry Andric   if (D && LangOpts.CUDA && LangOpts.CUDAIsDevice) {
24737ae0e2c9SDimitry Andric     if (D->hasAttr<CUDAConstantAttr>())
24747ae0e2c9SDimitry Andric       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
24757ae0e2c9SDimitry Andric     else if (D->hasAttr<CUDASharedAttr>())
24767ae0e2c9SDimitry Andric       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
24777ae0e2c9SDimitry Andric     else
24787ae0e2c9SDimitry Andric       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
24797ae0e2c9SDimitry Andric   }
24807ae0e2c9SDimitry Andric 
24817ae0e2c9SDimitry Andric   return AddrSpace;
24827ae0e2c9SDimitry Andric }
24837ae0e2c9SDimitry Andric 
2484284c1978SDimitry Andric template<typename SomeDecl>
2485284c1978SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
2486284c1978SDimitry Andric                                                llvm::GlobalValue *GV) {
2487284c1978SDimitry Andric   if (!getLangOpts().CPlusPlus)
2488284c1978SDimitry Andric     return;
2489284c1978SDimitry Andric 
2490284c1978SDimitry Andric   // Must have 'used' attribute, or else inline assembly can't rely on
2491284c1978SDimitry Andric   // the name existing.
2492284c1978SDimitry Andric   if (!D->template hasAttr<UsedAttr>())
2493284c1978SDimitry Andric     return;
2494284c1978SDimitry Andric 
2495284c1978SDimitry Andric   // Must have internal linkage and an ordinary name.
2496f785676fSDimitry Andric   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
2497284c1978SDimitry Andric     return;
2498284c1978SDimitry Andric 
2499284c1978SDimitry Andric   // Must be in an extern "C" context. Entities declared directly within
2500284c1978SDimitry Andric   // a record are not extern "C" even if the record is in such a context.
2501f785676fSDimitry Andric   const SomeDecl *First = D->getFirstDecl();
2502284c1978SDimitry Andric   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
2503284c1978SDimitry Andric     return;
2504284c1978SDimitry Andric 
2505284c1978SDimitry Andric   // OK, this is an internal linkage entity inside an extern "C" linkage
2506284c1978SDimitry Andric   // specification. Make a note of that so we can give it the "expected"
2507284c1978SDimitry Andric   // mangled name if nothing else is using that name.
2508284c1978SDimitry Andric   std::pair<StaticExternCMap::iterator, bool> R =
2509284c1978SDimitry Andric       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
2510284c1978SDimitry Andric 
2511284c1978SDimitry Andric   // If we have multiple internal linkage entities with the same name
2512284c1978SDimitry Andric   // in extern "C" regions, none of them gets that name.
2513284c1978SDimitry Andric   if (!R.second)
251459d1ed5bSDimitry Andric     R.first->second = nullptr;
2515284c1978SDimitry Andric }
2516284c1978SDimitry Andric 
251733956c43SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
251833956c43SDimitry Andric   if (!CGM.supportsCOMDAT())
251933956c43SDimitry Andric     return false;
252033956c43SDimitry Andric 
252133956c43SDimitry Andric   if (D.hasAttr<SelectAnyAttr>())
252233956c43SDimitry Andric     return true;
252333956c43SDimitry Andric 
252433956c43SDimitry Andric   GVALinkage Linkage;
252533956c43SDimitry Andric   if (auto *VD = dyn_cast<VarDecl>(&D))
252633956c43SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
252733956c43SDimitry Andric   else
252833956c43SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
252933956c43SDimitry Andric 
253033956c43SDimitry Andric   switch (Linkage) {
253133956c43SDimitry Andric   case GVA_Internal:
253233956c43SDimitry Andric   case GVA_AvailableExternally:
253333956c43SDimitry Andric   case GVA_StrongExternal:
253433956c43SDimitry Andric     return false;
253533956c43SDimitry Andric   case GVA_DiscardableODR:
253633956c43SDimitry Andric   case GVA_StrongODR:
253733956c43SDimitry Andric     return true;
253833956c43SDimitry Andric   }
253933956c43SDimitry Andric   llvm_unreachable("No such linkage");
254033956c43SDimitry Andric }
254133956c43SDimitry Andric 
254233956c43SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
254333956c43SDimitry Andric                                           llvm::GlobalObject &GO) {
254433956c43SDimitry Andric   if (!shouldBeInCOMDAT(*this, D))
254533956c43SDimitry Andric     return;
254633956c43SDimitry Andric   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
254733956c43SDimitry Andric }
254833956c43SDimitry Andric 
2549e7145dcbSDimitry Andric /// Pass IsTentative as true if you want to create a tentative definition.
2550e7145dcbSDimitry Andric void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
2551e7145dcbSDimitry Andric                                             bool IsTentative) {
255244290647SDimitry Andric   // OpenCL global variables of sampler type are translated to function calls,
255344290647SDimitry Andric   // therefore no need to be translated.
2554f22ef01cSRoman Divacky   QualType ASTTy = D->getType();
255544290647SDimitry Andric   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
255644290647SDimitry Andric     return;
255744290647SDimitry Andric 
255844290647SDimitry Andric   llvm::Constant *Init = nullptr;
2559dff0c46cSDimitry Andric   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2560dff0c46cSDimitry Andric   bool NeedsGlobalCtor = false;
2561dff0c46cSDimitry Andric   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
2562f22ef01cSRoman Divacky 
2563dff0c46cSDimitry Andric   const VarDecl *InitDecl;
2564dff0c46cSDimitry Andric   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
2565f22ef01cSRoman Divacky 
2566e7145dcbSDimitry Andric   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
2567e7145dcbSDimitry Andric   // as part of their declaration."  Sema has already checked for
2568e7145dcbSDimitry Andric   // error cases, so we just need to set Init to UndefValue.
2569e7145dcbSDimitry Andric   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
2570e7145dcbSDimitry Andric       D->hasAttr<CUDASharedAttr>())
25710623d748SDimitry Andric     Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
2572e7145dcbSDimitry Andric   else if (!InitExpr) {
2573f22ef01cSRoman Divacky     // This is a tentative definition; tentative definitions are
2574f22ef01cSRoman Divacky     // implicitly initialized with { 0 }.
2575f22ef01cSRoman Divacky     //
2576f22ef01cSRoman Divacky     // Note that tentative definitions are only emitted at the end of
2577f22ef01cSRoman Divacky     // a translation unit, so they should never have incomplete
2578f22ef01cSRoman Divacky     // type. In addition, EmitTentativeDefinition makes sure that we
2579f22ef01cSRoman Divacky     // never attempt to emit a tentative definition if a real one
2580f22ef01cSRoman Divacky     // exists. A use may still exists, however, so we still may need
2581f22ef01cSRoman Divacky     // to do a RAUW.
2582f22ef01cSRoman Divacky     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
2583f22ef01cSRoman Divacky     Init = EmitNullConstant(D->getType());
2584f22ef01cSRoman Divacky   } else {
25857ae0e2c9SDimitry Andric     initializedGlobalDecl = GlobalDecl(D);
2586dff0c46cSDimitry Andric     Init = EmitConstantInit(*InitDecl);
2587f785676fSDimitry Andric 
2588f22ef01cSRoman Divacky     if (!Init) {
2589f22ef01cSRoman Divacky       QualType T = InitExpr->getType();
2590f22ef01cSRoman Divacky       if (D->getType()->isReferenceType())
2591f22ef01cSRoman Divacky         T = D->getType();
2592f22ef01cSRoman Divacky 
2593dff0c46cSDimitry Andric       if (getLangOpts().CPlusPlus) {
2594f22ef01cSRoman Divacky         Init = EmitNullConstant(T);
2595dff0c46cSDimitry Andric         NeedsGlobalCtor = true;
2596f22ef01cSRoman Divacky       } else {
2597f22ef01cSRoman Divacky         ErrorUnsupported(D, "static initializer");
2598f22ef01cSRoman Divacky         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
2599f22ef01cSRoman Divacky       }
2600e580952dSDimitry Andric     } else {
2601e580952dSDimitry Andric       // We don't need an initializer, so remove the entry for the delayed
2602dff0c46cSDimitry Andric       // initializer position (just in case this entry was delayed) if we
2603dff0c46cSDimitry Andric       // also don't need to register a destructor.
2604dff0c46cSDimitry Andric       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
2605e580952dSDimitry Andric         DelayedCXXInitPosition.erase(D);
2606f22ef01cSRoman Divacky     }
2607f22ef01cSRoman Divacky   }
2608f22ef01cSRoman Divacky 
26096122f3e6SDimitry Andric   llvm::Type* InitType = Init->getType();
2610e7145dcbSDimitry Andric   llvm::Constant *Entry =
261144290647SDimitry Andric       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
2612f22ef01cSRoman Divacky 
2613f22ef01cSRoman Divacky   // Strip off a bitcast if we got one back.
261459d1ed5bSDimitry Andric   if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2615f22ef01cSRoman Divacky     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2616f785676fSDimitry Andric            CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2617f785676fSDimitry Andric            // All zero index gep.
2618f22ef01cSRoman Divacky            CE->getOpcode() == llvm::Instruction::GetElementPtr);
2619f22ef01cSRoman Divacky     Entry = CE->getOperand(0);
2620f22ef01cSRoman Divacky   }
2621f22ef01cSRoman Divacky 
2622f22ef01cSRoman Divacky   // Entry is now either a Function or GlobalVariable.
262359d1ed5bSDimitry Andric   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
2624f22ef01cSRoman Divacky 
2625f22ef01cSRoman Divacky   // We have a definition after a declaration with the wrong type.
2626f22ef01cSRoman Divacky   // We must make a new GlobalVariable* and update everything that used OldGV
2627f22ef01cSRoman Divacky   // (a declaration or tentative definition) with the new GlobalVariable*
2628f22ef01cSRoman Divacky   // (which will be a definition).
2629f22ef01cSRoman Divacky   //
2630f22ef01cSRoman Divacky   // This happens if there is a prototype for a global (e.g.
2631f22ef01cSRoman Divacky   // "extern int x[];") and then a definition of a different type (e.g.
2632f22ef01cSRoman Divacky   // "int x[10];"). This also happens when an initializer has a different type
2633f22ef01cSRoman Divacky   // from the type of the global (this happens with unions).
263459d1ed5bSDimitry Andric   if (!GV ||
2635f22ef01cSRoman Divacky       GV->getType()->getElementType() != InitType ||
26363b0f4066SDimitry Andric       GV->getType()->getAddressSpace() !=
26377ae0e2c9SDimitry Andric        GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
2638f22ef01cSRoman Divacky 
2639f22ef01cSRoman Divacky     // Move the old entry aside so that we'll create a new one.
26406122f3e6SDimitry Andric     Entry->setName(StringRef());
2641f22ef01cSRoman Divacky 
2642f22ef01cSRoman Divacky     // Make a new global with the correct type, this is now guaranteed to work.
2643e7145dcbSDimitry Andric     GV = cast<llvm::GlobalVariable>(
264444290647SDimitry Andric         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
2645f22ef01cSRoman Divacky 
2646f22ef01cSRoman Divacky     // Replace all uses of the old global with the new global
2647f22ef01cSRoman Divacky     llvm::Constant *NewPtrForOldDecl =
2648f22ef01cSRoman Divacky         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2649f22ef01cSRoman Divacky     Entry->replaceAllUsesWith(NewPtrForOldDecl);
2650f22ef01cSRoman Divacky 
2651f22ef01cSRoman Divacky     // Erase the old global, since it is no longer used.
2652f22ef01cSRoman Divacky     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2653f22ef01cSRoman Divacky   }
2654f22ef01cSRoman Divacky 
2655284c1978SDimitry Andric   MaybeHandleStaticInExternC(D, GV);
2656284c1978SDimitry Andric 
26576122f3e6SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
26586122f3e6SDimitry Andric     AddGlobalAnnotations(D, GV);
2659f22ef01cSRoman Divacky 
2660e7145dcbSDimitry Andric   // Set the llvm linkage type as appropriate.
2661e7145dcbSDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
2662e7145dcbSDimitry Andric       getLLVMLinkageVarDefinition(D, GV->isConstant());
2663e7145dcbSDimitry Andric 
26640623d748SDimitry Andric   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
26650623d748SDimitry Andric   // the device. [...]"
26660623d748SDimitry Andric   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
26670623d748SDimitry Andric   // __device__, declares a variable that: [...]
26680623d748SDimitry Andric   // Is accessible from all the threads within the grid and from the host
26690623d748SDimitry Andric   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
26700623d748SDimitry Andric   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
2671e7145dcbSDimitry Andric   if (GV && LangOpts.CUDA) {
2672e7145dcbSDimitry Andric     if (LangOpts.CUDAIsDevice) {
2673e7145dcbSDimitry Andric       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
26740623d748SDimitry Andric         GV->setExternallyInitialized(true);
2675e7145dcbSDimitry Andric     } else {
2676e7145dcbSDimitry Andric       // Host-side shadows of external declarations of device-side
2677e7145dcbSDimitry Andric       // global variables become internal definitions. These have to
2678e7145dcbSDimitry Andric       // be internal in order to prevent name conflicts with global
2679e7145dcbSDimitry Andric       // host variables with the same name in a different TUs.
2680e7145dcbSDimitry Andric       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
2681e7145dcbSDimitry Andric         Linkage = llvm::GlobalValue::InternalLinkage;
2682e7145dcbSDimitry Andric 
2683e7145dcbSDimitry Andric         // Shadow variables and their properties must be registered
2684e7145dcbSDimitry Andric         // with CUDA runtime.
2685e7145dcbSDimitry Andric         unsigned Flags = 0;
2686e7145dcbSDimitry Andric         if (!D->hasDefinition())
2687e7145dcbSDimitry Andric           Flags |= CGCUDARuntime::ExternDeviceVar;
2688e7145dcbSDimitry Andric         if (D->hasAttr<CUDAConstantAttr>())
2689e7145dcbSDimitry Andric           Flags |= CGCUDARuntime::ConstantDeviceVar;
2690e7145dcbSDimitry Andric         getCUDARuntime().registerDeviceVar(*GV, Flags);
2691e7145dcbSDimitry Andric       } else if (D->hasAttr<CUDASharedAttr>())
2692e7145dcbSDimitry Andric         // __shared__ variables are odd. Shadows do get created, but
2693e7145dcbSDimitry Andric         // they are not registered with the CUDA runtime, so they
2694e7145dcbSDimitry Andric         // can't really be used to access their device-side
2695e7145dcbSDimitry Andric         // counterparts. It's not clear yet whether it's nvcc's bug or
2696e7145dcbSDimitry Andric         // a feature, but we've got to do the same for compatibility.
2697e7145dcbSDimitry Andric         Linkage = llvm::GlobalValue::InternalLinkage;
2698e7145dcbSDimitry Andric     }
26990623d748SDimitry Andric   }
2700f22ef01cSRoman Divacky   GV->setInitializer(Init);
2701f22ef01cSRoman Divacky 
2702f22ef01cSRoman Divacky   // If it is safe to mark the global 'constant', do so now.
2703dff0c46cSDimitry Andric   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2704dff0c46cSDimitry Andric                   isTypeConstant(D->getType(), true));
2705f22ef01cSRoman Divacky 
270639d628a0SDimitry Andric   // If it is in a read-only section, mark it 'constant'.
270739d628a0SDimitry Andric   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
270839d628a0SDimitry Andric     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
270939d628a0SDimitry Andric     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
271039d628a0SDimitry Andric       GV->setConstant(true);
271139d628a0SDimitry Andric   }
271239d628a0SDimitry Andric 
2713f22ef01cSRoman Divacky   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2714f22ef01cSRoman Divacky 
2715f785676fSDimitry Andric 
27160623d748SDimitry Andric   // On Darwin, if the normal linkage of a C++ thread_local variable is
27170623d748SDimitry Andric   // LinkOnce or Weak, we keep the normal linkage to prevent multiple
27180623d748SDimitry Andric   // copies within a linkage unit; otherwise, the backing variable has
27190623d748SDimitry Andric   // internal linkage and all accesses should just be calls to the
272059d1ed5bSDimitry Andric   // Itanium-specified entry point, which has the normal linkage of the
27210623d748SDimitry Andric   // variable. This is to preserve the ability to change the implementation
27220623d748SDimitry Andric   // behind the scenes.
272339d628a0SDimitry Andric   if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
27240623d748SDimitry Andric       Context.getTargetInfo().getTriple().isOSDarwin() &&
27250623d748SDimitry Andric       !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
27260623d748SDimitry Andric       !llvm::GlobalVariable::isWeakLinkage(Linkage))
272759d1ed5bSDimitry Andric     Linkage = llvm::GlobalValue::InternalLinkage;
272859d1ed5bSDimitry Andric 
272959d1ed5bSDimitry Andric   GV->setLinkage(Linkage);
273059d1ed5bSDimitry Andric   if (D->hasAttr<DLLImportAttr>())
273159d1ed5bSDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
273259d1ed5bSDimitry Andric   else if (D->hasAttr<DLLExportAttr>())
273359d1ed5bSDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
273439d628a0SDimitry Andric   else
273539d628a0SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2736f785676fSDimitry Andric 
273744290647SDimitry Andric   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
2738f22ef01cSRoman Divacky     // common vars aren't constant even if declared const.
2739f22ef01cSRoman Divacky     GV->setConstant(false);
274044290647SDimitry Andric     // Tentative definition of global variables may be initialized with
274144290647SDimitry Andric     // non-zero null pointers. In this case they should have weak linkage
274244290647SDimitry Andric     // since common linkage must have zero initializer and must not have
274344290647SDimitry Andric     // explicit section therefore cannot have non-zero initial value.
274444290647SDimitry Andric     if (!GV->getInitializer()->isNullValue())
274544290647SDimitry Andric       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
274644290647SDimitry Andric   }
2747f22ef01cSRoman Divacky 
274859d1ed5bSDimitry Andric   setNonAliasAttributes(D, GV);
2749f22ef01cSRoman Divacky 
275039d628a0SDimitry Andric   if (D->getTLSKind() && !GV->isThreadLocal()) {
275139d628a0SDimitry Andric     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
27520623d748SDimitry Andric       CXXThreadLocals.push_back(D);
275339d628a0SDimitry Andric     setTLSMode(GV, *D);
275439d628a0SDimitry Andric   }
275539d628a0SDimitry Andric 
275633956c43SDimitry Andric   maybeSetTrivialComdat(*D, *GV);
275733956c43SDimitry Andric 
27582754fe60SDimitry Andric   // Emit the initializer function if necessary.
2759dff0c46cSDimitry Andric   if (NeedsGlobalCtor || NeedsGlobalDtor)
2760dff0c46cSDimitry Andric     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
27612754fe60SDimitry Andric 
276239d628a0SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
27633861d79fSDimitry Andric 
2764f22ef01cSRoman Divacky   // Emit global variable debug information.
27656122f3e6SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
2766e7145dcbSDimitry Andric     if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
2767f22ef01cSRoman Divacky       DI->EmitGlobalVariable(GV, D);
2768f22ef01cSRoman Divacky }
2769f22ef01cSRoman Divacky 
277039d628a0SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context,
277133956c43SDimitry Andric                                       CodeGenModule &CGM, const VarDecl *D,
277233956c43SDimitry Andric                                       bool NoCommon) {
277359d1ed5bSDimitry Andric   // Don't give variables common linkage if -fno-common was specified unless it
277459d1ed5bSDimitry Andric   // was overridden by a NoCommon attribute.
277559d1ed5bSDimitry Andric   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
277659d1ed5bSDimitry Andric     return true;
277759d1ed5bSDimitry Andric 
277859d1ed5bSDimitry Andric   // C11 6.9.2/2:
277959d1ed5bSDimitry Andric   //   A declaration of an identifier for an object that has file scope without
278059d1ed5bSDimitry Andric   //   an initializer, and without a storage-class specifier or with the
278159d1ed5bSDimitry Andric   //   storage-class specifier static, constitutes a tentative definition.
278259d1ed5bSDimitry Andric   if (D->getInit() || D->hasExternalStorage())
278359d1ed5bSDimitry Andric     return true;
278459d1ed5bSDimitry Andric 
278559d1ed5bSDimitry Andric   // A variable cannot be both common and exist in a section.
278659d1ed5bSDimitry Andric   if (D->hasAttr<SectionAttr>())
278759d1ed5bSDimitry Andric     return true;
278859d1ed5bSDimitry Andric 
278959d1ed5bSDimitry Andric   // Thread local vars aren't considered common linkage.
279059d1ed5bSDimitry Andric   if (D->getTLSKind())
279159d1ed5bSDimitry Andric     return true;
279259d1ed5bSDimitry Andric 
279359d1ed5bSDimitry Andric   // Tentative definitions marked with WeakImportAttr are true definitions.
279459d1ed5bSDimitry Andric   if (D->hasAttr<WeakImportAttr>())
279559d1ed5bSDimitry Andric     return true;
279659d1ed5bSDimitry Andric 
279733956c43SDimitry Andric   // A variable cannot be both common and exist in a comdat.
279833956c43SDimitry Andric   if (shouldBeInCOMDAT(CGM, *D))
279933956c43SDimitry Andric     return true;
280033956c43SDimitry Andric 
2801e7145dcbSDimitry Andric   // Declarations with a required alignment do not have common linkage in MSVC
280239d628a0SDimitry Andric   // mode.
28030623d748SDimitry Andric   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
280433956c43SDimitry Andric     if (D->hasAttr<AlignedAttr>())
280539d628a0SDimitry Andric       return true;
280633956c43SDimitry Andric     QualType VarType = D->getType();
280733956c43SDimitry Andric     if (Context.isAlignmentRequired(VarType))
280833956c43SDimitry Andric       return true;
280933956c43SDimitry Andric 
281033956c43SDimitry Andric     if (const auto *RT = VarType->getAs<RecordType>()) {
281133956c43SDimitry Andric       const RecordDecl *RD = RT->getDecl();
281233956c43SDimitry Andric       for (const FieldDecl *FD : RD->fields()) {
281333956c43SDimitry Andric         if (FD->isBitField())
281433956c43SDimitry Andric           continue;
281533956c43SDimitry Andric         if (FD->hasAttr<AlignedAttr>())
281633956c43SDimitry Andric           return true;
281733956c43SDimitry Andric         if (Context.isAlignmentRequired(FD->getType()))
281833956c43SDimitry Andric           return true;
281933956c43SDimitry Andric       }
282033956c43SDimitry Andric     }
282133956c43SDimitry Andric   }
282239d628a0SDimitry Andric 
282359d1ed5bSDimitry Andric   return false;
282459d1ed5bSDimitry Andric }
282559d1ed5bSDimitry Andric 
282659d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
282759d1ed5bSDimitry Andric     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
28282754fe60SDimitry Andric   if (Linkage == GVA_Internal)
28292754fe60SDimitry Andric     return llvm::Function::InternalLinkage;
283059d1ed5bSDimitry Andric 
283159d1ed5bSDimitry Andric   if (D->hasAttr<WeakAttr>()) {
283259d1ed5bSDimitry Andric     if (IsConstantVariable)
283359d1ed5bSDimitry Andric       return llvm::GlobalVariable::WeakODRLinkage;
283459d1ed5bSDimitry Andric     else
283559d1ed5bSDimitry Andric       return llvm::GlobalVariable::WeakAnyLinkage;
283659d1ed5bSDimitry Andric   }
283759d1ed5bSDimitry Andric 
283859d1ed5bSDimitry Andric   // We are guaranteed to have a strong definition somewhere else,
283959d1ed5bSDimitry Andric   // so we can use available_externally linkage.
284059d1ed5bSDimitry Andric   if (Linkage == GVA_AvailableExternally)
284120e90f04SDimitry Andric     return llvm::GlobalValue::AvailableExternallyLinkage;
284259d1ed5bSDimitry Andric 
284359d1ed5bSDimitry Andric   // Note that Apple's kernel linker doesn't support symbol
284459d1ed5bSDimitry Andric   // coalescing, so we need to avoid linkonce and weak linkages there.
284559d1ed5bSDimitry Andric   // Normally, this means we just map to internal, but for explicit
284659d1ed5bSDimitry Andric   // instantiations we'll map to external.
284759d1ed5bSDimitry Andric 
284859d1ed5bSDimitry Andric   // In C++, the compiler has to emit a definition in every translation unit
284959d1ed5bSDimitry Andric   // that references the function.  We should use linkonce_odr because
285059d1ed5bSDimitry Andric   // a) if all references in this translation unit are optimized away, we
285159d1ed5bSDimitry Andric   // don't need to codegen it.  b) if the function persists, it needs to be
285259d1ed5bSDimitry Andric   // merged with other definitions. c) C++ has the ODR, so we know the
285359d1ed5bSDimitry Andric   // definition is dependable.
285459d1ed5bSDimitry Andric   if (Linkage == GVA_DiscardableODR)
285559d1ed5bSDimitry Andric     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
285659d1ed5bSDimitry Andric                                             : llvm::Function::InternalLinkage;
285759d1ed5bSDimitry Andric 
285859d1ed5bSDimitry Andric   // An explicit instantiation of a template has weak linkage, since
285959d1ed5bSDimitry Andric   // explicit instantiations can occur in multiple translation units
286059d1ed5bSDimitry Andric   // and must all be equivalent. However, we are not allowed to
286159d1ed5bSDimitry Andric   // throw away these explicit instantiations.
2862e7145dcbSDimitry Andric   //
2863e7145dcbSDimitry Andric   // We don't currently support CUDA device code spread out across multiple TUs,
2864e7145dcbSDimitry Andric   // so say that CUDA templates are either external (for kernels) or internal.
2865e7145dcbSDimitry Andric   // This lets llvm perform aggressive inter-procedural optimizations.
2866e7145dcbSDimitry Andric   if (Linkage == GVA_StrongODR) {
2867e7145dcbSDimitry Andric     if (Context.getLangOpts().AppleKext)
2868e7145dcbSDimitry Andric       return llvm::Function::ExternalLinkage;
2869e7145dcbSDimitry Andric     if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
2870e7145dcbSDimitry Andric       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
2871e7145dcbSDimitry Andric                                           : llvm::Function::InternalLinkage;
2872e7145dcbSDimitry Andric     return llvm::Function::WeakODRLinkage;
2873e7145dcbSDimitry Andric   }
287459d1ed5bSDimitry Andric 
287559d1ed5bSDimitry Andric   // C++ doesn't have tentative definitions and thus cannot have common
287659d1ed5bSDimitry Andric   // linkage.
287759d1ed5bSDimitry Andric   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
287833956c43SDimitry Andric       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
287939d628a0SDimitry Andric                                  CodeGenOpts.NoCommon))
288059d1ed5bSDimitry Andric     return llvm::GlobalVariable::CommonLinkage;
288159d1ed5bSDimitry Andric 
2882f785676fSDimitry Andric   // selectany symbols are externally visible, so use weak instead of
2883f785676fSDimitry Andric   // linkonce.  MSVC optimizes away references to const selectany globals, so
2884f785676fSDimitry Andric   // all definitions should be the same and ODR linkage should be used.
2885f785676fSDimitry Andric   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
288659d1ed5bSDimitry Andric   if (D->hasAttr<SelectAnyAttr>())
2887f785676fSDimitry Andric     return llvm::GlobalVariable::WeakODRLinkage;
288859d1ed5bSDimitry Andric 
288959d1ed5bSDimitry Andric   // Otherwise, we have strong external linkage.
289059d1ed5bSDimitry Andric   assert(Linkage == GVA_StrongExternal);
28912754fe60SDimitry Andric   return llvm::GlobalVariable::ExternalLinkage;
28922754fe60SDimitry Andric }
28932754fe60SDimitry Andric 
289459d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
289559d1ed5bSDimitry Andric     const VarDecl *VD, bool IsConstant) {
289659d1ed5bSDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
289759d1ed5bSDimitry Andric   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
289859d1ed5bSDimitry Andric }
289959d1ed5bSDimitry Andric 
2900139f7f9bSDimitry Andric /// Replace the uses of a function that was declared with a non-proto type.
2901139f7f9bSDimitry Andric /// We want to silently drop extra arguments from call sites
2902139f7f9bSDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2903139f7f9bSDimitry Andric                                           llvm::Function *newFn) {
2904139f7f9bSDimitry Andric   // Fast path.
2905139f7f9bSDimitry Andric   if (old->use_empty()) return;
2906139f7f9bSDimitry Andric 
2907139f7f9bSDimitry Andric   llvm::Type *newRetTy = newFn->getReturnType();
2908139f7f9bSDimitry Andric   SmallVector<llvm::Value*, 4> newArgs;
29090623d748SDimitry Andric   SmallVector<llvm::OperandBundleDef, 1> newBundles;
2910139f7f9bSDimitry Andric 
2911139f7f9bSDimitry Andric   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2912139f7f9bSDimitry Andric          ui != ue; ) {
2913139f7f9bSDimitry Andric     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
291459d1ed5bSDimitry Andric     llvm::User *user = use->getUser();
2915139f7f9bSDimitry Andric 
2916139f7f9bSDimitry Andric     // Recognize and replace uses of bitcasts.  Most calls to
2917139f7f9bSDimitry Andric     // unprototyped functions will use bitcasts.
291859d1ed5bSDimitry Andric     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
2919139f7f9bSDimitry Andric       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2920139f7f9bSDimitry Andric         replaceUsesOfNonProtoConstant(bitcast, newFn);
2921139f7f9bSDimitry Andric       continue;
2922139f7f9bSDimitry Andric     }
2923139f7f9bSDimitry Andric 
2924139f7f9bSDimitry Andric     // Recognize calls to the function.
2925139f7f9bSDimitry Andric     llvm::CallSite callSite(user);
2926139f7f9bSDimitry Andric     if (!callSite) continue;
292759d1ed5bSDimitry Andric     if (!callSite.isCallee(&*use)) continue;
2928139f7f9bSDimitry Andric 
2929139f7f9bSDimitry Andric     // If the return types don't match exactly, then we can't
2930139f7f9bSDimitry Andric     // transform this call unless it's dead.
2931139f7f9bSDimitry Andric     if (callSite->getType() != newRetTy && !callSite->use_empty())
2932139f7f9bSDimitry Andric       continue;
2933139f7f9bSDimitry Andric 
2934139f7f9bSDimitry Andric     // Get the call site's attribute list.
293520e90f04SDimitry Andric     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
293620e90f04SDimitry Andric     llvm::AttributeList oldAttrs = callSite.getAttributes();
2937139f7f9bSDimitry Andric 
2938139f7f9bSDimitry Andric     // If the function was passed too few arguments, don't transform.
2939139f7f9bSDimitry Andric     unsigned newNumArgs = newFn->arg_size();
2940139f7f9bSDimitry Andric     if (callSite.arg_size() < newNumArgs) continue;
2941139f7f9bSDimitry Andric 
2942139f7f9bSDimitry Andric     // If extra arguments were passed, we silently drop them.
2943139f7f9bSDimitry Andric     // If any of the types mismatch, we don't transform.
2944139f7f9bSDimitry Andric     unsigned argNo = 0;
2945139f7f9bSDimitry Andric     bool dontTransform = false;
294620e90f04SDimitry Andric     for (llvm::Argument &A : newFn->args()) {
294720e90f04SDimitry Andric       if (callSite.getArgument(argNo)->getType() != A.getType()) {
2948139f7f9bSDimitry Andric         dontTransform = true;
2949139f7f9bSDimitry Andric         break;
2950139f7f9bSDimitry Andric       }
2951139f7f9bSDimitry Andric 
2952139f7f9bSDimitry Andric       // Add any parameter attributes.
295320e90f04SDimitry Andric       newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
295420e90f04SDimitry Andric       argNo++;
2955139f7f9bSDimitry Andric     }
2956139f7f9bSDimitry Andric     if (dontTransform)
2957139f7f9bSDimitry Andric       continue;
2958139f7f9bSDimitry Andric 
2959139f7f9bSDimitry Andric     // Okay, we can transform this.  Create the new call instruction and copy
2960139f7f9bSDimitry Andric     // over the required information.
2961139f7f9bSDimitry Andric     newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2962139f7f9bSDimitry Andric 
29630623d748SDimitry Andric     // Copy over any operand bundles.
29640623d748SDimitry Andric     callSite.getOperandBundlesAsDefs(newBundles);
29650623d748SDimitry Andric 
2966139f7f9bSDimitry Andric     llvm::CallSite newCall;
2967139f7f9bSDimitry Andric     if (callSite.isCall()) {
29680623d748SDimitry Andric       newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
2969139f7f9bSDimitry Andric                                        callSite.getInstruction());
2970139f7f9bSDimitry Andric     } else {
297159d1ed5bSDimitry Andric       auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
2972139f7f9bSDimitry Andric       newCall = llvm::InvokeInst::Create(newFn,
2973139f7f9bSDimitry Andric                                          oldInvoke->getNormalDest(),
2974139f7f9bSDimitry Andric                                          oldInvoke->getUnwindDest(),
29750623d748SDimitry Andric                                          newArgs, newBundles, "",
2976139f7f9bSDimitry Andric                                          callSite.getInstruction());
2977139f7f9bSDimitry Andric     }
2978139f7f9bSDimitry Andric     newArgs.clear(); // for the next iteration
2979139f7f9bSDimitry Andric 
2980139f7f9bSDimitry Andric     if (!newCall->getType()->isVoidTy())
2981139f7f9bSDimitry Andric       newCall->takeName(callSite.getInstruction());
298220e90f04SDimitry Andric     newCall.setAttributes(llvm::AttributeList::get(
298320e90f04SDimitry Andric         newFn->getContext(), oldAttrs.getFnAttributes(),
298420e90f04SDimitry Andric         oldAttrs.getRetAttributes(), newArgAttrs));
2985139f7f9bSDimitry Andric     newCall.setCallingConv(callSite.getCallingConv());
2986139f7f9bSDimitry Andric 
2987139f7f9bSDimitry Andric     // Finally, remove the old call, replacing any uses with the new one.
2988139f7f9bSDimitry Andric     if (!callSite->use_empty())
2989139f7f9bSDimitry Andric       callSite->replaceAllUsesWith(newCall.getInstruction());
2990139f7f9bSDimitry Andric 
2991139f7f9bSDimitry Andric     // Copy debug location attached to CI.
299233956c43SDimitry Andric     if (callSite->getDebugLoc())
2993139f7f9bSDimitry Andric       newCall->setDebugLoc(callSite->getDebugLoc());
29940623d748SDimitry Andric 
2995139f7f9bSDimitry Andric     callSite->eraseFromParent();
2996139f7f9bSDimitry Andric   }
2997139f7f9bSDimitry Andric }
2998139f7f9bSDimitry Andric 
2999f22ef01cSRoman Divacky /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
3000f22ef01cSRoman Divacky /// implement a function with no prototype, e.g. "int foo() {}".  If there are
3001f22ef01cSRoman Divacky /// existing call uses of the old function in the module, this adjusts them to
3002f22ef01cSRoman Divacky /// call the new function directly.
3003f22ef01cSRoman Divacky ///
3004f22ef01cSRoman Divacky /// This is not just a cleanup: the always_inline pass requires direct calls to
3005f22ef01cSRoman Divacky /// functions to be able to inline them.  If there is a bitcast in the way, it
3006f22ef01cSRoman Divacky /// won't inline them.  Instcombine normally deletes these calls, but it isn't
3007f22ef01cSRoman Divacky /// run at -O0.
3008f22ef01cSRoman Divacky static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3009f22ef01cSRoman Divacky                                                       llvm::Function *NewFn) {
3010f22ef01cSRoman Divacky   // If we're redefining a global as a function, don't transform it.
3011139f7f9bSDimitry Andric   if (!isa<llvm::Function>(Old)) return;
3012f22ef01cSRoman Divacky 
3013139f7f9bSDimitry Andric   replaceUsesOfNonProtoConstant(Old, NewFn);
3014f22ef01cSRoman Divacky }
3015f22ef01cSRoman Divacky 
3016dff0c46cSDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
3017e7145dcbSDimitry Andric   auto DK = VD->isThisDeclarationADefinition();
3018e7145dcbSDimitry Andric   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
3019e7145dcbSDimitry Andric     return;
3020e7145dcbSDimitry Andric 
3021dff0c46cSDimitry Andric   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
3022dff0c46cSDimitry Andric   // If we have a definition, this might be a deferred decl. If the
3023dff0c46cSDimitry Andric   // instantiation is explicit, make sure we emit it at the end.
3024dff0c46cSDimitry Andric   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
3025dff0c46cSDimitry Andric     GetAddrOfGlobalVar(VD);
3026139f7f9bSDimitry Andric 
3027139f7f9bSDimitry Andric   EmitTopLevelDecl(VD);
3028dff0c46cSDimitry Andric }
3029f22ef01cSRoman Divacky 
303059d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
303159d1ed5bSDimitry Andric                                                  llvm::GlobalValue *GV) {
303259d1ed5bSDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
30333b0f4066SDimitry Andric 
30343b0f4066SDimitry Andric   // Compute the function info and LLVM type.
3035dff0c46cSDimitry Andric   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3036dff0c46cSDimitry Andric   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
30373b0f4066SDimitry Andric 
3038f22ef01cSRoman Divacky   // Get or create the prototype for the function.
30390623d748SDimitry Andric   if (!GV || (GV->getType()->getElementType() != Ty))
30400623d748SDimitry Andric     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
30410623d748SDimitry Andric                                                    /*DontDefer=*/true,
304244290647SDimitry Andric                                                    ForDefinition));
3043f22ef01cSRoman Divacky 
30440623d748SDimitry Andric   // Already emitted.
30450623d748SDimitry Andric   if (!GV->isDeclaration())
3046f785676fSDimitry Andric     return;
3047f22ef01cSRoman Divacky 
30482754fe60SDimitry Andric   // We need to set linkage and visibility on the function before
30492754fe60SDimitry Andric   // generating code for it because various parts of IR generation
30502754fe60SDimitry Andric   // want to propagate this information down (e.g. to local static
30512754fe60SDimitry Andric   // declarations).
305259d1ed5bSDimitry Andric   auto *Fn = cast<llvm::Function>(GV);
3053f785676fSDimitry Andric   setFunctionLinkage(GD, Fn);
305497bc6c73SDimitry Andric   setFunctionDLLStorageClass(GD, Fn);
3055f22ef01cSRoman Divacky 
305659d1ed5bSDimitry Andric   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
30572754fe60SDimitry Andric   setGlobalVisibility(Fn, D);
30582754fe60SDimitry Andric 
3059284c1978SDimitry Andric   MaybeHandleStaticInExternC(D, Fn);
3060284c1978SDimitry Andric 
306133956c43SDimitry Andric   maybeSetTrivialComdat(*D, *Fn);
306233956c43SDimitry Andric 
30633b0f4066SDimitry Andric   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
3064f22ef01cSRoman Divacky 
306559d1ed5bSDimitry Andric   setFunctionDefinitionAttributes(D, Fn);
3066f22ef01cSRoman Divacky   SetLLVMFunctionAttributesForDefinition(D, Fn);
3067f22ef01cSRoman Divacky 
3068f22ef01cSRoman Divacky   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
3069f22ef01cSRoman Divacky     AddGlobalCtor(Fn, CA->getPriority());
3070f22ef01cSRoman Divacky   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
3071f22ef01cSRoman Divacky     AddGlobalDtor(Fn, DA->getPriority());
30726122f3e6SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
30736122f3e6SDimitry Andric     AddGlobalAnnotations(D, Fn);
3074f22ef01cSRoman Divacky }
3075f22ef01cSRoman Divacky 
3076f22ef01cSRoman Divacky void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
307759d1ed5bSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
3078f22ef01cSRoman Divacky   const AliasAttr *AA = D->getAttr<AliasAttr>();
3079f22ef01cSRoman Divacky   assert(AA && "Not an alias?");
3080f22ef01cSRoman Divacky 
30816122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
3082f22ef01cSRoman Divacky 
30839a4b3118SDimitry Andric   if (AA->getAliasee() == MangledName) {
3084e7145dcbSDimitry Andric     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
30859a4b3118SDimitry Andric     return;
30869a4b3118SDimitry Andric   }
30879a4b3118SDimitry Andric 
3088f22ef01cSRoman Divacky   // If there is a definition in the module, then it wins over the alias.
3089f22ef01cSRoman Divacky   // This is dubious, but allow it to be safe.  Just ignore the alias.
3090f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3091f22ef01cSRoman Divacky   if (Entry && !Entry->isDeclaration())
3092f22ef01cSRoman Divacky     return;
3093f22ef01cSRoman Divacky 
3094f785676fSDimitry Andric   Aliases.push_back(GD);
3095f785676fSDimitry Andric 
30966122f3e6SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3097f22ef01cSRoman Divacky 
3098f22ef01cSRoman Divacky   // Create a reference to the named value.  This ensures that it is emitted
3099f22ef01cSRoman Divacky   // if a deferred decl.
3100f22ef01cSRoman Divacky   llvm::Constant *Aliasee;
3101f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(DeclTy))
31023861d79fSDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
31032754fe60SDimitry Andric                                       /*ForVTable=*/false);
3104f22ef01cSRoman Divacky   else
3105f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
310659d1ed5bSDimitry Andric                                     llvm::PointerType::getUnqual(DeclTy),
310739d628a0SDimitry Andric                                     /*D=*/nullptr);
3108f22ef01cSRoman Divacky 
3109f22ef01cSRoman Divacky   // Create the new alias itself, but don't set a name yet.
311059d1ed5bSDimitry Andric   auto *GA = llvm::GlobalAlias::create(
31110623d748SDimitry Andric       DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
3112f22ef01cSRoman Divacky 
3113f22ef01cSRoman Divacky   if (Entry) {
311459d1ed5bSDimitry Andric     if (GA->getAliasee() == Entry) {
3115e7145dcbSDimitry Andric       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
311659d1ed5bSDimitry Andric       return;
311759d1ed5bSDimitry Andric     }
311859d1ed5bSDimitry Andric 
3119f22ef01cSRoman Divacky     assert(Entry->isDeclaration());
3120f22ef01cSRoman Divacky 
3121f22ef01cSRoman Divacky     // If there is a declaration in the module, then we had an extern followed
3122f22ef01cSRoman Divacky     // by the alias, as in:
3123f22ef01cSRoman Divacky     //   extern int test6();
3124f22ef01cSRoman Divacky     //   ...
3125f22ef01cSRoman Divacky     //   int test6() __attribute__((alias("test7")));
3126f22ef01cSRoman Divacky     //
3127f22ef01cSRoman Divacky     // Remove it and replace uses of it with the alias.
3128f22ef01cSRoman Divacky     GA->takeName(Entry);
3129f22ef01cSRoman Divacky 
3130f22ef01cSRoman Divacky     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
3131f22ef01cSRoman Divacky                                                           Entry->getType()));
3132f22ef01cSRoman Divacky     Entry->eraseFromParent();
3133f22ef01cSRoman Divacky   } else {
3134ffd1746dSEd Schouten     GA->setName(MangledName);
3135f22ef01cSRoman Divacky   }
3136f22ef01cSRoman Divacky 
3137f22ef01cSRoman Divacky   // Set attributes which are particular to an alias; this is a
3138f22ef01cSRoman Divacky   // specialization of the attributes which may be set on a global
3139f22ef01cSRoman Divacky   // variable/function.
314039d628a0SDimitry Andric   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
31413b0f4066SDimitry Andric       D->isWeakImported()) {
3142f22ef01cSRoman Divacky     GA->setLinkage(llvm::Function::WeakAnyLinkage);
3143f22ef01cSRoman Divacky   }
3144f22ef01cSRoman Divacky 
314539d628a0SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
314639d628a0SDimitry Andric     if (VD->getTLSKind())
314739d628a0SDimitry Andric       setTLSMode(GA, *VD);
314839d628a0SDimitry Andric 
314939d628a0SDimitry Andric   setAliasAttributes(D, GA);
3150f22ef01cSRoman Divacky }
3151f22ef01cSRoman Divacky 
3152e7145dcbSDimitry Andric void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
3153e7145dcbSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
3154e7145dcbSDimitry Andric   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
3155e7145dcbSDimitry Andric   assert(IFA && "Not an ifunc?");
3156e7145dcbSDimitry Andric 
3157e7145dcbSDimitry Andric   StringRef MangledName = getMangledName(GD);
3158e7145dcbSDimitry Andric 
3159e7145dcbSDimitry Andric   if (IFA->getResolver() == MangledName) {
3160e7145dcbSDimitry Andric     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3161e7145dcbSDimitry Andric     return;
3162e7145dcbSDimitry Andric   }
3163e7145dcbSDimitry Andric 
3164e7145dcbSDimitry Andric   // Report an error if some definition overrides ifunc.
3165e7145dcbSDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3166e7145dcbSDimitry Andric   if (Entry && !Entry->isDeclaration()) {
3167e7145dcbSDimitry Andric     GlobalDecl OtherGD;
3168e7145dcbSDimitry Andric     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3169e7145dcbSDimitry Andric         DiagnosedConflictingDefinitions.insert(GD).second) {
3170e7145dcbSDimitry Andric       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
3171e7145dcbSDimitry Andric       Diags.Report(OtherGD.getDecl()->getLocation(),
3172e7145dcbSDimitry Andric                    diag::note_previous_definition);
3173e7145dcbSDimitry Andric     }
3174e7145dcbSDimitry Andric     return;
3175e7145dcbSDimitry Andric   }
3176e7145dcbSDimitry Andric 
3177e7145dcbSDimitry Andric   Aliases.push_back(GD);
3178e7145dcbSDimitry Andric 
3179e7145dcbSDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3180e7145dcbSDimitry Andric   llvm::Constant *Resolver =
3181e7145dcbSDimitry Andric       GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3182e7145dcbSDimitry Andric                               /*ForVTable=*/false);
3183e7145dcbSDimitry Andric   llvm::GlobalIFunc *GIF =
3184e7145dcbSDimitry Andric       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
3185e7145dcbSDimitry Andric                                 "", Resolver, &getModule());
3186e7145dcbSDimitry Andric   if (Entry) {
3187e7145dcbSDimitry Andric     if (GIF->getResolver() == Entry) {
3188e7145dcbSDimitry Andric       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3189e7145dcbSDimitry Andric       return;
3190e7145dcbSDimitry Andric     }
3191e7145dcbSDimitry Andric     assert(Entry->isDeclaration());
3192e7145dcbSDimitry Andric 
3193e7145dcbSDimitry Andric     // If there is a declaration in the module, then we had an extern followed
3194e7145dcbSDimitry Andric     // by the ifunc, as in:
3195e7145dcbSDimitry Andric     //   extern int test();
3196e7145dcbSDimitry Andric     //   ...
3197e7145dcbSDimitry Andric     //   int test() __attribute__((ifunc("resolver")));
3198e7145dcbSDimitry Andric     //
3199e7145dcbSDimitry Andric     // Remove it and replace uses of it with the ifunc.
3200e7145dcbSDimitry Andric     GIF->takeName(Entry);
3201e7145dcbSDimitry Andric 
3202e7145dcbSDimitry Andric     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3203e7145dcbSDimitry Andric                                                           Entry->getType()));
3204e7145dcbSDimitry Andric     Entry->eraseFromParent();
3205e7145dcbSDimitry Andric   } else
3206e7145dcbSDimitry Andric     GIF->setName(MangledName);
3207e7145dcbSDimitry Andric 
3208e7145dcbSDimitry Andric   SetCommonAttributes(D, GIF);
3209e7145dcbSDimitry Andric }
3210e7145dcbSDimitry Andric 
321117a519f9SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
32126122f3e6SDimitry Andric                                             ArrayRef<llvm::Type*> Tys) {
321317a519f9SDimitry Andric   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
321417a519f9SDimitry Andric                                          Tys);
3215f22ef01cSRoman Divacky }
3216f22ef01cSRoman Divacky 
321733956c43SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> &
321833956c43SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
321933956c43SDimitry Andric                          const StringLiteral *Literal, bool TargetIsLSB,
322033956c43SDimitry Andric                          bool &IsUTF16, unsigned &StringLength) {
32216122f3e6SDimitry Andric   StringRef String = Literal->getString();
3222e580952dSDimitry Andric   unsigned NumBytes = String.size();
3223f22ef01cSRoman Divacky 
3224f22ef01cSRoman Divacky   // Check for simple case.
3225f22ef01cSRoman Divacky   if (!Literal->containsNonAsciiOrNull()) {
3226f22ef01cSRoman Divacky     StringLength = NumBytes;
322739d628a0SDimitry Andric     return *Map.insert(std::make_pair(String, nullptr)).first;
3228f22ef01cSRoman Divacky   }
3229f22ef01cSRoman Divacky 
3230dff0c46cSDimitry Andric   // Otherwise, convert the UTF8 literals into a string of shorts.
3231dff0c46cSDimitry Andric   IsUTF16 = true;
3232dff0c46cSDimitry Andric 
323344290647SDimitry Andric   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
323444290647SDimitry Andric   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
323544290647SDimitry Andric   llvm::UTF16 *ToPtr = &ToBuf[0];
3236f22ef01cSRoman Divacky 
323744290647SDimitry Andric   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
323844290647SDimitry Andric                                  ToPtr + NumBytes, llvm::strictConversion);
3239f22ef01cSRoman Divacky 
3240f22ef01cSRoman Divacky   // ConvertUTF8toUTF16 returns the length in ToPtr.
3241f22ef01cSRoman Divacky   StringLength = ToPtr - &ToBuf[0];
3242f22ef01cSRoman Divacky 
3243dff0c46cSDimitry Andric   // Add an explicit null.
3244dff0c46cSDimitry Andric   *ToPtr = 0;
324539d628a0SDimitry Andric   return *Map.insert(std::make_pair(
324639d628a0SDimitry Andric                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
324739d628a0SDimitry Andric                                    (StringLength + 1) * 2),
324839d628a0SDimitry Andric                          nullptr)).first;
3249f22ef01cSRoman Divacky }
3250f22ef01cSRoman Divacky 
32510623d748SDimitry Andric ConstantAddress
3252f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
3253f22ef01cSRoman Divacky   unsigned StringLength = 0;
3254f22ef01cSRoman Divacky   bool isUTF16 = false;
325533956c43SDimitry Andric   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3256f22ef01cSRoman Divacky       GetConstantCFStringEntry(CFConstantStringMap, Literal,
325733956c43SDimitry Andric                                getDataLayout().isLittleEndian(), isUTF16,
325833956c43SDimitry Andric                                StringLength);
3259f22ef01cSRoman Divacky 
326039d628a0SDimitry Andric   if (auto *C = Entry.second)
32610623d748SDimitry Andric     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
3262f22ef01cSRoman Divacky 
3263dff0c46cSDimitry Andric   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
3264f22ef01cSRoman Divacky   llvm::Constant *Zeros[] = { Zero, Zero };
3265f22ef01cSRoman Divacky 
3266f22ef01cSRoman Divacky   // If we don't already have it, get __CFConstantStringClassReference.
3267f22ef01cSRoman Divacky   if (!CFConstantStringClassRef) {
32686122f3e6SDimitry Andric     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
3269f22ef01cSRoman Divacky     Ty = llvm::ArrayType::get(Ty, 0);
3270e7145dcbSDimitry Andric     llvm::Constant *GV =
3271e7145dcbSDimitry Andric         CreateRuntimeVariable(Ty, "__CFConstantStringClassReference");
3272e7145dcbSDimitry Andric 
327344290647SDimitry Andric     if (getTriple().isOSBinFormatCOFF()) {
3274e7145dcbSDimitry Andric       IdentifierInfo &II = getContext().Idents.get(GV->getName());
3275e7145dcbSDimitry Andric       TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
3276e7145dcbSDimitry Andric       DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3277e7145dcbSDimitry Andric       llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
3278e7145dcbSDimitry Andric 
3279e7145dcbSDimitry Andric       const VarDecl *VD = nullptr;
3280e7145dcbSDimitry Andric       for (const auto &Result : DC->lookup(&II))
3281e7145dcbSDimitry Andric         if ((VD = dyn_cast<VarDecl>(Result)))
3282e7145dcbSDimitry Andric           break;
3283e7145dcbSDimitry Andric 
3284e7145dcbSDimitry Andric       if (!VD || !VD->hasAttr<DLLExportAttr>()) {
3285e7145dcbSDimitry Andric         CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3286e7145dcbSDimitry Andric         CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3287e7145dcbSDimitry Andric       } else {
3288e7145dcbSDimitry Andric         CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3289e7145dcbSDimitry Andric         CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3290e7145dcbSDimitry Andric       }
3291e7145dcbSDimitry Andric     }
3292e7145dcbSDimitry Andric 
3293f22ef01cSRoman Divacky     // Decay array -> ptr
329444290647SDimitry Andric     CFConstantStringClassRef =
329544290647SDimitry Andric         llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
3296e7145dcbSDimitry Andric   }
3297f22ef01cSRoman Divacky 
3298f22ef01cSRoman Divacky   QualType CFTy = getContext().getCFConstantStringType();
3299f22ef01cSRoman Divacky 
330059d1ed5bSDimitry Andric   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
3301f22ef01cSRoman Divacky 
330244290647SDimitry Andric   ConstantInitBuilder Builder(*this);
330344290647SDimitry Andric   auto Fields = Builder.beginStruct(STy);
3304f22ef01cSRoman Divacky 
3305f22ef01cSRoman Divacky   // Class pointer.
330644290647SDimitry Andric   Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
3307f22ef01cSRoman Divacky 
3308f22ef01cSRoman Divacky   // Flags.
330944290647SDimitry Andric   Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
3310f22ef01cSRoman Divacky 
3311f22ef01cSRoman Divacky   // String pointer.
331259d1ed5bSDimitry Andric   llvm::Constant *C = nullptr;
3313dff0c46cSDimitry Andric   if (isUTF16) {
33140623d748SDimitry Andric     auto Arr = llvm::makeArrayRef(
331539d628a0SDimitry Andric         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
331639d628a0SDimitry Andric         Entry.first().size() / 2);
3317dff0c46cSDimitry Andric     C = llvm::ConstantDataArray::get(VMContext, Arr);
3318dff0c46cSDimitry Andric   } else {
331939d628a0SDimitry Andric     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
3320dff0c46cSDimitry Andric   }
3321f22ef01cSRoman Divacky 
3322dff0c46cSDimitry Andric   // Note: -fwritable-strings doesn't make the backing store strings of
3323dff0c46cSDimitry Andric   // CFStrings writable. (See <rdar://problem/10657500>)
332459d1ed5bSDimitry Andric   auto *GV =
3325dff0c46cSDimitry Andric       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
332659d1ed5bSDimitry Andric                                llvm::GlobalValue::PrivateLinkage, C, ".str");
3327e7145dcbSDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3328284c1978SDimitry Andric   // Don't enforce the target's minimum global alignment, since the only use
3329284c1978SDimitry Andric   // of the string is via this class initializer.
3330e7145dcbSDimitry Andric   CharUnits Align = isUTF16
3331e7145dcbSDimitry Andric                         ? getContext().getTypeAlignInChars(getContext().ShortTy)
3332e7145dcbSDimitry Andric                         : getContext().getTypeAlignInChars(getContext().CharTy);
3333f22ef01cSRoman Divacky   GV->setAlignment(Align.getQuantity());
3334e7145dcbSDimitry Andric 
3335e7145dcbSDimitry Andric   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
3336e7145dcbSDimitry Andric   // Without it LLVM can merge the string with a non unnamed_addr one during
3337e7145dcbSDimitry Andric   // LTO.  Doing that changes the section it ends in, which surprises ld64.
333844290647SDimitry Andric   if (getTriple().isOSBinFormatMachO())
3339e7145dcbSDimitry Andric     GV->setSection(isUTF16 ? "__TEXT,__ustring"
3340e7145dcbSDimitry Andric                            : "__TEXT,__cstring,cstring_literals");
3341dff0c46cSDimitry Andric 
3342dff0c46cSDimitry Andric   // String.
334344290647SDimitry Andric   llvm::Constant *Str =
334433956c43SDimitry Andric       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3345f22ef01cSRoman Divacky 
3346dff0c46cSDimitry Andric   if (isUTF16)
3347dff0c46cSDimitry Andric     // Cast the UTF16 string to the correct type.
334844290647SDimitry Andric     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
334944290647SDimitry Andric   Fields.add(Str);
3350dff0c46cSDimitry Andric 
3351f22ef01cSRoman Divacky   // String length.
335244290647SDimitry Andric   auto Ty = getTypes().ConvertType(getContext().LongTy);
335344290647SDimitry Andric   Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
3354f22ef01cSRoman Divacky 
33550623d748SDimitry Andric   CharUnits Alignment = getPointerAlign();
33560623d748SDimitry Andric 
3357f22ef01cSRoman Divacky   // The struct.
335844290647SDimitry Andric   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
335944290647SDimitry Andric                                     /*isConstant=*/false,
336044290647SDimitry Andric                                     llvm::GlobalVariable::PrivateLinkage);
336144290647SDimitry Andric   switch (getTriple().getObjectFormat()) {
3362e7145dcbSDimitry Andric   case llvm::Triple::UnknownObjectFormat:
3363e7145dcbSDimitry Andric     llvm_unreachable("unknown file format");
3364e7145dcbSDimitry Andric   case llvm::Triple::COFF:
3365e7145dcbSDimitry Andric   case llvm::Triple::ELF:
336620e90f04SDimitry Andric   case llvm::Triple::Wasm:
3367e7145dcbSDimitry Andric     GV->setSection("cfstring");
3368e7145dcbSDimitry Andric     break;
3369e7145dcbSDimitry Andric   case llvm::Triple::MachO:
3370e7145dcbSDimitry Andric     GV->setSection("__DATA,__cfstring");
3371e7145dcbSDimitry Andric     break;
3372e7145dcbSDimitry Andric   }
337339d628a0SDimitry Andric   Entry.second = GV;
3374f22ef01cSRoman Divacky 
33750623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
3376f22ef01cSRoman Divacky }
3377f22ef01cSRoman Divacky 
33786122f3e6SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() {
33796122f3e6SDimitry Andric   if (ObjCFastEnumerationStateType.isNull()) {
338059d1ed5bSDimitry Andric     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
33816122f3e6SDimitry Andric     D->startDefinition();
33826122f3e6SDimitry Andric 
33836122f3e6SDimitry Andric     QualType FieldTypes[] = {
33846122f3e6SDimitry Andric       Context.UnsignedLongTy,
33856122f3e6SDimitry Andric       Context.getPointerType(Context.getObjCIdType()),
33866122f3e6SDimitry Andric       Context.getPointerType(Context.UnsignedLongTy),
33876122f3e6SDimitry Andric       Context.getConstantArrayType(Context.UnsignedLongTy,
33886122f3e6SDimitry Andric                            llvm::APInt(32, 5), ArrayType::Normal, 0)
33896122f3e6SDimitry Andric     };
33906122f3e6SDimitry Andric 
33916122f3e6SDimitry Andric     for (size_t i = 0; i < 4; ++i) {
33926122f3e6SDimitry Andric       FieldDecl *Field = FieldDecl::Create(Context,
33936122f3e6SDimitry Andric                                            D,
33946122f3e6SDimitry Andric                                            SourceLocation(),
339559d1ed5bSDimitry Andric                                            SourceLocation(), nullptr,
339659d1ed5bSDimitry Andric                                            FieldTypes[i], /*TInfo=*/nullptr,
339759d1ed5bSDimitry Andric                                            /*BitWidth=*/nullptr,
33986122f3e6SDimitry Andric                                            /*Mutable=*/false,
33997ae0e2c9SDimitry Andric                                            ICIS_NoInit);
34006122f3e6SDimitry Andric       Field->setAccess(AS_public);
34016122f3e6SDimitry Andric       D->addDecl(Field);
34026122f3e6SDimitry Andric     }
34036122f3e6SDimitry Andric 
34046122f3e6SDimitry Andric     D->completeDefinition();
34056122f3e6SDimitry Andric     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
34066122f3e6SDimitry Andric   }
34076122f3e6SDimitry Andric 
34086122f3e6SDimitry Andric   return ObjCFastEnumerationStateType;
34096122f3e6SDimitry Andric }
34106122f3e6SDimitry Andric 
3411dff0c46cSDimitry Andric llvm::Constant *
3412dff0c46cSDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
3413dff0c46cSDimitry Andric   assert(!E->getType()->isPointerType() && "Strings are always arrays");
3414f22ef01cSRoman Divacky 
3415dff0c46cSDimitry Andric   // Don't emit it as the address of the string, emit the string data itself
3416dff0c46cSDimitry Andric   // as an inline array.
3417dff0c46cSDimitry Andric   if (E->getCharByteWidth() == 1) {
3418dff0c46cSDimitry Andric     SmallString<64> Str(E->getString());
3419f22ef01cSRoman Divacky 
3420dff0c46cSDimitry Andric     // Resize the string to the right size, which is indicated by its type.
3421dff0c46cSDimitry Andric     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
3422dff0c46cSDimitry Andric     Str.resize(CAT->getSize().getZExtValue());
3423dff0c46cSDimitry Andric     return llvm::ConstantDataArray::getString(VMContext, Str, false);
34246122f3e6SDimitry Andric   }
3425f22ef01cSRoman Divacky 
342659d1ed5bSDimitry Andric   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
3427dff0c46cSDimitry Andric   llvm::Type *ElemTy = AType->getElementType();
3428dff0c46cSDimitry Andric   unsigned NumElements = AType->getNumElements();
3429f22ef01cSRoman Divacky 
3430dff0c46cSDimitry Andric   // Wide strings have either 2-byte or 4-byte elements.
3431dff0c46cSDimitry Andric   if (ElemTy->getPrimitiveSizeInBits() == 16) {
3432dff0c46cSDimitry Andric     SmallVector<uint16_t, 32> Elements;
3433dff0c46cSDimitry Andric     Elements.reserve(NumElements);
3434dff0c46cSDimitry Andric 
3435dff0c46cSDimitry Andric     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3436dff0c46cSDimitry Andric       Elements.push_back(E->getCodeUnit(i));
3437dff0c46cSDimitry Andric     Elements.resize(NumElements);
3438dff0c46cSDimitry Andric     return llvm::ConstantDataArray::get(VMContext, Elements);
3439dff0c46cSDimitry Andric   }
3440dff0c46cSDimitry Andric 
3441dff0c46cSDimitry Andric   assert(ElemTy->getPrimitiveSizeInBits() == 32);
3442dff0c46cSDimitry Andric   SmallVector<uint32_t, 32> Elements;
3443dff0c46cSDimitry Andric   Elements.reserve(NumElements);
3444dff0c46cSDimitry Andric 
3445dff0c46cSDimitry Andric   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3446dff0c46cSDimitry Andric     Elements.push_back(E->getCodeUnit(i));
3447dff0c46cSDimitry Andric   Elements.resize(NumElements);
3448dff0c46cSDimitry Andric   return llvm::ConstantDataArray::get(VMContext, Elements);
3449f22ef01cSRoman Divacky }
3450f22ef01cSRoman Divacky 
345159d1ed5bSDimitry Andric static llvm::GlobalVariable *
345259d1ed5bSDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
345359d1ed5bSDimitry Andric                       CodeGenModule &CGM, StringRef GlobalName,
34540623d748SDimitry Andric                       CharUnits Alignment) {
345559d1ed5bSDimitry Andric   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
345659d1ed5bSDimitry Andric   unsigned AddrSpace = 0;
345759d1ed5bSDimitry Andric   if (CGM.getLangOpts().OpenCL)
345859d1ed5bSDimitry Andric     AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
3459dff0c46cSDimitry Andric 
346033956c43SDimitry Andric   llvm::Module &M = CGM.getModule();
346159d1ed5bSDimitry Andric   // Create a global variable for this string
346259d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
346333956c43SDimitry Andric       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
346433956c43SDimitry Andric       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
34650623d748SDimitry Andric   GV->setAlignment(Alignment.getQuantity());
3466e7145dcbSDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
346733956c43SDimitry Andric   if (GV->isWeakForLinker()) {
346833956c43SDimitry Andric     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
346933956c43SDimitry Andric     GV->setComdat(M.getOrInsertComdat(GV->getName()));
347033956c43SDimitry Andric   }
347133956c43SDimitry Andric 
347259d1ed5bSDimitry Andric   return GV;
3473f22ef01cSRoman Divacky }
3474dff0c46cSDimitry Andric 
347559d1ed5bSDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
347659d1ed5bSDimitry Andric /// constant array for the given string literal.
34770623d748SDimitry Andric ConstantAddress
347839d628a0SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
347939d628a0SDimitry Andric                                                   StringRef Name) {
34800623d748SDimitry Andric   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
3481dff0c46cSDimitry Andric 
348259d1ed5bSDimitry Andric   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
348359d1ed5bSDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
348459d1ed5bSDimitry Andric   if (!LangOpts.WritableStrings) {
348559d1ed5bSDimitry Andric     Entry = &ConstantStringMap[C];
348659d1ed5bSDimitry Andric     if (auto GV = *Entry) {
34870623d748SDimitry Andric       if (Alignment.getQuantity() > GV->getAlignment())
34880623d748SDimitry Andric         GV->setAlignment(Alignment.getQuantity());
34890623d748SDimitry Andric       return ConstantAddress(GV, Alignment);
349059d1ed5bSDimitry Andric     }
349159d1ed5bSDimitry Andric   }
349259d1ed5bSDimitry Andric 
349359d1ed5bSDimitry Andric   SmallString<256> MangledNameBuffer;
349459d1ed5bSDimitry Andric   StringRef GlobalVariableName;
349559d1ed5bSDimitry Andric   llvm::GlobalValue::LinkageTypes LT;
349659d1ed5bSDimitry Andric 
349759d1ed5bSDimitry Andric   // Mangle the string literal if the ABI allows for it.  However, we cannot
349859d1ed5bSDimitry Andric   // do this if  we are compiling with ASan or -fwritable-strings because they
349959d1ed5bSDimitry Andric   // rely on strings having normal linkage.
350039d628a0SDimitry Andric   if (!LangOpts.WritableStrings &&
350139d628a0SDimitry Andric       !LangOpts.Sanitize.has(SanitizerKind::Address) &&
350259d1ed5bSDimitry Andric       getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
350359d1ed5bSDimitry Andric     llvm::raw_svector_ostream Out(MangledNameBuffer);
350459d1ed5bSDimitry Andric     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
350559d1ed5bSDimitry Andric 
350659d1ed5bSDimitry Andric     LT = llvm::GlobalValue::LinkOnceODRLinkage;
350759d1ed5bSDimitry Andric     GlobalVariableName = MangledNameBuffer;
350859d1ed5bSDimitry Andric   } else {
350959d1ed5bSDimitry Andric     LT = llvm::GlobalValue::PrivateLinkage;
351039d628a0SDimitry Andric     GlobalVariableName = Name;
351159d1ed5bSDimitry Andric   }
351259d1ed5bSDimitry Andric 
351359d1ed5bSDimitry Andric   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
351459d1ed5bSDimitry Andric   if (Entry)
351559d1ed5bSDimitry Andric     *Entry = GV;
351659d1ed5bSDimitry Andric 
351739d628a0SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
351839d628a0SDimitry Andric                                   QualType());
35190623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
3520f22ef01cSRoman Divacky }
3521f22ef01cSRoman Divacky 
3522f22ef01cSRoman Divacky /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
3523f22ef01cSRoman Divacky /// array for the given ObjCEncodeExpr node.
35240623d748SDimitry Andric ConstantAddress
3525f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
3526f22ef01cSRoman Divacky   std::string Str;
3527f22ef01cSRoman Divacky   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
3528f22ef01cSRoman Divacky 
3529f22ef01cSRoman Divacky   return GetAddrOfConstantCString(Str);
3530f22ef01cSRoman Divacky }
3531f22ef01cSRoman Divacky 
353259d1ed5bSDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing
353359d1ed5bSDimitry Andric /// the literal and a terminating '\0' character.
353459d1ed5bSDimitry Andric /// The result has pointer to array type.
35350623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString(
35360623d748SDimitry Andric     const std::string &Str, const char *GlobalName) {
353759d1ed5bSDimitry Andric   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
35380623d748SDimitry Andric   CharUnits Alignment =
35390623d748SDimitry Andric     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
3540f22ef01cSRoman Divacky 
354159d1ed5bSDimitry Andric   llvm::Constant *C =
354259d1ed5bSDimitry Andric       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
354359d1ed5bSDimitry Andric 
354459d1ed5bSDimitry Andric   // Don't share any string literals if strings aren't constant.
354559d1ed5bSDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
354659d1ed5bSDimitry Andric   if (!LangOpts.WritableStrings) {
354759d1ed5bSDimitry Andric     Entry = &ConstantStringMap[C];
354859d1ed5bSDimitry Andric     if (auto GV = *Entry) {
35490623d748SDimitry Andric       if (Alignment.getQuantity() > GV->getAlignment())
35500623d748SDimitry Andric         GV->setAlignment(Alignment.getQuantity());
35510623d748SDimitry Andric       return ConstantAddress(GV, Alignment);
355259d1ed5bSDimitry Andric     }
355359d1ed5bSDimitry Andric   }
355459d1ed5bSDimitry Andric 
3555f22ef01cSRoman Divacky   // Get the default prefix if a name wasn't specified.
3556f22ef01cSRoman Divacky   if (!GlobalName)
3557f22ef01cSRoman Divacky     GlobalName = ".str";
3558f22ef01cSRoman Divacky   // Create a global variable for this.
355959d1ed5bSDimitry Andric   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
356059d1ed5bSDimitry Andric                                   GlobalName, Alignment);
356159d1ed5bSDimitry Andric   if (Entry)
356259d1ed5bSDimitry Andric     *Entry = GV;
35630623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
3564f22ef01cSRoman Divacky }
3565f22ef01cSRoman Divacky 
35660623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
3567f785676fSDimitry Andric     const MaterializeTemporaryExpr *E, const Expr *Init) {
3568f785676fSDimitry Andric   assert((E->getStorageDuration() == SD_Static ||
3569f785676fSDimitry Andric           E->getStorageDuration() == SD_Thread) && "not a global temporary");
357059d1ed5bSDimitry Andric   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
3571f785676fSDimitry Andric 
3572f785676fSDimitry Andric   // If we're not materializing a subobject of the temporary, keep the
3573f785676fSDimitry Andric   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
3574f785676fSDimitry Andric   QualType MaterializedType = Init->getType();
3575f785676fSDimitry Andric   if (Init == E->GetTemporaryExpr())
3576f785676fSDimitry Andric     MaterializedType = E->getType();
3577f785676fSDimitry Andric 
35780623d748SDimitry Andric   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
35790623d748SDimitry Andric 
35800623d748SDimitry Andric   if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
35810623d748SDimitry Andric     return ConstantAddress(Slot, Align);
3582f785676fSDimitry Andric 
3583f785676fSDimitry Andric   // FIXME: If an externally-visible declaration extends multiple temporaries,
3584f785676fSDimitry Andric   // we need to give each temporary the same name in every translation unit (and
3585f785676fSDimitry Andric   // we also need to make the temporaries externally-visible).
3586f785676fSDimitry Andric   SmallString<256> Name;
3587f785676fSDimitry Andric   llvm::raw_svector_ostream Out(Name);
358859d1ed5bSDimitry Andric   getCXXABI().getMangleContext().mangleReferenceTemporary(
358959d1ed5bSDimitry Andric       VD, E->getManglingNumber(), Out);
3590f785676fSDimitry Andric 
359159d1ed5bSDimitry Andric   APValue *Value = nullptr;
3592f785676fSDimitry Andric   if (E->getStorageDuration() == SD_Static) {
3593f785676fSDimitry Andric     // We might have a cached constant initializer for this temporary. Note
3594f785676fSDimitry Andric     // that this might have a different value from the value computed by
3595f785676fSDimitry Andric     // evaluating the initializer if the surrounding constant expression
3596f785676fSDimitry Andric     // modifies the temporary.
3597f785676fSDimitry Andric     Value = getContext().getMaterializedTemporaryValue(E, false);
3598f785676fSDimitry Andric     if (Value && Value->isUninit())
359959d1ed5bSDimitry Andric       Value = nullptr;
3600f785676fSDimitry Andric   }
3601f785676fSDimitry Andric 
3602f785676fSDimitry Andric   // Try evaluating it now, it might have a constant initializer.
3603f785676fSDimitry Andric   Expr::EvalResult EvalResult;
3604f785676fSDimitry Andric   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3605f785676fSDimitry Andric       !EvalResult.hasSideEffects())
3606f785676fSDimitry Andric     Value = &EvalResult.Val;
3607f785676fSDimitry Andric 
360859d1ed5bSDimitry Andric   llvm::Constant *InitialValue = nullptr;
3609f785676fSDimitry Andric   bool Constant = false;
3610f785676fSDimitry Andric   llvm::Type *Type;
3611f785676fSDimitry Andric   if (Value) {
3612f785676fSDimitry Andric     // The temporary has a constant initializer, use it.
361359d1ed5bSDimitry Andric     InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
3614f785676fSDimitry Andric     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3615f785676fSDimitry Andric     Type = InitialValue->getType();
3616f785676fSDimitry Andric   } else {
3617f785676fSDimitry Andric     // No initializer, the initialization will be provided when we
3618f785676fSDimitry Andric     // initialize the declaration which performed lifetime extension.
3619f785676fSDimitry Andric     Type = getTypes().ConvertTypeForMem(MaterializedType);
3620f785676fSDimitry Andric   }
3621f785676fSDimitry Andric 
3622f785676fSDimitry Andric   // Create a global variable for this lifetime-extended temporary.
362359d1ed5bSDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
362459d1ed5bSDimitry Andric       getLLVMLinkageVarDefinition(VD, Constant);
362533956c43SDimitry Andric   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
362633956c43SDimitry Andric     const VarDecl *InitVD;
362733956c43SDimitry Andric     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
362833956c43SDimitry Andric         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
362933956c43SDimitry Andric       // Temporaries defined inside a class get linkonce_odr linkage because the
363033956c43SDimitry Andric       // class can be defined in multipe translation units.
363133956c43SDimitry Andric       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
363233956c43SDimitry Andric     } else {
363333956c43SDimitry Andric       // There is no need for this temporary to have external linkage if the
363433956c43SDimitry Andric       // VarDecl has external linkage.
363533956c43SDimitry Andric       Linkage = llvm::GlobalVariable::InternalLinkage;
363633956c43SDimitry Andric     }
363733956c43SDimitry Andric   }
363859d1ed5bSDimitry Andric   unsigned AddrSpace = GetGlobalVarAddressSpace(
363959d1ed5bSDimitry Andric       VD, getContext().getTargetAddressSpace(MaterializedType));
364059d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
364159d1ed5bSDimitry Andric       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
364259d1ed5bSDimitry Andric       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
364359d1ed5bSDimitry Andric       AddrSpace);
364459d1ed5bSDimitry Andric   setGlobalVisibility(GV, VD);
36450623d748SDimitry Andric   GV->setAlignment(Align.getQuantity());
364633956c43SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker())
364733956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3648f785676fSDimitry Andric   if (VD->getTLSKind())
3649f785676fSDimitry Andric     setTLSMode(GV, *VD);
36500623d748SDimitry Andric   MaterializedGlobalTemporaryMap[E] = GV;
36510623d748SDimitry Andric   return ConstantAddress(GV, Align);
3652f785676fSDimitry Andric }
3653f785676fSDimitry Andric 
3654f22ef01cSRoman Divacky /// EmitObjCPropertyImplementations - Emit information for synthesized
3655f22ef01cSRoman Divacky /// properties for an implementation.
3656f22ef01cSRoman Divacky void CodeGenModule::EmitObjCPropertyImplementations(const
3657f22ef01cSRoman Divacky                                                     ObjCImplementationDecl *D) {
365859d1ed5bSDimitry Andric   for (const auto *PID : D->property_impls()) {
3659f22ef01cSRoman Divacky     // Dynamic is just for type-checking.
3660f22ef01cSRoman Divacky     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3661f22ef01cSRoman Divacky       ObjCPropertyDecl *PD = PID->getPropertyDecl();
3662f22ef01cSRoman Divacky 
3663f22ef01cSRoman Divacky       // Determine which methods need to be implemented, some may have
36643861d79fSDimitry Andric       // been overridden. Note that ::isPropertyAccessor is not the method
3665f22ef01cSRoman Divacky       // we want, that just indicates if the decl came from a
3666f22ef01cSRoman Divacky       // property. What we want to know is if the method is defined in
3667f22ef01cSRoman Divacky       // this implementation.
3668f22ef01cSRoman Divacky       if (!D->getInstanceMethod(PD->getGetterName()))
3669f22ef01cSRoman Divacky         CodeGenFunction(*this).GenerateObjCGetter(
3670f22ef01cSRoman Divacky                                  const_cast<ObjCImplementationDecl *>(D), PID);
3671f22ef01cSRoman Divacky       if (!PD->isReadOnly() &&
3672f22ef01cSRoman Divacky           !D->getInstanceMethod(PD->getSetterName()))
3673f22ef01cSRoman Divacky         CodeGenFunction(*this).GenerateObjCSetter(
3674f22ef01cSRoman Divacky                                  const_cast<ObjCImplementationDecl *>(D), PID);
3675f22ef01cSRoman Divacky     }
3676f22ef01cSRoman Divacky   }
3677f22ef01cSRoman Divacky }
3678f22ef01cSRoman Divacky 
36793b0f4066SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) {
36806122f3e6SDimitry Andric   const ObjCInterfaceDecl *iface = impl->getClassInterface();
36816122f3e6SDimitry Andric   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
36823b0f4066SDimitry Andric        ivar; ivar = ivar->getNextIvar())
36833b0f4066SDimitry Andric     if (ivar->getType().isDestructedType())
36843b0f4066SDimitry Andric       return true;
36853b0f4066SDimitry Andric 
36863b0f4066SDimitry Andric   return false;
36873b0f4066SDimitry Andric }
36883b0f4066SDimitry Andric 
368939d628a0SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM,
369039d628a0SDimitry Andric                                    ObjCImplementationDecl *D) {
369139d628a0SDimitry Andric   CodeGenFunction CGF(CGM);
369239d628a0SDimitry Andric   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
369339d628a0SDimitry Andric        E = D->init_end(); B != E; ++B) {
369439d628a0SDimitry Andric     CXXCtorInitializer *CtorInitExp = *B;
369539d628a0SDimitry Andric     Expr *Init = CtorInitExp->getInit();
369639d628a0SDimitry Andric     if (!CGF.isTrivialInitializer(Init))
369739d628a0SDimitry Andric       return false;
369839d628a0SDimitry Andric   }
369939d628a0SDimitry Andric   return true;
370039d628a0SDimitry Andric }
370139d628a0SDimitry Andric 
3702f22ef01cSRoman Divacky /// EmitObjCIvarInitializations - Emit information for ivar initialization
3703f22ef01cSRoman Divacky /// for an implementation.
3704f22ef01cSRoman Divacky void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
37053b0f4066SDimitry Andric   // We might need a .cxx_destruct even if we don't have any ivar initializers.
37063b0f4066SDimitry Andric   if (needsDestructMethod(D)) {
3707f22ef01cSRoman Divacky     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3708f22ef01cSRoman Divacky     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
37093b0f4066SDimitry Andric     ObjCMethodDecl *DTORMethod =
37103b0f4066SDimitry Andric       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
371159d1ed5bSDimitry Andric                              cxxSelector, getContext().VoidTy, nullptr, D,
37126122f3e6SDimitry Andric                              /*isInstance=*/true, /*isVariadic=*/false,
37133861d79fSDimitry Andric                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
37146122f3e6SDimitry Andric                              /*isDefined=*/false, ObjCMethodDecl::Required);
3715f22ef01cSRoman Divacky     D->addInstanceMethod(DTORMethod);
3716f22ef01cSRoman Divacky     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
37173861d79fSDimitry Andric     D->setHasDestructors(true);
37183b0f4066SDimitry Andric   }
3719f22ef01cSRoman Divacky 
37203b0f4066SDimitry Andric   // If the implementation doesn't have any ivar initializers, we don't need
37213b0f4066SDimitry Andric   // a .cxx_construct.
372239d628a0SDimitry Andric   if (D->getNumIvarInitializers() == 0 ||
372339d628a0SDimitry Andric       AllTrivialInitializers(*this, D))
37243b0f4066SDimitry Andric     return;
37253b0f4066SDimitry Andric 
37263b0f4066SDimitry Andric   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
37273b0f4066SDimitry Andric   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3728f22ef01cSRoman Divacky   // The constructor returns 'self'.
3729f22ef01cSRoman Divacky   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3730f22ef01cSRoman Divacky                                                 D->getLocation(),
37316122f3e6SDimitry Andric                                                 D->getLocation(),
37326122f3e6SDimitry Andric                                                 cxxSelector,
373359d1ed5bSDimitry Andric                                                 getContext().getObjCIdType(),
373459d1ed5bSDimitry Andric                                                 nullptr, D, /*isInstance=*/true,
37356122f3e6SDimitry Andric                                                 /*isVariadic=*/false,
37363861d79fSDimitry Andric                                                 /*isPropertyAccessor=*/true,
37376122f3e6SDimitry Andric                                                 /*isImplicitlyDeclared=*/true,
37386122f3e6SDimitry Andric                                                 /*isDefined=*/false,
3739f22ef01cSRoman Divacky                                                 ObjCMethodDecl::Required);
3740f22ef01cSRoman Divacky   D->addInstanceMethod(CTORMethod);
3741f22ef01cSRoman Divacky   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
37423861d79fSDimitry Andric   D->setHasNonZeroConstructors(true);
3743f22ef01cSRoman Divacky }
3744f22ef01cSRoman Divacky 
3745f22ef01cSRoman Divacky // EmitLinkageSpec - Emit all declarations in a linkage spec.
3746f22ef01cSRoman Divacky void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
3747f22ef01cSRoman Divacky   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3748f22ef01cSRoman Divacky       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
3749f22ef01cSRoman Divacky     ErrorUnsupported(LSD, "linkage spec");
3750f22ef01cSRoman Divacky     return;
3751f22ef01cSRoman Divacky   }
3752f22ef01cSRoman Divacky 
375344290647SDimitry Andric   EmitDeclContext(LSD);
375444290647SDimitry Andric }
375544290647SDimitry Andric 
375644290647SDimitry Andric void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
375744290647SDimitry Andric   for (auto *I : DC->decls()) {
375844290647SDimitry Andric     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
375944290647SDimitry Andric     // are themselves considered "top-level", so EmitTopLevelDecl on an
376044290647SDimitry Andric     // ObjCImplDecl does not recursively visit them. We need to do that in
376144290647SDimitry Andric     // case they're nested inside another construct (LinkageSpecDecl /
376244290647SDimitry Andric     // ExportDecl) that does stop them from being considered "top-level".
376359d1ed5bSDimitry Andric     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
376459d1ed5bSDimitry Andric       for (auto *M : OID->methods())
376559d1ed5bSDimitry Andric         EmitTopLevelDecl(M);
37663861d79fSDimitry Andric     }
376744290647SDimitry Andric 
376859d1ed5bSDimitry Andric     EmitTopLevelDecl(I);
3769f22ef01cSRoman Divacky   }
37703861d79fSDimitry Andric }
3771f22ef01cSRoman Divacky 
3772f22ef01cSRoman Divacky /// EmitTopLevelDecl - Emit code for a single top level declaration.
3773f22ef01cSRoman Divacky void CodeGenModule::EmitTopLevelDecl(Decl *D) {
3774f22ef01cSRoman Divacky   // Ignore dependent declarations.
3775f22ef01cSRoman Divacky   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3776f22ef01cSRoman Divacky     return;
3777f22ef01cSRoman Divacky 
3778f22ef01cSRoman Divacky   switch (D->getKind()) {
3779f22ef01cSRoman Divacky   case Decl::CXXConversion:
3780f22ef01cSRoman Divacky   case Decl::CXXMethod:
3781f22ef01cSRoman Divacky   case Decl::Function:
3782f22ef01cSRoman Divacky     // Skip function templates
37833b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
37843b0f4066SDimitry Andric         cast<FunctionDecl>(D)->isLateTemplateParsed())
3785f22ef01cSRoman Divacky       return;
3786f22ef01cSRoman Divacky 
3787f22ef01cSRoman Divacky     EmitGlobal(cast<FunctionDecl>(D));
378839d628a0SDimitry Andric     // Always provide some coverage mapping
378939d628a0SDimitry Andric     // even for the functions that aren't emitted.
379039d628a0SDimitry Andric     AddDeferredUnusedCoverageMapping(D);
3791f22ef01cSRoman Divacky     break;
3792f22ef01cSRoman Divacky 
37936bc11b14SDimitry Andric   case Decl::CXXDeductionGuide:
37946bc11b14SDimitry Andric     // Function-like, but does not result in code emission.
37956bc11b14SDimitry Andric     break;
37966bc11b14SDimitry Andric 
3797f22ef01cSRoman Divacky   case Decl::Var:
379844290647SDimitry Andric   case Decl::Decomposition:
3799f785676fSDimitry Andric     // Skip variable templates
3800f785676fSDimitry Andric     if (cast<VarDecl>(D)->getDescribedVarTemplate())
3801f785676fSDimitry Andric       return;
3802f785676fSDimitry Andric   case Decl::VarTemplateSpecialization:
3803f22ef01cSRoman Divacky     EmitGlobal(cast<VarDecl>(D));
380444290647SDimitry Andric     if (auto *DD = dyn_cast<DecompositionDecl>(D))
380544290647SDimitry Andric       for (auto *B : DD->bindings())
380644290647SDimitry Andric         if (auto *HD = B->getHoldingVar())
380744290647SDimitry Andric           EmitGlobal(HD);
3808f22ef01cSRoman Divacky     break;
3809f22ef01cSRoman Divacky 
38103b0f4066SDimitry Andric   // Indirect fields from global anonymous structs and unions can be
38113b0f4066SDimitry Andric   // ignored; only the actual variable requires IR gen support.
38123b0f4066SDimitry Andric   case Decl::IndirectField:
38133b0f4066SDimitry Andric     break;
38143b0f4066SDimitry Andric 
3815f22ef01cSRoman Divacky   // C++ Decls
3816f22ef01cSRoman Divacky   case Decl::Namespace:
381744290647SDimitry Andric     EmitDeclContext(cast<NamespaceDecl>(D));
3818f22ef01cSRoman Divacky     break;
3819e7145dcbSDimitry Andric   case Decl::CXXRecord:
382020e90f04SDimitry Andric     if (DebugInfo) {
382120e90f04SDimitry Andric       if (auto *ES = D->getASTContext().getExternalSource())
382220e90f04SDimitry Andric         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
382320e90f04SDimitry Andric           DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
382420e90f04SDimitry Andric     }
3825e7145dcbSDimitry Andric     // Emit any static data members, they may be definitions.
3826e7145dcbSDimitry Andric     for (auto *I : cast<CXXRecordDecl>(D)->decls())
3827e7145dcbSDimitry Andric       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
3828e7145dcbSDimitry Andric         EmitTopLevelDecl(I);
3829e7145dcbSDimitry Andric     break;
3830f22ef01cSRoman Divacky     // No code generation needed.
3831f22ef01cSRoman Divacky   case Decl::UsingShadow:
3832f22ef01cSRoman Divacky   case Decl::ClassTemplate:
3833f785676fSDimitry Andric   case Decl::VarTemplate:
3834f785676fSDimitry Andric   case Decl::VarTemplatePartialSpecialization:
3835f22ef01cSRoman Divacky   case Decl::FunctionTemplate:
3836bd5abe19SDimitry Andric   case Decl::TypeAliasTemplate:
3837bd5abe19SDimitry Andric   case Decl::Block:
3838139f7f9bSDimitry Andric   case Decl::Empty:
3839f22ef01cSRoman Divacky     break;
384059d1ed5bSDimitry Andric   case Decl::Using:          // using X; [C++]
384159d1ed5bSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
384259d1ed5bSDimitry Andric         DI->EmitUsingDecl(cast<UsingDecl>(*D));
384359d1ed5bSDimitry Andric     return;
3844f785676fSDimitry Andric   case Decl::NamespaceAlias:
3845f785676fSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
3846f785676fSDimitry Andric         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3847f785676fSDimitry Andric     return;
3848284c1978SDimitry Andric   case Decl::UsingDirective: // using namespace X; [C++]
3849284c1978SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
3850284c1978SDimitry Andric       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3851284c1978SDimitry Andric     return;
3852f22ef01cSRoman Divacky   case Decl::CXXConstructor:
3853f22ef01cSRoman Divacky     // Skip function templates
38543b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
38553b0f4066SDimitry Andric         cast<FunctionDecl>(D)->isLateTemplateParsed())
3856f22ef01cSRoman Divacky       return;
3857f22ef01cSRoman Divacky 
3858f785676fSDimitry Andric     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
3859f22ef01cSRoman Divacky     break;
3860f22ef01cSRoman Divacky   case Decl::CXXDestructor:
38613b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
38623b0f4066SDimitry Andric       return;
3863f785676fSDimitry Andric     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
3864f22ef01cSRoman Divacky     break;
3865f22ef01cSRoman Divacky 
3866f22ef01cSRoman Divacky   case Decl::StaticAssert:
3867f22ef01cSRoman Divacky     // Nothing to do.
3868f22ef01cSRoman Divacky     break;
3869f22ef01cSRoman Divacky 
3870f22ef01cSRoman Divacky   // Objective-C Decls
3871f22ef01cSRoman Divacky 
3872f22ef01cSRoman Divacky   // Forward declarations, no (immediate) code generation.
3873f22ef01cSRoman Divacky   case Decl::ObjCInterface:
38747ae0e2c9SDimitry Andric   case Decl::ObjCCategory:
3875f22ef01cSRoman Divacky     break;
3876f22ef01cSRoman Divacky 
3877dff0c46cSDimitry Andric   case Decl::ObjCProtocol: {
387859d1ed5bSDimitry Andric     auto *Proto = cast<ObjCProtocolDecl>(D);
3879dff0c46cSDimitry Andric     if (Proto->isThisDeclarationADefinition())
3880dff0c46cSDimitry Andric       ObjCRuntime->GenerateProtocol(Proto);
3881f22ef01cSRoman Divacky     break;
3882dff0c46cSDimitry Andric   }
3883f22ef01cSRoman Divacky 
3884f22ef01cSRoman Divacky   case Decl::ObjCCategoryImpl:
3885f22ef01cSRoman Divacky     // Categories have properties but don't support synthesize so we
3886f22ef01cSRoman Divacky     // can ignore them here.
38876122f3e6SDimitry Andric     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
3888f22ef01cSRoman Divacky     break;
3889f22ef01cSRoman Divacky 
3890f22ef01cSRoman Divacky   case Decl::ObjCImplementation: {
389159d1ed5bSDimitry Andric     auto *OMD = cast<ObjCImplementationDecl>(D);
3892f22ef01cSRoman Divacky     EmitObjCPropertyImplementations(OMD);
3893f22ef01cSRoman Divacky     EmitObjCIvarInitializations(OMD);
38946122f3e6SDimitry Andric     ObjCRuntime->GenerateClass(OMD);
3895dff0c46cSDimitry Andric     // Emit global variable debug information.
3896dff0c46cSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
3897e7145dcbSDimitry Andric       if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
3898139f7f9bSDimitry Andric         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3899139f7f9bSDimitry Andric             OMD->getClassInterface()), OMD->getLocation());
3900f22ef01cSRoman Divacky     break;
3901f22ef01cSRoman Divacky   }
3902f22ef01cSRoman Divacky   case Decl::ObjCMethod: {
390359d1ed5bSDimitry Andric     auto *OMD = cast<ObjCMethodDecl>(D);
3904f22ef01cSRoman Divacky     // If this is not a prototype, emit the body.
3905f22ef01cSRoman Divacky     if (OMD->getBody())
3906f22ef01cSRoman Divacky       CodeGenFunction(*this).GenerateObjCMethod(OMD);
3907f22ef01cSRoman Divacky     break;
3908f22ef01cSRoman Divacky   }
3909f22ef01cSRoman Divacky   case Decl::ObjCCompatibleAlias:
3910dff0c46cSDimitry Andric     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3911f22ef01cSRoman Divacky     break;
3912f22ef01cSRoman Divacky 
3913e7145dcbSDimitry Andric   case Decl::PragmaComment: {
3914e7145dcbSDimitry Andric     const auto *PCD = cast<PragmaCommentDecl>(D);
3915e7145dcbSDimitry Andric     switch (PCD->getCommentKind()) {
3916e7145dcbSDimitry Andric     case PCK_Unknown:
3917e7145dcbSDimitry Andric       llvm_unreachable("unexpected pragma comment kind");
3918e7145dcbSDimitry Andric     case PCK_Linker:
3919e7145dcbSDimitry Andric       AppendLinkerOptions(PCD->getArg());
3920e7145dcbSDimitry Andric       break;
3921e7145dcbSDimitry Andric     case PCK_Lib:
3922e7145dcbSDimitry Andric       AddDependentLib(PCD->getArg());
3923e7145dcbSDimitry Andric       break;
3924e7145dcbSDimitry Andric     case PCK_Compiler:
3925e7145dcbSDimitry Andric     case PCK_ExeStr:
3926e7145dcbSDimitry Andric     case PCK_User:
3927e7145dcbSDimitry Andric       break; // We ignore all of these.
3928e7145dcbSDimitry Andric     }
3929e7145dcbSDimitry Andric     break;
3930e7145dcbSDimitry Andric   }
3931e7145dcbSDimitry Andric 
3932e7145dcbSDimitry Andric   case Decl::PragmaDetectMismatch: {
3933e7145dcbSDimitry Andric     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
3934e7145dcbSDimitry Andric     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
3935e7145dcbSDimitry Andric     break;
3936e7145dcbSDimitry Andric   }
3937e7145dcbSDimitry Andric 
3938f22ef01cSRoman Divacky   case Decl::LinkageSpec:
3939f22ef01cSRoman Divacky     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
3940f22ef01cSRoman Divacky     break;
3941f22ef01cSRoman Divacky 
3942f22ef01cSRoman Divacky   case Decl::FileScopeAsm: {
394333956c43SDimitry Andric     // File-scope asm is ignored during device-side CUDA compilation.
394433956c43SDimitry Andric     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
394533956c43SDimitry Andric       break;
3946ea942507SDimitry Andric     // File-scope asm is ignored during device-side OpenMP compilation.
3947ea942507SDimitry Andric     if (LangOpts.OpenMPIsDevice)
3948ea942507SDimitry Andric       break;
394959d1ed5bSDimitry Andric     auto *AD = cast<FileScopeAsmDecl>(D);
395033956c43SDimitry Andric     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
3951f22ef01cSRoman Divacky     break;
3952f22ef01cSRoman Divacky   }
3953f22ef01cSRoman Divacky 
3954139f7f9bSDimitry Andric   case Decl::Import: {
395559d1ed5bSDimitry Andric     auto *Import = cast<ImportDecl>(D);
3956139f7f9bSDimitry Andric 
395744290647SDimitry Andric     // If we've already imported this module, we're done.
395844290647SDimitry Andric     if (!ImportedModules.insert(Import->getImportedModule()))
3959139f7f9bSDimitry Andric       break;
396044290647SDimitry Andric 
396144290647SDimitry Andric     // Emit debug information for direct imports.
396244290647SDimitry Andric     if (!Import->getImportedOwningModule()) {
39633dac3a9bSDimitry Andric       if (CGDebugInfo *DI = getModuleDebugInfo())
39643dac3a9bSDimitry Andric         DI->EmitImportDecl(*Import);
396544290647SDimitry Andric     }
3966139f7f9bSDimitry Andric 
396744290647SDimitry Andric     // Find all of the submodules and emit the module initializers.
396844290647SDimitry Andric     llvm::SmallPtrSet<clang::Module *, 16> Visited;
396944290647SDimitry Andric     SmallVector<clang::Module *, 16> Stack;
397044290647SDimitry Andric     Visited.insert(Import->getImportedModule());
397144290647SDimitry Andric     Stack.push_back(Import->getImportedModule());
397244290647SDimitry Andric 
397344290647SDimitry Andric     while (!Stack.empty()) {
397444290647SDimitry Andric       clang::Module *Mod = Stack.pop_back_val();
397544290647SDimitry Andric       if (!EmittedModuleInitializers.insert(Mod).second)
397644290647SDimitry Andric         continue;
397744290647SDimitry Andric 
397844290647SDimitry Andric       for (auto *D : Context.getModuleInitializers(Mod))
397944290647SDimitry Andric         EmitTopLevelDecl(D);
398044290647SDimitry Andric 
398144290647SDimitry Andric       // Visit the submodules of this module.
398244290647SDimitry Andric       for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
398344290647SDimitry Andric                                              SubEnd = Mod->submodule_end();
398444290647SDimitry Andric            Sub != SubEnd; ++Sub) {
398544290647SDimitry Andric         // Skip explicit children; they need to be explicitly imported to emit
398644290647SDimitry Andric         // the initializers.
398744290647SDimitry Andric         if ((*Sub)->IsExplicit)
398844290647SDimitry Andric           continue;
398944290647SDimitry Andric 
399044290647SDimitry Andric         if (Visited.insert(*Sub).second)
399144290647SDimitry Andric           Stack.push_back(*Sub);
399244290647SDimitry Andric       }
399344290647SDimitry Andric     }
3994139f7f9bSDimitry Andric     break;
3995139f7f9bSDimitry Andric   }
3996139f7f9bSDimitry Andric 
399744290647SDimitry Andric   case Decl::Export:
399844290647SDimitry Andric     EmitDeclContext(cast<ExportDecl>(D));
399944290647SDimitry Andric     break;
400044290647SDimitry Andric 
400139d628a0SDimitry Andric   case Decl::OMPThreadPrivate:
400239d628a0SDimitry Andric     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
400339d628a0SDimitry Andric     break;
400439d628a0SDimitry Andric 
400559d1ed5bSDimitry Andric   case Decl::ClassTemplateSpecialization: {
400659d1ed5bSDimitry Andric     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
400759d1ed5bSDimitry Andric     if (DebugInfo &&
400839d628a0SDimitry Andric         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
400939d628a0SDimitry Andric         Spec->hasDefinition())
401059d1ed5bSDimitry Andric       DebugInfo->completeTemplateDefinition(*Spec);
401139d628a0SDimitry Andric     break;
401259d1ed5bSDimitry Andric   }
401359d1ed5bSDimitry Andric 
4014e7145dcbSDimitry Andric   case Decl::OMPDeclareReduction:
4015e7145dcbSDimitry Andric     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
4016e7145dcbSDimitry Andric     break;
4017e7145dcbSDimitry Andric 
4018f22ef01cSRoman Divacky   default:
4019f22ef01cSRoman Divacky     // Make sure we handled everything we should, every other kind is a
4020f22ef01cSRoman Divacky     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
4021f22ef01cSRoman Divacky     // function. Need to recode Decl::Kind to do that easily.
4022f22ef01cSRoman Divacky     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
402339d628a0SDimitry Andric     break;
402439d628a0SDimitry Andric   }
402539d628a0SDimitry Andric }
402639d628a0SDimitry Andric 
402739d628a0SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
402839d628a0SDimitry Andric   // Do we need to generate coverage mapping?
402939d628a0SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
403039d628a0SDimitry Andric     return;
403139d628a0SDimitry Andric   switch (D->getKind()) {
403239d628a0SDimitry Andric   case Decl::CXXConversion:
403339d628a0SDimitry Andric   case Decl::CXXMethod:
403439d628a0SDimitry Andric   case Decl::Function:
403539d628a0SDimitry Andric   case Decl::ObjCMethod:
403639d628a0SDimitry Andric   case Decl::CXXConstructor:
403739d628a0SDimitry Andric   case Decl::CXXDestructor: {
40380623d748SDimitry Andric     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
403939d628a0SDimitry Andric       return;
404039d628a0SDimitry Andric     auto I = DeferredEmptyCoverageMappingDecls.find(D);
404139d628a0SDimitry Andric     if (I == DeferredEmptyCoverageMappingDecls.end())
404239d628a0SDimitry Andric       DeferredEmptyCoverageMappingDecls[D] = true;
404339d628a0SDimitry Andric     break;
404439d628a0SDimitry Andric   }
404539d628a0SDimitry Andric   default:
404639d628a0SDimitry Andric     break;
404739d628a0SDimitry Andric   };
404839d628a0SDimitry Andric }
404939d628a0SDimitry Andric 
405039d628a0SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
405139d628a0SDimitry Andric   // Do we need to generate coverage mapping?
405239d628a0SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
405339d628a0SDimitry Andric     return;
405439d628a0SDimitry Andric   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
405539d628a0SDimitry Andric     if (Fn->isTemplateInstantiation())
405639d628a0SDimitry Andric       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
405739d628a0SDimitry Andric   }
405839d628a0SDimitry Andric   auto I = DeferredEmptyCoverageMappingDecls.find(D);
405939d628a0SDimitry Andric   if (I == DeferredEmptyCoverageMappingDecls.end())
406039d628a0SDimitry Andric     DeferredEmptyCoverageMappingDecls[D] = false;
406139d628a0SDimitry Andric   else
406239d628a0SDimitry Andric     I->second = false;
406339d628a0SDimitry Andric }
406439d628a0SDimitry Andric 
406539d628a0SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
406639d628a0SDimitry Andric   std::vector<const Decl *> DeferredDecls;
406733956c43SDimitry Andric   for (const auto &I : DeferredEmptyCoverageMappingDecls) {
406839d628a0SDimitry Andric     if (!I.second)
406939d628a0SDimitry Andric       continue;
407039d628a0SDimitry Andric     DeferredDecls.push_back(I.first);
407139d628a0SDimitry Andric   }
407239d628a0SDimitry Andric   // Sort the declarations by their location to make sure that the tests get a
407339d628a0SDimitry Andric   // predictable order for the coverage mapping for the unused declarations.
407439d628a0SDimitry Andric   if (CodeGenOpts.DumpCoverageMapping)
407539d628a0SDimitry Andric     std::sort(DeferredDecls.begin(), DeferredDecls.end(),
407639d628a0SDimitry Andric               [] (const Decl *LHS, const Decl *RHS) {
407739d628a0SDimitry Andric       return LHS->getLocStart() < RHS->getLocStart();
407839d628a0SDimitry Andric     });
407939d628a0SDimitry Andric   for (const auto *D : DeferredDecls) {
408039d628a0SDimitry Andric     switch (D->getKind()) {
408139d628a0SDimitry Andric     case Decl::CXXConversion:
408239d628a0SDimitry Andric     case Decl::CXXMethod:
408339d628a0SDimitry Andric     case Decl::Function:
408439d628a0SDimitry Andric     case Decl::ObjCMethod: {
408539d628a0SDimitry Andric       CodeGenPGO PGO(*this);
408639d628a0SDimitry Andric       GlobalDecl GD(cast<FunctionDecl>(D));
408739d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
408839d628a0SDimitry Andric                                   getFunctionLinkage(GD));
408939d628a0SDimitry Andric       break;
409039d628a0SDimitry Andric     }
409139d628a0SDimitry Andric     case Decl::CXXConstructor: {
409239d628a0SDimitry Andric       CodeGenPGO PGO(*this);
409339d628a0SDimitry Andric       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
409439d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
409539d628a0SDimitry Andric                                   getFunctionLinkage(GD));
409639d628a0SDimitry Andric       break;
409739d628a0SDimitry Andric     }
409839d628a0SDimitry Andric     case Decl::CXXDestructor: {
409939d628a0SDimitry Andric       CodeGenPGO PGO(*this);
410039d628a0SDimitry Andric       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
410139d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
410239d628a0SDimitry Andric                                   getFunctionLinkage(GD));
410339d628a0SDimitry Andric       break;
410439d628a0SDimitry Andric     }
410539d628a0SDimitry Andric     default:
410639d628a0SDimitry Andric       break;
410739d628a0SDimitry Andric     };
4108f22ef01cSRoman Divacky   }
4109f22ef01cSRoman Divacky }
4110ffd1746dSEd Schouten 
4111ffd1746dSEd Schouten /// Turns the given pointer into a constant.
4112ffd1746dSEd Schouten static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
4113ffd1746dSEd Schouten                                           const void *Ptr) {
4114ffd1746dSEd Schouten   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
41156122f3e6SDimitry Andric   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
4116ffd1746dSEd Schouten   return llvm::ConstantInt::get(i64, PtrInt);
4117ffd1746dSEd Schouten }
4118ffd1746dSEd Schouten 
4119ffd1746dSEd Schouten static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
4120ffd1746dSEd Schouten                                    llvm::NamedMDNode *&GlobalMetadata,
4121ffd1746dSEd Schouten                                    GlobalDecl D,
4122ffd1746dSEd Schouten                                    llvm::GlobalValue *Addr) {
4123ffd1746dSEd Schouten   if (!GlobalMetadata)
4124ffd1746dSEd Schouten     GlobalMetadata =
4125ffd1746dSEd Schouten       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
4126ffd1746dSEd Schouten 
4127ffd1746dSEd Schouten   // TODO: should we report variant information for ctors/dtors?
412839d628a0SDimitry Andric   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
412939d628a0SDimitry Andric                            llvm::ConstantAsMetadata::get(GetPointerConstant(
413039d628a0SDimitry Andric                                CGM.getLLVMContext(), D.getDecl()))};
41313b0f4066SDimitry Andric   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
4132ffd1746dSEd Schouten }
4133ffd1746dSEd Schouten 
4134284c1978SDimitry Andric /// For each function which is declared within an extern "C" region and marked
4135284c1978SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled
4136284c1978SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer
4137284c1978SDimitry Andric /// to such functions with an unmangled name from inline assembly within the
4138284c1978SDimitry Andric /// same translation unit.
4139284c1978SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() {
4140e7145dcbSDimitry Andric   // Don't do anything if we're generating CUDA device code -- the NVPTX
4141e7145dcbSDimitry Andric   // assembly target doesn't support aliases.
4142e7145dcbSDimitry Andric   if (Context.getTargetInfo().getTriple().isNVPTX())
4143e7145dcbSDimitry Andric     return;
41448f0fd8f6SDimitry Andric   for (auto &I : StaticExternCValues) {
41458f0fd8f6SDimitry Andric     IdentifierInfo *Name = I.first;
41468f0fd8f6SDimitry Andric     llvm::GlobalValue *Val = I.second;
4147284c1978SDimitry Andric     if (Val && !getModule().getNamedValue(Name->getName()))
414859d1ed5bSDimitry Andric       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
4149284c1978SDimitry Andric   }
4150284c1978SDimitry Andric }
4151284c1978SDimitry Andric 
415259d1ed5bSDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
415359d1ed5bSDimitry Andric                                              GlobalDecl &Result) const {
415459d1ed5bSDimitry Andric   auto Res = Manglings.find(MangledName);
415559d1ed5bSDimitry Andric   if (Res == Manglings.end())
415659d1ed5bSDimitry Andric     return false;
415759d1ed5bSDimitry Andric   Result = Res->getValue();
415859d1ed5bSDimitry Andric   return true;
415959d1ed5bSDimitry Andric }
416059d1ed5bSDimitry Andric 
4161ffd1746dSEd Schouten /// Emits metadata nodes associating all the global values in the
4162ffd1746dSEd Schouten /// current module with the Decls they came from.  This is useful for
4163ffd1746dSEd Schouten /// projects using IR gen as a subroutine.
4164ffd1746dSEd Schouten ///
4165ffd1746dSEd Schouten /// Since there's currently no way to associate an MDNode directly
4166ffd1746dSEd Schouten /// with an llvm::GlobalValue, we create a global named metadata
4167ffd1746dSEd Schouten /// with the name 'clang.global.decl.ptrs'.
4168ffd1746dSEd Schouten void CodeGenModule::EmitDeclMetadata() {
416959d1ed5bSDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
4170ffd1746dSEd Schouten 
417159d1ed5bSDimitry Andric   for (auto &I : MangledDeclNames) {
417259d1ed5bSDimitry Andric     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
41730623d748SDimitry Andric     // Some mangled names don't necessarily have an associated GlobalValue
41740623d748SDimitry Andric     // in this module, e.g. if we mangled it for DebugInfo.
41750623d748SDimitry Andric     if (Addr)
417659d1ed5bSDimitry Andric       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
4177ffd1746dSEd Schouten   }
4178ffd1746dSEd Schouten }
4179ffd1746dSEd Schouten 
4180ffd1746dSEd Schouten /// Emits metadata nodes for all the local variables in the current
4181ffd1746dSEd Schouten /// function.
4182ffd1746dSEd Schouten void CodeGenFunction::EmitDeclMetadata() {
4183ffd1746dSEd Schouten   if (LocalDeclMap.empty()) return;
4184ffd1746dSEd Schouten 
4185ffd1746dSEd Schouten   llvm::LLVMContext &Context = getLLVMContext();
4186ffd1746dSEd Schouten 
4187ffd1746dSEd Schouten   // Find the unique metadata ID for this name.
4188ffd1746dSEd Schouten   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
4189ffd1746dSEd Schouten 
419059d1ed5bSDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
4191ffd1746dSEd Schouten 
419259d1ed5bSDimitry Andric   for (auto &I : LocalDeclMap) {
419359d1ed5bSDimitry Andric     const Decl *D = I.first;
41940623d748SDimitry Andric     llvm::Value *Addr = I.second.getPointer();
419559d1ed5bSDimitry Andric     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
4196ffd1746dSEd Schouten       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
419739d628a0SDimitry Andric       Alloca->setMetadata(
419839d628a0SDimitry Andric           DeclPtrKind, llvm::MDNode::get(
419939d628a0SDimitry Andric                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
420059d1ed5bSDimitry Andric     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
4201ffd1746dSEd Schouten       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
4202ffd1746dSEd Schouten       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
4203ffd1746dSEd Schouten     }
4204ffd1746dSEd Schouten   }
4205ffd1746dSEd Schouten }
4206e580952dSDimitry Andric 
4207f785676fSDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() {
4208f785676fSDimitry Andric   llvm::NamedMDNode *IdentMetadata =
4209f785676fSDimitry Andric     TheModule.getOrInsertNamedMetadata("llvm.ident");
4210f785676fSDimitry Andric   std::string Version = getClangFullVersion();
4211f785676fSDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
4212f785676fSDimitry Andric 
421339d628a0SDimitry Andric   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
4214f785676fSDimitry Andric   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4215f785676fSDimitry Andric }
4216f785676fSDimitry Andric 
421759d1ed5bSDimitry Andric void CodeGenModule::EmitTargetMetadata() {
421839d628a0SDimitry Andric   // Warning, new MangledDeclNames may be appended within this loop.
421939d628a0SDimitry Andric   // We rely on MapVector insertions adding new elements to the end
422039d628a0SDimitry Andric   // of the container.
422139d628a0SDimitry Andric   // FIXME: Move this loop into the one target that needs it, and only
422239d628a0SDimitry Andric   // loop over those declarations for which we couldn't emit the target
422339d628a0SDimitry Andric   // metadata when we emitted the declaration.
422439d628a0SDimitry Andric   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
422539d628a0SDimitry Andric     auto Val = *(MangledDeclNames.begin() + I);
422639d628a0SDimitry Andric     const Decl *D = Val.first.getDecl()->getMostRecentDecl();
422739d628a0SDimitry Andric     llvm::GlobalValue *GV = GetGlobalValue(Val.second);
422859d1ed5bSDimitry Andric     getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
422959d1ed5bSDimitry Andric   }
423059d1ed5bSDimitry Andric }
423159d1ed5bSDimitry Andric 
4232bd5abe19SDimitry Andric void CodeGenModule::EmitCoverageFile() {
423344290647SDimitry Andric   if (getCodeGenOpts().CoverageDataFile.empty() &&
423444290647SDimitry Andric       getCodeGenOpts().CoverageNotesFile.empty())
423544290647SDimitry Andric     return;
423644290647SDimitry Andric 
423744290647SDimitry Andric   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
423844290647SDimitry Andric   if (!CUNode)
423944290647SDimitry Andric     return;
424044290647SDimitry Andric 
4241bd5abe19SDimitry Andric   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
4242bd5abe19SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
424344290647SDimitry Andric   auto *CoverageDataFile =
424444290647SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
424544290647SDimitry Andric   auto *CoverageNotesFile =
424644290647SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
4247bd5abe19SDimitry Andric   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
4248bd5abe19SDimitry Andric     llvm::MDNode *CU = CUNode->getOperand(i);
424944290647SDimitry Andric     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
425039d628a0SDimitry Andric     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
4251bd5abe19SDimitry Andric   }
4252bd5abe19SDimitry Andric }
42533861d79fSDimitry Andric 
425439d628a0SDimitry Andric llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
42553861d79fSDimitry Andric   // Sema has checked that all uuid strings are of the form
42563861d79fSDimitry Andric   // "12345678-1234-1234-1234-1234567890ab".
42573861d79fSDimitry Andric   assert(Uuid.size() == 36);
4258f785676fSDimitry Andric   for (unsigned i = 0; i < 36; ++i) {
4259f785676fSDimitry Andric     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
4260f785676fSDimitry Andric     else                                         assert(isHexDigit(Uuid[i]));
42613861d79fSDimitry Andric   }
42623861d79fSDimitry Andric 
426339d628a0SDimitry Andric   // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
4264f785676fSDimitry Andric   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
42653861d79fSDimitry Andric 
4266f785676fSDimitry Andric   llvm::Constant *Field3[8];
4267f785676fSDimitry Andric   for (unsigned Idx = 0; Idx < 8; ++Idx)
4268f785676fSDimitry Andric     Field3[Idx] = llvm::ConstantInt::get(
4269f785676fSDimitry Andric         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
42703861d79fSDimitry Andric 
4271f785676fSDimitry Andric   llvm::Constant *Fields[4] = {
4272f785676fSDimitry Andric     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
4273f785676fSDimitry Andric     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
4274f785676fSDimitry Andric     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
4275f785676fSDimitry Andric     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
4276f785676fSDimitry Andric   };
4277f785676fSDimitry Andric 
4278f785676fSDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
42793861d79fSDimitry Andric }
428059d1ed5bSDimitry Andric 
428159d1ed5bSDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
428259d1ed5bSDimitry Andric                                                        bool ForEH) {
428359d1ed5bSDimitry Andric   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
428459d1ed5bSDimitry Andric   // FIXME: should we even be calling this method if RTTI is disabled
428559d1ed5bSDimitry Andric   // and it's not for EH?
428659d1ed5bSDimitry Andric   if (!ForEH && !getLangOpts().RTTI)
428759d1ed5bSDimitry Andric     return llvm::Constant::getNullValue(Int8PtrTy);
428859d1ed5bSDimitry Andric 
428959d1ed5bSDimitry Andric   if (ForEH && Ty->isObjCObjectPointerType() &&
429059d1ed5bSDimitry Andric       LangOpts.ObjCRuntime.isGNUFamily())
429159d1ed5bSDimitry Andric     return ObjCRuntime->GetEHType(Ty);
429259d1ed5bSDimitry Andric 
429359d1ed5bSDimitry Andric   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
429459d1ed5bSDimitry Andric }
429559d1ed5bSDimitry Andric 
429639d628a0SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
429739d628a0SDimitry Andric   for (auto RefExpr : D->varlists()) {
429839d628a0SDimitry Andric     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
429939d628a0SDimitry Andric     bool PerformInit =
430039d628a0SDimitry Andric         VD->getAnyInitializer() &&
430139d628a0SDimitry Andric         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
430239d628a0SDimitry Andric                                                         /*ForRef=*/false);
43030623d748SDimitry Andric 
43040623d748SDimitry Andric     Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
430533956c43SDimitry Andric     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
43060623d748SDimitry Andric             VD, Addr, RefExpr->getLocStart(), PerformInit))
430739d628a0SDimitry Andric       CXXGlobalInits.push_back(InitFunction);
430839d628a0SDimitry Andric   }
430939d628a0SDimitry Andric }
43108f0fd8f6SDimitry Andric 
43110623d748SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
43120623d748SDimitry Andric   llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
43130623d748SDimitry Andric   if (InternalId)
43140623d748SDimitry Andric     return InternalId;
43150623d748SDimitry Andric 
43160623d748SDimitry Andric   if (isExternallyVisible(T->getLinkage())) {
43178f0fd8f6SDimitry Andric     std::string OutName;
43188f0fd8f6SDimitry Andric     llvm::raw_string_ostream Out(OutName);
43190623d748SDimitry Andric     getCXXABI().getMangleContext().mangleTypeName(T, Out);
43208f0fd8f6SDimitry Andric 
43210623d748SDimitry Andric     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
43220623d748SDimitry Andric   } else {
43230623d748SDimitry Andric     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
43240623d748SDimitry Andric                                            llvm::ArrayRef<llvm::Metadata *>());
43250623d748SDimitry Andric   }
43260623d748SDimitry Andric 
43270623d748SDimitry Andric   return InternalId;
43280623d748SDimitry Andric }
43290623d748SDimitry Andric 
4330e7145dcbSDimitry Andric /// Returns whether this module needs the "all-vtables" type identifier.
4331e7145dcbSDimitry Andric bool CodeGenModule::NeedAllVtablesTypeId() const {
4332e7145dcbSDimitry Andric   // Returns true if at least one of vtable-based CFI checkers is enabled and
4333e7145dcbSDimitry Andric   // is not in the trapping mode.
4334e7145dcbSDimitry Andric   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
4335e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
4336e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
4337e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
4338e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
4339e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
4340e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
4341e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
4342e7145dcbSDimitry Andric }
4343e7145dcbSDimitry Andric 
4344e7145dcbSDimitry Andric void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
43450623d748SDimitry Andric                                           CharUnits Offset,
43460623d748SDimitry Andric                                           const CXXRecordDecl *RD) {
43470623d748SDimitry Andric   llvm::Metadata *MD =
43480623d748SDimitry Andric       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
4349e7145dcbSDimitry Andric   VTable->addTypeMetadata(Offset.getQuantity(), MD);
43500623d748SDimitry Andric 
4351e7145dcbSDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
4352e7145dcbSDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
4353e7145dcbSDimitry Andric       VTable->addTypeMetadata(Offset.getQuantity(),
4354e7145dcbSDimitry Andric                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
4355e7145dcbSDimitry Andric 
4356e7145dcbSDimitry Andric   if (NeedAllVtablesTypeId()) {
4357e7145dcbSDimitry Andric     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
4358e7145dcbSDimitry Andric     VTable->addTypeMetadata(Offset.getQuantity(), MD);
43590623d748SDimitry Andric   }
43600623d748SDimitry Andric }
43610623d748SDimitry Andric 
43620623d748SDimitry Andric // Fills in the supplied string map with the set of target features for the
43630623d748SDimitry Andric // passed in function.
43640623d748SDimitry Andric void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
43650623d748SDimitry Andric                                           const FunctionDecl *FD) {
43660623d748SDimitry Andric   StringRef TargetCPU = Target.getTargetOpts().CPU;
43670623d748SDimitry Andric   if (const auto *TD = FD->getAttr<TargetAttr>()) {
43680623d748SDimitry Andric     // If we have a TargetAttr build up the feature map based on that.
43690623d748SDimitry Andric     TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
43700623d748SDimitry Andric 
43710623d748SDimitry Andric     // Make a copy of the features as passed on the command line into the
43720623d748SDimitry Andric     // beginning of the additional features from the function to override.
43730623d748SDimitry Andric     ParsedAttr.first.insert(ParsedAttr.first.begin(),
43740623d748SDimitry Andric                             Target.getTargetOpts().FeaturesAsWritten.begin(),
43750623d748SDimitry Andric                             Target.getTargetOpts().FeaturesAsWritten.end());
43760623d748SDimitry Andric 
43770623d748SDimitry Andric     if (ParsedAttr.second != "")
43780623d748SDimitry Andric       TargetCPU = ParsedAttr.second;
43790623d748SDimitry Andric 
43800623d748SDimitry Andric     // Now populate the feature map, first with the TargetCPU which is either
43810623d748SDimitry Andric     // the default or a new one from the target attribute string. Then we'll use
43820623d748SDimitry Andric     // the passed in features (FeaturesAsWritten) along with the new ones from
43830623d748SDimitry Andric     // the attribute.
43840623d748SDimitry Andric     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first);
43850623d748SDimitry Andric   } else {
43860623d748SDimitry Andric     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
43870623d748SDimitry Andric                           Target.getTargetOpts().Features);
43880623d748SDimitry Andric   }
43898f0fd8f6SDimitry Andric }
4390e7145dcbSDimitry Andric 
4391e7145dcbSDimitry Andric llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
4392e7145dcbSDimitry Andric   if (!SanStats)
4393e7145dcbSDimitry Andric     SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
4394e7145dcbSDimitry Andric 
4395e7145dcbSDimitry Andric   return *SanStats;
4396e7145dcbSDimitry Andric }
439744290647SDimitry Andric llvm::Value *
439844290647SDimitry Andric CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
439944290647SDimitry Andric                                                   CodeGenFunction &CGF) {
440044290647SDimitry Andric   llvm::Constant *C = EmitConstantExpr(E, E->getType(), &CGF);
440144290647SDimitry Andric   auto SamplerT = getOpenCLRuntime().getSamplerType();
440244290647SDimitry Andric   auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
440344290647SDimitry Andric   return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
440444290647SDimitry Andric                                 "__translate_sampler_initializer"),
440544290647SDimitry Andric                                 {C});
440644290647SDimitry Andric }
4407