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/LLVMContext.h"
22 #include "llvm/Module.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/Support/Dwarf.h"
26 #include "llvm/Support/DebugLoc.h"
27 #include "llvm/Support/raw_ostream.h"
29 using namespace llvm::dwarf;
31 //===----------------------------------------------------------------------===//
33 //===----------------------------------------------------------------------===//
35 /// ValidDebugInfo - Return true if V represents valid debug info value.
36 /// FIXME : Add DIDescriptor.isValid()
37 bool DIDescriptor::ValidDebugInfo(MDNode *N, CodeGenOpt::Level OptLevel) {
43 // Check current version. Allow Version6 for now.
44 unsigned Version = DI.getVersion();
45 if (Version != LLVMDebugVersion && Version != LLVMDebugVersion6)
48 unsigned Tag = DI.getTag();
51 assert(DIVariable(N).Verify() && "Invalid DebugInfo value");
53 case DW_TAG_compile_unit:
54 assert(DICompileUnit(N).Verify() && "Invalid DebugInfo value");
56 case DW_TAG_subprogram:
57 assert(DISubprogram(N).Verify() && "Invalid DebugInfo value");
59 case DW_TAG_lexical_block:
60 // FIXME: This interfers with the quality of generated code during
62 if (OptLevel != CodeGenOpt::None)
72 DIDescriptor::DIDescriptor(MDNode *N, unsigned RequiredTag) {
75 // If this is non-null, check to see if the Tag matches. If not, set to null.
76 if (N && getTag() != RequiredTag) {
82 DIDescriptor::getStringField(unsigned Elt) const {
86 if (Elt < DbgNode->getNumElements())
87 if (MDString *MDS = dyn_cast_or_null<MDString>(DbgNode->getElement(Elt)))
88 return MDS->getString();
93 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
97 if (Elt < DbgNode->getNumElements())
98 if (ConstantInt *CI = dyn_cast<ConstantInt>(DbgNode->getElement(Elt)))
99 return CI->getZExtValue();
104 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
106 return DIDescriptor();
108 if (Elt < DbgNode->getNumElements() && DbgNode->getElement(Elt))
109 return DIDescriptor(dyn_cast<MDNode>(DbgNode->getElement(Elt)));
111 return DIDescriptor();
114 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
118 if (Elt < DbgNode->getNumElements())
119 return dyn_cast_or_null<GlobalVariable>(DbgNode->getElement(Elt));
123 //===----------------------------------------------------------------------===//
125 //===----------------------------------------------------------------------===//
127 /// isBasicType - Return true if the specified tag is legal for
129 bool DIDescriptor::isBasicType() const {
130 assert (!isNull() && "Invalid descriptor!");
131 unsigned Tag = getTag();
133 return Tag == dwarf::DW_TAG_base_type;
136 /// isDerivedType - Return true if the specified tag is legal for DIDerivedType.
137 bool DIDescriptor::isDerivedType() const {
138 assert (!isNull() && "Invalid descriptor!");
139 unsigned Tag = getTag();
142 case dwarf::DW_TAG_typedef:
143 case dwarf::DW_TAG_pointer_type:
144 case dwarf::DW_TAG_reference_type:
145 case dwarf::DW_TAG_const_type:
146 case dwarf::DW_TAG_volatile_type:
147 case dwarf::DW_TAG_restrict_type:
148 case dwarf::DW_TAG_member:
149 case dwarf::DW_TAG_inheritance:
152 // CompositeTypes are currently modelled as DerivedTypes.
153 return isCompositeType();
157 /// isCompositeType - Return true if the specified tag is legal for
159 bool DIDescriptor::isCompositeType() const {
160 assert (!isNull() && "Invalid descriptor!");
161 unsigned Tag = getTag();
164 case dwarf::DW_TAG_array_type:
165 case dwarf::DW_TAG_structure_type:
166 case dwarf::DW_TAG_union_type:
167 case dwarf::DW_TAG_enumeration_type:
168 case dwarf::DW_TAG_vector_type:
169 case dwarf::DW_TAG_subroutine_type:
170 case dwarf::DW_TAG_class_type:
177 /// isVariable - Return true if the specified tag is legal for DIVariable.
178 bool DIDescriptor::isVariable() const {
179 assert (!isNull() && "Invalid descriptor!");
180 unsigned Tag = getTag();
183 case dwarf::DW_TAG_auto_variable:
184 case dwarf::DW_TAG_arg_variable:
185 case dwarf::DW_TAG_return_variable:
192 /// isType - Return true if the specified tag is legal for DIType.
193 bool DIDescriptor::isType() const {
194 return isBasicType() || isCompositeType() || isDerivedType();
197 /// isSubprogram - Return true if the specified tag is legal for
199 bool DIDescriptor::isSubprogram() const {
200 assert (!isNull() && "Invalid descriptor!");
201 unsigned Tag = getTag();
203 return Tag == dwarf::DW_TAG_subprogram;
206 /// isGlobalVariable - Return true if the specified tag is legal for
207 /// DIGlobalVariable.
208 bool DIDescriptor::isGlobalVariable() const {
209 assert (!isNull() && "Invalid descriptor!");
210 unsigned Tag = getTag();
212 return Tag == dwarf::DW_TAG_variable;
215 /// isGlobal - Return true if the specified tag is legal for DIGlobal.
216 bool DIDescriptor::isGlobal() const {
217 return isGlobalVariable();
220 /// isScope - Return true if the specified tag is one of the scope
222 bool DIDescriptor::isScope() const {
223 assert (!isNull() && "Invalid descriptor!");
224 unsigned Tag = getTag();
227 case dwarf::DW_TAG_compile_unit:
228 case dwarf::DW_TAG_lexical_block:
229 case dwarf::DW_TAG_subprogram:
237 /// isCompileUnit - Return true if the specified tag is DW_TAG_compile_unit.
238 bool DIDescriptor::isCompileUnit() const {
239 assert (!isNull() && "Invalid descriptor!");
240 unsigned Tag = getTag();
242 return Tag == dwarf::DW_TAG_compile_unit;
245 /// isLexicalBlock - Return true if the specified tag is DW_TAG_lexical_block.
246 bool DIDescriptor::isLexicalBlock() const {
247 assert (!isNull() && "Invalid descriptor!");
248 unsigned Tag = getTag();
250 return Tag == dwarf::DW_TAG_lexical_block;
253 /// isSubrange - Return true if the specified tag is DW_TAG_subrange_type.
254 bool DIDescriptor::isSubrange() const {
255 assert (!isNull() && "Invalid descriptor!");
256 unsigned Tag = getTag();
258 return Tag == dwarf::DW_TAG_subrange_type;
261 /// isEnumerator - Return true if the specified tag is DW_TAG_enumerator.
262 bool DIDescriptor::isEnumerator() const {
263 assert (!isNull() && "Invalid descriptor!");
264 unsigned Tag = getTag();
266 return Tag == dwarf::DW_TAG_enumerator;
269 //===----------------------------------------------------------------------===//
270 // Simple Descriptor Constructors and other Methods
271 //===----------------------------------------------------------------------===//
273 DIType::DIType(MDNode *N) : DIDescriptor(N) {
275 if (!isBasicType() && !isDerivedType() && !isCompositeType()) {
280 unsigned DIArray::getNumElements() const {
281 assert (DbgNode && "Invalid DIArray");
282 return DbgNode->getNumElements();
285 /// replaceAllUsesWith - Replace all uses of debug info referenced by
286 /// this descriptor. After this completes, the current debug info value
288 void DIDerivedType::replaceAllUsesWith(DIDescriptor &D) {
292 assert (!D.isNull() && "Can not replace with null");
294 // Since we use a TrackingVH for the node, its easy for clients to manufacture
295 // legitimate situations where they want to replaceAllUsesWith() on something
296 // which, due to uniquing, has merged with the source. We shield clients from
297 // this detail by allowing a value to be replaced with replaceAllUsesWith()
299 if (getNode() != D.getNode()) {
300 MDNode *Node = DbgNode;
301 Node->replaceAllUsesWith(D.getNode());
306 /// Verify - Verify that a compile unit is well formed.
307 bool DICompileUnit::Verify() const {
310 StringRef N = getFilename();
313 // It is possible that directory and produce string is empty.
317 /// Verify - Verify that a type descriptor is well formed.
318 bool DIType::Verify() const {
321 if (getContext().isNull())
324 DICompileUnit CU = getCompileUnit();
325 if (!CU.isNull() && !CU.Verify())
330 /// Verify - Verify that a composite type descriptor is well formed.
331 bool DICompositeType::Verify() const {
334 if (getContext().isNull())
337 DICompileUnit CU = getCompileUnit();
338 if (!CU.isNull() && !CU.Verify())
343 /// Verify - Verify that a subprogram descriptor is well formed.
344 bool DISubprogram::Verify() const {
348 if (getContext().isNull())
351 DICompileUnit CU = getCompileUnit();
355 DICompositeType Ty = getType();
356 if (!Ty.isNull() && !Ty.Verify())
361 /// Verify - Verify that a global variable descriptor is well formed.
362 bool DIGlobalVariable::Verify() const {
366 if (getDisplayName().empty())
369 if (getContext().isNull())
372 DICompileUnit CU = getCompileUnit();
373 if (!CU.isNull() && !CU.Verify())
376 DIType Ty = getType();
386 /// Verify - Verify that a variable descriptor is well formed.
387 bool DIVariable::Verify() const {
391 if (getContext().isNull())
394 DIType Ty = getType();
401 /// getOriginalTypeSize - If this type is derived from a base type then
402 /// return base type size.
403 uint64_t DIDerivedType::getOriginalTypeSize() const {
404 unsigned Tag = getTag();
405 if (Tag == dwarf::DW_TAG_member || Tag == dwarf::DW_TAG_typedef ||
406 Tag == dwarf::DW_TAG_const_type || Tag == dwarf::DW_TAG_volatile_type ||
407 Tag == dwarf::DW_TAG_restrict_type) {
408 DIType BaseType = getTypeDerivedFrom();
409 // If this type is not derived from any type then take conservative
411 if (BaseType.isNull())
412 return getSizeInBits();
413 if (BaseType.isDerivedType())
414 return DIDerivedType(BaseType.getNode()).getOriginalTypeSize();
416 return BaseType.getSizeInBits();
419 return getSizeInBits();
422 /// describes - Return true if this subprogram provides debugging
423 /// information for the function F.
424 bool DISubprogram::describes(const Function *F) {
425 assert (F && "Invalid function");
426 StringRef Name = getLinkageName();
429 if (F->getName() == Name)
434 StringRef DIScope::getFilename() const {
435 if (isLexicalBlock())
436 return DILexicalBlock(DbgNode).getFilename();
437 else if (isSubprogram())
438 return DISubprogram(DbgNode).getFilename();
439 else if (isCompileUnit())
440 return DICompileUnit(DbgNode).getFilename();
442 assert (0 && "Invalid DIScope!");
446 StringRef DIScope::getDirectory() const {
447 if (isLexicalBlock())
448 return DILexicalBlock(DbgNode).getDirectory();
449 else if (isSubprogram())
450 return DISubprogram(DbgNode).getDirectory();
451 else if (isCompileUnit())
452 return DICompileUnit(DbgNode).getDirectory();
454 assert (0 && "Invalid DIScope!");
458 //===----------------------------------------------------------------------===//
459 // DIDescriptor: dump routines for all descriptors.
460 //===----------------------------------------------------------------------===//
463 /// dump - Print descriptor.
464 void DIDescriptor::dump() const {
465 errs() << "[" << dwarf::TagString(getTag()) << "] ";
466 errs().write_hex((intptr_t) &*DbgNode) << ']';
469 /// dump - Print compile unit.
470 void DICompileUnit::dump() const {
472 errs() << " [" << dwarf::LanguageString(getLanguage()) << "] ";
474 errs() << " [" << getDirectory() << "/" << getFilename() << " ]";
477 /// dump - Print type.
478 void DIType::dump() const {
479 if (isNull()) return;
481 StringRef Res = getName();
483 errs() << " [" << Res << "] ";
485 unsigned Tag = getTag();
486 errs() << " [" << dwarf::TagString(Tag) << "] ";
488 // TODO : Print context
489 getCompileUnit().dump();
491 << getLineNumber() << ", "
492 << getSizeInBits() << ", "
493 << getAlignInBits() << ", "
498 errs() << " [private] ";
499 else if (isProtected())
500 errs() << " [protected] ";
506 DIBasicType(DbgNode).dump();
507 else if (isDerivedType())
508 DIDerivedType(DbgNode).dump();
509 else if (isCompositeType())
510 DICompositeType(DbgNode).dump();
512 errs() << "Invalid DIType\n";
519 /// dump - Print basic type.
520 void DIBasicType::dump() const {
521 errs() << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
524 /// dump - Print derived type.
525 void DIDerivedType::dump() const {
526 errs() << "\n\t Derived From: "; getTypeDerivedFrom().dump();
529 /// dump - Print composite type.
530 void DICompositeType::dump() const {
531 DIArray A = getTypeArray();
534 errs() << " [" << A.getNumElements() << " elements]";
537 /// dump - Print global.
538 void DIGlobal::dump() const {
539 StringRef Res = getName();
541 errs() << " [" << Res << "] ";
543 unsigned Tag = getTag();
544 errs() << " [" << dwarf::TagString(Tag) << "] ";
546 // TODO : Print context
547 getCompileUnit().dump();
548 errs() << " [" << getLineNumber() << "] ";
551 errs() << " [local] ";
556 if (isGlobalVariable())
557 DIGlobalVariable(DbgNode).dump();
562 /// dump - Print subprogram.
563 void DISubprogram::dump() const {
564 StringRef Res = getName();
566 errs() << " [" << Res << "] ";
568 unsigned Tag = getTag();
569 errs() << " [" << dwarf::TagString(Tag) << "] ";
571 // TODO : Print context
572 getCompileUnit().dump();
573 errs() << " [" << getLineNumber() << "] ";
576 errs() << " [local] ";
584 /// dump - Print global variable.
585 void DIGlobalVariable::dump() const {
591 /// dump - Print variable.
592 void DIVariable::dump() const {
593 StringRef Res = getName();
595 errs() << " [" << Res << "] ";
597 getCompileUnit().dump();
598 errs() << " [" << getLineNumber() << "] ";
602 // FIXME: Dump complex addresses
605 //===----------------------------------------------------------------------===//
606 // DIFactory: Basic Helpers
607 //===----------------------------------------------------------------------===//
609 DIFactory::DIFactory(Module &m)
610 : M(m), VMContext(M.getContext()), DeclareFn(0) {
611 EmptyStructPtr = PointerType::getUnqual(StructType::get(VMContext));
614 Constant *DIFactory::GetTagConstant(unsigned TAG) {
615 assert((TAG & LLVMDebugVersionMask) == 0 &&
616 "Tag too large for debug encoding!");
617 return ConstantInt::get(Type::getInt32Ty(VMContext), TAG | LLVMDebugVersion);
620 //===----------------------------------------------------------------------===//
621 // DIFactory: Primary Constructors
622 //===----------------------------------------------------------------------===//
624 /// GetOrCreateArray - Create an descriptor for an array of descriptors.
625 /// This implicitly uniques the arrays created.
626 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
627 SmallVector<Value*, 16> Elts;
630 Elts.push_back(llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)));
632 for (unsigned i = 0; i != NumTys; ++i)
633 Elts.push_back(Tys[i].getNode());
635 return DIArray(MDNode::get(VMContext,Elts.data(), Elts.size()));
638 /// GetOrCreateSubrange - Create a descriptor for a value range. This
639 /// implicitly uniques the values returned.
640 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
642 GetTagConstant(dwarf::DW_TAG_subrange_type),
643 ConstantInt::get(Type::getInt64Ty(VMContext), Lo),
644 ConstantInt::get(Type::getInt64Ty(VMContext), Hi)
647 return DISubrange(MDNode::get(VMContext, &Elts[0], 3));
652 /// CreateCompileUnit - Create a new descriptor for the specified compile
653 /// unit. Note that this does not unique compile units within the module.
654 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
661 unsigned RunTimeVer) {
663 GetTagConstant(dwarf::DW_TAG_compile_unit),
664 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
665 ConstantInt::get(Type::getInt32Ty(VMContext), LangID),
666 MDString::get(VMContext, Filename),
667 MDString::get(VMContext, Directory),
668 MDString::get(VMContext, Producer),
669 ConstantInt::get(Type::getInt1Ty(VMContext), isMain),
670 ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
671 MDString::get(VMContext, Flags),
672 ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeVer)
675 return DICompileUnit(MDNode::get(VMContext, &Elts[0], 10));
678 /// CreateEnumerator - Create a single enumerator value.
679 DIEnumerator DIFactory::CreateEnumerator(StringRef Name, uint64_t Val){
681 GetTagConstant(dwarf::DW_TAG_enumerator),
682 MDString::get(VMContext, Name),
683 ConstantInt::get(Type::getInt64Ty(VMContext), Val)
685 return DIEnumerator(MDNode::get(VMContext, &Elts[0], 3));
689 /// CreateBasicType - Create a basic type like int, float, etc.
690 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
692 DICompileUnit CompileUnit,
695 uint64_t AlignInBits,
696 uint64_t OffsetInBits, unsigned Flags,
699 GetTagConstant(dwarf::DW_TAG_base_type),
701 MDString::get(VMContext, Name),
702 CompileUnit.getNode(),
703 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
704 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
705 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
706 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
707 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
708 ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
710 return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
714 /// CreateBasicType - Create a basic type like int, float, etc.
715 DIBasicType DIFactory::CreateBasicTypeEx(DIDescriptor Context,
717 DICompileUnit CompileUnit,
719 Constant *SizeInBits,
720 Constant *AlignInBits,
721 Constant *OffsetInBits, unsigned Flags,
724 GetTagConstant(dwarf::DW_TAG_base_type),
726 MDString::get(VMContext, Name),
727 CompileUnit.getNode(),
728 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
732 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
733 ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
735 return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
739 /// CreateDerivedType - Create a derived type like const qualified type,
740 /// pointer, typedef, etc.
741 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
742 DIDescriptor Context,
744 DICompileUnit CompileUnit,
747 uint64_t AlignInBits,
748 uint64_t OffsetInBits,
750 DIType DerivedFrom) {
754 MDString::get(VMContext, Name),
755 CompileUnit.getNode(),
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 DerivedFrom.getNode(),
763 return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
767 /// CreateDerivedType - Create a derived type like const qualified type,
768 /// pointer, typedef, etc.
769 DIDerivedType DIFactory::CreateDerivedTypeEx(unsigned Tag,
770 DIDescriptor Context,
772 DICompileUnit CompileUnit,
774 Constant *SizeInBits,
775 Constant *AlignInBits,
776 Constant *OffsetInBits,
778 DIType DerivedFrom) {
782 MDString::get(VMContext, Name),
783 CompileUnit.getNode(),
784 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
788 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
789 DerivedFrom.getNode(),
791 return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
795 /// CreateCompositeType - Create a composite type like array, struct, etc.
796 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
797 DIDescriptor Context,
799 DICompileUnit CompileUnit,
802 uint64_t AlignInBits,
803 uint64_t OffsetInBits,
807 unsigned RuntimeLang) {
812 MDString::get(VMContext, Name),
813 CompileUnit.getNode(),
814 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
815 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
816 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
817 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
818 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
819 DerivedFrom.getNode(),
821 ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang)
823 return DICompositeType(MDNode::get(VMContext, &Elts[0], 12));
827 /// CreateCompositeType - Create a composite type like array, struct, etc.
828 DICompositeType DIFactory::CreateCompositeTypeEx(unsigned Tag,
829 DIDescriptor Context,
831 DICompileUnit CompileUnit,
833 Constant *SizeInBits,
834 Constant *AlignInBits,
835 Constant *OffsetInBits,
839 unsigned RuntimeLang) {
844 MDString::get(VMContext, Name),
845 CompileUnit.getNode(),
846 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
850 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
851 DerivedFrom.getNode(),
853 ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang)
855 return DICompositeType(MDNode::get(VMContext, &Elts[0], 12));
859 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
860 /// See comments in DISubprogram for descriptions of these fields. This
861 /// method does not unique the generated descriptors.
862 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context,
864 StringRef DisplayName,
865 StringRef LinkageName,
866 DICompileUnit CompileUnit,
867 unsigned LineNo, DIType Type,
872 GetTagConstant(dwarf::DW_TAG_subprogram),
873 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
875 MDString::get(VMContext, Name),
876 MDString::get(VMContext, DisplayName),
877 MDString::get(VMContext, LinkageName),
878 CompileUnit.getNode(),
879 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
881 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
882 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition)
884 return DISubprogram(MDNode::get(VMContext, &Elts[0], 11));
887 /// CreateSubprogramDefinition - Create new subprogram descriptor for the
888 /// given declaration.
889 DISubprogram DIFactory::CreateSubprogramDefinition(DISubprogram &SPDeclaration) {
890 if (SPDeclaration.isDefinition())
891 return DISubprogram(SPDeclaration.getNode());
893 MDNode *DeclNode = SPDeclaration.getNode();
895 GetTagConstant(dwarf::DW_TAG_subprogram),
896 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
897 DeclNode->getElement(2), // Context
898 DeclNode->getElement(3), // Name
899 DeclNode->getElement(4), // DisplayName
900 DeclNode->getElement(5), // LinkageName
901 DeclNode->getElement(6), // CompileUnit
902 DeclNode->getElement(7), // LineNo
903 DeclNode->getElement(8), // Type
904 DeclNode->getElement(9), // isLocalToUnit
905 ConstantInt::get(Type::getInt1Ty(VMContext), true)
907 return DISubprogram(MDNode::get(VMContext, &Elts[0], 11));
910 /// CreateGlobalVariable - Create a new descriptor for the specified global.
912 DIFactory::CreateGlobalVariable(DIDescriptor Context, StringRef Name,
913 StringRef DisplayName,
914 StringRef LinkageName,
915 DICompileUnit CompileUnit,
916 unsigned LineNo, DIType Type,bool isLocalToUnit,
917 bool isDefinition, llvm::GlobalVariable *Val) {
919 GetTagConstant(dwarf::DW_TAG_variable),
920 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
922 MDString::get(VMContext, Name),
923 MDString::get(VMContext, DisplayName),
924 MDString::get(VMContext, LinkageName),
925 CompileUnit.getNode(),
926 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
928 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
929 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
933 Value *const *Vs = &Elts[0];
934 MDNode *Node = MDNode::get(VMContext,Vs, 12);
936 // Create a named metadata so that we do not lose this mdnode.
937 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.gv");
938 NMD->addElement(Node);
940 return DIGlobalVariable(Node);
944 /// CreateVariable - Create a new descriptor for the specified variable.
945 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
947 DICompileUnit CompileUnit, unsigned LineNo,
952 MDString::get(VMContext, Name),
953 CompileUnit.getNode(),
954 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
957 return DIVariable(MDNode::get(VMContext, &Elts[0], 6));
961 /// CreateComplexVariable - Create a new descriptor for the specified variable
962 /// which has a complex address expression for its address.
963 DIVariable DIFactory::CreateComplexVariable(unsigned Tag, DIDescriptor Context,
964 const std::string &Name,
965 DICompileUnit CompileUnit,
967 DIType Type, SmallVector<Value *, 9> &addr) {
968 SmallVector<Value *, 9> Elts;
969 Elts.push_back(GetTagConstant(Tag));
970 Elts.push_back(Context.getNode());
971 Elts.push_back(MDString::get(VMContext, Name));
972 Elts.push_back(CompileUnit.getNode());
973 Elts.push_back(ConstantInt::get(Type::getInt32Ty(VMContext), LineNo));
974 Elts.push_back(Type.getNode());
975 Elts.insert(Elts.end(), addr.begin(), addr.end());
977 return DIVariable(MDNode::get(VMContext, &Elts[0], 6+addr.size()));
981 /// CreateBlock - This creates a descriptor for a lexical block with the
982 /// specified parent VMContext.
983 DILexicalBlock DIFactory::CreateLexicalBlock(DIDescriptor Context) {
985 GetTagConstant(dwarf::DW_TAG_lexical_block),
988 return DILexicalBlock(MDNode::get(VMContext, &Elts[0], 2));
991 /// CreateLocation - Creates a debug info location.
992 DILocation DIFactory::CreateLocation(unsigned LineNo, unsigned ColumnNo,
993 DIScope S, DILocation OrigLoc) {
995 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
996 ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo),
1000 return DILocation(MDNode::get(VMContext, &Elts[0], 4));
1003 /// CreateLocation - Creates a debug info location.
1004 DILocation DIFactory::CreateLocation(unsigned LineNo, unsigned ColumnNo,
1005 DIScope S, MDNode *OrigLoc) {
1007 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1008 ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo),
1012 return DILocation(MDNode::get(VMContext, &Elts[0], 4));
1015 //===----------------------------------------------------------------------===//
1016 // DIFactory: Routines for inserting code into a function
1017 //===----------------------------------------------------------------------===//
1019 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1020 Instruction *DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1021 Instruction *InsertBefore) {
1022 // Cast the storage to a {}* for the call to llvm.dbg.declare.
1023 Storage = new BitCastInst(Storage, EmptyStructPtr, "", InsertBefore);
1026 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1028 Value *Args[] = { Storage, D.getNode() };
1029 return CallInst::Create(DeclareFn, Args, Args+2, "", InsertBefore);
1032 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1033 Instruction *DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1034 BasicBlock *InsertAtEnd) {
1035 // Cast the storage to a {}* for the call to llvm.dbg.declare.
1036 Storage = new BitCastInst(Storage, EmptyStructPtr, "", InsertAtEnd);
1039 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1041 Value *Args[] = { Storage, D.getNode() };
1042 return CallInst::Create(DeclareFn, Args, Args+2, "", InsertAtEnd);
1046 //===----------------------------------------------------------------------===//
1047 // DebugInfoFinder implementations.
1048 //===----------------------------------------------------------------------===//
1050 /// processModule - Process entire module and collect debug info.
1051 void DebugInfoFinder::processModule(Module &M) {
1053 MetadataContext &TheMetadata = M.getContext().getMetadata();
1054 unsigned MDDbgKind = TheMetadata.getMDKind("dbg");
1056 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1057 for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI)
1058 for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE;
1060 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
1061 processDeclare(DDI);
1063 if (MDNode *L = TheMetadata.getMD(MDDbgKind, BI))
1064 processLocation(DILocation(L));
1067 NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv");
1071 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
1072 DIGlobalVariable DIG(cast<MDNode>(NMD->getElement(i)));
1073 if (addGlobalVariable(DIG)) {
1074 addCompileUnit(DIG.getCompileUnit());
1075 processType(DIG.getType());
1080 /// processLocation - Process DILocation.
1081 void DebugInfoFinder::processLocation(DILocation Loc) {
1082 if (Loc.isNull()) return;
1083 DIScope S(Loc.getScope().getNode());
1084 if (S.isNull()) return;
1085 if (S.isCompileUnit())
1086 addCompileUnit(DICompileUnit(S.getNode()));
1087 else if (S.isSubprogram())
1088 processSubprogram(DISubprogram(S.getNode()));
1089 else if (S.isLexicalBlock())
1090 processLexicalBlock(DILexicalBlock(S.getNode()));
1091 processLocation(Loc.getOrigLocation());
1094 /// processType - Process DIType.
1095 void DebugInfoFinder::processType(DIType DT) {
1099 addCompileUnit(DT.getCompileUnit());
1100 if (DT.isCompositeType()) {
1101 DICompositeType DCT(DT.getNode());
1102 processType(DCT.getTypeDerivedFrom());
1103 DIArray DA = DCT.getTypeArray();
1105 for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
1106 DIDescriptor D = DA.getElement(i);
1107 DIType TypeE = DIType(D.getNode());
1108 if (!TypeE.isNull())
1111 processSubprogram(DISubprogram(D.getNode()));
1113 } else if (DT.isDerivedType()) {
1114 DIDerivedType DDT(DT.getNode());
1116 processType(DDT.getTypeDerivedFrom());
1120 /// processLexicalBlock
1121 void DebugInfoFinder::processLexicalBlock(DILexicalBlock LB) {
1124 DIScope Context = LB.getContext();
1125 if (Context.isLexicalBlock())
1126 return processLexicalBlock(DILexicalBlock(Context.getNode()));
1128 return processSubprogram(DISubprogram(Context.getNode()));
1131 /// processSubprogram - Process DISubprogram.
1132 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
1135 if (!addSubprogram(SP))
1137 addCompileUnit(SP.getCompileUnit());
1138 processType(SP.getType());
1141 /// processDeclare - Process DbgDeclareInst.
1142 void DebugInfoFinder::processDeclare(DbgDeclareInst *DDI) {
1143 DIVariable DV(cast<MDNode>(DDI->getVariable()));
1147 if (!NodesSeen.insert(DV.getNode()))
1150 addCompileUnit(DV.getCompileUnit());
1151 processType(DV.getType());
1154 /// addType - Add type into Tys.
1155 bool DebugInfoFinder::addType(DIType DT) {
1159 if (!NodesSeen.insert(DT.getNode()))
1162 TYs.push_back(DT.getNode());
1166 /// addCompileUnit - Add compile unit into CUs.
1167 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1171 if (!NodesSeen.insert(CU.getNode()))
1174 CUs.push_back(CU.getNode());
1178 /// addGlobalVariable - Add global variable into GVs.
1179 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1183 if (!NodesSeen.insert(DIG.getNode()))
1186 GVs.push_back(DIG.getNode());
1190 // addSubprogram - Add subprgoram into SPs.
1191 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1195 if (!NodesSeen.insert(SP.getNode()))
1198 SPs.push_back(SP.getNode());
1203 /// findStopPoint - Find the stoppoint coressponding to this instruction, that
1204 /// is the stoppoint that dominates this instruction.
1205 const DbgStopPointInst *findStopPoint(const Instruction *Inst) {
1206 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(Inst))
1209 const BasicBlock *BB = Inst->getParent();
1210 BasicBlock::const_iterator I = Inst, B;
1214 // A BB consisting only of a terminator can't have a stoppoint.
1217 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1221 // This BB didn't have a stoppoint: if there is only one predecessor, look
1222 // for a stoppoint there. We could use getIDom(), but that would require
1224 BB = I->getParent()->getUniquePredecessor();
1226 I = BB->getTerminator();
1232 /// findBBStopPoint - Find the stoppoint corresponding to first real
1233 /// (non-debug intrinsic) instruction in this Basic Block, and return the
1234 /// stoppoint for it.
1235 const DbgStopPointInst *findBBStopPoint(const BasicBlock *BB) {
1236 for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1237 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1240 // Fallback to looking for stoppoint of unique predecessor. Useful if this
1241 // BB contains no stoppoints, but unique predecessor does.
1242 BB = BB->getUniquePredecessor();
1244 return findStopPoint(BB->getTerminator());
1249 Value *findDbgGlobalDeclare(GlobalVariable *V) {
1250 const Module *M = V->getParent();
1251 NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv");
1255 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
1256 DIGlobalVariable DIG(cast_or_null<MDNode>(NMD->getElement(i)));
1259 if (DIG.getGlobal() == V)
1260 return DIG.getNode();
1265 /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
1266 /// It looks through pointer casts too.
1267 const DbgDeclareInst *findDbgDeclare(const Value *V, bool stripCasts) {
1269 V = V->stripPointerCasts();
1271 // Look for the bitcast.
1272 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1274 if (isa<BitCastInst>(I)) {
1275 const DbgDeclareInst *DDI = findDbgDeclare(*I, false);
1276 if (DDI) return DDI;
1281 // Find llvm.dbg.declare among uses of the instruction.
1282 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1284 if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
1290 bool getLocationInfo(const Value *V, std::string &DisplayName,
1291 std::string &Type, unsigned &LineNo, std::string &File,
1296 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
1297 Value *DIGV = findDbgGlobalDeclare(GV);
1298 if (!DIGV) return false;
1299 DIGlobalVariable Var(cast<MDNode>(DIGV));
1301 StringRef D = Var.getDisplayName();
1304 LineNo = Var.getLineNumber();
1305 Unit = Var.getCompileUnit();
1306 TypeD = Var.getType();
1308 const DbgDeclareInst *DDI = findDbgDeclare(V);
1309 if (!DDI) return false;
1310 DIVariable Var(cast<MDNode>(DDI->getVariable()));
1312 StringRef D = Var.getName();
1315 LineNo = Var.getLineNumber();
1316 Unit = Var.getCompileUnit();
1317 TypeD = Var.getType();
1320 StringRef T = TypeD.getName();
1323 StringRef F = Unit.getFilename();
1326 StringRef D = Unit.getDirectory();
1332 /// isValidDebugInfoIntrinsic - Return true if SPI is a valid debug
1334 bool isValidDebugInfoIntrinsic(DbgStopPointInst &SPI,
1335 CodeGenOpt::Level OptLev) {
1336 return DIDescriptor::ValidDebugInfo(SPI.getContext(), OptLev);
1339 /// isValidDebugInfoIntrinsic - Return true if FSI is a valid debug
1341 bool isValidDebugInfoIntrinsic(DbgFuncStartInst &FSI,
1342 CodeGenOpt::Level OptLev) {
1343 return DIDescriptor::ValidDebugInfo(FSI.getSubprogram(), OptLev);
1346 /// isValidDebugInfoIntrinsic - Return true if RSI is a valid debug
1348 bool isValidDebugInfoIntrinsic(DbgRegionStartInst &RSI,
1349 CodeGenOpt::Level OptLev) {
1350 return DIDescriptor::ValidDebugInfo(RSI.getContext(), OptLev);
1353 /// isValidDebugInfoIntrinsic - Return true if REI is a valid debug
1355 bool isValidDebugInfoIntrinsic(DbgRegionEndInst &REI,
1356 CodeGenOpt::Level OptLev) {
1357 return DIDescriptor::ValidDebugInfo(REI.getContext(), OptLev);
1361 /// isValidDebugInfoIntrinsic - Return true if DI is a valid debug
1363 bool isValidDebugInfoIntrinsic(DbgDeclareInst &DI,
1364 CodeGenOpt::Level OptLev) {
1365 return DIDescriptor::ValidDebugInfo(DI.getVariable(), OptLev);
1368 /// ExtractDebugLocation - Extract debug location information
1369 /// from llvm.dbg.stoppoint intrinsic.
1370 DebugLoc ExtractDebugLocation(DbgStopPointInst &SPI,
1371 DebugLocTracker &DebugLocInfo) {
1373 Value *Context = SPI.getContext();
1375 // If this location is already tracked then use it.
1376 DebugLocTuple Tuple(cast<MDNode>(Context), NULL, SPI.getLine(),
1378 DenseMap<DebugLocTuple, unsigned>::iterator II
1379 = DebugLocInfo.DebugIdMap.find(Tuple);
1380 if (II != DebugLocInfo.DebugIdMap.end())
1381 return DebugLoc::get(II->second);
1383 // Add a new location entry.
1384 unsigned Id = DebugLocInfo.DebugLocations.size();
1385 DebugLocInfo.DebugLocations.push_back(Tuple);
1386 DebugLocInfo.DebugIdMap[Tuple] = Id;
1388 return DebugLoc::get(Id);
1391 /// ExtractDebugLocation - Extract debug location information
1392 /// from DILocation.
1393 DebugLoc ExtractDebugLocation(DILocation &Loc,
1394 DebugLocTracker &DebugLocInfo) {
1396 MDNode *Context = Loc.getScope().getNode();
1397 MDNode *InlinedLoc = NULL;
1398 if (!Loc.getOrigLocation().isNull())
1399 InlinedLoc = Loc.getOrigLocation().getNode();
1400 // If this location is already tracked then use it.
1401 DebugLocTuple Tuple(Context, InlinedLoc, Loc.getLineNumber(),
1402 Loc.getColumnNumber());
1403 DenseMap<DebugLocTuple, unsigned>::iterator II
1404 = DebugLocInfo.DebugIdMap.find(Tuple);
1405 if (II != DebugLocInfo.DebugIdMap.end())
1406 return DebugLoc::get(II->second);
1408 // Add a new location entry.
1409 unsigned Id = DebugLocInfo.DebugLocations.size();
1410 DebugLocInfo.DebugLocations.push_back(Tuple);
1411 DebugLocInfo.DebugIdMap[Tuple] = Id;
1413 return DebugLoc::get(Id);
1416 /// ExtractDebugLocation - Extract debug location information
1417 /// from llvm.dbg.func_start intrinsic.
1418 DebugLoc ExtractDebugLocation(DbgFuncStartInst &FSI,
1419 DebugLocTracker &DebugLocInfo) {
1421 Value *SP = FSI.getSubprogram();
1423 DISubprogram Subprogram(cast<MDNode>(SP));
1424 unsigned Line = Subprogram.getLineNumber();
1425 DICompileUnit CU(Subprogram.getCompileUnit());
1427 // If this location is already tracked then use it.
1428 DebugLocTuple Tuple(CU.getNode(), NULL, Line, /* Column */ 0);
1429 DenseMap<DebugLocTuple, unsigned>::iterator II
1430 = DebugLocInfo.DebugIdMap.find(Tuple);
1431 if (II != DebugLocInfo.DebugIdMap.end())
1432 return DebugLoc::get(II->second);
1434 // Add a new location entry.
1435 unsigned Id = DebugLocInfo.DebugLocations.size();
1436 DebugLocInfo.DebugLocations.push_back(Tuple);
1437 DebugLocInfo.DebugIdMap[Tuple] = Id;
1439 return DebugLoc::get(Id);
1442 /// getDISubprogram - Find subprogram that is enclosing this scope.
1443 DISubprogram getDISubprogram(MDNode *Scope) {
1444 DIDescriptor D(Scope);
1446 return DISubprogram();
1448 if (D.isCompileUnit())
1449 return DISubprogram();
1451 if (D.isSubprogram())
1452 return DISubprogram(Scope);
1454 if (D.isLexicalBlock())
1455 return getDISubprogram(DILexicalBlock(Scope).getContext().getNode());
1457 return DISubprogram();
1460 /// getDICompositeType - Find underlying composite type.
1461 DICompositeType getDICompositeType(DIType T) {
1463 return DICompositeType();
1465 if (T.isCompositeType())
1466 return DICompositeType(T.getNode());
1468 if (T.isDerivedType())
1469 return getDICompositeType(DIDerivedType(T.getNode()).getTypeDerivedFrom());
1471 return DICompositeType();