clang 22.0.0git
CodeGenModule.cpp
Go to the documentation of this file.
1//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This coordinates the per-module state used while generating code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CodeGenModule.h"
14#include "ABIInfo.h"
15#include "CGBlocks.h"
16#include "CGCUDARuntime.h"
17#include "CGCXXABI.h"
18#include "CGCall.h"
19#include "CGDebugInfo.h"
20#include "CGHLSLRuntime.h"
21#include "CGObjCRuntime.h"
22#include "CGOpenCLRuntime.h"
23#include "CGOpenMPRuntime.h"
24#include "CGOpenMPRuntimeGPU.h"
25#include "CodeGenFunction.h"
26#include "CodeGenPGO.h"
27#include "ConstantEmitter.h"
28#include "CoverageMappingGen.h"
29#include "TargetInfo.h"
31#include "clang/AST/ASTLambda.h"
32#include "clang/AST/CharUnits.h"
33#include "clang/AST/Decl.h"
34#include "clang/AST/DeclCXX.h"
35#include "clang/AST/DeclObjC.h"
37#include "clang/AST/Mangle.h"
44#include "clang/Basic/Module.h"
47#include "clang/Basic/Version.h"
50#include "llvm/ADT/STLExtras.h"
51#include "llvm/ADT/StringExtras.h"
52#include "llvm/ADT/StringSwitch.h"
53#include "llvm/Analysis/TargetLibraryInfo.h"
54#include "llvm/BinaryFormat/ELF.h"
55#include "llvm/IR/AttributeMask.h"
56#include "llvm/IR/CallingConv.h"
57#include "llvm/IR/DataLayout.h"
58#include "llvm/IR/Intrinsics.h"
59#include "llvm/IR/LLVMContext.h"
60#include "llvm/IR/Module.h"
61#include "llvm/IR/ProfileSummary.h"
62#include "llvm/ProfileData/InstrProfReader.h"
63#include "llvm/ProfileData/SampleProf.h"
64#include "llvm/Support/CRC.h"
65#include "llvm/Support/CodeGen.h"
66#include "llvm/Support/CommandLine.h"
67#include "llvm/Support/ConvertUTF.h"
68#include "llvm/Support/ErrorHandling.h"
69#include "llvm/Support/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::NonLeafNoReserve);
1517 break;
1519 getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
1520 break;
1522 getModule().setFramePointer(llvm::FramePointerKind::All);
1523 break;
1524 }
1525
1526 SimplifyPersonality();
1527
1528 if (getCodeGenOpts().EmitDeclMetadata)
1529 EmitDeclMetadata();
1530
1531 if (getCodeGenOpts().CoverageNotesFile.size() ||
1532 getCodeGenOpts().CoverageDataFile.size())
1533 EmitCoverageFile();
1534
1535 if (CGDebugInfo *DI = getModuleDebugInfo())
1536 DI->finalize();
1537
1538 if (getCodeGenOpts().EmitVersionIdentMetadata)
1539 EmitVersionIdentMetadata();
1540
1541 if (!getCodeGenOpts().RecordCommandLine.empty())
1542 EmitCommandLineMetadata();
1543
1544 if (!getCodeGenOpts().StackProtectorGuard.empty())
1545 getModule().setStackProtectorGuard(getCodeGenOpts().StackProtectorGuard);
1546 if (!getCodeGenOpts().StackProtectorGuardReg.empty())
1547 getModule().setStackProtectorGuardReg(
1548 getCodeGenOpts().StackProtectorGuardReg);
1549 if (!getCodeGenOpts().StackProtectorGuardSymbol.empty())
1550 getModule().setStackProtectorGuardSymbol(
1551 getCodeGenOpts().StackProtectorGuardSymbol);
1552 if (getCodeGenOpts().StackProtectorGuardOffset != INT_MAX)
1553 getModule().setStackProtectorGuardOffset(
1554 getCodeGenOpts().StackProtectorGuardOffset);
1555 if (getCodeGenOpts().StackAlignment)
1556 getModule().setOverrideStackAlignment(getCodeGenOpts().StackAlignment);
1557 if (getCodeGenOpts().SkipRaxSetup)
1558 getModule().addModuleFlag(llvm::Module::Override, "SkipRaxSetup", 1);
1559 if (getLangOpts().RegCall4)
1560 getModule().addModuleFlag(llvm::Module::Override, "RegCallv4", 1);
1561
1562 if (getContext().getTargetInfo().getMaxTLSAlign())
1563 getModule().addModuleFlag(llvm::Module::Error, "MaxTLSAlign",
1564 getContext().getTargetInfo().getMaxTLSAlign());
1565
1567
1568 getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames);
1569
1570 EmitBackendOptionsMetadata(getCodeGenOpts());
1571
1572 // If there is device offloading code embed it in the host now.
1573 EmbedObject(&getModule(), CodeGenOpts, *getFileSystem(), getDiags());
1574
1575 // Set visibility from DLL storage class
1576 // We do this at the end of LLVM IR generation; after any operation
1577 // that might affect the DLL storage class or the visibility, and
1578 // before anything that might act on these.
1580
1581 // Check the tail call symbols are truly undefined.
1582 if (getTriple().isPPC() && !MustTailCallUndefinedGlobals.empty()) {
1583 for (auto &I : MustTailCallUndefinedGlobals) {
1584 if (!I.first->isDefined())
1585 getDiags().Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1586 else {
1587 StringRef MangledName = getMangledName(GlobalDecl(I.first));
1588 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1589 if (!Entry || Entry->isWeakForLinker() ||
1590 Entry->isDeclarationForLinker())
1591 getDiags().Report(I.second, diag::err_ppc_impossible_musttail) << 2;
1592 }
1593 }
1594 }
1595
1596 // Emit `!llvm.errno.tbaa`, a module-level metadata that specifies the TBAA
1597 // for an int access. This allows LLVM to reason about what memory can be
1598 // accessed by certain library calls that only touch errno.
1599 if (TBAA) {
1600 TBAAAccessInfo TBAAInfo = getTBAAAccessInfo(Context.IntTy);
1601 if (llvm::MDNode *IntegerNode = getTBAAAccessTagInfo(TBAAInfo)) {
1602 auto *ErrnoTBAAMD = TheModule.getOrInsertNamedMetadata(ErrnoTBAAMDName);
1603 ErrnoTBAAMD->addOperand(IntegerNode);
1604 }
1605 }
1606}
1607
1608void CodeGenModule::EmitOpenCLMetadata() {
1609 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
1610 // opencl.ocl.version named metadata node.
1611 // C++ for OpenCL has a distinct mapping for versions compatible with OpenCL.
1612 auto CLVersion = LangOpts.getOpenCLCompatibleVersion();
1613
1614 auto EmitVersion = [this](StringRef MDName, int Version) {
1615 llvm::Metadata *OCLVerElts[] = {
1616 llvm::ConstantAsMetadata::get(
1617 llvm::ConstantInt::get(Int32Ty, Version / 100)),
1618 llvm::ConstantAsMetadata::get(
1619 llvm::ConstantInt::get(Int32Ty, (Version % 100) / 10))};
1620 llvm::NamedMDNode *OCLVerMD = TheModule.getOrInsertNamedMetadata(MDName);
1621 llvm::LLVMContext &Ctx = TheModule.getContext();
1622 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
1623 };
1624
1625 EmitVersion("opencl.ocl.version", CLVersion);
1626 if (LangOpts.OpenCLCPlusPlus) {
1627 // In addition to the OpenCL compatible version, emit the C++ version.
1628 EmitVersion("opencl.cxx.version", LangOpts.OpenCLCPlusPlusVersion);
1629 }
1630}
1631
1632void CodeGenModule::EmitBackendOptionsMetadata(
1633 const CodeGenOptions &CodeGenOpts) {
1634 if (getTriple().isRISCV()) {
1635 getModule().addModuleFlag(llvm::Module::Min, "SmallDataLimit",
1636 CodeGenOpts.SmallDataLimit);
1637 }
1638
1639 // Set AllocToken configuration for backend pipeline.
1640 if (LangOpts.AllocTokenMode) {
1641 StringRef S = llvm::getAllocTokenModeAsString(*LangOpts.AllocTokenMode);
1642 getModule().addModuleFlag(llvm::Module::Error, "alloc-token-mode",
1643 llvm::MDString::get(VMContext, S));
1644 }
1645 if (LangOpts.AllocTokenMax)
1646 getModule().addModuleFlag(
1647 llvm::Module::Error, "alloc-token-max",
1648 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
1649 *LangOpts.AllocTokenMax));
1650 if (CodeGenOpts.SanitizeAllocTokenFastABI)
1651 getModule().addModuleFlag(llvm::Module::Error, "alloc-token-fast-abi", 1);
1652 if (CodeGenOpts.SanitizeAllocTokenExtended)
1653 getModule().addModuleFlag(llvm::Module::Error, "alloc-token-extended", 1);
1654}
1655
1657 // Make sure that this type is translated.
1659}
1660
1662 // Make sure that this type is translated.
1664}
1665
1667 if (!TBAA)
1668 return nullptr;
1669 return TBAA->getTypeInfo(QTy);
1670}
1671
1673 if (!TBAA)
1674 return TBAAAccessInfo();
1675 if (getLangOpts().CUDAIsDevice) {
1676 // As CUDA builtin surface/texture types are replaced, skip generating TBAA
1677 // access info.
1678 if (AccessType->isCUDADeviceBuiltinSurfaceType()) {
1679 if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() !=
1680 nullptr)
1681 return TBAAAccessInfo();
1682 } else if (AccessType->isCUDADeviceBuiltinTextureType()) {
1683 if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() !=
1684 nullptr)
1685 return TBAAAccessInfo();
1686 }
1687 }
1688 return TBAA->getAccessInfo(AccessType);
1689}
1690
1693 if (!TBAA)
1694 return TBAAAccessInfo();
1695 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
1696}
1697
1699 if (!TBAA)
1700 return nullptr;
1701 return TBAA->getTBAAStructInfo(QTy);
1702}
1703
1705 if (!TBAA)
1706 return nullptr;
1707 return TBAA->getBaseTypeInfo(QTy);
1708}
1709
1711 if (!TBAA)
1712 return nullptr;
1713 return TBAA->getAccessTagInfo(Info);
1714}
1715
1718 if (!TBAA)
1719 return TBAAAccessInfo();
1720 return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
1721}
1722
1725 TBAAAccessInfo InfoB) {
1726 if (!TBAA)
1727 return TBAAAccessInfo();
1728 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
1729}
1730
1733 TBAAAccessInfo SrcInfo) {
1734 if (!TBAA)
1735 return TBAAAccessInfo();
1736 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
1737}
1738
1740 TBAAAccessInfo TBAAInfo) {
1741 if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
1742 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
1743}
1744
1746 llvm::Instruction *I, const CXXRecordDecl *RD) {
1747 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
1748 llvm::MDNode::get(getLLVMContext(), {}));
1749}
1750
1751void CodeGenModule::Error(SourceLocation loc, StringRef message) {
1752 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
1753 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
1754}
1755
1756/// ErrorUnsupported - Print out an error that codegen doesn't support the
1757/// specified stmt yet.
1758void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
1760 "cannot compile this %0 yet");
1761 std::string Msg = Type;
1762 getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
1763 << Msg << S->getSourceRange();
1764}
1765
1766/// ErrorUnsupported - Print out an error that codegen doesn't support the
1767/// specified decl yet.
1768void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
1770 "cannot compile this %0 yet");
1771 std::string Msg = Type;
1772 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
1773}
1774
1776 llvm::function_ref<void()> Fn) {
1777 StackHandler.runWithSufficientStackSpace(Loc, Fn);
1778}
1779
1780llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
1781 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
1782}
1783
1784void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
1785 const NamedDecl *D) const {
1786 // Internal definitions always have default visibility.
1787 if (GV->hasLocalLinkage()) {
1788 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1789 return;
1790 }
1791 if (!D)
1792 return;
1793
1794 // Set visibility for definitions, and for declarations if requested globally
1795 // or set explicitly.
1797
1798 // OpenMP declare target variables must be visible to the host so they can
1799 // be registered. We require protected visibility unless the variable has
1800 // the DT_nohost modifier and does not need to be registered.
1801 if (Context.getLangOpts().OpenMP &&
1802 Context.getLangOpts().OpenMPIsTargetDevice && isa<VarDecl>(D) &&
1803 D->hasAttr<OMPDeclareTargetDeclAttr>() &&
1804 D->getAttr<OMPDeclareTargetDeclAttr>()->getDevType() !=
1805 OMPDeclareTargetDeclAttr::DT_NoHost &&
1807 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
1808 return;
1809 }
1810
1811 if (Context.getLangOpts().HLSL && !D->isInExportDeclContext()) {
1812 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1813 return;
1814 }
1815
1816 if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) {
1817 // Reject incompatible dlllstorage and visibility annotations.
1818 if (!LV.isVisibilityExplicit())
1819 return;
1820 if (GV->hasDLLExportStorageClass()) {
1821 if (LV.getVisibility() == HiddenVisibility)
1823 diag::err_hidden_visibility_dllexport);
1824 } else if (LV.getVisibility() != DefaultVisibility) {
1826 diag::err_non_default_visibility_dllimport);
1827 }
1828 return;
1829 }
1830
1831 if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls ||
1832 !GV->isDeclarationForLinker())
1833 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
1834}
1835
1837 llvm::GlobalValue *GV) {
1838 if (GV->hasLocalLinkage())
1839 return true;
1840
1841 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
1842 return true;
1843
1844 // DLLImport explicitly marks the GV as external.
1845 if (GV->hasDLLImportStorageClass())
1846 return false;
1847
1848 const llvm::Triple &TT = CGM.getTriple();
1849 const auto &CGOpts = CGM.getCodeGenOpts();
1850 if (TT.isOSCygMing()) {
1851 // In MinGW, variables without DLLImport can still be automatically
1852 // imported from a DLL by the linker; don't mark variables that
1853 // potentially could come from another DLL as DSO local.
1854
1855 // With EmulatedTLS, TLS variables can be autoimported from other DLLs
1856 // (and this actually happens in the public interface of libstdc++), so
1857 // such variables can't be marked as DSO local. (Native TLS variables
1858 // can't be dllimported at all, though.)
1859 if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
1860 (!GV->isThreadLocal() || CGM.getCodeGenOpts().EmulatedTLS) &&
1861 CGOpts.AutoImport)
1862 return false;
1863 }
1864
1865 // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols
1866 // remain unresolved in the link, they can be resolved to zero, which is
1867 // outside the current DSO.
1868 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
1869 return false;
1870
1871 // Every other GV is local on COFF.
1872 // Make an exception for windows OS in the triple: Some firmware builds use
1873 // *-win32-macho triples. This (accidentally?) produced windows relocations
1874 // without GOT tables in older clang versions; Keep this behaviour.
1875 // FIXME: even thread local variables?
1876 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
1877 return true;
1878
1879 // Only handle COFF and ELF for now.
1880 if (!TT.isOSBinFormatELF())
1881 return false;
1882
1883 // If this is not an executable, don't assume anything is local.
1884 llvm::Reloc::Model RM = CGOpts.RelocationModel;
1885 const auto &LOpts = CGM.getLangOpts();
1886 if (RM != llvm::Reloc::Static && !LOpts.PIE) {
1887 // On ELF, if -fno-semantic-interposition is specified and the target
1888 // supports local aliases, there will be neither CC1
1889 // -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set
1890 // dso_local on the function if using a local alias is preferable (can avoid
1891 // PLT indirection).
1892 if (!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias()))
1893 return false;
1894 return !(CGM.getLangOpts().SemanticInterposition ||
1895 CGM.getLangOpts().HalfNoSemanticInterposition);
1896 }
1897
1898 // A definition cannot be preempted from an executable.
1899 if (!GV->isDeclarationForLinker())
1900 return true;
1901
1902 // Most PIC code sequences that assume that a symbol is local cannot produce a
1903 // 0 if it turns out the symbol is undefined. While this is ABI and relocation
1904 // depended, it seems worth it to handle it here.
1905 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
1906 return false;
1907
1908 // PowerPC64 prefers TOC indirection to avoid copy relocations.
1909 if (TT.isPPC64())
1910 return false;
1911
1912 if (CGOpts.DirectAccessExternalData) {
1913 // If -fdirect-access-external-data (default for -fno-pic), set dso_local
1914 // for non-thread-local variables. If the symbol is not defined in the
1915 // executable, a copy relocation will be needed at link time. dso_local is
1916 // excluded for thread-local variables because they generally don't support
1917 // copy relocations.
1918 if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
1919 if (!Var->isThreadLocal())
1920 return true;
1921
1922 // -fno-pic sets dso_local on a function declaration to allow direct
1923 // accesses when taking its address (similar to a data symbol). If the
1924 // function is not defined in the executable, a canonical PLT entry will be
1925 // needed at link time. -fno-direct-access-external-data can avoid the
1926 // canonical PLT entry. We don't generalize this condition to -fpie/-fpic as
1927 // it could just cause trouble without providing perceptible benefits.
1928 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
1929 return true;
1930 }
1931
1932 // If we can use copy relocations we can assume it is local.
1933
1934 // Otherwise don't assume it is local.
1935 return false;
1936}
1937
1938void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
1939 GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
1940}
1941
1942void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
1943 GlobalDecl GD) const {
1944 const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
1945 // C++ destructors have a few C++ ABI specific special cases.
1946 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
1948 return;
1949 }
1950 setDLLImportDLLExport(GV, D);
1951}
1952
1953void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
1954 const NamedDecl *D) const {
1955 if (D && D->isExternallyVisible()) {
1956 if (D->hasAttr<DLLImportAttr>())
1957 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
1958 else if ((D->hasAttr<DLLExportAttr>() ||
1960 !GV->isDeclarationForLinker())
1961 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
1962 }
1963}
1964
1965void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
1966 GlobalDecl GD) const {
1967 setDLLImportDLLExport(GV, GD);
1968 setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl()));
1969}
1970
1971void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
1972 const NamedDecl *D) const {
1973 setDLLImportDLLExport(GV, D);
1974 setGVPropertiesAux(GV, D);
1975}
1976
1977void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV,
1978 const NamedDecl *D) const {
1979 setGlobalVisibility(GV, D);
1980 setDSOLocal(GV);
1981 GV->setPartition(CodeGenOpts.SymbolPartition);
1982}
1983
1984static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
1985 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
1986 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
1987 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
1988 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
1989 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
1990}
1991
1992llvm::GlobalVariable::ThreadLocalMode
1994 switch (CodeGenOpts.getDefaultTLSModel()) {
1996 return llvm::GlobalVariable::GeneralDynamicTLSModel;
1998 return llvm::GlobalVariable::LocalDynamicTLSModel;
2000 return llvm::GlobalVariable::InitialExecTLSModel;
2002 return llvm::GlobalVariable::LocalExecTLSModel;
2003 }
2004 llvm_unreachable("Invalid TLS model!");
2005}
2006
2007void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
2008 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
2009
2010 llvm::GlobalValue::ThreadLocalMode TLM;
2011 TLM = GetDefaultLLVMTLSModel();
2012
2013 // Override the TLS model if it is explicitly specified.
2014 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
2015 TLM = GetLLVMTLSModel(Attr->getModel());
2016 }
2017
2018 GV->setThreadLocalMode(TLM);
2019}
2020
2021static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
2022 StringRef Name) {
2023 const TargetInfo &Target = CGM.getTarget();
2024 return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
2025}
2026
2028 const CPUSpecificAttr *Attr,
2029 unsigned CPUIndex,
2030 raw_ostream &Out) {
2031 // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
2032 // supported.
2033 if (Attr)
2034 Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName());
2035 else if (CGM.getTarget().supportsIFunc())
2036 Out << ".resolver";
2037}
2038
2039// Returns true if GD is a function decl with internal linkage and
2040// needs a unique suffix after the mangled name.
2042 CodeGenModule &CGM) {
2043 const Decl *D = GD.getDecl();
2044 return !CGM.getModuleNameHash().empty() && isa<FunctionDecl>(D) &&
2045 (CGM.getFunctionLinkage(GD) == llvm::GlobalValue::InternalLinkage);
2046}
2047
2048static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD,
2049 const NamedDecl *ND,
2050 bool OmitMultiVersionMangling = false) {
2051 SmallString<256> Buffer;
2052 llvm::raw_svector_ostream Out(Buffer);
2054 if (!CGM.getModuleNameHash().empty())
2056 bool ShouldMangle = MC.shouldMangleDeclName(ND);
2057 if (ShouldMangle)
2058 MC.mangleName(GD.getWithDecl(ND), Out);
2059 else {
2060 IdentifierInfo *II = ND->getIdentifier();
2061 assert(II && "Attempt to mangle unnamed decl.");
2062 const auto *FD = dyn_cast<FunctionDecl>(ND);
2063
2064 if (FD &&
2065 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
2066 if (CGM.getLangOpts().RegCall4)
2067 Out << "__regcall4__" << II->getName();
2068 else
2069 Out << "__regcall3__" << II->getName();
2070 } else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
2072 Out << "__device_stub__" << II->getName();
2073 } else if (FD &&
2074 DeviceKernelAttr::isOpenCLSpelling(
2075 FD->getAttr<DeviceKernelAttr>()) &&
2077 Out << "__clang_ocl_kern_imp_" << II->getName();
2078 } else {
2079 Out << II->getName();
2080 }
2081 }
2082
2083 // Check if the module name hash should be appended for internal linkage
2084 // symbols. This should come before multi-version target suffixes are
2085 // appended. This is to keep the name and module hash suffix of the
2086 // internal linkage function together. The unique suffix should only be
2087 // added when name mangling is done to make sure that the final name can
2088 // be properly demangled. For example, for C functions without prototypes,
2089 // name mangling is not done and the unique suffix should not be appeneded
2090 // then.
2091 if (ShouldMangle && isUniqueInternalLinkageDecl(GD, CGM)) {
2092 assert(CGM.getCodeGenOpts().UniqueInternalLinkageNames &&
2093 "Hash computed when not explicitly requested");
2094 Out << CGM.getModuleNameHash();
2095 }
2096
2097 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
2098 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
2099 switch (FD->getMultiVersionKind()) {
2103 FD->getAttr<CPUSpecificAttr>(),
2104 GD.getMultiVersionIndex(), Out);
2105 break;
2107 auto *Attr = FD->getAttr<TargetAttr>();
2108 assert(Attr && "Expected TargetAttr to be present "
2109 "for attribute mangling");
2110 const ABIInfo &Info = CGM.getTargetCodeGenInfo().getABIInfo();
2111 Info.appendAttributeMangling(Attr, Out);
2112 break;
2113 }
2115 auto *Attr = FD->getAttr<TargetVersionAttr>();
2116 assert(Attr && "Expected TargetVersionAttr to be present "
2117 "for attribute mangling");
2118 const ABIInfo &Info = CGM.getTargetCodeGenInfo().getABIInfo();
2119 Info.appendAttributeMangling(Attr, Out);
2120 break;
2121 }
2123 auto *Attr = FD->getAttr<TargetClonesAttr>();
2124 assert(Attr && "Expected TargetClonesAttr to be present "
2125 "for attribute mangling");
2126 unsigned Index = GD.getMultiVersionIndex();
2127 const ABIInfo &Info = CGM.getTargetCodeGenInfo().getABIInfo();
2128 Info.appendAttributeMangling(Attr, Index, Out);
2129 break;
2130 }
2132 llvm_unreachable("None multiversion type isn't valid here");
2133 }
2134 }
2135
2136 // Make unique name for device side static file-scope variable for HIP.
2137 if (CGM.getContext().shouldExternalize(ND) &&
2138 CGM.getLangOpts().GPURelocatableDeviceCode &&
2139 CGM.getLangOpts().CUDAIsDevice)
2141
2142 return std::string(Out.str());
2143}
2144
2145void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
2146 const FunctionDecl *FD,
2147 StringRef &CurName) {
2148 if (!FD->isMultiVersion())
2149 return;
2150
2151 // Get the name of what this would be without the 'target' attribute. This
2152 // allows us to lookup the version that was emitted when this wasn't a
2153 // multiversion function.
2154 std::string NonTargetName =
2155 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
2156 GlobalDecl OtherGD;
2157 if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
2158 assert(OtherGD.getCanonicalDecl()
2159 .getDecl()
2160 ->getAsFunction()
2161 ->isMultiVersion() &&
2162 "Other GD should now be a multiversioned function");
2163 // OtherFD is the version of this function that was mangled BEFORE
2164 // becoming a MultiVersion function. It potentially needs to be updated.
2165 const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
2166 .getDecl()
2167 ->getAsFunction()
2169 std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
2170 // This is so that if the initial version was already the 'default'
2171 // version, we don't try to update it.
2172 if (OtherName != NonTargetName) {
2173 // Remove instead of erase, since others may have stored the StringRef
2174 // to this.
2175 const auto ExistingRecord = Manglings.find(NonTargetName);
2176 if (ExistingRecord != std::end(Manglings))
2177 Manglings.remove(&(*ExistingRecord));
2178 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
2179 StringRef OtherNameRef = MangledDeclNames[OtherGD.getCanonicalDecl()] =
2180 Result.first->first();
2181 // If this is the current decl is being created, make sure we update the name.
2182 if (GD.getCanonicalDecl() == OtherGD.getCanonicalDecl())
2183 CurName = OtherNameRef;
2184 if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
2185 Entry->setName(OtherName);
2186 }
2187 }
2188}
2189
2191 GlobalDecl CanonicalGD = GD.getCanonicalDecl();
2192
2193 // Some ABIs don't have constructor variants. Make sure that base and
2194 // complete constructors get mangled the same.
2195 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
2196 if (!getTarget().getCXXABI().hasConstructorVariants()) {
2197 CXXCtorType OrigCtorType = GD.getCtorType();
2198 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
2199 if (OrigCtorType == Ctor_Base)
2200 CanonicalGD = GlobalDecl(CD, Ctor_Complete);
2201 }
2202 }
2203
2204 // In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a
2205 // static device variable depends on whether the variable is referenced by
2206 // a host or device host function. Therefore the mangled name cannot be
2207 // cached.
2208 if (!LangOpts.CUDAIsDevice || !getContext().mayExternalize(GD.getDecl())) {
2209 auto FoundName = MangledDeclNames.find(CanonicalGD);
2210 if (FoundName != MangledDeclNames.end())
2211 return FoundName->second;
2212 }
2213
2214 // Keep the first result in the case of a mangling collision.
2215 const auto *ND = cast<NamedDecl>(GD.getDecl());
2216 std::string MangledName = getMangledNameImpl(*this, GD, ND);
2217
2218 // Ensure either we have different ABIs between host and device compilations,
2219 // says host compilation following MSVC ABI but device compilation follows
2220 // Itanium C++ ABI or, if they follow the same ABI, kernel names after
2221 // mangling should be the same after name stubbing. The later checking is
2222 // very important as the device kernel name being mangled in host-compilation
2223 // is used to resolve the device binaries to be executed. Inconsistent naming
2224 // result in undefined behavior. Even though we cannot check that naming
2225 // directly between host- and device-compilations, the host- and
2226 // device-mangling in host compilation could help catching certain ones.
2227 assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() ||
2228 getContext().shouldExternalize(ND) || getLangOpts().CUDAIsDevice ||
2229 (getContext().getAuxTargetInfo() &&
2230 (getContext().getAuxTargetInfo()->getCXXABI() !=
2231 getContext().getTargetInfo().getCXXABI())) ||
2232 getCUDARuntime().getDeviceSideName(ND) ==
2234 *this,
2236 ND));
2237
2238 // This invariant should hold true in the future.
2239 // Prior work:
2240 // https://discourse.llvm.org/t/rfc-clang-diagnostic-for-demangling-failures/82835/8
2241 // https://github.com/llvm/llvm-project/issues/111345
2242 // assert(!((StringRef(MangledName).starts_with("_Z") ||
2243 // StringRef(MangledName).starts_with("?")) &&
2244 // !GD.getDecl()->hasAttr<AsmLabelAttr>() &&
2245 // llvm::demangle(MangledName) == MangledName) &&
2246 // "LLVM demangler must demangle clang-generated names");
2247
2248 auto Result = Manglings.insert(std::make_pair(MangledName, GD));
2249 return MangledDeclNames[CanonicalGD] = Result.first->first();
2250}
2251
2253 const BlockDecl *BD) {
2254 MangleContext &MangleCtx = getCXXABI().getMangleContext();
2255 const Decl *D = GD.getDecl();
2256
2257 SmallString<256> Buffer;
2258 llvm::raw_svector_ostream Out(Buffer);
2259 if (!D)
2260 MangleCtx.mangleGlobalBlock(BD,
2261 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
2262 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
2263 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
2264 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
2265 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
2266 else
2267 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
2268
2269 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
2270 return Result.first->first();
2271}
2272
2274 auto it = MangledDeclNames.begin();
2275 while (it != MangledDeclNames.end()) {
2276 if (it->second == Name)
2277 return it->first;
2278 it++;
2279 }
2280 return GlobalDecl();
2281}
2282
2283llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
2284 return getModule().getNamedValue(Name);
2285}
2286
2287/// AddGlobalCtor - Add a function to the list that will be called before
2288/// main() runs.
2289void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
2290 unsigned LexOrder,
2291 llvm::Constant *AssociatedData) {
2292 // FIXME: Type coercion of void()* types.
2293 GlobalCtors.push_back(Structor(Priority, LexOrder, Ctor, AssociatedData));
2294}
2295
2296/// AddGlobalDtor - Add a function to the list that will be called
2297/// when the module is unloaded.
2298void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority,
2299 bool IsDtorAttrFunc) {
2300 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
2301 (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) {
2302 DtorsUsingAtExit[Priority].push_back(Dtor);
2303 return;
2304 }
2305
2306 // FIXME: Type coercion of void()* types.
2307 GlobalDtors.push_back(Structor(Priority, ~0U, Dtor, nullptr));
2308}
2309
2310void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
2311 if (Fns.empty()) return;
2312
2313 const PointerAuthSchema &InitFiniAuthSchema =
2315
2316 // Ctor function type is ptr.
2317 llvm::PointerType *PtrTy = llvm::PointerType::get(
2318 getLLVMContext(), TheModule.getDataLayout().getProgramAddressSpace());
2319
2320 // Get the type of a ctor entry, { i32, ptr, ptr }.
2321 llvm::StructType *CtorStructTy = llvm::StructType::get(Int32Ty, PtrTy, PtrTy);
2322
2323 // Construct the constructor and destructor arrays.
2324 ConstantInitBuilder Builder(*this);
2325 auto Ctors = Builder.beginArray(CtorStructTy);
2326 for (const auto &I : Fns) {
2327 auto Ctor = Ctors.beginStruct(CtorStructTy);
2328 Ctor.addInt(Int32Ty, I.Priority);
2329 if (InitFiniAuthSchema) {
2330 llvm::Constant *StorageAddress =
2331 (InitFiniAuthSchema.isAddressDiscriminated()
2332 ? llvm::ConstantExpr::getIntToPtr(
2333 llvm::ConstantInt::get(
2334 IntPtrTy,
2335 llvm::ConstantPtrAuth::AddrDiscriminator_CtorsDtors),
2336 PtrTy)
2337 : nullptr);
2338 llvm::Constant *SignedCtorPtr = getConstantSignedPointer(
2339 I.Initializer, InitFiniAuthSchema.getKey(), StorageAddress,
2340 llvm::ConstantInt::get(
2341 SizeTy, InitFiniAuthSchema.getConstantDiscrimination()));
2342 Ctor.add(SignedCtorPtr);
2343 } else {
2344 Ctor.add(I.Initializer);
2345 }
2346 if (I.AssociatedData)
2347 Ctor.add(I.AssociatedData);
2348 else
2349 Ctor.addNullPointer(PtrTy);
2350 Ctor.finishAndAddTo(Ctors);
2351 }
2352
2353 auto List = Ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
2354 /*constant*/ false,
2355 llvm::GlobalValue::AppendingLinkage);
2356
2357 // The LTO linker doesn't seem to like it when we set an alignment
2358 // on appending variables. Take it off as a workaround.
2359 List->setAlignment(std::nullopt);
2360
2361 Fns.clear();
2362}
2363
2364llvm::GlobalValue::LinkageTypes
2366 const auto *D = cast<FunctionDecl>(GD.getDecl());
2367
2369
2370 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
2372
2374}
2375
2376llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
2377 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
2378 if (!MDS) return nullptr;
2379
2380 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
2381}
2382
2384 const RecordType *UT = Ty->getAsUnionType();
2385 if (!UT)
2386 return Ty;
2387 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2388 if (!UD->hasAttr<TransparentUnionAttr>())
2389 return Ty;
2390 if (!UD->fields().empty())
2391 return UD->fields().begin()->getType();
2392 return Ty;
2393}
2394
2395// If `GeneralizePointers` is true, generalizes types to a void pointer with the
2396// qualifiers of the originally pointed-to type, e.g. 'const char *' and 'char *
2397// const *' generalize to 'const void *' while 'char *' and 'const char **'
2398// generalize to 'void *'.
2400 bool GeneralizePointers) {
2402
2403 if (!GeneralizePointers || !Ty->isPointerType())
2404 return Ty;
2405
2406 return Ctx.getPointerType(
2407 QualType(Ctx.VoidTy)
2409}
2410
2411// Apply type generalization to a FunctionType's return and argument types
2413 bool GeneralizePointers) {
2414 if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
2415 SmallVector<QualType, 8> GeneralizedParams;
2416 for (auto &Param : FnType->param_types())
2417 GeneralizedParams.push_back(
2418 GeneralizeType(Ctx, Param, GeneralizePointers));
2419
2420 return Ctx.getFunctionType(
2421 GeneralizeType(Ctx, FnType->getReturnType(), GeneralizePointers),
2422 GeneralizedParams, FnType->getExtProtoInfo());
2423 }
2424
2425 if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
2426 return Ctx.getFunctionNoProtoType(
2427 GeneralizeType(Ctx, FnType->getReturnType(), GeneralizePointers));
2428
2429 llvm_unreachable("Encountered unknown FunctionType");
2430}
2431
2432llvm::ConstantInt *CodeGenModule::CreateKCFITypeId(QualType T, StringRef Salt) {
2434 getContext(), T, getCodeGenOpts().SanitizeCfiICallGeneralizePointers);
2435 if (auto *FnType = T->getAs<FunctionProtoType>())
2437 FnType->getReturnType(), FnType->getParamTypes(),
2438 FnType->getExtProtoInfo().withExceptionSpec(EST_None));
2439
2440 std::string OutName;
2441 llvm::raw_string_ostream Out(OutName);
2443 T, Out, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers);
2444
2445 if (!Salt.empty())
2446 Out << "." << Salt;
2447
2448 if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers)
2449 Out << ".normalized";
2450 if (getCodeGenOpts().SanitizeCfiICallGeneralizePointers)
2451 Out << ".generalized";
2452
2453 return llvm::ConstantInt::get(Int32Ty,
2454 static_cast<uint32_t>(llvm::xxHash64(OutName)));
2455}
2456
2458 const CGFunctionInfo &Info,
2459 llvm::Function *F, bool IsThunk) {
2460 unsigned CallingConv;
2461 llvm::AttributeList PAL;
2462 ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv,
2463 /*AttrOnCallSite=*/false, IsThunk);
2464 if (CallingConv == llvm::CallingConv::X86_VectorCall &&
2465 getTarget().getTriple().isWindowsArm64EC()) {
2466 SourceLocation Loc;
2467 if (const Decl *D = GD.getDecl())
2468 Loc = D->getLocation();
2469
2470 Error(Loc, "__vectorcall calling convention is not currently supported");
2471 }
2472 F->setAttributes(PAL);
2473 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
2474}
2475
2476static void removeImageAccessQualifier(std::string& TyName) {
2477 std::string ReadOnlyQual("__read_only");
2478 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
2479 if (ReadOnlyPos != std::string::npos)
2480 // "+ 1" for the space after access qualifier.
2481 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
2482 else {
2483 std::string WriteOnlyQual("__write_only");
2484 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
2485 if (WriteOnlyPos != std::string::npos)
2486 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
2487 else {
2488 std::string ReadWriteQual("__read_write");
2489 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
2490 if (ReadWritePos != std::string::npos)
2491 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
2492 }
2493 }
2494}
2495
2496// Returns the address space id that should be produced to the
2497// kernel_arg_addr_space metadata. This is always fixed to the ids
2498// as specified in the SPIR 2.0 specification in order to differentiate
2499// for example in clGetKernelArgInfo() implementation between the address
2500// spaces with targets without unique mapping to the OpenCL address spaces
2501// (basically all single AS CPUs).
2502static unsigned ArgInfoAddressSpace(LangAS AS) {
2503 switch (AS) {
2505 return 1;
2507 return 2;
2509 return 3;
2511 return 4; // Not in SPIR 2.0 specs.
2513 return 5;
2515 return 6;
2516 default:
2517 return 0; // Assume private.
2518 }
2519}
2520
2522 const FunctionDecl *FD,
2523 CodeGenFunction *CGF) {
2524 assert(((FD && CGF) || (!FD && !CGF)) &&
2525 "Incorrect use - FD and CGF should either be both null or not!");
2526 // Create MDNodes that represent the kernel arg metadata.
2527 // Each MDNode is a list in the form of "key", N number of values which is
2528 // the same number of values as their are kernel arguments.
2529
2530 const PrintingPolicy &Policy = Context.getPrintingPolicy();
2531
2532 // MDNode for the kernel argument address space qualifiers.
2534
2535 // MDNode for the kernel argument access qualifiers (images only).
2537
2538 // MDNode for the kernel argument type names.
2540
2541 // MDNode for the kernel argument base type names.
2542 SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
2543
2544 // MDNode for the kernel argument type qualifiers.
2546
2547 // MDNode for the kernel argument names.
2549
2550 if (FD && CGF)
2551 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
2552 const ParmVarDecl *parm = FD->getParamDecl(i);
2553 // Get argument name.
2554 argNames.push_back(llvm::MDString::get(VMContext, parm->getName()));
2555
2556 if (!getLangOpts().OpenCL)
2557 continue;
2558 QualType ty = parm->getType();
2559 std::string typeQuals;
2560
2561 // Get image and pipe access qualifier:
2562 if (ty->isImageType() || ty->isPipeType()) {
2563 const Decl *PDecl = parm;
2564 if (const auto *TD = ty->getAs<TypedefType>())
2565 PDecl = TD->getDecl();
2566 const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
2567 if (A && A->isWriteOnly())
2568 accessQuals.push_back(llvm::MDString::get(VMContext, "write_only"));
2569 else if (A && A->isReadWrite())
2570 accessQuals.push_back(llvm::MDString::get(VMContext, "read_write"));
2571 else
2572 accessQuals.push_back(llvm::MDString::get(VMContext, "read_only"));
2573 } else
2574 accessQuals.push_back(llvm::MDString::get(VMContext, "none"));
2575
2576 auto getTypeSpelling = [&](QualType Ty) {
2577 auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
2578
2579 if (Ty.isCanonical()) {
2580 StringRef typeNameRef = typeName;
2581 // Turn "unsigned type" to "utype"
2582 if (typeNameRef.consume_front("unsigned "))
2583 return std::string("u") + typeNameRef.str();
2584 if (typeNameRef.consume_front("signed "))
2585 return typeNameRef.str();
2586 }
2587
2588 return typeName;
2589 };
2590
2591 if (ty->isPointerType()) {
2592 QualType pointeeTy = ty->getPointeeType();
2593
2594 // Get address qualifier.
2595 addressQuals.push_back(
2596 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(
2597 ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
2598
2599 // Get argument type name.
2600 std::string typeName = getTypeSpelling(pointeeTy) + "*";
2601 std::string baseTypeName =
2602 getTypeSpelling(pointeeTy.getCanonicalType()) + "*";
2603 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2604 argBaseTypeNames.push_back(
2605 llvm::MDString::get(VMContext, baseTypeName));
2606
2607 // Get argument type qualifiers:
2608 if (ty.isRestrictQualified())
2609 typeQuals = "restrict";
2610 if (pointeeTy.isConstQualified() ||
2612 typeQuals += typeQuals.empty() ? "const" : " const";
2613 if (pointeeTy.isVolatileQualified())
2614 typeQuals += typeQuals.empty() ? "volatile" : " volatile";
2615 } else {
2616 uint32_t AddrSpc = 0;
2617 bool isPipe = ty->isPipeType();
2618 if (ty->isImageType() || isPipe)
2620
2621 addressQuals.push_back(
2622 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc)));
2623
2624 // Get argument type name.
2625 ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty;
2626 std::string typeName = getTypeSpelling(ty);
2627 std::string baseTypeName = getTypeSpelling(ty.getCanonicalType());
2628
2629 // Remove access qualifiers on images
2630 // (as they are inseparable from type in clang implementation,
2631 // but OpenCL spec provides a special query to get access qualifier
2632 // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
2633 if (ty->isImageType()) {
2635 removeImageAccessQualifier(baseTypeName);
2636 }
2637
2638 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
2639 argBaseTypeNames.push_back(
2640 llvm::MDString::get(VMContext, baseTypeName));
2641
2642 if (isPipe)
2643 typeQuals = "pipe";
2644 }
2645 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
2646 }
2647
2648 if (getLangOpts().OpenCL) {
2649 Fn->setMetadata("kernel_arg_addr_space",
2650 llvm::MDNode::get(VMContext, addressQuals));
2651 Fn->setMetadata("kernel_arg_access_qual",
2652 llvm::MDNode::get(VMContext, accessQuals));
2653 Fn->setMetadata("kernel_arg_type",
2654 llvm::MDNode::get(VMContext, argTypeNames));
2655 Fn->setMetadata("kernel_arg_base_type",
2656 llvm::MDNode::get(VMContext, argBaseTypeNames));
2657 Fn->setMetadata("kernel_arg_type_qual",
2658 llvm::MDNode::get(VMContext, argTypeQuals));
2659 }
2660 if (getCodeGenOpts().EmitOpenCLArgMetadata ||
2661 getCodeGenOpts().HIPSaveKernelArgName)
2662 Fn->setMetadata("kernel_arg_name",
2663 llvm::MDNode::get(VMContext, argNames));
2664}
2665
2666/// Determines whether the language options require us to model
2667/// unwind exceptions. We treat -fexceptions as mandating this
2668/// except under the fragile ObjC ABI with only ObjC exceptions
2669/// enabled. This means, for example, that C with -fexceptions
2670/// enables this.
2671static bool hasUnwindExceptions(const LangOptions &LangOpts) {
2672 // If exceptions are completely disabled, obviously this is false.
2673 if (!LangOpts.Exceptions) return false;
2674
2675 // If C++ exceptions are enabled, this is true.
2676 if (LangOpts.CXXExceptions) return true;
2677
2678 // If ObjC exceptions are enabled, this depends on the ABI.
2679 if (LangOpts.ObjCExceptions) {
2680 return LangOpts.ObjCRuntime.hasUnwindExceptions();
2681 }
2682
2683 return true;
2684}
2685
2687 const CXXMethodDecl *MD) {
2688 // Check that the type metadata can ever actually be used by a call.
2689 if (!CGM.getCodeGenOpts().LTOUnit ||
2691 return false;
2692
2693 // Only functions whose address can be taken with a member function pointer
2694 // need this sort of type metadata.
2695 return MD->isImplicitObjectMemberFunction() && !MD->isVirtual() &&
2697}
2698
2699SmallVector<const CXXRecordDecl *, 0>
2701 llvm::SetVector<const CXXRecordDecl *> MostBases;
2702
2703 std::function<void (const CXXRecordDecl *)> CollectMostBases;
2704 CollectMostBases = [&](const CXXRecordDecl *RD) {
2705 if (RD->getNumBases() == 0)
2706 MostBases.insert(RD);
2707 for (const CXXBaseSpecifier &B : RD->bases())
2708 CollectMostBases(B.getType()->getAsCXXRecordDecl());
2709 };
2710 CollectMostBases(RD);
2711 return MostBases.takeVector();
2712}
2713
2715 llvm::Function *F) {
2716 llvm::AttrBuilder B(F->getContext());
2717
2718 if ((!D || !D->hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables)
2719 B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
2720
2721 if (CodeGenOpts.StackClashProtector)
2722 B.addAttribute("probe-stack", "inline-asm");
2723
2724 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
2725 B.addAttribute("stack-probe-size",
2726 std::to_string(CodeGenOpts.StackProbeSize));
2727
2728 if (!hasUnwindExceptions(LangOpts))
2729 B.addAttribute(llvm::Attribute::NoUnwind);
2730
2731 if (D && D->hasAttr<NoStackProtectorAttr>())
2732 ; // Do nothing.
2733 else if (D && D->hasAttr<StrictGuardStackCheckAttr>() &&
2735 B.addAttribute(llvm::Attribute::StackProtectStrong);
2736 else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPOn))
2737 B.addAttribute(llvm::Attribute::StackProtect);
2739 B.addAttribute(llvm::Attribute::StackProtectStrong);
2740 else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPReq))
2741 B.addAttribute(llvm::Attribute::StackProtectReq);
2742
2743 if (!D) {
2744 // Non-entry HLSL functions must always be inlined.
2745 if (getLangOpts().HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline))
2746 B.addAttribute(llvm::Attribute::AlwaysInline);
2747 // If we don't have a declaration to control inlining, the function isn't
2748 // explicitly marked as alwaysinline for semantic reasons, and inlining is
2749 // disabled, mark the function as noinline.
2750 else if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
2751 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
2752 B.addAttribute(llvm::Attribute::NoInline);
2753
2754 F->addFnAttrs(B);
2755 return;
2756 }
2757
2758 // Handle SME attributes that apply to function definitions,
2759 // rather than to function prototypes.
2760 if (D->hasAttr<ArmLocallyStreamingAttr>())
2761 B.addAttribute("aarch64_pstate_sm_body");
2762
2763 if (auto *Attr = D->getAttr<ArmNewAttr>()) {
2764 if (Attr->isNewZA())
2765 B.addAttribute("aarch64_new_za");
2766 if (Attr->isNewZT0())
2767 B.addAttribute("aarch64_new_zt0");
2768 }
2769
2770 // Track whether we need to add the optnone LLVM attribute,
2771 // starting with the default for this optimization level.
2772 bool ShouldAddOptNone =
2773 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
2774 // We can't add optnone in the following cases, it won't pass the verifier.
2775 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
2776 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
2777
2778 // Non-entry HLSL functions must always be inlined.
2779 if (getLangOpts().HLSL && !F->hasFnAttribute(llvm::Attribute::NoInline) &&
2780 !D->hasAttr<NoInlineAttr>()) {
2781 B.addAttribute(llvm::Attribute::AlwaysInline);
2782 } else if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) &&
2783 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2784 // Add optnone, but do so only if the function isn't always_inline.
2785 B.addAttribute(llvm::Attribute::OptimizeNone);
2786
2787 // OptimizeNone implies noinline; we should not be inlining such functions.
2788 B.addAttribute(llvm::Attribute::NoInline);
2789
2790 // We still need to handle naked functions even though optnone subsumes
2791 // much of their semantics.
2792 if (D->hasAttr<NakedAttr>())
2793 B.addAttribute(llvm::Attribute::Naked);
2794
2795 // OptimizeNone wins over OptimizeForSize and MinSize.
2796 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
2797 F->removeFnAttr(llvm::Attribute::MinSize);
2798 } else if (D->hasAttr<NakedAttr>()) {
2799 // Naked implies noinline: we should not be inlining such functions.
2800 B.addAttribute(llvm::Attribute::Naked);
2801 B.addAttribute(llvm::Attribute::NoInline);
2802 } else if (D->hasAttr<NoDuplicateAttr>()) {
2803 B.addAttribute(llvm::Attribute::NoDuplicate);
2804 } else if (D->hasAttr<NoInlineAttr>() &&
2805 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2806 // Add noinline if the function isn't always_inline.
2807 B.addAttribute(llvm::Attribute::NoInline);
2808 } else if (D->hasAttr<AlwaysInlineAttr>() &&
2809 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
2810 // (noinline wins over always_inline, and we can't specify both in IR)
2811 B.addAttribute(llvm::Attribute::AlwaysInline);
2812 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
2813 // If we're not inlining, then force everything that isn't always_inline to
2814 // carry an explicit noinline attribute.
2815 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
2816 B.addAttribute(llvm::Attribute::NoInline);
2817 } else {
2818 // Otherwise, propagate the inline hint attribute and potentially use its
2819 // absence to mark things as noinline.
2820 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
2821 // Search function and template pattern redeclarations for inline.
2822 auto CheckForInline = [](const FunctionDecl *FD) {
2823 auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
2824 return Redecl->isInlineSpecified();
2825 };
2826 if (any_of(FD->redecls(), CheckRedeclForInline))
2827 return true;
2828 const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
2829 if (!Pattern)
2830 return false;
2831 return any_of(Pattern->redecls(), CheckRedeclForInline);
2832 };
2833 if (CheckForInline(FD)) {
2834 B.addAttribute(llvm::Attribute::InlineHint);
2835 } else if (CodeGenOpts.getInlining() ==
2837 !FD->isInlined() &&
2838 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
2839 B.addAttribute(llvm::Attribute::NoInline);
2840 }
2841 }
2842 }
2843
2844 // Add other optimization related attributes if we are optimizing this
2845 // function.
2846 if (!D->hasAttr<OptimizeNoneAttr>()) {
2847 if (D->hasAttr<ColdAttr>()) {
2848 if (!ShouldAddOptNone)
2849 B.addAttribute(llvm::Attribute::OptimizeForSize);
2850 B.addAttribute(llvm::Attribute::Cold);
2851 }
2852 if (D->hasAttr<HotAttr>())
2853 B.addAttribute(llvm::Attribute::Hot);
2854 if (D->hasAttr<MinSizeAttr>())
2855 B.addAttribute(llvm::Attribute::MinSize);
2856 }
2857
2858 F->addFnAttrs(B);
2859
2860 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
2861 if (alignment)
2862 F->setAlignment(llvm::Align(alignment));
2863
2864 if (!D->hasAttr<AlignedAttr>())
2865 if (LangOpts.FunctionAlignment)
2866 F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
2867
2868 // Some C++ ABIs require 2-byte alignment for member functions, in order to
2869 // reserve a bit for differentiating between virtual and non-virtual member
2870 // functions. If the current target's C++ ABI requires this and this is a
2871 // member function, set its alignment accordingly.
2872 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
2873 if (isa<CXXMethodDecl>(D) && F->getPointerAlignment(getDataLayout()) < 2)
2874 F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne()));
2875 }
2876
2877 // In the cross-dso CFI mode with canonical jump tables, we want !type
2878 // attributes on definitions only.
2879 if (CodeGenOpts.SanitizeCfiCrossDso &&
2880 CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
2881 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
2882 // Skip available_externally functions. They won't be codegen'ed in the
2883 // current module anyway.
2884 if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally)
2886 }
2887 }
2888
2889 if (CodeGenOpts.CallGraphSection) {
2890 if (auto *FD = dyn_cast<FunctionDecl>(D))
2892 }
2893
2894 // Emit type metadata on member functions for member function pointer checks.
2895 // These are only ever necessary on definitions; we're guaranteed that the
2896 // definition will be present in the LTO unit as a result of LTO visibility.
2897 auto *MD = dyn_cast<CXXMethodDecl>(D);
2898 if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
2899 for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
2900 llvm::Metadata *Id =
2901 CreateMetadataIdentifierForType(Context.getMemberPointerType(
2902 MD->getType(), /*Qualifier=*/std::nullopt, Base));
2903 F->addTypeMetadata(0, Id);
2904 }
2905 }
2906}
2907
2908void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
2909 const Decl *D = GD.getDecl();
2910 if (isa_and_nonnull<NamedDecl>(D))
2911 setGVProperties(GV, GD);
2912 else
2913 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
2914
2915 if (D && D->hasAttr<UsedAttr>())
2917
2918 if (const auto *VD = dyn_cast_if_present<VarDecl>(D);
2919 VD &&
2920 ((CodeGenOpts.KeepPersistentStorageVariables &&
2921 (VD->getStorageDuration() == SD_Static ||
2922 VD->getStorageDuration() == SD_Thread)) ||
2923 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static &&
2924 VD->getType().isConstQualified())))
2926}
2927
2928bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
2929 llvm::AttrBuilder &Attrs,
2930 bool SetTargetFeatures) {
2931 // Add target-cpu and target-features attributes to functions. If
2932 // we have a decl for the function and it has a target attribute then
2933 // parse that and add it to the feature set.
2934 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
2935 StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU;
2936 std::vector<std::string> Features;
2937 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
2938 FD = FD ? FD->getMostRecentDecl() : FD;
2939 const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
2940 const auto *TV = FD ? FD->getAttr<TargetVersionAttr>() : nullptr;
2941 assert((!TD || !TV) && "both target_version and target specified");
2942 const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
2943 const auto *TC = FD ? FD->getAttr<TargetClonesAttr>() : nullptr;
2944 bool AddedAttr = false;
2945 if (TD || TV || SD || TC) {
2946 llvm::StringMap<bool> FeatureMap;
2947 getContext().getFunctionFeatureMap(FeatureMap, GD);
2948
2949 // Produce the canonical string for this set of features.
2950 for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
2951 Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
2952
2953 // Now add the target-cpu and target-features to the function.
2954 // While we populated the feature map above, we still need to
2955 // get and parse the target attribute so we can get the cpu for
2956 // the function.
2957 if (TD) {
2959 Target.parseTargetAttr(TD->getFeaturesStr());
2960 if (!ParsedAttr.CPU.empty() &&
2961 getTarget().isValidCPUName(ParsedAttr.CPU)) {
2962 TargetCPU = ParsedAttr.CPU;
2963 TuneCPU = ""; // Clear the tune CPU.
2964 }
2965 if (!ParsedAttr.Tune.empty() &&
2966 getTarget().isValidCPUName(ParsedAttr.Tune))
2967 TuneCPU = ParsedAttr.Tune;
2968 }
2969
2970 if (SD) {
2971 // Apply the given CPU name as the 'tune-cpu' so that the optimizer can
2972 // favor this processor.
2973 TuneCPU = SD->getCPUName(GD.getMultiVersionIndex())->getName();
2974 }
2975 } else {
2976 // Otherwise just add the existing target cpu and target features to the
2977 // function.
2978 Features = getTarget().getTargetOpts().Features;
2979 }
2980
2981 if (!TargetCPU.empty()) {
2982 Attrs.addAttribute("target-cpu", TargetCPU);
2983 AddedAttr = true;
2984 }
2985 if (!TuneCPU.empty()) {
2986 Attrs.addAttribute("tune-cpu", TuneCPU);
2987 AddedAttr = true;
2988 }
2989 if (!Features.empty() && SetTargetFeatures) {
2990 llvm::erase_if(Features, [&](const std::string& F) {
2991 return getTarget().isReadOnlyFeature(F.substr(1));
2992 });
2993 llvm::sort(Features);
2994 Attrs.addAttribute("target-features", llvm::join(Features, ","));
2995 AddedAttr = true;
2996 }
2997 // Add metadata for AArch64 Function Multi Versioning.
2998 if (getTarget().getTriple().isAArch64()) {
2999 llvm::SmallVector<StringRef, 8> Feats;
3000 bool IsDefault = false;
3001 if (TV) {
3002 IsDefault = TV->isDefaultVersion();
3003 TV->getFeatures(Feats);
3004 } else if (TC) {
3005 IsDefault = TC->isDefaultVersion(GD.getMultiVersionIndex());
3006 TC->getFeatures(Feats, GD.getMultiVersionIndex());
3007 }
3008 if (IsDefault) {
3009 Attrs.addAttribute("fmv-features");
3010 AddedAttr = true;
3011 } else if (!Feats.empty()) {
3012 // Sort features and remove duplicates.
3013 std::set<StringRef> OrderedFeats(Feats.begin(), Feats.end());
3014 std::string FMVFeatures;
3015 for (StringRef F : OrderedFeats)
3016 FMVFeatures.append("," + F.str());
3017 Attrs.addAttribute("fmv-features", FMVFeatures.substr(1));
3018 AddedAttr = true;
3019 }
3020 }
3021 return AddedAttr;
3022}
3023
3024void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
3025 llvm::GlobalObject *GO) {
3026 const Decl *D = GD.getDecl();
3027 SetCommonAttributes(GD, GO);
3028
3029 if (D) {
3030 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
3031 if (D->hasAttr<RetainAttr>())
3032 addUsedGlobal(GV);
3033 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
3034 GV->addAttribute("bss-section", SA->getName());
3035 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
3036 GV->addAttribute("data-section", SA->getName());
3037 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
3038 GV->addAttribute("rodata-section", SA->getName());
3039 if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>())
3040 GV->addAttribute("relro-section", SA->getName());
3041 }
3042
3043 if (auto *F = dyn_cast<llvm::Function>(GO)) {
3044 if (D->hasAttr<RetainAttr>())
3045 addUsedGlobal(F);
3046 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
3047 if (!D->getAttr<SectionAttr>())
3048 F->setSection(SA->getName());
3049
3050 llvm::AttrBuilder Attrs(F->getContext());
3051 if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
3052 // We know that GetCPUAndFeaturesAttributes will always have the
3053 // newest set, since it has the newest possible FunctionDecl, so the
3054 // new ones should replace the old.
3055 llvm::AttributeMask RemoveAttrs;
3056 RemoveAttrs.addAttribute("target-cpu");
3057 RemoveAttrs.addAttribute("target-features");
3058 RemoveAttrs.addAttribute("fmv-features");
3059 RemoveAttrs.addAttribute("tune-cpu");
3060 F->removeFnAttrs(RemoveAttrs);
3061 F->addFnAttrs(Attrs);
3062 }
3063 }
3064
3065 if (const auto *CSA = D->getAttr<CodeSegAttr>())
3066 GO->setSection(CSA->getName());
3067 else if (const auto *SA = D->getAttr<SectionAttr>())
3068 GO->setSection(SA->getName());
3069 }
3070
3072}
3073
3075 llvm::Function *F,
3076 const CGFunctionInfo &FI) {
3077 const Decl *D = GD.getDecl();
3078 SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false);
3080
3081 F->setLinkage(llvm::Function::InternalLinkage);
3082
3083 setNonAliasAttributes(GD, F);
3084}
3085
3086static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
3087 // Set linkage and visibility in case we never see a definition.
3089 // Don't set internal linkage on declarations.
3090 // "extern_weak" is overloaded in LLVM; we probably should have
3091 // separate linkage types for this.
3092 if (isExternallyVisible(LV.getLinkage()) &&
3093 (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
3094 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
3095}
3096
3097static bool hasExistingGeneralizedTypeMD(llvm::Function *F) {
3098 llvm::MDNode *MD = F->getMetadata(llvm::LLVMContext::MD_type);
3099 return MD && MD->hasGeneralizedMDString();
3100}
3101
3103 llvm::Function *F) {
3104 // Return if generalized type metadata is already attached.
3106 return;
3107
3108 // All functions which are not internal linkage could be indirect targets.
3109 // Address taken functions with internal linkage could be indirect targets.
3110 if (!F->hasLocalLinkage() ||
3111 F->getFunction().hasAddressTaken(nullptr, /*IgnoreCallbackUses=*/true,
3112 /*IgnoreAssumeLikeCalls=*/true,
3113 /*IgnoreLLVMUsed=*/false))
3114 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
3115}
3116
3118 llvm::Function *F) {
3119 // Only if we are checking indirect calls.
3120 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
3121 return;
3122
3123 // Non-static class methods are handled via vtable or member function pointer
3124 // checks elsewhere.
3125 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
3126 return;
3127
3129 /*GeneralizePointers=*/false);
3130 llvm::Metadata *MD = CreateMetadataIdentifierForType(FnType);
3131 F->addTypeMetadata(0, MD);
3132 // Add the generalized identifier if not added already.
3134 QualType GenPtrFnType = GeneralizeFunctionType(getContext(), FD->getType(),
3135 /*GeneralizePointers=*/true);
3136 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(GenPtrFnType));
3137 }
3138
3139 // Emit a hash-based bit set entry for cross-DSO calls.
3140 if (CodeGenOpts.SanitizeCfiCrossDso)
3141 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
3142 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
3143}
3144
3146 llvm::CallBase *CB) {
3147 // Only if needed for call graph section and only for indirect calls.
3148 if (!CodeGenOpts.CallGraphSection || !CB->isIndirectCall())
3149 return;
3150
3151 llvm::Metadata *TypeIdMD = CreateMetadataIdentifierGeneralized(QT);
3152 llvm::MDTuple *TypeTuple = llvm::MDTuple::get(
3153 getLLVMContext(), {llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
3154 llvm::Type::getInt64Ty(getLLVMContext()), 0)),
3155 TypeIdMD});
3156 llvm::MDTuple *MDN = llvm::MDNode::get(getLLVMContext(), {TypeTuple});
3157 CB->setMetadata(llvm::LLVMContext::MD_callee_type, MDN);
3158}
3159
3160void CodeGenModule::setKCFIType(const FunctionDecl *FD, llvm::Function *F) {
3161 llvm::LLVMContext &Ctx = F->getContext();
3162 llvm::MDBuilder MDB(Ctx);
3163 llvm::StringRef Salt;
3164
3165 if (const auto *FP = FD->getType()->getAs<FunctionProtoType>())
3166 if (const auto &Info = FP->getExtraAttributeInfo())
3167 Salt = Info.CFISalt;
3168
3169 F->setMetadata(llvm::LLVMContext::MD_kcfi_type,
3170 llvm::MDNode::get(Ctx, MDB.createConstant(CreateKCFITypeId(
3171 FD->getType(), Salt))));
3172}
3173
3174static bool allowKCFIIdentifier(StringRef Name) {
3175 // KCFI type identifier constants are only necessary for external assembly
3176 // functions, which means it's safe to skip unusual names. Subset of
3177 // MCAsmInfo::isAcceptableChar() and MCAsmInfoXCOFF::isAcceptableChar().
3178 return llvm::all_of(Name, [](const char &C) {
3179 return llvm::isAlnum(C) || C == '_' || C == '.';
3180 });
3181}
3182
3184 llvm::Module &M = getModule();
3185 for (auto &F : M.functions()) {
3186 // Remove KCFI type metadata from non-address-taken local functions.
3187 bool AddressTaken = F.hasAddressTaken();
3188 if (!AddressTaken && F.hasLocalLinkage())
3189 F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type);
3190
3191 // Generate a constant with the expected KCFI type identifier for all
3192 // address-taken function declarations to support annotating indirectly
3193 // called assembly functions.
3194 if (!AddressTaken || !F.isDeclaration())
3195 continue;
3196
3197 const llvm::ConstantInt *Type;
3198 if (const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type))
3199 Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0));
3200 else
3201 continue;
3202
3203 StringRef Name = F.getName();
3204 if (!allowKCFIIdentifier(Name))
3205 continue;
3206
3207 std::string Asm = (".weak __kcfi_typeid_" + Name + "\n.set __kcfi_typeid_" +
3208 Name + ", " + Twine(Type->getZExtValue()) + "\n")
3209 .str();
3210 M.appendModuleInlineAsm(Asm);
3211 }
3212}
3213
3214void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
3215 bool IsIncompleteFunction,
3216 bool IsThunk) {
3217
3218 if (F->getIntrinsicID() != llvm::Intrinsic::not_intrinsic) {
3219 // If this is an intrinsic function, the attributes will have been set
3220 // when the function was created.
3221 return;
3222 }
3223
3224 const auto *FD = cast<FunctionDecl>(GD.getDecl());
3225
3226 if (!IsIncompleteFunction)
3227 SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F,
3228 IsThunk);
3229
3230 // Add the Returned attribute for "this", except for iOS 5 and earlier
3231 // where substantial code, including the libstdc++ dylib, was compiled with
3232 // GCC and does not actually return "this".
3233 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
3234 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
3235 assert(!F->arg_empty() &&
3236 F->arg_begin()->getType()
3237 ->canLosslesslyBitCastTo(F->getReturnType()) &&
3238 "unexpected this return");
3239 F->addParamAttr(0, llvm::Attribute::Returned);
3240 }
3241
3242 // Only a few attributes are set on declarations; these may later be
3243 // overridden by a definition.
3244
3245 setLinkageForGV(F, FD);
3246 setGVProperties(F, FD);
3247
3248 // Setup target-specific attributes.
3249 if (!IsIncompleteFunction && F->isDeclaration())
3251
3252 if (const auto *CSA = FD->getAttr<CodeSegAttr>())
3253 F->setSection(CSA->getName());
3254 else if (const auto *SA = FD->getAttr<SectionAttr>())
3255 F->setSection(SA->getName());
3256
3257 if (const auto *EA = FD->getAttr<ErrorAttr>()) {
3258 if (EA->isError())
3259 F->addFnAttr("dontcall-error", EA->getUserDiagnostic());
3260 else if (EA->isWarning())
3261 F->addFnAttr("dontcall-warn", EA->getUserDiagnostic());
3262 }
3263
3264 // If we plan on emitting this inline builtin, we can't treat it as a builtin.
3265 if (FD->isInlineBuiltinDeclaration()) {
3266 const FunctionDecl *FDBody;
3267 bool HasBody = FD->hasBody(FDBody);
3268 (void)HasBody;
3269 assert(HasBody && "Inline builtin declarations should always have an "
3270 "available body!");
3271 if (shouldEmitFunction(FDBody))
3272 F->addFnAttr(llvm::Attribute::NoBuiltin);
3273 }
3274
3276 // A replaceable global allocation function does not act like a builtin by
3277 // default, only if it is invoked by a new-expression or delete-expression.
3278 F->addFnAttr(llvm::Attribute::NoBuiltin);
3279 }
3280
3282 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3283 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
3284 if (MD->isVirtual())
3285 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3286
3287 // Don't emit entries for function declarations in the cross-DSO mode. This
3288 // is handled with better precision by the receiving DSO. But if jump tables
3289 // are non-canonical then we need type metadata in order to produce the local
3290 // jump table.
3291 if (!CodeGenOpts.SanitizeCfiCrossDso ||
3292 !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
3294
3295 if (CodeGenOpts.CallGraphSection)
3297
3298 if (LangOpts.Sanitize.has(SanitizerKind::KCFI))
3299 setKCFIType(FD, F);
3300
3301 if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
3303
3304 if (CodeGenOpts.InlineMaxStackSize != UINT_MAX)
3305 F->addFnAttr("inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize));
3306
3307 if (const auto *CB = FD->getAttr<CallbackAttr>()) {
3308 // Annotate the callback behavior as metadata:
3309 // - The callback callee (as argument number).
3310 // - The callback payloads (as argument numbers).
3311 llvm::LLVMContext &Ctx = F->getContext();
3312 llvm::MDBuilder MDB(Ctx);
3313
3314 // The payload indices are all but the first one in the encoding. The first
3315 // identifies the callback callee.
3316 int CalleeIdx = *CB->encoding_begin();
3317 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
3318 F->addMetadata(llvm::LLVMContext::MD_callback,
3319 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
3320 CalleeIdx, PayloadIndices,
3321 /* VarArgsArePassed */ false)}));
3322 }
3323}
3324
3325void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
3326 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
3327 "Only globals with definition can force usage.");
3328 LLVMUsed.emplace_back(GV);
3329}
3330
3331void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
3332 assert(!GV->isDeclaration() &&
3333 "Only globals with definition can force usage.");
3334 LLVMCompilerUsed.emplace_back(GV);
3335}
3336
3338 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
3339 "Only globals with definition can force usage.");
3340 if (getTriple().isOSBinFormatELF())
3341 LLVMCompilerUsed.emplace_back(GV);
3342 else
3343 LLVMUsed.emplace_back(GV);
3344}
3345
3346static void emitUsed(CodeGenModule &CGM, StringRef Name,
3347 std::vector<llvm::WeakTrackingVH> &List) {
3348 // Don't create llvm.used if there is no need.
3349 if (List.empty())
3350 return;
3351
3352 // Convert List to what ConstantArray needs.
3354 UsedArray.resize(List.size());
3355 for (unsigned i = 0, e = List.size(); i != e; ++i) {
3356 UsedArray[i] =
3357 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
3358 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
3359 }
3360
3361 if (UsedArray.empty())
3362 return;
3363 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
3364
3365 auto *GV = new llvm::GlobalVariable(
3366 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
3367 llvm::ConstantArray::get(ATy, UsedArray), Name);
3368
3369 GV->setSection("llvm.metadata");
3370}
3371
3372void CodeGenModule::emitLLVMUsed() {
3373 emitUsed(*this, "llvm.used", LLVMUsed);
3374 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
3375}
3376
3378 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
3379 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
3380}
3381
3382void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
3385 if (Opt.empty())
3386 return;
3387 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
3388 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
3389}
3390
3392 auto &C = getLLVMContext();
3393 if (getTarget().getTriple().isOSBinFormatELF()) {
3394 ELFDependentLibraries.push_back(
3395 llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
3396 return;
3397 }
3398
3401 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
3402 LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
3403}
3404
3405/// Add link options implied by the given module, including modules
3406/// it depends on, using a postorder walk.
3410 // Import this module's parent.
3411 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
3412 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
3413 }
3414
3415 // Import this module's dependencies.
3416 for (Module *Import : llvm::reverse(Mod->Imports)) {
3417 if (Visited.insert(Import).second)
3418 addLinkOptionsPostorder(CGM, Import, Metadata, Visited);
3419 }
3420
3421 // Add linker options to link against the libraries/frameworks
3422 // described by this module.
3423 llvm::LLVMContext &Context = CGM.getLLVMContext();
3424 bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
3425
3426 // For modules that use export_as for linking, use that module
3427 // name instead.
3429 return;
3430
3431 for (const Module::LinkLibrary &LL : llvm::reverse(Mod->LinkLibraries)) {
3432 // Link against a framework. Frameworks are currently Darwin only, so we
3433 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
3434 if (LL.IsFramework) {
3435 llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
3436 llvm::MDString::get(Context, LL.Library)};
3437
3438 Metadata.push_back(llvm::MDNode::get(Context, Args));
3439 continue;
3440 }
3441
3442 // Link against a library.
3443 if (IsELF) {
3444 llvm::Metadata *Args[2] = {
3445 llvm::MDString::get(Context, "lib"),
3446 llvm::MDString::get(Context, LL.Library),
3447 };
3448 Metadata.push_back(llvm::MDNode::get(Context, Args));
3449 } else {
3451 CGM.getTargetCodeGenInfo().getDependentLibraryOption(LL.Library, Opt);
3452 auto *OptString = llvm::MDString::get(Context, Opt);
3453 Metadata.push_back(llvm::MDNode::get(Context, OptString));
3454 }
3455 }
3456}
3457
3458void CodeGenModule::EmitModuleInitializers(clang::Module *Primary) {
3459 assert(Primary->isNamedModuleUnit() &&
3460 "We should only emit module initializers for named modules.");
3461
3462 // Emit the initializers in the order that sub-modules appear in the
3463 // source, first Global Module Fragments, if present.
3464 if (auto GMF = Primary->getGlobalModuleFragment()) {
3465 for (Decl *D : getContext().getModuleInitializers(GMF)) {
3466 if (isa<ImportDecl>(D))
3467 continue;
3468 assert(isa<VarDecl>(D) && "GMF initializer decl is not a var?");
3470 }
3471 }
3472 // Second any associated with the module, itself.
3473 for (Decl *D : getContext().getModuleInitializers(Primary)) {
3474 // Skip import decls, the inits for those are called explicitly.
3475 if (isa<ImportDecl>(D))
3476 continue;
3478 }
3479 // Third any associated with the Privat eMOdule Fragment, if present.
3480 if (auto PMF = Primary->getPrivateModuleFragment()) {
3481 for (Decl *D : getContext().getModuleInitializers(PMF)) {
3482 // Skip import decls, the inits for those are called explicitly.
3483 if (isa<ImportDecl>(D))
3484 continue;
3485 assert(isa<VarDecl>(D) && "PMF initializer decl is not a var?");
3487 }
3488 }
3489}
3490
3491void CodeGenModule::EmitModuleLinkOptions() {
3492 // Collect the set of all of the modules we want to visit to emit link
3493 // options, which is essentially the imported modules and all of their
3494 // non-explicit child modules.
3495 llvm::SetVector<clang::Module *> LinkModules;
3496 llvm::SmallPtrSet<clang::Module *, 16> Visited;
3497 SmallVector<clang::Module *, 16> Stack;
3498
3499 // Seed the stack with imported modules.
3500 for (Module *M : ImportedModules) {
3501 // Do not add any link flags when an implementation TU of a module imports
3502 // a header of that same module.
3503 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
3504 !getLangOpts().isCompilingModule())
3505 continue;
3506 if (Visited.insert(M).second)
3507 Stack.push_back(M);
3508 }
3509
3510 // Find all of the modules to import, making a little effort to prune
3511 // non-leaf modules.
3512 while (!Stack.empty()) {
3513 clang::Module *Mod = Stack.pop_back_val();
3514
3515 bool AnyChildren = false;
3516
3517 // Visit the submodules of this module.
3518 for (const auto &SM : Mod->submodules()) {
3519 // Skip explicit children; they need to be explicitly imported to be
3520 // linked against.
3521 if (SM->IsExplicit)
3522 continue;
3523
3524 if (Visited.insert(SM).second) {
3525 Stack.push_back(SM);
3526 AnyChildren = true;
3527 }
3528 }
3529
3530 // We didn't find any children, so add this module to the list of
3531 // modules to link against.
3532 if (!AnyChildren) {
3533 LinkModules.insert(Mod);
3534 }
3535 }
3536
3537 // Add link options for all of the imported modules in reverse topological
3538 // order. We don't do anything to try to order import link flags with respect
3539 // to linker options inserted by things like #pragma comment().
3540 SmallVector<llvm::MDNode *, 16> MetadataArgs;
3541 Visited.clear();
3542 for (Module *M : LinkModules)
3543 if (Visited.insert(M).second)
3544 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
3545 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
3546 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
3547
3548 // Add the linker options metadata flag.
3549 if (!LinkerOptionsMetadata.empty()) {
3550 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
3551 for (auto *MD : LinkerOptionsMetadata)
3552 NMD->addOperand(MD);
3553 }
3554}
3555
3556void CodeGenModule::EmitDeferred() {
3557 // Emit deferred declare target declarations.
3558 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
3560
3561 // Emit code for any potentially referenced deferred decls. Since a
3562 // previously unused static decl may become used during the generation of code
3563 // for a static function, iterate until no changes are made.
3564
3565 if (!DeferredVTables.empty()) {
3566 EmitDeferredVTables();
3567
3568 // Emitting a vtable doesn't directly cause more vtables to
3569 // become deferred, although it can cause functions to be
3570 // emitted that then need those vtables.
3571 assert(DeferredVTables.empty());
3572 }
3573
3574 // Emit CUDA/HIP static device variables referenced by host code only.
3575 // Note we should not clear CUDADeviceVarODRUsedByHost since it is still
3576 // needed for further handling.
3577 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
3578 llvm::append_range(DeferredDeclsToEmit,
3579 getContext().CUDADeviceVarODRUsedByHost);
3580
3581 // Stop if we're out of both deferred vtables and deferred declarations.
3582 if (DeferredDeclsToEmit.empty())
3583 return;
3584
3585 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
3586 // work, it will not interfere with this.
3587 std::vector<GlobalDecl> CurDeclsToEmit;
3588 CurDeclsToEmit.swap(DeferredDeclsToEmit);
3589
3590 for (GlobalDecl &D : CurDeclsToEmit) {
3591 // Functions declared with the sycl_kernel_entry_point attribute are
3592 // emitted normally during host compilation. During device compilation,
3593 // a SYCL kernel caller offload entry point function is generated and
3594 // emitted in place of each of these functions.
3595 if (const auto *FD = D.getDecl()->getAsFunction()) {
3596 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelEntryPointAttr>() &&
3597 FD->isDefined()) {
3598 // Functions with an invalid sycl_kernel_entry_point attribute are
3599 // ignored during device compilation.
3600 if (!FD->getAttr<SYCLKernelEntryPointAttr>()->isInvalidAttr()) {
3601 // Generate and emit the SYCL kernel caller function.
3602 EmitSYCLKernelCaller(FD, getContext());
3603 // Recurse to emit any symbols directly or indirectly referenced
3604 // by the SYCL kernel caller function.
3605 EmitDeferred();
3606 }
3607 // Do not emit the sycl_kernel_entry_point attributed function.
3608 continue;
3609 }
3610 }
3611
3612 // We should call GetAddrOfGlobal with IsForDefinition set to true in order
3613 // to get GlobalValue with exactly the type we need, not something that
3614 // might had been created for another decl with the same mangled name but
3615 // different type.
3616 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
3618
3619 // In case of different address spaces, we may still get a cast, even with
3620 // IsForDefinition equal to true. Query mangled names table to get
3621 // GlobalValue.
3622 if (!GV)
3624
3625 // Make sure GetGlobalValue returned non-null.
3626 assert(GV);
3627
3628 // Check to see if we've already emitted this. This is necessary
3629 // for a couple of reasons: first, decls can end up in the
3630 // deferred-decls queue multiple times, and second, decls can end
3631 // up with definitions in unusual ways (e.g. by an extern inline
3632 // function acquiring a strong function redefinition). Just
3633 // ignore these cases.
3634 if (!GV->isDeclaration())
3635 continue;
3636
3637 // If this is OpenMP, check if it is legal to emit this global normally.
3638 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
3639 continue;
3640
3641 // Otherwise, emit the definition and move on to the next one.
3642 EmitGlobalDefinition(D, GV);
3643
3644 // If we found out that we need to emit more decls, do that recursively.
3645 // This has the advantage that the decls are emitted in a DFS and related
3646 // ones are close together, which is convenient for testing.
3647 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
3648 EmitDeferred();
3649 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
3650 }
3651 }
3652}
3653
3654void CodeGenModule::EmitVTablesOpportunistically() {
3655 // Try to emit external vtables as available_externally if they have emitted
3656 // all inlined virtual functions. It runs after EmitDeferred() and therefore
3657 // is not allowed to create new references to things that need to be emitted
3658 // lazily. Note that it also uses fact that we eagerly emitting RTTI.
3659
3660 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
3661 && "Only emit opportunistic vtables with optimizations");
3662
3663 for (const CXXRecordDecl *RD : OpportunisticVTables) {
3664 assert(getVTables().isVTableExternal(RD) &&
3665 "This queue should only contain external vtables");
3666 if (getCXXABI().canSpeculativelyEmitVTable(RD))
3667 VTables.GenerateClassData(RD);
3668 }
3669 OpportunisticVTables.clear();
3670}
3671
3673 for (const auto& [MangledName, VD] : DeferredAnnotations) {
3674 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
3675 if (GV)
3676 AddGlobalAnnotations(VD, GV);
3677 }
3678 DeferredAnnotations.clear();
3679
3680 if (Annotations.empty())
3681 return;
3682
3683 // Create a new global variable for the ConstantStruct in the Module.
3684 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
3685 Annotations[0]->getType(), Annotations.size()), Annotations);
3686 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
3687 llvm::GlobalValue::AppendingLinkage,
3688 Array, "llvm.global.annotations");
3689 gv->setSection(AnnotationSection);
3690}
3691
3692llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
3693 llvm::Constant *&AStr = AnnotationStrings[Str];
3694 if (AStr)
3695 return AStr;
3696
3697 // Not found yet, create a new global.
3698 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
3699 auto *gv = new llvm::GlobalVariable(
3700 getModule(), s->getType(), true, llvm::GlobalValue::PrivateLinkage, s,
3701 ".str", nullptr, llvm::GlobalValue::NotThreadLocal,
3702 ConstGlobalsPtrTy->getAddressSpace());
3703 gv->setSection(AnnotationSection);
3704 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3705 AStr = gv;
3706 return gv;
3707}
3708
3711 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
3712 if (PLoc.isValid())
3713 return EmitAnnotationString(PLoc.getFilename());
3714 return EmitAnnotationString(SM.getBufferName(Loc));
3715}
3716
3719 PresumedLoc PLoc = SM.getPresumedLoc(L);
3720 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
3721 SM.getExpansionLineNumber(L);
3722 return llvm::ConstantInt::get(Int32Ty, LineNo);
3723}
3724
3725llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) {
3726 ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()};
3727 if (Exprs.empty())
3728 return llvm::ConstantPointerNull::get(ConstGlobalsPtrTy);
3729
3730 llvm::FoldingSetNodeID ID;
3731 for (Expr *E : Exprs) {
3732 ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult());
3733 }
3734 llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
3735 if (Lookup)
3736 return Lookup;
3737
3739 LLVMArgs.reserve(Exprs.size());
3740 ConstantEmitter ConstEmiter(*this);
3741 llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) {
3742 const auto *CE = cast<clang::ConstantExpr>(E);
3743 return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
3744 CE->getType());
3745 });
3746 auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
3747 auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true,
3748 llvm::GlobalValue::PrivateLinkage, Struct,
3749 ".args");
3750 GV->setSection(AnnotationSection);
3751 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3752
3753 Lookup = GV;
3754 return GV;
3755}
3756
3757llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
3758 const AnnotateAttr *AA,
3759 SourceLocation L) {
3760 // Get the globals for file name, annotation, and the line number.
3761 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
3762 *UnitGV = EmitAnnotationUnit(L),
3763 *LineNoCst = EmitAnnotationLineNo(L),
3764 *Args = EmitAnnotationArgs(AA);
3765
3766 llvm::Constant *GVInGlobalsAS = GV;
3767 if (GV->getAddressSpace() !=
3768 getDataLayout().getDefaultGlobalsAddressSpace()) {
3769 GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast(
3770 GV,
3771 llvm::PointerType::get(
3772 GV->getContext(), getDataLayout().getDefaultGlobalsAddressSpace()));
3773 }
3774
3775 // Create the ConstantStruct for the global annotation.
3776 llvm::Constant *Fields[] = {
3777 GVInGlobalsAS, AnnoGV, UnitGV, LineNoCst, Args,
3778 };
3779 return llvm::ConstantStruct::getAnon(Fields);
3780}
3781
3783 llvm::GlobalValue *GV) {
3784 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
3785 // Get the struct elements for these annotations.
3786 for (const auto *I : D->specific_attrs<AnnotateAttr>())
3787 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
3788}
3789
3791 SourceLocation Loc) const {
3792 const auto &NoSanitizeL = getContext().getNoSanitizeList();
3793 // NoSanitize by function name.
3794 if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
3795 return true;
3796 // NoSanitize by location. Check "mainfile" prefix.
3797 auto &SM = Context.getSourceManager();
3798 FileEntryRef MainFile = *SM.getFileEntryRefForID(SM.getMainFileID());
3799 if (NoSanitizeL.containsMainFile(Kind, MainFile.getName()))
3800 return true;
3801
3802 // Check "src" prefix.
3803 if (Loc.isValid())
3804 return NoSanitizeL.containsLocation(Kind, Loc);
3805 // If location is unknown, this may be a compiler-generated function. Assume
3806 // it's located in the main file.
3807 return NoSanitizeL.containsFile(Kind, MainFile.getName());
3808}
3809
3811 llvm::GlobalVariable *GV,
3812 SourceLocation Loc, QualType Ty,
3813 StringRef Category) const {
3814 const auto &NoSanitizeL = getContext().getNoSanitizeList();
3815 if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category))
3816 return true;
3817 auto &SM = Context.getSourceManager();
3818 if (NoSanitizeL.containsMainFile(
3819 Kind, SM.getFileEntryRefForID(SM.getMainFileID())->getName(),
3820 Category))
3821 return true;
3822 if (NoSanitizeL.containsLocation(Kind, Loc, Category))
3823 return true;
3824
3825 // Check global type.
3826 if (!Ty.isNull()) {
3827 // Drill down the array types: if global variable of a fixed type is
3828 // not sanitized, we also don't instrument arrays of them.
3829 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
3830 Ty = AT->getElementType();
3832 // Only record types (classes, structs etc.) are ignored.
3833 if (Ty->isRecordType()) {
3834 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
3835 if (NoSanitizeL.containsType(Kind, TypeStr, Category))
3836 return true;
3837 }
3838 }
3839 return false;
3840}
3841
3843 StringRef Category) const {
3844 const auto &XRayFilter = getContext().getXRayFilter();
3845 using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
3846 auto Attr = ImbueAttr::NONE;
3847 if (Loc.isValid())
3848 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
3849 if (Attr == ImbueAttr::NONE)
3850 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
3851 switch (Attr) {
3852 case ImbueAttr::NONE:
3853 return false;
3854 case ImbueAttr::ALWAYS:
3855 Fn->addFnAttr("function-instrument", "xray-always");
3856 break;
3857 case ImbueAttr::ALWAYS_ARG1:
3858 Fn->addFnAttr("function-instrument", "xray-always");
3859 Fn->addFnAttr("xray-log-args", "1");
3860 break;
3861 case ImbueAttr::NEVER:
3862 Fn->addFnAttr("function-instrument", "xray-never");
3863 break;
3864 }
3865 return true;
3866}
3867
3870 SourceLocation Loc) const {
3871 const auto &ProfileList = getContext().getProfileList();
3872 // If the profile list is empty, then instrument everything.
3873 if (ProfileList.isEmpty())
3874 return ProfileList::Allow;
3875 llvm::driver::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr();
3876 // First, check the function name.
3877 if (auto V = ProfileList.isFunctionExcluded(Fn->getName(), Kind))
3878 return *V;
3879 // Next, check the source location.
3880 if (Loc.isValid())
3881 if (auto V = ProfileList.isLocationExcluded(Loc, Kind))
3882 return *V;
3883 // If location is unknown, this may be a compiler-generated function. Assume
3884 // it's located in the main file.
3885 auto &SM = Context.getSourceManager();
3886 if (auto MainFile = SM.getFileEntryRefForID(SM.getMainFileID()))
3887 if (auto V = ProfileList.isFileExcluded(MainFile->getName(), Kind))
3888 return *V;
3889 return ProfileList.getDefault(Kind);
3890}
3891
3894 SourceLocation Loc) const {
3895 auto V = isFunctionBlockedByProfileList(Fn, Loc);
3896 if (V != ProfileList::Allow)
3897 return V;
3898
3899 auto NumGroups = getCodeGenOpts().ProfileTotalFunctionGroups;
3900 if (NumGroups > 1) {
3901 auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups;
3902 if (Group != getCodeGenOpts().ProfileSelectedFunctionGroup)
3903 return ProfileList::Skip;
3904 }
3905 return ProfileList::Allow;
3906}
3907
3908bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
3909 // Never defer when EmitAllDecls is specified.
3910 if (LangOpts.EmitAllDecls)
3911 return true;
3912
3913 const auto *VD = dyn_cast<VarDecl>(Global);
3914 if (VD &&
3915 ((CodeGenOpts.KeepPersistentStorageVariables &&
3916 (VD->getStorageDuration() == SD_Static ||
3917 VD->getStorageDuration() == SD_Thread)) ||
3918 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static &&
3919 VD->getType().isConstQualified())))
3920 return true;
3921
3923}
3924
3925bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
3926 // In OpenMP 5.0 variables and function may be marked as
3927 // device_type(host/nohost) and we should not emit them eagerly unless we sure
3928 // that they must be emitted on the host/device. To be sure we need to have
3929 // seen a declare target with an explicit mentioning of the function, we know
3930 // we have if the level of the declare target attribute is -1. Note that we
3931 // check somewhere else if we should emit this at all.
3932 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
3933 std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
3934 OMPDeclareTargetDeclAttr::getActiveAttr(Global);
3935 if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1)
3936 return false;
3937 }
3938
3939 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
3941 // Implicit template instantiations may change linkage if they are later
3942 // explicitly instantiated, so they should not be emitted eagerly.
3943 return false;
3944 // Defer until all versions have been semantically checked.
3945 if (FD->hasAttr<TargetVersionAttr>() && !FD->isMultiVersion())
3946 return false;
3947 // Defer emission of SYCL kernel entry point functions during device
3948 // compilation.
3949 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelEntryPointAttr>())
3950 return false;
3951 }
3952 if (const auto *VD = dyn_cast<VarDecl>(Global)) {
3953 if (Context.getInlineVariableDefinitionKind(VD) ==
3955 // A definition of an inline constexpr static data member may change
3956 // linkage later if it's redeclared outside the class.
3957 return false;
3958 if (CXX20ModuleInits && VD->getOwningModule() &&
3959 !VD->getOwningModule()->isModuleMapModule()) {
3960 // For CXX20, module-owned initializers need to be deferred, since it is
3961 // not known at this point if they will be run for the current module or
3962 // as part of the initializer for an imported one.
3963 return false;
3964 }
3965 }
3966 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
3967 // codegen for global variables, because they may be marked as threadprivate.
3968 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
3969 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
3970 !Global->getType().isConstantStorage(getContext(), false, false) &&
3971 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
3972 return false;
3973
3974 return true;
3975}
3976
3978 StringRef Name = getMangledName(GD);
3979
3980 // The UUID descriptor should be pointer aligned.
3982
3983 // Look for an existing global.
3984 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
3985 return ConstantAddress(GV, GV->getValueType(), Alignment);
3986
3987 ConstantEmitter Emitter(*this);
3988 llvm::Constant *Init;
3989
3990 APValue &V = GD->getAsAPValue();
3991 if (!V.isAbsent()) {
3992 // If possible, emit the APValue version of the initializer. In particular,
3993 // this gets the type of the constant right.
3994 Init = Emitter.emitForInitializer(
3995 GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType());
3996 } else {
3997 // As a fallback, directly construct the constant.
3998 // FIXME: This may get padding wrong under esoteric struct layout rules.
3999 // MSVC appears to create a complete type 'struct __s_GUID' that it
4000 // presumably uses to represent these constants.
4001 MSGuidDecl::Parts Parts = GD->getParts();
4002 llvm::Constant *Fields[4] = {
4003 llvm::ConstantInt::get(Int32Ty, Parts.Part1),
4004 llvm::ConstantInt::get(Int16Ty, Parts.Part2),
4005 llvm::ConstantInt::get(Int16Ty, Parts.Part3),
4006 llvm::ConstantDataArray::getRaw(
4007 StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8,
4008 Int8Ty)};
4009 Init = llvm::ConstantStruct::getAnon(Fields);
4010 }
4011
4012 auto *GV = new llvm::GlobalVariable(
4013 getModule(), Init->getType(),
4014 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
4015 if (supportsCOMDAT())
4016 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4017 setDSOLocal(GV);
4018
4019 if (!V.isAbsent()) {
4020 Emitter.finalize(GV);
4021 return ConstantAddress(GV, GV->getValueType(), Alignment);
4022 }
4023
4024 llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType());
4025 return ConstantAddress(GV, Ty, Alignment);
4026}
4027
4029 const UnnamedGlobalConstantDecl *GCD) {
4030 CharUnits Alignment = getContext().getTypeAlignInChars(GCD->getType());
4031
4032 llvm::GlobalVariable **Entry = nullptr;
4033 Entry = &UnnamedGlobalConstantDeclMap[GCD];
4034 if (*Entry)
4035 return ConstantAddress(*Entry, (*Entry)->getValueType(), Alignment);
4036
4037 ConstantEmitter Emitter(*this);
4038 llvm::Constant *Init;
4039
4040 const APValue &V = GCD->getValue();
4041
4042 assert(!V.isAbsent());
4043 Init = Emitter.emitForInitializer(V, GCD->getType().getAddressSpace(),
4044 GCD->getType());
4045
4046 auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(),
4047 /*isConstant=*/true,
4048 llvm::GlobalValue::PrivateLinkage, Init,
4049 ".constant");
4050 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4051 GV->setAlignment(Alignment.getAsAlign());
4052
4053 Emitter.finalize(GV);
4054
4055 *Entry = GV;
4056 return ConstantAddress(GV, GV->getValueType(), Alignment);
4057}
4058
4060 const TemplateParamObjectDecl *TPO) {
4061 StringRef Name = getMangledName(TPO);
4062 CharUnits Alignment = getNaturalTypeAlignment(TPO->getType());
4063
4064 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
4065 return ConstantAddress(GV, GV->getValueType(), Alignment);
4066
4067 ConstantEmitter Emitter(*this);
4068 llvm::Constant *Init = Emitter.emitForInitializer(
4069 TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType());
4070
4071 if (!Init) {
4072 ErrorUnsupported(TPO, "template parameter object");
4073 return ConstantAddress::invalid();
4074 }
4075
4076 llvm::GlobalValue::LinkageTypes Linkage =
4078 ? llvm::GlobalValue::LinkOnceODRLinkage
4079 : llvm::GlobalValue::InternalLinkage;
4080 auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(),
4081 /*isConstant=*/true, Linkage, Init, Name);
4082 setGVProperties(GV, TPO);
4083 if (supportsCOMDAT() && Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
4084 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4085 Emitter.finalize(GV);
4086
4087 return ConstantAddress(GV, GV->getValueType(), Alignment);
4088}
4089
4091 const AliasAttr *AA = VD->getAttr<AliasAttr>();
4092 assert(AA && "No alias?");
4093
4094 CharUnits Alignment = getContext().getDeclAlign(VD);
4095 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
4096
4097 // See if there is already something with the target's name in the module.
4098 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
4099 if (Entry)
4100 return ConstantAddress(Entry, DeclTy, Alignment);
4101
4102 llvm::Constant *Aliasee;
4103 if (isa<llvm::FunctionType>(DeclTy))
4104 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
4106 /*ForVTable=*/false);
4107 else
4108 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
4109 nullptr);
4110
4111 auto *F = cast<llvm::GlobalValue>(Aliasee);
4112 F->setLinkage(llvm::Function::ExternalWeakLinkage);
4113 WeakRefReferences.insert(F);
4114
4115 return ConstantAddress(Aliasee, DeclTy, Alignment);
4116}
4117
4118template <typename AttrT> static bool hasImplicitAttr(const ValueDecl *D) {
4119 if (!D)
4120 return false;
4121 if (auto *A = D->getAttr<AttrT>())
4122 return A->isImplicit();
4123 return D->isImplicit();
4124}
4125
4127 const ValueDecl *Global) {
4128 const LangOptions &LangOpts = CGM.getLangOpts();
4129 if (!LangOpts.OpenMPIsTargetDevice && !LangOpts.CUDA)
4130 return false;
4131
4132 const auto *AA = Global->getAttr<AliasAttr>();
4133 GlobalDecl AliaseeGD;
4134
4135 // Check if the aliasee exists, if the aliasee is not found, skip the alias
4136 // emission. This is executed for both the host and device.
4137 if (!CGM.lookupRepresentativeDecl(AA->getAliasee(), AliaseeGD))
4138 return true;
4139
4140 const auto *AliaseeDecl = dyn_cast<ValueDecl>(AliaseeGD.getDecl());
4141 if (LangOpts.OpenMPIsTargetDevice)
4142 return !AliaseeDecl ||
4143 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(AliaseeDecl);
4144
4145 // CUDA / HIP
4146 const bool HasDeviceAttr = Global->hasAttr<CUDADeviceAttr>();
4147 const bool AliaseeHasDeviceAttr =
4148 AliaseeDecl && AliaseeDecl->hasAttr<CUDADeviceAttr>();
4149
4150 if (LangOpts.CUDAIsDevice)
4151 return !HasDeviceAttr || !AliaseeHasDeviceAttr;
4152
4153 // CUDA / HIP Host
4154 // we know that the aliasee exists from above, so we know to emit
4155 return false;
4156}
4157
4158bool CodeGenModule::shouldEmitCUDAGlobalVar(const VarDecl *Global) const {
4159 assert(LangOpts.CUDA && "Should not be called by non-CUDA languages");
4160 // We need to emit host-side 'shadows' for all global
4161 // device-side variables because the CUDA runtime needs their
4162 // size and host-side address in order to provide access to
4163 // their device-side incarnations.
4164 return !LangOpts.CUDAIsDevice || Global->hasAttr<CUDADeviceAttr>() ||
4165 Global->hasAttr<CUDAConstantAttr>() ||
4166 Global->hasAttr<CUDASharedAttr>() ||
4167 Global->getType()->isCUDADeviceBuiltinSurfaceType() ||
4168 Global->getType()->isCUDADeviceBuiltinTextureType();
4169}
4170
4172 const auto *Global = cast<ValueDecl>(GD.getDecl());
4173
4174 // Weak references don't produce any output by themselves.
4175 if (Global->hasAttr<WeakRefAttr>())
4176 return;
4177
4178 // If this is an alias definition (which otherwise looks like a declaration)
4179 // emit it now.
4180 if (Global->hasAttr<AliasAttr>()) {
4181 if (shouldSkipAliasEmission(*this, Global))
4182 return;
4183 return EmitAliasDefinition(GD);
4184 }
4185
4186 // IFunc like an alias whose value is resolved at runtime by calling resolver.
4187 if (Global->hasAttr<IFuncAttr>())
4188 return emitIFuncDefinition(GD);
4189
4190 // If this is a cpu_dispatch multiversion function, emit the resolver.
4191 if (Global->hasAttr<CPUDispatchAttr>())
4192 return emitCPUDispatchDefinition(GD);
4193
4194 // If this is CUDA, be selective about which declarations we emit.
4195 // Non-constexpr non-lambda implicit host device functions are not emitted
4196 // unless they are used on device side.
4197 if (LangOpts.CUDA) {
4199 "Expected Variable or Function");
4200 if (const auto *VD = dyn_cast<VarDecl>(Global)) {
4201 if (!shouldEmitCUDAGlobalVar(VD))
4202 return;
4203 } else if (LangOpts.CUDAIsDevice) {
4204 const auto *FD = dyn_cast<FunctionDecl>(Global);
4205 if ((!Global->hasAttr<CUDADeviceAttr>() ||
4206 (LangOpts.OffloadImplicitHostDeviceTemplates &&
4209 !isLambdaCallOperator(FD) &&
4210 !getContext().CUDAImplicitHostDeviceFunUsedByDevice.count(FD))) &&
4211 !Global->hasAttr<CUDAGlobalAttr>() &&
4212 !(LangOpts.HIPStdPar && isa<FunctionDecl>(Global) &&
4213 !Global->hasAttr<CUDAHostAttr>()))
4214 return;
4215 // Device-only functions are the only things we skip.
4216 } else if (!Global->hasAttr<CUDAHostAttr>() &&
4217 Global->hasAttr<CUDADeviceAttr>())
4218 return;
4219 }
4220
4221 if (LangOpts.OpenMP) {
4222 // If this is OpenMP, check if it is legal to emit this global normally.
4223 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
4224 return;
4225 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
4226 if (MustBeEmitted(Global))
4228 return;
4229 }
4230 if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
4231 if (MustBeEmitted(Global))
4233 return;
4234 }
4235 }
4236
4237 // Ignore declarations, they will be emitted on their first use.
4238 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
4239 if (DeviceKernelAttr::isOpenCLSpelling(FD->getAttr<DeviceKernelAttr>()) &&
4241 addDeferredDeclToEmit(GlobalDecl(FD, KernelReferenceKind::Stub));
4242
4243 // Update deferred annotations with the latest declaration if the function
4244 // function was already used or defined.
4245 if (FD->hasAttr<AnnotateAttr>()) {
4246 StringRef MangledName = getMangledName(GD);
4247 if (GetGlobalValue(MangledName))
4248 DeferredAnnotations[MangledName] = FD;
4249 }
4250
4251 // Forward declarations are emitted lazily on first use.
4252 if (!FD->doesThisDeclarationHaveABody()) {
4254 (!FD->isMultiVersion() || !getTarget().getTriple().isAArch64()))
4255 return;
4256
4257 StringRef MangledName = getMangledName(GD);
4258
4259 // Compute the function info and LLVM type.
4261 llvm::Type *Ty = getTypes().GetFunctionType(FI);
4262
4263 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
4264 /*DontDefer=*/false);
4265 return;
4266 }
4267 } else {
4268 const auto *VD = cast<VarDecl>(Global);
4269 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
4270 if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
4271 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
4272 if (LangOpts.OpenMP) {
4273 // Emit declaration of the must-be-emitted declare target variable.
4274 if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
4275 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
4276
4277 // If this variable has external storage and doesn't require special
4278 // link handling we defer to its canonical definition.
4279 if (VD->hasExternalStorage() &&
4280 Res != OMPDeclareTargetDeclAttr::MT_Link)
4281 return;
4282
4283 bool UnifiedMemoryEnabled =
4285 if ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
4286 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
4287 !UnifiedMemoryEnabled) {
4288 (void)GetAddrOfGlobalVar(VD);
4289 } else {
4290 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
4291 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
4292 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
4293 UnifiedMemoryEnabled)) &&
4294 "Link clause or to clause with unified memory expected.");
4296 }
4297
4298 return;
4299 }
4300 }
4301 // If this declaration may have caused an inline variable definition to
4302 // change linkage, make sure that it's emitted.
4303 if (Context.getInlineVariableDefinitionKind(VD) ==
4306 return;
4307 }
4308 }
4309
4310 // Defer code generation to first use when possible, e.g. if this is an inline
4311 // function. If the global must always be emitted, do it eagerly if possible
4312 // to benefit from cache locality.
4313 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
4314 // Emit the definition if it can't be deferred.
4315 EmitGlobalDefinition(GD);
4316 addEmittedDeferredDecl(GD);
4317 return;
4318 }
4319
4320 // If we're deferring emission of a C++ variable with an
4321 // initializer, remember the order in which it appeared in the file.
4323 cast<VarDecl>(Global)->hasInit()) {
4324 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
4325 CXXGlobalInits.push_back(nullptr);
4326 }
4327
4328 StringRef MangledName = getMangledName(GD);
4329 if (GetGlobalValue(MangledName) != nullptr) {
4330 // The value has already been used and should therefore be emitted.
4331 addDeferredDeclToEmit(GD);
4332 } else if (MustBeEmitted(Global)) {
4333 // The value must be emitted, but cannot be emitted eagerly.
4334 assert(!MayBeEmittedEagerly(Global));
4335 addDeferredDeclToEmit(GD);
4336 } else {
4337 // Otherwise, remember that we saw a deferred decl with this name. The
4338 // first use of the mangled name will cause it to move into
4339 // DeferredDeclsToEmit.
4340 DeferredDecls[MangledName] = GD;
4341 }
4342}
4343
4344// Check if T is a class type with a destructor that's not dllimport.
4346 if (const auto *RT =
4347 T->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())
4348 if (auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
4349 RD = RD->getDefinitionOrSelf();
4350 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
4351 return true;
4352 }
4353
4354 return false;
4355}
4356
4357namespace {
4358 struct FunctionIsDirectlyRecursive
4359 : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
4360 const StringRef Name;
4361 const Builtin::Context &BI;
4362 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
4363 : Name(N), BI(C) {}
4364
4365 bool VisitCallExpr(const CallExpr *E) {
4366 const FunctionDecl *FD = E->getDirectCallee();
4367 if (!FD)
4368 return false;
4369 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
4370 if (Attr && Name == Attr->getLabel())
4371 return true;
4372 unsigned BuiltinID = FD->getBuiltinID();
4373 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
4374 return false;
4375 std::string BuiltinNameStr = BI.getName(BuiltinID);
4376 StringRef BuiltinName = BuiltinNameStr;
4377 return BuiltinName.consume_front("__builtin_") && Name == BuiltinName;
4378 }
4379
4380 bool VisitStmt(const Stmt *S) {
4381 for (const Stmt *Child : S->children())
4382 if (Child && this->Visit(Child))
4383 return true;
4384 return false;
4385 }
4386 };
4387
4388 // Make sure we're not referencing non-imported vars or functions.
4389 struct DLLImportFunctionVisitor
4390 : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
4391 bool SafeToInline = true;
4392
4393 bool shouldVisitImplicitCode() const { return true; }
4394
4395 bool VisitVarDecl(VarDecl *VD) {
4396 if (VD->getTLSKind()) {
4397 // A thread-local variable cannot be imported.
4398 SafeToInline = false;
4399 return SafeToInline;
4400 }
4401
4402 // A variable definition might imply a destructor call.
4404 SafeToInline = !HasNonDllImportDtor(VD->getType());
4405
4406 return SafeToInline;
4407 }
4408
4409 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
4410 if (const auto *D = E->getTemporary()->getDestructor())
4411 SafeToInline = D->hasAttr<DLLImportAttr>();
4412 return SafeToInline;
4413 }
4414
4415 bool VisitDeclRefExpr(DeclRefExpr *E) {
4416 ValueDecl *VD = E->getDecl();
4417 if (isa<FunctionDecl>(VD))
4418 SafeToInline = VD->hasAttr<DLLImportAttr>();
4419 else if (VarDecl *V = dyn_cast<VarDecl>(VD))
4420 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
4421 return SafeToInline;
4422 }
4423
4424 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
4425 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
4426 return SafeToInline;
4427 }
4428
4429 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4430 CXXMethodDecl *M = E->getMethodDecl();
4431 if (!M) {
4432 // Call through a pointer to member function. This is safe to inline.
4433 SafeToInline = true;
4434 } else {
4435 SafeToInline = M->hasAttr<DLLImportAttr>();
4436 }
4437 return SafeToInline;
4438 }
4439
4440 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
4441 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
4442 return SafeToInline;
4443 }
4444
4445 bool VisitCXXNewExpr(CXXNewExpr *E) {
4446 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
4447 return SafeToInline;
4448 }
4449 };
4450}
4451
4452// isTriviallyRecursive - Check if this function calls another
4453// decl that, because of the asm attribute or the other decl being a builtin,
4454// ends up pointing to itself.
4455bool
4456CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
4457 StringRef Name;
4458 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
4459 // asm labels are a special kind of mangling we have to support.
4460 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
4461 if (!Attr)
4462 return false;
4463 Name = Attr->getLabel();
4464 } else {
4465 Name = FD->getName();
4466 }
4467
4468 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
4469 const Stmt *Body = FD->getBody();
4470 return Body ? Walker.Visit(Body) : false;
4471}
4472
4473bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
4474 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
4475 return true;
4476
4477 const auto *F = cast<FunctionDecl>(GD.getDecl());
4478 // Inline builtins declaration must be emitted. They often are fortified
4479 // functions.
4480 if (F->isInlineBuiltinDeclaration())
4481 return true;
4482
4483 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
4484 return false;
4485
4486 // We don't import function bodies from other named module units since that
4487 // behavior may break ABI compatibility of the current unit.
4488 if (const Module *M = F->getOwningModule();
4489 M && M->getTopLevelModule()->isNamedModule() &&
4490 getContext().getCurrentNamedModule() != M->getTopLevelModule()) {
4491 // There are practices to mark template member function as always-inline
4492 // and mark the template as extern explicit instantiation but not give
4493 // the definition for member function. So we have to emit the function
4494 // from explicitly instantiation with always-inline.
4495 //
4496 // See https://github.com/llvm/llvm-project/issues/86893 for details.
4497 //
4498 // TODO: Maybe it is better to give it a warning if we call a non-inline
4499 // function from other module units which is marked as always-inline.
4500 if (!F->isTemplateInstantiation() || !F->hasAttr<AlwaysInlineAttr>()) {
4501 return false;
4502 }
4503 }
4504
4505 if (F->hasAttr<NoInlineAttr>())
4506 return false;
4507
4508 if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
4509 // Check whether it would be safe to inline this dllimport function.
4510 DLLImportFunctionVisitor Visitor;
4511 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
4512 if (!Visitor.SafeToInline)
4513 return false;
4514
4515 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
4516 // Implicit destructor invocations aren't captured in the AST, so the
4517 // check above can't see them. Check for them manually here.
4518 for (const Decl *Member : Dtor->getParent()->decls())
4521 return false;
4522 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
4523 if (HasNonDllImportDtor(B.getType()))
4524 return false;
4525 }
4526 }
4527
4528 // PR9614. Avoid cases where the source code is lying to us. An available
4529 // externally function should have an equivalent function somewhere else,
4530 // but a function that calls itself through asm label/`__builtin_` trickery is
4531 // clearly not equivalent to the real implementation.
4532 // This happens in glibc's btowc and in some configure checks.
4533 return !isTriviallyRecursive(F);
4534}
4535
4536bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
4537 return CodeGenOpts.OptimizationLevel > 0;
4538}
4539
4540void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
4541 llvm::GlobalValue *GV) {
4542 const auto *FD = cast<FunctionDecl>(GD.getDecl());
4543
4544 if (FD->isCPUSpecificMultiVersion()) {
4545 auto *Spec = FD->getAttr<CPUSpecificAttr>();
4546 for (unsigned I = 0; I < Spec->cpus_size(); ++I)
4547 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
4548 } else if (auto *TC = FD->getAttr<TargetClonesAttr>()) {
4549 for (unsigned I = 0; I < TC->featuresStrs_size(); ++I)
4550 if (TC->isFirstOfVersion(I))
4551 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
4552 } else
4553 EmitGlobalFunctionDefinition(GD, GV);
4554
4555 // Ensure that the resolver function is also emitted.
4557 // On AArch64 defer the resolver emission until the entire TU is processed.
4558 if (getTarget().getTriple().isAArch64())
4559 AddDeferredMultiVersionResolverToEmit(GD);
4560 else
4561 GetOrCreateMultiVersionResolver(GD);
4562 }
4563}
4564
4565void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
4566 const auto *D = cast<ValueDecl>(GD.getDecl());
4567
4568 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
4569 Context.getSourceManager(),
4570 "Generating code for declaration");
4571
4572 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4573 // At -O0, don't generate IR for functions with available_externally
4574 // linkage.
4575 if (!shouldEmitFunction(GD))
4576 return;
4577
4578 llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
4579 std::string Name;
4580 llvm::raw_string_ostream OS(Name);
4581 FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
4582 /*Qualified=*/true);
4583 return Name;
4584 });
4585
4586 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
4587 // Make sure to emit the definition(s) before we emit the thunks.
4588 // This is necessary for the generation of certain thunks.
4590 ABI->emitCXXStructor(GD);
4591 else if (FD->isMultiVersion())
4592 EmitMultiVersionFunctionDefinition(GD, GV);
4593 else
4594 EmitGlobalFunctionDefinition(GD, GV);
4595
4596 if (Method->isVirtual())
4597 getVTables().EmitThunks(GD);
4598
4599 return;
4600 }
4601
4602 if (FD->isMultiVersion())
4603 return EmitMultiVersionFunctionDefinition(GD, GV);
4604 return EmitGlobalFunctionDefinition(GD, GV);
4605 }
4606
4607 if (const auto *VD = dyn_cast<VarDecl>(D))
4608 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
4609
4610 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
4611}
4612
4613static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
4614 llvm::Function *NewFn);
4615
4616static llvm::APInt
4620 if (RO.Architecture)
4621 Features.push_back(*RO.Architecture);
4622 return TI.getFMVPriority(Features);
4623}
4624
4625// Multiversion functions should be at most 'WeakODRLinkage' so that a different
4626// TU can forward declare the function without causing problems. Particularly
4627// in the cases of CPUDispatch, this causes issues. This also makes sure we
4628// work with internal linkage functions, so that the same function name can be
4629// used with internal linkage in multiple TUs.
4630static llvm::GlobalValue::LinkageTypes
4632 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
4634 return llvm::GlobalValue::InternalLinkage;
4635 return llvm::GlobalValue::WeakODRLinkage;
4636}
4637
4638void CodeGenModule::emitMultiVersionFunctions() {
4639 std::vector<GlobalDecl> MVFuncsToEmit;
4640 MultiVersionFuncs.swap(MVFuncsToEmit);
4641 for (GlobalDecl GD : MVFuncsToEmit) {
4642 const auto *FD = cast<FunctionDecl>(GD.getDecl());
4643 assert(FD && "Expected a FunctionDecl");
4644
4645 auto createFunction = [&](const FunctionDecl *Decl, unsigned MVIdx = 0) {
4646 GlobalDecl CurGD{Decl->isDefined() ? Decl->getDefinition() : Decl, MVIdx};
4647 StringRef MangledName = getMangledName(CurGD);
4648 llvm::Constant *Func = GetGlobalValue(MangledName);
4649 if (!Func) {
4650 if (Decl->isDefined()) {
4651 EmitGlobalFunctionDefinition(CurGD, nullptr);
4652 Func = GetGlobalValue(MangledName);
4653 } else {
4654 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(CurGD);
4655 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
4656 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
4657 /*DontDefer=*/false, ForDefinition);
4658 }
4659 assert(Func && "This should have just been created");
4660 }
4661 return cast<llvm::Function>(Func);
4662 };
4663
4664 // For AArch64, a resolver is only emitted if a function marked with
4665 // target_version("default")) or target_clones("default") is defined
4666 // in this TU. For other architectures it is always emitted.
4667 bool ShouldEmitResolver = !getTarget().getTriple().isAArch64();
4668 SmallVector<CodeGenFunction::FMVResolverOption, 10> Options;
4669
4671 FD, [&](const FunctionDecl *CurFD) {
4672 llvm::SmallVector<StringRef, 8> Feats;
4673 bool IsDefined = CurFD->getDefinition() != nullptr;
4674
4675 if (const auto *TA = CurFD->getAttr<TargetAttr>()) {
4676 assert(getTarget().getTriple().isX86() && "Unsupported target");
4677 TA->getX86AddedFeatures(Feats);
4678 llvm::Function *Func = createFunction(CurFD);
4679 Options.emplace_back(Func, Feats, TA->getX86Architecture());
4680 } else if (const auto *TVA = CurFD->getAttr<TargetVersionAttr>()) {
4681 if (TVA->isDefaultVersion() && IsDefined)
4682 ShouldEmitResolver = true;
4683 llvm::Function *Func = createFunction(CurFD);
4684 char Delim = getTarget().getTriple().isAArch64() ? '+' : ',';
4685 TVA->getFeatures(Feats, Delim);
4686 Options.emplace_back(Func, Feats);
4687 } else if (const auto *TC = CurFD->getAttr<TargetClonesAttr>()) {
4688 for (unsigned I = 0; I < TC->featuresStrs_size(); ++I) {
4689 if (!TC->isFirstOfVersion(I))
4690 continue;
4691 if (TC->isDefaultVersion(I) && IsDefined)
4692 ShouldEmitResolver = true;
4693 llvm::Function *Func = createFunction(CurFD, I);
4694 Feats.clear();
4695 if (getTarget().getTriple().isX86()) {
4696 TC->getX86Feature(Feats, I);
4697 Options.emplace_back(Func, Feats, TC->getX86Architecture(I));
4698 } else {
4699 char Delim = getTarget().getTriple().isAArch64() ? '+' : ',';
4700 TC->getFeatures(Feats, I, Delim);
4701 Options.emplace_back(Func, Feats);
4702 }
4703 }
4704 } else
4705 llvm_unreachable("unexpected MultiVersionKind");
4706 });
4707
4708 if (!ShouldEmitResolver)
4709 continue;
4710
4711 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD);
4712 if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) {
4713 ResolverConstant = IFunc->getResolver();
4714 if (FD->isTargetClonesMultiVersion() &&
4715 !getTarget().getTriple().isAArch64()) {
4716 std::string MangledName = getMangledNameImpl(
4717 *this, GD, FD, /*OmitMultiVersionMangling=*/true);
4718 if (!GetGlobalValue(MangledName + ".ifunc")) {
4719 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4720 llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
4721 // In prior versions of Clang, the mangling for ifuncs incorrectly
4722 // included an .ifunc suffix. This alias is generated for backward
4723 // compatibility. It is deprecated, and may be removed in the future.
4724 auto *Alias = llvm::GlobalAlias::create(
4725 DeclTy, 0, getMultiversionLinkage(*this, GD),
4726 MangledName + ".ifunc", IFunc, &getModule());
4727 SetCommonAttributes(FD, Alias);
4728 }
4729 }
4730 }
4731 llvm::Function *ResolverFunc = cast<llvm::Function>(ResolverConstant);
4732
4733 const TargetInfo &TI = getTarget();
4734 llvm::stable_sort(
4735 Options, [&TI](const CodeGenFunction::FMVResolverOption &LHS,
4736 const CodeGenFunction::FMVResolverOption &RHS) {
4737 return getFMVPriority(TI, LHS).ugt(getFMVPriority(TI, RHS));
4738 });
4739 CodeGenFunction CGF(*this);
4740 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4741
4742 setMultiVersionResolverAttributes(ResolverFunc, GD);
4743 if (!ResolverFunc->hasLocalLinkage() && supportsCOMDAT())
4744 ResolverFunc->setComdat(
4745 getModule().getOrInsertComdat(ResolverFunc->getName()));
4746 }
4747
4748 // Ensure that any additions to the deferred decls list caused by emitting a
4749 // variant are emitted. This can happen when the variant itself is inline and
4750 // calls a function without linkage.
4751 if (!MVFuncsToEmit.empty())
4752 EmitDeferred();
4753
4754 // Ensure that any additions to the multiversion funcs list from either the
4755 // deferred decls or the multiversion functions themselves are emitted.
4756 if (!MultiVersionFuncs.empty())
4757 emitMultiVersionFunctions();
4758}
4759
4760static void replaceDeclarationWith(llvm::GlobalValue *Old,
4761 llvm::Constant *New) {
4762 assert(cast<llvm::Function>(Old)->isDeclaration() && "Not a declaration");
4763 New->takeName(Old);
4764 Old->replaceAllUsesWith(New);
4765 Old->eraseFromParent();
4766}
4767
4768void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
4769 const auto *FD = cast<FunctionDecl>(GD.getDecl());
4770 assert(FD && "Not a FunctionDecl?");
4771 assert(FD->isCPUDispatchMultiVersion() && "Not a multiversion function?");
4772 const auto *DD = FD->getAttr<CPUDispatchAttr>();
4773 assert(DD && "Not a cpu_dispatch Function?");
4774
4775 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4776 llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
4777
4778 StringRef ResolverName = getMangledName(GD);
4779 UpdateMultiVersionNames(GD, FD, ResolverName);
4780
4781 llvm::Type *ResolverType;
4782 GlobalDecl ResolverGD;
4783 if (getTarget().supportsIFunc()) {
4784 ResolverType = llvm::FunctionType::get(
4785 llvm::PointerType::get(getLLVMContext(),
4786 getTypes().getTargetAddressSpace(FD->getType())),
4787 false);
4788 }
4789 else {
4790 ResolverType = DeclTy;
4791 ResolverGD = GD;
4792 }
4793
4794 auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
4795 ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
4796
4797 if (supportsCOMDAT())
4798 ResolverFunc->setComdat(
4799 getModule().getOrInsertComdat(ResolverFunc->getName()));
4800
4801 SmallVector<CodeGenFunction::FMVResolverOption, 10> Options;
4802 const TargetInfo &Target = getTarget();
4803 unsigned Index = 0;
4804 for (const IdentifierInfo *II : DD->cpus()) {
4805 // Get the name of the target function so we can look it up/create it.
4806 std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
4807 getCPUSpecificMangling(*this, II->getName());
4808
4809 llvm::Constant *Func = GetGlobalValue(MangledName);
4810
4811 if (!Func) {
4812 GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
4813 if (ExistingDecl.getDecl() &&
4814 ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
4815 EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
4816 Func = GetGlobalValue(MangledName);
4817 } else {
4818 if (!ExistingDecl.getDecl())
4819 ExistingDecl = GD.getWithMultiVersionIndex(Index);
4820
4821 Func = GetOrCreateLLVMFunction(
4822 MangledName, DeclTy, ExistingDecl,
4823 /*ForVTable=*/false, /*DontDefer=*/true,
4824 /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
4825 }
4826 }
4827
4828 llvm::SmallVector<StringRef, 32> Features;
4829 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
4830 llvm::transform(Features, Features.begin(),
4831 [](StringRef Str) { return Str.substr(1); });
4832 llvm::erase_if(Features, [&Target](StringRef Feat) {
4833 return !Target.validateCpuSupports(Feat);
4834 });
4835 Options.emplace_back(cast<llvm::Function>(Func), Features);
4836 ++Index;
4837 }
4838
4839 llvm::stable_sort(Options, [](const CodeGenFunction::FMVResolverOption &LHS,
4840 const CodeGenFunction::FMVResolverOption &RHS) {
4841 return llvm::X86::getCpuSupportsMask(LHS.Features) >
4842 llvm::X86::getCpuSupportsMask(RHS.Features);
4843 });
4844
4845 // If the list contains multiple 'default' versions, such as when it contains
4846 // 'pentium' and 'generic', don't emit the call to the generic one (since we
4847 // always run on at least a 'pentium'). We do this by deleting the 'least
4848 // advanced' (read, lowest mangling letter).
4849 while (Options.size() > 1 && llvm::all_of(llvm::X86::getCpuSupportsMask(
4850 (Options.end() - 2)->Features),
4851 [](auto X) { return X == 0; })) {
4852 StringRef LHSName = (Options.end() - 2)->Function->getName();
4853 StringRef RHSName = (Options.end() - 1)->Function->getName();
4854 if (LHSName.compare(RHSName) < 0)
4855 Options.erase(Options.end() - 2);
4856 else
4857 Options.erase(Options.end() - 1);
4858 }
4859
4860 CodeGenFunction CGF(*this);
4861 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
4862 setMultiVersionResolverAttributes(ResolverFunc, GD);
4863
4864 if (getTarget().supportsIFunc()) {
4865 llvm::GlobalValue::LinkageTypes Linkage = getMultiversionLinkage(*this, GD);
4866 auto *IFunc = cast<llvm::GlobalValue>(GetOrCreateMultiVersionResolver(GD));
4867 unsigned AS = IFunc->getType()->getPointerAddressSpace();
4868
4869 // Fix up function declarations that were created for cpu_specific before
4870 // cpu_dispatch was known
4871 if (!isa<llvm::GlobalIFunc>(IFunc)) {
4872 auto *GI = llvm::GlobalIFunc::create(DeclTy, AS, Linkage, "",
4873 ResolverFunc, &getModule());
4874 replaceDeclarationWith(IFunc, GI);
4875 IFunc = GI;
4876 }
4877
4878 std::string AliasName = getMangledNameImpl(
4879 *this, GD, FD, /*OmitMultiVersionMangling=*/true);
4880 llvm::Constant *AliasFunc = GetGlobalValue(AliasName);
4881 if (!AliasFunc) {
4882 auto *GA = llvm::GlobalAlias::create(DeclTy, AS, Linkage, AliasName,
4883 IFunc, &getModule());
4884 SetCommonAttributes(GD, GA);
4885 }
4886 }
4887}
4888
4889/// Adds a declaration to the list of multi version functions if not present.
4890void CodeGenModule::AddDeferredMultiVersionResolverToEmit(GlobalDecl GD) {
4891 const auto *FD = cast<FunctionDecl>(GD.getDecl());
4892 assert(FD && "Not a FunctionDecl?");
4893
4895 std::string MangledName =
4896 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
4897 if (!DeferredResolversToEmit.insert(MangledName).second)
4898 return;
4899 }
4900 MultiVersionFuncs.push_back(GD);
4901}
4902
4903/// If a dispatcher for the specified mangled name is not in the module, create
4904/// and return it. The dispatcher is either an llvm Function with the specified
4905/// type, or a global ifunc.
4906llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) {
4907 const auto *FD = cast<FunctionDecl>(GD.getDecl());
4908 assert(FD && "Not a FunctionDecl?");
4909
4910 std::string MangledName =
4911 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
4912
4913 // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
4914 // a separate resolver).
4915 std::string ResolverName = MangledName;
4916 if (getTarget().supportsIFunc()) {
4917 switch (FD->getMultiVersionKind()) {
4919 llvm_unreachable("unexpected MultiVersionKind::None for resolver");
4923 ResolverName += ".ifunc";
4924 break;
4927 break;
4928 }
4929 } else if (FD->isTargetMultiVersion()) {
4930 ResolverName += ".resolver";
4931 }
4932
4933 bool ShouldReturnIFunc =
4935
4936 // If the resolver has already been created, just return it. This lookup may
4937 // yield a function declaration instead of a resolver on AArch64. That is
4938 // because we didn't know whether a resolver will be generated when we first
4939 // encountered a use of the symbol named after this resolver. Therefore,
4940 // targets which support ifuncs should not return here unless we actually
4941 // found an ifunc.
4942 llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName);
4943 if (ResolverGV && (isa<llvm::GlobalIFunc>(ResolverGV) || !ShouldReturnIFunc))
4944 return ResolverGV;
4945
4946 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4947 llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI);
4948
4949 // The resolver needs to be created. For target and target_clones, defer
4950 // creation until the end of the TU.
4952 AddDeferredMultiVersionResolverToEmit(GD);
4953
4954 // For cpu_specific, don't create an ifunc yet because we don't know if the
4955 // cpu_dispatch will be emitted in this translation unit.
4956 if (ShouldReturnIFunc) {
4957 unsigned AS = getTypes().getTargetAddressSpace(FD->getType());
4958 llvm::Type *ResolverType = llvm::FunctionType::get(
4959 llvm::PointerType::get(getLLVMContext(), AS), false);
4960 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
4961 MangledName + ".resolver", ResolverType, GlobalDecl{},
4962 /*ForVTable=*/false);
4963 llvm::GlobalIFunc *GIF =
4964 llvm::GlobalIFunc::create(DeclTy, AS, getMultiversionLinkage(*this, GD),
4965 "", Resolver, &getModule());
4966 GIF->setName(ResolverName);
4967 SetCommonAttributes(FD, GIF);
4968 if (ResolverGV)
4969 replaceDeclarationWith(ResolverGV, GIF);
4970 return GIF;
4971 }
4972
4973 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
4974 ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
4975 assert(isa<llvm::GlobalValue>(Resolver) && !ResolverGV &&
4976 "Resolver should be created for the first time");
4978 return Resolver;
4979}
4980
4981void CodeGenModule::setMultiVersionResolverAttributes(llvm::Function *Resolver,
4982 GlobalDecl GD) {
4983 const NamedDecl *D = dyn_cast_or_null<NamedDecl>(GD.getDecl());
4984 Resolver->setLinkage(getMultiversionLinkage(*this, GD));
4985
4986 // Function body has to be emitted before calling setGlobalVisibility
4987 // for Resolver to be considered as definition.
4988 setGlobalVisibility(Resolver, D);
4989
4990 setDSOLocal(Resolver);
4991
4992 // The resolver must be exempt from sanitizer instrumentation, as it can run
4993 // before the sanitizer is initialized.
4994 // (https://github.com/llvm/llvm-project/issues/163369)
4995 Resolver->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation);
4996
4997 // Set the default target-specific attributes, such as PAC and BTI ones on
4998 // AArch64. Not passing Decl to prevent setting unrelated attributes,
4999 // as Resolver can be shared by multiple declarations.
5000 // FIXME Some targets may require a non-null D to set some attributes
5001 // (such as "stackrealign" on X86, even when it is requested via
5002 // "-mstackrealign" command line option).
5003 getTargetCodeGenInfo().setTargetAttributes(/*D=*/nullptr, Resolver, *this);
5004}
5005
5006bool CodeGenModule::shouldDropDLLAttribute(const Decl *D,
5007 const llvm::GlobalValue *GV) const {
5008 auto SC = GV->getDLLStorageClass();
5009 if (SC == llvm::GlobalValue::DefaultStorageClass)
5010 return false;
5011 const Decl *MRD = D->getMostRecentDecl();
5012 return (((SC == llvm::GlobalValue::DLLImportStorageClass &&
5013 !MRD->hasAttr<DLLImportAttr>()) ||
5014 (SC == llvm::GlobalValue::DLLExportStorageClass &&
5015 !MRD->hasAttr<DLLExportAttr>())) &&
5017}
5018
5019/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
5020/// module, create and return an llvm Function with the specified type. If there
5021/// is something in the module with the specified name, return it potentially
5022/// bitcasted to the right type.
5023///
5024/// If D is non-null, it specifies a decl that correspond to this. This is used
5025/// to set the attributes on the function when it is first created.
5026llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
5027 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
5028 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
5029 ForDefinition_t IsForDefinition) {
5030 const Decl *D = GD.getDecl();
5031
5032 std::string NameWithoutMultiVersionMangling;
5033 if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
5034 // For the device mark the function as one that should be emitted.
5035 if (getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime &&
5036 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
5037 !DontDefer && !IsForDefinition) {
5038 if (const FunctionDecl *FDDef = FD->getDefinition()) {
5039 GlobalDecl GDDef;
5040 if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
5041 GDDef = GlobalDecl(CD, GD.getCtorType());
5042 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
5043 GDDef = GlobalDecl(DD, GD.getDtorType());
5044 else
5045 GDDef = GlobalDecl(FDDef);
5046 EmitGlobal(GDDef);
5047 }
5048 }
5049
5050 // Any attempts to use a MultiVersion function should result in retrieving
5051 // the iFunc instead. Name Mangling will handle the rest of the changes.
5052 if (FD->isMultiVersion()) {
5053 UpdateMultiVersionNames(GD, FD, MangledName);
5054 if (!IsForDefinition) {
5055 // On AArch64 we do not immediatelly emit an ifunc resolver when a
5056 // function is used. Instead we defer the emission until we see a
5057 // default definition. In the meantime we just reference the symbol
5058 // without FMV mangling (it may or may not be replaced later).
5059 if (getTarget().getTriple().isAArch64()) {
5060 AddDeferredMultiVersionResolverToEmit(GD);
5061 NameWithoutMultiVersionMangling = getMangledNameImpl(
5062 *this, GD, FD, /*OmitMultiVersionMangling=*/true);
5063 } else
5064 return GetOrCreateMultiVersionResolver(GD);
5065 }
5066 }
5067 }
5068
5069 if (!NameWithoutMultiVersionMangling.empty())
5070 MangledName = NameWithoutMultiVersionMangling;
5071
5072 // Lookup the entry, lazily creating it if necessary.
5073 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
5074 if (Entry) {
5075 if (WeakRefReferences.erase(Entry)) {
5076 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
5077 if (FD && !FD->hasAttr<WeakAttr>())
5078 Entry->setLinkage(llvm::Function::ExternalLinkage);
5079 }
5080
5081 // Handle dropped DLL attributes.
5082 if (D && shouldDropDLLAttribute(D, Entry)) {
5083 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
5084 setDSOLocal(Entry);
5085 }
5086
5087 // If there are two attempts to define the same mangled name, issue an
5088 // error.
5089 if (IsForDefinition && !Entry->isDeclaration()) {
5090 GlobalDecl OtherGD;
5091 // Check that GD is not yet in DiagnosedConflictingDefinitions is required
5092 // to make sure that we issue an error only once.
5093 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
5094 (GD.getCanonicalDecl().getDecl() !=
5095 OtherGD.getCanonicalDecl().getDecl()) &&
5096 DiagnosedConflictingDefinitions.insert(GD).second) {
5097 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
5098 << MangledName;
5099 getDiags().Report(OtherGD.getDecl()->getLocation(),
5100 diag::note_previous_definition);
5101 }
5102 }
5103
5104 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
5105 (Entry->getValueType() == Ty)) {
5106 return Entry;
5107 }
5108
5109 // Make sure the result is of the correct type.
5110 // (If function is requested for a definition, we always need to create a new
5111 // function, not just return a bitcast.)
5112 if (!IsForDefinition)
5113 return Entry;
5114 }
5115
5116 // This function doesn't have a complete type (for example, the return
5117 // type is an incomplete struct). Use a fake type instead, and make
5118 // sure not to try to set attributes.
5119 bool IsIncompleteFunction = false;
5120
5121 llvm::FunctionType *FTy;
5122 if (isa<llvm::FunctionType>(Ty)) {
5123 FTy = cast<llvm::FunctionType>(Ty);
5124 } else {
5125 FTy = llvm::FunctionType::get(VoidTy, false);
5126 IsIncompleteFunction = true;
5127 }
5128
5129 llvm::Function *F =
5130 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
5131 Entry ? StringRef() : MangledName, &getModule());
5132
5133 // Store the declaration associated with this function so it is potentially
5134 // updated by further declarations or definitions and emitted at the end.
5135 if (D && D->hasAttr<AnnotateAttr>())
5136 DeferredAnnotations[MangledName] = cast<ValueDecl>(D);
5137
5138 // If we already created a function with the same mangled name (but different
5139 // type) before, take its name and add it to the list of functions to be
5140 // replaced with F at the end of CodeGen.
5141 //
5142 // This happens if there is a prototype for a function (e.g. "int f()") and
5143 // then a definition of a different type (e.g. "int f(int x)").
5144 if (Entry) {
5145 F->takeName(Entry);
5146
5147 // This might be an implementation of a function without a prototype, in
5148 // which case, try to do special replacement of calls which match the new
5149 // prototype. The really key thing here is that we also potentially drop
5150 // arguments from the call site so as to make a direct call, which makes the
5151 // inliner happier and suppresses a number of optimizer warnings (!) about
5152 // dropping arguments.
5153 if (!Entry->use_empty()) {
5155 Entry->removeDeadConstantUsers();
5156 }
5157
5158 addGlobalValReplacement(Entry, F);
5159 }
5160
5161 assert(F->getName() == MangledName && "name was uniqued!");
5162 if (D)
5163 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
5164 if (ExtraAttrs.hasFnAttrs()) {
5165 llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs());
5166 F->addFnAttrs(B);
5167 }
5168
5169 if (!DontDefer) {
5170 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
5171 // each other bottoming out with the base dtor. Therefore we emit non-base
5172 // dtors on usage, even if there is no dtor definition in the TU.
5173 if (isa_and_nonnull<CXXDestructorDecl>(D) &&
5174 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
5175 GD.getDtorType()))
5176 addDeferredDeclToEmit(GD);
5177
5178 // This is the first use or definition of a mangled name. If there is a
5179 // deferred decl with this name, remember that we need to emit it at the end
5180 // of the file.
5181 auto DDI = DeferredDecls.find(MangledName);
5182 if (DDI != DeferredDecls.end()) {
5183 // Move the potentially referenced deferred decl to the
5184 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
5185 // don't need it anymore).
5186 addDeferredDeclToEmit(DDI->second);
5187 DeferredDecls.erase(DDI);
5188
5189 // Otherwise, there are cases we have to worry about where we're
5190 // using a declaration for which we must emit a definition but where
5191 // we might not find a top-level definition:
5192 // - member functions defined inline in their classes
5193 // - friend functions defined inline in some class
5194 // - special member functions with implicit definitions
5195 // If we ever change our AST traversal to walk into class methods,
5196 // this will be unnecessary.
5197 //
5198 // We also don't emit a definition for a function if it's going to be an
5199 // entry in a vtable, unless it's already marked as used.
5200 } else if (getLangOpts().CPlusPlus && D) {
5201 // Look for a declaration that's lexically in a record.
5202 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
5203 FD = FD->getPreviousDecl()) {
5205 if (FD->doesThisDeclarationHaveABody()) {
5206 addDeferredDeclToEmit(GD.getWithDecl(FD));
5207 break;
5208 }
5209 }
5210 }
5211 }
5212 }
5213
5214 // Make sure the result is of the requested type.
5215 if (!IsIncompleteFunction) {
5216 assert(F->getFunctionType() == Ty);
5217 return F;
5218 }
5219
5220 return F;
5221}
5222
5223/// GetAddrOfFunction - Return the address of the given function. If Ty is
5224/// non-null, then this function will use the specified type if it has to
5225/// create it (this occurs when we see a definition of the function).
5226llvm::Constant *
5227CodeGenModule::GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty, bool ForVTable,
5228 bool DontDefer,
5229 ForDefinition_t IsForDefinition) {
5230 // If there was no specific requested type, just convert it now.
5231 if (!Ty) {
5232 const auto *FD = cast<FunctionDecl>(GD.getDecl());
5233 Ty = getTypes().ConvertType(FD->getType());
5234 if (DeviceKernelAttr::isOpenCLSpelling(FD->getAttr<DeviceKernelAttr>()) &&
5237 Ty = getTypes().GetFunctionType(FI);
5238 }
5239 }
5240
5241 // Devirtualized destructor calls may come through here instead of via
5242 // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
5243 // of the complete destructor when necessary.
5244 if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
5245 if (getTarget().getCXXABI().isMicrosoft() &&
5246 GD.getDtorType() == Dtor_Complete &&
5247 DD->getParent()->getNumVBases() == 0)
5248 GD = GlobalDecl(DD, Dtor_Base);
5249 }
5250
5251 StringRef MangledName = getMangledName(GD);
5252 auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
5253 /*IsThunk=*/false, llvm::AttributeList(),
5254 IsForDefinition);
5255 // Returns kernel handle for HIP kernel stub function.
5256 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
5257 cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) {
5258 auto *Handle = getCUDARuntime().getKernelHandle(
5259 cast<llvm::Function>(F->stripPointerCasts()), GD);
5260 if (IsForDefinition)
5261 return F;
5262 return Handle;
5263 }
5264 return F;
5265}
5266
5268 llvm::GlobalValue *F =
5269 cast<llvm::GlobalValue>(GetAddrOfFunction(Decl)->stripPointerCasts());
5270
5271 return llvm::NoCFIValue::get(F);
5272}
5273
5274static const FunctionDecl *
5276 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
5278
5279 IdentifierInfo &CII = C.Idents.get(Name);
5280 for (const auto *Result : DC->lookup(&CII))
5281 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
5282 return FD;
5283
5284 if (!C.getLangOpts().CPlusPlus)
5285 return nullptr;
5286
5287 // Demangle the premangled name from getTerminateFn()
5288 IdentifierInfo &CXXII =
5289 (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
5290 ? C.Idents.get("terminate")
5291 : C.Idents.get(Name);
5292
5293 for (const auto &N : {"__cxxabiv1", "std"}) {
5294 IdentifierInfo &NS = C.Idents.get(N);
5295 for (const auto *Result : DC->lookup(&NS)) {
5296 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
5297 if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result))
5298 for (const auto *Result : LSD->lookup(&NS))
5299 if ((ND = dyn_cast<NamespaceDecl>(Result)))
5300 break;
5301
5302 if (ND)
5303 for (const auto *Result : ND->lookup(&CXXII))
5304 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
5305 return FD;
5306 }
5307 }
5308
5309 return nullptr;
5310}
5311
5312static void setWindowsItaniumDLLImport(CodeGenModule &CGM, bool Local,
5313 llvm::Function *F, StringRef Name) {
5314 // In Windows Itanium environments, try to mark runtime functions
5315 // dllimport. For Mingw and MSVC, don't. We don't really know if the user
5316 // will link their standard library statically or dynamically. Marking
5317 // functions imported when they are not imported can cause linker errors
5318 // and warnings.
5319 if (!Local && CGM.getTriple().isWindowsItaniumEnvironment() &&
5320 !CGM.getCodeGenOpts().LTOVisibilityPublicStd) {
5321 const FunctionDecl *FD = GetRuntimeFunctionDecl(CGM.getContext(), Name);
5322 if (!FD || FD->hasAttr<DLLImportAttr>()) {
5323 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
5324 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
5325 }
5326 }
5327}
5328
5330 QualType ReturnTy, ArrayRef<QualType> ArgTys, StringRef Name,
5331 llvm::AttributeList ExtraAttrs, bool Local, bool AssumeConvergent) {
5332 if (AssumeConvergent) {
5333 ExtraAttrs =
5334 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
5335 }
5336
5337 QualType FTy = Context.getFunctionType(ReturnTy, ArgTys,
5340 Context.getCanonicalType(FTy).castAs<FunctionProtoType>());
5341 auto *ConvTy = getTypes().GetFunctionType(Info);
5342 llvm::Constant *C = GetOrCreateLLVMFunction(
5343 Name, ConvTy, GlobalDecl(), /*ForVTable=*/false,
5344 /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
5345
5346 if (auto *F = dyn_cast<llvm::Function>(C)) {
5347 if (F->empty()) {
5348 SetLLVMFunctionAttributes(GlobalDecl(), Info, F, /*IsThunk*/ false);
5349 // FIXME: Set calling-conv properly in ExtProtoInfo
5350 F->setCallingConv(getRuntimeCC());
5351 setWindowsItaniumDLLImport(*this, Local, F, Name);
5352 setDSOLocal(F);
5353 }
5354 }
5355 return {ConvTy, C};
5356}
5357
5358/// CreateRuntimeFunction - Create a new runtime function with the specified
5359/// type and name.
5360llvm::FunctionCallee
5361CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
5362 llvm::AttributeList ExtraAttrs, bool Local,
5363 bool AssumeConvergent) {
5364 if (AssumeConvergent) {
5365 ExtraAttrs =
5366 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent);
5367 }
5368
5369 llvm::Constant *C =
5370 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
5371 /*DontDefer=*/false, /*IsThunk=*/false,
5372 ExtraAttrs);
5373
5374 if (auto *F = dyn_cast<llvm::Function>(C)) {
5375 if (F->empty()) {
5376 F->setCallingConv(getRuntimeCC());
5377 setWindowsItaniumDLLImport(*this, Local, F, Name);
5378 setDSOLocal(F);
5379 // FIXME: We should use CodeGenModule::SetLLVMFunctionAttributes() instead
5380 // of trying to approximate the attributes using the LLVM function
5381 // signature. The other overload of CreateRuntimeFunction does this; it
5382 // should be used for new code.
5383 markRegisterParameterAttributes(F);
5384 }
5385 }
5386
5387 return {FTy, C};
5388}
5389
5390/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
5391/// create and return an llvm GlobalVariable with the specified type and address
5392/// space. If there is something in the module with the specified name, return
5393/// it potentially bitcasted to the right type.
5394///
5395/// If D is non-null, it specifies a decl that correspond to this. This is used
5396/// to set the attributes on the global when it is first created.
5397///
5398/// If IsForDefinition is true, it is guaranteed that an actual global with
5399/// type Ty will be returned, not conversion of a variable with the same
5400/// mangled name but some other type.
5401llvm::Constant *
5402CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty,
5403 LangAS AddrSpace, const VarDecl *D,
5404 ForDefinition_t IsForDefinition) {
5405 // Lookup the entry, lazily creating it if necessary.
5406 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
5407 unsigned TargetAS = getContext().getTargetAddressSpace(AddrSpace);
5408 if (Entry) {
5409 if (WeakRefReferences.erase(Entry)) {
5410 if (D && !D->hasAttr<WeakAttr>())
5411 Entry->setLinkage(llvm::Function::ExternalLinkage);
5412 }
5413
5414 // Handle dropped DLL attributes.
5415 if (D && shouldDropDLLAttribute(D, Entry))
5416 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
5417
5418 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
5420
5421 if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS)
5422 return Entry;
5423
5424 // If there are two attempts to define the same mangled name, issue an
5425 // error.
5426 if (IsForDefinition && !Entry->isDeclaration()) {
5427 GlobalDecl OtherGD;
5428 const VarDecl *OtherD;
5429
5430 // Check that D is not yet in DiagnosedConflictingDefinitions is required
5431 // to make sure that we issue an error only once.
5432 if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
5433 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
5434 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
5435 OtherD->hasInit() &&
5436 DiagnosedConflictingDefinitions.insert(D).second) {
5437 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
5438 << MangledName;
5439 getDiags().Report(OtherGD.getDecl()->getLocation(),
5440 diag::note_previous_definition);
5441 }
5442 }
5443
5444 // Make sure the result is of the correct type.
5445 if (Entry->getType()->getAddressSpace() != TargetAS)
5446 return llvm::ConstantExpr::getAddrSpaceCast(
5447 Entry, llvm::PointerType::get(Ty->getContext(), TargetAS));
5448
5449 // (If global is requested for a definition, we always need to create a new
5450 // global, not just return a bitcast.)
5451 if (!IsForDefinition)
5452 return Entry;
5453 }
5454
5455 auto DAddrSpace = GetGlobalVarAddressSpace(D);
5456
5457 auto *GV = new llvm::GlobalVariable(
5458 getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr,
5459 MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal,
5460 getContext().getTargetAddressSpace(DAddrSpace));
5461
5462 // If we already created a global with the same mangled name (but different
5463 // type) before, take its name and remove it from its parent.
5464 if (Entry) {
5465 GV->takeName(Entry);
5466
5467 if (!Entry->use_empty()) {
5468 Entry->replaceAllUsesWith(GV);
5469 }
5470
5471 Entry->eraseFromParent();
5472 }
5473
5474 // This is the first use or definition of a mangled name. If there is a
5475 // deferred decl with this name, remember that we need to emit it at the end
5476 // of the file.
5477 auto DDI = DeferredDecls.find(MangledName);
5478 if (DDI != DeferredDecls.end()) {
5479 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
5480 // list, and remove it from DeferredDecls (since we don't need it anymore).
5481 addDeferredDeclToEmit(DDI->second);
5482 DeferredDecls.erase(DDI);
5483 }
5484
5485 // Handle things which are present even on external declarations.
5486 if (D) {
5487 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
5489
5490 // FIXME: This code is overly simple and should be merged with other global
5491 // handling.
5492 GV->setConstant(D->getType().isConstantStorage(getContext(), false, false));
5493
5494 GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
5495
5496 setLinkageForGV(GV, D);
5497
5498 if (D->getTLSKind()) {
5499 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
5500 CXXThreadLocals.push_back(D);
5501 setTLSMode(GV, *D);
5502 }
5503
5504 setGVProperties(GV, D);
5505
5506 // If required by the ABI, treat declarations of static data members with
5507 // inline initializers as definitions.
5508 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
5509 EmitGlobalVarDefinition(D);
5510 }
5511
5512 // Emit section information for extern variables.
5513 if (D->hasExternalStorage()) {
5514 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
5515 GV->setSection(SA->getName());
5516 }
5517
5518 // Handle XCore specific ABI requirements.
5519 if (getTriple().getArch() == llvm::Triple::xcore &&
5521 D->getType().isConstant(Context) &&
5523 GV->setSection(".cp.rodata");
5524
5525 // Handle code model attribute
5526 if (const auto *CMA = D->getAttr<CodeModelAttr>())
5527 GV->setCodeModel(CMA->getModel());
5528
5529 // Check if we a have a const declaration with an initializer, we may be
5530 // able to emit it as available_externally to expose it's value to the
5531 // optimizer.
5532 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
5533 D->getType().isConstQualified() && !GV->hasInitializer() &&
5534 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
5535 const auto *Record =
5536 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
5537 bool HasMutableFields = Record && Record->hasMutableFields();
5538 if (!HasMutableFields) {
5539 const VarDecl *InitDecl;
5540 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
5541 if (InitExpr) {
5542 ConstantEmitter emitter(*this);
5543 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
5544 if (Init) {
5545 auto *InitType = Init->getType();
5546 if (GV->getValueType() != InitType) {
5547 // The type of the initializer does not match the definition.
5548 // This happens when an initializer has a different type from
5549 // the type of the global (because of padding at the end of a
5550 // structure for instance).
5551 GV->setName(StringRef());
5552 // Make a new global with the correct type, this is now guaranteed
5553 // to work.
5554 auto *NewGV = cast<llvm::GlobalVariable>(
5555 GetAddrOfGlobalVar(D, InitType, IsForDefinition)
5556 ->stripPointerCasts());
5557
5558 // Erase the old global, since it is no longer used.
5559 GV->eraseFromParent();
5560 GV = NewGV;
5561 } else {
5562 GV->setInitializer(Init);
5563 GV->setConstant(true);
5564 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
5565 }
5566 emitter.finalize(GV);
5567 }
5568 }
5569 }
5570 }
5571 }
5572
5573 if (D &&
5576 // External HIP managed variables needed to be recorded for transformation
5577 // in both device and host compilations.
5578 if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() &&
5579 D->hasExternalStorage())
5581 }
5582
5583 if (D)
5584 SanitizerMD->reportGlobal(GV, *D);
5585
5586 LangAS ExpectedAS =
5587 D ? D->getType().getAddressSpace()
5588 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
5589 assert(getContext().getTargetAddressSpace(ExpectedAS) == TargetAS);
5590 if (DAddrSpace != ExpectedAS) {
5592 *this, GV, DAddrSpace,
5593 llvm::PointerType::get(getLLVMContext(), TargetAS));
5594 }
5595
5596 return GV;
5597}
5598
5599llvm::Constant *
5601 const Decl *D = GD.getDecl();
5602
5604 return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
5605 /*DontDefer=*/false, IsForDefinition);
5606
5607 if (isa<CXXMethodDecl>(D)) {
5608 auto FInfo =
5610 auto Ty = getTypes().GetFunctionType(*FInfo);
5611 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
5612 IsForDefinition);
5613 }
5614
5615 if (isa<FunctionDecl>(D)) {
5617 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
5618 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
5619 IsForDefinition);
5620 }
5621
5622 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition);
5623}
5624
5626 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
5627 llvm::Align Alignment) {
5628 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
5629 llvm::GlobalVariable *OldGV = nullptr;
5630
5631 if (GV) {
5632 // Check if the variable has the right type.
5633 if (GV->getValueType() == Ty)
5634 return GV;
5635
5636 // Because C++ name mangling, the only way we can end up with an already
5637 // existing global with the same name is if it has been declared extern "C".
5638 assert(GV->isDeclaration() && "Declaration has wrong type!");
5639 OldGV = GV;
5640 }
5641
5642 // Create a new variable.
5643 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
5644 Linkage, nullptr, Name);
5645
5646 if (OldGV) {
5647 // Replace occurrences of the old variable if needed.
5648 GV->takeName(OldGV);
5649
5650 if (!OldGV->use_empty()) {
5651 OldGV->replaceAllUsesWith(GV);
5652 }
5653
5654 OldGV->eraseFromParent();
5655 }
5656
5657 if (supportsCOMDAT() && GV->isWeakForLinker() &&
5658 !GV->hasAvailableExternallyLinkage())
5659 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
5660
5661 GV->setAlignment(Alignment);
5662
5663 return GV;
5664}
5665
5666/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
5667/// given global variable. If Ty is non-null and if the global doesn't exist,
5668/// then it will be created with the specified type instead of whatever the
5669/// normal requested type would be. If IsForDefinition is true, it is guaranteed
5670/// that an actual global with type Ty will be returned, not conversion of a
5671/// variable with the same mangled name but some other type.
5673 llvm::Type *Ty,
5674 ForDefinition_t IsForDefinition) {
5675 assert(D->hasGlobalStorage() && "Not a global variable");
5676 QualType ASTTy = D->getType();
5677 if (!Ty)
5678 Ty = getTypes().ConvertTypeForMem(ASTTy);
5679
5680 StringRef MangledName = getMangledName(D);
5681 return GetOrCreateLLVMGlobal(MangledName, Ty, ASTTy.getAddressSpace(), D,
5682 IsForDefinition);
5683}
5684
5685/// CreateRuntimeVariable - Create a new runtime global variable with the
5686/// specified type and name.
5687llvm::Constant *
5689 StringRef Name) {
5690 LangAS AddrSpace = getContext().getLangOpts().OpenCL ? LangAS::opencl_global
5692 auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr);
5693 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
5694 return Ret;
5695}
5696
5698 assert(!D->getInit() && "Cannot emit definite definitions here!");
5699
5700 StringRef MangledName = getMangledName(D);
5701 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
5702
5703 // We already have a definition, not declaration, with the same mangled name.
5704 // Emitting of declaration is not required (and actually overwrites emitted
5705 // definition).
5706 if (GV && !GV->isDeclaration())
5707 return;
5708
5709 // If we have not seen a reference to this variable yet, place it into the
5710 // deferred declarations table to be emitted if needed later.
5711 if (!MustBeEmitted(D) && !GV) {
5712 DeferredDecls[MangledName] = D;
5713 return;
5714 }
5715
5716 // The tentative definition is the only definition.
5717 EmitGlobalVarDefinition(D);
5718}
5719
5720// Return a GlobalDecl. Use the base variants for destructors and constructors.
5722 if (auto const *CD = dyn_cast<const CXXConstructorDecl>(D))
5724 else if (auto const *DD = dyn_cast<const CXXDestructorDecl>(D))
5726 return GlobalDecl(D);
5727}
5728
5731 if (!DI || !getCodeGenOpts().hasReducedDebugInfo())
5732 return;
5733
5735 if (!GD)
5736 return;
5737
5738 llvm::Constant *Addr = GetAddrOfGlobal(GD)->stripPointerCasts();
5739 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5741 cast<llvm::GlobalVariable>(Addr->stripPointerCasts()), VD);
5742 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
5743 llvm::Function *Fn = cast<llvm::Function>(Addr);
5744 if (!Fn->getSubprogram())
5745 DI->EmitFunctionDecl(GD, FD->getLocation(), FD->getType(), Fn);
5746 }
5747}
5748
5750 return Context.toCharUnitsFromBits(
5751 getDataLayout().getTypeStoreSizeInBits(Ty));
5752}
5753
5755 if (LangOpts.OpenCL) {
5757 assert(AS == LangAS::opencl_global ||
5761 AS == LangAS::opencl_local ||
5763 return AS;
5764 }
5765
5766 if (LangOpts.SYCLIsDevice &&
5767 (!D || D->getType().getAddressSpace() == LangAS::Default))
5768 return LangAS::sycl_global;
5769
5770 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
5771 if (D) {
5772 if (D->hasAttr<CUDAConstantAttr>())
5773 return LangAS::cuda_constant;
5774 if (D->hasAttr<CUDASharedAttr>())
5775 return LangAS::cuda_shared;
5776 if (D->hasAttr<CUDADeviceAttr>())
5777 return LangAS::cuda_device;
5778 if (D->getType().isConstQualified())
5779 return LangAS::cuda_constant;
5780 }
5781 return LangAS::cuda_device;
5782 }
5783
5784 if (LangOpts.OpenMP) {
5785 LangAS AS;
5786 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
5787 return AS;
5788 }
5790}
5791
5793 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
5794 if (LangOpts.OpenCL)
5796 if (LangOpts.SYCLIsDevice)
5797 return LangAS::sycl_global;
5798 if (LangOpts.HIP && LangOpts.CUDAIsDevice && getTriple().isSPIRV())
5799 // For HIPSPV map literals to cuda_device (maps to CrossWorkGroup in SPIR-V)
5800 // instead of default AS (maps to Generic in SPIR-V). Otherwise, we end up
5801 // with OpVariable instructions with Generic storage class which is not
5802 // allowed (SPIR-V V1.6 s3.42.8). Also, mapping literals to SPIR-V
5803 // UniformConstant storage class is not viable as pointers to it may not be
5804 // casted to Generic pointers which are used to model HIP's "flat" pointers.
5805 return LangAS::cuda_device;
5806 if (auto AS = getTarget().getConstantAddressSpace())
5807 return *AS;
5808 return LangAS::Default;
5809}
5810
5811// In address space agnostic languages, string literals are in default address
5812// space in AST. However, certain targets (e.g. amdgcn) request them to be
5813// emitted in constant address space in LLVM IR. To be consistent with other
5814// parts of AST, string literal global variables in constant address space
5815// need to be casted to default address space before being put into address
5816// map and referenced by other part of CodeGen.
5817// In OpenCL, string literals are in constant address space in AST, therefore
5818// they should not be casted to default address space.
5819static llvm::Constant *
5821 llvm::GlobalVariable *GV) {
5822 llvm::Constant *Cast = GV;
5823 if (!CGM.getLangOpts().OpenCL) {
5824 auto AS = CGM.GetGlobalConstantAddressSpace();
5825 if (AS != LangAS::Default)
5827 CGM, GV, AS,
5828 llvm::PointerType::get(
5829 CGM.getLLVMContext(),
5831 }
5832 return Cast;
5833}
5834
5835template<typename SomeDecl>
5837 llvm::GlobalValue *GV) {
5838 if (!getLangOpts().CPlusPlus)
5839 return;
5840
5841 // Must have 'used' attribute, or else inline assembly can't rely on
5842 // the name existing.
5843 if (!D->template hasAttr<UsedAttr>())
5844 return;
5845
5846 // Must have internal linkage and an ordinary name.
5847 if (!D->getIdentifier() || D->getFormalLinkage() != Linkage::Internal)
5848 return;
5849
5850 // Must be in an extern "C" context. Entities declared directly within
5851 // a record are not extern "C" even if the record is in such a context.
5852 const SomeDecl *First = D->getFirstDecl();
5853 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
5854 return;
5855
5856 // OK, this is an internal linkage entity inside an extern "C" linkage
5857 // specification. Make a note of that so we can give it the "expected"
5858 // mangled name if nothing else is using that name.
5859 std::pair<StaticExternCMap::iterator, bool> R =
5860 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
5861
5862 // If we have multiple internal linkage entities with the same name
5863 // in extern "C" regions, none of them gets that name.
5864 if (!R.second)
5865 R.first->second = nullptr;
5866}
5867
5868static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
5869 if (!CGM.supportsCOMDAT())
5870 return false;
5871
5872 if (D.hasAttr<SelectAnyAttr>())
5873 return true;
5874
5876 if (auto *VD = dyn_cast<VarDecl>(&D))
5878 else
5880
5881 switch (Linkage) {
5882 case GVA_Internal:
5884 case GVA_StrongExternal:
5885 return false;
5886 case GVA_DiscardableODR:
5887 case GVA_StrongODR:
5888 return true;
5889 }
5890 llvm_unreachable("No such linkage");
5891}
5892
5894 return getTriple().supportsCOMDAT();
5895}
5896
5898 llvm::GlobalObject &GO) {
5899 if (!shouldBeInCOMDAT(*this, D))
5900 return;
5901 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
5902}
5903
5907
5908/// Pass IsTentative as true if you want to create a tentative definition.
5909void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
5910 bool IsTentative) {
5911 // OpenCL global variables of sampler type are translated to function calls,
5912 // therefore no need to be translated.
5913 QualType ASTTy = D->getType();
5914 if (getLangOpts().OpenCL && ASTTy->isSamplerT())
5915 return;
5916
5917 // HLSL default buffer constants will be emitted during HLSLBufferDecl codegen
5918 if (getLangOpts().HLSL &&
5920 return;
5921
5922 // If this is OpenMP device, check if it is legal to emit this global
5923 // normally.
5924 if (LangOpts.OpenMPIsTargetDevice && OpenMPRuntime &&
5925 OpenMPRuntime->emitTargetGlobalVariable(D))
5926 return;
5927
5928 llvm::TrackingVH<llvm::Constant> Init;
5929 bool NeedsGlobalCtor = false;
5930 // Whether the definition of the variable is available externally.
5931 // If yes, we shouldn't emit the GloablCtor and GlobalDtor for the variable
5932 // since this is the job for its original source.
5933 bool IsDefinitionAvailableExternally =
5935 bool NeedsGlobalDtor =
5936 !IsDefinitionAvailableExternally &&
5938
5939 // It is helpless to emit the definition for an available_externally variable
5940 // which can't be marked as const.
5941 // We don't need to check if it needs global ctor or dtor. See the above
5942 // comment for ideas.
5943 if (IsDefinitionAvailableExternally &&
5945 // TODO: Update this when we have interface to check constexpr
5946 // destructor.
5948 !D->getType().isConstantStorage(getContext(), true, true)))
5949 return;
5950
5951 const VarDecl *InitDecl;
5952 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
5953
5954 std::optional<ConstantEmitter> emitter;
5955
5956 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
5957 // as part of their declaration." Sema has already checked for
5958 // error cases, so we just need to set Init to UndefValue.
5959 bool IsCUDASharedVar =
5960 getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
5961 // Shadows of initialized device-side global variables are also left
5962 // undefined.
5963 // Managed Variables should be initialized on both host side and device side.
5964 bool IsCUDAShadowVar =
5965 !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
5966 (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
5967 D->hasAttr<CUDASharedAttr>());
5968 bool IsCUDADeviceShadowVar =
5969 getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
5972 if (getLangOpts().CUDA &&
5973 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar)) {
5974 Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
5975 } else if (getLangOpts().HLSL &&
5976 (D->getType()->isHLSLResourceRecord() ||
5978 Init = llvm::PoisonValue::get(getTypes().ConvertType(ASTTy));
5979 NeedsGlobalCtor = D->getType()->isHLSLResourceRecord();
5980 } else if (D->hasAttr<LoaderUninitializedAttr>()) {
5981 Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
5982 } else if (!InitExpr) {
5983 // This is a tentative definition; tentative definitions are
5984 // implicitly initialized with { 0 }.
5985 //
5986 // Note that tentative definitions are only emitted at the end of
5987 // a translation unit, so they should never have incomplete
5988 // type. In addition, EmitTentativeDefinition makes sure that we
5989 // never attempt to emit a tentative definition if a real one
5990 // exists. A use may still exists, however, so we still may need
5991 // to do a RAUW.
5992 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
5994 } else {
5995 initializedGlobalDecl = GlobalDecl(D);
5996 emitter.emplace(*this);
5997 llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl);
5998 if (!Initializer) {
5999 QualType T = InitExpr->getType();
6000 if (D->getType()->isReferenceType())
6001 T = D->getType();
6002
6003 if (getLangOpts().CPlusPlus) {
6005 if (!IsDefinitionAvailableExternally)
6006 NeedsGlobalCtor = true;
6007 if (InitDecl->hasFlexibleArrayInit(getContext())) {
6008 ErrorUnsupported(D, "flexible array initializer");
6009 // We cannot create ctor for flexible array initializer
6010 NeedsGlobalCtor = false;
6011 }
6012 } else {
6013 ErrorUnsupported(D, "static initializer");
6014 Init = llvm::PoisonValue::get(getTypes().ConvertType(T));
6015 }
6016 } else {
6017 Init = Initializer;
6018 // We don't need an initializer, so remove the entry for the delayed
6019 // initializer position (just in case this entry was delayed) if we
6020 // also don't need to register a destructor.
6021 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
6022 DelayedCXXInitPosition.erase(D);
6023
6024#ifndef NDEBUG
6025 CharUnits VarSize = getContext().getTypeSizeInChars(ASTTy) +
6027 CharUnits CstSize = CharUnits::fromQuantity(
6028 getDataLayout().getTypeAllocSize(Init->getType()));
6029 assert(VarSize == CstSize && "Emitted constant has unexpected size");
6030#endif
6031 }
6032 }
6033
6034 llvm::Type* InitType = Init->getType();
6035 llvm::Constant *Entry =
6036 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
6037
6038 // Strip off pointer casts if we got them.
6039 Entry = Entry->stripPointerCasts();
6040
6041 // Entry is now either a Function or GlobalVariable.
6042 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
6043
6044 // We have a definition after a declaration with the wrong type.
6045 // We must make a new GlobalVariable* and update everything that used OldGV
6046 // (a declaration or tentative definition) with the new GlobalVariable*
6047 // (which will be a definition).
6048 //
6049 // This happens if there is a prototype for a global (e.g.
6050 // "extern int x[];") and then a definition of a different type (e.g.
6051 // "int x[10];"). This also happens when an initializer has a different type
6052 // from the type of the global (this happens with unions).
6053 if (!GV || GV->getValueType() != InitType ||
6054 GV->getType()->getAddressSpace() !=
6055 getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
6056
6057 // Move the old entry aside so that we'll create a new one.
6058 Entry->setName(StringRef());
6059
6060 // Make a new global with the correct type, this is now guaranteed to work.
6062 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))
6063 ->stripPointerCasts());
6064
6065 // Replace all uses of the old global with the new global
6066 llvm::Constant *NewPtrForOldDecl =
6067 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
6068 Entry->getType());
6069 Entry->replaceAllUsesWith(NewPtrForOldDecl);
6070
6071 // Erase the old global, since it is no longer used.
6072 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
6073 }
6074
6076
6077 if (D->hasAttr<AnnotateAttr>())
6078 AddGlobalAnnotations(D, GV);
6079
6080 // Set the llvm linkage type as appropriate.
6081 llvm::GlobalValue::LinkageTypes Linkage = getLLVMLinkageVarDefinition(D);
6082
6083 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
6084 // the device. [...]"
6085 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
6086 // __device__, declares a variable that: [...]
6087 // Is accessible from all the threads within the grid and from the host
6088 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
6089 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
6090 if (LangOpts.CUDA) {
6091 if (LangOpts.CUDAIsDevice) {
6092 if (Linkage != llvm::GlobalValue::InternalLinkage &&
6093 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
6096 GV->setExternallyInitialized(true);
6097 } else {
6099 }
6101 }
6102
6103 if (LangOpts.HLSL && GetGlobalVarAddressSpace(D) == LangAS::hlsl_input) {
6104 // HLSL Input variables are considered to be set by the driver/pipeline, but
6105 // only visible to a single thread/wave.
6106 GV->setExternallyInitialized(true);
6107 } else {
6108 GV->setInitializer(Init);
6109 }
6110
6111 if (LangOpts.HLSL)
6113
6114 if (emitter)
6115 emitter->finalize(GV);
6116
6117 // If it is safe to mark the global 'constant', do so now.
6118 GV->setConstant((D->hasAttr<CUDAConstantAttr>() && LangOpts.CUDAIsDevice) ||
6119 (!NeedsGlobalCtor && !NeedsGlobalDtor &&
6120 D->getType().isConstantStorage(getContext(), true, true)));
6121
6122 // If it is in a read-only section, mark it 'constant'.
6123 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
6124 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
6125 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
6126 GV->setConstant(true);
6127 }
6128
6129 CharUnits AlignVal = getContext().getDeclAlign(D);
6130 // Check for alignment specifed in an 'omp allocate' directive.
6131 if (std::optional<CharUnits> AlignValFromAllocate =
6133 AlignVal = *AlignValFromAllocate;
6134 GV->setAlignment(AlignVal.getAsAlign());
6135
6136 // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper
6137 // function is only defined alongside the variable, not also alongside
6138 // callers. Normally, all accesses to a thread_local go through the
6139 // thread-wrapper in order to ensure initialization has occurred, underlying
6140 // variable will never be used other than the thread-wrapper, so it can be
6141 // converted to internal linkage.
6142 //
6143 // However, if the variable has the 'constinit' attribute, it _can_ be
6144 // referenced directly, without calling the thread-wrapper, so the linkage
6145 // must not be changed.
6146 //
6147 // Additionally, if the variable isn't plain external linkage, e.g. if it's
6148 // weak or linkonce, the de-duplication semantics are important to preserve,
6149 // so we don't change the linkage.
6150 if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
6151 Linkage == llvm::GlobalValue::ExternalLinkage &&
6152 Context.getTargetInfo().getTriple().isOSDarwin() &&
6153 !D->hasAttr<ConstInitAttr>())
6154 Linkage = llvm::GlobalValue::InternalLinkage;
6155
6156 // HLSL variables in the input address space maps like memory-mapped
6157 // variables. Even if they are 'static', they are externally initialized and
6158 // read/write by the hardware/driver/pipeline.
6159 if (LangOpts.HLSL && GetGlobalVarAddressSpace(D) == LangAS::hlsl_input)
6160 Linkage = llvm::GlobalValue::ExternalLinkage;
6161
6162 GV->setLinkage(Linkage);
6163 if (D->hasAttr<DLLImportAttr>())
6164 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
6165 else if (D->hasAttr<DLLExportAttr>())
6166 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
6167 else
6168 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
6169
6170 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
6171 // common vars aren't constant even if declared const.
6172 GV->setConstant(false);
6173 // Tentative definition of global variables may be initialized with
6174 // non-zero null pointers. In this case they should have weak linkage
6175 // since common linkage must have zero initializer and must not have
6176 // explicit section therefore cannot have non-zero initial value.
6177 if (!GV->getInitializer()->isNullValue())
6178 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
6179 }
6180
6181 setNonAliasAttributes(D, GV);
6182
6183 if (D->getTLSKind() && !GV->isThreadLocal()) {
6184 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
6185 CXXThreadLocals.push_back(D);
6186 setTLSMode(GV, *D);
6187 }
6188
6189 maybeSetTrivialComdat(*D, *GV);
6190
6191 // Emit the initializer function if necessary.
6192 if (NeedsGlobalCtor || NeedsGlobalDtor)
6193 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
6194
6195 SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor);
6196
6197 // Emit global variable debug information.
6198 if (CGDebugInfo *DI = getModuleDebugInfo())
6199 if (getCodeGenOpts().hasReducedDebugInfo())
6200 DI->EmitGlobalVariable(GV, D);
6201}
6202
6203static bool isVarDeclStrongDefinition(const ASTContext &Context,
6204 CodeGenModule &CGM, const VarDecl *D,
6205 bool NoCommon) {
6206 // Don't give variables common linkage if -fno-common was specified unless it
6207 // was overridden by a NoCommon attribute.
6208 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
6209 return true;
6210
6211 // C11 6.9.2/2:
6212 // A declaration of an identifier for an object that has file scope without
6213 // an initializer, and without a storage-class specifier or with the
6214 // storage-class specifier static, constitutes a tentative definition.
6215 if (D->getInit() || D->hasExternalStorage())
6216 return true;
6217
6218 // A variable cannot be both common and exist in a section.
6219 if (D->hasAttr<SectionAttr>())
6220 return true;
6221
6222 // A variable cannot be both common and exist in a section.
6223 // We don't try to determine which is the right section in the front-end.
6224 // If no specialized section name is applicable, it will resort to default.
6225 if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
6226 D->hasAttr<PragmaClangDataSectionAttr>() ||
6227 D->hasAttr<PragmaClangRelroSectionAttr>() ||
6228 D->hasAttr<PragmaClangRodataSectionAttr>())
6229 return true;
6230
6231 // Thread local vars aren't considered common linkage.
6232 if (D->getTLSKind())
6233 return true;
6234
6235 // Tentative definitions marked with WeakImportAttr are true definitions.
6236 if (D->hasAttr<WeakImportAttr>())
6237 return true;
6238
6239 // A variable cannot be both common and exist in a comdat.
6240 if (shouldBeInCOMDAT(CGM, *D))
6241 return true;
6242
6243 // Declarations with a required alignment do not have common linkage in MSVC
6244 // mode.
6245 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6246 if (D->hasAttr<AlignedAttr>())
6247 return true;
6248 QualType VarType = D->getType();
6249 if (Context.isAlignmentRequired(VarType))
6250 return true;
6251
6252 if (const auto *RD = VarType->getAsRecordDecl()) {
6253 for (const FieldDecl *FD : RD->fields()) {
6254 if (FD->isBitField())
6255 continue;
6256 if (FD->hasAttr<AlignedAttr>())
6257 return true;
6258 if (Context.isAlignmentRequired(FD->getType()))
6259 return true;
6260 }
6261 }
6262 }
6263
6264 // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
6265 // common symbols, so symbols with greater alignment requirements cannot be
6266 // common.
6267 // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
6268 // alignments for common symbols via the aligncomm directive, so this
6269 // restriction only applies to MSVC environments.
6270 if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
6271 Context.getTypeAlignIfKnown(D->getType()) >
6272 Context.toBits(CharUnits::fromQuantity(32)))
6273 return true;
6274
6275 return false;
6276}
6277
6278llvm::GlobalValue::LinkageTypes
6281 if (Linkage == GVA_Internal)
6282 return llvm::Function::InternalLinkage;
6283
6284 if (D->hasAttr<WeakAttr>())
6285 return llvm::GlobalVariable::WeakAnyLinkage;
6286
6287 if (const auto *FD = D->getAsFunction())
6289 return llvm::GlobalVariable::LinkOnceAnyLinkage;
6290
6291 // We are guaranteed to have a strong definition somewhere else,
6292 // so we can use available_externally linkage.
6294 return llvm::GlobalValue::AvailableExternallyLinkage;
6295
6296 // Note that Apple's kernel linker doesn't support symbol
6297 // coalescing, so we need to avoid linkonce and weak linkages there.
6298 // Normally, this means we just map to internal, but for explicit
6299 // instantiations we'll map to external.
6300
6301 // In C++, the compiler has to emit a definition in every translation unit
6302 // that references the function. We should use linkonce_odr because
6303 // a) if all references in this translation unit are optimized away, we
6304 // don't need to codegen it. b) if the function persists, it needs to be
6305 // merged with other definitions. c) C++ has the ODR, so we know the
6306 // definition is dependable.
6308 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
6309 : llvm::Function::InternalLinkage;
6310
6311 // An explicit instantiation of a template has weak linkage, since
6312 // explicit instantiations can occur in multiple translation units
6313 // and must all be equivalent. However, we are not allowed to
6314 // throw away these explicit instantiations.
6315 //
6316 // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU,
6317 // so say that CUDA templates are either external (for kernels) or internal.
6318 // This lets llvm perform aggressive inter-procedural optimizations. For
6319 // -fgpu-rdc case, device function calls across multiple TU's are allowed,
6320 // therefore we need to follow the normal linkage paradigm.
6321 if (Linkage == GVA_StrongODR) {
6322 if (getLangOpts().AppleKext)
6323 return llvm::Function::ExternalLinkage;
6324 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
6325 !getLangOpts().GPURelocatableDeviceCode)
6326 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
6327 : llvm::Function::InternalLinkage;
6328 return llvm::Function::WeakODRLinkage;
6329 }
6330
6331 // C++ doesn't have tentative definitions and thus cannot have common
6332 // linkage.
6333 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
6334 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
6335 CodeGenOpts.NoCommon))
6336 return llvm::GlobalVariable::CommonLinkage;
6337
6338 // selectany symbols are externally visible, so use weak instead of
6339 // linkonce. MSVC optimizes away references to const selectany globals, so
6340 // all definitions should be the same and ODR linkage should be used.
6341 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
6342 if (D->hasAttr<SelectAnyAttr>())
6343 return llvm::GlobalVariable::WeakODRLinkage;
6344
6345 // Otherwise, we have strong external linkage.
6346 assert(Linkage == GVA_StrongExternal);
6347 return llvm::GlobalVariable::ExternalLinkage;
6348}
6349
6350llvm::GlobalValue::LinkageTypes
6355
6356/// Replace the uses of a function that was declared with a non-proto type.
6357/// We want to silently drop extra arguments from call sites
6358static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
6359 llvm::Function *newFn) {
6360 // Fast path.
6361 if (old->use_empty())
6362 return;
6363
6364 llvm::Type *newRetTy = newFn->getReturnType();
6366
6367 SmallVector<llvm::CallBase *> callSitesToBeRemovedFromParent;
6368
6369 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
6370 ui != ue; ui++) {
6371 llvm::User *user = ui->getUser();
6372
6373 // Recognize and replace uses of bitcasts. Most calls to
6374 // unprototyped functions will use bitcasts.
6375 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
6376 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
6377 replaceUsesOfNonProtoConstant(bitcast, newFn);
6378 continue;
6379 }
6380
6381 // Recognize calls to the function.
6382 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
6383 if (!callSite)
6384 continue;
6385 if (!callSite->isCallee(&*ui))
6386 continue;
6387
6388 // If the return types don't match exactly, then we can't
6389 // transform this call unless it's dead.
6390 if (callSite->getType() != newRetTy && !callSite->use_empty())
6391 continue;
6392
6393 // Get the call site's attribute list.
6395 llvm::AttributeList oldAttrs = callSite->getAttributes();
6396
6397 // If the function was passed too few arguments, don't transform.
6398 unsigned newNumArgs = newFn->arg_size();
6399 if (callSite->arg_size() < newNumArgs)
6400 continue;
6401
6402 // If extra arguments were passed, we silently drop them.
6403 // If any of the types mismatch, we don't transform.
6404 unsigned argNo = 0;
6405 bool dontTransform = false;
6406 for (llvm::Argument &A : newFn->args()) {
6407 if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
6408 dontTransform = true;
6409 break;
6410 }
6411
6412 // Add any parameter attributes.
6413 newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo));
6414 argNo++;
6415 }
6416 if (dontTransform)
6417 continue;
6418
6419 // Okay, we can transform this. Create the new call instruction and copy
6420 // over the required information.
6421 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
6422
6423 // Copy over any operand bundles.
6425 callSite->getOperandBundlesAsDefs(newBundles);
6426
6427 llvm::CallBase *newCall;
6428 if (isa<llvm::CallInst>(callSite)) {
6429 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
6430 callSite->getIterator());
6431 } else {
6432 auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
6433 newCall = llvm::InvokeInst::Create(
6434 newFn, oldInvoke->getNormalDest(), oldInvoke->getUnwindDest(),
6435 newArgs, newBundles, "", callSite->getIterator());
6436 }
6437 newArgs.clear(); // for the next iteration
6438
6439 if (!newCall->getType()->isVoidTy())
6440 newCall->takeName(callSite);
6441 newCall->setAttributes(
6442 llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(),
6443 oldAttrs.getRetAttrs(), newArgAttrs));
6444 newCall->setCallingConv(callSite->getCallingConv());
6445
6446 // Finally, remove the old call, replacing any uses with the new one.
6447 if (!callSite->use_empty())
6448 callSite->replaceAllUsesWith(newCall);
6449
6450 // Copy debug location attached to CI.
6451 if (callSite->getDebugLoc())
6452 newCall->setDebugLoc(callSite->getDebugLoc());
6453
6454 callSitesToBeRemovedFromParent.push_back(callSite);
6455 }
6456
6457 for (auto *callSite : callSitesToBeRemovedFromParent) {
6458 callSite->eraseFromParent();
6459 }
6460}
6461
6462/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
6463/// implement a function with no prototype, e.g. "int foo() {}". If there are
6464/// existing call uses of the old function in the module, this adjusts them to
6465/// call the new function directly.
6466///
6467/// This is not just a cleanup: the always_inline pass requires direct calls to
6468/// functions to be able to inline them. If there is a bitcast in the way, it
6469/// won't inline them. Instcombine normally deletes these calls, but it isn't
6470/// run at -O0.
6471static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
6472 llvm::Function *NewFn) {
6473 // If we're redefining a global as a function, don't transform it.
6474 if (!isa<llvm::Function>(Old)) return;
6475
6477}
6478
6480 auto DK = VD->isThisDeclarationADefinition();
6481 if ((DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>()) ||
6482 (LangOpts.CUDA && !shouldEmitCUDAGlobalVar(VD)))
6483 return;
6484
6486 // If we have a definition, this might be a deferred decl. If the
6487 // instantiation is explicit, make sure we emit it at the end.
6490
6491 EmitTopLevelDecl(VD);
6492}
6493
6494void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
6495 llvm::GlobalValue *GV) {
6496 const auto *D = cast<FunctionDecl>(GD.getDecl());
6497
6498 // Compute the function info and LLVM type.
6500 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
6501
6502 // Get or create the prototype for the function.
6503 if (!GV || (GV->getValueType() != Ty))
6504 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
6505 /*DontDefer=*/true,
6506 ForDefinition));
6507
6508 // Already emitted.
6509 if (!GV->isDeclaration())
6510 return;
6511
6512 // We need to set linkage and visibility on the function before
6513 // generating code for it because various parts of IR generation
6514 // want to propagate this information down (e.g. to local static
6515 // declarations).
6516 auto *Fn = cast<llvm::Function>(GV);
6517 setFunctionLinkage(GD, Fn);
6518
6519 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
6520 setGVProperties(Fn, GD);
6521
6523
6524 maybeSetTrivialComdat(*D, *Fn);
6525
6526 CodeGenFunction(*this).GenerateCode(GD, Fn, FI);
6527
6528 setNonAliasAttributes(GD, Fn);
6529
6530 bool ShouldAddOptNone = !CodeGenOpts.DisableO0ImplyOptNone &&
6531 (CodeGenOpts.OptimizationLevel == 0) &&
6532 !D->hasAttr<MinSizeAttr>();
6533
6534 if (DeviceKernelAttr::isOpenCLSpelling(D->getAttr<DeviceKernelAttr>())) {
6536 !D->hasAttr<NoInlineAttr>() &&
6537 !Fn->hasFnAttribute(llvm::Attribute::NoInline) &&
6538 !D->hasAttr<OptimizeNoneAttr>() &&
6539 !Fn->hasFnAttribute(llvm::Attribute::OptimizeNone) &&
6540 !ShouldAddOptNone) {
6541 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
6542 }
6543 }
6544
6546
6547 auto GetPriority = [this](const auto *Attr) -> int {
6548 Expr *E = Attr->getPriority();
6549 if (E) {
6550 return E->EvaluateKnownConstInt(this->getContext()).getExtValue();
6551 }
6552 return Attr->DefaultPriority;
6553 };
6554
6555 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
6556 AddGlobalCtor(Fn, GetPriority(CA));
6557 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
6558 AddGlobalDtor(Fn, GetPriority(DA), true);
6559 if (getLangOpts().OpenMP && D->hasAttr<OMPDeclareTargetDeclAttr>())
6561}
6562
6563void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
6564 const auto *D = cast<ValueDecl>(GD.getDecl());
6565 const AliasAttr *AA = D->getAttr<AliasAttr>();
6566 assert(AA && "Not an alias?");
6567
6568 StringRef MangledName = getMangledName(GD);
6569
6570 if (AA->getAliasee() == MangledName) {
6571 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
6572 return;
6573 }
6574
6575 // If there is a definition in the module, then it wins over the alias.
6576 // This is dubious, but allow it to be safe. Just ignore the alias.
6577 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
6578 if (Entry && !Entry->isDeclaration())
6579 return;
6580
6581 Aliases.push_back(GD);
6582
6583 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
6584
6585 // Create a reference to the named value. This ensures that it is emitted
6586 // if a deferred decl.
6587 llvm::Constant *Aliasee;
6588 llvm::GlobalValue::LinkageTypes LT;
6589 if (isa<llvm::FunctionType>(DeclTy)) {
6590 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
6591 /*ForVTable=*/false);
6592 LT = getFunctionLinkage(GD);
6593 } else {
6594 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default,
6595 /*D=*/nullptr);
6596 if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl()))
6598 else
6599 LT = getFunctionLinkage(GD);
6600 }
6601
6602 // Create the new alias itself, but don't set a name yet.
6603 unsigned AS = Aliasee->getType()->getPointerAddressSpace();
6604 auto *GA =
6605 llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule());
6606
6607 if (Entry) {
6608 if (GA->getAliasee() == Entry) {
6609 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
6610 return;
6611 }
6612
6613 assert(Entry->isDeclaration());
6614
6615 // If there is a declaration in the module, then we had an extern followed
6616 // by the alias, as in:
6617 // extern int test6();
6618 // ...
6619 // int test6() __attribute__((alias("test7")));
6620 //
6621 // Remove it and replace uses of it with the alias.
6622 GA->takeName(Entry);
6623
6624 Entry->replaceAllUsesWith(GA);
6625 Entry->eraseFromParent();
6626 } else {
6627 GA->setName(MangledName);
6628 }
6629
6630 // Set attributes which are particular to an alias; this is a
6631 // specialization of the attributes which may be set on a global
6632 // variable/function.
6633 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
6634 D->isWeakImported()) {
6635 GA->setLinkage(llvm::Function::WeakAnyLinkage);
6636 }
6637
6638 if (const auto *VD = dyn_cast<VarDecl>(D))
6639 if (VD->getTLSKind())
6640 setTLSMode(GA, *VD);
6641
6642 SetCommonAttributes(GD, GA);
6643
6644 // Emit global alias debug information.
6645 if (isa<VarDecl>(D))
6646 if (CGDebugInfo *DI = getModuleDebugInfo())
6647 DI->EmitGlobalAlias(cast<llvm::GlobalValue>(GA->getAliasee()->stripPointerCasts()), GD);
6648}
6649
6650void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
6651 const auto *D = cast<ValueDecl>(GD.getDecl());
6652 const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
6653 assert(IFA && "Not an ifunc?");
6654
6655 StringRef MangledName = getMangledName(GD);
6656
6657 if (IFA->getResolver() == MangledName) {
6658 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
6659 return;
6660 }
6661
6662 // Report an error if some definition overrides ifunc.
6663 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
6664 if (Entry && !Entry->isDeclaration()) {
6665 GlobalDecl OtherGD;
6666 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
6667 DiagnosedConflictingDefinitions.insert(GD).second) {
6668 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
6669 << MangledName;
6670 Diags.Report(OtherGD.getDecl()->getLocation(),
6671 diag::note_previous_definition);
6672 }
6673 return;
6674 }
6675
6676 Aliases.push_back(GD);
6677
6678 // The resolver might not be visited yet. Specify a dummy non-function type to
6679 // indicate IsIncompleteFunction. Either the type is ignored (if the resolver
6680 // was emitted) or the whole function will be replaced (if the resolver has
6681 // not been emitted).
6682 llvm::Constant *Resolver =
6683 GetOrCreateLLVMFunction(IFA->getResolver(), VoidTy, {},
6684 /*ForVTable=*/false);
6685 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
6686 unsigned AS = getTypes().getTargetAddressSpace(D->getType());
6687 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
6688 DeclTy, AS, llvm::Function::ExternalLinkage, "", Resolver, &getModule());
6689 if (Entry) {
6690 if (GIF->getResolver() == Entry) {
6691 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
6692 return;
6693 }
6694 assert(Entry->isDeclaration());
6695
6696 // If there is a declaration in the module, then we had an extern followed
6697 // by the ifunc, as in:
6698 // extern int test();
6699 // ...
6700 // int test() __attribute__((ifunc("resolver")));
6701 //
6702 // Remove it and replace uses of it with the ifunc.
6703 GIF->takeName(Entry);
6704
6705 Entry->replaceAllUsesWith(GIF);
6706 Entry->eraseFromParent();
6707 } else
6708 GIF->setName(MangledName);
6709 SetCommonAttributes(GD, GIF);
6710}
6711
6712llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
6714 return llvm::Intrinsic::getOrInsertDeclaration(&getModule(),
6715 (llvm::Intrinsic::ID)IID, Tys);
6716}
6717
6718static llvm::StringMapEntry<llvm::GlobalVariable *> &
6719GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
6720 const StringLiteral *Literal, bool TargetIsLSB,
6721 bool &IsUTF16, unsigned &StringLength) {
6722 StringRef String = Literal->getString();
6723 unsigned NumBytes = String.size();
6724
6725 // Check for simple case.
6726 if (!Literal->containsNonAsciiOrNull()) {
6727 StringLength = NumBytes;
6728 return *Map.insert(std::make_pair(String, nullptr)).first;
6729 }
6730
6731 // Otherwise, convert the UTF8 literals into a string of shorts.
6732 IsUTF16 = true;
6733
6734 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
6735 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6736 llvm::UTF16 *ToPtr = &ToBuf[0];
6737
6738 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6739 ToPtr + NumBytes, llvm::strictConversion);
6740
6741 // ConvertUTF8toUTF16 returns the length in ToPtr.
6742 StringLength = ToPtr - &ToBuf[0];
6743
6744 // Add an explicit null.
6745 *ToPtr = 0;
6746 return *Map.insert(std::make_pair(
6747 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
6748 (StringLength + 1) * 2),
6749 nullptr)).first;
6750}
6751
6754 unsigned StringLength = 0;
6755 bool isUTF16 = false;
6756 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
6757 GetConstantCFStringEntry(CFConstantStringMap, Literal,
6758 getDataLayout().isLittleEndian(), isUTF16,
6759 StringLength);
6760
6761 if (auto *C = Entry.second)
6762 return ConstantAddress(
6763 C, C->getValueType(), CharUnits::fromQuantity(C->getAlignment()));
6764
6765 const ASTContext &Context = getContext();
6766 const llvm::Triple &Triple = getTriple();
6767
6768 const auto CFRuntime = getLangOpts().CFRuntime;
6769 const bool IsSwiftABI =
6770 static_cast<unsigned>(CFRuntime) >=
6771 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
6772 const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
6773
6774 // If we don't already have it, get __CFConstantStringClassReference.
6775 if (!CFConstantStringClassRef) {
6776 const char *CFConstantStringClassName = "__CFConstantStringClassReference";
6777 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
6778 Ty = llvm::ArrayType::get(Ty, 0);
6779
6780 switch (CFRuntime) {
6781 default: break;
6782 case LangOptions::CoreFoundationABI::Swift: [[fallthrough]];
6784 CFConstantStringClassName =
6785 Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
6786 : "$s10Foundation19_NSCFConstantStringCN";
6787 Ty = IntPtrTy;
6788 break;
6790 CFConstantStringClassName =
6791 Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
6792 : "$S10Foundation19_NSCFConstantStringCN";
6793 Ty = IntPtrTy;
6794 break;
6796 CFConstantStringClassName =
6797 Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
6798 : "__T010Foundation19_NSCFConstantStringCN";
6799 Ty = IntPtrTy;
6800 break;
6801 }
6802
6803 llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
6804
6805 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
6806 llvm::GlobalValue *GV = nullptr;
6807
6808 if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
6809 IdentifierInfo &II = Context.Idents.get(GV->getName());
6810 TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
6812
6813 const VarDecl *VD = nullptr;
6814 for (const auto *Result : DC->lookup(&II))
6815 if ((VD = dyn_cast<VarDecl>(Result)))
6816 break;
6817
6818 if (Triple.isOSBinFormatELF()) {
6819 if (!VD)
6820 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
6821 } else {
6822 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
6823 if (!VD || !VD->hasAttr<DLLExportAttr>())
6824 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
6825 else
6826 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
6827 }
6828
6829 setDSOLocal(GV);
6830 }
6831 }
6832
6833 // Decay array -> ptr
6834 CFConstantStringClassRef =
6835 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty) : C;
6836 }
6837
6838 QualType CFTy = Context.getCFConstantStringType();
6839
6840 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
6841
6842 ConstantInitBuilder Builder(*this);
6843 auto Fields = Builder.beginStruct(STy);
6844
6845 // Class pointer.
6846 Fields.addSignedPointer(cast<llvm::Constant>(CFConstantStringClassRef),
6847 getCodeGenOpts().PointerAuth.ObjCIsaPointers,
6848 GlobalDecl(), QualType());
6849
6850 // Flags.
6851 if (IsSwiftABI) {
6852 Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
6853 Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
6854 } else {
6855 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
6856 }
6857
6858 // String pointer.
6859 llvm::Constant *C = nullptr;
6860 if (isUTF16) {
6861 auto Arr = llvm::ArrayRef(
6862 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
6863 Entry.first().size() / 2);
6864 C = llvm::ConstantDataArray::get(VMContext, Arr);
6865 } else {
6866 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
6867 }
6868
6869 // Note: -fwritable-strings doesn't make the backing store strings of
6870 // CFStrings writable.
6871 auto *GV =
6872 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
6873 llvm::GlobalValue::PrivateLinkage, C, ".str");
6874 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
6875 // Don't enforce the target's minimum global alignment, since the only use
6876 // of the string is via this class initializer.
6877 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
6878 : Context.getTypeAlignInChars(Context.CharTy);
6879 GV->setAlignment(Align.getAsAlign());
6880
6881 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
6882 // Without it LLVM can merge the string with a non unnamed_addr one during
6883 // LTO. Doing that changes the section it ends in, which surprises ld64.
6884 if (Triple.isOSBinFormatMachO())
6885 GV->setSection(isUTF16 ? "__TEXT,__ustring"
6886 : "__TEXT,__cstring,cstring_literals");
6887 // Make sure the literal ends up in .rodata to allow for safe ICF and for
6888 // the static linker to adjust permissions to read-only later on.
6889 else if (Triple.isOSBinFormatELF())
6890 GV->setSection(".rodata");
6891
6892 // String.
6893 Fields.add(GV);
6894
6895 // String length.
6896 llvm::IntegerType *LengthTy =
6897 llvm::IntegerType::get(getModule().getContext(),
6898 Context.getTargetInfo().getLongWidth());
6899 if (IsSwiftABI) {
6902 LengthTy = Int32Ty;
6903 else
6904 LengthTy = IntPtrTy;
6905 }
6906 Fields.addInt(LengthTy, StringLength);
6907
6908 // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is
6909 // properly aligned on 32-bit platforms.
6910 CharUnits Alignment =
6911 IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign();
6912
6913 // The struct.
6914 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
6915 /*isConstant=*/false,
6916 llvm::GlobalVariable::PrivateLinkage);
6917 GV->addAttribute("objc_arc_inert");
6918 switch (Triple.getObjectFormat()) {
6919 case llvm::Triple::UnknownObjectFormat:
6920 llvm_unreachable("unknown file format");
6921 case llvm::Triple::DXContainer:
6922 case llvm::Triple::GOFF:
6923 case llvm::Triple::SPIRV:
6924 case llvm::Triple::XCOFF:
6925 llvm_unreachable("unimplemented");
6926 case llvm::Triple::COFF:
6927 case llvm::Triple::ELF:
6928 case llvm::Triple::Wasm:
6929 GV->setSection("cfstring");
6930 break;
6931 case llvm::Triple::MachO:
6932 GV->setSection("__DATA,__cfstring");
6933 break;
6934 }
6935 Entry.second = GV;
6936
6937 return ConstantAddress(GV, GV->getValueType(), Alignment);
6938}
6939
6941 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
6942}
6943
6945 if (ObjCFastEnumerationStateType.isNull()) {
6946 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
6947 D->startDefinition();
6948
6949 QualType FieldTypes[] = {
6950 Context.UnsignedLongTy, Context.getPointerType(Context.getObjCIdType()),
6951 Context.getPointerType(Context.UnsignedLongTy),
6952 Context.getConstantArrayType(Context.UnsignedLongTy, llvm::APInt(32, 5),
6953 nullptr, ArraySizeModifier::Normal, 0)};
6954
6955 for (size_t i = 0; i < 4; ++i) {
6956 FieldDecl *Field = FieldDecl::Create(Context,
6957 D,
6959 SourceLocation(), nullptr,
6960 FieldTypes[i], /*TInfo=*/nullptr,
6961 /*BitWidth=*/nullptr,
6962 /*Mutable=*/false,
6963 ICIS_NoInit);
6964 Field->setAccess(AS_public);
6965 D->addDecl(Field);
6966 }
6967
6968 D->completeDefinition();
6969 ObjCFastEnumerationStateType = Context.getCanonicalTagType(D);
6970 }
6971
6972 return ObjCFastEnumerationStateType;
6973}
6974
6975llvm::Constant *
6977 assert(!E->getType()->isPointerType() && "Strings are always arrays");
6978
6979 // Don't emit it as the address of the string, emit the string data itself
6980 // as an inline array.
6981 if (E->getCharByteWidth() == 1) {
6982 SmallString<64> Str(E->getString());
6983
6984 // Resize the string to the right size, which is indicated by its type.
6985 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
6986 assert(CAT && "String literal not of constant array type!");
6987 Str.resize(CAT->getZExtSize());
6988 return llvm::ConstantDataArray::getString(VMContext, Str, false);
6989 }
6990
6991 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
6992 llvm::Type *ElemTy = AType->getElementType();
6993 unsigned NumElements = AType->getNumElements();
6994
6995 // Wide strings have either 2-byte or 4-byte elements.
6996 if (ElemTy->getPrimitiveSizeInBits() == 16) {
6998 Elements.reserve(NumElements);
6999
7000 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
7001 Elements.push_back(E->getCodeUnit(i));
7002 Elements.resize(NumElements);
7003 return llvm::ConstantDataArray::get(VMContext, Elements);
7004 }
7005
7006 assert(ElemTy->getPrimitiveSizeInBits() == 32);
7008 Elements.reserve(NumElements);
7009
7010 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
7011 Elements.push_back(E->getCodeUnit(i));
7012 Elements.resize(NumElements);
7013 return llvm::ConstantDataArray::get(VMContext, Elements);
7014}
7015
7016static llvm::GlobalVariable *
7017GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
7018 CodeGenModule &CGM, StringRef GlobalName,
7019 CharUnits Alignment) {
7020 unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
7022
7023 llvm::Module &M = CGM.getModule();
7024 // Create a global variable for this string
7025 auto *GV = new llvm::GlobalVariable(
7026 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
7027 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
7028 GV->setAlignment(Alignment.getAsAlign());
7029 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
7030 if (GV->isWeakForLinker()) {
7031 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
7032 GV->setComdat(M.getOrInsertComdat(GV->getName()));
7033 }
7034 CGM.setDSOLocal(GV);
7035
7036 return GV;
7037}
7038
7039/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
7040/// constant array for the given string literal.
7043 StringRef Name) {
7044 CharUnits Alignment =
7045 getContext().getAlignOfGlobalVarInChars(S->getType(), /*VD=*/nullptr);
7046
7047 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
7048 llvm::GlobalVariable **Entry = nullptr;
7049 if (!LangOpts.WritableStrings) {
7050 Entry = &ConstantStringMap[C];
7051 if (auto GV = *Entry) {
7052 if (uint64_t(Alignment.getQuantity()) > GV->getAlignment())
7053 GV->setAlignment(Alignment.getAsAlign());
7055 GV->getValueType(), Alignment);
7056 }
7057 }
7058
7059 SmallString<256> MangledNameBuffer;
7060 StringRef GlobalVariableName;
7061 llvm::GlobalValue::LinkageTypes LT;
7062
7063 // Mangle the string literal if that's how the ABI merges duplicate strings.
7064 // Don't do it if they are writable, since we don't want writes in one TU to
7065 // affect strings in another.
7066 if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
7067 !LangOpts.WritableStrings) {
7068 llvm::raw_svector_ostream Out(MangledNameBuffer);
7070 LT = llvm::GlobalValue::LinkOnceODRLinkage;
7071 GlobalVariableName = MangledNameBuffer;
7072 } else {
7073 LT = llvm::GlobalValue::PrivateLinkage;
7074 GlobalVariableName = Name;
7075 }
7076
7077 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
7078
7080 if (DI && getCodeGenOpts().hasReducedDebugInfo())
7081 DI->AddStringLiteralDebugInfo(GV, S);
7082
7083 if (Entry)
7084 *Entry = GV;
7085
7086 SanitizerMD->reportGlobal(GV, S->getStrTokenLoc(0), "<string literal>");
7087
7089 GV->getValueType(), Alignment);
7090}
7091
7092/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
7093/// array for the given ObjCEncodeExpr node.
7101
7102/// GetAddrOfConstantCString - Returns a pointer to a character array containing
7103/// the literal and a terminating '\0' character.
7104/// The result has pointer to array type.
7106 StringRef GlobalName) {
7107 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
7109 getContext().CharTy, /*VD=*/nullptr);
7110
7111 llvm::Constant *C =
7112 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
7113
7114 // Don't share any string literals if strings aren't constant.
7115 llvm::GlobalVariable **Entry = nullptr;
7116 if (!LangOpts.WritableStrings) {
7117 Entry = &ConstantStringMap[C];
7118 if (auto GV = *Entry) {
7119 if (uint64_t(Alignment.getQuantity()) > GV->getAlignment())
7120 GV->setAlignment(Alignment.getAsAlign());
7122 GV->getValueType(), Alignment);
7123 }
7124 }
7125
7126 // Create a global variable for this.
7127 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
7128 GlobalName, Alignment);
7129 if (Entry)
7130 *Entry = GV;
7131
7133 GV->getValueType(), Alignment);
7134}
7135
7137 const MaterializeTemporaryExpr *E, const Expr *Init) {
7138 assert((E->getStorageDuration() == SD_Static ||
7139 E->getStorageDuration() == SD_Thread) && "not a global temporary");
7140 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
7141
7142 // If we're not materializing a subobject of the temporary, keep the
7143 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
7144 QualType MaterializedType = Init->getType();
7145 if (Init == E->getSubExpr())
7146 MaterializedType = E->getType();
7147
7148 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
7149
7150 auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr});
7151 if (!InsertResult.second) {
7152 // We've seen this before: either we already created it or we're in the
7153 // process of doing so.
7154 if (!InsertResult.first->second) {
7155 // We recursively re-entered this function, probably during emission of
7156 // the initializer. Create a placeholder. We'll clean this up in the
7157 // outer call, at the end of this function.
7158 llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType);
7159 InsertResult.first->second = new llvm::GlobalVariable(
7160 getModule(), Type, false, llvm::GlobalVariable::InternalLinkage,
7161 nullptr);
7162 }
7163 return ConstantAddress(InsertResult.first->second,
7164 llvm::cast<llvm::GlobalVariable>(
7165 InsertResult.first->second->stripPointerCasts())
7166 ->getValueType(),
7167 Align);
7168 }
7169
7170 // FIXME: If an externally-visible declaration extends multiple temporaries,
7171 // we need to give each temporary the same name in every translation unit (and
7172 // we also need to make the temporaries externally-visible).
7173 SmallString<256> Name;
7174 llvm::raw_svector_ostream Out(Name);
7176 VD, E->getManglingNumber(), Out);
7177
7178 APValue *Value = nullptr;
7179 if (E->getStorageDuration() == SD_Static && VD->evaluateValue()) {
7180 // If the initializer of the extending declaration is a constant
7181 // initializer, we should have a cached constant initializer for this
7182 // temporary. Note that this might have a different value from the value
7183 // computed by evaluating the initializer if the surrounding constant
7184 // expression modifies the temporary.
7185 Value = E->getOrCreateValue(false);
7186 }
7187
7188 // Try evaluating it now, it might have a constant initializer.
7189 Expr::EvalResult EvalResult;
7190 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
7191 !EvalResult.hasSideEffects())
7192 Value = &EvalResult.Val;
7193
7194 LangAS AddrSpace = GetGlobalVarAddressSpace(VD);
7195
7196 std::optional<ConstantEmitter> emitter;
7197 llvm::Constant *InitialValue = nullptr;
7198 bool Constant = false;
7199 llvm::Type *Type;
7200 if (Value) {
7201 // The temporary has a constant initializer, use it.
7202 emitter.emplace(*this);
7203 InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
7204 MaterializedType);
7205 Constant =
7206 MaterializedType.isConstantStorage(getContext(), /*ExcludeCtor*/ Value,
7207 /*ExcludeDtor*/ false);
7208 Type = InitialValue->getType();
7209 } else {
7210 // No initializer, the initialization will be provided when we
7211 // initialize the declaration which performed lifetime extension.
7212 Type = getTypes().ConvertTypeForMem(MaterializedType);
7213 }
7214
7215 // Create a global variable for this lifetime-extended temporary.
7216 llvm::GlobalValue::LinkageTypes Linkage = getLLVMLinkageVarDefinition(VD);
7217 if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
7218 const VarDecl *InitVD;
7219 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
7221 // Temporaries defined inside a class get linkonce_odr linkage because the
7222 // class can be defined in multiple translation units.
7223 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
7224 } else {
7225 // There is no need for this temporary to have external linkage if the
7226 // VarDecl has external linkage.
7227 Linkage = llvm::GlobalVariable::InternalLinkage;
7228 }
7229 }
7230 auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
7231 auto *GV = new llvm::GlobalVariable(
7232 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
7233 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
7234 if (emitter) emitter->finalize(GV);
7235 // Don't assign dllimport or dllexport to local linkage globals.
7236 if (!llvm::GlobalValue::isLocalLinkage(Linkage)) {
7237 setGVProperties(GV, VD);
7238 if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass)
7239 // The reference temporary should never be dllexport.
7240 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
7241 }
7242 GV->setAlignment(Align.getAsAlign());
7243 if (supportsCOMDAT() && GV->isWeakForLinker())
7244 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
7245 if (VD->getTLSKind())
7246 setTLSMode(GV, *VD);
7247 llvm::Constant *CV = GV;
7248 if (AddrSpace != LangAS::Default)
7250 *this, GV, AddrSpace,
7251 llvm::PointerType::get(
7253 getContext().getTargetAddressSpace(LangAS::Default)));
7254
7255 // Update the map with the new temporary. If we created a placeholder above,
7256 // replace it with the new global now.
7257 llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
7258 if (Entry) {
7259 Entry->replaceAllUsesWith(CV);
7260 llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
7261 }
7262 Entry = CV;
7263
7264 return ConstantAddress(CV, Type, Align);
7265}
7266
7267/// EmitObjCPropertyImplementations - Emit information for synthesized
7268/// properties for an implementation.
7269void CodeGenModule::EmitObjCPropertyImplementations(const
7271 for (const auto *PID : D->property_impls()) {
7272 // Dynamic is just for type-checking.
7273 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
7274 ObjCPropertyDecl *PD = PID->getPropertyDecl();
7275
7276 // Determine which methods need to be implemented, some may have
7277 // been overridden. Note that ::isPropertyAccessor is not the method
7278 // we want, that just indicates if the decl came from a
7279 // property. What we want to know is if the method is defined in
7280 // this implementation.
7281 auto *Getter = PID->getGetterMethodDecl();
7282 if (!Getter || Getter->isSynthesizedAccessorStub())
7284 const_cast<ObjCImplementationDecl *>(D), PID);
7285 auto *Setter = PID->getSetterMethodDecl();
7286 if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
7288 const_cast<ObjCImplementationDecl *>(D), PID);
7289 }
7290 }
7291}
7292
7294 const ObjCInterfaceDecl *iface = impl->getClassInterface();
7295 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
7296 ivar; ivar = ivar->getNextIvar())
7297 if (ivar->getType().isDestructedType())
7298 return true;
7299
7300 return false;
7301}
7302
7305 CodeGenFunction CGF(CGM);
7307 E = D->init_end(); B != E; ++B) {
7308 CXXCtorInitializer *CtorInitExp = *B;
7309 Expr *Init = CtorInitExp->getInit();
7310 if (!CGF.isTrivialInitializer(Init))
7311 return false;
7312 }
7313 return true;
7314}
7315
7316/// EmitObjCIvarInitializations - Emit information for ivar initialization
7317/// for an implementation.
7318void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
7319 // We might need a .cxx_destruct even if we don't have any ivar initializers.
7320 if (needsDestructMethod(D)) {
7321 const IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
7322 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
7323 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(
7324 getContext(), D->getLocation(), D->getLocation(), cxxSelector,
7325 getContext().VoidTy, nullptr, D,
7326 /*isInstance=*/true, /*isVariadic=*/false,
7327 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
7328 /*isImplicitlyDeclared=*/true,
7329 /*isDefined=*/false, ObjCImplementationControl::Required);
7330 D->addInstanceMethod(DTORMethod);
7331 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
7332 D->setHasDestructors(true);
7333 }
7334
7335 // If the implementation doesn't have any ivar initializers, we don't need
7336 // a .cxx_construct.
7337 if (D->getNumIvarInitializers() == 0 ||
7338 AllTrivialInitializers(*this, D))
7339 return;
7340
7341 const IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
7342 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
7343 // The constructor returns 'self'.
7344 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(
7345 getContext(), D->getLocation(), D->getLocation(), cxxSelector,
7346 getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true,
7347 /*isVariadic=*/false,
7348 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
7349 /*isImplicitlyDeclared=*/true,
7350 /*isDefined=*/false, ObjCImplementationControl::Required);
7351 D->addInstanceMethod(CTORMethod);
7352 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
7354}
7355
7356// EmitLinkageSpec - Emit all declarations in a linkage spec.
7357void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
7358 if (LSD->getLanguage() != LinkageSpecLanguageIDs::C &&
7360 ErrorUnsupported(LSD, "linkage spec");
7361 return;
7362 }
7363
7364 EmitDeclContext(LSD);
7365}
7366
7367void CodeGenModule::EmitTopLevelStmt(const TopLevelStmtDecl *D) {
7368 // Device code should not be at top level.
7369 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
7370 return;
7371
7372 std::unique_ptr<CodeGenFunction> &CurCGF =
7373 GlobalTopLevelStmtBlockInFlight.first;
7374
7375 // We emitted a top-level stmt but after it there is initialization.
7376 // Stop squashing the top-level stmts into a single function.
7377 if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) {
7378 CurCGF->FinishFunction(D->getEndLoc());
7379 CurCGF = nullptr;
7380 }
7381
7382 if (!CurCGF) {
7383 // void __stmts__N(void)
7384 // FIXME: Ask the ABI name mangler to pick a name.
7385 std::string Name = "__stmts__" + llvm::utostr(CXXGlobalInits.size());
7386 FunctionArgList Args;
7387 QualType RetTy = getContext().VoidTy;
7388 const CGFunctionInfo &FnInfo =
7390 llvm::FunctionType *FnTy = getTypes().GetFunctionType(FnInfo);
7391 llvm::Function *Fn = llvm::Function::Create(
7392 FnTy, llvm::GlobalValue::InternalLinkage, Name, &getModule());
7393
7394 CurCGF.reset(new CodeGenFunction(*this));
7395 GlobalTopLevelStmtBlockInFlight.second = D;
7396 CurCGF->StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args,
7397 D->getBeginLoc(), D->getBeginLoc());
7398 CXXGlobalInits.push_back(Fn);
7399 }
7400
7401 CurCGF->EmitStmt(D->getStmt());
7402}
7403
7404void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
7405 for (auto *I : DC->decls()) {
7406 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
7407 // are themselves considered "top-level", so EmitTopLevelDecl on an
7408 // ObjCImplDecl does not recursively visit them. We need to do that in
7409 // case they're nested inside another construct (LinkageSpecDecl /
7410 // ExportDecl) that does stop them from being considered "top-level".
7411 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
7412 for (auto *M : OID->methods())
7414 }
7415
7417 }
7418}
7419
7420/// EmitTopLevelDecl - Emit code for a single top level declaration.
7422 // Ignore dependent declarations.
7423 if (D->isTemplated())
7424 return;
7425
7426 // Consteval function shouldn't be emitted.
7427 if (auto *FD = dyn_cast<FunctionDecl>(D); FD && FD->isImmediateFunction())
7428 return;
7429
7430 switch (D->getKind()) {
7431 case Decl::CXXConversion:
7432 case Decl::CXXMethod:
7433 case Decl::Function:
7435 // Always provide some coverage mapping
7436 // even for the functions that aren't emitted.
7438 break;
7439
7440 case Decl::CXXDeductionGuide:
7441 // Function-like, but does not result in code emission.
7442 break;
7443
7444 case Decl::Var:
7445 case Decl::Decomposition:
7446 case Decl::VarTemplateSpecialization:
7448 if (auto *DD = dyn_cast<DecompositionDecl>(D))
7449 for (auto *B : DD->flat_bindings())
7450 if (auto *HD = B->getHoldingVar())
7451 EmitGlobal(HD);
7452
7453 break;
7454
7455 // Indirect fields from global anonymous structs and unions can be
7456 // ignored; only the actual variable requires IR gen support.
7457 case Decl::IndirectField:
7458 break;
7459
7460 // C++ Decls
7461 case Decl::Namespace:
7462 EmitDeclContext(cast<NamespaceDecl>(D));
7463 break;
7464 case Decl::ClassTemplateSpecialization: {
7465 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
7466 if (CGDebugInfo *DI = getModuleDebugInfo())
7467 if (Spec->getSpecializationKind() ==
7469 Spec->hasDefinition())
7470 DI->completeTemplateDefinition(*Spec);
7471 } [[fallthrough]];
7472 case Decl::CXXRecord: {
7474 if (CGDebugInfo *DI = getModuleDebugInfo()) {
7475 if (CRD->hasDefinition())
7476 DI->EmitAndRetainType(
7477 getContext().getCanonicalTagType(cast<RecordDecl>(D)));
7478 if (auto *ES = D->getASTContext().getExternalSource())
7479 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
7480 DI->completeUnusedClass(*CRD);
7481 }
7482 // Emit any static data members, they may be definitions.
7483 for (auto *I : CRD->decls())
7486 break;
7487 }
7488 // No code generation needed.
7489 case Decl::UsingShadow:
7490 case Decl::ClassTemplate:
7491 case Decl::VarTemplate:
7492 case Decl::Concept:
7493 case Decl::VarTemplatePartialSpecialization:
7494 case Decl::FunctionTemplate:
7495 case Decl::TypeAliasTemplate:
7496 case Decl::Block:
7497 case Decl::Empty:
7498 case Decl::Binding:
7499 break;
7500 case Decl::Using: // using X; [C++]
7501 if (CGDebugInfo *DI = getModuleDebugInfo())
7502 DI->EmitUsingDecl(cast<UsingDecl>(*D));
7503 break;
7504 case Decl::UsingEnum: // using enum X; [C++]
7505 if (CGDebugInfo *DI = getModuleDebugInfo())
7506 DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D));
7507 break;
7508 case Decl::NamespaceAlias:
7509 if (CGDebugInfo *DI = getModuleDebugInfo())
7510 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
7511 break;
7512 case Decl::UsingDirective: // using namespace X; [C++]
7513 if (CGDebugInfo *DI = getModuleDebugInfo())
7514 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
7515 break;
7516 case Decl::CXXConstructor:
7518 break;
7519 case Decl::CXXDestructor:
7521 break;
7522
7523 case Decl::StaticAssert:
7524 // Nothing to do.
7525 break;
7526
7527 // Objective-C Decls
7528
7529 // Forward declarations, no (immediate) code generation.
7530 case Decl::ObjCInterface:
7531 case Decl::ObjCCategory:
7532 break;
7533
7534 case Decl::ObjCProtocol: {
7535 auto *Proto = cast<ObjCProtocolDecl>(D);
7536 if (Proto->isThisDeclarationADefinition())
7537 ObjCRuntime->GenerateProtocol(Proto);
7538 break;
7539 }
7540
7541 case Decl::ObjCCategoryImpl:
7542 // Categories have properties but don't support synthesize so we
7543 // can ignore them here.
7544 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
7545 break;
7546
7547 case Decl::ObjCImplementation: {
7548 auto *OMD = cast<ObjCImplementationDecl>(D);
7549 EmitObjCPropertyImplementations(OMD);
7550 EmitObjCIvarInitializations(OMD);
7551 ObjCRuntime->GenerateClass(OMD);
7552 // Emit global variable debug information.
7553 if (CGDebugInfo *DI = getModuleDebugInfo())
7554 if (getCodeGenOpts().hasReducedDebugInfo())
7555 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
7556 OMD->getClassInterface()), OMD->getLocation());
7557 break;
7558 }
7559 case Decl::ObjCMethod: {
7560 auto *OMD = cast<ObjCMethodDecl>(D);
7561 // If this is not a prototype, emit the body.
7562 if (OMD->getBody())
7564 break;
7565 }
7566 case Decl::ObjCCompatibleAlias:
7567 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
7568 break;
7569
7570 case Decl::PragmaComment: {
7571 const auto *PCD = cast<PragmaCommentDecl>(D);
7572 switch (PCD->getCommentKind()) {
7573 case PCK_Unknown:
7574 llvm_unreachable("unexpected pragma comment kind");
7575 case PCK_Linker:
7576 AppendLinkerOptions(PCD->getArg());
7577 break;
7578 case PCK_Lib:
7579 AddDependentLib(PCD->getArg());
7580 break;
7581 case PCK_Compiler:
7582 case PCK_ExeStr:
7583 case PCK_User:
7584 break; // We ignore all of these.
7585 }
7586 break;
7587 }
7588
7589 case Decl::PragmaDetectMismatch: {
7590 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
7591 AddDetectMismatch(PDMD->getName(), PDMD->getValue());
7592 break;
7593 }
7594
7595 case Decl::LinkageSpec:
7596 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
7597 break;
7598
7599 case Decl::FileScopeAsm: {
7600 // File-scope asm is ignored during device-side CUDA compilation.
7601 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
7602 break;
7603 // File-scope asm is ignored during device-side OpenMP compilation.
7604 if (LangOpts.OpenMPIsTargetDevice)
7605 break;
7606 // File-scope asm is ignored during device-side SYCL compilation.
7607 if (LangOpts.SYCLIsDevice)
7608 break;
7609 auto *AD = cast<FileScopeAsmDecl>(D);
7610 getModule().appendModuleInlineAsm(AD->getAsmString());
7611 break;
7612 }
7613
7614 case Decl::TopLevelStmt:
7615 EmitTopLevelStmt(cast<TopLevelStmtDecl>(D));
7616 break;
7617
7618 case Decl::Import: {
7619 auto *Import = cast<ImportDecl>(D);
7620
7621 // If we've already imported this module, we're done.
7622 if (!ImportedModules.insert(Import->getImportedModule()))
7623 break;
7624
7625 // Emit debug information for direct imports.
7626 if (!Import->getImportedOwningModule()) {
7627 if (CGDebugInfo *DI = getModuleDebugInfo())
7628 DI->EmitImportDecl(*Import);
7629 }
7630
7631 // For C++ standard modules we are done - we will call the module
7632 // initializer for imported modules, and that will likewise call those for
7633 // any imports it has.
7634 if (CXX20ModuleInits && Import->getImportedModule() &&
7635 Import->getImportedModule()->isNamedModule())
7636 break;
7637
7638 // For clang C++ module map modules the initializers for sub-modules are
7639 // emitted here.
7640
7641 // Find all of the submodules and emit the module initializers.
7644 Visited.insert(Import->getImportedModule());
7645 Stack.push_back(Import->getImportedModule());
7646
7647 while (!Stack.empty()) {
7648 clang::Module *Mod = Stack.pop_back_val();
7649 if (!EmittedModuleInitializers.insert(Mod).second)
7650 continue;
7651
7652 for (auto *D : Context.getModuleInitializers(Mod))
7654
7655 // Visit the submodules of this module.
7656 for (auto *Submodule : Mod->submodules()) {
7657 // Skip explicit children; they need to be explicitly imported to emit
7658 // the initializers.
7659 if (Submodule->IsExplicit)
7660 continue;
7661
7662 if (Visited.insert(Submodule).second)
7663 Stack.push_back(Submodule);
7664 }
7665 }
7666 break;
7667 }
7668
7669 case Decl::Export:
7670 EmitDeclContext(cast<ExportDecl>(D));
7671 break;
7672
7673 case Decl::OMPThreadPrivate:
7675 break;
7676
7677 case Decl::OMPAllocate:
7679 break;
7680
7681 case Decl::OMPDeclareReduction:
7683 break;
7684
7685 case Decl::OMPDeclareMapper:
7687 break;
7688
7689 case Decl::OMPRequires:
7691 break;
7692
7693 case Decl::Typedef:
7694 case Decl::TypeAlias: // using foo = bar; [C++11]
7695 if (CGDebugInfo *DI = getModuleDebugInfo())
7696 DI->EmitAndRetainType(getContext().getTypedefType(
7697 ElaboratedTypeKeyword::None, /*Qualifier=*/std::nullopt,
7699 break;
7700
7701 case Decl::Record:
7702 if (CGDebugInfo *DI = getModuleDebugInfo())
7704 DI->EmitAndRetainType(
7705 getContext().getCanonicalTagType(cast<RecordDecl>(D)));
7706 break;
7707
7708 case Decl::Enum:
7709 if (CGDebugInfo *DI = getModuleDebugInfo())
7710 if (cast<EnumDecl>(D)->getDefinition())
7711 DI->EmitAndRetainType(
7712 getContext().getCanonicalTagType(cast<EnumDecl>(D)));
7713 break;
7714
7715 case Decl::HLSLRootSignature:
7717 break;
7718 case Decl::HLSLBuffer:
7720 break;
7721
7722 case Decl::OpenACCDeclare:
7724 break;
7725 case Decl::OpenACCRoutine:
7727 break;
7728
7729 default:
7730 // Make sure we handled everything we should, every other kind is a
7731 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
7732 // function. Need to recode Decl::Kind to do that easily.
7733 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
7734 break;
7735 }
7736}
7737
7739 // Do we need to generate coverage mapping?
7740 if (!CodeGenOpts.CoverageMapping)
7741 return;
7742 switch (D->getKind()) {
7743 case Decl::CXXConversion:
7744 case Decl::CXXMethod:
7745 case Decl::Function:
7746 case Decl::ObjCMethod:
7747 case Decl::CXXConstructor:
7748 case Decl::CXXDestructor: {
7749 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
7750 break;
7752 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
7753 break;
7755 SM.isInSystemHeader(D->getBeginLoc()))
7756 break;
7757 DeferredEmptyCoverageMappingDecls.try_emplace(D, true);
7758 break;
7759 }
7760 default:
7761 break;
7762 };
7763}
7764
7766 // Do we need to generate coverage mapping?
7767 if (!CodeGenOpts.CoverageMapping)
7768 return;
7769 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
7770 if (Fn->isTemplateInstantiation())
7771 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
7772 }
7773 DeferredEmptyCoverageMappingDecls.insert_or_assign(D, false);
7774}
7775
7777 // We call takeVector() here to avoid use-after-free.
7778 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
7779 // we deserialize function bodies to emit coverage info for them, and that
7780 // deserializes more declarations. How should we handle that case?
7781 for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
7782 if (!Entry.second)
7783 continue;
7784 const Decl *D = Entry.first;
7785 switch (D->getKind()) {
7786 case Decl::CXXConversion:
7787 case Decl::CXXMethod:
7788 case Decl::Function:
7789 case Decl::ObjCMethod: {
7790 CodeGenPGO PGO(*this);
7793 getFunctionLinkage(GD));
7794 break;
7795 }
7796 case Decl::CXXConstructor: {
7797 CodeGenPGO PGO(*this);
7800 getFunctionLinkage(GD));
7801 break;
7802 }
7803 case Decl::CXXDestructor: {
7804 CodeGenPGO PGO(*this);
7807 getFunctionLinkage(GD));
7808 break;
7809 }
7810 default:
7811 break;
7812 };
7813 }
7814}
7815
7817 // In order to transition away from "__original_main" gracefully, emit an
7818 // alias for "main" in the no-argument case so that libc can detect when
7819 // new-style no-argument main is in used.
7820 if (llvm::Function *F = getModule().getFunction("main")) {
7821 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
7822 F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) {
7823 auto *GA = llvm::GlobalAlias::create("__main_void", F);
7824 GA->setVisibility(llvm::GlobalValue::HiddenVisibility);
7825 }
7826 }
7827}
7828
7829/// Turns the given pointer into a constant.
7830static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
7831 const void *Ptr) {
7832 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
7833 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
7834 return llvm::ConstantInt::get(i64, PtrInt);
7835}
7836
7838 llvm::NamedMDNode *&GlobalMetadata,
7839 GlobalDecl D,
7840 llvm::GlobalValue *Addr) {
7841 if (!GlobalMetadata)
7842 GlobalMetadata =
7843 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
7844
7845 // TODO: should we report variant information for ctors/dtors?
7846 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
7847 llvm::ConstantAsMetadata::get(GetPointerConstant(
7848 CGM.getLLVMContext(), D.getDecl()))};
7849 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
7850}
7851
7852bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem,
7853 llvm::GlobalValue *CppFunc) {
7854 // Store the list of ifuncs we need to replace uses in.
7855 llvm::SmallVector<llvm::GlobalIFunc *> IFuncs;
7856 // List of ConstantExprs that we should be able to delete when we're done
7857 // here.
7858 llvm::SmallVector<llvm::ConstantExpr *> CEs;
7859
7860 // It isn't valid to replace the extern-C ifuncs if all we find is itself!
7861 if (Elem == CppFunc)
7862 return false;
7863
7864 // First make sure that all users of this are ifuncs (or ifuncs via a
7865 // bitcast), and collect the list of ifuncs and CEs so we can work on them
7866 // later.
7867 for (llvm::User *User : Elem->users()) {
7868 // Users can either be a bitcast ConstExpr that is used by the ifuncs, OR an
7869 // ifunc directly. In any other case, just give up, as we don't know what we
7870 // could break by changing those.
7871 if (auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) {
7872 if (ConstExpr->getOpcode() != llvm::Instruction::BitCast)
7873 return false;
7874
7875 for (llvm::User *CEUser : ConstExpr->users()) {
7876 if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) {
7877 IFuncs.push_back(IFunc);
7878 } else {
7879 return false;
7880 }
7881 }
7882 CEs.push_back(ConstExpr);
7883 } else if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) {
7884 IFuncs.push_back(IFunc);
7885 } else {
7886 // This user is one we don't know how to handle, so fail redirection. This
7887 // will result in an ifunc retaining a resolver name that will ultimately
7888 // fail to be resolved to a defined function.
7889 return false;
7890 }
7891 }
7892
7893 // Now we know this is a valid case where we can do this alias replacement, we
7894 // need to remove all of the references to Elem (and the bitcasts!) so we can
7895 // delete it.
7896 for (llvm::GlobalIFunc *IFunc : IFuncs)
7897 IFunc->setResolver(nullptr);
7898 for (llvm::ConstantExpr *ConstExpr : CEs)
7899 ConstExpr->destroyConstant();
7900
7901 // We should now be out of uses for the 'old' version of this function, so we
7902 // can erase it as well.
7903 Elem->eraseFromParent();
7904
7905 for (llvm::GlobalIFunc *IFunc : IFuncs) {
7906 // The type of the resolver is always just a function-type that returns the
7907 // type of the IFunc, so create that here. If the type of the actual
7908 // resolver doesn't match, it just gets bitcast to the right thing.
7909 auto *ResolverTy =
7910 llvm::FunctionType::get(IFunc->getType(), /*isVarArg*/ false);
7911 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
7912 CppFunc->getName(), ResolverTy, {}, /*ForVTable*/ false);
7913 IFunc->setResolver(Resolver);
7914 }
7915 return true;
7916}
7917
7918/// For each function which is declared within an extern "C" region and marked
7919/// as 'used', but has internal linkage, create an alias from the unmangled
7920/// name to the mangled name if possible. People expect to be able to refer
7921/// to such functions with an unmangled name from inline assembly within the
7922/// same translation unit.
7923void CodeGenModule::EmitStaticExternCAliases() {
7924 if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
7925 return;
7926 for (auto &I : StaticExternCValues) {
7927 const IdentifierInfo *Name = I.first;
7928 llvm::GlobalValue *Val = I.second;
7929
7930 // If Val is null, that implies there were multiple declarations that each
7931 // had a claim to the unmangled name. In this case, generation of the alias
7932 // is suppressed. See CodeGenModule::MaybeHandleStaticInExternC.
7933 if (!Val)
7934 break;
7935
7936 llvm::GlobalValue *ExistingElem =
7937 getModule().getNamedValue(Name->getName());
7938
7939 // If there is either not something already by this name, or we were able to
7940 // replace all uses from IFuncs, create the alias.
7941 if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val))
7942 addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
7943 }
7944}
7945
7947 GlobalDecl &Result) const {
7948 auto Res = Manglings.find(MangledName);
7949 if (Res == Manglings.end())
7950 return false;
7951 Result = Res->getValue();
7952 return true;
7953}
7954
7955/// Emits metadata nodes associating all the global values in the
7956/// current module with the Decls they came from. This is useful for
7957/// projects using IR gen as a subroutine.
7958///
7959/// Since there's currently no way to associate an MDNode directly
7960/// with an llvm::GlobalValue, we create a global named metadata
7961/// with the name 'clang.global.decl.ptrs'.
7962void CodeGenModule::EmitDeclMetadata() {
7963 llvm::NamedMDNode *GlobalMetadata = nullptr;
7964
7965 for (auto &I : MangledDeclNames) {
7966 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
7967 // Some mangled names don't necessarily have an associated GlobalValue
7968 // in this module, e.g. if we mangled it for DebugInfo.
7969 if (Addr)
7970 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
7971 }
7972}
7973
7974/// Emits metadata nodes for all the local variables in the current
7975/// function.
7976void CodeGenFunction::EmitDeclMetadata() {
7977 if (LocalDeclMap.empty()) return;
7978
7979 llvm::LLVMContext &Context = getLLVMContext();
7980
7981 // Find the unique metadata ID for this name.
7982 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
7983
7984 llvm::NamedMDNode *GlobalMetadata = nullptr;
7985
7986 for (auto &I : LocalDeclMap) {
7987 const Decl *D = I.first;
7988 llvm::Value *Addr = I.second.emitRawPointer(*this);
7989 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
7990 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
7991 Alloca->setMetadata(
7992 DeclPtrKind, llvm::MDNode::get(
7993 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
7994 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
7995 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
7996 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
7997 }
7998 }
7999}
8000
8001void CodeGenModule::EmitVersionIdentMetadata() {
8002 llvm::NamedMDNode *IdentMetadata =
8003 TheModule.getOrInsertNamedMetadata("llvm.ident");
8004 std::string Version = getClangFullVersion();
8005 llvm::LLVMContext &Ctx = TheModule.getContext();
8006
8007 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
8008 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
8009}
8010
8011void CodeGenModule::EmitCommandLineMetadata() {
8012 llvm::NamedMDNode *CommandLineMetadata =
8013 TheModule.getOrInsertNamedMetadata("llvm.commandline");
8014 std::string CommandLine = getCodeGenOpts().RecordCommandLine;
8015 llvm::LLVMContext &Ctx = TheModule.getContext();
8016
8017 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
8018 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
8019}
8020
8021void CodeGenModule::EmitCoverageFile() {
8022 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
8023 if (!CUNode)
8024 return;
8025
8026 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
8027 llvm::LLVMContext &Ctx = TheModule.getContext();
8028 auto *CoverageDataFile =
8029 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
8030 auto *CoverageNotesFile =
8031 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
8032 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
8033 llvm::MDNode *CU = CUNode->getOperand(i);
8034 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
8035 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
8036 }
8037}
8038
8040 bool ForEH) {
8041 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
8042 // FIXME: should we even be calling this method if RTTI is disabled
8043 // and it's not for EH?
8044 if (!shouldEmitRTTI(ForEH))
8045 return llvm::Constant::getNullValue(GlobalsInt8PtrTy);
8046
8047 if (ForEH && Ty->isObjCObjectPointerType() &&
8048 LangOpts.ObjCRuntime.isGNUFamily())
8049 return ObjCRuntime->GetEHType(Ty);
8050
8052}
8053
8055 // Do not emit threadprivates in simd-only mode.
8056 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
8057 return;
8058 for (auto RefExpr : D->varlist()) {
8059 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
8060 bool PerformInit =
8061 VD->getAnyInitializer() &&
8062 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
8063 /*ForRef=*/false);
8064
8066 getTypes().ConvertTypeForMem(VD->getType()),
8067 getContext().getDeclAlign(VD));
8068 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
8069 VD, Addr, RefExpr->getBeginLoc(), PerformInit))
8070 CXXGlobalInits.push_back(InitFunction);
8071 }
8072}
8073
8074llvm::Metadata *
8075CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
8076 StringRef Suffix) {
8077 if (auto *FnType = T->getAs<FunctionProtoType>())
8079 FnType->getReturnType(), FnType->getParamTypes(),
8080 FnType->getExtProtoInfo().withExceptionSpec(EST_None));
8081
8082 llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
8083 if (InternalId)
8084 return InternalId;
8085
8086 if (isExternallyVisible(T->getLinkage())) {
8087 std::string OutName;
8088 llvm::raw_string_ostream Out(OutName);
8090 T, Out, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers);
8091
8092 if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers)
8093 Out << ".normalized";
8094
8095 Out << Suffix;
8096
8097 InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
8098 } else {
8099 InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
8101 }
8102
8103 return InternalId;
8104}
8105
8107 assert(isa<FunctionType>(T));
8109 getContext(), T, getCodeGenOpts().SanitizeCfiICallGeneralizePointers);
8110 if (getCodeGenOpts().SanitizeCfiICallGeneralizePointers)
8113}
8114
8116 return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
8117}
8118
8119llvm::Metadata *
8121 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
8122}
8123
8125 return CreateMetadataIdentifierImpl(T, GeneralizedMetadataIdMap,
8126 ".generalized");
8127}
8128
8129/// Returns whether this module needs the "all-vtables" type identifier.
8131 // Returns true if at least one of vtable-based CFI checkers is enabled and
8132 // is not in the trapping mode.
8133 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
8134 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
8135 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
8136 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
8137 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
8138 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
8139 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
8140 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
8141}
8142
8143void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
8144 CharUnits Offset,
8145 const CXXRecordDecl *RD) {
8147 llvm::Metadata *MD = CreateMetadataIdentifierForType(T);
8148 VTable->addTypeMetadata(Offset.getQuantity(), MD);
8149
8150 if (CodeGenOpts.SanitizeCfiCrossDso)
8151 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
8152 VTable->addTypeMetadata(Offset.getQuantity(),
8153 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
8154
8155 if (NeedAllVtablesTypeId()) {
8156 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
8157 VTable->addTypeMetadata(Offset.getQuantity(), MD);
8158 }
8159}
8160
8161llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
8162 if (!SanStats)
8163 SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule());
8164
8165 return *SanStats;
8166}
8167
8168llvm::Value *
8170 CodeGenFunction &CGF) {
8171 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
8172 auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
8173 auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
8174 auto *Call = CGF.EmitRuntimeCall(
8175 CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C});
8176 return Call;
8177}
8178
8180 QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) {
8181 return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
8182 /* forPointeeType= */ true);
8183}
8184
8186 LValueBaseInfo *BaseInfo,
8187 TBAAAccessInfo *TBAAInfo,
8188 bool forPointeeType) {
8189 if (TBAAInfo)
8190 *TBAAInfo = getTBAAAccessInfo(T);
8191
8192 // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But
8193 // that doesn't return the information we need to compute BaseInfo.
8194
8195 // Honor alignment typedef attributes even on incomplete types.
8196 // We also honor them straight for C++ class types, even as pointees;
8197 // there's an expressivity gap here.
8198 if (auto TT = T->getAs<TypedefType>()) {
8199 if (auto Align = TT->getDecl()->getMaxAlignment()) {
8200 if (BaseInfo)
8202 return getContext().toCharUnitsFromBits(Align);
8203 }
8204 }
8205
8206 bool AlignForArray = T->isArrayType();
8207
8208 // Analyze the base element type, so we don't get confused by incomplete
8209 // array types.
8211
8212 if (T->isIncompleteType()) {
8213 // We could try to replicate the logic from
8214 // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the
8215 // type is incomplete, so it's impossible to test. We could try to reuse
8216 // getTypeAlignIfKnown, but that doesn't return the information we need
8217 // to set BaseInfo. So just ignore the possibility that the alignment is
8218 // greater than one.
8219 if (BaseInfo)
8221 return CharUnits::One();
8222 }
8223
8224 if (BaseInfo)
8226
8227 CharUnits Alignment;
8228 const CXXRecordDecl *RD;
8229 if (T.getQualifiers().hasUnaligned()) {
8230 Alignment = CharUnits::One();
8231 } else if (forPointeeType && !AlignForArray &&
8232 (RD = T->getAsCXXRecordDecl())) {
8233 // For C++ class pointees, we don't know whether we're pointing at a
8234 // base or a complete object, so we generally need to use the
8235 // non-virtual alignment.
8236 Alignment = getClassPointerAlignment(RD);
8237 } else {
8238 Alignment = getContext().getTypeAlignInChars(T);
8239 }
8240
8241 // Cap to the global maximum type alignment unless the alignment
8242 // was somehow explicit on the type.
8243 if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
8244 if (Alignment.getQuantity() > MaxAlign &&
8245 !getContext().isAlignmentRequired(T))
8246 Alignment = CharUnits::fromQuantity(MaxAlign);
8247 }
8248 return Alignment;
8249}
8250
8252 unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter;
8253 if (StopAfter) {
8254 // This number is positive only when -ftrivial-auto-var-init-stop-after=* is
8255 // used
8256 if (NumAutoVarInit >= StopAfter) {
8257 return true;
8258 }
8259 if (!NumAutoVarInit) {
8260 unsigned DiagID = getDiags().getCustomDiagID(
8262 "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
8263 "number of times ftrivial-auto-var-init=%1 gets applied.");
8264 getDiags().Report(DiagID)
8265 << StopAfter
8266 << (getContext().getLangOpts().getTrivialAutoVarInit() ==
8268 ? "zero"
8269 : "pattern");
8270 }
8271 ++NumAutoVarInit;
8272 }
8273 return false;
8274}
8275
8277 const Decl *D) const {
8278 // ptxas does not allow '.' in symbol names. On the other hand, HIP prefers
8279 // postfix beginning with '.' since the symbol name can be demangled.
8280 if (LangOpts.HIP)
8281 OS << (isa<VarDecl>(D) ? ".static." : ".intern.");
8282 else
8283 OS << (isa<VarDecl>(D) ? "__static__" : "__intern__");
8284
8285 // If the CUID is not specified we try to generate a unique postfix.
8286 if (getLangOpts().CUID.empty()) {
8288 PresumedLoc PLoc = SM.getPresumedLoc(D->getLocation());
8289 assert(PLoc.isValid() && "Source location is expected to be valid.");
8290
8291 // Get the hash of the user defined macros.
8292 llvm::MD5 Hash;
8293 llvm::MD5::MD5Result Result;
8294 for (const auto &Arg : PreprocessorOpts.Macros)
8295 Hash.update(Arg.first);
8296 Hash.final(Result);
8297
8298 // Get the UniqueID for the file containing the decl.
8299 llvm::sys::fs::UniqueID ID;
8300 auto Status = FS->status(PLoc.getFilename());
8301 if (!Status) {
8302 PLoc = SM.getPresumedLoc(D->getLocation(), /*UseLineDirectives=*/false);
8303 assert(PLoc.isValid() && "Source location is expected to be valid.");
8304 Status = FS->status(PLoc.getFilename());
8305 }
8306 if (!Status) {
8307 SM.getDiagnostics().Report(diag::err_cannot_open_file)
8308 << PLoc.getFilename() << Status.getError().message();
8309 } else {
8310 ID = Status->getUniqueID();
8311 }
8312 OS << llvm::format("%x", ID.getFile()) << llvm::format("%x", ID.getDevice())
8313 << "_" << llvm::utohexstr(Result.low(), /*LowerCase=*/true, /*Width=*/8);
8314 } else {
8315 OS << getContext().getCUIDHash();
8316 }
8317}
8318
8319void CodeGenModule::moveLazyEmissionStates(CodeGenModule *NewBuilder) {
8320 assert(DeferredDeclsToEmit.empty() &&
8321 "Should have emitted all decls deferred to emit.");
8322 assert(NewBuilder->DeferredDecls.empty() &&
8323 "Newly created module should not have deferred decls");
8324 NewBuilder->DeferredDecls = std::move(DeferredDecls);
8325 assert(EmittedDeferredDecls.empty() &&
8326 "Still have (unmerged) EmittedDeferredDecls deferred decls");
8327
8328 assert(NewBuilder->DeferredVTables.empty() &&
8329 "Newly created module should not have deferred vtables");
8330 NewBuilder->DeferredVTables = std::move(DeferredVTables);
8331
8332 assert(NewBuilder->MangledDeclNames.empty() &&
8333 "Newly created module should not have mangled decl names");
8334 assert(NewBuilder->Manglings.empty() &&
8335 "Newly created module should not have manglings");
8336 NewBuilder->Manglings = std::move(Manglings);
8337
8338 NewBuilder->WeakRefReferences = std::move(WeakRefReferences);
8339
8340 NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx);
8341}
Defines the clang::ASTContext interface.
#define V(N, I)
This file provides some common utility functions for processing Lambda related AST Constructs.
Defines the Diagnostic-related interfaces.
Defines enum values for all the target-independent builtin functions.
static bool shouldAssumeDSOLocal(const CIRGenModule &cgm, cir::CIRGlobalValueInterface gv)
static bool shouldBeInCOMDAT(CIRGenModule &cgm, const Decl &d)
static std::string getMangledNameImpl(CIRGenModule &cgm, GlobalDecl gd, const NamedDecl *nd)
static CIRGenCXXABI * createCXXABI(CIRGenModule &cgm)
static bool isVarDeclStrongDefinition(const ASTContext &astContext, CIRGenModule &cgm, const VarDecl *vd, bool noCommon)
static void setLinkageForGV(cir::GlobalOp &gv, const NamedDecl *nd)
static bool hasExistingGeneralizedTypeMD(llvm::Function *F)
static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM, const CPUSpecificAttr *Attr, unsigned CPUIndex, raw_ostream &Out)
static bool AllTrivialInitializers(CodeGenModule &CGM, ObjCImplementationDecl *D)
static const FunctionDecl * GetRuntimeFunctionDecl(ASTContext &C, StringRef Name)
static GlobalDecl getBaseVariantGlobalDecl(const NamedDecl *D)
static void checkAliasForTocData(llvm::GlobalVariable *GVar, const CodeGenOptions &CodeGenOpts, DiagnosticsEngine &Diags, SourceLocation Location)
static bool hasImplicitAttr(const ValueDecl *D)
static void emitUsed(CodeGenModule &CGM, StringRef Name, std::vector< llvm::WeakTrackingVH > &List)
static bool HasNonDllImportDtor(QualType T)
static llvm::Constant * GetPointerConstant(llvm::LLVMContext &Context, const void *Ptr)
Turns the given pointer into a constant.
static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S)
static llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM, GlobalDecl GD)
static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO, llvm::Module &M)
static QualType GeneralizeTransparentUnion(QualType Ty)
static std::string getCPUSpecificMangling(const CodeGenModule &CGM, StringRef Name)
static void setWindowsItaniumDLLImport(CodeGenModule &CGM, bool Local, llvm::Function *F, StringRef Name)
static const char AnnotationSection[]
static bool isUniqueInternalLinkageDecl(GlobalDecl GD, CodeGenModule &CGM)
static bool allowKCFIIdentifier(StringRef Name)
static void replaceUsesOfNonProtoConstant(llvm::Constant *old, llvm::Function *newFn)
Replace the uses of a function that was declared with a non-proto type.
static llvm::Constant * castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM, llvm::GlobalVariable *GV)
static void checkDataLayoutConsistency(const TargetInfo &Target, llvm::LLVMContext &Context, const LangOptions &Opts)
static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty, bool GeneralizePointers)
static bool needsDestructMethod(ObjCImplementationDecl *impl)
static bool isStackProtectorOn(const LangOptions &LangOpts, const llvm::Triple &Triple, clang::LangOptions::StackProtectorMode Mode)
static void removeImageAccessQualifier(std::string &TyName)
static llvm::StringMapEntry< llvm::GlobalVariable * > & GetConstantCFStringEntry(llvm::StringMap< llvm::GlobalVariable * > &Map, const StringLiteral *Literal, bool TargetIsLSB, bool &IsUTF16, unsigned &StringLength)
static void setLLVMVisibility(llvm::GlobalValue &GV, std::optional< llvm::GlobalValue::VisibilityTypes > V)
static llvm::GlobalVariable * GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, CodeGenModule &CGM, StringRef GlobalName, CharUnits Alignment)
static bool hasUnwindExceptions(const LangOptions &LangOpts)
Determines whether the language options require us to model unwind exceptions.
static llvm::APInt getFMVPriority(const TargetInfo &TI, const CodeGenFunction::FMVResolverOption &RO)
static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, SmallVectorImpl< llvm::MDNode * > &Metadata, llvm::SmallPtrSet< Module *, 16 > &Visited)
Add link options implied by the given module, including modules it depends on, using a postorder walk...
static llvm::cl::opt< bool > LimitedCoverage("limited-coverage-experimental", llvm::cl::Hidden, llvm::cl::desc("Emit limited coverage mapping information (experimental)"))
static CGCXXABI * createCXXABI(CodeGenModule &CGM)
static std::unique_ptr< TargetCodeGenInfo > createTargetCodeGenInfo(CodeGenModule &CGM)
static const llvm::GlobalValue * getAliasedGlobal(const llvm::GlobalValue *GV)
static QualType GeneralizeType(ASTContext &Ctx, QualType Ty, bool GeneralizePointers)
static bool shouldSkipAliasEmission(const CodeGenModule &CGM, const ValueDecl *Global)
static constexpr auto ErrnoTBAAMDName
static unsigned ArgInfoAddressSpace(LangAS AS)
static void replaceDeclarationWith(llvm::GlobalValue *Old, llvm::Constant *New)
static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, llvm::Function *NewFn)
ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we implement a function with...
static std::optional< llvm::GlobalValue::VisibilityTypes > getLLVMVisibility(clang::LangOptions::VisibilityFromDLLStorageClassKinds K)
static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM, const CXXMethodDecl *MD)
static bool checkAliasedGlobal(const ASTContext &Context, DiagnosticsEngine &Diags, SourceLocation Location, bool IsIFunc, const llvm::GlobalValue *Alias, const llvm::GlobalValue *&GV, const llvm::MapVector< GlobalDecl, StringRef > &MangledDeclNames, SourceRange AliasRange)
static void EmitGlobalDeclMetadata(CodeGenModule &CGM, llvm::NamedMDNode *&GlobalMetadata, GlobalDecl D, llvm::GlobalValue *Addr)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
TokenType getType() const
Returns the token's type, e.g.
#define X(type, name)
Definition Value.h:97
llvm::MachO::Target Target
Definition MachO.h:51
llvm::MachO::Record Record
Definition MachO.h:31
Defines the clang::Module class, which describes a module in the source code.
#define SM(sm)
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
Definition SemaCUDA.cpp:187
static const NamedDecl * getDefinition(const Decl *D)
Defines the SourceManager interface.
static CharUnits getTypeAllocSize(CodeGenModule &CGM, llvm::Type *type)
Defines version macros and version-related utility functions for Clang.
__device__ __2f16 float __ockl_bool s
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
SourceManager & getSourceManager()
Definition ASTContext.h:837
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
@ WeakUnknown
Weak for now, might become strong later in this TU.
const ProfileList & getProfileList() const
Definition ASTContext.h:949
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
bool shouldExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel should be externalized.
const XRayFunctionFilter & getXRayFilter() const
Definition ASTContext.h:945
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
StringRef getCUIDHash() const
IdentifierTable & Idents
Definition ASTContext.h:776
const LangOptions & getLangOpts() const
Definition ASTContext.h:930
SelectorTable & Selectors
Definition ASTContext.h:777
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
const NoSanitizeList & getNoSanitizeList() const
Definition ASTContext.h:940
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
CharUnits getAlignOfGlobalVarInChars(QualType T, const VarDecl *VD) const
Return the alignment in characters that should be given to a global variable with type T.
GVALinkage GetGVALinkageForVariable(const VarDecl *VD) const
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:895
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
TargetCXXABI::Kind getCXXABIKind() const
Return the C++ ABI kind that should be used.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
CanQualType getCanonicalTagType(const TagDecl *TD) const
unsigned getTargetAddressSpace(LangAS AS) const
Module * getCurrentNamedModule() const
Get module under construction, nullptr if this is not a C++20 module.
Attr - This represents one attribute.
Definition Attr.h:45
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4659
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:303
std::string getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition Builtins.cpp:80
Represents a base class of a C++ class.
Definition DeclCXX.h:146
CXXTemporary * getTemporary()
Definition ExprCXX.h:1511
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1611
Represents a C++ base or member initializer.
Definition DeclCXX.h:2369
Expr * getInit() const
Get the initializer.
Definition DeclCXX.h:2571
FunctionDecl * getOperatorDelete() const
Definition ExprCXX.h:2665
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
Definition ExprCXX.cpp:741
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition DeclCXX.cpp:2710
bool isVirtual() const
Definition DeclCXX.h:2184
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2255
FunctionDecl * getOperatorNew() const
Definition ExprCXX.h:2459
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
base_class_range bases()
Definition DeclCXX.h:608
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
bool hasDefinition() const
Definition DeclCXX.h:561
const CXXDestructorDecl * getDestructor() const
Definition ExprCXX.h:1470
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3060
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
Definition CharUnits.h:189
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition CharUnits.h:58
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
std::string MSSecureHotPatchFunctionsFile
The name of a file that contains functions which will be compiled for hotpatching.
std::string RecordCommandLine
The string containing the commandline for the llvm.commandline metadata, if non-empty.
std::string FloatABI
The ABI to use for passing floating point arguments.
llvm::Reloc::Model RelocationModel
The name of the relocation model to use.
std::vector< std::string > TocDataVarsUserSpecified
List of global variables explicitly specified by the user as toc-data.
PointerAuthOptions PointerAuth
Configuration for pointer-signing.
std::vector< std::string > MSSecureHotPatchFunctionsList
A list of functions which will be compiled for hotpatching.
ABIInfo - Target specific hooks for defining how a type should be passed or returned from functions.
Definition ABIInfo.h:48
virtual void appendAttributeMangling(TargetAttr *Attr, raw_ostream &Out) const
Definition ABIInfo.cpp:186
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition Address.h:128
virtual void handleVarRegistration(const VarDecl *VD, llvm::GlobalVariable &Var)=0
Check whether a variable is a device variable and register it if true.
virtual llvm::GlobalValue * getKernelHandle(llvm::Function *Stub, GlobalDecl GD)=0
Get kernel handle by stub function.
virtual void internalizeDeviceSideVar(const VarDecl *D, llvm::GlobalValue::LinkageTypes &Linkage)=0
Adjust linkage of shadow variables in host compilation.
Implements C++ ABI-specific code generation functions.
Definition CGCXXABI.h:43
virtual void EmitCXXConstructors(const CXXConstructorDecl *D)=0
Emit constructor variants required by this ABI.
virtual llvm::Constant * getAddrOfRTTIDescriptor(QualType Ty)=0
virtual void EmitCXXDestructors(const CXXDestructorDecl *D)=0
Emit destructor variants required by this ABI.
virtual void setCXXDestructorDLLStorage(llvm::GlobalValue *GV, const CXXDestructorDecl *Dtor, CXXDtorType DT) const
Definition CGCXXABI.cpp:309
virtual llvm::GlobalValue::LinkageTypes getCXXDestructorLinkage(GVALinkage Linkage, const CXXDestructorDecl *Dtor, CXXDtorType DT) const
Definition CGCXXABI.cpp:316
MangleContext & getMangleContext()
Gets the mangle context.
Definition CGCXXABI.h:113
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition CGDebugInfo.h:59
void EmitExternalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl)
Emit information about an external variable.
void EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc, QualType FnType, llvm::Function *Fn=nullptr)
Emit debug info for a function declaration.
void AddStringLiteralDebugInfo(llvm::GlobalVariable *GV, const StringLiteral *S)
DebugInfo isn't attached to string literals by default.
CGFunctionInfo - Class to encapsulate the information about a function definition.
void handleGlobalVarDefinition(const VarDecl *VD, llvm::GlobalVariable *Var)
void addRootSignature(const HLSLRootSignatureDecl *D)
void addBuffer(const HLSLBufferDecl *D)
llvm::Type * getSamplerType(const Type *T)
void emitDeferredTargetDecls() const
Emit deferred declare target variables marked for deferred emission.
virtual void emitDeclareTargetFunction(const FunctionDecl *FD, llvm::GlobalValue *GV)
Emit code for handling declare target functions in the runtime.
virtual ConstantAddress getAddrOfDeclareTargetVar(const VarDecl *VD)
Returns the address of the variable marked as declare target with link clause OR as declare target wi...
bool hasRequiresUnifiedSharedMemory() const
Return whether the unified_shared_memory has been specified.
virtual void emitDeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn)
Marks function Fn with properly mangled versions of vector functions.
virtual void registerTargetGlobalVariable(const VarDecl *VD, llvm::Constant *Addr)
Checks if the provided global decl GD is a declare target variable and registers it when emitting cod...
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
void GenerateCode(GlobalDecl GD, llvm::Function *Fn, const CGFunctionInfo &FnInfo)
void EmitCfiCheckFail()
Emit a cross-DSO CFI failure handling function.
Definition CGExpr.cpp:4114
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:4075
void GenerateObjCMethod(const ObjCMethodDecl *OMD)
Generate an Objective-C method.
Definition CGObjC.cpp:807
llvm::CallInst * EmitRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
void GenerateObjCSetter(ObjCImplementationDecl *IMP, const ObjCPropertyImplDecl *PID)
GenerateObjCSetter - Synthesize an Objective-C property setter function for the given property.
Definition CGObjC.cpp:1672
llvm::LLVMContext & getLLVMContext()
bool isTrivialInitializer(const Expr *Init)
Determine whether the given initializer is trivial in the sense that it requires no code to be genera...
Definition CGDecl.cpp:1807
This class organizes the cross-function state that is used while generating LLVM code.
StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD)
ConstantAddress GetAddrOfMSGuidDecl(const MSGuidDecl *GD)
Get the address of a GUID.
void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const
Set visibility, dllimport/dllexport and dso_local.
void AddVTableTypeMetadata(llvm::GlobalVariable *VTable, CharUnits Offset, const CXXRecordDecl *RD)
Create and attach type metadata for the given vtable.
void UpdateCompletedType(const TagDecl *TD)
llvm::MDNode * getTBAAAccessTagInfo(TBAAAccessInfo Info)
getTBAAAccessTagInfo - Get TBAA tag for a given memory access.
llvm::GlobalVariable::ThreadLocalMode GetDefaultLLVMTLSModel() const
Get LLVM TLS mode from CodeGenOptions.
void SetInternalFunctionAttributes(GlobalDecl GD, llvm::Function *F, const CGFunctionInfo &FI)
Set the attributes on the LLVM function for the given decl and function info.
void setDSOLocal(llvm::GlobalValue *GV) const
llvm::MDNode * getTBAAStructInfo(QualType QTy)
CGHLSLRuntime & getHLSLRuntime()
Return a reference to the configured HLSL runtime.
llvm::Constant * EmitAnnotationArgs(const AnnotateAttr *Attr)
Emit additional args of the annotation.
llvm::Module & getModule() const
llvm::FunctionCallee CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false, bool AssumeConvergent=false)
Create or return a runtime function declaration with the specified type and name.
llvm::ConstantInt * CreateKCFITypeId(QualType T, StringRef Salt)
Generate a KCFI type identifier for T.
bool NeedAllVtablesTypeId() const
Returns whether this module needs the "all-vtables" type identifier.
void addCompilerUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.compiler.used metadata.
CodeGenVTables & getVTables()
llvm::ConstantInt * CreateCrossDsoCfiTypeId(llvm::Metadata *MD)
Generate a cross-DSO type identifier for MD.
CharUnits GetTargetTypeStoreSize(llvm::Type *Ty) const
Return the store size, in character units, of the given LLVM type.
void createFunctionTypeMetadataForIcall(const FunctionDecl *FD, llvm::Function *F)
Create and attach type metadata to the given function.
bool getExpressionLocationsEnabled() const
Return true if we should emit location information for expressions.
void addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C)
llvm::Constant * GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH=false)
Get the address of the RTTI descriptor for the given type.
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the given function.
void setGVPropertiesAux(llvm::GlobalValue *GV, const NamedDecl *D) const
const IntrusiveRefCntPtr< llvm::vfs::FileSystem > & getFileSystem() const
void EmitMainVoidAlias()
Emit an alias for "main" if it has no arguments (needed for wasm).
void DecorateInstructionWithInvariantGroup(llvm::Instruction *I, const CXXRecordDecl *RD)
Adds !invariant.barrier !tag to instruction.
DiagnosticsEngine & getDiags() const
bool isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn, SourceLocation Loc) const
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
llvm::Constant * getAddrOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the constructor/destructor of the given type.
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn't support the specified stmt yet.
llvm::Constant * EmitAnnotateAttr(llvm::GlobalValue *GV, const AnnotateAttr *AA, SourceLocation L)
Generate the llvm::ConstantStruct which contains the annotation information for a given GlobalValue.
void EmitOpenACCDeclare(const OpenACCDeclareDecl *D, CodeGenFunction *CGF=nullptr)
Definition CGDecl.cpp:2879
llvm::GlobalValue::LinkageTypes getLLVMLinkageForDeclarator(const DeclaratorDecl *D, GVALinkage Linkage)
Returns LLVM linkage for a declarator.
TBAAAccessInfo mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo, TBAAAccessInfo SrcInfo)
mergeTBAAInfoForMemoryTransfer - Get merged TBAA information for the purposes of memory transfer call...
const LangOptions & getLangOpts() const
CGCUDARuntime & getCUDARuntime()
Return a reference to the configured CUDA runtime.
llvm::Constant * EmitAnnotationLineNo(SourceLocation L)
Emit the annotation line number.
QualType getObjCFastEnumerationStateType()
Retrieve the record type that describes the state of an Objective-C fast enumeration loop (for....
CharUnits getNaturalTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, bool forPointeeType=false)
bool shouldMapVisibilityToDLLExport(const NamedDecl *D) const
CGOpenCLRuntime & getOpenCLRuntime()
Return a reference to the configured OpenCL runtime.
const std::string & getModuleNameHash() const
const TargetInfo & getTarget() const
bool shouldEmitRTTI(bool ForEH=false)
void EmitGlobal(GlobalDecl D)
Emit code for a single global function or var decl.
llvm::Metadata * CreateMetadataIdentifierForType(QualType T)
Create a metadata identifier for the given type.
void addUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.used metadata.
void createIndirectFunctionTypeMD(const FunctionDecl *FD, llvm::Function *F)
Create and attach type metadata if the function is a potential indirect call target to support call g...
void AppendLinkerOptions(StringRef Opts)
Appends Opts to the "llvm.linker.options" metadata value.
void createCalleeTypeMetadataForIcall(const QualType &QT, llvm::CallBase *CB)
Create and attach type metadata to the given call.
void EmitExternalDeclaration(const DeclaratorDecl *D)
void AddDependentLib(StringRef Lib)
Appends a dependent lib to the appropriate metadata value.
void Release()
Finalize LLVM code generation.
ProfileList::ExclusionType isFunctionBlockedByProfileList(llvm::Function *Fn, SourceLocation Loc) const
llvm::MDNode * getTBAABaseTypeInfo(QualType QTy)
getTBAABaseTypeInfo - Get metadata that describes the given base access type.
bool lookupRepresentativeDecl(StringRef MangledName, GlobalDecl &Result) const
void EmitOMPAllocateDecl(const OMPAllocateDecl *D)
Emit a code for the allocate directive.
Definition CGDecl.cpp:2893
void setGlobalVisibility(llvm::GlobalValue *GV, const NamedDecl *D) const
Set the visibility for the given LLVM GlobalValue.
llvm::GlobalValue::LinkageTypes getLLVMLinkageVarDefinition(const VarDecl *VD)
Returns LLVM linkage for a declarator.
bool HasHiddenLTOVisibility(const CXXRecordDecl *RD)
Returns whether the given record has hidden LTO visibility and therefore may participate in (single-m...
const llvm::DataLayout & getDataLayout() const
void Error(SourceLocation loc, StringRef error)
Emit a general error that something can't be done.
TBAAAccessInfo getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType)
getTBAAVTablePtrAccessInfo - Get the TBAA information that describes an access to a virtual table poi...
ConstantAddress GetWeakRefReference(const ValueDecl *VD)
Get a reference to the target of VD.
llvm::Constant * GetFunctionStart(const ValueDecl *Decl)
static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V)
void EmitTentativeDefinition(const VarDecl *D)
void EmitDeferredUnusedCoverageMappings()
Emit all the deferred coverage mappings for the uninstrumented functions.
void addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.compiler.used metadata.
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
bool imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, StringRef Category=StringRef()) const
Imbue XRay attributes to a function, applying the always/never attribute lists in the process.
SanitizerMetadata * getSanitizerMetadata()
llvm::Metadata * CreateMetadataIdentifierGeneralized(QualType T)
Create a metadata identifier for the generalization of the given type.
void EmitGlobalAnnotations()
Emit all the global annotations.
CharUnits getClassPointerAlignment(const CXXRecordDecl *CD)
Returns the assumed alignment of an opaque pointer to the given class.
Definition CGClass.cpp:40
const llvm::Triple & getTriple() const
SmallVector< const CXXRecordDecl *, 0 > getMostBaseClasses(const CXXRecordDecl *RD)
Return a vector of most-base classes for RD.
void AddDeferredUnusedCoverageMapping(Decl *D)
Stored a deferred empty coverage mapping for an unused and thus uninstrumented top level declaration.
void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV)
If the declaration has internal linkage but is inside an extern "C" linkage specification,...
void DecorateInstructionWithTBAA(llvm::Instruction *Inst, TBAAAccessInfo TBAAInfo)
DecorateInstructionWithTBAA - Decorate the instruction with a TBAA tag.
llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD)
void AddGlobalDtor(llvm::Function *Dtor, int Priority=65535, bool IsDtorAttrFunc=false)
AddGlobalDtor - Add a function to the list that will be called when the module is unloaded.
llvm::Constant * CreateRuntimeVariable(llvm::Type *Ty, StringRef Name)
Create a new runtime global variable with the specified type and name.
void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info, CGCalleeInfo CalleeInfo, llvm::AttributeList &Attrs, unsigned &CallingConv, bool AttrOnCallSite, bool IsThunk)
Get the LLVM attributes and calling convention to use for a particular function type.
Definition CGCall.cpp:2404
llvm::Constant * GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, LangAS AddrSpace, const VarDecl *D, ForDefinition_t IsForDefinition=NotForDefinition)
GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, create and return an llvm...
TBAAAccessInfo getTBAAAccessInfo(QualType AccessType)
getTBAAAccessInfo - Get TBAA information that describes an access to an object of the given type.
void setFunctionLinkage(GlobalDecl GD, llvm::Function *F)
llvm::Constant * GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition=NotForDefinition)
AtomicOptions getAtomicOpts()
Get the current Atomic options.
ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal)
Return a pointer to a constant CFString object for the given string.
ProfileList::ExclusionType isFunctionBlockedFromProfileInstr(llvm::Function *Fn, SourceLocation Loc) const
void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV)
Add global annotations that are set on D, for the global GV.
void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const
Set the TLS mode for the given LLVM GlobalValue for the thread-local variable declaration D.
ConstantAddress GetAddrOfConstantStringFromLiteral(const StringLiteral *S, StringRef Name=".str")
Return a pointer to a constant array for the given string literal.
ASTContext & getContext() const
ConstantAddress GetAddrOfTemplateParamObject(const TemplateParamObjectDecl *TPO)
Get the address of a template parameter object.
void EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D)
Emit a code for threadprivate directive.
ConstantAddress GetAddrOfUnnamedGlobalConstantDecl(const UnnamedGlobalConstantDecl *GCD)
Get the address of a UnnamedGlobalConstant.
TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, TBAAAccessInfo TargetInfo)
mergeTBAAInfoForCast - Get merged TBAA information for the purposes of type casts.
llvm::Constant * GetAddrOfGlobalVar(const VarDecl *D, llvm::Type *Ty=nullptr, ForDefinition_t IsForDefinition=NotForDefinition)
Return the llvm::Constant for the address of the given global variable.
llvm::SanitizerStatReport & getSanStats()
llvm::Constant * EmitAnnotationString(StringRef Str)
Emit an annotation string.
void EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D, CodeGenFunction *CGF=nullptr)
Emit a code for declare mapper construct.
Definition CGDecl.cpp:2871
void RefreshTypeCacheForClass(const CXXRecordDecl *Class)
llvm::MDNode * getTBAATypeInfo(QualType QTy)
getTBAATypeInfo - Get metadata used to describe accesses to objects of the given type.
void EmitOMPRequiresDecl(const OMPRequiresDecl *D)
Emit a code for requires directive.
Definition CGDecl.cpp:2889
void HandleCXXStaticMemberVarInstantiation(VarDecl *VD)
Tell the consumer that this variable has been instantiated.
const TargetCodeGenInfo & getTargetCodeGenInfo()
const CodeGenOptions & getCodeGenOpts() const
StringRef getMangledName(GlobalDecl GD)
llvm::Constant * GetConstantArrayFromStringLiteral(const StringLiteral *E)
Return a constant array for the given string.
void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV)
Set attributes which are common to any form of a global definition (alias, Objective-C method,...
std::optional< CharUnits > getOMPAllocateAlignment(const VarDecl *VD)
Return the alignment specified in an allocate directive, if present.
Definition CGDecl.cpp:2944
llvm::GlobalVariable * CreateOrReplaceCXXRuntimeVariable(StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, llvm::Align Alignment)
Will return a global variable of the given type.
CharUnits getNaturalPointeeTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, TBAAAccessInfo InfoB)
mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the purposes of conditional ope...
llvm::LLVMContext & getLLVMContext()
llvm::GlobalValue * GetGlobalValue(StringRef Ref)
void GenKernelArgMetadata(llvm::Function *FN, const FunctionDecl *FD=nullptr, CodeGenFunction *CGF=nullptr)
OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument information in the program executab...
void setKCFIType(const FunctionDecl *FD, llvm::Function *F)
Set type metadata to the given function.
void maybeSetTrivialComdat(const Decl &D, llvm::GlobalObject &GO)
void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D, CodeGenFunction *CGF=nullptr)
Emit a code for declare reduction construct.
Definition CGDecl.cpp:2864
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys={})
void AddDetectMismatch(StringRef Name, StringRef Value)
Appends a detect mismatch command to the linker options.
void setDLLImportDLLExport(llvm::GlobalValue *GV, GlobalDecl D) const
llvm::Value * createOpenCLIntToSamplerConversion(const Expr *E, CodeGenFunction &CGF)
ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E, const Expr *Inner)
Returns a pointer to a global variable representing a temporary with static or thread storage duratio...
llvm::Constant * EmitNullConstant(QualType T)
Return the result of value-initializing the given type, i.e.
LangAS GetGlobalConstantAddressSpace() const
Return the AST address space of constant literal, which is used to emit the constant literal as globa...
LangAS GetGlobalVarAddressSpace(const VarDecl *D)
Return the AST address space of the underlying global variable for D, as determined by its declaratio...
void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info, llvm::Function *F, bool IsThunk)
Set the LLVM function attributes (sext, zext, etc).
void EmitOpenACCRoutine(const OpenACCRoutineDecl *D, CodeGenFunction *CGF=nullptr)
Definition CGDecl.cpp:2884
void addReplacement(StringRef Name, llvm::Constant *C)
llvm::Constant * getConstantSignedPointer(llvm::Constant *Pointer, const PointerAuthSchema &Schema, llvm::Constant *StorageAddress, GlobalDecl SchemaDecl, QualType SchemaType)
Sign a constant pointer using the given scheme, producing a constant with the same IR type.
void AddGlobalCtor(llvm::Function *Ctor, int Priority=65535, unsigned LexOrder=~0U, llvm::Constant *AssociatedData=nullptr)
AddGlobalCtor - Add a function to the list that will be called before main() runs.
llvm::Metadata * CreateMetadataIdentifierForFnType(QualType T)
Create a metadata identifier for the given function type.
void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F)
Set the LLVM function attributes which only apply to a function definition.
llvm::Metadata * CreateMetadataIdentifierForVirtualMemPtrType(QualType T)
Create a metadata identifier that is intended to be used to check virtual calls via a member function...
ConstantAddress GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *)
Return a pointer to a constant array for the given ObjCEncodeExpr node.
const GlobalDecl getMangledNameDecl(StringRef)
void ClearUnusedCoverageMapping(const Decl *D)
Remove the deferred empty coverage mapping as this declaration is actually instrumented.
void EmitTopLevelDecl(Decl *D)
Emit code for a single top level declaration.
llvm::Constant * EmitAnnotationUnit(SourceLocation Loc)
Emit the annotation's translation unit.
ConstantAddress GetAddrOfConstantCString(const std::string &Str, StringRef GlobalName=".str")
Returns a pointer to a character array containing the literal and a terminating '\0' character.
void printPostfixForExternalizedDecl(llvm::raw_ostream &OS, const Decl *D) const
Print the postfix for externalized static variable or kernels for single source offloading languages ...
void moveLazyEmissionStates(CodeGenModule *NewBuilder)
Move some lazily-emitted states to the NewBuilder.
llvm::ConstantInt * getSize(CharUnits numChars)
Emit the given number of characters as a value of type size_t.
void finalizeKCFITypes()
Emit KCFI type identifier constants and remove unused identifiers.
Per-function PGO state.
Definition CodeGenPGO.h:29
void setValueProfilingFlag(llvm::Module &M)
void setProfileVersion(llvm::Module &M)
void emitEmptyCounterMapping(const Decl *D, StringRef FuncName, llvm::GlobalValue::LinkageTypes Linkage)
Emit a coverage mapping range with a counter zero for an unused declaration.
CodeGenTBAA - This class organizes the cross-module state that is used while lowering AST types to LL...
This class organizes the cross-module state that is used while lowering AST types to LLVM types.
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
const CGFunctionInfo & arrangeCXXMethodDeclaration(const CXXMethodDecl *MD)
C++ methods have some special rules and also have implicit parameters.
Definition CGCall.cpp:374
const CGFunctionInfo & arrangeFreeFunctionType(CanQual< FunctionProtoType > Ty)
Arrange the argument and result information for a value of the given freestanding function type.
Definition CGCall.cpp:250
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition CGCall.cpp:1702
const CGFunctionInfo & arrangeBuiltinFunctionDeclaration(QualType resultType, const FunctionArgList &args)
A builtin function is a freestanding function using the default C conventions.
Definition CGCall.cpp:740
unsigned getTargetAddressSpace(QualType T) const
void RefreshTypeCacheForClass(const CXXRecordDecl *RD)
Remove stale types from the type cache when an inheritance model gets assigned to a class.
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
void UpdateCompletedType(const TagDecl *TD)
UpdateCompletedType - When we find the full definition for a TagDecl, replace the 'opaque' type we pr...
const CGFunctionInfo & arrangeGlobalDeclaration(GlobalDecl GD)
Definition CGCall.cpp:612
void EmitThunks(GlobalDecl GD)
EmitThunks - Emit the associated thunks for the given global decl.
A specialization of Address that requires the address to be an LLVM Constant.
Definition Address.h:296
static ConstantAddress invalid()
Definition Address.h:304
llvm::Constant * tryEmitForInitializer(const VarDecl &D)
Try to emit the initiaizer of the given declaration as an abstract constant.
void finalize(llvm::GlobalVariable *global)
llvm::Constant * emitAbstract(const Expr *E, QualType T)
Emit the result of the given expression as an abstract constant, asserting that it succeeded.
The standard implementation of ConstantInitBuilder used in Clang.
Organizes the cross-function state that is used while generating code coverage mapping data.
bool hasDiagnostics()
Whether or not the stats we've gathered indicate any potential problems.
void reportDiagnostics(DiagnosticsEngine &Diags, StringRef MainFile)
Report potential problems we've found to Diags.
void disableSanitizerForGlobal(llvm::GlobalVariable *GV)
TargetCodeGenInfo - This class organizes various target-specific codegeneration issues,...
Definition TargetInfo.h:49
virtual void getDependentLibraryOption(llvm::StringRef Lib, llvm::SmallString< 24 > &Opt) const
Gets the linker options necessary to link a dependent library on this platform.
Address performAddrSpaceCast(CodeGen::CodeGenFunction &CGF, Address Addr, LangAS SrcAddr, llvm::Type *DestTy, bool IsNonNull=false) const
virtual LangAS getGlobalVarAddressSpace(CodeGenModule &CGM, const VarDecl *D) const
Get target favored AST address space of a global variable for languages other than OpenCL and CUDA.
virtual void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const
setTargetAttributes - Provides a convenient hook to handle extra target-specific attributes for the g...
Definition TargetInfo.h:82
virtual LangAS getASTAllocaAddressSpace() const
Get the AST address space for alloca.
Definition TargetInfo.h:322
virtual void emitTargetMetadata(CodeGen::CodeGenModule &CGM, const llvm::MapVector< GlobalDecl, StringRef > &MangledDeclNames) const
emitTargetMetadata - Provides a convenient hook to handle extra target-specific metadata for the give...
Definition TargetInfo.h:87
virtual void emitTargetGlobals(CodeGen::CodeGenModule &CGM) const
Provides a convenient hook to handle extra target-specific globals.
Definition TargetInfo.h:92
virtual void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, llvm::SmallString< 32 > &Opt) const
Gets the linker options necessary to detect object file mismatches on this platform.
Definition TargetInfo.h:299
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3760
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3836
Stores additional source code information like skipped ranges which is required by the coverage mappi...
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
void addDecl(Decl *D)
Add the declaration D into this context.
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2373
ValueDecl * getDecl()
Definition Expr.h:1338
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition DeclBase.h:1076
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:435
T * getAttr() const
Definition DeclBase.h:573
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:546
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:593
bool isWeakImported() const
Determine whether this is a weak-imported symbol.
Definition DeclBase.cpp:870
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition DeclBase.cpp:560
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:308
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:559
SourceLocation getLocation() const
Definition DeclBase.h:439
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:431
TranslationUnitDecl * getTranslationUnitDecl()
Definition DeclBase.cpp:531
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
bool hasAttr() const
Definition DeclBase.h:577
Kind getKind() const
Definition DeclBase.h:442
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:780
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:232
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition Diagnostic.h:905
This represents one expression.
Definition Expr.h:112
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
QualType getType() const
Definition Expr.h:144
Represents a member of a struct/union/class.
Definition Decl.h:3160
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition Decl.cpp:4694
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Definition FileEntry.h:57
StringRef getName() const
The name of this FileEntry.
Definition FileEntry.h:61
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h: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:3718
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:3273
bool isImmediateFunction() const
Definition Decl.cpp:3334
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3756
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:3700
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:4258
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:3520
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:3722
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition Decl.cpp:3696
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4411
bool doesDeclarationForceExternallyVisibleDefinition() const
For a function declaration in C or C++, determine whether this declaration causes the definition to b...
Definition Decl.cpp:3935
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
Definition Decl.cpp:3704
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3820
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3193
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:3240
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:3682
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:3119
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4832
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5254
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4450
CallingConv getCallConv() const
Definition TypeBase.h:4805
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:57
GlobalDecl getWithMultiVersionIndex(unsigned Index)
Definition GlobalDecl.h:192
CXXCtorType getCtorType() const
Definition GlobalDecl.h:108
GlobalDecl getWithKernelReferenceKind(KernelReferenceKind Kind)
Definition GlobalDecl.h:203
GlobalDecl getCanonicalDecl() const
Definition GlobalDecl.h:97
KernelReferenceKind getKernelReferenceKind() const
Definition GlobalDecl.h:135
GlobalDecl getWithDecl(const Decl *D)
Definition GlobalDecl.h:172
unsigned getMultiVersionIndex() const
Definition GlobalDecl.h:125
CXXDtorType getDtorType() const
Definition GlobalDecl.h:113
const Decl * getDecl() const
Definition GlobalDecl.h:106
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
@ Swift5_0
Interoperability with the Swift 5.0 runtime.
@ Swift
Interoperability with the latest known version of the Swift runtime.
@ Swift4_2
Interoperability with the Swift 4.2 runtime.
@ Swift4_1
Interoperability with the Swift 4.1 runtime.
@ Protected
Override the IR-gen assigned visibility with protected visibility.
@ Default
Override the IR-gen assigned visibility with default visibility.
@ Hidden
Override the IR-gen assigned visibility with hidden visibility.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
clang::ObjCRuntime ObjCRuntime
CoreFoundationABI CFRuntime
std::string CUID
The user provided compilation unit ID, if non-empty.
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Visibility getVisibility() const
Definition Visibility.h:89
void setLinkage(Linkage L)
Definition Visibility.h:92
Linkage getLinkage() const
Definition Visibility.h:88
bool isVisibilityExplicit() const
Definition Visibility.h:90
LinkageSpecLanguageIDs getLanguage() const
Return the language specified by this linkage specification.
Definition DeclCXX.h:3038
A global _GUID constant.
Definition DeclCXX.h:4398
Parts getParts() const
Get the decomposed parts of this declaration.
Definition DeclCXX.h:4428
APValue & getAsAPValue() const
Get the value of this MSGuidDecl as an APValue.
Definition DeclCXX.cpp:3761
MSGuidDeclParts Parts
Definition DeclCXX.h:4400
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition Mangle.h:52
void mangleBlock(const DeclContext *DC, const BlockDecl *BD, raw_ostream &Out)
Definition Mangle.cpp:345
void mangleCtorBlock(const CXXConstructorDecl *CD, CXXCtorType CT, const BlockDecl *BD, raw_ostream &Out)
Definition Mangle.cpp:327
void mangleGlobalBlock(const BlockDecl *BD, const NamedDecl *ID, raw_ostream &Out)
Definition Mangle.cpp:310
bool shouldMangleDeclName(const NamedDecl *D)
Definition Mangle.cpp:121
void mangleName(GlobalDecl GD, raw_ostream &)
Definition Mangle.cpp:186
virtual void mangleCanonicalTypeName(QualType T, raw_ostream &, bool NormalizeIntegers=false)=0
Generates a unique string for an externally visible type for use with TBAA or type uniquing.
virtual void mangleStringLiteral(const StringLiteral *SL, raw_ostream &)=0
ManglerKind getKind() const
Definition Mangle.h:72
virtual void needsUniqueInternalLinkageNames()
Definition Mangle.h:132
virtual void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber, raw_ostream &)=0
void mangleDtorBlock(const CXXDestructorDecl *CD, CXXDtorType DT, const BlockDecl *BD, raw_ostream &Out)
Definition Mangle.cpp:336
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4920
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4945
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4937
APValue * getOrCreateValue(bool MayCreate) const
Get the storage for the constant value of a materialized temporary of static storage duration.
Definition ExprCXX.h:4953
ValueDecl * getExtendingDecl()
Get the declaration which triggered the lifetime-extension of this temporary, if any.
Definition ExprCXX.h:4970
unsigned getManglingNumber() const
Definition ExprCXX.h:4981
Describes a module or submodule.
Definition Module.h:144
bool isInterfaceOrPartition() const
Definition Module.h:671
bool isNamedModuleUnit() const
Is this a C++20 named module unit.
Definition Module.h:676
Module * Parent
The parent of this module.
Definition Module.h:193
Module * getPrivateModuleFragment() const
Get the Private Module Fragment (sub-module) for this module, it there is one.
Definition Module.cpp:372
llvm::SmallSetVector< Module *, 2 > Imports
The set of modules imported by this module, and on which this module depends.
Definition Module.h:458
Module * getGlobalModuleFragment() const
Get the Global Module Fragment (sub-module) for this module, it there is one.
Definition Module.cpp:361
llvm::iterator_range< submodule_iterator > submodules()
Definition Module.h:838
llvm::SmallVector< LinkLibrary, 2 > LinkLibraries
The set of libraries or frameworks to link against when an entity from this module is used.
Definition Module.h:520
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition Module.h:648
bool UseExportAsModuleLinkName
Autolinking uses the framework name for linking purposes when this is false and the export_as name ot...
Definition Module.h:524
This represents a decl that may have a name.
Definition Decl.h:274
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
LinkageInfo getLinkageAndVisibility() const
Determines the linkage and visibility of this entity.
Definition Decl.cpp:1226
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1206
bool isExternallyVisible() const
Definition Decl.h:433
Represent a C++ namespace.
Definition Decl.h:592
This represents 'pragma omp threadprivate ...' directive.
Definition DeclOpenMP.h:110
ObjCEncodeExpr, used for @encode in Objective-C.
Definition ExprObjC.h:407
QualType getEncodedType() const
Definition ExprObjC.h:426
propimpl_range property_impls() const
Definition DeclObjC.h:2513
const ObjCInterfaceDecl * getClassInterface() const
Definition DeclObjC.h:2486
void addInstanceMethod(ObjCMethodDecl *method)
Definition DeclObjC.h:2490
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition DeclObjC.h:2597
init_iterator init_end()
init_end() - Retrieve an iterator past the last initializer.
Definition DeclObjC.h:2678
CXXCtorInitializer ** init_iterator
init_iterator - Iterates through the ivar initializer list.
Definition DeclObjC.h:2654
init_iterator init_begin()
init_begin() - Retrieve an iterator to the first initializer.
Definition DeclObjC.h:2669
unsigned getNumIvarInitializers() const
getNumArgs - Number of ivars which must be initialized.
Definition DeclObjC.h:2688
void setHasDestructors(bool val)
Definition DeclObjC.h:2708
void setHasNonZeroConstructors(bool val)
Definition DeclObjC.h:2703
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
ObjCIvarDecl * all_declared_ivar_begin()
all_declared_ivar_begin - return first ivar declared in this class, its extensions and its implementa...
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1952
ObjCIvarDecl * getNextIvar()
Definition DeclObjC.h:1987
static ObjCMethodDecl * Create(ASTContext &C, SourceLocation beginLoc, SourceLocation endLoc, Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo, DeclContext *contextDecl, bool isInstance=true, bool isVariadic=false, bool isPropertyAccessor=false, bool isSynthesizedAccessorStub=false, bool isImplicitlyDeclared=false, bool isDefined=false, ObjCImplementationControl impControl=ObjCImplementationControl::None, bool HasRelatedResultType=false)
Definition DeclObjC.cpp:849
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:731
ObjCMethodDecl * getGetterMethodDecl() const
Definition DeclObjC.h:901
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
Definition DeclObjC.h:838
The basic abstraction for the target Objective-C runtime.
Definition ObjCRuntime.h:28
bool hasUnwindExceptions() const
Does this runtime use zero-cost exceptions?
Kind getKind() const
Definition ObjCRuntime.h:77
@ MacOSX
'macosx' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the non-fragile AB...
Definition ObjCRuntime.h:35
@ FragileMacOSX
'macosx-fragile' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
Definition ObjCRuntime.h:40
@ GNUstep
'gnustep' is the modern non-fragile GNUstep runtime.
Definition ObjCRuntime.h:56
@ ObjFW
'objfw' is the Objective-C runtime included in ObjFW
Definition ObjCRuntime.h:59
@ iOS
'ios' is the Apple-provided NeXT-derived runtime on iOS or the iOS simulator; it is always non-fragil...
Definition ObjCRuntime.h:45
@ GCC
'gcc' is the Objective-C runtime shipped with GCC, implementing a fragile Objective-C ABI
Definition ObjCRuntime.h:53
@ WatchOS
'watchos' is a variant of iOS for Apple's watchOS.
Definition ObjCRuntime.h:49
Represents a parameter to a function.
Definition Decl.h:1790
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
PipeType - OpenCL20.
Definition TypeBase.h:8096
uint16_t getConstantDiscrimination() const
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
Represents an unpacked "presumed" location which can be presented to the user.
const char * getFilename() const
Return the presumed filename of this location.
unsigned getLine() const
Return the presumed line number of this location.
ExclusionType getDefault(llvm::driver::ProfileInstrKind Kind) const
std::optional< ExclusionType > isFunctionExcluded(StringRef FunctionName, llvm::driver::ProfileInstrKind Kind) const
bool isEmpty() const
Definition ProfileList.h:51
std::optional< ExclusionType > isFileExcluded(StringRef FileName, llvm::driver::ProfileInstrKind Kind) const
ExclusionType
Represents if an how something should be excluded from profiling.
Definition ProfileList.h:31
@ Skip
Profiling is skipped using the skipprofile attribute.
Definition ProfileList.h:35
@ Allow
Profiling is allowed.
Definition ProfileList.h:33
std::optional< ExclusionType > isLocationExcluded(SourceLocation Loc, llvm::driver::ProfileInstrKind Kind) const
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8362
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8356
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8278
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8404
bool isConstant(const ASTContext &Ctx) const
Definition TypeBase.h:1097
QualType getCanonicalType() const
Definition TypeBase.h:8330
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8372
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1179
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8351
bool isConstantStorage(const ASTContext &Ctx, bool ExcludeCtor, bool ExcludeDtor)
Definition TypeBase.h:1036
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8324
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1332
Represents a struct/union/class.
Definition Decl.h: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:5223
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:4900
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:4622
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:2173
bool hasInit() const
Definition Decl.cpp:2403
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition Decl.cpp:2265
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2262
bool hasFlexibleArrayInit(const ASTContext &Ctx) const
Whether this variable has a flexible array member initialized with one or more elements.
Definition Decl.cpp:2867
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:2882
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition Decl.cpp:2653
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2371
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition Decl.cpp:2246
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
Definition Decl.cpp:2856
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:2380
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:2784
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1358
Defines the clang::TargetInfo interface.
#define INT_MAX
Definition limits.h:50
#define UINT_MAX
Definition limits.h:64
std::unique_ptr< TargetCodeGenInfo > createARMTargetCodeGenInfo(CodeGenModule &CGM, ARMABIKind Kind)
Definition ARM.cpp:846
std::unique_ptr< TargetCodeGenInfo > createM68kTargetCodeGenInfo(CodeGenModule &CGM)
Definition M68k.cpp:53
@ AttributedType
The l-value was considered opaque, so the alignment was determined from a type, but that type was an ...
Definition CGValue.h:151
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
Definition CGValue.h:155
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
Definition CGValue.h:146
std::unique_ptr< TargetCodeGenInfo > createBPFTargetCodeGenInfo(CodeGenModule &CGM)
Definition BPF.cpp:102
std::unique_ptr< TargetCodeGenInfo > createMSP430TargetCodeGenInfo(CodeGenModule &CGM)
Definition MSP430.cpp:96
std::unique_ptr< TargetCodeGenInfo > createX86_64TargetCodeGenInfo(CodeGenModule &CGM, X86AVXABILevel AVXLevel)
Definition X86.cpp:3533
std::unique_ptr< TargetCodeGenInfo > createWebAssemblyTargetCodeGenInfo(CodeGenModule &CGM, WebAssemblyABIKind K)
std::unique_ptr< TargetCodeGenInfo > createPPC64_SVR4_TargetCodeGenInfo(CodeGenModule &CGM, PPC64_SVR4_ABIKind Kind, bool SoftFloatABI)
Definition PPC.cpp:1056
std::unique_ptr< TargetCodeGenInfo > createMIPSTargetCodeGenInfo(CodeGenModule &CGM, bool IsOS32)
Definition Mips.cpp:455
std::unique_ptr< TargetCodeGenInfo > createHexagonTargetCodeGenInfo(CodeGenModule &CGM)
Definition Hexagon.cpp:420
std::unique_ptr< TargetCodeGenInfo > createNVPTXTargetCodeGenInfo(CodeGenModule &CGM)
Definition NVPTX.cpp: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:3522
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:613
std::unique_ptr< TargetCodeGenInfo > createTCETargetCodeGenInfo(CodeGenModule &CGM)
Definition TCE.cpp:77
CGObjCRuntime * CreateGNUObjCRuntime(CodeGenModule &CGM)
Creates an instance of an Objective-C runtime class.
std::unique_ptr< TargetCodeGenInfo > createWindowsARMTargetCodeGenInfo(CodeGenModule &CGM, ARMABIKind K)
Definition ARM.cpp:851
std::unique_ptr< TargetCodeGenInfo > createAVRTargetCodeGenInfo(CodeGenModule &CGM, unsigned NPR, unsigned NRR)
Definition AVR.cpp:151
std::unique_ptr< TargetCodeGenInfo > createDirectXTargetCodeGenInfo(CodeGenModule &CGM)
Definition DirectX.cpp:108
std::unique_ptr< TargetCodeGenInfo > createARCTargetCodeGenInfo(CodeGenModule &CGM)
Definition ARC.cpp:159
std::unique_ptr< TargetCodeGenInfo > createDefaultTargetCodeGenInfo(CodeGenModule &CGM)
std::unique_ptr< TargetCodeGenInfo > createAArch64TargetCodeGenInfo(CodeGenModule &CGM, AArch64ABIKind Kind)
Definition AArch64.cpp:1368
std::unique_ptr< TargetCodeGenInfo > createSPIRVTargetCodeGenInfo(CodeGenModule &CGM)
Definition SPIR.cpp:702
std::unique_ptr< TargetCodeGenInfo > createWindowsMIPSTargetCodeGenInfo(CodeGenModule &CGM, bool IsOS32)
Definition Mips.cpp:460
std::unique_ptr< TargetCodeGenInfo > createSparcV8TargetCodeGenInfo(CodeGenModule &CGM)
Definition Sparc.cpp:415
std::unique_ptr< TargetCodeGenInfo > createVETargetCodeGenInfo(CodeGenModule &CGM)
Definition VE.cpp:69
std::unique_ptr< TargetCodeGenInfo > createCommonSPIRTargetCodeGenInfo(CodeGenModule &CGM)
Definition SPIR.cpp:697
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:1374
std::unique_ptr< TargetCodeGenInfo > createSparcV9TargetCodeGenInfo(CodeGenModule &CGM)
Definition Sparc.cpp:420
std::unique_ptr< TargetCodeGenInfo > createX86_32TargetCodeGenInfo(CodeGenModule &CGM, bool DarwinVectorABI, bool Win32StructABI, unsigned NumRegisterParameters, bool SoftFloatABI)
Definition X86.cpp:3512
std::unique_ptr< TargetCodeGenInfo > createLanaiTargetCodeGenInfo(CodeGenModule &CGM)
Definition Lanai.cpp:156
std::unique_ptr< TargetCodeGenInfo > createPPC32TargetCodeGenInfo(CodeGenModule &CGM, bool SoftFloatABI)
Definition PPC.cpp:1044
CGCUDARuntime * CreateNVCUDARuntime(CodeGenModule &CGM)
Creates an instance of a CUDA runtime class.
std::unique_ptr< TargetCodeGenInfo > createLoongArchTargetCodeGenInfo(CodeGenModule &CGM, unsigned GRLen, unsigned FLen)
std::unique_ptr< TargetCodeGenInfo > createPPC64TargetCodeGenInfo(CodeGenModule &CGM)
Definition PPC.cpp:1052
std::unique_ptr< TargetCodeGenInfo > createWinX86_64TargetCodeGenInfo(CodeGenModule &CGM, X86AVXABILevel AVXLevel)
Definition X86.cpp:3539
std::unique_ptr< TargetCodeGenInfo > createXCoreTargetCodeGenInfo(CodeGenModule &CGM)
Definition XCore.cpp:658
std::unique_ptr< TargetCodeGenInfo > createCSKYTargetCodeGenInfo(CodeGenModule &CGM, unsigned FLen)
Definition CSKY.cpp:173
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
bool LT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1242
llvm::PointerUnion< const Decl *, const Expr * > DeclTy
Definition Descriptor.h:29
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
CXXCtorType
C++ constructor types.
Definition ABI.h:24
@ Ctor_Base
Base object ctor.
Definition ABI.h:26
@ Ctor_Complete
Complete object ctor.
Definition ABI.h:25
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus
GVALinkage
A more specific kind of linkage than enum Linkage.
Definition Linkage.h:72
@ GVA_StrongODR
Definition Linkage.h:77
@ GVA_StrongExternal
Definition Linkage.h:76
@ GVA_AvailableExternally
Definition Linkage.h:74
@ GVA_DiscardableODR
Definition Linkage.h:75
@ GVA_Internal
Definition Linkage.h:73
std::string getClangVendor()
Retrieves the Clang vendor tag.
Definition Version.cpp:60
@ PCK_ExeStr
Definition PragmaKinds.h:19
@ PCK_Compiler
Definition PragmaKinds.h:18
@ PCK_Linker
Definition PragmaKinds.h:16
@ PCK_Lib
Definition PragmaKinds.h:17
@ PCK_Unknown
Definition PragmaKinds.h:15
@ PCK_User
Definition PragmaKinds.h:20
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:272
CXXABI * CreateMicrosoftCXXABI(ASTContext &Ctx)
@ AS_public
Definition Specifiers.h:124
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ CLanguageLinkage
Definition Linkage.h:64
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.