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/Support/Dwarf.h"
25 #include "llvm/Support/DebugLoc.h"
26 #include "llvm/Support/Streams.h"
29 using namespace llvm::dwarf;
31 //===----------------------------------------------------------------------===//
33 //===----------------------------------------------------------------------===//
35 /// ValidDebugInfo - Return true if V represents valid debug info value.
36 bool DIDescriptor::ValidDebugInfo(Value *V, CodeGenOpt::Level OptLevel) {
40 GlobalVariable *GV = dyn_cast<GlobalVariable>(V->stripPointerCasts());
44 if (!GV->hasInternalLinkage () && !GV->hasLinkOnceLinkage())
49 // Check current version. Allow Version6 for now.
50 unsigned Version = DI.getVersion();
51 if (Version != LLVMDebugVersion && Version != LLVMDebugVersion6)
54 unsigned Tag = DI.getTag();
57 assert(DIVariable(GV).Verify() && "Invalid DebugInfo value");
59 case DW_TAG_compile_unit:
60 assert(DICompileUnit(GV).Verify() && "Invalid DebugInfo value");
62 case DW_TAG_subprogram:
63 assert(DISubprogram(GV).Verify() && "Invalid DebugInfo value");
65 case DW_TAG_lexical_block:
66 // FIXME: This interfers with the quality of generated code during
68 if (OptLevel != CodeGenOpt::None)
78 DIDescriptor::DIDescriptor(GlobalVariable *GV, unsigned RequiredTag) {
81 // If this is non-null, check to see if the Tag matches. If not, set to null.
82 if (GV && getTag() != RequiredTag)
87 DIDescriptor::getStringField(unsigned Elt, std::string &Result) const {
93 Constant *C = DbgGV->getInitializer();
94 if (C == 0 || Elt >= C->getNumOperands()) {
99 // Fills in the string if it succeeds
100 if (!GetConstantStringInfo(C->getOperand(Elt), Result))
106 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
107 if (DbgGV == 0) return 0;
108 if (!DbgGV->hasInitializer()) return 0;
110 Constant *C = DbgGV->getInitializer();
111 if (C == 0 || Elt >= C->getNumOperands())
114 if (ConstantInt *CI = dyn_cast<ConstantInt>(C->getOperand(Elt)))
115 return CI->getZExtValue();
119 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
120 if (DbgGV == 0) return DIDescriptor();
122 Constant *C = DbgGV->getInitializer();
123 if (C == 0 || Elt >= C->getNumOperands())
124 return DIDescriptor();
126 C = C->getOperand(Elt);
127 return DIDescriptor(dyn_cast<GlobalVariable>(C->stripPointerCasts()));
130 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
131 if (DbgGV == 0) return 0;
133 Constant *C = DbgGV->getInitializer();
134 if (C == 0 || Elt >= C->getNumOperands())
137 C = C->getOperand(Elt);
138 return dyn_cast<GlobalVariable>(C->stripPointerCasts());
141 //===----------------------------------------------------------------------===//
142 // Simple Descriptor Constructors and other Methods
143 //===----------------------------------------------------------------------===//
145 // Needed by DIVariable::getType().
146 DIType::DIType(GlobalVariable *GV) : DIDescriptor(GV) {
148 unsigned tag = getTag();
149 if (tag != dwarf::DW_TAG_base_type && !DIDerivedType::isDerivedType(tag) &&
150 !DICompositeType::isCompositeType(tag))
154 /// isDerivedType - Return true if the specified tag is legal for
156 bool DIType::isDerivedType(unsigned Tag) {
158 case dwarf::DW_TAG_typedef:
159 case dwarf::DW_TAG_pointer_type:
160 case dwarf::DW_TAG_reference_type:
161 case dwarf::DW_TAG_const_type:
162 case dwarf::DW_TAG_volatile_type:
163 case dwarf::DW_TAG_restrict_type:
164 case dwarf::DW_TAG_member:
165 case dwarf::DW_TAG_inheritance:
168 // FIXME: Even though it doesn't make sense, CompositeTypes are current
169 // modelled as DerivedTypes, this should return true for them as well.
174 /// isCompositeType - Return true if the specified tag is legal for
176 bool DIType::isCompositeType(unsigned TAG) {
178 case dwarf::DW_TAG_array_type:
179 case dwarf::DW_TAG_structure_type:
180 case dwarf::DW_TAG_union_type:
181 case dwarf::DW_TAG_enumeration_type:
182 case dwarf::DW_TAG_vector_type:
183 case dwarf::DW_TAG_subroutine_type:
184 case dwarf::DW_TAG_class_type:
191 /// isVariable - Return true if the specified tag is legal for DIVariable.
192 bool DIVariable::isVariable(unsigned Tag) {
194 case dwarf::DW_TAG_auto_variable:
195 case dwarf::DW_TAG_arg_variable:
196 case dwarf::DW_TAG_return_variable:
203 unsigned DIArray::getNumElements() const {
204 assert (DbgGV && "Invalid DIArray");
205 Constant *C = DbgGV->getInitializer();
206 assert (C && "Invalid DIArray initializer");
207 return C->getNumOperands();
210 /// replaceAllUsesWith - Replace all uses of debug info referenced by
211 /// this descriptor. After this completes, the current debug info value
213 void DIDerivedType::replaceAllUsesWith(DIDescriptor &D) {
217 assert (!D.isNull() && "Can not replace with null");
218 getGV()->replaceAllUsesWith(D.getGV());
219 getGV()->eraseFromParent();
222 /// Verify - Verify that a compile unit is well formed.
223 bool DICompileUnit::Verify() const {
227 if (getFilename(Res).empty())
229 // It is possible that directory and produce string is empty.
233 /// Verify - Verify that a type descriptor is well formed.
234 bool DIType::Verify() const {
237 if (getContext().isNull())
240 DICompileUnit CU = getCompileUnit();
241 if (!CU.isNull() && !CU.Verify())
246 /// Verify - Verify that a composite type descriptor is well formed.
247 bool DICompositeType::Verify() const {
250 if (getContext().isNull())
253 DICompileUnit CU = getCompileUnit();
254 if (!CU.isNull() && !CU.Verify())
259 /// Verify - Verify that a subprogram descriptor is well formed.
260 bool DISubprogram::Verify() const {
264 if (getContext().isNull())
267 DICompileUnit CU = getCompileUnit();
271 DICompositeType Ty = getType();
272 if (!Ty.isNull() && !Ty.Verify())
277 /// Verify - Verify that a global variable descriptor is well formed.
278 bool DIGlobalVariable::Verify() const {
282 if (getContext().isNull())
285 DICompileUnit CU = getCompileUnit();
286 if (!CU.isNull() && !CU.Verify())
289 DIType Ty = getType();
299 /// Verify - Verify that a variable descriptor is well formed.
300 bool DIVariable::Verify() const {
304 if (getContext().isNull())
307 DIType Ty = getType();
314 /// getOriginalTypeSize - If this type is derived from a base type then
315 /// return base type size.
316 uint64_t DIDerivedType::getOriginalTypeSize() const {
317 if (getTag() != dwarf::DW_TAG_member)
318 return getSizeInBits();
319 DIType BT = getTypeDerivedFrom();
320 if (BT.getTag() != dwarf::DW_TAG_base_type)
321 return getSizeInBits();
322 return BT.getSizeInBits();
325 /// describes - Return true if this subprogram provides debugging
326 /// information for the function F.
327 bool DISubprogram::describes(const Function *F) {
328 assert (F && "Invalid function");
330 getLinkageName(Name);
333 if (F->getName() == Name)
338 //===----------------------------------------------------------------------===//
339 // DIDescriptor: dump routines for all descriptors.
340 //===----------------------------------------------------------------------===//
343 /// dump - Print descriptor.
344 void DIDescriptor::dump() const {
345 cerr << "[" << dwarf::TagString(getTag()) << "] ";
346 cerr << std::hex << "[GV:" << DbgGV << "]" << std::dec;
349 /// dump - Print compile unit.
350 void DICompileUnit::dump() const {
352 cerr << " [" << dwarf::LanguageString(getLanguage()) << "] ";
354 std::string Res1, Res2;
355 cerr << " [" << getDirectory(Res1) << "/" << getFilename(Res2) << " ]";
358 /// dump - Print type.
359 void DIType::dump() const {
360 if (isNull()) return;
363 if (!getName(Res).empty())
364 cerr << " [" << Res << "] ";
366 unsigned Tag = getTag();
367 cerr << " [" << dwarf::TagString(Tag) << "] ";
369 // TODO : Print context
370 getCompileUnit().dump();
372 << getLineNumber() << ", "
373 << getSizeInBits() << ", "
374 << getAlignInBits() << ", "
379 cerr << " [private] ";
380 else if (isProtected())
381 cerr << " [protected] ";
386 if (isBasicType(Tag))
387 DIBasicType(DbgGV).dump();
388 else if (isDerivedType(Tag))
389 DIDerivedType(DbgGV).dump();
390 else if (isCompositeType(Tag))
391 DICompositeType(DbgGV).dump();
393 cerr << "Invalid DIType\n";
400 /// dump - Print basic type.
401 void DIBasicType::dump() const {
402 cerr << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
405 /// dump - Print derived type.
406 void DIDerivedType::dump() const {
407 cerr << "\n\t Derived From: "; getTypeDerivedFrom().dump();
410 /// dump - Print composite type.
411 void DICompositeType::dump() const {
412 DIArray A = getTypeArray();
415 cerr << " [" << A.getNumElements() << " elements]";
418 /// dump - Print global.
419 void DIGlobal::dump() const {
421 if (!getName(Res).empty())
422 cerr << " [" << Res << "] ";
424 unsigned Tag = getTag();
425 cerr << " [" << dwarf::TagString(Tag) << "] ";
427 // TODO : Print context
428 getCompileUnit().dump();
429 cerr << " [" << getLineNumber() << "] ";
437 if (isGlobalVariable(Tag))
438 DIGlobalVariable(DbgGV).dump();
443 /// dump - Print subprogram.
444 void DISubprogram::dump() const {
448 /// dump - Print global variable.
449 void DIGlobalVariable::dump() const {
450 cerr << " ["; getGlobal()->dump(); cerr << "] ";
453 /// dump - Print variable.
454 void DIVariable::dump() const {
456 if (!getName(Res).empty())
457 cerr << " [" << Res << "] ";
459 getCompileUnit().dump();
460 cerr << " [" << getLineNumber() << "] ";
465 //===----------------------------------------------------------------------===//
466 // DIFactory: Basic Helpers
467 //===----------------------------------------------------------------------===//
469 DIFactory::DIFactory(Module &m)
470 : M(m), VMContext(M.getContext()), StopPointFn(0), FuncStartFn(0),
471 RegionStartFn(0), RegionEndFn(0),
473 EmptyStructPtr = PointerType::getUnqual(StructType::get(VMContext));
476 /// getCastToEmpty - Return this descriptor as a Constant* with type '{}*'.
477 /// This is only valid when the descriptor is non-null.
478 Constant *DIFactory::getCastToEmpty(DIDescriptor D) {
479 if (D.isNull()) return llvm::Constant::getNullValue(EmptyStructPtr);
480 return ConstantExpr::getBitCast(D.getGV(), EmptyStructPtr);
483 Constant *DIFactory::GetTagConstant(unsigned TAG) {
484 assert((TAG & LLVMDebugVersionMask) == 0 &&
485 "Tag too large for debug encoding!");
486 return ConstantInt::get(Type::Int32Ty, TAG | LLVMDebugVersion);
489 Constant *DIFactory::GetStringConstant(const std::string &String) {
490 // Check string cache for previous edition.
491 Constant *&Slot = StringCache[String];
493 // Return Constant if previously defined.
494 if (Slot) return Slot;
496 const PointerType *DestTy = PointerType::getUnqual(Type::Int8Ty);
498 // If empty string then use a i8* null instead.
500 return Slot = ConstantPointerNull::get(DestTy);
502 // Construct string as an llvm constant.
503 Constant *ConstStr = ConstantArray::get(String);
505 // Otherwise create and return a new string global.
506 GlobalVariable *StrGV = new GlobalVariable(M, ConstStr->getType(), true,
507 GlobalVariable::InternalLinkage,
509 StrGV->setSection("llvm.metadata");
510 return Slot = ConstantExpr::getBitCast(StrGV, DestTy);
513 //===----------------------------------------------------------------------===//
514 // DIFactory: Primary Constructors
515 //===----------------------------------------------------------------------===//
517 /// GetOrCreateArray - Create an descriptor for an array of descriptors.
518 /// This implicitly uniques the arrays created.
519 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
520 SmallVector<Constant*, 16> Elts;
522 for (unsigned i = 0; i != NumTys; ++i)
523 Elts.push_back(getCastToEmpty(Tys[i]));
525 Constant *Init = ConstantArray::get(ArrayType::get(EmptyStructPtr,
527 Elts.data(), Elts.size());
528 // If we already have this array, just return the uniqued version.
529 DIDescriptor &Entry = SimpleConstantCache[Init];
530 if (!Entry.isNull()) return DIArray(Entry.getGV());
532 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
533 GlobalValue::InternalLinkage,
534 Init, "llvm.dbg.array");
535 GV->setSection("llvm.metadata");
536 Entry = DIDescriptor(GV);
540 /// GetOrCreateSubrange - Create a descriptor for a value range. This
541 /// implicitly uniques the values returned.
542 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
544 GetTagConstant(dwarf::DW_TAG_subrange_type),
545 ConstantInt::get(Type::Int64Ty, Lo),
546 ConstantInt::get(Type::Int64Ty, Hi)
549 Constant *Init = ConstantStruct::get(VMContext, Elts,
550 sizeof(Elts)/sizeof(Elts[0]));
552 // If we already have this range, just return the uniqued version.
553 DIDescriptor &Entry = SimpleConstantCache[Init];
554 if (!Entry.isNull()) return DISubrange(Entry.getGV());
556 M.addTypeName("llvm.dbg.subrange.type", Init->getType());
558 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
559 GlobalValue::InternalLinkage,
560 Init, "llvm.dbg.subrange");
561 GV->setSection("llvm.metadata");
562 Entry = DIDescriptor(GV);
563 return DISubrange(GV);
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(EmptyStructPtr),
581 ConstantInt::get(Type::Int32Ty, LangID),
582 GetStringConstant(Filename),
583 GetStringConstant(Directory),
584 GetStringConstant(Producer),
585 ConstantInt::get(Type::Int1Ty, isMain),
586 ConstantInt::get(Type::Int1Ty, isOptimized),
587 GetStringConstant(Flags),
588 ConstantInt::get(Type::Int32Ty, RunTimeVer)
591 Constant *Init = ConstantStruct::get(VMContext, Elts,
592 sizeof(Elts)/sizeof(Elts[0]));
594 M.addTypeName("llvm.dbg.compile_unit.type", Init->getType());
595 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
596 GlobalValue::LinkOnceAnyLinkage,
597 Init, "llvm.dbg.compile_unit");
598 GV->setSection("llvm.metadata");
599 return DICompileUnit(GV);
602 /// CreateEnumerator - Create a single enumerator value.
603 DIEnumerator DIFactory::CreateEnumerator(const std::string &Name, uint64_t Val){
605 GetTagConstant(dwarf::DW_TAG_enumerator),
606 GetStringConstant(Name),
607 ConstantInt::get(Type::Int64Ty, Val)
610 Constant *Init = ConstantStruct::get(VMContext, Elts,
611 sizeof(Elts)/sizeof(Elts[0]));
613 M.addTypeName("llvm.dbg.enumerator.type", Init->getType());
614 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
615 GlobalValue::InternalLinkage,
616 Init, "llvm.dbg.enumerator");
617 GV->setSection("llvm.metadata");
618 return DIEnumerator(GV);
622 /// CreateBasicType - Create a basic type like int, float, etc.
623 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
624 const std::string &Name,
625 DICompileUnit CompileUnit,
628 uint64_t AlignInBits,
629 uint64_t OffsetInBits, unsigned Flags,
632 GetTagConstant(dwarf::DW_TAG_base_type),
633 getCastToEmpty(Context),
634 GetStringConstant(Name),
635 getCastToEmpty(CompileUnit),
636 ConstantInt::get(Type::Int32Ty, LineNumber),
637 ConstantInt::get(Type::Int64Ty, SizeInBits),
638 ConstantInt::get(Type::Int64Ty, AlignInBits),
639 ConstantInt::get(Type::Int64Ty, OffsetInBits),
640 ConstantInt::get(Type::Int32Ty, Flags),
641 ConstantInt::get(Type::Int32Ty, Encoding)
644 Constant *Init = ConstantStruct::get(VMContext, Elts,
645 sizeof(Elts)/sizeof(Elts[0]));
647 M.addTypeName("llvm.dbg.basictype.type", Init->getType());
648 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
649 GlobalValue::InternalLinkage,
650 Init, "llvm.dbg.basictype");
651 GV->setSection("llvm.metadata");
652 return DIBasicType(GV);
655 /// CreateDerivedType - Create a derived type like const qualified type,
656 /// pointer, typedef, etc.
657 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
658 DIDescriptor Context,
659 const std::string &Name,
660 DICompileUnit CompileUnit,
663 uint64_t AlignInBits,
664 uint64_t OffsetInBits,
666 DIType DerivedFrom) {
669 getCastToEmpty(Context),
670 GetStringConstant(Name),
671 getCastToEmpty(CompileUnit),
672 ConstantInt::get(Type::Int32Ty, LineNumber),
673 ConstantInt::get(Type::Int64Ty, SizeInBits),
674 ConstantInt::get(Type::Int64Ty, AlignInBits),
675 ConstantInt::get(Type::Int64Ty, OffsetInBits),
676 ConstantInt::get(Type::Int32Ty, Flags),
677 getCastToEmpty(DerivedFrom)
680 Constant *Init = ConstantStruct::get(VMContext, Elts,
681 sizeof(Elts)/sizeof(Elts[0]));
683 M.addTypeName("llvm.dbg.derivedtype.type", Init->getType());
684 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
685 GlobalValue::InternalLinkage,
686 Init, "llvm.dbg.derivedtype");
687 GV->setSection("llvm.metadata");
688 return DIDerivedType(GV);
691 /// CreateCompositeType - Create a composite type like array, struct, etc.
692 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
693 DIDescriptor Context,
694 const std::string &Name,
695 DICompileUnit CompileUnit,
698 uint64_t AlignInBits,
699 uint64_t OffsetInBits,
703 unsigned RuntimeLang) {
707 getCastToEmpty(Context),
708 GetStringConstant(Name),
709 getCastToEmpty(CompileUnit),
710 ConstantInt::get(Type::Int32Ty, LineNumber),
711 ConstantInt::get(Type::Int64Ty, SizeInBits),
712 ConstantInt::get(Type::Int64Ty, AlignInBits),
713 ConstantInt::get(Type::Int64Ty, OffsetInBits),
714 ConstantInt::get(Type::Int32Ty, Flags),
715 getCastToEmpty(DerivedFrom),
716 getCastToEmpty(Elements),
717 ConstantInt::get(Type::Int32Ty, RuntimeLang)
720 Constant *Init = ConstantStruct::get(VMContext, Elts,
721 sizeof(Elts)/sizeof(Elts[0]));
723 M.addTypeName("llvm.dbg.composite.type", Init->getType());
724 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
725 GlobalValue::InternalLinkage,
726 Init, "llvm.dbg.composite");
727 GV->setSection("llvm.metadata");
728 return DICompositeType(GV);
732 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
733 /// See comments in DISubprogram for descriptions of these fields. This
734 /// method does not unique the generated descriptors.
735 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context,
736 const std::string &Name,
737 const std::string &DisplayName,
738 const std::string &LinkageName,
739 DICompileUnit CompileUnit,
740 unsigned LineNo, DIType Type,
745 GetTagConstant(dwarf::DW_TAG_subprogram),
746 llvm::Constant::getNullValue(EmptyStructPtr),
747 getCastToEmpty(Context),
748 GetStringConstant(Name),
749 GetStringConstant(DisplayName),
750 GetStringConstant(LinkageName),
751 getCastToEmpty(CompileUnit),
752 ConstantInt::get(Type::Int32Ty, LineNo),
753 getCastToEmpty(Type),
754 ConstantInt::get(Type::Int1Ty, isLocalToUnit),
755 ConstantInt::get(Type::Int1Ty, isDefinition)
758 Constant *Init = ConstantStruct::get(VMContext, Elts,
759 sizeof(Elts)/sizeof(Elts[0]));
761 M.addTypeName("llvm.dbg.subprogram.type", Init->getType());
762 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
763 GlobalValue::LinkOnceAnyLinkage,
764 Init, "llvm.dbg.subprogram");
765 GV->setSection("llvm.metadata");
766 return DISubprogram(GV);
769 /// CreateGlobalVariable - Create a new descriptor for the specified global.
771 DIFactory::CreateGlobalVariable(DIDescriptor Context, const std::string &Name,
772 const std::string &DisplayName,
773 const std::string &LinkageName,
774 DICompileUnit CompileUnit,
775 unsigned LineNo, DIType Type,bool isLocalToUnit,
776 bool isDefinition, llvm::GlobalVariable *Val) {
778 GetTagConstant(dwarf::DW_TAG_variable),
779 llvm::Constant::getNullValue(EmptyStructPtr),
780 getCastToEmpty(Context),
781 GetStringConstant(Name),
782 GetStringConstant(DisplayName),
783 GetStringConstant(LinkageName),
784 getCastToEmpty(CompileUnit),
785 ConstantInt::get(Type::Int32Ty, LineNo),
786 getCastToEmpty(Type),
787 ConstantInt::get(Type::Int1Ty, isLocalToUnit),
788 ConstantInt::get(Type::Int1Ty, isDefinition),
789 ConstantExpr::getBitCast(Val, EmptyStructPtr)
792 Constant *Init = ConstantStruct::get(VMContext, Elts,
793 sizeof(Elts)/sizeof(Elts[0]));
795 M.addTypeName("llvm.dbg.global_variable.type", Init->getType());
796 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
797 GlobalValue::LinkOnceAnyLinkage,
798 Init, "llvm.dbg.global_variable");
799 GV->setSection("llvm.metadata");
800 return DIGlobalVariable(GV);
804 /// CreateVariable - Create a new descriptor for the specified variable.
805 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
806 const std::string &Name,
807 DICompileUnit CompileUnit, unsigned LineNo,
811 getCastToEmpty(Context),
812 GetStringConstant(Name),
813 getCastToEmpty(CompileUnit),
814 ConstantInt::get(Type::Int32Ty, LineNo),
818 Constant *Init = ConstantStruct::get(VMContext, Elts,
819 sizeof(Elts)/sizeof(Elts[0]));
821 M.addTypeName("llvm.dbg.variable.type", Init->getType());
822 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
823 GlobalValue::InternalLinkage,
824 Init, "llvm.dbg.variable");
825 GV->setSection("llvm.metadata");
826 return DIVariable(GV);
830 /// CreateBlock - This creates a descriptor for a lexical block with the
831 /// specified parent VMContext.
832 DIBlock DIFactory::CreateBlock(DIDescriptor Context) {
834 GetTagConstant(dwarf::DW_TAG_lexical_block),
835 getCastToEmpty(Context)
838 Constant *Init = ConstantStruct::get(VMContext, Elts,
839 sizeof(Elts)/sizeof(Elts[0]));
841 M.addTypeName("llvm.dbg.block.type", Init->getType());
842 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
843 GlobalValue::InternalLinkage,
844 Init, "llvm.dbg.block");
845 GV->setSection("llvm.metadata");
850 //===----------------------------------------------------------------------===//
851 // DIFactory: Routines for inserting code into a function
852 //===----------------------------------------------------------------------===//
854 /// InsertStopPoint - Create a new llvm.dbg.stoppoint intrinsic invocation,
855 /// inserting it at the end of the specified basic block.
856 void DIFactory::InsertStopPoint(DICompileUnit CU, unsigned LineNo,
857 unsigned ColNo, BasicBlock *BB) {
859 // Lazily construct llvm.dbg.stoppoint function.
861 StopPointFn = llvm::Intrinsic::getDeclaration(&M,
862 llvm::Intrinsic::dbg_stoppoint);
864 // Invoke llvm.dbg.stoppoint
866 ConstantInt::get(llvm::Type::Int32Ty, LineNo),
867 ConstantInt::get(llvm::Type::Int32Ty, ColNo),
870 CallInst::Create(StopPointFn, Args, Args+3, "", BB);
873 /// InsertSubprogramStart - Create a new llvm.dbg.func.start intrinsic to
874 /// mark the start of the specified subprogram.
875 void DIFactory::InsertSubprogramStart(DISubprogram SP, BasicBlock *BB) {
876 // Lazily construct llvm.dbg.func.start.
878 FuncStartFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_func_start);
880 // Call llvm.dbg.func.start which also implicitly sets a stoppoint.
881 CallInst::Create(FuncStartFn, getCastToEmpty(SP), "", BB);
884 /// InsertRegionStart - Insert a new llvm.dbg.region.start intrinsic call to
885 /// mark the start of a region for the specified scoping descriptor.
886 void DIFactory::InsertRegionStart(DIDescriptor D, BasicBlock *BB) {
887 // Lazily construct llvm.dbg.region.start function.
889 RegionStartFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_region_start);
891 // Call llvm.dbg.func.start.
892 CallInst::Create(RegionStartFn, getCastToEmpty(D), "", BB);
895 /// InsertRegionEnd - Insert a new llvm.dbg.region.end intrinsic call to
896 /// mark the end of a region for the specified scoping descriptor.
897 void DIFactory::InsertRegionEnd(DIDescriptor D, BasicBlock *BB) {
898 // Lazily construct llvm.dbg.region.end function.
900 RegionEndFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_region_end);
902 // Call llvm.dbg.region.end.
903 CallInst::Create(RegionEndFn, getCastToEmpty(D), "", BB);
906 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
907 void DIFactory::InsertDeclare(Value *Storage, DIVariable D, BasicBlock *BB) {
908 // Cast the storage to a {}* for the call to llvm.dbg.declare.
909 Storage = new BitCastInst(Storage, EmptyStructPtr, "", BB);
912 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
914 Value *Args[] = { Storage, getCastToEmpty(D) };
915 CallInst::Create(DeclareFn, Args, Args+2, "", BB);
918 //===----------------------------------------------------------------------===//
919 // DebugInfoFinder implementations.
920 //===----------------------------------------------------------------------===//
922 /// processModule - Process entire module and collect debug info.
923 void DebugInfoFinder::processModule(Module &M) {
925 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
926 for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI)
927 for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE;
929 if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(BI))
930 processStopPoint(SPI);
931 else if (DbgFuncStartInst *FSI = dyn_cast<DbgFuncStartInst>(BI))
932 processFuncStart(FSI);
933 else if (DbgRegionStartInst *DRS = dyn_cast<DbgRegionStartInst>(BI))
934 processRegionStart(DRS);
935 else if (DbgRegionEndInst *DRE = dyn_cast<DbgRegionEndInst>(BI))
936 processRegionEnd(DRE);
937 else if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
941 for (Module::global_iterator GVI = M.global_begin(), GVE = M.global_end();
943 GlobalVariable *GV = GVI;
944 if (!GV->hasName() || !GV->isConstant()
945 || strcmp(GV->getName().data(), "llvm.dbg.global_variable")
946 || !GV->hasInitializer())
948 DIGlobalVariable DIG(GV);
949 if (addGlobalVariable(DIG)) {
950 addCompileUnit(DIG.getCompileUnit());
951 processType(DIG.getType());
956 /// processType - Process DIType.
957 void DebugInfoFinder::processType(DIType DT) {
961 addCompileUnit(DT.getCompileUnit());
962 if (DT.isCompositeType(DT.getTag())) {
963 DICompositeType DCT(DT.getGV());
964 processType(DCT.getTypeDerivedFrom());
965 DIArray DA = DCT.getTypeArray();
967 for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
968 DIDescriptor D = DA.getElement(i);
969 DIType TypeE = DIType(D.getGV());
973 processSubprogram(DISubprogram(D.getGV()));
975 } else if (DT.isDerivedType(DT.getTag())) {
976 DIDerivedType DDT(DT.getGV());
978 processType(DDT.getTypeDerivedFrom());
982 /// processSubprogram - Process DISubprogram.
983 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
986 if (!addSubprogram(SP))
988 addCompileUnit(SP.getCompileUnit());
989 processType(SP.getType());
992 /// processStopPoint - Process DbgStopPointInst.
993 void DebugInfoFinder::processStopPoint(DbgStopPointInst *SPI) {
994 GlobalVariable *Context = dyn_cast<GlobalVariable>(SPI->getContext());
995 addCompileUnit(DICompileUnit(Context));
998 /// processFuncStart - Process DbgFuncStartInst.
999 void DebugInfoFinder::processFuncStart(DbgFuncStartInst *FSI) {
1000 GlobalVariable *SP = dyn_cast<GlobalVariable>(FSI->getSubprogram());
1001 processSubprogram(DISubprogram(SP));
1004 /// processRegionStart - Process DbgRegionStart.
1005 void DebugInfoFinder::processRegionStart(DbgRegionStartInst *DRS) {
1006 GlobalVariable *SP = dyn_cast<GlobalVariable>(DRS->getContext());
1007 processSubprogram(DISubprogram(SP));
1010 /// processRegionEnd - Process DbgRegionEnd.
1011 void DebugInfoFinder::processRegionEnd(DbgRegionEndInst *DRE) {
1012 GlobalVariable *SP = dyn_cast<GlobalVariable>(DRE->getContext());
1013 processSubprogram(DISubprogram(SP));
1016 /// processDeclare - Process DbgDeclareInst.
1017 void DebugInfoFinder::processDeclare(DbgDeclareInst *DDI) {
1018 DIVariable DV(cast<GlobalVariable>(DDI->getVariable()));
1022 if (!NodesSeen.insert(DV.getGV()))
1025 addCompileUnit(DV.getCompileUnit());
1026 processType(DV.getType());
1029 /// addType - Add type into Tys.
1030 bool DebugInfoFinder::addType(DIType DT) {
1034 if (!NodesSeen.insert(DT.getGV()))
1037 TYs.push_back(DT.getGV());
1041 /// addCompileUnit - Add compile unit into CUs.
1042 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1046 if (!NodesSeen.insert(CU.getGV()))
1049 CUs.push_back(CU.getGV());
1053 /// addGlobalVariable - Add global variable into GVs.
1054 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1058 if (!NodesSeen.insert(DIG.getGV()))
1061 GVs.push_back(DIG.getGV());
1065 // addSubprogram - Add subprgoram into SPs.
1066 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1070 if (!NodesSeen.insert(SP.getGV()))
1073 SPs.push_back(SP.getGV());
1078 /// findStopPoint - Find the stoppoint coressponding to this instruction, that
1079 /// is the stoppoint that dominates this instruction.
1080 const DbgStopPointInst *findStopPoint(const Instruction *Inst) {
1081 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(Inst))
1084 const BasicBlock *BB = Inst->getParent();
1085 BasicBlock::const_iterator I = Inst, B;
1089 // A BB consisting only of a terminator can't have a stoppoint.
1092 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1096 // This BB didn't have a stoppoint: if there is only one predecessor, look
1097 // for a stoppoint there. We could use getIDom(), but that would require
1099 BB = I->getParent()->getUniquePredecessor();
1101 I = BB->getTerminator();
1107 /// findBBStopPoint - Find the stoppoint corresponding to first real
1108 /// (non-debug intrinsic) instruction in this Basic Block, and return the
1109 /// stoppoint for it.
1110 const DbgStopPointInst *findBBStopPoint(const BasicBlock *BB) {
1111 for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1112 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1115 // Fallback to looking for stoppoint of unique predecessor. Useful if this
1116 // BB contains no stoppoints, but unique predecessor does.
1117 BB = BB->getUniquePredecessor();
1119 return findStopPoint(BB->getTerminator());
1124 Value *findDbgGlobalDeclare(GlobalVariable *V) {
1125 const Module *M = V->getParent();
1127 const Type *Ty = M->getTypeByName("llvm.dbg.global_variable.type");
1130 Ty = PointerType::get(Ty, 0);
1132 Value *Val = V->stripPointerCasts();
1133 for (Value::use_iterator I = Val->use_begin(), E = Val->use_end();
1135 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I)) {
1136 if (CE->getOpcode() == Instruction::BitCast) {
1139 while (VV->hasOneUse())
1140 VV = *VV->use_begin();
1142 if (VV->getType() == Ty)
1148 if (Val->getType() == Ty)
1154 /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
1155 /// It looks through pointer casts too.
1156 const DbgDeclareInst *findDbgDeclare(const Value *V, bool stripCasts) {
1158 V = V->stripPointerCasts();
1160 // Look for the bitcast.
1161 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1163 if (isa<BitCastInst>(I))
1164 return findDbgDeclare(*I, false);
1169 // Find llvm.dbg.declare among uses of the instruction.
1170 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1172 if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
1178 bool getLocationInfo(const Value *V, std::string &DisplayName,
1179 std::string &Type, unsigned &LineNo, std::string &File,
1184 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
1185 Value *DIGV = findDbgGlobalDeclare(GV);
1186 if (!DIGV) return false;
1187 DIGlobalVariable Var(cast<GlobalVariable>(DIGV));
1189 Var.getDisplayName(DisplayName);
1190 LineNo = Var.getLineNumber();
1191 Unit = Var.getCompileUnit();
1192 TypeD = Var.getType();
1194 const DbgDeclareInst *DDI = findDbgDeclare(V);
1195 if (!DDI) return false;
1196 DIVariable Var(cast<GlobalVariable>(DDI->getVariable()));
1198 Var.getName(DisplayName);
1199 LineNo = Var.getLineNumber();
1200 Unit = Var.getCompileUnit();
1201 TypeD = Var.getType();
1204 TypeD.getName(Type);
1205 Unit.getFilename(File);
1206 Unit.getDirectory(Dir);
1210 /// isValidDebugInfoIntrinsic - Return true if SPI is a valid debug
1212 bool isValidDebugInfoIntrinsic(DbgStopPointInst &SPI,
1213 CodeGenOpt::Level OptLev) {
1214 return DIDescriptor::ValidDebugInfo(SPI.getContext(), OptLev);
1217 /// isValidDebugInfoIntrinsic - Return true if FSI is a valid debug
1219 bool isValidDebugInfoIntrinsic(DbgFuncStartInst &FSI,
1220 CodeGenOpt::Level OptLev) {
1221 return DIDescriptor::ValidDebugInfo(FSI.getSubprogram(), OptLev);
1224 /// isValidDebugInfoIntrinsic - Return true if RSI is a valid debug
1226 bool isValidDebugInfoIntrinsic(DbgRegionStartInst &RSI,
1227 CodeGenOpt::Level OptLev) {
1228 return DIDescriptor::ValidDebugInfo(RSI.getContext(), OptLev);
1231 /// isValidDebugInfoIntrinsic - Return true if REI is a valid debug
1233 bool isValidDebugInfoIntrinsic(DbgRegionEndInst &REI,
1234 CodeGenOpt::Level OptLev) {
1235 return DIDescriptor::ValidDebugInfo(REI.getContext(), OptLev);
1239 /// isValidDebugInfoIntrinsic - Return true if DI is a valid debug
1241 bool isValidDebugInfoIntrinsic(DbgDeclareInst &DI,
1242 CodeGenOpt::Level OptLev) {
1243 return DIDescriptor::ValidDebugInfo(DI.getVariable(), OptLev);
1246 /// ExtractDebugLocation - Extract debug location information
1247 /// from llvm.dbg.stoppoint intrinsic.
1248 DebugLoc ExtractDebugLocation(DbgStopPointInst &SPI,
1249 DebugLocTracker &DebugLocInfo) {
1251 Value *Context = SPI.getContext();
1253 // If this location is already tracked then use it.
1254 DebugLocTuple Tuple(cast<GlobalVariable>(Context), SPI.getLine(),
1256 DenseMap<DebugLocTuple, unsigned>::iterator II
1257 = DebugLocInfo.DebugIdMap.find(Tuple);
1258 if (II != DebugLocInfo.DebugIdMap.end())
1259 return DebugLoc::get(II->second);
1261 // Add a new location entry.
1262 unsigned Id = DebugLocInfo.DebugLocations.size();
1263 DebugLocInfo.DebugLocations.push_back(Tuple);
1264 DebugLocInfo.DebugIdMap[Tuple] = Id;
1266 return DebugLoc::get(Id);
1269 /// ExtractDebugLocation - Extract debug location information
1270 /// from llvm.dbg.func_start intrinsic.
1271 DebugLoc ExtractDebugLocation(DbgFuncStartInst &FSI,
1272 DebugLocTracker &DebugLocInfo) {
1274 Value *SP = FSI.getSubprogram();
1276 DISubprogram Subprogram(cast<GlobalVariable>(SP));
1277 unsigned Line = Subprogram.getLineNumber();
1278 DICompileUnit CU(Subprogram.getCompileUnit());
1280 // If this location is already tracked then use it.
1281 DebugLocTuple Tuple(CU.getGV(), Line, /* Column */ 0);
1282 DenseMap<DebugLocTuple, unsigned>::iterator II
1283 = DebugLocInfo.DebugIdMap.find(Tuple);
1284 if (II != DebugLocInfo.DebugIdMap.end())
1285 return DebugLoc::get(II->second);
1287 // Add a new location entry.
1288 unsigned Id = DebugLocInfo.DebugLocations.size();
1289 DebugLocInfo.DebugLocations.push_back(Tuple);
1290 DebugLocInfo.DebugIdMap[Tuple] = Id;
1292 return DebugLoc::get(Id);
1295 /// isInlinedFnStart - Return true if FSI is starting an inlined function.
1296 bool isInlinedFnStart(DbgFuncStartInst &FSI, const Function *CurrentFn) {
1297 DISubprogram Subprogram(cast<GlobalVariable>(FSI.getSubprogram()));
1298 if (Subprogram.describes(CurrentFn))
1304 /// isInlinedFnEnd - Return true if REI is ending an inlined function.
1305 bool isInlinedFnEnd(DbgRegionEndInst &REI, const Function *CurrentFn) {
1306 DISubprogram Subprogram(cast<GlobalVariable>(REI.getContext()));
1307 if (Subprogram.isNull() || Subprogram.describes(CurrentFn))