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