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