1 //===--- DebugInfo.cpp - Debug Information Helper Classes -----------------===//
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 file implements the helper classes used to build and interpret debug
11 // information in LLVM IR form.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Analysis/DebugInfo.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Intrinsics.h"
19 #include "llvm/IntrinsicInst.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/Dwarf.h"
28 #include "llvm/Support/raw_ostream.h"
30 using namespace llvm::dwarf;
32 //===----------------------------------------------------------------------===//
34 //===----------------------------------------------------------------------===//
36 DIDescriptor::DIDescriptor(const DIFile F) : DbgNode(F.DbgNode) {
39 DIDescriptor::DIDescriptor(const DISubprogram F) : DbgNode(F.DbgNode) {
42 DIDescriptor::DIDescriptor(const DILexicalBlock F) : DbgNode(F.DbgNode) {
45 DIDescriptor::DIDescriptor(const DIVariable F) : DbgNode(F.DbgNode) {
48 DIDescriptor::DIDescriptor(const DIType F) : DbgNode(F.DbgNode) {
52 DIDescriptor::getStringField(unsigned Elt) const {
56 if (Elt < DbgNode->getNumOperands())
57 if (MDString *MDS = dyn_cast_or_null<MDString>(DbgNode->getOperand(Elt)))
58 return MDS->getString();
63 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
67 if (Elt < DbgNode->getNumOperands())
68 if (ConstantInt *CI = dyn_cast<ConstantInt>(DbgNode->getOperand(Elt)))
69 return CI->getZExtValue();
74 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
76 return DIDescriptor();
78 if (Elt < DbgNode->getNumOperands())
80 DIDescriptor(dyn_cast_or_null<const MDNode>(DbgNode->getOperand(Elt)));
81 return DIDescriptor();
84 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
88 if (Elt < DbgNode->getNumOperands())
89 return dyn_cast_or_null<GlobalVariable>(DbgNode->getOperand(Elt));
93 Constant *DIDescriptor::getConstantField(unsigned Elt) const {
97 if (Elt < DbgNode->getNumOperands())
98 return dyn_cast_or_null<Constant>(DbgNode->getOperand(Elt));
102 Function *DIDescriptor::getFunctionField(unsigned Elt) const {
106 if (Elt < DbgNode->getNumOperands())
107 return dyn_cast_or_null<Function>(DbgNode->getOperand(Elt));
111 unsigned DIVariable::getNumAddrElements() const {
112 return DbgNode->getNumOperands()-6;
116 //===----------------------------------------------------------------------===//
118 //===----------------------------------------------------------------------===//
120 /// isBasicType - Return true if the specified tag is legal for
122 bool DIDescriptor::isBasicType() const {
123 return DbgNode && getTag() == dwarf::DW_TAG_base_type;
126 /// isDerivedType - Return true if the specified tag is legal for DIDerivedType.
127 bool DIDescriptor::isDerivedType() const {
128 if (!DbgNode) return false;
130 case dwarf::DW_TAG_typedef:
131 case dwarf::DW_TAG_pointer_type:
132 case dwarf::DW_TAG_reference_type:
133 case dwarf::DW_TAG_const_type:
134 case dwarf::DW_TAG_volatile_type:
135 case dwarf::DW_TAG_restrict_type:
136 case dwarf::DW_TAG_member:
137 case dwarf::DW_TAG_inheritance:
138 case dwarf::DW_TAG_friend:
141 // CompositeTypes are currently modelled as DerivedTypes.
142 return isCompositeType();
146 /// isCompositeType - Return true if the specified tag is legal for
148 bool DIDescriptor::isCompositeType() const {
149 if (!DbgNode) return false;
151 case dwarf::DW_TAG_array_type:
152 case dwarf::DW_TAG_structure_type:
153 case dwarf::DW_TAG_union_type:
154 case dwarf::DW_TAG_enumeration_type:
155 case dwarf::DW_TAG_vector_type:
156 case dwarf::DW_TAG_subroutine_type:
157 case dwarf::DW_TAG_class_type:
164 /// isVariable - Return true if the specified tag is legal for DIVariable.
165 bool DIDescriptor::isVariable() const {
166 if (!DbgNode) return false;
168 case dwarf::DW_TAG_auto_variable:
169 case dwarf::DW_TAG_arg_variable:
170 case dwarf::DW_TAG_return_variable:
177 /// isType - Return true if the specified tag is legal for DIType.
178 bool DIDescriptor::isType() const {
179 return isBasicType() || isCompositeType() || isDerivedType();
182 /// isSubprogram - Return true if the specified tag is legal for
184 bool DIDescriptor::isSubprogram() const {
185 return DbgNode && getTag() == dwarf::DW_TAG_subprogram;
188 /// isGlobalVariable - Return true if the specified tag is legal for
189 /// DIGlobalVariable.
190 bool DIDescriptor::isGlobalVariable() const {
191 return DbgNode && (getTag() == dwarf::DW_TAG_variable ||
192 getTag() == dwarf::DW_TAG_constant);
195 /// isGlobal - Return true if the specified tag is legal for DIGlobal.
196 bool DIDescriptor::isGlobal() const {
197 return isGlobalVariable();
200 /// isScope - Return true if the specified tag is one of the scope
202 bool DIDescriptor::isScope() const {
203 if (!DbgNode) return false;
205 case dwarf::DW_TAG_compile_unit:
206 case dwarf::DW_TAG_lexical_block:
207 case dwarf::DW_TAG_subprogram:
208 case dwarf::DW_TAG_namespace:
216 /// isCompileUnit - Return true if the specified tag is DW_TAG_compile_unit.
217 bool DIDescriptor::isCompileUnit() const {
218 return DbgNode && getTag() == dwarf::DW_TAG_compile_unit;
221 /// isFile - Return true if the specified tag is DW_TAG_file_type.
222 bool DIDescriptor::isFile() const {
223 return DbgNode && getTag() == dwarf::DW_TAG_file_type;
226 /// isNameSpace - Return true if the specified tag is DW_TAG_namespace.
227 bool DIDescriptor::isNameSpace() const {
228 return DbgNode && getTag() == dwarf::DW_TAG_namespace;
231 /// isLexicalBlock - Return true if the specified tag is DW_TAG_lexical_block.
232 bool DIDescriptor::isLexicalBlock() const {
233 return DbgNode && getTag() == dwarf::DW_TAG_lexical_block;
236 /// isSubrange - Return true if the specified tag is DW_TAG_subrange_type.
237 bool DIDescriptor::isSubrange() const {
238 return DbgNode && getTag() == dwarf::DW_TAG_subrange_type;
241 /// isEnumerator - Return true if the specified tag is DW_TAG_enumerator.
242 bool DIDescriptor::isEnumerator() const {
243 return DbgNode && getTag() == dwarf::DW_TAG_enumerator;
246 //===----------------------------------------------------------------------===//
247 // Simple Descriptor Constructors and other Methods
248 //===----------------------------------------------------------------------===//
250 DIType::DIType(const MDNode *N) : DIScope(N) {
252 if (!isBasicType() && !isDerivedType() && !isCompositeType()) {
257 unsigned DIArray::getNumElements() const {
260 return DbgNode->getNumOperands();
263 /// replaceAllUsesWith - Replace all uses of debug info referenced by
265 void DIType::replaceAllUsesWith(DIDescriptor &D) {
269 // Since we use a TrackingVH for the node, its easy for clients to manufacture
270 // legitimate situations where they want to replaceAllUsesWith() on something
271 // which, due to uniquing, has merged with the source. We shield clients from
272 // this detail by allowing a value to be replaced with replaceAllUsesWith()
275 MDNode *Node = const_cast<MDNode*>(DbgNode);
276 const MDNode *DN = D;
277 const Value *V = cast_or_null<Value>(DN);
278 Node->replaceAllUsesWith(const_cast<Value*>(V));
279 MDNode::deleteTemporary(Node);
283 /// Verify - Verify that a compile unit is well formed.
284 bool DICompileUnit::Verify() const {
287 StringRef N = getFilename();
290 // It is possible that directory and produce string is empty.
294 /// Verify - Verify that a type descriptor is well formed.
295 bool DIType::Verify() const {
298 if (!getContext().Verify())
301 DICompileUnit CU = getCompileUnit();
307 /// Verify - Verify that a basic type descriptor is well formed.
308 bool DIBasicType::Verify() const {
309 return isBasicType();
312 /// Verify - Verify that a derived type descriptor is well formed.
313 bool DIDerivedType::Verify() const {
314 return isDerivedType();
317 /// Verify - Verify that a composite type descriptor is well formed.
318 bool DICompositeType::Verify() const {
321 if (!getContext().Verify())
324 DICompileUnit CU = getCompileUnit();
330 /// Verify - Verify that a subprogram descriptor is well formed.
331 bool DISubprogram::Verify() const {
335 if (!getContext().Verify())
338 DICompileUnit CU = getCompileUnit();
342 DICompositeType Ty = getType();
348 /// Verify - Verify that a global variable descriptor is well formed.
349 bool DIGlobalVariable::Verify() const {
353 if (getDisplayName().empty())
356 if (!getContext().Verify())
359 DICompileUnit CU = getCompileUnit();
363 DIType Ty = getType();
367 if (!getGlobal() && !getConstant())
373 /// Verify - Verify that a variable descriptor is well formed.
374 bool DIVariable::Verify() const {
378 if (!getContext().Verify())
381 if (!getCompileUnit().Verify())
384 DIType Ty = getType();
391 /// Verify - Verify that a location descriptor is well formed.
392 bool DILocation::Verify() const {
396 return DbgNode->getNumOperands() == 4;
399 /// Verify - Verify that a namespace descriptor is well formed.
400 bool DINameSpace::Verify() const {
403 if (getName().empty())
405 if (!getCompileUnit().Verify())
410 /// getOriginalTypeSize - If this type is derived from a base type then
411 /// return base type size.
412 uint64_t DIDerivedType::getOriginalTypeSize() const {
413 unsigned Tag = getTag();
414 if (Tag == dwarf::DW_TAG_member || Tag == dwarf::DW_TAG_typedef ||
415 Tag == dwarf::DW_TAG_const_type || Tag == dwarf::DW_TAG_volatile_type ||
416 Tag == dwarf::DW_TAG_restrict_type) {
417 DIType BaseType = getTypeDerivedFrom();
418 // If this type is not derived from any type then take conservative
420 if (!BaseType.isValid())
421 return getSizeInBits();
422 if (BaseType.isDerivedType())
423 return DIDerivedType(BaseType).getOriginalTypeSize();
425 return BaseType.getSizeInBits();
428 return getSizeInBits();
431 /// isInlinedFnArgument - Return true if this variable provides debugging
432 /// information for an inlined function arguments.
433 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
434 assert(CurFn && "Invalid function");
435 if (!getContext().isSubprogram())
437 // This variable is not inlined function argument if its scope
438 // does not describe current function.
439 return !(DISubprogram(getContext()).describes(CurFn));
442 /// describes - Return true if this subprogram provides debugging
443 /// information for the function F.
444 bool DISubprogram::describes(const Function *F) {
445 assert(F && "Invalid function");
446 if (F == getFunction())
448 StringRef Name = getLinkageName();
451 if (F->getName() == Name)
456 unsigned DISubprogram::isOptimized() const {
457 assert (DbgNode && "Invalid subprogram descriptor!");
458 if (DbgNode->getNumOperands() == 16)
459 return getUnsignedField(15);
463 StringRef DIScope::getFilename() const {
466 if (isLexicalBlock())
467 return DILexicalBlock(DbgNode).getFilename();
469 return DISubprogram(DbgNode).getFilename();
471 return DICompileUnit(DbgNode).getFilename();
473 return DINameSpace(DbgNode).getFilename();
475 return DIType(DbgNode).getFilename();
477 return DIFile(DbgNode).getFilename();
478 assert(0 && "Invalid DIScope!");
482 StringRef DIScope::getDirectory() const {
485 if (isLexicalBlock())
486 return DILexicalBlock(DbgNode).getDirectory();
488 return DISubprogram(DbgNode).getDirectory();
490 return DICompileUnit(DbgNode).getDirectory();
492 return DINameSpace(DbgNode).getDirectory();
494 return DIType(DbgNode).getDirectory();
496 return DIFile(DbgNode).getDirectory();
497 assert(0 && "Invalid DIScope!");
501 //===----------------------------------------------------------------------===//
502 // DIDescriptor: dump routines for all descriptors.
503 //===----------------------------------------------------------------------===//
506 /// print - Print descriptor.
507 void DIDescriptor::print(raw_ostream &OS) const {
508 OS << "[" << dwarf::TagString(getTag()) << "] ";
509 OS.write_hex((intptr_t) &*DbgNode) << ']';
512 /// print - Print compile unit.
513 void DICompileUnit::print(raw_ostream &OS) const {
515 OS << " [" << dwarf::LanguageString(getLanguage()) << "] ";
517 OS << " [" << getDirectory() << "/" << getFilename() << "]";
520 /// print - Print type.
521 void DIType::print(raw_ostream &OS) const {
522 if (!DbgNode) return;
524 StringRef Res = getName();
526 OS << " [" << Res << "] ";
528 unsigned Tag = getTag();
529 OS << " [" << dwarf::TagString(Tag) << "] ";
531 // TODO : Print context
532 getCompileUnit().print(OS);
534 << "line " << getLineNumber() << ", "
535 << getSizeInBits() << " bits, "
536 << getAlignInBits() << " bit alignment, "
537 << getOffsetInBits() << " bit offset"
542 else if (isProtected())
543 OS << " [protected] ";
549 DIBasicType(DbgNode).print(OS);
550 else if (isDerivedType())
551 DIDerivedType(DbgNode).print(OS);
552 else if (isCompositeType())
553 DICompositeType(DbgNode).print(OS);
555 OS << "Invalid DIType\n";
562 /// print - Print basic type.
563 void DIBasicType::print(raw_ostream &OS) const {
564 OS << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
567 /// print - Print derived type.
568 void DIDerivedType::print(raw_ostream &OS) const {
569 OS << "\n\t Derived From: "; getTypeDerivedFrom().print(OS);
572 /// print - Print composite type.
573 void DICompositeType::print(raw_ostream &OS) const {
574 DIArray A = getTypeArray();
575 OS << " [" << A.getNumElements() << " elements]";
578 /// print - Print subprogram.
579 void DISubprogram::print(raw_ostream &OS) const {
580 StringRef Res = getName();
582 OS << " [" << Res << "] ";
584 unsigned Tag = getTag();
585 OS << " [" << dwarf::TagString(Tag) << "] ";
587 // TODO : Print context
588 getCompileUnit().print(OS);
589 OS << " [" << getLineNumber() << "] ";
600 /// print - Print global variable.
601 void DIGlobalVariable::print(raw_ostream &OS) const {
603 StringRef Res = getName();
605 OS << " [" << Res << "] ";
607 unsigned Tag = getTag();
608 OS << " [" << dwarf::TagString(Tag) << "] ";
610 // TODO : Print context
611 getCompileUnit().print(OS);
612 OS << " [" << getLineNumber() << "] ";
620 if (isGlobalVariable())
621 DIGlobalVariable(DbgNode).print(OS);
625 /// print - Print variable.
626 void DIVariable::print(raw_ostream &OS) const {
627 StringRef Res = getName();
629 OS << " [" << Res << "] ";
631 getCompileUnit().print(OS);
632 OS << " [" << getLineNumber() << "] ";
636 // FIXME: Dump complex addresses
639 /// dump - Print descriptor to dbgs() with a newline.
640 void DIDescriptor::dump() const {
641 print(dbgs()); dbgs() << '\n';
644 /// dump - Print compile unit to dbgs() with a newline.
645 void DICompileUnit::dump() const {
646 print(dbgs()); dbgs() << '\n';
649 /// dump - Print type to dbgs() with a newline.
650 void DIType::dump() const {
651 print(dbgs()); dbgs() << '\n';
654 /// dump - Print basic type to dbgs() with a newline.
655 void DIBasicType::dump() const {
656 print(dbgs()); dbgs() << '\n';
659 /// dump - Print derived type to dbgs() with a newline.
660 void DIDerivedType::dump() const {
661 print(dbgs()); dbgs() << '\n';
664 /// dump - Print composite type to dbgs() with a newline.
665 void DICompositeType::dump() const {
666 print(dbgs()); dbgs() << '\n';
669 /// dump - Print subprogram to dbgs() with a newline.
670 void DISubprogram::dump() const {
671 print(dbgs()); dbgs() << '\n';
674 /// dump - Print global variable.
675 void DIGlobalVariable::dump() const {
676 print(dbgs()); dbgs() << '\n';
679 /// dump - Print variable.
680 void DIVariable::dump() const {
681 print(dbgs()); dbgs() << '\n';
684 //===----------------------------------------------------------------------===//
685 // DIFactory: Basic Helpers
686 //===----------------------------------------------------------------------===//
688 DIFactory::DIFactory(Module &m)
689 : M(m), VMContext(M.getContext()), DeclareFn(0), ValueFn(0) {}
691 Constant *DIFactory::GetTagConstant(unsigned TAG) {
692 assert((TAG & LLVMDebugVersionMask) == 0 &&
693 "Tag too large for debug encoding!");
694 return ConstantInt::get(Type::getInt32Ty(VMContext), TAG | LLVMDebugVersion);
697 //===----------------------------------------------------------------------===//
698 // DIFactory: Primary Constructors
699 //===----------------------------------------------------------------------===//
701 /// GetOrCreateArray - Create an descriptor for an array of descriptors.
702 /// This implicitly uniques the arrays created.
703 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
704 SmallVector<Value*, 16> Elts;
707 Elts.push_back(llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)));
709 for (unsigned i = 0; i != NumTys; ++i)
710 Elts.push_back(Tys[i]);
712 return DIArray(MDNode::get(VMContext,Elts.data(), Elts.size()));
715 /// GetOrCreateSubrange - Create a descriptor for a value range. This
716 /// implicitly uniques the values returned.
717 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
719 GetTagConstant(dwarf::DW_TAG_subrange_type),
720 ConstantInt::get(Type::getInt64Ty(VMContext), Lo),
721 ConstantInt::get(Type::getInt64Ty(VMContext), Hi)
724 return DISubrange(MDNode::get(VMContext, &Elts[0], 3));
729 /// CreateCompileUnit - Create a new descriptor for the specified compile
730 /// unit. Note that this does not unique compile units within the module.
731 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
738 unsigned RunTimeVer) {
740 GetTagConstant(dwarf::DW_TAG_compile_unit),
741 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
742 ConstantInt::get(Type::getInt32Ty(VMContext), LangID),
743 MDString::get(VMContext, Filename),
744 MDString::get(VMContext, Directory),
745 MDString::get(VMContext, Producer),
746 ConstantInt::get(Type::getInt1Ty(VMContext), isMain),
747 ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
748 MDString::get(VMContext, Flags),
749 ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeVer)
752 return DICompileUnit(MDNode::get(VMContext, &Elts[0], 10));
755 /// CreateFile - Create a new descriptor for the specified file.
756 DIFile DIFactory::CreateFile(StringRef Filename,
760 GetTagConstant(dwarf::DW_TAG_file_type),
761 MDString::get(VMContext, Filename),
762 MDString::get(VMContext, Directory),
766 return DIFile(MDNode::get(VMContext, &Elts[0], 4));
769 /// CreateEnumerator - Create a single enumerator value.
770 DIEnumerator DIFactory::CreateEnumerator(StringRef Name, uint64_t Val){
772 GetTagConstant(dwarf::DW_TAG_enumerator),
773 MDString::get(VMContext, Name),
774 ConstantInt::get(Type::getInt64Ty(VMContext), Val)
776 return DIEnumerator(MDNode::get(VMContext, &Elts[0], 3));
780 /// CreateBasicType - Create a basic type like int, float, etc.
781 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
786 uint64_t AlignInBits,
787 uint64_t OffsetInBits, unsigned Flags,
790 GetTagConstant(dwarf::DW_TAG_base_type),
792 MDString::get(VMContext, Name),
794 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
795 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
796 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
797 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
798 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
799 ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
801 return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
805 /// CreateBasicType - Create a basic type like int, float, etc.
806 DIBasicType DIFactory::CreateBasicTypeEx(DIDescriptor Context,
810 Constant *SizeInBits,
811 Constant *AlignInBits,
812 Constant *OffsetInBits, unsigned Flags,
815 GetTagConstant(dwarf::DW_TAG_base_type),
817 MDString::get(VMContext, Name),
819 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
823 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
824 ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
826 return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
829 /// CreateArtificialType - Create a new DIType with "artificial" flag set.
830 DIType DIFactory::CreateArtificialType(DIType Ty) {
831 if (Ty.isArtificial())
834 SmallVector<Value *, 9> Elts;
836 assert (N && "Unexpected input DIType!");
837 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
838 if (Value *V = N->getOperand(i))
841 Elts.push_back(Constant::getNullValue(Type::getInt32Ty(VMContext)));
844 unsigned CurFlags = Ty.getFlags();
845 CurFlags = CurFlags | DIType::FlagArtificial;
847 // Flags are stored at this slot.
848 Elts[8] = ConstantInt::get(Type::getInt32Ty(VMContext), CurFlags);
850 return DIType(MDNode::get(VMContext, Elts.data(), Elts.size()));
853 /// CreateDerivedType - Create a derived type like const qualified type,
854 /// pointer, typedef, etc.
855 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
856 DIDescriptor Context,
861 uint64_t AlignInBits,
862 uint64_t OffsetInBits,
864 DIType DerivedFrom) {
868 MDString::get(VMContext, Name),
870 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
871 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
872 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
873 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
874 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
877 return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
881 /// CreateDerivedType - Create a derived type like const qualified type,
882 /// pointer, typedef, etc.
883 DIDerivedType DIFactory::CreateDerivedTypeEx(unsigned Tag,
884 DIDescriptor Context,
888 Constant *SizeInBits,
889 Constant *AlignInBits,
890 Constant *OffsetInBits,
892 DIType DerivedFrom) {
896 MDString::get(VMContext, Name),
898 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
902 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
905 return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
909 /// CreateCompositeType - Create a composite type like array, struct, etc.
910 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
911 DIDescriptor Context,
916 uint64_t AlignInBits,
917 uint64_t OffsetInBits,
921 unsigned RuntimeLang,
922 MDNode *ContainingType) {
927 MDString::get(VMContext, Name),
929 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
930 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
931 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
932 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
933 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
936 ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang),
940 MDNode *Node = MDNode::get(VMContext, &Elts[0], 13);
941 // Create a named metadata so that we do not lose this enum info.
942 if (Tag == dwarf::DW_TAG_enumeration_type) {
943 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.enum");
944 NMD->addOperand(Node);
946 return DICompositeType(Node);
950 /// CreateTemporaryType - Create a temporary forward-declared type.
951 DIType DIFactory::CreateTemporaryType() {
952 // Give the temporary MDNode a tag. It doesn't matter what tag we
953 // use here as long as DIType accepts it.
955 GetTagConstant(DW_TAG_base_type)
957 MDNode *Node = MDNode::getTemporary(VMContext, Elts, array_lengthof(Elts));
962 /// CreateCompositeType - Create a composite type like array, struct, etc.
963 DICompositeType DIFactory::CreateCompositeTypeEx(unsigned Tag,
964 DIDescriptor Context,
968 Constant *SizeInBits,
969 Constant *AlignInBits,
970 Constant *OffsetInBits,
974 unsigned RuntimeLang,
975 MDNode *ContainingType) {
979 MDString::get(VMContext, Name),
981 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
985 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
988 ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang),
991 MDNode *Node = MDNode::get(VMContext, &Elts[0], 13);
992 // Create a named metadata so that we do not lose this enum info.
993 if (Tag == dwarf::DW_TAG_enumeration_type) {
994 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.enum");
995 NMD->addOperand(Node);
997 return DICompositeType(Node);
1001 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
1002 /// See comments in DISubprogram for descriptions of these fields. This
1003 /// method does not unique the generated descriptors.
1004 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context,
1006 StringRef DisplayName,
1007 StringRef LinkageName,
1009 unsigned LineNo, DIType Ty,
1012 unsigned VK, unsigned VIndex,
1013 DIType ContainingType,
1019 GetTagConstant(dwarf::DW_TAG_subprogram),
1020 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
1022 MDString::get(VMContext, Name),
1023 MDString::get(VMContext, DisplayName),
1024 MDString::get(VMContext, LinkageName),
1026 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1028 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
1029 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
1030 ConstantInt::get(Type::getInt32Ty(VMContext), (unsigned)VK),
1031 ConstantInt::get(Type::getInt32Ty(VMContext), VIndex),
1033 ConstantInt::get(Type::getInt1Ty(VMContext), isArtificial),
1034 ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
1037 MDNode *Node = MDNode::get(VMContext, &Elts[0], 17);
1039 // Create a named metadata so that we do not lose this mdnode.
1040 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.sp");
1041 NMD->addOperand(Node);
1042 return DISubprogram(Node);
1045 /// CreateSubprogramDefinition - Create new subprogram descriptor for the
1046 /// given declaration.
1047 DISubprogram DIFactory::CreateSubprogramDefinition(DISubprogram &SPDeclaration){
1048 if (SPDeclaration.isDefinition())
1049 return DISubprogram(SPDeclaration);
1051 MDNode *DeclNode = SPDeclaration;
1053 GetTagConstant(dwarf::DW_TAG_subprogram),
1054 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
1055 DeclNode->getOperand(2), // Context
1056 DeclNode->getOperand(3), // Name
1057 DeclNode->getOperand(4), // DisplayName
1058 DeclNode->getOperand(5), // LinkageName
1059 DeclNode->getOperand(6), // CompileUnit
1060 DeclNode->getOperand(7), // LineNo
1061 DeclNode->getOperand(8), // Type
1062 DeclNode->getOperand(9), // isLocalToUnit
1063 ConstantInt::get(Type::getInt1Ty(VMContext), true),
1064 DeclNode->getOperand(11), // Virtuality
1065 DeclNode->getOperand(12), // VIndex
1066 DeclNode->getOperand(13), // Containting Type
1067 DeclNode->getOperand(14), // isArtificial
1068 DeclNode->getOperand(15), // isOptimized
1069 SPDeclaration.getFunction()
1071 MDNode *Node =MDNode::get(VMContext, &Elts[0], 16);
1073 // Create a named metadata so that we do not lose this mdnode.
1074 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.sp");
1075 NMD->addOperand(Node);
1076 return DISubprogram(Node);
1079 /// CreateGlobalVariable - Create a new descriptor for the specified global.
1081 DIFactory::CreateGlobalVariable(DIDescriptor Context, StringRef Name,
1082 StringRef DisplayName,
1083 StringRef LinkageName,
1085 unsigned LineNo, DIType Ty,bool isLocalToUnit,
1086 bool isDefinition, llvm::GlobalVariable *Val) {
1088 GetTagConstant(dwarf::DW_TAG_variable),
1089 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
1091 MDString::get(VMContext, Name),
1092 MDString::get(VMContext, DisplayName),
1093 MDString::get(VMContext, LinkageName),
1095 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1097 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
1098 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
1102 Value *const *Vs = &Elts[0];
1103 MDNode *Node = MDNode::get(VMContext,Vs, 12);
1105 // Create a named metadata so that we do not lose this mdnode.
1106 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.gv");
1107 NMD->addOperand(Node);
1109 return DIGlobalVariable(Node);
1112 /// CreateGlobalVariable - Create a new descriptor for the specified constant.
1114 DIFactory::CreateGlobalVariable(DIDescriptor Context, StringRef Name,
1115 StringRef DisplayName,
1116 StringRef LinkageName,
1118 unsigned LineNo, DIType Ty,bool isLocalToUnit,
1119 bool isDefinition, llvm::Constant *Val) {
1121 GetTagConstant(dwarf::DW_TAG_variable),
1122 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
1124 MDString::get(VMContext, Name),
1125 MDString::get(VMContext, DisplayName),
1126 MDString::get(VMContext, LinkageName),
1128 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1130 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
1131 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
1135 Value *const *Vs = &Elts[0];
1136 MDNode *Node = MDNode::get(VMContext,Vs, 12);
1138 // Create a named metadata so that we do not lose this mdnode.
1139 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.gv");
1140 NMD->addOperand(Node);
1142 return DIGlobalVariable(Node);
1145 /// CreateVariable - Create a new descriptor for the specified variable.
1146 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
1150 DIType Ty, bool AlwaysPreserve) {
1152 GetTagConstant(Tag),
1154 MDString::get(VMContext, Name),
1156 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1159 MDNode *Node = MDNode::get(VMContext, &Elts[0], 6);
1160 if (AlwaysPreserve) {
1161 // The optimizer may remove local variable. If there is an interest
1162 // to preserve variable info in such situation then stash it in a
1164 DISubprogram Fn(getDISubprogram(Context));
1165 StringRef FName = "fn";
1166 if (Fn.getFunction())
1167 FName = Fn.getFunction()->getName();
1169 if (FName.startswith(StringRef(&One, 1)))
1170 FName = FName.substr(1);
1172 SmallString<32> Out;
1173 NamedMDNode *FnLocals =
1174 M.getOrInsertNamedMetadata(Twine("llvm.dbg.lv.", FName).toStringRef(Out));
1175 FnLocals->addOperand(Node);
1177 return DIVariable(Node);
1181 /// CreateComplexVariable - Create a new descriptor for the specified variable
1182 /// which has a complex address expression for its address.
1183 DIVariable DIFactory::CreateComplexVariable(unsigned Tag, DIDescriptor Context,
1184 StringRef Name, DIFile F,
1186 DIType Ty, Value *const *Addr,
1188 SmallVector<Value *, 15> Elts;
1189 Elts.push_back(GetTagConstant(Tag));
1190 Elts.push_back(Context);
1191 Elts.push_back(MDString::get(VMContext, Name));
1193 Elts.push_back(ConstantInt::get(Type::getInt32Ty(VMContext), LineNo));
1195 Elts.append(Addr, Addr+NumAddr);
1197 return DIVariable(MDNode::get(VMContext, Elts.data(), Elts.size()));
1201 /// CreateBlock - This creates a descriptor for a lexical block with the
1202 /// specified parent VMContext.
1203 DILexicalBlock DIFactory::CreateLexicalBlock(DIDescriptor Context,
1204 DIFile F, unsigned LineNo,
1206 // Defeat MDNode uniqing for lexical blocks.
1207 static unsigned int unique_id = 0;
1209 GetTagConstant(dwarf::DW_TAG_lexical_block),
1211 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1212 ConstantInt::get(Type::getInt32Ty(VMContext), Col),
1214 ConstantInt::get(Type::getInt32Ty(VMContext), unique_id++)
1216 return DILexicalBlock(MDNode::get(VMContext, &Elts[0], 6));
1219 /// CreateNameSpace - This creates new descriptor for a namespace
1220 /// with the specified parent context.
1221 DINameSpace DIFactory::CreateNameSpace(DIDescriptor Context, StringRef Name,
1225 GetTagConstant(dwarf::DW_TAG_namespace),
1227 MDString::get(VMContext, Name),
1229 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo)
1231 return DINameSpace(MDNode::get(VMContext, &Elts[0], 5));
1234 /// CreateLocation - Creates a debug info location.
1235 DILocation DIFactory::CreateLocation(unsigned LineNo, unsigned ColumnNo,
1236 DIScope S, DILocation OrigLoc) {
1238 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1239 ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo),
1243 return DILocation(MDNode::get(VMContext, &Elts[0], 4));
1246 //===----------------------------------------------------------------------===//
1247 // DIFactory: Routines for inserting code into a function
1248 //===----------------------------------------------------------------------===//
1250 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1251 Instruction *DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1252 Instruction *InsertBefore) {
1253 assert(Storage && "no storage passed to dbg.declare");
1254 assert(D.Verify() && "empty DIVariable passed to dbg.declare");
1256 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1258 Value *Args[] = { MDNode::get(Storage->getContext(), &Storage, 1),
1260 return CallInst::Create(DeclareFn, Args, Args+2, "", InsertBefore);
1263 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1264 Instruction *DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1265 BasicBlock *InsertAtEnd) {
1266 assert(Storage && "no storage passed to dbg.declare");
1267 assert(D.Verify() && "invalid DIVariable passed to dbg.declare");
1269 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1271 Value *Args[] = { MDNode::get(Storage->getContext(), &Storage, 1),
1274 // If this block already has a terminator then insert this intrinsic
1275 // before the terminator.
1276 if (TerminatorInst *T = InsertAtEnd->getTerminator())
1277 return CallInst::Create(DeclareFn, Args, Args+2, "", T);
1279 return CallInst::Create(DeclareFn, Args, Args+2, "", InsertAtEnd);}
1281 /// InsertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
1282 Instruction *DIFactory::InsertDbgValueIntrinsic(Value *V, uint64_t Offset,
1284 Instruction *InsertBefore) {
1285 assert(V && "no value passed to dbg.value");
1286 assert(D.Verify() && "invalid DIVariable passed to dbg.value");
1288 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1290 Value *Args[] = { MDNode::get(V->getContext(), &V, 1),
1291 ConstantInt::get(Type::getInt64Ty(V->getContext()), Offset),
1293 return CallInst::Create(ValueFn, Args, Args+3, "", InsertBefore);
1296 /// InsertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
1297 Instruction *DIFactory::InsertDbgValueIntrinsic(Value *V, uint64_t Offset,
1299 BasicBlock *InsertAtEnd) {
1300 assert(V && "no value passed to dbg.value");
1301 assert(D.Verify() && "invalid DIVariable passed to dbg.value");
1303 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1305 Value *Args[] = { MDNode::get(V->getContext(), &V, 1),
1306 ConstantInt::get(Type::getInt64Ty(V->getContext()), Offset),
1308 return CallInst::Create(ValueFn, Args, Args+3, "", InsertAtEnd);
1311 //===----------------------------------------------------------------------===//
1312 // DebugInfoFinder implementations.
1313 //===----------------------------------------------------------------------===//
1315 /// processModule - Process entire module and collect debug info.
1316 void DebugInfoFinder::processModule(Module &M) {
1317 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1318 for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI)
1319 for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE;
1321 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
1322 processDeclare(DDI);
1324 DebugLoc Loc = BI->getDebugLoc();
1325 if (Loc.isUnknown())
1328 LLVMContext &Ctx = BI->getContext();
1329 DIDescriptor Scope(Loc.getScope(Ctx));
1331 if (Scope.isCompileUnit())
1332 addCompileUnit(DICompileUnit(Scope));
1333 else if (Scope.isSubprogram())
1334 processSubprogram(DISubprogram(Scope));
1335 else if (Scope.isLexicalBlock())
1336 processLexicalBlock(DILexicalBlock(Scope));
1338 if (MDNode *IA = Loc.getInlinedAt(Ctx))
1339 processLocation(DILocation(IA));
1342 if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv")) {
1343 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1344 DIGlobalVariable DIG(cast<MDNode>(NMD->getOperand(i)));
1345 if (addGlobalVariable(DIG)) {
1346 addCompileUnit(DIG.getCompileUnit());
1347 processType(DIG.getType());
1352 if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.sp"))
1353 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
1354 processSubprogram(DISubprogram(NMD->getOperand(i)));
1357 /// processLocation - Process DILocation.
1358 void DebugInfoFinder::processLocation(DILocation Loc) {
1359 if (!Loc.Verify()) return;
1360 DIDescriptor S(Loc.getScope());
1361 if (S.isCompileUnit())
1362 addCompileUnit(DICompileUnit(S));
1363 else if (S.isSubprogram())
1364 processSubprogram(DISubprogram(S));
1365 else if (S.isLexicalBlock())
1366 processLexicalBlock(DILexicalBlock(S));
1367 processLocation(Loc.getOrigLocation());
1370 /// processType - Process DIType.
1371 void DebugInfoFinder::processType(DIType DT) {
1375 addCompileUnit(DT.getCompileUnit());
1376 if (DT.isCompositeType()) {
1377 DICompositeType DCT(DT);
1378 processType(DCT.getTypeDerivedFrom());
1379 DIArray DA = DCT.getTypeArray();
1380 for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
1381 DIDescriptor D = DA.getElement(i);
1383 processType(DIType(D));
1384 else if (D.isSubprogram())
1385 processSubprogram(DISubprogram(D));
1387 } else if (DT.isDerivedType()) {
1388 DIDerivedType DDT(DT);
1389 processType(DDT.getTypeDerivedFrom());
1393 /// processLexicalBlock
1394 void DebugInfoFinder::processLexicalBlock(DILexicalBlock LB) {
1395 DIScope Context = LB.getContext();
1396 if (Context.isLexicalBlock())
1397 return processLexicalBlock(DILexicalBlock(Context));
1399 return processSubprogram(DISubprogram(Context));
1402 /// processSubprogram - Process DISubprogram.
1403 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
1404 if (!addSubprogram(SP))
1406 addCompileUnit(SP.getCompileUnit());
1407 processType(SP.getType());
1410 /// processDeclare - Process DbgDeclareInst.
1411 void DebugInfoFinder::processDeclare(DbgDeclareInst *DDI) {
1412 MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
1416 if (!DV.isVariable())
1419 if (!NodesSeen.insert(DV))
1422 addCompileUnit(DIVariable(N).getCompileUnit());
1423 processType(DIVariable(N).getType());
1426 /// addType - Add type into Tys.
1427 bool DebugInfoFinder::addType(DIType DT) {
1431 if (!NodesSeen.insert(DT))
1438 /// addCompileUnit - Add compile unit into CUs.
1439 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1443 if (!NodesSeen.insert(CU))
1450 /// addGlobalVariable - Add global variable into GVs.
1451 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1452 if (!DIDescriptor(DIG).isGlobalVariable())
1455 if (!NodesSeen.insert(DIG))
1462 // addSubprogram - Add subprgoram into SPs.
1463 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1464 if (!DIDescriptor(SP).isSubprogram())
1467 if (!NodesSeen.insert(SP))
1474 /// Find the debug info descriptor corresponding to this global variable.
1475 static Value *findDbgGlobalDeclare(GlobalVariable *V) {
1476 const Module *M = V->getParent();
1477 NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv");
1481 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1482 DIDescriptor DIG(cast<MDNode>(NMD->getOperand(i)));
1483 if (!DIG.isGlobalVariable())
1485 if (DIGlobalVariable(DIG).getGlobal() == V)
1491 /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
1492 /// It looks through pointer casts too.
1493 static const DbgDeclareInst *findDbgDeclare(const Value *V) {
1494 V = V->stripPointerCasts();
1496 if (!isa<Instruction>(V) && !isa<Argument>(V))
1499 const Function *F = NULL;
1500 if (const Instruction *I = dyn_cast<Instruction>(V))
1501 F = I->getParent()->getParent();
1502 else if (const Argument *A = dyn_cast<Argument>(V))
1505 for (Function::const_iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
1506 for (BasicBlock::const_iterator BI = (*FI).begin(), BE = (*FI).end();
1508 if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
1509 if (DDI->getAddress() == V)
1515 bool llvm::getLocationInfo(const Value *V, std::string &DisplayName,
1516 std::string &Type, unsigned &LineNo,
1517 std::string &File, std::string &Dir) {
1521 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
1522 Value *DIGV = findDbgGlobalDeclare(GV);
1523 if (!DIGV) return false;
1524 DIGlobalVariable Var(cast<MDNode>(DIGV));
1526 StringRef D = Var.getDisplayName();
1529 LineNo = Var.getLineNumber();
1530 Unit = Var.getCompileUnit();
1531 TypeD = Var.getType();
1533 const DbgDeclareInst *DDI = findDbgDeclare(V);
1534 if (!DDI) return false;
1535 DIVariable Var(cast<MDNode>(DDI->getVariable()));
1537 StringRef D = Var.getName();
1540 LineNo = Var.getLineNumber();
1541 Unit = Var.getCompileUnit();
1542 TypeD = Var.getType();
1545 StringRef T = TypeD.getName();
1548 StringRef F = Unit.getFilename();
1551 StringRef D = Unit.getDirectory();
1557 /// getDISubprogram - Find subprogram that is enclosing this scope.
1558 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
1559 DIDescriptor D(Scope);
1560 if (D.isSubprogram())
1561 return DISubprogram(Scope);
1563 if (D.isLexicalBlock())
1564 return getDISubprogram(DILexicalBlock(Scope).getContext());
1566 return DISubprogram();
1569 /// getDICompositeType - Find underlying composite type.
1570 DICompositeType llvm::getDICompositeType(DIType T) {
1571 if (T.isCompositeType())
1572 return DICompositeType(T);
1574 if (T.isDerivedType())
1575 return getDICompositeType(DIDerivedType(T).getTypeDerivedFrom());
1577 return DICompositeType();