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