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