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