CGDebugInfo.cpp revision 23e81bae8c91ccd408e31ca472dca25faed85028
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 "CodeGenModule.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/RecordLayout.h"
20#include "clang/Basic/SourceManager.h"
21#include "clang/Basic/FileManager.h"
22#include "clang/Basic/Version.h"
23#include "clang/Frontend/CompileOptions.h"
24#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
26#include "llvm/Instructions.h"
27#include "llvm/Intrinsics.h"
28#include "llvm/Module.h"
29#include "llvm/ADT/StringExtras.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/Support/Dwarf.h"
32#include "llvm/System/Path.h"
33#include "llvm/Target/TargetMachine.h"
34using namespace clang;
35using namespace clang::CodeGen;
36
37CGDebugInfo::CGDebugInfo(CodeGenModule *m)
38  : M(m), isMainCompileUnitCreated(false), DebugFactory(M->getModule()),
39    BlockLiteralGenericSet(false) {
40}
41
42CGDebugInfo::~CGDebugInfo() {
43  assert(RegionStack.empty() && "Region stack mismatch, stack not empty!");
44}
45
46void CGDebugInfo::setLocation(SourceLocation Loc) {
47  if (Loc.isValid())
48    CurLoc = M->getContext().getSourceManager().getInstantiationLoc(Loc);
49}
50
51/// getOrCreateCompileUnit - Get the compile unit from the cache or create a new
52/// one if necessary. This returns null for invalid source locations.
53llvm::DICompileUnit CGDebugInfo::getOrCreateCompileUnit(SourceLocation Loc) {
54  // Get source file information.
55  const char *FileName =  "<unknown>";
56  SourceManager &SM = M->getContext().getSourceManager();
57  unsigned FID = 0;
58  if (Loc.isValid()) {
59    PresumedLoc PLoc = SM.getPresumedLoc(Loc);
60    FileName = PLoc.getFilename();
61    FID = PLoc.getIncludeLoc().getRawEncoding();
62  }
63
64  // See if this compile unit has been used before.
65  llvm::DICompileUnit &Unit = CompileUnitCache[FID];
66  if (!Unit.isNull()) return Unit;
67
68  // Get absolute path name.
69  llvm::sys::Path AbsFileName(FileName);
70  if (!AbsFileName.isAbsolute()) {
71    llvm::sys::Path tmp = llvm::sys::Path::GetCurrentDirectory();
72    tmp.appendComponent(FileName);
73    AbsFileName = tmp;
74  }
75
76  // See if thie compile unit is representing main source file. Each source
77  // file has corresponding compile unit. There is only one main source
78  // file at a time.
79  bool isMain = false;
80  const LangOptions &LO = M->getLangOptions();
81  const char *MainFileName = LO.getMainFileName();
82  if (isMainCompileUnitCreated == false) {
83    if (MainFileName) {
84      if (!strcmp(AbsFileName.getLast().c_str(), MainFileName))
85        isMain = true;
86    } else {
87      if (Loc.isValid() && SM.isFromMainFile(Loc))
88        isMain = true;
89    }
90    if (isMain)
91      isMainCompileUnitCreated = true;
92  }
93
94  unsigned LangTag;
95  if (LO.CPlusPlus) {
96    if (LO.ObjC1)
97      LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
98    else
99      LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
100  } else if (LO.ObjC1) {
101    LangTag = llvm::dwarf::DW_LANG_ObjC;
102  } else if (LO.C99) {
103    LangTag = llvm::dwarf::DW_LANG_C99;
104  } else {
105    LangTag = llvm::dwarf::DW_LANG_C89;
106  }
107
108  std::string Producer = "clang " CLANG_VERSION_STRING;
109  bool isOptimized = LO.Optimize;
110  const char *Flags = "";   // FIXME: Encode command line options.
111
112  // Figure out which version of the ObjC runtime we have.
113  unsigned RuntimeVers = 0;
114  if (LO.ObjC1)
115    RuntimeVers = LO.ObjCNonFragileABI ? 2 : 1;
116
117  // Create new compile unit.
118  return Unit = DebugFactory.CreateCompileUnit(LangTag, AbsFileName.getLast(),
119                                               AbsFileName.getDirname(),
120                                               Producer, isMain, isOptimized,
121                                               Flags, RuntimeVers);
122}
123
124/// CreateType - Get the Basic type from the cache or create a new
125/// one if necessary.
126llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT,
127                                     llvm::DICompileUnit Unit) {
128  unsigned Encoding = 0;
129  switch (BT->getKind()) {
130  default:
131  case BuiltinType::Void:
132    return llvm::DIType();
133  case BuiltinType::UChar:
134  case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
135  case BuiltinType::Char_S:
136  case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
137  case BuiltinType::UShort:
138  case BuiltinType::UInt:
139  case BuiltinType::ULong:
140  case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
141  case BuiltinType::Short:
142  case BuiltinType::Int:
143  case BuiltinType::Long:
144  case BuiltinType::LongLong:  Encoding = llvm::dwarf::DW_ATE_signed; break;
145  case BuiltinType::Bool:      Encoding = llvm::dwarf::DW_ATE_boolean; break;
146  case BuiltinType::Float:
147  case BuiltinType::Double:    Encoding = llvm::dwarf::DW_ATE_float; break;
148  }
149  // Bit size, align and offset of the type.
150  uint64_t Size = M->getContext().getTypeSize(BT);
151  uint64_t Align = M->getContext().getTypeAlign(BT);
152  uint64_t Offset = 0;
153
154  return DebugFactory.CreateBasicType(Unit,
155                                  BT->getName(M->getContext().getLangOptions()),
156                                      Unit, 0, Size, Align,
157                                      Offset, /*flags*/ 0, Encoding);
158}
159
160llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty,
161                                     llvm::DICompileUnit Unit) {
162  // Bit size, align and offset of the type.
163  unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
164  if (Ty->isComplexIntegerType())
165    Encoding = llvm::dwarf::DW_ATE_lo_user;
166
167  uint64_t Size = M->getContext().getTypeSize(Ty);
168  uint64_t Align = M->getContext().getTypeAlign(Ty);
169  uint64_t Offset = 0;
170
171  return DebugFactory.CreateBasicType(Unit, "complex",
172                                      Unit, 0, Size, Align,
173                                      Offset, /*flags*/ 0, Encoding);
174}
175
176/// getOrCreateCVRType - Get the CVR qualified type from the cache or create
177/// a new one if necessary.
178llvm::DIType CGDebugInfo::CreateCVRType(QualType Ty, llvm::DICompileUnit Unit) {
179  // We will create one Derived type for one qualifier and recurse to handle any
180  // additional ones.
181  llvm::DIType FromTy;
182  unsigned Tag;
183  if (Ty.isConstQualified()) {
184    Tag = llvm::dwarf::DW_TAG_const_type;
185    Ty.removeConst();
186    FromTy = getOrCreateType(Ty, Unit);
187  } else if (Ty.isVolatileQualified()) {
188    Tag = llvm::dwarf::DW_TAG_volatile_type;
189    Ty.removeVolatile();
190    FromTy = getOrCreateType(Ty, Unit);
191  } else {
192    assert(Ty.isRestrictQualified() && "Unknown type qualifier for debug info");
193    Tag = llvm::dwarf::DW_TAG_restrict_type;
194    Ty.removeRestrict();
195    FromTy = getOrCreateType(Ty, Unit);
196  }
197
198  // No need to fill in the Name, Line, Size, Alignment, Offset in case of
199  // CVR derived types.
200  return DebugFactory.CreateDerivedType(Tag, Unit, "", llvm::DICompileUnit(),
201                                        0, 0, 0, 0, 0, FromTy);
202}
203
204llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
205                                     llvm::DICompileUnit Unit) {
206  llvm::DIType EltTy = getOrCreateType(Ty->getPointeeType(), Unit);
207
208  // Bit size, align and offset of the type.
209  uint64_t Size = M->getContext().getTypeSize(Ty);
210  uint64_t Align = M->getContext().getTypeAlign(Ty);
211
212  return DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, Unit,
213                                        "", llvm::DICompileUnit(),
214                                        0, Size, Align, 0, 0, EltTy);
215}
216
217llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
218                                     llvm::DICompileUnit Unit) {
219  llvm::DIType EltTy = getOrCreateType(Ty->getPointeeType(), Unit);
220
221  // Bit size, align and offset of the type.
222  uint64_t Size = M->getContext().getTypeSize(Ty);
223  uint64_t Align = M->getContext().getTypeAlign(Ty);
224
225  return DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, Unit,
226                                        "", llvm::DICompileUnit(),
227                                        0, Size, Align, 0, 0, EltTy);
228}
229
230llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
231                                     llvm::DICompileUnit Unit) {
232  if (BlockLiteralGenericSet)
233    return BlockLiteralGeneric;
234
235  llvm::DICompileUnit DefUnit;
236  unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
237
238  llvm::SmallVector<llvm::DIDescriptor, 5> EltTys;
239
240  llvm::DIType FieldTy;
241
242  QualType FType;
243  uint64_t FieldSize, FieldOffset;
244  unsigned FieldAlign;
245
246  llvm::DIArray Elements;
247  llvm::DIType EltTy, DescTy;
248
249  FieldOffset = 0;
250  FType = M->getContext().UnsignedLongTy;
251  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
252  FieldSize = M->getContext().getTypeSize(FType);
253  FieldAlign = M->getContext().getTypeAlign(FType);
254  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
255                                           "reserved", DefUnit,
256                                           0, FieldSize, FieldAlign,
257                                           FieldOffset, 0, FieldTy);
258  EltTys.push_back(FieldTy);
259
260  FieldOffset += FieldSize;
261  FType = M->getContext().UnsignedLongTy;
262  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
263  FieldSize = M->getContext().getTypeSize(FType);
264  FieldAlign = M->getContext().getTypeAlign(FType);
265  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
266                                           "Size", DefUnit,
267                                           0, FieldSize, FieldAlign,
268                                           FieldOffset, 0, FieldTy);
269  EltTys.push_back(FieldTy);
270
271  FieldOffset += FieldSize;
272  Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
273  EltTys.clear();
274
275  EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_descriptor",
276                                           DefUnit, 0, FieldOffset, 0, 0, 0,
277                                           llvm::DIType(), Elements);
278
279  // Bit size, align and offset of the type.
280  uint64_t Size = M->getContext().getTypeSize(Ty);
281  uint64_t Align = M->getContext().getTypeAlign(Ty);
282
283  DescTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
284                                          Unit, "", llvm::DICompileUnit(),
285                                          0, Size, Align, 0, 0, EltTy);
286
287  FieldOffset = 0;
288  FType = M->getContext().getPointerType(M->getContext().VoidTy);
289  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
290  FieldSize = M->getContext().getTypeSize(FType);
291  FieldAlign = M->getContext().getTypeAlign(FType);
292  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
293                                           "__isa", DefUnit,
294                                           0, FieldSize, FieldAlign,
295                                           FieldOffset, 0, FieldTy);
296  EltTys.push_back(FieldTy);
297
298  FieldOffset += FieldSize;
299  FType = M->getContext().IntTy;
300  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
301  FieldSize = M->getContext().getTypeSize(FType);
302  FieldAlign = M->getContext().getTypeAlign(FType);
303  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
304                                           "__flags", DefUnit,
305                                           0, FieldSize, FieldAlign,
306                                           FieldOffset, 0, FieldTy);
307  EltTys.push_back(FieldTy);
308
309  FieldOffset += FieldSize;
310  FType = M->getContext().IntTy;
311  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
312  FieldSize = M->getContext().getTypeSize(FType);
313  FieldAlign = M->getContext().getTypeAlign(FType);
314  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
315                                           "__reserved", DefUnit,
316                                           0, FieldSize, FieldAlign,
317                                           FieldOffset, 0, FieldTy);
318  EltTys.push_back(FieldTy);
319
320  FieldOffset += FieldSize;
321  FType = M->getContext().getPointerType(M->getContext().VoidTy);
322  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
323  FieldSize = M->getContext().getTypeSize(FType);
324  FieldAlign = M->getContext().getTypeAlign(FType);
325  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
326                                           "__FuncPtr", DefUnit,
327                                           0, FieldSize, FieldAlign,
328                                           FieldOffset, 0, FieldTy);
329  EltTys.push_back(FieldTy);
330
331  FieldOffset += FieldSize;
332  FType = M->getContext().getPointerType(M->getContext().VoidTy);
333  FieldTy = DescTy;
334  FieldSize = M->getContext().getTypeSize(Ty);
335  FieldAlign = M->getContext().getTypeAlign(Ty);
336  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
337                                           "__descriptor", DefUnit,
338                                           0, FieldSize, FieldAlign,
339                                           FieldOffset, 0, FieldTy);
340  EltTys.push_back(FieldTy);
341
342  FieldOffset += FieldSize;
343  Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
344
345  EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_literal_generic",
346                                           DefUnit, 0, FieldOffset, 0, 0, 0,
347                                           llvm::DIType(), Elements);
348
349  BlockLiteralGenericSet = true;
350  BlockLiteralGeneric
351    = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, Unit,
352                                     "", llvm::DICompileUnit(),
353                                     0, Size, Align, 0, 0, EltTy);
354  return BlockLiteralGeneric;
355}
356
357llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty,
358                                     llvm::DICompileUnit Unit) {
359  // Typedefs are derived from some other type.  If we have a typedef of a
360  // typedef, make sure to emit the whole chain.
361  llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
362
363  // We don't set size information, but do specify where the typedef was
364  // declared.
365  std::string TyName = Ty->getDecl()->getNameAsString();
366  SourceLocation DefLoc = Ty->getDecl()->getLocation();
367  llvm::DICompileUnit DefUnit = getOrCreateCompileUnit(DefLoc);
368
369  SourceManager &SM = M->getContext().getSourceManager();
370  PresumedLoc PLoc = SM.getPresumedLoc(DefLoc);
371  unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
372
373  return DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_typedef, Unit,
374                                        TyName, DefUnit, Line, 0, 0, 0, 0, Src);
375}
376
377llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
378                                     llvm::DICompileUnit Unit) {
379  llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
380
381  // Add the result type at least.
382  EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
383
384  // Set up remainder of arguments if there is a prototype.
385  // FIXME: IF NOT, HOW IS THIS REPRESENTED?  llvm-gcc doesn't represent '...'!
386  if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(Ty)) {
387    for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
388      EltTys.push_back(getOrCreateType(FTP->getArgType(i), Unit));
389  } else {
390    // FIXME: Handle () case in C.  llvm-gcc doesn't do it either.
391  }
392
393  llvm::DIArray EltTypeArray =
394    DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
395
396  return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
397                                          Unit, "", llvm::DICompileUnit(),
398                                          0, 0, 0, 0, 0,
399                                          llvm::DIType(), EltTypeArray);
400}
401
402/// CreateType - get structure or union type.
403llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty,
404                                     llvm::DICompileUnit Unit) {
405  RecordDecl *Decl = Ty->getDecl();
406
407  unsigned Tag;
408  if (Decl->isStruct())
409    Tag = llvm::dwarf::DW_TAG_structure_type;
410  else if (Decl->isUnion())
411    Tag = llvm::dwarf::DW_TAG_union_type;
412  else {
413    assert(Decl->isClass() && "Unknown RecordType!");
414    Tag = llvm::dwarf::DW_TAG_class_type;
415  }
416
417  SourceManager &SM = M->getContext().getSourceManager();
418
419  // Get overall information about the record type for the debug info.
420  std::string Name = Decl->getNameAsString();
421
422  PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
423  llvm::DICompileUnit DefUnit;
424  unsigned Line = 0;
425  if (!PLoc.isInvalid()) {
426    DefUnit = getOrCreateCompileUnit(Decl->getLocation());
427    Line = PLoc.getLine();
428  }
429
430  // Records and classes and unions can all be recursive.  To handle them, we
431  // first generate a debug descriptor for the struct as a forward declaration.
432  // Then (if it is a definition) we go through and get debug info for all of
433  // its members.  Finally, we create a descriptor for the complete type (which
434  // may refer to the forward decl if the struct is recursive) and replace all
435  // uses of the forward declaration with the final definition.
436  llvm::DICompositeType FwdDecl =
437    DebugFactory.CreateCompositeType(Tag, Unit, Name, DefUnit, Line, 0, 0, 0, 0,
438                                     llvm::DIType(), llvm::DIArray());
439
440  // If this is just a forward declaration, return it.
441  if (!Decl->getDefinition(M->getContext()))
442    return FwdDecl;
443
444  // Otherwise, insert it into the TypeCache so that recursive uses will find
445  // it.
446  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl.getNode();
447
448  // Convert all the elements.
449  llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
450
451  const ASTRecordLayout &RL = M->getContext().getASTRecordLayout(Decl);
452
453  unsigned FieldNo = 0;
454  for (RecordDecl::field_iterator I = Decl->field_begin(),
455                                  E = Decl->field_end();
456       I != E; ++I, ++FieldNo) {
457    FieldDecl *Field = *I;
458    llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
459
460    std::string FieldName = Field->getNameAsString();
461
462    // Ignore unnamed fields.
463    if (FieldName.empty())
464      continue;
465
466    // Get the location for the field.
467    SourceLocation FieldDefLoc = Field->getLocation();
468    PresumedLoc PLoc = SM.getPresumedLoc(FieldDefLoc);
469    llvm::DICompileUnit FieldDefUnit;
470    unsigned FieldLine = 0;
471
472    if (!PLoc.isInvalid()) {
473      FieldDefUnit = getOrCreateCompileUnit(FieldDefLoc);
474      FieldLine = PLoc.getLine();
475    }
476
477    QualType FType = Field->getType();
478    uint64_t FieldSize = 0;
479    unsigned FieldAlign = 0;
480    if (!FType->isIncompleteArrayType()) {
481
482      // Bit size, align and offset of the type.
483      FieldSize = M->getContext().getTypeSize(FType);
484      Expr *BitWidth = Field->getBitWidth();
485      if (BitWidth)
486        FieldSize = BitWidth->EvaluateAsInt(M->getContext()).getZExtValue();
487
488      FieldAlign =  M->getContext().getTypeAlign(FType);
489    }
490
491    uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
492
493    // Create a DW_TAG_member node to remember the offset of this field in the
494    // struct.  FIXME: This is an absolutely insane way to capture this
495    // information.  When we gut debug info, this should be fixed.
496    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
497                                             FieldName, FieldDefUnit,
498                                             FieldLine, FieldSize, FieldAlign,
499                                             FieldOffset, 0, FieldTy);
500    EltTys.push_back(FieldTy);
501  }
502
503  llvm::DIArray Elements =
504    DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
505
506  // Bit size, align and offset of the type.
507  uint64_t Size = M->getContext().getTypeSize(Ty);
508  uint64_t Align = M->getContext().getTypeAlign(Ty);
509
510  llvm::DICompositeType RealDecl =
511    DebugFactory.CreateCompositeType(Tag, Unit, Name, DefUnit, Line, Size,
512                                     Align, 0, 0, llvm::DIType(), Elements);
513
514  // Update TypeCache.
515  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl.getNode();
516
517  // Now that we have a real decl for the struct, replace anything using the
518  // old decl with the new one.  This will recursively update the debug info.
519  FwdDecl.replaceAllUsesWith(RealDecl);
520
521  return RealDecl;
522}
523
524/// CreateType - get objective-c interface type.
525llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
526                                     llvm::DICompileUnit Unit) {
527  ObjCInterfaceDecl *Decl = Ty->getDecl();
528
529  unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
530  SourceManager &SM = M->getContext().getSourceManager();
531
532  // Get overall information about the record type for the debug info.
533  std::string Name = Decl->getNameAsString();
534
535  llvm::DICompileUnit DefUnit = getOrCreateCompileUnit(Decl->getLocation());
536  PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
537  unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
538
539
540  unsigned RuntimeLang = DefUnit.getLanguage();
541
542  // To handle recursive interface, we
543  // first generate a debug descriptor for the struct as a forward declaration.
544  // Then (if it is a definition) we go through and get debug info for all of
545  // its members.  Finally, we create a descriptor for the complete type (which
546  // may refer to the forward decl if the struct is recursive) and replace all
547  // uses of the forward declaration with the final definition.
548  llvm::DICompositeType FwdDecl =
549    DebugFactory.CreateCompositeType(Tag, Unit, Name, DefUnit, Line, 0, 0, 0, 0,
550                                     llvm::DIType(), llvm::DIArray(),
551                                     RuntimeLang);
552
553  // If this is just a forward declaration, return it.
554  if (Decl->isForwardDecl())
555    return FwdDecl;
556
557  // Otherwise, insert it into the TypeCache so that recursive uses will find
558  // it.
559  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl.getNode();
560
561  // Convert all the elements.
562  llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
563
564  ObjCInterfaceDecl *SClass = Decl->getSuperClass();
565  if (SClass) {
566    llvm::DIType SClassTy =
567      getOrCreateType(M->getContext().getObjCInterfaceType(SClass), Unit);
568    llvm::DIType InhTag =
569      DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_inheritance,
570                                     Unit, "", llvm::DICompileUnit(), 0, 0, 0,
571                                     0 /* offset */, 0, SClassTy);
572    EltTys.push_back(InhTag);
573  }
574
575  const ASTRecordLayout &RL = M->getContext().getASTObjCInterfaceLayout(Decl);
576
577  unsigned FieldNo = 0;
578  for (ObjCInterfaceDecl::ivar_iterator I = Decl->ivar_begin(),
579         E = Decl->ivar_end();  I != E; ++I, ++FieldNo) {
580    ObjCIvarDecl *Field = *I;
581    llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
582
583    std::string FieldName = Field->getNameAsString();
584
585    // Ignore unnamed fields.
586    if (FieldName.empty())
587      continue;
588
589    // Get the location for the field.
590    SourceLocation FieldDefLoc = Field->getLocation();
591    llvm::DICompileUnit FieldDefUnit = getOrCreateCompileUnit(FieldDefLoc);
592    PresumedLoc PLoc = SM.getPresumedLoc(FieldDefLoc);
593    unsigned FieldLine = PLoc.isInvalid() ? 0 : PLoc.getLine();
594
595
596    QualType FType = Field->getType();
597    uint64_t FieldSize = 0;
598    unsigned FieldAlign = 0;
599
600    if (!FType->isIncompleteArrayType()) {
601
602      // Bit size, align and offset of the type.
603      FieldSize = M->getContext().getTypeSize(FType);
604      Expr *BitWidth = Field->getBitWidth();
605      if (BitWidth)
606        FieldSize = BitWidth->EvaluateAsInt(M->getContext()).getZExtValue();
607
608      FieldAlign =  M->getContext().getTypeAlign(FType);
609    }
610
611    uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
612
613    unsigned Flags = 0;
614    if (Field->getAccessControl() == ObjCIvarDecl::Protected)
615      Flags = llvm::DIType::FlagProtected;
616    else if (Field->getAccessControl() == ObjCIvarDecl::Private)
617      Flags = llvm::DIType::FlagPrivate;
618
619    // Create a DW_TAG_member node to remember the offset of this field in the
620    // struct.  FIXME: This is an absolutely insane way to capture this
621    // information.  When we gut debug info, this should be fixed.
622    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
623                                             FieldName, FieldDefUnit,
624                                             FieldLine, FieldSize, FieldAlign,
625                                             FieldOffset, Flags, FieldTy);
626    EltTys.push_back(FieldTy);
627  }
628
629  llvm::DIArray Elements =
630    DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
631
632  // Bit size, align and offset of the type.
633  uint64_t Size = M->getContext().getTypeSize(Ty);
634  uint64_t Align = M->getContext().getTypeAlign(Ty);
635
636  llvm::DICompositeType RealDecl =
637    DebugFactory.CreateCompositeType(Tag, Unit, Name, DefUnit, Line, Size,
638                                     Align, 0, 0, llvm::DIType(), Elements,
639                                     RuntimeLang);
640
641  // Update TypeCache.
642  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl.getNode();
643
644  // Now that we have a real decl for the struct, replace anything using the
645  // old decl with the new one.  This will recursively update the debug info.
646  FwdDecl.replaceAllUsesWith(RealDecl);
647
648  return RealDecl;
649}
650
651llvm::DIType CGDebugInfo::CreateType(const EnumType *Ty,
652                                     llvm::DICompileUnit Unit) {
653  EnumDecl *Decl = Ty->getDecl();
654
655  llvm::SmallVector<llvm::DIDescriptor, 32> Enumerators;
656
657  // Create DIEnumerator elements for each enumerator.
658  for (EnumDecl::enumerator_iterator
659         Enum = Decl->enumerator_begin(), EnumEnd = Decl->enumerator_end();
660       Enum != EnumEnd; ++Enum) {
661    Enumerators.push_back(DebugFactory.CreateEnumerator(Enum->getNameAsString(),
662                                            Enum->getInitVal().getZExtValue()));
663  }
664
665  // Return a CompositeType for the enum itself.
666  llvm::DIArray EltArray =
667    DebugFactory.GetOrCreateArray(Enumerators.data(), Enumerators.size());
668
669  std::string EnumName = Decl->getNameAsString();
670  SourceLocation DefLoc = Decl->getLocation();
671  llvm::DICompileUnit DefUnit = getOrCreateCompileUnit(DefLoc);
672  SourceManager &SM = M->getContext().getSourceManager();
673  PresumedLoc PLoc = SM.getPresumedLoc(DefLoc);
674  unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
675
676
677  // Size and align of the type.
678  uint64_t Size = 0;
679  unsigned Align = 0;
680  if (!Ty->isIncompleteType()) {
681    Size = M->getContext().getTypeSize(Ty);
682    Align = M->getContext().getTypeAlign(Ty);
683  }
684
685  return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_enumeration_type,
686                                          Unit, EnumName, DefUnit, Line,
687                                          Size, Align, 0, 0,
688                                          llvm::DIType(), EltArray);
689}
690
691llvm::DIType CGDebugInfo::CreateType(const TagType *Ty,
692                                     llvm::DICompileUnit Unit) {
693  if (const RecordType *RT = dyn_cast<RecordType>(Ty))
694    return CreateType(RT, Unit);
695  else if (const EnumType *ET = dyn_cast<EnumType>(Ty))
696    return CreateType(ET, Unit);
697
698  return llvm::DIType();
699}
700
701llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
702                                     llvm::DICompileUnit Unit) {
703  uint64_t Size;
704  uint64_t Align;
705
706
707  // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
708  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
709    Size = 0;
710    Align =
711      M->getContext().getTypeAlign(M->getContext().getBaseElementType(VAT));
712  } else if (Ty->isIncompleteArrayType()) {
713    Size = 0;
714    Align = M->getContext().getTypeAlign(Ty->getElementType());
715  } else {
716    // Size and align of the whole array, not the element type.
717    Size = M->getContext().getTypeSize(Ty);
718    Align = M->getContext().getTypeAlign(Ty);
719  }
720
721  // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
722  // interior arrays, do we care?  Why aren't nested arrays represented the
723  // obvious/recursive way?
724  llvm::SmallVector<llvm::DIDescriptor, 8> Subscripts;
725  QualType EltTy(Ty, 0);
726  while ((Ty = dyn_cast<ArrayType>(EltTy))) {
727    uint64_t Upper = 0;
728    if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
729      if (CAT->getSize().getZExtValue())
730        Upper = CAT->getSize().getZExtValue() - 1;
731    // FIXME: Verify this is right for VLAs.
732    Subscripts.push_back(DebugFactory.GetOrCreateSubrange(0, Upper));
733    EltTy = Ty->getElementType();
734  }
735
736  llvm::DIArray SubscriptArray =
737    DebugFactory.GetOrCreateArray(Subscripts.data(), Subscripts.size());
738
739  return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_array_type,
740                                          Unit, "", llvm::DICompileUnit(),
741                                          0, Size, Align, 0, 0,
742                                          getOrCreateType(EltTy, Unit),
743                                          SubscriptArray);
744}
745
746
747/// getOrCreateType - Get the type from the cache or create a new
748/// one if necessary.
749llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty,
750                                          llvm::DICompileUnit Unit) {
751  if (Ty.isNull())
752    return llvm::DIType();
753
754  // Check for existing entry.
755  std::map<void *, llvm::AssertingVH<llvm::MDNode> >::iterator it =
756    TypeCache.find(Ty.getAsOpaquePtr());
757  if (it != TypeCache.end())
758    return llvm::DIType(it->second);
759
760  // Otherwise create the type.
761  llvm::DIType Res = CreateTypeNode(Ty, Unit);
762  TypeCache.insert(std::make_pair(Ty.getAsOpaquePtr(), Res.getNode()));
763  return Res;
764}
765
766/// getOrCreateTypeNode - Get the type metadata node from the cache or create a
767/// new one if necessary.
768llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty,
769                                         llvm::DICompileUnit Unit) {
770  // Handle CVR qualifiers, which recursively handles what they refer to.
771  if (Ty.getCVRQualifiers())
772    return CreateCVRType(Ty, Unit);
773
774  // Work out details of type.
775  switch (Ty->getTypeClass()) {
776#define TYPE(Class, Base)
777#define ABSTRACT_TYPE(Class, Base)
778#define NON_CANONICAL_TYPE(Class, Base)
779#define DEPENDENT_TYPE(Class, Base) case Type::Class:
780#include "clang/AST/TypeNodes.def"
781    assert(false && "Dependent types cannot show up in debug information");
782
783  default:
784  case Type::LValueReference:
785  case Type::RValueReference:
786  case Type::Vector:
787  case Type::ExtVector:
788  case Type::ExtQual:
789  case Type::FixedWidthInt:
790  case Type::MemberPointer:
791  case Type::TemplateSpecialization:
792  case Type::QualifiedName:
793    // Unsupported types
794    return llvm::DIType();
795  case Type::ObjCObjectPointer:
796    return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
797  case Type::ObjCInterface:
798    return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
799  case Type::Builtin: return CreateType(cast<BuiltinType>(Ty), Unit);
800  case Type::Complex: return CreateType(cast<ComplexType>(Ty), Unit);
801  case Type::Pointer: return CreateType(cast<PointerType>(Ty), Unit);
802  case Type::BlockPointer:
803    return CreateType(cast<BlockPointerType>(Ty), Unit);
804  case Type::Typedef: return CreateType(cast<TypedefType>(Ty), Unit);
805  case Type::Record:
806  case Type::Enum:
807    return CreateType(cast<TagType>(Ty), Unit);
808  case Type::FunctionProto:
809  case Type::FunctionNoProto:
810    return CreateType(cast<FunctionType>(Ty), Unit);
811  case Type::Elaborated:
812    return getOrCreateType(cast<ElaboratedType>(Ty)->getUnderlyingType(),
813                           Unit);
814
815  case Type::ConstantArray:
816  case Type::ConstantArrayWithExpr:
817  case Type::ConstantArrayWithoutExpr:
818  case Type::VariableArray:
819  case Type::IncompleteArray:
820    return CreateType(cast<ArrayType>(Ty), Unit);
821  case Type::TypeOfExpr:
822    return getOrCreateType(cast<TypeOfExprType>(Ty)->getUnderlyingExpr()
823                           ->getType(), Unit);
824  case Type::TypeOf:
825    return getOrCreateType(cast<TypeOfType>(Ty)->getUnderlyingType(), Unit);
826  case Type::Decltype:
827    return getOrCreateType(cast<DecltypeType>(Ty)->getUnderlyingType(), Unit);
828  }
829}
830
831/// EmitFunctionStart - Constructs the debug code for entering a function -
832/// "llvm.dbg.func.start.".
833void CGDebugInfo::EmitFunctionStart(const char *Name, QualType ReturnType,
834                                    llvm::Function *Fn,
835                                    CGBuilderTy &Builder) {
836  const char *LinkageName = Name;
837
838  // Skip the asm prefix if it exists.
839  //
840  // FIXME: This should probably be the unmangled name?
841  if (Name[0] == '\01')
842    ++Name;
843
844  // FIXME: Why is this using CurLoc???
845  llvm::DICompileUnit Unit = getOrCreateCompileUnit(CurLoc);
846  SourceManager &SM = M->getContext().getSourceManager();
847  unsigned LineNo = SM.getPresumedLoc(CurLoc).getLine();
848
849  llvm::DISubprogram SP =
850    DebugFactory.CreateSubprogram(Unit, Name, Name, LinkageName, Unit, LineNo,
851                                  getOrCreateType(ReturnType, Unit),
852                                  Fn->hasInternalLinkage(), true/*definition*/);
853
854  DebugFactory.InsertSubprogramStart(SP, Builder.GetInsertBlock());
855
856  // Push function on region stack.
857  RegionStack.push_back(SP);
858}
859
860
861void CGDebugInfo::EmitStopPoint(llvm::Function *Fn, CGBuilderTy &Builder) {
862  if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
863
864  // Don't bother if things are the same as last time.
865  SourceManager &SM = M->getContext().getSourceManager();
866  if (CurLoc == PrevLoc
867       || (SM.getInstantiationLineNumber(CurLoc) ==
868           SM.getInstantiationLineNumber(PrevLoc)
869           && SM.isFromSameFile(CurLoc, PrevLoc)))
870    return;
871
872  // Update last state.
873  PrevLoc = CurLoc;
874
875  // Get the appropriate compile unit.
876  llvm::DICompileUnit Unit = getOrCreateCompileUnit(CurLoc);
877  PresumedLoc PLoc = SM.getPresumedLoc(CurLoc);
878  DebugFactory.InsertStopPoint(Unit, PLoc.getLine(), PLoc.getColumn(),
879                               Builder.GetInsertBlock());
880}
881
882/// EmitRegionStart- Constructs the debug code for entering a declarative
883/// region - "llvm.dbg.region.start.".
884void CGDebugInfo::EmitRegionStart(llvm::Function *Fn, CGBuilderTy &Builder) {
885  llvm::DIDescriptor D;
886  if (!RegionStack.empty())
887    D = RegionStack.back();
888  D = DebugFactory.CreateLexicalBlock(D);
889  RegionStack.push_back(D);
890  DebugFactory.InsertRegionStart(D, Builder.GetInsertBlock());
891}
892
893/// EmitRegionEnd - Constructs the debug code for exiting a declarative
894/// region - "llvm.dbg.region.end."
895void CGDebugInfo::EmitRegionEnd(llvm::Function *Fn, CGBuilderTy &Builder) {
896  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
897
898  // Provide an region stop point.
899  EmitStopPoint(Fn, Builder);
900
901  DebugFactory.InsertRegionEnd(RegionStack.back(), Builder.GetInsertBlock());
902  RegionStack.pop_back();
903}
904
905/// EmitDeclare - Emit local variable declaration debug info.
906void CGDebugInfo::EmitDeclare(const VarDecl *Decl, unsigned Tag,
907                              llvm::Value *Storage, CGBuilderTy &Builder) {
908  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
909
910  // Do not emit variable debug information while generating optimized code.
911  // The llvm optimizer and code generator are not yet ready to support
912  // optimized code debugging.
913  const CompileOptions &CO = M->getCompileOpts();
914  if (CO.OptimizationLevel)
915    return;
916
917  llvm::DICompileUnit Unit = getOrCreateCompileUnit(Decl->getLocation());
918  llvm::DIType Ty = getOrCreateType(Decl->getType(), Unit);
919
920  // Get location information.
921  SourceManager &SM = M->getContext().getSourceManager();
922  PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
923  unsigned Line = 0;
924  if (!PLoc.isInvalid())
925    Line = PLoc.getLine();
926  else
927    Unit = llvm::DICompileUnit();
928
929
930  // Create the descriptor for the variable.
931  llvm::DIVariable D =
932    DebugFactory.CreateVariable(Tag, RegionStack.back(),Decl->getNameAsString(),
933                                Unit, Line, Ty);
934  // Insert an llvm.dbg.declare into the current block.
935  DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock());
936}
937
938void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *Decl,
939                                            llvm::Value *Storage,
940                                            CGBuilderTy &Builder) {
941  EmitDeclare(Decl, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder);
942}
943
944/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
945/// variable declaration.
946void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *Decl, llvm::Value *AI,
947                                           CGBuilderTy &Builder) {
948  EmitDeclare(Decl, llvm::dwarf::DW_TAG_arg_variable, AI, Builder);
949}
950
951
952
953/// EmitGlobalVariable - Emit information about a global variable.
954void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
955                                     const VarDecl *Decl) {
956
957  // Do not emit variable debug information while generating optimized code.
958  // The llvm optimizer and code generator are not yet ready to support
959  // optimized code debugging.
960  const CompileOptions &CO = M->getCompileOpts();
961  if (CO.OptimizationLevel)
962    return;
963
964  // Create global variable debug descriptor.
965  llvm::DICompileUnit Unit = getOrCreateCompileUnit(Decl->getLocation());
966  SourceManager &SM = M->getContext().getSourceManager();
967  PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
968  unsigned LineNo = PLoc.isInvalid() ? 0 : PLoc.getLine();
969
970  std::string Name = Decl->getNameAsString();
971
972  QualType T = Decl->getType();
973  if (T->isIncompleteArrayType()) {
974
975    // CodeGen turns int[] into int[1] so we'll do the same here.
976    llvm::APSInt ConstVal(32);
977
978    ConstVal = 1;
979    QualType ET = M->getContext().getAsArrayType(T)->getElementType();
980
981    T = M->getContext().getConstantArrayType(ET, ConstVal,
982                                           ArrayType::Normal, 0);
983  }
984
985  DebugFactory.CreateGlobalVariable(Unit, Name, Name, "", Unit, LineNo,
986                                    getOrCreateType(T, Unit),
987                                    Var->hasInternalLinkage(),
988                                    true/*definition*/, Var);
989}
990
991/// EmitGlobalVariable - Emit information about an objective-c interface.
992void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
993                                     ObjCInterfaceDecl *Decl) {
994  // Create global variable debug descriptor.
995  llvm::DICompileUnit Unit = getOrCreateCompileUnit(Decl->getLocation());
996  SourceManager &SM = M->getContext().getSourceManager();
997  PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
998  unsigned LineNo = PLoc.isInvalid() ? 0 : PLoc.getLine();
999
1000  std::string Name = Decl->getNameAsString();
1001
1002  QualType T = M->getContext().getObjCInterfaceType(Decl);
1003  if (T->isIncompleteArrayType()) {
1004
1005    // CodeGen turns int[] into int[1] so we'll do the same here.
1006    llvm::APSInt ConstVal(32);
1007
1008    ConstVal = 1;
1009    QualType ET = M->getContext().getAsArrayType(T)->getElementType();
1010
1011    T = M->getContext().getConstantArrayType(ET, ConstVal,
1012                                           ArrayType::Normal, 0);
1013  }
1014
1015  DebugFactory.CreateGlobalVariable(Unit, Name, Name, "", Unit, LineNo,
1016                                    getOrCreateType(T, Unit),
1017                                    Var->hasInternalLinkage(),
1018                                    true/*definition*/, Var);
1019}
1020