CGDebugInfo.cpp revision 414ee4bb74957b4c5fe05e11848028e4701b51f7
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 "CGBlocks.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/DeclFriend.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/RecordLayout.h"
24#include "clang/Basic/SourceManager.h"
25#include "clang/Basic/FileManager.h"
26#include "clang/Basic/Version.h"
27#include "clang/Frontend/CodeGenOptions.h"
28#include "llvm/Constants.h"
29#include "llvm/DerivedTypes.h"
30#include "llvm/Instructions.h"
31#include "llvm/Intrinsics.h"
32#include "llvm/Module.h"
33#include "llvm/ADT/StringExtras.h"
34#include "llvm/ADT/SmallVector.h"
35#include "llvm/Support/Dwarf.h"
36#include "llvm/Support/Path.h"
37#include "llvm/Target/TargetData.h"
38#include "llvm/Target/TargetMachine.h"
39using namespace clang;
40using namespace clang::CodeGen;
41
42CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
43  : CGM(CGM), DBuilder(CGM.getModule()),
44    BlockLiteralGenericSet(false) {
45  CreateCompileUnit();
46}
47
48CGDebugInfo::~CGDebugInfo() {
49  assert(RegionStack.empty() && "Region stack mismatch, stack not empty!");
50}
51
52void CGDebugInfo::setLocation(SourceLocation Loc) {
53  if (Loc.isValid())
54    CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
55}
56
57/// getContextDescriptor - Get context info for the decl.
58llvm::DIDescriptor CGDebugInfo::getContextDescriptor(const Decl *Context) {
59  if (!Context)
60    return TheCU;
61
62  llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
63    I = RegionMap.find(Context);
64  if (I != RegionMap.end())
65    return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(&*I->second));
66
67  // Check namespace.
68  if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
69    return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
70
71  if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context)) {
72    if (!RDecl->isDependentType()) {
73      llvm::DIType Ty = getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
74                                        getOrCreateMainFile());
75      return llvm::DIDescriptor(Ty);
76    }
77  }
78  return TheCU;
79}
80
81/// getFunctionName - Get function name for the given FunctionDecl. If the
82/// name is constructred on demand (e.g. C++ destructor) then the name
83/// is stored on the side.
84StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
85  assert (FD && "Invalid FunctionDecl!");
86  IdentifierInfo *FII = FD->getIdentifier();
87  if (FII)
88    return FII->getName();
89
90  // Otherwise construct human readable name for debug info.
91  std::string NS = FD->getNameAsString();
92
93  // Copy this name on the side and use its reference.
94  char *StrPtr = DebugInfoNames.Allocate<char>(NS.length());
95  memcpy(StrPtr, NS.data(), NS.length());
96  return StringRef(StrPtr, NS.length());
97}
98
99StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
100  llvm::SmallString<256> MethodName;
101  llvm::raw_svector_ostream OS(MethodName);
102  OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
103  const DeclContext *DC = OMD->getDeclContext();
104  if (const ObjCImplementationDecl *OID =
105      dyn_cast<const ObjCImplementationDecl>(DC)) {
106     OS << OID->getName();
107  } else if (const ObjCInterfaceDecl *OID =
108             dyn_cast<const ObjCInterfaceDecl>(DC)) {
109      OS << OID->getName();
110  } else if (const ObjCCategoryImplDecl *OCD =
111             dyn_cast<const ObjCCategoryImplDecl>(DC)){
112      OS << ((NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
113          OCD->getIdentifier()->getNameStart() << ')';
114  }
115  OS << ' ' << OMD->getSelector().getAsString() << ']';
116
117  char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
118  memcpy(StrPtr, MethodName.begin(), OS.tell());
119  return StringRef(StrPtr, OS.tell());
120}
121
122/// getSelectorName - Return selector name. This is used for debugging
123/// info.
124StringRef CGDebugInfo::getSelectorName(Selector S) {
125  llvm::SmallString<256> SName;
126  llvm::raw_svector_ostream OS(SName);
127  OS << S.getAsString();
128  char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
129  memcpy(StrPtr, SName.begin(), OS.tell());
130  return StringRef(StrPtr, OS.tell());
131}
132
133/// getClassName - Get class name including template argument list.
134StringRef
135CGDebugInfo::getClassName(RecordDecl *RD) {
136  ClassTemplateSpecializationDecl *Spec
137    = dyn_cast<ClassTemplateSpecializationDecl>(RD);
138  if (!Spec)
139    return RD->getName();
140
141  const TemplateArgument *Args;
142  unsigned NumArgs;
143  std::string Buffer;
144  if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
145    const TemplateSpecializationType *TST =
146      cast<TemplateSpecializationType>(TAW->getType());
147    Args = TST->getArgs();
148    NumArgs = TST->getNumArgs();
149  } else {
150    const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
151    Args = TemplateArgs.data();
152    NumArgs = TemplateArgs.size();
153  }
154  Buffer = RD->getIdentifier()->getNameStart();
155  PrintingPolicy Policy(CGM.getLangOptions());
156  Buffer += TemplateSpecializationType::PrintTemplateArgumentList(Args,
157                                                                  NumArgs,
158                                                                  Policy);
159
160  // Copy this name on the side and use its reference.
161  char *StrPtr = DebugInfoNames.Allocate<char>(Buffer.length());
162  memcpy(StrPtr, Buffer.data(), Buffer.length());
163  return StringRef(StrPtr, Buffer.length());
164}
165
166/// getOrCreateFile - Get the file debug info descriptor for the input location.
167llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
168  if (!Loc.isValid())
169    // If Location is not valid then use main input file.
170    return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
171
172  SourceManager &SM = CGM.getContext().getSourceManager();
173  PresumedLoc PLoc = SM.getPresumedLoc(Loc);
174
175  if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
176    // If the location is not valid then use main input file.
177    return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
178
179  // Cache the results.
180  const char *fname = PLoc.getFilename();
181  llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
182    DIFileCache.find(fname);
183
184  if (it != DIFileCache.end()) {
185    // Verify that the information still exists.
186    if (&*it->second)
187      return llvm::DIFile(cast<llvm::MDNode>(it->second));
188  }
189
190  llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
191
192  DIFileCache[fname] = F;
193  return F;
194
195}
196
197/// getOrCreateMainFile - Get the file info for main compile unit.
198llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
199  return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
200}
201
202/// getLineNumber - Get line number for the location. If location is invalid
203/// then use current location.
204unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
205  assert (CurLoc.isValid() && "Invalid current location!");
206  SourceManager &SM = CGM.getContext().getSourceManager();
207  PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
208  return PLoc.isValid()? PLoc.getLine() : 0;
209}
210
211/// getColumnNumber - Get column number for the location. If location is
212/// invalid then use current location.
213unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc) {
214  assert (CurLoc.isValid() && "Invalid current location!");
215  SourceManager &SM = CGM.getContext().getSourceManager();
216  PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
217  return PLoc.isValid()? PLoc.getColumn() : 0;
218}
219
220StringRef CGDebugInfo::getCurrentDirname() {
221  if (!CWDName.empty())
222    return CWDName;
223  char *CompDirnamePtr = NULL;
224  llvm::sys::Path CWD = llvm::sys::Path::GetCurrentDirectory();
225  CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
226  memcpy(CompDirnamePtr, CWD.c_str(), CWD.size());
227  return CWDName = StringRef(CompDirnamePtr, CWD.size());
228}
229
230/// CreateCompileUnit - Create new compile unit.
231void CGDebugInfo::CreateCompileUnit() {
232
233  // Get absolute path name.
234  SourceManager &SM = CGM.getContext().getSourceManager();
235  std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
236  if (MainFileName.empty())
237    MainFileName = "<unknown>";
238
239  // The main file name provided via the "-main-file-name" option contains just
240  // the file name itself with no path information. This file name may have had
241  // a relative path, so we look into the actual file entry for the main
242  // file to determine the real absolute path for the file.
243  std::string MainFileDir;
244  if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
245    MainFileDir = MainFile->getDir()->getName();
246    if (MainFileDir != ".")
247      MainFileName = MainFileDir + "/" + MainFileName;
248  }
249
250  // Save filename string.
251  char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
252  memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
253  StringRef Filename(FilenamePtr, MainFileName.length());
254
255  unsigned LangTag;
256  const LangOptions &LO = CGM.getLangOptions();
257  if (LO.CPlusPlus) {
258    if (LO.ObjC1)
259      LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
260    else
261      LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
262  } else if (LO.ObjC1) {
263    LangTag = llvm::dwarf::DW_LANG_ObjC;
264  } else if (LO.C99) {
265    LangTag = llvm::dwarf::DW_LANG_C99;
266  } else {
267    LangTag = llvm::dwarf::DW_LANG_C89;
268  }
269
270  std::string Producer = getClangFullVersion();
271
272  // Figure out which version of the ObjC runtime we have.
273  unsigned RuntimeVers = 0;
274  if (LO.ObjC1)
275    RuntimeVers = LO.ObjCNonFragileABI ? 2 : 1;
276
277  // Create new compile unit.
278  DBuilder.createCompileUnit(
279    LangTag, Filename, getCurrentDirname(),
280    Producer,
281    LO.Optimize, CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers);
282  // FIXME - Eliminate TheCU.
283  TheCU = llvm::DICompileUnit(DBuilder.getCU());
284}
285
286/// CreateType - Get the Basic type from the cache or create a new
287/// one if necessary.
288llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
289  unsigned Encoding = 0;
290  const char *BTName = NULL;
291  switch (BT->getKind()) {
292  case BuiltinType::Dependent:
293    llvm_unreachable("Unexpected builtin type Dependent");
294  case BuiltinType::Overload:
295    llvm_unreachable("Unexpected builtin type Overload");
296  case BuiltinType::BoundMember:
297    llvm_unreachable("Unexpected builtin type BoundMember");
298  case BuiltinType::UnknownAny:
299    llvm_unreachable("Unexpected builtin type UnknownAny");
300  case BuiltinType::NullPtr:
301    return DBuilder.
302      createNullPtrType(BT->getName(CGM.getContext().getLangOptions()));
303  case BuiltinType::Void:
304    return llvm::DIType();
305  case BuiltinType::ObjCClass:
306    return DBuilder.createStructType(TheCU, "objc_class",
307                                     getOrCreateMainFile(), 0, 0, 0,
308                                     llvm::DIDescriptor::FlagFwdDecl,
309                                     llvm::DIArray());
310  case BuiltinType::ObjCId: {
311    // typedef struct objc_class *Class;
312    // typedef struct objc_object {
313    //  Class isa;
314    // } *id;
315
316    llvm::DIType OCTy =
317      DBuilder.createStructType(TheCU, "objc_class",
318                                getOrCreateMainFile(), 0, 0, 0,
319                                llvm::DIDescriptor::FlagFwdDecl,
320                                llvm::DIArray());
321    unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
322
323    llvm::DIType ISATy = DBuilder.createPointerType(OCTy, Size);
324
325    SmallVector<llvm::Value *, 16> EltTys;
326    llvm::DIType FieldTy =
327      DBuilder.createMemberType(getOrCreateMainFile(), "isa",
328                                getOrCreateMainFile(), 0, Size,
329                                0, 0, 0, ISATy);
330    EltTys.push_back(FieldTy);
331    llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
332
333    return DBuilder.createStructType(TheCU, "objc_object",
334                                     getOrCreateMainFile(),
335                                     0, 0, 0, 0, Elements);
336  }
337  case BuiltinType::ObjCSel: {
338    return  DBuilder.createStructType(TheCU, "objc_selector",
339                                      getOrCreateMainFile(), 0, 0, 0,
340                                      llvm::DIDescriptor::FlagFwdDecl,
341                                      llvm::DIArray());
342  }
343  case BuiltinType::UChar:
344  case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
345  case BuiltinType::Char_S:
346  case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
347  case BuiltinType::Char16:
348  case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
349  case BuiltinType::UShort:
350  case BuiltinType::UInt:
351  case BuiltinType::UInt128:
352  case BuiltinType::ULong:
353  case BuiltinType::WChar_U:
354  case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
355  case BuiltinType::Short:
356  case BuiltinType::Int:
357  case BuiltinType::Int128:
358  case BuiltinType::Long:
359  case BuiltinType::WChar_S:
360  case BuiltinType::LongLong:  Encoding = llvm::dwarf::DW_ATE_signed; break;
361  case BuiltinType::Bool:      Encoding = llvm::dwarf::DW_ATE_boolean; break;
362  case BuiltinType::Float:
363  case BuiltinType::LongDouble:
364  case BuiltinType::Double:    Encoding = llvm::dwarf::DW_ATE_float; break;
365  }
366
367  switch (BT->getKind()) {
368  case BuiltinType::Long:      BTName = "long int"; break;
369  case BuiltinType::LongLong:  BTName = "long long int"; break;
370  case BuiltinType::ULong:     BTName = "long unsigned int"; break;
371  case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
372  default:
373    BTName = BT->getName(CGM.getContext().getLangOptions());
374    break;
375  }
376  // Bit size, align and offset of the type.
377  uint64_t Size = CGM.getContext().getTypeSize(BT);
378  uint64_t Align = CGM.getContext().getTypeAlign(BT);
379  llvm::DIType DbgTy =
380    DBuilder.createBasicType(BTName, Size, Align, Encoding);
381  return DbgTy;
382}
383
384llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
385  // Bit size, align and offset of the type.
386  unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
387  if (Ty->isComplexIntegerType())
388    Encoding = llvm::dwarf::DW_ATE_lo_user;
389
390  uint64_t Size = CGM.getContext().getTypeSize(Ty);
391  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
392  llvm::DIType DbgTy =
393    DBuilder.createBasicType("complex", Size, Align, Encoding);
394
395  return DbgTy;
396}
397
398/// CreateCVRType - Get the qualified type from the cache or create
399/// a new one if necessary.
400llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
401  QualifierCollector Qc;
402  const Type *T = Qc.strip(Ty);
403
404  // Ignore these qualifiers for now.
405  Qc.removeObjCGCAttr();
406  Qc.removeAddressSpace();
407  Qc.removeObjCLifetime();
408
409  // We will create one Derived type for one qualifier and recurse to handle any
410  // additional ones.
411  unsigned Tag;
412  if (Qc.hasConst()) {
413    Tag = llvm::dwarf::DW_TAG_const_type;
414    Qc.removeConst();
415  } else if (Qc.hasVolatile()) {
416    Tag = llvm::dwarf::DW_TAG_volatile_type;
417    Qc.removeVolatile();
418  } else if (Qc.hasRestrict()) {
419    Tag = llvm::dwarf::DW_TAG_restrict_type;
420    Qc.removeRestrict();
421  } else {
422    assert(Qc.empty() && "Unknown type qualifier for debug info");
423    return getOrCreateType(QualType(T, 0), Unit);
424  }
425
426  llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
427
428  // No need to fill in the Name, Line, Size, Alignment, Offset in case of
429  // CVR derived types.
430  llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
431
432  return DbgTy;
433}
434
435llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
436                                     llvm::DIFile Unit) {
437  llvm::DIType DbgTy =
438    CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
439                          Ty->getPointeeType(), Unit);
440  return DbgTy;
441}
442
443llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
444                                     llvm::DIFile Unit) {
445  return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
446                               Ty->getPointeeType(), Unit);
447}
448
449/// CreatePointeeType - Create Pointee type. If Pointee is a record
450/// then emit record's fwd if debug info size reduction is enabled.
451llvm::DIType CGDebugInfo::CreatePointeeType(QualType PointeeTy,
452                                            llvm::DIFile Unit) {
453  if (!CGM.getCodeGenOpts().LimitDebugInfo)
454    return getOrCreateType(PointeeTy, Unit);
455
456  if (const RecordType *RTy = dyn_cast<RecordType>(PointeeTy)) {
457    RecordDecl *RD = RTy->getDecl();
458    llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
459    unsigned Line = getLineNumber(RD->getLocation());
460    llvm::DIDescriptor FDContext =
461      getContextDescriptor(cast<Decl>(RD->getDeclContext()));
462
463    if (RD->isStruct())
464      return DBuilder.createStructType(FDContext, RD->getName(), DefUnit,
465                                       Line, 0, 0, llvm::DIType::FlagFwdDecl,
466                                       llvm::DIArray());
467    else if (RD->isUnion())
468      return DBuilder.createUnionType(FDContext, RD->getName(), DefUnit,
469                                      Line, 0, 0, llvm::DIType::FlagFwdDecl,
470                                      llvm::DIArray());
471    else {
472      assert(RD->isClass() && "Unknown RecordType!");
473      return DBuilder.createClassType(FDContext, RD->getName(), DefUnit,
474                                      Line, 0, 0, 0, llvm::DIType::FlagFwdDecl,
475                                      llvm::DIType(), llvm::DIArray());
476    }
477  }
478  return getOrCreateType(PointeeTy, Unit);
479
480}
481
482llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
483                                                const Type *Ty,
484                                                QualType PointeeTy,
485                                                llvm::DIFile Unit) {
486
487  if (Tag == llvm::dwarf::DW_TAG_reference_type)
488    return DBuilder.createReferenceType(CreatePointeeType(PointeeTy, Unit));
489
490  // Bit size, align and offset of the type.
491  // Size is always the size of a pointer. We can't use getTypeSize here
492  // because that does not return the correct value for references.
493  unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
494  uint64_t Size = CGM.getContext().getTargetInfo().getPointerWidth(AS);
495  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
496
497  return
498    DBuilder.createPointerType(CreatePointeeType(PointeeTy, Unit), Size, Align);
499}
500
501llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
502                                     llvm::DIFile Unit) {
503  if (BlockLiteralGenericSet)
504    return BlockLiteralGeneric;
505
506  SmallVector<llvm::Value *, 8> EltTys;
507  llvm::DIType FieldTy;
508  QualType FType;
509  uint64_t FieldSize, FieldOffset;
510  unsigned FieldAlign;
511  llvm::DIArray Elements;
512  llvm::DIType EltTy, DescTy;
513
514  FieldOffset = 0;
515  FType = CGM.getContext().UnsignedLongTy;
516  EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
517  EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
518
519  Elements = DBuilder.getOrCreateArray(EltTys);
520  EltTys.clear();
521
522  unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
523  unsigned LineNo = getLineNumber(CurLoc);
524
525  EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
526                                    Unit, LineNo, FieldOffset, 0,
527                                    Flags, Elements);
528
529  // Bit size, align and offset of the type.
530  uint64_t Size = CGM.getContext().getTypeSize(Ty);
531
532  DescTy = DBuilder.createPointerType(EltTy, Size);
533
534  FieldOffset = 0;
535  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
536  EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
537  FType = CGM.getContext().IntTy;
538  EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
539  EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
540  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
541  EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
542
543  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
544  FieldTy = DescTy;
545  FieldSize = CGM.getContext().getTypeSize(Ty);
546  FieldAlign = CGM.getContext().getTypeAlign(Ty);
547  FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
548                                      LineNo, FieldSize, FieldAlign,
549                                      FieldOffset, 0, FieldTy);
550  EltTys.push_back(FieldTy);
551
552  FieldOffset += FieldSize;
553  Elements = DBuilder.getOrCreateArray(EltTys);
554
555  EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
556                                    Unit, LineNo, FieldOffset, 0,
557                                    Flags, Elements);
558
559  BlockLiteralGenericSet = true;
560  BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
561  return BlockLiteralGeneric;
562}
563
564llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty,
565                                     llvm::DIFile Unit) {
566  // Typedefs are derived from some other type.  If we have a typedef of a
567  // typedef, make sure to emit the whole chain.
568  llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
569  if (!Src.Verify())
570    return llvm::DIType();
571  // We don't set size information, but do specify where the typedef was
572  // declared.
573  unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
574  const TypedefNameDecl *TyDecl = Ty->getDecl();
575  llvm::DIDescriptor TydefContext =
576    getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
577
578  return
579    DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TydefContext);
580}
581
582llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
583                                     llvm::DIFile Unit) {
584  SmallVector<llvm::Value *, 16> EltTys;
585
586  // Add the result type at least.
587  EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
588
589  // Set up remainder of arguments if there is a prototype.
590  // FIXME: IF NOT, HOW IS THIS REPRESENTED?  llvm-gcc doesn't represent '...'!
591  if (isa<FunctionNoProtoType>(Ty))
592    EltTys.push_back(DBuilder.createUnspecifiedParameter());
593  else if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(Ty)) {
594    for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
595      EltTys.push_back(getOrCreateType(FTP->getArgType(i), Unit));
596  }
597
598  llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
599
600  llvm::DIType DbgTy = DBuilder.createSubroutineType(Unit, EltTypeArray);
601  return DbgTy;
602}
603
604llvm::DIType CGDebugInfo::createFieldType(StringRef name,
605                                          QualType type,
606                                          Expr *bitWidth,
607                                          SourceLocation loc,
608                                          AccessSpecifier AS,
609                                          uint64_t offsetInBits,
610                                          llvm::DIFile tunit,
611                                          llvm::DIDescriptor scope) {
612  llvm::DIType debugType = getOrCreateType(type, tunit);
613
614  // Get the location for the field.
615  llvm::DIFile file = getOrCreateFile(loc);
616  unsigned line = getLineNumber(loc);
617
618  uint64_t sizeInBits = 0;
619  unsigned alignInBits = 0;
620  if (!type->isIncompleteArrayType()) {
621    llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
622
623    if (bitWidth)
624      sizeInBits = bitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
625  }
626
627  unsigned flags = 0;
628  if (AS == clang::AS_private)
629    flags |= llvm::DIDescriptor::FlagPrivate;
630  else if (AS == clang::AS_protected)
631    flags |= llvm::DIDescriptor::FlagProtected;
632
633  return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
634                                   alignInBits, offsetInBits, flags, debugType);
635}
636
637/// CollectRecordFields - A helper function to collect debug info for
638/// record fields. This is used while creating debug info entry for a Record.
639void CGDebugInfo::
640CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
641                    SmallVectorImpl<llvm::Value *> &elements,
642                    llvm::DIType RecordTy) {
643  unsigned fieldNo = 0;
644  const FieldDecl *LastFD = 0;
645  bool IsMsStruct = record->hasAttr<MsStructAttr>();
646
647  const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
648  for (RecordDecl::field_iterator I = record->field_begin(),
649                                  E = record->field_end();
650       I != E; ++I, ++fieldNo) {
651    FieldDecl *field = *I;
652    if (IsMsStruct) {
653      // Zero-length bitfields following non-bitfield members are ignored
654      if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD)) {
655        --fieldNo;
656        continue;
657      }
658      LastFD = field;
659    }
660
661    StringRef name = field->getName();
662    QualType type = field->getType();
663
664    // Ignore unnamed fields unless they're anonymous structs/unions.
665    if (name.empty() && !type->isRecordType()) {
666      LastFD = field;
667      continue;
668    }
669
670    llvm::DIType fieldType
671      = createFieldType(name, type, field->getBitWidth(),
672                        field->getLocation(), field->getAccess(),
673                        layout.getFieldOffset(fieldNo), tunit, RecordTy);
674
675    elements.push_back(fieldType);
676  }
677}
678
679/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
680/// function type is not updated to include implicit "this" pointer. Use this
681/// routine to get a method type which includes "this" pointer.
682llvm::DIType
683CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
684                                   llvm::DIFile Unit) {
685  llvm::DIType FnTy
686    = getOrCreateType(QualType(Method->getType()->getAs<FunctionProtoType>(),
687                               0),
688                      Unit);
689
690  // Add "this" pointer.
691  llvm::DIArray Args = llvm::DICompositeType(FnTy).getTypeArray();
692  assert (Args.getNumElements() && "Invalid number of arguments!");
693
694  SmallVector<llvm::Value *, 16> Elts;
695
696  // First element is always return type. For 'void' functions it is NULL.
697  Elts.push_back(Args.getElement(0));
698
699  if (!Method->isStatic()) {
700    // "this" pointer is always first argument.
701    QualType ThisPtr = Method->getThisType(CGM.getContext());
702    llvm::DIType ThisPtrType =
703      DBuilder.createArtificialType(getOrCreateType(ThisPtr, Unit));
704
705    TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
706    Elts.push_back(ThisPtrType);
707  }
708
709  // Copy rest of the arguments.
710  for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
711    Elts.push_back(Args.getElement(i));
712
713  llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
714
715  return DBuilder.createSubroutineType(Unit, EltTypeArray);
716}
717
718/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
719/// inside a function.
720static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
721  if (const CXXRecordDecl *NRD =
722      dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
723    return isFunctionLocalClass(NRD);
724  else if (isa<FunctionDecl>(RD->getDeclContext()))
725    return true;
726  return false;
727
728}
729/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
730/// a single member function GlobalDecl.
731llvm::DISubprogram
732CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
733                                     llvm::DIFile Unit,
734                                     llvm::DIType RecordTy) {
735  bool IsCtorOrDtor =
736    isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
737
738  StringRef MethodName = getFunctionName(Method);
739  llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit);
740
741  // Since a single ctor/dtor corresponds to multiple functions, it doesn't
742  // make sense to give a single ctor/dtor a linkage name.
743  StringRef MethodLinkageName;
744  if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
745    MethodLinkageName = CGM.getMangledName(Method);
746
747  // Get the location for the method.
748  llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
749  unsigned MethodLine = getLineNumber(Method->getLocation());
750
751  // Collect virtual method info.
752  llvm::DIType ContainingType;
753  unsigned Virtuality = 0;
754  unsigned VIndex = 0;
755
756  if (Method->isVirtual()) {
757    if (Method->isPure())
758      Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
759    else
760      Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
761
762    // It doesn't make sense to give a virtual destructor a vtable index,
763    // since a single destructor has two entries in the vtable.
764    if (!isa<CXXDestructorDecl>(Method))
765      VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
766    ContainingType = RecordTy;
767  }
768
769  unsigned Flags = 0;
770  if (Method->isImplicit())
771    Flags |= llvm::DIDescriptor::FlagArtificial;
772  AccessSpecifier Access = Method->getAccess();
773  if (Access == clang::AS_private)
774    Flags |= llvm::DIDescriptor::FlagPrivate;
775  else if (Access == clang::AS_protected)
776    Flags |= llvm::DIDescriptor::FlagProtected;
777  if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
778    if (CXXC->isExplicit())
779      Flags |= llvm::DIDescriptor::FlagExplicit;
780  } else if (const CXXConversionDecl *CXXC =
781             dyn_cast<CXXConversionDecl>(Method)) {
782    if (CXXC->isExplicit())
783      Flags |= llvm::DIDescriptor::FlagExplicit;
784  }
785  if (Method->hasPrototype())
786    Flags |= llvm::DIDescriptor::FlagPrototyped;
787
788  llvm::DISubprogram SP =
789    DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
790                          MethodDefUnit, MethodLine,
791                          MethodTy, /*isLocalToUnit=*/false,
792                          /* isDefinition=*/ false,
793                          Virtuality, VIndex, ContainingType,
794                          Flags, CGM.getLangOptions().Optimize);
795
796  SPCache[Method] = llvm::WeakVH(SP);
797
798  return SP;
799}
800
801/// CollectCXXMemberFunctions - A helper function to collect debug info for
802/// C++ member functions.This is used while creating debug info entry for
803/// a Record.
804void CGDebugInfo::
805CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
806                          SmallVectorImpl<llvm::Value *> &EltTys,
807                          llvm::DIType RecordTy) {
808  for(CXXRecordDecl::method_iterator I = RD->method_begin(),
809        E = RD->method_end(); I != E; ++I) {
810    const CXXMethodDecl *Method = *I;
811
812    if (Method->isImplicit() && !Method->isUsed())
813      continue;
814
815    EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
816  }
817}
818
819/// CollectCXXFriends - A helper function to collect debug info for
820/// C++ base classes. This is used while creating debug info entry for
821/// a Record.
822void CGDebugInfo::
823CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
824                SmallVectorImpl<llvm::Value *> &EltTys,
825                llvm::DIType RecordTy) {
826  for (CXXRecordDecl::friend_iterator BI =  RD->friend_begin(),
827         BE = RD->friend_end(); BI != BE; ++BI) {
828    if ((*BI)->isUnsupportedFriend())
829      continue;
830    if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
831      EltTys.push_back(DBuilder.createFriend(RecordTy,
832                                             getOrCreateType(TInfo->getType(),
833                                                             Unit)));
834  }
835}
836
837/// CollectCXXBases - A helper function to collect debug info for
838/// C++ base classes. This is used while creating debug info entry for
839/// a Record.
840void CGDebugInfo::
841CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
842                SmallVectorImpl<llvm::Value *> &EltTys,
843                llvm::DIType RecordTy) {
844
845  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
846  for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
847         BE = RD->bases_end(); BI != BE; ++BI) {
848    unsigned BFlags = 0;
849    uint64_t BaseOffset;
850
851    const CXXRecordDecl *Base =
852      cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
853
854    if (BI->isVirtual()) {
855      // virtual base offset offset is -ve. The code generator emits dwarf
856      // expression where it expects +ve number.
857      BaseOffset =
858        0 - CGM.getVTableContext()
859               .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
860      BFlags = llvm::DIDescriptor::FlagVirtual;
861    } else
862      BaseOffset = RL.getBaseClassOffsetInBits(Base);
863    // FIXME: Inconsistent units for BaseOffset. It is in bytes when
864    // BI->isVirtual() and bits when not.
865
866    AccessSpecifier Access = BI->getAccessSpecifier();
867    if (Access == clang::AS_private)
868      BFlags |= llvm::DIDescriptor::FlagPrivate;
869    else if (Access == clang::AS_protected)
870      BFlags |= llvm::DIDescriptor::FlagProtected;
871
872    llvm::DIType DTy =
873      DBuilder.createInheritance(RecordTy,
874                                 getOrCreateType(BI->getType(), Unit),
875                                 BaseOffset, BFlags);
876    EltTys.push_back(DTy);
877  }
878}
879
880/// CollectTemplateParams - A helper function to collect template parameters.
881llvm::DIArray CGDebugInfo::
882CollectTemplateParams(const TemplateParameterList *TPList,
883                      const TemplateArgumentList &TAList,
884                      llvm::DIFile Unit) {
885  SmallVector<llvm::Value *, 16> TemplateParams;
886  for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
887    const TemplateArgument &TA = TAList[i];
888    const NamedDecl *ND = TPList->getParam(i);
889    if (TA.getKind() == TemplateArgument::Type) {
890      llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
891      llvm::DITemplateTypeParameter TTP =
892        DBuilder.createTemplateTypeParameter(TheCU, ND->getName(), TTy);
893      TemplateParams.push_back(TTP);
894    } else if (TA.getKind() == TemplateArgument::Integral) {
895      llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
896      llvm::DITemplateValueParameter TVP =
897        DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy,
898                                          TA.getAsIntegral()->getZExtValue());
899      TemplateParams.push_back(TVP);
900    }
901  }
902  return DBuilder.getOrCreateArray(TemplateParams);
903}
904
905/// CollectFunctionTemplateParams - A helper function to collect debug
906/// info for function template parameters.
907llvm::DIArray CGDebugInfo::
908CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
909  if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplateSpecialization){
910    const TemplateParameterList *TList =
911      FD->getTemplateSpecializationInfo()->getTemplate()->getTemplateParameters();
912    return
913      CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit);
914  }
915  return llvm::DIArray();
916}
917
918/// CollectCXXTemplateParams - A helper function to collect debug info for
919/// template parameters.
920llvm::DIArray CGDebugInfo::
921CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
922                         llvm::DIFile Unit) {
923  llvm::PointerUnion<ClassTemplateDecl *,
924                     ClassTemplatePartialSpecializationDecl *>
925    PU = TSpecial->getSpecializedTemplateOrPartial();
926
927  TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
928    PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
929    PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
930  const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
931  return CollectTemplateParams(TPList, TAList, Unit);
932}
933
934/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
935llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
936  if (VTablePtrType.isValid())
937    return VTablePtrType;
938
939  ASTContext &Context = CGM.getContext();
940
941  /* Function type */
942  llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
943  llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
944  llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
945  unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
946  llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
947                                                          "__vtbl_ptr_type");
948  VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
949  return VTablePtrType;
950}
951
952/// getVTableName - Get vtable name for the given Class.
953StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
954  // Otherwise construct gdb compatible name name.
955  std::string Name = "_vptr$" + RD->getNameAsString();
956
957  // Copy this name on the side and use its reference.
958  char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
959  memcpy(StrPtr, Name.data(), Name.length());
960  return StringRef(StrPtr, Name.length());
961}
962
963
964/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
965/// debug info entry in EltTys vector.
966void CGDebugInfo::
967CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
968                  SmallVectorImpl<llvm::Value *> &EltTys) {
969  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
970
971  // If there is a primary base then it will hold vtable info.
972  if (RL.getPrimaryBase())
973    return;
974
975  // If this class is not dynamic then there is not any vtable info to collect.
976  if (!RD->isDynamicClass())
977    return;
978
979  unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
980  llvm::DIType VPTR
981    = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
982                                0, Size, 0, 0, 0,
983                                getOrCreateVTablePtrType(Unit));
984  EltTys.push_back(VPTR);
985}
986
987/// getOrCreateRecordType - Emit record type's standalone debug info.
988llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
989                                                SourceLocation Loc) {
990  llvm::DIType T =  getOrCreateType(RTy, getOrCreateFile(Loc));
991  DBuilder.retainType(T);
992  return T;
993}
994
995/// CreateType - get structure or union type.
996llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
997  RecordDecl *RD = Ty->getDecl();
998  llvm::DIFile Unit = getOrCreateFile(RD->getLocation());
999
1000  // Get overall information about the record type for the debug info.
1001  llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1002  unsigned Line = getLineNumber(RD->getLocation());
1003
1004  // Records and classes and unions can all be recursive.  To handle them, we
1005  // first generate a debug descriptor for the struct as a forward declaration.
1006  // Then (if it is a definition) we go through and get debug info for all of
1007  // its members.  Finally, we create a descriptor for the complete type (which
1008  // may refer to the forward decl if the struct is recursive) and replace all
1009  // uses of the forward declaration with the final definition.
1010  llvm::DIDescriptor FDContext =
1011    getContextDescriptor(cast<Decl>(RD->getDeclContext()));
1012
1013  // If this is just a forward declaration, construct an appropriately
1014  // marked node and just return it.
1015  if (!RD->getDefinition()) {
1016    llvm::DIType FwdDecl =
1017      DBuilder.createStructType(FDContext, RD->getName(),
1018                                DefUnit, Line, 0, 0,
1019                                llvm::DIDescriptor::FlagFwdDecl,
1020                                llvm::DIArray());
1021
1022      return FwdDecl;
1023  }
1024
1025  llvm::DIType FwdDecl = DBuilder.createTemporaryType(DefUnit);
1026
1027  llvm::MDNode *MN = FwdDecl;
1028  llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN;
1029  // Otherwise, insert it into the TypeCache so that recursive uses will find
1030  // it.
1031  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1032  // Push the struct on region stack.
1033  RegionStack.push_back(FwdDeclNode);
1034  RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1035
1036  // Convert all the elements.
1037  SmallVector<llvm::Value *, 16> EltTys;
1038
1039  const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1040  if (CXXDecl) {
1041    CollectCXXBases(CXXDecl, Unit, EltTys, FwdDecl);
1042    CollectVTableInfo(CXXDecl, Unit, EltTys);
1043  }
1044
1045  // Collect static variables with initializers.
1046  for (RecordDecl::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
1047       I != E; ++I)
1048    if (const VarDecl *V = dyn_cast<VarDecl>(*I)) {
1049      if (const Expr *Init = V->getInit()) {
1050        Expr::EvalResult Result;
1051        if (Init->Evaluate(Result, CGM.getContext()) && Result.Val.isInt()) {
1052          llvm::ConstantInt *CI
1053            = llvm::ConstantInt::get(CGM.getLLVMContext(), Result.Val.getInt());
1054
1055          // Create the descriptor for static variable.
1056          llvm::DIFile VUnit = getOrCreateFile(V->getLocation());
1057          StringRef VName = V->getName();
1058          llvm::DIType VTy = getOrCreateType(V->getType(), VUnit);
1059          // Do not use DIGlobalVariable for enums.
1060          if (VTy.getTag() != llvm::dwarf::DW_TAG_enumeration_type) {
1061            DBuilder.createStaticVariable(FwdDecl, VName, VName, VUnit,
1062                                          getLineNumber(V->getLocation()),
1063                                          VTy, true, CI);
1064          }
1065        }
1066      }
1067    }
1068
1069  CollectRecordFields(RD, Unit, EltTys, FwdDecl);
1070  llvm::DIArray TParamsArray;
1071  if (CXXDecl) {
1072    CollectCXXMemberFunctions(CXXDecl, Unit, EltTys, FwdDecl);
1073    CollectCXXFriends(CXXDecl, Unit, EltTys, FwdDecl);
1074    if (const ClassTemplateSpecializationDecl *TSpecial
1075        = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1076      TParamsArray = CollectCXXTemplateParams(TSpecial, Unit);
1077  }
1078
1079  RegionStack.pop_back();
1080  llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI =
1081    RegionMap.find(Ty->getDecl());
1082  if (RI != RegionMap.end())
1083    RegionMap.erase(RI);
1084
1085  llvm::DIDescriptor RDContext =
1086    getContextDescriptor(cast<Decl>(RD->getDeclContext()));
1087  StringRef RDName = RD->getName();
1088  uint64_t Size = CGM.getContext().getTypeSize(Ty);
1089  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1090  llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1091  llvm::MDNode *RealDecl = NULL;
1092
1093  if (RD->isUnion())
1094    RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
1095                                        Size, Align, 0, Elements);
1096  else if (CXXDecl) {
1097    RDName = getClassName(RD);
1098     // A class's primary base or the class itself contains the vtable.
1099    llvm::MDNode *ContainingType = NULL;
1100    const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1101    if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
1102      // Seek non virtual primary base root.
1103      while (1) {
1104        const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
1105        const CXXRecordDecl *PBT = BRL.getPrimaryBase();
1106        if (PBT && !BRL.isPrimaryBaseVirtual())
1107          PBase = PBT;
1108        else
1109          break;
1110      }
1111      ContainingType =
1112        getOrCreateType(QualType(PBase->getTypeForDecl(), 0), Unit);
1113    }
1114    else if (CXXDecl->isDynamicClass())
1115      ContainingType = FwdDecl;
1116
1117   RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
1118                                       Size, Align, 0, 0, llvm::DIType(),
1119                                       Elements, ContainingType,
1120                                       TParamsArray);
1121  } else
1122    RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
1123                                         Size, Align, 0, Elements);
1124
1125  // Now that we have a real decl for the struct, replace anything using the
1126  // old decl with the new one.  This will recursively update the debug info.
1127  llvm::DIType(FwdDeclNode).replaceAllUsesWith(RealDecl);
1128  RegionMap[RD] = llvm::WeakVH(RealDecl);
1129  return llvm::DIType(RealDecl);
1130}
1131
1132/// CreateType - get objective-c object type.
1133llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1134                                     llvm::DIFile Unit) {
1135  // Ignore protocols.
1136  return getOrCreateType(Ty->getBaseType(), Unit);
1137}
1138
1139/// CreateType - get objective-c interface type.
1140llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1141                                     llvm::DIFile Unit) {
1142  ObjCInterfaceDecl *ID = Ty->getDecl();
1143  if (!ID)
1144    return llvm::DIType();
1145
1146  // Get overall information about the record type for the debug info.
1147  llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1148  unsigned Line = getLineNumber(ID->getLocation());
1149  unsigned RuntimeLang = TheCU.getLanguage();
1150
1151  // If this is just a forward declaration, return a special forward-declaration
1152  // debug type.
1153  if (ID->isForwardDecl()) {
1154    llvm::DIType FwdDecl =
1155      DBuilder.createStructType(Unit, ID->getName(),
1156                                DefUnit, Line, 0, 0, 0,
1157                                llvm::DIArray(), RuntimeLang);
1158    return FwdDecl;
1159  }
1160
1161  // To handle recursive interface, we
1162  // first generate a debug descriptor for the struct as a forward declaration.
1163  // Then (if it is a definition) we go through and get debug info for all of
1164  // its members.  Finally, we create a descriptor for the complete type (which
1165  // may refer to the forward decl if the struct is recursive) and replace all
1166  // uses of the forward declaration with the final definition.
1167  llvm::DIType FwdDecl = DBuilder.createTemporaryType(DefUnit);
1168
1169  llvm::MDNode *MN = FwdDecl;
1170  llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN;
1171  // Otherwise, insert it into the TypeCache so that recursive uses will find
1172  // it.
1173  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1174  // Push the struct on region stack.
1175  RegionStack.push_back(FwdDeclNode);
1176  RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1177
1178  // Convert all the elements.
1179  SmallVector<llvm::Value *, 16> EltTys;
1180
1181  ObjCInterfaceDecl *SClass = ID->getSuperClass();
1182  if (SClass) {
1183    llvm::DIType SClassTy =
1184      getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1185    if (!SClassTy.isValid())
1186      return llvm::DIType();
1187
1188    llvm::DIType InhTag =
1189      DBuilder.createInheritance(FwdDecl, SClassTy, 0, 0);
1190    EltTys.push_back(InhTag);
1191  }
1192
1193  const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1194  ObjCImplementationDecl *ImpD = ID->getImplementation();
1195  unsigned FieldNo = 0;
1196  for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1197       Field = Field->getNextIvar(), ++FieldNo) {
1198    llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1199    if (!FieldTy.isValid())
1200      return llvm::DIType();
1201
1202    StringRef FieldName = Field->getName();
1203
1204    // Ignore unnamed fields.
1205    if (FieldName.empty())
1206      continue;
1207
1208    // Get the location for the field.
1209    llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1210    unsigned FieldLine = getLineNumber(Field->getLocation());
1211    QualType FType = Field->getType();
1212    uint64_t FieldSize = 0;
1213    unsigned FieldAlign = 0;
1214
1215    if (!FType->isIncompleteArrayType()) {
1216
1217      // Bit size, align and offset of the type.
1218      FieldSize = CGM.getContext().getTypeSize(FType);
1219      Expr *BitWidth = Field->getBitWidth();
1220      if (BitWidth)
1221        FieldSize = BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
1222
1223      FieldAlign =  CGM.getContext().getTypeAlign(FType);
1224    }
1225
1226    uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
1227
1228    unsigned Flags = 0;
1229    if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1230      Flags = llvm::DIDescriptor::FlagProtected;
1231    else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1232      Flags = llvm::DIDescriptor::FlagPrivate;
1233
1234    StringRef PropertyName;
1235    StringRef PropertyGetter;
1236    StringRef PropertySetter;
1237    unsigned PropertyAttributes = 0;
1238    ObjCPropertyDecl *PD = NULL;
1239    if (ImpD)
1240      if (ObjCPropertyImplDecl *PImpD =
1241	  ImpD->FindPropertyImplIvarDecl(Field->getIdentifier()))
1242	PD = PImpD->getPropertyDecl();
1243    if (PD) {
1244      PropertyName = PD->getName();
1245      PropertyGetter = getSelectorName(PD->getGetterName());
1246      PropertySetter = getSelectorName(PD->getSetterName());
1247      PropertyAttributes = PD->getPropertyAttributes();
1248    }
1249    FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1250                                      FieldLine, FieldSize, FieldAlign,
1251                                      FieldOffset, Flags, FieldTy,
1252                                      PropertyName, PropertyGetter,
1253                                      PropertySetter, PropertyAttributes);
1254    EltTys.push_back(FieldTy);
1255  }
1256
1257  llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1258
1259  RegionStack.pop_back();
1260  llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI =
1261    RegionMap.find(Ty->getDecl());
1262  if (RI != RegionMap.end())
1263    RegionMap.erase(RI);
1264
1265  // Bit size, align and offset of the type.
1266  uint64_t Size = CGM.getContext().getTypeSize(Ty);
1267  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1268
1269  unsigned Flags = 0;
1270  if (ID->getImplementation())
1271    Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1272
1273  llvm::DIType RealDecl =
1274    DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1275                                  Line, Size, Align, Flags,
1276                                  Elements, RuntimeLang);
1277
1278  // Now that we have a real decl for the struct, replace anything using the
1279  // old decl with the new one.  This will recursively update the debug info.
1280  llvm::DIType(FwdDeclNode).replaceAllUsesWith(RealDecl);
1281  RegionMap[ID] = llvm::WeakVH(RealDecl);
1282
1283  return RealDecl;
1284}
1285
1286llvm::DIType CGDebugInfo::CreateType(const TagType *Ty) {
1287  if (const RecordType *RT = dyn_cast<RecordType>(Ty))
1288    return CreateType(RT);
1289  else if (const EnumType *ET = dyn_cast<EnumType>(Ty))
1290    return CreateEnumType(ET->getDecl());
1291
1292  return llvm::DIType();
1293}
1294
1295llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty,
1296                                     llvm::DIFile Unit) {
1297  llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1298  int64_t NumElems = Ty->getNumElements();
1299  int64_t LowerBound = 0;
1300  if (NumElems == 0)
1301    // If number of elements are not known then this is an unbounded array.
1302    // Use Low = 1, Hi = 0 to express such arrays.
1303    LowerBound = 1;
1304  else
1305    --NumElems;
1306
1307  llvm::Value *Subscript = DBuilder.getOrCreateSubrange(LowerBound, NumElems);
1308  llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1309
1310  uint64_t Size = CGM.getContext().getTypeSize(Ty);
1311  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1312
1313  return
1314    DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1315}
1316
1317llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1318                                     llvm::DIFile Unit) {
1319  uint64_t Size;
1320  uint64_t Align;
1321
1322
1323  // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1324  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1325    Size = 0;
1326    Align =
1327      CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1328  } else if (Ty->isIncompleteArrayType()) {
1329    Size = 0;
1330    Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1331  } else if (Ty->isDependentSizedArrayType() || Ty->isIncompleteType()) {
1332    Size = 0;
1333    Align = 0;
1334  } else {
1335    // Size and align of the whole array, not the element type.
1336    Size = CGM.getContext().getTypeSize(Ty);
1337    Align = CGM.getContext().getTypeAlign(Ty);
1338  }
1339
1340  // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
1341  // interior arrays, do we care?  Why aren't nested arrays represented the
1342  // obvious/recursive way?
1343  SmallVector<llvm::Value *, 8> Subscripts;
1344  QualType EltTy(Ty, 0);
1345  if (Ty->isIncompleteArrayType())
1346    EltTy = Ty->getElementType();
1347  else {
1348    while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1349      int64_t UpperBound = 0;
1350      int64_t LowerBound = 0;
1351      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty)) {
1352        if (CAT->getSize().getZExtValue())
1353          UpperBound = CAT->getSize().getZExtValue() - 1;
1354      } else
1355        // This is an unbounded array. Use Low = 1, Hi = 0 to express such
1356        // arrays.
1357        LowerBound = 1;
1358
1359      // FIXME: Verify this is right for VLAs.
1360      Subscripts.push_back(DBuilder.getOrCreateSubrange(LowerBound, UpperBound));
1361      EltTy = Ty->getElementType();
1362    }
1363  }
1364
1365  llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1366
1367  llvm::DIType DbgTy =
1368    DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1369                             SubscriptArray);
1370  return DbgTy;
1371}
1372
1373llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1374                                     llvm::DIFile Unit) {
1375  return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1376                               Ty, Ty->getPointeeType(), Unit);
1377}
1378
1379llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1380                                     llvm::DIFile Unit) {
1381  return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
1382                               Ty, Ty->getPointeeType(), Unit);
1383}
1384
1385llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1386                                     llvm::DIFile U) {
1387  QualType PointerDiffTy = CGM.getContext().getPointerDiffType();
1388  llvm::DIType PointerDiffDITy = getOrCreateType(PointerDiffTy, U);
1389
1390  if (!Ty->getPointeeType()->isFunctionType()) {
1391    // We have a data member pointer type.
1392    return PointerDiffDITy;
1393  }
1394
1395  // We have a member function pointer type. Treat it as a struct with two
1396  // ptrdiff_t members.
1397  std::pair<uint64_t, unsigned> Info = CGM.getContext().getTypeInfo(Ty);
1398
1399  uint64_t FieldOffset = 0;
1400  llvm::Value *ElementTypes[2];
1401
1402  // FIXME: This should probably be a function type instead.
1403  ElementTypes[0] =
1404    DBuilder.createMemberType(U, "ptr", U, 0,
1405                              Info.first, Info.second, FieldOffset, 0,
1406                              PointerDiffDITy);
1407  FieldOffset += Info.first;
1408
1409  ElementTypes[1] =
1410    DBuilder.createMemberType(U, "ptr", U, 0,
1411                              Info.first, Info.second, FieldOffset, 0,
1412                              PointerDiffDITy);
1413
1414  llvm::DIArray Elements = DBuilder.getOrCreateArray(ElementTypes);
1415
1416  return DBuilder.createStructType(U, StringRef("test"),
1417                                   U, 0, FieldOffset,
1418                                   0, 0, Elements);
1419}
1420
1421/// CreateEnumType - get enumeration type.
1422llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1423  llvm::DIFile Unit = getOrCreateFile(ED->getLocation());
1424  SmallVector<llvm::Value *, 16> Enumerators;
1425
1426  // Create DIEnumerator elements for each enumerator.
1427  for (EnumDecl::enumerator_iterator
1428         Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1429       Enum != EnumEnd; ++Enum) {
1430    Enumerators.push_back(
1431      DBuilder.createEnumerator(Enum->getName(),
1432                                Enum->getInitVal().getZExtValue()));
1433  }
1434
1435  // Return a CompositeType for the enum itself.
1436  llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1437
1438  llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1439  unsigned Line = getLineNumber(ED->getLocation());
1440  uint64_t Size = 0;
1441  uint64_t Align = 0;
1442  if (!ED->getTypeForDecl()->isIncompleteType()) {
1443    Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1444    Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1445  }
1446  llvm::DIDescriptor EnumContext =
1447    getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1448  llvm::DIType DbgTy =
1449    DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1450                                   Size, Align, EltArray);
1451  return DbgTy;
1452}
1453
1454static QualType UnwrapTypeForDebugInfo(QualType T) {
1455  do {
1456    QualType LastT = T;
1457    switch (T->getTypeClass()) {
1458    default:
1459      return T;
1460    case Type::TemplateSpecialization:
1461      T = cast<TemplateSpecializationType>(T)->desugar();
1462      break;
1463    case Type::TypeOfExpr:
1464      T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1465      break;
1466    case Type::TypeOf:
1467      T = cast<TypeOfType>(T)->getUnderlyingType();
1468      break;
1469    case Type::Decltype:
1470      T = cast<DecltypeType>(T)->getUnderlyingType();
1471      break;
1472    case Type::UnaryTransform:
1473      T = cast<UnaryTransformType>(T)->getUnderlyingType();
1474      break;
1475    case Type::Attributed:
1476      T = cast<AttributedType>(T)->getEquivalentType();
1477      break;
1478    case Type::Elaborated:
1479      T = cast<ElaboratedType>(T)->getNamedType();
1480      break;
1481    case Type::Paren:
1482      T = cast<ParenType>(T)->getInnerType();
1483      break;
1484    case Type::SubstTemplateTypeParm:
1485      T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
1486      break;
1487    case Type::Auto:
1488      T = cast<AutoType>(T)->getDeducedType();
1489      break;
1490    }
1491
1492    assert(T != LastT && "Type unwrapping failed to unwrap!");
1493    if (T == LastT)
1494      return T;
1495  } while (true);
1496
1497  return T;
1498}
1499
1500/// getOrCreateType - Get the type from the cache or create a new
1501/// one if necessary.
1502llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty,
1503                                          llvm::DIFile Unit) {
1504  if (Ty.isNull())
1505    return llvm::DIType();
1506
1507  // Unwrap the type as needed for debug information.
1508  Ty = UnwrapTypeForDebugInfo(Ty);
1509
1510  // Check for existing entry.
1511  llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1512    TypeCache.find(Ty.getAsOpaquePtr());
1513  if (it != TypeCache.end()) {
1514    // Verify that the debug info still exists.
1515    if (&*it->second)
1516      return llvm::DIType(cast<llvm::MDNode>(it->second));
1517  }
1518
1519  // Otherwise create the type.
1520  llvm::DIType Res = CreateTypeNode(Ty, Unit);
1521
1522  // And update the type cache.
1523  TypeCache[Ty.getAsOpaquePtr()] = Res;
1524  return Res;
1525}
1526
1527/// CreateTypeNode - Create a new debug type node.
1528llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty,
1529                                         llvm::DIFile Unit) {
1530  // Handle qualifiers, which recursively handles what they refer to.
1531  if (Ty.hasLocalQualifiers())
1532    return CreateQualifiedType(Ty, Unit);
1533
1534  const char *Diag = 0;
1535
1536  // Work out details of type.
1537  switch (Ty->getTypeClass()) {
1538#define TYPE(Class, Base)
1539#define ABSTRACT_TYPE(Class, Base)
1540#define NON_CANONICAL_TYPE(Class, Base)
1541#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1542#include "clang/AST/TypeNodes.def"
1543    llvm_unreachable("Dependent types cannot show up in debug information");
1544
1545  case Type::ExtVector:
1546  case Type::Vector:
1547    return CreateType(cast<VectorType>(Ty), Unit);
1548  case Type::ObjCObjectPointer:
1549    return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1550  case Type::ObjCObject:
1551    return CreateType(cast<ObjCObjectType>(Ty), Unit);
1552  case Type::ObjCInterface:
1553    return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1554  case Type::Builtin: return CreateType(cast<BuiltinType>(Ty));
1555  case Type::Complex: return CreateType(cast<ComplexType>(Ty));
1556  case Type::Pointer: return CreateType(cast<PointerType>(Ty), Unit);
1557  case Type::BlockPointer:
1558    return CreateType(cast<BlockPointerType>(Ty), Unit);
1559  case Type::Typedef: return CreateType(cast<TypedefType>(Ty), Unit);
1560  case Type::Record:
1561  case Type::Enum:
1562    return CreateType(cast<TagType>(Ty));
1563  case Type::FunctionProto:
1564  case Type::FunctionNoProto:
1565    return CreateType(cast<FunctionType>(Ty), Unit);
1566  case Type::ConstantArray:
1567  case Type::VariableArray:
1568  case Type::IncompleteArray:
1569    return CreateType(cast<ArrayType>(Ty), Unit);
1570
1571  case Type::LValueReference:
1572    return CreateType(cast<LValueReferenceType>(Ty), Unit);
1573  case Type::RValueReference:
1574    return CreateType(cast<RValueReferenceType>(Ty), Unit);
1575
1576  case Type::MemberPointer:
1577    return CreateType(cast<MemberPointerType>(Ty), Unit);
1578
1579  case Type::Attributed:
1580  case Type::TemplateSpecialization:
1581  case Type::Elaborated:
1582  case Type::Paren:
1583  case Type::SubstTemplateTypeParm:
1584  case Type::TypeOfExpr:
1585  case Type::TypeOf:
1586  case Type::Decltype:
1587  case Type::UnaryTransform:
1588  case Type::Auto:
1589    llvm_unreachable("type should have been unwrapped!");
1590    return llvm::DIType();
1591  }
1592
1593  assert(Diag && "Fall through without a diagnostic?");
1594  unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1595                               "debug information for %0 is not yet supported");
1596  CGM.getDiags().Report(DiagID)
1597    << Diag;
1598  return llvm::DIType();
1599}
1600
1601/// CreateMemberType - Create new member and increase Offset by FType's size.
1602llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
1603                                           StringRef Name,
1604                                           uint64_t *Offset) {
1605  llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1606  uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
1607  unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
1608  llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
1609                                              FieldSize, FieldAlign,
1610                                              *Offset, 0, FieldTy);
1611  *Offset += FieldSize;
1612  return Ty;
1613}
1614
1615/// getFunctionDeclaration - Return debug info descriptor to describe method
1616/// declaration for the given method definition.
1617llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
1618  const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
1619  if (!FD) return llvm::DISubprogram();
1620
1621  // Setup context.
1622  getContextDescriptor(cast<Decl>(D->getDeclContext()));
1623
1624  llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1625    MI = SPCache.find(FD);
1626  if (MI != SPCache.end()) {
1627    llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(&*MI->second));
1628    if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
1629      return SP;
1630  }
1631
1632  for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
1633         E = FD->redecls_end(); I != E; ++I) {
1634    const FunctionDecl *NextFD = *I;
1635    llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1636      MI = SPCache.find(NextFD);
1637    if (MI != SPCache.end()) {
1638      llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(&*MI->second));
1639      if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
1640        return SP;
1641    }
1642  }
1643  return llvm::DISubprogram();
1644}
1645
1646// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
1647// implicit parameter "this".
1648llvm::DIType CGDebugInfo::getOrCreateFunctionType(const Decl * D, QualType FnType,
1649                                                  llvm::DIFile F) {
1650  if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1651    return getOrCreateMethodType(Method, F);
1652  else if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
1653    // Add "self" and "_cmd"
1654    SmallVector<llvm::Value *, 16> Elts;
1655
1656    // First element is always return type. For 'void' functions it is NULL.
1657    Elts.push_back(getOrCreateType(OMethod->getResultType(), F));
1658    // "self" pointer is always first argument.
1659    Elts.push_back(getOrCreateType(OMethod->getSelfDecl()->getType(), F));
1660    // "cmd" pointer is always second argument.
1661    Elts.push_back(getOrCreateType(OMethod->getCmdDecl()->getType(), F));
1662    // Get rest of the arguments.
1663    for (ObjCMethodDecl::param_iterator PI = OMethod->param_begin(),
1664           PE = OMethod->param_end(); PI != PE; ++PI)
1665      Elts.push_back(getOrCreateType((*PI)->getType(), F));
1666
1667    llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1668    return DBuilder.createSubroutineType(F, EltTypeArray);
1669  }
1670  return getOrCreateType(FnType, F);
1671}
1672
1673/// EmitFunctionStart - Constructs the debug code for entering a function -
1674/// "llvm.dbg.func.start.".
1675void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
1676                                    llvm::Function *Fn,
1677                                    CGBuilderTy &Builder) {
1678
1679  StringRef Name;
1680  StringRef LinkageName;
1681
1682  FnBeginRegionCount.push_back(RegionStack.size());
1683
1684  const Decl *D = GD.getDecl();
1685
1686  unsigned Flags = 0;
1687  llvm::DIFile Unit = getOrCreateFile(CurLoc);
1688  llvm::DIDescriptor FDContext(Unit);
1689  llvm::DIArray TParamsArray;
1690  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1691    // If there is a DISubprogram for  this function available then use it.
1692    llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1693      FI = SPCache.find(FD);
1694    if (FI != SPCache.end()) {
1695      llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(&*FI->second));
1696      if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
1697        llvm::MDNode *SPN = SP;
1698        RegionStack.push_back(SPN);
1699        RegionMap[D] = llvm::WeakVH(SP);
1700        return;
1701      }
1702    }
1703    Name = getFunctionName(FD);
1704    // Use mangled name as linkage name for c/c++ functions.
1705    if (!Fn->hasInternalLinkage())
1706      LinkageName = CGM.getMangledName(GD);
1707    if (LinkageName == Name)
1708      LinkageName = StringRef();
1709    if (FD->hasPrototype())
1710      Flags |= llvm::DIDescriptor::FlagPrototyped;
1711    if (const NamespaceDecl *NSDecl =
1712        dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
1713      FDContext = getOrCreateNameSpace(NSDecl);
1714    else if (const RecordDecl *RDecl =
1715             dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
1716      FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
1717
1718    // Collect template parameters.
1719    TParamsArray = CollectFunctionTemplateParams(FD, Unit);
1720  } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
1721    Name = getObjCMethodName(OMD);
1722    Flags |= llvm::DIDescriptor::FlagPrototyped;
1723  } else {
1724    // Use llvm function name.
1725    Name = Fn->getName();
1726    Flags |= llvm::DIDescriptor::FlagPrototyped;
1727  }
1728  if (!Name.empty() && Name[0] == '\01')
1729    Name = Name.substr(1);
1730
1731  // It is expected that CurLoc is set before using EmitFunctionStart.
1732  // Usually, CurLoc points to the left bracket location of compound
1733  // statement representing function body.
1734  unsigned LineNo = getLineNumber(CurLoc);
1735  if (D->isImplicit())
1736    Flags |= llvm::DIDescriptor::FlagArtificial;
1737  llvm::DISubprogram SPDecl = getFunctionDeclaration(D);
1738  llvm::DISubprogram SP =
1739    DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
1740                            LineNo, getOrCreateFunctionType(D, FnType, Unit),
1741                            Fn->hasInternalLinkage(), true/*definition*/,
1742                            Flags, CGM.getLangOptions().Optimize, Fn,
1743                            TParamsArray, SPDecl);
1744
1745  // Push function on region stack.
1746  llvm::MDNode *SPN = SP;
1747  RegionStack.push_back(SPN);
1748  RegionMap[D] = llvm::WeakVH(SP);
1749
1750  // Clear stack used to keep track of #line directives.
1751  LineDirectiveFiles.clear();
1752}
1753
1754
1755void CGDebugInfo::EmitStopPoint(CGBuilderTy &Builder) {
1756  if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
1757
1758  // Don't bother if things are the same as last time.
1759  SourceManager &SM = CGM.getContext().getSourceManager();
1760  if (CurLoc == PrevLoc ||
1761      SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
1762    // New Builder may not be in sync with CGDebugInfo.
1763    if (!Builder.getCurrentDebugLocation().isUnknown())
1764      return;
1765
1766  // The file may have had a line directive change. Process any of
1767  // those before updating the state.
1768  UpdateLineDirectiveRegion(Builder);
1769
1770  // Update last state.
1771  PrevLoc = CurLoc;
1772
1773  llvm::MDNode *Scope = RegionStack.back();
1774  Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(CurLoc),
1775                                                      getColumnNumber(CurLoc),
1776                                                      Scope));
1777}
1778
1779/// UpdateLineDirectiveRegion - Update region stack only if #line directive
1780/// has introduced scope change.
1781void CGDebugInfo::UpdateLineDirectiveRegion(CGBuilderTy &Builder) {
1782  if (CurLoc.isInvalid() || CurLoc.isMacroID() ||
1783      PrevLoc.isInvalid() || PrevLoc.isMacroID())
1784    return;
1785  SourceManager &SM = CGM.getContext().getSourceManager();
1786  PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
1787  PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
1788
1789  if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
1790      !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
1791    return;
1792
1793  // If #line directive stack is empty then we are entering a new scope.
1794  if (LineDirectiveFiles.empty()) {
1795    EmitRegionStart(Builder);
1796    LineDirectiveFiles.push_back(PCLoc.getFilename());
1797    return;
1798  }
1799
1800  assert (RegionStack.size() >= LineDirectiveFiles.size()
1801          && "error handling #line regions!");
1802
1803  bool SeenThisFile = false;
1804  // Chek if current file is already seen earlier.
1805  for(std::vector<const char *>::iterator I = LineDirectiveFiles.begin(),
1806        E = LineDirectiveFiles.end(); I != E; ++I)
1807    if (!strcmp(PCLoc.getFilename(), *I)) {
1808      SeenThisFile = true;
1809      break;
1810    }
1811
1812  // If #line for this file is seen earlier then pop out #line regions.
1813  if (SeenThisFile) {
1814    while (!LineDirectiveFiles.empty()) {
1815      const char *LastFile = LineDirectiveFiles.back();
1816      RegionStack.pop_back();
1817      LineDirectiveFiles.pop_back();
1818      if (!strcmp(PPLoc.getFilename(), LastFile))
1819        break;
1820    }
1821    return;
1822  }
1823
1824  // .. otherwise insert new #line region.
1825  EmitRegionStart(Builder);
1826  LineDirectiveFiles.push_back(PCLoc.getFilename());
1827
1828  return;
1829}
1830
1831/// EmitRegionStart- Constructs the debug code for entering a declarative
1832/// region - beginning of a DW_TAG_lexical_block.
1833void CGDebugInfo::EmitRegionStart(CGBuilderTy &Builder) {
1834  llvm::DIDescriptor D =
1835    DBuilder.createLexicalBlock(RegionStack.empty() ?
1836                                llvm::DIDescriptor() :
1837                                llvm::DIDescriptor(RegionStack.back()),
1838                                getOrCreateFile(CurLoc),
1839                                getLineNumber(CurLoc),
1840                                getColumnNumber(CurLoc));
1841  llvm::MDNode *DN = D;
1842  RegionStack.push_back(DN);
1843}
1844
1845/// EmitRegionEnd - Constructs the debug code for exiting a declarative
1846/// region - end of a DW_TAG_lexical_block.
1847void CGDebugInfo::EmitRegionEnd(CGBuilderTy &Builder) {
1848  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1849
1850  // Provide a region stop point.
1851  EmitStopPoint(Builder);
1852
1853  RegionStack.pop_back();
1854}
1855
1856/// EmitFunctionEnd - Constructs the debug code for exiting a function.
1857void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
1858  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1859  unsigned RCount = FnBeginRegionCount.back();
1860  assert(RCount <= RegionStack.size() && "Region stack mismatch");
1861
1862  // Pop all regions for this function.
1863  while (RegionStack.size() != RCount)
1864    EmitRegionEnd(Builder);
1865  FnBeginRegionCount.pop_back();
1866}
1867
1868// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
1869// See BuildByRefType.
1870llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const ValueDecl *VD,
1871                                                       uint64_t *XOffset) {
1872
1873  SmallVector<llvm::Value *, 5> EltTys;
1874  QualType FType;
1875  uint64_t FieldSize, FieldOffset;
1876  unsigned FieldAlign;
1877
1878  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1879  QualType Type = VD->getType();
1880
1881  FieldOffset = 0;
1882  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1883  EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1884  EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
1885  FType = CGM.getContext().IntTy;
1886  EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1887  EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1888
1889  bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type);
1890  if (HasCopyAndDispose) {
1891    FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1892    EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
1893                                      &FieldOffset));
1894    EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
1895                                      &FieldOffset));
1896  }
1897
1898  CharUnits Align = CGM.getContext().getDeclAlign(VD);
1899  if (Align > CGM.getContext().toCharUnitsFromBits(
1900        CGM.getContext().getTargetInfo().getPointerAlign(0))) {
1901    CharUnits FieldOffsetInBytes
1902      = CGM.getContext().toCharUnitsFromBits(FieldOffset);
1903    CharUnits AlignedOffsetInBytes
1904      = FieldOffsetInBytes.RoundUpToAlignment(Align);
1905    CharUnits NumPaddingBytes
1906      = AlignedOffsetInBytes - FieldOffsetInBytes;
1907
1908    if (NumPaddingBytes.isPositive()) {
1909      llvm::APInt pad(32, NumPaddingBytes.getQuantity());
1910      FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
1911                                                    pad, ArrayType::Normal, 0);
1912      EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
1913    }
1914  }
1915
1916  FType = Type;
1917  llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1918  FieldSize = CGM.getContext().getTypeSize(FType);
1919  FieldAlign = CGM.getContext().toBits(Align);
1920
1921  *XOffset = FieldOffset;
1922  FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
1923                                      0, FieldSize, FieldAlign,
1924                                      FieldOffset, 0, FieldTy);
1925  EltTys.push_back(FieldTy);
1926  FieldOffset += FieldSize;
1927
1928  llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1929
1930  unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
1931
1932  return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
1933                                   Elements);
1934}
1935
1936/// EmitDeclare - Emit local variable declaration debug info.
1937void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
1938                              llvm::Value *Storage,
1939                              unsigned ArgNo, CGBuilderTy &Builder) {
1940  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1941
1942  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1943  llvm::DIType Ty;
1944  uint64_t XOffset = 0;
1945  if (VD->hasAttr<BlocksAttr>())
1946    Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
1947  else
1948    Ty = getOrCreateType(VD->getType(), Unit);
1949
1950  // If there is not any debug info for type then do not emit debug info
1951  // for this variable.
1952  if (!Ty)
1953    return;
1954
1955  if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) {
1956    // If Storage is an aggregate returned as 'sret' then let debugger know
1957    // about this.
1958    if (Arg->hasStructRetAttr())
1959      Ty = DBuilder.createReferenceType(Ty);
1960    else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) {
1961      // If an aggregate variable has non trivial destructor or non trivial copy
1962      // constructor than it is pass indirectly. Let debug info know about this
1963      // by using reference of the aggregate type as a argument type.
1964      if (!Record->hasTrivialCopyConstructor() || !Record->hasTrivialDestructor())
1965        Ty = DBuilder.createReferenceType(Ty);
1966    }
1967  }
1968
1969  // Get location information.
1970  unsigned Line = getLineNumber(VD->getLocation());
1971  unsigned Column = getColumnNumber(VD->getLocation());
1972  unsigned Flags = 0;
1973  if (VD->isImplicit())
1974    Flags |= llvm::DIDescriptor::FlagArtificial;
1975  llvm::MDNode *Scope = RegionStack.back();
1976
1977  StringRef Name = VD->getName();
1978  if (!Name.empty()) {
1979    if (VD->hasAttr<BlocksAttr>()) {
1980      CharUnits offset = CharUnits::fromQuantity(32);
1981      SmallVector<llvm::Value *, 9> addr;
1982      llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext());
1983      addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
1984      // offset of __forwarding field
1985      offset = CGM.getContext().toCharUnitsFromBits(
1986        CGM.getContext().getTargetInfo().getPointerWidth(0));
1987      addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1988      addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
1989      addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
1990      // offset of x field
1991      offset = CGM.getContext().toCharUnitsFromBits(XOffset);
1992      addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1993
1994      // Create the descriptor for the variable.
1995      llvm::DIVariable D =
1996        DBuilder.createComplexVariable(Tag,
1997                                       llvm::DIDescriptor(RegionStack.back()),
1998                                       VD->getName(), Unit, Line, Ty,
1999                                       addr, ArgNo);
2000
2001      // Insert an llvm.dbg.declare into the current block.
2002      llvm::Instruction *Call =
2003        DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2004
2005      Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2006      return;
2007    }
2008      // Create the descriptor for the variable.
2009    llvm::DIVariable D =
2010      DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2011                                   Name, Unit, Line, Ty,
2012                                   CGM.getLangOptions().Optimize, Flags, ArgNo);
2013
2014    // Insert an llvm.dbg.declare into the current block.
2015    llvm::Instruction *Call =
2016      DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2017
2018    Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2019    return;
2020  }
2021
2022  // If VD is an anonymous union then Storage represents value for
2023  // all union fields.
2024  if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2025    const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2026    if (RD->isUnion()) {
2027      for (RecordDecl::field_iterator I = RD->field_begin(),
2028             E = RD->field_end();
2029           I != E; ++I) {
2030        FieldDecl *Field = *I;
2031        llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2032        StringRef FieldName = Field->getName();
2033
2034        // Ignore unnamed fields. Do not ignore unnamed records.
2035        if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2036          continue;
2037
2038        // Use VarDecl's Tag, Scope and Line number.
2039        llvm::DIVariable D =
2040          DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2041                                       FieldName, Unit, Line, FieldTy,
2042                                       CGM.getLangOptions().Optimize, Flags,
2043                                       ArgNo);
2044
2045        // Insert an llvm.dbg.declare into the current block.
2046        llvm::Instruction *Call =
2047          DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2048
2049        Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2050      }
2051    }
2052  }
2053}
2054
2055void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2056                                            llvm::Value *Storage,
2057                                            CGBuilderTy &Builder) {
2058  EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2059}
2060
2061void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
2062  const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
2063  const CGBlockInfo &blockInfo) {
2064  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
2065
2066  if (Builder.GetInsertBlock() == 0)
2067    return;
2068
2069  bool isByRef = VD->hasAttr<BlocksAttr>();
2070
2071  uint64_t XOffset = 0;
2072  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2073  llvm::DIType Ty;
2074  if (isByRef)
2075    Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2076  else
2077    Ty = getOrCreateType(VD->getType(), Unit);
2078
2079  // Get location information.
2080  unsigned Line = getLineNumber(VD->getLocation());
2081  unsigned Column = getColumnNumber(VD->getLocation());
2082
2083  const llvm::TargetData &target = CGM.getTargetData();
2084
2085  CharUnits offset = CharUnits::fromQuantity(
2086    target.getStructLayout(blockInfo.StructureType)
2087          ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2088
2089  SmallVector<llvm::Value *, 9> addr;
2090  llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext());
2091  addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2092  addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2093  if (isByRef) {
2094    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2095    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2096    // offset of __forwarding field
2097    offset = CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits());
2098    addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2099    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2100    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2101    // offset of x field
2102    offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2103    addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2104  }
2105
2106  // Create the descriptor for the variable.
2107  llvm::DIVariable D =
2108    DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
2109                                   llvm::DIDescriptor(RegionStack.back()),
2110                                   VD->getName(), Unit, Line, Ty, addr);
2111  // Insert an llvm.dbg.declare into the current block.
2112  llvm::Instruction *Call =
2113    DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2114
2115  llvm::MDNode *Scope = RegionStack.back();
2116  Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2117}
2118
2119/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2120/// variable declaration.
2121void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2122                                           unsigned ArgNo,
2123                                           CGBuilderTy &Builder) {
2124  EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2125}
2126
2127namespace {
2128  struct BlockLayoutChunk {
2129    uint64_t OffsetInBits;
2130    const BlockDecl::Capture *Capture;
2131  };
2132  bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2133    return l.OffsetInBits < r.OffsetInBits;
2134  }
2135}
2136
2137void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
2138                                                       llvm::Value *addr,
2139                                                       CGBuilderTy &Builder) {
2140  ASTContext &C = CGM.getContext();
2141  const BlockDecl *blockDecl = block.getBlockDecl();
2142
2143  // Collect some general information about the block's location.
2144  SourceLocation loc = blockDecl->getCaretLocation();
2145  llvm::DIFile tunit = getOrCreateFile(loc);
2146  unsigned line = getLineNumber(loc);
2147  unsigned column = getColumnNumber(loc);
2148
2149  // Build the debug-info type for the block literal.
2150  getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2151
2152  const llvm::StructLayout *blockLayout =
2153    CGM.getTargetData().getStructLayout(block.StructureType);
2154
2155  SmallVector<llvm::Value*, 16> fields;
2156  fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2157                                   blockLayout->getElementOffsetInBits(0),
2158                                   tunit, tunit));
2159  fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2160                                   blockLayout->getElementOffsetInBits(1),
2161                                   tunit, tunit));
2162  fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2163                                   blockLayout->getElementOffsetInBits(2),
2164                                   tunit, tunit));
2165  fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2166                                   blockLayout->getElementOffsetInBits(3),
2167                                   tunit, tunit));
2168  fields.push_back(createFieldType("__descriptor",
2169                                   C.getPointerType(block.NeedsCopyDispose ?
2170                                        C.getBlockDescriptorExtendedType() :
2171                                        C.getBlockDescriptorType()),
2172                                   0, loc, AS_public,
2173                                   blockLayout->getElementOffsetInBits(4),
2174                                   tunit, tunit));
2175
2176  // We want to sort the captures by offset, not because DWARF
2177  // requires this, but because we're paranoid about debuggers.
2178  SmallVector<BlockLayoutChunk, 8> chunks;
2179
2180  // 'this' capture.
2181  if (blockDecl->capturesCXXThis()) {
2182    BlockLayoutChunk chunk;
2183    chunk.OffsetInBits =
2184      blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2185    chunk.Capture = 0;
2186    chunks.push_back(chunk);
2187  }
2188
2189  // Variable captures.
2190  for (BlockDecl::capture_const_iterator
2191         i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2192       i != e; ++i) {
2193    const BlockDecl::Capture &capture = *i;
2194    const VarDecl *variable = capture.getVariable();
2195    const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2196
2197    // Ignore constant captures.
2198    if (captureInfo.isConstant())
2199      continue;
2200
2201    BlockLayoutChunk chunk;
2202    chunk.OffsetInBits =
2203      blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2204    chunk.Capture = &capture;
2205    chunks.push_back(chunk);
2206  }
2207
2208  // Sort by offset.
2209  llvm::array_pod_sort(chunks.begin(), chunks.end());
2210
2211  for (SmallVectorImpl<BlockLayoutChunk>::iterator
2212         i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2213    uint64_t offsetInBits = i->OffsetInBits;
2214    const BlockDecl::Capture *capture = i->Capture;
2215
2216    // If we have a null capture, this must be the C++ 'this' capture.
2217    if (!capture) {
2218      const CXXMethodDecl *method =
2219        cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2220      QualType type = method->getThisType(C);
2221
2222      fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2223                                       offsetInBits, tunit, tunit));
2224      continue;
2225    }
2226
2227    const VarDecl *variable = capture->getVariable();
2228    StringRef name = variable->getName();
2229
2230    llvm::DIType fieldType;
2231    if (capture->isByRef()) {
2232      std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2233
2234      // FIXME: this creates a second copy of this type!
2235      uint64_t xoffset;
2236      fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2237      fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2238      fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2239                                            ptrInfo.first, ptrInfo.second,
2240                                            offsetInBits, 0, fieldType);
2241    } else {
2242      fieldType = createFieldType(name, variable->getType(), 0,
2243                                  loc, AS_public, offsetInBits, tunit, tunit);
2244    }
2245    fields.push_back(fieldType);
2246  }
2247
2248  llvm::SmallString<36> typeName;
2249  llvm::raw_svector_ostream(typeName)
2250    << "__block_literal_" << CGM.getUniqueBlockCount();
2251
2252  llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2253
2254  llvm::DIType type =
2255    DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2256                              CGM.getContext().toBits(block.BlockSize),
2257                              CGM.getContext().toBits(block.BlockAlign),
2258                              0, fieldsArray);
2259  type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2260
2261  // Get overall information about the block.
2262  unsigned flags = llvm::DIDescriptor::FlagArtificial;
2263  llvm::MDNode *scope = RegionStack.back();
2264  StringRef name = ".block_descriptor";
2265
2266  // Create the descriptor for the parameter.
2267  llvm::DIVariable debugVar =
2268    DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
2269                                 llvm::DIDescriptor(scope),
2270                                 name, tunit, line, type,
2271                                 CGM.getLangOptions().Optimize, flags,
2272                                 cast<llvm::Argument>(addr)->getArgNo() + 1);
2273
2274  // Insert an llvm.dbg.value into the current block.
2275  llvm::Instruction *declare =
2276    DBuilder.insertDbgValueIntrinsic(addr, 0, debugVar,
2277                                     Builder.GetInsertBlock());
2278  declare->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2279}
2280
2281/// EmitGlobalVariable - Emit information about a global variable.
2282void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2283                                     const VarDecl *D) {
2284
2285  // Create global variable debug descriptor.
2286  llvm::DIFile Unit = getOrCreateFile(D->getLocation());
2287  unsigned LineNo = getLineNumber(D->getLocation());
2288
2289  QualType T = D->getType();
2290  if (T->isIncompleteArrayType()) {
2291
2292    // CodeGen turns int[] into int[1] so we'll do the same here.
2293    llvm::APSInt ConstVal(32);
2294
2295    ConstVal = 1;
2296    QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2297
2298    T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2299                                           ArrayType::Normal, 0);
2300  }
2301  StringRef DeclName = D->getName();
2302  StringRef LinkageName;
2303  if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
2304      && !isa<ObjCMethodDecl>(D->getDeclContext()))
2305    LinkageName = Var->getName();
2306  if (LinkageName == DeclName)
2307    LinkageName = StringRef();
2308  llvm::DIDescriptor DContext =
2309    getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
2310  DBuilder.createStaticVariable(DContext, DeclName, LinkageName,
2311                                Unit, LineNo, getOrCreateType(T, Unit),
2312                                Var->hasInternalLinkage(), Var);
2313}
2314
2315/// EmitGlobalVariable - Emit information about an objective-c interface.
2316void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2317                                     ObjCInterfaceDecl *ID) {
2318  // Create global variable debug descriptor.
2319  llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
2320  unsigned LineNo = getLineNumber(ID->getLocation());
2321
2322  StringRef Name = ID->getName();
2323
2324  QualType T = CGM.getContext().getObjCInterfaceType(ID);
2325  if (T->isIncompleteArrayType()) {
2326
2327    // CodeGen turns int[] into int[1] so we'll do the same here.
2328    llvm::APSInt ConstVal(32);
2329
2330    ConstVal = 1;
2331    QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2332
2333    T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2334                                           ArrayType::Normal, 0);
2335  }
2336
2337  DBuilder.createGlobalVariable(Name, Unit, LineNo,
2338                                getOrCreateType(T, Unit),
2339                                Var->hasInternalLinkage(), Var);
2340}
2341
2342/// EmitGlobalVariable - Emit global variable's debug info.
2343void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
2344                                     llvm::Constant *Init) {
2345  // Create the descriptor for the variable.
2346  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2347  StringRef Name = VD->getName();
2348  llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
2349  if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
2350    if (const EnumDecl *ED = dyn_cast<EnumDecl>(ECD->getDeclContext()))
2351      Ty = CreateEnumType(ED);
2352  }
2353  // Do not use DIGlobalVariable for enums.
2354  if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
2355    return;
2356  DBuilder.createStaticVariable(Unit, Name, Name, Unit,
2357                                getLineNumber(VD->getLocation()),
2358                                Ty, true, Init);
2359}
2360
2361/// getOrCreateNamesSpace - Return namespace descriptor for the given
2362/// namespace decl.
2363llvm::DINameSpace
2364CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
2365  llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
2366    NameSpaceCache.find(NSDecl);
2367  if (I != NameSpaceCache.end())
2368    return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
2369
2370  unsigned LineNo = getLineNumber(NSDecl->getLocation());
2371  llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
2372  llvm::DIDescriptor Context =
2373    getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
2374  llvm::DINameSpace NS =
2375    DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
2376  NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
2377  return NS;
2378}
2379
2380/// UpdateCompletedType - Update type cache because the type is now
2381/// translated.
2382void CGDebugInfo::UpdateCompletedType(const TagDecl *TD) {
2383  QualType Ty = CGM.getContext().getTagDeclType(TD);
2384
2385  // If the type exist in type cache then remove it from the cache.
2386  // There is no need to prepare debug info for the completed type
2387  // right now. It will be generated on demand lazily.
2388  llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2389    TypeCache.find(Ty.getAsOpaquePtr());
2390  if (it != TypeCache.end())
2391    TypeCache.erase(it);
2392}
2393