xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision cd05ade13a66d4fb2daff489b2c02ac1ae2070d1)
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/DeclCXX.h"
34 #include "clang/AST/DeclObjC.h"
35 #include "clang/AST/DeclTemplate.h"
36 #include "clang/AST/Mangle.h"
37 #include "clang/AST/RecursiveASTVisitor.h"
38 #include "clang/AST/StmtVisitor.h"
39 #include "clang/Basic/Builtins.h"
40 #include "clang/Basic/CharInfo.h"
41 #include "clang/Basic/CodeGenOptions.h"
42 #include "clang/Basic/Diagnostic.h"
43 #include "clang/Basic/FileManager.h"
44 #include "clang/Basic/Module.h"
45 #include "clang/Basic/SourceManager.h"
46 #include "clang/Basic/TargetInfo.h"
47 #include "clang/Basic/Version.h"
48 #include "clang/CodeGen/BackendUtil.h"
49 #include "clang/CodeGen/ConstantInitBuilder.h"
50 #include "clang/Frontend/FrontendDiagnostic.h"
51 #include "llvm/ADT/STLExtras.h"
52 #include "llvm/ADT/StringExtras.h"
53 #include "llvm/ADT/StringSwitch.h"
54 #include "llvm/Analysis/TargetLibraryInfo.h"
55 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
56 #include "llvm/IR/AttributeMask.h"
57 #include "llvm/IR/CallingConv.h"
58 #include "llvm/IR/DataLayout.h"
59 #include "llvm/IR/Intrinsics.h"
60 #include "llvm/IR/LLVMContext.h"
61 #include "llvm/IR/Module.h"
62 #include "llvm/IR/ProfileSummary.h"
63 #include "llvm/ProfileData/InstrProfReader.h"
64 #include "llvm/ProfileData/SampleProf.h"
65 #include "llvm/Support/CRC.h"
66 #include "llvm/Support/CodeGen.h"
67 #include "llvm/Support/CommandLine.h"
68 #include "llvm/Support/ConvertUTF.h"
69 #include "llvm/Support/ErrorHandling.h"
70 #include "llvm/Support/TimeProfiler.h"
71 #include "llvm/Support/xxhash.h"
72 #include "llvm/TargetParser/Triple.h"
73 #include "llvm/TargetParser/X86TargetParser.h"
74 #include <optional>
75 
76 using namespace clang;
77 using namespace CodeGen;
78 
79 static llvm::cl::opt<bool> LimitedCoverage(
80     "limited-coverage-experimental", llvm::cl::Hidden,
81     llvm::cl::desc("Emit limited coverage mapping information (experimental)"));
82 
83 static const char AnnotationSection[] = "llvm.metadata";
84 
85 static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
86   switch (CGM.getContext().getCXXABIKind()) {
87   case TargetCXXABI::AppleARM64:
88   case TargetCXXABI::Fuchsia:
89   case TargetCXXABI::GenericAArch64:
90   case TargetCXXABI::GenericARM:
91   case TargetCXXABI::iOS:
92   case TargetCXXABI::WatchOS:
93   case TargetCXXABI::GenericMIPS:
94   case TargetCXXABI::GenericItanium:
95   case TargetCXXABI::WebAssembly:
96   case TargetCXXABI::XL:
97     return CreateItaniumCXXABI(CGM);
98   case TargetCXXABI::Microsoft:
99     return CreateMicrosoftCXXABI(CGM);
100   }
101 
102   llvm_unreachable("invalid C++ ABI kind");
103 }
104 
105 static std::unique_ptr<TargetCodeGenInfo>
106 createTargetCodeGenInfo(CodeGenModule &CGM) {
107   const TargetInfo &Target = CGM.getTarget();
108   const llvm::Triple &Triple = Target.getTriple();
109   const CodeGenOptions &CodeGenOpts = CGM.getCodeGenOpts();
110 
111   switch (Triple.getArch()) {
112   default:
113     return createDefaultTargetCodeGenInfo(CGM);
114 
115   case llvm::Triple::le32:
116     return createPNaClTargetCodeGenInfo(CGM);
117   case llvm::Triple::m68k:
118     return createM68kTargetCodeGenInfo(CGM);
119   case llvm::Triple::mips:
120   case llvm::Triple::mipsel:
121     if (Triple.getOS() == llvm::Triple::NaCl)
122       return createPNaClTargetCodeGenInfo(CGM);
123     return createMIPSTargetCodeGenInfo(CGM, /*IsOS32=*/true);
124 
125   case llvm::Triple::mips64:
126   case llvm::Triple::mips64el:
127     return createMIPSTargetCodeGenInfo(CGM, /*IsOS32=*/false);
128 
129   case llvm::Triple::avr: {
130     // For passing parameters, R8~R25 are used on avr, and R18~R25 are used
131     // on avrtiny. For passing return value, R18~R25 are used on avr, and
132     // R22~R25 are used on avrtiny.
133     unsigned NPR = Target.getABI() == "avrtiny" ? 6 : 18;
134     unsigned NRR = Target.getABI() == "avrtiny" ? 4 : 8;
135     return createAVRTargetCodeGenInfo(CGM, NPR, NRR);
136   }
137 
138   case llvm::Triple::aarch64:
139   case llvm::Triple::aarch64_32:
140   case llvm::Triple::aarch64_be: {
141     AArch64ABIKind Kind = AArch64ABIKind::AAPCS;
142     if (Target.getABI() == "darwinpcs")
143       Kind = AArch64ABIKind::DarwinPCS;
144     else if (Triple.isOSWindows())
145       return createWindowsAArch64TargetCodeGenInfo(CGM, AArch64ABIKind::Win64);
146 
147     return createAArch64TargetCodeGenInfo(CGM, Kind);
148   }
149 
150   case llvm::Triple::wasm32:
151   case llvm::Triple::wasm64: {
152     WebAssemblyABIKind Kind = WebAssemblyABIKind::MVP;
153     if (Target.getABI() == "experimental-mv")
154       Kind = WebAssemblyABIKind::ExperimentalMV;
155     return createWebAssemblyTargetCodeGenInfo(CGM, Kind);
156   }
157 
158   case llvm::Triple::arm:
159   case llvm::Triple::armeb:
160   case llvm::Triple::thumb:
161   case llvm::Triple::thumbeb: {
162     if (Triple.getOS() == llvm::Triple::Win32)
163       return createWindowsARMTargetCodeGenInfo(CGM, ARMABIKind::AAPCS_VFP);
164 
165     ARMABIKind Kind = ARMABIKind::AAPCS;
166     StringRef ABIStr = Target.getABI();
167     if (ABIStr == "apcs-gnu")
168       Kind = ARMABIKind::APCS;
169     else if (ABIStr == "aapcs16")
170       Kind = ARMABIKind::AAPCS16_VFP;
171     else if (CodeGenOpts.FloatABI == "hard" ||
172              (CodeGenOpts.FloatABI != "soft" &&
173               (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
174                Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
175                Triple.getEnvironment() == llvm::Triple::EABIHF)))
176       Kind = ARMABIKind::AAPCS_VFP;
177 
178     return createARMTargetCodeGenInfo(CGM, Kind);
179   }
180 
181   case llvm::Triple::ppc: {
182     if (Triple.isOSAIX())
183       return createAIXTargetCodeGenInfo(CGM, /*Is64Bit=*/false);
184 
185     bool IsSoftFloat =
186         CodeGenOpts.FloatABI == "soft" || Target.hasFeature("spe");
187     return createPPC32TargetCodeGenInfo(CGM, IsSoftFloat);
188   }
189   case llvm::Triple::ppcle: {
190     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
191     return createPPC32TargetCodeGenInfo(CGM, IsSoftFloat);
192   }
193   case llvm::Triple::ppc64:
194     if (Triple.isOSAIX())
195       return createAIXTargetCodeGenInfo(CGM, /*Is64Bit=*/true);
196 
197     if (Triple.isOSBinFormatELF()) {
198       PPC64_SVR4_ABIKind Kind = PPC64_SVR4_ABIKind::ELFv1;
199       if (Target.getABI() == "elfv2")
200         Kind = PPC64_SVR4_ABIKind::ELFv2;
201       bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
202 
203       return createPPC64_SVR4_TargetCodeGenInfo(CGM, Kind, IsSoftFloat);
204     }
205     return createPPC64TargetCodeGenInfo(CGM);
206   case llvm::Triple::ppc64le: {
207     assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
208     PPC64_SVR4_ABIKind Kind = PPC64_SVR4_ABIKind::ELFv2;
209     if (Target.getABI() == "elfv1")
210       Kind = PPC64_SVR4_ABIKind::ELFv1;
211     bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
212 
213     return createPPC64_SVR4_TargetCodeGenInfo(CGM, Kind, IsSoftFloat);
214   }
215 
216   case llvm::Triple::nvptx:
217   case llvm::Triple::nvptx64:
218     return createNVPTXTargetCodeGenInfo(CGM);
219 
220   case llvm::Triple::msp430:
221     return createMSP430TargetCodeGenInfo(CGM);
222 
223   case llvm::Triple::riscv32:
224   case llvm::Triple::riscv64: {
225     StringRef ABIStr = Target.getABI();
226     unsigned XLen = Target.getPointerWidth(LangAS::Default);
227     unsigned ABIFLen = 0;
228     if (ABIStr.ends_with("f"))
229       ABIFLen = 32;
230     else if (ABIStr.ends_with("d"))
231       ABIFLen = 64;
232     bool EABI = ABIStr.ends_with("e");
233     return createRISCVTargetCodeGenInfo(CGM, XLen, ABIFLen, EABI);
234   }
235 
236   case llvm::Triple::systemz: {
237     bool SoftFloat = CodeGenOpts.FloatABI == "soft";
238     bool HasVector = !SoftFloat && Target.getABI() == "vector";
239     return createSystemZTargetCodeGenInfo(CGM, HasVector, SoftFloat);
240   }
241 
242   case llvm::Triple::tce:
243   case llvm::Triple::tcele:
244     return createTCETargetCodeGenInfo(CGM);
245 
246   case llvm::Triple::x86: {
247     bool IsDarwinVectorABI = Triple.isOSDarwin();
248     bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
249 
250     if (Triple.getOS() == llvm::Triple::Win32) {
251       return createWinX86_32TargetCodeGenInfo(
252           CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
253           CodeGenOpts.NumRegisterParameters);
254     }
255     return createX86_32TargetCodeGenInfo(
256         CGM, IsDarwinVectorABI, IsWin32FloatStructABI,
257         CodeGenOpts.NumRegisterParameters, CodeGenOpts.FloatABI == "soft");
258   }
259 
260   case llvm::Triple::x86_64: {
261     StringRef ABI = Target.getABI();
262     X86AVXABILevel AVXLevel = (ABI == "avx512" ? X86AVXABILevel::AVX512
263                                : ABI == "avx"  ? X86AVXABILevel::AVX
264                                                : X86AVXABILevel::None);
265 
266     switch (Triple.getOS()) {
267     case llvm::Triple::Win32:
268       return createWinX86_64TargetCodeGenInfo(CGM, AVXLevel);
269     default:
270       return createX86_64TargetCodeGenInfo(CGM, AVXLevel);
271     }
272   }
273   case llvm::Triple::hexagon:
274     return createHexagonTargetCodeGenInfo(CGM);
275   case llvm::Triple::lanai:
276     return createLanaiTargetCodeGenInfo(CGM);
277   case llvm::Triple::r600:
278     return createAMDGPUTargetCodeGenInfo(CGM);
279   case llvm::Triple::amdgcn:
280     return createAMDGPUTargetCodeGenInfo(CGM);
281   case llvm::Triple::sparc:
282     return createSparcV8TargetCodeGenInfo(CGM);
283   case llvm::Triple::sparcv9:
284     return createSparcV9TargetCodeGenInfo(CGM);
285   case llvm::Triple::xcore:
286     return createXCoreTargetCodeGenInfo(CGM);
287   case llvm::Triple::arc:
288     return createARCTargetCodeGenInfo(CGM);
289   case llvm::Triple::spir:
290   case llvm::Triple::spir64:
291     return createCommonSPIRTargetCodeGenInfo(CGM);
292   case llvm::Triple::spirv32:
293   case llvm::Triple::spirv64:
294     return createSPIRVTargetCodeGenInfo(CGM);
295   case llvm::Triple::ve:
296     return createVETargetCodeGenInfo(CGM);
297   case llvm::Triple::csky: {
298     bool IsSoftFloat = !Target.hasFeature("hard-float-abi");
299     bool hasFP64 =
300         Target.hasFeature("fpuv2_df") || Target.hasFeature("fpuv3_df");
301     return createCSKYTargetCodeGenInfo(CGM, IsSoftFloat ? 0
302                                             : hasFP64   ? 64
303                                                         : 32);
304   }
305   case llvm::Triple::bpfeb:
306   case llvm::Triple::bpfel:
307     return createBPFTargetCodeGenInfo(CGM);
308   case llvm::Triple::loongarch32:
309   case llvm::Triple::loongarch64: {
310     StringRef ABIStr = Target.getABI();
311     unsigned ABIFRLen = 0;
312     if (ABIStr.ends_with("f"))
313       ABIFRLen = 32;
314     else if (ABIStr.ends_with("d"))
315       ABIFRLen = 64;
316     return createLoongArchTargetCodeGenInfo(
317         CGM, Target.getPointerWidth(LangAS::Default), ABIFRLen);
318   }
319   }
320 }
321 
322 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
323   if (!TheTargetCodeGenInfo)
324     TheTargetCodeGenInfo = createTargetCodeGenInfo(*this);
325   return *TheTargetCodeGenInfo;
326 }
327 
328 CodeGenModule::CodeGenModule(ASTContext &C,
329                              IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS,
330                              const HeaderSearchOptions &HSO,
331                              const PreprocessorOptions &PPO,
332                              const CodeGenOptions &CGO, llvm::Module &M,
333                              DiagnosticsEngine &diags,
334                              CoverageSourceInfo *CoverageInfo)
335     : Context(C), LangOpts(C.getLangOpts()), FS(FS), HeaderSearchOpts(HSO),
336       PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
337       Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
338       VMContext(M.getContext()), Types(*this), VTables(*this),
339       SanitizerMD(new SanitizerMetadata(*this)) {
340 
341   // Initialize the type cache.
342   llvm::LLVMContext &LLVMContext = M.getContext();
343   VoidTy = llvm::Type::getVoidTy(LLVMContext);
344   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
345   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
346   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
347   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
348   HalfTy = llvm::Type::getHalfTy(LLVMContext);
349   BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
350   FloatTy = llvm::Type::getFloatTy(LLVMContext);
351   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
352   PointerWidthInBits = C.getTargetInfo().getPointerWidth(LangAS::Default);
353   PointerAlignInBytes =
354       C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(LangAS::Default))
355           .getQuantity();
356   SizeSizeInBytes =
357     C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
358   IntAlignInBytes =
359     C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
360   CharTy =
361     llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getCharWidth());
362   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
363   IntPtrTy = llvm::IntegerType::get(LLVMContext,
364     C.getTargetInfo().getMaxPointerWidth());
365   Int8PtrTy = llvm::PointerType::get(LLVMContext, 0);
366   const llvm::DataLayout &DL = M.getDataLayout();
367   AllocaInt8PtrTy =
368       llvm::PointerType::get(LLVMContext, DL.getAllocaAddrSpace());
369   GlobalsInt8PtrTy =
370       llvm::PointerType::get(LLVMContext, DL.getDefaultGlobalsAddressSpace());
371   ConstGlobalsPtrTy = llvm::PointerType::get(
372       LLVMContext, C.getTargetAddressSpace(GetGlobalConstantAddressSpace()));
373   ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
374 
375   // Build C++20 Module initializers.
376   // TODO: Add Microsoft here once we know the mangling required for the
377   // initializers.
378   CXX20ModuleInits =
379       LangOpts.CPlusPlusModules && getCXXABI().getMangleContext().getKind() ==
380                                        ItaniumMangleContext::MK_Itanium;
381 
382   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
383 
384   if (LangOpts.ObjC)
385     createObjCRuntime();
386   if (LangOpts.OpenCL)
387     createOpenCLRuntime();
388   if (LangOpts.OpenMP)
389     createOpenMPRuntime();
390   if (LangOpts.CUDA)
391     createCUDARuntime();
392   if (LangOpts.HLSL)
393     createHLSLRuntime();
394 
395   // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
396   if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
397       (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
398     TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
399                                getCXXABI().getMangleContext()));
400 
401   // If debug info or coverage generation is enabled, create the CGDebugInfo
402   // object.
403   if (CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo ||
404       CodeGenOpts.CoverageNotesFile.size() ||
405       CodeGenOpts.CoverageDataFile.size())
406     DebugInfo.reset(new CGDebugInfo(*this));
407 
408   Block.GlobalUniqueCount = 0;
409 
410   if (C.getLangOpts().ObjC)
411     ObjCData.reset(new ObjCEntrypoints());
412 
413   if (CodeGenOpts.hasProfileClangUse()) {
414     auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
415         CodeGenOpts.ProfileInstrumentUsePath, *FS,
416         CodeGenOpts.ProfileRemappingFile);
417     // We're checking for profile read errors in CompilerInvocation, so if
418     // there was an error it should've already been caught. If it hasn't been
419     // somehow, trip an assertion.
420     assert(ReaderOrErr);
421     PGOReader = std::move(ReaderOrErr.get());
422   }
423 
424   // If coverage mapping generation is enabled, create the
425   // CoverageMappingModuleGen object.
426   if (CodeGenOpts.CoverageMapping)
427     CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
428 
429   // Generate the module name hash here if needed.
430   if (CodeGenOpts.UniqueInternalLinkageNames &&
431       !getModule().getSourceFileName().empty()) {
432     std::string Path = getModule().getSourceFileName();
433     // Check if a path substitution is needed from the MacroPrefixMap.
434     for (const auto &Entry : LangOpts.MacroPrefixMap)
435       if (Path.rfind(Entry.first, 0) != std::string::npos) {
436         Path = Entry.second + Path.substr(Entry.first.size());
437         break;
438       }
439     ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(Path);
440   }
441 }
442 
443 CodeGenModule::~CodeGenModule() {}
444 
445 void CodeGenModule::createObjCRuntime() {
446   // This is just isGNUFamily(), but we want to force implementors of
447   // new ABIs to decide how best to do this.
448   switch (LangOpts.ObjCRuntime.getKind()) {
449   case ObjCRuntime::GNUstep:
450   case ObjCRuntime::GCC:
451   case ObjCRuntime::ObjFW:
452     ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
453     return;
454 
455   case ObjCRuntime::FragileMacOSX:
456   case ObjCRuntime::MacOSX:
457   case ObjCRuntime::iOS:
458   case ObjCRuntime::WatchOS:
459     ObjCRuntime.reset(CreateMacObjCRuntime(*this));
460     return;
461   }
462   llvm_unreachable("bad runtime kind");
463 }
464 
465 void CodeGenModule::createOpenCLRuntime() {
466   OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
467 }
468 
469 void CodeGenModule::createOpenMPRuntime() {
470   // Select a specialized code generation class based on the target, if any.
471   // If it does not exist use the default implementation.
472   switch (getTriple().getArch()) {
473   case llvm::Triple::nvptx:
474   case llvm::Triple::nvptx64:
475   case llvm::Triple::amdgcn:
476     assert(getLangOpts().OpenMPIsTargetDevice &&
477            "OpenMP AMDGPU/NVPTX is only prepared to deal with device code.");
478     OpenMPRuntime.reset(new CGOpenMPRuntimeGPU(*this));
479     break;
480   default:
481     if (LangOpts.OpenMPSimd)
482       OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
483     else
484       OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
485     break;
486   }
487 }
488 
489 void CodeGenModule::createCUDARuntime() {
490   CUDARuntime.reset(CreateNVCUDARuntime(*this));
491 }
492 
493 void CodeGenModule::createHLSLRuntime() {
494   HLSLRuntime.reset(new CGHLSLRuntime(*this));
495 }
496 
497 void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
498   Replacements[Name] = C;
499 }
500 
501 void CodeGenModule::applyReplacements() {
502   for (auto &I : Replacements) {
503     StringRef MangledName = I.first;
504     llvm::Constant *Replacement = I.second;
505     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
506     if (!Entry)
507       continue;
508     auto *OldF = cast<llvm::Function>(Entry);
509     auto *NewF = dyn_cast<llvm::Function>(Replacement);
510     if (!NewF) {
511       if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
512         NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
513       } else {
514         auto *CE = cast<llvm::ConstantExpr>(Replacement);
515         assert(CE->getOpcode() == llvm::Instruction::BitCast ||
516                CE->getOpcode() == llvm::Instruction::GetElementPtr);
517         NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
518       }
519     }
520 
521     // Replace old with new, but keep the old order.
522     OldF->replaceAllUsesWith(Replacement);
523     if (NewF) {
524       NewF->removeFromParent();
525       OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
526                                                        NewF);
527     }
528     OldF->eraseFromParent();
529   }
530 }
531 
532 void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
533   GlobalValReplacements.push_back(std::make_pair(GV, C));
534 }
535 
536 void CodeGenModule::applyGlobalValReplacements() {
537   for (auto &I : GlobalValReplacements) {
538     llvm::GlobalValue *GV = I.first;
539     llvm::Constant *C = I.second;
540 
541     GV->replaceAllUsesWith(C);
542     GV->eraseFromParent();
543   }
544 }
545 
546 // This is only used in aliases that we created and we know they have a
547 // linear structure.
548 static const llvm::GlobalValue *getAliasedGlobal(const llvm::GlobalValue *GV) {
549   const llvm::Constant *C;
550   if (auto *GA = dyn_cast<llvm::GlobalAlias>(GV))
551     C = GA->getAliasee();
552   else if (auto *GI = dyn_cast<llvm::GlobalIFunc>(GV))
553     C = GI->getResolver();
554   else
555     return GV;
556 
557   const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(C->stripPointerCasts());
558   if (!AliaseeGV)
559     return nullptr;
560 
561   const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject();
562   if (FinalGV == GV)
563     return nullptr;
564 
565   return FinalGV;
566 }
567 
568 static bool checkAliasedGlobal(
569     const ASTContext &Context, DiagnosticsEngine &Diags, SourceLocation Location,
570     bool IsIFunc, const llvm::GlobalValue *Alias, const llvm::GlobalValue *&GV,
571     const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames,
572     SourceRange AliasRange) {
573   GV = getAliasedGlobal(Alias);
574   if (!GV) {
575     Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
576     return false;
577   }
578 
579   if (GV->hasCommonLinkage()) {
580     const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
581     if (Triple.getObjectFormat() == llvm::Triple::XCOFF) {
582       Diags.Report(Location, diag::err_alias_to_common);
583       return false;
584     }
585   }
586 
587   if (GV->isDeclaration()) {
588     Diags.Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc;
589     Diags.Report(Location, diag::note_alias_requires_mangled_name)
590         << IsIFunc << IsIFunc;
591     // Provide a note if the given function is not found and exists as a
592     // mangled name.
593     for (const auto &[Decl, Name] : MangledDeclNames) {
594       if (const auto *ND = dyn_cast<NamedDecl>(Decl.getDecl())) {
595         if (ND->getName() == GV->getName()) {
596           Diags.Report(Location, diag::note_alias_mangled_name_alternative)
597               << Name
598               << FixItHint::CreateReplacement(
599                      AliasRange,
600                      (Twine(IsIFunc ? "ifunc" : "alias") + "(\"" + Name + "\")")
601                          .str());
602         }
603       }
604     }
605     return false;
606   }
607 
608   if (IsIFunc) {
609     // Check resolver function type.
610     const auto *F = dyn_cast<llvm::Function>(GV);
611     if (!F) {
612       Diags.Report(Location, diag::err_alias_to_undefined)
613           << IsIFunc << IsIFunc;
614       return false;
615     }
616 
617     llvm::FunctionType *FTy = F->getFunctionType();
618     if (!FTy->getReturnType()->isPointerTy()) {
619       Diags.Report(Location, diag::err_ifunc_resolver_return);
620       return false;
621     }
622   }
623 
624   return true;
625 }
626 
627 void CodeGenModule::checkAliases() {
628   // Check if the constructed aliases are well formed. It is really unfortunate
629   // that we have to do this in CodeGen, but we only construct mangled names
630   // and aliases during codegen.
631   bool Error = false;
632   DiagnosticsEngine &Diags = getDiags();
633   for (const GlobalDecl &GD : Aliases) {
634     const auto *D = cast<ValueDecl>(GD.getDecl());
635     SourceLocation Location;
636     SourceRange Range;
637     bool IsIFunc = D->hasAttr<IFuncAttr>();
638     if (const Attr *A = D->getDefiningAttr()) {
639       Location = A->getLocation();
640       Range = A->getRange();
641     } else
642       llvm_unreachable("Not an alias or ifunc?");
643 
644     StringRef MangledName = getMangledName(GD);
645     llvm::GlobalValue *Alias = GetGlobalValue(MangledName);
646     const llvm::GlobalValue *GV = nullptr;
647     if (!checkAliasedGlobal(getContext(), Diags, Location, IsIFunc, Alias, GV,
648                             MangledDeclNames, Range)) {
649       Error = true;
650       continue;
651     }
652 
653     llvm::Constant *Aliasee =
654         IsIFunc ? cast<llvm::GlobalIFunc>(Alias)->getResolver()
655                 : cast<llvm::GlobalAlias>(Alias)->getAliasee();
656 
657     llvm::GlobalValue *AliaseeGV;
658     if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
659       AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
660     else
661       AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
662 
663     if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
664       StringRef AliasSection = SA->getName();
665       if (AliasSection != AliaseeGV->getSection())
666         Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
667             << AliasSection << IsIFunc << IsIFunc;
668     }
669 
670     // We have to handle alias to weak aliases in here. LLVM itself disallows
671     // this since the object semantics would not match the IL one. For
672     // compatibility with gcc we implement it by just pointing the alias
673     // to its aliasee's aliasee. We also warn, since the user is probably
674     // expecting the link to be weak.
675     if (auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
676       if (GA->isInterposable()) {
677         Diags.Report(Location, diag::warn_alias_to_weak_alias)
678             << GV->getName() << GA->getName() << IsIFunc;
679         Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
680             GA->getAliasee(), Alias->getType());
681 
682         if (IsIFunc)
683           cast<llvm::GlobalIFunc>(Alias)->setResolver(Aliasee);
684         else
685           cast<llvm::GlobalAlias>(Alias)->setAliasee(Aliasee);
686       }
687     }
688   }
689   if (!Error)
690     return;
691 
692   for (const GlobalDecl &GD : Aliases) {
693     StringRef MangledName = getMangledName(GD);
694     llvm::GlobalValue *Alias = GetGlobalValue(MangledName);
695     Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
696     Alias->eraseFromParent();
697   }
698 }
699 
700 void CodeGenModule::clear() {
701   DeferredDeclsToEmit.clear();
702   EmittedDeferredDecls.clear();
703   DeferredAnnotations.clear();
704   if (OpenMPRuntime)
705     OpenMPRuntime->clear();
706 }
707 
708 void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
709                                        StringRef MainFile) {
710   if (!hasDiagnostics())
711     return;
712   if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
713     if (MainFile.empty())
714       MainFile = "<stdin>";
715     Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
716   } else {
717     if (Mismatched > 0)
718       Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
719 
720     if (Missing > 0)
721       Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
722   }
723 }
724 
725 static std::optional<llvm::GlobalValue::VisibilityTypes>
726 getLLVMVisibility(clang::LangOptions::VisibilityFromDLLStorageClassKinds K) {
727   // Map to LLVM visibility.
728   switch (K) {
729   case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Keep:
730     return std::nullopt;
731   case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Default:
732     return llvm::GlobalValue::DefaultVisibility;
733   case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Hidden:
734     return llvm::GlobalValue::HiddenVisibility;
735   case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Protected:
736     return llvm::GlobalValue::ProtectedVisibility;
737   }
738   llvm_unreachable("unknown option value!");
739 }
740 
741 void setLLVMVisibility(llvm::GlobalValue &GV,
742                        std::optional<llvm::GlobalValue::VisibilityTypes> V) {
743   if (!V)
744     return;
745 
746   // Reset DSO locality before setting the visibility. This removes
747   // any effects that visibility options and annotations may have
748   // had on the DSO locality. Setting the visibility will implicitly set
749   // appropriate globals to DSO Local; however, this will be pessimistic
750   // w.r.t. to the normal compiler IRGen.
751   GV.setDSOLocal(false);
752   GV.setVisibility(*V);
753 }
754 
755 static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO,
756                                              llvm::Module &M) {
757   if (!LO.VisibilityFromDLLStorageClass)
758     return;
759 
760   std::optional<llvm::GlobalValue::VisibilityTypes> DLLExportVisibility =
761       getLLVMVisibility(LO.getDLLExportVisibility());
762 
763   std::optional<llvm::GlobalValue::VisibilityTypes>
764       NoDLLStorageClassVisibility =
765           getLLVMVisibility(LO.getNoDLLStorageClassVisibility());
766 
767   std::optional<llvm::GlobalValue::VisibilityTypes>
768       ExternDeclDLLImportVisibility =
769           getLLVMVisibility(LO.getExternDeclDLLImportVisibility());
770 
771   std::optional<llvm::GlobalValue::VisibilityTypes>
772       ExternDeclNoDLLStorageClassVisibility =
773           getLLVMVisibility(LO.getExternDeclNoDLLStorageClassVisibility());
774 
775   for (llvm::GlobalValue &GV : M.global_values()) {
776     if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
777       continue;
778 
779     if (GV.isDeclarationForLinker())
780       setLLVMVisibility(GV, GV.getDLLStorageClass() ==
781                                     llvm::GlobalValue::DLLImportStorageClass
782                                 ? ExternDeclDLLImportVisibility
783                                 : ExternDeclNoDLLStorageClassVisibility);
784     else
785       setLLVMVisibility(GV, GV.getDLLStorageClass() ==
786                                     llvm::GlobalValue::DLLExportStorageClass
787                                 ? DLLExportVisibility
788                                 : NoDLLStorageClassVisibility);
789 
790     GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
791   }
792 }
793 
794 static bool isStackProtectorOn(const LangOptions &LangOpts,
795                                const llvm::Triple &Triple,
796                                clang::LangOptions::StackProtectorMode Mode) {
797   if (Triple.isAMDGPU() || Triple.isNVPTX())
798     return false;
799   return LangOpts.getStackProtector() == Mode;
800 }
801 
802 void CodeGenModule::Release() {
803   Module *Primary = getContext().getCurrentNamedModule();
804   if (CXX20ModuleInits && Primary && !Primary->isHeaderLikeModule())
805     EmitModuleInitializers(Primary);
806   EmitDeferred();
807   DeferredDecls.insert(EmittedDeferredDecls.begin(),
808                        EmittedDeferredDecls.end());
809   EmittedDeferredDecls.clear();
810   EmitVTablesOpportunistically();
811   applyGlobalValReplacements();
812   applyReplacements();
813   emitMultiVersionFunctions();
814 
815   if (Context.getLangOpts().IncrementalExtensions &&
816       GlobalTopLevelStmtBlockInFlight.first) {
817     const TopLevelStmtDecl *TLSD = GlobalTopLevelStmtBlockInFlight.second;
818     GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->getEndLoc());
819     GlobalTopLevelStmtBlockInFlight = {nullptr, nullptr};
820   }
821 
822   // Module implementations are initialized the same way as a regular TU that
823   // imports one or more modules.
824   if (CXX20ModuleInits && Primary && Primary->isInterfaceOrPartition())
825     EmitCXXModuleInitFunc(Primary);
826   else
827     EmitCXXGlobalInitFunc();
828   EmitCXXGlobalCleanUpFunc();
829   registerGlobalDtorsWithAtExit();
830   EmitCXXThreadLocalInitFunc();
831   if (ObjCRuntime)
832     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
833       AddGlobalCtor(ObjCInitFunction);
834   if (Context.getLangOpts().CUDA && CUDARuntime) {
835     if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
836       AddGlobalCtor(CudaCtorFunction);
837   }
838   if (OpenMPRuntime) {
839     if (llvm::Function *OpenMPRequiresDirectiveRegFun =
840             OpenMPRuntime->emitRequiresDirectiveRegFun()) {
841       AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0);
842     }
843     OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
844     OpenMPRuntime->clear();
845   }
846   if (PGOReader) {
847     getModule().setProfileSummary(
848         PGOReader->getSummary(/* UseCS */ false).getMD(VMContext),
849         llvm::ProfileSummary::PSK_Instr);
850     if (PGOStats.hasDiagnostics())
851       PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
852   }
853   llvm::stable_sort(GlobalCtors, [](const Structor &L, const Structor &R) {
854     return L.LexOrder < R.LexOrder;
855   });
856   EmitCtorList(GlobalCtors, "llvm.global_ctors");
857   EmitCtorList(GlobalDtors, "llvm.global_dtors");
858   EmitGlobalAnnotations();
859   EmitStaticExternCAliases();
860   checkAliases();
861   EmitDeferredUnusedCoverageMappings();
862   CodeGenPGO(*this).setValueProfilingFlag(getModule());
863   if (CoverageMapping)
864     CoverageMapping->emit();
865   if (CodeGenOpts.SanitizeCfiCrossDso) {
866     CodeGenFunction(*this).EmitCfiCheckFail();
867     CodeGenFunction(*this).EmitCfiCheckStub();
868   }
869   if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
870     finalizeKCFITypes();
871   emitAtAvailableLinkGuard();
872   if (Context.getTargetInfo().getTriple().isWasm())
873     EmitMainVoidAlias();
874 
875   if (getTriple().isAMDGPU()) {
876     // Emit amdgpu_code_object_version module flag, which is code object version
877     // times 100.
878     if (getTarget().getTargetOpts().CodeObjectVersion !=
879         llvm::CodeObjectVersionKind::COV_None) {
880       getModule().addModuleFlag(llvm::Module::Error,
881                                 "amdgpu_code_object_version",
882                                 getTarget().getTargetOpts().CodeObjectVersion);
883     }
884 
885     // Currently, "-mprintf-kind" option is only supported for HIP
886     if (LangOpts.HIP) {
887       auto *MDStr = llvm::MDString::get(
888           getLLVMContext(), (getTarget().getTargetOpts().AMDGPUPrintfKindVal ==
889                              TargetOptions::AMDGPUPrintfKind::Hostcall)
890                                 ? "hostcall"
891                                 : "buffered");
892       getModule().addModuleFlag(llvm::Module::Error, "amdgpu_printf_kind",
893                                 MDStr);
894     }
895   }
896 
897   // Emit a global array containing all external kernels or device variables
898   // used by host functions and mark it as used for CUDA/HIP. This is necessary
899   // to get kernels or device variables in archives linked in even if these
900   // kernels or device variables are only used in host functions.
901   if (!Context.CUDAExternalDeviceDeclODRUsedByHost.empty()) {
902     SmallVector<llvm::Constant *, 8> UsedArray;
903     for (auto D : Context.CUDAExternalDeviceDeclODRUsedByHost) {
904       GlobalDecl GD;
905       if (auto *FD = dyn_cast<FunctionDecl>(D))
906         GD = GlobalDecl(FD, KernelReferenceKind::Kernel);
907       else
908         GD = GlobalDecl(D);
909       UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
910           GetAddrOfGlobal(GD), Int8PtrTy));
911     }
912 
913     llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
914 
915     auto *GV = new llvm::GlobalVariable(
916         getModule(), ATy, false, llvm::GlobalValue::InternalLinkage,
917         llvm::ConstantArray::get(ATy, UsedArray), "__clang_gpu_used_external");
918     addCompilerUsedGlobal(GV);
919   }
920 
921   emitLLVMUsed();
922   if (SanStats)
923     SanStats->finish();
924 
925   if (CodeGenOpts.Autolink &&
926       (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
927     EmitModuleLinkOptions();
928   }
929 
930   // On ELF we pass the dependent library specifiers directly to the linker
931   // without manipulating them. This is in contrast to other platforms where
932   // they are mapped to a specific linker option by the compiler. This
933   // difference is a result of the greater variety of ELF linkers and the fact
934   // that ELF linkers tend to handle libraries in a more complicated fashion
935   // than on other platforms. This forces us to defer handling the dependent
936   // libs to the linker.
937   //
938   // CUDA/HIP device and host libraries are different. Currently there is no
939   // way to differentiate dependent libraries for host or device. Existing
940   // usage of #pragma comment(lib, *) is intended for host libraries on
941   // Windows. Therefore emit llvm.dependent-libraries only for host.
942   if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
943     auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries");
944     for (auto *MD : ELFDependentLibraries)
945       NMD->addOperand(MD);
946   }
947 
948   // Record mregparm value now so it is visible through rest of codegen.
949   if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
950     getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
951                               CodeGenOpts.NumRegisterParameters);
952 
953   if (CodeGenOpts.DwarfVersion) {
954     getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version",
955                               CodeGenOpts.DwarfVersion);
956   }
957 
958   if (CodeGenOpts.Dwarf64)
959     getModule().addModuleFlag(llvm::Module::Max, "DWARF64", 1);
960 
961   if (Context.getLangOpts().SemanticInterposition)
962     // Require various optimization to respect semantic interposition.
963     getModule().setSemanticInterposition(true);
964 
965   if (CodeGenOpts.EmitCodeView) {
966     // Indicate that we want CodeView in the metadata.
967     getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
968   }
969   if (CodeGenOpts.CodeViewGHash) {
970     getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
971   }
972   if (CodeGenOpts.ControlFlowGuard) {
973     // Function ID tables and checks for Control Flow Guard (cfguard=2).
974     getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2);
975   } else if (CodeGenOpts.ControlFlowGuardNoChecks) {
976     // Function ID tables for Control Flow Guard (cfguard=1).
977     getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
978   }
979   if (CodeGenOpts.EHContGuard) {
980     // Function ID tables for EH Continuation Guard.
981     getModule().addModuleFlag(llvm::Module::Warning, "ehcontguard", 1);
982   }
983   if (Context.getLangOpts().Kernel) {
984     // Note if we are compiling with /kernel.
985     getModule().addModuleFlag(llvm::Module::Warning, "ms-kernel", 1);
986   }
987   if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
988     // We don't support LTO with 2 with different StrictVTablePointers
989     // FIXME: we could support it by stripping all the information introduced
990     // by StrictVTablePointers.
991 
992     getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
993 
994     llvm::Metadata *Ops[2] = {
995               llvm::MDString::get(VMContext, "StrictVTablePointers"),
996               llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
997                   llvm::Type::getInt32Ty(VMContext), 1))};
998 
999     getModule().addModuleFlag(llvm::Module::Require,
1000                               "StrictVTablePointersRequirement",
1001                               llvm::MDNode::get(VMContext, Ops));
1002   }
1003   if (getModuleDebugInfo())
1004     // We support a single version in the linked module. The LLVM
1005     // parser will drop debug info with a different version number
1006     // (and warn about it, too).
1007     getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
1008                               llvm::DEBUG_METADATA_VERSION);
1009 
1010   // We need to record the widths of enums and wchar_t, so that we can generate
1011   // the correct build attributes in the ARM backend. wchar_size is also used by
1012   // TargetLibraryInfo.
1013   uint64_t WCharWidth =
1014       Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
1015   getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
1016 
1017   if (getTriple().isOSzOS()) {
1018     getModule().addModuleFlag(llvm::Module::Warning,
1019                               "zos_product_major_version",
1020                               uint32_t(CLANG_VERSION_MAJOR));
1021     getModule().addModuleFlag(llvm::Module::Warning,
1022                               "zos_product_minor_version",
1023                               uint32_t(CLANG_VERSION_MINOR));
1024     getModule().addModuleFlag(llvm::Module::Warning, "zos_product_patchlevel",
1025                               uint32_t(CLANG_VERSION_PATCHLEVEL));
1026     std::string ProductId = getClangVendor() + "clang";
1027     getModule().addModuleFlag(llvm::Module::Error, "zos_product_id",
1028                               llvm::MDString::get(VMContext, ProductId));
1029 
1030     // Record the language because we need it for the PPA2.
1031     StringRef lang_str = languageToString(
1032         LangStandard::getLangStandardForKind(LangOpts.LangStd).Language);
1033     getModule().addModuleFlag(llvm::Module::Error, "zos_cu_language",
1034                               llvm::MDString::get(VMContext, lang_str));
1035 
1036     time_t TT = PreprocessorOpts.SourceDateEpoch
1037                     ? *PreprocessorOpts.SourceDateEpoch
1038                     : std::time(nullptr);
1039     getModule().addModuleFlag(llvm::Module::Max, "zos_translation_time",
1040                               static_cast<uint64_t>(TT));
1041 
1042     // Multiple modes will be supported here.
1043     getModule().addModuleFlag(llvm::Module::Error, "zos_le_char_mode",
1044                               llvm::MDString::get(VMContext, "ascii"));
1045   }
1046 
1047   llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1048   if (   Arch == llvm::Triple::arm
1049       || Arch == llvm::Triple::armeb
1050       || Arch == llvm::Triple::thumb
1051       || Arch == llvm::Triple::thumbeb) {
1052     // The minimum width of an enum in bytes
1053     uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
1054     getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
1055   }
1056 
1057   if (Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64) {
1058     StringRef ABIStr = Target.getABI();
1059     llvm::LLVMContext &Ctx = TheModule.getContext();
1060     getModule().addModuleFlag(llvm::Module::Error, "target-abi",
1061                               llvm::MDString::get(Ctx, ABIStr));
1062   }
1063 
1064   if (CodeGenOpts.SanitizeCfiCrossDso) {
1065     // Indicate that we want cross-DSO control flow integrity checks.
1066     getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
1067   }
1068 
1069   if (CodeGenOpts.WholeProgramVTables) {
1070     // Indicate whether VFE was enabled for this module, so that the
1071     // vcall_visibility metadata added under whole program vtables is handled
1072     // appropriately in the optimizer.
1073     getModule().addModuleFlag(llvm::Module::Error, "Virtual Function Elim",
1074                               CodeGenOpts.VirtualFunctionElimination);
1075   }
1076 
1077   if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
1078     getModule().addModuleFlag(llvm::Module::Override,
1079                               "CFI Canonical Jump Tables",
1080                               CodeGenOpts.SanitizeCfiCanonicalJumpTables);
1081   }
1082 
1083   if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) {
1084     getModule().addModuleFlag(llvm::Module::Override, "kcfi", 1);
1085     // KCFI assumes patchable-function-prefix is the same for all indirectly
1086     // called functions. Store the expected offset for code generation.
1087     if (CodeGenOpts.PatchableFunctionEntryOffset)
1088       getModule().addModuleFlag(llvm::Module::Override, "kcfi-offset",
1089                                 CodeGenOpts.PatchableFunctionEntryOffset);
1090   }
1091 
1092   if (CodeGenOpts.CFProtectionReturn &&
1093       Target.checkCFProtectionReturnSupported(getDiags())) {
1094     // Indicate that we want to instrument return control flow protection.
1095     getModule().addModuleFlag(llvm::Module::Min, "cf-protection-return",
1096                               1);
1097   }
1098 
1099   if (CodeGenOpts.CFProtectionBranch &&
1100       Target.checkCFProtectionBranchSupported(getDiags())) {
1101     // Indicate that we want to instrument branch control flow protection.
1102     getModule().addModuleFlag(llvm::Module::Min, "cf-protection-branch",
1103                               1);
1104   }
1105 
1106   if (CodeGenOpts.FunctionReturnThunks)
1107     getModule().addModuleFlag(llvm::Module::Override, "function_return_thunk_extern", 1);
1108 
1109   if (CodeGenOpts.IndirectBranchCSPrefix)
1110     getModule().addModuleFlag(llvm::Module::Override, "indirect_branch_cs_prefix", 1);
1111 
1112   // Add module metadata for return address signing (ignoring
1113   // non-leaf/all) and stack tagging. These are actually turned on by function
1114   // attributes, but we use module metadata to emit build attributes. This is
1115   // needed for LTO, where the function attributes are inside bitcode
1116   // serialised into a global variable by the time build attributes are
1117   // emitted, so we can't access them. LTO objects could be compiled with
1118   // different flags therefore module flags are set to "Min" behavior to achieve
1119   // the same end result of the normal build where e.g BTI is off if any object
1120   // doesn't support it.
1121   if (Context.getTargetInfo().hasFeature("ptrauth") &&
1122       LangOpts.getSignReturnAddressScope() !=
1123           LangOptions::SignReturnAddressScopeKind::None)
1124     getModule().addModuleFlag(llvm::Module::Override,
1125                               "sign-return-address-buildattr", 1);
1126   if (LangOpts.Sanitize.has(SanitizerKind::MemtagStack))
1127     getModule().addModuleFlag(llvm::Module::Override,
1128                               "tag-stack-memory-buildattr", 1);
1129 
1130   if (Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb ||
1131       Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
1132       Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_32 ||
1133       Arch == llvm::Triple::aarch64_be) {
1134     if (LangOpts.BranchTargetEnforcement)
1135       getModule().addModuleFlag(llvm::Module::Min, "branch-target-enforcement",
1136                                 1);
1137     if (LangOpts.BranchProtectionPAuthLR)
1138       getModule().addModuleFlag(llvm::Module::Min, "branch-protection-pauth-lr",
1139                                 1);
1140     if (LangOpts.GuardedControlStack)
1141       getModule().addModuleFlag(llvm::Module::Min, "guarded-control-stack", 1);
1142     if (LangOpts.hasSignReturnAddress())
1143       getModule().addModuleFlag(llvm::Module::Min, "sign-return-address", 1);
1144     if (LangOpts.isSignReturnAddressScopeAll())
1145       getModule().addModuleFlag(llvm::Module::Min, "sign-return-address-all",
1146                                 1);
1147     if (!LangOpts.isSignReturnAddressWithAKey())
1148       getModule().addModuleFlag(llvm::Module::Min,
1149                                 "sign-return-address-with-bkey", 1);
1150   }
1151 
1152   if (CodeGenOpts.StackClashProtector)
1153     getModule().addModuleFlag(
1154         llvm::Module::Override, "probe-stack",
1155         llvm::MDString::get(TheModule.getContext(), "inline-asm"));
1156 
1157   if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
1158     getModule().addModuleFlag(llvm::Module::Min, "stack-probe-size",
1159                               CodeGenOpts.StackProbeSize);
1160 
1161   if (!CodeGenOpts.MemoryProfileOutput.empty()) {
1162     llvm::LLVMContext &Ctx = TheModule.getContext();
1163     getModule().addModuleFlag(
1164         llvm::Module::Error, "MemProfProfileFilename",
1165         llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput));
1166   }
1167 
1168   if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
1169     // Indicate whether __nvvm_reflect should be configured to flush denormal
1170     // floating point values to 0.  (This corresponds to its "__CUDA_FTZ"
1171     // property.)
1172     getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
1173                               CodeGenOpts.FP32DenormalMode.Output !=
1174                                   llvm::DenormalMode::IEEE);
1175   }
1176 
1177   if (LangOpts.EHAsynch)
1178     getModule().addModuleFlag(llvm::Module::Warning, "eh-asynch", 1);
1179 
1180   // Indicate whether this Module was compiled with -fopenmp
1181   if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
1182     getModule().addModuleFlag(llvm::Module::Max, "openmp", LangOpts.OpenMP);
1183   if (getLangOpts().OpenMPIsTargetDevice)
1184     getModule().addModuleFlag(llvm::Module::Max, "openmp-device",
1185                               LangOpts.OpenMP);
1186 
1187   // Emit OpenCL specific module metadata: OpenCL/SPIR version.
1188   if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice && getTriple().isSPIRV())) {
1189     EmitOpenCLMetadata();
1190     // Emit SPIR version.
1191     if (getTriple().isSPIR()) {
1192       // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
1193       // opencl.spir.version named metadata.
1194       // C++ for OpenCL has a distinct mapping for version compatibility with
1195       // OpenCL.
1196       auto Version = LangOpts.getOpenCLCompatibleVersion();
1197       llvm::Metadata *SPIRVerElts[] = {
1198           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1199               Int32Ty, Version / 100)),
1200           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1201               Int32Ty, (Version / 100 > 1) ? 0 : 2))};
1202       llvm::NamedMDNode *SPIRVerMD =
1203           TheModule.getOrInsertNamedMetadata("opencl.spir.version");
1204       llvm::LLVMContext &Ctx = TheModule.getContext();
1205       SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
1206     }
1207   }
1208 
1209   // HLSL related end of code gen work items.
1210   if (LangOpts.HLSL)
1211     getHLSLRuntime().finishCodeGen();
1212 
1213   if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
1214     assert(PLevel < 3 && "Invalid PIC Level");
1215     getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
1216     if (Context.getLangOpts().PIE)
1217       getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
1218   }
1219 
1220   if (getCodeGenOpts().CodeModel.size() > 0) {
1221     unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
1222                   .Case("tiny", llvm::CodeModel::Tiny)
1223                   .Case("small", llvm::CodeModel::Small)
1224                   .Case("kernel", llvm::CodeModel::Kernel)
1225                   .Case("medium", llvm::CodeModel::Medium)
1226                   .Case("large", llvm::CodeModel::Large)
1227                   .Default(~0u);
1228     if (CM != ~0u) {
1229       llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
1230       getModule().setCodeModel(codeModel);
1231 
1232       if ((CM == llvm::CodeModel::Medium || CM == llvm::CodeModel::Large) &&
1233           Context.getTargetInfo().getTriple().getArch() ==
1234               llvm::Triple::x86_64) {
1235         getModule().setLargeDataThreshold(getCodeGenOpts().LargeDataThreshold);
1236       }
1237     }
1238   }
1239 
1240   if (CodeGenOpts.NoPLT)
1241     getModule().setRtLibUseGOT();
1242   if (getTriple().isOSBinFormatELF() &&
1243       CodeGenOpts.DirectAccessExternalData !=
1244           getModule().getDirectAccessExternalData()) {
1245     getModule().setDirectAccessExternalData(
1246         CodeGenOpts.DirectAccessExternalData);
1247   }
1248   if (CodeGenOpts.UnwindTables)
1249     getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables));
1250 
1251   switch (CodeGenOpts.getFramePointer()) {
1252   case CodeGenOptions::FramePointerKind::None:
1253     // 0 ("none") is the default.
1254     break;
1255   case CodeGenOptions::FramePointerKind::NonLeaf:
1256     getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
1257     break;
1258   case CodeGenOptions::FramePointerKind::All:
1259     getModule().setFramePointer(llvm::FramePointerKind::All);
1260     break;
1261   }
1262 
1263   SimplifyPersonality();
1264 
1265   if (getCodeGenOpts().EmitDeclMetadata)
1266     EmitDeclMetadata();
1267 
1268   if (getCodeGenOpts().CoverageNotesFile.size() ||
1269       getCodeGenOpts().CoverageDataFile.size())
1270     EmitCoverageFile();
1271 
1272   if (CGDebugInfo *DI = getModuleDebugInfo())
1273     DI->finalize();
1274 
1275   if (getCodeGenOpts().EmitVersionIdentMetadata)
1276     EmitVersionIdentMetadata();
1277 
1278   if (!getCodeGenOpts().RecordCommandLine.empty())
1279     EmitCommandLineMetadata();
1280 
1281   if (!getCodeGenOpts().StackProtectorGuard.empty())
1282     getModule().setStackProtectorGuard(getCodeGenOpts().StackProtectorGuard);
1283   if (!getCodeGenOpts().StackProtectorGuardReg.empty())
1284     getModule().setStackProtectorGuardReg(
1285         getCodeGenOpts().StackProtectorGuardReg);
1286   if (!getCodeGenOpts().StackProtectorGuardSymbol.empty())
1287     getModule().setStackProtectorGuardSymbol(
1288         getCodeGenOpts().StackProtectorGuardSymbol);
1289   if (getCodeGenOpts().StackProtectorGuardOffset != INT_MAX)
1290     getModule().setStackProtectorGuardOffset(
1291         getCodeGenOpts().StackProtectorGuardOffset);
1292   if (getCodeGenOpts().StackAlignment)
1293     getModule().setOverrideStackAlignment(getCodeGenOpts().StackAlignment);
1294   if (getCodeGenOpts().SkipRaxSetup)
1295     getModule().addModuleFlag(llvm::Module::Override, "SkipRaxSetup", 1);
1296   if (getLangOpts().RegCall4)
1297     getModule().addModuleFlag(llvm::Module::Override, "RegCallv4", 1);
1298 
1299   if (getContext().getTargetInfo().getMaxTLSAlign())
1300     getModule().addModuleFlag(llvm::Module::Error, "MaxTLSAlign",
1301                               getContext().getTargetInfo().getMaxTLSAlign());
1302 
1303   getTargetCodeGenInfo().emitTargetGlobals(*this);
1304 
1305   getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames);
1306 
1307   EmitBackendOptionsMetadata(getCodeGenOpts());
1308 
1309   // If there is device offloading code embed it in the host now.
1310   EmbedObject(&getModule(), CodeGenOpts, getDiags());
1311 
1312   // Set visibility from DLL storage class
1313   // We do this at the end of LLVM IR generation; after any operation
1314   // that might affect the DLL storage class or the visibility, and
1315   // before anything that might act on these.
1316   setVisibilityFromDLLStorageClass(LangOpts, getModule());
1317 }
1318 
1319 void CodeGenModule::EmitOpenCLMetadata() {
1320   // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
1321   // opencl.ocl.version named metadata node.
1322   // C++ for OpenCL has a distinct mapping for versions compatibile with OpenCL.
1323   auto Version = LangOpts.getOpenCLCompatibleVersion();
1324   llvm::Metadata *OCLVerElts[] = {
1325       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1326           Int32Ty, Version / 100)),
1327       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1328           Int32Ty, (Version % 100) / 10))};
1329   llvm::NamedMDNode *OCLVerMD =
1330       TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
1331   llvm::LLVMContext &Ctx = TheModule.getContext();
1332   OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
1333 }
1334 
1335 void CodeGenModule::EmitBackendOptionsMetadata(
1336     const CodeGenOptions &CodeGenOpts) {
1337   if (getTriple().isRISCV()) {
1338     getModule().addModuleFlag(llvm::Module::Min, "SmallDataLimit",
1339                               CodeGenOpts.SmallDataLimit);
1340   }
1341 }
1342 
1343 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
1344   // Make sure that this type is translated.
1345   Types.UpdateCompletedType(TD);
1346 }
1347 
1348 void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
1349   // Make sure that this type is translated.
1350   Types.RefreshTypeCacheForClass(RD);
1351 }
1352 
1353 llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
1354   if (!TBAA)
1355     return nullptr;
1356   return TBAA->getTypeInfo(QTy);
1357 }
1358 
1359 TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
1360   if (!TBAA)
1361     return TBAAAccessInfo();
1362   if (getLangOpts().CUDAIsDevice) {
1363     // As CUDA builtin surface/texture types are replaced, skip generating TBAA
1364     // access info.
1365     if (AccessType->isCUDADeviceBuiltinSurfaceType()) {
1366       if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() !=
1367           nullptr)
1368         return TBAAAccessInfo();
1369     } else if (AccessType->isCUDADeviceBuiltinTextureType()) {
1370       if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() !=
1371           nullptr)
1372         return TBAAAccessInfo();
1373     }
1374   }
1375   return TBAA->getAccessInfo(AccessType);
1376 }
1377 
1378 TBAAAccessInfo
1379 CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
1380   if (!TBAA)
1381     return TBAAAccessInfo();
1382   return TBAA->getVTablePtrAccessInfo(VTablePtrType);
1383 }
1384 
1385 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
1386   if (!TBAA)
1387     return nullptr;
1388   return TBAA->getTBAAStructInfo(QTy);
1389 }
1390 
1391 llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
1392   if (!TBAA)
1393     return nullptr;
1394   return TBAA->getBaseTypeInfo(QTy);
1395 }
1396 
1397 llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
1398   if (!TBAA)
1399     return nullptr;
1400   return TBAA->getAccessTagInfo(Info);
1401 }
1402 
1403 TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
1404                                                    TBAAAccessInfo TargetInfo) {
1405   if (!TBAA)
1406     return TBAAAccessInfo();
1407   return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
1408 }
1409 
1410 TBAAAccessInfo
1411 CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
1412                                                    TBAAAccessInfo InfoB) {
1413   if (!TBAA)
1414     return TBAAAccessInfo();
1415   return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
1416 }
1417 
1418 TBAAAccessInfo
1419 CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
1420                                               TBAAAccessInfo SrcInfo) {
1421   if (!TBAA)
1422     return TBAAAccessInfo();
1423   return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
1424 }
1425 
1426 void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
1427                                                 TBAAAccessInfo TBAAInfo) {
1428   if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
1429     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
1430 }
1431 
1432 void CodeGenModule::DecorateInstructionWithInvariantGroup(
1433     llvm::Instruction *I, const CXXRecordDecl *RD) {
1434   I->setMetadata(llvm::LLVMContext::MD_invariant_group,
1435                  llvm::MDNode::get(getLLVMContext(), {}));
1436 }
1437 
1438 void CodeGenModule::Error(SourceLocation loc, StringRef message) {
1439   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
1440   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
1441 }
1442 
1443 /// ErrorUnsupported - Print out an error that codegen doesn't support the
1444 /// specified stmt yet.
1445 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
1446   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1447                                                "cannot compile this %0 yet");
1448   std::string Msg = Type;
1449   getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
1450       << Msg << S->getSourceRange();
1451 }
1452 
1453 /// ErrorUnsupported - Print out an error that codegen doesn't support the
1454 /// specified decl yet.
1455 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
1456   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1457                                                "cannot compile this %0 yet");
1458   std::string Msg = Type;
1459   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
1460 }
1461 
1462 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
1463   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
1464 }
1465 
1466 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
1467                                         const NamedDecl *D) const {
1468   // Internal definitions always have default visibility.
1469   if (GV->hasLocalLinkage()) {
1470     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1471     return;
1472   }
1473   if (!D)
1474     return;
1475 
1476   // Set visibility for definitions, and for declarations if requested globally
1477   // or set explicitly.
1478   LinkageInfo LV = D->getLinkageAndVisibility();
1479 
1480   // OpenMP declare target variables must be visible to the host so they can
1481   // be registered. We require protected visibility unless the variable has
1482   // the DT_nohost modifier and does not need to be registered.
1483   if (Context.getLangOpts().OpenMP &&
1484       Context.getLangOpts().OpenMPIsTargetDevice && isa<VarDecl>(D) &&
1485       D->hasAttr<OMPDeclareTargetDeclAttr>() &&
1486       D->getAttr<OMPDeclareTargetDeclAttr>()->getDevType() !=
1487           OMPDeclareTargetDeclAttr::DT_NoHost &&
1488       LV.getVisibility() == HiddenVisibility) {
1489     GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
1490     return;
1491   }
1492 
1493   if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) {
1494     // Reject incompatible dlllstorage and visibility annotations.
1495     if (!LV.isVisibilityExplicit())
1496       return;
1497     if (GV->hasDLLExportStorageClass()) {
1498       if (LV.getVisibility() == HiddenVisibility)
1499         getDiags().Report(D->getLocation(),
1500                           diag::err_hidden_visibility_dllexport);
1501     } else if (LV.getVisibility() != DefaultVisibility) {
1502       getDiags().Report(D->getLocation(),
1503                         diag::err_non_default_visibility_dllimport);
1504     }
1505     return;
1506   }
1507 
1508   if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls ||
1509       !GV->isDeclarationForLinker())
1510     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
1511 }
1512 
1513 static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
1514                                  llvm::GlobalValue *GV) {
1515   if (GV->hasLocalLinkage())
1516     return true;
1517 
1518   if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
1519     return true;
1520 
1521   // DLLImport explicitly marks the GV as external.
1522   if (GV->hasDLLImportStorageClass())
1523     return false;
1524 
1525   const llvm::Triple &TT = CGM.getTriple();
1526   const auto &CGOpts = CGM.getCodeGenOpts();
1527   if (TT.isWindowsGNUEnvironment()) {
1528     // In MinGW, variables without DLLImport can still be automatically
1529     // imported from a DLL by the linker; don't mark variables that
1530     // potentially could come from another DLL as DSO local.
1531 
1532     // With EmulatedTLS, TLS variables can be autoimported from other DLLs
1533     // (and this actually happens in the public interface of libstdc++), so
1534     // such variables can't be marked as DSO local. (Native TLS variables
1535     // can't be dllimported at all, though.)
1536     if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
1537         (!GV->isThreadLocal() || CGM.getCodeGenOpts().EmulatedTLS) &&
1538         CGOpts.AutoImport)
1539       return false;
1540   }
1541 
1542   // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols
1543   // remain unresolved in the link, they can be resolved to zero, which is
1544   // outside the current DSO.
1545   if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
1546     return false;
1547 
1548   // Every other GV is local on COFF.
1549   // Make an exception for windows OS in the triple: Some firmware builds use
1550   // *-win32-macho triples. This (accidentally?) produced windows relocations
1551   // without GOT tables in older clang versions; Keep this behaviour.
1552   // FIXME: even thread local variables?
1553   if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
1554     return true;
1555 
1556   // Only handle COFF and ELF for now.
1557   if (!TT.isOSBinFormatELF())
1558     return false;
1559 
1560   // If this is not an executable, don't assume anything is local.
1561   llvm::Reloc::Model RM = CGOpts.RelocationModel;
1562   const auto &LOpts = CGM.getLangOpts();
1563   if (RM != llvm::Reloc::Static && !LOpts.PIE) {
1564     // On ELF, if -fno-semantic-interposition is specified and the target
1565     // supports local aliases, there will be neither CC1
1566     // -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set
1567     // dso_local on the function if using a local alias is preferable (can avoid
1568     // PLT indirection).
1569     if (!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias()))
1570       return false;
1571     return !(CGM.getLangOpts().SemanticInterposition ||
1572              CGM.getLangOpts().HalfNoSemanticInterposition);
1573   }
1574 
1575   // A definition cannot be preempted from an executable.
1576   if (!GV->isDeclarationForLinker())
1577     return true;
1578 
1579   // Most PIC code sequences that assume that a symbol is local cannot produce a
1580   // 0 if it turns out the symbol is undefined. While this is ABI and relocation
1581   // depended, it seems worth it to handle it here.
1582   if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
1583     return false;
1584 
1585   // PowerPC64 prefers TOC indirection to avoid copy relocations.
1586   if (TT.isPPC64())
1587     return false;
1588 
1589   if (CGOpts.DirectAccessExternalData) {
1590     // If -fdirect-access-external-data (default for -fno-pic), set dso_local
1591     // for non-thread-local variables. If the symbol is not defined in the
1592     // executable, a copy relocation will be needed at link time. dso_local is
1593     // excluded for thread-local variables because they generally don't support
1594     // copy relocations.
1595     if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
1596       if (!Var->isThreadLocal())
1597         return true;
1598 
1599     // -fno-pic sets dso_local on a function declaration to allow direct
1600     // accesses when taking its address (similar to a data symbol). If the
1601     // function is not defined in the executable, a canonical PLT entry will be
1602     // needed at link time. -fno-direct-access-external-data can avoid the
1603     // canonical PLT entry. We don't generalize this condition to -fpie/-fpic as
1604     // it could just cause trouble without providing perceptible benefits.
1605     if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
1606       return true;
1607   }
1608 
1609   // If we can use copy relocations we can assume it is local.
1610 
1611   // Otherwise don't assume it is local.
1612   return false;
1613 }
1614 
1615 void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
1616   GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
1617 }
1618 
1619 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
1620                                           GlobalDecl GD) const {
1621   const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
1622   // C++ destructors have a few C++ ABI specific special cases.
1623   if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
1624     getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
1625     return;
1626   }
1627   setDLLImportDLLExport(GV, D);
1628 }
1629 
1630 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
1631                                           const NamedDecl *D) const {
1632   if (D && D->isExternallyVisible()) {
1633     if (D->hasAttr<DLLImportAttr>())
1634       GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
1635     else if ((D->hasAttr<DLLExportAttr>() ||
1636               shouldMapVisibilityToDLLExport(D)) &&
1637              !GV->isDeclarationForLinker())
1638       GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
1639   }
1640 }
1641 
1642 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
1643                                     GlobalDecl GD) const {
1644   setDLLImportDLLExport(GV, GD);
1645   setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl()));
1646 }
1647 
1648 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
1649                                     const NamedDecl *D) const {
1650   setDLLImportDLLExport(GV, D);
1651   setGVPropertiesAux(GV, D);
1652 }
1653 
1654 void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV,
1655                                        const NamedDecl *D) const {
1656   setGlobalVisibility(GV, D);
1657   setDSOLocal(GV);
1658   GV->setPartition(CodeGenOpts.SymbolPartition);
1659 }
1660 
1661 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
1662   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
1663       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
1664       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
1665       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
1666       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
1667 }
1668 
1669 llvm::GlobalVariable::ThreadLocalMode
1670 CodeGenModule::GetDefaultLLVMTLSModel() const {
1671   switch (CodeGenOpts.getDefaultTLSModel()) {
1672   case CodeGenOptions::GeneralDynamicTLSModel:
1673     return llvm::GlobalVariable::GeneralDynamicTLSModel;
1674   case CodeGenOptions::LocalDynamicTLSModel:
1675     return llvm::GlobalVariable::LocalDynamicTLSModel;
1676   case CodeGenOptions::InitialExecTLSModel:
1677     return llvm::GlobalVariable::InitialExecTLSModel;
1678   case CodeGenOptions::LocalExecTLSModel:
1679     return llvm::GlobalVariable::LocalExecTLSModel;
1680   }
1681   llvm_unreachable("Invalid TLS model!");
1682 }
1683 
1684 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
1685   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
1686 
1687   llvm::GlobalValue::ThreadLocalMode TLM;
1688   TLM = GetDefaultLLVMTLSModel();
1689 
1690   // Override the TLS model if it is explicitly specified.
1691   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
1692     TLM = GetLLVMTLSModel(Attr->getModel());
1693   }
1694 
1695   GV->setThreadLocalMode(TLM);
1696 }
1697 
1698 static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
1699                                           StringRef Name) {
1700   const TargetInfo &Target = CGM.getTarget();
1701   return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
1702 }
1703 
1704 static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
1705                                                  const CPUSpecificAttr *Attr,
1706                                                  unsigned CPUIndex,
1707                                                  raw_ostream &Out) {
1708   // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
1709   // supported.
1710   if (Attr)
1711     Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName());
1712   else if (CGM.getTarget().supportsIFunc())
1713     Out << ".resolver";
1714 }
1715 
1716 static void AppendTargetVersionMangling(const CodeGenModule &CGM,
1717                                         const TargetVersionAttr *Attr,
1718                                         raw_ostream &Out) {
1719   if (Attr->isDefaultVersion())
1720     return;
1721   Out << "._";
1722   const TargetInfo &TI = CGM.getTarget();
1723   llvm::SmallVector<StringRef, 8> Feats;
1724   Attr->getFeatures(Feats);
1725   llvm::stable_sort(Feats, [&TI](const StringRef FeatL, const StringRef FeatR) {
1726     return TI.multiVersionSortPriority(FeatL) <
1727            TI.multiVersionSortPriority(FeatR);
1728   });
1729   for (const auto &Feat : Feats) {
1730     Out << 'M';
1731     Out << Feat;
1732   }
1733 }
1734 
1735 static void AppendTargetMangling(const CodeGenModule &CGM,
1736                                  const TargetAttr *Attr, raw_ostream &Out) {
1737   if (Attr->isDefaultVersion())
1738     return;
1739 
1740   Out << '.';
1741   const TargetInfo &Target = CGM.getTarget();
1742   ParsedTargetAttr Info = Target.parseTargetAttr(Attr->getFeaturesStr());
1743   llvm::sort(Info.Features, [&Target](StringRef LHS, StringRef RHS) {
1744     // Multiversioning doesn't allow "no-${feature}", so we can
1745     // only have "+" prefixes here.
1746     assert(LHS.starts_with("+") && RHS.starts_with("+") &&
1747            "Features should always have a prefix.");
1748     return Target.multiVersionSortPriority(LHS.substr(1)) >
1749            Target.multiVersionSortPriority(RHS.substr(1));
1750   });
1751 
1752   bool IsFirst = true;
1753 
1754   if (!Info.CPU.empty()) {
1755     IsFirst = false;
1756     Out << "arch_" << Info.CPU;
1757   }
1758 
1759   for (StringRef Feat : Info.Features) {
1760     if (!IsFirst)
1761       Out << '_';
1762     IsFirst = false;
1763     Out << Feat.substr(1);
1764   }
1765 }
1766 
1767 // Returns true if GD is a function decl with internal linkage and
1768 // needs a unique suffix after the mangled name.
1769 static bool isUniqueInternalLinkageDecl(GlobalDecl GD,
1770                                         CodeGenModule &CGM) {
1771   const Decl *D = GD.getDecl();
1772   return !CGM.getModuleNameHash().empty() && isa<FunctionDecl>(D) &&
1773          (CGM.getFunctionLinkage(GD) == llvm::GlobalValue::InternalLinkage);
1774 }
1775 
1776 static void AppendTargetClonesMangling(const CodeGenModule &CGM,
1777                                        const TargetClonesAttr *Attr,
1778                                        unsigned VersionIndex,
1779                                        raw_ostream &Out) {
1780   const TargetInfo &TI = CGM.getTarget();
1781   if (TI.getTriple().isAArch64()) {
1782     StringRef FeatureStr = Attr->getFeatureStr(VersionIndex);
1783     if (FeatureStr == "default")
1784       return;
1785     Out << "._";
1786     SmallVector<StringRef, 8> Features;
1787     FeatureStr.split(Features, "+");
1788     llvm::stable_sort(Features,
1789                       [&TI](const StringRef FeatL, const StringRef FeatR) {
1790                         return TI.multiVersionSortPriority(FeatL) <
1791                                TI.multiVersionSortPriority(FeatR);
1792                       });
1793     for (auto &Feat : Features) {
1794       Out << 'M';
1795       Out << Feat;
1796     }
1797   } else {
1798     Out << '.';
1799     StringRef FeatureStr = Attr->getFeatureStr(VersionIndex);
1800     if (FeatureStr.starts_with("arch="))
1801       Out << "arch_" << FeatureStr.substr(sizeof("arch=") - 1);
1802     else
1803       Out << FeatureStr;
1804 
1805     Out << '.' << Attr->getMangledIndex(VersionIndex);
1806   }
1807 }
1808 
1809 static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD,
1810                                       const NamedDecl *ND,
1811                                       bool OmitMultiVersionMangling = false) {
1812   SmallString<256> Buffer;
1813   llvm::raw_svector_ostream Out(Buffer);
1814   MangleContext &MC = CGM.getCXXABI().getMangleContext();
1815   if (!CGM.getModuleNameHash().empty())
1816     MC.needsUniqueInternalLinkageNames();
1817   bool ShouldMangle = MC.shouldMangleDeclName(ND);
1818   if (ShouldMangle)
1819     MC.mangleName(GD.getWithDecl(ND), Out);
1820   else {
1821     IdentifierInfo *II = ND->getIdentifier();
1822     assert(II && "Attempt to mangle unnamed decl.");
1823     const auto *FD = dyn_cast<FunctionDecl>(ND);
1824 
1825     if (FD &&
1826         FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
1827       if (CGM.getLangOpts().RegCall4)
1828         Out << "__regcall4__" << II->getName();
1829       else
1830         Out << "__regcall3__" << II->getName();
1831     } else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
1832                GD.getKernelReferenceKind() == KernelReferenceKind::Stub) {
1833       Out << "__device_stub__" << II->getName();
1834     } else {
1835       Out << II->getName();
1836     }
1837   }
1838 
1839   // Check if the module name hash should be appended for internal linkage
1840   // symbols.   This should come before multi-version target suffixes are
1841   // appended. This is to keep the name and module hash suffix of the
1842   // internal linkage function together.  The unique suffix should only be
1843   // added when name mangling is done to make sure that the final name can
1844   // be properly demangled.  For example, for C functions without prototypes,
1845   // name mangling is not done and the unique suffix should not be appeneded
1846   // then.
1847   if (ShouldMangle && isUniqueInternalLinkageDecl(GD, CGM)) {
1848     assert(CGM.getCodeGenOpts().UniqueInternalLinkageNames &&
1849            "Hash computed when not explicitly requested");
1850     Out << CGM.getModuleNameHash();
1851   }
1852 
1853   if (const auto *FD = dyn_cast<FunctionDecl>(ND))
1854     if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
1855       switch (FD->getMultiVersionKind()) {
1856       case MultiVersionKind::CPUDispatch:
1857       case MultiVersionKind::CPUSpecific:
1858         AppendCPUSpecificCPUDispatchMangling(CGM,
1859                                              FD->getAttr<CPUSpecificAttr>(),
1860                                              GD.getMultiVersionIndex(), Out);
1861         break;
1862       case MultiVersionKind::Target:
1863         AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
1864         break;
1865       case MultiVersionKind::TargetVersion:
1866         AppendTargetVersionMangling(CGM, FD->getAttr<TargetVersionAttr>(), Out);
1867         break;
1868       case MultiVersionKind::TargetClones:
1869         AppendTargetClonesMangling(CGM, FD->getAttr<TargetClonesAttr>(),
1870                                    GD.getMultiVersionIndex(), Out);
1871         break;
1872       case MultiVersionKind::None:
1873         llvm_unreachable("None multiversion type isn't valid here");
1874       }
1875     }
1876 
1877   // Make unique name for device side static file-scope variable for HIP.
1878   if (CGM.getContext().shouldExternalize(ND) &&
1879       CGM.getLangOpts().GPURelocatableDeviceCode &&
1880       CGM.getLangOpts().CUDAIsDevice)
1881     CGM.printPostfixForExternalizedDecl(Out, ND);
1882 
1883   return std::string(Out.str());
1884 }
1885 
1886 void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
1887                                             const FunctionDecl *FD,
1888                                             StringRef &CurName) {
1889   if (!FD->isMultiVersion())
1890     return;
1891 
1892   // Get the name of what this would be without the 'target' attribute.  This
1893   // allows us to lookup the version that was emitted when this wasn't a
1894   // multiversion function.
1895   std::string NonTargetName =
1896       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
1897   GlobalDecl OtherGD;
1898   if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
1899     assert(OtherGD.getCanonicalDecl()
1900                .getDecl()
1901                ->getAsFunction()
1902                ->isMultiVersion() &&
1903            "Other GD should now be a multiversioned function");
1904     // OtherFD is the version of this function that was mangled BEFORE
1905     // becoming a MultiVersion function.  It potentially needs to be updated.
1906     const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
1907                                       .getDecl()
1908                                       ->getAsFunction()
1909                                       ->getMostRecentDecl();
1910     std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
1911     // This is so that if the initial version was already the 'default'
1912     // version, we don't try to update it.
1913     if (OtherName != NonTargetName) {
1914       // Remove instead of erase, since others may have stored the StringRef
1915       // to this.
1916       const auto ExistingRecord = Manglings.find(NonTargetName);
1917       if (ExistingRecord != std::end(Manglings))
1918         Manglings.remove(&(*ExistingRecord));
1919       auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
1920       StringRef OtherNameRef = MangledDeclNames[OtherGD.getCanonicalDecl()] =
1921           Result.first->first();
1922       // If this is the current decl is being created, make sure we update the name.
1923       if (GD.getCanonicalDecl() == OtherGD.getCanonicalDecl())
1924         CurName = OtherNameRef;
1925       if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
1926         Entry->setName(OtherName);
1927     }
1928   }
1929 }
1930 
1931 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
1932   GlobalDecl CanonicalGD = GD.getCanonicalDecl();
1933 
1934   // Some ABIs don't have constructor variants.  Make sure that base and
1935   // complete constructors get mangled the same.
1936   if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
1937     if (!getTarget().getCXXABI().hasConstructorVariants()) {
1938       CXXCtorType OrigCtorType = GD.getCtorType();
1939       assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
1940       if (OrigCtorType == Ctor_Base)
1941         CanonicalGD = GlobalDecl(CD, Ctor_Complete);
1942     }
1943   }
1944 
1945   // In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a
1946   // static device variable depends on whether the variable is referenced by
1947   // a host or device host function. Therefore the mangled name cannot be
1948   // cached.
1949   if (!LangOpts.CUDAIsDevice || !getContext().mayExternalize(GD.getDecl())) {
1950     auto FoundName = MangledDeclNames.find(CanonicalGD);
1951     if (FoundName != MangledDeclNames.end())
1952       return FoundName->second;
1953   }
1954 
1955   // Keep the first result in the case of a mangling collision.
1956   const auto *ND = cast<NamedDecl>(GD.getDecl());
1957   std::string MangledName = getMangledNameImpl(*this, GD, ND);
1958 
1959   // Ensure either we have different ABIs between host and device compilations,
1960   // says host compilation following MSVC ABI but device compilation follows
1961   // Itanium C++ ABI or, if they follow the same ABI, kernel names after
1962   // mangling should be the same after name stubbing. The later checking is
1963   // very important as the device kernel name being mangled in host-compilation
1964   // is used to resolve the device binaries to be executed. Inconsistent naming
1965   // result in undefined behavior. Even though we cannot check that naming
1966   // directly between host- and device-compilations, the host- and
1967   // device-mangling in host compilation could help catching certain ones.
1968   assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() ||
1969          getContext().shouldExternalize(ND) || getLangOpts().CUDAIsDevice ||
1970          (getContext().getAuxTargetInfo() &&
1971           (getContext().getAuxTargetInfo()->getCXXABI() !=
1972            getContext().getTargetInfo().getCXXABI())) ||
1973          getCUDARuntime().getDeviceSideName(ND) ==
1974              getMangledNameImpl(
1975                  *this,
1976                  GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel),
1977                  ND));
1978 
1979   auto Result = Manglings.insert(std::make_pair(MangledName, GD));
1980   return MangledDeclNames[CanonicalGD] = Result.first->first();
1981 }
1982 
1983 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
1984                                              const BlockDecl *BD) {
1985   MangleContext &MangleCtx = getCXXABI().getMangleContext();
1986   const Decl *D = GD.getDecl();
1987 
1988   SmallString<256> Buffer;
1989   llvm::raw_svector_ostream Out(Buffer);
1990   if (!D)
1991     MangleCtx.mangleGlobalBlock(BD,
1992       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
1993   else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
1994     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
1995   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
1996     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
1997   else
1998     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
1999 
2000   auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
2001   return Result.first->first();
2002 }
2003 
2004 const GlobalDecl CodeGenModule::getMangledNameDecl(StringRef Name) {
2005   auto it = MangledDeclNames.begin();
2006   while (it != MangledDeclNames.end()) {
2007     if (it->second == Name)
2008       return it->first;
2009     it++;
2010   }
2011   return GlobalDecl();
2012 }
2013 
2014 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
2015   return getModule().getNamedValue(Name);
2016 }
2017 
2018 /// AddGlobalCtor - Add a function to the list that will be called before
2019 /// main() runs.
2020 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
2021                                   unsigned LexOrder,
2022                                   llvm::Constant *AssociatedData) {
2023   // FIXME: Type coercion of void()* types.
2024   GlobalCtors.push_back(Structor(Priority, LexOrder, Ctor, AssociatedData));
2025 }
2026 
2027 /// AddGlobalDtor - Add a function to the list that will be called
2028 /// when the module is unloaded.
2029 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority,
2030                                   bool IsDtorAttrFunc) {
2031   if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
2032       (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) {
2033     DtorsUsingAtExit[Priority].push_back(Dtor);
2034     return;
2035   }
2036 
2037   // FIXME: Type coercion of void()* types.
2038   GlobalDtors.push_back(Structor(Priority, ~0U, Dtor, nullptr));
2039 }
2040 
2041 void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
2042   if (Fns.empty()) return;
2043 
2044   // Ctor function type is void()*.
2045   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
2046   llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
2047       TheModule.getDataLayout().getProgramAddressSpace());
2048 
2049   // Get the type of a ctor entry, { i32, void ()*, i8* }.
2050   llvm::StructType *CtorStructTy = llvm::StructType::get(
2051       Int32Ty, CtorPFTy, VoidPtrTy);
2052 
2053   // Construct the constructor and destructor arrays.
2054   ConstantInitBuilder builder(*this);
2055   auto ctors = builder.beginArray(CtorStructTy);
2056   for (const auto &I : Fns) {
2057     auto ctor = ctors.beginStruct(CtorStructTy);
2058     ctor.addInt(Int32Ty, I.Priority);
2059     ctor.add(I.Initializer);
2060     if (I.AssociatedData)
2061       ctor.add(I.AssociatedData);
2062     else
2063       ctor.addNullPointer(VoidPtrTy);
2064     ctor.finishAndAddTo(ctors);
2065   }
2066 
2067   auto list =
2068     ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
2069                                 /*constant*/ false,
2070                                 llvm::GlobalValue::AppendingLinkage);
2071 
2072   // The LTO linker doesn't seem to like it when we set an alignment
2073   // on appending variables.  Take it off as a workaround.
2074   list->setAlignment(std::nullopt);
2075 
2076   Fns.clear();
2077 }
2078 
2079 llvm::GlobalValue::LinkageTypes
2080 CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
2081   const auto *D = cast<FunctionDecl>(GD.getDecl());
2082 
2083   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
2084 
2085   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
2086     return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
2087 
2088   return getLLVMLinkageForDeclarator(D, Linkage);
2089 }
2090 
2091 llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
2092   llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
2093   if (!MDS) return nullptr;
2094 
2095   return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
2096 }
2097 
2098 llvm::ConstantInt *CodeGenModule::CreateKCFITypeId(QualType T) {
2099   if (auto *FnType = T->getAs<FunctionProtoType>())
2100     T = getContext().getFunctionType(
2101         FnType->getReturnType(), FnType->getParamTypes(),
2102         FnType->getExtProtoInfo().withExceptionSpec(EST_None));
2103 
2104   std::string OutName;
2105   llvm::raw_string_ostream Out(OutName);
2106   getCXXABI().getMangleContext().mangleCanonicalTypeName(
2107       T, Out, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers);
2108 
2109   if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers)
2110     Out << ".normalized";
2111 
2112   return llvm::ConstantInt::get(Int32Ty,
2113                                 static_cast<uint32_t>(llvm::xxHash64(OutName)));
2114 }
2115 
2116 void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
2117                                               const CGFunctionInfo &Info,
2118                                               llvm::Function *F, bool IsThunk) {
2119   unsigned CallingConv;
2120   llvm::AttributeList PAL;
2121   ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv,
2122                          /*AttrOnCallSite=*/false, IsThunk);
2123   F->setAttributes(PAL);
2124   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
2125 }
2126 
2127 static void removeImageAccessQualifier(std::string& TyName) {
2128   std::string ReadOnlyQual("__read_only");
2129   std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
2130   if (ReadOnlyPos != std::string::npos)
2131     // "+ 1" for the space after access qualifier.
2132     TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
2133   else {
2134     std::string WriteOnlyQual("__write_only");
2135     std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
2136     if (WriteOnlyPos != std::string::npos)
2137       TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
2138     else {
2139       std::string ReadWriteQual("__read_write");
2140       std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
2141       if (ReadWritePos != std::string::npos)
2142         TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
2143     }
2144   }
2145 }
2146 
2147 // Returns the address space id that should be produced to the
2148 // kernel_arg_addr_space metadata. This is always fixed to the ids
2149 // as specified in the SPIR 2.0 specification in order to differentiate
2150 // for example in clGetKernelArgInfo() implementation between the address
2151 // spaces with targets without unique mapping to the OpenCL address spaces
2152 // (basically all single AS CPUs).
2153 static unsigned ArgInfoAddressSpace(LangAS AS) {
2154   switch (AS) {
2155   case LangAS::opencl_global:
2156     return 1;
2157   case LangAS::opencl_constant:
2158     return 2;
2159   case LangAS::opencl_local:
2160     return 3;
2161   case LangAS::opencl_generic:
2162     return 4; // Not in SPIR 2.0 specs.
2163   case LangAS::opencl_global_device:
2164     return 5;
2165   case LangAS::opencl_global_host:
2166     return 6;
2167   default:
2168     return 0; // Assume private.
2169   }
2170 }
2171 
2172 void CodeGenModule::GenKernelArgMetadata(llvm::Function *Fn,
2173                                          const FunctionDecl *FD,
2174                                          CodeGenFunction *CGF) {
2175   assert(((FD && CGF) || (!FD && !CGF)) &&
2176          "Incorrect use - FD and CGF should either be both null or not!");
2177   // Create MDNodes that represent the kernel arg metadata.
2178   // Each MDNode is a list in the form of "key", N number of values which is
2179   // the same number of values as their are kernel arguments.
2180 
2181   const PrintingPolicy &Policy = Context.getPrintingPolicy();
2182 
2183   // MDNode for the kernel argument address space qualifiers.
2184   SmallVector<llvm::Metadata *, 8> addressQuals;
2185 
2186   // MDNode for the kernel argument access qualifiers (images only).
2187   SmallVector<llvm::Metadata *, 8> accessQuals;
2188 
2189   // MDNode for the kernel argument type names.
2190   SmallVector<llvm::Metadata *, 8> argTypeNames;
2191 
2192   // MDNode for the kernel argument base type names.
2193   SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
2194 
2195   // MDNode for the kernel argument type qualifiers.
2196   SmallVector<llvm::Metadata *, 8> argTypeQuals;
2197 
2198   // MDNode for the kernel argument names.
2199   SmallVector<llvm::Metadata *, 8> argNames;
2200 
2201   if (FD && CGF)
2202     for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
2203       const ParmVarDecl *parm = FD->getParamDecl(i);
2204       // Get argument name.
2205       argNames.push_back(llvm::MDString::get(VMContext, parm->getName()));
2206 
2207       if (!getLangOpts().OpenCL)
2208         continue;
2209       QualType ty = parm->getType();
2210       std::string typeQuals;
2211 
2212       // Get image and pipe access qualifier:
2213       if (ty->isImageType() || ty->isPipeType()) {
2214         const Decl *PDecl = parm;
2215         if (const auto *TD = ty->getAs<TypedefType>())
2216           PDecl = TD->getDecl();
2217         const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
2218         if (A && A->isWriteOnly())
2219           accessQuals.push_back(llvm::MDString::get(VMContext, "write_only"));
2220         else if (A && A->isReadWrite())
2221           accessQuals.push_back(llvm::MDString::get(VMContext, "read_write"));
2222         else
2223           accessQuals.push_back(llvm::MDString::get(VMContext, "read_only"));
2224       } else
2225         accessQuals.push_back(llvm::MDString::get(VMContext, "none"));
2226 
2227       auto getTypeSpelling = [&](QualType Ty) {
2228         auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
2229 
2230         if (Ty.isCanonical()) {
2231           StringRef typeNameRef = typeName;
2232           // Turn "unsigned type" to "utype"
2233           if (typeNameRef.consume_front("unsigned "))
2234             return std::string("u") + typeNameRef.str();
2235           if (typeNameRef.consume_front("signed "))
2236             return typeNameRef.str();
2237         }
2238 
2239         return typeName;
2240       };
2241 
2242       if (ty->isPointerType()) {
2243         QualType pointeeTy = ty->getPointeeType();
2244 
2245         // Get address qualifier.
2246         addressQuals.push_back(
2247             llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(
2248                 ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
2249 
2250         // Get argument type name.
2251         std::string typeName = getTypeSpelling(pointeeTy) + "*";
2252         std::string baseTypeName =
2253             getTypeSpelling(pointeeTy.getCanonicalType()) + "*";
2254         argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2255         argBaseTypeNames.push_back(
2256             llvm::MDString::get(VMContext, baseTypeName));
2257 
2258         // Get argument type qualifiers:
2259         if (ty.isRestrictQualified())
2260           typeQuals = "restrict";
2261         if (pointeeTy.isConstQualified() ||
2262             (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
2263           typeQuals += typeQuals.empty() ? "const" : " const";
2264         if (pointeeTy.isVolatileQualified())
2265           typeQuals += typeQuals.empty() ? "volatile" : " volatile";
2266       } else {
2267         uint32_t AddrSpc = 0;
2268         bool isPipe = ty->isPipeType();
2269         if (ty->isImageType() || isPipe)
2270           AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
2271 
2272         addressQuals.push_back(
2273             llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc)));
2274 
2275         // Get argument type name.
2276         ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty;
2277         std::string typeName = getTypeSpelling(ty);
2278         std::string baseTypeName = getTypeSpelling(ty.getCanonicalType());
2279 
2280         // Remove access qualifiers on images
2281         // (as they are inseparable from type in clang implementation,
2282         // but OpenCL spec provides a special query to get access qualifier
2283         // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
2284         if (ty->isImageType()) {
2285           removeImageAccessQualifier(typeName);
2286           removeImageAccessQualifier(baseTypeName);
2287         }
2288 
2289         argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2290         argBaseTypeNames.push_back(
2291             llvm::MDString::get(VMContext, baseTypeName));
2292 
2293         if (isPipe)
2294           typeQuals = "pipe";
2295       }
2296       argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
2297     }
2298 
2299   if (getLangOpts().OpenCL) {
2300     Fn->setMetadata("kernel_arg_addr_space",
2301                     llvm::MDNode::get(VMContext, addressQuals));
2302     Fn->setMetadata("kernel_arg_access_qual",
2303                     llvm::MDNode::get(VMContext, accessQuals));
2304     Fn->setMetadata("kernel_arg_type",
2305                     llvm::MDNode::get(VMContext, argTypeNames));
2306     Fn->setMetadata("kernel_arg_base_type",
2307                     llvm::MDNode::get(VMContext, argBaseTypeNames));
2308     Fn->setMetadata("kernel_arg_type_qual",
2309                     llvm::MDNode::get(VMContext, argTypeQuals));
2310   }
2311   if (getCodeGenOpts().EmitOpenCLArgMetadata ||
2312       getCodeGenOpts().HIPSaveKernelArgName)
2313     Fn->setMetadata("kernel_arg_name",
2314                     llvm::MDNode::get(VMContext, argNames));
2315 }
2316 
2317 /// Determines whether the language options require us to model
2318 /// unwind exceptions.  We treat -fexceptions as mandating this
2319 /// except under the fragile ObjC ABI with only ObjC exceptions
2320 /// enabled.  This means, for example, that C with -fexceptions
2321 /// enables this.
2322 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
2323   // If exceptions are completely disabled, obviously this is false.
2324   if (!LangOpts.Exceptions) return false;
2325 
2326   // If C++ exceptions are enabled, this is true.
2327   if (LangOpts.CXXExceptions) return true;
2328 
2329   // If ObjC exceptions are enabled, this depends on the ABI.
2330   if (LangOpts.ObjCExceptions) {
2331     return LangOpts.ObjCRuntime.hasUnwindExceptions();
2332   }
2333 
2334   return true;
2335 }
2336 
2337 static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
2338                                                       const CXXMethodDecl *MD) {
2339   // Check that the type metadata can ever actually be used by a call.
2340   if (!CGM.getCodeGenOpts().LTOUnit ||
2341       !CGM.HasHiddenLTOVisibility(MD->getParent()))
2342     return false;
2343 
2344   // Only functions whose address can be taken with a member function pointer
2345   // need this sort of type metadata.
2346   return MD->isImplicitObjectMemberFunction() && !MD->isVirtual() &&
2347          !isa<CXXConstructorDecl, CXXDestructorDecl>(MD);
2348 }
2349 
2350 SmallVector<const CXXRecordDecl *, 0>
2351 CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
2352   llvm::SetVector<const CXXRecordDecl *> MostBases;
2353 
2354   std::function<void (const CXXRecordDecl *)> CollectMostBases;
2355   CollectMostBases = [&](const CXXRecordDecl *RD) {
2356     if (RD->getNumBases() == 0)
2357       MostBases.insert(RD);
2358     for (const CXXBaseSpecifier &B : RD->bases())
2359       CollectMostBases(B.getType()->getAsCXXRecordDecl());
2360   };
2361   CollectMostBases(RD);
2362   return MostBases.takeVector();
2363 }
2364 
2365 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
2366                                                            llvm::Function *F) {
2367   llvm::AttrBuilder B(F->getContext());
2368 
2369   if ((!D || !D->hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables)
2370     B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
2371 
2372   if (CodeGenOpts.StackClashProtector)
2373     B.addAttribute("probe-stack", "inline-asm");
2374 
2375   if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
2376     B.addAttribute("stack-probe-size",
2377                    std::to_string(CodeGenOpts.StackProbeSize));
2378 
2379   if (!hasUnwindExceptions(LangOpts))
2380     B.addAttribute(llvm::Attribute::NoUnwind);
2381 
2382   if (D && D->hasAttr<NoStackProtectorAttr>())
2383     ; // Do nothing.
2384   else if (D && D->hasAttr<StrictGuardStackCheckAttr>() &&
2385            isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPOn))
2386     B.addAttribute(llvm::Attribute::StackProtectStrong);
2387   else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPOn))
2388     B.addAttribute(llvm::Attribute::StackProtect);
2389   else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPStrong))
2390     B.addAttribute(llvm::Attribute::StackProtectStrong);
2391   else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPReq))
2392     B.addAttribute(llvm::Attribute::StackProtectReq);
2393 
2394   if (!D) {
2395     // If we don't have a declaration to control inlining, the function isn't
2396     // explicitly marked as alwaysinline for semantic reasons, and inlining is
2397     // disabled, mark the function as noinline.
2398     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
2399         CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
2400       B.addAttribute(llvm::Attribute::NoInline);
2401 
2402     F->addFnAttrs(B);
2403     return;
2404   }
2405 
2406   // Handle SME attributes that apply to function definitions,
2407   // rather than to function prototypes.
2408   if (D->hasAttr<ArmLocallyStreamingAttr>())
2409     B.addAttribute("aarch64_pstate_sm_body");
2410 
2411   if (auto *Attr = D->getAttr<ArmNewAttr>()) {
2412     if (Attr->isNewZA())
2413       B.addAttribute("aarch64_pstate_za_new");
2414   }
2415 
2416   // Track whether we need to add the optnone LLVM attribute,
2417   // starting with the default for this optimization level.
2418   bool ShouldAddOptNone =
2419       !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
2420   // We can't add optnone in the following cases, it won't pass the verifier.
2421   ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
2422   ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
2423 
2424   // Add optnone, but do so only if the function isn't always_inline.
2425   if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) &&
2426       !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2427     B.addAttribute(llvm::Attribute::OptimizeNone);
2428 
2429     // OptimizeNone implies noinline; we should not be inlining such functions.
2430     B.addAttribute(llvm::Attribute::NoInline);
2431 
2432     // We still need to handle naked functions even though optnone subsumes
2433     // much of their semantics.
2434     if (D->hasAttr<NakedAttr>())
2435       B.addAttribute(llvm::Attribute::Naked);
2436 
2437     // OptimizeNone wins over OptimizeForSize and MinSize.
2438     F->removeFnAttr(llvm::Attribute::OptimizeForSize);
2439     F->removeFnAttr(llvm::Attribute::MinSize);
2440   } else if (D->hasAttr<NakedAttr>()) {
2441     // Naked implies noinline: we should not be inlining such functions.
2442     B.addAttribute(llvm::Attribute::Naked);
2443     B.addAttribute(llvm::Attribute::NoInline);
2444   } else if (D->hasAttr<NoDuplicateAttr>()) {
2445     B.addAttribute(llvm::Attribute::NoDuplicate);
2446   } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2447     // Add noinline if the function isn't always_inline.
2448     B.addAttribute(llvm::Attribute::NoInline);
2449   } else if (D->hasAttr<AlwaysInlineAttr>() &&
2450              !F->hasFnAttribute(llvm::Attribute::NoInline)) {
2451     // (noinline wins over always_inline, and we can't specify both in IR)
2452     B.addAttribute(llvm::Attribute::AlwaysInline);
2453   } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
2454     // If we're not inlining, then force everything that isn't always_inline to
2455     // carry an explicit noinline attribute.
2456     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
2457       B.addAttribute(llvm::Attribute::NoInline);
2458   } else {
2459     // Otherwise, propagate the inline hint attribute and potentially use its
2460     // absence to mark things as noinline.
2461     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
2462       // Search function and template pattern redeclarations for inline.
2463       auto CheckForInline = [](const FunctionDecl *FD) {
2464         auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
2465           return Redecl->isInlineSpecified();
2466         };
2467         if (any_of(FD->redecls(), CheckRedeclForInline))
2468           return true;
2469         const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
2470         if (!Pattern)
2471           return false;
2472         return any_of(Pattern->redecls(), CheckRedeclForInline);
2473       };
2474       if (CheckForInline(FD)) {
2475         B.addAttribute(llvm::Attribute::InlineHint);
2476       } else if (CodeGenOpts.getInlining() ==
2477                      CodeGenOptions::OnlyHintInlining &&
2478                  !FD->isInlined() &&
2479                  !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2480         B.addAttribute(llvm::Attribute::NoInline);
2481       }
2482     }
2483   }
2484 
2485   // Add other optimization related attributes if we are optimizing this
2486   // function.
2487   if (!D->hasAttr<OptimizeNoneAttr>()) {
2488     if (D->hasAttr<ColdAttr>()) {
2489       if (!ShouldAddOptNone)
2490         B.addAttribute(llvm::Attribute::OptimizeForSize);
2491       B.addAttribute(llvm::Attribute::Cold);
2492     }
2493     if (D->hasAttr<HotAttr>())
2494       B.addAttribute(llvm::Attribute::Hot);
2495     if (D->hasAttr<MinSizeAttr>())
2496       B.addAttribute(llvm::Attribute::MinSize);
2497   }
2498 
2499   F->addFnAttrs(B);
2500 
2501   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
2502   if (alignment)
2503     F->setAlignment(llvm::Align(alignment));
2504 
2505   if (!D->hasAttr<AlignedAttr>())
2506     if (LangOpts.FunctionAlignment)
2507       F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
2508 
2509   // Some C++ ABIs require 2-byte alignment for member functions, in order to
2510   // reserve a bit for differentiating between virtual and non-virtual member
2511   // functions. If the current target's C++ ABI requires this and this is a
2512   // member function, set its alignment accordingly.
2513   if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
2514     if (isa<CXXMethodDecl>(D) && F->getPointerAlignment(getDataLayout()) < 2)
2515       F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
2516   }
2517 
2518   // In the cross-dso CFI mode with canonical jump tables, we want !type
2519   // attributes on definitions only.
2520   if (CodeGenOpts.SanitizeCfiCrossDso &&
2521       CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
2522     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
2523       // Skip available_externally functions. They won't be codegen'ed in the
2524       // current module anyway.
2525       if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally)
2526         CreateFunctionTypeMetadataForIcall(FD, F);
2527     }
2528   }
2529 
2530   // Emit type metadata on member functions for member function pointer checks.
2531   // These are only ever necessary on definitions; we're guaranteed that the
2532   // definition will be present in the LTO unit as a result of LTO visibility.
2533   auto *MD = dyn_cast<CXXMethodDecl>(D);
2534   if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
2535     for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
2536       llvm::Metadata *Id =
2537           CreateMetadataIdentifierForType(Context.getMemberPointerType(
2538               MD->getType(), Context.getRecordType(Base).getTypePtr()));
2539       F->addTypeMetadata(0, Id);
2540     }
2541   }
2542 }
2543 
2544 void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
2545   const Decl *D = GD.getDecl();
2546   if (isa_and_nonnull<NamedDecl>(D))
2547     setGVProperties(GV, GD);
2548   else
2549     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
2550 
2551   if (D && D->hasAttr<UsedAttr>())
2552     addUsedOrCompilerUsedGlobal(GV);
2553 
2554   if (const auto *VD = dyn_cast_if_present<VarDecl>(D);
2555       VD &&
2556       ((CodeGenOpts.KeepPersistentStorageVariables &&
2557         (VD->getStorageDuration() == SD_Static ||
2558          VD->getStorageDuration() == SD_Thread)) ||
2559        (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static &&
2560         VD->getType().isConstQualified())))
2561     addUsedOrCompilerUsedGlobal(GV);
2562 }
2563 
2564 bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
2565                                                 llvm::AttrBuilder &Attrs,
2566                                                 bool SetTargetFeatures) {
2567   // Add target-cpu and target-features attributes to functions. If
2568   // we have a decl for the function and it has a target attribute then
2569   // parse that and add it to the feature set.
2570   StringRef TargetCPU = getTarget().getTargetOpts().CPU;
2571   StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU;
2572   std::vector<std::string> Features;
2573   const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
2574   FD = FD ? FD->getMostRecentDecl() : FD;
2575   const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
2576   const auto *TV = FD ? FD->getAttr<TargetVersionAttr>() : nullptr;
2577   assert((!TD || !TV) && "both target_version and target specified");
2578   const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
2579   const auto *TC = FD ? FD->getAttr<TargetClonesAttr>() : nullptr;
2580   bool AddedAttr = false;
2581   if (TD || TV || SD || TC) {
2582     llvm::StringMap<bool> FeatureMap;
2583     getContext().getFunctionFeatureMap(FeatureMap, GD);
2584 
2585     // Produce the canonical string for this set of features.
2586     for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
2587       Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
2588 
2589     // Now add the target-cpu and target-features to the function.
2590     // While we populated the feature map above, we still need to
2591     // get and parse the target attribute so we can get the cpu for
2592     // the function.
2593     if (TD) {
2594       ParsedTargetAttr ParsedAttr =
2595           Target.parseTargetAttr(TD->getFeaturesStr());
2596       if (!ParsedAttr.CPU.empty() &&
2597           getTarget().isValidCPUName(ParsedAttr.CPU)) {
2598         TargetCPU = ParsedAttr.CPU;
2599         TuneCPU = ""; // Clear the tune CPU.
2600       }
2601       if (!ParsedAttr.Tune.empty() &&
2602           getTarget().isValidCPUName(ParsedAttr.Tune))
2603         TuneCPU = ParsedAttr.Tune;
2604     }
2605 
2606     if (SD) {
2607       // Apply the given CPU name as the 'tune-cpu' so that the optimizer can
2608       // favor this processor.
2609       TuneCPU = SD->getCPUName(GD.getMultiVersionIndex())->getName();
2610     }
2611   } else {
2612     // Otherwise just add the existing target cpu and target features to the
2613     // function.
2614     Features = getTarget().getTargetOpts().Features;
2615   }
2616 
2617   if (!TargetCPU.empty()) {
2618     Attrs.addAttribute("target-cpu", TargetCPU);
2619     AddedAttr = true;
2620   }
2621   if (!TuneCPU.empty()) {
2622     Attrs.addAttribute("tune-cpu", TuneCPU);
2623     AddedAttr = true;
2624   }
2625   if (!Features.empty() && SetTargetFeatures) {
2626     llvm::erase_if(Features, [&](const std::string& F) {
2627        return getTarget().isReadOnlyFeature(F.substr(1));
2628     });
2629     llvm::sort(Features);
2630     Attrs.addAttribute("target-features", llvm::join(Features, ","));
2631     AddedAttr = true;
2632   }
2633 
2634   return AddedAttr;
2635 }
2636 
2637 void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
2638                                           llvm::GlobalObject *GO) {
2639   const Decl *D = GD.getDecl();
2640   SetCommonAttributes(GD, GO);
2641 
2642   if (D) {
2643     if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
2644       if (D->hasAttr<RetainAttr>())
2645         addUsedGlobal(GV);
2646       if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
2647         GV->addAttribute("bss-section", SA->getName());
2648       if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
2649         GV->addAttribute("data-section", SA->getName());
2650       if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
2651         GV->addAttribute("rodata-section", SA->getName());
2652       if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>())
2653         GV->addAttribute("relro-section", SA->getName());
2654     }
2655 
2656     if (auto *F = dyn_cast<llvm::Function>(GO)) {
2657       if (D->hasAttr<RetainAttr>())
2658         addUsedGlobal(F);
2659       if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
2660         if (!D->getAttr<SectionAttr>())
2661           F->addFnAttr("implicit-section-name", SA->getName());
2662 
2663       llvm::AttrBuilder Attrs(F->getContext());
2664       if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
2665         // We know that GetCPUAndFeaturesAttributes will always have the
2666         // newest set, since it has the newest possible FunctionDecl, so the
2667         // new ones should replace the old.
2668         llvm::AttributeMask RemoveAttrs;
2669         RemoveAttrs.addAttribute("target-cpu");
2670         RemoveAttrs.addAttribute("target-features");
2671         RemoveAttrs.addAttribute("tune-cpu");
2672         F->removeFnAttrs(RemoveAttrs);
2673         F->addFnAttrs(Attrs);
2674       }
2675     }
2676 
2677     if (const auto *CSA = D->getAttr<CodeSegAttr>())
2678       GO->setSection(CSA->getName());
2679     else if (const auto *SA = D->getAttr<SectionAttr>())
2680       GO->setSection(SA->getName());
2681   }
2682 
2683   getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
2684 }
2685 
2686 void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
2687                                                   llvm::Function *F,
2688                                                   const CGFunctionInfo &FI) {
2689   const Decl *D = GD.getDecl();
2690   SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false);
2691   SetLLVMFunctionAttributesForDefinition(D, F);
2692 
2693   F->setLinkage(llvm::Function::InternalLinkage);
2694 
2695   setNonAliasAttributes(GD, F);
2696 }
2697 
2698 static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
2699   // Set linkage and visibility in case we never see a definition.
2700   LinkageInfo LV = ND->getLinkageAndVisibility();
2701   // Don't set internal linkage on declarations.
2702   // "extern_weak" is overloaded in LLVM; we probably should have
2703   // separate linkage types for this.
2704   if (isExternallyVisible(LV.getLinkage()) &&
2705       (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
2706     GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2707 }
2708 
2709 void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
2710                                                        llvm::Function *F) {
2711   // Only if we are checking indirect calls.
2712   if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
2713     return;
2714 
2715   // Non-static class methods are handled via vtable or member function pointer
2716   // checks elsewhere.
2717   if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2718     return;
2719 
2720   llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
2721   F->addTypeMetadata(0, MD);
2722   F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
2723 
2724   // Emit a hash-based bit set entry for cross-DSO calls.
2725   if (CodeGenOpts.SanitizeCfiCrossDso)
2726     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
2727       F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
2728 }
2729 
2730 void CodeGenModule::setKCFIType(const FunctionDecl *FD, llvm::Function *F) {
2731   llvm::LLVMContext &Ctx = F->getContext();
2732   llvm::MDBuilder MDB(Ctx);
2733   F->setMetadata(llvm::LLVMContext::MD_kcfi_type,
2734                  llvm::MDNode::get(
2735                      Ctx, MDB.createConstant(CreateKCFITypeId(FD->getType()))));
2736 }
2737 
2738 static bool allowKCFIIdentifier(StringRef Name) {
2739   // KCFI type identifier constants are only necessary for external assembly
2740   // functions, which means it's safe to skip unusual names. Subset of
2741   // MCAsmInfo::isAcceptableChar() and MCAsmInfoXCOFF::isAcceptableChar().
2742   return llvm::all_of(Name, [](const char &C) {
2743     return llvm::isAlnum(C) || C == '_' || C == '.';
2744   });
2745 }
2746 
2747 void CodeGenModule::finalizeKCFITypes() {
2748   llvm::Module &M = getModule();
2749   for (auto &F : M.functions()) {
2750     // Remove KCFI type metadata from non-address-taken local functions.
2751     bool AddressTaken = F.hasAddressTaken();
2752     if (!AddressTaken && F.hasLocalLinkage())
2753       F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type);
2754 
2755     // Generate a constant with the expected KCFI type identifier for all
2756     // address-taken function declarations to support annotating indirectly
2757     // called assembly functions.
2758     if (!AddressTaken || !F.isDeclaration())
2759       continue;
2760 
2761     const llvm::ConstantInt *Type;
2762     if (const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type))
2763       Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0));
2764     else
2765       continue;
2766 
2767     StringRef Name = F.getName();
2768     if (!allowKCFIIdentifier(Name))
2769       continue;
2770 
2771     std::string Asm = (".weak __kcfi_typeid_" + Name + "\n.set __kcfi_typeid_" +
2772                        Name + ", " + Twine(Type->getZExtValue()) + "\n")
2773                           .str();
2774     M.appendModuleInlineAsm(Asm);
2775   }
2776 }
2777 
2778 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
2779                                           bool IsIncompleteFunction,
2780                                           bool IsThunk) {
2781 
2782   if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
2783     // If this is an intrinsic function, set the function's attributes
2784     // to the intrinsic's attributes.
2785     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
2786     return;
2787   }
2788 
2789   const auto *FD = cast<FunctionDecl>(GD.getDecl());
2790 
2791   if (!IsIncompleteFunction)
2792     SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F,
2793                               IsThunk);
2794 
2795   // Add the Returned attribute for "this", except for iOS 5 and earlier
2796   // where substantial code, including the libstdc++ dylib, was compiled with
2797   // GCC and does not actually return "this".
2798   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
2799       !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
2800     assert(!F->arg_empty() &&
2801            F->arg_begin()->getType()
2802              ->canLosslesslyBitCastTo(F->getReturnType()) &&
2803            "unexpected this return");
2804     F->addParamAttr(0, llvm::Attribute::Returned);
2805   }
2806 
2807   // Only a few attributes are set on declarations; these may later be
2808   // overridden by a definition.
2809 
2810   setLinkageForGV(F, FD);
2811   setGVProperties(F, FD);
2812 
2813   // Setup target-specific attributes.
2814   if (!IsIncompleteFunction && F->isDeclaration())
2815     getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
2816 
2817   if (const auto *CSA = FD->getAttr<CodeSegAttr>())
2818     F->setSection(CSA->getName());
2819   else if (const auto *SA = FD->getAttr<SectionAttr>())
2820      F->setSection(SA->getName());
2821 
2822   if (const auto *EA = FD->getAttr<ErrorAttr>()) {
2823     if (EA->isError())
2824       F->addFnAttr("dontcall-error", EA->getUserDiagnostic());
2825     else if (EA->isWarning())
2826       F->addFnAttr("dontcall-warn", EA->getUserDiagnostic());
2827   }
2828 
2829   // If we plan on emitting this inline builtin, we can't treat it as a builtin.
2830   if (FD->isInlineBuiltinDeclaration()) {
2831     const FunctionDecl *FDBody;
2832     bool HasBody = FD->hasBody(FDBody);
2833     (void)HasBody;
2834     assert(HasBody && "Inline builtin declarations should always have an "
2835                       "available body!");
2836     if (shouldEmitFunction(FDBody))
2837       F->addFnAttr(llvm::Attribute::NoBuiltin);
2838   }
2839 
2840   if (FD->isReplaceableGlobalAllocationFunction()) {
2841     // A replaceable global allocation function does not act like a builtin by
2842     // default, only if it is invoked by a new-expression or delete-expression.
2843     F->addFnAttr(llvm::Attribute::NoBuiltin);
2844   }
2845 
2846   if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
2847     F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2848   else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
2849     if (MD->isVirtual())
2850       F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2851 
2852   // Don't emit entries for function declarations in the cross-DSO mode. This
2853   // is handled with better precision by the receiving DSO. But if jump tables
2854   // are non-canonical then we need type metadata in order to produce the local
2855   // jump table.
2856   if (!CodeGenOpts.SanitizeCfiCrossDso ||
2857       !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
2858     CreateFunctionTypeMetadataForIcall(FD, F);
2859 
2860   if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
2861     setKCFIType(FD, F);
2862 
2863   if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
2864     getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
2865 
2866   if (CodeGenOpts.InlineMaxStackSize != UINT_MAX)
2867     F->addFnAttr("inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize));
2868 
2869   if (const auto *CB = FD->getAttr<CallbackAttr>()) {
2870     // Annotate the callback behavior as metadata:
2871     //  - The callback callee (as argument number).
2872     //  - The callback payloads (as argument numbers).
2873     llvm::LLVMContext &Ctx = F->getContext();
2874     llvm::MDBuilder MDB(Ctx);
2875 
2876     // The payload indices are all but the first one in the encoding. The first
2877     // identifies the callback callee.
2878     int CalleeIdx = *CB->encoding_begin();
2879     ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
2880     F->addMetadata(llvm::LLVMContext::MD_callback,
2881                    *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
2882                                                CalleeIdx, PayloadIndices,
2883                                                /* VarArgsArePassed */ false)}));
2884   }
2885 }
2886 
2887 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
2888   assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
2889          "Only globals with definition can force usage.");
2890   LLVMUsed.emplace_back(GV);
2891 }
2892 
2893 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
2894   assert(!GV->isDeclaration() &&
2895          "Only globals with definition can force usage.");
2896   LLVMCompilerUsed.emplace_back(GV);
2897 }
2898 
2899 void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) {
2900   assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
2901          "Only globals with definition can force usage.");
2902   if (getTriple().isOSBinFormatELF())
2903     LLVMCompilerUsed.emplace_back(GV);
2904   else
2905     LLVMUsed.emplace_back(GV);
2906 }
2907 
2908 static void emitUsed(CodeGenModule &CGM, StringRef Name,
2909                      std::vector<llvm::WeakTrackingVH> &List) {
2910   // Don't create llvm.used if there is no need.
2911   if (List.empty())
2912     return;
2913 
2914   // Convert List to what ConstantArray needs.
2915   SmallVector<llvm::Constant*, 8> UsedArray;
2916   UsedArray.resize(List.size());
2917   for (unsigned i = 0, e = List.size(); i != e; ++i) {
2918     UsedArray[i] =
2919         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
2920             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
2921   }
2922 
2923   if (UsedArray.empty())
2924     return;
2925   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
2926 
2927   auto *GV = new llvm::GlobalVariable(
2928       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
2929       llvm::ConstantArray::get(ATy, UsedArray), Name);
2930 
2931   GV->setSection("llvm.metadata");
2932 }
2933 
2934 void CodeGenModule::emitLLVMUsed() {
2935   emitUsed(*this, "llvm.used", LLVMUsed);
2936   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
2937 }
2938 
2939 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
2940   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
2941   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
2942 }
2943 
2944 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
2945   llvm::SmallString<32> Opt;
2946   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
2947   if (Opt.empty())
2948     return;
2949   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
2950   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
2951 }
2952 
2953 void CodeGenModule::AddDependentLib(StringRef Lib) {
2954   auto &C = getLLVMContext();
2955   if (getTarget().getTriple().isOSBinFormatELF()) {
2956       ELFDependentLibraries.push_back(
2957         llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
2958     return;
2959   }
2960 
2961   llvm::SmallString<24> Opt;
2962   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
2963   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
2964   LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
2965 }
2966 
2967 /// Add link options implied by the given module, including modules
2968 /// it depends on, using a postorder walk.
2969 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
2970                                     SmallVectorImpl<llvm::MDNode *> &Metadata,
2971                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
2972   // Import this module's parent.
2973   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
2974     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
2975   }
2976 
2977   // Import this module's dependencies.
2978   for (Module *Import : llvm::reverse(Mod->Imports)) {
2979     if (Visited.insert(Import).second)
2980       addLinkOptionsPostorder(CGM, Import, Metadata, Visited);
2981   }
2982 
2983   // Add linker options to link against the libraries/frameworks
2984   // described by this module.
2985   llvm::LLVMContext &Context = CGM.getLLVMContext();
2986   bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
2987 
2988   // For modules that use export_as for linking, use that module
2989   // name instead.
2990   if (Mod->UseExportAsModuleLinkName)
2991     return;
2992 
2993   for (const Module::LinkLibrary &LL : llvm::reverse(Mod->LinkLibraries)) {
2994     // Link against a framework.  Frameworks are currently Darwin only, so we
2995     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
2996     if (LL.IsFramework) {
2997       llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
2998                                  llvm::MDString::get(Context, LL.Library)};
2999 
3000       Metadata.push_back(llvm::MDNode::get(Context, Args));
3001       continue;
3002     }
3003 
3004     // Link against a library.
3005     if (IsELF) {
3006       llvm::Metadata *Args[2] = {
3007           llvm::MDString::get(Context, "lib"),
3008           llvm::MDString::get(Context, LL.Library),
3009       };
3010       Metadata.push_back(llvm::MDNode::get(Context, Args));
3011     } else {
3012       llvm::SmallString<24> Opt;
3013       CGM.getTargetCodeGenInfo().getDependentLibraryOption(LL.Library, Opt);
3014       auto *OptString = llvm::MDString::get(Context, Opt);
3015       Metadata.push_back(llvm::MDNode::get(Context, OptString));
3016     }
3017   }
3018 }
3019 
3020 void CodeGenModule::EmitModuleInitializers(clang::Module *Primary) {
3021   assert(Primary->isNamedModuleUnit() &&
3022          "We should only emit module initializers for named modules.");
3023 
3024   // Emit the initializers in the order that sub-modules appear in the
3025   // source, first Global Module Fragments, if present.
3026   if (auto GMF = Primary->getGlobalModuleFragment()) {
3027     for (Decl *D : getContext().getModuleInitializers(GMF)) {
3028       if (isa<ImportDecl>(D))
3029         continue;
3030       assert(isa<VarDecl>(D) && "GMF initializer decl is not a var?");
3031       EmitTopLevelDecl(D);
3032     }
3033   }
3034   // Second any associated with the module, itself.
3035   for (Decl *D : getContext().getModuleInitializers(Primary)) {
3036     // Skip import decls, the inits for those are called explicitly.
3037     if (isa<ImportDecl>(D))
3038       continue;
3039     EmitTopLevelDecl(D);
3040   }
3041   // Third any associated with the Privat eMOdule Fragment, if present.
3042   if (auto PMF = Primary->getPrivateModuleFragment()) {
3043     for (Decl *D : getContext().getModuleInitializers(PMF)) {
3044       // Skip import decls, the inits for those are called explicitly.
3045       if (isa<ImportDecl>(D))
3046         continue;
3047       assert(isa<VarDecl>(D) && "PMF initializer decl is not a var?");
3048       EmitTopLevelDecl(D);
3049     }
3050   }
3051 }
3052 
3053 void CodeGenModule::EmitModuleLinkOptions() {
3054   // Collect the set of all of the modules we want to visit to emit link
3055   // options, which is essentially the imported modules and all of their
3056   // non-explicit child modules.
3057   llvm::SetVector<clang::Module *> LinkModules;
3058   llvm::SmallPtrSet<clang::Module *, 16> Visited;
3059   SmallVector<clang::Module *, 16> Stack;
3060 
3061   // Seed the stack with imported modules.
3062   for (Module *M : ImportedModules) {
3063     // Do not add any link flags when an implementation TU of a module imports
3064     // a header of that same module.
3065     if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
3066         !getLangOpts().isCompilingModule())
3067       continue;
3068     if (Visited.insert(M).second)
3069       Stack.push_back(M);
3070   }
3071 
3072   // Find all of the modules to import, making a little effort to prune
3073   // non-leaf modules.
3074   while (!Stack.empty()) {
3075     clang::Module *Mod = Stack.pop_back_val();
3076 
3077     bool AnyChildren = false;
3078 
3079     // Visit the submodules of this module.
3080     for (const auto &SM : Mod->submodules()) {
3081       // Skip explicit children; they need to be explicitly imported to be
3082       // linked against.
3083       if (SM->IsExplicit)
3084         continue;
3085 
3086       if (Visited.insert(SM).second) {
3087         Stack.push_back(SM);
3088         AnyChildren = true;
3089       }
3090     }
3091 
3092     // We didn't find any children, so add this module to the list of
3093     // modules to link against.
3094     if (!AnyChildren) {
3095       LinkModules.insert(Mod);
3096     }
3097   }
3098 
3099   // Add link options for all of the imported modules in reverse topological
3100   // order.  We don't do anything to try to order import link flags with respect
3101   // to linker options inserted by things like #pragma comment().
3102   SmallVector<llvm::MDNode *, 16> MetadataArgs;
3103   Visited.clear();
3104   for (Module *M : LinkModules)
3105     if (Visited.insert(M).second)
3106       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
3107   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
3108   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
3109 
3110   // Add the linker options metadata flag.
3111   auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
3112   for (auto *MD : LinkerOptionsMetadata)
3113     NMD->addOperand(MD);
3114 }
3115 
3116 void CodeGenModule::EmitDeferred() {
3117   // Emit deferred declare target declarations.
3118   if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
3119     getOpenMPRuntime().emitDeferredTargetDecls();
3120 
3121   // Emit code for any potentially referenced deferred decls.  Since a
3122   // previously unused static decl may become used during the generation of code
3123   // for a static function, iterate until no changes are made.
3124 
3125   if (!DeferredVTables.empty()) {
3126     EmitDeferredVTables();
3127 
3128     // Emitting a vtable doesn't directly cause more vtables to
3129     // become deferred, although it can cause functions to be
3130     // emitted that then need those vtables.
3131     assert(DeferredVTables.empty());
3132   }
3133 
3134   // Emit CUDA/HIP static device variables referenced by host code only.
3135   // Note we should not clear CUDADeviceVarODRUsedByHost since it is still
3136   // needed for further handling.
3137   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
3138     llvm::append_range(DeferredDeclsToEmit,
3139                        getContext().CUDADeviceVarODRUsedByHost);
3140 
3141   // Stop if we're out of both deferred vtables and deferred declarations.
3142   if (DeferredDeclsToEmit.empty())
3143     return;
3144 
3145   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
3146   // work, it will not interfere with this.
3147   std::vector<GlobalDecl> CurDeclsToEmit;
3148   CurDeclsToEmit.swap(DeferredDeclsToEmit);
3149 
3150   for (GlobalDecl &D : CurDeclsToEmit) {
3151     // We should call GetAddrOfGlobal with IsForDefinition set to true in order
3152     // to get GlobalValue with exactly the type we need, not something that
3153     // might had been created for another decl with the same mangled name but
3154     // different type.
3155     llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
3156         GetAddrOfGlobal(D, ForDefinition));
3157 
3158     // In case of different address spaces, we may still get a cast, even with
3159     // IsForDefinition equal to true. Query mangled names table to get
3160     // GlobalValue.
3161     if (!GV)
3162       GV = GetGlobalValue(getMangledName(D));
3163 
3164     // Make sure GetGlobalValue returned non-null.
3165     assert(GV);
3166 
3167     // Check to see if we've already emitted this.  This is necessary
3168     // for a couple of reasons: first, decls can end up in the
3169     // deferred-decls queue multiple times, and second, decls can end
3170     // up with definitions in unusual ways (e.g. by an extern inline
3171     // function acquiring a strong function redefinition).  Just
3172     // ignore these cases.
3173     if (!GV->isDeclaration())
3174       continue;
3175 
3176     // If this is OpenMP, check if it is legal to emit this global normally.
3177     if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
3178       continue;
3179 
3180     // Otherwise, emit the definition and move on to the next one.
3181     EmitGlobalDefinition(D, GV);
3182 
3183     // If we found out that we need to emit more decls, do that recursively.
3184     // This has the advantage that the decls are emitted in a DFS and related
3185     // ones are close together, which is convenient for testing.
3186     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
3187       EmitDeferred();
3188       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
3189     }
3190   }
3191 }
3192 
3193 void CodeGenModule::EmitVTablesOpportunistically() {
3194   // Try to emit external vtables as available_externally if they have emitted
3195   // all inlined virtual functions.  It runs after EmitDeferred() and therefore
3196   // is not allowed to create new references to things that need to be emitted
3197   // lazily. Note that it also uses fact that we eagerly emitting RTTI.
3198 
3199   assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
3200          && "Only emit opportunistic vtables with optimizations");
3201 
3202   for (const CXXRecordDecl *RD : OpportunisticVTables) {
3203     assert(getVTables().isVTableExternal(RD) &&
3204            "This queue should only contain external vtables");
3205     if (getCXXABI().canSpeculativelyEmitVTable(RD))
3206       VTables.GenerateClassData(RD);
3207   }
3208   OpportunisticVTables.clear();
3209 }
3210 
3211 void CodeGenModule::EmitGlobalAnnotations() {
3212   for (const auto& [MangledName, VD] : DeferredAnnotations) {
3213     llvm::GlobalValue *GV = GetGlobalValue(MangledName);
3214     if (GV)
3215       AddGlobalAnnotations(VD, GV);
3216   }
3217   DeferredAnnotations.clear();
3218 
3219   if (Annotations.empty())
3220     return;
3221 
3222   // Create a new global variable for the ConstantStruct in the Module.
3223   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
3224     Annotations[0]->getType(), Annotations.size()), Annotations);
3225   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
3226                                       llvm::GlobalValue::AppendingLinkage,
3227                                       Array, "llvm.global.annotations");
3228   gv->setSection(AnnotationSection);
3229 }
3230 
3231 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
3232   llvm::Constant *&AStr = AnnotationStrings[Str];
3233   if (AStr)
3234     return AStr;
3235 
3236   // Not found yet, create a new global.
3237   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
3238   auto *gv = new llvm::GlobalVariable(
3239       getModule(), s->getType(), true, llvm::GlobalValue::PrivateLinkage, s,
3240       ".str", nullptr, llvm::GlobalValue::NotThreadLocal,
3241       ConstGlobalsPtrTy->getAddressSpace());
3242   gv->setSection(AnnotationSection);
3243   gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3244   AStr = gv;
3245   return gv;
3246 }
3247 
3248 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
3249   SourceManager &SM = getContext().getSourceManager();
3250   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
3251   if (PLoc.isValid())
3252     return EmitAnnotationString(PLoc.getFilename());
3253   return EmitAnnotationString(SM.getBufferName(Loc));
3254 }
3255 
3256 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
3257   SourceManager &SM = getContext().getSourceManager();
3258   PresumedLoc PLoc = SM.getPresumedLoc(L);
3259   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
3260     SM.getExpansionLineNumber(L);
3261   return llvm::ConstantInt::get(Int32Ty, LineNo);
3262 }
3263 
3264 llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) {
3265   ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()};
3266   if (Exprs.empty())
3267     return llvm::ConstantPointerNull::get(ConstGlobalsPtrTy);
3268 
3269   llvm::FoldingSetNodeID ID;
3270   for (Expr *E : Exprs) {
3271     ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult());
3272   }
3273   llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
3274   if (Lookup)
3275     return Lookup;
3276 
3277   llvm::SmallVector<llvm::Constant *, 4> LLVMArgs;
3278   LLVMArgs.reserve(Exprs.size());
3279   ConstantEmitter ConstEmiter(*this);
3280   llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) {
3281     const auto *CE = cast<clang::ConstantExpr>(E);
3282     return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
3283                                     CE->getType());
3284   });
3285   auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
3286   auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true,
3287                                       llvm::GlobalValue::PrivateLinkage, Struct,
3288                                       ".args");
3289   GV->setSection(AnnotationSection);
3290   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3291 
3292   Lookup = GV;
3293   return GV;
3294 }
3295 
3296 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
3297                                                 const AnnotateAttr *AA,
3298                                                 SourceLocation L) {
3299   // Get the globals for file name, annotation, and the line number.
3300   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
3301                  *UnitGV = EmitAnnotationUnit(L),
3302                  *LineNoCst = EmitAnnotationLineNo(L),
3303                  *Args = EmitAnnotationArgs(AA);
3304 
3305   llvm::Constant *GVInGlobalsAS = GV;
3306   if (GV->getAddressSpace() !=
3307       getDataLayout().getDefaultGlobalsAddressSpace()) {
3308     GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
3309         GV,
3310         llvm::PointerType::get(
3311             GV->getContext(), getDataLayout().getDefaultGlobalsAddressSpace()));
3312   }
3313 
3314   // Create the ConstantStruct for the global annotation.
3315   llvm::Constant *Fields[] = {
3316       GVInGlobalsAS, AnnoGV, UnitGV, LineNoCst, Args,
3317   };
3318   return llvm::ConstantStruct::getAnon(Fields);
3319 }
3320 
3321 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
3322                                          llvm::GlobalValue *GV) {
3323   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
3324   // Get the struct elements for these annotations.
3325   for (const auto *I : D->specific_attrs<AnnotateAttr>())
3326     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
3327 }
3328 
3329 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn,
3330                                        SourceLocation Loc) const {
3331   const auto &NoSanitizeL = getContext().getNoSanitizeList();
3332   // NoSanitize by function name.
3333   if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
3334     return true;
3335   // NoSanitize by location. Check "mainfile" prefix.
3336   auto &SM = Context.getSourceManager();
3337   FileEntryRef MainFile = *SM.getFileEntryRefForID(SM.getMainFileID());
3338   if (NoSanitizeL.containsMainFile(Kind, MainFile.getName()))
3339     return true;
3340 
3341   // Check "src" prefix.
3342   if (Loc.isValid())
3343     return NoSanitizeL.containsLocation(Kind, Loc);
3344   // If location is unknown, this may be a compiler-generated function. Assume
3345   // it's located in the main file.
3346   return NoSanitizeL.containsFile(Kind, MainFile.getName());
3347 }
3348 
3349 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind,
3350                                        llvm::GlobalVariable *GV,
3351                                        SourceLocation Loc, QualType Ty,
3352                                        StringRef Category) const {
3353   const auto &NoSanitizeL = getContext().getNoSanitizeList();
3354   if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category))
3355     return true;
3356   auto &SM = Context.getSourceManager();
3357   if (NoSanitizeL.containsMainFile(
3358           Kind, SM.getFileEntryRefForID(SM.getMainFileID())->getName(),
3359           Category))
3360     return true;
3361   if (NoSanitizeL.containsLocation(Kind, Loc, Category))
3362     return true;
3363 
3364   // Check global type.
3365   if (!Ty.isNull()) {
3366     // Drill down the array types: if global variable of a fixed type is
3367     // not sanitized, we also don't instrument arrays of them.
3368     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
3369       Ty = AT->getElementType();
3370     Ty = Ty.getCanonicalType().getUnqualifiedType();
3371     // Only record types (classes, structs etc.) are ignored.
3372     if (Ty->isRecordType()) {
3373       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
3374       if (NoSanitizeL.containsType(Kind, TypeStr, Category))
3375         return true;
3376     }
3377   }
3378   return false;
3379 }
3380 
3381 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
3382                                    StringRef Category) const {
3383   const auto &XRayFilter = getContext().getXRayFilter();
3384   using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
3385   auto Attr = ImbueAttr::NONE;
3386   if (Loc.isValid())
3387     Attr = XRayFilter.shouldImbueLocation(Loc, Category);
3388   if (Attr == ImbueAttr::NONE)
3389     Attr = XRayFilter.shouldImbueFunction(Fn->getName());
3390   switch (Attr) {
3391   case ImbueAttr::NONE:
3392     return false;
3393   case ImbueAttr::ALWAYS:
3394     Fn->addFnAttr("function-instrument", "xray-always");
3395     break;
3396   case ImbueAttr::ALWAYS_ARG1:
3397     Fn->addFnAttr("function-instrument", "xray-always");
3398     Fn->addFnAttr("xray-log-args", "1");
3399     break;
3400   case ImbueAttr::NEVER:
3401     Fn->addFnAttr("function-instrument", "xray-never");
3402     break;
3403   }
3404   return true;
3405 }
3406 
3407 ProfileList::ExclusionType
3408 CodeGenModule::isFunctionBlockedByProfileList(llvm::Function *Fn,
3409                                               SourceLocation Loc) const {
3410   const auto &ProfileList = getContext().getProfileList();
3411   // If the profile list is empty, then instrument everything.
3412   if (ProfileList.isEmpty())
3413     return ProfileList::Allow;
3414   CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr();
3415   // First, check the function name.
3416   if (auto V = ProfileList.isFunctionExcluded(Fn->getName(), Kind))
3417     return *V;
3418   // Next, check the source location.
3419   if (Loc.isValid())
3420     if (auto V = ProfileList.isLocationExcluded(Loc, Kind))
3421       return *V;
3422   // If location is unknown, this may be a compiler-generated function. Assume
3423   // it's located in the main file.
3424   auto &SM = Context.getSourceManager();
3425   if (auto MainFile = SM.getFileEntryRefForID(SM.getMainFileID()))
3426     if (auto V = ProfileList.isFileExcluded(MainFile->getName(), Kind))
3427       return *V;
3428   return ProfileList.getDefault(Kind);
3429 }
3430 
3431 ProfileList::ExclusionType
3432 CodeGenModule::isFunctionBlockedFromProfileInstr(llvm::Function *Fn,
3433                                                  SourceLocation Loc) const {
3434   auto V = isFunctionBlockedByProfileList(Fn, Loc);
3435   if (V != ProfileList::Allow)
3436     return V;
3437 
3438   auto NumGroups = getCodeGenOpts().ProfileTotalFunctionGroups;
3439   if (NumGroups > 1) {
3440     auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups;
3441     if (Group != getCodeGenOpts().ProfileSelectedFunctionGroup)
3442       return ProfileList::Skip;
3443   }
3444   return ProfileList::Allow;
3445 }
3446 
3447 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
3448   // Never defer when EmitAllDecls is specified.
3449   if (LangOpts.EmitAllDecls)
3450     return true;
3451 
3452   const auto *VD = dyn_cast<VarDecl>(Global);
3453   if (VD &&
3454       ((CodeGenOpts.KeepPersistentStorageVariables &&
3455         (VD->getStorageDuration() == SD_Static ||
3456          VD->getStorageDuration() == SD_Thread)) ||
3457        (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static &&
3458         VD->getType().isConstQualified())))
3459     return true;
3460 
3461   return getContext().DeclMustBeEmitted(Global);
3462 }
3463 
3464 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
3465   // In OpenMP 5.0 variables and function may be marked as
3466   // device_type(host/nohost) and we should not emit them eagerly unless we sure
3467   // that they must be emitted on the host/device. To be sure we need to have
3468   // seen a declare target with an explicit mentioning of the function, we know
3469   // we have if the level of the declare target attribute is -1. Note that we
3470   // check somewhere else if we should emit this at all.
3471   if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
3472     std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
3473         OMPDeclareTargetDeclAttr::getActiveAttr(Global);
3474     if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1)
3475       return false;
3476   }
3477 
3478   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
3479     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
3480       // Implicit template instantiations may change linkage if they are later
3481       // explicitly instantiated, so they should not be emitted eagerly.
3482       return false;
3483   }
3484   if (const auto *VD = dyn_cast<VarDecl>(Global)) {
3485     if (Context.getInlineVariableDefinitionKind(VD) ==
3486         ASTContext::InlineVariableDefinitionKind::WeakUnknown)
3487       // A definition of an inline constexpr static data member may change
3488       // linkage later if it's redeclared outside the class.
3489       return false;
3490     if (CXX20ModuleInits && VD->getOwningModule() &&
3491         !VD->getOwningModule()->isModuleMapModule()) {
3492       // For CXX20, module-owned initializers need to be deferred, since it is
3493       // not known at this point if they will be run for the current module or
3494       // as part of the initializer for an imported one.
3495       return false;
3496     }
3497   }
3498   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
3499   // codegen for global variables, because they may be marked as threadprivate.
3500   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
3501       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
3502       !Global->getType().isConstantStorage(getContext(), false, false) &&
3503       !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
3504     return false;
3505 
3506   return true;
3507 }
3508 
3509 ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) {
3510   StringRef Name = getMangledName(GD);
3511 
3512   // The UUID descriptor should be pointer aligned.
3513   CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
3514 
3515   // Look for an existing global.
3516   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
3517     return ConstantAddress(GV, GV->getValueType(), Alignment);
3518 
3519   ConstantEmitter Emitter(*this);
3520   llvm::Constant *Init;
3521 
3522   APValue &V = GD->getAsAPValue();
3523   if (!V.isAbsent()) {
3524     // If possible, emit the APValue version of the initializer. In particular,
3525     // this gets the type of the constant right.
3526     Init = Emitter.emitForInitializer(
3527         GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType());
3528   } else {
3529     // As a fallback, directly construct the constant.
3530     // FIXME: This may get padding wrong under esoteric struct layout rules.
3531     // MSVC appears to create a complete type 'struct __s_GUID' that it
3532     // presumably uses to represent these constants.
3533     MSGuidDecl::Parts Parts = GD->getParts();
3534     llvm::Constant *Fields[4] = {
3535         llvm::ConstantInt::get(Int32Ty, Parts.Part1),
3536         llvm::ConstantInt::get(Int16Ty, Parts.Part2),
3537         llvm::ConstantInt::get(Int16Ty, Parts.Part3),
3538         llvm::ConstantDataArray::getRaw(
3539             StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8,
3540             Int8Ty)};
3541     Init = llvm::ConstantStruct::getAnon(Fields);
3542   }
3543 
3544   auto *GV = new llvm::GlobalVariable(
3545       getModule(), Init->getType(),
3546       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
3547   if (supportsCOMDAT())
3548     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3549   setDSOLocal(GV);
3550 
3551   if (!V.isAbsent()) {
3552     Emitter.finalize(GV);
3553     return ConstantAddress(GV, GV->getValueType(), Alignment);
3554   }
3555 
3556   llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType());
3557   return ConstantAddress(GV, Ty, Alignment);
3558 }
3559 
3560 ConstantAddress CodeGenModule::GetAddrOfUnnamedGlobalConstantDecl(
3561     const UnnamedGlobalConstantDecl *GCD) {
3562   CharUnits Alignment = getContext().getTypeAlignInChars(GCD->getType());
3563 
3564   llvm::GlobalVariable **Entry = nullptr;
3565   Entry = &UnnamedGlobalConstantDeclMap[GCD];
3566   if (*Entry)
3567     return ConstantAddress(*Entry, (*Entry)->getValueType(), Alignment);
3568 
3569   ConstantEmitter Emitter(*this);
3570   llvm::Constant *Init;
3571 
3572   const APValue &V = GCD->getValue();
3573 
3574   assert(!V.isAbsent());
3575   Init = Emitter.emitForInitializer(V, GCD->getType().getAddressSpace(),
3576                                     GCD->getType());
3577 
3578   auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(),
3579                                       /*isConstant=*/true,
3580                                       llvm::GlobalValue::PrivateLinkage, Init,
3581                                       ".constant");
3582   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3583   GV->setAlignment(Alignment.getAsAlign());
3584 
3585   Emitter.finalize(GV);
3586 
3587   *Entry = GV;
3588   return ConstantAddress(GV, GV->getValueType(), Alignment);
3589 }
3590 
3591 ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject(
3592     const TemplateParamObjectDecl *TPO) {
3593   StringRef Name = getMangledName(TPO);
3594   CharUnits Alignment = getNaturalTypeAlignment(TPO->getType());
3595 
3596   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
3597     return ConstantAddress(GV, GV->getValueType(), Alignment);
3598 
3599   ConstantEmitter Emitter(*this);
3600   llvm::Constant *Init = Emitter.emitForInitializer(
3601         TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType());
3602 
3603   if (!Init) {
3604     ErrorUnsupported(TPO, "template parameter object");
3605     return ConstantAddress::invalid();
3606   }
3607 
3608   llvm::GlobalValue::LinkageTypes Linkage =
3609       isExternallyVisible(TPO->getLinkageAndVisibility().getLinkage())
3610           ? llvm::GlobalValue::LinkOnceODRLinkage
3611           : llvm::GlobalValue::InternalLinkage;
3612   auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(),
3613                                       /*isConstant=*/true, Linkage, Init, Name);
3614   setGVProperties(GV, TPO);
3615   if (supportsCOMDAT())
3616     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3617   Emitter.finalize(GV);
3618 
3619     return ConstantAddress(GV, GV->getValueType(), Alignment);
3620 }
3621 
3622 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
3623   const AliasAttr *AA = VD->getAttr<AliasAttr>();
3624   assert(AA && "No alias?");
3625 
3626   CharUnits Alignment = getContext().getDeclAlign(VD);
3627   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
3628 
3629   // See if there is already something with the target's name in the module.
3630   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
3631   if (Entry)
3632     return ConstantAddress(Entry, DeclTy, Alignment);
3633 
3634   llvm::Constant *Aliasee;
3635   if (isa<llvm::FunctionType>(DeclTy))
3636     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
3637                                       GlobalDecl(cast<FunctionDecl>(VD)),
3638                                       /*ForVTable=*/false);
3639   else
3640     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
3641                                     nullptr);
3642 
3643   auto *F = cast<llvm::GlobalValue>(Aliasee);
3644   F->setLinkage(llvm::Function::ExternalWeakLinkage);
3645   WeakRefReferences.insert(F);
3646 
3647   return ConstantAddress(Aliasee, DeclTy, Alignment);
3648 }
3649 
3650 template <typename AttrT> static bool hasImplicitAttr(const ValueDecl *D) {
3651   if (!D)
3652     return false;
3653   if (auto *A = D->getAttr<AttrT>())
3654     return A->isImplicit();
3655   return D->isImplicit();
3656 }
3657 
3658 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
3659   const auto *Global = cast<ValueDecl>(GD.getDecl());
3660 
3661   // Weak references don't produce any output by themselves.
3662   if (Global->hasAttr<WeakRefAttr>())
3663     return;
3664 
3665   // If this is an alias definition (which otherwise looks like a declaration)
3666   // emit it now.
3667   if (Global->hasAttr<AliasAttr>())
3668     return EmitAliasDefinition(GD);
3669 
3670   // IFunc like an alias whose value is resolved at runtime by calling resolver.
3671   if (Global->hasAttr<IFuncAttr>())
3672     return emitIFuncDefinition(GD);
3673 
3674   // If this is a cpu_dispatch multiversion function, emit the resolver.
3675   if (Global->hasAttr<CPUDispatchAttr>())
3676     return emitCPUDispatchDefinition(GD);
3677 
3678   // If this is CUDA, be selective about which declarations we emit.
3679   // Non-constexpr non-lambda implicit host device functions are not emitted
3680   // unless they are used on device side.
3681   if (LangOpts.CUDA) {
3682     if (LangOpts.CUDAIsDevice) {
3683       const auto *FD = dyn_cast<FunctionDecl>(Global);
3684       if ((!Global->hasAttr<CUDADeviceAttr>() ||
3685            (LangOpts.OffloadImplicitHostDeviceTemplates && FD &&
3686             hasImplicitAttr<CUDAHostAttr>(FD) &&
3687             hasImplicitAttr<CUDADeviceAttr>(FD) && !FD->isConstexpr() &&
3688             !isLambdaCallOperator(FD) &&
3689             !getContext().CUDAImplicitHostDeviceFunUsedByDevice.count(FD))) &&
3690           !Global->hasAttr<CUDAGlobalAttr>() &&
3691           !Global->hasAttr<CUDAConstantAttr>() &&
3692           !Global->hasAttr<CUDASharedAttr>() &&
3693           !Global->getType()->isCUDADeviceBuiltinSurfaceType() &&
3694           !Global->getType()->isCUDADeviceBuiltinTextureType() &&
3695           !(LangOpts.HIPStdPar && isa<FunctionDecl>(Global) &&
3696             !Global->hasAttr<CUDAHostAttr>()))
3697         return;
3698     } else {
3699       // We need to emit host-side 'shadows' for all global
3700       // device-side variables because the CUDA runtime needs their
3701       // size and host-side address in order to provide access to
3702       // their device-side incarnations.
3703 
3704       // So device-only functions are the only things we skip.
3705       if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
3706           Global->hasAttr<CUDADeviceAttr>())
3707         return;
3708 
3709       assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
3710              "Expected Variable or Function");
3711     }
3712   }
3713 
3714   if (LangOpts.OpenMP) {
3715     // If this is OpenMP, check if it is legal to emit this global normally.
3716     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
3717       return;
3718     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
3719       if (MustBeEmitted(Global))
3720         EmitOMPDeclareReduction(DRD);
3721       return;
3722     }
3723     if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
3724       if (MustBeEmitted(Global))
3725         EmitOMPDeclareMapper(DMD);
3726       return;
3727     }
3728   }
3729 
3730   // Ignore declarations, they will be emitted on their first use.
3731   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
3732     // Update deferred annotations with the latest declaration if the function
3733     // function was already used or defined.
3734     if (FD->hasAttr<AnnotateAttr>()) {
3735       StringRef MangledName = getMangledName(GD);
3736       if (GetGlobalValue(MangledName))
3737         DeferredAnnotations[MangledName] = FD;
3738     }
3739 
3740     // Forward declarations are emitted lazily on first use.
3741     if (!FD->doesThisDeclarationHaveABody()) {
3742       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
3743         return;
3744 
3745       StringRef MangledName = getMangledName(GD);
3746 
3747       // Compute the function info and LLVM type.
3748       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3749       llvm::Type *Ty = getTypes().GetFunctionType(FI);
3750 
3751       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
3752                               /*DontDefer=*/false);
3753       return;
3754     }
3755   } else {
3756     const auto *VD = cast<VarDecl>(Global);
3757     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
3758     if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
3759         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
3760       if (LangOpts.OpenMP) {
3761         // Emit declaration of the must-be-emitted declare target variable.
3762         if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3763                 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
3764 
3765           // If this variable has external storage and doesn't require special
3766           // link handling we defer to its canonical definition.
3767           if (VD->hasExternalStorage() &&
3768               Res != OMPDeclareTargetDeclAttr::MT_Link)
3769             return;
3770 
3771           bool UnifiedMemoryEnabled =
3772               getOpenMPRuntime().hasRequiresUnifiedSharedMemory();
3773           if ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3774                *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3775               !UnifiedMemoryEnabled) {
3776             (void)GetAddrOfGlobalVar(VD);
3777           } else {
3778             assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
3779                     ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3780                       *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3781                      UnifiedMemoryEnabled)) &&
3782                    "Link clause or to clause with unified memory expected.");
3783             (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
3784           }
3785 
3786           return;
3787         }
3788       }
3789       // If this declaration may have caused an inline variable definition to
3790       // change linkage, make sure that it's emitted.
3791       if (Context.getInlineVariableDefinitionKind(VD) ==
3792           ASTContext::InlineVariableDefinitionKind::Strong)
3793         GetAddrOfGlobalVar(VD);
3794       return;
3795     }
3796   }
3797 
3798   // Defer code generation to first use when possible, e.g. if this is an inline
3799   // function. If the global must always be emitted, do it eagerly if possible
3800   // to benefit from cache locality.
3801   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
3802     // Emit the definition if it can't be deferred.
3803     EmitGlobalDefinition(GD);
3804     addEmittedDeferredDecl(GD);
3805     return;
3806   }
3807 
3808   // If we're deferring emission of a C++ variable with an
3809   // initializer, remember the order in which it appeared in the file.
3810   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
3811       cast<VarDecl>(Global)->hasInit()) {
3812     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
3813     CXXGlobalInits.push_back(nullptr);
3814   }
3815 
3816   StringRef MangledName = getMangledName(GD);
3817   if (GetGlobalValue(MangledName) != nullptr) {
3818     // The value has already been used and should therefore be emitted.
3819     addDeferredDeclToEmit(GD);
3820   } else if (MustBeEmitted(Global)) {
3821     // The value must be emitted, but cannot be emitted eagerly.
3822     assert(!MayBeEmittedEagerly(Global));
3823     addDeferredDeclToEmit(GD);
3824   } else {
3825     // Otherwise, remember that we saw a deferred decl with this name.  The
3826     // first use of the mangled name will cause it to move into
3827     // DeferredDeclsToEmit.
3828     DeferredDecls[MangledName] = GD;
3829   }
3830 }
3831 
3832 // Check if T is a class type with a destructor that's not dllimport.
3833 static bool HasNonDllImportDtor(QualType T) {
3834   if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
3835     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
3836       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
3837         return true;
3838 
3839   return false;
3840 }
3841 
3842 namespace {
3843   struct FunctionIsDirectlyRecursive
3844       : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
3845     const StringRef Name;
3846     const Builtin::Context &BI;
3847     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
3848         : Name(N), BI(C) {}
3849 
3850     bool VisitCallExpr(const CallExpr *E) {
3851       const FunctionDecl *FD = E->getDirectCallee();
3852       if (!FD)
3853         return false;
3854       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
3855       if (Attr && Name == Attr->getLabel())
3856         return true;
3857       unsigned BuiltinID = FD->getBuiltinID();
3858       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
3859         return false;
3860       StringRef BuiltinName = BI.getName(BuiltinID);
3861       if (BuiltinName.starts_with("__builtin_") &&
3862           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
3863         return true;
3864       }
3865       return false;
3866     }
3867 
3868     bool VisitStmt(const Stmt *S) {
3869       for (const Stmt *Child : S->children())
3870         if (Child && this->Visit(Child))
3871           return true;
3872       return false;
3873     }
3874   };
3875 
3876   // Make sure we're not referencing non-imported vars or functions.
3877   struct DLLImportFunctionVisitor
3878       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
3879     bool SafeToInline = true;
3880 
3881     bool shouldVisitImplicitCode() const { return true; }
3882 
3883     bool VisitVarDecl(VarDecl *VD) {
3884       if (VD->getTLSKind()) {
3885         // A thread-local variable cannot be imported.
3886         SafeToInline = false;
3887         return SafeToInline;
3888       }
3889 
3890       // A variable definition might imply a destructor call.
3891       if (VD->isThisDeclarationADefinition())
3892         SafeToInline = !HasNonDllImportDtor(VD->getType());
3893 
3894       return SafeToInline;
3895     }
3896 
3897     bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
3898       if (const auto *D = E->getTemporary()->getDestructor())
3899         SafeToInline = D->hasAttr<DLLImportAttr>();
3900       return SafeToInline;
3901     }
3902 
3903     bool VisitDeclRefExpr(DeclRefExpr *E) {
3904       ValueDecl *VD = E->getDecl();
3905       if (isa<FunctionDecl>(VD))
3906         SafeToInline = VD->hasAttr<DLLImportAttr>();
3907       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
3908         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
3909       return SafeToInline;
3910     }
3911 
3912     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
3913       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
3914       return SafeToInline;
3915     }
3916 
3917     bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3918       CXXMethodDecl *M = E->getMethodDecl();
3919       if (!M) {
3920         // Call through a pointer to member function. This is safe to inline.
3921         SafeToInline = true;
3922       } else {
3923         SafeToInline = M->hasAttr<DLLImportAttr>();
3924       }
3925       return SafeToInline;
3926     }
3927 
3928     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
3929       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
3930       return SafeToInline;
3931     }
3932 
3933     bool VisitCXXNewExpr(CXXNewExpr *E) {
3934       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
3935       return SafeToInline;
3936     }
3937   };
3938 }
3939 
3940 // isTriviallyRecursive - Check if this function calls another
3941 // decl that, because of the asm attribute or the other decl being a builtin,
3942 // ends up pointing to itself.
3943 bool
3944 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
3945   StringRef Name;
3946   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
3947     // asm labels are a special kind of mangling we have to support.
3948     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
3949     if (!Attr)
3950       return false;
3951     Name = Attr->getLabel();
3952   } else {
3953     Name = FD->getName();
3954   }
3955 
3956   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
3957   const Stmt *Body = FD->getBody();
3958   return Body ? Walker.Visit(Body) : false;
3959 }
3960 
3961 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
3962   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
3963     return true;
3964 
3965   const auto *F = cast<FunctionDecl>(GD.getDecl());
3966   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
3967     return false;
3968 
3969   // We don't import function bodies from other named module units since that
3970   // behavior may break ABI compatibility of the current unit.
3971   if (const Module *M = F->getOwningModule();
3972       M && M->getTopLevelModule()->isNamedModule() &&
3973       getContext().getCurrentNamedModule() != M->getTopLevelModule() &&
3974       !F->hasAttr<AlwaysInlineAttr>())
3975     return false;
3976 
3977   if (F->hasAttr<NoInlineAttr>())
3978     return false;
3979 
3980   if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
3981     // Check whether it would be safe to inline this dllimport function.
3982     DLLImportFunctionVisitor Visitor;
3983     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
3984     if (!Visitor.SafeToInline)
3985       return false;
3986 
3987     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
3988       // Implicit destructor invocations aren't captured in the AST, so the
3989       // check above can't see them. Check for them manually here.
3990       for (const Decl *Member : Dtor->getParent()->decls())
3991         if (isa<FieldDecl>(Member))
3992           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
3993             return false;
3994       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
3995         if (HasNonDllImportDtor(B.getType()))
3996           return false;
3997     }
3998   }
3999 
4000   // Inline builtins declaration must be emitted. They often are fortified
4001   // functions.
4002   if (F->isInlineBuiltinDeclaration())
4003     return true;
4004 
4005   // PR9614. Avoid cases where the source code is lying to us. An available
4006   // externally function should have an equivalent function somewhere else,
4007   // but a function that calls itself through asm label/`__builtin_` trickery is
4008   // clearly not equivalent to the real implementation.
4009   // This happens in glibc's btowc and in some configure checks.
4010   return !isTriviallyRecursive(F);
4011 }
4012 
4013 bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
4014   return CodeGenOpts.OptimizationLevel > 0;
4015 }
4016 
4017 void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
4018                                                        llvm::GlobalValue *GV) {
4019   const auto *FD = cast<FunctionDecl>(GD.getDecl());
4020 
4021   if (FD->isCPUSpecificMultiVersion()) {
4022     auto *Spec = FD->getAttr<CPUSpecificAttr>();
4023     for (unsigned I = 0; I < Spec->cpus_size(); ++I)
4024       EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
4025   } else if (FD->isTargetClonesMultiVersion()) {
4026     auto *Clone = FD->getAttr<TargetClonesAttr>();
4027     for (unsigned I = 0; I < Clone->featuresStrs_size(); ++I)
4028       if (Clone->isFirstOfVersion(I))
4029         EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
4030     // Ensure that the resolver function is also emitted.
4031     GetOrCreateMultiVersionResolver(GD);
4032   } else
4033     EmitGlobalFunctionDefinition(GD, GV);
4034 }
4035 
4036 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
4037   const auto *D = cast<ValueDecl>(GD.getDecl());
4038 
4039   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
4040                                  Context.getSourceManager(),
4041                                  "Generating code for declaration");
4042 
4043   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4044     // At -O0, don't generate IR for functions with available_externally
4045     // linkage.
4046     if (!shouldEmitFunction(GD))
4047       return;
4048 
4049     llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
4050       std::string Name;
4051       llvm::raw_string_ostream OS(Name);
4052       FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
4053                                /*Qualified=*/true);
4054       return Name;
4055     });
4056 
4057     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
4058       // Make sure to emit the definition(s) before we emit the thunks.
4059       // This is necessary for the generation of certain thunks.
4060       if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
4061         ABI->emitCXXStructor(GD);
4062       else if (FD->isMultiVersion())
4063         EmitMultiVersionFunctionDefinition(GD, GV);
4064       else
4065         EmitGlobalFunctionDefinition(GD, GV);
4066 
4067       if (Method->isVirtual())
4068         getVTables().EmitThunks(GD);
4069 
4070       return;
4071     }
4072 
4073     if (FD->isMultiVersion())
4074       return EmitMultiVersionFunctionDefinition(GD, GV);
4075     return EmitGlobalFunctionDefinition(GD, GV);
4076   }
4077 
4078   if (const auto *VD = dyn_cast<VarDecl>(D))
4079     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
4080 
4081   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
4082 }
4083 
4084 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
4085                                                       llvm::Function *NewFn);
4086 
4087 static unsigned
4088 TargetMVPriority(const TargetInfo &TI,
4089                  const CodeGenFunction::MultiVersionResolverOption &RO) {
4090   unsigned Priority = 0;
4091   unsigned NumFeatures = 0;
4092   for (StringRef Feat : RO.Conditions.Features) {
4093     Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
4094     NumFeatures++;
4095   }
4096 
4097   if (!RO.Conditions.Architecture.empty())
4098     Priority = std::max(
4099         Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
4100 
4101   Priority += TI.multiVersionFeatureCost() * NumFeatures;
4102 
4103   return Priority;
4104 }
4105 
4106 // Multiversion functions should be at most 'WeakODRLinkage' so that a different
4107 // TU can forward declare the function without causing problems.  Particularly
4108 // in the cases of CPUDispatch, this causes issues. This also makes sure we
4109 // work with internal linkage functions, so that the same function name can be
4110 // used with internal linkage in multiple TUs.
4111 llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM,
4112                                                        GlobalDecl GD) {
4113   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
4114   if (FD->getFormalLinkage() == Linkage::Internal)
4115     return llvm::GlobalValue::InternalLinkage;
4116   return llvm::GlobalValue::WeakODRLinkage;
4117 }
4118 
4119 void CodeGenModule::emitMultiVersionFunctions() {
4120   std::vector<GlobalDecl> MVFuncsToEmit;
4121   MultiVersionFuncs.swap(MVFuncsToEmit);
4122   for (GlobalDecl GD : MVFuncsToEmit) {
4123     const auto *FD = cast<FunctionDecl>(GD.getDecl());
4124     assert(FD && "Expected a FunctionDecl");
4125 
4126     SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
4127     if (FD->isTargetMultiVersion()) {
4128       getContext().forEachMultiversionedFunctionVersion(
4129           FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
4130             GlobalDecl CurGD{
4131                 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
4132             StringRef MangledName = getMangledName(CurGD);
4133             llvm::Constant *Func = GetGlobalValue(MangledName);
4134             if (!Func) {
4135               if (CurFD->isDefined()) {
4136                 EmitGlobalFunctionDefinition(CurGD, nullptr);
4137                 Func = GetGlobalValue(MangledName);
4138               } else {
4139                 const CGFunctionInfo &FI =
4140                     getTypes().arrangeGlobalDeclaration(GD);
4141                 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
4142                 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
4143                                          /*DontDefer=*/false, ForDefinition);
4144               }
4145               assert(Func && "This should have just been created");
4146             }
4147             if (CurFD->getMultiVersionKind() == MultiVersionKind::Target) {
4148               const auto *TA = CurFD->getAttr<TargetAttr>();
4149               llvm::SmallVector<StringRef, 8> Feats;
4150               TA->getAddedFeatures(Feats);
4151               Options.emplace_back(cast<llvm::Function>(Func),
4152                                    TA->getArchitecture(), Feats);
4153             } else {
4154               const auto *TVA = CurFD->getAttr<TargetVersionAttr>();
4155               llvm::SmallVector<StringRef, 8> Feats;
4156               TVA->getFeatures(Feats);
4157               Options.emplace_back(cast<llvm::Function>(Func),
4158                                    /*Architecture*/ "", Feats);
4159             }
4160           });
4161     } else if (FD->isTargetClonesMultiVersion()) {
4162       const auto *TC = FD->getAttr<TargetClonesAttr>();
4163       for (unsigned VersionIndex = 0; VersionIndex < TC->featuresStrs_size();
4164            ++VersionIndex) {
4165         if (!TC->isFirstOfVersion(VersionIndex))
4166           continue;
4167         GlobalDecl CurGD{(FD->isDefined() ? FD->getDefinition() : FD),
4168                          VersionIndex};
4169         StringRef Version = TC->getFeatureStr(VersionIndex);
4170         StringRef MangledName = getMangledName(CurGD);
4171         llvm::Constant *Func = GetGlobalValue(MangledName);
4172         if (!Func) {
4173           if (FD->isDefined()) {
4174             EmitGlobalFunctionDefinition(CurGD, nullptr);
4175             Func = GetGlobalValue(MangledName);
4176           } else {
4177             const CGFunctionInfo &FI =
4178                 getTypes().arrangeGlobalDeclaration(CurGD);
4179             llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
4180             Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
4181                                      /*DontDefer=*/false, ForDefinition);
4182           }
4183           assert(Func && "This should have just been created");
4184         }
4185 
4186         StringRef Architecture;
4187         llvm::SmallVector<StringRef, 1> Feature;
4188 
4189         if (getTarget().getTriple().isAArch64()) {
4190           if (Version != "default") {
4191             llvm::SmallVector<StringRef, 8> VerFeats;
4192             Version.split(VerFeats, "+");
4193             for (auto &CurFeat : VerFeats)
4194               Feature.push_back(CurFeat.trim());
4195           }
4196         } else {
4197           if (Version.starts_with("arch="))
4198             Architecture = Version.drop_front(sizeof("arch=") - 1);
4199           else if (Version != "default")
4200             Feature.push_back(Version);
4201         }
4202 
4203         Options.emplace_back(cast<llvm::Function>(Func), Architecture, Feature);
4204       }
4205     } else {
4206       assert(0 && "Expected a target or target_clones multiversion function");
4207       continue;
4208     }
4209 
4210     llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
4211     if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) {
4212       ResolverConstant = IFunc->getResolver();
4213       // In Aarch64, default versions of multiversioned functions are mangled to
4214       // their 'normal' assembly name. This deviates from other targets which
4215       // append a '.default' string. As a result we need to continue appending
4216       // .ifunc in Aarch64.
4217       // FIXME: Should Aarch64 mangling for 'default' multiversion function and
4218       // in turn ifunc function match that of other targets?
4219       if (FD->isTargetClonesMultiVersion() &&
4220           !getTarget().getTriple().isAArch64()) {
4221         const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4222         llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
4223         std::string MangledName = getMangledNameImpl(
4224             *this, GD, FD, /*OmitMultiVersionMangling=*/true);
4225         // In prior versions of Clang, the mangling for ifuncs incorrectly
4226         // included an .ifunc suffix. This alias is generated for backward
4227         // compatibility. It is deprecated, and may be removed in the future.
4228         auto *Alias = llvm::GlobalAlias::create(
4229             DeclTy, 0, getMultiversionLinkage(*this, GD),
4230             MangledName + ".ifunc", IFunc, &getModule());
4231         SetCommonAttributes(FD, Alias);
4232       }
4233     }
4234     llvm::Function *ResolverFunc = cast<llvm::Function>(ResolverConstant);
4235 
4236     ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD));
4237 
4238     if (!ResolverFunc->hasLocalLinkage() && supportsCOMDAT())
4239       ResolverFunc->setComdat(
4240           getModule().getOrInsertComdat(ResolverFunc->getName()));
4241 
4242     const TargetInfo &TI = getTarget();
4243     llvm::stable_sort(
4244         Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
4245                        const CodeGenFunction::MultiVersionResolverOption &RHS) {
4246           return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
4247         });
4248     CodeGenFunction CGF(*this);
4249     CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4250   }
4251 
4252   // Ensure that any additions to the deferred decls list caused by emitting a
4253   // variant are emitted.  This can happen when the variant itself is inline and
4254   // calls a function without linkage.
4255   if (!MVFuncsToEmit.empty())
4256     EmitDeferred();
4257 
4258   // Ensure that any additions to the multiversion funcs list from either the
4259   // deferred decls or the multiversion functions themselves are emitted.
4260   if (!MultiVersionFuncs.empty())
4261     emitMultiVersionFunctions();
4262 }
4263 
4264 void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
4265   const auto *FD = cast<FunctionDecl>(GD.getDecl());
4266   assert(FD && "Not a FunctionDecl?");
4267   assert(FD->isCPUDispatchMultiVersion() && "Not a multiversion function?");
4268   const auto *DD = FD->getAttr<CPUDispatchAttr>();
4269   assert(DD && "Not a cpu_dispatch Function?");
4270 
4271   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4272   llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
4273 
4274   StringRef ResolverName = getMangledName(GD);
4275   UpdateMultiVersionNames(GD, FD, ResolverName);
4276 
4277   llvm::Type *ResolverType;
4278   GlobalDecl ResolverGD;
4279   if (getTarget().supportsIFunc()) {
4280     ResolverType = llvm::FunctionType::get(
4281         llvm::PointerType::get(DeclTy,
4282                                getTypes().getTargetAddressSpace(FD->getType())),
4283         false);
4284   }
4285   else {
4286     ResolverType = DeclTy;
4287     ResolverGD = GD;
4288   }
4289 
4290   auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
4291       ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
4292   ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD));
4293   if (supportsCOMDAT())
4294     ResolverFunc->setComdat(
4295         getModule().getOrInsertComdat(ResolverFunc->getName()));
4296 
4297   SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
4298   const TargetInfo &Target = getTarget();
4299   unsigned Index = 0;
4300   for (const IdentifierInfo *II : DD->cpus()) {
4301     // Get the name of the target function so we can look it up/create it.
4302     std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
4303                               getCPUSpecificMangling(*this, II->getName());
4304 
4305     llvm::Constant *Func = GetGlobalValue(MangledName);
4306 
4307     if (!Func) {
4308       GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
4309       if (ExistingDecl.getDecl() &&
4310           ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
4311         EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
4312         Func = GetGlobalValue(MangledName);
4313       } else {
4314         if (!ExistingDecl.getDecl())
4315           ExistingDecl = GD.getWithMultiVersionIndex(Index);
4316 
4317       Func = GetOrCreateLLVMFunction(
4318           MangledName, DeclTy, ExistingDecl,
4319           /*ForVTable=*/false, /*DontDefer=*/true,
4320           /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
4321       }
4322     }
4323 
4324     llvm::SmallVector<StringRef, 32> Features;
4325     Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
4326     llvm::transform(Features, Features.begin(),
4327                     [](StringRef Str) { return Str.substr(1); });
4328     llvm::erase_if(Features, [&Target](StringRef Feat) {
4329       return !Target.validateCpuSupports(Feat);
4330     });
4331     Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
4332     ++Index;
4333   }
4334 
4335   llvm::stable_sort(
4336       Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
4337                   const CodeGenFunction::MultiVersionResolverOption &RHS) {
4338         return llvm::X86::getCpuSupportsMask(LHS.Conditions.Features) >
4339                llvm::X86::getCpuSupportsMask(RHS.Conditions.Features);
4340       });
4341 
4342   // If the list contains multiple 'default' versions, such as when it contains
4343   // 'pentium' and 'generic', don't emit the call to the generic one (since we
4344   // always run on at least a 'pentium'). We do this by deleting the 'least
4345   // advanced' (read, lowest mangling letter).
4346   while (Options.size() > 1 &&
4347          llvm::all_of(llvm::X86::getCpuSupportsMask(
4348                           (Options.end() - 2)->Conditions.Features),
4349                       [](auto X) { return X == 0; })) {
4350     StringRef LHSName = (Options.end() - 2)->Function->getName();
4351     StringRef RHSName = (Options.end() - 1)->Function->getName();
4352     if (LHSName.compare(RHSName) < 0)
4353       Options.erase(Options.end() - 2);
4354     else
4355       Options.erase(Options.end() - 1);
4356   }
4357 
4358   CodeGenFunction CGF(*this);
4359   CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4360 
4361   if (getTarget().supportsIFunc()) {
4362     llvm::GlobalValue::LinkageTypes Linkage = getMultiversionLinkage(*this, GD);
4363     auto *IFunc = cast<llvm::GlobalValue>(GetOrCreateMultiVersionResolver(GD));
4364 
4365     // Fix up function declarations that were created for cpu_specific before
4366     // cpu_dispatch was known
4367     if (!isa<llvm::GlobalIFunc>(IFunc)) {
4368       assert(cast<llvm::Function>(IFunc)->isDeclaration());
4369       auto *GI = llvm::GlobalIFunc::create(DeclTy, 0, Linkage, "", ResolverFunc,
4370                                            &getModule());
4371       GI->takeName(IFunc);
4372       IFunc->replaceAllUsesWith(GI);
4373       IFunc->eraseFromParent();
4374       IFunc = GI;
4375     }
4376 
4377     std::string AliasName = getMangledNameImpl(
4378         *this, GD, FD, /*OmitMultiVersionMangling=*/true);
4379     llvm::Constant *AliasFunc = GetGlobalValue(AliasName);
4380     if (!AliasFunc) {
4381       auto *GA = llvm::GlobalAlias::create(DeclTy, 0, Linkage, AliasName, IFunc,
4382                                            &getModule());
4383       SetCommonAttributes(GD, GA);
4384     }
4385   }
4386 }
4387 
4388 /// If a dispatcher for the specified mangled name is not in the module, create
4389 /// and return an llvm Function with the specified type.
4390 llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) {
4391   const auto *FD = cast<FunctionDecl>(GD.getDecl());
4392   assert(FD && "Not a FunctionDecl?");
4393 
4394   std::string MangledName =
4395       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
4396 
4397   // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
4398   // a separate resolver).
4399   std::string ResolverName = MangledName;
4400   if (getTarget().supportsIFunc()) {
4401     // In Aarch64, default versions of multiversioned functions are mangled to
4402     // their 'normal' assembly name. This deviates from other targets which
4403     // append a '.default' string. As a result we need to continue appending
4404     // .ifunc in Aarch64.
4405     // FIXME: Should Aarch64 mangling for 'default' multiversion function and
4406     // in turn ifunc function match that of other targets?
4407     if (!FD->isTargetClonesMultiVersion() ||
4408         getTarget().getTriple().isAArch64())
4409       ResolverName += ".ifunc";
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 = getContext().getAlignOfGlobalVarInChars(S->getType());
6340 
6341   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
6342   llvm::GlobalVariable **Entry = nullptr;
6343   if (!LangOpts.WritableStrings) {
6344     Entry = &ConstantStringMap[C];
6345     if (auto GV = *Entry) {
6346       if (uint64_t(Alignment.getQuantity()) > GV->getAlignment())
6347         GV->setAlignment(Alignment.getAsAlign());
6348       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
6349                              GV->getValueType(), Alignment);
6350     }
6351   }
6352 
6353   SmallString<256> MangledNameBuffer;
6354   StringRef GlobalVariableName;
6355   llvm::GlobalValue::LinkageTypes LT;
6356 
6357   // Mangle the string literal if that's how the ABI merges duplicate strings.
6358   // Don't do it if they are writable, since we don't want writes in one TU to
6359   // affect strings in another.
6360   if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
6361       !LangOpts.WritableStrings) {
6362     llvm::raw_svector_ostream Out(MangledNameBuffer);
6363     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
6364     LT = llvm::GlobalValue::LinkOnceODRLinkage;
6365     GlobalVariableName = MangledNameBuffer;
6366   } else {
6367     LT = llvm::GlobalValue::PrivateLinkage;
6368     GlobalVariableName = Name;
6369   }
6370 
6371   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
6372 
6373   CGDebugInfo *DI = getModuleDebugInfo();
6374   if (DI && getCodeGenOpts().hasReducedDebugInfo())
6375     DI->AddStringLiteralDebugInfo(GV, S);
6376 
6377   if (Entry)
6378     *Entry = GV;
6379 
6380   SanitizerMD->reportGlobal(GV, S->getStrTokenLoc(0), "<string literal>");
6381 
6382   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
6383                          GV->getValueType(), Alignment);
6384 }
6385 
6386 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
6387 /// array for the given ObjCEncodeExpr node.
6388 ConstantAddress
6389 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
6390   std::string Str;
6391   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
6392 
6393   return GetAddrOfConstantCString(Str);
6394 }
6395 
6396 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
6397 /// the literal and a terminating '\0' character.
6398 /// The result has pointer to array type.
6399 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
6400     const std::string &Str, const char *GlobalName) {
6401   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
6402   CharUnits Alignment =
6403     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
6404 
6405   llvm::Constant *C =
6406       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
6407 
6408   // Don't share any string literals if strings aren't constant.
6409   llvm::GlobalVariable **Entry = nullptr;
6410   if (!LangOpts.WritableStrings) {
6411     Entry = &ConstantStringMap[C];
6412     if (auto GV = *Entry) {
6413       if (uint64_t(Alignment.getQuantity()) > GV->getAlignment())
6414         GV->setAlignment(Alignment.getAsAlign());
6415       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
6416                              GV->getValueType(), Alignment);
6417     }
6418   }
6419 
6420   // Get the default prefix if a name wasn't specified.
6421   if (!GlobalName)
6422     GlobalName = ".str";
6423   // Create a global variable for this.
6424   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
6425                                   GlobalName, Alignment);
6426   if (Entry)
6427     *Entry = GV;
6428 
6429   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
6430                          GV->getValueType(), Alignment);
6431 }
6432 
6433 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
6434     const MaterializeTemporaryExpr *E, const Expr *Init) {
6435   assert((E->getStorageDuration() == SD_Static ||
6436           E->getStorageDuration() == SD_Thread) && "not a global temporary");
6437   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
6438 
6439   // If we're not materializing a subobject of the temporary, keep the
6440   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
6441   QualType MaterializedType = Init->getType();
6442   if (Init == E->getSubExpr())
6443     MaterializedType = E->getType();
6444 
6445   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
6446 
6447   auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr});
6448   if (!InsertResult.second) {
6449     // We've seen this before: either we already created it or we're in the
6450     // process of doing so.
6451     if (!InsertResult.first->second) {
6452       // We recursively re-entered this function, probably during emission of
6453       // the initializer. Create a placeholder. We'll clean this up in the
6454       // outer call, at the end of this function.
6455       llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType);
6456       InsertResult.first->second = new llvm::GlobalVariable(
6457           getModule(), Type, false, llvm::GlobalVariable::InternalLinkage,
6458           nullptr);
6459     }
6460     return ConstantAddress(InsertResult.first->second,
6461                            llvm::cast<llvm::GlobalVariable>(
6462                                InsertResult.first->second->stripPointerCasts())
6463                                ->getValueType(),
6464                            Align);
6465   }
6466 
6467   // FIXME: If an externally-visible declaration extends multiple temporaries,
6468   // we need to give each temporary the same name in every translation unit (and
6469   // we also need to make the temporaries externally-visible).
6470   SmallString<256> Name;
6471   llvm::raw_svector_ostream Out(Name);
6472   getCXXABI().getMangleContext().mangleReferenceTemporary(
6473       VD, E->getManglingNumber(), Out);
6474 
6475   APValue *Value = nullptr;
6476   if (E->getStorageDuration() == SD_Static && VD->evaluateValue()) {
6477     // If the initializer of the extending declaration is a constant
6478     // initializer, we should have a cached constant initializer for this
6479     // temporary. Note that this might have a different value from the value
6480     // computed by evaluating the initializer if the surrounding constant
6481     // expression modifies the temporary.
6482     Value = E->getOrCreateValue(false);
6483   }
6484 
6485   // Try evaluating it now, it might have a constant initializer.
6486   Expr::EvalResult EvalResult;
6487   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
6488       !EvalResult.hasSideEffects())
6489     Value = &EvalResult.Val;
6490 
6491   LangAS AddrSpace = GetGlobalVarAddressSpace(VD);
6492 
6493   std::optional<ConstantEmitter> emitter;
6494   llvm::Constant *InitialValue = nullptr;
6495   bool Constant = false;
6496   llvm::Type *Type;
6497   if (Value) {
6498     // The temporary has a constant initializer, use it.
6499     emitter.emplace(*this);
6500     InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
6501                                                MaterializedType);
6502     Constant =
6503         MaterializedType.isConstantStorage(getContext(), /*ExcludeCtor*/ Value,
6504                                            /*ExcludeDtor*/ false);
6505     Type = InitialValue->getType();
6506   } else {
6507     // No initializer, the initialization will be provided when we
6508     // initialize the declaration which performed lifetime extension.
6509     Type = getTypes().ConvertTypeForMem(MaterializedType);
6510   }
6511 
6512   // Create a global variable for this lifetime-extended temporary.
6513   llvm::GlobalValue::LinkageTypes Linkage = getLLVMLinkageVarDefinition(VD);
6514   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
6515     const VarDecl *InitVD;
6516     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
6517         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
6518       // Temporaries defined inside a class get linkonce_odr linkage because the
6519       // class can be defined in multiple translation units.
6520       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
6521     } else {
6522       // There is no need for this temporary to have external linkage if the
6523       // VarDecl has external linkage.
6524       Linkage = llvm::GlobalVariable::InternalLinkage;
6525     }
6526   }
6527   auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
6528   auto *GV = new llvm::GlobalVariable(
6529       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
6530       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
6531   if (emitter) emitter->finalize(GV);
6532   // Don't assign dllimport or dllexport to local linkage globals.
6533   if (!llvm::GlobalValue::isLocalLinkage(Linkage)) {
6534     setGVProperties(GV, VD);
6535     if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass)
6536       // The reference temporary should never be dllexport.
6537       GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
6538   }
6539   GV->setAlignment(Align.getAsAlign());
6540   if (supportsCOMDAT() && GV->isWeakForLinker())
6541     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
6542   if (VD->getTLSKind())
6543     setTLSMode(GV, *VD);
6544   llvm::Constant *CV = GV;
6545   if (AddrSpace != LangAS::Default)
6546     CV = getTargetCodeGenInfo().performAddrSpaceCast(
6547         *this, GV, AddrSpace, LangAS::Default,
6548         llvm::PointerType::get(
6549             getLLVMContext(),
6550             getContext().getTargetAddressSpace(LangAS::Default)));
6551 
6552   // Update the map with the new temporary. If we created a placeholder above,
6553   // replace it with the new global now.
6554   llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
6555   if (Entry) {
6556     Entry->replaceAllUsesWith(CV);
6557     llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
6558   }
6559   Entry = CV;
6560 
6561   return ConstantAddress(CV, Type, Align);
6562 }
6563 
6564 /// EmitObjCPropertyImplementations - Emit information for synthesized
6565 /// properties for an implementation.
6566 void CodeGenModule::EmitObjCPropertyImplementations(const
6567                                                     ObjCImplementationDecl *D) {
6568   for (const auto *PID : D->property_impls()) {
6569     // Dynamic is just for type-checking.
6570     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
6571       ObjCPropertyDecl *PD = PID->getPropertyDecl();
6572 
6573       // Determine which methods need to be implemented, some may have
6574       // been overridden. Note that ::isPropertyAccessor is not the method
6575       // we want, that just indicates if the decl came from a
6576       // property. What we want to know is if the method is defined in
6577       // this implementation.
6578       auto *Getter = PID->getGetterMethodDecl();
6579       if (!Getter || Getter->isSynthesizedAccessorStub())
6580         CodeGenFunction(*this).GenerateObjCGetter(
6581             const_cast<ObjCImplementationDecl *>(D), PID);
6582       auto *Setter = PID->getSetterMethodDecl();
6583       if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
6584         CodeGenFunction(*this).GenerateObjCSetter(
6585                                  const_cast<ObjCImplementationDecl *>(D), PID);
6586     }
6587   }
6588 }
6589 
6590 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
6591   const ObjCInterfaceDecl *iface = impl->getClassInterface();
6592   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
6593        ivar; ivar = ivar->getNextIvar())
6594     if (ivar->getType().isDestructedType())
6595       return true;
6596 
6597   return false;
6598 }
6599 
6600 static bool AllTrivialInitializers(CodeGenModule &CGM,
6601                                    ObjCImplementationDecl *D) {
6602   CodeGenFunction CGF(CGM);
6603   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
6604        E = D->init_end(); B != E; ++B) {
6605     CXXCtorInitializer *CtorInitExp = *B;
6606     Expr *Init = CtorInitExp->getInit();
6607     if (!CGF.isTrivialInitializer(Init))
6608       return false;
6609   }
6610   return true;
6611 }
6612 
6613 /// EmitObjCIvarInitializations - Emit information for ivar initialization
6614 /// for an implementation.
6615 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
6616   // We might need a .cxx_destruct even if we don't have any ivar initializers.
6617   if (needsDestructMethod(D)) {
6618     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
6619     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
6620     ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(
6621         getContext(), D->getLocation(), D->getLocation(), cxxSelector,
6622         getContext().VoidTy, nullptr, D,
6623         /*isInstance=*/true, /*isVariadic=*/false,
6624         /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
6625         /*isImplicitlyDeclared=*/true,
6626         /*isDefined=*/false, ObjCImplementationControl::Required);
6627     D->addInstanceMethod(DTORMethod);
6628     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
6629     D->setHasDestructors(true);
6630   }
6631 
6632   // If the implementation doesn't have any ivar initializers, we don't need
6633   // a .cxx_construct.
6634   if (D->getNumIvarInitializers() == 0 ||
6635       AllTrivialInitializers(*this, D))
6636     return;
6637 
6638   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
6639   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
6640   // The constructor returns 'self'.
6641   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(
6642       getContext(), D->getLocation(), D->getLocation(), cxxSelector,
6643       getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true,
6644       /*isVariadic=*/false,
6645       /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
6646       /*isImplicitlyDeclared=*/true,
6647       /*isDefined=*/false, ObjCImplementationControl::Required);
6648   D->addInstanceMethod(CTORMethod);
6649   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
6650   D->setHasNonZeroConstructors(true);
6651 }
6652 
6653 // EmitLinkageSpec - Emit all declarations in a linkage spec.
6654 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
6655   if (LSD->getLanguage() != LinkageSpecLanguageIDs::C &&
6656       LSD->getLanguage() != LinkageSpecLanguageIDs::CXX) {
6657     ErrorUnsupported(LSD, "linkage spec");
6658     return;
6659   }
6660 
6661   EmitDeclContext(LSD);
6662 }
6663 
6664 void CodeGenModule::EmitTopLevelStmt(const TopLevelStmtDecl *D) {
6665   // Device code should not be at top level.
6666   if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
6667     return;
6668 
6669   std::unique_ptr<CodeGenFunction> &CurCGF =
6670       GlobalTopLevelStmtBlockInFlight.first;
6671 
6672   // We emitted a top-level stmt but after it there is initialization.
6673   // Stop squashing the top-level stmts into a single function.
6674   if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) {
6675     CurCGF->FinishFunction(D->getEndLoc());
6676     CurCGF = nullptr;
6677   }
6678 
6679   if (!CurCGF) {
6680     // void __stmts__N(void)
6681     // FIXME: Ask the ABI name mangler to pick a name.
6682     std::string Name = "__stmts__" + llvm::utostr(CXXGlobalInits.size());
6683     FunctionArgList Args;
6684     QualType RetTy = getContext().VoidTy;
6685     const CGFunctionInfo &FnInfo =
6686         getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args);
6687     llvm::FunctionType *FnTy = getTypes().GetFunctionType(FnInfo);
6688     llvm::Function *Fn = llvm::Function::Create(
6689         FnTy, llvm::GlobalValue::InternalLinkage, Name, &getModule());
6690 
6691     CurCGF.reset(new CodeGenFunction(*this));
6692     GlobalTopLevelStmtBlockInFlight.second = D;
6693     CurCGF->StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
6694                           D->getBeginLoc(), D->getBeginLoc());
6695     CXXGlobalInits.push_back(Fn);
6696   }
6697 
6698   CurCGF->EmitStmt(D->getStmt());
6699 }
6700 
6701 void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
6702   for (auto *I : DC->decls()) {
6703     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
6704     // are themselves considered "top-level", so EmitTopLevelDecl on an
6705     // ObjCImplDecl does not recursively visit them. We need to do that in
6706     // case they're nested inside another construct (LinkageSpecDecl /
6707     // ExportDecl) that does stop them from being considered "top-level".
6708     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
6709       for (auto *M : OID->methods())
6710         EmitTopLevelDecl(M);
6711     }
6712 
6713     EmitTopLevelDecl(I);
6714   }
6715 }
6716 
6717 /// EmitTopLevelDecl - Emit code for a single top level declaration.
6718 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
6719   // Ignore dependent declarations.
6720   if (D->isTemplated())
6721     return;
6722 
6723   // Consteval function shouldn't be emitted.
6724   if (auto *FD = dyn_cast<FunctionDecl>(D); FD && FD->isImmediateFunction())
6725     return;
6726 
6727   switch (D->getKind()) {
6728   case Decl::CXXConversion:
6729   case Decl::CXXMethod:
6730   case Decl::Function:
6731     EmitGlobal(cast<FunctionDecl>(D));
6732     // Always provide some coverage mapping
6733     // even for the functions that aren't emitted.
6734     AddDeferredUnusedCoverageMapping(D);
6735     break;
6736 
6737   case Decl::CXXDeductionGuide:
6738     // Function-like, but does not result in code emission.
6739     break;
6740 
6741   case Decl::Var:
6742   case Decl::Decomposition:
6743   case Decl::VarTemplateSpecialization:
6744     EmitGlobal(cast<VarDecl>(D));
6745     if (auto *DD = dyn_cast<DecompositionDecl>(D))
6746       for (auto *B : DD->bindings())
6747         if (auto *HD = B->getHoldingVar())
6748           EmitGlobal(HD);
6749     break;
6750 
6751   // Indirect fields from global anonymous structs and unions can be
6752   // ignored; only the actual variable requires IR gen support.
6753   case Decl::IndirectField:
6754     break;
6755 
6756   // C++ Decls
6757   case Decl::Namespace:
6758     EmitDeclContext(cast<NamespaceDecl>(D));
6759     break;
6760   case Decl::ClassTemplateSpecialization: {
6761     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
6762     if (CGDebugInfo *DI = getModuleDebugInfo())
6763       if (Spec->getSpecializationKind() ==
6764               TSK_ExplicitInstantiationDefinition &&
6765           Spec->hasDefinition())
6766         DI->completeTemplateDefinition(*Spec);
6767   } [[fallthrough]];
6768   case Decl::CXXRecord: {
6769     CXXRecordDecl *CRD = cast<CXXRecordDecl>(D);
6770     if (CGDebugInfo *DI = getModuleDebugInfo()) {
6771       if (CRD->hasDefinition())
6772         DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
6773       if (auto *ES = D->getASTContext().getExternalSource())
6774         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
6775           DI->completeUnusedClass(*CRD);
6776     }
6777     // Emit any static data members, they may be definitions.
6778     for (auto *I : CRD->decls())
6779       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
6780         EmitTopLevelDecl(I);
6781     break;
6782   }
6783     // No code generation needed.
6784   case Decl::UsingShadow:
6785   case Decl::ClassTemplate:
6786   case Decl::VarTemplate:
6787   case Decl::Concept:
6788   case Decl::VarTemplatePartialSpecialization:
6789   case Decl::FunctionTemplate:
6790   case Decl::TypeAliasTemplate:
6791   case Decl::Block:
6792   case Decl::Empty:
6793   case Decl::Binding:
6794     break;
6795   case Decl::Using:          // using X; [C++]
6796     if (CGDebugInfo *DI = getModuleDebugInfo())
6797         DI->EmitUsingDecl(cast<UsingDecl>(*D));
6798     break;
6799   case Decl::UsingEnum: // using enum X; [C++]
6800     if (CGDebugInfo *DI = getModuleDebugInfo())
6801       DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D));
6802     break;
6803   case Decl::NamespaceAlias:
6804     if (CGDebugInfo *DI = getModuleDebugInfo())
6805         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
6806     break;
6807   case Decl::UsingDirective: // using namespace X; [C++]
6808     if (CGDebugInfo *DI = getModuleDebugInfo())
6809       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
6810     break;
6811   case Decl::CXXConstructor:
6812     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
6813     break;
6814   case Decl::CXXDestructor:
6815     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
6816     break;
6817 
6818   case Decl::StaticAssert:
6819     // Nothing to do.
6820     break;
6821 
6822   // Objective-C Decls
6823 
6824   // Forward declarations, no (immediate) code generation.
6825   case Decl::ObjCInterface:
6826   case Decl::ObjCCategory:
6827     break;
6828 
6829   case Decl::ObjCProtocol: {
6830     auto *Proto = cast<ObjCProtocolDecl>(D);
6831     if (Proto->isThisDeclarationADefinition())
6832       ObjCRuntime->GenerateProtocol(Proto);
6833     break;
6834   }
6835 
6836   case Decl::ObjCCategoryImpl:
6837     // Categories have properties but don't support synthesize so we
6838     // can ignore them here.
6839     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
6840     break;
6841 
6842   case Decl::ObjCImplementation: {
6843     auto *OMD = cast<ObjCImplementationDecl>(D);
6844     EmitObjCPropertyImplementations(OMD);
6845     EmitObjCIvarInitializations(OMD);
6846     ObjCRuntime->GenerateClass(OMD);
6847     // Emit global variable debug information.
6848     if (CGDebugInfo *DI = getModuleDebugInfo())
6849       if (getCodeGenOpts().hasReducedDebugInfo())
6850         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
6851             OMD->getClassInterface()), OMD->getLocation());
6852     break;
6853   }
6854   case Decl::ObjCMethod: {
6855     auto *OMD = cast<ObjCMethodDecl>(D);
6856     // If this is not a prototype, emit the body.
6857     if (OMD->getBody())
6858       CodeGenFunction(*this).GenerateObjCMethod(OMD);
6859     break;
6860   }
6861   case Decl::ObjCCompatibleAlias:
6862     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
6863     break;
6864 
6865   case Decl::PragmaComment: {
6866     const auto *PCD = cast<PragmaCommentDecl>(D);
6867     switch (PCD->getCommentKind()) {
6868     case PCK_Unknown:
6869       llvm_unreachable("unexpected pragma comment kind");
6870     case PCK_Linker:
6871       AppendLinkerOptions(PCD->getArg());
6872       break;
6873     case PCK_Lib:
6874         AddDependentLib(PCD->getArg());
6875       break;
6876     case PCK_Compiler:
6877     case PCK_ExeStr:
6878     case PCK_User:
6879       break; // We ignore all of these.
6880     }
6881     break;
6882   }
6883 
6884   case Decl::PragmaDetectMismatch: {
6885     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
6886     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
6887     break;
6888   }
6889 
6890   case Decl::LinkageSpec:
6891     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
6892     break;
6893 
6894   case Decl::FileScopeAsm: {
6895     // File-scope asm is ignored during device-side CUDA compilation.
6896     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
6897       break;
6898     // File-scope asm is ignored during device-side OpenMP compilation.
6899     if (LangOpts.OpenMPIsTargetDevice)
6900       break;
6901     // File-scope asm is ignored during device-side SYCL compilation.
6902     if (LangOpts.SYCLIsDevice)
6903       break;
6904     auto *AD = cast<FileScopeAsmDecl>(D);
6905     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
6906     break;
6907   }
6908 
6909   case Decl::TopLevelStmt:
6910     EmitTopLevelStmt(cast<TopLevelStmtDecl>(D));
6911     break;
6912 
6913   case Decl::Import: {
6914     auto *Import = cast<ImportDecl>(D);
6915 
6916     // If we've already imported this module, we're done.
6917     if (!ImportedModules.insert(Import->getImportedModule()))
6918       break;
6919 
6920     // Emit debug information for direct imports.
6921     if (!Import->getImportedOwningModule()) {
6922       if (CGDebugInfo *DI = getModuleDebugInfo())
6923         DI->EmitImportDecl(*Import);
6924     }
6925 
6926     // For C++ standard modules we are done - we will call the module
6927     // initializer for imported modules, and that will likewise call those for
6928     // any imports it has.
6929     if (CXX20ModuleInits && Import->getImportedOwningModule() &&
6930         !Import->getImportedOwningModule()->isModuleMapModule())
6931       break;
6932 
6933     // For clang C++ module map modules the initializers for sub-modules are
6934     // emitted here.
6935 
6936     // Find all of the submodules and emit the module initializers.
6937     llvm::SmallPtrSet<clang::Module *, 16> Visited;
6938     SmallVector<clang::Module *, 16> Stack;
6939     Visited.insert(Import->getImportedModule());
6940     Stack.push_back(Import->getImportedModule());
6941 
6942     while (!Stack.empty()) {
6943       clang::Module *Mod = Stack.pop_back_val();
6944       if (!EmittedModuleInitializers.insert(Mod).second)
6945         continue;
6946 
6947       for (auto *D : Context.getModuleInitializers(Mod))
6948         EmitTopLevelDecl(D);
6949 
6950       // Visit the submodules of this module.
6951       for (auto *Submodule : Mod->submodules()) {
6952         // Skip explicit children; they need to be explicitly imported to emit
6953         // the initializers.
6954         if (Submodule->IsExplicit)
6955           continue;
6956 
6957         if (Visited.insert(Submodule).second)
6958           Stack.push_back(Submodule);
6959       }
6960     }
6961     break;
6962   }
6963 
6964   case Decl::Export:
6965     EmitDeclContext(cast<ExportDecl>(D));
6966     break;
6967 
6968   case Decl::OMPThreadPrivate:
6969     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
6970     break;
6971 
6972   case Decl::OMPAllocate:
6973     EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D));
6974     break;
6975 
6976   case Decl::OMPDeclareReduction:
6977     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
6978     break;
6979 
6980   case Decl::OMPDeclareMapper:
6981     EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
6982     break;
6983 
6984   case Decl::OMPRequires:
6985     EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
6986     break;
6987 
6988   case Decl::Typedef:
6989   case Decl::TypeAlias: // using foo = bar; [C++11]
6990     if (CGDebugInfo *DI = getModuleDebugInfo())
6991       DI->EmitAndRetainType(
6992           getContext().getTypedefType(cast<TypedefNameDecl>(D)));
6993     break;
6994 
6995   case Decl::Record:
6996     if (CGDebugInfo *DI = getModuleDebugInfo())
6997       if (cast<RecordDecl>(D)->getDefinition())
6998         DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
6999     break;
7000 
7001   case Decl::Enum:
7002     if (CGDebugInfo *DI = getModuleDebugInfo())
7003       if (cast<EnumDecl>(D)->getDefinition())
7004         DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D)));
7005     break;
7006 
7007   case Decl::HLSLBuffer:
7008     getHLSLRuntime().addBuffer(cast<HLSLBufferDecl>(D));
7009     break;
7010 
7011   default:
7012     // Make sure we handled everything we should, every other kind is a
7013     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
7014     // function. Need to recode Decl::Kind to do that easily.
7015     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
7016     break;
7017   }
7018 }
7019 
7020 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
7021   // Do we need to generate coverage mapping?
7022   if (!CodeGenOpts.CoverageMapping)
7023     return;
7024   switch (D->getKind()) {
7025   case Decl::CXXConversion:
7026   case Decl::CXXMethod:
7027   case Decl::Function:
7028   case Decl::ObjCMethod:
7029   case Decl::CXXConstructor:
7030   case Decl::CXXDestructor: {
7031     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
7032       break;
7033     SourceManager &SM = getContext().getSourceManager();
7034     if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
7035       break;
7036     DeferredEmptyCoverageMappingDecls.try_emplace(D, true);
7037     break;
7038   }
7039   default:
7040     break;
7041   };
7042 }
7043 
7044 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
7045   // Do we need to generate coverage mapping?
7046   if (!CodeGenOpts.CoverageMapping)
7047     return;
7048   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
7049     if (Fn->isTemplateInstantiation())
7050       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
7051   }
7052   DeferredEmptyCoverageMappingDecls.insert_or_assign(D, false);
7053 }
7054 
7055 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
7056   // We call takeVector() here to avoid use-after-free.
7057   // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
7058   // we deserialize function bodies to emit coverage info for them, and that
7059   // deserializes more declarations. How should we handle that case?
7060   for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
7061     if (!Entry.second)
7062       continue;
7063     const Decl *D = Entry.first;
7064     switch (D->getKind()) {
7065     case Decl::CXXConversion:
7066     case Decl::CXXMethod:
7067     case Decl::Function:
7068     case Decl::ObjCMethod: {
7069       CodeGenPGO PGO(*this);
7070       GlobalDecl GD(cast<FunctionDecl>(D));
7071       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
7072                                   getFunctionLinkage(GD));
7073       break;
7074     }
7075     case Decl::CXXConstructor: {
7076       CodeGenPGO PGO(*this);
7077       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
7078       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
7079                                   getFunctionLinkage(GD));
7080       break;
7081     }
7082     case Decl::CXXDestructor: {
7083       CodeGenPGO PGO(*this);
7084       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
7085       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
7086                                   getFunctionLinkage(GD));
7087       break;
7088     }
7089     default:
7090       break;
7091     };
7092   }
7093 }
7094 
7095 void CodeGenModule::EmitMainVoidAlias() {
7096   // In order to transition away from "__original_main" gracefully, emit an
7097   // alias for "main" in the no-argument case so that libc can detect when
7098   // new-style no-argument main is in used.
7099   if (llvm::Function *F = getModule().getFunction("main")) {
7100     if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
7101         F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) {
7102       auto *GA = llvm::GlobalAlias::create("__main_void", F);
7103       GA->setVisibility(llvm::GlobalValue::HiddenVisibility);
7104     }
7105   }
7106 }
7107 
7108 /// Turns the given pointer into a constant.
7109 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
7110                                           const void *Ptr) {
7111   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
7112   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
7113   return llvm::ConstantInt::get(i64, PtrInt);
7114 }
7115 
7116 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
7117                                    llvm::NamedMDNode *&GlobalMetadata,
7118                                    GlobalDecl D,
7119                                    llvm::GlobalValue *Addr) {
7120   if (!GlobalMetadata)
7121     GlobalMetadata =
7122       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
7123 
7124   // TODO: should we report variant information for ctors/dtors?
7125   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
7126                            llvm::ConstantAsMetadata::get(GetPointerConstant(
7127                                CGM.getLLVMContext(), D.getDecl()))};
7128   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
7129 }
7130 
7131 bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
7132                                                  llvm::GlobalValue *CppFunc) {
7133   // Store the list of ifuncs we need to replace uses in.
7134   llvm::SmallVector<llvm::GlobalIFunc *> IFuncs;
7135   // List of ConstantExprs that we should be able to delete when we're done
7136   // here.
7137   llvm::SmallVector<llvm::ConstantExpr *> CEs;
7138 
7139   // It isn't valid to replace the extern-C ifuncs if all we find is itself!
7140   if (Elem == CppFunc)
7141     return false;
7142 
7143   // First make sure that all users of this are ifuncs (or ifuncs via a
7144   // bitcast), and collect the list of ifuncs and CEs so we can work on them
7145   // later.
7146   for (llvm::User *User : Elem->users()) {
7147     // Users can either be a bitcast ConstExpr that is used by the ifuncs, OR an
7148     // ifunc directly. In any other case, just give up, as we don't know what we
7149     // could break by changing those.
7150     if (auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) {
7151       if (ConstExpr->getOpcode() != llvm::Instruction::BitCast)
7152         return false;
7153 
7154       for (llvm::User *CEUser : ConstExpr->users()) {
7155         if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) {
7156           IFuncs.push_back(IFunc);
7157         } else {
7158           return false;
7159         }
7160       }
7161       CEs.push_back(ConstExpr);
7162     } else if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) {
7163       IFuncs.push_back(IFunc);
7164     } else {
7165       // This user is one we don't know how to handle, so fail redirection. This
7166       // will result in an ifunc retaining a resolver name that will ultimately
7167       // fail to be resolved to a defined function.
7168       return false;
7169     }
7170   }
7171 
7172   // Now we know this is a valid case where we can do this alias replacement, we
7173   // need to remove all of the references to Elem (and the bitcasts!) so we can
7174   // delete it.
7175   for (llvm::GlobalIFunc *IFunc : IFuncs)
7176     IFunc->setResolver(nullptr);
7177   for (llvm::ConstantExpr *ConstExpr : CEs)
7178     ConstExpr->destroyConstant();
7179 
7180   // We should now be out of uses for the 'old' version of this function, so we
7181   // can erase it as well.
7182   Elem->eraseFromParent();
7183 
7184   for (llvm::GlobalIFunc *IFunc : IFuncs) {
7185     // The type of the resolver is always just a function-type that returns the
7186     // type of the IFunc, so create that here. If the type of the actual
7187     // resolver doesn't match, it just gets bitcast to the right thing.
7188     auto *ResolverTy =
7189         llvm::FunctionType::get(IFunc->getType(), /*isVarArg*/ false);
7190     llvm::Constant *Resolver = GetOrCreateLLVMFunction(
7191         CppFunc->getName(), ResolverTy, {}, /*ForVTable*/ false);
7192     IFunc->setResolver(Resolver);
7193   }
7194   return true;
7195 }
7196 
7197 /// For each function which is declared within an extern "C" region and marked
7198 /// as 'used', but has internal linkage, create an alias from the unmangled
7199 /// name to the mangled name if possible. People expect to be able to refer
7200 /// to such functions with an unmangled name from inline assembly within the
7201 /// same translation unit.
7202 void CodeGenModule::EmitStaticExternCAliases() {
7203   if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
7204     return;
7205   for (auto &I : StaticExternCValues) {
7206     IdentifierInfo *Name = I.first;
7207     llvm::GlobalValue *Val = I.second;
7208 
7209     // If Val is null, that implies there were multiple declarations that each
7210     // had a claim to the unmangled name. In this case, generation of the alias
7211     // is suppressed. See CodeGenModule::MaybeHandleStaticInExternC.
7212     if (!Val)
7213       break;
7214 
7215     llvm::GlobalValue *ExistingElem =
7216         getModule().getNamedValue(Name->getName());
7217 
7218     // If there is either not something already by this name, or we were able to
7219     // replace all uses from IFuncs, create the alias.
7220     if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val))
7221       addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
7222   }
7223 }
7224 
7225 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
7226                                              GlobalDecl &Result) const {
7227   auto Res = Manglings.find(MangledName);
7228   if (Res == Manglings.end())
7229     return false;
7230   Result = Res->getValue();
7231   return true;
7232 }
7233 
7234 /// Emits metadata nodes associating all the global values in the
7235 /// current module with the Decls they came from.  This is useful for
7236 /// projects using IR gen as a subroutine.
7237 ///
7238 /// Since there's currently no way to associate an MDNode directly
7239 /// with an llvm::GlobalValue, we create a global named metadata
7240 /// with the name 'clang.global.decl.ptrs'.
7241 void CodeGenModule::EmitDeclMetadata() {
7242   llvm::NamedMDNode *GlobalMetadata = nullptr;
7243 
7244   for (auto &I : MangledDeclNames) {
7245     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
7246     // Some mangled names don't necessarily have an associated GlobalValue
7247     // in this module, e.g. if we mangled it for DebugInfo.
7248     if (Addr)
7249       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
7250   }
7251 }
7252 
7253 /// Emits metadata nodes for all the local variables in the current
7254 /// function.
7255 void CodeGenFunction::EmitDeclMetadata() {
7256   if (LocalDeclMap.empty()) return;
7257 
7258   llvm::LLVMContext &Context = getLLVMContext();
7259 
7260   // Find the unique metadata ID for this name.
7261   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
7262 
7263   llvm::NamedMDNode *GlobalMetadata = nullptr;
7264 
7265   for (auto &I : LocalDeclMap) {
7266     const Decl *D = I.first;
7267     llvm::Value *Addr = I.second.getPointer();
7268     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
7269       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
7270       Alloca->setMetadata(
7271           DeclPtrKind, llvm::MDNode::get(
7272                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
7273     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
7274       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
7275       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
7276     }
7277   }
7278 }
7279 
7280 void CodeGenModule::EmitVersionIdentMetadata() {
7281   llvm::NamedMDNode *IdentMetadata =
7282     TheModule.getOrInsertNamedMetadata("llvm.ident");
7283   std::string Version = getClangFullVersion();
7284   llvm::LLVMContext &Ctx = TheModule.getContext();
7285 
7286   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
7287   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
7288 }
7289 
7290 void CodeGenModule::EmitCommandLineMetadata() {
7291   llvm::NamedMDNode *CommandLineMetadata =
7292     TheModule.getOrInsertNamedMetadata("llvm.commandline");
7293   std::string CommandLine = getCodeGenOpts().RecordCommandLine;
7294   llvm::LLVMContext &Ctx = TheModule.getContext();
7295 
7296   llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
7297   CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
7298 }
7299 
7300 void CodeGenModule::EmitCoverageFile() {
7301   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
7302   if (!CUNode)
7303     return;
7304 
7305   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
7306   llvm::LLVMContext &Ctx = TheModule.getContext();
7307   auto *CoverageDataFile =
7308       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
7309   auto *CoverageNotesFile =
7310       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
7311   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
7312     llvm::MDNode *CU = CUNode->getOperand(i);
7313     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
7314     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
7315   }
7316 }
7317 
7318 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
7319                                                        bool ForEH) {
7320   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
7321   // FIXME: should we even be calling this method if RTTI is disabled
7322   // and it's not for EH?
7323   if (!shouldEmitRTTI(ForEH))
7324     return llvm::Constant::getNullValue(GlobalsInt8PtrTy);
7325 
7326   if (ForEH && Ty->isObjCObjectPointerType() &&
7327       LangOpts.ObjCRuntime.isGNUFamily())
7328     return ObjCRuntime->GetEHType(Ty);
7329 
7330   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
7331 }
7332 
7333 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
7334   // Do not emit threadprivates in simd-only mode.
7335   if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
7336     return;
7337   for (auto RefExpr : D->varlists()) {
7338     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
7339     bool PerformInit =
7340         VD->getAnyInitializer() &&
7341         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
7342                                                         /*ForRef=*/false);
7343 
7344     Address Addr(GetAddrOfGlobalVar(VD),
7345                  getTypes().ConvertTypeForMem(VD->getType()),
7346                  getContext().getDeclAlign(VD));
7347     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
7348             VD, Addr, RefExpr->getBeginLoc(), PerformInit))
7349       CXXGlobalInits.push_back(InitFunction);
7350   }
7351 }
7352 
7353 llvm::Metadata *
7354 CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
7355                                             StringRef Suffix) {
7356   if (auto *FnType = T->getAs<FunctionProtoType>())
7357     T = getContext().getFunctionType(
7358         FnType->getReturnType(), FnType->getParamTypes(),
7359         FnType->getExtProtoInfo().withExceptionSpec(EST_None));
7360 
7361   llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
7362   if (InternalId)
7363     return InternalId;
7364 
7365   if (isExternallyVisible(T->getLinkage())) {
7366     std::string OutName;
7367     llvm::raw_string_ostream Out(OutName);
7368     getCXXABI().getMangleContext().mangleCanonicalTypeName(
7369         T, Out, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers);
7370 
7371     if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers)
7372       Out << ".normalized";
7373 
7374     Out << Suffix;
7375 
7376     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
7377   } else {
7378     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
7379                                            llvm::ArrayRef<llvm::Metadata *>());
7380   }
7381 
7382   return InternalId;
7383 }
7384 
7385 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
7386   return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
7387 }
7388 
7389 llvm::Metadata *
7390 CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
7391   return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
7392 }
7393 
7394 // Generalize pointer types to a void pointer with the qualifiers of the
7395 // originally pointed-to type, e.g. 'const char *' and 'char * const *'
7396 // generalize to 'const void *' while 'char *' and 'const char **' generalize to
7397 // 'void *'.
7398 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
7399   if (!Ty->isPointerType())
7400     return Ty;
7401 
7402   return Ctx.getPointerType(
7403       QualType(Ctx.VoidTy).withCVRQualifiers(
7404           Ty->getPointeeType().getCVRQualifiers()));
7405 }
7406 
7407 // Apply type generalization to a FunctionType's return and argument types
7408 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
7409   if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
7410     SmallVector<QualType, 8> GeneralizedParams;
7411     for (auto &Param : FnType->param_types())
7412       GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
7413 
7414     return Ctx.getFunctionType(
7415         GeneralizeType(Ctx, FnType->getReturnType()),
7416         GeneralizedParams, FnType->getExtProtoInfo());
7417   }
7418 
7419   if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
7420     return Ctx.getFunctionNoProtoType(
7421         GeneralizeType(Ctx, FnType->getReturnType()));
7422 
7423   llvm_unreachable("Encountered unknown FunctionType");
7424 }
7425 
7426 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
7427   return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
7428                                       GeneralizedMetadataIdMap, ".generalized");
7429 }
7430 
7431 /// Returns whether this module needs the "all-vtables" type identifier.
7432 bool CodeGenModule::NeedAllVtablesTypeId() const {
7433   // Returns true if at least one of vtable-based CFI checkers is enabled and
7434   // is not in the trapping mode.
7435   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
7436            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
7437           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
7438            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
7439           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
7440            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
7441           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
7442            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
7443 }
7444 
7445 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
7446                                           CharUnits Offset,
7447                                           const CXXRecordDecl *RD) {
7448   llvm::Metadata *MD =
7449       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
7450   VTable->addTypeMetadata(Offset.getQuantity(), MD);
7451 
7452   if (CodeGenOpts.SanitizeCfiCrossDso)
7453     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
7454       VTable->addTypeMetadata(Offset.getQuantity(),
7455                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
7456 
7457   if (NeedAllVtablesTypeId()) {
7458     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
7459     VTable->addTypeMetadata(Offset.getQuantity(), MD);
7460   }
7461 }
7462 
7463 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
7464   if (!SanStats)
7465     SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule());
7466 
7467   return *SanStats;
7468 }
7469 
7470 llvm::Value *
7471 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
7472                                                   CodeGenFunction &CGF) {
7473   llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
7474   auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
7475   auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
7476   auto *Call = CGF.EmitRuntimeCall(
7477       CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C});
7478   return Call;
7479 }
7480 
7481 CharUnits CodeGenModule::getNaturalPointeeTypeAlignment(
7482     QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) {
7483   return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
7484                                  /* forPointeeType= */ true);
7485 }
7486 
7487 CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T,
7488                                                  LValueBaseInfo *BaseInfo,
7489                                                  TBAAAccessInfo *TBAAInfo,
7490                                                  bool forPointeeType) {
7491   if (TBAAInfo)
7492     *TBAAInfo = getTBAAAccessInfo(T);
7493 
7494   // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But
7495   // that doesn't return the information we need to compute BaseInfo.
7496 
7497   // Honor alignment typedef attributes even on incomplete types.
7498   // We also honor them straight for C++ class types, even as pointees;
7499   // there's an expressivity gap here.
7500   if (auto TT = T->getAs<TypedefType>()) {
7501     if (auto Align = TT->getDecl()->getMaxAlignment()) {
7502       if (BaseInfo)
7503         *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
7504       return getContext().toCharUnitsFromBits(Align);
7505     }
7506   }
7507 
7508   bool AlignForArray = T->isArrayType();
7509 
7510   // Analyze the base element type, so we don't get confused by incomplete
7511   // array types.
7512   T = getContext().getBaseElementType(T);
7513 
7514   if (T->isIncompleteType()) {
7515     // We could try to replicate the logic from
7516     // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the
7517     // type is incomplete, so it's impossible to test. We could try to reuse
7518     // getTypeAlignIfKnown, but that doesn't return the information we need
7519     // to set BaseInfo.  So just ignore the possibility that the alignment is
7520     // greater than one.
7521     if (BaseInfo)
7522       *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
7523     return CharUnits::One();
7524   }
7525 
7526   if (BaseInfo)
7527     *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
7528 
7529   CharUnits Alignment;
7530   const CXXRecordDecl *RD;
7531   if (T.getQualifiers().hasUnaligned()) {
7532     Alignment = CharUnits::One();
7533   } else if (forPointeeType && !AlignForArray &&
7534              (RD = T->getAsCXXRecordDecl())) {
7535     // For C++ class pointees, we don't know whether we're pointing at a
7536     // base or a complete object, so we generally need to use the
7537     // non-virtual alignment.
7538     Alignment = getClassPointerAlignment(RD);
7539   } else {
7540     Alignment = getContext().getTypeAlignInChars(T);
7541   }
7542 
7543   // Cap to the global maximum type alignment unless the alignment
7544   // was somehow explicit on the type.
7545   if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
7546     if (Alignment.getQuantity() > MaxAlign &&
7547         !getContext().isAlignmentRequired(T))
7548       Alignment = CharUnits::fromQuantity(MaxAlign);
7549   }
7550   return Alignment;
7551 }
7552 
7553 bool CodeGenModule::stopAutoInit() {
7554   unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter;
7555   if (StopAfter) {
7556     // This number is positive only when -ftrivial-auto-var-init-stop-after=* is
7557     // used
7558     if (NumAutoVarInit >= StopAfter) {
7559       return true;
7560     }
7561     if (!NumAutoVarInit) {
7562       unsigned DiagID = getDiags().getCustomDiagID(
7563           DiagnosticsEngine::Warning,
7564           "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
7565           "number of times ftrivial-auto-var-init=%1 gets applied.");
7566       getDiags().Report(DiagID)
7567           << StopAfter
7568           << (getContext().getLangOpts().getTrivialAutoVarInit() ==
7569                       LangOptions::TrivialAutoVarInitKind::Zero
7570                   ? "zero"
7571                   : "pattern");
7572     }
7573     ++NumAutoVarInit;
7574   }
7575   return false;
7576 }
7577 
7578 void CodeGenModule::printPostfixForExternalizedDecl(llvm::raw_ostream &OS,
7579                                                     const Decl *D) const {
7580   // ptxas does not allow '.' in symbol names. On the other hand, HIP prefers
7581   // postfix beginning with '.' since the symbol name can be demangled.
7582   if (LangOpts.HIP)
7583     OS << (isa<VarDecl>(D) ? ".static." : ".intern.");
7584   else
7585     OS << (isa<VarDecl>(D) ? "__static__" : "__intern__");
7586 
7587   // If the CUID is not specified we try to generate a unique postfix.
7588   if (getLangOpts().CUID.empty()) {
7589     SourceManager &SM = getContext().getSourceManager();
7590     PresumedLoc PLoc = SM.getPresumedLoc(D->getLocation());
7591     assert(PLoc.isValid() && "Source location is expected to be valid.");
7592 
7593     // Get the hash of the user defined macros.
7594     llvm::MD5 Hash;
7595     llvm::MD5::MD5Result Result;
7596     for (const auto &Arg : PreprocessorOpts.Macros)
7597       Hash.update(Arg.first);
7598     Hash.final(Result);
7599 
7600     // Get the UniqueID for the file containing the decl.
7601     llvm::sys::fs::UniqueID ID;
7602     if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) {
7603       PLoc = SM.getPresumedLoc(D->getLocation(), /*UseLineDirectives=*/false);
7604       assert(PLoc.isValid() && "Source location is expected to be valid.");
7605       if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
7606         SM.getDiagnostics().Report(diag::err_cannot_open_file)
7607             << PLoc.getFilename() << EC.message();
7608     }
7609     OS << llvm::format("%x", ID.getFile()) << llvm::format("%x", ID.getDevice())
7610        << "_" << llvm::utohexstr(Result.low(), /*LowerCase=*/true, /*Width=*/8);
7611   } else {
7612     OS << getContext().getCUIDHash();
7613   }
7614 }
7615 
7616 void CodeGenModule::moveLazyEmissionStates(CodeGenModule *NewBuilder) {
7617   assert(DeferredDeclsToEmit.empty() &&
7618          "Should have emitted all decls deferred to emit.");
7619   assert(NewBuilder->DeferredDecls.empty() &&
7620          "Newly created module should not have deferred decls");
7621   NewBuilder->DeferredDecls = std::move(DeferredDecls);
7622   assert(EmittedDeferredDecls.empty() &&
7623          "Still have (unmerged) EmittedDeferredDecls deferred decls");
7624 
7625   assert(NewBuilder->DeferredVTables.empty() &&
7626          "Newly created module should not have deferred vtables");
7627   NewBuilder->DeferredVTables = std::move(DeferredVTables);
7628 
7629   assert(NewBuilder->MangledDeclNames.empty() &&
7630          "Newly created module should not have mangled decl names");
7631   assert(NewBuilder->Manglings.empty() &&
7632          "Newly created module should not have manglings");
7633   NewBuilder->Manglings = std::move(Manglings);
7634 
7635   NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
7636 
7637   NewBuilder->TBAA = std::move(TBAA);
7638 
7639   NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx);
7640 }
7641