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