1f22ef01cSRoman Divacky //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This coordinates the per-module state used while generating code.
11f22ef01cSRoman Divacky //
12f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
13f22ef01cSRoman Divacky 
14f22ef01cSRoman Divacky #include "CodeGenModule.h"
150623d748SDimitry Andric #include "CGBlocks.h"
166122f3e6SDimitry Andric #include "CGCUDARuntime.h"
17e580952dSDimitry Andric #include "CGCXXABI.h"
18139f7f9bSDimitry Andric #include "CGCall.h"
19139f7f9bSDimitry Andric #include "CGDebugInfo.h"
20f22ef01cSRoman Divacky #include "CGObjCRuntime.h"
216122f3e6SDimitry Andric #include "CGOpenCLRuntime.h"
2259d1ed5bSDimitry Andric #include "CGOpenMPRuntime.h"
23e7145dcbSDimitry Andric #include "CGOpenMPRuntimeNVPTX.h"
24139f7f9bSDimitry Andric #include "CodeGenFunction.h"
2559d1ed5bSDimitry Andric #include "CodeGenPGO.h"
269a199699SDimitry Andric #include "ConstantEmitter.h"
2739d628a0SDimitry Andric #include "CoverageMappingGen.h"
28f22ef01cSRoman Divacky #include "TargetInfo.h"
29f22ef01cSRoman Divacky #include "clang/AST/ASTContext.h"
30f22ef01cSRoman Divacky #include "clang/AST/CharUnits.h"
31f22ef01cSRoman Divacky #include "clang/AST/DeclCXX.h"
32139f7f9bSDimitry Andric #include "clang/AST/DeclObjC.h"
33ffd1746dSEd Schouten #include "clang/AST/DeclTemplate.h"
342754fe60SDimitry Andric #include "clang/AST/Mangle.h"
35f22ef01cSRoman Divacky #include "clang/AST/RecordLayout.h"
36f8254f43SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h"
37dff0c46cSDimitry Andric #include "clang/Basic/Builtins.h"
38139f7f9bSDimitry Andric #include "clang/Basic/CharInfo.h"
39f22ef01cSRoman Divacky #include "clang/Basic/Diagnostic.h"
40139f7f9bSDimitry Andric #include "clang/Basic/Module.h"
41f22ef01cSRoman Divacky #include "clang/Basic/SourceManager.h"
42f22ef01cSRoman Divacky #include "clang/Basic/TargetInfo.h"
43f785676fSDimitry Andric #include "clang/Basic/Version.h"
4420e90f04SDimitry Andric #include "clang/CodeGen/ConstantInitBuilder.h"
45139f7f9bSDimitry Andric #include "clang/Frontend/CodeGenOptions.h"
46f785676fSDimitry Andric #include "clang/Sema/SemaDiagnostic.h"
47f22ef01cSRoman Divacky #include "llvm/ADT/Triple.h"
48d8866befSDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
4959d1ed5bSDimitry Andric #include "llvm/IR/CallSite.h"
50139f7f9bSDimitry Andric #include "llvm/IR/CallingConv.h"
51139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h"
52139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h"
53139f7f9bSDimitry Andric #include "llvm/IR/LLVMContext.h"
54139f7f9bSDimitry Andric #include "llvm/IR/Module.h"
5559d1ed5bSDimitry Andric #include "llvm/ProfileData/InstrProfReader.h"
56139f7f9bSDimitry Andric #include "llvm/Support/ConvertUTF.h"
57f22ef01cSRoman Divacky #include "llvm/Support/ErrorHandling.h"
580623d748SDimitry Andric #include "llvm/Support/MD5.h"
59139f7f9bSDimitry Andric 
60f22ef01cSRoman Divacky using namespace clang;
61f22ef01cSRoman Divacky using namespace CodeGen;
62f22ef01cSRoman Divacky 
639a199699SDimitry Andric static llvm::cl::opt<bool> LimitedCoverage(
649a199699SDimitry Andric     "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
659a199699SDimitry Andric     llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
669a199699SDimitry Andric     llvm::cl::init(false));
679a199699SDimitry Andric 
686122f3e6SDimitry Andric static const char AnnotationSection[] = "llvm.metadata";
696122f3e6SDimitry Andric 
7059d1ed5bSDimitry Andric static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
71284c1978SDimitry Andric   switch (CGM.getTarget().getCXXABI().getKind()) {
72139f7f9bSDimitry Andric   case TargetCXXABI::GenericAArch64:
73139f7f9bSDimitry Andric   case TargetCXXABI::GenericARM:
74139f7f9bSDimitry Andric   case TargetCXXABI::iOS:
7559d1ed5bSDimitry Andric   case TargetCXXABI::iOS64:
760623d748SDimitry Andric   case TargetCXXABI::WatchOS:
77ef6fa9e2SDimitry Andric   case TargetCXXABI::GenericMIPS:
78139f7f9bSDimitry Andric   case TargetCXXABI::GenericItanium:
790623d748SDimitry Andric   case TargetCXXABI::WebAssembly:
8059d1ed5bSDimitry Andric     return CreateItaniumCXXABI(CGM);
81139f7f9bSDimitry Andric   case TargetCXXABI::Microsoft:
8259d1ed5bSDimitry Andric     return CreateMicrosoftCXXABI(CGM);
83e580952dSDimitry Andric   }
84e580952dSDimitry Andric 
85e580952dSDimitry Andric   llvm_unreachable("invalid C++ ABI kind");
86e580952dSDimitry Andric }
87e580952dSDimitry Andric 
883dac3a9bSDimitry Andric CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
893dac3a9bSDimitry Andric                              const PreprocessorOptions &PPO,
903dac3a9bSDimitry Andric                              const CodeGenOptions &CGO, llvm::Module &M,
9139d628a0SDimitry Andric                              DiagnosticsEngine &diags,
9239d628a0SDimitry Andric                              CoverageSourceInfo *CoverageInfo)
933dac3a9bSDimitry Andric     : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
943dac3a9bSDimitry Andric       PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
950623d748SDimitry Andric       Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
96e7145dcbSDimitry Andric       VMContext(M.getContext()), Types(*this), VTables(*this),
97e7145dcbSDimitry Andric       SanitizerMD(new SanitizerMetadata(*this)) {
98dff0c46cSDimitry Andric 
99dff0c46cSDimitry Andric   // Initialize the type cache.
100dff0c46cSDimitry Andric   llvm::LLVMContext &LLVMContext = M.getContext();
101dff0c46cSDimitry Andric   VoidTy = llvm::Type::getVoidTy(LLVMContext);
102dff0c46cSDimitry Andric   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
103dff0c46cSDimitry Andric   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
104dff0c46cSDimitry Andric   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
105dff0c46cSDimitry Andric   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
10613ddaa84SDimitry Andric   HalfTy = llvm::Type::getHalfTy(LLVMContext);
107dff0c46cSDimitry Andric   FloatTy = llvm::Type::getFloatTy(LLVMContext);
108dff0c46cSDimitry Andric   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
109dff0c46cSDimitry Andric   PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
110dff0c46cSDimitry Andric   PointerAlignInBytes =
111dff0c46cSDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
11244290647SDimitry Andric   SizeSizeInBytes =
11344290647SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
1140623d748SDimitry Andric   IntAlignInBytes =
1150623d748SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
116dff0c46cSDimitry Andric   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
11744290647SDimitry Andric   IntPtrTy = llvm::IntegerType::get(LLVMContext,
11844290647SDimitry Andric     C.getTargetInfo().getMaxPointerWidth());
119dff0c46cSDimitry Andric   Int8PtrTy = Int8Ty->getPointerTo(0);
120dff0c46cSDimitry Andric   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
1216bc11b14SDimitry Andric   AllocaInt8PtrTy = Int8Ty->getPointerTo(
1226bc11b14SDimitry Andric       M.getDataLayout().getAllocaAddrSpace());
123d8866befSDimitry Andric   ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
124dff0c46cSDimitry Andric 
125139f7f9bSDimitry Andric   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
12639d628a0SDimitry Andric   BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
127139f7f9bSDimitry Andric 
128dff0c46cSDimitry Andric   if (LangOpts.ObjC1)
1293b0f4066SDimitry Andric     createObjCRuntime();
130dff0c46cSDimitry Andric   if (LangOpts.OpenCL)
1316122f3e6SDimitry Andric     createOpenCLRuntime();
13259d1ed5bSDimitry Andric   if (LangOpts.OpenMP)
13359d1ed5bSDimitry Andric     createOpenMPRuntime();
134dff0c46cSDimitry Andric   if (LangOpts.CUDA)
1356122f3e6SDimitry Andric     createCUDARuntime();
136f22ef01cSRoman Divacky 
1377ae0e2c9SDimitry Andric   // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
13839d628a0SDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
1397ae0e2c9SDimitry Andric       (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
1409a199699SDimitry Andric     TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
141e7145dcbSDimitry Andric                                getCXXABI().getMangleContext()));
1422754fe60SDimitry Andric 
1433b0f4066SDimitry Andric   // If debug info or coverage generation is enabled, create the CGDebugInfo
1443b0f4066SDimitry Andric   // object.
145e7145dcbSDimitry Andric   if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
146e7145dcbSDimitry Andric       CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
147e7145dcbSDimitry Andric     DebugInfo.reset(new CGDebugInfo(*this));
1482754fe60SDimitry Andric 
1492754fe60SDimitry Andric   Block.GlobalUniqueCount = 0;
1502754fe60SDimitry Andric 
1510623d748SDimitry Andric   if (C.getLangOpts().ObjC1)
152e7145dcbSDimitry Andric     ObjCData.reset(new ObjCEntrypoints());
15359d1ed5bSDimitry Andric 
154e7145dcbSDimitry Andric   if (CodeGenOpts.hasProfileClangUse()) {
155e7145dcbSDimitry Andric     auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
156e7145dcbSDimitry Andric         CodeGenOpts.ProfileInstrumentUsePath);
157e7145dcbSDimitry Andric     if (auto E = ReaderOrErr.takeError()) {
15859d1ed5bSDimitry Andric       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1593dac3a9bSDimitry Andric                                               "Could not read profile %0: %1");
160e7145dcbSDimitry Andric       llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
161e7145dcbSDimitry Andric         getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
162e7145dcbSDimitry Andric                                   << EI.message();
163e7145dcbSDimitry Andric       });
16433956c43SDimitry Andric     } else
16533956c43SDimitry Andric       PGOReader = std::move(ReaderOrErr.get());
16659d1ed5bSDimitry Andric   }
16739d628a0SDimitry Andric 
16839d628a0SDimitry Andric   // If coverage mapping generation is enabled, create the
16939d628a0SDimitry Andric   // CoverageMappingModuleGen object.
17039d628a0SDimitry Andric   if (CodeGenOpts.CoverageMapping)
17139d628a0SDimitry Andric     CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
172f22ef01cSRoman Divacky }
173f22ef01cSRoman Divacky 
174e7145dcbSDimitry Andric CodeGenModule::~CodeGenModule() {}
175f22ef01cSRoman Divacky 
176f22ef01cSRoman Divacky void CodeGenModule::createObjCRuntime() {
1777ae0e2c9SDimitry Andric   // This is just isGNUFamily(), but we want to force implementors of
1787ae0e2c9SDimitry Andric   // new ABIs to decide how best to do this.
1797ae0e2c9SDimitry Andric   switch (LangOpts.ObjCRuntime.getKind()) {
1807ae0e2c9SDimitry Andric   case ObjCRuntime::GNUstep:
1817ae0e2c9SDimitry Andric   case ObjCRuntime::GCC:
1827ae0e2c9SDimitry Andric   case ObjCRuntime::ObjFW:
183e7145dcbSDimitry Andric     ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
1847ae0e2c9SDimitry Andric     return;
1857ae0e2c9SDimitry Andric 
1867ae0e2c9SDimitry Andric   case ObjCRuntime::FragileMacOSX:
1877ae0e2c9SDimitry Andric   case ObjCRuntime::MacOSX:
1887ae0e2c9SDimitry Andric   case ObjCRuntime::iOS:
1890623d748SDimitry Andric   case ObjCRuntime::WatchOS:
190e7145dcbSDimitry Andric     ObjCRuntime.reset(CreateMacObjCRuntime(*this));
1917ae0e2c9SDimitry Andric     return;
1927ae0e2c9SDimitry Andric   }
1937ae0e2c9SDimitry Andric   llvm_unreachable("bad runtime kind");
1946122f3e6SDimitry Andric }
1956122f3e6SDimitry Andric 
1966122f3e6SDimitry Andric void CodeGenModule::createOpenCLRuntime() {
197e7145dcbSDimitry Andric   OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
1986122f3e6SDimitry Andric }
1996122f3e6SDimitry Andric 
20059d1ed5bSDimitry Andric void CodeGenModule::createOpenMPRuntime() {
201e7145dcbSDimitry Andric   // Select a specialized code generation class based on the target, if any.
202e7145dcbSDimitry Andric   // If it does not exist use the default implementation.
20344290647SDimitry Andric   switch (getTriple().getArch()) {
204e7145dcbSDimitry Andric   case llvm::Triple::nvptx:
205e7145dcbSDimitry Andric   case llvm::Triple::nvptx64:
206e7145dcbSDimitry Andric     assert(getLangOpts().OpenMPIsDevice &&
207e7145dcbSDimitry Andric            "OpenMP NVPTX is only prepared to deal with device code.");
208e7145dcbSDimitry Andric     OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
209e7145dcbSDimitry Andric     break;
210e7145dcbSDimitry Andric   default:
21130785c0eSDimitry Andric     if (LangOpts.OpenMPSimd)
21230785c0eSDimitry Andric       OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
21330785c0eSDimitry Andric     else
214e7145dcbSDimitry Andric       OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
215e7145dcbSDimitry Andric     break;
216e7145dcbSDimitry Andric   }
21759d1ed5bSDimitry Andric }
21859d1ed5bSDimitry Andric 
2196122f3e6SDimitry Andric void CodeGenModule::createCUDARuntime() {
220e7145dcbSDimitry Andric   CUDARuntime.reset(CreateNVCUDARuntime(*this));
221f22ef01cSRoman Divacky }
222f22ef01cSRoman Divacky 
22339d628a0SDimitry Andric void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
22439d628a0SDimitry Andric   Replacements[Name] = C;
22539d628a0SDimitry Andric }
22639d628a0SDimitry Andric 
227f785676fSDimitry Andric void CodeGenModule::applyReplacements() {
2288f0fd8f6SDimitry Andric   for (auto &I : Replacements) {
2298f0fd8f6SDimitry Andric     StringRef MangledName = I.first();
2308f0fd8f6SDimitry Andric     llvm::Constant *Replacement = I.second;
231f785676fSDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
232f785676fSDimitry Andric     if (!Entry)
233f785676fSDimitry Andric       continue;
23459d1ed5bSDimitry Andric     auto *OldF = cast<llvm::Function>(Entry);
23559d1ed5bSDimitry Andric     auto *NewF = dyn_cast<llvm::Function>(Replacement);
236f785676fSDimitry Andric     if (!NewF) {
23759d1ed5bSDimitry Andric       if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
23859d1ed5bSDimitry Andric         NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
23959d1ed5bSDimitry Andric       } else {
24059d1ed5bSDimitry Andric         auto *CE = cast<llvm::ConstantExpr>(Replacement);
241f785676fSDimitry Andric         assert(CE->getOpcode() == llvm::Instruction::BitCast ||
242f785676fSDimitry Andric                CE->getOpcode() == llvm::Instruction::GetElementPtr);
243f785676fSDimitry Andric         NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
244f785676fSDimitry Andric       }
24559d1ed5bSDimitry Andric     }
246f785676fSDimitry Andric 
247f785676fSDimitry Andric     // Replace old with new, but keep the old order.
248f785676fSDimitry Andric     OldF->replaceAllUsesWith(Replacement);
249f785676fSDimitry Andric     if (NewF) {
250f785676fSDimitry Andric       NewF->removeFromParent();
2510623d748SDimitry Andric       OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
2520623d748SDimitry Andric                                                        NewF);
253f785676fSDimitry Andric     }
254f785676fSDimitry Andric     OldF->eraseFromParent();
255f785676fSDimitry Andric   }
256f785676fSDimitry Andric }
257f785676fSDimitry Andric 
2580623d748SDimitry Andric void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
2590623d748SDimitry Andric   GlobalValReplacements.push_back(std::make_pair(GV, C));
2600623d748SDimitry Andric }
2610623d748SDimitry Andric 
2620623d748SDimitry Andric void CodeGenModule::applyGlobalValReplacements() {
2630623d748SDimitry Andric   for (auto &I : GlobalValReplacements) {
2640623d748SDimitry Andric     llvm::GlobalValue *GV = I.first;
2650623d748SDimitry Andric     llvm::Constant *C = I.second;
2660623d748SDimitry Andric 
2670623d748SDimitry Andric     GV->replaceAllUsesWith(C);
2680623d748SDimitry Andric     GV->eraseFromParent();
2690623d748SDimitry Andric   }
2700623d748SDimitry Andric }
2710623d748SDimitry Andric 
27259d1ed5bSDimitry Andric // This is only used in aliases that we created and we know they have a
27359d1ed5bSDimitry Andric // linear structure.
274e7145dcbSDimitry Andric static const llvm::GlobalObject *getAliasedGlobal(
275e7145dcbSDimitry Andric     const llvm::GlobalIndirectSymbol &GIS) {
276e7145dcbSDimitry Andric   llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
277e7145dcbSDimitry Andric   const llvm::Constant *C = &GIS;
27859d1ed5bSDimitry Andric   for (;;) {
27959d1ed5bSDimitry Andric     C = C->stripPointerCasts();
28059d1ed5bSDimitry Andric     if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
28159d1ed5bSDimitry Andric       return GO;
28259d1ed5bSDimitry Andric     // stripPointerCasts will not walk over weak aliases.
283e7145dcbSDimitry Andric     auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
284e7145dcbSDimitry Andric     if (!GIS2)
28559d1ed5bSDimitry Andric       return nullptr;
286e7145dcbSDimitry Andric     if (!Visited.insert(GIS2).second)
28759d1ed5bSDimitry Andric       return nullptr;
288e7145dcbSDimitry Andric     C = GIS2->getIndirectSymbol();
28959d1ed5bSDimitry Andric   }
29059d1ed5bSDimitry Andric }
29159d1ed5bSDimitry Andric 
292f785676fSDimitry Andric void CodeGenModule::checkAliases() {
29359d1ed5bSDimitry Andric   // Check if the constructed aliases are well formed. It is really unfortunate
29459d1ed5bSDimitry Andric   // that we have to do this in CodeGen, but we only construct mangled names
29559d1ed5bSDimitry Andric   // and aliases during codegen.
296f785676fSDimitry Andric   bool Error = false;
29759d1ed5bSDimitry Andric   DiagnosticsEngine &Diags = getDiags();
2988f0fd8f6SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
29959d1ed5bSDimitry Andric     const auto *D = cast<ValueDecl>(GD.getDecl());
300e7145dcbSDimitry Andric     SourceLocation Location;
301e7145dcbSDimitry Andric     bool IsIFunc = D->hasAttr<IFuncAttr>();
302e7145dcbSDimitry Andric     if (const Attr *A = D->getDefiningAttr())
303e7145dcbSDimitry Andric       Location = A->getLocation();
304e7145dcbSDimitry Andric     else
305e7145dcbSDimitry Andric       llvm_unreachable("Not an alias or ifunc?");
306f785676fSDimitry Andric     StringRef MangledName = getMangledName(GD);
307f785676fSDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
308e7145dcbSDimitry Andric     auto *Alias  = cast<llvm::GlobalIndirectSymbol>(Entry);
30959d1ed5bSDimitry Andric     const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
31059d1ed5bSDimitry Andric     if (!GV) {
311f785676fSDimitry Andric       Error = true;
312e7145dcbSDimitry Andric       Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
31359d1ed5bSDimitry Andric     } else if (GV->isDeclaration()) {
314f785676fSDimitry Andric       Error = true;
315e7145dcbSDimitry Andric       Diags.Report(Location, diag::err_alias_to_undefined)
316e7145dcbSDimitry Andric           << IsIFunc << IsIFunc;
317e7145dcbSDimitry Andric     } else if (IsIFunc) {
318e7145dcbSDimitry Andric       // Check resolver function type.
319e7145dcbSDimitry Andric       llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
320e7145dcbSDimitry Andric           GV->getType()->getPointerElementType());
321e7145dcbSDimitry Andric       assert(FTy);
322e7145dcbSDimitry Andric       if (!FTy->getReturnType()->isPointerTy())
323e7145dcbSDimitry Andric         Diags.Report(Location, diag::err_ifunc_resolver_return);
324e7145dcbSDimitry Andric       if (FTy->getNumParams())
325e7145dcbSDimitry Andric         Diags.Report(Location, diag::err_ifunc_resolver_params);
32659d1ed5bSDimitry Andric     }
32759d1ed5bSDimitry Andric 
328e7145dcbSDimitry Andric     llvm::Constant *Aliasee = Alias->getIndirectSymbol();
32959d1ed5bSDimitry Andric     llvm::GlobalValue *AliaseeGV;
33059d1ed5bSDimitry Andric     if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
33159d1ed5bSDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
33259d1ed5bSDimitry Andric     else
33359d1ed5bSDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
33459d1ed5bSDimitry Andric 
33559d1ed5bSDimitry Andric     if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
33659d1ed5bSDimitry Andric       StringRef AliasSection = SA->getName();
33759d1ed5bSDimitry Andric       if (AliasSection != AliaseeGV->getSection())
33859d1ed5bSDimitry Andric         Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
339e7145dcbSDimitry Andric             << AliasSection << IsIFunc << IsIFunc;
34059d1ed5bSDimitry Andric     }
34159d1ed5bSDimitry Andric 
34259d1ed5bSDimitry Andric     // We have to handle alias to weak aliases in here. LLVM itself disallows
34359d1ed5bSDimitry Andric     // this since the object semantics would not match the IL one. For
34459d1ed5bSDimitry Andric     // compatibility with gcc we implement it by just pointing the alias
34559d1ed5bSDimitry Andric     // to its aliasee's aliasee. We also warn, since the user is probably
34659d1ed5bSDimitry Andric     // expecting the link to be weak.
347e7145dcbSDimitry Andric     if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
348e7145dcbSDimitry Andric       if (GA->isInterposable()) {
349e7145dcbSDimitry Andric         Diags.Report(Location, diag::warn_alias_to_weak_alias)
350e7145dcbSDimitry Andric             << GV->getName() << GA->getName() << IsIFunc;
35159d1ed5bSDimitry Andric         Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
352e7145dcbSDimitry Andric             GA->getIndirectSymbol(), Alias->getType());
353e7145dcbSDimitry Andric         Alias->setIndirectSymbol(Aliasee);
35459d1ed5bSDimitry Andric       }
355f785676fSDimitry Andric     }
356f785676fSDimitry Andric   }
357f785676fSDimitry Andric   if (!Error)
358f785676fSDimitry Andric     return;
359f785676fSDimitry Andric 
3608f0fd8f6SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
361f785676fSDimitry Andric     StringRef MangledName = getMangledName(GD);
362f785676fSDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
363e7145dcbSDimitry Andric     auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
364f785676fSDimitry Andric     Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
365f785676fSDimitry Andric     Alias->eraseFromParent();
366f785676fSDimitry Andric   }
367f785676fSDimitry Andric }
368f785676fSDimitry Andric 
36959d1ed5bSDimitry Andric void CodeGenModule::clear() {
37059d1ed5bSDimitry Andric   DeferredDeclsToEmit.clear();
37133956c43SDimitry Andric   if (OpenMPRuntime)
37233956c43SDimitry Andric     OpenMPRuntime->clear();
37359d1ed5bSDimitry Andric }
37459d1ed5bSDimitry Andric 
37559d1ed5bSDimitry Andric void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
37659d1ed5bSDimitry Andric                                        StringRef MainFile) {
37759d1ed5bSDimitry Andric   if (!hasDiagnostics())
37859d1ed5bSDimitry Andric     return;
37959d1ed5bSDimitry Andric   if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
38059d1ed5bSDimitry Andric     if (MainFile.empty())
38159d1ed5bSDimitry Andric       MainFile = "<stdin>";
38259d1ed5bSDimitry Andric     Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
383f37b6182SDimitry Andric   } else {
384f37b6182SDimitry Andric     if (Mismatched > 0)
385f37b6182SDimitry Andric       Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
386f37b6182SDimitry Andric 
387f37b6182SDimitry Andric     if (Missing > 0)
388f37b6182SDimitry Andric       Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
389f37b6182SDimitry Andric   }
39059d1ed5bSDimitry Andric }
39159d1ed5bSDimitry Andric 
392f22ef01cSRoman Divacky void CodeGenModule::Release() {
393f22ef01cSRoman Divacky   EmitDeferred();
394f9448bf3SDimitry Andric   EmitVTablesOpportunistically();
3950623d748SDimitry Andric   applyGlobalValReplacements();
396f785676fSDimitry Andric   applyReplacements();
397f785676fSDimitry Andric   checkAliases();
398f22ef01cSRoman Divacky   EmitCXXGlobalInitFunc();
399f22ef01cSRoman Divacky   EmitCXXGlobalDtorFunc();
400284c1978SDimitry Andric   EmitCXXThreadLocalInitFunc();
4016122f3e6SDimitry Andric   if (ObjCRuntime)
4026122f3e6SDimitry Andric     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
403f22ef01cSRoman Divacky       AddGlobalCtor(ObjCInitFunction);
40433956c43SDimitry Andric   if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
40533956c43SDimitry Andric       CUDARuntime) {
40633956c43SDimitry Andric     if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
40733956c43SDimitry Andric       AddGlobalCtor(CudaCtorFunction);
40833956c43SDimitry Andric     if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
40933956c43SDimitry Andric       AddGlobalDtor(CudaDtorFunction);
41033956c43SDimitry Andric   }
411ea942507SDimitry Andric   if (OpenMPRuntime)
412ea942507SDimitry Andric     if (llvm::Function *OpenMPRegistrationFunction =
413302affcbSDimitry Andric             OpenMPRuntime->emitRegistrationFunction()) {
414302affcbSDimitry Andric       auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
415302affcbSDimitry Andric         OpenMPRegistrationFunction : nullptr;
416302affcbSDimitry Andric       AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
417302affcbSDimitry Andric     }
4180623d748SDimitry Andric   if (PGOReader) {
419e7145dcbSDimitry Andric     getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
4200623d748SDimitry Andric     if (PGOStats.hasDiagnostics())
42159d1ed5bSDimitry Andric       PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
4220623d748SDimitry Andric   }
423f22ef01cSRoman Divacky   EmitCtorList(GlobalCtors, "llvm.global_ctors");
424f22ef01cSRoman Divacky   EmitCtorList(GlobalDtors, "llvm.global_dtors");
4256122f3e6SDimitry Andric   EmitGlobalAnnotations();
426284c1978SDimitry Andric   EmitStaticExternCAliases();
42739d628a0SDimitry Andric   EmitDeferredUnusedCoverageMappings();
42839d628a0SDimitry Andric   if (CoverageMapping)
42939d628a0SDimitry Andric     CoverageMapping->emit();
43020e90f04SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
431e7145dcbSDimitry Andric     CodeGenFunction(*this).EmitCfiCheckFail();
43220e90f04SDimitry Andric     CodeGenFunction(*this).EmitCfiCheckStub();
43320e90f04SDimitry Andric   }
43420e90f04SDimitry Andric   emitAtAvailableLinkGuard();
43559d1ed5bSDimitry Andric   emitLLVMUsed();
436e7145dcbSDimitry Andric   if (SanStats)
437e7145dcbSDimitry Andric     SanStats->finish();
438ffd1746dSEd Schouten 
439f785676fSDimitry Andric   if (CodeGenOpts.Autolink &&
440f785676fSDimitry Andric       (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
441139f7f9bSDimitry Andric     EmitModuleLinkOptions();
442139f7f9bSDimitry Andric   }
44320e90f04SDimitry Andric 
44420e90f04SDimitry Andric   // Record mregparm value now so it is visible through rest of codegen.
44520e90f04SDimitry Andric   if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
44620e90f04SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
44720e90f04SDimitry Andric                               CodeGenOpts.NumRegisterParameters);
44820e90f04SDimitry Andric 
4490623d748SDimitry Andric   if (CodeGenOpts.DwarfVersion) {
450f785676fSDimitry Andric     // We actually want the latest version when there are conflicts.
451f785676fSDimitry Andric     // We can change from Warning to Latest if such mode is supported.
452f785676fSDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
453f785676fSDimitry Andric                               CodeGenOpts.DwarfVersion);
4540623d748SDimitry Andric   }
4550623d748SDimitry Andric   if (CodeGenOpts.EmitCodeView) {
4560623d748SDimitry Andric     // Indicate that we want CodeView in the metadata.
4570623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
4580623d748SDimitry Andric   }
4590623d748SDimitry Andric   if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
4600623d748SDimitry Andric     // We don't support LTO with 2 with different StrictVTablePointers
4610623d748SDimitry Andric     // FIXME: we could support it by stripping all the information introduced
4620623d748SDimitry Andric     // by StrictVTablePointers.
4630623d748SDimitry Andric 
4640623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
4650623d748SDimitry Andric 
4660623d748SDimitry Andric     llvm::Metadata *Ops[2] = {
4670623d748SDimitry Andric               llvm::MDString::get(VMContext, "StrictVTablePointers"),
4680623d748SDimitry Andric               llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
4690623d748SDimitry Andric                   llvm::Type::getInt32Ty(VMContext), 1))};
4700623d748SDimitry Andric 
4710623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Require,
4720623d748SDimitry Andric                               "StrictVTablePointersRequirement",
4730623d748SDimitry Andric                               llvm::MDNode::get(VMContext, Ops));
4740623d748SDimitry Andric   }
475f785676fSDimitry Andric   if (DebugInfo)
47659d1ed5bSDimitry Andric     // We support a single version in the linked module. The LLVM
47759d1ed5bSDimitry Andric     // parser will drop debug info with a different version number
47859d1ed5bSDimitry Andric     // (and warn about it, too).
47959d1ed5bSDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
480f785676fSDimitry Andric                               llvm::DEBUG_METADATA_VERSION);
481139f7f9bSDimitry Andric 
48259d1ed5bSDimitry Andric   // We need to record the widths of enums and wchar_t, so that we can generate
483d8866befSDimitry Andric   // the correct build attributes in the ARM backend. wchar_size is also used by
484d8866befSDimitry Andric   // TargetLibraryInfo.
4859a199699SDimitry Andric   uint64_t WCharWidth =
4869a199699SDimitry Andric       Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
487d8866befSDimitry Andric   getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
488d8866befSDimitry Andric 
48959d1ed5bSDimitry Andric   llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
49059d1ed5bSDimitry Andric   if (   Arch == llvm::Triple::arm
49159d1ed5bSDimitry Andric       || Arch == llvm::Triple::armeb
49259d1ed5bSDimitry Andric       || Arch == llvm::Triple::thumb
49359d1ed5bSDimitry Andric       || Arch == llvm::Triple::thumbeb) {
49459d1ed5bSDimitry Andric     // The minimum width of an enum in bytes
49559d1ed5bSDimitry Andric     uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
49659d1ed5bSDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
49759d1ed5bSDimitry Andric   }
49859d1ed5bSDimitry Andric 
4990623d748SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
5000623d748SDimitry Andric     // Indicate that we want cross-DSO control flow integrity checks.
5010623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
5020623d748SDimitry Andric   }
5030623d748SDimitry Andric 
50444290647SDimitry Andric   if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
505e7145dcbSDimitry Andric     // Indicate whether __nvvm_reflect should be configured to flush denormal
506e7145dcbSDimitry Andric     // floating point values to 0.  (This corresponds to its "__CUDA_FTZ"
507e7145dcbSDimitry Andric     // property.)
508e7145dcbSDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
509e7145dcbSDimitry Andric                               LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
51039d628a0SDimitry Andric   }
51139d628a0SDimitry Andric 
512edd7eaddSDimitry Andric   // Emit OpenCL specific module metadata: OpenCL/SPIR version.
513edd7eaddSDimitry Andric   if (LangOpts.OpenCL) {
514edd7eaddSDimitry Andric     EmitOpenCLMetadata();
515edd7eaddSDimitry Andric     // Emit SPIR version.
516edd7eaddSDimitry Andric     if (getTriple().getArch() == llvm::Triple::spir ||
517edd7eaddSDimitry Andric         getTriple().getArch() == llvm::Triple::spir64) {
518edd7eaddSDimitry Andric       // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
519edd7eaddSDimitry Andric       // opencl.spir.version named metadata.
520edd7eaddSDimitry Andric       llvm::Metadata *SPIRVerElts[] = {
521edd7eaddSDimitry Andric           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
522edd7eaddSDimitry Andric               Int32Ty, LangOpts.OpenCLVersion / 100)),
523edd7eaddSDimitry Andric           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
524edd7eaddSDimitry Andric               Int32Ty, (LangOpts.OpenCLVersion / 100 > 1) ? 0 : 2))};
525edd7eaddSDimitry Andric       llvm::NamedMDNode *SPIRVerMD =
526edd7eaddSDimitry Andric           TheModule.getOrInsertNamedMetadata("opencl.spir.version");
527edd7eaddSDimitry Andric       llvm::LLVMContext &Ctx = TheModule.getContext();
528edd7eaddSDimitry Andric       SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
529edd7eaddSDimitry Andric     }
530edd7eaddSDimitry Andric   }
531edd7eaddSDimitry Andric 
532e7145dcbSDimitry Andric   if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
533e7145dcbSDimitry Andric     assert(PLevel < 3 && "Invalid PIC Level");
534e7145dcbSDimitry Andric     getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
535e7145dcbSDimitry Andric     if (Context.getLangOpts().PIE)
536e7145dcbSDimitry Andric       getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
53739d628a0SDimitry Andric   }
53839d628a0SDimitry Andric 
5392754fe60SDimitry Andric   SimplifyPersonality();
5402754fe60SDimitry Andric 
541ffd1746dSEd Schouten   if (getCodeGenOpts().EmitDeclMetadata)
542ffd1746dSEd Schouten     EmitDeclMetadata();
543bd5abe19SDimitry Andric 
544bd5abe19SDimitry Andric   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
545bd5abe19SDimitry Andric     EmitCoverageFile();
5466122f3e6SDimitry Andric 
5476122f3e6SDimitry Andric   if (DebugInfo)
5486122f3e6SDimitry Andric     DebugInfo->finalize();
549f785676fSDimitry Andric 
550f785676fSDimitry Andric   EmitVersionIdentMetadata();
55159d1ed5bSDimitry Andric 
55259d1ed5bSDimitry Andric   EmitTargetMetadata();
553f22ef01cSRoman Divacky }
554f22ef01cSRoman Divacky 
555edd7eaddSDimitry Andric void CodeGenModule::EmitOpenCLMetadata() {
556edd7eaddSDimitry Andric   // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
557edd7eaddSDimitry Andric   // opencl.ocl.version named metadata node.
558edd7eaddSDimitry Andric   llvm::Metadata *OCLVerElts[] = {
559edd7eaddSDimitry Andric       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
560edd7eaddSDimitry Andric           Int32Ty, LangOpts.OpenCLVersion / 100)),
561edd7eaddSDimitry Andric       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
562edd7eaddSDimitry Andric           Int32Ty, (LangOpts.OpenCLVersion % 100) / 10))};
563edd7eaddSDimitry Andric   llvm::NamedMDNode *OCLVerMD =
564edd7eaddSDimitry Andric       TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
565edd7eaddSDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
566edd7eaddSDimitry Andric   OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
567edd7eaddSDimitry Andric }
568edd7eaddSDimitry Andric 
5693b0f4066SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
5703b0f4066SDimitry Andric   // Make sure that this type is translated.
5713b0f4066SDimitry Andric   Types.UpdateCompletedType(TD);
5723b0f4066SDimitry Andric }
5733b0f4066SDimitry Andric 
574e7145dcbSDimitry Andric void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
575e7145dcbSDimitry Andric   // Make sure that this type is translated.
576e7145dcbSDimitry Andric   Types.RefreshTypeCacheForClass(RD);
577e7145dcbSDimitry Andric }
578e7145dcbSDimitry Andric 
5799a199699SDimitry Andric llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
5802754fe60SDimitry Andric   if (!TBAA)
58159d1ed5bSDimitry Andric     return nullptr;
5829a199699SDimitry Andric   return TBAA->getTypeInfo(QTy);
5832754fe60SDimitry Andric }
5842754fe60SDimitry Andric 
5859a199699SDimitry Andric TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
5869a199699SDimitry Andric   // Pointee values may have incomplete types, but they shall never be
5879a199699SDimitry Andric   // dereferenced.
5889a199699SDimitry Andric   if (AccessType->isIncompleteType())
5899a199699SDimitry Andric     return TBAAAccessInfo::getIncompleteInfo();
5909a199699SDimitry Andric 
5919a199699SDimitry Andric   uint64_t Size = Context.getTypeSizeInChars(AccessType).getQuantity();
5929a199699SDimitry Andric   return TBAAAccessInfo(getTBAATypeInfo(AccessType), Size);
5939a199699SDimitry Andric }
5949a199699SDimitry Andric 
5959a199699SDimitry Andric TBAAAccessInfo
5969a199699SDimitry Andric CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
597dff0c46cSDimitry Andric   if (!TBAA)
5989a199699SDimitry Andric     return TBAAAccessInfo();
5999a199699SDimitry Andric   return TBAA->getVTablePtrAccessInfo(VTablePtrType);
600dff0c46cSDimitry Andric }
601dff0c46cSDimitry Andric 
6023861d79fSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
6033861d79fSDimitry Andric   if (!TBAA)
60459d1ed5bSDimitry Andric     return nullptr;
6053861d79fSDimitry Andric   return TBAA->getTBAAStructInfo(QTy);
6063861d79fSDimitry Andric }
6073861d79fSDimitry Andric 
6089a199699SDimitry Andric llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
609139f7f9bSDimitry Andric   if (!TBAA)
61059d1ed5bSDimitry Andric     return nullptr;
6119a199699SDimitry Andric   return TBAA->getBaseTypeInfo(QTy);
612139f7f9bSDimitry Andric }
613139f7f9bSDimitry Andric 
6149a199699SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
6159a199699SDimitry Andric   if (!TBAA)
6169a199699SDimitry Andric     return nullptr;
6179a199699SDimitry Andric   return TBAA->getAccessTagInfo(Info);
6189a199699SDimitry Andric }
6199a199699SDimitry Andric 
6209a199699SDimitry Andric TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
6219a199699SDimitry Andric                                                    TBAAAccessInfo TargetInfo) {
6229a199699SDimitry Andric   if (!TBAA)
6239a199699SDimitry Andric     return TBAAAccessInfo();
6249a199699SDimitry Andric   return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
6259a199699SDimitry Andric }
6269a199699SDimitry Andric 
6279a199699SDimitry Andric TBAAAccessInfo
6289a199699SDimitry Andric CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
6299a199699SDimitry Andric                                                    TBAAAccessInfo InfoB) {
6309a199699SDimitry Andric   if (!TBAA)
6319a199699SDimitry Andric     return TBAAAccessInfo();
6329a199699SDimitry Andric   return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
6339a199699SDimitry Andric }
6349a199699SDimitry Andric 
6350623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
6369a199699SDimitry Andric                                                 TBAAAccessInfo TBAAInfo) {
6379a199699SDimitry Andric   if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
6389a199699SDimitry Andric     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
6392754fe60SDimitry Andric }
6402754fe60SDimitry Andric 
6410623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithInvariantGroup(
6420623d748SDimitry Andric     llvm::Instruction *I, const CXXRecordDecl *RD) {
64351690af2SDimitry Andric   I->setMetadata(llvm::LLVMContext::MD_invariant_group,
64451690af2SDimitry Andric                  llvm::MDNode::get(getLLVMContext(), {}));
6450623d748SDimitry Andric }
6460623d748SDimitry Andric 
64759d1ed5bSDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) {
64859d1ed5bSDimitry Andric   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
64959d1ed5bSDimitry Andric   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
650f22ef01cSRoman Divacky }
651f22ef01cSRoman Divacky 
652f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
653f22ef01cSRoman Divacky /// specified stmt yet.
654f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
6556122f3e6SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
656f22ef01cSRoman Divacky                                                "cannot compile this %0 yet");
657f22ef01cSRoman Divacky   std::string Msg = Type;
658f22ef01cSRoman Divacky   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
659f22ef01cSRoman Divacky     << Msg << S->getSourceRange();
660f22ef01cSRoman Divacky }
661f22ef01cSRoman Divacky 
662f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
663f22ef01cSRoman Divacky /// specified decl yet.
664f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
6656122f3e6SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
666f22ef01cSRoman Divacky                                                "cannot compile this %0 yet");
667f22ef01cSRoman Divacky   std::string Msg = Type;
668f22ef01cSRoman Divacky   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
669f22ef01cSRoman Divacky }
670f22ef01cSRoman Divacky 
67117a519f9SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
67217a519f9SDimitry Andric   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
67317a519f9SDimitry Andric }
67417a519f9SDimitry Andric 
675f22ef01cSRoman Divacky void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
6769a199699SDimitry Andric                                         const NamedDecl *D,
6779a199699SDimitry Andric                                         ForDefinition_t IsForDefinition) const {
678f22ef01cSRoman Divacky   // Internal definitions always have default visibility.
679f22ef01cSRoman Divacky   if (GV->hasLocalLinkage()) {
680f22ef01cSRoman Divacky     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
681f22ef01cSRoman Divacky     return;
682f22ef01cSRoman Divacky   }
683f22ef01cSRoman Divacky 
6842754fe60SDimitry Andric   // Set visibility for definitions.
685139f7f9bSDimitry Andric   LinkageInfo LV = D->getLinkageAndVisibility();
6869a199699SDimitry Andric   if (LV.isVisibilityExplicit() ||
6879a199699SDimitry Andric       (IsForDefinition && !GV->hasAvailableExternallyLinkage()))
688139f7f9bSDimitry Andric     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
689f22ef01cSRoman Divacky }
690f22ef01cSRoman Divacky 
6917ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
6927ae0e2c9SDimitry Andric   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
6937ae0e2c9SDimitry Andric       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
6947ae0e2c9SDimitry Andric       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
6957ae0e2c9SDimitry Andric       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
6967ae0e2c9SDimitry Andric       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
6977ae0e2c9SDimitry Andric }
6987ae0e2c9SDimitry Andric 
6997ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
7007ae0e2c9SDimitry Andric     CodeGenOptions::TLSModel M) {
7017ae0e2c9SDimitry Andric   switch (M) {
7027ae0e2c9SDimitry Andric   case CodeGenOptions::GeneralDynamicTLSModel:
7037ae0e2c9SDimitry Andric     return llvm::GlobalVariable::GeneralDynamicTLSModel;
7047ae0e2c9SDimitry Andric   case CodeGenOptions::LocalDynamicTLSModel:
7057ae0e2c9SDimitry Andric     return llvm::GlobalVariable::LocalDynamicTLSModel;
7067ae0e2c9SDimitry Andric   case CodeGenOptions::InitialExecTLSModel:
7077ae0e2c9SDimitry Andric     return llvm::GlobalVariable::InitialExecTLSModel;
7087ae0e2c9SDimitry Andric   case CodeGenOptions::LocalExecTLSModel:
7097ae0e2c9SDimitry Andric     return llvm::GlobalVariable::LocalExecTLSModel;
7107ae0e2c9SDimitry Andric   }
7117ae0e2c9SDimitry Andric   llvm_unreachable("Invalid TLS model!");
7127ae0e2c9SDimitry Andric }
7137ae0e2c9SDimitry Andric 
71439d628a0SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
715284c1978SDimitry Andric   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
7167ae0e2c9SDimitry Andric 
71739d628a0SDimitry Andric   llvm::GlobalValue::ThreadLocalMode TLM;
7183861d79fSDimitry Andric   TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
7197ae0e2c9SDimitry Andric 
7207ae0e2c9SDimitry Andric   // Override the TLS model if it is explicitly specified.
72159d1ed5bSDimitry Andric   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
7227ae0e2c9SDimitry Andric     TLM = GetLLVMTLSModel(Attr->getModel());
7237ae0e2c9SDimitry Andric   }
7247ae0e2c9SDimitry Andric 
7257ae0e2c9SDimitry Andric   GV->setThreadLocalMode(TLM);
7267ae0e2c9SDimitry Andric }
7277ae0e2c9SDimitry Andric 
7286122f3e6SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
729444ed5c5SDimitry Andric   GlobalDecl CanonicalGD = GD.getCanonicalDecl();
730444ed5c5SDimitry Andric 
731444ed5c5SDimitry Andric   // Some ABIs don't have constructor variants.  Make sure that base and
732444ed5c5SDimitry Andric   // complete constructors get mangled the same.
733444ed5c5SDimitry Andric   if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
734444ed5c5SDimitry Andric     if (!getTarget().getCXXABI().hasConstructorVariants()) {
735444ed5c5SDimitry Andric       CXXCtorType OrigCtorType = GD.getCtorType();
736444ed5c5SDimitry Andric       assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
737444ed5c5SDimitry Andric       if (OrigCtorType == Ctor_Base)
738444ed5c5SDimitry Andric         CanonicalGD = GlobalDecl(CD, Ctor_Complete);
739444ed5c5SDimitry Andric     }
740444ed5c5SDimitry Andric   }
741444ed5c5SDimitry Andric 
7429a199699SDimitry Andric   auto FoundName = MangledDeclNames.find(CanonicalGD);
7439a199699SDimitry Andric   if (FoundName != MangledDeclNames.end())
7449a199699SDimitry Andric     return FoundName->second;
745f22ef01cSRoman Divacky 
74659d1ed5bSDimitry Andric   const auto *ND = cast<NamedDecl>(GD.getDecl());
747dff0c46cSDimitry Andric   SmallString<256> Buffer;
74859d1ed5bSDimitry Andric   StringRef Str;
74959d1ed5bSDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
7502754fe60SDimitry Andric     llvm::raw_svector_ostream Out(Buffer);
75159d1ed5bSDimitry Andric     if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
7522754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
75359d1ed5bSDimitry Andric     else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
7542754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
755ffd1746dSEd Schouten     else
7562754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleName(ND, Out);
75759d1ed5bSDimitry Andric     Str = Out.str();
75859d1ed5bSDimitry Andric   } else {
75959d1ed5bSDimitry Andric     IdentifierInfo *II = ND->getIdentifier();
76059d1ed5bSDimitry Andric     assert(II && "Attempt to mangle unnamed decl.");
76144290647SDimitry Andric     const auto *FD = dyn_cast<FunctionDecl>(ND);
76244290647SDimitry Andric 
76344290647SDimitry Andric     if (FD &&
76444290647SDimitry Andric         FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
76544290647SDimitry Andric       llvm::raw_svector_ostream Out(Buffer);
76644290647SDimitry Andric       Out << "__regcall3__" << II->getName();
76744290647SDimitry Andric       Str = Out.str();
76844290647SDimitry Andric     } else {
76959d1ed5bSDimitry Andric       Str = II->getName();
770ffd1746dSEd Schouten     }
77144290647SDimitry Andric   }
772ffd1746dSEd Schouten 
77339d628a0SDimitry Andric   // Keep the first result in the case of a mangling collision.
77439d628a0SDimitry Andric   auto Result = Manglings.insert(std::make_pair(Str, GD));
7759a199699SDimitry Andric   return MangledDeclNames[CanonicalGD] = Result.first->first();
77659d1ed5bSDimitry Andric }
77759d1ed5bSDimitry Andric 
77859d1ed5bSDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
779ffd1746dSEd Schouten                                              const BlockDecl *BD) {
7802754fe60SDimitry Andric   MangleContext &MangleCtx = getCXXABI().getMangleContext();
7812754fe60SDimitry Andric   const Decl *D = GD.getDecl();
78259d1ed5bSDimitry Andric 
78359d1ed5bSDimitry Andric   SmallString<256> Buffer;
78459d1ed5bSDimitry Andric   llvm::raw_svector_ostream Out(Buffer);
78559d1ed5bSDimitry Andric   if (!D)
7867ae0e2c9SDimitry Andric     MangleCtx.mangleGlobalBlock(BD,
7877ae0e2c9SDimitry Andric       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
78859d1ed5bSDimitry Andric   else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
7892754fe60SDimitry Andric     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
79059d1ed5bSDimitry Andric   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
7912754fe60SDimitry Andric     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
7922754fe60SDimitry Andric   else
7932754fe60SDimitry Andric     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
79459d1ed5bSDimitry Andric 
79539d628a0SDimitry Andric   auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
79639d628a0SDimitry Andric   return Result.first->first();
797f22ef01cSRoman Divacky }
798f22ef01cSRoman Divacky 
7996122f3e6SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
800f22ef01cSRoman Divacky   return getModule().getNamedValue(Name);
801f22ef01cSRoman Divacky }
802f22ef01cSRoman Divacky 
803f22ef01cSRoman Divacky /// AddGlobalCtor - Add a function to the list that will be called before
804f22ef01cSRoman Divacky /// main() runs.
80559d1ed5bSDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
80659d1ed5bSDimitry Andric                                   llvm::Constant *AssociatedData) {
807f22ef01cSRoman Divacky   // FIXME: Type coercion of void()* types.
80859d1ed5bSDimitry Andric   GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
809f22ef01cSRoman Divacky }
810f22ef01cSRoman Divacky 
811f22ef01cSRoman Divacky /// AddGlobalDtor - Add a function to the list that will be called
812f22ef01cSRoman Divacky /// when the module is unloaded.
813f22ef01cSRoman Divacky void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
814f22ef01cSRoman Divacky   // FIXME: Type coercion of void()* types.
81559d1ed5bSDimitry Andric   GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
816f22ef01cSRoman Divacky }
817f22ef01cSRoman Divacky 
81844290647SDimitry Andric void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
81944290647SDimitry Andric   if (Fns.empty()) return;
82044290647SDimitry Andric 
821f22ef01cSRoman Divacky   // Ctor function type is void()*.
822bd5abe19SDimitry Andric   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
823f22ef01cSRoman Divacky   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
824f22ef01cSRoman Divacky 
82559d1ed5bSDimitry Andric   // Get the type of a ctor entry, { i32, void ()*, i8* }.
82659d1ed5bSDimitry Andric   llvm::StructType *CtorStructTy = llvm::StructType::get(
8275517e702SDimitry Andric       Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy);
828f22ef01cSRoman Divacky 
829f22ef01cSRoman Divacky   // Construct the constructor and destructor arrays.
83044290647SDimitry Andric   ConstantInitBuilder builder(*this);
83144290647SDimitry Andric   auto ctors = builder.beginArray(CtorStructTy);
8328f0fd8f6SDimitry Andric   for (const auto &I : Fns) {
83344290647SDimitry Andric     auto ctor = ctors.beginStruct(CtorStructTy);
83444290647SDimitry Andric     ctor.addInt(Int32Ty, I.Priority);
83544290647SDimitry Andric     ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
83644290647SDimitry Andric     if (I.AssociatedData)
83744290647SDimitry Andric       ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
83844290647SDimitry Andric     else
83944290647SDimitry Andric       ctor.addNullPointer(VoidPtrTy);
84044290647SDimitry Andric     ctor.finishAndAddTo(ctors);
841f22ef01cSRoman Divacky   }
842f22ef01cSRoman Divacky 
84344290647SDimitry Andric   auto list =
84444290647SDimitry Andric     ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
84544290647SDimitry Andric                                 /*constant*/ false,
84644290647SDimitry Andric                                 llvm::GlobalValue::AppendingLinkage);
84744290647SDimitry Andric 
84844290647SDimitry Andric   // The LTO linker doesn't seem to like it when we set an alignment
84944290647SDimitry Andric   // on appending variables.  Take it off as a workaround.
85044290647SDimitry Andric   list->setAlignment(0);
85144290647SDimitry Andric 
85244290647SDimitry Andric   Fns.clear();
853f22ef01cSRoman Divacky }
854f22ef01cSRoman Divacky 
855f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes
856f785676fSDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
85759d1ed5bSDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
858f785676fSDimitry Andric 
859e580952dSDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
860f22ef01cSRoman Divacky 
86159d1ed5bSDimitry Andric   if (isa<CXXDestructorDecl>(D) &&
86259d1ed5bSDimitry Andric       getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
86359d1ed5bSDimitry Andric                                          GD.getDtorType())) {
86459d1ed5bSDimitry Andric     // Destructor variants in the Microsoft C++ ABI are always internal or
86559d1ed5bSDimitry Andric     // linkonce_odr thunks emitted on an as-needed basis.
86659d1ed5bSDimitry Andric     return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
86759d1ed5bSDimitry Andric                                    : llvm::GlobalValue::LinkOnceODRLinkage;
868f22ef01cSRoman Divacky   }
869f22ef01cSRoman Divacky 
870e7145dcbSDimitry Andric   if (isa<CXXConstructorDecl>(D) &&
871e7145dcbSDimitry Andric       cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
872e7145dcbSDimitry Andric       Context.getTargetInfo().getCXXABI().isMicrosoft()) {
873e7145dcbSDimitry Andric     // Our approach to inheriting constructors is fundamentally different from
874e7145dcbSDimitry Andric     // that used by the MS ABI, so keep our inheriting constructor thunks
875e7145dcbSDimitry Andric     // internal rather than trying to pick an unambiguous mangling for them.
876e7145dcbSDimitry Andric     return llvm::GlobalValue::InternalLinkage;
877e7145dcbSDimitry Andric   }
878e7145dcbSDimitry Andric 
87959d1ed5bSDimitry Andric   return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
88059d1ed5bSDimitry Andric }
881f22ef01cSRoman Divacky 
88297bc6c73SDimitry Andric void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
88397bc6c73SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
88497bc6c73SDimitry Andric 
88597bc6c73SDimitry Andric   if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
88697bc6c73SDimitry Andric     if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
88797bc6c73SDimitry Andric       // Don't dllexport/import destructor thunks.
88897bc6c73SDimitry Andric       F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
88997bc6c73SDimitry Andric       return;
89097bc6c73SDimitry Andric     }
89197bc6c73SDimitry Andric   }
89297bc6c73SDimitry Andric 
89397bc6c73SDimitry Andric   if (FD->hasAttr<DLLImportAttr>())
89497bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
89597bc6c73SDimitry Andric   else if (FD->hasAttr<DLLExportAttr>())
89697bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
89797bc6c73SDimitry Andric   else
89897bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
89997bc6c73SDimitry Andric }
90097bc6c73SDimitry Andric 
901e7145dcbSDimitry Andric llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
9020623d748SDimitry Andric   llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
9030623d748SDimitry Andric   if (!MDS) return nullptr;
9040623d748SDimitry Andric 
90544290647SDimitry Andric   return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
9060623d748SDimitry Andric }
9070623d748SDimitry Andric 
90859d1ed5bSDimitry Andric void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
90959d1ed5bSDimitry Andric                                                     llvm::Function *F) {
91059d1ed5bSDimitry Andric   setNonAliasAttributes(D, F);
911f22ef01cSRoman Divacky }
912f22ef01cSRoman Divacky 
913f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
914f22ef01cSRoman Divacky                                               const CGFunctionInfo &Info,
915f22ef01cSRoman Divacky                                               llvm::Function *F) {
916f22ef01cSRoman Divacky   unsigned CallingConv;
9176bc11b14SDimitry Andric   llvm::AttributeList PAL;
9186bc11b14SDimitry Andric   ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false);
9196bc11b14SDimitry Andric   F->setAttributes(PAL);
920f22ef01cSRoman Divacky   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
921f22ef01cSRoman Divacky }
922f22ef01cSRoman Divacky 
9236122f3e6SDimitry Andric /// Determines whether the language options require us to model
9246122f3e6SDimitry Andric /// unwind exceptions.  We treat -fexceptions as mandating this
9256122f3e6SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions
9266122f3e6SDimitry Andric /// enabled.  This means, for example, that C with -fexceptions
9276122f3e6SDimitry Andric /// enables this.
928dff0c46cSDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) {
9296122f3e6SDimitry Andric   // If exceptions are completely disabled, obviously this is false.
930dff0c46cSDimitry Andric   if (!LangOpts.Exceptions) return false;
9316122f3e6SDimitry Andric 
9326122f3e6SDimitry Andric   // If C++ exceptions are enabled, this is true.
933dff0c46cSDimitry Andric   if (LangOpts.CXXExceptions) return true;
9346122f3e6SDimitry Andric 
9356122f3e6SDimitry Andric   // If ObjC exceptions are enabled, this depends on the ABI.
936dff0c46cSDimitry Andric   if (LangOpts.ObjCExceptions) {
9377ae0e2c9SDimitry Andric     return LangOpts.ObjCRuntime.hasUnwindExceptions();
9386122f3e6SDimitry Andric   }
9396122f3e6SDimitry Andric 
9406122f3e6SDimitry Andric   return true;
9416122f3e6SDimitry Andric }
9426122f3e6SDimitry Andric 
943f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
944f22ef01cSRoman Divacky                                                            llvm::Function *F) {
945f785676fSDimitry Andric   llvm::AttrBuilder B;
946f785676fSDimitry Andric 
947bd5abe19SDimitry Andric   if (CodeGenOpts.UnwindTables)
948f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::UWTable);
949bd5abe19SDimitry Andric 
950dff0c46cSDimitry Andric   if (!hasUnwindExceptions(LangOpts))
951f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoUnwind);
952f22ef01cSRoman Divacky 
9530623d748SDimitry Andric   if (LangOpts.getStackProtector() == LangOptions::SSPOn)
9540623d748SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtect);
9550623d748SDimitry Andric   else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
9560623d748SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtectStrong);
9570623d748SDimitry Andric   else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
9580623d748SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtectReq);
9590623d748SDimitry Andric 
9600623d748SDimitry Andric   if (!D) {
96144290647SDimitry Andric     // If we don't have a declaration to control inlining, the function isn't
96244290647SDimitry Andric     // explicitly marked as alwaysinline for semantic reasons, and inlining is
96344290647SDimitry Andric     // disabled, mark the function as noinline.
96444290647SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
96544290647SDimitry Andric         CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
96644290647SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
96744290647SDimitry Andric 
968f37b6182SDimitry Andric     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
9690623d748SDimitry Andric     return;
9700623d748SDimitry Andric   }
9710623d748SDimitry Andric 
972302affcbSDimitry Andric   // Track whether we need to add the optnone LLVM attribute,
973302affcbSDimitry Andric   // starting with the default for this optimization level.
974302affcbSDimitry Andric   bool ShouldAddOptNone =
975302affcbSDimitry Andric       !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
976302affcbSDimitry Andric   // We can't add optnone in the following cases, it won't pass the verifier.
977302affcbSDimitry Andric   ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
978302affcbSDimitry Andric   ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
979302affcbSDimitry Andric   ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
980302affcbSDimitry Andric 
981302affcbSDimitry Andric   if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) {
98244290647SDimitry Andric     B.addAttribute(llvm::Attribute::OptimizeNone);
98344290647SDimitry Andric 
98444290647SDimitry Andric     // OptimizeNone implies noinline; we should not be inlining such functions.
98544290647SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
98644290647SDimitry Andric     assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
98744290647SDimitry Andric            "OptimizeNone and AlwaysInline on same function!");
98844290647SDimitry Andric 
98944290647SDimitry Andric     // We still need to handle naked functions even though optnone subsumes
99044290647SDimitry Andric     // much of their semantics.
99144290647SDimitry Andric     if (D->hasAttr<NakedAttr>())
99244290647SDimitry Andric       B.addAttribute(llvm::Attribute::Naked);
99344290647SDimitry Andric 
99444290647SDimitry Andric     // OptimizeNone wins over OptimizeForSize and MinSize.
99544290647SDimitry Andric     F->removeFnAttr(llvm::Attribute::OptimizeForSize);
99644290647SDimitry Andric     F->removeFnAttr(llvm::Attribute::MinSize);
99744290647SDimitry Andric   } else if (D->hasAttr<NakedAttr>()) {
9986122f3e6SDimitry Andric     // Naked implies noinline: we should not be inlining such functions.
999f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::Naked);
1000f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
100159d1ed5bSDimitry Andric   } else if (D->hasAttr<NoDuplicateAttr>()) {
100259d1ed5bSDimitry Andric     B.addAttribute(llvm::Attribute::NoDuplicate);
1003f785676fSDimitry Andric   } else if (D->hasAttr<NoInlineAttr>()) {
1004f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
100559d1ed5bSDimitry Andric   } else if (D->hasAttr<AlwaysInlineAttr>() &&
100644290647SDimitry Andric              !F->hasFnAttribute(llvm::Attribute::NoInline)) {
1007f785676fSDimitry Andric     // (noinline wins over always_inline, and we can't specify both in IR)
1008f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::AlwaysInline);
100944290647SDimitry Andric   } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
101044290647SDimitry Andric     // If we're not inlining, then force everything that isn't always_inline to
101144290647SDimitry Andric     // carry an explicit noinline attribute.
101244290647SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
101344290647SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
101444290647SDimitry Andric   } else {
101544290647SDimitry Andric     // Otherwise, propagate the inline hint attribute and potentially use its
101644290647SDimitry Andric     // absence to mark things as noinline.
101744290647SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
101844290647SDimitry Andric       if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
101944290647SDimitry Andric             return Redecl->isInlineSpecified();
102044290647SDimitry Andric           })) {
102144290647SDimitry Andric         B.addAttribute(llvm::Attribute::InlineHint);
102244290647SDimitry Andric       } else if (CodeGenOpts.getInlining() ==
102344290647SDimitry Andric                      CodeGenOptions::OnlyHintInlining &&
102444290647SDimitry Andric                  !FD->isInlined() &&
102544290647SDimitry Andric                  !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
102644290647SDimitry Andric         B.addAttribute(llvm::Attribute::NoInline);
102744290647SDimitry Andric       }
102844290647SDimitry Andric     }
10296122f3e6SDimitry Andric   }
10302754fe60SDimitry Andric 
103144290647SDimitry Andric   // Add other optimization related attributes if we are optimizing this
103244290647SDimitry Andric   // function.
103344290647SDimitry Andric   if (!D->hasAttr<OptimizeNoneAttr>()) {
1034f785676fSDimitry Andric     if (D->hasAttr<ColdAttr>()) {
1035302affcbSDimitry Andric       if (!ShouldAddOptNone)
1036f785676fSDimitry Andric         B.addAttribute(llvm::Attribute::OptimizeForSize);
1037f785676fSDimitry Andric       B.addAttribute(llvm::Attribute::Cold);
1038f785676fSDimitry Andric     }
10393861d79fSDimitry Andric 
10403861d79fSDimitry Andric     if (D->hasAttr<MinSizeAttr>())
1041f785676fSDimitry Andric       B.addAttribute(llvm::Attribute::MinSize);
104244290647SDimitry Andric   }
1043f22ef01cSRoman Divacky 
1044f37b6182SDimitry Andric   F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1045f785676fSDimitry Andric 
1046e580952dSDimitry Andric   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
1047e580952dSDimitry Andric   if (alignment)
1048e580952dSDimitry Andric     F->setAlignment(alignment);
1049e580952dSDimitry Andric 
10500623d748SDimitry Andric   // Some C++ ABIs require 2-byte alignment for member functions, in order to
10510623d748SDimitry Andric   // reserve a bit for differentiating between virtual and non-virtual member
10520623d748SDimitry Andric   // functions. If the current target's C++ ABI requires this and this is a
10530623d748SDimitry Andric   // member function, set its alignment accordingly.
10540623d748SDimitry Andric   if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
1055f22ef01cSRoman Divacky     if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1056f22ef01cSRoman Divacky       F->setAlignment(2);
1057f22ef01cSRoman Divacky   }
105844290647SDimitry Andric 
105944290647SDimitry Andric   // In the cross-dso CFI mode, we want !type attributes on definitions only.
106044290647SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
106144290647SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D))
106244290647SDimitry Andric       CreateFunctionTypeMetadata(FD, F);
10630623d748SDimitry Andric }
1064f22ef01cSRoman Divacky 
1065f22ef01cSRoman Divacky void CodeGenModule::SetCommonAttributes(const Decl *D,
1066f22ef01cSRoman Divacky                                         llvm::GlobalValue *GV) {
10670623d748SDimitry Andric   if (const auto *ND = dyn_cast_or_null<NamedDecl>(D))
10689a199699SDimitry Andric     setGlobalVisibility(GV, ND, ForDefinition);
10692754fe60SDimitry Andric   else
10702754fe60SDimitry Andric     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1071f22ef01cSRoman Divacky 
10720623d748SDimitry Andric   if (D && D->hasAttr<UsedAttr>())
107359d1ed5bSDimitry Andric     addUsedGlobal(GV);
107459d1ed5bSDimitry Andric }
107559d1ed5bSDimitry Andric 
107639d628a0SDimitry Andric void CodeGenModule::setAliasAttributes(const Decl *D,
107739d628a0SDimitry Andric                                        llvm::GlobalValue *GV) {
107839d628a0SDimitry Andric   SetCommonAttributes(D, GV);
107939d628a0SDimitry Andric 
108039d628a0SDimitry Andric   // Process the dllexport attribute based on whether the original definition
108139d628a0SDimitry Andric   // (not necessarily the aliasee) was exported.
108239d628a0SDimitry Andric   if (D->hasAttr<DLLExportAttr>())
108339d628a0SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
108439d628a0SDimitry Andric }
108539d628a0SDimitry Andric 
108659d1ed5bSDimitry Andric void CodeGenModule::setNonAliasAttributes(const Decl *D,
108759d1ed5bSDimitry Andric                                           llvm::GlobalObject *GO) {
108859d1ed5bSDimitry Andric   SetCommonAttributes(D, GO);
1089f22ef01cSRoman Divacky 
1090db17bf38SDimitry Andric   if (D) {
1091db17bf38SDimitry Andric     if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
1092db17bf38SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
1093db17bf38SDimitry Andric         GV->addAttribute("bss-section", SA->getName());
1094db17bf38SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
1095db17bf38SDimitry Andric         GV->addAttribute("data-section", SA->getName());
1096db17bf38SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
1097db17bf38SDimitry Andric         GV->addAttribute("rodata-section", SA->getName());
1098db17bf38SDimitry Andric     }
1099db17bf38SDimitry Andric 
1100db17bf38SDimitry Andric     if (auto *F = dyn_cast<llvm::Function>(GO)) {
1101db17bf38SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
1102db17bf38SDimitry Andric        if (!D->getAttr<SectionAttr>())
1103db17bf38SDimitry Andric          F->addFnAttr("implicit-section-name", SA->getName());
1104db17bf38SDimitry Andric     }
1105db17bf38SDimitry Andric 
1106f22ef01cSRoman Divacky     if (const SectionAttr *SA = D->getAttr<SectionAttr>())
110759d1ed5bSDimitry Andric       GO->setSection(SA->getName());
1108db17bf38SDimitry Andric   }
1109f22ef01cSRoman Divacky 
11109a199699SDimitry Andric   getTargetCodeGenInfo().setTargetAttributes(D, GO, *this, ForDefinition);
1111f22ef01cSRoman Divacky }
1112f22ef01cSRoman Divacky 
1113f22ef01cSRoman Divacky void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
1114f22ef01cSRoman Divacky                                                   llvm::Function *F,
1115f22ef01cSRoman Divacky                                                   const CGFunctionInfo &FI) {
1116f22ef01cSRoman Divacky   SetLLVMFunctionAttributes(D, FI, F);
1117f22ef01cSRoman Divacky   SetLLVMFunctionAttributesForDefinition(D, F);
1118f22ef01cSRoman Divacky 
1119f22ef01cSRoman Divacky   F->setLinkage(llvm::Function::InternalLinkage);
1120f22ef01cSRoman Divacky 
112159d1ed5bSDimitry Andric   setNonAliasAttributes(D, F);
112259d1ed5bSDimitry Andric }
112359d1ed5bSDimitry Andric 
11249a199699SDimitry Andric static void setLinkageForGV(llvm::GlobalValue *GV,
112559d1ed5bSDimitry Andric                             const NamedDecl *ND) {
112659d1ed5bSDimitry Andric   // Set linkage and visibility in case we never see a definition.
112759d1ed5bSDimitry Andric   LinkageInfo LV = ND->getLinkageAndVisibility();
1128c4394386SDimitry Andric   if (!isExternallyVisible(LV.getLinkage())) {
112959d1ed5bSDimitry Andric     // Don't set internal linkage on declarations.
113059d1ed5bSDimitry Andric   } else {
113159d1ed5bSDimitry Andric     if (ND->hasAttr<DLLImportAttr>()) {
113259d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
113359d1ed5bSDimitry Andric       GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
113459d1ed5bSDimitry Andric     } else if (ND->hasAttr<DLLExportAttr>()) {
113559d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
113659d1ed5bSDimitry Andric     } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
113759d1ed5bSDimitry Andric       // "extern_weak" is overloaded in LLVM; we probably should have
113859d1ed5bSDimitry Andric       // separate linkage types for this.
113959d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
114059d1ed5bSDimitry Andric     }
114159d1ed5bSDimitry Andric   }
1142f22ef01cSRoman Divacky }
1143f22ef01cSRoman Divacky 
1144e7145dcbSDimitry Andric void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD,
11450623d748SDimitry Andric                                                llvm::Function *F) {
11460623d748SDimitry Andric   // Only if we are checking indirect calls.
11470623d748SDimitry Andric   if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
11480623d748SDimitry Andric     return;
11490623d748SDimitry Andric 
11500623d748SDimitry Andric   // Non-static class methods are handled via vtable pointer checks elsewhere.
11510623d748SDimitry Andric   if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
11520623d748SDimitry Andric     return;
11530623d748SDimitry Andric 
11540623d748SDimitry Andric   // Additionally, if building with cross-DSO support...
11550623d748SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
11560623d748SDimitry Andric     // Skip available_externally functions. They won't be codegen'ed in the
11570623d748SDimitry Andric     // current module anyway.
11580623d748SDimitry Andric     if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
11590623d748SDimitry Andric       return;
11600623d748SDimitry Andric   }
11610623d748SDimitry Andric 
11620623d748SDimitry Andric   llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
1163e7145dcbSDimitry Andric   F->addTypeMetadata(0, MD);
11649a199699SDimitry Andric   F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
11650623d748SDimitry Andric 
11660623d748SDimitry Andric   // Emit a hash-based bit set entry for cross-DSO calls.
1167e7145dcbSDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
1168e7145dcbSDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1169e7145dcbSDimitry Andric       F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
11700623d748SDimitry Andric }
11710623d748SDimitry Andric 
117239d628a0SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
117339d628a0SDimitry Andric                                           bool IsIncompleteFunction,
11749a199699SDimitry Andric                                           bool IsThunk,
11759a199699SDimitry Andric                                           ForDefinition_t IsForDefinition) {
11769a199699SDimitry Andric 
117733956c43SDimitry Andric   if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
11783b0f4066SDimitry Andric     // If this is an intrinsic function, set the function's attributes
11793b0f4066SDimitry Andric     // to the intrinsic's attributes.
118033956c43SDimitry Andric     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
11813b0f4066SDimitry Andric     return;
11823b0f4066SDimitry Andric   }
11833b0f4066SDimitry Andric 
118459d1ed5bSDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
1185f22ef01cSRoman Divacky 
11869a199699SDimitry Andric   if (!IsIncompleteFunction) {
1187dff0c46cSDimitry Andric     SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
11889a199699SDimitry Andric     // Setup target-specific attributes.
11899a199699SDimitry Andric     if (!IsForDefinition)
11909a199699SDimitry Andric       getTargetCodeGenInfo().setTargetAttributes(FD, F, *this,
11919a199699SDimitry Andric                                                  NotForDefinition);
11929a199699SDimitry Andric   }
1193f22ef01cSRoman Divacky 
119459d1ed5bSDimitry Andric   // Add the Returned attribute for "this", except for iOS 5 and earlier
119559d1ed5bSDimitry Andric   // where substantial code, including the libstdc++ dylib, was compiled with
119659d1ed5bSDimitry Andric   // GCC and does not actually return "this".
119739d628a0SDimitry Andric   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
119844290647SDimitry Andric       !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
1199f785676fSDimitry Andric     assert(!F->arg_empty() &&
1200f785676fSDimitry Andric            F->arg_begin()->getType()
1201f785676fSDimitry Andric              ->canLosslesslyBitCastTo(F->getReturnType()) &&
1202f785676fSDimitry Andric            "unexpected this return");
1203f785676fSDimitry Andric     F->addAttribute(1, llvm::Attribute::Returned);
1204f785676fSDimitry Andric   }
1205f785676fSDimitry Andric 
1206f22ef01cSRoman Divacky   // Only a few attributes are set on declarations; these may later be
1207f22ef01cSRoman Divacky   // overridden by a definition.
1208f22ef01cSRoman Divacky 
12099a199699SDimitry Andric   setLinkageForGV(F, FD);
12109a199699SDimitry Andric   setGlobalVisibility(F, FD, NotForDefinition);
12112754fe60SDimitry Andric 
1212db17bf38SDimitry Andric   if (FD->getAttr<PragmaClangTextSectionAttr>()) {
1213db17bf38SDimitry Andric     F->addFnAttr("implicit-section-name");
1214db17bf38SDimitry Andric   }
1215db17bf38SDimitry Andric 
1216f22ef01cSRoman Divacky   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
1217f22ef01cSRoman Divacky     F->setSection(SA->getName());
1218f785676fSDimitry Andric 
1219e7145dcbSDimitry Andric   if (FD->isReplaceableGlobalAllocationFunction()) {
1220f785676fSDimitry Andric     // A replaceable global allocation function does not act like a builtin by
1221f785676fSDimitry Andric     // default, only if it is invoked by a new-expression or delete-expression.
122220e90f04SDimitry Andric     F->addAttribute(llvm::AttributeList::FunctionIndex,
1223f785676fSDimitry Andric                     llvm::Attribute::NoBuiltin);
12240623d748SDimitry Andric 
1225e7145dcbSDimitry Andric     // A sane operator new returns a non-aliasing pointer.
1226e7145dcbSDimitry Andric     // FIXME: Also add NonNull attribute to the return value
1227e7145dcbSDimitry Andric     // for the non-nothrow forms?
1228e7145dcbSDimitry Andric     auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1229e7145dcbSDimitry Andric     if (getCodeGenOpts().AssumeSaneOperatorNew &&
1230e7145dcbSDimitry Andric         (Kind == OO_New || Kind == OO_Array_New))
123120e90f04SDimitry Andric       F->addAttribute(llvm::AttributeList::ReturnIndex,
1232e7145dcbSDimitry Andric                       llvm::Attribute::NoAlias);
1233e7145dcbSDimitry Andric   }
1234e7145dcbSDimitry Andric 
1235e7145dcbSDimitry Andric   if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1236e7145dcbSDimitry Andric     F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1237e7145dcbSDimitry Andric   else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1238e7145dcbSDimitry Andric     if (MD->isVirtual())
1239e7145dcbSDimitry Andric       F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1240e7145dcbSDimitry Andric 
124144290647SDimitry Andric   // Don't emit entries for function declarations in the cross-DSO mode. This
124244290647SDimitry Andric   // is handled with better precision by the receiving DSO.
124344290647SDimitry Andric   if (!CodeGenOpts.SanitizeCfiCrossDso)
1244e7145dcbSDimitry Andric     CreateFunctionTypeMetadata(FD, F);
12459a199699SDimitry Andric 
12469a199699SDimitry Andric   if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
12479a199699SDimitry Andric     getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
1248f22ef01cSRoman Divacky }
1249f22ef01cSRoman Divacky 
125059d1ed5bSDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
1251f22ef01cSRoman Divacky   assert(!GV->isDeclaration() &&
1252f22ef01cSRoman Divacky          "Only globals with definition can force usage.");
125397bc6c73SDimitry Andric   LLVMUsed.emplace_back(GV);
1254f22ef01cSRoman Divacky }
1255f22ef01cSRoman Divacky 
125659d1ed5bSDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
125759d1ed5bSDimitry Andric   assert(!GV->isDeclaration() &&
125859d1ed5bSDimitry Andric          "Only globals with definition can force usage.");
125997bc6c73SDimitry Andric   LLVMCompilerUsed.emplace_back(GV);
126059d1ed5bSDimitry Andric }
126159d1ed5bSDimitry Andric 
126259d1ed5bSDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name,
1263f37b6182SDimitry Andric                      std::vector<llvm::WeakTrackingVH> &List) {
1264f22ef01cSRoman Divacky   // Don't create llvm.used if there is no need.
126559d1ed5bSDimitry Andric   if (List.empty())
1266f22ef01cSRoman Divacky     return;
1267f22ef01cSRoman Divacky 
126859d1ed5bSDimitry Andric   // Convert List to what ConstantArray needs.
1269dff0c46cSDimitry Andric   SmallVector<llvm::Constant*, 8> UsedArray;
127059d1ed5bSDimitry Andric   UsedArray.resize(List.size());
127159d1ed5bSDimitry Andric   for (unsigned i = 0, e = List.size(); i != e; ++i) {
1272f22ef01cSRoman Divacky     UsedArray[i] =
127344f7b0dcSDimitry Andric         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
127444f7b0dcSDimitry Andric             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
1275f22ef01cSRoman Divacky   }
1276f22ef01cSRoman Divacky 
1277f22ef01cSRoman Divacky   if (UsedArray.empty())
1278f22ef01cSRoman Divacky     return;
127959d1ed5bSDimitry Andric   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
1280f22ef01cSRoman Divacky 
128159d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
128259d1ed5bSDimitry Andric       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
128359d1ed5bSDimitry Andric       llvm::ConstantArray::get(ATy, UsedArray), Name);
1284f22ef01cSRoman Divacky 
1285f22ef01cSRoman Divacky   GV->setSection("llvm.metadata");
1286f22ef01cSRoman Divacky }
1287f22ef01cSRoman Divacky 
128859d1ed5bSDimitry Andric void CodeGenModule::emitLLVMUsed() {
128959d1ed5bSDimitry Andric   emitUsed(*this, "llvm.used", LLVMUsed);
129059d1ed5bSDimitry Andric   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
129159d1ed5bSDimitry Andric }
129259d1ed5bSDimitry Andric 
1293f785676fSDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
129439d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
1295f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1296f785676fSDimitry Andric }
1297f785676fSDimitry Andric 
1298f785676fSDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1299f785676fSDimitry Andric   llvm::SmallString<32> Opt;
1300f785676fSDimitry Andric   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
130139d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1302f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1303f785676fSDimitry Andric }
1304f785676fSDimitry Andric 
1305f785676fSDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) {
1306f785676fSDimitry Andric   llvm::SmallString<24> Opt;
1307f785676fSDimitry Andric   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
130839d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1309f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1310f785676fSDimitry Andric }
1311f785676fSDimitry Andric 
1312139f7f9bSDimitry Andric /// \brief Add link options implied by the given module, including modules
1313139f7f9bSDimitry Andric /// it depends on, using a postorder walk.
131439d628a0SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
131524d58133SDimitry Andric                                     SmallVectorImpl<llvm::MDNode *> &Metadata,
1316139f7f9bSDimitry Andric                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
1317139f7f9bSDimitry Andric   // Import this module's parent.
131839d628a0SDimitry Andric   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
1319f785676fSDimitry Andric     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
1320139f7f9bSDimitry Andric   }
1321139f7f9bSDimitry Andric 
1322139f7f9bSDimitry Andric   // Import this module's dependencies.
1323139f7f9bSDimitry Andric   for (unsigned I = Mod->Imports.size(); I > 0; --I) {
132439d628a0SDimitry Andric     if (Visited.insert(Mod->Imports[I - 1]).second)
1325f785676fSDimitry Andric       addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
1326139f7f9bSDimitry Andric   }
1327139f7f9bSDimitry Andric 
1328139f7f9bSDimitry Andric   // Add linker options to link against the libraries/frameworks
1329139f7f9bSDimitry Andric   // described by this module.
1330f785676fSDimitry Andric   llvm::LLVMContext &Context = CGM.getLLVMContext();
1331139f7f9bSDimitry Andric   for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
1332f785676fSDimitry Andric     // Link against a framework.  Frameworks are currently Darwin only, so we
1333f785676fSDimitry Andric     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
1334139f7f9bSDimitry Andric     if (Mod->LinkLibraries[I-1].IsFramework) {
133539d628a0SDimitry Andric       llvm::Metadata *Args[2] = {
1336139f7f9bSDimitry Andric           llvm::MDString::get(Context, "-framework"),
133739d628a0SDimitry Andric           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
1338139f7f9bSDimitry Andric 
1339139f7f9bSDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, Args));
1340139f7f9bSDimitry Andric       continue;
1341139f7f9bSDimitry Andric     }
1342139f7f9bSDimitry Andric 
1343139f7f9bSDimitry Andric     // Link against a library.
1344f785676fSDimitry Andric     llvm::SmallString<24> Opt;
1345f785676fSDimitry Andric     CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1346f785676fSDimitry Andric       Mod->LinkLibraries[I-1].Library, Opt);
134739d628a0SDimitry Andric     auto *OptString = llvm::MDString::get(Context, Opt);
1348139f7f9bSDimitry Andric     Metadata.push_back(llvm::MDNode::get(Context, OptString));
1349139f7f9bSDimitry Andric   }
1350139f7f9bSDimitry Andric }
1351139f7f9bSDimitry Andric 
1352139f7f9bSDimitry Andric void CodeGenModule::EmitModuleLinkOptions() {
1353139f7f9bSDimitry Andric   // Collect the set of all of the modules we want to visit to emit link
1354139f7f9bSDimitry Andric   // options, which is essentially the imported modules and all of their
1355139f7f9bSDimitry Andric   // non-explicit child modules.
1356139f7f9bSDimitry Andric   llvm::SetVector<clang::Module *> LinkModules;
1357139f7f9bSDimitry Andric   llvm::SmallPtrSet<clang::Module *, 16> Visited;
1358139f7f9bSDimitry Andric   SmallVector<clang::Module *, 16> Stack;
1359139f7f9bSDimitry Andric 
1360139f7f9bSDimitry Andric   // Seed the stack with imported modules.
1361f1a29dd3SDimitry Andric   for (Module *M : ImportedModules) {
1362f1a29dd3SDimitry Andric     // Do not add any link flags when an implementation TU of a module imports
1363f1a29dd3SDimitry Andric     // a header of that same module.
1364f1a29dd3SDimitry Andric     if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
1365f1a29dd3SDimitry Andric         !getLangOpts().isCompilingModule())
1366f1a29dd3SDimitry Andric       continue;
13678f0fd8f6SDimitry Andric     if (Visited.insert(M).second)
13688f0fd8f6SDimitry Andric       Stack.push_back(M);
1369f1a29dd3SDimitry Andric   }
1370139f7f9bSDimitry Andric 
1371139f7f9bSDimitry Andric   // Find all of the modules to import, making a little effort to prune
1372139f7f9bSDimitry Andric   // non-leaf modules.
1373139f7f9bSDimitry Andric   while (!Stack.empty()) {
1374f785676fSDimitry Andric     clang::Module *Mod = Stack.pop_back_val();
1375139f7f9bSDimitry Andric 
1376139f7f9bSDimitry Andric     bool AnyChildren = false;
1377139f7f9bSDimitry Andric 
1378139f7f9bSDimitry Andric     // Visit the submodules of this module.
1379139f7f9bSDimitry Andric     for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1380139f7f9bSDimitry Andric                                         SubEnd = Mod->submodule_end();
1381139f7f9bSDimitry Andric          Sub != SubEnd; ++Sub) {
1382139f7f9bSDimitry Andric       // Skip explicit children; they need to be explicitly imported to be
1383139f7f9bSDimitry Andric       // linked against.
1384139f7f9bSDimitry Andric       if ((*Sub)->IsExplicit)
1385139f7f9bSDimitry Andric         continue;
1386139f7f9bSDimitry Andric 
138739d628a0SDimitry Andric       if (Visited.insert(*Sub).second) {
1388139f7f9bSDimitry Andric         Stack.push_back(*Sub);
1389139f7f9bSDimitry Andric         AnyChildren = true;
1390139f7f9bSDimitry Andric       }
1391139f7f9bSDimitry Andric     }
1392139f7f9bSDimitry Andric 
1393139f7f9bSDimitry Andric     // We didn't find any children, so add this module to the list of
1394139f7f9bSDimitry Andric     // modules to link against.
1395139f7f9bSDimitry Andric     if (!AnyChildren) {
1396139f7f9bSDimitry Andric       LinkModules.insert(Mod);
1397139f7f9bSDimitry Andric     }
1398139f7f9bSDimitry Andric   }
1399139f7f9bSDimitry Andric 
1400139f7f9bSDimitry Andric   // Add link options for all of the imported modules in reverse topological
1401f785676fSDimitry Andric   // order.  We don't do anything to try to order import link flags with respect
1402f785676fSDimitry Andric   // to linker options inserted by things like #pragma comment().
140324d58133SDimitry Andric   SmallVector<llvm::MDNode *, 16> MetadataArgs;
1404139f7f9bSDimitry Andric   Visited.clear();
14058f0fd8f6SDimitry Andric   for (Module *M : LinkModules)
14068f0fd8f6SDimitry Andric     if (Visited.insert(M).second)
14078f0fd8f6SDimitry Andric       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
1408139f7f9bSDimitry Andric   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1409f785676fSDimitry Andric   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1410139f7f9bSDimitry Andric 
1411139f7f9bSDimitry Andric   // Add the linker options metadata flag.
141224d58133SDimitry Andric   auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
141324d58133SDimitry Andric   for (auto *MD : LinkerOptionsMetadata)
141424d58133SDimitry Andric     NMD->addOperand(MD);
1415139f7f9bSDimitry Andric }
1416139f7f9bSDimitry Andric 
1417f22ef01cSRoman Divacky void CodeGenModule::EmitDeferred() {
1418f22ef01cSRoman Divacky   // Emit code for any potentially referenced deferred decls.  Since a
1419f22ef01cSRoman Divacky   // previously unused static decl may become used during the generation of code
1420f22ef01cSRoman Divacky   // for a static function, iterate until no changes are made.
1421f22ef01cSRoman Divacky 
1422f22ef01cSRoman Divacky   if (!DeferredVTables.empty()) {
1423139f7f9bSDimitry Andric     EmitDeferredVTables();
1424139f7f9bSDimitry Andric 
1425e7145dcbSDimitry Andric     // Emitting a vtable doesn't directly cause more vtables to
1426139f7f9bSDimitry Andric     // become deferred, although it can cause functions to be
1427e7145dcbSDimitry Andric     // emitted that then need those vtables.
1428139f7f9bSDimitry Andric     assert(DeferredVTables.empty());
1429f22ef01cSRoman Divacky   }
1430f22ef01cSRoman Divacky 
1431e7145dcbSDimitry Andric   // Stop if we're out of both deferred vtables and deferred declarations.
143233956c43SDimitry Andric   if (DeferredDeclsToEmit.empty())
143333956c43SDimitry Andric     return;
1434139f7f9bSDimitry Andric 
143533956c43SDimitry Andric   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
143633956c43SDimitry Andric   // work, it will not interfere with this.
1437f37b6182SDimitry Andric   std::vector<GlobalDecl> CurDeclsToEmit;
143833956c43SDimitry Andric   CurDeclsToEmit.swap(DeferredDeclsToEmit);
143933956c43SDimitry Andric 
1440f37b6182SDimitry Andric   for (GlobalDecl &D : CurDeclsToEmit) {
14410623d748SDimitry Andric     // We should call GetAddrOfGlobal with IsForDefinition set to true in order
14420623d748SDimitry Andric     // to get GlobalValue with exactly the type we need, not something that
14430623d748SDimitry Andric     // might had been created for another decl with the same mangled name but
14440623d748SDimitry Andric     // different type.
1445e7145dcbSDimitry Andric     llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
144644290647SDimitry Andric         GetAddrOfGlobal(D, ForDefinition));
1447e7145dcbSDimitry Andric 
1448e7145dcbSDimitry Andric     // In case of different address spaces, we may still get a cast, even with
1449e7145dcbSDimitry Andric     // IsForDefinition equal to true. Query mangled names table to get
1450e7145dcbSDimitry Andric     // GlobalValue.
145139d628a0SDimitry Andric     if (!GV)
145239d628a0SDimitry Andric       GV = GetGlobalValue(getMangledName(D));
145339d628a0SDimitry Andric 
1454e7145dcbSDimitry Andric     // Make sure GetGlobalValue returned non-null.
1455e7145dcbSDimitry Andric     assert(GV);
1456e7145dcbSDimitry Andric 
1457f22ef01cSRoman Divacky     // Check to see if we've already emitted this.  This is necessary
1458f22ef01cSRoman Divacky     // for a couple of reasons: first, decls can end up in the
1459f22ef01cSRoman Divacky     // deferred-decls queue multiple times, and second, decls can end
1460f22ef01cSRoman Divacky     // up with definitions in unusual ways (e.g. by an extern inline
1461f22ef01cSRoman Divacky     // function acquiring a strong function redefinition).  Just
1462f22ef01cSRoman Divacky     // ignore these cases.
1463e7145dcbSDimitry Andric     if (!GV->isDeclaration())
1464f22ef01cSRoman Divacky       continue;
1465f22ef01cSRoman Divacky 
1466f22ef01cSRoman Divacky     // Otherwise, emit the definition and move on to the next one.
146759d1ed5bSDimitry Andric     EmitGlobalDefinition(D, GV);
146833956c43SDimitry Andric 
146933956c43SDimitry Andric     // If we found out that we need to emit more decls, do that recursively.
147033956c43SDimitry Andric     // This has the advantage that the decls are emitted in a DFS and related
147133956c43SDimitry Andric     // ones are close together, which is convenient for testing.
147233956c43SDimitry Andric     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
147333956c43SDimitry Andric       EmitDeferred();
147433956c43SDimitry Andric       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
147533956c43SDimitry Andric     }
1476f22ef01cSRoman Divacky   }
1477f22ef01cSRoman Divacky }
1478f22ef01cSRoman Divacky 
1479f9448bf3SDimitry Andric void CodeGenModule::EmitVTablesOpportunistically() {
1480f9448bf3SDimitry Andric   // Try to emit external vtables as available_externally if they have emitted
1481f9448bf3SDimitry Andric   // all inlined virtual functions.  It runs after EmitDeferred() and therefore
1482f9448bf3SDimitry Andric   // is not allowed to create new references to things that need to be emitted
1483f9448bf3SDimitry Andric   // lazily. Note that it also uses fact that we eagerly emitting RTTI.
1484f9448bf3SDimitry Andric 
1485f9448bf3SDimitry Andric   assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
1486f9448bf3SDimitry Andric          && "Only emit opportunistic vtables with optimizations");
1487f9448bf3SDimitry Andric 
1488f9448bf3SDimitry Andric   for (const CXXRecordDecl *RD : OpportunisticVTables) {
1489f9448bf3SDimitry Andric     assert(getVTables().isVTableExternal(RD) &&
1490f9448bf3SDimitry Andric            "This queue should only contain external vtables");
1491f9448bf3SDimitry Andric     if (getCXXABI().canSpeculativelyEmitVTable(RD))
1492f9448bf3SDimitry Andric       VTables.GenerateClassData(RD);
1493f9448bf3SDimitry Andric   }
1494f9448bf3SDimitry Andric   OpportunisticVTables.clear();
1495f9448bf3SDimitry Andric }
1496f9448bf3SDimitry Andric 
14976122f3e6SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() {
14986122f3e6SDimitry Andric   if (Annotations.empty())
14996122f3e6SDimitry Andric     return;
15006122f3e6SDimitry Andric 
15016122f3e6SDimitry Andric   // Create a new global variable for the ConstantStruct in the Module.
15026122f3e6SDimitry Andric   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
15036122f3e6SDimitry Andric     Annotations[0]->getType(), Annotations.size()), Annotations);
150459d1ed5bSDimitry Andric   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
150559d1ed5bSDimitry Andric                                       llvm::GlobalValue::AppendingLinkage,
150659d1ed5bSDimitry Andric                                       Array, "llvm.global.annotations");
15076122f3e6SDimitry Andric   gv->setSection(AnnotationSection);
15086122f3e6SDimitry Andric }
15096122f3e6SDimitry Andric 
1510139f7f9bSDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1511f785676fSDimitry Andric   llvm::Constant *&AStr = AnnotationStrings[Str];
1512f785676fSDimitry Andric   if (AStr)
1513f785676fSDimitry Andric     return AStr;
15146122f3e6SDimitry Andric 
15156122f3e6SDimitry Andric   // Not found yet, create a new global.
1516dff0c46cSDimitry Andric   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
151759d1ed5bSDimitry Andric   auto *gv =
151859d1ed5bSDimitry Andric       new llvm::GlobalVariable(getModule(), s->getType(), true,
151959d1ed5bSDimitry Andric                                llvm::GlobalValue::PrivateLinkage, s, ".str");
15206122f3e6SDimitry Andric   gv->setSection(AnnotationSection);
1521e7145dcbSDimitry Andric   gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1522f785676fSDimitry Andric   AStr = gv;
15236122f3e6SDimitry Andric   return gv;
15246122f3e6SDimitry Andric }
15256122f3e6SDimitry Andric 
15266122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
15276122f3e6SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
15286122f3e6SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
15296122f3e6SDimitry Andric   if (PLoc.isValid())
15306122f3e6SDimitry Andric     return EmitAnnotationString(PLoc.getFilename());
15316122f3e6SDimitry Andric   return EmitAnnotationString(SM.getBufferName(Loc));
15326122f3e6SDimitry Andric }
15336122f3e6SDimitry Andric 
15346122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
15356122f3e6SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
15366122f3e6SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(L);
15376122f3e6SDimitry Andric   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
15386122f3e6SDimitry Andric     SM.getExpansionLineNumber(L);
15396122f3e6SDimitry Andric   return llvm::ConstantInt::get(Int32Ty, LineNo);
15406122f3e6SDimitry Andric }
15416122f3e6SDimitry Andric 
1542f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1543f22ef01cSRoman Divacky                                                 const AnnotateAttr *AA,
15446122f3e6SDimitry Andric                                                 SourceLocation L) {
15456122f3e6SDimitry Andric   // Get the globals for file name, annotation, and the line number.
15466122f3e6SDimitry Andric   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
15476122f3e6SDimitry Andric                  *UnitGV = EmitAnnotationUnit(L),
15486122f3e6SDimitry Andric                  *LineNoCst = EmitAnnotationLineNo(L);
1549f22ef01cSRoman Divacky 
1550f22ef01cSRoman Divacky   // Create the ConstantStruct for the global annotation.
1551f22ef01cSRoman Divacky   llvm::Constant *Fields[4] = {
15526122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
15536122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
15546122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
15556122f3e6SDimitry Andric     LineNoCst
1556f22ef01cSRoman Divacky   };
155717a519f9SDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
1558f22ef01cSRoman Divacky }
1559f22ef01cSRoman Divacky 
15606122f3e6SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
15616122f3e6SDimitry Andric                                          llvm::GlobalValue *GV) {
15626122f3e6SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
15636122f3e6SDimitry Andric   // Get the struct elements for these annotations.
156459d1ed5bSDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>())
156559d1ed5bSDimitry Andric     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
15666122f3e6SDimitry Andric }
15676122f3e6SDimitry Andric 
15689a199699SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind,
15699a199699SDimitry Andric                                            llvm::Function *Fn,
157039d628a0SDimitry Andric                                            SourceLocation Loc) const {
157139d628a0SDimitry Andric   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
157239d628a0SDimitry Andric   // Blacklist by function name.
15739a199699SDimitry Andric   if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
157439d628a0SDimitry Andric     return true;
157539d628a0SDimitry Andric   // Blacklist by location.
15760623d748SDimitry Andric   if (Loc.isValid())
15779a199699SDimitry Andric     return SanitizerBL.isBlacklistedLocation(Kind, Loc);
157839d628a0SDimitry Andric   // If location is unknown, this may be a compiler-generated function. Assume
157939d628a0SDimitry Andric   // it's located in the main file.
158039d628a0SDimitry Andric   auto &SM = Context.getSourceManager();
158139d628a0SDimitry Andric   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
15829a199699SDimitry Andric     return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
158339d628a0SDimitry Andric   }
158439d628a0SDimitry Andric   return false;
158539d628a0SDimitry Andric }
158639d628a0SDimitry Andric 
158739d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
158839d628a0SDimitry Andric                                            SourceLocation Loc, QualType Ty,
158939d628a0SDimitry Andric                                            StringRef Category) const {
15908f0fd8f6SDimitry Andric   // For now globals can be blacklisted only in ASan and KASan.
15919a199699SDimitry Andric   const SanitizerMask EnabledAsanMask = LangOpts.Sanitize.Mask &
15929a199699SDimitry Andric       (SanitizerKind::Address | SanitizerKind::KernelAddress | SanitizerKind::HWAddress);
15939a199699SDimitry Andric   if (!EnabledAsanMask)
159439d628a0SDimitry Andric     return false;
159539d628a0SDimitry Andric   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
15969a199699SDimitry Andric   if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
159739d628a0SDimitry Andric     return true;
15989a199699SDimitry Andric   if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
159939d628a0SDimitry Andric     return true;
160039d628a0SDimitry Andric   // Check global type.
160139d628a0SDimitry Andric   if (!Ty.isNull()) {
160239d628a0SDimitry Andric     // Drill down the array types: if global variable of a fixed type is
160339d628a0SDimitry Andric     // blacklisted, we also don't instrument arrays of them.
160439d628a0SDimitry Andric     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
160539d628a0SDimitry Andric       Ty = AT->getElementType();
160639d628a0SDimitry Andric     Ty = Ty.getCanonicalType().getUnqualifiedType();
160739d628a0SDimitry Andric     // We allow to blacklist only record types (classes, structs etc.)
160839d628a0SDimitry Andric     if (Ty->isRecordType()) {
160939d628a0SDimitry Andric       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
16109a199699SDimitry Andric       if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
161139d628a0SDimitry Andric         return true;
161239d628a0SDimitry Andric     }
161339d628a0SDimitry Andric   }
161439d628a0SDimitry Andric   return false;
161539d628a0SDimitry Andric }
161639d628a0SDimitry Andric 
161720e90f04SDimitry Andric bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
161820e90f04SDimitry Andric                                    StringRef Category) const {
161920e90f04SDimitry Andric   if (!LangOpts.XRayInstrument)
162020e90f04SDimitry Andric     return false;
162120e90f04SDimitry Andric   const auto &XRayFilter = getContext().getXRayFilter();
162220e90f04SDimitry Andric   using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
162320e90f04SDimitry Andric   auto Attr = XRayFunctionFilter::ImbueAttribute::NONE;
162420e90f04SDimitry Andric   if (Loc.isValid())
162520e90f04SDimitry Andric     Attr = XRayFilter.shouldImbueLocation(Loc, Category);
162620e90f04SDimitry Andric   if (Attr == ImbueAttr::NONE)
162720e90f04SDimitry Andric     Attr = XRayFilter.shouldImbueFunction(Fn->getName());
162820e90f04SDimitry Andric   switch (Attr) {
162920e90f04SDimitry Andric   case ImbueAttr::NONE:
163020e90f04SDimitry Andric     return false;
163120e90f04SDimitry Andric   case ImbueAttr::ALWAYS:
163220e90f04SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-always");
163320e90f04SDimitry Andric     break;
1634302affcbSDimitry Andric   case ImbueAttr::ALWAYS_ARG1:
1635302affcbSDimitry Andric     Fn->addFnAttr("function-instrument", "xray-always");
1636302affcbSDimitry Andric     Fn->addFnAttr("xray-log-args", "1");
1637302affcbSDimitry Andric     break;
163820e90f04SDimitry Andric   case ImbueAttr::NEVER:
163920e90f04SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-never");
164020e90f04SDimitry Andric     break;
164120e90f04SDimitry Andric   }
164220e90f04SDimitry Andric   return true;
164320e90f04SDimitry Andric }
164420e90f04SDimitry Andric 
164539d628a0SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
1646e580952dSDimitry Andric   // Never defer when EmitAllDecls is specified.
1647dff0c46cSDimitry Andric   if (LangOpts.EmitAllDecls)
164839d628a0SDimitry Andric     return true;
164939d628a0SDimitry Andric 
165039d628a0SDimitry Andric   return getContext().DeclMustBeEmitted(Global);
165139d628a0SDimitry Andric }
165239d628a0SDimitry Andric 
165339d628a0SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
165439d628a0SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global))
165539d628a0SDimitry Andric     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
165639d628a0SDimitry Andric       // Implicit template instantiations may change linkage if they are later
165739d628a0SDimitry Andric       // explicitly instantiated, so they should not be emitted eagerly.
1658f22ef01cSRoman Divacky       return false;
1659e7145dcbSDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(Global))
1660e7145dcbSDimitry Andric     if (Context.getInlineVariableDefinitionKind(VD) ==
1661e7145dcbSDimitry Andric         ASTContext::InlineVariableDefinitionKind::WeakUnknown)
1662e7145dcbSDimitry Andric       // A definition of an inline constexpr static data member may change
1663e7145dcbSDimitry Andric       // linkage later if it's redeclared outside the class.
1664e7145dcbSDimitry Andric       return false;
1665875ed548SDimitry Andric   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
1666875ed548SDimitry Andric   // codegen for global variables, because they may be marked as threadprivate.
1667875ed548SDimitry Andric   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1668875ed548SDimitry Andric       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
1669875ed548SDimitry Andric     return false;
1670f22ef01cSRoman Divacky 
167139d628a0SDimitry Andric   return true;
1672f22ef01cSRoman Divacky }
1673f22ef01cSRoman Divacky 
16740623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
16753861d79fSDimitry Andric     const CXXUuidofExpr* E) {
16763861d79fSDimitry Andric   // Sema has verified that IIDSource has a __declspec(uuid()), and that its
16773861d79fSDimitry Andric   // well-formed.
1678e7145dcbSDimitry Andric   StringRef Uuid = E->getUuidStr();
1679f785676fSDimitry Andric   std::string Name = "_GUID_" + Uuid.lower();
1680f785676fSDimitry Andric   std::replace(Name.begin(), Name.end(), '-', '_');
16813861d79fSDimitry Andric 
1682e7145dcbSDimitry Andric   // The UUID descriptor should be pointer aligned.
1683e7145dcbSDimitry Andric   CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
16840623d748SDimitry Andric 
16853861d79fSDimitry Andric   // Look for an existing global.
16863861d79fSDimitry Andric   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
16870623d748SDimitry Andric     return ConstantAddress(GV, Alignment);
16883861d79fSDimitry Andric 
168939d628a0SDimitry Andric   llvm::Constant *Init = EmitUuidofInitializer(Uuid);
16903861d79fSDimitry Andric   assert(Init && "failed to initialize as constant");
16913861d79fSDimitry Andric 
169259d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
1693f785676fSDimitry Andric       getModule(), Init->getType(),
1694f785676fSDimitry Andric       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
169533956c43SDimitry Andric   if (supportsCOMDAT())
169633956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
16970623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
16983861d79fSDimitry Andric }
16993861d79fSDimitry Andric 
17000623d748SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1701f22ef01cSRoman Divacky   const AliasAttr *AA = VD->getAttr<AliasAttr>();
1702f22ef01cSRoman Divacky   assert(AA && "No alias?");
1703f22ef01cSRoman Divacky 
17040623d748SDimitry Andric   CharUnits Alignment = getContext().getDeclAlign(VD);
17056122f3e6SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1706f22ef01cSRoman Divacky 
1707f22ef01cSRoman Divacky   // See if there is already something with the target's name in the module.
1708f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
17093861d79fSDimitry Andric   if (Entry) {
17103861d79fSDimitry Andric     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
17110623d748SDimitry Andric     auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
17120623d748SDimitry Andric     return ConstantAddress(Ptr, Alignment);
17133861d79fSDimitry Andric   }
1714f22ef01cSRoman Divacky 
1715f22ef01cSRoman Divacky   llvm::Constant *Aliasee;
1716f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(DeclTy))
17173861d79fSDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
17183861d79fSDimitry Andric                                       GlobalDecl(cast<FunctionDecl>(VD)),
17192754fe60SDimitry Andric                                       /*ForVTable=*/false);
1720f22ef01cSRoman Divacky   else
1721f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
172259d1ed5bSDimitry Andric                                     llvm::PointerType::getUnqual(DeclTy),
172359d1ed5bSDimitry Andric                                     nullptr);
17243861d79fSDimitry Andric 
172559d1ed5bSDimitry Andric   auto *F = cast<llvm::GlobalValue>(Aliasee);
1726f22ef01cSRoman Divacky   F->setLinkage(llvm::Function::ExternalWeakLinkage);
1727f22ef01cSRoman Divacky   WeakRefReferences.insert(F);
1728f22ef01cSRoman Divacky 
17290623d748SDimitry Andric   return ConstantAddress(Aliasee, Alignment);
1730f22ef01cSRoman Divacky }
1731f22ef01cSRoman Divacky 
1732f22ef01cSRoman Divacky void CodeGenModule::EmitGlobal(GlobalDecl GD) {
173359d1ed5bSDimitry Andric   const auto *Global = cast<ValueDecl>(GD.getDecl());
1734f22ef01cSRoman Divacky 
1735f22ef01cSRoman Divacky   // Weak references don't produce any output by themselves.
1736f22ef01cSRoman Divacky   if (Global->hasAttr<WeakRefAttr>())
1737f22ef01cSRoman Divacky     return;
1738f22ef01cSRoman Divacky 
1739f22ef01cSRoman Divacky   // If this is an alias definition (which otherwise looks like a declaration)
1740f22ef01cSRoman Divacky   // emit it now.
1741f22ef01cSRoman Divacky   if (Global->hasAttr<AliasAttr>())
1742f22ef01cSRoman Divacky     return EmitAliasDefinition(GD);
1743f22ef01cSRoman Divacky 
1744e7145dcbSDimitry Andric   // IFunc like an alias whose value is resolved at runtime by calling resolver.
1745e7145dcbSDimitry Andric   if (Global->hasAttr<IFuncAttr>())
1746e7145dcbSDimitry Andric     return emitIFuncDefinition(GD);
1747e7145dcbSDimitry Andric 
17486122f3e6SDimitry Andric   // If this is CUDA, be selective about which declarations we emit.
1749dff0c46cSDimitry Andric   if (LangOpts.CUDA) {
175033956c43SDimitry Andric     if (LangOpts.CUDAIsDevice) {
17516122f3e6SDimitry Andric       if (!Global->hasAttr<CUDADeviceAttr>() &&
17526122f3e6SDimitry Andric           !Global->hasAttr<CUDAGlobalAttr>() &&
17536122f3e6SDimitry Andric           !Global->hasAttr<CUDAConstantAttr>() &&
17546122f3e6SDimitry Andric           !Global->hasAttr<CUDASharedAttr>())
17556122f3e6SDimitry Andric         return;
17566122f3e6SDimitry Andric     } else {
1757e7145dcbSDimitry Andric       // We need to emit host-side 'shadows' for all global
1758e7145dcbSDimitry Andric       // device-side variables because the CUDA runtime needs their
1759e7145dcbSDimitry Andric       // size and host-side address in order to provide access to
1760e7145dcbSDimitry Andric       // their device-side incarnations.
1761e7145dcbSDimitry Andric 
1762e7145dcbSDimitry Andric       // So device-only functions are the only things we skip.
1763e7145dcbSDimitry Andric       if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
1764e7145dcbSDimitry Andric           Global->hasAttr<CUDADeviceAttr>())
17656122f3e6SDimitry Andric         return;
1766e7145dcbSDimitry Andric 
1767e7145dcbSDimitry Andric       assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
1768e7145dcbSDimitry Andric              "Expected Variable or Function");
1769e580952dSDimitry Andric     }
1770e580952dSDimitry Andric   }
1771e580952dSDimitry Andric 
1772e7145dcbSDimitry Andric   if (LangOpts.OpenMP) {
1773ea942507SDimitry Andric     // If this is OpenMP device, check if it is legal to emit this global
1774ea942507SDimitry Andric     // normally.
1775ea942507SDimitry Andric     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
1776ea942507SDimitry Andric       return;
1777e7145dcbSDimitry Andric     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
1778e7145dcbSDimitry Andric       if (MustBeEmitted(Global))
1779e7145dcbSDimitry Andric         EmitOMPDeclareReduction(DRD);
1780e7145dcbSDimitry Andric       return;
1781e7145dcbSDimitry Andric     }
1782e7145dcbSDimitry Andric   }
1783ea942507SDimitry Andric 
17846122f3e6SDimitry Andric   // Ignore declarations, they will be emitted on their first use.
178559d1ed5bSDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
1786f22ef01cSRoman Divacky     // Forward declarations are emitted lazily on first use.
17876122f3e6SDimitry Andric     if (!FD->doesThisDeclarationHaveABody()) {
17886122f3e6SDimitry Andric       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1789f22ef01cSRoman Divacky         return;
17906122f3e6SDimitry Andric 
17916122f3e6SDimitry Andric       StringRef MangledName = getMangledName(GD);
179259d1ed5bSDimitry Andric 
179359d1ed5bSDimitry Andric       // Compute the function info and LLVM type.
179459d1ed5bSDimitry Andric       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
179559d1ed5bSDimitry Andric       llvm::Type *Ty = getTypes().GetFunctionType(FI);
179659d1ed5bSDimitry Andric 
179759d1ed5bSDimitry Andric       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
179859d1ed5bSDimitry Andric                               /*DontDefer=*/false);
17996122f3e6SDimitry Andric       return;
18006122f3e6SDimitry Andric     }
1801f22ef01cSRoman Divacky   } else {
180259d1ed5bSDimitry Andric     const auto *VD = cast<VarDecl>(Global);
1803f22ef01cSRoman Divacky     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1804e7145dcbSDimitry Andric     // We need to emit device-side global CUDA variables even if a
1805e7145dcbSDimitry Andric     // variable does not have a definition -- we still need to define
1806e7145dcbSDimitry Andric     // host-side shadow for it.
1807e7145dcbSDimitry Andric     bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
1808e7145dcbSDimitry Andric                            !VD->hasDefinition() &&
1809e7145dcbSDimitry Andric                            (VD->hasAttr<CUDAConstantAttr>() ||
1810e7145dcbSDimitry Andric                             VD->hasAttr<CUDADeviceAttr>());
1811e7145dcbSDimitry Andric     if (!MustEmitForCuda &&
1812e7145dcbSDimitry Andric         VD->isThisDeclarationADefinition() != VarDecl::Definition &&
1813e7145dcbSDimitry Andric         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
1814e7145dcbSDimitry Andric       // If this declaration may have caused an inline variable definition to
1815e7145dcbSDimitry Andric       // change linkage, make sure that it's emitted.
1816e7145dcbSDimitry Andric       if (Context.getInlineVariableDefinitionKind(VD) ==
1817e7145dcbSDimitry Andric           ASTContext::InlineVariableDefinitionKind::Strong)
1818e7145dcbSDimitry Andric         GetAddrOfGlobalVar(VD);
1819f22ef01cSRoman Divacky       return;
1820f22ef01cSRoman Divacky     }
1821e7145dcbSDimitry Andric   }
1822f22ef01cSRoman Divacky 
182339d628a0SDimitry Andric   // Defer code generation to first use when possible, e.g. if this is an inline
182439d628a0SDimitry Andric   // function. If the global must always be emitted, do it eagerly if possible
182539d628a0SDimitry Andric   // to benefit from cache locality.
182639d628a0SDimitry Andric   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
1827f22ef01cSRoman Divacky     // Emit the definition if it can't be deferred.
1828f22ef01cSRoman Divacky     EmitGlobalDefinition(GD);
1829f22ef01cSRoman Divacky     return;
1830f22ef01cSRoman Divacky   }
1831f22ef01cSRoman Divacky 
1832e580952dSDimitry Andric   // If we're deferring emission of a C++ variable with an
1833e580952dSDimitry Andric   // initializer, remember the order in which it appeared in the file.
1834dff0c46cSDimitry Andric   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1835e580952dSDimitry Andric       cast<VarDecl>(Global)->hasInit()) {
1836e580952dSDimitry Andric     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
183759d1ed5bSDimitry Andric     CXXGlobalInits.push_back(nullptr);
1838e580952dSDimitry Andric   }
1839e580952dSDimitry Andric 
18406122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
1841f37b6182SDimitry Andric   if (GetGlobalValue(MangledName) != nullptr) {
184239d628a0SDimitry Andric     // The value has already been used and should therefore be emitted.
1843f37b6182SDimitry Andric     addDeferredDeclToEmit(GD);
184439d628a0SDimitry Andric   } else if (MustBeEmitted(Global)) {
184539d628a0SDimitry Andric     // The value must be emitted, but cannot be emitted eagerly.
184639d628a0SDimitry Andric     assert(!MayBeEmittedEagerly(Global));
1847f37b6182SDimitry Andric     addDeferredDeclToEmit(GD);
184839d628a0SDimitry Andric   } else {
1849f22ef01cSRoman Divacky     // Otherwise, remember that we saw a deferred decl with this name.  The
1850f22ef01cSRoman Divacky     // first use of the mangled name will cause it to move into
1851f22ef01cSRoman Divacky     // DeferredDeclsToEmit.
1852f22ef01cSRoman Divacky     DeferredDecls[MangledName] = GD;
1853f22ef01cSRoman Divacky   }
1854f22ef01cSRoman Divacky }
1855f22ef01cSRoman Divacky 
185620e90f04SDimitry Andric // Check if T is a class type with a destructor that's not dllimport.
185720e90f04SDimitry Andric static bool HasNonDllImportDtor(QualType T) {
185820e90f04SDimitry Andric   if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
185920e90f04SDimitry Andric     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
186020e90f04SDimitry Andric       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
186120e90f04SDimitry Andric         return true;
186220e90f04SDimitry Andric 
186320e90f04SDimitry Andric   return false;
186420e90f04SDimitry Andric }
186520e90f04SDimitry Andric 
1866f8254f43SDimitry Andric namespace {
1867f8254f43SDimitry Andric   struct FunctionIsDirectlyRecursive :
1868f8254f43SDimitry Andric     public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1869f8254f43SDimitry Andric     const StringRef Name;
1870dff0c46cSDimitry Andric     const Builtin::Context &BI;
1871f8254f43SDimitry Andric     bool Result;
1872dff0c46cSDimitry Andric     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1873dff0c46cSDimitry Andric       Name(N), BI(C), Result(false) {
1874f8254f43SDimitry Andric     }
1875f8254f43SDimitry Andric     typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1876f8254f43SDimitry Andric 
1877f8254f43SDimitry Andric     bool TraverseCallExpr(CallExpr *E) {
1878dff0c46cSDimitry Andric       const FunctionDecl *FD = E->getDirectCallee();
1879dff0c46cSDimitry Andric       if (!FD)
1880f8254f43SDimitry Andric         return true;
1881dff0c46cSDimitry Andric       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1882dff0c46cSDimitry Andric       if (Attr && Name == Attr->getLabel()) {
1883dff0c46cSDimitry Andric         Result = true;
1884dff0c46cSDimitry Andric         return false;
1885dff0c46cSDimitry Andric       }
1886dff0c46cSDimitry Andric       unsigned BuiltinID = FD->getBuiltinID();
18873dac3a9bSDimitry Andric       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
1888f8254f43SDimitry Andric         return true;
18890623d748SDimitry Andric       StringRef BuiltinName = BI.getName(BuiltinID);
1890dff0c46cSDimitry Andric       if (BuiltinName.startswith("__builtin_") &&
1891dff0c46cSDimitry Andric           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1892f8254f43SDimitry Andric         Result = true;
1893f8254f43SDimitry Andric         return false;
1894f8254f43SDimitry Andric       }
1895f8254f43SDimitry Andric       return true;
1896f8254f43SDimitry Andric     }
1897f8254f43SDimitry Andric   };
18980623d748SDimitry Andric 
189920e90f04SDimitry Andric   // Make sure we're not referencing non-imported vars or functions.
19000623d748SDimitry Andric   struct DLLImportFunctionVisitor
19010623d748SDimitry Andric       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
19020623d748SDimitry Andric     bool SafeToInline = true;
19030623d748SDimitry Andric 
190444290647SDimitry Andric     bool shouldVisitImplicitCode() const { return true; }
190544290647SDimitry Andric 
19060623d748SDimitry Andric     bool VisitVarDecl(VarDecl *VD) {
190720e90f04SDimitry Andric       if (VD->getTLSKind()) {
19080623d748SDimitry Andric         // A thread-local variable cannot be imported.
190920e90f04SDimitry Andric         SafeToInline = false;
19100623d748SDimitry Andric         return SafeToInline;
19110623d748SDimitry Andric       }
19120623d748SDimitry Andric 
191320e90f04SDimitry Andric       // A variable definition might imply a destructor call.
191420e90f04SDimitry Andric       if (VD->isThisDeclarationADefinition())
191520e90f04SDimitry Andric         SafeToInline = !HasNonDllImportDtor(VD->getType());
191620e90f04SDimitry Andric 
191720e90f04SDimitry Andric       return SafeToInline;
191820e90f04SDimitry Andric     }
191920e90f04SDimitry Andric 
192020e90f04SDimitry Andric     bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
192120e90f04SDimitry Andric       if (const auto *D = E->getTemporary()->getDestructor())
192220e90f04SDimitry Andric         SafeToInline = D->hasAttr<DLLImportAttr>();
192320e90f04SDimitry Andric       return SafeToInline;
192420e90f04SDimitry Andric     }
192520e90f04SDimitry Andric 
19260623d748SDimitry Andric     bool VisitDeclRefExpr(DeclRefExpr *E) {
19270623d748SDimitry Andric       ValueDecl *VD = E->getDecl();
19280623d748SDimitry Andric       if (isa<FunctionDecl>(VD))
19290623d748SDimitry Andric         SafeToInline = VD->hasAttr<DLLImportAttr>();
19300623d748SDimitry Andric       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
19310623d748SDimitry Andric         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
19320623d748SDimitry Andric       return SafeToInline;
19330623d748SDimitry Andric     }
193420e90f04SDimitry Andric 
193544290647SDimitry Andric     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
193644290647SDimitry Andric       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
193744290647SDimitry Andric       return SafeToInline;
193844290647SDimitry Andric     }
193920e90f04SDimitry Andric 
194020e90f04SDimitry Andric     bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
194120e90f04SDimitry Andric       CXXMethodDecl *M = E->getMethodDecl();
194220e90f04SDimitry Andric       if (!M) {
194320e90f04SDimitry Andric         // Call through a pointer to member function. This is safe to inline.
194420e90f04SDimitry Andric         SafeToInline = true;
194520e90f04SDimitry Andric       } else {
194620e90f04SDimitry Andric         SafeToInline = M->hasAttr<DLLImportAttr>();
194720e90f04SDimitry Andric       }
194820e90f04SDimitry Andric       return SafeToInline;
194920e90f04SDimitry Andric     }
195020e90f04SDimitry Andric 
19510623d748SDimitry Andric     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
19520623d748SDimitry Andric       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
19530623d748SDimitry Andric       return SafeToInline;
19540623d748SDimitry Andric     }
195520e90f04SDimitry Andric 
19560623d748SDimitry Andric     bool VisitCXXNewExpr(CXXNewExpr *E) {
19570623d748SDimitry Andric       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
19580623d748SDimitry Andric       return SafeToInline;
19590623d748SDimitry Andric     }
19600623d748SDimitry Andric   };
1961f8254f43SDimitry Andric }
1962f8254f43SDimitry Andric 
1963dff0c46cSDimitry Andric // isTriviallyRecursive - Check if this function calls another
1964dff0c46cSDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin,
1965dff0c46cSDimitry Andric // ends up pointing to itself.
1966f8254f43SDimitry Andric bool
1967dff0c46cSDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1968dff0c46cSDimitry Andric   StringRef Name;
1969dff0c46cSDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1970dff0c46cSDimitry Andric     // asm labels are a special kind of mangling we have to support.
1971dff0c46cSDimitry Andric     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1972dff0c46cSDimitry Andric     if (!Attr)
1973f8254f43SDimitry Andric       return false;
1974dff0c46cSDimitry Andric     Name = Attr->getLabel();
1975dff0c46cSDimitry Andric   } else {
1976dff0c46cSDimitry Andric     Name = FD->getName();
1977dff0c46cSDimitry Andric   }
1978f8254f43SDimitry Andric 
1979dff0c46cSDimitry Andric   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1980dff0c46cSDimitry Andric   Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1981f8254f43SDimitry Andric   return Walker.Result;
1982f8254f43SDimitry Andric }
1983f8254f43SDimitry Andric 
198444290647SDimitry Andric bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1985f785676fSDimitry Andric   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1986f8254f43SDimitry Andric     return true;
198759d1ed5bSDimitry Andric   const auto *F = cast<FunctionDecl>(GD.getDecl());
198859d1ed5bSDimitry Andric   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1989f8254f43SDimitry Andric     return false;
19900623d748SDimitry Andric 
19910623d748SDimitry Andric   if (F->hasAttr<DLLImportAttr>()) {
19920623d748SDimitry Andric     // Check whether it would be safe to inline this dllimport function.
19930623d748SDimitry Andric     DLLImportFunctionVisitor Visitor;
19940623d748SDimitry Andric     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
19950623d748SDimitry Andric     if (!Visitor.SafeToInline)
19960623d748SDimitry Andric       return false;
199744290647SDimitry Andric 
199844290647SDimitry Andric     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
199944290647SDimitry Andric       // Implicit destructor invocations aren't captured in the AST, so the
200044290647SDimitry Andric       // check above can't see them. Check for them manually here.
200144290647SDimitry Andric       for (const Decl *Member : Dtor->getParent()->decls())
200244290647SDimitry Andric         if (isa<FieldDecl>(Member))
200344290647SDimitry Andric           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
200444290647SDimitry Andric             return false;
200544290647SDimitry Andric       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
200644290647SDimitry Andric         if (HasNonDllImportDtor(B.getType()))
200744290647SDimitry Andric           return false;
200844290647SDimitry Andric     }
20090623d748SDimitry Andric   }
20100623d748SDimitry Andric 
2011f8254f43SDimitry Andric   // PR9614. Avoid cases where the source code is lying to us. An available
2012f8254f43SDimitry Andric   // externally function should have an equivalent function somewhere else,
2013f8254f43SDimitry Andric   // but a function that calls itself is clearly not equivalent to the real
2014f8254f43SDimitry Andric   // implementation.
2015f8254f43SDimitry Andric   // This happens in glibc's btowc and in some configure checks.
2016dff0c46cSDimitry Andric   return !isTriviallyRecursive(F);
2017f8254f43SDimitry Andric }
2018f8254f43SDimitry Andric 
2019f9448bf3SDimitry Andric bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
2020f9448bf3SDimitry Andric   return CodeGenOpts.OptimizationLevel > 0;
2021f9448bf3SDimitry Andric }
2022f9448bf3SDimitry Andric 
202359d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
202459d1ed5bSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
2025f22ef01cSRoman Divacky 
2026f22ef01cSRoman Divacky   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
2027f22ef01cSRoman Divacky                                  Context.getSourceManager(),
2028f22ef01cSRoman Divacky                                  "Generating code for declaration");
2029f22ef01cSRoman Divacky 
2030f785676fSDimitry Andric   if (isa<FunctionDecl>(D)) {
2031ffd1746dSEd Schouten     // At -O0, don't generate IR for functions with available_externally
2032ffd1746dSEd Schouten     // linkage.
2033f785676fSDimitry Andric     if (!shouldEmitFunction(GD))
2034ffd1746dSEd Schouten       return;
2035ffd1746dSEd Schouten 
203659d1ed5bSDimitry Andric     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
2037bd5abe19SDimitry Andric       // Make sure to emit the definition(s) before we emit the thunks.
2038bd5abe19SDimitry Andric       // This is necessary for the generation of certain thunks.
203959d1ed5bSDimitry Andric       if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
204039d628a0SDimitry Andric         ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
204159d1ed5bSDimitry Andric       else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
204239d628a0SDimitry Andric         ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
2043bd5abe19SDimitry Andric       else
204459d1ed5bSDimitry Andric         EmitGlobalFunctionDefinition(GD, GV);
2045bd5abe19SDimitry Andric 
2046f22ef01cSRoman Divacky       if (Method->isVirtual())
2047f22ef01cSRoman Divacky         getVTables().EmitThunks(GD);
2048f22ef01cSRoman Divacky 
2049bd5abe19SDimitry Andric       return;
2050ffd1746dSEd Schouten     }
2051f22ef01cSRoman Divacky 
205259d1ed5bSDimitry Andric     return EmitGlobalFunctionDefinition(GD, GV);
2053ffd1746dSEd Schouten   }
2054f22ef01cSRoman Divacky 
205559d1ed5bSDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
2056e7145dcbSDimitry Andric     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
2057f22ef01cSRoman Divacky 
20586122f3e6SDimitry Andric   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
2059f22ef01cSRoman Divacky }
2060f22ef01cSRoman Divacky 
20610623d748SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
20620623d748SDimitry Andric                                                       llvm::Function *NewFn);
20630623d748SDimitry Andric 
2064f22ef01cSRoman Divacky /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
2065f22ef01cSRoman Divacky /// module, create and return an llvm Function with the specified type. If there
2066f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially
2067f22ef01cSRoman Divacky /// bitcasted to the right type.
2068f22ef01cSRoman Divacky ///
2069f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this.  This is used
2070f22ef01cSRoman Divacky /// to set the attributes on the function when it is first created.
207120e90f04SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
207220e90f04SDimitry Andric     StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
207320e90f04SDimitry Andric     bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
207444290647SDimitry Andric     ForDefinition_t IsForDefinition) {
2075f785676fSDimitry Andric   const Decl *D = GD.getDecl();
2076f785676fSDimitry Andric 
2077f22ef01cSRoman Divacky   // Lookup the entry, lazily creating it if necessary.
2078f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2079f22ef01cSRoman Divacky   if (Entry) {
20803861d79fSDimitry Andric     if (WeakRefReferences.erase(Entry)) {
2081f785676fSDimitry Andric       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
2082f22ef01cSRoman Divacky       if (FD && !FD->hasAttr<WeakAttr>())
2083f22ef01cSRoman Divacky         Entry->setLinkage(llvm::Function::ExternalLinkage);
2084f22ef01cSRoman Divacky     }
2085f22ef01cSRoman Divacky 
208639d628a0SDimitry Andric     // Handle dropped DLL attributes.
208739d628a0SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
208839d628a0SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
208939d628a0SDimitry Andric 
20900623d748SDimitry Andric     // If there are two attempts to define the same mangled name, issue an
20910623d748SDimitry Andric     // error.
20920623d748SDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
20930623d748SDimitry Andric       GlobalDecl OtherGD;
2094e7145dcbSDimitry Andric       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
2095e7145dcbSDimitry Andric       // to make sure that we issue an error only once.
20960623d748SDimitry Andric       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
20970623d748SDimitry Andric           (GD.getCanonicalDecl().getDecl() !=
20980623d748SDimitry Andric            OtherGD.getCanonicalDecl().getDecl()) &&
20990623d748SDimitry Andric           DiagnosedConflictingDefinitions.insert(GD).second) {
21000623d748SDimitry Andric         getDiags().Report(D->getLocation(),
21010623d748SDimitry Andric                           diag::err_duplicate_mangled_name);
21020623d748SDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
21030623d748SDimitry Andric                           diag::note_previous_definition);
21040623d748SDimitry Andric       }
21050623d748SDimitry Andric     }
21060623d748SDimitry Andric 
21070623d748SDimitry Andric     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
21080623d748SDimitry Andric         (Entry->getType()->getElementType() == Ty)) {
2109f22ef01cSRoman Divacky       return Entry;
21100623d748SDimitry Andric     }
2111f22ef01cSRoman Divacky 
2112f22ef01cSRoman Divacky     // Make sure the result is of the correct type.
21130623d748SDimitry Andric     // (If function is requested for a definition, we always need to create a new
21140623d748SDimitry Andric     // function, not just return a bitcast.)
21150623d748SDimitry Andric     if (!IsForDefinition)
211617a519f9SDimitry Andric       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
2117f22ef01cSRoman Divacky   }
2118f22ef01cSRoman Divacky 
2119f22ef01cSRoman Divacky   // This function doesn't have a complete type (for example, the return
2120f22ef01cSRoman Divacky   // type is an incomplete struct). Use a fake type instead, and make
2121f22ef01cSRoman Divacky   // sure not to try to set attributes.
2122f22ef01cSRoman Divacky   bool IsIncompleteFunction = false;
2123f22ef01cSRoman Divacky 
21246122f3e6SDimitry Andric   llvm::FunctionType *FTy;
2125f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(Ty)) {
2126f22ef01cSRoman Divacky     FTy = cast<llvm::FunctionType>(Ty);
2127f22ef01cSRoman Divacky   } else {
2128bd5abe19SDimitry Andric     FTy = llvm::FunctionType::get(VoidTy, false);
2129f22ef01cSRoman Divacky     IsIncompleteFunction = true;
2130f22ef01cSRoman Divacky   }
2131ffd1746dSEd Schouten 
21320623d748SDimitry Andric   llvm::Function *F =
21330623d748SDimitry Andric       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
21340623d748SDimitry Andric                              Entry ? StringRef() : MangledName, &getModule());
21350623d748SDimitry Andric 
21360623d748SDimitry Andric   // If we already created a function with the same mangled name (but different
21370623d748SDimitry Andric   // type) before, take its name and add it to the list of functions to be
21380623d748SDimitry Andric   // replaced with F at the end of CodeGen.
21390623d748SDimitry Andric   //
21400623d748SDimitry Andric   // This happens if there is a prototype for a function (e.g. "int f()") and
21410623d748SDimitry Andric   // then a definition of a different type (e.g. "int f(int x)").
21420623d748SDimitry Andric   if (Entry) {
21430623d748SDimitry Andric     F->takeName(Entry);
21440623d748SDimitry Andric 
21450623d748SDimitry Andric     // This might be an implementation of a function without a prototype, in
21460623d748SDimitry Andric     // which case, try to do special replacement of calls which match the new
21470623d748SDimitry Andric     // prototype.  The really key thing here is that we also potentially drop
21480623d748SDimitry Andric     // arguments from the call site so as to make a direct call, which makes the
21490623d748SDimitry Andric     // inliner happier and suppresses a number of optimizer warnings (!) about
21500623d748SDimitry Andric     // dropping arguments.
21510623d748SDimitry Andric     if (!Entry->use_empty()) {
21520623d748SDimitry Andric       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
21530623d748SDimitry Andric       Entry->removeDeadConstantUsers();
21540623d748SDimitry Andric     }
21550623d748SDimitry Andric 
21560623d748SDimitry Andric     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
21570623d748SDimitry Andric         F, Entry->getType()->getElementType()->getPointerTo());
21580623d748SDimitry Andric     addGlobalValReplacement(Entry, BC);
21590623d748SDimitry Andric   }
21600623d748SDimitry Andric 
2161f22ef01cSRoman Divacky   assert(F->getName() == MangledName && "name was uniqued!");
2162f785676fSDimitry Andric   if (D)
21639a199699SDimitry Andric     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk,
21649a199699SDimitry Andric                           IsForDefinition);
216520e90f04SDimitry Andric   if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
216620e90f04SDimitry Andric     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
2167f37b6182SDimitry Andric     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
2168139f7f9bSDimitry Andric   }
2169f22ef01cSRoman Divacky 
217059d1ed5bSDimitry Andric   if (!DontDefer) {
217159d1ed5bSDimitry Andric     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
217259d1ed5bSDimitry Andric     // each other bottoming out with the base dtor.  Therefore we emit non-base
217359d1ed5bSDimitry Andric     // dtors on usage, even if there is no dtor definition in the TU.
217459d1ed5bSDimitry Andric     if (D && isa<CXXDestructorDecl>(D) &&
217559d1ed5bSDimitry Andric         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
217659d1ed5bSDimitry Andric                                            GD.getDtorType()))
2177f37b6182SDimitry Andric       addDeferredDeclToEmit(GD);
217859d1ed5bSDimitry Andric 
2179f22ef01cSRoman Divacky     // This is the first use or definition of a mangled name.  If there is a
2180f22ef01cSRoman Divacky     // deferred decl with this name, remember that we need to emit it at the end
2181f22ef01cSRoman Divacky     // of the file.
218259d1ed5bSDimitry Andric     auto DDI = DeferredDecls.find(MangledName);
2183f22ef01cSRoman Divacky     if (DDI != DeferredDecls.end()) {
218459d1ed5bSDimitry Andric       // Move the potentially referenced deferred decl to the
218559d1ed5bSDimitry Andric       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
218659d1ed5bSDimitry Andric       // don't need it anymore).
2187f37b6182SDimitry Andric       addDeferredDeclToEmit(DDI->second);
2188f22ef01cSRoman Divacky       DeferredDecls.erase(DDI);
21892754fe60SDimitry Andric 
21902754fe60SDimitry Andric       // Otherwise, there are cases we have to worry about where we're
21912754fe60SDimitry Andric       // using a declaration for which we must emit a definition but where
21922754fe60SDimitry Andric       // we might not find a top-level definition:
21932754fe60SDimitry Andric       //   - member functions defined inline in their classes
21942754fe60SDimitry Andric       //   - friend functions defined inline in some class
21952754fe60SDimitry Andric       //   - special member functions with implicit definitions
21962754fe60SDimitry Andric       // If we ever change our AST traversal to walk into class methods,
21972754fe60SDimitry Andric       // this will be unnecessary.
21982754fe60SDimitry Andric       //
219959d1ed5bSDimitry Andric       // We also don't emit a definition for a function if it's going to be an
220039d628a0SDimitry Andric       // entry in a vtable, unless it's already marked as used.
2201f785676fSDimitry Andric     } else if (getLangOpts().CPlusPlus && D) {
22022754fe60SDimitry Andric       // Look for a declaration that's lexically in a record.
220339d628a0SDimitry Andric       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
220439d628a0SDimitry Andric            FD = FD->getPreviousDecl()) {
22052754fe60SDimitry Andric         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
220639d628a0SDimitry Andric           if (FD->doesThisDeclarationHaveABody()) {
2207f37b6182SDimitry Andric             addDeferredDeclToEmit(GD.getWithDecl(FD));
22082754fe60SDimitry Andric             break;
2209f22ef01cSRoman Divacky           }
2210f22ef01cSRoman Divacky         }
221139d628a0SDimitry Andric       }
2212f22ef01cSRoman Divacky     }
221359d1ed5bSDimitry Andric   }
2214f22ef01cSRoman Divacky 
2215f22ef01cSRoman Divacky   // Make sure the result is of the requested type.
2216f22ef01cSRoman Divacky   if (!IsIncompleteFunction) {
2217f22ef01cSRoman Divacky     assert(F->getType()->getElementType() == Ty);
2218f22ef01cSRoman Divacky     return F;
2219f22ef01cSRoman Divacky   }
2220f22ef01cSRoman Divacky 
222117a519f9SDimitry Andric   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2222f22ef01cSRoman Divacky   return llvm::ConstantExpr::getBitCast(F, PTy);
2223f22ef01cSRoman Divacky }
2224f22ef01cSRoman Divacky 
2225f22ef01cSRoman Divacky /// GetAddrOfFunction - Return the address of the given function.  If Ty is
2226f22ef01cSRoman Divacky /// non-null, then this function will use the specified type if it has to
2227f22ef01cSRoman Divacky /// create it (this occurs when we see a definition of the function).
2228f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
22296122f3e6SDimitry Andric                                                  llvm::Type *Ty,
223059d1ed5bSDimitry Andric                                                  bool ForVTable,
22310623d748SDimitry Andric                                                  bool DontDefer,
223244290647SDimitry Andric                                               ForDefinition_t IsForDefinition) {
2233f22ef01cSRoman Divacky   // If there was no specific requested type, just convert it now.
22340623d748SDimitry Andric   if (!Ty) {
22350623d748SDimitry Andric     const auto *FD = cast<FunctionDecl>(GD.getDecl());
22360623d748SDimitry Andric     auto CanonTy = Context.getCanonicalType(FD->getType());
22370623d748SDimitry Andric     Ty = getTypes().ConvertFunctionType(CanonTy, FD);
22380623d748SDimitry Andric   }
2239ffd1746dSEd Schouten 
22406122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
22410623d748SDimitry Andric   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
224220e90f04SDimitry Andric                                  /*IsThunk=*/false, llvm::AttributeList(),
22430623d748SDimitry Andric                                  IsForDefinition);
2244f22ef01cSRoman Divacky }
2245f22ef01cSRoman Divacky 
224644290647SDimitry Andric static const FunctionDecl *
224744290647SDimitry Andric GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
224844290647SDimitry Andric   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
224944290647SDimitry Andric   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
225044290647SDimitry Andric 
225144290647SDimitry Andric   IdentifierInfo &CII = C.Idents.get(Name);
225244290647SDimitry Andric   for (const auto &Result : DC->lookup(&CII))
225344290647SDimitry Andric     if (const auto FD = dyn_cast<FunctionDecl>(Result))
225444290647SDimitry Andric       return FD;
225544290647SDimitry Andric 
225644290647SDimitry Andric   if (!C.getLangOpts().CPlusPlus)
225744290647SDimitry Andric     return nullptr;
225844290647SDimitry Andric 
225944290647SDimitry Andric   // Demangle the premangled name from getTerminateFn()
226044290647SDimitry Andric   IdentifierInfo &CXXII =
226144290647SDimitry Andric       (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ")
226244290647SDimitry Andric           ? C.Idents.get("terminate")
226344290647SDimitry Andric           : C.Idents.get(Name);
226444290647SDimitry Andric 
226544290647SDimitry Andric   for (const auto &N : {"__cxxabiv1", "std"}) {
226644290647SDimitry Andric     IdentifierInfo &NS = C.Idents.get(N);
226744290647SDimitry Andric     for (const auto &Result : DC->lookup(&NS)) {
226844290647SDimitry Andric       NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
226944290647SDimitry Andric       if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
227044290647SDimitry Andric         for (const auto &Result : LSD->lookup(&NS))
227144290647SDimitry Andric           if ((ND = dyn_cast<NamespaceDecl>(Result)))
227244290647SDimitry Andric             break;
227344290647SDimitry Andric 
227444290647SDimitry Andric       if (ND)
227544290647SDimitry Andric         for (const auto &Result : ND->lookup(&CXXII))
227644290647SDimitry Andric           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
227744290647SDimitry Andric             return FD;
227844290647SDimitry Andric     }
227944290647SDimitry Andric   }
228044290647SDimitry Andric 
228144290647SDimitry Andric   return nullptr;
228244290647SDimitry Andric }
228344290647SDimitry Andric 
2284f22ef01cSRoman Divacky /// CreateRuntimeFunction - Create a new runtime function with the specified
2285f22ef01cSRoman Divacky /// type and name.
2286f22ef01cSRoman Divacky llvm::Constant *
228744290647SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
228820e90f04SDimitry Andric                                      llvm::AttributeList ExtraAttrs,
228944290647SDimitry Andric                                      bool Local) {
229059d1ed5bSDimitry Andric   llvm::Constant *C =
229159d1ed5bSDimitry Andric       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
229244290647SDimitry Andric                               /*DontDefer=*/false, /*IsThunk=*/false,
229344290647SDimitry Andric                               ExtraAttrs);
229444290647SDimitry Andric 
229544290647SDimitry Andric   if (auto *F = dyn_cast<llvm::Function>(C)) {
229644290647SDimitry Andric     if (F->empty()) {
2297139f7f9bSDimitry Andric       F->setCallingConv(getRuntimeCC());
229844290647SDimitry Andric 
229944290647SDimitry Andric       if (!Local && getTriple().isOSBinFormatCOFF() &&
23009a199699SDimitry Andric           !getCodeGenOpts().LTOVisibilityPublicStd &&
23019a199699SDimitry Andric           !getTriple().isWindowsGNUEnvironment()) {
230244290647SDimitry Andric         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
230344290647SDimitry Andric         if (!FD || FD->hasAttr<DLLImportAttr>()) {
230444290647SDimitry Andric           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
230544290647SDimitry Andric           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
230644290647SDimitry Andric         }
230744290647SDimitry Andric       }
230844290647SDimitry Andric     }
230944290647SDimitry Andric   }
231044290647SDimitry Andric 
2311139f7f9bSDimitry Andric   return C;
2312f22ef01cSRoman Divacky }
2313f22ef01cSRoman Divacky 
231439d628a0SDimitry Andric /// CreateBuiltinFunction - Create a new builtin function with the specified
231539d628a0SDimitry Andric /// type and name.
231639d628a0SDimitry Andric llvm::Constant *
231720e90f04SDimitry Andric CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
231820e90f04SDimitry Andric                                      llvm::AttributeList ExtraAttrs) {
231939d628a0SDimitry Andric   llvm::Constant *C =
232039d628a0SDimitry Andric       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
232139d628a0SDimitry Andric                               /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
232239d628a0SDimitry Andric   if (auto *F = dyn_cast<llvm::Function>(C))
232339d628a0SDimitry Andric     if (F->empty())
232439d628a0SDimitry Andric       F->setCallingConv(getBuiltinCC());
232539d628a0SDimitry Andric   return C;
232639d628a0SDimitry Andric }
232739d628a0SDimitry Andric 
2328dff0c46cSDimitry Andric /// isTypeConstant - Determine whether an object of this type can be emitted
2329dff0c46cSDimitry Andric /// as a constant.
2330dff0c46cSDimitry Andric ///
2331dff0c46cSDimitry Andric /// If ExcludeCtor is true, the duration when the object's constructor runs
2332dff0c46cSDimitry Andric /// will not be considered. The caller will need to verify that the object is
2333dff0c46cSDimitry Andric /// not written to during its construction.
2334dff0c46cSDimitry Andric bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2335dff0c46cSDimitry Andric   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
2336f22ef01cSRoman Divacky     return false;
2337bd5abe19SDimitry Andric 
2338dff0c46cSDimitry Andric   if (Context.getLangOpts().CPlusPlus) {
2339dff0c46cSDimitry Andric     if (const CXXRecordDecl *Record
2340dff0c46cSDimitry Andric           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2341dff0c46cSDimitry Andric       return ExcludeCtor && !Record->hasMutableFields() &&
2342dff0c46cSDimitry Andric              Record->hasTrivialDestructor();
2343f22ef01cSRoman Divacky   }
2344bd5abe19SDimitry Andric 
2345f22ef01cSRoman Divacky   return true;
2346f22ef01cSRoman Divacky }
2347f22ef01cSRoman Divacky 
2348f22ef01cSRoman Divacky /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2349f22ef01cSRoman Divacky /// create and return an llvm GlobalVariable with the specified type.  If there
2350f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially
2351f22ef01cSRoman Divacky /// bitcasted to the right type.
2352f22ef01cSRoman Divacky ///
2353f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this.  This is used
2354f22ef01cSRoman Divacky /// to set the attributes on the global when it is first created.
2355e7145dcbSDimitry Andric ///
2356e7145dcbSDimitry Andric /// If IsForDefinition is true, it is guranteed that an actual global with
2357e7145dcbSDimitry Andric /// type Ty will be returned, not conversion of a variable with the same
2358e7145dcbSDimitry Andric /// mangled name but some other type.
2359f22ef01cSRoman Divacky llvm::Constant *
23606122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
23616122f3e6SDimitry Andric                                      llvm::PointerType *Ty,
2362e7145dcbSDimitry Andric                                      const VarDecl *D,
236344290647SDimitry Andric                                      ForDefinition_t IsForDefinition) {
2364f22ef01cSRoman Divacky   // Lookup the entry, lazily creating it if necessary.
2365f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2366f22ef01cSRoman Divacky   if (Entry) {
23673861d79fSDimitry Andric     if (WeakRefReferences.erase(Entry)) {
2368f22ef01cSRoman Divacky       if (D && !D->hasAttr<WeakAttr>())
2369f22ef01cSRoman Divacky         Entry->setLinkage(llvm::Function::ExternalLinkage);
2370f22ef01cSRoman Divacky     }
2371f22ef01cSRoman Divacky 
237239d628a0SDimitry Andric     // Handle dropped DLL attributes.
237339d628a0SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
237439d628a0SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
237539d628a0SDimitry Andric 
2376f22ef01cSRoman Divacky     if (Entry->getType() == Ty)
2377f22ef01cSRoman Divacky       return Entry;
2378f22ef01cSRoman Divacky 
2379e7145dcbSDimitry Andric     // If there are two attempts to define the same mangled name, issue an
2380e7145dcbSDimitry Andric     // error.
2381e7145dcbSDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
2382e7145dcbSDimitry Andric       GlobalDecl OtherGD;
2383e7145dcbSDimitry Andric       const VarDecl *OtherD;
2384e7145dcbSDimitry Andric 
2385e7145dcbSDimitry Andric       // Check that D is not yet in DiagnosedConflictingDefinitions is required
2386e7145dcbSDimitry Andric       // to make sure that we issue an error only once.
2387e7145dcbSDimitry Andric       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
2388e7145dcbSDimitry Andric           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2389e7145dcbSDimitry Andric           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2390e7145dcbSDimitry Andric           OtherD->hasInit() &&
2391e7145dcbSDimitry Andric           DiagnosedConflictingDefinitions.insert(D).second) {
2392e7145dcbSDimitry Andric         getDiags().Report(D->getLocation(),
2393e7145dcbSDimitry Andric                           diag::err_duplicate_mangled_name);
2394e7145dcbSDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
2395e7145dcbSDimitry Andric                           diag::note_previous_definition);
2396e7145dcbSDimitry Andric       }
2397e7145dcbSDimitry Andric     }
2398e7145dcbSDimitry Andric 
2399f22ef01cSRoman Divacky     // Make sure the result is of the correct type.
2400f785676fSDimitry Andric     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2401f785676fSDimitry Andric       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2402f785676fSDimitry Andric 
2403e7145dcbSDimitry Andric     // (If global is requested for a definition, we always need to create a new
2404e7145dcbSDimitry Andric     // global, not just return a bitcast.)
2405e7145dcbSDimitry Andric     if (!IsForDefinition)
2406f22ef01cSRoman Divacky       return llvm::ConstantExpr::getBitCast(Entry, Ty);
2407f22ef01cSRoman Divacky   }
2408f22ef01cSRoman Divacky 
2409c4394386SDimitry Andric   auto AddrSpace = GetGlobalVarAddressSpace(D);
2410c4394386SDimitry Andric   auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
2411c4394386SDimitry Andric 
241259d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
241359d1ed5bSDimitry Andric       getModule(), Ty->getElementType(), false,
241459d1ed5bSDimitry Andric       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
2415c4394386SDimitry Andric       llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
241659d1ed5bSDimitry Andric 
2417e7145dcbSDimitry Andric   // If we already created a global with the same mangled name (but different
2418e7145dcbSDimitry Andric   // type) before, take its name and remove it from its parent.
2419e7145dcbSDimitry Andric   if (Entry) {
2420e7145dcbSDimitry Andric     GV->takeName(Entry);
2421e7145dcbSDimitry Andric 
2422e7145dcbSDimitry Andric     if (!Entry->use_empty()) {
2423e7145dcbSDimitry Andric       llvm::Constant *NewPtrForOldDecl =
2424e7145dcbSDimitry Andric           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2425e7145dcbSDimitry Andric       Entry->replaceAllUsesWith(NewPtrForOldDecl);
2426e7145dcbSDimitry Andric     }
2427e7145dcbSDimitry Andric 
2428e7145dcbSDimitry Andric     Entry->eraseFromParent();
2429e7145dcbSDimitry Andric   }
2430e7145dcbSDimitry Andric 
2431f22ef01cSRoman Divacky   // This is the first use or definition of a mangled name.  If there is a
2432f22ef01cSRoman Divacky   // deferred decl with this name, remember that we need to emit it at the end
2433f22ef01cSRoman Divacky   // of the file.
243459d1ed5bSDimitry Andric   auto DDI = DeferredDecls.find(MangledName);
2435f22ef01cSRoman Divacky   if (DDI != DeferredDecls.end()) {
2436f22ef01cSRoman Divacky     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2437f22ef01cSRoman Divacky     // list, and remove it from DeferredDecls (since we don't need it anymore).
2438f37b6182SDimitry Andric     addDeferredDeclToEmit(DDI->second);
2439f22ef01cSRoman Divacky     DeferredDecls.erase(DDI);
2440f22ef01cSRoman Divacky   }
2441f22ef01cSRoman Divacky 
2442f22ef01cSRoman Divacky   // Handle things which are present even on external declarations.
2443f22ef01cSRoman Divacky   if (D) {
2444f22ef01cSRoman Divacky     // FIXME: This code is overly simple and should be merged with other global
2445f22ef01cSRoman Divacky     // handling.
2446dff0c46cSDimitry Andric     GV->setConstant(isTypeConstant(D->getType(), false));
2447f22ef01cSRoman Divacky 
244833956c43SDimitry Andric     GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
244933956c43SDimitry Andric 
24509a199699SDimitry Andric     setLinkageForGV(GV, D);
24519a199699SDimitry Andric     setGlobalVisibility(GV, D, NotForDefinition);
24522754fe60SDimitry Andric 
2453284c1978SDimitry Andric     if (D->getTLSKind()) {
2454284c1978SDimitry Andric       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
24550623d748SDimitry Andric         CXXThreadLocals.push_back(D);
24567ae0e2c9SDimitry Andric       setTLSMode(GV, *D);
2457f22ef01cSRoman Divacky     }
2458f785676fSDimitry Andric 
2459f785676fSDimitry Andric     // If required by the ABI, treat declarations of static data members with
2460f785676fSDimitry Andric     // inline initializers as definitions.
246159d1ed5bSDimitry Andric     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
2462f785676fSDimitry Andric       EmitGlobalVarDefinition(D);
2463284c1978SDimitry Andric     }
2464f22ef01cSRoman Divacky 
24659a199699SDimitry Andric     // Emit section information for extern variables.
24669a199699SDimitry Andric     if (D->hasExternalStorage()) {
24679a199699SDimitry Andric       if (const SectionAttr *SA = D->getAttr<SectionAttr>())
24689a199699SDimitry Andric         GV->setSection(SA->getName());
24699a199699SDimitry Andric     }
24709a199699SDimitry Andric 
247159d1ed5bSDimitry Andric     // Handle XCore specific ABI requirements.
247244290647SDimitry Andric     if (getTriple().getArch() == llvm::Triple::xcore &&
247359d1ed5bSDimitry Andric         D->getLanguageLinkage() == CLanguageLinkage &&
247459d1ed5bSDimitry Andric         D->getType().isConstant(Context) &&
247559d1ed5bSDimitry Andric         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
247659d1ed5bSDimitry Andric       GV->setSection(".cp.rodata");
24779a199699SDimitry Andric 
24789a199699SDimitry Andric     // Check if we a have a const declaration with an initializer, we may be
24799a199699SDimitry Andric     // able to emit it as available_externally to expose it's value to the
24809a199699SDimitry Andric     // optimizer.
24819a199699SDimitry Andric     if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
24829a199699SDimitry Andric         D->getType().isConstQualified() && !GV->hasInitializer() &&
24839a199699SDimitry Andric         !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
24849a199699SDimitry Andric       const auto *Record =
24859a199699SDimitry Andric           Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
24869a199699SDimitry Andric       bool HasMutableFields = Record && Record->hasMutableFields();
24879a199699SDimitry Andric       if (!HasMutableFields) {
24889a199699SDimitry Andric         const VarDecl *InitDecl;
24899a199699SDimitry Andric         const Expr *InitExpr = D->getAnyInitializer(InitDecl);
24909a199699SDimitry Andric         if (InitExpr) {
24919a199699SDimitry Andric           ConstantEmitter emitter(*this);
24929a199699SDimitry Andric           llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
24939a199699SDimitry Andric           if (Init) {
24949a199699SDimitry Andric             auto *InitType = Init->getType();
24959a199699SDimitry Andric             if (GV->getType()->getElementType() != InitType) {
24969a199699SDimitry Andric               // The type of the initializer does not match the definition.
24979a199699SDimitry Andric               // This happens when an initializer has a different type from
24989a199699SDimitry Andric               // the type of the global (because of padding at the end of a
24999a199699SDimitry Andric               // structure for instance).
25009a199699SDimitry Andric               GV->setName(StringRef());
25019a199699SDimitry Andric               // Make a new global with the correct type, this is now guaranteed
25029a199699SDimitry Andric               // to work.
25039a199699SDimitry Andric               auto *NewGV = cast<llvm::GlobalVariable>(
25049a199699SDimitry Andric                   GetAddrOfGlobalVar(D, InitType, IsForDefinition));
25059a199699SDimitry Andric 
25069a199699SDimitry Andric               // Erase the old global, since it is no longer used.
25079a199699SDimitry Andric               cast<llvm::GlobalValue>(GV)->eraseFromParent();
25089a199699SDimitry Andric               GV = NewGV;
25099a199699SDimitry Andric             } else {
25109a199699SDimitry Andric               GV->setInitializer(Init);
25119a199699SDimitry Andric               GV->setConstant(true);
25129a199699SDimitry Andric               GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
25139a199699SDimitry Andric             }
25149a199699SDimitry Andric             emitter.finalize(GV);
25159a199699SDimitry Andric           }
25169a199699SDimitry Andric         }
25179a199699SDimitry Andric       }
25189a199699SDimitry Andric     }
251959d1ed5bSDimitry Andric   }
252059d1ed5bSDimitry Andric 
25219a199699SDimitry Andric   LangAS ExpectedAS =
2522c4394386SDimitry Andric       D ? D->getType().getAddressSpace()
25239a199699SDimitry Andric         : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
2524c4394386SDimitry Andric   assert(getContext().getTargetAddressSpace(ExpectedAS) ==
2525c4394386SDimitry Andric          Ty->getPointerAddressSpace());
2526c4394386SDimitry Andric   if (AddrSpace != ExpectedAS)
2527c4394386SDimitry Andric     return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
2528c4394386SDimitry Andric                                                        ExpectedAS, Ty);
2529f785676fSDimitry Andric 
2530f22ef01cSRoman Divacky   return GV;
2531f22ef01cSRoman Divacky }
2532f22ef01cSRoman Divacky 
25330623d748SDimitry Andric llvm::Constant *
25340623d748SDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
253544290647SDimitry Andric                                ForDefinition_t IsForDefinition) {
253644290647SDimitry Andric   const Decl *D = GD.getDecl();
253744290647SDimitry Andric   if (isa<CXXConstructorDecl>(D))
253844290647SDimitry Andric     return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
25390623d748SDimitry Andric                                 getFromCtorType(GD.getCtorType()),
25400623d748SDimitry Andric                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
25410623d748SDimitry Andric                                 /*DontDefer=*/false, IsForDefinition);
254244290647SDimitry Andric   else if (isa<CXXDestructorDecl>(D))
254344290647SDimitry Andric     return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
25440623d748SDimitry Andric                                 getFromDtorType(GD.getDtorType()),
25450623d748SDimitry Andric                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
25460623d748SDimitry Andric                                 /*DontDefer=*/false, IsForDefinition);
254744290647SDimitry Andric   else if (isa<CXXMethodDecl>(D)) {
25480623d748SDimitry Andric     auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
254944290647SDimitry Andric         cast<CXXMethodDecl>(D));
25500623d748SDimitry Andric     auto Ty = getTypes().GetFunctionType(*FInfo);
25510623d748SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
25520623d748SDimitry Andric                              IsForDefinition);
255344290647SDimitry Andric   } else if (isa<FunctionDecl>(D)) {
25540623d748SDimitry Andric     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
25550623d748SDimitry Andric     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
25560623d748SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
25570623d748SDimitry Andric                              IsForDefinition);
25580623d748SDimitry Andric   } else
255944290647SDimitry Andric     return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
2560e7145dcbSDimitry Andric                               IsForDefinition);
25610623d748SDimitry Andric }
2562f22ef01cSRoman Divacky 
25632754fe60SDimitry Andric llvm::GlobalVariable *
25646122f3e6SDimitry Andric CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
25656122f3e6SDimitry Andric                                       llvm::Type *Ty,
25662754fe60SDimitry Andric                                       llvm::GlobalValue::LinkageTypes Linkage) {
25672754fe60SDimitry Andric   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
256859d1ed5bSDimitry Andric   llvm::GlobalVariable *OldGV = nullptr;
25692754fe60SDimitry Andric 
25702754fe60SDimitry Andric   if (GV) {
25712754fe60SDimitry Andric     // Check if the variable has the right type.
25722754fe60SDimitry Andric     if (GV->getType()->getElementType() == Ty)
25732754fe60SDimitry Andric       return GV;
25742754fe60SDimitry Andric 
25752754fe60SDimitry Andric     // Because C++ name mangling, the only way we can end up with an already
25762754fe60SDimitry Andric     // existing global with the same name is if it has been declared extern "C".
25772754fe60SDimitry Andric     assert(GV->isDeclaration() && "Declaration has wrong type!");
25782754fe60SDimitry Andric     OldGV = GV;
25792754fe60SDimitry Andric   }
25802754fe60SDimitry Andric 
25812754fe60SDimitry Andric   // Create a new variable.
25822754fe60SDimitry Andric   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
258359d1ed5bSDimitry Andric                                 Linkage, nullptr, Name);
25842754fe60SDimitry Andric 
25852754fe60SDimitry Andric   if (OldGV) {
25862754fe60SDimitry Andric     // Replace occurrences of the old variable if needed.
25872754fe60SDimitry Andric     GV->takeName(OldGV);
25882754fe60SDimitry Andric 
25892754fe60SDimitry Andric     if (!OldGV->use_empty()) {
25902754fe60SDimitry Andric       llvm::Constant *NewPtrForOldDecl =
25912754fe60SDimitry Andric       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
25922754fe60SDimitry Andric       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
25932754fe60SDimitry Andric     }
25942754fe60SDimitry Andric 
25952754fe60SDimitry Andric     OldGV->eraseFromParent();
25962754fe60SDimitry Andric   }
25972754fe60SDimitry Andric 
259833956c43SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker() &&
259933956c43SDimitry Andric       !GV->hasAvailableExternallyLinkage())
260033956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
260133956c43SDimitry Andric 
26022754fe60SDimitry Andric   return GV;
26032754fe60SDimitry Andric }
26042754fe60SDimitry Andric 
2605f22ef01cSRoman Divacky /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
2606f22ef01cSRoman Divacky /// given global variable.  If Ty is non-null and if the global doesn't exist,
2607cb4dff85SDimitry Andric /// then it will be created with the specified type instead of whatever the
2608e7145dcbSDimitry Andric /// normal requested type would be. If IsForDefinition is true, it is guranteed
2609e7145dcbSDimitry Andric /// that an actual global with type Ty will be returned, not conversion of a
2610e7145dcbSDimitry Andric /// variable with the same mangled name but some other type.
2611f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
2612e7145dcbSDimitry Andric                                                   llvm::Type *Ty,
261344290647SDimitry Andric                                            ForDefinition_t IsForDefinition) {
2614f22ef01cSRoman Divacky   assert(D->hasGlobalStorage() && "Not a global variable");
2615f22ef01cSRoman Divacky   QualType ASTTy = D->getType();
261659d1ed5bSDimitry Andric   if (!Ty)
2617f22ef01cSRoman Divacky     Ty = getTypes().ConvertTypeForMem(ASTTy);
2618f22ef01cSRoman Divacky 
26196122f3e6SDimitry Andric   llvm::PointerType *PTy =
26203b0f4066SDimitry Andric     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
2621f22ef01cSRoman Divacky 
26226122f3e6SDimitry Andric   StringRef MangledName = getMangledName(D);
2623e7145dcbSDimitry Andric   return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
2624f22ef01cSRoman Divacky }
2625f22ef01cSRoman Divacky 
2626f22ef01cSRoman Divacky /// CreateRuntimeVariable - Create a new runtime global variable with the
2627f22ef01cSRoman Divacky /// specified type and name.
2628f22ef01cSRoman Divacky llvm::Constant *
26296122f3e6SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
26306122f3e6SDimitry Andric                                      StringRef Name) {
263159d1ed5bSDimitry Andric   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
2632f22ef01cSRoman Divacky }
2633f22ef01cSRoman Divacky 
2634f22ef01cSRoman Divacky void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
2635f22ef01cSRoman Divacky   assert(!D->getInit() && "Cannot emit definite definitions here!");
2636f22ef01cSRoman Divacky 
26376122f3e6SDimitry Andric   StringRef MangledName = getMangledName(D);
2638e7145dcbSDimitry Andric   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
2639e7145dcbSDimitry Andric 
2640e7145dcbSDimitry Andric   // We already have a definition, not declaration, with the same mangled name.
2641e7145dcbSDimitry Andric   // Emitting of declaration is not required (and actually overwrites emitted
2642e7145dcbSDimitry Andric   // definition).
2643e7145dcbSDimitry Andric   if (GV && !GV->isDeclaration())
2644e7145dcbSDimitry Andric     return;
2645e7145dcbSDimitry Andric 
2646e7145dcbSDimitry Andric   // If we have not seen a reference to this variable yet, place it into the
2647e7145dcbSDimitry Andric   // deferred declarations table to be emitted if needed later.
2648e7145dcbSDimitry Andric   if (!MustBeEmitted(D) && !GV) {
2649f22ef01cSRoman Divacky       DeferredDecls[MangledName] = D;
2650f22ef01cSRoman Divacky       return;
2651f22ef01cSRoman Divacky   }
2652f22ef01cSRoman Divacky 
2653f22ef01cSRoman Divacky   // The tentative definition is the only definition.
2654f22ef01cSRoman Divacky   EmitGlobalVarDefinition(D);
2655f22ef01cSRoman Divacky }
2656f22ef01cSRoman Divacky 
26576122f3e6SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
26582754fe60SDimitry Andric   return Context.toCharUnitsFromBits(
26590623d748SDimitry Andric       getDataLayout().getTypeStoreSizeInBits(Ty));
2660f22ef01cSRoman Divacky }
2661f22ef01cSRoman Divacky 
26629a199699SDimitry Andric LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
26639a199699SDimitry Andric   LangAS AddrSpace = LangAS::Default;
2664c4394386SDimitry Andric   if (LangOpts.OpenCL) {
26659a199699SDimitry Andric     AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
2666c4394386SDimitry Andric     assert(AddrSpace == LangAS::opencl_global ||
2667c4394386SDimitry Andric            AddrSpace == LangAS::opencl_constant ||
2668c4394386SDimitry Andric            AddrSpace == LangAS::opencl_local ||
2669c4394386SDimitry Andric            AddrSpace >= LangAS::FirstTargetAddressSpace);
2670c4394386SDimitry Andric     return AddrSpace;
26717ae0e2c9SDimitry Andric   }
26727ae0e2c9SDimitry Andric 
2673c4394386SDimitry Andric   if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
2674c4394386SDimitry Andric     if (D && D->hasAttr<CUDAConstantAttr>())
2675c4394386SDimitry Andric       return LangAS::cuda_constant;
2676c4394386SDimitry Andric     else if (D && D->hasAttr<CUDASharedAttr>())
2677c4394386SDimitry Andric       return LangAS::cuda_shared;
2678c4394386SDimitry Andric     else
2679c4394386SDimitry Andric       return LangAS::cuda_device;
2680c4394386SDimitry Andric   }
2681c4394386SDimitry Andric 
2682c4394386SDimitry Andric   return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
26837ae0e2c9SDimitry Andric }
26847ae0e2c9SDimitry Andric 
2685284c1978SDimitry Andric template<typename SomeDecl>
2686284c1978SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
2687284c1978SDimitry Andric                                                llvm::GlobalValue *GV) {
2688284c1978SDimitry Andric   if (!getLangOpts().CPlusPlus)
2689284c1978SDimitry Andric     return;
2690284c1978SDimitry Andric 
2691284c1978SDimitry Andric   // Must have 'used' attribute, or else inline assembly can't rely on
2692284c1978SDimitry Andric   // the name existing.
2693284c1978SDimitry Andric   if (!D->template hasAttr<UsedAttr>())
2694284c1978SDimitry Andric     return;
2695284c1978SDimitry Andric 
2696284c1978SDimitry Andric   // Must have internal linkage and an ordinary name.
2697f785676fSDimitry Andric   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
2698284c1978SDimitry Andric     return;
2699284c1978SDimitry Andric 
2700284c1978SDimitry Andric   // Must be in an extern "C" context. Entities declared directly within
2701284c1978SDimitry Andric   // a record are not extern "C" even if the record is in such a context.
2702f785676fSDimitry Andric   const SomeDecl *First = D->getFirstDecl();
2703284c1978SDimitry Andric   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
2704284c1978SDimitry Andric     return;
2705284c1978SDimitry Andric 
2706284c1978SDimitry Andric   // OK, this is an internal linkage entity inside an extern "C" linkage
2707284c1978SDimitry Andric   // specification. Make a note of that so we can give it the "expected"
2708284c1978SDimitry Andric   // mangled name if nothing else is using that name.
2709284c1978SDimitry Andric   std::pair<StaticExternCMap::iterator, bool> R =
2710284c1978SDimitry Andric       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
2711284c1978SDimitry Andric 
2712284c1978SDimitry Andric   // If we have multiple internal linkage entities with the same name
2713284c1978SDimitry Andric   // in extern "C" regions, none of them gets that name.
2714284c1978SDimitry Andric   if (!R.second)
271559d1ed5bSDimitry Andric     R.first->second = nullptr;
2716284c1978SDimitry Andric }
2717284c1978SDimitry Andric 
271833956c43SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
271933956c43SDimitry Andric   if (!CGM.supportsCOMDAT())
272033956c43SDimitry Andric     return false;
272133956c43SDimitry Andric 
272233956c43SDimitry Andric   if (D.hasAttr<SelectAnyAttr>())
272333956c43SDimitry Andric     return true;
272433956c43SDimitry Andric 
272533956c43SDimitry Andric   GVALinkage Linkage;
272633956c43SDimitry Andric   if (auto *VD = dyn_cast<VarDecl>(&D))
272733956c43SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
272833956c43SDimitry Andric   else
272933956c43SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
273033956c43SDimitry Andric 
273133956c43SDimitry Andric   switch (Linkage) {
273233956c43SDimitry Andric   case GVA_Internal:
273333956c43SDimitry Andric   case GVA_AvailableExternally:
273433956c43SDimitry Andric   case GVA_StrongExternal:
273533956c43SDimitry Andric     return false;
273633956c43SDimitry Andric   case GVA_DiscardableODR:
273733956c43SDimitry Andric   case GVA_StrongODR:
273833956c43SDimitry Andric     return true;
273933956c43SDimitry Andric   }
274033956c43SDimitry Andric   llvm_unreachable("No such linkage");
274133956c43SDimitry Andric }
274233956c43SDimitry Andric 
274333956c43SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
274433956c43SDimitry Andric                                           llvm::GlobalObject &GO) {
274533956c43SDimitry Andric   if (!shouldBeInCOMDAT(*this, D))
274633956c43SDimitry Andric     return;
274733956c43SDimitry Andric   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
274833956c43SDimitry Andric }
274933956c43SDimitry Andric 
2750e7145dcbSDimitry Andric /// Pass IsTentative as true if you want to create a tentative definition.
2751e7145dcbSDimitry Andric void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
2752e7145dcbSDimitry Andric                                             bool IsTentative) {
275344290647SDimitry Andric   // OpenCL global variables of sampler type are translated to function calls,
275444290647SDimitry Andric   // therefore no need to be translated.
2755f22ef01cSRoman Divacky   QualType ASTTy = D->getType();
275644290647SDimitry Andric   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
275744290647SDimitry Andric     return;
275844290647SDimitry Andric 
275944290647SDimitry Andric   llvm::Constant *Init = nullptr;
2760dff0c46cSDimitry Andric   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2761dff0c46cSDimitry Andric   bool NeedsGlobalCtor = false;
2762dff0c46cSDimitry Andric   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
2763f22ef01cSRoman Divacky 
2764dff0c46cSDimitry Andric   const VarDecl *InitDecl;
2765dff0c46cSDimitry Andric   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
2766f22ef01cSRoman Divacky 
27679a199699SDimitry Andric   Optional<ConstantEmitter> emitter;
27689a199699SDimitry Andric 
2769e7145dcbSDimitry Andric   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
2770e7145dcbSDimitry Andric   // as part of their declaration."  Sema has already checked for
2771e7145dcbSDimitry Andric   // error cases, so we just need to set Init to UndefValue.
2772e7145dcbSDimitry Andric   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
2773e7145dcbSDimitry Andric       D->hasAttr<CUDASharedAttr>())
27740623d748SDimitry Andric     Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
2775e7145dcbSDimitry Andric   else if (!InitExpr) {
2776f22ef01cSRoman Divacky     // This is a tentative definition; tentative definitions are
2777f22ef01cSRoman Divacky     // implicitly initialized with { 0 }.
2778f22ef01cSRoman Divacky     //
2779f22ef01cSRoman Divacky     // Note that tentative definitions are only emitted at the end of
2780f22ef01cSRoman Divacky     // a translation unit, so they should never have incomplete
2781f22ef01cSRoman Divacky     // type. In addition, EmitTentativeDefinition makes sure that we
2782f22ef01cSRoman Divacky     // never attempt to emit a tentative definition if a real one
2783f22ef01cSRoman Divacky     // exists. A use may still exists, however, so we still may need
2784f22ef01cSRoman Divacky     // to do a RAUW.
2785f22ef01cSRoman Divacky     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
2786f22ef01cSRoman Divacky     Init = EmitNullConstant(D->getType());
2787f22ef01cSRoman Divacky   } else {
27887ae0e2c9SDimitry Andric     initializedGlobalDecl = GlobalDecl(D);
27899a199699SDimitry Andric     emitter.emplace(*this);
27909a199699SDimitry Andric     Init = emitter->tryEmitForInitializer(*InitDecl);
2791f785676fSDimitry Andric 
2792f22ef01cSRoman Divacky     if (!Init) {
2793f22ef01cSRoman Divacky       QualType T = InitExpr->getType();
2794f22ef01cSRoman Divacky       if (D->getType()->isReferenceType())
2795f22ef01cSRoman Divacky         T = D->getType();
2796f22ef01cSRoman Divacky 
2797dff0c46cSDimitry Andric       if (getLangOpts().CPlusPlus) {
2798f22ef01cSRoman Divacky         Init = EmitNullConstant(T);
2799dff0c46cSDimitry Andric         NeedsGlobalCtor = true;
2800f22ef01cSRoman Divacky       } else {
2801f22ef01cSRoman Divacky         ErrorUnsupported(D, "static initializer");
2802f22ef01cSRoman Divacky         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
2803f22ef01cSRoman Divacky       }
2804e580952dSDimitry Andric     } else {
2805e580952dSDimitry Andric       // We don't need an initializer, so remove the entry for the delayed
2806dff0c46cSDimitry Andric       // initializer position (just in case this entry was delayed) if we
2807dff0c46cSDimitry Andric       // also don't need to register a destructor.
2808dff0c46cSDimitry Andric       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
2809e580952dSDimitry Andric         DelayedCXXInitPosition.erase(D);
2810f22ef01cSRoman Divacky     }
2811f22ef01cSRoman Divacky   }
2812f22ef01cSRoman Divacky 
28136122f3e6SDimitry Andric   llvm::Type* InitType = Init->getType();
2814e7145dcbSDimitry Andric   llvm::Constant *Entry =
281544290647SDimitry Andric       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
2816f22ef01cSRoman Divacky 
2817f22ef01cSRoman Divacky   // Strip off a bitcast if we got one back.
281859d1ed5bSDimitry Andric   if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2819f22ef01cSRoman Divacky     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2820f785676fSDimitry Andric            CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2821f785676fSDimitry Andric            // All zero index gep.
2822f22ef01cSRoman Divacky            CE->getOpcode() == llvm::Instruction::GetElementPtr);
2823f22ef01cSRoman Divacky     Entry = CE->getOperand(0);
2824f22ef01cSRoman Divacky   }
2825f22ef01cSRoman Divacky 
2826f22ef01cSRoman Divacky   // Entry is now either a Function or GlobalVariable.
282759d1ed5bSDimitry Andric   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
2828f22ef01cSRoman Divacky 
2829f22ef01cSRoman Divacky   // We have a definition after a declaration with the wrong type.
2830f22ef01cSRoman Divacky   // We must make a new GlobalVariable* and update everything that used OldGV
2831f22ef01cSRoman Divacky   // (a declaration or tentative definition) with the new GlobalVariable*
2832f22ef01cSRoman Divacky   // (which will be a definition).
2833f22ef01cSRoman Divacky   //
2834f22ef01cSRoman Divacky   // This happens if there is a prototype for a global (e.g.
2835f22ef01cSRoman Divacky   // "extern int x[];") and then a definition of a different type (e.g.
2836f22ef01cSRoman Divacky   // "int x[10];"). This also happens when an initializer has a different type
2837f22ef01cSRoman Divacky   // from the type of the global (this happens with unions).
2838c4394386SDimitry Andric   if (!GV || GV->getType()->getElementType() != InitType ||
28393b0f4066SDimitry Andric       GV->getType()->getAddressSpace() !=
2840c4394386SDimitry Andric           getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
2841f22ef01cSRoman Divacky 
2842f22ef01cSRoman Divacky     // Move the old entry aside so that we'll create a new one.
28436122f3e6SDimitry Andric     Entry->setName(StringRef());
2844f22ef01cSRoman Divacky 
2845f22ef01cSRoman Divacky     // Make a new global with the correct type, this is now guaranteed to work.
2846e7145dcbSDimitry Andric     GV = cast<llvm::GlobalVariable>(
284744290647SDimitry Andric         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
2848f22ef01cSRoman Divacky 
2849f22ef01cSRoman Divacky     // Replace all uses of the old global with the new global
2850f22ef01cSRoman Divacky     llvm::Constant *NewPtrForOldDecl =
2851f22ef01cSRoman Divacky         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2852f22ef01cSRoman Divacky     Entry->replaceAllUsesWith(NewPtrForOldDecl);
2853f22ef01cSRoman Divacky 
2854f22ef01cSRoman Divacky     // Erase the old global, since it is no longer used.
2855f22ef01cSRoman Divacky     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2856f22ef01cSRoman Divacky   }
2857f22ef01cSRoman Divacky 
2858284c1978SDimitry Andric   MaybeHandleStaticInExternC(D, GV);
2859284c1978SDimitry Andric 
28606122f3e6SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
28616122f3e6SDimitry Andric     AddGlobalAnnotations(D, GV);
2862f22ef01cSRoman Divacky 
2863e7145dcbSDimitry Andric   // Set the llvm linkage type as appropriate.
2864e7145dcbSDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
2865e7145dcbSDimitry Andric       getLLVMLinkageVarDefinition(D, GV->isConstant());
2866e7145dcbSDimitry Andric 
28670623d748SDimitry Andric   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
28680623d748SDimitry Andric   // the device. [...]"
28690623d748SDimitry Andric   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
28700623d748SDimitry Andric   // __device__, declares a variable that: [...]
28710623d748SDimitry Andric   // Is accessible from all the threads within the grid and from the host
28720623d748SDimitry Andric   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
28730623d748SDimitry Andric   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
2874e7145dcbSDimitry Andric   if (GV && LangOpts.CUDA) {
2875e7145dcbSDimitry Andric     if (LangOpts.CUDAIsDevice) {
2876e7145dcbSDimitry Andric       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
28770623d748SDimitry Andric         GV->setExternallyInitialized(true);
2878e7145dcbSDimitry Andric     } else {
2879e7145dcbSDimitry Andric       // Host-side shadows of external declarations of device-side
2880e7145dcbSDimitry Andric       // global variables become internal definitions. These have to
2881e7145dcbSDimitry Andric       // be internal in order to prevent name conflicts with global
2882e7145dcbSDimitry Andric       // host variables with the same name in a different TUs.
2883e7145dcbSDimitry Andric       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
2884e7145dcbSDimitry Andric         Linkage = llvm::GlobalValue::InternalLinkage;
2885e7145dcbSDimitry Andric 
2886e7145dcbSDimitry Andric         // Shadow variables and their properties must be registered
2887e7145dcbSDimitry Andric         // with CUDA runtime.
2888e7145dcbSDimitry Andric         unsigned Flags = 0;
2889e7145dcbSDimitry Andric         if (!D->hasDefinition())
2890e7145dcbSDimitry Andric           Flags |= CGCUDARuntime::ExternDeviceVar;
2891e7145dcbSDimitry Andric         if (D->hasAttr<CUDAConstantAttr>())
2892e7145dcbSDimitry Andric           Flags |= CGCUDARuntime::ConstantDeviceVar;
2893e7145dcbSDimitry Andric         getCUDARuntime().registerDeviceVar(*GV, Flags);
2894e7145dcbSDimitry Andric       } else if (D->hasAttr<CUDASharedAttr>())
2895e7145dcbSDimitry Andric         // __shared__ variables are odd. Shadows do get created, but
2896e7145dcbSDimitry Andric         // they are not registered with the CUDA runtime, so they
2897e7145dcbSDimitry Andric         // can't really be used to access their device-side
2898e7145dcbSDimitry Andric         // counterparts. It's not clear yet whether it's nvcc's bug or
2899e7145dcbSDimitry Andric         // a feature, but we've got to do the same for compatibility.
2900e7145dcbSDimitry Andric         Linkage = llvm::GlobalValue::InternalLinkage;
2901e7145dcbSDimitry Andric     }
29020623d748SDimitry Andric   }
29039a199699SDimitry Andric 
2904f22ef01cSRoman Divacky   GV->setInitializer(Init);
29059a199699SDimitry Andric   if (emitter) emitter->finalize(GV);
2906f22ef01cSRoman Divacky 
2907f22ef01cSRoman Divacky   // If it is safe to mark the global 'constant', do so now.
2908dff0c46cSDimitry Andric   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2909dff0c46cSDimitry Andric                   isTypeConstant(D->getType(), true));
2910f22ef01cSRoman Divacky 
291139d628a0SDimitry Andric   // If it is in a read-only section, mark it 'constant'.
291239d628a0SDimitry Andric   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
291339d628a0SDimitry Andric     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
291439d628a0SDimitry Andric     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
291539d628a0SDimitry Andric       GV->setConstant(true);
291639d628a0SDimitry Andric   }
291739d628a0SDimitry Andric 
2918f22ef01cSRoman Divacky   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2919f22ef01cSRoman Divacky 
2920f785676fSDimitry Andric 
29210623d748SDimitry Andric   // On Darwin, if the normal linkage of a C++ thread_local variable is
29220623d748SDimitry Andric   // LinkOnce or Weak, we keep the normal linkage to prevent multiple
29230623d748SDimitry Andric   // copies within a linkage unit; otherwise, the backing variable has
29240623d748SDimitry Andric   // internal linkage and all accesses should just be calls to the
292559d1ed5bSDimitry Andric   // Itanium-specified entry point, which has the normal linkage of the
29260623d748SDimitry Andric   // variable. This is to preserve the ability to change the implementation
29270623d748SDimitry Andric   // behind the scenes.
292839d628a0SDimitry Andric   if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
29290623d748SDimitry Andric       Context.getTargetInfo().getTriple().isOSDarwin() &&
29300623d748SDimitry Andric       !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
29310623d748SDimitry Andric       !llvm::GlobalVariable::isWeakLinkage(Linkage))
293259d1ed5bSDimitry Andric     Linkage = llvm::GlobalValue::InternalLinkage;
293359d1ed5bSDimitry Andric 
293459d1ed5bSDimitry Andric   GV->setLinkage(Linkage);
293559d1ed5bSDimitry Andric   if (D->hasAttr<DLLImportAttr>())
293659d1ed5bSDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
293759d1ed5bSDimitry Andric   else if (D->hasAttr<DLLExportAttr>())
293859d1ed5bSDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
293939d628a0SDimitry Andric   else
294039d628a0SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2941f785676fSDimitry Andric 
294244290647SDimitry Andric   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
2943f22ef01cSRoman Divacky     // common vars aren't constant even if declared const.
2944f22ef01cSRoman Divacky     GV->setConstant(false);
294544290647SDimitry Andric     // Tentative definition of global variables may be initialized with
294644290647SDimitry Andric     // non-zero null pointers. In this case they should have weak linkage
294744290647SDimitry Andric     // since common linkage must have zero initializer and must not have
294844290647SDimitry Andric     // explicit section therefore cannot have non-zero initial value.
294944290647SDimitry Andric     if (!GV->getInitializer()->isNullValue())
295044290647SDimitry Andric       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
295144290647SDimitry Andric   }
2952f22ef01cSRoman Divacky 
295359d1ed5bSDimitry Andric   setNonAliasAttributes(D, GV);
2954f22ef01cSRoman Divacky 
295539d628a0SDimitry Andric   if (D->getTLSKind() && !GV->isThreadLocal()) {
295639d628a0SDimitry Andric     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
29570623d748SDimitry Andric       CXXThreadLocals.push_back(D);
295839d628a0SDimitry Andric     setTLSMode(GV, *D);
295939d628a0SDimitry Andric   }
296039d628a0SDimitry Andric 
296133956c43SDimitry Andric   maybeSetTrivialComdat(*D, *GV);
296233956c43SDimitry Andric 
29632754fe60SDimitry Andric   // Emit the initializer function if necessary.
2964dff0c46cSDimitry Andric   if (NeedsGlobalCtor || NeedsGlobalDtor)
2965dff0c46cSDimitry Andric     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
29662754fe60SDimitry Andric 
296739d628a0SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
29683861d79fSDimitry Andric 
2969f22ef01cSRoman Divacky   // Emit global variable debug information.
29706122f3e6SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
2971e7145dcbSDimitry Andric     if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
2972f22ef01cSRoman Divacky       DI->EmitGlobalVariable(GV, D);
2973f22ef01cSRoman Divacky }
2974f22ef01cSRoman Divacky 
297539d628a0SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context,
297633956c43SDimitry Andric                                       CodeGenModule &CGM, const VarDecl *D,
297733956c43SDimitry Andric                                       bool NoCommon) {
297859d1ed5bSDimitry Andric   // Don't give variables common linkage if -fno-common was specified unless it
297959d1ed5bSDimitry Andric   // was overridden by a NoCommon attribute.
298059d1ed5bSDimitry Andric   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
298159d1ed5bSDimitry Andric     return true;
298259d1ed5bSDimitry Andric 
298359d1ed5bSDimitry Andric   // C11 6.9.2/2:
298459d1ed5bSDimitry Andric   //   A declaration of an identifier for an object that has file scope without
298559d1ed5bSDimitry Andric   //   an initializer, and without a storage-class specifier or with the
298659d1ed5bSDimitry Andric   //   storage-class specifier static, constitutes a tentative definition.
298759d1ed5bSDimitry Andric   if (D->getInit() || D->hasExternalStorage())
298859d1ed5bSDimitry Andric     return true;
298959d1ed5bSDimitry Andric 
299059d1ed5bSDimitry Andric   // A variable cannot be both common and exist in a section.
299159d1ed5bSDimitry Andric   if (D->hasAttr<SectionAttr>())
299259d1ed5bSDimitry Andric     return true;
299359d1ed5bSDimitry Andric 
2994db17bf38SDimitry Andric   // A variable cannot be both common and exist in a section.
2995db17bf38SDimitry Andric   // We dont try to determine which is the right section in the front-end.
2996db17bf38SDimitry Andric   // If no specialized section name is applicable, it will resort to default.
2997db17bf38SDimitry Andric   if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
2998db17bf38SDimitry Andric       D->hasAttr<PragmaClangDataSectionAttr>() ||
2999db17bf38SDimitry Andric       D->hasAttr<PragmaClangRodataSectionAttr>())
3000db17bf38SDimitry Andric     return true;
3001db17bf38SDimitry Andric 
300259d1ed5bSDimitry Andric   // Thread local vars aren't considered common linkage.
300359d1ed5bSDimitry Andric   if (D->getTLSKind())
300459d1ed5bSDimitry Andric     return true;
300559d1ed5bSDimitry Andric 
300659d1ed5bSDimitry Andric   // Tentative definitions marked with WeakImportAttr are true definitions.
300759d1ed5bSDimitry Andric   if (D->hasAttr<WeakImportAttr>())
300859d1ed5bSDimitry Andric     return true;
300959d1ed5bSDimitry Andric 
301033956c43SDimitry Andric   // A variable cannot be both common and exist in a comdat.
301133956c43SDimitry Andric   if (shouldBeInCOMDAT(CGM, *D))
301233956c43SDimitry Andric     return true;
301333956c43SDimitry Andric 
3014e7145dcbSDimitry Andric   // Declarations with a required alignment do not have common linkage in MSVC
301539d628a0SDimitry Andric   // mode.
30160623d748SDimitry Andric   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
301733956c43SDimitry Andric     if (D->hasAttr<AlignedAttr>())
301839d628a0SDimitry Andric       return true;
301933956c43SDimitry Andric     QualType VarType = D->getType();
302033956c43SDimitry Andric     if (Context.isAlignmentRequired(VarType))
302133956c43SDimitry Andric       return true;
302233956c43SDimitry Andric 
302333956c43SDimitry Andric     if (const auto *RT = VarType->getAs<RecordType>()) {
302433956c43SDimitry Andric       const RecordDecl *RD = RT->getDecl();
302533956c43SDimitry Andric       for (const FieldDecl *FD : RD->fields()) {
302633956c43SDimitry Andric         if (FD->isBitField())
302733956c43SDimitry Andric           continue;
302833956c43SDimitry Andric         if (FD->hasAttr<AlignedAttr>())
302933956c43SDimitry Andric           return true;
303033956c43SDimitry Andric         if (Context.isAlignmentRequired(FD->getType()))
303133956c43SDimitry Andric           return true;
303233956c43SDimitry Andric       }
303333956c43SDimitry Andric     }
303433956c43SDimitry Andric   }
303539d628a0SDimitry Andric 
303659d1ed5bSDimitry Andric   return false;
303759d1ed5bSDimitry Andric }
303859d1ed5bSDimitry Andric 
303959d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
304059d1ed5bSDimitry Andric     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
30412754fe60SDimitry Andric   if (Linkage == GVA_Internal)
30422754fe60SDimitry Andric     return llvm::Function::InternalLinkage;
304359d1ed5bSDimitry Andric 
304459d1ed5bSDimitry Andric   if (D->hasAttr<WeakAttr>()) {
304559d1ed5bSDimitry Andric     if (IsConstantVariable)
304659d1ed5bSDimitry Andric       return llvm::GlobalVariable::WeakODRLinkage;
304759d1ed5bSDimitry Andric     else
304859d1ed5bSDimitry Andric       return llvm::GlobalVariable::WeakAnyLinkage;
304959d1ed5bSDimitry Andric   }
305059d1ed5bSDimitry Andric 
305159d1ed5bSDimitry Andric   // We are guaranteed to have a strong definition somewhere else,
305259d1ed5bSDimitry Andric   // so we can use available_externally linkage.
305359d1ed5bSDimitry Andric   if (Linkage == GVA_AvailableExternally)
305420e90f04SDimitry Andric     return llvm::GlobalValue::AvailableExternallyLinkage;
305559d1ed5bSDimitry Andric 
305659d1ed5bSDimitry Andric   // Note that Apple's kernel linker doesn't support symbol
305759d1ed5bSDimitry Andric   // coalescing, so we need to avoid linkonce and weak linkages there.
305859d1ed5bSDimitry Andric   // Normally, this means we just map to internal, but for explicit
305959d1ed5bSDimitry Andric   // instantiations we'll map to external.
306059d1ed5bSDimitry Andric 
306159d1ed5bSDimitry Andric   // In C++, the compiler has to emit a definition in every translation unit
306259d1ed5bSDimitry Andric   // that references the function.  We should use linkonce_odr because
306359d1ed5bSDimitry Andric   // a) if all references in this translation unit are optimized away, we
306459d1ed5bSDimitry Andric   // don't need to codegen it.  b) if the function persists, it needs to be
306559d1ed5bSDimitry Andric   // merged with other definitions. c) C++ has the ODR, so we know the
306659d1ed5bSDimitry Andric   // definition is dependable.
306759d1ed5bSDimitry Andric   if (Linkage == GVA_DiscardableODR)
306859d1ed5bSDimitry Andric     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
306959d1ed5bSDimitry Andric                                             : llvm::Function::InternalLinkage;
307059d1ed5bSDimitry Andric 
307159d1ed5bSDimitry Andric   // An explicit instantiation of a template has weak linkage, since
307259d1ed5bSDimitry Andric   // explicit instantiations can occur in multiple translation units
307359d1ed5bSDimitry Andric   // and must all be equivalent. However, we are not allowed to
307459d1ed5bSDimitry Andric   // throw away these explicit instantiations.
3075e7145dcbSDimitry Andric   //
3076e7145dcbSDimitry Andric   // We don't currently support CUDA device code spread out across multiple TUs,
3077e7145dcbSDimitry Andric   // so say that CUDA templates are either external (for kernels) or internal.
3078e7145dcbSDimitry Andric   // This lets llvm perform aggressive inter-procedural optimizations.
3079e7145dcbSDimitry Andric   if (Linkage == GVA_StrongODR) {
3080e7145dcbSDimitry Andric     if (Context.getLangOpts().AppleKext)
3081e7145dcbSDimitry Andric       return llvm::Function::ExternalLinkage;
3082e7145dcbSDimitry Andric     if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
3083e7145dcbSDimitry Andric       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
3084e7145dcbSDimitry Andric                                           : llvm::Function::InternalLinkage;
3085e7145dcbSDimitry Andric     return llvm::Function::WeakODRLinkage;
3086e7145dcbSDimitry Andric   }
308759d1ed5bSDimitry Andric 
308859d1ed5bSDimitry Andric   // C++ doesn't have tentative definitions and thus cannot have common
308959d1ed5bSDimitry Andric   // linkage.
309059d1ed5bSDimitry Andric   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
309133956c43SDimitry Andric       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
309239d628a0SDimitry Andric                                  CodeGenOpts.NoCommon))
309359d1ed5bSDimitry Andric     return llvm::GlobalVariable::CommonLinkage;
309459d1ed5bSDimitry Andric 
3095f785676fSDimitry Andric   // selectany symbols are externally visible, so use weak instead of
3096f785676fSDimitry Andric   // linkonce.  MSVC optimizes away references to const selectany globals, so
3097f785676fSDimitry Andric   // all definitions should be the same and ODR linkage should be used.
3098f785676fSDimitry Andric   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
309959d1ed5bSDimitry Andric   if (D->hasAttr<SelectAnyAttr>())
3100f785676fSDimitry Andric     return llvm::GlobalVariable::WeakODRLinkage;
310159d1ed5bSDimitry Andric 
310259d1ed5bSDimitry Andric   // Otherwise, we have strong external linkage.
310359d1ed5bSDimitry Andric   assert(Linkage == GVA_StrongExternal);
31042754fe60SDimitry Andric   return llvm::GlobalVariable::ExternalLinkage;
31052754fe60SDimitry Andric }
31062754fe60SDimitry Andric 
310759d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
310859d1ed5bSDimitry Andric     const VarDecl *VD, bool IsConstant) {
310959d1ed5bSDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
311059d1ed5bSDimitry Andric   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
311159d1ed5bSDimitry Andric }
311259d1ed5bSDimitry Andric 
3113139f7f9bSDimitry Andric /// Replace the uses of a function that was declared with a non-proto type.
3114139f7f9bSDimitry Andric /// We want to silently drop extra arguments from call sites
3115139f7f9bSDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
3116139f7f9bSDimitry Andric                                           llvm::Function *newFn) {
3117139f7f9bSDimitry Andric   // Fast path.
3118139f7f9bSDimitry Andric   if (old->use_empty()) return;
3119139f7f9bSDimitry Andric 
3120139f7f9bSDimitry Andric   llvm::Type *newRetTy = newFn->getReturnType();
3121139f7f9bSDimitry Andric   SmallVector<llvm::Value*, 4> newArgs;
31220623d748SDimitry Andric   SmallVector<llvm::OperandBundleDef, 1> newBundles;
3123139f7f9bSDimitry Andric 
3124139f7f9bSDimitry Andric   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
3125139f7f9bSDimitry Andric          ui != ue; ) {
3126139f7f9bSDimitry Andric     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
312759d1ed5bSDimitry Andric     llvm::User *user = use->getUser();
3128139f7f9bSDimitry Andric 
3129139f7f9bSDimitry Andric     // Recognize and replace uses of bitcasts.  Most calls to
3130139f7f9bSDimitry Andric     // unprototyped functions will use bitcasts.
313159d1ed5bSDimitry Andric     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
3132139f7f9bSDimitry Andric       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
3133139f7f9bSDimitry Andric         replaceUsesOfNonProtoConstant(bitcast, newFn);
3134139f7f9bSDimitry Andric       continue;
3135139f7f9bSDimitry Andric     }
3136139f7f9bSDimitry Andric 
3137139f7f9bSDimitry Andric     // Recognize calls to the function.
3138139f7f9bSDimitry Andric     llvm::CallSite callSite(user);
3139139f7f9bSDimitry Andric     if (!callSite) continue;
314059d1ed5bSDimitry Andric     if (!callSite.isCallee(&*use)) continue;
3141139f7f9bSDimitry Andric 
3142139f7f9bSDimitry Andric     // If the return types don't match exactly, then we can't
3143139f7f9bSDimitry Andric     // transform this call unless it's dead.
3144139f7f9bSDimitry Andric     if (callSite->getType() != newRetTy && !callSite->use_empty())
3145139f7f9bSDimitry Andric       continue;
3146139f7f9bSDimitry Andric 
3147139f7f9bSDimitry Andric     // Get the call site's attribute list.
314820e90f04SDimitry Andric     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
314920e90f04SDimitry Andric     llvm::AttributeList oldAttrs = callSite.getAttributes();
3150139f7f9bSDimitry Andric 
3151139f7f9bSDimitry Andric     // If the function was passed too few arguments, don't transform.
3152139f7f9bSDimitry Andric     unsigned newNumArgs = newFn->arg_size();
3153139f7f9bSDimitry Andric     if (callSite.arg_size() < newNumArgs) continue;
3154139f7f9bSDimitry Andric 
3155139f7f9bSDimitry Andric     // If extra arguments were passed, we silently drop them.
3156139f7f9bSDimitry Andric     // If any of the types mismatch, we don't transform.
3157139f7f9bSDimitry Andric     unsigned argNo = 0;
3158139f7f9bSDimitry Andric     bool dontTransform = false;
315920e90f04SDimitry Andric     for (llvm::Argument &A : newFn->args()) {
316020e90f04SDimitry Andric       if (callSite.getArgument(argNo)->getType() != A.getType()) {
3161139f7f9bSDimitry Andric         dontTransform = true;
3162139f7f9bSDimitry Andric         break;
3163139f7f9bSDimitry Andric       }
3164139f7f9bSDimitry Andric 
3165139f7f9bSDimitry Andric       // Add any parameter attributes.
316620e90f04SDimitry Andric       newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
316720e90f04SDimitry Andric       argNo++;
3168139f7f9bSDimitry Andric     }
3169139f7f9bSDimitry Andric     if (dontTransform)
3170139f7f9bSDimitry Andric       continue;
3171139f7f9bSDimitry Andric 
3172139f7f9bSDimitry Andric     // Okay, we can transform this.  Create the new call instruction and copy
3173139f7f9bSDimitry Andric     // over the required information.
3174139f7f9bSDimitry Andric     newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
3175139f7f9bSDimitry Andric 
31760623d748SDimitry Andric     // Copy over any operand bundles.
31770623d748SDimitry Andric     callSite.getOperandBundlesAsDefs(newBundles);
31780623d748SDimitry Andric 
3179139f7f9bSDimitry Andric     llvm::CallSite newCall;
3180139f7f9bSDimitry Andric     if (callSite.isCall()) {
31810623d748SDimitry Andric       newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
3182139f7f9bSDimitry Andric                                        callSite.getInstruction());
3183139f7f9bSDimitry Andric     } else {
318459d1ed5bSDimitry Andric       auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
3185139f7f9bSDimitry Andric       newCall = llvm::InvokeInst::Create(newFn,
3186139f7f9bSDimitry Andric                                          oldInvoke->getNormalDest(),
3187139f7f9bSDimitry Andric                                          oldInvoke->getUnwindDest(),
31880623d748SDimitry Andric                                          newArgs, newBundles, "",
3189139f7f9bSDimitry Andric                                          callSite.getInstruction());
3190139f7f9bSDimitry Andric     }
3191139f7f9bSDimitry Andric     newArgs.clear(); // for the next iteration
3192139f7f9bSDimitry Andric 
3193139f7f9bSDimitry Andric     if (!newCall->getType()->isVoidTy())
3194139f7f9bSDimitry Andric       newCall->takeName(callSite.getInstruction());
319520e90f04SDimitry Andric     newCall.setAttributes(llvm::AttributeList::get(
319620e90f04SDimitry Andric         newFn->getContext(), oldAttrs.getFnAttributes(),
319720e90f04SDimitry Andric         oldAttrs.getRetAttributes(), newArgAttrs));
3198139f7f9bSDimitry Andric     newCall.setCallingConv(callSite.getCallingConv());
3199139f7f9bSDimitry Andric 
3200139f7f9bSDimitry Andric     // Finally, remove the old call, replacing any uses with the new one.
3201139f7f9bSDimitry Andric     if (!callSite->use_empty())
3202139f7f9bSDimitry Andric       callSite->replaceAllUsesWith(newCall.getInstruction());
3203139f7f9bSDimitry Andric 
3204139f7f9bSDimitry Andric     // Copy debug location attached to CI.
320533956c43SDimitry Andric     if (callSite->getDebugLoc())
3206139f7f9bSDimitry Andric       newCall->setDebugLoc(callSite->getDebugLoc());
32070623d748SDimitry Andric 
3208139f7f9bSDimitry Andric     callSite->eraseFromParent();
3209139f7f9bSDimitry Andric   }
3210139f7f9bSDimitry Andric }
3211139f7f9bSDimitry Andric 
3212f22ef01cSRoman Divacky /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
3213f22ef01cSRoman Divacky /// implement a function with no prototype, e.g. "int foo() {}".  If there are
3214f22ef01cSRoman Divacky /// existing call uses of the old function in the module, this adjusts them to
3215f22ef01cSRoman Divacky /// call the new function directly.
3216f22ef01cSRoman Divacky ///
3217f22ef01cSRoman Divacky /// This is not just a cleanup: the always_inline pass requires direct calls to
3218f22ef01cSRoman Divacky /// functions to be able to inline them.  If there is a bitcast in the way, it
3219f22ef01cSRoman Divacky /// won't inline them.  Instcombine normally deletes these calls, but it isn't
3220f22ef01cSRoman Divacky /// run at -O0.
3221f22ef01cSRoman Divacky static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3222f22ef01cSRoman Divacky                                                       llvm::Function *NewFn) {
3223f22ef01cSRoman Divacky   // If we're redefining a global as a function, don't transform it.
3224139f7f9bSDimitry Andric   if (!isa<llvm::Function>(Old)) return;
3225f22ef01cSRoman Divacky 
3226139f7f9bSDimitry Andric   replaceUsesOfNonProtoConstant(Old, NewFn);
3227f22ef01cSRoman Divacky }
3228f22ef01cSRoman Divacky 
3229dff0c46cSDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
3230e7145dcbSDimitry Andric   auto DK = VD->isThisDeclarationADefinition();
3231e7145dcbSDimitry Andric   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
3232e7145dcbSDimitry Andric     return;
3233e7145dcbSDimitry Andric 
3234dff0c46cSDimitry Andric   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
3235dff0c46cSDimitry Andric   // If we have a definition, this might be a deferred decl. If the
3236dff0c46cSDimitry Andric   // instantiation is explicit, make sure we emit it at the end.
3237dff0c46cSDimitry Andric   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
3238dff0c46cSDimitry Andric     GetAddrOfGlobalVar(VD);
3239139f7f9bSDimitry Andric 
3240139f7f9bSDimitry Andric   EmitTopLevelDecl(VD);
3241dff0c46cSDimitry Andric }
3242f22ef01cSRoman Divacky 
324359d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
324459d1ed5bSDimitry Andric                                                  llvm::GlobalValue *GV) {
324559d1ed5bSDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
32463b0f4066SDimitry Andric 
32473b0f4066SDimitry Andric   // Compute the function info and LLVM type.
3248dff0c46cSDimitry Andric   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3249dff0c46cSDimitry Andric   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
32503b0f4066SDimitry Andric 
3251f22ef01cSRoman Divacky   // Get or create the prototype for the function.
32520623d748SDimitry Andric   if (!GV || (GV->getType()->getElementType() != Ty))
32530623d748SDimitry Andric     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
32540623d748SDimitry Andric                                                    /*DontDefer=*/true,
325544290647SDimitry Andric                                                    ForDefinition));
3256f22ef01cSRoman Divacky 
32570623d748SDimitry Andric   // Already emitted.
32580623d748SDimitry Andric   if (!GV->isDeclaration())
3259f785676fSDimitry Andric     return;
3260f22ef01cSRoman Divacky 
32612754fe60SDimitry Andric   // We need to set linkage and visibility on the function before
32622754fe60SDimitry Andric   // generating code for it because various parts of IR generation
32632754fe60SDimitry Andric   // want to propagate this information down (e.g. to local static
32642754fe60SDimitry Andric   // declarations).
326559d1ed5bSDimitry Andric   auto *Fn = cast<llvm::Function>(GV);
3266f785676fSDimitry Andric   setFunctionLinkage(GD, Fn);
326797bc6c73SDimitry Andric   setFunctionDLLStorageClass(GD, Fn);
3268f22ef01cSRoman Divacky 
326959d1ed5bSDimitry Andric   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
32709a199699SDimitry Andric   setGlobalVisibility(Fn, D, ForDefinition);
32712754fe60SDimitry Andric 
3272284c1978SDimitry Andric   MaybeHandleStaticInExternC(D, Fn);
3273284c1978SDimitry Andric 
327433956c43SDimitry Andric   maybeSetTrivialComdat(*D, *Fn);
327533956c43SDimitry Andric 
32763b0f4066SDimitry Andric   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
3277f22ef01cSRoman Divacky 
327859d1ed5bSDimitry Andric   setFunctionDefinitionAttributes(D, Fn);
3279f22ef01cSRoman Divacky   SetLLVMFunctionAttributesForDefinition(D, Fn);
3280f22ef01cSRoman Divacky 
3281f22ef01cSRoman Divacky   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
3282f22ef01cSRoman Divacky     AddGlobalCtor(Fn, CA->getPriority());
3283f22ef01cSRoman Divacky   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
3284f22ef01cSRoman Divacky     AddGlobalDtor(Fn, DA->getPriority());
32856122f3e6SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
32866122f3e6SDimitry Andric     AddGlobalAnnotations(D, Fn);
3287f22ef01cSRoman Divacky }
3288f22ef01cSRoman Divacky 
3289f22ef01cSRoman Divacky void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
329059d1ed5bSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
3291f22ef01cSRoman Divacky   const AliasAttr *AA = D->getAttr<AliasAttr>();
3292f22ef01cSRoman Divacky   assert(AA && "Not an alias?");
3293f22ef01cSRoman Divacky 
32946122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
3295f22ef01cSRoman Divacky 
32969a4b3118SDimitry Andric   if (AA->getAliasee() == MangledName) {
3297e7145dcbSDimitry Andric     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
32989a4b3118SDimitry Andric     return;
32999a4b3118SDimitry Andric   }
33009a4b3118SDimitry Andric 
3301f22ef01cSRoman Divacky   // If there is a definition in the module, then it wins over the alias.
3302f22ef01cSRoman Divacky   // This is dubious, but allow it to be safe.  Just ignore the alias.
3303f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3304f22ef01cSRoman Divacky   if (Entry && !Entry->isDeclaration())
3305f22ef01cSRoman Divacky     return;
3306f22ef01cSRoman Divacky 
3307f785676fSDimitry Andric   Aliases.push_back(GD);
3308f785676fSDimitry Andric 
33096122f3e6SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3310f22ef01cSRoman Divacky 
3311f22ef01cSRoman Divacky   // Create a reference to the named value.  This ensures that it is emitted
3312f22ef01cSRoman Divacky   // if a deferred decl.
3313f22ef01cSRoman Divacky   llvm::Constant *Aliasee;
3314f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(DeclTy))
33153861d79fSDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
33162754fe60SDimitry Andric                                       /*ForVTable=*/false);
3317f22ef01cSRoman Divacky   else
3318f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
331959d1ed5bSDimitry Andric                                     llvm::PointerType::getUnqual(DeclTy),
332039d628a0SDimitry Andric                                     /*D=*/nullptr);
3321f22ef01cSRoman Divacky 
3322f22ef01cSRoman Divacky   // Create the new alias itself, but don't set a name yet.
332359d1ed5bSDimitry Andric   auto *GA = llvm::GlobalAlias::create(
33240623d748SDimitry Andric       DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
3325f22ef01cSRoman Divacky 
3326f22ef01cSRoman Divacky   if (Entry) {
332759d1ed5bSDimitry Andric     if (GA->getAliasee() == Entry) {
3328e7145dcbSDimitry Andric       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
332959d1ed5bSDimitry Andric       return;
333059d1ed5bSDimitry Andric     }
333159d1ed5bSDimitry Andric 
3332f22ef01cSRoman Divacky     assert(Entry->isDeclaration());
3333f22ef01cSRoman Divacky 
3334f22ef01cSRoman Divacky     // If there is a declaration in the module, then we had an extern followed
3335f22ef01cSRoman Divacky     // by the alias, as in:
3336f22ef01cSRoman Divacky     //   extern int test6();
3337f22ef01cSRoman Divacky     //   ...
3338f22ef01cSRoman Divacky     //   int test6() __attribute__((alias("test7")));
3339f22ef01cSRoman Divacky     //
3340f22ef01cSRoman Divacky     // Remove it and replace uses of it with the alias.
3341f22ef01cSRoman Divacky     GA->takeName(Entry);
3342f22ef01cSRoman Divacky 
3343f22ef01cSRoman Divacky     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
3344f22ef01cSRoman Divacky                                                           Entry->getType()));
3345f22ef01cSRoman Divacky     Entry->eraseFromParent();
3346f22ef01cSRoman Divacky   } else {
3347ffd1746dSEd Schouten     GA->setName(MangledName);
3348f22ef01cSRoman Divacky   }
3349f22ef01cSRoman Divacky 
3350f22ef01cSRoman Divacky   // Set attributes which are particular to an alias; this is a
3351f22ef01cSRoman Divacky   // specialization of the attributes which may be set on a global
3352f22ef01cSRoman Divacky   // variable/function.
335339d628a0SDimitry Andric   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
33543b0f4066SDimitry Andric       D->isWeakImported()) {
3355f22ef01cSRoman Divacky     GA->setLinkage(llvm::Function::WeakAnyLinkage);
3356f22ef01cSRoman Divacky   }
3357f22ef01cSRoman Divacky 
335839d628a0SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
335939d628a0SDimitry Andric     if (VD->getTLSKind())
336039d628a0SDimitry Andric       setTLSMode(GA, *VD);
336139d628a0SDimitry Andric 
336239d628a0SDimitry Andric   setAliasAttributes(D, GA);
3363f22ef01cSRoman Divacky }
3364f22ef01cSRoman Divacky 
3365e7145dcbSDimitry Andric void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
3366e7145dcbSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
3367e7145dcbSDimitry Andric   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
3368e7145dcbSDimitry Andric   assert(IFA && "Not an ifunc?");
3369e7145dcbSDimitry Andric 
3370e7145dcbSDimitry Andric   StringRef MangledName = getMangledName(GD);
3371e7145dcbSDimitry Andric 
3372e7145dcbSDimitry Andric   if (IFA->getResolver() == MangledName) {
3373e7145dcbSDimitry Andric     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3374e7145dcbSDimitry Andric     return;
3375e7145dcbSDimitry Andric   }
3376e7145dcbSDimitry Andric 
3377e7145dcbSDimitry Andric   // Report an error if some definition overrides ifunc.
3378e7145dcbSDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3379e7145dcbSDimitry Andric   if (Entry && !Entry->isDeclaration()) {
3380e7145dcbSDimitry Andric     GlobalDecl OtherGD;
3381e7145dcbSDimitry Andric     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3382e7145dcbSDimitry Andric         DiagnosedConflictingDefinitions.insert(GD).second) {
3383e7145dcbSDimitry Andric       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
3384e7145dcbSDimitry Andric       Diags.Report(OtherGD.getDecl()->getLocation(),
3385e7145dcbSDimitry Andric                    diag::note_previous_definition);
3386e7145dcbSDimitry Andric     }
3387e7145dcbSDimitry Andric     return;
3388e7145dcbSDimitry Andric   }
3389e7145dcbSDimitry Andric 
3390e7145dcbSDimitry Andric   Aliases.push_back(GD);
3391e7145dcbSDimitry Andric 
3392e7145dcbSDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3393e7145dcbSDimitry Andric   llvm::Constant *Resolver =
3394e7145dcbSDimitry Andric       GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3395e7145dcbSDimitry Andric                               /*ForVTable=*/false);
3396e7145dcbSDimitry Andric   llvm::GlobalIFunc *GIF =
3397e7145dcbSDimitry Andric       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
3398e7145dcbSDimitry Andric                                 "", Resolver, &getModule());
3399e7145dcbSDimitry Andric   if (Entry) {
3400e7145dcbSDimitry Andric     if (GIF->getResolver() == Entry) {
3401e7145dcbSDimitry Andric       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3402e7145dcbSDimitry Andric       return;
3403e7145dcbSDimitry Andric     }
3404e7145dcbSDimitry Andric     assert(Entry->isDeclaration());
3405e7145dcbSDimitry Andric 
3406e7145dcbSDimitry Andric     // If there is a declaration in the module, then we had an extern followed
3407e7145dcbSDimitry Andric     // by the ifunc, as in:
3408e7145dcbSDimitry Andric     //   extern int test();
3409e7145dcbSDimitry Andric     //   ...
3410e7145dcbSDimitry Andric     //   int test() __attribute__((ifunc("resolver")));
3411e7145dcbSDimitry Andric     //
3412e7145dcbSDimitry Andric     // Remove it and replace uses of it with the ifunc.
3413e7145dcbSDimitry Andric     GIF->takeName(Entry);
3414e7145dcbSDimitry Andric 
3415e7145dcbSDimitry Andric     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3416e7145dcbSDimitry Andric                                                           Entry->getType()));
3417e7145dcbSDimitry Andric     Entry->eraseFromParent();
3418e7145dcbSDimitry Andric   } else
3419e7145dcbSDimitry Andric     GIF->setName(MangledName);
3420e7145dcbSDimitry Andric 
3421e7145dcbSDimitry Andric   SetCommonAttributes(D, GIF);
3422e7145dcbSDimitry Andric }
3423e7145dcbSDimitry Andric 
342417a519f9SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
34256122f3e6SDimitry Andric                                             ArrayRef<llvm::Type*> Tys) {
342617a519f9SDimitry Andric   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
342717a519f9SDimitry Andric                                          Tys);
3428f22ef01cSRoman Divacky }
3429f22ef01cSRoman Divacky 
343033956c43SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> &
343133956c43SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
343233956c43SDimitry Andric                          const StringLiteral *Literal, bool TargetIsLSB,
343333956c43SDimitry Andric                          bool &IsUTF16, unsigned &StringLength) {
34346122f3e6SDimitry Andric   StringRef String = Literal->getString();
3435e580952dSDimitry Andric   unsigned NumBytes = String.size();
3436f22ef01cSRoman Divacky 
3437f22ef01cSRoman Divacky   // Check for simple case.
3438f22ef01cSRoman Divacky   if (!Literal->containsNonAsciiOrNull()) {
3439f22ef01cSRoman Divacky     StringLength = NumBytes;
344039d628a0SDimitry Andric     return *Map.insert(std::make_pair(String, nullptr)).first;
3441f22ef01cSRoman Divacky   }
3442f22ef01cSRoman Divacky 
3443dff0c46cSDimitry Andric   // Otherwise, convert the UTF8 literals into a string of shorts.
3444dff0c46cSDimitry Andric   IsUTF16 = true;
3445dff0c46cSDimitry Andric 
344644290647SDimitry Andric   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
344744290647SDimitry Andric   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
344844290647SDimitry Andric   llvm::UTF16 *ToPtr = &ToBuf[0];
3449f22ef01cSRoman Divacky 
345044290647SDimitry Andric   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
345144290647SDimitry Andric                                  ToPtr + NumBytes, llvm::strictConversion);
3452f22ef01cSRoman Divacky 
3453f22ef01cSRoman Divacky   // ConvertUTF8toUTF16 returns the length in ToPtr.
3454f22ef01cSRoman Divacky   StringLength = ToPtr - &ToBuf[0];
3455f22ef01cSRoman Divacky 
3456dff0c46cSDimitry Andric   // Add an explicit null.
3457dff0c46cSDimitry Andric   *ToPtr = 0;
345839d628a0SDimitry Andric   return *Map.insert(std::make_pair(
345939d628a0SDimitry Andric                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
346039d628a0SDimitry Andric                                    (StringLength + 1) * 2),
346139d628a0SDimitry Andric                          nullptr)).first;
3462f22ef01cSRoman Divacky }
3463f22ef01cSRoman Divacky 
34640623d748SDimitry Andric ConstantAddress
3465f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
3466f22ef01cSRoman Divacky   unsigned StringLength = 0;
3467f22ef01cSRoman Divacky   bool isUTF16 = false;
346833956c43SDimitry Andric   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3469f22ef01cSRoman Divacky       GetConstantCFStringEntry(CFConstantStringMap, Literal,
347033956c43SDimitry Andric                                getDataLayout().isLittleEndian(), isUTF16,
347133956c43SDimitry Andric                                StringLength);
3472f22ef01cSRoman Divacky 
347339d628a0SDimitry Andric   if (auto *C = Entry.second)
34740623d748SDimitry Andric     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
3475f22ef01cSRoman Divacky 
3476dff0c46cSDimitry Andric   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
3477f22ef01cSRoman Divacky   llvm::Constant *Zeros[] = { Zero, Zero };
3478f22ef01cSRoman Divacky 
3479f22ef01cSRoman Divacky   // If we don't already have it, get __CFConstantStringClassReference.
3480f22ef01cSRoman Divacky   if (!CFConstantStringClassRef) {
34816122f3e6SDimitry Andric     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
3482f22ef01cSRoman Divacky     Ty = llvm::ArrayType::get(Ty, 0);
3483e7145dcbSDimitry Andric     llvm::Constant *GV =
3484e7145dcbSDimitry Andric         CreateRuntimeVariable(Ty, "__CFConstantStringClassReference");
3485e7145dcbSDimitry Andric 
348644290647SDimitry Andric     if (getTriple().isOSBinFormatCOFF()) {
3487e7145dcbSDimitry Andric       IdentifierInfo &II = getContext().Idents.get(GV->getName());
3488e7145dcbSDimitry Andric       TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
3489e7145dcbSDimitry Andric       DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3490e7145dcbSDimitry Andric       llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
3491e7145dcbSDimitry Andric 
3492e7145dcbSDimitry Andric       const VarDecl *VD = nullptr;
3493e7145dcbSDimitry Andric       for (const auto &Result : DC->lookup(&II))
3494e7145dcbSDimitry Andric         if ((VD = dyn_cast<VarDecl>(Result)))
3495e7145dcbSDimitry Andric           break;
3496e7145dcbSDimitry Andric 
3497e7145dcbSDimitry Andric       if (!VD || !VD->hasAttr<DLLExportAttr>()) {
3498e7145dcbSDimitry Andric         CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3499e7145dcbSDimitry Andric         CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3500e7145dcbSDimitry Andric       } else {
3501e7145dcbSDimitry Andric         CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3502e7145dcbSDimitry Andric         CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3503e7145dcbSDimitry Andric       }
3504e7145dcbSDimitry Andric     }
3505e7145dcbSDimitry Andric 
3506f22ef01cSRoman Divacky     // Decay array -> ptr
350744290647SDimitry Andric     CFConstantStringClassRef =
350844290647SDimitry Andric         llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
3509e7145dcbSDimitry Andric   }
3510f22ef01cSRoman Divacky 
3511f22ef01cSRoman Divacky   QualType CFTy = getContext().getCFConstantStringType();
3512f22ef01cSRoman Divacky 
351359d1ed5bSDimitry Andric   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
3514f22ef01cSRoman Divacky 
351544290647SDimitry Andric   ConstantInitBuilder Builder(*this);
351644290647SDimitry Andric   auto Fields = Builder.beginStruct(STy);
3517f22ef01cSRoman Divacky 
3518f22ef01cSRoman Divacky   // Class pointer.
351944290647SDimitry Andric   Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
3520f22ef01cSRoman Divacky 
3521f22ef01cSRoman Divacky   // Flags.
352244290647SDimitry Andric   Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
3523f22ef01cSRoman Divacky 
3524f22ef01cSRoman Divacky   // String pointer.
352559d1ed5bSDimitry Andric   llvm::Constant *C = nullptr;
3526dff0c46cSDimitry Andric   if (isUTF16) {
35270623d748SDimitry Andric     auto Arr = llvm::makeArrayRef(
352839d628a0SDimitry Andric         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
352939d628a0SDimitry Andric         Entry.first().size() / 2);
3530dff0c46cSDimitry Andric     C = llvm::ConstantDataArray::get(VMContext, Arr);
3531dff0c46cSDimitry Andric   } else {
353239d628a0SDimitry Andric     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
3533dff0c46cSDimitry Andric   }
3534f22ef01cSRoman Divacky 
3535dff0c46cSDimitry Andric   // Note: -fwritable-strings doesn't make the backing store strings of
3536dff0c46cSDimitry Andric   // CFStrings writable. (See <rdar://problem/10657500>)
353759d1ed5bSDimitry Andric   auto *GV =
3538dff0c46cSDimitry Andric       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
353959d1ed5bSDimitry Andric                                llvm::GlobalValue::PrivateLinkage, C, ".str");
3540e7145dcbSDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3541284c1978SDimitry Andric   // Don't enforce the target's minimum global alignment, since the only use
3542284c1978SDimitry Andric   // of the string is via this class initializer.
3543e7145dcbSDimitry Andric   CharUnits Align = isUTF16
3544e7145dcbSDimitry Andric                         ? getContext().getTypeAlignInChars(getContext().ShortTy)
3545e7145dcbSDimitry Andric                         : getContext().getTypeAlignInChars(getContext().CharTy);
3546f22ef01cSRoman Divacky   GV->setAlignment(Align.getQuantity());
3547e7145dcbSDimitry Andric 
3548e7145dcbSDimitry Andric   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
3549e7145dcbSDimitry Andric   // Without it LLVM can merge the string with a non unnamed_addr one during
3550e7145dcbSDimitry Andric   // LTO.  Doing that changes the section it ends in, which surprises ld64.
355144290647SDimitry Andric   if (getTriple().isOSBinFormatMachO())
3552e7145dcbSDimitry Andric     GV->setSection(isUTF16 ? "__TEXT,__ustring"
3553e7145dcbSDimitry Andric                            : "__TEXT,__cstring,cstring_literals");
3554dff0c46cSDimitry Andric 
3555dff0c46cSDimitry Andric   // String.
355644290647SDimitry Andric   llvm::Constant *Str =
355733956c43SDimitry Andric       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3558f22ef01cSRoman Divacky 
3559dff0c46cSDimitry Andric   if (isUTF16)
3560dff0c46cSDimitry Andric     // Cast the UTF16 string to the correct type.
356144290647SDimitry Andric     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
356244290647SDimitry Andric   Fields.add(Str);
3563dff0c46cSDimitry Andric 
3564f22ef01cSRoman Divacky   // String length.
356544290647SDimitry Andric   auto Ty = getTypes().ConvertType(getContext().LongTy);
356644290647SDimitry Andric   Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
3567f22ef01cSRoman Divacky 
35680623d748SDimitry Andric   CharUnits Alignment = getPointerAlign();
35690623d748SDimitry Andric 
3570f22ef01cSRoman Divacky   // The struct.
357144290647SDimitry Andric   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
357244290647SDimitry Andric                                     /*isConstant=*/false,
357344290647SDimitry Andric                                     llvm::GlobalVariable::PrivateLinkage);
357444290647SDimitry Andric   switch (getTriple().getObjectFormat()) {
3575e7145dcbSDimitry Andric   case llvm::Triple::UnknownObjectFormat:
3576e7145dcbSDimitry Andric     llvm_unreachable("unknown file format");
3577e7145dcbSDimitry Andric   case llvm::Triple::COFF:
3578e7145dcbSDimitry Andric   case llvm::Triple::ELF:
357920e90f04SDimitry Andric   case llvm::Triple::Wasm:
3580e7145dcbSDimitry Andric     GV->setSection("cfstring");
3581e7145dcbSDimitry Andric     break;
3582e7145dcbSDimitry Andric   case llvm::Triple::MachO:
3583e7145dcbSDimitry Andric     GV->setSection("__DATA,__cfstring");
3584e7145dcbSDimitry Andric     break;
3585e7145dcbSDimitry Andric   }
358639d628a0SDimitry Andric   Entry.second = GV;
3587f22ef01cSRoman Divacky 
35880623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
3589f22ef01cSRoman Divacky }
3590f22ef01cSRoman Divacky 
35919a199699SDimitry Andric bool CodeGenModule::getExpressionLocationsEnabled() const {
35929a199699SDimitry Andric   return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
35939a199699SDimitry Andric }
35949a199699SDimitry Andric 
35956122f3e6SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() {
35966122f3e6SDimitry Andric   if (ObjCFastEnumerationStateType.isNull()) {
359759d1ed5bSDimitry Andric     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
35986122f3e6SDimitry Andric     D->startDefinition();
35996122f3e6SDimitry Andric 
36006122f3e6SDimitry Andric     QualType FieldTypes[] = {
36016122f3e6SDimitry Andric       Context.UnsignedLongTy,
36026122f3e6SDimitry Andric       Context.getPointerType(Context.getObjCIdType()),
36036122f3e6SDimitry Andric       Context.getPointerType(Context.UnsignedLongTy),
36046122f3e6SDimitry Andric       Context.getConstantArrayType(Context.UnsignedLongTy,
36056122f3e6SDimitry Andric                            llvm::APInt(32, 5), ArrayType::Normal, 0)
36066122f3e6SDimitry Andric     };
36076122f3e6SDimitry Andric 
36086122f3e6SDimitry Andric     for (size_t i = 0; i < 4; ++i) {
36096122f3e6SDimitry Andric       FieldDecl *Field = FieldDecl::Create(Context,
36106122f3e6SDimitry Andric                                            D,
36116122f3e6SDimitry Andric                                            SourceLocation(),
361259d1ed5bSDimitry Andric                                            SourceLocation(), nullptr,
361359d1ed5bSDimitry Andric                                            FieldTypes[i], /*TInfo=*/nullptr,
361459d1ed5bSDimitry Andric                                            /*BitWidth=*/nullptr,
36156122f3e6SDimitry Andric                                            /*Mutable=*/false,
36167ae0e2c9SDimitry Andric                                            ICIS_NoInit);
36176122f3e6SDimitry Andric       Field->setAccess(AS_public);
36186122f3e6SDimitry Andric       D->addDecl(Field);
36196122f3e6SDimitry Andric     }
36206122f3e6SDimitry Andric 
36216122f3e6SDimitry Andric     D->completeDefinition();
36226122f3e6SDimitry Andric     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
36236122f3e6SDimitry Andric   }
36246122f3e6SDimitry Andric 
36256122f3e6SDimitry Andric   return ObjCFastEnumerationStateType;
36266122f3e6SDimitry Andric }
36276122f3e6SDimitry Andric 
3628dff0c46cSDimitry Andric llvm::Constant *
3629dff0c46cSDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
3630dff0c46cSDimitry Andric   assert(!E->getType()->isPointerType() && "Strings are always arrays");
3631f22ef01cSRoman Divacky 
3632dff0c46cSDimitry Andric   // Don't emit it as the address of the string, emit the string data itself
3633dff0c46cSDimitry Andric   // as an inline array.
3634dff0c46cSDimitry Andric   if (E->getCharByteWidth() == 1) {
3635dff0c46cSDimitry Andric     SmallString<64> Str(E->getString());
3636f22ef01cSRoman Divacky 
3637dff0c46cSDimitry Andric     // Resize the string to the right size, which is indicated by its type.
3638dff0c46cSDimitry Andric     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
3639dff0c46cSDimitry Andric     Str.resize(CAT->getSize().getZExtValue());
3640dff0c46cSDimitry Andric     return llvm::ConstantDataArray::getString(VMContext, Str, false);
36416122f3e6SDimitry Andric   }
3642f22ef01cSRoman Divacky 
364359d1ed5bSDimitry Andric   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
3644dff0c46cSDimitry Andric   llvm::Type *ElemTy = AType->getElementType();
3645dff0c46cSDimitry Andric   unsigned NumElements = AType->getNumElements();
3646f22ef01cSRoman Divacky 
3647dff0c46cSDimitry Andric   // Wide strings have either 2-byte or 4-byte elements.
3648dff0c46cSDimitry Andric   if (ElemTy->getPrimitiveSizeInBits() == 16) {
3649dff0c46cSDimitry Andric     SmallVector<uint16_t, 32> Elements;
3650dff0c46cSDimitry Andric     Elements.reserve(NumElements);
3651dff0c46cSDimitry Andric 
3652dff0c46cSDimitry Andric     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3653dff0c46cSDimitry Andric       Elements.push_back(E->getCodeUnit(i));
3654dff0c46cSDimitry Andric     Elements.resize(NumElements);
3655dff0c46cSDimitry Andric     return llvm::ConstantDataArray::get(VMContext, Elements);
3656dff0c46cSDimitry Andric   }
3657dff0c46cSDimitry Andric 
3658dff0c46cSDimitry Andric   assert(ElemTy->getPrimitiveSizeInBits() == 32);
3659dff0c46cSDimitry Andric   SmallVector<uint32_t, 32> Elements;
3660dff0c46cSDimitry Andric   Elements.reserve(NumElements);
3661dff0c46cSDimitry Andric 
3662dff0c46cSDimitry Andric   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3663dff0c46cSDimitry Andric     Elements.push_back(E->getCodeUnit(i));
3664dff0c46cSDimitry Andric   Elements.resize(NumElements);
3665dff0c46cSDimitry Andric   return llvm::ConstantDataArray::get(VMContext, Elements);
3666f22ef01cSRoman Divacky }
3667f22ef01cSRoman Divacky 
366859d1ed5bSDimitry Andric static llvm::GlobalVariable *
366959d1ed5bSDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
367059d1ed5bSDimitry Andric                       CodeGenModule &CGM, StringRef GlobalName,
36710623d748SDimitry Andric                       CharUnits Alignment) {
367259d1ed5bSDimitry Andric   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
367359d1ed5bSDimitry Andric   unsigned AddrSpace = 0;
367459d1ed5bSDimitry Andric   if (CGM.getLangOpts().OpenCL)
367559d1ed5bSDimitry Andric     AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
3676dff0c46cSDimitry Andric 
367733956c43SDimitry Andric   llvm::Module &M = CGM.getModule();
367859d1ed5bSDimitry Andric   // Create a global variable for this string
367959d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
368033956c43SDimitry Andric       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
368133956c43SDimitry Andric       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
36820623d748SDimitry Andric   GV->setAlignment(Alignment.getQuantity());
3683e7145dcbSDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
368433956c43SDimitry Andric   if (GV->isWeakForLinker()) {
368533956c43SDimitry Andric     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
368633956c43SDimitry Andric     GV->setComdat(M.getOrInsertComdat(GV->getName()));
368733956c43SDimitry Andric   }
368833956c43SDimitry Andric 
368959d1ed5bSDimitry Andric   return GV;
3690f22ef01cSRoman Divacky }
3691dff0c46cSDimitry Andric 
369259d1ed5bSDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
369359d1ed5bSDimitry Andric /// constant array for the given string literal.
36940623d748SDimitry Andric ConstantAddress
369539d628a0SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
369639d628a0SDimitry Andric                                                   StringRef Name) {
36970623d748SDimitry Andric   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
3698dff0c46cSDimitry Andric 
369959d1ed5bSDimitry Andric   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
370059d1ed5bSDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
370159d1ed5bSDimitry Andric   if (!LangOpts.WritableStrings) {
370259d1ed5bSDimitry Andric     Entry = &ConstantStringMap[C];
370359d1ed5bSDimitry Andric     if (auto GV = *Entry) {
37040623d748SDimitry Andric       if (Alignment.getQuantity() > GV->getAlignment())
37050623d748SDimitry Andric         GV->setAlignment(Alignment.getQuantity());
37060623d748SDimitry Andric       return ConstantAddress(GV, Alignment);
370759d1ed5bSDimitry Andric     }
370859d1ed5bSDimitry Andric   }
370959d1ed5bSDimitry Andric 
371059d1ed5bSDimitry Andric   SmallString<256> MangledNameBuffer;
371159d1ed5bSDimitry Andric   StringRef GlobalVariableName;
371259d1ed5bSDimitry Andric   llvm::GlobalValue::LinkageTypes LT;
371359d1ed5bSDimitry Andric 
371459d1ed5bSDimitry Andric   // Mangle the string literal if the ABI allows for it.  However, we cannot
371559d1ed5bSDimitry Andric   // do this if  we are compiling with ASan or -fwritable-strings because they
371659d1ed5bSDimitry Andric   // rely on strings having normal linkage.
371739d628a0SDimitry Andric   if (!LangOpts.WritableStrings &&
371839d628a0SDimitry Andric       !LangOpts.Sanitize.has(SanitizerKind::Address) &&
371959d1ed5bSDimitry Andric       getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
372059d1ed5bSDimitry Andric     llvm::raw_svector_ostream Out(MangledNameBuffer);
372159d1ed5bSDimitry Andric     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
372259d1ed5bSDimitry Andric 
372359d1ed5bSDimitry Andric     LT = llvm::GlobalValue::LinkOnceODRLinkage;
372459d1ed5bSDimitry Andric     GlobalVariableName = MangledNameBuffer;
372559d1ed5bSDimitry Andric   } else {
372659d1ed5bSDimitry Andric     LT = llvm::GlobalValue::PrivateLinkage;
372739d628a0SDimitry Andric     GlobalVariableName = Name;
372859d1ed5bSDimitry Andric   }
372959d1ed5bSDimitry Andric 
373059d1ed5bSDimitry Andric   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
373159d1ed5bSDimitry Andric   if (Entry)
373259d1ed5bSDimitry Andric     *Entry = GV;
373359d1ed5bSDimitry Andric 
373439d628a0SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
373539d628a0SDimitry Andric                                   QualType());
37360623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
3737f22ef01cSRoman Divacky }
3738f22ef01cSRoman Divacky 
3739f22ef01cSRoman Divacky /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
3740f22ef01cSRoman Divacky /// array for the given ObjCEncodeExpr node.
37410623d748SDimitry Andric ConstantAddress
3742f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
3743f22ef01cSRoman Divacky   std::string Str;
3744f22ef01cSRoman Divacky   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
3745f22ef01cSRoman Divacky 
3746f22ef01cSRoman Divacky   return GetAddrOfConstantCString(Str);
3747f22ef01cSRoman Divacky }
3748f22ef01cSRoman Divacky 
374959d1ed5bSDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing
375059d1ed5bSDimitry Andric /// the literal and a terminating '\0' character.
375159d1ed5bSDimitry Andric /// The result has pointer to array type.
37520623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString(
37530623d748SDimitry Andric     const std::string &Str, const char *GlobalName) {
375459d1ed5bSDimitry Andric   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
37550623d748SDimitry Andric   CharUnits Alignment =
37560623d748SDimitry Andric     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
3757f22ef01cSRoman Divacky 
375859d1ed5bSDimitry Andric   llvm::Constant *C =
375959d1ed5bSDimitry Andric       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
376059d1ed5bSDimitry Andric 
376159d1ed5bSDimitry Andric   // Don't share any string literals if strings aren't constant.
376259d1ed5bSDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
376359d1ed5bSDimitry Andric   if (!LangOpts.WritableStrings) {
376459d1ed5bSDimitry Andric     Entry = &ConstantStringMap[C];
376559d1ed5bSDimitry Andric     if (auto GV = *Entry) {
37660623d748SDimitry Andric       if (Alignment.getQuantity() > GV->getAlignment())
37670623d748SDimitry Andric         GV->setAlignment(Alignment.getQuantity());
37680623d748SDimitry Andric       return ConstantAddress(GV, Alignment);
376959d1ed5bSDimitry Andric     }
377059d1ed5bSDimitry Andric   }
377159d1ed5bSDimitry Andric 
3772f22ef01cSRoman Divacky   // Get the default prefix if a name wasn't specified.
3773f22ef01cSRoman Divacky   if (!GlobalName)
3774f22ef01cSRoman Divacky     GlobalName = ".str";
3775f22ef01cSRoman Divacky   // Create a global variable for this.
377659d1ed5bSDimitry Andric   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
377759d1ed5bSDimitry Andric                                   GlobalName, Alignment);
377859d1ed5bSDimitry Andric   if (Entry)
377959d1ed5bSDimitry Andric     *Entry = GV;
37800623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
3781f22ef01cSRoman Divacky }
3782f22ef01cSRoman Divacky 
37830623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
3784f785676fSDimitry Andric     const MaterializeTemporaryExpr *E, const Expr *Init) {
3785f785676fSDimitry Andric   assert((E->getStorageDuration() == SD_Static ||
3786f785676fSDimitry Andric           E->getStorageDuration() == SD_Thread) && "not a global temporary");
378759d1ed5bSDimitry Andric   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
3788f785676fSDimitry Andric 
3789f785676fSDimitry Andric   // If we're not materializing a subobject of the temporary, keep the
3790f785676fSDimitry Andric   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
3791f785676fSDimitry Andric   QualType MaterializedType = Init->getType();
3792f785676fSDimitry Andric   if (Init == E->GetTemporaryExpr())
3793f785676fSDimitry Andric     MaterializedType = E->getType();
3794f785676fSDimitry Andric 
37950623d748SDimitry Andric   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
37960623d748SDimitry Andric 
37970623d748SDimitry Andric   if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
37980623d748SDimitry Andric     return ConstantAddress(Slot, Align);
3799f785676fSDimitry Andric 
3800f785676fSDimitry Andric   // FIXME: If an externally-visible declaration extends multiple temporaries,
3801f785676fSDimitry Andric   // we need to give each temporary the same name in every translation unit (and
3802f785676fSDimitry Andric   // we also need to make the temporaries externally-visible).
3803f785676fSDimitry Andric   SmallString<256> Name;
3804f785676fSDimitry Andric   llvm::raw_svector_ostream Out(Name);
380559d1ed5bSDimitry Andric   getCXXABI().getMangleContext().mangleReferenceTemporary(
380659d1ed5bSDimitry Andric       VD, E->getManglingNumber(), Out);
3807f785676fSDimitry Andric 
380859d1ed5bSDimitry Andric   APValue *Value = nullptr;
3809f785676fSDimitry Andric   if (E->getStorageDuration() == SD_Static) {
3810f785676fSDimitry Andric     // We might have a cached constant initializer for this temporary. Note
3811f785676fSDimitry Andric     // that this might have a different value from the value computed by
3812f785676fSDimitry Andric     // evaluating the initializer if the surrounding constant expression
3813f785676fSDimitry Andric     // modifies the temporary.
3814f785676fSDimitry Andric     Value = getContext().getMaterializedTemporaryValue(E, false);
3815f785676fSDimitry Andric     if (Value && Value->isUninit())
381659d1ed5bSDimitry Andric       Value = nullptr;
3817f785676fSDimitry Andric   }
3818f785676fSDimitry Andric 
3819f785676fSDimitry Andric   // Try evaluating it now, it might have a constant initializer.
3820f785676fSDimitry Andric   Expr::EvalResult EvalResult;
3821f785676fSDimitry Andric   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3822f785676fSDimitry Andric       !EvalResult.hasSideEffects())
3823f785676fSDimitry Andric     Value = &EvalResult.Val;
3824f785676fSDimitry Andric 
38259a199699SDimitry Andric   LangAS AddrSpace =
38269a199699SDimitry Andric       VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
38279a199699SDimitry Andric 
38289a199699SDimitry Andric   Optional<ConstantEmitter> emitter;
382959d1ed5bSDimitry Andric   llvm::Constant *InitialValue = nullptr;
3830f785676fSDimitry Andric   bool Constant = false;
3831f785676fSDimitry Andric   llvm::Type *Type;
3832f785676fSDimitry Andric   if (Value) {
3833f785676fSDimitry Andric     // The temporary has a constant initializer, use it.
38349a199699SDimitry Andric     emitter.emplace(*this);
38359a199699SDimitry Andric     InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
38369a199699SDimitry Andric                                                MaterializedType);
3837f785676fSDimitry Andric     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3838f785676fSDimitry Andric     Type = InitialValue->getType();
3839f785676fSDimitry Andric   } else {
3840f785676fSDimitry Andric     // No initializer, the initialization will be provided when we
3841f785676fSDimitry Andric     // initialize the declaration which performed lifetime extension.
3842f785676fSDimitry Andric     Type = getTypes().ConvertTypeForMem(MaterializedType);
3843f785676fSDimitry Andric   }
3844f785676fSDimitry Andric 
3845f785676fSDimitry Andric   // Create a global variable for this lifetime-extended temporary.
384659d1ed5bSDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
384759d1ed5bSDimitry Andric       getLLVMLinkageVarDefinition(VD, Constant);
384833956c43SDimitry Andric   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
384933956c43SDimitry Andric     const VarDecl *InitVD;
385033956c43SDimitry Andric     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
385133956c43SDimitry Andric         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
385233956c43SDimitry Andric       // Temporaries defined inside a class get linkonce_odr linkage because the
385333956c43SDimitry Andric       // class can be defined in multipe translation units.
385433956c43SDimitry Andric       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
385533956c43SDimitry Andric     } else {
385633956c43SDimitry Andric       // There is no need for this temporary to have external linkage if the
385733956c43SDimitry Andric       // VarDecl has external linkage.
385833956c43SDimitry Andric       Linkage = llvm::GlobalVariable::InternalLinkage;
385933956c43SDimitry Andric     }
386033956c43SDimitry Andric   }
3861c4394386SDimitry Andric   auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
386259d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
386359d1ed5bSDimitry Andric       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
3864c4394386SDimitry Andric       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
38659a199699SDimitry Andric   if (emitter) emitter->finalize(GV);
38669a199699SDimitry Andric   setGlobalVisibility(GV, VD, ForDefinition);
38670623d748SDimitry Andric   GV->setAlignment(Align.getQuantity());
386833956c43SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker())
386933956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3870f785676fSDimitry Andric   if (VD->getTLSKind())
3871f785676fSDimitry Andric     setTLSMode(GV, *VD);
3872c4394386SDimitry Andric   llvm::Constant *CV = GV;
3873c4394386SDimitry Andric   if (AddrSpace != LangAS::Default)
3874c4394386SDimitry Andric     CV = getTargetCodeGenInfo().performAddrSpaceCast(
3875c4394386SDimitry Andric         *this, GV, AddrSpace, LangAS::Default,
3876c4394386SDimitry Andric         Type->getPointerTo(
3877c4394386SDimitry Andric             getContext().getTargetAddressSpace(LangAS::Default)));
3878c4394386SDimitry Andric   MaterializedGlobalTemporaryMap[E] = CV;
3879c4394386SDimitry Andric   return ConstantAddress(CV, Align);
3880f785676fSDimitry Andric }
3881f785676fSDimitry Andric 
3882f22ef01cSRoman Divacky /// EmitObjCPropertyImplementations - Emit information for synthesized
3883f22ef01cSRoman Divacky /// properties for an implementation.
3884f22ef01cSRoman Divacky void CodeGenModule::EmitObjCPropertyImplementations(const
3885f22ef01cSRoman Divacky                                                     ObjCImplementationDecl *D) {
388659d1ed5bSDimitry Andric   for (const auto *PID : D->property_impls()) {
3887f22ef01cSRoman Divacky     // Dynamic is just for type-checking.
3888f22ef01cSRoman Divacky     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3889f22ef01cSRoman Divacky       ObjCPropertyDecl *PD = PID->getPropertyDecl();
3890f22ef01cSRoman Divacky 
3891f22ef01cSRoman Divacky       // Determine which methods need to be implemented, some may have
38923861d79fSDimitry Andric       // been overridden. Note that ::isPropertyAccessor is not the method
3893f22ef01cSRoman Divacky       // we want, that just indicates if the decl came from a
3894f22ef01cSRoman Divacky       // property. What we want to know is if the method is defined in
3895f22ef01cSRoman Divacky       // this implementation.
3896f22ef01cSRoman Divacky       if (!D->getInstanceMethod(PD->getGetterName()))
3897f22ef01cSRoman Divacky         CodeGenFunction(*this).GenerateObjCGetter(
3898f22ef01cSRoman Divacky                                  const_cast<ObjCImplementationDecl *>(D), PID);
3899f22ef01cSRoman Divacky       if (!PD->isReadOnly() &&
3900f22ef01cSRoman Divacky           !D->getInstanceMethod(PD->getSetterName()))
3901f22ef01cSRoman Divacky         CodeGenFunction(*this).GenerateObjCSetter(
3902f22ef01cSRoman Divacky                                  const_cast<ObjCImplementationDecl *>(D), PID);
3903f22ef01cSRoman Divacky     }
3904f22ef01cSRoman Divacky   }
3905f22ef01cSRoman Divacky }
3906f22ef01cSRoman Divacky 
39073b0f4066SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) {
39086122f3e6SDimitry Andric   const ObjCInterfaceDecl *iface = impl->getClassInterface();
39096122f3e6SDimitry Andric   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
39103b0f4066SDimitry Andric        ivar; ivar = ivar->getNextIvar())
39113b0f4066SDimitry Andric     if (ivar->getType().isDestructedType())
39123b0f4066SDimitry Andric       return true;
39133b0f4066SDimitry Andric 
39143b0f4066SDimitry Andric   return false;
39153b0f4066SDimitry Andric }
39163b0f4066SDimitry Andric 
391739d628a0SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM,
391839d628a0SDimitry Andric                                    ObjCImplementationDecl *D) {
391939d628a0SDimitry Andric   CodeGenFunction CGF(CGM);
392039d628a0SDimitry Andric   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
392139d628a0SDimitry Andric        E = D->init_end(); B != E; ++B) {
392239d628a0SDimitry Andric     CXXCtorInitializer *CtorInitExp = *B;
392339d628a0SDimitry Andric     Expr *Init = CtorInitExp->getInit();
392439d628a0SDimitry Andric     if (!CGF.isTrivialInitializer(Init))
392539d628a0SDimitry Andric       return false;
392639d628a0SDimitry Andric   }
392739d628a0SDimitry Andric   return true;
392839d628a0SDimitry Andric }
392939d628a0SDimitry Andric 
3930f22ef01cSRoman Divacky /// EmitObjCIvarInitializations - Emit information for ivar initialization
3931f22ef01cSRoman Divacky /// for an implementation.
3932f22ef01cSRoman Divacky void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
39333b0f4066SDimitry Andric   // We might need a .cxx_destruct even if we don't have any ivar initializers.
39343b0f4066SDimitry Andric   if (needsDestructMethod(D)) {
3935f22ef01cSRoman Divacky     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3936f22ef01cSRoman Divacky     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
39373b0f4066SDimitry Andric     ObjCMethodDecl *DTORMethod =
39383b0f4066SDimitry Andric       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
393959d1ed5bSDimitry Andric                              cxxSelector, getContext().VoidTy, nullptr, D,
39406122f3e6SDimitry Andric                              /*isInstance=*/true, /*isVariadic=*/false,
39413861d79fSDimitry Andric                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
39426122f3e6SDimitry Andric                              /*isDefined=*/false, ObjCMethodDecl::Required);
3943f22ef01cSRoman Divacky     D->addInstanceMethod(DTORMethod);
3944f22ef01cSRoman Divacky     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
39453861d79fSDimitry Andric     D->setHasDestructors(true);
39463b0f4066SDimitry Andric   }
3947f22ef01cSRoman Divacky 
39483b0f4066SDimitry Andric   // If the implementation doesn't have any ivar initializers, we don't need
39493b0f4066SDimitry Andric   // a .cxx_construct.
395039d628a0SDimitry Andric   if (D->getNumIvarInitializers() == 0 ||
395139d628a0SDimitry Andric       AllTrivialInitializers(*this, D))
39523b0f4066SDimitry Andric     return;
39533b0f4066SDimitry Andric 
39543b0f4066SDimitry Andric   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
39553b0f4066SDimitry Andric   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3956f22ef01cSRoman Divacky   // The constructor returns 'self'.
3957f22ef01cSRoman Divacky   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3958f22ef01cSRoman Divacky                                                 D->getLocation(),
39596122f3e6SDimitry Andric                                                 D->getLocation(),
39606122f3e6SDimitry Andric                                                 cxxSelector,
396159d1ed5bSDimitry Andric                                                 getContext().getObjCIdType(),
396259d1ed5bSDimitry Andric                                                 nullptr, D, /*isInstance=*/true,
39636122f3e6SDimitry Andric                                                 /*isVariadic=*/false,
39643861d79fSDimitry Andric                                                 /*isPropertyAccessor=*/true,
39656122f3e6SDimitry Andric                                                 /*isImplicitlyDeclared=*/true,
39666122f3e6SDimitry Andric                                                 /*isDefined=*/false,
3967f22ef01cSRoman Divacky                                                 ObjCMethodDecl::Required);
3968f22ef01cSRoman Divacky   D->addInstanceMethod(CTORMethod);
3969f22ef01cSRoman Divacky   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
39703861d79fSDimitry Andric   D->setHasNonZeroConstructors(true);
3971f22ef01cSRoman Divacky }
3972f22ef01cSRoman Divacky 
3973f22ef01cSRoman Divacky // EmitLinkageSpec - Emit all declarations in a linkage spec.
3974f22ef01cSRoman Divacky void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
3975f22ef01cSRoman Divacky   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3976f22ef01cSRoman Divacky       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
3977f22ef01cSRoman Divacky     ErrorUnsupported(LSD, "linkage spec");
3978f22ef01cSRoman Divacky     return;
3979f22ef01cSRoman Divacky   }
3980f22ef01cSRoman Divacky 
398144290647SDimitry Andric   EmitDeclContext(LSD);
398244290647SDimitry Andric }
398344290647SDimitry Andric 
398444290647SDimitry Andric void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
398544290647SDimitry Andric   for (auto *I : DC->decls()) {
398644290647SDimitry Andric     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
398744290647SDimitry Andric     // are themselves considered "top-level", so EmitTopLevelDecl on an
398844290647SDimitry Andric     // ObjCImplDecl does not recursively visit them. We need to do that in
398944290647SDimitry Andric     // case they're nested inside another construct (LinkageSpecDecl /
399044290647SDimitry Andric     // ExportDecl) that does stop them from being considered "top-level".
399159d1ed5bSDimitry Andric     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
399259d1ed5bSDimitry Andric       for (auto *M : OID->methods())
399359d1ed5bSDimitry Andric         EmitTopLevelDecl(M);
39943861d79fSDimitry Andric     }
399544290647SDimitry Andric 
399659d1ed5bSDimitry Andric     EmitTopLevelDecl(I);
3997f22ef01cSRoman Divacky   }
39983861d79fSDimitry Andric }
3999f22ef01cSRoman Divacky 
4000f22ef01cSRoman Divacky /// EmitTopLevelDecl - Emit code for a single top level declaration.
4001f22ef01cSRoman Divacky void CodeGenModule::EmitTopLevelDecl(Decl *D) {
4002f22ef01cSRoman Divacky   // Ignore dependent declarations.
4003f22ef01cSRoman Divacky   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
4004f22ef01cSRoman Divacky     return;
4005f22ef01cSRoman Divacky 
4006f22ef01cSRoman Divacky   switch (D->getKind()) {
4007f22ef01cSRoman Divacky   case Decl::CXXConversion:
4008f22ef01cSRoman Divacky   case Decl::CXXMethod:
4009f22ef01cSRoman Divacky   case Decl::Function:
4010f22ef01cSRoman Divacky     // Skip function templates
40113b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
40123b0f4066SDimitry Andric         cast<FunctionDecl>(D)->isLateTemplateParsed())
4013f22ef01cSRoman Divacky       return;
4014f22ef01cSRoman Divacky 
4015f22ef01cSRoman Divacky     EmitGlobal(cast<FunctionDecl>(D));
401639d628a0SDimitry Andric     // Always provide some coverage mapping
401739d628a0SDimitry Andric     // even for the functions that aren't emitted.
401839d628a0SDimitry Andric     AddDeferredUnusedCoverageMapping(D);
4019f22ef01cSRoman Divacky     break;
4020f22ef01cSRoman Divacky 
40216bc11b14SDimitry Andric   case Decl::CXXDeductionGuide:
40226bc11b14SDimitry Andric     // Function-like, but does not result in code emission.
40236bc11b14SDimitry Andric     break;
40246bc11b14SDimitry Andric 
4025f22ef01cSRoman Divacky   case Decl::Var:
402644290647SDimitry Andric   case Decl::Decomposition:
4027f785676fSDimitry Andric     // Skip variable templates
4028f785676fSDimitry Andric     if (cast<VarDecl>(D)->getDescribedVarTemplate())
4029f785676fSDimitry Andric       return;
40306d97bb29SDimitry Andric     LLVM_FALLTHROUGH;
4031f785676fSDimitry Andric   case Decl::VarTemplateSpecialization:
4032f22ef01cSRoman Divacky     EmitGlobal(cast<VarDecl>(D));
403344290647SDimitry Andric     if (auto *DD = dyn_cast<DecompositionDecl>(D))
403444290647SDimitry Andric       for (auto *B : DD->bindings())
403544290647SDimitry Andric         if (auto *HD = B->getHoldingVar())
403644290647SDimitry Andric           EmitGlobal(HD);
4037f22ef01cSRoman Divacky     break;
4038f22ef01cSRoman Divacky 
40393b0f4066SDimitry Andric   // Indirect fields from global anonymous structs and unions can be
40403b0f4066SDimitry Andric   // ignored; only the actual variable requires IR gen support.
40413b0f4066SDimitry Andric   case Decl::IndirectField:
40423b0f4066SDimitry Andric     break;
40433b0f4066SDimitry Andric 
4044f22ef01cSRoman Divacky   // C++ Decls
4045f22ef01cSRoman Divacky   case Decl::Namespace:
404644290647SDimitry Andric     EmitDeclContext(cast<NamespaceDecl>(D));
4047f22ef01cSRoman Divacky     break;
40489a199699SDimitry Andric   case Decl::ClassTemplateSpecialization: {
40499a199699SDimitry Andric     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
40509a199699SDimitry Andric     if (DebugInfo &&
40519a199699SDimitry Andric         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
40529a199699SDimitry Andric         Spec->hasDefinition())
40539a199699SDimitry Andric       DebugInfo->completeTemplateDefinition(*Spec);
40549a199699SDimitry Andric   } LLVM_FALLTHROUGH;
4055e7145dcbSDimitry Andric   case Decl::CXXRecord:
405620e90f04SDimitry Andric     if (DebugInfo) {
405720e90f04SDimitry Andric       if (auto *ES = D->getASTContext().getExternalSource())
405820e90f04SDimitry Andric         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
405920e90f04SDimitry Andric           DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
406020e90f04SDimitry Andric     }
4061e7145dcbSDimitry Andric     // Emit any static data members, they may be definitions.
4062e7145dcbSDimitry Andric     for (auto *I : cast<CXXRecordDecl>(D)->decls())
4063e7145dcbSDimitry Andric       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
4064e7145dcbSDimitry Andric         EmitTopLevelDecl(I);
4065e7145dcbSDimitry Andric     break;
4066f22ef01cSRoman Divacky     // No code generation needed.
4067f22ef01cSRoman Divacky   case Decl::UsingShadow:
4068f22ef01cSRoman Divacky   case Decl::ClassTemplate:
4069f785676fSDimitry Andric   case Decl::VarTemplate:
4070f785676fSDimitry Andric   case Decl::VarTemplatePartialSpecialization:
4071f22ef01cSRoman Divacky   case Decl::FunctionTemplate:
4072bd5abe19SDimitry Andric   case Decl::TypeAliasTemplate:
4073bd5abe19SDimitry Andric   case Decl::Block:
4074139f7f9bSDimitry Andric   case Decl::Empty:
4075f22ef01cSRoman Divacky     break;
407659d1ed5bSDimitry Andric   case Decl::Using:          // using X; [C++]
407759d1ed5bSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
407859d1ed5bSDimitry Andric         DI->EmitUsingDecl(cast<UsingDecl>(*D));
407959d1ed5bSDimitry Andric     return;
4080f785676fSDimitry Andric   case Decl::NamespaceAlias:
4081f785676fSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
4082f785676fSDimitry Andric         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
4083f785676fSDimitry Andric     return;
4084284c1978SDimitry Andric   case Decl::UsingDirective: // using namespace X; [C++]
4085284c1978SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
4086284c1978SDimitry Andric       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
4087284c1978SDimitry Andric     return;
4088f22ef01cSRoman Divacky   case Decl::CXXConstructor:
4089f22ef01cSRoman Divacky     // Skip function templates
40903b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
40913b0f4066SDimitry Andric         cast<FunctionDecl>(D)->isLateTemplateParsed())
4092f22ef01cSRoman Divacky       return;
4093f22ef01cSRoman Divacky 
4094f785676fSDimitry Andric     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
4095f22ef01cSRoman Divacky     break;
4096f22ef01cSRoman Divacky   case Decl::CXXDestructor:
40973b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
40983b0f4066SDimitry Andric       return;
4099f785676fSDimitry Andric     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
4100f22ef01cSRoman Divacky     break;
4101f22ef01cSRoman Divacky 
4102f22ef01cSRoman Divacky   case Decl::StaticAssert:
4103f22ef01cSRoman Divacky     // Nothing to do.
4104f22ef01cSRoman Divacky     break;
4105f22ef01cSRoman Divacky 
4106f22ef01cSRoman Divacky   // Objective-C Decls
4107f22ef01cSRoman Divacky 
4108f22ef01cSRoman Divacky   // Forward declarations, no (immediate) code generation.
4109f22ef01cSRoman Divacky   case Decl::ObjCInterface:
41107ae0e2c9SDimitry Andric   case Decl::ObjCCategory:
4111f22ef01cSRoman Divacky     break;
4112f22ef01cSRoman Divacky 
4113dff0c46cSDimitry Andric   case Decl::ObjCProtocol: {
411459d1ed5bSDimitry Andric     auto *Proto = cast<ObjCProtocolDecl>(D);
4115dff0c46cSDimitry Andric     if (Proto->isThisDeclarationADefinition())
4116dff0c46cSDimitry Andric       ObjCRuntime->GenerateProtocol(Proto);
4117f22ef01cSRoman Divacky     break;
4118dff0c46cSDimitry Andric   }
4119f22ef01cSRoman Divacky 
4120f22ef01cSRoman Divacky   case Decl::ObjCCategoryImpl:
4121f22ef01cSRoman Divacky     // Categories have properties but don't support synthesize so we
4122f22ef01cSRoman Divacky     // can ignore them here.
41236122f3e6SDimitry Andric     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
4124f22ef01cSRoman Divacky     break;
4125f22ef01cSRoman Divacky 
4126f22ef01cSRoman Divacky   case Decl::ObjCImplementation: {
412759d1ed5bSDimitry Andric     auto *OMD = cast<ObjCImplementationDecl>(D);
4128f22ef01cSRoman Divacky     EmitObjCPropertyImplementations(OMD);
4129f22ef01cSRoman Divacky     EmitObjCIvarInitializations(OMD);
41306122f3e6SDimitry Andric     ObjCRuntime->GenerateClass(OMD);
4131dff0c46cSDimitry Andric     // Emit global variable debug information.
4132dff0c46cSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
4133e7145dcbSDimitry Andric       if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
4134139f7f9bSDimitry Andric         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
4135139f7f9bSDimitry Andric             OMD->getClassInterface()), OMD->getLocation());
4136f22ef01cSRoman Divacky     break;
4137f22ef01cSRoman Divacky   }
4138f22ef01cSRoman Divacky   case Decl::ObjCMethod: {
413959d1ed5bSDimitry Andric     auto *OMD = cast<ObjCMethodDecl>(D);
4140f22ef01cSRoman Divacky     // If this is not a prototype, emit the body.
4141f22ef01cSRoman Divacky     if (OMD->getBody())
4142f22ef01cSRoman Divacky       CodeGenFunction(*this).GenerateObjCMethod(OMD);
4143f22ef01cSRoman Divacky     break;
4144f22ef01cSRoman Divacky   }
4145f22ef01cSRoman Divacky   case Decl::ObjCCompatibleAlias:
4146dff0c46cSDimitry Andric     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
4147f22ef01cSRoman Divacky     break;
4148f22ef01cSRoman Divacky 
4149e7145dcbSDimitry Andric   case Decl::PragmaComment: {
4150e7145dcbSDimitry Andric     const auto *PCD = cast<PragmaCommentDecl>(D);
4151e7145dcbSDimitry Andric     switch (PCD->getCommentKind()) {
4152e7145dcbSDimitry Andric     case PCK_Unknown:
4153e7145dcbSDimitry Andric       llvm_unreachable("unexpected pragma comment kind");
4154e7145dcbSDimitry Andric     case PCK_Linker:
4155e7145dcbSDimitry Andric       AppendLinkerOptions(PCD->getArg());
4156e7145dcbSDimitry Andric       break;
4157e7145dcbSDimitry Andric     case PCK_Lib:
4158e7145dcbSDimitry Andric       AddDependentLib(PCD->getArg());
4159e7145dcbSDimitry Andric       break;
4160e7145dcbSDimitry Andric     case PCK_Compiler:
4161e7145dcbSDimitry Andric     case PCK_ExeStr:
4162e7145dcbSDimitry Andric     case PCK_User:
4163e7145dcbSDimitry Andric       break; // We ignore all of these.
4164e7145dcbSDimitry Andric     }
4165e7145dcbSDimitry Andric     break;
4166e7145dcbSDimitry Andric   }
4167e7145dcbSDimitry Andric 
4168e7145dcbSDimitry Andric   case Decl::PragmaDetectMismatch: {
4169e7145dcbSDimitry Andric     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
4170e7145dcbSDimitry Andric     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
4171e7145dcbSDimitry Andric     break;
4172e7145dcbSDimitry Andric   }
4173e7145dcbSDimitry Andric 
4174f22ef01cSRoman Divacky   case Decl::LinkageSpec:
4175f22ef01cSRoman Divacky     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
4176f22ef01cSRoman Divacky     break;
4177f22ef01cSRoman Divacky 
4178f22ef01cSRoman Divacky   case Decl::FileScopeAsm: {
417933956c43SDimitry Andric     // File-scope asm is ignored during device-side CUDA compilation.
418033956c43SDimitry Andric     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
418133956c43SDimitry Andric       break;
4182ea942507SDimitry Andric     // File-scope asm is ignored during device-side OpenMP compilation.
4183ea942507SDimitry Andric     if (LangOpts.OpenMPIsDevice)
4184ea942507SDimitry Andric       break;
418559d1ed5bSDimitry Andric     auto *AD = cast<FileScopeAsmDecl>(D);
418633956c43SDimitry Andric     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
4187f22ef01cSRoman Divacky     break;
4188f22ef01cSRoman Divacky   }
4189f22ef01cSRoman Divacky 
4190139f7f9bSDimitry Andric   case Decl::Import: {
419159d1ed5bSDimitry Andric     auto *Import = cast<ImportDecl>(D);
4192139f7f9bSDimitry Andric 
419344290647SDimitry Andric     // If we've already imported this module, we're done.
419444290647SDimitry Andric     if (!ImportedModules.insert(Import->getImportedModule()))
4195139f7f9bSDimitry Andric       break;
419644290647SDimitry Andric 
419744290647SDimitry Andric     // Emit debug information for direct imports.
419844290647SDimitry Andric     if (!Import->getImportedOwningModule()) {
41993dac3a9bSDimitry Andric       if (CGDebugInfo *DI = getModuleDebugInfo())
42003dac3a9bSDimitry Andric         DI->EmitImportDecl(*Import);
420144290647SDimitry Andric     }
4202139f7f9bSDimitry Andric 
420344290647SDimitry Andric     // Find all of the submodules and emit the module initializers.
420444290647SDimitry Andric     llvm::SmallPtrSet<clang::Module *, 16> Visited;
420544290647SDimitry Andric     SmallVector<clang::Module *, 16> Stack;
420644290647SDimitry Andric     Visited.insert(Import->getImportedModule());
420744290647SDimitry Andric     Stack.push_back(Import->getImportedModule());
420844290647SDimitry Andric 
420944290647SDimitry Andric     while (!Stack.empty()) {
421044290647SDimitry Andric       clang::Module *Mod = Stack.pop_back_val();
421144290647SDimitry Andric       if (!EmittedModuleInitializers.insert(Mod).second)
421244290647SDimitry Andric         continue;
421344290647SDimitry Andric 
421444290647SDimitry Andric       for (auto *D : Context.getModuleInitializers(Mod))
421544290647SDimitry Andric         EmitTopLevelDecl(D);
421644290647SDimitry Andric 
421744290647SDimitry Andric       // Visit the submodules of this module.
421844290647SDimitry Andric       for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
421944290647SDimitry Andric                                              SubEnd = Mod->submodule_end();
422044290647SDimitry Andric            Sub != SubEnd; ++Sub) {
422144290647SDimitry Andric         // Skip explicit children; they need to be explicitly imported to emit
422244290647SDimitry Andric         // the initializers.
422344290647SDimitry Andric         if ((*Sub)->IsExplicit)
422444290647SDimitry Andric           continue;
422544290647SDimitry Andric 
422644290647SDimitry Andric         if (Visited.insert(*Sub).second)
422744290647SDimitry Andric           Stack.push_back(*Sub);
422844290647SDimitry Andric       }
422944290647SDimitry Andric     }
4230139f7f9bSDimitry Andric     break;
4231139f7f9bSDimitry Andric   }
4232139f7f9bSDimitry Andric 
423344290647SDimitry Andric   case Decl::Export:
423444290647SDimitry Andric     EmitDeclContext(cast<ExportDecl>(D));
423544290647SDimitry Andric     break;
423644290647SDimitry Andric 
423739d628a0SDimitry Andric   case Decl::OMPThreadPrivate:
423839d628a0SDimitry Andric     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
423939d628a0SDimitry Andric     break;
424039d628a0SDimitry Andric 
4241e7145dcbSDimitry Andric   case Decl::OMPDeclareReduction:
4242e7145dcbSDimitry Andric     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
4243e7145dcbSDimitry Andric     break;
4244e7145dcbSDimitry Andric 
4245f22ef01cSRoman Divacky   default:
4246f22ef01cSRoman Divacky     // Make sure we handled everything we should, every other kind is a
4247f22ef01cSRoman Divacky     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
4248f22ef01cSRoman Divacky     // function. Need to recode Decl::Kind to do that easily.
4249f22ef01cSRoman Divacky     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
425039d628a0SDimitry Andric     break;
425139d628a0SDimitry Andric   }
425239d628a0SDimitry Andric }
425339d628a0SDimitry Andric 
425439d628a0SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
425539d628a0SDimitry Andric   // Do we need to generate coverage mapping?
425639d628a0SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
425739d628a0SDimitry Andric     return;
425839d628a0SDimitry Andric   switch (D->getKind()) {
425939d628a0SDimitry Andric   case Decl::CXXConversion:
426039d628a0SDimitry Andric   case Decl::CXXMethod:
426139d628a0SDimitry Andric   case Decl::Function:
426239d628a0SDimitry Andric   case Decl::ObjCMethod:
426339d628a0SDimitry Andric   case Decl::CXXConstructor:
426439d628a0SDimitry Andric   case Decl::CXXDestructor: {
42650623d748SDimitry Andric     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
426639d628a0SDimitry Andric       return;
42679a199699SDimitry Andric     SourceManager &SM = getContext().getSourceManager();
42689a199699SDimitry Andric     if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getLocStart()))
42699a199699SDimitry Andric       return;
427039d628a0SDimitry Andric     auto I = DeferredEmptyCoverageMappingDecls.find(D);
427139d628a0SDimitry Andric     if (I == DeferredEmptyCoverageMappingDecls.end())
427239d628a0SDimitry Andric       DeferredEmptyCoverageMappingDecls[D] = true;
427339d628a0SDimitry Andric     break;
427439d628a0SDimitry Andric   }
427539d628a0SDimitry Andric   default:
427639d628a0SDimitry Andric     break;
427739d628a0SDimitry Andric   };
427839d628a0SDimitry Andric }
427939d628a0SDimitry Andric 
428039d628a0SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
428139d628a0SDimitry Andric   // Do we need to generate coverage mapping?
428239d628a0SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
428339d628a0SDimitry Andric     return;
428439d628a0SDimitry Andric   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
428539d628a0SDimitry Andric     if (Fn->isTemplateInstantiation())
428639d628a0SDimitry Andric       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
428739d628a0SDimitry Andric   }
428839d628a0SDimitry Andric   auto I = DeferredEmptyCoverageMappingDecls.find(D);
428939d628a0SDimitry Andric   if (I == DeferredEmptyCoverageMappingDecls.end())
429039d628a0SDimitry Andric     DeferredEmptyCoverageMappingDecls[D] = false;
429139d628a0SDimitry Andric   else
429239d628a0SDimitry Andric     I->second = false;
429339d628a0SDimitry Andric }
429439d628a0SDimitry Andric 
429539d628a0SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
429613ddaa84SDimitry Andric   // We call takeVector() here to avoid use-after-free.
429713ddaa84SDimitry Andric   // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
429813ddaa84SDimitry Andric   // we deserialize function bodies to emit coverage info for them, and that
429913ddaa84SDimitry Andric   // deserializes more declarations. How should we handle that case?
430013ddaa84SDimitry Andric   for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
43019a199699SDimitry Andric     if (!Entry.second)
430239d628a0SDimitry Andric       continue;
43039a199699SDimitry Andric     const Decl *D = Entry.first;
430439d628a0SDimitry Andric     switch (D->getKind()) {
430539d628a0SDimitry Andric     case Decl::CXXConversion:
430639d628a0SDimitry Andric     case Decl::CXXMethod:
430739d628a0SDimitry Andric     case Decl::Function:
430839d628a0SDimitry Andric     case Decl::ObjCMethod: {
430939d628a0SDimitry Andric       CodeGenPGO PGO(*this);
431039d628a0SDimitry Andric       GlobalDecl GD(cast<FunctionDecl>(D));
431139d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
431239d628a0SDimitry Andric                                   getFunctionLinkage(GD));
431339d628a0SDimitry Andric       break;
431439d628a0SDimitry Andric     }
431539d628a0SDimitry Andric     case Decl::CXXConstructor: {
431639d628a0SDimitry Andric       CodeGenPGO PGO(*this);
431739d628a0SDimitry Andric       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
431839d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
431939d628a0SDimitry Andric                                   getFunctionLinkage(GD));
432039d628a0SDimitry Andric       break;
432139d628a0SDimitry Andric     }
432239d628a0SDimitry Andric     case Decl::CXXDestructor: {
432339d628a0SDimitry Andric       CodeGenPGO PGO(*this);
432439d628a0SDimitry Andric       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
432539d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
432639d628a0SDimitry Andric                                   getFunctionLinkage(GD));
432739d628a0SDimitry Andric       break;
432839d628a0SDimitry Andric     }
432939d628a0SDimitry Andric     default:
433039d628a0SDimitry Andric       break;
433139d628a0SDimitry Andric     };
4332f22ef01cSRoman Divacky   }
4333f22ef01cSRoman Divacky }
4334ffd1746dSEd Schouten 
4335ffd1746dSEd Schouten /// Turns the given pointer into a constant.
4336ffd1746dSEd Schouten static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
4337ffd1746dSEd Schouten                                           const void *Ptr) {
4338ffd1746dSEd Schouten   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
43396122f3e6SDimitry Andric   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
4340ffd1746dSEd Schouten   return llvm::ConstantInt::get(i64, PtrInt);
4341ffd1746dSEd Schouten }
4342ffd1746dSEd Schouten 
4343ffd1746dSEd Schouten static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
4344ffd1746dSEd Schouten                                    llvm::NamedMDNode *&GlobalMetadata,
4345ffd1746dSEd Schouten                                    GlobalDecl D,
4346ffd1746dSEd Schouten                                    llvm::GlobalValue *Addr) {
4347ffd1746dSEd Schouten   if (!GlobalMetadata)
4348ffd1746dSEd Schouten     GlobalMetadata =
4349ffd1746dSEd Schouten       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
4350ffd1746dSEd Schouten 
4351ffd1746dSEd Schouten   // TODO: should we report variant information for ctors/dtors?
435239d628a0SDimitry Andric   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
435339d628a0SDimitry Andric                            llvm::ConstantAsMetadata::get(GetPointerConstant(
435439d628a0SDimitry Andric                                CGM.getLLVMContext(), D.getDecl()))};
43553b0f4066SDimitry Andric   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
4356ffd1746dSEd Schouten }
4357ffd1746dSEd Schouten 
4358284c1978SDimitry Andric /// For each function which is declared within an extern "C" region and marked
4359284c1978SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled
4360284c1978SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer
4361284c1978SDimitry Andric /// to such functions with an unmangled name from inline assembly within the
4362284c1978SDimitry Andric /// same translation unit.
4363284c1978SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() {
4364e7145dcbSDimitry Andric   // Don't do anything if we're generating CUDA device code -- the NVPTX
4365e7145dcbSDimitry Andric   // assembly target doesn't support aliases.
4366e7145dcbSDimitry Andric   if (Context.getTargetInfo().getTriple().isNVPTX())
4367e7145dcbSDimitry Andric     return;
43688f0fd8f6SDimitry Andric   for (auto &I : StaticExternCValues) {
43698f0fd8f6SDimitry Andric     IdentifierInfo *Name = I.first;
43708f0fd8f6SDimitry Andric     llvm::GlobalValue *Val = I.second;
4371284c1978SDimitry Andric     if (Val && !getModule().getNamedValue(Name->getName()))
437259d1ed5bSDimitry Andric       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
4373284c1978SDimitry Andric   }
4374284c1978SDimitry Andric }
4375284c1978SDimitry Andric 
437659d1ed5bSDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
437759d1ed5bSDimitry Andric                                              GlobalDecl &Result) const {
437859d1ed5bSDimitry Andric   auto Res = Manglings.find(MangledName);
437959d1ed5bSDimitry Andric   if (Res == Manglings.end())
438059d1ed5bSDimitry Andric     return false;
438159d1ed5bSDimitry Andric   Result = Res->getValue();
438259d1ed5bSDimitry Andric   return true;
438359d1ed5bSDimitry Andric }
438459d1ed5bSDimitry Andric 
4385ffd1746dSEd Schouten /// Emits metadata nodes associating all the global values in the
4386ffd1746dSEd Schouten /// current module with the Decls they came from.  This is useful for
4387ffd1746dSEd Schouten /// projects using IR gen as a subroutine.
4388ffd1746dSEd Schouten ///
4389ffd1746dSEd Schouten /// Since there's currently no way to associate an MDNode directly
4390ffd1746dSEd Schouten /// with an llvm::GlobalValue, we create a global named metadata
4391ffd1746dSEd Schouten /// with the name 'clang.global.decl.ptrs'.
4392ffd1746dSEd Schouten void CodeGenModule::EmitDeclMetadata() {
439359d1ed5bSDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
4394ffd1746dSEd Schouten 
439559d1ed5bSDimitry Andric   for (auto &I : MangledDeclNames) {
439659d1ed5bSDimitry Andric     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
43970623d748SDimitry Andric     // Some mangled names don't necessarily have an associated GlobalValue
43980623d748SDimitry Andric     // in this module, e.g. if we mangled it for DebugInfo.
43990623d748SDimitry Andric     if (Addr)
440059d1ed5bSDimitry Andric       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
4401ffd1746dSEd Schouten   }
4402ffd1746dSEd Schouten }
4403ffd1746dSEd Schouten 
4404ffd1746dSEd Schouten /// Emits metadata nodes for all the local variables in the current
4405ffd1746dSEd Schouten /// function.
4406ffd1746dSEd Schouten void CodeGenFunction::EmitDeclMetadata() {
4407ffd1746dSEd Schouten   if (LocalDeclMap.empty()) return;
4408ffd1746dSEd Schouten 
4409ffd1746dSEd Schouten   llvm::LLVMContext &Context = getLLVMContext();
4410ffd1746dSEd Schouten 
4411ffd1746dSEd Schouten   // Find the unique metadata ID for this name.
4412ffd1746dSEd Schouten   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
4413ffd1746dSEd Schouten 
441459d1ed5bSDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
4415ffd1746dSEd Schouten 
441659d1ed5bSDimitry Andric   for (auto &I : LocalDeclMap) {
441759d1ed5bSDimitry Andric     const Decl *D = I.first;
44180623d748SDimitry Andric     llvm::Value *Addr = I.second.getPointer();
441959d1ed5bSDimitry Andric     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
4420ffd1746dSEd Schouten       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
442139d628a0SDimitry Andric       Alloca->setMetadata(
442239d628a0SDimitry Andric           DeclPtrKind, llvm::MDNode::get(
442339d628a0SDimitry Andric                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
442459d1ed5bSDimitry Andric     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
4425ffd1746dSEd Schouten       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
4426ffd1746dSEd Schouten       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
4427ffd1746dSEd Schouten     }
4428ffd1746dSEd Schouten   }
4429ffd1746dSEd Schouten }
4430e580952dSDimitry Andric 
4431f785676fSDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() {
4432f785676fSDimitry Andric   llvm::NamedMDNode *IdentMetadata =
4433f785676fSDimitry Andric     TheModule.getOrInsertNamedMetadata("llvm.ident");
4434f785676fSDimitry Andric   std::string Version = getClangFullVersion();
4435f785676fSDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
4436f785676fSDimitry Andric 
443739d628a0SDimitry Andric   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
4438f785676fSDimitry Andric   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4439f785676fSDimitry Andric }
4440f785676fSDimitry Andric 
444159d1ed5bSDimitry Andric void CodeGenModule::EmitTargetMetadata() {
444239d628a0SDimitry Andric   // Warning, new MangledDeclNames may be appended within this loop.
444339d628a0SDimitry Andric   // We rely on MapVector insertions adding new elements to the end
444439d628a0SDimitry Andric   // of the container.
444539d628a0SDimitry Andric   // FIXME: Move this loop into the one target that needs it, and only
444639d628a0SDimitry Andric   // loop over those declarations for which we couldn't emit the target
444739d628a0SDimitry Andric   // metadata when we emitted the declaration.
444839d628a0SDimitry Andric   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
444939d628a0SDimitry Andric     auto Val = *(MangledDeclNames.begin() + I);
445039d628a0SDimitry Andric     const Decl *D = Val.first.getDecl()->getMostRecentDecl();
445139d628a0SDimitry Andric     llvm::GlobalValue *GV = GetGlobalValue(Val.second);
445259d1ed5bSDimitry Andric     getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
445359d1ed5bSDimitry Andric   }
445459d1ed5bSDimitry Andric }
445559d1ed5bSDimitry Andric 
4456bd5abe19SDimitry Andric void CodeGenModule::EmitCoverageFile() {
445744290647SDimitry Andric   if (getCodeGenOpts().CoverageDataFile.empty() &&
445844290647SDimitry Andric       getCodeGenOpts().CoverageNotesFile.empty())
445944290647SDimitry Andric     return;
446044290647SDimitry Andric 
446144290647SDimitry Andric   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
446244290647SDimitry Andric   if (!CUNode)
446344290647SDimitry Andric     return;
446444290647SDimitry Andric 
4465bd5abe19SDimitry Andric   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
4466bd5abe19SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
446744290647SDimitry Andric   auto *CoverageDataFile =
446844290647SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
446944290647SDimitry Andric   auto *CoverageNotesFile =
447044290647SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
4471bd5abe19SDimitry Andric   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
4472bd5abe19SDimitry Andric     llvm::MDNode *CU = CUNode->getOperand(i);
447344290647SDimitry Andric     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
447439d628a0SDimitry Andric     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
4475bd5abe19SDimitry Andric   }
4476bd5abe19SDimitry Andric }
44773861d79fSDimitry Andric 
447839d628a0SDimitry Andric llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
44793861d79fSDimitry Andric   // Sema has checked that all uuid strings are of the form
44803861d79fSDimitry Andric   // "12345678-1234-1234-1234-1234567890ab".
44813861d79fSDimitry Andric   assert(Uuid.size() == 36);
4482f785676fSDimitry Andric   for (unsigned i = 0; i < 36; ++i) {
4483f785676fSDimitry Andric     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
4484f785676fSDimitry Andric     else                                         assert(isHexDigit(Uuid[i]));
44853861d79fSDimitry Andric   }
44863861d79fSDimitry Andric 
448739d628a0SDimitry Andric   // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
4488f785676fSDimitry Andric   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
44893861d79fSDimitry Andric 
4490f785676fSDimitry Andric   llvm::Constant *Field3[8];
4491f785676fSDimitry Andric   for (unsigned Idx = 0; Idx < 8; ++Idx)
4492f785676fSDimitry Andric     Field3[Idx] = llvm::ConstantInt::get(
4493f785676fSDimitry Andric         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
44943861d79fSDimitry Andric 
4495f785676fSDimitry Andric   llvm::Constant *Fields[4] = {
4496f785676fSDimitry Andric     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
4497f785676fSDimitry Andric     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
4498f785676fSDimitry Andric     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
4499f785676fSDimitry Andric     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
4500f785676fSDimitry Andric   };
4501f785676fSDimitry Andric 
4502f785676fSDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
45033861d79fSDimitry Andric }
450459d1ed5bSDimitry Andric 
450559d1ed5bSDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
450659d1ed5bSDimitry Andric                                                        bool ForEH) {
450759d1ed5bSDimitry Andric   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
450859d1ed5bSDimitry Andric   // FIXME: should we even be calling this method if RTTI is disabled
450959d1ed5bSDimitry Andric   // and it's not for EH?
451059d1ed5bSDimitry Andric   if (!ForEH && !getLangOpts().RTTI)
451159d1ed5bSDimitry Andric     return llvm::Constant::getNullValue(Int8PtrTy);
451259d1ed5bSDimitry Andric 
451359d1ed5bSDimitry Andric   if (ForEH && Ty->isObjCObjectPointerType() &&
451459d1ed5bSDimitry Andric       LangOpts.ObjCRuntime.isGNUFamily())
451559d1ed5bSDimitry Andric     return ObjCRuntime->GetEHType(Ty);
451659d1ed5bSDimitry Andric 
451759d1ed5bSDimitry Andric   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
451859d1ed5bSDimitry Andric }
451959d1ed5bSDimitry Andric 
452039d628a0SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
452130785c0eSDimitry Andric   // Do not emit threadprivates in simd-only mode.
452230785c0eSDimitry Andric   if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
452330785c0eSDimitry Andric     return;
452439d628a0SDimitry Andric   for (auto RefExpr : D->varlists()) {
452539d628a0SDimitry Andric     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
452639d628a0SDimitry Andric     bool PerformInit =
452739d628a0SDimitry Andric         VD->getAnyInitializer() &&
452839d628a0SDimitry Andric         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
452939d628a0SDimitry Andric                                                         /*ForRef=*/false);
45300623d748SDimitry Andric 
45310623d748SDimitry Andric     Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
453233956c43SDimitry Andric     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
45330623d748SDimitry Andric             VD, Addr, RefExpr->getLocStart(), PerformInit))
453439d628a0SDimitry Andric       CXXGlobalInits.push_back(InitFunction);
453539d628a0SDimitry Andric   }
453639d628a0SDimitry Andric }
45378f0fd8f6SDimitry Andric 
45380623d748SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
45390623d748SDimitry Andric   llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
45400623d748SDimitry Andric   if (InternalId)
45410623d748SDimitry Andric     return InternalId;
45420623d748SDimitry Andric 
45430623d748SDimitry Andric   if (isExternallyVisible(T->getLinkage())) {
45448f0fd8f6SDimitry Andric     std::string OutName;
45458f0fd8f6SDimitry Andric     llvm::raw_string_ostream Out(OutName);
45460623d748SDimitry Andric     getCXXABI().getMangleContext().mangleTypeName(T, Out);
45478f0fd8f6SDimitry Andric 
45480623d748SDimitry Andric     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
45490623d748SDimitry Andric   } else {
45500623d748SDimitry Andric     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
45510623d748SDimitry Andric                                            llvm::ArrayRef<llvm::Metadata *>());
45520623d748SDimitry Andric   }
45530623d748SDimitry Andric 
45540623d748SDimitry Andric   return InternalId;
45550623d748SDimitry Andric }
45560623d748SDimitry Andric 
45579a199699SDimitry Andric // Generalize pointer types to a void pointer with the qualifiers of the
45589a199699SDimitry Andric // originally pointed-to type, e.g. 'const char *' and 'char * const *'
45599a199699SDimitry Andric // generalize to 'const void *' while 'char *' and 'const char **' generalize to
45609a199699SDimitry Andric // 'void *'.
45619a199699SDimitry Andric static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
45629a199699SDimitry Andric   if (!Ty->isPointerType())
45639a199699SDimitry Andric     return Ty;
45649a199699SDimitry Andric 
45659a199699SDimitry Andric   return Ctx.getPointerType(
45669a199699SDimitry Andric       QualType(Ctx.VoidTy).withCVRQualifiers(
45679a199699SDimitry Andric           Ty->getPointeeType().getCVRQualifiers()));
45689a199699SDimitry Andric }
45699a199699SDimitry Andric 
45709a199699SDimitry Andric // Apply type generalization to a FunctionType's return and argument types
45719a199699SDimitry Andric static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
45729a199699SDimitry Andric   if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
45739a199699SDimitry Andric     SmallVector<QualType, 8> GeneralizedParams;
45749a199699SDimitry Andric     for (auto &Param : FnType->param_types())
45759a199699SDimitry Andric       GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
45769a199699SDimitry Andric 
45779a199699SDimitry Andric     return Ctx.getFunctionType(
45789a199699SDimitry Andric         GeneralizeType(Ctx, FnType->getReturnType()),
45799a199699SDimitry Andric         GeneralizedParams, FnType->getExtProtoInfo());
45809a199699SDimitry Andric   }
45819a199699SDimitry Andric 
45829a199699SDimitry Andric   if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
45839a199699SDimitry Andric     return Ctx.getFunctionNoProtoType(
45849a199699SDimitry Andric         GeneralizeType(Ctx, FnType->getReturnType()));
45859a199699SDimitry Andric 
45869a199699SDimitry Andric   llvm_unreachable("Encountered unknown FunctionType");
45879a199699SDimitry Andric }
45889a199699SDimitry Andric 
45899a199699SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
45909a199699SDimitry Andric   T = GeneralizeFunctionType(getContext(), T);
45919a199699SDimitry Andric 
45929a199699SDimitry Andric   llvm::Metadata *&InternalId = GeneralizedMetadataIdMap[T.getCanonicalType()];
45939a199699SDimitry Andric   if (InternalId)
45949a199699SDimitry Andric     return InternalId;
45959a199699SDimitry Andric 
45969a199699SDimitry Andric   if (isExternallyVisible(T->getLinkage())) {
45979a199699SDimitry Andric     std::string OutName;
45989a199699SDimitry Andric     llvm::raw_string_ostream Out(OutName);
45999a199699SDimitry Andric     getCXXABI().getMangleContext().mangleTypeName(T, Out);
46009a199699SDimitry Andric     Out << ".generalized";
46019a199699SDimitry Andric 
46029a199699SDimitry Andric     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
46039a199699SDimitry Andric   } else {
46049a199699SDimitry Andric     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
46059a199699SDimitry Andric                                            llvm::ArrayRef<llvm::Metadata *>());
46069a199699SDimitry Andric   }
46079a199699SDimitry Andric 
46089a199699SDimitry Andric   return InternalId;
46099a199699SDimitry Andric }
46109a199699SDimitry Andric 
4611e7145dcbSDimitry Andric /// Returns whether this module needs the "all-vtables" type identifier.
4612e7145dcbSDimitry Andric bool CodeGenModule::NeedAllVtablesTypeId() const {
4613e7145dcbSDimitry Andric   // Returns true if at least one of vtable-based CFI checkers is enabled and
4614e7145dcbSDimitry Andric   // is not in the trapping mode.
4615e7145dcbSDimitry Andric   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
4616e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
4617e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
4618e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
4619e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
4620e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
4621e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
4622e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
4623e7145dcbSDimitry Andric }
4624e7145dcbSDimitry Andric 
4625e7145dcbSDimitry Andric void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
46260623d748SDimitry Andric                                           CharUnits Offset,
46270623d748SDimitry Andric                                           const CXXRecordDecl *RD) {
46280623d748SDimitry Andric   llvm::Metadata *MD =
46290623d748SDimitry Andric       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
4630e7145dcbSDimitry Andric   VTable->addTypeMetadata(Offset.getQuantity(), MD);
46310623d748SDimitry Andric 
4632e7145dcbSDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
4633e7145dcbSDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
4634e7145dcbSDimitry Andric       VTable->addTypeMetadata(Offset.getQuantity(),
4635e7145dcbSDimitry Andric                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
4636e7145dcbSDimitry Andric 
4637e7145dcbSDimitry Andric   if (NeedAllVtablesTypeId()) {
4638e7145dcbSDimitry Andric     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
4639e7145dcbSDimitry Andric     VTable->addTypeMetadata(Offset.getQuantity(), MD);
46400623d748SDimitry Andric   }
46410623d748SDimitry Andric }
46420623d748SDimitry Andric 
46430623d748SDimitry Andric // Fills in the supplied string map with the set of target features for the
46440623d748SDimitry Andric // passed in function.
46450623d748SDimitry Andric void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
46460623d748SDimitry Andric                                           const FunctionDecl *FD) {
46470623d748SDimitry Andric   StringRef TargetCPU = Target.getTargetOpts().CPU;
46480623d748SDimitry Andric   if (const auto *TD = FD->getAttr<TargetAttr>()) {
46490623d748SDimitry Andric     // If we have a TargetAttr build up the feature map based on that.
46500623d748SDimitry Andric     TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
46510623d748SDimitry Andric 
46529a199699SDimitry Andric     ParsedAttr.Features.erase(
46539a199699SDimitry Andric         llvm::remove_if(ParsedAttr.Features,
46549a199699SDimitry Andric                         [&](const std::string &Feat) {
46559a199699SDimitry Andric                           return !Target.isValidFeatureName(
46569a199699SDimitry Andric                               StringRef{Feat}.substr(1));
46579a199699SDimitry Andric                         }),
46589a199699SDimitry Andric         ParsedAttr.Features.end());
46599a199699SDimitry Andric 
46600623d748SDimitry Andric     // Make a copy of the features as passed on the command line into the
46610623d748SDimitry Andric     // beginning of the additional features from the function to override.
4662b40b48b8SDimitry Andric     ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
46630623d748SDimitry Andric                             Target.getTargetOpts().FeaturesAsWritten.begin(),
46640623d748SDimitry Andric                             Target.getTargetOpts().FeaturesAsWritten.end());
46650623d748SDimitry Andric 
46669a199699SDimitry Andric     if (ParsedAttr.Architecture != "" &&
46679a199699SDimitry Andric         Target.isValidCPUName(ParsedAttr.Architecture))
4668b40b48b8SDimitry Andric       TargetCPU = ParsedAttr.Architecture;
46690623d748SDimitry Andric 
46700623d748SDimitry Andric     // Now populate the feature map, first with the TargetCPU which is either
46710623d748SDimitry Andric     // the default or a new one from the target attribute string. Then we'll use
46720623d748SDimitry Andric     // the passed in features (FeaturesAsWritten) along with the new ones from
46730623d748SDimitry Andric     // the attribute.
4674b40b48b8SDimitry Andric     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
4675b40b48b8SDimitry Andric                           ParsedAttr.Features);
46760623d748SDimitry Andric   } else {
46770623d748SDimitry Andric     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
46780623d748SDimitry Andric                           Target.getTargetOpts().Features);
46790623d748SDimitry Andric   }
46808f0fd8f6SDimitry Andric }
4681e7145dcbSDimitry Andric 
4682e7145dcbSDimitry Andric llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
4683e7145dcbSDimitry Andric   if (!SanStats)
4684e7145dcbSDimitry Andric     SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
4685e7145dcbSDimitry Andric 
4686e7145dcbSDimitry Andric   return *SanStats;
4687e7145dcbSDimitry Andric }
468844290647SDimitry Andric llvm::Value *
468944290647SDimitry Andric CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
469044290647SDimitry Andric                                                   CodeGenFunction &CGF) {
46919a199699SDimitry Andric   llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
46929a199699SDimitry Andric   auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
469344290647SDimitry Andric   auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
469444290647SDimitry Andric   return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
469544290647SDimitry Andric                                 "__translate_sampler_initializer"),
469644290647SDimitry Andric                                 {C});
469744290647SDimitry Andric }
4698