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