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