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