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