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