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