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