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