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