CGDebugInfo.cpp revision 258cf2766859f706bcd231a48593fbb6a1a1d0fe
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 "CodeGenFunction.h"
16#include "CodeGenModule.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/RecordLayout.h"
21#include "clang/Basic/SourceManager.h"
22#include "clang/Basic/FileManager.h"
23#include "clang/Basic/Version.h"
24#include "clang/CodeGen/CodeGenOptions.h"
25#include "llvm/Constants.h"
26#include "llvm/DerivedTypes.h"
27#include "llvm/Instructions.h"
28#include "llvm/Intrinsics.h"
29#include "llvm/Module.h"
30#include "llvm/ADT/StringExtras.h"
31#include "llvm/ADT/SmallVector.h"
32#include "llvm/Support/Dwarf.h"
33#include "llvm/System/Path.h"
34#include "llvm/Target/TargetMachine.h"
35using namespace clang;
36using namespace clang::CodeGen;
37
38CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
39  : CGM(CGM), DebugFactory(CGM.getModule()),
40    FwdDeclCount(0), BlockLiteralGenericSet(false) {
41  CreateCompileUnit();
42}
43
44CGDebugInfo::~CGDebugInfo() {
45  assert(RegionStack.empty() && "Region stack mismatch, stack not empty!");
46}
47
48void CGDebugInfo::setLocation(SourceLocation Loc) {
49  if (Loc.isValid())
50    CurLoc = CGM.getContext().getSourceManager().getInstantiationLoc(Loc);
51}
52
53/// getContextDescriptor - Get context info for the decl.
54llvm::DIDescriptor CGDebugInfo::getContextDescriptor(const Decl *Context,
55                                              llvm::DIDescriptor &CompileUnit) {
56  if (!Context)
57    return CompileUnit;
58
59  llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
60    I = RegionMap.find(Context);
61  if (I != RegionMap.end())
62    return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(I->second));
63
64  // Check namespace.
65  if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
66    return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl, CompileUnit));
67
68  return CompileUnit;
69}
70
71/// getFunctionName - Get function name for the given FunctionDecl. If the
72/// name is constructred on demand (e.g. C++ destructor) then the name
73/// is stored on the side.
74llvm::StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
75  assert (FD && "Invalid FunctionDecl!");
76  IdentifierInfo *FII = FD->getIdentifier();
77  if (FII)
78    return FII->getName();
79
80  // Otherwise construct human readable name for debug info.
81  std::string NS = FD->getNameAsString();
82
83  // Copy this name on the side and use its reference.
84  char *StrPtr = DebugInfoNames.Allocate<char>(NS.length());
85  memcpy(StrPtr, NS.data(), NS.length());
86  return llvm::StringRef(StrPtr, NS.length());
87}
88
89/// getOrCreateFile - Get the file debug info descriptor for the input location.
90llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
91  if (!Loc.isValid())
92    // If Location is not valid then use main input file.
93    return DebugFactory.CreateFile(TheCU.getFilename(), TheCU.getDirectory(),
94                                   TheCU);
95  SourceManager &SM = CGM.getContext().getSourceManager();
96  PresumedLoc PLoc = SM.getPresumedLoc(Loc);
97
98  // Cache the results.
99  const char *fname = PLoc.getFilename();
100  llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
101    DIFileCache.find(fname);
102
103  if (it != DIFileCache.end()) {
104    // Verify that the information still exists.
105    if (&*it->second)
106      return llvm::DIFile(cast<llvm::MDNode>(it->second));
107  }
108
109  // FIXME: We shouldn't even need to call 'makeAbsolute()' in the cases
110  // where we can consult the FileEntry.
111  llvm::sys::Path AbsFileName(PLoc.getFilename());
112  AbsFileName.makeAbsolute();
113
114  llvm::DIFile F = DebugFactory.CreateFile(AbsFileName.getLast(),
115                                           AbsFileName.getDirname(), TheCU);
116
117  DIFileCache[fname] = F;
118  return F;
119
120}
121/// CreateCompileUnit - Create new compile unit.
122void CGDebugInfo::CreateCompileUnit() {
123
124  // Get absolute path name.
125  SourceManager &SM = CGM.getContext().getSourceManager();
126  std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
127  if (MainFileName.empty())
128    MainFileName = "<unknown>";
129
130  llvm::sys::Path AbsFileName(MainFileName);
131  AbsFileName.makeAbsolute();
132
133  // The main file name provided via the "-main-file-name" option contains just
134  // the file name itself with no path information. This file name may have had
135  // a relative path, so we look into the actual file entry for the main
136  // file to determine the real absolute path for the file.
137  std::string MainFileDir;
138  if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID()))
139    MainFileDir = MainFile->getDir()->getName();
140  else
141    MainFileDir = AbsFileName.getDirname();
142
143  unsigned LangTag;
144  const LangOptions &LO = CGM.getLangOptions();
145  if (LO.CPlusPlus) {
146    if (LO.ObjC1)
147      LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
148    else
149      LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
150  } else if (LO.ObjC1) {
151    LangTag = llvm::dwarf::DW_LANG_ObjC;
152  } else if (LO.C99) {
153    LangTag = llvm::dwarf::DW_LANG_C99;
154  } else {
155    LangTag = llvm::dwarf::DW_LANG_C89;
156  }
157
158  const char *Producer =
159#ifdef CLANG_VENDOR
160    CLANG_VENDOR
161#endif
162    "clang " CLANG_VERSION_STRING;
163
164  // Figure out which version of the ObjC runtime we have.
165  unsigned RuntimeVers = 0;
166  if (LO.ObjC1)
167    RuntimeVers = LO.ObjCNonFragileABI ? 2 : 1;
168
169  // Create new compile unit.
170  TheCU = DebugFactory.CreateCompileUnit(
171    LangTag, AbsFileName.getLast(), MainFileDir, Producer, true,
172    LO.Optimize, CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers);
173}
174
175/// CreateType - Get the Basic type from the cache or create a new
176/// one if necessary.
177llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT,
178                                     llvm::DIFile Unit) {
179  unsigned Encoding = 0;
180  switch (BT->getKind()) {
181  default:
182  case BuiltinType::Void:
183    return llvm::DIType();
184  case BuiltinType::UChar:
185  case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
186  case BuiltinType::Char_S:
187  case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
188  case BuiltinType::UShort:
189  case BuiltinType::UInt:
190  case BuiltinType::ULong:
191  case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
192  case BuiltinType::Short:
193  case BuiltinType::Int:
194  case BuiltinType::Long:
195  case BuiltinType::LongLong:  Encoding = llvm::dwarf::DW_ATE_signed; break;
196  case BuiltinType::Bool:      Encoding = llvm::dwarf::DW_ATE_boolean; break;
197  case BuiltinType::Float:
198  case BuiltinType::LongDouble:
199  case BuiltinType::Double:    Encoding = llvm::dwarf::DW_ATE_float; break;
200  }
201  // Bit size, align and offset of the type.
202  uint64_t Size = CGM.getContext().getTypeSize(BT);
203  uint64_t Align = CGM.getContext().getTypeAlign(BT);
204  uint64_t Offset = 0;
205
206  llvm::DIType DbgTy =
207    DebugFactory.CreateBasicType(Unit,
208                                 BT->getName(CGM.getContext().getLangOptions()),
209                                 Unit, 0, Size, Align,
210                                 Offset, /*flags*/ 0, Encoding);
211  return DbgTy;
212}
213
214llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty,
215                                     llvm::DIFile Unit) {
216  // Bit size, align and offset of the type.
217  unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
218  if (Ty->isComplexIntegerType())
219    Encoding = llvm::dwarf::DW_ATE_lo_user;
220
221  uint64_t Size = CGM.getContext().getTypeSize(Ty);
222  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
223  uint64_t Offset = 0;
224
225  llvm::DIType DbgTy =
226    DebugFactory.CreateBasicType(Unit, "complex",
227                                 Unit, 0, Size, Align,
228                                 Offset, /*flags*/ 0, Encoding);
229  return DbgTy;
230}
231
232/// CreateCVRType - Get the qualified type from the cache or create
233/// a new one if necessary.
234llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
235  QualifierCollector Qc;
236  const Type *T = Qc.strip(Ty);
237
238  // Ignore these qualifiers for now.
239  Qc.removeObjCGCAttr();
240  Qc.removeAddressSpace();
241
242  // We will create one Derived type for one qualifier and recurse to handle any
243  // additional ones.
244  unsigned Tag;
245  if (Qc.hasConst()) {
246    Tag = llvm::dwarf::DW_TAG_const_type;
247    Qc.removeConst();
248  } else if (Qc.hasVolatile()) {
249    Tag = llvm::dwarf::DW_TAG_volatile_type;
250    Qc.removeVolatile();
251  } else if (Qc.hasRestrict()) {
252    Tag = llvm::dwarf::DW_TAG_restrict_type;
253    Qc.removeRestrict();
254  } else {
255    assert(Qc.empty() && "Unknown type qualifier for debug info");
256    return getOrCreateType(QualType(T, 0), Unit);
257  }
258
259  llvm::DIType FromTy = getOrCreateType(Qc.apply(T), Unit);
260
261  // No need to fill in the Name, Line, Size, Alignment, Offset in case of
262  // CVR derived types.
263  llvm::DIType DbgTy =
264    DebugFactory.CreateDerivedType(Tag, Unit, "", Unit,
265                                   0, 0, 0, 0, 0, FromTy);
266  return DbgTy;
267}
268
269llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
270                                     llvm::DIFile Unit) {
271  llvm::DIType DbgTy =
272    CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
273                          Ty->getPointeeType(), Unit);
274  return DbgTy;
275}
276
277llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
278                                     llvm::DIFile Unit) {
279  return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
280                               Ty->getPointeeType(), Unit);
281}
282
283llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
284                                                const Type *Ty,
285                                                QualType PointeeTy,
286                                                llvm::DIFile Unit) {
287  llvm::DIType EltTy = getOrCreateType(PointeeTy, Unit);
288
289  // Bit size, align and offset of the type.
290
291  // Size is always the size of a pointer. We can't use getTypeSize here
292  // because that does not return the correct value for references.
293  uint64_t Size =
294    CGM.getContext().Target.getPointerWidth(PointeeTy.getAddressSpace());
295  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
296
297  return
298    DebugFactory.CreateDerivedType(Tag, Unit, "", Unit,
299                                   0, Size, Align, 0, 0, EltTy);
300
301}
302
303llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
304                                     llvm::DIFile Unit) {
305  if (BlockLiteralGenericSet)
306    return BlockLiteralGeneric;
307
308  unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
309
310  llvm::SmallVector<llvm::DIDescriptor, 5> EltTys;
311
312  llvm::DIType FieldTy;
313
314  QualType FType;
315  uint64_t FieldSize, FieldOffset;
316  unsigned FieldAlign;
317
318  llvm::DIArray Elements;
319  llvm::DIType EltTy, DescTy;
320
321  FieldOffset = 0;
322  FType = CGM.getContext().UnsignedLongTy;
323  EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
324  EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
325
326  Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
327  EltTys.clear();
328
329  unsigned Flags = llvm::DIType::FlagAppleBlock;
330
331  EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_descriptor",
332                                           Unit, 0, FieldOffset, 0, 0, Flags,
333                                           llvm::DIType(), Elements);
334
335  // Bit size, align and offset of the type.
336  uint64_t Size = CGM.getContext().getTypeSize(Ty);
337  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
338
339  DescTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
340                                          Unit, "", Unit,
341                                          0, Size, Align, 0, 0, EltTy);
342
343  FieldOffset = 0;
344  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
345  EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
346  FType = CGM.getContext().IntTy;
347  EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
348  EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
349  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
350  EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
351
352  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
353  FieldTy = DescTy;
354  FieldSize = CGM.getContext().getTypeSize(Ty);
355  FieldAlign = CGM.getContext().getTypeAlign(Ty);
356  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
357                                           "__descriptor", Unit,
358                                           0, FieldSize, FieldAlign,
359                                           FieldOffset, 0, FieldTy);
360  EltTys.push_back(FieldTy);
361
362  FieldOffset += FieldSize;
363  Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
364
365  EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_literal_generic",
366                                           Unit, 0, FieldOffset, 0, 0, Flags,
367                                           llvm::DIType(), Elements);
368
369  BlockLiteralGenericSet = true;
370  BlockLiteralGeneric
371    = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, Unit,
372                                     "", Unit,
373                                     0, Size, Align, 0, 0, EltTy);
374  return BlockLiteralGeneric;
375}
376
377llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty,
378                                     llvm::DIFile Unit) {
379  // Typedefs are derived from some other type.  If we have a typedef of a
380  // typedef, make sure to emit the whole chain.
381  llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
382
383  // We don't set size information, but do specify where the typedef was
384  // declared.
385  SourceManager &SM = CGM.getContext().getSourceManager();
386  PresumedLoc PLoc = SM.getPresumedLoc(Ty->getDecl()->getLocation());
387  unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
388
389  llvm::DIDescriptor TyContext
390    = getContextDescriptor(dyn_cast<Decl>(Ty->getDecl()->getDeclContext()),
391                           Unit);
392  llvm::DIType DbgTy =
393    DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_typedef,
394                                   TyContext,
395                                   Ty->getDecl()->getName(), Unit,
396                                   Line, 0, 0, 0, 0, Src);
397  return DbgTy;
398}
399
400llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
401                                     llvm::DIFile Unit) {
402  llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
403
404  // Add the result type at least.
405  EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
406
407  // Set up remainder of arguments if there is a prototype.
408  // FIXME: IF NOT, HOW IS THIS REPRESENTED?  llvm-gcc doesn't represent '...'!
409  if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(Ty)) {
410    for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
411      EltTys.push_back(getOrCreateType(FTP->getArgType(i), Unit));
412  } else {
413    // FIXME: Handle () case in C.  llvm-gcc doesn't do it either.
414  }
415
416  llvm::DIArray EltTypeArray =
417    DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
418
419  llvm::DIType DbgTy =
420    DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
421                                     Unit, "", Unit,
422                                     0, 0, 0, 0, 0,
423                                     llvm::DIType(), EltTypeArray);
424  return DbgTy;
425}
426
427/// CollectRecordFields - A helper function to collect debug info for
428/// record fields. This is used while creating debug info entry for a Record.
429void CGDebugInfo::
430CollectRecordFields(const RecordDecl *RD, llvm::DIFile Unit,
431                    llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys) {
432  unsigned FieldNo = 0;
433  SourceManager &SM = CGM.getContext().getSourceManager();
434  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
435  for (RecordDecl::field_iterator I = RD->field_begin(),
436                                  E = RD->field_end();
437       I != E; ++I, ++FieldNo) {
438    FieldDecl *Field = *I;
439    llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
440
441    llvm::StringRef FieldName = Field->getName();
442
443    // Ignore unnamed fields. Do not ignore unnamed records.
444    if (FieldName.empty() && !isa<RecordType>(Field->getType()))
445      continue;
446
447    // Get the location for the field.
448    SourceLocation FieldDefLoc = Field->getLocation();
449    PresumedLoc PLoc = SM.getPresumedLoc(FieldDefLoc);
450    llvm::DIFile FieldDefUnit;
451    unsigned FieldLine = 0;
452
453    if (!PLoc.isInvalid()) {
454      FieldDefUnit = getOrCreateFile(FieldDefLoc);
455      FieldLine = PLoc.getLine();
456    }
457
458    QualType FType = Field->getType();
459    uint64_t FieldSize = 0;
460    unsigned FieldAlign = 0;
461    if (!FType->isIncompleteArrayType()) {
462
463      // Bit size, align and offset of the type.
464      FieldSize = CGM.getContext().getTypeSize(FType);
465      Expr *BitWidth = Field->getBitWidth();
466      if (BitWidth)
467        FieldSize = BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
468
469      FieldAlign =  CGM.getContext().getTypeAlign(FType);
470    }
471
472    uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
473
474    unsigned Flags = 0;
475    AccessSpecifier Access = I->getAccess();
476    if (Access == clang::AS_private)
477      Flags |= llvm::DIType::FlagPrivate;
478    else if (Access == clang::AS_protected)
479      Flags |= llvm::DIType::FlagProtected;
480
481    // Create a DW_TAG_member node to remember the offset of this field in the
482    // struct.  FIXME: This is an absolutely insane way to capture this
483    // information.  When we gut debug info, this should be fixed.
484    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
485                                             FieldName, FieldDefUnit,
486                                             FieldLine, FieldSize, FieldAlign,
487                                             FieldOffset, Flags, FieldTy);
488    EltTys.push_back(FieldTy);
489  }
490}
491
492/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
493/// function type is not updated to include implicit "this" pointer. Use this
494/// routine to get a method type which includes "this" pointer.
495llvm::DIType
496CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
497                                   llvm::DIFile Unit) {
498  llvm::DIType FnTy
499    = getOrCreateType(QualType(Method->getType()->getAs<FunctionProtoType>(),
500                               0),
501                      Unit);
502
503  // Static methods do not need "this" pointer argument.
504  if (Method->isStatic())
505    return FnTy;
506
507  // Add "this" pointer.
508
509  llvm::DIArray Args = llvm::DICompositeType(FnTy).getTypeArray();
510  assert (Args.getNumElements() && "Invalid number of arguments!");
511
512  llvm::SmallVector<llvm::DIDescriptor, 16> Elts;
513
514  // First element is always return type. For 'void' functions it is NULL.
515  Elts.push_back(Args.getElement(0));
516
517  // "this" pointer is always first argument.
518  ASTContext &Context = CGM.getContext();
519  QualType ThisPtr =
520    Context.getPointerType(Context.getTagDeclType(Method->getParent()));
521  llvm::DIType ThisPtrType =
522    DebugFactory.CreateArtificialType(getOrCreateType(ThisPtr, Unit));
523  TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
524  Elts.push_back(ThisPtrType);
525
526  // Copy rest of the arguments.
527  for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
528    Elts.push_back(Args.getElement(i));
529
530  llvm::DIArray EltTypeArray =
531    DebugFactory.GetOrCreateArray(Elts.data(), Elts.size());
532
533  return
534    DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
535                                     Unit, "", Unit,
536                                     0, 0, 0, 0, 0,
537                                     llvm::DIType(), EltTypeArray);
538}
539
540/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
541/// a single member function GlobalDecl.
542llvm::DISubprogram
543CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
544                                     llvm::DIFile Unit,
545                                     llvm::DICompositeType &RecordTy) {
546  bool IsCtorOrDtor =
547    isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
548
549  llvm::StringRef MethodName = getFunctionName(Method);
550  llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit);
551
552  // Since a single ctor/dtor corresponds to multiple functions, it doesn't
553  // make sense to give a single ctor/dtor a linkage name.
554  MangleBuffer MethodLinkageName;
555  if (!IsCtorOrDtor)
556    CGM.getMangledName(MethodLinkageName, Method);
557
558  SourceManager &SM = CGM.getContext().getSourceManager();
559
560  // Get the location for the method.
561  SourceLocation MethodDefLoc = Method->getLocation();
562  PresumedLoc PLoc = SM.getPresumedLoc(MethodDefLoc);
563  llvm::DIFile MethodDefUnit;
564  unsigned MethodLine = 0;
565
566  if (!PLoc.isInvalid()) {
567    MethodDefUnit = getOrCreateFile(MethodDefLoc);
568    MethodLine = PLoc.getLine();
569  }
570
571  // Collect virtual method info.
572  llvm::DIType ContainingType;
573  unsigned Virtuality = 0;
574  unsigned VIndex = 0;
575
576  if (Method->isVirtual()) {
577    if (Method->isPure())
578      Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
579    else
580      Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
581
582    // It doesn't make sense to give a virtual destructor a vtable index,
583    // since a single destructor has two entries in the vtable.
584    if (!isa<CXXDestructorDecl>(Method))
585      VIndex = CGM.getVTables().getMethodVTableIndex(Method);
586    ContainingType = RecordTy;
587  }
588
589  llvm::DISubprogram SP =
590    DebugFactory.CreateSubprogram(RecordTy , MethodName, MethodName,
591                                  MethodLinkageName,
592                                  MethodDefUnit, MethodLine,
593                                  MethodTy, /*isLocalToUnit=*/false,
594                                  Method->isThisDeclarationADefinition(),
595                                  Virtuality, VIndex, ContainingType);
596
597  // Don't cache ctors or dtors since we have to emit multiple functions for
598  // a single ctor or dtor.
599  if (!IsCtorOrDtor && Method->isThisDeclarationADefinition())
600    SPCache[Method] = llvm::WeakVH(SP);
601
602  return SP;
603}
604
605/// CollectCXXMemberFunctions - A helper function to collect debug info for
606/// C++ member functions.This is used while creating debug info entry for
607/// a Record.
608void CGDebugInfo::
609CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
610                          llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys,
611                          llvm::DICompositeType &RecordTy) {
612  for(CXXRecordDecl::method_iterator I = RD->method_begin(),
613        E = RD->method_end(); I != E; ++I) {
614    const CXXMethodDecl *Method = *I;
615
616    if (Method->isImplicit() && !Method->isUsed())
617      continue;
618
619    EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
620  }
621}
622
623/// CollectCXXBases - A helper function to collect debug info for
624/// C++ base classes. This is used while creating debug info entry for
625/// a Record.
626void CGDebugInfo::
627CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
628                llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys,
629                llvm::DICompositeType &RecordTy) {
630
631  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
632  for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
633         BE = RD->bases_end(); BI != BE; ++BI) {
634    unsigned BFlags = 0;
635    uint64_t BaseOffset;
636
637    const CXXRecordDecl *Base =
638      cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
639
640    if (BI->isVirtual()) {
641      // virtual base offset offset is -ve. The code generator emits dwarf
642      // expression where it expects +ve number.
643      BaseOffset = 0 - CGM.getVTables().getVirtualBaseOffsetOffset(RD, Base);
644      BFlags = llvm::DIType::FlagVirtual;
645    } else
646      BaseOffset = RL.getBaseClassOffset(Base);
647
648    AccessSpecifier Access = BI->getAccessSpecifier();
649    if (Access == clang::AS_private)
650      BFlags |= llvm::DIType::FlagPrivate;
651    else if (Access == clang::AS_protected)
652      BFlags |= llvm::DIType::FlagProtected;
653
654    llvm::DIType DTy =
655      DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_inheritance,
656                                     RecordTy, llvm::StringRef(),
657                                     Unit, 0, 0, 0,
658                                     BaseOffset, BFlags,
659                                     getOrCreateType(BI->getType(),
660                                                     Unit));
661    EltTys.push_back(DTy);
662  }
663}
664
665/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
666llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
667  if (VTablePtrType.isValid())
668    return VTablePtrType;
669
670  ASTContext &Context = CGM.getContext();
671
672  /* Function type */
673  llvm::DIDescriptor STy = getOrCreateType(Context.IntTy, Unit);
674  llvm::DIArray SElements = DebugFactory.GetOrCreateArray(&STy, 1);
675  llvm::DIType SubTy =
676    DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
677                                     Unit, "", Unit,
678                                     0, 0, 0, 0, 0, llvm::DIType(), SElements);
679
680  unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
681  llvm::DIType vtbl_ptr_type
682    = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
683                                     Unit, "__vtbl_ptr_type", Unit,
684                                     0, Size, 0, 0, 0, SubTy);
685
686  VTablePtrType =
687    DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
688                                   Unit, "", Unit,
689                                   0, Size, 0, 0, 0, vtbl_ptr_type);
690  return VTablePtrType;
691}
692
693/// getVTableName - Get vtable name for the given Class.
694llvm::StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
695  // Otherwise construct gdb compatible name name.
696  std::string Name = "_vptr$" + RD->getNameAsString();
697
698  // Copy this name on the side and use its reference.
699  char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
700  memcpy(StrPtr, Name.data(), Name.length());
701  return llvm::StringRef(StrPtr, Name.length());
702}
703
704
705/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
706/// debug info entry in EltTys vector.
707void CGDebugInfo::
708CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
709                  llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys) {
710  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
711
712  // If there is a primary base then it will hold vtable info.
713  if (RL.getPrimaryBase())
714    return;
715
716  // If this class is not dynamic then there is not any vtable info to collect.
717  if (!RD->isDynamicClass())
718    return;
719
720  unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
721  llvm::DIType VPTR
722    = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
723                                     getVTableName(RD), Unit,
724                                     0, Size, 0, 0, 0,
725                                     getOrCreateVTablePtrType(Unit));
726  EltTys.push_back(VPTR);
727}
728
729/// CreateType - get structure or union type.
730llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty,
731                                     llvm::DIFile Unit) {
732  RecordDecl *RD = Ty->getDecl();
733
734  unsigned Tag;
735  if (RD->isStruct())
736    Tag = llvm::dwarf::DW_TAG_structure_type;
737  else if (RD->isUnion())
738    Tag = llvm::dwarf::DW_TAG_union_type;
739  else {
740    assert(RD->isClass() && "Unknown RecordType!");
741    Tag = llvm::dwarf::DW_TAG_class_type;
742  }
743
744  SourceManager &SM = CGM.getContext().getSourceManager();
745
746  // Get overall information about the record type for the debug info.
747  PresumedLoc PLoc = SM.getPresumedLoc(RD->getLocation());
748  llvm::DIFile DefUnit;
749  unsigned Line = 0;
750  if (!PLoc.isInvalid()) {
751    DefUnit = getOrCreateFile(RD->getLocation());
752    Line = PLoc.getLine();
753  }
754
755  // Records and classes and unions can all be recursive.  To handle them, we
756  // first generate a debug descriptor for the struct as a forward declaration.
757  // Then (if it is a definition) we go through and get debug info for all of
758  // its members.  Finally, we create a descriptor for the complete type (which
759  // may refer to the forward decl if the struct is recursive) and replace all
760  // uses of the forward declaration with the final definition.
761
762  // A RD->getName() is not unique. However, the debug info descriptors
763  // are uniqued so use type name to ensure uniquness.
764  llvm::SmallString<128> FwdDeclName;
765  llvm::raw_svector_ostream(FwdDeclName) << "fwd.type." << FwdDeclCount++;
766  llvm::DIDescriptor FDContext =
767    getContextDescriptor(dyn_cast<Decl>(RD->getDeclContext()), Unit);
768  llvm::DICompositeType FwdDecl =
769    DebugFactory.CreateCompositeType(Tag, FDContext, FwdDeclName,
770                                     DefUnit, Line, 0, 0, 0, 0,
771                                     llvm::DIType(), llvm::DIArray());
772
773  // If this is just a forward declaration, return it.
774  if (!RD->getDefinition())
775    return FwdDecl;
776
777  llvm::MDNode *MN = FwdDecl;
778  llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN;
779  // Otherwise, insert it into the TypeCache so that recursive uses will find
780  // it.
781  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
782  // Push the struct on region stack.
783  RegionStack.push_back(FwdDeclNode);
784  RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
785
786  // Convert all the elements.
787  llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
788
789  const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
790  if (CXXDecl) {
791    CollectCXXBases(CXXDecl, Unit, EltTys, FwdDecl);
792    CollectVTableInfo(CXXDecl, Unit, EltTys);
793  }
794  CollectRecordFields(RD, Unit, EltTys);
795  llvm::MDNode *ContainingType = NULL;
796  if (CXXDecl) {
797    CollectCXXMemberFunctions(CXXDecl, Unit, EltTys, FwdDecl);
798
799    // A class's primary base or the class itself contains the vtable.
800    const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
801    if (const CXXRecordDecl *PBase = RL.getPrimaryBase())
802      ContainingType =
803        getOrCreateType(QualType(PBase->getTypeForDecl(), 0), Unit);
804    else if (CXXDecl->isDynamicClass())
805      ContainingType = FwdDecl;
806  }
807
808  llvm::DIArray Elements =
809    DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
810
811  // Bit size, align and offset of the type.
812  uint64_t Size = CGM.getContext().getTypeSize(Ty);
813  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
814
815  RegionStack.pop_back();
816  llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI =
817    RegionMap.find(Ty->getDecl());
818  if (RI != RegionMap.end())
819    RegionMap.erase(RI);
820
821  llvm::DIDescriptor RDContext =
822    getContextDescriptor(dyn_cast<Decl>(RD->getDeclContext()), Unit);
823  llvm::DICompositeType RealDecl =
824    DebugFactory.CreateCompositeType(Tag, RDContext,
825                                     RD->getName(),
826                                     DefUnit, Line, Size, Align, 0, 0,
827                                     llvm::DIType(), Elements,
828                                     0, ContainingType);
829
830  // Now that we have a real decl for the struct, replace anything using the
831  // old decl with the new one.  This will recursively update the debug info.
832  llvm::DIDerivedType(FwdDeclNode).replaceAllUsesWith(RealDecl);
833  RegionMap[RD] = llvm::WeakVH(RealDecl);
834  return RealDecl;
835}
836
837/// CreateType - get objective-c interface type.
838llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
839                                     llvm::DIFile Unit) {
840  ObjCInterfaceDecl *ID = Ty->getDecl();
841
842  unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
843  SourceManager &SM = CGM.getContext().getSourceManager();
844
845  // Get overall information about the record type for the debug info.
846  llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
847  PresumedLoc PLoc = SM.getPresumedLoc(ID->getLocation());
848  unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
849
850
851  unsigned RuntimeLang = TheCU.getLanguage();
852
853  // To handle recursive interface, we
854  // first generate a debug descriptor for the struct as a forward declaration.
855  // Then (if it is a definition) we go through and get debug info for all of
856  // its members.  Finally, we create a descriptor for the complete type (which
857  // may refer to the forward decl if the struct is recursive) and replace all
858  // uses of the forward declaration with the final definition.
859  llvm::DICompositeType FwdDecl =
860    DebugFactory.CreateCompositeType(Tag, Unit, ID->getName(),
861                                     DefUnit, Line, 0, 0, 0, 0,
862                                     llvm::DIType(), llvm::DIArray(),
863                                     RuntimeLang);
864
865  // If this is just a forward declaration, return it.
866  if (ID->isForwardDecl())
867    return FwdDecl;
868
869  llvm::MDNode *MN = FwdDecl;
870  llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN;
871  // Otherwise, insert it into the TypeCache so that recursive uses will find
872  // it.
873  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
874  // Push the struct on region stack.
875  RegionStack.push_back(FwdDeclNode);
876  RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
877
878  // Convert all the elements.
879  llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
880
881  ObjCInterfaceDecl *SClass = ID->getSuperClass();
882  if (SClass) {
883    llvm::DIType SClassTy =
884      getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
885    llvm::DIType InhTag =
886      DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_inheritance,
887                                     Unit, "", Unit, 0, 0, 0,
888                                     0 /* offset */, 0, SClassTy);
889    EltTys.push_back(InhTag);
890  }
891
892  const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
893
894  unsigned FieldNo = 0;
895  for (ObjCInterfaceDecl::ivar_iterator I = ID->ivar_begin(),
896         E = ID->ivar_end();  I != E; ++I, ++FieldNo) {
897    ObjCIvarDecl *Field = *I;
898    llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
899
900    llvm::StringRef FieldName = Field->getName();
901
902    // Ignore unnamed fields.
903    if (FieldName.empty())
904      continue;
905
906    // Get the location for the field.
907    SourceLocation FieldDefLoc = Field->getLocation();
908    llvm::DIFile FieldDefUnit = getOrCreateFile(FieldDefLoc);
909    PresumedLoc PLoc = SM.getPresumedLoc(FieldDefLoc);
910    unsigned FieldLine = PLoc.isInvalid() ? 0 : PLoc.getLine();
911
912
913    QualType FType = Field->getType();
914    uint64_t FieldSize = 0;
915    unsigned FieldAlign = 0;
916
917    if (!FType->isIncompleteArrayType()) {
918
919      // Bit size, align and offset of the type.
920      FieldSize = CGM.getContext().getTypeSize(FType);
921      Expr *BitWidth = Field->getBitWidth();
922      if (BitWidth)
923        FieldSize = BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
924
925      FieldAlign =  CGM.getContext().getTypeAlign(FType);
926    }
927
928    uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
929
930    unsigned Flags = 0;
931    if (Field->getAccessControl() == ObjCIvarDecl::Protected)
932      Flags = llvm::DIType::FlagProtected;
933    else if (Field->getAccessControl() == ObjCIvarDecl::Private)
934      Flags = llvm::DIType::FlagPrivate;
935
936    // Create a DW_TAG_member node to remember the offset of this field in the
937    // struct.  FIXME: This is an absolutely insane way to capture this
938    // information.  When we gut debug info, this should be fixed.
939    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
940                                             FieldName, FieldDefUnit,
941                                             FieldLine, FieldSize, FieldAlign,
942                                             FieldOffset, Flags, FieldTy);
943    EltTys.push_back(FieldTy);
944  }
945
946  llvm::DIArray Elements =
947    DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
948
949  RegionStack.pop_back();
950  llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI =
951    RegionMap.find(Ty->getDecl());
952  if (RI != RegionMap.end())
953    RegionMap.erase(RI);
954
955  // Bit size, align and offset of the type.
956  uint64_t Size = CGM.getContext().getTypeSize(Ty);
957  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
958
959  llvm::DICompositeType RealDecl =
960    DebugFactory.CreateCompositeType(Tag, Unit, ID->getName(), DefUnit,
961                                     Line, Size, Align, 0, 0, llvm::DIType(),
962                                     Elements, RuntimeLang);
963
964  // Now that we have a real decl for the struct, replace anything using the
965  // old decl with the new one.  This will recursively update the debug info.
966  llvm::DIDerivedType(FwdDeclNode).replaceAllUsesWith(RealDecl);
967  RegionMap[ID] = llvm::WeakVH(RealDecl);
968
969  return RealDecl;
970}
971
972llvm::DIType CGDebugInfo::CreateType(const EnumType *Ty,
973                                     llvm::DIFile Unit) {
974  EnumDecl *ED = Ty->getDecl();
975
976  llvm::SmallVector<llvm::DIDescriptor, 32> Enumerators;
977
978  // Create DIEnumerator elements for each enumerator.
979  for (EnumDecl::enumerator_iterator
980         Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
981       Enum != EnumEnd; ++Enum) {
982    Enumerators.push_back(DebugFactory.CreateEnumerator(Enum->getName(),
983                                            Enum->getInitVal().getZExtValue()));
984  }
985
986  // Return a CompositeType for the enum itself.
987  llvm::DIArray EltArray =
988    DebugFactory.GetOrCreateArray(Enumerators.data(), Enumerators.size());
989
990  SourceLocation DefLoc = ED->getLocation();
991  llvm::DIFile DefUnit = getOrCreateFile(DefLoc);
992  SourceManager &SM = CGM.getContext().getSourceManager();
993  PresumedLoc PLoc = SM.getPresumedLoc(DefLoc);
994  unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
995
996
997  // Size and align of the type.
998  uint64_t Size = 0;
999  unsigned Align = 0;
1000  if (!Ty->isIncompleteType()) {
1001    Size = CGM.getContext().getTypeSize(Ty);
1002    Align = CGM.getContext().getTypeAlign(Ty);
1003  }
1004
1005  llvm::DIType DbgTy =
1006    DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_enumeration_type,
1007                                     Unit, ED->getName(), DefUnit, Line,
1008                                     Size, Align, 0, 0,
1009                                     llvm::DIType(), EltArray);
1010  return DbgTy;
1011}
1012
1013llvm::DIType CGDebugInfo::CreateType(const TagType *Ty,
1014                                     llvm::DIFile Unit) {
1015  if (const RecordType *RT = dyn_cast<RecordType>(Ty))
1016    return CreateType(RT, Unit);
1017  else if (const EnumType *ET = dyn_cast<EnumType>(Ty))
1018    return CreateType(ET, Unit);
1019
1020  return llvm::DIType();
1021}
1022
1023llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty,
1024				     llvm::DIFile Unit) {
1025  llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1026  uint64_t NumElems = Ty->getNumElements();
1027  if (NumElems > 0)
1028    --NumElems;
1029
1030  llvm::DIDescriptor Subscript = DebugFactory.GetOrCreateSubrange(0, NumElems);
1031  llvm::DIArray SubscriptArray = DebugFactory.GetOrCreateArray(&Subscript, 1);
1032
1033  uint64_t Size = CGM.getContext().getTypeSize(Ty);
1034  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1035
1036  return
1037    DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_vector_type,
1038                                     Unit, "", Unit,
1039                                     0, Size, Align, 0, 0,
1040				     ElementTy,  SubscriptArray);
1041}
1042
1043llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1044                                     llvm::DIFile Unit) {
1045  uint64_t Size;
1046  uint64_t Align;
1047
1048
1049  // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1050  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1051    Size = 0;
1052    Align =
1053      CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1054  } else if (Ty->isIncompleteArrayType()) {
1055    Size = 0;
1056    Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1057  } else {
1058    // Size and align of the whole array, not the element type.
1059    Size = CGM.getContext().getTypeSize(Ty);
1060    Align = CGM.getContext().getTypeAlign(Ty);
1061  }
1062
1063  // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
1064  // interior arrays, do we care?  Why aren't nested arrays represented the
1065  // obvious/recursive way?
1066  llvm::SmallVector<llvm::DIDescriptor, 8> Subscripts;
1067  QualType EltTy(Ty, 0);
1068  while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1069    uint64_t Upper = 0;
1070    if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1071      if (CAT->getSize().getZExtValue())
1072        Upper = CAT->getSize().getZExtValue() - 1;
1073    // FIXME: Verify this is right for VLAs.
1074    Subscripts.push_back(DebugFactory.GetOrCreateSubrange(0, Upper));
1075    EltTy = Ty->getElementType();
1076  }
1077
1078  llvm::DIArray SubscriptArray =
1079    DebugFactory.GetOrCreateArray(Subscripts.data(), Subscripts.size());
1080
1081  llvm::DIType DbgTy =
1082    DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_array_type,
1083                                     Unit, "", Unit,
1084                                     0, Size, Align, 0, 0,
1085                                     getOrCreateType(EltTy, Unit),
1086                                     SubscriptArray);
1087  return DbgTy;
1088}
1089
1090llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1091                                     llvm::DIFile Unit) {
1092  return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1093                               Ty, Ty->getPointeeType(), Unit);
1094}
1095
1096llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1097                                     llvm::DIFile U) {
1098  QualType PointerDiffTy = CGM.getContext().getPointerDiffType();
1099  llvm::DIType PointerDiffDITy = getOrCreateType(PointerDiffTy, U);
1100
1101  if (!Ty->getPointeeType()->isFunctionType()) {
1102    // We have a data member pointer type.
1103    return PointerDiffDITy;
1104  }
1105
1106  // We have a member function pointer type. Treat it as a struct with two
1107  // ptrdiff_t members.
1108  std::pair<uint64_t, unsigned> Info = CGM.getContext().getTypeInfo(Ty);
1109
1110  uint64_t FieldOffset = 0;
1111  llvm::DIDescriptor ElementTypes[2];
1112
1113  // FIXME: This should probably be a function type instead.
1114  ElementTypes[0] =
1115    DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, U,
1116                                   "ptr", U, 0,
1117                                   Info.first, Info.second, FieldOffset, 0,
1118                                   PointerDiffDITy);
1119  FieldOffset += Info.first;
1120
1121  ElementTypes[1] =
1122    DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, U,
1123                                   "ptr", U, 0,
1124                                   Info.first, Info.second, FieldOffset, 0,
1125                                   PointerDiffDITy);
1126
1127  llvm::DIArray Elements =
1128    DebugFactory.GetOrCreateArray(&ElementTypes[0],
1129                                  llvm::array_lengthof(ElementTypes));
1130
1131  return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type,
1132                                          U, llvm::StringRef("test"),
1133                                          U, 0, FieldOffset,
1134                                          0, 0, 0, llvm::DIType(), Elements);
1135}
1136
1137static QualType UnwrapTypeForDebugInfo(QualType T) {
1138  do {
1139    QualType LastT = T;
1140    switch (T->getTypeClass()) {
1141    default:
1142      return T;
1143    case Type::TemplateSpecialization:
1144      T = cast<TemplateSpecializationType>(T)->desugar();
1145      break;
1146    case Type::TypeOfExpr: {
1147      TypeOfExprType *Ty = cast<TypeOfExprType>(T);
1148      T = Ty->getUnderlyingExpr()->getType();
1149      break;
1150    }
1151    case Type::TypeOf:
1152      T = cast<TypeOfType>(T)->getUnderlyingType();
1153      break;
1154    case Type::Decltype:
1155      T = cast<DecltypeType>(T)->getUnderlyingType();
1156      break;
1157    case Type::QualifiedName:
1158      T = cast<QualifiedNameType>(T)->getNamedType();
1159      break;
1160    case Type::SubstTemplateTypeParm:
1161      T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
1162      break;
1163    case Type::Elaborated:
1164      T = cast<ElaboratedType>(T)->getUnderlyingType();
1165      break;
1166    }
1167
1168    assert(T != LastT && "Type unwrapping failed to unwrap!");
1169    if (T == LastT)
1170      return T;
1171  } while (true);
1172
1173  return T;
1174}
1175
1176/// getOrCreateType - Get the type from the cache or create a new
1177/// one if necessary.
1178llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty,
1179                                          llvm::DIFile Unit) {
1180  if (Ty.isNull())
1181    return llvm::DIType();
1182
1183  // Unwrap the type as needed for debug information.
1184  Ty = UnwrapTypeForDebugInfo(Ty);
1185
1186  // Check for existing entry.
1187  llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1188    TypeCache.find(Ty.getAsOpaquePtr());
1189  if (it != TypeCache.end()) {
1190    // Verify that the debug info still exists.
1191    if (&*it->second)
1192      return llvm::DIType(cast<llvm::MDNode>(it->second));
1193  }
1194
1195  // Otherwise create the type.
1196  llvm::DIType Res = CreateTypeNode(Ty, Unit);
1197
1198  // And update the type cache.
1199  TypeCache[Ty.getAsOpaquePtr()] = Res;
1200  return Res;
1201}
1202
1203/// CreateTypeNode - Create a new debug type node.
1204llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty,
1205                                         llvm::DIFile Unit) {
1206  // Handle qualifiers, which recursively handles what they refer to.
1207  if (Ty.hasLocalQualifiers())
1208    return CreateQualifiedType(Ty, Unit);
1209
1210  const char *Diag = 0;
1211
1212  // Work out details of type.
1213  switch (Ty->getTypeClass()) {
1214#define TYPE(Class, Base)
1215#define ABSTRACT_TYPE(Class, Base)
1216#define NON_CANONICAL_TYPE(Class, Base)
1217#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1218#include "clang/AST/TypeNodes.def"
1219    assert(false && "Dependent types cannot show up in debug information");
1220
1221  // FIXME: Handle these.
1222  case Type::ExtVector:
1223    return llvm::DIType();
1224
1225  case Type::Vector:
1226    return CreateType(cast<VectorType>(Ty), Unit);
1227  case Type::ObjCObjectPointer:
1228    return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1229  case Type::ObjCInterface:
1230    return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1231  case Type::Builtin: return CreateType(cast<BuiltinType>(Ty), Unit);
1232  case Type::Complex: return CreateType(cast<ComplexType>(Ty), Unit);
1233  case Type::Pointer: return CreateType(cast<PointerType>(Ty), Unit);
1234  case Type::BlockPointer:
1235    return CreateType(cast<BlockPointerType>(Ty), Unit);
1236  case Type::Typedef: return CreateType(cast<TypedefType>(Ty), Unit);
1237  case Type::Record:
1238  case Type::Enum:
1239    return CreateType(cast<TagType>(Ty), Unit);
1240  case Type::FunctionProto:
1241  case Type::FunctionNoProto:
1242    return CreateType(cast<FunctionType>(Ty), Unit);
1243  case Type::ConstantArray:
1244  case Type::VariableArray:
1245  case Type::IncompleteArray:
1246    return CreateType(cast<ArrayType>(Ty), Unit);
1247
1248  case Type::LValueReference:
1249    return CreateType(cast<LValueReferenceType>(Ty), Unit);
1250
1251  case Type::MemberPointer:
1252    return CreateType(cast<MemberPointerType>(Ty), Unit);
1253
1254  case Type::TemplateSpecialization:
1255  case Type::Elaborated:
1256  case Type::QualifiedName:
1257  case Type::SubstTemplateTypeParm:
1258  case Type::TypeOfExpr:
1259  case Type::TypeOf:
1260  case Type::Decltype:
1261    llvm_unreachable("type should have been unwrapped!");
1262    return llvm::DIType();
1263
1264  case Type::RValueReference:
1265    // FIXME: Implement!
1266    Diag = "rvalue references";
1267    break;
1268  }
1269
1270  assert(Diag && "Fall through without a diagnostic?");
1271  unsigned DiagID = CGM.getDiags().getCustomDiagID(Diagnostic::Error,
1272                               "debug information for %0 is not yet supported");
1273  CGM.getDiags().Report(FullSourceLoc(), DiagID)
1274    << Diag;
1275  return llvm::DIType();
1276}
1277
1278/// CreateMemberType - Create new member and increase Offset by FType's size.
1279llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
1280                                           llvm::StringRef Name,
1281                                           uint64_t *Offset) {
1282  llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1283  uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
1284  unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
1285  llvm::DIType Ty = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member,
1286                                                   Unit, Name, Unit, 0,
1287                                                   FieldSize, FieldAlign,
1288                                                   *Offset, 0, FieldTy);
1289  *Offset += FieldSize;
1290  return Ty;
1291}
1292
1293/// EmitFunctionStart - Constructs the debug code for entering a function -
1294/// "llvm.dbg.func.start.".
1295void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
1296                                    llvm::Function *Fn,
1297                                    CGBuilderTy &Builder) {
1298
1299  llvm::StringRef Name;
1300  MangleBuffer LinkageName;
1301
1302  const Decl *D = GD.getDecl();
1303  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1304    // If there is a DISubprogram for  this function available then use it.
1305    llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1306      FI = SPCache.find(FD);
1307    if (FI != SPCache.end()) {
1308      llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(FI->second));
1309      if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
1310        llvm::MDNode *SPN = SP;
1311        RegionStack.push_back(SPN);
1312        RegionMap[D] = llvm::WeakVH(SP);
1313        return;
1314      }
1315    }
1316    Name = getFunctionName(FD);
1317    // Use mangled name as linkage name for c/c++ functions.
1318    CGM.getMangledName(LinkageName, GD);
1319  } else {
1320    // Use llvm function name as linkage name.
1321    Name = Fn->getName();
1322    LinkageName.setString(Name);
1323  }
1324  if (!Name.empty() && Name[0] == '\01')
1325    Name = Name.substr(1);
1326
1327  // It is expected that CurLoc is set before using EmitFunctionStart.
1328  // Usually, CurLoc points to the left bracket location of compound
1329  // statement representing function body.
1330  llvm::DIFile Unit = getOrCreateFile(CurLoc);
1331  SourceManager &SM = CGM.getContext().getSourceManager();
1332  unsigned LineNo = SM.getPresumedLoc(CurLoc).getLine();
1333
1334  llvm::DISubprogram SP =
1335    DebugFactory.CreateSubprogram(Unit, Name, Name, LinkageName, Unit, LineNo,
1336                                  getOrCreateType(FnType, Unit),
1337                                  Fn->hasInternalLinkage(), true/*definition*/);
1338
1339  // Push function on region stack.
1340  llvm::MDNode *SPN = SP;
1341  RegionStack.push_back(SPN);
1342  RegionMap[D] = llvm::WeakVH(SP);
1343}
1344
1345
1346void CGDebugInfo::EmitStopPoint(llvm::Function *Fn, CGBuilderTy &Builder) {
1347  if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
1348
1349  // Don't bother if things are the same as last time.
1350  SourceManager &SM = CGM.getContext().getSourceManager();
1351  if (CurLoc == PrevLoc
1352       || (SM.getInstantiationLineNumber(CurLoc) ==
1353           SM.getInstantiationLineNumber(PrevLoc)
1354           && SM.isFromSameFile(CurLoc, PrevLoc)))
1355    // New Builder may not be in sync with CGDebugInfo.
1356    if (!Builder.getCurrentDebugLocation().isUnknown())
1357      return;
1358
1359  // Update last state.
1360  PrevLoc = CurLoc;
1361
1362  // Get the appropriate compile unit.
1363  llvm::DIFile Unit = getOrCreateFile(CurLoc);
1364  PresumedLoc PLoc = SM.getPresumedLoc(CurLoc);
1365
1366  llvm::MDNode *Scope = RegionStack.back();
1367  Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(PLoc.getLine(),
1368                                                      PLoc.getColumn(),
1369                                                      Scope));
1370}
1371
1372/// EmitRegionStart- Constructs the debug code for entering a declarative
1373/// region - "llvm.dbg.region.start.".
1374void CGDebugInfo::EmitRegionStart(llvm::Function *Fn, CGBuilderTy &Builder) {
1375  SourceManager &SM = CGM.getContext().getSourceManager();
1376  PresumedLoc PLoc = SM.getPresumedLoc(CurLoc);
1377  llvm::DIDescriptor D =
1378    DebugFactory.CreateLexicalBlock(RegionStack.empty() ?
1379                                    llvm::DIDescriptor() :
1380                                    llvm::DIDescriptor(RegionStack.back()),
1381                                    PLoc.getLine(), PLoc.getColumn());
1382  llvm::MDNode *DN = D;
1383  RegionStack.push_back(DN);
1384}
1385
1386/// EmitRegionEnd - Constructs the debug code for exiting a declarative
1387/// region - "llvm.dbg.region.end."
1388void CGDebugInfo::EmitRegionEnd(llvm::Function *Fn, CGBuilderTy &Builder) {
1389  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1390
1391  // Provide an region stop point.
1392  EmitStopPoint(Fn, Builder);
1393
1394  RegionStack.pop_back();
1395}
1396
1397// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
1398// See BuildByRefType.
1399llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const ValueDecl *VD,
1400                                                       uint64_t *XOffset) {
1401
1402  llvm::SmallVector<llvm::DIDescriptor, 5> EltTys;
1403
1404  QualType FType;
1405  uint64_t FieldSize, FieldOffset;
1406  unsigned FieldAlign;
1407
1408  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1409  QualType Type = VD->getType();
1410
1411  FieldOffset = 0;
1412  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1413  EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1414  EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
1415  FType = CGM.getContext().IntTy;
1416  EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1417  EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1418
1419  bool HasCopyAndDispose = CGM.BlockRequiresCopying(Type);
1420  if (HasCopyAndDispose) {
1421    FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1422    EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
1423                                      &FieldOffset));
1424    EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
1425                                      &FieldOffset));
1426  }
1427
1428  CharUnits Align = CGM.getContext().getDeclAlign(VD);
1429  if (Align > CharUnits::fromQuantity(
1430        CGM.getContext().Target.getPointerAlign(0) / 8)) {
1431    unsigned AlignedOffsetInBytes
1432      = llvm::RoundUpToAlignment(FieldOffset/8, Align.getQuantity());
1433    unsigned NumPaddingBytes
1434      = AlignedOffsetInBytes - FieldOffset/8;
1435
1436    if (NumPaddingBytes > 0) {
1437      llvm::APInt pad(32, NumPaddingBytes);
1438      FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
1439                                                    pad, ArrayType::Normal, 0);
1440      EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
1441    }
1442  }
1443
1444  FType = Type;
1445  llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1446  FieldSize = CGM.getContext().getTypeSize(FType);
1447  FieldAlign = Align.getQuantity()*8;
1448
1449  *XOffset = FieldOffset;
1450  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1451                                           VD->getName(), Unit,
1452                                           0, FieldSize, FieldAlign,
1453                                           FieldOffset, 0, FieldTy);
1454  EltTys.push_back(FieldTy);
1455  FieldOffset += FieldSize;
1456
1457  llvm::DIArray Elements =
1458    DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
1459
1460  unsigned Flags = llvm::DIType::FlagBlockByrefStruct;
1461
1462  return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type,
1463                                          Unit, "", Unit,
1464                                          0, FieldOffset, 0, 0, Flags,
1465                                          llvm::DIType(), Elements);
1466
1467}
1468/// EmitDeclare - Emit local variable declaration debug info.
1469void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
1470                              llvm::Value *Storage, CGBuilderTy &Builder) {
1471  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1472
1473  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1474  llvm::DIType Ty;
1475  uint64_t XOffset = 0;
1476  if (VD->hasAttr<BlocksAttr>())
1477    Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
1478  else
1479    Ty = getOrCreateType(VD->getType(), Unit);
1480
1481  // If there is not any debug info for type then do not emit debug info
1482  // for this variable.
1483  if (!Ty)
1484    return;
1485
1486  // Get location information.
1487  SourceManager &SM = CGM.getContext().getSourceManager();
1488  PresumedLoc PLoc = SM.getPresumedLoc(VD->getLocation());
1489  unsigned Line = 0;
1490  unsigned Column = 0;
1491  if (PLoc.isInvalid())
1492    PLoc = SM.getPresumedLoc(CurLoc);
1493  if (PLoc.isValid()) {
1494    Line = PLoc.getLine();
1495    Column = PLoc.getColumn();
1496    Unit = getOrCreateFile(CurLoc);
1497  } else {
1498    Unit = llvm::DIFile();
1499  }
1500
1501  // Create the descriptor for the variable.
1502  llvm::DIVariable D =
1503    DebugFactory.CreateVariable(Tag, llvm::DIDescriptor(RegionStack.back()),
1504                                VD->getName(),
1505                                Unit, Line, Ty);
1506  // Insert an llvm.dbg.declare into the current block.
1507  llvm::Instruction *Call =
1508    DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock());
1509
1510  llvm::MDNode *Scope = RegionStack.back();
1511  Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
1512}
1513
1514/// EmitDeclare - Emit local variable declaration debug info.
1515void CGDebugInfo::EmitDeclare(const BlockDeclRefExpr *BDRE, unsigned Tag,
1516                              llvm::Value *Storage, CGBuilderTy &Builder,
1517                              CodeGenFunction *CGF) {
1518  const ValueDecl *VD = BDRE->getDecl();
1519  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1520
1521  if (Builder.GetInsertBlock() == 0)
1522    return;
1523
1524  uint64_t XOffset = 0;
1525  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1526  llvm::DIType Ty;
1527  if (VD->hasAttr<BlocksAttr>())
1528    Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
1529  else
1530    Ty = getOrCreateType(VD->getType(), Unit);
1531
1532  // Get location information.
1533  SourceManager &SM = CGM.getContext().getSourceManager();
1534  PresumedLoc PLoc = SM.getPresumedLoc(VD->getLocation());
1535  unsigned Line = 0;
1536  if (!PLoc.isInvalid())
1537    Line = PLoc.getLine();
1538  else
1539    // If variable location is invalid, use current location to find
1540    // corresponding file info.
1541    Unit = getOrCreateFile(CurLoc);
1542
1543  CharUnits offset = CGF->BlockDecls[VD];
1544  llvm::SmallVector<llvm::Value *, 9> addr;
1545  const llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext());
1546  addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1547  addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1548  addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1549  if (BDRE->isByRef()) {
1550    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1551    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1552    // offset of __forwarding field
1553    offset = CharUnits::fromQuantity(CGF->LLVMPointerWidth/8);
1554    addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1555    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1556    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1557    // offset of x field
1558    offset = CharUnits::fromQuantity(XOffset/8);
1559    addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1560  }
1561
1562  // Create the descriptor for the variable.
1563  llvm::DIVariable D =
1564    DebugFactory.CreateComplexVariable(Tag,
1565                                       llvm::DIDescriptor(RegionStack.back()),
1566                                       VD->getName(), Unit, Line, Ty,
1567                                       addr);
1568  // Insert an llvm.dbg.declare into the current block.
1569  llvm::Instruction *Call =
1570    DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock());
1571
1572  llvm::MDNode *Scope = RegionStack.back();
1573  Call->setDebugLoc(llvm::DebugLoc::get(Line, PLoc.getColumn(), Scope));
1574}
1575
1576void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
1577                                            llvm::Value *Storage,
1578                                            CGBuilderTy &Builder) {
1579  EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder);
1580}
1581
1582void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
1583  const BlockDeclRefExpr *BDRE, llvm::Value *Storage, CGBuilderTy &Builder,
1584  CodeGenFunction *CGF) {
1585  EmitDeclare(BDRE, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder, CGF);
1586}
1587
1588/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
1589/// variable declaration.
1590void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
1591                                           CGBuilderTy &Builder) {
1592  EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, Builder);
1593}
1594
1595
1596
1597/// EmitGlobalVariable - Emit information about a global variable.
1598void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
1599                                     const VarDecl *D) {
1600
1601  // Create global variable debug descriptor.
1602  llvm::DIFile Unit = getOrCreateFile(D->getLocation());
1603  SourceManager &SM = CGM.getContext().getSourceManager();
1604  PresumedLoc PLoc = SM.getPresumedLoc(D->getLocation());
1605  unsigned LineNo = PLoc.isInvalid() ? 0 : PLoc.getLine();
1606
1607  QualType T = D->getType();
1608  if (T->isIncompleteArrayType()) {
1609
1610    // CodeGen turns int[] into int[1] so we'll do the same here.
1611    llvm::APSInt ConstVal(32);
1612
1613    ConstVal = 1;
1614    QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
1615
1616    T = CGM.getContext().getConstantArrayType(ET, ConstVal,
1617                                           ArrayType::Normal, 0);
1618  }
1619  llvm::StringRef DeclName = D->getName();
1620  llvm::DIDescriptor DContext =
1621    getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()), Unit);
1622  DebugFactory.CreateGlobalVariable(DContext, DeclName,
1623                                    DeclName, llvm::StringRef(), Unit, LineNo,
1624                                    getOrCreateType(T, Unit),
1625                                    Var->hasInternalLinkage(),
1626                                    true/*definition*/, Var);
1627}
1628
1629/// EmitGlobalVariable - Emit information about an objective-c interface.
1630void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
1631                                     ObjCInterfaceDecl *ID) {
1632  // Create global variable debug descriptor.
1633  llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
1634  SourceManager &SM = CGM.getContext().getSourceManager();
1635  PresumedLoc PLoc = SM.getPresumedLoc(ID->getLocation());
1636  unsigned LineNo = PLoc.isInvalid() ? 0 : PLoc.getLine();
1637
1638  llvm::StringRef Name = ID->getName();
1639
1640  QualType T = CGM.getContext().getObjCInterfaceType(ID);
1641  if (T->isIncompleteArrayType()) {
1642
1643    // CodeGen turns int[] into int[1] so we'll do the same here.
1644    llvm::APSInt ConstVal(32);
1645
1646    ConstVal = 1;
1647    QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
1648
1649    T = CGM.getContext().getConstantArrayType(ET, ConstVal,
1650                                           ArrayType::Normal, 0);
1651  }
1652
1653  DebugFactory.CreateGlobalVariable(Unit, Name, Name, Name, Unit, LineNo,
1654                                    getOrCreateType(T, Unit),
1655                                    Var->hasInternalLinkage(),
1656                                    true/*definition*/, Var);
1657}
1658
1659/// getOrCreateNamesSpace - Return namespace descriptor for the given
1660/// namespace decl.
1661llvm::DINameSpace
1662CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl,
1663                                  llvm::DIDescriptor Unit) {
1664  llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
1665    NameSpaceCache.find(NSDecl);
1666  if (I != NameSpaceCache.end())
1667    return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
1668
1669  SourceManager &SM = CGM.getContext().getSourceManager();
1670  PresumedLoc PLoc = SM.getPresumedLoc(NSDecl->getLocation());
1671  unsigned LineNo = PLoc.isInvalid() ? 0 : PLoc.getLine();
1672
1673  llvm::DIDescriptor Context =
1674    getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()), Unit);
1675  llvm::DINameSpace NS =
1676    DebugFactory.CreateNameSpace(Context, NSDecl->getName(),
1677	llvm::DIFile(Unit), LineNo);
1678  NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
1679  return NS;
1680}
1681