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