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