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