1 //===--- DebugInfo.cpp - Debug Information Helper Classes -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the helper classes used to build and interpret debug
11 // information in LLVM IR form.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Analysis/DebugInfo.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Intrinsics.h"
19 #include "llvm/IntrinsicInst.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/Support/Dwarf.h"
24 #include "llvm/Support/Streams.h"
26 using namespace llvm::dwarf;
28 //===----------------------------------------------------------------------===//
30 //===----------------------------------------------------------------------===//
32 /// ValidDebugInfo - Return true if V represents valid debug info value.
33 bool DIDescriptor::ValidDebugInfo(Value *V, CodeGenOpt::Level OptLevel) {
37 GlobalVariable *GV = dyn_cast<GlobalVariable>(V->stripPointerCasts());
41 if (!GV->hasInternalLinkage () && !GV->hasLinkOnceLinkage())
46 // Check current version. Allow Version6 for now.
47 unsigned Version = DI.getVersion();
48 if (Version != LLVMDebugVersion && Version != LLVMDebugVersion6)
51 unsigned Tag = DI.getTag();
54 assert(DIVariable(GV).Verify() && "Invalid DebugInfo value");
56 case DW_TAG_compile_unit:
57 assert(DICompileUnit(GV).Verify() && "Invalid DebugInfo value");
59 case DW_TAG_subprogram:
60 assert(DISubprogram(GV).Verify() && "Invalid DebugInfo value");
62 case DW_TAG_inlined_subroutine:
63 assert(DIInlinedSubprogram(GV).Verify() && "Invalid DebugInfo value");
65 case DW_TAG_lexical_block:
66 /// FIXME. This interfers with the quality of generated code when
67 /// during optimization.
68 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 = GV->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 (GV == 0) return 0;
107 Constant *C = GV->getInitializer();
108 if (C == 0 || Elt >= C->getNumOperands())
110 if (ConstantInt *CI = dyn_cast<ConstantInt>(C->getOperand(Elt)))
111 return CI->getZExtValue();
115 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
116 if (GV == 0) return DIDescriptor();
117 Constant *C = GV->getInitializer();
118 if (C == 0 || Elt >= C->getNumOperands())
119 return DIDescriptor();
120 C = C->getOperand(Elt);
121 return DIDescriptor(dyn_cast<GlobalVariable>(C->stripPointerCasts()));
124 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
125 if (GV == 0) return 0;
126 Constant *C = GV->getInitializer();
127 if (C == 0 || Elt >= C->getNumOperands())
129 C = C->getOperand(Elt);
131 return dyn_cast<GlobalVariable>(C->stripPointerCasts());
136 //===----------------------------------------------------------------------===//
137 // Simple Descriptor Constructors and other Methods
138 //===----------------------------------------------------------------------===//
140 DIAnchor::DIAnchor(GlobalVariable *GV)
141 : DIDescriptor(GV, dwarf::DW_TAG_anchor) {}
142 DIEnumerator::DIEnumerator(GlobalVariable *GV)
143 : DIDescriptor(GV, dwarf::DW_TAG_enumerator) {}
144 DISubrange::DISubrange(GlobalVariable *GV)
145 : DIDescriptor(GV, dwarf::DW_TAG_subrange_type) {}
146 DICompileUnit::DICompileUnit(GlobalVariable *GV)
147 : DIDescriptor(GV, dwarf::DW_TAG_compile_unit) {}
148 DIBasicType::DIBasicType(GlobalVariable *GV)
149 : DIType(GV, dwarf::DW_TAG_base_type) {}
150 DISubprogram::DISubprogram(GlobalVariable *GV)
151 : DIGlobal(GV, dwarf::DW_TAG_subprogram) {}
152 DIInlinedSubprogram::DIInlinedSubprogram(GlobalVariable *GV)
153 : DIGlobal(GV, dwarf::DW_TAG_inlined_subroutine) {}
154 DIGlobalVariable::DIGlobalVariable(GlobalVariable *GV)
155 : DIGlobal(GV, dwarf::DW_TAG_variable) {}
156 DIBlock::DIBlock(GlobalVariable *GV)
157 : DIDescriptor(GV, dwarf::DW_TAG_lexical_block) {}
158 // needed by DIVariable::getType()
159 DIType::DIType(GlobalVariable *gv) : DIDescriptor(gv) {
161 unsigned tag = getTag();
162 if (tag != dwarf::DW_TAG_base_type && !DIDerivedType::isDerivedType(tag) &&
163 !DICompositeType::isCompositeType(tag))
167 /// isDerivedType - Return true if the specified tag is legal for
169 bool DIType::isDerivedType(unsigned Tag) {
171 case dwarf::DW_TAG_typedef:
172 case dwarf::DW_TAG_pointer_type:
173 case dwarf::DW_TAG_reference_type:
174 case dwarf::DW_TAG_const_type:
175 case dwarf::DW_TAG_volatile_type:
176 case dwarf::DW_TAG_restrict_type:
177 case dwarf::DW_TAG_member:
178 case dwarf::DW_TAG_inheritance:
181 // FIXME: Even though it doesn't make sense, CompositeTypes are current
182 // modelled as DerivedTypes, this should return true for them as well.
187 DIDerivedType::DIDerivedType(GlobalVariable *GV) : DIType(GV, true, true) {
188 if (GV && !isDerivedType(getTag()))
192 /// isCompositeType - Return true if the specified tag is legal for
194 bool DIType::isCompositeType(unsigned TAG) {
196 case dwarf::DW_TAG_array_type:
197 case dwarf::DW_TAG_structure_type:
198 case dwarf::DW_TAG_union_type:
199 case dwarf::DW_TAG_enumeration_type:
200 case dwarf::DW_TAG_vector_type:
201 case dwarf::DW_TAG_subroutine_type:
202 case dwarf::DW_TAG_class_type:
209 DICompositeType::DICompositeType(GlobalVariable *GV)
210 : DIDerivedType(GV, true, true) {
211 if (GV && !isCompositeType(getTag()))
215 /// isVariable - Return true if the specified tag is legal for DIVariable.
216 bool DIVariable::isVariable(unsigned Tag) {
218 case dwarf::DW_TAG_auto_variable:
219 case dwarf::DW_TAG_arg_variable:
220 case dwarf::DW_TAG_return_variable:
227 DIVariable::DIVariable(GlobalVariable *gv) : DIDescriptor(gv) {
228 if (gv && !isVariable(getTag()))
232 unsigned DIArray::getNumElements() const {
233 assert (GV && "Invalid DIArray");
234 Constant *C = GV->getInitializer();
235 assert (C && "Invalid DIArray initializer");
236 return C->getNumOperands();
239 /// Verify - Verify that a compile unit is well formed.
240 bool DICompileUnit::Verify() const {
244 if (getFilename(Res).empty())
246 // It is possible that directory and produce string is empty.
250 /// Verify - Verify that a type descriptor is well formed.
251 bool DIType::Verify() const {
254 if (getContext().isNull())
257 DICompileUnit CU = getCompileUnit();
258 if (!CU.isNull() && !CU.Verify())
263 /// Verify - Verify that a composite type descriptor is well formed.
264 bool DICompositeType::Verify() const {
267 if (getContext().isNull())
270 DICompileUnit CU = getCompileUnit();
271 if (!CU.isNull() && !CU.Verify())
276 /// Verify - Verify that a subprogram descriptor is well formed.
277 bool DISubprogram::Verify() const {
281 if (getContext().isNull())
284 DICompileUnit CU = getCompileUnit();
288 DICompositeType Ty = getType();
289 if (!Ty.isNull() && !Ty.Verify())
294 /// Verify - Verify that an inlined subprogram descriptor is well formed.
295 bool DIInlinedSubprogram::Verify() const {
299 if (getContext().isNull())
302 DICompileUnit CU = getCompileUnit();
306 DICompositeType Ty = getType();
307 if (!Ty.isNull() && !Ty.Verify())
313 /// Verify - Verify that a global variable descriptor is well formed.
314 bool DIGlobalVariable::Verify() const {
318 if (getContext().isNull())
321 DICompileUnit CU = getCompileUnit();
322 if (!CU.isNull() && !CU.Verify())
325 DIType Ty = getType();
335 /// Verify - Verify that a variable descriptor is well formed.
336 bool DIVariable::Verify() const {
340 if (getContext().isNull())
343 DIType Ty = getType();
350 /// getOriginalTypeSize - If this type is derived from a base type then
351 /// return base type size.
352 uint64_t DIDerivedType::getOriginalTypeSize() const {
353 if (getTag() != dwarf::DW_TAG_member)
354 return getSizeInBits();
355 DIType BT = getTypeDerivedFrom();
356 if (BT.getTag() != dwarf::DW_TAG_base_type)
357 return getSizeInBits();
358 return BT.getSizeInBits();
361 /// describes - Return true if this subprogram provides debugging
362 /// information for the function F.
363 bool DISubprogram::describes(const Function *F) {
364 assert (F && "Invalid function");
366 getLinkageName(Name);
369 if (!Name.empty() && (strcmp(Name.c_str(), F->getNameStart()) == false))
374 //===----------------------------------------------------------------------===//
375 // DIFactory: Basic Helpers
376 //===----------------------------------------------------------------------===//
378 DIFactory::DIFactory(Module &m) : M(m) {
379 StopPointFn = FuncStartFn = RegionStartFn = RegionEndFn = DeclareFn = 0;
380 EmptyStructPtr = PointerType::getUnqual(StructType::get(NULL, NULL));
383 /// getCastToEmpty - Return this descriptor as a Constant* with type '{}*'.
384 /// This is only valid when the descriptor is non-null.
385 Constant *DIFactory::getCastToEmpty(DIDescriptor D) {
386 if (D.isNull()) return Constant::getNullValue(EmptyStructPtr);
387 return ConstantExpr::getBitCast(D.getGV(), EmptyStructPtr);
390 Constant *DIFactory::GetTagConstant(unsigned TAG) {
391 assert((TAG & LLVMDebugVersionMask) == 0 &&
392 "Tag too large for debug encoding!");
393 return ConstantInt::get(Type::Int32Ty, TAG | LLVMDebugVersion);
396 Constant *DIFactory::GetStringConstant(const std::string &String) {
397 // Check string cache for previous edition.
398 Constant *&Slot = StringCache[String];
400 // Return Constant if previously defined.
401 if (Slot) return Slot;
403 const PointerType *DestTy = PointerType::getUnqual(Type::Int8Ty);
405 // If empty string then use a sbyte* null instead.
407 return Slot = ConstantPointerNull::get(DestTy);
409 // Construct string as an llvm constant.
410 Constant *ConstStr = ConstantArray::get(String);
412 // Otherwise create and return a new string global.
413 GlobalVariable *StrGV = new GlobalVariable(ConstStr->getType(), true,
414 GlobalVariable::InternalLinkage,
415 ConstStr, ".str", &M);
416 StrGV->setSection("llvm.metadata");
417 return Slot = ConstantExpr::getBitCast(StrGV, DestTy);
420 /// GetOrCreateAnchor - Look up an anchor for the specified tag and name. If it
421 /// already exists, return it. If not, create a new one and return it.
422 DIAnchor DIFactory::GetOrCreateAnchor(unsigned TAG, const char *Name) {
423 const Type *EltTy = StructType::get(Type::Int32Ty, Type::Int32Ty, NULL);
425 // Otherwise, create the global or return it if already in the module.
426 Constant *C = M.getOrInsertGlobal(Name, EltTy);
427 assert(isa<GlobalVariable>(C) && "Incorrectly typed anchor?");
428 GlobalVariable *GV = cast<GlobalVariable>(C);
430 // If it has an initializer, it is already in the module.
431 if (GV->hasInitializer())
432 return SubProgramAnchor = DIAnchor(GV);
434 GV->setLinkage(GlobalValue::LinkOnceAnyLinkage);
435 GV->setSection("llvm.metadata");
436 GV->setConstant(true);
437 M.addTypeName("llvm.dbg.anchor.type", EltTy);
439 // Otherwise, set the initializer.
441 GetTagConstant(dwarf::DW_TAG_anchor),
442 ConstantInt::get(Type::Int32Ty, TAG)
445 GV->setInitializer(ConstantStruct::get(Elts, 2));
451 //===----------------------------------------------------------------------===//
452 // DIFactory: Primary Constructors
453 //===----------------------------------------------------------------------===//
455 /// GetOrCreateCompileUnitAnchor - Return the anchor for compile units,
456 /// creating a new one if there isn't already one in the module.
457 DIAnchor DIFactory::GetOrCreateCompileUnitAnchor() {
458 // If we already created one, just return it.
459 if (!CompileUnitAnchor.isNull())
460 return CompileUnitAnchor;
461 return CompileUnitAnchor = GetOrCreateAnchor(dwarf::DW_TAG_compile_unit,
462 "llvm.dbg.compile_units");
465 /// GetOrCreateSubprogramAnchor - Return the anchor for subprograms,
466 /// creating a new one if there isn't already one in the module.
467 DIAnchor DIFactory::GetOrCreateSubprogramAnchor() {
468 // If we already created one, just return it.
469 if (!SubProgramAnchor.isNull())
470 return SubProgramAnchor;
471 return SubProgramAnchor = GetOrCreateAnchor(dwarf::DW_TAG_subprogram,
472 "llvm.dbg.subprograms");
475 /// GetOrCreateGlobalVariableAnchor - Return the anchor for globals,
476 /// creating a new one if there isn't already one in the module.
477 DIAnchor DIFactory::GetOrCreateGlobalVariableAnchor() {
478 // If we already created one, just return it.
479 if (!GlobalVariableAnchor.isNull())
480 return GlobalVariableAnchor;
481 return GlobalVariableAnchor = GetOrCreateAnchor(dwarf::DW_TAG_variable,
482 "llvm.dbg.global_variables");
485 /// GetOrCreateArray - Create an descriptor for an array of descriptors.
486 /// This implicitly uniques the arrays created.
487 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
488 SmallVector<Constant*, 16> Elts;
490 for (unsigned i = 0; i != NumTys; ++i)
491 Elts.push_back(getCastToEmpty(Tys[i]));
493 Constant *Init = ConstantArray::get(ArrayType::get(EmptyStructPtr,
495 &Elts[0], Elts.size());
496 // If we already have this array, just return the uniqued version.
497 DIDescriptor &Entry = SimpleConstantCache[Init];
498 if (!Entry.isNull()) return DIArray(Entry.getGV());
500 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
501 GlobalValue::InternalLinkage,
502 Init, "llvm.dbg.array", &M);
503 GV->setSection("llvm.metadata");
504 Entry = DIDescriptor(GV);
508 /// GetOrCreateSubrange - Create a descriptor for a value range. This
509 /// implicitly uniques the values returned.
510 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
512 GetTagConstant(dwarf::DW_TAG_subrange_type),
513 ConstantInt::get(Type::Int64Ty, Lo),
514 ConstantInt::get(Type::Int64Ty, Hi)
517 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
519 // If we already have this range, just return the uniqued version.
520 DIDescriptor &Entry = SimpleConstantCache[Init];
521 if (!Entry.isNull()) return DISubrange(Entry.getGV());
523 M.addTypeName("llvm.dbg.subrange.type", Init->getType());
525 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
526 GlobalValue::InternalLinkage,
527 Init, "llvm.dbg.subrange", &M);
528 GV->setSection("llvm.metadata");
529 Entry = DIDescriptor(GV);
530 return DISubrange(GV);
535 /// CreateCompileUnit - Create a new descriptor for the specified compile
536 /// unit. Note that this does not unique compile units within the module.
537 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
538 const std::string &Filename,
539 const std::string &Directory,
540 const std::string &Producer,
544 unsigned RunTimeVer) {
546 GetTagConstant(dwarf::DW_TAG_compile_unit),
547 getCastToEmpty(GetOrCreateCompileUnitAnchor()),
548 ConstantInt::get(Type::Int32Ty, LangID),
549 GetStringConstant(Filename),
550 GetStringConstant(Directory),
551 GetStringConstant(Producer),
552 ConstantInt::get(Type::Int1Ty, isMain),
553 ConstantInt::get(Type::Int1Ty, isOptimized),
554 GetStringConstant(Flags),
555 ConstantInt::get(Type::Int32Ty, RunTimeVer)
558 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
560 M.addTypeName("llvm.dbg.compile_unit.type", Init->getType());
561 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
562 GlobalValue::InternalLinkage,
563 Init, "llvm.dbg.compile_unit", &M);
564 GV->setSection("llvm.metadata");
565 return DICompileUnit(GV);
568 /// CreateEnumerator - Create a single enumerator value.
569 DIEnumerator DIFactory::CreateEnumerator(const std::string &Name, uint64_t Val){
571 GetTagConstant(dwarf::DW_TAG_enumerator),
572 GetStringConstant(Name),
573 ConstantInt::get(Type::Int64Ty, Val)
576 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
578 M.addTypeName("llvm.dbg.enumerator.type", Init->getType());
579 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
580 GlobalValue::InternalLinkage,
581 Init, "llvm.dbg.enumerator", &M);
582 GV->setSection("llvm.metadata");
583 return DIEnumerator(GV);
587 /// CreateBasicType - Create a basic type like int, float, etc.
588 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
589 const std::string &Name,
590 DICompileUnit CompileUnit,
593 uint64_t AlignInBits,
594 uint64_t OffsetInBits, unsigned Flags,
597 GetTagConstant(dwarf::DW_TAG_base_type),
598 getCastToEmpty(Context),
599 GetStringConstant(Name),
600 getCastToEmpty(CompileUnit),
601 ConstantInt::get(Type::Int32Ty, LineNumber),
602 ConstantInt::get(Type::Int64Ty, SizeInBits),
603 ConstantInt::get(Type::Int64Ty, AlignInBits),
604 ConstantInt::get(Type::Int64Ty, OffsetInBits),
605 ConstantInt::get(Type::Int32Ty, Flags),
606 ConstantInt::get(Type::Int32Ty, Encoding)
609 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
611 M.addTypeName("llvm.dbg.basictype.type", Init->getType());
612 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
613 GlobalValue::InternalLinkage,
614 Init, "llvm.dbg.basictype", &M);
615 GV->setSection("llvm.metadata");
616 return DIBasicType(GV);
619 /// CreateDerivedType - Create a derived type like const qualified type,
620 /// pointer, typedef, etc.
621 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
622 DIDescriptor Context,
623 const std::string &Name,
624 DICompileUnit CompileUnit,
627 uint64_t AlignInBits,
628 uint64_t OffsetInBits,
630 DIType DerivedFrom) {
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 getCastToEmpty(DerivedFrom)
644 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
646 M.addTypeName("llvm.dbg.derivedtype.type", Init->getType());
647 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
648 GlobalValue::InternalLinkage,
649 Init, "llvm.dbg.derivedtype", &M);
650 GV->setSection("llvm.metadata");
651 return DIDerivedType(GV);
654 /// CreateCompositeType - Create a composite type like array, struct, etc.
655 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
656 DIDescriptor Context,
657 const std::string &Name,
658 DICompileUnit CompileUnit,
661 uint64_t AlignInBits,
662 uint64_t OffsetInBits,
666 unsigned RuntimeLang) {
670 getCastToEmpty(Context),
671 GetStringConstant(Name),
672 getCastToEmpty(CompileUnit),
673 ConstantInt::get(Type::Int32Ty, LineNumber),
674 ConstantInt::get(Type::Int64Ty, SizeInBits),
675 ConstantInt::get(Type::Int64Ty, AlignInBits),
676 ConstantInt::get(Type::Int64Ty, OffsetInBits),
677 ConstantInt::get(Type::Int32Ty, Flags),
678 getCastToEmpty(DerivedFrom),
679 getCastToEmpty(Elements),
680 ConstantInt::get(Type::Int32Ty, RuntimeLang)
683 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
685 M.addTypeName("llvm.dbg.composite.type", Init->getType());
686 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
687 GlobalValue::InternalLinkage,
688 Init, "llvm.dbg.composite", &M);
689 GV->setSection("llvm.metadata");
690 return DICompositeType(GV);
694 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
695 /// See comments in DISubprogram for descriptions of these fields. This
696 /// method does not unique the generated descriptors.
697 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context,
698 const std::string &Name,
699 const std::string &DisplayName,
700 const std::string &LinkageName,
701 DICompileUnit CompileUnit,
702 unsigned LineNo, DIType Type,
707 GetTagConstant(dwarf::DW_TAG_subprogram),
708 getCastToEmpty(GetOrCreateSubprogramAnchor()),
709 getCastToEmpty(Context),
710 GetStringConstant(Name),
711 GetStringConstant(DisplayName),
712 GetStringConstant(LinkageName),
713 getCastToEmpty(CompileUnit),
714 ConstantInt::get(Type::Int32Ty, LineNo),
715 getCastToEmpty(Type),
716 ConstantInt::get(Type::Int1Ty, isLocalToUnit),
717 ConstantInt::get(Type::Int1Ty, isDefinition)
720 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
722 M.addTypeName("llvm.dbg.subprogram.type", Init->getType());
723 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
724 GlobalValue::InternalLinkage,
725 Init, "llvm.dbg.subprogram", &M);
726 GV->setSection("llvm.metadata");
727 return DISubprogram(GV);
730 /// CreateGlobalVariable - Create a new descriptor for the specified global.
732 DIFactory::CreateGlobalVariable(DIDescriptor Context, const std::string &Name,
733 const std::string &DisplayName,
734 const std::string &LinkageName,
735 DICompileUnit CompileUnit,
736 unsigned LineNo, DIType Type,bool isLocalToUnit,
737 bool isDefinition, llvm::GlobalVariable *Val) {
739 GetTagConstant(dwarf::DW_TAG_variable),
740 getCastToEmpty(GetOrCreateGlobalVariableAnchor()),
741 getCastToEmpty(Context),
742 GetStringConstant(Name),
743 GetStringConstant(DisplayName),
744 GetStringConstant(LinkageName),
745 getCastToEmpty(CompileUnit),
746 ConstantInt::get(Type::Int32Ty, LineNo),
747 getCastToEmpty(Type),
748 ConstantInt::get(Type::Int1Ty, isLocalToUnit),
749 ConstantInt::get(Type::Int1Ty, isDefinition),
750 ConstantExpr::getBitCast(Val, EmptyStructPtr)
753 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
755 M.addTypeName("llvm.dbg.global_variable.type", Init->getType());
756 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
757 GlobalValue::InternalLinkage,
758 Init, "llvm.dbg.global_variable", &M);
759 GV->setSection("llvm.metadata");
760 return DIGlobalVariable(GV);
764 /// CreateVariable - Create a new descriptor for the specified variable.
765 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
766 const std::string &Name,
767 DICompileUnit CompileUnit, unsigned LineNo,
771 getCastToEmpty(Context),
772 GetStringConstant(Name),
773 getCastToEmpty(CompileUnit),
774 ConstantInt::get(Type::Int32Ty, LineNo),
778 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
780 M.addTypeName("llvm.dbg.variable.type", Init->getType());
781 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
782 GlobalValue::InternalLinkage,
783 Init, "llvm.dbg.variable", &M);
784 GV->setSection("llvm.metadata");
785 return DIVariable(GV);
789 /// CreateBlock - This creates a descriptor for a lexical block with the
790 /// specified parent context.
791 DIBlock DIFactory::CreateBlock(DIDescriptor Context) {
793 GetTagConstant(dwarf::DW_TAG_lexical_block),
794 getCastToEmpty(Context)
797 Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
799 M.addTypeName("llvm.dbg.block.type", Init->getType());
800 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
801 GlobalValue::InternalLinkage,
802 Init, "llvm.dbg.block", &M);
803 GV->setSection("llvm.metadata");
808 //===----------------------------------------------------------------------===//
809 // DIFactory: Routines for inserting code into a function
810 //===----------------------------------------------------------------------===//
812 /// InsertStopPoint - Create a new llvm.dbg.stoppoint intrinsic invocation,
813 /// inserting it at the end of the specified basic block.
814 void DIFactory::InsertStopPoint(DICompileUnit CU, unsigned LineNo,
815 unsigned ColNo, BasicBlock *BB) {
817 // Lazily construct llvm.dbg.stoppoint function.
819 StopPointFn = llvm::Intrinsic::getDeclaration(&M,
820 llvm::Intrinsic::dbg_stoppoint);
822 // Invoke llvm.dbg.stoppoint
824 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo),
825 llvm::ConstantInt::get(llvm::Type::Int32Ty, ColNo),
828 CallInst::Create(StopPointFn, Args, Args+3, "", BB);
831 /// InsertSubprogramStart - Create a new llvm.dbg.func.start intrinsic to
832 /// mark the start of the specified subprogram.
833 void DIFactory::InsertSubprogramStart(DISubprogram SP, BasicBlock *BB) {
834 // Lazily construct llvm.dbg.func.start.
836 FuncStartFn = llvm::Intrinsic::getDeclaration(&M,
837 llvm::Intrinsic::dbg_func_start);
839 // Call llvm.dbg.func.start which also implicitly sets a stoppoint.
840 CallInst::Create(FuncStartFn, getCastToEmpty(SP), "", BB);
843 /// InsertRegionStart - Insert a new llvm.dbg.region.start intrinsic call to
844 /// mark the start of a region for the specified scoping descriptor.
845 void DIFactory::InsertRegionStart(DIDescriptor D, BasicBlock *BB) {
846 // Lazily construct llvm.dbg.region.start function.
848 RegionStartFn = llvm::Intrinsic::getDeclaration(&M,
849 llvm::Intrinsic::dbg_region_start);
850 // Call llvm.dbg.func.start.
851 CallInst::Create(RegionStartFn, getCastToEmpty(D), "", BB);
855 /// InsertRegionEnd - Insert a new llvm.dbg.region.end intrinsic call to
856 /// mark the end of a region for the specified scoping descriptor.
857 void DIFactory::InsertRegionEnd(DIDescriptor D, BasicBlock *BB) {
858 // Lazily construct llvm.dbg.region.end function.
860 RegionEndFn = llvm::Intrinsic::getDeclaration(&M,
861 llvm::Intrinsic::dbg_region_end);
863 CallInst::Create(RegionEndFn, getCastToEmpty(D), "", BB);
866 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
867 void DIFactory::InsertDeclare(llvm::Value *Storage, DIVariable D,
869 // Cast the storage to a {}* for the call to llvm.dbg.declare.
870 Storage = new llvm::BitCastInst(Storage, EmptyStructPtr, "", BB);
873 DeclareFn = llvm::Intrinsic::getDeclaration(&M,
874 llvm::Intrinsic::dbg_declare);
875 Value *Args[] = { Storage, getCastToEmpty(D) };
876 CallInst::Create(DeclareFn, Args, Args+2, "", BB);
880 /// Finds the stoppoint coressponding to this instruction, that is the
881 /// stoppoint that dominates this instruction
882 const DbgStopPointInst *findStopPoint(const Instruction *Inst)
884 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(Inst))
887 const BasicBlock *BB = Inst->getParent();
888 BasicBlock::const_iterator I = Inst, B;
891 // A BB consisting only of a terminator can't have a stoppoint.
895 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
899 // This BB didn't have a stoppoint: if there is only one
900 // predecessor, look for a stoppoint there.
901 // We could use getIDom(), but that would require dominator info.
902 BB = I->getParent()->getUniquePredecessor();
904 I = BB->getTerminator();
909 /// Finds the stoppoint corresponding to first real (non-debug intrinsic)
910 /// instruction in this Basic Block, and returns the stoppoint for it.
911 const DbgStopPointInst *findBBStopPoint(const BasicBlock *BB)
913 for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
914 if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
917 // Fallback to looking for stoppoint of unique predecessor.
918 // Useful if this BB contains no stoppoints, but unique predecessor does.
919 BB = BB->getUniquePredecessor();
921 return findStopPoint(BB->getTerminator());
925 Value *findDbgGlobalDeclare(GlobalVariable *V)
927 const Module *M = V->getParent();
928 const Type *Ty = M->getTypeByName("llvm.dbg.global_variable.type");
931 Ty = PointerType::get(Ty, 0);
933 Value *Val = V->stripPointerCasts();
934 for (Value::use_iterator I = Val->use_begin(), E =Val->use_end();
936 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I)) {
937 if (CE->getOpcode() == Instruction::BitCast) {
939 while (VV->hasOneUse()) {
940 VV = *VV->use_begin();
942 if (VV->getType() == Ty)
948 if (Val->getType() == Ty)
953 /// Finds the dbg.declare intrinsic corresponding to this value if any.
954 /// It looks through pointer casts too.
955 const DbgDeclareInst *findDbgDeclare(const Value *V, bool stripCasts)
958 V = V->stripPointerCasts();
959 // Look for the bitcast.
960 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
962 if (isa<BitCastInst>(I))
963 return findDbgDeclare(*I, false);
968 // Find dbg.declare among uses of the instruction.
969 for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
971 if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
977 bool getLocationInfo(const Value *V, std::string &DisplayName, std::string &Type,
978 unsigned &LineNo, std::string &File, std::string &Dir)
982 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
983 Value *DIGV = findDbgGlobalDeclare(GV);
986 DIGlobalVariable Var(cast<GlobalVariable>(DIGV));
987 Var.getDisplayName(DisplayName);
988 LineNo = Var.getLineNumber();
989 Unit = Var.getCompileUnit();
990 TypeD = Var.getType();
992 const DbgDeclareInst *DDI = findDbgDeclare(V);
995 DIVariable Var(cast<GlobalVariable>(DDI->getVariable()));
996 Var.getName(DisplayName);
997 LineNo = Var.getLineNumber();
998 Unit = Var.getCompileUnit();
999 TypeD = Var.getType();
1001 TypeD.getName(Type);
1002 Unit.getFilename(File);
1003 Unit.getDirectory(Dir);
1008 /// dump - print descriptor.
1009 void DIDescriptor::dump() const {
1010 cerr << "[" << dwarf::TagString(getTag()) << "] ";
1011 cerr << std::hex << "[GV:" << GV << "]" << std::dec;
1014 /// dump - print compile unit.
1015 void DICompileUnit::dump() const {
1017 cerr << " [" << dwarf::LanguageString(getLanguage()) << "] ";
1019 std::string Res1, Res2;
1020 cerr << " [" << getDirectory(Res1) << "/" << getFilename(Res2) << " ]";
1023 /// dump - print type.
1024 void DIType::dump() const {
1025 if (isNull()) return;
1028 if (!getName(Res).empty())
1029 cerr << " [" << Res << "] ";
1031 unsigned Tag = getTag();
1032 cerr << " [" << dwarf::TagString(Tag) << "] ";
1034 // TODO : Print context
1035 getCompileUnit().dump();
1037 << getLineNumber() << ", "
1038 << getSizeInBits() << ", "
1039 << getAlignInBits() << ", "
1040 << getOffsetInBits()
1044 cerr << " [private] ";
1045 else if (isProtected())
1046 cerr << " [protected] ";
1048 if (isForwardDecl())
1051 if (isBasicType(Tag))
1052 DIBasicType(GV).dump();
1053 else if (isDerivedType(Tag))
1054 DIDerivedType(GV).dump();
1055 else if (isCompositeType(Tag))
1056 DICompositeType(GV).dump();
1058 cerr << "Invalid DIType\n";
1065 /// dump - print basic type.
1066 void DIBasicType::dump() const {
1067 cerr << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
1070 /// dump - print derived type.
1071 void DIDerivedType::dump() const {
1072 cerr << "\n\t Derived From: "; getTypeDerivedFrom().dump();
1075 /// dump - print composite type.
1076 void DICompositeType::dump() const {
1077 DIArray A = getTypeArray();
1080 cerr << " [" << A.getNumElements() << " elements]";
1083 /// dump - print global.
1084 void DIGlobal::dump() const {
1086 if (!getName(Res).empty())
1087 cerr << " [" << Res << "] ";
1089 unsigned Tag = getTag();
1090 cerr << " [" << dwarf::TagString(Tag) << "] ";
1092 // TODO : Print context
1093 getCompileUnit().dump();
1094 cerr << " [" << getLineNumber() << "] ";
1096 if (isLocalToUnit())
1097 cerr << " [local] ";
1102 if (isGlobalVariable(Tag))
1103 DIGlobalVariable(GV).dump();
1108 /// dump - print subprogram.
1109 void DISubprogram::dump() const {
1113 /// dump - print subprogram.
1114 void DIInlinedSubprogram::dump() const {
1118 /// dump - print global variable.
1119 void DIGlobalVariable::dump() const {
1120 cerr << " ["; getGlobal()->dump(); cerr << "] ";
1123 /// dump - print variable.
1124 void DIVariable::dump() const {
1126 if (!getName(Res).empty())
1127 cerr << " [" << Res << "] ";
1129 getCompileUnit().dump();
1130 cerr << " [" << getLineNumber() << "] ";