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