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