CGDebugInfo.cpp revision d1ab1a2dffa66a88e5215216893adcfc658d3e7e
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(LexicalBlockStack.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  LexicalBlockStack.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  LexicalBlockStack.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 since we won't be able to lay out the entire 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 a recursive interface, we first generate a debug descriptor
1162  // for the struct as a forward declaration. Then (if it is a definition)
1163  // we go through and get debug info for all of its members.  Finally, we
1164  // create a descriptor for the complete type (which may refer to the
1165  // forward decl if the struct is recursive) and replace all uses of the
1166  // 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  LexicalBlockStack.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    // We can't know the offset of our ivar in the structure if we're using
1227    // the non-fragile abi and the debugger should ignore the value anyways.
1228    // Call it the FieldNo+1 due to how debuggers use the information,
1229    // e.g. negating the value when it needs a lookup in the dynamic table.
1230    uint64_t FieldOffset = CGM.getLangOptions().ObjCNonFragileABI ? FieldNo+1
1231      : RL.getFieldOffset(FieldNo);
1232
1233    unsigned Flags = 0;
1234    if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1235      Flags = llvm::DIDescriptor::FlagProtected;
1236    else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1237      Flags = llvm::DIDescriptor::FlagPrivate;
1238
1239    StringRef PropertyName;
1240    StringRef PropertyGetter;
1241    StringRef PropertySetter;
1242    unsigned PropertyAttributes = 0;
1243    ObjCPropertyDecl *PD = NULL;
1244    if (ImpD)
1245      if (ObjCPropertyImplDecl *PImpD =
1246	  ImpD->FindPropertyImplIvarDecl(Field->getIdentifier()))
1247	PD = PImpD->getPropertyDecl();
1248    if (PD) {
1249      PropertyName = PD->getName();
1250      PropertyGetter = getSelectorName(PD->getGetterName());
1251      PropertySetter = getSelectorName(PD->getSetterName());
1252      PropertyAttributes = PD->getPropertyAttributes();
1253    }
1254    FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1255                                      FieldLine, FieldSize, FieldAlign,
1256                                      FieldOffset, Flags, FieldTy,
1257                                      PropertyName, PropertyGetter,
1258                                      PropertySetter, PropertyAttributes);
1259    EltTys.push_back(FieldTy);
1260  }
1261
1262  llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1263
1264  LexicalBlockStack.pop_back();
1265  llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI =
1266    RegionMap.find(Ty->getDecl());
1267  if (RI != RegionMap.end())
1268    RegionMap.erase(RI);
1269
1270  // Bit size, align and offset of the type.
1271  uint64_t Size = CGM.getContext().getTypeSize(Ty);
1272  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1273
1274  unsigned Flags = 0;
1275  if (ID->getImplementation())
1276    Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1277
1278  llvm::DIType RealDecl =
1279    DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1280                                  Line, Size, Align, Flags,
1281                                  Elements, RuntimeLang);
1282
1283  // Now that we have a real decl for the struct, replace anything using the
1284  // old decl with the new one.  This will recursively update the debug info.
1285  llvm::DIType(FwdDeclNode).replaceAllUsesWith(RealDecl);
1286  RegionMap[ID] = llvm::WeakVH(RealDecl);
1287
1288  return RealDecl;
1289}
1290
1291llvm::DIType CGDebugInfo::CreateType(const TagType *Ty) {
1292  if (const RecordType *RT = dyn_cast<RecordType>(Ty))
1293    return CreateType(RT);
1294  else if (const EnumType *ET = dyn_cast<EnumType>(Ty))
1295    return CreateEnumType(ET->getDecl());
1296
1297  return llvm::DIType();
1298}
1299
1300llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty,
1301                                     llvm::DIFile Unit) {
1302  llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1303  int64_t NumElems = Ty->getNumElements();
1304  int64_t LowerBound = 0;
1305  if (NumElems == 0)
1306    // If number of elements are not known then this is an unbounded array.
1307    // Use Low = 1, Hi = 0 to express such arrays.
1308    LowerBound = 1;
1309  else
1310    --NumElems;
1311
1312  llvm::Value *Subscript = DBuilder.getOrCreateSubrange(LowerBound, NumElems);
1313  llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1314
1315  uint64_t Size = CGM.getContext().getTypeSize(Ty);
1316  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1317
1318  return
1319    DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1320}
1321
1322llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1323                                     llvm::DIFile Unit) {
1324  uint64_t Size;
1325  uint64_t Align;
1326
1327
1328  // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1329  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1330    Size = 0;
1331    Align =
1332      CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1333  } else if (Ty->isIncompleteArrayType()) {
1334    Size = 0;
1335    Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1336  } else if (Ty->isDependentSizedArrayType() || Ty->isIncompleteType()) {
1337    Size = 0;
1338    Align = 0;
1339  } else {
1340    // Size and align of the whole array, not the element type.
1341    Size = CGM.getContext().getTypeSize(Ty);
1342    Align = CGM.getContext().getTypeAlign(Ty);
1343  }
1344
1345  // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
1346  // interior arrays, do we care?  Why aren't nested arrays represented the
1347  // obvious/recursive way?
1348  SmallVector<llvm::Value *, 8> Subscripts;
1349  QualType EltTy(Ty, 0);
1350  if (Ty->isIncompleteArrayType())
1351    EltTy = Ty->getElementType();
1352  else {
1353    while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1354      int64_t UpperBound = 0;
1355      int64_t LowerBound = 0;
1356      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty)) {
1357        if (CAT->getSize().getZExtValue())
1358          UpperBound = CAT->getSize().getZExtValue() - 1;
1359      } else
1360        // This is an unbounded array. Use Low = 1, Hi = 0 to express such
1361        // arrays.
1362        LowerBound = 1;
1363
1364      // FIXME: Verify this is right for VLAs.
1365      Subscripts.push_back(DBuilder.getOrCreateSubrange(LowerBound, UpperBound));
1366      EltTy = Ty->getElementType();
1367    }
1368  }
1369
1370  llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1371
1372  llvm::DIType DbgTy =
1373    DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1374                             SubscriptArray);
1375  return DbgTy;
1376}
1377
1378llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1379                                     llvm::DIFile Unit) {
1380  return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1381                               Ty, Ty->getPointeeType(), Unit);
1382}
1383
1384llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1385                                     llvm::DIFile Unit) {
1386  return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
1387                               Ty, Ty->getPointeeType(), Unit);
1388}
1389
1390llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1391                                     llvm::DIFile U) {
1392  QualType PointerDiffTy = CGM.getContext().getPointerDiffType();
1393  llvm::DIType PointerDiffDITy = getOrCreateType(PointerDiffTy, U);
1394
1395  if (!Ty->getPointeeType()->isFunctionType()) {
1396    // We have a data member pointer type.
1397    return PointerDiffDITy;
1398  }
1399
1400  // We have a member function pointer type. Treat it as a struct with two
1401  // ptrdiff_t members.
1402  std::pair<uint64_t, unsigned> Info = CGM.getContext().getTypeInfo(Ty);
1403
1404  uint64_t FieldOffset = 0;
1405  llvm::Value *ElementTypes[2];
1406
1407  // FIXME: This should probably be a function type instead.
1408  ElementTypes[0] =
1409    DBuilder.createMemberType(U, "ptr", U, 0,
1410                              Info.first, Info.second, FieldOffset, 0,
1411                              PointerDiffDITy);
1412  FieldOffset += Info.first;
1413
1414  ElementTypes[1] =
1415    DBuilder.createMemberType(U, "ptr", U, 0,
1416                              Info.first, Info.second, FieldOffset, 0,
1417                              PointerDiffDITy);
1418
1419  llvm::DIArray Elements = DBuilder.getOrCreateArray(ElementTypes);
1420
1421  return DBuilder.createStructType(U, StringRef("test"),
1422                                   U, 0, FieldOffset,
1423                                   0, 0, Elements);
1424}
1425
1426/// CreateEnumType - get enumeration type.
1427llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1428  llvm::DIFile Unit = getOrCreateFile(ED->getLocation());
1429  SmallVector<llvm::Value *, 16> Enumerators;
1430
1431  // Create DIEnumerator elements for each enumerator.
1432  for (EnumDecl::enumerator_iterator
1433         Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1434       Enum != EnumEnd; ++Enum) {
1435    Enumerators.push_back(
1436      DBuilder.createEnumerator(Enum->getName(),
1437                                Enum->getInitVal().getZExtValue()));
1438  }
1439
1440  // Return a CompositeType for the enum itself.
1441  llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1442
1443  llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1444  unsigned Line = getLineNumber(ED->getLocation());
1445  uint64_t Size = 0;
1446  uint64_t Align = 0;
1447  if (!ED->getTypeForDecl()->isIncompleteType()) {
1448    Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1449    Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1450  }
1451  llvm::DIDescriptor EnumContext =
1452    getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1453  llvm::DIType DbgTy =
1454    DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1455                                   Size, Align, EltArray);
1456  return DbgTy;
1457}
1458
1459static QualType UnwrapTypeForDebugInfo(QualType T) {
1460  do {
1461    QualType LastT = T;
1462    switch (T->getTypeClass()) {
1463    default:
1464      return T;
1465    case Type::TemplateSpecialization:
1466      T = cast<TemplateSpecializationType>(T)->desugar();
1467      break;
1468    case Type::TypeOfExpr:
1469      T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1470      break;
1471    case Type::TypeOf:
1472      T = cast<TypeOfType>(T)->getUnderlyingType();
1473      break;
1474    case Type::Decltype:
1475      T = cast<DecltypeType>(T)->getUnderlyingType();
1476      break;
1477    case Type::UnaryTransform:
1478      T = cast<UnaryTransformType>(T)->getUnderlyingType();
1479      break;
1480    case Type::Attributed:
1481      T = cast<AttributedType>(T)->getEquivalentType();
1482      break;
1483    case Type::Elaborated:
1484      T = cast<ElaboratedType>(T)->getNamedType();
1485      break;
1486    case Type::Paren:
1487      T = cast<ParenType>(T)->getInnerType();
1488      break;
1489    case Type::SubstTemplateTypeParm:
1490      T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
1491      break;
1492    case Type::Auto:
1493      T = cast<AutoType>(T)->getDeducedType();
1494      break;
1495    }
1496
1497    assert(T != LastT && "Type unwrapping failed to unwrap!");
1498    if (T == LastT)
1499      return T;
1500  } while (true);
1501
1502  return T;
1503}
1504
1505/// getOrCreateType - Get the type from the cache or create a new
1506/// one if necessary.
1507llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty,
1508                                          llvm::DIFile Unit) {
1509  if (Ty.isNull())
1510    return llvm::DIType();
1511
1512  // Unwrap the type as needed for debug information.
1513  Ty = UnwrapTypeForDebugInfo(Ty);
1514
1515  // Check for existing entry.
1516  llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1517    TypeCache.find(Ty.getAsOpaquePtr());
1518  if (it != TypeCache.end()) {
1519    // Verify that the debug info still exists.
1520    if (&*it->second)
1521      return llvm::DIType(cast<llvm::MDNode>(it->second));
1522  }
1523
1524  // Otherwise create the type.
1525  llvm::DIType Res = CreateTypeNode(Ty, Unit);
1526
1527  // And update the type cache.
1528  TypeCache[Ty.getAsOpaquePtr()] = Res;
1529  return Res;
1530}
1531
1532/// CreateTypeNode - Create a new debug type node.
1533llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty,
1534                                         llvm::DIFile Unit) {
1535  // Handle qualifiers, which recursively handles what they refer to.
1536  if (Ty.hasLocalQualifiers())
1537    return CreateQualifiedType(Ty, Unit);
1538
1539  const char *Diag = 0;
1540
1541  // Work out details of type.
1542  switch (Ty->getTypeClass()) {
1543#define TYPE(Class, Base)
1544#define ABSTRACT_TYPE(Class, Base)
1545#define NON_CANONICAL_TYPE(Class, Base)
1546#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1547#include "clang/AST/TypeNodes.def"
1548    llvm_unreachable("Dependent types cannot show up in debug information");
1549
1550  case Type::ExtVector:
1551  case Type::Vector:
1552    return CreateType(cast<VectorType>(Ty), Unit);
1553  case Type::ObjCObjectPointer:
1554    return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1555  case Type::ObjCObject:
1556    return CreateType(cast<ObjCObjectType>(Ty), Unit);
1557  case Type::ObjCInterface:
1558    return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1559  case Type::Builtin: return CreateType(cast<BuiltinType>(Ty));
1560  case Type::Complex: return CreateType(cast<ComplexType>(Ty));
1561  case Type::Pointer: return CreateType(cast<PointerType>(Ty), Unit);
1562  case Type::BlockPointer:
1563    return CreateType(cast<BlockPointerType>(Ty), Unit);
1564  case Type::Typedef: return CreateType(cast<TypedefType>(Ty), Unit);
1565  case Type::Record:
1566  case Type::Enum:
1567    return CreateType(cast<TagType>(Ty));
1568  case Type::FunctionProto:
1569  case Type::FunctionNoProto:
1570    return CreateType(cast<FunctionType>(Ty), Unit);
1571  case Type::ConstantArray:
1572  case Type::VariableArray:
1573  case Type::IncompleteArray:
1574    return CreateType(cast<ArrayType>(Ty), Unit);
1575
1576  case Type::LValueReference:
1577    return CreateType(cast<LValueReferenceType>(Ty), Unit);
1578  case Type::RValueReference:
1579    return CreateType(cast<RValueReferenceType>(Ty), Unit);
1580
1581  case Type::MemberPointer:
1582    return CreateType(cast<MemberPointerType>(Ty), Unit);
1583
1584  case Type::Attributed:
1585  case Type::TemplateSpecialization:
1586  case Type::Elaborated:
1587  case Type::Paren:
1588  case Type::SubstTemplateTypeParm:
1589  case Type::TypeOfExpr:
1590  case Type::TypeOf:
1591  case Type::Decltype:
1592  case Type::UnaryTransform:
1593  case Type::Auto:
1594    llvm_unreachable("type should have been unwrapped!");
1595    return llvm::DIType();
1596  }
1597
1598  assert(Diag && "Fall through without a diagnostic?");
1599  unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1600                               "debug information for %0 is not yet supported");
1601  CGM.getDiags().Report(DiagID)
1602    << Diag;
1603  return llvm::DIType();
1604}
1605
1606/// CreateMemberType - Create new member and increase Offset by FType's size.
1607llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
1608                                           StringRef Name,
1609                                           uint64_t *Offset) {
1610  llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1611  uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
1612  unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
1613  llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
1614                                              FieldSize, FieldAlign,
1615                                              *Offset, 0, FieldTy);
1616  *Offset += FieldSize;
1617  return Ty;
1618}
1619
1620/// getFunctionDeclaration - Return debug info descriptor to describe method
1621/// declaration for the given method definition.
1622llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
1623  const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
1624  if (!FD) return llvm::DISubprogram();
1625
1626  // Setup context.
1627  getContextDescriptor(cast<Decl>(D->getDeclContext()));
1628
1629  llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1630    MI = SPCache.find(FD);
1631  if (MI != SPCache.end()) {
1632    llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(&*MI->second));
1633    if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
1634      return SP;
1635  }
1636
1637  for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
1638         E = FD->redecls_end(); I != E; ++I) {
1639    const FunctionDecl *NextFD = *I;
1640    llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1641      MI = SPCache.find(NextFD);
1642    if (MI != SPCache.end()) {
1643      llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(&*MI->second));
1644      if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
1645        return SP;
1646    }
1647  }
1648  return llvm::DISubprogram();
1649}
1650
1651// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
1652// implicit parameter "this".
1653llvm::DIType CGDebugInfo::getOrCreateFunctionType(const Decl * D, QualType FnType,
1654                                                  llvm::DIFile F) {
1655  if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1656    return getOrCreateMethodType(Method, F);
1657  else if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
1658    // Add "self" and "_cmd"
1659    SmallVector<llvm::Value *, 16> Elts;
1660
1661    // First element is always return type. For 'void' functions it is NULL.
1662    Elts.push_back(getOrCreateType(OMethod->getResultType(), F));
1663    // "self" pointer is always first argument.
1664    Elts.push_back(getOrCreateType(OMethod->getSelfDecl()->getType(), F));
1665    // "cmd" pointer is always second argument.
1666    Elts.push_back(getOrCreateType(OMethod->getCmdDecl()->getType(), F));
1667    // Get rest of the arguments.
1668    for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
1669           PE = OMethod->param_end(); PI != PE; ++PI)
1670      Elts.push_back(getOrCreateType((*PI)->getType(), F));
1671
1672    llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1673    return DBuilder.createSubroutineType(F, EltTypeArray);
1674  }
1675  return getOrCreateType(FnType, F);
1676}
1677
1678/// EmitFunctionStart - Constructs the debug code for entering a function -
1679/// "llvm.dbg.func.start.".
1680void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
1681                                    llvm::Function *Fn,
1682                                    CGBuilderTy &Builder) {
1683
1684  StringRef Name;
1685  StringRef LinkageName;
1686
1687  FnBeginRegionCount.push_back(LexicalBlockStack.size());
1688
1689  const Decl *D = GD.getDecl();
1690
1691  unsigned Flags = 0;
1692  llvm::DIFile Unit = getOrCreateFile(CurLoc);
1693  llvm::DIDescriptor FDContext(Unit);
1694  llvm::DIArray TParamsArray;
1695  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1696    // If there is a DISubprogram for  this function available then use it.
1697    llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1698      FI = SPCache.find(FD);
1699    if (FI != SPCache.end()) {
1700      llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(&*FI->second));
1701      if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
1702        llvm::MDNode *SPN = SP;
1703        LexicalBlockStack.push_back(SPN);
1704        RegionMap[D] = llvm::WeakVH(SP);
1705        return;
1706      }
1707    }
1708    Name = getFunctionName(FD);
1709    // Use mangled name as linkage name for c/c++ functions.
1710    if (!Fn->hasInternalLinkage())
1711      LinkageName = CGM.getMangledName(GD);
1712    if (LinkageName == Name)
1713      LinkageName = StringRef();
1714    if (FD->hasPrototype())
1715      Flags |= llvm::DIDescriptor::FlagPrototyped;
1716    if (const NamespaceDecl *NSDecl =
1717        dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
1718      FDContext = getOrCreateNameSpace(NSDecl);
1719    else if (const RecordDecl *RDecl =
1720             dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
1721      FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
1722
1723    // Collect template parameters.
1724    TParamsArray = CollectFunctionTemplateParams(FD, Unit);
1725  } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
1726    Name = getObjCMethodName(OMD);
1727    Flags |= llvm::DIDescriptor::FlagPrototyped;
1728  } else {
1729    // Use llvm function name.
1730    Name = Fn->getName();
1731    Flags |= llvm::DIDescriptor::FlagPrototyped;
1732  }
1733  if (!Name.empty() && Name[0] == '\01')
1734    Name = Name.substr(1);
1735
1736  // It is expected that CurLoc is set before using EmitFunctionStart.
1737  // Usually, CurLoc points to the left bracket location of compound
1738  // statement representing function body.
1739  unsigned LineNo = getLineNumber(CurLoc);
1740  if (D->isImplicit())
1741    Flags |= llvm::DIDescriptor::FlagArtificial;
1742  llvm::DISubprogram SPDecl = getFunctionDeclaration(D);
1743  llvm::DISubprogram SP =
1744    DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
1745                            LineNo, getOrCreateFunctionType(D, FnType, Unit),
1746                            Fn->hasInternalLinkage(), true/*definition*/,
1747                            Flags, CGM.getLangOptions().Optimize, Fn,
1748                            TParamsArray, SPDecl);
1749
1750  // Push function on region stack.
1751  llvm::MDNode *SPN = SP;
1752  LexicalBlockStack.push_back(SPN);
1753  RegionMap[D] = llvm::WeakVH(SP);
1754
1755  // Clear stack used to keep track of #line directives.
1756  LineDirectiveFiles.clear();
1757}
1758
1759// UpdateLineDirectiveRegion - Update region stack only if #line directive
1760// has introduced scope change.
1761void CGDebugInfo::UpdateLineDirectiveRegion(CGBuilderTy &Builder) {
1762  if (CurLoc.isInvalid() || CurLoc.isMacroID() ||
1763      PrevLoc.isInvalid() || PrevLoc.isMacroID())
1764    return;
1765  SourceManager &SM = CGM.getContext().getSourceManager();
1766  PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
1767  PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
1768
1769  if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
1770      !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
1771    return;
1772
1773  // If #line directive stack is empty then we are entering a new scope.
1774  if (LineDirectiveFiles.empty()) {
1775    EmitLexicalBlockStart(Builder);
1776    LineDirectiveFiles.push_back(PCLoc.getFilename());
1777    return;
1778  }
1779
1780  assert (LexicalBlockStack.size() >= LineDirectiveFiles.size()
1781	  && "error handling #line regions!");
1782
1783  bool SeenThisFile = false;
1784  // Chek if current file is already seen earlier.
1785  for(std::vector<const char *>::iterator I = LineDirectiveFiles.begin(),
1786	E = LineDirectiveFiles.end(); I != E; ++I)
1787    if (!strcmp(PCLoc.getFilename(), *I)) {
1788      SeenThisFile = true;
1789      break;
1790    }
1791
1792  // If #line for this file is seen earlier then pop out #line regions.
1793  if (SeenThisFile) {
1794    while (!LineDirectiveFiles.empty()) {
1795      const char *LastFile = LineDirectiveFiles.back();
1796      LexicalBlockStack.pop_back();
1797      LineDirectiveFiles.pop_back();
1798      if (!strcmp(PPLoc.getFilename(), LastFile))
1799	break;
1800    }
1801    return;
1802  }
1803
1804  // .. otherwise insert new #line region.
1805  EmitLexicalBlockStart(Builder);
1806  LineDirectiveFiles.push_back(PCLoc.getFilename());
1807
1808  return;
1809}
1810
1811/// EmitLocation - Emit metadata to indicate a change in line/column
1812/// information in the source file.
1813void CGDebugInfo::EmitLocation(CGBuilderTy &Builder) {
1814  if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
1815
1816  // Don't bother if things are the same as last time.
1817  SourceManager &SM = CGM.getContext().getSourceManager();
1818  if (CurLoc == PrevLoc ||
1819      SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
1820    // New Builder may not be in sync with CGDebugInfo.
1821    if (!Builder.getCurrentDebugLocation().isUnknown())
1822      return;
1823
1824  // The file may have had a line directive change. Process any of
1825  // those before updating the state.
1826  UpdateLineDirectiveRegion(Builder);
1827
1828  // Update last state.
1829  PrevLoc = CurLoc;
1830
1831  llvm::MDNode *Scope = LexicalBlockStack.back();
1832  Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(CurLoc),
1833                                                      getColumnNumber(CurLoc),
1834                                                      Scope));
1835}
1836
1837/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
1838/// region - beginning of a DW_TAG_lexical_block.
1839void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder) {
1840  llvm::DIDescriptor D =
1841    DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
1842                                llvm::DIDescriptor() :
1843                                llvm::DIDescriptor(LexicalBlockStack.back()),
1844                                getOrCreateFile(CurLoc),
1845                                getLineNumber(CurLoc),
1846                                getColumnNumber(CurLoc));
1847  llvm::MDNode *DN = D;
1848  LexicalBlockStack.push_back(DN);
1849}
1850
1851/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
1852/// region - end of a DW_TAG_lexical_block.
1853void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder) {
1854  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
1855
1856  // Provide a region stop point.
1857  EmitLocation(Builder);
1858
1859  LexicalBlockStack.pop_back();
1860}
1861
1862/// EmitFunctionEnd - Constructs the debug code for exiting a function.
1863void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
1864  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
1865  unsigned RCount = FnBeginRegionCount.back();
1866  assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
1867
1868  // Pop all regions for this function.
1869  while (LexicalBlockStack.size() != RCount)
1870    EmitLexicalBlockEnd(Builder);
1871  FnBeginRegionCount.pop_back();
1872}
1873
1874// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
1875// See BuildByRefType.
1876llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const ValueDecl *VD,
1877                                                       uint64_t *XOffset) {
1878
1879  SmallVector<llvm::Value *, 5> EltTys;
1880  QualType FType;
1881  uint64_t FieldSize, FieldOffset;
1882  unsigned FieldAlign;
1883
1884  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1885  QualType Type = VD->getType();
1886
1887  FieldOffset = 0;
1888  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1889  EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1890  EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
1891  FType = CGM.getContext().IntTy;
1892  EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1893  EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1894
1895  bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type);
1896  if (HasCopyAndDispose) {
1897    FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1898    EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
1899                                      &FieldOffset));
1900    EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
1901                                      &FieldOffset));
1902  }
1903
1904  CharUnits Align = CGM.getContext().getDeclAlign(VD);
1905  if (Align > CGM.getContext().toCharUnitsFromBits(
1906        CGM.getContext().getTargetInfo().getPointerAlign(0))) {
1907    CharUnits FieldOffsetInBytes
1908      = CGM.getContext().toCharUnitsFromBits(FieldOffset);
1909    CharUnits AlignedOffsetInBytes
1910      = FieldOffsetInBytes.RoundUpToAlignment(Align);
1911    CharUnits NumPaddingBytes
1912      = AlignedOffsetInBytes - FieldOffsetInBytes;
1913
1914    if (NumPaddingBytes.isPositive()) {
1915      llvm::APInt pad(32, NumPaddingBytes.getQuantity());
1916      FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
1917                                                    pad, ArrayType::Normal, 0);
1918      EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
1919    }
1920  }
1921
1922  FType = Type;
1923  llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1924  FieldSize = CGM.getContext().getTypeSize(FType);
1925  FieldAlign = CGM.getContext().toBits(Align);
1926
1927  *XOffset = FieldOffset;
1928  FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
1929                                      0, FieldSize, FieldAlign,
1930                                      FieldOffset, 0, FieldTy);
1931  EltTys.push_back(FieldTy);
1932  FieldOffset += FieldSize;
1933
1934  llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1935
1936  unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
1937
1938  return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
1939                                   Elements);
1940}
1941
1942/// EmitDeclare - Emit local variable declaration debug info.
1943void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
1944                              llvm::Value *Storage,
1945                              unsigned ArgNo, CGBuilderTy &Builder) {
1946  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
1947
1948  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1949  llvm::DIType Ty;
1950  uint64_t XOffset = 0;
1951  if (VD->hasAttr<BlocksAttr>())
1952    Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
1953  else
1954    Ty = getOrCreateType(VD->getType(), Unit);
1955
1956  // If there is not any debug info for type then do not emit debug info
1957  // for this variable.
1958  if (!Ty)
1959    return;
1960
1961  if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) {
1962    // If Storage is an aggregate returned as 'sret' then let debugger know
1963    // about this.
1964    if (Arg->hasStructRetAttr())
1965      Ty = DBuilder.createReferenceType(Ty);
1966    else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) {
1967      // If an aggregate variable has non trivial destructor or non trivial copy
1968      // constructor than it is pass indirectly. Let debug info know about this
1969      // by using reference of the aggregate type as a argument type.
1970      if (!Record->hasTrivialCopyConstructor() || !Record->hasTrivialDestructor())
1971        Ty = DBuilder.createReferenceType(Ty);
1972    }
1973  }
1974
1975  // Get location information.
1976  unsigned Line = getLineNumber(VD->getLocation());
1977  unsigned Column = getColumnNumber(VD->getLocation());
1978  unsigned Flags = 0;
1979  if (VD->isImplicit())
1980    Flags |= llvm::DIDescriptor::FlagArtificial;
1981  llvm::MDNode *Scope = LexicalBlockStack.back();
1982
1983  StringRef Name = VD->getName();
1984  if (!Name.empty()) {
1985    if (VD->hasAttr<BlocksAttr>()) {
1986      CharUnits offset = CharUnits::fromQuantity(32);
1987      SmallVector<llvm::Value *, 9> addr;
1988      llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext());
1989      addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
1990      // offset of __forwarding field
1991      offset = CGM.getContext().toCharUnitsFromBits(
1992        CGM.getContext().getTargetInfo().getPointerWidth(0));
1993      addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1994      addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
1995      addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
1996      // offset of x field
1997      offset = CGM.getContext().toCharUnitsFromBits(XOffset);
1998      addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1999
2000      // Create the descriptor for the variable.
2001      llvm::DIVariable D =
2002        DBuilder.createComplexVariable(Tag,
2003                                       llvm::DIDescriptor(LexicalBlockStack.back()),
2004                                       VD->getName(), Unit, Line, Ty,
2005                                       addr, ArgNo);
2006
2007      // Insert an llvm.dbg.declare into the current block.
2008      llvm::Instruction *Call =
2009        DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2010
2011      Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2012      return;
2013    }
2014      // Create the descriptor for the variable.
2015    llvm::DIVariable D =
2016      DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2017                                   Name, Unit, Line, Ty,
2018                                   CGM.getLangOptions().Optimize, Flags, ArgNo);
2019
2020    // Insert an llvm.dbg.declare into the current block.
2021    llvm::Instruction *Call =
2022      DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2023
2024    Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2025    return;
2026  }
2027
2028  // If VD is an anonymous union then Storage represents value for
2029  // all union fields.
2030  if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2031    const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2032    if (RD->isUnion()) {
2033      for (RecordDecl::field_iterator I = RD->field_begin(),
2034             E = RD->field_end();
2035           I != E; ++I) {
2036        FieldDecl *Field = *I;
2037        llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2038        StringRef FieldName = Field->getName();
2039
2040        // Ignore unnamed fields. Do not ignore unnamed records.
2041        if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2042          continue;
2043
2044        // Use VarDecl's Tag, Scope and Line number.
2045        llvm::DIVariable D =
2046          DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2047                                       FieldName, Unit, Line, FieldTy,
2048                                       CGM.getLangOptions().Optimize, Flags,
2049                                       ArgNo);
2050
2051        // Insert an llvm.dbg.declare into the current block.
2052        llvm::Instruction *Call =
2053          DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2054
2055        Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2056      }
2057    }
2058  }
2059}
2060
2061void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2062                                            llvm::Value *Storage,
2063                                            CGBuilderTy &Builder) {
2064  EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2065}
2066
2067void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
2068  const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
2069  const CGBlockInfo &blockInfo) {
2070  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2071
2072  if (Builder.GetInsertBlock() == 0)
2073    return;
2074
2075  bool isByRef = VD->hasAttr<BlocksAttr>();
2076
2077  uint64_t XOffset = 0;
2078  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2079  llvm::DIType Ty;
2080  if (isByRef)
2081    Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2082  else
2083    Ty = getOrCreateType(VD->getType(), Unit);
2084
2085  // Get location information.
2086  unsigned Line = getLineNumber(VD->getLocation());
2087  unsigned Column = getColumnNumber(VD->getLocation());
2088
2089  const llvm::TargetData &target = CGM.getTargetData();
2090
2091  CharUnits offset = CharUnits::fromQuantity(
2092    target.getStructLayout(blockInfo.StructureType)
2093          ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2094
2095  SmallVector<llvm::Value *, 9> addr;
2096  llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext());
2097  addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2098  addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2099  if (isByRef) {
2100    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2101    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2102    // offset of __forwarding field
2103    offset = CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits());
2104    addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2105    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2106    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2107    // offset of x field
2108    offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2109    addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2110  }
2111
2112  // Create the descriptor for the variable.
2113  llvm::DIVariable D =
2114    DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
2115                                   llvm::DIDescriptor(LexicalBlockStack.back()),
2116                                   VD->getName(), Unit, Line, Ty, addr);
2117  // Insert an llvm.dbg.declare into the current block.
2118  llvm::Instruction *Call =
2119    DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2120
2121  llvm::MDNode *Scope = LexicalBlockStack.back();
2122  Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2123}
2124
2125/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2126/// variable declaration.
2127void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2128                                           unsigned ArgNo,
2129                                           CGBuilderTy &Builder) {
2130  EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2131}
2132
2133namespace {
2134  struct BlockLayoutChunk {
2135    uint64_t OffsetInBits;
2136    const BlockDecl::Capture *Capture;
2137  };
2138  bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2139    return l.OffsetInBits < r.OffsetInBits;
2140  }
2141}
2142
2143void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
2144                                                       llvm::Value *addr,
2145                                                       CGBuilderTy &Builder) {
2146  ASTContext &C = CGM.getContext();
2147  const BlockDecl *blockDecl = block.getBlockDecl();
2148
2149  // Collect some general information about the block's location.
2150  SourceLocation loc = blockDecl->getCaretLocation();
2151  llvm::DIFile tunit = getOrCreateFile(loc);
2152  unsigned line = getLineNumber(loc);
2153  unsigned column = getColumnNumber(loc);
2154
2155  // Build the debug-info type for the block literal.
2156  getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2157
2158  const llvm::StructLayout *blockLayout =
2159    CGM.getTargetData().getStructLayout(block.StructureType);
2160
2161  SmallVector<llvm::Value*, 16> fields;
2162  fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2163                                   blockLayout->getElementOffsetInBits(0),
2164                                   tunit, tunit));
2165  fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2166                                   blockLayout->getElementOffsetInBits(1),
2167                                   tunit, tunit));
2168  fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2169                                   blockLayout->getElementOffsetInBits(2),
2170                                   tunit, tunit));
2171  fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2172                                   blockLayout->getElementOffsetInBits(3),
2173                                   tunit, tunit));
2174  fields.push_back(createFieldType("__descriptor",
2175                                   C.getPointerType(block.NeedsCopyDispose ?
2176                                        C.getBlockDescriptorExtendedType() :
2177                                        C.getBlockDescriptorType()),
2178                                   0, loc, AS_public,
2179                                   blockLayout->getElementOffsetInBits(4),
2180                                   tunit, tunit));
2181
2182  // We want to sort the captures by offset, not because DWARF
2183  // requires this, but because we're paranoid about debuggers.
2184  SmallVector<BlockLayoutChunk, 8> chunks;
2185
2186  // 'this' capture.
2187  if (blockDecl->capturesCXXThis()) {
2188    BlockLayoutChunk chunk;
2189    chunk.OffsetInBits =
2190      blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2191    chunk.Capture = 0;
2192    chunks.push_back(chunk);
2193  }
2194
2195  // Variable captures.
2196  for (BlockDecl::capture_const_iterator
2197         i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2198       i != e; ++i) {
2199    const BlockDecl::Capture &capture = *i;
2200    const VarDecl *variable = capture.getVariable();
2201    const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2202
2203    // Ignore constant captures.
2204    if (captureInfo.isConstant())
2205      continue;
2206
2207    BlockLayoutChunk chunk;
2208    chunk.OffsetInBits =
2209      blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2210    chunk.Capture = &capture;
2211    chunks.push_back(chunk);
2212  }
2213
2214  // Sort by offset.
2215  llvm::array_pod_sort(chunks.begin(), chunks.end());
2216
2217  for (SmallVectorImpl<BlockLayoutChunk>::iterator
2218         i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2219    uint64_t offsetInBits = i->OffsetInBits;
2220    const BlockDecl::Capture *capture = i->Capture;
2221
2222    // If we have a null capture, this must be the C++ 'this' capture.
2223    if (!capture) {
2224      const CXXMethodDecl *method =
2225        cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2226      QualType type = method->getThisType(C);
2227
2228      fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2229                                       offsetInBits, tunit, tunit));
2230      continue;
2231    }
2232
2233    const VarDecl *variable = capture->getVariable();
2234    StringRef name = variable->getName();
2235
2236    llvm::DIType fieldType;
2237    if (capture->isByRef()) {
2238      std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2239
2240      // FIXME: this creates a second copy of this type!
2241      uint64_t xoffset;
2242      fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2243      fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2244      fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2245                                            ptrInfo.first, ptrInfo.second,
2246                                            offsetInBits, 0, fieldType);
2247    } else {
2248      fieldType = createFieldType(name, variable->getType(), 0,
2249                                  loc, AS_public, offsetInBits, tunit, tunit);
2250    }
2251    fields.push_back(fieldType);
2252  }
2253
2254  llvm::SmallString<36> typeName;
2255  llvm::raw_svector_ostream(typeName)
2256    << "__block_literal_" << CGM.getUniqueBlockCount();
2257
2258  llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2259
2260  llvm::DIType type =
2261    DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2262                              CGM.getContext().toBits(block.BlockSize),
2263                              CGM.getContext().toBits(block.BlockAlign),
2264                              0, fieldsArray);
2265  type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2266
2267  // Get overall information about the block.
2268  unsigned flags = llvm::DIDescriptor::FlagArtificial;
2269  llvm::MDNode *scope = LexicalBlockStack.back();
2270  StringRef name = ".block_descriptor";
2271
2272  // Create the descriptor for the parameter.
2273  llvm::DIVariable debugVar =
2274    DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
2275                                 llvm::DIDescriptor(scope),
2276                                 name, tunit, line, type,
2277                                 CGM.getLangOptions().Optimize, flags,
2278                                 cast<llvm::Argument>(addr)->getArgNo() + 1);
2279
2280  // Insert an llvm.dbg.value into the current block.
2281  llvm::Instruction *declare =
2282    DBuilder.insertDbgValueIntrinsic(addr, 0, debugVar,
2283                                     Builder.GetInsertBlock());
2284  declare->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2285}
2286
2287/// EmitGlobalVariable - Emit information about a global variable.
2288void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2289                                     const VarDecl *D) {
2290
2291  // Create global variable debug descriptor.
2292  llvm::DIFile Unit = getOrCreateFile(D->getLocation());
2293  unsigned LineNo = getLineNumber(D->getLocation());
2294
2295  QualType T = D->getType();
2296  if (T->isIncompleteArrayType()) {
2297
2298    // CodeGen turns int[] into int[1] so we'll do the same here.
2299    llvm::APSInt ConstVal(32);
2300
2301    ConstVal = 1;
2302    QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2303
2304    T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2305                                           ArrayType::Normal, 0);
2306  }
2307  StringRef DeclName = D->getName();
2308  StringRef LinkageName;
2309  if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
2310      && !isa<ObjCMethodDecl>(D->getDeclContext()))
2311    LinkageName = Var->getName();
2312  if (LinkageName == DeclName)
2313    LinkageName = StringRef();
2314  llvm::DIDescriptor DContext =
2315    getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
2316  DBuilder.createStaticVariable(DContext, DeclName, LinkageName,
2317                                Unit, LineNo, getOrCreateType(T, Unit),
2318                                Var->hasInternalLinkage(), Var);
2319}
2320
2321/// EmitGlobalVariable - Emit information about an objective-c interface.
2322void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2323                                     ObjCInterfaceDecl *ID) {
2324  // Create global variable debug descriptor.
2325  llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
2326  unsigned LineNo = getLineNumber(ID->getLocation());
2327
2328  StringRef Name = ID->getName();
2329
2330  QualType T = CGM.getContext().getObjCInterfaceType(ID);
2331  if (T->isIncompleteArrayType()) {
2332
2333    // CodeGen turns int[] into int[1] so we'll do the same here.
2334    llvm::APSInt ConstVal(32);
2335
2336    ConstVal = 1;
2337    QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2338
2339    T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2340                                           ArrayType::Normal, 0);
2341  }
2342
2343  DBuilder.createGlobalVariable(Name, Unit, LineNo,
2344                                getOrCreateType(T, Unit),
2345                                Var->hasInternalLinkage(), Var);
2346}
2347
2348/// EmitGlobalVariable - Emit global variable's debug info.
2349void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
2350                                     llvm::Constant *Init) {
2351  // Create the descriptor for the variable.
2352  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2353  StringRef Name = VD->getName();
2354  llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
2355  if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
2356    if (const EnumDecl *ED = dyn_cast<EnumDecl>(ECD->getDeclContext()))
2357      Ty = CreateEnumType(ED);
2358  }
2359  // Do not use DIGlobalVariable for enums.
2360  if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
2361    return;
2362  DBuilder.createStaticVariable(Unit, Name, Name, Unit,
2363                                getLineNumber(VD->getLocation()),
2364                                Ty, true, Init);
2365}
2366
2367/// getOrCreateNamesSpace - Return namespace descriptor for the given
2368/// namespace decl.
2369llvm::DINameSpace
2370CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
2371  llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
2372    NameSpaceCache.find(NSDecl);
2373  if (I != NameSpaceCache.end())
2374    return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
2375
2376  unsigned LineNo = getLineNumber(NSDecl->getLocation());
2377  llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
2378  llvm::DIDescriptor Context =
2379    getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
2380  llvm::DINameSpace NS =
2381    DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
2382  NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
2383  return NS;
2384}
2385
2386/// UpdateCompletedType - Update type cache because the type is now
2387/// translated.
2388void CGDebugInfo::UpdateCompletedType(const TagDecl *TD) {
2389  QualType Ty = CGM.getContext().getTagDeclType(TD);
2390
2391  // If the type exist in type cache then remove it from the cache.
2392  // There is no need to prepare debug info for the completed type
2393  // right now. It will be generated on demand lazily.
2394  llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2395    TypeCache.find(Ty.getAsOpaquePtr());
2396  if (it != TypeCache.end())
2397    TypeCache.erase(it);
2398}
2399