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