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