CGDebugInfo.cpp revision 5f6e2f4010e1ebbc07231eff7c92e474e8912350
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 "CGBlocks.h"
16#include "CGCXXABI.h"
17#include "CGObjCRuntime.h"
18#include "CodeGenFunction.h"
19#include "CodeGenModule.h"
20#include "clang/AST/ASTContext.h"
21#include "clang/AST/DeclFriend.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/RecordLayout.h"
26#include "clang/Basic/FileManager.h"
27#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/Version.h"
29#include "clang/Frontend/CodeGenOptions.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/StringExtras.h"
32#include "llvm/IR/Constants.h"
33#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/DerivedTypes.h"
35#include "llvm/IR/Instructions.h"
36#include "llvm/IR/Intrinsics.h"
37#include "llvm/IR/Module.h"
38#include "llvm/Support/Dwarf.h"
39#include "llvm/Support/FileSystem.h"
40using namespace clang;
41using namespace clang::CodeGen;
42
43CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
44  : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
45    DBuilder(CGM.getModule()),
46    BlockLiteralGenericSet(false) {
47  CreateCompileUnit();
48}
49
50CGDebugInfo::~CGDebugInfo() {
51  assert(LexicalBlockStack.empty() &&
52         "Region stack mismatch, stack not empty!");
53}
54
55void CGDebugInfo::setLocation(SourceLocation Loc) {
56  // If the new location isn't valid return.
57  if (!Loc.isValid()) return;
58
59  CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
60
61  // If we've changed files in the middle of a lexical scope go ahead
62  // and create a new lexical scope with file node if it's different
63  // from the one in the scope.
64  if (LexicalBlockStack.empty()) return;
65
66  SourceManager &SM = CGM.getContext().getSourceManager();
67  PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
68  PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
69
70  if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
71      !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
72    return;
73
74  llvm::MDNode *LB = LexicalBlockStack.back();
75  llvm::DIScope Scope = llvm::DIScope(LB);
76  if (Scope.isLexicalBlockFile()) {
77    llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
78    llvm::DIDescriptor D
79      = DBuilder.createLexicalBlockFile(LBF.getScope(),
80                                        getOrCreateFile(CurLoc));
81    llvm::MDNode *N = D;
82    LexicalBlockStack.pop_back();
83    LexicalBlockStack.push_back(N);
84  } else if (Scope.isLexicalBlock() || Scope.isSubprogram()) {
85    llvm::DIDescriptor D
86      = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
87    llvm::MDNode *N = D;
88    LexicalBlockStack.pop_back();
89    LexicalBlockStack.push_back(N);
90  }
91}
92
93/// getContextDescriptor - Get context info for the decl.
94llvm::DIScope CGDebugInfo::getContextDescriptor(const Decl *Context) {
95  if (!Context)
96    return TheCU;
97
98  llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
99    I = RegionMap.find(Context);
100  if (I != RegionMap.end()) {
101    llvm::Value *V = I->second;
102    return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
103  }
104
105  // Check namespace.
106  if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
107    return getOrCreateNameSpace(NSDecl);
108
109  if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
110    if (!RDecl->isDependentType())
111      return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
112                                        getOrCreateMainFile());
113  return TheCU;
114}
115
116/// getFunctionName - Get function name for the given FunctionDecl. If the
117/// name is constructred on demand (e.g. C++ destructor) then the name
118/// is stored on the side.
119StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
120  assert (FD && "Invalid FunctionDecl!");
121  IdentifierInfo *FII = FD->getIdentifier();
122  FunctionTemplateSpecializationInfo *Info
123    = FD->getTemplateSpecializationInfo();
124  if (!Info && FII)
125    return FII->getName();
126
127  // Otherwise construct human readable name for debug info.
128  SmallString<128> NS;
129  llvm::raw_svector_ostream OS(NS);
130  FD->printName(OS);
131
132  // Add any template specialization args.
133  if (Info) {
134    const TemplateArgumentList *TArgs = Info->TemplateArguments;
135    const TemplateArgument *Args = TArgs->data();
136    unsigned NumArgs = TArgs->size();
137    PrintingPolicy Policy(CGM.getLangOpts());
138    TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
139                                                          Policy);
140  }
141
142  // Copy this name on the side and use its reference.
143  OS.flush();
144  char *StrPtr = DebugInfoNames.Allocate<char>(NS.size());
145  memcpy(StrPtr, NS.data(), NS.size());
146  return StringRef(StrPtr, NS.size());
147}
148
149StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
150  SmallString<256> MethodName;
151  llvm::raw_svector_ostream OS(MethodName);
152  OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
153  const DeclContext *DC = OMD->getDeclContext();
154  if (const ObjCImplementationDecl *OID =
155      dyn_cast<const ObjCImplementationDecl>(DC)) {
156     OS << OID->getName();
157  } else if (const ObjCInterfaceDecl *OID =
158             dyn_cast<const ObjCInterfaceDecl>(DC)) {
159      OS << OID->getName();
160  } else if (const ObjCCategoryImplDecl *OCD =
161             dyn_cast<const ObjCCategoryImplDecl>(DC)){
162      OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
163          OCD->getIdentifier()->getNameStart() << ')';
164  } else if (isa<ObjCProtocolDecl>(DC)) {
165    // We can extract the type of the class from the self pointer.
166    if (ImplicitParamDecl* SelfDecl = OMD->getSelfDecl()) {
167      QualType ClassTy =
168        cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
169      ClassTy.print(OS, PrintingPolicy(LangOptions()));
170    }
171  }
172  OS << ' ' << OMD->getSelector().getAsString() << ']';
173
174  char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
175  memcpy(StrPtr, MethodName.begin(), OS.tell());
176  return StringRef(StrPtr, OS.tell());
177}
178
179/// getSelectorName - Return selector name. This is used for debugging
180/// info.
181StringRef CGDebugInfo::getSelectorName(Selector S) {
182  const std::string &SName = S.getAsString();
183  char *StrPtr = DebugInfoNames.Allocate<char>(SName.size());
184  memcpy(StrPtr, SName.data(), SName.size());
185  return StringRef(StrPtr, SName.size());
186}
187
188/// getClassName - Get class name including template argument list.
189StringRef
190CGDebugInfo::getClassName(const RecordDecl *RD) {
191  const ClassTemplateSpecializationDecl *Spec
192    = dyn_cast<ClassTemplateSpecializationDecl>(RD);
193  if (!Spec)
194    return RD->getName();
195
196  const TemplateArgument *Args;
197  unsigned NumArgs;
198  if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
199    const TemplateSpecializationType *TST =
200      cast<TemplateSpecializationType>(TAW->getType());
201    Args = TST->getArgs();
202    NumArgs = TST->getNumArgs();
203  } else {
204    const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
205    Args = TemplateArgs.data();
206    NumArgs = TemplateArgs.size();
207  }
208  StringRef Name = RD->getIdentifier()->getName();
209  PrintingPolicy Policy(CGM.getLangOpts());
210  SmallString<128> TemplateArgList;
211  {
212    llvm::raw_svector_ostream OS(TemplateArgList);
213    TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
214                                                          Policy);
215  }
216
217  // Copy this name on the side and use its reference.
218  size_t Length = Name.size() + TemplateArgList.size();
219  char *StrPtr = DebugInfoNames.Allocate<char>(Length);
220  memcpy(StrPtr, Name.data(), Name.size());
221  memcpy(StrPtr + Name.size(), TemplateArgList.data(), TemplateArgList.size());
222  return StringRef(StrPtr, Length);
223}
224
225/// getOrCreateFile - Get the file debug info descriptor for the input location.
226llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
227  if (!Loc.isValid())
228    // If Location is not valid then use main input file.
229    return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
230
231  SourceManager &SM = CGM.getContext().getSourceManager();
232  PresumedLoc PLoc = SM.getPresumedLoc(Loc);
233
234  if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
235    // If the location is not valid then use main input file.
236    return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
237
238  // Cache the results.
239  const char *fname = PLoc.getFilename();
240  llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
241    DIFileCache.find(fname);
242
243  if (it != DIFileCache.end()) {
244    // Verify that the information still exists.
245    if (llvm::Value *V = it->second)
246      return llvm::DIFile(cast<llvm::MDNode>(V));
247  }
248
249  llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
250
251  DIFileCache[fname] = F;
252  return F;
253}
254
255/// getOrCreateMainFile - Get the file info for main compile unit.
256llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
257  return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
258}
259
260/// getLineNumber - Get line number for the location. If location is invalid
261/// then use current location.
262unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
263  if (Loc.isInvalid() && CurLoc.isInvalid())
264    return 0;
265  SourceManager &SM = CGM.getContext().getSourceManager();
266  PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
267  return PLoc.isValid()? PLoc.getLine() : 0;
268}
269
270/// getColumnNumber - Get column number for the location.
271unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
272  // We may not want column information at all.
273  if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
274    return 0;
275
276  // If the location is invalid then use the current column.
277  if (Loc.isInvalid() && CurLoc.isInvalid())
278    return 0;
279  SourceManager &SM = CGM.getContext().getSourceManager();
280  PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
281  return PLoc.isValid()? PLoc.getColumn() : 0;
282}
283
284StringRef CGDebugInfo::getCurrentDirname() {
285  if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
286    return CGM.getCodeGenOpts().DebugCompilationDir;
287
288  if (!CWDName.empty())
289    return CWDName;
290  SmallString<256> CWD;
291  llvm::sys::fs::current_path(CWD);
292  char *CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
293  memcpy(CompDirnamePtr, CWD.data(), CWD.size());
294  return CWDName = StringRef(CompDirnamePtr, CWD.size());
295}
296
297/// CreateCompileUnit - Create new compile unit.
298void CGDebugInfo::CreateCompileUnit() {
299
300  // Get absolute path name.
301  SourceManager &SM = CGM.getContext().getSourceManager();
302  std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
303  if (MainFileName.empty())
304    MainFileName = "<unknown>";
305
306  // The main file name provided via the "-main-file-name" option contains just
307  // the file name itself with no path information. This file name may have had
308  // a relative path, so we look into the actual file entry for the main
309  // file to determine the real absolute path for the file.
310  std::string MainFileDir;
311  if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
312    MainFileDir = MainFile->getDir()->getName();
313    if (MainFileDir != ".")
314      MainFileName = MainFileDir + "/" + MainFileName;
315  }
316
317  // Save filename string.
318  char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
319  memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
320  StringRef Filename(FilenamePtr, MainFileName.length());
321
322  // Save split dwarf file string.
323  std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
324  char *SplitDwarfPtr = DebugInfoNames.Allocate<char>(SplitDwarfFile.length());
325  memcpy(SplitDwarfPtr, SplitDwarfFile.c_str(), SplitDwarfFile.length());
326  StringRef SplitDwarfFilename(SplitDwarfPtr, SplitDwarfFile.length());
327
328  unsigned LangTag;
329  const LangOptions &LO = CGM.getLangOpts();
330  if (LO.CPlusPlus) {
331    if (LO.ObjC1)
332      LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
333    else
334      LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
335  } else if (LO.ObjC1) {
336    LangTag = llvm::dwarf::DW_LANG_ObjC;
337  } else if (LO.C99) {
338    LangTag = llvm::dwarf::DW_LANG_C99;
339  } else {
340    LangTag = llvm::dwarf::DW_LANG_C89;
341  }
342
343  std::string Producer = getClangFullVersion();
344
345  // Figure out which version of the ObjC runtime we have.
346  unsigned RuntimeVers = 0;
347  if (LO.ObjC1)
348    RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
349
350  // Create new compile unit.
351  DBuilder.createCompileUnit(LangTag, Filename, getCurrentDirname(),
352                             Producer, LO.Optimize,
353                             CGM.getCodeGenOpts().DwarfDebugFlags,
354                             RuntimeVers, SplitDwarfFilename);
355  // FIXME - Eliminate TheCU.
356  TheCU = llvm::DICompileUnit(DBuilder.getCU());
357}
358
359/// CreateType - Get the Basic type from the cache or create a new
360/// one if necessary.
361llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
362  unsigned Encoding = 0;
363  StringRef BTName;
364  switch (BT->getKind()) {
365#define BUILTIN_TYPE(Id, SingletonId)
366#define PLACEHOLDER_TYPE(Id, SingletonId) \
367  case BuiltinType::Id:
368#include "clang/AST/BuiltinTypes.def"
369  case BuiltinType::Dependent:
370    llvm_unreachable("Unexpected builtin type");
371  case BuiltinType::NullPtr:
372    return DBuilder.
373      createNullPtrType(BT->getName(CGM.getLangOpts()));
374  case BuiltinType::Void:
375    return llvm::DIType();
376  case BuiltinType::ObjCClass:
377    if (ClassTy.Verify())
378      return ClassTy;
379    ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
380                                         "objc_class", TheCU,
381                                         getOrCreateMainFile(), 0);
382    return ClassTy;
383  case BuiltinType::ObjCId: {
384    // typedef struct objc_class *Class;
385    // typedef struct objc_object {
386    //  Class isa;
387    // } *id;
388
389    if (ObjTy.Verify())
390      return ObjTy;
391
392    if (!ClassTy.Verify())
393      ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
394                                           "objc_class", TheCU,
395                                           getOrCreateMainFile(), 0);
396
397    unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
398
399    llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
400
401    ObjTy =
402        DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
403                                  0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
404
405    ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
406        ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
407    return ObjTy;
408  }
409  case BuiltinType::ObjCSel: {
410    if (SelTy.Verify())
411      return SelTy;
412    SelTy =
413      DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
414                                 "objc_selector", TheCU, getOrCreateMainFile(),
415                                 0);
416    return SelTy;
417  }
418
419  case BuiltinType::OCLImage1d:
420    return getOrCreateStructPtrType("opencl_image1d_t",
421                                    OCLImage1dDITy);
422  case BuiltinType::OCLImage1dArray:
423    return getOrCreateStructPtrType("opencl_image1d_array_t",
424                                    OCLImage1dArrayDITy);
425  case BuiltinType::OCLImage1dBuffer:
426    return getOrCreateStructPtrType("opencl_image1d_buffer_t",
427                                    OCLImage1dBufferDITy);
428  case BuiltinType::OCLImage2d:
429    return getOrCreateStructPtrType("opencl_image2d_t",
430                                    OCLImage2dDITy);
431  case BuiltinType::OCLImage2dArray:
432    return getOrCreateStructPtrType("opencl_image2d_array_t",
433                                    OCLImage2dArrayDITy);
434  case BuiltinType::OCLImage3d:
435    return getOrCreateStructPtrType("opencl_image3d_t",
436                                    OCLImage3dDITy);
437  case BuiltinType::OCLSampler:
438    return DBuilder.createBasicType("opencl_sampler_t",
439                                    CGM.getContext().getTypeSize(BT),
440                                    CGM.getContext().getTypeAlign(BT),
441                                    llvm::dwarf::DW_ATE_unsigned);
442  case BuiltinType::OCLEvent:
443    return getOrCreateStructPtrType("opencl_event_t",
444                                    OCLEventDITy);
445
446  case BuiltinType::UChar:
447  case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
448  case BuiltinType::Char_S:
449  case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
450  case BuiltinType::Char16:
451  case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
452  case BuiltinType::UShort:
453  case BuiltinType::UInt:
454  case BuiltinType::UInt128:
455  case BuiltinType::ULong:
456  case BuiltinType::WChar_U:
457  case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
458  case BuiltinType::Short:
459  case BuiltinType::Int:
460  case BuiltinType::Int128:
461  case BuiltinType::Long:
462  case BuiltinType::WChar_S:
463  case BuiltinType::LongLong:  Encoding = llvm::dwarf::DW_ATE_signed; break;
464  case BuiltinType::Bool:      Encoding = llvm::dwarf::DW_ATE_boolean; break;
465  case BuiltinType::Half:
466  case BuiltinType::Float:
467  case BuiltinType::LongDouble:
468  case BuiltinType::Double:    Encoding = llvm::dwarf::DW_ATE_float; break;
469  }
470
471  switch (BT->getKind()) {
472  case BuiltinType::Long:      BTName = "long int"; break;
473  case BuiltinType::LongLong:  BTName = "long long int"; break;
474  case BuiltinType::ULong:     BTName = "long unsigned int"; break;
475  case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
476  default:
477    BTName = BT->getName(CGM.getLangOpts());
478    break;
479  }
480  // Bit size, align and offset of the type.
481  uint64_t Size = CGM.getContext().getTypeSize(BT);
482  uint64_t Align = CGM.getContext().getTypeAlign(BT);
483  llvm::DIType DbgTy =
484    DBuilder.createBasicType(BTName, Size, Align, Encoding);
485  return DbgTy;
486}
487
488llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
489  // Bit size, align and offset of the type.
490  unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
491  if (Ty->isComplexIntegerType())
492    Encoding = llvm::dwarf::DW_ATE_lo_user;
493
494  uint64_t Size = CGM.getContext().getTypeSize(Ty);
495  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
496  llvm::DIType DbgTy =
497    DBuilder.createBasicType("complex", Size, Align, Encoding);
498
499  return DbgTy;
500}
501
502/// CreateCVRType - Get the qualified type from the cache or create
503/// a new one if necessary.
504llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit, bool Declaration) {
505  QualifierCollector Qc;
506  const Type *T = Qc.strip(Ty);
507
508  // Ignore these qualifiers for now.
509  Qc.removeObjCGCAttr();
510  Qc.removeAddressSpace();
511  Qc.removeObjCLifetime();
512
513  // We will create one Derived type for one qualifier and recurse to handle any
514  // additional ones.
515  unsigned Tag;
516  if (Qc.hasConst()) {
517    Tag = llvm::dwarf::DW_TAG_const_type;
518    Qc.removeConst();
519  } else if (Qc.hasVolatile()) {
520    Tag = llvm::dwarf::DW_TAG_volatile_type;
521    Qc.removeVolatile();
522  } else if (Qc.hasRestrict()) {
523    Tag = llvm::dwarf::DW_TAG_restrict_type;
524    Qc.removeRestrict();
525  } else {
526    assert(Qc.empty() && "Unknown type qualifier for debug info");
527    return getOrCreateType(QualType(T, 0), Unit);
528  }
529
530  llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit, Declaration);
531
532  // No need to fill in the Name, Line, Size, Alignment, Offset in case of
533  // CVR derived types.
534  llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
535
536  return DbgTy;
537}
538
539llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
540                                     llvm::DIFile Unit) {
541
542  // The frontend treats 'id' as a typedef to an ObjCObjectType,
543  // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
544  // debug info, we want to emit 'id' in both cases.
545  if (Ty->isObjCQualifiedIdType())
546      return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
547
548  llvm::DIType DbgTy =
549    CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
550                          Ty->getPointeeType(), Unit);
551  return DbgTy;
552}
553
554llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
555                                     llvm::DIFile Unit) {
556  return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
557                               Ty->getPointeeType(), Unit);
558}
559
560// Creates a forward declaration for a RecordDecl in the given context.
561llvm::DIType CGDebugInfo::createRecordFwdDecl(const RecordDecl *RD,
562                                              llvm::DIDescriptor Ctx) {
563  llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
564  unsigned Line = getLineNumber(RD->getLocation());
565  StringRef RDName = getClassName(RD);
566
567  unsigned Tag = 0;
568  if (RD->isStruct() || RD->isInterface())
569    Tag = llvm::dwarf::DW_TAG_structure_type;
570  else if (RD->isUnion())
571    Tag = llvm::dwarf::DW_TAG_union_type;
572  else {
573    assert(RD->isClass());
574    Tag = llvm::dwarf::DW_TAG_class_type;
575  }
576
577  // Create the type.
578  return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line);
579}
580
581// Walk up the context chain and create forward decls for record decls,
582// and normal descriptors for namespaces.
583llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) {
584  if (!Context)
585    return TheCU;
586
587  // See if we already have the parent.
588  llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
589    I = RegionMap.find(Context);
590  if (I != RegionMap.end()) {
591    llvm::Value *V = I->second;
592    return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
593  }
594
595  // Check namespace.
596  if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
597    return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
598
599  if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context)) {
600    if (!RD->isDependentType()) {
601      llvm::DIType Ty =
602        getOrCreateLimitedType(CGM.getContext().getTypeDeclType(RD),
603                               getOrCreateMainFile());
604      return llvm::DIDescriptor(Ty);
605    }
606  }
607  return TheCU;
608}
609
610/// getOrCreateTypeDeclaration - Create Pointee type. If Pointee is a record
611/// then emit record's fwd if debug info size reduction is enabled.
612llvm::DIType CGDebugInfo::getOrCreateTypeDeclaration(QualType PointeeTy,
613                                                     llvm::DIFile Unit) {
614  if (DebugKind > CodeGenOptions::LimitedDebugInfo)
615    return getOrCreateType(PointeeTy, Unit);
616  return getOrCreateType(PointeeTy, Unit, true);
617}
618
619llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
620                                                const Type *Ty,
621                                                QualType PointeeTy,
622                                                llvm::DIFile Unit) {
623  if (Tag == llvm::dwarf::DW_TAG_reference_type ||
624      Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
625    return DBuilder.createReferenceType(
626        Tag, getOrCreateTypeDeclaration(PointeeTy, Unit));
627
628  // Bit size, align and offset of the type.
629  // Size is always the size of a pointer. We can't use getTypeSize here
630  // because that does not return the correct value for references.
631  unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
632  uint64_t Size = CGM.getTarget().getPointerWidth(AS);
633  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
634
635  return DBuilder.createPointerType(getOrCreateTypeDeclaration(PointeeTy, Unit),
636                                    Size, Align);
637}
638
639llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
640                                                   llvm::DIType &Cache) {
641  if (Cache.Verify())
642    return Cache;
643  Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
644                                     TheCU, getOrCreateMainFile(), 0);
645  unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
646  Cache = DBuilder.createPointerType(Cache, Size);
647  return Cache;
648}
649
650llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
651                                     llvm::DIFile Unit) {
652  if (BlockLiteralGenericSet)
653    return BlockLiteralGeneric;
654
655  SmallVector<llvm::Value *, 8> EltTys;
656  llvm::DIType FieldTy;
657  QualType FType;
658  uint64_t FieldSize, FieldOffset;
659  unsigned FieldAlign;
660  llvm::DIArray Elements;
661  llvm::DIType EltTy, DescTy;
662
663  FieldOffset = 0;
664  FType = CGM.getContext().UnsignedLongTy;
665  EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
666  EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
667
668  Elements = DBuilder.getOrCreateArray(EltTys);
669  EltTys.clear();
670
671  unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
672  unsigned LineNo = getLineNumber(CurLoc);
673
674  EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
675                                    Unit, LineNo, FieldOffset, 0,
676                                    Flags, llvm::DIType(), Elements);
677
678  // Bit size, align and offset of the type.
679  uint64_t Size = CGM.getContext().getTypeSize(Ty);
680
681  DescTy = DBuilder.createPointerType(EltTy, Size);
682
683  FieldOffset = 0;
684  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
685  EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
686  FType = CGM.getContext().IntTy;
687  EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
688  EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
689  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
690  EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
691
692  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
693  FieldTy = DescTy;
694  FieldSize = CGM.getContext().getTypeSize(Ty);
695  FieldAlign = CGM.getContext().getTypeAlign(Ty);
696  FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
697                                      LineNo, FieldSize, FieldAlign,
698                                      FieldOffset, 0, FieldTy);
699  EltTys.push_back(FieldTy);
700
701  FieldOffset += FieldSize;
702  Elements = DBuilder.getOrCreateArray(EltTys);
703
704  EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
705                                    Unit, LineNo, FieldOffset, 0,
706                                    Flags, llvm::DIType(), Elements);
707
708  BlockLiteralGenericSet = true;
709  BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
710  return BlockLiteralGeneric;
711}
712
713llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit,
714                                     bool Declaration) {
715  // Typedefs are derived from some other type.  If we have a typedef of a
716  // typedef, make sure to emit the whole chain.
717  llvm::DIType Src =
718      getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit, Declaration);
719  if (!Src.Verify())
720    return llvm::DIType();
721  // We don't set size information, but do specify where the typedef was
722  // declared.
723  unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
724  const TypedefNameDecl *TyDecl = Ty->getDecl();
725
726  llvm::DIDescriptor TypedefContext =
727    getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
728
729  return
730    DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
731}
732
733llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
734                                     llvm::DIFile Unit) {
735  SmallVector<llvm::Value *, 16> EltTys;
736
737  // Add the result type at least.
738  EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
739
740  // Set up remainder of arguments if there is a prototype.
741  // FIXME: IF NOT, HOW IS THIS REPRESENTED?  llvm-gcc doesn't represent '...'!
742  if (isa<FunctionNoProtoType>(Ty))
743    EltTys.push_back(DBuilder.createUnspecifiedParameter());
744  else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
745    for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
746      EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
747  }
748
749  llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
750  return DBuilder.createSubroutineType(Unit, EltTypeArray);
751}
752
753
754llvm::DIType CGDebugInfo::createFieldType(StringRef name,
755                                          QualType type,
756                                          uint64_t sizeInBitsOverride,
757                                          SourceLocation loc,
758                                          AccessSpecifier AS,
759                                          uint64_t offsetInBits,
760                                          llvm::DIFile tunit,
761                                          llvm::DIDescriptor scope) {
762  llvm::DIType debugType = getOrCreateType(type, tunit);
763
764  // Get the location for the field.
765  llvm::DIFile file = getOrCreateFile(loc);
766  unsigned line = getLineNumber(loc);
767
768  uint64_t sizeInBits = 0;
769  unsigned alignInBits = 0;
770  if (!type->isIncompleteArrayType()) {
771    llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
772
773    if (sizeInBitsOverride)
774      sizeInBits = sizeInBitsOverride;
775  }
776
777  unsigned flags = 0;
778  if (AS == clang::AS_private)
779    flags |= llvm::DIDescriptor::FlagPrivate;
780  else if (AS == clang::AS_protected)
781    flags |= llvm::DIDescriptor::FlagProtected;
782
783  return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
784                                   alignInBits, offsetInBits, flags, debugType);
785}
786
787/// CollectRecordLambdaFields - Helper for CollectRecordFields.
788void CGDebugInfo::
789CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
790                          SmallVectorImpl<llvm::Value *> &elements,
791                          llvm::DIType RecordTy) {
792  // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
793  // has the name and the location of the variable so we should iterate over
794  // both concurrently.
795  const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
796  RecordDecl::field_iterator Field = CXXDecl->field_begin();
797  unsigned fieldno = 0;
798  for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
799         E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
800    const LambdaExpr::Capture C = *I;
801    if (C.capturesVariable()) {
802      VarDecl *V = C.getCapturedVar();
803      llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
804      StringRef VName = V->getName();
805      uint64_t SizeInBitsOverride = 0;
806      if (Field->isBitField()) {
807        SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
808        assert(SizeInBitsOverride && "found named 0-width bitfield");
809      }
810      llvm::DIType fieldType
811        = createFieldType(VName, Field->getType(), SizeInBitsOverride,
812                          C.getLocation(), Field->getAccess(),
813                          layout.getFieldOffset(fieldno), VUnit, RecordTy);
814      elements.push_back(fieldType);
815    } else {
816      // TODO: Need to handle 'this' in some way by probably renaming the
817      // this of the lambda class and having a field member of 'this' or
818      // by using AT_object_pointer for the function and having that be
819      // used as 'this' for semantic references.
820      assert(C.capturesThis() && "Field that isn't captured and isn't this?");
821      FieldDecl *f = *Field;
822      llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
823      QualType type = f->getType();
824      llvm::DIType fieldType
825        = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
826                          layout.getFieldOffset(fieldno), VUnit, RecordTy);
827
828      elements.push_back(fieldType);
829    }
830  }
831}
832
833/// CollectRecordStaticField - Helper for CollectRecordFields.
834void CGDebugInfo::
835CollectRecordStaticField(const VarDecl *Var,
836                         SmallVectorImpl<llvm::Value *> &elements,
837                         llvm::DIType RecordTy) {
838  // Create the descriptor for the static variable, with or without
839  // constant initializers.
840  llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
841  llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
842
843  // Do not describe enums as static members.
844  if (VTy.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
845    return;
846
847  unsigned LineNumber = getLineNumber(Var->getLocation());
848  StringRef VName = Var->getName();
849  llvm::Constant *C = NULL;
850  if (Var->getInit()) {
851    const APValue *Value = Var->evaluateValue();
852    if (Value) {
853      if (Value->isInt())
854        C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
855      if (Value->isFloat())
856        C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
857    }
858  }
859
860  unsigned Flags = 0;
861  AccessSpecifier Access = Var->getAccess();
862  if (Access == clang::AS_private)
863    Flags |= llvm::DIDescriptor::FlagPrivate;
864  else if (Access == clang::AS_protected)
865    Flags |= llvm::DIDescriptor::FlagProtected;
866
867  llvm::DIType GV = DBuilder.createStaticMemberType(RecordTy, VName, VUnit,
868                                                    LineNumber, VTy, Flags, C);
869  elements.push_back(GV);
870  StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
871}
872
873/// CollectRecordNormalField - Helper for CollectRecordFields.
874void CGDebugInfo::
875CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
876                         llvm::DIFile tunit,
877                         SmallVectorImpl<llvm::Value *> &elements,
878                         llvm::DIType RecordTy) {
879  StringRef name = field->getName();
880  QualType type = field->getType();
881
882  // Ignore unnamed fields unless they're anonymous structs/unions.
883  if (name.empty() && !type->isRecordType())
884    return;
885
886  uint64_t SizeInBitsOverride = 0;
887  if (field->isBitField()) {
888    SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
889    assert(SizeInBitsOverride && "found named 0-width bitfield");
890  }
891
892  llvm::DIType fieldType
893    = createFieldType(name, type, SizeInBitsOverride,
894                      field->getLocation(), field->getAccess(),
895                      OffsetInBits, tunit, RecordTy);
896
897  elements.push_back(fieldType);
898}
899
900/// CollectRecordFields - A helper function to collect debug info for
901/// record fields. This is used while creating debug info entry for a Record.
902void CGDebugInfo::
903CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
904                    SmallVectorImpl<llvm::Value *> &elements,
905                    llvm::DIType RecordTy) {
906  const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
907
908  if (CXXDecl && CXXDecl->isLambda())
909    CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
910  else {
911    const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
912
913    // Field number for non-static fields.
914    unsigned fieldNo = 0;
915
916    // Bookkeeping for an ms struct, which ignores certain fields.
917    bool IsMsStruct = record->isMsStruct(CGM.getContext());
918    const FieldDecl *LastFD = 0;
919
920    // Static and non-static members should appear in the same order as
921    // the corresponding declarations in the source program.
922    for (RecordDecl::decl_iterator I = record->decls_begin(),
923           E = record->decls_end(); I != E; ++I)
924      if (const VarDecl *V = dyn_cast<VarDecl>(*I))
925        CollectRecordStaticField(V, elements, RecordTy);
926      else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
927        if (IsMsStruct) {
928          // Zero-length bitfields following non-bitfield members are
929          // completely ignored; we don't even count them.
930          if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD))
931            continue;
932          LastFD = field;
933        }
934        CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
935                                 tunit, elements, RecordTy);
936
937        // Bump field number for next field.
938        ++fieldNo;
939      }
940  }
941}
942
943/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
944/// function type is not updated to include implicit "this" pointer. Use this
945/// routine to get a method type which includes "this" pointer.
946llvm::DICompositeType
947CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
948                                   llvm::DIFile Unit) {
949  const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
950  if (Method->isStatic())
951    return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
952  return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
953                                       Func, Unit);
954}
955
956llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
957    QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
958  // Add "this" pointer.
959  llvm::DIArray Args = llvm::DICompositeType(
960      getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
961  assert (Args.getNumElements() && "Invalid number of arguments!");
962
963  SmallVector<llvm::Value *, 16> Elts;
964
965  // First element is always return type. For 'void' functions it is NULL.
966  Elts.push_back(Args.getElement(0));
967
968  // "this" pointer is always first argument.
969  const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
970  if (isa<ClassTemplateSpecializationDecl>(RD)) {
971    // Create pointer type directly in this case.
972    const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
973    QualType PointeeTy = ThisPtrTy->getPointeeType();
974    unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
975    uint64_t Size = CGM.getTarget().getPointerWidth(AS);
976    uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
977    llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
978    llvm::DIType ThisPtrType =
979      DBuilder.createPointerType(PointeeType, Size, Align);
980    TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
981    // TODO: This and the artificial type below are misleading, the
982    // types aren't artificial the argument is, but the current
983    // metadata doesn't represent that.
984    ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
985    Elts.push_back(ThisPtrType);
986  } else {
987    llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
988    TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
989    ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
990    Elts.push_back(ThisPtrType);
991  }
992
993  // Copy rest of the arguments.
994  for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
995    Elts.push_back(Args.getElement(i));
996
997  llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
998
999  return DBuilder.createSubroutineType(Unit, EltTypeArray);
1000}
1001
1002/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
1003/// inside a function.
1004static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1005  if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1006    return isFunctionLocalClass(NRD);
1007  if (isa<FunctionDecl>(RD->getDeclContext()))
1008    return true;
1009  return false;
1010}
1011
1012/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1013/// a single member function GlobalDecl.
1014llvm::DISubprogram
1015CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1016                                     llvm::DIFile Unit,
1017                                     llvm::DIType RecordTy) {
1018  bool IsCtorOrDtor =
1019    isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
1020
1021  StringRef MethodName = getFunctionName(Method);
1022  llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
1023
1024  // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1025  // make sense to give a single ctor/dtor a linkage name.
1026  StringRef MethodLinkageName;
1027  if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1028    MethodLinkageName = CGM.getMangledName(Method);
1029
1030  // Get the location for the method.
1031  llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
1032  unsigned MethodLine = getLineNumber(Method->getLocation());
1033
1034  // Collect virtual method info.
1035  llvm::DIType ContainingType;
1036  unsigned Virtuality = 0;
1037  unsigned VIndex = 0;
1038
1039  if (Method->isVirtual()) {
1040    if (Method->isPure())
1041      Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1042    else
1043      Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
1044
1045    // It doesn't make sense to give a virtual destructor a vtable index,
1046    // since a single destructor has two entries in the vtable.
1047    if (!isa<CXXDestructorDecl>(Method))
1048      VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
1049    ContainingType = RecordTy;
1050  }
1051
1052  unsigned Flags = 0;
1053  if (Method->isImplicit())
1054    Flags |= llvm::DIDescriptor::FlagArtificial;
1055  AccessSpecifier Access = Method->getAccess();
1056  if (Access == clang::AS_private)
1057    Flags |= llvm::DIDescriptor::FlagPrivate;
1058  else if (Access == clang::AS_protected)
1059    Flags |= llvm::DIDescriptor::FlagProtected;
1060  if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1061    if (CXXC->isExplicit())
1062      Flags |= llvm::DIDescriptor::FlagExplicit;
1063  } else if (const CXXConversionDecl *CXXC =
1064             dyn_cast<CXXConversionDecl>(Method)) {
1065    if (CXXC->isExplicit())
1066      Flags |= llvm::DIDescriptor::FlagExplicit;
1067  }
1068  if (Method->hasPrototype())
1069    Flags |= llvm::DIDescriptor::FlagPrototyped;
1070
1071  llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1072  llvm::DISubprogram SP =
1073    DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
1074                          MethodDefUnit, MethodLine,
1075                          MethodTy, /*isLocalToUnit=*/false,
1076                          /* isDefinition=*/ false,
1077                          Virtuality, VIndex, ContainingType,
1078                          Flags, CGM.getLangOpts().Optimize, NULL,
1079                          TParamsArray);
1080
1081  SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1082
1083  return SP;
1084}
1085
1086/// CollectCXXMemberFunctions - A helper function to collect debug info for
1087/// C++ member functions. This is used while creating debug info entry for
1088/// a Record.
1089void CGDebugInfo::
1090CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1091                          SmallVectorImpl<llvm::Value *> &EltTys,
1092                          llvm::DIType RecordTy) {
1093
1094  // Since we want more than just the individual member decls if we
1095  // have templated functions iterate over every declaration to gather
1096  // the functions.
1097  for(DeclContext::decl_iterator I = RD->decls_begin(),
1098        E = RD->decls_end(); I != E; ++I) {
1099    Decl *D = *I;
1100    if (D->isImplicit() && !D->isUsed())
1101      continue;
1102
1103    if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1104      EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1105    else if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
1106      for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1107             SE = FTD->spec_end(); SI != SE; ++SI)
1108        EltTys.push_back(CreateCXXMemberFunction(cast<CXXMethodDecl>(*SI), Unit,
1109                                                 RecordTy));
1110  }
1111}
1112
1113/// CollectCXXFriends - A helper function to collect debug info for
1114/// C++ base classes. This is used while creating debug info entry for
1115/// a Record.
1116void CGDebugInfo::
1117CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1118                SmallVectorImpl<llvm::Value *> &EltTys,
1119                llvm::DIType RecordTy) {
1120  for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1121         BE = RD->friend_end(); BI != BE; ++BI) {
1122    if ((*BI)->isUnsupportedFriend())
1123      continue;
1124    if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
1125      EltTys.push_back(DBuilder.createFriend(RecordTy,
1126                                             getOrCreateType(TInfo->getType(),
1127                                                             Unit)));
1128  }
1129}
1130
1131/// CollectCXXBases - A helper function to collect debug info for
1132/// C++ base classes. This is used while creating debug info entry for
1133/// a Record.
1134void CGDebugInfo::
1135CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1136                SmallVectorImpl<llvm::Value *> &EltTys,
1137                llvm::DIType RecordTy) {
1138
1139  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1140  for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1141         BE = RD->bases_end(); BI != BE; ++BI) {
1142    unsigned BFlags = 0;
1143    uint64_t BaseOffset;
1144
1145    const CXXRecordDecl *Base =
1146      cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
1147
1148    if (BI->isVirtual()) {
1149      // virtual base offset offset is -ve. The code generator emits dwarf
1150      // expression where it expects +ve number.
1151      BaseOffset =
1152        0 - CGM.getVTableContext()
1153               .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1154      BFlags = llvm::DIDescriptor::FlagVirtual;
1155    } else
1156      BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1157    // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1158    // BI->isVirtual() and bits when not.
1159
1160    AccessSpecifier Access = BI->getAccessSpecifier();
1161    if (Access == clang::AS_private)
1162      BFlags |= llvm::DIDescriptor::FlagPrivate;
1163    else if (Access == clang::AS_protected)
1164      BFlags |= llvm::DIDescriptor::FlagProtected;
1165
1166    llvm::DIType DTy =
1167      DBuilder.createInheritance(RecordTy,
1168                                 getOrCreateType(BI->getType(), Unit),
1169                                 BaseOffset, BFlags);
1170    EltTys.push_back(DTy);
1171  }
1172}
1173
1174/// CollectTemplateParams - A helper function to collect template parameters.
1175llvm::DIArray CGDebugInfo::
1176CollectTemplateParams(const TemplateParameterList *TPList,
1177                      const TemplateArgumentList &TAList,
1178                      llvm::DIFile Unit) {
1179  SmallVector<llvm::Value *, 16> TemplateParams;
1180  for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1181    const TemplateArgument &TA = TAList[i];
1182    const NamedDecl *ND = TPList->getParam(i);
1183    switch (TA.getKind()) {
1184    case TemplateArgument::Type: {
1185      llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1186      llvm::DITemplateTypeParameter TTP =
1187        DBuilder.createTemplateTypeParameter(TheCU, ND->getName(), TTy);
1188      TemplateParams.push_back(TTP);
1189    } break;
1190    case TemplateArgument::Integral: {
1191      llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1192      llvm::DITemplateValueParameter TVP =
1193          DBuilder.createTemplateValueParameter(
1194              TheCU, ND->getName(), TTy,
1195              llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1196      TemplateParams.push_back(TVP);
1197    } break;
1198    case TemplateArgument::Declaration: {
1199      const ValueDecl *D = TA.getAsDecl();
1200      bool InstanceMember = D->isCXXInstanceMember();
1201      QualType T = InstanceMember
1202                       ? CGM.getContext().getMemberPointerType(
1203                             D->getType(), cast<RecordDecl>(D->getDeclContext())
1204                                               ->getTypeForDecl())
1205                       : CGM.getContext().getPointerType(D->getType());
1206      llvm::DIType TTy = getOrCreateType(T, Unit);
1207      llvm::Value *V = 0;
1208      // Variable pointer template parameters have a value that is the address
1209      // of the variable.
1210      if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1211        V = CGM.GetAddrOfGlobalVar(VD);
1212      // Member function pointers have special support for building them, though
1213      // this is currently unsupported in LLVM CodeGen.
1214      if (InstanceMember) {
1215        if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1216          V = CGM.getCXXABI().EmitMemberPointer(method);
1217      } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1218        V = CGM.GetAddrOfFunction(FD);
1219      // Member data pointers have special handling too to compute the fixed
1220      // offset within the object.
1221      if (isa<FieldDecl>(D)) {
1222        // These five lines (& possibly the above member function pointer
1223        // handling) might be able to be refactored to use similar code in
1224        // CodeGenModule::getMemberPointerConstant
1225        uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1226        CharUnits chars =
1227            CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1228        V = CGM.getCXXABI().EmitMemberDataPointer(
1229            cast<MemberPointerType>(T.getTypePtr()), chars);
1230      }
1231      llvm::DITemplateValueParameter TVP =
1232          DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy, V);
1233      TemplateParams.push_back(TVP);
1234    } break;
1235    case TemplateArgument::NullPtr: {
1236      QualType T = TA.getNullPtrType();
1237      llvm::DIType TTy = getOrCreateType(T, Unit);
1238      llvm::Value *V = 0;
1239      // Special case member data pointer null values since they're actually -1
1240      // instead of zero.
1241      if (const MemberPointerType *MPT =
1242              dyn_cast<MemberPointerType>(T.getTypePtr()))
1243        // But treat member function pointers as simple zero integers because
1244        // it's easier than having a special case in LLVM's CodeGen. If LLVM
1245        // CodeGen grows handling for values of non-null member function
1246        // pointers then perhaps we could remove this special case and rely on
1247        // EmitNullMemberPointer for member function pointers.
1248        if (MPT->isMemberDataPointer())
1249          V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1250      if (!V)
1251        V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1252      llvm::DITemplateValueParameter TVP =
1253          DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy, V);
1254      TemplateParams.push_back(TVP);
1255    } break;
1256    case TemplateArgument::Template:
1257      // We could support this with the GCC extension
1258      // DW_TAG_GNU_template_template_param
1259      break;
1260    case TemplateArgument::Pack:
1261      // And this with DW_TAG_GNU_template_parameter_pack
1262      break;
1263    // And the following should never occur:
1264    case TemplateArgument::Expression:
1265    case TemplateArgument::TemplateExpansion:
1266    case TemplateArgument::Null:
1267      llvm_unreachable(
1268          "These argument types shouldn't exist in concrete types");
1269    }
1270  }
1271  return DBuilder.getOrCreateArray(TemplateParams);
1272}
1273
1274/// CollectFunctionTemplateParams - A helper function to collect debug
1275/// info for function template parameters.
1276llvm::DIArray CGDebugInfo::
1277CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1278  if (FD->getTemplatedKind() ==
1279      FunctionDecl::TK_FunctionTemplateSpecialization) {
1280    const TemplateParameterList *TList =
1281      FD->getTemplateSpecializationInfo()->getTemplate()
1282      ->getTemplateParameters();
1283    return
1284      CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit);
1285  }
1286  return llvm::DIArray();
1287}
1288
1289/// CollectCXXTemplateParams - A helper function to collect debug info for
1290/// template parameters.
1291llvm::DIArray CGDebugInfo::
1292CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1293                         llvm::DIFile Unit) {
1294  llvm::PointerUnion<ClassTemplateDecl *,
1295                     ClassTemplatePartialSpecializationDecl *>
1296    PU = TSpecial->getSpecializedTemplateOrPartial();
1297
1298  TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1299    PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1300    PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1301  const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
1302  return CollectTemplateParams(TPList, TAList, Unit);
1303}
1304
1305/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1306llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1307  if (VTablePtrType.isValid())
1308    return VTablePtrType;
1309
1310  ASTContext &Context = CGM.getContext();
1311
1312  /* Function type */
1313  llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1314  llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1315  llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1316  unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1317  llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1318                                                          "__vtbl_ptr_type");
1319  VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1320  return VTablePtrType;
1321}
1322
1323/// getVTableName - Get vtable name for the given Class.
1324StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1325  // Construct gdb compatible name name.
1326  std::string Name = "_vptr$" + RD->getNameAsString();
1327
1328  // Copy this name on the side and use its reference.
1329  char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1330  memcpy(StrPtr, Name.data(), Name.length());
1331  return StringRef(StrPtr, Name.length());
1332}
1333
1334
1335/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1336/// debug info entry in EltTys vector.
1337void CGDebugInfo::
1338CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1339                  SmallVectorImpl<llvm::Value *> &EltTys) {
1340  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1341
1342  // If there is a primary base then it will hold vtable info.
1343  if (RL.getPrimaryBase())
1344    return;
1345
1346  // If this class is not dynamic then there is not any vtable info to collect.
1347  if (!RD->isDynamicClass())
1348    return;
1349
1350  unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1351  llvm::DIType VPTR
1352    = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
1353                                0, Size, 0, 0,
1354                                llvm::DIDescriptor::FlagArtificial,
1355                                getOrCreateVTablePtrType(Unit));
1356  EltTys.push_back(VPTR);
1357}
1358
1359/// getOrCreateRecordType - Emit record type's standalone debug info.
1360llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
1361                                                SourceLocation Loc) {
1362  assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
1363  llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1364  return T;
1365}
1366
1367/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1368/// debug info.
1369llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
1370                                                   SourceLocation Loc) {
1371  assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
1372  llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
1373  RetainedTypes.push_back(D.getAsOpaquePtr());
1374  return T;
1375}
1376
1377/// CreateType - get structure or union type.
1378llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty, bool Declaration) {
1379  RecordDecl *RD = Ty->getDecl();
1380  if (Declaration) {
1381    llvm::DIDescriptor FDContext =
1382      getContextDescriptor(cast<Decl>(RD->getDeclContext()));
1383    llvm::DIType RetTy = createRecordFwdDecl(RD, FDContext);
1384    TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RetTy;
1385    return RetTy;
1386  }
1387
1388  // Get overall information about the record type for the debug info.
1389  llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1390
1391  // Records and classes and unions can all be recursive.  To handle them, we
1392  // first generate a debug descriptor for the struct as a forward declaration.
1393  // Then (if it is a definition) we go through and get debug info for all of
1394  // its members.  Finally, we create a descriptor for the complete type (which
1395  // may refer to the forward decl if the struct is recursive) and replace all
1396  // uses of the forward declaration with the final definition.
1397
1398  llvm::DICompositeType FwdDecl(
1399      getOrCreateLimitedType(QualType(Ty, 0), DefUnit));
1400  assert(FwdDecl.Verify() &&
1401         "The debug type of a RecordType should be a llvm::DICompositeType");
1402
1403  if (FwdDecl.isForwardDecl())
1404    return FwdDecl;
1405
1406  // Push the struct on region stack.
1407  LexicalBlockStack.push_back(&*FwdDecl);
1408  RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1409
1410  // Add this to the completed-type cache while we're completing it recursively.
1411  CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1412
1413  // Convert all the elements.
1414  SmallVector<llvm::Value *, 16> EltTys;
1415
1416  // Note: The split of CXXDecl information here is intentional, the
1417  // gdb tests will depend on a certain ordering at printout. The debug
1418  // information offsets are still correct if we merge them all together
1419  // though.
1420  const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1421  if (CXXDecl) {
1422    CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1423    CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1424  }
1425
1426  // Collect data fields (including static variables and any initializers).
1427  CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1428  llvm::DIArray TParamsArray;
1429  if (CXXDecl) {
1430    CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1431    CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
1432    if (const ClassTemplateSpecializationDecl *TSpecial
1433        = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1434      TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit);
1435  }
1436
1437  LexicalBlockStack.pop_back();
1438  RegionMap.erase(Ty->getDecl());
1439
1440  llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1441  FwdDecl.setTypeArray(Elements, TParamsArray);
1442
1443  RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1444  return FwdDecl;
1445}
1446
1447/// CreateType - get objective-c object type.
1448llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1449                                     llvm::DIFile Unit) {
1450  // Ignore protocols.
1451  return getOrCreateType(Ty->getBaseType(), Unit);
1452}
1453
1454/// CreateType - get objective-c interface type.
1455llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1456                                     llvm::DIFile Unit) {
1457  ObjCInterfaceDecl *ID = Ty->getDecl();
1458  if (!ID)
1459    return llvm::DIType();
1460
1461  // Get overall information about the record type for the debug info.
1462  llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1463  unsigned Line = getLineNumber(ID->getLocation());
1464  unsigned RuntimeLang = TheCU.getLanguage();
1465
1466  // If this is just a forward declaration return a special forward-declaration
1467  // debug type since we won't be able to lay out the entire type.
1468  ObjCInterfaceDecl *Def = ID->getDefinition();
1469  if (!Def) {
1470    llvm::DIType FwdDecl =
1471      DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
1472                                 ID->getName(), TheCU, DefUnit, Line,
1473                                 RuntimeLang);
1474    return FwdDecl;
1475  }
1476
1477  ID = Def;
1478
1479  // Bit size, align and offset of the type.
1480  uint64_t Size = CGM.getContext().getTypeSize(Ty);
1481  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1482
1483  unsigned Flags = 0;
1484  if (ID->getImplementation())
1485    Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1486
1487  llvm::DICompositeType RealDecl =
1488    DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1489                              Line, Size, Align, Flags,
1490                              llvm::DIType(), llvm::DIArray(), RuntimeLang);
1491
1492  // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1493  // will find it and we're emitting the complete type.
1494  QualType QualTy = QualType(Ty, 0);
1495  CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
1496  // Push the struct on region stack.
1497
1498  LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
1499  RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1500
1501  // Convert all the elements.
1502  SmallVector<llvm::Value *, 16> EltTys;
1503
1504  ObjCInterfaceDecl *SClass = ID->getSuperClass();
1505  if (SClass) {
1506    llvm::DIType SClassTy =
1507      getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1508    if (!SClassTy.isValid())
1509      return llvm::DIType();
1510
1511    llvm::DIType InhTag =
1512      DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1513    EltTys.push_back(InhTag);
1514  }
1515
1516  for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1517         E = ID->prop_end(); I != E; ++I) {
1518    const ObjCPropertyDecl *PD = *I;
1519    SourceLocation Loc = PD->getLocation();
1520    llvm::DIFile PUnit = getOrCreateFile(Loc);
1521    unsigned PLine = getLineNumber(Loc);
1522    ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1523    ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1524    llvm::MDNode *PropertyNode =
1525      DBuilder.createObjCProperty(PD->getName(),
1526                                  PUnit, PLine,
1527                                  (Getter && Getter->isImplicit()) ? "" :
1528                                  getSelectorName(PD->getGetterName()),
1529                                  (Setter && Setter->isImplicit()) ? "" :
1530                                  getSelectorName(PD->getSetterName()),
1531                                  PD->getPropertyAttributes(),
1532                                  getOrCreateType(PD->getType(), PUnit));
1533    EltTys.push_back(PropertyNode);
1534  }
1535
1536  const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1537  unsigned FieldNo = 0;
1538  for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1539       Field = Field->getNextIvar(), ++FieldNo) {
1540    llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1541    if (!FieldTy.isValid())
1542      return llvm::DIType();
1543
1544    StringRef FieldName = Field->getName();
1545
1546    // Ignore unnamed fields.
1547    if (FieldName.empty())
1548      continue;
1549
1550    // Get the location for the field.
1551    llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1552    unsigned FieldLine = getLineNumber(Field->getLocation());
1553    QualType FType = Field->getType();
1554    uint64_t FieldSize = 0;
1555    unsigned FieldAlign = 0;
1556
1557    if (!FType->isIncompleteArrayType()) {
1558
1559      // Bit size, align and offset of the type.
1560      FieldSize = Field->isBitField()
1561        ? Field->getBitWidthValue(CGM.getContext())
1562        : CGM.getContext().getTypeSize(FType);
1563      FieldAlign = CGM.getContext().getTypeAlign(FType);
1564    }
1565
1566    uint64_t FieldOffset;
1567    if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1568      // We don't know the runtime offset of an ivar if we're using the
1569      // non-fragile ABI.  For bitfields, use the bit offset into the first
1570      // byte of storage of the bitfield.  For other fields, use zero.
1571      if (Field->isBitField()) {
1572        FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1573            CGM, ID, Field);
1574        FieldOffset %= CGM.getContext().getCharWidth();
1575      } else {
1576        FieldOffset = 0;
1577      }
1578    } else {
1579      FieldOffset = RL.getFieldOffset(FieldNo);
1580    }
1581
1582    unsigned Flags = 0;
1583    if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1584      Flags = llvm::DIDescriptor::FlagProtected;
1585    else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1586      Flags = llvm::DIDescriptor::FlagPrivate;
1587
1588    llvm::MDNode *PropertyNode = NULL;
1589    if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
1590      if (ObjCPropertyImplDecl *PImpD =
1591          ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1592        if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
1593          SourceLocation Loc = PD->getLocation();
1594          llvm::DIFile PUnit = getOrCreateFile(Loc);
1595          unsigned PLine = getLineNumber(Loc);
1596          ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1597          ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1598          PropertyNode =
1599            DBuilder.createObjCProperty(PD->getName(),
1600                                        PUnit, PLine,
1601                                        (Getter && Getter->isImplicit()) ? "" :
1602                                        getSelectorName(PD->getGetterName()),
1603                                        (Setter && Setter->isImplicit()) ? "" :
1604                                        getSelectorName(PD->getSetterName()),
1605                                        PD->getPropertyAttributes(),
1606                                        getOrCreateType(PD->getType(), PUnit));
1607        }
1608      }
1609    }
1610    FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1611                                      FieldLine, FieldSize, FieldAlign,
1612                                      FieldOffset, Flags, FieldTy,
1613                                      PropertyNode);
1614    EltTys.push_back(FieldTy);
1615  }
1616
1617  llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1618  RealDecl.setTypeArray(Elements);
1619
1620  // If the implementation is not yet set, we do not want to mark it
1621  // as complete. An implementation may declare additional
1622  // private ivars that we would miss otherwise.
1623  if (ID->getImplementation() == 0)
1624    CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
1625
1626  LexicalBlockStack.pop_back();
1627  return RealDecl;
1628}
1629
1630llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1631  llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1632  int64_t Count = Ty->getNumElements();
1633  if (Count == 0)
1634    // If number of elements are not known then this is an unbounded array.
1635    // Use Count == -1 to express such arrays.
1636    Count = -1;
1637
1638  llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1639  llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1640
1641  uint64_t Size = CGM.getContext().getTypeSize(Ty);
1642  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1643
1644  return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1645}
1646
1647llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1648                                     llvm::DIFile Unit) {
1649  uint64_t Size;
1650  uint64_t Align;
1651
1652  // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1653  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1654    Size = 0;
1655    Align =
1656      CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1657  } else if (Ty->isIncompleteArrayType()) {
1658    Size = 0;
1659    if (Ty->getElementType()->isIncompleteType())
1660      Align = 0;
1661    else
1662      Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1663  } else if (Ty->isIncompleteType()) {
1664    Size = 0;
1665    Align = 0;
1666  } else {
1667    // Size and align of the whole array, not the element type.
1668    Size = CGM.getContext().getTypeSize(Ty);
1669    Align = CGM.getContext().getTypeAlign(Ty);
1670  }
1671
1672  // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
1673  // interior arrays, do we care?  Why aren't nested arrays represented the
1674  // obvious/recursive way?
1675  SmallVector<llvm::Value *, 8> Subscripts;
1676  QualType EltTy(Ty, 0);
1677  while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1678    // If the number of elements is known, then count is that number. Otherwise,
1679    // it's -1. This allows us to represent a subrange with an array of 0
1680    // elements, like this:
1681    //
1682    //   struct foo {
1683    //     int x[0];
1684    //   };
1685    int64_t Count = -1;         // Count == -1 is an unbounded array.
1686    if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1687      Count = CAT->getSize().getZExtValue();
1688
1689    // FIXME: Verify this is right for VLAs.
1690    Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1691    EltTy = Ty->getElementType();
1692  }
1693
1694  llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1695
1696  llvm::DIType DbgTy =
1697    DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1698                             SubscriptArray);
1699  return DbgTy;
1700}
1701
1702llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1703                                     llvm::DIFile Unit) {
1704  return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1705                               Ty, Ty->getPointeeType(), Unit);
1706}
1707
1708llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1709                                     llvm::DIFile Unit) {
1710  return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
1711                               Ty, Ty->getPointeeType(), Unit);
1712}
1713
1714llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1715                                     llvm::DIFile U) {
1716  llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1717  if (!Ty->getPointeeType()->isFunctionType())
1718    return DBuilder.createMemberPointerType(
1719        getOrCreateTypeDeclaration(Ty->getPointeeType(), U), ClassType);
1720  return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1721      CGM.getContext().getPointerType(
1722          QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1723      Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1724                                          ClassType);
1725}
1726
1727llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
1728                                     llvm::DIFile U) {
1729  // Ignore the atomic wrapping
1730  // FIXME: What is the correct representation?
1731  return getOrCreateType(Ty->getValueType(), U);
1732}
1733
1734/// CreateEnumType - get enumeration type.
1735llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1736  uint64_t Size = 0;
1737  uint64_t Align = 0;
1738  if (!ED->getTypeForDecl()->isIncompleteType()) {
1739    Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1740    Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1741  }
1742
1743  // If this is just a forward declaration, construct an appropriately
1744  // marked node and just return it.
1745  if (!ED->getDefinition()) {
1746    llvm::DIDescriptor EDContext;
1747    EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1748    llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1749    unsigned Line = getLineNumber(ED->getLocation());
1750    StringRef EDName = ED->getName();
1751    return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1752                                      EDName, EDContext, DefUnit, Line, 0,
1753                                      Size, Align);
1754  }
1755
1756  // Create DIEnumerator elements for each enumerator.
1757  SmallVector<llvm::Value *, 16> Enumerators;
1758  ED = ED->getDefinition();
1759  for (EnumDecl::enumerator_iterator
1760         Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1761       Enum != EnumEnd; ++Enum) {
1762    Enumerators.push_back(
1763      DBuilder.createEnumerator(Enum->getName(),
1764                                Enum->getInitVal().getZExtValue()));
1765  }
1766
1767  // Return a CompositeType for the enum itself.
1768  llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1769
1770  llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1771  unsigned Line = getLineNumber(ED->getLocation());
1772  llvm::DIDescriptor EnumContext =
1773    getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1774  llvm::DIType ClassTy = ED->isFixed() ?
1775    getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
1776  llvm::DIType DbgTy =
1777    DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1778                                   Size, Align, EltArray,
1779                                   ClassTy);
1780  return DbgTy;
1781}
1782
1783static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1784  Qualifiers Quals;
1785  do {
1786    Quals += T.getLocalQualifiers();
1787    QualType LastT = T;
1788    switch (T->getTypeClass()) {
1789    default:
1790      return C.getQualifiedType(T.getTypePtr(), Quals);
1791    case Type::TemplateSpecialization:
1792      T = cast<TemplateSpecializationType>(T)->desugar();
1793      break;
1794    case Type::TypeOfExpr:
1795      T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1796      break;
1797    case Type::TypeOf:
1798      T = cast<TypeOfType>(T)->getUnderlyingType();
1799      break;
1800    case Type::Decltype:
1801      T = cast<DecltypeType>(T)->getUnderlyingType();
1802      break;
1803    case Type::UnaryTransform:
1804      T = cast<UnaryTransformType>(T)->getUnderlyingType();
1805      break;
1806    case Type::Attributed:
1807      T = cast<AttributedType>(T)->getEquivalentType();
1808      break;
1809    case Type::Elaborated:
1810      T = cast<ElaboratedType>(T)->getNamedType();
1811      break;
1812    case Type::Paren:
1813      T = cast<ParenType>(T)->getInnerType();
1814      break;
1815    case Type::SubstTemplateTypeParm:
1816      T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
1817      break;
1818    case Type::Auto:
1819      QualType DT = cast<AutoType>(T)->getDeducedType();
1820      if (DT.isNull())
1821        return T;
1822      T = DT;
1823      break;
1824    }
1825
1826    assert(T != LastT && "Type unwrapping failed to unwrap!");
1827    (void)LastT;
1828  } while (true);
1829}
1830
1831/// getType - Get the type from the cache or return null type if it doesn't
1832/// exist.
1833llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1834
1835  // Unwrap the type as needed for debug information.
1836  Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
1837
1838  // Check for existing entry.
1839  if (Ty->getTypeClass() == Type::ObjCInterface) {
1840    llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1841    if (V)
1842      return llvm::DIType(cast<llvm::MDNode>(V));
1843    else return llvm::DIType();
1844  }
1845
1846  llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1847    TypeCache.find(Ty.getAsOpaquePtr());
1848  if (it != TypeCache.end()) {
1849    // Verify that the debug info still exists.
1850    if (llvm::Value *V = it->second)
1851      return llvm::DIType(cast<llvm::MDNode>(V));
1852  }
1853
1854  return llvm::DIType();
1855}
1856
1857/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1858/// doesn't exist.
1859llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1860
1861  // Unwrap the type as needed for debug information.
1862  Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
1863
1864  // Check for existing entry.
1865  llvm::Value *V = 0;
1866  llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1867    CompletedTypeCache.find(Ty.getAsOpaquePtr());
1868  if (it != CompletedTypeCache.end())
1869    V = it->second;
1870  else {
1871    V = getCachedInterfaceTypeOrNull(Ty);
1872  }
1873
1874  // Verify that any cached debug info still exists.
1875  if (V != 0)
1876    return llvm::DIType(cast<llvm::MDNode>(V));
1877
1878  return llvm::DIType();
1879}
1880
1881/// getCachedInterfaceTypeOrNull - Get the type from the interface
1882/// cache, unless it needs to regenerated. Otherwise return null.
1883llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
1884  // Is there a cached interface that hasn't changed?
1885  llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1886    ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
1887
1888  if (it1 != ObjCInterfaceCache.end())
1889    if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
1890      if (Checksum(Decl) == it1->second.second)
1891        // Return cached forward declaration.
1892        return it1->second.first;
1893
1894  return 0;
1895}
1896
1897/// getOrCreateType - Get the type from the cache or create a new
1898/// one if necessary.
1899llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit, bool Declaration) {
1900  if (Ty.isNull())
1901    return llvm::DIType();
1902
1903  // Unwrap the type as needed for debug information.
1904  Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
1905
1906  llvm::DIType T = getCompletedTypeOrNull(Ty);
1907
1908  if (T.Verify())
1909    return T;
1910
1911  // Otherwise create the type.
1912  llvm::DIType Res = CreateTypeNode(Ty, Unit, Declaration);
1913  void* TyPtr = Ty.getAsOpaquePtr();
1914
1915  // And update the type cache.
1916  TypeCache[TyPtr] = Res;
1917
1918  llvm::DIType TC = getTypeOrNull(Ty);
1919  if (TC.Verify() && TC.isForwardDecl())
1920    ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1921  else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
1922    // Interface types may have elements added to them by a
1923    // subsequent implementation or extension, so we keep them in
1924    // the ObjCInterfaceCache together with a checksum. Instead of
1925    // the (possibly) incomplete interface type, we return a forward
1926    // declaration that gets RAUW'd in CGDebugInfo::finalize().
1927    std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
1928    if (V.first)
1929      return llvm::DIType(cast<llvm::MDNode>(V.first));
1930    TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
1931                                    Decl->getName(), TheCU, Unit,
1932                                    getLineNumber(Decl->getLocation()),
1933                                    TheCU.getLanguage());
1934    // Store the forward declaration in the cache.
1935    V.first = TC;
1936    V.second = Checksum(Decl);
1937
1938    // Register the type for replacement in finalize().
1939    ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1940
1941    return TC;
1942  }
1943
1944  if (!Res.isForwardDecl())
1945    CompletedTypeCache[TyPtr] = Res;
1946
1947  return Res;
1948}
1949
1950/// Currently the checksum merely consists of the number of ivars.
1951unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl
1952                               *InterfaceDecl) {
1953  unsigned IvarNo = 0;
1954  for (const ObjCIvarDecl *Ivar = InterfaceDecl->all_declared_ivar_begin();
1955       Ivar != 0; Ivar = Ivar->getNextIvar()) ++IvarNo;
1956  return IvarNo;
1957}
1958
1959ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
1960  switch (Ty->getTypeClass()) {
1961  case Type::ObjCObjectPointer:
1962    return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
1963                                    ->getPointeeType());
1964  case Type::ObjCInterface:
1965    return cast<ObjCInterfaceType>(Ty)->getDecl();
1966  default:
1967    return 0;
1968  }
1969}
1970
1971/// CreateTypeNode - Create a new debug type node.
1972llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit, bool Declaration) {
1973  // Handle qualifiers, which recursively handles what they refer to.
1974  if (Ty.hasLocalQualifiers())
1975    return CreateQualifiedType(Ty, Unit, Declaration);
1976
1977  const char *Diag = 0;
1978
1979  // Work out details of type.
1980  switch (Ty->getTypeClass()) {
1981#define TYPE(Class, Base)
1982#define ABSTRACT_TYPE(Class, Base)
1983#define NON_CANONICAL_TYPE(Class, Base)
1984#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1985#include "clang/AST/TypeNodes.def"
1986    llvm_unreachable("Dependent types cannot show up in debug information");
1987
1988  case Type::ExtVector:
1989  case Type::Vector:
1990    return CreateType(cast<VectorType>(Ty), Unit);
1991  case Type::ObjCObjectPointer:
1992    return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1993  case Type::ObjCObject:
1994    return CreateType(cast<ObjCObjectType>(Ty), Unit);
1995  case Type::ObjCInterface:
1996    return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1997  case Type::Builtin:
1998    return CreateType(cast<BuiltinType>(Ty));
1999  case Type::Complex:
2000    return CreateType(cast<ComplexType>(Ty));
2001  case Type::Pointer:
2002    return CreateType(cast<PointerType>(Ty), Unit);
2003  case Type::BlockPointer:
2004    return CreateType(cast<BlockPointerType>(Ty), Unit);
2005  case Type::Typedef:
2006    return CreateType(cast<TypedefType>(Ty), Unit, Declaration);
2007  case Type::Record:
2008    return CreateType(cast<RecordType>(Ty), Declaration);
2009  case Type::Enum:
2010    return CreateEnumType(cast<EnumType>(Ty)->getDecl());
2011  case Type::FunctionProto:
2012  case Type::FunctionNoProto:
2013    return CreateType(cast<FunctionType>(Ty), Unit);
2014  case Type::ConstantArray:
2015  case Type::VariableArray:
2016  case Type::IncompleteArray:
2017    return CreateType(cast<ArrayType>(Ty), Unit);
2018
2019  case Type::LValueReference:
2020    return CreateType(cast<LValueReferenceType>(Ty), Unit);
2021  case Type::RValueReference:
2022    return CreateType(cast<RValueReferenceType>(Ty), Unit);
2023
2024  case Type::MemberPointer:
2025    return CreateType(cast<MemberPointerType>(Ty), Unit);
2026
2027  case Type::Atomic:
2028    return CreateType(cast<AtomicType>(Ty), Unit);
2029
2030  case Type::Attributed:
2031  case Type::TemplateSpecialization:
2032  case Type::Elaborated:
2033  case Type::Paren:
2034  case Type::SubstTemplateTypeParm:
2035  case Type::TypeOfExpr:
2036  case Type::TypeOf:
2037  case Type::Decltype:
2038  case Type::UnaryTransform:
2039    llvm_unreachable("type should have been unwrapped!");
2040  case Type::Auto:
2041    Diag = "auto";
2042    break;
2043  }
2044
2045  assert(Diag && "Fall through without a diagnostic?");
2046  unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2047                               "debug information for %0 is not yet supported");
2048  CGM.getDiags().Report(DiagID)
2049    << Diag;
2050  return llvm::DIType();
2051}
2052
2053/// getOrCreateLimitedType - Get the type from the cache or create a new
2054/// limited type if necessary.
2055llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty,
2056                                                 llvm::DIFile Unit) {
2057  if (Ty.isNull())
2058    return llvm::DIType();
2059
2060  // Unwrap the type as needed for debug information.
2061  Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2062
2063  llvm::DIType T = getTypeOrNull(Ty);
2064
2065  // We may have cached a forward decl when we could have created
2066  // a non-forward decl. Go ahead and create a non-forward decl
2067  // now.
2068  if (T.Verify() && !T.isForwardDecl()) return T;
2069
2070  // Otherwise create the type.
2071  llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit);
2072
2073  if (T.Verify() && T.isForwardDecl())
2074    ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
2075                                        static_cast<llvm::Value*>(T)));
2076
2077  // And update the type cache.
2078  TypeCache[Ty.getAsOpaquePtr()] = Res;
2079  return Res;
2080}
2081
2082// TODO: Currently used for context chains when limiting debug info.
2083llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2084  RecordDecl *RD = Ty->getDecl();
2085
2086  // Get overall information about the record type for the debug info.
2087  llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2088  unsigned Line = getLineNumber(RD->getLocation());
2089  StringRef RDName = getClassName(RD);
2090
2091  llvm::DIDescriptor RDContext;
2092  if (DebugKind == CodeGenOptions::LimitedDebugInfo)
2093    RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
2094  else
2095    RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2096
2097  // If this is just a forward declaration, construct an appropriately
2098  // marked node and just return it.
2099  if (!RD->getDefinition())
2100    return createRecordFwdDecl(RD, RDContext);
2101
2102  uint64_t Size = CGM.getContext().getTypeSize(Ty);
2103  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
2104  const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2105  llvm::DICompositeType RealDecl;
2106
2107  if (RD->isUnion())
2108    RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
2109                                        Size, Align, 0, llvm::DIArray());
2110  else if (RD->isClass()) {
2111    // FIXME: This could be a struct type giving a default visibility different
2112    // than C++ class type, but needs llvm metadata changes first.
2113    RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
2114                                        Size, Align, 0, 0, llvm::DIType(),
2115                                        llvm::DIArray(), llvm::DIType(),
2116                                        llvm::DIArray());
2117  } else
2118    RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
2119                                         Size, Align, 0, llvm::DIType(),
2120                                         llvm::DIArray());
2121
2122  RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
2123  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
2124
2125  if (CXXDecl) {
2126    // A class's primary base or the class itself contains the vtable.
2127    llvm::DICompositeType ContainingType;
2128    const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2129    if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2130      // Seek non virtual primary base root.
2131      while (1) {
2132        const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2133        const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2134        if (PBT && !BRL.isPrimaryBaseVirtual())
2135          PBase = PBT;
2136        else
2137          break;
2138      }
2139      ContainingType = llvm::DICompositeType(
2140          getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit));
2141    } else if (CXXDecl->isDynamicClass())
2142      ContainingType = RealDecl;
2143
2144    RealDecl.setContainingType(ContainingType);
2145  }
2146  return llvm::DIType(RealDecl);
2147}
2148
2149/// CreateLimitedTypeNode - Create a new debug type node, but only forward
2150/// declare composite types that haven't been processed yet.
2151llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) {
2152
2153  // Work out details of type.
2154  switch (Ty->getTypeClass()) {
2155#define TYPE(Class, Base)
2156#define ABSTRACT_TYPE(Class, Base)
2157#define NON_CANONICAL_TYPE(Class, Base)
2158#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2159        #include "clang/AST/TypeNodes.def"
2160    llvm_unreachable("Dependent types cannot show up in debug information");
2161
2162  case Type::Record:
2163    return CreateLimitedType(cast<RecordType>(Ty));
2164  default:
2165    return CreateTypeNode(Ty, Unit, false);
2166  }
2167}
2168
2169/// CreateMemberType - Create new member and increase Offset by FType's size.
2170llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2171                                           StringRef Name,
2172                                           uint64_t *Offset) {
2173  llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2174  uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2175  unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2176  llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2177                                              FieldSize, FieldAlign,
2178                                              *Offset, 0, FieldTy);
2179  *Offset += FieldSize;
2180  return Ty;
2181}
2182
2183llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2184  // We only need a declaration (not a definition) of the type - so use whatever
2185  // we would otherwise do to get a type for a pointee. (forward declarations in
2186  // limited debug info, full definitions (if the type definition is available)
2187  // in unlimited debug info)
2188  if (const TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
2189    llvm::DIFile DefUnit = getOrCreateFile(TD->getLocation());
2190    return getOrCreateTypeDeclaration(CGM.getContext().getTypeDeclType(TD),
2191                                      DefUnit);
2192  }
2193  // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2194  // This doesn't handle providing declarations (for functions or variables) for
2195  // entities without definitions in this TU, nor when the definition proceeds
2196  // the call to this function.
2197  // FIXME: This should be split out into more specific maps with support for
2198  // emitting forward declarations and merging definitions with declarations,
2199  // the same way as we do for types.
2200  llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2201      DeclCache.find(D->getCanonicalDecl());
2202  if (I == DeclCache.end())
2203    return llvm::DIDescriptor();
2204  llvm::Value *V = I->second;
2205  return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2206}
2207
2208/// getFunctionDeclaration - Return debug info descriptor to describe method
2209/// declaration for the given method definition.
2210llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
2211  const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2212  if (!FD) return llvm::DISubprogram();
2213
2214  // Setup context.
2215  getContextDescriptor(cast<Decl>(D->getDeclContext()));
2216
2217  llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2218    MI = SPCache.find(FD->getCanonicalDecl());
2219  if (MI != SPCache.end()) {
2220    llvm::Value *V = MI->second;
2221    llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2222    if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2223      return SP;
2224  }
2225
2226  for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2227         E = FD->redecls_end(); I != E; ++I) {
2228    const FunctionDecl *NextFD = *I;
2229    llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2230      MI = SPCache.find(NextFD->getCanonicalDecl());
2231    if (MI != SPCache.end()) {
2232      llvm::Value *V = MI->second;
2233      llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2234      if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2235        return SP;
2236    }
2237  }
2238  return llvm::DISubprogram();
2239}
2240
2241// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2242// implicit parameter "this".
2243llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2244                                                           QualType FnType,
2245                                                           llvm::DIFile F) {
2246
2247  if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2248    return getOrCreateMethodType(Method, F);
2249  if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2250    // Add "self" and "_cmd"
2251    SmallVector<llvm::Value *, 16> Elts;
2252
2253    // First element is always return type. For 'void' functions it is NULL.
2254    QualType ResultTy = OMethod->getResultType();
2255
2256    // Replace the instancetype keyword with the actual type.
2257    if (ResultTy == CGM.getContext().getObjCInstanceType())
2258      ResultTy = CGM.getContext().getPointerType(
2259        QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2260
2261    Elts.push_back(getOrCreateType(ResultTy, F));
2262    // "self" pointer is always first argument.
2263    QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2264    llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2265    Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
2266    // "_cmd" pointer is always second argument.
2267    llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2268    Elts.push_back(DBuilder.createArtificialType(CmdTy));
2269    // Get rest of the arguments.
2270    for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
2271           PE = OMethod->param_end(); PI != PE; ++PI)
2272      Elts.push_back(getOrCreateType((*PI)->getType(), F));
2273
2274    llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2275    return DBuilder.createSubroutineType(F, EltTypeArray);
2276  }
2277  return llvm::DICompositeType(getOrCreateType(FnType, F));
2278}
2279
2280/// EmitFunctionStart - Constructs the debug code for entering a function.
2281void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2282                                    llvm::Function *Fn,
2283                                    CGBuilderTy &Builder) {
2284
2285  StringRef Name;
2286  StringRef LinkageName;
2287
2288  FnBeginRegionCount.push_back(LexicalBlockStack.size());
2289
2290  const Decl *D = GD.getDecl();
2291  // Function may lack declaration in source code if it is created by Clang
2292  // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2293  bool HasDecl = (D != 0);
2294  // Use the location of the declaration.
2295  SourceLocation Loc;
2296  if (HasDecl)
2297    Loc = D->getLocation();
2298
2299  unsigned Flags = 0;
2300  llvm::DIFile Unit = getOrCreateFile(Loc);
2301  llvm::DIDescriptor FDContext(Unit);
2302  llvm::DIArray TParamsArray;
2303  if (!HasDecl) {
2304    // Use llvm function name.
2305    Name = Fn->getName();
2306  } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2307    // If there is a DISubprogram for this function available then use it.
2308    llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2309      FI = SPCache.find(FD->getCanonicalDecl());
2310    if (FI != SPCache.end()) {
2311      llvm::Value *V = FI->second;
2312      llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2313      if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2314        llvm::MDNode *SPN = SP;
2315        LexicalBlockStack.push_back(SPN);
2316        RegionMap[D] = llvm::WeakVH(SP);
2317        return;
2318      }
2319    }
2320    Name = getFunctionName(FD);
2321    // Use mangled name as linkage name for C/C++ functions.
2322    if (FD->hasPrototype()) {
2323      LinkageName = CGM.getMangledName(GD);
2324      Flags |= llvm::DIDescriptor::FlagPrototyped;
2325    }
2326    // No need to replicate the linkage name if it isn't different from the
2327    // subprogram name, no need to have it at all unless coverage is enabled or
2328    // debug is set to more than just line tables.
2329    if (LinkageName == Name ||
2330        (!CGM.getCodeGenOpts().EmitGcovArcs &&
2331         !CGM.getCodeGenOpts().EmitGcovNotes &&
2332         DebugKind <= CodeGenOptions::DebugLineTablesOnly))
2333      LinkageName = StringRef();
2334
2335    if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
2336      if (const NamespaceDecl *NSDecl =
2337          dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2338        FDContext = getOrCreateNameSpace(NSDecl);
2339      else if (const RecordDecl *RDecl =
2340               dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2341        FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2342
2343      // Collect template parameters.
2344      TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2345    }
2346  } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2347    Name = getObjCMethodName(OMD);
2348    Flags |= llvm::DIDescriptor::FlagPrototyped;
2349  } else {
2350    // Use llvm function name.
2351    Name = Fn->getName();
2352    Flags |= llvm::DIDescriptor::FlagPrototyped;
2353  }
2354  if (!Name.empty() && Name[0] == '\01')
2355    Name = Name.substr(1);
2356
2357  unsigned LineNo = getLineNumber(Loc);
2358  if (!HasDecl || D->isImplicit())
2359    Flags |= llvm::DIDescriptor::FlagArtificial;
2360
2361  llvm::DICompositeType DIFnType;
2362  llvm::DISubprogram SPDecl;
2363  if (HasDecl &&
2364      DebugKind >= CodeGenOptions::LimitedDebugInfo) {
2365    DIFnType = getOrCreateFunctionType(D, FnType, Unit);
2366    SPDecl = getFunctionDeclaration(D);
2367  } else {
2368    // Create fake but valid subroutine type. Otherwise
2369    // llvm::DISubprogram::Verify() would return false, and
2370    // subprogram DIE will miss DW_AT_decl_file and
2371    // DW_AT_decl_line fields.
2372    SmallVector<llvm::Value*, 16> Elts;
2373    llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2374    DIFnType = DBuilder.createSubroutineType(Unit, EltTypeArray);
2375  }
2376  llvm::DISubprogram SP;
2377  SP = DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
2378                               LineNo, DIFnType,
2379                               Fn->hasInternalLinkage(), true/*definition*/,
2380                               getLineNumber(CurLoc), Flags,
2381                               CGM.getLangOpts().Optimize,
2382                               Fn, TParamsArray, SPDecl);
2383  if (HasDecl)
2384    DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
2385
2386  // Push function on region stack.
2387  llvm::MDNode *SPN = SP;
2388  LexicalBlockStack.push_back(SPN);
2389  if (HasDecl)
2390    RegionMap[D] = llvm::WeakVH(SP);
2391}
2392
2393/// EmitLocation - Emit metadata to indicate a change in line/column
2394/// information in the source file.
2395void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2396                               bool ForceColumnInfo) {
2397
2398  // Update our current location
2399  setLocation(Loc);
2400
2401  if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2402
2403  // Don't bother if things are the same as last time.
2404  SourceManager &SM = CGM.getContext().getSourceManager();
2405  if (CurLoc == PrevLoc ||
2406      SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2407    // New Builder may not be in sync with CGDebugInfo.
2408    if (!Builder.getCurrentDebugLocation().isUnknown() &&
2409        Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2410          LexicalBlockStack.back())
2411      return;
2412
2413  // Update last state.
2414  PrevLoc = CurLoc;
2415
2416  llvm::MDNode *Scope = LexicalBlockStack.back();
2417  Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2418                                  (getLineNumber(CurLoc),
2419                                   getColumnNumber(CurLoc, ForceColumnInfo),
2420                                   Scope));
2421}
2422
2423/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2424/// the stack.
2425void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2426  llvm::DIDescriptor D =
2427    DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2428                                llvm::DIDescriptor() :
2429                                llvm::DIDescriptor(LexicalBlockStack.back()),
2430                                getOrCreateFile(CurLoc),
2431                                getLineNumber(CurLoc),
2432                                getColumnNumber(CurLoc));
2433  llvm::MDNode *DN = D;
2434  LexicalBlockStack.push_back(DN);
2435}
2436
2437/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2438/// region - beginning of a DW_TAG_lexical_block.
2439void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2440                                        SourceLocation Loc) {
2441  // Set our current location.
2442  setLocation(Loc);
2443
2444  // Create a new lexical block and push it on the stack.
2445  CreateLexicalBlock(Loc);
2446
2447  // Emit a line table change for the current location inside the new scope.
2448  Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2449                                  getColumnNumber(Loc),
2450                                  LexicalBlockStack.back()));
2451}
2452
2453/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2454/// region - end of a DW_TAG_lexical_block.
2455void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2456                                      SourceLocation Loc) {
2457  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2458
2459  // Provide an entry in the line table for the end of the block.
2460  EmitLocation(Builder, Loc);
2461
2462  LexicalBlockStack.pop_back();
2463}
2464
2465/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2466void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2467  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2468  unsigned RCount = FnBeginRegionCount.back();
2469  assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2470
2471  // Pop all regions for this function.
2472  while (LexicalBlockStack.size() != RCount)
2473    EmitLexicalBlockEnd(Builder, CurLoc);
2474  FnBeginRegionCount.pop_back();
2475}
2476
2477// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
2478// See BuildByRefType.
2479llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2480                                                       uint64_t *XOffset) {
2481
2482  SmallVector<llvm::Value *, 5> EltTys;
2483  QualType FType;
2484  uint64_t FieldSize, FieldOffset;
2485  unsigned FieldAlign;
2486
2487  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2488  QualType Type = VD->getType();
2489
2490  FieldOffset = 0;
2491  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2492  EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2493  EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2494  FType = CGM.getContext().IntTy;
2495  EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2496  EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2497
2498  bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2499  if (HasCopyAndDispose) {
2500    FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2501    EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2502                                      &FieldOffset));
2503    EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2504                                      &FieldOffset));
2505  }
2506  bool HasByrefExtendedLayout;
2507  Qualifiers::ObjCLifetime Lifetime;
2508  if (CGM.getContext().getByrefLifetime(Type,
2509                                        Lifetime, HasByrefExtendedLayout)
2510      && HasByrefExtendedLayout)
2511    EltTys.push_back(CreateMemberType(Unit, FType,
2512                                      "__byref_variable_layout",
2513                                      &FieldOffset));
2514
2515  CharUnits Align = CGM.getContext().getDeclAlign(VD);
2516  if (Align > CGM.getContext().toCharUnitsFromBits(
2517        CGM.getTarget().getPointerAlign(0))) {
2518    CharUnits FieldOffsetInBytes
2519      = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2520    CharUnits AlignedOffsetInBytes
2521      = FieldOffsetInBytes.RoundUpToAlignment(Align);
2522    CharUnits NumPaddingBytes
2523      = AlignedOffsetInBytes - FieldOffsetInBytes;
2524
2525    if (NumPaddingBytes.isPositive()) {
2526      llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2527      FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2528                                                    pad, ArrayType::Normal, 0);
2529      EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2530    }
2531  }
2532
2533  FType = Type;
2534  llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2535  FieldSize = CGM.getContext().getTypeSize(FType);
2536  FieldAlign = CGM.getContext().toBits(Align);
2537
2538  *XOffset = FieldOffset;
2539  FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2540                                      0, FieldSize, FieldAlign,
2541                                      FieldOffset, 0, FieldTy);
2542  EltTys.push_back(FieldTy);
2543  FieldOffset += FieldSize;
2544
2545  llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
2546
2547  unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
2548
2549  return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
2550                                   llvm::DIType(), Elements);
2551}
2552
2553/// EmitDeclare - Emit local variable declaration debug info.
2554void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
2555                              llvm::Value *Storage,
2556                              unsigned ArgNo, CGBuilderTy &Builder) {
2557  assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2558  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2559
2560  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2561  llvm::DIType Ty;
2562  uint64_t XOffset = 0;
2563  if (VD->hasAttr<BlocksAttr>())
2564    Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2565  else
2566    Ty = getOrCreateType(VD->getType(), Unit);
2567
2568  // If there is no debug info for this type then do not emit debug info
2569  // for this variable.
2570  if (!Ty)
2571    return;
2572
2573  if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) {
2574    // If Storage is an aggregate returned as 'sret' then let debugger know
2575    // about this.
2576    if (Arg->hasStructRetAttr())
2577      Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2578    else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) {
2579      // If an aggregate variable has non trivial destructor or non trivial copy
2580      // constructor than it is pass indirectly. Let debug info know about this
2581      // by using reference of the aggregate type as a argument type.
2582      if (Record->hasNonTrivialCopyConstructor() ||
2583          !Record->hasTrivialDestructor())
2584        Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type,
2585                                          Ty);
2586    }
2587  }
2588
2589  // Get location information.
2590  unsigned Line = getLineNumber(VD->getLocation());
2591  unsigned Column = getColumnNumber(VD->getLocation());
2592  unsigned Flags = 0;
2593  if (VD->isImplicit())
2594    Flags |= llvm::DIDescriptor::FlagArtificial;
2595  // If this is the first argument and it is implicit then
2596  // give it an object pointer flag.
2597  // FIXME: There has to be a better way to do this, but for static
2598  // functions there won't be an implicit param at arg1 and
2599  // otherwise it is 'self' or 'this'.
2600  if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2601    Flags |= llvm::DIDescriptor::FlagObjectPointer;
2602
2603  llvm::MDNode *Scope = LexicalBlockStack.back();
2604
2605  StringRef Name = VD->getName();
2606  if (!Name.empty()) {
2607    if (VD->hasAttr<BlocksAttr>()) {
2608      CharUnits offset = CharUnits::fromQuantity(32);
2609      SmallVector<llvm::Value *, 9> addr;
2610      llvm::Type *Int64Ty = CGM.Int64Ty;
2611      addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2612      // offset of __forwarding field
2613      offset = CGM.getContext().toCharUnitsFromBits(
2614        CGM.getTarget().getPointerWidth(0));
2615      addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2616      addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2617      addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2618      // offset of x field
2619      offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2620      addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2621
2622      // Create the descriptor for the variable.
2623      llvm::DIVariable D =
2624        DBuilder.createComplexVariable(Tag,
2625                                       llvm::DIDescriptor(Scope),
2626                                       VD->getName(), Unit, Line, Ty,
2627                                       addr, ArgNo);
2628
2629      // Insert an llvm.dbg.declare into the current block.
2630      llvm::Instruction *Call =
2631        DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2632      Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2633      return;
2634    } else if (isa<VariableArrayType>(VD->getType())) {
2635      // These are "complex" variables in that they need an op_deref.
2636      // Create the descriptor for the variable.
2637      llvm::Value *Addr = llvm::ConstantInt::get(CGM.Int64Ty,
2638                                                 llvm::DIBuilder::OpDeref);
2639      llvm::DIVariable D =
2640        DBuilder.createComplexVariable(Tag,
2641                                       llvm::DIDescriptor(Scope),
2642                                       Name, Unit, Line, Ty,
2643                                       Addr, ArgNo);
2644
2645      // Insert an llvm.dbg.declare into the current block.
2646      llvm::Instruction *Call =
2647        DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2648      Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2649      return;
2650    }
2651  } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2652    // If VD is an anonymous union then Storage represents value for
2653    // all union fields.
2654    const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2655    if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
2656      for (RecordDecl::field_iterator I = RD->field_begin(),
2657             E = RD->field_end();
2658           I != E; ++I) {
2659        FieldDecl *Field = *I;
2660        llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2661        StringRef FieldName = Field->getName();
2662
2663        // Ignore unnamed fields. Do not ignore unnamed records.
2664        if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2665          continue;
2666
2667        // Use VarDecl's Tag, Scope and Line number.
2668        llvm::DIVariable D =
2669          DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2670                                       FieldName, Unit, Line, FieldTy,
2671                                       CGM.getLangOpts().Optimize, Flags,
2672                                       ArgNo);
2673
2674        // Insert an llvm.dbg.declare into the current block.
2675        llvm::Instruction *Call =
2676          DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2677        Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2678      }
2679      return;
2680    }
2681  }
2682
2683  // Create the descriptor for the variable.
2684  llvm::DIVariable D =
2685    DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2686                                 Name, Unit, Line, Ty,
2687                                 CGM.getLangOpts().Optimize, Flags, ArgNo);
2688
2689  // Insert an llvm.dbg.declare into the current block.
2690  llvm::Instruction *Call =
2691    DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2692  Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2693}
2694
2695void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2696                                            llvm::Value *Storage,
2697                                            CGBuilderTy &Builder) {
2698  assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2699  EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2700}
2701
2702/// Look up the completed type for a self pointer in the TypeCache and
2703/// create a copy of it with the ObjectPointer and Artificial flags
2704/// set. If the type is not cached, a new one is created. This should
2705/// never happen though, since creating a type for the implicit self
2706/// argument implies that we already parsed the interface definition
2707/// and the ivar declarations in the implementation.
2708llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2709                                         llvm::DIType Ty) {
2710  llvm::DIType CachedTy = getTypeOrNull(QualTy);
2711  if (CachedTy.Verify()) Ty = CachedTy;
2712  else DEBUG(llvm::dbgs() << "No cached type for self.");
2713  return DBuilder.createObjectPointerType(Ty);
2714}
2715
2716void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2717                                                    llvm::Value *Storage,
2718                                                    CGBuilderTy &Builder,
2719                                                 const CGBlockInfo &blockInfo) {
2720  assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2721  assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2722
2723  if (Builder.GetInsertBlock() == 0)
2724    return;
2725
2726  bool isByRef = VD->hasAttr<BlocksAttr>();
2727
2728  uint64_t XOffset = 0;
2729  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2730  llvm::DIType Ty;
2731  if (isByRef)
2732    Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2733  else
2734    Ty = getOrCreateType(VD->getType(), Unit);
2735
2736  // Self is passed along as an implicit non-arg variable in a
2737  // block. Mark it as the object pointer.
2738  if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
2739    Ty = CreateSelfType(VD->getType(), Ty);
2740
2741  // Get location information.
2742  unsigned Line = getLineNumber(VD->getLocation());
2743  unsigned Column = getColumnNumber(VD->getLocation());
2744
2745  const llvm::DataLayout &target = CGM.getDataLayout();
2746
2747  CharUnits offset = CharUnits::fromQuantity(
2748    target.getStructLayout(blockInfo.StructureType)
2749          ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2750
2751  SmallVector<llvm::Value *, 9> addr;
2752  llvm::Type *Int64Ty = CGM.Int64Ty;
2753  if (isa<llvm::AllocaInst>(Storage))
2754    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2755  addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2756  addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2757  if (isByRef) {
2758    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2759    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2760    // offset of __forwarding field
2761    offset = CGM.getContext()
2762                .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2763    addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2764    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2765    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2766    // offset of x field
2767    offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2768    addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2769  }
2770
2771  // Create the descriptor for the variable.
2772  llvm::DIVariable D =
2773    DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
2774                                   llvm::DIDescriptor(LexicalBlockStack.back()),
2775                                   VD->getName(), Unit, Line, Ty, addr);
2776
2777  // Insert an llvm.dbg.declare into the current block.
2778  llvm::Instruction *Call =
2779    DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2780  Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2781                                        LexicalBlockStack.back()));
2782}
2783
2784/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2785/// variable declaration.
2786void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2787                                           unsigned ArgNo,
2788                                           CGBuilderTy &Builder) {
2789  assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2790  EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2791}
2792
2793namespace {
2794  struct BlockLayoutChunk {
2795    uint64_t OffsetInBits;
2796    const BlockDecl::Capture *Capture;
2797  };
2798  bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2799    return l.OffsetInBits < r.OffsetInBits;
2800  }
2801}
2802
2803void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
2804                                                       llvm::Value *Arg,
2805                                                       llvm::Value *LocalAddr,
2806                                                       CGBuilderTy &Builder) {
2807  assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2808  ASTContext &C = CGM.getContext();
2809  const BlockDecl *blockDecl = block.getBlockDecl();
2810
2811  // Collect some general information about the block's location.
2812  SourceLocation loc = blockDecl->getCaretLocation();
2813  llvm::DIFile tunit = getOrCreateFile(loc);
2814  unsigned line = getLineNumber(loc);
2815  unsigned column = getColumnNumber(loc);
2816
2817  // Build the debug-info type for the block literal.
2818  getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2819
2820  const llvm::StructLayout *blockLayout =
2821    CGM.getDataLayout().getStructLayout(block.StructureType);
2822
2823  SmallVector<llvm::Value*, 16> fields;
2824  fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2825                                   blockLayout->getElementOffsetInBits(0),
2826                                   tunit, tunit));
2827  fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2828                                   blockLayout->getElementOffsetInBits(1),
2829                                   tunit, tunit));
2830  fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2831                                   blockLayout->getElementOffsetInBits(2),
2832                                   tunit, tunit));
2833  fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2834                                   blockLayout->getElementOffsetInBits(3),
2835                                   tunit, tunit));
2836  fields.push_back(createFieldType("__descriptor",
2837                                   C.getPointerType(block.NeedsCopyDispose ?
2838                                        C.getBlockDescriptorExtendedType() :
2839                                        C.getBlockDescriptorType()),
2840                                   0, loc, AS_public,
2841                                   blockLayout->getElementOffsetInBits(4),
2842                                   tunit, tunit));
2843
2844  // We want to sort the captures by offset, not because DWARF
2845  // requires this, but because we're paranoid about debuggers.
2846  SmallVector<BlockLayoutChunk, 8> chunks;
2847
2848  // 'this' capture.
2849  if (blockDecl->capturesCXXThis()) {
2850    BlockLayoutChunk chunk;
2851    chunk.OffsetInBits =
2852      blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2853    chunk.Capture = 0;
2854    chunks.push_back(chunk);
2855  }
2856
2857  // Variable captures.
2858  for (BlockDecl::capture_const_iterator
2859         i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2860       i != e; ++i) {
2861    const BlockDecl::Capture &capture = *i;
2862    const VarDecl *variable = capture.getVariable();
2863    const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2864
2865    // Ignore constant captures.
2866    if (captureInfo.isConstant())
2867      continue;
2868
2869    BlockLayoutChunk chunk;
2870    chunk.OffsetInBits =
2871      blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2872    chunk.Capture = &capture;
2873    chunks.push_back(chunk);
2874  }
2875
2876  // Sort by offset.
2877  llvm::array_pod_sort(chunks.begin(), chunks.end());
2878
2879  for (SmallVectorImpl<BlockLayoutChunk>::iterator
2880         i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2881    uint64_t offsetInBits = i->OffsetInBits;
2882    const BlockDecl::Capture *capture = i->Capture;
2883
2884    // If we have a null capture, this must be the C++ 'this' capture.
2885    if (!capture) {
2886      const CXXMethodDecl *method =
2887        cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2888      QualType type = method->getThisType(C);
2889
2890      fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2891                                       offsetInBits, tunit, tunit));
2892      continue;
2893    }
2894
2895    const VarDecl *variable = capture->getVariable();
2896    StringRef name = variable->getName();
2897
2898    llvm::DIType fieldType;
2899    if (capture->isByRef()) {
2900      std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2901
2902      // FIXME: this creates a second copy of this type!
2903      uint64_t xoffset;
2904      fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2905      fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2906      fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2907                                            ptrInfo.first, ptrInfo.second,
2908                                            offsetInBits, 0, fieldType);
2909    } else {
2910      fieldType = createFieldType(name, variable->getType(), 0,
2911                                  loc, AS_public, offsetInBits, tunit, tunit);
2912    }
2913    fields.push_back(fieldType);
2914  }
2915
2916  SmallString<36> typeName;
2917  llvm::raw_svector_ostream(typeName)
2918    << "__block_literal_" << CGM.getUniqueBlockCount();
2919
2920  llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2921
2922  llvm::DIType type =
2923    DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2924                              CGM.getContext().toBits(block.BlockSize),
2925                              CGM.getContext().toBits(block.BlockAlign),
2926                              0, llvm::DIType(), fieldsArray);
2927  type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2928
2929  // Get overall information about the block.
2930  unsigned flags = llvm::DIDescriptor::FlagArtificial;
2931  llvm::MDNode *scope = LexicalBlockStack.back();
2932
2933  // Create the descriptor for the parameter.
2934  llvm::DIVariable debugVar =
2935    DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
2936                                 llvm::DIDescriptor(scope),
2937                                 Arg->getName(), tunit, line, type,
2938                                 CGM.getLangOpts().Optimize, flags,
2939                                 cast<llvm::Argument>(Arg)->getArgNo() + 1);
2940
2941  if (LocalAddr) {
2942    // Insert an llvm.dbg.value into the current block.
2943    llvm::Instruction *DbgVal =
2944      DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
2945                                       Builder.GetInsertBlock());
2946    DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2947  }
2948
2949  // Insert an llvm.dbg.declare into the current block.
2950  llvm::Instruction *DbgDecl =
2951    DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
2952  DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2953}
2954
2955/// getStaticDataMemberDeclaration - If D is an out-of-class definition of
2956/// a static data member of a class, find its corresponding in-class
2957/// declaration.
2958llvm::DIDerivedType CGDebugInfo::getStaticDataMemberDeclaration(const Decl *D) {
2959  if (cast<VarDecl>(D)->isStaticDataMember()) {
2960    llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
2961      MI = StaticDataMemberCache.find(D->getCanonicalDecl());
2962    if (MI != StaticDataMemberCache.end())
2963      // Verify the info still exists.
2964      if (llvm::Value *V = MI->second)
2965        return llvm::DIDerivedType(cast<llvm::MDNode>(V));
2966  }
2967  return llvm::DIDerivedType();
2968}
2969
2970/// EmitGlobalVariable - Emit information about a global variable.
2971void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2972                                     const VarDecl *D) {
2973  assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2974  // Create global variable debug descriptor.
2975  llvm::DIFile Unit = getOrCreateFile(D->getLocation());
2976  unsigned LineNo = getLineNumber(D->getLocation());
2977
2978  setLocation(D->getLocation());
2979
2980  QualType T = D->getType();
2981  if (T->isIncompleteArrayType()) {
2982
2983    // CodeGen turns int[] into int[1] so we'll do the same here.
2984    llvm::APInt ConstVal(32, 1);
2985    QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2986
2987    T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2988                                              ArrayType::Normal, 0);
2989  }
2990  StringRef DeclName = D->getName();
2991  StringRef LinkageName;
2992  if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
2993      && !isa<ObjCMethodDecl>(D->getDeclContext()))
2994    LinkageName = Var->getName();
2995  if (LinkageName == DeclName)
2996    LinkageName = StringRef();
2997  llvm::DIDescriptor DContext =
2998    getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
2999  llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(DContext, DeclName, LinkageName,
3000                                Unit, LineNo, getOrCreateType(T, Unit),
3001                                Var->hasInternalLinkage(), Var,
3002                                getStaticDataMemberDeclaration(D));
3003  DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
3004}
3005
3006/// EmitGlobalVariable - Emit information about an objective-c interface.
3007void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3008                                     ObjCInterfaceDecl *ID) {
3009  assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
3010  // Create global variable debug descriptor.
3011  llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3012  unsigned LineNo = getLineNumber(ID->getLocation());
3013
3014  StringRef Name = ID->getName();
3015
3016  QualType T = CGM.getContext().getObjCInterfaceType(ID);
3017  if (T->isIncompleteArrayType()) {
3018
3019    // CodeGen turns int[] into int[1] so we'll do the same here.
3020    llvm::APInt ConstVal(32, 1);
3021    QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3022
3023    T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3024                                           ArrayType::Normal, 0);
3025  }
3026
3027  DBuilder.createGlobalVariable(Name, Unit, LineNo,
3028                                getOrCreateType(T, Unit),
3029                                Var->hasInternalLinkage(), Var);
3030}
3031
3032/// EmitGlobalVariable - Emit global variable's debug info.
3033void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
3034                                     llvm::Constant *Init) {
3035  assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
3036  // Create the descriptor for the variable.
3037  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3038  StringRef Name = VD->getName();
3039  llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3040  if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3041    const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3042    assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3043    Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3044  }
3045  // Do not use DIGlobalVariable for enums.
3046  if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3047    return;
3048  llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(Unit, Name, Name, Unit,
3049                                getLineNumber(VD->getLocation()),
3050                                Ty, true, Init,
3051                                getStaticDataMemberDeclaration(VD));
3052  DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
3053}
3054
3055llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3056  if (!LexicalBlockStack.empty())
3057    return llvm::DIScope(LexicalBlockStack.back());
3058  return getContextDescriptor(D);
3059}
3060
3061void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
3062  if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3063    return;
3064  DBuilder.createImportedModule(
3065      getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3066      getOrCreateNameSpace(UD.getNominatedNamespace()),
3067      getLineNumber(UD.getLocation()));
3068}
3069
3070void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3071  if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3072    return;
3073  assert(UD.shadow_size() &&
3074         "We shouldn't be codegening an invalid UsingDecl containing no decls");
3075  // Emitting one decl is sufficient - debuggers can detect that this is an
3076  // overloaded name & provide lookup for all the overloads.
3077  const UsingShadowDecl &USD = **UD.shadow_begin();
3078  if (llvm::DIDescriptor Target = getDeclarationOrDefinition(USD.getUnderlyingDecl()))
3079    DBuilder.createImportedDeclaration(
3080        getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3081        getLineNumber(USD.getLocation()));
3082}
3083
3084llvm::DIImportedEntity
3085CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3086  if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3087    return llvm::DIImportedEntity(0);
3088  llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3089  if (VH)
3090    return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3091  llvm::DIImportedEntity R(0);
3092  if (const NamespaceAliasDecl *Underlying =
3093          dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3094    // This could cache & dedup here rather than relying on metadata deduping.
3095    R = DBuilder.createImportedModule(
3096        getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3097        EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3098        NA.getName());
3099  else
3100    R = DBuilder.createImportedModule(
3101        getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3102        getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3103        getLineNumber(NA.getLocation()), NA.getName());
3104  VH = R;
3105  return R;
3106}
3107
3108/// getOrCreateNamesSpace - Return namespace descriptor for the given
3109/// namespace decl.
3110llvm::DINameSpace
3111CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
3112  llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
3113    NameSpaceCache.find(NSDecl);
3114  if (I != NameSpaceCache.end())
3115    return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
3116
3117  unsigned LineNo = getLineNumber(NSDecl->getLocation());
3118  llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
3119  llvm::DIDescriptor Context =
3120    getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3121  llvm::DINameSpace NS =
3122    DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3123  NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3124  return NS;
3125}
3126
3127void CGDebugInfo::finalize() {
3128  for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3129         = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3130    llvm::DIType Ty, RepTy;
3131    // Verify that the debug info still exists.
3132    if (llvm::Value *V = VI->second)
3133      Ty = llvm::DIType(cast<llvm::MDNode>(V));
3134
3135    llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3136      TypeCache.find(VI->first);
3137    if (it != TypeCache.end()) {
3138      // Verify that the debug info still exists.
3139      if (llvm::Value *V = it->second)
3140        RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3141    }
3142
3143    if (Ty.Verify() && Ty.isForwardDecl() && RepTy.Verify())
3144      Ty.replaceAllUsesWith(RepTy);
3145  }
3146
3147  // We keep our own list of retained types, because we need to look
3148  // up the final type in the type cache.
3149  for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3150         RE = RetainedTypes.end(); RI != RE; ++RI)
3151    DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
3152
3153  DBuilder.finalize();
3154}
3155