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/Support/Debug.h"
26 #include "llvm/Support/Dwarf.h"
27 #include "llvm/Support/raw_ostream.h"
29 using namespace llvm::dwarf;
31 //===----------------------------------------------------------------------===//
33 //===----------------------------------------------------------------------===//
36 DIDescriptor::getStringField(unsigned Elt) const {
40 if (Elt < DbgNode->getNumOperands())
41 if (MDString *MDS = dyn_cast_or_null<MDString>(DbgNode->getOperand(Elt)))
42 return MDS->getString();
47 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
51 if (Elt < DbgNode->getNumOperands())
52 if (ConstantInt *CI = dyn_cast<ConstantInt>(DbgNode->getOperand(Elt)))
53 return CI->getZExtValue();
58 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
60 return DIDescriptor();
62 if (Elt < DbgNode->getNumOperands())
64 DIDescriptor(dyn_cast_or_null<const MDNode>(DbgNode->getOperand(Elt)));
65 return DIDescriptor();
68 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
72 if (Elt < DbgNode->getNumOperands())
73 return dyn_cast_or_null<GlobalVariable>(DbgNode->getOperand(Elt));
77 Function *DIDescriptor::getFunctionField(unsigned Elt) const {
81 if (Elt < DbgNode->getNumOperands())
82 return dyn_cast_or_null<Function>(DbgNode->getOperand(Elt));
86 unsigned DIVariable::getNumAddrElements() const {
87 return DbgNode->getNumOperands()-6;
91 //===----------------------------------------------------------------------===//
93 //===----------------------------------------------------------------------===//
95 /// isBasicType - Return true if the specified tag is legal for
97 bool DIDescriptor::isBasicType() const {
98 return DbgNode && getTag() == dwarf::DW_TAG_base_type;
101 /// isDerivedType - Return true if the specified tag is legal for DIDerivedType.
102 bool DIDescriptor::isDerivedType() const {
103 if (!DbgNode) return false;
105 case dwarf::DW_TAG_typedef:
106 case dwarf::DW_TAG_pointer_type:
107 case dwarf::DW_TAG_reference_type:
108 case dwarf::DW_TAG_const_type:
109 case dwarf::DW_TAG_volatile_type:
110 case dwarf::DW_TAG_restrict_type:
111 case dwarf::DW_TAG_member:
112 case dwarf::DW_TAG_inheritance:
115 // CompositeTypes are currently modelled as DerivedTypes.
116 return isCompositeType();
120 /// isCompositeType - Return true if the specified tag is legal for
122 bool DIDescriptor::isCompositeType() const {
123 if (!DbgNode) return false;
125 case dwarf::DW_TAG_array_type:
126 case dwarf::DW_TAG_structure_type:
127 case dwarf::DW_TAG_union_type:
128 case dwarf::DW_TAG_enumeration_type:
129 case dwarf::DW_TAG_vector_type:
130 case dwarf::DW_TAG_subroutine_type:
131 case dwarf::DW_TAG_class_type:
138 /// isVariable - Return true if the specified tag is legal for DIVariable.
139 bool DIDescriptor::isVariable() const {
140 if (!DbgNode) return false;
142 case dwarf::DW_TAG_auto_variable:
143 case dwarf::DW_TAG_arg_variable:
144 case dwarf::DW_TAG_return_variable:
151 /// isType - Return true if the specified tag is legal for DIType.
152 bool DIDescriptor::isType() const {
153 return isBasicType() || isCompositeType() || isDerivedType();
156 /// isSubprogram - Return true if the specified tag is legal for
158 bool DIDescriptor::isSubprogram() const {
159 return DbgNode && getTag() == dwarf::DW_TAG_subprogram;
162 /// isGlobalVariable - Return true if the specified tag is legal for
163 /// DIGlobalVariable.
164 bool DIDescriptor::isGlobalVariable() const {
165 return DbgNode && getTag() == dwarf::DW_TAG_variable;
168 /// isGlobal - Return true if the specified tag is legal for DIGlobal.
169 bool DIDescriptor::isGlobal() const {
170 return isGlobalVariable();
173 /// isScope - Return true if the specified tag is one of the scope
175 bool DIDescriptor::isScope() const {
176 if (!DbgNode) return false;
178 case dwarf::DW_TAG_compile_unit:
179 case dwarf::DW_TAG_lexical_block:
180 case dwarf::DW_TAG_subprogram:
181 case dwarf::DW_TAG_namespace:
189 /// isCompileUnit - Return true if the specified tag is DW_TAG_compile_unit.
190 bool DIDescriptor::isCompileUnit() const {
191 return DbgNode && getTag() == dwarf::DW_TAG_compile_unit;
194 /// isFile - Return true if the specified tag is DW_TAG_file_type.
195 bool DIDescriptor::isFile() const {
196 return DbgNode && getTag() == dwarf::DW_TAG_file_type;
199 /// isNameSpace - Return true if the specified tag is DW_TAG_namespace.
200 bool DIDescriptor::isNameSpace() const {
201 return DbgNode && getTag() == dwarf::DW_TAG_namespace;
204 /// isLexicalBlock - Return true if the specified tag is DW_TAG_lexical_block.
205 bool DIDescriptor::isLexicalBlock() const {
206 return DbgNode && getTag() == dwarf::DW_TAG_lexical_block;
209 /// isSubrange - Return true if the specified tag is DW_TAG_subrange_type.
210 bool DIDescriptor::isSubrange() const {
211 return DbgNode && getTag() == dwarf::DW_TAG_subrange_type;
214 /// isEnumerator - Return true if the specified tag is DW_TAG_enumerator.
215 bool DIDescriptor::isEnumerator() const {
216 return DbgNode && getTag() == dwarf::DW_TAG_enumerator;
219 //===----------------------------------------------------------------------===//
220 // Simple Descriptor Constructors and other Methods
221 //===----------------------------------------------------------------------===//
223 DIType::DIType(const MDNode *N) : DIScope(N) {
225 if (!isBasicType() && !isDerivedType() && !isCompositeType()) {
230 unsigned DIArray::getNumElements() const {
233 return DbgNode->getNumOperands();
236 /// replaceAllUsesWith - Replace all uses of debug info referenced by
238 void DIDerivedType::replaceAllUsesWith(DIDescriptor &D) {
242 // Since we use a TrackingVH for the node, its easy for clients to manufacture
243 // legitimate situations where they want to replaceAllUsesWith() on something
244 // which, due to uniquing, has merged with the source. We shield clients from
245 // this detail by allowing a value to be replaced with replaceAllUsesWith()
248 MDNode *Node = const_cast<MDNode*>(DbgNode);
249 const MDNode *DN = D;
250 const Value *V = cast_or_null<Value>(DN);
251 Node->replaceAllUsesWith(const_cast<Value*>(V));
255 /// Verify - Verify that a compile unit is well formed.
256 bool DICompileUnit::Verify() const {
259 StringRef N = getFilename();
262 // It is possible that directory and produce string is empty.
266 /// Verify - Verify that a type descriptor is well formed.
267 bool DIType::Verify() const {
270 if (!getContext().Verify())
273 DICompileUnit CU = getCompileUnit();
279 /// Verify - Verify that a composite type descriptor is well formed.
280 bool DICompositeType::Verify() const {
283 if (!getContext().Verify())
286 DICompileUnit CU = getCompileUnit();
292 /// Verify - Verify that a subprogram descriptor is well formed.
293 bool DISubprogram::Verify() const {
297 if (!getContext().Verify())
300 DICompileUnit CU = getCompileUnit();
304 DICompositeType Ty = getType();
310 /// Verify - Verify that a global variable descriptor is well formed.
311 bool DIGlobalVariable::Verify() const {
315 if (getDisplayName().empty())
318 if (!getContext().Verify())
321 DICompileUnit CU = getCompileUnit();
325 DIType Ty = getType();
335 /// Verify - Verify that a variable descriptor is well formed.
336 bool DIVariable::Verify() const {
340 if (!getContext().Verify())
343 if (!getCompileUnit().Verify())
346 DIType Ty = getType();
353 /// Verify - Verify that a location descriptor is well formed.
354 bool DILocation::Verify() const {
358 return DbgNode->getNumOperands() == 4;
361 /// Verify - Verify that a namespace descriptor is well formed.
362 bool DINameSpace::Verify() const {
365 if (getName().empty())
367 if (!getCompileUnit().Verify())
372 /// getOriginalTypeSize - If this type is derived from a base type then
373 /// return base type size.
374 uint64_t DIDerivedType::getOriginalTypeSize() const {
375 unsigned Tag = getTag();
376 if (Tag == dwarf::DW_TAG_member || Tag == dwarf::DW_TAG_typedef ||
377 Tag == dwarf::DW_TAG_const_type || Tag == dwarf::DW_TAG_volatile_type ||
378 Tag == dwarf::DW_TAG_restrict_type) {
379 DIType BaseType = getTypeDerivedFrom();
380 // If this type is not derived from any type then take conservative
382 if (!BaseType.isValid())
383 return getSizeInBits();
384 if (BaseType.isDerivedType())
385 return DIDerivedType(BaseType).getOriginalTypeSize();
387 return BaseType.getSizeInBits();
390 return getSizeInBits();
393 /// isInlinedFnArgument - Return true if this variable provides debugging
394 /// information for an inlined function arguments.
395 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
396 assert(CurFn && "Invalid function");
397 if (!getContext().isSubprogram())
399 // This variable is not inlined function argument if its scope
400 // does not describe current function.
401 return !(DISubprogram(getContext()).describes(CurFn));
404 /// describes - Return true if this subprogram provides debugging
405 /// information for the function F.
406 bool DISubprogram::describes(const Function *F) {
407 assert(F && "Invalid function");
408 if (F == getFunction())
410 StringRef Name = getLinkageName();
413 if (F->getName() == Name)
418 unsigned DISubprogram::isOptimized() const {
419 assert (DbgNode && "Invalid subprogram descriptor!");
420 if (DbgNode->getNumOperands() == 16)
421 return getUnsignedField(15);
425 StringRef DIScope::getFilename() const {
428 if (isLexicalBlock())
429 return DILexicalBlock(DbgNode).getFilename();
431 return DISubprogram(DbgNode).getFilename();
433 return DICompileUnit(DbgNode).getFilename();
435 return DINameSpace(DbgNode).getFilename();
437 return DIType(DbgNode).getFilename();
439 return DIFile(DbgNode).getFilename();
440 assert(0 && "Invalid DIScope!");
444 StringRef DIScope::getDirectory() const {
447 if (isLexicalBlock())
448 return DILexicalBlock(DbgNode).getDirectory();
450 return DISubprogram(DbgNode).getDirectory();
452 return DICompileUnit(DbgNode).getDirectory();
454 return DINameSpace(DbgNode).getDirectory();
456 return DIType(DbgNode).getDirectory();
458 return DIFile(DbgNode).getDirectory();
459 assert(0 && "Invalid DIScope!");
463 //===----------------------------------------------------------------------===//
464 // DIDescriptor: dump routines for all descriptors.
465 //===----------------------------------------------------------------------===//
468 /// print - Print descriptor.
469 void DIDescriptor::print(raw_ostream &OS) const {
470 OS << "[" << dwarf::TagString(getTag()) << "] ";
471 OS.write_hex((intptr_t) &*DbgNode) << ']';
474 /// print - Print compile unit.
475 void DICompileUnit::print(raw_ostream &OS) const {
477 OS << " [" << dwarf::LanguageString(getLanguage()) << "] ";
479 OS << " [" << getDirectory() << "/" << getFilename() << "]";
482 /// print - Print type.
483 void DIType::print(raw_ostream &OS) const {
484 if (!DbgNode) return;
486 StringRef Res = getName();
488 OS << " [" << Res << "] ";
490 unsigned Tag = getTag();
491 OS << " [" << dwarf::TagString(Tag) << "] ";
493 // TODO : Print context
494 getCompileUnit().print(OS);
496 << "line " << getLineNumber() << ", "
497 << getSizeInBits() << " bits, "
498 << getAlignInBits() << " bit alignment, "
499 << getOffsetInBits() << " bit offset"
504 else if (isProtected())
505 OS << " [protected] ";
511 DIBasicType(DbgNode).print(OS);
512 else if (isDerivedType())
513 DIDerivedType(DbgNode).print(OS);
514 else if (isCompositeType())
515 DICompositeType(DbgNode).print(OS);
517 OS << "Invalid DIType\n";
524 /// print - Print basic type.
525 void DIBasicType::print(raw_ostream &OS) const {
526 OS << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
529 /// print - Print derived type.
530 void DIDerivedType::print(raw_ostream &OS) const {
531 OS << "\n\t Derived From: "; getTypeDerivedFrom().print(OS);
534 /// print - Print composite type.
535 void DICompositeType::print(raw_ostream &OS) const {
536 DIArray A = getTypeArray();
537 OS << " [" << A.getNumElements() << " elements]";
540 /// print - Print subprogram.
541 void DISubprogram::print(raw_ostream &OS) const {
542 StringRef Res = getName();
544 OS << " [" << Res << "] ";
546 unsigned Tag = getTag();
547 OS << " [" << dwarf::TagString(Tag) << "] ";
549 // TODO : Print context
550 getCompileUnit().print(OS);
551 OS << " [" << getLineNumber() << "] ";
562 /// print - Print global variable.
563 void DIGlobalVariable::print(raw_ostream &OS) const {
565 StringRef Res = getName();
567 OS << " [" << Res << "] ";
569 unsigned Tag = getTag();
570 OS << " [" << dwarf::TagString(Tag) << "] ";
572 // TODO : Print context
573 getCompileUnit().print(OS);
574 OS << " [" << getLineNumber() << "] ";
582 if (isGlobalVariable())
583 DIGlobalVariable(DbgNode).print(OS);
587 /// print - Print variable.
588 void DIVariable::print(raw_ostream &OS) const {
589 StringRef Res = getName();
591 OS << " [" << Res << "] ";
593 getCompileUnit().print(OS);
594 OS << " [" << getLineNumber() << "] ";
598 // FIXME: Dump complex addresses
601 /// dump - Print descriptor to dbgs() with a newline.
602 void DIDescriptor::dump() const {
603 print(dbgs()); dbgs() << '\n';
606 /// dump - Print compile unit to dbgs() with a newline.
607 void DICompileUnit::dump() const {
608 print(dbgs()); dbgs() << '\n';
611 /// dump - Print type to dbgs() with a newline.
612 void DIType::dump() const {
613 print(dbgs()); dbgs() << '\n';
616 /// dump - Print basic type to dbgs() with a newline.
617 void DIBasicType::dump() const {
618 print(dbgs()); dbgs() << '\n';
621 /// dump - Print derived type to dbgs() with a newline.
622 void DIDerivedType::dump() const {
623 print(dbgs()); dbgs() << '\n';
626 /// dump - Print composite type to dbgs() with a newline.
627 void DICompositeType::dump() const {
628 print(dbgs()); dbgs() << '\n';
631 /// dump - Print subprogram to dbgs() with a newline.
632 void DISubprogram::dump() const {
633 print(dbgs()); dbgs() << '\n';
636 /// dump - Print global variable.
637 void DIGlobalVariable::dump() const {
638 print(dbgs()); dbgs() << '\n';
641 /// dump - Print variable.
642 void DIVariable::dump() const {
643 print(dbgs()); dbgs() << '\n';
646 //===----------------------------------------------------------------------===//
647 // DIFactory: Basic Helpers
648 //===----------------------------------------------------------------------===//
650 DIFactory::DIFactory(Module &m)
651 : M(m), VMContext(M.getContext()), DeclareFn(0), ValueFn(0) {}
653 Constant *DIFactory::GetTagConstant(unsigned TAG) {
654 assert((TAG & LLVMDebugVersionMask) == 0 &&
655 "Tag too large for debug encoding!");
656 return ConstantInt::get(Type::getInt32Ty(VMContext), TAG | LLVMDebugVersion);
659 //===----------------------------------------------------------------------===//
660 // DIFactory: Primary Constructors
661 //===----------------------------------------------------------------------===//
663 /// GetOrCreateArray - Create an descriptor for an array of descriptors.
664 /// This implicitly uniques the arrays created.
665 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
666 SmallVector<Value*, 16> Elts;
669 Elts.push_back(llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)));
671 for (unsigned i = 0; i != NumTys; ++i)
672 Elts.push_back(Tys[i]);
674 return DIArray(MDNode::get(VMContext,Elts.data(), Elts.size()));
677 /// GetOrCreateSubrange - Create a descriptor for a value range. This
678 /// implicitly uniques the values returned.
679 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
681 GetTagConstant(dwarf::DW_TAG_subrange_type),
682 ConstantInt::get(Type::getInt64Ty(VMContext), Lo),
683 ConstantInt::get(Type::getInt64Ty(VMContext), Hi)
686 return DISubrange(MDNode::get(VMContext, &Elts[0], 3));
691 /// CreateCompileUnit - Create a new descriptor for the specified compile
692 /// unit. Note that this does not unique compile units within the module.
693 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
700 unsigned RunTimeVer) {
702 GetTagConstant(dwarf::DW_TAG_compile_unit),
703 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
704 ConstantInt::get(Type::getInt32Ty(VMContext), LangID),
705 MDString::get(VMContext, Filename),
706 MDString::get(VMContext, Directory),
707 MDString::get(VMContext, Producer),
708 ConstantInt::get(Type::getInt1Ty(VMContext), isMain),
709 ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
710 MDString::get(VMContext, Flags),
711 ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeVer)
714 return DICompileUnit(MDNode::get(VMContext, &Elts[0], 10));
717 /// CreateFile - Create a new descriptor for the specified file.
718 DIFile DIFactory::CreateFile(StringRef Filename,
722 GetTagConstant(dwarf::DW_TAG_file_type),
723 MDString::get(VMContext, Filename),
724 MDString::get(VMContext, Directory),
728 return DIFile(MDNode::get(VMContext, &Elts[0], 4));
731 /// CreateEnumerator - Create a single enumerator value.
732 DIEnumerator DIFactory::CreateEnumerator(StringRef Name, uint64_t Val){
734 GetTagConstant(dwarf::DW_TAG_enumerator),
735 MDString::get(VMContext, Name),
736 ConstantInt::get(Type::getInt64Ty(VMContext), Val)
738 return DIEnumerator(MDNode::get(VMContext, &Elts[0], 3));
742 /// CreateBasicType - Create a basic type like int, float, etc.
743 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
748 uint64_t AlignInBits,
749 uint64_t OffsetInBits, unsigned Flags,
752 GetTagConstant(dwarf::DW_TAG_base_type),
754 MDString::get(VMContext, Name),
756 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
757 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
758 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
759 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
760 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
761 ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
763 return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
767 /// CreateBasicType - Create a basic type like int, float, etc.
768 DIBasicType DIFactory::CreateBasicTypeEx(DIDescriptor Context,
772 Constant *SizeInBits,
773 Constant *AlignInBits,
774 Constant *OffsetInBits, unsigned Flags,
777 GetTagConstant(dwarf::DW_TAG_base_type),
779 MDString::get(VMContext, Name),
781 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
785 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
786 ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
788 return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
791 /// CreateArtificialType - Create a new DIType with "artificial" flag set.
792 DIType DIFactory::CreateArtificialType(DIType Ty) {
793 if (Ty.isArtificial())
796 SmallVector<Value *, 9> Elts;
798 assert (N && "Unexpected input DIType!");
799 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
800 if (Value *V = N->getOperand(i))
803 Elts.push_back(Constant::getNullValue(Type::getInt32Ty(VMContext)));
806 unsigned CurFlags = Ty.getFlags();
807 CurFlags = CurFlags | DIType::FlagArtificial;
809 // Flags are stored at this slot.
810 Elts[8] = ConstantInt::get(Type::getInt32Ty(VMContext), CurFlags);
812 return DIType(MDNode::get(VMContext, Elts.data(), Elts.size()));
815 /// CreateDerivedType - Create a derived type like const qualified type,
816 /// pointer, typedef, etc.
817 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
818 DIDescriptor Context,
823 uint64_t AlignInBits,
824 uint64_t OffsetInBits,
826 DIType DerivedFrom) {
830 MDString::get(VMContext, Name),
832 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
833 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
834 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
835 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
836 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
839 return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
843 /// CreateDerivedType - Create a derived type like const qualified type,
844 /// pointer, typedef, etc.
845 DIDerivedType DIFactory::CreateDerivedTypeEx(unsigned Tag,
846 DIDescriptor Context,
850 Constant *SizeInBits,
851 Constant *AlignInBits,
852 Constant *OffsetInBits,
854 DIType DerivedFrom) {
858 MDString::get(VMContext, Name),
860 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
864 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
867 return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
871 /// CreateCompositeType - Create a composite type like array, struct, etc.
872 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
873 DIDescriptor Context,
878 uint64_t AlignInBits,
879 uint64_t OffsetInBits,
883 unsigned RuntimeLang,
884 MDNode *ContainingType) {
889 MDString::get(VMContext, Name),
891 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
892 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
893 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
894 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
895 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
898 ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang),
901 return DICompositeType(MDNode::get(VMContext, &Elts[0], 13));
905 /// CreateCompositeType - Create a composite type like array, struct, etc.
906 DICompositeType DIFactory::CreateCompositeTypeEx(unsigned Tag,
907 DIDescriptor Context,
911 Constant *SizeInBits,
912 Constant *AlignInBits,
913 Constant *OffsetInBits,
917 unsigned RuntimeLang) {
922 MDString::get(VMContext, Name),
924 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
928 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
931 ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang)
933 return DICompositeType(MDNode::get(VMContext, &Elts[0], 12));
937 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
938 /// See comments in DISubprogram for descriptions of these fields. This
939 /// method does not unique the generated descriptors.
940 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context,
942 StringRef DisplayName,
943 StringRef LinkageName,
945 unsigned LineNo, DIType Ty,
948 unsigned VK, unsigned VIndex,
949 DIType ContainingType,
955 GetTagConstant(dwarf::DW_TAG_subprogram),
956 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
958 MDString::get(VMContext, Name),
959 MDString::get(VMContext, DisplayName),
960 MDString::get(VMContext, LinkageName),
962 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
964 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
965 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
966 ConstantInt::get(Type::getInt32Ty(VMContext), (unsigned)VK),
967 ConstantInt::get(Type::getInt32Ty(VMContext), VIndex),
969 ConstantInt::get(Type::getInt1Ty(VMContext), isArtificial),
970 ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
973 MDNode *Node = MDNode::get(VMContext, &Elts[0], 17);
975 // Create a named metadata so that we do not lose this mdnode.
976 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.sp");
977 NMD->addOperand(Node);
978 return DISubprogram(Node);
981 /// CreateSubprogramDefinition - Create new subprogram descriptor for the
982 /// given declaration.
983 DISubprogram DIFactory::CreateSubprogramDefinition(DISubprogram &SPDeclaration){
984 if (SPDeclaration.isDefinition())
985 return DISubprogram(SPDeclaration);
987 MDNode *DeclNode = SPDeclaration;
989 GetTagConstant(dwarf::DW_TAG_subprogram),
990 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
991 DeclNode->getOperand(2), // Context
992 DeclNode->getOperand(3), // Name
993 DeclNode->getOperand(4), // DisplayName
994 DeclNode->getOperand(5), // LinkageName
995 DeclNode->getOperand(6), // CompileUnit
996 DeclNode->getOperand(7), // LineNo
997 DeclNode->getOperand(8), // Type
998 DeclNode->getOperand(9), // isLocalToUnit
999 ConstantInt::get(Type::getInt1Ty(VMContext), true),
1000 DeclNode->getOperand(11), // Virtuality
1001 DeclNode->getOperand(12), // VIndex
1002 DeclNode->getOperand(13), // Containting Type
1003 DeclNode->getOperand(14), // isArtificial
1004 DeclNode->getOperand(15), // isOptimized
1005 SPDeclaration.getFunction()
1007 MDNode *Node =MDNode::get(VMContext, &Elts[0], 16);
1009 // Create a named metadata so that we do not lose this mdnode.
1010 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.sp");
1011 NMD->addOperand(Node);
1012 return DISubprogram(Node);
1015 /// CreateGlobalVariable - Create a new descriptor for the specified global.
1017 DIFactory::CreateGlobalVariable(DIDescriptor Context, StringRef Name,
1018 StringRef DisplayName,
1019 StringRef LinkageName,
1021 unsigned LineNo, DIType Ty,bool isLocalToUnit,
1022 bool isDefinition, llvm::GlobalVariable *Val) {
1024 GetTagConstant(dwarf::DW_TAG_variable),
1025 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
1027 MDString::get(VMContext, Name),
1028 MDString::get(VMContext, DisplayName),
1029 MDString::get(VMContext, LinkageName),
1031 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1033 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
1034 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
1038 Value *const *Vs = &Elts[0];
1039 MDNode *Node = MDNode::get(VMContext,Vs, 12);
1041 // Create a named metadata so that we do not lose this mdnode.
1042 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.gv");
1043 NMD->addOperand(Node);
1045 return DIGlobalVariable(Node);
1049 /// CreateVariable - Create a new descriptor for the specified variable.
1050 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
1054 DIType Ty, bool AlwaysPreserve) {
1056 GetTagConstant(Tag),
1058 MDString::get(VMContext, Name),
1060 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1063 MDNode *Node = MDNode::get(VMContext, &Elts[0], 6);
1064 if (AlwaysPreserve) {
1065 // The optimizer may remove local variable. If there is an interest
1066 // to preserve variable info in such situation then stash it in a
1068 DISubprogram Fn(getDISubprogram(Context));
1069 StringRef FName = "fn";
1070 if (Fn.getFunction())
1071 FName = Fn.getFunction()->getName();
1073 if (FName.startswith(StringRef(&One, 1)))
1074 FName = FName.substr(1);
1076 SmallString<32> Out;
1077 NamedMDNode *FnLocals =
1078 M.getOrInsertNamedMetadata(Twine("llvm.dbg.lv.", FName).toStringRef(Out));
1079 FnLocals->addOperand(Node);
1081 return DIVariable(Node);
1085 /// CreateComplexVariable - Create a new descriptor for the specified variable
1086 /// which has a complex address expression for its address.
1087 DIVariable DIFactory::CreateComplexVariable(unsigned Tag, DIDescriptor Context,
1088 const std::string &Name,
1092 SmallVector<Value *, 9> &addr) {
1093 SmallVector<Value *, 9> Elts;
1094 Elts.push_back(GetTagConstant(Tag));
1095 Elts.push_back(Context);
1096 Elts.push_back(MDString::get(VMContext, Name));
1098 Elts.push_back(ConstantInt::get(Type::getInt32Ty(VMContext), LineNo));
1100 Elts.insert(Elts.end(), addr.begin(), addr.end());
1102 return DIVariable(MDNode::get(VMContext, &Elts[0], 6+addr.size()));
1106 /// CreateBlock - This creates a descriptor for a lexical block with the
1107 /// specified parent VMContext.
1108 DILexicalBlock DIFactory::CreateLexicalBlock(DIDescriptor Context,
1109 DIFile F, unsigned LineNo,
1111 // Defeat MDNode uniqing for lexical blocks.
1112 static unsigned int unique_id = 0;
1114 GetTagConstant(dwarf::DW_TAG_lexical_block),
1116 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1117 ConstantInt::get(Type::getInt32Ty(VMContext), Col),
1119 ConstantInt::get(Type::getInt32Ty(VMContext), unique_id++)
1121 return DILexicalBlock(MDNode::get(VMContext, &Elts[0], 6));
1124 /// CreateNameSpace - This creates new descriptor for a namespace
1125 /// with the specified parent context.
1126 DINameSpace DIFactory::CreateNameSpace(DIDescriptor Context, StringRef Name,
1130 GetTagConstant(dwarf::DW_TAG_namespace),
1132 MDString::get(VMContext, Name),
1134 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo)
1136 return DINameSpace(MDNode::get(VMContext, &Elts[0], 5));
1139 /// CreateLocation - Creates a debug info location.
1140 DILocation DIFactory::CreateLocation(unsigned LineNo, unsigned ColumnNo,
1141 DIScope S, DILocation OrigLoc) {
1143 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1144 ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo),
1148 return DILocation(MDNode::get(VMContext, &Elts[0], 4));
1151 //===----------------------------------------------------------------------===//
1152 // DIFactory: Routines for inserting code into a function
1153 //===----------------------------------------------------------------------===//
1155 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1156 Instruction *DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1157 Instruction *InsertBefore) {
1158 assert(Storage && "no storage passed to dbg.declare");
1159 assert(D.Verify() && "empty DIVariable passed to dbg.declare");
1161 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1163 Value *Args[] = { MDNode::get(Storage->getContext(), &Storage, 1),
1165 return CallInst::Create(DeclareFn, Args, Args+2, "", InsertBefore);
1168 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1169 Instruction *DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1170 BasicBlock *InsertAtEnd) {
1171 assert(Storage && "no storage passed to dbg.declare");
1172 assert(D.Verify() && "invalid DIVariable passed to dbg.declare");
1174 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1176 Value *Args[] = { MDNode::get(Storage->getContext(), &Storage, 1),
1179 // If this block already has a terminator then insert this intrinsic
1180 // before the terminator.
1181 if (TerminatorInst *T = InsertAtEnd->getTerminator())
1182 return CallInst::Create(DeclareFn, Args, Args+2, "", T);
1184 return CallInst::Create(DeclareFn, Args, Args+2, "", InsertAtEnd);}
1186 /// InsertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
1187 Instruction *DIFactory::InsertDbgValueIntrinsic(Value *V, uint64_t Offset,
1189 Instruction *InsertBefore) {
1190 assert(V && "no value passed to dbg.value");
1191 assert(D.Verify() && "invalid DIVariable passed to dbg.value");
1193 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1195 Value *Args[] = { MDNode::get(V->getContext(), &V, 1),
1196 ConstantInt::get(Type::getInt64Ty(V->getContext()), Offset),
1198 return CallInst::Create(ValueFn, Args, Args+3, "", InsertBefore);
1201 /// InsertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
1202 Instruction *DIFactory::InsertDbgValueIntrinsic(Value *V, uint64_t Offset,
1204 BasicBlock *InsertAtEnd) {
1205 assert(V && "no value passed to dbg.value");
1206 assert(D.Verify() && "invalid DIVariable passed to dbg.value");
1208 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1210 Value *Args[] = { MDNode::get(V->getContext(), &V, 1),
1211 ConstantInt::get(Type::getInt64Ty(V->getContext()), Offset),
1213 return CallInst::Create(ValueFn, Args, Args+3, "", InsertAtEnd);
1216 //===----------------------------------------------------------------------===//
1217 // DebugInfoFinder implementations.
1218 //===----------------------------------------------------------------------===//
1220 /// processModule - Process entire module and collect debug info.
1221 void DebugInfoFinder::processModule(Module &M) {
1222 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1223 for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI)
1224 for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE;
1226 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
1227 processDeclare(DDI);
1229 DebugLoc Loc = BI->getDebugLoc();
1230 if (Loc.isUnknown())
1233 LLVMContext &Ctx = BI->getContext();
1234 DIDescriptor Scope(Loc.getScope(Ctx));
1236 if (Scope.isCompileUnit())
1237 addCompileUnit(DICompileUnit(Scope));
1238 else if (Scope.isSubprogram())
1239 processSubprogram(DISubprogram(Scope));
1240 else if (Scope.isLexicalBlock())
1241 processLexicalBlock(DILexicalBlock(Scope));
1243 if (MDNode *IA = Loc.getInlinedAt(Ctx))
1244 processLocation(DILocation(IA));
1247 if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv")) {
1248 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1249 DIGlobalVariable DIG(cast<MDNode>(NMD->getOperand(i)));
1250 if (addGlobalVariable(DIG)) {
1251 addCompileUnit(DIG.getCompileUnit());
1252 processType(DIG.getType());
1257 if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.sp"))
1258 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
1259 processSubprogram(DISubprogram(NMD->getOperand(i)));
1262 /// processLocation - Process DILocation.
1263 void DebugInfoFinder::processLocation(DILocation Loc) {
1264 if (!Loc.Verify()) return;
1265 DIDescriptor S(Loc.getScope());
1266 if (S.isCompileUnit())
1267 addCompileUnit(DICompileUnit(S));
1268 else if (S.isSubprogram())
1269 processSubprogram(DISubprogram(S));
1270 else if (S.isLexicalBlock())
1271 processLexicalBlock(DILexicalBlock(S));
1272 processLocation(Loc.getOrigLocation());
1275 /// processType - Process DIType.
1276 void DebugInfoFinder::processType(DIType DT) {
1280 addCompileUnit(DT.getCompileUnit());
1281 if (DT.isCompositeType()) {
1282 DICompositeType DCT(DT);
1283 processType(DCT.getTypeDerivedFrom());
1284 DIArray DA = DCT.getTypeArray();
1285 for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
1286 DIDescriptor D = DA.getElement(i);
1288 processType(DIType(D));
1289 else if (D.isSubprogram())
1290 processSubprogram(DISubprogram(D));
1292 } else if (DT.isDerivedType()) {
1293 DIDerivedType DDT(DT);
1294 processType(DDT.getTypeDerivedFrom());
1298 /// processLexicalBlock
1299 void DebugInfoFinder::processLexicalBlock(DILexicalBlock LB) {
1300 DIScope Context = LB.getContext();
1301 if (Context.isLexicalBlock())
1302 return processLexicalBlock(DILexicalBlock(Context));
1304 return processSubprogram(DISubprogram(Context));
1307 /// processSubprogram - Process DISubprogram.
1308 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
1309 if (!addSubprogram(SP))
1311 addCompileUnit(SP.getCompileUnit());
1312 processType(SP.getType());
1315 /// processDeclare - Process DbgDeclareInst.
1316 void DebugInfoFinder::processDeclare(DbgDeclareInst *DDI) {
1317 MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
1321 if (!DV.isVariable())
1324 if (!NodesSeen.insert(DV))
1327 addCompileUnit(DIVariable(N).getCompileUnit());
1328 processType(DIVariable(N).getType());
1331 /// addType - Add type into Tys.
1332 bool DebugInfoFinder::addType(DIType DT) {
1336 if (!NodesSeen.insert(DT))
1343 /// addCompileUnit - Add compile unit into CUs.
1344 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1348 if (!NodesSeen.insert(CU))
1355 /// addGlobalVariable - Add global variable into GVs.
1356 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1357 if (!DIDescriptor(DIG).isGlobalVariable())
1360 if (!NodesSeen.insert(DIG))
1367 // addSubprogram - Add subprgoram into SPs.
1368 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1369 if (!DIDescriptor(SP).isSubprogram())
1372 if (!NodesSeen.insert(SP))
1379 /// Find the debug info descriptor corresponding to this global variable.
1380 static Value *findDbgGlobalDeclare(GlobalVariable *V) {
1381 const Module *M = V->getParent();
1382 NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv");
1386 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1387 DIDescriptor DIG(cast<MDNode>(NMD->getOperand(i)));
1388 if (!DIG.isGlobalVariable())
1390 if (DIGlobalVariable(DIG).getGlobal() == V)
1396 /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
1397 /// It looks through pointer casts too.
1398 static const DbgDeclareInst *findDbgDeclare(const Value *V) {
1399 V = V->stripPointerCasts();
1401 if (!isa<Instruction>(V) && !isa<Argument>(V))
1404 const Function *F = NULL;
1405 if (const Instruction *I = dyn_cast<Instruction>(V))
1406 F = I->getParent()->getParent();
1407 else if (const Argument *A = dyn_cast<Argument>(V))
1410 for (Function::const_iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
1411 for (BasicBlock::const_iterator BI = (*FI).begin(), BE = (*FI).end();
1413 if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
1414 if (DDI->getAddress() == V)
1420 bool llvm::getLocationInfo(const Value *V, std::string &DisplayName,
1421 std::string &Type, unsigned &LineNo,
1422 std::string &File, std::string &Dir) {
1426 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
1427 Value *DIGV = findDbgGlobalDeclare(GV);
1428 if (!DIGV) return false;
1429 DIGlobalVariable Var(cast<MDNode>(DIGV));
1431 StringRef D = Var.getDisplayName();
1434 LineNo = Var.getLineNumber();
1435 Unit = Var.getCompileUnit();
1436 TypeD = Var.getType();
1438 const DbgDeclareInst *DDI = findDbgDeclare(V);
1439 if (!DDI) return false;
1440 DIVariable Var(cast<MDNode>(DDI->getVariable()));
1442 StringRef D = Var.getName();
1445 LineNo = Var.getLineNumber();
1446 Unit = Var.getCompileUnit();
1447 TypeD = Var.getType();
1450 StringRef T = TypeD.getName();
1453 StringRef F = Unit.getFilename();
1456 StringRef D = Unit.getDirectory();
1462 /// getDISubprogram - Find subprogram that is enclosing this scope.
1463 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
1464 DIDescriptor D(Scope);
1465 if (D.isSubprogram())
1466 return DISubprogram(Scope);
1468 if (D.isLexicalBlock())
1469 return getDISubprogram(DILexicalBlock(Scope).getContext());
1471 return DISubprogram();
1474 /// getDICompositeType - Find underlying composite type.
1475 DICompositeType llvm::getDICompositeType(DIType T) {
1476 if (T.isCompositeType())
1477 return DICompositeType(T);
1479 if (T.isDerivedType())
1480 return getDICompositeType(DIDerivedType(T).getTypeDerivedFrom());
1482 return DICompositeType();