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