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