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