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