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