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