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

Follow Lee on X/Twitter - Father, Husband, Serial builder creating AI, crypto, games & web tools. We are friends :) AI Will Come To Life!

Check out: eBank.nz (Art Generator) | Netwrck.com (AI Tools) | Text-Generator.io (AI API) | BitBank.nz (Crypto AI) | ReadingTime (Kids Reading) | RewordGame | BigMultiplayerChess | WebFiddle | How.nz | Helix AI Assistant