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