1 //===--- DebugInfo.cpp - Debug Information Helper Classes -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the helper classes used to build and interpret debug
11 // information in LLVM IR form.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Analysis/DebugInfo.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Intrinsics.h"
19 #include "llvm/IntrinsicInst.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/Dwarf.h"
28 #include "llvm/Support/raw_ostream.h"
30 using namespace llvm::dwarf;
32 //===----------------------------------------------------------------------===//
34 //===----------------------------------------------------------------------===//
36 DIDescriptor::DIDescriptor(const DIFile F) : DbgNode(F.DbgNode) {
39 DIDescriptor::DIDescriptor(const DISubprogram F) : DbgNode(F.DbgNode) {
42 DIDescriptor::DIDescriptor(const DILexicalBlock F) : DbgNode(F.DbgNode) {
45 DIDescriptor::DIDescriptor(const DIVariable F) : DbgNode(F.DbgNode) {
48 DIDescriptor::DIDescriptor(const DIType F) : DbgNode(F.DbgNode) {
52 DIDescriptor::getStringField(unsigned Elt) const {
56 if (Elt < DbgNode->getNumOperands())
57 if (MDString *MDS = dyn_cast_or_null<MDString>(DbgNode->getOperand(Elt)))
58 return MDS->getString();
63 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
67 if (Elt < DbgNode->getNumOperands())
68 if (ConstantInt *CI = dyn_cast<ConstantInt>(DbgNode->getOperand(Elt)))
69 return CI->getZExtValue();
74 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
76 return DIDescriptor();
78 if (Elt < DbgNode->getNumOperands())
80 DIDescriptor(dyn_cast_or_null<const MDNode>(DbgNode->getOperand(Elt)));
81 return DIDescriptor();
84 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
88 if (Elt < DbgNode->getNumOperands())
89 return dyn_cast_or_null<GlobalVariable>(DbgNode->getOperand(Elt));
93 Constant *DIDescriptor::getConstantField(unsigned Elt) const {
97 if (Elt < DbgNode->getNumOperands())
98 return dyn_cast_or_null<Constant>(DbgNode->getOperand(Elt));
102 Function *DIDescriptor::getFunctionField(unsigned Elt) const {
106 if (Elt < DbgNode->getNumOperands())
107 return dyn_cast_or_null<Function>(DbgNode->getOperand(Elt));
111 unsigned DIVariable::getNumAddrElements() const {
112 return DbgNode->getNumOperands()-6;
116 //===----------------------------------------------------------------------===//
118 //===----------------------------------------------------------------------===//
120 /// isBasicType - Return true if the specified tag is legal for
122 bool DIDescriptor::isBasicType() const {
123 return DbgNode && getTag() == dwarf::DW_TAG_base_type;
126 /// isDerivedType - Return true if the specified tag is legal for DIDerivedType.
127 bool DIDescriptor::isDerivedType() const {
128 if (!DbgNode) return false;
130 case dwarf::DW_TAG_typedef:
131 case dwarf::DW_TAG_pointer_type:
132 case dwarf::DW_TAG_reference_type:
133 case dwarf::DW_TAG_const_type:
134 case dwarf::DW_TAG_volatile_type:
135 case dwarf::DW_TAG_restrict_type:
136 case dwarf::DW_TAG_member:
137 case dwarf::DW_TAG_inheritance:
140 // CompositeTypes are currently modelled as DerivedTypes.
141 return isCompositeType();
145 /// isCompositeType - Return true if the specified tag is legal for
147 bool DIDescriptor::isCompositeType() const {
148 if (!DbgNode) return false;
150 case dwarf::DW_TAG_array_type:
151 case dwarf::DW_TAG_structure_type:
152 case dwarf::DW_TAG_union_type:
153 case dwarf::DW_TAG_enumeration_type:
154 case dwarf::DW_TAG_vector_type:
155 case dwarf::DW_TAG_subroutine_type:
156 case dwarf::DW_TAG_class_type:
163 /// isVariable - Return true if the specified tag is legal for DIVariable.
164 bool DIDescriptor::isVariable() const {
165 if (!DbgNode) return false;
167 case dwarf::DW_TAG_auto_variable:
168 case dwarf::DW_TAG_arg_variable:
169 case dwarf::DW_TAG_return_variable:
176 /// isType - Return true if the specified tag is legal for DIType.
177 bool DIDescriptor::isType() const {
178 return isBasicType() || isCompositeType() || isDerivedType();
181 /// isSubprogram - Return true if the specified tag is legal for
183 bool DIDescriptor::isSubprogram() const {
184 return DbgNode && getTag() == dwarf::DW_TAG_subprogram;
187 /// isGlobalVariable - Return true if the specified tag is legal for
188 /// DIGlobalVariable.
189 bool DIDescriptor::isGlobalVariable() const {
190 return DbgNode && (getTag() == dwarf::DW_TAG_variable ||
191 getTag() == dwarf::DW_TAG_constant);
194 /// isGlobal - Return true if the specified tag is legal for DIGlobal.
195 bool DIDescriptor::isGlobal() const {
196 return isGlobalVariable();
199 /// isScope - Return true if the specified tag is one of the scope
201 bool DIDescriptor::isScope() const {
202 if (!DbgNode) return false;
204 case dwarf::DW_TAG_compile_unit:
205 case dwarf::DW_TAG_lexical_block:
206 case dwarf::DW_TAG_subprogram:
207 case dwarf::DW_TAG_namespace:
215 /// isCompileUnit - Return true if the specified tag is DW_TAG_compile_unit.
216 bool DIDescriptor::isCompileUnit() const {
217 return DbgNode && getTag() == dwarf::DW_TAG_compile_unit;
220 /// isFile - Return true if the specified tag is DW_TAG_file_type.
221 bool DIDescriptor::isFile() const {
222 return DbgNode && getTag() == dwarf::DW_TAG_file_type;
225 /// isNameSpace - Return true if the specified tag is DW_TAG_namespace.
226 bool DIDescriptor::isNameSpace() const {
227 return DbgNode && getTag() == dwarf::DW_TAG_namespace;
230 /// isLexicalBlock - Return true if the specified tag is DW_TAG_lexical_block.
231 bool DIDescriptor::isLexicalBlock() const {
232 return DbgNode && getTag() == dwarf::DW_TAG_lexical_block;
235 /// isSubrange - Return true if the specified tag is DW_TAG_subrange_type.
236 bool DIDescriptor::isSubrange() const {
237 return DbgNode && getTag() == dwarf::DW_TAG_subrange_type;
240 /// isEnumerator - Return true if the specified tag is DW_TAG_enumerator.
241 bool DIDescriptor::isEnumerator() const {
242 return DbgNode && getTag() == dwarf::DW_TAG_enumerator;
245 //===----------------------------------------------------------------------===//
246 // Simple Descriptor Constructors and other Methods
247 //===----------------------------------------------------------------------===//
249 DIType::DIType(const MDNode *N) : DIScope(N) {
251 if (!isBasicType() && !isDerivedType() && !isCompositeType()) {
256 unsigned DIArray::getNumElements() const {
259 return DbgNode->getNumOperands();
262 /// replaceAllUsesWith - Replace all uses of debug info referenced by
264 void DIType::replaceAllUsesWith(DIDescriptor &D) {
268 // Since we use a TrackingVH for the node, its easy for clients to manufacture
269 // legitimate situations where they want to replaceAllUsesWith() on something
270 // which, due to uniquing, has merged with the source. We shield clients from
271 // this detail by allowing a value to be replaced with replaceAllUsesWith()
274 MDNode *Node = const_cast<MDNode*>(DbgNode);
275 const MDNode *DN = D;
276 const Value *V = cast_or_null<Value>(DN);
277 Node->replaceAllUsesWith(const_cast<Value*>(V));
278 MDNode::deleteTemporary(Node);
282 /// Verify - Verify that a compile unit is well formed.
283 bool DICompileUnit::Verify() const {
286 StringRef N = getFilename();
289 // It is possible that directory and produce string is empty.
293 /// Verify - Verify that a type descriptor is well formed.
294 bool DIType::Verify() const {
297 if (!getContext().Verify())
300 DICompileUnit CU = getCompileUnit();
306 /// Verify - Verify that a basic type descriptor is well formed.
307 bool DIBasicType::Verify() const {
308 return isBasicType();
311 /// Verify - Verify that a derived type descriptor is well formed.
312 bool DIDerivedType::Verify() const {
313 return isDerivedType();
316 /// Verify - Verify that a composite type descriptor is well formed.
317 bool DICompositeType::Verify() const {
320 if (!getContext().Verify())
323 DICompileUnit CU = getCompileUnit();
329 /// Verify - Verify that a subprogram descriptor is well formed.
330 bool DISubprogram::Verify() const {
334 if (!getContext().Verify())
337 DICompileUnit CU = getCompileUnit();
341 DICompositeType Ty = getType();
347 /// Verify - Verify that a global variable descriptor is well formed.
348 bool DIGlobalVariable::Verify() const {
352 if (getDisplayName().empty())
355 if (!getContext().Verify())
358 DICompileUnit CU = getCompileUnit();
362 DIType Ty = getType();
366 if (!getGlobal() && !getConstant())
372 /// Verify - Verify that a variable descriptor is well formed.
373 bool DIVariable::Verify() const {
377 if (!getContext().Verify())
380 if (!getCompileUnit().Verify())
383 DIType Ty = getType();
390 /// Verify - Verify that a location descriptor is well formed.
391 bool DILocation::Verify() const {
395 return DbgNode->getNumOperands() == 4;
398 /// Verify - Verify that a namespace descriptor is well formed.
399 bool DINameSpace::Verify() const {
402 if (getName().empty())
404 if (!getCompileUnit().Verify())
409 /// getOriginalTypeSize - If this type is derived from a base type then
410 /// return base type size.
411 uint64_t DIDerivedType::getOriginalTypeSize() const {
412 unsigned Tag = getTag();
413 if (Tag == dwarf::DW_TAG_member || Tag == dwarf::DW_TAG_typedef ||
414 Tag == dwarf::DW_TAG_const_type || Tag == dwarf::DW_TAG_volatile_type ||
415 Tag == dwarf::DW_TAG_restrict_type) {
416 DIType BaseType = getTypeDerivedFrom();
417 // If this type is not derived from any type then take conservative
419 if (!BaseType.isValid())
420 return getSizeInBits();
421 if (BaseType.isDerivedType())
422 return DIDerivedType(BaseType).getOriginalTypeSize();
424 return BaseType.getSizeInBits();
427 return getSizeInBits();
430 /// isInlinedFnArgument - Return true if this variable provides debugging
431 /// information for an inlined function arguments.
432 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
433 assert(CurFn && "Invalid function");
434 if (!getContext().isSubprogram())
436 // This variable is not inlined function argument if its scope
437 // does not describe current function.
438 return !(DISubprogram(getContext()).describes(CurFn));
441 /// describes - Return true if this subprogram provides debugging
442 /// information for the function F.
443 bool DISubprogram::describes(const Function *F) {
444 assert(F && "Invalid function");
445 if (F == getFunction())
447 StringRef Name = getLinkageName();
450 if (F->getName() == Name)
455 unsigned DISubprogram::isOptimized() const {
456 assert (DbgNode && "Invalid subprogram descriptor!");
457 if (DbgNode->getNumOperands() == 16)
458 return getUnsignedField(15);
462 StringRef DIScope::getFilename() const {
465 if (isLexicalBlock())
466 return DILexicalBlock(DbgNode).getFilename();
468 return DISubprogram(DbgNode).getFilename();
470 return DICompileUnit(DbgNode).getFilename();
472 return DINameSpace(DbgNode).getFilename();
474 return DIType(DbgNode).getFilename();
476 return DIFile(DbgNode).getFilename();
477 assert(0 && "Invalid DIScope!");
481 StringRef DIScope::getDirectory() const {
484 if (isLexicalBlock())
485 return DILexicalBlock(DbgNode).getDirectory();
487 return DISubprogram(DbgNode).getDirectory();
489 return DICompileUnit(DbgNode).getDirectory();
491 return DINameSpace(DbgNode).getDirectory();
493 return DIType(DbgNode).getDirectory();
495 return DIFile(DbgNode).getDirectory();
496 assert(0 && "Invalid DIScope!");
500 //===----------------------------------------------------------------------===//
501 // DIDescriptor: dump routines for all descriptors.
502 //===----------------------------------------------------------------------===//
505 /// print - Print descriptor.
506 void DIDescriptor::print(raw_ostream &OS) const {
507 OS << "[" << dwarf::TagString(getTag()) << "] ";
508 OS.write_hex((intptr_t) &*DbgNode) << ']';
511 /// print - Print compile unit.
512 void DICompileUnit::print(raw_ostream &OS) const {
514 OS << " [" << dwarf::LanguageString(getLanguage()) << "] ";
516 OS << " [" << getDirectory() << "/" << getFilename() << "]";
519 /// print - Print type.
520 void DIType::print(raw_ostream &OS) const {
521 if (!DbgNode) return;
523 StringRef Res = getName();
525 OS << " [" << Res << "] ";
527 unsigned Tag = getTag();
528 OS << " [" << dwarf::TagString(Tag) << "] ";
530 // TODO : Print context
531 getCompileUnit().print(OS);
533 << "line " << getLineNumber() << ", "
534 << getSizeInBits() << " bits, "
535 << getAlignInBits() << " bit alignment, "
536 << getOffsetInBits() << " bit offset"
541 else if (isProtected())
542 OS << " [protected] ";
548 DIBasicType(DbgNode).print(OS);
549 else if (isDerivedType())
550 DIDerivedType(DbgNode).print(OS);
551 else if (isCompositeType())
552 DICompositeType(DbgNode).print(OS);
554 OS << "Invalid DIType\n";
561 /// print - Print basic type.
562 void DIBasicType::print(raw_ostream &OS) const {
563 OS << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
566 /// print - Print derived type.
567 void DIDerivedType::print(raw_ostream &OS) const {
568 OS << "\n\t Derived From: "; getTypeDerivedFrom().print(OS);
571 /// print - Print composite type.
572 void DICompositeType::print(raw_ostream &OS) const {
573 DIArray A = getTypeArray();
574 OS << " [" << A.getNumElements() << " elements]";
577 /// print - Print subprogram.
578 void DISubprogram::print(raw_ostream &OS) const {
579 StringRef Res = getName();
581 OS << " [" << Res << "] ";
583 unsigned Tag = getTag();
584 OS << " [" << dwarf::TagString(Tag) << "] ";
586 // TODO : Print context
587 getCompileUnit().print(OS);
588 OS << " [" << getLineNumber() << "] ";
599 /// print - Print global variable.
600 void DIGlobalVariable::print(raw_ostream &OS) const {
602 StringRef Res = getName();
604 OS << " [" << Res << "] ";
606 unsigned Tag = getTag();
607 OS << " [" << dwarf::TagString(Tag) << "] ";
609 // TODO : Print context
610 getCompileUnit().print(OS);
611 OS << " [" << getLineNumber() << "] ";
619 if (isGlobalVariable())
620 DIGlobalVariable(DbgNode).print(OS);
624 /// print - Print variable.
625 void DIVariable::print(raw_ostream &OS) const {
626 StringRef Res = getName();
628 OS << " [" << Res << "] ";
630 getCompileUnit().print(OS);
631 OS << " [" << getLineNumber() << "] ";
635 // FIXME: Dump complex addresses
638 /// dump - Print descriptor to dbgs() with a newline.
639 void DIDescriptor::dump() const {
640 print(dbgs()); dbgs() << '\n';
643 /// dump - Print compile unit to dbgs() with a newline.
644 void DICompileUnit::dump() const {
645 print(dbgs()); dbgs() << '\n';
648 /// dump - Print type to dbgs() with a newline.
649 void DIType::dump() const {
650 print(dbgs()); dbgs() << '\n';
653 /// dump - Print basic type to dbgs() with a newline.
654 void DIBasicType::dump() const {
655 print(dbgs()); dbgs() << '\n';
658 /// dump - Print derived type to dbgs() with a newline.
659 void DIDerivedType::dump() const {
660 print(dbgs()); dbgs() << '\n';
663 /// dump - Print composite type to dbgs() with a newline.
664 void DICompositeType::dump() const {
665 print(dbgs()); dbgs() << '\n';
668 /// dump - Print subprogram to dbgs() with a newline.
669 void DISubprogram::dump() const {
670 print(dbgs()); dbgs() << '\n';
673 /// dump - Print global variable.
674 void DIGlobalVariable::dump() const {
675 print(dbgs()); dbgs() << '\n';
678 /// dump - Print variable.
679 void DIVariable::dump() const {
680 print(dbgs()); dbgs() << '\n';
683 //===----------------------------------------------------------------------===//
684 // DIFactory: Basic Helpers
685 //===----------------------------------------------------------------------===//
687 DIFactory::DIFactory(Module &m)
688 : M(m), VMContext(M.getContext()), DeclareFn(0), ValueFn(0) {}
690 Constant *DIFactory::GetTagConstant(unsigned TAG) {
691 assert((TAG & LLVMDebugVersionMask) == 0 &&
692 "Tag too large for debug encoding!");
693 return ConstantInt::get(Type::getInt32Ty(VMContext), TAG | LLVMDebugVersion);
696 //===----------------------------------------------------------------------===//
697 // DIFactory: Primary Constructors
698 //===----------------------------------------------------------------------===//
700 /// GetOrCreateArray - Create an descriptor for an array of descriptors.
701 /// This implicitly uniques the arrays created.
702 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
703 SmallVector<Value*, 16> Elts;
706 Elts.push_back(llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)));
708 for (unsigned i = 0; i != NumTys; ++i)
709 Elts.push_back(Tys[i]);
711 return DIArray(MDNode::get(VMContext,Elts.data(), Elts.size()));
714 /// GetOrCreateSubrange - Create a descriptor for a value range. This
715 /// implicitly uniques the values returned.
716 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
718 GetTagConstant(dwarf::DW_TAG_subrange_type),
719 ConstantInt::get(Type::getInt64Ty(VMContext), Lo),
720 ConstantInt::get(Type::getInt64Ty(VMContext), Hi)
723 return DISubrange(MDNode::get(VMContext, &Elts[0], 3));
728 /// CreateCompileUnit - Create a new descriptor for the specified compile
729 /// unit. Note that this does not unique compile units within the module.
730 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
737 unsigned RunTimeVer) {
739 GetTagConstant(dwarf::DW_TAG_compile_unit),
740 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
741 ConstantInt::get(Type::getInt32Ty(VMContext), LangID),
742 MDString::get(VMContext, Filename),
743 MDString::get(VMContext, Directory),
744 MDString::get(VMContext, Producer),
745 ConstantInt::get(Type::getInt1Ty(VMContext), isMain),
746 ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
747 MDString::get(VMContext, Flags),
748 ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeVer)
751 return DICompileUnit(MDNode::get(VMContext, &Elts[0], 10));
754 /// CreateFile - Create a new descriptor for the specified file.
755 DIFile DIFactory::CreateFile(StringRef Filename,
759 GetTagConstant(dwarf::DW_TAG_file_type),
760 MDString::get(VMContext, Filename),
761 MDString::get(VMContext, Directory),
765 return DIFile(MDNode::get(VMContext, &Elts[0], 4));
768 /// CreateEnumerator - Create a single enumerator value.
769 DIEnumerator DIFactory::CreateEnumerator(StringRef Name, uint64_t Val){
771 GetTagConstant(dwarf::DW_TAG_enumerator),
772 MDString::get(VMContext, Name),
773 ConstantInt::get(Type::getInt64Ty(VMContext), Val)
775 return DIEnumerator(MDNode::get(VMContext, &Elts[0], 3));
779 /// CreateBasicType - Create a basic type like int, float, etc.
780 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
785 uint64_t AlignInBits,
786 uint64_t OffsetInBits, unsigned Flags,
789 GetTagConstant(dwarf::DW_TAG_base_type),
791 MDString::get(VMContext, Name),
793 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
794 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
795 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
796 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
797 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
798 ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
800 return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
804 /// CreateBasicType - Create a basic type like int, float, etc.
805 DIBasicType DIFactory::CreateBasicTypeEx(DIDescriptor Context,
809 Constant *SizeInBits,
810 Constant *AlignInBits,
811 Constant *OffsetInBits, unsigned Flags,
814 GetTagConstant(dwarf::DW_TAG_base_type),
816 MDString::get(VMContext, Name),
818 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
822 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
823 ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
825 return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
828 /// CreateArtificialType - Create a new DIType with "artificial" flag set.
829 DIType DIFactory::CreateArtificialType(DIType Ty) {
830 if (Ty.isArtificial())
833 SmallVector<Value *, 9> Elts;
835 assert (N && "Unexpected input DIType!");
836 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
837 if (Value *V = N->getOperand(i))
840 Elts.push_back(Constant::getNullValue(Type::getInt32Ty(VMContext)));
843 unsigned CurFlags = Ty.getFlags();
844 CurFlags = CurFlags | DIType::FlagArtificial;
846 // Flags are stored at this slot.
847 Elts[8] = ConstantInt::get(Type::getInt32Ty(VMContext), CurFlags);
849 return DIType(MDNode::get(VMContext, Elts.data(), Elts.size()));
852 /// CreateDerivedType - Create a derived type like const qualified type,
853 /// pointer, typedef, etc.
854 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
855 DIDescriptor Context,
860 uint64_t AlignInBits,
861 uint64_t OffsetInBits,
863 DIType DerivedFrom) {
867 MDString::get(VMContext, Name),
869 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
870 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
871 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
872 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
873 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
876 return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
880 /// CreateDerivedType - Create a derived type like const qualified type,
881 /// pointer, typedef, etc.
882 DIDerivedType DIFactory::CreateDerivedTypeEx(unsigned Tag,
883 DIDescriptor Context,
887 Constant *SizeInBits,
888 Constant *AlignInBits,
889 Constant *OffsetInBits,
891 DIType DerivedFrom) {
895 MDString::get(VMContext, Name),
897 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
901 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
904 return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
908 /// CreateCompositeType - Create a composite type like array, struct, etc.
909 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
910 DIDescriptor Context,
915 uint64_t AlignInBits,
916 uint64_t OffsetInBits,
920 unsigned RuntimeLang,
921 MDNode *ContainingType) {
926 MDString::get(VMContext, Name),
928 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
929 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
930 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
931 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
932 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
935 ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang),
939 MDNode *Node = MDNode::get(VMContext, &Elts[0], 13);
940 // Create a named metadata so that we do not lose this enum info.
941 if (Tag == dwarf::DW_TAG_enumeration_type) {
942 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.enum");
943 NMD->addOperand(Node);
945 return DICompositeType(Node);
949 /// CreateTemporaryType - Create a temporary forward-declared type.
950 DIType DIFactory::CreateTemporaryType() {
951 // Give the temporary MDNode a tag. It doesn't matter what tag we
952 // use here as long as DIType accepts it.
954 GetTagConstant(DW_TAG_base_type)
956 MDNode *Node = MDNode::getTemporary(VMContext, Elts, array_lengthof(Elts));
961 /// CreateCompositeType - Create a composite type like array, struct, etc.
962 DICompositeType DIFactory::CreateCompositeTypeEx(unsigned Tag,
963 DIDescriptor Context,
967 Constant *SizeInBits,
968 Constant *AlignInBits,
969 Constant *OffsetInBits,
973 unsigned RuntimeLang,
974 MDNode *ContainingType) {
978 MDString::get(VMContext, Name),
980 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
984 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
987 ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang),
990 MDNode *Node = MDNode::get(VMContext, &Elts[0], 13);
991 // Create a named metadata so that we do not lose this enum info.
992 if (Tag == dwarf::DW_TAG_enumeration_type) {
993 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.enum");
994 NMD->addOperand(Node);
996 return DICompositeType(Node);
1000 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
1001 /// See comments in DISubprogram for descriptions of these fields. This
1002 /// method does not unique the generated descriptors.
1003 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context,
1005 StringRef DisplayName,
1006 StringRef LinkageName,
1008 unsigned LineNo, DIType Ty,
1011 unsigned VK, unsigned VIndex,
1012 DIType ContainingType,
1018 GetTagConstant(dwarf::DW_TAG_subprogram),
1019 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
1021 MDString::get(VMContext, Name),
1022 MDString::get(VMContext, DisplayName),
1023 MDString::get(VMContext, LinkageName),
1025 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1027 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
1028 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
1029 ConstantInt::get(Type::getInt32Ty(VMContext), (unsigned)VK),
1030 ConstantInt::get(Type::getInt32Ty(VMContext), VIndex),
1032 ConstantInt::get(Type::getInt1Ty(VMContext), isArtificial),
1033 ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
1036 MDNode *Node = MDNode::get(VMContext, &Elts[0], 17);
1038 // Create a named metadata so that we do not lose this mdnode.
1039 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.sp");
1040 NMD->addOperand(Node);
1041 return DISubprogram(Node);
1044 /// CreateSubprogramDefinition - Create new subprogram descriptor for the
1045 /// given declaration.
1046 DISubprogram DIFactory::CreateSubprogramDefinition(DISubprogram &SPDeclaration){
1047 if (SPDeclaration.isDefinition())
1048 return DISubprogram(SPDeclaration);
1050 MDNode *DeclNode = SPDeclaration;
1052 GetTagConstant(dwarf::DW_TAG_subprogram),
1053 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
1054 DeclNode->getOperand(2), // Context
1055 DeclNode->getOperand(3), // Name
1056 DeclNode->getOperand(4), // DisplayName
1057 DeclNode->getOperand(5), // LinkageName
1058 DeclNode->getOperand(6), // CompileUnit
1059 DeclNode->getOperand(7), // LineNo
1060 DeclNode->getOperand(8), // Type
1061 DeclNode->getOperand(9), // isLocalToUnit
1062 ConstantInt::get(Type::getInt1Ty(VMContext), true),
1063 DeclNode->getOperand(11), // Virtuality
1064 DeclNode->getOperand(12), // VIndex
1065 DeclNode->getOperand(13), // Containting Type
1066 DeclNode->getOperand(14), // isArtificial
1067 DeclNode->getOperand(15), // isOptimized
1068 SPDeclaration.getFunction()
1070 MDNode *Node =MDNode::get(VMContext, &Elts[0], 16);
1072 // Create a named metadata so that we do not lose this mdnode.
1073 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.sp");
1074 NMD->addOperand(Node);
1075 return DISubprogram(Node);
1078 /// CreateGlobalVariable - Create a new descriptor for the specified global.
1080 DIFactory::CreateGlobalVariable(DIDescriptor Context, StringRef Name,
1081 StringRef DisplayName,
1082 StringRef LinkageName,
1084 unsigned LineNo, DIType Ty,bool isLocalToUnit,
1085 bool isDefinition, llvm::GlobalVariable *Val) {
1087 GetTagConstant(dwarf::DW_TAG_variable),
1088 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
1090 MDString::get(VMContext, Name),
1091 MDString::get(VMContext, DisplayName),
1092 MDString::get(VMContext, LinkageName),
1094 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1096 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
1097 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
1101 Value *const *Vs = &Elts[0];
1102 MDNode *Node = MDNode::get(VMContext,Vs, 12);
1104 // Create a named metadata so that we do not lose this mdnode.
1105 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.gv");
1106 NMD->addOperand(Node);
1108 return DIGlobalVariable(Node);
1111 /// CreateGlobalVariable - Create a new descriptor for the specified constant.
1113 DIFactory::CreateGlobalVariable(DIDescriptor Context, StringRef Name,
1114 StringRef DisplayName,
1115 StringRef LinkageName,
1117 unsigned LineNo, DIType Ty,bool isLocalToUnit,
1118 bool isDefinition, llvm::Constant *Val) {
1120 GetTagConstant(dwarf::DW_TAG_variable),
1121 llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
1123 MDString::get(VMContext, Name),
1124 MDString::get(VMContext, DisplayName),
1125 MDString::get(VMContext, LinkageName),
1127 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1129 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
1130 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
1134 Value *const *Vs = &Elts[0];
1135 MDNode *Node = MDNode::get(VMContext,Vs, 12);
1137 // Create a named metadata so that we do not lose this mdnode.
1138 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.gv");
1139 NMD->addOperand(Node);
1141 return DIGlobalVariable(Node);
1144 /// CreateVariable - Create a new descriptor for the specified variable.
1145 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
1149 DIType Ty, bool AlwaysPreserve) {
1151 GetTagConstant(Tag),
1153 MDString::get(VMContext, Name),
1155 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1158 MDNode *Node = MDNode::get(VMContext, &Elts[0], 6);
1159 if (AlwaysPreserve) {
1160 // The optimizer may remove local variable. If there is an interest
1161 // to preserve variable info in such situation then stash it in a
1163 DISubprogram Fn(getDISubprogram(Context));
1164 StringRef FName = "fn";
1165 if (Fn.getFunction())
1166 FName = Fn.getFunction()->getName();
1168 if (FName.startswith(StringRef(&One, 1)))
1169 FName = FName.substr(1);
1171 SmallString<32> Out;
1172 NamedMDNode *FnLocals =
1173 M.getOrInsertNamedMetadata(Twine("llvm.dbg.lv.", FName).toStringRef(Out));
1174 FnLocals->addOperand(Node);
1176 return DIVariable(Node);
1180 /// CreateComplexVariable - Create a new descriptor for the specified variable
1181 /// which has a complex address expression for its address.
1182 DIVariable DIFactory::CreateComplexVariable(unsigned Tag, DIDescriptor Context,
1183 const std::string &Name,
1187 SmallVector<Value *, 9> &addr) {
1188 SmallVector<Value *, 9> Elts;
1189 Elts.push_back(GetTagConstant(Tag));
1190 Elts.push_back(Context);
1191 Elts.push_back(MDString::get(VMContext, Name));
1193 Elts.push_back(ConstantInt::get(Type::getInt32Ty(VMContext), LineNo));
1195 Elts.insert(Elts.end(), addr.begin(), addr.end());
1197 return DIVariable(MDNode::get(VMContext, &Elts[0], 6+addr.size()));
1201 /// CreateBlock - This creates a descriptor for a lexical block with the
1202 /// specified parent VMContext.
1203 DILexicalBlock DIFactory::CreateLexicalBlock(DIDescriptor Context,
1204 DIFile F, unsigned LineNo,
1206 // Defeat MDNode uniqing for lexical blocks.
1207 static unsigned int unique_id = 0;
1209 GetTagConstant(dwarf::DW_TAG_lexical_block),
1211 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1212 ConstantInt::get(Type::getInt32Ty(VMContext), Col),
1214 ConstantInt::get(Type::getInt32Ty(VMContext), unique_id++)
1216 return DILexicalBlock(MDNode::get(VMContext, &Elts[0], 6));
1219 /// CreateNameSpace - This creates new descriptor for a namespace
1220 /// with the specified parent context.
1221 DINameSpace DIFactory::CreateNameSpace(DIDescriptor Context, StringRef Name,
1225 GetTagConstant(dwarf::DW_TAG_namespace),
1227 MDString::get(VMContext, Name),
1229 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo)
1231 return DINameSpace(MDNode::get(VMContext, &Elts[0], 5));
1234 /// CreateLocation - Creates a debug info location.
1235 DILocation DIFactory::CreateLocation(unsigned LineNo, unsigned ColumnNo,
1236 DIScope S, DILocation OrigLoc) {
1238 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1239 ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo),
1243 return DILocation(MDNode::get(VMContext, &Elts[0], 4));
1246 //===----------------------------------------------------------------------===//
1247 // DIFactory: Routines for inserting code into a function
1248 //===----------------------------------------------------------------------===//
1250 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1251 Instruction *DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1252 Instruction *InsertBefore) {
1253 assert(Storage && "no storage passed to dbg.declare");
1254 assert(D.Verify() && "empty DIVariable passed to dbg.declare");
1256 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1258 Value *Args[] = { MDNode::get(Storage->getContext(), &Storage, 1),
1260 return CallInst::Create(DeclareFn, Args, Args+2, "", InsertBefore);
1263 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1264 Instruction *DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1265 BasicBlock *InsertAtEnd) {
1266 assert(Storage && "no storage passed to dbg.declare");
1267 assert(D.Verify() && "invalid DIVariable passed to dbg.declare");
1269 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1271 Value *Args[] = { MDNode::get(Storage->getContext(), &Storage, 1),
1274 // If this block already has a terminator then insert this intrinsic
1275 // before the terminator.
1276 if (TerminatorInst *T = InsertAtEnd->getTerminator())
1277 return CallInst::Create(DeclareFn, Args, Args+2, "", T);
1279 return CallInst::Create(DeclareFn, Args, Args+2, "", InsertAtEnd);}
1281 /// InsertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
1282 Instruction *DIFactory::InsertDbgValueIntrinsic(Value *V, uint64_t Offset,
1284 Instruction *InsertBefore) {
1285 assert(V && "no value passed to dbg.value");
1286 assert(D.Verify() && "invalid DIVariable passed to dbg.value");
1288 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1290 Value *Args[] = { MDNode::get(V->getContext(), &V, 1),
1291 ConstantInt::get(Type::getInt64Ty(V->getContext()), Offset),
1293 return CallInst::Create(ValueFn, Args, Args+3, "", InsertBefore);
1296 /// InsertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
1297 Instruction *DIFactory::InsertDbgValueIntrinsic(Value *V, uint64_t Offset,
1299 BasicBlock *InsertAtEnd) {
1300 assert(V && "no value passed to dbg.value");
1301 assert(D.Verify() && "invalid DIVariable passed to dbg.value");
1303 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1305 Value *Args[] = { MDNode::get(V->getContext(), &V, 1),
1306 ConstantInt::get(Type::getInt64Ty(V->getContext()), Offset),
1308 return CallInst::Create(ValueFn, Args, Args+3, "", InsertAtEnd);
1311 //===----------------------------------------------------------------------===//
1312 // DebugInfoFinder implementations.
1313 //===----------------------------------------------------------------------===//
1315 /// processModule - Process entire module and collect debug info.
1316 void DebugInfoFinder::processModule(Module &M) {
1317 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1318 for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI)
1319 for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE;
1321 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
1322 processDeclare(DDI);
1324 DebugLoc Loc = BI->getDebugLoc();
1325 if (Loc.isUnknown())
1328 LLVMContext &Ctx = BI->getContext();
1329 DIDescriptor Scope(Loc.getScope(Ctx));
1331 if (Scope.isCompileUnit())
1332 addCompileUnit(DICompileUnit(Scope));
1333 else if (Scope.isSubprogram())
1334 processSubprogram(DISubprogram(Scope));
1335 else if (Scope.isLexicalBlock())
1336 processLexicalBlock(DILexicalBlock(Scope));
1338 if (MDNode *IA = Loc.getInlinedAt(Ctx))
1339 processLocation(DILocation(IA));
1342 if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv")) {
1343 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1344 DIGlobalVariable DIG(cast<MDNode>(NMD->getOperand(i)));
1345 if (addGlobalVariable(DIG)) {
1346 addCompileUnit(DIG.getCompileUnit());
1347 processType(DIG.getType());
1352 if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.sp"))
1353 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
1354 processSubprogram(DISubprogram(NMD->getOperand(i)));
1357 /// processLocation - Process DILocation.
1358 void DebugInfoFinder::processLocation(DILocation Loc) {
1359 if (!Loc.Verify()) return;
1360 DIDescriptor S(Loc.getScope());
1361 if (S.isCompileUnit())
1362 addCompileUnit(DICompileUnit(S));
1363 else if (S.isSubprogram())
1364 processSubprogram(DISubprogram(S));
1365 else if (S.isLexicalBlock())
1366 processLexicalBlock(DILexicalBlock(S));
1367 processLocation(Loc.getOrigLocation());
1370 /// processType - Process DIType.
1371 void DebugInfoFinder::processType(DIType DT) {
1375 addCompileUnit(DT.getCompileUnit());
1376 if (DT.isCompositeType()) {
1377 DICompositeType DCT(DT);
1378 processType(DCT.getTypeDerivedFrom());
1379 DIArray DA = DCT.getTypeArray();
1380 for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
1381 DIDescriptor D = DA.getElement(i);
1383 processType(DIType(D));
1384 else if (D.isSubprogram())
1385 processSubprogram(DISubprogram(D));
1387 } else if (DT.isDerivedType()) {
1388 DIDerivedType DDT(DT);
1389 processType(DDT.getTypeDerivedFrom());
1393 /// processLexicalBlock
1394 void DebugInfoFinder::processLexicalBlock(DILexicalBlock LB) {
1395 DIScope Context = LB.getContext();
1396 if (Context.isLexicalBlock())
1397 return processLexicalBlock(DILexicalBlock(Context));
1399 return processSubprogram(DISubprogram(Context));
1402 /// processSubprogram - Process DISubprogram.
1403 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
1404 if (!addSubprogram(SP))
1406 addCompileUnit(SP.getCompileUnit());
1407 processType(SP.getType());
1410 /// processDeclare - Process DbgDeclareInst.
1411 void DebugInfoFinder::processDeclare(DbgDeclareInst *DDI) {
1412 MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
1416 if (!DV.isVariable())
1419 if (!NodesSeen.insert(DV))
1422 addCompileUnit(DIVariable(N).getCompileUnit());
1423 processType(DIVariable(N).getType());
1426 /// addType - Add type into Tys.
1427 bool DebugInfoFinder::addType(DIType DT) {
1431 if (!NodesSeen.insert(DT))
1438 /// addCompileUnit - Add compile unit into CUs.
1439 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1443 if (!NodesSeen.insert(CU))
1450 /// addGlobalVariable - Add global variable into GVs.
1451 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1452 if (!DIDescriptor(DIG).isGlobalVariable())
1455 if (!NodesSeen.insert(DIG))
1462 // addSubprogram - Add subprgoram into SPs.
1463 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1464 if (!DIDescriptor(SP).isSubprogram())
1467 if (!NodesSeen.insert(SP))
1474 /// Find the debug info descriptor corresponding to this global variable.
1475 static Value *findDbgGlobalDeclare(GlobalVariable *V) {
1476 const Module *M = V->getParent();
1477 NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv");
1481 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1482 DIDescriptor DIG(cast<MDNode>(NMD->getOperand(i)));
1483 if (!DIG.isGlobalVariable())
1485 if (DIGlobalVariable(DIG).getGlobal() == V)
1491 /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
1492 /// It looks through pointer casts too.
1493 static const DbgDeclareInst *findDbgDeclare(const Value *V) {
1494 V = V->stripPointerCasts();
1496 if (!isa<Instruction>(V) && !isa<Argument>(V))
1499 const Function *F = NULL;
1500 if (const Instruction *I = dyn_cast<Instruction>(V))
1501 F = I->getParent()->getParent();
1502 else if (const Argument *A = dyn_cast<Argument>(V))
1505 for (Function::const_iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
1506 for (BasicBlock::const_iterator BI = (*FI).begin(), BE = (*FI).end();
1508 if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
1509 if (DDI->getAddress() == V)
1515 bool llvm::getLocationInfo(const Value *V, std::string &DisplayName,
1516 std::string &Type, unsigned &LineNo,
1517 std::string &File, std::string &Dir) {
1521 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
1522 Value *DIGV = findDbgGlobalDeclare(GV);
1523 if (!DIGV) return false;
1524 DIGlobalVariable Var(cast<MDNode>(DIGV));
1526 StringRef D = Var.getDisplayName();
1529 LineNo = Var.getLineNumber();
1530 Unit = Var.getCompileUnit();
1531 TypeD = Var.getType();
1533 const DbgDeclareInst *DDI = findDbgDeclare(V);
1534 if (!DDI) return false;
1535 DIVariable Var(cast<MDNode>(DDI->getVariable()));
1537 StringRef D = Var.getName();
1540 LineNo = Var.getLineNumber();
1541 Unit = Var.getCompileUnit();
1542 TypeD = Var.getType();
1545 StringRef T = TypeD.getName();
1548 StringRef F = Unit.getFilename();
1551 StringRef D = Unit.getDirectory();
1557 /// getDISubprogram - Find subprogram that is enclosing this scope.
1558 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
1559 DIDescriptor D(Scope);
1560 if (D.isSubprogram())
1561 return DISubprogram(Scope);
1563 if (D.isLexicalBlock())
1564 return getDISubprogram(DILexicalBlock(Scope).getContext());
1566 return DISubprogram();
1569 /// getDICompositeType - Find underlying composite type.
1570 DICompositeType llvm::getDICompositeType(DIType T) {
1571 if (T.isCompositeType())
1572 return DICompositeType(T);
1574 if (T.isDerivedType())
1575 return getDICompositeType(DIDerivedType(T).getTypeDerivedFrom());
1577 return DICompositeType();