1 //===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This coordinates the debug information generation while generating code.
12 //===----------------------------------------------------------------------===//
14 #include "CGDebugInfo.h"
15 #include "CodeGenFunction.h"
16 #include "CodeGenModule.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/RecordLayout.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "clang/Basic/FileManager.h"
23 #include "clang/Basic/Version.h"
24 #include "clang/CodeGen/CodeGenOptions.h"
25 #include "llvm/Constants.h"
26 #include "llvm/DerivedTypes.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/Module.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/Support/Dwarf.h"
33 #include "llvm/System/Path.h"
34 #include "llvm/Target/TargetMachine.h"
35 using namespace clang;
36 using namespace clang::CodeGen;
38 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
39 : CGM(CGM), DebugFactory(CGM.getModule()),
40 FwdDeclCount(0), BlockLiteralGenericSet(false) {
44 CGDebugInfo::~CGDebugInfo() {
45 assert(RegionStack.empty() && "Region stack mismatch, stack not empty!");
48 void CGDebugInfo::setLocation(SourceLocation Loc) {
50 CurLoc = CGM.getContext().getSourceManager().getInstantiationLoc(Loc);
53 /// getContextDescriptor - Get context info for the decl.
54 llvm::DIDescriptor CGDebugInfo::getContextDescriptor(const Decl *Context,
55 llvm::DIDescriptor &CompileUnit) {
59 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
60 I = RegionMap.find(Context);
61 if (I != RegionMap.end())
62 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(I->second));
65 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
66 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl, CompileUnit));
68 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context)) {
69 if (!RDecl->isDependentType()) {
70 llvm::DIType Ty = getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
71 llvm::DIFile(CompileUnit));
72 return llvm::DIDescriptor(Ty);
78 /// getFunctionName - Get function name for the given FunctionDecl. If the
79 /// name is constructred on demand (e.g. C++ destructor) then the name
80 /// is stored on the side.
81 llvm::StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
82 assert (FD && "Invalid FunctionDecl!");
83 IdentifierInfo *FII = FD->getIdentifier();
85 return FII->getName();
87 // Otherwise construct human readable name for debug info.
88 std::string NS = FD->getNameAsString();
90 // Copy this name on the side and use its reference.
91 char *StrPtr = DebugInfoNames.Allocate<char>(NS.length());
92 memcpy(StrPtr, NS.data(), NS.length());
93 return llvm::StringRef(StrPtr, NS.length());
96 /// getOrCreateFile - Get the file debug info descriptor for the input location.
97 llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
99 // If Location is not valid then use main input file.
100 return DebugFactory.CreateFile(TheCU.getFilename(), TheCU.getDirectory(),
102 SourceManager &SM = CGM.getContext().getSourceManager();
103 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
105 // Cache the results.
106 const char *fname = PLoc.getFilename();
107 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
108 DIFileCache.find(fname);
110 if (it != DIFileCache.end()) {
111 // Verify that the information still exists.
113 return llvm::DIFile(cast<llvm::MDNode>(it->second));
116 // FIXME: We shouldn't even need to call 'makeAbsolute()' in the cases
117 // where we can consult the FileEntry.
118 llvm::sys::Path AbsFileName(PLoc.getFilename());
119 AbsFileName.makeAbsolute();
121 llvm::DIFile F = DebugFactory.CreateFile(AbsFileName.getLast(),
122 AbsFileName.getDirname(), TheCU);
124 DIFileCache[fname] = F;
129 /// getLineNumber - Get line number for the location. If location is invalid
130 /// then use current location.
131 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
132 assert (CurLoc.isValid() && "Invalid current location!");
133 SourceManager &SM = CGM.getContext().getSourceManager();
134 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
135 return PLoc.getLine();
138 /// getColumnNumber - Get column number for the location. If location is
139 /// invalid then use current location.
140 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc) {
141 assert (CurLoc.isValid() && "Invalid current location!");
142 SourceManager &SM = CGM.getContext().getSourceManager();
143 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
144 return PLoc.getColumn();
147 /// CreateCompileUnit - Create new compile unit.
148 void CGDebugInfo::CreateCompileUnit() {
150 // Get absolute path name.
151 SourceManager &SM = CGM.getContext().getSourceManager();
152 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
153 if (MainFileName.empty())
154 MainFileName = "<unknown>";
156 llvm::sys::Path AbsFileName(MainFileName);
157 AbsFileName.makeAbsolute();
159 // The main file name provided via the "-main-file-name" option contains just
160 // the file name itself with no path information. This file name may have had
161 // a relative path, so we look into the actual file entry for the main
162 // file to determine the real absolute path for the file.
163 std::string MainFileDir;
164 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID()))
165 MainFileDir = MainFile->getDir()->getName();
167 MainFileDir = AbsFileName.getDirname();
170 const LangOptions &LO = CGM.getLangOptions();
173 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
175 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
176 } else if (LO.ObjC1) {
177 LangTag = llvm::dwarf::DW_LANG_ObjC;
179 LangTag = llvm::dwarf::DW_LANG_C99;
181 LangTag = llvm::dwarf::DW_LANG_C89;
184 const char *Producer =
188 "clang " CLANG_VERSION_STRING;
190 // Figure out which version of the ObjC runtime we have.
191 unsigned RuntimeVers = 0;
193 RuntimeVers = LO.ObjCNonFragileABI ? 2 : 1;
195 // Create new compile unit.
196 TheCU = DebugFactory.CreateCompileUnit(
197 LangTag, AbsFileName.getLast(), MainFileDir, Producer, true,
198 LO.Optimize, CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers);
201 /// CreateType - Get the Basic type from the cache or create a new
202 /// one if necessary.
203 llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT,
205 unsigned Encoding = 0;
206 switch (BT->getKind()) {
208 case BuiltinType::Void:
209 return llvm::DIType();
210 case BuiltinType::UChar:
211 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
212 case BuiltinType::Char_S:
213 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
214 case BuiltinType::UShort:
215 case BuiltinType::UInt:
216 case BuiltinType::ULong:
217 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
218 case BuiltinType::Short:
219 case BuiltinType::Int:
220 case BuiltinType::Long:
221 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
222 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
223 case BuiltinType::Float:
224 case BuiltinType::LongDouble:
225 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
227 // Bit size, align and offset of the type.
228 uint64_t Size = CGM.getContext().getTypeSize(BT);
229 uint64_t Align = CGM.getContext().getTypeAlign(BT);
233 DebugFactory.CreateBasicType(Unit,
234 BT->getName(CGM.getContext().getLangOptions()),
235 Unit, 0, Size, Align,
236 Offset, /*flags*/ 0, Encoding);
240 llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty,
242 // Bit size, align and offset of the type.
243 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
244 if (Ty->isComplexIntegerType())
245 Encoding = llvm::dwarf::DW_ATE_lo_user;
247 uint64_t Size = CGM.getContext().getTypeSize(Ty);
248 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
252 DebugFactory.CreateBasicType(Unit, "complex",
253 Unit, 0, Size, Align,
254 Offset, /*flags*/ 0, Encoding);
258 /// CreateCVRType - Get the qualified type from the cache or create
259 /// a new one if necessary.
260 llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
261 QualifierCollector Qc;
262 const Type *T = Qc.strip(Ty);
264 // Ignore these qualifiers for now.
265 Qc.removeObjCGCAttr();
266 Qc.removeAddressSpace();
268 // We will create one Derived type for one qualifier and recurse to handle any
272 Tag = llvm::dwarf::DW_TAG_const_type;
274 } else if (Qc.hasVolatile()) {
275 Tag = llvm::dwarf::DW_TAG_volatile_type;
277 } else if (Qc.hasRestrict()) {
278 Tag = llvm::dwarf::DW_TAG_restrict_type;
281 assert(Qc.empty() && "Unknown type qualifier for debug info");
282 return getOrCreateType(QualType(T, 0), Unit);
285 llvm::DIType FromTy = getOrCreateType(Qc.apply(T), Unit);
287 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
288 // CVR derived types.
290 DebugFactory.CreateDerivedType(Tag, Unit, "", Unit,
291 0, 0, 0, 0, 0, FromTy);
295 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
298 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
299 Ty->getPointeeType(), Unit);
303 llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
305 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
306 Ty->getPointeeType(), Unit);
309 llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
313 llvm::DIType EltTy = getOrCreateType(PointeeTy, Unit);
315 // Bit size, align and offset of the type.
317 // Size is always the size of a pointer. We can't use getTypeSize here
318 // because that does not return the correct value for references.
320 CGM.getContext().Target.getPointerWidth(PointeeTy.getAddressSpace());
321 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
324 DebugFactory.CreateDerivedType(Tag, Unit, "", Unit,
325 0, Size, Align, 0, 0, EltTy);
329 llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
331 if (BlockLiteralGenericSet)
332 return BlockLiteralGeneric;
334 unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
336 llvm::SmallVector<llvm::DIDescriptor, 5> EltTys;
338 llvm::DIType FieldTy;
341 uint64_t FieldSize, FieldOffset;
344 llvm::DIArray Elements;
345 llvm::DIType EltTy, DescTy;
348 FType = CGM.getContext().UnsignedLongTy;
349 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
350 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
352 Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
355 unsigned Flags = llvm::DIType::FlagAppleBlock;
356 unsigned LineNo = getLineNumber(CurLoc);
358 EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_descriptor",
359 Unit, LineNo, FieldOffset, 0, 0,
360 Flags, llvm::DIType(), Elements);
362 // Bit size, align and offset of the type.
363 uint64_t Size = CGM.getContext().getTypeSize(Ty);
364 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
366 DescTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
368 LineNo, Size, Align, 0, 0, EltTy);
371 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
372 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
373 FType = CGM.getContext().IntTy;
374 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
375 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
376 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
377 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
379 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
381 FieldSize = CGM.getContext().getTypeSize(Ty);
382 FieldAlign = CGM.getContext().getTypeAlign(Ty);
383 FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
384 "__descriptor", Unit,
385 LineNo, FieldSize, FieldAlign,
386 FieldOffset, 0, FieldTy);
387 EltTys.push_back(FieldTy);
389 FieldOffset += FieldSize;
390 Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
392 EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_literal_generic",
393 Unit, LineNo, FieldOffset, 0, 0,
394 Flags, llvm::DIType(), Elements);
396 BlockLiteralGenericSet = true;
398 = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, Unit,
400 LineNo, Size, Align, 0, 0, EltTy);
401 return BlockLiteralGeneric;
404 llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty,
406 // Typedefs are derived from some other type. If we have a typedef of a
407 // typedef, make sure to emit the whole chain.
408 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
410 // We don't set size information, but do specify where the typedef was
412 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
414 llvm::DIDescriptor TyContext
415 = getContextDescriptor(dyn_cast<Decl>(Ty->getDecl()->getDeclContext()),
418 DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_typedef,
420 Ty->getDecl()->getName(), Unit,
421 Line, 0, 0, 0, 0, Src);
425 llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
427 llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
429 // Add the result type at least.
430 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
432 // Set up remainder of arguments if there is a prototype.
433 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
434 if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(Ty)) {
435 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
436 EltTys.push_back(getOrCreateType(FTP->getArgType(i), Unit));
438 // FIXME: Handle () case in C. llvm-gcc doesn't do it either.
441 llvm::DIArray EltTypeArray =
442 DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
445 DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
448 llvm::DIType(), EltTypeArray);
452 /// CollectRecordFields - A helper function to collect debug info for
453 /// record fields. This is used while creating debug info entry for a Record.
455 CollectRecordFields(const RecordDecl *RD, llvm::DIFile Unit,
456 llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys) {
457 unsigned FieldNo = 0;
458 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
459 for (RecordDecl::field_iterator I = RD->field_begin(),
461 I != E; ++I, ++FieldNo) {
462 FieldDecl *Field = *I;
463 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
465 llvm::StringRef FieldName = Field->getName();
467 // Ignore unnamed fields. Do not ignore unnamed records.
468 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
471 // Get the location for the field.
472 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
473 unsigned FieldLine = getLineNumber(Field->getLocation());
474 QualType FType = Field->getType();
475 uint64_t FieldSize = 0;
476 unsigned FieldAlign = 0;
477 if (!FType->isIncompleteArrayType()) {
479 // Bit size, align and offset of the type.
480 FieldSize = CGM.getContext().getTypeSize(FType);
481 Expr *BitWidth = Field->getBitWidth();
483 FieldSize = BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
485 FieldAlign = CGM.getContext().getTypeAlign(FType);
488 uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
491 AccessSpecifier Access = I->getAccess();
492 if (Access == clang::AS_private)
493 Flags |= llvm::DIType::FlagPrivate;
494 else if (Access == clang::AS_protected)
495 Flags |= llvm::DIType::FlagProtected;
497 // Create a DW_TAG_member node to remember the offset of this field in the
498 // struct. FIXME: This is an absolutely insane way to capture this
499 // information. When we gut debug info, this should be fixed.
500 FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
501 FieldName, FieldDefUnit,
502 FieldLine, FieldSize, FieldAlign,
503 FieldOffset, Flags, FieldTy);
504 EltTys.push_back(FieldTy);
508 /// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
509 /// function type is not updated to include implicit "this" pointer. Use this
510 /// routine to get a method type which includes "this" pointer.
512 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
515 = getOrCreateType(QualType(Method->getType()->getAs<FunctionProtoType>(),
519 // Static methods do not need "this" pointer argument.
520 if (Method->isStatic())
523 // Add "this" pointer.
525 llvm::DIArray Args = llvm::DICompositeType(FnTy).getTypeArray();
526 assert (Args.getNumElements() && "Invalid number of arguments!");
528 llvm::SmallVector<llvm::DIDescriptor, 16> Elts;
530 // First element is always return type. For 'void' functions it is NULL.
531 Elts.push_back(Args.getElement(0));
533 // "this" pointer is always first argument.
534 ASTContext &Context = CGM.getContext();
536 Context.getPointerType(Context.getTagDeclType(Method->getParent()));
537 llvm::DIType ThisPtrType =
538 DebugFactory.CreateArtificialType(getOrCreateType(ThisPtr, Unit));
539 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
540 Elts.push_back(ThisPtrType);
542 // Copy rest of the arguments.
543 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
544 Elts.push_back(Args.getElement(i));
546 llvm::DIArray EltTypeArray =
547 DebugFactory.GetOrCreateArray(Elts.data(), Elts.size());
550 DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
553 llvm::DIType(), EltTypeArray);
556 /// CreateCXXMemberFunction - A helper function to create a DISubprogram for
557 /// a single member function GlobalDecl.
559 CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
561 llvm::DICompositeType &RecordTy) {
563 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
565 llvm::StringRef MethodName = getFunctionName(Method);
566 llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit);
568 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
569 // make sense to give a single ctor/dtor a linkage name.
570 MangleBuffer MethodLinkageName;
572 CGM.getMangledName(MethodLinkageName, Method);
574 // Get the location for the method.
575 llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
576 unsigned MethodLine = getLineNumber(Method->getLocation());
578 // Collect virtual method info.
579 llvm::DIType ContainingType;
580 unsigned Virtuality = 0;
583 if (Method->isVirtual()) {
584 if (Method->isPure())
585 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
587 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
589 // It doesn't make sense to give a virtual destructor a vtable index,
590 // since a single destructor has two entries in the vtable.
591 if (!isa<CXXDestructorDecl>(Method))
592 VIndex = CGM.getVTables().getMethodVTableIndex(Method);
593 ContainingType = RecordTy;
596 llvm::DISubprogram SP =
597 DebugFactory.CreateSubprogram(RecordTy , MethodName, MethodName,
599 MethodDefUnit, MethodLine,
600 MethodTy, /*isLocalToUnit=*/false,
601 Method->isThisDeclarationADefinition(),
602 Virtuality, VIndex, ContainingType);
604 // Don't cache ctors or dtors since we have to emit multiple functions for
605 // a single ctor or dtor.
606 if (!IsCtorOrDtor && Method->isThisDeclarationADefinition())
607 SPCache[Method] = llvm::WeakVH(SP);
612 /// CollectCXXMemberFunctions - A helper function to collect debug info for
613 /// C++ member functions.This is used while creating debug info entry for
616 CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
617 llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys,
618 llvm::DICompositeType &RecordTy) {
619 for(CXXRecordDecl::method_iterator I = RD->method_begin(),
620 E = RD->method_end(); I != E; ++I) {
621 const CXXMethodDecl *Method = *I;
623 if (Method->isImplicit() && !Method->isUsed())
626 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
630 /// CollectCXXBases - A helper function to collect debug info for
631 /// C++ base classes. This is used while creating debug info entry for
634 CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
635 llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys,
636 llvm::DICompositeType &RecordTy) {
638 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
639 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
640 BE = RD->bases_end(); BI != BE; ++BI) {
644 const CXXRecordDecl *Base =
645 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
647 if (BI->isVirtual()) {
648 // virtual base offset offset is -ve. The code generator emits dwarf
649 // expression where it expects +ve number.
650 BaseOffset = 0 - CGM.getVTables().getVirtualBaseOffsetOffset(RD, Base);
651 BFlags = llvm::DIType::FlagVirtual;
653 BaseOffset = RL.getBaseClassOffset(Base);
655 AccessSpecifier Access = BI->getAccessSpecifier();
656 if (Access == clang::AS_private)
657 BFlags |= llvm::DIType::FlagPrivate;
658 else if (Access == clang::AS_protected)
659 BFlags |= llvm::DIType::FlagProtected;
662 DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_inheritance,
663 RecordTy, llvm::StringRef(),
666 getOrCreateType(BI->getType(),
668 EltTys.push_back(DTy);
672 /// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
673 llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
674 if (VTablePtrType.isValid())
675 return VTablePtrType;
677 ASTContext &Context = CGM.getContext();
680 llvm::DIDescriptor STy = getOrCreateType(Context.IntTy, Unit);
681 llvm::DIArray SElements = DebugFactory.GetOrCreateArray(&STy, 1);
683 DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
685 0, 0, 0, 0, 0, llvm::DIType(), SElements);
687 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
688 llvm::DIType vtbl_ptr_type
689 = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
690 Unit, "__vtbl_ptr_type", Unit,
691 0, Size, 0, 0, 0, SubTy);
694 DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
696 0, Size, 0, 0, 0, vtbl_ptr_type);
697 return VTablePtrType;
700 /// getVTableName - Get vtable name for the given Class.
701 llvm::StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
702 // Otherwise construct gdb compatible name name.
703 std::string Name = "_vptr$" + RD->getNameAsString();
705 // Copy this name on the side and use its reference.
706 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
707 memcpy(StrPtr, Name.data(), Name.length());
708 return llvm::StringRef(StrPtr, Name.length());
712 /// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
713 /// debug info entry in EltTys vector.
715 CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
716 llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys) {
717 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
719 // If there is a primary base then it will hold vtable info.
720 if (RL.getPrimaryBase())
723 // If this class is not dynamic then there is not any vtable info to collect.
724 if (!RD->isDynamicClass())
727 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
729 = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
730 getVTableName(RD), Unit,
732 getOrCreateVTablePtrType(Unit));
733 EltTys.push_back(VPTR);
736 /// CreateType - get structure or union type.
737 llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty,
739 RecordDecl *RD = Ty->getDecl();
743 Tag = llvm::dwarf::DW_TAG_structure_type;
744 else if (RD->isUnion())
745 Tag = llvm::dwarf::DW_TAG_union_type;
747 assert(RD->isClass() && "Unknown RecordType!");
748 Tag = llvm::dwarf::DW_TAG_class_type;
751 // Get overall information about the record type for the debug info.
752 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
753 unsigned Line = getLineNumber(RD->getLocation());
755 // Records and classes and unions can all be recursive. To handle them, we
756 // first generate a debug descriptor for the struct as a forward declaration.
757 // Then (if it is a definition) we go through and get debug info for all of
758 // its members. Finally, we create a descriptor for the complete type (which
759 // may refer to the forward decl if the struct is recursive) and replace all
760 // uses of the forward declaration with the final definition.
762 // A RD->getName() is not unique. However, the debug info descriptors
763 // are uniqued so use type name to ensure uniquness.
764 llvm::SmallString<128> FwdDeclName;
765 llvm::raw_svector_ostream(FwdDeclName) << "fwd.type." << FwdDeclCount++;
766 llvm::DIDescriptor FDContext =
767 getContextDescriptor(dyn_cast<Decl>(RD->getDeclContext()), Unit);
768 llvm::DICompositeType FwdDecl =
769 DebugFactory.CreateCompositeType(Tag, FDContext, FwdDeclName,
770 DefUnit, Line, 0, 0, 0, 0,
771 llvm::DIType(), llvm::DIArray());
773 // If this is just a forward declaration, return it.
774 if (!RD->getDefinition())
777 llvm::MDNode *MN = FwdDecl;
778 llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN;
779 // Otherwise, insert it into the TypeCache so that recursive uses will find
781 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
782 // Push the struct on region stack.
783 RegionStack.push_back(FwdDeclNode);
784 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
786 // Convert all the elements.
787 llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
789 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
791 CollectCXXBases(CXXDecl, Unit, EltTys, FwdDecl);
792 CollectVTableInfo(CXXDecl, Unit, EltTys);
794 CollectRecordFields(RD, Unit, EltTys);
795 llvm::MDNode *ContainingType = NULL;
797 CollectCXXMemberFunctions(CXXDecl, Unit, EltTys, FwdDecl);
799 // A class's primary base or the class itself contains the vtable.
800 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
801 if (const CXXRecordDecl *PBase = RL.getPrimaryBase())
803 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), Unit);
804 else if (CXXDecl->isDynamicClass())
805 ContainingType = FwdDecl;
808 llvm::DIArray Elements =
809 DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
811 // Bit size, align and offset of the type.
812 uint64_t Size = CGM.getContext().getTypeSize(Ty);
813 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
815 RegionStack.pop_back();
816 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI =
817 RegionMap.find(Ty->getDecl());
818 if (RI != RegionMap.end())
821 llvm::DIDescriptor RDContext =
822 getContextDescriptor(dyn_cast<Decl>(RD->getDeclContext()), Unit);
823 llvm::DICompositeType RealDecl =
824 DebugFactory.CreateCompositeType(Tag, RDContext,
826 DefUnit, Line, Size, Align, 0, 0,
827 llvm::DIType(), Elements,
830 // Now that we have a real decl for the struct, replace anything using the
831 // old decl with the new one. This will recursively update the debug info.
832 llvm::DIDerivedType(FwdDeclNode).replaceAllUsesWith(RealDecl);
833 RegionMap[RD] = llvm::WeakVH(RealDecl);
837 /// CreateType - get objective-c object type.
838 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
841 return getOrCreateType(Ty->getBaseType(), Unit);
844 /// CreateType - get objective-c interface type.
845 llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
847 ObjCInterfaceDecl *ID = Ty->getDecl();
848 unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
850 // Get overall information about the record type for the debug info.
851 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
852 unsigned Line = getLineNumber(ID->getLocation());
853 unsigned RuntimeLang = TheCU.getLanguage();
855 // To handle recursive interface, we
856 // first generate a debug descriptor for the struct as a forward declaration.
857 // Then (if it is a definition) we go through and get debug info for all of
858 // its members. Finally, we create a descriptor for the complete type (which
859 // may refer to the forward decl if the struct is recursive) and replace all
860 // uses of the forward declaration with the final definition.
861 llvm::DICompositeType FwdDecl =
862 DebugFactory.CreateCompositeType(Tag, Unit, ID->getName(),
863 DefUnit, Line, 0, 0, 0, 0,
864 llvm::DIType(), llvm::DIArray(),
867 // If this is just a forward declaration, return it.
868 if (ID->isForwardDecl())
871 llvm::MDNode *MN = FwdDecl;
872 llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN;
873 // Otherwise, insert it into the TypeCache so that recursive uses will find
875 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
876 // Push the struct on region stack.
877 RegionStack.push_back(FwdDeclNode);
878 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
880 // Convert all the elements.
881 llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
883 ObjCInterfaceDecl *SClass = ID->getSuperClass();
885 llvm::DIType SClassTy =
886 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
887 llvm::DIType InhTag =
888 DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_inheritance,
889 Unit, "", Unit, 0, 0, 0,
890 0 /* offset */, 0, SClassTy);
891 EltTys.push_back(InhTag);
894 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
896 unsigned FieldNo = 0;
897 for (ObjCInterfaceDecl::ivar_iterator I = ID->ivar_begin(),
898 E = ID->ivar_end(); I != E; ++I, ++FieldNo) {
899 ObjCIvarDecl *Field = *I;
900 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
902 llvm::StringRef FieldName = Field->getName();
904 // Ignore unnamed fields.
905 if (FieldName.empty())
908 // Get the location for the field.
909 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
910 unsigned FieldLine = getLineNumber(Field->getLocation());
911 QualType FType = Field->getType();
912 uint64_t FieldSize = 0;
913 unsigned FieldAlign = 0;
915 if (!FType->isIncompleteArrayType()) {
917 // Bit size, align and offset of the type.
918 FieldSize = CGM.getContext().getTypeSize(FType);
919 Expr *BitWidth = Field->getBitWidth();
921 FieldSize = BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
923 FieldAlign = CGM.getContext().getTypeAlign(FType);
926 uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
929 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
930 Flags = llvm::DIType::FlagProtected;
931 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
932 Flags = llvm::DIType::FlagPrivate;
934 // Create a DW_TAG_member node to remember the offset of this field in the
935 // struct. FIXME: This is an absolutely insane way to capture this
936 // information. When we gut debug info, this should be fixed.
937 FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
938 FieldName, FieldDefUnit,
939 FieldLine, FieldSize, FieldAlign,
940 FieldOffset, Flags, FieldTy);
941 EltTys.push_back(FieldTy);
944 llvm::DIArray Elements =
945 DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
947 RegionStack.pop_back();
948 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI =
949 RegionMap.find(Ty->getDecl());
950 if (RI != RegionMap.end())
953 // Bit size, align and offset of the type.
954 uint64_t Size = CGM.getContext().getTypeSize(Ty);
955 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
957 llvm::DICompositeType RealDecl =
958 DebugFactory.CreateCompositeType(Tag, Unit, ID->getName(), DefUnit,
959 Line, Size, Align, 0, 0, llvm::DIType(),
960 Elements, RuntimeLang);
962 // Now that we have a real decl for the struct, replace anything using the
963 // old decl with the new one. This will recursively update the debug info.
964 llvm::DIDerivedType(FwdDeclNode).replaceAllUsesWith(RealDecl);
965 RegionMap[ID] = llvm::WeakVH(RealDecl);
970 llvm::DIType CGDebugInfo::CreateType(const EnumType *Ty,
972 EnumDecl *ED = Ty->getDecl();
974 llvm::SmallVector<llvm::DIDescriptor, 32> Enumerators;
976 // Create DIEnumerator elements for each enumerator.
977 for (EnumDecl::enumerator_iterator
978 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
979 Enum != EnumEnd; ++Enum) {
980 Enumerators.push_back(DebugFactory.CreateEnumerator(Enum->getName(),
981 Enum->getInitVal().getZExtValue()));
984 // Return a CompositeType for the enum itself.
985 llvm::DIArray EltArray =
986 DebugFactory.GetOrCreateArray(Enumerators.data(), Enumerators.size());
988 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
989 unsigned Line = getLineNumber(ED->getLocation());
991 // Size and align of the type.
994 if (!Ty->isIncompleteType()) {
995 Size = CGM.getContext().getTypeSize(Ty);
996 Align = CGM.getContext().getTypeAlign(Ty);
1000 DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_enumeration_type,
1001 Unit, ED->getName(), DefUnit, Line,
1003 llvm::DIType(), EltArray);
1007 llvm::DIType CGDebugInfo::CreateType(const TagType *Ty,
1008 llvm::DIFile Unit) {
1009 if (const RecordType *RT = dyn_cast<RecordType>(Ty))
1010 return CreateType(RT, Unit);
1011 else if (const EnumType *ET = dyn_cast<EnumType>(Ty))
1012 return CreateType(ET, Unit);
1014 return llvm::DIType();
1017 llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty,
1018 llvm::DIFile Unit) {
1019 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1020 uint64_t NumElems = Ty->getNumElements();
1024 llvm::DIDescriptor Subscript = DebugFactory.GetOrCreateSubrange(0, NumElems);
1025 llvm::DIArray SubscriptArray = DebugFactory.GetOrCreateArray(&Subscript, 1);
1027 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1028 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1031 DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_vector_type,
1033 0, Size, Align, 0, 0,
1034 ElementTy, SubscriptArray);
1037 llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1038 llvm::DIFile Unit) {
1043 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1044 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1047 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1048 } else if (Ty->isIncompleteArrayType()) {
1050 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1052 // Size and align of the whole array, not the element type.
1053 Size = CGM.getContext().getTypeSize(Ty);
1054 Align = CGM.getContext().getTypeAlign(Ty);
1057 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1058 // interior arrays, do we care? Why aren't nested arrays represented the
1059 // obvious/recursive way?
1060 llvm::SmallVector<llvm::DIDescriptor, 8> Subscripts;
1061 QualType EltTy(Ty, 0);
1062 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1064 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1065 if (CAT->getSize().getZExtValue())
1066 Upper = CAT->getSize().getZExtValue() - 1;
1067 // FIXME: Verify this is right for VLAs.
1068 Subscripts.push_back(DebugFactory.GetOrCreateSubrange(0, Upper));
1069 EltTy = Ty->getElementType();
1072 llvm::DIArray SubscriptArray =
1073 DebugFactory.GetOrCreateArray(Subscripts.data(), Subscripts.size());
1075 llvm::DIType DbgTy =
1076 DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_array_type,
1078 0, Size, Align, 0, 0,
1079 getOrCreateType(EltTy, Unit),
1084 llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1085 llvm::DIFile Unit) {
1086 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1087 Ty, Ty->getPointeeType(), Unit);
1090 llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1092 QualType PointerDiffTy = CGM.getContext().getPointerDiffType();
1093 llvm::DIType PointerDiffDITy = getOrCreateType(PointerDiffTy, U);
1095 if (!Ty->getPointeeType()->isFunctionType()) {
1096 // We have a data member pointer type.
1097 return PointerDiffDITy;
1100 // We have a member function pointer type. Treat it as a struct with two
1101 // ptrdiff_t members.
1102 std::pair<uint64_t, unsigned> Info = CGM.getContext().getTypeInfo(Ty);
1104 uint64_t FieldOffset = 0;
1105 llvm::DIDescriptor ElementTypes[2];
1107 // FIXME: This should probably be a function type instead.
1109 DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, U,
1111 Info.first, Info.second, FieldOffset, 0,
1113 FieldOffset += Info.first;
1116 DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, U,
1118 Info.first, Info.second, FieldOffset, 0,
1121 llvm::DIArray Elements =
1122 DebugFactory.GetOrCreateArray(&ElementTypes[0],
1123 llvm::array_lengthof(ElementTypes));
1125 return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type,
1126 U, llvm::StringRef("test"),
1128 0, 0, 0, llvm::DIType(), Elements);
1131 static QualType UnwrapTypeForDebugInfo(QualType T) {
1134 switch (T->getTypeClass()) {
1137 case Type::TemplateSpecialization:
1138 T = cast<TemplateSpecializationType>(T)->desugar();
1140 case Type::TypeOfExpr: {
1141 TypeOfExprType *Ty = cast<TypeOfExprType>(T);
1142 T = Ty->getUnderlyingExpr()->getType();
1146 T = cast<TypeOfType>(T)->getUnderlyingType();
1148 case Type::Decltype:
1149 T = cast<DecltypeType>(T)->getUnderlyingType();
1151 case Type::Elaborated:
1152 T = cast<ElaboratedType>(T)->getNamedType();
1154 case Type::SubstTemplateTypeParm:
1155 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
1159 assert(T != LastT && "Type unwrapping failed to unwrap!");
1167 /// getOrCreateType - Get the type from the cache or create a new
1168 /// one if necessary.
1169 llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty,
1170 llvm::DIFile Unit) {
1172 return llvm::DIType();
1174 // Unwrap the type as needed for debug information.
1175 Ty = UnwrapTypeForDebugInfo(Ty);
1177 // Check for existing entry.
1178 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1179 TypeCache.find(Ty.getAsOpaquePtr());
1180 if (it != TypeCache.end()) {
1181 // Verify that the debug info still exists.
1183 return llvm::DIType(cast<llvm::MDNode>(it->second));
1186 // Otherwise create the type.
1187 llvm::DIType Res = CreateTypeNode(Ty, Unit);
1189 // And update the type cache.
1190 TypeCache[Ty.getAsOpaquePtr()] = Res;
1194 /// CreateTypeNode - Create a new debug type node.
1195 llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty,
1196 llvm::DIFile Unit) {
1197 // Handle qualifiers, which recursively handles what they refer to.
1198 if (Ty.hasLocalQualifiers())
1199 return CreateQualifiedType(Ty, Unit);
1201 const char *Diag = 0;
1203 // Work out details of type.
1204 switch (Ty->getTypeClass()) {
1205 #define TYPE(Class, Base)
1206 #define ABSTRACT_TYPE(Class, Base)
1207 #define NON_CANONICAL_TYPE(Class, Base)
1208 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1209 #include "clang/AST/TypeNodes.def"
1210 assert(false && "Dependent types cannot show up in debug information");
1212 // FIXME: Handle these.
1213 case Type::ExtVector:
1214 return llvm::DIType();
1217 return CreateType(cast<VectorType>(Ty), Unit);
1218 case Type::ObjCObjectPointer:
1219 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1220 case Type::ObjCObject:
1221 return CreateType(cast<ObjCObjectType>(Ty), Unit);
1222 case Type::ObjCInterface:
1223 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1224 case Type::Builtin: return CreateType(cast<BuiltinType>(Ty), Unit);
1225 case Type::Complex: return CreateType(cast<ComplexType>(Ty), Unit);
1226 case Type::Pointer: return CreateType(cast<PointerType>(Ty), Unit);
1227 case Type::BlockPointer:
1228 return CreateType(cast<BlockPointerType>(Ty), Unit);
1229 case Type::Typedef: return CreateType(cast<TypedefType>(Ty), Unit);
1232 return CreateType(cast<TagType>(Ty), Unit);
1233 case Type::FunctionProto:
1234 case Type::FunctionNoProto:
1235 return CreateType(cast<FunctionType>(Ty), Unit);
1236 case Type::ConstantArray:
1237 case Type::VariableArray:
1238 case Type::IncompleteArray:
1239 return CreateType(cast<ArrayType>(Ty), Unit);
1241 case Type::LValueReference:
1242 return CreateType(cast<LValueReferenceType>(Ty), Unit);
1244 case Type::MemberPointer:
1245 return CreateType(cast<MemberPointerType>(Ty), Unit);
1247 case Type::TemplateSpecialization:
1248 case Type::Elaborated:
1249 case Type::SubstTemplateTypeParm:
1250 case Type::TypeOfExpr:
1252 case Type::Decltype:
1253 llvm_unreachable("type should have been unwrapped!");
1254 return llvm::DIType();
1256 case Type::RValueReference:
1257 // FIXME: Implement!
1258 Diag = "rvalue references";
1262 assert(Diag && "Fall through without a diagnostic?");
1263 unsigned DiagID = CGM.getDiags().getCustomDiagID(Diagnostic::Error,
1264 "debug information for %0 is not yet supported");
1265 CGM.getDiags().Report(FullSourceLoc(), DiagID)
1267 return llvm::DIType();
1270 /// CreateMemberType - Create new member and increase Offset by FType's size.
1271 llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
1272 llvm::StringRef Name,
1274 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1275 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
1276 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
1277 llvm::DIType Ty = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member,
1278 Unit, Name, Unit, 0,
1279 FieldSize, FieldAlign,
1280 *Offset, 0, FieldTy);
1281 *Offset += FieldSize;
1285 /// EmitFunctionStart - Constructs the debug code for entering a function -
1286 /// "llvm.dbg.func.start.".
1287 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
1289 CGBuilderTy &Builder) {
1291 llvm::StringRef Name;
1292 MangleBuffer LinkageName;
1294 const Decl *D = GD.getDecl();
1295 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1296 // If there is a DISubprogram for this function available then use it.
1297 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1298 FI = SPCache.find(FD);
1299 if (FI != SPCache.end()) {
1300 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(FI->second));
1301 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
1302 llvm::MDNode *SPN = SP;
1303 RegionStack.push_back(SPN);
1304 RegionMap[D] = llvm::WeakVH(SP);
1308 Name = getFunctionName(FD);
1309 // Use mangled name as linkage name for c/c++ functions.
1310 CGM.getMangledName(LinkageName, GD);
1312 // Use llvm function name as linkage name.
1313 Name = Fn->getName();
1314 LinkageName.setString(Name);
1316 if (!Name.empty() && Name[0] == '\01')
1317 Name = Name.substr(1);
1319 // It is expected that CurLoc is set before using EmitFunctionStart.
1320 // Usually, CurLoc points to the left bracket location of compound
1321 // statement representing function body.
1322 llvm::DIFile Unit = getOrCreateFile(CurLoc);
1323 unsigned LineNo = getLineNumber(CurLoc);
1325 llvm::DISubprogram SP =
1326 DebugFactory.CreateSubprogram(Unit, Name, Name, LinkageName, Unit, LineNo,
1327 getOrCreateType(FnType, Unit),
1328 Fn->hasInternalLinkage(), true/*definition*/);
1330 // Push function on region stack.
1331 llvm::MDNode *SPN = SP;
1332 RegionStack.push_back(SPN);
1333 RegionMap[D] = llvm::WeakVH(SP);
1337 void CGDebugInfo::EmitStopPoint(llvm::Function *Fn, CGBuilderTy &Builder) {
1338 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
1340 // Don't bother if things are the same as last time.
1341 SourceManager &SM = CGM.getContext().getSourceManager();
1342 if (CurLoc == PrevLoc
1343 || (SM.getInstantiationLineNumber(CurLoc) ==
1344 SM.getInstantiationLineNumber(PrevLoc)
1345 && SM.isFromSameFile(CurLoc, PrevLoc)))
1346 // New Builder may not be in sync with CGDebugInfo.
1347 if (!Builder.getCurrentDebugLocation().isUnknown())
1350 // Update last state.
1353 llvm::MDNode *Scope = RegionStack.back();
1354 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(CurLoc),
1355 getColumnNumber(CurLoc),
1359 /// EmitRegionStart- Constructs the debug code for entering a declarative
1360 /// region - "llvm.dbg.region.start.".
1361 void CGDebugInfo::EmitRegionStart(llvm::Function *Fn, CGBuilderTy &Builder) {
1362 llvm::DIDescriptor D =
1363 DebugFactory.CreateLexicalBlock(RegionStack.empty() ?
1364 llvm::DIDescriptor() :
1365 llvm::DIDescriptor(RegionStack.back()),
1366 getLineNumber(CurLoc),
1367 getColumnNumber(CurLoc));
1368 llvm::MDNode *DN = D;
1369 RegionStack.push_back(DN);
1372 /// EmitRegionEnd - Constructs the debug code for exiting a declarative
1373 /// region - "llvm.dbg.region.end."
1374 void CGDebugInfo::EmitRegionEnd(llvm::Function *Fn, CGBuilderTy &Builder) {
1375 assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1377 // Provide an region stop point.
1378 EmitStopPoint(Fn, Builder);
1380 RegionStack.pop_back();
1383 // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
1384 // See BuildByRefType.
1385 llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const ValueDecl *VD,
1386 uint64_t *XOffset) {
1388 llvm::SmallVector<llvm::DIDescriptor, 5> EltTys;
1391 uint64_t FieldSize, FieldOffset;
1392 unsigned FieldAlign;
1394 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1395 QualType Type = VD->getType();
1398 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1399 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1400 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
1401 FType = CGM.getContext().IntTy;
1402 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1403 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1405 bool HasCopyAndDispose = CGM.BlockRequiresCopying(Type);
1406 if (HasCopyAndDispose) {
1407 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1408 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
1410 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
1414 CharUnits Align = CGM.getContext().getDeclAlign(VD);
1415 if (Align > CharUnits::fromQuantity(
1416 CGM.getContext().Target.getPointerAlign(0) / 8)) {
1417 unsigned AlignedOffsetInBytes
1418 = llvm::RoundUpToAlignment(FieldOffset/8, Align.getQuantity());
1419 unsigned NumPaddingBytes
1420 = AlignedOffsetInBytes - FieldOffset/8;
1422 if (NumPaddingBytes > 0) {
1423 llvm::APInt pad(32, NumPaddingBytes);
1424 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
1425 pad, ArrayType::Normal, 0);
1426 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
1431 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1432 FieldSize = CGM.getContext().getTypeSize(FType);
1433 FieldAlign = Align.getQuantity()*8;
1435 *XOffset = FieldOffset;
1436 FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1437 VD->getName(), Unit,
1438 0, FieldSize, FieldAlign,
1439 FieldOffset, 0, FieldTy);
1440 EltTys.push_back(FieldTy);
1441 FieldOffset += FieldSize;
1443 llvm::DIArray Elements =
1444 DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
1446 unsigned Flags = llvm::DIType::FlagBlockByrefStruct;
1448 return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type,
1450 0, FieldOffset, 0, 0, Flags,
1451 llvm::DIType(), Elements);
1454 /// EmitDeclare - Emit local variable declaration debug info.
1455 void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
1456 llvm::Value *Storage, CGBuilderTy &Builder) {
1457 assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1459 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1461 uint64_t XOffset = 0;
1462 if (VD->hasAttr<BlocksAttr>())
1463 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
1465 Ty = getOrCreateType(VD->getType(), Unit);
1467 // If there is not any debug info for type then do not emit debug info
1468 // for this variable.
1472 // Get location information.
1473 unsigned Line = getLineNumber(VD->getLocation());
1474 unsigned Column = getColumnNumber(VD->getLocation());
1476 // Create the descriptor for the variable.
1477 llvm::DIVariable D =
1478 DebugFactory.CreateVariable(Tag, llvm::DIDescriptor(RegionStack.back()),
1481 // Insert an llvm.dbg.declare into the current block.
1482 llvm::Instruction *Call =
1483 DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock());
1485 llvm::MDNode *Scope = RegionStack.back();
1486 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
1489 /// EmitDeclare - Emit local variable declaration debug info.
1490 void CGDebugInfo::EmitDeclare(const BlockDeclRefExpr *BDRE, unsigned Tag,
1491 llvm::Value *Storage, CGBuilderTy &Builder,
1492 CodeGenFunction *CGF) {
1493 const ValueDecl *VD = BDRE->getDecl();
1494 assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1496 if (Builder.GetInsertBlock() == 0)
1499 uint64_t XOffset = 0;
1500 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1502 if (VD->hasAttr<BlocksAttr>())
1503 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
1505 Ty = getOrCreateType(VD->getType(), Unit);
1507 // Get location information.
1508 unsigned Line = getLineNumber(VD->getLocation());
1509 unsigned Column = getColumnNumber(VD->getLocation());
1511 CharUnits offset = CGF->BlockDecls[VD];
1512 llvm::SmallVector<llvm::Value *, 9> addr;
1513 const llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext());
1514 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1515 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1516 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1517 if (BDRE->isByRef()) {
1518 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1519 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1520 // offset of __forwarding field
1521 offset = CharUnits::fromQuantity(CGF->LLVMPointerWidth/8);
1522 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1523 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1524 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1525 // offset of x field
1526 offset = CharUnits::fromQuantity(XOffset/8);
1527 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1530 // Create the descriptor for the variable.
1531 llvm::DIVariable D =
1532 DebugFactory.CreateComplexVariable(Tag,
1533 llvm::DIDescriptor(RegionStack.back()),
1534 VD->getName(), Unit, Line, Ty,
1536 // Insert an llvm.dbg.declare into the current block.
1537 llvm::Instruction *Call =
1538 DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock());
1540 llvm::MDNode *Scope = RegionStack.back();
1541 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
1544 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
1545 llvm::Value *Storage,
1546 CGBuilderTy &Builder) {
1547 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder);
1550 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
1551 const BlockDeclRefExpr *BDRE, llvm::Value *Storage, CGBuilderTy &Builder,
1552 CodeGenFunction *CGF) {
1553 EmitDeclare(BDRE, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder, CGF);
1556 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
1557 /// variable declaration.
1558 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
1559 CGBuilderTy &Builder) {
1560 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, Builder);
1565 /// EmitGlobalVariable - Emit information about a global variable.
1566 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
1569 // Create global variable debug descriptor.
1570 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
1571 unsigned LineNo = getLineNumber(D->getLocation());
1573 QualType T = D->getType();
1574 if (T->isIncompleteArrayType()) {
1576 // CodeGen turns int[] into int[1] so we'll do the same here.
1577 llvm::APSInt ConstVal(32);
1580 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
1582 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
1583 ArrayType::Normal, 0);
1585 llvm::StringRef DeclName = D->getName();
1586 llvm::StringRef LinkageName;
1587 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext()))
1588 LinkageName = Var->getName();
1589 llvm::DIDescriptor DContext =
1590 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()), Unit);
1591 DebugFactory.CreateGlobalVariable(DContext, DeclName, DeclName, LinkageName,
1592 Unit, LineNo, getOrCreateType(T, Unit),
1593 Var->hasInternalLinkage(),
1594 true/*definition*/, Var);
1597 /// EmitGlobalVariable - Emit information about an objective-c interface.
1598 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
1599 ObjCInterfaceDecl *ID) {
1600 // Create global variable debug descriptor.
1601 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
1602 unsigned LineNo = getLineNumber(ID->getLocation());
1604 llvm::StringRef Name = ID->getName();
1606 QualType T = CGM.getContext().getObjCInterfaceType(ID);
1607 if (T->isIncompleteArrayType()) {
1609 // CodeGen turns int[] into int[1] so we'll do the same here.
1610 llvm::APSInt ConstVal(32);
1613 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
1615 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
1616 ArrayType::Normal, 0);
1619 DebugFactory.CreateGlobalVariable(Unit, Name, Name, Name, Unit, LineNo,
1620 getOrCreateType(T, Unit),
1621 Var->hasInternalLinkage(),
1622 true/*definition*/, Var);
1625 /// getOrCreateNamesSpace - Return namespace descriptor for the given
1628 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl,
1629 llvm::DIDescriptor Unit) {
1630 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
1631 NameSpaceCache.find(NSDecl);
1632 if (I != NameSpaceCache.end())
1633 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
1635 unsigned LineNo = getLineNumber(NSDecl->getLocation());
1637 llvm::DIDescriptor Context =
1638 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()), Unit);
1639 llvm::DINameSpace NS =
1640 DebugFactory.CreateNameSpace(Context, NSDecl->getName(),
1641 llvm::DIFile(Unit), LineNo);
1642 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);