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