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