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