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