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