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