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