xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision 1d0bd8e51be2627f79bede54735c38b917ea04ee)
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   return getLLVMLinkageForDeclarator(D, Linkage);
1974 }
1975 
1976 llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
1977   llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
1978   if (!MDS) return nullptr;
1979 
1980   return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
1981 }
1982 
1983 llvm::ConstantInt *CodeGenModule::CreateKCFITypeId(QualType T) {
1984   if (auto *FnType = T->getAs<FunctionProtoType>())
1985     T = getContext().getFunctionType(
1986         FnType->getReturnType(), FnType->getParamTypes(),
1987         FnType->getExtProtoInfo().withExceptionSpec(EST_None));
1988 
1989   std::string OutName;
1990   llvm::raw_string_ostream Out(OutName);
1991   getCXXABI().getMangleContext().mangleTypeName(
1992       T, Out, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers);
1993 
1994   if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers)
1995     Out << ".normalized";
1996 
1997   return llvm::ConstantInt::get(Int32Ty,
1998                                 static_cast<uint32_t>(llvm::xxHash64(OutName)));
1999 }
2000 
2001 void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
2002                                               const CGFunctionInfo &Info,
2003                                               llvm::Function *F, bool IsThunk) {
2004   unsigned CallingConv;
2005   llvm::AttributeList PAL;
2006   ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv,
2007                          /*AttrOnCallSite=*/false, IsThunk);
2008   F->setAttributes(PAL);
2009   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
2010 }
2011 
2012 static void removeImageAccessQualifier(std::string& TyName) {
2013   std::string ReadOnlyQual("__read_only");
2014   std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
2015   if (ReadOnlyPos != std::string::npos)
2016     // "+ 1" for the space after access qualifier.
2017     TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
2018   else {
2019     std::string WriteOnlyQual("__write_only");
2020     std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
2021     if (WriteOnlyPos != std::string::npos)
2022       TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
2023     else {
2024       std::string ReadWriteQual("__read_write");
2025       std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
2026       if (ReadWritePos != std::string::npos)
2027         TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
2028     }
2029   }
2030 }
2031 
2032 // Returns the address space id that should be produced to the
2033 // kernel_arg_addr_space metadata. This is always fixed to the ids
2034 // as specified in the SPIR 2.0 specification in order to differentiate
2035 // for example in clGetKernelArgInfo() implementation between the address
2036 // spaces with targets without unique mapping to the OpenCL address spaces
2037 // (basically all single AS CPUs).
2038 static unsigned ArgInfoAddressSpace(LangAS AS) {
2039   switch (AS) {
2040   case LangAS::opencl_global:
2041     return 1;
2042   case LangAS::opencl_constant:
2043     return 2;
2044   case LangAS::opencl_local:
2045     return 3;
2046   case LangAS::opencl_generic:
2047     return 4; // Not in SPIR 2.0 specs.
2048   case LangAS::opencl_global_device:
2049     return 5;
2050   case LangAS::opencl_global_host:
2051     return 6;
2052   default:
2053     return 0; // Assume private.
2054   }
2055 }
2056 
2057 void CodeGenModule::GenKernelArgMetadata(llvm::Function *Fn,
2058                                          const FunctionDecl *FD,
2059                                          CodeGenFunction *CGF) {
2060   assert(((FD && CGF) || (!FD && !CGF)) &&
2061          "Incorrect use - FD and CGF should either be both null or not!");
2062   // Create MDNodes that represent the kernel arg metadata.
2063   // Each MDNode is a list in the form of "key", N number of values which is
2064   // the same number of values as their are kernel arguments.
2065 
2066   const PrintingPolicy &Policy = Context.getPrintingPolicy();
2067 
2068   // MDNode for the kernel argument address space qualifiers.
2069   SmallVector<llvm::Metadata *, 8> addressQuals;
2070 
2071   // MDNode for the kernel argument access qualifiers (images only).
2072   SmallVector<llvm::Metadata *, 8> accessQuals;
2073 
2074   // MDNode for the kernel argument type names.
2075   SmallVector<llvm::Metadata *, 8> argTypeNames;
2076 
2077   // MDNode for the kernel argument base type names.
2078   SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
2079 
2080   // MDNode for the kernel argument type qualifiers.
2081   SmallVector<llvm::Metadata *, 8> argTypeQuals;
2082 
2083   // MDNode for the kernel argument names.
2084   SmallVector<llvm::Metadata *, 8> argNames;
2085 
2086   if (FD && CGF)
2087     for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
2088       const ParmVarDecl *parm = FD->getParamDecl(i);
2089       // Get argument name.
2090       argNames.push_back(llvm::MDString::get(VMContext, parm->getName()));
2091 
2092       if (!getLangOpts().OpenCL)
2093         continue;
2094       QualType ty = parm->getType();
2095       std::string typeQuals;
2096 
2097       // Get image and pipe access qualifier:
2098       if (ty->isImageType() || ty->isPipeType()) {
2099         const Decl *PDecl = parm;
2100         if (const auto *TD = ty->getAs<TypedefType>())
2101           PDecl = TD->getDecl();
2102         const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
2103         if (A && A->isWriteOnly())
2104           accessQuals.push_back(llvm::MDString::get(VMContext, "write_only"));
2105         else if (A && A->isReadWrite())
2106           accessQuals.push_back(llvm::MDString::get(VMContext, "read_write"));
2107         else
2108           accessQuals.push_back(llvm::MDString::get(VMContext, "read_only"));
2109       } else
2110         accessQuals.push_back(llvm::MDString::get(VMContext, "none"));
2111 
2112       auto getTypeSpelling = [&](QualType Ty) {
2113         auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
2114 
2115         if (Ty.isCanonical()) {
2116           StringRef typeNameRef = typeName;
2117           // Turn "unsigned type" to "utype"
2118           if (typeNameRef.consume_front("unsigned "))
2119             return std::string("u") + typeNameRef.str();
2120           if (typeNameRef.consume_front("signed "))
2121             return typeNameRef.str();
2122         }
2123 
2124         return typeName;
2125       };
2126 
2127       if (ty->isPointerType()) {
2128         QualType pointeeTy = ty->getPointeeType();
2129 
2130         // Get address qualifier.
2131         addressQuals.push_back(
2132             llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(
2133                 ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
2134 
2135         // Get argument type name.
2136         std::string typeName = getTypeSpelling(pointeeTy) + "*";
2137         std::string baseTypeName =
2138             getTypeSpelling(pointeeTy.getCanonicalType()) + "*";
2139         argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2140         argBaseTypeNames.push_back(
2141             llvm::MDString::get(VMContext, baseTypeName));
2142 
2143         // Get argument type qualifiers:
2144         if (ty.isRestrictQualified())
2145           typeQuals = "restrict";
2146         if (pointeeTy.isConstQualified() ||
2147             (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
2148           typeQuals += typeQuals.empty() ? "const" : " const";
2149         if (pointeeTy.isVolatileQualified())
2150           typeQuals += typeQuals.empty() ? "volatile" : " volatile";
2151       } else {
2152         uint32_t AddrSpc = 0;
2153         bool isPipe = ty->isPipeType();
2154         if (ty->isImageType() || isPipe)
2155           AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
2156 
2157         addressQuals.push_back(
2158             llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc)));
2159 
2160         // Get argument type name.
2161         ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty;
2162         std::string typeName = getTypeSpelling(ty);
2163         std::string baseTypeName = getTypeSpelling(ty.getCanonicalType());
2164 
2165         // Remove access qualifiers on images
2166         // (as they are inseparable from type in clang implementation,
2167         // but OpenCL spec provides a special query to get access qualifier
2168         // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
2169         if (ty->isImageType()) {
2170           removeImageAccessQualifier(typeName);
2171           removeImageAccessQualifier(baseTypeName);
2172         }
2173 
2174         argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2175         argBaseTypeNames.push_back(
2176             llvm::MDString::get(VMContext, baseTypeName));
2177 
2178         if (isPipe)
2179           typeQuals = "pipe";
2180       }
2181       argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
2182     }
2183 
2184   if (getLangOpts().OpenCL) {
2185     Fn->setMetadata("kernel_arg_addr_space",
2186                     llvm::MDNode::get(VMContext, addressQuals));
2187     Fn->setMetadata("kernel_arg_access_qual",
2188                     llvm::MDNode::get(VMContext, accessQuals));
2189     Fn->setMetadata("kernel_arg_type",
2190                     llvm::MDNode::get(VMContext, argTypeNames));
2191     Fn->setMetadata("kernel_arg_base_type",
2192                     llvm::MDNode::get(VMContext, argBaseTypeNames));
2193     Fn->setMetadata("kernel_arg_type_qual",
2194                     llvm::MDNode::get(VMContext, argTypeQuals));
2195   }
2196   if (getCodeGenOpts().EmitOpenCLArgMetadata ||
2197       getCodeGenOpts().HIPSaveKernelArgName)
2198     Fn->setMetadata("kernel_arg_name",
2199                     llvm::MDNode::get(VMContext, argNames));
2200 }
2201 
2202 /// Determines whether the language options require us to model
2203 /// unwind exceptions.  We treat -fexceptions as mandating this
2204 /// except under the fragile ObjC ABI with only ObjC exceptions
2205 /// enabled.  This means, for example, that C with -fexceptions
2206 /// enables this.
2207 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
2208   // If exceptions are completely disabled, obviously this is false.
2209   if (!LangOpts.Exceptions) return false;
2210 
2211   // If C++ exceptions are enabled, this is true.
2212   if (LangOpts.CXXExceptions) return true;
2213 
2214   // If ObjC exceptions are enabled, this depends on the ABI.
2215   if (LangOpts.ObjCExceptions) {
2216     return LangOpts.ObjCRuntime.hasUnwindExceptions();
2217   }
2218 
2219   return true;
2220 }
2221 
2222 static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
2223                                                       const CXXMethodDecl *MD) {
2224   // Check that the type metadata can ever actually be used by a call.
2225   if (!CGM.getCodeGenOpts().LTOUnit ||
2226       !CGM.HasHiddenLTOVisibility(MD->getParent()))
2227     return false;
2228 
2229   // Only functions whose address can be taken with a member function pointer
2230   // need this sort of type metadata.
2231   return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
2232          !isa<CXXDestructorDecl>(MD);
2233 }
2234 
2235 SmallVector<const CXXRecordDecl *, 0>
2236 CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
2237   llvm::SetVector<const CXXRecordDecl *> MostBases;
2238 
2239   std::function<void (const CXXRecordDecl *)> CollectMostBases;
2240   CollectMostBases = [&](const CXXRecordDecl *RD) {
2241     if (RD->getNumBases() == 0)
2242       MostBases.insert(RD);
2243     for (const CXXBaseSpecifier &B : RD->bases())
2244       CollectMostBases(B.getType()->getAsCXXRecordDecl());
2245   };
2246   CollectMostBases(RD);
2247   return MostBases.takeVector();
2248 }
2249 
2250 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
2251                                                            llvm::Function *F) {
2252   llvm::AttrBuilder B(F->getContext());
2253 
2254   if ((!D || !D->hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables)
2255     B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
2256 
2257   if (CodeGenOpts.StackClashProtector)
2258     B.addAttribute("probe-stack", "inline-asm");
2259 
2260   if (!hasUnwindExceptions(LangOpts))
2261     B.addAttribute(llvm::Attribute::NoUnwind);
2262 
2263   if (D && D->hasAttr<NoStackProtectorAttr>())
2264     ; // Do nothing.
2265   else if (D && D->hasAttr<StrictGuardStackCheckAttr>() &&
2266            LangOpts.getStackProtector() == LangOptions::SSPOn)
2267     B.addAttribute(llvm::Attribute::StackProtectStrong);
2268   else if (LangOpts.getStackProtector() == LangOptions::SSPOn)
2269     B.addAttribute(llvm::Attribute::StackProtect);
2270   else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
2271     B.addAttribute(llvm::Attribute::StackProtectStrong);
2272   else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
2273     B.addAttribute(llvm::Attribute::StackProtectReq);
2274 
2275   if (!D) {
2276     // If we don't have a declaration to control inlining, the function isn't
2277     // explicitly marked as alwaysinline for semantic reasons, and inlining is
2278     // disabled, mark the function as noinline.
2279     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
2280         CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
2281       B.addAttribute(llvm::Attribute::NoInline);
2282 
2283     F->addFnAttrs(B);
2284     return;
2285   }
2286 
2287   // Handle SME attributes that apply to function definitions,
2288   // rather than to function prototypes.
2289   if (D->hasAttr<ArmLocallyStreamingAttr>())
2290     B.addAttribute("aarch64_pstate_sm_body");
2291 
2292   if (D->hasAttr<ArmNewZAAttr>())
2293     B.addAttribute("aarch64_pstate_za_new");
2294 
2295   // Track whether we need to add the optnone LLVM attribute,
2296   // starting with the default for this optimization level.
2297   bool ShouldAddOptNone =
2298       !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
2299   // We can't add optnone in the following cases, it won't pass the verifier.
2300   ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
2301   ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
2302 
2303   // Add optnone, but do so only if the function isn't always_inline.
2304   if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) &&
2305       !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2306     B.addAttribute(llvm::Attribute::OptimizeNone);
2307 
2308     // OptimizeNone implies noinline; we should not be inlining such functions.
2309     B.addAttribute(llvm::Attribute::NoInline);
2310 
2311     // We still need to handle naked functions even though optnone subsumes
2312     // much of their semantics.
2313     if (D->hasAttr<NakedAttr>())
2314       B.addAttribute(llvm::Attribute::Naked);
2315 
2316     // OptimizeNone wins over OptimizeForSize and MinSize.
2317     F->removeFnAttr(llvm::Attribute::OptimizeForSize);
2318     F->removeFnAttr(llvm::Attribute::MinSize);
2319   } else if (D->hasAttr<NakedAttr>()) {
2320     // Naked implies noinline: we should not be inlining such functions.
2321     B.addAttribute(llvm::Attribute::Naked);
2322     B.addAttribute(llvm::Attribute::NoInline);
2323   } else if (D->hasAttr<NoDuplicateAttr>()) {
2324     B.addAttribute(llvm::Attribute::NoDuplicate);
2325   } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2326     // Add noinline if the function isn't always_inline.
2327     B.addAttribute(llvm::Attribute::NoInline);
2328   } else if (D->hasAttr<AlwaysInlineAttr>() &&
2329              !F->hasFnAttribute(llvm::Attribute::NoInline)) {
2330     // (noinline wins over always_inline, and we can't specify both in IR)
2331     B.addAttribute(llvm::Attribute::AlwaysInline);
2332   } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
2333     // If we're not inlining, then force everything that isn't always_inline to
2334     // carry an explicit noinline attribute.
2335     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
2336       B.addAttribute(llvm::Attribute::NoInline);
2337   } else {
2338     // Otherwise, propagate the inline hint attribute and potentially use its
2339     // absence to mark things as noinline.
2340     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
2341       // Search function and template pattern redeclarations for inline.
2342       auto CheckForInline = [](const FunctionDecl *FD) {
2343         auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
2344           return Redecl->isInlineSpecified();
2345         };
2346         if (any_of(FD->redecls(), CheckRedeclForInline))
2347           return true;
2348         const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
2349         if (!Pattern)
2350           return false;
2351         return any_of(Pattern->redecls(), CheckRedeclForInline);
2352       };
2353       if (CheckForInline(FD)) {
2354         B.addAttribute(llvm::Attribute::InlineHint);
2355       } else if (CodeGenOpts.getInlining() ==
2356                      CodeGenOptions::OnlyHintInlining &&
2357                  !FD->isInlined() &&
2358                  !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2359         B.addAttribute(llvm::Attribute::NoInline);
2360       }
2361     }
2362   }
2363 
2364   // Add other optimization related attributes if we are optimizing this
2365   // function.
2366   if (!D->hasAttr<OptimizeNoneAttr>()) {
2367     if (D->hasAttr<ColdAttr>()) {
2368       if (!ShouldAddOptNone)
2369         B.addAttribute(llvm::Attribute::OptimizeForSize);
2370       B.addAttribute(llvm::Attribute::Cold);
2371     }
2372     if (D->hasAttr<HotAttr>())
2373       B.addAttribute(llvm::Attribute::Hot);
2374     if (D->hasAttr<MinSizeAttr>())
2375       B.addAttribute(llvm::Attribute::MinSize);
2376   }
2377 
2378   F->addFnAttrs(B);
2379 
2380   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
2381   if (alignment)
2382     F->setAlignment(llvm::Align(alignment));
2383 
2384   if (!D->hasAttr<AlignedAttr>())
2385     if (LangOpts.FunctionAlignment)
2386       F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
2387 
2388   // Some C++ ABIs require 2-byte alignment for member functions, in order to
2389   // reserve a bit for differentiating between virtual and non-virtual member
2390   // functions. If the current target's C++ ABI requires this and this is a
2391   // member function, set its alignment accordingly.
2392   if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
2393     if (F->getPointerAlignment(getDataLayout()) < 2 && isa<CXXMethodDecl>(D))
2394       F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
2395   }
2396 
2397   // In the cross-dso CFI mode with canonical jump tables, we want !type
2398   // attributes on definitions only.
2399   if (CodeGenOpts.SanitizeCfiCrossDso &&
2400       CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
2401     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
2402       // Skip available_externally functions. They won't be codegen'ed in the
2403       // current module anyway.
2404       if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally)
2405         CreateFunctionTypeMetadataForIcall(FD, F);
2406     }
2407   }
2408 
2409   // Emit type metadata on member functions for member function pointer checks.
2410   // These are only ever necessary on definitions; we're guaranteed that the
2411   // definition will be present in the LTO unit as a result of LTO visibility.
2412   auto *MD = dyn_cast<CXXMethodDecl>(D);
2413   if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
2414     for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
2415       llvm::Metadata *Id =
2416           CreateMetadataIdentifierForType(Context.getMemberPointerType(
2417               MD->getType(), Context.getRecordType(Base).getTypePtr()));
2418       F->addTypeMetadata(0, Id);
2419     }
2420   }
2421 }
2422 
2423 void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
2424   const Decl *D = GD.getDecl();
2425   if (isa_and_nonnull<NamedDecl>(D))
2426     setGVProperties(GV, GD);
2427   else
2428     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
2429 
2430   if (D && D->hasAttr<UsedAttr>())
2431     addUsedOrCompilerUsedGlobal(GV);
2432 
2433   if (const auto *VD = dyn_cast_if_present<VarDecl>(D);
2434       VD &&
2435       ((CodeGenOpts.KeepPersistentStorageVariables &&
2436         (VD->getStorageDuration() == SD_Static ||
2437          VD->getStorageDuration() == SD_Thread)) ||
2438        (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static &&
2439         VD->getType().isConstQualified())))
2440     addUsedOrCompilerUsedGlobal(GV);
2441 }
2442 
2443 bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
2444                                                 llvm::AttrBuilder &Attrs,
2445                                                 bool SetTargetFeatures) {
2446   // Add target-cpu and target-features attributes to functions. If
2447   // we have a decl for the function and it has a target attribute then
2448   // parse that and add it to the feature set.
2449   StringRef TargetCPU = getTarget().getTargetOpts().CPU;
2450   StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU;
2451   std::vector<std::string> Features;
2452   const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
2453   FD = FD ? FD->getMostRecentDecl() : FD;
2454   const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
2455   const auto *TV = FD ? FD->getAttr<TargetVersionAttr>() : nullptr;
2456   assert((!TD || !TV) && "both target_version and target specified");
2457   const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
2458   const auto *TC = FD ? FD->getAttr<TargetClonesAttr>() : nullptr;
2459   bool AddedAttr = false;
2460   if (TD || TV || SD || TC) {
2461     llvm::StringMap<bool> FeatureMap;
2462     getContext().getFunctionFeatureMap(FeatureMap, GD);
2463 
2464     // Produce the canonical string for this set of features.
2465     for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
2466       Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
2467 
2468     // Now add the target-cpu and target-features to the function.
2469     // While we populated the feature map above, we still need to
2470     // get and parse the target attribute so we can get the cpu for
2471     // the function.
2472     if (TD) {
2473       ParsedTargetAttr ParsedAttr =
2474           Target.parseTargetAttr(TD->getFeaturesStr());
2475       if (!ParsedAttr.CPU.empty() &&
2476           getTarget().isValidCPUName(ParsedAttr.CPU)) {
2477         TargetCPU = ParsedAttr.CPU;
2478         TuneCPU = ""; // Clear the tune CPU.
2479       }
2480       if (!ParsedAttr.Tune.empty() &&
2481           getTarget().isValidCPUName(ParsedAttr.Tune))
2482         TuneCPU = ParsedAttr.Tune;
2483     }
2484 
2485     if (SD) {
2486       // Apply the given CPU name as the 'tune-cpu' so that the optimizer can
2487       // favor this processor.
2488       TuneCPU = SD->getCPUName(GD.getMultiVersionIndex())->getName();
2489     }
2490   } else {
2491     // Otherwise just add the existing target cpu and target features to the
2492     // function.
2493     Features = getTarget().getTargetOpts().Features;
2494   }
2495 
2496   if (!TargetCPU.empty()) {
2497     Attrs.addAttribute("target-cpu", TargetCPU);
2498     AddedAttr = true;
2499   }
2500   if (!TuneCPU.empty()) {
2501     Attrs.addAttribute("tune-cpu", TuneCPU);
2502     AddedAttr = true;
2503   }
2504   if (!Features.empty() && SetTargetFeatures) {
2505     llvm::erase_if(Features, [&](const std::string& F) {
2506        return getTarget().isReadOnlyFeature(F.substr(1));
2507     });
2508     llvm::sort(Features);
2509     Attrs.addAttribute("target-features", llvm::join(Features, ","));
2510     AddedAttr = true;
2511   }
2512 
2513   return AddedAttr;
2514 }
2515 
2516 void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
2517                                           llvm::GlobalObject *GO) {
2518   const Decl *D = GD.getDecl();
2519   SetCommonAttributes(GD, GO);
2520 
2521   if (D) {
2522     if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
2523       if (D->hasAttr<RetainAttr>())
2524         addUsedGlobal(GV);
2525       if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
2526         GV->addAttribute("bss-section", SA->getName());
2527       if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
2528         GV->addAttribute("data-section", SA->getName());
2529       if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
2530         GV->addAttribute("rodata-section", SA->getName());
2531       if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>())
2532         GV->addAttribute("relro-section", SA->getName());
2533     }
2534 
2535     if (auto *F = dyn_cast<llvm::Function>(GO)) {
2536       if (D->hasAttr<RetainAttr>())
2537         addUsedGlobal(F);
2538       if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
2539         if (!D->getAttr<SectionAttr>())
2540           F->addFnAttr("implicit-section-name", SA->getName());
2541 
2542       llvm::AttrBuilder Attrs(F->getContext());
2543       if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
2544         // We know that GetCPUAndFeaturesAttributes will always have the
2545         // newest set, since it has the newest possible FunctionDecl, so the
2546         // new ones should replace the old.
2547         llvm::AttributeMask RemoveAttrs;
2548         RemoveAttrs.addAttribute("target-cpu");
2549         RemoveAttrs.addAttribute("target-features");
2550         RemoveAttrs.addAttribute("tune-cpu");
2551         F->removeFnAttrs(RemoveAttrs);
2552         F->addFnAttrs(Attrs);
2553       }
2554     }
2555 
2556     if (const auto *CSA = D->getAttr<CodeSegAttr>())
2557       GO->setSection(CSA->getName());
2558     else if (const auto *SA = D->getAttr<SectionAttr>())
2559       GO->setSection(SA->getName());
2560   }
2561 
2562   getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
2563 }
2564 
2565 void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
2566                                                   llvm::Function *F,
2567                                                   const CGFunctionInfo &FI) {
2568   const Decl *D = GD.getDecl();
2569   SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false);
2570   SetLLVMFunctionAttributesForDefinition(D, F);
2571 
2572   F->setLinkage(llvm::Function::InternalLinkage);
2573 
2574   setNonAliasAttributes(GD, F);
2575 }
2576 
2577 static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
2578   // Set linkage and visibility in case we never see a definition.
2579   LinkageInfo LV = ND->getLinkageAndVisibility();
2580   // Don't set internal linkage on declarations.
2581   // "extern_weak" is overloaded in LLVM; we probably should have
2582   // separate linkage types for this.
2583   if (isExternallyVisible(LV.getLinkage()) &&
2584       (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
2585     GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2586 }
2587 
2588 void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
2589                                                        llvm::Function *F) {
2590   // Only if we are checking indirect calls.
2591   if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
2592     return;
2593 
2594   // Non-static class methods are handled via vtable or member function pointer
2595   // checks elsewhere.
2596   if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2597     return;
2598 
2599   llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
2600   F->addTypeMetadata(0, MD);
2601   F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
2602 
2603   // Emit a hash-based bit set entry for cross-DSO calls.
2604   if (CodeGenOpts.SanitizeCfiCrossDso)
2605     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
2606       F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
2607 }
2608 
2609 void CodeGenModule::setKCFIType(const FunctionDecl *FD, llvm::Function *F) {
2610   llvm::LLVMContext &Ctx = F->getContext();
2611   llvm::MDBuilder MDB(Ctx);
2612   F->setMetadata(llvm::LLVMContext::MD_kcfi_type,
2613                  llvm::MDNode::get(
2614                      Ctx, MDB.createConstant(CreateKCFITypeId(FD->getType()))));
2615 }
2616 
2617 static bool allowKCFIIdentifier(StringRef Name) {
2618   // KCFI type identifier constants are only necessary for external assembly
2619   // functions, which means it's safe to skip unusual names. Subset of
2620   // MCAsmInfo::isAcceptableChar() and MCAsmInfoXCOFF::isAcceptableChar().
2621   return llvm::all_of(Name, [](const char &C) {
2622     return llvm::isAlnum(C) || C == '_' || C == '.';
2623   });
2624 }
2625 
2626 void CodeGenModule::finalizeKCFITypes() {
2627   llvm::Module &M = getModule();
2628   for (auto &F : M.functions()) {
2629     // Remove KCFI type metadata from non-address-taken local functions.
2630     bool AddressTaken = F.hasAddressTaken();
2631     if (!AddressTaken && F.hasLocalLinkage())
2632       F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type);
2633 
2634     // Generate a constant with the expected KCFI type identifier for all
2635     // address-taken function declarations to support annotating indirectly
2636     // called assembly functions.
2637     if (!AddressTaken || !F.isDeclaration())
2638       continue;
2639 
2640     const llvm::ConstantInt *Type;
2641     if (const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type))
2642       Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0));
2643     else
2644       continue;
2645 
2646     StringRef Name = F.getName();
2647     if (!allowKCFIIdentifier(Name))
2648       continue;
2649 
2650     std::string Asm = (".weak __kcfi_typeid_" + Name + "\n.set __kcfi_typeid_" +
2651                        Name + ", " + Twine(Type->getZExtValue()) + "\n")
2652                           .str();
2653     M.appendModuleInlineAsm(Asm);
2654   }
2655 }
2656 
2657 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
2658                                           bool IsIncompleteFunction,
2659                                           bool IsThunk) {
2660 
2661   if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
2662     // If this is an intrinsic function, set the function's attributes
2663     // to the intrinsic's attributes.
2664     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
2665     return;
2666   }
2667 
2668   const auto *FD = cast<FunctionDecl>(GD.getDecl());
2669 
2670   if (!IsIncompleteFunction)
2671     SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F,
2672                               IsThunk);
2673 
2674   // Add the Returned attribute for "this", except for iOS 5 and earlier
2675   // where substantial code, including the libstdc++ dylib, was compiled with
2676   // GCC and does not actually return "this".
2677   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
2678       !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
2679     assert(!F->arg_empty() &&
2680            F->arg_begin()->getType()
2681              ->canLosslesslyBitCastTo(F->getReturnType()) &&
2682            "unexpected this return");
2683     F->addParamAttr(0, llvm::Attribute::Returned);
2684   }
2685 
2686   // Only a few attributes are set on declarations; these may later be
2687   // overridden by a definition.
2688 
2689   setLinkageForGV(F, FD);
2690   setGVProperties(F, FD);
2691 
2692   // Setup target-specific attributes.
2693   if (!IsIncompleteFunction && F->isDeclaration())
2694     getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
2695 
2696   if (const auto *CSA = FD->getAttr<CodeSegAttr>())
2697     F->setSection(CSA->getName());
2698   else if (const auto *SA = FD->getAttr<SectionAttr>())
2699      F->setSection(SA->getName());
2700 
2701   if (const auto *EA = FD->getAttr<ErrorAttr>()) {
2702     if (EA->isError())
2703       F->addFnAttr("dontcall-error", EA->getUserDiagnostic());
2704     else if (EA->isWarning())
2705       F->addFnAttr("dontcall-warn", EA->getUserDiagnostic());
2706   }
2707 
2708   // If we plan on emitting this inline builtin, we can't treat it as a builtin.
2709   if (FD->isInlineBuiltinDeclaration()) {
2710     const FunctionDecl *FDBody;
2711     bool HasBody = FD->hasBody(FDBody);
2712     (void)HasBody;
2713     assert(HasBody && "Inline builtin declarations should always have an "
2714                       "available body!");
2715     if (shouldEmitFunction(FDBody))
2716       F->addFnAttr(llvm::Attribute::NoBuiltin);
2717   }
2718 
2719   if (FD->isReplaceableGlobalAllocationFunction()) {
2720     // A replaceable global allocation function does not act like a builtin by
2721     // default, only if it is invoked by a new-expression or delete-expression.
2722     F->addFnAttr(llvm::Attribute::NoBuiltin);
2723   }
2724 
2725   if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
2726     F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2727   else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
2728     if (MD->isVirtual())
2729       F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2730 
2731   // Don't emit entries for function declarations in the cross-DSO mode. This
2732   // is handled with better precision by the receiving DSO. But if jump tables
2733   // are non-canonical then we need type metadata in order to produce the local
2734   // jump table.
2735   if (!CodeGenOpts.SanitizeCfiCrossDso ||
2736       !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
2737     CreateFunctionTypeMetadataForIcall(FD, F);
2738 
2739   if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
2740     setKCFIType(FD, F);
2741 
2742   if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
2743     getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
2744 
2745   if (CodeGenOpts.InlineMaxStackSize != UINT_MAX)
2746     F->addFnAttr("inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize));
2747 
2748   if (const auto *CB = FD->getAttr<CallbackAttr>()) {
2749     // Annotate the callback behavior as metadata:
2750     //  - The callback callee (as argument number).
2751     //  - The callback payloads (as argument numbers).
2752     llvm::LLVMContext &Ctx = F->getContext();
2753     llvm::MDBuilder MDB(Ctx);
2754 
2755     // The payload indices are all but the first one in the encoding. The first
2756     // identifies the callback callee.
2757     int CalleeIdx = *CB->encoding_begin();
2758     ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
2759     F->addMetadata(llvm::LLVMContext::MD_callback,
2760                    *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
2761                                                CalleeIdx, PayloadIndices,
2762                                                /* VarArgsArePassed */ false)}));
2763   }
2764 }
2765 
2766 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
2767   assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
2768          "Only globals with definition can force usage.");
2769   LLVMUsed.emplace_back(GV);
2770 }
2771 
2772 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
2773   assert(!GV->isDeclaration() &&
2774          "Only globals with definition can force usage.");
2775   LLVMCompilerUsed.emplace_back(GV);
2776 }
2777 
2778 void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) {
2779   assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
2780          "Only globals with definition can force usage.");
2781   if (getTriple().isOSBinFormatELF())
2782     LLVMCompilerUsed.emplace_back(GV);
2783   else
2784     LLVMUsed.emplace_back(GV);
2785 }
2786 
2787 static void emitUsed(CodeGenModule &CGM, StringRef Name,
2788                      std::vector<llvm::WeakTrackingVH> &List) {
2789   // Don't create llvm.used if there is no need.
2790   if (List.empty())
2791     return;
2792 
2793   // Convert List to what ConstantArray needs.
2794   SmallVector<llvm::Constant*, 8> UsedArray;
2795   UsedArray.resize(List.size());
2796   for (unsigned i = 0, e = List.size(); i != e; ++i) {
2797     UsedArray[i] =
2798         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
2799             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
2800   }
2801 
2802   if (UsedArray.empty())
2803     return;
2804   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
2805 
2806   auto *GV = new llvm::GlobalVariable(
2807       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
2808       llvm::ConstantArray::get(ATy, UsedArray), Name);
2809 
2810   GV->setSection("llvm.metadata");
2811 }
2812 
2813 void CodeGenModule::emitLLVMUsed() {
2814   emitUsed(*this, "llvm.used", LLVMUsed);
2815   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
2816 }
2817 
2818 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
2819   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
2820   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
2821 }
2822 
2823 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
2824   llvm::SmallString<32> Opt;
2825   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
2826   if (Opt.empty())
2827     return;
2828   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
2829   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
2830 }
2831 
2832 void CodeGenModule::AddDependentLib(StringRef Lib) {
2833   auto &C = getLLVMContext();
2834   if (getTarget().getTriple().isOSBinFormatELF()) {
2835       ELFDependentLibraries.push_back(
2836         llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
2837     return;
2838   }
2839 
2840   llvm::SmallString<24> Opt;
2841   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
2842   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
2843   LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
2844 }
2845 
2846 /// Add link options implied by the given module, including modules
2847 /// it depends on, using a postorder walk.
2848 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
2849                                     SmallVectorImpl<llvm::MDNode *> &Metadata,
2850                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
2851   // Import this module's parent.
2852   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
2853     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
2854   }
2855 
2856   // Import this module's dependencies.
2857   for (Module *Import : llvm::reverse(Mod->Imports)) {
2858     if (Visited.insert(Import).second)
2859       addLinkOptionsPostorder(CGM, Import, Metadata, Visited);
2860   }
2861 
2862   // Add linker options to link against the libraries/frameworks
2863   // described by this module.
2864   llvm::LLVMContext &Context = CGM.getLLVMContext();
2865   bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
2866 
2867   // For modules that use export_as for linking, use that module
2868   // name instead.
2869   if (Mod->UseExportAsModuleLinkName)
2870     return;
2871 
2872   for (const Module::LinkLibrary &LL : llvm::reverse(Mod->LinkLibraries)) {
2873     // Link against a framework.  Frameworks are currently Darwin only, so we
2874     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
2875     if (LL.IsFramework) {
2876       llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
2877                                  llvm::MDString::get(Context, LL.Library)};
2878 
2879       Metadata.push_back(llvm::MDNode::get(Context, Args));
2880       continue;
2881     }
2882 
2883     // Link against a library.
2884     if (IsELF) {
2885       llvm::Metadata *Args[2] = {
2886           llvm::MDString::get(Context, "lib"),
2887           llvm::MDString::get(Context, LL.Library),
2888       };
2889       Metadata.push_back(llvm::MDNode::get(Context, Args));
2890     } else {
2891       llvm::SmallString<24> Opt;
2892       CGM.getTargetCodeGenInfo().getDependentLibraryOption(LL.Library, Opt);
2893       auto *OptString = llvm::MDString::get(Context, Opt);
2894       Metadata.push_back(llvm::MDNode::get(Context, OptString));
2895     }
2896   }
2897 }
2898 
2899 void CodeGenModule::EmitModuleInitializers(clang::Module *Primary) {
2900   // Emit the initializers in the order that sub-modules appear in the
2901   // source, first Global Module Fragments, if present.
2902   if (auto GMF = Primary->getGlobalModuleFragment()) {
2903     for (Decl *D : getContext().getModuleInitializers(GMF)) {
2904       if (isa<ImportDecl>(D))
2905         continue;
2906       assert(isa<VarDecl>(D) && "GMF initializer decl is not a var?");
2907       EmitTopLevelDecl(D);
2908     }
2909   }
2910   // Second any associated with the module, itself.
2911   for (Decl *D : getContext().getModuleInitializers(Primary)) {
2912     // Skip import decls, the inits for those are called explicitly.
2913     if (isa<ImportDecl>(D))
2914       continue;
2915     EmitTopLevelDecl(D);
2916   }
2917   // Third any associated with the Privat eMOdule Fragment, if present.
2918   if (auto PMF = Primary->getPrivateModuleFragment()) {
2919     for (Decl *D : getContext().getModuleInitializers(PMF)) {
2920       assert(isa<VarDecl>(D) && "PMF initializer decl is not a var?");
2921       EmitTopLevelDecl(D);
2922     }
2923   }
2924 }
2925 
2926 void CodeGenModule::EmitModuleLinkOptions() {
2927   // Collect the set of all of the modules we want to visit to emit link
2928   // options, which is essentially the imported modules and all of their
2929   // non-explicit child modules.
2930   llvm::SetVector<clang::Module *> LinkModules;
2931   llvm::SmallPtrSet<clang::Module *, 16> Visited;
2932   SmallVector<clang::Module *, 16> Stack;
2933 
2934   // Seed the stack with imported modules.
2935   for (Module *M : ImportedModules) {
2936     // Do not add any link flags when an implementation TU of a module imports
2937     // a header of that same module.
2938     if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
2939         !getLangOpts().isCompilingModule())
2940       continue;
2941     if (Visited.insert(M).second)
2942       Stack.push_back(M);
2943   }
2944 
2945   // Find all of the modules to import, making a little effort to prune
2946   // non-leaf modules.
2947   while (!Stack.empty()) {
2948     clang::Module *Mod = Stack.pop_back_val();
2949 
2950     bool AnyChildren = false;
2951 
2952     // Visit the submodules of this module.
2953     for (const auto &SM : Mod->submodules()) {
2954       // Skip explicit children; they need to be explicitly imported to be
2955       // linked against.
2956       if (SM->IsExplicit)
2957         continue;
2958 
2959       if (Visited.insert(SM).second) {
2960         Stack.push_back(SM);
2961         AnyChildren = true;
2962       }
2963     }
2964 
2965     // We didn't find any children, so add this module to the list of
2966     // modules to link against.
2967     if (!AnyChildren) {
2968       LinkModules.insert(Mod);
2969     }
2970   }
2971 
2972   // Add link options for all of the imported modules in reverse topological
2973   // order.  We don't do anything to try to order import link flags with respect
2974   // to linker options inserted by things like #pragma comment().
2975   SmallVector<llvm::MDNode *, 16> MetadataArgs;
2976   Visited.clear();
2977   for (Module *M : LinkModules)
2978     if (Visited.insert(M).second)
2979       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
2980   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
2981   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
2982 
2983   // Add the linker options metadata flag.
2984   auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
2985   for (auto *MD : LinkerOptionsMetadata)
2986     NMD->addOperand(MD);
2987 }
2988 
2989 void CodeGenModule::EmitDeferred() {
2990   // Emit deferred declare target declarations.
2991   if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
2992     getOpenMPRuntime().emitDeferredTargetDecls();
2993 
2994   // Emit code for any potentially referenced deferred decls.  Since a
2995   // previously unused static decl may become used during the generation of code
2996   // for a static function, iterate until no changes are made.
2997 
2998   if (!DeferredVTables.empty()) {
2999     EmitDeferredVTables();
3000 
3001     // Emitting a vtable doesn't directly cause more vtables to
3002     // become deferred, although it can cause functions to be
3003     // emitted that then need those vtables.
3004     assert(DeferredVTables.empty());
3005   }
3006 
3007   // Emit CUDA/HIP static device variables referenced by host code only.
3008   // Note we should not clear CUDADeviceVarODRUsedByHost since it is still
3009   // needed for further handling.
3010   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
3011     llvm::append_range(DeferredDeclsToEmit,
3012                        getContext().CUDADeviceVarODRUsedByHost);
3013 
3014   // Stop if we're out of both deferred vtables and deferred declarations.
3015   if (DeferredDeclsToEmit.empty())
3016     return;
3017 
3018   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
3019   // work, it will not interfere with this.
3020   std::vector<GlobalDecl> CurDeclsToEmit;
3021   CurDeclsToEmit.swap(DeferredDeclsToEmit);
3022 
3023   for (GlobalDecl &D : CurDeclsToEmit) {
3024     // We should call GetAddrOfGlobal with IsForDefinition set to true in order
3025     // to get GlobalValue with exactly the type we need, not something that
3026     // might had been created for another decl with the same mangled name but
3027     // different type.
3028     llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
3029         GetAddrOfGlobal(D, ForDefinition));
3030 
3031     // In case of different address spaces, we may still get a cast, even with
3032     // IsForDefinition equal to true. Query mangled names table to get
3033     // GlobalValue.
3034     if (!GV)
3035       GV = GetGlobalValue(getMangledName(D));
3036 
3037     // Make sure GetGlobalValue returned non-null.
3038     assert(GV);
3039 
3040     // Check to see if we've already emitted this.  This is necessary
3041     // for a couple of reasons: first, decls can end up in the
3042     // deferred-decls queue multiple times, and second, decls can end
3043     // up with definitions in unusual ways (e.g. by an extern inline
3044     // function acquiring a strong function redefinition).  Just
3045     // ignore these cases.
3046     if (!GV->isDeclaration())
3047       continue;
3048 
3049     // If this is OpenMP, check if it is legal to emit this global normally.
3050     if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
3051       continue;
3052 
3053     // Otherwise, emit the definition and move on to the next one.
3054     EmitGlobalDefinition(D, GV);
3055 
3056     // If we found out that we need to emit more decls, do that recursively.
3057     // This has the advantage that the decls are emitted in a DFS and related
3058     // ones are close together, which is convenient for testing.
3059     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
3060       EmitDeferred();
3061       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
3062     }
3063   }
3064 }
3065 
3066 void CodeGenModule::EmitVTablesOpportunistically() {
3067   // Try to emit external vtables as available_externally if they have emitted
3068   // all inlined virtual functions.  It runs after EmitDeferred() and therefore
3069   // is not allowed to create new references to things that need to be emitted
3070   // lazily. Note that it also uses fact that we eagerly emitting RTTI.
3071 
3072   assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
3073          && "Only emit opportunistic vtables with optimizations");
3074 
3075   for (const CXXRecordDecl *RD : OpportunisticVTables) {
3076     assert(getVTables().isVTableExternal(RD) &&
3077            "This queue should only contain external vtables");
3078     if (getCXXABI().canSpeculativelyEmitVTable(RD))
3079       VTables.GenerateClassData(RD);
3080   }
3081   OpportunisticVTables.clear();
3082 }
3083 
3084 void CodeGenModule::EmitGlobalAnnotations() {
3085   if (Annotations.empty())
3086     return;
3087 
3088   // Create a new global variable for the ConstantStruct in the Module.
3089   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
3090     Annotations[0]->getType(), Annotations.size()), Annotations);
3091   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
3092                                       llvm::GlobalValue::AppendingLinkage,
3093                                       Array, "llvm.global.annotations");
3094   gv->setSection(AnnotationSection);
3095 }
3096 
3097 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
3098   llvm::Constant *&AStr = AnnotationStrings[Str];
3099   if (AStr)
3100     return AStr;
3101 
3102   // Not found yet, create a new global.
3103   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
3104   auto *gv = new llvm::GlobalVariable(
3105       getModule(), s->getType(), true, llvm::GlobalValue::PrivateLinkage, s,
3106       ".str", nullptr, llvm::GlobalValue::NotThreadLocal,
3107       ConstGlobalsPtrTy->getAddressSpace());
3108   gv->setSection(AnnotationSection);
3109   gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3110   AStr = gv;
3111   return gv;
3112 }
3113 
3114 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
3115   SourceManager &SM = getContext().getSourceManager();
3116   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
3117   if (PLoc.isValid())
3118     return EmitAnnotationString(PLoc.getFilename());
3119   return EmitAnnotationString(SM.getBufferName(Loc));
3120 }
3121 
3122 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
3123   SourceManager &SM = getContext().getSourceManager();
3124   PresumedLoc PLoc = SM.getPresumedLoc(L);
3125   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
3126     SM.getExpansionLineNumber(L);
3127   return llvm::ConstantInt::get(Int32Ty, LineNo);
3128 }
3129 
3130 llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) {
3131   ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()};
3132   if (Exprs.empty())
3133     return llvm::ConstantPointerNull::get(ConstGlobalsPtrTy);
3134 
3135   llvm::FoldingSetNodeID ID;
3136   for (Expr *E : Exprs) {
3137     ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult());
3138   }
3139   llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
3140   if (Lookup)
3141     return Lookup;
3142 
3143   llvm::SmallVector<llvm::Constant *, 4> LLVMArgs;
3144   LLVMArgs.reserve(Exprs.size());
3145   ConstantEmitter ConstEmiter(*this);
3146   llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) {
3147     const auto *CE = cast<clang::ConstantExpr>(E);
3148     return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
3149                                     CE->getType());
3150   });
3151   auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
3152   auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true,
3153                                       llvm::GlobalValue::PrivateLinkage, Struct,
3154                                       ".args");
3155   GV->setSection(AnnotationSection);
3156   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3157   auto *Bitcasted = llvm::ConstantExpr::getBitCast(GV, GlobalsInt8PtrTy);
3158 
3159   Lookup = Bitcasted;
3160   return Bitcasted;
3161 }
3162 
3163 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
3164                                                 const AnnotateAttr *AA,
3165                                                 SourceLocation L) {
3166   // Get the globals for file name, annotation, and the line number.
3167   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
3168                  *UnitGV = EmitAnnotationUnit(L),
3169                  *LineNoCst = EmitAnnotationLineNo(L),
3170                  *Args = EmitAnnotationArgs(AA);
3171 
3172   llvm::Constant *GVInGlobalsAS = GV;
3173   if (GV->getAddressSpace() !=
3174       getDataLayout().getDefaultGlobalsAddressSpace()) {
3175     GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
3176         GV, GV->getValueType()->getPointerTo(
3177                 getDataLayout().getDefaultGlobalsAddressSpace()));
3178   }
3179 
3180   // Create the ConstantStruct for the global annotation.
3181   llvm::Constant *Fields[] = {
3182       llvm::ConstantExpr::getBitCast(GVInGlobalsAS, GlobalsInt8PtrTy),
3183       llvm::ConstantExpr::getBitCast(AnnoGV, ConstGlobalsPtrTy),
3184       llvm::ConstantExpr::getBitCast(UnitGV, ConstGlobalsPtrTy),
3185       LineNoCst,
3186       Args,
3187   };
3188   return llvm::ConstantStruct::getAnon(Fields);
3189 }
3190 
3191 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
3192                                          llvm::GlobalValue *GV) {
3193   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
3194   // Get the struct elements for these annotations.
3195   for (const auto *I : D->specific_attrs<AnnotateAttr>())
3196     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
3197 }
3198 
3199 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn,
3200                                        SourceLocation Loc) const {
3201   const auto &NoSanitizeL = getContext().getNoSanitizeList();
3202   // NoSanitize by function name.
3203   if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
3204     return true;
3205   // NoSanitize by location. Check "mainfile" prefix.
3206   auto &SM = Context.getSourceManager();
3207   const FileEntry &MainFile = *SM.getFileEntryForID(SM.getMainFileID());
3208   if (NoSanitizeL.containsMainFile(Kind, MainFile.getName()))
3209     return true;
3210 
3211   // Check "src" prefix.
3212   if (Loc.isValid())
3213     return NoSanitizeL.containsLocation(Kind, Loc);
3214   // If location is unknown, this may be a compiler-generated function. Assume
3215   // it's located in the main file.
3216   return NoSanitizeL.containsFile(Kind, MainFile.getName());
3217 }
3218 
3219 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind,
3220                                        llvm::GlobalVariable *GV,
3221                                        SourceLocation Loc, QualType Ty,
3222                                        StringRef Category) const {
3223   const auto &NoSanitizeL = getContext().getNoSanitizeList();
3224   if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category))
3225     return true;
3226   auto &SM = Context.getSourceManager();
3227   if (NoSanitizeL.containsMainFile(
3228           Kind, SM.getFileEntryForID(SM.getMainFileID())->getName(), Category))
3229     return true;
3230   if (NoSanitizeL.containsLocation(Kind, Loc, Category))
3231     return true;
3232 
3233   // Check global type.
3234   if (!Ty.isNull()) {
3235     // Drill down the array types: if global variable of a fixed type is
3236     // not sanitized, we also don't instrument arrays of them.
3237     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
3238       Ty = AT->getElementType();
3239     Ty = Ty.getCanonicalType().getUnqualifiedType();
3240     // Only record types (classes, structs etc.) are ignored.
3241     if (Ty->isRecordType()) {
3242       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
3243       if (NoSanitizeL.containsType(Kind, TypeStr, Category))
3244         return true;
3245     }
3246   }
3247   return false;
3248 }
3249 
3250 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
3251                                    StringRef Category) const {
3252   const auto &XRayFilter = getContext().getXRayFilter();
3253   using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
3254   auto Attr = ImbueAttr::NONE;
3255   if (Loc.isValid())
3256     Attr = XRayFilter.shouldImbueLocation(Loc, Category);
3257   if (Attr == ImbueAttr::NONE)
3258     Attr = XRayFilter.shouldImbueFunction(Fn->getName());
3259   switch (Attr) {
3260   case ImbueAttr::NONE:
3261     return false;
3262   case ImbueAttr::ALWAYS:
3263     Fn->addFnAttr("function-instrument", "xray-always");
3264     break;
3265   case ImbueAttr::ALWAYS_ARG1:
3266     Fn->addFnAttr("function-instrument", "xray-always");
3267     Fn->addFnAttr("xray-log-args", "1");
3268     break;
3269   case ImbueAttr::NEVER:
3270     Fn->addFnAttr("function-instrument", "xray-never");
3271     break;
3272   }
3273   return true;
3274 }
3275 
3276 ProfileList::ExclusionType
3277 CodeGenModule::isFunctionBlockedByProfileList(llvm::Function *Fn,
3278                                               SourceLocation Loc) const {
3279   const auto &ProfileList = getContext().getProfileList();
3280   // If the profile list is empty, then instrument everything.
3281   if (ProfileList.isEmpty())
3282     return ProfileList::Allow;
3283   CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr();
3284   // First, check the function name.
3285   if (auto V = ProfileList.isFunctionExcluded(Fn->getName(), Kind))
3286     return *V;
3287   // Next, check the source location.
3288   if (Loc.isValid())
3289     if (auto V = ProfileList.isLocationExcluded(Loc, Kind))
3290       return *V;
3291   // If location is unknown, this may be a compiler-generated function. Assume
3292   // it's located in the main file.
3293   auto &SM = Context.getSourceManager();
3294   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID()))
3295     if (auto V = ProfileList.isFileExcluded(MainFile->getName(), Kind))
3296       return *V;
3297   return ProfileList.getDefault(Kind);
3298 }
3299 
3300 ProfileList::ExclusionType
3301 CodeGenModule::isFunctionBlockedFromProfileInstr(llvm::Function *Fn,
3302                                                  SourceLocation Loc) const {
3303   auto V = isFunctionBlockedByProfileList(Fn, Loc);
3304   if (V != ProfileList::Allow)
3305     return V;
3306 
3307   auto NumGroups = getCodeGenOpts().ProfileTotalFunctionGroups;
3308   if (NumGroups > 1) {
3309     auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups;
3310     if (Group != getCodeGenOpts().ProfileSelectedFunctionGroup)
3311       return ProfileList::Skip;
3312   }
3313   return ProfileList::Allow;
3314 }
3315 
3316 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
3317   // Never defer when EmitAllDecls is specified.
3318   if (LangOpts.EmitAllDecls)
3319     return true;
3320 
3321   const auto *VD = dyn_cast<VarDecl>(Global);
3322   if (VD &&
3323       ((CodeGenOpts.KeepPersistentStorageVariables &&
3324         (VD->getStorageDuration() == SD_Static ||
3325          VD->getStorageDuration() == SD_Thread)) ||
3326        (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static &&
3327         VD->getType().isConstQualified())))
3328     return true;
3329 
3330   return getContext().DeclMustBeEmitted(Global);
3331 }
3332 
3333 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
3334   // In OpenMP 5.0 variables and function may be marked as
3335   // device_type(host/nohost) and we should not emit them eagerly unless we sure
3336   // that they must be emitted on the host/device. To be sure we need to have
3337   // seen a declare target with an explicit mentioning of the function, we know
3338   // we have if the level of the declare target attribute is -1. Note that we
3339   // check somewhere else if we should emit this at all.
3340   if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
3341     std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
3342         OMPDeclareTargetDeclAttr::getActiveAttr(Global);
3343     if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1)
3344       return false;
3345   }
3346 
3347   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
3348     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
3349       // Implicit template instantiations may change linkage if they are later
3350       // explicitly instantiated, so they should not be emitted eagerly.
3351       return false;
3352   }
3353   if (const auto *VD = dyn_cast<VarDecl>(Global)) {
3354     if (Context.getInlineVariableDefinitionKind(VD) ==
3355         ASTContext::InlineVariableDefinitionKind::WeakUnknown)
3356       // A definition of an inline constexpr static data member may change
3357       // linkage later if it's redeclared outside the class.
3358       return false;
3359     if (CXX20ModuleInits && VD->getOwningModule() &&
3360         !VD->getOwningModule()->isModuleMapModule()) {
3361       // For CXX20, module-owned initializers need to be deferred, since it is
3362       // not known at this point if they will be run for the current module or
3363       // as part of the initializer for an imported one.
3364       return false;
3365     }
3366   }
3367   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
3368   // codegen for global variables, because they may be marked as threadprivate.
3369   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
3370       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
3371       !Global->getType().isConstantStorage(getContext(), false, false) &&
3372       !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
3373     return false;
3374 
3375   return true;
3376 }
3377 
3378 ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) {
3379   StringRef Name = getMangledName(GD);
3380 
3381   // The UUID descriptor should be pointer aligned.
3382   CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
3383 
3384   // Look for an existing global.
3385   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
3386     return ConstantAddress(GV, GV->getValueType(), Alignment);
3387 
3388   ConstantEmitter Emitter(*this);
3389   llvm::Constant *Init;
3390 
3391   APValue &V = GD->getAsAPValue();
3392   if (!V.isAbsent()) {
3393     // If possible, emit the APValue version of the initializer. In particular,
3394     // this gets the type of the constant right.
3395     Init = Emitter.emitForInitializer(
3396         GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType());
3397   } else {
3398     // As a fallback, directly construct the constant.
3399     // FIXME: This may get padding wrong under esoteric struct layout rules.
3400     // MSVC appears to create a complete type 'struct __s_GUID' that it
3401     // presumably uses to represent these constants.
3402     MSGuidDecl::Parts Parts = GD->getParts();
3403     llvm::Constant *Fields[4] = {
3404         llvm::ConstantInt::get(Int32Ty, Parts.Part1),
3405         llvm::ConstantInt::get(Int16Ty, Parts.Part2),
3406         llvm::ConstantInt::get(Int16Ty, Parts.Part3),
3407         llvm::ConstantDataArray::getRaw(
3408             StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8,
3409             Int8Ty)};
3410     Init = llvm::ConstantStruct::getAnon(Fields);
3411   }
3412 
3413   auto *GV = new llvm::GlobalVariable(
3414       getModule(), Init->getType(),
3415       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
3416   if (supportsCOMDAT())
3417     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3418   setDSOLocal(GV);
3419 
3420   if (!V.isAbsent()) {
3421     Emitter.finalize(GV);
3422     return ConstantAddress(GV, GV->getValueType(), Alignment);
3423   }
3424 
3425   llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType());
3426   llvm::Constant *Addr = llvm::ConstantExpr::getBitCast(
3427       GV, Ty->getPointerTo(GV->getAddressSpace()));
3428   return ConstantAddress(Addr, Ty, Alignment);
3429 }
3430 
3431 ConstantAddress CodeGenModule::GetAddrOfUnnamedGlobalConstantDecl(
3432     const UnnamedGlobalConstantDecl *GCD) {
3433   CharUnits Alignment = getContext().getTypeAlignInChars(GCD->getType());
3434 
3435   llvm::GlobalVariable **Entry = nullptr;
3436   Entry = &UnnamedGlobalConstantDeclMap[GCD];
3437   if (*Entry)
3438     return ConstantAddress(*Entry, (*Entry)->getValueType(), Alignment);
3439 
3440   ConstantEmitter Emitter(*this);
3441   llvm::Constant *Init;
3442 
3443   const APValue &V = GCD->getValue();
3444 
3445   assert(!V.isAbsent());
3446   Init = Emitter.emitForInitializer(V, GCD->getType().getAddressSpace(),
3447                                     GCD->getType());
3448 
3449   auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(),
3450                                       /*isConstant=*/true,
3451                                       llvm::GlobalValue::PrivateLinkage, Init,
3452                                       ".constant");
3453   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3454   GV->setAlignment(Alignment.getAsAlign());
3455 
3456   Emitter.finalize(GV);
3457 
3458   *Entry = GV;
3459   return ConstantAddress(GV, GV->getValueType(), Alignment);
3460 }
3461 
3462 ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject(
3463     const TemplateParamObjectDecl *TPO) {
3464   StringRef Name = getMangledName(TPO);
3465   CharUnits Alignment = getNaturalTypeAlignment(TPO->getType());
3466 
3467   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
3468     return ConstantAddress(GV, GV->getValueType(), Alignment);
3469 
3470   ConstantEmitter Emitter(*this);
3471   llvm::Constant *Init = Emitter.emitForInitializer(
3472         TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType());
3473 
3474   if (!Init) {
3475     ErrorUnsupported(TPO, "template parameter object");
3476     return ConstantAddress::invalid();
3477   }
3478 
3479   llvm::GlobalValue::LinkageTypes Linkage =
3480       isExternallyVisible(TPO->getLinkageAndVisibility().getLinkage())
3481           ? llvm::GlobalValue::LinkOnceODRLinkage
3482           : llvm::GlobalValue::InternalLinkage;
3483   auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(),
3484                                       /*isConstant=*/true, Linkage, Init, Name);
3485   setGVProperties(GV, TPO);
3486   if (supportsCOMDAT())
3487     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3488   Emitter.finalize(GV);
3489 
3490   return ConstantAddress(GV, GV->getValueType(), Alignment);
3491 }
3492 
3493 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
3494   const AliasAttr *AA = VD->getAttr<AliasAttr>();
3495   assert(AA && "No alias?");
3496 
3497   CharUnits Alignment = getContext().getDeclAlign(VD);
3498   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
3499 
3500   // See if there is already something with the target's name in the module.
3501   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
3502   if (Entry) {
3503     unsigned AS = getTypes().getTargetAddressSpace(VD->getType());
3504     auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
3505     return ConstantAddress(Ptr, DeclTy, Alignment);
3506   }
3507 
3508   llvm::Constant *Aliasee;
3509   if (isa<llvm::FunctionType>(DeclTy))
3510     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
3511                                       GlobalDecl(cast<FunctionDecl>(VD)),
3512                                       /*ForVTable=*/false);
3513   else
3514     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
3515                                     nullptr);
3516 
3517   auto *F = cast<llvm::GlobalValue>(Aliasee);
3518   F->setLinkage(llvm::Function::ExternalWeakLinkage);
3519   WeakRefReferences.insert(F);
3520 
3521   return ConstantAddress(Aliasee, DeclTy, Alignment);
3522 }
3523 
3524 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
3525   const auto *Global = cast<ValueDecl>(GD.getDecl());
3526 
3527   // Weak references don't produce any output by themselves.
3528   if (Global->hasAttr<WeakRefAttr>())
3529     return;
3530 
3531   // If this is an alias definition (which otherwise looks like a declaration)
3532   // emit it now.
3533   if (Global->hasAttr<AliasAttr>())
3534     return EmitAliasDefinition(GD);
3535 
3536   // IFunc like an alias whose value is resolved at runtime by calling resolver.
3537   if (Global->hasAttr<IFuncAttr>())
3538     return emitIFuncDefinition(GD);
3539 
3540   // If this is a cpu_dispatch multiversion function, emit the resolver.
3541   if (Global->hasAttr<CPUDispatchAttr>())
3542     return emitCPUDispatchDefinition(GD);
3543 
3544   // If this is CUDA, be selective about which declarations we emit.
3545   if (LangOpts.CUDA) {
3546     if (LangOpts.CUDAIsDevice) {
3547       if (!Global->hasAttr<CUDADeviceAttr>() &&
3548           !Global->hasAttr<CUDAGlobalAttr>() &&
3549           !Global->hasAttr<CUDAConstantAttr>() &&
3550           !Global->hasAttr<CUDASharedAttr>() &&
3551           !Global->getType()->isCUDADeviceBuiltinSurfaceType() &&
3552           !Global->getType()->isCUDADeviceBuiltinTextureType())
3553         return;
3554     } else {
3555       // We need to emit host-side 'shadows' for all global
3556       // device-side variables because the CUDA runtime needs their
3557       // size and host-side address in order to provide access to
3558       // their device-side incarnations.
3559 
3560       // So device-only functions are the only things we skip.
3561       if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
3562           Global->hasAttr<CUDADeviceAttr>())
3563         return;
3564 
3565       assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
3566              "Expected Variable or Function");
3567     }
3568   }
3569 
3570   if (LangOpts.OpenMP) {
3571     // If this is OpenMP, check if it is legal to emit this global normally.
3572     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
3573       return;
3574     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
3575       if (MustBeEmitted(Global))
3576         EmitOMPDeclareReduction(DRD);
3577       return;
3578     }
3579     if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
3580       if (MustBeEmitted(Global))
3581         EmitOMPDeclareMapper(DMD);
3582       return;
3583     }
3584   }
3585 
3586   // Ignore declarations, they will be emitted on their first use.
3587   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
3588     // Forward declarations are emitted lazily on first use.
3589     if (!FD->doesThisDeclarationHaveABody()) {
3590       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
3591         return;
3592 
3593       StringRef MangledName = getMangledName(GD);
3594 
3595       // Compute the function info and LLVM type.
3596       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3597       llvm::Type *Ty = getTypes().GetFunctionType(FI);
3598 
3599       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
3600                               /*DontDefer=*/false);
3601       return;
3602     }
3603   } else {
3604     const auto *VD = cast<VarDecl>(Global);
3605     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
3606     if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
3607         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
3608       if (LangOpts.OpenMP) {
3609         // Emit declaration of the must-be-emitted declare target variable.
3610         if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3611                 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
3612 
3613           // If this variable has external storage and doesn't require special
3614           // link handling we defer to its canonical definition.
3615           if (VD->hasExternalStorage() &&
3616               Res != OMPDeclareTargetDeclAttr::MT_Link)
3617             return;
3618 
3619           bool UnifiedMemoryEnabled =
3620               getOpenMPRuntime().hasRequiresUnifiedSharedMemory();
3621           if ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3622                *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3623               !UnifiedMemoryEnabled) {
3624             (void)GetAddrOfGlobalVar(VD);
3625           } else {
3626             assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
3627                     ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3628                       *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3629                      UnifiedMemoryEnabled)) &&
3630                    "Link clause or to clause with unified memory expected.");
3631             (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
3632           }
3633 
3634           return;
3635         }
3636       }
3637       // If this declaration may have caused an inline variable definition to
3638       // change linkage, make sure that it's emitted.
3639       if (Context.getInlineVariableDefinitionKind(VD) ==
3640           ASTContext::InlineVariableDefinitionKind::Strong)
3641         GetAddrOfGlobalVar(VD);
3642       return;
3643     }
3644   }
3645 
3646   // Defer code generation to first use when possible, e.g. if this is an inline
3647   // function. If the global must always be emitted, do it eagerly if possible
3648   // to benefit from cache locality.
3649   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
3650     // Emit the definition if it can't be deferred.
3651     EmitGlobalDefinition(GD);
3652     addEmittedDeferredDecl(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   } else {
3673     // Otherwise, remember that we saw a deferred decl with this name.  The
3674     // first use of the mangled name will cause it to move into
3675     // DeferredDeclsToEmit.
3676     DeferredDecls[MangledName] = GD;
3677   }
3678 }
3679 
3680 // Check if T is a class type with a destructor that's not dllimport.
3681 static bool HasNonDllImportDtor(QualType T) {
3682   if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
3683     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
3684       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
3685         return true;
3686 
3687   return false;
3688 }
3689 
3690 namespace {
3691   struct FunctionIsDirectlyRecursive
3692       : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
3693     const StringRef Name;
3694     const Builtin::Context &BI;
3695     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
3696         : Name(N), BI(C) {}
3697 
3698     bool VisitCallExpr(const CallExpr *E) {
3699       const FunctionDecl *FD = E->getDirectCallee();
3700       if (!FD)
3701         return false;
3702       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
3703       if (Attr && Name == Attr->getLabel())
3704         return true;
3705       unsigned BuiltinID = FD->getBuiltinID();
3706       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
3707         return false;
3708       StringRef BuiltinName = BI.getName(BuiltinID);
3709       if (BuiltinName.startswith("__builtin_") &&
3710           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
3711         return true;
3712       }
3713       return false;
3714     }
3715 
3716     bool VisitStmt(const Stmt *S) {
3717       for (const Stmt *Child : S->children())
3718         if (Child && this->Visit(Child))
3719           return true;
3720       return false;
3721     }
3722   };
3723 
3724   // Make sure we're not referencing non-imported vars or functions.
3725   struct DLLImportFunctionVisitor
3726       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
3727     bool SafeToInline = true;
3728 
3729     bool shouldVisitImplicitCode() const { return true; }
3730 
3731     bool VisitVarDecl(VarDecl *VD) {
3732       if (VD->getTLSKind()) {
3733         // A thread-local variable cannot be imported.
3734         SafeToInline = false;
3735         return SafeToInline;
3736       }
3737 
3738       // A variable definition might imply a destructor call.
3739       if (VD->isThisDeclarationADefinition())
3740         SafeToInline = !HasNonDllImportDtor(VD->getType());
3741 
3742       return SafeToInline;
3743     }
3744 
3745     bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
3746       if (const auto *D = E->getTemporary()->getDestructor())
3747         SafeToInline = D->hasAttr<DLLImportAttr>();
3748       return SafeToInline;
3749     }
3750 
3751     bool VisitDeclRefExpr(DeclRefExpr *E) {
3752       ValueDecl *VD = E->getDecl();
3753       if (isa<FunctionDecl>(VD))
3754         SafeToInline = VD->hasAttr<DLLImportAttr>();
3755       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
3756         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
3757       return SafeToInline;
3758     }
3759 
3760     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
3761       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
3762       return SafeToInline;
3763     }
3764 
3765     bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3766       CXXMethodDecl *M = E->getMethodDecl();
3767       if (!M) {
3768         // Call through a pointer to member function. This is safe to inline.
3769         SafeToInline = true;
3770       } else {
3771         SafeToInline = M->hasAttr<DLLImportAttr>();
3772       }
3773       return SafeToInline;
3774     }
3775 
3776     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
3777       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
3778       return SafeToInline;
3779     }
3780 
3781     bool VisitCXXNewExpr(CXXNewExpr *E) {
3782       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
3783       return SafeToInline;
3784     }
3785   };
3786 }
3787 
3788 // isTriviallyRecursive - Check if this function calls another
3789 // decl that, because of the asm attribute or the other decl being a builtin,
3790 // ends up pointing to itself.
3791 bool
3792 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
3793   StringRef Name;
3794   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
3795     // asm labels are a special kind of mangling we have to support.
3796     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
3797     if (!Attr)
3798       return false;
3799     Name = Attr->getLabel();
3800   } else {
3801     Name = FD->getName();
3802   }
3803 
3804   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
3805   const Stmt *Body = FD->getBody();
3806   return Body ? Walker.Visit(Body) : false;
3807 }
3808 
3809 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
3810   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
3811     return true;
3812   const auto *F = cast<FunctionDecl>(GD.getDecl());
3813   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
3814     return false;
3815 
3816   if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
3817     // Check whether it would be safe to inline this dllimport function.
3818     DLLImportFunctionVisitor Visitor;
3819     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
3820     if (!Visitor.SafeToInline)
3821       return false;
3822 
3823     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
3824       // Implicit destructor invocations aren't captured in the AST, so the
3825       // check above can't see them. Check for them manually here.
3826       for (const Decl *Member : Dtor->getParent()->decls())
3827         if (isa<FieldDecl>(Member))
3828           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
3829             return false;
3830       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
3831         if (HasNonDllImportDtor(B.getType()))
3832           return false;
3833     }
3834   }
3835 
3836   // Inline builtins declaration must be emitted. They often are fortified
3837   // functions.
3838   if (F->isInlineBuiltinDeclaration())
3839     return true;
3840 
3841   // PR9614. Avoid cases where the source code is lying to us. An available
3842   // externally function should have an equivalent function somewhere else,
3843   // but a function that calls itself through asm label/`__builtin_` trickery is
3844   // clearly not equivalent to the real implementation.
3845   // This happens in glibc's btowc and in some configure checks.
3846   return !isTriviallyRecursive(F);
3847 }
3848 
3849 bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
3850   return CodeGenOpts.OptimizationLevel > 0;
3851 }
3852 
3853 void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
3854                                                        llvm::GlobalValue *GV) {
3855   const auto *FD = cast<FunctionDecl>(GD.getDecl());
3856 
3857   if (FD->isCPUSpecificMultiVersion()) {
3858     auto *Spec = FD->getAttr<CPUSpecificAttr>();
3859     for (unsigned I = 0; I < Spec->cpus_size(); ++I)
3860       EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
3861   } else if (FD->isTargetClonesMultiVersion()) {
3862     auto *Clone = FD->getAttr<TargetClonesAttr>();
3863     for (unsigned I = 0; I < Clone->featuresStrs_size(); ++I)
3864       if (Clone->isFirstOfVersion(I))
3865         EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
3866     // Ensure that the resolver function is also emitted.
3867     GetOrCreateMultiVersionResolver(GD);
3868   } else
3869     EmitGlobalFunctionDefinition(GD, GV);
3870 }
3871 
3872 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
3873   const auto *D = cast<ValueDecl>(GD.getDecl());
3874 
3875   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
3876                                  Context.getSourceManager(),
3877                                  "Generating code for declaration");
3878 
3879   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3880     // At -O0, don't generate IR for functions with available_externally
3881     // linkage.
3882     if (!shouldEmitFunction(GD))
3883       return;
3884 
3885     llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
3886       std::string Name;
3887       llvm::raw_string_ostream OS(Name);
3888       FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
3889                                /*Qualified=*/true);
3890       return Name;
3891     });
3892 
3893     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
3894       // Make sure to emit the definition(s) before we emit the thunks.
3895       // This is necessary for the generation of certain thunks.
3896       if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
3897         ABI->emitCXXStructor(GD);
3898       else if (FD->isMultiVersion())
3899         EmitMultiVersionFunctionDefinition(GD, GV);
3900       else
3901         EmitGlobalFunctionDefinition(GD, GV);
3902 
3903       if (Method->isVirtual())
3904         getVTables().EmitThunks(GD);
3905 
3906       return;
3907     }
3908 
3909     if (FD->isMultiVersion())
3910       return EmitMultiVersionFunctionDefinition(GD, GV);
3911     return EmitGlobalFunctionDefinition(GD, GV);
3912   }
3913 
3914   if (const auto *VD = dyn_cast<VarDecl>(D))
3915     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
3916 
3917   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
3918 }
3919 
3920 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3921                                                       llvm::Function *NewFn);
3922 
3923 static unsigned
3924 TargetMVPriority(const TargetInfo &TI,
3925                  const CodeGenFunction::MultiVersionResolverOption &RO) {
3926   unsigned Priority = 0;
3927   unsigned NumFeatures = 0;
3928   for (StringRef Feat : RO.Conditions.Features) {
3929     Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
3930     NumFeatures++;
3931   }
3932 
3933   if (!RO.Conditions.Architecture.empty())
3934     Priority = std::max(
3935         Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
3936 
3937   Priority += TI.multiVersionFeatureCost() * NumFeatures;
3938 
3939   return Priority;
3940 }
3941 
3942 // Multiversion functions should be at most 'WeakODRLinkage' so that a different
3943 // TU can forward declare the function without causing problems.  Particularly
3944 // in the cases of CPUDispatch, this causes issues. This also makes sure we
3945 // work with internal linkage functions, so that the same function name can be
3946 // used with internal linkage in multiple TUs.
3947 llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM,
3948                                                        GlobalDecl GD) {
3949   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
3950   if (FD->getFormalLinkage() == InternalLinkage)
3951     return llvm::GlobalValue::InternalLinkage;
3952   return llvm::GlobalValue::WeakODRLinkage;
3953 }
3954 
3955 void CodeGenModule::emitMultiVersionFunctions() {
3956   std::vector<GlobalDecl> MVFuncsToEmit;
3957   MultiVersionFuncs.swap(MVFuncsToEmit);
3958   for (GlobalDecl GD : MVFuncsToEmit) {
3959     const auto *FD = cast<FunctionDecl>(GD.getDecl());
3960     assert(FD && "Expected a FunctionDecl");
3961 
3962     SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
3963     if (FD->isTargetMultiVersion()) {
3964       getContext().forEachMultiversionedFunctionVersion(
3965           FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
3966             GlobalDecl CurGD{
3967                 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
3968             StringRef MangledName = getMangledName(CurGD);
3969             llvm::Constant *Func = GetGlobalValue(MangledName);
3970             if (!Func) {
3971               if (CurFD->isDefined()) {
3972                 EmitGlobalFunctionDefinition(CurGD, nullptr);
3973                 Func = GetGlobalValue(MangledName);
3974               } else {
3975                 const CGFunctionInfo &FI =
3976                     getTypes().arrangeGlobalDeclaration(GD);
3977                 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3978                 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
3979                                          /*DontDefer=*/false, ForDefinition);
3980               }
3981               assert(Func && "This should have just been created");
3982             }
3983             if (CurFD->getMultiVersionKind() == MultiVersionKind::Target) {
3984               const auto *TA = CurFD->getAttr<TargetAttr>();
3985               llvm::SmallVector<StringRef, 8> Feats;
3986               TA->getAddedFeatures(Feats);
3987               Options.emplace_back(cast<llvm::Function>(Func),
3988                                    TA->getArchitecture(), Feats);
3989             } else {
3990               const auto *TVA = CurFD->getAttr<TargetVersionAttr>();
3991               llvm::SmallVector<StringRef, 8> Feats;
3992               TVA->getFeatures(Feats);
3993               Options.emplace_back(cast<llvm::Function>(Func),
3994                                    /*Architecture*/ "", Feats);
3995             }
3996           });
3997     } else if (FD->isTargetClonesMultiVersion()) {
3998       const auto *TC = FD->getAttr<TargetClonesAttr>();
3999       for (unsigned VersionIndex = 0; VersionIndex < TC->featuresStrs_size();
4000            ++VersionIndex) {
4001         if (!TC->isFirstOfVersion(VersionIndex))
4002           continue;
4003         GlobalDecl CurGD{(FD->isDefined() ? FD->getDefinition() : FD),
4004                          VersionIndex};
4005         StringRef Version = TC->getFeatureStr(VersionIndex);
4006         StringRef MangledName = getMangledName(CurGD);
4007         llvm::Constant *Func = GetGlobalValue(MangledName);
4008         if (!Func) {
4009           if (FD->isDefined()) {
4010             EmitGlobalFunctionDefinition(CurGD, nullptr);
4011             Func = GetGlobalValue(MangledName);
4012           } else {
4013             const CGFunctionInfo &FI =
4014                 getTypes().arrangeGlobalDeclaration(CurGD);
4015             llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
4016             Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
4017                                      /*DontDefer=*/false, ForDefinition);
4018           }
4019           assert(Func && "This should have just been created");
4020         }
4021 
4022         StringRef Architecture;
4023         llvm::SmallVector<StringRef, 1> Feature;
4024 
4025         if (getTarget().getTriple().isAArch64()) {
4026           if (Version != "default") {
4027             llvm::SmallVector<StringRef, 8> VerFeats;
4028             Version.split(VerFeats, "+");
4029             for (auto &CurFeat : VerFeats)
4030               Feature.push_back(CurFeat.trim());
4031           }
4032         } else {
4033           if (Version.startswith("arch="))
4034             Architecture = Version.drop_front(sizeof("arch=") - 1);
4035           else if (Version != "default")
4036             Feature.push_back(Version);
4037         }
4038 
4039         Options.emplace_back(cast<llvm::Function>(Func), Architecture, Feature);
4040       }
4041     } else {
4042       assert(0 && "Expected a target or target_clones multiversion function");
4043       continue;
4044     }
4045 
4046     llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
4047     if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant))
4048       ResolverConstant = IFunc->getResolver();
4049     llvm::Function *ResolverFunc = cast<llvm::Function>(ResolverConstant);
4050 
4051     ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD));
4052 
4053     if (supportsCOMDAT())
4054       ResolverFunc->setComdat(
4055           getModule().getOrInsertComdat(ResolverFunc->getName()));
4056 
4057     const TargetInfo &TI = getTarget();
4058     llvm::stable_sort(
4059         Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
4060                        const CodeGenFunction::MultiVersionResolverOption &RHS) {
4061           return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
4062         });
4063     CodeGenFunction CGF(*this);
4064     CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4065   }
4066 
4067   // Ensure that any additions to the deferred decls list caused by emitting a
4068   // variant are emitted.  This can happen when the variant itself is inline and
4069   // calls a function without linkage.
4070   if (!MVFuncsToEmit.empty())
4071     EmitDeferred();
4072 
4073   // Ensure that any additions to the multiversion funcs list from either the
4074   // deferred decls or the multiversion functions themselves are emitted.
4075   if (!MultiVersionFuncs.empty())
4076     emitMultiVersionFunctions();
4077 }
4078 
4079 void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
4080   const auto *FD = cast<FunctionDecl>(GD.getDecl());
4081   assert(FD && "Not a FunctionDecl?");
4082   assert(FD->isCPUDispatchMultiVersion() && "Not a multiversion function?");
4083   const auto *DD = FD->getAttr<CPUDispatchAttr>();
4084   assert(DD && "Not a cpu_dispatch Function?");
4085 
4086   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4087   llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
4088 
4089   StringRef ResolverName = getMangledName(GD);
4090   UpdateMultiVersionNames(GD, FD, ResolverName);
4091 
4092   llvm::Type *ResolverType;
4093   GlobalDecl ResolverGD;
4094   if (getTarget().supportsIFunc()) {
4095     ResolverType = llvm::FunctionType::get(
4096         llvm::PointerType::get(DeclTy,
4097                                getTypes().getTargetAddressSpace(FD->getType())),
4098         false);
4099   }
4100   else {
4101     ResolverType = DeclTy;
4102     ResolverGD = GD;
4103   }
4104 
4105   auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
4106       ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
4107   ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD));
4108   if (supportsCOMDAT())
4109     ResolverFunc->setComdat(
4110         getModule().getOrInsertComdat(ResolverFunc->getName()));
4111 
4112   SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
4113   const TargetInfo &Target = getTarget();
4114   unsigned Index = 0;
4115   for (const IdentifierInfo *II : DD->cpus()) {
4116     // Get the name of the target function so we can look it up/create it.
4117     std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
4118                               getCPUSpecificMangling(*this, II->getName());
4119 
4120     llvm::Constant *Func = GetGlobalValue(MangledName);
4121 
4122     if (!Func) {
4123       GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
4124       if (ExistingDecl.getDecl() &&
4125           ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
4126         EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
4127         Func = GetGlobalValue(MangledName);
4128       } else {
4129         if (!ExistingDecl.getDecl())
4130           ExistingDecl = GD.getWithMultiVersionIndex(Index);
4131 
4132       Func = GetOrCreateLLVMFunction(
4133           MangledName, DeclTy, ExistingDecl,
4134           /*ForVTable=*/false, /*DontDefer=*/true,
4135           /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
4136       }
4137     }
4138 
4139     llvm::SmallVector<StringRef, 32> Features;
4140     Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
4141     llvm::transform(Features, Features.begin(),
4142                     [](StringRef Str) { return Str.substr(1); });
4143     llvm::erase_if(Features, [&Target](StringRef Feat) {
4144       return !Target.validateCpuSupports(Feat);
4145     });
4146     Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
4147     ++Index;
4148   }
4149 
4150   llvm::stable_sort(
4151       Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
4152                   const CodeGenFunction::MultiVersionResolverOption &RHS) {
4153         return llvm::X86::getCpuSupportsMask(LHS.Conditions.Features) >
4154                llvm::X86::getCpuSupportsMask(RHS.Conditions.Features);
4155       });
4156 
4157   // If the list contains multiple 'default' versions, such as when it contains
4158   // 'pentium' and 'generic', don't emit the call to the generic one (since we
4159   // always run on at least a 'pentium'). We do this by deleting the 'least
4160   // advanced' (read, lowest mangling letter).
4161   while (Options.size() > 1 &&
4162          llvm::all_of(llvm::X86::getCpuSupportsMask(
4163                           (Options.end() - 2)->Conditions.Features),
4164                       [](auto X) { return X == 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       DeferredDecls.erase(DDI);
4413 
4414       // Otherwise, there are cases we have to worry about where we're
4415       // using a declaration for which we must emit a definition but where
4416       // we might not find a top-level definition:
4417       //   - member functions defined inline in their classes
4418       //   - friend functions defined inline in some class
4419       //   - special member functions with implicit definitions
4420       // If we ever change our AST traversal to walk into class methods,
4421       // this will be unnecessary.
4422       //
4423       // We also don't emit a definition for a function if it's going to be an
4424       // entry in a vtable, unless it's already marked as used.
4425     } else if (getLangOpts().CPlusPlus && D) {
4426       // Look for a declaration that's lexically in a record.
4427       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
4428            FD = FD->getPreviousDecl()) {
4429         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
4430           if (FD->doesThisDeclarationHaveABody()) {
4431             addDeferredDeclToEmit(GD.getWithDecl(FD));
4432             break;
4433           }
4434         }
4435       }
4436     }
4437   }
4438 
4439   // Make sure the result is of the requested type.
4440   if (!IsIncompleteFunction) {
4441     assert(F->getFunctionType() == Ty);
4442     return F;
4443   }
4444 
4445   return llvm::ConstantExpr::getBitCast(F,
4446                                         Ty->getPointerTo(F->getAddressSpace()));
4447 }
4448 
4449 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
4450 /// non-null, then this function will use the specified type if it has to
4451 /// create it (this occurs when we see a definition of the function).
4452 llvm::Constant *
4453 CodeGenModule::GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty, bool ForVTable,
4454                                  bool DontDefer,
4455                                  ForDefinition_t IsForDefinition) {
4456   // If there was no specific requested type, just convert it now.
4457   if (!Ty) {
4458     const auto *FD = cast<FunctionDecl>(GD.getDecl());
4459     Ty = getTypes().ConvertType(FD->getType());
4460   }
4461 
4462   // Devirtualized destructor calls may come through here instead of via
4463   // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
4464   // of the complete destructor when necessary.
4465   if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
4466     if (getTarget().getCXXABI().isMicrosoft() &&
4467         GD.getDtorType() == Dtor_Complete &&
4468         DD->getParent()->getNumVBases() == 0)
4469       GD = GlobalDecl(DD, Dtor_Base);
4470   }
4471 
4472   StringRef MangledName = getMangledName(GD);
4473   auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
4474                                     /*IsThunk=*/false, llvm::AttributeList(),
4475                                     IsForDefinition);
4476   // Returns kernel handle for HIP kernel stub function.
4477   if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
4478       cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) {
4479     auto *Handle = getCUDARuntime().getKernelHandle(
4480         cast<llvm::Function>(F->stripPointerCasts()), GD);
4481     if (IsForDefinition)
4482       return F;
4483     return llvm::ConstantExpr::getBitCast(Handle, Ty->getPointerTo());
4484   }
4485   return F;
4486 }
4487 
4488 llvm::Constant *CodeGenModule::GetFunctionStart(const ValueDecl *Decl) {
4489   llvm::GlobalValue *F =
4490       cast<llvm::GlobalValue>(GetAddrOfFunction(Decl)->stripPointerCasts());
4491 
4492   return llvm::ConstantExpr::getBitCast(
4493       llvm::NoCFIValue::get(F),
4494       llvm::PointerType::get(VMContext, F->getAddressSpace()));
4495 }
4496 
4497 static const FunctionDecl *
4498 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
4499   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
4500   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
4501 
4502   IdentifierInfo &CII = C.Idents.get(Name);
4503   for (const auto *Result : DC->lookup(&CII))
4504     if (const auto *FD = dyn_cast<FunctionDecl>(Result))
4505       return FD;
4506 
4507   if (!C.getLangOpts().CPlusPlus)
4508     return nullptr;
4509 
4510   // Demangle the premangled name from getTerminateFn()
4511   IdentifierInfo &CXXII =
4512       (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
4513           ? C.Idents.get("terminate")
4514           : C.Idents.get(Name);
4515 
4516   for (const auto &N : {"__cxxabiv1", "std"}) {
4517     IdentifierInfo &NS = C.Idents.get(N);
4518     for (const auto *Result : DC->lookup(&NS)) {
4519       const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
4520       if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result))
4521         for (const auto *Result : LSD->lookup(&NS))
4522           if ((ND = dyn_cast<NamespaceDecl>(Result)))
4523             break;
4524 
4525       if (ND)
4526         for (const auto *Result : ND->lookup(&CXXII))
4527           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
4528             return FD;
4529     }
4530   }
4531 
4532   return nullptr;
4533 }
4534 
4535 /// CreateRuntimeFunction - Create a new runtime function with the specified
4536 /// type and name.
4537 llvm::FunctionCallee
4538 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
4539                                      llvm::AttributeList ExtraAttrs, bool Local,
4540                                      bool AssumeConvergent) {
4541   if (AssumeConvergent) {
4542     ExtraAttrs =
4543         ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
4544   }
4545 
4546   llvm::Constant *C =
4547       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
4548                               /*DontDefer=*/false, /*IsThunk=*/false,
4549                               ExtraAttrs);
4550 
4551   if (auto *F = dyn_cast<llvm::Function>(C)) {
4552     if (F->empty()) {
4553       F->setCallingConv(getRuntimeCC());
4554 
4555       // In Windows Itanium environments, try to mark runtime functions
4556       // dllimport. For Mingw and MSVC, don't. We don't really know if the user
4557       // will link their standard library statically or dynamically. Marking
4558       // functions imported when they are not imported can cause linker errors
4559       // and warnings.
4560       if (!Local && getTriple().isWindowsItaniumEnvironment() &&
4561           !getCodeGenOpts().LTOVisibilityPublicStd) {
4562         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
4563         if (!FD || FD->hasAttr<DLLImportAttr>()) {
4564           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
4565           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
4566         }
4567       }
4568       setDSOLocal(F);
4569     }
4570   }
4571 
4572   return {FTy, C};
4573 }
4574 
4575 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
4576 /// create and return an llvm GlobalVariable with the specified type and address
4577 /// space. If there is something in the module with the specified name, return
4578 /// it potentially bitcasted to the right type.
4579 ///
4580 /// If D is non-null, it specifies a decl that correspond to this.  This is used
4581 /// to set the attributes on the global when it is first created.
4582 ///
4583 /// If IsForDefinition is true, it is guaranteed that an actual global with
4584 /// type Ty will be returned, not conversion of a variable with the same
4585 /// mangled name but some other type.
4586 llvm::Constant *
4587 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty,
4588                                      LangAS AddrSpace, const VarDecl *D,
4589                                      ForDefinition_t IsForDefinition) {
4590   // Lookup the entry, lazily creating it if necessary.
4591   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4592   unsigned TargetAS = getContext().getTargetAddressSpace(AddrSpace);
4593   if (Entry) {
4594     if (WeakRefReferences.erase(Entry)) {
4595       if (D && !D->hasAttr<WeakAttr>())
4596         Entry->setLinkage(llvm::Function::ExternalLinkage);
4597     }
4598 
4599     // Handle dropped DLL attributes.
4600     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() &&
4601         !shouldMapVisibilityToDLLExport(D))
4602       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
4603 
4604     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
4605       getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
4606 
4607     if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
4608       return Entry;
4609 
4610     // If there are two attempts to define the same mangled name, issue an
4611     // error.
4612     if (IsForDefinition && !Entry->isDeclaration()) {
4613       GlobalDecl OtherGD;
4614       const VarDecl *OtherD;
4615 
4616       // Check that D is not yet in DiagnosedConflictingDefinitions is required
4617       // to make sure that we issue an error only once.
4618       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
4619           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
4620           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
4621           OtherD->hasInit() &&
4622           DiagnosedConflictingDefinitions.insert(D).second) {
4623         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
4624             << MangledName;
4625         getDiags().Report(OtherGD.getDecl()->getLocation(),
4626                           diag::note_previous_definition);
4627       }
4628     }
4629 
4630     // Make sure the result is of the correct type.
4631     if (Entry->getType()->getAddressSpace() != TargetAS) {
4632       return llvm::ConstantExpr::getAddrSpaceCast(Entry,
4633                                                   Ty->getPointerTo(TargetAS));
4634     }
4635 
4636     // (If global is requested for a definition, we always need to create a new
4637     // global, not just return a bitcast.)
4638     if (!IsForDefinition)
4639       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo(TargetAS));
4640   }
4641 
4642   auto DAddrSpace = GetGlobalVarAddressSpace(D);
4643 
4644   auto *GV = new llvm::GlobalVariable(
4645       getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr,
4646       MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal,
4647       getContext().getTargetAddressSpace(DAddrSpace));
4648 
4649   // If we already created a global with the same mangled name (but different
4650   // type) before, take its name and remove it from its parent.
4651   if (Entry) {
4652     GV->takeName(Entry);
4653 
4654     if (!Entry->use_empty()) {
4655       llvm::Constant *NewPtrForOldDecl =
4656           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
4657       Entry->replaceAllUsesWith(NewPtrForOldDecl);
4658     }
4659 
4660     Entry->eraseFromParent();
4661   }
4662 
4663   // This is the first use or definition of a mangled name.  If there is a
4664   // deferred decl with this name, remember that we need to emit it at the end
4665   // of the file.
4666   auto DDI = DeferredDecls.find(MangledName);
4667   if (DDI != DeferredDecls.end()) {
4668     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
4669     // list, and remove it from DeferredDecls (since we don't need it anymore).
4670     addDeferredDeclToEmit(DDI->second);
4671     DeferredDecls.erase(DDI);
4672   }
4673 
4674   // Handle things which are present even on external declarations.
4675   if (D) {
4676     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
4677       getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
4678 
4679     // FIXME: This code is overly simple and should be merged with other global
4680     // handling.
4681     GV->setConstant(D->getType().isConstantStorage(getContext(), false, false));
4682 
4683     GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
4684 
4685     setLinkageForGV(GV, D);
4686 
4687     if (D->getTLSKind()) {
4688       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
4689         CXXThreadLocals.push_back(D);
4690       setTLSMode(GV, *D);
4691     }
4692 
4693     setGVProperties(GV, D);
4694 
4695     // If required by the ABI, treat declarations of static data members with
4696     // inline initializers as definitions.
4697     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
4698       EmitGlobalVarDefinition(D);
4699     }
4700 
4701     // Emit section information for extern variables.
4702     if (D->hasExternalStorage()) {
4703       if (const SectionAttr *SA = D->getAttr<SectionAttr>())
4704         GV->setSection(SA->getName());
4705     }
4706 
4707     // Handle XCore specific ABI requirements.
4708     if (getTriple().getArch() == llvm::Triple::xcore &&
4709         D->getLanguageLinkage() == CLanguageLinkage &&
4710         D->getType().isConstant(Context) &&
4711         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
4712       GV->setSection(".cp.rodata");
4713 
4714     // Check if we a have a const declaration with an initializer, we may be
4715     // able to emit it as available_externally to expose it's value to the
4716     // optimizer.
4717     if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
4718         D->getType().isConstQualified() && !GV->hasInitializer() &&
4719         !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
4720       const auto *Record =
4721           Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
4722       bool HasMutableFields = Record && Record->hasMutableFields();
4723       if (!HasMutableFields) {
4724         const VarDecl *InitDecl;
4725         const Expr *InitExpr = D->getAnyInitializer(InitDecl);
4726         if (InitExpr) {
4727           ConstantEmitter emitter(*this);
4728           llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
4729           if (Init) {
4730             auto *InitType = Init->getType();
4731             if (GV->getValueType() != InitType) {
4732               // The type of the initializer does not match the definition.
4733               // This happens when an initializer has a different type from
4734               // the type of the global (because of padding at the end of a
4735               // structure for instance).
4736               GV->setName(StringRef());
4737               // Make a new global with the correct type, this is now guaranteed
4738               // to work.
4739               auto *NewGV = cast<llvm::GlobalVariable>(
4740                   GetAddrOfGlobalVar(D, InitType, IsForDefinition)
4741                       ->stripPointerCasts());
4742 
4743               // Erase the old global, since it is no longer used.
4744               GV->eraseFromParent();
4745               GV = NewGV;
4746             } else {
4747               GV->setInitializer(Init);
4748               GV->setConstant(true);
4749               GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
4750             }
4751             emitter.finalize(GV);
4752           }
4753         }
4754       }
4755     }
4756   }
4757 
4758   if (D &&
4759       D->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly) {
4760     getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
4761     // External HIP managed variables needed to be recorded for transformation
4762     // in both device and host compilations.
4763     if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() &&
4764         D->hasExternalStorage())
4765       getCUDARuntime().handleVarRegistration(D, *GV);
4766   }
4767 
4768   if (D)
4769     SanitizerMD->reportGlobal(GV, *D);
4770 
4771   LangAS ExpectedAS =
4772       D ? D->getType().getAddressSpace()
4773         : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
4774   assert(getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
4775   if (DAddrSpace != ExpectedAS) {
4776     return getTargetCodeGenInfo().performAddrSpaceCast(
4777         *this, GV, DAddrSpace, ExpectedAS, Ty->getPointerTo(TargetAS));
4778   }
4779 
4780   return GV;
4781 }
4782 
4783 llvm::Constant *
4784 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) {
4785   const Decl *D = GD.getDecl();
4786 
4787   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
4788     return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
4789                                 /*DontDefer=*/false, IsForDefinition);
4790 
4791   if (isa<CXXMethodDecl>(D)) {
4792     auto FInfo =
4793         &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D));
4794     auto Ty = getTypes().GetFunctionType(*FInfo);
4795     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
4796                              IsForDefinition);
4797   }
4798 
4799   if (isa<FunctionDecl>(D)) {
4800     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4801     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
4802     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
4803                              IsForDefinition);
4804   }
4805 
4806   return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition);
4807 }
4808 
4809 llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
4810     StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
4811     llvm::Align Alignment) {
4812   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
4813   llvm::GlobalVariable *OldGV = nullptr;
4814 
4815   if (GV) {
4816     // Check if the variable has the right type.
4817     if (GV->getValueType() == Ty)
4818       return GV;
4819 
4820     // Because C++ name mangling, the only way we can end up with an already
4821     // existing global with the same name is if it has been declared extern "C".
4822     assert(GV->isDeclaration() && "Declaration has wrong type!");
4823     OldGV = GV;
4824   }
4825 
4826   // Create a new variable.
4827   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
4828                                 Linkage, nullptr, Name);
4829 
4830   if (OldGV) {
4831     // Replace occurrences of the old variable if needed.
4832     GV->takeName(OldGV);
4833 
4834     if (!OldGV->use_empty()) {
4835       llvm::Constant *NewPtrForOldDecl =
4836       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
4837       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
4838     }
4839 
4840     OldGV->eraseFromParent();
4841   }
4842 
4843   if (supportsCOMDAT() && GV->isWeakForLinker() &&
4844       !GV->hasAvailableExternallyLinkage())
4845     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4846 
4847   GV->setAlignment(Alignment);
4848 
4849   return GV;
4850 }
4851 
4852 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
4853 /// given global variable.  If Ty is non-null and if the global doesn't exist,
4854 /// then it will be created with the specified type instead of whatever the
4855 /// normal requested type would be. If IsForDefinition is true, it is guaranteed
4856 /// that an actual global with type Ty will be returned, not conversion of a
4857 /// variable with the same mangled name but some other type.
4858 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
4859                                                   llvm::Type *Ty,
4860                                            ForDefinition_t IsForDefinition) {
4861   assert(D->hasGlobalStorage() && "Not a global variable");
4862   QualType ASTTy = D->getType();
4863   if (!Ty)
4864     Ty = getTypes().ConvertTypeForMem(ASTTy);
4865 
4866   StringRef MangledName = getMangledName(D);
4867   return GetOrCreateLLVMGlobal(MangledName, Ty, ASTTy.getAddressSpace(), D,
4868                                IsForDefinition);
4869 }
4870 
4871 /// CreateRuntimeVariable - Create a new runtime global variable with the
4872 /// specified type and name.
4873 llvm::Constant *
4874 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
4875                                      StringRef Name) {
4876   LangAS AddrSpace = getContext().getLangOpts().OpenCL ? LangAS::opencl_global
4877                                                        : LangAS::Default;
4878   auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr);
4879   setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
4880   return Ret;
4881 }
4882 
4883 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
4884   assert(!D->getInit() && "Cannot emit definite definitions here!");
4885 
4886   StringRef MangledName = getMangledName(D);
4887   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
4888 
4889   // We already have a definition, not declaration, with the same mangled name.
4890   // Emitting of declaration is not required (and actually overwrites emitted
4891   // definition).
4892   if (GV && !GV->isDeclaration())
4893     return;
4894 
4895   // If we have not seen a reference to this variable yet, place it into the
4896   // deferred declarations table to be emitted if needed later.
4897   if (!MustBeEmitted(D) && !GV) {
4898       DeferredDecls[MangledName] = D;
4899       return;
4900   }
4901 
4902   // The tentative definition is the only definition.
4903   EmitGlobalVarDefinition(D);
4904 }
4905 
4906 void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) {
4907   EmitExternalVarDeclaration(D);
4908 }
4909 
4910 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
4911   return Context.toCharUnitsFromBits(
4912       getDataLayout().getTypeStoreSizeInBits(Ty));
4913 }
4914 
4915 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
4916   if (LangOpts.OpenCL) {
4917     LangAS AS = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
4918     assert(AS == LangAS::opencl_global ||
4919            AS == LangAS::opencl_global_device ||
4920            AS == LangAS::opencl_global_host ||
4921            AS == LangAS::opencl_constant ||
4922            AS == LangAS::opencl_local ||
4923            AS >= LangAS::FirstTargetAddressSpace);
4924     return AS;
4925   }
4926 
4927   if (LangOpts.SYCLIsDevice &&
4928       (!D || D->getType().getAddressSpace() == LangAS::Default))
4929     return LangAS::sycl_global;
4930 
4931   if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
4932     if (D) {
4933       if (D->hasAttr<CUDAConstantAttr>())
4934         return LangAS::cuda_constant;
4935       if (D->hasAttr<CUDASharedAttr>())
4936         return LangAS::cuda_shared;
4937       if (D->hasAttr<CUDADeviceAttr>())
4938         return LangAS::cuda_device;
4939       if (D->getType().isConstQualified())
4940         return LangAS::cuda_constant;
4941     }
4942     return LangAS::cuda_device;
4943   }
4944 
4945   if (LangOpts.OpenMP) {
4946     LangAS AS;
4947     if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
4948       return AS;
4949   }
4950   return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
4951 }
4952 
4953 LangAS CodeGenModule::GetGlobalConstantAddressSpace() const {
4954   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
4955   if (LangOpts.OpenCL)
4956     return LangAS::opencl_constant;
4957   if (LangOpts.SYCLIsDevice)
4958     return LangAS::sycl_global;
4959   if (LangOpts.HIP && LangOpts.CUDAIsDevice && getTriple().isSPIRV())
4960     // For HIPSPV map literals to cuda_device (maps to CrossWorkGroup in SPIR-V)
4961     // instead of default AS (maps to Generic in SPIR-V). Otherwise, we end up
4962     // with OpVariable instructions with Generic storage class which is not
4963     // allowed (SPIR-V V1.6 s3.42.8). Also, mapping literals to SPIR-V
4964     // UniformConstant storage class is not viable as pointers to it may not be
4965     // casted to Generic pointers which are used to model HIP's "flat" pointers.
4966     return LangAS::cuda_device;
4967   if (auto AS = getTarget().getConstantAddressSpace())
4968     return *AS;
4969   return LangAS::Default;
4970 }
4971 
4972 // In address space agnostic languages, string literals are in default address
4973 // space in AST. However, certain targets (e.g. amdgcn) request them to be
4974 // emitted in constant address space in LLVM IR. To be consistent with other
4975 // parts of AST, string literal global variables in constant address space
4976 // need to be casted to default address space before being put into address
4977 // map and referenced by other part of CodeGen.
4978 // In OpenCL, string literals are in constant address space in AST, therefore
4979 // they should not be casted to default address space.
4980 static llvm::Constant *
4981 castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
4982                                        llvm::GlobalVariable *GV) {
4983   llvm::Constant *Cast = GV;
4984   if (!CGM.getLangOpts().OpenCL) {
4985     auto AS = CGM.GetGlobalConstantAddressSpace();
4986     if (AS != LangAS::Default)
4987       Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
4988           CGM, GV, AS, LangAS::Default,
4989           GV->getValueType()->getPointerTo(
4990               CGM.getContext().getTargetAddressSpace(LangAS::Default)));
4991   }
4992   return Cast;
4993 }
4994 
4995 template<typename SomeDecl>
4996 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
4997                                                llvm::GlobalValue *GV) {
4998   if (!getLangOpts().CPlusPlus)
4999     return;
5000 
5001   // Must have 'used' attribute, or else inline assembly can't rely on
5002   // the name existing.
5003   if (!D->template hasAttr<UsedAttr>())
5004     return;
5005 
5006   // Must have internal linkage and an ordinary name.
5007   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
5008     return;
5009 
5010   // Must be in an extern "C" context. Entities declared directly within
5011   // a record are not extern "C" even if the record is in such a context.
5012   const SomeDecl *First = D->getFirstDecl();
5013   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
5014     return;
5015 
5016   // OK, this is an internal linkage entity inside an extern "C" linkage
5017   // specification. Make a note of that so we can give it the "expected"
5018   // mangled name if nothing else is using that name.
5019   std::pair<StaticExternCMap::iterator, bool> R =
5020       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
5021 
5022   // If we have multiple internal linkage entities with the same name
5023   // in extern "C" regions, none of them gets that name.
5024   if (!R.second)
5025     R.first->second = nullptr;
5026 }
5027 
5028 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
5029   if (!CGM.supportsCOMDAT())
5030     return false;
5031 
5032   if (D.hasAttr<SelectAnyAttr>())
5033     return true;
5034 
5035   GVALinkage Linkage;
5036   if (auto *VD = dyn_cast<VarDecl>(&D))
5037     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
5038   else
5039     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
5040 
5041   switch (Linkage) {
5042   case GVA_Internal:
5043   case GVA_AvailableExternally:
5044   case GVA_StrongExternal:
5045     return false;
5046   case GVA_DiscardableODR:
5047   case GVA_StrongODR:
5048     return true;
5049   }
5050   llvm_unreachable("No such linkage");
5051 }
5052 
5053 bool CodeGenModule::supportsCOMDAT() const {
5054   return getTriple().supportsCOMDAT();
5055 }
5056 
5057 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
5058                                           llvm::GlobalObject &GO) {
5059   if (!shouldBeInCOMDAT(*this, D))
5060     return;
5061   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
5062 }
5063 
5064 /// Pass IsTentative as true if you want to create a tentative definition.
5065 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
5066                                             bool IsTentative) {
5067   // OpenCL global variables of sampler type are translated to function calls,
5068   // therefore no need to be translated.
5069   QualType ASTTy = D->getType();
5070   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
5071     return;
5072 
5073   // If this is OpenMP device, check if it is legal to emit this global
5074   // normally.
5075   if (LangOpts.OpenMPIsTargetDevice && OpenMPRuntime &&
5076       OpenMPRuntime->emitTargetGlobalVariable(D))
5077     return;
5078 
5079   llvm::TrackingVH<llvm::Constant> Init;
5080   bool NeedsGlobalCtor = false;
5081   // Whether the definition of the variable is available externally.
5082   // If yes, we shouldn't emit the GloablCtor and GlobalDtor for the variable
5083   // since this is the job for its original source.
5084   bool IsDefinitionAvailableExternally =
5085       getContext().GetGVALinkageForVariable(D) == GVA_AvailableExternally;
5086   bool NeedsGlobalDtor =
5087       !IsDefinitionAvailableExternally &&
5088       D->needsDestruction(getContext()) == QualType::DK_cxx_destructor;
5089 
5090   const VarDecl *InitDecl;
5091   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
5092 
5093   std::optional<ConstantEmitter> emitter;
5094 
5095   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
5096   // as part of their declaration."  Sema has already checked for
5097   // error cases, so we just need to set Init to UndefValue.
5098   bool IsCUDASharedVar =
5099       getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
5100   // Shadows of initialized device-side global variables are also left
5101   // undefined.
5102   // Managed Variables should be initialized on both host side and device side.
5103   bool IsCUDAShadowVar =
5104       !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
5105       (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
5106        D->hasAttr<CUDASharedAttr>());
5107   bool IsCUDADeviceShadowVar =
5108       getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
5109       (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
5110        D->getType()->isCUDADeviceBuiltinTextureType());
5111   if (getLangOpts().CUDA &&
5112       (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar))
5113     Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
5114   else if (D->hasAttr<LoaderUninitializedAttr>())
5115     Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
5116   else if (!InitExpr) {
5117     // This is a tentative definition; tentative definitions are
5118     // implicitly initialized with { 0 }.
5119     //
5120     // Note that tentative definitions are only emitted at the end of
5121     // a translation unit, so they should never have incomplete
5122     // type. In addition, EmitTentativeDefinition makes sure that we
5123     // never attempt to emit a tentative definition if a real one
5124     // exists. A use may still exists, however, so we still may need
5125     // to do a RAUW.
5126     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
5127     Init = EmitNullConstant(D->getType());
5128   } else {
5129     initializedGlobalDecl = GlobalDecl(D);
5130     emitter.emplace(*this);
5131     llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl);
5132     if (!Initializer) {
5133       QualType T = InitExpr->getType();
5134       if (D->getType()->isReferenceType())
5135         T = D->getType();
5136 
5137       if (getLangOpts().CPlusPlus) {
5138         if (InitDecl->hasFlexibleArrayInit(getContext()))
5139           ErrorUnsupported(D, "flexible array initializer");
5140         Init = EmitNullConstant(T);
5141 
5142         if (!IsDefinitionAvailableExternally)
5143           NeedsGlobalCtor = true;
5144       } else {
5145         ErrorUnsupported(D, "static initializer");
5146         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
5147       }
5148     } else {
5149       Init = Initializer;
5150       // We don't need an initializer, so remove the entry for the delayed
5151       // initializer position (just in case this entry was delayed) if we
5152       // also don't need to register a destructor.
5153       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
5154         DelayedCXXInitPosition.erase(D);
5155 
5156 #ifndef NDEBUG
5157       CharUnits VarSize = getContext().getTypeSizeInChars(ASTTy) +
5158                           InitDecl->getFlexibleArrayInitChars(getContext());
5159       CharUnits CstSize = CharUnits::fromQuantity(
5160           getDataLayout().getTypeAllocSize(Init->getType()));
5161       assert(VarSize == CstSize && "Emitted constant has unexpected size");
5162 #endif
5163     }
5164   }
5165 
5166   llvm::Type* InitType = Init->getType();
5167   llvm::Constant *Entry =
5168       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
5169 
5170   // Strip off pointer casts if we got them.
5171   Entry = Entry->stripPointerCasts();
5172 
5173   // Entry is now either a Function or GlobalVariable.
5174   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
5175 
5176   // We have a definition after a declaration with the wrong type.
5177   // We must make a new GlobalVariable* and update everything that used OldGV
5178   // (a declaration or tentative definition) with the new GlobalVariable*
5179   // (which will be a definition).
5180   //
5181   // This happens if there is a prototype for a global (e.g.
5182   // "extern int x[];") and then a definition of a different type (e.g.
5183   // "int x[10];"). This also happens when an initializer has a different type
5184   // from the type of the global (this happens with unions).
5185   if (!GV || GV->getValueType() != InitType ||
5186       GV->getType()->getAddressSpace() !=
5187           getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
5188 
5189     // Move the old entry aside so that we'll create a new one.
5190     Entry->setName(StringRef());
5191 
5192     // Make a new global with the correct type, this is now guaranteed to work.
5193     GV = cast<llvm::GlobalVariable>(
5194         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))
5195             ->stripPointerCasts());
5196 
5197     // Replace all uses of the old global with the new global
5198     llvm::Constant *NewPtrForOldDecl =
5199         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
5200                                                              Entry->getType());
5201     Entry->replaceAllUsesWith(NewPtrForOldDecl);
5202 
5203     // Erase the old global, since it is no longer used.
5204     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
5205   }
5206 
5207   MaybeHandleStaticInExternC(D, GV);
5208 
5209   if (D->hasAttr<AnnotateAttr>())
5210     AddGlobalAnnotations(D, GV);
5211 
5212   // Set the llvm linkage type as appropriate.
5213   llvm::GlobalValue::LinkageTypes Linkage = getLLVMLinkageVarDefinition(D);
5214 
5215   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
5216   // the device. [...]"
5217   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
5218   // __device__, declares a variable that: [...]
5219   // Is accessible from all the threads within the grid and from the host
5220   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
5221   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
5222   if (LangOpts.CUDA) {
5223     if (LangOpts.CUDAIsDevice) {
5224       if (Linkage != llvm::GlobalValue::InternalLinkage &&
5225           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
5226            D->getType()->isCUDADeviceBuiltinSurfaceType() ||
5227            D->getType()->isCUDADeviceBuiltinTextureType()))
5228         GV->setExternallyInitialized(true);
5229     } else {
5230       getCUDARuntime().internalizeDeviceSideVar(D, Linkage);
5231     }
5232     getCUDARuntime().handleVarRegistration(D, *GV);
5233   }
5234 
5235   GV->setInitializer(Init);
5236   if (emitter)
5237     emitter->finalize(GV);
5238 
5239   // If it is safe to mark the global 'constant', do so now.
5240   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
5241                   D->getType().isConstantStorage(getContext(), true, true));
5242 
5243   // If it is in a read-only section, mark it 'constant'.
5244   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
5245     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
5246     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
5247       GV->setConstant(true);
5248   }
5249 
5250   CharUnits AlignVal = getContext().getDeclAlign(D);
5251   // Check for alignment specifed in an 'omp allocate' directive.
5252   if (std::optional<CharUnits> AlignValFromAllocate =
5253           getOMPAllocateAlignment(D))
5254     AlignVal = *AlignValFromAllocate;
5255   GV->setAlignment(AlignVal.getAsAlign());
5256 
5257   // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper
5258   // function is only defined alongside the variable, not also alongside
5259   // callers. Normally, all accesses to a thread_local go through the
5260   // thread-wrapper in order to ensure initialization has occurred, underlying
5261   // variable will never be used other than the thread-wrapper, so it can be
5262   // converted to internal linkage.
5263   //
5264   // However, if the variable has the 'constinit' attribute, it _can_ be
5265   // referenced directly, without calling the thread-wrapper, so the linkage
5266   // must not be changed.
5267   //
5268   // Additionally, if the variable isn't plain external linkage, e.g. if it's
5269   // weak or linkonce, the de-duplication semantics are important to preserve,
5270   // so we don't change the linkage.
5271   if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
5272       Linkage == llvm::GlobalValue::ExternalLinkage &&
5273       Context.getTargetInfo().getTriple().isOSDarwin() &&
5274       !D->hasAttr<ConstInitAttr>())
5275     Linkage = llvm::GlobalValue::InternalLinkage;
5276 
5277   GV->setLinkage(Linkage);
5278   if (D->hasAttr<DLLImportAttr>())
5279     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
5280   else if (D->hasAttr<DLLExportAttr>())
5281     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
5282   else
5283     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
5284 
5285   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
5286     // common vars aren't constant even if declared const.
5287     GV->setConstant(false);
5288     // Tentative definition of global variables may be initialized with
5289     // non-zero null pointers. In this case they should have weak linkage
5290     // since common linkage must have zero initializer and must not have
5291     // explicit section therefore cannot have non-zero initial value.
5292     if (!GV->getInitializer()->isNullValue())
5293       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
5294   }
5295 
5296   setNonAliasAttributes(D, GV);
5297 
5298   if (D->getTLSKind() && !GV->isThreadLocal()) {
5299     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
5300       CXXThreadLocals.push_back(D);
5301     setTLSMode(GV, *D);
5302   }
5303 
5304   maybeSetTrivialComdat(*D, *GV);
5305 
5306   // Emit the initializer function if necessary.
5307   if (NeedsGlobalCtor || NeedsGlobalDtor)
5308     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
5309 
5310   SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor);
5311 
5312   // Emit global variable debug information.
5313   if (CGDebugInfo *DI = getModuleDebugInfo())
5314     if (getCodeGenOpts().hasReducedDebugInfo())
5315       DI->EmitGlobalVariable(GV, D);
5316 }
5317 
5318 void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) {
5319   if (CGDebugInfo *DI = getModuleDebugInfo())
5320     if (getCodeGenOpts().hasReducedDebugInfo()) {
5321       QualType ASTTy = D->getType();
5322       llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
5323       llvm::Constant *GV =
5324           GetOrCreateLLVMGlobal(D->getName(), Ty, ASTTy.getAddressSpace(), D);
5325       DI->EmitExternalVariable(
5326           cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D);
5327     }
5328 }
5329 
5330 static bool isVarDeclStrongDefinition(const ASTContext &Context,
5331                                       CodeGenModule &CGM, const VarDecl *D,
5332                                       bool NoCommon) {
5333   // Don't give variables common linkage if -fno-common was specified unless it
5334   // was overridden by a NoCommon attribute.
5335   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
5336     return true;
5337 
5338   // C11 6.9.2/2:
5339   //   A declaration of an identifier for an object that has file scope without
5340   //   an initializer, and without a storage-class specifier or with the
5341   //   storage-class specifier static, constitutes a tentative definition.
5342   if (D->getInit() || D->hasExternalStorage())
5343     return true;
5344 
5345   // A variable cannot be both common and exist in a section.
5346   if (D->hasAttr<SectionAttr>())
5347     return true;
5348 
5349   // A variable cannot be both common and exist in a section.
5350   // We don't try to determine which is the right section in the front-end.
5351   // If no specialized section name is applicable, it will resort to default.
5352   if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
5353       D->hasAttr<PragmaClangDataSectionAttr>() ||
5354       D->hasAttr<PragmaClangRelroSectionAttr>() ||
5355       D->hasAttr<PragmaClangRodataSectionAttr>())
5356     return true;
5357 
5358   // Thread local vars aren't considered common linkage.
5359   if (D->getTLSKind())
5360     return true;
5361 
5362   // Tentative definitions marked with WeakImportAttr are true definitions.
5363   if (D->hasAttr<WeakImportAttr>())
5364     return true;
5365 
5366   // A variable cannot be both common and exist in a comdat.
5367   if (shouldBeInCOMDAT(CGM, *D))
5368     return true;
5369 
5370   // Declarations with a required alignment do not have common linkage in MSVC
5371   // mode.
5372   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5373     if (D->hasAttr<AlignedAttr>())
5374       return true;
5375     QualType VarType = D->getType();
5376     if (Context.isAlignmentRequired(VarType))
5377       return true;
5378 
5379     if (const auto *RT = VarType->getAs<RecordType>()) {
5380       const RecordDecl *RD = RT->getDecl();
5381       for (const FieldDecl *FD : RD->fields()) {
5382         if (FD->isBitField())
5383           continue;
5384         if (FD->hasAttr<AlignedAttr>())
5385           return true;
5386         if (Context.isAlignmentRequired(FD->getType()))
5387           return true;
5388       }
5389     }
5390   }
5391 
5392   // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
5393   // common symbols, so symbols with greater alignment requirements cannot be
5394   // common.
5395   // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
5396   // alignments for common symbols via the aligncomm directive, so this
5397   // restriction only applies to MSVC environments.
5398   if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
5399       Context.getTypeAlignIfKnown(D->getType()) >
5400           Context.toBits(CharUnits::fromQuantity(32)))
5401     return true;
5402 
5403   return false;
5404 }
5405 
5406 llvm::GlobalValue::LinkageTypes
5407 CodeGenModule::getLLVMLinkageForDeclarator(const DeclaratorDecl *D,
5408                                            GVALinkage Linkage) {
5409   if (Linkage == GVA_Internal)
5410     return llvm::Function::InternalLinkage;
5411 
5412   if (D->hasAttr<WeakAttr>())
5413     return llvm::GlobalVariable::WeakAnyLinkage;
5414 
5415   if (const auto *FD = D->getAsFunction())
5416     if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
5417       return llvm::GlobalVariable::LinkOnceAnyLinkage;
5418 
5419   // We are guaranteed to have a strong definition somewhere else,
5420   // so we can use available_externally linkage.
5421   if (Linkage == GVA_AvailableExternally)
5422     return llvm::GlobalValue::AvailableExternallyLinkage;
5423 
5424   // Note that Apple's kernel linker doesn't support symbol
5425   // coalescing, so we need to avoid linkonce and weak linkages there.
5426   // Normally, this means we just map to internal, but for explicit
5427   // instantiations we'll map to external.
5428 
5429   // In C++, the compiler has to emit a definition in every translation unit
5430   // that references the function.  We should use linkonce_odr because
5431   // a) if all references in this translation unit are optimized away, we
5432   // don't need to codegen it.  b) if the function persists, it needs to be
5433   // merged with other definitions. c) C++ has the ODR, so we know the
5434   // definition is dependable.
5435   if (Linkage == GVA_DiscardableODR)
5436     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
5437                                             : llvm::Function::InternalLinkage;
5438 
5439   // An explicit instantiation of a template has weak linkage, since
5440   // explicit instantiations can occur in multiple translation units
5441   // and must all be equivalent. However, we are not allowed to
5442   // throw away these explicit instantiations.
5443   //
5444   // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU,
5445   // so say that CUDA templates are either external (for kernels) or internal.
5446   // This lets llvm perform aggressive inter-procedural optimizations. For
5447   // -fgpu-rdc case, device function calls across multiple TU's are allowed,
5448   // therefore we need to follow the normal linkage paradigm.
5449   if (Linkage == GVA_StrongODR) {
5450     if (getLangOpts().AppleKext)
5451       return llvm::Function::ExternalLinkage;
5452     if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
5453         !getLangOpts().GPURelocatableDeviceCode)
5454       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
5455                                           : llvm::Function::InternalLinkage;
5456     return llvm::Function::WeakODRLinkage;
5457   }
5458 
5459   // C++ doesn't have tentative definitions and thus cannot have common
5460   // linkage.
5461   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
5462       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
5463                                  CodeGenOpts.NoCommon))
5464     return llvm::GlobalVariable::CommonLinkage;
5465 
5466   // selectany symbols are externally visible, so use weak instead of
5467   // linkonce.  MSVC optimizes away references to const selectany globals, so
5468   // all definitions should be the same and ODR linkage should be used.
5469   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
5470   if (D->hasAttr<SelectAnyAttr>())
5471     return llvm::GlobalVariable::WeakODRLinkage;
5472 
5473   // Otherwise, we have strong external linkage.
5474   assert(Linkage == GVA_StrongExternal);
5475   return llvm::GlobalVariable::ExternalLinkage;
5476 }
5477 
5478 llvm::GlobalValue::LinkageTypes
5479 CodeGenModule::getLLVMLinkageVarDefinition(const VarDecl *VD) {
5480   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
5481   return getLLVMLinkageForDeclarator(VD, Linkage);
5482 }
5483 
5484 /// Replace the uses of a function that was declared with a non-proto type.
5485 /// We want to silently drop extra arguments from call sites
5486 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
5487                                           llvm::Function *newFn) {
5488   // Fast path.
5489   if (old->use_empty()) return;
5490 
5491   llvm::Type *newRetTy = newFn->getReturnType();
5492   SmallVector<llvm::Value*, 4> newArgs;
5493 
5494   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
5495          ui != ue; ) {
5496     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
5497     llvm::User *user = use->getUser();
5498 
5499     // Recognize and replace uses of bitcasts.  Most calls to
5500     // unprototyped functions will use bitcasts.
5501     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
5502       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
5503         replaceUsesOfNonProtoConstant(bitcast, newFn);
5504       continue;
5505     }
5506 
5507     // Recognize calls to the function.
5508     llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
5509     if (!callSite) continue;
5510     if (!callSite->isCallee(&*use))
5511       continue;
5512 
5513     // If the return types don't match exactly, then we can't
5514     // transform this call unless it's dead.
5515     if (callSite->getType() != newRetTy && !callSite->use_empty())
5516       continue;
5517 
5518     // Get the call site's attribute list.
5519     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
5520     llvm::AttributeList oldAttrs = callSite->getAttributes();
5521 
5522     // If the function was passed too few arguments, don't transform.
5523     unsigned newNumArgs = newFn->arg_size();
5524     if (callSite->arg_size() < newNumArgs)
5525       continue;
5526 
5527     // If extra arguments were passed, we silently drop them.
5528     // If any of the types mismatch, we don't transform.
5529     unsigned argNo = 0;
5530     bool dontTransform = false;
5531     for (llvm::Argument &A : newFn->args()) {
5532       if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
5533         dontTransform = true;
5534         break;
5535       }
5536 
5537       // Add any parameter attributes.
5538       newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
5539       argNo++;
5540     }
5541     if (dontTransform)
5542       continue;
5543 
5544     // Okay, we can transform this.  Create the new call instruction and copy
5545     // over the required information.
5546     newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
5547 
5548     // Copy over any operand bundles.
5549     SmallVector<llvm::OperandBundleDef, 1> newBundles;
5550     callSite->getOperandBundlesAsDefs(newBundles);
5551 
5552     llvm::CallBase *newCall;
5553     if (isa<llvm::CallInst>(callSite)) {
5554       newCall =
5555           llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
5556     } else {
5557       auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
5558       newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
5559                                          oldInvoke->getUnwindDest(), newArgs,
5560                                          newBundles, "", callSite);
5561     }
5562     newArgs.clear(); // for the next iteration
5563 
5564     if (!newCall->getType()->isVoidTy())
5565       newCall->takeName(callSite);
5566     newCall->setAttributes(
5567         llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
5568                                  oldAttrs.getRetAttrs(), newArgAttrs));
5569     newCall->setCallingConv(callSite->getCallingConv());
5570 
5571     // Finally, remove the old call, replacing any uses with the new one.
5572     if (!callSite->use_empty())
5573       callSite->replaceAllUsesWith(newCall);
5574 
5575     // Copy debug location attached to CI.
5576     if (callSite->getDebugLoc())
5577       newCall->setDebugLoc(callSite->getDebugLoc());
5578 
5579     callSite->eraseFromParent();
5580   }
5581 }
5582 
5583 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
5584 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
5585 /// existing call uses of the old function in the module, this adjusts them to
5586 /// call the new function directly.
5587 ///
5588 /// This is not just a cleanup: the always_inline pass requires direct calls to
5589 /// functions to be able to inline them.  If there is a bitcast in the way, it
5590 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
5591 /// run at -O0.
5592 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
5593                                                       llvm::Function *NewFn) {
5594   // If we're redefining a global as a function, don't transform it.
5595   if (!isa<llvm::Function>(Old)) return;
5596 
5597   replaceUsesOfNonProtoConstant(Old, NewFn);
5598 }
5599 
5600 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
5601   auto DK = VD->isThisDeclarationADefinition();
5602   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
5603     return;
5604 
5605   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
5606   // If we have a definition, this might be a deferred decl. If the
5607   // instantiation is explicit, make sure we emit it at the end.
5608   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
5609     GetAddrOfGlobalVar(VD);
5610 
5611   EmitTopLevelDecl(VD);
5612 }
5613 
5614 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
5615                                                  llvm::GlobalValue *GV) {
5616   const auto *D = cast<FunctionDecl>(GD.getDecl());
5617 
5618   // Compute the function info and LLVM type.
5619   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
5620   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
5621 
5622   // Get or create the prototype for the function.
5623   if (!GV || (GV->getValueType() != Ty))
5624     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
5625                                                    /*DontDefer=*/true,
5626                                                    ForDefinition));
5627 
5628   // Already emitted.
5629   if (!GV->isDeclaration())
5630     return;
5631 
5632   // We need to set linkage and visibility on the function before
5633   // generating code for it because various parts of IR generation
5634   // want to propagate this information down (e.g. to local static
5635   // declarations).
5636   auto *Fn = cast<llvm::Function>(GV);
5637   setFunctionLinkage(GD, Fn);
5638 
5639   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
5640   setGVProperties(Fn, GD);
5641 
5642   MaybeHandleStaticInExternC(D, Fn);
5643 
5644   maybeSetTrivialComdat(*D, *Fn);
5645 
5646   CodeGenFunction(*this).GenerateCode(GD, Fn, FI);
5647 
5648   setNonAliasAttributes(GD, Fn);
5649   SetLLVMFunctionAttributesForDefinition(D, Fn);
5650 
5651   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
5652     AddGlobalCtor(Fn, CA->getPriority());
5653   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
5654     AddGlobalDtor(Fn, DA->getPriority(), true);
5655   if (D->hasAttr<AnnotateAttr>())
5656     AddGlobalAnnotations(D, Fn);
5657   if (getLangOpts().OpenMP && D->hasAttr<OMPDeclareTargetDeclAttr>())
5658     getOpenMPRuntime().emitDeclareTargetFunction(D, GV);
5659 }
5660 
5661 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
5662   const auto *D = cast<ValueDecl>(GD.getDecl());
5663   const AliasAttr *AA = D->getAttr<AliasAttr>();
5664   assert(AA && "Not an alias?");
5665 
5666   StringRef MangledName = getMangledName(GD);
5667 
5668   if (AA->getAliasee() == MangledName) {
5669     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
5670     return;
5671   }
5672 
5673   // If there is a definition in the module, then it wins over the alias.
5674   // This is dubious, but allow it to be safe.  Just ignore the alias.
5675   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
5676   if (Entry && !Entry->isDeclaration())
5677     return;
5678 
5679   Aliases.push_back(GD);
5680 
5681   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
5682 
5683   // Create a reference to the named value.  This ensures that it is emitted
5684   // if a deferred decl.
5685   llvm::Constant *Aliasee;
5686   llvm::GlobalValue::LinkageTypes LT;
5687   if (isa<llvm::FunctionType>(DeclTy)) {
5688     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
5689                                       /*ForVTable=*/false);
5690     LT = getFunctionLinkage(GD);
5691   } else {
5692     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
5693                                     /*D=*/nullptr);
5694     if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl()))
5695       LT = getLLVMLinkageVarDefinition(VD);
5696     else
5697       LT = getFunctionLinkage(GD);
5698   }
5699 
5700   // Create the new alias itself, but don't set a name yet.
5701   unsigned AS = Aliasee->getType()->getPointerAddressSpace();
5702   auto *GA =
5703       llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule());
5704 
5705   if (Entry) {
5706     if (GA->getAliasee() == Entry) {
5707       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
5708       return;
5709     }
5710 
5711     assert(Entry->isDeclaration());
5712 
5713     // If there is a declaration in the module, then we had an extern followed
5714     // by the alias, as in:
5715     //   extern int test6();
5716     //   ...
5717     //   int test6() __attribute__((alias("test7")));
5718     //
5719     // Remove it and replace uses of it with the alias.
5720     GA->takeName(Entry);
5721 
5722     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
5723                                                           Entry->getType()));
5724     Entry->eraseFromParent();
5725   } else {
5726     GA->setName(MangledName);
5727   }
5728 
5729   // Set attributes which are particular to an alias; this is a
5730   // specialization of the attributes which may be set on a global
5731   // variable/function.
5732   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
5733       D->isWeakImported()) {
5734     GA->setLinkage(llvm::Function::WeakAnyLinkage);
5735   }
5736 
5737   if (const auto *VD = dyn_cast<VarDecl>(D))
5738     if (VD->getTLSKind())
5739       setTLSMode(GA, *VD);
5740 
5741   SetCommonAttributes(GD, GA);
5742 
5743   // Emit global alias debug information.
5744   if (isa<VarDecl>(D))
5745     if (CGDebugInfo *DI = getModuleDebugInfo())
5746       DI->EmitGlobalAlias(cast<llvm::GlobalValue>(GA->getAliasee()->stripPointerCasts()), GD);
5747 }
5748 
5749 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
5750   const auto *D = cast<ValueDecl>(GD.getDecl());
5751   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
5752   assert(IFA && "Not an ifunc?");
5753 
5754   StringRef MangledName = getMangledName(GD);
5755 
5756   if (IFA->getResolver() == MangledName) {
5757     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
5758     return;
5759   }
5760 
5761   // Report an error if some definition overrides ifunc.
5762   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
5763   if (Entry && !Entry->isDeclaration()) {
5764     GlobalDecl OtherGD;
5765     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
5766         DiagnosedConflictingDefinitions.insert(GD).second) {
5767       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
5768           << MangledName;
5769       Diags.Report(OtherGD.getDecl()->getLocation(),
5770                    diag::note_previous_definition);
5771     }
5772     return;
5773   }
5774 
5775   Aliases.push_back(GD);
5776 
5777   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
5778   llvm::Type *ResolverTy = llvm::GlobalIFunc::getResolverFunctionType(DeclTy);
5779   llvm::Constant *Resolver =
5780       GetOrCreateLLVMFunction(IFA->getResolver(), ResolverTy, {},
5781                               /*ForVTable=*/false);
5782   llvm::GlobalIFunc *GIF =
5783       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
5784                                 "", Resolver, &getModule());
5785   if (Entry) {
5786     if (GIF->getResolver() == Entry) {
5787       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
5788       return;
5789     }
5790     assert(Entry->isDeclaration());
5791 
5792     // If there is a declaration in the module, then we had an extern followed
5793     // by the ifunc, as in:
5794     //   extern int test();
5795     //   ...
5796     //   int test() __attribute__((ifunc("resolver")));
5797     //
5798     // Remove it and replace uses of it with the ifunc.
5799     GIF->takeName(Entry);
5800 
5801     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
5802                                                           Entry->getType()));
5803     Entry->eraseFromParent();
5804   } else
5805     GIF->setName(MangledName);
5806   if (auto *F = dyn_cast<llvm::Function>(Resolver)) {
5807     F->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation);
5808   }
5809   SetCommonAttributes(GD, GIF);
5810 }
5811 
5812 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
5813                                             ArrayRef<llvm::Type*> Tys) {
5814   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
5815                                          Tys);
5816 }
5817 
5818 static llvm::StringMapEntry<llvm::GlobalVariable *> &
5819 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
5820                          const StringLiteral *Literal, bool TargetIsLSB,
5821                          bool &IsUTF16, unsigned &StringLength) {
5822   StringRef String = Literal->getString();
5823   unsigned NumBytes = String.size();
5824 
5825   // Check for simple case.
5826   if (!Literal->containsNonAsciiOrNull()) {
5827     StringLength = NumBytes;
5828     return *Map.insert(std::make_pair(String, nullptr)).first;
5829   }
5830 
5831   // Otherwise, convert the UTF8 literals into a string of shorts.
5832   IsUTF16 = true;
5833 
5834   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
5835   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5836   llvm::UTF16 *ToPtr = &ToBuf[0];
5837 
5838   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5839                                  ToPtr + NumBytes, llvm::strictConversion);
5840 
5841   // ConvertUTF8toUTF16 returns the length in ToPtr.
5842   StringLength = ToPtr - &ToBuf[0];
5843 
5844   // Add an explicit null.
5845   *ToPtr = 0;
5846   return *Map.insert(std::make_pair(
5847                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
5848                                    (StringLength + 1) * 2),
5849                          nullptr)).first;
5850 }
5851 
5852 ConstantAddress
5853 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
5854   unsigned StringLength = 0;
5855   bool isUTF16 = false;
5856   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
5857       GetConstantCFStringEntry(CFConstantStringMap, Literal,
5858                                getDataLayout().isLittleEndian(), isUTF16,
5859                                StringLength);
5860 
5861   if (auto *C = Entry.second)
5862     return ConstantAddress(
5863         C, C->getValueType(), CharUnits::fromQuantity(C->getAlignment()));
5864 
5865   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
5866   llvm::Constant *Zeros[] = { Zero, Zero };
5867 
5868   const ASTContext &Context = getContext();
5869   const llvm::Triple &Triple = getTriple();
5870 
5871   const auto CFRuntime = getLangOpts().CFRuntime;
5872   const bool IsSwiftABI =
5873       static_cast<unsigned>(CFRuntime) >=
5874       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
5875   const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
5876 
5877   // If we don't already have it, get __CFConstantStringClassReference.
5878   if (!CFConstantStringClassRef) {
5879     const char *CFConstantStringClassName = "__CFConstantStringClassReference";
5880     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
5881     Ty = llvm::ArrayType::get(Ty, 0);
5882 
5883     switch (CFRuntime) {
5884     default: break;
5885     case LangOptions::CoreFoundationABI::Swift: [[fallthrough]];
5886     case LangOptions::CoreFoundationABI::Swift5_0:
5887       CFConstantStringClassName =
5888           Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
5889                               : "$s10Foundation19_NSCFConstantStringCN";
5890       Ty = IntPtrTy;
5891       break;
5892     case LangOptions::CoreFoundationABI::Swift4_2:
5893       CFConstantStringClassName =
5894           Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
5895                               : "$S10Foundation19_NSCFConstantStringCN";
5896       Ty = IntPtrTy;
5897       break;
5898     case LangOptions::CoreFoundationABI::Swift4_1:
5899       CFConstantStringClassName =
5900           Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
5901                               : "__T010Foundation19_NSCFConstantStringCN";
5902       Ty = IntPtrTy;
5903       break;
5904     }
5905 
5906     llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
5907 
5908     if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
5909       llvm::GlobalValue *GV = nullptr;
5910 
5911       if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
5912         IdentifierInfo &II = Context.Idents.get(GV->getName());
5913         TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
5914         DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
5915 
5916         const VarDecl *VD = nullptr;
5917         for (const auto *Result : DC->lookup(&II))
5918           if ((VD = dyn_cast<VarDecl>(Result)))
5919             break;
5920 
5921         if (Triple.isOSBinFormatELF()) {
5922           if (!VD)
5923             GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
5924         } else {
5925           GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
5926           if (!VD || !VD->hasAttr<DLLExportAttr>())
5927             GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
5928           else
5929             GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
5930         }
5931 
5932         setDSOLocal(GV);
5933       }
5934     }
5935 
5936     // Decay array -> ptr
5937     CFConstantStringClassRef =
5938         IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
5939                    : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
5940   }
5941 
5942   QualType CFTy = Context.getCFConstantStringType();
5943 
5944   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
5945 
5946   ConstantInitBuilder Builder(*this);
5947   auto Fields = Builder.beginStruct(STy);
5948 
5949   // Class pointer.
5950   Fields.add(cast<llvm::Constant>(CFConstantStringClassRef));
5951 
5952   // Flags.
5953   if (IsSwiftABI) {
5954     Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
5955     Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
5956   } else {
5957     Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
5958   }
5959 
5960   // String pointer.
5961   llvm::Constant *C = nullptr;
5962   if (isUTF16) {
5963     auto Arr = llvm::ArrayRef(
5964         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
5965         Entry.first().size() / 2);
5966     C = llvm::ConstantDataArray::get(VMContext, Arr);
5967   } else {
5968     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
5969   }
5970 
5971   // Note: -fwritable-strings doesn't make the backing store strings of
5972   // CFStrings writable.
5973   auto *GV =
5974       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
5975                                llvm::GlobalValue::PrivateLinkage, C, ".str");
5976   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
5977   // Don't enforce the target's minimum global alignment, since the only use
5978   // of the string is via this class initializer.
5979   CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
5980                             : Context.getTypeAlignInChars(Context.CharTy);
5981   GV->setAlignment(Align.getAsAlign());
5982 
5983   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
5984   // Without it LLVM can merge the string with a non unnamed_addr one during
5985   // LTO.  Doing that changes the section it ends in, which surprises ld64.
5986   if (Triple.isOSBinFormatMachO())
5987     GV->setSection(isUTF16 ? "__TEXT,__ustring"
5988                            : "__TEXT,__cstring,cstring_literals");
5989   // Make sure the literal ends up in .rodata to allow for safe ICF and for
5990   // the static linker to adjust permissions to read-only later on.
5991   else if (Triple.isOSBinFormatELF())
5992     GV->setSection(".rodata");
5993 
5994   // String.
5995   llvm::Constant *Str =
5996       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
5997 
5998   if (isUTF16)
5999     // Cast the UTF16 string to the correct type.
6000     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
6001   Fields.add(Str);
6002 
6003   // String length.
6004   llvm::IntegerType *LengthTy =
6005       llvm::IntegerType::get(getModule().getContext(),
6006                              Context.getTargetInfo().getLongWidth());
6007   if (IsSwiftABI) {
6008     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
6009         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
6010       LengthTy = Int32Ty;
6011     else
6012       LengthTy = IntPtrTy;
6013   }
6014   Fields.addInt(LengthTy, StringLength);
6015 
6016   // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is
6017   // properly aligned on 32-bit platforms.
6018   CharUnits Alignment =
6019       IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign();
6020 
6021   // The struct.
6022   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
6023                                     /*isConstant=*/false,
6024                                     llvm::GlobalVariable::PrivateLinkage);
6025   GV->addAttribute("objc_arc_inert");
6026   switch (Triple.getObjectFormat()) {
6027   case llvm::Triple::UnknownObjectFormat:
6028     llvm_unreachable("unknown file format");
6029   case llvm::Triple::DXContainer:
6030   case llvm::Triple::GOFF:
6031   case llvm::Triple::SPIRV:
6032   case llvm::Triple::XCOFF:
6033     llvm_unreachable("unimplemented");
6034   case llvm::Triple::COFF:
6035   case llvm::Triple::ELF:
6036   case llvm::Triple::Wasm:
6037     GV->setSection("cfstring");
6038     break;
6039   case llvm::Triple::MachO:
6040     GV->setSection("__DATA,__cfstring");
6041     break;
6042   }
6043   Entry.second = GV;
6044 
6045   return ConstantAddress(GV, GV->getValueType(), Alignment);
6046 }
6047 
6048 bool CodeGenModule::getExpressionLocationsEnabled() const {
6049   return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
6050 }
6051 
6052 QualType CodeGenModule::getObjCFastEnumerationStateType() {
6053   if (ObjCFastEnumerationStateType.isNull()) {
6054     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
6055     D->startDefinition();
6056 
6057     QualType FieldTypes[] = {
6058       Context.UnsignedLongTy,
6059       Context.getPointerType(Context.getObjCIdType()),
6060       Context.getPointerType(Context.UnsignedLongTy),
6061       Context.getConstantArrayType(Context.UnsignedLongTy,
6062                            llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0)
6063     };
6064 
6065     for (size_t i = 0; i < 4; ++i) {
6066       FieldDecl *Field = FieldDecl::Create(Context,
6067                                            D,
6068                                            SourceLocation(),
6069                                            SourceLocation(), nullptr,
6070                                            FieldTypes[i], /*TInfo=*/nullptr,
6071                                            /*BitWidth=*/nullptr,
6072                                            /*Mutable=*/false,
6073                                            ICIS_NoInit);
6074       Field->setAccess(AS_public);
6075       D->addDecl(Field);
6076     }
6077 
6078     D->completeDefinition();
6079     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
6080   }
6081 
6082   return ObjCFastEnumerationStateType;
6083 }
6084 
6085 llvm::Constant *
6086 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
6087   assert(!E->getType()->isPointerType() && "Strings are always arrays");
6088 
6089   // Don't emit it as the address of the string, emit the string data itself
6090   // as an inline array.
6091   if (E->getCharByteWidth() == 1) {
6092     SmallString<64> Str(E->getString());
6093 
6094     // Resize the string to the right size, which is indicated by its type.
6095     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
6096     assert(CAT && "String literal not of constant array type!");
6097     Str.resize(CAT->getSize().getZExtValue());
6098     return llvm::ConstantDataArray::getString(VMContext, Str, false);
6099   }
6100 
6101   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
6102   llvm::Type *ElemTy = AType->getElementType();
6103   unsigned NumElements = AType->getNumElements();
6104 
6105   // Wide strings have either 2-byte or 4-byte elements.
6106   if (ElemTy->getPrimitiveSizeInBits() == 16) {
6107     SmallVector<uint16_t, 32> Elements;
6108     Elements.reserve(NumElements);
6109 
6110     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
6111       Elements.push_back(E->getCodeUnit(i));
6112     Elements.resize(NumElements);
6113     return llvm::ConstantDataArray::get(VMContext, Elements);
6114   }
6115 
6116   assert(ElemTy->getPrimitiveSizeInBits() == 32);
6117   SmallVector<uint32_t, 32> Elements;
6118   Elements.reserve(NumElements);
6119 
6120   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
6121     Elements.push_back(E->getCodeUnit(i));
6122   Elements.resize(NumElements);
6123   return llvm::ConstantDataArray::get(VMContext, Elements);
6124 }
6125 
6126 static llvm::GlobalVariable *
6127 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
6128                       CodeGenModule &CGM, StringRef GlobalName,
6129                       CharUnits Alignment) {
6130   unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
6131       CGM.GetGlobalConstantAddressSpace());
6132 
6133   llvm::Module &M = CGM.getModule();
6134   // Create a global variable for this string
6135   auto *GV = new llvm::GlobalVariable(
6136       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
6137       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
6138   GV->setAlignment(Alignment.getAsAlign());
6139   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
6140   if (GV->isWeakForLinker()) {
6141     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
6142     GV->setComdat(M.getOrInsertComdat(GV->getName()));
6143   }
6144   CGM.setDSOLocal(GV);
6145 
6146   return GV;
6147 }
6148 
6149 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
6150 /// constant array for the given string literal.
6151 ConstantAddress
6152 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
6153                                                   StringRef Name) {
6154   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
6155 
6156   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
6157   llvm::GlobalVariable **Entry = nullptr;
6158   if (!LangOpts.WritableStrings) {
6159     Entry = &ConstantStringMap[C];
6160     if (auto GV = *Entry) {
6161       if (uint64_t(Alignment.getQuantity()) > GV->getAlignment())
6162         GV->setAlignment(Alignment.getAsAlign());
6163       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
6164                              GV->getValueType(), Alignment);
6165     }
6166   }
6167 
6168   SmallString<256> MangledNameBuffer;
6169   StringRef GlobalVariableName;
6170   llvm::GlobalValue::LinkageTypes LT;
6171 
6172   // Mangle the string literal if that's how the ABI merges duplicate strings.
6173   // Don't do it if they are writable, since we don't want writes in one TU to
6174   // affect strings in another.
6175   if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
6176       !LangOpts.WritableStrings) {
6177     llvm::raw_svector_ostream Out(MangledNameBuffer);
6178     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
6179     LT = llvm::GlobalValue::LinkOnceODRLinkage;
6180     GlobalVariableName = MangledNameBuffer;
6181   } else {
6182     LT = llvm::GlobalValue::PrivateLinkage;
6183     GlobalVariableName = Name;
6184   }
6185 
6186   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
6187 
6188   CGDebugInfo *DI = getModuleDebugInfo();
6189   if (DI && getCodeGenOpts().hasReducedDebugInfo())
6190     DI->AddStringLiteralDebugInfo(GV, S);
6191 
6192   if (Entry)
6193     *Entry = GV;
6194 
6195   SanitizerMD->reportGlobal(GV, S->getStrTokenLoc(0), "<string literal>");
6196 
6197   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
6198                          GV->getValueType(), Alignment);
6199 }
6200 
6201 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
6202 /// array for the given ObjCEncodeExpr node.
6203 ConstantAddress
6204 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
6205   std::string Str;
6206   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
6207 
6208   return GetAddrOfConstantCString(Str);
6209 }
6210 
6211 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
6212 /// the literal and a terminating '\0' character.
6213 /// The result has pointer to array type.
6214 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
6215     const std::string &Str, const char *GlobalName) {
6216   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
6217   CharUnits Alignment =
6218     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
6219 
6220   llvm::Constant *C =
6221       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
6222 
6223   // Don't share any string literals if strings aren't constant.
6224   llvm::GlobalVariable **Entry = nullptr;
6225   if (!LangOpts.WritableStrings) {
6226     Entry = &ConstantStringMap[C];
6227     if (auto GV = *Entry) {
6228       if (uint64_t(Alignment.getQuantity()) > GV->getAlignment())
6229         GV->setAlignment(Alignment.getAsAlign());
6230       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
6231                              GV->getValueType(), Alignment);
6232     }
6233   }
6234 
6235   // Get the default prefix if a name wasn't specified.
6236   if (!GlobalName)
6237     GlobalName = ".str";
6238   // Create a global variable for this.
6239   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
6240                                   GlobalName, Alignment);
6241   if (Entry)
6242     *Entry = GV;
6243 
6244   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
6245                          GV->getValueType(), Alignment);
6246 }
6247 
6248 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
6249     const MaterializeTemporaryExpr *E, const Expr *Init) {
6250   assert((E->getStorageDuration() == SD_Static ||
6251           E->getStorageDuration() == SD_Thread) && "not a global temporary");
6252   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
6253 
6254   // If we're not materializing a subobject of the temporary, keep the
6255   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
6256   QualType MaterializedType = Init->getType();
6257   if (Init == E->getSubExpr())
6258     MaterializedType = E->getType();
6259 
6260   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
6261 
6262   auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr});
6263   if (!InsertResult.second) {
6264     // We've seen this before: either we already created it or we're in the
6265     // process of doing so.
6266     if (!InsertResult.first->second) {
6267       // We recursively re-entered this function, probably during emission of
6268       // the initializer. Create a placeholder. We'll clean this up in the
6269       // outer call, at the end of this function.
6270       llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType);
6271       InsertResult.first->second = new llvm::GlobalVariable(
6272           getModule(), Type, false, llvm::GlobalVariable::InternalLinkage,
6273           nullptr);
6274     }
6275     return ConstantAddress(InsertResult.first->second,
6276                            llvm::cast<llvm::GlobalVariable>(
6277                                InsertResult.first->second->stripPointerCasts())
6278                                ->getValueType(),
6279                            Align);
6280   }
6281 
6282   // FIXME: If an externally-visible declaration extends multiple temporaries,
6283   // we need to give each temporary the same name in every translation unit (and
6284   // we also need to make the temporaries externally-visible).
6285   SmallString<256> Name;
6286   llvm::raw_svector_ostream Out(Name);
6287   getCXXABI().getMangleContext().mangleReferenceTemporary(
6288       VD, E->getManglingNumber(), Out);
6289 
6290   APValue *Value = nullptr;
6291   if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) {
6292     // If the initializer of the extending declaration is a constant
6293     // initializer, we should have a cached constant initializer for this
6294     // temporary. Note that this might have a different value from the value
6295     // computed by evaluating the initializer if the surrounding constant
6296     // expression modifies the temporary.
6297     Value = E->getOrCreateValue(false);
6298   }
6299 
6300   // Try evaluating it now, it might have a constant initializer.
6301   Expr::EvalResult EvalResult;
6302   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
6303       !EvalResult.hasSideEffects())
6304     Value = &EvalResult.Val;
6305 
6306   LangAS AddrSpace =
6307       VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
6308 
6309   std::optional<ConstantEmitter> emitter;
6310   llvm::Constant *InitialValue = nullptr;
6311   bool Constant = false;
6312   llvm::Type *Type;
6313   if (Value) {
6314     // The temporary has a constant initializer, use it.
6315     emitter.emplace(*this);
6316     InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
6317                                                MaterializedType);
6318     Constant =
6319         MaterializedType.isConstantStorage(getContext(), /*ExcludeCtor*/ Value,
6320                                            /*ExcludeDtor*/ false);
6321     Type = InitialValue->getType();
6322   } else {
6323     // No initializer, the initialization will be provided when we
6324     // initialize the declaration which performed lifetime extension.
6325     Type = getTypes().ConvertTypeForMem(MaterializedType);
6326   }
6327 
6328   // Create a global variable for this lifetime-extended temporary.
6329   llvm::GlobalValue::LinkageTypes Linkage = getLLVMLinkageVarDefinition(VD);
6330   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
6331     const VarDecl *InitVD;
6332     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
6333         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
6334       // Temporaries defined inside a class get linkonce_odr linkage because the
6335       // class can be defined in multiple translation units.
6336       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
6337     } else {
6338       // There is no need for this temporary to have external linkage if the
6339       // VarDecl has external linkage.
6340       Linkage = llvm::GlobalVariable::InternalLinkage;
6341     }
6342   }
6343   auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
6344   auto *GV = new llvm::GlobalVariable(
6345       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
6346       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
6347   if (emitter) emitter->finalize(GV);
6348   // Don't assign dllimport or dllexport to local linkage globals.
6349   if (!llvm::GlobalValue::isLocalLinkage(Linkage)) {
6350     setGVProperties(GV, VD);
6351     if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass)
6352       // The reference temporary should never be dllexport.
6353       GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
6354   }
6355   GV->setAlignment(Align.getAsAlign());
6356   if (supportsCOMDAT() && GV->isWeakForLinker())
6357     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
6358   if (VD->getTLSKind())
6359     setTLSMode(GV, *VD);
6360   llvm::Constant *CV = GV;
6361   if (AddrSpace != LangAS::Default)
6362     CV = getTargetCodeGenInfo().performAddrSpaceCast(
6363         *this, GV, AddrSpace, LangAS::Default,
6364         Type->getPointerTo(
6365             getContext().getTargetAddressSpace(LangAS::Default)));
6366 
6367   // Update the map with the new temporary. If we created a placeholder above,
6368   // replace it with the new global now.
6369   llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
6370   if (Entry) {
6371     Entry->replaceAllUsesWith(
6372         llvm::ConstantExpr::getBitCast(CV, Entry->getType()));
6373     llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
6374   }
6375   Entry = CV;
6376 
6377   return ConstantAddress(CV, Type, Align);
6378 }
6379 
6380 /// EmitObjCPropertyImplementations - Emit information for synthesized
6381 /// properties for an implementation.
6382 void CodeGenModule::EmitObjCPropertyImplementations(const
6383                                                     ObjCImplementationDecl *D) {
6384   for (const auto *PID : D->property_impls()) {
6385     // Dynamic is just for type-checking.
6386     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
6387       ObjCPropertyDecl *PD = PID->getPropertyDecl();
6388 
6389       // Determine which methods need to be implemented, some may have
6390       // been overridden. Note that ::isPropertyAccessor is not the method
6391       // we want, that just indicates if the decl came from a
6392       // property. What we want to know is if the method is defined in
6393       // this implementation.
6394       auto *Getter = PID->getGetterMethodDecl();
6395       if (!Getter || Getter->isSynthesizedAccessorStub())
6396         CodeGenFunction(*this).GenerateObjCGetter(
6397             const_cast<ObjCImplementationDecl *>(D), PID);
6398       auto *Setter = PID->getSetterMethodDecl();
6399       if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
6400         CodeGenFunction(*this).GenerateObjCSetter(
6401                                  const_cast<ObjCImplementationDecl *>(D), PID);
6402     }
6403   }
6404 }
6405 
6406 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
6407   const ObjCInterfaceDecl *iface = impl->getClassInterface();
6408   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
6409        ivar; ivar = ivar->getNextIvar())
6410     if (ivar->getType().isDestructedType())
6411       return true;
6412 
6413   return false;
6414 }
6415 
6416 static bool AllTrivialInitializers(CodeGenModule &CGM,
6417                                    ObjCImplementationDecl *D) {
6418   CodeGenFunction CGF(CGM);
6419   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
6420        E = D->init_end(); B != E; ++B) {
6421     CXXCtorInitializer *CtorInitExp = *B;
6422     Expr *Init = CtorInitExp->getInit();
6423     if (!CGF.isTrivialInitializer(Init))
6424       return false;
6425   }
6426   return true;
6427 }
6428 
6429 /// EmitObjCIvarInitializations - Emit information for ivar initialization
6430 /// for an implementation.
6431 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
6432   // We might need a .cxx_destruct even if we don't have any ivar initializers.
6433   if (needsDestructMethod(D)) {
6434     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
6435     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
6436     ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(
6437         getContext(), D->getLocation(), D->getLocation(), cxxSelector,
6438         getContext().VoidTy, nullptr, D,
6439         /*isInstance=*/true, /*isVariadic=*/false,
6440         /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
6441         /*isImplicitlyDeclared=*/true,
6442         /*isDefined=*/false, ObjCMethodDecl::Required);
6443     D->addInstanceMethod(DTORMethod);
6444     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
6445     D->setHasDestructors(true);
6446   }
6447 
6448   // If the implementation doesn't have any ivar initializers, we don't need
6449   // a .cxx_construct.
6450   if (D->getNumIvarInitializers() == 0 ||
6451       AllTrivialInitializers(*this, D))
6452     return;
6453 
6454   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
6455   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
6456   // The constructor returns 'self'.
6457   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(
6458       getContext(), D->getLocation(), D->getLocation(), cxxSelector,
6459       getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true,
6460       /*isVariadic=*/false,
6461       /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
6462       /*isImplicitlyDeclared=*/true,
6463       /*isDefined=*/false, ObjCMethodDecl::Required);
6464   D->addInstanceMethod(CTORMethod);
6465   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
6466   D->setHasNonZeroConstructors(true);
6467 }
6468 
6469 // EmitLinkageSpec - Emit all declarations in a linkage spec.
6470 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
6471   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
6472       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
6473     ErrorUnsupported(LSD, "linkage spec");
6474     return;
6475   }
6476 
6477   EmitDeclContext(LSD);
6478 }
6479 
6480 void CodeGenModule::EmitTopLevelStmt(const TopLevelStmtDecl *D) {
6481   // Device code should not be at top level.
6482   if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
6483     return;
6484 
6485   std::unique_ptr<CodeGenFunction> &CurCGF =
6486       GlobalTopLevelStmtBlockInFlight.first;
6487 
6488   // We emitted a top-level stmt but after it there is initialization.
6489   // Stop squashing the top-level stmts into a single function.
6490   if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) {
6491     CurCGF->FinishFunction(D->getEndLoc());
6492     CurCGF = nullptr;
6493   }
6494 
6495   if (!CurCGF) {
6496     // void __stmts__N(void)
6497     // FIXME: Ask the ABI name mangler to pick a name.
6498     std::string Name = "__stmts__" + llvm::utostr(CXXGlobalInits.size());
6499     FunctionArgList Args;
6500     QualType RetTy = getContext().VoidTy;
6501     const CGFunctionInfo &FnInfo =
6502         getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args);
6503     llvm::FunctionType *FnTy = getTypes().GetFunctionType(FnInfo);
6504     llvm::Function *Fn = llvm::Function::Create(
6505         FnTy, llvm::GlobalValue::InternalLinkage, Name, &getModule());
6506 
6507     CurCGF.reset(new CodeGenFunction(*this));
6508     GlobalTopLevelStmtBlockInFlight.second = D;
6509     CurCGF->StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
6510                           D->getBeginLoc(), D->getBeginLoc());
6511     CXXGlobalInits.push_back(Fn);
6512   }
6513 
6514   CurCGF->EmitStmt(D->getStmt());
6515 }
6516 
6517 void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
6518   for (auto *I : DC->decls()) {
6519     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
6520     // are themselves considered "top-level", so EmitTopLevelDecl on an
6521     // ObjCImplDecl does not recursively visit them. We need to do that in
6522     // case they're nested inside another construct (LinkageSpecDecl /
6523     // ExportDecl) that does stop them from being considered "top-level".
6524     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
6525       for (auto *M : OID->methods())
6526         EmitTopLevelDecl(M);
6527     }
6528 
6529     EmitTopLevelDecl(I);
6530   }
6531 }
6532 
6533 /// EmitTopLevelDecl - Emit code for a single top level declaration.
6534 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
6535   // Ignore dependent declarations.
6536   if (D->isTemplated())
6537     return;
6538 
6539   // Consteval function shouldn't be emitted.
6540   if (auto *FD = dyn_cast<FunctionDecl>(D); FD && FD->isImmediateFunction())
6541     return;
6542 
6543   switch (D->getKind()) {
6544   case Decl::CXXConversion:
6545   case Decl::CXXMethod:
6546   case Decl::Function:
6547     EmitGlobal(cast<FunctionDecl>(D));
6548     // Always provide some coverage mapping
6549     // even for the functions that aren't emitted.
6550     AddDeferredUnusedCoverageMapping(D);
6551     break;
6552 
6553   case Decl::CXXDeductionGuide:
6554     // Function-like, but does not result in code emission.
6555     break;
6556 
6557   case Decl::Var:
6558   case Decl::Decomposition:
6559   case Decl::VarTemplateSpecialization:
6560     EmitGlobal(cast<VarDecl>(D));
6561     if (auto *DD = dyn_cast<DecompositionDecl>(D))
6562       for (auto *B : DD->bindings())
6563         if (auto *HD = B->getHoldingVar())
6564           EmitGlobal(HD);
6565     break;
6566 
6567   // Indirect fields from global anonymous structs and unions can be
6568   // ignored; only the actual variable requires IR gen support.
6569   case Decl::IndirectField:
6570     break;
6571 
6572   // C++ Decls
6573   case Decl::Namespace:
6574     EmitDeclContext(cast<NamespaceDecl>(D));
6575     break;
6576   case Decl::ClassTemplateSpecialization: {
6577     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
6578     if (CGDebugInfo *DI = getModuleDebugInfo())
6579       if (Spec->getSpecializationKind() ==
6580               TSK_ExplicitInstantiationDefinition &&
6581           Spec->hasDefinition())
6582         DI->completeTemplateDefinition(*Spec);
6583   } [[fallthrough]];
6584   case Decl::CXXRecord: {
6585     CXXRecordDecl *CRD = cast<CXXRecordDecl>(D);
6586     if (CGDebugInfo *DI = getModuleDebugInfo()) {
6587       if (CRD->hasDefinition())
6588         DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
6589       if (auto *ES = D->getASTContext().getExternalSource())
6590         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
6591           DI->completeUnusedClass(*CRD);
6592     }
6593     // Emit any static data members, they may be definitions.
6594     for (auto *I : CRD->decls())
6595       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
6596         EmitTopLevelDecl(I);
6597     break;
6598   }
6599     // No code generation needed.
6600   case Decl::UsingShadow:
6601   case Decl::ClassTemplate:
6602   case Decl::VarTemplate:
6603   case Decl::Concept:
6604   case Decl::VarTemplatePartialSpecialization:
6605   case Decl::FunctionTemplate:
6606   case Decl::TypeAliasTemplate:
6607   case Decl::Block:
6608   case Decl::Empty:
6609   case Decl::Binding:
6610     break;
6611   case Decl::Using:          // using X; [C++]
6612     if (CGDebugInfo *DI = getModuleDebugInfo())
6613         DI->EmitUsingDecl(cast<UsingDecl>(*D));
6614     break;
6615   case Decl::UsingEnum: // using enum X; [C++]
6616     if (CGDebugInfo *DI = getModuleDebugInfo())
6617       DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D));
6618     break;
6619   case Decl::NamespaceAlias:
6620     if (CGDebugInfo *DI = getModuleDebugInfo())
6621         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
6622     break;
6623   case Decl::UsingDirective: // using namespace X; [C++]
6624     if (CGDebugInfo *DI = getModuleDebugInfo())
6625       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
6626     break;
6627   case Decl::CXXConstructor:
6628     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
6629     break;
6630   case Decl::CXXDestructor:
6631     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
6632     break;
6633 
6634   case Decl::StaticAssert:
6635     // Nothing to do.
6636     break;
6637 
6638   // Objective-C Decls
6639 
6640   // Forward declarations, no (immediate) code generation.
6641   case Decl::ObjCInterface:
6642   case Decl::ObjCCategory:
6643     break;
6644 
6645   case Decl::ObjCProtocol: {
6646     auto *Proto = cast<ObjCProtocolDecl>(D);
6647     if (Proto->isThisDeclarationADefinition())
6648       ObjCRuntime->GenerateProtocol(Proto);
6649     break;
6650   }
6651 
6652   case Decl::ObjCCategoryImpl:
6653     // Categories have properties but don't support synthesize so we
6654     // can ignore them here.
6655     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
6656     break;
6657 
6658   case Decl::ObjCImplementation: {
6659     auto *OMD = cast<ObjCImplementationDecl>(D);
6660     EmitObjCPropertyImplementations(OMD);
6661     EmitObjCIvarInitializations(OMD);
6662     ObjCRuntime->GenerateClass(OMD);
6663     // Emit global variable debug information.
6664     if (CGDebugInfo *DI = getModuleDebugInfo())
6665       if (getCodeGenOpts().hasReducedDebugInfo())
6666         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
6667             OMD->getClassInterface()), OMD->getLocation());
6668     break;
6669   }
6670   case Decl::ObjCMethod: {
6671     auto *OMD = cast<ObjCMethodDecl>(D);
6672     // If this is not a prototype, emit the body.
6673     if (OMD->getBody())
6674       CodeGenFunction(*this).GenerateObjCMethod(OMD);
6675     break;
6676   }
6677   case Decl::ObjCCompatibleAlias:
6678     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
6679     break;
6680 
6681   case Decl::PragmaComment: {
6682     const auto *PCD = cast<PragmaCommentDecl>(D);
6683     switch (PCD->getCommentKind()) {
6684     case PCK_Unknown:
6685       llvm_unreachable("unexpected pragma comment kind");
6686     case PCK_Linker:
6687       AppendLinkerOptions(PCD->getArg());
6688       break;
6689     case PCK_Lib:
6690         AddDependentLib(PCD->getArg());
6691       break;
6692     case PCK_Compiler:
6693     case PCK_ExeStr:
6694     case PCK_User:
6695       break; // We ignore all of these.
6696     }
6697     break;
6698   }
6699 
6700   case Decl::PragmaDetectMismatch: {
6701     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
6702     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
6703     break;
6704   }
6705 
6706   case Decl::LinkageSpec:
6707     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
6708     break;
6709 
6710   case Decl::FileScopeAsm: {
6711     // File-scope asm is ignored during device-side CUDA compilation.
6712     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
6713       break;
6714     // File-scope asm is ignored during device-side OpenMP compilation.
6715     if (LangOpts.OpenMPIsTargetDevice)
6716       break;
6717     // File-scope asm is ignored during device-side SYCL compilation.
6718     if (LangOpts.SYCLIsDevice)
6719       break;
6720     auto *AD = cast<FileScopeAsmDecl>(D);
6721     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
6722     break;
6723   }
6724 
6725   case Decl::TopLevelStmt:
6726     EmitTopLevelStmt(cast<TopLevelStmtDecl>(D));
6727     break;
6728 
6729   case Decl::Import: {
6730     auto *Import = cast<ImportDecl>(D);
6731 
6732     // If we've already imported this module, we're done.
6733     if (!ImportedModules.insert(Import->getImportedModule()))
6734       break;
6735 
6736     // Emit debug information for direct imports.
6737     if (!Import->getImportedOwningModule()) {
6738       if (CGDebugInfo *DI = getModuleDebugInfo())
6739         DI->EmitImportDecl(*Import);
6740     }
6741 
6742     // For C++ standard modules we are done - we will call the module
6743     // initializer for imported modules, and that will likewise call those for
6744     // any imports it has.
6745     if (CXX20ModuleInits && Import->getImportedOwningModule() &&
6746         !Import->getImportedOwningModule()->isModuleMapModule())
6747       break;
6748 
6749     // For clang C++ module map modules the initializers for sub-modules are
6750     // emitted here.
6751 
6752     // Find all of the submodules and emit the module initializers.
6753     llvm::SmallPtrSet<clang::Module *, 16> Visited;
6754     SmallVector<clang::Module *, 16> Stack;
6755     Visited.insert(Import->getImportedModule());
6756     Stack.push_back(Import->getImportedModule());
6757 
6758     while (!Stack.empty()) {
6759       clang::Module *Mod = Stack.pop_back_val();
6760       if (!EmittedModuleInitializers.insert(Mod).second)
6761         continue;
6762 
6763       for (auto *D : Context.getModuleInitializers(Mod))
6764         EmitTopLevelDecl(D);
6765 
6766       // Visit the submodules of this module.
6767       for (auto *Submodule : Mod->submodules()) {
6768         // Skip explicit children; they need to be explicitly imported to emit
6769         // the initializers.
6770         if (Submodule->IsExplicit)
6771           continue;
6772 
6773         if (Visited.insert(Submodule).second)
6774           Stack.push_back(Submodule);
6775       }
6776     }
6777     break;
6778   }
6779 
6780   case Decl::Export:
6781     EmitDeclContext(cast<ExportDecl>(D));
6782     break;
6783 
6784   case Decl::OMPThreadPrivate:
6785     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
6786     break;
6787 
6788   case Decl::OMPAllocate:
6789     EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D));
6790     break;
6791 
6792   case Decl::OMPDeclareReduction:
6793     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
6794     break;
6795 
6796   case Decl::OMPDeclareMapper:
6797     EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
6798     break;
6799 
6800   case Decl::OMPRequires:
6801     EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
6802     break;
6803 
6804   case Decl::Typedef:
6805   case Decl::TypeAlias: // using foo = bar; [C++11]
6806     if (CGDebugInfo *DI = getModuleDebugInfo())
6807       DI->EmitAndRetainType(
6808           getContext().getTypedefType(cast<TypedefNameDecl>(D)));
6809     break;
6810 
6811   case Decl::Record:
6812     if (CGDebugInfo *DI = getModuleDebugInfo())
6813       if (cast<RecordDecl>(D)->getDefinition())
6814         DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
6815     break;
6816 
6817   case Decl::Enum:
6818     if (CGDebugInfo *DI = getModuleDebugInfo())
6819       if (cast<EnumDecl>(D)->getDefinition())
6820         DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D)));
6821     break;
6822 
6823   case Decl::HLSLBuffer:
6824     getHLSLRuntime().addBuffer(cast<HLSLBufferDecl>(D));
6825     break;
6826 
6827   default:
6828     // Make sure we handled everything we should, every other kind is a
6829     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
6830     // function. Need to recode Decl::Kind to do that easily.
6831     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
6832     break;
6833   }
6834 }
6835 
6836 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
6837   // Do we need to generate coverage mapping?
6838   if (!CodeGenOpts.CoverageMapping)
6839     return;
6840   switch (D->getKind()) {
6841   case Decl::CXXConversion:
6842   case Decl::CXXMethod:
6843   case Decl::Function:
6844   case Decl::ObjCMethod:
6845   case Decl::CXXConstructor:
6846   case Decl::CXXDestructor: {
6847     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
6848       break;
6849     SourceManager &SM = getContext().getSourceManager();
6850     if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
6851       break;
6852     auto I = DeferredEmptyCoverageMappingDecls.find(D);
6853     if (I == DeferredEmptyCoverageMappingDecls.end())
6854       DeferredEmptyCoverageMappingDecls[D] = true;
6855     break;
6856   }
6857   default:
6858     break;
6859   };
6860 }
6861 
6862 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
6863   // Do we need to generate coverage mapping?
6864   if (!CodeGenOpts.CoverageMapping)
6865     return;
6866   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
6867     if (Fn->isTemplateInstantiation())
6868       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
6869   }
6870   auto I = DeferredEmptyCoverageMappingDecls.find(D);
6871   if (I == DeferredEmptyCoverageMappingDecls.end())
6872     DeferredEmptyCoverageMappingDecls[D] = false;
6873   else
6874     I->second = false;
6875 }
6876 
6877 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
6878   // We call takeVector() here to avoid use-after-free.
6879   // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
6880   // we deserialize function bodies to emit coverage info for them, and that
6881   // deserializes more declarations. How should we handle that case?
6882   for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
6883     if (!Entry.second)
6884       continue;
6885     const Decl *D = Entry.first;
6886     switch (D->getKind()) {
6887     case Decl::CXXConversion:
6888     case Decl::CXXMethod:
6889     case Decl::Function:
6890     case Decl::ObjCMethod: {
6891       CodeGenPGO PGO(*this);
6892       GlobalDecl GD(cast<FunctionDecl>(D));
6893       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
6894                                   getFunctionLinkage(GD));
6895       break;
6896     }
6897     case Decl::CXXConstructor: {
6898       CodeGenPGO PGO(*this);
6899       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
6900       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
6901                                   getFunctionLinkage(GD));
6902       break;
6903     }
6904     case Decl::CXXDestructor: {
6905       CodeGenPGO PGO(*this);
6906       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
6907       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
6908                                   getFunctionLinkage(GD));
6909       break;
6910     }
6911     default:
6912       break;
6913     };
6914   }
6915 }
6916 
6917 void CodeGenModule::EmitMainVoidAlias() {
6918   // In order to transition away from "__original_main" gracefully, emit an
6919   // alias for "main" in the no-argument case so that libc can detect when
6920   // new-style no-argument main is in used.
6921   if (llvm::Function *F = getModule().getFunction("main")) {
6922     if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
6923         F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) {
6924       auto *GA = llvm::GlobalAlias::create("__main_void", F);
6925       GA->setVisibility(llvm::GlobalValue::HiddenVisibility);
6926     }
6927   }
6928 }
6929 
6930 /// Turns the given pointer into a constant.
6931 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
6932                                           const void *Ptr) {
6933   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
6934   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
6935   return llvm::ConstantInt::get(i64, PtrInt);
6936 }
6937 
6938 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
6939                                    llvm::NamedMDNode *&GlobalMetadata,
6940                                    GlobalDecl D,
6941                                    llvm::GlobalValue *Addr) {
6942   if (!GlobalMetadata)
6943     GlobalMetadata =
6944       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
6945 
6946   // TODO: should we report variant information for ctors/dtors?
6947   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
6948                            llvm::ConstantAsMetadata::get(GetPointerConstant(
6949                                CGM.getLLVMContext(), D.getDecl()))};
6950   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
6951 }
6952 
6953 bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
6954                                                  llvm::GlobalValue *CppFunc) {
6955   // Store the list of ifuncs we need to replace uses in.
6956   llvm::SmallVector<llvm::GlobalIFunc *> IFuncs;
6957   // List of ConstantExprs that we should be able to delete when we're done
6958   // here.
6959   llvm::SmallVector<llvm::ConstantExpr *> CEs;
6960 
6961   // It isn't valid to replace the extern-C ifuncs if all we find is itself!
6962   if (Elem == CppFunc)
6963     return false;
6964 
6965   // First make sure that all users of this are ifuncs (or ifuncs via a
6966   // bitcast), and collect the list of ifuncs and CEs so we can work on them
6967   // later.
6968   for (llvm::User *User : Elem->users()) {
6969     // Users can either be a bitcast ConstExpr that is used by the ifuncs, OR an
6970     // ifunc directly. In any other case, just give up, as we don't know what we
6971     // could break by changing those.
6972     if (auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) {
6973       if (ConstExpr->getOpcode() != llvm::Instruction::BitCast)
6974         return false;
6975 
6976       for (llvm::User *CEUser : ConstExpr->users()) {
6977         if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) {
6978           IFuncs.push_back(IFunc);
6979         } else {
6980           return false;
6981         }
6982       }
6983       CEs.push_back(ConstExpr);
6984     } else if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) {
6985       IFuncs.push_back(IFunc);
6986     } else {
6987       // This user is one we don't know how to handle, so fail redirection. This
6988       // will result in an ifunc retaining a resolver name that will ultimately
6989       // fail to be resolved to a defined function.
6990       return false;
6991     }
6992   }
6993 
6994   // Now we know this is a valid case where we can do this alias replacement, we
6995   // need to remove all of the references to Elem (and the bitcasts!) so we can
6996   // delete it.
6997   for (llvm::GlobalIFunc *IFunc : IFuncs)
6998     IFunc->setResolver(nullptr);
6999   for (llvm::ConstantExpr *ConstExpr : CEs)
7000     ConstExpr->destroyConstant();
7001 
7002   // We should now be out of uses for the 'old' version of this function, so we
7003   // can erase it as well.
7004   Elem->eraseFromParent();
7005 
7006   for (llvm::GlobalIFunc *IFunc : IFuncs) {
7007     // The type of the resolver is always just a function-type that returns the
7008     // type of the IFunc, so create that here. If the type of the actual
7009     // resolver doesn't match, it just gets bitcast to the right thing.
7010     auto *ResolverTy =
7011         llvm::FunctionType::get(IFunc->getType(), /*isVarArg*/ false);
7012     llvm::Constant *Resolver = GetOrCreateLLVMFunction(
7013         CppFunc->getName(), ResolverTy, {}, /*ForVTable*/ false);
7014     IFunc->setResolver(Resolver);
7015   }
7016   return true;
7017 }
7018 
7019 /// For each function which is declared within an extern "C" region and marked
7020 /// as 'used', but has internal linkage, create an alias from the unmangled
7021 /// name to the mangled name if possible. People expect to be able to refer
7022 /// to such functions with an unmangled name from inline assembly within the
7023 /// same translation unit.
7024 void CodeGenModule::EmitStaticExternCAliases() {
7025   if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
7026     return;
7027   for (auto &I : StaticExternCValues) {
7028     IdentifierInfo *Name = I.first;
7029     llvm::GlobalValue *Val = I.second;
7030 
7031     // If Val is null, that implies there were multiple declarations that each
7032     // had a claim to the unmangled name. In this case, generation of the alias
7033     // is suppressed. See CodeGenModule::MaybeHandleStaticInExternC.
7034     if (!Val)
7035       break;
7036 
7037     llvm::GlobalValue *ExistingElem =
7038         getModule().getNamedValue(Name->getName());
7039 
7040     // If there is either not something already by this name, or we were able to
7041     // replace all uses from IFuncs, create the alias.
7042     if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val))
7043       addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
7044   }
7045 }
7046 
7047 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
7048                                              GlobalDecl &Result) const {
7049   auto Res = Manglings.find(MangledName);
7050   if (Res == Manglings.end())
7051     return false;
7052   Result = Res->getValue();
7053   return true;
7054 }
7055 
7056 /// Emits metadata nodes associating all the global values in the
7057 /// current module with the Decls they came from.  This is useful for
7058 /// projects using IR gen as a subroutine.
7059 ///
7060 /// Since there's currently no way to associate an MDNode directly
7061 /// with an llvm::GlobalValue, we create a global named metadata
7062 /// with the name 'clang.global.decl.ptrs'.
7063 void CodeGenModule::EmitDeclMetadata() {
7064   llvm::NamedMDNode *GlobalMetadata = nullptr;
7065 
7066   for (auto &I : MangledDeclNames) {
7067     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
7068     // Some mangled names don't necessarily have an associated GlobalValue
7069     // in this module, e.g. if we mangled it for DebugInfo.
7070     if (Addr)
7071       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
7072   }
7073 }
7074 
7075 /// Emits metadata nodes for all the local variables in the current
7076 /// function.
7077 void CodeGenFunction::EmitDeclMetadata() {
7078   if (LocalDeclMap.empty()) return;
7079 
7080   llvm::LLVMContext &Context = getLLVMContext();
7081 
7082   // Find the unique metadata ID for this name.
7083   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
7084 
7085   llvm::NamedMDNode *GlobalMetadata = nullptr;
7086 
7087   for (auto &I : LocalDeclMap) {
7088     const Decl *D = I.first;
7089     llvm::Value *Addr = I.second.getPointer();
7090     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
7091       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
7092       Alloca->setMetadata(
7093           DeclPtrKind, llvm::MDNode::get(
7094                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
7095     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
7096       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
7097       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
7098     }
7099   }
7100 }
7101 
7102 void CodeGenModule::EmitVersionIdentMetadata() {
7103   llvm::NamedMDNode *IdentMetadata =
7104     TheModule.getOrInsertNamedMetadata("llvm.ident");
7105   std::string Version = getClangFullVersion();
7106   llvm::LLVMContext &Ctx = TheModule.getContext();
7107 
7108   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
7109   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
7110 }
7111 
7112 void CodeGenModule::EmitCommandLineMetadata() {
7113   llvm::NamedMDNode *CommandLineMetadata =
7114     TheModule.getOrInsertNamedMetadata("llvm.commandline");
7115   std::string CommandLine = getCodeGenOpts().RecordCommandLine;
7116   llvm::LLVMContext &Ctx = TheModule.getContext();
7117 
7118   llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
7119   CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
7120 }
7121 
7122 void CodeGenModule::EmitCoverageFile() {
7123   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
7124   if (!CUNode)
7125     return;
7126 
7127   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
7128   llvm::LLVMContext &Ctx = TheModule.getContext();
7129   auto *CoverageDataFile =
7130       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
7131   auto *CoverageNotesFile =
7132       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
7133   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
7134     llvm::MDNode *CU = CUNode->getOperand(i);
7135     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
7136     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
7137   }
7138 }
7139 
7140 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
7141                                                        bool ForEH) {
7142   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
7143   // FIXME: should we even be calling this method if RTTI is disabled
7144   // and it's not for EH?
7145   if (!shouldEmitRTTI(ForEH))
7146     return llvm::Constant::getNullValue(GlobalsInt8PtrTy);
7147 
7148   if (ForEH && Ty->isObjCObjectPointerType() &&
7149       LangOpts.ObjCRuntime.isGNUFamily())
7150     return ObjCRuntime->GetEHType(Ty);
7151 
7152   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
7153 }
7154 
7155 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
7156   // Do not emit threadprivates in simd-only mode.
7157   if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
7158     return;
7159   for (auto RefExpr : D->varlists()) {
7160     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
7161     bool PerformInit =
7162         VD->getAnyInitializer() &&
7163         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
7164                                                         /*ForRef=*/false);
7165 
7166     Address Addr(GetAddrOfGlobalVar(VD),
7167                  getTypes().ConvertTypeForMem(VD->getType()),
7168                  getContext().getDeclAlign(VD));
7169     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
7170             VD, Addr, RefExpr->getBeginLoc(), PerformInit))
7171       CXXGlobalInits.push_back(InitFunction);
7172   }
7173 }
7174 
7175 llvm::Metadata *
7176 CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
7177                                             StringRef Suffix) {
7178   if (auto *FnType = T->getAs<FunctionProtoType>())
7179     T = getContext().getFunctionType(
7180         FnType->getReturnType(), FnType->getParamTypes(),
7181         FnType->getExtProtoInfo().withExceptionSpec(EST_None));
7182 
7183   llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
7184   if (InternalId)
7185     return InternalId;
7186 
7187   if (isExternallyVisible(T->getLinkage())) {
7188     std::string OutName;
7189     llvm::raw_string_ostream Out(OutName);
7190     getCXXABI().getMangleContext().mangleTypeName(
7191         T, Out, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers);
7192 
7193     if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers)
7194       Out << ".normalized";
7195 
7196     Out << Suffix;
7197 
7198     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
7199   } else {
7200     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
7201                                            llvm::ArrayRef<llvm::Metadata *>());
7202   }
7203 
7204   return InternalId;
7205 }
7206 
7207 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
7208   return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
7209 }
7210 
7211 llvm::Metadata *
7212 CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
7213   return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
7214 }
7215 
7216 // Generalize pointer types to a void pointer with the qualifiers of the
7217 // originally pointed-to type, e.g. 'const char *' and 'char * const *'
7218 // generalize to 'const void *' while 'char *' and 'const char **' generalize to
7219 // 'void *'.
7220 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
7221   if (!Ty->isPointerType())
7222     return Ty;
7223 
7224   return Ctx.getPointerType(
7225       QualType(Ctx.VoidTy).withCVRQualifiers(
7226           Ty->getPointeeType().getCVRQualifiers()));
7227 }
7228 
7229 // Apply type generalization to a FunctionType's return and argument types
7230 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
7231   if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
7232     SmallVector<QualType, 8> GeneralizedParams;
7233     for (auto &Param : FnType->param_types())
7234       GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
7235 
7236     return Ctx.getFunctionType(
7237         GeneralizeType(Ctx, FnType->getReturnType()),
7238         GeneralizedParams, FnType->getExtProtoInfo());
7239   }
7240 
7241   if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
7242     return Ctx.getFunctionNoProtoType(
7243         GeneralizeType(Ctx, FnType->getReturnType()));
7244 
7245   llvm_unreachable("Encountered unknown FunctionType");
7246 }
7247 
7248 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
7249   return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
7250                                       GeneralizedMetadataIdMap, ".generalized");
7251 }
7252 
7253 /// Returns whether this module needs the "all-vtables" type identifier.
7254 bool CodeGenModule::NeedAllVtablesTypeId() const {
7255   // Returns true if at least one of vtable-based CFI checkers is enabled and
7256   // is not in the trapping mode.
7257   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
7258            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
7259           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
7260            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
7261           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
7262            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
7263           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
7264            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
7265 }
7266 
7267 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
7268                                           CharUnits Offset,
7269                                           const CXXRecordDecl *RD) {
7270   llvm::Metadata *MD =
7271       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
7272   VTable->addTypeMetadata(Offset.getQuantity(), MD);
7273 
7274   if (CodeGenOpts.SanitizeCfiCrossDso)
7275     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
7276       VTable->addTypeMetadata(Offset.getQuantity(),
7277                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
7278 
7279   if (NeedAllVtablesTypeId()) {
7280     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
7281     VTable->addTypeMetadata(Offset.getQuantity(), MD);
7282   }
7283 }
7284 
7285 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
7286   if (!SanStats)
7287     SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule());
7288 
7289   return *SanStats;
7290 }
7291 
7292 llvm::Value *
7293 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
7294                                                   CodeGenFunction &CGF) {
7295   llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
7296   auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
7297   auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
7298   auto *Call = CGF.EmitRuntimeCall(
7299       CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C});
7300   return Call;
7301 }
7302 
7303 CharUnits CodeGenModule::getNaturalPointeeTypeAlignment(
7304     QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) {
7305   return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
7306                                  /* forPointeeType= */ true);
7307 }
7308 
7309 CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T,
7310                                                  LValueBaseInfo *BaseInfo,
7311                                                  TBAAAccessInfo *TBAAInfo,
7312                                                  bool forPointeeType) {
7313   if (TBAAInfo)
7314     *TBAAInfo = getTBAAAccessInfo(T);
7315 
7316   // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But
7317   // that doesn't return the information we need to compute BaseInfo.
7318 
7319   // Honor alignment typedef attributes even on incomplete types.
7320   // We also honor them straight for C++ class types, even as pointees;
7321   // there's an expressivity gap here.
7322   if (auto TT = T->getAs<TypedefType>()) {
7323     if (auto Align = TT->getDecl()->getMaxAlignment()) {
7324       if (BaseInfo)
7325         *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
7326       return getContext().toCharUnitsFromBits(Align);
7327     }
7328   }
7329 
7330   bool AlignForArray = T->isArrayType();
7331 
7332   // Analyze the base element type, so we don't get confused by incomplete
7333   // array types.
7334   T = getContext().getBaseElementType(T);
7335 
7336   if (T->isIncompleteType()) {
7337     // We could try to replicate the logic from
7338     // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the
7339     // type is incomplete, so it's impossible to test. We could try to reuse
7340     // getTypeAlignIfKnown, but that doesn't return the information we need
7341     // to set BaseInfo.  So just ignore the possibility that the alignment is
7342     // greater than one.
7343     if (BaseInfo)
7344       *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
7345     return CharUnits::One();
7346   }
7347 
7348   if (BaseInfo)
7349     *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
7350 
7351   CharUnits Alignment;
7352   const CXXRecordDecl *RD;
7353   if (T.getQualifiers().hasUnaligned()) {
7354     Alignment = CharUnits::One();
7355   } else if (forPointeeType && !AlignForArray &&
7356              (RD = T->getAsCXXRecordDecl())) {
7357     // For C++ class pointees, we don't know whether we're pointing at a
7358     // base or a complete object, so we generally need to use the
7359     // non-virtual alignment.
7360     Alignment = getClassPointerAlignment(RD);
7361   } else {
7362     Alignment = getContext().getTypeAlignInChars(T);
7363   }
7364 
7365   // Cap to the global maximum type alignment unless the alignment
7366   // was somehow explicit on the type.
7367   if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
7368     if (Alignment.getQuantity() > MaxAlign &&
7369         !getContext().isAlignmentRequired(T))
7370       Alignment = CharUnits::fromQuantity(MaxAlign);
7371   }
7372   return Alignment;
7373 }
7374 
7375 bool CodeGenModule::stopAutoInit() {
7376   unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter;
7377   if (StopAfter) {
7378     // This number is positive only when -ftrivial-auto-var-init-stop-after=* is
7379     // used
7380     if (NumAutoVarInit >= StopAfter) {
7381       return true;
7382     }
7383     if (!NumAutoVarInit) {
7384       unsigned DiagID = getDiags().getCustomDiagID(
7385           DiagnosticsEngine::Warning,
7386           "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
7387           "number of times ftrivial-auto-var-init=%1 gets applied.");
7388       getDiags().Report(DiagID)
7389           << StopAfter
7390           << (getContext().getLangOpts().getTrivialAutoVarInit() ==
7391                       LangOptions::TrivialAutoVarInitKind::Zero
7392                   ? "zero"
7393                   : "pattern");
7394     }
7395     ++NumAutoVarInit;
7396   }
7397   return false;
7398 }
7399 
7400 void CodeGenModule::printPostfixForExternalizedDecl(llvm::raw_ostream &OS,
7401                                                     const Decl *D) const {
7402   // ptxas does not allow '.' in symbol names. On the other hand, HIP prefers
7403   // postfix beginning with '.' since the symbol name can be demangled.
7404   if (LangOpts.HIP)
7405     OS << (isa<VarDecl>(D) ? ".static." : ".intern.");
7406   else
7407     OS << (isa<VarDecl>(D) ? "__static__" : "__intern__");
7408 
7409   // If the CUID is not specified we try to generate a unique postfix.
7410   if (getLangOpts().CUID.empty()) {
7411     SourceManager &SM = getContext().getSourceManager();
7412     PresumedLoc PLoc = SM.getPresumedLoc(D->getLocation());
7413     assert(PLoc.isValid() && "Source location is expected to be valid.");
7414 
7415     // Get the hash of the user defined macros.
7416     llvm::MD5 Hash;
7417     llvm::MD5::MD5Result Result;
7418     for (const auto &Arg : PreprocessorOpts.Macros)
7419       Hash.update(Arg.first);
7420     Hash.final(Result);
7421 
7422     // Get the UniqueID for the file containing the decl.
7423     llvm::sys::fs::UniqueID ID;
7424     if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) {
7425       PLoc = SM.getPresumedLoc(D->getLocation(), /*UseLineDirectives=*/false);
7426       assert(PLoc.isValid() && "Source location is expected to be valid.");
7427       if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
7428         SM.getDiagnostics().Report(diag::err_cannot_open_file)
7429             << PLoc.getFilename() << EC.message();
7430     }
7431     OS << llvm::format("%x", ID.getFile()) << llvm::format("%x", ID.getDevice())
7432        << "_" << llvm::utohexstr(Result.low(), /*LowerCase=*/true, /*Width=*/8);
7433   } else {
7434     OS << getContext().getCUIDHash();
7435   }
7436 }
7437 
7438 void CodeGenModule::moveLazyEmissionStates(CodeGenModule *NewBuilder) {
7439   assert(DeferredDeclsToEmit.empty() &&
7440          "Should have emitted all decls deferred to emit.");
7441   assert(NewBuilder->DeferredDecls.empty() &&
7442          "Newly created module should not have deferred decls");
7443   NewBuilder->DeferredDecls = std::move(DeferredDecls);
7444   assert(EmittedDeferredDecls.empty() &&
7445          "Still have (unmerged) EmittedDeferredDecls deferred decls");
7446 
7447   assert(NewBuilder->DeferredVTables.empty() &&
7448          "Newly created module should not have deferred vtables");
7449   NewBuilder->DeferredVTables = std::move(DeferredVTables);
7450 
7451   assert(NewBuilder->MangledDeclNames.empty() &&
7452          "Newly created module should not have mangled decl names");
7453   assert(NewBuilder->Manglings.empty() &&
7454          "Newly created module should not have manglings");
7455   NewBuilder->Manglings = std::move(Manglings);
7456 
7457   NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
7458 
7459   NewBuilder->TBAA = std::move(TBAA);
7460 
7461   NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx);
7462 }
7463