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