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