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