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