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