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