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