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