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