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