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