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