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