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