clang  10.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 "clang/AST/ASTContext.h"
22 #include "clang/AST/Attr.h"
23 #include "clang/AST/DeclFriend.h"
24 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/DeclTemplate.h"
26 #include "clang/AST/Expr.h"
27 #include "clang/AST/RecordLayout.h"
31 #include "clang/Basic/Version.h"
34 #include "clang/Lex/ModuleMap.h"
36 #include "llvm/ADT/DenseSet.h"
37 #include "llvm/ADT/SmallVector.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/IR/Constants.h"
40 #include "llvm/IR/DataLayout.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/Metadata.h"
45 #include "llvm/IR/Module.h"
46 #include "llvm/Support/FileSystem.h"
47 #include "llvm/Support/MD5.h"
48 #include "llvm/Support/Path.h"
49 #include "llvm/Support/TimeProfiler.h"
50 using namespace clang;
51 using namespace clang::CodeGen;
52 
53 static uint32_t getTypeAlignIfRequired(const Type *Ty, const ASTContext &Ctx) {
54  auto TI = Ctx.getTypeInfo(Ty);
55  return TI.AlignIsRequired ? TI.Align : 0;
56 }
57 
58 static uint32_t getTypeAlignIfRequired(QualType Ty, const ASTContext &Ctx) {
59  return getTypeAlignIfRequired(Ty.getTypePtr(), Ctx);
60 }
61 
62 static uint32_t getDeclAlignIfRequired(const Decl *D, const ASTContext &Ctx) {
63  return D->hasAttr<AlignedAttr>() ? D->getMaxAlignment() : 0;
64 }
65 
67  : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
68  DebugTypeExtRefs(CGM.getCodeGenOpts().DebugTypeExtRefs),
69  DBuilder(CGM.getModule()) {
70  for (const auto &KV : CGM.getCodeGenOpts().DebugPrefixMap)
71  DebugPrefixMap[KV.first] = KV.second;
72  CreateCompileUnit();
73 }
74 
76  assert(LexicalBlockStack.empty() &&
77  "Region stack mismatch, stack not empty!");
78 }
79 
80 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
81  SourceLocation TemporaryLocation)
82  : CGF(&CGF) {
83  init(TemporaryLocation);
84 }
85 
86 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
87  bool DefaultToEmpty,
88  SourceLocation TemporaryLocation)
89  : CGF(&CGF) {
90  init(TemporaryLocation, DefaultToEmpty);
91 }
92 
93 void ApplyDebugLocation::init(SourceLocation TemporaryLocation,
94  bool DefaultToEmpty) {
95  auto *DI = CGF->getDebugInfo();
96  if (!DI) {
97  CGF = nullptr;
98  return;
99  }
100 
101  OriginalLocation = CGF->Builder.getCurrentDebugLocation();
102 
103  if (OriginalLocation && !DI->CGM.getExpressionLocationsEnabled())
104  return;
105 
106  if (TemporaryLocation.isValid()) {
107  DI->EmitLocation(CGF->Builder, TemporaryLocation);
108  return;
109  }
110 
111  if (DefaultToEmpty) {
112  CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc());
113  return;
114  }
115 
116  // Construct a location that has a valid scope, but no line info.
117  assert(!DI->LexicalBlockStack.empty());
118  CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
119  0, 0, DI->LexicalBlockStack.back(), DI->getInlinedAt()));
120 }
121 
122 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E)
123  : CGF(&CGF) {
124  init(E->getExprLoc());
125 }
126 
127 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc)
128  : CGF(&CGF) {
129  if (!CGF.getDebugInfo()) {
130  this->CGF = nullptr;
131  return;
132  }
133  OriginalLocation = CGF.Builder.getCurrentDebugLocation();
134  if (Loc)
135  CGF.Builder.SetCurrentDebugLocation(std::move(Loc));
136 }
137 
139  // Query CGF so the location isn't overwritten when location updates are
140  // temporarily disabled (for C++ default function arguments)
141  if (CGF)
142  CGF->Builder.SetCurrentDebugLocation(std::move(OriginalLocation));
143 }
144 
146  GlobalDecl InlinedFn)
147  : CGF(&CGF) {
148  if (!CGF.getDebugInfo()) {
149  this->CGF = nullptr;
150  return;
151  }
152  auto &DI = *CGF.getDebugInfo();
153  SavedLocation = DI.getLocation();
154  assert((DI.getInlinedAt() ==
155  CGF.Builder.getCurrentDebugLocation()->getInlinedAt()) &&
156  "CGDebugInfo and IRBuilder are out of sync");
157 
158  DI.EmitInlineFunctionStart(CGF.Builder, InlinedFn);
159 }
160 
162  if (!CGF)
163  return;
164  auto &DI = *CGF->getDebugInfo();
166  DI.EmitLocation(CGF->Builder, SavedLocation);
167 }
168 
170  // If the new location isn't valid return.
171  if (Loc.isInvalid())
172  return;
173 
174  CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
175 
176  // If we've changed files in the middle of a lexical scope go ahead
177  // and create a new lexical scope with file node if it's different
178  // from the one in the scope.
179  if (LexicalBlockStack.empty())
180  return;
181 
182  SourceManager &SM = CGM.getContext().getSourceManager();
183  auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
184  PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
185  if (PCLoc.isInvalid() || Scope->getFile() == getOrCreateFile(CurLoc))
186  return;
187 
188  if (auto *LBF = dyn_cast<llvm::DILexicalBlockFile>(Scope)) {
189  LexicalBlockStack.pop_back();
190  LexicalBlockStack.emplace_back(DBuilder.createLexicalBlockFile(
191  LBF->getScope(), getOrCreateFile(CurLoc)));
192  } else if (isa<llvm::DILexicalBlock>(Scope) ||
193  isa<llvm::DISubprogram>(Scope)) {
194  LexicalBlockStack.pop_back();
195  LexicalBlockStack.emplace_back(
196  DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc)));
197  }
198 }
199 
200 llvm::DIScope *CGDebugInfo::getDeclContextDescriptor(const Decl *D) {
201  llvm::DIScope *Mod = getParentModuleOrNull(D);
202  return getContextDescriptor(cast<Decl>(D->getDeclContext()),
203  Mod ? Mod : TheCU);
204 }
205 
206 llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context,
207  llvm::DIScope *Default) {
208  if (!Context)
209  return Default;
210 
211  auto I = RegionMap.find(Context);
212  if (I != RegionMap.end()) {
213  llvm::Metadata *V = I->second;
214  return dyn_cast_or_null<llvm::DIScope>(V);
215  }
216 
217  // Check namespace.
218  if (const auto *NSDecl = dyn_cast<NamespaceDecl>(Context))
219  return getOrCreateNamespace(NSDecl);
220 
221  if (const auto *RDecl = dyn_cast<RecordDecl>(Context))
222  if (!RDecl->isDependentType())
223  return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
224  TheCU->getFile());
225  return Default;
226 }
227 
228 PrintingPolicy CGDebugInfo::getPrintingPolicy() const {
229  PrintingPolicy PP = CGM.getContext().getPrintingPolicy();
230 
231  // If we're emitting codeview, it's important to try to match MSVC's naming so
232  // that visualizers written for MSVC will trigger for our class names. In
233  // particular, we can't have spaces between arguments of standard templates
234  // like basic_string and vector.
235  if (CGM.getCodeGenOpts().EmitCodeView)
236  PP.MSVCFormatting = true;
237 
238  // Apply -fdebug-prefix-map.
239  PP.Callbacks = &PrintCB;
240  return PP;
241 }
242 
243 StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
244  assert(FD && "Invalid FunctionDecl!");
245  IdentifierInfo *FII = FD->getIdentifier();
248 
249  // Emit the unqualified name in normal operation. LLVM and the debugger can
250  // compute the fully qualified name from the scope chain. If we're only
251  // emitting line table info, there won't be any scope chains, so emit the
252  // fully qualified name here so that stack traces are more accurate.
253  // FIXME: Do this when emitting DWARF as well as when emitting CodeView after
254  // evaluating the size impact.
255  bool UseQualifiedName = DebugKind == codegenoptions::DebugLineTablesOnly &&
256  CGM.getCodeGenOpts().EmitCodeView;
257 
258  if (!Info && FII && !UseQualifiedName)
259  return FII->getName();
260 
261  SmallString<128> NS;
262  llvm::raw_svector_ostream OS(NS);
263  if (!UseQualifiedName)
264  FD->printName(OS);
265  else
266  FD->printQualifiedName(OS, getPrintingPolicy());
267 
268  // Add any template specialization args.
269  if (Info) {
270  const TemplateArgumentList *TArgs = Info->TemplateArguments;
271  printTemplateArgumentList(OS, TArgs->asArray(), getPrintingPolicy());
272  }
273 
274  // Copy this name on the side and use its reference.
275  return internString(OS.str());
276 }
277 
278 StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
279  SmallString<256> MethodName;
280  llvm::raw_svector_ostream OS(MethodName);
281  OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
282  const DeclContext *DC = OMD->getDeclContext();
283  if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) {
284  OS << OID->getName();
285  } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) {
286  OS << OID->getName();
287  } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) {
288  if (OC->IsClassExtension()) {
289  OS << OC->getClassInterface()->getName();
290  } else {
291  OS << OC->getIdentifier()->getNameStart() << '('
292  << OC->getIdentifier()->getNameStart() << ')';
293  }
294  } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) {
295  OS << OCD->getClassInterface()->getName() << '(' << OCD->getName() << ')';
296  }
297  OS << ' ' << OMD->getSelector().getAsString() << ']';
298 
299  return internString(OS.str());
300 }
301 
302 StringRef CGDebugInfo::getSelectorName(Selector S) {
303  return internString(S.getAsString());
304 }
305 
306 StringRef CGDebugInfo::getClassName(const RecordDecl *RD) {
307  if (isa<ClassTemplateSpecializationDecl>(RD)) {
308  SmallString<128> Name;
309  llvm::raw_svector_ostream OS(Name);
310  PrintingPolicy PP = getPrintingPolicy();
311  PP.PrintCanonicalTypes = true;
312  RD->getNameForDiagnostic(OS, PP,
313  /*Qualified*/ false);
314 
315  // Copy this name on the side and use its reference.
316  return internString(Name);
317  }
318 
319  // quick optimization to avoid having to intern strings that are already
320  // stored reliably elsewhere
321  if (const IdentifierInfo *II = RD->getIdentifier())
322  return II->getName();
323 
324  // The CodeView printer in LLVM wants to see the names of unnamed types: it is
325  // used to reconstruct the fully qualified type names.
326  if (CGM.getCodeGenOpts().EmitCodeView) {
327  if (const TypedefNameDecl *D = RD->getTypedefNameForAnonDecl()) {
328  assert(RD->getDeclContext() == D->getDeclContext() &&
329  "Typedef should not be in another decl context!");
330  assert(D->getDeclName().getAsIdentifierInfo() &&
331  "Typedef was not named!");
332  return D->getDeclName().getAsIdentifierInfo()->getName();
333  }
334 
335  if (CGM.getLangOpts().CPlusPlus) {
336  StringRef Name;
337 
338  ASTContext &Context = CGM.getContext();
339  if (const DeclaratorDecl *DD = Context.getDeclaratorForUnnamedTagDecl(RD))
340  // Anonymous types without a name for linkage purposes have their
341  // declarator mangled in if they have one.
342  Name = DD->getName();
343  else if (const TypedefNameDecl *TND =
345  // Anonymous types without a name for linkage purposes have their
346  // associate typedef mangled in if they have one.
347  Name = TND->getName();
348 
349  if (!Name.empty()) {
350  SmallString<256> UnnamedType("<unnamed-type-");
351  UnnamedType += Name;
352  UnnamedType += '>';
353  return internString(UnnamedType);
354  }
355  }
356  }
357 
358  return StringRef();
359 }
360 
362 CGDebugInfo::computeChecksum(FileID FID, SmallString<32> &Checksum) const {
363  Checksum.clear();
364 
365  if (!CGM.getCodeGenOpts().EmitCodeView &&
366  CGM.getCodeGenOpts().DwarfVersion < 5)
367  return None;
368 
369  SourceManager &SM = CGM.getContext().getSourceManager();
370  bool Invalid;
371  const llvm::MemoryBuffer *MemBuffer = SM.getBuffer(FID, &Invalid);
372  if (Invalid)
373  return None;
374 
375  llvm::MD5 Hash;
376  llvm::MD5::MD5Result Result;
377 
378  Hash.update(MemBuffer->getBuffer());
379  Hash.final(Result);
380 
381  Hash.stringifyResult(Result, Checksum);
382  return llvm::DIFile::CSK_MD5;
383 }
384 
385 Optional<StringRef> CGDebugInfo::getSource(const SourceManager &SM,
386  FileID FID) {
387  if (!CGM.getCodeGenOpts().EmbedSource)
388  return None;
389 
390  bool SourceInvalid = false;
391  StringRef Source = SM.getBufferData(FID, &SourceInvalid);
392 
393  if (SourceInvalid)
394  return None;
395 
396  return Source;
397 }
398 
399 llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
400  if (!Loc.isValid())
401  // If Location is not valid then use main input file.
402  return TheCU->getFile();
403 
404  SourceManager &SM = CGM.getContext().getSourceManager();
405  PresumedLoc PLoc = SM.getPresumedLoc(Loc);
406 
407  StringRef FileName = PLoc.getFilename();
408  if (PLoc.isInvalid() || FileName.empty())
409  // If the location is not valid then use main input file.
410  return TheCU->getFile();
411 
412  // Cache the results.
413  auto It = DIFileCache.find(FileName.data());
414  if (It != DIFileCache.end()) {
415  // Verify that the information still exists.
416  if (llvm::Metadata *V = It->second)
417  return cast<llvm::DIFile>(V);
418  }
419 
420  SmallString<32> Checksum;
421 
422  // Compute the checksum if possible. If the location is affected by a #line
423  // directive that refers to a file, PLoc will have an invalid FileID, and we
424  // will correctly get no checksum.
426  computeChecksum(PLoc.getFileID(), Checksum);
428  if (CSKind)
429  CSInfo.emplace(*CSKind, Checksum);
430  return createFile(FileName, CSInfo, getSource(SM, SM.getFileID(Loc)));
431 }
432 
433 llvm::DIFile *
434 CGDebugInfo::createFile(StringRef FileName,
435  Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo,
436  Optional<StringRef> Source) {
437  StringRef Dir;
438  StringRef File;
439  std::string RemappedFile = remapDIPath(FileName);
440  std::string CurDir = remapDIPath(getCurrentDirname());
441  SmallString<128> DirBuf;
442  SmallString<128> FileBuf;
443  if (llvm::sys::path::is_absolute(RemappedFile)) {
444  // Strip the common prefix (if it is more than just "/") from current
445  // directory and FileName for a more space-efficient encoding.
446  auto FileIt = llvm::sys::path::begin(RemappedFile);
447  auto FileE = llvm::sys::path::end(RemappedFile);
448  auto CurDirIt = llvm::sys::path::begin(CurDir);
449  auto CurDirE = llvm::sys::path::end(CurDir);
450  for (; CurDirIt != CurDirE && *CurDirIt == *FileIt; ++CurDirIt, ++FileIt)
451  llvm::sys::path::append(DirBuf, *CurDirIt);
452  if (std::distance(llvm::sys::path::begin(CurDir), CurDirIt) == 1) {
453  // Don't strip the common prefix if it is only the root "/"
454  // since that would make LLVM diagnostic locations confusing.
455  Dir = {};
456  File = RemappedFile;
457  } else {
458  for (; FileIt != FileE; ++FileIt)
459  llvm::sys::path::append(FileBuf, *FileIt);
460  Dir = DirBuf;
461  File = FileBuf;
462  }
463  } else {
464  Dir = CurDir;
465  File = RemappedFile;
466  }
467  llvm::DIFile *F = DBuilder.createFile(File, Dir, CSInfo, Source);
468  DIFileCache[FileName.data()].reset(F);
469  return F;
470 }
471 
472 std::string CGDebugInfo::remapDIPath(StringRef Path) const {
473  for (const auto &Entry : DebugPrefixMap)
474  if (Path.startswith(Entry.first))
475  return (Twine(Entry.second) + Path.substr(Entry.first.size())).str();
476  return Path.str();
477 }
478 
479 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
480  if (Loc.isInvalid() && CurLoc.isInvalid())
481  return 0;
482  SourceManager &SM = CGM.getContext().getSourceManager();
483  PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
484  return PLoc.isValid() ? PLoc.getLine() : 0;
485 }
486 
487 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
488  // We may not want column information at all.
489  if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
490  return 0;
491 
492  // If the location is invalid then use the current column.
493  if (Loc.isInvalid() && CurLoc.isInvalid())
494  return 0;
495  SourceManager &SM = CGM.getContext().getSourceManager();
496  PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
497  return PLoc.isValid() ? PLoc.getColumn() : 0;
498 }
499 
500 StringRef CGDebugInfo::getCurrentDirname() {
501  if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
502  return CGM.getCodeGenOpts().DebugCompilationDir;
503 
504  if (!CWDName.empty())
505  return CWDName;
506  SmallString<256> CWD;
507  llvm::sys::fs::current_path(CWD);
508  return CWDName = internString(CWD);
509 }
510 
511 void CGDebugInfo::CreateCompileUnit() {
512  SmallString<32> Checksum;
515 
516  // Should we be asking the SourceManager for the main file name, instead of
517  // accepting it as an argument? This just causes the main file name to
518  // mismatch with source locations and create extra lexical scopes or
519  // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
520  // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
521  // because that's what the SourceManager says)
522 
523  // Get absolute path name.
524  SourceManager &SM = CGM.getContext().getSourceManager();
525  std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
526  if (MainFileName.empty())
527  MainFileName = "<stdin>";
528 
529  // The main file name provided via the "-main-file-name" option contains just
530  // the file name itself with no path information. This file name may have had
531  // a relative path, so we look into the actual file entry for the main
532  // file to determine the real absolute path for the file.
533  std::string MainFileDir;
534  if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
535  MainFileDir = MainFile->getDir()->getName();
536  if (!llvm::sys::path::is_absolute(MainFileName)) {
537  llvm::SmallString<1024> MainFileDirSS(MainFileDir);
538  llvm::sys::path::append(MainFileDirSS, MainFileName);
539  MainFileName = llvm::sys::path::remove_leading_dotslash(MainFileDirSS);
540  }
541  // If the main file name provided is identical to the input file name, and
542  // if the input file is a preprocessed source, use the module name for
543  // debug info. The module name comes from the name specified in the first
544  // linemarker if the input is a preprocessed source.
545  if (MainFile->getName() == MainFileName &&
547  MainFile->getName().rsplit('.').second)
548  .isPreprocessed())
549  MainFileName = CGM.getModule().getName().str();
550 
551  CSKind = computeChecksum(SM.getMainFileID(), Checksum);
552  }
553 
554  llvm::dwarf::SourceLanguage LangTag;
555  const LangOptions &LO = CGM.getLangOpts();
556  if (LO.CPlusPlus) {
557  if (LO.ObjC)
558  LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
559  else if (LO.CPlusPlus14)
560  LangTag = llvm::dwarf::DW_LANG_C_plus_plus_14;
561  else if (LO.CPlusPlus11)
562  LangTag = llvm::dwarf::DW_LANG_C_plus_plus_11;
563  else
564  LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
565  } else if (LO.ObjC) {
566  LangTag = llvm::dwarf::DW_LANG_ObjC;
567  } else if (LO.RenderScript) {
568  LangTag = llvm::dwarf::DW_LANG_GOOGLE_RenderScript;
569  } else if (LO.C99) {
570  LangTag = llvm::dwarf::DW_LANG_C99;
571  } else {
572  LangTag = llvm::dwarf::DW_LANG_C89;
573  }
574 
575  std::string Producer = getClangFullVersion();
576 
577  // Figure out which version of the ObjC runtime we have.
578  unsigned RuntimeVers = 0;
579  if (LO.ObjC)
580  RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
581 
582  llvm::DICompileUnit::DebugEmissionKind EmissionKind;
583  switch (DebugKind) {
586  EmissionKind = llvm::DICompileUnit::NoDebug;
587  break;
589  EmissionKind = llvm::DICompileUnit::LineTablesOnly;
590  break;
593  break;
597  EmissionKind = llvm::DICompileUnit::FullDebug;
598  break;
599  }
600 
601  uint64_t DwoId = 0;
602  auto &CGOpts = CGM.getCodeGenOpts();
603  // The DIFile used by the CU is distinct from the main source
604  // file. Its directory part specifies what becomes the
605  // DW_AT_comp_dir (the compilation directory), even if the source
606  // file was specified with an absolute path.
607  if (CSKind)
608  CSInfo.emplace(*CSKind, Checksum);
609  llvm::DIFile *CUFile = DBuilder.createFile(
610  remapDIPath(MainFileName), remapDIPath(getCurrentDirname()), CSInfo,
611  getSource(SM, SM.getMainFileID()));
612 
613  // Create new compile unit.
614  TheCU = DBuilder.createCompileUnit(
615  LangTag, CUFile, CGOpts.EmitVersionIdentMetadata ? Producer : "",
616  LO.Optimize || CGOpts.PrepareForLTO || CGOpts.PrepareForThinLTO,
617  CGOpts.DwarfDebugFlags, RuntimeVers, CGOpts.SplitDwarfFile, EmissionKind,
618  DwoId, CGOpts.SplitDwarfInlining, CGOpts.DebugInfoForProfiling,
619  CGM.getTarget().getTriple().isNVPTX()
621  : static_cast<llvm::DICompileUnit::DebugNameTableKind>(
622  CGOpts.DebugNameTable),
623  CGOpts.DebugRangesBaseAddress);
624 }
625 
626 llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {
627  llvm::dwarf::TypeKind Encoding;
628  StringRef BTName;
629  switch (BT->getKind()) {
630 #define BUILTIN_TYPE(Id, SingletonId)
631 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
632 #include "clang/AST/BuiltinTypes.def"
633  case BuiltinType::Dependent:
634  llvm_unreachable("Unexpected builtin type");
635  case BuiltinType::NullPtr:
636  return DBuilder.createNullPtrType();
637  case BuiltinType::Void:
638  return nullptr;
639  case BuiltinType::ObjCClass:
640  if (!ClassTy)
641  ClassTy =
642  DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
643  "objc_class", TheCU, TheCU->getFile(), 0);
644  return ClassTy;
645  case BuiltinType::ObjCId: {
646  // typedef struct objc_class *Class;
647  // typedef struct objc_object {
648  // Class isa;
649  // } *id;
650 
651  if (ObjTy)
652  return ObjTy;
653 
654  if (!ClassTy)
655  ClassTy =
656  DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
657  "objc_class", TheCU, TheCU->getFile(), 0);
658 
659  unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
660 
661  auto *ISATy = DBuilder.createPointerType(ClassTy, Size);
662 
663  ObjTy = DBuilder.createStructType(TheCU, "objc_object", TheCU->getFile(), 0,
664  0, 0, llvm::DINode::FlagZero, nullptr,
665  llvm::DINodeArray());
666 
667  DBuilder.replaceArrays(
668  ObjTy, DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
669  ObjTy, "isa", TheCU->getFile(), 0, Size, 0, 0,
670  llvm::DINode::FlagZero, ISATy)));
671  return ObjTy;
672  }
673  case BuiltinType::ObjCSel: {
674  if (!SelTy)
675  SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
676  "objc_selector", TheCU,
677  TheCU->getFile(), 0);
678  return SelTy;
679  }
680 
681 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
682  case BuiltinType::Id: \
683  return getOrCreateStructPtrType("opencl_" #ImgType "_" #Suffix "_t", \
684  SingletonId);
685 #include "clang/Basic/OpenCLImageTypes.def"
686  case BuiltinType::OCLSampler:
687  return getOrCreateStructPtrType("opencl_sampler_t", OCLSamplerDITy);
688  case BuiltinType::OCLEvent:
689  return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);
690  case BuiltinType::OCLClkEvent:
691  return getOrCreateStructPtrType("opencl_clk_event_t", OCLClkEventDITy);
692  case BuiltinType::OCLQueue:
693  return getOrCreateStructPtrType("opencl_queue_t", OCLQueueDITy);
694  case BuiltinType::OCLReserveID:
695  return getOrCreateStructPtrType("opencl_reserve_id_t", OCLReserveIDDITy);
696 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
697  case BuiltinType::Id: \
698  return getOrCreateStructPtrType("opencl_" #ExtType, Id##Ty);
699 #include "clang/Basic/OpenCLExtensionTypes.def"
700  // TODO: real support for SVE types requires more infrastructure
701  // to be added first. The types have a variable length and are
702  // represented in debug info as types whose length depends on a
703  // target-specific pseudo register.
704 #define SVE_TYPE(Name, Id, SingletonId) \
705  case BuiltinType::Id:
706 #include "clang/Basic/AArch64SVEACLETypes.def"
707  {
708  unsigned DiagID = CGM.getDiags().getCustomDiagID(
710  "cannot yet generate debug info for SVE type '%0'");
711  auto Name = BT->getName(CGM.getContext().getPrintingPolicy());
712  CGM.getDiags().Report(DiagID) << Name;
713  // Return something safe.
714  return CreateType(cast<const BuiltinType>(CGM.getContext().IntTy));
715  }
716 
717  case BuiltinType::UChar:
718  case BuiltinType::Char_U:
719  Encoding = llvm::dwarf::DW_ATE_unsigned_char;
720  break;
721  case BuiltinType::Char_S:
722  case BuiltinType::SChar:
723  Encoding = llvm::dwarf::DW_ATE_signed_char;
724  break;
725  case BuiltinType::Char8:
726  case BuiltinType::Char16:
727  case BuiltinType::Char32:
728  Encoding = llvm::dwarf::DW_ATE_UTF;
729  break;
730  case BuiltinType::UShort:
731  case BuiltinType::UInt:
732  case BuiltinType::UInt128:
733  case BuiltinType::ULong:
734  case BuiltinType::WChar_U:
735  case BuiltinType::ULongLong:
736  Encoding = llvm::dwarf::DW_ATE_unsigned;
737  break;
738  case BuiltinType::Short:
739  case BuiltinType::Int:
740  case BuiltinType::Int128:
741  case BuiltinType::Long:
742  case BuiltinType::WChar_S:
743  case BuiltinType::LongLong:
744  Encoding = llvm::dwarf::DW_ATE_signed;
745  break;
746  case BuiltinType::Bool:
747  Encoding = llvm::dwarf::DW_ATE_boolean;
748  break;
749  case BuiltinType::Half:
750  case BuiltinType::Float:
751  case BuiltinType::LongDouble:
752  case BuiltinType::Float16:
753  case BuiltinType::Float128:
754  case BuiltinType::Double:
755  // FIXME: For targets where long double and __float128 have the same size,
756  // they are currently indistinguishable in the debugger without some
757  // special treatment. However, there is currently no consensus on encoding
758  // and this should be updated once a DWARF encoding exists for distinct
759  // floating point types of the same size.
760  Encoding = llvm::dwarf::DW_ATE_float;
761  break;
762  case BuiltinType::ShortAccum:
763  case BuiltinType::Accum:
764  case BuiltinType::LongAccum:
765  case BuiltinType::ShortFract:
766  case BuiltinType::Fract:
767  case BuiltinType::LongFract:
768  case BuiltinType::SatShortFract:
769  case BuiltinType::SatFract:
770  case BuiltinType::SatLongFract:
771  case BuiltinType::SatShortAccum:
772  case BuiltinType::SatAccum:
773  case BuiltinType::SatLongAccum:
774  Encoding = llvm::dwarf::DW_ATE_signed_fixed;
775  break;
776  case BuiltinType::UShortAccum:
777  case BuiltinType::UAccum:
778  case BuiltinType::ULongAccum:
779  case BuiltinType::UShortFract:
780  case BuiltinType::UFract:
781  case BuiltinType::ULongFract:
782  case BuiltinType::SatUShortAccum:
783  case BuiltinType::SatUAccum:
784  case BuiltinType::SatULongAccum:
785  case BuiltinType::SatUShortFract:
786  case BuiltinType::SatUFract:
787  case BuiltinType::SatULongFract:
788  Encoding = llvm::dwarf::DW_ATE_unsigned_fixed;
789  break;
790  }
791 
792  switch (BT->getKind()) {
793  case BuiltinType::Long:
794  BTName = "long int";
795  break;
796  case BuiltinType::LongLong:
797  BTName = "long long int";
798  break;
799  case BuiltinType::ULong:
800  BTName = "long unsigned int";
801  break;
802  case BuiltinType::ULongLong:
803  BTName = "long long unsigned int";
804  break;
805  default:
806  BTName = BT->getName(CGM.getLangOpts());
807  break;
808  }
809  // Bit size and offset of the type.
810  uint64_t Size = CGM.getContext().getTypeSize(BT);
811  return DBuilder.createBasicType(BTName, Size, Encoding);
812 }
813 
814 llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) {
815  // Bit size and offset of the type.
816  llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
817  if (Ty->isComplexIntegerType())
818  Encoding = llvm::dwarf::DW_ATE_lo_user;
819 
820  uint64_t Size = CGM.getContext().getTypeSize(Ty);
821  return DBuilder.createBasicType("complex", Size, Encoding);
822 }
823 
824 llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty,
825  llvm::DIFile *Unit) {
827  const Type *T = Qc.strip(Ty);
828 
829  // Ignore these qualifiers for now.
830  Qc.removeObjCGCAttr();
831  Qc.removeAddressSpace();
832  Qc.removeObjCLifetime();
833 
834  // We will create one Derived type for one qualifier and recurse to handle any
835  // additional ones.
836  llvm::dwarf::Tag Tag;
837  if (Qc.hasConst()) {
838  Tag = llvm::dwarf::DW_TAG_const_type;
839  Qc.removeConst();
840  } else if (Qc.hasVolatile()) {
841  Tag = llvm::dwarf::DW_TAG_volatile_type;
842  Qc.removeVolatile();
843  } else if (Qc.hasRestrict()) {
844  Tag = llvm::dwarf::DW_TAG_restrict_type;
845  Qc.removeRestrict();
846  } else {
847  assert(Qc.empty() && "Unknown type qualifier for debug info");
848  return getOrCreateType(QualType(T, 0), Unit);
849  }
850 
851  auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
852 
853  // No need to fill in the Name, Line, Size, Alignment, Offset in case of
854  // CVR derived types.
855  return DBuilder.createQualifiedType(Tag, FromTy);
856 }
857 
858 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
859  llvm::DIFile *Unit) {
860 
861  // The frontend treats 'id' as a typedef to an ObjCObjectType,
862  // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
863  // debug info, we want to emit 'id' in both cases.
864  if (Ty->isObjCQualifiedIdType())
865  return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
866 
867  return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
868  Ty->getPointeeType(), Unit);
869 }
870 
871 llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty,
872  llvm::DIFile *Unit) {
873  return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
874  Ty->getPointeeType(), Unit);
875 }
876 
877 /// \return whether a C++ mangling exists for the type defined by TD.
878 static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {
879  switch (TheCU->getSourceLanguage()) {
880  case llvm::dwarf::DW_LANG_C_plus_plus:
881  case llvm::dwarf::DW_LANG_C_plus_plus_11:
882  case llvm::dwarf::DW_LANG_C_plus_plus_14:
883  return true;
884  case llvm::dwarf::DW_LANG_ObjC_plus_plus:
885  return isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD);
886  default:
887  return false;
888  }
889 }
890 
891 // Determines if the debug info for this tag declaration needs a type
892 // identifier. The purpose of the unique identifier is to deduplicate type
893 // information for identical types across TUs. Because of the C++ one definition
894 // rule (ODR), it is valid to assume that the type is defined the same way in
895 // every TU and its debug info is equivalent.
896 //
897 // C does not have the ODR, and it is common for codebases to contain multiple
898 // different definitions of a struct with the same name in different TUs.
899 // Therefore, if the type doesn't have a C++ mangling, don't give it an
900 // identifer. Type information in C is smaller and simpler than C++ type
901 // information, so the increase in debug info size is negligible.
902 //
903 // If the type is not externally visible, it should be unique to the current TU,
904 // and should not need an identifier to participate in type deduplication.
905 // However, when emitting CodeView, the format internally uses these
906 // unique type name identifers for references between debug info. For example,
907 // the method of a class in an anonymous namespace uses the identifer to refer
908 // to its parent class. The Microsoft C++ ABI attempts to provide unique names
909 // for such types, so when emitting CodeView, always use identifiers for C++
910 // types. This may create problems when attempting to emit CodeView when the MS
911 // C++ ABI is not in use.
912 static bool needsTypeIdentifier(const TagDecl *TD, CodeGenModule &CGM,
913  llvm::DICompileUnit *TheCU) {
914  // We only add a type identifier for types with C++ name mangling.
915  if (!hasCXXMangling(TD, TheCU))
916  return false;
917 
918  // Externally visible types with C++ mangling need a type identifier.
919  if (TD->isExternallyVisible())
920  return true;
921 
922  // CodeView types with C++ mangling need a type identifier.
923  if (CGM.getCodeGenOpts().EmitCodeView)
924  return true;
925 
926  return false;
927 }
928 
929 // Returns a unique type identifier string if one exists, or an empty string.
930 static SmallString<256> getTypeIdentifier(const TagType *Ty, CodeGenModule &CGM,
931  llvm::DICompileUnit *TheCU) {
932  SmallString<256> Identifier;
933  const TagDecl *TD = Ty->getDecl();
934 
935  if (!needsTypeIdentifier(TD, CGM, TheCU))
936  return Identifier;
937  if (const auto *RD = dyn_cast<CXXRecordDecl>(TD))
938  if (RD->getDefinition())
939  if (RD->isDynamicClass() &&
941  return Identifier;
942 
943  // TODO: This is using the RTTI name. Is there a better way to get
944  // a unique string for a type?
945  llvm::raw_svector_ostream Out(Identifier);
947  return Identifier;
948 }
949 
950 /// \return the appropriate DWARF tag for a composite type.
951 static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
952  llvm::dwarf::Tag Tag;
953  if (RD->isStruct() || RD->isInterface())
954  Tag = llvm::dwarf::DW_TAG_structure_type;
955  else if (RD->isUnion())
956  Tag = llvm::dwarf::DW_TAG_union_type;
957  else {
958  // FIXME: This could be a struct type giving a default visibility different
959  // than C++ class type, but needs llvm metadata changes first.
960  assert(RD->isClass());
961  Tag = llvm::dwarf::DW_TAG_class_type;
962  }
963  return Tag;
964 }
965 
966 llvm::DICompositeType *
967 CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
968  llvm::DIScope *Ctx) {
969  const RecordDecl *RD = Ty->getDecl();
970  if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
971  return cast<llvm::DICompositeType>(T);
972  llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
973  unsigned Line = getLineNumber(RD->getLocation());
974  StringRef RDName = getClassName(RD);
975 
976  uint64_t Size = 0;
977  uint32_t Align = 0;
978 
979  // Create the type.
980  SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
981  llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(
982  getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align,
983  llvm::DINode::FlagFwdDecl, Identifier);
984  if (CGM.getCodeGenOpts().DebugFwdTemplateParams)
985  if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
986  DBuilder.replaceArrays(RetTy, llvm::DINodeArray(),
987  CollectCXXTemplateParams(TSpecial, DefUnit));
988  ReplaceMap.emplace_back(
989  std::piecewise_construct, std::make_tuple(Ty),
990  std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
991  return RetTy;
992 }
993 
994 llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
995  const Type *Ty,
996  QualType PointeeTy,
997  llvm::DIFile *Unit) {
998  // Bit size, align and offset of the type.
999  // Size is always the size of a pointer. We can't use getTypeSize here
1000  // because that does not return the correct value for references.
1001  unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(PointeeTy);
1002  uint64_t Size = CGM.getTarget().getPointerWidth(AddressSpace);
1003  auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
1004  Optional<unsigned> DWARFAddressSpace =
1005  CGM.getTarget().getDWARFAddressSpace(AddressSpace);
1006 
1007  if (Tag == llvm::dwarf::DW_TAG_reference_type ||
1008  Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
1009  return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit),
1010  Size, Align, DWARFAddressSpace);
1011  else
1012  return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
1013  Align, DWARFAddressSpace);
1014 }
1015 
1016 llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
1017  llvm::DIType *&Cache) {
1018  if (Cache)
1019  return Cache;
1020  Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
1021  TheCU, TheCU->getFile(), 0);
1022  unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1023  Cache = DBuilder.createPointerType(Cache, Size);
1024  return Cache;
1025 }
1026 
1027 uint64_t CGDebugInfo::collectDefaultElementTypesForBlockPointer(
1028  const BlockPointerType *Ty, llvm::DIFile *Unit, llvm::DIDerivedType *DescTy,
1029  unsigned LineNo, SmallVectorImpl<llvm::Metadata *> &EltTys) {
1030  QualType FType;
1031 
1032  // Advanced by calls to CreateMemberType in increments of FType, then
1033  // returned as the overall size of the default elements.
1034  uint64_t FieldOffset = 0;
1035 
1036  // Blocks in OpenCL have unique constraints which make the standard fields
1037  // redundant while requiring size and align fields for enqueue_kernel. See
1038  // initializeForBlockHeader in CGBlocks.cpp
1039  if (CGM.getLangOpts().OpenCL) {
1040  FType = CGM.getContext().IntTy;
1041  EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1042  EltTys.push_back(CreateMemberType(Unit, FType, "__align", &FieldOffset));
1043  } else {
1044  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1045  EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1046  FType = CGM.getContext().IntTy;
1047  EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1048  EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
1049  FType = CGM.getContext().getPointerType(Ty->getPointeeType());
1050  EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
1051  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1052  uint64_t FieldSize = CGM.getContext().getTypeSize(Ty);
1053  uint32_t FieldAlign = CGM.getContext().getTypeAlign(Ty);
1054  EltTys.push_back(DBuilder.createMemberType(
1055  Unit, "__descriptor", nullptr, LineNo, FieldSize, FieldAlign,
1056  FieldOffset, llvm::DINode::FlagZero, DescTy));
1057  FieldOffset += FieldSize;
1058  }
1059 
1060  return FieldOffset;
1061 }
1062 
1063 llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,
1064  llvm::DIFile *Unit) {
1066  QualType FType;
1067  uint64_t FieldOffset;
1068  llvm::DINodeArray Elements;
1069 
1070  FieldOffset = 0;
1071  FType = CGM.getContext().UnsignedLongTy;
1072  EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
1073  EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
1074 
1075  Elements = DBuilder.getOrCreateArray(EltTys);
1076  EltTys.clear();
1077 
1078  llvm::DINode::DIFlags Flags = llvm::DINode::FlagAppleBlock;
1079 
1080  auto *EltTy =
1081  DBuilder.createStructType(Unit, "__block_descriptor", nullptr, 0,
1082  FieldOffset, 0, Flags, nullptr, Elements);
1083 
1084  // Bit size, align and offset of the type.
1085  uint64_t Size = CGM.getContext().getTypeSize(Ty);
1086 
1087  auto *DescTy = DBuilder.createPointerType(EltTy, Size);
1088 
1089  FieldOffset = collectDefaultElementTypesForBlockPointer(Ty, Unit, DescTy,
1090  0, EltTys);
1091 
1092  Elements = DBuilder.getOrCreateArray(EltTys);
1093 
1094  // The __block_literal_generic structs are marked with a special
1095  // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
1096  // the debugger needs to know about. To allow type uniquing, emit
1097  // them without a name or a location.
1098  EltTy = DBuilder.createStructType(Unit, "", nullptr, 0, FieldOffset, 0,
1099  Flags, nullptr, Elements);
1100 
1101  return DBuilder.createPointerType(EltTy, Size);
1102 }
1103 
1104 llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
1105  llvm::DIFile *Unit) {
1106  assert(Ty->isTypeAlias());
1107  llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
1108 
1109  auto *AliasDecl =
1110  cast<TypeAliasTemplateDecl>(Ty->getTemplateName().getAsTemplateDecl())
1111  ->getTemplatedDecl();
1112 
1113  if (AliasDecl->hasAttr<NoDebugAttr>())
1114  return Src;
1115 
1116  SmallString<128> NS;
1117  llvm::raw_svector_ostream OS(NS);
1118  Ty->getTemplateName().print(OS, getPrintingPolicy(), /*qualified*/ false);
1119  printTemplateArgumentList(OS, Ty->template_arguments(), getPrintingPolicy());
1120 
1121  SourceLocation Loc = AliasDecl->getLocation();
1122  return DBuilder.createTypedef(Src, OS.str(), getOrCreateFile(Loc),
1123  getLineNumber(Loc),
1124  getDeclContextDescriptor(AliasDecl));
1125 }
1126 
1127 llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
1128  llvm::DIFile *Unit) {
1129  llvm::DIType *Underlying =
1130  getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
1131 
1132  if (Ty->getDecl()->hasAttr<NoDebugAttr>())
1133  return Underlying;
1134 
1135  // We don't set size information, but do specify where the typedef was
1136  // declared.
1137  SourceLocation Loc = Ty->getDecl()->getLocation();
1138 
1139  uint32_t Align = getDeclAlignIfRequired(Ty->getDecl(), CGM.getContext());
1140  // Typedefs are derived from some other type.
1141  return DBuilder.createTypedef(Underlying, Ty->getDecl()->getName(),
1142  getOrCreateFile(Loc), getLineNumber(Loc),
1143  getDeclContextDescriptor(Ty->getDecl()), Align);
1144 }
1145 
1146 static unsigned getDwarfCC(CallingConv CC) {
1147  switch (CC) {
1148  case CC_C:
1149  // Avoid emitting DW_AT_calling_convention if the C convention was used.
1150  return 0;
1151 
1152  case CC_X86StdCall:
1153  return llvm::dwarf::DW_CC_BORLAND_stdcall;
1154  case CC_X86FastCall:
1155  return llvm::dwarf::DW_CC_BORLAND_msfastcall;
1156  case CC_X86ThisCall:
1157  return llvm::dwarf::DW_CC_BORLAND_thiscall;
1158  case CC_X86VectorCall:
1159  return llvm::dwarf::DW_CC_LLVM_vectorcall;
1160  case CC_X86Pascal:
1161  return llvm::dwarf::DW_CC_BORLAND_pascal;
1162  case CC_Win64:
1163  return llvm::dwarf::DW_CC_LLVM_Win64;
1164  case CC_X86_64SysV:
1165  return llvm::dwarf::DW_CC_LLVM_X86_64SysV;
1166  case CC_AAPCS:
1167  case CC_AArch64VectorCall:
1168  return llvm::dwarf::DW_CC_LLVM_AAPCS;
1169  case CC_AAPCS_VFP:
1170  return llvm::dwarf::DW_CC_LLVM_AAPCS_VFP;
1171  case CC_IntelOclBicc:
1172  return llvm::dwarf::DW_CC_LLVM_IntelOclBicc;
1173  case CC_SpirFunction:
1174  return llvm::dwarf::DW_CC_LLVM_SpirFunction;
1175  case CC_OpenCLKernel:
1176  return llvm::dwarf::DW_CC_LLVM_OpenCLKernel;
1177  case CC_Swift:
1178  return llvm::dwarf::DW_CC_LLVM_Swift;
1179  case CC_PreserveMost:
1180  return llvm::dwarf::DW_CC_LLVM_PreserveMost;
1181  case CC_PreserveAll:
1182  return llvm::dwarf::DW_CC_LLVM_PreserveAll;
1183  case CC_X86RegCall:
1184  return llvm::dwarf::DW_CC_LLVM_X86RegCall;
1185  }
1186  return 0;
1187 }
1188 
1189 llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,
1190  llvm::DIFile *Unit) {
1192 
1193  // Add the result type at least.
1194  EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
1195 
1196  // Set up remainder of arguments if there is a prototype.
1197  // otherwise emit it as a variadic function.
1198  if (isa<FunctionNoProtoType>(Ty))
1199  EltTys.push_back(DBuilder.createUnspecifiedParameter());
1200  else if (const auto *FPT = dyn_cast<FunctionProtoType>(Ty)) {
1201  for (const QualType &ParamType : FPT->param_types())
1202  EltTys.push_back(getOrCreateType(ParamType, Unit));
1203  if (FPT->isVariadic())
1204  EltTys.push_back(DBuilder.createUnspecifiedParameter());
1205  }
1206 
1207  llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
1208  return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
1209  getDwarfCC(Ty->getCallConv()));
1210 }
1211 
1212 /// Convert an AccessSpecifier into the corresponding DINode flag.
1213 /// As an optimization, return 0 if the access specifier equals the
1214 /// default for the containing type.
1215 static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access,
1216  const RecordDecl *RD) {
1218  if (RD && RD->isClass())
1219  Default = clang::AS_private;
1220  else if (RD && (RD->isStruct() || RD->isUnion()))
1221  Default = clang::AS_public;
1222 
1223  if (Access == Default)
1224  return llvm::DINode::FlagZero;
1225 
1226  switch (Access) {
1227  case clang::AS_private:
1228  return llvm::DINode::FlagPrivate;
1229  case clang::AS_protected:
1230  return llvm::DINode::FlagProtected;
1231  case clang::AS_public:
1232  return llvm::DINode::FlagPublic;
1233  case clang::AS_none:
1234  return llvm::DINode::FlagZero;
1235  }
1236  llvm_unreachable("unexpected access enumerator");
1237 }
1238 
1239 llvm::DIType *CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl,
1240  llvm::DIScope *RecordTy,
1241  const RecordDecl *RD) {
1242  StringRef Name = BitFieldDecl->getName();
1243  QualType Ty = BitFieldDecl->getType();
1244  SourceLocation Loc = BitFieldDecl->getLocation();
1245  llvm::DIFile *VUnit = getOrCreateFile(Loc);
1246  llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
1247 
1248  // Get the location for the field.
1249  llvm::DIFile *File = getOrCreateFile(Loc);
1250  unsigned Line = getLineNumber(Loc);
1251 
1252  const CGBitFieldInfo &BitFieldInfo =
1253  CGM.getTypes().getCGRecordLayout(RD).getBitFieldInfo(BitFieldDecl);
1254  uint64_t SizeInBits = BitFieldInfo.Size;
1255  assert(SizeInBits > 0 && "found named 0-width bitfield");
1256  uint64_t StorageOffsetInBits =
1257  CGM.getContext().toBits(BitFieldInfo.StorageOffset);
1258  uint64_t Offset = BitFieldInfo.Offset;
1259  // The bit offsets for big endian machines are reversed for big
1260  // endian target, compensate for that as the DIDerivedType requires
1261  // un-reversed offsets.
1262  if (CGM.getDataLayout().isBigEndian())
1263  Offset = BitFieldInfo.StorageSize - BitFieldInfo.Size - Offset;
1264  uint64_t OffsetInBits = StorageOffsetInBits + Offset;
1265  llvm::DINode::DIFlags Flags = getAccessFlag(BitFieldDecl->getAccess(), RD);
1266  return DBuilder.createBitFieldMemberType(
1267  RecordTy, Name, File, Line, SizeInBits, OffsetInBits, StorageOffsetInBits,
1268  Flags, DebugType);
1269 }
1270 
1271 llvm::DIType *
1272 CGDebugInfo::createFieldType(StringRef name, QualType type, SourceLocation loc,
1273  AccessSpecifier AS, uint64_t offsetInBits,
1274  uint32_t AlignInBits, llvm::DIFile *tunit,
1275  llvm::DIScope *scope, const RecordDecl *RD) {
1276  llvm::DIType *debugType = getOrCreateType(type, tunit);
1277 
1278  // Get the location for the field.
1279  llvm::DIFile *file = getOrCreateFile(loc);
1280  unsigned line = getLineNumber(loc);
1281 
1282  uint64_t SizeInBits = 0;
1283  auto Align = AlignInBits;
1284  if (!type->isIncompleteArrayType()) {
1285  TypeInfo TI = CGM.getContext().getTypeInfo(type);
1286  SizeInBits = TI.Width;
1287  if (!Align)
1288  Align = getTypeAlignIfRequired(type, CGM.getContext());
1289  }
1290 
1291  llvm::DINode::DIFlags flags = getAccessFlag(AS, RD);
1292  return DBuilder.createMemberType(scope, name, file, line, SizeInBits, Align,
1293  offsetInBits, flags, debugType);
1294 }
1295 
1296 void CGDebugInfo::CollectRecordLambdaFields(
1297  const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
1298  llvm::DIType *RecordTy) {
1299  // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
1300  // has the name and the location of the variable so we should iterate over
1301  // both concurrently.
1302  const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
1303  RecordDecl::field_iterator Field = CXXDecl->field_begin();
1304  unsigned fieldno = 0;
1306  E = CXXDecl->captures_end();
1307  I != E; ++I, ++Field, ++fieldno) {
1308  const LambdaCapture &C = *I;
1309  if (C.capturesVariable()) {
1310  SourceLocation Loc = C.getLocation();
1311  assert(!Field->isBitField() && "lambdas don't have bitfield members!");
1312  VarDecl *V = C.getCapturedVar();
1313  StringRef VName = V->getName();
1314  llvm::DIFile *VUnit = getOrCreateFile(Loc);
1315  auto Align = getDeclAlignIfRequired(V, CGM.getContext());
1316  llvm::DIType *FieldType = createFieldType(
1317  VName, Field->getType(), Loc, Field->getAccess(),
1318  layout.getFieldOffset(fieldno), Align, VUnit, RecordTy, CXXDecl);
1319  elements.push_back(FieldType);
1320  } else if (C.capturesThis()) {
1321  // TODO: Need to handle 'this' in some way by probably renaming the
1322  // this of the lambda class and having a field member of 'this' or
1323  // by using AT_object_pointer for the function and having that be
1324  // used as 'this' for semantic references.
1325  FieldDecl *f = *Field;
1326  llvm::DIFile *VUnit = getOrCreateFile(f->getLocation());
1327  QualType type = f->getType();
1328  llvm::DIType *fieldType = createFieldType(
1329  "this", type, f->getLocation(), f->getAccess(),
1330  layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
1331 
1332  elements.push_back(fieldType);
1333  }
1334  }
1335 }
1336 
1337 llvm::DIDerivedType *
1338 CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
1339  const RecordDecl *RD) {
1340  // Create the descriptor for the static variable, with or without
1341  // constant initializers.
1342  Var = Var->getCanonicalDecl();
1343  llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());
1344  llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);
1345 
1346  unsigned LineNumber = getLineNumber(Var->getLocation());
1347  StringRef VName = Var->getName();
1348  llvm::Constant *C = nullptr;
1349  if (Var->getInit()) {
1350  const APValue *Value = Var->evaluateValue();
1351  if (Value) {
1352  if (Value->isInt())
1353  C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
1354  if (Value->isFloat())
1355  C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
1356  }
1357  }
1358 
1359  llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD);
1360  auto Align = getDeclAlignIfRequired(Var, CGM.getContext());
1361  llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
1362  RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Align);
1363  StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
1364  return GV;
1365 }
1366 
1367 void CGDebugInfo::CollectRecordNormalField(
1368  const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,
1369  SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,
1370  const RecordDecl *RD) {
1371  StringRef name = field->getName();
1372  QualType type = field->getType();
1373 
1374  // Ignore unnamed fields unless they're anonymous structs/unions.
1375  if (name.empty() && !type->isRecordType())
1376  return;
1377 
1378  llvm::DIType *FieldType;
1379  if (field->isBitField()) {
1380  FieldType = createBitFieldType(field, RecordTy, RD);
1381  } else {
1382  auto Align = getDeclAlignIfRequired(field, CGM.getContext());
1383  FieldType =
1384  createFieldType(name, type, field->getLocation(), field->getAccess(),
1385  OffsetInBits, Align, tunit, RecordTy, RD);
1386  }
1387 
1388  elements.push_back(FieldType);
1389 }
1390 
1391 void CGDebugInfo::CollectRecordNestedType(
1392  const TypeDecl *TD, SmallVectorImpl<llvm::Metadata *> &elements) {
1393  QualType Ty = CGM.getContext().getTypeDeclType(TD);
1394  // Injected class names are not considered nested records.
1395  if (isa<InjectedClassNameType>(Ty))
1396  return;
1397  SourceLocation Loc = TD->getLocation();
1398  llvm::DIType *nestedType = getOrCreateType(Ty, getOrCreateFile(Loc));
1399  elements.push_back(nestedType);
1400 }
1401 
1402 void CGDebugInfo::CollectRecordFields(
1403  const RecordDecl *record, llvm::DIFile *tunit,
1405  llvm::DICompositeType *RecordTy) {
1406  const auto *CXXDecl = dyn_cast<CXXRecordDecl>(record);
1407 
1408  if (CXXDecl && CXXDecl->isLambda())
1409  CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
1410  else {
1411  const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
1412 
1413  // Field number for non-static fields.
1414  unsigned fieldNo = 0;
1415 
1416  // Static and non-static members should appear in the same order as
1417  // the corresponding declarations in the source program.
1418  for (const auto *I : record->decls())
1419  if (const auto *V = dyn_cast<VarDecl>(I)) {
1420  if (V->hasAttr<NoDebugAttr>())
1421  continue;
1422 
1423  // Skip variable template specializations when emitting CodeView. MSVC
1424  // doesn't emit them.
1425  if (CGM.getCodeGenOpts().EmitCodeView &&
1426  isa<VarTemplateSpecializationDecl>(V))
1427  continue;
1428 
1429  if (isa<VarTemplatePartialSpecializationDecl>(V))
1430  continue;
1431 
1432  // Reuse the existing static member declaration if one exists
1433  auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
1434  if (MI != StaticDataMemberCache.end()) {
1435  assert(MI->second &&
1436  "Static data member declaration should still exist");
1437  elements.push_back(MI->second);
1438  } else {
1439  auto Field = CreateRecordStaticField(V, RecordTy, record);
1440  elements.push_back(Field);
1441  }
1442  } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
1443  CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
1444  elements, RecordTy, record);
1445 
1446  // Bump field number for next field.
1447  ++fieldNo;
1448  } else if (CGM.getCodeGenOpts().EmitCodeView) {
1449  // Debug info for nested types is included in the member list only for
1450  // CodeView.
1451  if (const auto *nestedType = dyn_cast<TypeDecl>(I))
1452  if (!nestedType->isImplicit() &&
1453  nestedType->getDeclContext() == record)
1454  CollectRecordNestedType(nestedType, elements);
1455  }
1456  }
1457 }
1458 
1459 llvm::DISubroutineType *
1460 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
1461  llvm::DIFile *Unit) {
1462  const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
1463  if (Method->isStatic())
1464  return cast_or_null<llvm::DISubroutineType>(
1465  getOrCreateType(QualType(Func, 0), Unit));
1466  return getOrCreateInstanceMethodType(Method->getThisType(), Func, Unit);
1467 }
1468 
1469 llvm::DISubroutineType *CGDebugInfo::getOrCreateInstanceMethodType(
1470  QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile *Unit) {
1471  // Add "this" pointer.
1472  llvm::DITypeRefArray Args(
1473  cast<llvm::DISubroutineType>(getOrCreateType(QualType(Func, 0), Unit))
1474  ->getTypeArray());
1475  assert(Args.size() && "Invalid number of arguments!");
1476 
1478 
1479  // First element is always return type. For 'void' functions it is NULL.
1480  Elts.push_back(Args[0]);
1481 
1482  // "this" pointer is always first argument.
1483  const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
1484  if (isa<ClassTemplateSpecializationDecl>(RD)) {
1485  // Create pointer type directly in this case.
1486  const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1487  QualType PointeeTy = ThisPtrTy->getPointeeType();
1488  unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
1489  uint64_t Size = CGM.getTarget().getPointerWidth(AS);
1490  auto Align = getTypeAlignIfRequired(ThisPtrTy, CGM.getContext());
1491  llvm::DIType *PointeeType = getOrCreateType(PointeeTy, Unit);
1492  llvm::DIType *ThisPtrType =
1493  DBuilder.createPointerType(PointeeType, Size, Align);
1494  TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1495  // TODO: This and the artificial type below are misleading, the
1496  // types aren't artificial the argument is, but the current
1497  // metadata doesn't represent that.
1498  ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1499  Elts.push_back(ThisPtrType);
1500  } else {
1501  llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);
1502  TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1503  ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1504  Elts.push_back(ThisPtrType);
1505  }
1506 
1507  // Copy rest of the arguments.
1508  for (unsigned i = 1, e = Args.size(); i != e; ++i)
1509  Elts.push_back(Args[i]);
1510 
1511  llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
1512 
1513  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1514  if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1515  Flags |= llvm::DINode::FlagLValueReference;
1516  if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1517  Flags |= llvm::DINode::FlagRValueReference;
1518 
1519  return DBuilder.createSubroutineType(EltTypeArray, Flags,
1520  getDwarfCC(Func->getCallConv()));
1521 }
1522 
1523 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
1524 /// inside a function.
1525 static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1526  if (const auto *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1527  return isFunctionLocalClass(NRD);
1528  if (isa<FunctionDecl>(RD->getDeclContext()))
1529  return true;
1530  return false;
1531 }
1532 
1533 llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
1534  const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {
1535  bool IsCtorOrDtor =
1536  isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
1537 
1538  StringRef MethodName = getFunctionName(Method);
1539  llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit);
1540 
1541  // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1542  // make sense to give a single ctor/dtor a linkage name.
1543  StringRef MethodLinkageName;
1544  // FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional
1545  // property to use here. It may've been intended to model "is non-external
1546  // type" but misses cases of non-function-local but non-external classes such
1547  // as those in anonymous namespaces as well as the reverse - external types
1548  // that are function local, such as those in (non-local) inline functions.
1549  if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1550  MethodLinkageName = CGM.getMangledName(Method);
1551 
1552  // Get the location for the method.
1553  llvm::DIFile *MethodDefUnit = nullptr;
1554  unsigned MethodLine = 0;
1555  if (!Method->isImplicit()) {
1556  MethodDefUnit = getOrCreateFile(Method->getLocation());
1557  MethodLine = getLineNumber(Method->getLocation());
1558  }
1559 
1560  // Collect virtual method info.
1561  llvm::DIType *ContainingType = nullptr;
1562  unsigned VIndex = 0;
1563  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1564  llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
1565  int ThisAdjustment = 0;
1566 
1567  if (Method->isVirtual()) {
1568  if (Method->isPure())
1569  SPFlags |= llvm::DISubprogram::SPFlagPureVirtual;
1570  else
1571  SPFlags |= llvm::DISubprogram::SPFlagVirtual;
1572 
1573  if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1574  // It doesn't make sense to give a virtual destructor a vtable index,
1575  // since a single destructor has two entries in the vtable.
1576  if (!isa<CXXDestructorDecl>(Method))
1577  VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
1578  } else {
1579  // Emit MS ABI vftable information. There is only one entry for the
1580  // deleting dtor.
1581  const auto *DD = dyn_cast<CXXDestructorDecl>(Method);
1582  GlobalDecl GD = DD ? GlobalDecl(DD, Dtor_Deleting) : GlobalDecl(Method);
1584  CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1585  VIndex = ML.Index;
1586 
1587  // CodeView only records the vftable offset in the class that introduces
1588  // the virtual method. This is possible because, unlike Itanium, the MS
1589  // C++ ABI does not include all virtual methods from non-primary bases in
1590  // the vtable for the most derived class. For example, if C inherits from
1591  // A and B, C's primary vftable will not include B's virtual methods.
1592  if (Method->size_overridden_methods() == 0)
1593  Flags |= llvm::DINode::FlagIntroducedVirtual;
1594 
1595  // The 'this' adjustment accounts for both the virtual and non-virtual
1596  // portions of the adjustment. Presumably the debugger only uses it when
1597  // it knows the dynamic type of an object.
1598  ThisAdjustment = CGM.getCXXABI()
1599  .getVirtualFunctionPrologueThisAdjustment(GD)
1600  .getQuantity();
1601  }
1602  ContainingType = RecordTy;
1603  }
1604 
1605  // We're checking for deleted C++ special member functions
1606  // [Ctors,Dtors, Copy/Move]
1607  auto checkAttrDeleted = [&](const auto *Method) {
1608  if (Method->getCanonicalDecl()->isDeleted())
1609  SPFlags |= llvm::DISubprogram::SPFlagDeleted;
1610  };
1611 
1612  switch (Method->getKind()) {
1613 
1614  case Decl::CXXConstructor:
1615  case Decl::CXXDestructor:
1616  checkAttrDeleted(Method);
1617  break;
1618  case Decl::CXXMethod:
1619  if (Method->isCopyAssignmentOperator() ||
1620  Method->isMoveAssignmentOperator())
1621  checkAttrDeleted(Method);
1622  break;
1623  default:
1624  break;
1625  }
1626 
1627  if (Method->isNoReturn())
1628  Flags |= llvm::DINode::FlagNoReturn;
1629 
1630  if (Method->isStatic())
1631  Flags |= llvm::DINode::FlagStaticMember;
1632  if (Method->isImplicit())
1633  Flags |= llvm::DINode::FlagArtificial;
1634  Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
1635  if (const auto *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1636  if (CXXC->isExplicit())
1637  Flags |= llvm::DINode::FlagExplicit;
1638  } else if (const auto *CXXC = dyn_cast<CXXConversionDecl>(Method)) {
1639  if (CXXC->isExplicit())
1640  Flags |= llvm::DINode::FlagExplicit;
1641  }
1642  if (Method->hasPrototype())
1643  Flags |= llvm::DINode::FlagPrototyped;
1644  if (Method->getRefQualifier() == RQ_LValue)
1645  Flags |= llvm::DINode::FlagLValueReference;
1646  if (Method->getRefQualifier() == RQ_RValue)
1647  Flags |= llvm::DINode::FlagRValueReference;
1648  if (CGM.getLangOpts().Optimize)
1649  SPFlags |= llvm::DISubprogram::SPFlagOptimized;
1650 
1651  // In this debug mode, emit type info for a class when its constructor type
1652  // info is emitted.
1653  if (DebugKind == codegenoptions::DebugInfoConstructor)
1654  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
1655  completeClass(CD->getParent());
1656 
1657  llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1658  llvm::DISubprogram *SP = DBuilder.createMethod(
1659  RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
1660  MethodTy, VIndex, ThisAdjustment, ContainingType, Flags, SPFlags,
1661  TParamsArray.get());
1662 
1663  SPCache[Method->getCanonicalDecl()].reset(SP);
1664 
1665  return SP;
1666 }
1667 
1668 void CGDebugInfo::CollectCXXMemberFunctions(
1669  const CXXRecordDecl *RD, llvm::DIFile *Unit,
1670  SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
1671 
1672  // Since we want more than just the individual member decls if we
1673  // have templated functions iterate over every declaration to gather
1674  // the functions.
1675  for (const auto *I : RD->decls()) {
1676  const auto *Method = dyn_cast<CXXMethodDecl>(I);
1677  // If the member is implicit, don't add it to the member list. This avoids
1678  // the member being added to type units by LLVM, while still allowing it
1679  // to be emitted into the type declaration/reference inside the compile
1680  // unit.
1681  // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
1682  // FIXME: Handle Using(Shadow?)Decls here to create
1683  // DW_TAG_imported_declarations inside the class for base decls brought into
1684  // derived classes. GDB doesn't seem to notice/leverage these when I tried
1685  // it, so I'm not rushing to fix this. (GCC seems to produce them, if
1686  // referenced)
1687  if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>())
1688  continue;
1689 
1690  if (Method->getType()->castAs<FunctionProtoType>()->getContainedAutoType())
1691  continue;
1692 
1693  // Reuse the existing member function declaration if it exists.
1694  // It may be associated with the declaration of the type & should be
1695  // reused as we're building the definition.
1696  //
1697  // This situation can arise in the vtable-based debug info reduction where
1698  // implicit members are emitted in a non-vtable TU.
1699  auto MI = SPCache.find(Method->getCanonicalDecl());
1700  EltTys.push_back(MI == SPCache.end()
1701  ? CreateCXXMemberFunction(Method, Unit, RecordTy)
1702  : static_cast<llvm::Metadata *>(MI->second));
1703  }
1704 }
1705 
1706 void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
1708  llvm::DIType *RecordTy) {
1710  CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->bases(), SeenTypes,
1711  llvm::DINode::FlagZero);
1712 
1713  // If we are generating CodeView debug info, we also need to emit records for
1714  // indirect virtual base classes.
1715  if (CGM.getCodeGenOpts().EmitCodeView) {
1716  CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->vbases(), SeenTypes,
1717  llvm::DINode::FlagIndirectVirtualBase);
1718  }
1719 }
1720 
1721 void CGDebugInfo::CollectCXXBasesAux(
1722  const CXXRecordDecl *RD, llvm::DIFile *Unit,
1723  SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy,
1726  llvm::DINode::DIFlags StartingFlags) {
1727  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1728  for (const auto &BI : Bases) {
1729  const auto *Base =
1730  cast<CXXRecordDecl>(BI.getType()->castAs<RecordType>()->getDecl());
1731  if (!SeenTypes.insert(Base).second)
1732  continue;
1733  auto *BaseTy = getOrCreateType(BI.getType(), Unit);
1734  llvm::DINode::DIFlags BFlags = StartingFlags;
1735  uint64_t BaseOffset;
1736  uint32_t VBPtrOffset = 0;
1737 
1738  if (BI.isVirtual()) {
1739  if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1740  // virtual base offset offset is -ve. The code generator emits dwarf
1741  // expression where it expects +ve number.
1742  BaseOffset = 0 - CGM.getItaniumVTableContext()
1743  .getVirtualBaseOffsetOffset(RD, Base)
1744  .getQuantity();
1745  } else {
1746  // In the MS ABI, store the vbtable offset, which is analogous to the
1747  // vbase offset offset in Itanium.
1748  BaseOffset =
1749  4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base);
1750  VBPtrOffset = CGM.getContext()
1751  .getASTRecordLayout(RD)
1752  .getVBPtrOffset()
1753  .getQuantity();
1754  }
1755  BFlags |= llvm::DINode::FlagVirtual;
1756  } else
1757  BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1758  // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1759  // BI->isVirtual() and bits when not.
1760 
1761  BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
1762  llvm::DIType *DTy = DBuilder.createInheritance(RecordTy, BaseTy, BaseOffset,
1763  VBPtrOffset, BFlags);
1764  EltTys.push_back(DTy);
1765  }
1766 }
1767 
1768 llvm::DINodeArray
1769 CGDebugInfo::CollectTemplateParams(const TemplateParameterList *TPList,
1771  llvm::DIFile *Unit) {
1772  SmallVector<llvm::Metadata *, 16> TemplateParams;
1773  for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1774  const TemplateArgument &TA = TAList[i];
1775  StringRef Name;
1776  if (TPList)
1777  Name = TPList->getParam(i)->getName();
1778  switch (TA.getKind()) {
1779  case TemplateArgument::Type: {
1780  llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
1781  TemplateParams.push_back(
1782  DBuilder.createTemplateTypeParameter(TheCU, Name, TTy));
1783  } break;
1785  llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
1786  TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1787  TheCU, Name, TTy,
1788  llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
1789  } break;
1791  const ValueDecl *D = TA.getAsDecl();
1792  QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext());
1793  llvm::DIType *TTy = getOrCreateType(T, Unit);
1794  llvm::Constant *V = nullptr;
1795  // Skip retrieve the value if that template parameter has cuda device
1796  // attribute, i.e. that value is not available at the host side.
1797  if (!CGM.getLangOpts().CUDA || CGM.getLangOpts().CUDAIsDevice ||
1798  !D->hasAttr<CUDADeviceAttr>()) {
1799  const CXXMethodDecl *MD;
1800  // Variable pointer template parameters have a value that is the address
1801  // of the variable.
1802  if (const auto *VD = dyn_cast<VarDecl>(D))
1803  V = CGM.GetAddrOfGlobalVar(VD);
1804  // Member function pointers have special support for building them,
1805  // though this is currently unsupported in LLVM CodeGen.
1806  else if ((MD = dyn_cast<CXXMethodDecl>(D)) && MD->isInstance())
1807  V = CGM.getCXXABI().EmitMemberFunctionPointer(MD);
1808  else if (const auto *FD = dyn_cast<FunctionDecl>(D))
1809  V = CGM.GetAddrOfFunction(FD);
1810  // Member data pointers have special handling too to compute the fixed
1811  // offset within the object.
1812  else if (const auto *MPT =
1813  dyn_cast<MemberPointerType>(T.getTypePtr())) {
1814  // These five lines (& possibly the above member function pointer
1815  // handling) might be able to be refactored to use similar code in
1816  // CodeGenModule::getMemberPointerConstant
1817  uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1818  CharUnits chars =
1819  CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
1820  V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
1821  }
1822  assert(V && "Failed to find template parameter pointer");
1823  V = V->stripPointerCasts();
1824  }
1825  TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1826  TheCU, Name, TTy, cast_or_null<llvm::Constant>(V)));
1827  } break;
1829  QualType T = TA.getNullPtrType();
1830  llvm::DIType *TTy = getOrCreateType(T, Unit);
1831  llvm::Constant *V = nullptr;
1832  // Special case member data pointer null values since they're actually -1
1833  // instead of zero.
1834  if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr()))
1835  // But treat member function pointers as simple zero integers because
1836  // it's easier than having a special case in LLVM's CodeGen. If LLVM
1837  // CodeGen grows handling for values of non-null member function
1838  // pointers then perhaps we could remove this special case and rely on
1839  // EmitNullMemberPointer for member function pointers.
1840  if (MPT->isMemberDataPointer())
1841  V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1842  if (!V)
1843  V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1844  TemplateParams.push_back(
1845  DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V));
1846  } break;
1848  TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
1849  TheCU, Name, nullptr,
1851  break;
1853  TemplateParams.push_back(DBuilder.createTemplateParameterPack(
1854  TheCU, Name, nullptr,
1855  CollectTemplateParams(nullptr, TA.getPackAsArray(), Unit)));
1856  break;
1858  const Expr *E = TA.getAsExpr();
1859  QualType T = E->getType();
1860  if (E->isGLValue())
1861  T = CGM.getContext().getLValueReferenceType(T);
1862  llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(E, T);
1863  assert(V && "Expression in template argument isn't constant");
1864  llvm::DIType *TTy = getOrCreateType(T, Unit);
1865  TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1866  TheCU, Name, TTy, V->stripPointerCasts()));
1867  } break;
1868  // And the following should never occur:
1871  llvm_unreachable(
1872  "These argument types shouldn't exist in concrete types");
1873  }
1874  }
1875  return DBuilder.getOrCreateArray(TemplateParams);
1876 }
1877 
1878 llvm::DINodeArray
1879 CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
1880  llvm::DIFile *Unit) {
1881  if (FD->getTemplatedKind() ==
1884  ->getTemplate()
1886  return CollectTemplateParams(
1887  TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
1888  }
1889  return llvm::DINodeArray();
1890 }
1891 
1892 llvm::DINodeArray CGDebugInfo::CollectVarTemplateParams(const VarDecl *VL,
1893  llvm::DIFile *Unit) {
1894  // Always get the full list of parameters, not just the ones from the
1895  // specialization. A partial specialization may have fewer parameters than
1896  // there are arguments.
1897  auto *TS = dyn_cast<VarTemplateSpecializationDecl>(VL);
1898  if (!TS)
1899  return llvm::DINodeArray();
1900  VarTemplateDecl *T = TS->getSpecializedTemplate();
1901  const TemplateParameterList *TList = T->getTemplateParameters();
1902  auto TA = TS->getTemplateArgs().asArray();
1903  return CollectTemplateParams(TList, TA, Unit);
1904 }
1905 
1906 llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(
1907  const ClassTemplateSpecializationDecl *TSpecial, llvm::DIFile *Unit) {
1908  // Always get the full list of parameters, not just the ones from the
1909  // specialization. A partial specialization may have fewer parameters than
1910  // there are arguments.
1911  TemplateParameterList *TPList =
1913  const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
1914  return CollectTemplateParams(TPList, TAList.asArray(), Unit);
1915 }
1916 
1917 llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
1918  if (VTablePtrType)
1919  return VTablePtrType;
1920 
1921  ASTContext &Context = CGM.getContext();
1922 
1923  /* Function type */
1924  llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
1925  llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);
1926  llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements);
1927  unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1928  unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
1929  Optional<unsigned> DWARFAddressSpace =
1930  CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
1931 
1932  llvm::DIType *vtbl_ptr_type = DBuilder.createPointerType(
1933  SubTy, Size, 0, DWARFAddressSpace, "__vtbl_ptr_type");
1934  VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1935  return VTablePtrType;
1936 }
1937 
1938 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1939  // Copy the gdb compatible name on the side and use its reference.
1940  return internString("_vptr$", RD->getNameAsString());
1941 }
1942 
1943 StringRef CGDebugInfo::getDynamicInitializerName(const VarDecl *VD,
1944  DynamicInitKind StubKind,
1945  llvm::Function *InitFn) {
1946  // If we're not emitting codeview, use the mangled name. For Itanium, this is
1947  // arbitrary.
1948  if (!CGM.getCodeGenOpts().EmitCodeView)
1949  return InitFn->getName();
1950 
1951  // Print the normal qualified name for the variable, then break off the last
1952  // NNS, and add the appropriate other text. Clang always prints the global
1953  // variable name without template arguments, so we can use rsplit("::") and
1954  // then recombine the pieces.
1955  SmallString<128> QualifiedGV;
1956  StringRef Quals;
1957  StringRef GVName;
1958  {
1959  llvm::raw_svector_ostream OS(QualifiedGV);
1960  VD->printQualifiedName(OS, getPrintingPolicy());
1961  std::tie(Quals, GVName) = OS.str().rsplit("::");
1962  if (GVName.empty())
1963  std::swap(Quals, GVName);
1964  }
1965 
1966  SmallString<128> InitName;
1967  llvm::raw_svector_ostream OS(InitName);
1968  if (!Quals.empty())
1969  OS << Quals << "::";
1970 
1971  switch (StubKind) {
1973  llvm_unreachable("not an initializer");
1975  OS << "`dynamic initializer for '";
1976  break;
1978  OS << "`dynamic atexit destructor for '";
1979  break;
1980  }
1981 
1982  OS << GVName;
1983 
1984  // Add any template specialization args.
1985  if (const auto *VTpl = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
1986  printTemplateArgumentList(OS, VTpl->getTemplateArgs().asArray(),
1987  getPrintingPolicy());
1988  }
1989 
1990  OS << '\'';
1991 
1992  return internString(OS.str());
1993 }
1994 
1995 void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
1997  llvm::DICompositeType *RecordTy) {
1998  // If this class is not dynamic then there is not any vtable info to collect.
1999  if (!RD->isDynamicClass())
2000  return;
2001 
2002  // Don't emit any vtable shape or vptr info if this class doesn't have an
2003  // extendable vfptr. This can happen if the class doesn't have virtual
2004  // methods, or in the MS ABI if those virtual methods only come from virtually
2005  // inherited bases.
2006  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2007  if (!RL.hasExtendableVFPtr())
2008  return;
2009 
2010  // CodeView needs to know how large the vtable of every dynamic class is, so
2011  // emit a special named pointer type into the element list. The vptr type
2012  // points to this type as well.
2013  llvm::DIType *VPtrTy = nullptr;
2014  bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView &&
2015  CGM.getTarget().getCXXABI().isMicrosoft();
2016  if (NeedVTableShape) {
2017  uint64_t PtrWidth =
2018  CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
2019  const VTableLayout &VFTLayout =
2020  CGM.getMicrosoftVTableContext().getVFTableLayout(RD, CharUnits::Zero());
2021  unsigned VSlotCount =
2022  VFTLayout.vtable_components().size() - CGM.getLangOpts().RTTIData;
2023  unsigned VTableWidth = PtrWidth * VSlotCount;
2024  unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
2025  Optional<unsigned> DWARFAddressSpace =
2026  CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
2027 
2028  // Create a very wide void* type and insert it directly in the element list.
2029  llvm::DIType *VTableType = DBuilder.createPointerType(
2030  nullptr, VTableWidth, 0, DWARFAddressSpace, "__vtbl_ptr_type");
2031  EltTys.push_back(VTableType);
2032 
2033  // The vptr is a pointer to this special vtable type.
2034  VPtrTy = DBuilder.createPointerType(VTableType, PtrWidth);
2035  }
2036 
2037  // If there is a primary base then the artificial vptr member lives there.
2038  if (RL.getPrimaryBase())
2039  return;
2040 
2041  if (!VPtrTy)
2042  VPtrTy = getOrCreateVTablePtrType(Unit);
2043 
2044  unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
2045  llvm::DIType *VPtrMember =
2046  DBuilder.createMemberType(Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
2047  llvm::DINode::FlagArtificial, VPtrTy);
2048  EltTys.push_back(VPtrMember);
2049 }
2050 
2052  SourceLocation Loc) {
2053  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
2054  llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
2055  return T;
2056 }
2057 
2059  SourceLocation Loc) {
2060  return getOrCreateStandaloneType(D, Loc);
2061 }
2062 
2064  SourceLocation Loc) {
2065  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
2066  assert(!D.isNull() && "null type");
2067  llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
2068  assert(T && "could not create debug info for type");
2069 
2070  RetainedTypes.push_back(D.getAsOpaquePtr());
2071  return T;
2072 }
2073 
2074 void CGDebugInfo::addHeapAllocSiteMetadata(llvm::Instruction *CI,
2075  QualType D,
2076  SourceLocation Loc) {
2077  llvm::MDNode *node;
2078  if (D.getTypePtr()->isVoidPointerType()) {
2079  node = llvm::MDNode::get(CGM.getLLVMContext(), None);
2080  } else {
2081  QualType PointeeTy = D.getTypePtr()->getPointeeType();
2082  node = getOrCreateType(PointeeTy, getOrCreateFile(Loc));
2083  }
2084 
2085  CI->setMetadata("heapallocsite", node);
2086 }
2087 
2089  if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2090  return;
2091  QualType Ty = CGM.getContext().getEnumType(ED);
2092  void *TyPtr = Ty.getAsOpaquePtr();
2093  auto I = TypeCache.find(TyPtr);
2094  if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl())
2095  return;
2096  llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>());
2097  assert(!Res->isForwardDecl());
2098  TypeCache[TyPtr].reset(Res);
2099 }
2100 
2102  if (DebugKind > codegenoptions::LimitedDebugInfo ||
2103  !CGM.getLangOpts().CPlusPlus)
2104  completeRequiredType(RD);
2105 }
2106 
2107 /// Return true if the class or any of its methods are marked dllimport.
2108 static bool isClassOrMethodDLLImport(const CXXRecordDecl *RD) {
2109  if (RD->hasAttr<DLLImportAttr>())
2110  return true;
2111  for (const CXXMethodDecl *MD : RD->methods())
2112  if (MD->hasAttr<DLLImportAttr>())
2113  return true;
2114  return false;
2115 }
2116 
2117 /// Does a type definition exist in an imported clang module?
2118 static bool isDefinedInClangModule(const RecordDecl *RD) {
2119  // Only definitions that where imported from an AST file come from a module.
2120  if (!RD || !RD->isFromASTFile())
2121  return false;
2122  // Anonymous entities cannot be addressed. Treat them as not from module.
2123  if (!RD->isExternallyVisible() && RD->getName().empty())
2124  return false;
2125  if (auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) {
2126  if (!CXXDecl->isCompleteDefinition())
2127  return false;
2128  // Check wether RD is a template.
2129  auto TemplateKind = CXXDecl->getTemplateSpecializationKind();
2130  if (TemplateKind != TSK_Undeclared) {
2131  // Unfortunately getOwningModule() isn't accurate enough to find the
2132  // owning module of a ClassTemplateSpecializationDecl that is inside a
2133  // namespace spanning multiple modules.
2134  bool Explicit = false;
2135  if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(CXXDecl))
2136  Explicit = TD->isExplicitInstantiationOrSpecialization();
2137  if (!Explicit && CXXDecl->getEnclosingNamespaceContext())
2138  return false;
2139  // This is a template, check the origin of the first member.
2140  if (CXXDecl->field_begin() == CXXDecl->field_end())
2141  return TemplateKind == TSK_ExplicitInstantiationDeclaration;
2142  if (!CXXDecl->field_begin()->isFromASTFile())
2143  return false;
2144  }
2145  }
2146  return true;
2147 }
2148 
2150  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2151  if (CXXRD->isDynamicClass() &&
2152  CGM.getVTableLinkage(CXXRD) ==
2153  llvm::GlobalValue::AvailableExternallyLinkage &&
2154  !isClassOrMethodDLLImport(CXXRD))
2155  return;
2156 
2157  if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
2158  return;
2159 
2160  completeClass(RD);
2161 }
2162 
2164  if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2165  return;
2166  QualType Ty = CGM.getContext().getRecordType(RD);
2167  void *TyPtr = Ty.getAsOpaquePtr();
2168  auto I = TypeCache.find(TyPtr);
2169  if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl())
2170  return;
2171  llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<RecordType>());
2172  assert(!Res->isForwardDecl());
2173  TypeCache[TyPtr].reset(Res);
2174 }
2175 
2178  for (CXXMethodDecl *MD : llvm::make_range(I, End))
2180  if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
2181  !MD->getMemberSpecializationInfo()->isExplicitSpecialization())
2182  return true;
2183  return false;
2184 }
2185 
2187  bool DebugTypeExtRefs, const RecordDecl *RD,
2188  const LangOptions &LangOpts) {
2189  if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
2190  return true;
2191 
2192  if (auto *ES = RD->getASTContext().getExternalSource())
2193  if (ES->hasExternalDefinitions(RD) == ExternalASTSource::EK_Always)
2194  return true;
2195 
2196  if (DebugKind > codegenoptions::LimitedDebugInfo)
2197  return false;
2198 
2199  if (!LangOpts.CPlusPlus)
2200  return false;
2201 
2202  if (!RD->isCompleteDefinitionRequired())
2203  return true;
2204 
2205  const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2206 
2207  if (!CXXDecl)
2208  return false;
2209 
2210  // Only emit complete debug info for a dynamic class when its vtable is
2211  // emitted. However, Microsoft debuggers don't resolve type information
2212  // across DLL boundaries, so skip this optimization if the class or any of its
2213  // methods are marked dllimport. This isn't a complete solution, since objects
2214  // without any dllimport methods can be used in one DLL and constructed in
2215  // another, but it is the current behavior of LimitedDebugInfo.
2216  if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() &&
2217  !isClassOrMethodDLLImport(CXXDecl))
2218  return true;
2219 
2220  // In constructor debug mode, only emit debug info for a class when its
2221  // constructor is emitted. Skip this optimization if the class or any of
2222  // its methods are marked dllimport.
2223  if (DebugKind == codegenoptions::DebugInfoConstructor &&
2224  !CXXDecl->isLambda() && !isClassOrMethodDLLImport(CXXDecl)) {
2225  for (const auto *Ctor : CXXDecl->ctors()) {
2226  if (Ctor->isUserProvided())
2227  return true;
2228  }
2229  }
2230 
2232  if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
2233  Spec = SD->getSpecializationKind();
2234 
2237  CXXDecl->method_end()))
2238  return true;
2239 
2240  return false;
2241 }
2242 
2244  if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, CGM.getLangOpts()))
2245  return;
2246 
2247  QualType Ty = CGM.getContext().getRecordType(RD);
2248  llvm::DIType *T = getTypeOrNull(Ty);
2249  if (T && T->isForwardDecl())
2250  completeClassData(RD);
2251 }
2252 
2253 llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
2254  RecordDecl *RD = Ty->getDecl();
2255  llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
2256  if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
2257  CGM.getLangOpts())) {
2258  if (!T)
2259  T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
2260  return T;
2261  }
2262 
2263  return CreateTypeDefinition(Ty);
2264 }
2265 
2266 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
2267  RecordDecl *RD = Ty->getDecl();
2268 
2269  // Get overall information about the record type for the debug info.
2270  llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
2271 
2272  // Records and classes and unions can all be recursive. To handle them, we
2273  // first generate a debug descriptor for the struct as a forward declaration.
2274  // Then (if it is a definition) we go through and get debug info for all of
2275  // its members. Finally, we create a descriptor for the complete type (which
2276  // may refer to the forward decl if the struct is recursive) and replace all
2277  // uses of the forward declaration with the final definition.
2278  llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty, DefUnit);
2279 
2280  const RecordDecl *D = RD->getDefinition();
2281  if (!D || !D->isCompleteDefinition())
2282  return FwdDecl;
2283 
2284  if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
2285  CollectContainingType(CXXDecl, FwdDecl);
2286 
2287  // Push the struct on region stack.
2288  LexicalBlockStack.emplace_back(&*FwdDecl);
2289  RegionMap[Ty->getDecl()].reset(FwdDecl);
2290 
2291  // Convert all the elements.
2293  // what about nested types?
2294 
2295  // Note: The split of CXXDecl information here is intentional, the
2296  // gdb tests will depend on a certain ordering at printout. The debug
2297  // information offsets are still correct if we merge them all together
2298  // though.
2299  const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2300  if (CXXDecl) {
2301  CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
2302  CollectVTableInfo(CXXDecl, DefUnit, EltTys, FwdDecl);
2303  }
2304 
2305  // Collect data fields (including static variables and any initializers).
2306  CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
2307  if (CXXDecl)
2308  CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
2309 
2310  LexicalBlockStack.pop_back();
2311  RegionMap.erase(Ty->getDecl());
2312 
2313  llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2314  DBuilder.replaceArrays(FwdDecl, Elements);
2315 
2316  if (FwdDecl->isTemporary())
2317  FwdDecl =
2318  llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
2319 
2320  RegionMap[Ty->getDecl()].reset(FwdDecl);
2321  return FwdDecl;
2322 }
2323 
2324 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
2325  llvm::DIFile *Unit) {
2326  // Ignore protocols.
2327  return getOrCreateType(Ty->getBaseType(), Unit);
2328 }
2329 
2330 llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty,
2331  llvm::DIFile *Unit) {
2332  // Ignore protocols.
2333  SourceLocation Loc = Ty->getDecl()->getLocation();
2334 
2335  // Use Typedefs to represent ObjCTypeParamType.
2336  return DBuilder.createTypedef(
2337  getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
2338  Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
2339  getDeclContextDescriptor(Ty->getDecl()));
2340 }
2341 
2342 /// \return true if Getter has the default name for the property PD.
2344  const ObjCMethodDecl *Getter) {
2345  assert(PD);
2346  if (!Getter)
2347  return true;
2348 
2349  assert(Getter->getDeclName().isObjCZeroArgSelector());
2350  return PD->getName() ==
2352 }
2353 
2354 /// \return true if Setter has the default name for the property PD.
2356  const ObjCMethodDecl *Setter) {
2357  assert(PD);
2358  if (!Setter)
2359  return true;
2360 
2361  assert(Setter->getDeclName().isObjCOneArgSelector());
2364 }
2365 
2366 llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
2367  llvm::DIFile *Unit) {
2368  ObjCInterfaceDecl *ID = Ty->getDecl();
2369  if (!ID)
2370  return nullptr;
2371 
2372  // Return a forward declaration if this type was imported from a clang module,
2373  // and this is not the compile unit with the implementation of the type (which
2374  // may contain hidden ivars).
2375  if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition() &&
2376  !ID->getImplementation())
2377  return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2378  ID->getName(),
2379  getDeclContextDescriptor(ID), Unit, 0);
2380 
2381  // Get overall information about the record type for the debug info.
2382  llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2383  unsigned Line = getLineNumber(ID->getLocation());
2384  auto RuntimeLang =
2385  static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
2386 
2387  // If this is just a forward declaration return a special forward-declaration
2388  // debug type since we won't be able to lay out the entire type.
2389  ObjCInterfaceDecl *Def = ID->getDefinition();
2390  if (!Def || !Def->getImplementation()) {
2391  llvm::DIScope *Mod = getParentModuleOrNull(ID);
2392  llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
2393  llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU,
2394  DefUnit, Line, RuntimeLang);
2395  ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
2396  return FwdDecl;
2397  }
2398 
2399  return CreateTypeDefinition(Ty, Unit);
2400 }
2401 
2402 llvm::DIModule *
2403 CGDebugInfo::getOrCreateModuleRef(ExternalASTSource::ASTSourceDescriptor Mod,
2404  bool CreateSkeletonCU) {
2405  // Use the Module pointer as the key into the cache. This is a
2406  // nullptr if the "Module" is a PCH, which is safe because we don't
2407  // support chained PCH debug info, so there can only be a single PCH.
2408  const Module *M = Mod.getModuleOrNull();
2409  auto ModRef = ModuleCache.find(M);
2410  if (ModRef != ModuleCache.end())
2411  return cast<llvm::DIModule>(ModRef->second);
2412 
2413  // Macro definitions that were defined with "-D" on the command line.
2414  SmallString<128> ConfigMacros;
2415  {
2416  llvm::raw_svector_ostream OS(ConfigMacros);
2417  const auto &PPOpts = CGM.getPreprocessorOpts();
2418  unsigned I = 0;
2419  // Translate the macro definitions back into a command line.
2420  for (auto &M : PPOpts.Macros) {
2421  if (++I > 1)
2422  OS << " ";
2423  const std::string &Macro = M.first;
2424  bool Undef = M.second;
2425  OS << "\"-" << (Undef ? 'U' : 'D');
2426  for (char c : Macro)
2427  switch (c) {
2428  case '\\':
2429  OS << "\\\\";
2430  break;
2431  case '"':
2432  OS << "\\\"";
2433  break;
2434  default:
2435  OS << c;
2436  }
2437  OS << '\"';
2438  }
2439  }
2440 
2441  bool IsRootModule = M ? !M->Parent : true;
2442  // When a module name is specified as -fmodule-name, that module gets a
2443  // clang::Module object, but it won't actually be built or imported; it will
2444  // be textual.
2445  if (CreateSkeletonCU && IsRootModule && Mod.getASTFile().empty() && M)
2446  assert(StringRef(M->Name).startswith(CGM.getLangOpts().ModuleName) &&
2447  "clang module without ASTFile must be specified by -fmodule-name");
2448 
2449  if (CreateSkeletonCU && IsRootModule && !Mod.getASTFile().empty()) {
2450  // PCH files don't have a signature field in the control block,
2451  // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
2452  // We use the lower 64 bits for debug info.
2453  uint64_t Signature =
2454  Mod.getSignature()
2455  ? (uint64_t)Mod.getSignature()[1] << 32 | Mod.getSignature()[0]
2456  : ~1ULL;
2457  llvm::DIBuilder DIB(CGM.getModule());
2458  DIB.createCompileUnit(TheCU->getSourceLanguage(),
2459  // TODO: Support "Source" from external AST providers?
2460  DIB.createFile(Mod.getModuleName(), Mod.getPath()),
2461  TheCU->getProducer(), true, StringRef(), 0,
2462  Mod.getASTFile(), llvm::DICompileUnit::FullDebug,
2463  Signature);
2464  DIB.finalize();
2465  }
2466 
2467  llvm::DIModule *Parent =
2468  IsRootModule ? nullptr
2469  : getOrCreateModuleRef(
2471  CreateSkeletonCU);
2472  llvm::DIModule *DIMod =
2473  DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
2474  Mod.getPath(), CGM.getHeaderSearchOpts().Sysroot);
2475  ModuleCache[M].reset(DIMod);
2476  return DIMod;
2477 }
2478 
2479 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
2480  llvm::DIFile *Unit) {
2481  ObjCInterfaceDecl *ID = Ty->getDecl();
2482  llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2483  unsigned Line = getLineNumber(ID->getLocation());
2484  unsigned RuntimeLang = TheCU->getSourceLanguage();
2485 
2486  // Bit size, align and offset of the type.
2487  uint64_t Size = CGM.getContext().getTypeSize(Ty);
2488  auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2489 
2490  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2491  if (ID->getImplementation())
2492  Flags |= llvm::DINode::FlagObjcClassComplete;
2493 
2494  llvm::DIScope *Mod = getParentModuleOrNull(ID);
2495  llvm::DICompositeType *RealDecl = DBuilder.createStructType(
2496  Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags,
2497  nullptr, llvm::DINodeArray(), RuntimeLang);
2498 
2499  QualType QTy(Ty, 0);
2500  TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
2501 
2502  // Push the struct on region stack.
2503  LexicalBlockStack.emplace_back(RealDecl);
2504  RegionMap[Ty->getDecl()].reset(RealDecl);
2505 
2506  // Convert all the elements.
2508 
2509  ObjCInterfaceDecl *SClass = ID->getSuperClass();
2510  if (SClass) {
2511  llvm::DIType *SClassTy =
2512  getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
2513  if (!SClassTy)
2514  return nullptr;
2515 
2516  llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0,
2517  llvm::DINode::FlagZero);
2518  EltTys.push_back(InhTag);
2519  }
2520 
2521  // Create entries for all of the properties.
2522  auto AddProperty = [&](const ObjCPropertyDecl *PD) {
2523  SourceLocation Loc = PD->getLocation();
2524  llvm::DIFile *PUnit = getOrCreateFile(Loc);
2525  unsigned PLine = getLineNumber(Loc);
2526  ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
2527  ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
2528  llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
2529  PD->getName(), PUnit, PLine,
2530  hasDefaultGetterName(PD, Getter) ? ""
2531  : getSelectorName(PD->getGetterName()),
2532  hasDefaultSetterName(PD, Setter) ? ""
2533  : getSelectorName(PD->getSetterName()),
2534  PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
2535  EltTys.push_back(PropertyNode);
2536  };
2537  {
2538  llvm::SmallPtrSet<const IdentifierInfo *, 16> PropertySet;
2539  for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
2540  for (auto *PD : ClassExt->properties()) {
2541  PropertySet.insert(PD->getIdentifier());
2542  AddProperty(PD);
2543  }
2544  for (const auto *PD : ID->properties()) {
2545  // Don't emit duplicate metadata for properties that were already in a
2546  // class extension.
2547  if (!PropertySet.insert(PD->getIdentifier()).second)
2548  continue;
2549  AddProperty(PD);
2550  }
2551  }
2552 
2553  const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
2554  unsigned FieldNo = 0;
2555  for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
2556  Field = Field->getNextIvar(), ++FieldNo) {
2557  llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
2558  if (!FieldTy)
2559  return nullptr;
2560 
2561  StringRef FieldName = Field->getName();
2562 
2563  // Ignore unnamed fields.
2564  if (FieldName.empty())
2565  continue;
2566 
2567  // Get the location for the field.
2568  llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
2569  unsigned FieldLine = getLineNumber(Field->getLocation());
2570  QualType FType = Field->getType();
2571  uint64_t FieldSize = 0;
2572  uint32_t FieldAlign = 0;
2573 
2574  if (!FType->isIncompleteArrayType()) {
2575 
2576  // Bit size, align and offset of the type.
2577  FieldSize = Field->isBitField()
2578  ? Field->getBitWidthValue(CGM.getContext())
2579  : CGM.getContext().getTypeSize(FType);
2580  FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
2581  }
2582 
2583  uint64_t FieldOffset;
2584  if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2585  // We don't know the runtime offset of an ivar if we're using the
2586  // non-fragile ABI. For bitfields, use the bit offset into the first
2587  // byte of storage of the bitfield. For other fields, use zero.
2588  if (Field->isBitField()) {
2589  FieldOffset =
2590  CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
2591  FieldOffset %= CGM.getContext().getCharWidth();
2592  } else {
2593  FieldOffset = 0;
2594  }
2595  } else {
2596  FieldOffset = RL.getFieldOffset(FieldNo);
2597  }
2598 
2599  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2600  if (Field->getAccessControl() == ObjCIvarDecl::Protected)
2601  Flags = llvm::DINode::FlagProtected;
2602  else if (Field->getAccessControl() == ObjCIvarDecl::Private)
2603  Flags = llvm::DINode::FlagPrivate;
2604  else if (Field->getAccessControl() == ObjCIvarDecl::Public)
2605  Flags = llvm::DINode::FlagPublic;
2606 
2607  llvm::MDNode *PropertyNode = nullptr;
2608  if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
2609  if (ObjCPropertyImplDecl *PImpD =
2610  ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
2611  if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
2612  SourceLocation Loc = PD->getLocation();
2613  llvm::DIFile *PUnit = getOrCreateFile(Loc);
2614  unsigned PLine = getLineNumber(Loc);
2615  ObjCMethodDecl *Getter = PImpD->getGetterMethodDecl();
2616  ObjCMethodDecl *Setter = PImpD->getSetterMethodDecl();
2617  PropertyNode = DBuilder.createObjCProperty(
2618  PD->getName(), PUnit, PLine,
2619  hasDefaultGetterName(PD, Getter)
2620  ? ""
2621  : getSelectorName(PD->getGetterName()),
2622  hasDefaultSetterName(PD, Setter)
2623  ? ""
2624  : getSelectorName(PD->getSetterName()),
2625  PD->getPropertyAttributes(),
2626  getOrCreateType(PD->getType(), PUnit));
2627  }
2628  }
2629  }
2630  FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
2631  FieldSize, FieldAlign, FieldOffset, Flags,
2632  FieldTy, PropertyNode);
2633  EltTys.push_back(FieldTy);
2634  }
2635 
2636  llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2637  DBuilder.replaceArrays(RealDecl, Elements);
2638 
2639  LexicalBlockStack.pop_back();
2640  return RealDecl;
2641 }
2642 
2643 llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
2644  llvm::DIFile *Unit) {
2645  llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
2646  int64_t Count = Ty->getNumElements();
2647 
2648  llvm::Metadata *Subscript;
2649  QualType QTy(Ty, 0);
2650  auto SizeExpr = SizeExprCache.find(QTy);
2651  if (SizeExpr != SizeExprCache.end())
2652  Subscript = DBuilder.getOrCreateSubrange(0, SizeExpr->getSecond());
2653  else
2654  Subscript = DBuilder.getOrCreateSubrange(0, Count ? Count : -1);
2655  llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
2656 
2657  uint64_t Size = CGM.getContext().getTypeSize(Ty);
2658  auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2659 
2660  return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
2661 }
2662 
2663 llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
2664  uint64_t Size;
2665  uint32_t Align;
2666 
2667  // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
2668  if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
2669  Size = 0;
2670  Align = getTypeAlignIfRequired(CGM.getContext().getBaseElementType(VAT),
2671  CGM.getContext());
2672  } else if (Ty->isIncompleteArrayType()) {
2673  Size = 0;
2674  if (Ty->getElementType()->isIncompleteType())
2675  Align = 0;
2676  else
2677  Align = getTypeAlignIfRequired(Ty->getElementType(), CGM.getContext());
2678  } else if (Ty->isIncompleteType()) {
2679  Size = 0;
2680  Align = 0;
2681  } else {
2682  // Size and align of the whole array, not the element type.
2683  Size = CGM.getContext().getTypeSize(Ty);
2684  Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2685  }
2686 
2687  // Add the dimensions of the array. FIXME: This loses CV qualifiers from
2688  // interior arrays, do we care? Why aren't nested arrays represented the
2689  // obvious/recursive way?
2691  QualType EltTy(Ty, 0);
2692  while ((Ty = dyn_cast<ArrayType>(EltTy))) {
2693  // If the number of elements is known, then count is that number. Otherwise,
2694  // it's -1. This allows us to represent a subrange with an array of 0
2695  // elements, like this:
2696  //
2697  // struct foo {
2698  // int x[0];
2699  // };
2700  int64_t Count = -1; // Count == -1 is an unbounded array.
2701  if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty))
2702  Count = CAT->getSize().getZExtValue();
2703  else if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
2704  if (Expr *Size = VAT->getSizeExpr()) {
2705  Expr::EvalResult Result;
2706  if (Size->EvaluateAsInt(Result, CGM.getContext()))
2707  Count = Result.Val.getInt().getExtValue();
2708  }
2709  }
2710 
2711  auto SizeNode = SizeExprCache.find(EltTy);
2712  if (SizeNode != SizeExprCache.end())
2713  Subscripts.push_back(
2714  DBuilder.getOrCreateSubrange(0, SizeNode->getSecond()));
2715  else
2716  Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
2717  EltTy = Ty->getElementType();
2718  }
2719 
2720  llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
2721 
2722  return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
2723  SubscriptArray);
2724 }
2725 
2726 llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
2727  llvm::DIFile *Unit) {
2728  return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
2729  Ty->getPointeeType(), Unit);
2730 }
2731 
2732 llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
2733  llvm::DIFile *Unit) {
2734  return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, Ty,
2735  Ty->getPointeeType(), Unit);
2736 }
2737 
2738 llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
2739  llvm::DIFile *U) {
2740  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2741  uint64_t Size = 0;
2742 
2743  if (!Ty->isIncompleteType()) {
2744  Size = CGM.getContext().getTypeSize(Ty);
2745 
2746  // Set the MS inheritance model. There is no flag for the unspecified model.
2747  if (CGM.getTarget().getCXXABI().isMicrosoft()) {
2750  Flags |= llvm::DINode::FlagSingleInheritance;
2751  break;
2753  Flags |= llvm::DINode::FlagMultipleInheritance;
2754  break;
2756  Flags |= llvm::DINode::FlagVirtualInheritance;
2757  break;
2759  break;
2760  }
2761  }
2762  }
2763 
2764  llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
2765  if (Ty->isMemberDataPointerType())
2766  return DBuilder.createMemberPointerType(
2767  getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0,
2768  Flags);
2769 
2770  const FunctionProtoType *FPT =
2772  return DBuilder.createMemberPointerType(
2773  getOrCreateInstanceMethodType(
2775  FPT, U),
2776  ClassType, Size, /*Align=*/0, Flags);
2777 }
2778 
2779 llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
2780  auto *FromTy = getOrCreateType(Ty->getValueType(), U);
2781  return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy);
2782 }
2783 
2784 llvm::DIType *CGDebugInfo::CreateType(const PipeType *Ty, llvm::DIFile *U) {
2785  return getOrCreateType(Ty->getElementType(), U);
2786 }
2787 
2788 llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
2789  const EnumDecl *ED = Ty->getDecl();
2790 
2791  uint64_t Size = 0;
2792  uint32_t Align = 0;
2793  if (!ED->getTypeForDecl()->isIncompleteType()) {
2794  Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
2795  Align = getDeclAlignIfRequired(ED, CGM.getContext());
2796  }
2797 
2798  SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
2799 
2800  bool isImportedFromModule =
2801  DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition();
2802 
2803  // If this is just a forward declaration, construct an appropriately
2804  // marked node and just return it.
2805  if (isImportedFromModule || !ED->getDefinition()) {
2806  // Note that it is possible for enums to be created as part of
2807  // their own declcontext. In this case a FwdDecl will be created
2808  // twice. This doesn't cause a problem because both FwdDecls are
2809  // entered into the ReplaceMap: finalize() will replace the first
2810  // FwdDecl with the second and then replace the second with
2811  // complete type.
2812  llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
2813  llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
2814  llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType(
2815  llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0));
2816 
2817  unsigned Line = getLineNumber(ED->getLocation());
2818  StringRef EDName = ED->getName();
2819  llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
2820  llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
2821  0, Size, Align, llvm::DINode::FlagFwdDecl, Identifier);
2822 
2823  ReplaceMap.emplace_back(
2824  std::piecewise_construct, std::make_tuple(Ty),
2825  std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
2826  return RetTy;
2827  }
2828 
2829  return CreateTypeDefinition(Ty);
2830 }
2831 
2832 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
2833  const EnumDecl *ED = Ty->getDecl();
2834  uint64_t Size = 0;
2835  uint32_t Align = 0;
2836  if (!ED->getTypeForDecl()->isIncompleteType()) {
2837  Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
2838  Align = getDeclAlignIfRequired(ED, CGM.getContext());
2839  }
2840 
2841  SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
2842 
2843  // Create elements for each enumerator.
2845  ED = ED->getDefinition();
2846  bool IsSigned = ED->getIntegerType()->isSignedIntegerType();
2847  for (const auto *Enum : ED->enumerators()) {
2848  const auto &InitVal = Enum->getInitVal();
2849  auto Value = IsSigned ? InitVal.getSExtValue() : InitVal.getZExtValue();
2850  Enumerators.push_back(
2851  DBuilder.createEnumerator(Enum->getName(), Value, !IsSigned));
2852  }
2853 
2854  // Return a CompositeType for the enum itself.
2855  llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
2856 
2857  llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
2858  unsigned Line = getLineNumber(ED->getLocation());
2859  llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
2860  llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit);
2861  return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit,
2862  Line, Size, Align, EltArray, ClassTy,
2863  Identifier, ED->isScoped());
2864 }
2865 
2866 llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent,
2867  unsigned MType, SourceLocation LineLoc,
2868  StringRef Name, StringRef Value) {
2869  unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
2870  return DBuilder.createMacro(Parent, Line, MType, Name, Value);
2871 }
2872 
2873 llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent,
2874  SourceLocation LineLoc,
2875  SourceLocation FileLoc) {
2876  llvm::DIFile *FName = getOrCreateFile(FileLoc);
2877  unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
2878  return DBuilder.createTempMacroFile(Parent, Line, FName);
2879 }
2880 
2882  Qualifiers Quals;
2883  do {
2884  Qualifiers InnerQuals = T.getLocalQualifiers();
2885  // Qualifiers::operator+() doesn't like it if you add a Qualifier
2886  // that is already there.
2887  Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
2888  Quals += InnerQuals;
2889  QualType LastT = T;
2890  switch (T->getTypeClass()) {
2891  default:
2892  return C.getQualifiedType(T.getTypePtr(), Quals);
2893  case Type::TemplateSpecialization: {
2894  const auto *Spec = cast<TemplateSpecializationType>(T);
2895  if (Spec->isTypeAlias())
2896  return C.getQualifiedType(T.getTypePtr(), Quals);
2897  T = Spec->desugar();
2898  break;
2899  }
2900  case Type::TypeOfExpr:
2901  T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
2902  break;
2903  case Type::TypeOf:
2904  T = cast<TypeOfType>(T)->getUnderlyingType();
2905  break;
2906  case Type::Decltype:
2907  T = cast<DecltypeType>(T)->getUnderlyingType();
2908  break;
2909  case Type::UnaryTransform:
2910  T = cast<UnaryTransformType>(T)->getUnderlyingType();
2911  break;
2912  case Type::Attributed:
2913  T = cast<AttributedType>(T)->getEquivalentType();
2914  break;
2915  case Type::Elaborated:
2916  T = cast<ElaboratedType>(T)->getNamedType();
2917  break;
2918  case Type::Paren:
2919  T = cast<ParenType>(T)->getInnerType();
2920  break;
2921  case Type::MacroQualified:
2922  T = cast<MacroQualifiedType>(T)->getUnderlyingType();
2923  break;
2924  case Type::SubstTemplateTypeParm:
2925  T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
2926  break;
2927  case Type::Auto:
2928  case Type::DeducedTemplateSpecialization: {
2929  QualType DT = cast<DeducedType>(T)->getDeducedType();
2930  assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
2931  T = DT;
2932  break;
2933  }
2934  case Type::Adjusted:
2935  case Type::Decayed:
2936  // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
2937  T = cast<AdjustedType>(T)->getAdjustedType();
2938  break;
2939  }
2940 
2941  assert(T != LastT && "Type unwrapping failed to unwrap!");
2942  (void)LastT;
2943  } while (true);
2944 }
2945 
2946 llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
2947 
2948  // Unwrap the type as needed for debug information.
2949  Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2950 
2951  auto It = TypeCache.find(Ty.getAsOpaquePtr());
2952  if (It != TypeCache.end()) {
2953  // Verify that the debug info still exists.
2954  if (llvm::Metadata *V = It->second)
2955  return cast<llvm::DIType>(V);
2956  }
2957 
2958  return nullptr;
2959 }
2960 
2962  const ClassTemplateSpecializationDecl &SD) {
2963  if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2964  return;
2965  completeUnusedClass(SD);
2966 }
2967 
2969  if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2970  return;
2971 
2972  completeClassData(&D);
2973  // In case this type has no member function definitions being emitted, ensure
2974  // it is retained
2975  RetainedTypes.push_back(CGM.getContext().getRecordType(&D).getAsOpaquePtr());
2976 }
2977 
2978 llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
2979  if (Ty.isNull())
2980  return nullptr;
2981 
2982  llvm::TimeTraceScope TimeScope("DebugType", [&]() {
2983  std::string Name;
2984  llvm::raw_string_ostream OS(Name);
2985  Ty.print(OS, getPrintingPolicy());
2986  return Name;
2987  });
2988 
2989  // Unwrap the type as needed for debug information.
2990  Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2991 
2992  if (auto *T = getTypeOrNull(Ty))
2993  return T;
2994 
2995  llvm::DIType *Res = CreateTypeNode(Ty, Unit);
2996  void *TyPtr = Ty.getAsOpaquePtr();
2997 
2998  // And update the type cache.
2999  TypeCache[TyPtr].reset(Res);
3000 
3001  return Res;
3002 }
3003 
3004 llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
3005  // A forward declaration inside a module header does not belong to the module.
3006  if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition())
3007  return nullptr;
3008  if (DebugTypeExtRefs && D->isFromASTFile()) {
3009  // Record a reference to an imported clang module or precompiled header.
3010  auto *Reader = CGM.getContext().getExternalSource();
3011  auto Idx = D->getOwningModuleID();
3012  auto Info = Reader->getSourceDescriptor(Idx);
3013  if (Info)
3014  return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
3015  } else if (ClangModuleMap) {
3016  // We are building a clang module or a precompiled header.
3017  //
3018  // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
3019  // and it wouldn't be necessary to specify the parent scope
3020  // because the type is already unique by definition (it would look
3021  // like the output of -fno-standalone-debug). On the other hand,
3022  // the parent scope helps a consumer to quickly locate the object
3023  // file where the type's definition is located, so it might be
3024  // best to make this behavior a command line or debugger tuning
3025  // option.
3026  if (Module *M = D->getOwningModule()) {
3027  // This is a (sub-)module.
3029  return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
3030  } else {
3031  // This the precompiled header being built.
3032  return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false);
3033  }
3034  }
3035 
3036  return nullptr;
3037 }
3038 
3039 llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
3040  // Handle qualifiers, which recursively handles what they refer to.
3041  if (Ty.hasLocalQualifiers())
3042  return CreateQualifiedType(Ty, Unit);
3043 
3044  // Work out details of type.
3045  switch (Ty->getTypeClass()) {
3046 #define TYPE(Class, Base)
3047 #define ABSTRACT_TYPE(Class, Base)
3048 #define NON_CANONICAL_TYPE(Class, Base)
3049 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3050 #include "clang/AST/TypeNodes.inc"
3051  llvm_unreachable("Dependent types cannot show up in debug information");
3052 
3053  case Type::ExtVector:
3054  case Type::Vector:
3055  return CreateType(cast<VectorType>(Ty), Unit);
3056  case Type::ObjCObjectPointer:
3057  return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
3058  case Type::ObjCObject:
3059  return CreateType(cast<ObjCObjectType>(Ty), Unit);
3060  case Type::ObjCTypeParam:
3061  return CreateType(cast<ObjCTypeParamType>(Ty), Unit);
3062  case Type::ObjCInterface:
3063  return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
3064  case Type::Builtin:
3065  return CreateType(cast<BuiltinType>(Ty));
3066  case Type::Complex:
3067  return CreateType(cast<ComplexType>(Ty));
3068  case Type::Pointer:
3069  return CreateType(cast<PointerType>(Ty), Unit);
3070  case Type::BlockPointer:
3071  return CreateType(cast<BlockPointerType>(Ty), Unit);
3072  case Type::Typedef:
3073  return CreateType(cast<TypedefType>(Ty), Unit);
3074  case Type::Record:
3075  return CreateType(cast<RecordType>(Ty));
3076  case Type::Enum:
3077  return CreateEnumType(cast<EnumType>(Ty));
3078  case Type::FunctionProto:
3079  case Type::FunctionNoProto:
3080  return CreateType(cast<FunctionType>(Ty), Unit);
3081  case Type::ConstantArray:
3082  case Type::VariableArray:
3083  case Type::IncompleteArray:
3084  return CreateType(cast<ArrayType>(Ty), Unit);
3085 
3086  case Type::LValueReference:
3087  return CreateType(cast<LValueReferenceType>(Ty), Unit);
3088  case Type::RValueReference:
3089  return CreateType(cast<RValueReferenceType>(Ty), Unit);
3090 
3091  case Type::MemberPointer:
3092  return CreateType(cast<MemberPointerType>(Ty), Unit);
3093 
3094  case Type::Atomic:
3095  return CreateType(cast<AtomicType>(Ty), Unit);
3096 
3097  case Type::Pipe:
3098  return CreateType(cast<PipeType>(Ty), Unit);
3099 
3100  case Type::TemplateSpecialization:
3101  return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
3102 
3103  case Type::Auto:
3104  case Type::Attributed:
3105  case Type::Adjusted:
3106  case Type::Decayed:
3107  case Type::DeducedTemplateSpecialization:
3108  case Type::Elaborated:
3109  case Type::Paren:
3110  case Type::MacroQualified:
3111  case Type::SubstTemplateTypeParm:
3112  case Type::TypeOfExpr:
3113  case Type::TypeOf:
3114  case Type::Decltype:
3115  case Type::UnaryTransform:
3116  case Type::PackExpansion:
3117  break;
3118  }
3119 
3120  llvm_unreachable("type should have been unwrapped!");
3121 }
3122 
3123 llvm::DICompositeType *CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
3124  llvm::DIFile *Unit) {
3125  QualType QTy(Ty, 0);
3126 
3127  auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
3128 
3129  // We may have cached a forward decl when we could have created
3130  // a non-forward decl. Go ahead and create a non-forward decl
3131  // now.
3132  if (T && !T->isForwardDecl())
3133  return T;
3134 
3135  // Otherwise create the type.
3136  llvm::DICompositeType *Res = CreateLimitedType(Ty);
3137 
3138  // Propagate members from the declaration to the definition
3139  // CreateType(const RecordType*) will overwrite this with the members in the
3140  // correct order if the full type is needed.
3141  DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
3142 
3143  // And update the type cache.
3144  TypeCache[QTy.getAsOpaquePtr()].reset(Res);
3145  return Res;
3146 }
3147 
3148 // TODO: Currently used for context chains when limiting debug info.
3149 llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
3150  RecordDecl *RD = Ty->getDecl();
3151 
3152  // Get overall information about the record type for the debug info.
3153  llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
3154  unsigned Line = getLineNumber(RD->getLocation());
3155  StringRef RDName = getClassName(RD);
3156 
3157  llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
3158 
3159  // If we ended up creating the type during the context chain construction,
3160  // just return that.
3161  auto *T = cast_or_null<llvm::DICompositeType>(
3162  getTypeOrNull(CGM.getContext().getRecordType(RD)));
3163  if (T && (!T->isForwardDecl() || !RD->getDefinition()))
3164  return T;
3165 
3166  // If this is just a forward or incomplete declaration, construct an
3167  // appropriately marked node and just return it.
3168  const RecordDecl *D = RD->getDefinition();
3169  if (!D || !D->isCompleteDefinition())
3170  return getOrCreateRecordFwdDecl(Ty, RDContext);
3171 
3172  uint64_t Size = CGM.getContext().getTypeSize(Ty);
3173  auto Align = getDeclAlignIfRequired(D, CGM.getContext());
3174 
3175  SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
3176 
3177  // Explicitly record the calling convention and export symbols for C++
3178  // records.
3179  auto Flags = llvm::DINode::FlagZero;
3180  if (auto CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3181  if (CGM.getCXXABI().getRecordArgABI(CXXRD) == CGCXXABI::RAA_Indirect)
3182  Flags |= llvm::DINode::FlagTypePassByReference;
3183  else
3184  Flags |= llvm::DINode::FlagTypePassByValue;
3185 
3186  // Record if a C++ record is non-trivial type.
3187  if (!CXXRD->isTrivial())
3188  Flags |= llvm::DINode::FlagNonTrivial;
3189 
3190  // Record exports it symbols to the containing structure.
3191  if (CXXRD->isAnonymousStructOrUnion())
3192  Flags |= llvm::DINode::FlagExportSymbols;
3193  }
3194 
3195  llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
3196  getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align,
3197  Flags, Identifier);
3198 
3199  // Elements of composite types usually have back to the type, creating
3200  // uniquing cycles. Distinct nodes are more efficient.
3201  switch (RealDecl->getTag()) {
3202  default:
3203  llvm_unreachable("invalid composite type tag");
3204 
3205  case llvm::dwarf::DW_TAG_array_type:
3206  case llvm::dwarf::DW_TAG_enumeration_type:
3207  // Array elements and most enumeration elements don't have back references,
3208  // so they don't tend to be involved in uniquing cycles and there is some
3209  // chance of merging them when linking together two modules. Only make
3210  // them distinct if they are ODR-uniqued.
3211  if (Identifier.empty())
3212  break;
3213  LLVM_FALLTHROUGH;
3214 
3215  case llvm::dwarf::DW_TAG_structure_type:
3216  case llvm::dwarf::DW_TAG_union_type:
3217  case llvm::dwarf::DW_TAG_class_type:
3218  // Immediately resolve to a distinct node.
3219  RealDecl =
3220  llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl));
3221  break;
3222  }
3223 
3224  RegionMap[Ty->getDecl()].reset(RealDecl);
3225  TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
3226 
3227  if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
3228  DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
3229  CollectCXXTemplateParams(TSpecial, DefUnit));
3230  return RealDecl;
3231 }
3232 
3233 void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
3234  llvm::DICompositeType *RealDecl) {
3235  // A class's primary base or the class itself contains the vtable.
3236  llvm::DICompositeType *ContainingType = nullptr;
3237  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
3238  if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
3239  // Seek non-virtual primary base root.
3240  while (1) {
3241  const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
3242  const CXXRecordDecl *PBT = BRL.getPrimaryBase();
3243  if (PBT && !BRL.isPrimaryBaseVirtual())
3244  PBase = PBT;
3245  else
3246  break;
3247  }
3248  ContainingType = cast<llvm::DICompositeType>(
3249  getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
3250  getOrCreateFile(RD->getLocation())));
3251  } else if (RD->isDynamicClass())
3252  ContainingType = RealDecl;
3253 
3254  DBuilder.replaceVTableHolder(RealDecl, ContainingType);
3255 }
3256 
3257 llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
3258  StringRef Name, uint64_t *Offset) {
3259  llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
3260  uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
3261  auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
3262  llvm::DIType *Ty =
3263  DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign,
3264  *Offset, llvm::DINode::FlagZero, FieldTy);
3265  *Offset += FieldSize;
3266  return Ty;
3267 }
3268 
3269 void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
3270  StringRef &Name,
3271  StringRef &LinkageName,
3272  llvm::DIScope *&FDContext,
3273  llvm::DINodeArray &TParamsArray,
3274  llvm::DINode::DIFlags &Flags) {
3275  const auto *FD = cast<FunctionDecl>(GD.getDecl());
3276  Name = getFunctionName(FD);
3277  // Use mangled name as linkage name for C/C++ functions.
3278  if (FD->hasPrototype()) {
3279  LinkageName = CGM.getMangledName(GD);
3280  Flags |= llvm::DINode::FlagPrototyped;
3281  }
3282  // No need to replicate the linkage name if it isn't different from the
3283  // subprogram name, no need to have it at all unless coverage is enabled or
3284  // debug is set to more than just line tables or extra debug info is needed.
3285  if (LinkageName == Name || (!CGM.getCodeGenOpts().EmitGcovArcs &&
3286  !CGM.getCodeGenOpts().EmitGcovNotes &&
3287  !CGM.getCodeGenOpts().DebugInfoForProfiling &&
3289  LinkageName = StringRef();
3290 
3291  if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
3292  if (const NamespaceDecl *NSDecl =
3293  dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
3294  FDContext = getOrCreateNamespace(NSDecl);
3295  else if (const RecordDecl *RDecl =
3296  dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
3297  llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
3298  FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);
3299  }
3300  // Check if it is a noreturn-marked function
3301  if (FD->isNoReturn())
3302  Flags |= llvm::DINode::FlagNoReturn;
3303  // Collect template parameters.
3304  TParamsArray = CollectFunctionTemplateParams(FD, Unit);
3305  }
3306 }
3307 
3308 void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
3309  unsigned &LineNo, QualType &T,
3310  StringRef &Name, StringRef &LinkageName,
3311  llvm::MDTuple *&TemplateParameters,
3312  llvm::DIScope *&VDContext) {
3313  Unit = getOrCreateFile(VD->getLocation());
3314  LineNo = getLineNumber(VD->getLocation());
3315 
3316  setLocation(VD->getLocation());
3317 
3318  T = VD->getType();
3319  if (T->isIncompleteArrayType()) {
3320  // CodeGen turns int[] into int[1] so we'll do the same here.
3321  llvm::APInt ConstVal(32, 1);
3322  QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3323 
3324  T = CGM.getContext().getConstantArrayType(ET, ConstVal, nullptr,
3325  ArrayType::Normal, 0);
3326  }
3327 
3328  Name = VD->getName();
3329  if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
3330  !isa<ObjCMethodDecl>(VD->getDeclContext()))
3331  LinkageName = CGM.getMangledName(VD);
3332  if (LinkageName == Name)
3333  LinkageName = StringRef();
3334 
3335  if (isa<VarTemplateSpecializationDecl>(VD)) {
3336  llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VD, &*Unit);
3337  TemplateParameters = parameterNodes.get();
3338  } else {
3339  TemplateParameters = nullptr;
3340  }
3341 
3342  // Since we emit declarations (DW_AT_members) for static members, place the
3343  // definition of those static members in the namespace they were declared in
3344  // in the source code (the lexical decl context).
3345  // FIXME: Generalize this for even non-member global variables where the
3346  // declaration and definition may have different lexical decl contexts, once
3347  // we have support for emitting declarations of (non-member) global variables.
3348  const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
3349  : VD->getDeclContext();
3350  // When a record type contains an in-line initialization of a static data
3351  // member, and the record type is marked as __declspec(dllexport), an implicit
3352  // definition of the member will be created in the record context. DWARF
3353  // doesn't seem to have a nice way to describe this in a form that consumers
3354  // are likely to understand, so fake the "normal" situation of a definition
3355  // outside the class by putting it in the global scope.
3356  if (DC->isRecord())
3357  DC = CGM.getContext().getTranslationUnitDecl();
3358 
3359  llvm::DIScope *Mod = getParentModuleOrNull(VD);
3360  VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU);
3361 }
3362 
3363 llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD,
3364  bool Stub) {
3365  llvm::DINodeArray TParamsArray;
3366  StringRef Name, LinkageName;
3367  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3368  llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
3369  SourceLocation Loc = GD.getDecl()->getLocation();
3370  llvm::DIFile *Unit = getOrCreateFile(Loc);
3371  llvm::DIScope *DContext = Unit;
3372  unsigned Line = getLineNumber(Loc);
3373  collectFunctionDeclProps(GD, Unit, Name, LinkageName, DContext, TParamsArray,
3374  Flags);
3375  auto *FD = cast<FunctionDecl>(GD.getDecl());
3376 
3377  // Build function type.
3378  SmallVector<QualType, 16> ArgTypes;
3379  for (const ParmVarDecl *Parm : FD->parameters())
3380  ArgTypes.push_back(Parm->getType());
3381 
3382  CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
3383  QualType FnType = CGM.getContext().getFunctionType(
3384  FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
3385  if (!FD->isExternallyVisible())
3386  SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
3387  if (CGM.getLangOpts().Optimize)
3388  SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3389 
3390  if (Stub) {
3391  Flags |= getCallSiteRelatedAttrs();
3392  SPFlags |= llvm::DISubprogram::SPFlagDefinition;
3393  return DBuilder.createFunction(
3394  DContext, Name, LinkageName, Unit, Line,
3395  getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
3396  TParamsArray.get(), getFunctionDeclaration(FD));
3397  }
3398 
3399  llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
3400  DContext, Name, LinkageName, Unit, Line,
3401  getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
3402  TParamsArray.get(), getFunctionDeclaration(FD));
3403  const FunctionDecl *CanonDecl = FD->getCanonicalDecl();
3404  FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
3405  std::make_tuple(CanonDecl),
3406  std::make_tuple(SP));
3407  return SP;
3408 }
3409 
3410 llvm::DISubprogram *CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) {
3411  return getFunctionFwdDeclOrStub(GD, /* Stub = */ false);
3412 }
3413 
3414 llvm::DISubprogram *CGDebugInfo::getFunctionStub(GlobalDecl GD) {
3415  return getFunctionFwdDeclOrStub(GD, /* Stub = */ true);
3416 }
3417 
3418 llvm::DIGlobalVariable *
3419 CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
3420  QualType T;
3421  StringRef Name, LinkageName;
3422  SourceLocation Loc = VD->getLocation();
3423  llvm::DIFile *Unit = getOrCreateFile(Loc);
3424  llvm::DIScope *DContext = Unit;
3425  unsigned Line = getLineNumber(Loc);
3426  llvm::MDTuple *TemplateParameters = nullptr;
3427 
3428  collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, TemplateParameters,
3429  DContext);
3430  auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
3431  auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
3432  DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
3433  !VD->isExternallyVisible(), nullptr, TemplateParameters, Align);
3434  FwdDeclReplaceMap.emplace_back(
3435  std::piecewise_construct,
3436  std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
3437  std::make_tuple(static_cast<llvm::Metadata *>(GV)));
3438  return GV;
3439 }
3440 
3441 llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
3442  // We only need a declaration (not a definition) of the type - so use whatever
3443  // we would otherwise do to get a type for a pointee. (forward declarations in
3444  // limited debug info, full definitions (if the type definition is available)
3445  // in unlimited debug info)
3446  if (const auto *TD = dyn_cast<TypeDecl>(D))
3447  return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
3448  getOrCreateFile(TD->getLocation()));
3449  auto I = DeclCache.find(D->getCanonicalDecl());
3450 
3451  if (I != DeclCache.end()) {
3452  auto N = I->second;
3453  if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N))
3454  return GVE->getVariable();
3455  return dyn_cast_or_null<llvm::DINode>(N);
3456  }
3457 
3458  // No definition for now. Emit a forward definition that might be
3459  // merged with a potential upcoming definition.
3460  if (const auto *FD = dyn_cast<FunctionDecl>(D))
3461  return getFunctionForwardDeclaration(FD);
3462  else if (const auto *VD = dyn_cast<VarDecl>(D))
3463  return getGlobalVariableForwardDeclaration(VD);
3464 
3465  return nullptr;
3466 }
3467 
3468 llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
3469  if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3470  return nullptr;
3471 
3472  const auto *FD = dyn_cast<FunctionDecl>(D);
3473  if (!FD)
3474  return nullptr;
3475 
3476  // Setup context.
3477  auto *S = getDeclContextDescriptor(D);
3478 
3479  auto MI = SPCache.find(FD->getCanonicalDecl());
3480  if (MI == SPCache.end()) {
3481  if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
3482  return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
3483  cast<llvm::DICompositeType>(S));
3484  }
3485  }
3486  if (MI != SPCache.end()) {
3487  auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
3488  if (SP && !SP->isDefinition())
3489  return SP;
3490  }
3491 
3492  for (auto NextFD : FD->redecls()) {
3493  auto MI = SPCache.find(NextFD->getCanonicalDecl());
3494  if (MI != SPCache.end()) {
3495  auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
3496  if (SP && !SP->isDefinition())
3497  return SP;
3498  }
3499  }
3500  return nullptr;
3501 }
3502 
3503 llvm::DISubprogram *CGDebugInfo::getObjCMethodDeclaration(
3504  const Decl *D, llvm::DISubroutineType *FnType, unsigned LineNo,
3505  llvm::DINode::DIFlags Flags, llvm::DISubprogram::DISPFlags SPFlags) {
3506  if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3507  return nullptr;
3508 
3509  const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
3510  if (!OMD)
3511  return nullptr;
3512 
3513  if (CGM.getCodeGenOpts().DwarfVersion < 5 && !OMD->isDirectMethod())
3514  return nullptr;
3515 
3516  if (OMD->isDirectMethod())
3517  SPFlags |= llvm::DISubprogram::SPFlagObjCDirect;
3518 
3519  // Starting with DWARF V5 method declarations are emitted as children of
3520  // the interface type.
3521  auto *ID = dyn_cast_or_null<ObjCInterfaceDecl>(D->getDeclContext());
3522  if (!ID)
3523  ID = OMD->getClassInterface();
3524  if (!ID)
3525  return nullptr;
3526  QualType QTy(ID->getTypeForDecl(), 0);
3527  auto It = TypeCache.find(QTy.getAsOpaquePtr());
3528  if (It == TypeCache.end())
3529  return nullptr;
3530  auto *InterfaceType = cast<llvm::DICompositeType>(It->second);
3531  llvm::DISubprogram *FD = DBuilder.createFunction(
3532  InterfaceType, getObjCMethodName(OMD), StringRef(),
3533  InterfaceType->getFile(), LineNo, FnType, LineNo, Flags, SPFlags);
3534  DBuilder.finalizeSubprogram(FD);
3535  ObjCMethodCache[ID].push_back({FD, OMD->isDirectMethod()});
3536  return FD;
3537 }
3538 
3539 // getOrCreateFunctionType - Construct type. If it is a c++ method, include
3540 // implicit parameter "this".
3541 llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
3542  QualType FnType,
3543  llvm::DIFile *F) {
3544  if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3545  // Create fake but valid subroutine type. Otherwise -verify would fail, and
3546  // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
3547  return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray(None));
3548 
3549  if (const auto *Method = dyn_cast<CXXMethodDecl>(D))
3550  return getOrCreateMethodType(Method, F);
3551 
3552  const auto *FTy = FnType->getAs<FunctionType>();
3553  CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C;
3554 
3555  if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
3556  // Add "self" and "_cmd"
3558 
3559  // First element is always return type. For 'void' functions it is NULL.
3560  QualType ResultTy = OMethod->getReturnType();
3561 
3562  // Replace the instancetype keyword with the actual type.
3563  if (ResultTy == CGM.getContext().getObjCInstanceType())
3564  ResultTy = CGM.getContext().getPointerType(
3565  QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
3566 
3567  Elts.push_back(getOrCreateType(ResultTy, F));
3568  // "self" pointer is always first argument.
3569  QualType SelfDeclTy;
3570  if (auto *SelfDecl = OMethod->getSelfDecl())
3571  SelfDeclTy = SelfDecl->getType();
3572  else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3573  if (FPT->getNumParams() > 1)
3574  SelfDeclTy = FPT->getParamType(0);
3575  if (!SelfDeclTy.isNull())
3576  Elts.push_back(
3577  CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
3578  // "_cmd" pointer is always second argument.
3579  Elts.push_back(DBuilder.createArtificialType(
3580  getOrCreateType(CGM.getContext().getObjCSelType(), F)));
3581  // Get rest of the arguments.
3582  for (const auto *PI : OMethod->parameters())
3583  Elts.push_back(getOrCreateType(PI->getType(), F));
3584  // Variadic methods need a special marker at the end of the type list.
3585  if (OMethod->isVariadic())
3586  Elts.push_back(DBuilder.createUnspecifiedParameter());
3587 
3588  llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
3589  return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3590  getDwarfCC(CC));
3591  }
3592 
3593  // Handle variadic function types; they need an additional
3594  // unspecified parameter.
3595  if (const auto *FD = dyn_cast<FunctionDecl>(D))
3596  if (FD->isVariadic()) {
3598  EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
3599  if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3600  for (QualType ParamType : FPT->param_types())
3601  EltTys.push_back(getOrCreateType(ParamType, F));
3602  EltTys.push_back(DBuilder.createUnspecifiedParameter());
3603  llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
3604  return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3605  getDwarfCC(CC));
3606  }
3607 
3608  return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
3609 }
3610 
3612  SourceLocation ScopeLoc, QualType FnType,
3613  llvm::Function *Fn, bool CurFuncIsThunk,
3614  CGBuilderTy &Builder) {
3615 
3616  StringRef Name;
3617  StringRef LinkageName;
3618 
3619  FnBeginRegionCount.push_back(LexicalBlockStack.size());
3620 
3621  const Decl *D = GD.getDecl();
3622  bool HasDecl = (D != nullptr);
3623 
3624  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3625  llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
3626  llvm::DIFile *Unit = getOrCreateFile(Loc);
3627  llvm::DIScope *FDContext = Unit;
3628  llvm::DINodeArray TParamsArray;
3629  if (!HasDecl) {
3630  // Use llvm function name.
3631  LinkageName = Fn->getName();
3632  } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3633  // If there is a subprogram for this function available then use it.
3634  auto FI = SPCache.find(FD->getCanonicalDecl());
3635  if (FI != SPCache.end()) {
3636  auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
3637  if (SP && SP->isDefinition()) {
3638  LexicalBlockStack.emplace_back(SP);
3639  RegionMap[D].reset(SP);
3640  return;
3641  }
3642  }
3643  collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3644  TParamsArray, Flags);
3645  } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
3646  Name = getObjCMethodName(OMD);
3647  Flags |= llvm::DINode::FlagPrototyped;
3648  } else if (isa<VarDecl>(D) &&
3650  // This is a global initializer or atexit destructor for a global variable.
3651  Name = getDynamicInitializerName(cast<VarDecl>(D), GD.getDynamicInitKind(),
3652  Fn);
3653  } else {
3654  // Use llvm function name.
3655  Name = Fn->getName();
3656  Flags |= llvm::DINode::FlagPrototyped;
3657  }
3658  if (Name.startswith("\01"))
3659  Name = Name.substr(1);
3660 
3661  if (!HasDecl || D->isImplicit() || D->hasAttr<ArtificialAttr>()) {
3662  Flags |= llvm::DINode::FlagArtificial;
3663  // Artificial functions should not silently reuse CurLoc.
3664  CurLoc = SourceLocation();
3665  }
3666 
3667  if (CurFuncIsThunk)
3668  Flags |= llvm::DINode::FlagThunk;
3669 
3670  if (Fn->hasLocalLinkage())
3671  SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
3672  if (CGM.getLangOpts().Optimize)
3673  SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3674 
3675  llvm::DINode::DIFlags FlagsForDef = Flags | getCallSiteRelatedAttrs();
3676  llvm::DISubprogram::DISPFlags SPFlagsForDef =
3677  SPFlags | llvm::DISubprogram::SPFlagDefinition;
3678 
3679  unsigned LineNo = getLineNumber(Loc);
3680  unsigned ScopeLine = getLineNumber(ScopeLoc);
3681  llvm::DISubroutineType *DIFnType = getOrCreateFunctionType(D, FnType, Unit);
3682  llvm::DISubprogram *Decl = nullptr;
3683  if (D)
3684  Decl = isa<ObjCMethodDecl>(D)
3685  ? getObjCMethodDeclaration(D, DIFnType, LineNo, Flags, SPFlags)
3686  : getFunctionDeclaration(D);
3687 
3688  // FIXME: The function declaration we're constructing here is mostly reusing
3689  // declarations from CXXMethodDecl and not constructing new ones for arbitrary
3690  // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
3691  // all subprograms instead of the actual context since subprogram definitions
3692  // are emitted as CU level entities by the backend.
3693  llvm::DISubprogram *SP = DBuilder.createFunction(
3694  FDContext, Name, LinkageName, Unit, LineNo, DIFnType, ScopeLine,
3695  FlagsForDef, SPFlagsForDef, TParamsArray.get(), Decl);
3696  Fn->setSubprogram(SP);
3697  // We might get here with a VarDecl in the case we're generating
3698  // code for the initialization of globals. Do not record these decls
3699  // as they will overwrite the actual VarDecl Decl in the cache.
3700  if (HasDecl && isa<FunctionDecl>(D))
3701  DeclCache[D->getCanonicalDecl()].reset(SP);
3702 
3703  // Push the function onto the lexical block stack.
3704  LexicalBlockStack.emplace_back(SP);
3705 
3706  if (HasDecl)
3707  RegionMap[D].reset(SP);
3708 }
3709 
3711  QualType FnType, llvm::Function *Fn) {
3712  StringRef Name;
3713  StringRef LinkageName;
3714 
3715  const Decl *D = GD.getDecl();
3716  if (!D)
3717  return;
3718 
3719  llvm::TimeTraceScope TimeScope("DebugFunction", [&]() {
3720  std::string Name;
3721  llvm::raw_string_ostream OS(Name);
3722  if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
3723  ND->getNameForDiagnostic(OS, getPrintingPolicy(),
3724  /*Qualified=*/true);
3725  return Name;
3726  });
3727 
3728  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3729  llvm::DIFile *Unit = getOrCreateFile(Loc);
3730  bool IsDeclForCallSite = Fn ? true : false;
3731  llvm::DIScope *FDContext =
3732  IsDeclForCallSite ? Unit : getDeclContextDescriptor(D);
3733  llvm::DINodeArray TParamsArray;
3734  if (isa<FunctionDecl>(D)) {
3735  // If there is a DISubprogram for this function available then use it.
3736  collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3737  TParamsArray, Flags);
3738  } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
3739  Name = getObjCMethodName(OMD);
3740  Flags |= llvm::DINode::FlagPrototyped;
3741  } else {
3742  llvm_unreachable("not a function or ObjC method");
3743  }
3744  if (!Name.empty() && Name[0] == '\01')
3745  Name = Name.substr(1);
3746 
3747  if (D->isImplicit()) {
3748  Flags |= llvm::DINode::FlagArtificial;
3749  // Artificial functions without a location should not silently reuse CurLoc.
3750  if (Loc.isInvalid())
3751  CurLoc = SourceLocation();
3752  }
3753  unsigned LineNo = getLineNumber(Loc);
3754  unsigned ScopeLine = 0;
3755  llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
3756  if (CGM.getLangOpts().Optimize)
3757  SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3758 
3759  llvm::DISubprogram *SP = DBuilder.createFunction(
3760  FDContext, Name, LinkageName, Unit, LineNo,
3761  getOrCreateFunctionType(D, FnType, Unit), ScopeLine, Flags, SPFlags,
3762  TParamsArray.get(), getFunctionDeclaration(D));
3763 
3764  if (IsDeclForCallSite)
3765  Fn->setSubprogram(SP);
3766 
3767  DBuilder.retainType(SP);
3768 }
3769 
3770 void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,
3771  QualType CalleeType,
3772  const FunctionDecl *CalleeDecl) {
3773  if (!CallOrInvoke)
3774  return;
3775  auto *Func = CallOrInvoke->getCalledFunction();
3776  if (!Func)
3777  return;
3778  if (Func->getSubprogram())
3779  return;
3780 
3781  // Do not emit a declaration subprogram for a builtin or if call site info
3782  // isn't required. Also, elide declarations for functions with reserved names,
3783  // as call site-related features aren't interesting in this case (& also, the
3784  // compiler may emit calls to these functions without debug locations, which
3785  // makes the verifier complain).
3786  if (CalleeDecl->getBuiltinID() != 0 ||
3787  getCallSiteRelatedAttrs() == llvm::DINode::FlagZero)
3788  return;
3789  if (const auto *Id = CalleeDecl->getIdentifier())
3790  if (Id->isReservedName())
3791  return;
3792 
3793  // If there is no DISubprogram attached to the function being called,
3794  // create the one describing the function in order to have complete
3795  // call site debug info.
3796  if (!CalleeDecl->isStatic() && !CalleeDecl->isInlined())
3797  EmitFunctionDecl(CalleeDecl, CalleeDecl->getLocation(), CalleeType, Func);
3798 }
3799 
3801  const auto *FD = cast<FunctionDecl>(GD.getDecl());
3802  // If there is a subprogram for this function available then use it.
3803  auto FI = SPCache.find(FD->getCanonicalDecl());
3804  llvm::DISubprogram *SP = nullptr;
3805  if (FI != SPCache.end())
3806  SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
3807  if (!SP || !SP->isDefinition())
3808  SP = getFunctionStub(GD);
3809  FnBeginRegionCount.push_back(LexicalBlockStack.size());
3810  LexicalBlockStack.emplace_back(SP);
3811  setInlinedAt(Builder.getCurrentDebugLocation());
3812  EmitLocation(Builder, FD->getLocation());
3813 }
3814 
3816  assert(CurInlinedAt && "unbalanced inline scope stack");
3817  EmitFunctionEnd(Builder, nullptr);
3818  setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt());
3819 }
3820 
3822  // Update our current location
3823  setLocation(Loc);
3824 
3825  if (CurLoc.isInvalid() || CurLoc.isMacroID() || LexicalBlockStack.empty())
3826  return;
3827 
3828  llvm::MDNode *Scope = LexicalBlockStack.back();
3829  Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
3830  getLineNumber(CurLoc), getColumnNumber(CurLoc), Scope, CurInlinedAt));
3831 }
3832 
3833 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
3834  llvm::MDNode *Back = nullptr;
3835  if (!LexicalBlockStack.empty())
3836  Back = LexicalBlockStack.back().get();
3837  LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
3838  cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
3839  getColumnNumber(CurLoc)));
3840 }
3841 
3842 void CGDebugInfo::AppendAddressSpaceXDeref(
3843  unsigned AddressSpace, SmallVectorImpl<int64_t> &Expr) const {
3844  Optional<unsigned> DWARFAddressSpace =
3845  CGM.getTarget().getDWARFAddressSpace(AddressSpace);
3846  if (!DWARFAddressSpace)
3847  return;
3848 
3849  Expr.push_back(llvm::dwarf::DW_OP_constu);
3850  Expr.push_back(DWARFAddressSpace.getValue());
3851  Expr.push_back(llvm::dwarf::DW_OP_swap);
3852  Expr.push_back(llvm::dwarf::DW_OP_xderef);
3853 }
3854 
3856  SourceLocation Loc) {
3857  // Set our current location.
3858  setLocation(Loc);
3859 
3860  // Emit a line table change for the current location inside the new scope.
3861  Builder.SetCurrentDebugLocation(
3862  llvm::DebugLoc::get(getLineNumber(Loc), getColumnNumber(Loc),
3863  LexicalBlockStack.back(), CurInlinedAt));
3864 
3865  if (DebugKind <= codegenoptions::DebugLineTablesOnly)
3866  return;
3867 
3868  // Create a new lexical block and push it on the stack.
3869  CreateLexicalBlock(Loc);
3870 }
3871 
3873  SourceLocation Loc) {
3874  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3875 
3876  // Provide an entry in the line table for the end of the block.
3877  EmitLocation(Builder, Loc);
3878 
3879  if (DebugKind <= codegenoptions::DebugLineTablesOnly)
3880  return;
3881 
3882  LexicalBlockStack.pop_back();
3883 }
3884 
3885 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) {
3886  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3887  unsigned RCount = FnBeginRegionCount.back();
3888  assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
3889 
3890  // Pop all regions for this function.
3891  while (LexicalBlockStack.size() != RCount) {
3892  // Provide an entry in the line table for the end of the block.
3893  EmitLocation(Builder, CurLoc);
3894  LexicalBlockStack.pop_back();
3895  }
3896  FnBeginRegionCount.pop_back();
3897 
3898  if (Fn && Fn->getSubprogram())
3899  DBuilder.finalizeSubprogram(Fn->getSubprogram());
3900 }
3901 
3902 CGDebugInfo::BlockByRefType
3903 CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
3904  uint64_t *XOffset) {
3906  QualType FType;
3907  uint64_t FieldSize, FieldOffset;
3908  uint32_t FieldAlign;
3909 
3910  llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
3911  QualType Type = VD->getType();
3912 
3913  FieldOffset = 0;
3914  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
3915  EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
3916  EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
3917  FType = CGM.getContext().IntTy;
3918  EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
3919  EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
3920 
3921  bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
3922  if (HasCopyAndDispose) {
3923  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
3924  EltTys.push_back(
3925  CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
3926  EltTys.push_back(
3927  CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
3928  }
3929  bool HasByrefExtendedLayout;
3930  Qualifiers::ObjCLifetime Lifetime;
3931  if (CGM.getContext().getByrefLifetime(Type, Lifetime,
3932  HasByrefExtendedLayout) &&
3933  HasByrefExtendedLayout) {
3934  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
3935  EltTys.push_back(
3936  CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
3937  }
3938 
3939  CharUnits Align = CGM.getContext().getDeclAlign(VD);
3940  if (Align > CGM.getContext().toCharUnitsFromBits(
3941  CGM.getTarget().getPointerAlign(0))) {
3942  CharUnits FieldOffsetInBytes =
3943  CGM.getContext().toCharUnitsFromBits(FieldOffset);
3944  CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);
3945  CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
3946 
3947  if (NumPaddingBytes.isPositive()) {
3948  llvm::APInt pad(32, NumPaddingBytes.getQuantity());
3949  FType = CGM.getContext().getConstantArrayType(
3950  CGM.getContext().CharTy, pad, nullptr, ArrayType::Normal, 0);
3951  EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
3952  }
3953  }
3954 
3955  FType = Type;
3956  llvm::DIType *WrappedTy = getOrCreateType(FType, Unit);
3957  FieldSize = CGM.getContext().getTypeSize(FType);
3958  FieldAlign = CGM.getContext().toBits(Align);
3959 
3960  *XOffset = FieldOffset;
3961  llvm::DIType *FieldTy = DBuilder.createMemberType(
3962  Unit, VD->getName(), Unit, 0, FieldSize, FieldAlign, FieldOffset,
3963  llvm::DINode::FlagZero, WrappedTy);
3964  EltTys.push_back(FieldTy);
3965  FieldOffset += FieldSize;
3966 
3967  llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
3968  return {DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0,
3969  llvm::DINode::FlagZero, nullptr, Elements),
3970  WrappedTy};
3971 }
3972 
3973 llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD,
3974  llvm::Value *Storage,
3976  CGBuilderTy &Builder,
3977  const bool UsePointerValue) {
3978  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
3979  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3980  if (VD->hasAttr<NoDebugAttr>())
3981  return nullptr;
3982 
3983  bool Unwritten =
3984  VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
3985  cast<Decl>(VD->getDeclContext())->isImplicit());
3986  llvm::DIFile *Unit = nullptr;
3987  if (!Unwritten)
3988  Unit = getOrCreateFile(VD->getLocation());
3989  llvm::DIType *Ty;
3990  uint64_t XOffset = 0;
3991  if (VD->hasAttr<BlocksAttr>())
3992  Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
3993  else
3994  Ty = getOrCreateType(VD->getType(), Unit);
3995 
3996  // If there is no debug info for this type then do not emit debug info
3997  // for this variable.
3998  if (!Ty)
3999  return nullptr;
4000 
4001  // Get location information.
4002  unsigned Line = 0;
4003  unsigned Column = 0;
4004  if (!Unwritten) {
4005  Line = getLineNumber(VD->getLocation());
4006  Column = getColumnNumber(VD->getLocation());
4007  }
4009  llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4010  if (VD->isImplicit())
4011  Flags |= llvm::DINode::FlagArtificial;
4012 
4013  auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4014 
4015  unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(VD->getType());
4016  AppendAddressSpaceXDeref(AddressSpace, Expr);
4017 
4018  // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an
4019  // object pointer flag.
4020  if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) {
4021  if (IPD->getParameterKind() == ImplicitParamDecl::CXXThis ||
4022  IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
4023  Flags |= llvm::DINode::FlagObjectPointer;
4024  }
4025 
4026  // Note: Older versions of clang used to emit byval references with an extra
4027  // DW_OP_deref, because they referenced the IR arg directly instead of
4028  // referencing an alloca. Newer versions of LLVM don't treat allocas
4029  // differently from other function arguments when used in a dbg.declare.
4030  auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4031  StringRef Name = VD->getName();
4032  if (!Name.empty()) {
4033  if (VD->hasAttr<BlocksAttr>()) {
4034  // Here, we need an offset *into* the alloca.
4035  CharUnits offset = CharUnits::fromQuantity(32);
4036  Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4037  // offset of __forwarding field
4038  offset = CGM.getContext().toCharUnitsFromBits(
4039  CGM.getTarget().getPointerWidth(0));
4040  Expr.push_back(offset.getQuantity());
4041  Expr.push_back(llvm::dwarf::DW_OP_deref);
4042  Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4043  // offset of x field
4044  offset = CGM.getContext().toCharUnitsFromBits(XOffset);
4045  Expr.push_back(offset.getQuantity());
4046  }
4047  } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) {
4048  // If VD is an anonymous union then Storage represents value for
4049  // all union fields.
4050  const RecordDecl *RD = RT->getDecl();
4051  if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
4052  // GDB has trouble finding local variables in anonymous unions, so we emit
4053  // artificial local variables for each of the members.
4054  //
4055  // FIXME: Remove this code as soon as GDB supports this.
4056  // The debug info verifier in LLVM operates based on the assumption that a
4057  // variable has the same size as its storage and we had to disable the
4058  // check for artificial variables.
4059  for (const auto *Field : RD->fields()) {
4060  llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
4061  StringRef FieldName = Field->getName();
4062 
4063  // Ignore unnamed fields. Do not ignore unnamed records.
4064  if (FieldName.empty() && !isa<RecordType>(Field->getType()))
4065  continue;
4066 
4067  // Use VarDecl's Tag, Scope and Line number.
4068  auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext());
4069  auto *D = DBuilder.createAutoVariable(
4070  Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,
4071  Flags | llvm::DINode::FlagArtificial, FieldAlign);
4072 
4073  // Insert an llvm.dbg.declare into the current block.
4074  DBuilder.insertDeclare(
4075  Storage, D, DBuilder.createExpression(Expr),
4076  llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
4077  Builder.GetInsertBlock());
4078  }
4079  }
4080  }
4081 
4082  // Clang stores the sret pointer provided by the caller in a static alloca.
4083  // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
4084  // the address of the variable.
4085  if (UsePointerValue) {
4086  assert(std::find(Expr.begin(), Expr.end(), llvm::dwarf::DW_OP_deref) ==
4087  Expr.end() &&
4088  "Debug info already contains DW_OP_deref.");
4089  Expr.push_back(llvm::dwarf::DW_OP_deref);
4090  }
4091 
4092  // Create the descriptor for the variable.
4093  auto *D = ArgNo ? DBuilder.createParameterVariable(
4094  Scope, Name, *ArgNo, Unit, Line, Ty,
4095  CGM.getLangOpts().Optimize, Flags)
4096  : DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,
4097  CGM.getLangOpts().Optimize,
4098  Flags, Align);
4099 
4100  // Insert an llvm.dbg.declare into the current block.
4101  DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
4102  llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
4103  Builder.GetInsertBlock());
4104 
4105  return D;
4106 }
4107 
4108 llvm::DILocalVariable *
4110  CGBuilderTy &Builder,
4111  const bool UsePointerValue) {
4112  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4113  return EmitDeclare(VD, Storage, llvm::None, Builder, UsePointerValue);
4114 }
4115 
4117  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4118  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4119 
4120  if (D->hasAttr<NoDebugAttr>())
4121  return;
4122 
4123  auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4124  llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
4125 
4126  // Get location information.
4127  unsigned Line = getLineNumber(D->getLocation());
4128  unsigned Column = getColumnNumber(D->getLocation());
4129 
4130  StringRef Name = D->getName();
4131 
4132  // Create the descriptor for the label.
4133  auto *L =
4134  DBuilder.createLabel(Scope, Name, Unit, Line, CGM.getLangOpts().Optimize);
4135 
4136  // Insert an llvm.dbg.label into the current block.
4137  DBuilder.insertLabel(L,
4138  llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
4139  Builder.GetInsertBlock());
4140 }
4141 
4142 llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
4143  llvm::DIType *Ty) {
4144  llvm::DIType *CachedTy = getTypeOrNull(QualTy);
4145  if (CachedTy)
4146  Ty = CachedTy;
4147  return DBuilder.createObjectPointerType(Ty);
4148 }
4149 
4151  const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
4152  const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
4153  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4154  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4155 
4156  if (Builder.GetInsertBlock() == nullptr)
4157  return;
4158  if (VD->hasAttr<NoDebugAttr>())
4159  return;
4160 
4161  bool isByRef = VD->hasAttr<BlocksAttr>();
4162 
4163  uint64_t XOffset = 0;
4164  llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4165  llvm::DIType *Ty;
4166  if (isByRef)
4167  Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
4168  else
4169  Ty = getOrCreateType(VD->getType(), Unit);
4170 
4171  // Self is passed along as an implicit non-arg variable in a
4172  // block. Mark it as the object pointer.
4173  if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD))
4174  if (IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
4175  Ty = CreateSelfType(VD->getType(), Ty);
4176 
4177  // Get location information.
4178  unsigned Line = getLineNumber(VD->getLocation());
4179  unsigned Column = getColumnNumber(VD->getLocation());
4180 
4181  const llvm::DataLayout &target = CGM.getDataLayout();
4182 
4184  target.getStructLayout(blockInfo.StructureType)
4185  ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
4186 
4188  addr.push_back(llvm::dwarf::DW_OP_deref);
4189  addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4190  addr.push_back(offset.getQuantity());
4191  if (isByRef) {
4192  addr.push_back(llvm::dwarf::DW_OP_deref);
4193  addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4194  // offset of __forwarding field
4195  offset =
4196  CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
4197  addr.push_back(offset.getQuantity());
4198  addr.push_back(llvm::dwarf::DW_OP_deref);
4199  addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4200  // offset of x field
4201  offset = CGM.getContext().toCharUnitsFromBits(XOffset);
4202  addr.push_back(offset.getQuantity());
4203  }
4204 
4205  // Create the descriptor for the variable.
4206  auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4207  auto *D = DBuilder.createAutoVariable(
4208  cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
4209  Line, Ty, false, llvm::DINode::FlagZero, Align);
4210 
4211  // Insert an llvm.dbg.declare into the current block.
4212  auto DL =
4213  llvm::DebugLoc::get(Line, Column, LexicalBlockStack.back(), CurInlinedAt);
4214  auto *Expr = DBuilder.createExpression(addr);
4215  if (InsertPoint)
4216  DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint);
4217  else
4218  DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock());
4219 }
4220 
4222  unsigned ArgNo,
4223  CGBuilderTy &Builder) {
4224  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4225  EmitDeclare(VD, AI, ArgNo, Builder);
4226 }
4227 
4228 namespace {
4229 struct BlockLayoutChunk {
4230  uint64_t OffsetInBits;
4231  const BlockDecl::Capture *Capture;
4232 };
4233 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
4234  return l.OffsetInBits < r.OffsetInBits;
4235 }
4236 } // namespace
4237 
4238 void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare(
4239  const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc,
4240  const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit,
4242  // Blocks in OpenCL have unique constraints which make the standard fields
4243  // redundant while requiring size and align fields for enqueue_kernel. See
4244  // initializeForBlockHeader in CGBlocks.cpp
4245  if (CGM.getLangOpts().OpenCL) {
4246  Fields.push_back(createFieldType("__size", Context.IntTy, Loc, AS_public,
4247  BlockLayout.getElementOffsetInBits(0),
4248  Unit, Unit));
4249  Fields.push_back(createFieldType("__align", Context.IntTy, Loc, AS_public,
4250  BlockLayout.getElementOffsetInBits(1),
4251  Unit, Unit));
4252  } else {
4253  Fields.push_back(createFieldType("__isa", Context.VoidPtrTy, Loc, AS_public,
4254  BlockLayout.getElementOffsetInBits(0),
4255  Unit, Unit));
4256  Fields.push_back(createFieldType("__flags", Context.IntTy, Loc, AS_public,
4257  BlockLayout.getElementOffsetInBits(1),
4258  Unit, Unit));
4259  Fields.push_back(
4260  createFieldType("__reserved", Context.IntTy, Loc, AS_public,
4261  BlockLayout.getElementOffsetInBits(2), Unit, Unit));
4262  auto *FnTy = Block.getBlockExpr()->getFunctionType();
4263  auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
4264  Fields.push_back(createFieldType("__FuncPtr", FnPtrType, Loc, AS_public,
4265  BlockLayout.getElementOffsetInBits(3),
4266  Unit, Unit));
4267  Fields.push_back(createFieldType(
4268  "__descriptor",
4269  Context.getPointerType(Block.NeedsCopyDispose
4270  ? Context.getBlockDescriptorExtendedType()
4271  : Context.getBlockDescriptorType()),
4272  Loc, AS_public, BlockLayout.getElementOffsetInBits(4), Unit, Unit));
4273  }
4274 }
4275 
4277  StringRef Name,
4278  unsigned ArgNo,
4279  llvm::AllocaInst *Alloca,
4280  CGBuilderTy &Builder) {
4281  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4282  ASTContext &C = CGM.getContext();
4283  const BlockDecl *blockDecl = block.getBlockDecl();
4284 
4285  // Collect some general information about the block's location.
4286  SourceLocation loc = blockDecl->getCaretLocation();
4287  llvm::DIFile *tunit = getOrCreateFile(loc);
4288  unsigned line = getLineNumber(loc);
4289  unsigned column = getColumnNumber(loc);
4290 
4291  // Build the debug-info type for the block literal.
4292  getDeclContextDescriptor(blockDecl);
4293 
4294  const llvm::StructLayout *blockLayout =
4295  CGM.getDataLayout().getStructLayout(block.StructureType);
4296 
4298  collectDefaultFieldsForBlockLiteralDeclare(block, C, loc, *blockLayout, tunit,
4299  fields);
4300 
4301  // We want to sort the captures by offset, not because DWARF
4302  // requires this, but because we're paranoid about debuggers.
4304 
4305  // 'this' capture.
4306  if (blockDecl->capturesCXXThis()) {
4307  BlockLayoutChunk chunk;
4308  chunk.OffsetInBits =
4309  blockLayout->getElementOffsetInBits(block.CXXThisIndex);
4310  chunk.Capture = nullptr;
4311  chunks.push_back(chunk);
4312  }
4313 
4314  // Variable captures.
4315  for (const auto &capture : blockDecl->captures()) {
4316  const VarDecl *variable = capture.getVariable();
4317  const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
4318 
4319  // Ignore constant captures.
4320  if (captureInfo.isConstant())
4321  continue;
4322 
4323  BlockLayoutChunk chunk;
4324  chunk.OffsetInBits =
4325  blockLayout->getElementOffsetInBits(captureInfo.getIndex());
4326  chunk.Capture = &capture;
4327  chunks.push_back(chunk);
4328  }
4329 
4330  // Sort by offset.
4331  llvm::array_pod_sort(chunks.begin(), chunks.end());
4332 
4333  for (const BlockLayoutChunk &Chunk : chunks) {
4334  uint64_t offsetInBits = Chunk.OffsetInBits;
4335  const BlockDecl::Capture *capture = Chunk.Capture;
4336 
4337  // If we have a null capture, this must be the C++ 'this' capture.
4338  if (!capture) {
4339  QualType type;
4340  if (auto *Method =
4341  cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext()))
4342  type = Method->getThisType();
4343  else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent()))
4344  type = QualType(RDecl->getTypeForDecl(), 0);
4345  else
4346  llvm_unreachable("unexpected block declcontext");
4347 
4348  fields.push_back(createFieldType("this", type, loc, AS_public,
4349  offsetInBits, tunit, tunit));
4350  continue;
4351  }
4352 
4353  const VarDecl *variable = capture->getVariable();
4354  StringRef name = variable->getName();
4355 
4356  llvm::DIType *fieldType;
4357  if (capture->isByRef()) {
4358  TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
4359  auto Align = PtrInfo.AlignIsRequired ? PtrInfo.Align : 0;
4360  // FIXME: This recomputes the layout of the BlockByRefWrapper.
4361  uint64_t xoffset;
4362  fieldType =
4363  EmitTypeForVarWithBlocksAttr(variable, &xoffset).BlockByRefWrapper;
4364  fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
4365  fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
4366  PtrInfo.Width, Align, offsetInBits,
4367  llvm::DINode::FlagZero, fieldType);
4368  } else {
4369  auto Align = getDeclAlignIfRequired(variable, CGM.getContext());
4370  fieldType = createFieldType(name, variable->getType(), loc, AS_public,
4371  offsetInBits, Align, tunit, tunit);
4372  }
4373  fields.push_back(fieldType);
4374  }
4375 
4376  SmallString<36> typeName;
4377  llvm::raw_svector_ostream(typeName)
4378  << "__block_literal_" << CGM.getUniqueBlockCount();
4379 
4380  llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
4381 
4382  llvm::DIType *type =
4383  DBuilder.createStructType(tunit, typeName.str(), tunit, line,
4384  CGM.getContext().toBits(block.BlockSize), 0,
4385  llvm::DINode::FlagZero, nullptr, fieldsArray);
4386  type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
4387 
4388  // Get overall information about the block.
4389  llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial;
4390  auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
4391 
4392  // Create the descriptor for the parameter.
4393  auto *debugVar = DBuilder.createParameterVariable(
4394  scope, Name, ArgNo, tunit, line, type, CGM.getLangOpts().Optimize, flags);
4395 
4396  // Insert an llvm.dbg.declare into the current block.
4397  DBuilder.insertDeclare(Alloca, debugVar, DBuilder.createExpression(),
4398  llvm::DebugLoc::get(line, column, scope, CurInlinedAt),
4399  Builder.GetInsertBlock());
4400 }
4401 
4402 llvm::DIDerivedType *
4403 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
4404  if (!D || !D->isStaticDataMember())
4405  return nullptr;
4406 
4407  auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
4408  if (MI != StaticDataMemberCache.end()) {
4409  assert(MI->second && "Static data member declaration should still exist");
4410  return MI->second;
4411  }
4412 
4413  // If the member wasn't found in the cache, lazily construct and add it to the
4414  // type (used when a limited form of the type is emitted).
4415  auto DC = D->getDeclContext();
4416  auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
4417  return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
4418 }
4419 
4420 llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls(
4421  const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
4422  StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
4423  llvm::DIGlobalVariableExpression *GVE = nullptr;
4424 
4425  for (const auto *Field : RD->fields()) {
4426  llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
4427  StringRef FieldName = Field->getName();
4428 
4429  // Ignore unnamed fields, but recurse into anonymous records.
4430  if (FieldName.empty()) {
4431  if (const auto *RT = dyn_cast<RecordType>(Field->getType()))
4432  GVE = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
4433  Var, DContext);
4434  continue;
4435  }
4436  // Use VarDecl's Tag, Scope and Line number.
4437  GVE = DBuilder.createGlobalVariableExpression(
4438  DContext, FieldName, LinkageName, Unit, LineNo, FieldTy,
4439  Var->hasLocalLinkage());
4440  Var->addDebugInfo(GVE);
4441  }
4442  return GVE;
4443 }
4444 
4445 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
4446  const VarDecl *D) {
4447  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4448  if (D->hasAttr<NoDebugAttr>())
4449  return;
4450 
4451  llvm::TimeTraceScope TimeScope("DebugGlobalVariable", [&]() {
4452  std::string Name;
4453  llvm::raw_string_ostream OS(Name);
4454  D->getNameForDiagnostic(OS, getPrintingPolicy(),
4455  /*Qualified=*/true);
4456  return Name;
4457  });
4458 
4459  // If we already created a DIGlobalVariable for this declaration, just attach
4460  // it to the llvm::GlobalVariable.
4461  auto Cached = DeclCache.find(D->getCanonicalDecl());
4462  if (Cached != DeclCache.end())
4463  return Var->addDebugInfo(
4464  cast<llvm::DIGlobalVariableExpression>(Cached->second));
4465 
4466  // Create global variable debug descriptor.
4467  llvm::DIFile *Unit = nullptr;
4468  llvm::DIScope *DContext = nullptr;
4469  unsigned LineNo;
4470  StringRef DeclName, LinkageName;
4471  QualType T;
4472  llvm::MDTuple *TemplateParameters = nullptr;
4473  collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName,
4474  TemplateParameters, DContext);
4475 
4476  // Attempt to store one global variable for the declaration - even if we
4477  // emit a lot of fields.
4478  llvm::DIGlobalVariableExpression *GVE = nullptr;
4479 
4480  // If this is an anonymous union then we'll want to emit a global
4481  // variable for each member of the anonymous union so that it's possible
4482  // to find the name of any field in the union.
4483  if (T->isUnionType() && DeclName.empty()) {
4484  const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
4485  assert(RD->isAnonymousStructOrUnion() &&
4486  "unnamed non-anonymous struct or union?");
4487  GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
4488  } else {
4489  auto Align = getDeclAlignIfRequired(D, CGM.getContext());
4490 
4492  unsigned AddressSpace =
4493  CGM.getContext().getTargetAddressSpace(D->getType());
4494  if (CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) {
4495  if (D->hasAttr<CUDASharedAttr>())
4496  AddressSpace =
4497  CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared);
4498  else if (D->hasAttr<CUDAConstantAttr>())
4499  AddressSpace =
4500  CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
4501  }
4502  AppendAddressSpaceXDeref(AddressSpace, Expr);
4503 
4504  GVE = DBuilder.createGlobalVariableExpression(
4505  DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
4506  Var->hasLocalLinkage(), true,
4507  Expr.empty() ? nullptr : DBuilder.createExpression(Expr),
4508  getOrCreateStaticDataMemberDeclarationOrNull(D), TemplateParameters,
4509  Align);
4510  Var->addDebugInfo(GVE);
4511  }
4512  DeclCache[D->getCanonicalDecl()].reset(GVE);
4513 }
4514 
4515 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) {
4516  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4517  if (VD->hasAttr<NoDebugAttr>())
4518  return;
4519  llvm::TimeTraceScope TimeScope("DebugConstGlobalVariable", [&]() {
4520  std::string Name;
4521  llvm::raw_string_ostream OS(Name);
4522  VD->getNameForDiagnostic(OS, getPrintingPolicy(),
4523  /*Qualified=*/true);
4524  return Name;
4525  });
4526 
4527  auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4528  // Create the descriptor for the variable.
4529  llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4530  StringRef Name = VD->getName();
4531  llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
4532 
4533  if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) {
4534  const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
4535  assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
4536 
4537  if (CGM.getCodeGenOpts().EmitCodeView) {
4538  // If CodeView, emit enums as global variables, unless they are defined
4539  // inside a class. We do this because MSVC doesn't emit S_CONSTANTs for
4540  // enums in classes, and because it is difficult to attach this scope
4541  // information to the global variable.
4542  if (isa<RecordDecl>(ED->getDeclContext()))
4543  return;
4544  } else {
4545  // If not CodeView, emit DW_TAG_enumeration_type if necessary. For
4546  // example: for "enum { ZERO };", a DW_TAG_enumeration_type is created the
4547  // first time `ZERO` is referenced in a function.
4548  llvm::DIType *EDTy =
4549  getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
4550  assert (EDTy->getTag() == llvm::dwarf::DW_TAG_enumeration_type);
4551  (void)EDTy;
4552  return;
4553  }
4554  }
4555 
4556  llvm::DIScope *DContext = nullptr;
4557 
4558  // Do not emit separate definitions for function local consts.
4559  if (isa<FunctionDecl>(VD->getDeclContext()))
4560  return;
4561 
4562  // Emit definition for static members in CodeView.
4563  VD = cast<ValueDecl>(VD->getCanonicalDecl());
4564  auto *VarD = dyn_cast<VarDecl>(VD);
4565  if (VarD && VarD->isStaticDataMember()) {
4566  auto *RD = cast<RecordDecl>(VarD->getDeclContext());
4567  getDeclContextDescriptor(VarD);
4568  // Ensure that the type is retained even though it's otherwise unreferenced.
4569  //
4570  // FIXME: This is probably unnecessary, since Ty should reference RD
4571  // through its scope.
4572  RetainedTypes.push_back(
4573  CGM.getContext().getRecordType(RD).getAsOpaquePtr());
4574 
4575  if (!CGM.getCodeGenOpts().EmitCodeView)
4576  return;
4577 
4578  // Use the global scope for static members.
4579  DContext = getContextDescriptor(
4580  cast<Decl>(CGM.getContext().getTranslationUnitDecl()), TheCU);
4581  } else {
4582  DContext = getDeclContextDescriptor(VD);
4583  }
4584 
4585  auto &GV = DeclCache[VD];
4586  if (GV)
4587  return;
4588  llvm::DIExpression *InitExpr = nullptr;
4589  if (CGM.getContext().getTypeSize(VD->getType()) <= 64) {
4590  // FIXME: Add a representation for integer constants wider than 64 bits.
4591  if (Init.isInt())
4592  InitExpr =
4593  DBuilder.createConstantValueExpression(Init.getInt().getExtValue());
4594  else if (Init.isFloat())
4595  InitExpr = DBuilder.createConstantValueExpression(
4596  Init.getFloat().bitcastToAPInt().getZExtValue());
4597  }
4598 
4599  llvm::MDTuple *TemplateParameters = nullptr;
4600 
4601  if (isa<VarTemplateSpecializationDecl>(VD))
4602  if (VarD) {
4603  llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VarD, &*Unit);
4604  TemplateParameters = parameterNodes.get();
4605  }
4606 
4607  GV.reset(DBuilder.createGlobalVariableExpression(
4608  DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
4609  true, true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD),
4610  TemplateParameters, Align));
4611 }
4612 
4613 void CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable *Var,
4614  const VarDecl *D) {
4615  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4616  if (D->hasAttr<NoDebugAttr>())
4617  return;
4618 
4619  auto Align = getDeclAlignIfRequired(D, CGM.getContext());
4620  llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
4621  StringRef Name = D->getName();
4622  llvm::DIType *Ty = getOrCreateType(D->getType(), Unit);
4623 
4624  llvm::DIScope *DContext = getDeclContextDescriptor(D);
4625  llvm::DIGlobalVariableExpression *GVE =
4626  DBuilder.createGlobalVariableExpression(
4627  DContext, Name, StringRef(), Unit, getLineNumber(D->getLocation()),
4628  Ty, false, false, nullptr, nullptr, nullptr, Align);
4629  Var->addDebugInfo(GVE);
4630 }
4631 
4632 llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
4633  if (!LexicalBlockStack.empty())
4634  return LexicalBlockStack.back();
4635  llvm::DIScope *Mod = getParentModuleOrNull(D);
4636  return getContextDescriptor(D, Mod ? Mod : TheCU);
4637 }
4638 
4640  if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
4641  return;
4642  const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
4643  if (!NSDecl->isAnonymousNamespace() ||
4644  CGM.getCodeGenOpts().DebugExplicitImport) {
4645  auto Loc = UD.getLocation();
4646  DBuilder.createImportedModule(
4647  getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
4648  getOrCreateNamespace(NSDecl), getOrCreateFile(Loc), getLineNumber(Loc));
4649  }
4650 }
4651 
4653  if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
4654  return;
4655  assert(UD.shadow_size() &&
4656  "We shouldn't be codegening an invalid UsingDecl containing no decls");
4657  // Emitting one decl is sufficient - debuggers can detect that this is an
4658  // overloaded name & provide lookup for all the overloads.
4659  const UsingShadowDecl &USD = **UD.shadow_begin();
4660 
4661  // FIXME: Skip functions with undeduced auto return type for now since we
4662  // don't currently have the plumbing for separate declarations & definitions
4663  // of free functions and mismatched types (auto in the declaration, concrete
4664  // return type in the definition)
4665  if (const auto *FD = dyn_cast<FunctionDecl>(USD.getUnderlyingDecl()))
4666  if (const auto *AT =
4667  FD->getType()->castAs<FunctionProtoType>()->getContainedAutoType())
4668  if (AT->getDeducedType().isNull())
4669  return;
4670  if (llvm::DINode *Target =
4671  getDeclarationOrDefinition(USD.getUnderlyingDecl())) {
4672  auto Loc = USD.getLocation();
4673  DBuilder.createImportedDeclaration(
4674  getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
4675  getOrCreateFile(Loc), getLineNumber(Loc));
4676  }
4677 }
4678 
4680  if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)
4681  return;
4682  if (Module *M = ID.getImportedModule()) {
4684  auto Loc = ID.getLocation();
4685  DBuilder.createImportedDeclaration(
4686  getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
4687  getOrCreateModuleRef(Info, DebugTypeExtRefs), getOrCreateFile(Loc),
4688  getLineNumber(Loc));
4689  }
4690 }
4691 
4692 llvm::DIImportedEntity *
4694  if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
4695  return nullptr;
4696  auto &VH = NamespaceAliasCache[&NA];
4697  if (VH)
4698  return cast<llvm::DIImportedEntity>(VH);
4699  llvm::DIImportedEntity *R;
4700  auto Loc = NA.getLocation();
4701  if (const auto *Underlying =
4702  dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
4703  // This could cache & dedup here rather than relying on metadata deduping.
4704  R = DBuilder.createImportedDeclaration(
4705  getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
4706  EmitNamespaceAlias(*Underlying), getOrCreateFile(Loc),
4707  getLineNumber(Loc), NA.getName());
4708  else
4709  R = DBuilder.createImportedDeclaration(
4710  getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
4711  getOrCreateNamespace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
4712  getOrCreateFile(Loc), getLineNumber(Loc), NA.getName());
4713  VH.reset(R);
4714  return R;
4715 }
4716 
4717 llvm::DINamespace *
4718 CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) {
4719  // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued
4720  // if necessary, and this way multiple declarations of the same namespace in
4721  // different parent modules stay distinct.
4722  auto I = NamespaceCache.find(NSDecl);
4723  if (I != NamespaceCache.end())
4724  return cast<llvm::DINamespace>(I->second);
4725 
4726  llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);
4727  // Don't trust the context if it is a DIModule (see comment above).
4728  llvm::DINamespace *NS =
4729  DBuilder.createNameSpace(Context, NSDecl->getName(), NSDecl->isInline());
4730  NamespaceCache[NSDecl].reset(NS);
4731  return NS;
4732 }
4733 
4734 void CGDebugInfo::setDwoId(uint64_t Signature) {
4735  assert(TheCU && "no main compile unit");
4736  TheCU->setDWOId(Signature);
4737 }
4738 
4740  // Creating types might create further types - invalidating the current
4741  // element and the size(), so don't cache/reference them.
4742  for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
4743  ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
4744  llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
4745  ? CreateTypeDefinition(E.Type, E.Unit)
4746  : E.Decl;
4747  DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
4748  }
4749 
4750  // Add methods to interface.
4751  for (const auto &P : ObjCMethodCache) {
4752  if (P.second.empty())
4753  continue;
4754 
4755  QualType QTy(P.first->getTypeForDecl(), 0);
4756  auto It = TypeCache.find(QTy.getAsOpaquePtr());
4757  assert(It != TypeCache.end());
4758 
4759  llvm::DICompositeType *InterfaceDecl =
4760  cast<llvm::DICompositeType>(It->second);
4761 
4762  auto CurElts = InterfaceDecl->getElements();
4763  SmallVector<llvm::Metadata *, 16> EltTys(CurElts.begin(), CurElts.end());
4764 
4765  // For DWARF v4 or earlier, only add objc_direct methods.
4766  for (auto &SubprogramDirect : P.second)
4767  if (CGM.getCodeGenOpts().DwarfVersion >= 5 || SubprogramDirect.getInt())
4768  EltTys.push_back(SubprogramDirect.getPointer());
4769 
4770  llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
4771  DBuilder.replaceArrays(InterfaceDecl, Elements);
4772  }
4773 
4774  for (const auto &P : ReplaceMap) {
4775  assert(P.second);
4776  auto *Ty = cast<llvm::DIType>(P.second);
4777  assert(Ty->isForwardDecl());
4778 
4779  auto It = TypeCache.find(P.first);
4780  assert(It != TypeCache.end());
4781  assert(It->second);
4782 
4783  DBuilder.replaceTemporary(llvm::TempDIType(Ty),
4784  cast<llvm::DIType>(It->second));
4785  }
4786 
4787  for (const auto &P : FwdDeclReplaceMap) {
4788  assert(P.second);
4789  llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(P.second));
4790  llvm::Metadata *Repl;
4791 
4792  auto It = DeclCache.find(P.first);
4793  // If there has been no definition for the declaration, call RAUW
4794  // with ourselves, that will destroy the temporary MDNode and
4795  // replace it with a standard one, avoiding leaking memory.
4796  if (It == DeclCache.end())
4797  Repl = P.second;
4798  else
4799  Repl = It->second;
4800 
4801  if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Repl))
4802  Repl = GVE->getVariable();
4803  DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
4804  }
4805 
4806  // We keep our own list of retained types, because we need to look
4807  // up the final type in the type cache.
4808  for (auto &RT : RetainedTypes)
4809  if (auto MD = TypeCache[RT])
4810  DBuilder.retainType(cast<llvm::DIType>(MD));
4811 
4812  DBuilder.finalize();
4813 }
4814 
4816  if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
4817  return;
4818 
4819  if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
4820  // Don't ignore in case of explicit cast where it is referenced indirectly.
4821  DBuilder.retainType(DieTy);
4822 }
4823 
4825  if (LexicalBlockStack.empty())
4826  return llvm::DebugLoc();
4827 
4828  llvm::MDNode *Scope = LexicalBlockStack.back();
4829  return llvm::DebugLoc::get(getLineNumber(Loc), getColumnNumber(Loc), Scope);
4830 }
4831 
4832 llvm::DINode::DIFlags CGDebugInfo::getCallSiteRelatedAttrs() const {
4833  // Call site-related attributes are only useful in optimized programs, and
4834  // when there's a possibility of debugging backtraces.
4835  if (!CGM.getLangOpts().Optimize || DebugKind == codegenoptions::NoDebugInfo ||
4836  DebugKind == codegenoptions::LocTrackingOnly)
4837  return llvm::DINode::FlagZero;
4838 
4839  // Call site-related attributes are available in DWARF v5. Some debuggers,
4840  // while not fully DWARF v5-compliant, may accept these attributes as if they
4841  // were part of DWARF v4.
4842  bool SupportsDWARFv4Ext =
4843  CGM.getCodeGenOpts().DwarfVersion == 4 &&
4844  (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB ||
4845  CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::GDB);
4846 
4847  if (!SupportsDWARFv4Ext && CGM.getCodeGenOpts().DwarfVersion < 5 &&
4848  !CGM.getCodeGenOpts().EnableDebugEntryValues)
4849  return llvm::DINode::FlagZero;
4850 
4851  return llvm::DINode::FlagAllCallsDescribed;
4852 }
bool isNoReturn() const
Determines whether this function is known to be &#39;noreturn&#39;, through an attribute on its declaration o...
Definition: Decl.cpp:3109
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
Defines the clang::ASTContext interface.
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:188
VarDecl * getCapturedVar() const
Retrieve the declaration of the local variable being captured.
bool isStruct() const
Definition: Decl.h:3404
const Capture & getCapture(const VarDecl *var) const
Definition: CGBlocks.h:270
Represents a function declaration or definition.
Definition: Decl.h:1783
FunctionTemplateDecl * getTemplate() const
Retrieve the template from which this function was specialized.
Definition: DeclTemplate.h:529
std::string Name
The name of this module.
Definition: Module.h:67
External linkage, which indicates that the entity can be referred to from other translation units...
Definition: Linkage.h:59
StringRef Identifier
Definition: Format.cpp:1833
static bool hasDefaultSetterName(const ObjCPropertyDecl *PD, const ObjCMethodDecl *Setter)
bool isObjCQualifiedIdType() const
True if this is equivalent to &#39;id.
Definition: Type.h:6030
const FunctionProtoType * getFunctionType() const
getFunctionType - Return the underlying function type for this block.
Definition: Expr.cpp:2375
Smart pointer class that efficiently represents Objective-C method names.
A class which contains all the information about a particular captured value.
Definition: Decl.h:4043
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:759
StringRef getName(const PrintingPolicy &Policy) const
Definition: Type.cpp:2761
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2614
QualType getElementType() const
Definition: Type.h:6173
CanQualType VoidPtrTy
Definition: ASTContext.h:1044
QualType getPointeeType() const
Definition: Type.h:2627
void EmitLocation(raw_ostream &o, const SourceManager &SM, SourceLocation L, const FIDMap &FM, unsigned indent)
Definition: PlistSupport.h:107
bool isPrimaryBaseVirtual() const
isPrimaryBaseVirtual - Get whether the primary base for this record is virtual or not...
Definition: RecordLayout.h:225
static uint32_t getTypeAlignIfRequired(const Type *Ty, const ASTContext &Ctx)
Definition: CGDebugInfo.cpp:53
A (possibly-)qualified type.
Definition: Type.h:654
base_class_range bases()
Definition: DeclCXX.h:587
const CodeGenOptions & getCodeGenOpts() const
ObjCInterfaceDecl * getClassInterface()
Definition: DeclObjC.cpp:1155
void EmitExplicitCastType(QualType Ty)
Emit the type explicitly casted to.
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
Definition: TemplateBase.h:365
Defines the clang::FileManager interface and associated types.
bool isMemberDataPointerType() const
Definition: Type.h:6563
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition: Type.h:954
std::string getClangFullVersion()
Retrieves a string representing the complete clang version, which includes the clang version number...
Definition: Version.cpp:117
void EmitLabel(const LabelDecl *D, CGBuilderTy &Builder)
Emit call to llvm.dbg.label for an label.
TypePropertyCache< Private > Cache
Definition: Type.cpp:3625
llvm::DIType * getOrCreateRecordType(QualType Ty, SourceLocation L)
Emit record type&#39;s standalone debug info.
FileID getFileID() const
Kind getKind() const
Definition: Type.h:2495
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3422
void EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc)
Emit metadata to indicate the end of a new lexical block and pop the current block.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:557
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:232
Defines the SourceManager interface.
QualType getThisType() const
Return the type of the this pointer.
Definition: DeclCXX.cpp:2352
static bool shouldOmitDefinition(codegenoptions::DebugInfoKind DebugKind, bool DebugTypeExtRefs, const RecordDecl *RD, const LangOptions &LangOpts)
The template argument is an expression, and we&#39;ve not resolved it to one of the other forms yet...
Definition: TemplateBase.h:86
bool isRecordType() const
Definition: Type.h:6594
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:1958
const Type * getTypeForDecl() const
Definition: Decl.h:3053
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:88
TagDecl * getDecl() const
Definition: Type.cpp:3296
bool isVirtual() const
Definition: DeclCXX.h:1976
ArrayRef< NamedDecl * > asArray()
Definition: DeclTemplate.h:131
Selector getObjCSelector() const
Get the Objective-C selector stored in this declaration name.
Defines the C++ template declaration subclasses.
StringRef P
Parameter for C++ &#39;this&#39; argument.
Definition: Decl.h:1546
static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C)
static bool hasDefaultGetterName(const ObjCPropertyDecl *PD, const ObjCMethodDecl *Getter)
The base class of the type hierarchy.
Definition: Type.h:1450
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2889
Declaration of a variable template.
The template argument is a declaration that was provided for a pointer, reference, or pointer to member non-type template parameter.
Definition: TemplateBase.h:63
Represent a C++ namespace.
Definition: Decl.h:497
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:138
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:113
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:6140
static bool needsTypeIdentifier(const TagDecl *TD, CodeGenModule &CGM, llvm::DICompileUnit *TheCU)
bool isStatic() const
Definition: Decl.h:2521
Describes the capture of a variable or of this, or of a C++1y init-capture.
Definition: LambdaCapture.h:25
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2383
float __ovld __cnfn distance(float p0, float p1)
Returns the distance between p0 and p1.
DynamicInitKind
Definition: GlobalDecl.h:30
QualType getElementType() const
Definition: Type.h:2910
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3324
StringRef getBufferData(FileID FID, bool *Invalid=nullptr) const
Return a StringRef to the source buffer data for the specified FileID.
enumerator_range enumerators() const
Definition: Decl.h:3608
bool isInterface() const
Definition: Decl.h:3405
Represents a variable declaration or definition.
Definition: Decl.h:820
void removeObjCLifetime()
Definition: Type.h:339
QualType getReturnType() const
Definition: Decl.h:2445
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:7002
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:56
Extra information about a function prototype.
Definition: Type.h:3837
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2033
void EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke, QualType CalleeType, const FunctionDecl *CalleeDecl)
Emit debug info for an extern function being called.
A this pointer adjustment.
Definition: ABI.h:107
Represents a variable template specialization, which refers to a variable template with a given set o...
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:138
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:69
Describes how types, statements, expressions, and declarations should be printed. ...
Definition: PrettyPrinter.h:47
bool isStatic() const
Definition: DeclCXX.cpp:1983
void completeTemplateDefinition(const ClassTemplateSpecializationDecl &SD)
bool hasDefinition() const
Definition: DeclCXX.h:540
Don&#39;t generate debug info.
static const NamedDecl * getDefinition(const Decl *D)
Definition: SemaDecl.cpp:2613
Represents a parameter to a function.
Definition: Decl.h:1595
QualType getIntegralType() const
Retrieve the type of the integral value.
Definition: TemplateBase.h:314
static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD)
The collection of all-type qualifiers we support.
Definition: Type.h:143
PipeType - OpenCL20.
Definition: Type.h:6159
bool isClass() const
Definition: Decl.h:3406
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:244
void EmitInlineFunctionEnd(CGBuilderTy &Builder)
End an inlined function scope.
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2281
Represents a struct/union/class.
Definition: Decl.h:3748
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the class template specialization.
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:272
Represents a class template specialization, which refers to a class template with a given set of temp...
One of these records is kept for each identifier that is lexed.
void EmitExternalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl)
Emit information about an external variable.
std::map< std::string, std::string > DebugPrefixMap
void print(raw_ostream &OS, const PrintingPolicy &Policy, bool SuppressNNS=false) const
Print the template name.
void addHeapAllocSiteMetadata(llvm::Instruction *CallSite, QualType Ty, SourceLocation Loc)
Add heapallocsite metadata for MSAllocator calls.
Represents a class type in Objective C.
Definition: Type.h:5694
void removeRestrict()
Definition: Type.h:272
QualType getPointeeType() const
Definition: Type.h:2731
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:329
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:168
bool isInline() const
Returns true if this is an inline namespace declaration.
Definition: Decl.h:558
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:71
static bool isFunctionLocalClass(const CXXRecordDecl *RD)
isFunctionLocalClass - Return true if CXXRecordDecl is defined inside a function. ...
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known...
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:3953
void EmitImportDecl(const ImportDecl &ID)
Emit an declaration.
field_range fields() const
Definition: Decl.h:3963
Represents a member of a struct/union/class.
Definition: Decl.h:2729
TemplateName getTemplateName() const
Retrieve the name of the template that we are specializing.
Definition: Type.h:5059
void removeConst()
Definition: Type.h:262
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2017
prop_range properties() const
Definition: DeclObjC.h:1002
void completeClassData(const RecordDecl *RD)
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
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...
method_iterator method_begin() const
Method begin iterator.
Definition: DeclCXX.h:635
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:53
bool isFloat() const
Definition: APValue.h:362
Describes a module or submodule.
Definition: Module.h:64
QualType getParamTypeForDecl() const
Definition: TemplateBase.h:268
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:6275
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2399
Provides information about a function template specialization, which is a FunctionDecl that has been ...
Definition: DeclTemplate.h:470
bool isGLValue() const
Definition: Expr.h:261
Represents a C++ using-declaration.
Definition: DeclCXX.h:3369
Type(TypeClass tc, QualType canon, bool Dependent, bool InstantiationDependent, bool VariablyModified, bool ContainsUnexpandedParameterPack)
Definition: Type.h:1831
const TemplateArgumentList * TemplateArguments
The template arguments used to produce the function template specialization from the function templat...
Definition: DeclTemplate.h:487
static SmallString< 64 > constructSetterName(StringRef Name)
Return the default setter name for the given identifier.
bool isDirectMethod() const
True if the method is tagged as objc_direct.
Definition: DeclObjC.cpp:826
ArrayRef< VTableComponent > vtable_components() const
unsigned Size
The total size of the bit-field, in bits.
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2815
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:2807
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:1765
bool isNonFragile() const
Does this runtime follow the set of implied behaviors for a "non-fragile" ABI?
Definition: ObjCRuntime.h:81
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition: DeclCXX.h:2091
An lvalue ref-qualifier was provided (&).
Definition: Type.h:1406
~ApplyInlineDebugLocation()
Restore everything back to the original state.
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool capturesThis() const
Determine whether this capture handles the C++ this pointer.
Definition: LambdaCapture.h:82
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:588
const BlockDecl * getBlockDecl() const
Definition: CGBlocks.h:280
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
Emit only debug directives with the line numbers data.
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2173
CharUnits StorageOffset
The offset of the bitfield storage from the start of the struct.
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
Definition: TemplateBase.h:274
bool isTypeAlias() const
Determine if this template specialization type is for a type alias template that has been substituted...
Definition: Type.h:5044
void EmitGlobalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl)
Emit information about a global variable.
Deleting dtor.
Definition: ABI.h:34
bool isByRef() const
Whether this is a "by ref" capture, i.e.
Definition: Decl.h:4068
Represents a declaration of a type.
Definition: Decl.h:3029
static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU)
Module * Parent
The parent of this module.
Definition: Module.h:92
const Type * getClass() const
Definition: Type.h:2867
RangeSelector name(std::string ID)
Given a node with a "name", (like NamedDecl, DeclRefExpr or CxxCtorInitializer) selects the name&#39;s to...
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition: Decl.cpp:3663
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:960
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:40
static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R)
Returns the common set of qualifiers while removing them from the given sets.
Definition: Type.h:194
llvm::DIType * getOrCreateInterfaceType(QualType Ty, SourceLocation Loc)
Emit an Objective-C interface type standalone debug info.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6256
unsigned Align
Definition: ASTContext.h:158
field_iterator field_begin() const
Definition: Decl.cpp:4425
bool AlignIsRequired
Definition: ASTContext.h:159
bool isInt() const
Definition: APValue.h:361
bool isCompleteDefinitionRequired() const
Return true if this complete decl is required to be complete for some existing use.
Definition: Decl.h:3333
unsigned Offset
The offset within a contiguous run of bitfields that are represented as a single "field" within the L...
static uint32_t getDeclAlignIfRequired(const Decl *D, const ASTContext &Ctx)
Definition: CGDebugInfo.cpp:62
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC)...
Definition: DeclBase.h:828
void EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn)
Constructs the debug code for exiting a function.
llvm::DIImportedEntity * EmitNamespaceAlias(const NamespaceAliasDecl &NA)
Emit C++ namespace alias.
bool isInstance() const
Definition: DeclCXX.h:1959
void * getAsOpaquePtr() const
Definition: Type.h:699
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization, retrieves the function from which it was instantiated.
Definition: Decl.cpp:3533
Represents an ObjC class declaration.
Definition: DeclObjC.h:1186
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3173
shadow_iterator shadow_begin() const
Definition: DeclCXX.h:3473
void removeVolatile()
Definition: Type.h:267
bool hasConst() const
Definition: Type.h:260
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:877
unsigned PrintCanonicalTypes
Whether to print types as written or canonically.
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition: Decl.h:3821
Module * getImportedModule() const
Retrieve the module that was imported by the import declaration.
Definition: Decl.h:4375
bool NeedsCopyDispose
True if the block has captures that would necessitate custom copy or dispose helper functions if the ...
Definition: CGBlocks.h:222
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition: DeclObjC.h:2773
NodeId Parent
Definition: ASTDiff.cpp:191
QualType getBlockDescriptorExtendedType() const
Gets the struct used to keep track of the extended descriptor for pointer to blocks.
static unsigned getDwarfCC(CallingConv CC)
bool hasAttr() const
Definition: DeclBase.h:542
QualType getBaseType() const
Gets the base type of this object type.
Definition: Type.h:5757
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3754
bool isDynamicClass() const
Definition: DeclCXX.h:553
unsigned MSVCFormatting
Use whitespace and punctuation like MSVC does.
CGBlockInfo - Information to generate a block literal.
Definition: CGBlocks.h:152
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1700
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:671
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:179
ObjCTypeParamDecl * getDecl() const
Definition: Type.h:5663
void setDwoId(uint64_t Signature)
Module debugging: Support for building PCMs.
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:263
unsigned Offset
Definition: Format.cpp:1827
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
capture_const_iterator captures_end() const
Definition: DeclCXX.h:1027
bool isValid() const
void EmitLocation(CGBuilderTy &Builder, SourceLocation Loc)
Emit metadata to indicate a change in line/column information in the source file. ...
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:421
ApplyInlineDebugLocation(CodeGenFunction &CGF, GlobalDecl InlinedFn)
Set up the CodeGenFunction&#39;s DebugInfo to produce inline locations for the function InlinedFn...
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4037
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:619
This represents one expression.
Definition: Expr.h:108
QualType getPointeeType() const
Definition: Type.h:2771
SourceLocation End
known_extensions_range known_extensions() const
Definition: DeclObjC.h:1775
Limit generated debug info to reduce size (-fno-standalone-debug).
bool isPositive() const
isPositive - Test whether the quantity is greater than zero.
Definition: CharUnits.h:122
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:2827
bool isInvalid() const
Return true if this object is invalid or uninitialized.
int Id
Definition: ASTDiff.cpp:190
void EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD)
Start a new scope for an inlined function.
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
const AnnotatedLine * Line
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:1675
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:7067
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:67
unsigned getLine() const
Return the presumed line number of this location.
#define V(N, I)
Definition: ASTContext.h:2941
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2649
Defines version macros and version-related utility functions for Clang.
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition: Decl.h:553
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:558
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:3669
llvm::DIMacroFile * CreateTempMacroFile(llvm::DIMacroFile *Parent, SourceLocation LineLoc, SourceLocation FileLoc)
Create debug info for a file referenced by an #include directive.
field_iterator field_end() const
Definition: Decl.h:3966
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
DeclContext * getDeclContext()
Definition: DeclBase.h:438
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:337
const CXXRecordDecl * getPrimaryBase() const
getPrimaryBase - Get the primary base for this record.
Definition: RecordLayout.h:217
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:293
void completeUnusedClass(const CXXRecordDecl &D)
EnumDecl * getDefinition() const
Definition: Decl.h:3582
void printTemplateArgumentList(raw_ostream &OS, ArrayRef< TemplateArgument > Args, const PrintingPolicy &Policy)
Print a template argument list, including the &#39;<&#39; and &#39;>&#39; enclosing the template arguments.
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], or an enum decl which has a signed representation.
Definition: Type.cpp:1928
QualType getType() const
Definition: Expr.h:137
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:257
bool hasExtendableVFPtr() const
hasVFPtr - Does this class have a virtual function table pointer that can be extended by a derived cl...
Definition: RecordLayout.h:267
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl, 0 if there are none.
Definition: DeclBase.cpp:385
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1784
method_iterator method_end() const
Method past-the-end iterator.
Definition: DeclCXX.h:640
Represents an unpacked "presumed" location which can be presented to the user.
bool isInstanceMethod() const
Definition: DeclObjC.h:423
QualType getBlockDescriptorType() const
Gets the struct used to keep track of the descriptor for pointer to blocks.
Represents a GCC generic vector type.
Definition: Type.h:3235
SourceLocation getCaretLocation() const
Definition: Decl.h:4110
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2797
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition: Decl.cpp:2356
Selector getSelector() const
Definition: DeclObjC.h:322
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:1562
bool isUnionType() const
Definition: Type.cpp:527
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:719
const SourceManager & SM
Definition: Format.cpp:1685
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:265
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2088
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:40
DynamicInitKind getDynamicInitKind() const
Definition: GlobalDecl.h:89
bool isVoidPointerType() const
Definition: Type.cpp:521
bool isObjCOneArgSelector() const
The l-value was considered opaque, so the alignment was determined from a type.
RecordDecl * getDecl() const
Definition: Type.h:4505
const char * getFilename() const
Return the presumed filename of this location.
void EmitDeclareOfArgVariable(const VarDecl *Decl, llvm::Value *AI, unsigned ArgNo, CGBuilderTy &Builder)
Emit call to llvm.dbg.declare for an argument variable declaration.
bool capturesVariable() const
Determine whether this capture handles a variable.
Definition: LambdaCapture.h:88
Pass it as a pointer to temporary memory.
Definition: CGCXXABI.h:136
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:190
virtual void printName(raw_ostream &os) const
Definition: Decl.cpp:1551
unsigned size_overridden_methods() const
Definition: DeclCXX.cpp:2321
static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access, const RecordDecl *RD)
Convert an AccessSpecifier into the corresponding DINode flag.
std::string getAsString() const
Derive the full selector name (e.g.
virtual void mangleCXXRTTIName(QualType T, raw_ostream &)=0
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:3975
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:294
unsigned getColumn() const
Return the presumed column number of this location.
Encodes a location in the source.
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition: Type.h:5908
QualType getReturnType() const
Definition: Type.h:3680
bool isPure() const
Whether this virtual function is pure, i.e.
Definition: Decl.h:2105
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:4521
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:5894
llvm::StructType * StructureType
Definition: CGBlocks.h:245
void completeRequiredType(const RecordDecl *RD)
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:266
Generate complete debug info.
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3219
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:377
QualType getElementType() const
Definition: Type.h:3270
const Decl * getDecl() const
Definition: GlobalDecl.h:77
static QualType getUnderlyingType(const SubRegion *R)
Represents the declaration of a label.
Definition: Decl.h:451
Cached information about one file (either on disk or in the virtual file system). ...
Definition: FileManager.h:78
APFloat & getFloat()
Definition: APValue.h:394
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1931
TypedefNameDecl * getTypedefNameForUnnamedTagDecl(const TagDecl *TD)
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2294
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:3675
llvm::Constant * emitAbstract(const Expr *E, QualType T)
Emit the result of the given expression as an abstract constant, asserting that it succeeded...
Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
Definition: Decl.h:4058
bool hasRestrict() const
Definition: Type.h:270
void EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc, QualType FnType, llvm::Function *Fn=nullptr)
Emit debug info for a function declaration.
llvm::APInt APInt
Definition: Integral.h:27
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:741
Limit generated debug info for classes to reduce size.
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition: DeclBase.h:702
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.
const BlockExpr * getBlockExpr() const
Definition: CGBlocks.h:281
TypeClass getTypeClass() const
Definition: Type.h:1876
MangleContext & getMangleContext()
Gets the mangle context.
Definition: CGCXXABI.h:96
This template specialization was formed from a template-id but has not yet been declared, defined, or instantiated.
Definition: Specifiers.h:178
constexpr XRayInstrMask None
Definition: XRayInstr.h:37
bool operator<(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
VarDecl * getVariable() const
The variable being captured.
Definition: Decl.h:4064
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
Definition: TemplateBase.h:300
EnumDecl * getDecl() const
Definition: Type.h:4528
unsigned CXXThisIndex
The field index of &#39;this&#39; within the block, if there is one.
Definition: CGBlocks.h:158
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1409
void removeObjCGCAttr()
Definition: Type.h:311
ObjCImplementationDecl * getImplementation() const
Definition: DeclObjC.cpp:1574
static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I, CXXRecordDecl::method_iterator End)
llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Loc)
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition: Decl.h:4331
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:224
StringRef getName() const
Return the actual identifier string.
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3071
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Definition: Type.cpp:4152
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Represents a template argument.
Definition: TemplateBase.h:50
const llvm::MemoryBuffer * getBuffer(FileID FID, SourceLocation Loc, bool *Invalid=nullptr) const
Return the buffer for the specified FileID.
void completeClass(const RecordDecl *RD)
This class organizes the cross-function state that is used while generating LLVM code.
NamespaceDecl * getNominatedNamespace()
Returns the namespace nominated by this using-directive.
Definition: DeclCXX.cpp:2753
Dataflow Directional Tag Classes.
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:1672
bool isValid() const
Return true if this is a valid SourceLocation object.
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:6196
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1271
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:586
uint64_t Index
Method&#39;s index in the vftable.
ArrayRef< Capture > captures() const
Definition: Decl.h:4164
static SmallString< 256 > getTypeIdentifier(const TagType *Ty, CodeGenModule &CGM, llvm::DICompileUnit *TheCU)
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:79
bool isRecord() const
Definition: DeclBase.h:1863
Parameter for Objective-C &#39;self&#39; argument.
Definition: Decl.h:1540
QualType getUnderlyingType() const
Definition: Decl.h:3126
llvm::iterator_range< base_class_const_iterator > base_class_const_range
Definition: DeclCXX.h:585
const Expr * getInit() const
Definition: Decl.h:1229
AccessSpecifier getAccess() const
Definition: DeclBase.h:473
ObjCInterfaceDecl * getDefinition()
Retrieve the definition of this class, or NULL if this class has been forward-declared (with @class) ...
Definition: DeclObjC.h:1563
FileID getMainFileID() const
Returns the FileID of the main source file.
bool hasLocalQualifiers() const
Determine whether this particular QualType instance has any qualifiers, without looking through any t...
Definition: Type.h:756
Emit only debug info necessary for generating line number tables (-gline-tables-only).
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:189
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:2046
Kind getKind() const
Definition: DeclBase.h:432
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:6203
Decl * getNonClosureContext()
Find the innermost non-closure ancestor of this declaration, walking up through blocks, lambdas, etc.
Definition: DeclBase.cpp:994
unsigned shadow_size() const
Return the number of shadowed declarations associated with this using declaration.
Definition: DeclCXX.h:3481
CGDebugInfo(CodeGenModule &CGM)
Definition: CGDebugInfo.cpp:66
Represents an enum.
Definition: Decl.h:3481
unsigned StorageSize
The storage size in bits which should be used when accessing this bitfield.
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2833
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2260
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:175
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition: Type.cpp:3500
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any...
Definition: ASTContext.h:1086
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext, providing only those that are of type SpecificDecl (or a class derived from it).
Definition: DeclBase.h:2053
Represents a pointer to an Objective C object.
Definition: Type.h:5951
Pointer to a block type.
Definition: Type.h:2716
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:832
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2566
bool isIncompleteArrayType() const
Definition: Type.h:6578
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4495
Complex values, per C99 6.2.5p11.
Definition: Type.h:2554
Emit location information but do not generate debug info in the output.
void EmitFunctionStart(GlobalDecl GD, SourceLocation Loc, SourceLocation ScopeLoc, QualType FnType, llvm::Function *Fn, bool CurFnIsThunk, CGBuilderTy &Builder)
Emit a call to llvm.dbg.function.start to indicate start of a new function.
bool empty() const
Definition: Type.h:421
llvm::DIType * getOrCreateStandaloneType(QualType Ty, SourceLocation Loc)
Emit standalone debug info for a type.
std::string remapDIPath(StringRef) const
Remap a given path with the current debug prefix map.
unsigned getOwningModuleID() const
Retrieve the global ID of the module that owns this particular declaration.
Definition: DeclBase.h:714
void completeType(const EnumDecl *ED)
DeclaratorDecl * getDeclaratorForUnnamedTagDecl(const TagDecl *TD)
The template argument is a type.
Definition: TemplateBase.h:59
The template argument is actually a parameter pack.
Definition: TemplateBase.h:90
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat]...
Definition: APValue.h:115
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2104
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
Definition: Type.cpp:2115
The type-property cache.
Definition: Type.cpp:3579
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2513
bool capturesCXXThis() const
Definition: Decl.h:4169
A template argument list.
Definition: DeclTemplate.h:239
TypedefNameDecl * getDecl() const
Definition: Type.h:4256
void EmitUsingDecl(const UsingDecl &UD)
Emit C++ using declaration.
void EmitUsingDirective(const UsingDirectiveDecl &UD)
Emit C++ using directive.
void EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc)
Emit metadata to indicate the beginning of a new lexical block and push the block onto the stack...
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:234
Represents a type parameter type in Objective C.
Definition: Type.h:5620
CallingConv getCallConv() const
Definition: Type.h:3690
QualType getAliasedType() const
Get the aliased type, if this is a specialization of a type alias template.
Definition: Type.h:5048
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3429
true
A convenience builder class for complex constant initializers, especially for anonymous global struct...
Represents a C++ struct/union/class.
Definition: DeclCXX.h:253
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:5075
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
The template argument is a template name that was provided for a template template parameter...
Definition: TemplateBase.h:75
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1959
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
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.
This class is used for builtin types like &#39;int&#39;.
Definition: Type.h:2465
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...
SourceLocation getLocation() const
Retrieve the source location of the capture.
bool isComplexIntegerType() const
Definition: Type.cpp:539
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:3635
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:250
bool hasVolatile() const
Definition: Type.h:265
void setLocation(SourceLocation Loc)
Update the current source location.
CGCXXABI & getCXXABI() const
uint64_t Width
Definition: ASTContext.h:157
std::string getQualifiedNameAsString() const
Definition: Decl.cpp:1555
CanQualType IntTy
Definition: ASTContext.h:1025
Abstracts clang modules and precompiled header files and holds everything needed to generate debug in...
unsigned getNumElements() const
Definition: Type.h:3271
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:256
bool isUnion() const
Definition: Decl.h:3407
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:4996
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2259
const internal::VariadicDynCastAllOfMatcher< Decl, BlockDecl > blockDecl
Matches block declarations.
static bool isClassOrMethodDLLImport(const CXXRecordDecl *RD)
Return true if the class or any of its methods are marked dllimport.
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3517
capture_const_iterator captures_begin() const
Definition: DeclCXX.h:1023
RangeSelector node(std::string ID)
Selects a node, including trailing semicolon (for non-expression statements).
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1144
QualType getType() const
Definition: Decl.h:630
static InputKind getInputKindForExtension(StringRef Extension)
getInputKindForExtension - Return the appropriate input kind for a file extension.
A wrapper class around a pointer that always points to its canonical declaration. ...
Definition: Redeclarable.h:347
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3158
This represents a decl that may have a name.
Definition: Decl.h:223
ObjCIvarDecl * all_declared_ivar_begin()
all_declared_ivar_begin - return first ivar declared in this class, its extensions and its implementa...
Definition: DeclObjC.cpp:1617
Represents a C++ namespace alias.
Definition: DeclCXX.h:2967
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:280
APSInt & getInt()
Definition: APValue.h:380
static bool isDefinedInClangModule(const RecordDecl *RD)
Does a type definition exist in an imported clang module?
Represents C++ using-directive.
Definition: DeclCXX.h:2863
void removeAddressSpace()
Definition: Type.h:384
ctor_range ctors() const
Definition: DeclCXX.h:649
MSInheritanceModel getMSInheritanceModel() const
Returns the inheritance model used for this record.
bool isObjCZeroArgSelector() const
base_class_range vbases()
Definition: DeclCXX.h:604
This class handles loading and caching of source files into memory.
SourceLocation getLocation() const
Definition: DeclBase.h:429
QualType getPointeeType() const
Definition: Type.h:2853
Represents a shadow declaration introduced into a scope by a (resolved) using declaration.
Definition: DeclCXX.h:3162
bool isExternallyVisible() const
Definition: Decl.h:362
Structure with information about how a bitfield should be accessed.
NamedDecl * getAliasedNamespace() const
Retrieve the namespace that this alias refers to, which may either be a NamespaceDecl or a NamespaceA...
Definition: DeclCXX.h:3063
const PrintingCallbacks * Callbacks
Callbacks to use to allow the behavior of printing to be customized.
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:5967
method_range methods() const
Definition: DeclCXX.h:629