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