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