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/raw_ostream.h"
28 using namespace llvm::dwarf;
30 //===----------------------------------------------------------------------===//
32 //===----------------------------------------------------------------------===//
34 /// ValidDebugInfo - Return true if V represents valid debug info value.
35 bool DIDescriptor::ValidDebugInfo(Value *V, CodeGenOpt::Level OptLevel) {
39 GlobalVariable *GV = dyn_cast<GlobalVariable>(V->stripPointerCasts());
43 if (!GV->hasInternalLinkage () && !GV->hasLinkOnceLinkage())
48 // Check current version. Allow Version6 for now.
49 unsigned Version = DI.getVersion();
50 if (Version != LLVMDebugVersion && Version != LLVMDebugVersion6)
53 unsigned Tag = DI.getTag();
56 assert(DIVariable(GV).Verify() && "Invalid DebugInfo value");
58 case DW_TAG_compile_unit:
59 assert(DICompileUnit(GV).Verify() && "Invalid DebugInfo value");
61 case DW_TAG_subprogram:
62 assert(DISubprogram(GV).Verify() && "Invalid DebugInfo value");
64 case DW_TAG_lexical_block:
65 // FIXME: This interfers with the quality of generated code during
67 if (OptLevel != CodeGenOpt::None)
77 DIDescriptor::DIDescriptor(GlobalVariable *GV, unsigned RequiredTag) {
80 // If this is non-null, check to see if the Tag matches. If not, set to null.
81 if (GV && getTag() != RequiredTag)
86 DIDescriptor::getStringField(unsigned Elt, std::string &Result) const {
92 Constant *C = DbgGV->getInitializer();
93 if (C == 0 || Elt >= C->getNumOperands()) {
98 // Fills in the string if it succeeds
99 if (!GetConstantStringInfo(C->getOperand(Elt), Result))
105 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
106 if (DbgGV == 0) return 0;
107 if (!DbgGV->hasInitializer()) return 0;
109 Constant *C = DbgGV->getInitializer();
110 if (C == 0 || Elt >= C->getNumOperands())
113 if (ConstantInt *CI = dyn_cast<ConstantInt>(C->getOperand(Elt)))
114 return CI->getZExtValue();
118 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
119 if (DbgGV == 0) return DIDescriptor();
121 Constant *C = DbgGV->getInitializer();
122 if (C == 0 || Elt >= C->getNumOperands())
123 return DIDescriptor();
125 C = C->getOperand(Elt);
126 return DIDescriptor(dyn_cast<GlobalVariable>(C->stripPointerCasts()));
129 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
130 if (DbgGV == 0) return 0;
132 Constant *C = DbgGV->getInitializer();
133 if (C == 0 || Elt >= C->getNumOperands())
136 C = C->getOperand(Elt);
137 return dyn_cast<GlobalVariable>(C->stripPointerCasts());
140 //===----------------------------------------------------------------------===//
141 // Simple Descriptor Constructors and other Methods
142 //===----------------------------------------------------------------------===//
144 // Needed by DIVariable::getType().
145 DIType::DIType(GlobalVariable *GV) : DIDescriptor(GV) {
147 unsigned tag = getTag();
148 if (tag != dwarf::DW_TAG_base_type && !DIDerivedType::isDerivedType(tag) &&
149 !DICompositeType::isCompositeType(tag))
153 /// isDerivedType - Return true if the specified tag is legal for
155 bool DIType::isDerivedType(unsigned Tag) {
157 case dwarf::DW_TAG_typedef:
158 case dwarf::DW_TAG_pointer_type:
159 case dwarf::DW_TAG_reference_type:
160 case dwarf::DW_TAG_const_type:
161 case dwarf::DW_TAG_volatile_type:
162 case dwarf::DW_TAG_restrict_type:
163 case dwarf::DW_TAG_member:
164 case dwarf::DW_TAG_inheritance:
167 // FIXME: Even though it doesn't make sense, CompositeTypes are current
168 // modelled as DerivedTypes, this should return true for them as well.
173 /// isCompositeType - Return true if the specified tag is legal for
175 bool DIType::isCompositeType(unsigned TAG) {
177 case dwarf::DW_TAG_array_type:
178 case dwarf::DW_TAG_structure_type:
179 case dwarf::DW_TAG_union_type:
180 case dwarf::DW_TAG_enumeration_type:
181 case dwarf::DW_TAG_vector_type:
182 case dwarf::DW_TAG_subroutine_type:
183 case dwarf::DW_TAG_class_type:
190 /// isVariable - Return true if the specified tag is legal for DIVariable.
191 bool DIVariable::isVariable(unsigned Tag) {
193 case dwarf::DW_TAG_auto_variable:
194 case dwarf::DW_TAG_arg_variable:
195 case dwarf::DW_TAG_return_variable:
202 unsigned DIArray::getNumElements() const {
203 assert (DbgGV && "Invalid DIArray");
204 Constant *C = DbgGV->getInitializer();
205 assert (C && "Invalid DIArray initializer");
206 return C->getNumOperands();
209 /// replaceAllUsesWith - Replace all uses of debug info referenced by
210 /// this descriptor. After this completes, the current debug info value
212 void DIDerivedType::replaceAllUsesWith(DIDescriptor &D) {
216 assert (!D.isNull() && "Can not replace with null");
217 getGV()->replaceAllUsesWith(D.getGV());
218 getGV()->eraseFromParent();
221 /// Verify - Verify that a compile unit is well formed.
222 bool DICompileUnit::Verify() const {
226 if (getFilename(Res).empty())
228 // It is possible that directory and produce string is empty.
232 /// Verify - Verify that a type descriptor is well formed.
233 bool DIType::Verify() const {
236 if (getContext().isNull())
239 DICompileUnit CU = getCompileUnit();
240 if (!CU.isNull() && !CU.Verify())
245 /// Verify - Verify that a composite type descriptor is well formed.
246 bool DICompositeType::Verify() const {
249 if (getContext().isNull())
252 DICompileUnit CU = getCompileUnit();
253 if (!CU.isNull() && !CU.Verify())
258 /// Verify - Verify that a subprogram descriptor is well formed.
259 bool DISubprogram::Verify() const {
263 if (getContext().isNull())
266 DICompileUnit CU = getCompileUnit();
270 DICompositeType Ty = getType();
271 if (!Ty.isNull() && !Ty.Verify())
276 /// Verify - Verify that a global variable descriptor is well formed.
277 bool DIGlobalVariable::Verify() const {
281 if (getContext().isNull())
284 DICompileUnit CU = getCompileUnit();
285 if (!CU.isNull() && !CU.Verify())
288 DIType Ty = getType();
298 /// Verify - Verify that a variable descriptor is well formed.
299 bool DIVariable::Verify() const {
303 if (getContext().isNull())
306 DIType Ty = getType();
313 /// getOriginalTypeSize - If this type is derived from a base type then
314 /// return base type size.
315 uint64_t DIDerivedType::getOriginalTypeSize() const {
316 if (getTag() != dwarf::DW_TAG_member)
317 return getSizeInBits();
318 DIType BT = getTypeDerivedFrom();
319 if (BT.getTag() != dwarf::DW_TAG_base_type)
320 return getSizeInBits();
321 return BT.getSizeInBits();
324 /// describes - Return true if this subprogram provides debugging
325 /// information for the function F.
326 bool DISubprogram::describes(const Function *F) {
327 assert (F && "Invalid function");
329 getLinkageName(Name);
332 if (F->getName() == Name)
337 //===----------------------------------------------------------------------===//
338 // DIDescriptor: dump routines for all descriptors.
339 //===----------------------------------------------------------------------===//
342 /// dump - Print descriptor.
343 void DIDescriptor::dump() const {
344 errs() << "[" << dwarf::TagString(getTag()) << "] [GV:";
345 errs().write_hex((intptr_t)DbgGV) << ']';
348 /// dump - Print compile unit.
349 void DICompileUnit::dump() const {
351 errs() << " [" << dwarf::LanguageString(getLanguage()) << "] ";
353 std::string Res1, Res2;
354 errs() << " [" << getDirectory(Res1) << "/" << getFilename(Res2) << " ]";
357 /// dump - Print type.
358 void DIType::dump() const {
359 if (isNull()) return;
362 if (!getName(Res).empty())
363 errs() << " [" << Res << "] ";
365 unsigned Tag = getTag();
366 errs() << " [" << dwarf::TagString(Tag) << "] ";
368 // TODO : Print context
369 getCompileUnit().dump();
371 << getLineNumber() << ", "
372 << getSizeInBits() << ", "
373 << getAlignInBits() << ", "
378 errs() << " [private] ";
379 else if (isProtected())
380 errs() << " [protected] ";
385 if (isBasicType(Tag))
386 DIBasicType(DbgGV).dump();
387 else if (isDerivedType(Tag))
388 DIDerivedType(DbgGV).dump();
389 else if (isCompositeType(Tag))
390 DICompositeType(DbgGV).dump();
392 errs() << "Invalid DIType\n";
399 /// dump - Print basic type.
400 void DIBasicType::dump() const {
401 errs() << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
404 /// dump - Print derived type.
405 void DIDerivedType::dump() const {
406 errs() << "\n\t Derived From: "; getTypeDerivedFrom().dump();
409 /// dump - Print composite type.
410 void DICompositeType::dump() const {
411 DIArray A = getTypeArray();
414 errs() << " [" << A.getNumElements() << " elements]";
417 /// dump - Print global.
418 void DIGlobal::dump() const {
420 if (!getName(Res).empty())
421 errs() << " [" << Res << "] ";
423 unsigned Tag = getTag();
424 errs() << " [" << dwarf::TagString(Tag) << "] ";
426 // TODO : Print context
427 getCompileUnit().dump();
428 errs() << " [" << getLineNumber() << "] ";
431 errs() << " [local] ";
436 if (isGlobalVariable(Tag))
437 DIGlobalVariable(DbgGV).dump();
442 /// dump - Print subprogram.
443 void DISubprogram::dump() const {
447 /// dump - Print global variable.
448 void DIGlobalVariable::dump() const {
454 /// dump - Print variable.
455 void DIVariable::dump() const {
457 if (!getName(Res).empty())
458 errs() << " [" << Res << "] ";
460 getCompileUnit().dump();
461 errs() << " [" << getLineNumber() << "] ";
466 //===----------------------------------------------------------------------===//
467 // DIFactory: Basic Helpers
468 //===----------------------------------------------------------------------===//
470 DIFactory::DIFactory(Module &m)
471 : M(m), VMContext(M.getContext()), StopPointFn(0), FuncStartFn(0),
472 RegionStartFn(0), RegionEndFn(0),
474 EmptyStructPtr = PointerType::getUnqual(StructType::get(VMContext));
477 /// getCastToEmpty - Return this descriptor as a Constant* with type '{}*'.
478 /// This is only valid when the descriptor is non-null.
479 Constant *DIFactory::getCastToEmpty(DIDescriptor D) {
480 if (D.isNull()) return llvm::Constant::getNullValue(EmptyStructPtr);
481 return ConstantExpr::getBitCast(D.getGV(), EmptyStructPtr);
484 Constant *DIFactory::GetTagConstant(unsigned TAG) {
485 assert((TAG & LLVMDebugVersionMask) == 0 &&
486 "Tag too large for debug encoding!");
487 return ConstantInt::get(Type::getInt32Ty(VMContext), TAG | LLVMDebugVersion);
490 Constant *DIFactory::GetStringConstant(const std::string &String) {
491 // Check string cache for previous edition.
492 Constant *&Slot = StringCache[String];
494 // Return Constant if previously defined.
495 if (Slot) return Slot;
497 const PointerType *DestTy = PointerType::getUnqual(Type::getInt8Ty(VMContext));
499 // If empty string then use a i8* null instead.
501 return Slot = ConstantPointerNull::get(DestTy);
503 // Construct string as an llvm constant.
504 Constant *ConstStr = ConstantArray::get(VMContext, String);
506 // Otherwise create and return a new string global.
507 GlobalVariable *StrGV = new GlobalVariable(M, ConstStr->getType(), true,
508 GlobalVariable::InternalLinkage,
510 StrGV->setSection("llvm.metadata");
511 return Slot = ConstantExpr::getBitCast(StrGV, DestTy);
514 //===----------------------------------------------------------------------===//
515 // DIFactory: Primary Constructors
516 //===----------------------------------------------------------------------===//
518 /// GetOrCreateArray - Create an descriptor for an array of descriptors.
519 /// This implicitly uniques the arrays created.
520 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
521 SmallVector<Constant*, 16> Elts;
523 for (unsigned i = 0; i != NumTys; ++i)
524 Elts.push_back(getCastToEmpty(Tys[i]));
526 Constant *Init = ConstantArray::get(ArrayType::get(EmptyStructPtr,
528 Elts.data(), Elts.size());
529 // If we already have this array, just return the uniqued version.
530 DIDescriptor &Entry = SimpleConstantCache[Init];
531 if (!Entry.isNull()) return DIArray(Entry.getGV());
533 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
534 GlobalValue::InternalLinkage,
535 Init, "llvm.dbg.array");
536 GV->setSection("llvm.metadata");
537 Entry = DIDescriptor(GV);
541 /// GetOrCreateSubrange - Create a descriptor for a value range. This
542 /// implicitly uniques the values returned.
543 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
545 GetTagConstant(dwarf::DW_TAG_subrange_type),
546 ConstantInt::get(Type::getInt64Ty(VMContext), Lo),
547 ConstantInt::get(Type::getInt64Ty(VMContext), Hi)
550 Constant *Init = ConstantStruct::get(VMContext, Elts,
551 sizeof(Elts)/sizeof(Elts[0]));
553 // If we already have this range, just return the uniqued version.
554 DIDescriptor &Entry = SimpleConstantCache[Init];
555 if (!Entry.isNull()) return DISubrange(Entry.getGV());
557 M.addTypeName("llvm.dbg.subrange.type", Init->getType());
559 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
560 GlobalValue::InternalLinkage,
561 Init, "llvm.dbg.subrange");
562 GV->setSection("llvm.metadata");
563 Entry = DIDescriptor(GV);
564 return DISubrange(GV);
569 /// CreateCompileUnit - Create a new descriptor for the specified compile
570 /// unit. Note that this does not unique compile units within the module.
571 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
572 const std::string &Filename,
573 const std::string &Directory,
574 const std::string &Producer,
578 unsigned RunTimeVer) {
580 GetTagConstant(dwarf::DW_TAG_compile_unit),
581 llvm::Constant::getNullValue(EmptyStructPtr),
582 ConstantInt::get(Type::getInt32Ty(VMContext), LangID),
583 GetStringConstant(Filename),
584 GetStringConstant(Directory),
585 GetStringConstant(Producer),
586 ConstantInt::get(Type::getInt1Ty(VMContext), isMain),
587 ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
588 GetStringConstant(Flags),
589 ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeVer)
592 Constant *Init = ConstantStruct::get(VMContext, Elts,
593 sizeof(Elts)/sizeof(Elts[0]));
595 M.addTypeName("llvm.dbg.compile_unit.type", Init->getType());
596 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
597 GlobalValue::InternalLinkage,
598 Init, "llvm.dbg.compile_unit");
599 GV->setSection("llvm.metadata");
600 return DICompileUnit(GV);
603 /// CreateEnumerator - Create a single enumerator value.
604 DIEnumerator DIFactory::CreateEnumerator(const std::string &Name, uint64_t Val){
606 GetTagConstant(dwarf::DW_TAG_enumerator),
607 GetStringConstant(Name),
608 ConstantInt::get(Type::getInt64Ty(VMContext), Val)
611 Constant *Init = ConstantStruct::get(VMContext, Elts,
612 sizeof(Elts)/sizeof(Elts[0]));
614 M.addTypeName("llvm.dbg.enumerator.type", Init->getType());
615 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
616 GlobalValue::InternalLinkage,
617 Init, "llvm.dbg.enumerator");
618 GV->setSection("llvm.metadata");
619 return DIEnumerator(GV);
623 /// CreateBasicType - Create a basic type like int, float, etc.
624 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
625 const std::string &Name,
626 DICompileUnit CompileUnit,
629 uint64_t AlignInBits,
630 uint64_t OffsetInBits, unsigned Flags,
633 GetTagConstant(dwarf::DW_TAG_base_type),
634 getCastToEmpty(Context),
635 GetStringConstant(Name),
636 getCastToEmpty(CompileUnit),
637 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
638 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
639 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
640 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
641 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
642 ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
645 Constant *Init = ConstantStruct::get(VMContext, Elts,
646 sizeof(Elts)/sizeof(Elts[0]));
648 M.addTypeName("llvm.dbg.basictype.type", Init->getType());
649 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
650 GlobalValue::InternalLinkage,
651 Init, "llvm.dbg.basictype");
652 GV->setSection("llvm.metadata");
653 return DIBasicType(GV);
656 /// CreateDerivedType - Create a derived type like const qualified type,
657 /// pointer, typedef, etc.
658 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
659 DIDescriptor Context,
660 const std::string &Name,
661 DICompileUnit CompileUnit,
664 uint64_t AlignInBits,
665 uint64_t OffsetInBits,
667 DIType DerivedFrom) {
670 getCastToEmpty(Context),
671 GetStringConstant(Name),
672 getCastToEmpty(CompileUnit),
673 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
674 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
675 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
676 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
677 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
678 getCastToEmpty(DerivedFrom)
681 Constant *Init = ConstantStruct::get(VMContext, Elts,
682 sizeof(Elts)/sizeof(Elts[0]));
684 M.addTypeName("llvm.dbg.derivedtype.type", Init->getType());
685 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
686 GlobalValue::InternalLinkage,
687 Init, "llvm.dbg.derivedtype");
688 GV->setSection("llvm.metadata");
689 return DIDerivedType(GV);
692 /// CreateCompositeType - Create a composite type like array, struct, etc.
693 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
694 DIDescriptor Context,
695 const std::string &Name,
696 DICompileUnit CompileUnit,
699 uint64_t AlignInBits,
700 uint64_t OffsetInBits,
704 unsigned RuntimeLang) {
708 getCastToEmpty(Context),
709 GetStringConstant(Name),
710 getCastToEmpty(CompileUnit),
711 ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
712 ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
713 ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
714 ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
715 ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
716 getCastToEmpty(DerivedFrom),
717 getCastToEmpty(Elements),
718 ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang)
721 Constant *Init = ConstantStruct::get(VMContext, Elts,
722 sizeof(Elts)/sizeof(Elts[0]));
724 M.addTypeName("llvm.dbg.composite.type", Init->getType());
725 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
726 GlobalValue::InternalLinkage,
727 Init, "llvm.dbg.composite");
728 GV->setSection("llvm.metadata");
729 return DICompositeType(GV);
733 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
734 /// See comments in DISubprogram for descriptions of these fields. This
735 /// method does not unique the generated descriptors.
736 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context,
737 const std::string &Name,
738 const std::string &DisplayName,
739 const std::string &LinkageName,
740 DICompileUnit CompileUnit,
741 unsigned LineNo, DIType Type,
746 GetTagConstant(dwarf::DW_TAG_subprogram),
747 llvm::Constant::getNullValue(EmptyStructPtr),
748 getCastToEmpty(Context),
749 GetStringConstant(Name),
750 GetStringConstant(DisplayName),
751 GetStringConstant(LinkageName),
752 getCastToEmpty(CompileUnit),
753 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
754 getCastToEmpty(Type),
755 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
756 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition)
759 Constant *Init = ConstantStruct::get(VMContext, Elts,
760 sizeof(Elts)/sizeof(Elts[0]));
762 M.addTypeName("llvm.dbg.subprogram.type", Init->getType());
763 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
764 GlobalValue::InternalLinkage,
765 Init, "llvm.dbg.subprogram");
766 GV->setSection("llvm.metadata");
767 return DISubprogram(GV);
770 /// CreateGlobalVariable - Create a new descriptor for the specified global.
772 DIFactory::CreateGlobalVariable(DIDescriptor Context, const std::string &Name,
773 const std::string &DisplayName,
774 const std::string &LinkageName,
775 DICompileUnit CompileUnit,
776 unsigned LineNo, DIType Type,bool isLocalToUnit,
777 bool isDefinition, llvm::GlobalVariable *Val) {
779 GetTagConstant(dwarf::DW_TAG_variable),
780 llvm::Constant::getNullValue(EmptyStructPtr),
781 getCastToEmpty(Context),
782 GetStringConstant(Name),
783 GetStringConstant(DisplayName),
784 GetStringConstant(LinkageName),
785 getCastToEmpty(CompileUnit),
786 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
787 getCastToEmpty(Type),
788 ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
789 ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
790 ConstantExpr::getBitCast(Val, EmptyStructPtr)
793 Constant *Init = ConstantStruct::get(VMContext, Elts,
794 sizeof(Elts)/sizeof(Elts[0]));
796 M.addTypeName("llvm.dbg.global_variable.type", Init->getType());
797 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
798 GlobalValue::LinkOnceAnyLinkage,
799 Init, "llvm.dbg.global_variable");
800 GV->setSection("llvm.metadata");
801 return DIGlobalVariable(GV);
805 /// CreateVariable - Create a new descriptor for the specified variable.
806 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
807 const std::string &Name,
808 DICompileUnit CompileUnit, unsigned LineNo,
812 getCastToEmpty(Context),
813 GetStringConstant(Name),
814 getCastToEmpty(CompileUnit),
815 ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
819 Constant *Init = ConstantStruct::get(VMContext, Elts,
820 sizeof(Elts)/sizeof(Elts[0]));
822 M.addTypeName("llvm.dbg.variable.type", Init->getType());
823 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
824 GlobalValue::InternalLinkage,
825 Init, "llvm.dbg.variable");
826 GV->setSection("llvm.metadata");
827 return DIVariable(GV);
831 /// CreateBlock - This creates a descriptor for a lexical block with the
832 /// specified parent VMContext.
833 DIBlock DIFactory::CreateBlock(DIDescriptor Context) {
835 GetTagConstant(dwarf::DW_TAG_lexical_block),
836 getCastToEmpty(Context)
839 Constant *Init = ConstantStruct::get(VMContext, Elts,
840 sizeof(Elts)/sizeof(Elts[0]));
842 M.addTypeName("llvm.dbg.block.type", Init->getType());
843 GlobalVariable *GV = new GlobalVariable(M, Init->getType(), true,
844 GlobalValue::InternalLinkage,
845 Init, "llvm.dbg.block");
846 GV->setSection("llvm.metadata");
851 //===----------------------------------------------------------------------===//
852 // DIFactory: Routines for inserting code into a function
853 //===----------------------------------------------------------------------===//
855 /// InsertStopPoint - Create a new llvm.dbg.stoppoint intrinsic invocation,
856 /// inserting it at the end of the specified basic block.
857 void DIFactory::InsertStopPoint(DICompileUnit CU, unsigned LineNo,
858 unsigned ColNo, BasicBlock *BB) {
860 // Lazily construct llvm.dbg.stoppoint function.
862 StopPointFn = llvm::Intrinsic::getDeclaration(&M,
863 llvm::Intrinsic::dbg_stoppoint);
865 // Invoke llvm.dbg.stoppoint
867 ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo),
868 ConstantInt::get(llvm::Type::getInt32Ty(VMContext), ColNo),
871 CallInst::Create(StopPointFn, Args, Args+3, "", BB);
874 /// InsertSubprogramStart - Create a new llvm.dbg.func.start intrinsic to
875 /// mark the start of the specified subprogram.
876 void DIFactory::InsertSubprogramStart(DISubprogram SP, BasicBlock *BB) {
877 // Lazily construct llvm.dbg.func.start.
879 FuncStartFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_func_start);
881 // Call llvm.dbg.func.start which also implicitly sets a stoppoint.
882 CallInst::Create(FuncStartFn, getCastToEmpty(SP), "", BB);
885 /// InsertRegionStart - Insert a new llvm.dbg.region.start intrinsic call to
886 /// mark the start of a region for the specified scoping descriptor.
887 void DIFactory::InsertRegionStart(DIDescriptor D, BasicBlock *BB) {
888 // Lazily construct llvm.dbg.region.start function.
890 RegionStartFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_region_start);
892 // Call llvm.dbg.func.start.
893 CallInst::Create(RegionStartFn, getCastToEmpty(D), "", BB);
896 /// InsertRegionEnd - Insert a new llvm.dbg.region.end intrinsic call to
897 /// mark the end of a region for the specified scoping descriptor.
898 void DIFactory::InsertRegionEnd(DIDescriptor D, BasicBlock *BB) {
899 // Lazily construct llvm.dbg.region.end function.
901 RegionEndFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_region_end);
903 // Call llvm.dbg.region.end.
904 CallInst::Create(RegionEndFn, getCastToEmpty(D), "", BB);
907 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
908 void DIFactory::InsertDeclare(Value *Storage, DIVariable D, BasicBlock *BB) {
909 // Cast the storage to a {}* for the call to llvm.dbg.declare.
910 Storage = new BitCastInst(Storage, EmptyStructPtr, "", BB);
913 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
915 Value *Args[] = { Storage, getCastToEmpty(D) };
916 CallInst::Create(DeclareFn, Args, Args+2, "", BB);
919 //===----------------------------------------------------------------------===//
920 // DebugInfoFinder implementations.
921 //===----------------------------------------------------------------------===//
923 /// processModule - Process entire module and collect debug info.
924 void DebugInfoFinder::processModule(Module &M) {
926 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
927 for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI)
928 for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE;
930 if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(BI))
931 processStopPoint(SPI);
932 else if (DbgFuncStartInst *FSI = dyn_cast<DbgFuncStartInst>(BI))
933 processFuncStart(FSI);
934 else if (DbgRegionStartInst *DRS = dyn_cast<DbgRegionStartInst>(BI))
935 processRegionStart(DRS);
936 else if (DbgRegionEndInst *DRE = dyn_cast<DbgRegionEndInst>(BI))
937 processRegionEnd(DRE);
938 else if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
942 for (Module::global_iterator GVI = M.global_begin(), GVE = M.global_end();
944 GlobalVariable *GV = GVI;
945 if (!GV->hasName() || !GV->isConstant()
946 || strncmp(GV->getName().data(), "llvm.dbg.global_variable", 24)
947 || !GV->hasInitializer())
949 DIGlobalVariable DIG(GV);
950 if (addGlobalVariable(DIG)) {
951 addCompileUnit(DIG.getCompileUnit());
952 processType(DIG.getType());
957 /// processType - Process DIType.
958 void DebugInfoFinder::processType(DIType DT) {
962 addCompileUnit(DT.getCompileUnit());
963 if (DT.isCompositeType(DT.getTag())) {
964 DICompositeType DCT(DT.getGV());
965 processType(DCT.getTypeDerivedFrom());
966 DIArray DA = DCT.getTypeArray();
968 for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
969 DIDescriptor D = DA.getElement(i);
970 DIType TypeE = DIType(D.getGV());
974 processSubprogram(DISubprogram(D.getGV()));
976 } else if (DT.isDerivedType(DT.getTag())) {
977 DIDerivedType DDT(DT.getGV());
979 processType(DDT.getTypeDerivedFrom());
983 /// processSubprogram - Process DISubprogram.
984 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
987 if (!addSubprogram(SP))
989 addCompileUnit(SP.getCompileUnit());
990 processType(SP.getType());
993 /// processStopPoint - Process DbgStopPointInst.
994 void DebugInfoFinder::processStopPoint(DbgStopPointInst *SPI) {
995 GlobalVariable *Context = dyn_cast<GlobalVariable>(SPI->getContext());
996 addCompileUnit(DICompileUnit(Context));
999 /// processFuncStart - Process DbgFuncStartInst.
1000 void DebugInfoFinder::processFuncStart(DbgFuncStartInst *FSI) {
1001 GlobalVariable *SP = dyn_cast<GlobalVariable>(FSI->getSubprogram());
1002 processSubprogram(DISubprogram(SP));
1005 /// processRegionStart - Process DbgRegionStart.
1006 void DebugInfoFinder::processRegionStart(DbgRegionStartInst *DRS) {
1007 GlobalVariable *SP = dyn_cast<GlobalVariable>(DRS->getContext());
1008 processSubprogram(DISubprogram(SP));
1011 /// processRegionEnd - Process DbgRegionEnd.
1012 void DebugInfoFinder::processRegionEnd(DbgRegionEndInst *DRE) {
1013 GlobalVariable *SP = dyn_cast<GlobalVariable>(DRE->getContext());
1014 processSubprogram(DISubprogram(SP));
1017 /// processDeclare - Process DbgDeclareInst.
1018 void DebugInfoFinder::processDeclare(DbgDeclareInst *DDI) {
1019 DIVariable DV(cast<GlobalVariable>(DDI->getVariable()));
1023 if (!NodesSeen.insert(DV.getGV()))
1026 addCompileUnit(DV.getCompileUnit());
1027 processType(DV.getType());
1030 /// addType - Add type into Tys.
1031 bool DebugInfoFinder::addType(DIType DT) {
1035 if (!NodesSeen.insert(DT.getGV()))
1038 TYs.push_back(DT.getGV());
1042 /// addCompileUnit - Add compile unit into CUs.
1043 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1047 if (!NodesSeen.insert(CU.getGV()))
1050 CUs.push_back(CU.getGV());
1054 /// addGlobalVariable - Add global variable into GVs.
1055 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1059 if (!NodesSeen.insert(DIG.getGV()))
1062 GVs.push_back(DIG.getGV());
1066 // addSubprogram - Add subprgoram into SPs.
1067 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1071 if (!NodesSeen.insert(SP.getGV()))
1074 SPs.push_back(SP.getGV());
1079 /// findStopPoint - Find the stoppoint coressponding to this instruction, that
1080 /// is the stoppoint that dominates this instruction.
1081 const DbgStopPointInst *findStopPoint(const Instruction *Inst) {
1082 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(Inst))
1085 const BasicBlock *BB = Inst->getParent();
1086 BasicBlock::const_iterator I = Inst, B;
1090 // A BB consisting only of a terminator can't have a stoppoint.
1093 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1097 // This BB didn't have a stoppoint: if there is only one predecessor, look
1098 // for a stoppoint there. We could use getIDom(), but that would require
1100 BB = I->getParent()->getUniquePredecessor();
1102 I = BB->getTerminator();
1108 /// findBBStopPoint - Find the stoppoint corresponding to first real
1109 /// (non-debug intrinsic) instruction in this Basic Block, and return the
1110 /// stoppoint for it.
1111 const DbgStopPointInst *findBBStopPoint(const BasicBlock *BB) {
1112 for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1113 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1116 // Fallback to looking for stoppoint of unique predecessor. Useful if this
1117 // BB contains no stoppoints, but unique predecessor does.
1118 BB = BB->getUniquePredecessor();
1120 return findStopPoint(BB->getTerminator());
1125 Value *findDbgGlobalDeclare(GlobalVariable *V) {
1126 const Module *M = V->getParent();
1128 const Type *Ty = M->getTypeByName("llvm.dbg.global_variable.type");
1131 Ty = PointerType::get(Ty, 0);
1133 Value *Val = V->stripPointerCasts();
1134 for (Value::use_iterator I = Val->use_begin(), E = Val->use_end();
1136 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I)) {
1137 if (CE->getOpcode() == Instruction::BitCast) {
1140 while (VV->hasOneUse())
1141 VV = *VV->use_begin();
1143 if (VV->getType() == Ty)
1149 if (Val->getType() == Ty)
1155 /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
1156 /// It looks through pointer casts too.
1157 const DbgDeclareInst *findDbgDeclare(const Value *V, bool stripCasts) {
1159 V = V->stripPointerCasts();
1161 // Look for the bitcast.
1162 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1164 if (isa<BitCastInst>(I))
1165 return findDbgDeclare(*I, false);
1170 // Find llvm.dbg.declare among uses of the instruction.
1171 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1173 if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
1179 bool getLocationInfo(const Value *V, std::string &DisplayName,
1180 std::string &Type, unsigned &LineNo, std::string &File,
1185 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
1186 Value *DIGV = findDbgGlobalDeclare(GV);
1187 if (!DIGV) return false;
1188 DIGlobalVariable Var(cast<GlobalVariable>(DIGV));
1190 Var.getDisplayName(DisplayName);
1191 LineNo = Var.getLineNumber();
1192 Unit = Var.getCompileUnit();
1193 TypeD = Var.getType();
1195 const DbgDeclareInst *DDI = findDbgDeclare(V);
1196 if (!DDI) return false;
1197 DIVariable Var(cast<GlobalVariable>(DDI->getVariable()));
1199 Var.getName(DisplayName);
1200 LineNo = Var.getLineNumber();
1201 Unit = Var.getCompileUnit();
1202 TypeD = Var.getType();
1205 TypeD.getName(Type);
1206 Unit.getFilename(File);
1207 Unit.getDirectory(Dir);
1211 /// isValidDebugInfoIntrinsic - Return true if SPI is a valid debug
1213 bool isValidDebugInfoIntrinsic(DbgStopPointInst &SPI,
1214 CodeGenOpt::Level OptLev) {
1215 return DIDescriptor::ValidDebugInfo(SPI.getContext(), OptLev);
1218 /// isValidDebugInfoIntrinsic - Return true if FSI is a valid debug
1220 bool isValidDebugInfoIntrinsic(DbgFuncStartInst &FSI,
1221 CodeGenOpt::Level OptLev) {
1222 return DIDescriptor::ValidDebugInfo(FSI.getSubprogram(), OptLev);
1225 /// isValidDebugInfoIntrinsic - Return true if RSI is a valid debug
1227 bool isValidDebugInfoIntrinsic(DbgRegionStartInst &RSI,
1228 CodeGenOpt::Level OptLev) {
1229 return DIDescriptor::ValidDebugInfo(RSI.getContext(), OptLev);
1232 /// isValidDebugInfoIntrinsic - Return true if REI is a valid debug
1234 bool isValidDebugInfoIntrinsic(DbgRegionEndInst &REI,
1235 CodeGenOpt::Level OptLev) {
1236 return DIDescriptor::ValidDebugInfo(REI.getContext(), OptLev);
1240 /// isValidDebugInfoIntrinsic - Return true if DI is a valid debug
1242 bool isValidDebugInfoIntrinsic(DbgDeclareInst &DI,
1243 CodeGenOpt::Level OptLev) {
1244 return DIDescriptor::ValidDebugInfo(DI.getVariable(), OptLev);
1247 /// ExtractDebugLocation - Extract debug location information
1248 /// from llvm.dbg.stoppoint intrinsic.
1249 DebugLoc ExtractDebugLocation(DbgStopPointInst &SPI,
1250 DebugLocTracker &DebugLocInfo) {
1252 Value *Context = SPI.getContext();
1254 // If this location is already tracked then use it.
1255 DebugLocTuple Tuple(cast<GlobalVariable>(Context), SPI.getLine(),
1257 DenseMap<DebugLocTuple, unsigned>::iterator II
1258 = DebugLocInfo.DebugIdMap.find(Tuple);
1259 if (II != DebugLocInfo.DebugIdMap.end())
1260 return DebugLoc::get(II->second);
1262 // Add a new location entry.
1263 unsigned Id = DebugLocInfo.DebugLocations.size();
1264 DebugLocInfo.DebugLocations.push_back(Tuple);
1265 DebugLocInfo.DebugIdMap[Tuple] = Id;
1267 return DebugLoc::get(Id);
1270 /// ExtractDebugLocation - Extract debug location information
1271 /// from llvm.dbg.func_start intrinsic.
1272 DebugLoc ExtractDebugLocation(DbgFuncStartInst &FSI,
1273 DebugLocTracker &DebugLocInfo) {
1275 Value *SP = FSI.getSubprogram();
1277 DISubprogram Subprogram(cast<GlobalVariable>(SP));
1278 unsigned Line = Subprogram.getLineNumber();
1279 DICompileUnit CU(Subprogram.getCompileUnit());
1281 // If this location is already tracked then use it.
1282 DebugLocTuple Tuple(CU.getGV(), Line, /* Column */ 0);
1283 DenseMap<DebugLocTuple, unsigned>::iterator II
1284 = DebugLocInfo.DebugIdMap.find(Tuple);
1285 if (II != DebugLocInfo.DebugIdMap.end())
1286 return DebugLoc::get(II->second);
1288 // Add a new location entry.
1289 unsigned Id = DebugLocInfo.DebugLocations.size();
1290 DebugLocInfo.DebugLocations.push_back(Tuple);
1291 DebugLocInfo.DebugIdMap[Tuple] = Id;
1293 return DebugLoc::get(Id);
1296 /// isInlinedFnStart - Return true if FSI is starting an inlined function.
1297 bool isInlinedFnStart(DbgFuncStartInst &FSI, const Function *CurrentFn) {
1298 DISubprogram Subprogram(cast<GlobalVariable>(FSI.getSubprogram()));
1299 if (Subprogram.describes(CurrentFn))
1305 /// isInlinedFnEnd - Return true if REI is ending an inlined function.
1306 bool isInlinedFnEnd(DbgRegionEndInst &REI, const Function *CurrentFn) {
1307 DISubprogram Subprogram(cast<GlobalVariable>(REI.getContext()));
1308 if (Subprogram.isNull() || Subprogram.describes(CurrentFn))