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