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