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