clang  19.0.0git
CGDebugInfo.cpp
Go to the documentation of this file.
1 //===--- CGDebugInfo.cpp - Emit Debug Information 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 debug information generation while generating code.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CGDebugInfo.h"
14 #include "CGBlocks.h"
15 #include "CGCXXABI.h"
16 #include "CGObjCRuntime.h"
17 #include "CGRecordLayout.h"
18 #include "CodeGenFunction.h"
19 #include "CodeGenModule.h"
20 #include "ConstantEmitter.h"
21 #include "TargetInfo.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/Attr.h"
24 #include "clang/AST/DeclFriend.h"
25 #include "clang/AST/DeclObjC.h"
26 #include "clang/AST/DeclTemplate.h"
27 #include "clang/AST/Expr.h"
28 #include "clang/AST/RecordLayout.h"
34 #include "clang/Basic/Version.h"
37 #include "clang/Lex/ModuleMap.h"
39 #include "llvm/ADT/DenseSet.h"
40 #include "llvm/ADT/SmallVector.h"
41 #include "llvm/ADT/StringExtras.h"
42 #include "llvm/IR/Constants.h"
43 #include "llvm/IR/DataLayout.h"
44 #include "llvm/IR/DerivedTypes.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/IR/Intrinsics.h"
47 #include "llvm/IR/Metadata.h"
48 #include "llvm/IR/Module.h"
49 #include "llvm/Support/FileSystem.h"
50 #include "llvm/Support/MD5.h"
51 #include "llvm/Support/Path.h"
52 #include "llvm/Support/SHA1.h"
53 #include "llvm/Support/SHA256.h"
54 #include "llvm/Support/TimeProfiler.h"
55 #include <optional>
56 using namespace clang;
57 using namespace clang::CodeGen;
58 
59 static uint32_t getTypeAlignIfRequired(const Type *Ty, const ASTContext &Ctx) {
60  auto TI = Ctx.getTypeInfo(Ty);
61  return TI.isAlignRequired() ? TI.Align : 0;
62 }
63 
64 static uint32_t getTypeAlignIfRequired(QualType Ty, const ASTContext &Ctx) {
65  return getTypeAlignIfRequired(Ty.getTypePtr(), Ctx);
66 }
67 
68 static uint32_t getDeclAlignIfRequired(const Decl *D, const ASTContext &Ctx) {
69  return D->hasAttr<AlignedAttr>() ? D->getMaxAlignment() : 0;
70 }
71 
73  : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
74  DebugTypeExtRefs(CGM.getCodeGenOpts().DebugTypeExtRefs),
75  DBuilder(CGM.getModule()) {
76  CreateCompileUnit();
77 }
78 
80  assert(LexicalBlockStack.empty() &&
81  "Region stack mismatch, stack not empty!");
82 }
83 
84 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
85  SourceLocation TemporaryLocation)
86  : CGF(&CGF) {
87  init(TemporaryLocation);
88 }
89 
90 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
91  bool DefaultToEmpty,
92  SourceLocation TemporaryLocation)
93  : CGF(&CGF) {
94  init(TemporaryLocation, DefaultToEmpty);
95 }
96 
97 void ApplyDebugLocation::init(SourceLocation TemporaryLocation,
98  bool DefaultToEmpty) {
99  auto *DI = CGF->getDebugInfo();
100  if (!DI) {
101  CGF = nullptr;
102  return;
103  }
104 
105  OriginalLocation = CGF->Builder.getCurrentDebugLocation();
106 
107  if (OriginalLocation && !DI->CGM.getExpressionLocationsEnabled())
108  return;
109 
110  if (TemporaryLocation.isValid()) {
111  DI->EmitLocation(CGF->Builder, TemporaryLocation);
112  return;
113  }
114 
115  if (DefaultToEmpty) {
116  CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc());
117  return;
118  }
119 
120  // Construct a location that has a valid scope, but no line info.
121  assert(!DI->LexicalBlockStack.empty());
122  CGF->Builder.SetCurrentDebugLocation(
123  llvm::DILocation::get(DI->LexicalBlockStack.back()->getContext(), 0, 0,
124  DI->LexicalBlockStack.back(), DI->getInlinedAt()));
125 }
126 
127 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E)
128  : CGF(&CGF) {
129  init(E->getExprLoc());
130 }
131 
132 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc)
133  : CGF(&CGF) {
134  if (!CGF.getDebugInfo()) {
135  this->CGF = nullptr;
136  return;
137  }
138  OriginalLocation = CGF.Builder.getCurrentDebugLocation();
139  if (Loc)
140  CGF.Builder.SetCurrentDebugLocation(std::move(Loc));
141 }
142 
144  // Query CGF so the location isn't overwritten when location updates are
145  // temporarily disabled (for C++ default function arguments)
146  if (CGF)
147  CGF->Builder.SetCurrentDebugLocation(std::move(OriginalLocation));
148 }
149 
151  GlobalDecl InlinedFn)
152  : CGF(&CGF) {
153  if (!CGF.getDebugInfo()) {
154  this->CGF = nullptr;
155  return;
156  }
157  auto &DI = *CGF.getDebugInfo();
158  SavedLocation = DI.getLocation();
159  assert((DI.getInlinedAt() ==
160  CGF.Builder.getCurrentDebugLocation()->getInlinedAt()) &&
161  "CGDebugInfo and IRBuilder are out of sync");
162 
163  DI.EmitInlineFunctionStart(CGF.Builder, InlinedFn);
164 }
165 
167  if (!CGF)
168  return;
169  auto &DI = *CGF->getDebugInfo();
171  DI.EmitLocation(CGF->Builder, SavedLocation);
172 }
173 
175  // If the new location isn't valid return.
176  if (Loc.isInvalid())
177  return;
178 
180 
181  // If we've changed files in the middle of a lexical scope go ahead
182  // and create a new lexical scope with file node if it's different
183  // from the one in the scope.
184  if (LexicalBlockStack.empty())
185  return;
186 
188  auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
189  PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
190  if (PCLoc.isInvalid() || Scope->getFile() == getOrCreateFile(CurLoc))
191  return;
192 
193  if (auto *LBF = dyn_cast<llvm::DILexicalBlockFile>(Scope)) {
194  LexicalBlockStack.pop_back();
195  LexicalBlockStack.emplace_back(DBuilder.createLexicalBlockFile(
196  LBF->getScope(), getOrCreateFile(CurLoc)));
197  } else if (isa<llvm::DILexicalBlock>(Scope) ||
198  isa<llvm::DISubprogram>(Scope)) {
199  LexicalBlockStack.pop_back();
200  LexicalBlockStack.emplace_back(
201  DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc)));
202  }
203 }
204 
205 llvm::DIScope *CGDebugInfo::getDeclContextDescriptor(const Decl *D) {
206  llvm::DIScope *Mod = getParentModuleOrNull(D);
207  return getContextDescriptor(cast<Decl>(D->getDeclContext()),
208  Mod ? Mod : TheCU);
209 }
210 
211 llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context,
212  llvm::DIScope *Default) {
213  if (!Context)
214  return Default;
215 
216  auto I = RegionMap.find(Context);
217  if (I != RegionMap.end()) {
218  llvm::Metadata *V = I->second;
219  return dyn_cast_or_null<llvm::DIScope>(V);
220  }
221 
222  // Check namespace.
223  if (const auto *NSDecl = dyn_cast<NamespaceDecl>(Context))
224  return getOrCreateNamespace(NSDecl);
225 
226  if (const auto *RDecl = dyn_cast<RecordDecl>(Context))
227  if (!RDecl->isDependentType())
228  return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
229  TheCU->getFile());
230  return Default;
231 }
232 
233 PrintingPolicy CGDebugInfo::getPrintingPolicy() const {
235 
236  // If we're emitting codeview, it's important to try to match MSVC's naming so
237  // that visualizers written for MSVC will trigger for our class names. In
238  // particular, we can't have spaces between arguments of standard templates
239  // like basic_string and vector, but we must have spaces between consecutive
240  // angle brackets that close nested template argument lists.
241  if (CGM.getCodeGenOpts().EmitCodeView) {
242  PP.MSVCFormatting = true;
243  PP.SplitTemplateClosers = true;
244  } else {
245  // For DWARF, printing rules are underspecified.
246  // SplitTemplateClosers yields better interop with GCC and GDB (PR46052).
247  PP.SplitTemplateClosers = true;
248  }
249 
250  PP.SuppressInlineNamespace = false;
251  PP.PrintCanonicalTypes = true;
252  PP.UsePreferredNames = false;
254  PP.UseEnumerators = false;
255 
256  // Apply -fdebug-prefix-map.
257  PP.Callbacks = &PrintCB;
258  return PP;
259 }
260 
261 StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
262  return internString(GetName(FD));
263 }
264 
265 StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
266  SmallString<256> MethodName;
267  llvm::raw_svector_ostream OS(MethodName);
268  OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
269  const DeclContext *DC = OMD->getDeclContext();
270  if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) {
271  OS << OID->getName();
272  } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) {
273  OS << OID->getName();
274  } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) {
275  if (OC->IsClassExtension()) {
276  OS << OC->getClassInterface()->getName();
277  } else {
278  OS << OC->getIdentifier()->getNameStart() << '('
279  << OC->getIdentifier()->getNameStart() << ')';
280  }
281  } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) {
282  OS << OCD->getClassInterface()->getName() << '(' << OCD->getName() << ')';
283  }
284  OS << ' ' << OMD->getSelector().getAsString() << ']';
285 
286  return internString(OS.str());
287 }
288 
289 StringRef CGDebugInfo::getSelectorName(Selector S) {
290  return internString(S.getAsString());
291 }
292 
293 StringRef CGDebugInfo::getClassName(const RecordDecl *RD) {
294  if (isa<ClassTemplateSpecializationDecl>(RD)) {
295  // Copy this name on the side and use its reference.
296  return internString(GetName(RD));
297  }
298 
299  // quick optimization to avoid having to intern strings that are already
300  // stored reliably elsewhere
301  if (const IdentifierInfo *II = RD->getIdentifier())
302  return II->getName();
303 
304  // The CodeView printer in LLVM wants to see the names of unnamed types
305  // because they need to have a unique identifier.
306  // These names are used to reconstruct the fully qualified type names.
307  if (CGM.getCodeGenOpts().EmitCodeView) {
308  if (const TypedefNameDecl *D = RD->getTypedefNameForAnonDecl()) {
309  assert(RD->getDeclContext() == D->getDeclContext() &&
310  "Typedef should not be in another decl context!");
311  assert(D->getDeclName().getAsIdentifierInfo() &&
312  "Typedef was not named!");
313  return D->getDeclName().getAsIdentifierInfo()->getName();
314  }
315 
316  if (CGM.getLangOpts().CPlusPlus) {
317  StringRef Name;
318 
319  ASTContext &Context = CGM.getContext();
320  if (const DeclaratorDecl *DD = Context.getDeclaratorForUnnamedTagDecl(RD))
321  // Anonymous types without a name for linkage purposes have their
322  // declarator mangled in if they have one.
323  Name = DD->getName();
324  else if (const TypedefNameDecl *TND =
326  // Anonymous types without a name for linkage purposes have their
327  // associate typedef mangled in if they have one.
328  Name = TND->getName();
329 
330  // Give lambdas a display name based on their name mangling.
331  if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
332  if (CXXRD->isLambda())
333  return internString(
335 
336  if (!Name.empty()) {
337  SmallString<256> UnnamedType("<unnamed-type-");
338  UnnamedType += Name;
339  UnnamedType += '>';
340  return internString(UnnamedType);
341  }
342  }
343  }
344 
345  return StringRef();
346 }
347 
348 std::optional<llvm::DIFile::ChecksumKind>
349 CGDebugInfo::computeChecksum(FileID FID, SmallString<64> &Checksum) const {
350  Checksum.clear();
351 
352  if (!CGM.getCodeGenOpts().EmitCodeView &&
353  CGM.getCodeGenOpts().DwarfVersion < 5)
354  return std::nullopt;
355 
357  std::optional<llvm::MemoryBufferRef> MemBuffer = SM.getBufferOrNone(FID);
358  if (!MemBuffer)
359  return std::nullopt;
360 
361  auto Data = llvm::arrayRefFromStringRef(MemBuffer->getBuffer());
362  switch (CGM.getCodeGenOpts().getDebugSrcHash()) {
364  llvm::toHex(llvm::MD5::hash(Data), /*LowerCase=*/true, Checksum);
365  return llvm::DIFile::CSK_MD5;
367  llvm::toHex(llvm::SHA1::hash(Data), /*LowerCase=*/true, Checksum);
368  return llvm::DIFile::CSK_SHA1;
370  llvm::toHex(llvm::SHA256::hash(Data), /*LowerCase=*/true, Checksum);
371  return llvm::DIFile::CSK_SHA256;
372  }
373  llvm_unreachable("Unhandled DebugSrcHashKind enum");
374 }
375 
376 std::optional<StringRef> CGDebugInfo::getSource(const SourceManager &SM,
377  FileID FID) {
378  if (!CGM.getCodeGenOpts().EmbedSource)
379  return std::nullopt;
380 
381  bool SourceInvalid = false;
382  StringRef Source = SM.getBufferData(FID, &SourceInvalid);
383 
384  if (SourceInvalid)
385  return std::nullopt;
386 
387  return Source;
388 }
389 
390 // Compute valid FID for FileName.
391 FileID ComputeValidFileID(SourceManager &SM, StringRef FileName) {
392  FileID MainFileID = SM.getMainFileID();
393  // Find the filename FileName and load it.
394  llvm::Expected<FileEntryRef> ExpectedFileRef =
395  SM.getFileManager().getFileRef(FileName);
396  if (ExpectedFileRef) {
397  MainFileID = SM.getOrCreateFileID(ExpectedFileRef.get(),
399  }
400  return MainFileID;
401 }
402 
403 llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
405  StringRef FileName;
406  FileID FID;
407  std::optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
408 
409  if (Loc.isInvalid()) {
410  if (CGM.getCodeGenOpts().SYCLUseMainFileName &&
411  CGM.getLangOpts().MacroPrefixMap.size() > 0) {
412  // When fmacro-prefix-map is used, the original source file
413  // file name is indicated by FullMainFileName instead of the CU.
414  auto &CGO = CGM.getCodeGenOpts();
415  FileName = CGO.FullMainFileName;
416  FID = ComputeValidFileID(SM, CGO.FullMainFileName);
417  } else {
418  // The DIFile used by the CU is distinct from the main source file. Call
419  // createFile() below for canonicalization if the source file was specified
420  // with an absolute path.
421  FileName = TheCU->getFile()->getFilename();
422  CSInfo = TheCU->getFile()->getChecksum();
423  }
424  } else {
425  PresumedLoc PLoc = SM.getPresumedLoc(Loc);
426  FileName = PLoc.getFilename();
427 
428  if (FileName.empty()) {
429  FileName = TheCU->getFile()->getFilename();
430  }
431  FID = PLoc.getFileID();
432  }
433 
434  // Cache the results.
435  auto It = DIFileCache.find(FileName.data());
436  if (It != DIFileCache.end()) {
437  // Verify that the information still exists.
438  if (llvm::Metadata *V = It->second)
439  return cast<llvm::DIFile>(V);
440  }
441 
442  if (SM.getFileEntryForID(SM.getMainFileID()) &&
443  CGM.getCodeGenOpts().SYCLUseMainFileName && FID.isInvalid())
444  // When an integration footer is involved, the main file is a temporary
445  // file generated by the compiler. FileName is pointing to original user
446  // source file. We use it here to properly calculate its checksum.
447  FID = ComputeValidFileID(SM, FileName);
448 
449  // Put Checksum at a scope where it will persist past the createFile call.
450  SmallString<64> Checksum;
451  if (!CSInfo) {
452  std::optional<llvm::DIFile::ChecksumKind> CSKind =
453  computeChecksum(FID, Checksum);
454  if (CSKind)
455  CSInfo.emplace(*CSKind, Checksum);
456  }
457  return createFile(FileName, CSInfo, getSource(SM, SM.getFileID(Loc)));
458 }
459 
460 llvm::DIFile *CGDebugInfo::createFile(
461  StringRef FileName,
462  std::optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo,
463  std::optional<StringRef> Source) {
464  StringRef Dir;
465  StringRef File;
466  std::string RemappedFile = remapDIPath(FileName);
467  std::string CurDir = remapDIPath(getCurrentDirname());
468  SmallString<128> DirBuf;
469  SmallString<128> FileBuf;
470  if (llvm::sys::path::is_absolute(RemappedFile)) {
471  // Strip the common prefix (if it is more than just "/" or "C:\") from
472  // current directory and FileName for a more space-efficient encoding.
473  auto FileIt = llvm::sys::path::begin(RemappedFile);
474  auto FileE = llvm::sys::path::end(RemappedFile);
475  auto CurDirIt = llvm::sys::path::begin(CurDir);
476  auto CurDirE = llvm::sys::path::end(CurDir);
477  for (; CurDirIt != CurDirE && *CurDirIt == *FileIt; ++CurDirIt, ++FileIt)
478  llvm::sys::path::append(DirBuf, *CurDirIt);
479  if (llvm::sys::path::root_path(DirBuf) == DirBuf) {
480  // Don't strip the common prefix if it is only the root ("/" or "C:\")
481  // since that would make LLVM diagnostic locations confusing.
482  Dir = {};
483  File = RemappedFile;
484  } else {
485  for (; FileIt != FileE; ++FileIt)
486  llvm::sys::path::append(FileBuf, *FileIt);
487  Dir = DirBuf;
488  File = FileBuf;
489  }
490  } else {
491  if (!llvm::sys::path::is_absolute(FileName))
492  Dir = CurDir;
493  File = RemappedFile;
494  }
495  llvm::DIFile *F = DBuilder.createFile(File, Dir, CSInfo, Source);
496  DIFileCache[FileName.data()].reset(F);
497  return F;
498 }
499 
500 std::string CGDebugInfo::remapDIPath(StringRef Path) const {
501  SmallString<256> P = Path;
502  for (auto &[From, To] : llvm::reverse(CGM.getCodeGenOpts().DebugPrefixMap))
503  if (llvm::sys::path::replace_path_prefix(P, From, To))
504  break;
505  return P.str().str();
506 }
507 
508 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
509  if (Loc.isInvalid())
510  return 0;
512  return SM.getPresumedLoc(Loc).getLine();
513 }
514 
515 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
516  // We may not want column information at all.
517  if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
518  return 0;
519 
520  // If the location is invalid then use the current column.
521  if (Loc.isInvalid() && CurLoc.isInvalid())
522  return 0;
524  PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
525  return PLoc.isValid() ? PLoc.getColumn() : 0;
526 }
527 
528 StringRef CGDebugInfo::getCurrentDirname() {
529  if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
530  return CGM.getCodeGenOpts().DebugCompilationDir;
531 
532  if (!CWDName.empty())
533  return CWDName;
534  llvm::ErrorOr<std::string> CWD =
535  CGM.getFileSystem()->getCurrentWorkingDirectory();
536  if (!CWD)
537  return StringRef();
538  return CWDName = internString(*CWD);
539 }
540 
541 void CGDebugInfo::CreateCompileUnit() {
542  SmallString<64> Checksum;
543  std::optional<llvm::DIFile::ChecksumKind> CSKind;
544  std::optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
545 
546  // Should we be asking the SourceManager for the main file name, instead of
547  // accepting it as an argument? This just causes the main file name to
548  // mismatch with source locations and create extra lexical scopes or
549  // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
550  // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
551  // because that's what the SourceManager says)
552 
553  // Get absolute path name.
555  auto &CGO = CGM.getCodeGenOpts();
556  const LangOptions &LO = CGM.getLangOpts();
557  std::string MainFileName = CGO.MainFileName;
558  std::string FullMainFileName = CGO.FullMainFileName;
559  if (MainFileName.empty())
560  MainFileName = "<stdin>";
561 
562  // The main file name provided via the "-main-file-name" option contains just
563  // the file name itself with no path information. This file name may have had
564  // a relative path, so we look into the actual file entry for the main
565  // file to determine the real absolute path for the file.
566  // An exception here is workflow when integration footer is involved: in that
567  // case driver passes an absolute path to the original user-provided source
568  // file, whilst main file corresponds to a temporary file generated by the
569  // compiler.
570  std::string MainFileDir;
571  if (OptionalFileEntryRef MainFile =
572  SM.getFileEntryRefForID(SM.getMainFileID())) {
573  MainFileDir = std::string(MainFile->getDir().getName());
574  FileID MainFileID = SM.getMainFileID();
575  if (!llvm::sys::path::is_absolute(MainFileName) &&
576  !CGM.getCodeGenOpts().SYCLUseMainFileName) {
577  llvm::SmallString<1024> MainFileDirSS(MainFileDir);
578  llvm::sys::path::Style Style =
580  ? (CGM.getTarget().getTriple().isOSWindows()
581  ? llvm::sys::path::Style::windows_backslash
582  : llvm::sys::path::Style::posix)
583  : llvm::sys::path::Style::native;
584  llvm::sys::path::append(MainFileDirSS, Style, MainFileName);
585  MainFileName = std::string(
586  llvm::sys::path::remove_leading_dotslash(MainFileDirSS, Style));
587  } else if (CGM.getCodeGenOpts().SYCLUseMainFileName) {
588  // When an integration footer is involved, the main file is a temporary
589  // file generated by the compiler. FullMainFileName is pointing to
590  // original user source file. We use it here to properly calculate its
591  // checksum.
592  MainFileID = ComputeValidFileID(SM, FullMainFileName);
593  // Make sure the filename points to the original user source filename.
594  MainFileName = FullMainFileName;
595  }
596  // If the main file name provided is identical to the input file name, and
597  // if the input file is a preprocessed source, use the module name for
598  // debug info. The module name comes from the name specified in the first
599  // linemarker if the input is a preprocessed source. In this case we don't
600  // know the content to compute a checksum.
601  if (MainFile->getName() == MainFileName &&
603  MainFile->getName().rsplit('.').second)
604  .isPreprocessed()) {
605  MainFileName = CGM.getModule().getName().str();
606  } else {
607  CSKind = computeChecksum(MainFileID, Checksum);
608  }
609  }
610 
611  llvm::dwarf::SourceLanguage LangTag;
612  if (LO.CPlusPlus) {
613  if (LO.ObjC)
614  LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
615  else if (CGO.DebugStrictDwarf && CGO.DwarfVersion < 5)
616  LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
617  else if (LO.CPlusPlus14)
618  LangTag = llvm::dwarf::DW_LANG_C_plus_plus_14;
619  else if (LO.CPlusPlus11)
620  LangTag = llvm::dwarf::DW_LANG_C_plus_plus_11;
621  else
622  LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
623  } else if (LO.ObjC) {
624  LangTag = llvm::dwarf::DW_LANG_ObjC;
625  } else if (LO.OpenCL && (!CGM.getCodeGenOpts().DebugStrictDwarf ||
626  CGM.getCodeGenOpts().DwarfVersion >= 5)) {
627  LangTag = llvm::dwarf::DW_LANG_OpenCL;
628  } else if (LO.RenderScript) {
629  LangTag = llvm::dwarf::DW_LANG_GOOGLE_RenderScript;
630  } else if (LO.C11 && !(CGO.DebugStrictDwarf && CGO.DwarfVersion < 5)) {
631  LangTag = llvm::dwarf::DW_LANG_C11;
632  } else if (LO.C99) {
633  LangTag = llvm::dwarf::DW_LANG_C99;
634  } else {
635  LangTag = llvm::dwarf::DW_LANG_C89;
636  }
637 
638  std::string Producer = getClangFullVersion();
639 
640  // Figure out which version of the ObjC runtime we have.
641  unsigned RuntimeVers = 0;
642  if (LO.ObjC)
643  RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
644 
645  llvm::DICompileUnit::DebugEmissionKind EmissionKind;
646  switch (DebugKind) {
647  case llvm::codegenoptions::NoDebugInfo:
648  case llvm::codegenoptions::LocTrackingOnly:
649  EmissionKind = llvm::DICompileUnit::NoDebug;
650  break;
651  case llvm::codegenoptions::DebugLineTablesOnly:
652  EmissionKind = llvm::DICompileUnit::LineTablesOnly;
653  break;
654  case llvm::codegenoptions::DebugDirectivesOnly:
655  EmissionKind = llvm::DICompileUnit::DebugDirectivesOnly;
656  break;
657  case llvm::codegenoptions::DebugInfoConstructor:
658  case llvm::codegenoptions::LimitedDebugInfo:
659  case llvm::codegenoptions::FullDebugInfo:
660  case llvm::codegenoptions::UnusedTypeInfo:
661  EmissionKind = llvm::DICompileUnit::FullDebug;
662  break;
663  }
664 
665  uint64_t DwoId = 0;
666  auto &CGOpts = CGM.getCodeGenOpts();
667  // The DIFile used by the CU is distinct from the main source
668  // file. Its directory part specifies what becomes the
669  // DW_AT_comp_dir (the compilation directory), even if the source
670  // file was specified with an absolute path.
671  // Unless an integration footer is involved, and the directory part is
672  // specified by the FileEntryRef provided by the FileID of the main source
673  // file.
674  if (CSKind)
675  CSInfo.emplace(*CSKind, Checksum);
676 
677  llvm::DIFile *CUFile =
678  DBuilder.createFile(remapDIPath(MainFileName), remapDIPath(getCurrentDirname()),
679  CSInfo, getSource(SM, SM.getMainFileID()));
680 
681  StringRef Sysroot, SDK;
682  if (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB) {
683  Sysroot = CGM.getHeaderSearchOpts().Sysroot;
684  auto B = llvm::sys::path::rbegin(Sysroot);
685  auto E = llvm::sys::path::rend(Sysroot);
686  auto It =
687  std::find_if(B, E, [](auto SDK) { return SDK.ends_with(".sdk"); });
688  if (It != E)
689  SDK = *It;
690  }
691 
692  llvm::DICompileUnit::DebugNameTableKind NameTableKind =
693  static_cast<llvm::DICompileUnit::DebugNameTableKind>(
694  CGOpts.DebugNameTable);
695  if (CGM.getTarget().getTriple().isNVPTX())
697  else if (CGM.getTarget().getTriple().getVendor() == llvm::Triple::Apple)
698  NameTableKind = llvm::DICompileUnit::DebugNameTableKind::Apple;
699 
700  // Create new compile unit.
701  TheCU = DBuilder.createCompileUnit(
702  LangTag, CUFile, CGOpts.EmitVersionIdentMetadata ? Producer : "",
703  LO.Optimize || CGOpts.PrepareForLTO || CGOpts.PrepareForThinLTO,
704  CGOpts.DwarfDebugFlags, RuntimeVers, CGOpts.SplitDwarfFile, EmissionKind,
705  DwoId, CGOpts.SplitDwarfInlining, CGOpts.DebugInfoForProfiling,
706  NameTableKind, CGOpts.DebugRangesBaseAddress, remapDIPath(Sysroot), SDK);
707 }
708 
709 llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {
710  llvm::dwarf::TypeKind Encoding;
711  StringRef BTName;
712  switch (BT->getKind()) {
713 #define BUILTIN_TYPE(Id, SingletonId)
714 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
715 #include "clang/AST/BuiltinTypes.def"
716  case BuiltinType::Dependent:
717  llvm_unreachable("Unexpected builtin type");
718  case BuiltinType::NullPtr:
719  return DBuilder.createNullPtrType();
720  case BuiltinType::Void:
721  return nullptr;
722  case BuiltinType::ObjCClass:
723  if (!ClassTy)
724  ClassTy =
725  DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
726  "objc_class", TheCU, TheCU->getFile(), 0);
727  return ClassTy;
728  case BuiltinType::ObjCId: {
729  // typedef struct objc_class *Class;
730  // typedef struct objc_object {
731  // Class isa;
732  // } *id;
733 
734  if (ObjTy)
735  return ObjTy;
736 
737  if (!ClassTy)
738  ClassTy =
739  DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
740  "objc_class", TheCU, TheCU->getFile(), 0);
741 
742  unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
743 
744  auto *ISATy = DBuilder.createPointerType(ClassTy, Size);
745 
746  ObjTy = DBuilder.createStructType(TheCU, "objc_object", TheCU->getFile(), 0,
747  0, 0, llvm::DINode::FlagZero, nullptr,
748  llvm::DINodeArray());
749 
750  DBuilder.replaceArrays(
751  ObjTy, DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
752  ObjTy, "isa", TheCU->getFile(), 0, Size, 0, 0,
753  llvm::DINode::FlagZero, ISATy)));
754  return ObjTy;
755  }
756  case BuiltinType::ObjCSel: {
757  if (!SelTy)
758  SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
759  "objc_selector", TheCU,
760  TheCU->getFile(), 0);
761  return SelTy;
762  }
763 
764 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
765  case BuiltinType::Id: \
766  return getOrCreateStructPtrType("opencl_" #ImgType "_" #Suffix "_t", \
767  SingletonId);
768 #include "clang/Basic/OpenCLImageTypes.def"
769 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
770  case BuiltinType::Sampled##Id: \
771  return getOrCreateStructPtrType( \
772  "spirv_sampled_" #ImgType "_" #Suffix "_t", Sampled##SingletonId);
773 #define IMAGE_WRITE_TYPE(Type, Id, Ext)
774 #define IMAGE_READ_WRITE_TYPE(Type, Id, Ext)
775 #include "clang/Basic/OpenCLImageTypes.def"
776  case BuiltinType::OCLSampler:
777  return getOrCreateStructPtrType("opencl_sampler_t", OCLSamplerDITy);
778  case BuiltinType::OCLEvent:
779  return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);
780  case BuiltinType::OCLClkEvent:
781  return getOrCreateStructPtrType("opencl_clk_event_t", OCLClkEventDITy);
782  case BuiltinType::OCLQueue:
783  return getOrCreateStructPtrType("opencl_queue_t", OCLQueueDITy);
784  case BuiltinType::OCLReserveID:
785  return getOrCreateStructPtrType("opencl_reserve_id_t", OCLReserveIDDITy);
786 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
787  case BuiltinType::Id: \
788  return getOrCreateStructPtrType("opencl_" #ExtType, Id##Ty);
789 #include "clang/Basic/OpenCLExtensionTypes.def"
790 
791 #define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
792 #include "clang/Basic/AArch64SVEACLETypes.def"
793  {
795  // For svcount_t, only the lower 2 bytes are relevant.
796  BT->getKind() == BuiltinType::SveCount
798  CGM.getContext().BoolTy, llvm::ElementCount::getFixed(16),
799  1)
800  : CGM.getContext().getBuiltinVectorTypeInfo(BT);
801 
802  // A single vector of bytes may not suffice as the representation of
803  // svcount_t tuples because of the gap between the active 16bits of
804  // successive tuple members. Currently no such tuples are defined for
805  // svcount_t, so assert that NumVectors is 1.
806  assert((BT->getKind() != BuiltinType::SveCount || Info.NumVectors == 1) &&
807  "Unsupported number of vectors for svcount_t");
808 
809  // Debuggers can't extract 1bit from a vector, so will display a
810  // bitpattern for predicates instead.
811  unsigned NumElems = Info.EC.getKnownMinValue() * Info.NumVectors;
812  if (Info.ElementType == CGM.getContext().BoolTy) {
813  NumElems /= 8;
815  }
816 
817  llvm::Metadata *LowerBound, *UpperBound;
818  LowerBound = llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
819  llvm::Type::getInt64Ty(CGM.getLLVMContext()), 0));
820  if (Info.EC.isScalable()) {
821  unsigned NumElemsPerVG = NumElems / 2;
823  {llvm::dwarf::DW_OP_constu, NumElemsPerVG, llvm::dwarf::DW_OP_bregx,
824  /* AArch64::VG */ 46, 0, llvm::dwarf::DW_OP_mul,
825  llvm::dwarf::DW_OP_constu, 1, llvm::dwarf::DW_OP_minus});
826  UpperBound = DBuilder.createExpression(Expr);
827  } else
828  UpperBound = llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
829  llvm::Type::getInt64Ty(CGM.getLLVMContext()), NumElems - 1));
830 
831  llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(
832  /*count*/ nullptr, LowerBound, UpperBound, /*stride*/ nullptr);
833  llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
834  llvm::DIType *ElemTy =
835  getOrCreateType(Info.ElementType, TheCU->getFile());
836  auto Align = getTypeAlignIfRequired(BT, CGM.getContext());
837  return DBuilder.createVectorType(/*Size*/ 0, Align, ElemTy,
838  SubscriptArray);
839  }
840  // It doesn't make sense to generate debug info for PowerPC MMA vector types.
841  // So we return a safe type here to avoid generating an error.
842 #define PPC_VECTOR_TYPE(Name, Id, size) \
843  case BuiltinType::Id:
844 #include "clang/Basic/PPCTypes.def"
845  return CreateType(cast<const BuiltinType>(CGM.getContext().IntTy));
846 
847 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
848 #include "clang/Basic/RISCVVTypes.def"
849  {
852 
853  unsigned ElementCount = Info.EC.getKnownMinValue();
854  unsigned SEW = CGM.getContext().getTypeSize(Info.ElementType);
855 
856  bool Fractional = false;
857  unsigned LMUL;
858  unsigned FixedSize = ElementCount * SEW;
859  if (Info.ElementType == CGM.getContext().BoolTy) {
860  // Mask type only occupies one vector register.
861  LMUL = 1;
862  } else if (FixedSize < 64) {
863  // In RVV scalable vector types, we encode 64 bits in the fixed part.
864  Fractional = true;
865  LMUL = 64 / FixedSize;
866  } else {
867  LMUL = FixedSize / 64;
868  }
869 
870  // Element count = (VLENB / SEW) x LMUL
872  // The DW_OP_bregx operation has two operands: a register which is
873  // specified by an unsigned LEB128 number, followed by a signed LEB128
874  // offset.
875  {llvm::dwarf::DW_OP_bregx, // Read the contents of a register.
876  4096 + 0xC22, // RISC-V VLENB CSR register.
877  0, // Offset for DW_OP_bregx. It is dummy here.
878  llvm::dwarf::DW_OP_constu,
879  SEW / 8, // SEW is in bits.
880  llvm::dwarf::DW_OP_div, llvm::dwarf::DW_OP_constu, LMUL});
881  if (Fractional)
882  Expr.push_back(llvm::dwarf::DW_OP_div);
883  else
884  Expr.push_back(llvm::dwarf::DW_OP_mul);
885  // Element max index = count - 1
886  Expr.append({llvm::dwarf::DW_OP_constu, 1, llvm::dwarf::DW_OP_minus});
887 
888  auto *LowerBound =
889  llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
890  llvm::Type::getInt64Ty(CGM.getLLVMContext()), 0));
891  auto *UpperBound = DBuilder.createExpression(Expr);
892  llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(
893  /*count*/ nullptr, LowerBound, UpperBound, /*stride*/ nullptr);
894  llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
895  llvm::DIType *ElemTy =
896  getOrCreateType(Info.ElementType, TheCU->getFile());
897 
898  auto Align = getTypeAlignIfRequired(BT, CGM.getContext());
899  return DBuilder.createVectorType(/*Size=*/0, Align, ElemTy,
900  SubscriptArray);
901  }
902 
903 #define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
904  case BuiltinType::Id: { \
905  if (!SingletonId) \
906  SingletonId = \
907  DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, \
908  MangledName, TheCU, TheCU->getFile(), 0); \
909  return SingletonId; \
910  }
911 #include "clang/Basic/WebAssemblyReferenceTypes.def"
912 
913  case BuiltinType::UChar:
914  case BuiltinType::Char_U:
915  Encoding = llvm::dwarf::DW_ATE_unsigned_char;
916  break;
917  case BuiltinType::Char_S:
918  case BuiltinType::SChar:
919  Encoding = llvm::dwarf::DW_ATE_signed_char;
920  break;
921  case BuiltinType::Char8:
922  case BuiltinType::Char16:
923  case BuiltinType::Char32:
924  Encoding = llvm::dwarf::DW_ATE_UTF;
925  break;
926  case BuiltinType::UShort:
927  case BuiltinType::UInt:
928  case BuiltinType::UInt128:
929  case BuiltinType::ULong:
930  case BuiltinType::WChar_U:
931  case BuiltinType::ULongLong:
932  Encoding = llvm::dwarf::DW_ATE_unsigned;
933  break;
934  case BuiltinType::Short:
935  case BuiltinType::Int:
936  case BuiltinType::Int128:
937  case BuiltinType::Long:
938  case BuiltinType::WChar_S:
939  case BuiltinType::LongLong:
940  Encoding = llvm::dwarf::DW_ATE_signed;
941  break;
942  case BuiltinType::Bool:
943  Encoding = llvm::dwarf::DW_ATE_boolean;
944  break;
945  case BuiltinType::Half:
946  case BuiltinType::Float:
947  case BuiltinType::LongDouble:
948  case BuiltinType::Float16:
949  case BuiltinType::BFloat16:
950  case BuiltinType::Float128:
951  case BuiltinType::Double:
952  case BuiltinType::Ibm128:
953  // FIXME: For targets where long double, __ibm128 and __float128 have the
954  // same size, they are currently indistinguishable in the debugger without
955  // some special treatment. However, there is currently no consensus on
956  // encoding and this should be updated once a DWARF encoding exists for
957  // distinct floating point types of the same size.
958  Encoding = llvm::dwarf::DW_ATE_float;
959  break;
960  case BuiltinType::ShortAccum:
961  case BuiltinType::Accum:
962  case BuiltinType::LongAccum:
963  case BuiltinType::ShortFract:
964  case BuiltinType::Fract:
965  case BuiltinType::LongFract:
966  case BuiltinType::SatShortFract:
967  case BuiltinType::SatFract:
968  case BuiltinType::SatLongFract:
969  case BuiltinType::SatShortAccum:
970  case BuiltinType::SatAccum:
971  case BuiltinType::SatLongAccum:
972  Encoding = llvm::dwarf::DW_ATE_signed_fixed;
973  break;
974  case BuiltinType::UShortAccum:
975  case BuiltinType::UAccum:
976  case BuiltinType::ULongAccum:
977  case BuiltinType::UShortFract:
978  case BuiltinType::UFract:
979  case BuiltinType::ULongFract:
980  case BuiltinType::SatUShortAccum:
981  case BuiltinType::SatUAccum:
982  case BuiltinType::SatULongAccum:
983  case BuiltinType::SatUShortFract:
984  case BuiltinType::SatUFract:
985  case BuiltinType::SatULongFract:
986  Encoding = llvm::dwarf::DW_ATE_unsigned_fixed;
987  break;
988  }
989 
990  BTName = BT->getName(CGM.getLangOpts());
991  // Bit size and offset of the type.
992  uint64_t Size = CGM.getContext().getTypeSize(BT);
993  return DBuilder.createBasicType(BTName, Size, Encoding);
994 }
995 
996 llvm::DIType *CGDebugInfo::CreateType(const BitIntType *Ty) {
997 
998  StringRef Name = Ty->isUnsigned() ? "unsigned _BitInt" : "_BitInt";
999  llvm::dwarf::TypeKind Encoding = Ty->isUnsigned()
1000  ? llvm::dwarf::DW_ATE_unsigned
1001  : llvm::dwarf::DW_ATE_signed;
1002 
1003  return DBuilder.createBasicType(Name, CGM.getContext().getTypeSize(Ty),
1004  Encoding);
1005 }
1006 
1007 llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) {
1008  // Bit size and offset of the type.
1009  llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
1010  if (Ty->isComplexIntegerType())
1011  Encoding = llvm::dwarf::DW_ATE_lo_user;
1012 
1013  uint64_t Size = CGM.getContext().getTypeSize(Ty);
1014  return DBuilder.createBasicType("complex", Size, Encoding);
1015 }
1016 
1018  // Ignore these qualifiers for now.
1019  Q.removeObjCGCAttr();
1020  Q.removeAddressSpace();
1021  Q.removeObjCLifetime();
1022  Q.removeUnaligned();
1023 }
1024 
1025 static llvm::dwarf::Tag getNextQualifier(Qualifiers &Q) {
1026  if (Q.hasConst()) {
1027  Q.removeConst();
1028  return llvm::dwarf::DW_TAG_const_type;
1029  }
1030  if (Q.hasVolatile()) {
1031  Q.removeVolatile();
1032  return llvm::dwarf::DW_TAG_volatile_type;
1033  }
1034  if (Q.hasRestrict()) {
1035  Q.removeRestrict();
1036  return llvm::dwarf::DW_TAG_restrict_type;
1037  }
1038  return (llvm::dwarf::Tag)0;
1039 }
1040 
1041 llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty,
1042  llvm::DIFile *Unit) {
1043  QualifierCollector Qc;
1044  const Type *T = Qc.strip(Ty);
1045 
1047 
1048  // We will create one Derived type for one qualifier and recurse to handle any
1049  // additional ones.
1050  llvm::dwarf::Tag Tag = getNextQualifier(Qc);
1051  if (!Tag) {
1052  assert(Qc.empty() && "Unknown type qualifier for debug info");
1053  return getOrCreateType(QualType(T, 0), Unit);
1054  }
1055 
1056  auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
1057 
1058  // No need to fill in the Name, Line, Size, Alignment, Offset in case of
1059  // CVR derived types.
1060  return DBuilder.createQualifiedType(Tag, FromTy);
1061 }
1062 
1063 llvm::DIType *CGDebugInfo::CreateQualifiedType(const FunctionProtoType *F,
1064  llvm::DIFile *Unit) {
1066  Qualifiers &Q = EPI.TypeQuals;
1068 
1069  // We will create one Derived type for one qualifier and recurse to handle any
1070  // additional ones.
1071  llvm::dwarf::Tag Tag = getNextQualifier(Q);
1072  if (!Tag) {
1073  assert(Q.empty() && "Unknown type qualifier for debug info");
1074  return nullptr;
1075  }
1076 
1077  auto *FromTy =
1078  getOrCreateType(CGM.getContext().getFunctionType(F->getReturnType(),
1079  F->getParamTypes(), EPI),
1080  Unit);
1081 
1082  // No need to fill in the Name, Line, Size, Alignment, Offset in case of
1083  // CVR derived types.
1084  return DBuilder.createQualifiedType(Tag, FromTy);
1085 }
1086 
1087 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
1088  llvm::DIFile *Unit) {
1089 
1090  // The frontend treats 'id' as a typedef to an ObjCObjectType,
1091  // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
1092  // debug info, we want to emit 'id' in both cases.
1093  if (Ty->isObjCQualifiedIdType())
1094  return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
1095 
1096  return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
1097  Ty->getPointeeType(), Unit);
1098 }
1099 
1100 llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty,
1101  llvm::DIFile *Unit) {
1102  return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
1103  Ty->getPointeeType(), Unit);
1104 }
1105 
1106 /// \return whether a C++ mangling exists for the type defined by TD.
1107 static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {
1108  switch (TheCU->getSourceLanguage()) {
1109  case llvm::dwarf::DW_LANG_C_plus_plus:
1110  case llvm::dwarf::DW_LANG_C_plus_plus_11:
1111  case llvm::dwarf::DW_LANG_C_plus_plus_14:
1112  return true;
1113  case llvm::dwarf::DW_LANG_ObjC_plus_plus:
1114  return isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD);
1115  default:
1116  return false;
1117  }
1118 }
1119 
1120 // Determines if the debug info for this tag declaration needs a type
1121 // identifier. The purpose of the unique identifier is to deduplicate type
1122 // information for identical types across TUs. Because of the C++ one definition
1123 // rule (ODR), it is valid to assume that the type is defined the same way in
1124 // every TU and its debug info is equivalent.
1125 //
1126 // C does not have the ODR, and it is common for codebases to contain multiple
1127 // different definitions of a struct with the same name in different TUs.
1128 // Therefore, if the type doesn't have a C++ mangling, don't give it an
1129 // identifer. Type information in C is smaller and simpler than C++ type
1130 // information, so the increase in debug info size is negligible.
1131 //
1132 // If the type is not externally visible, it should be unique to the current TU,
1133 // and should not need an identifier to participate in type deduplication.
1134 // However, when emitting CodeView, the format internally uses these
1135 // unique type name identifers for references between debug info. For example,
1136 // the method of a class in an anonymous namespace uses the identifer to refer
1137 // to its parent class. The Microsoft C++ ABI attempts to provide unique names
1138 // for such types, so when emitting CodeView, always use identifiers for C++
1139 // types. This may create problems when attempting to emit CodeView when the MS
1140 // C++ ABI is not in use.
1141 static bool needsTypeIdentifier(const TagDecl *TD, CodeGenModule &CGM,
1142  llvm::DICompileUnit *TheCU) {
1143  // We only add a type identifier for types with C++ name mangling.
1144  if (!hasCXXMangling(TD, TheCU))
1145  return false;
1146 
1147  // Externally visible types with C++ mangling need a type identifier.
1148  if (TD->isExternallyVisible())
1149  return true;
1150 
1151  // CodeView types with C++ mangling need a type identifier.
1152  if (CGM.getCodeGenOpts().EmitCodeView)
1153  return true;
1154 
1155  return false;
1156 }
1157 
1158 // Returns a unique type identifier string if one exists, or an empty string.
1160  llvm::DICompileUnit *TheCU) {
1162  const TagDecl *TD = Ty->getDecl();
1163 
1164  if (!needsTypeIdentifier(TD, CGM, TheCU))
1165  return Identifier;
1166  if (const auto *RD = dyn_cast<CXXRecordDecl>(TD))
1167  if (RD->getDefinition())
1168  if (RD->isDynamicClass() &&
1169  CGM.getVTableLinkage(RD) == llvm::GlobalValue::ExternalLinkage)
1170  return Identifier;
1171 
1172  // TODO: This is using the RTTI name. Is there a better way to get
1173  // a unique string for a type?
1174  llvm::raw_svector_ostream Out(Identifier);
1176  return Identifier;
1177 }
1178 
1179 /// \return the appropriate DWARF tag for a composite type.
1180 static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
1181  llvm::dwarf::Tag Tag;
1182  if (RD->isStruct() || RD->isInterface())
1183  Tag = llvm::dwarf::DW_TAG_structure_type;
1184  else if (RD->isUnion())
1185  Tag = llvm::dwarf::DW_TAG_union_type;
1186  else {
1187  // FIXME: This could be a struct type giving a default visibility different
1188  // than C++ class type, but needs llvm metadata changes first.
1189  assert(RD->isClass());
1190  Tag = llvm::dwarf::DW_TAG_class_type;
1191  }
1192  return Tag;
1193 }
1194 
1195 llvm::DICompositeType *
1196 CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
1197  llvm::DIScope *Ctx) {
1198  const RecordDecl *RD = Ty->getDecl();
1199  if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
1200  return cast<llvm::DICompositeType>(T);
1201  llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
1202  const unsigned Line =
1203  getLineNumber(RD->getLocation().isValid() ? RD->getLocation() : CurLoc);
1204  StringRef RDName = getClassName(RD);
1205 
1206  uint64_t Size = 0;
1207  uint32_t Align = 0;
1208 
1209  const RecordDecl *D = RD->getDefinition();
1210  if (D && D->isCompleteDefinition())
1211  Size = CGM.getContext().getTypeSize(Ty);
1212 
1213  llvm::DINode::DIFlags Flags = llvm::DINode::FlagFwdDecl;
1214 
1215  // Add flag to nontrivial forward declarations. To be consistent with MSVC,
1216  // add the flag if a record has no definition because we don't know whether
1217  // it will be trivial or not.
1218  if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1219  if (!CXXRD->hasDefinition() ||
1220  (CXXRD->hasDefinition() && !CXXRD->isTrivial()))
1221  Flags |= llvm::DINode::FlagNonTrivial;
1222 
1223  // Create the type.
1225  // Don't include a linkage name in line tables only.
1226  if (CGM.getCodeGenOpts().hasReducedDebugInfo())
1227  Identifier = getTypeIdentifier(Ty, CGM, TheCU);
1228  llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(
1229  getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align, Flags,
1230  Identifier);
1231  if (CGM.getCodeGenOpts().DebugFwdTemplateParams)
1232  if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1233  DBuilder.replaceArrays(RetTy, llvm::DINodeArray(),
1234  CollectCXXTemplateParams(TSpecial, DefUnit));
1235  ReplaceMap.emplace_back(
1236  std::piecewise_construct, std::make_tuple(Ty),
1237  std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
1238  return RetTy;
1239 }
1240 
1241 llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
1242  const Type *Ty,
1243  QualType PointeeTy,
1244  llvm::DIFile *Unit) {
1245  // Bit size, align and offset of the type.
1246  // Size is always the size of a pointer.
1247  uint64_t Size = CGM.getContext().getTypeSize(Ty);
1248  auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
1249  std::optional<unsigned> DWARFAddressSpace =
1251  CGM.getTypes().getTargetAddressSpace(PointeeTy));
1252 
1254  auto *BTFAttrTy = dyn_cast<BTFTagAttributedType>(PointeeTy);
1255  while (BTFAttrTy) {
1256  StringRef Tag = BTFAttrTy->getAttr()->getBTFTypeTag();
1257  if (!Tag.empty()) {
1258  llvm::Metadata *Ops[2] = {
1259  llvm::MDString::get(CGM.getLLVMContext(), StringRef("btf_type_tag")),
1260  llvm::MDString::get(CGM.getLLVMContext(), Tag)};
1261  Annots.insert(Annots.begin(),
1262  llvm::MDNode::get(CGM.getLLVMContext(), Ops));
1263  }
1264  BTFAttrTy = dyn_cast<BTFTagAttributedType>(BTFAttrTy->getWrappedType());
1265  }
1266 
1267  llvm::DINodeArray Annotations = nullptr;
1268  if (Annots.size() > 0)
1269  Annotations = DBuilder.getOrCreateArray(Annots);
1270 
1271  if (Tag == llvm::dwarf::DW_TAG_reference_type ||
1272  Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
1273  return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit),
1274  Size, Align, DWARFAddressSpace);
1275  else
1276  return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
1277  Align, DWARFAddressSpace, StringRef(),
1278  Annotations);
1279 }
1280 
1281 llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
1282  llvm::DIType *&Cache) {
1283  if (Cache)
1284  return Cache;
1285  Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
1286  TheCU, TheCU->getFile(), 0);
1287  unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1288  Cache = DBuilder.createPointerType(Cache, Size);
1289  return Cache;
1290 }
1291 
1292 uint64_t CGDebugInfo::collectDefaultElementTypesForBlockPointer(
1293  const BlockPointerType *Ty, llvm::DIFile *Unit, llvm::DIDerivedType *DescTy,
1294  unsigned LineNo, SmallVectorImpl<llvm::Metadata *> &EltTys) {
1295  QualType FType;
1296 
1297  // Advanced by calls to CreateMemberType in increments of FType, then
1298  // returned as the overall size of the default elements.
1299  uint64_t FieldOffset = 0;
1300 
1301  // Blocks in OpenCL have unique constraints which make the standard fields
1302  // redundant while requiring size and align fields for enqueue_kernel. See
1303  // initializeForBlockHeader in CGBlocks.cpp
1304  if (CGM.getLangOpts().OpenCL) {
1305  FType = CGM.getContext().IntTy;
1306  EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1307  EltTys.push_back(CreateMemberType(Unit, FType, "__align", &FieldOffset));
1308  } else {
1309  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1310  EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1311  FType = CGM.getContext().IntTy;
1312  EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1313  EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
1314  FType = CGM.getContext().getPointerType(Ty->getPointeeType());
1315  EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
1316  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1317  uint64_t FieldSize = CGM.getContext().getTypeSize(Ty);
1318  uint32_t FieldAlign = CGM.getContext().getTypeAlign(Ty);
1319  EltTys.push_back(DBuilder.createMemberType(
1320  Unit, "__descriptor", nullptr, LineNo, FieldSize, FieldAlign,
1321  FieldOffset, llvm::DINode::FlagZero, DescTy));
1322  FieldOffset += FieldSize;
1323  }
1324 
1325  return FieldOffset;
1326 }
1327 
1328 llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,
1329  llvm::DIFile *Unit) {
1331  QualType FType;
1332  uint64_t FieldOffset;
1333  llvm::DINodeArray Elements;
1334 
1335  FieldOffset = 0;
1336  FType = CGM.getContext().UnsignedLongTy;
1337  EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
1338  EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
1339 
1340  Elements = DBuilder.getOrCreateArray(EltTys);
1341  EltTys.clear();
1342 
1343  llvm::DINode::DIFlags Flags = llvm::DINode::FlagAppleBlock;
1344 
1345  auto *EltTy =
1346  DBuilder.createStructType(Unit, "__block_descriptor", nullptr, 0,
1347  FieldOffset, 0, Flags, nullptr, Elements);
1348 
1349  // Bit size, align and offset of the type.
1350  uint64_t Size = CGM.getContext().getTypeSize(Ty);
1351 
1352  auto *DescTy = DBuilder.createPointerType(EltTy, Size);
1353 
1354  FieldOffset = collectDefaultElementTypesForBlockPointer(Ty, Unit, DescTy,
1355  0, EltTys);
1356 
1357  Elements = DBuilder.getOrCreateArray(EltTys);
1358 
1359  // The __block_literal_generic structs are marked with a special
1360  // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
1361  // the debugger needs to know about. To allow type uniquing, emit
1362  // them without a name or a location.
1363  EltTy = DBuilder.createStructType(Unit, "", nullptr, 0, FieldOffset, 0,
1364  Flags, nullptr, Elements);
1365 
1366  return DBuilder.createPointerType(EltTy, Size);
1367 }
1368 
1371  assert(Ty->isTypeAlias());
1372  // TemplateSpecializationType doesn't know if its template args are
1373  // being substituted into a parameter pack. We can find out if that's
1374  // the case now by inspecting the TypeAliasTemplateDecl template
1375  // parameters. Insert Ty's template args into SpecArgs, bundling args
1376  // passed to a parameter pack into a TemplateArgument::Pack. It also
1377  // doesn't know the value of any defaulted args, so collect those now
1378  // too.
1380  ArrayRef SubstArgs = Ty->template_arguments();
1381  for (const NamedDecl *Param : TD->getTemplateParameters()->asArray()) {
1382  // If Param is a parameter pack, pack the remaining arguments.
1383  if (Param->isParameterPack()) {
1384  SpecArgs.push_back(TemplateArgument(SubstArgs));
1385  break;
1386  }
1387 
1388  // Skip defaulted args.
1389  // FIXME: Ideally, we wouldn't do this. We can read the default values
1390  // for each parameter. However, defaulted arguments which are dependent
1391  // values or dependent types can't (easily?) be resolved here.
1392  if (SubstArgs.empty()) {
1393  // If SubstArgs is now empty (we're taking from it each iteration) and
1394  // this template parameter isn't a pack, then that should mean we're
1395  // using default values for the remaining template parameters (after
1396  // which there may be an empty pack too which we will ignore).
1397  break;
1398  }
1399 
1400  // Take the next argument.
1401  SpecArgs.push_back(SubstArgs.front());
1402  SubstArgs = SubstArgs.drop_front();
1403  }
1404  return SpecArgs;
1405 }
1406 
1407 llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
1408  llvm::DIFile *Unit) {
1409  assert(Ty->isTypeAlias());
1410  llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
1411 
1412  const TemplateDecl *TD = Ty->getTemplateName().getAsTemplateDecl();
1413  if (isa<BuiltinTemplateDecl>(TD))
1414  return Src;
1415 
1416  const auto *AliasDecl = cast<TypeAliasTemplateDecl>(TD)->getTemplatedDecl();
1417  if (AliasDecl->hasAttr<NoDebugAttr>() || noSystemDebugInfo(AliasDecl, CGM))
1418  return Src;
1419 
1420  SmallString<128> NS;
1421  llvm::raw_svector_ostream OS(NS);
1422 
1423  auto PP = getPrintingPolicy();
1425 
1426  SourceLocation Loc = AliasDecl->getLocation();
1427 
1428  if (CGM.getCodeGenOpts().DebugTemplateAlias &&
1429  // FIXME: This is a workaround for the issue
1430  // https://github.com/llvm/llvm-project/issues/89774
1431  // The TemplateSpecializationType doesn't contain any instantiation
1432  // information; dependent template arguments can't be resolved. For now,
1433  // fall back to DW_TAG_typedefs for template aliases that are
1434  // instantiation dependent, e.g.:
1435  // ```
1436  // template <int>
1437  // using A = int;
1438  //
1439  // template<int I>
1440  // struct S {
1441  // using AA = A<I>; // Instantiation dependent.
1442  // AA aa;
1443  // };
1444  //
1445  // S<0> s;
1446  // ```
1447  // S::AA's underlying type A<I> is dependent on I so will be emitted as a
1448  // DW_TAG_typedef.
1450  auto ArgVector = ::GetTemplateArgs(TD, Ty);
1451  TemplateArgs Args = {TD->getTemplateParameters(), ArgVector};
1452 
1453  // FIXME: Respect DebugTemplateNameKind::Mangled, e.g. by using GetName.
1454  // Note we can't use GetName without additional work: TypeAliasTemplateDecl
1455  // doesn't have instantiation information, so
1456  // TypeAliasTemplateDecl::getNameForDiagnostic wouldn't have access to the
1457  // template args.
1458  std::string Name;
1459  llvm::raw_string_ostream OS(Name);
1460  TD->getNameForDiagnostic(OS, PP, /*Qualified=*/false);
1461  if (CGM.getCodeGenOpts().getDebugSimpleTemplateNames() !=
1462  llvm::codegenoptions::DebugTemplateNamesKind::Simple ||
1463  !HasReconstitutableArgs(Args.Args))
1464  printTemplateArgumentList(OS, Args.Args, PP);
1465 
1466  llvm::DIDerivedType *AliasTy = DBuilder.createTemplateAlias(
1467  Src, Name, getOrCreateFile(Loc), getLineNumber(Loc),
1468  getDeclContextDescriptor(AliasDecl), CollectTemplateParams(Args, Unit));
1469  return AliasTy;
1470  }
1471 
1472  // Disable PrintCanonicalTypes here because we want
1473  // the DW_AT_name to benefit from the TypePrinter's ability
1474  // to skip defaulted template arguments.
1475  //
1476  // FIXME: Once -gsimple-template-names is enabled by default
1477  // and we attach template parameters to alias template DIEs
1478  // we don't need to worry about customizing the PrintingPolicy
1479  // here anymore.
1480  PP.PrintCanonicalTypes = false;
1482  TD->getTemplateParameters());
1483  return DBuilder.createTypedef(Src, OS.str(), getOrCreateFile(Loc),
1484  getLineNumber(Loc),
1485  getDeclContextDescriptor(AliasDecl));
1486 }
1487 
1488 /// Convert an AccessSpecifier into the corresponding DINode flag.
1489 /// As an optimization, return 0 if the access specifier equals the
1490 /// default for the containing type.
1491 static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access,
1492  const RecordDecl *RD) {
1494  if (RD && RD->isClass())
1496  else if (RD && (RD->isStruct() || RD->isUnion()))
1498 
1499  if (Access == Default)
1500  return llvm::DINode::FlagZero;
1501 
1502  switch (Access) {
1503  case clang::AS_private:
1504  return llvm::DINode::FlagPrivate;
1505  case clang::AS_protected:
1506  return llvm::DINode::FlagProtected;
1507  case clang::AS_public:
1508  return llvm::DINode::FlagPublic;
1509  case clang::AS_none:
1510  return llvm::DINode::FlagZero;
1511  }
1512  llvm_unreachable("unexpected access enumerator");
1513 }
1514 
1515 llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
1516  llvm::DIFile *Unit) {
1517  llvm::DIType *Underlying =
1518  getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
1519 
1520  if (Ty->getDecl()->hasAttr<NoDebugAttr>() ||
1521  noSystemDebugInfo(Ty->getDecl(), CGM))
1522  return Underlying;
1523 
1524  // We don't set size information, but do specify where the typedef was
1525  // declared.
1527 
1528  uint32_t Align = getDeclAlignIfRequired(Ty->getDecl(), CGM.getContext());
1529  // Typedefs are derived from some other type.
1530  llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(Ty->getDecl());
1531 
1532  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1533  const DeclContext *DC = Ty->getDecl()->getDeclContext();
1534  if (isa<RecordDecl>(DC))
1535  Flags = getAccessFlag(Ty->getDecl()->getAccess(), cast<RecordDecl>(DC));
1536 
1537  return DBuilder.createTypedef(Underlying, Ty->getDecl()->getName(),
1538  getOrCreateFile(Loc), getLineNumber(Loc),
1539  getDeclContextDescriptor(Ty->getDecl()), Align,
1540  Flags, Annotations);
1541 }
1542 
1543 static unsigned getDwarfCC(CallingConv CC) {
1544  switch (CC) {
1545  case CC_C:
1546  // Avoid emitting DW_AT_calling_convention if the C convention was used.
1547  return 0;
1548 
1549  case CC_X86StdCall:
1550  return llvm::dwarf::DW_CC_BORLAND_stdcall;
1551  case CC_X86FastCall:
1552  return llvm::dwarf::DW_CC_BORLAND_msfastcall;
1553  case CC_X86ThisCall:
1554  return llvm::dwarf::DW_CC_BORLAND_thiscall;
1555  case CC_X86VectorCall:
1556  return llvm::dwarf::DW_CC_LLVM_vectorcall;
1557  case CC_X86Pascal:
1558  return llvm::dwarf::DW_CC_BORLAND_pascal;
1559  case CC_Win64:
1560  return llvm::dwarf::DW_CC_LLVM_Win64;
1561  case CC_X86_64SysV:
1562  return llvm::dwarf::DW_CC_LLVM_X86_64SysV;
1563  case CC_AAPCS:
1564  case CC_AArch64VectorCall:
1565  case CC_AArch64SVEPCS:
1566  return llvm::dwarf::DW_CC_LLVM_AAPCS;
1567  case CC_AAPCS_VFP:
1568  return llvm::dwarf::DW_CC_LLVM_AAPCS_VFP;
1569  case CC_IntelOclBicc:
1570  return llvm::dwarf::DW_CC_LLVM_IntelOclBicc;
1571  case CC_SpirFunction:
1572  return llvm::dwarf::DW_CC_LLVM_SpirFunction;
1573  case CC_OpenCLKernel:
1574  case CC_AMDGPUKernelCall:
1575  return llvm::dwarf::DW_CC_LLVM_OpenCLKernel;
1576  case CC_Swift:
1577  return llvm::dwarf::DW_CC_LLVM_Swift;
1578  case CC_SwiftAsync:
1579  return llvm::dwarf::DW_CC_LLVM_SwiftTail;
1580  case CC_PreserveMost:
1581  return llvm::dwarf::DW_CC_LLVM_PreserveMost;
1582  case CC_PreserveAll:
1583  return llvm::dwarf::DW_CC_LLVM_PreserveAll;
1584  case CC_X86RegCall:
1585  return llvm::dwarf::DW_CC_LLVM_X86RegCall;
1586  case CC_M68kRTD:
1587  return llvm::dwarf::DW_CC_LLVM_M68kRTD;
1588  case CC_PreserveNone:
1589  return llvm::dwarf::DW_CC_LLVM_PreserveNone;
1590  case CC_RISCVVectorCall:
1591  return llvm::dwarf::DW_CC_LLVM_RISCVVectorCall;
1592  }
1593  return 0;
1594 }
1595 
1596 static llvm::DINode::DIFlags getRefFlags(const FunctionProtoType *Func) {
1597  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1598  if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1599  Flags |= llvm::DINode::FlagLValueReference;
1600  if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1601  Flags |= llvm::DINode::FlagRValueReference;
1602  return Flags;
1603 }
1604 
1605 llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,
1606  llvm::DIFile *Unit) {
1607  const auto *FPT = dyn_cast<FunctionProtoType>(Ty);
1608  if (FPT) {
1609  if (llvm::DIType *QTy = CreateQualifiedType(FPT, Unit))
1610  return QTy;
1611  }
1612 
1613  // Create the type without any qualifiers
1614 
1616 
1617  // Add the result type at least.
1618  EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
1619 
1620  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1621  // Set up remainder of arguments if there is a prototype.
1622  // otherwise emit it as a variadic function.
1623  if (!FPT) {
1624  EltTys.push_back(DBuilder.createUnspecifiedParameter());
1625  } else {
1626  Flags = getRefFlags(FPT);
1627  for (const QualType &ParamType : FPT->param_types())
1628  EltTys.push_back(getOrCreateType(ParamType, Unit));
1629  if (FPT->isVariadic())
1630  EltTys.push_back(DBuilder.createUnspecifiedParameter());
1631  }
1632 
1633  llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
1634  llvm::DIType *F = DBuilder.createSubroutineType(
1635  EltTypeArray, Flags, getDwarfCC(Ty->getCallConv()));
1636  return F;
1637 }
1638 
1639 llvm::DIDerivedType *
1640 CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl,
1641  llvm::DIScope *RecordTy, const RecordDecl *RD) {
1642  StringRef Name = BitFieldDecl->getName();
1643  QualType Ty = BitFieldDecl->getType();
1644  if (BitFieldDecl->hasAttr<PreferredTypeAttr>())
1645  Ty = BitFieldDecl->getAttr<PreferredTypeAttr>()->getType();
1646  SourceLocation Loc = BitFieldDecl->getLocation();
1647  llvm::DIFile *VUnit = getOrCreateFile(Loc);
1648  llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
1649 
1650  // Get the location for the field.
1651  llvm::DIFile *File = getOrCreateFile(Loc);
1652  unsigned Line = getLineNumber(Loc);
1653 
1654  const CGBitFieldInfo &BitFieldInfo =
1655  CGM.getTypes().getCGRecordLayout(RD).getBitFieldInfo(BitFieldDecl);
1656  uint64_t SizeInBits = BitFieldInfo.Size;
1657  assert(SizeInBits > 0 && "found named 0-width bitfield");
1658  uint64_t StorageOffsetInBits =
1659  CGM.getContext().toBits(BitFieldInfo.StorageOffset);
1660  uint64_t Offset = BitFieldInfo.Offset;
1661  // The bit offsets for big endian machines are reversed for big
1662  // endian target, compensate for that as the DIDerivedType requires
1663  // un-reversed offsets.
1664  if (CGM.getDataLayout().isBigEndian())
1665  Offset = BitFieldInfo.StorageSize - BitFieldInfo.Size - Offset;
1666  uint64_t OffsetInBits = StorageOffsetInBits + Offset;
1667  llvm::DINode::DIFlags Flags = getAccessFlag(BitFieldDecl->getAccess(), RD);
1668  llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(BitFieldDecl);
1669  return DBuilder.createBitFieldMemberType(
1670  RecordTy, Name, File, Line, SizeInBits, OffsetInBits, StorageOffsetInBits,
1671  Flags, DebugType, Annotations);
1672 }
1673 
1674 llvm::DIDerivedType *CGDebugInfo::createBitFieldSeparatorIfNeeded(
1675  const FieldDecl *BitFieldDecl, const llvm::DIDerivedType *BitFieldDI,
1676  llvm::ArrayRef<llvm::Metadata *> PreviousFieldsDI, const RecordDecl *RD) {
1677 
1679  return nullptr;
1680 
1681  /*
1682  Add a *single* zero-bitfield separator between two non-zero bitfields
1683  separated by one or more zero-bitfields. This is used to distinguish between
1684  structures such the ones below, where the memory layout is the same, but how
1685  the ABI assigns fields to registers differs.
1686 
1687  struct foo {
1688  int space[4];
1689  char a : 8; // on amdgpu, passed on v4
1690  char b : 8;
1691  char x : 8;
1692  char y : 8;
1693  };
1694  struct bar {
1695  int space[4];
1696  char a : 8; // on amdgpu, passed on v4
1697  char b : 8;
1698  char : 0;
1699  char x : 8; // passed on v5
1700  char y : 8;
1701  };
1702  */
1703  if (PreviousFieldsDI.empty())
1704  return nullptr;
1705 
1706  // If we already emitted metadata for a 0-length bitfield, nothing to do here.
1707  auto *PreviousMDEntry =
1708  PreviousFieldsDI.empty() ? nullptr : PreviousFieldsDI.back();
1709  auto *PreviousMDField =
1710  dyn_cast_or_null<llvm::DIDerivedType>(PreviousMDEntry);
1711  if (!PreviousMDField || !PreviousMDField->isBitField() ||
1712  PreviousMDField->getSizeInBits() == 0)
1713  return nullptr;
1714 
1715  auto PreviousBitfield = RD->field_begin();
1716  std::advance(PreviousBitfield, BitFieldDecl->getFieldIndex() - 1);
1717 
1718  assert(PreviousBitfield->isBitField());
1719 
1720  ASTContext &Context = CGM.getContext();
1721  if (!PreviousBitfield->isZeroLengthBitField(Context))
1722  return nullptr;
1723 
1724  QualType Ty = PreviousBitfield->getType();
1725  SourceLocation Loc = PreviousBitfield->getLocation();
1726  llvm::DIFile *VUnit = getOrCreateFile(Loc);
1727  llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
1728  llvm::DIScope *RecordTy = BitFieldDI->getScope();
1729 
1730  llvm::DIFile *File = getOrCreateFile(Loc);
1731  unsigned Line = getLineNumber(Loc);
1732 
1733  uint64_t StorageOffsetInBits =
1734  cast<llvm::ConstantInt>(BitFieldDI->getStorageOffsetInBits())
1735  ->getZExtValue();
1736 
1737  llvm::DINode::DIFlags Flags =
1738  getAccessFlag(PreviousBitfield->getAccess(), RD);
1739  llvm::DINodeArray Annotations =
1740  CollectBTFDeclTagAnnotations(*PreviousBitfield);
1741  return DBuilder.createBitFieldMemberType(
1742  RecordTy, "", File, Line, 0, StorageOffsetInBits, StorageOffsetInBits,
1743  Flags, DebugType, Annotations);
1744 }
1745 
1746 llvm::DIType *CGDebugInfo::createFieldType(
1747  StringRef name, QualType type, SourceLocation loc, AccessSpecifier AS,
1748  uint64_t offsetInBits, uint32_t AlignInBits, llvm::DIFile *tunit,
1749  llvm::DIScope *scope, const RecordDecl *RD, llvm::DINodeArray Annotations) {
1750  llvm::DIType *debugType = getOrCreateType(type, tunit);
1751 
1752  // Get the location for the field.
1753  llvm::DIFile *file = getOrCreateFile(loc);
1754  const unsigned line = getLineNumber(loc.isValid() ? loc : CurLoc);
1755 
1756  uint64_t SizeInBits = 0;
1757  auto Align = AlignInBits;
1758  if (!type->isIncompleteArrayType()) {
1759  TypeInfo TI = CGM.getContext().getTypeInfo(type);
1760  SizeInBits = TI.Width;
1761  if (!Align)
1762  Align = getTypeAlignIfRequired(type, CGM.getContext());
1763  }
1764 
1765  llvm::DINode::DIFlags flags = getAccessFlag(AS, RD);
1766  return DBuilder.createMemberType(scope, name, file, line, SizeInBits, Align,
1767  offsetInBits, flags, debugType, Annotations);
1768 }
1769 
1770 void CGDebugInfo::CollectRecordLambdaFields(
1771  const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
1772  llvm::DIType *RecordTy) {
1773  // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
1774  // has the name and the location of the variable so we should iterate over
1775  // both concurrently.
1776  const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
1778  unsigned fieldno = 0;
1780  E = CXXDecl->captures_end();
1781  I != E; ++I, ++Field, ++fieldno) {
1782  const LambdaCapture &C = *I;
1783  if (C.capturesVariable()) {
1784  SourceLocation Loc = C.getLocation();
1785  assert(!Field->isBitField() && "lambdas don't have bitfield members!");
1786  ValueDecl *V = C.getCapturedVar();
1787  StringRef VName = V->getName();
1788  llvm::DIFile *VUnit = getOrCreateFile(Loc);
1789  auto Align = getDeclAlignIfRequired(V, CGM.getContext());
1790  llvm::DIType *FieldType = createFieldType(
1791  VName, Field->getType(), Loc, Field->getAccess(),
1792  layout.getFieldOffset(fieldno), Align, VUnit, RecordTy, CXXDecl);
1793  elements.push_back(FieldType);
1794  } else if (C.capturesThis()) {
1795  // TODO: Need to handle 'this' in some way by probably renaming the
1796  // this of the lambda class and having a field member of 'this' or
1797  // by using AT_object_pointer for the function and having that be
1798  // used as 'this' for semantic references.
1799  FieldDecl *f = *Field;
1800  llvm::DIFile *VUnit = getOrCreateFile(f->getLocation());
1801  QualType type = f->getType();
1802  StringRef ThisName =
1803  CGM.getCodeGenOpts().EmitCodeView ? "__this" : "this";
1804  llvm::DIType *fieldType = createFieldType(
1805  ThisName, type, f->getLocation(), f->getAccess(),
1806  layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
1807 
1808  elements.push_back(fieldType);
1809  }
1810  }
1811 }
1812 
1813 llvm::DIDerivedType *
1814 CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
1815  const RecordDecl *RD) {
1816  // Create the descriptor for the static variable, with or without
1817  // constant initializers.
1818  Var = Var->getCanonicalDecl();
1819  llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());
1820  llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);
1821 
1822  unsigned LineNumber = getLineNumber(Var->getLocation());
1823  StringRef VName = Var->getName();
1824 
1825  // FIXME: to avoid complications with type merging we should
1826  // emit the constant on the definition instead of the declaration.
1827  llvm::Constant *C = nullptr;
1828  if (Var->getInit()) {
1829  const APValue *Value = Var->evaluateValue();
1830  if (Value) {
1831  if (Value->isInt())
1832  C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
1833  if (Value->isFloat())
1834  C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
1835  }
1836  }
1837 
1838  llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD);
1839  auto Tag = CGM.getCodeGenOpts().DwarfVersion >= 5
1840  ? llvm::dwarf::DW_TAG_variable
1841  : llvm::dwarf::DW_TAG_member;
1842  auto Align = getDeclAlignIfRequired(Var, CGM.getContext());
1843  llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
1844  RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Tag, Align);
1845  StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
1846  return GV;
1847 }
1848 
1849 void CGDebugInfo::CollectRecordNormalField(
1850  const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,
1851  SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,
1852  const RecordDecl *RD) {
1853  StringRef name = field->getName();
1854  QualType type = field->getType();
1855 
1856  // Ignore unnamed fields unless they're anonymous structs/unions.
1857  if (name.empty() && !type->isRecordType())
1858  return;
1859 
1860  llvm::DIType *FieldType;
1861  if (field->isBitField()) {
1862  llvm::DIDerivedType *BitFieldType;
1863  FieldType = BitFieldType = createBitFieldType(field, RecordTy, RD);
1864  if (llvm::DIType *Separator =
1865  createBitFieldSeparatorIfNeeded(field, BitFieldType, elements, RD))
1866  elements.push_back(Separator);
1867  } else {
1868  auto Align = getDeclAlignIfRequired(field, CGM.getContext());
1869  llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(field);
1870  FieldType =
1871  createFieldType(name, type, field->getLocation(), field->getAccess(),
1872  OffsetInBits, Align, tunit, RecordTy, RD, Annotations);
1873  }
1874 
1875  elements.push_back(FieldType);
1876 }
1877 
1878 void CGDebugInfo::CollectRecordNestedType(
1879  const TypeDecl *TD, SmallVectorImpl<llvm::Metadata *> &elements) {
1880  QualType Ty = CGM.getContext().getTypeDeclType(TD);
1881  // Injected class names are not considered nested records.
1882  if (isa<InjectedClassNameType>(Ty))
1883  return;
1884  SourceLocation Loc = TD->getLocation();
1885  llvm::DIType *nestedType = getOrCreateType(Ty, getOrCreateFile(Loc));
1886  elements.push_back(nestedType);
1887 }
1888 
1889 void CGDebugInfo::CollectRecordFields(
1890  const RecordDecl *record, llvm::DIFile *tunit,
1892  llvm::DICompositeType *RecordTy) {
1893  const auto *CXXDecl = dyn_cast<CXXRecordDecl>(record);
1894 
1895  if (CXXDecl && CXXDecl->isLambda())
1896  CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
1897  else {
1898  const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
1899 
1900  // Field number for non-static fields.
1901  unsigned fieldNo = 0;
1902 
1903  // Static and non-static members should appear in the same order as
1904  // the corresponding declarations in the source program.
1905  for (const auto *I : record->decls())
1906  if (const auto *V = dyn_cast<VarDecl>(I)) {
1907  if (V->hasAttr<NoDebugAttr>() || noSystemDebugInfo(V, CGM))
1908  continue;
1909 
1910  // Skip variable template specializations when emitting CodeView. MSVC
1911  // doesn't emit them.
1912  if (CGM.getCodeGenOpts().EmitCodeView &&
1913  isa<VarTemplateSpecializationDecl>(V))
1914  continue;
1915 
1916  if (isa<VarTemplatePartialSpecializationDecl>(V))
1917  continue;
1918 
1919  // Reuse the existing static member declaration if one exists
1920  auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
1921  if (MI != StaticDataMemberCache.end()) {
1922  assert(MI->second &&
1923  "Static data member declaration should still exist");
1924  elements.push_back(MI->second);
1925  } else {
1926  auto Field = CreateRecordStaticField(V, RecordTy, record);
1927  elements.push_back(Field);
1928  }
1929  } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
1930  CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
1931  elements, RecordTy, record);
1932 
1933  // Bump field number for next field.
1934  ++fieldNo;
1935  } else if (CGM.getCodeGenOpts().EmitCodeView) {
1936  // Debug info for nested types is included in the member list only for
1937  // CodeView.
1938  if (const auto *nestedType = dyn_cast<TypeDecl>(I)) {
1939  // MSVC doesn't generate nested type for anonymous struct/union.
1940  if (isa<RecordDecl>(I) &&
1941  cast<RecordDecl>(I)->isAnonymousStructOrUnion())
1942  continue;
1943  if (!nestedType->isImplicit() &&
1944  nestedType->getDeclContext() == record)
1945  CollectRecordNestedType(nestedType, elements);
1946  }
1947  }
1948  }
1949 }
1950 
1951 llvm::DISubroutineType *
1952 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
1953  llvm::DIFile *Unit) {
1954  const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
1955  if (Method->isStatic())
1956  return cast_or_null<llvm::DISubroutineType>(
1957  getOrCreateType(QualType(Func, 0), Unit));
1958  return getOrCreateInstanceMethodType(Method->getThisType(), Func, Unit);
1959 }
1960 
1961 llvm::DISubroutineType *CGDebugInfo::getOrCreateInstanceMethodType(
1962  QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile *Unit) {
1963  FunctionProtoType::ExtProtoInfo EPI = Func->getExtProtoInfo();
1964  Qualifiers &Qc = EPI.TypeQuals;
1965  Qc.removeConst();
1966  Qc.removeVolatile();
1967  Qc.removeRestrict();
1968  Qc.removeUnaligned();
1969  // Keep the removed qualifiers in sync with
1970  // CreateQualifiedType(const FunctionPrototype*, DIFile *Unit)
1971  // On a 'real' member function type, these qualifiers are carried on the type
1972  // of the first parameter, not as separate DW_TAG_const_type (etc) decorator
1973  // tags around them. (But, in the raw function types with qualifiers, they have
1974  // to use wrapper types.)
1975 
1976  // Add "this" pointer.
1977  const auto *OriginalFunc = cast<llvm::DISubroutineType>(
1978  getOrCreateType(CGM.getContext().getFunctionType(
1979  Func->getReturnType(), Func->getParamTypes(), EPI),
1980  Unit));
1981  llvm::DITypeRefArray Args = OriginalFunc->getTypeArray();
1982  assert(Args.size() && "Invalid number of arguments!");
1983 
1985 
1986  // First element is always return type. For 'void' functions it is NULL.
1987  Elts.push_back(Args[0]);
1988 
1989  // "this" pointer is always first argument.
1990  const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
1991  if (isa<ClassTemplateSpecializationDecl>(RD)) {
1992  // Create pointer type directly in this case.
1993  const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1994  uint64_t Size = CGM.getContext().getTypeSize(ThisPtrTy);
1995  auto Align = getTypeAlignIfRequired(ThisPtrTy, CGM.getContext());
1996  llvm::DIType *PointeeType =
1997  getOrCreateType(ThisPtrTy->getPointeeType(), Unit);
1998  llvm::DIType *ThisPtrType =
1999  DBuilder.createPointerType(PointeeType, Size, Align);
2000  TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
2001  // TODO: This and the artificial type below are misleading, the
2002  // types aren't artificial the argument is, but the current
2003  // metadata doesn't represent that.
2004  ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
2005  Elts.push_back(ThisPtrType);
2006  } else {
2007  llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);
2008  TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
2009  ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
2010  Elts.push_back(ThisPtrType);
2011  }
2012 
2013  // Copy rest of the arguments.
2014  for (unsigned i = 1, e = Args.size(); i != e; ++i)
2015  Elts.push_back(Args[i]);
2016 
2017  llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
2018 
2019  return DBuilder.createSubroutineType(EltTypeArray, OriginalFunc->getFlags(),
2020  getDwarfCC(Func->getCallConv()));
2021 }
2022 
2023 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
2024 /// inside a function.
2025 static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
2026  if (const auto *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
2027  return isFunctionLocalClass(NRD);
2028  if (isa<FunctionDecl>(RD->getDeclContext()))
2029  return true;
2030  return false;
2031 }
2032 
2033 llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
2034  const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {
2035  bool IsCtorOrDtor =
2036  isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
2037 
2038  StringRef MethodName = getFunctionName(Method);
2039  llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit);
2040 
2041  // Since a single ctor/dtor corresponds to multiple functions, it doesn't
2042  // make sense to give a single ctor/dtor a linkage name.
2043  StringRef MethodLinkageName;
2044  // FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional
2045  // property to use here. It may've been intended to model "is non-external
2046  // type" but misses cases of non-function-local but non-external classes such
2047  // as those in anonymous namespaces as well as the reverse - external types
2048  // that are function local, such as those in (non-local) inline functions.
2049  if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
2050  MethodLinkageName = CGM.getMangledName(Method);
2051 
2052  // Get the location for the method.
2053  llvm::DIFile *MethodDefUnit = nullptr;
2054  unsigned MethodLine = 0;
2055  if (!Method->isImplicit()) {
2056  MethodDefUnit = getOrCreateFile(Method->getLocation());
2057  MethodLine = getLineNumber(Method->getLocation());
2058  }
2059 
2060  // Collect virtual method info.
2061  llvm::DIType *ContainingType = nullptr;
2062  unsigned VIndex = 0;
2063  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2064  llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
2065  int ThisAdjustment = 0;
2066 
2067  if (VTableContextBase::hasVtableSlot(Method)) {
2068  if (Method->isPureVirtual())
2069  SPFlags |= llvm::DISubprogram::SPFlagPureVirtual;
2070  else
2071  SPFlags |= llvm::DISubprogram::SPFlagVirtual;
2072 
2073  if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
2074  // It doesn't make sense to give a virtual destructor a vtable index,
2075  // since a single destructor has two entries in the vtable.
2076  if (!isa<CXXDestructorDecl>(Method))
2077  VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
2078  } else {
2079  // Emit MS ABI vftable information. There is only one entry for the
2080  // deleting dtor.
2081  const auto *DD = dyn_cast<CXXDestructorDecl>(Method);
2082  GlobalDecl GD = DD ? GlobalDecl(DD, Dtor_Deleting) : GlobalDecl(Method);
2085  VIndex = ML.Index;
2086 
2087  // CodeView only records the vftable offset in the class that introduces
2088  // the virtual method. This is possible because, unlike Itanium, the MS
2089  // C++ ABI does not include all virtual methods from non-primary bases in
2090  // the vtable for the most derived class. For example, if C inherits from
2091  // A and B, C's primary vftable will not include B's virtual methods.
2092  if (Method->size_overridden_methods() == 0)
2093  Flags |= llvm::DINode::FlagIntroducedVirtual;
2094 
2095  // The 'this' adjustment accounts for both the virtual and non-virtual
2096  // portions of the adjustment. Presumably the debugger only uses it when
2097  // it knows the dynamic type of an object.
2098  ThisAdjustment = CGM.getCXXABI()
2100  .getQuantity();
2101  }
2102  ContainingType = RecordTy;
2103  }
2104 
2105  if (Method->getCanonicalDecl()->isDeleted())
2106  SPFlags |= llvm::DISubprogram::SPFlagDeleted;
2107 
2108  if (Method->isNoReturn())
2109  Flags |= llvm::DINode::FlagNoReturn;
2110 
2111  if (Method->isStatic())
2112  Flags |= llvm::DINode::FlagStaticMember;
2113  if (Method->isImplicit())
2114  Flags |= llvm::DINode::FlagArtificial;
2115  Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
2116  if (const auto *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
2117  if (CXXC->isExplicit())
2118  Flags |= llvm::DINode::FlagExplicit;
2119  } else if (const auto *CXXC = dyn_cast<CXXConversionDecl>(Method)) {
2120  if (CXXC->isExplicit())
2121  Flags |= llvm::DINode::FlagExplicit;
2122  }
2123  if (Method->hasPrototype())
2124  Flags |= llvm::DINode::FlagPrototyped;
2125  if (Method->getRefQualifier() == RQ_LValue)
2126  Flags |= llvm::DINode::FlagLValueReference;
2127  if (Method->getRefQualifier() == RQ_RValue)
2128  Flags |= llvm::DINode::FlagRValueReference;
2129  if (!Method->isExternallyVisible())
2130  SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
2131  if (CGM.getLangOpts().Optimize)
2132  SPFlags |= llvm::DISubprogram::SPFlagOptimized;
2133 
2134  // In this debug mode, emit type info for a class when its constructor type
2135  // info is emitted.
2136  if (DebugKind == llvm::codegenoptions::DebugInfoConstructor)
2137  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
2138  completeUnusedClass(*CD->getParent());
2139 
2140  llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
2141  llvm::DISubprogram *SP = DBuilder.createMethod(
2142  RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
2143  MethodTy, VIndex, ThisAdjustment, ContainingType, Flags, SPFlags,
2144  TParamsArray.get());
2145 
2146  SPCache[Method->getCanonicalDecl()].reset(SP);
2147 
2148  return SP;
2149 }
2150 
2151 void CGDebugInfo::CollectCXXMemberFunctions(
2152  const CXXRecordDecl *RD, llvm::DIFile *Unit,
2153  SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
2154 
2155  // Since we want more than just the individual member decls if we
2156  // have templated functions iterate over every declaration to gather
2157  // the functions.
2158  for (const auto *I : RD->decls()) {
2159  const auto *Method = dyn_cast<CXXMethodDecl>(I);
2160  // If the member is implicit, don't add it to the member list. This avoids
2161  // the member being added to type units by LLVM, while still allowing it
2162  // to be emitted into the type declaration/reference inside the compile
2163  // unit.
2164  // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
2165  // FIXME: Handle Using(Shadow?)Decls here to create
2166  // DW_TAG_imported_declarations inside the class for base decls brought into
2167  // derived classes. GDB doesn't seem to notice/leverage these when I tried
2168  // it, so I'm not rushing to fix this. (GCC seems to produce them, if
2169  // referenced)
2170  if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>() ||
2171  noSystemDebugInfo(Method, CGM))
2172  continue;
2173 
2175  continue;
2176 
2177  // Reuse the existing member function declaration if it exists.
2178  // It may be associated with the declaration of the type & should be
2179  // reused as we're building the definition.
2180  //
2181  // This situation can arise in the vtable-based debug info reduction where
2182  // implicit members are emitted in a non-vtable TU.
2183  auto MI = SPCache.find(Method->getCanonicalDecl());
2184  EltTys.push_back(MI == SPCache.end()
2185  ? CreateCXXMemberFunction(Method, Unit, RecordTy)
2186  : static_cast<llvm::Metadata *>(MI->second));
2187  }
2188 }
2189 
2190 void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
2192  llvm::DIType *RecordTy) {
2194  CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->bases(), SeenTypes,
2195  llvm::DINode::FlagZero);
2196 
2197  // If we are generating CodeView debug info, we also need to emit records for
2198  // indirect virtual base classes.
2199  if (CGM.getCodeGenOpts().EmitCodeView) {
2200  CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->vbases(), SeenTypes,
2201  llvm::DINode::FlagIndirectVirtualBase);
2202  }
2203 }
2204 
2205 void CGDebugInfo::CollectCXXBasesAux(
2206  const CXXRecordDecl *RD, llvm::DIFile *Unit,
2207  SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy,
2210  llvm::DINode::DIFlags StartingFlags) {
2211  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2212  for (const auto &BI : Bases) {
2213  const auto *Base =
2214  cast<CXXRecordDecl>(BI.getType()->castAs<RecordType>()->getDecl());
2215  if (!SeenTypes.insert(Base).second)
2216  continue;
2217  auto *BaseTy = getOrCreateType(BI.getType(), Unit);
2218  llvm::DINode::DIFlags BFlags = StartingFlags;
2219  uint64_t BaseOffset;
2220  uint32_t VBPtrOffset = 0;
2221 
2222  if (BI.isVirtual()) {
2223  if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
2224  // virtual base offset offset is -ve. The code generator emits dwarf
2225  // expression where it expects +ve number.
2226  BaseOffset = 0 - CGM.getItaniumVTableContext()
2228  .getQuantity();
2229  } else {
2230  // In the MS ABI, store the vbtable offset, which is analogous to the
2231  // vbase offset offset in Itanium.
2232  BaseOffset =
2234  VBPtrOffset = CGM.getContext()
2235  .getASTRecordLayout(RD)
2236  .getVBPtrOffset()
2237  .getQuantity();
2238  }
2239  BFlags |= llvm::DINode::FlagVirtual;
2240  } else
2241  BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
2242  // FIXME: Inconsistent units for BaseOffset. It is in bytes when
2243  // BI->isVirtual() and bits when not.
2244 
2245  BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
2246  llvm::DIType *DTy = DBuilder.createInheritance(RecordTy, BaseTy, BaseOffset,
2247  VBPtrOffset, BFlags);
2248  EltTys.push_back(DTy);
2249  }
2250 }
2251 
2252 llvm::DINodeArray
2253 CGDebugInfo::CollectTemplateParams(std::optional<TemplateArgs> OArgs,
2254  llvm::DIFile *Unit) {
2255  if (!OArgs)
2256  return llvm::DINodeArray();
2257  TemplateArgs &Args = *OArgs;
2258  SmallVector<llvm::Metadata *, 16> TemplateParams;
2259  for (unsigned i = 0, e = Args.Args.size(); i != e; ++i) {
2260  const TemplateArgument &TA = Args.Args[i];
2261  StringRef Name;
2262  const bool defaultParameter = TA.getIsDefaulted();
2263  if (Args.TList)
2264  Name = Args.TList->getParam(i)->getName();
2265 
2266  switch (TA.getKind()) {
2267  case TemplateArgument::Type: {
2268  llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
2269  TemplateParams.push_back(DBuilder.createTemplateTypeParameter(
2270  TheCU, Name, TTy, defaultParameter));
2271 
2272  } break;
2274  llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
2275  TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2276  TheCU, Name, TTy, defaultParameter,
2277  llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
2278  } break;
2280  const ValueDecl *D = TA.getAsDecl();
2282  llvm::DIType *TTy = getOrCreateType(T, Unit);
2283  llvm::Constant *V = nullptr;
2284  // Skip retrieve the value if that template parameter has cuda device
2285  // attribute, i.e. that value is not available at the host side.
2286  if (!CGM.getLangOpts().CUDA || CGM.getLangOpts().CUDAIsDevice ||
2287  !D->hasAttr<CUDADeviceAttr>()) {
2288  // Variable pointer template parameters have a value that is the address
2289  // of the variable.
2290  if (const auto *VD = dyn_cast<VarDecl>(D))
2291  V = CGM.GetAddrOfGlobalVar(VD);
2292  // Member function pointers have special support for building them,
2293  // though this is currently unsupported in LLVM CodeGen.
2294  else if (const auto *MD = dyn_cast<CXXMethodDecl>(D);
2295  MD && MD->isImplicitObjectMemberFunction())
2297  else if (const auto *FD = dyn_cast<FunctionDecl>(D))
2298  V = CGM.GetAddrOfFunction(FD);
2299  // Member data pointers have special handling too to compute the fixed
2300  // offset within the object.
2301  else if (const auto *MPT =
2302  dyn_cast<MemberPointerType>(T.getTypePtr())) {
2303  // These five lines (& possibly the above member function pointer
2304  // handling) might be able to be refactored to use similar code in
2305  // CodeGenModule::getMemberPointerConstant
2306  uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
2307  CharUnits chars =
2308  CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
2309  V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
2310  } else if (const auto *GD = dyn_cast<MSGuidDecl>(D)) {
2311  V = CGM.GetAddrOfMSGuidDecl(GD).getPointer();
2312  } else if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
2313  if (T->isRecordType())
2315  SourceLocation(), TPO->getValue(), TPO->getType());
2316  else
2318  }
2319  assert(V && "Failed to find template parameter pointer");
2320  V = V->stripPointerCasts();
2321  }
2322  TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2323  TheCU, Name, TTy, defaultParameter, cast_or_null<llvm::Constant>(V)));
2324  } break;
2326  QualType T = TA.getNullPtrType();
2327  llvm::DIType *TTy = getOrCreateType(T, Unit);
2328  llvm::Constant *V = nullptr;
2329  // Special case member data pointer null values since they're actually -1
2330  // instead of zero.
2331  if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr()))
2332  // But treat member function pointers as simple zero integers because
2333  // it's easier than having a special case in LLVM's CodeGen. If LLVM
2334  // CodeGen grows handling for values of non-null member function
2335  // pointers then perhaps we could remove this special case and rely on
2336  // EmitNullMemberPointer for member function pointers.
2337  if (MPT->isMemberDataPointer())
2338  V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
2339  if (!V)
2340  V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
2341  TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2342  TheCU, Name, TTy, defaultParameter, V));
2343  } break;
2346  llvm::DIType *TTy = getOrCreateType(T, Unit);
2347  llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(
2349  TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2350  TheCU, Name, TTy, defaultParameter, V));
2351  } break;
2353  std::string QualName;
2354  llvm::raw_string_ostream OS(QualName);
2356  OS, getPrintingPolicy());
2357  TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
2358  TheCU, Name, nullptr, OS.str(), defaultParameter));
2359  break;
2360  }
2362  TemplateParams.push_back(DBuilder.createTemplateParameterPack(
2363  TheCU, Name, nullptr,
2364  CollectTemplateParams({{nullptr, TA.getPackAsArray()}}, Unit)));
2365  break;
2367  const Expr *E = TA.getAsExpr();
2368  QualType T = E->getType();
2369  if (E->isGLValue())
2371  llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(E, T);
2372  assert(V && "Expression in template argument isn't constant");
2373  llvm::DIType *TTy = getOrCreateType(T, Unit);
2374  TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2375  TheCU, Name, TTy, defaultParameter, V->stripPointerCasts()));
2376  } break;
2377  // And the following should never occur:
2380  llvm_unreachable(
2381  "These argument types shouldn't exist in concrete types");
2382  }
2383  }
2384  return DBuilder.getOrCreateArray(TemplateParams);
2385 }
2386 
2387 std::optional<CGDebugInfo::TemplateArgs>
2388 CGDebugInfo::GetTemplateArgs(const FunctionDecl *FD) const {
2389  if (FD->getTemplatedKind() ==
2392  ->getTemplate()
2394  return {{TList, FD->getTemplateSpecializationArgs()->asArray()}};
2395  }
2396  return std::nullopt;
2397 }
2398 std::optional<CGDebugInfo::TemplateArgs>
2399 CGDebugInfo::GetTemplateArgs(const VarDecl *VD) const {
2400  // Always get the full list of parameters, not just the ones from the
2401  // specialization. A partial specialization may have fewer parameters than
2402  // there are arguments.
2403  auto *TS = dyn_cast<VarTemplateSpecializationDecl>(VD);
2404  if (!TS)
2405  return std::nullopt;
2406  VarTemplateDecl *T = TS->getSpecializedTemplate();
2407  const TemplateParameterList *TList = T->getTemplateParameters();
2408  auto TA = TS->getTemplateArgs().asArray();
2409  return {{TList, TA}};
2410 }
2411 std::optional<CGDebugInfo::TemplateArgs>
2412 CGDebugInfo::GetTemplateArgs(const RecordDecl *RD) const {
2413  if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
2414  // Always get the full list of parameters, not just the ones from the
2415  // specialization. A partial specialization may have fewer parameters than
2416  // there are arguments.
2417  TemplateParameterList *TPList =
2418  TSpecial->getSpecializedTemplate()->getTemplateParameters();
2419  const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
2420  return {{TPList, TAList.asArray()}};
2421  }
2422  return std::nullopt;
2423 }
2424 
2425 llvm::DINodeArray
2426 CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
2427  llvm::DIFile *Unit) {
2428  return CollectTemplateParams(GetTemplateArgs(FD), Unit);
2429 }
2430 
2431 llvm::DINodeArray CGDebugInfo::CollectVarTemplateParams(const VarDecl *VL,
2432  llvm::DIFile *Unit) {
2433  return CollectTemplateParams(GetTemplateArgs(VL), Unit);
2434 }
2435 
2436 llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(const RecordDecl *RD,
2437  llvm::DIFile *Unit) {
2438  return CollectTemplateParams(GetTemplateArgs(RD), Unit);
2439 }
2440 
2441 llvm::DINodeArray CGDebugInfo::CollectBTFDeclTagAnnotations(const Decl *D) {
2442  if (!D->hasAttr<BTFDeclTagAttr>())
2443  return nullptr;
2444 
2446  for (const auto *I : D->specific_attrs<BTFDeclTagAttr>()) {
2447  llvm::Metadata *Ops[2] = {
2448  llvm::MDString::get(CGM.getLLVMContext(), StringRef("btf_decl_tag")),
2449  llvm::MDString::get(CGM.getLLVMContext(), I->getBTFDeclTag())};
2450  Annotations.push_back(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2451  }
2452  return DBuilder.getOrCreateArray(Annotations);
2453 }
2454 
2455 llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
2456  if (VTablePtrType)
2457  return VTablePtrType;
2458 
2459  ASTContext &Context = CGM.getContext();
2460 
2461  /* Function type */
2462  llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
2463  llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);
2464  llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements);
2465  unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
2466  unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
2467  std::optional<unsigned> DWARFAddressSpace =
2468  CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
2469 
2470  llvm::DIType *vtbl_ptr_type = DBuilder.createPointerType(
2471  SubTy, Size, 0, DWARFAddressSpace, "__vtbl_ptr_type");
2472  VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
2473  return VTablePtrType;
2474 }
2475 
2476 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
2477  // Copy the gdb compatible name on the side and use its reference.
2478  return internString("_vptr$", RD->getNameAsString());
2479 }
2480 
2481 StringRef CGDebugInfo::getDynamicInitializerName(const VarDecl *VD,
2482  DynamicInitKind StubKind,
2483  llvm::Function *InitFn) {
2484  // If we're not emitting codeview, use the mangled name. For Itanium, this is
2485  // arbitrary.
2486  if (!CGM.getCodeGenOpts().EmitCodeView ||
2488  return InitFn->getName();
2489 
2490  // Print the normal qualified name for the variable, then break off the last
2491  // NNS, and add the appropriate other text. Clang always prints the global
2492  // variable name without template arguments, so we can use rsplit("::") and
2493  // then recombine the pieces.
2494  SmallString<128> QualifiedGV;
2495  StringRef Quals;
2496  StringRef GVName;
2497  {
2498  llvm::raw_svector_ostream OS(QualifiedGV);
2499  VD->printQualifiedName(OS, getPrintingPolicy());
2500  std::tie(Quals, GVName) = OS.str().rsplit("::");
2501  if (GVName.empty())
2502  std::swap(Quals, GVName);
2503  }
2504 
2505  SmallString<128> InitName;
2506  llvm::raw_svector_ostream OS(InitName);
2507  if (!Quals.empty())
2508  OS << Quals << "::";
2509 
2510  switch (StubKind) {
2513  llvm_unreachable("not an initializer");
2515  OS << "`dynamic initializer for '";
2516  break;
2518  OS << "`dynamic atexit destructor for '";
2519  break;
2520  }
2521 
2522  OS << GVName;
2523 
2524  // Add any template specialization args.
2525  if (const auto *VTpl = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
2526  printTemplateArgumentList(OS, VTpl->getTemplateArgs().asArray(),
2527  getPrintingPolicy());
2528  }
2529 
2530  OS << '\'';
2531 
2532  return internString(OS.str());
2533 }
2534 
2535 void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
2537  // If this class is not dynamic then there is not any vtable info to collect.
2538  if (!RD->isDynamicClass())
2539  return;
2540 
2541  // Don't emit any vtable shape or vptr info if this class doesn't have an
2542  // extendable vfptr. This can happen if the class doesn't have virtual
2543  // methods, or in the MS ABI if those virtual methods only come from virtually
2544  // inherited bases.
2545  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2546  if (!RL.hasExtendableVFPtr())
2547  return;
2548 
2549  // CodeView needs to know how large the vtable of every dynamic class is, so
2550  // emit a special named pointer type into the element list. The vptr type
2551  // points to this type as well.
2552  llvm::DIType *VPtrTy = nullptr;
2553  bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView &&
2554  CGM.getTarget().getCXXABI().isMicrosoft();
2555  if (NeedVTableShape) {
2556  uint64_t PtrWidth =
2558  const VTableLayout &VFTLayout =
2560  unsigned VSlotCount =
2561  VFTLayout.vtable_components().size() - CGM.getLangOpts().RTTIData;
2562  unsigned VTableWidth = PtrWidth * VSlotCount;
2563  unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
2564  std::optional<unsigned> DWARFAddressSpace =
2565  CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
2566 
2567  // Create a very wide void* type and insert it directly in the element list.
2568  llvm::DIType *VTableType = DBuilder.createPointerType(
2569  nullptr, VTableWidth, 0, DWARFAddressSpace, "__vtbl_ptr_type");
2570  EltTys.push_back(VTableType);
2571 
2572  // The vptr is a pointer to this special vtable type.
2573  VPtrTy = DBuilder.createPointerType(VTableType, PtrWidth);
2574  }
2575 
2576  // If there is a primary base then the artificial vptr member lives there.
2577  if (RL.getPrimaryBase())
2578  return;
2579 
2580  if (!VPtrTy)
2581  VPtrTy = getOrCreateVTablePtrType(Unit);
2582 
2583  unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
2584  llvm::DIType *VPtrMember =
2585  DBuilder.createMemberType(Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
2586  llvm::DINode::FlagArtificial, VPtrTy);
2587  EltTys.push_back(VPtrMember);
2588 }
2589 
2591  SourceLocation Loc) {
2592  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
2593  llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
2594  return T;
2595 }
2596 
2598  SourceLocation Loc) {
2599  return getOrCreateStandaloneType(D, Loc);
2600 }
2601 
2603  SourceLocation Loc) {
2604  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
2605  assert(!D.isNull() && "null type");
2606  llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
2607  assert(T && "could not create debug info for type");
2608 
2609  RetainedTypes.push_back(D.getAsOpaquePtr());
2610  return T;
2611 }
2612 
2614  QualType AllocatedTy,
2615  SourceLocation Loc) {
2616  if (CGM.getCodeGenOpts().getDebugInfo() <=
2617  llvm::codegenoptions::DebugLineTablesOnly)
2618  return;
2619  llvm::MDNode *node;
2620  if (AllocatedTy->isVoidType())
2621  node = llvm::MDNode::get(CGM.getLLVMContext(), std::nullopt);
2622  else
2623  node = getOrCreateType(AllocatedTy, getOrCreateFile(Loc));
2624 
2625  CI->setMetadata("heapallocsite", node);
2626 }
2627 
2629  if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
2630  return;
2631  QualType Ty = CGM.getContext().getEnumType(ED);
2632  void *TyPtr = Ty.getAsOpaquePtr();
2633  auto I = TypeCache.find(TyPtr);
2634  if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl())
2635  return;
2636  llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>());
2637  assert(!Res->isForwardDecl());
2638  TypeCache[TyPtr].reset(Res);
2639 }
2640 
2642  if (DebugKind > llvm::codegenoptions::LimitedDebugInfo ||
2643  !CGM.getLangOpts().CPlusPlus)
2645 }
2646 
2647 /// Return true if the class or any of its methods are marked dllimport.
2648 static bool isClassOrMethodDLLImport(const CXXRecordDecl *RD) {
2649  if (RD->hasAttr<DLLImportAttr>())
2650  return true;
2651  for (const CXXMethodDecl *MD : RD->methods())
2652  if (MD->hasAttr<DLLImportAttr>())
2653  return true;
2654  return false;
2655 }
2656 
2657 /// Does a type definition exist in an imported clang module?
2658 static bool isDefinedInClangModule(const RecordDecl *RD) {
2659  // Only definitions that where imported from an AST file come from a module.
2660  if (!RD || !RD->isFromASTFile())
2661  return false;
2662  // Anonymous entities cannot be addressed. Treat them as not from module.
2663  if (!RD->isExternallyVisible() && RD->getName().empty())
2664  return false;
2665  if (auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) {
2666  if (!CXXDecl->isCompleteDefinition())
2667  return false;
2668  // Check wether RD is a template.
2669  auto TemplateKind = CXXDecl->getTemplateSpecializationKind();
2670  if (TemplateKind != TSK_Undeclared) {
2671  // Unfortunately getOwningModule() isn't accurate enough to find the
2672  // owning module of a ClassTemplateSpecializationDecl that is inside a
2673  // namespace spanning multiple modules.
2674  bool Explicit = false;
2675  if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(CXXDecl))
2676  Explicit = TD->isExplicitInstantiationOrSpecialization();
2677  if (!Explicit && CXXDecl->getEnclosingNamespaceContext())
2678  return false;
2679  // This is a template, check the origin of the first member.
2680  if (CXXDecl->field_begin() == CXXDecl->field_end())
2681  return TemplateKind == TSK_ExplicitInstantiationDeclaration;
2682  if (!CXXDecl->field_begin()->isFromASTFile())
2683  return false;
2684  }
2685  }
2686  return true;
2687 }
2688 
2690  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2691  if (CXXRD->isDynamicClass() &&
2692  CGM.getVTableLinkage(CXXRD) ==
2693  llvm::GlobalValue::AvailableExternallyLinkage &&
2694  !isClassOrMethodDLLImport(CXXRD))
2695  return;
2696 
2697  if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
2698  return;
2699 
2700  completeClass(RD);
2701 }
2702 
2704  if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
2705  return;
2706  QualType Ty = CGM.getContext().getRecordType(RD);
2707  void *TyPtr = Ty.getAsOpaquePtr();
2708  auto I = TypeCache.find(TyPtr);
2709  if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl())
2710  return;
2711 
2712  // We want the canonical definition of the structure to not
2713  // be the typedef. Since that would lead to circular typedef
2714  // metadata.
2715  auto [Res, PrefRes] = CreateTypeDefinition(Ty->castAs<RecordType>());
2716  assert(!Res->isForwardDecl());
2717  TypeCache[TyPtr].reset(Res);
2718 }
2719 
2722  for (CXXMethodDecl *MD : llvm::make_range(I, End))
2724  if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
2725  !MD->getMemberSpecializationInfo()->isExplicitSpecialization())
2726  return true;
2727  return false;
2728 }
2729 
2730 static bool canUseCtorHoming(const CXXRecordDecl *RD) {
2731  // Constructor homing can be used for classes that cannnot be constructed
2732  // without emitting code for one of their constructors. This is classes that
2733  // don't have trivial or constexpr constructors, or can be created from
2734  // aggregate initialization. Also skip lambda objects because they don't call
2735  // constructors.
2736 
2737  // Skip this optimization if the class or any of its methods are marked
2738  // dllimport.
2739  if (isClassOrMethodDLLImport(RD))
2740  return false;
2741 
2742  if (RD->isLambda() || RD->isAggregate() ||
2745  return false;
2746 
2747  for (const CXXConstructorDecl *Ctor : RD->ctors()) {
2748  if (Ctor->isCopyOrMoveConstructor())
2749  continue;
2750  if (!Ctor->isDeleted())
2751  return true;
2752  }
2753  return false;
2754 }
2755 
2756 static bool shouldOmitDefinition(llvm::codegenoptions::DebugInfoKind DebugKind,
2757  bool DebugTypeExtRefs, const RecordDecl *RD,
2758  const LangOptions &LangOpts) {
2759  if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
2760  return true;
2761 
2762  if (auto *ES = RD->getASTContext().getExternalSource())
2763  if (ES->hasExternalDefinitions(RD) == ExternalASTSource::EK_Always)
2764  return true;
2765 
2766  // Only emit forward declarations in line tables only to keep debug info size
2767  // small. This only applies to CodeView, since we don't emit types in DWARF
2768  // line tables only.
2769  if (DebugKind == llvm::codegenoptions::DebugLineTablesOnly)
2770  return true;
2771 
2772  if (DebugKind > llvm::codegenoptions::LimitedDebugInfo ||
2773  RD->hasAttr<StandaloneDebugAttr>())
2774  return false;
2775 
2776  if (!LangOpts.CPlusPlus)
2777  return false;
2778 
2779  if (!RD->isCompleteDefinitionRequired())
2780  return true;
2781 
2782  const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2783 
2784  if (!CXXDecl)
2785  return false;
2786 
2787  // Only emit complete debug info for a dynamic class when its vtable is
2788  // emitted. However, Microsoft debuggers don't resolve type information
2789  // across DLL boundaries, so skip this optimization if the class or any of its
2790  // methods are marked dllimport. This isn't a complete solution, since objects
2791  // without any dllimport methods can be used in one DLL and constructed in
2792  // another, but it is the current behavior of LimitedDebugInfo.
2793  if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() &&
2794  !isClassOrMethodDLLImport(CXXDecl))
2795  return true;
2796 
2798  if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
2799  Spec = SD->getSpecializationKind();
2800 
2803  CXXDecl->method_end()))
2804  return true;
2805 
2806  // In constructor homing mode, only emit complete debug info for a class
2807  // when its constructor is emitted.
2808  if ((DebugKind == llvm::codegenoptions::DebugInfoConstructor) &&
2809  canUseCtorHoming(CXXDecl))
2810  return true;
2811 
2812  return false;
2813 }
2814 
2816  if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, CGM.getLangOpts()))
2817  return;
2818 
2819  QualType Ty = CGM.getContext().getRecordType(RD);
2820  llvm::DIType *T = getTypeOrNull(Ty);
2821  if (T && T->isForwardDecl())
2822  completeClassData(RD);
2823 }
2824 
2825 llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
2826  RecordDecl *RD = Ty->getDecl();
2827  llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
2828  if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
2829  CGM.getLangOpts())) {
2830  if (!T)
2831  T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
2832  return T;
2833  }
2834 
2835  auto [Def, Pref] = CreateTypeDefinition(Ty);
2836 
2837  return Pref ? Pref : Def;
2838 }
2839 
2840 llvm::DIType *CGDebugInfo::GetPreferredNameType(const CXXRecordDecl *RD,
2841  llvm::DIFile *Unit) {
2842  if (!RD)
2843  return nullptr;
2844 
2845  auto const *PNA = RD->getAttr<PreferredNameAttr>();
2846  if (!PNA)
2847  return nullptr;
2848 
2849  return getOrCreateType(PNA->getTypedefType(), Unit);
2850 }
2851 
2852 std::pair<llvm::DIType *, llvm::DIType *>
2853 CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
2854  RecordDecl *RD = Ty->getDecl();
2855 
2856  // Get overall information about the record type for the debug info.
2857  llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
2858 
2859  // Records and classes and unions can all be recursive. To handle them, we
2860  // first generate a debug descriptor for the struct as a forward declaration.
2861  // Then (if it is a definition) we go through and get debug info for all of
2862  // its members. Finally, we create a descriptor for the complete type (which
2863  // may refer to the forward decl if the struct is recursive) and replace all
2864  // uses of the forward declaration with the final definition.
2865  llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty);
2866 
2867  const RecordDecl *D = RD->getDefinition();
2868  if (!D || !D->isCompleteDefinition())
2869  return {FwdDecl, nullptr};
2870 
2871  if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
2872  CollectContainingType(CXXDecl, FwdDecl);
2873 
2874  // Push the struct on region stack.
2875  LexicalBlockStack.emplace_back(&*FwdDecl);
2876  RegionMap[Ty->getDecl()].reset(FwdDecl);
2877 
2878  // Convert all the elements.
2880  // what about nested types?
2881 
2882  // Note: The split of CXXDecl information here is intentional, the
2883  // gdb tests will depend on a certain ordering at printout. The debug
2884  // information offsets are still correct if we merge them all together
2885  // though.
2886  const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2887  if (CXXDecl) {
2888  CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
2889  CollectVTableInfo(CXXDecl, DefUnit, EltTys);
2890  }
2891 
2892  // Collect data fields (including static variables and any initializers).
2893  CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
2894  if (CXXDecl)
2895  CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
2896 
2897  LexicalBlockStack.pop_back();
2898  RegionMap.erase(Ty->getDecl());
2899 
2900  llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2901  DBuilder.replaceArrays(FwdDecl, Elements);
2902 
2903  if (FwdDecl->isTemporary())
2904  FwdDecl =
2905  llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
2906 
2907  RegionMap[Ty->getDecl()].reset(FwdDecl);
2908 
2909  if (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB)
2910  if (auto *PrefDI = GetPreferredNameType(CXXDecl, DefUnit))
2911  return {FwdDecl, PrefDI};
2912 
2913  return {FwdDecl, nullptr};
2914 }
2915 
2916 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
2917  llvm::DIFile *Unit) {
2918  // Ignore protocols.
2919  return getOrCreateType(Ty->getBaseType(), Unit);
2920 }
2921 
2922 llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty,
2923  llvm::DIFile *Unit) {
2924  // Ignore protocols.
2926 
2927  // Use Typedefs to represent ObjCTypeParamType.
2928  return DBuilder.createTypedef(
2929  getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
2930  Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
2931  getDeclContextDescriptor(Ty->getDecl()));
2932 }
2933 
2934 /// \return true if Getter has the default name for the property PD.
2936  const ObjCMethodDecl *Getter) {
2937  assert(PD);
2938  if (!Getter)
2939  return true;
2940 
2941  assert(Getter->getDeclName().isObjCZeroArgSelector());
2942  return PD->getName() ==
2944 }
2945 
2946 /// \return true if Setter has the default name for the property PD.
2948  const ObjCMethodDecl *Setter) {
2949  assert(PD);
2950  if (!Setter)
2951  return true;
2952 
2953  assert(Setter->getDeclName().isObjCOneArgSelector());
2956 }
2957 
2958 llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
2959  llvm::DIFile *Unit) {
2960  ObjCInterfaceDecl *ID = Ty->getDecl();
2961  if (!ID)
2962  return nullptr;
2963 
2964  // Return a forward declaration if this type was imported from a clang module,
2965  // and this is not the compile unit with the implementation of the type (which
2966  // may contain hidden ivars).
2967  if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition() &&
2968  !ID->getImplementation())
2969  return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2970  ID->getName(),
2971  getDeclContextDescriptor(ID), Unit, 0);
2972 
2973  // Get overall information about the record type for the debug info.
2974  llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2975  unsigned Line = getLineNumber(ID->getLocation());
2976  auto RuntimeLang =
2977  static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
2978 
2979  // If this is just a forward declaration return a special forward-declaration
2980  // debug type since we won't be able to lay out the entire type.
2981  ObjCInterfaceDecl *Def = ID->getDefinition();
2982  if (!Def || !Def->getImplementation()) {
2983  llvm::DIScope *Mod = getParentModuleOrNull(ID);
2984  llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
2985  llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU,
2986  DefUnit, Line, RuntimeLang);
2987  ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
2988  return FwdDecl;
2989  }
2990 
2991  return CreateTypeDefinition(Ty, Unit);
2992 }
2993 
2994 llvm::DIModule *CGDebugInfo::getOrCreateModuleRef(ASTSourceDescriptor Mod,
2995  bool CreateSkeletonCU) {
2996  // Use the Module pointer as the key into the cache. This is a
2997  // nullptr if the "Module" is a PCH, which is safe because we don't
2998  // support chained PCH debug info, so there can only be a single PCH.
2999  const Module *M = Mod.getModuleOrNull();
3000  auto ModRef = ModuleCache.find(M);
3001  if (ModRef != ModuleCache.end())
3002  return cast<llvm::DIModule>(ModRef->second);
3003 
3004  // Macro definitions that were defined with "-D" on the command line.
3005  SmallString<128> ConfigMacros;
3006  {
3007  llvm::raw_svector_ostream OS(ConfigMacros);
3008  const auto &PPOpts = CGM.getPreprocessorOpts();
3009  unsigned I = 0;
3010  // Translate the macro definitions back into a command line.
3011  for (auto &M : PPOpts.Macros) {
3012  if (++I > 1)
3013  OS << " ";
3014  const std::string &Macro = M.first;
3015  bool Undef = M.second;
3016  OS << "\"-" << (Undef ? 'U' : 'D');
3017  for (char c : Macro)
3018  switch (c) {
3019  case '\\':
3020  OS << "\\\\";
3021  break;
3022  case '"':
3023  OS << "\\\"";
3024  break;
3025  default:
3026  OS << c;
3027  }
3028  OS << '\"';
3029  }
3030  }
3031 
3032  bool IsRootModule = M ? !M->Parent : true;
3033  // When a module name is specified as -fmodule-name, that module gets a
3034  // clang::Module object, but it won't actually be built or imported; it will
3035  // be textual.
3036  if (CreateSkeletonCU && IsRootModule && Mod.getASTFile().empty() && M)
3037  assert(StringRef(M->Name).starts_with(CGM.getLangOpts().ModuleName) &&
3038  "clang module without ASTFile must be specified by -fmodule-name");
3039 
3040  // Return a StringRef to the remapped Path.
3041  auto RemapPath = [this](StringRef Path) -> std::string {
3042  std::string Remapped = remapDIPath(Path);
3043  StringRef Relative(Remapped);
3044  StringRef CompDir = TheCU->getDirectory();
3045  if (Relative.consume_front(CompDir))
3046  Relative.consume_front(llvm::sys::path::get_separator());
3047 
3048  return Relative.str();
3049  };
3050 
3051  if (CreateSkeletonCU && IsRootModule && !Mod.getASTFile().empty()) {
3052  // PCH files don't have a signature field in the control block,
3053  // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
3054  // We use the lower 64 bits for debug info.
3055 
3056  uint64_t Signature = 0;
3057  if (const auto &ModSig = Mod.getSignature())
3058  Signature = ModSig.truncatedValue();
3059  else
3060  Signature = ~1ULL;
3061 
3062  llvm::DIBuilder DIB(CGM.getModule());
3063  SmallString<0> PCM;
3064  if (!llvm::sys::path::is_absolute(Mod.getASTFile())) {
3066  PCM = getCurrentDirname();
3067  else
3068  PCM = Mod.getPath();
3069  }
3070  llvm::sys::path::append(PCM, Mod.getASTFile());
3071  DIB.createCompileUnit(
3072  TheCU->getSourceLanguage(),
3073  // TODO: Support "Source" from external AST providers?
3074  DIB.createFile(Mod.getModuleName(), TheCU->getDirectory()),
3075  TheCU->getProducer(), false, StringRef(), 0, RemapPath(PCM),
3076  llvm::DICompileUnit::FullDebug, Signature);
3077  DIB.finalize();
3078  }
3079 
3080  llvm::DIModule *Parent =
3081  IsRootModule ? nullptr
3082  : getOrCreateModuleRef(ASTSourceDescriptor(*M->Parent),
3083  CreateSkeletonCU);
3084  std::string IncludePath = Mod.getPath().str();
3085  llvm::DIModule *DIMod =
3086  DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
3087  RemapPath(IncludePath));
3088  ModuleCache[M].reset(DIMod);
3089  return DIMod;
3090 }
3091 
3092 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
3093  llvm::DIFile *Unit) {
3094  ObjCInterfaceDecl *ID = Ty->getDecl();
3095  llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
3096  unsigned Line = getLineNumber(ID->getLocation());
3097  unsigned RuntimeLang = TheCU->getSourceLanguage();
3098 
3099  // Bit size, align and offset of the type.
3100  uint64_t Size = CGM.getContext().getTypeSize(Ty);
3101  auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3102 
3103  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3104  if (ID->getImplementation())
3105  Flags |= llvm::DINode::FlagObjcClassComplete;
3106 
3107  llvm::DIScope *Mod = getParentModuleOrNull(ID);
3108  llvm::DICompositeType *RealDecl = DBuilder.createStructType(
3109  Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags,
3110  nullptr, llvm::DINodeArray(), RuntimeLang);
3111 
3112  QualType QTy(Ty, 0);
3113  TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
3114 
3115  // Push the struct on region stack.
3116  LexicalBlockStack.emplace_back(RealDecl);
3117  RegionMap[Ty->getDecl()].reset(RealDecl);
3118 
3119  // Convert all the elements.
3121 
3122  ObjCInterfaceDecl *SClass = ID->getSuperClass();
3123  if (SClass) {
3124  llvm::DIType *SClassTy =
3125  getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
3126  if (!SClassTy)
3127  return nullptr;
3128 
3129  llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0,
3130  llvm::DINode::FlagZero);
3131  EltTys.push_back(InhTag);
3132  }
3133 
3134  // Create entries for all of the properties.
3135  auto AddProperty = [&](const ObjCPropertyDecl *PD) {
3136  SourceLocation Loc = PD->getLocation();
3137  llvm::DIFile *PUnit = getOrCreateFile(Loc);
3138  unsigned PLine = getLineNumber(Loc);
3139  ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
3140  ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
3141  llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
3142  PD->getName(), PUnit, PLine,
3143  hasDefaultGetterName(PD, Getter) ? ""
3144  : getSelectorName(PD->getGetterName()),
3145  hasDefaultSetterName(PD, Setter) ? ""
3146  : getSelectorName(PD->getSetterName()),
3147  PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
3148  EltTys.push_back(PropertyNode);
3149  };
3150  {
3151  // Use 'char' for the isClassProperty bit as DenseSet requires space for
3152  // empty/tombstone keys in the data type (and bool is too small for that).
3153  typedef std::pair<char, const IdentifierInfo *> IsClassAndIdent;
3154  /// List of already emitted properties. Two distinct class and instance
3155  /// properties can share the same identifier (but not two instance
3156  /// properties or two class properties).
3157  llvm::DenseSet<IsClassAndIdent> PropertySet;
3158  /// Returns the IsClassAndIdent key for the given property.
3159  auto GetIsClassAndIdent = [](const ObjCPropertyDecl *PD) {
3160  return std::make_pair(PD->isClassProperty(), PD->getIdentifier());
3161  };
3162  for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
3163  for (auto *PD : ClassExt->properties()) {
3164  PropertySet.insert(GetIsClassAndIdent(PD));
3165  AddProperty(PD);
3166  }
3167  for (const auto *PD : ID->properties()) {
3168  // Don't emit duplicate metadata for properties that were already in a
3169  // class extension.
3170  if (!PropertySet.insert(GetIsClassAndIdent(PD)).second)
3171  continue;
3172  AddProperty(PD);
3173  }
3174  }
3175 
3177  unsigned FieldNo = 0;
3178  for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
3179  Field = Field->getNextIvar(), ++FieldNo) {
3180  llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
3181  if (!FieldTy)
3182  return nullptr;
3183 
3184  StringRef FieldName = Field->getName();
3185 
3186  // Ignore unnamed fields.
3187  if (FieldName.empty())
3188  continue;
3189 
3190  // Get the location for the field.
3191  llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
3192  unsigned FieldLine = getLineNumber(Field->getLocation());
3193  QualType FType = Field->getType();
3194  uint64_t FieldSize = 0;
3195  uint32_t FieldAlign = 0;
3196 
3197  if (!FType->isIncompleteArrayType()) {
3198 
3199  // Bit size, align and offset of the type.
3200  FieldSize = Field->isBitField()
3201  ? Field->getBitWidthValue(CGM.getContext())
3202  : CGM.getContext().getTypeSize(FType);
3203  FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
3204  }
3205 
3206  uint64_t FieldOffset;
3207  if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
3208  // We don't know the runtime offset of an ivar if we're using the
3209  // non-fragile ABI. For bitfields, use the bit offset into the first
3210  // byte of storage of the bitfield. For other fields, use zero.
3211  if (Field->isBitField()) {
3212  FieldOffset =
3213  CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
3214  FieldOffset %= CGM.getContext().getCharWidth();
3215  } else {
3216  FieldOffset = 0;
3217  }
3218  } else {
3219  FieldOffset = RL.getFieldOffset(FieldNo);
3220  }
3221 
3222  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3223  if (Field->getAccessControl() == ObjCIvarDecl::Protected)
3224  Flags = llvm::DINode::FlagProtected;
3225  else if (Field->getAccessControl() == ObjCIvarDecl::Private)
3226  Flags = llvm::DINode::FlagPrivate;
3227  else if (Field->getAccessControl() == ObjCIvarDecl::Public)
3228  Flags = llvm::DINode::FlagPublic;
3229 
3230  if (Field->isBitField())
3231  Flags |= llvm::DINode::FlagBitField;
3232 
3233  llvm::MDNode *PropertyNode = nullptr;
3234  if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
3235  if (ObjCPropertyImplDecl *PImpD =
3236  ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
3237  if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
3238  SourceLocation Loc = PD->getLocation();
3239  llvm::DIFile *PUnit = getOrCreateFile(Loc);
3240  unsigned PLine = getLineNumber(Loc);
3241  ObjCMethodDecl *Getter = PImpD->getGetterMethodDecl();
3242  ObjCMethodDecl *Setter = PImpD->getSetterMethodDecl();
3243  PropertyNode = DBuilder.createObjCProperty(
3244  PD->getName(), PUnit, PLine,
3245  hasDefaultGetterName(PD, Getter)
3246  ? ""
3247  : getSelectorName(PD->getGetterName()),
3248  hasDefaultSetterName(PD, Setter)
3249  ? ""
3250  : getSelectorName(PD->getSetterName()),
3251  PD->getPropertyAttributes(),
3252  getOrCreateType(PD->getType(), PUnit));
3253  }
3254  }
3255  }
3256  FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
3257  FieldSize, FieldAlign, FieldOffset, Flags,
3258  FieldTy, PropertyNode);
3259  EltTys.push_back(FieldTy);
3260  }
3261 
3262  llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
3263  DBuilder.replaceArrays(RealDecl, Elements);
3264 
3265  LexicalBlockStack.pop_back();
3266  return RealDecl;
3267 }
3268 
3269 llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
3270  llvm::DIFile *Unit) {
3271  if (Ty->isExtVectorBoolType()) {
3272  // Boolean ext_vector_type(N) are special because their real element type
3273  // (bits of bit size) is not their Clang element type (_Bool of size byte).
3274  // For now, we pretend the boolean vector were actually a vector of bytes
3275  // (where each byte represents 8 bits of the actual vector).
3276  // FIXME Debug info should actually represent this proper as a vector mask
3277  // type.
3278  auto &Ctx = CGM.getContext();
3279  uint64_t Size = CGM.getContext().getTypeSize(Ty);
3280  uint64_t NumVectorBytes = Size / Ctx.getCharWidth();
3281 
3282  // Construct the vector of 'char' type.
3283  QualType CharVecTy =
3284  Ctx.getVectorType(Ctx.CharTy, NumVectorBytes, VectorKind::Generic);
3285  return CreateType(CharVecTy->getAs<VectorType>(), Unit);
3286  }
3287 
3288  llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
3289  int64_t Count = Ty->getNumElements();
3290 
3291  llvm::Metadata *Subscript;
3292  QualType QTy(Ty, 0);
3293  auto SizeExpr = SizeExprCache.find(QTy);
3294  if (SizeExpr != SizeExprCache.end())
3295  Subscript = DBuilder.getOrCreateSubrange(
3296  SizeExpr->getSecond() /*count*/, nullptr /*lowerBound*/,
3297  nullptr /*upperBound*/, nullptr /*stride*/);
3298  else {
3299  auto *CountNode =
3300  llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3301  llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count ? Count : -1));
3302  Subscript = DBuilder.getOrCreateSubrange(
3303  CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3304  nullptr /*stride*/);
3305  }
3306  llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
3307 
3308  uint64_t Size = CGM.getContext().getTypeSize(Ty);
3309  auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3310 
3311  return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
3312 }
3313 
3314 llvm::DIType *CGDebugInfo::CreateType(const ConstantMatrixType *Ty,
3315  llvm::DIFile *Unit) {
3316  // FIXME: Create another debug type for matrices
3317  // For the time being, it treats it like a nested ArrayType.
3318 
3319  llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
3320  uint64_t Size = CGM.getContext().getTypeSize(Ty);
3321  uint32_t Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3322 
3323  // Create ranges for both dimensions.
3325  auto *ColumnCountNode =
3326  llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3327  llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumColumns()));
3328  auto *RowCountNode =
3329  llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3330  llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumRows()));
3331  Subscripts.push_back(DBuilder.getOrCreateSubrange(
3332  ColumnCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3333  nullptr /*stride*/));
3334  Subscripts.push_back(DBuilder.getOrCreateSubrange(
3335  RowCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3336  nullptr /*stride*/));
3337  llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
3338  return DBuilder.createArrayType(Size, Align, ElementTy, SubscriptArray);
3339 }
3340 
3341 llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
3342  uint64_t Size;
3343  uint32_t Align;
3344 
3345  // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
3346  if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
3347  Size = 0;
3349  CGM.getContext());
3350  } else if (Ty->isIncompleteArrayType()) {
3351  Size = 0;
3352  if (Ty->getElementType()->isIncompleteType())
3353  Align = 0;
3354  else
3355  Align = getTypeAlignIfRequired(Ty->getElementType(), CGM.getContext());
3356  } else if (Ty->isIncompleteType()) {
3357  Size = 0;
3358  Align = 0;
3359  } else {
3360  // Size and align of the whole array, not the element type.
3361  Size = CGM.getContext().getTypeSize(Ty);
3362  Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3363  }
3364 
3365  // Add the dimensions of the array. FIXME: This loses CV qualifiers from
3366  // interior arrays, do we care? Why aren't nested arrays represented the
3367  // obvious/recursive way?
3369  QualType EltTy(Ty, 0);
3370  while ((Ty = dyn_cast<ArrayType>(EltTy))) {
3371  // If the number of elements is known, then count is that number. Otherwise,
3372  // it's -1. This allows us to represent a subrange with an array of 0
3373  // elements, like this:
3374  //
3375  // struct foo {
3376  // int x[0];
3377  // };
3378  int64_t Count = -1; // Count == -1 is an unbounded array.
3379  if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty))
3380  Count = CAT->getZExtSize();
3381  else if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
3382  if (Expr *Size = VAT->getSizeExpr()) {
3383  Expr::EvalResult Result;
3384  if (Size->EvaluateAsInt(Result, CGM.getContext()))
3385  Count = Result.Val.getInt().getExtValue();
3386  }
3387  }
3388 
3389  auto SizeNode = SizeExprCache.find(EltTy);
3390  if (SizeNode != SizeExprCache.end())
3391  Subscripts.push_back(DBuilder.getOrCreateSubrange(
3392  SizeNode->getSecond() /*count*/, nullptr /*lowerBound*/,
3393  nullptr /*upperBound*/, nullptr /*stride*/));
3394  else {
3395  auto *CountNode =
3396  llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3397  llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count));
3398  Subscripts.push_back(DBuilder.getOrCreateSubrange(
3399  CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3400  nullptr /*stride*/));
3401  }
3402  EltTy = Ty->getElementType();
3403  }
3404 
3405  llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
3406 
3407  return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
3408  SubscriptArray);
3409 }
3410 
3411 llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
3412  llvm::DIFile *Unit) {
3413  return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
3414  Ty->getPointeeType(), Unit);
3415 }
3416 
3417 llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
3418  llvm::DIFile *Unit) {
3419  llvm::dwarf::Tag Tag = llvm::dwarf::DW_TAG_rvalue_reference_type;
3420  // DW_TAG_rvalue_reference_type was introduced in DWARF 4.
3421  if (CGM.getCodeGenOpts().DebugStrictDwarf &&
3422  CGM.getCodeGenOpts().DwarfVersion < 4)
3423  Tag = llvm::dwarf::DW_TAG_reference_type;
3424 
3425  return CreatePointerLikeType(Tag, Ty, Ty->getPointeeType(), Unit);
3426 }
3427 
3428 llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
3429  llvm::DIFile *U) {
3430  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3431  uint64_t Size = 0;
3432 
3433  if (!Ty->isIncompleteType()) {
3434  Size = CGM.getContext().getTypeSize(Ty);
3435 
3436  // Set the MS inheritance model. There is no flag for the unspecified model.
3437  if (CGM.getTarget().getCXXABI().isMicrosoft()) {
3440  Flags |= llvm::DINode::FlagSingleInheritance;
3441  break;
3443  Flags |= llvm::DINode::FlagMultipleInheritance;
3444  break;
3446  Flags |= llvm::DINode::FlagVirtualInheritance;
3447  break;
3449  break;
3450  }
3451  }
3452  }
3453 
3454  llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
3455  if (Ty->isMemberDataPointerType())
3456  return DBuilder.createMemberPointerType(
3457  getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0,
3458  Flags);
3459 
3460  const FunctionProtoType *FPT =
3462  return DBuilder.createMemberPointerType(
3463  getOrCreateInstanceMethodType(
3465  FPT, U),
3466  ClassType, Size, /*Align=*/0, Flags);
3467 }
3468 
3469 llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
3470  auto *FromTy = getOrCreateType(Ty->getValueType(), U);
3471  return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy);
3472 }
3473 
3474 llvm::DIType *CGDebugInfo::CreateType(const PipeType *Ty, llvm::DIFile *U) {
3475  return getOrCreateType(Ty->getElementType(), U);
3476 }
3477 
3478 llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
3479  const EnumDecl *ED = Ty->getDecl();
3480 
3481  uint64_t Size = 0;
3482  uint32_t Align = 0;
3483  if (!ED->getTypeForDecl()->isIncompleteType()) {
3484  Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
3485  Align = getDeclAlignIfRequired(ED, CGM.getContext());
3486  }
3487 
3488  SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
3489 
3490  bool isImportedFromModule =
3491  DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition();
3492 
3493  // If this is just a forward declaration, construct an appropriately
3494  // marked node and just return it.
3495  if (isImportedFromModule || !ED->getDefinition()) {
3496  // Note that it is possible for enums to be created as part of
3497  // their own declcontext. In this case a FwdDecl will be created
3498  // twice. This doesn't cause a problem because both FwdDecls are
3499  // entered into the ReplaceMap: finalize() will replace the first
3500  // FwdDecl with the second and then replace the second with
3501  // complete type.
3502  llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
3503  llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
3504  llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType(
3505  llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0));
3506 
3507  unsigned Line = getLineNumber(ED->getLocation());
3508  StringRef EDName = ED->getName();
3509  llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
3510  llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
3511  0, Size, Align, llvm::DINode::FlagFwdDecl, Identifier);
3512 
3513  ReplaceMap.emplace_back(
3514  std::piecewise_construct, std::make_tuple(Ty),
3515  std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
3516  return RetTy;
3517  }
3518 
3519  return CreateTypeDefinition(Ty);
3520 }
3521 
3522 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
3523  const EnumDecl *ED = Ty->getDecl();
3524  uint64_t Size = 0;
3525  uint32_t Align = 0;
3526  if (!ED->getTypeForDecl()->isIncompleteType()) {
3527  Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
3528  Align = getDeclAlignIfRequired(ED, CGM.getContext());
3529  }
3530 
3531  SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
3532 
3534  ED = ED->getDefinition();
3535  for (const auto *Enum : ED->enumerators()) {
3536  Enumerators.push_back(
3537  DBuilder.createEnumerator(Enum->getName(), Enum->getInitVal()));
3538  }
3539 
3540  // Return a CompositeType for the enum itself.
3541  llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
3542 
3543  llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
3544  unsigned Line = getLineNumber(ED->getLocation());
3545  llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
3546  llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit);
3547  return DBuilder.createEnumerationType(
3548  EnumContext, ED->getName(), DefUnit, Line, Size, Align, EltArray, ClassTy,
3549  /*RunTimeLang=*/0, Identifier, ED->isScoped());
3550 }
3551 
3552 llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent,
3553  unsigned MType, SourceLocation LineLoc,
3554  StringRef Name, StringRef Value) {
3555  unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
3556  return DBuilder.createMacro(Parent, Line, MType, Name, Value);
3557 }
3558 
3559 llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent,
3560  SourceLocation LineLoc,
3561  SourceLocation FileLoc) {
3562  llvm::DIFile *FName = getOrCreateFile(FileLoc);
3563  unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
3564  return DBuilder.createTempMacroFile(Parent, Line, FName);
3565 }
3566 
3568  Qualifiers Quals;
3569  do {
3570  Qualifiers InnerQuals = T.getLocalQualifiers();
3571  // Qualifiers::operator+() doesn't like it if you add a Qualifier
3572  // that is already there.
3573  Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
3574  Quals += InnerQuals;
3575  QualType LastT = T;
3576  switch (T->getTypeClass()) {
3577  default:
3578  return C.getQualifiedType(T.getTypePtr(), Quals);
3579  case Type::TemplateSpecialization: {
3580  const auto *Spec = cast<TemplateSpecializationType>(T);
3581  if (Spec->isTypeAlias())
3582  return C.getQualifiedType(T.getTypePtr(), Quals);
3583  T = Spec->desugar();
3584  break;
3585  }
3586  case Type::TypeOfExpr:
3587  T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
3588  break;
3589  case Type::TypeOf:
3590  T = cast<TypeOfType>(T)->getUnmodifiedType();
3591  break;
3592  case Type::Decltype:
3593  T = cast<DecltypeType>(T)->getUnderlyingType();
3594  break;
3595  case Type::UnaryTransform:
3596  T = cast<UnaryTransformType>(T)->getUnderlyingType();
3597  break;
3598  case Type::Attributed:
3599  T = cast<AttributedType>(T)->getEquivalentType();
3600  break;
3601  case Type::BTFTagAttributed:
3602  T = cast<BTFTagAttributedType>(T)->getWrappedType();
3603  break;
3604  case Type::CountAttributed:
3605  T = cast<CountAttributedType>(T)->desugar();
3606  break;
3607  case Type::Elaborated:
3608  T = cast<ElaboratedType>(T)->getNamedType();
3609  break;
3610  case Type::Using:
3611  T = cast<UsingType>(T)->getUnderlyingType();
3612  break;
3613  case Type::Paren:
3614  T = cast<ParenType>(T)->getInnerType();
3615  break;
3616  case Type::MacroQualified:
3617  T = cast<MacroQualifiedType>(T)->getUnderlyingType();
3618  break;
3619  case Type::SubstTemplateTypeParm:
3620  T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
3621  break;
3622  case Type::Auto:
3623  case Type::DeducedTemplateSpecialization: {
3624  QualType DT = cast<DeducedType>(T)->getDeducedType();
3625  assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
3626  T = DT;
3627  break;
3628  }
3629  case Type::PackIndexing: {
3630  T = cast<PackIndexingType>(T)->getSelectedType();
3631  break;
3632  }
3633  case Type::Adjusted:
3634  case Type::Decayed:
3635  // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
3636  T = cast<AdjustedType>(T)->getAdjustedType();
3637  break;
3638  }
3639 
3640  assert(T != LastT && "Type unwrapping failed to unwrap!");
3641  (void)LastT;
3642  } while (true);
3643 }
3644 
3645 llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
3646  assert(Ty == UnwrapTypeForDebugInfo(Ty, CGM.getContext()));
3647  auto It = TypeCache.find(Ty.getAsOpaquePtr());
3648  if (It != TypeCache.end()) {
3649  // Verify that the debug info still exists.
3650  if (llvm::Metadata *V = It->second)
3651  return cast<llvm::DIType>(V);
3652  }
3653 
3654  return nullptr;
3655 }
3656 
3658  const ClassTemplateSpecializationDecl &SD) {
3659  completeUnusedClass(SD);
3660 }
3661 
3663  if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly ||
3664  D.isDynamicClass())
3665  return;
3666 
3667  completeClassData(&D);
3668  // In case this type has no member function definitions being emitted, ensure
3669  // it is retained
3670  RetainedTypes.push_back(CGM.getContext().getRecordType(&D).getAsOpaquePtr());
3671 }
3672 
3673 llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
3674  if (Ty.isNull())
3675  return nullptr;
3676 
3677  llvm::TimeTraceScope TimeScope("DebugType", [&]() {
3678  std::string Name;
3679  llvm::raw_string_ostream OS(Name);
3680  Ty.print(OS, getPrintingPolicy());
3681  return Name;
3682  });
3683 
3684  // Unwrap the type as needed for debug information.
3685  Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
3686 
3687  if (auto *T = getTypeOrNull(Ty))
3688  return T;
3689 
3690  llvm::DIType *Res = CreateTypeNode(Ty, Unit);
3691  void *TyPtr = Ty.getAsOpaquePtr();
3692 
3693  // And update the type cache.
3694  TypeCache[TyPtr].reset(Res);
3695 
3696  return Res;
3697 }
3698 
3699 llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
3700  // A forward declaration inside a module header does not belong to the module.
3701  if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition())
3702  return nullptr;
3703  if (DebugTypeExtRefs && D->isFromASTFile()) {
3704  // Record a reference to an imported clang module or precompiled header.
3705  auto *Reader = CGM.getContext().getExternalSource();
3706  auto Idx = D->getOwningModuleID();
3707  auto Info = Reader->getSourceDescriptor(Idx);
3708  if (Info)
3709  return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
3710  } else if (ClangModuleMap) {
3711  // We are building a clang module or a precompiled header.
3712  //
3713  // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
3714  // and it wouldn't be necessary to specify the parent scope
3715  // because the type is already unique by definition (it would look
3716  // like the output of -fno-standalone-debug). On the other hand,
3717  // the parent scope helps a consumer to quickly locate the object
3718  // file where the type's definition is located, so it might be
3719  // best to make this behavior a command line or debugger tuning
3720  // option.
3721  if (Module *M = D->getOwningModule()) {
3722  // This is a (sub-)module.
3723  auto Info = ASTSourceDescriptor(*M);
3724  return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
3725  } else {
3726  // This the precompiled header being built.
3727  return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false);
3728  }
3729  }
3730 
3731  return nullptr;
3732 }
3733 
3734 llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
3735  // Handle qualifiers, which recursively handles what they refer to.
3736  if (Ty.hasLocalQualifiers())
3737  return CreateQualifiedType(Ty, Unit);
3738 
3739  // Work out details of type.
3740  switch (Ty->getTypeClass()) {
3741 #define TYPE(Class, Base)
3742 #define ABSTRACT_TYPE(Class, Base)
3743 #define NON_CANONICAL_TYPE(Class, Base)
3744 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3745 #include "clang/AST/TypeNodes.inc"
3746  llvm_unreachable("Dependent types cannot show up in debug information");
3747 
3748  case Type::ExtVector:
3749  case Type::Vector:
3750  return CreateType(cast<VectorType>(Ty), Unit);
3751  case Type::ConstantMatrix:
3752  return CreateType(cast<ConstantMatrixType>(Ty), Unit);
3753  case Type::ObjCObjectPointer:
3754  return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
3755  case Type::ObjCObject:
3756  return CreateType(cast<ObjCObjectType>(Ty), Unit);
3757  case Type::ObjCTypeParam:
3758  return CreateType(cast<ObjCTypeParamType>(Ty), Unit);
3759  case Type::ObjCInterface:
3760  return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
3761  case Type::Builtin:
3762  return CreateType(cast<BuiltinType>(Ty));
3763  case Type::Complex:
3764  return CreateType(cast<ComplexType>(Ty));
3765  case Type::Pointer:
3766  return CreateType(cast<PointerType>(Ty), Unit);
3767  case Type::BlockPointer:
3768  return CreateType(cast<BlockPointerType>(Ty), Unit);
3769  case Type::Typedef:
3770  return CreateType(cast<TypedefType>(Ty), Unit);
3771  case Type::Record:
3772  return CreateType(cast<RecordType>(Ty));
3773  case Type::Enum:
3774  return CreateEnumType(cast<EnumType>(Ty));
3775  case Type::FunctionProto:
3776  case Type::FunctionNoProto:
3777  return CreateType(cast<FunctionType>(Ty), Unit);
3778  case Type::ConstantArray:
3779  case Type::VariableArray:
3780  case Type::IncompleteArray:
3781  case Type::ArrayParameter:
3782  return CreateType(cast<ArrayType>(Ty), Unit);
3783 
3784  case Type::LValueReference:
3785  return CreateType(cast<LValueReferenceType>(Ty), Unit);
3786  case Type::RValueReference:
3787  return CreateType(cast<RValueReferenceType>(Ty), Unit);
3788 
3789  case Type::MemberPointer:
3790  return CreateType(cast<MemberPointerType>(Ty), Unit);
3791 
3792  case Type::Atomic:
3793  return CreateType(cast<AtomicType>(Ty), Unit);
3794 
3795  case Type::BitInt:
3796  return CreateType(cast<BitIntType>(Ty));
3797  case Type::Pipe:
3798  return CreateType(cast<PipeType>(Ty), Unit);
3799 
3800  case Type::TemplateSpecialization:
3801  return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
3802 
3803  case Type::CountAttributed:
3804  case Type::Auto:
3805  case Type::Attributed:
3806  case Type::BTFTagAttributed:
3807  case Type::Adjusted:
3808  case Type::Decayed:
3809  case Type::DeducedTemplateSpecialization:
3810  case Type::Elaborated:
3811  case Type::Using:
3812  case Type::Paren:
3813  case Type::MacroQualified:
3814  case Type::SubstTemplateTypeParm:
3815  case Type::TypeOfExpr:
3816  case Type::TypeOf:
3817  case Type::Decltype:
3818  case Type::PackIndexing:
3819  case Type::UnaryTransform:
3820  break;
3821  }
3822 
3823  llvm_unreachable("type should have been unwrapped!");
3824 }
3825 
3826 llvm::DICompositeType *
3827 CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty) {
3828  QualType QTy(Ty, 0);
3829 
3830  auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
3831 
3832  // We may have cached a forward decl when we could have created
3833  // a non-forward decl. Go ahead and create a non-forward decl
3834  // now.
3835  if (T && !T->isForwardDecl())
3836  return T;
3837 
3838  // Otherwise create the type.
3839  llvm::DICompositeType *Res = CreateLimitedType(Ty);
3840 
3841  // Propagate members from the declaration to the definition
3842  // CreateType(const RecordType*) will overwrite this with the members in the
3843  // correct order if the full type is needed.
3844  DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
3845 
3846  // And update the type cache.
3847  TypeCache[QTy.getAsOpaquePtr()].reset(Res);
3848  return Res;
3849 }
3850 
3851 // TODO: Currently used for context chains when limiting debug info.
3852 llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
3853  RecordDecl *RD = Ty->getDecl();
3854 
3855  // Get overall information about the record type for the debug info.
3856  StringRef RDName = getClassName(RD);
3857  const SourceLocation Loc = RD->getLocation();
3858  llvm::DIFile *DefUnit = nullptr;
3859  unsigned Line = 0;
3860  if (Loc.isValid()) {
3861  DefUnit = getOrCreateFile(Loc);
3862  Line = getLineNumber(Loc);
3863  }
3864 
3865  llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
3866 
3867  // If we ended up creating the type during the context chain construction,
3868  // just return that.
3869  auto *T = cast_or_null<llvm::DICompositeType>(
3870  getTypeOrNull(CGM.getContext().getRecordType(RD)));
3871  if (T && (!T->isForwardDecl() || !RD->getDefinition()))
3872  return T;
3873 
3874  // If this is just a forward or incomplete declaration, construct an
3875  // appropriately marked node and just return it.
3876  const RecordDecl *D = RD->getDefinition();
3877  if (!D || !D->isCompleteDefinition())
3878  return getOrCreateRecordFwdDecl(Ty, RDContext);
3879 
3880  uint64_t Size = CGM.getContext().getTypeSize(Ty);
3881  // __attribute__((aligned)) can increase or decrease alignment *except* on a
3882  // struct or struct member, where it only increases alignment unless 'packed'
3883  // is also specified. To handle this case, the `getTypeAlignIfRequired` needs
3884  // to be used.
3885  auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3886 
3887  SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
3888 
3889  // Explicitly record the calling convention and export symbols for C++
3890  // records.
3891  auto Flags = llvm::DINode::FlagZero;
3892  if (auto CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3893  if (CGM.getCXXABI().getRecordArgABI(CXXRD) == CGCXXABI::RAA_Indirect)
3894  Flags |= llvm::DINode::FlagTypePassByReference;
3895  else
3896  Flags |= llvm::DINode::FlagTypePassByValue;
3897 
3898  // Record if a C++ record is non-trivial type.
3899  if (!CXXRD->isTrivial())
3900  Flags |= llvm::DINode::FlagNonTrivial;
3901 
3902  // Record exports it symbols to the containing structure.
3903  if (CXXRD->isAnonymousStructOrUnion())
3904  Flags |= llvm::DINode::FlagExportSymbols;
3905 
3906  Flags |= getAccessFlag(CXXRD->getAccess(),
3907  dyn_cast<CXXRecordDecl>(CXXRD->getDeclContext()));
3908  }
3909 
3910  llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
3911  llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
3912  getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align,
3913  Flags, Identifier, Annotations);
3914 
3915  // Elements of composite types usually have back to the type, creating
3916  // uniquing cycles. Distinct nodes are more efficient.
3917  switch (RealDecl->getTag()) {
3918  default:
3919  llvm_unreachable("invalid composite type tag");
3920 
3921  case llvm::dwarf::DW_TAG_array_type:
3922  case llvm::dwarf::DW_TAG_enumeration_type:
3923  // Array elements and most enumeration elements don't have back references,
3924  // so they don't tend to be involved in uniquing cycles and there is some
3925  // chance of merging them when linking together two modules. Only make
3926  // them distinct if they are ODR-uniqued.
3927  if (Identifier.empty())
3928  break;
3929  [[fallthrough]];
3930 
3931  case llvm::dwarf::DW_TAG_structure_type:
3932  case llvm::dwarf::DW_TAG_union_type:
3933  case llvm::dwarf::DW_TAG_class_type:
3934  // Immediately resolve to a distinct node.
3935  RealDecl =
3936  llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl));
3937  break;
3938  }
3939 
3940  RegionMap[Ty->getDecl()].reset(RealDecl);
3941  TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
3942 
3943  if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
3944  DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
3945  CollectCXXTemplateParams(TSpecial, DefUnit));
3946  return RealDecl;
3947 }
3948 
3949 void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
3950  llvm::DICompositeType *RealDecl) {
3951  // A class's primary base or the class itself contains the vtable.
3952  llvm::DIType *ContainingType = nullptr;
3953  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
3954  if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
3955  // Seek non-virtual primary base root.
3956  while (true) {
3957  const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
3958  const CXXRecordDecl *PBT = BRL.getPrimaryBase();
3959  if (PBT && !BRL.isPrimaryBaseVirtual())
3960  PBase = PBT;
3961  else
3962  break;
3963  }
3964  ContainingType = getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
3965  getOrCreateFile(RD->getLocation()));
3966  } else if (RD->isDynamicClass())
3967  ContainingType = RealDecl;
3968 
3969  DBuilder.replaceVTableHolder(RealDecl, ContainingType);
3970 }
3971 
3972 llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
3973  StringRef Name, uint64_t *Offset) {
3974  llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
3975  uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
3976  auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
3977  llvm::DIType *Ty =
3978  DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign,
3979  *Offset, llvm::DINode::FlagZero, FieldTy);
3980  *Offset += FieldSize;
3981  return Ty;
3982 }
3983 
3984 void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
3985  StringRef &Name,
3986  StringRef &LinkageName,
3987  llvm::DIScope *&FDContext,
3988  llvm::DINodeArray &TParamsArray,
3989  llvm::DINode::DIFlags &Flags) {
3990  const auto *FD = cast<FunctionDecl>(GD.getCanonicalDecl().getDecl());
3991  Name = getFunctionName(FD);
3992  // Use mangled name as linkage name for C/C++ functions.
3993  if (FD->getType()->getAs<FunctionProtoType>())
3994  LinkageName = CGM.getMangledName(GD);
3995  if (FD->hasPrototype())
3996  Flags |= llvm::DINode::FlagPrototyped;
3997  // No need to replicate the linkage name if it isn't different from the
3998  // subprogram name, no need to have it at all unless coverage is enabled or
3999  // debug is set to more than just line tables or extra debug info is needed.
4000  if (LinkageName == Name ||
4001  (CGM.getCodeGenOpts().CoverageNotesFile.empty() &&
4002  CGM.getCodeGenOpts().CoverageDataFile.empty() &&
4003  !CGM.getCodeGenOpts().DebugInfoForProfiling &&
4004  !CGM.getCodeGenOpts().PseudoProbeForProfiling &&
4005  DebugKind <= llvm::codegenoptions::DebugLineTablesOnly))
4006  LinkageName = StringRef();
4007 
4008  // Emit the function scope in line tables only mode (if CodeView) to
4009  // differentiate between function names.
4010  if (CGM.getCodeGenOpts().hasReducedDebugInfo() ||
4011  (DebugKind == llvm::codegenoptions::DebugLineTablesOnly &&
4012  CGM.getCodeGenOpts().EmitCodeView)) {
4013  if (const NamespaceDecl *NSDecl =
4014  dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
4015  FDContext = getOrCreateNamespace(NSDecl);
4016  else if (const RecordDecl *RDecl =
4017  dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
4018  llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
4019  FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);
4020  }
4021  }
4022  if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
4023  // Check if it is a noreturn-marked function
4024  if (FD->isNoReturn())
4025  Flags |= llvm::DINode::FlagNoReturn;
4026  // Collect template parameters.
4027  TParamsArray = CollectFunctionTemplateParams(FD, Unit);
4028  }
4029 }
4030 
4031 void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
4032  unsigned &LineNo, QualType &T,
4033  StringRef &Name, StringRef &LinkageName,
4034  llvm::MDTuple *&TemplateParameters,
4035  llvm::DIScope *&VDContext) {
4036  Unit = getOrCreateFile(VD->getLocation());
4037  LineNo = getLineNumber(VD->getLocation());
4038 
4039  setLocation(VD->getLocation());
4040 
4041  T = VD->getType();
4042  if (T->isIncompleteArrayType()) {
4043  // CodeGen turns int[] into int[1] so we'll do the same here.
4044  llvm::APInt ConstVal(32, 1);
4046 
4047  T = CGM.getContext().getConstantArrayType(ET, ConstVal, nullptr,
4049  }
4050 
4051  Name = VD->getName();
4052  if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
4053  !isa<ObjCMethodDecl>(VD->getDeclContext()))
4054  LinkageName = CGM.getMangledName(VD);
4055  if (LinkageName == Name)
4056  LinkageName = StringRef();
4057 
4058  if (isa<VarTemplateSpecializationDecl>(VD)) {
4059  llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VD, &*Unit);
4060  TemplateParameters = parameterNodes.get();
4061  } else {
4062  TemplateParameters = nullptr;
4063  }
4064 
4065  // Since we emit declarations (DW_AT_members) for static members, place the
4066  // definition of those static members in the namespace they were declared in
4067  // in the source code (the lexical decl context).
4068  // FIXME: Generalize this for even non-member global variables where the
4069  // declaration and definition may have different lexical decl contexts, once
4070  // we have support for emitting declarations of (non-member) global variables.
4071  const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
4072  : VD->getDeclContext();
4073  // When a record type contains an in-line initialization of a static data
4074  // member, and the record type is marked as __declspec(dllexport), an implicit
4075  // definition of the member will be created in the record context. DWARF
4076  // doesn't seem to have a nice way to describe this in a form that consumers
4077  // are likely to understand, so fake the "normal" situation of a definition
4078  // outside the class by putting it in the global scope.
4079  if (DC->isRecord())
4080  DC = CGM.getContext().getTranslationUnitDecl();
4081 
4082  llvm::DIScope *Mod = getParentModuleOrNull(VD);
4083  VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU);
4084 }
4085 
4086 llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD,
4087  bool Stub) {
4088  llvm::DINodeArray TParamsArray;
4089  StringRef Name, LinkageName;
4090  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4091  llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
4093  llvm::DIFile *Unit = getOrCreateFile(Loc);
4094  llvm::DIScope *DContext = Unit;
4095  unsigned Line = getLineNumber(Loc);
4096  collectFunctionDeclProps(GD, Unit, Name, LinkageName, DContext, TParamsArray,
4097  Flags);
4098  auto *FD = cast<FunctionDecl>(GD.getDecl());
4099 
4100  // Build function type.
4101  SmallVector<QualType, 16> ArgTypes;
4102  for (const ParmVarDecl *Parm : FD->parameters())
4103  ArgTypes.push_back(Parm->getType());
4104 
4105  CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
4106  QualType FnType = CGM.getContext().getFunctionType(
4107  FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
4108  if (!FD->isExternallyVisible())
4109  SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
4110  if (CGM.getLangOpts().Optimize)
4111  SPFlags |= llvm::DISubprogram::SPFlagOptimized;
4112 
4113  if (Stub) {
4114  Flags |= getCallSiteRelatedAttrs();
4115  SPFlags |= llvm::DISubprogram::SPFlagDefinition;
4116  return DBuilder.createFunction(
4117  DContext, Name, LinkageName, Unit, Line,
4118  getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
4119  TParamsArray.get(), getFunctionDeclaration(FD));
4120  }
4121 
4122  llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
4123  DContext, Name, LinkageName, Unit, Line,
4124  getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
4125  TParamsArray.get(), getFunctionDeclaration(FD));
4126  const FunctionDecl *CanonDecl = FD->getCanonicalDecl();
4127  FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
4128  std::make_tuple(CanonDecl),
4129  std::make_tuple(SP));
4130  return SP;
4131 }
4132 
4133 llvm::DISubprogram *CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) {
4134  return getFunctionFwdDeclOrStub(GD, /* Stub = */ false);
4135 }
4136 
4137 llvm::DISubprogram *CGDebugInfo::getFunctionStub(GlobalDecl GD) {
4138  return getFunctionFwdDeclOrStub(GD, /* Stub = */ true);
4139 }
4140 
4141 llvm::DIGlobalVariable *
4142 CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
4143  QualType T;
4144  StringRef Name, LinkageName;
4145  SourceLocation Loc = VD->getLocation();
4146  llvm::DIFile *Unit = getOrCreateFile(Loc);
4147  llvm::DIScope *DContext = Unit;
4148  unsigned Line = getLineNumber(Loc);
4149  llvm::MDTuple *TemplateParameters = nullptr;
4150 
4151  collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, TemplateParameters,
4152  DContext);
4153  auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4154  auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
4155  DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
4156  !VD->isExternallyVisible(), nullptr, TemplateParameters, Align);
4157  FwdDeclReplaceMap.emplace_back(
4158  std::piecewise_construct,
4159  std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
4160  std::make_tuple(static_cast<llvm::Metadata *>(GV)));
4161  return GV;
4162 }
4163 
4164 llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
4165  // We only need a declaration (not a definition) of the type - so use whatever
4166  // we would otherwise do to get a type for a pointee. (forward declarations in
4167  // limited debug info, full definitions (if the type definition is available)
4168  // in unlimited debug info)
4169  if (const auto *TD = dyn_cast<TypeDecl>(D))
4170  return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
4171  getOrCreateFile(TD->getLocation()));
4172  auto I = DeclCache.find(D->getCanonicalDecl());
4173 
4174  if (I != DeclCache.end()) {
4175  auto N = I->second;
4176  if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N))
4177  return GVE->getVariable();
4178  return cast<llvm::DINode>(N);
4179  }
4180 
4181  // Search imported declaration cache if it is already defined
4182  // as imported declaration.
4183  auto IE = ImportedDeclCache.find(D->getCanonicalDecl());
4184 
4185  if (IE != ImportedDeclCache.end()) {
4186  auto N = IE->second;
4187  if (auto *GVE = dyn_cast_or_null<llvm::DIImportedEntity>(N))
4188  return cast<llvm::DINode>(GVE);
4189  return dyn_cast_or_null<llvm::DINode>(N);
4190  }
4191 
4192  // No definition for now. Emit a forward definition that might be
4193  // merged with a potential upcoming definition.
4194  if (const auto *FD = dyn_cast<FunctionDecl>(D))
4195  return getFunctionForwardDeclaration(FD);
4196  else if (const auto *VD = dyn_cast<VarDecl>(D))
4197  return getGlobalVariableForwardDeclaration(VD);
4198 
4199  return nullptr;
4200 }
4201 
4202 llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
4203  if (!D || DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
4204  return nullptr;
4205 
4206  const auto *FD = dyn_cast<FunctionDecl>(D);
4207  if (!FD)
4208  return nullptr;
4209 
4210  // Setup context.
4211  auto *S = getDeclContextDescriptor(D);
4212 
4213  auto MI = SPCache.find(FD->getCanonicalDecl());
4214  if (MI == SPCache.end()) {
4215  if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
4216  return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
4217  cast<llvm::DICompositeType>(S));
4218  }
4219  }
4220  if (MI != SPCache.end()) {
4221  auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
4222  if (SP && !SP->isDefinition())
4223  return SP;
4224  }
4225 
4226  for (auto *NextFD : FD->redecls()) {
4227  auto MI = SPCache.find(NextFD->getCanonicalDecl());
4228  if (MI != SPCache.end()) {
4229  auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
4230  if (SP && !SP->isDefinition())
4231  return SP;
4232  }
4233  }
4234  return nullptr;
4235 }
4236 
4237 llvm::DISubprogram *CGDebugInfo::getObjCMethodDeclaration(
4238  const Decl *D, llvm::DISubroutineType *FnType, unsigned LineNo,
4239  llvm::DINode::DIFlags Flags, llvm::DISubprogram::DISPFlags SPFlags) {
4240  if (!D || DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
4241  return nullptr;
4242 
4243  const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
4244  if (!OMD)
4245  return nullptr;
4246 
4247  if (CGM.getCodeGenOpts().DwarfVersion < 5 && !OMD->isDirectMethod())
4248  return nullptr;
4249 
4250  if (OMD->isDirectMethod())
4251  SPFlags |= llvm::DISubprogram::SPFlagObjCDirect;
4252 
4253  // Starting with DWARF V5 method declarations are emitted as children of
4254  // the interface type.
4255  auto *ID = dyn_cast_or_null<ObjCInterfaceDecl>(D->getDeclContext());
4256  if (!ID)
4257  ID = OMD->getClassInterface();
4258  if (!ID)
4259  return nullptr;
4260  QualType QTy(ID->getTypeForDecl(), 0);
4261  auto It = TypeCache.find(QTy.getAsOpaquePtr());
4262  if (It == TypeCache.end())
4263  return nullptr;
4264  auto *InterfaceType = cast<llvm::DICompositeType>(It->second);
4265  llvm::DISubprogram *FD = DBuilder.createFunction(
4266  InterfaceType, getObjCMethodName(OMD), StringRef(),
4267  InterfaceType->getFile(), LineNo, FnType, LineNo, Flags, SPFlags);
4268  DBuilder.finalizeSubprogram(FD);
4269  ObjCMethodCache[ID].push_back({FD, OMD->isDirectMethod()});
4270  return FD;
4271 }
4272 
4273 // getOrCreateFunctionType - Construct type. If it is a c++ method, include
4274 // implicit parameter "this".
4275 llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
4276  QualType FnType,
4277  llvm::DIFile *F) {
4278  // In CodeView, we emit the function types in line tables only because the
4279  // only way to distinguish between functions is by display name and type.
4280  if (!D || (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly &&
4281  !CGM.getCodeGenOpts().EmitCodeView))
4282  // Create fake but valid subroutine type. Otherwise -verify would fail, and
4283  // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
4284  return DBuilder.createSubroutineType(
4285  DBuilder.getOrCreateTypeArray(std::nullopt));
4286 
4287  if (const auto *Method = dyn_cast<CXXMethodDecl>(D))
4288  return getOrCreateMethodType(Method, F);
4289 
4290  const auto *FTy = FnType->getAs<FunctionType>();
4291  CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C;
4292 
4293  if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
4294  // Add "self" and "_cmd"
4296 
4297  // First element is always return type. For 'void' functions it is NULL.
4298  QualType ResultTy = OMethod->getReturnType();
4299 
4300  // Replace the instancetype keyword with the actual type.
4301  if (ResultTy == CGM.getContext().getObjCInstanceType())
4302  ResultTy = CGM.getContext().getPointerType(
4303  QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
4304 
4305  Elts.push_back(getOrCreateType(ResultTy, F));
4306  // "self" pointer is always first argument.
4307  QualType SelfDeclTy;
4308  if (auto *SelfDecl = OMethod->getSelfDecl())
4309  SelfDeclTy = SelfDecl->getType();
4310  else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
4311  if (FPT->getNumParams() > 1)
4312  SelfDeclTy = FPT->getParamType(0);
4313  if (!SelfDeclTy.isNull())
4314  Elts.push_back(
4315  CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
4316  // "_cmd" pointer is always second argument.
4317  Elts.push_back(DBuilder.createArtificialType(
4318  getOrCreateType(CGM.getContext().getObjCSelType(), F)));
4319  // Get rest of the arguments.
4320  for (const auto *PI : OMethod->parameters())
4321  Elts.push_back(getOrCreateType(PI->getType(), F));
4322  // Variadic methods need a special marker at the end of the type list.
4323  if (OMethod->isVariadic())
4324  Elts.push_back(DBuilder.createUnspecifiedParameter());
4325 
4326  llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
4327  return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
4328  getDwarfCC(CC));
4329  }
4330 
4331  // Handle variadic function types; they need an additional
4332  // unspecified parameter.
4333  if (const auto *FD = dyn_cast<FunctionDecl>(D))
4334  if (FD->isVariadic()) {
4336  EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
4337  if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType))
4338  for (QualType ParamType : FPT->param_types())
4339  EltTys.push_back(getOrCreateType(ParamType, F));
4340  EltTys.push_back(DBuilder.createUnspecifiedParameter());
4341  llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
4342  return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
4343  getDwarfCC(CC));
4344  }
4345 
4346  return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
4347 }
4348 
4349 QualType
4351  const SmallVectorImpl<const VarDecl *> &Args) {
4353  if (FD)
4354  if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())
4355  CC = SrcFnTy->getCallConv();
4356  SmallVector<QualType, 16> ArgTypes;
4357  for (const VarDecl *VD : Args)
4358  ArgTypes.push_back(VD->getType());
4359  return CGM.getContext().getFunctionType(RetTy, ArgTypes,
4361 }
4362 
4364  SourceLocation ScopeLoc, QualType FnType,
4365  llvm::Function *Fn, bool CurFuncIsThunk) {
4366  StringRef Name;
4367  StringRef LinkageName;
4368 
4369  FnBeginRegionCount.push_back(LexicalBlockStack.size());
4370 
4371  const Decl *D = GD.getDecl();
4372  bool HasDecl = (D != nullptr);
4373 
4374  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4375  llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
4376  llvm::DIFile *Unit = getOrCreateFile(Loc);
4377  llvm::DIScope *FDContext = Unit;
4378  llvm::DINodeArray TParamsArray;
4379  if (!HasDecl) {
4380  // Use llvm function name.
4381  LinkageName = Fn->getName();
4382  } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4383  // If there is a subprogram for this function available then use it.
4384  auto FI = SPCache.find(FD->getCanonicalDecl());
4385  if (FI != SPCache.end()) {
4386  auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
4387  if (SP && SP->isDefinition()) {
4388  LexicalBlockStack.emplace_back(SP);
4389  RegionMap[D].reset(SP);
4390  return;
4391  }
4392  }
4393  collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
4394  TParamsArray, Flags);
4395  } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
4396  Name = getObjCMethodName(OMD);
4397  Flags |= llvm::DINode::FlagPrototyped;
4398  } else if (isa<VarDecl>(D) &&
4400  // This is a global initializer or atexit destructor for a global variable.
4401  Name = getDynamicInitializerName(cast<VarDecl>(D), GD.getDynamicInitKind(),
4402  Fn);
4403  } else {
4404  Name = Fn->getName();
4405 
4406  if (isa<BlockDecl>(D))
4407  LinkageName = Name;
4408 
4409  Flags |= llvm::DINode::FlagPrototyped;
4410  }
4411  if (Name.starts_with("\01"))
4412  Name = Name.substr(1);
4413 
4414  assert((!D || !isa<VarDecl>(D) ||
4416  "Unexpected DynamicInitKind !");
4417 
4418  if (!HasDecl || D->isImplicit() || D->hasAttr<ArtificialAttr>() ||
4419  isa<VarDecl>(D) || isa<CapturedDecl>(D)) {
4420  Flags |= llvm::DINode::FlagArtificial;
4421  // Artificial functions should not silently reuse CurLoc.
4422  CurLoc = SourceLocation();
4423  }
4424 
4425  if (CurFuncIsThunk)
4426  Flags |= llvm::DINode::FlagThunk;
4427 
4428  if (Fn->hasLocalLinkage())
4429  SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
4430  if (CGM.getLangOpts().Optimize)
4431  SPFlags |= llvm::DISubprogram::SPFlagOptimized;
4432 
4433  llvm::DINode::DIFlags FlagsForDef = Flags | getCallSiteRelatedAttrs();
4434  llvm::DISubprogram::DISPFlags SPFlagsForDef =
4435  SPFlags | llvm::DISubprogram::SPFlagDefinition;
4436 
4437  const unsigned LineNo = getLineNumber(Loc.isValid() ? Loc : CurLoc);
4438  unsigned ScopeLine = getLineNumber(ScopeLoc);
4439  llvm::DISubroutineType *DIFnType = getOrCreateFunctionType(D, FnType, Unit);
4440  llvm::DISubprogram *Decl = nullptr;
4441  llvm::DINodeArray Annotations = nullptr;
4442  if (D) {
4443  Decl = isa<ObjCMethodDecl>(D)
4444  ? getObjCMethodDeclaration(D, DIFnType, LineNo, Flags, SPFlags)
4445  : getFunctionDeclaration(D);
4446  Annotations = CollectBTFDeclTagAnnotations(D);
4447  }
4448 
4449  // FIXME: The function declaration we're constructing here is mostly reusing
4450  // declarations from CXXMethodDecl and not constructing new ones for arbitrary
4451  // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
4452  // all subprograms instead of the actual context since subprogram definitions
4453  // are emitted as CU level entities by the backend.
4454  llvm::DISubprogram *SP = DBuilder.createFunction(
4455  FDContext, Name, LinkageName, Unit, LineNo, DIFnType, ScopeLine,
4456  FlagsForDef, SPFlagsForDef, TParamsArray.get(), Decl, nullptr,
4457  Annotations);
4458  Fn->setSubprogram(SP);
4459  // We might get here with a VarDecl in the case we're generating
4460  // code for the initialization of globals. Do not record these decls
4461  // as they will overwrite the actual VarDecl Decl in the cache.
4462  if (HasDecl && isa<FunctionDecl>(D))
4463  DeclCache[D->getCanonicalDecl()].reset(SP);
4464 
4465  // Push the function onto the lexical block stack.
4466  LexicalBlockStack.emplace_back(SP);
4467 
4468  if (HasDecl)
4469  RegionMap[D].reset(SP);
4470 }
4471 
4473  QualType FnType, llvm::Function *Fn) {
4474  StringRef Name;
4475  StringRef LinkageName;
4476 
4477  const Decl *D = GD.getDecl();
4478  if (!D)
4479  return;
4480 
4481  llvm::TimeTraceScope TimeScope("DebugFunction", [&]() {
4482  return GetName(D, true);
4483  });
4484 
4485  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4486  llvm::DIFile *Unit = getOrCreateFile(Loc);
4487  bool IsDeclForCallSite = Fn ? true : false;
4488  llvm::DIScope *FDContext =
4489  IsDeclForCallSite ? Unit : getDeclContextDescriptor(D);
4490  llvm::DINodeArray TParamsArray;
4491  if (isa<FunctionDecl>(D)) {
4492  // If there is a DISubprogram for this function available then use it.
4493  collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
4494  TParamsArray, Flags);
4495  } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
4496  Name = getObjCMethodName(OMD);
4497  Flags |= llvm::DINode::FlagPrototyped;
4498  } else {
4499  llvm_unreachable("not a function or ObjC method");
4500  }
4501  if (!Name.empty() && Name[0] == '\01')
4502  Name = Name.substr(1);
4503 
4504  if (D->isImplicit()) {
4505  Flags |= llvm::DINode::FlagArtificial;
4506  // Artificial functions without a location should not silently reuse CurLoc.
4507  if (Loc.isInvalid())
4508  CurLoc = SourceLocation();
4509  }
4510  unsigned LineNo = getLineNumber(Loc);
4511  unsigned ScopeLine = 0;
4512  llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
4513  if (CGM.getLangOpts().Optimize)
4514  SPFlags |= llvm::DISubprogram::SPFlagOptimized;
4515 
4516  llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
4517  llvm::DISubroutineType *STy = getOrCreateFunctionType(D, FnType, Unit);
4518  llvm::DISubprogram *SP = DBuilder.createFunction(
4519  FDContext, Name, LinkageName, Unit, LineNo, STy, ScopeLine, Flags,
4520  SPFlags, TParamsArray.get(), nullptr, nullptr, Annotations);
4521 
4522  // Preserve btf_decl_tag attributes for parameters of extern functions
4523  // for BPF target. The parameters created in this loop are attached as
4524  // DISubprogram's retainedNodes in the subsequent finalizeSubprogram call.
4525  if (IsDeclForCallSite && CGM.getTarget().getTriple().isBPF()) {
4526  if (auto *FD = dyn_cast<FunctionDecl>(D)) {
4527  llvm::DITypeRefArray ParamTypes = STy->getTypeArray();
4528  unsigned ArgNo = 1;
4529  for (ParmVarDecl *PD : FD->parameters()) {
4530  llvm::DINodeArray ParamAnnotations = CollectBTFDeclTagAnnotations(PD);
4531  DBuilder.createParameterVariable(
4532  SP, PD->getName(), ArgNo, Unit, LineNo, ParamTypes[ArgNo], true,
4533  llvm::DINode::FlagZero, ParamAnnotations);
4534  ++ArgNo;
4535  }
4536  }
4537  }
4538 
4539  if (IsDeclForCallSite)
4540  Fn->setSubprogram(SP);
4541 
4542  DBuilder.finalizeSubprogram(SP);
4543 }
4544 
4545 void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,
4546  QualType CalleeType,
4547  const FunctionDecl *CalleeDecl) {
4548  if (!CallOrInvoke)
4549  return;
4550  auto *Func = CallOrInvoke->getCalledFunction();
4551  if (!Func)
4552  return;
4553  if (Func->getSubprogram())
4554  return;
4555 
4556  // Do not emit a declaration subprogram for a function with nodebug
4557  // attribute, or if call site info isn't required.
4558  if (CalleeDecl->hasAttr<NoDebugAttr>() ||
4559  noSystemDebugInfo(CalleeDecl, CGM) ||
4560  getCallSiteRelatedAttrs() == llvm::DINode::FlagZero)
4561  return;
4562 
4563  // If there is no DISubprogram attached to the function being called,
4564  // create the one describing the function in order to have complete
4565  // call site debug info.
4566  if (!CalleeDecl->isStatic() && !CalleeDecl->isInlined())
4567  EmitFunctionDecl(CalleeDecl, CalleeDecl->getLocation(), CalleeType, Func);
4568 }
4569 
4571  const auto *FD = cast<FunctionDecl>(GD.getDecl());
4572  // If there is a subprogram for this function available then use it.
4573  auto FI = SPCache.find(FD->getCanonicalDecl());
4574  llvm::DISubprogram *SP = nullptr;
4575  if (FI != SPCache.end())
4576  SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
4577  if (!SP || !SP->isDefinition())
4578  SP = getFunctionStub(GD);
4579  FnBeginRegionCount.push_back(LexicalBlockStack.size());
4580  LexicalBlockStack.emplace_back(SP);
4581  setInlinedAt(Builder.getCurrentDebugLocation());
4582  EmitLocation(Builder, FD->getLocation());
4583 }
4584 
4586  assert(CurInlinedAt && "unbalanced inline scope stack");
4587  EmitFunctionEnd(Builder, nullptr);
4588  setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt());
4589 }
4590 
4592  // Update our current location
4593  setLocation(Loc);
4594 
4595  if (CurLoc.isInvalid() || CurLoc.isMacroID() || LexicalBlockStack.empty())
4596  return;
4597 
4598  llvm::MDNode *Scope = LexicalBlockStack.back();
4599  Builder.SetCurrentDebugLocation(
4600  llvm::DILocation::get(CGM.getLLVMContext(), getLineNumber(CurLoc),
4601  getColumnNumber(CurLoc), Scope, CurInlinedAt));
4602 }
4603 
4604 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
4605  llvm::MDNode *Back = nullptr;
4606  if (!LexicalBlockStack.empty())
4607  Back = LexicalBlockStack.back().get();
4608  LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
4609  cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
4610  getColumnNumber(CurLoc)));
4611 }
4612 
4613 void CGDebugInfo::AppendAddressSpaceXDeref(
4614  unsigned AddressSpace, SmallVectorImpl<uint64_t> &Expr) const {
4615  std::optional<unsigned> DWARFAddressSpace =
4616  CGM.getTarget().getDWARFAddressSpace(AddressSpace);
4617  if (!DWARFAddressSpace)
4618  return;
4619 
4620  Expr.push_back(llvm::dwarf::DW_OP_constu);
4621  Expr.push_back(*DWARFAddressSpace);
4622  Expr.push_back(llvm::dwarf::DW_OP_swap);
4623  Expr.push_back(llvm::dwarf::DW_OP_xderef);
4624 }
4625 
4627  SourceLocation Loc) {
4628  // Set our current location.
4629  setLocation(Loc);
4630 
4631  // Emit a line table change for the current location inside the new scope.
4632  Builder.SetCurrentDebugLocation(llvm::DILocation::get(
4633  CGM.getLLVMContext(), getLineNumber(Loc), getColumnNumber(Loc),
4634  LexicalBlockStack.back(), CurInlinedAt));
4635 
4636  if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
4637  return;
4638 
4639  // Create a new lexical block and push it on the stack.
4640  CreateLexicalBlock(Loc);
4641 }
4642 
4644  SourceLocation Loc) {
4645  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4646 
4647  // Provide an entry in the line table for the end of the block.
4648  EmitLocation(Builder, Loc);
4649 
4650  if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
4651  return;
4652 
4653  LexicalBlockStack.pop_back();
4654 }
4655 
4656 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) {
4657  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4658  unsigned RCount = FnBeginRegionCount.back();
4659  assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
4660 
4661  // Pop all regions for this function.
4662  while (LexicalBlockStack.size() != RCount) {
4663  // Provide an entry in the line table for the end of the block.
4664  EmitLocation(Builder, CurLoc);
4665  LexicalBlockStack.pop_back();
4666  }
4667  FnBeginRegionCount.pop_back();
4668 
4669  if (Fn && Fn->getSubprogram())
4670  DBuilder.finalizeSubprogram(Fn->getSubprogram());
4671 }
4672 
4673 CGDebugInfo::BlockByRefType
4674 CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
4675  uint64_t *XOffset) {
4677  QualType FType;
4678  uint64_t FieldSize, FieldOffset;
4679  uint32_t FieldAlign;
4680 
4681  llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4682  QualType Type = VD->getType();
4683 
4684  FieldOffset = 0;
4685  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4686  EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
4687  EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
4688  FType = CGM.getContext().IntTy;
4689  EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
4690  EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
4691 
4692  bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
4693  if (HasCopyAndDispose) {
4694  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4695  EltTys.push_back(
4696  CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
4697  EltTys.push_back(
4698  CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
4699  }
4700  bool HasByrefExtendedLayout;
4701  Qualifiers::ObjCLifetime Lifetime;
4702  if (CGM.getContext().getByrefLifetime(Type, Lifetime,
4703  HasByrefExtendedLayout) &&
4704  HasByrefExtendedLayout) {
4705  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4706  EltTys.push_back(
4707  CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
4708  }
4709 
4710  CharUnits Align = CGM.getContext().getDeclAlign(VD);
4711  if (Align > CGM.getContext().toCharUnitsFromBits(
4713  CharUnits FieldOffsetInBytes =
4714  CGM.getContext().toCharUnitsFromBits(FieldOffset);
4715  CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);
4716  CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
4717 
4718  if (NumPaddingBytes.isPositive()) {
4719  llvm::APInt pad(32, NumPaddingBytes.getQuantity());
4720  FType = CGM.getContext().getConstantArrayType(
4721  CGM.getContext().CharTy, pad, nullptr, ArraySizeModifier::Normal, 0);
4722  EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
4723  }
4724  }
4725 
4726  FType = Type;
4727  llvm::DIType *WrappedTy = getOrCreateType(FType, Unit);
4728  FieldSize = CGM.getContext().getTypeSize(FType);
4729  FieldAlign = CGM.getContext().toBits(Align);
4730 
4731  *XOffset = FieldOffset;
4732  llvm::DIType *FieldTy = DBuilder.createMemberType(
4733  Unit, VD->getName(), Unit, 0, FieldSize, FieldAlign, FieldOffset,
4734  llvm::DINode::FlagZero, WrappedTy);
4735  EltTys.push_back(FieldTy);
4736  FieldOffset += FieldSize;
4737 
4738  llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
4739  return {DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0,
4740  llvm::DINode::FlagZero, nullptr, Elements),
4741  WrappedTy};
4742 }
4743 
4744 llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD,
4745  llvm::Value *Storage,
4746  std::optional<unsigned> ArgNo,
4747  CGBuilderTy &Builder,
4748  const bool UsePointerValue) {
4749  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4750  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4751  if (VD->hasAttr<NoDebugAttr>() || noSystemDebugInfo(VD, CGM))
4752  return nullptr;
4753 
4754  bool Unwritten =
4755  VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
4756  cast<Decl>(VD->getDeclContext())->isImplicit());
4757  llvm::DIFile *Unit = nullptr;
4758  if (!Unwritten)
4759  Unit = getOrCreateFile(VD->getLocation());
4760  llvm::DIType *Ty;
4761  uint64_t XOffset = 0;
4762  if (VD->hasAttr<BlocksAttr>())
4763  Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
4764  else
4765  Ty = getOrCreateType(VD->getType(), Unit);
4766 
4767  // If there is no debug info for this type then do not emit debug info
4768  // for this variable.
4769  if (!Ty)
4770  return nullptr;
4771 
4772  // Get location information.
4773  unsigned Line = 0;
4774  unsigned Column = 0;
4775  if (!Unwritten) {
4776  Line = getLineNumber(VD->getLocation());
4777  Column = getColumnNumber(VD->getLocation());
4778  }
4780  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4781  if (VD->isImplicit())
4782  Flags |= llvm::DINode::FlagArtificial;
4783 
4784  auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4785 
4786  unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(VD->getType());
4787  AppendAddressSpaceXDeref(AddressSpace, Expr);
4788 
4789  // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an
4790  // object pointer flag.
4791  if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) {
4792  if (IPD->getParameterKind() == ImplicitParamKind::CXXThis ||
4793  IPD->getParameterKind() == ImplicitParamKind::ObjCSelf)
4794  Flags |= llvm::DINode::FlagObjectPointer;
4795  }
4796 
4797  // Note: Older versions of clang used to emit byval references with an extra
4798  // DW_OP_deref, because they referenced the IR arg directly instead of
4799  // referencing an alloca. Newer versions of LLVM don't treat allocas
4800  // differently from other function arguments when used in a dbg.declare.
4801  auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4802  StringRef Name = VD->getName();
4803  if (!Name.empty()) {
4804  // __block vars are stored on the heap if they are captured by a block that
4805  // can escape the local scope.
4806  if (VD->isEscapingByref()) {
4807  // Here, we need an offset *into* the alloca.
4808  CharUnits offset = CharUnits::fromQuantity(32);
4809  Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4810  // offset of __forwarding field
4811  offset = CGM.getContext().toCharUnitsFromBits(
4813  Expr.push_back(offset.getQuantity());
4814  Expr.push_back(llvm::dwarf::DW_OP_deref);
4815  Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4816  // offset of x field
4817  offset = CGM.getContext().toCharUnitsFromBits(XOffset);
4818  Expr.push_back(offset.getQuantity());
4819  }
4820  } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) {
4821  // If VD is an anonymous union then Storage represents value for
4822  // all union fields.
4823  const RecordDecl *RD = RT->getDecl();
4824  if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
4825  // GDB has trouble finding local variables in anonymous unions, so we emit
4826  // artificial local variables for each of the members.
4827  //
4828  // FIXME: Remove this code as soon as GDB supports this.
4829  // The debug info verifier in LLVM operates based on the assumption that a
4830  // variable has the same size as its storage and we had to disable the
4831  // check for artificial variables.
4832  for (const auto *Field : RD->fields()) {
4833  llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
4834  StringRef FieldName = Field->getName();
4835 
4836  // Ignore unnamed fields. Do not ignore unnamed records.
4837  if (FieldName.empty() && !isa<RecordType>(Field->getType()))
4838  continue;
4839 
4840  // Use VarDecl's Tag, Scope and Line number.
4841  auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext());
4842  auto *D = DBuilder.createAutoVariable(
4843  Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,
4844  Flags | llvm::DINode::FlagArtificial, FieldAlign);
4845 
4846  // Insert an llvm.dbg.declare into the current block.
4847  DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
4848  llvm::DILocation::get(CGM.getLLVMContext(), Line,
4849  Column, Scope,
4850  CurInlinedAt),
4851  Builder.GetInsertBlock());
4852  }
4853  }
4854  }
4855 
4856  // Clang stores the sret pointer provided by the caller in a static alloca.
4857  // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
4858  // the address of the variable.
4859  if (UsePointerValue) {
4860  assert(!llvm::is_contained(Expr, llvm::dwarf::DW_OP_deref) &&
4861  "Debug info already contains DW_OP_deref.");
4862  Expr.push_back(llvm::dwarf::DW_OP_deref);
4863  }
4864 
4865  // Create the descriptor for the variable.
4866  llvm::DILocalVariable *D = nullptr;
4867  if (ArgNo) {
4868  llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(VD);
4869  D = DBuilder.createParameterVariable(Scope, Name, *ArgNo, Unit, Line, Ty,
4870  CGM.getLangOpts().Optimize, Flags,
4871  Annotations);
4872  } else {
4873  // For normal local variable, we will try to find out whether 'VD' is the
4874  // copy parameter of coroutine.
4875  // If yes, we are going to use DIVariable of the origin parameter instead
4876  // of creating the new one.
4877  // If no, it might be a normal alloc, we just create a new one for it.
4878 
4879  // Check whether the VD is move parameters.
4880  auto RemapCoroArgToLocalVar = [&]() -> llvm::DILocalVariable * {
4881  // The scope of parameter and move-parameter should be distinct
4882  // DISubprogram.
4883  if (!isa<llvm::DISubprogram>(Scope) || !Scope->isDistinct())
4884  return nullptr;
4885 
4886  auto Iter = llvm::find_if(CoroutineParameterMappings, [&](auto &Pair) {
4887  Stmt *StmtPtr = const_cast<Stmt *>(Pair.second);
4888  if (DeclStmt *DeclStmtPtr = dyn_cast<DeclStmt>(StmtPtr)) {
4889  DeclGroupRef DeclGroup = DeclStmtPtr->getDeclGroup();
4890  Decl *Decl = DeclGroup.getSingleDecl();
4891  if (VD == dyn_cast_or_null<VarDecl>(Decl))
4892  return true;
4893  }
4894  return false;
4895  });
4896 
4897  if (Iter != CoroutineParameterMappings.end()) {
4898  ParmVarDecl *PD = const_cast<ParmVarDecl *>(Iter->first);
4899  auto Iter2 = llvm::find_if(ParamDbgMappings, [&](auto &DbgPair) {
4900  return DbgPair.first == PD && DbgPair.second->getScope() == Scope;
4901  });
4902  if (Iter2 != ParamDbgMappings.end())
4903  return const_cast<llvm::DILocalVariable *>(Iter2->second);
4904  }
4905  return nullptr;
4906  };
4907 
4908  // If we couldn't find a move param DIVariable, create a new one.
4909  D = RemapCoroArgToLocalVar();
4910  // Or we will create a new DIVariable for this Decl if D dose not exists.
4911  if (!D)
4912  D = DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,
4913  CGM.getLangOpts().Optimize, Flags, Align);
4914  }
4915  // Insert an llvm.dbg.declare into the current block.
4916  DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
4917  llvm::DILocation::get(CGM.getLLVMContext(), Line,
4918  Column, Scope, CurInlinedAt),
4919  Builder.GetInsertBlock());
4920 
4921  return D;
4922 }
4923 
4924 llvm::DIType *CGDebugInfo::CreateBindingDeclType(const BindingDecl *BD) {
4925  llvm::DIFile *Unit = getOrCreateFile(BD->getLocation());
4926 
4927  // If the declaration is bound to a bitfield struct field, its type may have a
4928  // size that is different from its deduced declaration type's.
4929  if (const MemberExpr *ME = dyn_cast<MemberExpr>(BD->getBinding())) {
4930  if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
4931  if (FD->isBitField()) {
4932  ASTContext &Context = CGM.getContext();
4933  const CGRecordLayout &RL =
4934  CGM.getTypes().getCGRecordLayout(FD->getParent());
4935  const CGBitFieldInfo &Info = RL.getBitFieldInfo(FD);
4936 
4937  // Find an integer type with the same bitwidth as the bitfield size. If
4938  // no suitable type is present in the target, give up on producing debug
4939  // information as it would be wrong. It is certainly possible to produce
4940  // correct debug info, but the logic isn't currently implemented.
4941  uint64_t BitfieldSizeInBits = Info.Size;
4942  QualType IntTy =
4943  Context.getIntTypeForBitwidth(BitfieldSizeInBits, Info.IsSigned);
4944  if (IntTy.isNull())
4945  return nullptr;
4946  Qualifiers Quals = BD->getType().getQualifiers();
4947  QualType FinalTy = Context.getQualifiedType(IntTy, Quals);
4948  llvm::DIType *Ty = getOrCreateType(FinalTy, Unit);
4949  assert(Ty);
4950  return Ty;
4951  }
4952  }
4953  }
4954 
4955  return getOrCreateType(BD->getType(), Unit);
4956 }
4957 
4958 llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const BindingDecl *BD,
4959  llvm::Value *Storage,
4960  std::optional<unsigned> ArgNo,
4961  CGBuilderTy &Builder,
4962  const bool UsePointerValue) {
4963  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4964  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4965  if (BD->hasAttr<NoDebugAttr>() || noSystemDebugInfo(BD, CGM))
4966  return nullptr;
4967 
4968  // Skip the tuple like case, we don't handle that here
4969  if (isa<DeclRefExpr>(BD->getBinding()))
4970  return nullptr;
4971 
4972  llvm::DIType *Ty = CreateBindingDeclType(BD);
4973 
4974  // If there is no debug info for this type then do not emit debug info
4975  // for this variable.
4976  if (!Ty)
4977  return nullptr;
4978 
4979  auto Align = getDeclAlignIfRequired(BD, CGM.getContext());
4980  unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(BD->getType());
4981 
4983  AppendAddressSpaceXDeref(AddressSpace, Expr);
4984 
4985  // Clang stores the sret pointer provided by the caller in a static alloca.
4986  // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
4987  // the address of the variable.
4988  if (UsePointerValue) {
4989  assert(!llvm::is_contained(Expr, llvm::dwarf::DW_OP_deref) &&
4990  "Debug info already contains DW_OP_deref.");
4991  Expr.push_back(llvm::dwarf::DW_OP_deref);
4992  }
4993 
4994  unsigned Line = getLineNumber(BD->getLocation());
4995  unsigned Column = getColumnNumber(BD->getLocation());
4996  StringRef Name = BD->getName();
4997  auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4998  llvm::DIFile *Unit = getOrCreateFile(BD->getLocation());
4999  // Create the descriptor for the variable.
5000  llvm::DILocalVariable *D = DBuilder.createAutoVariable(
5001  Scope, Name, Unit, Line, Ty, CGM.getLangOpts().Optimize,
5002  llvm::DINode::FlagZero, Align);
5003 
5004  if (const MemberExpr *ME = dyn_cast<MemberExpr>(BD->getBinding())) {
5005  if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
5006  const unsigned fieldIndex = FD->getFieldIndex();
5007  const clang::CXXRecordDecl *parent =
5008  (const CXXRecordDecl *)FD->getParent();
5009  const ASTRecordLayout &layout =
5010  CGM.getContext().getASTRecordLayout(parent);
5011  const uint64_t fieldOffset = layout.getFieldOffset(fieldIndex);
5012 
5013  if (fieldOffset != 0) {
5014  // Currently if the field offset is not a multiple of byte, the produced
5015  // location would not be accurate. Therefore give up.
5016  if (fieldOffset % CGM.getContext().getCharWidth() != 0)
5017  return nullptr;
5018 
5019  Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5020  Expr.push_back(
5021  CGM.getContext().toCharUnitsFromBits(fieldOffset).getQuantity());
5022  }
5023  }
5024  } else if (const ArraySubscriptExpr *ASE =
5025  dyn_cast<ArraySubscriptExpr>(BD->getBinding())) {
5026  if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ASE->getIdx())) {
5027  const uint64_t value = IL->getValue().getZExtValue();
5028  const uint64_t typeSize = CGM.getContext().getTypeSize(BD->getType());
5029 
5030  if (value != 0) {
5031  Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5032  Expr.push_back(CGM.getContext()
5033  .toCharUnitsFromBits(value * typeSize)
5034  .getQuantity());
5035  }
5036  }
5037  }
5038 
5039  // Insert an llvm.dbg.declare into the current block.
5040  DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
5041  llvm::DILocation::get(CGM.getLLVMContext(), Line,
5042  Column, Scope, CurInlinedAt),
5043  Builder.GetInsertBlock());
5044 
5045  return D;
5046 }
5047 
5048 llvm::DILocalVariable *
5050  CGBuilderTy &Builder,
5051  const bool UsePointerValue) {
5052  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5053 
5054  if (auto *DD = dyn_cast<DecompositionDecl>(VD)) {
5055  for (auto *B : DD->bindings()) {
5056  EmitDeclare(B, Storage, std::nullopt, Builder,
5057  VD->getType()->isReferenceType());
5058  }
5059  // Don't emit an llvm.dbg.declare for the composite storage as it doesn't
5060  // correspond to a user variable.
5061  return nullptr;
5062  }
5063 
5064  return EmitDeclare(VD, Storage, std::nullopt, Builder, UsePointerValue);
5065 }
5066 
5068  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5069  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
5070 
5071  if (D->hasAttr<NoDebugAttr>() || noSystemDebugInfo(D, CGM))
5072  return;
5073 
5074  auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
5075  llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
5076 
5077  // Get location information.
5078  unsigned Line = getLineNumber(D->getLocation());
5079  unsigned Column = getColumnNumber(D->getLocation());
5080 
5081  StringRef Name = D->getName();
5082 
5083  // Create the descriptor for the label.
5084  auto *L =
5085  DBuilder.createLabel(Scope, Name, Unit, Line, CGM.getLangOpts().Optimize);
5086 
5087  // Insert an llvm.dbg.label into the current block.
5088  DBuilder.insertLabel(L,
5089  llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,
5090  Scope, CurInlinedAt),
5091  Builder.GetInsertBlock());
5092 }
5093 
5094 llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
5095  llvm::DIType *Ty) {
5096  llvm::DIType *CachedTy = getTypeOrNull(QualTy);
5097  if (CachedTy)
5098  Ty = CachedTy;
5099  return DBuilder.createObjectPointerType(Ty);
5100 }
5101 
5103  const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
5104  const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
5105  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5106  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
5107 
5108  if (Builder.GetInsertBlock() == nullptr)
5109  return;
5110  if (VD->hasAttr<NoDebugAttr>() || noSystemDebugInfo(VD, CGM))
5111  return;
5112 
5113  bool isByRef = VD->hasAttr<BlocksAttr>();
5114 
5115  uint64_t XOffset = 0;
5116  llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
5117  llvm::DIType *Ty;
5118  if (isByRef)
5119  Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
5120  else
5121  Ty = getOrCreateType(VD->getType(), Unit);
5122 
5123  // Self is passed along as an implicit non-arg variable in a
5124  // block. Mark it as the object pointer.
5125  if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD))
5126  if (IPD->getParameterKind() == ImplicitParamKind::ObjCSelf)
5127  Ty = CreateSelfType(VD->getType(), Ty);
5128 
5129  // Get location information.
5130  const unsigned Line =
5131  getLineNumber(VD->getLocation().isValid() ? VD->getLocation() : CurLoc);
5132  unsigned Column = getColumnNumber(VD->getLocation());
5133 
5134  const llvm::DataLayout &target = CGM.getDataLayout();
5135 
5137  target.getStructLayout(blockInfo.StructureType)
5138  ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
5139 
5141  addr.push_back(llvm::dwarf::DW_OP_deref);
5142  addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5143  addr.push_back(offset.getQuantity());
5144  if (isByRef) {
5145  addr.push_back(llvm::dwarf::DW_OP_deref);
5146  addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5147  // offset of __forwarding field
5148  offset =
5149  CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
5150  addr.push_back(offset.getQuantity());
5151  addr.push_back(llvm::dwarf::DW_OP_deref);
5152  addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5153  // offset of x field
5154  offset = CGM.getContext().toCharUnitsFromBits(XOffset);
5155  addr.push_back(offset.getQuantity());
5156  }
5157 
5158  // Create the descriptor for the variable.
5159  auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
5160  auto *D = DBuilder.createAutoVariable(
5161  cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
5162  Line, Ty, false, llvm::DINode::FlagZero, Align);
5163 
5164  // Insert an llvm.dbg.declare into the current block.
5165  auto DL = llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,
5166  LexicalBlockStack.back(), CurInlinedAt);
5167  auto *Expr = DBuilder.createExpression(addr);
5168  if (InsertPoint)
5169  DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint);
5170  else
5171  DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock());
5172 }
5173 
5174 llvm::DILocalVariable *
5176  unsigned ArgNo, CGBuilderTy &Builder,
5177  bool UsePointerValue) {
5178  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5179  return EmitDeclare(VD, AI, ArgNo, Builder, UsePointerValue);
5180 }
5181 
5182 namespace {
5183 struct BlockLayoutChunk {
5184  uint64_t OffsetInBits;
5185  const BlockDecl::Capture *Capture;
5186 };
5187 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
5188  return l.OffsetInBits < r.OffsetInBits;
5189 }
5190 } // namespace
5191 
5192 void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare(
5193  const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc,
5194  const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit,
5196  // Blocks in OpenCL have unique constraints which make the standard fields
5197  // redundant while requiring size and align fields for enqueue_kernel. See
5198  // initializeForBlockHeader in CGBlocks.cpp
5199  if (CGM.getLangOpts().OpenCL) {
5200  Fields.push_back(createFieldType("__size", Context.IntTy, Loc, AS_public,
5201  BlockLayout.getElementOffsetInBits(0),
5202  Unit, Unit));
5203  Fields.push_back(createFieldType("__align", Context.IntTy, Loc, AS_public,
5204  BlockLayout.getElementOffsetInBits(1),
5205  Unit, Unit));
5206  } else {
5207  Fields.push_back(createFieldType("__isa", Context.VoidPtrTy, Loc, AS_public,
5208  BlockLayout.getElementOffsetInBits(0),
5209  Unit, Unit));
5210  Fields.push_back(createFieldType("__flags", Context.IntTy, Loc, AS_public,
5211  BlockLayout.getElementOffsetInBits(1),
5212  Unit, Unit));
5213  Fields.push_back(
5214  createFieldType("__reserved", Context.IntTy, Loc, AS_public,
5215  BlockLayout.getElementOffsetInBits(2), Unit, Unit));
5216  auto *FnTy = Block.getBlockExpr()->getFunctionType();
5217  auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
5218  Fields.push_back(createFieldType("__FuncPtr", FnPtrType, Loc, AS_public,
5219  BlockLayout.getElementOffsetInBits(3),
5220  Unit, Unit));
5221  Fields.push_back(createFieldType(
5222  "__descriptor",
5223  Context.getPointerType(Block.NeedsCopyDispose
5224  ? Context.getBlockDescriptorExtendedType()
5225  : Context.getBlockDescriptorType()),
5226  Loc, AS_public, BlockLayout.getElementOffsetInBits(4), Unit, Unit));
5227  }
5228 }
5229 
5231  StringRef Name,
5232  unsigned ArgNo,
5233  llvm::AllocaInst *Alloca,
5234  CGBuilderTy &Builder) {
5235  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5236  ASTContext &C = CGM.getContext();
5237  const BlockDecl *blockDecl = block.getBlockDecl();
5238 
5239  // Collect some general information about the block's location.
5240  SourceLocation loc = blockDecl->getCaretLocation();
5241  llvm::DIFile *tunit = getOrCreateFile(loc);
5242  unsigned line = getLineNumber(loc);
5243  unsigned column = getColumnNumber(loc);
5244 
5245  // Build the debug-info type for the block literal.
5246  getDeclContextDescriptor(blockDecl);
5247 
5248  const llvm::StructLayout *blockLayout =
5249  CGM.getDataLayout().getStructLayout(block.StructureType);
5250 
5252  collectDefaultFieldsForBlockLiteralDeclare(block, C, loc, *blockLayout, tunit,
5253  fields);
5254 
5255  // We want to sort the captures by offset, not because DWARF
5256  // requires this, but because we're paranoid about debuggers.
5258 
5259  // 'this' capture.
5260  if (blockDecl->capturesCXXThis()) {
5261  BlockLayoutChunk chunk;
5262  chunk.OffsetInBits =
5263  blockLayout->getElementOffsetInBits(block.CXXThisIndex);
5264  chunk.Capture = nullptr;
5265  chunks.push_back(chunk);
5266  }
5267 
5268  // Variable captures.
5269  for (const auto &capture : blockDecl->captures()) {
5270  const VarDecl *variable = capture.getVariable();
5271  const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
5272 
5273  // Ignore constant captures.
5274  if (captureInfo.isConstant())
5275  continue;
5276 
5277  BlockLayoutChunk chunk;
5278  chunk.OffsetInBits =
5279  blockLayout->getElementOffsetInBits(captureInfo.getIndex());
5280  chunk.Capture = &capture;
5281  chunks.push_back(chunk);
5282  }
5283 
5284  // Sort by offset.
5285  llvm::array_pod_sort(chunks.begin(), chunks.end());
5286 
5287  for (const BlockLayoutChunk &Chunk : chunks) {
5288  uint64_t offsetInBits = Chunk.OffsetInBits;
5289  const BlockDecl::Capture *capture = Chunk.Capture;
5290 
5291  // If we have a null capture, this must be the C++ 'this' capture.
5292  if (!capture) {
5293  QualType type;
5294  if (auto *Method =
5295  cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext()))
5296  type = Method->getThisType();
5297  else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent()))
5298  type = QualType(RDecl->getTypeForDecl(), 0);
5299  else
5300  llvm_unreachable("unexpected block declcontext");
5301 
5302  fields.push_back(createFieldType("this", type, loc, AS_public,
5303  offsetInBits, tunit, tunit));
5304  continue;
5305  }
5306 
5307  const VarDecl *variable = capture->getVariable();
5308  StringRef name = variable->getName();
5309 
5310  llvm::DIType *fieldType;
5311  if (capture->isByRef()) {
5312  TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
5313  auto Align = PtrInfo.isAlignRequired() ? PtrInfo.Align : 0;
5314  // FIXME: This recomputes the layout of the BlockByRefWrapper.
5315  uint64_t xoffset;
5316  fieldType =
5317  EmitTypeForVarWithBlocksAttr(variable, &xoffset).BlockByRefWrapper;
5318  fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
5319  fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
5320  PtrInfo.Width, Align, offsetInBits,
5321  llvm::DINode::FlagZero, fieldType);
5322  } else {
5323  auto Align = getDeclAlignIfRequired(variable, CGM.getContext());
5324  fieldType = createFieldType(name, variable->getType(), loc, AS_public,
5325  offsetInBits, Align, tunit, tunit);
5326  }
5327  fields.push_back(fieldType);
5328  }
5329 
5330  SmallString<36> typeName;
5331  llvm::raw_svector_ostream(typeName)
5332  << "__block_literal_" << CGM.getUniqueBlockCount();
5333 
5334  llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
5335 
5336  llvm::DIType *type =
5337  DBuilder.createStructType(tunit, typeName.str(), tunit, line,
5338  CGM.getContext().toBits(block.BlockSize), 0,
5339  llvm::DINode::FlagZero, nullptr, fieldsArray);
5340  type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
5341 
5342  // Get overall information about the block.
5343  llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial;
5344  auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
5345 
5346  // Create the descriptor for the parameter.
5347  auto *debugVar = DBuilder.createParameterVariable(
5348  scope, Name, ArgNo, tunit, line, type, CGM.getLangOpts().Optimize, flags);
5349 
5350  // Insert an llvm.dbg.declare into the current block.
5351  DBuilder.insertDeclare(Alloca, debugVar, DBuilder.createExpression(),
5352  llvm::DILocation::get(CGM.getLLVMContext(), line,
5353  column, scope, CurInlinedAt),
5354  Builder.GetInsertBlock());
5355 }
5356 
5357 llvm::DIDerivedType *
5358 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
5359  if (!D || !D->isStaticDataMember())
5360  return nullptr;
5361 
5362  auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
5363  if (MI != StaticDataMemberCache.end()) {
5364  assert(MI->second && "Static data member declaration should still exist");
5365  return MI->second;
5366  }
5367 
5368  // If the member wasn't found in the cache, lazily construct and add it to the
5369  // type (used when a limited form of the type is emitted).
5370  auto DC = D->getDeclContext();
5371  auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
5372  return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
5373 }
5374 
5375 llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls(
5376  const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
5377  StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
5378  llvm::DIGlobalVariableExpression *GVE = nullptr;
5379 
5380  for (const auto *Field : RD->fields()) {
5381  llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
5382  StringRef FieldName = Field->getName();
5383 
5384  // Ignore unnamed fields, but recurse into anonymous records.
5385  if (FieldName.empty()) {
5386  if (const auto *RT = dyn_cast<RecordType>(Field->getType()))
5387  GVE = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
5388  Var, DContext);
5389  continue;
5390  }
5391  // Use VarDecl's Tag, Scope and Line number.
5392  GVE = DBuilder.createGlobalVariableExpression(
5393  DContext, FieldName, LinkageName, Unit, LineNo, FieldTy,
5394  Var->hasLocalLinkage());
5395  Var->addDebugInfo(GVE);
5396  }
5397  return GVE;
5398 }
5399 
5402  // Unnamed classes/lambdas can't be reconstituted due to a lack of column
5403  // info we produce in the DWARF, so we can't get Clang's full name back.
5404  // But so long as it's not one of those, it doesn't matter if some sub-type
5405  // of the record (a template parameter) can't be reconstituted - because the
5406  // un-reconstitutable type itself will carry its own name.
5407  const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5408  if (!RD)
5409  return false;
5410  if (!RD->getIdentifier())
5411  return true;
5412  auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD);
5413  if (!TSpecial)
5414  return false;
5415  return ReferencesAnonymousEntity(TSpecial->getTemplateArgs().asArray());
5416 }
5418  return llvm::any_of(Args, [&](const TemplateArgument &TA) {
5419  switch (TA.getKind()) {
5420  case TemplateArgument::Pack:
5421  return ReferencesAnonymousEntity(TA.getPackAsArray());
5422  case TemplateArgument::Type: {
5423  struct ReferencesAnonymous
5424  : public RecursiveASTVisitor<ReferencesAnonymous> {
5425  bool RefAnon = false;
5426  bool VisitRecordType(RecordType *RT) {
5427  if (ReferencesAnonymousEntity(RT)) {
5428  RefAnon = true;
5429  return false;
5430  }
5431  return true;
5432  }
5433  };
5434  ReferencesAnonymous RT;
5435  RT.TraverseType(TA.getAsType());
5436  if (RT.RefAnon)
5437  return true;
5438  break;
5439  }
5440  default:
5441  break;
5442  }
5443  return false;
5444  });
5445 }
5446 namespace {
5447 struct ReconstitutableType : public RecursiveASTVisitor<ReconstitutableType> {
5448  bool Reconstitutable = true;
5449  bool VisitVectorType(VectorType *FT) {
5450  Reconstitutable = false;
5451  return false;
5452  }
5453  bool VisitAtomicType(AtomicType *FT) {
5454  Reconstitutable = false;
5455  return false;
5456  }
5457  bool VisitType(Type *T) {
5458  // _BitInt(N) isn't reconstitutable because the bit width isn't encoded in
5459  // the DWARF, only the byte width.
5460  if (T->isBitIntType()) {
5461  Reconstitutable = false;
5462  return false;
5463  }
5464  return true;
5465  }
5466  bool TraverseEnumType(EnumType *ET) {
5467  // Unnamed enums can't be reconstituted due to a lack of column info we
5468  // produce in the DWARF, so we can't get Clang's full name back.
5469  if (const auto *ED = dyn_cast<EnumDecl>(ET->getDecl())) {
5470  if (!ED->getIdentifier()) {
5471  Reconstitutable = false;
5472  return false;
5473  }
5474  if (!ED->isExternallyVisible()) {
5475  Reconstitutable = false;
5476  return false;
5477  }
5478  }
5479  return true;
5480  }
5481  bool VisitFunctionProtoType(FunctionProtoType *FT) {
5482  // noexcept is not encoded in DWARF, so the reversi
5483  Reconstitutable &= !isNoexceptExceptionSpec(FT->getExceptionSpecType());
5484  Reconstitutable &= !FT->getNoReturnAttr();
5485  return Reconstitutable;
5486  }
5487  bool VisitRecordType(RecordType *RT) {
5488  if (ReferencesAnonymousEntity(RT)) {
5489  Reconstitutable = false;
5490  return false;
5491  }
5492  return true;
5493  }
5494 };
5495 } // anonymous namespace
5496 
5497 // Test whether a type name could be rebuilt from emitted debug info.
5499  ReconstitutableType T;
5500  T.TraverseType(QT);
5501  return T.Reconstitutable;
5502 }
5503 
5504 bool CGDebugInfo::HasReconstitutableArgs(
5505  ArrayRef<TemplateArgument> Args) const {
5506  return llvm::all_of(Args, [&](const TemplateArgument &TA) {
5507  switch (TA.getKind()) {
5508  case TemplateArgument::Template:
5509  // Easy to reconstitute - the value of the parameter in the debug
5510  // info is the string name of the template. The template name
5511  // itself won't benefit from any name rebuilding, but that's a
5512  // representational limitation - maybe DWARF could be
5513  // changed/improved to use some more structural representation.
5514  return true;
5515  case TemplateArgument::Declaration:
5516  // Reference and pointer non-type template parameters point to
5517  // variables, functions, etc and their value is, at best (for
5518  // variables) represented as an address - not a reference to the
5519  // DWARF describing the variable/function/etc. This makes it hard,
5520  // possibly impossible to rebuild the original name - looking up
5521  // the address in the executable file's symbol table would be
5522  // needed.
5523  return false;
5524  case TemplateArgument::NullPtr:
5525  // These could be rebuilt, but figured they're close enough to the
5526  // declaration case, and not worth rebuilding.
5527  return false;
5528  case TemplateArgument::Pack:
5529  // A pack is invalid if any of the elements of the pack are
5530  // invalid.
5531  return HasReconstitutableArgs(TA.getPackAsArray());
5532  case TemplateArgument::Integral:
5533  // Larger integers get encoded as DWARF blocks which are a bit
5534  // harder to parse back into a large integer, etc - so punting on
5535  // this for now. Re-parsing the integers back into APInt is
5536  // probably feasible some day.
5537  return TA.getAsIntegral().getBitWidth() <= 64 &&
5538  IsReconstitutableType(TA.getIntegralType());
5539  case TemplateArgument::StructuralValue:
5540  return false;
5541  case TemplateArgument::Type:
5542  return IsReconstitutableType(TA.getAsType());
5543  case TemplateArgument::Expression:
5544  return IsReconstitutableType(TA.getAsExpr()->getType());
5545  default:
5546  llvm_unreachable("Other, unresolved, template arguments should "
5547  "not be seen here");
5548  }
5549  });
5550 }
5551 
5552 std::string CGDebugInfo::GetName(const Decl *D, bool Qualified) const {
5553  std::string Name;
5554  llvm::raw_string_ostream OS(Name);
5555  const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5556  if (!ND)
5557  return Name;
5558  llvm::codegenoptions::DebugTemplateNamesKind TemplateNamesKind =
5559  CGM.getCodeGenOpts().getDebugSimpleTemplateNames();
5560 
5561  if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
5562  TemplateNamesKind = llvm::codegenoptions::DebugTemplateNamesKind::Full;
5563 
5564  std::optional<TemplateArgs> Args;
5565 
5566  bool IsOperatorOverload = false; // isa<CXXConversionDecl>(ND);
5567  if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
5568  Args = GetTemplateArgs(RD);
5569  } else if (auto *FD = dyn_cast<FunctionDecl>(ND)) {
5570  Args = GetTemplateArgs(FD);
5571  auto NameKind = ND->getDeclName().getNameKind();
5572  IsOperatorOverload |=
5573  NameKind == DeclarationName::CXXOperatorName ||
5575  } else if (auto *VD = dyn_cast<VarDecl>(ND)) {
5576  Args = GetTemplateArgs(VD);
5577  }
5578 
5579  // A conversion operator presents complications/ambiguity if there's a
5580  // conversion to class template that is itself a template, eg:
5581  // template<typename T>
5582  // operator ns::t1<T, int>();
5583  // This should be named, eg: "operator ns::t1<float, int><float>"
5584  // (ignoring clang bug that means this is currently "operator t1<float>")
5585  // but if the arguments were stripped, the consumer couldn't differentiate
5586  // whether the template argument list for the conversion type was the
5587  // function's argument list (& no reconstitution was needed) or not.
5588  // This could be handled if reconstitutable names had a separate attribute
5589  // annotating them as such - this would remove the ambiguity.
5590  //
5591  // Alternatively the template argument list could be parsed enough to check
5592  // whether there's one list or two, then compare that with the DWARF
5593  // description of the return type and the template argument lists to determine
5594  // how many lists there should be and if one is missing it could be assumed(?)
5595  // to be the function's template argument list & then be rebuilt.
5596  //
5597  // Other operator overloads that aren't conversion operators could be
5598  // reconstituted but would require a bit more nuance about detecting the
5599  // difference between these different operators during that rebuilding.
5600  bool Reconstitutable =
5601  Args && HasReconstitutableArgs(Args->Args) && !IsOperatorOverload;
5602 
5603  PrintingPolicy PP = getPrintingPolicy();
5604 
5605  if (TemplateNamesKind == llvm::codegenoptions::DebugTemplateNamesKind::Full ||
5606  !Reconstitutable) {
5607  ND->getNameForDiagnostic(OS, PP, Qualified);
5608  } else {
5609  bool Mangled = TemplateNamesKind ==
5610  llvm::codegenoptions::DebugTemplateNamesKind::Mangled;
5611  // check if it's a template
5612  if (Mangled)
5613  OS << "_STN|";
5614 
5615  OS << ND->getDeclName();
5616  std::string EncodedOriginalName;
5617  llvm::raw_string_ostream EncodedOriginalNameOS(EncodedOriginalName);
5618  EncodedOriginalNameOS << ND->getDeclName();
5619 
5620  if (Mangled) {
5621  OS << "|";
5622  printTemplateArgumentList(OS, Args->Args, PP);
5623  printTemplateArgumentList(EncodedOriginalNameOS, Args->Args, PP);
5624 #ifndef NDEBUG
5625  std::string CanonicalOriginalName;
5626  llvm::raw_string_ostream OriginalOS(CanonicalOriginalName);
5627  ND->getNameForDiagnostic(OriginalOS, PP, Qualified);
5628  assert(EncodedOriginalNameOS.str() == OriginalOS.str());
5629 #endif
5630  }
5631  }
5632  return Name;
5633 }
5634 
5635 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
5636  const VarDecl *D) {
5637  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5638  if (D->hasAttr<NoDebugAttr>() || noSystemDebugInfo(D, CGM))
5639  return;
5640 
5641  llvm::TimeTraceScope TimeScope("DebugGlobalVariable", [&]() {
5642  return GetName(D, true);
5643  });
5644 
5645  // If we already created a DIGlobalVariable for this declaration, just attach
5646  // it to the llvm::GlobalVariable.
5647  auto Cached = DeclCache.find(D->getCanonicalDecl());
5648  if (Cached != DeclCache.end())
5649  return Var->addDebugInfo(
5650  cast<llvm::DIGlobalVariableExpression>(Cached->second));
5651 
5652  // Create global variable debug descriptor.
5653  llvm::DIFile *Unit = nullptr;
5654  llvm::DIScope *DContext = nullptr;
5655  unsigned LineNo;
5656  StringRef DeclName, LinkageName;
5657  QualType T;
5658  llvm::MDTuple *TemplateParameters = nullptr;
5659  collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName,
5660  TemplateParameters, DContext);
5661 
5662  // Attempt to store one global variable for the declaration - even if we
5663  // emit a lot of fields.
5664  llvm::DIGlobalVariableExpression *GVE = nullptr;
5665 
5666  // If this is an anonymous union then we'll want to emit a global
5667  // variable for each member of the anonymous union so that it's possible
5668  // to find the name of any field in the union.
5669  if (T->isUnionType() && DeclName.empty()) {
5670  const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
5671  assert(RD->isAnonymousStructOrUnion() &&
5672  "unnamed non-anonymous struct or union?");
5673  GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
5674  } else {
5675  auto Align = getDeclAlignIfRequired(D, CGM.getContext());
5676 
5678  unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(D->getType());
5679  if (CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) {
5680  if (D->hasAttr<CUDASharedAttr>())
5681  AddressSpace =
5682  CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared);
5683  else if (D->hasAttr<CUDAConstantAttr>())
5684  AddressSpace =
5685  CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
5686  }
5687  AppendAddressSpaceXDeref(AddressSpace, Expr);
5688 
5689  llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
5690  GVE = DBuilder.createGlobalVariableExpression(
5691  DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
5692  Var->hasLocalLinkage(), true,
5693  Expr.empty() ? nullptr : DBuilder.createExpression(Expr),
5694  getOrCreateStaticDataMemberDeclarationOrNull(D), TemplateParameters,
5695  Align, Annotations);
5696  Var->addDebugInfo(GVE);
5697  }
5698  DeclCache[D->getCanonicalDecl()].reset(GVE);
5699 }
5700 
5701 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) {
5702  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5703  if (VD->hasAttr<NoDebugAttr>() || noSystemDebugInfo(VD, CGM))
5704  return;
5705  llvm::TimeTraceScope TimeScope("DebugConstGlobalVariable", [&]() {
5706  return GetName(VD, true);
5707  });
5708 
5709  auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
5710  // Create the descriptor for the variable.
5711  llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
5712  StringRef Name = VD->getName();
5713  llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
5714 
5715  if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) {
5716  const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
5717  assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
5718 
5719  if (CGM.getCodeGenOpts().EmitCodeView) {
5720  // If CodeView, emit enums as global variables, unless they are defined
5721  // inside a class. We do this because MSVC doesn't emit S_CONSTANTs for
5722  // enums in classes, and because it is difficult to attach this scope
5723  // information to the global variable.
5724  if (isa<RecordDecl>(ED->getDeclContext()))
5725  return;
5726  } else {
5727  // If not CodeView, emit DW_TAG_enumeration_type if necessary. For
5728  // example: for "enum { ZERO };", a DW_TAG_enumeration_type is created the
5729  // first time `ZERO` is referenced in a function.
5730  llvm::DIType *EDTy =
5731  getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
5732  assert (EDTy->getTag() == llvm::dwarf::DW_TAG_enumeration_type);
5733  (void)EDTy;
5734  return;
5735  }
5736  }
5737 
5738  // Do not emit separate definitions for function local consts.
5739  if (isa<FunctionDecl>(VD->getDeclContext()))
5740  return;
5741 
5742  VD = cast<ValueDecl>(VD->getCanonicalDecl());
5743  auto *VarD = dyn_cast<VarDecl>(VD);
5744  if (VarD && VarD->isStaticDataMember()) {
5745  auto *RD = cast<RecordDecl>(VarD->getDeclContext());
5746  getDeclContextDescriptor(VarD);
5747  // Ensure that the type is retained even though it's otherwise unreferenced.
5748  //
5749  // FIXME: This is probably unnecessary, since Ty should reference RD
5750  // through its scope.
5751  RetainedTypes.push_back(
5752  CGM.getContext().getRecordType(RD).getAsOpaquePtr());
5753 
5754  return;
5755  }
5756  llvm::DIScope *DContext = getDeclContextDescriptor(VD);
5757 
5758  auto &GV = DeclCache[VD];
5759  if (GV)
5760  return;
5761 
5762  llvm::DIExpression *InitExpr = createConstantValueExpression(VD, Init);
5763  llvm::MDTuple *TemplateParameters = nullptr;
5764 
5765  if (isa<VarTemplateSpecializationDecl>(VD))
5766  if (VarD) {
5767  llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VarD, &*Unit);
5768  TemplateParameters = parameterNodes.get();
5769  }
5770 
5771  GV.reset(DBuilder.createGlobalVariableExpression(
5772  DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
5773  true, true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD),
5774  TemplateParameters, Align));
5775 }
5776 
5777 void CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable *Var,
5778  const VarDecl *D) {
5779  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5780  if (D->hasAttr<NoDebugAttr>() || noSystemDebugInfo(D, CGM))
5781  return;
5782 
5783  auto Align = getDeclAlignIfRequired(D, CGM.getContext());
5784  llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
5785  StringRef Name = D->getName();
5786  llvm::DIType *Ty = getOrCreateType(D->getType(), Unit);
5787 
5788  llvm::DIScope *DContext = getDeclContextDescriptor(D);
5789  llvm::DIGlobalVariableExpression *GVE =
5790  DBuilder.createGlobalVariableExpression(
5791  DContext, Name, StringRef(), Unit, getLineNumber(D->getLocation()),
5792  Ty, false, false, nullptr, nullptr, nullptr, Align);
5793  Var->addDebugInfo(GVE);
5794 }
5795 
5796 void CGDebugInfo::EmitGlobalAlias(const llvm::GlobalValue *GV,
5797  const GlobalDecl GD) {
5798 
5799  assert(GV);
5800 
5801  if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
5802  return;
5803 
5804  const auto *D = cast<ValueDecl>(GD.getDecl());
5805  if (D->hasAttr<NoDebugAttr>() || noSystemDebugInfo(D, CGM))
5806  return;
5807 
5808  auto AliaseeDecl = CGM.getMangledNameDecl(GV->getName());
5809  llvm::DINode *DI;
5810 
5811  if (!AliaseeDecl)
5812  // FIXME: Aliasee not declared yet - possibly declared later
5813  // For example,
5814  //
5815  // 1 extern int newname __attribute__((alias("oldname")));
5816  // 2 int oldname = 1;
5817  //
5818  // No debug info would be generated for 'newname' in this case.
5819  //
5820  // Fix compiler to generate "newname" as imported_declaration
5821  // pointing to the DIE of "oldname".
5822  return;
5823  if (!(DI = getDeclarationOrDefinition(
5824  AliaseeDecl.getCanonicalDecl().getDecl())))
5825  return;
5826 
5827  llvm::DIScope *DContext = getDeclContextDescriptor(D);
5828  auto Loc = D->getLocation();
5829 
5830  llvm::DIImportedEntity *ImportDI = DBuilder.createImportedDeclaration(
5831  DContext, DI, getOrCreateFile(Loc), getLineNumber(Loc), D->getName());
5832 
5833  // Record this DIE in the cache for nested declaration reference.
5834  ImportedDeclCache[GD.getCanonicalDecl().getDecl()].reset(ImportDI);
5835 }
5836 
5837 void CGDebugInfo::AddStringLiteralDebugInfo(llvm::GlobalVariable *GV,
5838  const StringLiteral *S) {
5839  SourceLocation Loc = S->getStrTokenLoc(0);
5840  PresumedLoc PLoc = CGM.getContext().getSourceManager().getPresumedLoc(Loc);
5841  if (!PLoc.isValid())
5842  return;
5843 
5844  llvm::DIFile *File = getOrCreateFile(Loc);
5845  llvm::DIGlobalVariableExpression *Debug =
5846  DBuilder.createGlobalVariableExpression(
5847  nullptr, StringRef(), StringRef(), getOrCreateFile(Loc),
5848  getLineNumber(Loc), getOrCreateType(S->getType(), File), true);
5849  GV->addDebugInfo(Debug);
5850 }
5851 
5852 llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
5853  if (!LexicalBlockStack.empty())
5854  return LexicalBlockStack.back();
5855  llvm::DIScope *Mod = getParentModuleOrNull(D);
5856  return getContextDescriptor(D, Mod ? Mod : TheCU);
5857 }
5858 
5859 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
5860  if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
5861  return;
5862  if (noSystemDebugInfo(&UD, CGM))
5863  return;
5864  const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
5865  if (!NSDecl->isAnonymousNamespace() ||
5866  CGM.getCodeGenOpts().DebugExplicitImport) {
5867  auto Loc = UD.getLocation();
5868  if (!Loc.isValid())
5869  Loc = CurLoc;
5870  DBuilder.createImportedModule(
5871  getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
5872  getOrCreateNamespace(NSDecl), getOrCreateFile(Loc), getLineNumber(Loc));
5873  }
5874 }
5875 
5876 void CGDebugInfo::EmitUsingShadowDecl(const UsingShadowDecl &USD) {
5877  if (llvm::DINode *Target =
5878  getDeclarationOrDefinition(USD.getUnderlyingDecl())) {
5879  auto Loc = USD.getLocation();
5880  DBuilder.createImportedDeclaration(
5881  getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
5882  getOrCreateFile(Loc), getLineNumber(Loc));
5883  }
5884 }
5885 
5886 void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
5887  if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
5888  return;
5889  if (noSystemDebugInfo(&UD, CGM))
5890  return;
5891  assert(UD.shadow_size() &&
5892  "We shouldn't be codegening an invalid UsingDecl containing no decls");
5893 
5894  for (const auto *USD : UD.shadows()) {
5895  // FIXME: Skip functions with undeduced auto return type for now since we
5896  // don't currently have the plumbing for separate declarations & definitions
5897  // of free functions and mismatched types (auto in the declaration, concrete
5898  // return type in the definition)
5899  if (const auto *FD = dyn_cast<FunctionDecl>(USD->getUnderlyingDecl()))
5900  if (const auto *AT = FD->getType()
5901  ->castAs<FunctionProtoType>()
5903  if (AT->getDeducedType().isNull())
5904  continue;
5905 
5906  EmitUsingShadowDecl(*USD);
5907  // Emitting one decl is sufficient - debuggers can detect that this is an
5908  // overloaded name & provide lookup for all the overloads.
5909  break;
5910  }
5911 }
5912 
5913 void CGDebugInfo::EmitUsingEnumDecl(const UsingEnumDecl &UD) {
5914  if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
5915  return;
5916  if (noSystemDebugInfo(&UD, CGM))
5917  return;
5918  assert(UD.shadow_size() &&
5919  "We shouldn't be codegening an invalid UsingEnumDecl"
5920  " containing no decls");
5921 
5922  for (const auto *USD : UD.shadows())
5923  EmitUsingShadowDecl(*USD);
5924 }
5925 
5926 void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) {
5927  if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)
5928  return;
5929  if (Module *M = ID.getImportedModule()) {
5930  auto Info = ASTSourceDescriptor(*M);
5931  auto Loc = ID.getLocation();
5932  DBuilder.createImportedDeclaration(
5933  getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
5934  getOrCreateModuleRef(Info, DebugTypeExtRefs), getOrCreateFile(Loc),
5935  getLineNumber(Loc));
5936  }
5937 }
5938 
5939 llvm::DIImportedEntity *
5940 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
5941  if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
5942  return nullptr;
5943  if (noSystemDebugInfo(&NA, CGM))
5944  return nullptr;
5945  auto &VH = NamespaceAliasCache[&NA];
5946  if (VH)
5947  return cast<llvm::DIImportedEntity>(VH);
5948  llvm::DIImportedEntity *R;
5949  auto Loc = NA.getLocation();
5950  if (const auto *Underlying =
5951  dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
5952  // This could cache & dedup here rather than relying on metadata deduping.
5953  R = DBuilder.createImportedDeclaration(
5954  getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
5955  EmitNamespaceAlias(*Underlying), getOrCreateFile(Loc),
5956  getLineNumber(Loc), NA.getName());
5957  else
5958  R = DBuilder.createImportedDeclaration(
5959  getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
5960  getOrCreateNamespace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
5961  getOrCreateFile(Loc), getLineNumber(Loc), NA.getName());
5962  VH.reset(R);
5963  return R;
5964 }
5965 
5966 llvm::DINamespace *
5967 CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) {
5968  // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued
5969  // if necessary, and this way multiple declarations of the same namespace in
5970  // different parent modules stay distinct.
5971  auto I = NamespaceCache.find(NSDecl);
5972  if (I != NamespaceCache.end())
5973  return cast<llvm::DINamespace>(I->second);
5974 
5975  llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);
5976  // Don't trust the context if it is a DIModule (see comment above).
5977  llvm::DINamespace *NS =
5978  DBuilder.createNameSpace(Context, NSDecl->getName(), NSDecl->isInline());
5979  NamespaceCache[NSDecl].reset(NS);
5980  return NS;
5981 }
5982 
5983 void CGDebugInfo::setDwoId(uint64_t Signature) {
5984  assert(TheCU && "no main compile unit");
5985  TheCU->setDWOId(Signature);
5986 }
5987 
5989  // Creating types might create further types - invalidating the current
5990  // element and the size(), so don't cache/reference them.
5991  for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
5992  ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
5993  llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
5994  ? CreateTypeDefinition(E.Type, E.Unit)
5995  : E.Decl;
5996  DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
5997  }
5998 
5999  // Add methods to interface.
6000  for (const auto &P : ObjCMethodCache) {
6001  if (P.second.empty())
6002  continue;
6003 
6004  QualType QTy(P.first->getTypeForDecl(), 0);
6005  auto It = TypeCache.find(QTy.getAsOpaquePtr());
6006  assert(It != TypeCache.end());
6007 
6008  llvm::DICompositeType *InterfaceDecl =
6009  cast<llvm::DICompositeType>(It->second);
6010 
6011  auto CurElts = InterfaceDecl->getElements();
6012  SmallVector<llvm::Metadata *, 16> EltTys(CurElts.begin(), CurElts.end());
6013 
6014  // For DWARF v4 or earlier, only add objc_direct methods.
6015  for (auto &SubprogramDirect : P.second)
6016  if (CGM.getCodeGenOpts().DwarfVersion >= 5 || SubprogramDirect.getInt())
6017  EltTys.push_back(SubprogramDirect.getPointer());
6018 
6019  llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
6020  DBuilder.replaceArrays(InterfaceDecl, Elements);
6021  }
6022 
6023  for (const auto &P : ReplaceMap) {
6024  assert(P.second);
6025  auto *Ty = cast<llvm::DIType>(P.second);
6026  assert(Ty->isForwardDecl());
6027 
6028  auto It = TypeCache.find(P.first);
6029  assert(It != TypeCache.end());
6030  assert(It->second);
6031 
6032  DBuilder.replaceTemporary(llvm::TempDIType(Ty),
6033  cast<llvm::DIType>(It->second));
6034  }
6035 
6036  for (const auto &P : FwdDeclReplaceMap) {
6037  assert(P.second);
6038  llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(P.second));
6039  llvm::Metadata *Repl;
6040 
6041  auto It = DeclCache.find(P.first);
6042  // If there has been no definition for the declaration, call RAUW
6043  // with ourselves, that will destroy the temporary MDNode and
6044  // replace it with a standard one, avoiding leaking memory.
6045  if (It == DeclCache.end())
6046  Repl = P.second;
6047  else
6048  Repl = It->second;
6049 
6050  if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Repl))
6051  Repl = GVE->getVariable();
6052  DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
6053  }
6054 
6055  // We keep our own list of retained types, because we need to look
6056  // up the final type in the type cache.
6057  for (auto &RT : RetainedTypes)
6058  if (auto MD = TypeCache[RT])
6059  DBuilder.retainType(cast<llvm::DIType>(MD));
6060 
6061  DBuilder.finalize();
6062 }
6063 
6064 // Don't ignore in case of explicit cast where it is referenced indirectly.
6065 void CGDebugInfo::EmitExplicitCastType(QualType Ty) {
6066  if (CGM.getCodeGenOpts().hasReducedDebugInfo())
6067  if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
6068  DBuilder.retainType(DieTy);
6069 }
6070 
6071 void CGDebugInfo::EmitAndRetainType(QualType Ty) {
6072  if (CGM.getCodeGenOpts().hasMaybeUnusedDebugInfo())
6073  if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
6074  DBuilder.retainType(DieTy);
6075 }
6076 
6077 llvm::DebugLoc CGDebugInfo::SourceLocToDebugLoc(SourceLocation Loc) {
6078  if (LexicalBlockStack.empty())
6079  return llvm::DebugLoc();
6080 
6081  llvm::MDNode *Scope = LexicalBlockStack.back();
6082  return llvm::DILocation::get(CGM.getLLVMContext(), getLineNumber(Loc),
6083  getColumnNumber(Loc), Scope);
6084 }
6085 
6086 llvm::DINode::DIFlags CGDebugInfo::getCallSiteRelatedAttrs() const {
6087  // Call site-related attributes are only useful in optimized programs, and
6088  // when there's a possibility of debugging backtraces.
6089  if (!CGM.getLangOpts().Optimize ||
6090  DebugKind == llvm::codegenoptions::NoDebugInfo ||
6091  DebugKind == llvm::codegenoptions::LocTrackingOnly)
6092  return llvm::DINode::FlagZero;
6093 
6094  // Call site-related attributes are available in DWARF v5. Some debuggers,
6095  // while not fully DWARF v5-compliant, may accept these attributes as if they
6096  // were part of DWARF v4.
6097  bool SupportsDWARFv4Ext =
6098  CGM.getCodeGenOpts().DwarfVersion == 4 &&
6099  (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB ||
6100  CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::GDB);
6101 
6102  if (!SupportsDWARFv4Ext && CGM.getCodeGenOpts().DwarfVersion < 5)
6103  return llvm::DINode::FlagZero;
6104 
6105  return llvm::DINode::FlagAllCallsDescribed;
6106 }
6107 
6108 llvm::DIExpression *
6109 CGDebugInfo::createConstantValueExpression(const clang::ValueDecl *VD,
6110  const APValue &Val) {
6111  // FIXME: Add a representation for integer constants wider than 64 bits.
6112  if (CGM.getContext().getTypeSize(VD->getType()) > 64)
6113  return nullptr;
6114 
6115  if (Val.isFloat())
6116  return DBuilder.createConstantValueExpression(
6117  Val.getFloat().bitcastToAPInt().getZExtValue());
6118 
6119  if (!Val.isInt())
6120  return nullptr;
6121 
6122  llvm::APSInt const &ValInt = Val.getInt();
6123  std::optional<uint64_t> ValIntOpt;
6124  if (ValInt.isUnsigned())
6125  ValIntOpt = ValInt.tryZExtValue();
6126  else if (auto tmp = ValInt.trySExtValue())
6127  // Transform a signed optional to unsigned optional. When cpp 23 comes,
6128  // use std::optional::transform
6129  ValIntOpt = static_cast<uint64_t>(*tmp);
6130 
6131  if (ValIntOpt)
6132  return DBuilder.createConstantValueExpression(ValIntOpt.value());
6133 
6134  return nullptr;
6135 }
6136 
6138  const CodeGenModule &CGM) {
6139  // Declaration is in system file
6141  // Make an exception for typedefs in system header files. Generate debug
6142  // information for these decls because these are rare (thus they will not
6143  // greatly increase debug size) and a user could rely on these typedefs
6144  // during debugging. For example uid_t in in "sys/types.h" can be used in
6145  // the gdb command:
6146  //
6147  // print ruid == (uid_t)-1
6148  //
6149  // This occurs in GDB test gdb.reverse/getresuid-reverse.c
6150  if (isa<TypedefDecl>(D))
6151  return false;
6152 
6153  // -fno-system-debug was used. Do not generate debug info.
6154  if (CGM.getCodeGenOpts().NoSystemDebug)
6155  return true;
6156  }
6157  return false;
6158 }
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3299
NodeId Parent
Definition: ASTDiff.cpp:191
StringRef P
static char ID
Definition: Arena.cpp:183
#define SM(sm)
Definition: Cuda.cpp:83
llvm::APSInt APSInt
static bool IsReconstitutableType(QualType QT)
static void stripUnusedQualifiers(Qualifiers &Q)
static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU)
static bool needsTypeIdentifier(const TagDecl *TD, CodeGenModule &CGM, llvm::DICompileUnit *TheCU)
static bool shouldOmitDefinition(llvm::codegenoptions::DebugInfoKind DebugKind, bool DebugTypeExtRefs, const RecordDecl *RD, const LangOptions &LangOpts)
static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access, const RecordDecl *RD)
Convert an AccessSpecifier into the corresponding DINode flag.
static llvm::DINode::DIFlags getRefFlags(const FunctionProtoType *Func)
static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C)
static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD)
static bool isFunctionLocalClass(const CXXRecordDecl *RD)
isFunctionLocalClass - Return true if CXXRecordDecl is defined inside a function.
static uint32_t getDeclAlignIfRequired(const Decl *D, const ASTContext &Ctx)
Definition: CGDebugInfo.cpp:68
static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I, CXXRecordDecl::method_iterator End)
static bool canUseCtorHoming(const CXXRecordDecl *RD)
static bool hasDefaultGetterName(const ObjCPropertyDecl *PD, const ObjCMethodDecl *Getter)
static bool isClassOrMethodDLLImport(const CXXRecordDecl *RD)
Return true if the class or any of its methods are marked dllimport.
static SmallString< 256 > getTypeIdentifier(const TagType *Ty, CodeGenModule &CGM, llvm::DICompileUnit *TheCU)
static uint32_t getTypeAlignIfRequired(const Type *Ty, const ASTContext &Ctx)
Definition: CGDebugInfo.cpp:59
static bool hasDefaultSetterName(const ObjCPropertyDecl *PD, const ObjCMethodDecl *Setter)
static bool isDefinedInClangModule(const RecordDecl *RD)
Does a type definition exist in an imported clang module?
static llvm::dwarf::Tag getNextQualifier(Qualifiers &Q)
static llvm::SmallVector< TemplateArgument > GetTemplateArgs(const TemplateDecl *TD, const TemplateSpecializationType *Ty)
FileID ComputeValidFileID(SourceManager &SM, StringRef FileName)
static unsigned getDwarfCC(CallingConv CC)
static bool ReferencesAnonymousEntity(ArrayRef< TemplateArgument > Args)
Defines the C++ template declaration subclasses.
Defines the clang::FileManager interface and associated types.
unsigned Offset
Definition: Format.cpp:2978
StringRef Identifier
Definition: Format.cpp:2984
const CFGBlock * Block
Definition: HTMLLogger.cpp:153
unsigned Iter
Definition: HTMLLogger.cpp:154
llvm::MachO::Target Target
Definition: MachO.h:50
llvm::MachO::Record Record
Definition: MachO.h:31
static ParseState advance(ParseState S, size_t N)
Definition: Parsing.cpp:144
static const NamedDecl * getDefinition(const Decl *D)
Definition: SemaDecl.cpp:3023
SourceLocation Loc
Definition: SemaObjC.cpp:755
target
Definition: SemaSYCL.cpp:45
Defines the SourceManager interface.
const char * Data
SourceLocation End
Defines version macros and version-related utility functions for Clang.
__device__ __2f16 float c
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
APFloat & getFloat()
Definition: APValue.h:437
bool isFloat() const
Definition: APValue.h:402
bool isInt() const
Definition: APValue.h:401
APSInt & getInt()
Definition: APValue.h:423
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:185
bool getByrefLifetime(QualType Ty, Qualifiers::ObjCLifetime &Lifetime, bool &HasByrefExtendedLayout) const
Returns true, if given type has a known lifetime.
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:700
SourceManager & getSourceManager()
Definition: ASTContext.h:708
TypedefNameDecl * getTypedefNameForUnnamedTagDecl(const TagDecl *TD)
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl.
QualType getRecordType(const RecordDecl *Decl) const
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
QualType getEnumType(const EnumDecl *Decl) const
CanQualType VoidPtrTy
Definition: ASTContext.h:1121
QualType getBlockDescriptorExtendedType() const
Gets the struct used to keep track of the extended descriptor for pointer to blocks.
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
bool BlockRequiresCopying(QualType Ty, const VarDecl *D)
Returns true iff we need copy/dispose helpers for the given type.
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1605
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.
QualType getObjCInstanceType()
Retrieve the Objective-C "instancetype" type, if already known; otherwise, returns a NULL type;.
Definition: ASTContext.h:1959
const ASTRecordLayout & getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const
Get or compute information about the layout of the specified Objective-C interface.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
CanQualType BoolTy
Definition: ASTContext.h:1095
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth,...
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C 'SEL' type.
Definition: ASTContext.h:2088
CanQualType UnsignedLongTy
Definition: ASTContext.h:1104
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
CanQualType CharTy
Definition: ASTContext.h:1096
QualType getBlockDescriptorType() const
Gets the struct used to keep track of the descriptor for pointer to blocks.
CanQualType IntTy
Definition: ASTContext.h:1103
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2171
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.
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2078
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2355
CanQualType VoidTy
Definition: ASTContext.h:1094
CanQualType UnsignedCharTy
Definition: ASTContext.h:1104
DeclaratorDecl * getDeclaratorForUnnamedTagDecl(const TagDecl *TD)
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
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.
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1076
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Definition: ASTContext.h:2386
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2359
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
const CXXRecordDecl * getPrimaryBase() const
getPrimaryBase - Get the primary base for this record.
Definition: RecordLayout.h:234
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:200
CharUnits getVBPtrOffset() const
getVBPtrOffset - Get the offset for virtual base table pointer.
Definition: RecordLayout.h:324
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:249
bool hasExtendableVFPtr() const
hasVFPtr - Does this class have a virtual function table pointer that can be extended by a derived cl...
Definition: RecordLayout.h:288
bool isPrimaryBaseVirtual() const
isPrimaryBaseVirtual - Get whether the primary base for this record is virtual or not.
Definition: RecordLayout.h:242
Abstracts clang modules and precompiled header files and holds everything needed to generate debug in...
Definition: Module.h:874
ASTFileSignature getSignature() const
Definition: Module.h:892
std::string getModuleName() const
Definition: Module.cpp:736
StringRef getASTFile() const
Definition: Module.h:891
Module * getModuleOrNull() const
Definition: Module.h:893
StringRef getPath() const
Definition: Module.h:890
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2716
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3530
QualType getElementType() const
Definition: Type.h:3542
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:7201
unsigned shadow_size() const
Return the number of shadowed declarations associated with this using declaration.
Definition: DeclCXX.h:3495
shadow_range shadows() const
Definition: DeclCXX.h:3483
A binding in a decomposition declaration.
Definition: DeclCXX.h:4107
Expr * getBinding() const
Get the expression to which this declaration is bound.
Definition: DeclCXX.h:4131
A fixed int type of a specified bitwidth.
Definition: Type.h:7254
bool isUnsigned() const
Definition: Type.h:7264
A class which contains all the information about a particular captured value.
Definition: Decl.h:4503
VarDecl * getVariable() const
The variable being captured.
Definition: Decl.h:4524
bool isByRef() const
Whether this is a "by ref" capture, i.e.
Definition: Decl.h:4528
Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
Definition: Decl.h:4518
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4497
Pointer to a block type.
Definition: Type.h:3361
QualType getPointeeType() const
Definition: Type.h:3373
This class is used for builtin types like 'int'.
Definition: Type.h:2989
Kind getKind() const
Definition: Type.h:3035
StringRef getName(const PrintingPolicy &Policy) const
Definition: Type.cpp:3302
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2535
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
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
unsigned size_overridden_methods() const
Definition: DeclCXX.cpp:2528
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition: DeclCXX.h:2236
QualType getThisType() const
Return the type of the this pointer.
Definition: DeclCXX.cpp:2565
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2156
bool isStatic() const
Definition: DeclCXX.cpp:2186
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool isAggregate() const
Determine whether this class is an aggregate (C++ [dcl.init.aggr]), which is a class with no user-dec...
Definition: DeclCXX.h:1147
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1241
base_class_range bases()
Definition: DeclCXX.h:619
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1022
capture_const_iterator captures_end() const
Definition: DeclCXX.h:1111
method_range methods() const
Definition: DeclCXX.h:661
bool hasConstexprNonCopyMoveConstructor() const
Determine whether this class has at least one constexpr constructor other than the copy or move const...
Definition: DeclCXX.h:1256
method_iterator method_begin() const
Method begin iterator.
Definition: DeclCXX.h:667
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1905
base_class_range vbases()
Definition: DeclCXX.h:636
ctor_range ctors() const
Definition: DeclCXX.h:681
bool isDynamicClass() const
Definition: DeclCXX.h:585
MSInheritanceModel getMSInheritanceModel() const
Returns the inheritance model used for this record.
bool hasDefinition() const
Definition: DeclCXX.h:571
method_iterator method_end() const
Method past-the-end iterator.
Definition: DeclCXX.h:672
capture_const_iterator captures_begin() const
Definition: DeclCXX.h:1105
llvm::iterator_range< base_class_const_iterator > base_class_const_range
Definition: DeclCXX.h:617
A wrapper class around a pointer that always points to its canonical declaration.
Definition: Redeclarable.h:349
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isPositive() const
isPositive - Test whether the quantity is greater than zero.
Definition: CharUnits.h:128
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
CharUnits alignTo(const CharUnits &Align) const
alignTo - Returns the next integer (mod 2**64) that is greater than or equal to this quantity and is ...
Definition: CharUnits.h:201
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
Represents a class template specialization, which refers to a class template with a given set of temp...
llvm::SmallVector< std::pair< std::string, std::string >, 0 > DebugPrefixMap
std::string CoverageNotesFile
The filename with path we use for coverage notes files.
std::string CoverageDataFile
The filename with path we use for coverage data files.
std::string DebugCompilationDir
The string to embed in debug information as the current working directory.
bool hasReducedDebugInfo() const
Check if type and variable info should be emitted.
ApplyInlineDebugLocation(CodeGenFunction &CGF, GlobalDecl InlinedFn)
Set up the CodeGenFunction's DebugInfo to produce inline locations for the function InlinedFn.
~ApplyInlineDebugLocation()
Restore everything back to the original state.
CGBlockInfo - Information to generate a block literal.
Definition: CGBlocks.h:156
unsigned CXXThisIndex
The field index of 'this' within the block, if there is one.
Definition: CGBlocks.h:162
const BlockDecl * getBlockDecl() const
Definition: CGBlocks.h:305
llvm::StructType * StructureType
Definition: CGBlocks.h:276
const Capture & getCapture(const VarDecl *var) const
Definition: CGBlocks.h:296
virtual CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD)
Get the ABI-specific "this" parameter adjustment to apply in the prologue of a virtual function.
Definition: CGCXXABI.h:416
@ RAA_Indirect
Pass it as a pointer to temporary memory.
Definition: CGCXXABI.h:161
virtual llvm::Constant * EmitNullMemberPointer(const MemberPointerType *MPT)
Create a null member pointer of the given type.
Definition: CGCXXABI.cpp:105
MangleContext & getMangleContext()
Gets the mangle context.
Definition: CGCXXABI.h:113
virtual RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const =0
Returns how an argument of the given record type should be passed.
virtual llvm::Constant * EmitMemberDataPointer(const MemberPointerType *MPT, CharUnits offset)
Create a member pointer for the given field.
Definition: CGCXXABI.cpp:114
virtual llvm::Constant * EmitMemberFunctionPointer(const CXXMethodDecl *MD)
Create a member pointer for the given method.
Definition: CGCXXABI.cpp:109
llvm::DIType * getOrCreateStandaloneType(QualType Ty, SourceLocation Loc)
Emit standalone debug info for a type.
llvm::MDNode * getInlinedAt() const
Definition: CGDebugInfo.h:449
void EmitLocation(CGBuilderTy &Builder, SourceLocation Loc)
Emit metadata to indicate a change in line/column information in the source file.
void EmitLabel(const LabelDecl *D, CGBuilderTy &Builder)
Emit call to llvm.dbg.label for an label.
void setInlinedAt(llvm::MDNode *InlinedAt)
Update the current inline scope.
Definition: CGDebugInfo.h:446
void completeUnusedClass(const CXXRecordDecl &D)
void EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn)
Constructs the debug code for exiting a function.
void EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke, QualType CalleeType, const FunctionDecl *CalleeDecl)
Emit debug info for an extern function being called.
llvm::DIMacroFile * CreateTempMacroFile(llvm::DIMacroFile *Parent, SourceLocation LineLoc, SourceLocation FileLoc)
Create debug info for a file referenced by an #include directive.
void completeTemplateDefinition(const ClassTemplateSpecializationDecl &SD)
void emitFunctionStart(GlobalDecl GD, SourceLocation Loc, SourceLocation ScopeLoc, QualType FnType, llvm::Function *Fn, bool CurFnIsThunk)
Emit a call to llvm.dbg.function.start to indicate start of a new function.
llvm::DILocalVariable * EmitDeclareOfArgVariable(const VarDecl *Decl, llvm::Value *AI, unsigned ArgNo, CGBuilderTy &Builder, bool UsePointerValue=false)
Emit call to llvm.dbg.declare for an argument variable declaration.
void EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc)
Emit metadata to indicate the end of a new lexical block and pop the current block.
void completeRequiredType(const RecordDecl *RD)
void EmitInlineFunctionEnd(CGBuilderTy &Builder)
End an inlined function scope.
void EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc, QualType FnType, llvm::Function *Fn=nullptr)
Emit debug info for a function declaration.
llvm::DILocalVariable * EmitDeclareOfAutoVariable(const VarDecl *Decl, llvm::Value *AI, CGBuilderTy &Builder, const bool UsePointerValue=false)
Emit call to llvm.dbg.declare for an automatic variable declaration.
void completeClassData(const RecordDecl *RD)
void EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD)
Start a new scope for an inlined function.
void EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block, StringRef Name, unsigned ArgNo, llvm::AllocaInst *LocalAddr, CGBuilderTy &Builder)
Emit call to llvm.dbg.declare for the block-literal argument to a block invocation function.
CGDebugInfo(CodeGenModule &CGM)
Definition: CGDebugInfo.cpp:72
void completeClass(const RecordDecl *RD)
void EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc)
Emit metadata to indicate the beginning of a new lexical block and push the block onto the stack.
void setLocation(SourceLocation Loc)
Update the current source location.
llvm::DIMacro * CreateMacro(llvm::DIMacroFile *Parent, unsigned MType, SourceLocation LineLoc, StringRef Name, StringRef Value)
Create debug info for a macro defined by a #define directive or a macro undefined by a #undef directi...
llvm::DIType * getOrCreateRecordType(QualType Ty, SourceLocation L)
Emit record type's standalone debug info.
std::string remapDIPath(StringRef) const
Remap a given path with the current debug prefix map.
void addHeapAllocSiteMetadata(llvm::CallBase *CallSite, QualType AllocatedTy, SourceLocation Loc)
Add heapallocsite metadata for MSAllocator calls.
QualType getFunctionType(const FunctionDecl *FD, QualType RetTy, const SmallVectorImpl< const VarDecl * > &Args)
llvm::DIType * getOrCreateInterfaceType(QualType Ty, SourceLocation Loc)
Emit an Objective-C interface type standalone debug info.
void completeType(const EnumDecl *ED)
void EmitDeclareOfBlockDeclRefVariable(const VarDecl *variable, llvm::Value *storage, CGBuilderTy &Builder, const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint=nullptr)
Emit call to llvm.dbg.declare for an imported variable declaration in a block.
unsigned ComputeBitfieldBitOffset(CodeGen::CodeGenModule &CGM, const ObjCInterfaceDecl *ID, const ObjCIvarDecl *Ivar)
CGRecordLayout - This class handles struct and union layout info while lowering AST types to LLVM typ...
const CGBitFieldInfo & getBitFieldInfo(const FieldDecl *FD) const
Return the BitFieldInfo that corresponds to the field FD.
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
This class organizes the cross-function state that is used while generating LLVM code.
ConstantAddress GetAddrOfMSGuidDecl(const MSGuidDecl *GD)
Get the address of a GUID.
const TargetInfo & getTarget() const
CGObjCRuntime & getObjCRuntime()
Return a reference to the configured Objective-C runtime.
const llvm::DataLayout & getDataLayout() const
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.
llvm::Module & getModule() const
int getUniqueBlockCount()
Fetches the global unique block count.
const LangOptions & getLangOpts() const
llvm::LLVMContext & getLLVMContext()
CGCXXABI & getCXXABI() const
ItaniumVTableContext & getItaniumVTableContext()
ConstantAddress GetAddrOfTemplateParamObject(const TemplateParamObjectDecl *TPO)
Get the address of a template parameter object.
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.
const TargetCodeGenInfo & getTargetCodeGenInfo()
StringRef getMangledName(GlobalDecl GD)
const IntrusiveRefCntPtr< llvm::vfs::FileSystem > & getFileSystem() const
ASTContext & getContext() const
const CodeGenOptions & getCodeGenOpts() const
llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD)
Return the appropriate linkage for the vtable, VTT, and type information of the given class.
Definition: CGVTables.cpp:1063
MicrosoftVTableContext & getMicrosoftVTableContext()
const HeaderSearchOptions & getHeaderSearchOpts() const
const PreprocessorOptions & getPreprocessorOpts() const
const CGRecordLayout & getCGRecordLayout(const RecordDecl *)
getCGRecordLayout - Return record layout info for the given record decl.
unsigned getTargetAddressSpace(QualType T) const
llvm::Constant * getPointer() const
Definition: Address.h:272
llvm::Constant * emitAbstract(const Expr *E, QualType T)
Emit the result of the given expression as an abstract constant, asserting that it succeeded.
virtual bool shouldEmitDWARFBitFieldSeparators() const
Definition: TargetInfo.h:375
Complex values, per C99 6.2.5p11.
Definition: Type.h:3098
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:4179
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: Type.h:4200
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: Type.h:4197
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2342
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2066
bool isRecord() const
Definition: DeclBase.h:2146
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
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition: Stmt.h:1497
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
unsigned getOwningModuleID() const
Retrieve the global ID of the module that owns this particular declaration.
Definition: DeclBase.h:788
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:501
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:599
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition: DeclBase.cpp:515
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition: DeclBase.h:776
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
AccessSpecifier getAccess() const
Definition: DeclBase.h:513
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:833
bool hasAttr() const
Definition: DeclBase.h:583
T * getAttr() const
Definition: DeclBase.h:579
DeclContext * getDeclContext()
Definition: DeclBase.h:454
bool isObjCZeroArgSelector() const
Selector getObjCSelector() const
Get the Objective-C selector stored in this declaration name.
bool isObjCOneArgSelector() const
NameKind getNameKind() const
Determine what kind of name this is.
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:771
Represents an enum.
Definition: Decl.h:3870
enumerator_range enumerators() const
Definition: Decl.h:4003
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4075
EnumDecl * getDefinition() const
Definition: Decl.h:3973
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4030
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5587
EnumDecl * getDecl() const
Definition: Type.h:5594
This represents one expression.
Definition: Expr.h:110
bool isGLValue() const
Definition: Expr.h:280
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
QualType getType() const
Definition: Expr.h:142
Represents a member of a struct/union/class.
Definition: Decl.h:3060
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3151
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:4648
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
bool isInvalid() const
static InputKind getInputKindForExtension(StringRef Extension)
getInputKindForExtension - Return the appropriate input kind for a file extension.
Represents a function declaration or definition.
Definition: Decl.h:1972
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2833
bool isNoReturn() const
Determines whether this function is known to be 'noreturn', through an attribute on its declaration o...
Definition: Decl.cpp:3529
QualType getReturnType() const
Definition: Decl.h:2757
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2408
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition: Decl.cpp:4176
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3621
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2505
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4182
@ TK_FunctionTemplateSpecialization
Definition: Decl.h:1988
bool isStatic() const
Definition: Decl.h:2841
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3997
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition: Decl.h:2325
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2686
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4018
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4668
QualType desugar() const
Definition: Type.h:5135
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4908
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:4927
ArrayRef< QualType > param_types() const
Definition: Type.h:5056
unsigned getNumParams() const
Definition: Type.h:4901
QualType getParamType(unsigned i) const
Definition: Type.h:4903
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4912
FunctionTemplateDecl * getTemplate() const
Retrieve the template from which this function was specialized.
Definition: DeclTemplate.h:522
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4268
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition: Type.h:4593
CallingConv getCallConv() const
Definition: Type.h:4596
QualType getReturnType() const
Definition: Type.h:4585
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:56
GlobalDecl getCanonicalDecl() const
Definition: GlobalDecl.h:94
DynamicInitKind getDynamicInitKind() const
Definition: GlobalDecl.h:115
const Decl * getDecl() const
Definition: GlobalDecl.h:103
std::string Sysroot
If non-empty, the directory to use as a "virtual system root" for include paths.
unsigned ModuleFileHomeIsCwd
Set the base path of a built module file to be the current working directory.
One of these records is kept for each identifier that is lexed.
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition: Decl.h:4802
bool isPreprocessed() const
uint64_t getMethodVTableIndex(GlobalDecl GD)
Locate a virtual function in the vtable.
CharUnits getVirtualBaseOffsetOffset(const CXXRecordDecl *RD, const CXXRecordDecl *VBase)
Return the offset in chars (relative to the vtable address point) where the offset of the virtual bas...
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3436
Represents the declaration of a label.
Definition: Decl.h:500
Describes the capture of a variable or of this, or of a C++1y init-capture.
Definition: LambdaCapture.h:25
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:482
std::string ModuleName
The module currently being compiled as specified by -fmodule-name.
Definition: LangOptions.h:530
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:517
bool UseTargetPathSeparator
Indicates whether to use target's platform-specific file separator when FILE macro is used and when c...
Definition: LangOptions.h:600
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
virtual std::string getLambdaString(const CXXRecordDecl *Lambda)=0
virtual void mangleCXXRTTIName(QualType T, raw_ostream &, bool NormalizeIntegers=false)=0
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition: Type.h:4157
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3224
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3472
const Type * getClass() const
Definition: Type.h:3502
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Definition: Type.cpp:5013
QualType getPointeeType() const
Definition: Type.h:3488
unsigned getVBTableIndex(const CXXRecordDecl *Derived, const CXXRecordDecl *VBase)
Returns the index of VBase in the vbtable of Derived.
MethodVFTableLocation getMethodVFTableLocation(GlobalDecl GD)
const VTableLayout & getVFTableLayout(const CXXRecordDecl *RD, CharUnits VFPtrOffset)
Describes a module or submodule.
Definition: Module.h:105
Module * Parent
The parent of this module.
Definition: Module.h:154
std::string Name
The name of this module.
Definition: Module.h:108
This represents a decl that may have a name.
Definition: Decl.h:249
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Definition: Decl.h:292
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:463
virtual void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const
Appends a human-readable name for this declaration into the given stream.
Definition: Decl.cpp:1830
void printQualifiedName(raw_ostream &OS) const
Returns a human-readable qualified name for this declaration, like A::B::i, for i being member of nam...
Definition: Decl.cpp:1691
bool isExternallyVisible() const
Definition: Decl.h:409
Represents a C++ namespace alias.
Definition: DeclCXX.h:3120
NamedDecl * getAliasedNamespace() const
Retrieve the namespace that this alias refers to, which may either be a NamespaceDecl or a NamespaceA...
Definition: DeclCXX.h:3215
Represent a C++ namespace.
Definition: Decl.h:548
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition: Decl.h:606
bool isInline() const
Returns true if this is an inline namespace declaration.
Definition: Decl.h:611
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2326
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2594
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
ObjCImplementationDecl * getImplementation() const
Definition: DeclObjC.cpp:1629
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:6964
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition: Type.cpp:903
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1950
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
bool isDirectMethod() const
True if the method is tagged as objc_direct.
Definition: DeclObjC.cpp:871
Selector getSelector() const
Definition: DeclObjC.h:327
bool isInstanceMethod() const
Definition: DeclObjC.h:426
ObjCInterfaceDecl * getClassInterface()
Definition: DeclObjC.cpp:1211
Represents a pointer to an Objective C object.
Definition: Type.h:7020
bool isObjCQualifiedIdType() const
True if this is equivalent to 'id.
Definition: Type.h:7095
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7032
Represents a class type in Objective C.
Definition: Type.h:6766
QualType getBaseType() const
Gets the base type of this object type.
Definition: Type.h:6828
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:730
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition: DeclObjC.h:2802
bool isNonFragile() const
Does this runtime follow the set of implied behaviors for a "non-fragile" ABI?
Definition: ObjCRuntime.h:82
Represents a type parameter type in Objective C.
Definition: Type.h:6692
ObjCTypeParamDecl * getDecl() const
Definition: Type.h:6734
Represents a parameter to a function.
Definition: Decl.h:1762
PipeType - OpenCL20.
Definition: Type.h:7220
QualType getElementType() const
Definition: Type.h:7231
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3151
QualType getPointeeType() const
Definition: Type.h:3161
Represents an unpacked "presumed" location which can be presented to the user.
unsigned getColumn() const
Return the presumed column number of this location.
bool isValid() const
const char * getFilename() const
Return the presumed filename of this location.
bool isInvalid() const
Return true if this object is invalid or uninitialized.
FileID getFileID() const
A (possibly-)qualified type.
Definition: Type.h:940
void * getAsOpaquePtr() const
Definition: Type.h:987
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition: Type.h:1291
bool hasLocalQualifiers() const
Determine whether this particular QualType instance has any qualifiers, without looking through any t...
Definition: Type.h:1067
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
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7411
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:7311
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:7318
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition: Type.cpp:4311
The collection of all-type qualifiers we support.
Definition: Type.h:318
static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R)
Returns the common set of qualifiers while removing them from the given sets.
Definition: Type.h:370
void removeObjCLifetime()
Definition: Type.h:537
bool hasConst() const
Definition: Type.h:443
bool hasRestrict() const
Definition: Type.h:463
void removeObjCGCAttr()
Definition: Type.h:509
void removeUnaligned()
Definition: Type.h:501
void removeConst()
Definition: Type.h:445
void removeRestrict()
Definition: Type.h:465
void removeAddressSpace()
Definition: Type.h:582
bool hasVolatile() const
Definition: Type.h:453
bool empty() const
Definition: Type.h:633
void removeVolatile()
Definition: Type.h:455
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3454
Represents a struct/union/class.
Definition: Decl.h:4171
field_iterator field_end() const
Definition: Decl.h:4380
field_range fields() const
Definition: Decl.h:4377
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4362
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition: Decl.h:4223
field_iterator field_begin() const
Definition: Decl.cpp:5073
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5561
RecordDecl * getDecl() const
Definition: Type.h:5571
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:296
QualType getPointeeType() const
Definition: Type.h:3410
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
static SmallString< 64 > constructSetterName(StringRef Name)
Return the default setter name for the given identifier.
Smart pointer class that efficiently represents Objective-C method names.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
std::string getAsString() const
Derive the full selector name (e.g.
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.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID.
Stmt - This represents one statement.
Definition: Stmt.h:84
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1773
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3587
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3690
bool isStruct() const
Definition: Decl.h:3790
bool isCompleteDefinitionRequired() const
Return true if this complete decl is required to be complete for some existing use.
Definition: Decl.h:3699
bool isUnion() const
Definition: Decl.h:3793
bool isInterface() const
Definition: Decl.h:3791
bool isClass() const
Definition: Decl.h:3792
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3815
TagDecl * getDecl() const
Definition: Type.cpp:4032
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
bool isItaniumFamily() const
Does this ABI generally fall into the Itanium family of ABIs?
Definition: TargetCXXABI.h:122
virtual std::optional< unsigned > getDWARFAddressSpace(unsigned AddressSpace) const
Definition: TargetInfo.h:1773
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:472
virtual unsigned getVtblPtrAddressSpace() const
Definition: TargetInfo.h:1763
uint64_t getPointerAlign(LangAS AddrSpace) const
Definition: TargetInfo.h:476
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
A template argument list.
Definition: DeclTemplate.h:244
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:274
Represents a template argument.
Definition: TemplateBase.h:61
QualType getStructuralValueType() const
Get the type of a StructuralValue.
Definition: TemplateBase.h:399
QualType getParamTypeForDecl() const
Definition: TemplateBase.h:331
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:319
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
Definition: TemplateBase.h:444
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
Definition: TemplateBase.h:363
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
Definition: TemplateBase.h:337
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
Definition: TemplateBase.h:396
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:343
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:326
QualType getIntegralType() const
Retrieve the type of the integral value.
Definition: TemplateBase.h:377
bool getIsDefaulted() const
If returns 'true', this TemplateArgument corresponds to a default template parameter.
Definition: TemplateBase.h:393
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
Definition: TemplateBase.h:89
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:97
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:78
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:67
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:82
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:408
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
void print(raw_ostream &OS, const PrintingPolicy &Policy, Qualified Qual=Qualified::AsWritten) const
Print the template name.
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
ArrayRef< NamedDecl * > asArray()
Definition: DeclTemplate.h:139
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6101
QualType getAliasedType() const
Get the aliased type, if this is a specialization of a type alias template.
Definition: Type.cpp:4288
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:6169
TemplateName getTemplateName() const
Retrieve the name of the template that we are specializing.
Definition: Type.h:6167
bool isTypeAlias() const
Determine if this template specialization type is for a type alias template that has been substituted...
Definition: Type.h:6160
Represents a declaration of a type.
Definition: Decl.h:3393
const Type * getTypeForDecl() const
Definition: Decl.h:3417
The type-property cache.
Definition: Type.cpp:4392
The base class of the type hierarchy.
Definition: Type.h:1813
bool isVoidType() const
Definition: Type.h:7939
bool isIncompleteArrayType() const
Definition: Type.h:7698
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2766
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8227
bool isReferenceType() const
Definition: Type.h:7636
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition: Type.cpp:1866
bool isExtVectorBoolType() const
Definition: Type.h:7738
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2669
bool isMemberDataPointerType() const
Definition: Type.h:7683
bool isBitIntType() const
Definition: Type.h:7874
bool isComplexIntegerType() const
Definition: Type.cpp:683
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
TypeClass getTypeClass() const
Definition: Type.h:2300
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8160
bool isRecordType() const
Definition: Type.h:7718
bool isUnionType() const
Definition: Type.cpp:671
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3435
QualType getUnderlyingType() const
Definition: Decl.h:3490
TypedefNameDecl * getDecl() const
Definition: Type.h:5229
Represents a C++ using-declaration.
Definition: DeclCXX.h:3512
Represents C++ using-directive.
Definition: DeclCXX.h:3015
NamespaceDecl * getNominatedNamespace()
Returns the namespace nominated by this using-directive.
Definition: DeclCXX.cpp:2958
Represents a C++ using-enum-declaration.
Definition: DeclCXX.h:3713
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3320
static bool hasVtableSlot(const CXXMethodDecl *MD)
Determine whether this function should be assigned a vtable slot.
ArrayRef< VTableComponent > vtable_components() const
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
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2258
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition: Decl.cpp:2555
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1271
const Expr * getInit() const
Definition: Decl.h:1356
bool isEscapingByref() const
Indicates the capture is a __block variable that is captured by a block that can potentially escape (...
Definition: Decl.cpp:2679
Declaration of a variable template.
Represents a GCC generic vector type.
Definition: Type.h:3981
unsigned getNumElements() const
Definition: Type.h:3996
QualType getElementType() const
Definition: Type.h:3995
bool noSystemDebugInfo(const Decl *D, const CodeGenModule &CGM)
constexpr XRayInstrMask None
Definition: XRayInstr.h:38
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Decl, BlockDecl > blockDecl
Matches block declarations.
llvm::APInt APInt
Definition: Integral.h:29
RangeSelector node(std::string ID)
Selects a node, including trailing semicolon, if any (for declarations and non-expression statements)...
RangeSelector name(std::string ID)
Given a node with a "name", (like NamedDecl, DeclRefExpr, CxxCtorInitializer, and TypeLoc) selects th...
The JSON file list parser is used to communicate input to InstallAPI.
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition: Type.h:1765
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1768
bool operator<(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
bool isNoexceptExceptionSpec(ExceptionSpecificationType ESpecType)
DynamicInitKind
Definition: GlobalDecl.h:32
@ Dtor_Deleting
Deleting dtor.
Definition: ABI.h:34
const FunctionProtoType * T
void printTemplateArgumentList(raw_ostream &OS, ArrayRef< TemplateArgument > Args, const PrintingPolicy &Policy, const TemplateParameterList *TPL=nullptr)
Print a template argument list, including the '<' and '>' enclosing the template arguments.
void finalize(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema)
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:185
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:199
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:188
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
@ CC_X86Pascal
Definition: Specifiers.h:281
@ CC_Swift
Definition: Specifiers.h:290
@ CC_IntelOclBicc
Definition: Specifiers.h:287
@ CC_OpenCLKernel
Definition: Specifiers.h:289
@ CC_PreserveMost
Definition: Specifiers.h:292
@ CC_Win64
Definition: Specifiers.h:282
@ CC_X86ThisCall
Definition: Specifiers.h:279
@ CC_AArch64VectorCall
Definition: Specifiers.h:294
@ CC_AAPCS
Definition: Specifiers.h:285
@ CC_PreserveNone
Definition: Specifiers.h:298
@ CC_C
Definition: Specifiers.h:276
@ CC_AMDGPUKernelCall
Definition: Specifiers.h:296
@ CC_M68kRTD
Definition: Specifiers.h:297
@ CC_SwiftAsync
Definition: Specifiers.h:291
@ CC_X86RegCall
Definition: Specifiers.h:284
@ CC_RISCVVectorCall
Definition: Specifiers.h:299
@ CC_X86VectorCall
Definition: Specifiers.h:280
@ CC_SpirFunction
Definition: Specifiers.h:288
@ CC_AArch64SVEPCS
Definition: Specifiers.h:295
@ CC_X86StdCall
Definition: Specifiers.h:277
@ CC_X86_64SysV
Definition: Specifiers.h:283
@ CC_PreserveAll
Definition: Specifiers.h:293
@ CC_X86FastCall
Definition: Specifiers.h:278
@ CC_AAPCS_VFP
Definition: Specifiers.h:286
@ Generic
not a target-specific vector type
@ CXXThis
Parameter for C++ 'this' argument.
@ ObjCSelf
Parameter for Objective-C 'self' argument.
std::string getClangFullVersion()
Retrieves a string representing the complete clang version, which includes the clang version number,...
Definition: Version.cpp:96
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:120
@ AS_public
Definition: Specifiers.h:121
@ AS_protected
Definition: Specifiers.h:122
@ AS_none
Definition: Specifiers.h:124
@ AS_private
Definition: Specifiers.h:123
unsigned long uint64_t
long int64_t
#define true
Definition: stdbool.h:25
Structure with information about how a bitfield should be accessed.
CharUnits StorageOffset
The offset of the bitfield storage from the start of the struct.
unsigned Offset
The offset within a contiguous run of bitfields that are represented as a single "field" within the L...
unsigned Size
The total size of the bit-field, in bits.
unsigned StorageSize
The storage size in bits which should be used when accessing this bitfield.
unsigned IsSigned
Whether the bit-field is signed.
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
unsigned char PointerWidthInBits
The width of a pointer into the generic address space.
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
Extra information about a function prototype.
Definition: Type.h:4747
uint64_t Index
Method's index in the vftable.
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
unsigned MSVCFormatting
Use whitespace and punctuation like MSVC does.
unsigned SplitTemplateClosers
Whether nested templates must be closed like 'a<b<c> >' rather than 'a<b<c>>'.
unsigned PrintCanonicalTypes
Whether to print types as written or canonically.
unsigned AlwaysIncludeTypeForTemplateArgument
Whether to use type suffixes (eg: 1U) on integral non-type template parameters.
unsigned UsePreferredNames
Whether to use C++ template preferred_name attributes when printing templates.
unsigned UseEnumerators
Whether to print enumerator non-type template parameters with a matching enumerator name or via cast ...
unsigned SuppressInlineNamespace
Suppress printing parts of scope specifiers that correspond to inline namespaces, where the name is u...
const PrintingCallbacks * Callbacks
Callbacks to use to allow the behavior of printing to be customized.
A this pointer adjustment.
Definition: Thunk.h:91
bool isAlignRequired()
Definition: ASTContext.h:164
uint64_t Width
Definition: ASTContext.h:156
unsigned Align
Definition: ASTContext.h:157