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;
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 /// Verify - Verify that a compile unit is well formed.
210 bool DICompileUnit::Verify() const {
214 if (getFilename(Res).empty())
216 // It is possible that directory and produce string is empty.
220 /// Verify - Verify that a type descriptor is well formed.
221 bool DIType::Verify() const {
224 if (getContext().isNull())
227 DICompileUnit CU = getCompileUnit();
228 if (!CU.isNull() && !CU.Verify())
233 /// Verify - Verify that a composite type descriptor is well formed.
234 bool DICompositeType::Verify() const {
237 if (getContext().isNull())
240 DICompileUnit CU = getCompileUnit();
241 if (!CU.isNull() && !CU.Verify())
246 /// Verify - Verify that a subprogram descriptor is well formed.
247 bool DISubprogram::Verify() const {
251 if (getContext().isNull())
254 DICompileUnit CU = getCompileUnit();
258 DICompositeType Ty = getType();
259 if (!Ty.isNull() && !Ty.Verify())
264 /// Verify - Verify that a global variable descriptor is well formed.
265 bool DIGlobalVariable::Verify() const {
269 if (getContext().isNull())
272 DICompileUnit CU = getCompileUnit();
273 if (!CU.isNull() && !CU.Verify())
276 DIType Ty = getType();
286 /// Verify - Verify that a variable descriptor is well formed.
287 bool DIVariable::Verify() const {
291 if (getContext().isNull())
294 DIType Ty = getType();
301 /// getOriginalTypeSize - If this type is derived from a base type then
302 /// return base type size.
303 uint64_t DIDerivedType::getOriginalTypeSize() const {
304 if (getTag() != dwarf::DW_TAG_member)
305 return getSizeInBits();
306 DIType BT = getTypeDerivedFrom();
307 if (BT.getTag() != dwarf::DW_TAG_base_type)
308 return getSizeInBits();
309 return BT.getSizeInBits();
312 /// describes - Return true if this subprogram provides debugging
313 /// information for the function F.
314 bool DISubprogram::describes(const Function *F) {
315 assert (F && "Invalid function");
317 getLinkageName(Name);
320 if (!Name.empty() && (strcmp(Name.c_str(), F->getNameStart()) == false))
325 //===----------------------------------------------------------------------===//
326 // DIDescriptor: dump routines for all descriptors.
327 //===----------------------------------------------------------------------===//
330 /// dump - Print descriptor.
331 void DIDescriptor::dump() const {
332 cerr << "[" << dwarf::TagString(getTag()) << "] ";
333 cerr << std::hex << "[GV:" << DbgGV << "]" << std::dec;
336 /// dump - Print compile unit.
337 void DICompileUnit::dump() const {
339 cerr << " [" << dwarf::LanguageString(getLanguage()) << "] ";
341 std::string Res1, Res2;
342 cerr << " [" << getDirectory(Res1) << "/" << getFilename(Res2) << " ]";
345 /// dump - Print type.
346 void DIType::dump() const {
347 if (isNull()) return;
350 if (!getName(Res).empty())
351 cerr << " [" << Res << "] ";
353 unsigned Tag = getTag();
354 cerr << " [" << dwarf::TagString(Tag) << "] ";
356 // TODO : Print context
357 getCompileUnit().dump();
359 << getLineNumber() << ", "
360 << getSizeInBits() << ", "
361 << getAlignInBits() << ", "
366 cerr << " [private] ";
367 else if (isProtected())
368 cerr << " [protected] ";
373 if (isBasicType(Tag))
374 DIBasicType(DbgGV).dump();
375 else if (isDerivedType(Tag))
376 DIDerivedType(DbgGV).dump();
377 else if (isCompositeType(Tag))
378 DICompositeType(DbgGV).dump();
380 cerr << "Invalid DIType\n";
387 /// dump - Print basic type.
388 void DIBasicType::dump() const {
389 cerr << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
392 /// dump - Print derived type.
393 void DIDerivedType::dump() const {
394 cerr << "\n\t Derived From: "; getTypeDerivedFrom().dump();
397 /// dump - Print composite type.
398 void DICompositeType::dump() const {
399 DIArray A = getTypeArray();
402 cerr << " [" << A.getNumElements() << " elements]";
405 /// dump - Print global.
406 void DIGlobal::dump() const {
408 if (!getName(Res).empty())
409 cerr << " [" << Res << "] ";
411 unsigned Tag = getTag();
412 cerr << " [" << dwarf::TagString(Tag) << "] ";
414 // TODO : Print context
415 getCompileUnit().dump();
416 cerr << " [" << getLineNumber() << "] ";
424 if (isGlobalVariable(Tag))
425 DIGlobalVariable(DbgGV).dump();
430 /// dump - Print subprogram.
431 void DISubprogram::dump() const {
435 /// dump - Print global variable.
436 void DIGlobalVariable::dump() const {
437 cerr << " ["; getGlobal()->dump(); cerr << "] ";
440 /// dump - Print variable.
441 void DIVariable::dump() const {
443 if (!getName(Res).empty())
444 cerr << " [" << Res << "] ";
446 getCompileUnit().dump();
447 cerr << " [" << getLineNumber() << "] ";
452 //===----------------------------------------------------------------------===//
453 // DIFactory: Basic Helpers
454 //===----------------------------------------------------------------------===//
456 DIFactory::DIFactory(Module &m)
457 : M(m), StopPointFn(0), FuncStartFn(0), RegionStartFn(0), RegionEndFn(0),
460 M.getContext().getPointerTypeUnqual(M.getContext().getStructType());
463 /// getCastToEmpty - Return this descriptor as a Constant* with type '{}*'.
464 /// This is only valid when the descriptor is non-null.
465 Constant *DIFactory::getCastToEmpty(DIDescriptor D) {
466 if (D.isNull()) return M.getContext().getNullValue(EmptyStructPtr);
467 return M.getContext().getConstantExprBitCast(D.getGV(), EmptyStructPtr);
470 Constant *DIFactory::GetTagConstant(unsigned TAG) {
471 assert((TAG & LLVMDebugVersionMask) == 0 &&
472 "Tag too large for debug encoding!");
473 return ConstantInt::get(Type::Int32Ty, TAG | LLVMDebugVersion);
476 Constant *DIFactory::GetStringConstant(const std::string &String) {
477 // Check string cache for previous edition.
478 Constant *&Slot = StringCache[String];
480 // Return Constant if previously defined.
481 if (Slot) return Slot;
483 const PointerType *DestTy = M.getContext().getPointerTypeUnqual(Type::Int8Ty);
485 // If empty string then use a i8* null instead.
487 return Slot = M.getContext().getConstantPointerNull(DestTy);
489 // Construct string as an llvm constant.
490 Constant *ConstStr = M.getContext().getConstantArray(String);
492 // Otherwise create and return a new string global.
493 GlobalVariable *StrGV = new GlobalVariable(ConstStr->getType(), true,
494 GlobalVariable::InternalLinkage,
495 ConstStr, ".str", &M);
496 StrGV->setSection("llvm.metadata");
497 return Slot = M.getContext().getConstantExprBitCast(StrGV, DestTy);
500 //===----------------------------------------------------------------------===//
501 // DIFactory: Primary Constructors
502 //===----------------------------------------------------------------------===//
504 /// GetOrCreateArray - Create an descriptor for an array of descriptors.
505 /// This implicitly uniques the arrays created.
506 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
507 SmallVector<Constant*, 16> Elts;
509 LLVMContext& Ctxt = M.getContext();
511 for (unsigned i = 0; i != NumTys; ++i)
512 Elts.push_back(getCastToEmpty(Tys[i]));
514 Constant *Init = Ctxt.getConstantArray(Ctxt.getArrayType(EmptyStructPtr,
516 Elts.data(), Elts.size());
517 // If we already have this array, just return the uniqued version.
518 DIDescriptor &Entry = SimpleConstantCache[Init];
519 if (!Entry.isNull()) return DIArray(Entry.getGV());
521 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
522 GlobalValue::InternalLinkage,
523 Init, "llvm.dbg.array", &M);
524 GV->setSection("llvm.metadata");
525 Entry = DIDescriptor(GV);
529 /// GetOrCreateSubrange - Create a descriptor for a value range. This
530 /// implicitly uniques the values returned.
531 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
533 GetTagConstant(dwarf::DW_TAG_subrange_type),
534 M.getContext().getConstantInt(Type::Int64Ty, Lo),
535 M.getContext().getConstantInt(Type::Int64Ty, Hi)
539 M.getContext().getConstantStruct(Elts, sizeof(Elts)/sizeof(Elts[0]));
541 // If we already have this range, just return the uniqued version.
542 DIDescriptor &Entry = SimpleConstantCache[Init];
543 if (!Entry.isNull()) return DISubrange(Entry.getGV());
545 M.addTypeName("llvm.dbg.subrange.type", Init->getType());
547 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
548 GlobalValue::InternalLinkage,
549 Init, "llvm.dbg.subrange", &M);
550 GV->setSection("llvm.metadata");
551 Entry = DIDescriptor(GV);
552 return DISubrange(GV);
557 /// CreateCompileUnit - Create a new descriptor for the specified compile
558 /// unit. Note that this does not unique compile units within the module.
559 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
560 const std::string &Filename,
561 const std::string &Directory,
562 const std::string &Producer,
566 unsigned RunTimeVer) {
567 LLVMContext& Ctxt = M.getContext();
569 GetTagConstant(dwarf::DW_TAG_compile_unit),
570 Ctxt.getNullValue(EmptyStructPtr),
571 Ctxt.getConstantInt(Type::Int32Ty, LangID),
572 GetStringConstant(Filename),
573 GetStringConstant(Directory),
574 GetStringConstant(Producer),
575 Ctxt.getConstantInt(Type::Int1Ty, isMain),
576 Ctxt.getConstantInt(Type::Int1Ty, isOptimized),
577 GetStringConstant(Flags),
578 Ctxt.getConstantInt(Type::Int32Ty, RunTimeVer)
582 Ctxt.getConstantStruct(Elts, sizeof(Elts)/sizeof(Elts[0]));
584 M.addTypeName("llvm.dbg.compile_unit.type", Init->getType());
585 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
586 GlobalValue::LinkOnceAnyLinkage,
587 Init, "llvm.dbg.compile_unit", &M);
588 GV->setSection("llvm.metadata");
589 return DICompileUnit(GV);
592 /// CreateEnumerator - Create a single enumerator value.
593 DIEnumerator DIFactory::CreateEnumerator(const std::string &Name, uint64_t Val){
595 GetTagConstant(dwarf::DW_TAG_enumerator),
596 GetStringConstant(Name),
597 M.getContext().getConstantInt(Type::Int64Ty, Val)
601 M.getContext().getConstantStruct(Elts, sizeof(Elts)/sizeof(Elts[0]));
603 M.addTypeName("llvm.dbg.enumerator.type", Init->getType());
604 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
605 GlobalValue::InternalLinkage,
606 Init, "llvm.dbg.enumerator", &M);
607 GV->setSection("llvm.metadata");
608 return DIEnumerator(GV);
612 /// CreateBasicType - Create a basic type like int, float, etc.
613 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
614 const std::string &Name,
615 DICompileUnit CompileUnit,
618 uint64_t AlignInBits,
619 uint64_t OffsetInBits, unsigned Flags,
622 LLVMContext& Ctxt = M.getContext();
624 GetTagConstant(dwarf::DW_TAG_base_type),
625 getCastToEmpty(Context),
626 GetStringConstant(Name),
627 getCastToEmpty(CompileUnit),
628 Ctxt.getConstantInt(Type::Int32Ty, LineNumber),
629 Ctxt.getConstantInt(Type::Int64Ty, SizeInBits),
630 Ctxt.getConstantInt(Type::Int64Ty, AlignInBits),
631 Ctxt.getConstantInt(Type::Int64Ty, OffsetInBits),
632 Ctxt.getConstantInt(Type::Int32Ty, Flags),
633 Ctxt.getConstantInt(Type::Int32Ty, Encoding)
637 Ctxt.getConstantStruct(Elts, sizeof(Elts)/sizeof(Elts[0]));
639 M.addTypeName("llvm.dbg.basictype.type", Init->getType());
640 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
641 GlobalValue::InternalLinkage,
642 Init, "llvm.dbg.basictype", &M);
643 GV->setSection("llvm.metadata");
644 return DIBasicType(GV);
647 /// CreateDerivedType - Create a derived type like const qualified type,
648 /// pointer, typedef, etc.
649 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
650 DIDescriptor Context,
651 const std::string &Name,
652 DICompileUnit CompileUnit,
655 uint64_t AlignInBits,
656 uint64_t OffsetInBits,
658 DIType DerivedFrom) {
660 LLVMContext& Ctxt = M.getContext();
663 getCastToEmpty(Context),
664 GetStringConstant(Name),
665 getCastToEmpty(CompileUnit),
666 Ctxt.getConstantInt(Type::Int32Ty, LineNumber),
667 Ctxt.getConstantInt(Type::Int64Ty, SizeInBits),
668 Ctxt.getConstantInt(Type::Int64Ty, AlignInBits),
669 Ctxt.getConstantInt(Type::Int64Ty, OffsetInBits),
670 Ctxt.getConstantInt(Type::Int32Ty, Flags),
671 getCastToEmpty(DerivedFrom)
675 Ctxt.getConstantStruct(Elts, sizeof(Elts)/sizeof(Elts[0]));
677 M.addTypeName("llvm.dbg.derivedtype.type", Init->getType());
678 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
679 GlobalValue::InternalLinkage,
680 Init, "llvm.dbg.derivedtype", &M);
681 GV->setSection("llvm.metadata");
682 return DIDerivedType(GV);
685 /// CreateCompositeType - Create a composite type like array, struct, etc.
686 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
687 DIDescriptor Context,
688 const std::string &Name,
689 DICompileUnit CompileUnit,
692 uint64_t AlignInBits,
693 uint64_t OffsetInBits,
697 unsigned RuntimeLang) {
698 LLVMContext& Ctxt = M.getContext();
701 getCastToEmpty(Context),
702 GetStringConstant(Name),
703 getCastToEmpty(CompileUnit),
704 Ctxt.getConstantInt(Type::Int32Ty, LineNumber),
705 Ctxt.getConstantInt(Type::Int64Ty, SizeInBits),
706 Ctxt.getConstantInt(Type::Int64Ty, AlignInBits),
707 Ctxt.getConstantInt(Type::Int64Ty, OffsetInBits),
708 Ctxt.getConstantInt(Type::Int32Ty, Flags),
709 getCastToEmpty(DerivedFrom),
710 getCastToEmpty(Elements),
711 Ctxt.getConstantInt(Type::Int32Ty, RuntimeLang)
715 Ctxt.getConstantStruct(Elts, sizeof(Elts)/sizeof(Elts[0]));
717 M.addTypeName("llvm.dbg.composite.type", Init->getType());
718 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
719 GlobalValue::InternalLinkage,
720 Init, "llvm.dbg.composite", &M);
721 GV->setSection("llvm.metadata");
722 return DICompositeType(GV);
726 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
727 /// See comments in DISubprogram for descriptions of these fields. This
728 /// method does not unique the generated descriptors.
729 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context,
730 const std::string &Name,
731 const std::string &DisplayName,
732 const std::string &LinkageName,
733 DICompileUnit CompileUnit,
734 unsigned LineNo, DIType Type,
738 LLVMContext& Ctxt = M.getContext();
740 GetTagConstant(dwarf::DW_TAG_subprogram),
741 Ctxt.getNullValue(EmptyStructPtr),
742 getCastToEmpty(Context),
743 GetStringConstant(Name),
744 GetStringConstant(DisplayName),
745 GetStringConstant(LinkageName),
746 getCastToEmpty(CompileUnit),
747 Ctxt.getConstantInt(Type::Int32Ty, LineNo),
748 getCastToEmpty(Type),
749 Ctxt.getConstantInt(Type::Int1Ty, isLocalToUnit),
750 Ctxt.getConstantInt(Type::Int1Ty, isDefinition)
754 Ctxt.getConstantStruct(Elts, sizeof(Elts)/sizeof(Elts[0]));
756 M.addTypeName("llvm.dbg.subprogram.type", Init->getType());
757 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
758 GlobalValue::LinkOnceAnyLinkage,
759 Init, "llvm.dbg.subprogram", &M);
760 GV->setSection("llvm.metadata");
761 return DISubprogram(GV);
764 /// CreateGlobalVariable - Create a new descriptor for the specified global.
766 DIFactory::CreateGlobalVariable(DIDescriptor Context, const std::string &Name,
767 const std::string &DisplayName,
768 const std::string &LinkageName,
769 DICompileUnit CompileUnit,
770 unsigned LineNo, DIType Type,bool isLocalToUnit,
771 bool isDefinition, llvm::GlobalVariable *Val) {
773 LLVMContext& Ctxt = M.getContext();
775 GetTagConstant(dwarf::DW_TAG_variable),
776 Ctxt.getNullValue(EmptyStructPtr),
777 getCastToEmpty(Context),
778 GetStringConstant(Name),
779 GetStringConstant(DisplayName),
780 GetStringConstant(LinkageName),
781 getCastToEmpty(CompileUnit),
782 Ctxt.getConstantInt(Type::Int32Ty, LineNo),
783 getCastToEmpty(Type),
784 Ctxt.getConstantInt(Type::Int1Ty, isLocalToUnit),
785 Ctxt.getConstantInt(Type::Int1Ty, isDefinition),
786 Ctxt.getConstantExprBitCast(Val, EmptyStructPtr)
790 Ctxt.getConstantStruct(Elts, sizeof(Elts)/sizeof(Elts[0]));
792 M.addTypeName("llvm.dbg.global_variable.type", Init->getType());
793 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
794 GlobalValue::LinkOnceAnyLinkage,
795 Init, "llvm.dbg.global_variable", &M);
796 GV->setSection("llvm.metadata");
797 return DIGlobalVariable(GV);
801 /// CreateVariable - Create a new descriptor for the specified variable.
802 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
803 const std::string &Name,
804 DICompileUnit CompileUnit, unsigned LineNo,
806 LLVMContext& Ctxt = M.getContext();
810 getCastToEmpty(Context),
811 GetStringConstant(Name),
812 getCastToEmpty(CompileUnit),
813 Ctxt.getConstantInt(Type::Int32Ty, LineNo),
818 Ctxt.getConstantStruct(Elts, sizeof(Elts)/sizeof(Elts[0]));
820 M.addTypeName("llvm.dbg.variable.type", Init->getType());
821 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
822 GlobalValue::InternalLinkage,
823 Init, "llvm.dbg.variable", &M);
824 GV->setSection("llvm.metadata");
825 return DIVariable(GV);
829 /// CreateBlock - This creates a descriptor for a lexical block with the
830 /// specified parent context.
831 DIBlock DIFactory::CreateBlock(DIDescriptor Context) {
833 GetTagConstant(dwarf::DW_TAG_lexical_block),
834 getCastToEmpty(Context)
838 M.getContext().getConstantStruct(Elts, sizeof(Elts)/sizeof(Elts[0]));
840 M.addTypeName("llvm.dbg.block.type", Init->getType());
841 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
842 GlobalValue::InternalLinkage,
843 Init, "llvm.dbg.block", &M);
844 GV->setSection("llvm.metadata");
849 //===----------------------------------------------------------------------===//
850 // DIFactory: Routines for inserting code into a function
851 //===----------------------------------------------------------------------===//
853 /// InsertStopPoint - Create a new llvm.dbg.stoppoint intrinsic invocation,
854 /// inserting it at the end of the specified basic block.
855 void DIFactory::InsertStopPoint(DICompileUnit CU, unsigned LineNo,
856 unsigned ColNo, BasicBlock *BB) {
858 // Lazily construct llvm.dbg.stoppoint function.
860 StopPointFn = llvm::Intrinsic::getDeclaration(&M,
861 llvm::Intrinsic::dbg_stoppoint);
863 // Invoke llvm.dbg.stoppoint
865 M.getContext().getConstantInt(llvm::Type::Int32Ty, LineNo),
866 M.getContext().getConstantInt(llvm::Type::Int32Ty, ColNo),
869 CallInst::Create(StopPointFn, Args, Args+3, "", BB);
872 /// InsertSubprogramStart - Create a new llvm.dbg.func.start intrinsic to
873 /// mark the start of the specified subprogram.
874 void DIFactory::InsertSubprogramStart(DISubprogram SP, BasicBlock *BB) {
875 // Lazily construct llvm.dbg.func.start.
877 FuncStartFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_func_start);
879 // Call llvm.dbg.func.start which also implicitly sets a stoppoint.
880 CallInst::Create(FuncStartFn, getCastToEmpty(SP), "", BB);
883 /// InsertRegionStart - Insert a new llvm.dbg.region.start intrinsic call to
884 /// mark the start of a region for the specified scoping descriptor.
885 void DIFactory::InsertRegionStart(DIDescriptor D, BasicBlock *BB) {
886 // Lazily construct llvm.dbg.region.start function.
888 RegionStartFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_region_start);
890 // Call llvm.dbg.func.start.
891 CallInst::Create(RegionStartFn, getCastToEmpty(D), "", BB);
894 /// InsertRegionEnd - Insert a new llvm.dbg.region.end intrinsic call to
895 /// mark the end of a region for the specified scoping descriptor.
896 void DIFactory::InsertRegionEnd(DIDescriptor D, BasicBlock *BB) {
897 // Lazily construct llvm.dbg.region.end function.
899 RegionEndFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_region_end);
901 // Call llvm.dbg.region.end.
902 CallInst::Create(RegionEndFn, getCastToEmpty(D), "", BB);
905 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
906 void DIFactory::InsertDeclare(Value *Storage, DIVariable D, BasicBlock *BB) {
907 // Cast the storage to a {}* for the call to llvm.dbg.declare.
908 Storage = new BitCastInst(Storage, EmptyStructPtr, "", BB);
911 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
913 Value *Args[] = { Storage, getCastToEmpty(D) };
914 CallInst::Create(DeclareFn, Args, Args+2, "", BB);
918 /// findStopPoint - Find the stoppoint coressponding to this instruction, that
919 /// is the stoppoint that dominates this instruction.
920 const DbgStopPointInst *findStopPoint(const Instruction *Inst) {
921 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(Inst))
924 const BasicBlock *BB = Inst->getParent();
925 BasicBlock::const_iterator I = Inst, B;
929 // A BB consisting only of a terminator can't have a stoppoint.
932 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
936 // This BB didn't have a stoppoint: if there is only one predecessor, look
937 // for a stoppoint there. We could use getIDom(), but that would require
939 BB = I->getParent()->getUniquePredecessor();
941 I = BB->getTerminator();
947 /// findBBStopPoint - Find the stoppoint corresponding to first real
948 /// (non-debug intrinsic) instruction in this Basic Block, and return the
949 /// stoppoint for it.
950 const DbgStopPointInst *findBBStopPoint(const BasicBlock *BB) {
951 for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
952 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
955 // Fallback to looking for stoppoint of unique predecessor. Useful if this
956 // BB contains no stoppoints, but unique predecessor does.
957 BB = BB->getUniquePredecessor();
959 return findStopPoint(BB->getTerminator());
964 Value *findDbgGlobalDeclare(GlobalVariable *V) {
965 const Module *M = V->getParent();
966 const Type *Ty = M->getTypeByName("llvm.dbg.global_variable.type");
969 Ty = V->getParent()->getContext().getPointerType(Ty, 0);
971 Value *Val = V->stripPointerCasts();
972 for (Value::use_iterator I = Val->use_begin(), E = Val->use_end();
974 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I)) {
975 if (CE->getOpcode() == Instruction::BitCast) {
978 while (VV->hasOneUse())
979 VV = *VV->use_begin();
981 if (VV->getType() == Ty)
987 if (Val->getType() == Ty)
993 /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
994 /// It looks through pointer casts too.
995 const DbgDeclareInst *findDbgDeclare(const Value *V, bool stripCasts) {
997 V = V->stripPointerCasts();
999 // Look for the bitcast.
1000 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1002 if (isa<BitCastInst>(I))
1003 return findDbgDeclare(*I, false);
1008 // Find llvm.dbg.declare among uses of the instruction.
1009 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1011 if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
1017 bool getLocationInfo(const Value *V, std::string &DisplayName,
1018 std::string &Type, unsigned &LineNo, std::string &File,
1023 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
1024 Value *DIGV = findDbgGlobalDeclare(GV);
1025 if (!DIGV) return false;
1026 DIGlobalVariable Var(cast<GlobalVariable>(DIGV));
1028 Var.getDisplayName(DisplayName);
1029 LineNo = Var.getLineNumber();
1030 Unit = Var.getCompileUnit();
1031 TypeD = Var.getType();
1033 const DbgDeclareInst *DDI = findDbgDeclare(V);
1034 if (!DDI) return false;
1035 DIVariable Var(cast<GlobalVariable>(DDI->getVariable()));
1037 Var.getName(DisplayName);
1038 LineNo = Var.getLineNumber();
1039 Unit = Var.getCompileUnit();
1040 TypeD = Var.getType();
1043 TypeD.getName(Type);
1044 Unit.getFilename(File);
1045 Unit.getDirectory(Dir);
1049 /// CollectDebugInfoAnchors - Collect debugging information anchors.
1050 void CollectDebugInfoAnchors(Module &M,
1051 SmallVector<GlobalVariable *, 2> &CUs,
1052 SmallVector<GlobalVariable *, 4> &GVs,
1053 SmallVector<GlobalVariable *, 4> &SPs) {
1055 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1057 GlobalVariable *GV = GVI;
1058 if (GV->hasName() && strncmp(GV->getNameStart(), "llvm.dbg", 8) == 0
1059 && GV->isConstant() && GV->hasInitializer()) {
1060 DICompileUnit C(GV);
1061 if (C.isNull() == false) {
1065 DIGlobalVariable G(GV);
1066 if (G.isNull() == false) {
1071 if (S.isNull() == false) {
1079 /// isValidDebugInfoIntrinsic - Return true if SPI is a valid debug
1081 bool isValidDebugInfoIntrinsic(DbgStopPointInst &SPI,
1082 CodeGenOpt::Level OptLev) {
1083 return DIDescriptor::ValidDebugInfo(SPI.getContext(), OptLev);
1086 /// isValidDebugInfoIntrinsic - Return true if FSI is a valid debug
1088 bool isValidDebugInfoIntrinsic(DbgFuncStartInst &FSI,
1089 CodeGenOpt::Level OptLev) {
1090 return DIDescriptor::ValidDebugInfo(FSI.getSubprogram(), OptLev);
1093 /// isValidDebugInfoIntrinsic - Return true if RSI is a valid debug
1095 bool isValidDebugInfoIntrinsic(DbgRegionStartInst &RSI,
1096 CodeGenOpt::Level OptLev) {
1097 return DIDescriptor::ValidDebugInfo(RSI.getContext(), OptLev);
1100 /// isValidDebugInfoIntrinsic - Return true if REI is a valid debug
1102 bool isValidDebugInfoIntrinsic(DbgRegionEndInst &REI,
1103 CodeGenOpt::Level OptLev) {
1104 return DIDescriptor::ValidDebugInfo(REI.getContext(), OptLev);
1108 /// isValidDebugInfoIntrinsic - Return true if DI is a valid debug
1110 bool isValidDebugInfoIntrinsic(DbgDeclareInst &DI,
1111 CodeGenOpt::Level OptLev) {
1112 return DIDescriptor::ValidDebugInfo(DI.getVariable(), OptLev);
1115 /// ExtractDebugLocation - Extract debug location information
1116 /// from llvm.dbg.stoppoint intrinsic.
1117 DebugLoc ExtractDebugLocation(DbgStopPointInst &SPI,
1118 DebugLocTracker &DebugLocInfo) {
1120 Value *Context = SPI.getContext();
1122 // If this location is already tracked then use it.
1123 DebugLocTuple Tuple(cast<GlobalVariable>(Context), SPI.getLine(),
1125 DenseMap<DebugLocTuple, unsigned>::iterator II
1126 = DebugLocInfo.DebugIdMap.find(Tuple);
1127 if (II != DebugLocInfo.DebugIdMap.end())
1128 return DebugLoc::get(II->second);
1130 // Add a new location entry.
1131 unsigned Id = DebugLocInfo.DebugLocations.size();
1132 DebugLocInfo.DebugLocations.push_back(Tuple);
1133 DebugLocInfo.DebugIdMap[Tuple] = Id;
1135 return DebugLoc::get(Id);
1138 /// ExtractDebugLocation - Extract debug location information
1139 /// from llvm.dbg.func_start intrinsic.
1140 DebugLoc ExtractDebugLocation(DbgFuncStartInst &FSI,
1141 DebugLocTracker &DebugLocInfo) {
1143 Value *SP = FSI.getSubprogram();
1145 DISubprogram Subprogram(cast<GlobalVariable>(SP));
1146 unsigned Line = Subprogram.getLineNumber();
1147 DICompileUnit CU(Subprogram.getCompileUnit());
1149 // If this location is already tracked then use it.
1150 DebugLocTuple Tuple(CU.getGV(), Line, /* Column */ 0);
1151 DenseMap<DebugLocTuple, unsigned>::iterator II
1152 = DebugLocInfo.DebugIdMap.find(Tuple);
1153 if (II != DebugLocInfo.DebugIdMap.end())
1154 return DebugLoc::get(II->second);
1156 // Add a new location entry.
1157 unsigned Id = DebugLocInfo.DebugLocations.size();
1158 DebugLocInfo.DebugLocations.push_back(Tuple);
1159 DebugLocInfo.DebugIdMap[Tuple] = Id;
1161 return DebugLoc::get(Id);
1164 /// isInlinedFnStart - Return true if FSI is starting an inlined function.
1165 bool isInlinedFnStart(DbgFuncStartInst &FSI, const Function *CurrentFn) {
1166 DISubprogram Subprogram(cast<GlobalVariable>(FSI.getSubprogram()));
1167 if (Subprogram.describes(CurrentFn))
1173 /// isInlinedFnEnd - Return true if REI is ending an inlined function.
1174 bool isInlinedFnEnd(DbgRegionEndInst &REI, const Function *CurrentFn) {
1175 DISubprogram Subprogram(cast<GlobalVariable>(REI.getContext()));
1176 if (Subprogram.isNull() || Subprogram.describes(CurrentFn))