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, std::string &Result) const {
87 if (Elt < DbgNode->getNumElements())
88 if (MDString *MDS = dyn_cast_or_null<MDString>(DbgNode->getElement(Elt))) {
89 Result.assign(MDS->begin(), MDS->begin() + MDS->length());
96 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
100 if (Elt < DbgNode->getNumElements())
101 if (ConstantInt *CI = dyn_cast<ConstantInt>(DbgNode->getElement(Elt)))
102 return CI->getZExtValue();
107 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
109 return DIDescriptor();
111 if (Elt < DbgNode->getNumElements() && DbgNode->getElement(Elt))
112 return DIDescriptor(dyn_cast<MDNode>(DbgNode->getElement(Elt)));
114 return DIDescriptor();
117 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
121 if (Elt < DbgNode->getNumElements())
122 return dyn_cast<GlobalVariable>(DbgNode->getElement(Elt));
126 //===----------------------------------------------------------------------===//
128 //===----------------------------------------------------------------------===//
130 /// isBasicType - Return true if the specified tag is legal for
132 bool DIDescriptor::isBasicType() const {
133 assert (!isNull() && "Invalid descriptor!");
134 unsigned Tag = getTag();
136 return Tag == dwarf::DW_TAG_base_type;
139 /// isDerivedType - Return true if the specified tag is legal for DIDerivedType.
140 bool DIDescriptor::isDerivedType() const {
141 assert (!isNull() && "Invalid descriptor!");
142 unsigned Tag = getTag();
145 case dwarf::DW_TAG_typedef:
146 case dwarf::DW_TAG_pointer_type:
147 case dwarf::DW_TAG_reference_type:
148 case dwarf::DW_TAG_const_type:
149 case dwarf::DW_TAG_volatile_type:
150 case dwarf::DW_TAG_restrict_type:
151 case dwarf::DW_TAG_member:
152 case dwarf::DW_TAG_inheritance:
155 // CompositeTypes are currently modelled as DerivedTypes.
156 return isCompositeType();
160 /// isCompositeType - Return true if the specified tag is legal for
162 bool DIDescriptor::isCompositeType() const {
163 assert (!isNull() && "Invalid descriptor!");
164 unsigned Tag = getTag();
167 case dwarf::DW_TAG_array_type:
168 case dwarf::DW_TAG_structure_type:
169 case dwarf::DW_TAG_union_type:
170 case dwarf::DW_TAG_enumeration_type:
171 case dwarf::DW_TAG_vector_type:
172 case dwarf::DW_TAG_subroutine_type:
173 case dwarf::DW_TAG_class_type:
180 /// isVariable - Return true if the specified tag is legal for DIVariable.
181 bool DIDescriptor::isVariable() const {
182 assert (!isNull() && "Invalid descriptor!");
183 unsigned Tag = getTag();
186 case dwarf::DW_TAG_auto_variable:
187 case dwarf::DW_TAG_arg_variable:
188 case dwarf::DW_TAG_return_variable:
195 /// isSubprogram - Return true if the specified tag is legal for
197 bool DIDescriptor::isSubprogram() const {
198 assert (!isNull() && "Invalid descriptor!");
199 unsigned Tag = getTag();
201 return Tag == dwarf::DW_TAG_subprogram;
204 /// isGlobalVariable - Return true if the specified tag is legal for
205 /// DIGlobalVariable.
206 bool DIDescriptor::isGlobalVariable() const {
207 assert (!isNull() && "Invalid descriptor!");
208 unsigned Tag = getTag();
210 return Tag == dwarf::DW_TAG_variable;
214 //===----------------------------------------------------------------------===//
215 // Simple Descriptor Constructors and other Methods
216 //===----------------------------------------------------------------------===//
218 DIType::DIType(MDNode *N) : DIDescriptor(N) {
220 if (!isBasicType() && !isDerivedType() && !isCompositeType()) {
225 unsigned DIArray::getNumElements() const {
226 assert (DbgNode && "Invalid DIArray");
227 return DbgNode->getNumElements();
230 /// replaceAllUsesWith - Replace all uses of debug info referenced by
231 /// this descriptor. After this completes, the current debug info value
233 void DIDerivedType::replaceAllUsesWith(DIDescriptor &D) {
237 assert (!D.isNull() && "Can not replace with null");
238 DbgNode->replaceAllUsesWith(D.getNode());
242 /// Verify - Verify that a compile unit is well formed.
243 bool DICompileUnit::Verify() const {
247 if (getFilename(Res).empty())
249 // It is possible that directory and produce string is empty.
253 /// Verify - Verify that a type descriptor is well formed.
254 bool DIType::Verify() const {
257 if (getContext().isNull())
260 DICompileUnit CU = getCompileUnit();
261 if (!CU.isNull() && !CU.Verify())
266 /// Verify - Verify that a composite type descriptor is well formed.
267 bool DICompositeType::Verify() const {
270 if (getContext().isNull())
273 DICompileUnit CU = getCompileUnit();
274 if (!CU.isNull() && !CU.Verify())
279 /// Verify - Verify that a subprogram descriptor is well formed.
280 bool DISubprogram::Verify() const {
284 if (getContext().isNull())
287 DICompileUnit CU = getCompileUnit();
291 DICompositeType Ty = getType();
292 if (!Ty.isNull() && !Ty.Verify())
297 /// Verify - Verify that a global variable descriptor is well formed.
298 bool DIGlobalVariable::Verify() const {
302 if (getContext().isNull())
305 DICompileUnit CU = getCompileUnit();
306 if (!CU.isNull() && !CU.Verify())
309 DIType Ty = getType();
319 /// Verify - Verify that a variable descriptor is well formed.
320 bool DIVariable::Verify() const {
324 if (getContext().isNull())
327 DIType Ty = getType();
334 /// getOriginalTypeSize - If this type is derived from a base type then
335 /// return base type size.
336 uint64_t DIDerivedType::getOriginalTypeSize() const {
337 if (getTag() != dwarf::DW_TAG_member)
338 return getSizeInBits();
339 DIType BT = getTypeDerivedFrom();
340 if (BT.getTag() != dwarf::DW_TAG_base_type)
341 return getSizeInBits();
342 return BT.getSizeInBits();
345 /// describes - Return true if this subprogram provides debugging
346 /// information for the function F.
347 bool DISubprogram::describes(const Function *F) {
348 assert (F && "Invalid function");
350 getLinkageName(Name);
353 if (F->getName() == Name)
358 //===----------------------------------------------------------------------===//
359 // DIDescriptor: dump routines for all descriptors.
360 //===----------------------------------------------------------------------===//
363 /// dump - Print descriptor.
364 void DIDescriptor::dump() const {
365 errs() << "[" << dwarf::TagString(getTag()) << "] ";
366 errs().write_hex((intptr_t)DbgNode) << ']';
369 /// dump - Print compile unit.
370 void DICompileUnit::dump() const {
372 errs() << " [" << dwarf::LanguageString(getLanguage()) << "] ";
374 std::string Res1, Res2;
375 errs() << " [" << getDirectory(Res1) << "/" << getFilename(Res2) << " ]";
378 /// dump - Print type.
379 void DIType::dump() const {
380 if (isNull()) return;
383 if (!getName(Res).empty())
384 errs() << " [" << Res << "] ";
386 unsigned Tag = getTag();
387 errs() << " [" << dwarf::TagString(Tag) << "] ";
389 // TODO : Print context
390 getCompileUnit().dump();
392 << getLineNumber() << ", "
393 << getSizeInBits() << ", "
394 << getAlignInBits() << ", "
399 errs() << " [private] ";
400 else if (isProtected())
401 errs() << " [protected] ";
407 DIBasicType(DbgNode).dump();
408 else if (isDerivedType())
409 DIDerivedType(DbgNode).dump();
410 else if (isCompositeType())
411 DICompositeType(DbgNode).dump();
413 errs() << "Invalid DIType\n";
420 /// dump - Print basic type.
421 void DIBasicType::dump() const {
422 errs() << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
425 /// dump - Print derived type.
426 void DIDerivedType::dump() const {
427 errs() << "\n\t Derived From: "; getTypeDerivedFrom().dump();
430 /// dump - Print composite type.
431 void DICompositeType::dump() const {
432 DIArray A = getTypeArray();
435 errs() << " [" << A.getNumElements() << " elements]";
438 /// dump - Print global.
439 void DIGlobal::dump() const {
441 if (!getName(Res).empty())
442 errs() << " [" << Res << "] ";
444 unsigned Tag = getTag();
445 errs() << " [" << dwarf::TagString(Tag) << "] ";
447 // TODO : Print context
448 getCompileUnit().dump();
449 errs() << " [" << getLineNumber() << "] ";
452 errs() << " [local] ";
457 if (isGlobalVariable())
458 DIGlobalVariable(DbgNode).dump();
463 /// dump - Print subprogram.
464 void DISubprogram::dump() const {
468 /// dump - Print global variable.
469 void DIGlobalVariable::dump() const {
475 /// dump - Print variable.
476 void DIVariable::dump() const {
478 if (!getName(Res).empty())
479 errs() << " [" << Res << "] ";
481 getCompileUnit().dump();
482 errs() << " [" << getLineNumber() << "] ";
487 //===----------------------------------------------------------------------===//
488 // DIFactory: Basic Helpers
489 //===----------------------------------------------------------------------===//
491 DIFactory::DIFactory(Module &m)
492 : M(m), VMContext(M.getContext()), StopPointFn(0), FuncStartFn(0),
493 RegionStartFn(0), RegionEndFn(0),
495 EmptyStructPtr = PointerType::getUnqual(StructType::get(VMContext));
498 Constant *DIFactory::GetTagConstant(unsigned TAG) {
499 assert((TAG & LLVMDebugVersionMask) == 0 &&
500 "Tag too large for debug encoding!");
501 return ConstantInt::get(Type::getInt32Ty(VMContext), TAG | LLVMDebugVersion);
504 //===----------------------------------------------------------------------===//
505 // DIFactory: Primary Constructors
506 //===----------------------------------------------------------------------===//
508 /// GetOrCreateArray - Create an descriptor for an array of descriptors.
509 /// This implicitly uniques the arrays created.
510 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
511 SmallVector<Value*, 16> Elts;
514 Elts.push_back(llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)));
516 for (unsigned i = 0; i != NumTys; ++i)
517 Elts.push_back(Tys[i].getNode());
519 return DIArray(MDNode::get(VMContext,Elts.data(), Elts.size()));
522 /// GetOrCreateSubrange - Create a descriptor for a value range. This
523 /// implicitly uniques the values returned.
524 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
526 GetTagConstant(dwarf::DW_TAG_subrange_type),
527 ConstantInt::get(Type::getInt64Ty(VMContext), Lo),
528 ConstantInt::get(Type::getInt64Ty(VMContext), Hi)
531 return DISubrange(MDNode::get(VMContext, &Elts[0], 3));
536 /// CreateCompileUnit - Create a new descriptor for the specified compile
537 /// unit. Note that this does not unique compile units within the module.
538 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
539 const std::string &Filename,
540 const std::string &Directory,
541 const std::string &Producer,
545 unsigned RunTimeVer) {
547 GetTagConstant(dwarf::DW_TAG_compile_unit),
548 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
549 ConstantInt::get(Type::getInt32Ty(VMContext), LangID),
550 MDString::get(VMContext, Filename),
551 MDString::get(VMContext, Directory),
552 MDString::get(VMContext, Producer),
553 ConstantInt::get(Type::getInt1Ty(VMContext), isMain),
554 ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
555 MDString::get(VMContext, Flags),
556 ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeVer)
559 return DICompileUnit(MDNode::get(VMContext, &Elts[0], 10));
562 /// CreateEnumerator - Create a single enumerator value.
563 DIEnumerator DIFactory::CreateEnumerator(const std::string &Name, uint64_t Val){
565 GetTagConstant(dwarf::DW_TAG_enumerator),
566 MDString::get(VMContext, Name),
567 ConstantInt::get(Type::getInt64Ty(VMContext), Val)
569 return DIEnumerator(MDNode::get(VMContext, &Elts[0], 3));
573 /// CreateBasicType - Create a basic type like int, float, etc.
574 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
575 const std::string &Name,
576 DICompileUnit CompileUnit,
579 uint64_t AlignInBits,
580 uint64_t OffsetInBits, unsigned Flags,
583 GetTagConstant(dwarf::DW_TAG_base_type),
585 MDString::get(VMContext, Name),
586 CompileUnit.getNode(),
587 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
588 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
589 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
590 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
591 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
592 ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
594 return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
597 /// CreateDerivedType - Create a derived type like const qualified type,
598 /// pointer, typedef, etc.
599 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
600 DIDescriptor Context,
601 const std::string &Name,
602 DICompileUnit CompileUnit,
605 uint64_t AlignInBits,
606 uint64_t OffsetInBits,
608 DIType DerivedFrom) {
612 MDString::get(VMContext, Name),
613 CompileUnit.getNode(),
614 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
615 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
616 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
617 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
618 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
619 DerivedFrom.getNode(),
621 return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
624 /// CreateCompositeType - Create a composite type like array, struct, etc.
625 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
626 DIDescriptor Context,
627 const std::string &Name,
628 DICompileUnit CompileUnit,
631 uint64_t AlignInBits,
632 uint64_t OffsetInBits,
636 unsigned RuntimeLang) {
641 MDString::get(VMContext, Name),
642 CompileUnit.getNode(),
643 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
644 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
645 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
646 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
647 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
648 DerivedFrom.getNode(),
650 ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang)
652 return DICompositeType(MDNode::get(VMContext, &Elts[0], 12));
656 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
657 /// See comments in DISubprogram for descriptions of these fields. This
658 /// method does not unique the generated descriptors.
659 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context,
660 const std::string &Name,
661 const std::string &DisplayName,
662 const std::string &LinkageName,
663 DICompileUnit CompileUnit,
664 unsigned LineNo, DIType Type,
669 GetTagConstant(dwarf::DW_TAG_subprogram),
670 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
672 MDString::get(VMContext, Name),
673 MDString::get(VMContext, DisplayName),
674 MDString::get(VMContext, LinkageName),
675 CompileUnit.getNode(),
676 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
678 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
679 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition)
681 return DISubprogram(MDNode::get(VMContext, &Elts[0], 11));
684 /// CreateGlobalVariable - Create a new descriptor for the specified global.
686 DIFactory::CreateGlobalVariable(DIDescriptor Context, const std::string &Name,
687 const std::string &DisplayName,
688 const std::string &LinkageName,
689 DICompileUnit CompileUnit,
690 unsigned LineNo, DIType Type,bool isLocalToUnit,
691 bool isDefinition, llvm::GlobalVariable *Val) {
693 GetTagConstant(dwarf::DW_TAG_variable),
694 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
696 MDString::get(VMContext, Name),
697 MDString::get(VMContext, DisplayName),
698 MDString::get(VMContext, LinkageName),
699 CompileUnit.getNode(),
700 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
702 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
703 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
707 Value *const *Vs = &Elts[0];
708 MDNode *Node = MDNode::get(VMContext,Vs, 12);
710 // Create a named metadata so that we do not lose this mdnode.
711 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.gv");
712 NMD->addElement(Node);
714 return DIGlobalVariable(Node);
718 /// CreateVariable - Create a new descriptor for the specified variable.
719 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
720 const std::string &Name,
721 DICompileUnit CompileUnit, unsigned LineNo,
726 MDString::get(VMContext, Name),
727 CompileUnit.getNode(),
728 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
731 return DIVariable(MDNode::get(VMContext, &Elts[0], 6));
735 /// CreateBlock - This creates a descriptor for a lexical block with the
736 /// specified parent VMContext.
737 DIBlock DIFactory::CreateBlock(DIDescriptor Context) {
739 GetTagConstant(dwarf::DW_TAG_lexical_block),
742 return DIBlock(MDNode::get(VMContext, &Elts[0], 2));
746 //===----------------------------------------------------------------------===//
747 // DIFactory: Routines for inserting code into a function
748 //===----------------------------------------------------------------------===//
750 /// InsertStopPoint - Create a new llvm.dbg.stoppoint intrinsic invocation,
751 /// inserting it at the end of the specified basic block.
752 void DIFactory::InsertStopPoint(DICompileUnit CU, unsigned LineNo,
753 unsigned ColNo, BasicBlock *BB) {
755 // Lazily construct llvm.dbg.stoppoint function.
757 StopPointFn = llvm::Intrinsic::getDeclaration(&M,
758 llvm::Intrinsic::dbg_stoppoint);
760 // Invoke llvm.dbg.stoppoint
762 ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo),
763 ConstantInt::get(llvm::Type::getInt32Ty(VMContext), ColNo),
766 CallInst::Create(StopPointFn, Args, Args+3, "", BB);
769 /// InsertSubprogramStart - Create a new llvm.dbg.func.start intrinsic to
770 /// mark the start of the specified subprogram.
771 void DIFactory::InsertSubprogramStart(DISubprogram SP, BasicBlock *BB) {
772 // Lazily construct llvm.dbg.func.start.
774 FuncStartFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_func_start);
776 // Call llvm.dbg.func.start which also implicitly sets a stoppoint.
777 CallInst::Create(FuncStartFn, SP.getNode(), "", BB);
780 /// InsertRegionStart - Insert a new llvm.dbg.region.start intrinsic call to
781 /// mark the start of a region for the specified scoping descriptor.
782 void DIFactory::InsertRegionStart(DIDescriptor D, BasicBlock *BB) {
783 // Lazily construct llvm.dbg.region.start function.
785 RegionStartFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_region_start);
787 // Call llvm.dbg.func.start.
788 CallInst::Create(RegionStartFn, D.getNode(), "", BB);
791 /// InsertRegionEnd - Insert a new llvm.dbg.region.end intrinsic call to
792 /// mark the end of a region for the specified scoping descriptor.
793 void DIFactory::InsertRegionEnd(DIDescriptor D, BasicBlock *BB) {
794 // Lazily construct llvm.dbg.region.end function.
796 RegionEndFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_region_end);
798 // Call llvm.dbg.region.end.
799 CallInst::Create(RegionEndFn, D.getNode(), "", BB);
802 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
803 void DIFactory::InsertDeclare(Value *Storage, DIVariable D, BasicBlock *BB) {
804 // Cast the storage to a {}* for the call to llvm.dbg.declare.
805 Storage = new BitCastInst(Storage, EmptyStructPtr, "", BB);
808 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
810 Value *Args[] = { Storage, D.getNode() };
811 CallInst::Create(DeclareFn, Args, Args+2, "", BB);
815 //===----------------------------------------------------------------------===//
816 // DebugInfoFinder implementations.
817 //===----------------------------------------------------------------------===//
819 /// processModule - Process entire module and collect debug info.
820 void DebugInfoFinder::processModule(Module &M) {
823 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
824 for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI)
825 for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE;
827 if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(BI))
828 processStopPoint(SPI);
829 else if (DbgFuncStartInst *FSI = dyn_cast<DbgFuncStartInst>(BI))
830 processFuncStart(FSI);
831 else if (DbgRegionStartInst *DRS = dyn_cast<DbgRegionStartInst>(BI))
832 processRegionStart(DRS);
833 else if (DbgRegionEndInst *DRE = dyn_cast<DbgRegionEndInst>(BI))
834 processRegionEnd(DRE);
835 else if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
839 NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv");
843 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
844 DIGlobalVariable DIG(cast<MDNode>(NMD->getElement(i)));
845 if (addGlobalVariable(DIG)) {
846 addCompileUnit(DIG.getCompileUnit());
847 processType(DIG.getType());
852 /// processType - Process DIType.
853 void DebugInfoFinder::processType(DIType DT) {
857 addCompileUnit(DT.getCompileUnit());
858 if (DT.isCompositeType()) {
859 DICompositeType DCT(DT.getNode());
860 processType(DCT.getTypeDerivedFrom());
861 DIArray DA = DCT.getTypeArray();
863 for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
864 DIDescriptor D = DA.getElement(i);
865 DIType TypeE = DIType(D.getNode());
869 processSubprogram(DISubprogram(D.getNode()));
871 } else if (DT.isDerivedType()) {
872 DIDerivedType DDT(DT.getNode());
874 processType(DDT.getTypeDerivedFrom());
878 /// processSubprogram - Process DISubprogram.
879 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
882 if (!addSubprogram(SP))
884 addCompileUnit(SP.getCompileUnit());
885 processType(SP.getType());
888 /// processStopPoint - Process DbgStopPointInst.
889 void DebugInfoFinder::processStopPoint(DbgStopPointInst *SPI) {
890 MDNode *Context = dyn_cast<MDNode>(SPI->getContext());
891 addCompileUnit(DICompileUnit(Context));
894 /// processFuncStart - Process DbgFuncStartInst.
895 void DebugInfoFinder::processFuncStart(DbgFuncStartInst *FSI) {
896 MDNode *SP = dyn_cast<MDNode>(FSI->getSubprogram());
897 processSubprogram(DISubprogram(SP));
900 /// processRegionStart - Process DbgRegionStart.
901 void DebugInfoFinder::processRegionStart(DbgRegionStartInst *DRS) {
902 MDNode *SP = dyn_cast<MDNode>(DRS->getContext());
903 processSubprogram(DISubprogram(SP));
906 /// processRegionEnd - Process DbgRegionEnd.
907 void DebugInfoFinder::processRegionEnd(DbgRegionEndInst *DRE) {
908 MDNode *SP = dyn_cast<MDNode>(DRE->getContext());
909 processSubprogram(DISubprogram(SP));
912 /// processDeclare - Process DbgDeclareInst.
913 void DebugInfoFinder::processDeclare(DbgDeclareInst *DDI) {
914 DIVariable DV(cast<MDNode>(DDI->getVariable()));
918 if (!NodesSeen.insert(DV.getNode()))
921 addCompileUnit(DV.getCompileUnit());
922 processType(DV.getType());
925 /// addType - Add type into Tys.
926 bool DebugInfoFinder::addType(DIType DT) {
930 if (!NodesSeen.insert(DT.getNode()))
933 TYs.push_back(DT.getNode());
937 /// addCompileUnit - Add compile unit into CUs.
938 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
942 if (!NodesSeen.insert(CU.getNode()))
945 CUs.push_back(CU.getNode());
949 /// addGlobalVariable - Add global variable into GVs.
950 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
954 if (!NodesSeen.insert(DIG.getNode()))
957 GVs.push_back(DIG.getNode());
961 // addSubprogram - Add subprgoram into SPs.
962 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
966 if (!NodesSeen.insert(SP.getNode()))
969 SPs.push_back(SP.getNode());
974 /// findStopPoint - Find the stoppoint coressponding to this instruction, that
975 /// is the stoppoint that dominates this instruction.
976 const DbgStopPointInst *findStopPoint(const Instruction *Inst) {
977 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(Inst))
980 const BasicBlock *BB = Inst->getParent();
981 BasicBlock::const_iterator I = Inst, B;
985 // A BB consisting only of a terminator can't have a stoppoint.
988 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
992 // This BB didn't have a stoppoint: if there is only one predecessor, look
993 // for a stoppoint there. We could use getIDom(), but that would require
995 BB = I->getParent()->getUniquePredecessor();
997 I = BB->getTerminator();
1003 /// findBBStopPoint - Find the stoppoint corresponding to first real
1004 /// (non-debug intrinsic) instruction in this Basic Block, and return the
1005 /// stoppoint for it.
1006 const DbgStopPointInst *findBBStopPoint(const BasicBlock *BB) {
1007 for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1008 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1011 // Fallback to looking for stoppoint of unique predecessor. Useful if this
1012 // BB contains no stoppoints, but unique predecessor does.
1013 BB = BB->getUniquePredecessor();
1015 return findStopPoint(BB->getTerminator());
1020 Value *findDbgGlobalDeclare(GlobalVariable *V) {
1021 const Module *M = V->getParent();
1022 NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv");
1026 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
1027 DIGlobalVariable DIG(cast_or_null<MDNode>(NMD->getElement(i)));
1030 if (DIG.getGlobal() == V)
1031 return DIG.getNode();
1036 /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
1037 /// It looks through pointer casts too.
1038 const DbgDeclareInst *findDbgDeclare(const Value *V, bool stripCasts) {
1040 V = V->stripPointerCasts();
1042 // Look for the bitcast.
1043 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1045 if (isa<BitCastInst>(I))
1046 return findDbgDeclare(*I, false);
1051 // Find llvm.dbg.declare among uses of the instruction.
1052 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1054 if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
1060 bool getLocationInfo(const Value *V, std::string &DisplayName,
1061 std::string &Type, unsigned &LineNo, std::string &File,
1066 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
1067 Value *DIGV = findDbgGlobalDeclare(GV);
1068 if (!DIGV) return false;
1069 DIGlobalVariable Var(cast<MDNode>(DIGV));
1071 Var.getDisplayName(DisplayName);
1072 LineNo = Var.getLineNumber();
1073 Unit = Var.getCompileUnit();
1074 TypeD = Var.getType();
1076 const DbgDeclareInst *DDI = findDbgDeclare(V);
1077 if (!DDI) return false;
1078 DIVariable Var(cast<MDNode>(DDI->getVariable()));
1080 Var.getName(DisplayName);
1081 LineNo = Var.getLineNumber();
1082 Unit = Var.getCompileUnit();
1083 TypeD = Var.getType();
1086 TypeD.getName(Type);
1087 Unit.getFilename(File);
1088 Unit.getDirectory(Dir);
1092 /// isValidDebugInfoIntrinsic - Return true if SPI is a valid debug
1094 bool isValidDebugInfoIntrinsic(DbgStopPointInst &SPI,
1095 CodeGenOpt::Level OptLev) {
1096 return DIDescriptor::ValidDebugInfo(SPI.getContext(), OptLev);
1099 /// isValidDebugInfoIntrinsic - Return true if FSI is a valid debug
1101 bool isValidDebugInfoIntrinsic(DbgFuncStartInst &FSI,
1102 CodeGenOpt::Level OptLev) {
1103 return DIDescriptor::ValidDebugInfo(FSI.getSubprogram(), OptLev);
1106 /// isValidDebugInfoIntrinsic - Return true if RSI is a valid debug
1108 bool isValidDebugInfoIntrinsic(DbgRegionStartInst &RSI,
1109 CodeGenOpt::Level OptLev) {
1110 return DIDescriptor::ValidDebugInfo(RSI.getContext(), OptLev);
1113 /// isValidDebugInfoIntrinsic - Return true if REI is a valid debug
1115 bool isValidDebugInfoIntrinsic(DbgRegionEndInst &REI,
1116 CodeGenOpt::Level OptLev) {
1117 return DIDescriptor::ValidDebugInfo(REI.getContext(), OptLev);
1121 /// isValidDebugInfoIntrinsic - Return true if DI is a valid debug
1123 bool isValidDebugInfoIntrinsic(DbgDeclareInst &DI,
1124 CodeGenOpt::Level OptLev) {
1125 return DIDescriptor::ValidDebugInfo(DI.getVariable(), OptLev);
1128 /// ExtractDebugLocation - Extract debug location information
1129 /// from llvm.dbg.stoppoint intrinsic.
1130 DebugLoc ExtractDebugLocation(DbgStopPointInst &SPI,
1131 DebugLocTracker &DebugLocInfo) {
1133 Value *Context = SPI.getContext();
1135 // If this location is already tracked then use it.
1136 DebugLocTuple Tuple(cast<MDNode>(Context), SPI.getLine(),
1138 DenseMap<DebugLocTuple, unsigned>::iterator II
1139 = DebugLocInfo.DebugIdMap.find(Tuple);
1140 if (II != DebugLocInfo.DebugIdMap.end())
1141 return DebugLoc::get(II->second);
1143 // Add a new location entry.
1144 unsigned Id = DebugLocInfo.DebugLocations.size();
1145 DebugLocInfo.DebugLocations.push_back(Tuple);
1146 DebugLocInfo.DebugIdMap[Tuple] = Id;
1148 return DebugLoc::get(Id);
1151 /// ExtractDebugLocation - Extract debug location information
1152 /// from llvm.dbg.func_start intrinsic.
1153 DebugLoc ExtractDebugLocation(DbgFuncStartInst &FSI,
1154 DebugLocTracker &DebugLocInfo) {
1156 Value *SP = FSI.getSubprogram();
1158 DISubprogram Subprogram(cast<MDNode>(SP));
1159 unsigned Line = Subprogram.getLineNumber();
1160 DICompileUnit CU(Subprogram.getCompileUnit());
1162 // If this location is already tracked then use it.
1163 DebugLocTuple Tuple(CU.getNode(), Line, /* Column */ 0);
1164 DenseMap<DebugLocTuple, unsigned>::iterator II
1165 = DebugLocInfo.DebugIdMap.find(Tuple);
1166 if (II != DebugLocInfo.DebugIdMap.end())
1167 return DebugLoc::get(II->second);
1169 // Add a new location entry.
1170 unsigned Id = DebugLocInfo.DebugLocations.size();
1171 DebugLocInfo.DebugLocations.push_back(Tuple);
1172 DebugLocInfo.DebugIdMap[Tuple] = Id;
1174 return DebugLoc::get(Id);
1177 /// isInlinedFnStart - Return true if FSI is starting an inlined function.
1178 bool isInlinedFnStart(DbgFuncStartInst &FSI, const Function *CurrentFn) {
1179 DISubprogram Subprogram(cast<MDNode>(FSI.getSubprogram()));
1180 if (Subprogram.describes(CurrentFn))
1186 /// isInlinedFnEnd - Return true if REI is ending an inlined function.
1187 bool isInlinedFnEnd(DbgRegionEndInst &REI, const Function *CurrentFn) {
1188 DISubprogram Subprogram(cast<MDNode>(REI.getContext()));
1189 if (Subprogram.isNull() || Subprogram.describes(CurrentFn))