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