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