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