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