1*0b57cec5SDimitry Andric //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric //
9*0b57cec5SDimitry Andric // This coordinates the per-module state used while generating code.
10*0b57cec5SDimitry Andric //
11*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
12*0b57cec5SDimitry Andric 
13*0b57cec5SDimitry Andric #include "CodeGenModule.h"
14*0b57cec5SDimitry Andric #include "CGBlocks.h"
15*0b57cec5SDimitry Andric #include "CGCUDARuntime.h"
16*0b57cec5SDimitry Andric #include "CGCXXABI.h"
17*0b57cec5SDimitry Andric #include "CGCall.h"
18*0b57cec5SDimitry Andric #include "CGDebugInfo.h"
19*0b57cec5SDimitry Andric #include "CGObjCRuntime.h"
20*0b57cec5SDimitry Andric #include "CGOpenCLRuntime.h"
21*0b57cec5SDimitry Andric #include "CGOpenMPRuntime.h"
22*0b57cec5SDimitry Andric #include "CGOpenMPRuntimeNVPTX.h"
23*0b57cec5SDimitry Andric #include "CodeGenFunction.h"
24*0b57cec5SDimitry Andric #include "CodeGenPGO.h"
25*0b57cec5SDimitry Andric #include "ConstantEmitter.h"
26*0b57cec5SDimitry Andric #include "CoverageMappingGen.h"
27*0b57cec5SDimitry Andric #include "TargetInfo.h"
28*0b57cec5SDimitry Andric #include "clang/AST/ASTContext.h"
29*0b57cec5SDimitry Andric #include "clang/AST/CharUnits.h"
30*0b57cec5SDimitry Andric #include "clang/AST/DeclCXX.h"
31*0b57cec5SDimitry Andric #include "clang/AST/DeclObjC.h"
32*0b57cec5SDimitry Andric #include "clang/AST/DeclTemplate.h"
33*0b57cec5SDimitry Andric #include "clang/AST/Mangle.h"
34*0b57cec5SDimitry Andric #include "clang/AST/RecordLayout.h"
35*0b57cec5SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h"
36*0b57cec5SDimitry Andric #include "clang/AST/StmtVisitor.h"
37*0b57cec5SDimitry Andric #include "clang/Basic/Builtins.h"
38*0b57cec5SDimitry Andric #include "clang/Basic/CharInfo.h"
39*0b57cec5SDimitry Andric #include "clang/Basic/CodeGenOptions.h"
40*0b57cec5SDimitry Andric #include "clang/Basic/Diagnostic.h"
415ffd83dbSDimitry Andric #include "clang/Basic/FileManager.h"
42*0b57cec5SDimitry Andric #include "clang/Basic/Module.h"
43*0b57cec5SDimitry Andric #include "clang/Basic/SourceManager.h"
44*0b57cec5SDimitry Andric #include "clang/Basic/TargetInfo.h"
45*0b57cec5SDimitry Andric #include "clang/Basic/Version.h"
46*0b57cec5SDimitry Andric #include "clang/CodeGen/ConstantInitBuilder.h"
47*0b57cec5SDimitry Andric #include "clang/Frontend/FrontendDiagnostic.h"
48*0b57cec5SDimitry Andric #include "llvm/ADT/StringSwitch.h"
49*0b57cec5SDimitry Andric #include "llvm/ADT/Triple.h"
50*0b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
51480093f4SDimitry Andric #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
52*0b57cec5SDimitry Andric #include "llvm/IR/CallingConv.h"
53*0b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
54*0b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
55*0b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
56*0b57cec5SDimitry Andric #include "llvm/IR/Module.h"
57*0b57cec5SDimitry Andric #include "llvm/IR/ProfileSummary.h"
58*0b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProfReader.h"
59*0b57cec5SDimitry Andric #include "llvm/Support/CodeGen.h"
60480093f4SDimitry Andric #include "llvm/Support/CommandLine.h"
61*0b57cec5SDimitry Andric #include "llvm/Support/ConvertUTF.h"
62*0b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
63*0b57cec5SDimitry Andric #include "llvm/Support/MD5.h"
64*0b57cec5SDimitry Andric #include "llvm/Support/TimeProfiler.h"
65*0b57cec5SDimitry Andric 
66*0b57cec5SDimitry Andric using namespace clang;
67*0b57cec5SDimitry Andric using namespace CodeGen;
68*0b57cec5SDimitry Andric 
69*0b57cec5SDimitry Andric static llvm::cl::opt<bool> LimitedCoverage(
70*0b57cec5SDimitry Andric     "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
71*0b57cec5SDimitry Andric     llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
72*0b57cec5SDimitry Andric     llvm::cl::init(false));
73*0b57cec5SDimitry Andric 
74*0b57cec5SDimitry Andric static const char AnnotationSection[] = "llvm.metadata";
75*0b57cec5SDimitry Andric 
76*0b57cec5SDimitry Andric static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
77*0b57cec5SDimitry Andric   switch (CGM.getTarget().getCXXABI().getKind()) {
78480093f4SDimitry Andric   case TargetCXXABI::Fuchsia:
79*0b57cec5SDimitry Andric   case TargetCXXABI::GenericAArch64:
80*0b57cec5SDimitry Andric   case TargetCXXABI::GenericARM:
81*0b57cec5SDimitry Andric   case TargetCXXABI::iOS:
82*0b57cec5SDimitry Andric   case TargetCXXABI::iOS64:
83*0b57cec5SDimitry Andric   case TargetCXXABI::WatchOS:
84*0b57cec5SDimitry Andric   case TargetCXXABI::GenericMIPS:
85*0b57cec5SDimitry Andric   case TargetCXXABI::GenericItanium:
86*0b57cec5SDimitry Andric   case TargetCXXABI::WebAssembly:
875ffd83dbSDimitry Andric   case TargetCXXABI::XL:
88*0b57cec5SDimitry Andric     return CreateItaniumCXXABI(CGM);
89*0b57cec5SDimitry Andric   case TargetCXXABI::Microsoft:
90*0b57cec5SDimitry Andric     return CreateMicrosoftCXXABI(CGM);
91*0b57cec5SDimitry Andric   }
92*0b57cec5SDimitry Andric 
93*0b57cec5SDimitry Andric   llvm_unreachable("invalid C++ ABI kind");
94*0b57cec5SDimitry Andric }
95*0b57cec5SDimitry Andric 
96*0b57cec5SDimitry Andric CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
97*0b57cec5SDimitry Andric                              const PreprocessorOptions &PPO,
98*0b57cec5SDimitry Andric                              const CodeGenOptions &CGO, llvm::Module &M,
99*0b57cec5SDimitry Andric                              DiagnosticsEngine &diags,
100*0b57cec5SDimitry Andric                              CoverageSourceInfo *CoverageInfo)
101*0b57cec5SDimitry Andric     : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
102*0b57cec5SDimitry Andric       PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
103*0b57cec5SDimitry Andric       Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
104*0b57cec5SDimitry Andric       VMContext(M.getContext()), Types(*this), VTables(*this),
105*0b57cec5SDimitry Andric       SanitizerMD(new SanitizerMetadata(*this)) {
106*0b57cec5SDimitry Andric 
107*0b57cec5SDimitry Andric   // Initialize the type cache.
108*0b57cec5SDimitry Andric   llvm::LLVMContext &LLVMContext = M.getContext();
109*0b57cec5SDimitry Andric   VoidTy = llvm::Type::getVoidTy(LLVMContext);
110*0b57cec5SDimitry Andric   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
111*0b57cec5SDimitry Andric   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
112*0b57cec5SDimitry Andric   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
113*0b57cec5SDimitry Andric   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
114*0b57cec5SDimitry Andric   HalfTy = llvm::Type::getHalfTy(LLVMContext);
1155ffd83dbSDimitry Andric   BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
116*0b57cec5SDimitry Andric   FloatTy = llvm::Type::getFloatTy(LLVMContext);
117*0b57cec5SDimitry Andric   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
118*0b57cec5SDimitry Andric   PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
119*0b57cec5SDimitry Andric   PointerAlignInBytes =
120*0b57cec5SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
121*0b57cec5SDimitry Andric   SizeSizeInBytes =
122*0b57cec5SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
123*0b57cec5SDimitry Andric   IntAlignInBytes =
124*0b57cec5SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
125*0b57cec5SDimitry Andric   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
126*0b57cec5SDimitry Andric   IntPtrTy = llvm::IntegerType::get(LLVMContext,
127*0b57cec5SDimitry Andric     C.getTargetInfo().getMaxPointerWidth());
128*0b57cec5SDimitry Andric   Int8PtrTy = Int8Ty->getPointerTo(0);
129*0b57cec5SDimitry Andric   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
130*0b57cec5SDimitry Andric   AllocaInt8PtrTy = Int8Ty->getPointerTo(
131*0b57cec5SDimitry Andric       M.getDataLayout().getAllocaAddrSpace());
132*0b57cec5SDimitry Andric   ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
133*0b57cec5SDimitry Andric 
134*0b57cec5SDimitry Andric   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
135*0b57cec5SDimitry Andric 
136*0b57cec5SDimitry Andric   if (LangOpts.ObjC)
137*0b57cec5SDimitry Andric     createObjCRuntime();
138*0b57cec5SDimitry Andric   if (LangOpts.OpenCL)
139*0b57cec5SDimitry Andric     createOpenCLRuntime();
140*0b57cec5SDimitry Andric   if (LangOpts.OpenMP)
141*0b57cec5SDimitry Andric     createOpenMPRuntime();
142*0b57cec5SDimitry Andric   if (LangOpts.CUDA)
143*0b57cec5SDimitry Andric     createCUDARuntime();
144*0b57cec5SDimitry Andric 
145*0b57cec5SDimitry Andric   // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
146*0b57cec5SDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
147*0b57cec5SDimitry Andric       (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
148*0b57cec5SDimitry Andric     TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
149*0b57cec5SDimitry Andric                                getCXXABI().getMangleContext()));
150*0b57cec5SDimitry Andric 
151*0b57cec5SDimitry Andric   // If debug info or coverage generation is enabled, create the CGDebugInfo
152*0b57cec5SDimitry Andric   // object.
153*0b57cec5SDimitry Andric   if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
154*0b57cec5SDimitry Andric       CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
155*0b57cec5SDimitry Andric     DebugInfo.reset(new CGDebugInfo(*this));
156*0b57cec5SDimitry Andric 
157*0b57cec5SDimitry Andric   Block.GlobalUniqueCount = 0;
158*0b57cec5SDimitry Andric 
159*0b57cec5SDimitry Andric   if (C.getLangOpts().ObjC)
160*0b57cec5SDimitry Andric     ObjCData.reset(new ObjCEntrypoints());
161*0b57cec5SDimitry Andric 
162*0b57cec5SDimitry Andric   if (CodeGenOpts.hasProfileClangUse()) {
163*0b57cec5SDimitry Andric     auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
164*0b57cec5SDimitry Andric         CodeGenOpts.ProfileInstrumentUsePath, CodeGenOpts.ProfileRemappingFile);
165*0b57cec5SDimitry Andric     if (auto E = ReaderOrErr.takeError()) {
166*0b57cec5SDimitry Andric       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
167*0b57cec5SDimitry Andric                                               "Could not read profile %0: %1");
168*0b57cec5SDimitry Andric       llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
169*0b57cec5SDimitry Andric         getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
170*0b57cec5SDimitry Andric                                   << EI.message();
171*0b57cec5SDimitry Andric       });
172*0b57cec5SDimitry Andric     } else
173*0b57cec5SDimitry Andric       PGOReader = std::move(ReaderOrErr.get());
174*0b57cec5SDimitry Andric   }
175*0b57cec5SDimitry Andric 
176*0b57cec5SDimitry Andric   // If coverage mapping generation is enabled, create the
177*0b57cec5SDimitry Andric   // CoverageMappingModuleGen object.
178*0b57cec5SDimitry Andric   if (CodeGenOpts.CoverageMapping)
179*0b57cec5SDimitry Andric     CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
180*0b57cec5SDimitry Andric }
181*0b57cec5SDimitry Andric 
182*0b57cec5SDimitry Andric CodeGenModule::~CodeGenModule() {}
183*0b57cec5SDimitry Andric 
184*0b57cec5SDimitry Andric void CodeGenModule::createObjCRuntime() {
185*0b57cec5SDimitry Andric   // This is just isGNUFamily(), but we want to force implementors of
186*0b57cec5SDimitry Andric   // new ABIs to decide how best to do this.
187*0b57cec5SDimitry Andric   switch (LangOpts.ObjCRuntime.getKind()) {
188*0b57cec5SDimitry Andric   case ObjCRuntime::GNUstep:
189*0b57cec5SDimitry Andric   case ObjCRuntime::GCC:
190*0b57cec5SDimitry Andric   case ObjCRuntime::ObjFW:
191*0b57cec5SDimitry Andric     ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
192*0b57cec5SDimitry Andric     return;
193*0b57cec5SDimitry Andric 
194*0b57cec5SDimitry Andric   case ObjCRuntime::FragileMacOSX:
195*0b57cec5SDimitry Andric   case ObjCRuntime::MacOSX:
196*0b57cec5SDimitry Andric   case ObjCRuntime::iOS:
197*0b57cec5SDimitry Andric   case ObjCRuntime::WatchOS:
198*0b57cec5SDimitry Andric     ObjCRuntime.reset(CreateMacObjCRuntime(*this));
199*0b57cec5SDimitry Andric     return;
200*0b57cec5SDimitry Andric   }
201*0b57cec5SDimitry Andric   llvm_unreachable("bad runtime kind");
202*0b57cec5SDimitry Andric }
203*0b57cec5SDimitry Andric 
204*0b57cec5SDimitry Andric void CodeGenModule::createOpenCLRuntime() {
205*0b57cec5SDimitry Andric   OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
206*0b57cec5SDimitry Andric }
207*0b57cec5SDimitry Andric 
208*0b57cec5SDimitry Andric void CodeGenModule::createOpenMPRuntime() {
209*0b57cec5SDimitry Andric   // Select a specialized code generation class based on the target, if any.
210*0b57cec5SDimitry Andric   // If it does not exist use the default implementation.
211*0b57cec5SDimitry Andric   switch (getTriple().getArch()) {
212*0b57cec5SDimitry Andric   case llvm::Triple::nvptx:
213*0b57cec5SDimitry Andric   case llvm::Triple::nvptx64:
214*0b57cec5SDimitry Andric     assert(getLangOpts().OpenMPIsDevice &&
215*0b57cec5SDimitry Andric            "OpenMP NVPTX is only prepared to deal with device code.");
216*0b57cec5SDimitry Andric     OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
217*0b57cec5SDimitry Andric     break;
218*0b57cec5SDimitry Andric   default:
219*0b57cec5SDimitry Andric     if (LangOpts.OpenMPSimd)
220*0b57cec5SDimitry Andric       OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
221*0b57cec5SDimitry Andric     else
222*0b57cec5SDimitry Andric       OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
223*0b57cec5SDimitry Andric     break;
224*0b57cec5SDimitry Andric   }
225*0b57cec5SDimitry Andric }
226*0b57cec5SDimitry Andric 
227*0b57cec5SDimitry Andric void CodeGenModule::createCUDARuntime() {
228*0b57cec5SDimitry Andric   CUDARuntime.reset(CreateNVCUDARuntime(*this));
229*0b57cec5SDimitry Andric }
230*0b57cec5SDimitry Andric 
231*0b57cec5SDimitry Andric void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
232*0b57cec5SDimitry Andric   Replacements[Name] = C;
233*0b57cec5SDimitry Andric }
234*0b57cec5SDimitry Andric 
235*0b57cec5SDimitry Andric void CodeGenModule::applyReplacements() {
236*0b57cec5SDimitry Andric   for (auto &I : Replacements) {
237*0b57cec5SDimitry Andric     StringRef MangledName = I.first();
238*0b57cec5SDimitry Andric     llvm::Constant *Replacement = I.second;
239*0b57cec5SDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
240*0b57cec5SDimitry Andric     if (!Entry)
241*0b57cec5SDimitry Andric       continue;
242*0b57cec5SDimitry Andric     auto *OldF = cast<llvm::Function>(Entry);
243*0b57cec5SDimitry Andric     auto *NewF = dyn_cast<llvm::Function>(Replacement);
244*0b57cec5SDimitry Andric     if (!NewF) {
245*0b57cec5SDimitry Andric       if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
246*0b57cec5SDimitry Andric         NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
247*0b57cec5SDimitry Andric       } else {
248*0b57cec5SDimitry Andric         auto *CE = cast<llvm::ConstantExpr>(Replacement);
249*0b57cec5SDimitry Andric         assert(CE->getOpcode() == llvm::Instruction::BitCast ||
250*0b57cec5SDimitry Andric                CE->getOpcode() == llvm::Instruction::GetElementPtr);
251*0b57cec5SDimitry Andric         NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
252*0b57cec5SDimitry Andric       }
253*0b57cec5SDimitry Andric     }
254*0b57cec5SDimitry Andric 
255*0b57cec5SDimitry Andric     // Replace old with new, but keep the old order.
256*0b57cec5SDimitry Andric     OldF->replaceAllUsesWith(Replacement);
257*0b57cec5SDimitry Andric     if (NewF) {
258*0b57cec5SDimitry Andric       NewF->removeFromParent();
259*0b57cec5SDimitry Andric       OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
260*0b57cec5SDimitry Andric                                                        NewF);
261*0b57cec5SDimitry Andric     }
262*0b57cec5SDimitry Andric     OldF->eraseFromParent();
263*0b57cec5SDimitry Andric   }
264*0b57cec5SDimitry Andric }
265*0b57cec5SDimitry Andric 
266*0b57cec5SDimitry Andric void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
267*0b57cec5SDimitry Andric   GlobalValReplacements.push_back(std::make_pair(GV, C));
268*0b57cec5SDimitry Andric }
269*0b57cec5SDimitry Andric 
270*0b57cec5SDimitry Andric void CodeGenModule::applyGlobalValReplacements() {
271*0b57cec5SDimitry Andric   for (auto &I : GlobalValReplacements) {
272*0b57cec5SDimitry Andric     llvm::GlobalValue *GV = I.first;
273*0b57cec5SDimitry Andric     llvm::Constant *C = I.second;
274*0b57cec5SDimitry Andric 
275*0b57cec5SDimitry Andric     GV->replaceAllUsesWith(C);
276*0b57cec5SDimitry Andric     GV->eraseFromParent();
277*0b57cec5SDimitry Andric   }
278*0b57cec5SDimitry Andric }
279*0b57cec5SDimitry Andric 
280*0b57cec5SDimitry Andric // This is only used in aliases that we created and we know they have a
281*0b57cec5SDimitry Andric // linear structure.
282*0b57cec5SDimitry Andric static const llvm::GlobalObject *getAliasedGlobal(
283*0b57cec5SDimitry Andric     const llvm::GlobalIndirectSymbol &GIS) {
284*0b57cec5SDimitry Andric   llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
285*0b57cec5SDimitry Andric   const llvm::Constant *C = &GIS;
286*0b57cec5SDimitry Andric   for (;;) {
287*0b57cec5SDimitry Andric     C = C->stripPointerCasts();
288*0b57cec5SDimitry Andric     if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
289*0b57cec5SDimitry Andric       return GO;
290*0b57cec5SDimitry Andric     // stripPointerCasts will not walk over weak aliases.
291*0b57cec5SDimitry Andric     auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
292*0b57cec5SDimitry Andric     if (!GIS2)
293*0b57cec5SDimitry Andric       return nullptr;
294*0b57cec5SDimitry Andric     if (!Visited.insert(GIS2).second)
295*0b57cec5SDimitry Andric       return nullptr;
296*0b57cec5SDimitry Andric     C = GIS2->getIndirectSymbol();
297*0b57cec5SDimitry Andric   }
298*0b57cec5SDimitry Andric }
299*0b57cec5SDimitry Andric 
300*0b57cec5SDimitry Andric void CodeGenModule::checkAliases() {
301*0b57cec5SDimitry Andric   // Check if the constructed aliases are well formed. It is really unfortunate
302*0b57cec5SDimitry Andric   // that we have to do this in CodeGen, but we only construct mangled names
303*0b57cec5SDimitry Andric   // and aliases during codegen.
304*0b57cec5SDimitry Andric   bool Error = false;
305*0b57cec5SDimitry Andric   DiagnosticsEngine &Diags = getDiags();
306*0b57cec5SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
307*0b57cec5SDimitry Andric     const auto *D = cast<ValueDecl>(GD.getDecl());
308*0b57cec5SDimitry Andric     SourceLocation Location;
309*0b57cec5SDimitry Andric     bool IsIFunc = D->hasAttr<IFuncAttr>();
310*0b57cec5SDimitry Andric     if (const Attr *A = D->getDefiningAttr())
311*0b57cec5SDimitry Andric       Location = A->getLocation();
312*0b57cec5SDimitry Andric     else
313*0b57cec5SDimitry Andric       llvm_unreachable("Not an alias or ifunc?");
314*0b57cec5SDimitry Andric     StringRef MangledName = getMangledName(GD);
315*0b57cec5SDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
316*0b57cec5SDimitry Andric     auto *Alias  = cast<llvm::GlobalIndirectSymbol>(Entry);
317*0b57cec5SDimitry Andric     const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
318*0b57cec5SDimitry Andric     if (!GV) {
319*0b57cec5SDimitry Andric       Error = true;
320*0b57cec5SDimitry Andric       Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
321*0b57cec5SDimitry Andric     } else if (GV->isDeclaration()) {
322*0b57cec5SDimitry Andric       Error = true;
323*0b57cec5SDimitry Andric       Diags.Report(Location, diag::err_alias_to_undefined)
324*0b57cec5SDimitry Andric           << IsIFunc << IsIFunc;
325*0b57cec5SDimitry Andric     } else if (IsIFunc) {
326*0b57cec5SDimitry Andric       // Check resolver function type.
327*0b57cec5SDimitry Andric       llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
328*0b57cec5SDimitry Andric           GV->getType()->getPointerElementType());
329*0b57cec5SDimitry Andric       assert(FTy);
330*0b57cec5SDimitry Andric       if (!FTy->getReturnType()->isPointerTy())
331*0b57cec5SDimitry Andric         Diags.Report(Location, diag::err_ifunc_resolver_return);
332*0b57cec5SDimitry Andric     }
333*0b57cec5SDimitry Andric 
334*0b57cec5SDimitry Andric     llvm::Constant *Aliasee = Alias->getIndirectSymbol();
335*0b57cec5SDimitry Andric     llvm::GlobalValue *AliaseeGV;
336*0b57cec5SDimitry Andric     if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
337*0b57cec5SDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
338*0b57cec5SDimitry Andric     else
339*0b57cec5SDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
340*0b57cec5SDimitry Andric 
341*0b57cec5SDimitry Andric     if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
342*0b57cec5SDimitry Andric       StringRef AliasSection = SA->getName();
343*0b57cec5SDimitry Andric       if (AliasSection != AliaseeGV->getSection())
344*0b57cec5SDimitry Andric         Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
345*0b57cec5SDimitry Andric             << AliasSection << IsIFunc << IsIFunc;
346*0b57cec5SDimitry Andric     }
347*0b57cec5SDimitry Andric 
348*0b57cec5SDimitry Andric     // We have to handle alias to weak aliases in here. LLVM itself disallows
349*0b57cec5SDimitry Andric     // this since the object semantics would not match the IL one. For
350*0b57cec5SDimitry Andric     // compatibility with gcc we implement it by just pointing the alias
351*0b57cec5SDimitry Andric     // to its aliasee's aliasee. We also warn, since the user is probably
352*0b57cec5SDimitry Andric     // expecting the link to be weak.
353*0b57cec5SDimitry Andric     if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
354*0b57cec5SDimitry Andric       if (GA->isInterposable()) {
355*0b57cec5SDimitry Andric         Diags.Report(Location, diag::warn_alias_to_weak_alias)
356*0b57cec5SDimitry Andric             << GV->getName() << GA->getName() << IsIFunc;
357*0b57cec5SDimitry Andric         Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
358*0b57cec5SDimitry Andric             GA->getIndirectSymbol(), Alias->getType());
359*0b57cec5SDimitry Andric         Alias->setIndirectSymbol(Aliasee);
360*0b57cec5SDimitry Andric       }
361*0b57cec5SDimitry Andric     }
362*0b57cec5SDimitry Andric   }
363*0b57cec5SDimitry Andric   if (!Error)
364*0b57cec5SDimitry Andric     return;
365*0b57cec5SDimitry Andric 
366*0b57cec5SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
367*0b57cec5SDimitry Andric     StringRef MangledName = getMangledName(GD);
368*0b57cec5SDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
369*0b57cec5SDimitry Andric     auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
370*0b57cec5SDimitry Andric     Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
371*0b57cec5SDimitry Andric     Alias->eraseFromParent();
372*0b57cec5SDimitry Andric   }
373*0b57cec5SDimitry Andric }
374*0b57cec5SDimitry Andric 
375*0b57cec5SDimitry Andric void CodeGenModule::clear() {
376*0b57cec5SDimitry Andric   DeferredDeclsToEmit.clear();
377*0b57cec5SDimitry Andric   if (OpenMPRuntime)
378*0b57cec5SDimitry Andric     OpenMPRuntime->clear();
379*0b57cec5SDimitry Andric }
380*0b57cec5SDimitry Andric 
381*0b57cec5SDimitry Andric void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
382*0b57cec5SDimitry Andric                                        StringRef MainFile) {
383*0b57cec5SDimitry Andric   if (!hasDiagnostics())
384*0b57cec5SDimitry Andric     return;
385*0b57cec5SDimitry Andric   if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
386*0b57cec5SDimitry Andric     if (MainFile.empty())
387*0b57cec5SDimitry Andric       MainFile = "<stdin>";
388*0b57cec5SDimitry Andric     Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
389*0b57cec5SDimitry Andric   } else {
390*0b57cec5SDimitry Andric     if (Mismatched > 0)
391*0b57cec5SDimitry Andric       Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
392*0b57cec5SDimitry Andric 
393*0b57cec5SDimitry Andric     if (Missing > 0)
394*0b57cec5SDimitry Andric       Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
395*0b57cec5SDimitry Andric   }
396*0b57cec5SDimitry Andric }
397*0b57cec5SDimitry Andric 
398*0b57cec5SDimitry Andric void CodeGenModule::Release() {
399*0b57cec5SDimitry Andric   EmitDeferred();
400*0b57cec5SDimitry Andric   EmitVTablesOpportunistically();
401*0b57cec5SDimitry Andric   applyGlobalValReplacements();
402*0b57cec5SDimitry Andric   applyReplacements();
403*0b57cec5SDimitry Andric   checkAliases();
404*0b57cec5SDimitry Andric   emitMultiVersionFunctions();
405*0b57cec5SDimitry Andric   EmitCXXGlobalInitFunc();
4065ffd83dbSDimitry Andric   EmitCXXGlobalCleanUpFunc();
407*0b57cec5SDimitry Andric   registerGlobalDtorsWithAtExit();
408*0b57cec5SDimitry Andric   EmitCXXThreadLocalInitFunc();
409*0b57cec5SDimitry Andric   if (ObjCRuntime)
410*0b57cec5SDimitry Andric     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
411*0b57cec5SDimitry Andric       AddGlobalCtor(ObjCInitFunction);
412*0b57cec5SDimitry Andric   if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
413*0b57cec5SDimitry Andric       CUDARuntime) {
414*0b57cec5SDimitry Andric     if (llvm::Function *CudaCtorFunction =
415*0b57cec5SDimitry Andric             CUDARuntime->makeModuleCtorFunction())
416*0b57cec5SDimitry Andric       AddGlobalCtor(CudaCtorFunction);
417*0b57cec5SDimitry Andric   }
418*0b57cec5SDimitry Andric   if (OpenMPRuntime) {
419*0b57cec5SDimitry Andric     if (llvm::Function *OpenMPRequiresDirectiveRegFun =
420*0b57cec5SDimitry Andric             OpenMPRuntime->emitRequiresDirectiveRegFun()) {
421*0b57cec5SDimitry Andric       AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0);
422*0b57cec5SDimitry Andric     }
423a7dea167SDimitry Andric     OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
424*0b57cec5SDimitry Andric     OpenMPRuntime->clear();
425*0b57cec5SDimitry Andric   }
426*0b57cec5SDimitry Andric   if (PGOReader) {
427*0b57cec5SDimitry Andric     getModule().setProfileSummary(
428*0b57cec5SDimitry Andric         PGOReader->getSummary(/* UseCS */ false).getMD(VMContext),
429*0b57cec5SDimitry Andric         llvm::ProfileSummary::PSK_Instr);
430*0b57cec5SDimitry Andric     if (PGOStats.hasDiagnostics())
431*0b57cec5SDimitry Andric       PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
432*0b57cec5SDimitry Andric   }
433*0b57cec5SDimitry Andric   EmitCtorList(GlobalCtors, "llvm.global_ctors");
434*0b57cec5SDimitry Andric   EmitCtorList(GlobalDtors, "llvm.global_dtors");
435*0b57cec5SDimitry Andric   EmitGlobalAnnotations();
436*0b57cec5SDimitry Andric   EmitStaticExternCAliases();
437*0b57cec5SDimitry Andric   EmitDeferredUnusedCoverageMappings();
438*0b57cec5SDimitry Andric   if (CoverageMapping)
439*0b57cec5SDimitry Andric     CoverageMapping->emit();
440*0b57cec5SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
441*0b57cec5SDimitry Andric     CodeGenFunction(*this).EmitCfiCheckFail();
442*0b57cec5SDimitry Andric     CodeGenFunction(*this).EmitCfiCheckStub();
443*0b57cec5SDimitry Andric   }
444*0b57cec5SDimitry Andric   emitAtAvailableLinkGuard();
4455ffd83dbSDimitry Andric   if (Context.getTargetInfo().getTriple().isWasm() &&
4465ffd83dbSDimitry Andric       !Context.getTargetInfo().getTriple().isOSEmscripten()) {
4475ffd83dbSDimitry Andric     EmitMainVoidAlias();
4485ffd83dbSDimitry Andric   }
449*0b57cec5SDimitry Andric   emitLLVMUsed();
450*0b57cec5SDimitry Andric   if (SanStats)
451*0b57cec5SDimitry Andric     SanStats->finish();
452*0b57cec5SDimitry Andric 
453*0b57cec5SDimitry Andric   if (CodeGenOpts.Autolink &&
454*0b57cec5SDimitry Andric       (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
455*0b57cec5SDimitry Andric     EmitModuleLinkOptions();
456*0b57cec5SDimitry Andric   }
457*0b57cec5SDimitry Andric 
458*0b57cec5SDimitry Andric   // On ELF we pass the dependent library specifiers directly to the linker
459*0b57cec5SDimitry Andric   // without manipulating them. This is in contrast to other platforms where
460*0b57cec5SDimitry Andric   // they are mapped to a specific linker option by the compiler. This
461*0b57cec5SDimitry Andric   // difference is a result of the greater variety of ELF linkers and the fact
462*0b57cec5SDimitry Andric   // that ELF linkers tend to handle libraries in a more complicated fashion
463*0b57cec5SDimitry Andric   // than on other platforms. This forces us to defer handling the dependent
464*0b57cec5SDimitry Andric   // libs to the linker.
465*0b57cec5SDimitry Andric   //
466*0b57cec5SDimitry Andric   // CUDA/HIP device and host libraries are different. Currently there is no
467*0b57cec5SDimitry Andric   // way to differentiate dependent libraries for host or device. Existing
468*0b57cec5SDimitry Andric   // usage of #pragma comment(lib, *) is intended for host libraries on
469*0b57cec5SDimitry Andric   // Windows. Therefore emit llvm.dependent-libraries only for host.
470*0b57cec5SDimitry Andric   if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
471*0b57cec5SDimitry Andric     auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries");
472*0b57cec5SDimitry Andric     for (auto *MD : ELFDependentLibraries)
473*0b57cec5SDimitry Andric       NMD->addOperand(MD);
474*0b57cec5SDimitry Andric   }
475*0b57cec5SDimitry Andric 
476*0b57cec5SDimitry Andric   // Record mregparm value now so it is visible through rest of codegen.
477*0b57cec5SDimitry Andric   if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
478*0b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
479*0b57cec5SDimitry Andric                               CodeGenOpts.NumRegisterParameters);
480*0b57cec5SDimitry Andric 
481*0b57cec5SDimitry Andric   if (CodeGenOpts.DwarfVersion) {
482480093f4SDimitry Andric     getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version",
483*0b57cec5SDimitry Andric                               CodeGenOpts.DwarfVersion);
484*0b57cec5SDimitry Andric   }
4855ffd83dbSDimitry Andric 
4865ffd83dbSDimitry Andric   if (Context.getLangOpts().SemanticInterposition)
4875ffd83dbSDimitry Andric     // Require various optimization to respect semantic interposition.
4885ffd83dbSDimitry Andric     getModule().setSemanticInterposition(1);
4895ffd83dbSDimitry Andric   else if (Context.getLangOpts().ExplicitNoSemanticInterposition)
4905ffd83dbSDimitry Andric     // Allow dso_local on applicable targets.
4915ffd83dbSDimitry Andric     getModule().setSemanticInterposition(0);
4925ffd83dbSDimitry Andric 
493*0b57cec5SDimitry Andric   if (CodeGenOpts.EmitCodeView) {
494*0b57cec5SDimitry Andric     // Indicate that we want CodeView in the metadata.
495*0b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
496*0b57cec5SDimitry Andric   }
497*0b57cec5SDimitry Andric   if (CodeGenOpts.CodeViewGHash) {
498*0b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
499*0b57cec5SDimitry Andric   }
500*0b57cec5SDimitry Andric   if (CodeGenOpts.ControlFlowGuard) {
501480093f4SDimitry Andric     // Function ID tables and checks for Control Flow Guard (cfguard=2).
502480093f4SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2);
503480093f4SDimitry Andric   } else if (CodeGenOpts.ControlFlowGuardNoChecks) {
504480093f4SDimitry Andric     // Function ID tables for Control Flow Guard (cfguard=1).
505480093f4SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
506*0b57cec5SDimitry Andric   }
507*0b57cec5SDimitry Andric   if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
508*0b57cec5SDimitry Andric     // We don't support LTO with 2 with different StrictVTablePointers
509*0b57cec5SDimitry Andric     // FIXME: we could support it by stripping all the information introduced
510*0b57cec5SDimitry Andric     // by StrictVTablePointers.
511*0b57cec5SDimitry Andric 
512*0b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
513*0b57cec5SDimitry Andric 
514*0b57cec5SDimitry Andric     llvm::Metadata *Ops[2] = {
515*0b57cec5SDimitry Andric               llvm::MDString::get(VMContext, "StrictVTablePointers"),
516*0b57cec5SDimitry Andric               llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
517*0b57cec5SDimitry Andric                   llvm::Type::getInt32Ty(VMContext), 1))};
518*0b57cec5SDimitry Andric 
519*0b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Require,
520*0b57cec5SDimitry Andric                               "StrictVTablePointersRequirement",
521*0b57cec5SDimitry Andric                               llvm::MDNode::get(VMContext, Ops));
522*0b57cec5SDimitry Andric   }
5235ffd83dbSDimitry Andric   if (getModuleDebugInfo())
524*0b57cec5SDimitry Andric     // We support a single version in the linked module. The LLVM
525*0b57cec5SDimitry Andric     // parser will drop debug info with a different version number
526*0b57cec5SDimitry Andric     // (and warn about it, too).
527*0b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
528*0b57cec5SDimitry Andric                               llvm::DEBUG_METADATA_VERSION);
529*0b57cec5SDimitry Andric 
530*0b57cec5SDimitry Andric   // We need to record the widths of enums and wchar_t, so that we can generate
531*0b57cec5SDimitry Andric   // the correct build attributes in the ARM backend. wchar_size is also used by
532*0b57cec5SDimitry Andric   // TargetLibraryInfo.
533*0b57cec5SDimitry Andric   uint64_t WCharWidth =
534*0b57cec5SDimitry Andric       Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
535*0b57cec5SDimitry Andric   getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
536*0b57cec5SDimitry Andric 
537*0b57cec5SDimitry Andric   llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
538*0b57cec5SDimitry Andric   if (   Arch == llvm::Triple::arm
539*0b57cec5SDimitry Andric       || Arch == llvm::Triple::armeb
540*0b57cec5SDimitry Andric       || Arch == llvm::Triple::thumb
541*0b57cec5SDimitry Andric       || Arch == llvm::Triple::thumbeb) {
542*0b57cec5SDimitry Andric     // The minimum width of an enum in bytes
543*0b57cec5SDimitry Andric     uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
544*0b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
545*0b57cec5SDimitry Andric   }
546*0b57cec5SDimitry Andric 
54713138422SDimitry Andric   if (Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64) {
54813138422SDimitry Andric     StringRef ABIStr = Target.getABI();
54913138422SDimitry Andric     llvm::LLVMContext &Ctx = TheModule.getContext();
55013138422SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "target-abi",
55113138422SDimitry Andric                               llvm::MDString::get(Ctx, ABIStr));
55213138422SDimitry Andric   }
55313138422SDimitry Andric 
554*0b57cec5SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
555*0b57cec5SDimitry Andric     // Indicate that we want cross-DSO control flow integrity checks.
556*0b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
557*0b57cec5SDimitry Andric   }
558*0b57cec5SDimitry Andric 
5595ffd83dbSDimitry Andric   if (CodeGenOpts.WholeProgramVTables) {
5605ffd83dbSDimitry Andric     // Indicate whether VFE was enabled for this module, so that the
5615ffd83dbSDimitry Andric     // vcall_visibility metadata added under whole program vtables is handled
5625ffd83dbSDimitry Andric     // appropriately in the optimizer.
5635ffd83dbSDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "Virtual Function Elim",
5645ffd83dbSDimitry Andric                               CodeGenOpts.VirtualFunctionElimination);
5655ffd83dbSDimitry Andric   }
5665ffd83dbSDimitry Andric 
567a7dea167SDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
568a7dea167SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override,
569a7dea167SDimitry Andric                               "CFI Canonical Jump Tables",
570a7dea167SDimitry Andric                               CodeGenOpts.SanitizeCfiCanonicalJumpTables);
571a7dea167SDimitry Andric   }
572a7dea167SDimitry Andric 
573*0b57cec5SDimitry Andric   if (CodeGenOpts.CFProtectionReturn &&
574*0b57cec5SDimitry Andric       Target.checkCFProtectionReturnSupported(getDiags())) {
575*0b57cec5SDimitry Andric     // Indicate that we want to instrument return control flow protection.
576*0b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
577*0b57cec5SDimitry Andric                               1);
578*0b57cec5SDimitry Andric   }
579*0b57cec5SDimitry Andric 
580*0b57cec5SDimitry Andric   if (CodeGenOpts.CFProtectionBranch &&
581*0b57cec5SDimitry Andric       Target.checkCFProtectionBranchSupported(getDiags())) {
582*0b57cec5SDimitry Andric     // Indicate that we want to instrument branch control flow protection.
583*0b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
584*0b57cec5SDimitry Andric                               1);
585*0b57cec5SDimitry Andric   }
586*0b57cec5SDimitry Andric 
587*0b57cec5SDimitry Andric   if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
588*0b57cec5SDimitry Andric     // Indicate whether __nvvm_reflect should be configured to flush denormal
589*0b57cec5SDimitry Andric     // floating point values to 0.  (This corresponds to its "__CUDA_FTZ"
590*0b57cec5SDimitry Andric     // property.)
591*0b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
5925ffd83dbSDimitry Andric                               CodeGenOpts.FP32DenormalMode.Output !=
5935ffd83dbSDimitry Andric                                   llvm::DenormalMode::IEEE);
594*0b57cec5SDimitry Andric   }
595*0b57cec5SDimitry Andric 
596*0b57cec5SDimitry Andric   // Emit OpenCL specific module metadata: OpenCL/SPIR version.
597*0b57cec5SDimitry Andric   if (LangOpts.OpenCL) {
598*0b57cec5SDimitry Andric     EmitOpenCLMetadata();
599*0b57cec5SDimitry Andric     // Emit SPIR version.
600*0b57cec5SDimitry Andric     if (getTriple().isSPIR()) {
601*0b57cec5SDimitry Andric       // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
602*0b57cec5SDimitry Andric       // opencl.spir.version named metadata.
603*0b57cec5SDimitry Andric       // C++ is backwards compatible with OpenCL v2.0.
604*0b57cec5SDimitry Andric       auto Version = LangOpts.OpenCLCPlusPlus ? 200 : LangOpts.OpenCLVersion;
605*0b57cec5SDimitry Andric       llvm::Metadata *SPIRVerElts[] = {
606*0b57cec5SDimitry Andric           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
607*0b57cec5SDimitry Andric               Int32Ty, Version / 100)),
608*0b57cec5SDimitry Andric           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
609*0b57cec5SDimitry Andric               Int32Ty, (Version / 100 > 1) ? 0 : 2))};
610*0b57cec5SDimitry Andric       llvm::NamedMDNode *SPIRVerMD =
611*0b57cec5SDimitry Andric           TheModule.getOrInsertNamedMetadata("opencl.spir.version");
612*0b57cec5SDimitry Andric       llvm::LLVMContext &Ctx = TheModule.getContext();
613*0b57cec5SDimitry Andric       SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
614*0b57cec5SDimitry Andric     }
615*0b57cec5SDimitry Andric   }
616*0b57cec5SDimitry Andric 
617*0b57cec5SDimitry Andric   if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
618*0b57cec5SDimitry Andric     assert(PLevel < 3 && "Invalid PIC Level");
619*0b57cec5SDimitry Andric     getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
620*0b57cec5SDimitry Andric     if (Context.getLangOpts().PIE)
621*0b57cec5SDimitry Andric       getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
622*0b57cec5SDimitry Andric   }
623*0b57cec5SDimitry Andric 
624*0b57cec5SDimitry Andric   if (getCodeGenOpts().CodeModel.size() > 0) {
625*0b57cec5SDimitry Andric     unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
626*0b57cec5SDimitry Andric                   .Case("tiny", llvm::CodeModel::Tiny)
627*0b57cec5SDimitry Andric                   .Case("small", llvm::CodeModel::Small)
628*0b57cec5SDimitry Andric                   .Case("kernel", llvm::CodeModel::Kernel)
629*0b57cec5SDimitry Andric                   .Case("medium", llvm::CodeModel::Medium)
630*0b57cec5SDimitry Andric                   .Case("large", llvm::CodeModel::Large)
631*0b57cec5SDimitry Andric                   .Default(~0u);
632*0b57cec5SDimitry Andric     if (CM != ~0u) {
633*0b57cec5SDimitry Andric       llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
634*0b57cec5SDimitry Andric       getModule().setCodeModel(codeModel);
635*0b57cec5SDimitry Andric     }
636*0b57cec5SDimitry Andric   }
637*0b57cec5SDimitry Andric 
638*0b57cec5SDimitry Andric   if (CodeGenOpts.NoPLT)
639*0b57cec5SDimitry Andric     getModule().setRtLibUseGOT();
640*0b57cec5SDimitry Andric 
641*0b57cec5SDimitry Andric   SimplifyPersonality();
642*0b57cec5SDimitry Andric 
643*0b57cec5SDimitry Andric   if (getCodeGenOpts().EmitDeclMetadata)
644*0b57cec5SDimitry Andric     EmitDeclMetadata();
645*0b57cec5SDimitry Andric 
646*0b57cec5SDimitry Andric   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
647*0b57cec5SDimitry Andric     EmitCoverageFile();
648*0b57cec5SDimitry Andric 
6495ffd83dbSDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
6505ffd83dbSDimitry Andric     DI->finalize();
651*0b57cec5SDimitry Andric 
652*0b57cec5SDimitry Andric   if (getCodeGenOpts().EmitVersionIdentMetadata)
653*0b57cec5SDimitry Andric     EmitVersionIdentMetadata();
654*0b57cec5SDimitry Andric 
655*0b57cec5SDimitry Andric   if (!getCodeGenOpts().RecordCommandLine.empty())
656*0b57cec5SDimitry Andric     EmitCommandLineMetadata();
657*0b57cec5SDimitry Andric 
6585ffd83dbSDimitry Andric   getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames);
6595ffd83dbSDimitry Andric 
6605ffd83dbSDimitry Andric   EmitBackendOptionsMetadata(getCodeGenOpts());
661*0b57cec5SDimitry Andric }
662*0b57cec5SDimitry Andric 
663*0b57cec5SDimitry Andric void CodeGenModule::EmitOpenCLMetadata() {
664*0b57cec5SDimitry Andric   // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
665*0b57cec5SDimitry Andric   // opencl.ocl.version named metadata node.
666*0b57cec5SDimitry Andric   // C++ is backwards compatible with OpenCL v2.0.
667*0b57cec5SDimitry Andric   // FIXME: We might need to add CXX version at some point too?
668*0b57cec5SDimitry Andric   auto Version = LangOpts.OpenCLCPlusPlus ? 200 : LangOpts.OpenCLVersion;
669*0b57cec5SDimitry Andric   llvm::Metadata *OCLVerElts[] = {
670*0b57cec5SDimitry Andric       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
671*0b57cec5SDimitry Andric           Int32Ty, Version / 100)),
672*0b57cec5SDimitry Andric       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
673*0b57cec5SDimitry Andric           Int32Ty, (Version % 100) / 10))};
674*0b57cec5SDimitry Andric   llvm::NamedMDNode *OCLVerMD =
675*0b57cec5SDimitry Andric       TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
676*0b57cec5SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
677*0b57cec5SDimitry Andric   OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
678*0b57cec5SDimitry Andric }
679*0b57cec5SDimitry Andric 
6805ffd83dbSDimitry Andric void CodeGenModule::EmitBackendOptionsMetadata(
6815ffd83dbSDimitry Andric     const CodeGenOptions CodeGenOpts) {
6825ffd83dbSDimitry Andric   switch (getTriple().getArch()) {
6835ffd83dbSDimitry Andric   default:
6845ffd83dbSDimitry Andric     break;
6855ffd83dbSDimitry Andric   case llvm::Triple::riscv32:
6865ffd83dbSDimitry Andric   case llvm::Triple::riscv64:
6875ffd83dbSDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "SmallDataLimit",
6885ffd83dbSDimitry Andric                               CodeGenOpts.SmallDataLimit);
6895ffd83dbSDimitry Andric     break;
6905ffd83dbSDimitry Andric   }
6915ffd83dbSDimitry Andric }
6925ffd83dbSDimitry Andric 
693*0b57cec5SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
694*0b57cec5SDimitry Andric   // Make sure that this type is translated.
695*0b57cec5SDimitry Andric   Types.UpdateCompletedType(TD);
696*0b57cec5SDimitry Andric }
697*0b57cec5SDimitry Andric 
698*0b57cec5SDimitry Andric void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
699*0b57cec5SDimitry Andric   // Make sure that this type is translated.
700*0b57cec5SDimitry Andric   Types.RefreshTypeCacheForClass(RD);
701*0b57cec5SDimitry Andric }
702*0b57cec5SDimitry Andric 
703*0b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
704*0b57cec5SDimitry Andric   if (!TBAA)
705*0b57cec5SDimitry Andric     return nullptr;
706*0b57cec5SDimitry Andric   return TBAA->getTypeInfo(QTy);
707*0b57cec5SDimitry Andric }
708*0b57cec5SDimitry Andric 
709*0b57cec5SDimitry Andric TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
710*0b57cec5SDimitry Andric   if (!TBAA)
711*0b57cec5SDimitry Andric     return TBAAAccessInfo();
7125ffd83dbSDimitry Andric   if (getLangOpts().CUDAIsDevice) {
7135ffd83dbSDimitry Andric     // As CUDA builtin surface/texture types are replaced, skip generating TBAA
7145ffd83dbSDimitry Andric     // access info.
7155ffd83dbSDimitry Andric     if (AccessType->isCUDADeviceBuiltinSurfaceType()) {
7165ffd83dbSDimitry Andric       if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() !=
7175ffd83dbSDimitry Andric           nullptr)
7185ffd83dbSDimitry Andric         return TBAAAccessInfo();
7195ffd83dbSDimitry Andric     } else if (AccessType->isCUDADeviceBuiltinTextureType()) {
7205ffd83dbSDimitry Andric       if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() !=
7215ffd83dbSDimitry Andric           nullptr)
7225ffd83dbSDimitry Andric         return TBAAAccessInfo();
7235ffd83dbSDimitry Andric     }
7245ffd83dbSDimitry Andric   }
725*0b57cec5SDimitry Andric   return TBAA->getAccessInfo(AccessType);
726*0b57cec5SDimitry Andric }
727*0b57cec5SDimitry Andric 
728*0b57cec5SDimitry Andric TBAAAccessInfo
729*0b57cec5SDimitry Andric CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
730*0b57cec5SDimitry Andric   if (!TBAA)
731*0b57cec5SDimitry Andric     return TBAAAccessInfo();
732*0b57cec5SDimitry Andric   return TBAA->getVTablePtrAccessInfo(VTablePtrType);
733*0b57cec5SDimitry Andric }
734*0b57cec5SDimitry Andric 
735*0b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
736*0b57cec5SDimitry Andric   if (!TBAA)
737*0b57cec5SDimitry Andric     return nullptr;
738*0b57cec5SDimitry Andric   return TBAA->getTBAAStructInfo(QTy);
739*0b57cec5SDimitry Andric }
740*0b57cec5SDimitry Andric 
741*0b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
742*0b57cec5SDimitry Andric   if (!TBAA)
743*0b57cec5SDimitry Andric     return nullptr;
744*0b57cec5SDimitry Andric   return TBAA->getBaseTypeInfo(QTy);
745*0b57cec5SDimitry Andric }
746*0b57cec5SDimitry Andric 
747*0b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
748*0b57cec5SDimitry Andric   if (!TBAA)
749*0b57cec5SDimitry Andric     return nullptr;
750*0b57cec5SDimitry Andric   return TBAA->getAccessTagInfo(Info);
751*0b57cec5SDimitry Andric }
752*0b57cec5SDimitry Andric 
753*0b57cec5SDimitry Andric TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
754*0b57cec5SDimitry Andric                                                    TBAAAccessInfo TargetInfo) {
755*0b57cec5SDimitry Andric   if (!TBAA)
756*0b57cec5SDimitry Andric     return TBAAAccessInfo();
757*0b57cec5SDimitry Andric   return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
758*0b57cec5SDimitry Andric }
759*0b57cec5SDimitry Andric 
760*0b57cec5SDimitry Andric TBAAAccessInfo
761*0b57cec5SDimitry Andric CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
762*0b57cec5SDimitry Andric                                                    TBAAAccessInfo InfoB) {
763*0b57cec5SDimitry Andric   if (!TBAA)
764*0b57cec5SDimitry Andric     return TBAAAccessInfo();
765*0b57cec5SDimitry Andric   return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
766*0b57cec5SDimitry Andric }
767*0b57cec5SDimitry Andric 
768*0b57cec5SDimitry Andric TBAAAccessInfo
769*0b57cec5SDimitry Andric CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
770*0b57cec5SDimitry Andric                                               TBAAAccessInfo SrcInfo) {
771*0b57cec5SDimitry Andric   if (!TBAA)
772*0b57cec5SDimitry Andric     return TBAAAccessInfo();
773*0b57cec5SDimitry Andric   return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
774*0b57cec5SDimitry Andric }
775*0b57cec5SDimitry Andric 
776*0b57cec5SDimitry Andric void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
777*0b57cec5SDimitry Andric                                                 TBAAAccessInfo TBAAInfo) {
778*0b57cec5SDimitry Andric   if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
779*0b57cec5SDimitry Andric     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
780*0b57cec5SDimitry Andric }
781*0b57cec5SDimitry Andric 
782*0b57cec5SDimitry Andric void CodeGenModule::DecorateInstructionWithInvariantGroup(
783*0b57cec5SDimitry Andric     llvm::Instruction *I, const CXXRecordDecl *RD) {
784*0b57cec5SDimitry Andric   I->setMetadata(llvm::LLVMContext::MD_invariant_group,
785*0b57cec5SDimitry Andric                  llvm::MDNode::get(getLLVMContext(), {}));
786*0b57cec5SDimitry Andric }
787*0b57cec5SDimitry Andric 
788*0b57cec5SDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) {
789*0b57cec5SDimitry Andric   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
790*0b57cec5SDimitry Andric   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
791*0b57cec5SDimitry Andric }
792*0b57cec5SDimitry Andric 
793*0b57cec5SDimitry Andric /// ErrorUnsupported - Print out an error that codegen doesn't support the
794*0b57cec5SDimitry Andric /// specified stmt yet.
795*0b57cec5SDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
796*0b57cec5SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
797*0b57cec5SDimitry Andric                                                "cannot compile this %0 yet");
798*0b57cec5SDimitry Andric   std::string Msg = Type;
799*0b57cec5SDimitry Andric   getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
800*0b57cec5SDimitry Andric       << Msg << S->getSourceRange();
801*0b57cec5SDimitry Andric }
802*0b57cec5SDimitry Andric 
803*0b57cec5SDimitry Andric /// ErrorUnsupported - Print out an error that codegen doesn't support the
804*0b57cec5SDimitry Andric /// specified decl yet.
805*0b57cec5SDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
806*0b57cec5SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
807*0b57cec5SDimitry Andric                                                "cannot compile this %0 yet");
808*0b57cec5SDimitry Andric   std::string Msg = Type;
809*0b57cec5SDimitry Andric   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
810*0b57cec5SDimitry Andric }
811*0b57cec5SDimitry Andric 
812*0b57cec5SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
813*0b57cec5SDimitry Andric   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
814*0b57cec5SDimitry Andric }
815*0b57cec5SDimitry Andric 
816*0b57cec5SDimitry Andric void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
817*0b57cec5SDimitry Andric                                         const NamedDecl *D) const {
818*0b57cec5SDimitry Andric   if (GV->hasDLLImportStorageClass())
819*0b57cec5SDimitry Andric     return;
820*0b57cec5SDimitry Andric   // Internal definitions always have default visibility.
821*0b57cec5SDimitry Andric   if (GV->hasLocalLinkage()) {
822*0b57cec5SDimitry Andric     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
823*0b57cec5SDimitry Andric     return;
824*0b57cec5SDimitry Andric   }
825*0b57cec5SDimitry Andric   if (!D)
826*0b57cec5SDimitry Andric     return;
827*0b57cec5SDimitry Andric   // Set visibility for definitions, and for declarations if requested globally
828*0b57cec5SDimitry Andric   // or set explicitly.
829*0b57cec5SDimitry Andric   LinkageInfo LV = D->getLinkageAndVisibility();
830*0b57cec5SDimitry Andric   if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls ||
831*0b57cec5SDimitry Andric       !GV->isDeclarationForLinker())
832*0b57cec5SDimitry Andric     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
833*0b57cec5SDimitry Andric }
834*0b57cec5SDimitry Andric 
835*0b57cec5SDimitry Andric static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
836*0b57cec5SDimitry Andric                                  llvm::GlobalValue *GV) {
837*0b57cec5SDimitry Andric   if (GV->hasLocalLinkage())
838*0b57cec5SDimitry Andric     return true;
839*0b57cec5SDimitry Andric 
840*0b57cec5SDimitry Andric   if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
841*0b57cec5SDimitry Andric     return true;
842*0b57cec5SDimitry Andric 
843*0b57cec5SDimitry Andric   // DLLImport explicitly marks the GV as external.
844*0b57cec5SDimitry Andric   if (GV->hasDLLImportStorageClass())
845*0b57cec5SDimitry Andric     return false;
846*0b57cec5SDimitry Andric 
847*0b57cec5SDimitry Andric   const llvm::Triple &TT = CGM.getTriple();
848*0b57cec5SDimitry Andric   if (TT.isWindowsGNUEnvironment()) {
849*0b57cec5SDimitry Andric     // In MinGW, variables without DLLImport can still be automatically
850*0b57cec5SDimitry Andric     // imported from a DLL by the linker; don't mark variables that
851*0b57cec5SDimitry Andric     // potentially could come from another DLL as DSO local.
852*0b57cec5SDimitry Andric     if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
853*0b57cec5SDimitry Andric         !GV->isThreadLocal())
854*0b57cec5SDimitry Andric       return false;
855*0b57cec5SDimitry Andric   }
856*0b57cec5SDimitry Andric 
857*0b57cec5SDimitry Andric   // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols
858*0b57cec5SDimitry Andric   // remain unresolved in the link, they can be resolved to zero, which is
859*0b57cec5SDimitry Andric   // outside the current DSO.
860*0b57cec5SDimitry Andric   if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
861*0b57cec5SDimitry Andric     return false;
862*0b57cec5SDimitry Andric 
863*0b57cec5SDimitry Andric   // Every other GV is local on COFF.
864*0b57cec5SDimitry Andric   // Make an exception for windows OS in the triple: Some firmware builds use
865*0b57cec5SDimitry Andric   // *-win32-macho triples. This (accidentally?) produced windows relocations
866*0b57cec5SDimitry Andric   // without GOT tables in older clang versions; Keep this behaviour.
867*0b57cec5SDimitry Andric   // FIXME: even thread local variables?
868*0b57cec5SDimitry Andric   if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
869*0b57cec5SDimitry Andric     return true;
870*0b57cec5SDimitry Andric 
871*0b57cec5SDimitry Andric   // Only handle COFF and ELF for now.
872*0b57cec5SDimitry Andric   if (!TT.isOSBinFormatELF())
873*0b57cec5SDimitry Andric     return false;
874*0b57cec5SDimitry Andric 
875*0b57cec5SDimitry Andric   // If this is not an executable, don't assume anything is local.
876*0b57cec5SDimitry Andric   const auto &CGOpts = CGM.getCodeGenOpts();
877*0b57cec5SDimitry Andric   llvm::Reloc::Model RM = CGOpts.RelocationModel;
878*0b57cec5SDimitry Andric   const auto &LOpts = CGM.getLangOpts();
879480093f4SDimitry Andric   if (RM != llvm::Reloc::Static && !LOpts.PIE)
880*0b57cec5SDimitry Andric     return false;
881*0b57cec5SDimitry Andric 
882*0b57cec5SDimitry Andric   // A definition cannot be preempted from an executable.
883*0b57cec5SDimitry Andric   if (!GV->isDeclarationForLinker())
884*0b57cec5SDimitry Andric     return true;
885*0b57cec5SDimitry Andric 
886*0b57cec5SDimitry Andric   // Most PIC code sequences that assume that a symbol is local cannot produce a
887*0b57cec5SDimitry Andric   // 0 if it turns out the symbol is undefined. While this is ABI and relocation
888*0b57cec5SDimitry Andric   // depended, it seems worth it to handle it here.
889*0b57cec5SDimitry Andric   if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
890*0b57cec5SDimitry Andric     return false;
891*0b57cec5SDimitry Andric 
892*0b57cec5SDimitry Andric   // PPC has no copy relocations and cannot use a plt entry as a symbol address.
893*0b57cec5SDimitry Andric   llvm::Triple::ArchType Arch = TT.getArch();
894*0b57cec5SDimitry Andric   if (Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
895*0b57cec5SDimitry Andric       Arch == llvm::Triple::ppc64le)
896*0b57cec5SDimitry Andric     return false;
897*0b57cec5SDimitry Andric 
898*0b57cec5SDimitry Andric   // If we can use copy relocations we can assume it is local.
899*0b57cec5SDimitry Andric   if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
900*0b57cec5SDimitry Andric     if (!Var->isThreadLocal() &&
901*0b57cec5SDimitry Andric         (RM == llvm::Reloc::Static || CGOpts.PIECopyRelocations))
902*0b57cec5SDimitry Andric       return true;
903*0b57cec5SDimitry Andric 
904*0b57cec5SDimitry Andric   // If we can use a plt entry as the symbol address we can assume it
905*0b57cec5SDimitry Andric   // is local.
906*0b57cec5SDimitry Andric   // FIXME: This should work for PIE, but the gold linker doesn't support it.
907*0b57cec5SDimitry Andric   if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
908*0b57cec5SDimitry Andric     return true;
909*0b57cec5SDimitry Andric 
9105ffd83dbSDimitry Andric   // Otherwise don't assume it is local.
911*0b57cec5SDimitry Andric   return false;
912*0b57cec5SDimitry Andric }
913*0b57cec5SDimitry Andric 
914*0b57cec5SDimitry Andric void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
915*0b57cec5SDimitry Andric   GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
916*0b57cec5SDimitry Andric }
917*0b57cec5SDimitry Andric 
918*0b57cec5SDimitry Andric void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
919*0b57cec5SDimitry Andric                                           GlobalDecl GD) const {
920*0b57cec5SDimitry Andric   const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
921*0b57cec5SDimitry Andric   // C++ destructors have a few C++ ABI specific special cases.
922*0b57cec5SDimitry Andric   if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
923*0b57cec5SDimitry Andric     getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
924*0b57cec5SDimitry Andric     return;
925*0b57cec5SDimitry Andric   }
926*0b57cec5SDimitry Andric   setDLLImportDLLExport(GV, D);
927*0b57cec5SDimitry Andric }
928*0b57cec5SDimitry Andric 
929*0b57cec5SDimitry Andric void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
930*0b57cec5SDimitry Andric                                           const NamedDecl *D) const {
931*0b57cec5SDimitry Andric   if (D && D->isExternallyVisible()) {
932*0b57cec5SDimitry Andric     if (D->hasAttr<DLLImportAttr>())
933*0b57cec5SDimitry Andric       GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
934*0b57cec5SDimitry Andric     else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
935*0b57cec5SDimitry Andric       GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
936*0b57cec5SDimitry Andric   }
937*0b57cec5SDimitry Andric }
938*0b57cec5SDimitry Andric 
939*0b57cec5SDimitry Andric void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
940*0b57cec5SDimitry Andric                                     GlobalDecl GD) const {
941*0b57cec5SDimitry Andric   setDLLImportDLLExport(GV, GD);
942*0b57cec5SDimitry Andric   setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl()));
943*0b57cec5SDimitry Andric }
944*0b57cec5SDimitry Andric 
945*0b57cec5SDimitry Andric void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
946*0b57cec5SDimitry Andric                                     const NamedDecl *D) const {
947*0b57cec5SDimitry Andric   setDLLImportDLLExport(GV, D);
948*0b57cec5SDimitry Andric   setGVPropertiesAux(GV, D);
949*0b57cec5SDimitry Andric }
950*0b57cec5SDimitry Andric 
951*0b57cec5SDimitry Andric void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV,
952*0b57cec5SDimitry Andric                                        const NamedDecl *D) const {
953*0b57cec5SDimitry Andric   setGlobalVisibility(GV, D);
954*0b57cec5SDimitry Andric   setDSOLocal(GV);
955*0b57cec5SDimitry Andric   GV->setPartition(CodeGenOpts.SymbolPartition);
956*0b57cec5SDimitry Andric }
957*0b57cec5SDimitry Andric 
958*0b57cec5SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
959*0b57cec5SDimitry Andric   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
960*0b57cec5SDimitry Andric       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
961*0b57cec5SDimitry Andric       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
962*0b57cec5SDimitry Andric       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
963*0b57cec5SDimitry Andric       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
964*0b57cec5SDimitry Andric }
965*0b57cec5SDimitry Andric 
9665ffd83dbSDimitry Andric llvm::GlobalVariable::ThreadLocalMode
9675ffd83dbSDimitry Andric CodeGenModule::GetDefaultLLVMTLSModel() const {
9685ffd83dbSDimitry Andric   switch (CodeGenOpts.getDefaultTLSModel()) {
969*0b57cec5SDimitry Andric   case CodeGenOptions::GeneralDynamicTLSModel:
970*0b57cec5SDimitry Andric     return llvm::GlobalVariable::GeneralDynamicTLSModel;
971*0b57cec5SDimitry Andric   case CodeGenOptions::LocalDynamicTLSModel:
972*0b57cec5SDimitry Andric     return llvm::GlobalVariable::LocalDynamicTLSModel;
973*0b57cec5SDimitry Andric   case CodeGenOptions::InitialExecTLSModel:
974*0b57cec5SDimitry Andric     return llvm::GlobalVariable::InitialExecTLSModel;
975*0b57cec5SDimitry Andric   case CodeGenOptions::LocalExecTLSModel:
976*0b57cec5SDimitry Andric     return llvm::GlobalVariable::LocalExecTLSModel;
977*0b57cec5SDimitry Andric   }
978*0b57cec5SDimitry Andric   llvm_unreachable("Invalid TLS model!");
979*0b57cec5SDimitry Andric }
980*0b57cec5SDimitry Andric 
981*0b57cec5SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
982*0b57cec5SDimitry Andric   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
983*0b57cec5SDimitry Andric 
984*0b57cec5SDimitry Andric   llvm::GlobalValue::ThreadLocalMode TLM;
9855ffd83dbSDimitry Andric   TLM = GetDefaultLLVMTLSModel();
986*0b57cec5SDimitry Andric 
987*0b57cec5SDimitry Andric   // Override the TLS model if it is explicitly specified.
988*0b57cec5SDimitry Andric   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
989*0b57cec5SDimitry Andric     TLM = GetLLVMTLSModel(Attr->getModel());
990*0b57cec5SDimitry Andric   }
991*0b57cec5SDimitry Andric 
992*0b57cec5SDimitry Andric   GV->setThreadLocalMode(TLM);
993*0b57cec5SDimitry Andric }
994*0b57cec5SDimitry Andric 
995*0b57cec5SDimitry Andric static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
996*0b57cec5SDimitry Andric                                           StringRef Name) {
997*0b57cec5SDimitry Andric   const TargetInfo &Target = CGM.getTarget();
998*0b57cec5SDimitry Andric   return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
999*0b57cec5SDimitry Andric }
1000*0b57cec5SDimitry Andric 
1001*0b57cec5SDimitry Andric static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
1002*0b57cec5SDimitry Andric                                                  const CPUSpecificAttr *Attr,
1003*0b57cec5SDimitry Andric                                                  unsigned CPUIndex,
1004*0b57cec5SDimitry Andric                                                  raw_ostream &Out) {
1005*0b57cec5SDimitry Andric   // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
1006*0b57cec5SDimitry Andric   // supported.
1007*0b57cec5SDimitry Andric   if (Attr)
1008*0b57cec5SDimitry Andric     Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName());
1009*0b57cec5SDimitry Andric   else if (CGM.getTarget().supportsIFunc())
1010*0b57cec5SDimitry Andric     Out << ".resolver";
1011*0b57cec5SDimitry Andric }
1012*0b57cec5SDimitry Andric 
1013*0b57cec5SDimitry Andric static void AppendTargetMangling(const CodeGenModule &CGM,
1014*0b57cec5SDimitry Andric                                  const TargetAttr *Attr, raw_ostream &Out) {
1015*0b57cec5SDimitry Andric   if (Attr->isDefaultVersion())
1016*0b57cec5SDimitry Andric     return;
1017*0b57cec5SDimitry Andric 
1018*0b57cec5SDimitry Andric   Out << '.';
1019*0b57cec5SDimitry Andric   const TargetInfo &Target = CGM.getTarget();
1020480093f4SDimitry Andric   ParsedTargetAttr Info =
1021*0b57cec5SDimitry Andric       Attr->parse([&Target](StringRef LHS, StringRef RHS) {
1022*0b57cec5SDimitry Andric         // Multiversioning doesn't allow "no-${feature}", so we can
1023*0b57cec5SDimitry Andric         // only have "+" prefixes here.
1024*0b57cec5SDimitry Andric         assert(LHS.startswith("+") && RHS.startswith("+") &&
1025*0b57cec5SDimitry Andric                "Features should always have a prefix.");
1026*0b57cec5SDimitry Andric         return Target.multiVersionSortPriority(LHS.substr(1)) >
1027*0b57cec5SDimitry Andric                Target.multiVersionSortPriority(RHS.substr(1));
1028*0b57cec5SDimitry Andric       });
1029*0b57cec5SDimitry Andric 
1030*0b57cec5SDimitry Andric   bool IsFirst = true;
1031*0b57cec5SDimitry Andric 
1032*0b57cec5SDimitry Andric   if (!Info.Architecture.empty()) {
1033*0b57cec5SDimitry Andric     IsFirst = false;
1034*0b57cec5SDimitry Andric     Out << "arch_" << Info.Architecture;
1035*0b57cec5SDimitry Andric   }
1036*0b57cec5SDimitry Andric 
1037*0b57cec5SDimitry Andric   for (StringRef Feat : Info.Features) {
1038*0b57cec5SDimitry Andric     if (!IsFirst)
1039*0b57cec5SDimitry Andric       Out << '_';
1040*0b57cec5SDimitry Andric     IsFirst = false;
1041*0b57cec5SDimitry Andric     Out << Feat.substr(1);
1042*0b57cec5SDimitry Andric   }
1043*0b57cec5SDimitry Andric }
1044*0b57cec5SDimitry Andric 
1045*0b57cec5SDimitry Andric static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD,
1046*0b57cec5SDimitry Andric                                       const NamedDecl *ND,
1047*0b57cec5SDimitry Andric                                       bool OmitMultiVersionMangling = false) {
1048*0b57cec5SDimitry Andric   SmallString<256> Buffer;
1049*0b57cec5SDimitry Andric   llvm::raw_svector_ostream Out(Buffer);
1050*0b57cec5SDimitry Andric   MangleContext &MC = CGM.getCXXABI().getMangleContext();
10515ffd83dbSDimitry Andric   if (MC.shouldMangleDeclName(ND))
10525ffd83dbSDimitry Andric     MC.mangleName(GD.getWithDecl(ND), Out);
10535ffd83dbSDimitry Andric   else {
1054*0b57cec5SDimitry Andric     IdentifierInfo *II = ND->getIdentifier();
1055*0b57cec5SDimitry Andric     assert(II && "Attempt to mangle unnamed decl.");
1056*0b57cec5SDimitry Andric     const auto *FD = dyn_cast<FunctionDecl>(ND);
1057*0b57cec5SDimitry Andric 
1058*0b57cec5SDimitry Andric     if (FD &&
1059*0b57cec5SDimitry Andric         FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
1060*0b57cec5SDimitry Andric       Out << "__regcall3__" << II->getName();
10615ffd83dbSDimitry Andric     } else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
10625ffd83dbSDimitry Andric                GD.getKernelReferenceKind() == KernelReferenceKind::Stub) {
10635ffd83dbSDimitry Andric       Out << "__device_stub__" << II->getName();
1064*0b57cec5SDimitry Andric     } else {
1065*0b57cec5SDimitry Andric       Out << II->getName();
1066*0b57cec5SDimitry Andric     }
1067*0b57cec5SDimitry Andric   }
1068*0b57cec5SDimitry Andric 
1069*0b57cec5SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(ND))
1070*0b57cec5SDimitry Andric     if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
1071*0b57cec5SDimitry Andric       switch (FD->getMultiVersionKind()) {
1072*0b57cec5SDimitry Andric       case MultiVersionKind::CPUDispatch:
1073*0b57cec5SDimitry Andric       case MultiVersionKind::CPUSpecific:
1074*0b57cec5SDimitry Andric         AppendCPUSpecificCPUDispatchMangling(CGM,
1075*0b57cec5SDimitry Andric                                              FD->getAttr<CPUSpecificAttr>(),
1076*0b57cec5SDimitry Andric                                              GD.getMultiVersionIndex(), Out);
1077*0b57cec5SDimitry Andric         break;
1078*0b57cec5SDimitry Andric       case MultiVersionKind::Target:
1079*0b57cec5SDimitry Andric         AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
1080*0b57cec5SDimitry Andric         break;
1081*0b57cec5SDimitry Andric       case MultiVersionKind::None:
1082*0b57cec5SDimitry Andric         llvm_unreachable("None multiversion type isn't valid here");
1083*0b57cec5SDimitry Andric       }
1084*0b57cec5SDimitry Andric     }
1085*0b57cec5SDimitry Andric 
10865ffd83dbSDimitry Andric   return std::string(Out.str());
1087*0b57cec5SDimitry Andric }
1088*0b57cec5SDimitry Andric 
1089*0b57cec5SDimitry Andric void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
1090*0b57cec5SDimitry Andric                                             const FunctionDecl *FD) {
1091*0b57cec5SDimitry Andric   if (!FD->isMultiVersion())
1092*0b57cec5SDimitry Andric     return;
1093*0b57cec5SDimitry Andric 
1094*0b57cec5SDimitry Andric   // Get the name of what this would be without the 'target' attribute.  This
1095*0b57cec5SDimitry Andric   // allows us to lookup the version that was emitted when this wasn't a
1096*0b57cec5SDimitry Andric   // multiversion function.
1097*0b57cec5SDimitry Andric   std::string NonTargetName =
1098*0b57cec5SDimitry Andric       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
1099*0b57cec5SDimitry Andric   GlobalDecl OtherGD;
1100*0b57cec5SDimitry Andric   if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
1101*0b57cec5SDimitry Andric     assert(OtherGD.getCanonicalDecl()
1102*0b57cec5SDimitry Andric                .getDecl()
1103*0b57cec5SDimitry Andric                ->getAsFunction()
1104*0b57cec5SDimitry Andric                ->isMultiVersion() &&
1105*0b57cec5SDimitry Andric            "Other GD should now be a multiversioned function");
1106*0b57cec5SDimitry Andric     // OtherFD is the version of this function that was mangled BEFORE
1107*0b57cec5SDimitry Andric     // becoming a MultiVersion function.  It potentially needs to be updated.
1108*0b57cec5SDimitry Andric     const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
1109*0b57cec5SDimitry Andric                                       .getDecl()
1110*0b57cec5SDimitry Andric                                       ->getAsFunction()
1111*0b57cec5SDimitry Andric                                       ->getMostRecentDecl();
1112*0b57cec5SDimitry Andric     std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
1113*0b57cec5SDimitry Andric     // This is so that if the initial version was already the 'default'
1114*0b57cec5SDimitry Andric     // version, we don't try to update it.
1115*0b57cec5SDimitry Andric     if (OtherName != NonTargetName) {
1116*0b57cec5SDimitry Andric       // Remove instead of erase, since others may have stored the StringRef
1117*0b57cec5SDimitry Andric       // to this.
1118*0b57cec5SDimitry Andric       const auto ExistingRecord = Manglings.find(NonTargetName);
1119*0b57cec5SDimitry Andric       if (ExistingRecord != std::end(Manglings))
1120*0b57cec5SDimitry Andric         Manglings.remove(&(*ExistingRecord));
1121*0b57cec5SDimitry Andric       auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
1122*0b57cec5SDimitry Andric       MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first();
1123*0b57cec5SDimitry Andric       if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
1124*0b57cec5SDimitry Andric         Entry->setName(OtherName);
1125*0b57cec5SDimitry Andric     }
1126*0b57cec5SDimitry Andric   }
1127*0b57cec5SDimitry Andric }
1128*0b57cec5SDimitry Andric 
1129*0b57cec5SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
1130*0b57cec5SDimitry Andric   GlobalDecl CanonicalGD = GD.getCanonicalDecl();
1131*0b57cec5SDimitry Andric 
1132*0b57cec5SDimitry Andric   // Some ABIs don't have constructor variants.  Make sure that base and
1133*0b57cec5SDimitry Andric   // complete constructors get mangled the same.
1134*0b57cec5SDimitry Andric   if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
1135*0b57cec5SDimitry Andric     if (!getTarget().getCXXABI().hasConstructorVariants()) {
1136*0b57cec5SDimitry Andric       CXXCtorType OrigCtorType = GD.getCtorType();
1137*0b57cec5SDimitry Andric       assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
1138*0b57cec5SDimitry Andric       if (OrigCtorType == Ctor_Base)
1139*0b57cec5SDimitry Andric         CanonicalGD = GlobalDecl(CD, Ctor_Complete);
1140*0b57cec5SDimitry Andric     }
1141*0b57cec5SDimitry Andric   }
1142*0b57cec5SDimitry Andric 
1143*0b57cec5SDimitry Andric   auto FoundName = MangledDeclNames.find(CanonicalGD);
1144*0b57cec5SDimitry Andric   if (FoundName != MangledDeclNames.end())
1145*0b57cec5SDimitry Andric     return FoundName->second;
1146*0b57cec5SDimitry Andric 
1147*0b57cec5SDimitry Andric   // Keep the first result in the case of a mangling collision.
1148*0b57cec5SDimitry Andric   const auto *ND = cast<NamedDecl>(GD.getDecl());
1149*0b57cec5SDimitry Andric   std::string MangledName = getMangledNameImpl(*this, GD, ND);
1150*0b57cec5SDimitry Andric 
11515ffd83dbSDimitry Andric   // Ensure either we have different ABIs between host and device compilations,
11525ffd83dbSDimitry Andric   // says host compilation following MSVC ABI but device compilation follows
11535ffd83dbSDimitry Andric   // Itanium C++ ABI or, if they follow the same ABI, kernel names after
11545ffd83dbSDimitry Andric   // mangling should be the same after name stubbing. The later checking is
11555ffd83dbSDimitry Andric   // very important as the device kernel name being mangled in host-compilation
11565ffd83dbSDimitry Andric   // is used to resolve the device binaries to be executed. Inconsistent naming
11575ffd83dbSDimitry Andric   // result in undefined behavior. Even though we cannot check that naming
11585ffd83dbSDimitry Andric   // directly between host- and device-compilations, the host- and
11595ffd83dbSDimitry Andric   // device-mangling in host compilation could help catching certain ones.
11605ffd83dbSDimitry Andric   assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() ||
11615ffd83dbSDimitry Andric          getLangOpts().CUDAIsDevice ||
11625ffd83dbSDimitry Andric          (getContext().getAuxTargetInfo() &&
11635ffd83dbSDimitry Andric           (getContext().getAuxTargetInfo()->getCXXABI() !=
11645ffd83dbSDimitry Andric            getContext().getTargetInfo().getCXXABI())) ||
11655ffd83dbSDimitry Andric          getCUDARuntime().getDeviceSideName(ND) ==
11665ffd83dbSDimitry Andric              getMangledNameImpl(
11675ffd83dbSDimitry Andric                  *this,
11685ffd83dbSDimitry Andric                  GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel),
11695ffd83dbSDimitry Andric                  ND));
1170*0b57cec5SDimitry Andric 
1171*0b57cec5SDimitry Andric   auto Result = Manglings.insert(std::make_pair(MangledName, GD));
1172*0b57cec5SDimitry Andric   return MangledDeclNames[CanonicalGD] = Result.first->first();
1173*0b57cec5SDimitry Andric }
1174*0b57cec5SDimitry Andric 
1175*0b57cec5SDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
1176*0b57cec5SDimitry Andric                                              const BlockDecl *BD) {
1177*0b57cec5SDimitry Andric   MangleContext &MangleCtx = getCXXABI().getMangleContext();
1178*0b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
1179*0b57cec5SDimitry Andric 
1180*0b57cec5SDimitry Andric   SmallString<256> Buffer;
1181*0b57cec5SDimitry Andric   llvm::raw_svector_ostream Out(Buffer);
1182*0b57cec5SDimitry Andric   if (!D)
1183*0b57cec5SDimitry Andric     MangleCtx.mangleGlobalBlock(BD,
1184*0b57cec5SDimitry Andric       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
1185*0b57cec5SDimitry Andric   else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
1186*0b57cec5SDimitry Andric     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
1187*0b57cec5SDimitry Andric   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
1188*0b57cec5SDimitry Andric     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
1189*0b57cec5SDimitry Andric   else
1190*0b57cec5SDimitry Andric     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
1191*0b57cec5SDimitry Andric 
1192*0b57cec5SDimitry Andric   auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
1193*0b57cec5SDimitry Andric   return Result.first->first();
1194*0b57cec5SDimitry Andric }
1195*0b57cec5SDimitry Andric 
1196*0b57cec5SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
1197*0b57cec5SDimitry Andric   return getModule().getNamedValue(Name);
1198*0b57cec5SDimitry Andric }
1199*0b57cec5SDimitry Andric 
1200*0b57cec5SDimitry Andric /// AddGlobalCtor - Add a function to the list that will be called before
1201*0b57cec5SDimitry Andric /// main() runs.
1202*0b57cec5SDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
1203*0b57cec5SDimitry Andric                                   llvm::Constant *AssociatedData) {
1204*0b57cec5SDimitry Andric   // FIXME: Type coercion of void()* types.
1205*0b57cec5SDimitry Andric   GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
1206*0b57cec5SDimitry Andric }
1207*0b57cec5SDimitry Andric 
1208*0b57cec5SDimitry Andric /// AddGlobalDtor - Add a function to the list that will be called
1209*0b57cec5SDimitry Andric /// when the module is unloaded.
1210*0b57cec5SDimitry Andric void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
1211*0b57cec5SDimitry Andric   if (CodeGenOpts.RegisterGlobalDtorsWithAtExit) {
1212*0b57cec5SDimitry Andric     DtorsUsingAtExit[Priority].push_back(Dtor);
1213*0b57cec5SDimitry Andric     return;
1214*0b57cec5SDimitry Andric   }
1215*0b57cec5SDimitry Andric 
1216*0b57cec5SDimitry Andric   // FIXME: Type coercion of void()* types.
1217*0b57cec5SDimitry Andric   GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
1218*0b57cec5SDimitry Andric }
1219*0b57cec5SDimitry Andric 
1220*0b57cec5SDimitry Andric void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
1221*0b57cec5SDimitry Andric   if (Fns.empty()) return;
1222*0b57cec5SDimitry Andric 
1223*0b57cec5SDimitry Andric   // Ctor function type is void()*.
1224*0b57cec5SDimitry Andric   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
1225*0b57cec5SDimitry Andric   llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
1226*0b57cec5SDimitry Andric       TheModule.getDataLayout().getProgramAddressSpace());
1227*0b57cec5SDimitry Andric 
1228*0b57cec5SDimitry Andric   // Get the type of a ctor entry, { i32, void ()*, i8* }.
1229*0b57cec5SDimitry Andric   llvm::StructType *CtorStructTy = llvm::StructType::get(
1230*0b57cec5SDimitry Andric       Int32Ty, CtorPFTy, VoidPtrTy);
1231*0b57cec5SDimitry Andric 
1232*0b57cec5SDimitry Andric   // Construct the constructor and destructor arrays.
1233*0b57cec5SDimitry Andric   ConstantInitBuilder builder(*this);
1234*0b57cec5SDimitry Andric   auto ctors = builder.beginArray(CtorStructTy);
1235*0b57cec5SDimitry Andric   for (const auto &I : Fns) {
1236*0b57cec5SDimitry Andric     auto ctor = ctors.beginStruct(CtorStructTy);
1237*0b57cec5SDimitry Andric     ctor.addInt(Int32Ty, I.Priority);
1238*0b57cec5SDimitry Andric     ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
1239*0b57cec5SDimitry Andric     if (I.AssociatedData)
1240*0b57cec5SDimitry Andric       ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
1241*0b57cec5SDimitry Andric     else
1242*0b57cec5SDimitry Andric       ctor.addNullPointer(VoidPtrTy);
1243*0b57cec5SDimitry Andric     ctor.finishAndAddTo(ctors);
1244*0b57cec5SDimitry Andric   }
1245*0b57cec5SDimitry Andric 
1246*0b57cec5SDimitry Andric   auto list =
1247*0b57cec5SDimitry Andric     ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
1248*0b57cec5SDimitry Andric                                 /*constant*/ false,
1249*0b57cec5SDimitry Andric                                 llvm::GlobalValue::AppendingLinkage);
1250*0b57cec5SDimitry Andric 
1251*0b57cec5SDimitry Andric   // The LTO linker doesn't seem to like it when we set an alignment
1252*0b57cec5SDimitry Andric   // on appending variables.  Take it off as a workaround.
1253a7dea167SDimitry Andric   list->setAlignment(llvm::None);
1254*0b57cec5SDimitry Andric 
1255*0b57cec5SDimitry Andric   Fns.clear();
1256*0b57cec5SDimitry Andric }
1257*0b57cec5SDimitry Andric 
1258*0b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes
1259*0b57cec5SDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
1260*0b57cec5SDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
1261*0b57cec5SDimitry Andric 
1262*0b57cec5SDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
1263*0b57cec5SDimitry Andric 
1264*0b57cec5SDimitry Andric   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
1265*0b57cec5SDimitry Andric     return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
1266*0b57cec5SDimitry Andric 
1267*0b57cec5SDimitry Andric   if (isa<CXXConstructorDecl>(D) &&
1268*0b57cec5SDimitry Andric       cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
1269*0b57cec5SDimitry Andric       Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1270*0b57cec5SDimitry Andric     // Our approach to inheriting constructors is fundamentally different from
1271*0b57cec5SDimitry Andric     // that used by the MS ABI, so keep our inheriting constructor thunks
1272*0b57cec5SDimitry Andric     // internal rather than trying to pick an unambiguous mangling for them.
1273*0b57cec5SDimitry Andric     return llvm::GlobalValue::InternalLinkage;
1274*0b57cec5SDimitry Andric   }
1275*0b57cec5SDimitry Andric 
1276*0b57cec5SDimitry Andric   return getLLVMLinkageForDeclarator(D, Linkage, /*IsConstantVariable=*/false);
1277*0b57cec5SDimitry Andric }
1278*0b57cec5SDimitry Andric 
1279*0b57cec5SDimitry Andric llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
1280*0b57cec5SDimitry Andric   llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
1281*0b57cec5SDimitry Andric   if (!MDS) return nullptr;
1282*0b57cec5SDimitry Andric 
1283*0b57cec5SDimitry Andric   return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
1284*0b57cec5SDimitry Andric }
1285*0b57cec5SDimitry Andric 
1286*0b57cec5SDimitry Andric void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
1287*0b57cec5SDimitry Andric                                               const CGFunctionInfo &Info,
1288*0b57cec5SDimitry Andric                                               llvm::Function *F) {
1289*0b57cec5SDimitry Andric   unsigned CallingConv;
1290*0b57cec5SDimitry Andric   llvm::AttributeList PAL;
1291*0b57cec5SDimitry Andric   ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv, false);
1292*0b57cec5SDimitry Andric   F->setAttributes(PAL);
1293*0b57cec5SDimitry Andric   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
1294*0b57cec5SDimitry Andric }
1295*0b57cec5SDimitry Andric 
1296*0b57cec5SDimitry Andric static void removeImageAccessQualifier(std::string& TyName) {
1297*0b57cec5SDimitry Andric   std::string ReadOnlyQual("__read_only");
1298*0b57cec5SDimitry Andric   std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
1299*0b57cec5SDimitry Andric   if (ReadOnlyPos != std::string::npos)
1300*0b57cec5SDimitry Andric     // "+ 1" for the space after access qualifier.
1301*0b57cec5SDimitry Andric     TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
1302*0b57cec5SDimitry Andric   else {
1303*0b57cec5SDimitry Andric     std::string WriteOnlyQual("__write_only");
1304*0b57cec5SDimitry Andric     std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
1305*0b57cec5SDimitry Andric     if (WriteOnlyPos != std::string::npos)
1306*0b57cec5SDimitry Andric       TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
1307*0b57cec5SDimitry Andric     else {
1308*0b57cec5SDimitry Andric       std::string ReadWriteQual("__read_write");
1309*0b57cec5SDimitry Andric       std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
1310*0b57cec5SDimitry Andric       if (ReadWritePos != std::string::npos)
1311*0b57cec5SDimitry Andric         TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
1312*0b57cec5SDimitry Andric     }
1313*0b57cec5SDimitry Andric   }
1314*0b57cec5SDimitry Andric }
1315*0b57cec5SDimitry Andric 
1316*0b57cec5SDimitry Andric // Returns the address space id that should be produced to the
1317*0b57cec5SDimitry Andric // kernel_arg_addr_space metadata. This is always fixed to the ids
1318*0b57cec5SDimitry Andric // as specified in the SPIR 2.0 specification in order to differentiate
1319*0b57cec5SDimitry Andric // for example in clGetKernelArgInfo() implementation between the address
1320*0b57cec5SDimitry Andric // spaces with targets without unique mapping to the OpenCL address spaces
1321*0b57cec5SDimitry Andric // (basically all single AS CPUs).
1322*0b57cec5SDimitry Andric static unsigned ArgInfoAddressSpace(LangAS AS) {
1323*0b57cec5SDimitry Andric   switch (AS) {
1324*0b57cec5SDimitry Andric   case LangAS::opencl_global:   return 1;
1325*0b57cec5SDimitry Andric   case LangAS::opencl_constant: return 2;
1326*0b57cec5SDimitry Andric   case LangAS::opencl_local:    return 3;
1327*0b57cec5SDimitry Andric   case LangAS::opencl_generic:  return 4; // Not in SPIR 2.0 specs.
1328*0b57cec5SDimitry Andric   default:
1329*0b57cec5SDimitry Andric     return 0; // Assume private.
1330*0b57cec5SDimitry Andric   }
1331*0b57cec5SDimitry Andric }
1332*0b57cec5SDimitry Andric 
1333*0b57cec5SDimitry Andric void CodeGenModule::GenOpenCLArgMetadata(llvm::Function *Fn,
1334*0b57cec5SDimitry Andric                                          const FunctionDecl *FD,
1335*0b57cec5SDimitry Andric                                          CodeGenFunction *CGF) {
1336*0b57cec5SDimitry Andric   assert(((FD && CGF) || (!FD && !CGF)) &&
1337*0b57cec5SDimitry Andric          "Incorrect use - FD and CGF should either be both null or not!");
1338*0b57cec5SDimitry Andric   // Create MDNodes that represent the kernel arg metadata.
1339*0b57cec5SDimitry Andric   // Each MDNode is a list in the form of "key", N number of values which is
1340*0b57cec5SDimitry Andric   // the same number of values as their are kernel arguments.
1341*0b57cec5SDimitry Andric 
1342*0b57cec5SDimitry Andric   const PrintingPolicy &Policy = Context.getPrintingPolicy();
1343*0b57cec5SDimitry Andric 
1344*0b57cec5SDimitry Andric   // MDNode for the kernel argument address space qualifiers.
1345*0b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> addressQuals;
1346*0b57cec5SDimitry Andric 
1347*0b57cec5SDimitry Andric   // MDNode for the kernel argument access qualifiers (images only).
1348*0b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> accessQuals;
1349*0b57cec5SDimitry Andric 
1350*0b57cec5SDimitry Andric   // MDNode for the kernel argument type names.
1351*0b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> argTypeNames;
1352*0b57cec5SDimitry Andric 
1353*0b57cec5SDimitry Andric   // MDNode for the kernel argument base type names.
1354*0b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
1355*0b57cec5SDimitry Andric 
1356*0b57cec5SDimitry Andric   // MDNode for the kernel argument type qualifiers.
1357*0b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> argTypeQuals;
1358*0b57cec5SDimitry Andric 
1359*0b57cec5SDimitry Andric   // MDNode for the kernel argument names.
1360*0b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> argNames;
1361*0b57cec5SDimitry Andric 
1362*0b57cec5SDimitry Andric   if (FD && CGF)
1363*0b57cec5SDimitry Andric     for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
1364*0b57cec5SDimitry Andric       const ParmVarDecl *parm = FD->getParamDecl(i);
1365*0b57cec5SDimitry Andric       QualType ty = parm->getType();
1366*0b57cec5SDimitry Andric       std::string typeQuals;
1367*0b57cec5SDimitry Andric 
1368*0b57cec5SDimitry Andric       if (ty->isPointerType()) {
1369*0b57cec5SDimitry Andric         QualType pointeeTy = ty->getPointeeType();
1370*0b57cec5SDimitry Andric 
1371*0b57cec5SDimitry Andric         // Get address qualifier.
1372*0b57cec5SDimitry Andric         addressQuals.push_back(
1373*0b57cec5SDimitry Andric             llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(
1374*0b57cec5SDimitry Andric                 ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
1375*0b57cec5SDimitry Andric 
1376*0b57cec5SDimitry Andric         // Get argument type name.
1377*0b57cec5SDimitry Andric         std::string typeName =
1378*0b57cec5SDimitry Andric             pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
1379*0b57cec5SDimitry Andric 
1380*0b57cec5SDimitry Andric         // Turn "unsigned type" to "utype"
1381*0b57cec5SDimitry Andric         std::string::size_type pos = typeName.find("unsigned");
1382*0b57cec5SDimitry Andric         if (pointeeTy.isCanonical() && pos != std::string::npos)
1383*0b57cec5SDimitry Andric           typeName.erase(pos + 1, 8);
1384*0b57cec5SDimitry Andric 
1385*0b57cec5SDimitry Andric         argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
1386*0b57cec5SDimitry Andric 
1387*0b57cec5SDimitry Andric         std::string baseTypeName =
1388*0b57cec5SDimitry Andric             pointeeTy.getUnqualifiedType().getCanonicalType().getAsString(
1389*0b57cec5SDimitry Andric                 Policy) +
1390*0b57cec5SDimitry Andric             "*";
1391*0b57cec5SDimitry Andric 
1392*0b57cec5SDimitry Andric         // Turn "unsigned type" to "utype"
1393*0b57cec5SDimitry Andric         pos = baseTypeName.find("unsigned");
1394*0b57cec5SDimitry Andric         if (pos != std::string::npos)
1395*0b57cec5SDimitry Andric           baseTypeName.erase(pos + 1, 8);
1396*0b57cec5SDimitry Andric 
1397*0b57cec5SDimitry Andric         argBaseTypeNames.push_back(
1398*0b57cec5SDimitry Andric             llvm::MDString::get(VMContext, baseTypeName));
1399*0b57cec5SDimitry Andric 
1400*0b57cec5SDimitry Andric         // Get argument type qualifiers:
1401*0b57cec5SDimitry Andric         if (ty.isRestrictQualified())
1402*0b57cec5SDimitry Andric           typeQuals = "restrict";
1403*0b57cec5SDimitry Andric         if (pointeeTy.isConstQualified() ||
1404*0b57cec5SDimitry Andric             (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
1405*0b57cec5SDimitry Andric           typeQuals += typeQuals.empty() ? "const" : " const";
1406*0b57cec5SDimitry Andric         if (pointeeTy.isVolatileQualified())
1407*0b57cec5SDimitry Andric           typeQuals += typeQuals.empty() ? "volatile" : " volatile";
1408*0b57cec5SDimitry Andric       } else {
1409*0b57cec5SDimitry Andric         uint32_t AddrSpc = 0;
1410*0b57cec5SDimitry Andric         bool isPipe = ty->isPipeType();
1411*0b57cec5SDimitry Andric         if (ty->isImageType() || isPipe)
1412*0b57cec5SDimitry Andric           AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
1413*0b57cec5SDimitry Andric 
1414*0b57cec5SDimitry Andric         addressQuals.push_back(
1415*0b57cec5SDimitry Andric             llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc)));
1416*0b57cec5SDimitry Andric 
1417*0b57cec5SDimitry Andric         // Get argument type name.
1418*0b57cec5SDimitry Andric         std::string typeName;
1419*0b57cec5SDimitry Andric         if (isPipe)
1420*0b57cec5SDimitry Andric           typeName = ty.getCanonicalType()
14215ffd83dbSDimitry Andric                          ->castAs<PipeType>()
1422*0b57cec5SDimitry Andric                          ->getElementType()
1423*0b57cec5SDimitry Andric                          .getAsString(Policy);
1424*0b57cec5SDimitry Andric         else
1425*0b57cec5SDimitry Andric           typeName = ty.getUnqualifiedType().getAsString(Policy);
1426*0b57cec5SDimitry Andric 
1427*0b57cec5SDimitry Andric         // Turn "unsigned type" to "utype"
1428*0b57cec5SDimitry Andric         std::string::size_type pos = typeName.find("unsigned");
1429*0b57cec5SDimitry Andric         if (ty.isCanonical() && pos != std::string::npos)
1430*0b57cec5SDimitry Andric           typeName.erase(pos + 1, 8);
1431*0b57cec5SDimitry Andric 
1432*0b57cec5SDimitry Andric         std::string baseTypeName;
1433*0b57cec5SDimitry Andric         if (isPipe)
1434*0b57cec5SDimitry Andric           baseTypeName = ty.getCanonicalType()
14355ffd83dbSDimitry Andric                              ->castAs<PipeType>()
1436*0b57cec5SDimitry Andric                              ->getElementType()
1437*0b57cec5SDimitry Andric                              .getCanonicalType()
1438*0b57cec5SDimitry Andric                              .getAsString(Policy);
1439*0b57cec5SDimitry Andric         else
1440*0b57cec5SDimitry Andric           baseTypeName =
1441*0b57cec5SDimitry Andric               ty.getUnqualifiedType().getCanonicalType().getAsString(Policy);
1442*0b57cec5SDimitry Andric 
1443*0b57cec5SDimitry Andric         // Remove access qualifiers on images
1444*0b57cec5SDimitry Andric         // (as they are inseparable from type in clang implementation,
1445*0b57cec5SDimitry Andric         // but OpenCL spec provides a special query to get access qualifier
1446*0b57cec5SDimitry Andric         // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
1447*0b57cec5SDimitry Andric         if (ty->isImageType()) {
1448*0b57cec5SDimitry Andric           removeImageAccessQualifier(typeName);
1449*0b57cec5SDimitry Andric           removeImageAccessQualifier(baseTypeName);
1450*0b57cec5SDimitry Andric         }
1451*0b57cec5SDimitry Andric 
1452*0b57cec5SDimitry Andric         argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
1453*0b57cec5SDimitry Andric 
1454*0b57cec5SDimitry Andric         // Turn "unsigned type" to "utype"
1455*0b57cec5SDimitry Andric         pos = baseTypeName.find("unsigned");
1456*0b57cec5SDimitry Andric         if (pos != std::string::npos)
1457*0b57cec5SDimitry Andric           baseTypeName.erase(pos + 1, 8);
1458*0b57cec5SDimitry Andric 
1459*0b57cec5SDimitry Andric         argBaseTypeNames.push_back(
1460*0b57cec5SDimitry Andric             llvm::MDString::get(VMContext, baseTypeName));
1461*0b57cec5SDimitry Andric 
1462*0b57cec5SDimitry Andric         if (isPipe)
1463*0b57cec5SDimitry Andric           typeQuals = "pipe";
1464*0b57cec5SDimitry Andric       }
1465*0b57cec5SDimitry Andric 
1466*0b57cec5SDimitry Andric       argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
1467*0b57cec5SDimitry Andric 
1468*0b57cec5SDimitry Andric       // Get image and pipe access qualifier:
1469*0b57cec5SDimitry Andric       if (ty->isImageType() || ty->isPipeType()) {
1470*0b57cec5SDimitry Andric         const Decl *PDecl = parm;
1471*0b57cec5SDimitry Andric         if (auto *TD = dyn_cast<TypedefType>(ty))
1472*0b57cec5SDimitry Andric           PDecl = TD->getDecl();
1473*0b57cec5SDimitry Andric         const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
1474*0b57cec5SDimitry Andric         if (A && A->isWriteOnly())
1475*0b57cec5SDimitry Andric           accessQuals.push_back(llvm::MDString::get(VMContext, "write_only"));
1476*0b57cec5SDimitry Andric         else if (A && A->isReadWrite())
1477*0b57cec5SDimitry Andric           accessQuals.push_back(llvm::MDString::get(VMContext, "read_write"));
1478*0b57cec5SDimitry Andric         else
1479*0b57cec5SDimitry Andric           accessQuals.push_back(llvm::MDString::get(VMContext, "read_only"));
1480*0b57cec5SDimitry Andric       } else
1481*0b57cec5SDimitry Andric         accessQuals.push_back(llvm::MDString::get(VMContext, "none"));
1482*0b57cec5SDimitry Andric 
1483*0b57cec5SDimitry Andric       // Get argument name.
1484*0b57cec5SDimitry Andric       argNames.push_back(llvm::MDString::get(VMContext, parm->getName()));
1485*0b57cec5SDimitry Andric     }
1486*0b57cec5SDimitry Andric 
1487*0b57cec5SDimitry Andric   Fn->setMetadata("kernel_arg_addr_space",
1488*0b57cec5SDimitry Andric                   llvm::MDNode::get(VMContext, addressQuals));
1489*0b57cec5SDimitry Andric   Fn->setMetadata("kernel_arg_access_qual",
1490*0b57cec5SDimitry Andric                   llvm::MDNode::get(VMContext, accessQuals));
1491*0b57cec5SDimitry Andric   Fn->setMetadata("kernel_arg_type",
1492*0b57cec5SDimitry Andric                   llvm::MDNode::get(VMContext, argTypeNames));
1493*0b57cec5SDimitry Andric   Fn->setMetadata("kernel_arg_base_type",
1494*0b57cec5SDimitry Andric                   llvm::MDNode::get(VMContext, argBaseTypeNames));
1495*0b57cec5SDimitry Andric   Fn->setMetadata("kernel_arg_type_qual",
1496*0b57cec5SDimitry Andric                   llvm::MDNode::get(VMContext, argTypeQuals));
1497*0b57cec5SDimitry Andric   if (getCodeGenOpts().EmitOpenCLArgMetadata)
1498*0b57cec5SDimitry Andric     Fn->setMetadata("kernel_arg_name",
1499*0b57cec5SDimitry Andric                     llvm::MDNode::get(VMContext, argNames));
1500*0b57cec5SDimitry Andric }
1501*0b57cec5SDimitry Andric 
1502*0b57cec5SDimitry Andric /// Determines whether the language options require us to model
1503*0b57cec5SDimitry Andric /// unwind exceptions.  We treat -fexceptions as mandating this
1504*0b57cec5SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions
1505*0b57cec5SDimitry Andric /// enabled.  This means, for example, that C with -fexceptions
1506*0b57cec5SDimitry Andric /// enables this.
1507*0b57cec5SDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) {
1508*0b57cec5SDimitry Andric   // If exceptions are completely disabled, obviously this is false.
1509*0b57cec5SDimitry Andric   if (!LangOpts.Exceptions) return false;
1510*0b57cec5SDimitry Andric 
1511*0b57cec5SDimitry Andric   // If C++ exceptions are enabled, this is true.
1512*0b57cec5SDimitry Andric   if (LangOpts.CXXExceptions) return true;
1513*0b57cec5SDimitry Andric 
1514*0b57cec5SDimitry Andric   // If ObjC exceptions are enabled, this depends on the ABI.
1515*0b57cec5SDimitry Andric   if (LangOpts.ObjCExceptions) {
1516*0b57cec5SDimitry Andric     return LangOpts.ObjCRuntime.hasUnwindExceptions();
1517*0b57cec5SDimitry Andric   }
1518*0b57cec5SDimitry Andric 
1519*0b57cec5SDimitry Andric   return true;
1520*0b57cec5SDimitry Andric }
1521*0b57cec5SDimitry Andric 
1522*0b57cec5SDimitry Andric static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
1523*0b57cec5SDimitry Andric                                                       const CXXMethodDecl *MD) {
1524*0b57cec5SDimitry Andric   // Check that the type metadata can ever actually be used by a call.
1525*0b57cec5SDimitry Andric   if (!CGM.getCodeGenOpts().LTOUnit ||
1526*0b57cec5SDimitry Andric       !CGM.HasHiddenLTOVisibility(MD->getParent()))
1527*0b57cec5SDimitry Andric     return false;
1528*0b57cec5SDimitry Andric 
1529*0b57cec5SDimitry Andric   // Only functions whose address can be taken with a member function pointer
1530*0b57cec5SDimitry Andric   // need this sort of type metadata.
1531*0b57cec5SDimitry Andric   return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
1532*0b57cec5SDimitry Andric          !isa<CXXDestructorDecl>(MD);
1533*0b57cec5SDimitry Andric }
1534*0b57cec5SDimitry Andric 
1535*0b57cec5SDimitry Andric std::vector<const CXXRecordDecl *>
1536*0b57cec5SDimitry Andric CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
1537*0b57cec5SDimitry Andric   llvm::SetVector<const CXXRecordDecl *> MostBases;
1538*0b57cec5SDimitry Andric 
1539*0b57cec5SDimitry Andric   std::function<void (const CXXRecordDecl *)> CollectMostBases;
1540*0b57cec5SDimitry Andric   CollectMostBases = [&](const CXXRecordDecl *RD) {
1541*0b57cec5SDimitry Andric     if (RD->getNumBases() == 0)
1542*0b57cec5SDimitry Andric       MostBases.insert(RD);
1543*0b57cec5SDimitry Andric     for (const CXXBaseSpecifier &B : RD->bases())
1544*0b57cec5SDimitry Andric       CollectMostBases(B.getType()->getAsCXXRecordDecl());
1545*0b57cec5SDimitry Andric   };
1546*0b57cec5SDimitry Andric   CollectMostBases(RD);
1547*0b57cec5SDimitry Andric   return MostBases.takeVector();
1548*0b57cec5SDimitry Andric }
1549*0b57cec5SDimitry Andric 
1550*0b57cec5SDimitry Andric void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
1551*0b57cec5SDimitry Andric                                                            llvm::Function *F) {
1552*0b57cec5SDimitry Andric   llvm::AttrBuilder B;
1553*0b57cec5SDimitry Andric 
1554*0b57cec5SDimitry Andric   if (CodeGenOpts.UnwindTables)
1555*0b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::UWTable);
1556*0b57cec5SDimitry Andric 
15575ffd83dbSDimitry Andric   if (CodeGenOpts.StackClashProtector)
15585ffd83dbSDimitry Andric     B.addAttribute("probe-stack", "inline-asm");
15595ffd83dbSDimitry Andric 
1560*0b57cec5SDimitry Andric   if (!hasUnwindExceptions(LangOpts))
1561*0b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoUnwind);
1562*0b57cec5SDimitry Andric 
1563*0b57cec5SDimitry Andric   if (!D || !D->hasAttr<NoStackProtectorAttr>()) {
1564*0b57cec5SDimitry Andric     if (LangOpts.getStackProtector() == LangOptions::SSPOn)
1565*0b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::StackProtect);
1566*0b57cec5SDimitry Andric     else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
1567*0b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::StackProtectStrong);
1568*0b57cec5SDimitry Andric     else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
1569*0b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::StackProtectReq);
1570*0b57cec5SDimitry Andric   }
1571*0b57cec5SDimitry Andric 
1572*0b57cec5SDimitry Andric   if (!D) {
1573*0b57cec5SDimitry Andric     // If we don't have a declaration to control inlining, the function isn't
1574*0b57cec5SDimitry Andric     // explicitly marked as alwaysinline for semantic reasons, and inlining is
1575*0b57cec5SDimitry Andric     // disabled, mark the function as noinline.
1576*0b57cec5SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1577*0b57cec5SDimitry Andric         CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
1578*0b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
1579*0b57cec5SDimitry Andric 
1580*0b57cec5SDimitry Andric     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1581*0b57cec5SDimitry Andric     return;
1582*0b57cec5SDimitry Andric   }
1583*0b57cec5SDimitry Andric 
1584*0b57cec5SDimitry Andric   // Track whether we need to add the optnone LLVM attribute,
1585*0b57cec5SDimitry Andric   // starting with the default for this optimization level.
1586*0b57cec5SDimitry Andric   bool ShouldAddOptNone =
1587*0b57cec5SDimitry Andric       !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
1588*0b57cec5SDimitry Andric   // We can't add optnone in the following cases, it won't pass the verifier.
1589*0b57cec5SDimitry Andric   ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
1590*0b57cec5SDimitry Andric   ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
1591*0b57cec5SDimitry Andric 
1592480093f4SDimitry Andric   // Add optnone, but do so only if the function isn't always_inline.
1593480093f4SDimitry Andric   if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) &&
1594480093f4SDimitry Andric       !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1595*0b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::OptimizeNone);
1596*0b57cec5SDimitry Andric 
1597*0b57cec5SDimitry Andric     // OptimizeNone implies noinline; we should not be inlining such functions.
1598*0b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
1599*0b57cec5SDimitry Andric 
1600*0b57cec5SDimitry Andric     // We still need to handle naked functions even though optnone subsumes
1601*0b57cec5SDimitry Andric     // much of their semantics.
1602*0b57cec5SDimitry Andric     if (D->hasAttr<NakedAttr>())
1603*0b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::Naked);
1604*0b57cec5SDimitry Andric 
1605*0b57cec5SDimitry Andric     // OptimizeNone wins over OptimizeForSize and MinSize.
1606*0b57cec5SDimitry Andric     F->removeFnAttr(llvm::Attribute::OptimizeForSize);
1607*0b57cec5SDimitry Andric     F->removeFnAttr(llvm::Attribute::MinSize);
1608*0b57cec5SDimitry Andric   } else if (D->hasAttr<NakedAttr>()) {
1609*0b57cec5SDimitry Andric     // Naked implies noinline: we should not be inlining such functions.
1610*0b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::Naked);
1611*0b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
1612*0b57cec5SDimitry Andric   } else if (D->hasAttr<NoDuplicateAttr>()) {
1613*0b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoDuplicate);
1614480093f4SDimitry Andric   } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1615480093f4SDimitry Andric     // Add noinline if the function isn't always_inline.
1616*0b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
1617*0b57cec5SDimitry Andric   } else if (D->hasAttr<AlwaysInlineAttr>() &&
1618*0b57cec5SDimitry Andric              !F->hasFnAttribute(llvm::Attribute::NoInline)) {
1619*0b57cec5SDimitry Andric     // (noinline wins over always_inline, and we can't specify both in IR)
1620*0b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::AlwaysInline);
1621*0b57cec5SDimitry Andric   } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
1622*0b57cec5SDimitry Andric     // If we're not inlining, then force everything that isn't always_inline to
1623*0b57cec5SDimitry Andric     // carry an explicit noinline attribute.
1624*0b57cec5SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
1625*0b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
1626*0b57cec5SDimitry Andric   } else {
1627*0b57cec5SDimitry Andric     // Otherwise, propagate the inline hint attribute and potentially use its
1628*0b57cec5SDimitry Andric     // absence to mark things as noinline.
1629*0b57cec5SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1630*0b57cec5SDimitry Andric       // Search function and template pattern redeclarations for inline.
1631*0b57cec5SDimitry Andric       auto CheckForInline = [](const FunctionDecl *FD) {
1632*0b57cec5SDimitry Andric         auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
1633*0b57cec5SDimitry Andric           return Redecl->isInlineSpecified();
1634*0b57cec5SDimitry Andric         };
1635*0b57cec5SDimitry Andric         if (any_of(FD->redecls(), CheckRedeclForInline))
1636*0b57cec5SDimitry Andric           return true;
1637*0b57cec5SDimitry Andric         const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
1638*0b57cec5SDimitry Andric         if (!Pattern)
1639*0b57cec5SDimitry Andric           return false;
1640*0b57cec5SDimitry Andric         return any_of(Pattern->redecls(), CheckRedeclForInline);
1641*0b57cec5SDimitry Andric       };
1642*0b57cec5SDimitry Andric       if (CheckForInline(FD)) {
1643*0b57cec5SDimitry Andric         B.addAttribute(llvm::Attribute::InlineHint);
1644*0b57cec5SDimitry Andric       } else if (CodeGenOpts.getInlining() ==
1645*0b57cec5SDimitry Andric                      CodeGenOptions::OnlyHintInlining &&
1646*0b57cec5SDimitry Andric                  !FD->isInlined() &&
1647*0b57cec5SDimitry Andric                  !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1648*0b57cec5SDimitry Andric         B.addAttribute(llvm::Attribute::NoInline);
1649*0b57cec5SDimitry Andric       }
1650*0b57cec5SDimitry Andric     }
1651*0b57cec5SDimitry Andric   }
1652*0b57cec5SDimitry Andric 
1653*0b57cec5SDimitry Andric   // Add other optimization related attributes if we are optimizing this
1654*0b57cec5SDimitry Andric   // function.
1655*0b57cec5SDimitry Andric   if (!D->hasAttr<OptimizeNoneAttr>()) {
1656*0b57cec5SDimitry Andric     if (D->hasAttr<ColdAttr>()) {
1657*0b57cec5SDimitry Andric       if (!ShouldAddOptNone)
1658*0b57cec5SDimitry Andric         B.addAttribute(llvm::Attribute::OptimizeForSize);
1659*0b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::Cold);
1660*0b57cec5SDimitry Andric     }
1661*0b57cec5SDimitry Andric 
1662*0b57cec5SDimitry Andric     if (D->hasAttr<MinSizeAttr>())
1663*0b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::MinSize);
1664*0b57cec5SDimitry Andric   }
1665*0b57cec5SDimitry Andric 
1666*0b57cec5SDimitry Andric   F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1667*0b57cec5SDimitry Andric 
1668*0b57cec5SDimitry Andric   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
1669*0b57cec5SDimitry Andric   if (alignment)
1670a7dea167SDimitry Andric     F->setAlignment(llvm::Align(alignment));
1671*0b57cec5SDimitry Andric 
1672*0b57cec5SDimitry Andric   if (!D->hasAttr<AlignedAttr>())
1673*0b57cec5SDimitry Andric     if (LangOpts.FunctionAlignment)
1674a7dea167SDimitry Andric       F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
1675*0b57cec5SDimitry Andric 
1676*0b57cec5SDimitry Andric   // Some C++ ABIs require 2-byte alignment for member functions, in order to
1677*0b57cec5SDimitry Andric   // reserve a bit for differentiating between virtual and non-virtual member
1678*0b57cec5SDimitry Andric   // functions. If the current target's C++ ABI requires this and this is a
1679*0b57cec5SDimitry Andric   // member function, set its alignment accordingly.
1680*0b57cec5SDimitry Andric   if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
1681*0b57cec5SDimitry Andric     if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1682a7dea167SDimitry Andric       F->setAlignment(llvm::Align(2));
1683*0b57cec5SDimitry Andric   }
1684*0b57cec5SDimitry Andric 
1685a7dea167SDimitry Andric   // In the cross-dso CFI mode with canonical jump tables, we want !type
1686a7dea167SDimitry Andric   // attributes on definitions only.
1687a7dea167SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso &&
1688a7dea167SDimitry Andric       CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
1689a7dea167SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1690a7dea167SDimitry Andric       // Skip available_externally functions. They won't be codegen'ed in the
1691a7dea167SDimitry Andric       // current module anyway.
1692a7dea167SDimitry Andric       if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally)
1693*0b57cec5SDimitry Andric         CreateFunctionTypeMetadataForIcall(FD, F);
1694a7dea167SDimitry Andric     }
1695a7dea167SDimitry Andric   }
1696*0b57cec5SDimitry Andric 
1697*0b57cec5SDimitry Andric   // Emit type metadata on member functions for member function pointer checks.
1698*0b57cec5SDimitry Andric   // These are only ever necessary on definitions; we're guaranteed that the
1699*0b57cec5SDimitry Andric   // definition will be present in the LTO unit as a result of LTO visibility.
1700*0b57cec5SDimitry Andric   auto *MD = dyn_cast<CXXMethodDecl>(D);
1701*0b57cec5SDimitry Andric   if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
1702*0b57cec5SDimitry Andric     for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
1703*0b57cec5SDimitry Andric       llvm::Metadata *Id =
1704*0b57cec5SDimitry Andric           CreateMetadataIdentifierForType(Context.getMemberPointerType(
1705*0b57cec5SDimitry Andric               MD->getType(), Context.getRecordType(Base).getTypePtr()));
1706*0b57cec5SDimitry Andric       F->addTypeMetadata(0, Id);
1707*0b57cec5SDimitry Andric     }
1708*0b57cec5SDimitry Andric   }
1709*0b57cec5SDimitry Andric }
1710*0b57cec5SDimitry Andric 
1711*0b57cec5SDimitry Andric void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
1712*0b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
1713*0b57cec5SDimitry Andric   if (dyn_cast_or_null<NamedDecl>(D))
1714*0b57cec5SDimitry Andric     setGVProperties(GV, GD);
1715*0b57cec5SDimitry Andric   else
1716*0b57cec5SDimitry Andric     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1717*0b57cec5SDimitry Andric 
1718*0b57cec5SDimitry Andric   if (D && D->hasAttr<UsedAttr>())
1719*0b57cec5SDimitry Andric     addUsedGlobal(GV);
1720*0b57cec5SDimitry Andric 
1721*0b57cec5SDimitry Andric   if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) {
1722*0b57cec5SDimitry Andric     const auto *VD = cast<VarDecl>(D);
1723*0b57cec5SDimitry Andric     if (VD->getType().isConstQualified() &&
1724*0b57cec5SDimitry Andric         VD->getStorageDuration() == SD_Static)
1725*0b57cec5SDimitry Andric       addUsedGlobal(GV);
1726*0b57cec5SDimitry Andric   }
1727*0b57cec5SDimitry Andric }
1728*0b57cec5SDimitry Andric 
1729*0b57cec5SDimitry Andric bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
1730*0b57cec5SDimitry Andric                                                 llvm::AttrBuilder &Attrs) {
1731*0b57cec5SDimitry Andric   // Add target-cpu and target-features attributes to functions. If
1732*0b57cec5SDimitry Andric   // we have a decl for the function and it has a target attribute then
1733*0b57cec5SDimitry Andric   // parse that and add it to the feature set.
1734*0b57cec5SDimitry Andric   StringRef TargetCPU = getTarget().getTargetOpts().CPU;
1735*0b57cec5SDimitry Andric   std::vector<std::string> Features;
1736*0b57cec5SDimitry Andric   const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
1737*0b57cec5SDimitry Andric   FD = FD ? FD->getMostRecentDecl() : FD;
1738*0b57cec5SDimitry Andric   const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
1739*0b57cec5SDimitry Andric   const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
1740*0b57cec5SDimitry Andric   bool AddedAttr = false;
1741*0b57cec5SDimitry Andric   if (TD || SD) {
1742*0b57cec5SDimitry Andric     llvm::StringMap<bool> FeatureMap;
1743480093f4SDimitry Andric     getContext().getFunctionFeatureMap(FeatureMap, GD);
1744*0b57cec5SDimitry Andric 
1745*0b57cec5SDimitry Andric     // Produce the canonical string for this set of features.
1746*0b57cec5SDimitry Andric     for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
1747*0b57cec5SDimitry Andric       Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
1748*0b57cec5SDimitry Andric 
1749*0b57cec5SDimitry Andric     // Now add the target-cpu and target-features to the function.
1750*0b57cec5SDimitry Andric     // While we populated the feature map above, we still need to
1751*0b57cec5SDimitry Andric     // get and parse the target attribute so we can get the cpu for
1752*0b57cec5SDimitry Andric     // the function.
1753*0b57cec5SDimitry Andric     if (TD) {
1754480093f4SDimitry Andric       ParsedTargetAttr ParsedAttr = TD->parse();
1755*0b57cec5SDimitry Andric       if (ParsedAttr.Architecture != "" &&
1756*0b57cec5SDimitry Andric           getTarget().isValidCPUName(ParsedAttr.Architecture))
1757*0b57cec5SDimitry Andric         TargetCPU = ParsedAttr.Architecture;
1758*0b57cec5SDimitry Andric     }
1759*0b57cec5SDimitry Andric   } else {
1760*0b57cec5SDimitry Andric     // Otherwise just add the existing target cpu and target features to the
1761*0b57cec5SDimitry Andric     // function.
1762*0b57cec5SDimitry Andric     Features = getTarget().getTargetOpts().Features;
1763*0b57cec5SDimitry Andric   }
1764*0b57cec5SDimitry Andric 
1765*0b57cec5SDimitry Andric   if (TargetCPU != "") {
1766*0b57cec5SDimitry Andric     Attrs.addAttribute("target-cpu", TargetCPU);
1767*0b57cec5SDimitry Andric     AddedAttr = true;
1768*0b57cec5SDimitry Andric   }
1769*0b57cec5SDimitry Andric   if (!Features.empty()) {
1770*0b57cec5SDimitry Andric     llvm::sort(Features);
1771*0b57cec5SDimitry Andric     Attrs.addAttribute("target-features", llvm::join(Features, ","));
1772*0b57cec5SDimitry Andric     AddedAttr = true;
1773*0b57cec5SDimitry Andric   }
1774*0b57cec5SDimitry Andric 
1775*0b57cec5SDimitry Andric   return AddedAttr;
1776*0b57cec5SDimitry Andric }
1777*0b57cec5SDimitry Andric 
1778*0b57cec5SDimitry Andric void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
1779*0b57cec5SDimitry Andric                                           llvm::GlobalObject *GO) {
1780*0b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
1781*0b57cec5SDimitry Andric   SetCommonAttributes(GD, GO);
1782*0b57cec5SDimitry Andric 
1783*0b57cec5SDimitry Andric   if (D) {
1784*0b57cec5SDimitry Andric     if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
1785*0b57cec5SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
1786*0b57cec5SDimitry Andric         GV->addAttribute("bss-section", SA->getName());
1787*0b57cec5SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
1788*0b57cec5SDimitry Andric         GV->addAttribute("data-section", SA->getName());
1789*0b57cec5SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
1790*0b57cec5SDimitry Andric         GV->addAttribute("rodata-section", SA->getName());
1791a7dea167SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>())
1792a7dea167SDimitry Andric         GV->addAttribute("relro-section", SA->getName());
1793*0b57cec5SDimitry Andric     }
1794*0b57cec5SDimitry Andric 
1795*0b57cec5SDimitry Andric     if (auto *F = dyn_cast<llvm::Function>(GO)) {
1796*0b57cec5SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
1797*0b57cec5SDimitry Andric         if (!D->getAttr<SectionAttr>())
1798*0b57cec5SDimitry Andric           F->addFnAttr("implicit-section-name", SA->getName());
1799*0b57cec5SDimitry Andric 
1800*0b57cec5SDimitry Andric       llvm::AttrBuilder Attrs;
1801*0b57cec5SDimitry Andric       if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
1802*0b57cec5SDimitry Andric         // We know that GetCPUAndFeaturesAttributes will always have the
1803*0b57cec5SDimitry Andric         // newest set, since it has the newest possible FunctionDecl, so the
1804*0b57cec5SDimitry Andric         // new ones should replace the old.
1805*0b57cec5SDimitry Andric         F->removeFnAttr("target-cpu");
1806*0b57cec5SDimitry Andric         F->removeFnAttr("target-features");
1807*0b57cec5SDimitry Andric         F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
1808*0b57cec5SDimitry Andric       }
1809*0b57cec5SDimitry Andric     }
1810*0b57cec5SDimitry Andric 
1811*0b57cec5SDimitry Andric     if (const auto *CSA = D->getAttr<CodeSegAttr>())
1812*0b57cec5SDimitry Andric       GO->setSection(CSA->getName());
1813*0b57cec5SDimitry Andric     else if (const auto *SA = D->getAttr<SectionAttr>())
1814*0b57cec5SDimitry Andric       GO->setSection(SA->getName());
1815*0b57cec5SDimitry Andric   }
1816*0b57cec5SDimitry Andric 
1817*0b57cec5SDimitry Andric   getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
1818*0b57cec5SDimitry Andric }
1819*0b57cec5SDimitry Andric 
1820*0b57cec5SDimitry Andric void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
1821*0b57cec5SDimitry Andric                                                   llvm::Function *F,
1822*0b57cec5SDimitry Andric                                                   const CGFunctionInfo &FI) {
1823*0b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
1824*0b57cec5SDimitry Andric   SetLLVMFunctionAttributes(GD, FI, F);
1825*0b57cec5SDimitry Andric   SetLLVMFunctionAttributesForDefinition(D, F);
1826*0b57cec5SDimitry Andric 
1827*0b57cec5SDimitry Andric   F->setLinkage(llvm::Function::InternalLinkage);
1828*0b57cec5SDimitry Andric 
1829*0b57cec5SDimitry Andric   setNonAliasAttributes(GD, F);
1830*0b57cec5SDimitry Andric }
1831*0b57cec5SDimitry Andric 
1832*0b57cec5SDimitry Andric static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
1833*0b57cec5SDimitry Andric   // Set linkage and visibility in case we never see a definition.
1834*0b57cec5SDimitry Andric   LinkageInfo LV = ND->getLinkageAndVisibility();
1835*0b57cec5SDimitry Andric   // Don't set internal linkage on declarations.
1836*0b57cec5SDimitry Andric   // "extern_weak" is overloaded in LLVM; we probably should have
1837*0b57cec5SDimitry Andric   // separate linkage types for this.
1838*0b57cec5SDimitry Andric   if (isExternallyVisible(LV.getLinkage()) &&
1839*0b57cec5SDimitry Andric       (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
1840*0b57cec5SDimitry Andric     GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1841*0b57cec5SDimitry Andric }
1842*0b57cec5SDimitry Andric 
1843*0b57cec5SDimitry Andric void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
1844*0b57cec5SDimitry Andric                                                        llvm::Function *F) {
1845*0b57cec5SDimitry Andric   // Only if we are checking indirect calls.
1846*0b57cec5SDimitry Andric   if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
1847*0b57cec5SDimitry Andric     return;
1848*0b57cec5SDimitry Andric 
1849*0b57cec5SDimitry Andric   // Non-static class methods are handled via vtable or member function pointer
1850*0b57cec5SDimitry Andric   // checks elsewhere.
1851*0b57cec5SDimitry Andric   if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1852*0b57cec5SDimitry Andric     return;
1853*0b57cec5SDimitry Andric 
1854*0b57cec5SDimitry Andric   llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
1855*0b57cec5SDimitry Andric   F->addTypeMetadata(0, MD);
1856*0b57cec5SDimitry Andric   F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
1857*0b57cec5SDimitry Andric 
1858*0b57cec5SDimitry Andric   // Emit a hash-based bit set entry for cross-DSO calls.
1859*0b57cec5SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
1860*0b57cec5SDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1861*0b57cec5SDimitry Andric       F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
1862*0b57cec5SDimitry Andric }
1863*0b57cec5SDimitry Andric 
1864*0b57cec5SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1865*0b57cec5SDimitry Andric                                           bool IsIncompleteFunction,
1866*0b57cec5SDimitry Andric                                           bool IsThunk) {
1867*0b57cec5SDimitry Andric 
1868*0b57cec5SDimitry Andric   if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
1869*0b57cec5SDimitry Andric     // If this is an intrinsic function, set the function's attributes
1870*0b57cec5SDimitry Andric     // to the intrinsic's attributes.
1871*0b57cec5SDimitry Andric     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
1872*0b57cec5SDimitry Andric     return;
1873*0b57cec5SDimitry Andric   }
1874*0b57cec5SDimitry Andric 
1875*0b57cec5SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
1876*0b57cec5SDimitry Andric 
1877*0b57cec5SDimitry Andric   if (!IsIncompleteFunction)
1878*0b57cec5SDimitry Andric     SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F);
1879*0b57cec5SDimitry Andric 
1880*0b57cec5SDimitry Andric   // Add the Returned attribute for "this", except for iOS 5 and earlier
1881*0b57cec5SDimitry Andric   // where substantial code, including the libstdc++ dylib, was compiled with
1882*0b57cec5SDimitry Andric   // GCC and does not actually return "this".
1883*0b57cec5SDimitry Andric   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
1884*0b57cec5SDimitry Andric       !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
1885*0b57cec5SDimitry Andric     assert(!F->arg_empty() &&
1886*0b57cec5SDimitry Andric            F->arg_begin()->getType()
1887*0b57cec5SDimitry Andric              ->canLosslesslyBitCastTo(F->getReturnType()) &&
1888*0b57cec5SDimitry Andric            "unexpected this return");
1889*0b57cec5SDimitry Andric     F->addAttribute(1, llvm::Attribute::Returned);
1890*0b57cec5SDimitry Andric   }
1891*0b57cec5SDimitry Andric 
1892*0b57cec5SDimitry Andric   // Only a few attributes are set on declarations; these may later be
1893*0b57cec5SDimitry Andric   // overridden by a definition.
1894*0b57cec5SDimitry Andric 
1895*0b57cec5SDimitry Andric   setLinkageForGV(F, FD);
1896*0b57cec5SDimitry Andric   setGVProperties(F, FD);
1897*0b57cec5SDimitry Andric 
1898*0b57cec5SDimitry Andric   // Setup target-specific attributes.
1899*0b57cec5SDimitry Andric   if (!IsIncompleteFunction && F->isDeclaration())
1900*0b57cec5SDimitry Andric     getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
1901*0b57cec5SDimitry Andric 
1902*0b57cec5SDimitry Andric   if (const auto *CSA = FD->getAttr<CodeSegAttr>())
1903*0b57cec5SDimitry Andric     F->setSection(CSA->getName());
1904*0b57cec5SDimitry Andric   else if (const auto *SA = FD->getAttr<SectionAttr>())
1905*0b57cec5SDimitry Andric      F->setSection(SA->getName());
1906*0b57cec5SDimitry Andric 
1907d65cd7a5SDimitry Andric   // If we plan on emitting this inline builtin, we can't treat it as a builtin.
1908480093f4SDimitry Andric   if (FD->isInlineBuiltinDeclaration()) {
1909d65cd7a5SDimitry Andric     const FunctionDecl *FDBody;
1910d65cd7a5SDimitry Andric     bool HasBody = FD->hasBody(FDBody);
1911d65cd7a5SDimitry Andric     (void)HasBody;
1912d65cd7a5SDimitry Andric     assert(HasBody && "Inline builtin declarations should always have an "
1913d65cd7a5SDimitry Andric                       "available body!");
1914d65cd7a5SDimitry Andric     if (shouldEmitFunction(FDBody))
1915480093f4SDimitry Andric       F->addAttribute(llvm::AttributeList::FunctionIndex,
1916480093f4SDimitry Andric                       llvm::Attribute::NoBuiltin);
1917480093f4SDimitry Andric   }
1918480093f4SDimitry Andric 
1919*0b57cec5SDimitry Andric   if (FD->isReplaceableGlobalAllocationFunction()) {
1920*0b57cec5SDimitry Andric     // A replaceable global allocation function does not act like a builtin by
1921*0b57cec5SDimitry Andric     // default, only if it is invoked by a new-expression or delete-expression.
1922*0b57cec5SDimitry Andric     F->addAttribute(llvm::AttributeList::FunctionIndex,
1923*0b57cec5SDimitry Andric                     llvm::Attribute::NoBuiltin);
1924*0b57cec5SDimitry Andric   }
1925*0b57cec5SDimitry Andric 
1926*0b57cec5SDimitry Andric   if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1927*0b57cec5SDimitry Andric     F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1928*0b57cec5SDimitry Andric   else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1929*0b57cec5SDimitry Andric     if (MD->isVirtual())
1930*0b57cec5SDimitry Andric       F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1931*0b57cec5SDimitry Andric 
1932*0b57cec5SDimitry Andric   // Don't emit entries for function declarations in the cross-DSO mode. This
1933a7dea167SDimitry Andric   // is handled with better precision by the receiving DSO. But if jump tables
1934a7dea167SDimitry Andric   // are non-canonical then we need type metadata in order to produce the local
1935a7dea167SDimitry Andric   // jump table.
1936a7dea167SDimitry Andric   if (!CodeGenOpts.SanitizeCfiCrossDso ||
1937a7dea167SDimitry Andric       !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
1938*0b57cec5SDimitry Andric     CreateFunctionTypeMetadataForIcall(FD, F);
1939*0b57cec5SDimitry Andric 
1940*0b57cec5SDimitry Andric   if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
1941*0b57cec5SDimitry Andric     getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
1942*0b57cec5SDimitry Andric 
1943*0b57cec5SDimitry Andric   if (const auto *CB = FD->getAttr<CallbackAttr>()) {
1944*0b57cec5SDimitry Andric     // Annotate the callback behavior as metadata:
1945*0b57cec5SDimitry Andric     //  - The callback callee (as argument number).
1946*0b57cec5SDimitry Andric     //  - The callback payloads (as argument numbers).
1947*0b57cec5SDimitry Andric     llvm::LLVMContext &Ctx = F->getContext();
1948*0b57cec5SDimitry Andric     llvm::MDBuilder MDB(Ctx);
1949*0b57cec5SDimitry Andric 
1950*0b57cec5SDimitry Andric     // The payload indices are all but the first one in the encoding. The first
1951*0b57cec5SDimitry Andric     // identifies the callback callee.
1952*0b57cec5SDimitry Andric     int CalleeIdx = *CB->encoding_begin();
1953*0b57cec5SDimitry Andric     ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
1954*0b57cec5SDimitry Andric     F->addMetadata(llvm::LLVMContext::MD_callback,
1955*0b57cec5SDimitry Andric                    *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
1956*0b57cec5SDimitry Andric                                                CalleeIdx, PayloadIndices,
1957*0b57cec5SDimitry Andric                                                /* VarArgsArePassed */ false)}));
1958*0b57cec5SDimitry Andric   }
1959*0b57cec5SDimitry Andric }
1960*0b57cec5SDimitry Andric 
1961*0b57cec5SDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
1962*0b57cec5SDimitry Andric   assert(!GV->isDeclaration() &&
1963*0b57cec5SDimitry Andric          "Only globals with definition can force usage.");
1964*0b57cec5SDimitry Andric   LLVMUsed.emplace_back(GV);
1965*0b57cec5SDimitry Andric }
1966*0b57cec5SDimitry Andric 
1967*0b57cec5SDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
1968*0b57cec5SDimitry Andric   assert(!GV->isDeclaration() &&
1969*0b57cec5SDimitry Andric          "Only globals with definition can force usage.");
1970*0b57cec5SDimitry Andric   LLVMCompilerUsed.emplace_back(GV);
1971*0b57cec5SDimitry Andric }
1972*0b57cec5SDimitry Andric 
1973*0b57cec5SDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name,
1974*0b57cec5SDimitry Andric                      std::vector<llvm::WeakTrackingVH> &List) {
1975*0b57cec5SDimitry Andric   // Don't create llvm.used if there is no need.
1976*0b57cec5SDimitry Andric   if (List.empty())
1977*0b57cec5SDimitry Andric     return;
1978*0b57cec5SDimitry Andric 
1979*0b57cec5SDimitry Andric   // Convert List to what ConstantArray needs.
1980*0b57cec5SDimitry Andric   SmallVector<llvm::Constant*, 8> UsedArray;
1981*0b57cec5SDimitry Andric   UsedArray.resize(List.size());
1982*0b57cec5SDimitry Andric   for (unsigned i = 0, e = List.size(); i != e; ++i) {
1983*0b57cec5SDimitry Andric     UsedArray[i] =
1984*0b57cec5SDimitry Andric         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1985*0b57cec5SDimitry Andric             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
1986*0b57cec5SDimitry Andric   }
1987*0b57cec5SDimitry Andric 
1988*0b57cec5SDimitry Andric   if (UsedArray.empty())
1989*0b57cec5SDimitry Andric     return;
1990*0b57cec5SDimitry Andric   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
1991*0b57cec5SDimitry Andric 
1992*0b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
1993*0b57cec5SDimitry Andric       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
1994*0b57cec5SDimitry Andric       llvm::ConstantArray::get(ATy, UsedArray), Name);
1995*0b57cec5SDimitry Andric 
1996*0b57cec5SDimitry Andric   GV->setSection("llvm.metadata");
1997*0b57cec5SDimitry Andric }
1998*0b57cec5SDimitry Andric 
1999*0b57cec5SDimitry Andric void CodeGenModule::emitLLVMUsed() {
2000*0b57cec5SDimitry Andric   emitUsed(*this, "llvm.used", LLVMUsed);
2001*0b57cec5SDimitry Andric   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
2002*0b57cec5SDimitry Andric }
2003*0b57cec5SDimitry Andric 
2004*0b57cec5SDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
2005*0b57cec5SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
2006*0b57cec5SDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
2007*0b57cec5SDimitry Andric }
2008*0b57cec5SDimitry Andric 
2009*0b57cec5SDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
2010*0b57cec5SDimitry Andric   llvm::SmallString<32> Opt;
2011*0b57cec5SDimitry Andric   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
2012480093f4SDimitry Andric   if (Opt.empty())
2013480093f4SDimitry Andric     return;
2014*0b57cec5SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
2015*0b57cec5SDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
2016*0b57cec5SDimitry Andric }
2017*0b57cec5SDimitry Andric 
2018*0b57cec5SDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) {
2019*0b57cec5SDimitry Andric   auto &C = getLLVMContext();
2020*0b57cec5SDimitry Andric   if (getTarget().getTriple().isOSBinFormatELF()) {
2021*0b57cec5SDimitry Andric       ELFDependentLibraries.push_back(
2022*0b57cec5SDimitry Andric         llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
2023*0b57cec5SDimitry Andric     return;
2024*0b57cec5SDimitry Andric   }
2025*0b57cec5SDimitry Andric 
2026*0b57cec5SDimitry Andric   llvm::SmallString<24> Opt;
2027*0b57cec5SDimitry Andric   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
2028*0b57cec5SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
2029*0b57cec5SDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
2030*0b57cec5SDimitry Andric }
2031*0b57cec5SDimitry Andric 
2032*0b57cec5SDimitry Andric /// Add link options implied by the given module, including modules
2033*0b57cec5SDimitry Andric /// it depends on, using a postorder walk.
2034*0b57cec5SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
2035*0b57cec5SDimitry Andric                                     SmallVectorImpl<llvm::MDNode *> &Metadata,
2036*0b57cec5SDimitry Andric                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
2037*0b57cec5SDimitry Andric   // Import this module's parent.
2038*0b57cec5SDimitry Andric   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
2039*0b57cec5SDimitry Andric     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
2040*0b57cec5SDimitry Andric   }
2041*0b57cec5SDimitry Andric 
2042*0b57cec5SDimitry Andric   // Import this module's dependencies.
2043*0b57cec5SDimitry Andric   for (unsigned I = Mod->Imports.size(); I > 0; --I) {
2044*0b57cec5SDimitry Andric     if (Visited.insert(Mod->Imports[I - 1]).second)
2045*0b57cec5SDimitry Andric       addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
2046*0b57cec5SDimitry Andric   }
2047*0b57cec5SDimitry Andric 
2048*0b57cec5SDimitry Andric   // Add linker options to link against the libraries/frameworks
2049*0b57cec5SDimitry Andric   // described by this module.
2050*0b57cec5SDimitry Andric   llvm::LLVMContext &Context = CGM.getLLVMContext();
2051*0b57cec5SDimitry Andric   bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
2052*0b57cec5SDimitry Andric 
2053*0b57cec5SDimitry Andric   // For modules that use export_as for linking, use that module
2054*0b57cec5SDimitry Andric   // name instead.
2055*0b57cec5SDimitry Andric   if (Mod->UseExportAsModuleLinkName)
2056*0b57cec5SDimitry Andric     return;
2057*0b57cec5SDimitry Andric 
2058*0b57cec5SDimitry Andric   for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
2059*0b57cec5SDimitry Andric     // Link against a framework.  Frameworks are currently Darwin only, so we
2060*0b57cec5SDimitry Andric     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
2061*0b57cec5SDimitry Andric     if (Mod->LinkLibraries[I-1].IsFramework) {
2062*0b57cec5SDimitry Andric       llvm::Metadata *Args[2] = {
2063*0b57cec5SDimitry Andric           llvm::MDString::get(Context, "-framework"),
2064*0b57cec5SDimitry Andric           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
2065*0b57cec5SDimitry Andric 
2066*0b57cec5SDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, Args));
2067*0b57cec5SDimitry Andric       continue;
2068*0b57cec5SDimitry Andric     }
2069*0b57cec5SDimitry Andric 
2070*0b57cec5SDimitry Andric     // Link against a library.
2071*0b57cec5SDimitry Andric     if (IsELF) {
2072*0b57cec5SDimitry Andric       llvm::Metadata *Args[2] = {
2073*0b57cec5SDimitry Andric           llvm::MDString::get(Context, "lib"),
2074*0b57cec5SDimitry Andric           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library),
2075*0b57cec5SDimitry Andric       };
2076*0b57cec5SDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, Args));
2077*0b57cec5SDimitry Andric     } else {
2078*0b57cec5SDimitry Andric       llvm::SmallString<24> Opt;
2079*0b57cec5SDimitry Andric       CGM.getTargetCodeGenInfo().getDependentLibraryOption(
2080*0b57cec5SDimitry Andric           Mod->LinkLibraries[I - 1].Library, Opt);
2081*0b57cec5SDimitry Andric       auto *OptString = llvm::MDString::get(Context, Opt);
2082*0b57cec5SDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, OptString));
2083*0b57cec5SDimitry Andric     }
2084*0b57cec5SDimitry Andric   }
2085*0b57cec5SDimitry Andric }
2086*0b57cec5SDimitry Andric 
2087*0b57cec5SDimitry Andric void CodeGenModule::EmitModuleLinkOptions() {
2088*0b57cec5SDimitry Andric   // Collect the set of all of the modules we want to visit to emit link
2089*0b57cec5SDimitry Andric   // options, which is essentially the imported modules and all of their
2090*0b57cec5SDimitry Andric   // non-explicit child modules.
2091*0b57cec5SDimitry Andric   llvm::SetVector<clang::Module *> LinkModules;
2092*0b57cec5SDimitry Andric   llvm::SmallPtrSet<clang::Module *, 16> Visited;
2093*0b57cec5SDimitry Andric   SmallVector<clang::Module *, 16> Stack;
2094*0b57cec5SDimitry Andric 
2095*0b57cec5SDimitry Andric   // Seed the stack with imported modules.
2096*0b57cec5SDimitry Andric   for (Module *M : ImportedModules) {
2097*0b57cec5SDimitry Andric     // Do not add any link flags when an implementation TU of a module imports
2098*0b57cec5SDimitry Andric     // a header of that same module.
2099*0b57cec5SDimitry Andric     if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
2100*0b57cec5SDimitry Andric         !getLangOpts().isCompilingModule())
2101*0b57cec5SDimitry Andric       continue;
2102*0b57cec5SDimitry Andric     if (Visited.insert(M).second)
2103*0b57cec5SDimitry Andric       Stack.push_back(M);
2104*0b57cec5SDimitry Andric   }
2105*0b57cec5SDimitry Andric 
2106*0b57cec5SDimitry Andric   // Find all of the modules to import, making a little effort to prune
2107*0b57cec5SDimitry Andric   // non-leaf modules.
2108*0b57cec5SDimitry Andric   while (!Stack.empty()) {
2109*0b57cec5SDimitry Andric     clang::Module *Mod = Stack.pop_back_val();
2110*0b57cec5SDimitry Andric 
2111*0b57cec5SDimitry Andric     bool AnyChildren = false;
2112*0b57cec5SDimitry Andric 
2113*0b57cec5SDimitry Andric     // Visit the submodules of this module.
2114*0b57cec5SDimitry Andric     for (const auto &SM : Mod->submodules()) {
2115*0b57cec5SDimitry Andric       // Skip explicit children; they need to be explicitly imported to be
2116*0b57cec5SDimitry Andric       // linked against.
2117*0b57cec5SDimitry Andric       if (SM->IsExplicit)
2118*0b57cec5SDimitry Andric         continue;
2119*0b57cec5SDimitry Andric 
2120*0b57cec5SDimitry Andric       if (Visited.insert(SM).second) {
2121*0b57cec5SDimitry Andric         Stack.push_back(SM);
2122*0b57cec5SDimitry Andric         AnyChildren = true;
2123*0b57cec5SDimitry Andric       }
2124*0b57cec5SDimitry Andric     }
2125*0b57cec5SDimitry Andric 
2126*0b57cec5SDimitry Andric     // We didn't find any children, so add this module to the list of
2127*0b57cec5SDimitry Andric     // modules to link against.
2128*0b57cec5SDimitry Andric     if (!AnyChildren) {
2129*0b57cec5SDimitry Andric       LinkModules.insert(Mod);
2130*0b57cec5SDimitry Andric     }
2131*0b57cec5SDimitry Andric   }
2132*0b57cec5SDimitry Andric 
2133*0b57cec5SDimitry Andric   // Add link options for all of the imported modules in reverse topological
2134*0b57cec5SDimitry Andric   // order.  We don't do anything to try to order import link flags with respect
2135*0b57cec5SDimitry Andric   // to linker options inserted by things like #pragma comment().
2136*0b57cec5SDimitry Andric   SmallVector<llvm::MDNode *, 16> MetadataArgs;
2137*0b57cec5SDimitry Andric   Visited.clear();
2138*0b57cec5SDimitry Andric   for (Module *M : LinkModules)
2139*0b57cec5SDimitry Andric     if (Visited.insert(M).second)
2140*0b57cec5SDimitry Andric       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
2141*0b57cec5SDimitry Andric   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
2142*0b57cec5SDimitry Andric   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
2143*0b57cec5SDimitry Andric 
2144*0b57cec5SDimitry Andric   // Add the linker options metadata flag.
2145*0b57cec5SDimitry Andric   auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
2146*0b57cec5SDimitry Andric   for (auto *MD : LinkerOptionsMetadata)
2147*0b57cec5SDimitry Andric     NMD->addOperand(MD);
2148*0b57cec5SDimitry Andric }
2149*0b57cec5SDimitry Andric 
2150*0b57cec5SDimitry Andric void CodeGenModule::EmitDeferred() {
2151*0b57cec5SDimitry Andric   // Emit deferred declare target declarations.
2152*0b57cec5SDimitry Andric   if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
2153*0b57cec5SDimitry Andric     getOpenMPRuntime().emitDeferredTargetDecls();
2154*0b57cec5SDimitry Andric 
2155*0b57cec5SDimitry Andric   // Emit code for any potentially referenced deferred decls.  Since a
2156*0b57cec5SDimitry Andric   // previously unused static decl may become used during the generation of code
2157*0b57cec5SDimitry Andric   // for a static function, iterate until no changes are made.
2158*0b57cec5SDimitry Andric 
2159*0b57cec5SDimitry Andric   if (!DeferredVTables.empty()) {
2160*0b57cec5SDimitry Andric     EmitDeferredVTables();
2161*0b57cec5SDimitry Andric 
2162*0b57cec5SDimitry Andric     // Emitting a vtable doesn't directly cause more vtables to
2163*0b57cec5SDimitry Andric     // become deferred, although it can cause functions to be
2164*0b57cec5SDimitry Andric     // emitted that then need those vtables.
2165*0b57cec5SDimitry Andric     assert(DeferredVTables.empty());
2166*0b57cec5SDimitry Andric   }
2167*0b57cec5SDimitry Andric 
2168*0b57cec5SDimitry Andric   // Stop if we're out of both deferred vtables and deferred declarations.
2169*0b57cec5SDimitry Andric   if (DeferredDeclsToEmit.empty())
2170*0b57cec5SDimitry Andric     return;
2171*0b57cec5SDimitry Andric 
2172*0b57cec5SDimitry Andric   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
2173*0b57cec5SDimitry Andric   // work, it will not interfere with this.
2174*0b57cec5SDimitry Andric   std::vector<GlobalDecl> CurDeclsToEmit;
2175*0b57cec5SDimitry Andric   CurDeclsToEmit.swap(DeferredDeclsToEmit);
2176*0b57cec5SDimitry Andric 
2177*0b57cec5SDimitry Andric   for (GlobalDecl &D : CurDeclsToEmit) {
2178*0b57cec5SDimitry Andric     // We should call GetAddrOfGlobal with IsForDefinition set to true in order
2179*0b57cec5SDimitry Andric     // to get GlobalValue with exactly the type we need, not something that
2180*0b57cec5SDimitry Andric     // might had been created for another decl with the same mangled name but
2181*0b57cec5SDimitry Andric     // different type.
2182*0b57cec5SDimitry Andric     llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
2183*0b57cec5SDimitry Andric         GetAddrOfGlobal(D, ForDefinition));
2184*0b57cec5SDimitry Andric 
2185*0b57cec5SDimitry Andric     // In case of different address spaces, we may still get a cast, even with
2186*0b57cec5SDimitry Andric     // IsForDefinition equal to true. Query mangled names table to get
2187*0b57cec5SDimitry Andric     // GlobalValue.
2188*0b57cec5SDimitry Andric     if (!GV)
2189*0b57cec5SDimitry Andric       GV = GetGlobalValue(getMangledName(D));
2190*0b57cec5SDimitry Andric 
2191*0b57cec5SDimitry Andric     // Make sure GetGlobalValue returned non-null.
2192*0b57cec5SDimitry Andric     assert(GV);
2193*0b57cec5SDimitry Andric 
2194*0b57cec5SDimitry Andric     // Check to see if we've already emitted this.  This is necessary
2195*0b57cec5SDimitry Andric     // for a couple of reasons: first, decls can end up in the
2196*0b57cec5SDimitry Andric     // deferred-decls queue multiple times, and second, decls can end
2197*0b57cec5SDimitry Andric     // up with definitions in unusual ways (e.g. by an extern inline
2198*0b57cec5SDimitry Andric     // function acquiring a strong function redefinition).  Just
2199*0b57cec5SDimitry Andric     // ignore these cases.
2200*0b57cec5SDimitry Andric     if (!GV->isDeclaration())
2201*0b57cec5SDimitry Andric       continue;
2202*0b57cec5SDimitry Andric 
2203a7dea167SDimitry Andric     // If this is OpenMP, check if it is legal to emit this global normally.
2204a7dea167SDimitry Andric     if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
2205a7dea167SDimitry Andric       continue;
2206a7dea167SDimitry Andric 
2207*0b57cec5SDimitry Andric     // Otherwise, emit the definition and move on to the next one.
2208*0b57cec5SDimitry Andric     EmitGlobalDefinition(D, GV);
2209*0b57cec5SDimitry Andric 
2210*0b57cec5SDimitry Andric     // If we found out that we need to emit more decls, do that recursively.
2211*0b57cec5SDimitry Andric     // This has the advantage that the decls are emitted in a DFS and related
2212*0b57cec5SDimitry Andric     // ones are close together, which is convenient for testing.
2213*0b57cec5SDimitry Andric     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
2214*0b57cec5SDimitry Andric       EmitDeferred();
2215*0b57cec5SDimitry Andric       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
2216*0b57cec5SDimitry Andric     }
2217*0b57cec5SDimitry Andric   }
2218*0b57cec5SDimitry Andric }
2219*0b57cec5SDimitry Andric 
2220*0b57cec5SDimitry Andric void CodeGenModule::EmitVTablesOpportunistically() {
2221*0b57cec5SDimitry Andric   // Try to emit external vtables as available_externally if they have emitted
2222*0b57cec5SDimitry Andric   // all inlined virtual functions.  It runs after EmitDeferred() and therefore
2223*0b57cec5SDimitry Andric   // is not allowed to create new references to things that need to be emitted
2224*0b57cec5SDimitry Andric   // lazily. Note that it also uses fact that we eagerly emitting RTTI.
2225*0b57cec5SDimitry Andric 
2226*0b57cec5SDimitry Andric   assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
2227*0b57cec5SDimitry Andric          && "Only emit opportunistic vtables with optimizations");
2228*0b57cec5SDimitry Andric 
2229*0b57cec5SDimitry Andric   for (const CXXRecordDecl *RD : OpportunisticVTables) {
2230*0b57cec5SDimitry Andric     assert(getVTables().isVTableExternal(RD) &&
2231*0b57cec5SDimitry Andric            "This queue should only contain external vtables");
2232*0b57cec5SDimitry Andric     if (getCXXABI().canSpeculativelyEmitVTable(RD))
2233*0b57cec5SDimitry Andric       VTables.GenerateClassData(RD);
2234*0b57cec5SDimitry Andric   }
2235*0b57cec5SDimitry Andric   OpportunisticVTables.clear();
2236*0b57cec5SDimitry Andric }
2237*0b57cec5SDimitry Andric 
2238*0b57cec5SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() {
2239*0b57cec5SDimitry Andric   if (Annotations.empty())
2240*0b57cec5SDimitry Andric     return;
2241*0b57cec5SDimitry Andric 
2242*0b57cec5SDimitry Andric   // Create a new global variable for the ConstantStruct in the Module.
2243*0b57cec5SDimitry Andric   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
2244*0b57cec5SDimitry Andric     Annotations[0]->getType(), Annotations.size()), Annotations);
2245*0b57cec5SDimitry Andric   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
2246*0b57cec5SDimitry Andric                                       llvm::GlobalValue::AppendingLinkage,
2247*0b57cec5SDimitry Andric                                       Array, "llvm.global.annotations");
2248*0b57cec5SDimitry Andric   gv->setSection(AnnotationSection);
2249*0b57cec5SDimitry Andric }
2250*0b57cec5SDimitry Andric 
2251*0b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
2252*0b57cec5SDimitry Andric   llvm::Constant *&AStr = AnnotationStrings[Str];
2253*0b57cec5SDimitry Andric   if (AStr)
2254*0b57cec5SDimitry Andric     return AStr;
2255*0b57cec5SDimitry Andric 
2256*0b57cec5SDimitry Andric   // Not found yet, create a new global.
2257*0b57cec5SDimitry Andric   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
2258*0b57cec5SDimitry Andric   auto *gv =
2259*0b57cec5SDimitry Andric       new llvm::GlobalVariable(getModule(), s->getType(), true,
2260*0b57cec5SDimitry Andric                                llvm::GlobalValue::PrivateLinkage, s, ".str");
2261*0b57cec5SDimitry Andric   gv->setSection(AnnotationSection);
2262*0b57cec5SDimitry Andric   gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2263*0b57cec5SDimitry Andric   AStr = gv;
2264*0b57cec5SDimitry Andric   return gv;
2265*0b57cec5SDimitry Andric }
2266*0b57cec5SDimitry Andric 
2267*0b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
2268*0b57cec5SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
2269*0b57cec5SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2270*0b57cec5SDimitry Andric   if (PLoc.isValid())
2271*0b57cec5SDimitry Andric     return EmitAnnotationString(PLoc.getFilename());
2272*0b57cec5SDimitry Andric   return EmitAnnotationString(SM.getBufferName(Loc));
2273*0b57cec5SDimitry Andric }
2274*0b57cec5SDimitry Andric 
2275*0b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
2276*0b57cec5SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
2277*0b57cec5SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(L);
2278*0b57cec5SDimitry Andric   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
2279*0b57cec5SDimitry Andric     SM.getExpansionLineNumber(L);
2280*0b57cec5SDimitry Andric   return llvm::ConstantInt::get(Int32Ty, LineNo);
2281*0b57cec5SDimitry Andric }
2282*0b57cec5SDimitry Andric 
2283*0b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
2284*0b57cec5SDimitry Andric                                                 const AnnotateAttr *AA,
2285*0b57cec5SDimitry Andric                                                 SourceLocation L) {
2286*0b57cec5SDimitry Andric   // Get the globals for file name, annotation, and the line number.
2287*0b57cec5SDimitry Andric   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
2288*0b57cec5SDimitry Andric                  *UnitGV = EmitAnnotationUnit(L),
2289*0b57cec5SDimitry Andric                  *LineNoCst = EmitAnnotationLineNo(L);
2290*0b57cec5SDimitry Andric 
2291480093f4SDimitry Andric   llvm::Constant *ASZeroGV = GV;
2292480093f4SDimitry Andric   if (GV->getAddressSpace() != 0) {
2293480093f4SDimitry Andric     ASZeroGV = llvm::ConstantExpr::getAddrSpaceCast(
2294480093f4SDimitry Andric                    GV, GV->getValueType()->getPointerTo(0));
2295480093f4SDimitry Andric   }
2296480093f4SDimitry Andric 
2297*0b57cec5SDimitry Andric   // Create the ConstantStruct for the global annotation.
2298*0b57cec5SDimitry Andric   llvm::Constant *Fields[4] = {
2299480093f4SDimitry Andric     llvm::ConstantExpr::getBitCast(ASZeroGV, Int8PtrTy),
2300*0b57cec5SDimitry Andric     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
2301*0b57cec5SDimitry Andric     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
2302*0b57cec5SDimitry Andric     LineNoCst
2303*0b57cec5SDimitry Andric   };
2304*0b57cec5SDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
2305*0b57cec5SDimitry Andric }
2306*0b57cec5SDimitry Andric 
2307*0b57cec5SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
2308*0b57cec5SDimitry Andric                                          llvm::GlobalValue *GV) {
2309*0b57cec5SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2310*0b57cec5SDimitry Andric   // Get the struct elements for these annotations.
2311*0b57cec5SDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>())
2312*0b57cec5SDimitry Andric     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
2313*0b57cec5SDimitry Andric }
2314*0b57cec5SDimitry Andric 
2315*0b57cec5SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind,
2316*0b57cec5SDimitry Andric                                            llvm::Function *Fn,
2317*0b57cec5SDimitry Andric                                            SourceLocation Loc) const {
2318*0b57cec5SDimitry Andric   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
2319*0b57cec5SDimitry Andric   // Blacklist by function name.
2320*0b57cec5SDimitry Andric   if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
2321*0b57cec5SDimitry Andric     return true;
2322*0b57cec5SDimitry Andric   // Blacklist by location.
2323*0b57cec5SDimitry Andric   if (Loc.isValid())
2324*0b57cec5SDimitry Andric     return SanitizerBL.isBlacklistedLocation(Kind, Loc);
2325*0b57cec5SDimitry Andric   // If location is unknown, this may be a compiler-generated function. Assume
2326*0b57cec5SDimitry Andric   // it's located in the main file.
2327*0b57cec5SDimitry Andric   auto &SM = Context.getSourceManager();
2328*0b57cec5SDimitry Andric   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
2329*0b57cec5SDimitry Andric     return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
2330*0b57cec5SDimitry Andric   }
2331*0b57cec5SDimitry Andric   return false;
2332*0b57cec5SDimitry Andric }
2333*0b57cec5SDimitry Andric 
2334*0b57cec5SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
2335*0b57cec5SDimitry Andric                                            SourceLocation Loc, QualType Ty,
2336*0b57cec5SDimitry Andric                                            StringRef Category) const {
2337*0b57cec5SDimitry Andric   // For now globals can be blacklisted only in ASan and KASan.
2338*0b57cec5SDimitry Andric   const SanitizerMask EnabledAsanMask =
2339*0b57cec5SDimitry Andric       LangOpts.Sanitize.Mask &
2340*0b57cec5SDimitry Andric       (SanitizerKind::Address | SanitizerKind::KernelAddress |
2341*0b57cec5SDimitry Andric        SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress |
2342*0b57cec5SDimitry Andric        SanitizerKind::MemTag);
2343*0b57cec5SDimitry Andric   if (!EnabledAsanMask)
2344*0b57cec5SDimitry Andric     return false;
2345*0b57cec5SDimitry Andric   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
2346*0b57cec5SDimitry Andric   if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
2347*0b57cec5SDimitry Andric     return true;
2348*0b57cec5SDimitry Andric   if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
2349*0b57cec5SDimitry Andric     return true;
2350*0b57cec5SDimitry Andric   // Check global type.
2351*0b57cec5SDimitry Andric   if (!Ty.isNull()) {
2352*0b57cec5SDimitry Andric     // Drill down the array types: if global variable of a fixed type is
2353*0b57cec5SDimitry Andric     // blacklisted, we also don't instrument arrays of them.
2354*0b57cec5SDimitry Andric     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
2355*0b57cec5SDimitry Andric       Ty = AT->getElementType();
2356*0b57cec5SDimitry Andric     Ty = Ty.getCanonicalType().getUnqualifiedType();
2357*0b57cec5SDimitry Andric     // We allow to blacklist only record types (classes, structs etc.)
2358*0b57cec5SDimitry Andric     if (Ty->isRecordType()) {
2359*0b57cec5SDimitry Andric       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
2360*0b57cec5SDimitry Andric       if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
2361*0b57cec5SDimitry Andric         return true;
2362*0b57cec5SDimitry Andric     }
2363*0b57cec5SDimitry Andric   }
2364*0b57cec5SDimitry Andric   return false;
2365*0b57cec5SDimitry Andric }
2366*0b57cec5SDimitry Andric 
2367*0b57cec5SDimitry Andric bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
2368*0b57cec5SDimitry Andric                                    StringRef Category) const {
2369*0b57cec5SDimitry Andric   const auto &XRayFilter = getContext().getXRayFilter();
2370*0b57cec5SDimitry Andric   using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
2371*0b57cec5SDimitry Andric   auto Attr = ImbueAttr::NONE;
2372*0b57cec5SDimitry Andric   if (Loc.isValid())
2373*0b57cec5SDimitry Andric     Attr = XRayFilter.shouldImbueLocation(Loc, Category);
2374*0b57cec5SDimitry Andric   if (Attr == ImbueAttr::NONE)
2375*0b57cec5SDimitry Andric     Attr = XRayFilter.shouldImbueFunction(Fn->getName());
2376*0b57cec5SDimitry Andric   switch (Attr) {
2377*0b57cec5SDimitry Andric   case ImbueAttr::NONE:
2378*0b57cec5SDimitry Andric     return false;
2379*0b57cec5SDimitry Andric   case ImbueAttr::ALWAYS:
2380*0b57cec5SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-always");
2381*0b57cec5SDimitry Andric     break;
2382*0b57cec5SDimitry Andric   case ImbueAttr::ALWAYS_ARG1:
2383*0b57cec5SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-always");
2384*0b57cec5SDimitry Andric     Fn->addFnAttr("xray-log-args", "1");
2385*0b57cec5SDimitry Andric     break;
2386*0b57cec5SDimitry Andric   case ImbueAttr::NEVER:
2387*0b57cec5SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-never");
2388*0b57cec5SDimitry Andric     break;
2389*0b57cec5SDimitry Andric   }
2390*0b57cec5SDimitry Andric   return true;
2391*0b57cec5SDimitry Andric }
2392*0b57cec5SDimitry Andric 
2393*0b57cec5SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
2394*0b57cec5SDimitry Andric   // Never defer when EmitAllDecls is specified.
2395*0b57cec5SDimitry Andric   if (LangOpts.EmitAllDecls)
2396*0b57cec5SDimitry Andric     return true;
2397*0b57cec5SDimitry Andric 
2398*0b57cec5SDimitry Andric   if (CodeGenOpts.KeepStaticConsts) {
2399*0b57cec5SDimitry Andric     const auto *VD = dyn_cast<VarDecl>(Global);
2400*0b57cec5SDimitry Andric     if (VD && VD->getType().isConstQualified() &&
2401*0b57cec5SDimitry Andric         VD->getStorageDuration() == SD_Static)
2402*0b57cec5SDimitry Andric       return true;
2403*0b57cec5SDimitry Andric   }
2404*0b57cec5SDimitry Andric 
2405*0b57cec5SDimitry Andric   return getContext().DeclMustBeEmitted(Global);
2406*0b57cec5SDimitry Andric }
2407*0b57cec5SDimitry Andric 
2408*0b57cec5SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
2409a7dea167SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
2410*0b57cec5SDimitry Andric     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
2411*0b57cec5SDimitry Andric       // Implicit template instantiations may change linkage if they are later
2412*0b57cec5SDimitry Andric       // explicitly instantiated, so they should not be emitted eagerly.
2413*0b57cec5SDimitry Andric       return false;
2414a7dea167SDimitry Andric     // In OpenMP 5.0 function may be marked as device_type(nohost) and we should
2415a7dea167SDimitry Andric     // not emit them eagerly unless we sure that the function must be emitted on
2416a7dea167SDimitry Andric     // the host.
2417a7dea167SDimitry Andric     if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd &&
2418a7dea167SDimitry Andric         !LangOpts.OpenMPIsDevice &&
2419a7dea167SDimitry Andric         !OMPDeclareTargetDeclAttr::getDeviceType(FD) &&
2420a7dea167SDimitry Andric         !FD->isUsed(/*CheckUsedAttr=*/false) && !FD->isReferenced())
2421a7dea167SDimitry Andric       return false;
2422a7dea167SDimitry Andric   }
2423*0b57cec5SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(Global))
2424*0b57cec5SDimitry Andric     if (Context.getInlineVariableDefinitionKind(VD) ==
2425*0b57cec5SDimitry Andric         ASTContext::InlineVariableDefinitionKind::WeakUnknown)
2426*0b57cec5SDimitry Andric       // A definition of an inline constexpr static data member may change
2427*0b57cec5SDimitry Andric       // linkage later if it's redeclared outside the class.
2428*0b57cec5SDimitry Andric       return false;
2429*0b57cec5SDimitry Andric   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
2430*0b57cec5SDimitry Andric   // codegen for global variables, because they may be marked as threadprivate.
2431*0b57cec5SDimitry Andric   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
2432*0b57cec5SDimitry Andric       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
2433*0b57cec5SDimitry Andric       !isTypeConstant(Global->getType(), false) &&
2434*0b57cec5SDimitry Andric       !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
2435*0b57cec5SDimitry Andric     return false;
2436*0b57cec5SDimitry Andric 
2437*0b57cec5SDimitry Andric   return true;
2438*0b57cec5SDimitry Andric }
2439*0b57cec5SDimitry Andric 
24405ffd83dbSDimitry Andric ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) {
24415ffd83dbSDimitry Andric   StringRef Name = getMangledName(GD);
2442*0b57cec5SDimitry Andric 
2443*0b57cec5SDimitry Andric   // The UUID descriptor should be pointer aligned.
2444*0b57cec5SDimitry Andric   CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
2445*0b57cec5SDimitry Andric 
2446*0b57cec5SDimitry Andric   // Look for an existing global.
2447*0b57cec5SDimitry Andric   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
2448*0b57cec5SDimitry Andric     return ConstantAddress(GV, Alignment);
2449*0b57cec5SDimitry Andric 
24505ffd83dbSDimitry Andric   ConstantEmitter Emitter(*this);
24515ffd83dbSDimitry Andric   llvm::Constant *Init;
24525ffd83dbSDimitry Andric 
24535ffd83dbSDimitry Andric   APValue &V = GD->getAsAPValue();
24545ffd83dbSDimitry Andric   if (!V.isAbsent()) {
24555ffd83dbSDimitry Andric     // If possible, emit the APValue version of the initializer. In particular,
24565ffd83dbSDimitry Andric     // this gets the type of the constant right.
24575ffd83dbSDimitry Andric     Init = Emitter.emitForInitializer(
24585ffd83dbSDimitry Andric         GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType());
24595ffd83dbSDimitry Andric   } else {
24605ffd83dbSDimitry Andric     // As a fallback, directly construct the constant.
24615ffd83dbSDimitry Andric     // FIXME: This may get padding wrong under esoteric struct layout rules.
24625ffd83dbSDimitry Andric     // MSVC appears to create a complete type 'struct __s_GUID' that it
24635ffd83dbSDimitry Andric     // presumably uses to represent these constants.
24645ffd83dbSDimitry Andric     MSGuidDecl::Parts Parts = GD->getParts();
24655ffd83dbSDimitry Andric     llvm::Constant *Fields[4] = {
24665ffd83dbSDimitry Andric         llvm::ConstantInt::get(Int32Ty, Parts.Part1),
24675ffd83dbSDimitry Andric         llvm::ConstantInt::get(Int16Ty, Parts.Part2),
24685ffd83dbSDimitry Andric         llvm::ConstantInt::get(Int16Ty, Parts.Part3),
24695ffd83dbSDimitry Andric         llvm::ConstantDataArray::getRaw(
24705ffd83dbSDimitry Andric             StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8,
24715ffd83dbSDimitry Andric             Int8Ty)};
24725ffd83dbSDimitry Andric     Init = llvm::ConstantStruct::getAnon(Fields);
24735ffd83dbSDimitry Andric   }
2474*0b57cec5SDimitry Andric 
2475*0b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
2476*0b57cec5SDimitry Andric       getModule(), Init->getType(),
2477*0b57cec5SDimitry Andric       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
2478*0b57cec5SDimitry Andric   if (supportsCOMDAT())
2479*0b57cec5SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2480*0b57cec5SDimitry Andric   setDSOLocal(GV);
24815ffd83dbSDimitry Andric 
24825ffd83dbSDimitry Andric   llvm::Constant *Addr = GV;
24835ffd83dbSDimitry Andric   if (!V.isAbsent()) {
24845ffd83dbSDimitry Andric     Emitter.finalize(GV);
24855ffd83dbSDimitry Andric   } else {
24865ffd83dbSDimitry Andric     llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType());
24875ffd83dbSDimitry Andric     Addr = llvm::ConstantExpr::getBitCast(
24885ffd83dbSDimitry Andric         GV, Ty->getPointerTo(GV->getAddressSpace()));
24895ffd83dbSDimitry Andric   }
24905ffd83dbSDimitry Andric   return ConstantAddress(Addr, Alignment);
2491*0b57cec5SDimitry Andric }
2492*0b57cec5SDimitry Andric 
2493*0b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
2494*0b57cec5SDimitry Andric   const AliasAttr *AA = VD->getAttr<AliasAttr>();
2495*0b57cec5SDimitry Andric   assert(AA && "No alias?");
2496*0b57cec5SDimitry Andric 
2497*0b57cec5SDimitry Andric   CharUnits Alignment = getContext().getDeclAlign(VD);
2498*0b57cec5SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
2499*0b57cec5SDimitry Andric 
2500*0b57cec5SDimitry Andric   // See if there is already something with the target's name in the module.
2501*0b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
2502*0b57cec5SDimitry Andric   if (Entry) {
2503*0b57cec5SDimitry Andric     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
2504*0b57cec5SDimitry Andric     auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
2505*0b57cec5SDimitry Andric     return ConstantAddress(Ptr, Alignment);
2506*0b57cec5SDimitry Andric   }
2507*0b57cec5SDimitry Andric 
2508*0b57cec5SDimitry Andric   llvm::Constant *Aliasee;
2509*0b57cec5SDimitry Andric   if (isa<llvm::FunctionType>(DeclTy))
2510*0b57cec5SDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
2511*0b57cec5SDimitry Andric                                       GlobalDecl(cast<FunctionDecl>(VD)),
2512*0b57cec5SDimitry Andric                                       /*ForVTable=*/false);
2513*0b57cec5SDimitry Andric   else
2514*0b57cec5SDimitry Andric     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2515*0b57cec5SDimitry Andric                                     llvm::PointerType::getUnqual(DeclTy),
2516*0b57cec5SDimitry Andric                                     nullptr);
2517*0b57cec5SDimitry Andric 
2518*0b57cec5SDimitry Andric   auto *F = cast<llvm::GlobalValue>(Aliasee);
2519*0b57cec5SDimitry Andric   F->setLinkage(llvm::Function::ExternalWeakLinkage);
2520*0b57cec5SDimitry Andric   WeakRefReferences.insert(F);
2521*0b57cec5SDimitry Andric 
2522*0b57cec5SDimitry Andric   return ConstantAddress(Aliasee, Alignment);
2523*0b57cec5SDimitry Andric }
2524*0b57cec5SDimitry Andric 
2525*0b57cec5SDimitry Andric void CodeGenModule::EmitGlobal(GlobalDecl GD) {
2526*0b57cec5SDimitry Andric   const auto *Global = cast<ValueDecl>(GD.getDecl());
2527*0b57cec5SDimitry Andric 
2528*0b57cec5SDimitry Andric   // Weak references don't produce any output by themselves.
2529*0b57cec5SDimitry Andric   if (Global->hasAttr<WeakRefAttr>())
2530*0b57cec5SDimitry Andric     return;
2531*0b57cec5SDimitry Andric 
2532*0b57cec5SDimitry Andric   // If this is an alias definition (which otherwise looks like a declaration)
2533*0b57cec5SDimitry Andric   // emit it now.
2534*0b57cec5SDimitry Andric   if (Global->hasAttr<AliasAttr>())
2535*0b57cec5SDimitry Andric     return EmitAliasDefinition(GD);
2536*0b57cec5SDimitry Andric 
2537*0b57cec5SDimitry Andric   // IFunc like an alias whose value is resolved at runtime by calling resolver.
2538*0b57cec5SDimitry Andric   if (Global->hasAttr<IFuncAttr>())
2539*0b57cec5SDimitry Andric     return emitIFuncDefinition(GD);
2540*0b57cec5SDimitry Andric 
2541*0b57cec5SDimitry Andric   // If this is a cpu_dispatch multiversion function, emit the resolver.
2542*0b57cec5SDimitry Andric   if (Global->hasAttr<CPUDispatchAttr>())
2543*0b57cec5SDimitry Andric     return emitCPUDispatchDefinition(GD);
2544*0b57cec5SDimitry Andric 
2545*0b57cec5SDimitry Andric   // If this is CUDA, be selective about which declarations we emit.
2546*0b57cec5SDimitry Andric   if (LangOpts.CUDA) {
2547*0b57cec5SDimitry Andric     if (LangOpts.CUDAIsDevice) {
2548*0b57cec5SDimitry Andric       if (!Global->hasAttr<CUDADeviceAttr>() &&
2549*0b57cec5SDimitry Andric           !Global->hasAttr<CUDAGlobalAttr>() &&
2550*0b57cec5SDimitry Andric           !Global->hasAttr<CUDAConstantAttr>() &&
2551*0b57cec5SDimitry Andric           !Global->hasAttr<CUDASharedAttr>() &&
25525ffd83dbSDimitry Andric           !Global->getType()->isCUDADeviceBuiltinSurfaceType() &&
25535ffd83dbSDimitry Andric           !Global->getType()->isCUDADeviceBuiltinTextureType())
2554*0b57cec5SDimitry Andric         return;
2555*0b57cec5SDimitry Andric     } else {
2556*0b57cec5SDimitry Andric       // We need to emit host-side 'shadows' for all global
2557*0b57cec5SDimitry Andric       // device-side variables because the CUDA runtime needs their
2558*0b57cec5SDimitry Andric       // size and host-side address in order to provide access to
2559*0b57cec5SDimitry Andric       // their device-side incarnations.
2560*0b57cec5SDimitry Andric 
2561*0b57cec5SDimitry Andric       // So device-only functions are the only things we skip.
2562*0b57cec5SDimitry Andric       if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
2563*0b57cec5SDimitry Andric           Global->hasAttr<CUDADeviceAttr>())
2564*0b57cec5SDimitry Andric         return;
2565*0b57cec5SDimitry Andric 
2566*0b57cec5SDimitry Andric       assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
2567*0b57cec5SDimitry Andric              "Expected Variable or Function");
2568*0b57cec5SDimitry Andric     }
2569*0b57cec5SDimitry Andric   }
2570*0b57cec5SDimitry Andric 
2571*0b57cec5SDimitry Andric   if (LangOpts.OpenMP) {
2572a7dea167SDimitry Andric     // If this is OpenMP, check if it is legal to emit this global normally.
2573*0b57cec5SDimitry Andric     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
2574*0b57cec5SDimitry Andric       return;
2575*0b57cec5SDimitry Andric     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
2576*0b57cec5SDimitry Andric       if (MustBeEmitted(Global))
2577*0b57cec5SDimitry Andric         EmitOMPDeclareReduction(DRD);
2578*0b57cec5SDimitry Andric       return;
2579*0b57cec5SDimitry Andric     } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
2580*0b57cec5SDimitry Andric       if (MustBeEmitted(Global))
2581*0b57cec5SDimitry Andric         EmitOMPDeclareMapper(DMD);
2582*0b57cec5SDimitry Andric       return;
2583*0b57cec5SDimitry Andric     }
2584*0b57cec5SDimitry Andric   }
2585*0b57cec5SDimitry Andric 
2586*0b57cec5SDimitry Andric   // Ignore declarations, they will be emitted on their first use.
2587*0b57cec5SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
2588*0b57cec5SDimitry Andric     // Forward declarations are emitted lazily on first use.
2589*0b57cec5SDimitry Andric     if (!FD->doesThisDeclarationHaveABody()) {
2590*0b57cec5SDimitry Andric       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
2591*0b57cec5SDimitry Andric         return;
2592*0b57cec5SDimitry Andric 
2593*0b57cec5SDimitry Andric       StringRef MangledName = getMangledName(GD);
2594*0b57cec5SDimitry Andric 
2595*0b57cec5SDimitry Andric       // Compute the function info and LLVM type.
2596*0b57cec5SDimitry Andric       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2597*0b57cec5SDimitry Andric       llvm::Type *Ty = getTypes().GetFunctionType(FI);
2598*0b57cec5SDimitry Andric 
2599*0b57cec5SDimitry Andric       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
2600*0b57cec5SDimitry Andric                               /*DontDefer=*/false);
2601*0b57cec5SDimitry Andric       return;
2602*0b57cec5SDimitry Andric     }
2603*0b57cec5SDimitry Andric   } else {
2604*0b57cec5SDimitry Andric     const auto *VD = cast<VarDecl>(Global);
2605*0b57cec5SDimitry Andric     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
2606*0b57cec5SDimitry Andric     if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
2607*0b57cec5SDimitry Andric         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
2608*0b57cec5SDimitry Andric       if (LangOpts.OpenMP) {
2609*0b57cec5SDimitry Andric         // Emit declaration of the must-be-emitted declare target variable.
2610*0b57cec5SDimitry Andric         if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2611*0b57cec5SDimitry Andric                 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
2612*0b57cec5SDimitry Andric           bool UnifiedMemoryEnabled =
2613*0b57cec5SDimitry Andric               getOpenMPRuntime().hasRequiresUnifiedSharedMemory();
2614*0b57cec5SDimitry Andric           if (*Res == OMPDeclareTargetDeclAttr::MT_To &&
2615*0b57cec5SDimitry Andric               !UnifiedMemoryEnabled) {
2616*0b57cec5SDimitry Andric             (void)GetAddrOfGlobalVar(VD);
2617*0b57cec5SDimitry Andric           } else {
2618*0b57cec5SDimitry Andric             assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
2619*0b57cec5SDimitry Andric                     (*Res == OMPDeclareTargetDeclAttr::MT_To &&
2620*0b57cec5SDimitry Andric                      UnifiedMemoryEnabled)) &&
2621*0b57cec5SDimitry Andric                    "Link clause or to clause with unified memory expected.");
2622*0b57cec5SDimitry Andric             (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
2623*0b57cec5SDimitry Andric           }
2624*0b57cec5SDimitry Andric 
2625*0b57cec5SDimitry Andric           return;
2626*0b57cec5SDimitry Andric         }
2627*0b57cec5SDimitry Andric       }
2628*0b57cec5SDimitry Andric       // If this declaration may have caused an inline variable definition to
2629*0b57cec5SDimitry Andric       // change linkage, make sure that it's emitted.
2630*0b57cec5SDimitry Andric       if (Context.getInlineVariableDefinitionKind(VD) ==
2631*0b57cec5SDimitry Andric           ASTContext::InlineVariableDefinitionKind::Strong)
2632*0b57cec5SDimitry Andric         GetAddrOfGlobalVar(VD);
2633*0b57cec5SDimitry Andric       return;
2634*0b57cec5SDimitry Andric     }
2635*0b57cec5SDimitry Andric   }
2636*0b57cec5SDimitry Andric 
2637*0b57cec5SDimitry Andric   // Defer code generation to first use when possible, e.g. if this is an inline
2638*0b57cec5SDimitry Andric   // function. If the global must always be emitted, do it eagerly if possible
2639*0b57cec5SDimitry Andric   // to benefit from cache locality.
2640*0b57cec5SDimitry Andric   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
2641*0b57cec5SDimitry Andric     // Emit the definition if it can't be deferred.
2642*0b57cec5SDimitry Andric     EmitGlobalDefinition(GD);
2643*0b57cec5SDimitry Andric     return;
2644*0b57cec5SDimitry Andric   }
2645*0b57cec5SDimitry Andric 
2646*0b57cec5SDimitry Andric   // If we're deferring emission of a C++ variable with an
2647*0b57cec5SDimitry Andric   // initializer, remember the order in which it appeared in the file.
2648*0b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
2649*0b57cec5SDimitry Andric       cast<VarDecl>(Global)->hasInit()) {
2650*0b57cec5SDimitry Andric     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
2651*0b57cec5SDimitry Andric     CXXGlobalInits.push_back(nullptr);
2652*0b57cec5SDimitry Andric   }
2653*0b57cec5SDimitry Andric 
2654*0b57cec5SDimitry Andric   StringRef MangledName = getMangledName(GD);
2655*0b57cec5SDimitry Andric   if (GetGlobalValue(MangledName) != nullptr) {
2656*0b57cec5SDimitry Andric     // The value has already been used and should therefore be emitted.
2657*0b57cec5SDimitry Andric     addDeferredDeclToEmit(GD);
2658*0b57cec5SDimitry Andric   } else if (MustBeEmitted(Global)) {
2659*0b57cec5SDimitry Andric     // The value must be emitted, but cannot be emitted eagerly.
2660*0b57cec5SDimitry Andric     assert(!MayBeEmittedEagerly(Global));
2661*0b57cec5SDimitry Andric     addDeferredDeclToEmit(GD);
2662*0b57cec5SDimitry Andric   } else {
2663*0b57cec5SDimitry Andric     // Otherwise, remember that we saw a deferred decl with this name.  The
2664*0b57cec5SDimitry Andric     // first use of the mangled name will cause it to move into
2665*0b57cec5SDimitry Andric     // DeferredDeclsToEmit.
2666*0b57cec5SDimitry Andric     DeferredDecls[MangledName] = GD;
2667*0b57cec5SDimitry Andric   }
2668*0b57cec5SDimitry Andric }
2669*0b57cec5SDimitry Andric 
2670*0b57cec5SDimitry Andric // Check if T is a class type with a destructor that's not dllimport.
2671*0b57cec5SDimitry Andric static bool HasNonDllImportDtor(QualType T) {
2672*0b57cec5SDimitry Andric   if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
2673*0b57cec5SDimitry Andric     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2674*0b57cec5SDimitry Andric       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
2675*0b57cec5SDimitry Andric         return true;
2676*0b57cec5SDimitry Andric 
2677*0b57cec5SDimitry Andric   return false;
2678*0b57cec5SDimitry Andric }
2679*0b57cec5SDimitry Andric 
2680*0b57cec5SDimitry Andric namespace {
2681*0b57cec5SDimitry Andric   struct FunctionIsDirectlyRecursive
2682*0b57cec5SDimitry Andric       : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
2683*0b57cec5SDimitry Andric     const StringRef Name;
2684*0b57cec5SDimitry Andric     const Builtin::Context &BI;
2685*0b57cec5SDimitry Andric     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
2686*0b57cec5SDimitry Andric         : Name(N), BI(C) {}
2687*0b57cec5SDimitry Andric 
2688*0b57cec5SDimitry Andric     bool VisitCallExpr(const CallExpr *E) {
2689*0b57cec5SDimitry Andric       const FunctionDecl *FD = E->getDirectCallee();
2690*0b57cec5SDimitry Andric       if (!FD)
2691*0b57cec5SDimitry Andric         return false;
2692*0b57cec5SDimitry Andric       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2693*0b57cec5SDimitry Andric       if (Attr && Name == Attr->getLabel())
2694*0b57cec5SDimitry Andric         return true;
2695*0b57cec5SDimitry Andric       unsigned BuiltinID = FD->getBuiltinID();
2696*0b57cec5SDimitry Andric       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
2697*0b57cec5SDimitry Andric         return false;
2698*0b57cec5SDimitry Andric       StringRef BuiltinName = BI.getName(BuiltinID);
2699*0b57cec5SDimitry Andric       if (BuiltinName.startswith("__builtin_") &&
2700*0b57cec5SDimitry Andric           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
2701*0b57cec5SDimitry Andric         return true;
2702*0b57cec5SDimitry Andric       }
2703*0b57cec5SDimitry Andric       return false;
2704*0b57cec5SDimitry Andric     }
2705*0b57cec5SDimitry Andric 
2706*0b57cec5SDimitry Andric     bool VisitStmt(const Stmt *S) {
2707*0b57cec5SDimitry Andric       for (const Stmt *Child : S->children())
2708*0b57cec5SDimitry Andric         if (Child && this->Visit(Child))
2709*0b57cec5SDimitry Andric           return true;
2710*0b57cec5SDimitry Andric       return false;
2711*0b57cec5SDimitry Andric     }
2712*0b57cec5SDimitry Andric   };
2713*0b57cec5SDimitry Andric 
2714*0b57cec5SDimitry Andric   // Make sure we're not referencing non-imported vars or functions.
2715*0b57cec5SDimitry Andric   struct DLLImportFunctionVisitor
2716*0b57cec5SDimitry Andric       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
2717*0b57cec5SDimitry Andric     bool SafeToInline = true;
2718*0b57cec5SDimitry Andric 
2719*0b57cec5SDimitry Andric     bool shouldVisitImplicitCode() const { return true; }
2720*0b57cec5SDimitry Andric 
2721*0b57cec5SDimitry Andric     bool VisitVarDecl(VarDecl *VD) {
2722*0b57cec5SDimitry Andric       if (VD->getTLSKind()) {
2723*0b57cec5SDimitry Andric         // A thread-local variable cannot be imported.
2724*0b57cec5SDimitry Andric         SafeToInline = false;
2725*0b57cec5SDimitry Andric         return SafeToInline;
2726*0b57cec5SDimitry Andric       }
2727*0b57cec5SDimitry Andric 
2728*0b57cec5SDimitry Andric       // A variable definition might imply a destructor call.
2729*0b57cec5SDimitry Andric       if (VD->isThisDeclarationADefinition())
2730*0b57cec5SDimitry Andric         SafeToInline = !HasNonDllImportDtor(VD->getType());
2731*0b57cec5SDimitry Andric 
2732*0b57cec5SDimitry Andric       return SafeToInline;
2733*0b57cec5SDimitry Andric     }
2734*0b57cec5SDimitry Andric 
2735*0b57cec5SDimitry Andric     bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
2736*0b57cec5SDimitry Andric       if (const auto *D = E->getTemporary()->getDestructor())
2737*0b57cec5SDimitry Andric         SafeToInline = D->hasAttr<DLLImportAttr>();
2738*0b57cec5SDimitry Andric       return SafeToInline;
2739*0b57cec5SDimitry Andric     }
2740*0b57cec5SDimitry Andric 
2741*0b57cec5SDimitry Andric     bool VisitDeclRefExpr(DeclRefExpr *E) {
2742*0b57cec5SDimitry Andric       ValueDecl *VD = E->getDecl();
2743*0b57cec5SDimitry Andric       if (isa<FunctionDecl>(VD))
2744*0b57cec5SDimitry Andric         SafeToInline = VD->hasAttr<DLLImportAttr>();
2745*0b57cec5SDimitry Andric       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
2746*0b57cec5SDimitry Andric         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
2747*0b57cec5SDimitry Andric       return SafeToInline;
2748*0b57cec5SDimitry Andric     }
2749*0b57cec5SDimitry Andric 
2750*0b57cec5SDimitry Andric     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2751*0b57cec5SDimitry Andric       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
2752*0b57cec5SDimitry Andric       return SafeToInline;
2753*0b57cec5SDimitry Andric     }
2754*0b57cec5SDimitry Andric 
2755*0b57cec5SDimitry Andric     bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2756*0b57cec5SDimitry Andric       CXXMethodDecl *M = E->getMethodDecl();
2757*0b57cec5SDimitry Andric       if (!M) {
2758*0b57cec5SDimitry Andric         // Call through a pointer to member function. This is safe to inline.
2759*0b57cec5SDimitry Andric         SafeToInline = true;
2760*0b57cec5SDimitry Andric       } else {
2761*0b57cec5SDimitry Andric         SafeToInline = M->hasAttr<DLLImportAttr>();
2762*0b57cec5SDimitry Andric       }
2763*0b57cec5SDimitry Andric       return SafeToInline;
2764*0b57cec5SDimitry Andric     }
2765*0b57cec5SDimitry Andric 
2766*0b57cec5SDimitry Andric     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
2767*0b57cec5SDimitry Andric       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
2768*0b57cec5SDimitry Andric       return SafeToInline;
2769*0b57cec5SDimitry Andric     }
2770*0b57cec5SDimitry Andric 
2771*0b57cec5SDimitry Andric     bool VisitCXXNewExpr(CXXNewExpr *E) {
2772*0b57cec5SDimitry Andric       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
2773*0b57cec5SDimitry Andric       return SafeToInline;
2774*0b57cec5SDimitry Andric     }
2775*0b57cec5SDimitry Andric   };
2776*0b57cec5SDimitry Andric }
2777*0b57cec5SDimitry Andric 
2778*0b57cec5SDimitry Andric // isTriviallyRecursive - Check if this function calls another
2779*0b57cec5SDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin,
2780*0b57cec5SDimitry Andric // ends up pointing to itself.
2781*0b57cec5SDimitry Andric bool
2782*0b57cec5SDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
2783*0b57cec5SDimitry Andric   StringRef Name;
2784*0b57cec5SDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
2785*0b57cec5SDimitry Andric     // asm labels are a special kind of mangling we have to support.
2786*0b57cec5SDimitry Andric     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2787*0b57cec5SDimitry Andric     if (!Attr)
2788*0b57cec5SDimitry Andric       return false;
2789*0b57cec5SDimitry Andric     Name = Attr->getLabel();
2790*0b57cec5SDimitry Andric   } else {
2791*0b57cec5SDimitry Andric     Name = FD->getName();
2792*0b57cec5SDimitry Andric   }
2793*0b57cec5SDimitry Andric 
2794*0b57cec5SDimitry Andric   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
2795*0b57cec5SDimitry Andric   const Stmt *Body = FD->getBody();
2796*0b57cec5SDimitry Andric   return Body ? Walker.Visit(Body) : false;
2797*0b57cec5SDimitry Andric }
2798*0b57cec5SDimitry Andric 
2799*0b57cec5SDimitry Andric bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
2800*0b57cec5SDimitry Andric   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
2801*0b57cec5SDimitry Andric     return true;
2802*0b57cec5SDimitry Andric   const auto *F = cast<FunctionDecl>(GD.getDecl());
2803*0b57cec5SDimitry Andric   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
2804*0b57cec5SDimitry Andric     return false;
2805*0b57cec5SDimitry Andric 
2806*0b57cec5SDimitry Andric   if (F->hasAttr<DLLImportAttr>()) {
2807*0b57cec5SDimitry Andric     // Check whether it would be safe to inline this dllimport function.
2808*0b57cec5SDimitry Andric     DLLImportFunctionVisitor Visitor;
2809*0b57cec5SDimitry Andric     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
2810*0b57cec5SDimitry Andric     if (!Visitor.SafeToInline)
2811*0b57cec5SDimitry Andric       return false;
2812*0b57cec5SDimitry Andric 
2813*0b57cec5SDimitry Andric     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
2814*0b57cec5SDimitry Andric       // Implicit destructor invocations aren't captured in the AST, so the
2815*0b57cec5SDimitry Andric       // check above can't see them. Check for them manually here.
2816*0b57cec5SDimitry Andric       for (const Decl *Member : Dtor->getParent()->decls())
2817*0b57cec5SDimitry Andric         if (isa<FieldDecl>(Member))
2818*0b57cec5SDimitry Andric           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
2819*0b57cec5SDimitry Andric             return false;
2820*0b57cec5SDimitry Andric       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
2821*0b57cec5SDimitry Andric         if (HasNonDllImportDtor(B.getType()))
2822*0b57cec5SDimitry Andric           return false;
2823*0b57cec5SDimitry Andric     }
2824*0b57cec5SDimitry Andric   }
2825*0b57cec5SDimitry Andric 
2826*0b57cec5SDimitry Andric   // PR9614. Avoid cases where the source code is lying to us. An available
2827*0b57cec5SDimitry Andric   // externally function should have an equivalent function somewhere else,
28285ffd83dbSDimitry Andric   // but a function that calls itself through asm label/`__builtin_` trickery is
28295ffd83dbSDimitry Andric   // clearly not equivalent to the real implementation.
2830*0b57cec5SDimitry Andric   // This happens in glibc's btowc and in some configure checks.
2831*0b57cec5SDimitry Andric   return !isTriviallyRecursive(F);
2832*0b57cec5SDimitry Andric }
2833*0b57cec5SDimitry Andric 
2834*0b57cec5SDimitry Andric bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
2835*0b57cec5SDimitry Andric   return CodeGenOpts.OptimizationLevel > 0;
2836*0b57cec5SDimitry Andric }
2837*0b57cec5SDimitry Andric 
2838*0b57cec5SDimitry Andric void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
2839*0b57cec5SDimitry Andric                                                        llvm::GlobalValue *GV) {
2840*0b57cec5SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
2841*0b57cec5SDimitry Andric 
2842*0b57cec5SDimitry Andric   if (FD->isCPUSpecificMultiVersion()) {
2843*0b57cec5SDimitry Andric     auto *Spec = FD->getAttr<CPUSpecificAttr>();
2844*0b57cec5SDimitry Andric     for (unsigned I = 0; I < Spec->cpus_size(); ++I)
2845*0b57cec5SDimitry Andric       EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
2846*0b57cec5SDimitry Andric     // Requires multiple emits.
2847*0b57cec5SDimitry Andric   } else
2848*0b57cec5SDimitry Andric     EmitGlobalFunctionDefinition(GD, GV);
2849*0b57cec5SDimitry Andric }
2850*0b57cec5SDimitry Andric 
2851*0b57cec5SDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
2852*0b57cec5SDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
2853*0b57cec5SDimitry Andric 
2854*0b57cec5SDimitry Andric   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
2855*0b57cec5SDimitry Andric                                  Context.getSourceManager(),
2856*0b57cec5SDimitry Andric                                  "Generating code for declaration");
2857*0b57cec5SDimitry Andric 
2858*0b57cec5SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2859*0b57cec5SDimitry Andric     // At -O0, don't generate IR for functions with available_externally
2860*0b57cec5SDimitry Andric     // linkage.
2861*0b57cec5SDimitry Andric     if (!shouldEmitFunction(GD))
2862*0b57cec5SDimitry Andric       return;
2863*0b57cec5SDimitry Andric 
2864*0b57cec5SDimitry Andric     llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
2865*0b57cec5SDimitry Andric       std::string Name;
2866*0b57cec5SDimitry Andric       llvm::raw_string_ostream OS(Name);
2867*0b57cec5SDimitry Andric       FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
2868*0b57cec5SDimitry Andric                                /*Qualified=*/true);
2869*0b57cec5SDimitry Andric       return Name;
2870*0b57cec5SDimitry Andric     });
2871*0b57cec5SDimitry Andric 
2872*0b57cec5SDimitry Andric     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
2873*0b57cec5SDimitry Andric       // Make sure to emit the definition(s) before we emit the thunks.
2874*0b57cec5SDimitry Andric       // This is necessary for the generation of certain thunks.
2875*0b57cec5SDimitry Andric       if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
2876*0b57cec5SDimitry Andric         ABI->emitCXXStructor(GD);
2877*0b57cec5SDimitry Andric       else if (FD->isMultiVersion())
2878*0b57cec5SDimitry Andric         EmitMultiVersionFunctionDefinition(GD, GV);
2879*0b57cec5SDimitry Andric       else
2880*0b57cec5SDimitry Andric         EmitGlobalFunctionDefinition(GD, GV);
2881*0b57cec5SDimitry Andric 
2882*0b57cec5SDimitry Andric       if (Method->isVirtual())
2883*0b57cec5SDimitry Andric         getVTables().EmitThunks(GD);
2884*0b57cec5SDimitry Andric 
2885*0b57cec5SDimitry Andric       return;
2886*0b57cec5SDimitry Andric     }
2887*0b57cec5SDimitry Andric 
2888*0b57cec5SDimitry Andric     if (FD->isMultiVersion())
2889*0b57cec5SDimitry Andric       return EmitMultiVersionFunctionDefinition(GD, GV);
2890*0b57cec5SDimitry Andric     return EmitGlobalFunctionDefinition(GD, GV);
2891*0b57cec5SDimitry Andric   }
2892*0b57cec5SDimitry Andric 
2893*0b57cec5SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
2894*0b57cec5SDimitry Andric     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
2895*0b57cec5SDimitry Andric 
2896*0b57cec5SDimitry Andric   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
2897*0b57cec5SDimitry Andric }
2898*0b57cec5SDimitry Andric 
2899*0b57cec5SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2900*0b57cec5SDimitry Andric                                                       llvm::Function *NewFn);
2901*0b57cec5SDimitry Andric 
2902*0b57cec5SDimitry Andric static unsigned
2903*0b57cec5SDimitry Andric TargetMVPriority(const TargetInfo &TI,
2904*0b57cec5SDimitry Andric                  const CodeGenFunction::MultiVersionResolverOption &RO) {
2905*0b57cec5SDimitry Andric   unsigned Priority = 0;
2906*0b57cec5SDimitry Andric   for (StringRef Feat : RO.Conditions.Features)
2907*0b57cec5SDimitry Andric     Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
2908*0b57cec5SDimitry Andric 
2909*0b57cec5SDimitry Andric   if (!RO.Conditions.Architecture.empty())
2910*0b57cec5SDimitry Andric     Priority = std::max(
2911*0b57cec5SDimitry Andric         Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
2912*0b57cec5SDimitry Andric   return Priority;
2913*0b57cec5SDimitry Andric }
2914*0b57cec5SDimitry Andric 
2915*0b57cec5SDimitry Andric void CodeGenModule::emitMultiVersionFunctions() {
2916*0b57cec5SDimitry Andric   for (GlobalDecl GD : MultiVersionFuncs) {
2917*0b57cec5SDimitry Andric     SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
2918*0b57cec5SDimitry Andric     const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2919*0b57cec5SDimitry Andric     getContext().forEachMultiversionedFunctionVersion(
2920*0b57cec5SDimitry Andric         FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
2921*0b57cec5SDimitry Andric           GlobalDecl CurGD{
2922*0b57cec5SDimitry Andric               (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
2923*0b57cec5SDimitry Andric           StringRef MangledName = getMangledName(CurGD);
2924*0b57cec5SDimitry Andric           llvm::Constant *Func = GetGlobalValue(MangledName);
2925*0b57cec5SDimitry Andric           if (!Func) {
2926*0b57cec5SDimitry Andric             if (CurFD->isDefined()) {
2927*0b57cec5SDimitry Andric               EmitGlobalFunctionDefinition(CurGD, nullptr);
2928*0b57cec5SDimitry Andric               Func = GetGlobalValue(MangledName);
2929*0b57cec5SDimitry Andric             } else {
2930*0b57cec5SDimitry Andric               const CGFunctionInfo &FI =
2931*0b57cec5SDimitry Andric                   getTypes().arrangeGlobalDeclaration(GD);
2932*0b57cec5SDimitry Andric               llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2933*0b57cec5SDimitry Andric               Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
2934*0b57cec5SDimitry Andric                                        /*DontDefer=*/false, ForDefinition);
2935*0b57cec5SDimitry Andric             }
2936*0b57cec5SDimitry Andric             assert(Func && "This should have just been created");
2937*0b57cec5SDimitry Andric           }
2938*0b57cec5SDimitry Andric 
2939*0b57cec5SDimitry Andric           const auto *TA = CurFD->getAttr<TargetAttr>();
2940*0b57cec5SDimitry Andric           llvm::SmallVector<StringRef, 8> Feats;
2941*0b57cec5SDimitry Andric           TA->getAddedFeatures(Feats);
2942*0b57cec5SDimitry Andric 
2943*0b57cec5SDimitry Andric           Options.emplace_back(cast<llvm::Function>(Func),
2944*0b57cec5SDimitry Andric                                TA->getArchitecture(), Feats);
2945*0b57cec5SDimitry Andric         });
2946*0b57cec5SDimitry Andric 
2947*0b57cec5SDimitry Andric     llvm::Function *ResolverFunc;
2948*0b57cec5SDimitry Andric     const TargetInfo &TI = getTarget();
2949*0b57cec5SDimitry Andric 
2950a7dea167SDimitry Andric     if (TI.supportsIFunc() || FD->isTargetMultiVersion()) {
2951*0b57cec5SDimitry Andric       ResolverFunc = cast<llvm::Function>(
2952*0b57cec5SDimitry Andric           GetGlobalValue((getMangledName(GD) + ".resolver").str()));
2953a7dea167SDimitry Andric       ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage);
2954a7dea167SDimitry Andric     } else {
2955*0b57cec5SDimitry Andric       ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD)));
2956a7dea167SDimitry Andric     }
2957*0b57cec5SDimitry Andric 
2958*0b57cec5SDimitry Andric     if (supportsCOMDAT())
2959*0b57cec5SDimitry Andric       ResolverFunc->setComdat(
2960*0b57cec5SDimitry Andric           getModule().getOrInsertComdat(ResolverFunc->getName()));
2961*0b57cec5SDimitry Andric 
2962*0b57cec5SDimitry Andric     llvm::stable_sort(
2963*0b57cec5SDimitry Andric         Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
2964*0b57cec5SDimitry Andric                        const CodeGenFunction::MultiVersionResolverOption &RHS) {
2965*0b57cec5SDimitry Andric           return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
2966*0b57cec5SDimitry Andric         });
2967*0b57cec5SDimitry Andric     CodeGenFunction CGF(*this);
2968*0b57cec5SDimitry Andric     CGF.EmitMultiVersionResolver(ResolverFunc, Options);
2969*0b57cec5SDimitry Andric   }
2970*0b57cec5SDimitry Andric }
2971*0b57cec5SDimitry Andric 
2972*0b57cec5SDimitry Andric void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
2973*0b57cec5SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
2974*0b57cec5SDimitry Andric   assert(FD && "Not a FunctionDecl?");
2975*0b57cec5SDimitry Andric   const auto *DD = FD->getAttr<CPUDispatchAttr>();
2976*0b57cec5SDimitry Andric   assert(DD && "Not a cpu_dispatch Function?");
2977*0b57cec5SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertType(FD->getType());
2978*0b57cec5SDimitry Andric 
2979*0b57cec5SDimitry Andric   if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
2980*0b57cec5SDimitry Andric     const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD);
2981*0b57cec5SDimitry Andric     DeclTy = getTypes().GetFunctionType(FInfo);
2982*0b57cec5SDimitry Andric   }
2983*0b57cec5SDimitry Andric 
2984*0b57cec5SDimitry Andric   StringRef ResolverName = getMangledName(GD);
2985*0b57cec5SDimitry Andric 
2986*0b57cec5SDimitry Andric   llvm::Type *ResolverType;
2987*0b57cec5SDimitry Andric   GlobalDecl ResolverGD;
2988*0b57cec5SDimitry Andric   if (getTarget().supportsIFunc())
2989*0b57cec5SDimitry Andric     ResolverType = llvm::FunctionType::get(
2990*0b57cec5SDimitry Andric         llvm::PointerType::get(DeclTy,
2991*0b57cec5SDimitry Andric                                Context.getTargetAddressSpace(FD->getType())),
2992*0b57cec5SDimitry Andric         false);
2993*0b57cec5SDimitry Andric   else {
2994*0b57cec5SDimitry Andric     ResolverType = DeclTy;
2995*0b57cec5SDimitry Andric     ResolverGD = GD;
2996*0b57cec5SDimitry Andric   }
2997*0b57cec5SDimitry Andric 
2998*0b57cec5SDimitry Andric   auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
2999*0b57cec5SDimitry Andric       ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
3000a7dea167SDimitry Andric   ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage);
3001a7dea167SDimitry Andric   if (supportsCOMDAT())
3002a7dea167SDimitry Andric     ResolverFunc->setComdat(
3003a7dea167SDimitry Andric         getModule().getOrInsertComdat(ResolverFunc->getName()));
3004*0b57cec5SDimitry Andric 
3005*0b57cec5SDimitry Andric   SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
3006*0b57cec5SDimitry Andric   const TargetInfo &Target = getTarget();
3007*0b57cec5SDimitry Andric   unsigned Index = 0;
3008*0b57cec5SDimitry Andric   for (const IdentifierInfo *II : DD->cpus()) {
3009*0b57cec5SDimitry Andric     // Get the name of the target function so we can look it up/create it.
3010*0b57cec5SDimitry Andric     std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
3011*0b57cec5SDimitry Andric                               getCPUSpecificMangling(*this, II->getName());
3012*0b57cec5SDimitry Andric 
3013*0b57cec5SDimitry Andric     llvm::Constant *Func = GetGlobalValue(MangledName);
3014*0b57cec5SDimitry Andric 
3015*0b57cec5SDimitry Andric     if (!Func) {
3016*0b57cec5SDimitry Andric       GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
3017*0b57cec5SDimitry Andric       if (ExistingDecl.getDecl() &&
3018*0b57cec5SDimitry Andric           ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
3019*0b57cec5SDimitry Andric         EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
3020*0b57cec5SDimitry Andric         Func = GetGlobalValue(MangledName);
3021*0b57cec5SDimitry Andric       } else {
3022*0b57cec5SDimitry Andric         if (!ExistingDecl.getDecl())
3023*0b57cec5SDimitry Andric           ExistingDecl = GD.getWithMultiVersionIndex(Index);
3024*0b57cec5SDimitry Andric 
3025*0b57cec5SDimitry Andric       Func = GetOrCreateLLVMFunction(
3026*0b57cec5SDimitry Andric           MangledName, DeclTy, ExistingDecl,
3027*0b57cec5SDimitry Andric           /*ForVTable=*/false, /*DontDefer=*/true,
3028*0b57cec5SDimitry Andric           /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
3029*0b57cec5SDimitry Andric       }
3030*0b57cec5SDimitry Andric     }
3031*0b57cec5SDimitry Andric 
3032*0b57cec5SDimitry Andric     llvm::SmallVector<StringRef, 32> Features;
3033*0b57cec5SDimitry Andric     Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
3034*0b57cec5SDimitry Andric     llvm::transform(Features, Features.begin(),
3035*0b57cec5SDimitry Andric                     [](StringRef Str) { return Str.substr(1); });
3036*0b57cec5SDimitry Andric     Features.erase(std::remove_if(
3037*0b57cec5SDimitry Andric         Features.begin(), Features.end(), [&Target](StringRef Feat) {
3038*0b57cec5SDimitry Andric           return !Target.validateCpuSupports(Feat);
3039*0b57cec5SDimitry Andric         }), Features.end());
3040*0b57cec5SDimitry Andric     Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
3041*0b57cec5SDimitry Andric     ++Index;
3042*0b57cec5SDimitry Andric   }
3043*0b57cec5SDimitry Andric 
3044*0b57cec5SDimitry Andric   llvm::sort(
3045*0b57cec5SDimitry Andric       Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
3046*0b57cec5SDimitry Andric                   const CodeGenFunction::MultiVersionResolverOption &RHS) {
3047*0b57cec5SDimitry Andric         return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) >
3048*0b57cec5SDimitry Andric                CodeGenFunction::GetX86CpuSupportsMask(RHS.Conditions.Features);
3049*0b57cec5SDimitry Andric       });
3050*0b57cec5SDimitry Andric 
3051*0b57cec5SDimitry Andric   // If the list contains multiple 'default' versions, such as when it contains
3052*0b57cec5SDimitry Andric   // 'pentium' and 'generic', don't emit the call to the generic one (since we
3053*0b57cec5SDimitry Andric   // always run on at least a 'pentium'). We do this by deleting the 'least
3054*0b57cec5SDimitry Andric   // advanced' (read, lowest mangling letter).
3055*0b57cec5SDimitry Andric   while (Options.size() > 1 &&
3056*0b57cec5SDimitry Andric          CodeGenFunction::GetX86CpuSupportsMask(
3057*0b57cec5SDimitry Andric              (Options.end() - 2)->Conditions.Features) == 0) {
3058*0b57cec5SDimitry Andric     StringRef LHSName = (Options.end() - 2)->Function->getName();
3059*0b57cec5SDimitry Andric     StringRef RHSName = (Options.end() - 1)->Function->getName();
3060*0b57cec5SDimitry Andric     if (LHSName.compare(RHSName) < 0)
3061*0b57cec5SDimitry Andric       Options.erase(Options.end() - 2);
3062*0b57cec5SDimitry Andric     else
3063*0b57cec5SDimitry Andric       Options.erase(Options.end() - 1);
3064*0b57cec5SDimitry Andric   }
3065*0b57cec5SDimitry Andric 
3066*0b57cec5SDimitry Andric   CodeGenFunction CGF(*this);
3067*0b57cec5SDimitry Andric   CGF.EmitMultiVersionResolver(ResolverFunc, Options);
3068a7dea167SDimitry Andric 
3069a7dea167SDimitry Andric   if (getTarget().supportsIFunc()) {
3070a7dea167SDimitry Andric     std::string AliasName = getMangledNameImpl(
3071a7dea167SDimitry Andric         *this, GD, FD, /*OmitMultiVersionMangling=*/true);
3072a7dea167SDimitry Andric     llvm::Constant *AliasFunc = GetGlobalValue(AliasName);
3073a7dea167SDimitry Andric     if (!AliasFunc) {
3074a7dea167SDimitry Andric       auto *IFunc = cast<llvm::GlobalIFunc>(GetOrCreateLLVMFunction(
3075a7dea167SDimitry Andric           AliasName, DeclTy, GD, /*ForVTable=*/false, /*DontDefer=*/true,
3076a7dea167SDimitry Andric           /*IsThunk=*/false, llvm::AttributeList(), NotForDefinition));
3077a7dea167SDimitry Andric       auto *GA = llvm::GlobalAlias::create(
3078a7dea167SDimitry Andric          DeclTy, 0, getFunctionLinkage(GD), AliasName, IFunc, &getModule());
3079a7dea167SDimitry Andric       GA->setLinkage(llvm::Function::WeakODRLinkage);
3080a7dea167SDimitry Andric       SetCommonAttributes(GD, GA);
3081a7dea167SDimitry Andric     }
3082a7dea167SDimitry Andric   }
3083*0b57cec5SDimitry Andric }
3084*0b57cec5SDimitry Andric 
3085*0b57cec5SDimitry Andric /// If a dispatcher for the specified mangled name is not in the module, create
3086*0b57cec5SDimitry Andric /// and return an llvm Function with the specified type.
3087*0b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
3088*0b57cec5SDimitry Andric     GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) {
3089*0b57cec5SDimitry Andric   std::string MangledName =
3090*0b57cec5SDimitry Andric       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
3091*0b57cec5SDimitry Andric 
3092*0b57cec5SDimitry Andric   // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
3093*0b57cec5SDimitry Andric   // a separate resolver).
3094*0b57cec5SDimitry Andric   std::string ResolverName = MangledName;
3095*0b57cec5SDimitry Andric   if (getTarget().supportsIFunc())
3096*0b57cec5SDimitry Andric     ResolverName += ".ifunc";
3097*0b57cec5SDimitry Andric   else if (FD->isTargetMultiVersion())
3098*0b57cec5SDimitry Andric     ResolverName += ".resolver";
3099*0b57cec5SDimitry Andric 
3100*0b57cec5SDimitry Andric   // If this already exists, just return that one.
3101*0b57cec5SDimitry Andric   if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
3102*0b57cec5SDimitry Andric     return ResolverGV;
3103*0b57cec5SDimitry Andric 
3104*0b57cec5SDimitry Andric   // Since this is the first time we've created this IFunc, make sure
3105*0b57cec5SDimitry Andric   // that we put this multiversioned function into the list to be
3106*0b57cec5SDimitry Andric   // replaced later if necessary (target multiversioning only).
3107*0b57cec5SDimitry Andric   if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion())
3108*0b57cec5SDimitry Andric     MultiVersionFuncs.push_back(GD);
3109*0b57cec5SDimitry Andric 
3110*0b57cec5SDimitry Andric   if (getTarget().supportsIFunc()) {
3111*0b57cec5SDimitry Andric     llvm::Type *ResolverType = llvm::FunctionType::get(
3112*0b57cec5SDimitry Andric         llvm::PointerType::get(
3113*0b57cec5SDimitry Andric             DeclTy, getContext().getTargetAddressSpace(FD->getType())),
3114*0b57cec5SDimitry Andric         false);
3115*0b57cec5SDimitry Andric     llvm::Constant *Resolver = GetOrCreateLLVMFunction(
3116*0b57cec5SDimitry Andric         MangledName + ".resolver", ResolverType, GlobalDecl{},
3117*0b57cec5SDimitry Andric         /*ForVTable=*/false);
3118*0b57cec5SDimitry Andric     llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
3119a7dea167SDimitry Andric         DeclTy, 0, llvm::Function::WeakODRLinkage, "", Resolver, &getModule());
3120*0b57cec5SDimitry Andric     GIF->setName(ResolverName);
3121*0b57cec5SDimitry Andric     SetCommonAttributes(FD, GIF);
3122*0b57cec5SDimitry Andric 
3123*0b57cec5SDimitry Andric     return GIF;
3124*0b57cec5SDimitry Andric   }
3125*0b57cec5SDimitry Andric 
3126*0b57cec5SDimitry Andric   llvm::Constant *Resolver = GetOrCreateLLVMFunction(
3127*0b57cec5SDimitry Andric       ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
3128*0b57cec5SDimitry Andric   assert(isa<llvm::GlobalValue>(Resolver) &&
3129*0b57cec5SDimitry Andric          "Resolver should be created for the first time");
3130*0b57cec5SDimitry Andric   SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
3131*0b57cec5SDimitry Andric   return Resolver;
3132*0b57cec5SDimitry Andric }
3133*0b57cec5SDimitry Andric 
3134*0b57cec5SDimitry Andric /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
3135*0b57cec5SDimitry Andric /// module, create and return an llvm Function with the specified type. If there
3136*0b57cec5SDimitry Andric /// is something in the module with the specified name, return it potentially
3137*0b57cec5SDimitry Andric /// bitcasted to the right type.
3138*0b57cec5SDimitry Andric ///
3139*0b57cec5SDimitry Andric /// If D is non-null, it specifies a decl that correspond to this.  This is used
3140*0b57cec5SDimitry Andric /// to set the attributes on the function when it is first created.
3141*0b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
3142*0b57cec5SDimitry Andric     StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
3143*0b57cec5SDimitry Andric     bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
3144*0b57cec5SDimitry Andric     ForDefinition_t IsForDefinition) {
3145*0b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
3146*0b57cec5SDimitry Andric 
3147*0b57cec5SDimitry Andric   // Any attempts to use a MultiVersion function should result in retrieving
3148*0b57cec5SDimitry Andric   // the iFunc instead. Name Mangling will handle the rest of the changes.
3149*0b57cec5SDimitry Andric   if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
3150*0b57cec5SDimitry Andric     // For the device mark the function as one that should be emitted.
3151*0b57cec5SDimitry Andric     if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
3152*0b57cec5SDimitry Andric         !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
3153*0b57cec5SDimitry Andric         !DontDefer && !IsForDefinition) {
3154*0b57cec5SDimitry Andric       if (const FunctionDecl *FDDef = FD->getDefinition()) {
3155*0b57cec5SDimitry Andric         GlobalDecl GDDef;
3156*0b57cec5SDimitry Andric         if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
3157*0b57cec5SDimitry Andric           GDDef = GlobalDecl(CD, GD.getCtorType());
3158*0b57cec5SDimitry Andric         else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
3159*0b57cec5SDimitry Andric           GDDef = GlobalDecl(DD, GD.getDtorType());
3160*0b57cec5SDimitry Andric         else
3161*0b57cec5SDimitry Andric           GDDef = GlobalDecl(FDDef);
3162*0b57cec5SDimitry Andric         EmitGlobal(GDDef);
3163*0b57cec5SDimitry Andric       }
3164*0b57cec5SDimitry Andric     }
3165*0b57cec5SDimitry Andric 
3166*0b57cec5SDimitry Andric     if (FD->isMultiVersion()) {
31675ffd83dbSDimitry Andric       if (FD->hasAttr<TargetAttr>())
3168*0b57cec5SDimitry Andric         UpdateMultiVersionNames(GD, FD);
3169*0b57cec5SDimitry Andric       if (!IsForDefinition)
3170*0b57cec5SDimitry Andric         return GetOrCreateMultiVersionResolver(GD, Ty, FD);
3171*0b57cec5SDimitry Andric     }
3172*0b57cec5SDimitry Andric   }
3173*0b57cec5SDimitry Andric 
3174*0b57cec5SDimitry Andric   // Lookup the entry, lazily creating it if necessary.
3175*0b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3176*0b57cec5SDimitry Andric   if (Entry) {
3177*0b57cec5SDimitry Andric     if (WeakRefReferences.erase(Entry)) {
3178*0b57cec5SDimitry Andric       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
3179*0b57cec5SDimitry Andric       if (FD && !FD->hasAttr<WeakAttr>())
3180*0b57cec5SDimitry Andric         Entry->setLinkage(llvm::Function::ExternalLinkage);
3181*0b57cec5SDimitry Andric     }
3182*0b57cec5SDimitry Andric 
3183*0b57cec5SDimitry Andric     // Handle dropped DLL attributes.
3184*0b57cec5SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
3185*0b57cec5SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
3186*0b57cec5SDimitry Andric       setDSOLocal(Entry);
3187*0b57cec5SDimitry Andric     }
3188*0b57cec5SDimitry Andric 
3189*0b57cec5SDimitry Andric     // If there are two attempts to define the same mangled name, issue an
3190*0b57cec5SDimitry Andric     // error.
3191*0b57cec5SDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
3192*0b57cec5SDimitry Andric       GlobalDecl OtherGD;
3193*0b57cec5SDimitry Andric       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
3194*0b57cec5SDimitry Andric       // to make sure that we issue an error only once.
3195*0b57cec5SDimitry Andric       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3196*0b57cec5SDimitry Andric           (GD.getCanonicalDecl().getDecl() !=
3197*0b57cec5SDimitry Andric            OtherGD.getCanonicalDecl().getDecl()) &&
3198*0b57cec5SDimitry Andric           DiagnosedConflictingDefinitions.insert(GD).second) {
3199*0b57cec5SDimitry Andric         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
3200*0b57cec5SDimitry Andric             << MangledName;
3201*0b57cec5SDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
3202*0b57cec5SDimitry Andric                           diag::note_previous_definition);
3203*0b57cec5SDimitry Andric       }
3204*0b57cec5SDimitry Andric     }
3205*0b57cec5SDimitry Andric 
3206*0b57cec5SDimitry Andric     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
32075ffd83dbSDimitry Andric         (Entry->getValueType() == Ty)) {
3208*0b57cec5SDimitry Andric       return Entry;
3209*0b57cec5SDimitry Andric     }
3210*0b57cec5SDimitry Andric 
3211*0b57cec5SDimitry Andric     // Make sure the result is of the correct type.
3212*0b57cec5SDimitry Andric     // (If function is requested for a definition, we always need to create a new
3213*0b57cec5SDimitry Andric     // function, not just return a bitcast.)
3214*0b57cec5SDimitry Andric     if (!IsForDefinition)
3215*0b57cec5SDimitry Andric       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
3216*0b57cec5SDimitry Andric   }
3217*0b57cec5SDimitry Andric 
3218*0b57cec5SDimitry Andric   // This function doesn't have a complete type (for example, the return
3219*0b57cec5SDimitry Andric   // type is an incomplete struct). Use a fake type instead, and make
3220*0b57cec5SDimitry Andric   // sure not to try to set attributes.
3221*0b57cec5SDimitry Andric   bool IsIncompleteFunction = false;
3222*0b57cec5SDimitry Andric 
3223*0b57cec5SDimitry Andric   llvm::FunctionType *FTy;
3224*0b57cec5SDimitry Andric   if (isa<llvm::FunctionType>(Ty)) {
3225*0b57cec5SDimitry Andric     FTy = cast<llvm::FunctionType>(Ty);
3226*0b57cec5SDimitry Andric   } else {
3227*0b57cec5SDimitry Andric     FTy = llvm::FunctionType::get(VoidTy, false);
3228*0b57cec5SDimitry Andric     IsIncompleteFunction = true;
3229*0b57cec5SDimitry Andric   }
3230*0b57cec5SDimitry Andric 
3231*0b57cec5SDimitry Andric   llvm::Function *F =
3232*0b57cec5SDimitry Andric       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
3233*0b57cec5SDimitry Andric                              Entry ? StringRef() : MangledName, &getModule());
3234*0b57cec5SDimitry Andric 
3235*0b57cec5SDimitry Andric   // If we already created a function with the same mangled name (but different
3236*0b57cec5SDimitry Andric   // type) before, take its name and add it to the list of functions to be
3237*0b57cec5SDimitry Andric   // replaced with F at the end of CodeGen.
3238*0b57cec5SDimitry Andric   //
3239*0b57cec5SDimitry Andric   // This happens if there is a prototype for a function (e.g. "int f()") and
3240*0b57cec5SDimitry Andric   // then a definition of a different type (e.g. "int f(int x)").
3241*0b57cec5SDimitry Andric   if (Entry) {
3242*0b57cec5SDimitry Andric     F->takeName(Entry);
3243*0b57cec5SDimitry Andric 
3244*0b57cec5SDimitry Andric     // This might be an implementation of a function without a prototype, in
3245*0b57cec5SDimitry Andric     // which case, try to do special replacement of calls which match the new
3246*0b57cec5SDimitry Andric     // prototype.  The really key thing here is that we also potentially drop
3247*0b57cec5SDimitry Andric     // arguments from the call site so as to make a direct call, which makes the
3248*0b57cec5SDimitry Andric     // inliner happier and suppresses a number of optimizer warnings (!) about
3249*0b57cec5SDimitry Andric     // dropping arguments.
3250*0b57cec5SDimitry Andric     if (!Entry->use_empty()) {
3251*0b57cec5SDimitry Andric       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
3252*0b57cec5SDimitry Andric       Entry->removeDeadConstantUsers();
3253*0b57cec5SDimitry Andric     }
3254*0b57cec5SDimitry Andric 
3255*0b57cec5SDimitry Andric     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
32565ffd83dbSDimitry Andric         F, Entry->getValueType()->getPointerTo());
3257*0b57cec5SDimitry Andric     addGlobalValReplacement(Entry, BC);
3258*0b57cec5SDimitry Andric   }
3259*0b57cec5SDimitry Andric 
3260*0b57cec5SDimitry Andric   assert(F->getName() == MangledName && "name was uniqued!");
3261*0b57cec5SDimitry Andric   if (D)
3262*0b57cec5SDimitry Andric     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
3263*0b57cec5SDimitry Andric   if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
3264*0b57cec5SDimitry Andric     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
3265*0b57cec5SDimitry Andric     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
3266*0b57cec5SDimitry Andric   }
3267*0b57cec5SDimitry Andric 
3268*0b57cec5SDimitry Andric   if (!DontDefer) {
3269*0b57cec5SDimitry Andric     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
3270*0b57cec5SDimitry Andric     // each other bottoming out with the base dtor.  Therefore we emit non-base
3271*0b57cec5SDimitry Andric     // dtors on usage, even if there is no dtor definition in the TU.
3272*0b57cec5SDimitry Andric     if (D && isa<CXXDestructorDecl>(D) &&
3273*0b57cec5SDimitry Andric         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
3274*0b57cec5SDimitry Andric                                            GD.getDtorType()))
3275*0b57cec5SDimitry Andric       addDeferredDeclToEmit(GD);
3276*0b57cec5SDimitry Andric 
3277*0b57cec5SDimitry Andric     // This is the first use or definition of a mangled name.  If there is a
3278*0b57cec5SDimitry Andric     // deferred decl with this name, remember that we need to emit it at the end
3279*0b57cec5SDimitry Andric     // of the file.
3280*0b57cec5SDimitry Andric     auto DDI = DeferredDecls.find(MangledName);
3281*0b57cec5SDimitry Andric     if (DDI != DeferredDecls.end()) {
3282*0b57cec5SDimitry Andric       // Move the potentially referenced deferred decl to the
3283*0b57cec5SDimitry Andric       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
3284*0b57cec5SDimitry Andric       // don't need it anymore).
3285*0b57cec5SDimitry Andric       addDeferredDeclToEmit(DDI->second);
3286*0b57cec5SDimitry Andric       DeferredDecls.erase(DDI);
3287*0b57cec5SDimitry Andric 
3288*0b57cec5SDimitry Andric       // Otherwise, there are cases we have to worry about where we're
3289*0b57cec5SDimitry Andric       // using a declaration for which we must emit a definition but where
3290*0b57cec5SDimitry Andric       // we might not find a top-level definition:
3291*0b57cec5SDimitry Andric       //   - member functions defined inline in their classes
3292*0b57cec5SDimitry Andric       //   - friend functions defined inline in some class
3293*0b57cec5SDimitry Andric       //   - special member functions with implicit definitions
3294*0b57cec5SDimitry Andric       // If we ever change our AST traversal to walk into class methods,
3295*0b57cec5SDimitry Andric       // this will be unnecessary.
3296*0b57cec5SDimitry Andric       //
3297*0b57cec5SDimitry Andric       // We also don't emit a definition for a function if it's going to be an
3298*0b57cec5SDimitry Andric       // entry in a vtable, unless it's already marked as used.
3299*0b57cec5SDimitry Andric     } else if (getLangOpts().CPlusPlus && D) {
3300*0b57cec5SDimitry Andric       // Look for a declaration that's lexically in a record.
3301*0b57cec5SDimitry Andric       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
3302*0b57cec5SDimitry Andric            FD = FD->getPreviousDecl()) {
3303*0b57cec5SDimitry Andric         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
3304*0b57cec5SDimitry Andric           if (FD->doesThisDeclarationHaveABody()) {
3305*0b57cec5SDimitry Andric             addDeferredDeclToEmit(GD.getWithDecl(FD));
3306*0b57cec5SDimitry Andric             break;
3307*0b57cec5SDimitry Andric           }
3308*0b57cec5SDimitry Andric         }
3309*0b57cec5SDimitry Andric       }
3310*0b57cec5SDimitry Andric     }
3311*0b57cec5SDimitry Andric   }
3312*0b57cec5SDimitry Andric 
3313*0b57cec5SDimitry Andric   // Make sure the result is of the requested type.
3314*0b57cec5SDimitry Andric   if (!IsIncompleteFunction) {
33155ffd83dbSDimitry Andric     assert(F->getFunctionType() == Ty);
3316*0b57cec5SDimitry Andric     return F;
3317*0b57cec5SDimitry Andric   }
3318*0b57cec5SDimitry Andric 
3319*0b57cec5SDimitry Andric   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
3320*0b57cec5SDimitry Andric   return llvm::ConstantExpr::getBitCast(F, PTy);
3321*0b57cec5SDimitry Andric }
3322*0b57cec5SDimitry Andric 
3323*0b57cec5SDimitry Andric /// GetAddrOfFunction - Return the address of the given function.  If Ty is
3324*0b57cec5SDimitry Andric /// non-null, then this function will use the specified type if it has to
3325*0b57cec5SDimitry Andric /// create it (this occurs when we see a definition of the function).
3326*0b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
3327*0b57cec5SDimitry Andric                                                  llvm::Type *Ty,
3328*0b57cec5SDimitry Andric                                                  bool ForVTable,
3329*0b57cec5SDimitry Andric                                                  bool DontDefer,
3330*0b57cec5SDimitry Andric                                               ForDefinition_t IsForDefinition) {
33315ffd83dbSDimitry Andric   assert(!cast<FunctionDecl>(GD.getDecl())->isConsteval() &&
33325ffd83dbSDimitry Andric          "consteval function should never be emitted");
3333*0b57cec5SDimitry Andric   // If there was no specific requested type, just convert it now.
3334*0b57cec5SDimitry Andric   if (!Ty) {
3335*0b57cec5SDimitry Andric     const auto *FD = cast<FunctionDecl>(GD.getDecl());
3336*0b57cec5SDimitry Andric     Ty = getTypes().ConvertType(FD->getType());
3337*0b57cec5SDimitry Andric   }
3338*0b57cec5SDimitry Andric 
3339*0b57cec5SDimitry Andric   // Devirtualized destructor calls may come through here instead of via
3340*0b57cec5SDimitry Andric   // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
3341*0b57cec5SDimitry Andric   // of the complete destructor when necessary.
3342*0b57cec5SDimitry Andric   if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
3343*0b57cec5SDimitry Andric     if (getTarget().getCXXABI().isMicrosoft() &&
3344*0b57cec5SDimitry Andric         GD.getDtorType() == Dtor_Complete &&
3345*0b57cec5SDimitry Andric         DD->getParent()->getNumVBases() == 0)
3346*0b57cec5SDimitry Andric       GD = GlobalDecl(DD, Dtor_Base);
3347*0b57cec5SDimitry Andric   }
3348*0b57cec5SDimitry Andric 
3349*0b57cec5SDimitry Andric   StringRef MangledName = getMangledName(GD);
3350*0b57cec5SDimitry Andric   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
3351*0b57cec5SDimitry Andric                                  /*IsThunk=*/false, llvm::AttributeList(),
3352*0b57cec5SDimitry Andric                                  IsForDefinition);
3353*0b57cec5SDimitry Andric }
3354*0b57cec5SDimitry Andric 
3355*0b57cec5SDimitry Andric static const FunctionDecl *
3356*0b57cec5SDimitry Andric GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
3357*0b57cec5SDimitry Andric   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
3358*0b57cec5SDimitry Andric   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3359*0b57cec5SDimitry Andric 
3360*0b57cec5SDimitry Andric   IdentifierInfo &CII = C.Idents.get(Name);
3361*0b57cec5SDimitry Andric   for (const auto &Result : DC->lookup(&CII))
3362*0b57cec5SDimitry Andric     if (const auto FD = dyn_cast<FunctionDecl>(Result))
3363*0b57cec5SDimitry Andric       return FD;
3364*0b57cec5SDimitry Andric 
3365*0b57cec5SDimitry Andric   if (!C.getLangOpts().CPlusPlus)
3366*0b57cec5SDimitry Andric     return nullptr;
3367*0b57cec5SDimitry Andric 
3368*0b57cec5SDimitry Andric   // Demangle the premangled name from getTerminateFn()
3369*0b57cec5SDimitry Andric   IdentifierInfo &CXXII =
3370*0b57cec5SDimitry Andric       (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
3371*0b57cec5SDimitry Andric           ? C.Idents.get("terminate")
3372*0b57cec5SDimitry Andric           : C.Idents.get(Name);
3373*0b57cec5SDimitry Andric 
3374*0b57cec5SDimitry Andric   for (const auto &N : {"__cxxabiv1", "std"}) {
3375*0b57cec5SDimitry Andric     IdentifierInfo &NS = C.Idents.get(N);
3376*0b57cec5SDimitry Andric     for (const auto &Result : DC->lookup(&NS)) {
3377*0b57cec5SDimitry Andric       NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
3378*0b57cec5SDimitry Andric       if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
3379*0b57cec5SDimitry Andric         for (const auto &Result : LSD->lookup(&NS))
3380*0b57cec5SDimitry Andric           if ((ND = dyn_cast<NamespaceDecl>(Result)))
3381*0b57cec5SDimitry Andric             break;
3382*0b57cec5SDimitry Andric 
3383*0b57cec5SDimitry Andric       if (ND)
3384*0b57cec5SDimitry Andric         for (const auto &Result : ND->lookup(&CXXII))
3385*0b57cec5SDimitry Andric           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
3386*0b57cec5SDimitry Andric             return FD;
3387*0b57cec5SDimitry Andric     }
3388*0b57cec5SDimitry Andric   }
3389*0b57cec5SDimitry Andric 
3390*0b57cec5SDimitry Andric   return nullptr;
3391*0b57cec5SDimitry Andric }
3392*0b57cec5SDimitry Andric 
3393*0b57cec5SDimitry Andric /// CreateRuntimeFunction - Create a new runtime function with the specified
3394*0b57cec5SDimitry Andric /// type and name.
3395*0b57cec5SDimitry Andric llvm::FunctionCallee
3396*0b57cec5SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
3397480093f4SDimitry Andric                                      llvm::AttributeList ExtraAttrs, bool Local,
3398480093f4SDimitry Andric                                      bool AssumeConvergent) {
3399480093f4SDimitry Andric   if (AssumeConvergent) {
3400480093f4SDimitry Andric     ExtraAttrs =
3401480093f4SDimitry Andric         ExtraAttrs.addAttribute(VMContext, llvm::AttributeList::FunctionIndex,
3402480093f4SDimitry Andric                                 llvm::Attribute::Convergent);
3403480093f4SDimitry Andric   }
3404480093f4SDimitry Andric 
3405*0b57cec5SDimitry Andric   llvm::Constant *C =
3406*0b57cec5SDimitry Andric       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
3407*0b57cec5SDimitry Andric                               /*DontDefer=*/false, /*IsThunk=*/false,
3408*0b57cec5SDimitry Andric                               ExtraAttrs);
3409*0b57cec5SDimitry Andric 
3410*0b57cec5SDimitry Andric   if (auto *F = dyn_cast<llvm::Function>(C)) {
3411*0b57cec5SDimitry Andric     if (F->empty()) {
3412*0b57cec5SDimitry Andric       F->setCallingConv(getRuntimeCC());
3413*0b57cec5SDimitry Andric 
3414*0b57cec5SDimitry Andric       // In Windows Itanium environments, try to mark runtime functions
3415*0b57cec5SDimitry Andric       // dllimport. For Mingw and MSVC, don't. We don't really know if the user
3416*0b57cec5SDimitry Andric       // will link their standard library statically or dynamically. Marking
3417*0b57cec5SDimitry Andric       // functions imported when they are not imported can cause linker errors
3418*0b57cec5SDimitry Andric       // and warnings.
3419*0b57cec5SDimitry Andric       if (!Local && getTriple().isWindowsItaniumEnvironment() &&
3420*0b57cec5SDimitry Andric           !getCodeGenOpts().LTOVisibilityPublicStd) {
3421*0b57cec5SDimitry Andric         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
3422*0b57cec5SDimitry Andric         if (!FD || FD->hasAttr<DLLImportAttr>()) {
3423*0b57cec5SDimitry Andric           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3424*0b57cec5SDimitry Andric           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
3425*0b57cec5SDimitry Andric         }
3426*0b57cec5SDimitry Andric       }
3427*0b57cec5SDimitry Andric       setDSOLocal(F);
3428*0b57cec5SDimitry Andric     }
3429*0b57cec5SDimitry Andric   }
3430*0b57cec5SDimitry Andric 
3431*0b57cec5SDimitry Andric   return {FTy, C};
3432*0b57cec5SDimitry Andric }
3433*0b57cec5SDimitry Andric 
3434*0b57cec5SDimitry Andric /// isTypeConstant - Determine whether an object of this type can be emitted
3435*0b57cec5SDimitry Andric /// as a constant.
3436*0b57cec5SDimitry Andric ///
3437*0b57cec5SDimitry Andric /// If ExcludeCtor is true, the duration when the object's constructor runs
3438*0b57cec5SDimitry Andric /// will not be considered. The caller will need to verify that the object is
3439*0b57cec5SDimitry Andric /// not written to during its construction.
3440*0b57cec5SDimitry Andric bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
3441*0b57cec5SDimitry Andric   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
3442*0b57cec5SDimitry Andric     return false;
3443*0b57cec5SDimitry Andric 
3444*0b57cec5SDimitry Andric   if (Context.getLangOpts().CPlusPlus) {
3445*0b57cec5SDimitry Andric     if (const CXXRecordDecl *Record
3446*0b57cec5SDimitry Andric           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
3447*0b57cec5SDimitry Andric       return ExcludeCtor && !Record->hasMutableFields() &&
3448*0b57cec5SDimitry Andric              Record->hasTrivialDestructor();
3449*0b57cec5SDimitry Andric   }
3450*0b57cec5SDimitry Andric 
3451*0b57cec5SDimitry Andric   return true;
3452*0b57cec5SDimitry Andric }
3453*0b57cec5SDimitry Andric 
3454*0b57cec5SDimitry Andric /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
3455*0b57cec5SDimitry Andric /// create and return an llvm GlobalVariable with the specified type.  If there
3456*0b57cec5SDimitry Andric /// is something in the module with the specified name, return it potentially
3457*0b57cec5SDimitry Andric /// bitcasted to the right type.
3458*0b57cec5SDimitry Andric ///
3459*0b57cec5SDimitry Andric /// If D is non-null, it specifies a decl that correspond to this.  This is used
3460*0b57cec5SDimitry Andric /// to set the attributes on the global when it is first created.
3461*0b57cec5SDimitry Andric ///
3462*0b57cec5SDimitry Andric /// If IsForDefinition is true, it is guaranteed that an actual global with
3463*0b57cec5SDimitry Andric /// type Ty will be returned, not conversion of a variable with the same
3464*0b57cec5SDimitry Andric /// mangled name but some other type.
3465*0b57cec5SDimitry Andric llvm::Constant *
3466*0b57cec5SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
3467*0b57cec5SDimitry Andric                                      llvm::PointerType *Ty,
3468*0b57cec5SDimitry Andric                                      const VarDecl *D,
3469*0b57cec5SDimitry Andric                                      ForDefinition_t IsForDefinition) {
3470*0b57cec5SDimitry Andric   // Lookup the entry, lazily creating it if necessary.
3471*0b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3472*0b57cec5SDimitry Andric   if (Entry) {
3473*0b57cec5SDimitry Andric     if (WeakRefReferences.erase(Entry)) {
3474*0b57cec5SDimitry Andric       if (D && !D->hasAttr<WeakAttr>())
3475*0b57cec5SDimitry Andric         Entry->setLinkage(llvm::Function::ExternalLinkage);
3476*0b57cec5SDimitry Andric     }
3477*0b57cec5SDimitry Andric 
3478*0b57cec5SDimitry Andric     // Handle dropped DLL attributes.
3479*0b57cec5SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
3480*0b57cec5SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
3481*0b57cec5SDimitry Andric 
3482*0b57cec5SDimitry Andric     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
3483*0b57cec5SDimitry Andric       getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
3484*0b57cec5SDimitry Andric 
3485*0b57cec5SDimitry Andric     if (Entry->getType() == Ty)
3486*0b57cec5SDimitry Andric       return Entry;
3487*0b57cec5SDimitry Andric 
3488*0b57cec5SDimitry Andric     // If there are two attempts to define the same mangled name, issue an
3489*0b57cec5SDimitry Andric     // error.
3490*0b57cec5SDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
3491*0b57cec5SDimitry Andric       GlobalDecl OtherGD;
3492*0b57cec5SDimitry Andric       const VarDecl *OtherD;
3493*0b57cec5SDimitry Andric 
3494*0b57cec5SDimitry Andric       // Check that D is not yet in DiagnosedConflictingDefinitions is required
3495*0b57cec5SDimitry Andric       // to make sure that we issue an error only once.
3496*0b57cec5SDimitry Andric       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
3497*0b57cec5SDimitry Andric           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
3498*0b57cec5SDimitry Andric           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
3499*0b57cec5SDimitry Andric           OtherD->hasInit() &&
3500*0b57cec5SDimitry Andric           DiagnosedConflictingDefinitions.insert(D).second) {
3501*0b57cec5SDimitry Andric         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
3502*0b57cec5SDimitry Andric             << MangledName;
3503*0b57cec5SDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
3504*0b57cec5SDimitry Andric                           diag::note_previous_definition);
3505*0b57cec5SDimitry Andric       }
3506*0b57cec5SDimitry Andric     }
3507*0b57cec5SDimitry Andric 
3508*0b57cec5SDimitry Andric     // Make sure the result is of the correct type.
3509*0b57cec5SDimitry Andric     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
3510*0b57cec5SDimitry Andric       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
3511*0b57cec5SDimitry Andric 
3512*0b57cec5SDimitry Andric     // (If global is requested for a definition, we always need to create a new
3513*0b57cec5SDimitry Andric     // global, not just return a bitcast.)
3514*0b57cec5SDimitry Andric     if (!IsForDefinition)
3515*0b57cec5SDimitry Andric       return llvm::ConstantExpr::getBitCast(Entry, Ty);
3516*0b57cec5SDimitry Andric   }
3517*0b57cec5SDimitry Andric 
3518*0b57cec5SDimitry Andric   auto AddrSpace = GetGlobalVarAddressSpace(D);
3519*0b57cec5SDimitry Andric   auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
3520*0b57cec5SDimitry Andric 
3521*0b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
3522*0b57cec5SDimitry Andric       getModule(), Ty->getElementType(), false,
3523*0b57cec5SDimitry Andric       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
3524*0b57cec5SDimitry Andric       llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
3525*0b57cec5SDimitry Andric 
3526*0b57cec5SDimitry Andric   // If we already created a global with the same mangled name (but different
3527*0b57cec5SDimitry Andric   // type) before, take its name and remove it from its parent.
3528*0b57cec5SDimitry Andric   if (Entry) {
3529*0b57cec5SDimitry Andric     GV->takeName(Entry);
3530*0b57cec5SDimitry Andric 
3531*0b57cec5SDimitry Andric     if (!Entry->use_empty()) {
3532*0b57cec5SDimitry Andric       llvm::Constant *NewPtrForOldDecl =
3533*0b57cec5SDimitry Andric           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
3534*0b57cec5SDimitry Andric       Entry->replaceAllUsesWith(NewPtrForOldDecl);
3535*0b57cec5SDimitry Andric     }
3536*0b57cec5SDimitry Andric 
3537*0b57cec5SDimitry Andric     Entry->eraseFromParent();
3538*0b57cec5SDimitry Andric   }
3539*0b57cec5SDimitry Andric 
3540*0b57cec5SDimitry Andric   // This is the first use or definition of a mangled name.  If there is a
3541*0b57cec5SDimitry Andric   // deferred decl with this name, remember that we need to emit it at the end
3542*0b57cec5SDimitry Andric   // of the file.
3543*0b57cec5SDimitry Andric   auto DDI = DeferredDecls.find(MangledName);
3544*0b57cec5SDimitry Andric   if (DDI != DeferredDecls.end()) {
3545*0b57cec5SDimitry Andric     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
3546*0b57cec5SDimitry Andric     // list, and remove it from DeferredDecls (since we don't need it anymore).
3547*0b57cec5SDimitry Andric     addDeferredDeclToEmit(DDI->second);
3548*0b57cec5SDimitry Andric     DeferredDecls.erase(DDI);
3549*0b57cec5SDimitry Andric   }
3550*0b57cec5SDimitry Andric 
3551*0b57cec5SDimitry Andric   // Handle things which are present even on external declarations.
3552*0b57cec5SDimitry Andric   if (D) {
3553*0b57cec5SDimitry Andric     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
3554*0b57cec5SDimitry Andric       getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
3555*0b57cec5SDimitry Andric 
3556*0b57cec5SDimitry Andric     // FIXME: This code is overly simple and should be merged with other global
3557*0b57cec5SDimitry Andric     // handling.
3558*0b57cec5SDimitry Andric     GV->setConstant(isTypeConstant(D->getType(), false));
3559*0b57cec5SDimitry Andric 
3560a7dea167SDimitry Andric     GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
3561*0b57cec5SDimitry Andric 
3562*0b57cec5SDimitry Andric     setLinkageForGV(GV, D);
3563*0b57cec5SDimitry Andric 
3564*0b57cec5SDimitry Andric     if (D->getTLSKind()) {
3565*0b57cec5SDimitry Andric       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
3566*0b57cec5SDimitry Andric         CXXThreadLocals.push_back(D);
3567*0b57cec5SDimitry Andric       setTLSMode(GV, *D);
3568*0b57cec5SDimitry Andric     }
3569*0b57cec5SDimitry Andric 
3570*0b57cec5SDimitry Andric     setGVProperties(GV, D);
3571*0b57cec5SDimitry Andric 
3572*0b57cec5SDimitry Andric     // If required by the ABI, treat declarations of static data members with
3573*0b57cec5SDimitry Andric     // inline initializers as definitions.
3574*0b57cec5SDimitry Andric     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
3575*0b57cec5SDimitry Andric       EmitGlobalVarDefinition(D);
3576*0b57cec5SDimitry Andric     }
3577*0b57cec5SDimitry Andric 
3578*0b57cec5SDimitry Andric     // Emit section information for extern variables.
3579*0b57cec5SDimitry Andric     if (D->hasExternalStorage()) {
3580*0b57cec5SDimitry Andric       if (const SectionAttr *SA = D->getAttr<SectionAttr>())
3581*0b57cec5SDimitry Andric         GV->setSection(SA->getName());
3582*0b57cec5SDimitry Andric     }
3583*0b57cec5SDimitry Andric 
3584*0b57cec5SDimitry Andric     // Handle XCore specific ABI requirements.
3585*0b57cec5SDimitry Andric     if (getTriple().getArch() == llvm::Triple::xcore &&
3586*0b57cec5SDimitry Andric         D->getLanguageLinkage() == CLanguageLinkage &&
3587*0b57cec5SDimitry Andric         D->getType().isConstant(Context) &&
3588*0b57cec5SDimitry Andric         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
3589*0b57cec5SDimitry Andric       GV->setSection(".cp.rodata");
3590*0b57cec5SDimitry Andric 
3591*0b57cec5SDimitry Andric     // Check if we a have a const declaration with an initializer, we may be
3592*0b57cec5SDimitry Andric     // able to emit it as available_externally to expose it's value to the
3593*0b57cec5SDimitry Andric     // optimizer.
3594*0b57cec5SDimitry Andric     if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
3595*0b57cec5SDimitry Andric         D->getType().isConstQualified() && !GV->hasInitializer() &&
3596*0b57cec5SDimitry Andric         !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
3597*0b57cec5SDimitry Andric       const auto *Record =
3598*0b57cec5SDimitry Andric           Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
3599*0b57cec5SDimitry Andric       bool HasMutableFields = Record && Record->hasMutableFields();
3600*0b57cec5SDimitry Andric       if (!HasMutableFields) {
3601*0b57cec5SDimitry Andric         const VarDecl *InitDecl;
3602*0b57cec5SDimitry Andric         const Expr *InitExpr = D->getAnyInitializer(InitDecl);
3603*0b57cec5SDimitry Andric         if (InitExpr) {
3604*0b57cec5SDimitry Andric           ConstantEmitter emitter(*this);
3605*0b57cec5SDimitry Andric           llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
3606*0b57cec5SDimitry Andric           if (Init) {
3607*0b57cec5SDimitry Andric             auto *InitType = Init->getType();
36085ffd83dbSDimitry Andric             if (GV->getValueType() != InitType) {
3609*0b57cec5SDimitry Andric               // The type of the initializer does not match the definition.
3610*0b57cec5SDimitry Andric               // This happens when an initializer has a different type from
3611*0b57cec5SDimitry Andric               // the type of the global (because of padding at the end of a
3612*0b57cec5SDimitry Andric               // structure for instance).
3613*0b57cec5SDimitry Andric               GV->setName(StringRef());
3614*0b57cec5SDimitry Andric               // Make a new global with the correct type, this is now guaranteed
3615*0b57cec5SDimitry Andric               // to work.
3616*0b57cec5SDimitry Andric               auto *NewGV = cast<llvm::GlobalVariable>(
3617a7dea167SDimitry Andric                   GetAddrOfGlobalVar(D, InitType, IsForDefinition)
3618a7dea167SDimitry Andric                       ->stripPointerCasts());
3619*0b57cec5SDimitry Andric 
3620*0b57cec5SDimitry Andric               // Erase the old global, since it is no longer used.
3621*0b57cec5SDimitry Andric               GV->eraseFromParent();
3622*0b57cec5SDimitry Andric               GV = NewGV;
3623*0b57cec5SDimitry Andric             } else {
3624*0b57cec5SDimitry Andric               GV->setInitializer(Init);
3625*0b57cec5SDimitry Andric               GV->setConstant(true);
3626*0b57cec5SDimitry Andric               GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
3627*0b57cec5SDimitry Andric             }
3628*0b57cec5SDimitry Andric             emitter.finalize(GV);
3629*0b57cec5SDimitry Andric           }
3630*0b57cec5SDimitry Andric         }
3631*0b57cec5SDimitry Andric       }
3632*0b57cec5SDimitry Andric     }
3633*0b57cec5SDimitry Andric   }
3634*0b57cec5SDimitry Andric 
3635480093f4SDimitry Andric   if (GV->isDeclaration())
3636480093f4SDimitry Andric     getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
3637480093f4SDimitry Andric 
3638*0b57cec5SDimitry Andric   LangAS ExpectedAS =
3639*0b57cec5SDimitry Andric       D ? D->getType().getAddressSpace()
3640*0b57cec5SDimitry Andric         : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
3641*0b57cec5SDimitry Andric   assert(getContext().getTargetAddressSpace(ExpectedAS) ==
3642*0b57cec5SDimitry Andric          Ty->getPointerAddressSpace());
3643*0b57cec5SDimitry Andric   if (AddrSpace != ExpectedAS)
3644*0b57cec5SDimitry Andric     return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
3645*0b57cec5SDimitry Andric                                                        ExpectedAS, Ty);
3646*0b57cec5SDimitry Andric 
3647*0b57cec5SDimitry Andric   return GV;
3648*0b57cec5SDimitry Andric }
3649*0b57cec5SDimitry Andric 
3650*0b57cec5SDimitry Andric llvm::Constant *
36515ffd83dbSDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) {
3652*0b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
36535ffd83dbSDimitry Andric 
3654*0b57cec5SDimitry Andric   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
3655*0b57cec5SDimitry Andric     return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
3656*0b57cec5SDimitry Andric                                 /*DontDefer=*/false, IsForDefinition);
36575ffd83dbSDimitry Andric 
36585ffd83dbSDimitry Andric   if (isa<CXXMethodDecl>(D)) {
36595ffd83dbSDimitry Andric     auto FInfo =
36605ffd83dbSDimitry Andric         &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D));
3661*0b57cec5SDimitry Andric     auto Ty = getTypes().GetFunctionType(*FInfo);
3662*0b57cec5SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3663*0b57cec5SDimitry Andric                              IsForDefinition);
36645ffd83dbSDimitry Andric   }
36655ffd83dbSDimitry Andric 
36665ffd83dbSDimitry Andric   if (isa<FunctionDecl>(D)) {
3667*0b57cec5SDimitry Andric     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3668*0b57cec5SDimitry Andric     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3669*0b57cec5SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3670*0b57cec5SDimitry Andric                              IsForDefinition);
36715ffd83dbSDimitry Andric   }
36725ffd83dbSDimitry Andric 
36735ffd83dbSDimitry Andric   return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition);
3674*0b57cec5SDimitry Andric }
3675*0b57cec5SDimitry Andric 
3676*0b57cec5SDimitry Andric llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
3677*0b57cec5SDimitry Andric     StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
3678*0b57cec5SDimitry Andric     unsigned Alignment) {
3679*0b57cec5SDimitry Andric   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
3680*0b57cec5SDimitry Andric   llvm::GlobalVariable *OldGV = nullptr;
3681*0b57cec5SDimitry Andric 
3682*0b57cec5SDimitry Andric   if (GV) {
3683*0b57cec5SDimitry Andric     // Check if the variable has the right type.
36845ffd83dbSDimitry Andric     if (GV->getValueType() == Ty)
3685*0b57cec5SDimitry Andric       return GV;
3686*0b57cec5SDimitry Andric 
3687*0b57cec5SDimitry Andric     // Because C++ name mangling, the only way we can end up with an already
3688*0b57cec5SDimitry Andric     // existing global with the same name is if it has been declared extern "C".
3689*0b57cec5SDimitry Andric     assert(GV->isDeclaration() && "Declaration has wrong type!");
3690*0b57cec5SDimitry Andric     OldGV = GV;
3691*0b57cec5SDimitry Andric   }
3692*0b57cec5SDimitry Andric 
3693*0b57cec5SDimitry Andric   // Create a new variable.
3694*0b57cec5SDimitry Andric   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
3695*0b57cec5SDimitry Andric                                 Linkage, nullptr, Name);
3696*0b57cec5SDimitry Andric 
3697*0b57cec5SDimitry Andric   if (OldGV) {
3698*0b57cec5SDimitry Andric     // Replace occurrences of the old variable if needed.
3699*0b57cec5SDimitry Andric     GV->takeName(OldGV);
3700*0b57cec5SDimitry Andric 
3701*0b57cec5SDimitry Andric     if (!OldGV->use_empty()) {
3702*0b57cec5SDimitry Andric       llvm::Constant *NewPtrForOldDecl =
3703*0b57cec5SDimitry Andric       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3704*0b57cec5SDimitry Andric       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
3705*0b57cec5SDimitry Andric     }
3706*0b57cec5SDimitry Andric 
3707*0b57cec5SDimitry Andric     OldGV->eraseFromParent();
3708*0b57cec5SDimitry Andric   }
3709*0b57cec5SDimitry Andric 
3710*0b57cec5SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker() &&
3711*0b57cec5SDimitry Andric       !GV->hasAvailableExternallyLinkage())
3712*0b57cec5SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3713*0b57cec5SDimitry Andric 
3714a7dea167SDimitry Andric   GV->setAlignment(llvm::MaybeAlign(Alignment));
3715*0b57cec5SDimitry Andric 
3716*0b57cec5SDimitry Andric   return GV;
3717*0b57cec5SDimitry Andric }
3718*0b57cec5SDimitry Andric 
3719*0b57cec5SDimitry Andric /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
3720*0b57cec5SDimitry Andric /// given global variable.  If Ty is non-null and if the global doesn't exist,
3721*0b57cec5SDimitry Andric /// then it will be created with the specified type instead of whatever the
3722*0b57cec5SDimitry Andric /// normal requested type would be. If IsForDefinition is true, it is guaranteed
3723*0b57cec5SDimitry Andric /// that an actual global with type Ty will be returned, not conversion of a
3724*0b57cec5SDimitry Andric /// variable with the same mangled name but some other type.
3725*0b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
3726*0b57cec5SDimitry Andric                                                   llvm::Type *Ty,
3727*0b57cec5SDimitry Andric                                            ForDefinition_t IsForDefinition) {
3728*0b57cec5SDimitry Andric   assert(D->hasGlobalStorage() && "Not a global variable");
3729*0b57cec5SDimitry Andric   QualType ASTTy = D->getType();
3730*0b57cec5SDimitry Andric   if (!Ty)
3731*0b57cec5SDimitry Andric     Ty = getTypes().ConvertTypeForMem(ASTTy);
3732*0b57cec5SDimitry Andric 
3733*0b57cec5SDimitry Andric   llvm::PointerType *PTy =
3734*0b57cec5SDimitry Andric     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
3735*0b57cec5SDimitry Andric 
3736*0b57cec5SDimitry Andric   StringRef MangledName = getMangledName(D);
3737*0b57cec5SDimitry Andric   return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
3738*0b57cec5SDimitry Andric }
3739*0b57cec5SDimitry Andric 
3740*0b57cec5SDimitry Andric /// CreateRuntimeVariable - Create a new runtime global variable with the
3741*0b57cec5SDimitry Andric /// specified type and name.
3742*0b57cec5SDimitry Andric llvm::Constant *
3743*0b57cec5SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
3744*0b57cec5SDimitry Andric                                      StringRef Name) {
3745*0b57cec5SDimitry Andric   auto PtrTy =
3746*0b57cec5SDimitry Andric       getContext().getLangOpts().OpenCL
3747*0b57cec5SDimitry Andric           ? llvm::PointerType::get(
3748*0b57cec5SDimitry Andric                 Ty, getContext().getTargetAddressSpace(LangAS::opencl_global))
3749*0b57cec5SDimitry Andric           : llvm::PointerType::getUnqual(Ty);
3750*0b57cec5SDimitry Andric   auto *Ret = GetOrCreateLLVMGlobal(Name, PtrTy, nullptr);
3751*0b57cec5SDimitry Andric   setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
3752*0b57cec5SDimitry Andric   return Ret;
3753*0b57cec5SDimitry Andric }
3754*0b57cec5SDimitry Andric 
3755*0b57cec5SDimitry Andric void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
3756*0b57cec5SDimitry Andric   assert(!D->getInit() && "Cannot emit definite definitions here!");
3757*0b57cec5SDimitry Andric 
3758*0b57cec5SDimitry Andric   StringRef MangledName = getMangledName(D);
3759*0b57cec5SDimitry Andric   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
3760*0b57cec5SDimitry Andric 
3761*0b57cec5SDimitry Andric   // We already have a definition, not declaration, with the same mangled name.
3762*0b57cec5SDimitry Andric   // Emitting of declaration is not required (and actually overwrites emitted
3763*0b57cec5SDimitry Andric   // definition).
3764*0b57cec5SDimitry Andric   if (GV && !GV->isDeclaration())
3765*0b57cec5SDimitry Andric     return;
3766*0b57cec5SDimitry Andric 
3767*0b57cec5SDimitry Andric   // If we have not seen a reference to this variable yet, place it into the
3768*0b57cec5SDimitry Andric   // deferred declarations table to be emitted if needed later.
3769*0b57cec5SDimitry Andric   if (!MustBeEmitted(D) && !GV) {
3770*0b57cec5SDimitry Andric       DeferredDecls[MangledName] = D;
3771*0b57cec5SDimitry Andric       return;
3772*0b57cec5SDimitry Andric   }
3773*0b57cec5SDimitry Andric 
3774*0b57cec5SDimitry Andric   // The tentative definition is the only definition.
3775*0b57cec5SDimitry Andric   EmitGlobalVarDefinition(D);
3776*0b57cec5SDimitry Andric }
3777*0b57cec5SDimitry Andric 
3778480093f4SDimitry Andric void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) {
3779480093f4SDimitry Andric   EmitExternalVarDeclaration(D);
3780480093f4SDimitry Andric }
3781480093f4SDimitry Andric 
3782*0b57cec5SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
3783*0b57cec5SDimitry Andric   return Context.toCharUnitsFromBits(
3784*0b57cec5SDimitry Andric       getDataLayout().getTypeStoreSizeInBits(Ty));
3785*0b57cec5SDimitry Andric }
3786*0b57cec5SDimitry Andric 
3787*0b57cec5SDimitry Andric LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
3788*0b57cec5SDimitry Andric   LangAS AddrSpace = LangAS::Default;
3789*0b57cec5SDimitry Andric   if (LangOpts.OpenCL) {
3790*0b57cec5SDimitry Andric     AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
3791*0b57cec5SDimitry Andric     assert(AddrSpace == LangAS::opencl_global ||
3792*0b57cec5SDimitry Andric            AddrSpace == LangAS::opencl_constant ||
3793*0b57cec5SDimitry Andric            AddrSpace == LangAS::opencl_local ||
3794*0b57cec5SDimitry Andric            AddrSpace >= LangAS::FirstTargetAddressSpace);
3795*0b57cec5SDimitry Andric     return AddrSpace;
3796*0b57cec5SDimitry Andric   }
3797*0b57cec5SDimitry Andric 
3798*0b57cec5SDimitry Andric   if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
3799*0b57cec5SDimitry Andric     if (D && D->hasAttr<CUDAConstantAttr>())
3800*0b57cec5SDimitry Andric       return LangAS::cuda_constant;
3801*0b57cec5SDimitry Andric     else if (D && D->hasAttr<CUDASharedAttr>())
3802*0b57cec5SDimitry Andric       return LangAS::cuda_shared;
3803*0b57cec5SDimitry Andric     else if (D && D->hasAttr<CUDADeviceAttr>())
3804*0b57cec5SDimitry Andric       return LangAS::cuda_device;
3805*0b57cec5SDimitry Andric     else if (D && D->getType().isConstQualified())
3806*0b57cec5SDimitry Andric       return LangAS::cuda_constant;
3807*0b57cec5SDimitry Andric     else
3808*0b57cec5SDimitry Andric       return LangAS::cuda_device;
3809*0b57cec5SDimitry Andric   }
3810*0b57cec5SDimitry Andric 
3811*0b57cec5SDimitry Andric   if (LangOpts.OpenMP) {
3812*0b57cec5SDimitry Andric     LangAS AS;
3813*0b57cec5SDimitry Andric     if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
3814*0b57cec5SDimitry Andric       return AS;
3815*0b57cec5SDimitry Andric   }
3816*0b57cec5SDimitry Andric   return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
3817*0b57cec5SDimitry Andric }
3818*0b57cec5SDimitry Andric 
3819*0b57cec5SDimitry Andric LangAS CodeGenModule::getStringLiteralAddressSpace() const {
3820*0b57cec5SDimitry Andric   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3821*0b57cec5SDimitry Andric   if (LangOpts.OpenCL)
3822*0b57cec5SDimitry Andric     return LangAS::opencl_constant;
3823*0b57cec5SDimitry Andric   if (auto AS = getTarget().getConstantAddressSpace())
3824*0b57cec5SDimitry Andric     return AS.getValue();
3825*0b57cec5SDimitry Andric   return LangAS::Default;
3826*0b57cec5SDimitry Andric }
3827*0b57cec5SDimitry Andric 
3828*0b57cec5SDimitry Andric // In address space agnostic languages, string literals are in default address
3829*0b57cec5SDimitry Andric // space in AST. However, certain targets (e.g. amdgcn) request them to be
3830*0b57cec5SDimitry Andric // emitted in constant address space in LLVM IR. To be consistent with other
3831*0b57cec5SDimitry Andric // parts of AST, string literal global variables in constant address space
3832*0b57cec5SDimitry Andric // need to be casted to default address space before being put into address
3833*0b57cec5SDimitry Andric // map and referenced by other part of CodeGen.
3834*0b57cec5SDimitry Andric // In OpenCL, string literals are in constant address space in AST, therefore
3835*0b57cec5SDimitry Andric // they should not be casted to default address space.
3836*0b57cec5SDimitry Andric static llvm::Constant *
3837*0b57cec5SDimitry Andric castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
3838*0b57cec5SDimitry Andric                                        llvm::GlobalVariable *GV) {
3839*0b57cec5SDimitry Andric   llvm::Constant *Cast = GV;
3840*0b57cec5SDimitry Andric   if (!CGM.getLangOpts().OpenCL) {
3841*0b57cec5SDimitry Andric     if (auto AS = CGM.getTarget().getConstantAddressSpace()) {
3842*0b57cec5SDimitry Andric       if (AS != LangAS::Default)
3843*0b57cec5SDimitry Andric         Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
3844*0b57cec5SDimitry Andric             CGM, GV, AS.getValue(), LangAS::Default,
3845*0b57cec5SDimitry Andric             GV->getValueType()->getPointerTo(
3846*0b57cec5SDimitry Andric                 CGM.getContext().getTargetAddressSpace(LangAS::Default)));
3847*0b57cec5SDimitry Andric     }
3848*0b57cec5SDimitry Andric   }
3849*0b57cec5SDimitry Andric   return Cast;
3850*0b57cec5SDimitry Andric }
3851*0b57cec5SDimitry Andric 
3852*0b57cec5SDimitry Andric template<typename SomeDecl>
3853*0b57cec5SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
3854*0b57cec5SDimitry Andric                                                llvm::GlobalValue *GV) {
3855*0b57cec5SDimitry Andric   if (!getLangOpts().CPlusPlus)
3856*0b57cec5SDimitry Andric     return;
3857*0b57cec5SDimitry Andric 
3858*0b57cec5SDimitry Andric   // Must have 'used' attribute, or else inline assembly can't rely on
3859*0b57cec5SDimitry Andric   // the name existing.
3860*0b57cec5SDimitry Andric   if (!D->template hasAttr<UsedAttr>())
3861*0b57cec5SDimitry Andric     return;
3862*0b57cec5SDimitry Andric 
3863*0b57cec5SDimitry Andric   // Must have internal linkage and an ordinary name.
3864*0b57cec5SDimitry Andric   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
3865*0b57cec5SDimitry Andric     return;
3866*0b57cec5SDimitry Andric 
3867*0b57cec5SDimitry Andric   // Must be in an extern "C" context. Entities declared directly within
3868*0b57cec5SDimitry Andric   // a record are not extern "C" even if the record is in such a context.
3869*0b57cec5SDimitry Andric   const SomeDecl *First = D->getFirstDecl();
3870*0b57cec5SDimitry Andric   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
3871*0b57cec5SDimitry Andric     return;
3872*0b57cec5SDimitry Andric 
3873*0b57cec5SDimitry Andric   // OK, this is an internal linkage entity inside an extern "C" linkage
3874*0b57cec5SDimitry Andric   // specification. Make a note of that so we can give it the "expected"
3875*0b57cec5SDimitry Andric   // mangled name if nothing else is using that name.
3876*0b57cec5SDimitry Andric   std::pair<StaticExternCMap::iterator, bool> R =
3877*0b57cec5SDimitry Andric       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
3878*0b57cec5SDimitry Andric 
3879*0b57cec5SDimitry Andric   // If we have multiple internal linkage entities with the same name
3880*0b57cec5SDimitry Andric   // in extern "C" regions, none of them gets that name.
3881*0b57cec5SDimitry Andric   if (!R.second)
3882*0b57cec5SDimitry Andric     R.first->second = nullptr;
3883*0b57cec5SDimitry Andric }
3884*0b57cec5SDimitry Andric 
3885*0b57cec5SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
3886*0b57cec5SDimitry Andric   if (!CGM.supportsCOMDAT())
3887*0b57cec5SDimitry Andric     return false;
3888*0b57cec5SDimitry Andric 
3889*0b57cec5SDimitry Andric   // Do not set COMDAT attribute for CUDA/HIP stub functions to prevent
3890*0b57cec5SDimitry Andric   // them being "merged" by the COMDAT Folding linker optimization.
3891*0b57cec5SDimitry Andric   if (D.hasAttr<CUDAGlobalAttr>())
3892*0b57cec5SDimitry Andric     return false;
3893*0b57cec5SDimitry Andric 
3894*0b57cec5SDimitry Andric   if (D.hasAttr<SelectAnyAttr>())
3895*0b57cec5SDimitry Andric     return true;
3896*0b57cec5SDimitry Andric 
3897*0b57cec5SDimitry Andric   GVALinkage Linkage;
3898*0b57cec5SDimitry Andric   if (auto *VD = dyn_cast<VarDecl>(&D))
3899*0b57cec5SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
3900*0b57cec5SDimitry Andric   else
3901*0b57cec5SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
3902*0b57cec5SDimitry Andric 
3903*0b57cec5SDimitry Andric   switch (Linkage) {
3904*0b57cec5SDimitry Andric   case GVA_Internal:
3905*0b57cec5SDimitry Andric   case GVA_AvailableExternally:
3906*0b57cec5SDimitry Andric   case GVA_StrongExternal:
3907*0b57cec5SDimitry Andric     return false;
3908*0b57cec5SDimitry Andric   case GVA_DiscardableODR:
3909*0b57cec5SDimitry Andric   case GVA_StrongODR:
3910*0b57cec5SDimitry Andric     return true;
3911*0b57cec5SDimitry Andric   }
3912*0b57cec5SDimitry Andric   llvm_unreachable("No such linkage");
3913*0b57cec5SDimitry Andric }
3914*0b57cec5SDimitry Andric 
3915*0b57cec5SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
3916*0b57cec5SDimitry Andric                                           llvm::GlobalObject &GO) {
3917*0b57cec5SDimitry Andric   if (!shouldBeInCOMDAT(*this, D))
3918*0b57cec5SDimitry Andric     return;
3919*0b57cec5SDimitry Andric   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
3920*0b57cec5SDimitry Andric }
3921*0b57cec5SDimitry Andric 
3922*0b57cec5SDimitry Andric /// Pass IsTentative as true if you want to create a tentative definition.
3923*0b57cec5SDimitry Andric void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
3924*0b57cec5SDimitry Andric                                             bool IsTentative) {
3925*0b57cec5SDimitry Andric   // OpenCL global variables of sampler type are translated to function calls,
3926*0b57cec5SDimitry Andric   // therefore no need to be translated.
3927*0b57cec5SDimitry Andric   QualType ASTTy = D->getType();
3928*0b57cec5SDimitry Andric   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
3929*0b57cec5SDimitry Andric     return;
3930*0b57cec5SDimitry Andric 
3931*0b57cec5SDimitry Andric   // If this is OpenMP device, check if it is legal to emit this global
3932*0b57cec5SDimitry Andric   // normally.
3933*0b57cec5SDimitry Andric   if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
3934*0b57cec5SDimitry Andric       OpenMPRuntime->emitTargetGlobalVariable(D))
3935*0b57cec5SDimitry Andric     return;
3936*0b57cec5SDimitry Andric 
3937*0b57cec5SDimitry Andric   llvm::Constant *Init = nullptr;
3938*0b57cec5SDimitry Andric   bool NeedsGlobalCtor = false;
3939a7dea167SDimitry Andric   bool NeedsGlobalDtor =
3940a7dea167SDimitry Andric       D->needsDestruction(getContext()) == QualType::DK_cxx_destructor;
3941*0b57cec5SDimitry Andric 
3942*0b57cec5SDimitry Andric   const VarDecl *InitDecl;
3943*0b57cec5SDimitry Andric   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
3944*0b57cec5SDimitry Andric 
3945*0b57cec5SDimitry Andric   Optional<ConstantEmitter> emitter;
3946*0b57cec5SDimitry Andric 
3947*0b57cec5SDimitry Andric   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
3948*0b57cec5SDimitry Andric   // as part of their declaration."  Sema has already checked for
3949*0b57cec5SDimitry Andric   // error cases, so we just need to set Init to UndefValue.
3950*0b57cec5SDimitry Andric   bool IsCUDASharedVar =
3951*0b57cec5SDimitry Andric       getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
3952*0b57cec5SDimitry Andric   // Shadows of initialized device-side global variables are also left
3953*0b57cec5SDimitry Andric   // undefined.
3954*0b57cec5SDimitry Andric   bool IsCUDAShadowVar =
3955*0b57cec5SDimitry Andric       !getLangOpts().CUDAIsDevice &&
3956*0b57cec5SDimitry Andric       (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
3957*0b57cec5SDimitry Andric        D->hasAttr<CUDASharedAttr>());
39585ffd83dbSDimitry Andric   bool IsCUDADeviceShadowVar =
39595ffd83dbSDimitry Andric       getLangOpts().CUDAIsDevice &&
39605ffd83dbSDimitry Andric       (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
39615ffd83dbSDimitry Andric        D->getType()->isCUDADeviceBuiltinTextureType());
3962*0b57cec5SDimitry Andric   // HIP pinned shadow of initialized host-side global variables are also
3963*0b57cec5SDimitry Andric   // left undefined.
3964*0b57cec5SDimitry Andric   if (getLangOpts().CUDA &&
39655ffd83dbSDimitry Andric       (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar))
39665ffd83dbSDimitry Andric     Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
39675ffd83dbSDimitry Andric   else if (D->hasAttr<LoaderUninitializedAttr>())
3968*0b57cec5SDimitry Andric     Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
3969*0b57cec5SDimitry Andric   else if (!InitExpr) {
3970*0b57cec5SDimitry Andric     // This is a tentative definition; tentative definitions are
3971*0b57cec5SDimitry Andric     // implicitly initialized with { 0 }.
3972*0b57cec5SDimitry Andric     //
3973*0b57cec5SDimitry Andric     // Note that tentative definitions are only emitted at the end of
3974*0b57cec5SDimitry Andric     // a translation unit, so they should never have incomplete
3975*0b57cec5SDimitry Andric     // type. In addition, EmitTentativeDefinition makes sure that we
3976*0b57cec5SDimitry Andric     // never attempt to emit a tentative definition if a real one
3977*0b57cec5SDimitry Andric     // exists. A use may still exists, however, so we still may need
3978*0b57cec5SDimitry Andric     // to do a RAUW.
3979*0b57cec5SDimitry Andric     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
3980*0b57cec5SDimitry Andric     Init = EmitNullConstant(D->getType());
3981*0b57cec5SDimitry Andric   } else {
3982*0b57cec5SDimitry Andric     initializedGlobalDecl = GlobalDecl(D);
3983*0b57cec5SDimitry Andric     emitter.emplace(*this);
3984*0b57cec5SDimitry Andric     Init = emitter->tryEmitForInitializer(*InitDecl);
3985*0b57cec5SDimitry Andric 
3986*0b57cec5SDimitry Andric     if (!Init) {
3987*0b57cec5SDimitry Andric       QualType T = InitExpr->getType();
3988*0b57cec5SDimitry Andric       if (D->getType()->isReferenceType())
3989*0b57cec5SDimitry Andric         T = D->getType();
3990*0b57cec5SDimitry Andric 
3991*0b57cec5SDimitry Andric       if (getLangOpts().CPlusPlus) {
3992*0b57cec5SDimitry Andric         Init = EmitNullConstant(T);
3993*0b57cec5SDimitry Andric         NeedsGlobalCtor = true;
3994*0b57cec5SDimitry Andric       } else {
3995*0b57cec5SDimitry Andric         ErrorUnsupported(D, "static initializer");
3996*0b57cec5SDimitry Andric         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
3997*0b57cec5SDimitry Andric       }
3998*0b57cec5SDimitry Andric     } else {
3999*0b57cec5SDimitry Andric       // We don't need an initializer, so remove the entry for the delayed
4000*0b57cec5SDimitry Andric       // initializer position (just in case this entry was delayed) if we
4001*0b57cec5SDimitry Andric       // also don't need to register a destructor.
4002*0b57cec5SDimitry Andric       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
4003*0b57cec5SDimitry Andric         DelayedCXXInitPosition.erase(D);
4004*0b57cec5SDimitry Andric     }
4005*0b57cec5SDimitry Andric   }
4006*0b57cec5SDimitry Andric 
4007*0b57cec5SDimitry Andric   llvm::Type* InitType = Init->getType();
4008*0b57cec5SDimitry Andric   llvm::Constant *Entry =
4009*0b57cec5SDimitry Andric       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
4010*0b57cec5SDimitry Andric 
4011a7dea167SDimitry Andric   // Strip off pointer casts if we got them.
4012a7dea167SDimitry Andric   Entry = Entry->stripPointerCasts();
4013*0b57cec5SDimitry Andric 
4014*0b57cec5SDimitry Andric   // Entry is now either a Function or GlobalVariable.
4015*0b57cec5SDimitry Andric   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
4016*0b57cec5SDimitry Andric 
4017*0b57cec5SDimitry Andric   // We have a definition after a declaration with the wrong type.
4018*0b57cec5SDimitry Andric   // We must make a new GlobalVariable* and update everything that used OldGV
4019*0b57cec5SDimitry Andric   // (a declaration or tentative definition) with the new GlobalVariable*
4020*0b57cec5SDimitry Andric   // (which will be a definition).
4021*0b57cec5SDimitry Andric   //
4022*0b57cec5SDimitry Andric   // This happens if there is a prototype for a global (e.g.
4023*0b57cec5SDimitry Andric   // "extern int x[];") and then a definition of a different type (e.g.
4024*0b57cec5SDimitry Andric   // "int x[10];"). This also happens when an initializer has a different type
4025*0b57cec5SDimitry Andric   // from the type of the global (this happens with unions).
40265ffd83dbSDimitry Andric   if (!GV || GV->getValueType() != InitType ||
4027*0b57cec5SDimitry Andric       GV->getType()->getAddressSpace() !=
4028*0b57cec5SDimitry Andric           getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
4029*0b57cec5SDimitry Andric 
4030*0b57cec5SDimitry Andric     // Move the old entry aside so that we'll create a new one.
4031*0b57cec5SDimitry Andric     Entry->setName(StringRef());
4032*0b57cec5SDimitry Andric 
4033*0b57cec5SDimitry Andric     // Make a new global with the correct type, this is now guaranteed to work.
4034*0b57cec5SDimitry Andric     GV = cast<llvm::GlobalVariable>(
4035a7dea167SDimitry Andric         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))
4036a7dea167SDimitry Andric             ->stripPointerCasts());
4037*0b57cec5SDimitry Andric 
4038*0b57cec5SDimitry Andric     // Replace all uses of the old global with the new global
4039*0b57cec5SDimitry Andric     llvm::Constant *NewPtrForOldDecl =
4040*0b57cec5SDimitry Andric         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
4041*0b57cec5SDimitry Andric     Entry->replaceAllUsesWith(NewPtrForOldDecl);
4042*0b57cec5SDimitry Andric 
4043*0b57cec5SDimitry Andric     // Erase the old global, since it is no longer used.
4044*0b57cec5SDimitry Andric     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
4045*0b57cec5SDimitry Andric   }
4046*0b57cec5SDimitry Andric 
4047*0b57cec5SDimitry Andric   MaybeHandleStaticInExternC(D, GV);
4048*0b57cec5SDimitry Andric 
4049*0b57cec5SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
4050*0b57cec5SDimitry Andric     AddGlobalAnnotations(D, GV);
4051*0b57cec5SDimitry Andric 
4052*0b57cec5SDimitry Andric   // Set the llvm linkage type as appropriate.
4053*0b57cec5SDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
4054*0b57cec5SDimitry Andric       getLLVMLinkageVarDefinition(D, GV->isConstant());
4055*0b57cec5SDimitry Andric 
4056*0b57cec5SDimitry Andric   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
4057*0b57cec5SDimitry Andric   // the device. [...]"
4058*0b57cec5SDimitry Andric   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
4059*0b57cec5SDimitry Andric   // __device__, declares a variable that: [...]
4060*0b57cec5SDimitry Andric   // Is accessible from all the threads within the grid and from the host
4061*0b57cec5SDimitry Andric   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
4062*0b57cec5SDimitry Andric   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
4063*0b57cec5SDimitry Andric   if (GV && LangOpts.CUDA) {
4064*0b57cec5SDimitry Andric     if (LangOpts.CUDAIsDevice) {
4065*0b57cec5SDimitry Andric       if (Linkage != llvm::GlobalValue::InternalLinkage &&
4066*0b57cec5SDimitry Andric           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()))
4067*0b57cec5SDimitry Andric         GV->setExternallyInitialized(true);
4068*0b57cec5SDimitry Andric     } else {
4069*0b57cec5SDimitry Andric       // Host-side shadows of external declarations of device-side
4070*0b57cec5SDimitry Andric       // global variables become internal definitions. These have to
4071*0b57cec5SDimitry Andric       // be internal in order to prevent name conflicts with global
4072*0b57cec5SDimitry Andric       // host variables with the same name in a different TUs.
40735ffd83dbSDimitry Andric       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
4074*0b57cec5SDimitry Andric         Linkage = llvm::GlobalValue::InternalLinkage;
40755ffd83dbSDimitry Andric         // Shadow variables and their properties must be registered with CUDA
40765ffd83dbSDimitry Andric         // runtime. Skip Extern global variables, which will be registered in
40775ffd83dbSDimitry Andric         // the TU where they are defined.
4078*0b57cec5SDimitry Andric         if (!D->hasExternalStorage())
40795ffd83dbSDimitry Andric           getCUDARuntime().registerDeviceVar(D, *GV, !D->hasDefinition(),
40805ffd83dbSDimitry Andric                                              D->hasAttr<CUDAConstantAttr>());
40815ffd83dbSDimitry Andric       } else if (D->hasAttr<CUDASharedAttr>()) {
4082*0b57cec5SDimitry Andric         // __shared__ variables are odd. Shadows do get created, but
4083*0b57cec5SDimitry Andric         // they are not registered with the CUDA runtime, so they
4084*0b57cec5SDimitry Andric         // can't really be used to access their device-side
4085*0b57cec5SDimitry Andric         // counterparts. It's not clear yet whether it's nvcc's bug or
4086*0b57cec5SDimitry Andric         // a feature, but we've got to do the same for compatibility.
4087*0b57cec5SDimitry Andric         Linkage = llvm::GlobalValue::InternalLinkage;
40885ffd83dbSDimitry Andric       } else if (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
40895ffd83dbSDimitry Andric                  D->getType()->isCUDADeviceBuiltinTextureType()) {
40905ffd83dbSDimitry Andric         // Builtin surfaces and textures and their template arguments are
40915ffd83dbSDimitry Andric         // also registered with CUDA runtime.
40925ffd83dbSDimitry Andric         Linkage = llvm::GlobalValue::InternalLinkage;
40935ffd83dbSDimitry Andric         const ClassTemplateSpecializationDecl *TD =
40945ffd83dbSDimitry Andric             cast<ClassTemplateSpecializationDecl>(
40955ffd83dbSDimitry Andric                 D->getType()->getAs<RecordType>()->getDecl());
40965ffd83dbSDimitry Andric         const TemplateArgumentList &Args = TD->getTemplateArgs();
40975ffd83dbSDimitry Andric         if (TD->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) {
40985ffd83dbSDimitry Andric           assert(Args.size() == 2 &&
40995ffd83dbSDimitry Andric                  "Unexpected number of template arguments of CUDA device "
41005ffd83dbSDimitry Andric                  "builtin surface type.");
41015ffd83dbSDimitry Andric           auto SurfType = Args[1].getAsIntegral();
41025ffd83dbSDimitry Andric           if (!D->hasExternalStorage())
41035ffd83dbSDimitry Andric             getCUDARuntime().registerDeviceSurf(D, *GV, !D->hasDefinition(),
41045ffd83dbSDimitry Andric                                                 SurfType.getSExtValue());
41055ffd83dbSDimitry Andric         } else {
41065ffd83dbSDimitry Andric           assert(Args.size() == 3 &&
41075ffd83dbSDimitry Andric                  "Unexpected number of template arguments of CUDA device "
41085ffd83dbSDimitry Andric                  "builtin texture type.");
41095ffd83dbSDimitry Andric           auto TexType = Args[1].getAsIntegral();
41105ffd83dbSDimitry Andric           auto Normalized = Args[2].getAsIntegral();
41115ffd83dbSDimitry Andric           if (!D->hasExternalStorage())
41125ffd83dbSDimitry Andric             getCUDARuntime().registerDeviceTex(D, *GV, !D->hasDefinition(),
41135ffd83dbSDimitry Andric                                                TexType.getSExtValue(),
41145ffd83dbSDimitry Andric                                                Normalized.getZExtValue());
41155ffd83dbSDimitry Andric         }
41165ffd83dbSDimitry Andric       }
4117*0b57cec5SDimitry Andric     }
4118*0b57cec5SDimitry Andric   }
4119*0b57cec5SDimitry Andric 
4120*0b57cec5SDimitry Andric   GV->setInitializer(Init);
41215ffd83dbSDimitry Andric   if (emitter)
41225ffd83dbSDimitry Andric     emitter->finalize(GV);
4123*0b57cec5SDimitry Andric 
4124*0b57cec5SDimitry Andric   // If it is safe to mark the global 'constant', do so now.
4125*0b57cec5SDimitry Andric   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
4126*0b57cec5SDimitry Andric                   isTypeConstant(D->getType(), true));
4127*0b57cec5SDimitry Andric 
4128*0b57cec5SDimitry Andric   // If it is in a read-only section, mark it 'constant'.
4129*0b57cec5SDimitry Andric   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
4130*0b57cec5SDimitry Andric     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
4131*0b57cec5SDimitry Andric     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
4132*0b57cec5SDimitry Andric       GV->setConstant(true);
4133*0b57cec5SDimitry Andric   }
4134*0b57cec5SDimitry Andric 
4135a7dea167SDimitry Andric   GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
4136*0b57cec5SDimitry Andric 
41375ffd83dbSDimitry Andric   // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper
41385ffd83dbSDimitry Andric   // function is only defined alongside the variable, not also alongside
41395ffd83dbSDimitry Andric   // callers. Normally, all accesses to a thread_local go through the
41405ffd83dbSDimitry Andric   // thread-wrapper in order to ensure initialization has occurred, underlying
41415ffd83dbSDimitry Andric   // variable will never be used other than the thread-wrapper, so it can be
41425ffd83dbSDimitry Andric   // converted to internal linkage.
41435ffd83dbSDimitry Andric   //
41445ffd83dbSDimitry Andric   // However, if the variable has the 'constinit' attribute, it _can_ be
41455ffd83dbSDimitry Andric   // referenced directly, without calling the thread-wrapper, so the linkage
41465ffd83dbSDimitry Andric   // must not be changed.
41475ffd83dbSDimitry Andric   //
41485ffd83dbSDimitry Andric   // Additionally, if the variable isn't plain external linkage, e.g. if it's
41495ffd83dbSDimitry Andric   // weak or linkonce, the de-duplication semantics are important to preserve,
41505ffd83dbSDimitry Andric   // so we don't change the linkage.
41515ffd83dbSDimitry Andric   if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
41525ffd83dbSDimitry Andric       Linkage == llvm::GlobalValue::ExternalLinkage &&
4153*0b57cec5SDimitry Andric       Context.getTargetInfo().getTriple().isOSDarwin() &&
41545ffd83dbSDimitry Andric       !D->hasAttr<ConstInitAttr>())
4155*0b57cec5SDimitry Andric     Linkage = llvm::GlobalValue::InternalLinkage;
4156*0b57cec5SDimitry Andric 
4157*0b57cec5SDimitry Andric   GV->setLinkage(Linkage);
4158*0b57cec5SDimitry Andric   if (D->hasAttr<DLLImportAttr>())
4159*0b57cec5SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
4160*0b57cec5SDimitry Andric   else if (D->hasAttr<DLLExportAttr>())
4161*0b57cec5SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
4162*0b57cec5SDimitry Andric   else
4163*0b57cec5SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
4164*0b57cec5SDimitry Andric 
4165*0b57cec5SDimitry Andric   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
4166*0b57cec5SDimitry Andric     // common vars aren't constant even if declared const.
4167*0b57cec5SDimitry Andric     GV->setConstant(false);
4168*0b57cec5SDimitry Andric     // Tentative definition of global variables may be initialized with
4169*0b57cec5SDimitry Andric     // non-zero null pointers. In this case they should have weak linkage
4170*0b57cec5SDimitry Andric     // since common linkage must have zero initializer and must not have
4171*0b57cec5SDimitry Andric     // explicit section therefore cannot have non-zero initial value.
4172*0b57cec5SDimitry Andric     if (!GV->getInitializer()->isNullValue())
4173*0b57cec5SDimitry Andric       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
4174*0b57cec5SDimitry Andric   }
4175*0b57cec5SDimitry Andric 
4176*0b57cec5SDimitry Andric   setNonAliasAttributes(D, GV);
4177*0b57cec5SDimitry Andric 
4178*0b57cec5SDimitry Andric   if (D->getTLSKind() && !GV->isThreadLocal()) {
4179*0b57cec5SDimitry Andric     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
4180*0b57cec5SDimitry Andric       CXXThreadLocals.push_back(D);
4181*0b57cec5SDimitry Andric     setTLSMode(GV, *D);
4182*0b57cec5SDimitry Andric   }
4183*0b57cec5SDimitry Andric 
4184*0b57cec5SDimitry Andric   maybeSetTrivialComdat(*D, *GV);
4185*0b57cec5SDimitry Andric 
4186*0b57cec5SDimitry Andric   // Emit the initializer function if necessary.
4187*0b57cec5SDimitry Andric   if (NeedsGlobalCtor || NeedsGlobalDtor)
4188*0b57cec5SDimitry Andric     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
4189*0b57cec5SDimitry Andric 
4190*0b57cec5SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
4191*0b57cec5SDimitry Andric 
4192*0b57cec5SDimitry Andric   // Emit global variable debug information.
4193*0b57cec5SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
4194480093f4SDimitry Andric     if (getCodeGenOpts().hasReducedDebugInfo())
4195*0b57cec5SDimitry Andric       DI->EmitGlobalVariable(GV, D);
4196*0b57cec5SDimitry Andric }
4197*0b57cec5SDimitry Andric 
4198480093f4SDimitry Andric void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) {
4199480093f4SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
4200480093f4SDimitry Andric     if (getCodeGenOpts().hasReducedDebugInfo()) {
4201480093f4SDimitry Andric       QualType ASTTy = D->getType();
4202480093f4SDimitry Andric       llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
4203480093f4SDimitry Andric       llvm::PointerType *PTy =
4204480093f4SDimitry Andric           llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
4205480093f4SDimitry Andric       llvm::Constant *GV = GetOrCreateLLVMGlobal(D->getName(), PTy, D);
4206480093f4SDimitry Andric       DI->EmitExternalVariable(
4207480093f4SDimitry Andric           cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D);
4208480093f4SDimitry Andric     }
4209480093f4SDimitry Andric }
4210480093f4SDimitry Andric 
4211*0b57cec5SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context,
4212*0b57cec5SDimitry Andric                                       CodeGenModule &CGM, const VarDecl *D,
4213*0b57cec5SDimitry Andric                                       bool NoCommon) {
4214*0b57cec5SDimitry Andric   // Don't give variables common linkage if -fno-common was specified unless it
4215*0b57cec5SDimitry Andric   // was overridden by a NoCommon attribute.
4216*0b57cec5SDimitry Andric   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
4217*0b57cec5SDimitry Andric     return true;
4218*0b57cec5SDimitry Andric 
4219*0b57cec5SDimitry Andric   // C11 6.9.2/2:
4220*0b57cec5SDimitry Andric   //   A declaration of an identifier for an object that has file scope without
4221*0b57cec5SDimitry Andric   //   an initializer, and without a storage-class specifier or with the
4222*0b57cec5SDimitry Andric   //   storage-class specifier static, constitutes a tentative definition.
4223*0b57cec5SDimitry Andric   if (D->getInit() || D->hasExternalStorage())
4224*0b57cec5SDimitry Andric     return true;
4225*0b57cec5SDimitry Andric 
4226*0b57cec5SDimitry Andric   // A variable cannot be both common and exist in a section.
4227*0b57cec5SDimitry Andric   if (D->hasAttr<SectionAttr>())
4228*0b57cec5SDimitry Andric     return true;
4229*0b57cec5SDimitry Andric 
4230*0b57cec5SDimitry Andric   // A variable cannot be both common and exist in a section.
4231*0b57cec5SDimitry Andric   // We don't try to determine which is the right section in the front-end.
4232*0b57cec5SDimitry Andric   // If no specialized section name is applicable, it will resort to default.
4233*0b57cec5SDimitry Andric   if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
4234*0b57cec5SDimitry Andric       D->hasAttr<PragmaClangDataSectionAttr>() ||
4235a7dea167SDimitry Andric       D->hasAttr<PragmaClangRelroSectionAttr>() ||
4236*0b57cec5SDimitry Andric       D->hasAttr<PragmaClangRodataSectionAttr>())
4237*0b57cec5SDimitry Andric     return true;
4238*0b57cec5SDimitry Andric 
4239*0b57cec5SDimitry Andric   // Thread local vars aren't considered common linkage.
4240*0b57cec5SDimitry Andric   if (D->getTLSKind())
4241*0b57cec5SDimitry Andric     return true;
4242*0b57cec5SDimitry Andric 
4243*0b57cec5SDimitry Andric   // Tentative definitions marked with WeakImportAttr are true definitions.
4244*0b57cec5SDimitry Andric   if (D->hasAttr<WeakImportAttr>())
4245*0b57cec5SDimitry Andric     return true;
4246*0b57cec5SDimitry Andric 
4247*0b57cec5SDimitry Andric   // A variable cannot be both common and exist in a comdat.
4248*0b57cec5SDimitry Andric   if (shouldBeInCOMDAT(CGM, *D))
4249*0b57cec5SDimitry Andric     return true;
4250*0b57cec5SDimitry Andric 
4251*0b57cec5SDimitry Andric   // Declarations with a required alignment do not have common linkage in MSVC
4252*0b57cec5SDimitry Andric   // mode.
4253*0b57cec5SDimitry Andric   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4254*0b57cec5SDimitry Andric     if (D->hasAttr<AlignedAttr>())
4255*0b57cec5SDimitry Andric       return true;
4256*0b57cec5SDimitry Andric     QualType VarType = D->getType();
4257*0b57cec5SDimitry Andric     if (Context.isAlignmentRequired(VarType))
4258*0b57cec5SDimitry Andric       return true;
4259*0b57cec5SDimitry Andric 
4260*0b57cec5SDimitry Andric     if (const auto *RT = VarType->getAs<RecordType>()) {
4261*0b57cec5SDimitry Andric       const RecordDecl *RD = RT->getDecl();
4262*0b57cec5SDimitry Andric       for (const FieldDecl *FD : RD->fields()) {
4263*0b57cec5SDimitry Andric         if (FD->isBitField())
4264*0b57cec5SDimitry Andric           continue;
4265*0b57cec5SDimitry Andric         if (FD->hasAttr<AlignedAttr>())
4266*0b57cec5SDimitry Andric           return true;
4267*0b57cec5SDimitry Andric         if (Context.isAlignmentRequired(FD->getType()))
4268*0b57cec5SDimitry Andric           return true;
4269*0b57cec5SDimitry Andric       }
4270*0b57cec5SDimitry Andric     }
4271*0b57cec5SDimitry Andric   }
4272*0b57cec5SDimitry Andric 
4273*0b57cec5SDimitry Andric   // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
4274*0b57cec5SDimitry Andric   // common symbols, so symbols with greater alignment requirements cannot be
4275*0b57cec5SDimitry Andric   // common.
4276*0b57cec5SDimitry Andric   // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
4277*0b57cec5SDimitry Andric   // alignments for common symbols via the aligncomm directive, so this
4278*0b57cec5SDimitry Andric   // restriction only applies to MSVC environments.
4279*0b57cec5SDimitry Andric   if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
4280*0b57cec5SDimitry Andric       Context.getTypeAlignIfKnown(D->getType()) >
4281*0b57cec5SDimitry Andric           Context.toBits(CharUnits::fromQuantity(32)))
4282*0b57cec5SDimitry Andric     return true;
4283*0b57cec5SDimitry Andric 
4284*0b57cec5SDimitry Andric   return false;
4285*0b57cec5SDimitry Andric }
4286*0b57cec5SDimitry Andric 
4287*0b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
4288*0b57cec5SDimitry Andric     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
4289*0b57cec5SDimitry Andric   if (Linkage == GVA_Internal)
4290*0b57cec5SDimitry Andric     return llvm::Function::InternalLinkage;
4291*0b57cec5SDimitry Andric 
4292*0b57cec5SDimitry Andric   if (D->hasAttr<WeakAttr>()) {
4293*0b57cec5SDimitry Andric     if (IsConstantVariable)
4294*0b57cec5SDimitry Andric       return llvm::GlobalVariable::WeakODRLinkage;
4295*0b57cec5SDimitry Andric     else
4296*0b57cec5SDimitry Andric       return llvm::GlobalVariable::WeakAnyLinkage;
4297*0b57cec5SDimitry Andric   }
4298*0b57cec5SDimitry Andric 
4299*0b57cec5SDimitry Andric   if (const auto *FD = D->getAsFunction())
4300*0b57cec5SDimitry Andric     if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
4301*0b57cec5SDimitry Andric       return llvm::GlobalVariable::LinkOnceAnyLinkage;
4302*0b57cec5SDimitry Andric 
4303*0b57cec5SDimitry Andric   // We are guaranteed to have a strong definition somewhere else,
4304*0b57cec5SDimitry Andric   // so we can use available_externally linkage.
4305*0b57cec5SDimitry Andric   if (Linkage == GVA_AvailableExternally)
4306*0b57cec5SDimitry Andric     return llvm::GlobalValue::AvailableExternallyLinkage;
4307*0b57cec5SDimitry Andric 
4308*0b57cec5SDimitry Andric   // Note that Apple's kernel linker doesn't support symbol
4309*0b57cec5SDimitry Andric   // coalescing, so we need to avoid linkonce and weak linkages there.
4310*0b57cec5SDimitry Andric   // Normally, this means we just map to internal, but for explicit
4311*0b57cec5SDimitry Andric   // instantiations we'll map to external.
4312*0b57cec5SDimitry Andric 
4313*0b57cec5SDimitry Andric   // In C++, the compiler has to emit a definition in every translation unit
4314*0b57cec5SDimitry Andric   // that references the function.  We should use linkonce_odr because
4315*0b57cec5SDimitry Andric   // a) if all references in this translation unit are optimized away, we
4316*0b57cec5SDimitry Andric   // don't need to codegen it.  b) if the function persists, it needs to be
4317*0b57cec5SDimitry Andric   // merged with other definitions. c) C++ has the ODR, so we know the
4318*0b57cec5SDimitry Andric   // definition is dependable.
4319*0b57cec5SDimitry Andric   if (Linkage == GVA_DiscardableODR)
4320*0b57cec5SDimitry Andric     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
4321*0b57cec5SDimitry Andric                                             : llvm::Function::InternalLinkage;
4322*0b57cec5SDimitry Andric 
4323*0b57cec5SDimitry Andric   // An explicit instantiation of a template has weak linkage, since
4324*0b57cec5SDimitry Andric   // explicit instantiations can occur in multiple translation units
4325*0b57cec5SDimitry Andric   // and must all be equivalent. However, we are not allowed to
4326*0b57cec5SDimitry Andric   // throw away these explicit instantiations.
4327*0b57cec5SDimitry Andric   //
4328*0b57cec5SDimitry Andric   // We don't currently support CUDA device code spread out across multiple TUs,
4329*0b57cec5SDimitry Andric   // so say that CUDA templates are either external (for kernels) or internal.
4330*0b57cec5SDimitry Andric   // This lets llvm perform aggressive inter-procedural optimizations.
4331*0b57cec5SDimitry Andric   if (Linkage == GVA_StrongODR) {
4332*0b57cec5SDimitry Andric     if (Context.getLangOpts().AppleKext)
4333*0b57cec5SDimitry Andric       return llvm::Function::ExternalLinkage;
4334*0b57cec5SDimitry Andric     if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
4335*0b57cec5SDimitry Andric       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
4336*0b57cec5SDimitry Andric                                           : llvm::Function::InternalLinkage;
4337*0b57cec5SDimitry Andric     return llvm::Function::WeakODRLinkage;
4338*0b57cec5SDimitry Andric   }
4339*0b57cec5SDimitry Andric 
4340*0b57cec5SDimitry Andric   // C++ doesn't have tentative definitions and thus cannot have common
4341*0b57cec5SDimitry Andric   // linkage.
4342*0b57cec5SDimitry Andric   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
4343*0b57cec5SDimitry Andric       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
4344*0b57cec5SDimitry Andric                                  CodeGenOpts.NoCommon))
4345*0b57cec5SDimitry Andric     return llvm::GlobalVariable::CommonLinkage;
4346*0b57cec5SDimitry Andric 
4347*0b57cec5SDimitry Andric   // selectany symbols are externally visible, so use weak instead of
4348*0b57cec5SDimitry Andric   // linkonce.  MSVC optimizes away references to const selectany globals, so
4349*0b57cec5SDimitry Andric   // all definitions should be the same and ODR linkage should be used.
4350*0b57cec5SDimitry Andric   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
4351*0b57cec5SDimitry Andric   if (D->hasAttr<SelectAnyAttr>())
4352*0b57cec5SDimitry Andric     return llvm::GlobalVariable::WeakODRLinkage;
4353*0b57cec5SDimitry Andric 
4354*0b57cec5SDimitry Andric   // Otherwise, we have strong external linkage.
4355*0b57cec5SDimitry Andric   assert(Linkage == GVA_StrongExternal);
4356*0b57cec5SDimitry Andric   return llvm::GlobalVariable::ExternalLinkage;
4357*0b57cec5SDimitry Andric }
4358*0b57cec5SDimitry Andric 
4359*0b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
4360*0b57cec5SDimitry Andric     const VarDecl *VD, bool IsConstant) {
4361*0b57cec5SDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
4362*0b57cec5SDimitry Andric   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
4363*0b57cec5SDimitry Andric }
4364*0b57cec5SDimitry Andric 
4365*0b57cec5SDimitry Andric /// Replace the uses of a function that was declared with a non-proto type.
4366*0b57cec5SDimitry Andric /// We want to silently drop extra arguments from call sites
4367*0b57cec5SDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
4368*0b57cec5SDimitry Andric                                           llvm::Function *newFn) {
4369*0b57cec5SDimitry Andric   // Fast path.
4370*0b57cec5SDimitry Andric   if (old->use_empty()) return;
4371*0b57cec5SDimitry Andric 
4372*0b57cec5SDimitry Andric   llvm::Type *newRetTy = newFn->getReturnType();
4373*0b57cec5SDimitry Andric   SmallVector<llvm::Value*, 4> newArgs;
4374*0b57cec5SDimitry Andric   SmallVector<llvm::OperandBundleDef, 1> newBundles;
4375*0b57cec5SDimitry Andric 
4376*0b57cec5SDimitry Andric   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
4377*0b57cec5SDimitry Andric          ui != ue; ) {
4378*0b57cec5SDimitry Andric     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
4379*0b57cec5SDimitry Andric     llvm::User *user = use->getUser();
4380*0b57cec5SDimitry Andric 
4381*0b57cec5SDimitry Andric     // Recognize and replace uses of bitcasts.  Most calls to
4382*0b57cec5SDimitry Andric     // unprototyped functions will use bitcasts.
4383*0b57cec5SDimitry Andric     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
4384*0b57cec5SDimitry Andric       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
4385*0b57cec5SDimitry Andric         replaceUsesOfNonProtoConstant(bitcast, newFn);
4386*0b57cec5SDimitry Andric       continue;
4387*0b57cec5SDimitry Andric     }
4388*0b57cec5SDimitry Andric 
4389*0b57cec5SDimitry Andric     // Recognize calls to the function.
4390*0b57cec5SDimitry Andric     llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
4391*0b57cec5SDimitry Andric     if (!callSite) continue;
4392*0b57cec5SDimitry Andric     if (!callSite->isCallee(&*use))
4393*0b57cec5SDimitry Andric       continue;
4394*0b57cec5SDimitry Andric 
4395*0b57cec5SDimitry Andric     // If the return types don't match exactly, then we can't
4396*0b57cec5SDimitry Andric     // transform this call unless it's dead.
4397*0b57cec5SDimitry Andric     if (callSite->getType() != newRetTy && !callSite->use_empty())
4398*0b57cec5SDimitry Andric       continue;
4399*0b57cec5SDimitry Andric 
4400*0b57cec5SDimitry Andric     // Get the call site's attribute list.
4401*0b57cec5SDimitry Andric     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
4402*0b57cec5SDimitry Andric     llvm::AttributeList oldAttrs = callSite->getAttributes();
4403*0b57cec5SDimitry Andric 
4404*0b57cec5SDimitry Andric     // If the function was passed too few arguments, don't transform.
4405*0b57cec5SDimitry Andric     unsigned newNumArgs = newFn->arg_size();
4406*0b57cec5SDimitry Andric     if (callSite->arg_size() < newNumArgs)
4407*0b57cec5SDimitry Andric       continue;
4408*0b57cec5SDimitry Andric 
4409*0b57cec5SDimitry Andric     // If extra arguments were passed, we silently drop them.
4410*0b57cec5SDimitry Andric     // If any of the types mismatch, we don't transform.
4411*0b57cec5SDimitry Andric     unsigned argNo = 0;
4412*0b57cec5SDimitry Andric     bool dontTransform = false;
4413*0b57cec5SDimitry Andric     for (llvm::Argument &A : newFn->args()) {
4414*0b57cec5SDimitry Andric       if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
4415*0b57cec5SDimitry Andric         dontTransform = true;
4416*0b57cec5SDimitry Andric         break;
4417*0b57cec5SDimitry Andric       }
4418*0b57cec5SDimitry Andric 
4419*0b57cec5SDimitry Andric       // Add any parameter attributes.
4420*0b57cec5SDimitry Andric       newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
4421*0b57cec5SDimitry Andric       argNo++;
4422*0b57cec5SDimitry Andric     }
4423*0b57cec5SDimitry Andric     if (dontTransform)
4424*0b57cec5SDimitry Andric       continue;
4425*0b57cec5SDimitry Andric 
4426*0b57cec5SDimitry Andric     // Okay, we can transform this.  Create the new call instruction and copy
4427*0b57cec5SDimitry Andric     // over the required information.
4428*0b57cec5SDimitry Andric     newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
4429*0b57cec5SDimitry Andric 
4430*0b57cec5SDimitry Andric     // Copy over any operand bundles.
4431*0b57cec5SDimitry Andric     callSite->getOperandBundlesAsDefs(newBundles);
4432*0b57cec5SDimitry Andric 
4433*0b57cec5SDimitry Andric     llvm::CallBase *newCall;
4434*0b57cec5SDimitry Andric     if (dyn_cast<llvm::CallInst>(callSite)) {
4435*0b57cec5SDimitry Andric       newCall =
4436*0b57cec5SDimitry Andric           llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
4437*0b57cec5SDimitry Andric     } else {
4438*0b57cec5SDimitry Andric       auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
4439*0b57cec5SDimitry Andric       newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
4440*0b57cec5SDimitry Andric                                          oldInvoke->getUnwindDest(), newArgs,
4441*0b57cec5SDimitry Andric                                          newBundles, "", callSite);
4442*0b57cec5SDimitry Andric     }
4443*0b57cec5SDimitry Andric     newArgs.clear(); // for the next iteration
4444*0b57cec5SDimitry Andric 
4445*0b57cec5SDimitry Andric     if (!newCall->getType()->isVoidTy())
4446*0b57cec5SDimitry Andric       newCall->takeName(callSite);
4447*0b57cec5SDimitry Andric     newCall->setAttributes(llvm::AttributeList::get(
4448*0b57cec5SDimitry Andric         newFn->getContext(), oldAttrs.getFnAttributes(),
4449*0b57cec5SDimitry Andric         oldAttrs.getRetAttributes(), newArgAttrs));
4450*0b57cec5SDimitry Andric     newCall->setCallingConv(callSite->getCallingConv());
4451*0b57cec5SDimitry Andric 
4452*0b57cec5SDimitry Andric     // Finally, remove the old call, replacing any uses with the new one.
4453*0b57cec5SDimitry Andric     if (!callSite->use_empty())
4454*0b57cec5SDimitry Andric       callSite->replaceAllUsesWith(newCall);
4455*0b57cec5SDimitry Andric 
4456*0b57cec5SDimitry Andric     // Copy debug location attached to CI.
4457*0b57cec5SDimitry Andric     if (callSite->getDebugLoc())
4458*0b57cec5SDimitry Andric       newCall->setDebugLoc(callSite->getDebugLoc());
4459*0b57cec5SDimitry Andric 
4460*0b57cec5SDimitry Andric     callSite->eraseFromParent();
4461*0b57cec5SDimitry Andric   }
4462*0b57cec5SDimitry Andric }
4463*0b57cec5SDimitry Andric 
4464*0b57cec5SDimitry Andric /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
4465*0b57cec5SDimitry Andric /// implement a function with no prototype, e.g. "int foo() {}".  If there are
4466*0b57cec5SDimitry Andric /// existing call uses of the old function in the module, this adjusts them to
4467*0b57cec5SDimitry Andric /// call the new function directly.
4468*0b57cec5SDimitry Andric ///
4469*0b57cec5SDimitry Andric /// This is not just a cleanup: the always_inline pass requires direct calls to
4470*0b57cec5SDimitry Andric /// functions to be able to inline them.  If there is a bitcast in the way, it
4471*0b57cec5SDimitry Andric /// won't inline them.  Instcombine normally deletes these calls, but it isn't
4472*0b57cec5SDimitry Andric /// run at -O0.
4473*0b57cec5SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
4474*0b57cec5SDimitry Andric                                                       llvm::Function *NewFn) {
4475*0b57cec5SDimitry Andric   // If we're redefining a global as a function, don't transform it.
4476*0b57cec5SDimitry Andric   if (!isa<llvm::Function>(Old)) return;
4477*0b57cec5SDimitry Andric 
4478*0b57cec5SDimitry Andric   replaceUsesOfNonProtoConstant(Old, NewFn);
4479*0b57cec5SDimitry Andric }
4480*0b57cec5SDimitry Andric 
4481*0b57cec5SDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
4482*0b57cec5SDimitry Andric   auto DK = VD->isThisDeclarationADefinition();
4483*0b57cec5SDimitry Andric   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
4484*0b57cec5SDimitry Andric     return;
4485*0b57cec5SDimitry Andric 
4486*0b57cec5SDimitry Andric   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
4487*0b57cec5SDimitry Andric   // If we have a definition, this might be a deferred decl. If the
4488*0b57cec5SDimitry Andric   // instantiation is explicit, make sure we emit it at the end.
4489*0b57cec5SDimitry Andric   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
4490*0b57cec5SDimitry Andric     GetAddrOfGlobalVar(VD);
4491*0b57cec5SDimitry Andric 
4492*0b57cec5SDimitry Andric   EmitTopLevelDecl(VD);
4493*0b57cec5SDimitry Andric }
4494*0b57cec5SDimitry Andric 
4495*0b57cec5SDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
4496*0b57cec5SDimitry Andric                                                  llvm::GlobalValue *GV) {
4497*0b57cec5SDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
4498*0b57cec5SDimitry Andric 
4499*0b57cec5SDimitry Andric   // Compute the function info and LLVM type.
4500*0b57cec5SDimitry Andric   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4501*0b57cec5SDimitry Andric   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
4502*0b57cec5SDimitry Andric 
4503*0b57cec5SDimitry Andric   // Get or create the prototype for the function.
45045ffd83dbSDimitry Andric   if (!GV || (GV->getValueType() != Ty))
4505*0b57cec5SDimitry Andric     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
4506*0b57cec5SDimitry Andric                                                    /*DontDefer=*/true,
4507*0b57cec5SDimitry Andric                                                    ForDefinition));
4508*0b57cec5SDimitry Andric 
4509*0b57cec5SDimitry Andric   // Already emitted.
4510*0b57cec5SDimitry Andric   if (!GV->isDeclaration())
4511*0b57cec5SDimitry Andric     return;
4512*0b57cec5SDimitry Andric 
4513*0b57cec5SDimitry Andric   // We need to set linkage and visibility on the function before
4514*0b57cec5SDimitry Andric   // generating code for it because various parts of IR generation
4515*0b57cec5SDimitry Andric   // want to propagate this information down (e.g. to local static
4516*0b57cec5SDimitry Andric   // declarations).
4517*0b57cec5SDimitry Andric   auto *Fn = cast<llvm::Function>(GV);
4518*0b57cec5SDimitry Andric   setFunctionLinkage(GD, Fn);
4519*0b57cec5SDimitry Andric 
4520*0b57cec5SDimitry Andric   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
4521*0b57cec5SDimitry Andric   setGVProperties(Fn, GD);
4522*0b57cec5SDimitry Andric 
4523*0b57cec5SDimitry Andric   MaybeHandleStaticInExternC(D, Fn);
4524*0b57cec5SDimitry Andric 
4525*0b57cec5SDimitry Andric 
4526*0b57cec5SDimitry Andric   maybeSetTrivialComdat(*D, *Fn);
4527*0b57cec5SDimitry Andric 
45285ffd83dbSDimitry Andric   CodeGenFunction(*this).GenerateCode(GD, Fn, FI);
4529*0b57cec5SDimitry Andric 
4530*0b57cec5SDimitry Andric   setNonAliasAttributes(GD, Fn);
4531*0b57cec5SDimitry Andric   SetLLVMFunctionAttributesForDefinition(D, Fn);
4532*0b57cec5SDimitry Andric 
4533*0b57cec5SDimitry Andric   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
4534*0b57cec5SDimitry Andric     AddGlobalCtor(Fn, CA->getPriority());
4535*0b57cec5SDimitry Andric   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
4536*0b57cec5SDimitry Andric     AddGlobalDtor(Fn, DA->getPriority());
4537*0b57cec5SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
4538*0b57cec5SDimitry Andric     AddGlobalAnnotations(D, Fn);
4539*0b57cec5SDimitry Andric }
4540*0b57cec5SDimitry Andric 
4541*0b57cec5SDimitry Andric void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
4542*0b57cec5SDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
4543*0b57cec5SDimitry Andric   const AliasAttr *AA = D->getAttr<AliasAttr>();
4544*0b57cec5SDimitry Andric   assert(AA && "Not an alias?");
4545*0b57cec5SDimitry Andric 
4546*0b57cec5SDimitry Andric   StringRef MangledName = getMangledName(GD);
4547*0b57cec5SDimitry Andric 
4548*0b57cec5SDimitry Andric   if (AA->getAliasee() == MangledName) {
4549*0b57cec5SDimitry Andric     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
4550*0b57cec5SDimitry Andric     return;
4551*0b57cec5SDimitry Andric   }
4552*0b57cec5SDimitry Andric 
4553*0b57cec5SDimitry Andric   // If there is a definition in the module, then it wins over the alias.
4554*0b57cec5SDimitry Andric   // This is dubious, but allow it to be safe.  Just ignore the alias.
4555*0b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4556*0b57cec5SDimitry Andric   if (Entry && !Entry->isDeclaration())
4557*0b57cec5SDimitry Andric     return;
4558*0b57cec5SDimitry Andric 
4559*0b57cec5SDimitry Andric   Aliases.push_back(GD);
4560*0b57cec5SDimitry Andric 
4561*0b57cec5SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
4562*0b57cec5SDimitry Andric 
4563*0b57cec5SDimitry Andric   // Create a reference to the named value.  This ensures that it is emitted
4564*0b57cec5SDimitry Andric   // if a deferred decl.
4565*0b57cec5SDimitry Andric   llvm::Constant *Aliasee;
4566*0b57cec5SDimitry Andric   llvm::GlobalValue::LinkageTypes LT;
4567*0b57cec5SDimitry Andric   if (isa<llvm::FunctionType>(DeclTy)) {
4568*0b57cec5SDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
4569*0b57cec5SDimitry Andric                                       /*ForVTable=*/false);
4570*0b57cec5SDimitry Andric     LT = getFunctionLinkage(GD);
4571*0b57cec5SDimitry Andric   } else {
4572*0b57cec5SDimitry Andric     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
4573*0b57cec5SDimitry Andric                                     llvm::PointerType::getUnqual(DeclTy),
4574*0b57cec5SDimitry Andric                                     /*D=*/nullptr);
4575*0b57cec5SDimitry Andric     LT = getLLVMLinkageVarDefinition(cast<VarDecl>(GD.getDecl()),
4576*0b57cec5SDimitry Andric                                      D->getType().isConstQualified());
4577*0b57cec5SDimitry Andric   }
4578*0b57cec5SDimitry Andric 
4579*0b57cec5SDimitry Andric   // Create the new alias itself, but don't set a name yet.
45805ffd83dbSDimitry Andric   unsigned AS = Aliasee->getType()->getPointerAddressSpace();
4581*0b57cec5SDimitry Andric   auto *GA =
45825ffd83dbSDimitry Andric       llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule());
4583*0b57cec5SDimitry Andric 
4584*0b57cec5SDimitry Andric   if (Entry) {
4585*0b57cec5SDimitry Andric     if (GA->getAliasee() == Entry) {
4586*0b57cec5SDimitry Andric       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
4587*0b57cec5SDimitry Andric       return;
4588*0b57cec5SDimitry Andric     }
4589*0b57cec5SDimitry Andric 
4590*0b57cec5SDimitry Andric     assert(Entry->isDeclaration());
4591*0b57cec5SDimitry Andric 
4592*0b57cec5SDimitry Andric     // If there is a declaration in the module, then we had an extern followed
4593*0b57cec5SDimitry Andric     // by the alias, as in:
4594*0b57cec5SDimitry Andric     //   extern int test6();
4595*0b57cec5SDimitry Andric     //   ...
4596*0b57cec5SDimitry Andric     //   int test6() __attribute__((alias("test7")));
4597*0b57cec5SDimitry Andric     //
4598*0b57cec5SDimitry Andric     // Remove it and replace uses of it with the alias.
4599*0b57cec5SDimitry Andric     GA->takeName(Entry);
4600*0b57cec5SDimitry Andric 
4601*0b57cec5SDimitry Andric     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
4602*0b57cec5SDimitry Andric                                                           Entry->getType()));
4603*0b57cec5SDimitry Andric     Entry->eraseFromParent();
4604*0b57cec5SDimitry Andric   } else {
4605*0b57cec5SDimitry Andric     GA->setName(MangledName);
4606*0b57cec5SDimitry Andric   }
4607*0b57cec5SDimitry Andric 
4608*0b57cec5SDimitry Andric   // Set attributes which are particular to an alias; this is a
4609*0b57cec5SDimitry Andric   // specialization of the attributes which may be set on a global
4610*0b57cec5SDimitry Andric   // variable/function.
4611*0b57cec5SDimitry Andric   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
4612*0b57cec5SDimitry Andric       D->isWeakImported()) {
4613*0b57cec5SDimitry Andric     GA->setLinkage(llvm::Function::WeakAnyLinkage);
4614*0b57cec5SDimitry Andric   }
4615*0b57cec5SDimitry Andric 
4616*0b57cec5SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
4617*0b57cec5SDimitry Andric     if (VD->getTLSKind())
4618*0b57cec5SDimitry Andric       setTLSMode(GA, *VD);
4619*0b57cec5SDimitry Andric 
4620*0b57cec5SDimitry Andric   SetCommonAttributes(GD, GA);
4621*0b57cec5SDimitry Andric }
4622*0b57cec5SDimitry Andric 
4623*0b57cec5SDimitry Andric void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
4624*0b57cec5SDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
4625*0b57cec5SDimitry Andric   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
4626*0b57cec5SDimitry Andric   assert(IFA && "Not an ifunc?");
4627*0b57cec5SDimitry Andric 
4628*0b57cec5SDimitry Andric   StringRef MangledName = getMangledName(GD);
4629*0b57cec5SDimitry Andric 
4630*0b57cec5SDimitry Andric   if (IFA->getResolver() == MangledName) {
4631*0b57cec5SDimitry Andric     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4632*0b57cec5SDimitry Andric     return;
4633*0b57cec5SDimitry Andric   }
4634*0b57cec5SDimitry Andric 
4635*0b57cec5SDimitry Andric   // Report an error if some definition overrides ifunc.
4636*0b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4637*0b57cec5SDimitry Andric   if (Entry && !Entry->isDeclaration()) {
4638*0b57cec5SDimitry Andric     GlobalDecl OtherGD;
4639*0b57cec5SDimitry Andric     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
4640*0b57cec5SDimitry Andric         DiagnosedConflictingDefinitions.insert(GD).second) {
4641*0b57cec5SDimitry Andric       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
4642*0b57cec5SDimitry Andric           << MangledName;
4643*0b57cec5SDimitry Andric       Diags.Report(OtherGD.getDecl()->getLocation(),
4644*0b57cec5SDimitry Andric                    diag::note_previous_definition);
4645*0b57cec5SDimitry Andric     }
4646*0b57cec5SDimitry Andric     return;
4647*0b57cec5SDimitry Andric   }
4648*0b57cec5SDimitry Andric 
4649*0b57cec5SDimitry Andric   Aliases.push_back(GD);
4650*0b57cec5SDimitry Andric 
4651*0b57cec5SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
4652*0b57cec5SDimitry Andric   llvm::Constant *Resolver =
4653*0b57cec5SDimitry Andric       GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
4654*0b57cec5SDimitry Andric                               /*ForVTable=*/false);
4655*0b57cec5SDimitry Andric   llvm::GlobalIFunc *GIF =
4656*0b57cec5SDimitry Andric       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
4657*0b57cec5SDimitry Andric                                 "", Resolver, &getModule());
4658*0b57cec5SDimitry Andric   if (Entry) {
4659*0b57cec5SDimitry Andric     if (GIF->getResolver() == Entry) {
4660*0b57cec5SDimitry Andric       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4661*0b57cec5SDimitry Andric       return;
4662*0b57cec5SDimitry Andric     }
4663*0b57cec5SDimitry Andric     assert(Entry->isDeclaration());
4664*0b57cec5SDimitry Andric 
4665*0b57cec5SDimitry Andric     // If there is a declaration in the module, then we had an extern followed
4666*0b57cec5SDimitry Andric     // by the ifunc, as in:
4667*0b57cec5SDimitry Andric     //   extern int test();
4668*0b57cec5SDimitry Andric     //   ...
4669*0b57cec5SDimitry Andric     //   int test() __attribute__((ifunc("resolver")));
4670*0b57cec5SDimitry Andric     //
4671*0b57cec5SDimitry Andric     // Remove it and replace uses of it with the ifunc.
4672*0b57cec5SDimitry Andric     GIF->takeName(Entry);
4673*0b57cec5SDimitry Andric 
4674*0b57cec5SDimitry Andric     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
4675*0b57cec5SDimitry Andric                                                           Entry->getType()));
4676*0b57cec5SDimitry Andric     Entry->eraseFromParent();
4677*0b57cec5SDimitry Andric   } else
4678*0b57cec5SDimitry Andric     GIF->setName(MangledName);
4679*0b57cec5SDimitry Andric 
4680*0b57cec5SDimitry Andric   SetCommonAttributes(GD, GIF);
4681*0b57cec5SDimitry Andric }
4682*0b57cec5SDimitry Andric 
4683*0b57cec5SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
4684*0b57cec5SDimitry Andric                                             ArrayRef<llvm::Type*> Tys) {
4685*0b57cec5SDimitry Andric   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
4686*0b57cec5SDimitry Andric                                          Tys);
4687*0b57cec5SDimitry Andric }
4688*0b57cec5SDimitry Andric 
4689*0b57cec5SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> &
4690*0b57cec5SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
4691*0b57cec5SDimitry Andric                          const StringLiteral *Literal, bool TargetIsLSB,
4692*0b57cec5SDimitry Andric                          bool &IsUTF16, unsigned &StringLength) {
4693*0b57cec5SDimitry Andric   StringRef String = Literal->getString();
4694*0b57cec5SDimitry Andric   unsigned NumBytes = String.size();
4695*0b57cec5SDimitry Andric 
4696*0b57cec5SDimitry Andric   // Check for simple case.
4697*0b57cec5SDimitry Andric   if (!Literal->containsNonAsciiOrNull()) {
4698*0b57cec5SDimitry Andric     StringLength = NumBytes;
4699*0b57cec5SDimitry Andric     return *Map.insert(std::make_pair(String, nullptr)).first;
4700*0b57cec5SDimitry Andric   }
4701*0b57cec5SDimitry Andric 
4702*0b57cec5SDimitry Andric   // Otherwise, convert the UTF8 literals into a string of shorts.
4703*0b57cec5SDimitry Andric   IsUTF16 = true;
4704*0b57cec5SDimitry Andric 
4705*0b57cec5SDimitry Andric   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
4706*0b57cec5SDimitry Andric   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
4707*0b57cec5SDimitry Andric   llvm::UTF16 *ToPtr = &ToBuf[0];
4708*0b57cec5SDimitry Andric 
4709*0b57cec5SDimitry Andric   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4710*0b57cec5SDimitry Andric                                  ToPtr + NumBytes, llvm::strictConversion);
4711*0b57cec5SDimitry Andric 
4712*0b57cec5SDimitry Andric   // ConvertUTF8toUTF16 returns the length in ToPtr.
4713*0b57cec5SDimitry Andric   StringLength = ToPtr - &ToBuf[0];
4714*0b57cec5SDimitry Andric 
4715*0b57cec5SDimitry Andric   // Add an explicit null.
4716*0b57cec5SDimitry Andric   *ToPtr = 0;
4717*0b57cec5SDimitry Andric   return *Map.insert(std::make_pair(
4718*0b57cec5SDimitry Andric                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
4719*0b57cec5SDimitry Andric                                    (StringLength + 1) * 2),
4720*0b57cec5SDimitry Andric                          nullptr)).first;
4721*0b57cec5SDimitry Andric }
4722*0b57cec5SDimitry Andric 
4723*0b57cec5SDimitry Andric ConstantAddress
4724*0b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
4725*0b57cec5SDimitry Andric   unsigned StringLength = 0;
4726*0b57cec5SDimitry Andric   bool isUTF16 = false;
4727*0b57cec5SDimitry Andric   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
4728*0b57cec5SDimitry Andric       GetConstantCFStringEntry(CFConstantStringMap, Literal,
4729*0b57cec5SDimitry Andric                                getDataLayout().isLittleEndian(), isUTF16,
4730*0b57cec5SDimitry Andric                                StringLength);
4731*0b57cec5SDimitry Andric 
4732*0b57cec5SDimitry Andric   if (auto *C = Entry.second)
4733*0b57cec5SDimitry Andric     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
4734*0b57cec5SDimitry Andric 
4735*0b57cec5SDimitry Andric   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
4736*0b57cec5SDimitry Andric   llvm::Constant *Zeros[] = { Zero, Zero };
4737*0b57cec5SDimitry Andric 
4738*0b57cec5SDimitry Andric   const ASTContext &Context = getContext();
4739*0b57cec5SDimitry Andric   const llvm::Triple &Triple = getTriple();
4740*0b57cec5SDimitry Andric 
4741*0b57cec5SDimitry Andric   const auto CFRuntime = getLangOpts().CFRuntime;
4742*0b57cec5SDimitry Andric   const bool IsSwiftABI =
4743*0b57cec5SDimitry Andric       static_cast<unsigned>(CFRuntime) >=
4744*0b57cec5SDimitry Andric       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
4745*0b57cec5SDimitry Andric   const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
4746*0b57cec5SDimitry Andric 
4747*0b57cec5SDimitry Andric   // If we don't already have it, get __CFConstantStringClassReference.
4748*0b57cec5SDimitry Andric   if (!CFConstantStringClassRef) {
4749*0b57cec5SDimitry Andric     const char *CFConstantStringClassName = "__CFConstantStringClassReference";
4750*0b57cec5SDimitry Andric     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
4751*0b57cec5SDimitry Andric     Ty = llvm::ArrayType::get(Ty, 0);
4752*0b57cec5SDimitry Andric 
4753*0b57cec5SDimitry Andric     switch (CFRuntime) {
4754*0b57cec5SDimitry Andric     default: break;
4755*0b57cec5SDimitry Andric     case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH;
4756*0b57cec5SDimitry Andric     case LangOptions::CoreFoundationABI::Swift5_0:
4757*0b57cec5SDimitry Andric       CFConstantStringClassName =
4758*0b57cec5SDimitry Andric           Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
4759*0b57cec5SDimitry Andric                               : "$s10Foundation19_NSCFConstantStringCN";
4760*0b57cec5SDimitry Andric       Ty = IntPtrTy;
4761*0b57cec5SDimitry Andric       break;
4762*0b57cec5SDimitry Andric     case LangOptions::CoreFoundationABI::Swift4_2:
4763*0b57cec5SDimitry Andric       CFConstantStringClassName =
4764*0b57cec5SDimitry Andric           Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
4765*0b57cec5SDimitry Andric                               : "$S10Foundation19_NSCFConstantStringCN";
4766*0b57cec5SDimitry Andric       Ty = IntPtrTy;
4767*0b57cec5SDimitry Andric       break;
4768*0b57cec5SDimitry Andric     case LangOptions::CoreFoundationABI::Swift4_1:
4769*0b57cec5SDimitry Andric       CFConstantStringClassName =
4770*0b57cec5SDimitry Andric           Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
4771*0b57cec5SDimitry Andric                               : "__T010Foundation19_NSCFConstantStringCN";
4772*0b57cec5SDimitry Andric       Ty = IntPtrTy;
4773*0b57cec5SDimitry Andric       break;
4774*0b57cec5SDimitry Andric     }
4775*0b57cec5SDimitry Andric 
4776*0b57cec5SDimitry Andric     llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
4777*0b57cec5SDimitry Andric 
4778*0b57cec5SDimitry Andric     if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
4779*0b57cec5SDimitry Andric       llvm::GlobalValue *GV = nullptr;
4780*0b57cec5SDimitry Andric 
4781*0b57cec5SDimitry Andric       if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
4782*0b57cec5SDimitry Andric         IdentifierInfo &II = Context.Idents.get(GV->getName());
4783*0b57cec5SDimitry Andric         TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
4784*0b57cec5SDimitry Andric         DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
4785*0b57cec5SDimitry Andric 
4786*0b57cec5SDimitry Andric         const VarDecl *VD = nullptr;
4787*0b57cec5SDimitry Andric         for (const auto &Result : DC->lookup(&II))
4788*0b57cec5SDimitry Andric           if ((VD = dyn_cast<VarDecl>(Result)))
4789*0b57cec5SDimitry Andric             break;
4790*0b57cec5SDimitry Andric 
4791*0b57cec5SDimitry Andric         if (Triple.isOSBinFormatELF()) {
4792*0b57cec5SDimitry Andric           if (!VD)
4793*0b57cec5SDimitry Andric             GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4794*0b57cec5SDimitry Andric         } else {
4795*0b57cec5SDimitry Andric           GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4796*0b57cec5SDimitry Andric           if (!VD || !VD->hasAttr<DLLExportAttr>())
4797*0b57cec5SDimitry Andric             GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
4798*0b57cec5SDimitry Andric           else
4799*0b57cec5SDimitry Andric             GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
4800*0b57cec5SDimitry Andric         }
4801*0b57cec5SDimitry Andric 
4802*0b57cec5SDimitry Andric         setDSOLocal(GV);
4803*0b57cec5SDimitry Andric       }
4804*0b57cec5SDimitry Andric     }
4805*0b57cec5SDimitry Andric 
4806*0b57cec5SDimitry Andric     // Decay array -> ptr
4807*0b57cec5SDimitry Andric     CFConstantStringClassRef =
4808*0b57cec5SDimitry Andric         IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
4809*0b57cec5SDimitry Andric                    : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
4810*0b57cec5SDimitry Andric   }
4811*0b57cec5SDimitry Andric 
4812*0b57cec5SDimitry Andric   QualType CFTy = Context.getCFConstantStringType();
4813*0b57cec5SDimitry Andric 
4814*0b57cec5SDimitry Andric   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
4815*0b57cec5SDimitry Andric 
4816*0b57cec5SDimitry Andric   ConstantInitBuilder Builder(*this);
4817*0b57cec5SDimitry Andric   auto Fields = Builder.beginStruct(STy);
4818*0b57cec5SDimitry Andric 
4819*0b57cec5SDimitry Andric   // Class pointer.
4820*0b57cec5SDimitry Andric   Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
4821*0b57cec5SDimitry Andric 
4822*0b57cec5SDimitry Andric   // Flags.
4823*0b57cec5SDimitry Andric   if (IsSwiftABI) {
4824*0b57cec5SDimitry Andric     Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
4825*0b57cec5SDimitry Andric     Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
4826*0b57cec5SDimitry Andric   } else {
4827*0b57cec5SDimitry Andric     Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
4828*0b57cec5SDimitry Andric   }
4829*0b57cec5SDimitry Andric 
4830*0b57cec5SDimitry Andric   // String pointer.
4831*0b57cec5SDimitry Andric   llvm::Constant *C = nullptr;
4832*0b57cec5SDimitry Andric   if (isUTF16) {
4833*0b57cec5SDimitry Andric     auto Arr = llvm::makeArrayRef(
4834*0b57cec5SDimitry Andric         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
4835*0b57cec5SDimitry Andric         Entry.first().size() / 2);
4836*0b57cec5SDimitry Andric     C = llvm::ConstantDataArray::get(VMContext, Arr);
4837*0b57cec5SDimitry Andric   } else {
4838*0b57cec5SDimitry Andric     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
4839*0b57cec5SDimitry Andric   }
4840*0b57cec5SDimitry Andric 
4841*0b57cec5SDimitry Andric   // Note: -fwritable-strings doesn't make the backing store strings of
4842*0b57cec5SDimitry Andric   // CFStrings writable. (See <rdar://problem/10657500>)
4843*0b57cec5SDimitry Andric   auto *GV =
4844*0b57cec5SDimitry Andric       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
4845*0b57cec5SDimitry Andric                                llvm::GlobalValue::PrivateLinkage, C, ".str");
4846*0b57cec5SDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4847*0b57cec5SDimitry Andric   // Don't enforce the target's minimum global alignment, since the only use
4848*0b57cec5SDimitry Andric   // of the string is via this class initializer.
4849*0b57cec5SDimitry Andric   CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
4850*0b57cec5SDimitry Andric                             : Context.getTypeAlignInChars(Context.CharTy);
4851a7dea167SDimitry Andric   GV->setAlignment(Align.getAsAlign());
4852*0b57cec5SDimitry Andric 
4853*0b57cec5SDimitry Andric   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
4854*0b57cec5SDimitry Andric   // Without it LLVM can merge the string with a non unnamed_addr one during
4855*0b57cec5SDimitry Andric   // LTO.  Doing that changes the section it ends in, which surprises ld64.
4856*0b57cec5SDimitry Andric   if (Triple.isOSBinFormatMachO())
4857*0b57cec5SDimitry Andric     GV->setSection(isUTF16 ? "__TEXT,__ustring"
4858*0b57cec5SDimitry Andric                            : "__TEXT,__cstring,cstring_literals");
4859*0b57cec5SDimitry Andric   // Make sure the literal ends up in .rodata to allow for safe ICF and for
4860*0b57cec5SDimitry Andric   // the static linker to adjust permissions to read-only later on.
4861*0b57cec5SDimitry Andric   else if (Triple.isOSBinFormatELF())
4862*0b57cec5SDimitry Andric     GV->setSection(".rodata");
4863*0b57cec5SDimitry Andric 
4864*0b57cec5SDimitry Andric   // String.
4865*0b57cec5SDimitry Andric   llvm::Constant *Str =
4866*0b57cec5SDimitry Andric       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
4867*0b57cec5SDimitry Andric 
4868*0b57cec5SDimitry Andric   if (isUTF16)
4869*0b57cec5SDimitry Andric     // Cast the UTF16 string to the correct type.
4870*0b57cec5SDimitry Andric     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
4871*0b57cec5SDimitry Andric   Fields.add(Str);
4872*0b57cec5SDimitry Andric 
4873*0b57cec5SDimitry Andric   // String length.
4874*0b57cec5SDimitry Andric   llvm::IntegerType *LengthTy =
4875*0b57cec5SDimitry Andric       llvm::IntegerType::get(getModule().getContext(),
4876*0b57cec5SDimitry Andric                              Context.getTargetInfo().getLongWidth());
4877*0b57cec5SDimitry Andric   if (IsSwiftABI) {
4878*0b57cec5SDimitry Andric     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
4879*0b57cec5SDimitry Andric         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
4880*0b57cec5SDimitry Andric       LengthTy = Int32Ty;
4881*0b57cec5SDimitry Andric     else
4882*0b57cec5SDimitry Andric       LengthTy = IntPtrTy;
4883*0b57cec5SDimitry Andric   }
4884*0b57cec5SDimitry Andric   Fields.addInt(LengthTy, StringLength);
4885*0b57cec5SDimitry Andric 
4886a7dea167SDimitry Andric   // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is
4887a7dea167SDimitry Andric   // properly aligned on 32-bit platforms.
4888a7dea167SDimitry Andric   CharUnits Alignment =
4889a7dea167SDimitry Andric       IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign();
4890*0b57cec5SDimitry Andric 
4891*0b57cec5SDimitry Andric   // The struct.
4892*0b57cec5SDimitry Andric   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
4893*0b57cec5SDimitry Andric                                     /*isConstant=*/false,
4894*0b57cec5SDimitry Andric                                     llvm::GlobalVariable::PrivateLinkage);
4895*0b57cec5SDimitry Andric   GV->addAttribute("objc_arc_inert");
4896*0b57cec5SDimitry Andric   switch (Triple.getObjectFormat()) {
4897*0b57cec5SDimitry Andric   case llvm::Triple::UnknownObjectFormat:
4898*0b57cec5SDimitry Andric     llvm_unreachable("unknown file format");
4899*0b57cec5SDimitry Andric   case llvm::Triple::XCOFF:
4900*0b57cec5SDimitry Andric     llvm_unreachable("XCOFF is not yet implemented");
4901*0b57cec5SDimitry Andric   case llvm::Triple::COFF:
4902*0b57cec5SDimitry Andric   case llvm::Triple::ELF:
4903*0b57cec5SDimitry Andric   case llvm::Triple::Wasm:
4904*0b57cec5SDimitry Andric     GV->setSection("cfstring");
4905*0b57cec5SDimitry Andric     break;
4906*0b57cec5SDimitry Andric   case llvm::Triple::MachO:
4907*0b57cec5SDimitry Andric     GV->setSection("__DATA,__cfstring");
4908*0b57cec5SDimitry Andric     break;
4909*0b57cec5SDimitry Andric   }
4910*0b57cec5SDimitry Andric   Entry.second = GV;
4911*0b57cec5SDimitry Andric 
4912*0b57cec5SDimitry Andric   return ConstantAddress(GV, Alignment);
4913*0b57cec5SDimitry Andric }
4914*0b57cec5SDimitry Andric 
4915*0b57cec5SDimitry Andric bool CodeGenModule::getExpressionLocationsEnabled() const {
4916*0b57cec5SDimitry Andric   return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
4917*0b57cec5SDimitry Andric }
4918*0b57cec5SDimitry Andric 
4919*0b57cec5SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() {
4920*0b57cec5SDimitry Andric   if (ObjCFastEnumerationStateType.isNull()) {
4921*0b57cec5SDimitry Andric     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
4922*0b57cec5SDimitry Andric     D->startDefinition();
4923*0b57cec5SDimitry Andric 
4924*0b57cec5SDimitry Andric     QualType FieldTypes[] = {
4925*0b57cec5SDimitry Andric       Context.UnsignedLongTy,
4926*0b57cec5SDimitry Andric       Context.getPointerType(Context.getObjCIdType()),
4927*0b57cec5SDimitry Andric       Context.getPointerType(Context.UnsignedLongTy),
4928*0b57cec5SDimitry Andric       Context.getConstantArrayType(Context.UnsignedLongTy,
4929a7dea167SDimitry Andric                            llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0)
4930*0b57cec5SDimitry Andric     };
4931*0b57cec5SDimitry Andric 
4932*0b57cec5SDimitry Andric     for (size_t i = 0; i < 4; ++i) {
4933*0b57cec5SDimitry Andric       FieldDecl *Field = FieldDecl::Create(Context,
4934*0b57cec5SDimitry Andric                                            D,
4935*0b57cec5SDimitry Andric                                            SourceLocation(),
4936*0b57cec5SDimitry Andric                                            SourceLocation(), nullptr,
4937*0b57cec5SDimitry Andric                                            FieldTypes[i], /*TInfo=*/nullptr,
4938*0b57cec5SDimitry Andric                                            /*BitWidth=*/nullptr,
4939*0b57cec5SDimitry Andric                                            /*Mutable=*/false,
4940*0b57cec5SDimitry Andric                                            ICIS_NoInit);
4941*0b57cec5SDimitry Andric       Field->setAccess(AS_public);
4942*0b57cec5SDimitry Andric       D->addDecl(Field);
4943*0b57cec5SDimitry Andric     }
4944*0b57cec5SDimitry Andric 
4945*0b57cec5SDimitry Andric     D->completeDefinition();
4946*0b57cec5SDimitry Andric     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
4947*0b57cec5SDimitry Andric   }
4948*0b57cec5SDimitry Andric 
4949*0b57cec5SDimitry Andric   return ObjCFastEnumerationStateType;
4950*0b57cec5SDimitry Andric }
4951*0b57cec5SDimitry Andric 
4952*0b57cec5SDimitry Andric llvm::Constant *
4953*0b57cec5SDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
4954*0b57cec5SDimitry Andric   assert(!E->getType()->isPointerType() && "Strings are always arrays");
4955*0b57cec5SDimitry Andric 
4956*0b57cec5SDimitry Andric   // Don't emit it as the address of the string, emit the string data itself
4957*0b57cec5SDimitry Andric   // as an inline array.
4958*0b57cec5SDimitry Andric   if (E->getCharByteWidth() == 1) {
4959*0b57cec5SDimitry Andric     SmallString<64> Str(E->getString());
4960*0b57cec5SDimitry Andric 
4961*0b57cec5SDimitry Andric     // Resize the string to the right size, which is indicated by its type.
4962*0b57cec5SDimitry Andric     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
4963*0b57cec5SDimitry Andric     Str.resize(CAT->getSize().getZExtValue());
4964*0b57cec5SDimitry Andric     return llvm::ConstantDataArray::getString(VMContext, Str, false);
4965*0b57cec5SDimitry Andric   }
4966*0b57cec5SDimitry Andric 
4967*0b57cec5SDimitry Andric   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
4968*0b57cec5SDimitry Andric   llvm::Type *ElemTy = AType->getElementType();
4969*0b57cec5SDimitry Andric   unsigned NumElements = AType->getNumElements();
4970*0b57cec5SDimitry Andric 
4971*0b57cec5SDimitry Andric   // Wide strings have either 2-byte or 4-byte elements.
4972*0b57cec5SDimitry Andric   if (ElemTy->getPrimitiveSizeInBits() == 16) {
4973*0b57cec5SDimitry Andric     SmallVector<uint16_t, 32> Elements;
4974*0b57cec5SDimitry Andric     Elements.reserve(NumElements);
4975*0b57cec5SDimitry Andric 
4976*0b57cec5SDimitry Andric     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4977*0b57cec5SDimitry Andric       Elements.push_back(E->getCodeUnit(i));
4978*0b57cec5SDimitry Andric     Elements.resize(NumElements);
4979*0b57cec5SDimitry Andric     return llvm::ConstantDataArray::get(VMContext, Elements);
4980*0b57cec5SDimitry Andric   }
4981*0b57cec5SDimitry Andric 
4982*0b57cec5SDimitry Andric   assert(ElemTy->getPrimitiveSizeInBits() == 32);
4983*0b57cec5SDimitry Andric   SmallVector<uint32_t, 32> Elements;
4984*0b57cec5SDimitry Andric   Elements.reserve(NumElements);
4985*0b57cec5SDimitry Andric 
4986*0b57cec5SDimitry Andric   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4987*0b57cec5SDimitry Andric     Elements.push_back(E->getCodeUnit(i));
4988*0b57cec5SDimitry Andric   Elements.resize(NumElements);
4989*0b57cec5SDimitry Andric   return llvm::ConstantDataArray::get(VMContext, Elements);
4990*0b57cec5SDimitry Andric }
4991*0b57cec5SDimitry Andric 
4992*0b57cec5SDimitry Andric static llvm::GlobalVariable *
4993*0b57cec5SDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
4994*0b57cec5SDimitry Andric                       CodeGenModule &CGM, StringRef GlobalName,
4995*0b57cec5SDimitry Andric                       CharUnits Alignment) {
4996*0b57cec5SDimitry Andric   unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
4997*0b57cec5SDimitry Andric       CGM.getStringLiteralAddressSpace());
4998*0b57cec5SDimitry Andric 
4999*0b57cec5SDimitry Andric   llvm::Module &M = CGM.getModule();
5000*0b57cec5SDimitry Andric   // Create a global variable for this string
5001*0b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
5002*0b57cec5SDimitry Andric       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
5003*0b57cec5SDimitry Andric       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
5004a7dea167SDimitry Andric   GV->setAlignment(Alignment.getAsAlign());
5005*0b57cec5SDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
5006*0b57cec5SDimitry Andric   if (GV->isWeakForLinker()) {
5007*0b57cec5SDimitry Andric     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
5008*0b57cec5SDimitry Andric     GV->setComdat(M.getOrInsertComdat(GV->getName()));
5009*0b57cec5SDimitry Andric   }
5010*0b57cec5SDimitry Andric   CGM.setDSOLocal(GV);
5011*0b57cec5SDimitry Andric 
5012*0b57cec5SDimitry Andric   return GV;
5013*0b57cec5SDimitry Andric }
5014*0b57cec5SDimitry Andric 
5015*0b57cec5SDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
5016*0b57cec5SDimitry Andric /// constant array for the given string literal.
5017*0b57cec5SDimitry Andric ConstantAddress
5018*0b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
5019*0b57cec5SDimitry Andric                                                   StringRef Name) {
5020*0b57cec5SDimitry Andric   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
5021*0b57cec5SDimitry Andric 
5022*0b57cec5SDimitry Andric   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
5023*0b57cec5SDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
5024*0b57cec5SDimitry Andric   if (!LangOpts.WritableStrings) {
5025*0b57cec5SDimitry Andric     Entry = &ConstantStringMap[C];
5026*0b57cec5SDimitry Andric     if (auto GV = *Entry) {
5027*0b57cec5SDimitry Andric       if (Alignment.getQuantity() > GV->getAlignment())
5028a7dea167SDimitry Andric         GV->setAlignment(Alignment.getAsAlign());
5029*0b57cec5SDimitry Andric       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5030*0b57cec5SDimitry Andric                              Alignment);
5031*0b57cec5SDimitry Andric     }
5032*0b57cec5SDimitry Andric   }
5033*0b57cec5SDimitry Andric 
5034*0b57cec5SDimitry Andric   SmallString<256> MangledNameBuffer;
5035*0b57cec5SDimitry Andric   StringRef GlobalVariableName;
5036*0b57cec5SDimitry Andric   llvm::GlobalValue::LinkageTypes LT;
5037*0b57cec5SDimitry Andric 
5038*0b57cec5SDimitry Andric   // Mangle the string literal if that's how the ABI merges duplicate strings.
5039*0b57cec5SDimitry Andric   // Don't do it if they are writable, since we don't want writes in one TU to
5040*0b57cec5SDimitry Andric   // affect strings in another.
5041*0b57cec5SDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
5042*0b57cec5SDimitry Andric       !LangOpts.WritableStrings) {
5043*0b57cec5SDimitry Andric     llvm::raw_svector_ostream Out(MangledNameBuffer);
5044*0b57cec5SDimitry Andric     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
5045*0b57cec5SDimitry Andric     LT = llvm::GlobalValue::LinkOnceODRLinkage;
5046*0b57cec5SDimitry Andric     GlobalVariableName = MangledNameBuffer;
5047*0b57cec5SDimitry Andric   } else {
5048*0b57cec5SDimitry Andric     LT = llvm::GlobalValue::PrivateLinkage;
5049*0b57cec5SDimitry Andric     GlobalVariableName = Name;
5050*0b57cec5SDimitry Andric   }
5051*0b57cec5SDimitry Andric 
5052*0b57cec5SDimitry Andric   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
5053*0b57cec5SDimitry Andric   if (Entry)
5054*0b57cec5SDimitry Andric     *Entry = GV;
5055*0b57cec5SDimitry Andric 
5056*0b57cec5SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
5057*0b57cec5SDimitry Andric                                   QualType());
5058*0b57cec5SDimitry Andric 
5059*0b57cec5SDimitry Andric   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5060*0b57cec5SDimitry Andric                          Alignment);
5061*0b57cec5SDimitry Andric }
5062*0b57cec5SDimitry Andric 
5063*0b57cec5SDimitry Andric /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
5064*0b57cec5SDimitry Andric /// array for the given ObjCEncodeExpr node.
5065*0b57cec5SDimitry Andric ConstantAddress
5066*0b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
5067*0b57cec5SDimitry Andric   std::string Str;
5068*0b57cec5SDimitry Andric   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
5069*0b57cec5SDimitry Andric 
5070*0b57cec5SDimitry Andric   return GetAddrOfConstantCString(Str);
5071*0b57cec5SDimitry Andric }
5072*0b57cec5SDimitry Andric 
5073*0b57cec5SDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing
5074*0b57cec5SDimitry Andric /// the literal and a terminating '\0' character.
5075*0b57cec5SDimitry Andric /// The result has pointer to array type.
5076*0b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString(
5077*0b57cec5SDimitry Andric     const std::string &Str, const char *GlobalName) {
5078*0b57cec5SDimitry Andric   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
5079*0b57cec5SDimitry Andric   CharUnits Alignment =
5080*0b57cec5SDimitry Andric     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
5081*0b57cec5SDimitry Andric 
5082*0b57cec5SDimitry Andric   llvm::Constant *C =
5083*0b57cec5SDimitry Andric       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
5084*0b57cec5SDimitry Andric 
5085*0b57cec5SDimitry Andric   // Don't share any string literals if strings aren't constant.
5086*0b57cec5SDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
5087*0b57cec5SDimitry Andric   if (!LangOpts.WritableStrings) {
5088*0b57cec5SDimitry Andric     Entry = &ConstantStringMap[C];
5089*0b57cec5SDimitry Andric     if (auto GV = *Entry) {
5090*0b57cec5SDimitry Andric       if (Alignment.getQuantity() > GV->getAlignment())
5091a7dea167SDimitry Andric         GV->setAlignment(Alignment.getAsAlign());
5092*0b57cec5SDimitry Andric       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5093*0b57cec5SDimitry Andric                              Alignment);
5094*0b57cec5SDimitry Andric     }
5095*0b57cec5SDimitry Andric   }
5096*0b57cec5SDimitry Andric 
5097*0b57cec5SDimitry Andric   // Get the default prefix if a name wasn't specified.
5098*0b57cec5SDimitry Andric   if (!GlobalName)
5099*0b57cec5SDimitry Andric     GlobalName = ".str";
5100*0b57cec5SDimitry Andric   // Create a global variable for this.
5101*0b57cec5SDimitry Andric   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
5102*0b57cec5SDimitry Andric                                   GlobalName, Alignment);
5103*0b57cec5SDimitry Andric   if (Entry)
5104*0b57cec5SDimitry Andric     *Entry = GV;
5105*0b57cec5SDimitry Andric 
5106*0b57cec5SDimitry Andric   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5107*0b57cec5SDimitry Andric                          Alignment);
5108*0b57cec5SDimitry Andric }
5109*0b57cec5SDimitry Andric 
5110*0b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
5111*0b57cec5SDimitry Andric     const MaterializeTemporaryExpr *E, const Expr *Init) {
5112*0b57cec5SDimitry Andric   assert((E->getStorageDuration() == SD_Static ||
5113*0b57cec5SDimitry Andric           E->getStorageDuration() == SD_Thread) && "not a global temporary");
5114*0b57cec5SDimitry Andric   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
5115*0b57cec5SDimitry Andric 
5116*0b57cec5SDimitry Andric   // If we're not materializing a subobject of the temporary, keep the
5117*0b57cec5SDimitry Andric   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
5118*0b57cec5SDimitry Andric   QualType MaterializedType = Init->getType();
5119480093f4SDimitry Andric   if (Init == E->getSubExpr())
5120*0b57cec5SDimitry Andric     MaterializedType = E->getType();
5121*0b57cec5SDimitry Andric 
5122*0b57cec5SDimitry Andric   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
5123*0b57cec5SDimitry Andric 
5124*0b57cec5SDimitry Andric   if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
5125*0b57cec5SDimitry Andric     return ConstantAddress(Slot, Align);
5126*0b57cec5SDimitry Andric 
5127*0b57cec5SDimitry Andric   // FIXME: If an externally-visible declaration extends multiple temporaries,
5128*0b57cec5SDimitry Andric   // we need to give each temporary the same name in every translation unit (and
5129*0b57cec5SDimitry Andric   // we also need to make the temporaries externally-visible).
5130*0b57cec5SDimitry Andric   SmallString<256> Name;
5131*0b57cec5SDimitry Andric   llvm::raw_svector_ostream Out(Name);
5132*0b57cec5SDimitry Andric   getCXXABI().getMangleContext().mangleReferenceTemporary(
5133*0b57cec5SDimitry Andric       VD, E->getManglingNumber(), Out);
5134*0b57cec5SDimitry Andric 
5135*0b57cec5SDimitry Andric   APValue *Value = nullptr;
5136a7dea167SDimitry Andric   if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) {
5137a7dea167SDimitry Andric     // If the initializer of the extending declaration is a constant
5138a7dea167SDimitry Andric     // initializer, we should have a cached constant initializer for this
5139a7dea167SDimitry Andric     // temporary. Note that this might have a different value from the value
5140a7dea167SDimitry Andric     // computed by evaluating the initializer if the surrounding constant
5141a7dea167SDimitry Andric     // expression modifies the temporary.
5142480093f4SDimitry Andric     Value = E->getOrCreateValue(false);
5143*0b57cec5SDimitry Andric   }
5144*0b57cec5SDimitry Andric 
5145*0b57cec5SDimitry Andric   // Try evaluating it now, it might have a constant initializer.
5146*0b57cec5SDimitry Andric   Expr::EvalResult EvalResult;
5147*0b57cec5SDimitry Andric   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
5148*0b57cec5SDimitry Andric       !EvalResult.hasSideEffects())
5149*0b57cec5SDimitry Andric     Value = &EvalResult.Val;
5150*0b57cec5SDimitry Andric 
5151*0b57cec5SDimitry Andric   LangAS AddrSpace =
5152*0b57cec5SDimitry Andric       VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
5153*0b57cec5SDimitry Andric 
5154*0b57cec5SDimitry Andric   Optional<ConstantEmitter> emitter;
5155*0b57cec5SDimitry Andric   llvm::Constant *InitialValue = nullptr;
5156*0b57cec5SDimitry Andric   bool Constant = false;
5157*0b57cec5SDimitry Andric   llvm::Type *Type;
5158*0b57cec5SDimitry Andric   if (Value) {
5159*0b57cec5SDimitry Andric     // The temporary has a constant initializer, use it.
5160*0b57cec5SDimitry Andric     emitter.emplace(*this);
5161*0b57cec5SDimitry Andric     InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
5162*0b57cec5SDimitry Andric                                                MaterializedType);
5163*0b57cec5SDimitry Andric     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
5164*0b57cec5SDimitry Andric     Type = InitialValue->getType();
5165*0b57cec5SDimitry Andric   } else {
5166*0b57cec5SDimitry Andric     // No initializer, the initialization will be provided when we
5167*0b57cec5SDimitry Andric     // initialize the declaration which performed lifetime extension.
5168*0b57cec5SDimitry Andric     Type = getTypes().ConvertTypeForMem(MaterializedType);
5169*0b57cec5SDimitry Andric   }
5170*0b57cec5SDimitry Andric 
5171*0b57cec5SDimitry Andric   // Create a global variable for this lifetime-extended temporary.
5172*0b57cec5SDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
5173*0b57cec5SDimitry Andric       getLLVMLinkageVarDefinition(VD, Constant);
5174*0b57cec5SDimitry Andric   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
5175*0b57cec5SDimitry Andric     const VarDecl *InitVD;
5176*0b57cec5SDimitry Andric     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
5177*0b57cec5SDimitry Andric         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
5178*0b57cec5SDimitry Andric       // Temporaries defined inside a class get linkonce_odr linkage because the
5179*0b57cec5SDimitry Andric       // class can be defined in multiple translation units.
5180*0b57cec5SDimitry Andric       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
5181*0b57cec5SDimitry Andric     } else {
5182*0b57cec5SDimitry Andric       // There is no need for this temporary to have external linkage if the
5183*0b57cec5SDimitry Andric       // VarDecl has external linkage.
5184*0b57cec5SDimitry Andric       Linkage = llvm::GlobalVariable::InternalLinkage;
5185*0b57cec5SDimitry Andric     }
5186*0b57cec5SDimitry Andric   }
5187*0b57cec5SDimitry Andric   auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
5188*0b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
5189*0b57cec5SDimitry Andric       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
5190*0b57cec5SDimitry Andric       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
5191*0b57cec5SDimitry Andric   if (emitter) emitter->finalize(GV);
5192*0b57cec5SDimitry Andric   setGVProperties(GV, VD);
5193a7dea167SDimitry Andric   GV->setAlignment(Align.getAsAlign());
5194*0b57cec5SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker())
5195*0b57cec5SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
5196*0b57cec5SDimitry Andric   if (VD->getTLSKind())
5197*0b57cec5SDimitry Andric     setTLSMode(GV, *VD);
5198*0b57cec5SDimitry Andric   llvm::Constant *CV = GV;
5199*0b57cec5SDimitry Andric   if (AddrSpace != LangAS::Default)
5200*0b57cec5SDimitry Andric     CV = getTargetCodeGenInfo().performAddrSpaceCast(
5201*0b57cec5SDimitry Andric         *this, GV, AddrSpace, LangAS::Default,
5202*0b57cec5SDimitry Andric         Type->getPointerTo(
5203*0b57cec5SDimitry Andric             getContext().getTargetAddressSpace(LangAS::Default)));
5204*0b57cec5SDimitry Andric   MaterializedGlobalTemporaryMap[E] = CV;
5205*0b57cec5SDimitry Andric   return ConstantAddress(CV, Align);
5206*0b57cec5SDimitry Andric }
5207*0b57cec5SDimitry Andric 
5208*0b57cec5SDimitry Andric /// EmitObjCPropertyImplementations - Emit information for synthesized
5209*0b57cec5SDimitry Andric /// properties for an implementation.
5210*0b57cec5SDimitry Andric void CodeGenModule::EmitObjCPropertyImplementations(const
5211*0b57cec5SDimitry Andric                                                     ObjCImplementationDecl *D) {
5212*0b57cec5SDimitry Andric   for (const auto *PID : D->property_impls()) {
5213*0b57cec5SDimitry Andric     // Dynamic is just for type-checking.
5214*0b57cec5SDimitry Andric     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
5215*0b57cec5SDimitry Andric       ObjCPropertyDecl *PD = PID->getPropertyDecl();
5216*0b57cec5SDimitry Andric 
5217*0b57cec5SDimitry Andric       // Determine which methods need to be implemented, some may have
5218*0b57cec5SDimitry Andric       // been overridden. Note that ::isPropertyAccessor is not the method
5219*0b57cec5SDimitry Andric       // we want, that just indicates if the decl came from a
5220*0b57cec5SDimitry Andric       // property. What we want to know is if the method is defined in
5221*0b57cec5SDimitry Andric       // this implementation.
5222480093f4SDimitry Andric       auto *Getter = PID->getGetterMethodDecl();
5223480093f4SDimitry Andric       if (!Getter || Getter->isSynthesizedAccessorStub())
5224*0b57cec5SDimitry Andric         CodeGenFunction(*this).GenerateObjCGetter(
5225*0b57cec5SDimitry Andric             const_cast<ObjCImplementationDecl *>(D), PID);
5226480093f4SDimitry Andric       auto *Setter = PID->getSetterMethodDecl();
5227480093f4SDimitry Andric       if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
5228*0b57cec5SDimitry Andric         CodeGenFunction(*this).GenerateObjCSetter(
5229*0b57cec5SDimitry Andric                                  const_cast<ObjCImplementationDecl *>(D), PID);
5230*0b57cec5SDimitry Andric     }
5231*0b57cec5SDimitry Andric   }
5232*0b57cec5SDimitry Andric }
5233*0b57cec5SDimitry Andric 
5234*0b57cec5SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) {
5235*0b57cec5SDimitry Andric   const ObjCInterfaceDecl *iface = impl->getClassInterface();
5236*0b57cec5SDimitry Andric   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
5237*0b57cec5SDimitry Andric        ivar; ivar = ivar->getNextIvar())
5238*0b57cec5SDimitry Andric     if (ivar->getType().isDestructedType())
5239*0b57cec5SDimitry Andric       return true;
5240*0b57cec5SDimitry Andric 
5241*0b57cec5SDimitry Andric   return false;
5242*0b57cec5SDimitry Andric }
5243*0b57cec5SDimitry Andric 
5244*0b57cec5SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM,
5245*0b57cec5SDimitry Andric                                    ObjCImplementationDecl *D) {
5246*0b57cec5SDimitry Andric   CodeGenFunction CGF(CGM);
5247*0b57cec5SDimitry Andric   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
5248*0b57cec5SDimitry Andric        E = D->init_end(); B != E; ++B) {
5249*0b57cec5SDimitry Andric     CXXCtorInitializer *CtorInitExp = *B;
5250*0b57cec5SDimitry Andric     Expr *Init = CtorInitExp->getInit();
5251*0b57cec5SDimitry Andric     if (!CGF.isTrivialInitializer(Init))
5252*0b57cec5SDimitry Andric       return false;
5253*0b57cec5SDimitry Andric   }
5254*0b57cec5SDimitry Andric   return true;
5255*0b57cec5SDimitry Andric }
5256*0b57cec5SDimitry Andric 
5257*0b57cec5SDimitry Andric /// EmitObjCIvarInitializations - Emit information for ivar initialization
5258*0b57cec5SDimitry Andric /// for an implementation.
5259*0b57cec5SDimitry Andric void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
5260*0b57cec5SDimitry Andric   // We might need a .cxx_destruct even if we don't have any ivar initializers.
5261*0b57cec5SDimitry Andric   if (needsDestructMethod(D)) {
5262*0b57cec5SDimitry Andric     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
5263*0b57cec5SDimitry Andric     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
5264480093f4SDimitry Andric     ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(
5265480093f4SDimitry Andric         getContext(), D->getLocation(), D->getLocation(), cxxSelector,
5266480093f4SDimitry Andric         getContext().VoidTy, nullptr, D,
5267*0b57cec5SDimitry Andric         /*isInstance=*/true, /*isVariadic=*/false,
5268480093f4SDimitry Andric         /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
5269480093f4SDimitry Andric         /*isImplicitlyDeclared=*/true,
5270*0b57cec5SDimitry Andric         /*isDefined=*/false, ObjCMethodDecl::Required);
5271*0b57cec5SDimitry Andric     D->addInstanceMethod(DTORMethod);
5272*0b57cec5SDimitry Andric     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
5273*0b57cec5SDimitry Andric     D->setHasDestructors(true);
5274*0b57cec5SDimitry Andric   }
5275*0b57cec5SDimitry Andric 
5276*0b57cec5SDimitry Andric   // If the implementation doesn't have any ivar initializers, we don't need
5277*0b57cec5SDimitry Andric   // a .cxx_construct.
5278*0b57cec5SDimitry Andric   if (D->getNumIvarInitializers() == 0 ||
5279*0b57cec5SDimitry Andric       AllTrivialInitializers(*this, D))
5280*0b57cec5SDimitry Andric     return;
5281*0b57cec5SDimitry Andric 
5282*0b57cec5SDimitry Andric   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
5283*0b57cec5SDimitry Andric   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
5284*0b57cec5SDimitry Andric   // The constructor returns 'self'.
5285480093f4SDimitry Andric   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(
5286480093f4SDimitry Andric       getContext(), D->getLocation(), D->getLocation(), cxxSelector,
5287480093f4SDimitry Andric       getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true,
5288*0b57cec5SDimitry Andric       /*isVariadic=*/false,
5289480093f4SDimitry Andric       /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
5290*0b57cec5SDimitry Andric       /*isImplicitlyDeclared=*/true,
5291480093f4SDimitry Andric       /*isDefined=*/false, ObjCMethodDecl::Required);
5292*0b57cec5SDimitry Andric   D->addInstanceMethod(CTORMethod);
5293*0b57cec5SDimitry Andric   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
5294*0b57cec5SDimitry Andric   D->setHasNonZeroConstructors(true);
5295*0b57cec5SDimitry Andric }
5296*0b57cec5SDimitry Andric 
5297*0b57cec5SDimitry Andric // EmitLinkageSpec - Emit all declarations in a linkage spec.
5298*0b57cec5SDimitry Andric void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
5299*0b57cec5SDimitry Andric   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
5300480093f4SDimitry Andric       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
5301*0b57cec5SDimitry Andric     ErrorUnsupported(LSD, "linkage spec");
5302*0b57cec5SDimitry Andric     return;
5303*0b57cec5SDimitry Andric   }
5304*0b57cec5SDimitry Andric 
5305*0b57cec5SDimitry Andric   EmitDeclContext(LSD);
5306*0b57cec5SDimitry Andric }
5307*0b57cec5SDimitry Andric 
5308*0b57cec5SDimitry Andric void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
5309*0b57cec5SDimitry Andric   for (auto *I : DC->decls()) {
5310*0b57cec5SDimitry Andric     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
5311*0b57cec5SDimitry Andric     // are themselves considered "top-level", so EmitTopLevelDecl on an
5312*0b57cec5SDimitry Andric     // ObjCImplDecl does not recursively visit them. We need to do that in
5313*0b57cec5SDimitry Andric     // case they're nested inside another construct (LinkageSpecDecl /
5314*0b57cec5SDimitry Andric     // ExportDecl) that does stop them from being considered "top-level".
5315*0b57cec5SDimitry Andric     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
5316*0b57cec5SDimitry Andric       for (auto *M : OID->methods())
5317*0b57cec5SDimitry Andric         EmitTopLevelDecl(M);
5318*0b57cec5SDimitry Andric     }
5319*0b57cec5SDimitry Andric 
5320*0b57cec5SDimitry Andric     EmitTopLevelDecl(I);
5321*0b57cec5SDimitry Andric   }
5322*0b57cec5SDimitry Andric }
5323*0b57cec5SDimitry Andric 
5324*0b57cec5SDimitry Andric /// EmitTopLevelDecl - Emit code for a single top level declaration.
5325*0b57cec5SDimitry Andric void CodeGenModule::EmitTopLevelDecl(Decl *D) {
5326*0b57cec5SDimitry Andric   // Ignore dependent declarations.
5327*0b57cec5SDimitry Andric   if (D->isTemplated())
5328*0b57cec5SDimitry Andric     return;
5329*0b57cec5SDimitry Andric 
53305ffd83dbSDimitry Andric   // Consteval function shouldn't be emitted.
53315ffd83dbSDimitry Andric   if (auto *FD = dyn_cast<FunctionDecl>(D))
53325ffd83dbSDimitry Andric     if (FD->isConsteval())
53335ffd83dbSDimitry Andric       return;
53345ffd83dbSDimitry Andric 
5335*0b57cec5SDimitry Andric   switch (D->getKind()) {
5336*0b57cec5SDimitry Andric   case Decl::CXXConversion:
5337*0b57cec5SDimitry Andric   case Decl::CXXMethod:
5338*0b57cec5SDimitry Andric   case Decl::Function:
5339*0b57cec5SDimitry Andric     EmitGlobal(cast<FunctionDecl>(D));
5340*0b57cec5SDimitry Andric     // Always provide some coverage mapping
5341*0b57cec5SDimitry Andric     // even for the functions that aren't emitted.
5342*0b57cec5SDimitry Andric     AddDeferredUnusedCoverageMapping(D);
5343*0b57cec5SDimitry Andric     break;
5344*0b57cec5SDimitry Andric 
5345*0b57cec5SDimitry Andric   case Decl::CXXDeductionGuide:
5346*0b57cec5SDimitry Andric     // Function-like, but does not result in code emission.
5347*0b57cec5SDimitry Andric     break;
5348*0b57cec5SDimitry Andric 
5349*0b57cec5SDimitry Andric   case Decl::Var:
5350*0b57cec5SDimitry Andric   case Decl::Decomposition:
5351*0b57cec5SDimitry Andric   case Decl::VarTemplateSpecialization:
5352*0b57cec5SDimitry Andric     EmitGlobal(cast<VarDecl>(D));
5353*0b57cec5SDimitry Andric     if (auto *DD = dyn_cast<DecompositionDecl>(D))
5354*0b57cec5SDimitry Andric       for (auto *B : DD->bindings())
5355*0b57cec5SDimitry Andric         if (auto *HD = B->getHoldingVar())
5356*0b57cec5SDimitry Andric           EmitGlobal(HD);
5357*0b57cec5SDimitry Andric     break;
5358*0b57cec5SDimitry Andric 
5359*0b57cec5SDimitry Andric   // Indirect fields from global anonymous structs and unions can be
5360*0b57cec5SDimitry Andric   // ignored; only the actual variable requires IR gen support.
5361*0b57cec5SDimitry Andric   case Decl::IndirectField:
5362*0b57cec5SDimitry Andric     break;
5363*0b57cec5SDimitry Andric 
5364*0b57cec5SDimitry Andric   // C++ Decls
5365*0b57cec5SDimitry Andric   case Decl::Namespace:
5366*0b57cec5SDimitry Andric     EmitDeclContext(cast<NamespaceDecl>(D));
5367*0b57cec5SDimitry Andric     break;
5368*0b57cec5SDimitry Andric   case Decl::ClassTemplateSpecialization: {
5369*0b57cec5SDimitry Andric     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
53705ffd83dbSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
53715ffd83dbSDimitry Andric       if (Spec->getSpecializationKind() ==
53725ffd83dbSDimitry Andric               TSK_ExplicitInstantiationDefinition &&
5373*0b57cec5SDimitry Andric           Spec->hasDefinition())
53745ffd83dbSDimitry Andric         DI->completeTemplateDefinition(*Spec);
5375*0b57cec5SDimitry Andric   } LLVM_FALLTHROUGH;
5376*0b57cec5SDimitry Andric   case Decl::CXXRecord:
53775ffd83dbSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
5378*0b57cec5SDimitry Andric       if (auto *ES = D->getASTContext().getExternalSource())
5379*0b57cec5SDimitry Andric         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
53805ffd83dbSDimitry Andric           DI->completeUnusedClass(cast<CXXRecordDecl>(*D));
5381*0b57cec5SDimitry Andric     // Emit any static data members, they may be definitions.
5382*0b57cec5SDimitry Andric     for (auto *I : cast<CXXRecordDecl>(D)->decls())
5383*0b57cec5SDimitry Andric       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
5384*0b57cec5SDimitry Andric         EmitTopLevelDecl(I);
5385*0b57cec5SDimitry Andric     break;
5386*0b57cec5SDimitry Andric     // No code generation needed.
5387*0b57cec5SDimitry Andric   case Decl::UsingShadow:
5388*0b57cec5SDimitry Andric   case Decl::ClassTemplate:
5389*0b57cec5SDimitry Andric   case Decl::VarTemplate:
5390*0b57cec5SDimitry Andric   case Decl::Concept:
5391*0b57cec5SDimitry Andric   case Decl::VarTemplatePartialSpecialization:
5392*0b57cec5SDimitry Andric   case Decl::FunctionTemplate:
5393*0b57cec5SDimitry Andric   case Decl::TypeAliasTemplate:
5394*0b57cec5SDimitry Andric   case Decl::Block:
5395*0b57cec5SDimitry Andric   case Decl::Empty:
5396*0b57cec5SDimitry Andric   case Decl::Binding:
5397*0b57cec5SDimitry Andric     break;
5398*0b57cec5SDimitry Andric   case Decl::Using:          // using X; [C++]
5399*0b57cec5SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
5400*0b57cec5SDimitry Andric         DI->EmitUsingDecl(cast<UsingDecl>(*D));
54015ffd83dbSDimitry Andric     break;
5402*0b57cec5SDimitry Andric   case Decl::NamespaceAlias:
5403*0b57cec5SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
5404*0b57cec5SDimitry Andric         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
54055ffd83dbSDimitry Andric     break;
5406*0b57cec5SDimitry Andric   case Decl::UsingDirective: // using namespace X; [C++]
5407*0b57cec5SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
5408*0b57cec5SDimitry Andric       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
54095ffd83dbSDimitry Andric     break;
5410*0b57cec5SDimitry Andric   case Decl::CXXConstructor:
5411*0b57cec5SDimitry Andric     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
5412*0b57cec5SDimitry Andric     break;
5413*0b57cec5SDimitry Andric   case Decl::CXXDestructor:
5414*0b57cec5SDimitry Andric     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
5415*0b57cec5SDimitry Andric     break;
5416*0b57cec5SDimitry Andric 
5417*0b57cec5SDimitry Andric   case Decl::StaticAssert:
5418*0b57cec5SDimitry Andric     // Nothing to do.
5419*0b57cec5SDimitry Andric     break;
5420*0b57cec5SDimitry Andric 
5421*0b57cec5SDimitry Andric   // Objective-C Decls
5422*0b57cec5SDimitry Andric 
5423*0b57cec5SDimitry Andric   // Forward declarations, no (immediate) code generation.
5424*0b57cec5SDimitry Andric   case Decl::ObjCInterface:
5425*0b57cec5SDimitry Andric   case Decl::ObjCCategory:
5426*0b57cec5SDimitry Andric     break;
5427*0b57cec5SDimitry Andric 
5428*0b57cec5SDimitry Andric   case Decl::ObjCProtocol: {
5429*0b57cec5SDimitry Andric     auto *Proto = cast<ObjCProtocolDecl>(D);
5430*0b57cec5SDimitry Andric     if (Proto->isThisDeclarationADefinition())
5431*0b57cec5SDimitry Andric       ObjCRuntime->GenerateProtocol(Proto);
5432*0b57cec5SDimitry Andric     break;
5433*0b57cec5SDimitry Andric   }
5434*0b57cec5SDimitry Andric 
5435*0b57cec5SDimitry Andric   case Decl::ObjCCategoryImpl:
5436*0b57cec5SDimitry Andric     // Categories have properties but don't support synthesize so we
5437*0b57cec5SDimitry Andric     // can ignore them here.
5438*0b57cec5SDimitry Andric     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
5439*0b57cec5SDimitry Andric     break;
5440*0b57cec5SDimitry Andric 
5441*0b57cec5SDimitry Andric   case Decl::ObjCImplementation: {
5442*0b57cec5SDimitry Andric     auto *OMD = cast<ObjCImplementationDecl>(D);
5443*0b57cec5SDimitry Andric     EmitObjCPropertyImplementations(OMD);
5444*0b57cec5SDimitry Andric     EmitObjCIvarInitializations(OMD);
5445*0b57cec5SDimitry Andric     ObjCRuntime->GenerateClass(OMD);
5446*0b57cec5SDimitry Andric     // Emit global variable debug information.
5447*0b57cec5SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
5448480093f4SDimitry Andric       if (getCodeGenOpts().hasReducedDebugInfo())
5449*0b57cec5SDimitry Andric         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
5450*0b57cec5SDimitry Andric             OMD->getClassInterface()), OMD->getLocation());
5451*0b57cec5SDimitry Andric     break;
5452*0b57cec5SDimitry Andric   }
5453*0b57cec5SDimitry Andric   case Decl::ObjCMethod: {
5454*0b57cec5SDimitry Andric     auto *OMD = cast<ObjCMethodDecl>(D);
5455*0b57cec5SDimitry Andric     // If this is not a prototype, emit the body.
5456*0b57cec5SDimitry Andric     if (OMD->getBody())
5457*0b57cec5SDimitry Andric       CodeGenFunction(*this).GenerateObjCMethod(OMD);
5458*0b57cec5SDimitry Andric     break;
5459*0b57cec5SDimitry Andric   }
5460*0b57cec5SDimitry Andric   case Decl::ObjCCompatibleAlias:
5461*0b57cec5SDimitry Andric     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
5462*0b57cec5SDimitry Andric     break;
5463*0b57cec5SDimitry Andric 
5464*0b57cec5SDimitry Andric   case Decl::PragmaComment: {
5465*0b57cec5SDimitry Andric     const auto *PCD = cast<PragmaCommentDecl>(D);
5466*0b57cec5SDimitry Andric     switch (PCD->getCommentKind()) {
5467*0b57cec5SDimitry Andric     case PCK_Unknown:
5468*0b57cec5SDimitry Andric       llvm_unreachable("unexpected pragma comment kind");
5469*0b57cec5SDimitry Andric     case PCK_Linker:
5470*0b57cec5SDimitry Andric       AppendLinkerOptions(PCD->getArg());
5471*0b57cec5SDimitry Andric       break;
5472*0b57cec5SDimitry Andric     case PCK_Lib:
5473*0b57cec5SDimitry Andric         AddDependentLib(PCD->getArg());
5474*0b57cec5SDimitry Andric       break;
5475*0b57cec5SDimitry Andric     case PCK_Compiler:
5476*0b57cec5SDimitry Andric     case PCK_ExeStr:
5477*0b57cec5SDimitry Andric     case PCK_User:
5478*0b57cec5SDimitry Andric       break; // We ignore all of these.
5479*0b57cec5SDimitry Andric     }
5480*0b57cec5SDimitry Andric     break;
5481*0b57cec5SDimitry Andric   }
5482*0b57cec5SDimitry Andric 
5483*0b57cec5SDimitry Andric   case Decl::PragmaDetectMismatch: {
5484*0b57cec5SDimitry Andric     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
5485*0b57cec5SDimitry Andric     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
5486*0b57cec5SDimitry Andric     break;
5487*0b57cec5SDimitry Andric   }
5488*0b57cec5SDimitry Andric 
5489*0b57cec5SDimitry Andric   case Decl::LinkageSpec:
5490*0b57cec5SDimitry Andric     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
5491*0b57cec5SDimitry Andric     break;
5492*0b57cec5SDimitry Andric 
5493*0b57cec5SDimitry Andric   case Decl::FileScopeAsm: {
5494*0b57cec5SDimitry Andric     // File-scope asm is ignored during device-side CUDA compilation.
5495*0b57cec5SDimitry Andric     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
5496*0b57cec5SDimitry Andric       break;
5497*0b57cec5SDimitry Andric     // File-scope asm is ignored during device-side OpenMP compilation.
5498*0b57cec5SDimitry Andric     if (LangOpts.OpenMPIsDevice)
5499*0b57cec5SDimitry Andric       break;
5500*0b57cec5SDimitry Andric     auto *AD = cast<FileScopeAsmDecl>(D);
5501*0b57cec5SDimitry Andric     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
5502*0b57cec5SDimitry Andric     break;
5503*0b57cec5SDimitry Andric   }
5504*0b57cec5SDimitry Andric 
5505*0b57cec5SDimitry Andric   case Decl::Import: {
5506*0b57cec5SDimitry Andric     auto *Import = cast<ImportDecl>(D);
5507*0b57cec5SDimitry Andric 
5508*0b57cec5SDimitry Andric     // If we've already imported this module, we're done.
5509*0b57cec5SDimitry Andric     if (!ImportedModules.insert(Import->getImportedModule()))
5510*0b57cec5SDimitry Andric       break;
5511*0b57cec5SDimitry Andric 
5512*0b57cec5SDimitry Andric     // Emit debug information for direct imports.
5513*0b57cec5SDimitry Andric     if (!Import->getImportedOwningModule()) {
5514*0b57cec5SDimitry Andric       if (CGDebugInfo *DI = getModuleDebugInfo())
5515*0b57cec5SDimitry Andric         DI->EmitImportDecl(*Import);
5516*0b57cec5SDimitry Andric     }
5517*0b57cec5SDimitry Andric 
5518*0b57cec5SDimitry Andric     // Find all of the submodules and emit the module initializers.
5519*0b57cec5SDimitry Andric     llvm::SmallPtrSet<clang::Module *, 16> Visited;
5520*0b57cec5SDimitry Andric     SmallVector<clang::Module *, 16> Stack;
5521*0b57cec5SDimitry Andric     Visited.insert(Import->getImportedModule());
5522*0b57cec5SDimitry Andric     Stack.push_back(Import->getImportedModule());
5523*0b57cec5SDimitry Andric 
5524*0b57cec5SDimitry Andric     while (!Stack.empty()) {
5525*0b57cec5SDimitry Andric       clang::Module *Mod = Stack.pop_back_val();
5526*0b57cec5SDimitry Andric       if (!EmittedModuleInitializers.insert(Mod).second)
5527*0b57cec5SDimitry Andric         continue;
5528*0b57cec5SDimitry Andric 
5529*0b57cec5SDimitry Andric       for (auto *D : Context.getModuleInitializers(Mod))
5530*0b57cec5SDimitry Andric         EmitTopLevelDecl(D);
5531*0b57cec5SDimitry Andric 
5532*0b57cec5SDimitry Andric       // Visit the submodules of this module.
5533*0b57cec5SDimitry Andric       for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
5534*0b57cec5SDimitry Andric                                              SubEnd = Mod->submodule_end();
5535*0b57cec5SDimitry Andric            Sub != SubEnd; ++Sub) {
5536*0b57cec5SDimitry Andric         // Skip explicit children; they need to be explicitly imported to emit
5537*0b57cec5SDimitry Andric         // the initializers.
5538*0b57cec5SDimitry Andric         if ((*Sub)->IsExplicit)
5539*0b57cec5SDimitry Andric           continue;
5540*0b57cec5SDimitry Andric 
5541*0b57cec5SDimitry Andric         if (Visited.insert(*Sub).second)
5542*0b57cec5SDimitry Andric           Stack.push_back(*Sub);
5543*0b57cec5SDimitry Andric       }
5544*0b57cec5SDimitry Andric     }
5545*0b57cec5SDimitry Andric     break;
5546*0b57cec5SDimitry Andric   }
5547*0b57cec5SDimitry Andric 
5548*0b57cec5SDimitry Andric   case Decl::Export:
5549*0b57cec5SDimitry Andric     EmitDeclContext(cast<ExportDecl>(D));
5550*0b57cec5SDimitry Andric     break;
5551*0b57cec5SDimitry Andric 
5552*0b57cec5SDimitry Andric   case Decl::OMPThreadPrivate:
5553*0b57cec5SDimitry Andric     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
5554*0b57cec5SDimitry Andric     break;
5555*0b57cec5SDimitry Andric 
5556*0b57cec5SDimitry Andric   case Decl::OMPAllocate:
5557*0b57cec5SDimitry Andric     break;
5558*0b57cec5SDimitry Andric 
5559*0b57cec5SDimitry Andric   case Decl::OMPDeclareReduction:
5560*0b57cec5SDimitry Andric     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
5561*0b57cec5SDimitry Andric     break;
5562*0b57cec5SDimitry Andric 
5563*0b57cec5SDimitry Andric   case Decl::OMPDeclareMapper:
5564*0b57cec5SDimitry Andric     EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
5565*0b57cec5SDimitry Andric     break;
5566*0b57cec5SDimitry Andric 
5567*0b57cec5SDimitry Andric   case Decl::OMPRequires:
5568*0b57cec5SDimitry Andric     EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
5569*0b57cec5SDimitry Andric     break;
5570*0b57cec5SDimitry Andric 
5571*0b57cec5SDimitry Andric   default:
5572*0b57cec5SDimitry Andric     // Make sure we handled everything we should, every other kind is a
5573*0b57cec5SDimitry Andric     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
5574*0b57cec5SDimitry Andric     // function. Need to recode Decl::Kind to do that easily.
5575*0b57cec5SDimitry Andric     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
5576*0b57cec5SDimitry Andric     break;
5577*0b57cec5SDimitry Andric   }
5578*0b57cec5SDimitry Andric }
5579*0b57cec5SDimitry Andric 
5580*0b57cec5SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
5581*0b57cec5SDimitry Andric   // Do we need to generate coverage mapping?
5582*0b57cec5SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
5583*0b57cec5SDimitry Andric     return;
5584*0b57cec5SDimitry Andric   switch (D->getKind()) {
5585*0b57cec5SDimitry Andric   case Decl::CXXConversion:
5586*0b57cec5SDimitry Andric   case Decl::CXXMethod:
5587*0b57cec5SDimitry Andric   case Decl::Function:
5588*0b57cec5SDimitry Andric   case Decl::ObjCMethod:
5589*0b57cec5SDimitry Andric   case Decl::CXXConstructor:
5590*0b57cec5SDimitry Andric   case Decl::CXXDestructor: {
5591*0b57cec5SDimitry Andric     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
55925ffd83dbSDimitry Andric       break;
5593*0b57cec5SDimitry Andric     SourceManager &SM = getContext().getSourceManager();
5594*0b57cec5SDimitry Andric     if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
55955ffd83dbSDimitry Andric       break;
5596*0b57cec5SDimitry Andric     auto I = DeferredEmptyCoverageMappingDecls.find(D);
5597*0b57cec5SDimitry Andric     if (I == DeferredEmptyCoverageMappingDecls.end())
5598*0b57cec5SDimitry Andric       DeferredEmptyCoverageMappingDecls[D] = true;
5599*0b57cec5SDimitry Andric     break;
5600*0b57cec5SDimitry Andric   }
5601*0b57cec5SDimitry Andric   default:
5602*0b57cec5SDimitry Andric     break;
5603*0b57cec5SDimitry Andric   };
5604*0b57cec5SDimitry Andric }
5605*0b57cec5SDimitry Andric 
5606*0b57cec5SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
5607*0b57cec5SDimitry Andric   // Do we need to generate coverage mapping?
5608*0b57cec5SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
5609*0b57cec5SDimitry Andric     return;
5610*0b57cec5SDimitry Andric   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
5611*0b57cec5SDimitry Andric     if (Fn->isTemplateInstantiation())
5612*0b57cec5SDimitry Andric       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
5613*0b57cec5SDimitry Andric   }
5614*0b57cec5SDimitry Andric   auto I = DeferredEmptyCoverageMappingDecls.find(D);
5615*0b57cec5SDimitry Andric   if (I == DeferredEmptyCoverageMappingDecls.end())
5616*0b57cec5SDimitry Andric     DeferredEmptyCoverageMappingDecls[D] = false;
5617*0b57cec5SDimitry Andric   else
5618*0b57cec5SDimitry Andric     I->second = false;
5619*0b57cec5SDimitry Andric }
5620*0b57cec5SDimitry Andric 
5621*0b57cec5SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
5622*0b57cec5SDimitry Andric   // We call takeVector() here to avoid use-after-free.
5623*0b57cec5SDimitry Andric   // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
5624*0b57cec5SDimitry Andric   // we deserialize function bodies to emit coverage info for them, and that
5625*0b57cec5SDimitry Andric   // deserializes more declarations. How should we handle that case?
5626*0b57cec5SDimitry Andric   for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
5627*0b57cec5SDimitry Andric     if (!Entry.second)
5628*0b57cec5SDimitry Andric       continue;
5629*0b57cec5SDimitry Andric     const Decl *D = Entry.first;
5630*0b57cec5SDimitry Andric     switch (D->getKind()) {
5631*0b57cec5SDimitry Andric     case Decl::CXXConversion:
5632*0b57cec5SDimitry Andric     case Decl::CXXMethod:
5633*0b57cec5SDimitry Andric     case Decl::Function:
5634*0b57cec5SDimitry Andric     case Decl::ObjCMethod: {
5635*0b57cec5SDimitry Andric       CodeGenPGO PGO(*this);
5636*0b57cec5SDimitry Andric       GlobalDecl GD(cast<FunctionDecl>(D));
5637*0b57cec5SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5638*0b57cec5SDimitry Andric                                   getFunctionLinkage(GD));
5639*0b57cec5SDimitry Andric       break;
5640*0b57cec5SDimitry Andric     }
5641*0b57cec5SDimitry Andric     case Decl::CXXConstructor: {
5642*0b57cec5SDimitry Andric       CodeGenPGO PGO(*this);
5643*0b57cec5SDimitry Andric       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
5644*0b57cec5SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5645*0b57cec5SDimitry Andric                                   getFunctionLinkage(GD));
5646*0b57cec5SDimitry Andric       break;
5647*0b57cec5SDimitry Andric     }
5648*0b57cec5SDimitry Andric     case Decl::CXXDestructor: {
5649*0b57cec5SDimitry Andric       CodeGenPGO PGO(*this);
5650*0b57cec5SDimitry Andric       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
5651*0b57cec5SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5652*0b57cec5SDimitry Andric                                   getFunctionLinkage(GD));
5653*0b57cec5SDimitry Andric       break;
5654*0b57cec5SDimitry Andric     }
5655*0b57cec5SDimitry Andric     default:
5656*0b57cec5SDimitry Andric       break;
5657*0b57cec5SDimitry Andric     };
5658*0b57cec5SDimitry Andric   }
5659*0b57cec5SDimitry Andric }
5660*0b57cec5SDimitry Andric 
56615ffd83dbSDimitry Andric void CodeGenModule::EmitMainVoidAlias() {
56625ffd83dbSDimitry Andric   // In order to transition away from "__original_main" gracefully, emit an
56635ffd83dbSDimitry Andric   // alias for "main" in the no-argument case so that libc can detect when
56645ffd83dbSDimitry Andric   // new-style no-argument main is in used.
56655ffd83dbSDimitry Andric   if (llvm::Function *F = getModule().getFunction("main")) {
56665ffd83dbSDimitry Andric     if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
56675ffd83dbSDimitry Andric         F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth()))
56685ffd83dbSDimitry Andric       addUsedGlobal(llvm::GlobalAlias::create("__main_void", F));
56695ffd83dbSDimitry Andric   }
56705ffd83dbSDimitry Andric }
56715ffd83dbSDimitry Andric 
5672*0b57cec5SDimitry Andric /// Turns the given pointer into a constant.
5673*0b57cec5SDimitry Andric static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
5674*0b57cec5SDimitry Andric                                           const void *Ptr) {
5675*0b57cec5SDimitry Andric   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
5676*0b57cec5SDimitry Andric   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
5677*0b57cec5SDimitry Andric   return llvm::ConstantInt::get(i64, PtrInt);
5678*0b57cec5SDimitry Andric }
5679*0b57cec5SDimitry Andric 
5680*0b57cec5SDimitry Andric static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
5681*0b57cec5SDimitry Andric                                    llvm::NamedMDNode *&GlobalMetadata,
5682*0b57cec5SDimitry Andric                                    GlobalDecl D,
5683*0b57cec5SDimitry Andric                                    llvm::GlobalValue *Addr) {
5684*0b57cec5SDimitry Andric   if (!GlobalMetadata)
5685*0b57cec5SDimitry Andric     GlobalMetadata =
5686*0b57cec5SDimitry Andric       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
5687*0b57cec5SDimitry Andric 
5688*0b57cec5SDimitry Andric   // TODO: should we report variant information for ctors/dtors?
5689*0b57cec5SDimitry Andric   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
5690*0b57cec5SDimitry Andric                            llvm::ConstantAsMetadata::get(GetPointerConstant(
5691*0b57cec5SDimitry Andric                                CGM.getLLVMContext(), D.getDecl()))};
5692*0b57cec5SDimitry Andric   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
5693*0b57cec5SDimitry Andric }
5694*0b57cec5SDimitry Andric 
5695*0b57cec5SDimitry Andric /// For each function which is declared within an extern "C" region and marked
5696*0b57cec5SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled
5697*0b57cec5SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer
5698*0b57cec5SDimitry Andric /// to such functions with an unmangled name from inline assembly within the
5699*0b57cec5SDimitry Andric /// same translation unit.
5700*0b57cec5SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() {
5701*0b57cec5SDimitry Andric   if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
5702*0b57cec5SDimitry Andric     return;
5703*0b57cec5SDimitry Andric   for (auto &I : StaticExternCValues) {
5704*0b57cec5SDimitry Andric     IdentifierInfo *Name = I.first;
5705*0b57cec5SDimitry Andric     llvm::GlobalValue *Val = I.second;
5706*0b57cec5SDimitry Andric     if (Val && !getModule().getNamedValue(Name->getName()))
5707*0b57cec5SDimitry Andric       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
5708*0b57cec5SDimitry Andric   }
5709*0b57cec5SDimitry Andric }
5710*0b57cec5SDimitry Andric 
5711*0b57cec5SDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
5712*0b57cec5SDimitry Andric                                              GlobalDecl &Result) const {
5713*0b57cec5SDimitry Andric   auto Res = Manglings.find(MangledName);
5714*0b57cec5SDimitry Andric   if (Res == Manglings.end())
5715*0b57cec5SDimitry Andric     return false;
5716*0b57cec5SDimitry Andric   Result = Res->getValue();
5717*0b57cec5SDimitry Andric   return true;
5718*0b57cec5SDimitry Andric }
5719*0b57cec5SDimitry Andric 
5720*0b57cec5SDimitry Andric /// Emits metadata nodes associating all the global values in the
5721*0b57cec5SDimitry Andric /// current module with the Decls they came from.  This is useful for
5722*0b57cec5SDimitry Andric /// projects using IR gen as a subroutine.
5723*0b57cec5SDimitry Andric ///
5724*0b57cec5SDimitry Andric /// Since there's currently no way to associate an MDNode directly
5725*0b57cec5SDimitry Andric /// with an llvm::GlobalValue, we create a global named metadata
5726*0b57cec5SDimitry Andric /// with the name 'clang.global.decl.ptrs'.
5727*0b57cec5SDimitry Andric void CodeGenModule::EmitDeclMetadata() {
5728*0b57cec5SDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
5729*0b57cec5SDimitry Andric 
5730*0b57cec5SDimitry Andric   for (auto &I : MangledDeclNames) {
5731*0b57cec5SDimitry Andric     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
5732*0b57cec5SDimitry Andric     // Some mangled names don't necessarily have an associated GlobalValue
5733*0b57cec5SDimitry Andric     // in this module, e.g. if we mangled it for DebugInfo.
5734*0b57cec5SDimitry Andric     if (Addr)
5735*0b57cec5SDimitry Andric       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
5736*0b57cec5SDimitry Andric   }
5737*0b57cec5SDimitry Andric }
5738*0b57cec5SDimitry Andric 
5739*0b57cec5SDimitry Andric /// Emits metadata nodes for all the local variables in the current
5740*0b57cec5SDimitry Andric /// function.
5741*0b57cec5SDimitry Andric void CodeGenFunction::EmitDeclMetadata() {
5742*0b57cec5SDimitry Andric   if (LocalDeclMap.empty()) return;
5743*0b57cec5SDimitry Andric 
5744*0b57cec5SDimitry Andric   llvm::LLVMContext &Context = getLLVMContext();
5745*0b57cec5SDimitry Andric 
5746*0b57cec5SDimitry Andric   // Find the unique metadata ID for this name.
5747*0b57cec5SDimitry Andric   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
5748*0b57cec5SDimitry Andric 
5749*0b57cec5SDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
5750*0b57cec5SDimitry Andric 
5751*0b57cec5SDimitry Andric   for (auto &I : LocalDeclMap) {
5752*0b57cec5SDimitry Andric     const Decl *D = I.first;
5753*0b57cec5SDimitry Andric     llvm::Value *Addr = I.second.getPointer();
5754*0b57cec5SDimitry Andric     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
5755*0b57cec5SDimitry Andric       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
5756*0b57cec5SDimitry Andric       Alloca->setMetadata(
5757*0b57cec5SDimitry Andric           DeclPtrKind, llvm::MDNode::get(
5758*0b57cec5SDimitry Andric                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
5759*0b57cec5SDimitry Andric     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
5760*0b57cec5SDimitry Andric       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
5761*0b57cec5SDimitry Andric       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
5762*0b57cec5SDimitry Andric     }
5763*0b57cec5SDimitry Andric   }
5764*0b57cec5SDimitry Andric }
5765*0b57cec5SDimitry Andric 
5766*0b57cec5SDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() {
5767*0b57cec5SDimitry Andric   llvm::NamedMDNode *IdentMetadata =
5768*0b57cec5SDimitry Andric     TheModule.getOrInsertNamedMetadata("llvm.ident");
5769*0b57cec5SDimitry Andric   std::string Version = getClangFullVersion();
5770*0b57cec5SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
5771*0b57cec5SDimitry Andric 
5772*0b57cec5SDimitry Andric   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
5773*0b57cec5SDimitry Andric   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
5774*0b57cec5SDimitry Andric }
5775*0b57cec5SDimitry Andric 
5776*0b57cec5SDimitry Andric void CodeGenModule::EmitCommandLineMetadata() {
5777*0b57cec5SDimitry Andric   llvm::NamedMDNode *CommandLineMetadata =
5778*0b57cec5SDimitry Andric     TheModule.getOrInsertNamedMetadata("llvm.commandline");
5779*0b57cec5SDimitry Andric   std::string CommandLine = getCodeGenOpts().RecordCommandLine;
5780*0b57cec5SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
5781*0b57cec5SDimitry Andric 
5782*0b57cec5SDimitry Andric   llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
5783*0b57cec5SDimitry Andric   CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
5784*0b57cec5SDimitry Andric }
5785*0b57cec5SDimitry Andric 
5786*0b57cec5SDimitry Andric void CodeGenModule::EmitCoverageFile() {
5787*0b57cec5SDimitry Andric   if (getCodeGenOpts().CoverageDataFile.empty() &&
5788*0b57cec5SDimitry Andric       getCodeGenOpts().CoverageNotesFile.empty())
5789*0b57cec5SDimitry Andric     return;
5790*0b57cec5SDimitry Andric 
5791*0b57cec5SDimitry Andric   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
5792*0b57cec5SDimitry Andric   if (!CUNode)
5793*0b57cec5SDimitry Andric     return;
5794*0b57cec5SDimitry Andric 
5795*0b57cec5SDimitry Andric   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
5796*0b57cec5SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
5797*0b57cec5SDimitry Andric   auto *CoverageDataFile =
5798*0b57cec5SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
5799*0b57cec5SDimitry Andric   auto *CoverageNotesFile =
5800*0b57cec5SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
5801*0b57cec5SDimitry Andric   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
5802*0b57cec5SDimitry Andric     llvm::MDNode *CU = CUNode->getOperand(i);
5803*0b57cec5SDimitry Andric     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
5804*0b57cec5SDimitry Andric     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
5805*0b57cec5SDimitry Andric   }
5806*0b57cec5SDimitry Andric }
5807*0b57cec5SDimitry Andric 
5808*0b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
5809*0b57cec5SDimitry Andric                                                        bool ForEH) {
5810*0b57cec5SDimitry Andric   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
5811*0b57cec5SDimitry Andric   // FIXME: should we even be calling this method if RTTI is disabled
5812*0b57cec5SDimitry Andric   // and it's not for EH?
58135ffd83dbSDimitry Andric   if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice ||
58145ffd83dbSDimitry Andric       (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
58155ffd83dbSDimitry Andric        getTriple().isNVPTX()))
5816*0b57cec5SDimitry Andric     return llvm::Constant::getNullValue(Int8PtrTy);
5817*0b57cec5SDimitry Andric 
5818*0b57cec5SDimitry Andric   if (ForEH && Ty->isObjCObjectPointerType() &&
5819*0b57cec5SDimitry Andric       LangOpts.ObjCRuntime.isGNUFamily())
5820*0b57cec5SDimitry Andric     return ObjCRuntime->GetEHType(Ty);
5821*0b57cec5SDimitry Andric 
5822*0b57cec5SDimitry Andric   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
5823*0b57cec5SDimitry Andric }
5824*0b57cec5SDimitry Andric 
5825*0b57cec5SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
5826*0b57cec5SDimitry Andric   // Do not emit threadprivates in simd-only mode.
5827*0b57cec5SDimitry Andric   if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
5828*0b57cec5SDimitry Andric     return;
5829*0b57cec5SDimitry Andric   for (auto RefExpr : D->varlists()) {
5830*0b57cec5SDimitry Andric     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
5831*0b57cec5SDimitry Andric     bool PerformInit =
5832*0b57cec5SDimitry Andric         VD->getAnyInitializer() &&
5833*0b57cec5SDimitry Andric         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
5834*0b57cec5SDimitry Andric                                                         /*ForRef=*/false);
5835*0b57cec5SDimitry Andric 
5836*0b57cec5SDimitry Andric     Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
5837*0b57cec5SDimitry Andric     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
5838*0b57cec5SDimitry Andric             VD, Addr, RefExpr->getBeginLoc(), PerformInit))
5839*0b57cec5SDimitry Andric       CXXGlobalInits.push_back(InitFunction);
5840*0b57cec5SDimitry Andric   }
5841*0b57cec5SDimitry Andric }
5842*0b57cec5SDimitry Andric 
5843*0b57cec5SDimitry Andric llvm::Metadata *
5844*0b57cec5SDimitry Andric CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
5845*0b57cec5SDimitry Andric                                             StringRef Suffix) {
5846*0b57cec5SDimitry Andric   llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
5847*0b57cec5SDimitry Andric   if (InternalId)
5848*0b57cec5SDimitry Andric     return InternalId;
5849*0b57cec5SDimitry Andric 
5850*0b57cec5SDimitry Andric   if (isExternallyVisible(T->getLinkage())) {
5851*0b57cec5SDimitry Andric     std::string OutName;
5852*0b57cec5SDimitry Andric     llvm::raw_string_ostream Out(OutName);
5853*0b57cec5SDimitry Andric     getCXXABI().getMangleContext().mangleTypeName(T, Out);
5854*0b57cec5SDimitry Andric     Out << Suffix;
5855*0b57cec5SDimitry Andric 
5856*0b57cec5SDimitry Andric     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
5857*0b57cec5SDimitry Andric   } else {
5858*0b57cec5SDimitry Andric     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
5859*0b57cec5SDimitry Andric                                            llvm::ArrayRef<llvm::Metadata *>());
5860*0b57cec5SDimitry Andric   }
5861*0b57cec5SDimitry Andric 
5862*0b57cec5SDimitry Andric   return InternalId;
5863*0b57cec5SDimitry Andric }
5864*0b57cec5SDimitry Andric 
5865*0b57cec5SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
5866*0b57cec5SDimitry Andric   return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
5867*0b57cec5SDimitry Andric }
5868*0b57cec5SDimitry Andric 
5869*0b57cec5SDimitry Andric llvm::Metadata *
5870*0b57cec5SDimitry Andric CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
5871*0b57cec5SDimitry Andric   return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
5872*0b57cec5SDimitry Andric }
5873*0b57cec5SDimitry Andric 
5874*0b57cec5SDimitry Andric // Generalize pointer types to a void pointer with the qualifiers of the
5875*0b57cec5SDimitry Andric // originally pointed-to type, e.g. 'const char *' and 'char * const *'
5876*0b57cec5SDimitry Andric // generalize to 'const void *' while 'char *' and 'const char **' generalize to
5877*0b57cec5SDimitry Andric // 'void *'.
5878*0b57cec5SDimitry Andric static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
5879*0b57cec5SDimitry Andric   if (!Ty->isPointerType())
5880*0b57cec5SDimitry Andric     return Ty;
5881*0b57cec5SDimitry Andric 
5882*0b57cec5SDimitry Andric   return Ctx.getPointerType(
5883*0b57cec5SDimitry Andric       QualType(Ctx.VoidTy).withCVRQualifiers(
5884*0b57cec5SDimitry Andric           Ty->getPointeeType().getCVRQualifiers()));
5885*0b57cec5SDimitry Andric }
5886*0b57cec5SDimitry Andric 
5887*0b57cec5SDimitry Andric // Apply type generalization to a FunctionType's return and argument types
5888*0b57cec5SDimitry Andric static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
5889*0b57cec5SDimitry Andric   if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
5890*0b57cec5SDimitry Andric     SmallVector<QualType, 8> GeneralizedParams;
5891*0b57cec5SDimitry Andric     for (auto &Param : FnType->param_types())
5892*0b57cec5SDimitry Andric       GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
5893*0b57cec5SDimitry Andric 
5894*0b57cec5SDimitry Andric     return Ctx.getFunctionType(
5895*0b57cec5SDimitry Andric         GeneralizeType(Ctx, FnType->getReturnType()),
5896*0b57cec5SDimitry Andric         GeneralizedParams, FnType->getExtProtoInfo());
5897*0b57cec5SDimitry Andric   }
5898*0b57cec5SDimitry Andric 
5899*0b57cec5SDimitry Andric   if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
5900*0b57cec5SDimitry Andric     return Ctx.getFunctionNoProtoType(
5901*0b57cec5SDimitry Andric         GeneralizeType(Ctx, FnType->getReturnType()));
5902*0b57cec5SDimitry Andric 
5903*0b57cec5SDimitry Andric   llvm_unreachable("Encountered unknown FunctionType");
5904*0b57cec5SDimitry Andric }
5905*0b57cec5SDimitry Andric 
5906*0b57cec5SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
5907*0b57cec5SDimitry Andric   return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
5908*0b57cec5SDimitry Andric                                       GeneralizedMetadataIdMap, ".generalized");
5909*0b57cec5SDimitry Andric }
5910*0b57cec5SDimitry Andric 
5911*0b57cec5SDimitry Andric /// Returns whether this module needs the "all-vtables" type identifier.
5912*0b57cec5SDimitry Andric bool CodeGenModule::NeedAllVtablesTypeId() const {
5913*0b57cec5SDimitry Andric   // Returns true if at least one of vtable-based CFI checkers is enabled and
5914*0b57cec5SDimitry Andric   // is not in the trapping mode.
5915*0b57cec5SDimitry Andric   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
5916*0b57cec5SDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
5917*0b57cec5SDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
5918*0b57cec5SDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
5919*0b57cec5SDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
5920*0b57cec5SDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
5921*0b57cec5SDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
5922*0b57cec5SDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
5923*0b57cec5SDimitry Andric }
5924*0b57cec5SDimitry Andric 
5925*0b57cec5SDimitry Andric void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
5926*0b57cec5SDimitry Andric                                           CharUnits Offset,
5927*0b57cec5SDimitry Andric                                           const CXXRecordDecl *RD) {
5928*0b57cec5SDimitry Andric   llvm::Metadata *MD =
5929*0b57cec5SDimitry Andric       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
5930*0b57cec5SDimitry Andric   VTable->addTypeMetadata(Offset.getQuantity(), MD);
5931*0b57cec5SDimitry Andric 
5932*0b57cec5SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
5933*0b57cec5SDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
5934*0b57cec5SDimitry Andric       VTable->addTypeMetadata(Offset.getQuantity(),
5935*0b57cec5SDimitry Andric                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
5936*0b57cec5SDimitry Andric 
5937*0b57cec5SDimitry Andric   if (NeedAllVtablesTypeId()) {
5938*0b57cec5SDimitry Andric     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
5939*0b57cec5SDimitry Andric     VTable->addTypeMetadata(Offset.getQuantity(), MD);
5940*0b57cec5SDimitry Andric   }
5941*0b57cec5SDimitry Andric }
5942*0b57cec5SDimitry Andric 
5943*0b57cec5SDimitry Andric llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
5944*0b57cec5SDimitry Andric   if (!SanStats)
5945a7dea167SDimitry Andric     SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule());
5946*0b57cec5SDimitry Andric 
5947*0b57cec5SDimitry Andric   return *SanStats;
5948*0b57cec5SDimitry Andric }
5949*0b57cec5SDimitry Andric llvm::Value *
5950*0b57cec5SDimitry Andric CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
5951*0b57cec5SDimitry Andric                                                   CodeGenFunction &CGF) {
5952*0b57cec5SDimitry Andric   llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
5953*0b57cec5SDimitry Andric   auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
5954*0b57cec5SDimitry Andric   auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
5955*0b57cec5SDimitry Andric   return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
5956*0b57cec5SDimitry Andric                                 "__translate_sampler_initializer"),
5957*0b57cec5SDimitry Andric                                 {C});
5958*0b57cec5SDimitry Andric }
59595ffd83dbSDimitry Andric 
59605ffd83dbSDimitry Andric CharUnits CodeGenModule::getNaturalPointeeTypeAlignment(
59615ffd83dbSDimitry Andric     QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) {
59625ffd83dbSDimitry Andric   return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
59635ffd83dbSDimitry Andric                                  /* forPointeeType= */ true);
59645ffd83dbSDimitry Andric }
59655ffd83dbSDimitry Andric 
59665ffd83dbSDimitry Andric CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T,
59675ffd83dbSDimitry Andric                                                  LValueBaseInfo *BaseInfo,
59685ffd83dbSDimitry Andric                                                  TBAAAccessInfo *TBAAInfo,
59695ffd83dbSDimitry Andric                                                  bool forPointeeType) {
59705ffd83dbSDimitry Andric   if (TBAAInfo)
59715ffd83dbSDimitry Andric     *TBAAInfo = getTBAAAccessInfo(T);
59725ffd83dbSDimitry Andric 
59735ffd83dbSDimitry Andric   // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But
59745ffd83dbSDimitry Andric   // that doesn't return the information we need to compute BaseInfo.
59755ffd83dbSDimitry Andric 
59765ffd83dbSDimitry Andric   // Honor alignment typedef attributes even on incomplete types.
59775ffd83dbSDimitry Andric   // We also honor them straight for C++ class types, even as pointees;
59785ffd83dbSDimitry Andric   // there's an expressivity gap here.
59795ffd83dbSDimitry Andric   if (auto TT = T->getAs<TypedefType>()) {
59805ffd83dbSDimitry Andric     if (auto Align = TT->getDecl()->getMaxAlignment()) {
59815ffd83dbSDimitry Andric       if (BaseInfo)
59825ffd83dbSDimitry Andric         *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
59835ffd83dbSDimitry Andric       return getContext().toCharUnitsFromBits(Align);
59845ffd83dbSDimitry Andric     }
59855ffd83dbSDimitry Andric   }
59865ffd83dbSDimitry Andric 
59875ffd83dbSDimitry Andric   bool AlignForArray = T->isArrayType();
59885ffd83dbSDimitry Andric 
59895ffd83dbSDimitry Andric   // Analyze the base element type, so we don't get confused by incomplete
59905ffd83dbSDimitry Andric   // array types.
59915ffd83dbSDimitry Andric   T = getContext().getBaseElementType(T);
59925ffd83dbSDimitry Andric 
59935ffd83dbSDimitry Andric   if (T->isIncompleteType()) {
59945ffd83dbSDimitry Andric     // We could try to replicate the logic from
59955ffd83dbSDimitry Andric     // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the
59965ffd83dbSDimitry Andric     // type is incomplete, so it's impossible to test. We could try to reuse
59975ffd83dbSDimitry Andric     // getTypeAlignIfKnown, but that doesn't return the information we need
59985ffd83dbSDimitry Andric     // to set BaseInfo.  So just ignore the possibility that the alignment is
59995ffd83dbSDimitry Andric     // greater than one.
60005ffd83dbSDimitry Andric     if (BaseInfo)
60015ffd83dbSDimitry Andric       *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
60025ffd83dbSDimitry Andric     return CharUnits::One();
60035ffd83dbSDimitry Andric   }
60045ffd83dbSDimitry Andric 
60055ffd83dbSDimitry Andric   if (BaseInfo)
60065ffd83dbSDimitry Andric     *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
60075ffd83dbSDimitry Andric 
60085ffd83dbSDimitry Andric   CharUnits Alignment;
60095ffd83dbSDimitry Andric   // For C++ class pointees, we don't know whether we're pointing at a
60105ffd83dbSDimitry Andric   // base or a complete object, so we generally need to use the
60115ffd83dbSDimitry Andric   // non-virtual alignment.
60125ffd83dbSDimitry Andric   const CXXRecordDecl *RD;
60135ffd83dbSDimitry Andric   if (forPointeeType && !AlignForArray && (RD = T->getAsCXXRecordDecl())) {
60145ffd83dbSDimitry Andric     Alignment = getClassPointerAlignment(RD);
60155ffd83dbSDimitry Andric   } else {
60165ffd83dbSDimitry Andric     Alignment = getContext().getTypeAlignInChars(T);
60175ffd83dbSDimitry Andric     if (T.getQualifiers().hasUnaligned())
60185ffd83dbSDimitry Andric       Alignment = CharUnits::One();
60195ffd83dbSDimitry Andric   }
60205ffd83dbSDimitry Andric 
60215ffd83dbSDimitry Andric   // Cap to the global maximum type alignment unless the alignment
60225ffd83dbSDimitry Andric   // was somehow explicit on the type.
60235ffd83dbSDimitry Andric   if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
60245ffd83dbSDimitry Andric     if (Alignment.getQuantity() > MaxAlign &&
60255ffd83dbSDimitry Andric         !getContext().isAlignmentRequired(T))
60265ffd83dbSDimitry Andric       Alignment = CharUnits::fromQuantity(MaxAlign);
60275ffd83dbSDimitry Andric   }
60285ffd83dbSDimitry Andric   return Alignment;
60295ffd83dbSDimitry Andric }
60305ffd83dbSDimitry Andric 
60315ffd83dbSDimitry Andric bool CodeGenModule::stopAutoInit() {
60325ffd83dbSDimitry Andric   unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter;
60335ffd83dbSDimitry Andric   if (StopAfter) {
60345ffd83dbSDimitry Andric     // This number is positive only when -ftrivial-auto-var-init-stop-after=* is
60355ffd83dbSDimitry Andric     // used
60365ffd83dbSDimitry Andric     if (NumAutoVarInit >= StopAfter) {
60375ffd83dbSDimitry Andric       return true;
60385ffd83dbSDimitry Andric     }
60395ffd83dbSDimitry Andric     if (!NumAutoVarInit) {
60405ffd83dbSDimitry Andric       unsigned DiagID = getDiags().getCustomDiagID(
60415ffd83dbSDimitry Andric           DiagnosticsEngine::Warning,
60425ffd83dbSDimitry Andric           "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
60435ffd83dbSDimitry Andric           "number of times ftrivial-auto-var-init=%1 gets applied.");
60445ffd83dbSDimitry Andric       getDiags().Report(DiagID)
60455ffd83dbSDimitry Andric           << StopAfter
60465ffd83dbSDimitry Andric           << (getContext().getLangOpts().getTrivialAutoVarInit() ==
60475ffd83dbSDimitry Andric                       LangOptions::TrivialAutoVarInitKind::Zero
60485ffd83dbSDimitry Andric                   ? "zero"
60495ffd83dbSDimitry Andric                   : "pattern");
60505ffd83dbSDimitry Andric     }
60515ffd83dbSDimitry Andric     ++NumAutoVarInit;
60525ffd83dbSDimitry Andric   }
60535ffd83dbSDimitry Andric   return false;
60545ffd83dbSDimitry Andric }
6055