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