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));
71 /// getFunctionName - Get function name for the given FunctionDecl. If the
72 /// name is constructred on demand (e.g. C++ destructor) then the name
73 /// is stored on the side.
74 llvm::StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
75 assert (FD && "Invalid FunctionDecl!");
76 IdentifierInfo *FII = FD->getIdentifier();
78 return FII->getName();
80 // Otherwise construct human readable name for debug info.
81 std::string NS = FD->getNameAsString();
83 // Copy this name on the side and use its reference.
84 char *StrPtr = DebugInfoNames.Allocate<char>(NS.length());
85 memcpy(StrPtr, NS.data(), NS.length());
86 return llvm::StringRef(StrPtr, NS.length());
89 /// getOrCreateFile - Get the file debug info descriptor for the input location.
90 llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
92 // If Location is not valid then use main input file.
93 return DebugFactory.CreateFile(TheCU.getFilename(), TheCU.getDirectory(),
95 SourceManager &SM = CGM.getContext().getSourceManager();
96 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
97 llvm::sys::Path AbsFileName(PLoc.getFilename());
98 AbsFileName.makeAbsolute();
100 return DebugFactory.CreateFile(AbsFileName.getLast(),
101 AbsFileName.getDirname(), TheCU);
103 /// CreateCompileUnit - Create new compile unit.
104 void CGDebugInfo::CreateCompileUnit() {
106 // Get absolute path name.
107 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
108 if (MainFileName.empty())
109 MainFileName = "<unknown>";
110 llvm::sys::Path AbsFileName(MainFileName);
111 AbsFileName.makeAbsolute();
114 const LangOptions &LO = CGM.getLangOptions();
117 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
119 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
120 } else if (LO.ObjC1) {
121 LangTag = llvm::dwarf::DW_LANG_ObjC;
123 LangTag = llvm::dwarf::DW_LANG_C99;
125 LangTag = llvm::dwarf::DW_LANG_C89;
128 const char *Producer =
132 "clang " CLANG_VERSION_STRING;
134 // Figure out which version of the ObjC runtime we have.
135 unsigned RuntimeVers = 0;
137 RuntimeVers = LO.ObjCNonFragileABI ? 2 : 1;
139 // Create new compile unit.
140 TheCU = DebugFactory.CreateCompileUnit(
141 LangTag, AbsFileName.getLast(), AbsFileName.getDirname(), Producer, true,
142 LO.Optimize, CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers);
145 /// CreateType - Get the Basic type from the cache or create a new
146 /// one if necessary.
147 llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT,
149 unsigned Encoding = 0;
150 switch (BT->getKind()) {
152 case BuiltinType::Void:
153 return llvm::DIType();
154 case BuiltinType::UChar:
155 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
156 case BuiltinType::Char_S:
157 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
158 case BuiltinType::UShort:
159 case BuiltinType::UInt:
160 case BuiltinType::ULong:
161 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
162 case BuiltinType::Short:
163 case BuiltinType::Int:
164 case BuiltinType::Long:
165 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
166 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
167 case BuiltinType::Float:
168 case BuiltinType::LongDouble:
169 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
171 // Bit size, align and offset of the type.
172 uint64_t Size = CGM.getContext().getTypeSize(BT);
173 uint64_t Align = CGM.getContext().getTypeAlign(BT);
177 DebugFactory.CreateBasicType(Unit,
178 BT->getName(CGM.getContext().getLangOptions()),
179 Unit, 0, Size, Align,
180 Offset, /*flags*/ 0, Encoding);
184 llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty,
186 // Bit size, align and offset of the type.
187 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
188 if (Ty->isComplexIntegerType())
189 Encoding = llvm::dwarf::DW_ATE_lo_user;
191 uint64_t Size = CGM.getContext().getTypeSize(Ty);
192 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
196 DebugFactory.CreateBasicType(Unit, "complex",
197 Unit, 0, Size, Align,
198 Offset, /*flags*/ 0, Encoding);
202 /// CreateCVRType - Get the qualified type from the cache or create
203 /// a new one if necessary.
204 llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
205 QualifierCollector Qc;
206 const Type *T = Qc.strip(Ty);
208 // Ignore these qualifiers for now.
209 Qc.removeObjCGCAttr();
210 Qc.removeAddressSpace();
212 // We will create one Derived type for one qualifier and recurse to handle any
216 Tag = llvm::dwarf::DW_TAG_const_type;
218 } else if (Qc.hasVolatile()) {
219 Tag = llvm::dwarf::DW_TAG_volatile_type;
221 } else if (Qc.hasRestrict()) {
222 Tag = llvm::dwarf::DW_TAG_restrict_type;
225 assert(Qc.empty() && "Unknown type qualifier for debug info");
226 return getOrCreateType(QualType(T, 0), Unit);
229 llvm::DIType FromTy = getOrCreateType(Qc.apply(T), Unit);
231 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
232 // CVR derived types.
234 DebugFactory.CreateDerivedType(Tag, Unit, "", Unit,
235 0, 0, 0, 0, 0, FromTy);
239 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
242 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
243 Ty->getPointeeType(), Unit);
247 llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
249 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
250 Ty->getPointeeType(), Unit);
253 llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
257 llvm::DIType EltTy = getOrCreateType(PointeeTy, Unit);
259 // Bit size, align and offset of the type.
261 // Size is always the size of a pointer. We can't use getTypeSize here
262 // because that does not return the correct value for references.
264 CGM.getContext().Target.getPointerWidth(PointeeTy.getAddressSpace());
265 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
268 DebugFactory.CreateDerivedType(Tag, Unit, "", Unit,
269 0, Size, Align, 0, 0, EltTy);
273 llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
275 if (BlockLiteralGenericSet)
276 return BlockLiteralGeneric;
278 unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
280 llvm::SmallVector<llvm::DIDescriptor, 5> EltTys;
282 llvm::DIType FieldTy;
285 uint64_t FieldSize, FieldOffset;
288 llvm::DIArray Elements;
289 llvm::DIType EltTy, DescTy;
292 FType = CGM.getContext().UnsignedLongTy;
293 FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
294 FieldSize = CGM.getContext().getTypeSize(FType);
295 FieldAlign = CGM.getContext().getTypeAlign(FType);
296 FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
298 0, FieldSize, FieldAlign,
299 FieldOffset, 0, FieldTy);
300 EltTys.push_back(FieldTy);
302 FieldOffset += FieldSize;
303 FType = CGM.getContext().UnsignedLongTy;
304 FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
305 FieldSize = CGM.getContext().getTypeSize(FType);
306 FieldAlign = CGM.getContext().getTypeAlign(FType);
307 FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
309 0, FieldSize, FieldAlign,
310 FieldOffset, 0, FieldTy);
311 EltTys.push_back(FieldTy);
313 FieldOffset += FieldSize;
314 Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
317 unsigned Flags = llvm::DIType::FlagAppleBlock;
319 EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_descriptor",
320 Unit, 0, FieldOffset, 0, 0, Flags,
321 llvm::DIType(), Elements);
323 // Bit size, align and offset of the type.
324 uint64_t Size = CGM.getContext().getTypeSize(Ty);
325 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
327 DescTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
329 0, Size, Align, 0, 0, EltTy);
332 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
333 FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
334 FieldSize = CGM.getContext().getTypeSize(FType);
335 FieldAlign = CGM.getContext().getTypeAlign(FType);
336 FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
338 0, FieldSize, FieldAlign,
339 FieldOffset, 0, FieldTy);
340 EltTys.push_back(FieldTy);
342 FieldOffset += FieldSize;
343 FType = CGM.getContext().IntTy;
344 FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
345 FieldSize = CGM.getContext().getTypeSize(FType);
346 FieldAlign = CGM.getContext().getTypeAlign(FType);
347 FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
349 0, FieldSize, FieldAlign,
350 FieldOffset, 0, FieldTy);
351 EltTys.push_back(FieldTy);
353 FieldOffset += FieldSize;
354 FType = CGM.getContext().IntTy;
355 FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
356 FieldSize = CGM.getContext().getTypeSize(FType);
357 FieldAlign = CGM.getContext().getTypeAlign(FType);
358 FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
360 0, FieldSize, FieldAlign,
361 FieldOffset, 0, FieldTy);
362 EltTys.push_back(FieldTy);
364 FieldOffset += FieldSize;
365 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
366 FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
367 FieldSize = CGM.getContext().getTypeSize(FType);
368 FieldAlign = CGM.getContext().getTypeAlign(FType);
369 FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
371 0, FieldSize, FieldAlign,
372 FieldOffset, 0, FieldTy);
373 EltTys.push_back(FieldTy);
375 FieldOffset += FieldSize;
376 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
378 FieldSize = CGM.getContext().getTypeSize(Ty);
379 FieldAlign = CGM.getContext().getTypeAlign(Ty);
380 FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
381 "__descriptor", Unit,
382 0, FieldSize, FieldAlign,
383 FieldOffset, 0, FieldTy);
384 EltTys.push_back(FieldTy);
386 FieldOffset += FieldSize;
387 Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
389 EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_literal_generic",
390 Unit, 0, FieldOffset, 0, 0, Flags,
391 llvm::DIType(), Elements);
393 BlockLiteralGenericSet = true;
395 = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, Unit,
397 0, Size, Align, 0, 0, EltTy);
398 return BlockLiteralGeneric;
401 llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty,
403 // Typedefs are derived from some other type. If we have a typedef of a
404 // typedef, make sure to emit the whole chain.
405 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
407 // We don't set size information, but do specify where the typedef was
409 SourceManager &SM = CGM.getContext().getSourceManager();
410 PresumedLoc PLoc = SM.getPresumedLoc(Ty->getDecl()->getLocation());
411 unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
413 llvm::DIDescriptor TyContext
414 = getContextDescriptor(dyn_cast<Decl>(Ty->getDecl()->getDeclContext()),
417 DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_typedef,
419 Ty->getDecl()->getName(), Unit,
420 Line, 0, 0, 0, 0, Src);
424 llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
426 llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
428 // Add the result type at least.
429 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
431 // Set up remainder of arguments if there is a prototype.
432 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
433 if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(Ty)) {
434 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
435 EltTys.push_back(getOrCreateType(FTP->getArgType(i), Unit));
437 // FIXME: Handle () case in C. llvm-gcc doesn't do it either.
440 llvm::DIArray EltTypeArray =
441 DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
444 DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
447 llvm::DIType(), EltTypeArray);
451 /// CollectRecordFields - A helper function to collect debug info for
452 /// record fields. This is used while creating debug info entry for a Record.
454 CollectRecordFields(const RecordDecl *RD, llvm::DIFile Unit,
455 llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys) {
456 unsigned FieldNo = 0;
457 SourceManager &SM = CGM.getContext().getSourceManager();
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 SourceLocation FieldDefLoc = Field->getLocation();
473 PresumedLoc PLoc = SM.getPresumedLoc(FieldDefLoc);
474 llvm::DIFile FieldDefUnit;
475 unsigned FieldLine = 0;
477 if (!PLoc.isInvalid()) {
478 FieldDefUnit = getOrCreateFile(FieldDefLoc);
479 FieldLine = PLoc.getLine();
482 QualType FType = Field->getType();
483 uint64_t FieldSize = 0;
484 unsigned FieldAlign = 0;
485 if (!FType->isIncompleteArrayType()) {
487 // Bit size, align and offset of the type.
488 FieldSize = CGM.getContext().getTypeSize(FType);
489 Expr *BitWidth = Field->getBitWidth();
491 FieldSize = BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
493 FieldAlign = CGM.getContext().getTypeAlign(FType);
496 uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
498 // Create a DW_TAG_member node to remember the offset of this field in the
499 // struct. FIXME: This is an absolutely insane way to capture this
500 // information. When we gut debug info, this should be fixed.
501 FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
502 FieldName, FieldDefUnit,
503 FieldLine, FieldSize, FieldAlign,
504 FieldOffset, 0, FieldTy);
505 EltTys.push_back(FieldTy);
509 /// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
510 /// function type is not updated to include implicit "this" pointer. Use this
511 /// routine to get a method type which includes "this" pointer.
513 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
515 llvm::DIType FnTy = getOrCreateType(Method->getType(), Unit);
517 // Static methods do not need "this" pointer argument.
518 if (Method->isStatic())
521 // Add "this" pointer.
523 llvm::DIArray Args = llvm::DICompositeType(FnTy.getNode()).getTypeArray();
524 assert (Args.getNumElements() && "Invalid number of arguments!");
526 llvm::SmallVector<llvm::DIDescriptor, 16> Elts;
528 // First element is always return type. For 'void' functions it is NULL.
529 Elts.push_back(Args.getElement(0));
531 // "this" pointer is always first argument.
532 ASTContext &Context = CGM.getContext();
534 Context.getPointerType(Context.getTagDeclType(Method->getParent()));
535 llvm::DIType ThisPtrType =
536 DebugFactory.CreateArtificialType(getOrCreateType(ThisPtr, Unit));
537 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType.getNode();
538 Elts.push_back(ThisPtrType);
540 // Copy rest of the arguments.
541 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
542 Elts.push_back(Args.getElement(i));
544 llvm::DIArray EltTypeArray =
545 DebugFactory.GetOrCreateArray(Elts.data(), Elts.size());
548 DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
551 llvm::DIType(), EltTypeArray);
554 /// CreateCXXMemberFunction - A helper function to create a DISubprogram for
555 /// a single member function GlobalDecl.
557 CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
559 llvm::DICompositeType &RecordTy) {
561 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
563 llvm::StringRef MethodName = getFunctionName(Method);
564 llvm::StringRef MethodLinkageName;
565 llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit);
567 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
568 // make sense to give a single ctor/dtor a linkage name.
570 MethodLinkageName = CGM.getMangledName(Method);
572 SourceManager &SM = CGM.getContext().getSourceManager();
574 // Get the location for the method.
575 SourceLocation MethodDefLoc = Method->getLocation();
576 PresumedLoc PLoc = SM.getPresumedLoc(MethodDefLoc);
577 llvm::DIFile MethodDefUnit;
578 unsigned MethodLine = 0;
580 if (!PLoc.isInvalid()) {
581 MethodDefUnit = getOrCreateFile(MethodDefLoc);
582 MethodLine = PLoc.getLine();
585 // Collect virtual method info.
586 llvm::DIType ContainingType;
587 unsigned Virtuality = 0;
590 if (Method->isVirtual()) {
591 if (Method->isPure())
592 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
594 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
596 // It doesn't make sense to give a virtual destructor a vtable index,
597 // since a single destructor has two entries in the vtable.
598 if (!isa<CXXDestructorDecl>(Method))
599 VIndex = CGM.getVtableInfo().getMethodVtableIndex(Method);
600 ContainingType = RecordTy;
603 llvm::DISubprogram SP =
604 DebugFactory.CreateSubprogram(RecordTy , MethodName, MethodName,
606 MethodDefUnit, MethodLine,
607 MethodTy, /*isLocalToUnit=*/false,
608 Method->isThisDeclarationADefinition(),
609 Virtuality, VIndex, ContainingType);
611 // Don't cache ctors or dtors since we have to emit multiple functions for
612 // a single ctor or dtor.
613 if (!IsCtorOrDtor && Method->isThisDeclarationADefinition())
614 SPCache[Method] = llvm::WeakVH(SP.getNode());
619 /// CollectCXXMemberFunctions - A helper function to collect debug info for
620 /// C++ member functions.This is used while creating debug info entry for
623 CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
624 llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys,
625 llvm::DICompositeType &RecordTy) {
626 for(CXXRecordDecl::method_iterator I = RD->method_begin(),
627 E = RD->method_end(); I != E; ++I) {
628 const CXXMethodDecl *Method = *I;
630 if (Method->isImplicit() && !Method->isUsed())
633 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
637 /// CollectCXXBases - A helper function to collect debug info for
638 /// C++ base classes. This is used while creating debug info entry for
641 CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
642 llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys,
643 llvm::DICompositeType &RecordTy) {
645 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
646 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
647 BE = RD->bases_end(); BI != BE; ++BI) {
651 const CXXRecordDecl *Base =
652 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
654 if (BI->isVirtual()) {
655 // virtual base offset offset is -ve. The code generator emits dwarf
656 // expression where it expects +ve number.
657 BaseOffset = 0 - CGM.getVtableInfo().getVirtualBaseOffsetOffset(RD, Base);
658 BFlags = llvm::DIType::FlagVirtual;
660 BaseOffset = RL.getBaseClassOffset(Base);
662 AccessSpecifier Access = BI->getAccessSpecifier();
663 if (Access == clang::AS_private)
664 BFlags |= llvm::DIType::FlagPrivate;
665 else if (Access == clang::AS_protected)
666 BFlags |= llvm::DIType::FlagProtected;
669 DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_inheritance,
670 RecordTy, llvm::StringRef(),
673 getOrCreateType(BI->getType(),
675 EltTys.push_back(DTy);
679 /// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
680 llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
681 if (VTablePtrType.isValid())
682 return VTablePtrType;
684 ASTContext &Context = CGM.getContext();
687 llvm::SmallVector<llvm::DIDescriptor, 16> STys;
688 STys.push_back(getOrCreateType(Context.IntTy, Unit));
689 llvm::DIArray SElements =
690 DebugFactory.GetOrCreateArray(STys.data(), STys.size());
692 DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
694 0, 0, 0, 0, 0, llvm::DIType(), SElements);
696 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
697 llvm::DIType vtbl_ptr_type
698 = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
699 Unit, "__vtbl_ptr_type", Unit,
700 0, Size, 0, 0, 0, SubTy);
703 DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
705 0, Size, 0, 0, 0, vtbl_ptr_type);
706 return VTablePtrType;
709 /// getVtableName - Get vtable name for the given Class.
710 llvm::StringRef CGDebugInfo::getVtableName(const CXXRecordDecl *RD) {
711 // Otherwise construct gdb compatible name name.
712 std::string Name = "_vptr$" + RD->getNameAsString();
714 // Copy this name on the side and use its reference.
715 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
716 memcpy(StrPtr, Name.data(), Name.length());
717 return llvm::StringRef(StrPtr, Name.length());
721 /// CollectVtableInfo - If the C++ class has vtable info then insert appropriate
722 /// debug info entry in EltTys vector.
724 CollectVtableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
725 llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys) {
726 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
728 // If there is a primary base then it will hold vtable info.
729 if (RL.getPrimaryBase())
732 // If this class is not dynamic then there is not any vtable info to collect.
733 if (!RD->isDynamicClass())
736 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
738 = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
739 getVtableName(RD), Unit,
741 getOrCreateVTablePtrType(Unit));
742 EltTys.push_back(VPTR);
745 /// CreateType - get structure or union type.
746 llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty,
748 RecordDecl *RD = Ty->getDecl();
752 Tag = llvm::dwarf::DW_TAG_structure_type;
753 else if (RD->isUnion())
754 Tag = llvm::dwarf::DW_TAG_union_type;
756 assert(RD->isClass() && "Unknown RecordType!");
757 Tag = llvm::dwarf::DW_TAG_class_type;
760 SourceManager &SM = CGM.getContext().getSourceManager();
762 // Get overall information about the record type for the debug info.
763 PresumedLoc PLoc = SM.getPresumedLoc(RD->getLocation());
764 llvm::DIFile DefUnit;
766 if (!PLoc.isInvalid()) {
767 DefUnit = getOrCreateFile(RD->getLocation());
768 Line = PLoc.getLine();
771 // Records and classes and unions can all be recursive. To handle them, we
772 // first generate a debug descriptor for the struct as a forward declaration.
773 // Then (if it is a definition) we go through and get debug info for all of
774 // its members. Finally, we create a descriptor for the complete type (which
775 // may refer to the forward decl if the struct is recursive) and replace all
776 // uses of the forward declaration with the final definition.
778 // A RD->getName() is not unique. However, the debug info descriptors
779 // are uniqued so use type name to ensure uniquness.
780 llvm::SmallString<128> FwdDeclName;
781 llvm::raw_svector_ostream(FwdDeclName) << "fwd.type." << FwdDeclCount++;
782 llvm::DIDescriptor FDContext =
783 getContextDescriptor(dyn_cast<Decl>(RD->getDeclContext()), Unit);
784 llvm::DICompositeType FwdDecl =
785 DebugFactory.CreateCompositeType(Tag, FDContext, FwdDeclName,
786 DefUnit, Line, 0, 0, 0, 0,
787 llvm::DIType(), llvm::DIArray());
789 // If this is just a forward declaration, return it.
790 if (!RD->getDefinition())
793 llvm::TrackingVH<llvm::MDNode> FwdDeclNode = FwdDecl.getNode();
794 // Otherwise, insert it into the TypeCache so that recursive uses will find
796 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl.getNode();
797 // Push the struct on region stack.
798 RegionStack.push_back(FwdDecl.getNode());
799 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl.getNode());
801 // Convert all the elements.
802 llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
804 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
806 CollectCXXBases(CXXDecl, Unit, EltTys, FwdDecl);
807 CollectVtableInfo(CXXDecl, Unit, EltTys);
809 CollectRecordFields(RD, Unit, EltTys);
810 llvm::MDNode *ContainingType = NULL;
812 CollectCXXMemberFunctions(CXXDecl, Unit, EltTys, FwdDecl);
814 // A class's primary base or the class itself contains the vtable.
815 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
816 if (const CXXRecordDecl *PBase = RL.getPrimaryBase())
818 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), Unit).getNode();
819 else if (CXXDecl->isDynamicClass())
820 ContainingType = FwdDecl.getNode();
823 llvm::DIArray Elements =
824 DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
826 // Bit size, align and offset of the type.
827 uint64_t Size = CGM.getContext().getTypeSize(Ty);
828 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
830 RegionStack.pop_back();
831 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI =
832 RegionMap.find(Ty->getDecl());
833 if (RI != RegionMap.end())
836 llvm::DIDescriptor RDContext =
837 getContextDescriptor(dyn_cast<Decl>(RD->getDeclContext()), Unit);
838 llvm::DICompositeType RealDecl =
839 DebugFactory.CreateCompositeType(Tag, RDContext,
841 DefUnit, Line, Size, Align, 0, 0,
842 llvm::DIType(), Elements,
845 // Now that we have a real decl for the struct, replace anything using the
846 // old decl with the new one. This will recursively update the debug info.
847 llvm::DIDerivedType(FwdDeclNode).replaceAllUsesWith(RealDecl);
848 RegionMap[RD] = llvm::WeakVH(RealDecl.getNode());
852 /// CreateType - get objective-c interface type.
853 llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
855 ObjCInterfaceDecl *ID = Ty->getDecl();
857 unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
858 SourceManager &SM = CGM.getContext().getSourceManager();
860 // Get overall information about the record type for the debug info.
861 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
862 PresumedLoc PLoc = SM.getPresumedLoc(ID->getLocation());
863 unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
866 unsigned RuntimeLang = TheCU.getLanguage();
868 // To handle recursive interface, we
869 // first generate a debug descriptor for the struct as a forward declaration.
870 // Then (if it is a definition) we go through and get debug info for all of
871 // its members. Finally, we create a descriptor for the complete type (which
872 // may refer to the forward decl if the struct is recursive) and replace all
873 // uses of the forward declaration with the final definition.
874 llvm::DICompositeType FwdDecl =
875 DebugFactory.CreateCompositeType(Tag, Unit, ID->getName(),
876 DefUnit, Line, 0, 0, 0, 0,
877 llvm::DIType(), llvm::DIArray(),
880 // If this is just a forward declaration, return it.
881 if (ID->isForwardDecl())
884 llvm::TrackingVH<llvm::MDNode> FwdDeclNode = FwdDecl.getNode();
885 // Otherwise, insert it into the TypeCache so that recursive uses will find
887 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl.getNode();
888 // Push the struct on region stack.
889 RegionStack.push_back(FwdDecl.getNode());
890 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl.getNode());
892 // Convert all the elements.
893 llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
895 ObjCInterfaceDecl *SClass = ID->getSuperClass();
897 llvm::DIType SClassTy =
898 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
899 llvm::DIType InhTag =
900 DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_inheritance,
901 Unit, "", Unit, 0, 0, 0,
902 0 /* offset */, 0, SClassTy);
903 EltTys.push_back(InhTag);
906 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
908 unsigned FieldNo = 0;
909 for (ObjCInterfaceDecl::ivar_iterator I = ID->ivar_begin(),
910 E = ID->ivar_end(); I != E; ++I, ++FieldNo) {
911 ObjCIvarDecl *Field = *I;
912 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
914 llvm::StringRef FieldName = Field->getName();
916 // Ignore unnamed fields.
917 if (FieldName.empty())
920 // Get the location for the field.
921 SourceLocation FieldDefLoc = Field->getLocation();
922 llvm::DIFile FieldDefUnit = getOrCreateFile(FieldDefLoc);
923 PresumedLoc PLoc = SM.getPresumedLoc(FieldDefLoc);
924 unsigned FieldLine = PLoc.isInvalid() ? 0 : PLoc.getLine();
927 QualType FType = Field->getType();
928 uint64_t FieldSize = 0;
929 unsigned FieldAlign = 0;
931 if (!FType->isIncompleteArrayType()) {
933 // Bit size, align and offset of the type.
934 FieldSize = CGM.getContext().getTypeSize(FType);
935 Expr *BitWidth = Field->getBitWidth();
937 FieldSize = BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
939 FieldAlign = CGM.getContext().getTypeAlign(FType);
942 uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
945 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
946 Flags = llvm::DIType::FlagProtected;
947 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
948 Flags = llvm::DIType::FlagPrivate;
950 // Create a DW_TAG_member node to remember the offset of this field in the
951 // struct. FIXME: This is an absolutely insane way to capture this
952 // information. When we gut debug info, this should be fixed.
953 FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
954 FieldName, FieldDefUnit,
955 FieldLine, FieldSize, FieldAlign,
956 FieldOffset, Flags, FieldTy);
957 EltTys.push_back(FieldTy);
960 llvm::DIArray Elements =
961 DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
963 RegionStack.pop_back();
964 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI =
965 RegionMap.find(Ty->getDecl());
966 if (RI != RegionMap.end())
969 // Bit size, align and offset of the type.
970 uint64_t Size = CGM.getContext().getTypeSize(Ty);
971 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
973 llvm::DICompositeType RealDecl =
974 DebugFactory.CreateCompositeType(Tag, Unit, ID->getName(), DefUnit,
975 Line, Size, Align, 0, 0, llvm::DIType(),
976 Elements, RuntimeLang);
978 // Now that we have a real decl for the struct, replace anything using the
979 // old decl with the new one. This will recursively update the debug info.
980 llvm::DIDerivedType(FwdDeclNode).replaceAllUsesWith(RealDecl);
981 RegionMap[ID] = llvm::WeakVH(RealDecl.getNode());
986 llvm::DIType CGDebugInfo::CreateType(const EnumType *Ty,
988 EnumDecl *ED = Ty->getDecl();
990 llvm::SmallVector<llvm::DIDescriptor, 32> Enumerators;
992 // Create DIEnumerator elements for each enumerator.
993 for (EnumDecl::enumerator_iterator
994 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
995 Enum != EnumEnd; ++Enum) {
996 Enumerators.push_back(DebugFactory.CreateEnumerator(Enum->getName(),
997 Enum->getInitVal().getZExtValue()));
1000 // Return a CompositeType for the enum itself.
1001 llvm::DIArray EltArray =
1002 DebugFactory.GetOrCreateArray(Enumerators.data(), Enumerators.size());
1004 SourceLocation DefLoc = ED->getLocation();
1005 llvm::DIFile DefUnit = getOrCreateFile(DefLoc);
1006 SourceManager &SM = CGM.getContext().getSourceManager();
1007 PresumedLoc PLoc = SM.getPresumedLoc(DefLoc);
1008 unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
1011 // Size and align of the type.
1014 if (!Ty->isIncompleteType()) {
1015 Size = CGM.getContext().getTypeSize(Ty);
1016 Align = CGM.getContext().getTypeAlign(Ty);
1019 llvm::DIType DbgTy =
1020 DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_enumeration_type,
1021 Unit, ED->getName(), DefUnit, Line,
1023 llvm::DIType(), EltArray);
1027 llvm::DIType CGDebugInfo::CreateType(const TagType *Ty,
1028 llvm::DIFile Unit) {
1029 if (const RecordType *RT = dyn_cast<RecordType>(Ty))
1030 return CreateType(RT, Unit);
1031 else if (const EnumType *ET = dyn_cast<EnumType>(Ty))
1032 return CreateType(ET, Unit);
1034 return llvm::DIType();
1037 llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty,
1038 llvm::DIFile Unit) {
1039 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1040 uint64_t NumElems = Ty->getNumElements();
1043 llvm::SmallVector<llvm::DIDescriptor, 8> Subscripts;
1044 Subscripts.push_back(DebugFactory.GetOrCreateSubrange(0, NumElems));
1046 llvm::DIArray SubscriptArray =
1047 DebugFactory.GetOrCreateArray(Subscripts.data(), Subscripts.size());
1049 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1050 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1053 DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_vector_type,
1055 0, Size, Align, 0, 0,
1056 ElementTy, SubscriptArray);
1059 llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1060 llvm::DIFile Unit) {
1065 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1066 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1069 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1070 } else if (Ty->isIncompleteArrayType()) {
1072 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1074 // Size and align of the whole array, not the element type.
1075 Size = CGM.getContext().getTypeSize(Ty);
1076 Align = CGM.getContext().getTypeAlign(Ty);
1079 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1080 // interior arrays, do we care? Why aren't nested arrays represented the
1081 // obvious/recursive way?
1082 llvm::SmallVector<llvm::DIDescriptor, 8> Subscripts;
1083 QualType EltTy(Ty, 0);
1084 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1086 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1087 if (CAT->getSize().getZExtValue())
1088 Upper = CAT->getSize().getZExtValue() - 1;
1089 // FIXME: Verify this is right for VLAs.
1090 Subscripts.push_back(DebugFactory.GetOrCreateSubrange(0, Upper));
1091 EltTy = Ty->getElementType();
1094 llvm::DIArray SubscriptArray =
1095 DebugFactory.GetOrCreateArray(Subscripts.data(), Subscripts.size());
1097 llvm::DIType DbgTy =
1098 DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_array_type,
1100 0, Size, Align, 0, 0,
1101 getOrCreateType(EltTy, Unit),
1106 llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1107 llvm::DIFile Unit) {
1108 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1109 Ty, Ty->getPointeeType(), Unit);
1112 llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1114 QualType PointerDiffTy = CGM.getContext().getPointerDiffType();
1115 llvm::DIType PointerDiffDITy = getOrCreateType(PointerDiffTy, U);
1117 if (!Ty->getPointeeType()->isFunctionType()) {
1118 // We have a data member pointer type.
1119 return PointerDiffDITy;
1122 // We have a member function pointer type. Treat it as a struct with two
1123 // ptrdiff_t members.
1124 std::pair<uint64_t, unsigned> Info = CGM.getContext().getTypeInfo(Ty);
1126 uint64_t FieldOffset = 0;
1127 llvm::DIDescriptor ElementTypes[2];
1129 // FIXME: This should probably be a function type instead.
1131 DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, U,
1133 Info.first, Info.second, FieldOffset, 0,
1135 FieldOffset += Info.first;
1138 DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, U,
1140 Info.first, Info.second, FieldOffset, 0,
1143 llvm::DIArray Elements =
1144 DebugFactory.GetOrCreateArray(&ElementTypes[0],
1145 llvm::array_lengthof(ElementTypes));
1147 return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type,
1148 U, llvm::StringRef("test"),
1150 0, 0, 0, llvm::DIType(), Elements);
1153 static QualType UnwrapTypeForDebugInfo(QualType T) {
1156 switch (T->getTypeClass()) {
1159 case Type::TemplateSpecialization:
1160 T = cast<TemplateSpecializationType>(T)->desugar();
1162 case Type::TypeOfExpr: {
1163 TypeOfExprType *Ty = cast<TypeOfExprType>(T);
1164 T = Ty->getUnderlyingExpr()->getType();
1168 T = cast<TypeOfType>(T)->getUnderlyingType();
1170 case Type::Decltype:
1171 T = cast<DecltypeType>(T)->getUnderlyingType();
1173 case Type::QualifiedName:
1174 T = cast<QualifiedNameType>(T)->getNamedType();
1176 case Type::SubstTemplateTypeParm:
1177 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
1179 case Type::Elaborated:
1180 T = cast<ElaboratedType>(T)->getUnderlyingType();
1184 assert(T != LastT && "Type unwrapping failed to unwrap!");
1192 /// getOrCreateType - Get the type from the cache or create a new
1193 /// one if necessary.
1194 llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty,
1195 llvm::DIFile Unit) {
1197 return llvm::DIType();
1199 // Unwrap the type as needed for debug information.
1200 Ty = UnwrapTypeForDebugInfo(Ty);
1202 // Check for existing entry.
1203 std::map<void *, llvm::WeakVH>::iterator it =
1204 TypeCache.find(Ty.getAsOpaquePtr());
1205 if (it != TypeCache.end()) {
1206 // Verify that the debug info still exists.
1208 return llvm::DIType(cast<llvm::MDNode>(it->second));
1211 // Otherwise create the type.
1212 llvm::DIType Res = CreateTypeNode(Ty, Unit);
1214 // And update the type cache.
1215 TypeCache[Ty.getAsOpaquePtr()] = Res.getNode();
1219 /// CreateTypeNode - Create a new debug type node.
1220 llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty,
1221 llvm::DIFile Unit) {
1222 // Handle qualifiers, which recursively handles what they refer to.
1223 if (Ty.hasLocalQualifiers())
1224 return CreateQualifiedType(Ty, Unit);
1226 const char *Diag = 0;
1228 // Work out details of type.
1229 switch (Ty->getTypeClass()) {
1230 #define TYPE(Class, Base)
1231 #define ABSTRACT_TYPE(Class, Base)
1232 #define NON_CANONICAL_TYPE(Class, Base)
1233 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1234 #include "clang/AST/TypeNodes.def"
1235 assert(false && "Dependent types cannot show up in debug information");
1237 // FIXME: Handle these.
1238 case Type::ExtVector:
1239 return llvm::DIType();
1242 return CreateType(cast<VectorType>(Ty), Unit);
1243 case Type::ObjCObjectPointer:
1244 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1245 case Type::ObjCInterface:
1246 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1247 case Type::Builtin: return CreateType(cast<BuiltinType>(Ty), Unit);
1248 case Type::Complex: return CreateType(cast<ComplexType>(Ty), Unit);
1249 case Type::Pointer: return CreateType(cast<PointerType>(Ty), Unit);
1250 case Type::BlockPointer:
1251 return CreateType(cast<BlockPointerType>(Ty), Unit);
1252 case Type::Typedef: return CreateType(cast<TypedefType>(Ty), Unit);
1255 return CreateType(cast<TagType>(Ty), Unit);
1256 case Type::FunctionProto:
1257 case Type::FunctionNoProto:
1258 return CreateType(cast<FunctionType>(Ty), Unit);
1259 case Type::ConstantArray:
1260 case Type::VariableArray:
1261 case Type::IncompleteArray:
1262 return CreateType(cast<ArrayType>(Ty), Unit);
1264 case Type::LValueReference:
1265 return CreateType(cast<LValueReferenceType>(Ty), Unit);
1267 case Type::MemberPointer:
1268 return CreateType(cast<MemberPointerType>(Ty), Unit);
1270 case Type::InjectedClassName:
1271 case Type::TemplateSpecialization:
1272 case Type::Elaborated:
1273 case Type::QualifiedName:
1274 case Type::SubstTemplateTypeParm:
1275 case Type::TypeOfExpr:
1277 case Type::Decltype:
1278 llvm_unreachable("type should have been unwrapped!");
1279 return llvm::DIType();
1281 case Type::RValueReference:
1282 // FIXME: Implement!
1283 Diag = "rvalue references";
1287 assert(Diag && "Fall through without a diagnostic?");
1288 unsigned DiagID = CGM.getDiags().getCustomDiagID(Diagnostic::Error,
1289 "debug information for %0 is not yet supported");
1290 CGM.getDiags().Report(FullSourceLoc(), DiagID)
1292 return llvm::DIType();
1295 /// EmitFunctionStart - Constructs the debug code for entering a function -
1296 /// "llvm.dbg.func.start.".
1297 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
1299 CGBuilderTy &Builder) {
1301 llvm::StringRef Name;
1302 llvm::StringRef LinkageName;
1304 const Decl *D = GD.getDecl();
1305 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1306 // If there is a DISubprogram for this function available then use it.
1307 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1308 FI = SPCache.find(FD);
1309 if (FI != SPCache.end()) {
1310 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(FI->second));
1311 if (SP.isSubprogram() && llvm::DISubprogram(SP.getNode()).isDefinition()) {
1312 RegionStack.push_back(SP.getNode());
1313 RegionMap[D] = llvm::WeakVH(SP.getNode());
1317 Name = getFunctionName(FD);
1318 if (!Name.empty() && Name[0] == '\01')
1319 Name = Name.substr(1);
1320 // Use mangled name as linkage name for c/c++ functions.
1321 LinkageName = CGM.getMangledName(GD);
1323 // Use llvm function name as linkage name.
1324 Name = Fn->getName();
1326 if (!Name.empty() && Name[0] == '\01')
1327 Name = Name.substr(1);
1330 // It is expected that CurLoc is set before using EmitFunctionStart.
1331 // Usually, CurLoc points to the left bracket location of compound
1332 // statement representing function body.
1333 llvm::DIFile Unit = getOrCreateFile(CurLoc);
1334 SourceManager &SM = CGM.getContext().getSourceManager();
1335 unsigned LineNo = SM.getPresumedLoc(CurLoc).getLine();
1337 llvm::DISubprogram SP =
1338 DebugFactory.CreateSubprogram(Unit, Name, Name, LinkageName, Unit, LineNo,
1339 getOrCreateType(FnType, Unit),
1340 Fn->hasInternalLinkage(), true/*definition*/);
1342 // Push function on region stack.
1343 RegionStack.push_back(SP.getNode());
1344 RegionMap[D] = llvm::WeakVH(SP.getNode());
1348 void CGDebugInfo::EmitStopPoint(llvm::Function *Fn, CGBuilderTy &Builder) {
1349 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
1351 // Don't bother if things are the same as last time.
1352 SourceManager &SM = CGM.getContext().getSourceManager();
1353 if (CurLoc == PrevLoc
1354 || (SM.getInstantiationLineNumber(CurLoc) ==
1355 SM.getInstantiationLineNumber(PrevLoc)
1356 && SM.isFromSameFile(CurLoc, PrevLoc)))
1359 // Update last state.
1362 // Get the appropriate compile unit.
1363 llvm::DIFile Unit = getOrCreateFile(CurLoc);
1364 PresumedLoc PLoc = SM.getPresumedLoc(CurLoc);
1366 llvm::DIDescriptor DR(RegionStack.back());
1367 llvm::DIScope DS = llvm::DIScope(DR.getNode());
1368 llvm::DILocation DO(NULL);
1369 llvm::DILocation DL =
1370 DebugFactory.CreateLocation(PLoc.getLine(), PLoc.getColumn(),
1372 Builder.SetCurrentDebugLocation(DL.getNode());
1375 /// EmitRegionStart- Constructs the debug code for entering a declarative
1376 /// region - "llvm.dbg.region.start.".
1377 void CGDebugInfo::EmitRegionStart(llvm::Function *Fn, CGBuilderTy &Builder) {
1378 SourceManager &SM = CGM.getContext().getSourceManager();
1379 PresumedLoc PLoc = SM.getPresumedLoc(CurLoc);
1380 llvm::DIDescriptor D =
1381 DebugFactory.CreateLexicalBlock(RegionStack.empty() ?
1382 llvm::DIDescriptor() :
1383 llvm::DIDescriptor(RegionStack.back()),
1384 PLoc.getLine(), PLoc.getColumn());
1385 RegionStack.push_back(D.getNode());
1388 /// EmitRegionEnd - Constructs the debug code for exiting a declarative
1389 /// region - "llvm.dbg.region.end."
1390 void CGDebugInfo::EmitRegionEnd(llvm::Function *Fn, CGBuilderTy &Builder) {
1391 assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1393 // Provide an region stop point.
1394 EmitStopPoint(Fn, Builder);
1396 RegionStack.pop_back();
1399 // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
1400 // See BuildByRefType.
1401 llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const ValueDecl *VD,
1402 uint64_t *XOffset) {
1404 llvm::SmallVector<llvm::DIDescriptor, 5> EltTys;
1407 uint64_t FieldSize, FieldOffset;
1408 unsigned FieldAlign;
1410 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1411 QualType Type = VD->getType();
1414 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1415 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1416 FieldSize = CGM.getContext().getTypeSize(FType);
1417 FieldAlign = CGM.getContext().getTypeAlign(FType);
1418 FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1420 0, FieldSize, FieldAlign,
1421 FieldOffset, 0, FieldTy);
1422 EltTys.push_back(FieldTy);
1423 FieldOffset += FieldSize;
1425 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1426 FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1427 FieldSize = CGM.getContext().getTypeSize(FType);
1428 FieldAlign = CGM.getContext().getTypeAlign(FType);
1429 FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1430 "__forwarding", Unit,
1431 0, FieldSize, FieldAlign,
1432 FieldOffset, 0, FieldTy);
1433 EltTys.push_back(FieldTy);
1434 FieldOffset += FieldSize;
1436 FType = CGM.getContext().IntTy;
1437 FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1438 FieldSize = CGM.getContext().getTypeSize(FType);
1439 FieldAlign = CGM.getContext().getTypeAlign(FType);
1440 FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1442 0, FieldSize, FieldAlign,
1443 FieldOffset, 0, FieldTy);
1444 EltTys.push_back(FieldTy);
1445 FieldOffset += FieldSize;
1447 FType = CGM.getContext().IntTy;
1448 FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1449 FieldSize = CGM.getContext().getTypeSize(FType);
1450 FieldAlign = CGM.getContext().getTypeAlign(FType);
1451 FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1453 0, FieldSize, FieldAlign,
1454 FieldOffset, 0, FieldTy);
1455 EltTys.push_back(FieldTy);
1456 FieldOffset += FieldSize;
1458 bool HasCopyAndDispose = CGM.BlockRequiresCopying(Type);
1459 if (HasCopyAndDispose) {
1460 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1461 FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1462 FieldSize = CGM.getContext().getTypeSize(FType);
1463 FieldAlign = CGM.getContext().getTypeAlign(FType);
1464 FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1465 "__copy_helper", Unit,
1466 0, FieldSize, FieldAlign,
1467 FieldOffset, 0, FieldTy);
1468 EltTys.push_back(FieldTy);
1469 FieldOffset += FieldSize;
1471 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1472 FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1473 FieldSize = CGM.getContext().getTypeSize(FType);
1474 FieldAlign = CGM.getContext().getTypeAlign(FType);
1475 FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1476 "__destroy_helper", Unit,
1477 0, FieldSize, FieldAlign,
1478 FieldOffset, 0, FieldTy);
1479 EltTys.push_back(FieldTy);
1480 FieldOffset += FieldSize;
1483 CharUnits Align = CGM.getContext().getDeclAlign(VD);
1484 if (Align > CharUnits::fromQuantity(
1485 CGM.getContext().Target.getPointerAlign(0) / 8)) {
1486 unsigned AlignedOffsetInBytes
1487 = llvm::RoundUpToAlignment(FieldOffset/8, Align.getQuantity());
1488 unsigned NumPaddingBytes
1489 = AlignedOffsetInBytes - FieldOffset/8;
1491 if (NumPaddingBytes > 0) {
1492 llvm::APInt pad(32, NumPaddingBytes);
1493 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
1494 pad, ArrayType::Normal, 0);
1495 FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1496 FieldSize = CGM.getContext().getTypeSize(FType);
1497 FieldAlign = CGM.getContext().getTypeAlign(FType);
1498 FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member,
1500 0, FieldSize, FieldAlign,
1501 FieldOffset, 0, FieldTy);
1502 EltTys.push_back(FieldTy);
1503 FieldOffset += FieldSize;
1508 FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1509 FieldSize = CGM.getContext().getTypeSize(FType);
1510 FieldAlign = Align.getQuantity()*8;
1512 *XOffset = FieldOffset;
1513 FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1514 VD->getName(), Unit,
1515 0, FieldSize, FieldAlign,
1516 FieldOffset, 0, FieldTy);
1517 EltTys.push_back(FieldTy);
1518 FieldOffset += FieldSize;
1520 llvm::DIArray Elements =
1521 DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
1523 unsigned Flags = llvm::DIType::FlagBlockByrefStruct;
1525 return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type,
1527 0, FieldOffset, 0, 0, Flags,
1528 llvm::DIType(), Elements);
1531 /// EmitDeclare - Emit local variable declaration debug info.
1532 void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
1533 llvm::Value *Storage, CGBuilderTy &Builder) {
1534 assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1536 // Do not emit variable debug information while generating optimized code.
1537 // The llvm optimizer and code generator are not yet ready to support
1538 // optimized code debugging.
1539 const CodeGenOptions &CGO = CGM.getCodeGenOpts();
1540 if (CGO.OptimizationLevel)
1543 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1545 uint64_t XOffset = 0;
1546 if (VD->hasAttr<BlocksAttr>())
1547 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
1549 Ty = getOrCreateType(VD->getType(), Unit);
1551 // Get location information.
1552 SourceManager &SM = CGM.getContext().getSourceManager();
1553 PresumedLoc PLoc = SM.getPresumedLoc(VD->getLocation());
1555 unsigned Column = 0;
1556 if (PLoc.isInvalid())
1557 PLoc = SM.getPresumedLoc(CurLoc);
1558 if (PLoc.isValid()) {
1559 Line = PLoc.getLine();
1560 Column = PLoc.getColumn();
1561 Unit = getOrCreateFile(CurLoc);
1563 Unit = llvm::DIFile();
1566 // Create the descriptor for the variable.
1567 llvm::DIVariable D =
1568 DebugFactory.CreateVariable(Tag, llvm::DIDescriptor(RegionStack.back()),
1571 // Insert an llvm.dbg.declare into the current block.
1572 llvm::Instruction *Call =
1573 DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock());
1575 llvm::DIScope DS(RegionStack.back());
1576 llvm::DILocation DO(NULL);
1577 llvm::DILocation DL = DebugFactory.CreateLocation(Line, Column, DS, DO);
1579 Call->setMetadata("dbg", DL.getNode());
1582 /// EmitDeclare - Emit local variable declaration debug info.
1583 void CGDebugInfo::EmitDeclare(const BlockDeclRefExpr *BDRE, unsigned Tag,
1584 llvm::Value *Storage, CGBuilderTy &Builder,
1585 CodeGenFunction *CGF) {
1586 const ValueDecl *VD = BDRE->getDecl();
1587 assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1589 // Do not emit variable debug information while generating optimized code.
1590 // The llvm optimizer and code generator are not yet ready to support
1591 // optimized code debugging.
1592 const CodeGenOptions &CGO = CGM.getCodeGenOpts();
1593 if (CGO.OptimizationLevel || Builder.GetInsertBlock() == 0)
1596 uint64_t XOffset = 0;
1597 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1599 if (VD->hasAttr<BlocksAttr>())
1600 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
1602 Ty = getOrCreateType(VD->getType(), Unit);
1604 // Get location information.
1605 SourceManager &SM = CGM.getContext().getSourceManager();
1606 PresumedLoc PLoc = SM.getPresumedLoc(VD->getLocation());
1608 if (!PLoc.isInvalid())
1609 Line = PLoc.getLine();
1611 Unit = llvm::DIFile();
1613 CharUnits offset = CGF->BlockDecls[VD];
1614 llvm::SmallVector<llvm::Value *, 9> addr;
1615 const llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext());
1616 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1617 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1618 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1619 if (BDRE->isByRef()) {
1620 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1621 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1622 // offset of __forwarding field
1623 offset = CharUnits::fromQuantity(CGF->LLVMPointerWidth/8);
1624 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1625 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1626 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1627 // offset of x field
1628 offset = CharUnits::fromQuantity(XOffset/8);
1629 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1632 // Create the descriptor for the variable.
1633 llvm::DIVariable D =
1634 DebugFactory.CreateComplexVariable(Tag,
1635 llvm::DIDescriptor(RegionStack.back()),
1636 VD->getName(), Unit, Line, Ty,
1638 // Insert an llvm.dbg.declare into the current block.
1639 llvm::Instruction *Call =
1640 DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock());
1642 llvm::DIScope DS(RegionStack.back());
1643 llvm::DILocation DO(NULL);
1644 llvm::DILocation DL =
1645 DebugFactory.CreateLocation(Line, PLoc.getColumn(), DS, DO);
1647 Call->setMetadata("dbg", DL.getNode());
1650 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
1651 llvm::Value *Storage,
1652 CGBuilderTy &Builder) {
1653 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder);
1656 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
1657 const BlockDeclRefExpr *BDRE, llvm::Value *Storage, CGBuilderTy &Builder,
1658 CodeGenFunction *CGF) {
1659 EmitDeclare(BDRE, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder, CGF);
1662 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
1663 /// variable declaration.
1664 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
1665 CGBuilderTy &Builder) {
1666 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, Builder);
1671 /// EmitGlobalVariable - Emit information about a global variable.
1672 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
1675 // Create global variable debug descriptor.
1676 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
1677 SourceManager &SM = CGM.getContext().getSourceManager();
1678 PresumedLoc PLoc = SM.getPresumedLoc(D->getLocation());
1679 unsigned LineNo = PLoc.isInvalid() ? 0 : PLoc.getLine();
1681 QualType T = D->getType();
1682 if (T->isIncompleteArrayType()) {
1684 // CodeGen turns int[] into int[1] so we'll do the same here.
1685 llvm::APSInt ConstVal(32);
1688 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
1690 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
1691 ArrayType::Normal, 0);
1693 llvm::StringRef DeclName = Var->getName();
1694 llvm::DIDescriptor DContext =
1695 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()), Unit);
1696 DebugFactory.CreateGlobalVariable(DContext, DeclName,
1697 DeclName, llvm::StringRef(), Unit, LineNo,
1698 getOrCreateType(T, Unit),
1699 Var->hasInternalLinkage(),
1700 true/*definition*/, Var);
1703 /// EmitGlobalVariable - Emit information about an objective-c interface.
1704 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
1705 ObjCInterfaceDecl *ID) {
1706 // Create global variable debug descriptor.
1707 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
1708 SourceManager &SM = CGM.getContext().getSourceManager();
1709 PresumedLoc PLoc = SM.getPresumedLoc(ID->getLocation());
1710 unsigned LineNo = PLoc.isInvalid() ? 0 : PLoc.getLine();
1712 llvm::StringRef Name = ID->getName();
1714 QualType T = CGM.getContext().getObjCInterfaceType(ID);
1715 if (T->isIncompleteArrayType()) {
1717 // CodeGen turns int[] into int[1] so we'll do the same here.
1718 llvm::APSInt ConstVal(32);
1721 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
1723 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
1724 ArrayType::Normal, 0);
1727 DebugFactory.CreateGlobalVariable(Unit, Name, Name, Name, Unit, LineNo,
1728 getOrCreateType(T, Unit),
1729 Var->hasInternalLinkage(),
1730 true/*definition*/, Var);
1733 /// getOrCreateNamesSpace - Return namespace descriptor for the given
1736 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl,
1737 llvm::DIDescriptor Unit) {
1738 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
1739 NameSpaceCache.find(NSDecl);
1740 if (I != NameSpaceCache.end())
1741 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
1743 SourceManager &SM = CGM.getContext().getSourceManager();
1744 PresumedLoc PLoc = SM.getPresumedLoc(NSDecl->getLocation());
1745 unsigned LineNo = PLoc.isInvalid() ? 0 : PLoc.getLine();
1747 llvm::DIDescriptor Context =
1748 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()), Unit);
1749 llvm::DINameSpace NS =
1750 DebugFactory.CreateNameSpace(Context, NSDecl->getName(),
1751 llvm::DIFile(Unit.getNode()), LineNo);
1752 NameSpaceCache[NSDecl] = llvm::WeakVH(NS.getNode());