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