CGDebugInfo.cpp revision bea9b2375a6c5c121dcd83d4f2d544803bacd962
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/CodeGen/CodeGenOptions.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 &CGM)
39  : CGM(CGM), isMainCompileUnitCreated(false), DebugFactory(CGM.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 = CGM.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/// getFunctionName - Get function name for the given FunctionDecl. If the
69/// name is constructred on demand (e.g. C++ destructor) then the name
70/// is stored on the side.
71llvm::StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
72  assert (FD && "Invalid FunctionDecl!");
73  IdentifierInfo *FII = FD->getIdentifier();
74  if (FII)
75    return FII->getName();
76
77  // Otherwise construct human readable name for debug info.
78  std::string NS = FD->getNameAsString();
79
80  // Copy this name on the side and use its reference.
81  char *StrPtr = FunctionNames.Allocate<char>(NS.length());
82  memcpy(StrPtr, NS.data(), NS.length());
83  return llvm::StringRef(StrPtr, NS.length());
84}
85
86/// getOrCreateCompileUnit - Get the compile unit from the cache or create a new
87/// one if necessary. This returns null for invalid source locations.
88llvm::DICompileUnit CGDebugInfo::getOrCreateCompileUnit(SourceLocation Loc) {
89  // Get source file information.
90  const char *FileName =  "<unknown>";
91  SourceManager &SM = CGM.getContext().getSourceManager();
92  unsigned FID = 0;
93  if (Loc.isValid()) {
94    PresumedLoc PLoc = SM.getPresumedLoc(Loc);
95    FileName = PLoc.getFilename();
96    FID = PLoc.getIncludeLoc().getRawEncoding();
97  }
98
99  // See if this compile unit has been used before.
100  llvm::DICompileUnit &Unit = CompileUnitCache[FID];
101  if (!Unit.isNull()) return Unit;
102
103  // Get absolute path name.
104  llvm::sys::Path AbsFileName(FileName);
105  AbsFileName.makeAbsolute();
106
107  // See if thie compile unit is representing main source file. Each source
108  // file has corresponding compile unit. There is only one main source
109  // file at a time.
110  bool isMain = false;
111  const LangOptions &LO = CGM.getLangOptions();
112  const CodeGenOptions &CGO = CGM.getCodeGenOpts();
113  if (isMainCompileUnitCreated == false) {
114    if (!CGO.MainFileName.empty()) {
115      if (AbsFileName.getLast() == CGO.MainFileName)
116        isMain = true;
117    } else {
118      if (Loc.isValid() && SM.isFromMainFile(Loc))
119        isMain = true;
120    }
121    if (isMain)
122      isMainCompileUnitCreated = true;
123  }
124
125  unsigned LangTag;
126  if (LO.CPlusPlus) {
127    if (LO.ObjC1)
128      LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
129    else
130      LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
131  } else if (LO.ObjC1) {
132    LangTag = llvm::dwarf::DW_LANG_ObjC;
133  } else if (LO.C99) {
134    LangTag = llvm::dwarf::DW_LANG_C99;
135  } else {
136    LangTag = llvm::dwarf::DW_LANG_C89;
137  }
138
139  const char *Producer =
140#ifdef CLANG_VENDOR
141    CLANG_VENDOR
142#endif
143    "clang " CLANG_VERSION_STRING;
144
145  // Figure out which version of the ObjC runtime we have.
146  unsigned RuntimeVers = 0;
147  if (LO.ObjC1)
148    RuntimeVers = LO.ObjCNonFragileABI ? 2 : 1;
149
150  // Create new compile unit.
151  return Unit = DebugFactory.CreateCompileUnit(
152    LangTag, AbsFileName.getLast(), AbsFileName.getDirname(), Producer, isMain,
153    LO.Optimize, CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers);
154}
155
156/// CreateType - Get the Basic type from the cache or create a new
157/// one if necessary.
158llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT,
159                                     llvm::DICompileUnit Unit) {
160  unsigned Encoding = 0;
161  switch (BT->getKind()) {
162  default:
163  case BuiltinType::Void:
164    return llvm::DIType();
165  case BuiltinType::UChar:
166  case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
167  case BuiltinType::Char_S:
168  case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
169  case BuiltinType::UShort:
170  case BuiltinType::UInt:
171  case BuiltinType::ULong:
172  case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
173  case BuiltinType::Short:
174  case BuiltinType::Int:
175  case BuiltinType::Long:
176  case BuiltinType::LongLong:  Encoding = llvm::dwarf::DW_ATE_signed; break;
177  case BuiltinType::Bool:      Encoding = llvm::dwarf::DW_ATE_boolean; break;
178  case BuiltinType::Float:
179  case BuiltinType::LongDouble:
180  case BuiltinType::Double:    Encoding = llvm::dwarf::DW_ATE_float; break;
181  }
182  // Bit size, align and offset of the type.
183  uint64_t Size = CGM.getContext().getTypeSize(BT);
184  uint64_t Align = CGM.getContext().getTypeAlign(BT);
185  uint64_t Offset = 0;
186
187  llvm::DIType DbgTy =
188    DebugFactory.CreateBasicType(Unit,
189                                 BT->getName(CGM.getContext().getLangOptions()),
190                                 Unit, 0, Size, Align,
191                                 Offset, /*flags*/ 0, Encoding);
192  return DbgTy;
193}
194
195llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty,
196                                     llvm::DICompileUnit Unit) {
197  // Bit size, align and offset of the type.
198  unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
199  if (Ty->isComplexIntegerType())
200    Encoding = llvm::dwarf::DW_ATE_lo_user;
201
202  uint64_t Size = CGM.getContext().getTypeSize(Ty);
203  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
204  uint64_t Offset = 0;
205
206  llvm::DIType DbgTy =
207    DebugFactory.CreateBasicType(Unit, "complex",
208                                 Unit, 0, Size, Align,
209                                 Offset, /*flags*/ 0, Encoding);
210  return DbgTy;
211}
212
213/// CreateCVRType - Get the qualified type from the cache or create
214/// a new one if necessary.
215llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DICompileUnit Unit) {
216  QualifierCollector Qc;
217  const Type *T = Qc.strip(Ty);
218
219  // Ignore these qualifiers for now.
220  Qc.removeObjCGCAttr();
221  Qc.removeAddressSpace();
222
223  // We will create one Derived type for one qualifier and recurse to handle any
224  // additional ones.
225  unsigned Tag;
226  if (Qc.hasConst()) {
227    Tag = llvm::dwarf::DW_TAG_const_type;
228    Qc.removeConst();
229  } else if (Qc.hasVolatile()) {
230    Tag = llvm::dwarf::DW_TAG_volatile_type;
231    Qc.removeVolatile();
232  } else if (Qc.hasRestrict()) {
233    Tag = llvm::dwarf::DW_TAG_restrict_type;
234    Qc.removeRestrict();
235  } else {
236    assert(Qc.empty() && "Unknown type qualifier for debug info");
237    return getOrCreateType(QualType(T, 0), Unit);
238  }
239
240  llvm::DIType FromTy = getOrCreateType(Qc.apply(T), Unit);
241
242  // No need to fill in the Name, Line, Size, Alignment, Offset in case of
243  // CVR derived types.
244  llvm::DIType DbgTy =
245    DebugFactory.CreateDerivedType(Tag, Unit, "", llvm::DICompileUnit(),
246                                   0, 0, 0, 0, 0, FromTy);
247  return DbgTy;
248}
249
250llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
251                                     llvm::DICompileUnit Unit) {
252  llvm::DIType DbgTy =
253    CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
254                          Ty->getPointeeType(), Unit);
255  return DbgTy;
256}
257
258llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
259                                     llvm::DICompileUnit Unit) {
260  return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
261                               Ty->getPointeeType(), Unit);
262}
263
264llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
265                                                const Type *Ty,
266                                                QualType PointeeTy,
267                                                llvm::DICompileUnit Unit) {
268  llvm::DIType EltTy = getOrCreateType(PointeeTy, Unit);
269
270  // Bit size, align and offset of the type.
271
272  // Size is always the size of a pointer. We can't use getTypeSize here
273  // because that does not return the correct value for references.
274  uint64_t Size =
275    CGM.getContext().Target.getPointerWidth(PointeeTy.getAddressSpace());
276  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
277
278  return
279    DebugFactory.CreateDerivedType(Tag, Unit, "", llvm::DICompileUnit(),
280                                   0, Size, Align, 0, 0, EltTy);
281
282}
283
284llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
285                                     llvm::DICompileUnit Unit) {
286  if (BlockLiteralGenericSet)
287    return BlockLiteralGeneric;
288
289  llvm::DICompileUnit DefUnit;
290  unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
291
292  llvm::SmallVector<llvm::DIDescriptor, 5> EltTys;
293
294  llvm::DIType FieldTy;
295
296  QualType FType;
297  uint64_t FieldSize, FieldOffset;
298  unsigned FieldAlign;
299
300  llvm::DIArray Elements;
301  llvm::DIType EltTy, DescTy;
302
303  FieldOffset = 0;
304  FType = CGM.getContext().UnsignedLongTy;
305  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
306  FieldSize = CGM.getContext().getTypeSize(FType);
307  FieldAlign = CGM.getContext().getTypeAlign(FType);
308  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
309                                           "reserved", DefUnit,
310                                           0, FieldSize, FieldAlign,
311                                           FieldOffset, 0, FieldTy);
312  EltTys.push_back(FieldTy);
313
314  FieldOffset += FieldSize;
315  FType = CGM.getContext().UnsignedLongTy;
316  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
317  FieldSize = CGM.getContext().getTypeSize(FType);
318  FieldAlign = CGM.getContext().getTypeAlign(FType);
319  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
320                                           "Size", DefUnit,
321                                           0, FieldSize, FieldAlign,
322                                           FieldOffset, 0, FieldTy);
323  EltTys.push_back(FieldTy);
324
325  FieldOffset += FieldSize;
326  Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
327  EltTys.clear();
328
329  unsigned Flags = llvm::DIType::FlagAppleBlock;
330
331  EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_descriptor",
332                                           DefUnit, 0, FieldOffset, 0, 0, Flags,
333                                           llvm::DIType(), Elements);
334
335  // Bit size, align and offset of the type.
336  uint64_t Size = CGM.getContext().getTypeSize(Ty);
337  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
338
339  DescTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
340                                          Unit, "", llvm::DICompileUnit(),
341                                          0, Size, Align, 0, 0, EltTy);
342
343  FieldOffset = 0;
344  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
345  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
346  FieldSize = CGM.getContext().getTypeSize(FType);
347  FieldAlign = CGM.getContext().getTypeAlign(FType);
348  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
349                                           "__isa", DefUnit,
350                                           0, FieldSize, FieldAlign,
351                                           FieldOffset, 0, FieldTy);
352  EltTys.push_back(FieldTy);
353
354  FieldOffset += FieldSize;
355  FType = CGM.getContext().IntTy;
356  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
357  FieldSize = CGM.getContext().getTypeSize(FType);
358  FieldAlign = CGM.getContext().getTypeAlign(FType);
359  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
360                                           "__flags", DefUnit,
361                                           0, FieldSize, FieldAlign,
362                                           FieldOffset, 0, FieldTy);
363  EltTys.push_back(FieldTy);
364
365  FieldOffset += FieldSize;
366  FType = CGM.getContext().IntTy;
367  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
368  FieldSize = CGM.getContext().getTypeSize(FType);
369  FieldAlign = CGM.getContext().getTypeAlign(FType);
370  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
371                                           "__reserved", DefUnit,
372                                           0, FieldSize, FieldAlign,
373                                           FieldOffset, 0, FieldTy);
374  EltTys.push_back(FieldTy);
375
376  FieldOffset += FieldSize;
377  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
378  FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
379  FieldSize = CGM.getContext().getTypeSize(FType);
380  FieldAlign = CGM.getContext().getTypeAlign(FType);
381  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
382                                           "__FuncPtr", DefUnit,
383                                           0, FieldSize, FieldAlign,
384                                           FieldOffset, 0, FieldTy);
385  EltTys.push_back(FieldTy);
386
387  FieldOffset += FieldSize;
388  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
389  FieldTy = DescTy;
390  FieldSize = CGM.getContext().getTypeSize(Ty);
391  FieldAlign = CGM.getContext().getTypeAlign(Ty);
392  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
393                                           "__descriptor", DefUnit,
394                                           0, FieldSize, FieldAlign,
395                                           FieldOffset, 0, FieldTy);
396  EltTys.push_back(FieldTy);
397
398  FieldOffset += FieldSize;
399  Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
400
401  EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_literal_generic",
402                                           DefUnit, 0, FieldOffset, 0, 0, Flags,
403                                           llvm::DIType(), Elements);
404
405  BlockLiteralGenericSet = true;
406  BlockLiteralGeneric
407    = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, Unit,
408                                     "", llvm::DICompileUnit(),
409                                     0, Size, Align, 0, 0, EltTy);
410  return BlockLiteralGeneric;
411}
412
413llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty,
414                                     llvm::DICompileUnit Unit) {
415  // Typedefs are derived from some other type.  If we have a typedef of a
416  // typedef, make sure to emit the whole chain.
417  llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
418
419  // We don't set size information, but do specify where the typedef was
420  // declared.
421  SourceLocation DefLoc = Ty->getDecl()->getLocation();
422  llvm::DICompileUnit DefUnit = getOrCreateCompileUnit(DefLoc);
423
424  SourceManager &SM = CGM.getContext().getSourceManager();
425  PresumedLoc PLoc = SM.getPresumedLoc(DefLoc);
426  unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
427
428  llvm::DIType DbgTy =
429    DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_typedef, Unit,
430                                   Ty->getDecl()->getName(),
431                                   DefUnit, Line, 0, 0, 0, 0, Src);
432  return DbgTy;
433}
434
435llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
436                                     llvm::DICompileUnit Unit) {
437  llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
438
439  // Add the result type at least.
440  EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
441
442  // Set up remainder of arguments if there is a prototype.
443  // FIXME: IF NOT, HOW IS THIS REPRESENTED?  llvm-gcc doesn't represent '...'!
444  if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(Ty)) {
445    for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
446      EltTys.push_back(getOrCreateType(FTP->getArgType(i), Unit));
447  } else {
448    // FIXME: Handle () case in C.  llvm-gcc doesn't do it either.
449  }
450
451  llvm::DIArray EltTypeArray =
452    DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
453
454  llvm::DIType DbgTy =
455    DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
456                                     Unit, "", llvm::DICompileUnit(),
457                                     0, 0, 0, 0, 0,
458                                     llvm::DIType(), EltTypeArray);
459  return DbgTy;
460}
461
462/// CollectRecordFields - A helper function to collect debug info for
463/// record fields. This is used while creating debug info entry for a Record.
464void CGDebugInfo::
465CollectRecordFields(const RecordDecl *Decl,
466                    llvm::DICompileUnit Unit,
467                    llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys) {
468  unsigned FieldNo = 0;
469  SourceManager &SM = CGM.getContext().getSourceManager();
470  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(Decl);
471  for (RecordDecl::field_iterator I = Decl->field_begin(),
472                                  E = Decl->field_end();
473       I != E; ++I, ++FieldNo) {
474    FieldDecl *Field = *I;
475    llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
476
477    llvm::StringRef FieldName = Field->getName();
478
479    // Ignore unnamed fields.
480    if (FieldName.empty())
481      continue;
482
483    // Get the location for the field.
484    SourceLocation FieldDefLoc = Field->getLocation();
485    PresumedLoc PLoc = SM.getPresumedLoc(FieldDefLoc);
486    llvm::DICompileUnit FieldDefUnit;
487    unsigned FieldLine = 0;
488
489    if (!PLoc.isInvalid()) {
490      FieldDefUnit = getOrCreateCompileUnit(FieldDefLoc);
491      FieldLine = PLoc.getLine();
492    }
493
494    QualType FType = Field->getType();
495    uint64_t FieldSize = 0;
496    unsigned FieldAlign = 0;
497    if (!FType->isIncompleteArrayType()) {
498
499      // Bit size, align and offset of the type.
500      FieldSize = CGM.getContext().getTypeSize(FType);
501      Expr *BitWidth = Field->getBitWidth();
502      if (BitWidth)
503        FieldSize = BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
504
505      FieldAlign =  CGM.getContext().getTypeAlign(FType);
506    }
507
508    uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
509
510    // Create a DW_TAG_member node to remember the offset of this field in the
511    // struct.  FIXME: This is an absolutely insane way to capture this
512    // information.  When we gut debug info, this should be fixed.
513    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
514                                             FieldName, FieldDefUnit,
515                                             FieldLine, FieldSize, FieldAlign,
516                                             FieldOffset, 0, FieldTy);
517    EltTys.push_back(FieldTy);
518  }
519}
520
521/// CollectCXXMemberFunctions - A helper function to collect debug info for
522/// C++ member functions.This is used while creating debug info entry for
523/// a Record.
524void CGDebugInfo::
525CollectCXXMemberFunctions(const CXXRecordDecl *Decl,
526                          llvm::DICompileUnit Unit,
527                          llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys,
528                          llvm::DICompositeType &RecordTy) {
529  SourceManager &SM = CGM.getContext().getSourceManager();
530  for(CXXRecordDecl::method_iterator I = Decl->method_begin(),
531        E = Decl->method_end(); I != E; ++I) {
532    CXXMethodDecl *Method = *I;
533
534    if (Method->isImplicit())
535      continue;
536
537    llvm::StringRef MethodName;
538    llvm::StringRef MethodLinkageName;
539    llvm::DIType MethodTy = getOrCreateType(Method->getType(), Unit);
540    if (CXXConstructorDecl *CDecl = dyn_cast<CXXConstructorDecl>(Method)) {
541      (void)CDecl;
542      MethodName = Decl->getName();
543      // FIXME : Find linkage name.
544    } else if (CXXDestructorDecl *DDecl = dyn_cast<CXXDestructorDecl>(Method)) {
545      (void)DDecl;
546      MethodName = getFunctionName(Method);
547      // FIXME : Find linkage name.
548    } else {
549      // regular method
550      MethodName = getFunctionName(Method);
551      MethodLinkageName = CGM.getMangledName(Method);
552    }
553
554    // Get the location for the method.
555    SourceLocation MethodDefLoc = Method->getLocation();
556    PresumedLoc PLoc = SM.getPresumedLoc(MethodDefLoc);
557    llvm::DICompileUnit MethodDefUnit;
558    unsigned MethodLine = 0;
559
560    if (!PLoc.isInvalid()) {
561      MethodDefUnit = getOrCreateCompileUnit(MethodDefLoc);
562      MethodLine = PLoc.getLine();
563    }
564
565    // Collect virtual method info.
566    llvm::DIType ContainingType;
567    unsigned Virtuality = 0;
568    unsigned VIndex = 0;
569    if (Method->isVirtual()) {
570      // FIXME: Identify pure virtual functions.
571      Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
572      VIndex = CGM.getVtableInfo().getMethodVtableIndex(Method);
573      ContainingType = RecordTy;
574    }
575
576    llvm::DISubprogram SP =
577      DebugFactory.CreateSubprogram(RecordTy , MethodName, MethodName,
578                                    MethodLinkageName,
579                                    MethodDefUnit, MethodLine,
580                                    MethodTy, false,
581                                    Method->isThisDeclarationADefinition(),
582                                    Virtuality, VIndex, ContainingType);
583    if (Method->isThisDeclarationADefinition())
584      SPCache[cast<FunctionDecl>(Method)] = llvm::WeakVH(SP.getNode());
585    EltTys.push_back(SP);
586  }
587}
588
589/// CollectCXXBases - A helper function to collect debug info for
590/// C++ base classes. This is used while creating debug info entry for
591/// a Record.
592void CGDebugInfo::
593CollectCXXBases(const CXXRecordDecl *Decl,
594                llvm::DICompileUnit Unit,
595                llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys,
596                llvm::DICompositeType &RecordTy) {
597
598    const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(Decl);
599    for (CXXRecordDecl::base_class_const_iterator BI = Decl->bases_begin(),
600           BE = Decl->bases_end(); BI != BE; ++BI) {
601      unsigned BFlags = 0;
602      if (BI->isVirtual())
603        BFlags = llvm::DIType::FlagVirtual;
604      AccessSpecifier Access = BI->getAccessSpecifier();
605      if (Access == clang::AS_private)
606        BFlags |= llvm::DIType::FlagPrivate;
607      else if (Access == clang::AS_protected)
608        BFlags |= llvm::DIType::FlagProtected;
609
610      const CXXRecordDecl *Base =
611        cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
612      llvm::DIType DTy =
613        DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_inheritance,
614                                       RecordTy, llvm::StringRef(),
615                                       llvm::DICompileUnit(), 0, 0, 0,
616                                       RL.getBaseClassOffset(Base), BFlags,
617                                       getOrCreateType(BI->getType(),
618                                                       Unit));
619      EltTys.push_back(DTy);
620    }
621}
622
623/// CreateType - get structure or union type.
624llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty,
625                                     llvm::DICompileUnit Unit) {
626  RecordDecl *Decl = Ty->getDecl();
627
628  unsigned Tag;
629  if (Decl->isStruct())
630    Tag = llvm::dwarf::DW_TAG_structure_type;
631  else if (Decl->isUnion())
632    Tag = llvm::dwarf::DW_TAG_union_type;
633  else {
634    assert(Decl->isClass() && "Unknown RecordType!");
635    Tag = llvm::dwarf::DW_TAG_class_type;
636  }
637
638  SourceManager &SM = CGM.getContext().getSourceManager();
639
640  // Get overall information about the record type for the debug info.
641  PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
642  llvm::DICompileUnit DefUnit;
643  unsigned Line = 0;
644  if (!PLoc.isInvalid()) {
645    DefUnit = getOrCreateCompileUnit(Decl->getLocation());
646    Line = PLoc.getLine();
647  }
648
649  // Records and classes and unions can all be recursive.  To handle them, we
650  // first generate a debug descriptor for the struct as a forward declaration.
651  // Then (if it is a definition) we go through and get debug info for all of
652  // its members.  Finally, we create a descriptor for the complete type (which
653  // may refer to the forward decl if the struct is recursive) and replace all
654  // uses of the forward declaration with the final definition.
655
656  // A Decl->getName() is not unique. However, the debug info descriptors
657  // are uniqued. The debug info descriptor describing record's context is
658  // necessary to keep two Decl's descriptor unique if their name match.
659  // FIXME : Use RecordDecl's DeclContext's descriptor. As a temp. step
660  // use type's name in FwdDecl.
661  std::string STy = QualType(Ty, 0).getAsString();
662  llvm::DICompositeType FwdDecl =
663    DebugFactory.CreateCompositeType(Tag, Unit, STy.c_str(),
664                                     DefUnit, Line, 0, 0, 0, 0,
665                                     llvm::DIType(), llvm::DIArray());
666
667  // If this is just a forward declaration, return it.
668  if (!Decl->getDefinition(CGM.getContext()))
669    return FwdDecl;
670
671  llvm::TrackingVH<llvm::MDNode> FwdDeclNode = FwdDecl.getNode();
672  // Otherwise, insert it into the TypeCache so that recursive uses will find
673  // it.
674  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl.getNode();
675
676  // Convert all the elements.
677  llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
678
679  CollectRecordFields(Decl, Unit, EltTys);
680  if (CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(Decl)) {
681    CollectCXXMemberFunctions(CXXDecl, Unit, EltTys, FwdDecl);
682    CollectCXXBases(CXXDecl, Unit, EltTys, FwdDecl);
683  }
684
685  llvm::DIArray Elements =
686    DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
687
688  // Bit size, align and offset of the type.
689  uint64_t Size = CGM.getContext().getTypeSize(Ty);
690  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
691
692  llvm::DICompositeType RealDecl =
693    DebugFactory.CreateCompositeType(Tag, Unit, Decl->getName(),
694                                     DefUnit, Line, Size, Align, 0, 0,
695                                     llvm::DIType(), Elements);
696
697  // Now that we have a real decl for the struct, replace anything using the
698  // old decl with the new one.  This will recursively update the debug info.
699  llvm::DIDerivedType(FwdDeclNode).replaceAllUsesWith(RealDecl);
700
701  return RealDecl;
702}
703
704/// CreateType - get objective-c interface type.
705llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
706                                     llvm::DICompileUnit Unit) {
707  ObjCInterfaceDecl *Decl = Ty->getDecl();
708
709  unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
710  SourceManager &SM = CGM.getContext().getSourceManager();
711
712  // Get overall information about the record type for the debug info.
713  llvm::DICompileUnit DefUnit = getOrCreateCompileUnit(Decl->getLocation());
714  PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
715  unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
716
717
718  unsigned RuntimeLang = DefUnit.getLanguage();
719
720  // To handle recursive interface, we
721  // first generate a debug descriptor for the struct as a forward declaration.
722  // Then (if it is a definition) we go through and get debug info for all of
723  // its members.  Finally, we create a descriptor for the complete type (which
724  // may refer to the forward decl if the struct is recursive) and replace all
725  // uses of the forward declaration with the final definition.
726  llvm::DICompositeType FwdDecl =
727    DebugFactory.CreateCompositeType(Tag, Unit, Decl->getName(),
728                                     DefUnit, Line, 0, 0, 0, 0,
729                                     llvm::DIType(), llvm::DIArray(),
730                                     RuntimeLang);
731
732  // If this is just a forward declaration, return it.
733  if (Decl->isForwardDecl())
734    return FwdDecl;
735
736  llvm::TrackingVH<llvm::MDNode> FwdDeclNode = FwdDecl.getNode();
737  // Otherwise, insert it into the TypeCache so that recursive uses will find
738  // it.
739  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl.getNode();
740
741  // Convert all the elements.
742  llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
743
744  ObjCInterfaceDecl *SClass = Decl->getSuperClass();
745  if (SClass) {
746    llvm::DIType SClassTy =
747      getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
748    llvm::DIType InhTag =
749      DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_inheritance,
750                                     Unit, "", llvm::DICompileUnit(), 0, 0, 0,
751                                     0 /* offset */, 0, SClassTy);
752    EltTys.push_back(InhTag);
753  }
754
755  const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(Decl);
756
757  unsigned FieldNo = 0;
758  for (ObjCInterfaceDecl::ivar_iterator I = Decl->ivar_begin(),
759         E = Decl->ivar_end();  I != E; ++I, ++FieldNo) {
760    ObjCIvarDecl *Field = *I;
761    llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
762
763    llvm::StringRef FieldName = Field->getName();
764
765    // Ignore unnamed fields.
766    if (FieldName.empty())
767      continue;
768
769    // Get the location for the field.
770    SourceLocation FieldDefLoc = Field->getLocation();
771    llvm::DICompileUnit FieldDefUnit = getOrCreateCompileUnit(FieldDefLoc);
772    PresumedLoc PLoc = SM.getPresumedLoc(FieldDefLoc);
773    unsigned FieldLine = PLoc.isInvalid() ? 0 : PLoc.getLine();
774
775
776    QualType FType = Field->getType();
777    uint64_t FieldSize = 0;
778    unsigned FieldAlign = 0;
779
780    if (!FType->isIncompleteArrayType()) {
781
782      // Bit size, align and offset of the type.
783      FieldSize = CGM.getContext().getTypeSize(FType);
784      Expr *BitWidth = Field->getBitWidth();
785      if (BitWidth)
786        FieldSize = BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
787
788      FieldAlign =  CGM.getContext().getTypeAlign(FType);
789    }
790
791    uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
792
793    unsigned Flags = 0;
794    if (Field->getAccessControl() == ObjCIvarDecl::Protected)
795      Flags = llvm::DIType::FlagProtected;
796    else if (Field->getAccessControl() == ObjCIvarDecl::Private)
797      Flags = llvm::DIType::FlagPrivate;
798
799    // Create a DW_TAG_member node to remember the offset of this field in the
800    // struct.  FIXME: This is an absolutely insane way to capture this
801    // information.  When we gut debug info, this should be fixed.
802    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
803                                             FieldName, FieldDefUnit,
804                                             FieldLine, FieldSize, FieldAlign,
805                                             FieldOffset, Flags, FieldTy);
806    EltTys.push_back(FieldTy);
807  }
808
809  llvm::DIArray Elements =
810    DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
811
812  // Bit size, align and offset of the type.
813  uint64_t Size = CGM.getContext().getTypeSize(Ty);
814  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
815
816  llvm::DICompositeType RealDecl =
817    DebugFactory.CreateCompositeType(Tag, Unit, Decl->getName(), DefUnit,
818                                     Line, Size, Align, 0, 0, llvm::DIType(),
819                                     Elements, RuntimeLang);
820
821  // Now that we have a real decl for the struct, replace anything using the
822  // old decl with the new one.  This will recursively update the debug info.
823  llvm::DIDerivedType(FwdDeclNode).replaceAllUsesWith(RealDecl);
824
825  return RealDecl;
826}
827
828llvm::DIType CGDebugInfo::CreateType(const EnumType *Ty,
829                                     llvm::DICompileUnit Unit) {
830  EnumDecl *Decl = Ty->getDecl();
831
832  llvm::SmallVector<llvm::DIDescriptor, 32> Enumerators;
833
834  // Create DIEnumerator elements for each enumerator.
835  for (EnumDecl::enumerator_iterator
836         Enum = Decl->enumerator_begin(), EnumEnd = Decl->enumerator_end();
837       Enum != EnumEnd; ++Enum) {
838    Enumerators.push_back(DebugFactory.CreateEnumerator(Enum->getName(),
839                                            Enum->getInitVal().getZExtValue()));
840  }
841
842  // Return a CompositeType for the enum itself.
843  llvm::DIArray EltArray =
844    DebugFactory.GetOrCreateArray(Enumerators.data(), Enumerators.size());
845
846  SourceLocation DefLoc = Decl->getLocation();
847  llvm::DICompileUnit DefUnit = getOrCreateCompileUnit(DefLoc);
848  SourceManager &SM = CGM.getContext().getSourceManager();
849  PresumedLoc PLoc = SM.getPresumedLoc(DefLoc);
850  unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
851
852
853  // Size and align of the type.
854  uint64_t Size = 0;
855  unsigned Align = 0;
856  if (!Ty->isIncompleteType()) {
857    Size = CGM.getContext().getTypeSize(Ty);
858    Align = CGM.getContext().getTypeAlign(Ty);
859  }
860
861  llvm::DIType DbgTy =
862    DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_enumeration_type,
863                                     Unit, Decl->getName(), DefUnit, Line,
864                                     Size, Align, 0, 0,
865                                     llvm::DIType(), EltArray);
866  return DbgTy;
867}
868
869llvm::DIType CGDebugInfo::CreateType(const TagType *Ty,
870                                     llvm::DICompileUnit Unit) {
871  if (const RecordType *RT = dyn_cast<RecordType>(Ty))
872    return CreateType(RT, Unit);
873  else if (const EnumType *ET = dyn_cast<EnumType>(Ty))
874    return CreateType(ET, Unit);
875
876  return llvm::DIType();
877}
878
879llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
880                                     llvm::DICompileUnit Unit) {
881  uint64_t Size;
882  uint64_t Align;
883
884
885  // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
886  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
887    Size = 0;
888    Align =
889      CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
890  } else if (Ty->isIncompleteArrayType()) {
891    Size = 0;
892    Align = CGM.getContext().getTypeAlign(Ty->getElementType());
893  } else {
894    // Size and align of the whole array, not the element type.
895    Size = CGM.getContext().getTypeSize(Ty);
896    Align = CGM.getContext().getTypeAlign(Ty);
897  }
898
899  // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
900  // interior arrays, do we care?  Why aren't nested arrays represented the
901  // obvious/recursive way?
902  llvm::SmallVector<llvm::DIDescriptor, 8> Subscripts;
903  QualType EltTy(Ty, 0);
904  while ((Ty = dyn_cast<ArrayType>(EltTy))) {
905    uint64_t Upper = 0;
906    if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
907      if (CAT->getSize().getZExtValue())
908        Upper = CAT->getSize().getZExtValue() - 1;
909    // FIXME: Verify this is right for VLAs.
910    Subscripts.push_back(DebugFactory.GetOrCreateSubrange(0, Upper));
911    EltTy = Ty->getElementType();
912  }
913
914  llvm::DIArray SubscriptArray =
915    DebugFactory.GetOrCreateArray(Subscripts.data(), Subscripts.size());
916
917  llvm::DIType DbgTy =
918    DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_array_type,
919                                     Unit, "", llvm::DICompileUnit(),
920                                     0, Size, Align, 0, 0,
921                                     getOrCreateType(EltTy, Unit),
922                                     SubscriptArray);
923  return DbgTy;
924}
925
926llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
927                                     llvm::DICompileUnit Unit) {
928  return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
929                               Ty, Ty->getPointeeType(), Unit);
930}
931
932llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
933                                     llvm::DICompileUnit U) {
934  QualType PointerDiffTy = CGM.getContext().getPointerDiffType();
935  llvm::DIType PointerDiffDITy = getOrCreateType(PointerDiffTy, U);
936
937  if (!Ty->getPointeeType()->isFunctionType()) {
938    // We have a data member pointer type.
939    return PointerDiffDITy;
940  }
941
942  // We have a member function pointer type. Treat it as a struct with two
943  // ptrdiff_t members.
944  std::pair<uint64_t, unsigned> Info = CGM.getContext().getTypeInfo(Ty);
945
946  uint64_t FieldOffset = 0;
947  llvm::DIDescriptor ElementTypes[2];
948
949  // FIXME: This should probably be a function type instead.
950  ElementTypes[0] =
951    DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, U,
952                                   "ptr", llvm::DICompileUnit(), 0,
953                                   Info.first, Info.second, FieldOffset, 0,
954                                   PointerDiffDITy);
955  FieldOffset += Info.first;
956
957  ElementTypes[1] =
958    DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, U,
959                                   "ptr", llvm::DICompileUnit(), 0,
960                                   Info.first, Info.second, FieldOffset, 0,
961                                   PointerDiffDITy);
962
963  llvm::DIArray Elements =
964    DebugFactory.GetOrCreateArray(&ElementTypes[0],
965                                  llvm::array_lengthof(ElementTypes));
966
967  return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type,
968                                          U, llvm::StringRef("test"),
969                                          llvm::DICompileUnit(), 0, FieldOffset,
970                                          0, 0, 0, llvm::DIType(), Elements);
971}
972
973static QualType UnwrapTypeForDebugInfo(QualType T) {
974  do {
975    QualType LastT = T;
976    switch (T->getTypeClass()) {
977    default:
978      return T;
979    case Type::TemplateSpecialization:
980      T = cast<TemplateSpecializationType>(T)->desugar();
981      break;
982    case Type::TypeOfExpr: {
983      TypeOfExprType *Ty = cast<TypeOfExprType>(T);
984      T = Ty->getUnderlyingExpr()->getType();
985      break;
986    }
987    case Type::TypeOf:
988      T = cast<TypeOfType>(T)->getUnderlyingType();
989      break;
990    case Type::Decltype:
991      T = cast<DecltypeType>(T)->getUnderlyingType();
992      break;
993    case Type::QualifiedName:
994      T = cast<QualifiedNameType>(T)->getNamedType();
995      break;
996    case Type::SubstTemplateTypeParm:
997      T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
998      break;
999    case Type::Elaborated:
1000      T = cast<ElaboratedType>(T)->getUnderlyingType();
1001      break;
1002    }
1003
1004    assert(T != LastT && "Type unwrapping failed to unwrap!");
1005    if (T == LastT)
1006      return T;
1007  } while (true);
1008
1009  return T;
1010}
1011
1012/// getOrCreateType - Get the type from the cache or create a new
1013/// one if necessary.
1014llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty,
1015                                          llvm::DICompileUnit Unit) {
1016  if (Ty.isNull())
1017    return llvm::DIType();
1018
1019  // Unwrap the type as needed for debug information.
1020  Ty = UnwrapTypeForDebugInfo(Ty);
1021
1022  // Check for existing entry.
1023  std::map<void *, llvm::WeakVH>::iterator it =
1024    TypeCache.find(Ty.getAsOpaquePtr());
1025  if (it != TypeCache.end()) {
1026    // Verify that the debug info still exists.
1027    if (&*it->second)
1028      return llvm::DIType(cast<llvm::MDNode>(it->second));
1029  }
1030
1031  // Otherwise create the type.
1032  llvm::DIType Res = CreateTypeNode(Ty, Unit);
1033
1034  // And update the type cache.
1035  TypeCache[Ty.getAsOpaquePtr()] = Res.getNode();
1036  return Res;
1037}
1038
1039/// CreateTypeNode - Create a new debug type node.
1040llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty,
1041                                         llvm::DICompileUnit Unit) {
1042  // Handle qualifiers, which recursively handles what they refer to.
1043  if (Ty.hasLocalQualifiers())
1044    return CreateQualifiedType(Ty, Unit);
1045
1046  const char *Diag = 0;
1047
1048  // Work out details of type.
1049  switch (Ty->getTypeClass()) {
1050#define TYPE(Class, Base)
1051#define ABSTRACT_TYPE(Class, Base)
1052#define NON_CANONICAL_TYPE(Class, Base)
1053#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1054#include "clang/AST/TypeNodes.def"
1055    assert(false && "Dependent types cannot show up in debug information");
1056
1057  // FIXME: Handle these.
1058  case Type::ExtVector:
1059  case Type::Vector:
1060    return llvm::DIType();
1061
1062  case Type::ObjCObjectPointer:
1063    return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1064  case Type::ObjCInterface:
1065    return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1066  case Type::Builtin: return CreateType(cast<BuiltinType>(Ty), Unit);
1067  case Type::Complex: return CreateType(cast<ComplexType>(Ty), Unit);
1068  case Type::Pointer: return CreateType(cast<PointerType>(Ty), Unit);
1069  case Type::BlockPointer:
1070    return CreateType(cast<BlockPointerType>(Ty), Unit);
1071  case Type::Typedef: return CreateType(cast<TypedefType>(Ty), Unit);
1072  case Type::Record:
1073  case Type::Enum:
1074    return CreateType(cast<TagType>(Ty), Unit);
1075  case Type::FunctionProto:
1076  case Type::FunctionNoProto:
1077    return CreateType(cast<FunctionType>(Ty), Unit);
1078  case Type::ConstantArray:
1079  case Type::VariableArray:
1080  case Type::IncompleteArray:
1081    return CreateType(cast<ArrayType>(Ty), Unit);
1082
1083  case Type::LValueReference:
1084    return CreateType(cast<LValueReferenceType>(Ty), Unit);
1085
1086  case Type::MemberPointer:
1087    return CreateType(cast<MemberPointerType>(Ty), Unit);
1088
1089  case Type::TemplateSpecialization:
1090  case Type::Elaborated:
1091  case Type::QualifiedName:
1092  case Type::SubstTemplateTypeParm:
1093  case Type::TypeOfExpr:
1094  case Type::TypeOf:
1095  case Type::Decltype:
1096    llvm_unreachable("type should have been unwrapped!");
1097    return llvm::DIType();
1098
1099  case Type::RValueReference:
1100    // FIXME: Implement!
1101    Diag = "rvalue references";
1102    break;
1103  }
1104
1105  assert(Diag && "Fall through without a diagnostic?");
1106  unsigned DiagID = CGM.getDiags().getCustomDiagID(Diagnostic::Error,
1107                               "debug information for %0 is not yet supported");
1108  CGM.getDiags().Report(FullSourceLoc(), DiagID)
1109    << Diag;
1110  return llvm::DIType();
1111}
1112
1113/// EmitFunctionStart - Constructs the debug code for entering a function -
1114/// "llvm.dbg.func.start.".
1115void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
1116                                    llvm::Function *Fn,
1117                                    CGBuilderTy &Builder) {
1118
1119  llvm::StringRef Name;
1120  llvm::StringRef LinkageName;
1121
1122  const Decl *D = GD.getDecl();
1123  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1124    // If there is a DISubprogram for  this function available then use it.
1125    llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1126      FI = SPCache.find(FD);
1127    if (FI != SPCache.end()) {
1128      llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(FI->second));
1129      if (!SP.isNull() && SP.isSubprogram() && SP.isDefinition()) {
1130        RegionStack.push_back(SP.getNode());
1131        return;
1132      }
1133    }
1134    Name = getFunctionName(FD);
1135    if (!Name.empty() && Name[0] == '\01')
1136      Name = Name.substr(1);
1137    // Use mangled name as linkage name for c/c++ functions.
1138    LinkageName = CGM.getMangledName(GD);
1139  } else {
1140    // Use llvm function name as linkage name.
1141    Name = Fn->getName();
1142    LinkageName = Name;
1143    if (!Name.empty() && Name[0] == '\01')
1144      Name = Name.substr(1);
1145  }
1146
1147  // It is expected that CurLoc is set before using EmitFunctionStart.
1148  // Usually, CurLoc points to the left bracket location of compound
1149  // statement representing function body.
1150  llvm::DICompileUnit Unit = getOrCreateCompileUnit(CurLoc);
1151  SourceManager &SM = CGM.getContext().getSourceManager();
1152  unsigned LineNo = SM.getPresumedLoc(CurLoc).getLine();
1153
1154  llvm::DISubprogram SP =
1155    DebugFactory.CreateSubprogram(Unit, Name, Name, LinkageName, Unit, LineNo,
1156                                  getOrCreateType(FnType, Unit),
1157                                  Fn->hasInternalLinkage(), true/*definition*/);
1158
1159  // Push function on region stack.
1160  RegionStack.push_back(SP.getNode());
1161}
1162
1163
1164void CGDebugInfo::EmitStopPoint(llvm::Function *Fn, CGBuilderTy &Builder) {
1165  if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
1166
1167  // Don't bother if things are the same as last time.
1168  SourceManager &SM = CGM.getContext().getSourceManager();
1169  if (CurLoc == PrevLoc
1170       || (SM.getInstantiationLineNumber(CurLoc) ==
1171           SM.getInstantiationLineNumber(PrevLoc)
1172           && SM.isFromSameFile(CurLoc, PrevLoc)))
1173    return;
1174
1175  // Update last state.
1176  PrevLoc = CurLoc;
1177
1178  // Get the appropriate compile unit.
1179  llvm::DICompileUnit Unit = getOrCreateCompileUnit(CurLoc);
1180  PresumedLoc PLoc = SM.getPresumedLoc(CurLoc);
1181
1182  llvm::DIDescriptor DR(RegionStack.back());
1183  llvm::DIScope DS = llvm::DIScope(DR.getNode());
1184  llvm::DILocation DO(NULL);
1185  llvm::DILocation DL =
1186    DebugFactory.CreateLocation(PLoc.getLine(), PLoc.getColumn(),
1187                                DS, DO);
1188  Builder.SetCurrentDebugLocation(DL.getNode());
1189}
1190
1191/// EmitRegionStart- Constructs the debug code for entering a declarative
1192/// region - "llvm.dbg.region.start.".
1193void CGDebugInfo::EmitRegionStart(llvm::Function *Fn, CGBuilderTy &Builder) {
1194  llvm::DIDescriptor D =
1195    DebugFactory.CreateLexicalBlock(RegionStack.empty() ?
1196                                    llvm::DIDescriptor() :
1197                                    llvm::DIDescriptor(RegionStack.back()));
1198  RegionStack.push_back(D.getNode());
1199}
1200
1201/// EmitRegionEnd - Constructs the debug code for exiting a declarative
1202/// region - "llvm.dbg.region.end."
1203void CGDebugInfo::EmitRegionEnd(llvm::Function *Fn, CGBuilderTy &Builder) {
1204  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1205
1206  // Provide an region stop point.
1207  EmitStopPoint(Fn, Builder);
1208
1209  RegionStack.pop_back();
1210}
1211
1212/// EmitDeclare - Emit local variable declaration debug info.
1213void CGDebugInfo::EmitDeclare(const VarDecl *Decl, unsigned Tag,
1214                              llvm::Value *Storage, CGBuilderTy &Builder) {
1215  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1216
1217  // Do not emit variable debug information while generating optimized code.
1218  // The llvm optimizer and code generator are not yet ready to support
1219  // optimized code debugging.
1220  const CodeGenOptions &CGO = CGM.getCodeGenOpts();
1221  if (CGO.OptimizationLevel)
1222    return;
1223
1224  llvm::DICompileUnit Unit = getOrCreateCompileUnit(Decl->getLocation());
1225  QualType Type = Decl->getType();
1226  llvm::DIType Ty = getOrCreateType(Type, Unit);
1227  if (Decl->hasAttr<BlocksAttr>()) {
1228    llvm::DICompileUnit DefUnit;
1229    unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
1230
1231    llvm::SmallVector<llvm::DIDescriptor, 5> EltTys;
1232
1233    llvm::DIType FieldTy;
1234
1235    QualType FType;
1236    uint64_t FieldSize, FieldOffset;
1237    unsigned FieldAlign;
1238
1239    llvm::DIArray Elements;
1240    llvm::DIType EltTy;
1241
1242    // Build up structure for the byref.  See BuildByRefType.
1243    FieldOffset = 0;
1244    FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1245    FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1246    FieldSize = CGM.getContext().getTypeSize(FType);
1247    FieldAlign = CGM.getContext().getTypeAlign(FType);
1248    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1249                                             "__isa", DefUnit,
1250                                             0, FieldSize, FieldAlign,
1251                                             FieldOffset, 0, FieldTy);
1252    EltTys.push_back(FieldTy);
1253    FieldOffset += FieldSize;
1254
1255    FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1256    FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1257    FieldSize = CGM.getContext().getTypeSize(FType);
1258    FieldAlign = CGM.getContext().getTypeAlign(FType);
1259    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1260                                             "__forwarding", DefUnit,
1261                                             0, FieldSize, FieldAlign,
1262                                             FieldOffset, 0, FieldTy);
1263    EltTys.push_back(FieldTy);
1264    FieldOffset += FieldSize;
1265
1266    FType = CGM.getContext().IntTy;
1267    FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1268    FieldSize = CGM.getContext().getTypeSize(FType);
1269    FieldAlign = CGM.getContext().getTypeAlign(FType);
1270    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1271                                             "__flags", DefUnit,
1272                                             0, FieldSize, FieldAlign,
1273                                             FieldOffset, 0, FieldTy);
1274    EltTys.push_back(FieldTy);
1275    FieldOffset += FieldSize;
1276
1277    FType = CGM.getContext().IntTy;
1278    FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1279    FieldSize = CGM.getContext().getTypeSize(FType);
1280    FieldAlign = CGM.getContext().getTypeAlign(FType);
1281    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1282                                             "__size", DefUnit,
1283                                             0, FieldSize, FieldAlign,
1284                                             FieldOffset, 0, FieldTy);
1285    EltTys.push_back(FieldTy);
1286    FieldOffset += FieldSize;
1287
1288    bool HasCopyAndDispose = CGM.BlockRequiresCopying(Type);
1289    if (HasCopyAndDispose) {
1290      FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1291      FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1292      FieldSize = CGM.getContext().getTypeSize(FType);
1293      FieldAlign = CGM.getContext().getTypeAlign(FType);
1294      FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1295                                               "__copy_helper", DefUnit,
1296                                               0, FieldSize, FieldAlign,
1297                                               FieldOffset, 0, FieldTy);
1298      EltTys.push_back(FieldTy);
1299      FieldOffset += FieldSize;
1300
1301      FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1302      FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1303      FieldSize = CGM.getContext().getTypeSize(FType);
1304      FieldAlign = CGM.getContext().getTypeAlign(FType);
1305      FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1306                                               "__destroy_helper", DefUnit,
1307                                               0, FieldSize, FieldAlign,
1308                                               FieldOffset, 0, FieldTy);
1309      EltTys.push_back(FieldTy);
1310      FieldOffset += FieldSize;
1311    }
1312
1313    unsigned Align = CGM.getContext().getDeclAlignInBytes(Decl);
1314    if (Align > CGM.getContext().Target.getPointerAlign(0) / 8) {
1315      unsigned AlignedOffsetInBytes
1316        = llvm::RoundUpToAlignment(FieldOffset/8, Align);
1317      unsigned NumPaddingBytes
1318        = AlignedOffsetInBytes - FieldOffset/8;
1319
1320      if (NumPaddingBytes > 0) {
1321        llvm::APInt pad(32, NumPaddingBytes);
1322        FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
1323                                                     pad, ArrayType::Normal, 0);
1324        FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1325        FieldSize = CGM.getContext().getTypeSize(FType);
1326        FieldAlign = CGM.getContext().getTypeAlign(FType);
1327        FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member,
1328                                                 Unit, "", DefUnit,
1329                                                 0, FieldSize, FieldAlign,
1330                                                 FieldOffset, 0, FieldTy);
1331        EltTys.push_back(FieldTy);
1332        FieldOffset += FieldSize;
1333      }
1334    }
1335
1336    FType = Type;
1337    FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1338    FieldSize = CGM.getContext().getTypeSize(FType);
1339    FieldAlign = Align*8;
1340
1341    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1342                                             Decl->getName(), DefUnit,
1343                                             0, FieldSize, FieldAlign,
1344                                             FieldOffset, 0, FieldTy);
1345    EltTys.push_back(FieldTy);
1346    FieldOffset += FieldSize;
1347
1348    Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
1349
1350    unsigned Flags = llvm::DIType::FlagBlockByrefStruct;
1351
1352    Ty = DebugFactory.CreateCompositeType(Tag, Unit, "",
1353                                          llvm::DICompileUnit(),
1354                                          0, FieldOffset, 0, 0, Flags,
1355                                          llvm::DIType(), Elements);
1356  }
1357
1358  // Get location information.
1359  SourceManager &SM = CGM.getContext().getSourceManager();
1360  PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
1361  unsigned Line = 0;
1362  unsigned Column = 0;
1363  if (!PLoc.isInvalid()) {
1364    Line = PLoc.getLine();
1365    Column = PLoc.getColumn();
1366  } else {
1367    Unit = llvm::DICompileUnit();
1368  }
1369
1370  // Create the descriptor for the variable.
1371  llvm::DIVariable D =
1372    DebugFactory.CreateVariable(Tag, llvm::DIDescriptor(RegionStack.back()),
1373                                Decl->getName(),
1374                                Unit, Line, Ty);
1375  // Insert an llvm.dbg.declare into the current block.
1376  llvm::Instruction *Call =
1377    DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock());
1378
1379  llvm::DIScope DS(RegionStack.back());
1380  llvm::DILocation DO(NULL);
1381  llvm::DILocation DL = DebugFactory.CreateLocation(Line, Column, DS, DO);
1382
1383  Call->setMetadata("dbg", DL.getNode());
1384}
1385
1386/// EmitDeclare - Emit local variable declaration debug info.
1387void CGDebugInfo::EmitDeclare(const BlockDeclRefExpr *BDRE, unsigned Tag,
1388                              llvm::Value *Storage, CGBuilderTy &Builder,
1389                              CodeGenFunction *CGF) {
1390  const ValueDecl *Decl = BDRE->getDecl();
1391  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1392
1393  // Do not emit variable debug information while generating optimized code.
1394  // The llvm optimizer and code generator are not yet ready to support
1395  // optimized code debugging.
1396  const CodeGenOptions &CGO = CGM.getCodeGenOpts();
1397  if (CGO.OptimizationLevel || Builder.GetInsertBlock() == 0)
1398    return;
1399
1400  uint64_t XOffset = 0;
1401  llvm::DICompileUnit Unit = getOrCreateCompileUnit(Decl->getLocation());
1402  QualType Type = Decl->getType();
1403  llvm::DIType Ty = getOrCreateType(Type, Unit);
1404  if (Decl->hasAttr<BlocksAttr>()) {
1405    llvm::DICompileUnit DefUnit;
1406    unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
1407
1408    llvm::SmallVector<llvm::DIDescriptor, 5> EltTys;
1409
1410    llvm::DIType FieldTy;
1411
1412    QualType FType;
1413    uint64_t FieldSize, FieldOffset;
1414    unsigned FieldAlign;
1415
1416    llvm::DIArray Elements;
1417    llvm::DIType EltTy;
1418
1419    // Build up structure for the byref.  See BuildByRefType.
1420    FieldOffset = 0;
1421    FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1422    FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1423    FieldSize = CGM.getContext().getTypeSize(FType);
1424    FieldAlign = CGM.getContext().getTypeAlign(FType);
1425    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1426                                             "__isa", DefUnit,
1427                                             0, FieldSize, FieldAlign,
1428                                             FieldOffset, 0, FieldTy);
1429    EltTys.push_back(FieldTy);
1430    FieldOffset += FieldSize;
1431
1432    FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1433    FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1434    FieldSize = CGM.getContext().getTypeSize(FType);
1435    FieldAlign = CGM.getContext().getTypeAlign(FType);
1436    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1437                                             "__forwarding", DefUnit,
1438                                             0, FieldSize, FieldAlign,
1439                                             FieldOffset, 0, FieldTy);
1440    EltTys.push_back(FieldTy);
1441    FieldOffset += FieldSize;
1442
1443    FType = CGM.getContext().IntTy;
1444    FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1445    FieldSize = CGM.getContext().getTypeSize(FType);
1446    FieldAlign = CGM.getContext().getTypeAlign(FType);
1447    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1448                                             "__flags", DefUnit,
1449                                             0, FieldSize, FieldAlign,
1450                                             FieldOffset, 0, FieldTy);
1451    EltTys.push_back(FieldTy);
1452    FieldOffset += FieldSize;
1453
1454    FType = CGM.getContext().IntTy;
1455    FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1456    FieldSize = CGM.getContext().getTypeSize(FType);
1457    FieldAlign = CGM.getContext().getTypeAlign(FType);
1458    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1459                                             "__size", DefUnit,
1460                                             0, FieldSize, FieldAlign,
1461                                             FieldOffset, 0, FieldTy);
1462    EltTys.push_back(FieldTy);
1463    FieldOffset += FieldSize;
1464
1465    bool HasCopyAndDispose = CGM.BlockRequiresCopying(Type);
1466    if (HasCopyAndDispose) {
1467      FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1468      FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1469      FieldSize = CGM.getContext().getTypeSize(FType);
1470      FieldAlign = CGM.getContext().getTypeAlign(FType);
1471      FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1472                                               "__copy_helper", DefUnit,
1473                                               0, FieldSize, FieldAlign,
1474                                               FieldOffset, 0, FieldTy);
1475      EltTys.push_back(FieldTy);
1476      FieldOffset += FieldSize;
1477
1478      FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1479      FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1480      FieldSize = CGM.getContext().getTypeSize(FType);
1481      FieldAlign = CGM.getContext().getTypeAlign(FType);
1482      FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1483                                               "__destroy_helper", DefUnit,
1484                                               0, FieldSize, FieldAlign,
1485                                               FieldOffset, 0, FieldTy);
1486      EltTys.push_back(FieldTy);
1487      FieldOffset += FieldSize;
1488    }
1489
1490    unsigned Align = CGM.getContext().getDeclAlignInBytes(Decl);
1491    if (Align > CGM.getContext().Target.getPointerAlign(0) / 8) {
1492      unsigned AlignedOffsetInBytes
1493        = llvm::RoundUpToAlignment(FieldOffset/8, Align);
1494      unsigned NumPaddingBytes
1495        = AlignedOffsetInBytes - FieldOffset/8;
1496
1497      if (NumPaddingBytes > 0) {
1498        llvm::APInt pad(32, NumPaddingBytes);
1499        FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
1500                                                     pad, ArrayType::Normal, 0);
1501        FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1502        FieldSize = CGM.getContext().getTypeSize(FType);
1503        FieldAlign = CGM.getContext().getTypeAlign(FType);
1504        FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member,
1505                                                 Unit, "", DefUnit,
1506                                                 0, FieldSize, FieldAlign,
1507                                                 FieldOffset, 0, FieldTy);
1508        EltTys.push_back(FieldTy);
1509        FieldOffset += FieldSize;
1510      }
1511    }
1512
1513    FType = Type;
1514    FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1515    FieldSize = CGM.getContext().getTypeSize(FType);
1516    FieldAlign = Align*8;
1517
1518    XOffset = FieldOffset;
1519    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1520                                             Decl->getName(), DefUnit,
1521                                             0, FieldSize, FieldAlign,
1522                                             FieldOffset, 0, FieldTy);
1523    EltTys.push_back(FieldTy);
1524    FieldOffset += FieldSize;
1525
1526    Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
1527
1528    unsigned Flags = llvm::DIType::FlagBlockByrefStruct;
1529
1530    Ty = DebugFactory.CreateCompositeType(Tag, Unit, "",
1531                                          llvm::DICompileUnit(),
1532                                          0, FieldOffset, 0, 0, Flags,
1533                                          llvm::DIType(), Elements);
1534  }
1535
1536  // Get location information.
1537  SourceManager &SM = CGM.getContext().getSourceManager();
1538  PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
1539  unsigned Line = 0;
1540  if (!PLoc.isInvalid())
1541    Line = PLoc.getLine();
1542  else
1543    Unit = llvm::DICompileUnit();
1544
1545  CharUnits offset = CGF->BlockDecls[Decl];
1546  llvm::SmallVector<llvm::Value *, 9> addr;
1547  const llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext());
1548  addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1549  addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1550  addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1551  if (BDRE->isByRef()) {
1552    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1553    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1554    // offset of __forwarding field
1555    offset = CharUnits::fromQuantity(CGF->LLVMPointerWidth/8);
1556    addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1557    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1558    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1559    // offset of x field
1560    offset = CharUnits::fromQuantity(XOffset/8);
1561    addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1562  }
1563
1564  // Create the descriptor for the variable.
1565  llvm::DIVariable D =
1566    DebugFactory.CreateComplexVariable(Tag,
1567                                       llvm::DIDescriptor(RegionStack.back()),
1568                                       Decl->getName(), Unit, Line, Ty,
1569                                       addr);
1570  // Insert an llvm.dbg.declare into the current block.
1571  llvm::Instruction *Call =
1572    DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock());
1573
1574  llvm::DIScope DS(RegionStack.back());
1575  llvm::DILocation DO(NULL);
1576  llvm::DILocation DL =
1577    DebugFactory.CreateLocation(Line, PLoc.getColumn(), DS, DO);
1578
1579  Call->setMetadata("dbg", DL.getNode());
1580}
1581
1582void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *Decl,
1583                                            llvm::Value *Storage,
1584                                            CGBuilderTy &Builder) {
1585  EmitDeclare(Decl, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder);
1586}
1587
1588void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
1589  const BlockDeclRefExpr *BDRE, llvm::Value *Storage, CGBuilderTy &Builder,
1590  CodeGenFunction *CGF) {
1591  EmitDeclare(BDRE, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder, CGF);
1592}
1593
1594/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
1595/// variable declaration.
1596void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *Decl, llvm::Value *AI,
1597                                           CGBuilderTy &Builder) {
1598  EmitDeclare(Decl, llvm::dwarf::DW_TAG_arg_variable, AI, Builder);
1599}
1600
1601
1602
1603/// EmitGlobalVariable - Emit information about a global variable.
1604void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
1605                                     const VarDecl *Decl) {
1606
1607  // Create global variable debug descriptor.
1608  llvm::DICompileUnit Unit = getOrCreateCompileUnit(Decl->getLocation());
1609  SourceManager &SM = CGM.getContext().getSourceManager();
1610  PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
1611  unsigned LineNo = PLoc.isInvalid() ? 0 : PLoc.getLine();
1612
1613  QualType T = Decl->getType();
1614  if (T->isIncompleteArrayType()) {
1615
1616    // CodeGen turns int[] into int[1] so we'll do the same here.
1617    llvm::APSInt ConstVal(32);
1618
1619    ConstVal = 1;
1620    QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
1621
1622    T = CGM.getContext().getConstantArrayType(ET, ConstVal,
1623                                           ArrayType::Normal, 0);
1624  }
1625  llvm::StringRef DeclName = Decl->getName();
1626  DebugFactory.CreateGlobalVariable(getContext(Decl, Unit), DeclName, DeclName,
1627                                    llvm::StringRef(), Unit, LineNo,
1628                                    getOrCreateType(T, Unit),
1629                                    Var->hasInternalLinkage(),
1630                                    true/*definition*/, Var);
1631}
1632
1633/// EmitGlobalVariable - Emit information about an objective-c interface.
1634void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
1635                                     ObjCInterfaceDecl *Decl) {
1636  // Create global variable debug descriptor.
1637  llvm::DICompileUnit Unit = getOrCreateCompileUnit(Decl->getLocation());
1638  SourceManager &SM = CGM.getContext().getSourceManager();
1639  PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
1640  unsigned LineNo = PLoc.isInvalid() ? 0 : PLoc.getLine();
1641
1642  llvm::StringRef Name = Decl->getName();
1643
1644  QualType T = CGM.getContext().getObjCInterfaceType(Decl);
1645  if (T->isIncompleteArrayType()) {
1646
1647    // CodeGen turns int[] into int[1] so we'll do the same here.
1648    llvm::APSInt ConstVal(32);
1649
1650    ConstVal = 1;
1651    QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
1652
1653    T = CGM.getContext().getConstantArrayType(ET, ConstVal,
1654                                           ArrayType::Normal, 0);
1655  }
1656
1657  DebugFactory.CreateGlobalVariable(Unit, Name, Name, Name, Unit, LineNo,
1658                                    getOrCreateType(T, Unit),
1659                                    Var->hasInternalLinkage(),
1660                                    true/*definition*/, Var);
1661}
1662