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