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