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;
213 /// isScope - Return true if the specified tag is one of the scope
215 bool DIDescriptor::isScope() const {
216 assert (!isNull() && "Invalid descriptor!");
217 unsigned Tag = getTag();
220 case dwarf::DW_TAG_compile_unit:
221 case dwarf::DW_TAG_lexical_block:
222 case dwarf::DW_TAG_subprogram:
230 /// isCompileUnit - Return true if the specified tag is DW_TAG_compile_unit.
231 bool DIDescriptor::isCompileUnit() const {
232 assert (!isNull() && "Invalid descriptor!");
233 unsigned Tag = getTag();
235 return Tag == dwarf::DW_TAG_compile_unit;
238 /// isLexicalBlock - Return true if the specified tag is DW_TAG_lexical_block.
239 bool DIDescriptor::isLexicalBlock() const {
240 assert (!isNull() && "Invalid descriptor!");
241 unsigned Tag = getTag();
243 return Tag == dwarf::DW_TAG_lexical_block;
246 //===----------------------------------------------------------------------===//
247 // Simple Descriptor Constructors and other Methods
248 //===----------------------------------------------------------------------===//
250 DIType::DIType(MDNode *N) : DIDescriptor(N) {
252 if (!isBasicType() && !isDerivedType() && !isCompositeType()) {
257 unsigned DIArray::getNumElements() const {
258 assert (DbgNode && "Invalid DIArray");
259 return DbgNode->getNumElements();
262 /// replaceAllUsesWith - Replace all uses of debug info referenced by
263 /// this descriptor. After this completes, the current debug info value
265 void DIDerivedType::replaceAllUsesWith(DIDescriptor &D) {
269 assert (!D.isNull() && "Can not replace with null");
270 DbgNode->replaceAllUsesWith(D.getNode());
274 /// Verify - Verify that a compile unit is well formed.
275 bool DICompileUnit::Verify() const {
279 if (getFilename(Res).empty())
281 // It is possible that directory and produce string is empty.
285 /// Verify - Verify that a type descriptor is well formed.
286 bool DIType::Verify() const {
289 if (getContext().isNull())
292 DICompileUnit CU = getCompileUnit();
293 if (!CU.isNull() && !CU.Verify())
298 /// Verify - Verify that a composite type descriptor is well formed.
299 bool DICompositeType::Verify() const {
302 if (getContext().isNull())
305 DICompileUnit CU = getCompileUnit();
306 if (!CU.isNull() && !CU.Verify())
311 /// Verify - Verify that a subprogram descriptor is well formed.
312 bool DISubprogram::Verify() const {
316 if (getContext().isNull())
319 DICompileUnit CU = getCompileUnit();
323 DICompositeType Ty = getType();
324 if (!Ty.isNull() && !Ty.Verify())
329 /// Verify - Verify that a global variable descriptor is well formed.
330 bool DIGlobalVariable::Verify() const {
334 if (getContext().isNull())
337 DICompileUnit CU = getCompileUnit();
338 if (!CU.isNull() && !CU.Verify())
341 DIType Ty = getType();
351 /// Verify - Verify that a variable descriptor is well formed.
352 bool DIVariable::Verify() const {
356 if (getContext().isNull())
359 DIType Ty = getType();
366 /// getOriginalTypeSize - If this type is derived from a base type then
367 /// return base type size.
368 uint64_t DIDerivedType::getOriginalTypeSize() const {
369 if (getTag() != dwarf::DW_TAG_member)
370 return getSizeInBits();
371 DIType BT = getTypeDerivedFrom();
372 if (BT.getTag() != dwarf::DW_TAG_base_type)
373 return getSizeInBits();
374 return BT.getSizeInBits();
377 /// describes - Return true if this subprogram provides debugging
378 /// information for the function F.
379 bool DISubprogram::describes(const Function *F) {
380 assert (F && "Invalid function");
382 getLinkageName(Name);
385 if (F->getName() == Name)
390 //===----------------------------------------------------------------------===//
391 // DIDescriptor: dump routines for all descriptors.
392 //===----------------------------------------------------------------------===//
395 /// dump - Print descriptor.
396 void DIDescriptor::dump() const {
397 errs() << "[" << dwarf::TagString(getTag()) << "] ";
398 errs().write_hex((intptr_t)DbgNode) << ']';
401 /// dump - Print compile unit.
402 void DICompileUnit::dump() const {
404 errs() << " [" << dwarf::LanguageString(getLanguage()) << "] ";
406 std::string Res1, Res2;
407 errs() << " [" << getDirectory(Res1) << "/" << getFilename(Res2) << " ]";
410 /// dump - Print type.
411 void DIType::dump() const {
412 if (isNull()) return;
415 if (!getName(Res).empty())
416 errs() << " [" << Res << "] ";
418 unsigned Tag = getTag();
419 errs() << " [" << dwarf::TagString(Tag) << "] ";
421 // TODO : Print context
422 getCompileUnit().dump();
424 << getLineNumber() << ", "
425 << getSizeInBits() << ", "
426 << getAlignInBits() << ", "
431 errs() << " [private] ";
432 else if (isProtected())
433 errs() << " [protected] ";
439 DIBasicType(DbgNode).dump();
440 else if (isDerivedType())
441 DIDerivedType(DbgNode).dump();
442 else if (isCompositeType())
443 DICompositeType(DbgNode).dump();
445 errs() << "Invalid DIType\n";
452 /// dump - Print basic type.
453 void DIBasicType::dump() const {
454 errs() << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
457 /// dump - Print derived type.
458 void DIDerivedType::dump() const {
459 errs() << "\n\t Derived From: "; getTypeDerivedFrom().dump();
462 /// dump - Print composite type.
463 void DICompositeType::dump() const {
464 DIArray A = getTypeArray();
467 errs() << " [" << A.getNumElements() << " elements]";
470 /// dump - Print global.
471 void DIGlobal::dump() const {
473 if (!getName(Res).empty())
474 errs() << " [" << Res << "] ";
476 unsigned Tag = getTag();
477 errs() << " [" << dwarf::TagString(Tag) << "] ";
479 // TODO : Print context
480 getCompileUnit().dump();
481 errs() << " [" << getLineNumber() << "] ";
484 errs() << " [local] ";
489 if (isGlobalVariable())
490 DIGlobalVariable(DbgNode).dump();
495 /// dump - Print subprogram.
496 void DISubprogram::dump() const {
500 /// dump - Print global variable.
501 void DIGlobalVariable::dump() const {
507 /// dump - Print variable.
508 void DIVariable::dump() const {
510 if (!getName(Res).empty())
511 errs() << " [" << Res << "] ";
513 getCompileUnit().dump();
514 errs() << " [" << getLineNumber() << "] ";
519 //===----------------------------------------------------------------------===//
520 // DIFactory: Basic Helpers
521 //===----------------------------------------------------------------------===//
523 DIFactory::DIFactory(Module &m)
524 : M(m), VMContext(M.getContext()), StopPointFn(0), FuncStartFn(0),
525 RegionStartFn(0), RegionEndFn(0),
527 EmptyStructPtr = PointerType::getUnqual(StructType::get(VMContext));
530 Constant *DIFactory::GetTagConstant(unsigned TAG) {
531 assert((TAG & LLVMDebugVersionMask) == 0 &&
532 "Tag too large for debug encoding!");
533 return ConstantInt::get(Type::getInt32Ty(VMContext), TAG | LLVMDebugVersion);
536 //===----------------------------------------------------------------------===//
537 // DIFactory: Primary Constructors
538 //===----------------------------------------------------------------------===//
540 /// GetOrCreateArray - Create an descriptor for an array of descriptors.
541 /// This implicitly uniques the arrays created.
542 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
543 SmallVector<Value*, 16> Elts;
546 Elts.push_back(llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)));
548 for (unsigned i = 0; i != NumTys; ++i)
549 Elts.push_back(Tys[i].getNode());
551 return DIArray(MDNode::get(VMContext,Elts.data(), Elts.size()));
554 /// GetOrCreateSubrange - Create a descriptor for a value range. This
555 /// implicitly uniques the values returned.
556 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
558 GetTagConstant(dwarf::DW_TAG_subrange_type),
559 ConstantInt::get(Type::getInt64Ty(VMContext), Lo),
560 ConstantInt::get(Type::getInt64Ty(VMContext), Hi)
563 return DISubrange(MDNode::get(VMContext, &Elts[0], 3));
568 /// CreateCompileUnit - Create a new descriptor for the specified compile
569 /// unit. Note that this does not unique compile units within the module.
570 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
571 const std::string &Filename,
572 const std::string &Directory,
573 const std::string &Producer,
577 unsigned RunTimeVer) {
579 GetTagConstant(dwarf::DW_TAG_compile_unit),
580 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
581 ConstantInt::get(Type::getInt32Ty(VMContext), LangID),
582 MDString::get(VMContext, Filename),
583 MDString::get(VMContext, Directory),
584 MDString::get(VMContext, Producer),
585 ConstantInt::get(Type::getInt1Ty(VMContext), isMain),
586 ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
587 MDString::get(VMContext, Flags),
588 ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeVer)
591 return DICompileUnit(MDNode::get(VMContext, &Elts[0], 10));
594 /// CreateEnumerator - Create a single enumerator value.
595 DIEnumerator DIFactory::CreateEnumerator(const std::string &Name, uint64_t Val){
597 GetTagConstant(dwarf::DW_TAG_enumerator),
598 MDString::get(VMContext, Name),
599 ConstantInt::get(Type::getInt64Ty(VMContext), Val)
601 return DIEnumerator(MDNode::get(VMContext, &Elts[0], 3));
605 /// CreateBasicType - Create a basic type like int, float, etc.
606 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
607 const std::string &Name,
608 DICompileUnit CompileUnit,
611 uint64_t AlignInBits,
612 uint64_t OffsetInBits, unsigned Flags,
615 GetTagConstant(dwarf::DW_TAG_base_type),
617 MDString::get(VMContext, Name),
618 CompileUnit.getNode(),
619 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
620 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
621 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
622 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
623 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
624 ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
626 return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
629 /// CreateDerivedType - Create a derived type like const qualified type,
630 /// pointer, typedef, etc.
631 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
632 DIDescriptor Context,
633 const std::string &Name,
634 DICompileUnit CompileUnit,
637 uint64_t AlignInBits,
638 uint64_t OffsetInBits,
640 DIType DerivedFrom) {
644 MDString::get(VMContext, Name),
645 CompileUnit.getNode(),
646 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
647 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
648 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
649 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
650 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
651 DerivedFrom.getNode(),
653 return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
656 /// CreateCompositeType - Create a composite type like array, struct, etc.
657 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
658 DIDescriptor Context,
659 const std::string &Name,
660 DICompileUnit CompileUnit,
663 uint64_t AlignInBits,
664 uint64_t OffsetInBits,
668 unsigned RuntimeLang) {
673 MDString::get(VMContext, Name),
674 CompileUnit.getNode(),
675 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
676 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
677 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
678 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
679 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
680 DerivedFrom.getNode(),
682 ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang)
684 return DICompositeType(MDNode::get(VMContext, &Elts[0], 12));
688 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
689 /// See comments in DISubprogram for descriptions of these fields. This
690 /// method does not unique the generated descriptors.
691 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context,
692 const std::string &Name,
693 const std::string &DisplayName,
694 const std::string &LinkageName,
695 DICompileUnit CompileUnit,
696 unsigned LineNo, DIType Type,
701 GetTagConstant(dwarf::DW_TAG_subprogram),
702 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
704 MDString::get(VMContext, Name),
705 MDString::get(VMContext, DisplayName),
706 MDString::get(VMContext, LinkageName),
707 CompileUnit.getNode(),
708 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
710 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
711 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition)
713 return DISubprogram(MDNode::get(VMContext, &Elts[0], 11));
716 /// CreateGlobalVariable - Create a new descriptor for the specified global.
718 DIFactory::CreateGlobalVariable(DIDescriptor Context, const std::string &Name,
719 const std::string &DisplayName,
720 const std::string &LinkageName,
721 DICompileUnit CompileUnit,
722 unsigned LineNo, DIType Type,bool isLocalToUnit,
723 bool isDefinition, llvm::GlobalVariable *Val) {
725 GetTagConstant(dwarf::DW_TAG_variable),
726 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
728 MDString::get(VMContext, Name),
729 MDString::get(VMContext, DisplayName),
730 MDString::get(VMContext, LinkageName),
731 CompileUnit.getNode(),
732 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
734 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
735 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
739 Value *const *Vs = &Elts[0];
740 MDNode *Node = MDNode::get(VMContext,Vs, 12);
742 // Create a named metadata so that we do not lose this mdnode.
743 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.gv");
744 NMD->addElement(Node);
746 return DIGlobalVariable(Node);
750 /// CreateVariable - Create a new descriptor for the specified variable.
751 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
752 const std::string &Name,
753 DICompileUnit CompileUnit, unsigned LineNo,
758 MDString::get(VMContext, Name),
759 CompileUnit.getNode(),
760 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
763 return DIVariable(MDNode::get(VMContext, &Elts[0], 6));
767 /// CreateBlock - This creates a descriptor for a lexical block with the
768 /// specified parent VMContext.
769 DILexicalBlock DIFactory::CreateLexicalBlock(DIDescriptor Context) {
771 GetTagConstant(dwarf::DW_TAG_lexical_block),
774 return DILexicalBlock(MDNode::get(VMContext, &Elts[0], 2));
778 //===----------------------------------------------------------------------===//
779 // DIFactory: Routines for inserting code into a function
780 //===----------------------------------------------------------------------===//
782 /// InsertStopPoint - Create a new llvm.dbg.stoppoint intrinsic invocation,
783 /// inserting it at the end of the specified basic block.
784 void DIFactory::InsertStopPoint(DICompileUnit CU, unsigned LineNo,
785 unsigned ColNo, BasicBlock *BB) {
787 // Lazily construct llvm.dbg.stoppoint function.
789 StopPointFn = llvm::Intrinsic::getDeclaration(&M,
790 llvm::Intrinsic::dbg_stoppoint);
792 // Invoke llvm.dbg.stoppoint
794 ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo),
795 ConstantInt::get(llvm::Type::getInt32Ty(VMContext), ColNo),
798 CallInst::Create(StopPointFn, Args, Args+3, "", BB);
801 /// InsertSubprogramStart - Create a new llvm.dbg.func.start intrinsic to
802 /// mark the start of the specified subprogram.
803 void DIFactory::InsertSubprogramStart(DISubprogram SP, BasicBlock *BB) {
804 // Lazily construct llvm.dbg.func.start.
806 FuncStartFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_func_start);
808 // Call llvm.dbg.func.start which also implicitly sets a stoppoint.
809 CallInst::Create(FuncStartFn, SP.getNode(), "", BB);
812 /// InsertRegionStart - Insert a new llvm.dbg.region.start intrinsic call to
813 /// mark the start of a region for the specified scoping descriptor.
814 void DIFactory::InsertRegionStart(DIDescriptor D, BasicBlock *BB) {
815 // Lazily construct llvm.dbg.region.start function.
817 RegionStartFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_region_start);
819 // Call llvm.dbg.func.start.
820 CallInst::Create(RegionStartFn, D.getNode(), "", BB);
823 /// InsertRegionEnd - Insert a new llvm.dbg.region.end intrinsic call to
824 /// mark the end of a region for the specified scoping descriptor.
825 void DIFactory::InsertRegionEnd(DIDescriptor D, BasicBlock *BB) {
826 // Lazily construct llvm.dbg.region.end function.
828 RegionEndFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_region_end);
830 // Call llvm.dbg.region.end.
831 CallInst::Create(RegionEndFn, D.getNode(), "", BB);
834 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
835 void DIFactory::InsertDeclare(Value *Storage, DIVariable D, BasicBlock *BB) {
836 // Cast the storage to a {}* for the call to llvm.dbg.declare.
837 Storage = new BitCastInst(Storage, EmptyStructPtr, "", BB);
840 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
842 Value *Args[] = { Storage, D.getNode() };
843 CallInst::Create(DeclareFn, Args, Args+2, "", BB);
847 //===----------------------------------------------------------------------===//
848 // DebugInfoFinder implementations.
849 //===----------------------------------------------------------------------===//
851 /// processModule - Process entire module and collect debug info.
852 void DebugInfoFinder::processModule(Module &M) {
855 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
856 for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI)
857 for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE;
859 if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(BI))
860 processStopPoint(SPI);
861 else if (DbgFuncStartInst *FSI = dyn_cast<DbgFuncStartInst>(BI))
862 processFuncStart(FSI);
863 else if (DbgRegionStartInst *DRS = dyn_cast<DbgRegionStartInst>(BI))
864 processRegionStart(DRS);
865 else if (DbgRegionEndInst *DRE = dyn_cast<DbgRegionEndInst>(BI))
866 processRegionEnd(DRE);
867 else if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
871 NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv");
875 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
876 DIGlobalVariable DIG(cast<MDNode>(NMD->getElement(i)));
877 if (addGlobalVariable(DIG)) {
878 addCompileUnit(DIG.getCompileUnit());
879 processType(DIG.getType());
884 /// processType - Process DIType.
885 void DebugInfoFinder::processType(DIType DT) {
889 addCompileUnit(DT.getCompileUnit());
890 if (DT.isCompositeType()) {
891 DICompositeType DCT(DT.getNode());
892 processType(DCT.getTypeDerivedFrom());
893 DIArray DA = DCT.getTypeArray();
895 for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
896 DIDescriptor D = DA.getElement(i);
897 DIType TypeE = DIType(D.getNode());
901 processSubprogram(DISubprogram(D.getNode()));
903 } else if (DT.isDerivedType()) {
904 DIDerivedType DDT(DT.getNode());
906 processType(DDT.getTypeDerivedFrom());
910 /// processSubprogram - Process DISubprogram.
911 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
914 if (!addSubprogram(SP))
916 addCompileUnit(SP.getCompileUnit());
917 processType(SP.getType());
920 /// processStopPoint - Process DbgStopPointInst.
921 void DebugInfoFinder::processStopPoint(DbgStopPointInst *SPI) {
922 MDNode *Context = dyn_cast<MDNode>(SPI->getContext());
923 addCompileUnit(DICompileUnit(Context));
926 /// processFuncStart - Process DbgFuncStartInst.
927 void DebugInfoFinder::processFuncStart(DbgFuncStartInst *FSI) {
928 MDNode *SP = dyn_cast<MDNode>(FSI->getSubprogram());
929 processSubprogram(DISubprogram(SP));
932 /// processRegionStart - Process DbgRegionStart.
933 void DebugInfoFinder::processRegionStart(DbgRegionStartInst *DRS) {
934 MDNode *SP = dyn_cast<MDNode>(DRS->getContext());
935 processSubprogram(DISubprogram(SP));
938 /// processRegionEnd - Process DbgRegionEnd.
939 void DebugInfoFinder::processRegionEnd(DbgRegionEndInst *DRE) {
940 MDNode *SP = dyn_cast<MDNode>(DRE->getContext());
941 processSubprogram(DISubprogram(SP));
944 /// processDeclare - Process DbgDeclareInst.
945 void DebugInfoFinder::processDeclare(DbgDeclareInst *DDI) {
946 DIVariable DV(cast<MDNode>(DDI->getVariable()));
950 if (!NodesSeen.insert(DV.getNode()))
953 addCompileUnit(DV.getCompileUnit());
954 processType(DV.getType());
957 /// addType - Add type into Tys.
958 bool DebugInfoFinder::addType(DIType DT) {
962 if (!NodesSeen.insert(DT.getNode()))
965 TYs.push_back(DT.getNode());
969 /// addCompileUnit - Add compile unit into CUs.
970 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
974 if (!NodesSeen.insert(CU.getNode()))
977 CUs.push_back(CU.getNode());
981 /// addGlobalVariable - Add global variable into GVs.
982 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
986 if (!NodesSeen.insert(DIG.getNode()))
989 GVs.push_back(DIG.getNode());
993 // addSubprogram - Add subprgoram into SPs.
994 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
998 if (!NodesSeen.insert(SP.getNode()))
1001 SPs.push_back(SP.getNode());
1006 /// findStopPoint - Find the stoppoint coressponding to this instruction, that
1007 /// is the stoppoint that dominates this instruction.
1008 const DbgStopPointInst *findStopPoint(const Instruction *Inst) {
1009 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(Inst))
1012 const BasicBlock *BB = Inst->getParent();
1013 BasicBlock::const_iterator I = Inst, B;
1017 // A BB consisting only of a terminator can't have a stoppoint.
1020 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1024 // This BB didn't have a stoppoint: if there is only one predecessor, look
1025 // for a stoppoint there. We could use getIDom(), but that would require
1027 BB = I->getParent()->getUniquePredecessor();
1029 I = BB->getTerminator();
1035 /// findBBStopPoint - Find the stoppoint corresponding to first real
1036 /// (non-debug intrinsic) instruction in this Basic Block, and return the
1037 /// stoppoint for it.
1038 const DbgStopPointInst *findBBStopPoint(const BasicBlock *BB) {
1039 for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1040 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1043 // Fallback to looking for stoppoint of unique predecessor. Useful if this
1044 // BB contains no stoppoints, but unique predecessor does.
1045 BB = BB->getUniquePredecessor();
1047 return findStopPoint(BB->getTerminator());
1052 Value *findDbgGlobalDeclare(GlobalVariable *V) {
1053 const Module *M = V->getParent();
1054 NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv");
1058 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
1059 DIGlobalVariable DIG(cast_or_null<MDNode>(NMD->getElement(i)));
1062 if (DIG.getGlobal() == V)
1063 return DIG.getNode();
1068 /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
1069 /// It looks through pointer casts too.
1070 const DbgDeclareInst *findDbgDeclare(const Value *V, bool stripCasts) {
1072 V = V->stripPointerCasts();
1074 // Look for the bitcast.
1075 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1077 if (isa<BitCastInst>(I))
1078 return findDbgDeclare(*I, false);
1083 // Find llvm.dbg.declare among uses of the instruction.
1084 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1086 if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
1092 bool getLocationInfo(const Value *V, std::string &DisplayName,
1093 std::string &Type, unsigned &LineNo, std::string &File,
1098 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
1099 Value *DIGV = findDbgGlobalDeclare(GV);
1100 if (!DIGV) return false;
1101 DIGlobalVariable Var(cast<MDNode>(DIGV));
1103 Var.getDisplayName(DisplayName);
1104 LineNo = Var.getLineNumber();
1105 Unit = Var.getCompileUnit();
1106 TypeD = Var.getType();
1108 const DbgDeclareInst *DDI = findDbgDeclare(V);
1109 if (!DDI) return false;
1110 DIVariable Var(cast<MDNode>(DDI->getVariable()));
1112 Var.getName(DisplayName);
1113 LineNo = Var.getLineNumber();
1114 Unit = Var.getCompileUnit();
1115 TypeD = Var.getType();
1118 TypeD.getName(Type);
1119 Unit.getFilename(File);
1120 Unit.getDirectory(Dir);
1124 /// isValidDebugInfoIntrinsic - Return true if SPI is a valid debug
1126 bool isValidDebugInfoIntrinsic(DbgStopPointInst &SPI,
1127 CodeGenOpt::Level OptLev) {
1128 return DIDescriptor::ValidDebugInfo(SPI.getContext(), OptLev);
1131 /// isValidDebugInfoIntrinsic - Return true if FSI is a valid debug
1133 bool isValidDebugInfoIntrinsic(DbgFuncStartInst &FSI,
1134 CodeGenOpt::Level OptLev) {
1135 return DIDescriptor::ValidDebugInfo(FSI.getSubprogram(), OptLev);
1138 /// isValidDebugInfoIntrinsic - Return true if RSI is a valid debug
1140 bool isValidDebugInfoIntrinsic(DbgRegionStartInst &RSI,
1141 CodeGenOpt::Level OptLev) {
1142 return DIDescriptor::ValidDebugInfo(RSI.getContext(), OptLev);
1145 /// isValidDebugInfoIntrinsic - Return true if REI is a valid debug
1147 bool isValidDebugInfoIntrinsic(DbgRegionEndInst &REI,
1148 CodeGenOpt::Level OptLev) {
1149 return DIDescriptor::ValidDebugInfo(REI.getContext(), OptLev);
1153 /// isValidDebugInfoIntrinsic - Return true if DI is a valid debug
1155 bool isValidDebugInfoIntrinsic(DbgDeclareInst &DI,
1156 CodeGenOpt::Level OptLev) {
1157 return DIDescriptor::ValidDebugInfo(DI.getVariable(), OptLev);
1160 /// ExtractDebugLocation - Extract debug location information
1161 /// from llvm.dbg.stoppoint intrinsic.
1162 DebugLoc ExtractDebugLocation(DbgStopPointInst &SPI,
1163 DebugLocTracker &DebugLocInfo) {
1165 Value *Context = SPI.getContext();
1167 // If this location is already tracked then use it.
1168 DebugLocTuple Tuple(cast<MDNode>(Context), SPI.getLine(),
1170 DenseMap<DebugLocTuple, unsigned>::iterator II
1171 = DebugLocInfo.DebugIdMap.find(Tuple);
1172 if (II != DebugLocInfo.DebugIdMap.end())
1173 return DebugLoc::get(II->second);
1175 // Add a new location entry.
1176 unsigned Id = DebugLocInfo.DebugLocations.size();
1177 DebugLocInfo.DebugLocations.push_back(Tuple);
1178 DebugLocInfo.DebugIdMap[Tuple] = Id;
1180 return DebugLoc::get(Id);
1183 /// ExtractDebugLocation - Extract debug location information
1184 /// from llvm.dbg.func_start intrinsic.
1185 DebugLoc ExtractDebugLocation(DbgFuncStartInst &FSI,
1186 DebugLocTracker &DebugLocInfo) {
1188 Value *SP = FSI.getSubprogram();
1190 DISubprogram Subprogram(cast<MDNode>(SP));
1191 unsigned Line = Subprogram.getLineNumber();
1192 DICompileUnit CU(Subprogram.getCompileUnit());
1194 // If this location is already tracked then use it.
1195 DebugLocTuple Tuple(CU.getNode(), Line, /* Column */ 0);
1196 DenseMap<DebugLocTuple, unsigned>::iterator II
1197 = DebugLocInfo.DebugIdMap.find(Tuple);
1198 if (II != DebugLocInfo.DebugIdMap.end())
1199 return DebugLoc::get(II->second);
1201 // Add a new location entry.
1202 unsigned Id = DebugLocInfo.DebugLocations.size();
1203 DebugLocInfo.DebugLocations.push_back(Tuple);
1204 DebugLocInfo.DebugIdMap[Tuple] = Id;
1206 return DebugLoc::get(Id);
1209 /// isInlinedFnStart - Return true if FSI is starting an inlined function.
1210 bool isInlinedFnStart(DbgFuncStartInst &FSI, const Function *CurrentFn) {
1211 DISubprogram Subprogram(cast<MDNode>(FSI.getSubprogram()));
1212 if (Subprogram.describes(CurrentFn))
1218 /// isInlinedFnEnd - Return true if REI is ending an inlined function.
1219 bool isInlinedFnEnd(DbgRegionEndInst &REI, const Function *CurrentFn) {
1220 DISubprogram Subprogram(cast<MDNode>(REI.getContext()));
1221 if (Subprogram.isNull() || Subprogram.describes(CurrentFn))