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().data();
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<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 const char *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 (getContext().isNull())
369 DICompileUnit CU = getCompileUnit();
370 if (!CU.isNull() && !CU.Verify())
373 DIType Ty = getType();
383 /// Verify - Verify that a variable descriptor is well formed.
384 bool DIVariable::Verify() const {
388 if (getContext().isNull())
391 DIType Ty = getType();
398 /// getOriginalTypeSize - If this type is derived from a base type then
399 /// return base type size.
400 uint64_t DIDerivedType::getOriginalTypeSize() const {
401 if (getTag() != dwarf::DW_TAG_member)
402 return getSizeInBits();
403 DIType BT = getTypeDerivedFrom();
404 if (BT.getTag() != dwarf::DW_TAG_base_type)
405 return getSizeInBits();
406 return BT.getSizeInBits();
409 /// describes - Return true if this subprogram provides debugging
410 /// information for the function F.
411 bool DISubprogram::describes(const Function *F) {
412 assert (F && "Invalid function");
413 const char *Name = getLinkageName();
416 if (strcmp(F->getName().data(), Name) == 0)
421 const char *DIScope::getFilename() const {
422 if (isLexicalBlock())
423 return DILexicalBlock(DbgNode).getFilename();
424 else if (isSubprogram())
425 return DISubprogram(DbgNode).getFilename();
426 else if (isCompileUnit())
427 return DICompileUnit(DbgNode).getFilename();
429 assert (0 && "Invalid DIScope!");
433 const char *DIScope::getDirectory() const {
434 if (isLexicalBlock())
435 return DILexicalBlock(DbgNode).getDirectory();
436 else if (isSubprogram())
437 return DISubprogram(DbgNode).getDirectory();
438 else if (isCompileUnit())
439 return DICompileUnit(DbgNode).getDirectory();
441 assert (0 && "Invalid DIScope!");
445 //===----------------------------------------------------------------------===//
446 // DIDescriptor: dump routines for all descriptors.
447 //===----------------------------------------------------------------------===//
450 /// dump - Print descriptor.
451 void DIDescriptor::dump() const {
452 errs() << "[" << dwarf::TagString(getTag()) << "] ";
453 errs().write_hex((intptr_t) &*DbgNode) << ']';
456 /// dump - Print compile unit.
457 void DICompileUnit::dump() const {
459 errs() << " [" << dwarf::LanguageString(getLanguage()) << "] ";
461 errs() << " [" << getDirectory() << "/" << getFilename() << " ]";
464 /// dump - Print type.
465 void DIType::dump() const {
466 if (isNull()) return;
468 if (const char *Res = getName())
469 errs() << " [" << Res << "] ";
471 unsigned Tag = getTag();
472 errs() << " [" << dwarf::TagString(Tag) << "] ";
474 // TODO : Print context
475 getCompileUnit().dump();
477 << getLineNumber() << ", "
478 << getSizeInBits() << ", "
479 << getAlignInBits() << ", "
484 errs() << " [private] ";
485 else if (isProtected())
486 errs() << " [protected] ";
492 DIBasicType(DbgNode).dump();
493 else if (isDerivedType())
494 DIDerivedType(DbgNode).dump();
495 else if (isCompositeType())
496 DICompositeType(DbgNode).dump();
498 errs() << "Invalid DIType\n";
505 /// dump - Print basic type.
506 void DIBasicType::dump() const {
507 errs() << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
510 /// dump - Print derived type.
511 void DIDerivedType::dump() const {
512 errs() << "\n\t Derived From: "; getTypeDerivedFrom().dump();
515 /// dump - Print composite type.
516 void DICompositeType::dump() const {
517 DIArray A = getTypeArray();
520 errs() << " [" << A.getNumElements() << " elements]";
523 /// dump - Print global.
524 void DIGlobal::dump() const {
525 if (const char *Res = getName())
526 errs() << " [" << Res << "] ";
528 unsigned Tag = getTag();
529 errs() << " [" << dwarf::TagString(Tag) << "] ";
531 // TODO : Print context
532 getCompileUnit().dump();
533 errs() << " [" << getLineNumber() << "] ";
536 errs() << " [local] ";
541 if (isGlobalVariable())
542 DIGlobalVariable(DbgNode).dump();
547 /// dump - Print subprogram.
548 void DISubprogram::dump() const {
549 if (const char *Res = getName())
550 errs() << " [" << Res << "] ";
552 unsigned Tag = getTag();
553 errs() << " [" << dwarf::TagString(Tag) << "] ";
555 // TODO : Print context
556 getCompileUnit().dump();
557 errs() << " [" << getLineNumber() << "] ";
560 errs() << " [local] ";
568 /// dump - Print global variable.
569 void DIGlobalVariable::dump() const {
575 /// dump - Print variable.
576 void DIVariable::dump() const {
577 if (const char *Res = getName())
578 errs() << " [" << Res << "] ";
580 getCompileUnit().dump();
581 errs() << " [" << getLineNumber() << "] ";
585 // FIXME: Dump complex addresses
588 //===----------------------------------------------------------------------===//
589 // DIFactory: Basic Helpers
590 //===----------------------------------------------------------------------===//
592 DIFactory::DIFactory(Module &m)
593 : M(m), VMContext(M.getContext()), StopPointFn(0), FuncStartFn(0),
594 RegionStartFn(0), RegionEndFn(0),
596 EmptyStructPtr = PointerType::getUnqual(StructType::get(VMContext));
599 Constant *DIFactory::GetTagConstant(unsigned TAG) {
600 assert((TAG & LLVMDebugVersionMask) == 0 &&
601 "Tag too large for debug encoding!");
602 return ConstantInt::get(Type::getInt32Ty(VMContext), TAG | LLVMDebugVersion);
605 //===----------------------------------------------------------------------===//
606 // DIFactory: Primary Constructors
607 //===----------------------------------------------------------------------===//
609 /// GetOrCreateArray - Create an descriptor for an array of descriptors.
610 /// This implicitly uniques the arrays created.
611 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
612 SmallVector<Value*, 16> Elts;
615 Elts.push_back(llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)));
617 for (unsigned i = 0; i != NumTys; ++i)
618 Elts.push_back(Tys[i].getNode());
620 return DIArray(MDNode::get(VMContext,Elts.data(), Elts.size()));
623 /// GetOrCreateSubrange - Create a descriptor for a value range. This
624 /// implicitly uniques the values returned.
625 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
627 GetTagConstant(dwarf::DW_TAG_subrange_type),
628 ConstantInt::get(Type::getInt64Ty(VMContext), Lo),
629 ConstantInt::get(Type::getInt64Ty(VMContext), Hi)
632 return DISubrange(MDNode::get(VMContext, &Elts[0], 3));
637 /// CreateCompileUnit - Create a new descriptor for the specified compile
638 /// unit. Note that this does not unique compile units within the module.
639 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
646 unsigned RunTimeVer) {
648 GetTagConstant(dwarf::DW_TAG_compile_unit),
649 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
650 ConstantInt::get(Type::getInt32Ty(VMContext), LangID),
651 MDString::get(VMContext, Filename),
652 MDString::get(VMContext, Directory),
653 MDString::get(VMContext, Producer),
654 ConstantInt::get(Type::getInt1Ty(VMContext), isMain),
655 ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
656 MDString::get(VMContext, Flags),
657 ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeVer)
660 return DICompileUnit(MDNode::get(VMContext, &Elts[0], 10));
663 /// CreateEnumerator - Create a single enumerator value.
664 DIEnumerator DIFactory::CreateEnumerator(StringRef Name, uint64_t Val){
666 GetTagConstant(dwarf::DW_TAG_enumerator),
667 MDString::get(VMContext, Name),
668 ConstantInt::get(Type::getInt64Ty(VMContext), Val)
670 return DIEnumerator(MDNode::get(VMContext, &Elts[0], 3));
674 /// CreateBasicType - Create a basic type like int, float, etc.
675 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
677 DICompileUnit CompileUnit,
680 uint64_t AlignInBits,
681 uint64_t OffsetInBits, unsigned Flags,
684 GetTagConstant(dwarf::DW_TAG_base_type),
686 MDString::get(VMContext, Name),
687 CompileUnit.getNode(),
688 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
689 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
690 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
691 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
692 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
693 ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
695 return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
698 /// CreateDerivedType - Create a derived type like const qualified type,
699 /// pointer, typedef, etc.
700 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
701 DIDescriptor Context,
703 DICompileUnit CompileUnit,
706 uint64_t AlignInBits,
707 uint64_t OffsetInBits,
709 DIType DerivedFrom) {
713 MDString::get(VMContext, Name),
714 CompileUnit.getNode(),
715 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
716 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
717 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
718 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
719 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
720 DerivedFrom.getNode(),
722 return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
725 /// CreateCompositeType - Create a composite type like array, struct, etc.
726 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
727 DIDescriptor Context,
729 DICompileUnit CompileUnit,
732 uint64_t AlignInBits,
733 uint64_t OffsetInBits,
737 unsigned RuntimeLang) {
742 MDString::get(VMContext, Name),
743 CompileUnit.getNode(),
744 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
745 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
746 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
747 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
748 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
749 DerivedFrom.getNode(),
751 ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang)
753 return DICompositeType(MDNode::get(VMContext, &Elts[0], 12));
757 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
758 /// See comments in DISubprogram for descriptions of these fields. This
759 /// method does not unique the generated descriptors.
760 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context,
762 StringRef DisplayName,
763 StringRef LinkageName,
764 DICompileUnit CompileUnit,
765 unsigned LineNo, DIType Type,
770 GetTagConstant(dwarf::DW_TAG_subprogram),
771 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
773 MDString::get(VMContext, Name),
774 MDString::get(VMContext, DisplayName),
775 MDString::get(VMContext, LinkageName),
776 CompileUnit.getNode(),
777 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
779 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
780 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition)
782 return DISubprogram(MDNode::get(VMContext, &Elts[0], 11));
785 /// CreateGlobalVariable - Create a new descriptor for the specified global.
787 DIFactory::CreateGlobalVariable(DIDescriptor Context, StringRef Name,
788 StringRef DisplayName,
789 StringRef LinkageName,
790 DICompileUnit CompileUnit,
791 unsigned LineNo, DIType Type,bool isLocalToUnit,
792 bool isDefinition, llvm::GlobalVariable *Val) {
794 GetTagConstant(dwarf::DW_TAG_variable),
795 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
797 MDString::get(VMContext, Name),
798 MDString::get(VMContext, DisplayName),
799 MDString::get(VMContext, LinkageName),
800 CompileUnit.getNode(),
801 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
803 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
804 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
808 Value *const *Vs = &Elts[0];
809 MDNode *Node = MDNode::get(VMContext,Vs, 12);
811 // Create a named metadata so that we do not lose this mdnode.
812 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.gv");
813 NMD->addElement(Node);
815 return DIGlobalVariable(Node);
819 /// CreateVariable - Create a new descriptor for the specified variable.
820 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
822 DICompileUnit CompileUnit, unsigned LineNo,
827 MDString::get(VMContext, Name),
828 CompileUnit.getNode(),
829 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
832 return DIVariable(MDNode::get(VMContext, &Elts[0], 6));
836 /// CreateComplexVariable - Create a new descriptor for the specified variable
837 /// which has a complex address expression for its address.
838 DIVariable DIFactory::CreateComplexVariable(unsigned Tag, DIDescriptor Context,
839 const std::string &Name,
840 DICompileUnit CompileUnit,
842 DIType Type, SmallVector<Value *, 9> &addr) {
843 SmallVector<Value *, 9> Elts;
844 Elts.push_back(GetTagConstant(Tag));
845 Elts.push_back(Context.getNode());
846 Elts.push_back(MDString::get(VMContext, Name));
847 Elts.push_back(CompileUnit.getNode());
848 Elts.push_back(ConstantInt::get(Type::getInt32Ty(VMContext), LineNo));
849 Elts.push_back(Type.getNode());
850 Elts.insert(Elts.end(), addr.begin(), addr.end());
852 return DIVariable(MDNode::get(VMContext, &Elts[0], 6+addr.size()));
856 /// CreateBlock - This creates a descriptor for a lexical block with the
857 /// specified parent VMContext.
858 DILexicalBlock DIFactory::CreateLexicalBlock(DIDescriptor Context) {
860 GetTagConstant(dwarf::DW_TAG_lexical_block),
863 return DILexicalBlock(MDNode::get(VMContext, &Elts[0], 2));
866 /// CreateLocation - Creates a debug info location.
867 DILocation DIFactory::CreateLocation(unsigned LineNo, unsigned ColumnNo,
868 DIScope S, DILocation OrigLoc) {
870 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
871 ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo),
875 return DILocation(MDNode::get(VMContext, &Elts[0], 4));
879 //===----------------------------------------------------------------------===//
880 // DIFactory: Routines for inserting code into a function
881 //===----------------------------------------------------------------------===//
883 /// InsertStopPoint - Create a new llvm.dbg.stoppoint intrinsic invocation,
884 /// inserting it at the end of the specified basic block.
885 void DIFactory::InsertStopPoint(DICompileUnit CU, unsigned LineNo,
886 unsigned ColNo, BasicBlock *BB) {
888 // Lazily construct llvm.dbg.stoppoint function.
890 StopPointFn = llvm::Intrinsic::getDeclaration(&M,
891 llvm::Intrinsic::dbg_stoppoint);
893 // Invoke llvm.dbg.stoppoint
895 ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo),
896 ConstantInt::get(llvm::Type::getInt32Ty(VMContext), ColNo),
899 CallInst::Create(StopPointFn, Args, Args+3, "", BB);
902 /// InsertSubprogramStart - Create a new llvm.dbg.func.start intrinsic to
903 /// mark the start of the specified subprogram.
904 void DIFactory::InsertSubprogramStart(DISubprogram SP, BasicBlock *BB) {
905 // Lazily construct llvm.dbg.func.start.
907 FuncStartFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_func_start);
909 // Call llvm.dbg.func.start which also implicitly sets a stoppoint.
910 CallInst::Create(FuncStartFn, SP.getNode(), "", BB);
913 /// InsertRegionStart - Insert a new llvm.dbg.region.start intrinsic call to
914 /// mark the start of a region for the specified scoping descriptor.
915 void DIFactory::InsertRegionStart(DIDescriptor D, BasicBlock *BB) {
916 // Lazily construct llvm.dbg.region.start function.
918 RegionStartFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_region_start);
920 // Call llvm.dbg.func.start.
921 CallInst::Create(RegionStartFn, D.getNode(), "", BB);
924 /// InsertRegionEnd - Insert a new llvm.dbg.region.end intrinsic call to
925 /// mark the end of a region for the specified scoping descriptor.
926 void DIFactory::InsertRegionEnd(DIDescriptor D, BasicBlock *BB) {
927 // Lazily construct llvm.dbg.region.end function.
929 RegionEndFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_region_end);
931 // Call llvm.dbg.region.end.
932 CallInst::Create(RegionEndFn, D.getNode(), "", BB);
935 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
936 void DIFactory::InsertDeclare(Value *Storage, DIVariable D,
937 Instruction *InsertBefore) {
938 // Cast the storage to a {}* for the call to llvm.dbg.declare.
939 Storage = new BitCastInst(Storage, EmptyStructPtr, "", InsertBefore);
942 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
944 Value *Args[] = { Storage, D.getNode() };
945 CallInst::Create(DeclareFn, Args, Args+2, "", InsertBefore);
948 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
949 void DIFactory::InsertDeclare(Value *Storage, DIVariable D,
950 BasicBlock *InsertAtEnd) {
951 // Cast the storage to a {}* for the call to llvm.dbg.declare.
952 Storage = new BitCastInst(Storage, EmptyStructPtr, "", InsertAtEnd);
955 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
957 Value *Args[] = { Storage, D.getNode() };
958 CallInst::Create(DeclareFn, Args, Args+2, "", InsertAtEnd);
962 //===----------------------------------------------------------------------===//
963 // DebugInfoFinder implementations.
964 //===----------------------------------------------------------------------===//
966 /// processModule - Process entire module and collect debug info.
967 void DebugInfoFinder::processModule(Module &M) {
969 #ifdef ATTACH_DEBUG_INFO_TO_AN_INSN
970 MetadataContext &TheMetadata = M.getContext().getMetadata();
971 unsigned MDDbgKind = TheMetadata.getMDKind("dbg");
975 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
976 for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI)
977 for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE;
979 if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(BI))
980 processStopPoint(SPI);
981 else if (DbgFuncStartInst *FSI = dyn_cast<DbgFuncStartInst>(BI))
982 processFuncStart(FSI);
983 else if (DbgRegionStartInst *DRS = dyn_cast<DbgRegionStartInst>(BI))
984 processRegionStart(DRS);
985 else if (DbgRegionEndInst *DRE = dyn_cast<DbgRegionEndInst>(BI))
986 processRegionEnd(DRE);
987 else if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
989 #ifdef ATTACH_DEBUG_INFO_TO_AN_INSN
990 else if (MDNode *L = TheMetadata.getMD(MDDbgKind, BI)) {
992 DIScope S(Loc.getScope().getNode());
993 if (S.isCompileUnit())
994 addCompileUnit(DICompileUnit(S.getNode()));
995 else if (S.isSubprogram())
996 processSubprogram(DISubprogram(S.getNode()));
997 else if (S.isLexicalBlock())
998 processLexicalBlock(DILexicalBlock(S.getNode()));
1003 NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv");
1007 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
1008 DIGlobalVariable DIG(cast<MDNode>(NMD->getElement(i)));
1009 if (addGlobalVariable(DIG)) {
1010 addCompileUnit(DIG.getCompileUnit());
1011 processType(DIG.getType());
1016 /// processType - Process DIType.
1017 void DebugInfoFinder::processType(DIType DT) {
1021 addCompileUnit(DT.getCompileUnit());
1022 if (DT.isCompositeType()) {
1023 DICompositeType DCT(DT.getNode());
1024 processType(DCT.getTypeDerivedFrom());
1025 DIArray DA = DCT.getTypeArray();
1027 for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
1028 DIDescriptor D = DA.getElement(i);
1029 DIType TypeE = DIType(D.getNode());
1030 if (!TypeE.isNull())
1033 processSubprogram(DISubprogram(D.getNode()));
1035 } else if (DT.isDerivedType()) {
1036 DIDerivedType DDT(DT.getNode());
1038 processType(DDT.getTypeDerivedFrom());
1042 /// processLexicalBlock
1043 void DebugInfoFinder::processLexicalBlock(DILexicalBlock LB) {
1046 DIScope Context = LB.getContext();
1047 if (Context.isLexicalBlock())
1048 return processLexicalBlock(DILexicalBlock(Context.getNode()));
1050 return processSubprogram(DISubprogram(Context.getNode()));
1053 /// processSubprogram - Process DISubprogram.
1054 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
1057 if (!addSubprogram(SP))
1059 addCompileUnit(SP.getCompileUnit());
1060 processType(SP.getType());
1063 /// processStopPoint - Process DbgStopPointInst.
1064 void DebugInfoFinder::processStopPoint(DbgStopPointInst *SPI) {
1065 MDNode *Context = dyn_cast<MDNode>(SPI->getContext());
1066 addCompileUnit(DICompileUnit(Context));
1069 /// processFuncStart - Process DbgFuncStartInst.
1070 void DebugInfoFinder::processFuncStart(DbgFuncStartInst *FSI) {
1071 MDNode *SP = dyn_cast<MDNode>(FSI->getSubprogram());
1072 processSubprogram(DISubprogram(SP));
1075 /// processRegionStart - Process DbgRegionStart.
1076 void DebugInfoFinder::processRegionStart(DbgRegionStartInst *DRS) {
1077 MDNode *SP = dyn_cast<MDNode>(DRS->getContext());
1078 processSubprogram(DISubprogram(SP));
1081 /// processRegionEnd - Process DbgRegionEnd.
1082 void DebugInfoFinder::processRegionEnd(DbgRegionEndInst *DRE) {
1083 MDNode *SP = dyn_cast<MDNode>(DRE->getContext());
1084 processSubprogram(DISubprogram(SP));
1087 /// processDeclare - Process DbgDeclareInst.
1088 void DebugInfoFinder::processDeclare(DbgDeclareInst *DDI) {
1089 DIVariable DV(cast<MDNode>(DDI->getVariable()));
1093 if (!NodesSeen.insert(DV.getNode()))
1096 addCompileUnit(DV.getCompileUnit());
1097 processType(DV.getType());
1100 /// addType - Add type into Tys.
1101 bool DebugInfoFinder::addType(DIType DT) {
1105 if (!NodesSeen.insert(DT.getNode()))
1108 TYs.push_back(DT.getNode());
1112 /// addCompileUnit - Add compile unit into CUs.
1113 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1117 if (!NodesSeen.insert(CU.getNode()))
1120 CUs.push_back(CU.getNode());
1124 /// addGlobalVariable - Add global variable into GVs.
1125 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1129 if (!NodesSeen.insert(DIG.getNode()))
1132 GVs.push_back(DIG.getNode());
1136 // addSubprogram - Add subprgoram into SPs.
1137 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1141 if (!NodesSeen.insert(SP.getNode()))
1144 SPs.push_back(SP.getNode());
1149 /// findStopPoint - Find the stoppoint coressponding to this instruction, that
1150 /// is the stoppoint that dominates this instruction.
1151 const DbgStopPointInst *findStopPoint(const Instruction *Inst) {
1152 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(Inst))
1155 const BasicBlock *BB = Inst->getParent();
1156 BasicBlock::const_iterator I = Inst, B;
1160 // A BB consisting only of a terminator can't have a stoppoint.
1163 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1167 // This BB didn't have a stoppoint: if there is only one predecessor, look
1168 // for a stoppoint there. We could use getIDom(), but that would require
1170 BB = I->getParent()->getUniquePredecessor();
1172 I = BB->getTerminator();
1178 /// findBBStopPoint - Find the stoppoint corresponding to first real
1179 /// (non-debug intrinsic) instruction in this Basic Block, and return the
1180 /// stoppoint for it.
1181 const DbgStopPointInst *findBBStopPoint(const BasicBlock *BB) {
1182 for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1183 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1186 // Fallback to looking for stoppoint of unique predecessor. Useful if this
1187 // BB contains no stoppoints, but unique predecessor does.
1188 BB = BB->getUniquePredecessor();
1190 return findStopPoint(BB->getTerminator());
1195 Value *findDbgGlobalDeclare(GlobalVariable *V) {
1196 const Module *M = V->getParent();
1197 NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv");
1201 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
1202 DIGlobalVariable DIG(cast_or_null<MDNode>(NMD->getElement(i)));
1205 if (DIG.getGlobal() == V)
1206 return DIG.getNode();
1211 /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
1212 /// It looks through pointer casts too.
1213 const DbgDeclareInst *findDbgDeclare(const Value *V, bool stripCasts) {
1215 V = V->stripPointerCasts();
1217 // Look for the bitcast.
1218 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1220 if (isa<BitCastInst>(I))
1221 return findDbgDeclare(*I, false);
1226 // Find llvm.dbg.declare among uses of the instruction.
1227 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1229 if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
1235 bool getLocationInfo(const Value *V, std::string &DisplayName,
1236 std::string &Type, unsigned &LineNo, std::string &File,
1241 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
1242 Value *DIGV = findDbgGlobalDeclare(GV);
1243 if (!DIGV) return false;
1244 DIGlobalVariable Var(cast<MDNode>(DIGV));
1246 if (const char *D = Var.getDisplayName())
1248 LineNo = Var.getLineNumber();
1249 Unit = Var.getCompileUnit();
1250 TypeD = Var.getType();
1252 const DbgDeclareInst *DDI = findDbgDeclare(V);
1253 if (!DDI) return false;
1254 DIVariable Var(cast<MDNode>(DDI->getVariable()));
1256 if (const char *D = Var.getName())
1258 LineNo = Var.getLineNumber();
1259 Unit = Var.getCompileUnit();
1260 TypeD = Var.getType();
1263 if (const char *T = TypeD.getName())
1265 if (const char *F = Unit.getFilename())
1267 if (const char *D = Unit.getDirectory())
1272 /// isValidDebugInfoIntrinsic - Return true if SPI is a valid debug
1274 bool isValidDebugInfoIntrinsic(DbgStopPointInst &SPI,
1275 CodeGenOpt::Level OptLev) {
1276 return DIDescriptor::ValidDebugInfo(SPI.getContext(), OptLev);
1279 /// isValidDebugInfoIntrinsic - Return true if FSI is a valid debug
1281 bool isValidDebugInfoIntrinsic(DbgFuncStartInst &FSI,
1282 CodeGenOpt::Level OptLev) {
1283 return DIDescriptor::ValidDebugInfo(FSI.getSubprogram(), OptLev);
1286 /// isValidDebugInfoIntrinsic - Return true if RSI is a valid debug
1288 bool isValidDebugInfoIntrinsic(DbgRegionStartInst &RSI,
1289 CodeGenOpt::Level OptLev) {
1290 return DIDescriptor::ValidDebugInfo(RSI.getContext(), OptLev);
1293 /// isValidDebugInfoIntrinsic - Return true if REI is a valid debug
1295 bool isValidDebugInfoIntrinsic(DbgRegionEndInst &REI,
1296 CodeGenOpt::Level OptLev) {
1297 return DIDescriptor::ValidDebugInfo(REI.getContext(), OptLev);
1301 /// isValidDebugInfoIntrinsic - Return true if DI is a valid debug
1303 bool isValidDebugInfoIntrinsic(DbgDeclareInst &DI,
1304 CodeGenOpt::Level OptLev) {
1305 return DIDescriptor::ValidDebugInfo(DI.getVariable(), OptLev);
1308 /// ExtractDebugLocation - Extract debug location information
1309 /// from llvm.dbg.stoppoint intrinsic.
1310 DebugLoc ExtractDebugLocation(DbgStopPointInst &SPI,
1311 DebugLocTracker &DebugLocInfo) {
1313 Value *Context = SPI.getContext();
1315 // If this location is already tracked then use it.
1316 DebugLocTuple Tuple(cast<MDNode>(Context), NULL, SPI.getLine(),
1318 DenseMap<DebugLocTuple, unsigned>::iterator II
1319 = DebugLocInfo.DebugIdMap.find(Tuple);
1320 if (II != DebugLocInfo.DebugIdMap.end())
1321 return DebugLoc::get(II->second);
1323 // Add a new location entry.
1324 unsigned Id = DebugLocInfo.DebugLocations.size();
1325 DebugLocInfo.DebugLocations.push_back(Tuple);
1326 DebugLocInfo.DebugIdMap[Tuple] = Id;
1328 return DebugLoc::get(Id);
1331 /// ExtractDebugLocation - Extract debug location information
1332 /// from DILocation.
1333 DebugLoc ExtractDebugLocation(DILocation &Loc,
1334 DebugLocTracker &DebugLocInfo) {
1336 MDNode *Context = Loc.getScope().getNode();
1337 MDNode *InlinedLoc = NULL;
1338 if (!Loc.getOrigLocation().isNull())
1339 InlinedLoc = Loc.getOrigLocation().getNode();
1340 // If this location is already tracked then use it.
1341 DebugLocTuple Tuple(Context, InlinedLoc, Loc.getLineNumber(),
1342 Loc.getColumnNumber());
1343 DenseMap<DebugLocTuple, unsigned>::iterator II
1344 = DebugLocInfo.DebugIdMap.find(Tuple);
1345 if (II != DebugLocInfo.DebugIdMap.end())
1346 return DebugLoc::get(II->second);
1348 // Add a new location entry.
1349 unsigned Id = DebugLocInfo.DebugLocations.size();
1350 DebugLocInfo.DebugLocations.push_back(Tuple);
1351 DebugLocInfo.DebugIdMap[Tuple] = Id;
1353 return DebugLoc::get(Id);
1356 /// ExtractDebugLocation - Extract debug location information
1357 /// from llvm.dbg.func_start intrinsic.
1358 DebugLoc ExtractDebugLocation(DbgFuncStartInst &FSI,
1359 DebugLocTracker &DebugLocInfo) {
1361 Value *SP = FSI.getSubprogram();
1363 DISubprogram Subprogram(cast<MDNode>(SP));
1364 unsigned Line = Subprogram.getLineNumber();
1365 DICompileUnit CU(Subprogram.getCompileUnit());
1367 // If this location is already tracked then use it.
1368 DebugLocTuple Tuple(CU.getNode(), NULL, Line, /* Column */ 0);
1369 DenseMap<DebugLocTuple, unsigned>::iterator II
1370 = DebugLocInfo.DebugIdMap.find(Tuple);
1371 if (II != DebugLocInfo.DebugIdMap.end())
1372 return DebugLoc::get(II->second);
1374 // Add a new location entry.
1375 unsigned Id = DebugLocInfo.DebugLocations.size();
1376 DebugLocInfo.DebugLocations.push_back(Tuple);
1377 DebugLocInfo.DebugIdMap[Tuple] = Id;
1379 return DebugLoc::get(Id);
1382 /// isInlinedFnStart - Return true if FSI is starting an inlined function.
1383 bool isInlinedFnStart(DbgFuncStartInst &FSI, const Function *CurrentFn) {
1384 DISubprogram Subprogram(cast<MDNode>(FSI.getSubprogram()));
1385 if (Subprogram.describes(CurrentFn))
1391 /// isInlinedFnEnd - Return true if REI is ending an inlined function.
1392 bool isInlinedFnEnd(DbgRegionEndInst &REI, const Function *CurrentFn) {
1393 DISubprogram Subprogram(cast<MDNode>(REI.getContext()));
1394 if (Subprogram.isNull() || Subprogram.describes(CurrentFn))