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