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