clang  3.8.0
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 "CodeGenFunction.h"
19 #include "CodeGenModule.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/DeclFriend.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/RecordLayout.h"
28 #include "clang/Basic/Version.h"
31 #include "clang/Lex/ModuleMap.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DataLayout.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Instructions.h"
39 #include "llvm/IR/Intrinsics.h"
40 #include "llvm/IR/Module.h"
41 #include "llvm/Support/FileSystem.h"
42 #include "llvm/Support/Path.h"
43 using namespace clang;
44 using namespace clang::CodeGen;
45 
47  : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
48  DebugTypeExtRefs(CGM.getCodeGenOpts().DebugTypeExtRefs),
49  DBuilder(CGM.getModule()) {
50  for (const auto &KV : CGM.getCodeGenOpts().DebugPrefixMap)
51  DebugPrefixMap[KV.first] = KV.second;
52  CreateCompileUnit();
53 }
54 
56  assert(LexicalBlockStack.empty() &&
57  "Region stack mismatch, stack not empty!");
58 }
59 
60 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
61  SourceLocation TemporaryLocation)
62  : CGF(&CGF) {
63  init(TemporaryLocation);
64 }
65 
66 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
67  bool DefaultToEmpty,
68  SourceLocation TemporaryLocation)
69  : CGF(&CGF) {
70  init(TemporaryLocation, DefaultToEmpty);
71 }
72 
73 void ApplyDebugLocation::init(SourceLocation TemporaryLocation,
74  bool DefaultToEmpty) {
75  auto *DI = CGF->getDebugInfo();
76  if (!DI) {
77  CGF = nullptr;
78  return;
79  }
80 
81  OriginalLocation = CGF->Builder.getCurrentDebugLocation();
82  if (TemporaryLocation.isValid()) {
83  DI->EmitLocation(CGF->Builder, TemporaryLocation);
84  return;
85  }
86 
87  if (DefaultToEmpty) {
88  CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc());
89  return;
90  }
91 
92  // Construct a location that has a valid scope, but no line info.
93  assert(!DI->LexicalBlockStack.empty());
94  CGF->Builder.SetCurrentDebugLocation(
95  llvm::DebugLoc::get(0, 0, DI->LexicalBlockStack.back()));
96 }
97 
98 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E)
99  : CGF(&CGF) {
100  init(E->getExprLoc());
101 }
102 
103 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc)
104  : CGF(&CGF) {
105  if (!CGF.getDebugInfo()) {
106  this->CGF = nullptr;
107  return;
108  }
109  OriginalLocation = CGF.Builder.getCurrentDebugLocation();
110  if (Loc)
111  CGF.Builder.SetCurrentDebugLocation(std::move(Loc));
112 }
113 
115  // Query CGF so the location isn't overwritten when location updates are
116  // temporarily disabled (for C++ default function arguments)
117  if (CGF)
118  CGF->Builder.SetCurrentDebugLocation(std::move(OriginalLocation));
119 }
120 
122  // If the new location isn't valid return.
123  if (Loc.isInvalid())
124  return;
125 
126  CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
127 
128  // If we've changed files in the middle of a lexical scope go ahead
129  // and create a new lexical scope with file node if it's different
130  // from the one in the scope.
131  if (LexicalBlockStack.empty())
132  return;
133 
135  auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
136  PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
137 
138  if (PCLoc.isInvalid() || Scope->getFilename() == PCLoc.getFilename())
139  return;
140 
141  if (auto *LBF = dyn_cast<llvm::DILexicalBlockFile>(Scope)) {
142  LexicalBlockStack.pop_back();
143  LexicalBlockStack.emplace_back(DBuilder.createLexicalBlockFile(
144  LBF->getScope(), getOrCreateFile(CurLoc)));
145  } else if (isa<llvm::DILexicalBlock>(Scope) ||
146  isa<llvm::DISubprogram>(Scope)) {
147  LexicalBlockStack.pop_back();
148  LexicalBlockStack.emplace_back(
149  DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc)));
150  }
151 }
152 
153 llvm::DIScope *CGDebugInfo::getDeclContextDescriptor(const Decl *D) {
154  llvm::DIScope *Mod = getParentModuleOrNull(D);
155  return getContextDescriptor(cast<Decl>(D->getDeclContext()),
156  Mod ? Mod : TheCU);
157 }
158 
159 llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context,
160  llvm::DIScope *Default) {
161  if (!Context)
162  return Default;
163 
164  auto I = RegionMap.find(Context);
165  if (I != RegionMap.end()) {
166  llvm::Metadata *V = I->second;
167  return dyn_cast_or_null<llvm::DIScope>(V);
168  }
169 
170  // Check namespace.
171  if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
172  return getOrCreateNameSpace(NSDecl);
173 
174  if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
175  if (!RDecl->isDependentType())
176  return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
177  getOrCreateMainFile());
178  return Default;
179 }
180 
181 StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
182  assert(FD && "Invalid FunctionDecl!");
183  IdentifierInfo *FII = FD->getIdentifier();
186 
187  if (!Info && FII && !CGM.getCodeGenOpts().EmitCodeView)
188  return FII->getName();
189 
190  // Otherwise construct human readable name for debug info.
191  SmallString<128> NS;
192  llvm::raw_svector_ostream OS(NS);
193  PrintingPolicy Policy(CGM.getLangOpts());
194 
195  if (CGM.getCodeGenOpts().EmitCodeView) {
196  // Print a fully qualified name like MSVC would.
197  Policy.MSVCFormatting = true;
198  FD->printQualifiedName(OS, Policy);
199  } else {
200  // Print the unqualified name with some template arguments. This is what
201  // DWARF-based debuggers expect.
202  FD->printName(OS);
203  // Add any template specialization args.
204  if (Info) {
205  const TemplateArgumentList *TArgs = Info->TemplateArguments;
206  const TemplateArgument *Args = TArgs->data();
207  unsigned NumArgs = TArgs->size();
209  Policy);
210  }
211  }
212 
213  // Copy this name on the side and use its reference.
214  return internString(OS.str());
215 }
216 
217 StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
218  SmallString<256> MethodName;
219  llvm::raw_svector_ostream OS(MethodName);
220  OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
221  const DeclContext *DC = OMD->getDeclContext();
222  if (const ObjCImplementationDecl *OID =
223  dyn_cast<const ObjCImplementationDecl>(DC)) {
224  OS << OID->getName();
225  } else if (const ObjCInterfaceDecl *OID =
226  dyn_cast<const ObjCInterfaceDecl>(DC)) {
227  OS << OID->getName();
228  } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(DC)) {
229  if (OC->IsClassExtension()) {
230  OS << OC->getClassInterface()->getName();
231  } else {
232  OS << ((const NamedDecl *)OC)->getIdentifier()->getNameStart() << '('
233  << OC->getIdentifier()->getNameStart() << ')';
234  }
235  } else if (const ObjCCategoryImplDecl *OCD =
236  dyn_cast<const ObjCCategoryImplDecl>(DC)) {
237  OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '('
238  << OCD->getIdentifier()->getNameStart() << ')';
239  } else if (isa<ObjCProtocolDecl>(DC)) {
240  // We can extract the type of the class from the self pointer.
241  if (ImplicitParamDecl *SelfDecl = OMD->getSelfDecl()) {
242  QualType ClassTy =
243  cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
244  ClassTy.print(OS, PrintingPolicy(LangOptions()));
245  }
246  }
247  OS << ' ' << OMD->getSelector().getAsString() << ']';
248 
249  return internString(OS.str());
250 }
251 
252 StringRef CGDebugInfo::getSelectorName(Selector S) {
253  return internString(S.getAsString());
254 }
255 
256 StringRef CGDebugInfo::getClassName(const RecordDecl *RD) {
257  // quick optimization to avoid having to intern strings that are already
258  // stored reliably elsewhere
259  if (!isa<ClassTemplateSpecializationDecl>(RD))
260  return RD->getName();
261 
262  SmallString<128> Name;
263  {
264  llvm::raw_svector_ostream OS(Name);
266  /*Qualified*/ false);
267  }
268 
269  // Copy this name on the side and use its reference.
270  return internString(Name);
271 }
272 
273 llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
274  if (!Loc.isValid())
275  // If Location is not valid then use main input file.
276  return DBuilder.createFile(remapDIPath(TheCU->getFilename()),
277  remapDIPath(TheCU->getDirectory()));
278 
280  PresumedLoc PLoc = SM.getPresumedLoc(Loc);
281 
282  if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
283  // If the location is not valid then use main input file.
284  return DBuilder.createFile(remapDIPath(TheCU->getFilename()),
285  remapDIPath(TheCU->getDirectory()));
286 
287  // Cache the results.
288  const char *fname = PLoc.getFilename();
289  auto it = DIFileCache.find(fname);
290 
291  if (it != DIFileCache.end()) {
292  // Verify that the information still exists.
293  if (llvm::Metadata *V = it->second)
294  return cast<llvm::DIFile>(V);
295  }
296 
297  llvm::DIFile *F = DBuilder.createFile(remapDIPath(PLoc.getFilename()),
298  remapDIPath(getCurrentDirname()));
299 
300  DIFileCache[fname].reset(F);
301  return F;
302 }
303 
304 llvm::DIFile *CGDebugInfo::getOrCreateMainFile() {
305  return DBuilder.createFile(remapDIPath(TheCU->getFilename()),
306  remapDIPath(TheCU->getDirectory()));
307 }
308 
309 std::string CGDebugInfo::remapDIPath(StringRef Path) const {
310  for (const auto &Entry : DebugPrefixMap)
311  if (Path.startswith(Entry.first))
312  return (Twine(Entry.second) + Path.substr(Entry.first.size())).str();
313  return Path.str();
314 }
315 
316 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
317  if (Loc.isInvalid() && CurLoc.isInvalid())
318  return 0;
320  PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
321  return PLoc.isValid() ? PLoc.getLine() : 0;
322 }
323 
324 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
325  // We may not want column information at all.
326  if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
327  return 0;
328 
329  // If the location is invalid then use the current column.
330  if (Loc.isInvalid() && CurLoc.isInvalid())
331  return 0;
333  PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
334  return PLoc.isValid() ? PLoc.getColumn() : 0;
335 }
336 
337 StringRef CGDebugInfo::getCurrentDirname() {
338  if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
339  return CGM.getCodeGenOpts().DebugCompilationDir;
340 
341  if (!CWDName.empty())
342  return CWDName;
343  SmallString<256> CWD;
344  llvm::sys::fs::current_path(CWD);
345  return CWDName = internString(CWD);
346 }
347 
348 void CGDebugInfo::CreateCompileUnit() {
349 
350  // Should we be asking the SourceManager for the main file name, instead of
351  // accepting it as an argument? This just causes the main file name to
352  // mismatch with source locations and create extra lexical scopes or
353  // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
354  // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
355  // because that's what the SourceManager says)
356 
357  // Get absolute path name.
359  std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
360  if (MainFileName.empty())
361  MainFileName = "<stdin>";
362 
363  // The main file name provided via the "-main-file-name" option contains just
364  // the file name itself with no path information. This file name may have had
365  // a relative path, so we look into the actual file entry for the main
366  // file to determine the real absolute path for the file.
367  std::string MainFileDir;
368  if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
369  MainFileDir = remapDIPath(MainFile->getDir()->getName());
370  if (MainFileDir != ".") {
371  llvm::SmallString<1024> MainFileDirSS(MainFileDir);
372  llvm::sys::path::append(MainFileDirSS, MainFileName);
373  MainFileName = MainFileDirSS.str();
374  }
375  }
376 
377  llvm::dwarf::SourceLanguage LangTag;
378  const LangOptions &LO = CGM.getLangOpts();
379  if (LO.CPlusPlus) {
380  if (LO.ObjC1)
381  LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
382  else
383  LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
384  } else if (LO.ObjC1) {
385  LangTag = llvm::dwarf::DW_LANG_ObjC;
386  } else if (LO.C99) {
387  LangTag = llvm::dwarf::DW_LANG_C99;
388  } else {
389  LangTag = llvm::dwarf::DW_LANG_C89;
390  }
391 
392  std::string Producer = getClangFullVersion();
393 
394  // Figure out which version of the ObjC runtime we have.
395  unsigned RuntimeVers = 0;
396  if (LO.ObjC1)
397  RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
398 
399  // Create new compile unit.
400  // FIXME - Eliminate TheCU.
401  TheCU = DBuilder.createCompileUnit(
402  LangTag, remapDIPath(MainFileName), remapDIPath(getCurrentDirname()),
403  Producer, LO.Optimize, CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers,
406  ? llvm::DIBuilder::LineTablesOnly
407  : llvm::DIBuilder::FullDebug,
408  0 /* DWOid */, DebugKind != CodeGenOptions::LocTrackingOnly);
409 }
410 
411 llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {
412  llvm::dwarf::TypeKind Encoding;
413  StringRef BTName;
414  switch (BT->getKind()) {
415 #define BUILTIN_TYPE(Id, SingletonId)
416 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
417 #include "clang/AST/BuiltinTypes.def"
418  case BuiltinType::Dependent:
419  llvm_unreachable("Unexpected builtin type");
420  case BuiltinType::NullPtr:
421  return DBuilder.createNullPtrType();
422  case BuiltinType::Void:
423  return nullptr;
424  case BuiltinType::ObjCClass:
425  if (!ClassTy)
426  ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
427  "objc_class", TheCU,
428  getOrCreateMainFile(), 0);
429  return ClassTy;
430  case BuiltinType::ObjCId: {
431  // typedef struct objc_class *Class;
432  // typedef struct objc_object {
433  // Class isa;
434  // } *id;
435 
436  if (ObjTy)
437  return ObjTy;
438 
439  if (!ClassTy)
440  ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
441  "objc_class", TheCU,
442  getOrCreateMainFile(), 0);
443 
444  unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
445 
446  auto *ISATy = DBuilder.createPointerType(ClassTy, Size);
447 
448  ObjTy =
449  DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
450  0, 0, 0, 0, nullptr, llvm::DINodeArray());
451 
452  DBuilder.replaceArrays(
453  ObjTy,
454  DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
455  ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
456  return ObjTy;
457  }
458  case BuiltinType::ObjCSel: {
459  if (!SelTy)
460  SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
461  "objc_selector", TheCU,
462  getOrCreateMainFile(), 0);
463  return SelTy;
464  }
465 
466  case BuiltinType::OCLImage1d:
467  return getOrCreateStructPtrType("opencl_image1d_t", OCLImage1dDITy);
468  case BuiltinType::OCLImage1dArray:
469  return getOrCreateStructPtrType("opencl_image1d_array_t",
470  OCLImage1dArrayDITy);
471  case BuiltinType::OCLImage1dBuffer:
472  return getOrCreateStructPtrType("opencl_image1d_buffer_t",
473  OCLImage1dBufferDITy);
474  case BuiltinType::OCLImage2d:
475  return getOrCreateStructPtrType("opencl_image2d_t", OCLImage2dDITy);
476  case BuiltinType::OCLImage2dArray:
477  return getOrCreateStructPtrType("opencl_image2d_array_t",
478  OCLImage2dArrayDITy);
479  case BuiltinType::OCLImage2dDepth:
480  return getOrCreateStructPtrType("opencl_image2d_depth_t",
481  OCLImage2dDepthDITy);
482  case BuiltinType::OCLImage2dArrayDepth:
483  return getOrCreateStructPtrType("opencl_image2d_array_depth_t",
484  OCLImage2dArrayDepthDITy);
485  case BuiltinType::OCLImage2dMSAA:
486  return getOrCreateStructPtrType("opencl_image2d_msaa_t",
487  OCLImage2dMSAADITy);
488  case BuiltinType::OCLImage2dArrayMSAA:
489  return getOrCreateStructPtrType("opencl_image2d_array_msaa_t",
490  OCLImage2dArrayMSAADITy);
491  case BuiltinType::OCLImage2dMSAADepth:
492  return getOrCreateStructPtrType("opencl_image2d_msaa_depth_t",
493  OCLImage2dMSAADepthDITy);
494  case BuiltinType::OCLImage2dArrayMSAADepth:
495  return getOrCreateStructPtrType("opencl_image2d_array_msaa_depth_t",
496  OCLImage2dArrayMSAADepthDITy);
497  case BuiltinType::OCLImage3d:
498  return getOrCreateStructPtrType("opencl_image3d_t", OCLImage3dDITy);
499  case BuiltinType::OCLSampler:
500  return DBuilder.createBasicType(
501  "opencl_sampler_t", CGM.getContext().getTypeSize(BT),
502  CGM.getContext().getTypeAlign(BT), llvm::dwarf::DW_ATE_unsigned);
503  case BuiltinType::OCLEvent:
504  return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);
505  case BuiltinType::OCLClkEvent:
506  return getOrCreateStructPtrType("opencl_clk_event_t", OCLClkEventDITy);
507  case BuiltinType::OCLQueue:
508  return getOrCreateStructPtrType("opencl_queue_t", OCLQueueDITy);
509  case BuiltinType::OCLNDRange:
510  return getOrCreateStructPtrType("opencl_ndrange_t", OCLNDRangeDITy);
511  case BuiltinType::OCLReserveID:
512  return getOrCreateStructPtrType("opencl_reserve_id_t", OCLReserveIDDITy);
513 
514  case BuiltinType::UChar:
515  case BuiltinType::Char_U:
516  Encoding = llvm::dwarf::DW_ATE_unsigned_char;
517  break;
518  case BuiltinType::Char_S:
519  case BuiltinType::SChar:
520  Encoding = llvm::dwarf::DW_ATE_signed_char;
521  break;
522  case BuiltinType::Char16:
523  case BuiltinType::Char32:
524  Encoding = llvm::dwarf::DW_ATE_UTF;
525  break;
526  case BuiltinType::UShort:
527  case BuiltinType::UInt:
528  case BuiltinType::UInt128:
529  case BuiltinType::ULong:
530  case BuiltinType::WChar_U:
531  case BuiltinType::ULongLong:
532  Encoding = llvm::dwarf::DW_ATE_unsigned;
533  break;
534  case BuiltinType::Short:
535  case BuiltinType::Int:
536  case BuiltinType::Int128:
537  case BuiltinType::Long:
538  case BuiltinType::WChar_S:
539  case BuiltinType::LongLong:
540  Encoding = llvm::dwarf::DW_ATE_signed;
541  break;
542  case BuiltinType::Bool:
543  Encoding = llvm::dwarf::DW_ATE_boolean;
544  break;
545  case BuiltinType::Half:
546  case BuiltinType::Float:
547  case BuiltinType::LongDouble:
548  case BuiltinType::Double:
549  Encoding = llvm::dwarf::DW_ATE_float;
550  break;
551  }
552 
553  switch (BT->getKind()) {
554  case BuiltinType::Long:
555  BTName = "long int";
556  break;
557  case BuiltinType::LongLong:
558  BTName = "long long int";
559  break;
560  case BuiltinType::ULong:
561  BTName = "long unsigned int";
562  break;
563  case BuiltinType::ULongLong:
564  BTName = "long long unsigned int";
565  break;
566  default:
567  BTName = BT->getName(CGM.getLangOpts());
568  break;
569  }
570  // Bit size, align and offset of the type.
571  uint64_t Size = CGM.getContext().getTypeSize(BT);
572  uint64_t Align = CGM.getContext().getTypeAlign(BT);
573  return DBuilder.createBasicType(BTName, Size, Align, Encoding);
574 }
575 
576 llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) {
577  // Bit size, align and offset of the type.
578  llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
579  if (Ty->isComplexIntegerType())
580  Encoding = llvm::dwarf::DW_ATE_lo_user;
581 
582  uint64_t Size = CGM.getContext().getTypeSize(Ty);
583  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
584  return DBuilder.createBasicType("complex", Size, Align, Encoding);
585 }
586 
587 llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty,
588  llvm::DIFile *Unit) {
590  const Type *T = Qc.strip(Ty);
591 
592  // Ignore these qualifiers for now.
593  Qc.removeObjCGCAttr();
594  Qc.removeAddressSpace();
595  Qc.removeObjCLifetime();
596 
597  // We will create one Derived type for one qualifier and recurse to handle any
598  // additional ones.
599  llvm::dwarf::Tag Tag;
600  if (Qc.hasConst()) {
601  Tag = llvm::dwarf::DW_TAG_const_type;
602  Qc.removeConst();
603  } else if (Qc.hasVolatile()) {
604  Tag = llvm::dwarf::DW_TAG_volatile_type;
605  Qc.removeVolatile();
606  } else if (Qc.hasRestrict()) {
607  Tag = llvm::dwarf::DW_TAG_restrict_type;
608  Qc.removeRestrict();
609  } else {
610  assert(Qc.empty() && "Unknown type qualifier for debug info");
611  return getOrCreateType(QualType(T, 0), Unit);
612  }
613 
614  auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
615 
616  // No need to fill in the Name, Line, Size, Alignment, Offset in case of
617  // CVR derived types.
618  return DBuilder.createQualifiedType(Tag, FromTy);
619 }
620 
621 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
622  llvm::DIFile *Unit) {
623 
624  // The frontend treats 'id' as a typedef to an ObjCObjectType,
625  // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
626  // debug info, we want to emit 'id' in both cases.
627  if (Ty->isObjCQualifiedIdType())
628  return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
629 
630  return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
631  Ty->getPointeeType(), Unit);
632 }
633 
634 llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty,
635  llvm::DIFile *Unit) {
636  return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
637  Ty->getPointeeType(), Unit);
638 }
639 
640 /// \return whether a C++ mangling exists for the type defined by TD.
641 static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {
642  switch (TheCU->getSourceLanguage()) {
643  case llvm::dwarf::DW_LANG_C_plus_plus:
644  return true;
645  case llvm::dwarf::DW_LANG_ObjC_plus_plus:
646  return isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD);
647  default:
648  return false;
649  }
650 }
651 
652 /// In C++ mode, types have linkage, so we can rely on the ODR and
653 /// on their mangled names, if they're external.
654 static SmallString<256> getUniqueTagTypeName(const TagType *Ty,
655  CodeGenModule &CGM,
656  llvm::DICompileUnit *TheCU) {
657  SmallString<256> FullName;
658  const TagDecl *TD = Ty->getDecl();
659 
660  if (!hasCXXMangling(TD, TheCU) || !TD->isExternallyVisible())
661  return FullName;
662 
663  // Microsoft Mangler does not have support for mangleCXXRTTIName yet.
664  if (CGM.getTarget().getCXXABI().isMicrosoft())
665  return FullName;
666 
667  // TODO: This is using the RTTI name. Is there a better way to get
668  // a unique string for a type?
669  llvm::raw_svector_ostream Out(FullName);
671  return FullName;
672 }
673 
674 /// \return the approproate DWARF tag for a composite type.
675 static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
676  llvm::dwarf::Tag Tag;
677  if (RD->isStruct() || RD->isInterface())
678  Tag = llvm::dwarf::DW_TAG_structure_type;
679  else if (RD->isUnion())
680  Tag = llvm::dwarf::DW_TAG_union_type;
681  else {
682  // FIXME: This could be a struct type giving a default visibility different
683  // than C++ class type, but needs llvm metadata changes first.
684  assert(RD->isClass());
685  Tag = llvm::dwarf::DW_TAG_class_type;
686  }
687  return Tag;
688 }
689 
690 llvm::DICompositeType *
691 CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
692  llvm::DIScope *Ctx) {
693  const RecordDecl *RD = Ty->getDecl();
694  if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
695  return cast<llvm::DICompositeType>(T);
696  llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
697  unsigned Line = getLineNumber(RD->getLocation());
698  StringRef RDName = getClassName(RD);
699 
700  uint64_t Size = 0;
701  uint64_t Align = 0;
702 
703  const RecordDecl *D = RD->getDefinition();
704  if (D && D->isCompleteDefinition()) {
705  Size = CGM.getContext().getTypeSize(Ty);
706  Align = CGM.getContext().getTypeAlign(Ty);
707  }
708 
709  // Create the type.
710  SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
711  llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(
712  getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align,
713  llvm::DINode::FlagFwdDecl, FullName);
714  ReplaceMap.emplace_back(
715  std::piecewise_construct, std::make_tuple(Ty),
716  std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
717  return RetTy;
718 }
719 
720 llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
721  const Type *Ty,
722  QualType PointeeTy,
723  llvm::DIFile *Unit) {
724  // Bit size, align and offset of the type.
725  // Size is always the size of a pointer. We can't use getTypeSize here
726  // because that does not return the correct value for references.
727  unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
728  uint64_t Size = CGM.getTarget().getPointerWidth(AS);
729  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
730 
731  if (Tag == llvm::dwarf::DW_TAG_reference_type ||
732  Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
733  return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit),
734  Size, Align);
735  else
736  return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
737  Align);
738 }
739 
740 llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
741  llvm::DIType *&Cache) {
742  if (Cache)
743  return Cache;
744  Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
745  TheCU, getOrCreateMainFile(), 0);
746  unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
747  Cache = DBuilder.createPointerType(Cache, Size);
748  return Cache;
749 }
750 
751 llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,
752  llvm::DIFile *Unit) {
754  QualType FType;
755  uint64_t FieldSize, FieldOffset;
756  unsigned FieldAlign;
757  llvm::DINodeArray Elements;
758 
759  FieldOffset = 0;
760  FType = CGM.getContext().UnsignedLongTy;
761  EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
762  EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
763 
764  Elements = DBuilder.getOrCreateArray(EltTys);
765  EltTys.clear();
766 
767  unsigned Flags = llvm::DINode::FlagAppleBlock;
768  unsigned LineNo = 0;
769 
770  auto *EltTy =
771  DBuilder.createStructType(Unit, "__block_descriptor", nullptr, LineNo,
772  FieldOffset, 0, Flags, nullptr, Elements);
773 
774  // Bit size, align and offset of the type.
775  uint64_t Size = CGM.getContext().getTypeSize(Ty);
776 
777  auto *DescTy = DBuilder.createPointerType(EltTy, Size);
778 
779  FieldOffset = 0;
780  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
781  EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
782  FType = CGM.getContext().IntTy;
783  EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
784  EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
785  FType = CGM.getContext().getPointerType(Ty->getPointeeType());
786  EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
787 
788  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
789  FieldSize = CGM.getContext().getTypeSize(Ty);
790  FieldAlign = CGM.getContext().getTypeAlign(Ty);
791  EltTys.push_back(DBuilder.createMemberType(Unit, "__descriptor", nullptr, LineNo,
792  FieldSize, FieldAlign, FieldOffset,
793  0, DescTy));
794 
795  FieldOffset += FieldSize;
796  Elements = DBuilder.getOrCreateArray(EltTys);
797 
798  // The __block_literal_generic structs are marked with a special
799  // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
800  // the debugger needs to know about. To allow type uniquing, emit
801  // them without a name or a location.
802  EltTy =
803  DBuilder.createStructType(Unit, "", nullptr, LineNo,
804  FieldOffset, 0, Flags, nullptr, Elements);
805 
806  return DBuilder.createPointerType(EltTy, Size);
807 }
808 
809 llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
810  llvm::DIFile *Unit) {
811  assert(Ty->isTypeAlias());
812  llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
813 
814  SmallString<128> NS;
815  llvm::raw_svector_ostream OS(NS);
816  Ty->getTemplateName().print(OS, CGM.getContext().getPrintingPolicy(),
817  /*qualified*/ false);
818 
820  OS, Ty->getArgs(), Ty->getNumArgs(),
821  CGM.getContext().getPrintingPolicy());
822 
823  TypeAliasDecl *AliasDecl = cast<TypeAliasTemplateDecl>(
824  Ty->getTemplateName().getAsTemplateDecl())->getTemplatedDecl();
825 
826  SourceLocation Loc = AliasDecl->getLocation();
827  return DBuilder.createTypedef(Src, OS.str(), getOrCreateFile(Loc),
828  getLineNumber(Loc),
829  getDeclContextDescriptor(AliasDecl));
830 }
831 
832 llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
833  llvm::DIFile *Unit) {
834  // We don't set size information, but do specify where the typedef was
835  // declared.
836  SourceLocation Loc = Ty->getDecl()->getLocation();
837 
838  // Typedefs are derived from some other type.
839  return DBuilder.createTypedef(
840  getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
841  Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
842  getDeclContextDescriptor(Ty->getDecl()));
843 }
844 
845 llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,
846  llvm::DIFile *Unit) {
848 
849  // Add the result type at least.
850  EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
851 
852  // Set up remainder of arguments if there is a prototype.
853  // otherwise emit it as a variadic function.
854  if (isa<FunctionNoProtoType>(Ty))
855  EltTys.push_back(DBuilder.createUnspecifiedParameter());
856  else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
857  for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
858  EltTys.push_back(getOrCreateType(FPT->getParamType(i), Unit));
859  if (FPT->isVariadic())
860  EltTys.push_back(DBuilder.createUnspecifiedParameter());
861  }
862 
863  llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
864  return DBuilder.createSubroutineType(EltTypeArray);
865 }
866 
867 /// Convert an AccessSpecifier into the corresponding DINode flag.
868 /// As an optimization, return 0 if the access specifier equals the
869 /// default for the containing type.
870 static unsigned getAccessFlag(AccessSpecifier Access, const RecordDecl *RD) {
872  if (RD && RD->isClass())
873  Default = clang::AS_private;
874  else if (RD && (RD->isStruct() || RD->isUnion()))
875  Default = clang::AS_public;
876 
877  if (Access == Default)
878  return 0;
879 
880  switch (Access) {
881  case clang::AS_private:
882  return llvm::DINode::FlagPrivate;
883  case clang::AS_protected:
884  return llvm::DINode::FlagProtected;
885  case clang::AS_public:
886  return llvm::DINode::FlagPublic;
887  case clang::AS_none:
888  return 0;
889  }
890  llvm_unreachable("unexpected access enumerator");
891 }
892 
893 llvm::DIType *CGDebugInfo::createFieldType(
894  StringRef name, QualType type, uint64_t sizeInBitsOverride,
895  SourceLocation loc, AccessSpecifier AS, uint64_t offsetInBits,
896  llvm::DIFile *tunit, llvm::DIScope *scope, const RecordDecl *RD) {
897  llvm::DIType *debugType = getOrCreateType(type, tunit);
898 
899  // Get the location for the field.
900  llvm::DIFile *file = getOrCreateFile(loc);
901  unsigned line = getLineNumber(loc);
902 
903  uint64_t SizeInBits = 0;
904  unsigned AlignInBits = 0;
905  if (!type->isIncompleteArrayType()) {
906  TypeInfo TI = CGM.getContext().getTypeInfo(type);
907  SizeInBits = TI.Width;
908  AlignInBits = TI.Align;
909 
910  if (sizeInBitsOverride)
911  SizeInBits = sizeInBitsOverride;
912  }
913 
914  unsigned flags = getAccessFlag(AS, RD);
915  return DBuilder.createMemberType(scope, name, file, line, SizeInBits,
916  AlignInBits, offsetInBits, flags, debugType);
917 }
918 
919 void CGDebugInfo::CollectRecordLambdaFields(
920  const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
921  llvm::DIType *RecordTy) {
922  // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
923  // has the name and the location of the variable so we should iterate over
924  // both concurrently.
925  const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
926  RecordDecl::field_iterator Field = CXXDecl->field_begin();
927  unsigned fieldno = 0;
929  E = CXXDecl->captures_end();
930  I != E; ++I, ++Field, ++fieldno) {
931  const LambdaCapture &C = *I;
932  if (C.capturesVariable()) {
933  VarDecl *V = C.getCapturedVar();
934  llvm::DIFile *VUnit = getOrCreateFile(C.getLocation());
935  StringRef VName = V->getName();
936  uint64_t SizeInBitsOverride = 0;
937  if (Field->isBitField()) {
938  SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
939  assert(SizeInBitsOverride && "found named 0-width bitfield");
940  }
941  llvm::DIType *fieldType = createFieldType(
942  VName, Field->getType(), SizeInBitsOverride, C.getLocation(),
943  Field->getAccess(), layout.getFieldOffset(fieldno), VUnit, RecordTy,
944  CXXDecl);
945  elements.push_back(fieldType);
946  } else if (C.capturesThis()) {
947  // TODO: Need to handle 'this' in some way by probably renaming the
948  // this of the lambda class and having a field member of 'this' or
949  // by using AT_object_pointer for the function and having that be
950  // used as 'this' for semantic references.
951  FieldDecl *f = *Field;
952  llvm::DIFile *VUnit = getOrCreateFile(f->getLocation());
953  QualType type = f->getType();
954  llvm::DIType *fieldType = createFieldType(
955  "this", type, 0, f->getLocation(), f->getAccess(),
956  layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
957 
958  elements.push_back(fieldType);
959  }
960  }
961 }
962 
963 llvm::DIDerivedType *
964 CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
965  const RecordDecl *RD) {
966  // Create the descriptor for the static variable, with or without
967  // constant initializers.
968  Var = Var->getCanonicalDecl();
969  llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());
970  llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);
971 
972  unsigned LineNumber = getLineNumber(Var->getLocation());
973  StringRef VName = Var->getName();
974  llvm::Constant *C = nullptr;
975  if (Var->getInit()) {
976  const APValue *Value = Var->evaluateValue();
977  if (Value) {
978  if (Value->isInt())
979  C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
980  if (Value->isFloat())
981  C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
982  }
983  }
984 
985  unsigned Flags = getAccessFlag(Var->getAccess(), RD);
986  llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
987  RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
988  StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
989  return GV;
990 }
991 
992 void CGDebugInfo::CollectRecordNormalField(
993  const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,
994  SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,
995  const RecordDecl *RD) {
996  StringRef name = field->getName();
997  QualType type = field->getType();
998 
999  // Ignore unnamed fields unless they're anonymous structs/unions.
1000  if (name.empty() && !type->isRecordType())
1001  return;
1002 
1003  uint64_t SizeInBitsOverride = 0;
1004  if (field->isBitField()) {
1005  SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
1006  assert(SizeInBitsOverride && "found named 0-width bitfield");
1007  }
1008 
1009  llvm::DIType *fieldType =
1010  createFieldType(name, type, SizeInBitsOverride, field->getLocation(),
1011  field->getAccess(), OffsetInBits, tunit, RecordTy, RD);
1012 
1013  elements.push_back(fieldType);
1014 }
1015 
1016 void CGDebugInfo::CollectRecordFields(
1017  const RecordDecl *record, llvm::DIFile *tunit,
1019  llvm::DICompositeType *RecordTy) {
1020  const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
1021 
1022  if (CXXDecl && CXXDecl->isLambda())
1023  CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
1024  else {
1025  const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
1026 
1027  // Field number for non-static fields.
1028  unsigned fieldNo = 0;
1029 
1030  // Static and non-static members should appear in the same order as
1031  // the corresponding declarations in the source program.
1032  for (const auto *I : record->decls())
1033  if (const auto *V = dyn_cast<VarDecl>(I)) {
1034  // Reuse the existing static member declaration if one exists
1035  auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
1036  if (MI != StaticDataMemberCache.end()) {
1037  assert(MI->second &&
1038  "Static data member declaration should still exist");
1039  elements.push_back(MI->second);
1040  } else {
1041  auto Field = CreateRecordStaticField(V, RecordTy, record);
1042  elements.push_back(Field);
1043  }
1044  } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
1045  CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
1046  elements, RecordTy, record);
1047 
1048  // Bump field number for next field.
1049  ++fieldNo;
1050  }
1051  }
1052 }
1053 
1054 llvm::DISubroutineType *
1055 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
1056  llvm::DIFile *Unit) {
1057  const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
1058  if (Method->isStatic())
1059  return cast_or_null<llvm::DISubroutineType>(
1060  getOrCreateType(QualType(Func, 0), Unit));
1061  return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
1062  Func, Unit);
1063 }
1064 
1065 llvm::DISubroutineType *CGDebugInfo::getOrCreateInstanceMethodType(
1066  QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile *Unit) {
1067  // Add "this" pointer.
1068  llvm::DITypeRefArray Args(
1069  cast<llvm::DISubroutineType>(getOrCreateType(QualType(Func, 0), Unit))
1070  ->getTypeArray());
1071  assert(Args.size() && "Invalid number of arguments!");
1072 
1074 
1075  // First element is always return type. For 'void' functions it is NULL.
1076  Elts.push_back(Args[0]);
1077 
1078  // "this" pointer is always first argument.
1079  const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
1080  if (isa<ClassTemplateSpecializationDecl>(RD)) {
1081  // Create pointer type directly in this case.
1082  const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1083  QualType PointeeTy = ThisPtrTy->getPointeeType();
1084  unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
1085  uint64_t Size = CGM.getTarget().getPointerWidth(AS);
1086  uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
1087  llvm::DIType *PointeeType = getOrCreateType(PointeeTy, Unit);
1088  llvm::DIType *ThisPtrType =
1089  DBuilder.createPointerType(PointeeType, Size, Align);
1090  TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1091  // TODO: This and the artificial type below are misleading, the
1092  // types aren't artificial the argument is, but the current
1093  // metadata doesn't represent that.
1094  ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1095  Elts.push_back(ThisPtrType);
1096  } else {
1097  llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);
1098  TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1099  ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1100  Elts.push_back(ThisPtrType);
1101  }
1102 
1103  // Copy rest of the arguments.
1104  for (unsigned i = 1, e = Args.size(); i != e; ++i)
1105  Elts.push_back(Args[i]);
1106 
1107  llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
1108 
1109  unsigned Flags = 0;
1110  if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1111  Flags |= llvm::DINode::FlagLValueReference;
1112  if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1113  Flags |= llvm::DINode::FlagRValueReference;
1114 
1115  return DBuilder.createSubroutineType(EltTypeArray, Flags);
1116 }
1117 
1118 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
1119 /// inside a function.
1120 static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1121  if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1122  return isFunctionLocalClass(NRD);
1123  if (isa<FunctionDecl>(RD->getDeclContext()))
1124  return true;
1125  return false;
1126 }
1127 
1128 llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
1129  const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {
1130  bool IsCtorOrDtor =
1131  isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
1132 
1133  StringRef MethodName = getFunctionName(Method);
1134  llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit);
1135 
1136  // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1137  // make sense to give a single ctor/dtor a linkage name.
1138  StringRef MethodLinkageName;
1139  if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1140  MethodLinkageName = CGM.getMangledName(Method);
1141 
1142  // Get the location for the method.
1143  llvm::DIFile *MethodDefUnit = nullptr;
1144  unsigned MethodLine = 0;
1145  if (!Method->isImplicit()) {
1146  MethodDefUnit = getOrCreateFile(Method->getLocation());
1147  MethodLine = getLineNumber(Method->getLocation());
1148  }
1149 
1150  // Collect virtual method info.
1151  llvm::DIType *ContainingType = nullptr;
1152  unsigned Virtuality = 0;
1153  unsigned VIndex = 0;
1154 
1155  if (Method->isVirtual()) {
1156  if (Method->isPure())
1157  Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1158  else
1159  Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
1160 
1161  // It doesn't make sense to give a virtual destructor a vtable index,
1162  // since a single destructor has two entries in the vtable.
1163  // FIXME: Add proper support for debug info for virtual calls in
1164  // the Microsoft ABI, where we may use multiple vptrs to make a vftable
1165  // lookup if we have multiple or virtual inheritance.
1166  if (!isa<CXXDestructorDecl>(Method) &&
1167  !CGM.getTarget().getCXXABI().isMicrosoft())
1168  VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
1169  ContainingType = RecordTy;
1170  }
1171 
1172  unsigned Flags = 0;
1173  if (Method->isImplicit())
1174  Flags |= llvm::DINode::FlagArtificial;
1175  Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
1176  if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1177  if (CXXC->isExplicit())
1178  Flags |= llvm::DINode::FlagExplicit;
1179  } else if (const CXXConversionDecl *CXXC =
1180  dyn_cast<CXXConversionDecl>(Method)) {
1181  if (CXXC->isExplicit())
1182  Flags |= llvm::DINode::FlagExplicit;
1183  }
1184  if (Method->hasPrototype())
1185  Flags |= llvm::DINode::FlagPrototyped;
1186  if (Method->getRefQualifier() == RQ_LValue)
1187  Flags |= llvm::DINode::FlagLValueReference;
1188  if (Method->getRefQualifier() == RQ_RValue)
1189  Flags |= llvm::DINode::FlagRValueReference;
1190 
1191  llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1192  llvm::DISubprogram *SP = DBuilder.createMethod(
1193  RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
1194  MethodTy, /*isLocalToUnit=*/false,
1195  /* isDefinition=*/false, Virtuality, VIndex, ContainingType, Flags,
1196  CGM.getLangOpts().Optimize, TParamsArray.get());
1197 
1198  SPCache[Method->getCanonicalDecl()].reset(SP);
1199 
1200  return SP;
1201 }
1202 
1203 void CGDebugInfo::CollectCXXMemberFunctions(
1204  const CXXRecordDecl *RD, llvm::DIFile *Unit,
1205  SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
1206 
1207  // Since we want more than just the individual member decls if we
1208  // have templated functions iterate over every declaration to gather
1209  // the functions.
1210  for (const auto *I : RD->decls()) {
1211  const auto *Method = dyn_cast<CXXMethodDecl>(I);
1212  // If the member is implicit, don't add it to the member list. This avoids
1213  // the member being added to type units by LLVM, while still allowing it
1214  // to be emitted into the type declaration/reference inside the compile
1215  // unit.
1216  // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
1217  // FIXME: Handle Using(Shadow?)Decls here to create
1218  // DW_TAG_imported_declarations inside the class for base decls brought into
1219  // derived classes. GDB doesn't seem to notice/leverage these when I tried
1220  // it, so I'm not rushing to fix this. (GCC seems to produce them, if
1221  // referenced)
1222  if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>())
1223  continue;
1224 
1225  if (Method->getType()->getAs<FunctionProtoType>()->getContainedAutoType())
1226  continue;
1227 
1228  // Reuse the existing member function declaration if it exists.
1229  // It may be associated with the declaration of the type & should be
1230  // reused as we're building the definition.
1231  //
1232  // This situation can arise in the vtable-based debug info reduction where
1233  // implicit members are emitted in a non-vtable TU.
1234  auto MI = SPCache.find(Method->getCanonicalDecl());
1235  EltTys.push_back(MI == SPCache.end()
1236  ? CreateCXXMemberFunction(Method, Unit, RecordTy)
1237  : static_cast<llvm::Metadata *>(MI->second));
1238  }
1239 }
1240 
1241 void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
1243  llvm::DIType *RecordTy) {
1244  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1245  for (const auto &BI : RD->bases()) {
1246  unsigned BFlags = 0;
1247  uint64_t BaseOffset;
1248 
1249  const CXXRecordDecl *Base =
1250  cast<CXXRecordDecl>(BI.getType()->getAs<RecordType>()->getDecl());
1251 
1252  if (BI.isVirtual()) {
1253  if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1254  // virtual base offset offset is -ve. The code generator emits dwarf
1255  // expression where it expects +ve number.
1256  BaseOffset = 0 - CGM.getItaniumVTableContext()
1257  .getVirtualBaseOffsetOffset(RD, Base)
1258  .getQuantity();
1259  } else {
1260  // In the MS ABI, store the vbtable offset, which is analogous to the
1261  // vbase offset offset in Itanium.
1262  BaseOffset =
1263  4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base);
1264  }
1265  BFlags = llvm::DINode::FlagVirtual;
1266  } else
1267  BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1268  // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1269  // BI->isVirtual() and bits when not.
1270 
1271  BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
1272  llvm::DIType *DTy = DBuilder.createInheritance(
1273  RecordTy, getOrCreateType(BI.getType(), Unit), BaseOffset, BFlags);
1274  EltTys.push_back(DTy);
1275  }
1276 }
1277 
1278 llvm::DINodeArray
1279 CGDebugInfo::CollectTemplateParams(const TemplateParameterList *TPList,
1281  llvm::DIFile *Unit) {
1282  SmallVector<llvm::Metadata *, 16> TemplateParams;
1283  for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1284  const TemplateArgument &TA = TAList[i];
1285  StringRef Name;
1286  if (TPList)
1287  Name = TPList->getParam(i)->getName();
1288  switch (TA.getKind()) {
1289  case TemplateArgument::Type: {
1290  llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
1291  TemplateParams.push_back(
1292  DBuilder.createTemplateTypeParameter(TheCU, Name, TTy));
1293  } break;
1295  llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
1296  TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1297  TheCU, Name, TTy,
1298  llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
1299  } break;
1301  const ValueDecl *D = TA.getAsDecl();
1303  llvm::DIType *TTy = getOrCreateType(T, Unit);
1304  llvm::Constant *V = nullptr;
1305  const CXXMethodDecl *MD;
1306  // Variable pointer template parameters have a value that is the address
1307  // of the variable.
1308  if (const auto *VD = dyn_cast<VarDecl>(D))
1309  V = CGM.GetAddrOfGlobalVar(VD);
1310  // Member function pointers have special support for building them, though
1311  // this is currently unsupported in LLVM CodeGen.
1312  else if ((MD = dyn_cast<CXXMethodDecl>(D)) && MD->isInstance())
1313  V = CGM.getCXXABI().EmitMemberFunctionPointer(MD);
1314  else if (const auto *FD = dyn_cast<FunctionDecl>(D))
1315  V = CGM.GetAddrOfFunction(FD);
1316  // Member data pointers have special handling too to compute the fixed
1317  // offset within the object.
1318  else if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr())) {
1319  // These five lines (& possibly the above member function pointer
1320  // handling) might be able to be refactored to use similar code in
1321  // CodeGenModule::getMemberPointerConstant
1322  uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1323  CharUnits chars =
1324  CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
1325  V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
1326  }
1327  TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1328  TheCU, Name, TTy,
1329  cast_or_null<llvm::Constant>(V->stripPointerCasts())));
1330  } break;
1332  QualType T = TA.getNullPtrType();
1333  llvm::DIType *TTy = getOrCreateType(T, Unit);
1334  llvm::Constant *V = nullptr;
1335  // Special case member data pointer null values since they're actually -1
1336  // instead of zero.
1337  if (const MemberPointerType *MPT =
1338  dyn_cast<MemberPointerType>(T.getTypePtr()))
1339  // But treat member function pointers as simple zero integers because
1340  // it's easier than having a special case in LLVM's CodeGen. If LLVM
1341  // CodeGen grows handling for values of non-null member function
1342  // pointers then perhaps we could remove this special case and rely on
1343  // EmitNullMemberPointer for member function pointers.
1344  if (MPT->isMemberDataPointer())
1345  V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1346  if (!V)
1347  V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1348  TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1349  TheCU, Name, TTy, cast<llvm::Constant>(V)));
1350  } break;
1352  TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
1353  TheCU, Name, nullptr,
1355  break;
1357  TemplateParams.push_back(DBuilder.createTemplateParameterPack(
1358  TheCU, Name, nullptr,
1359  CollectTemplateParams(nullptr, TA.getPackAsArray(), Unit)));
1360  break;
1362  const Expr *E = TA.getAsExpr();
1363  QualType T = E->getType();
1364  if (E->isGLValue())
1365  T = CGM.getContext().getLValueReferenceType(T);
1366  llvm::Constant *V = CGM.EmitConstantExpr(E, T);
1367  assert(V && "Expression in template argument isn't constant");
1368  llvm::DIType *TTy = getOrCreateType(T, Unit);
1369  TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1370  TheCU, Name, TTy, cast<llvm::Constant>(V->stripPointerCasts())));
1371  } break;
1372  // And the following should never occur:
1375  llvm_unreachable(
1376  "These argument types shouldn't exist in concrete types");
1377  }
1378  }
1379  return DBuilder.getOrCreateArray(TemplateParams);
1380 }
1381 
1382 llvm::DINodeArray
1383 CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
1384  llvm::DIFile *Unit) {
1385  if (FD->getTemplatedKind() ==
1388  ->getTemplate()
1390  return CollectTemplateParams(
1391  TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
1392  }
1393  return llvm::DINodeArray();
1394 }
1395 
1396 llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(
1397  const ClassTemplateSpecializationDecl *TSpecial, llvm::DIFile *Unit) {
1398  // Always get the full list of parameters, not just the ones from
1399  // the specialization.
1400  TemplateParameterList *TPList =
1402  const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
1403  return CollectTemplateParams(TPList, TAList.asArray(), Unit);
1404 }
1405 
1406 llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
1407  if (VTablePtrType)
1408  return VTablePtrType;
1409 
1410  ASTContext &Context = CGM.getContext();
1411 
1412  /* Function type */
1413  llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
1414  llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);
1415  llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements);
1416  unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1417  llvm::DIType *vtbl_ptr_type =
1418  DBuilder.createPointerType(SubTy, Size, 0, "__vtbl_ptr_type");
1419  VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1420  return VTablePtrType;
1421 }
1422 
1423 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1424  // Copy the gdb compatible name on the side and use its reference.
1425  return internString("_vptr$", RD->getNameAsString());
1426 }
1427 
1428 void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
1430  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1431 
1432  // If there is a primary base then it will hold vtable info.
1433  if (RL.getPrimaryBase())
1434  return;
1435 
1436  // If this class is not dynamic then there is not any vtable info to collect.
1437  if (!RD->isDynamicClass())
1438  return;
1439 
1440  unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1441  llvm::DIType *VPTR = DBuilder.createMemberType(
1442  Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
1443  llvm::DINode::FlagArtificial, getOrCreateVTablePtrType(Unit));
1444  EltTys.push_back(VPTR);
1445 }
1446 
1448  SourceLocation Loc) {
1449  assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
1450  llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
1451  return T;
1452 }
1453 
1455  SourceLocation Loc) {
1456  return getOrCreateStandaloneType(D, Loc);
1457 }
1458 
1460  SourceLocation Loc) {
1461  assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
1462  assert(!D.isNull() && "null type");
1463  llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
1464  assert(T && "could not create debug info for type");
1465 
1466  // Composite types with UIDs were already retained by DIBuilder
1467  // because they are only referenced by name in the IR.
1468  if (auto *CTy = dyn_cast<llvm::DICompositeType>(T))
1469  if (!CTy->getIdentifier().empty())
1470  return T;
1471  RetainedTypes.push_back(D.getAsOpaquePtr());
1472  return T;
1473 }
1474 
1476  if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
1477  return;
1478  QualType Ty = CGM.getContext().getEnumType(ED);
1479  void *TyPtr = Ty.getAsOpaquePtr();
1480  auto I = TypeCache.find(TyPtr);
1481  if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl())
1482  return;
1483  llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>());
1484  assert(!Res->isForwardDecl());
1485  TypeCache[TyPtr].reset(Res);
1486 }
1487 
1489  if (DebugKind > CodeGenOptions::LimitedDebugInfo ||
1490  !CGM.getLangOpts().CPlusPlus)
1492 }
1493 
1495  if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
1496  return;
1497 
1498  if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1499  if (CXXDecl->isDynamicClass())
1500  return;
1501 
1502  if (DebugTypeExtRefs && RD->isFromASTFile())
1503  return;
1504 
1505  QualType Ty = CGM.getContext().getRecordType(RD);
1506  llvm::DIType *T = getTypeOrNull(Ty);
1507  if (T && T->isForwardDecl())
1508  completeClassData(RD);
1509 }
1510 
1512  if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
1513  return;
1514  QualType Ty = CGM.getContext().getRecordType(RD);
1515  void *TyPtr = Ty.getAsOpaquePtr();
1516  auto I = TypeCache.find(TyPtr);
1517  if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl())
1518  return;
1519  llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1520  assert(!Res->isForwardDecl());
1521  TypeCache[TyPtr].reset(Res);
1522 }
1523 
1526  for (; I != End; ++I)
1527  if (FunctionDecl *Tmpl = I->getInstantiatedFromMemberFunction())
1528  if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
1529  !I->getMemberSpecializationInfo()->isExplicitSpecialization())
1530  return true;
1531  return false;
1532 }
1533 
1535  bool DebugTypeExtRefs,
1536  const RecordDecl *RD,
1537  const LangOptions &LangOpts) {
1538  // Does the type exist in an imported clang module?
1539  if (DebugTypeExtRefs && RD->isFromASTFile() && RD->getDefinition())
1540  return true;
1541 
1542  if (DebugKind > CodeGenOptions::LimitedDebugInfo)
1543  return false;
1544 
1545  if (!LangOpts.CPlusPlus)
1546  return false;
1547 
1548  if (!RD->isCompleteDefinitionRequired())
1549  return true;
1550 
1551  const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1552 
1553  if (!CXXDecl)
1554  return false;
1555 
1556  if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass())
1557  return true;
1558 
1560  if (const ClassTemplateSpecializationDecl *SD =
1561  dyn_cast<ClassTemplateSpecializationDecl>(RD))
1562  Spec = SD->getSpecializationKind();
1563 
1566  CXXDecl->method_end()))
1567  return true;
1568 
1569  return false;
1570 }
1571 
1572 llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
1573  RecordDecl *RD = Ty->getDecl();
1574  llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
1575  if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
1576  CGM.getLangOpts())) {
1577  if (!T)
1578  T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
1579  return T;
1580  }
1581 
1582  return CreateTypeDefinition(Ty);
1583 }
1584 
1585 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1586  RecordDecl *RD = Ty->getDecl();
1587 
1588  // Get overall information about the record type for the debug info.
1589  llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
1590 
1591  // Records and classes and unions can all be recursive. To handle them, we
1592  // first generate a debug descriptor for the struct as a forward declaration.
1593  // Then (if it is a definition) we go through and get debug info for all of
1594  // its members. Finally, we create a descriptor for the complete type (which
1595  // may refer to the forward decl if the struct is recursive) and replace all
1596  // uses of the forward declaration with the final definition.
1597  llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty, DefUnit);
1598 
1599  const RecordDecl *D = RD->getDefinition();
1600  if (!D || !D->isCompleteDefinition())
1601  return FwdDecl;
1602 
1603  if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1604  CollectContainingType(CXXDecl, FwdDecl);
1605 
1606  // Push the struct on region stack.
1607  LexicalBlockStack.emplace_back(&*FwdDecl);
1608  RegionMap[Ty->getDecl()].reset(FwdDecl);
1609 
1610  // Convert all the elements.
1612  // what about nested types?
1613 
1614  // Note: The split of CXXDecl information here is intentional, the
1615  // gdb tests will depend on a certain ordering at printout. The debug
1616  // information offsets are still correct if we merge them all together
1617  // though.
1618  const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1619  if (CXXDecl) {
1620  CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1621  CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1622  }
1623 
1624  // Collect data fields (including static variables and any initializers).
1625  CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1626  if (CXXDecl)
1627  CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1628 
1629  LexicalBlockStack.pop_back();
1630  RegionMap.erase(Ty->getDecl());
1631 
1632  llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
1633  DBuilder.replaceArrays(FwdDecl, Elements);
1634 
1635  if (FwdDecl->isTemporary())
1636  FwdDecl =
1637  llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
1638 
1639  RegionMap[Ty->getDecl()].reset(FwdDecl);
1640  return FwdDecl;
1641 }
1642 
1643 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1644  llvm::DIFile *Unit) {
1645  // Ignore protocols.
1646  return getOrCreateType(Ty->getBaseType(), Unit);
1647 }
1648 
1649 /// \return true if Getter has the default name for the property PD.
1651  const ObjCMethodDecl *Getter) {
1652  assert(PD);
1653  if (!Getter)
1654  return true;
1655 
1656  assert(Getter->getDeclName().isObjCZeroArgSelector());
1657  return PD->getName() ==
1659 }
1660 
1661 /// \return true if Setter has the default name for the property PD.
1663  const ObjCMethodDecl *Setter) {
1664  assert(PD);
1665  if (!Setter)
1666  return true;
1667 
1668  assert(Setter->getDeclName().isObjCOneArgSelector());
1671 }
1672 
1673 llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1674  llvm::DIFile *Unit) {
1675  ObjCInterfaceDecl *ID = Ty->getDecl();
1676  if (!ID)
1677  return nullptr;
1678 
1679  // Return a forward declaration if this type was imported from a clang module.
1680  if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition())
1681  return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
1682  ID->getName(),
1683  getDeclContextDescriptor(ID), Unit, 0);
1684 
1685  // Get overall information about the record type for the debug info.
1686  llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
1687  unsigned Line = getLineNumber(ID->getLocation());
1688  auto RuntimeLang =
1689  static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
1690 
1691  // If this is just a forward declaration return a special forward-declaration
1692  // debug type since we won't be able to lay out the entire type.
1693  ObjCInterfaceDecl *Def = ID->getDefinition();
1694  if (!Def || !Def->getImplementation()) {
1695  llvm::DIScope *Mod = getParentModuleOrNull(ID);
1696  llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
1697  llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU,
1698  DefUnit, Line, RuntimeLang);
1699  ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
1700  return FwdDecl;
1701  }
1702 
1703  return CreateTypeDefinition(Ty, Unit);
1704 }
1705 
1706 llvm::DIModule *
1707 CGDebugInfo::getOrCreateModuleRef(ExternalASTSource::ASTSourceDescriptor Mod,
1708  bool CreateSkeletonCU) {
1709  // Use the Module pointer as the key into the cache. This is a
1710  // nullptr if the "Module" is a PCH, which is safe because we don't
1711  // support chained PCH debug info, so there can only be a single PCH.
1712  const Module *M = Mod.getModuleOrNull();
1713  auto ModRef = ModuleCache.find(M);
1714  if (ModRef != ModuleCache.end())
1715  return cast<llvm::DIModule>(ModRef->second);
1716 
1717  // Macro definitions that were defined with "-D" on the command line.
1718  SmallString<128> ConfigMacros;
1719  {
1720  llvm::raw_svector_ostream OS(ConfigMacros);
1721  const auto &PPOpts = CGM.getPreprocessorOpts();
1722  unsigned I = 0;
1723  // Translate the macro definitions back into a commmand line.
1724  for (auto &M : PPOpts.Macros) {
1725  if (++I > 1)
1726  OS << " ";
1727  const std::string &Macro = M.first;
1728  bool Undef = M.second;
1729  OS << "\"-" << (Undef ? 'U' : 'D');
1730  for (char c : Macro)
1731  switch (c) {
1732  case '\\' : OS << "\\\\"; break;
1733  case '"' : OS << "\\\""; break;
1734  default: OS << c;
1735  }
1736  OS << '\"';
1737  }
1738  }
1739 
1740  bool IsRootModule = M ? !M->Parent : true;
1741  if (CreateSkeletonCU && IsRootModule) {
1742  llvm::DIBuilder DIB(CGM.getModule());
1743  DIB.createCompileUnit(TheCU->getSourceLanguage(), Mod.getModuleName(),
1744  Mod.getPath(), TheCU->getProducer(), true,
1745  StringRef(), 0, Mod.getASTFile(),
1746  llvm::DIBuilder::FullDebug, Mod.getSignature());
1747  DIB.finalize();
1748  }
1749  llvm::DIModule *Parent =
1750  IsRootModule ? nullptr
1751  : getOrCreateModuleRef(
1753  CreateSkeletonCU);
1754  llvm::DIModule *DIMod =
1755  DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
1756  Mod.getPath(), CGM.getHeaderSearchOpts().Sysroot);
1757  ModuleCache[M].reset(DIMod);
1758  return DIMod;
1759 }
1760 
1761 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
1762  llvm::DIFile *Unit) {
1763  ObjCInterfaceDecl *ID = Ty->getDecl();
1764  llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
1765  unsigned Line = getLineNumber(ID->getLocation());
1766  unsigned RuntimeLang = TheCU->getSourceLanguage();
1767 
1768  // Bit size, align and offset of the type.
1769  uint64_t Size = CGM.getContext().getTypeSize(Ty);
1770  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1771 
1772  unsigned Flags = 0;
1773  if (ID->getImplementation())
1774  Flags |= llvm::DINode::FlagObjcClassComplete;
1775 
1776  llvm::DIScope *Mod = getParentModuleOrNull(ID);
1777  llvm::DICompositeType *RealDecl = DBuilder.createStructType(
1778  Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags,
1779  nullptr, llvm::DINodeArray(), RuntimeLang);
1780 
1781  QualType QTy(Ty, 0);
1782  TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
1783 
1784  // Push the struct on region stack.
1785  LexicalBlockStack.emplace_back(RealDecl);
1786  RegionMap[Ty->getDecl()].reset(RealDecl);
1787 
1788  // Convert all the elements.
1790 
1791  ObjCInterfaceDecl *SClass = ID->getSuperClass();
1792  if (SClass) {
1793  llvm::DIType *SClassTy =
1794  getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1795  if (!SClassTy)
1796  return nullptr;
1797 
1798  llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1799  EltTys.push_back(InhTag);
1800  }
1801 
1802  // Create entries for all of the properties.
1803  auto AddProperty = [&](const ObjCPropertyDecl *PD) {
1804  SourceLocation Loc = PD->getLocation();
1805  llvm::DIFile *PUnit = getOrCreateFile(Loc);
1806  unsigned PLine = getLineNumber(Loc);
1807  ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1808  ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1809  llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
1810  PD->getName(), PUnit, PLine,
1811  hasDefaultGetterName(PD, Getter) ? ""
1812  : getSelectorName(PD->getGetterName()),
1813  hasDefaultSetterName(PD, Setter) ? ""
1814  : getSelectorName(PD->getSetterName()),
1815  PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
1816  EltTys.push_back(PropertyNode);
1817  };
1818  {
1819  llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
1820  for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
1821  for (auto *PD : ClassExt->properties()) {
1822  PropertySet.insert(PD->getIdentifier());
1823  AddProperty(PD);
1824  }
1825  for (const auto *PD : ID->properties()) {
1826  // Don't emit duplicate metadata for properties that were already in a
1827  // class extension.
1828  if (!PropertySet.insert(PD->getIdentifier()).second)
1829  continue;
1830  AddProperty(PD);
1831  }
1832  }
1833 
1835  unsigned FieldNo = 0;
1836  for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1837  Field = Field->getNextIvar(), ++FieldNo) {
1838  llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
1839  if (!FieldTy)
1840  return nullptr;
1841 
1842  StringRef FieldName = Field->getName();
1843 
1844  // Ignore unnamed fields.
1845  if (FieldName.empty())
1846  continue;
1847 
1848  // Get the location for the field.
1849  llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
1850  unsigned FieldLine = getLineNumber(Field->getLocation());
1851  QualType FType = Field->getType();
1852  uint64_t FieldSize = 0;
1853  unsigned FieldAlign = 0;
1854 
1855  if (!FType->isIncompleteArrayType()) {
1856 
1857  // Bit size, align and offset of the type.
1858  FieldSize = Field->isBitField()
1859  ? Field->getBitWidthValue(CGM.getContext())
1860  : CGM.getContext().getTypeSize(FType);
1861  FieldAlign = CGM.getContext().getTypeAlign(FType);
1862  }
1863 
1864  uint64_t FieldOffset;
1865  if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1866  // We don't know the runtime offset of an ivar if we're using the
1867  // non-fragile ABI. For bitfields, use the bit offset into the first
1868  // byte of storage of the bitfield. For other fields, use zero.
1869  if (Field->isBitField()) {
1870  FieldOffset =
1871  CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
1872  FieldOffset %= CGM.getContext().getCharWidth();
1873  } else {
1874  FieldOffset = 0;
1875  }
1876  } else {
1877  FieldOffset = RL.getFieldOffset(FieldNo);
1878  }
1879 
1880  unsigned Flags = 0;
1881  if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1882  Flags = llvm::DINode::FlagProtected;
1883  else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1884  Flags = llvm::DINode::FlagPrivate;
1885  else if (Field->getAccessControl() == ObjCIvarDecl::Public)
1886  Flags = llvm::DINode::FlagPublic;
1887 
1888  llvm::MDNode *PropertyNode = nullptr;
1889  if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
1890  if (ObjCPropertyImplDecl *PImpD =
1891  ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1892  if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
1893  SourceLocation Loc = PD->getLocation();
1894  llvm::DIFile *PUnit = getOrCreateFile(Loc);
1895  unsigned PLine = getLineNumber(Loc);
1896  ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1897  ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1898  PropertyNode = DBuilder.createObjCProperty(
1899  PD->getName(), PUnit, PLine,
1900  hasDefaultGetterName(PD, Getter) ? "" : getSelectorName(
1901  PD->getGetterName()),
1902  hasDefaultSetterName(PD, Setter) ? "" : getSelectorName(
1903  PD->getSetterName()),
1904  PD->getPropertyAttributes(),
1905  getOrCreateType(PD->getType(), PUnit));
1906  }
1907  }
1908  }
1909  FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
1910  FieldSize, FieldAlign, FieldOffset, Flags,
1911  FieldTy, PropertyNode);
1912  EltTys.push_back(FieldTy);
1913  }
1914 
1915  llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
1916  DBuilder.replaceArrays(RealDecl, Elements);
1917 
1918  LexicalBlockStack.pop_back();
1919  return RealDecl;
1920 }
1921 
1922 llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
1923  llvm::DIFile *Unit) {
1924  llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1925  int64_t Count = Ty->getNumElements();
1926  if (Count == 0)
1927  // If number of elements are not known then this is an unbounded array.
1928  // Use Count == -1 to express such arrays.
1929  Count = -1;
1930 
1931  llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1932  llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1933 
1934  uint64_t Size = CGM.getContext().getTypeSize(Ty);
1935  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1936 
1937  return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1938 }
1939 
1940 llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
1941  uint64_t Size;
1942  uint64_t Align;
1943 
1944  // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1945  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1946  Size = 0;
1947  Align =
1949  } else if (Ty->isIncompleteArrayType()) {
1950  Size = 0;
1951  if (Ty->getElementType()->isIncompleteType())
1952  Align = 0;
1953  else
1954  Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1955  } else if (Ty->isIncompleteType()) {
1956  Size = 0;
1957  Align = 0;
1958  } else {
1959  // Size and align of the whole array, not the element type.
1960  Size = CGM.getContext().getTypeSize(Ty);
1961  Align = CGM.getContext().getTypeAlign(Ty);
1962  }
1963 
1964  // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1965  // interior arrays, do we care? Why aren't nested arrays represented the
1966  // obvious/recursive way?
1968  QualType EltTy(Ty, 0);
1969  while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1970  // If the number of elements is known, then count is that number. Otherwise,
1971  // it's -1. This allows us to represent a subrange with an array of 0
1972  // elements, like this:
1973  //
1974  // struct foo {
1975  // int x[0];
1976  // };
1977  int64_t Count = -1; // Count == -1 is an unbounded array.
1978  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1979  Count = CAT->getSize().getZExtValue();
1980 
1981  // FIXME: Verify this is right for VLAs.
1982  Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1983  EltTy = Ty->getElementType();
1984  }
1985 
1986  llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1987 
1988  return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1989  SubscriptArray);
1990 }
1991 
1992 llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1993  llvm::DIFile *Unit) {
1994  return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
1995  Ty->getPointeeType(), Unit);
1996 }
1997 
1998 llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1999  llvm::DIFile *Unit) {
2000  return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, Ty,
2001  Ty->getPointeeType(), Unit);
2002 }
2003 
2004 llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
2005  llvm::DIFile *U) {
2006  uint64_t Size =
2007  !Ty->isIncompleteType() ? CGM.getContext().getTypeSize(Ty) : 0;
2008  llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
2009  if (Ty->isMemberDataPointerType())
2010  return DBuilder.createMemberPointerType(
2011  getOrCreateType(Ty->getPointeeType(), U), ClassType, Size);
2012 
2013  const FunctionProtoType *FPT =
2015  return DBuilder.createMemberPointerType(
2016  getOrCreateInstanceMethodType(CGM.getContext().getPointerType(QualType(
2017  Ty->getClass(), FPT->getTypeQuals())),
2018  FPT, U),
2019  ClassType, Size);
2020 }
2021 
2022 llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
2023  // Ignore the atomic wrapping
2024  // FIXME: What is the correct representation?
2025  return getOrCreateType(Ty->getValueType(), U);
2026 }
2027 
2028 llvm::DIType* CGDebugInfo::CreateType(const PipeType *Ty,
2029  llvm::DIFile *U) {
2030  return getOrCreateType(Ty->getElementType(), U);
2031 }
2032 
2033 llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
2034  const EnumDecl *ED = Ty->getDecl();
2035 
2036  uint64_t Size = 0;
2037  uint64_t Align = 0;
2038  if (!ED->getTypeForDecl()->isIncompleteType()) {
2039  Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
2040  Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
2041  }
2042 
2043  SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2044 
2045  bool isImportedFromModule =
2046  DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition();
2047 
2048  // If this is just a forward declaration, construct an appropriately
2049  // marked node and just return it.
2050  if (isImportedFromModule || !ED->getDefinition()) {
2051  llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
2052  llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
2053  unsigned Line = getLineNumber(ED->getLocation());
2054  StringRef EDName = ED->getName();
2055  llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
2056  llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
2057  0, Size, Align, llvm::DINode::FlagFwdDecl, FullName);
2058  ReplaceMap.emplace_back(
2059  std::piecewise_construct, std::make_tuple(Ty),
2060  std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
2061  return RetTy;
2062  }
2063 
2064  return CreateTypeDefinition(Ty);
2065 }
2066 
2067 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
2068  const EnumDecl *ED = Ty->getDecl();
2069  uint64_t Size = 0;
2070  uint64_t Align = 0;
2071  if (!ED->getTypeForDecl()->isIncompleteType()) {
2072  Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
2073  Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
2074  }
2075 
2076  SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2077 
2078  // Create elements for each enumerator.
2080  ED = ED->getDefinition();
2081  for (const auto *Enum : ED->enumerators()) {
2082  Enumerators.push_back(DBuilder.createEnumerator(
2083  Enum->getName(), Enum->getInitVal().getSExtValue()));
2084  }
2085 
2086  // Return a CompositeType for the enum itself.
2087  llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
2088 
2089  llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
2090  unsigned Line = getLineNumber(ED->getLocation());
2091  llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
2092  llvm::DIType *ClassTy =
2093  ED->isFixed() ? getOrCreateType(ED->getIntegerType(), DefUnit) : nullptr;
2094  return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit,
2095  Line, Size, Align, EltArray, ClassTy,
2096  FullName);
2097 }
2098 
2100  Qualifiers Quals;
2101  do {
2102  Qualifiers InnerQuals = T.getLocalQualifiers();
2103  // Qualifiers::operator+() doesn't like it if you add a Qualifier
2104  // that is already there.
2105  Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
2106  Quals += InnerQuals;
2107  QualType LastT = T;
2108  switch (T->getTypeClass()) {
2109  default:
2110  return C.getQualifiedType(T.getTypePtr(), Quals);
2111  case Type::TemplateSpecialization: {
2112  const auto *Spec = cast<TemplateSpecializationType>(T);
2113  if (Spec->isTypeAlias())
2114  return C.getQualifiedType(T.getTypePtr(), Quals);
2115  T = Spec->desugar();
2116  break;
2117  }
2118  case Type::TypeOfExpr:
2119  T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
2120  break;
2121  case Type::TypeOf:
2122  T = cast<TypeOfType>(T)->getUnderlyingType();
2123  break;
2124  case Type::Decltype:
2125  T = cast<DecltypeType>(T)->getUnderlyingType();
2126  break;
2127  case Type::UnaryTransform:
2128  T = cast<UnaryTransformType>(T)->getUnderlyingType();
2129  break;
2130  case Type::Attributed:
2131  T = cast<AttributedType>(T)->getEquivalentType();
2132  break;
2133  case Type::Elaborated:
2134  T = cast<ElaboratedType>(T)->getNamedType();
2135  break;
2136  case Type::Paren:
2137  T = cast<ParenType>(T)->getInnerType();
2138  break;
2139  case Type::SubstTemplateTypeParm:
2140  T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
2141  break;
2142  case Type::Auto:
2143  QualType DT = cast<AutoType>(T)->getDeducedType();
2144  assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
2145  T = DT;
2146  break;
2147  }
2148 
2149  assert(T != LastT && "Type unwrapping failed to unwrap!");
2150  (void)LastT;
2151  } while (true);
2152 }
2153 
2154 llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
2155 
2156  // Unwrap the type as needed for debug information.
2157  Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2158 
2159  auto it = TypeCache.find(Ty.getAsOpaquePtr());
2160  if (it != TypeCache.end()) {
2161  // Verify that the debug info still exists.
2162  if (llvm::Metadata *V = it->second)
2163  return cast<llvm::DIType>(V);
2164  }
2165 
2166  return nullptr;
2167 }
2168 
2170  const ClassTemplateSpecializationDecl &SD) {
2171  if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2172  return;
2173 
2174  completeClassData(&SD);
2175  // In case this type has no member function definitions being emitted, ensure
2176  // it is retained
2177  RetainedTypes.push_back(CGM.getContext().getRecordType(&SD).getAsOpaquePtr());
2178 }
2179 
2180 llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
2181  if (Ty.isNull())
2182  return nullptr;
2183 
2184  // Unwrap the type as needed for debug information.
2185  Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2186 
2187  if (auto *T = getTypeOrNull(Ty))
2188  return T;
2189 
2190  llvm::DIType *Res = CreateTypeNode(Ty, Unit);
2191  void* TyPtr = Ty.getAsOpaquePtr();
2192 
2193  // And update the type cache.
2194  TypeCache[TyPtr].reset(Res);
2195 
2196  return Res;
2197 }
2198 
2199 llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
2200  // A forward declaration inside a module header does not belong to the module.
2201  if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition())
2202  return nullptr;
2203  if (DebugTypeExtRefs && D->isFromASTFile()) {
2204  // Record a reference to an imported clang module or precompiled header.
2205  auto *Reader = CGM.getContext().getExternalSource();
2206  auto Idx = D->getOwningModuleID();
2207  auto Info = Reader->getSourceDescriptor(Idx);
2208  if (Info)
2209  return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
2210  } else if (ClangModuleMap) {
2211  // We are building a clang module or a precompiled header.
2212  //
2213  // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
2214  // and it wouldn't be necessary to specify the parent scope
2215  // because the type is already unique by definition (it would look
2216  // like the output of -fno-standalone-debug). On the other hand,
2217  // the parent scope helps a consumer to quickly locate the object
2218  // file where the type's definition is located, so it might be
2219  // best to make this behavior a command line or debugger tuning
2220  // option.
2222  if (Module *M = ClangModuleMap->inferModuleFromLocation(Loc)) {
2224  return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
2225  }
2226  }
2227 
2228  return nullptr;
2229 }
2230 
2231 llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
2232  // Handle qualifiers, which recursively handles what they refer to.
2233  if (Ty.hasLocalQualifiers())
2234  return CreateQualifiedType(Ty, Unit);
2235 
2236  // Work out details of type.
2237  switch (Ty->getTypeClass()) {
2238 #define TYPE(Class, Base)
2239 #define ABSTRACT_TYPE(Class, Base)
2240 #define NON_CANONICAL_TYPE(Class, Base)
2241 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2242 #include "clang/AST/TypeNodes.def"
2243  llvm_unreachable("Dependent types cannot show up in debug information");
2244 
2245  case Type::ExtVector:
2246  case Type::Vector:
2247  return CreateType(cast<VectorType>(Ty), Unit);
2248  case Type::ObjCObjectPointer:
2249  return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2250  case Type::ObjCObject:
2251  return CreateType(cast<ObjCObjectType>(Ty), Unit);
2252  case Type::ObjCInterface:
2253  return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2254  case Type::Builtin:
2255  return CreateType(cast<BuiltinType>(Ty));
2256  case Type::Complex:
2257  return CreateType(cast<ComplexType>(Ty));
2258  case Type::Pointer:
2259  return CreateType(cast<PointerType>(Ty), Unit);
2260  case Type::Adjusted:
2261  case Type::Decayed:
2262  // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
2263  return CreateType(
2264  cast<PointerType>(cast<AdjustedType>(Ty)->getAdjustedType()), Unit);
2265  case Type::BlockPointer:
2266  return CreateType(cast<BlockPointerType>(Ty), Unit);
2267  case Type::Typedef:
2268  return CreateType(cast<TypedefType>(Ty), Unit);
2269  case Type::Record:
2270  return CreateType(cast<RecordType>(Ty));
2271  case Type::Enum:
2272  return CreateEnumType(cast<EnumType>(Ty));
2273  case Type::FunctionProto:
2274  case Type::FunctionNoProto:
2275  return CreateType(cast<FunctionType>(Ty), Unit);
2276  case Type::ConstantArray:
2277  case Type::VariableArray:
2278  case Type::IncompleteArray:
2279  return CreateType(cast<ArrayType>(Ty), Unit);
2280 
2281  case Type::LValueReference:
2282  return CreateType(cast<LValueReferenceType>(Ty), Unit);
2283  case Type::RValueReference:
2284  return CreateType(cast<RValueReferenceType>(Ty), Unit);
2285 
2286  case Type::MemberPointer:
2287  return CreateType(cast<MemberPointerType>(Ty), Unit);
2288 
2289  case Type::Atomic:
2290  return CreateType(cast<AtomicType>(Ty), Unit);
2291 
2292  case Type::Pipe:
2293  return CreateType(cast<PipeType>(Ty), Unit);
2294 
2295  case Type::TemplateSpecialization:
2296  return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
2297 
2298  case Type::Auto:
2299  case Type::Attributed:
2300  case Type::Elaborated:
2301  case Type::Paren:
2302  case Type::SubstTemplateTypeParm:
2303  case Type::TypeOfExpr:
2304  case Type::TypeOf:
2305  case Type::Decltype:
2306  case Type::UnaryTransform:
2307  case Type::PackExpansion:
2308  break;
2309  }
2310 
2311  llvm_unreachable("type should have been unwrapped!");
2312 }
2313 
2314 llvm::DICompositeType *CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
2315  llvm::DIFile *Unit) {
2316  QualType QTy(Ty, 0);
2317 
2318  auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
2319 
2320  // We may have cached a forward decl when we could have created
2321  // a non-forward decl. Go ahead and create a non-forward decl
2322  // now.
2323  if (T && !T->isForwardDecl())
2324  return T;
2325 
2326  // Otherwise create the type.
2327  llvm::DICompositeType *Res = CreateLimitedType(Ty);
2328 
2329  // Propagate members from the declaration to the definition
2330  // CreateType(const RecordType*) will overwrite this with the members in the
2331  // correct order if the full type is needed.
2332  DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
2333 
2334  // And update the type cache.
2335  TypeCache[QTy.getAsOpaquePtr()].reset(Res);
2336  return Res;
2337 }
2338 
2339 // TODO: Currently used for context chains when limiting debug info.
2340 llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2341  RecordDecl *RD = Ty->getDecl();
2342 
2343  // Get overall information about the record type for the debug info.
2344  llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
2345  unsigned Line = getLineNumber(RD->getLocation());
2346  StringRef RDName = getClassName(RD);
2347 
2348  llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
2349 
2350  // If we ended up creating the type during the context chain construction,
2351  // just return that.
2352  auto *T = cast_or_null<llvm::DICompositeType>(
2353  getTypeOrNull(CGM.getContext().getRecordType(RD)));
2354  if (T && (!T->isForwardDecl() || !RD->getDefinition()))
2355  return T;
2356 
2357  // If this is just a forward or incomplete declaration, construct an
2358  // appropriately marked node and just return it.
2359  const RecordDecl *D = RD->getDefinition();
2360  if (!D || !D->isCompleteDefinition())
2361  return getOrCreateRecordFwdDecl(Ty, RDContext);
2362 
2363  uint64_t Size = CGM.getContext().getTypeSize(Ty);
2364  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
2365 
2366  SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2367 
2368  llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
2369  getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align, 0,
2370  FullName);
2371 
2372  RegionMap[Ty->getDecl()].reset(RealDecl);
2373  TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
2374 
2375  if (const ClassTemplateSpecializationDecl *TSpecial =
2376  dyn_cast<ClassTemplateSpecializationDecl>(RD))
2377  DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
2378  CollectCXXTemplateParams(TSpecial, DefUnit));
2379  return RealDecl;
2380 }
2381 
2382 void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2383  llvm::DICompositeType *RealDecl) {
2384  // A class's primary base or the class itself contains the vtable.
2385  llvm::DICompositeType *ContainingType = nullptr;
2386  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2387  if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2388  // Seek non-virtual primary base root.
2389  while (1) {
2390  const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2391  const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2392  if (PBT && !BRL.isPrimaryBaseVirtual())
2393  PBase = PBT;
2394  else
2395  break;
2396  }
2397  ContainingType = cast<llvm::DICompositeType>(
2398  getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2399  getOrCreateFile(RD->getLocation())));
2400  } else if (RD->isDynamicClass())
2401  ContainingType = RealDecl;
2402 
2403  DBuilder.replaceVTableHolder(RealDecl, ContainingType);
2404 }
2405 
2406 llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
2407  StringRef Name, uint64_t *Offset) {
2408  llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2409  uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2410  unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2411  llvm::DIType *Ty = DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize,
2412  FieldAlign, *Offset, 0, FieldTy);
2413  *Offset += FieldSize;
2414  return Ty;
2415 }
2416 
2417 void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
2418  StringRef &Name,
2419  StringRef &LinkageName,
2420  llvm::DIScope *&FDContext,
2421  llvm::DINodeArray &TParamsArray,
2422  unsigned &Flags) {
2423  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2424  Name = getFunctionName(FD);
2425  // Use mangled name as linkage name for C/C++ functions.
2426  if (FD->hasPrototype()) {
2427  LinkageName = CGM.getMangledName(GD);
2428  Flags |= llvm::DINode::FlagPrototyped;
2429  }
2430  // No need to replicate the linkage name if it isn't different from the
2431  // subprogram name, no need to have it at all unless coverage is enabled or
2432  // debug is set to more than just line tables.
2433  if (LinkageName == Name ||
2434  (!CGM.getCodeGenOpts().EmitGcovArcs &&
2435  !CGM.getCodeGenOpts().EmitGcovNotes &&
2437  LinkageName = StringRef();
2438 
2439  if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
2440  if (const NamespaceDecl *NSDecl =
2441  dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2442  FDContext = getOrCreateNameSpace(NSDecl);
2443  else if (const RecordDecl *RDecl =
2444  dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
2445  llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
2446  FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);
2447  }
2448  // Collect template parameters.
2449  TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2450  }
2451 }
2452 
2453 void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
2454  unsigned &LineNo, QualType &T,
2455  StringRef &Name, StringRef &LinkageName,
2456  llvm::DIScope *&VDContext) {
2457  Unit = getOrCreateFile(VD->getLocation());
2458  LineNo = getLineNumber(VD->getLocation());
2459 
2460  setLocation(VD->getLocation());
2461 
2462  T = VD->getType();
2463  if (T->isIncompleteArrayType()) {
2464  // CodeGen turns int[] into int[1] so we'll do the same here.
2465  llvm::APInt ConstVal(32, 1);
2467 
2468  T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2469  ArrayType::Normal, 0);
2470  }
2471 
2472  Name = VD->getName();
2473  if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
2474  !isa<ObjCMethodDecl>(VD->getDeclContext()))
2475  LinkageName = CGM.getMangledName(VD);
2476  if (LinkageName == Name)
2477  LinkageName = StringRef();
2478 
2479  // Since we emit declarations (DW_AT_members) for static members, place the
2480  // definition of those static members in the namespace they were declared in
2481  // in the source code (the lexical decl context).
2482  // FIXME: Generalize this for even non-member global variables where the
2483  // declaration and definition may have different lexical decl contexts, once
2484  // we have support for emitting declarations of (non-member) global variables.
2485  const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
2486  : VD->getDeclContext();
2487  // When a record type contains an in-line initialization of a static data
2488  // member, and the record type is marked as __declspec(dllexport), an implicit
2489  // definition of the member will be created in the record context. DWARF
2490  // doesn't seem to have a nice way to describe this in a form that consumers
2491  // are likely to understand, so fake the "normal" situation of a definition
2492  // outside the class by putting it in the global scope.
2493  if (DC->isRecord())
2494  DC = CGM.getContext().getTranslationUnitDecl();
2495 
2496  llvm::DIScope *Mod = getParentModuleOrNull(VD);
2497  VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU);
2498 }
2499 
2500 llvm::DISubprogram *
2501 CGDebugInfo::getFunctionForwardDeclaration(const FunctionDecl *FD) {
2502  llvm::DINodeArray TParamsArray;
2503  StringRef Name, LinkageName;
2504  unsigned Flags = 0;
2505  SourceLocation Loc = FD->getLocation();
2506  llvm::DIFile *Unit = getOrCreateFile(Loc);
2507  llvm::DIScope *DContext = Unit;
2508  unsigned Line = getLineNumber(Loc);
2509 
2510  collectFunctionDeclProps(FD, Unit, Name, LinkageName, DContext,
2511  TParamsArray, Flags);
2512  // Build function type.
2513  SmallVector<QualType, 16> ArgTypes;
2514  for (const ParmVarDecl *Parm: FD->parameters())
2515  ArgTypes.push_back(Parm->getType());
2516  QualType FnType =
2517  CGM.getContext().getFunctionType(FD->getReturnType(), ArgTypes,
2519  llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
2520  DContext, Name, LinkageName, Unit, Line,
2521  getOrCreateFunctionType(FD, FnType, Unit), !FD->isExternallyVisible(),
2522  /* isDefinition = */ false, 0, Flags, CGM.getLangOpts().Optimize,
2523  TParamsArray.get(), getFunctionDeclaration(FD));
2524  const FunctionDecl *CanonDecl = cast<FunctionDecl>(FD->getCanonicalDecl());
2525  FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
2526  std::make_tuple(CanonDecl),
2527  std::make_tuple(SP));
2528  return SP;
2529 }
2530 
2531 llvm::DIGlobalVariable *
2532 CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
2533  QualType T;
2534  StringRef Name, LinkageName;
2535  SourceLocation Loc = VD->getLocation();
2536  llvm::DIFile *Unit = getOrCreateFile(Loc);
2537  llvm::DIScope *DContext = Unit;
2538  unsigned Line = getLineNumber(Loc);
2539 
2540  collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, DContext);
2541  auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
2542  DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
2543  !VD->isExternallyVisible(), nullptr, nullptr);
2544  FwdDeclReplaceMap.emplace_back(
2545  std::piecewise_construct,
2546  std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
2547  std::make_tuple(static_cast<llvm::Metadata *>(GV)));
2548  return GV;
2549 }
2550 
2551 llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2552  // We only need a declaration (not a definition) of the type - so use whatever
2553  // we would otherwise do to get a type for a pointee. (forward declarations in
2554  // limited debug info, full definitions (if the type definition is available)
2555  // in unlimited debug info)
2556  if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
2557  return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
2558  getOrCreateFile(TD->getLocation()));
2559  auto I = DeclCache.find(D->getCanonicalDecl());
2560 
2561  if (I != DeclCache.end())
2562  return dyn_cast_or_null<llvm::DINode>(I->second);
2563 
2564  // No definition for now. Emit a forward definition that might be
2565  // merged with a potential upcoming definition.
2566  if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
2567  return getFunctionForwardDeclaration(FD);
2568  else if (const auto *VD = dyn_cast<VarDecl>(D))
2569  return getGlobalVariableForwardDeclaration(VD);
2570 
2571  return nullptr;
2572 }
2573 
2574 llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
2575  if (!D || DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2576  return nullptr;
2577 
2578  const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2579  if (!FD)
2580  return nullptr;
2581 
2582  // Setup context.
2583  auto *S = getDeclContextDescriptor(D);
2584 
2585  auto MI = SPCache.find(FD->getCanonicalDecl());
2586  if (MI == SPCache.end()) {
2587  if (const CXXMethodDecl *MD =
2588  dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
2589  return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
2590  cast<llvm::DICompositeType>(S));
2591  }
2592  }
2593  if (MI != SPCache.end()) {
2594  auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
2595  if (SP && !SP->isDefinition())
2596  return SP;
2597  }
2598 
2599  for (auto NextFD : FD->redecls()) {
2600  auto MI = SPCache.find(NextFD->getCanonicalDecl());
2601  if (MI != SPCache.end()) {
2602  auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
2603  if (SP && !SP->isDefinition())
2604  return SP;
2605  }
2606  }
2607  return nullptr;
2608 }
2609 
2610 // getOrCreateFunctionType - Construct type. If it is a c++ method, include
2611 // implicit parameter "this".
2612 llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2613  QualType FnType,
2614  llvm::DIFile *F) {
2615  if (!D || DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2616  // Create fake but valid subroutine type. Otherwise -verify would fail, and
2617  // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
2618  return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray(None));
2619 
2620  if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2621  return getOrCreateMethodType(Method, F);
2622  if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2623  // Add "self" and "_cmd"
2625 
2626  // First element is always return type. For 'void' functions it is NULL.
2627  QualType ResultTy = OMethod->getReturnType();
2628 
2629  // Replace the instancetype keyword with the actual type.
2630  if (ResultTy == CGM.getContext().getObjCInstanceType())
2631  ResultTy = CGM.getContext().getPointerType(
2632  QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2633 
2634  Elts.push_back(getOrCreateType(ResultTy, F));
2635  // "self" pointer is always first argument.
2636  QualType SelfDeclTy;
2637  if (auto *SelfDecl = OMethod->getSelfDecl())
2638  SelfDeclTy = SelfDecl->getType();
2639  else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
2640  if (FPT->getNumParams() > 1)
2641  SelfDeclTy = FPT->getParamType(0);
2642  if (!SelfDeclTy.isNull())
2643  Elts.push_back(CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
2644  // "_cmd" pointer is always second argument.
2645  Elts.push_back(DBuilder.createArtificialType(
2646  getOrCreateType(CGM.getContext().getObjCSelType(), F)));
2647  // Get rest of the arguments.
2648  for (const auto *PI : OMethod->params())
2649  Elts.push_back(getOrCreateType(PI->getType(), F));
2650  // Variadic methods need a special marker at the end of the type list.
2651  if (OMethod->isVariadic())
2652  Elts.push_back(DBuilder.createUnspecifiedParameter());
2653 
2654  llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
2655  return DBuilder.createSubroutineType(EltTypeArray);
2656  }
2657 
2658  // Handle variadic function types; they need an additional
2659  // unspecified parameter.
2660  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2661  if (FD->isVariadic()) {
2663  EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
2664  if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FnType))
2665  for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
2666  EltTys.push_back(getOrCreateType(FPT->getParamType(i), F));
2667  EltTys.push_back(DBuilder.createUnspecifiedParameter());
2668  llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
2669  return DBuilder.createSubroutineType(EltTypeArray);
2670  }
2671 
2672  return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
2673 }
2674 
2676  SourceLocation ScopeLoc, QualType FnType,
2677  llvm::Function *Fn, CGBuilderTy &Builder) {
2678 
2679  StringRef Name;
2680  StringRef LinkageName;
2681 
2682  FnBeginRegionCount.push_back(LexicalBlockStack.size());
2683 
2684  const Decl *D = GD.getDecl();
2685  bool HasDecl = (D != nullptr);
2686 
2687  unsigned Flags = 0;
2688  llvm::DIFile *Unit = getOrCreateFile(Loc);
2689  llvm::DIScope *FDContext = Unit;
2690  llvm::DINodeArray TParamsArray;
2691  if (!HasDecl) {
2692  // Use llvm function name.
2693  LinkageName = Fn->getName();
2694  } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2695  // If there is a subprogram for this function available then use it.
2696  auto FI = SPCache.find(FD->getCanonicalDecl());
2697  if (FI != SPCache.end()) {
2698  auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
2699  if (SP && SP->isDefinition()) {
2700  LexicalBlockStack.emplace_back(SP);
2701  RegionMap[D].reset(SP);
2702  return;
2703  }
2704  }
2705  collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
2706  TParamsArray, Flags);
2707  } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2708  Name = getObjCMethodName(OMD);
2709  Flags |= llvm::DINode::FlagPrototyped;
2710  } else {
2711  // Use llvm function name.
2712  Name = Fn->getName();
2713  Flags |= llvm::DINode::FlagPrototyped;
2714  }
2715  if (!Name.empty() && Name[0] == '\01')
2716  Name = Name.substr(1);
2717 
2718  if (!HasDecl || D->isImplicit()) {
2719  Flags |= llvm::DINode::FlagArtificial;
2720  // Artificial functions without a location should not silently reuse CurLoc.
2721  if (Loc.isInvalid())
2722  CurLoc = SourceLocation();
2723  }
2724  unsigned LineNo = getLineNumber(Loc);
2725  unsigned ScopeLine = getLineNumber(ScopeLoc);
2726 
2727  // FIXME: The function declaration we're constructing here is mostly reusing
2728  // declarations from CXXMethodDecl and not constructing new ones for arbitrary
2729  // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
2730  // all subprograms instead of the actual context since subprogram definitions
2731  // are emitted as CU level entities by the backend.
2732  llvm::DISubprogram *SP = DBuilder.createFunction(
2733  FDContext, Name, LinkageName, Unit, LineNo,
2734  getOrCreateFunctionType(D, FnType, Unit), Fn->hasInternalLinkage(),
2735  true /*definition*/, ScopeLine, Flags, CGM.getLangOpts().Optimize,
2736  TParamsArray.get(), getFunctionDeclaration(D));
2737  Fn->setSubprogram(SP);
2738  // We might get here with a VarDecl in the case we're generating
2739  // code for the initialization of globals. Do not record these decls
2740  // as they will overwrite the actual VarDecl Decl in the cache.
2741  if (HasDecl && isa<FunctionDecl>(D))
2742  DeclCache[D->getCanonicalDecl()].reset(static_cast<llvm::Metadata *>(SP));
2743 
2744  // Push the function onto the lexical block stack.
2745  LexicalBlockStack.emplace_back(SP);
2746 
2747  if (HasDecl)
2748  RegionMap[D].reset(SP);
2749 }
2750 
2752  QualType FnType) {
2753  StringRef Name;
2754  StringRef LinkageName;
2755 
2756  const Decl *D = GD.getDecl();
2757  if (!D)
2758  return;
2759 
2760  unsigned Flags = 0;
2761  llvm::DIFile *Unit = getOrCreateFile(Loc);
2762  llvm::DIScope *FDContext = getDeclContextDescriptor(D);
2763  llvm::DINodeArray TParamsArray;
2764  if (isa<FunctionDecl>(D)) {
2765  // If there is a DISubprogram for this function available then use it.
2766  collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
2767  TParamsArray, Flags);
2768  } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2769  Name = getObjCMethodName(OMD);
2770  Flags |= llvm::DINode::FlagPrototyped;
2771  } else {
2772  llvm_unreachable("not a function or ObjC method");
2773  }
2774  if (!Name.empty() && Name[0] == '\01')
2775  Name = Name.substr(1);
2776 
2777  if (D->isImplicit()) {
2778  Flags |= llvm::DINode::FlagArtificial;
2779  // Artificial functions without a location should not silently reuse CurLoc.
2780  if (Loc.isInvalid())
2781  CurLoc = SourceLocation();
2782  }
2783  unsigned LineNo = getLineNumber(Loc);
2784  unsigned ScopeLine = 0;
2785 
2786  DBuilder.createFunction(FDContext, Name, LinkageName, Unit, LineNo,
2787  getOrCreateFunctionType(D, FnType, Unit),
2788  false /*internalLinkage*/, true /*definition*/,
2789  ScopeLine, Flags, CGM.getLangOpts().Optimize,
2790  TParamsArray.get(), getFunctionDeclaration(D));
2791 }
2792 
2794  // Update our current location
2795  setLocation(Loc);
2796 
2797  if (CurLoc.isInvalid() || CurLoc.isMacroID())
2798  return;
2799 
2800  llvm::MDNode *Scope = LexicalBlockStack.back();
2801  Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
2802  getLineNumber(CurLoc), getColumnNumber(CurLoc), Scope));
2803 }
2804 
2805 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2806  llvm::MDNode *Back = nullptr;
2807  if (!LexicalBlockStack.empty())
2808  Back = LexicalBlockStack.back().get();
2809  LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
2810  cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
2811  getColumnNumber(CurLoc)));
2812 }
2813 
2815  SourceLocation Loc) {
2816  // Set our current location.
2817  setLocation(Loc);
2818 
2819  // Emit a line table change for the current location inside the new scope.
2820  Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
2821  getLineNumber(Loc), getColumnNumber(Loc), LexicalBlockStack.back()));
2822 
2823  if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2824  return;
2825 
2826  // Create a new lexical block and push it on the stack.
2827  CreateLexicalBlock(Loc);
2828 }
2829 
2831  SourceLocation Loc) {
2832  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2833 
2834  // Provide an entry in the line table for the end of the block.
2835  EmitLocation(Builder, Loc);
2836 
2837  if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2838  return;
2839 
2840  LexicalBlockStack.pop_back();
2841 }
2842 
2844  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2845  unsigned RCount = FnBeginRegionCount.back();
2846  assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2847 
2848  // Pop all regions for this function.
2849  while (LexicalBlockStack.size() != RCount) {
2850  // Provide an entry in the line table for the end of the block.
2851  EmitLocation(Builder, CurLoc);
2852  LexicalBlockStack.pop_back();
2853  }
2854  FnBeginRegionCount.pop_back();
2855 }
2856 
2857 llvm::DIType *CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2858  uint64_t *XOffset) {
2859 
2861  QualType FType;
2862  uint64_t FieldSize, FieldOffset;
2863  unsigned FieldAlign;
2864 
2865  llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
2866  QualType Type = VD->getType();
2867 
2868  FieldOffset = 0;
2869  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2870  EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2871  EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2872  FType = CGM.getContext().IntTy;
2873  EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2874  EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2875 
2876  bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2877  if (HasCopyAndDispose) {
2878  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2879  EltTys.push_back(
2880  CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
2881  EltTys.push_back(
2882  CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
2883  }
2884  bool HasByrefExtendedLayout;
2885  Qualifiers::ObjCLifetime Lifetime;
2886  if (CGM.getContext().getByrefLifetime(Type, Lifetime,
2887  HasByrefExtendedLayout) &&
2888  HasByrefExtendedLayout) {
2889  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2890  EltTys.push_back(
2891  CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
2892  }
2893 
2894  CharUnits Align = CGM.getContext().getDeclAlign(VD);
2895  if (Align > CGM.getContext().toCharUnitsFromBits(
2896  CGM.getTarget().getPointerAlign(0))) {
2897  CharUnits FieldOffsetInBytes =
2898  CGM.getContext().toCharUnitsFromBits(FieldOffset);
2899  CharUnits AlignedOffsetInBytes =
2900  FieldOffsetInBytes.RoundUpToAlignment(Align);
2901  CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
2902 
2903  if (NumPaddingBytes.isPositive()) {
2904  llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2905  FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2906  pad, ArrayType::Normal, 0);
2907  EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2908  }
2909  }
2910 
2911  FType = Type;
2912  llvm::DIType *FieldTy = getOrCreateType(FType, Unit);
2913  FieldSize = CGM.getContext().getTypeSize(FType);
2914  FieldAlign = CGM.getContext().toBits(Align);
2915 
2916  *XOffset = FieldOffset;
2917  FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit, 0, FieldSize,
2918  FieldAlign, FieldOffset, 0, FieldTy);
2919  EltTys.push_back(FieldTy);
2920  FieldOffset += FieldSize;
2921 
2922  llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2923 
2924  unsigned Flags = llvm::DINode::FlagBlockByrefStruct;
2925 
2926  return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
2927  nullptr, Elements);
2928 }
2929 
2930 void CGDebugInfo::EmitDeclare(const VarDecl *VD, llvm::Value *Storage,
2932  CGBuilderTy &Builder) {
2933  assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2934  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2935 
2936  bool Unwritten =
2937  VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
2938  cast<Decl>(VD->getDeclContext())->isImplicit());
2939  llvm::DIFile *Unit = nullptr;
2940  if (!Unwritten)
2941  Unit = getOrCreateFile(VD->getLocation());
2942  llvm::DIType *Ty;
2943  uint64_t XOffset = 0;
2944  if (VD->hasAttr<BlocksAttr>())
2945  Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2946  else
2947  Ty = getOrCreateType(VD->getType(), Unit);
2948 
2949  // If there is no debug info for this type then do not emit debug info
2950  // for this variable.
2951  if (!Ty)
2952  return;
2953 
2954  // Get location information.
2955  unsigned Line = 0;
2956  unsigned Column = 0;
2957  if (!Unwritten) {
2958  Line = getLineNumber(VD->getLocation());
2959  Column = getColumnNumber(VD->getLocation());
2960  }
2962  unsigned Flags = 0;
2963  if (VD->isImplicit())
2964  Flags |= llvm::DINode::FlagArtificial;
2965  // If this is the first argument and it is implicit then
2966  // give it an object pointer flag.
2967  // FIXME: There has to be a better way to do this, but for static
2968  // functions there won't be an implicit param at arg1 and
2969  // otherwise it is 'self' or 'this'.
2970  if (isa<ImplicitParamDecl>(VD) && ArgNo && *ArgNo == 1)
2971  Flags |= llvm::DINode::FlagObjectPointer;
2972  if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
2973  if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2974  !VD->getType()->isPointerType())
2975  Expr.push_back(llvm::dwarf::DW_OP_deref);
2976 
2977  auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
2978 
2979  StringRef Name = VD->getName();
2980  if (!Name.empty()) {
2981  if (VD->hasAttr<BlocksAttr>()) {
2982  CharUnits offset = CharUnits::fromQuantity(32);
2983  Expr.push_back(llvm::dwarf::DW_OP_plus);
2984  // offset of __forwarding field
2985  offset = CGM.getContext().toCharUnitsFromBits(
2986  CGM.getTarget().getPointerWidth(0));
2987  Expr.push_back(offset.getQuantity());
2988  Expr.push_back(llvm::dwarf::DW_OP_deref);
2989  Expr.push_back(llvm::dwarf::DW_OP_plus);
2990  // offset of x field
2991  offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2992  Expr.push_back(offset.getQuantity());
2993 
2994  // Create the descriptor for the variable.
2995  auto *D = ArgNo
2996  ? DBuilder.createParameterVariable(Scope, VD->getName(),
2997  *ArgNo, Unit, Line, Ty)
2998  : DBuilder.createAutoVariable(Scope, VD->getName(), Unit,
2999  Line, Ty);
3000 
3001  // Insert an llvm.dbg.declare into the current block.
3002  DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
3003  llvm::DebugLoc::get(Line, Column, Scope),
3004  Builder.GetInsertBlock());
3005  return;
3006  } else if (isa<VariableArrayType>(VD->getType()))
3007  Expr.push_back(llvm::dwarf::DW_OP_deref);
3008  } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
3009  // If VD is an anonymous union then Storage represents value for
3010  // all union fields.
3011  const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
3012  if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
3013  // GDB has trouble finding local variables in anonymous unions, so we emit
3014  // artifical local variables for each of the members.
3015  //
3016  // FIXME: Remove this code as soon as GDB supports this.
3017  // The debug info verifier in LLVM operates based on the assumption that a
3018  // variable has the same size as its storage and we had to disable the check
3019  // for artificial variables.
3020  for (const auto *Field : RD->fields()) {
3021  llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
3022  StringRef FieldName = Field->getName();
3023 
3024  // Ignore unnamed fields. Do not ignore unnamed records.
3025  if (FieldName.empty() && !isa<RecordType>(Field->getType()))
3026  continue;
3027 
3028  // Use VarDecl's Tag, Scope and Line number.
3029  auto *D = DBuilder.createAutoVariable(
3030  Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,
3031  Flags | llvm::DINode::FlagArtificial);
3032 
3033  // Insert an llvm.dbg.declare into the current block.
3034  DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
3035  llvm::DebugLoc::get(Line, Column, Scope),
3036  Builder.GetInsertBlock());
3037  }
3038  }
3039  }
3040 
3041  // Create the descriptor for the variable.
3042  auto *D =
3043  ArgNo
3044  ? DBuilder.createParameterVariable(Scope, Name, *ArgNo, Unit, Line,
3045  Ty, CGM.getLangOpts().Optimize,
3046  Flags)
3047  : DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,
3048  CGM.getLangOpts().Optimize, Flags);
3049 
3050  // Insert an llvm.dbg.declare into the current block.
3051  DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
3052  llvm::DebugLoc::get(Line, Column, Scope),
3053  Builder.GetInsertBlock());
3054 }
3055 
3057  llvm::Value *Storage,
3058  CGBuilderTy &Builder) {
3059  assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
3060  EmitDeclare(VD, Storage, llvm::None, Builder);
3061 }
3062 
3063 llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
3064  llvm::DIType *Ty) {
3065  llvm::DIType *CachedTy = getTypeOrNull(QualTy);
3066  if (CachedTy)
3067  Ty = CachedTy;
3068  return DBuilder.createObjectPointerType(Ty);
3069 }
3070 
3072  const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
3073  const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
3074  assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
3075  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3076 
3077  if (Builder.GetInsertBlock() == nullptr)
3078  return;
3079 
3080  bool isByRef = VD->hasAttr<BlocksAttr>();
3081 
3082  uint64_t XOffset = 0;
3083  llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
3084  llvm::DIType *Ty;
3085  if (isByRef)
3086  Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
3087  else
3088  Ty = getOrCreateType(VD->getType(), Unit);
3089 
3090  // Self is passed along as an implicit non-arg variable in a
3091  // block. Mark it as the object pointer.
3092  if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
3093  Ty = CreateSelfType(VD->getType(), Ty);
3094 
3095  // Get location information.
3096  unsigned Line = getLineNumber(VD->getLocation());
3097  unsigned Column = getColumnNumber(VD->getLocation());
3098 
3099  const llvm::DataLayout &target = CGM.getDataLayout();
3100 
3102  target.getStructLayout(blockInfo.StructureType)
3103  ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
3104 
3106  if (isa<llvm::AllocaInst>(Storage))
3107  addr.push_back(llvm::dwarf::DW_OP_deref);
3108  addr.push_back(llvm::dwarf::DW_OP_plus);
3109  addr.push_back(offset.getQuantity());
3110  if (isByRef) {
3111  addr.push_back(llvm::dwarf::DW_OP_deref);
3112  addr.push_back(llvm::dwarf::DW_OP_plus);
3113  // offset of __forwarding field
3114  offset =
3115  CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
3116  addr.push_back(offset.getQuantity());
3117  addr.push_back(llvm::dwarf::DW_OP_deref);
3118  addr.push_back(llvm::dwarf::DW_OP_plus);
3119  // offset of x field
3120  offset = CGM.getContext().toCharUnitsFromBits(XOffset);
3121  addr.push_back(offset.getQuantity());
3122  }
3123 
3124  // Create the descriptor for the variable.
3125  auto *D = DBuilder.createAutoVariable(
3126  cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
3127  Line, Ty);
3128 
3129  // Insert an llvm.dbg.declare into the current block.
3130  auto DL = llvm::DebugLoc::get(Line, Column, LexicalBlockStack.back());
3131  if (InsertPoint)
3132  DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(addr), DL,
3133  InsertPoint);
3134  else
3135  DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(addr), DL,
3136  Builder.GetInsertBlock());
3137 }
3138 
3140  unsigned ArgNo,
3141  CGBuilderTy &Builder) {
3142  assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
3143  EmitDeclare(VD, AI, ArgNo, Builder);
3144 }
3145 
3146 namespace {
3147 struct BlockLayoutChunk {
3148  uint64_t OffsetInBits;
3149  const BlockDecl::Capture *Capture;
3150 };
3151 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
3152  return l.OffsetInBits < r.OffsetInBits;
3153 }
3154 }
3155 
3157  llvm::Value *Arg,
3158  unsigned ArgNo,
3159  llvm::Value *LocalAddr,
3160  CGBuilderTy &Builder) {
3161  assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
3162  ASTContext &C = CGM.getContext();
3163  const BlockDecl *blockDecl = block.getBlockDecl();
3164 
3165  // Collect some general information about the block's location.
3166  SourceLocation loc = blockDecl->getCaretLocation();
3167  llvm::DIFile *tunit = getOrCreateFile(loc);
3168  unsigned line = getLineNumber(loc);
3169  unsigned column = getColumnNumber(loc);
3170 
3171  // Build the debug-info type for the block literal.
3172  getDeclContextDescriptor(blockDecl);
3173 
3174  const llvm::StructLayout *blockLayout =
3175  CGM.getDataLayout().getStructLayout(block.StructureType);
3176 
3178  fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
3179  blockLayout->getElementOffsetInBits(0),
3180  tunit, tunit));
3181  fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
3182  blockLayout->getElementOffsetInBits(1),
3183  tunit, tunit));
3184  fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
3185  blockLayout->getElementOffsetInBits(2),
3186  tunit, tunit));
3187  auto *FnTy = block.getBlockExpr()->getFunctionType();
3188  auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
3189  fields.push_back(createFieldType("__FuncPtr", FnPtrType, 0, loc, AS_public,
3190  blockLayout->getElementOffsetInBits(3),
3191  tunit, tunit));
3192  fields.push_back(createFieldType(
3193  "__descriptor", C.getPointerType(block.NeedsCopyDispose
3195  : C.getBlockDescriptorType()),
3196  0, loc, AS_public, blockLayout->getElementOffsetInBits(4), tunit, tunit));
3197 
3198  // We want to sort the captures by offset, not because DWARF
3199  // requires this, but because we're paranoid about debuggers.
3201 
3202  // 'this' capture.
3203  if (blockDecl->capturesCXXThis()) {
3204  BlockLayoutChunk chunk;
3205  chunk.OffsetInBits =
3206  blockLayout->getElementOffsetInBits(block.CXXThisIndex);
3207  chunk.Capture = nullptr;
3208  chunks.push_back(chunk);
3209  }
3210 
3211  // Variable captures.
3212  for (const auto &capture : blockDecl->captures()) {
3213  const VarDecl *variable = capture.getVariable();
3214  const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
3215 
3216  // Ignore constant captures.
3217  if (captureInfo.isConstant())
3218  continue;
3219 
3220  BlockLayoutChunk chunk;
3221  chunk.OffsetInBits =
3222  blockLayout->getElementOffsetInBits(captureInfo.getIndex());
3223  chunk.Capture = &capture;
3224  chunks.push_back(chunk);
3225  }
3226 
3227  // Sort by offset.
3228  llvm::array_pod_sort(chunks.begin(), chunks.end());
3229 
3230  for (SmallVectorImpl<BlockLayoutChunk>::iterator i = chunks.begin(),
3231  e = chunks.end();
3232  i != e; ++i) {
3233  uint64_t offsetInBits = i->OffsetInBits;
3234  const BlockDecl::Capture *capture = i->Capture;
3235 
3236  // If we have a null capture, this must be the C++ 'this' capture.
3237  if (!capture) {
3238  const CXXMethodDecl *method =
3239  cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
3240  QualType type = method->getThisType(C);
3241 
3242  fields.push_back(createFieldType("this", type, 0, loc, AS_public,
3243  offsetInBits, tunit, tunit));
3244  continue;
3245  }
3246 
3247  const VarDecl *variable = capture->getVariable();
3248  StringRef name = variable->getName();
3249 
3250  llvm::DIType *fieldType;
3251  if (capture->isByRef()) {
3252  TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
3253 
3254  // FIXME: this creates a second copy of this type!
3255  uint64_t xoffset;
3256  fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3257  fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
3258  fieldType =
3259  DBuilder.createMemberType(tunit, name, tunit, line, PtrInfo.Width,
3260  PtrInfo.Align, offsetInBits, 0, fieldType);
3261  } else {
3262  fieldType = createFieldType(name, variable->getType(), 0, loc, AS_public,
3263  offsetInBits, tunit, tunit);
3264  }
3265  fields.push_back(fieldType);
3266  }
3267 
3268  SmallString<36> typeName;
3269  llvm::raw_svector_ostream(typeName) << "__block_literal_"
3270  << CGM.getUniqueBlockCount();
3271 
3272  llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
3273 
3274  llvm::DIType *type = DBuilder.createStructType(
3275  tunit, typeName.str(), tunit, line,
3276  CGM.getContext().toBits(block.BlockSize),
3277  CGM.getContext().toBits(block.BlockAlign), 0, nullptr, fieldsArray);
3278  type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3279 
3280  // Get overall information about the block.
3281  unsigned flags = llvm::DINode::FlagArtificial;
3282  auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
3283 
3284  // Create the descriptor for the parameter.
3285  auto *debugVar = DBuilder.createParameterVariable(
3286  scope, Arg->getName(), ArgNo, tunit, line, type,
3287  CGM.getLangOpts().Optimize, flags);
3288 
3289  if (LocalAddr) {
3290  // Insert an llvm.dbg.value into the current block.
3291  DBuilder.insertDbgValueIntrinsic(
3292  LocalAddr, 0, debugVar, DBuilder.createExpression(),
3293  llvm::DebugLoc::get(line, column, scope), Builder.GetInsertBlock());
3294  }
3295 
3296  // Insert an llvm.dbg.declare into the current block.
3297  DBuilder.insertDeclare(Arg, debugVar, DBuilder.createExpression(),
3298  llvm::DebugLoc::get(line, column, scope),
3299  Builder.GetInsertBlock());
3300 }
3301 
3302 llvm::DIDerivedType *
3303 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3304  if (!D->isStaticDataMember())
3305  return nullptr;
3306 
3307  auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
3308  if (MI != StaticDataMemberCache.end()) {
3309  assert(MI->second && "Static data member declaration should still exist");
3310  return MI->second;
3311  }
3312 
3313  // If the member wasn't found in the cache, lazily construct and add it to the
3314  // type (used when a limited form of the type is emitted).
3315  auto DC = D->getDeclContext();
3316  auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
3317  return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
3318 }
3319 
3320 llvm::DIGlobalVariable *CGDebugInfo::CollectAnonRecordDecls(
3321  const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
3322  StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
3323  llvm::DIGlobalVariable *GV = nullptr;
3324 
3325  for (const auto *Field : RD->fields()) {
3326  llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
3327  StringRef FieldName = Field->getName();
3328 
3329  // Ignore unnamed fields, but recurse into anonymous records.
3330  if (FieldName.empty()) {
3331  const RecordType *RT = dyn_cast<RecordType>(Field->getType());
3332  if (RT)
3333  GV = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
3334  Var, DContext);
3335  continue;
3336  }
3337  // Use VarDecl's Tag, Scope and Line number.
3338  GV = DBuilder.createGlobalVariable(DContext, FieldName, LinkageName, Unit,
3339  LineNo, FieldTy,
3340  Var->hasInternalLinkage(), Var, nullptr);
3341  }
3342  return GV;
3343 }
3344 
3345 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3346  const VarDecl *D) {
3347  assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
3348  // Create global variable debug descriptor.
3349  llvm::DIFile *Unit = nullptr;
3350  llvm::DIScope *DContext = nullptr;
3351  unsigned LineNo;
3352  StringRef DeclName, LinkageName;
3353  QualType T;
3354  collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName, DContext);
3355 
3356  // Attempt to store one global variable for the declaration - even if we
3357  // emit a lot of fields.
3358  llvm::DIGlobalVariable *GV = nullptr;
3359 
3360  // If this is an anonymous union then we'll want to emit a global
3361  // variable for each member of the anonymous union so that it's possible
3362  // to find the name of any field in the union.
3363  if (T->isUnionType() && DeclName.empty()) {
3364  const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
3365  assert(RD->isAnonymousStructOrUnion() &&
3366  "unnamed non-anonymous struct or union?");
3367  GV = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
3368  } else {
3369  GV = DBuilder.createGlobalVariable(
3370  DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
3371  Var->hasInternalLinkage(), Var,
3372  getOrCreateStaticDataMemberDeclarationOrNull(D));
3373  }
3374  DeclCache[D->getCanonicalDecl()].reset(static_cast<llvm::Metadata *>(GV));
3375 }
3376 
3378  llvm::Constant *Init) {
3379  assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
3380  // Create the descriptor for the variable.
3381  llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
3382  StringRef Name = VD->getName();
3383  llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
3384  if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3385  const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3386  assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3387  Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3388  }
3389  // Do not use global variables for enums.
3390  //
3391  // FIXME: why not?
3392  if (Ty->getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3393  return;
3394  // Do not emit separate definitions for function local const/statics.
3395  if (isa<FunctionDecl>(VD->getDeclContext()))
3396  return;
3397  VD = cast<ValueDecl>(VD->getCanonicalDecl());
3398  auto *VarD = cast<VarDecl>(VD);
3399  if (VarD->isStaticDataMember()) {
3400  auto *RD = cast<RecordDecl>(VarD->getDeclContext());
3401  getDeclContextDescriptor(VarD);
3402  // Ensure that the type is retained even though it's otherwise unreferenced.
3403  RetainedTypes.push_back(
3405  return;
3406  }
3407 
3408  llvm::DIScope *DContext = getDeclContextDescriptor(VD);
3409 
3410  auto &GV = DeclCache[VD];
3411  if (GV)
3412  return;
3413  GV.reset(DBuilder.createGlobalVariable(
3414  DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
3415  true, Init, getOrCreateStaticDataMemberDeclarationOrNull(VarD)));
3416 }
3417 
3418 llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3419  if (!LexicalBlockStack.empty())
3420  return LexicalBlockStack.back();
3421  llvm::DIScope *Mod = getParentModuleOrNull(D);
3422  return getContextDescriptor(D, Mod ? Mod : TheCU);
3423 }
3424 
3426  if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3427  return;
3428  const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
3429  if (!NSDecl->isAnonymousNamespace() ||
3430  CGM.getCodeGenOpts().DebugExplicitImport) {
3431  DBuilder.createImportedModule(
3432  getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3433  getOrCreateNameSpace(NSDecl),
3434  getLineNumber(UD.getLocation()));
3435  }
3436 }
3437 
3439  if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3440  return;
3441  assert(UD.shadow_size() &&
3442  "We shouldn't be codegening an invalid UsingDecl containing no decls");
3443  // Emitting one decl is sufficient - debuggers can detect that this is an
3444  // overloaded name & provide lookup for all the overloads.
3445  const UsingShadowDecl &USD = **UD.shadow_begin();
3446  if (llvm::DINode *Target =
3447  getDeclarationOrDefinition(USD.getUnderlyingDecl()))
3448  DBuilder.createImportedDeclaration(
3449  getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3450  getLineNumber(USD.getLocation()));
3451 }
3452 
3454  if (Module *M = ID.getImportedModule()) {
3456  DBuilder.createImportedDeclaration(
3457  getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
3458  getOrCreateModuleRef(Info, DebugTypeExtRefs),
3459  getLineNumber(ID.getLocation()));
3460  }
3461 }
3462 
3463 llvm::DIImportedEntity *
3465  if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3466  return nullptr;
3467  auto &VH = NamespaceAliasCache[&NA];
3468  if (VH)
3469  return cast<llvm::DIImportedEntity>(VH);
3470  llvm::DIImportedEntity *R;
3471  if (const NamespaceAliasDecl *Underlying =
3472  dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3473  // This could cache & dedup here rather than relying on metadata deduping.
3474  R = DBuilder.createImportedDeclaration(
3475  getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3476  EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3477  NA.getName());
3478  else
3479  R = DBuilder.createImportedDeclaration(
3480  getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3481  getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3482  getLineNumber(NA.getLocation()), NA.getName());
3483  VH.reset(R);
3484  return R;
3485 }
3486 
3487 llvm::DINamespace *
3488 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
3489  NSDecl = NSDecl->getCanonicalDecl();
3490  auto I = NameSpaceCache.find(NSDecl);
3491  if (I != NameSpaceCache.end())
3492  return cast<llvm::DINamespace>(I->second);
3493 
3494  unsigned LineNo = getLineNumber(NSDecl->getLocation());
3495  llvm::DIFile *FileD = getOrCreateFile(NSDecl->getLocation());
3496  llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);
3497  llvm::DINamespace *NS =
3498  DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3499  NameSpaceCache[NSDecl].reset(NS);
3500  return NS;
3501 }
3502 
3503 void CGDebugInfo::setDwoId(uint64_t Signature) {
3504  assert(TheCU && "no main compile unit");
3505  TheCU->setDWOId(Signature);
3506 }
3507 
3508 
3510  // Creating types might create further types - invalidating the current
3511  // element and the size(), so don't cache/reference them.
3512  for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
3513  ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
3514  llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
3515  ? CreateTypeDefinition(E.Type, E.Unit)
3516  : E.Decl;
3517  DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
3518  }
3519 
3520  for (auto p : ReplaceMap) {
3521  assert(p.second);
3522  auto *Ty = cast<llvm::DIType>(p.second);
3523  assert(Ty->isForwardDecl());
3524 
3525  auto it = TypeCache.find(p.first);
3526  assert(it != TypeCache.end());
3527  assert(it->second);
3528 
3529  DBuilder.replaceTemporary(llvm::TempDIType(Ty),
3530  cast<llvm::DIType>(it->second));
3531  }
3532 
3533  for (const auto &p : FwdDeclReplaceMap) {
3534  assert(p.second);
3535  llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(p.second));
3536  llvm::Metadata *Repl;
3537 
3538  auto it = DeclCache.find(p.first);
3539  // If there has been no definition for the declaration, call RAUW
3540  // with ourselves, that will destroy the temporary MDNode and
3541  // replace it with a standard one, avoiding leaking memory.
3542  if (it == DeclCache.end())
3543  Repl = p.second;
3544  else
3545  Repl = it->second;
3546 
3547  DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
3548  }
3549 
3550  // We keep our own list of retained types, because we need to look
3551  // up the final type in the type cache.
3552  for (auto &RT : RetainedTypes)
3553  if (auto MD = TypeCache[RT])
3554  DBuilder.retainType(cast<llvm::DIType>(MD));
3555 
3556  DBuilder.finalize();
3557 }
3558 
3560  if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3561  return;
3562 
3563  if (auto *DieTy = getOrCreateType(Ty, getOrCreateMainFile()))
3564  // Don't ignore in case of explicit cast where it is referenced indirectly.
3565  DBuilder.retainType(DieTy);
3566 }
Kind getKind() const
Definition: Type.h:2028
unsigned getNumElements() const
Definition: Type.h:2749
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:1941
Defines the clang::ASTContext interface.
bool isObjCOneArgSelector() const
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:5108
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition: Type.h:4778
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1483
static bool hasDefaultSetterName(const ObjCPropertyDecl *PD, const ObjCMethodDecl *Setter)
StringRef getName() const
getName - Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:169
void EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block, llvm::Value *Arg, unsigned ArgNo, llvm::Value *LocalAddr, CGBuilderTy &Builder)
Emit call to llvm.dbg.declare for the block-literal argument to a block invocation function...
Smart pointer class that efficiently represents Objective-C method names.
std::string DwarfDebugFlags
The string to embed in the debug information for the compile unit, if non-empty.
A class which contains all the information about a particular captured value.
Definition: Decl.h:3373
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2147
CanQualType VoidPtrTy
Definition: ASTContext.h:895
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition: Decl.cpp:2140
A (possibly-)qualified type.
Definition: Type.h:575
base_class_range bases()
Definition: DeclCXX.h:713
static unsigned getAccessFlag(AccessSpecifier Access, const RecordDecl *RD)
Convert an AccessSpecifier into the corresponding DINode flag.
unsigned getColumn() const
Return the presumed column number of this location.
bool isMacroID() const
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
Definition: TemplateBase.h:282
bool isValid() const
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:2277
bool isByRef() const
Whether this is a "by ref" capture, i.e.
Definition: Decl.h:3398
void EmitExplicitCastType(QualType Ty)
Emit the type explicitly casted to.
llvm::Module & getModule() const
Defines the clang::FileManager interface and associated types.
llvm::LLVMContext & getLLVMContext()
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
Definition: Decl.h:164
std::string getClangFullVersion()
Retrieves a string representing the complete clang version, which includes the clang version number...
Definition: Version.cpp:118
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:1673
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:3116
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:1439
llvm::DIType * getOrCreateRecordType(QualType Ty, SourceLocation L)
Emit record type's standalone debug info.
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:2847
bool isInvalid() const
Return true if this object is invalid or uninitialized.
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known...
void EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc)
Emit metadata to indicate the end of a new lexical block and pop the current block.
EnumConstantDecl - An instance of this object exists for each enum constant that is defined...
Definition: Decl.h:2397
Defines the SourceManager interface.
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:171
The template argument is an expression, and we've not resolved it to one of the other forms yet...
Definition: TemplateBase.h:69
bool isRecordType() const
Definition: Type.h:5362
QualType getUnderlyingType() const
Definition: Decl.h:2566
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:77
capture_const_iterator captures_begin() const
Definition: DeclCXX.h:1073
Defines the C++ template declaration subclasses.
method_iterator method_begin() const
Method begin iterator.
Definition: DeclCXX.h:761
static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C)
TypePropertyCache< Private > Cache
Definition: Type.cpp:3278
bool hasDefinition() const
Definition: DeclCXX.h:680
const llvm::DataLayout & getDataLayout() const
static bool hasDefaultGetterName(const ObjCPropertyDecl *PD, const ObjCMethodDecl *Getter)
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type...
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition: DeclCXX.h:1832
TemplateSpecializationType(TemplateName T, const TemplateArgument *Args, unsigned NumArgs, QualType Canon, QualType Aliased)
Definition: Type.cpp:3118
QualType getPointeeType() const
Definition: Type.h:2388
The base class of the type hierarchy.
Definition: Type.h:1249
Emit only debug info necessary for generating line number tables (-gline-tables-only).
QualType getRecordType(const RecordDecl *Decl) const
encoding::Encoding Encoding
Definition: Format.cpp:1357
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2424
const Expr * getInit() const
Definition: Decl.h:1070
The template argument is a declaration that was provided for a pointer, reference, or pointer to member non-type template parameter.
Definition: TemplateBase.h:51
NamespaceDecl - Represent a C++ namespace.
Definition: Decl.h:402
bool isPrimaryBaseVirtual() const
isPrimaryBaseVirtual - Get whether the primary base for this record is virtual or not...
Definition: RecordLayout.h:217
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:100
const PreprocessorOptions & getPreprocessorOpts() const
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:90
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:305
Describes the capture of a variable or of this, or of a C++1y init-capture.
Definition: LambdaCapture.h:26
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2134
void * getAsOpaquePtr() const
Definition: Type.h:623
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:699
void removeObjCLifetime()
Definition: Type.h:296
bool capturesCXXThis() const
Definition: Decl.h:3521
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:46
Extra information about a function prototype.
Definition: Type.h:3067
AccessSpecifier getAccess() const
Definition: DeclBase.h:428
field_iterator field_begin() const
Definition: Decl.cpp:3746
const FunctionProtoType * getFunctionType() const
getFunctionType - Return the underlying function type for this block.
Definition: Expr.cpp:2009
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:1793
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:113
QualType getThisType(ASTContext &C) const
Returns the type of the this pointer.
Definition: DeclCXX.cpp:1598
llvm::Constant * GetAddrOfGlobalVar(const VarDecl *D, llvm::Type *Ty=nullptr)
Return the llvm::Constant for the address of the given global variable.
NamespaceDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this namespace.
Definition: Decl.h:488
std::string SplitDwarfFile
The name for the split debug info file that we'll break out.
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:48
bool isMemberDataPointerType() const
Definition: Type.h:5338
capture_range captures()
Definition: Decl.h:3509
Describes how types, statements, expressions, and declarations should be printed. ...
Definition: PrettyPrinter.h:35
void completeTemplateDefinition(const ClassTemplateSpecializationDecl &SD)
ParmVarDecl - Represents a parameter to a function.
Definition: Decl.h:1299
bool isUnionType() const
Definition: Type.cpp:391
static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD)
The collection of all-type qualifiers we support.
Definition: Type.h:116
PipeType - OpenCL20.
Definition: Type.h:5020
unsigned getNumParams() const
Definition: Type.h:3160
RecordDecl - Represents a struct/union/class.
Definition: Decl.h:3166
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
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition: Type.cpp:3175
class LLVM_ALIGNAS(8) DependentTemplateSpecializationType const IdentifierInfo * Name
Represents a template specialization type whose template cannot be resolved, e.g. ...
Definition: Type.h:4381
bool hasAttr() const
Definition: DeclBase.h:498
Represents a class type in Objective C.
Definition: Type.h:4557
void removeRestrict()
Definition: Type.h:247
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:3184
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:91
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:57
static bool isFunctionLocalClass(const CXXRecordDecl *RD)
isFunctionLocalClass - Return true if CXXRecordDecl is defined inside a function. ...
void EmitImportDecl(const ImportDecl &ID)
Emit an declaration.
QualType getReturnType() const
Definition: Decl.h:1956
FieldDecl - An instance of this class is created by Sema::ActOnField to represent a member of a struc...
Definition: Decl.h:2209
bool isCompleteDefinition() const
isCompleteDefinition - Return true if this decl has its body fully specified.
Definition: Decl.h:2788
void removeConst()
Definition: Type.h:233
bool isClass() const
Definition: Decl.h:2855
Don't generate debug info.
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition: Decl.h:452
bool isPure() const
Whether this virtual function is pure, i.e.
Definition: Decl.h:1748
QualType getBlockDescriptorType() const
Gets the struct used to keep track of the descriptor for pointer to blocks.
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:1769
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:1507
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:232
unsigned shadow_size() const
Return the number of shadowed declarations associated with this using declaration.
Definition: DeclCXX.h:2965
void completeClassData(const RecordDecl *RD)
Emit location information but do not generate debug info in the output.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:48
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1191
const Decl * getDecl() const
Definition: GlobalDecl.h:60
Describes a module or submodule.
Definition: Basic/Module.h:47
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:1490
Provides information about a function template specialization, which is a FunctionDecl that has been ...
Definition: DeclTemplate.h:391
const Capture & getCapture(const VarDecl *var) const
Definition: CGBlocks.h:254
Represents a C++ using-declaration.
Definition: DeclCXX.h:2858
const TemplateArgumentList * TemplateArguments
The template arguments used to produce the function template specialization from the function templat...
Definition: DeclTemplate.h:424
static SmallString< 64 > constructSetterName(StringRef Name)
Return the default setter name for the given identifier.
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2351
An lvalue ref-qualifier was provided (&).
Definition: Type.h:1208
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:514
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
uint32_t Offset
Definition: CacheTokens.cpp:44
QualType getBaseType() const
Gets the base type of this object type.
Definition: Type.h:4612
NamedDecl * getAliasedNamespace() const
Retrieve the namespace that this alias refers to, which may either be a NamespaceDecl or a NamespaceA...
Definition: DeclCXX.h:2743
QualType getReturnType() const
Definition: Type.h:2977
const CXXRecordDecl * getParent() const
Returns the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:1801
shadow_iterator shadow_begin() const
Definition: DeclCXX.h:2958
unsigned char PointerWidthInBits
The width of a pointer into the generic address space.
void EmitGlobalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl)
Emit information about a global variable.
field_range fields() const
Definition: Decl.h:3295
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
TypeDecl - Represents a declaration of a type.
Definition: Decl.h:2486
bool getByrefLifetime(QualType Ty, Qualifiers::ObjCLifetime &Lifetime, bool &HasByrefExtendedLayout) const
Returns true, if given type has a known lifetime.
RecordDecl * getDecl() const
Definition: Type.h:3553
static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU)
Module * Parent
The parent of this module.
Definition: Basic/Module.h:57
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:184
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:2454
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:38
static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R)
Returns the common set of qualifiers while removing them from the given sets.
Definition: Type.h:169
llvm::DIType * getOrCreateInterfaceType(QualType Ty, SourceLocation Loc)
Emit an Objective-C interface type standalone debug info.
unsigned Align
Definition: ASTContext.h:82
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D...
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:181
TypeClass getTypeClass() const
Definition: Type.h:1501
VarDecl * getCapturedVar() const
Retrieve the declaration of the local variable being captured.
Definition: LambdaCapture.h:93
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
Definition: Type.cpp:1886
bool hasConst() const
Definition: Type.h:229
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC)...
Definition: DeclBase.h:708
llvm::DIImportedEntity * EmitNamespaceAlias(const NamespaceAliasDecl &NA)
Emit C++ namespace alias.
unsigned getLine() const
Return the presumed line number of this location.
Represents an ObjC class declaration.
Definition: DeclObjC.h:853
uint64_t getMethodVTableIndex(GlobalDecl GD)
Locate a virtual function in the vtable.
static void PrintTemplateArgumentList(raw_ostream &OS, const TemplateArgument *Args, unsigned NumArgs, const PrintingPolicy &Policy, bool SkipBrackets=false)
Print a template argument list, including the '<' and '>' enclosing the template arguments...
bool empty() const
Definition: Type.h:359
detail::InMemoryDirectory::const_iterator I
void removeVolatile()
Definition: Type.h:240
CharUnits getVirtualBaseOffsetOffset(const CXXRecordDecl *RD, const CXXRecordDecl *VBase)
Return the offset in chars (relative to the vtable address point) where the offset of the virtual bas...
QualType getType() const
Definition: Decl.h:530
bool isInvalid() const
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:753
bool NeedsCopyDispose
True if the block needs a custom copy or dispose function.
Definition: CGBlocks.h:211
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:1782
bool isPositive() const
isPositive - Test whether the quantity is greater than zero.
Definition: CharUnits.h:122
EnumDecl * getDecl() const
Definition: Type.h:3576
static const Decl * getDefinition(const Decl *D)
Definition: SemaDecl.cpp:2261
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition: DeclObjC.h:2605
bool isStatic() const
Definition: DeclCXX.cpp:1408
bool isUnion() const
Definition: Decl.h:2856
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:5003
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition: Decl.cpp:3178
const HeaderSearchOptions & getHeaderSearchOpts() const
TypeAliasDecl - Represents the declaration of a typedef-name via a C++0x alias-declaration.
Definition: Decl.h:2618
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
QualType getParamType(unsigned i) const
Definition: Type.h:3161
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3041
CGBlockInfo - Information to generate a block literal.
Definition: CGBlocks.h:153
const TargetInfo & getTarget() const
unsigned getOwningModuleID() const
Retrieve the global ID of the module that owns this particular declaration.
Definition: DeclBase.h:647
ASTContext * Context
const SmallVectorImpl< AnnotatedLine * >::const_iterator End
void setDwoId(uint64_t Signature)
Set the main CU's DwoId field to Signature.
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:226
ID
Defines the set of possible language-specific address spaces.
Definition: AddressSpaces.h:27
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl...
SourceManager & SM
bool hasLocalQualifiers() const
Determine whether this particular QualType instance has any qualifiers, without looking through any t...
Definition: Type.h:679
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:34
bool hasVolatile() const
Definition: Type.h:236
CGObjCRuntime & getObjCRuntime()
Return a reference to the configured Objective-C runtime.
void EmitLocation(CGBuilderTy &Builder, SourceLocation Loc)
Emit metadata to indicate a change in line/column information in the source file. ...
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:155
const Type * getTypeForDecl() const
Definition: Decl.h:2507
BlockDecl - This represents a block literal declaration, which is like an unnamed FunctionDecl...
Definition: Decl.h:3369
QualType getPointeeType() const
Definition: Type.h:2268
ValueDecl - Represent the declaration of a variable (in which case it is an lvalue) a function (in wh...
Definition: Decl.h:521
Expr - This represents one expression.
Definition: Expr.h:104
QualType getBlockDescriptorExtendedType() const
Gets the struct used to keep track of the extended descriptor for pointer to blocks.
StringRef getName() const
Return the actual identifier string.
bool isInstance() const
Definition: DeclCXX.h:1728
CGCXXABI & getCXXABI() const
VarDecl * getVariable() const
The variable being captured.
Definition: Decl.h:3394
bool isStruct() const
Definition: Decl.h:2853
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:54
bool isVirtual() const
Definition: DeclCXX.h:1745
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:875
Defines version macros and version-related utility functions for Clang.
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:216
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:3169
DeclContext * getDeclContext()
Definition: DeclBase.h:393
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:224
ASTContext & getContext() const
SourceLocation getLocation() const
Retrieve the source location of the capture.
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
MicrosoftVTableContext & getMicrosoftVTableContext()
ImplicitParamDecl * getSelfDecl() const
Definition: DeclObjC.h:411
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition: Type.h:869
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine()) const
Definition: Type.h:911
bool isInstanceMethod() const
Definition: DeclObjC.h:419
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:85
virtual llvm::Constant * EmitMemberFunctionPointer(const CXXMethodDecl *MD)
Create a member pointer for the given method.
Definition: CGCXXABI.cpp:137
bool isObjCQualifiedIdType() const
True if this is equivalent to 'id.
Definition: Type.h:4899
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition: DeclBase.h:635
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:1593
const TemplateArgument * data() const
Retrieve a pointer to the template argument list.
Definition: DeclTemplate.h:235
unsigned ComputeBitfieldBitOffset(CodeGen::CodeGenModule &CGM, const ObjCInterfaceDecl *ID, const ObjCIvarDecl *Ivar)
Represents an unpacked "presumed" location which can be presented to the user.
bool isExternallyVisible() const
Definition: Decl.h:280
Represents a GCC generic vector type.
Definition: Type.h:2724
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2334
DeclarationName getDeclName() const
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
Definition: Decl.h:190
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
class LLVM_ALIGNAS(8) TemplateSpecializationType unsigned NumArgs
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:3988
QualType getElementType() const
Definition: Type.h:2748
bool isGLValue() const
Definition: Expr.h:249
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2392
bool isComplexIntegerType() const
Definition: Type.cpp:403
RecordDecl * getDefinition() const
getDefinition - Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:3285
FunctionTemplateDecl * getTemplate() const
Retrieve the template from which this function was specialized.
Definition: DeclTemplate.h:434
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:1908
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:28
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:545
The l-value was considered opaque, so the alignment was determined from a type.
void EmitDeclareOfArgVariable(const VarDecl *Decl, llvm::Value *AI, unsigned ArgNo, CGBuilderTy &Builder)
Emit call to llvm.dbg.declare for an argument variable declaration.
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
unsigned getVBTableIndex(const CXXRecordDecl *Derived, const CXXRecordDecl *VBase)
Returns the index of VBase in the vbtable of Derived.
void EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc, QualType FnType)
Emit debug info for a function declaration.
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:236
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Definition: ASTContext.h:1814
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
bool isNonFragile() const
Does this runtime follow the set of implied behaviors for a "non-fragile" ABI?
Definition: ObjCRuntime.h:80
uint64_t getPointerAlign(unsigned AddrSpace) const
virtual void mangleCXXRTTIName(QualType T, raw_ostream &)=0
const char * getFilename() const
Return the presumed filename of this location.
llvm::Constant * EmitConstantExpr(const Expr *E, QualType DestType, CodeGenFunction *CGF=nullptr)
Try to emit the given expression as a constant; returns 0 if the expression cannot be emitted as a co...
bool isInterface() const
Definition: Decl.h:2854
Encodes a location in the source.
enumerator_range enumerators() const
Definition: Decl.h:3026
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any...
Definition: ASTContext.h:932
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:3570
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:5089
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:262
unsigned getBitWidthValue(const ASTContext &Ctx) const
Definition: Decl.cpp:3463
AnnotatedLine & Line
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:4766
const CXXRecordDecl * getPrimaryBase() const
getPrimaryBase - Get the primary base for this record.
Definition: RecordLayout.h:209
llvm::StructType * StructureType
Definition: CGBlocks.h:229
void completeRequiredType(const RecordDecl *RD)
bool isValid() const
Return true if this is a valid SourceLocation object.
TagDecl - Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:2644
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
static QualType getUnderlyingType(const SubRegion *R)
Cached information about one file (either on disk or in the virtual file system). ...
Definition: FileManager.h:53
APFloat & getFloat()
Definition: APValue.h:208
void printName(raw_ostream &os) const
Definition: Decl.h:186
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1701
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:1931
Module * getImportedModule() const
Retrieve the module that was imported by the import declaration.
Definition: Decl.h:3702
CanQualType VoidTy
Definition: ASTContext.h:881
Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
Definition: Decl.h:3388
const CodeGenOptions & getCodeGenOpts() const
const LangOptions & getLangOpts() const
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:2416
std::string getAsString() const
Derive the full selector name (e.g.
TypedefNameDecl * getDecl() const
Definition: Type.h:3375
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:5706
MangleContext & getMangleContext()
Gets the mangle context.
Definition: CGCXXABI.h:95
This template specialization was formed from a template-id but has not yet been declared, defined, or instantiated.
Definition: Specifiers.h:141
FileID getMainFileID() const
Returns the FileID of the main source file.
bool operator<(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
method_iterator method_end() const
Method past-the-end iterator.
Definition: DeclCXX.h:765
ItaniumVTableContext & getItaniumVTableContext()
unsigned CXXThisIndex
The field index of 'this' within the block, if there is one.
Definition: CGBlocks.h:159
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1210
void removeObjCGCAttr()
Definition: Type.h:273
virtual llvm::Constant * EmitNullMemberPointer(const MemberPointerType *MPT)
Create a null member pointer of the given type.
Definition: CGCXXABI.cpp:133
static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I, CXXRecordDecl::method_iterator End)
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:1402
bool isDynamicClass() const
Definition: DeclCXX.h:693
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:245
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition: Decl.h:3658
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:193
QualType getObjCInstanceType()
Retrieve the Objective-C "instancetype" type, if already known; otherwise, returns a NULL type;...
Definition: ASTContext.h:1469
QualType getPointeeType() const
Definition: Type.h:2161
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C 'SEL' type.
Definition: ASTContext.h:1603
ObjCIvarDecl * getNextIvar()
Definition: DeclObjC.h:1642
QualType getType() const
Definition: Expr.h:125
bool isAnonymousStructOrUnion() const
isAnonymousStructOrUnion - Whether this is an anonymous struct or union.
Definition: Decl.h:3233
CanQualType CharTy
Definition: ASTContext.h:883
Represents a template argument.
Definition: TemplateBase.h:40
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:238
This class organizes the cross-function state that is used while generating LLVM code.
Selector getObjCSelector() const
getObjCSelector - Get the Objective-C selector stored in this declaration name.
NamespaceDecl * getNominatedNamespace()
Returns the namespace nominated by this using-directive.
Definition: DeclCXX.cpp:1999
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3025
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:5055
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1121
int getUniqueBlockCount()
Fetches the global unique block count.
prop_range properties() const
Definition: DeclObjC.h:716
Module * inferModuleFromLocation(FullSourceLoc Loc)
Infers the (sub)module based on the given source location and source manager.
Definition: ModuleMap.cpp:919
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
Definition: ASTMatchers.h:1723
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:63
static __inline__ uint32_t volatile uint32_t * p
Definition: arm_acle.h:75
ObjCInterfaceDecl * getDefinition()
Retrieve the definition of this class, or NULL if this class has been forward-declared (with @class) ...
Definition: DeclObjC.h:1216
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:152
QualType getEnumType(const EnumDecl *Decl) const
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:5062
Decl * getNonClosureContext()
Find the innermost non-closure ancestor of this declaration, walking up through blocks, lambdas, etc.
Definition: DeclBase.cpp:815
CGDebugInfo(CodeGenModule &CGM)
Definition: CGDebugInfo.cpp:46
std::string DebugCompilationDir
The string to embed in debug information as the current working directory.
EnumDecl - Represents an enum.
Definition: Decl.h:2930
Selector getSelector() const
Definition: DeclObjC.h:328
detail::InMemoryDirectory::const_iterator E
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2369
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:138
bool isFloat() const
Definition: APValue.h:183
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1022
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:1459
known_extensions_range known_extensions() const
Definition: DeclObjC.h:1425
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:4836
bool isCompleteDefinitionRequired() const
Return true if this complete decl is required to be complete for some existing use.
Definition: Decl.h:2794
Represents a pointer to an Objective C object.
Definition: Type.h:4821
Pointer to a block type.
Definition: Type.h:2254
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2220
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:3544
Complex values, per C99 6.2.5p11.
Definition: Type.h:2087
SourceLocation getCaretLocation() const
Definition: Decl.h:3443
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:5675
unsigned getTypeQuals() const
Definition: Type.h:3267
CanQualType UnsignedLongTy
Definition: ASTContext.h:890
llvm::DIType * getOrCreateStandaloneType(QualType Ty, SourceLocation Loc)
Emit standalone debug info for a type.
QualType getIntegralType() const
Retrieve the type of the integral value.
Definition: TemplateBase.h:294
void completeType(const EnumDecl *ED)
QualType getIntegerType() const
getIntegerType - Return the integer type this enum decl corresponds to.
Definition: Decl.h:3054
virtual llvm::Constant * EmitMemberDataPointer(const MemberPointerType *MPT, CharUnits offset)
Create a member pointer for the given field.
Definition: CGCXXABI.cpp:142
StringRef getMangledName(GlobalDecl GD)
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:1797
The template argument is a type.
Definition: TemplateBase.h:48
ObjCImplementationDecl * getImplementation() const
Definition: DeclObjC.cpp:1447
The template argument is actually a parameter pack.
Definition: TemplateBase.h:72
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat]...
Definition: APValue.h:38
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:986
bool isObjCZeroArgSelector() const
QualType getPointeeType() const
Definition: Type.h:2308
SourceManager & getSourceManager()
Definition: ASTContext.h:553
The type-property cache.
Definition: Type.cpp:3238
uint64_t getPointerWidth(unsigned AddrSpace) const
Return the width of pointers on this target, for the specified address space.
std::string getQualifiedNameAsString() const
Definition: Decl.cpp:1395
A template argument list.
Definition: DeclTemplate.h:172
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the class template specialization.
const Type * getClass() const
Definition: Type.h:2402
void EmitUsingDecl(const UsingDecl &UD)
Emit C++ using declaration.
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
Definition: TemplateBase.h:256
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...
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
Definition: TemplateBase.h:341
Represents a C++ struct/union/class.
Definition: DeclCXX.h:285
BoundNodesTreeBuilder *const Builder
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
The template argument is a template name that was provided for a template template parameter...
Definition: TemplateBase.h:60
std::string MainFileName
The user provided name for the "main file", if non-empty.
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1609
bool isItaniumFamily() const
Does this ABI generally fall into the Itanium family of ABIs?
Definition: TargetCXXABI.h:136
const BlockDecl * getBlockDecl() const
Definition: CGBlocks.h:264
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 'int'.
Definition: Type.h:2011
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:355
QualType getParamTypeForDecl() const
Definition: TemplateBase.h:250
capture_const_iterator captures_end() const
Definition: DeclCXX.h:1076
A SourceLocation and its associated SourceManager.
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:289
void setLocation(SourceLocation Loc)
Update the current source location.
uint64_t Width
Definition: ASTContext.h:81
TagDecl * getDecl() const
Definition: Type.cpp:2961
bool isIncompleteArrayType() const
Definition: Type.h:5350
bool isInt() const
Definition: APValue.h:182
CanQualType IntTy
Definition: ASTContext.h:889
Abstracts clang modules and precompiled header files and holds everything needed to generate debug in...
bool isRecord() const
Definition: DeclBase.h:1273
unsigned getTargetAddressSpace(QualType T) const
Definition: ASTContext.h:2180
bool hasRestrict() const
Definition: Type.h:243
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type...
QualType getElementType() const
Definition: Type.h:5033
QualType getElementType() const
Definition: Type.h:2458
bool MSVCFormatting
Use whitespace and punctuation like MSVC does.
bool capturesThis() const
Determine whether this capture handles the C++ this pointer.
Definition: LambdaCapture.h:71
std::string Sysroot
If non-empty, the directory to use as a "virtual system root" for include paths.
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
const BlockExpr * getBlockExpr() const
Definition: CGBlocks.h:265
SourceLocation getLocation() const
Definition: DeclBase.h:384
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2682
NamedDecl - This represents a decl with a name.
Definition: Decl.h:145
ObjCIvarDecl * all_declared_ivar_begin()
all_declared_ivar_begin - return first ivar declared in this class, its extensions and its implementa...
Definition: DeclObjC.cpp:1487
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're external.
StringRef getName(const PrintingPolicy &Policy) const
Definition: Type.cpp:2513
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:2575
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID...
EnumDecl * getDefinition() const
Definition: Decl.h:2999
Represents a C++ namespace alias.
Definition: DeclCXX.h:2649
const ASTRecordLayout & getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const
Get or compute information about the layout of the specified Objective-C interface.
APSInt & getInt()
Definition: APValue.h:200
Represents C++ using-directive.
Definition: DeclCXX.h:2546
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:642
void EmitFunctionEnd(CGBuilderTy &Builder)
Constructs the debug code for exiting a function.
CharUnits RoundUpToAlignment(const CharUnits &Align) const
RoundUpToAlignment - Returns the next integer (mod 2**64) that is greater than or equal to this quant...
Definition: CharUnits.h:176
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, bool IsForDefinition=false)
Return the address of the given function.
void removeAddressSpace()
Definition: Type.h:322
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration...
Definition: DeclObjC.h:2139
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2480
This class handles loading and caching of source files into memory.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
bool BlockRequiresCopying(QualType Ty, const VarDecl *D)
Returns true iff we need copy/dispose helpers for the given type.
Represents a shadow declaration introduced into a scope by a (resolved) using declaration.
Definition: DeclCXX.h:2766
unsigned Column
Definition: Format.cpp:1349
bool capturesVariable() const
Determine whether this capture handles a variable.
Definition: LambdaCapture.h:77
bool isPointerType() const
Definition: Type.h:5305
static bool shouldOmitDefinition(CodeGenOptions::DebugInfoKind DebugKind, bool DebugTypeExtRefs, const RecordDecl *RD, const LangOptions &LangOpts)
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.