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