1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
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 contains support for writing dwarf debug info into asm files.
12 //===----------------------------------------------------------------------===//
14 #include "DwarfDebug.h"
15 #include "llvm/Module.h"
16 #include "llvm/CodeGen/MachineModuleInfo.h"
17 #include "llvm/Support/Timer.h"
18 #include "llvm/System/Path.h"
19 #include "llvm/Target/TargetAsmInfo.h"
20 #include "llvm/Target/TargetRegisterInfo.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/Target/TargetFrameInfo.h"
26 static TimerGroup &getDwarfTimerGroup() {
27 static TimerGroup DwarfTimerGroup("Dwarf Debugging");
28 return DwarfTimerGroup;
31 //===----------------------------------------------------------------------===//
33 /// Configuration values for initial hash set sizes (log2).
35 static const unsigned InitDiesSetSize = 9; // log2(512)
36 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
37 static const unsigned InitValuesSetSize = 9; // log2(512)
41 //===----------------------------------------------------------------------===//
42 /// CompileUnit - This dwarf writer support class manages information associate
43 /// with a source file.
44 class VISIBILITY_HIDDEN CompileUnit {
45 /// ID - File identifier for source.
49 /// Die - Compile unit debug information entry.
53 /// GVToDieMap - Tracks the mapping of unit level debug informaton
54 /// variables to debug information entries.
55 std::map<GlobalVariable *, DIE *> GVToDieMap;
57 /// GVToDIEEntryMap - Tracks the mapping of unit level debug informaton
58 /// descriptors to debug information entries using a DIEEntry proxy.
59 std::map<GlobalVariable *, DIEEntry *> GVToDIEEntryMap;
61 /// Globals - A map of globally visible named entities for this unit.
63 StringMap<DIE*> Globals;
65 /// DiesSet - Used to uniquely define dies within the compile unit.
67 FoldingSet<DIE> DiesSet;
69 CompileUnit(unsigned I, DIE *D)
70 : ID(I), Die(D), GVToDieMap(),
71 GVToDIEEntryMap(), Globals(), DiesSet(InitDiesSetSize)
79 unsigned getID() const { return ID; }
80 DIE* getDie() const { return Die; }
81 StringMap<DIE*> &getGlobals() { return Globals; }
83 /// hasContent - Return true if this compile unit has something to write out.
85 bool hasContent() const {
86 return !Die->getChildren().empty();
89 /// AddGlobal - Add a new global entity to the compile unit.
91 void AddGlobal(const std::string &Name, DIE *Die) {
95 /// getDieMapSlotFor - Returns the debug information entry map slot for the
96 /// specified debug variable.
97 DIE *&getDieMapSlotFor(GlobalVariable *GV) {
98 return GVToDieMap[GV];
101 /// getDIEEntrySlotFor - Returns the debug information entry proxy slot for the
102 /// specified debug variable.
103 DIEEntry *&getDIEEntrySlotFor(GlobalVariable *GV) {
104 return GVToDIEEntryMap[GV];
107 /// AddDie - Adds or interns the DIE to the compile unit.
109 DIE *AddDie(DIE &Buffer) {
113 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
116 Die = new DIE(Buffer);
117 DiesSet.InsertNode(Die, Where);
118 this->Die->AddChild(Die);
126 //===----------------------------------------------------------------------===//
127 /// DbgVariable - This class is used to track local variable information.
129 class VISIBILITY_HIDDEN DbgVariable {
130 DIVariable Var; // Variable Descriptor.
131 unsigned FrameIndex; // Variable frame index.
133 DbgVariable(DIVariable V, unsigned I) : Var(V), FrameIndex(I) {}
136 DIVariable getVariable() const { return Var; }
137 unsigned getFrameIndex() const { return FrameIndex; }
140 //===----------------------------------------------------------------------===//
141 /// DbgScope - This class is used to track scope information.
143 class DbgConcreteScope;
144 class VISIBILITY_HIDDEN DbgScope {
145 DbgScope *Parent; // Parent to this scope.
146 DIDescriptor Desc; // Debug info descriptor for scope.
147 // Either subprogram or block.
148 unsigned StartLabelID; // Label ID of the beginning of scope.
149 unsigned EndLabelID; // Label ID of the end of scope.
150 SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope.
151 SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
152 SmallVector<DbgConcreteScope *, 8> ConcreteInsts;// Concrete insts of funcs.
154 DbgScope(DbgScope *P, DIDescriptor D)
155 : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0) {}
159 DbgScope *getParent() const { return Parent; }
160 DIDescriptor getDesc() const { return Desc; }
161 unsigned getStartLabelID() const { return StartLabelID; }
162 unsigned getEndLabelID() const { return EndLabelID; }
163 SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
164 SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
165 SmallVector<DbgConcreteScope*,8> &getConcreteInsts() { return ConcreteInsts; }
166 void setStartLabelID(unsigned S) { StartLabelID = S; }
167 void setEndLabelID(unsigned E) { EndLabelID = E; }
169 /// AddScope - Add a scope to the scope.
171 void AddScope(DbgScope *S) { Scopes.push_back(S); }
173 /// AddVariable - Add a variable to the scope.
175 void AddVariable(DbgVariable *V) { Variables.push_back(V); }
177 /// AddConcreteInst - Add a concrete instance to the scope.
179 void AddConcreteInst(DbgConcreteScope *C) { ConcreteInsts.push_back(C); }
187 void DbgScope::dump() const {
188 static unsigned IndentLevel = 0;
189 std::string Indent(IndentLevel, ' ');
191 cerr << Indent; Desc.dump();
192 cerr << " [" << StartLabelID << ", " << EndLabelID << "]\n";
196 for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
197 if (Scopes[i] != this)
204 //===----------------------------------------------------------------------===//
205 /// DbgConcreteScope - This class is used to track a scope that holds concrete
206 /// instance information.
208 class VISIBILITY_HIDDEN DbgConcreteScope : public DbgScope {
210 DIE *Die; // Debug info for this concrete scope.
212 DbgConcreteScope(DIDescriptor D) : DbgScope(NULL, D) {}
215 DIE *getDie() const { return Die; }
216 void setDie(DIE *D) { Die = D; }
219 DbgScope::~DbgScope() {
220 for (unsigned i = 0, N = Scopes.size(); i < N; ++i)
222 for (unsigned j = 0, M = Variables.size(); j < M; ++j)
224 for (unsigned k = 0, O = ConcreteInsts.size(); k < O; ++k)
225 delete ConcreteInsts[k];
228 } // end llvm namespace
230 DwarfDebug::DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
231 : Dwarf(OS, A, T, "dbg"), MainCU(0),
232 AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(),
233 ValuesSet(InitValuesSetSize), Values(), StringPool(), SectionMap(),
234 SectionSourceLines(), didInitial(false), shouldEmit(false),
235 FunctionDbgScope(0), DebugTimer(0) {
236 if (TimePassesIsEnabled)
237 DebugTimer = new Timer("Dwarf Debug Writer",
238 getDwarfTimerGroup());
240 DwarfDebug::~DwarfDebug() {
241 for (unsigned j = 0, M = Values.size(); j < M; ++j)
244 for (DenseMap<const GlobalVariable *, DbgScope *>::iterator
245 I = AbstractInstanceRootMap.begin(),
246 E = AbstractInstanceRootMap.end(); I != E;++I)
252 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
254 void DwarfDebug::AssignAbbrevNumber(DIEAbbrev &Abbrev) {
255 // Profile the node so that we can make it unique.
259 // Check the set for priors.
260 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
262 // If it's newly added.
263 if (InSet == &Abbrev) {
264 // Add to abbreviation list.
265 Abbreviations.push_back(&Abbrev);
267 // Assign the vector position + 1 as its number.
268 Abbrev.setNumber(Abbreviations.size());
270 // Assign existing abbreviation number.
271 Abbrev.setNumber(InSet->getNumber());
275 /// NewDIEEntry - Creates a new DIEEntry to be a proxy for a debug information
277 DIEEntry *DwarfDebug::NewDIEEntry(DIE *Entry) {
282 DIEEntry::Profile(ID, Entry);
284 Value = static_cast<DIEEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
286 if (Value) return Value;
288 Value = new DIEEntry(Entry);
289 ValuesSet.InsertNode(Value, Where);
291 Value = new DIEEntry(Entry);
294 Values.push_back(Value);
298 /// SetDIEEntry - Set a DIEEntry once the debug information entry is defined.
300 void DwarfDebug::SetDIEEntry(DIEEntry *Value, DIE *Entry) {
301 Value->setEntry(Entry);
303 // Add to values set if not already there. If it is, we merely have a
304 // duplicate in the values list (no harm.)
305 ValuesSet.GetOrInsertNode(Value);
308 /// AddUInt - Add an unsigned integer attribute data and value.
310 void DwarfDebug::AddUInt(DIE *Die, unsigned Attribute,
311 unsigned Form, uint64_t Integer) {
312 if (!Form) Form = DIEInteger::BestForm(false, Integer);
315 DIEInteger::Profile(ID, Integer);
317 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
320 Value = new DIEInteger(Integer);
321 ValuesSet.InsertNode(Value, Where);
322 Values.push_back(Value);
325 Die->AddValue(Attribute, Form, Value);
328 /// AddSInt - Add an signed integer attribute data and value.
330 void DwarfDebug::AddSInt(DIE *Die, unsigned Attribute,
331 unsigned Form, int64_t Integer) {
332 if (!Form) Form = DIEInteger::BestForm(true, Integer);
335 DIEInteger::Profile(ID, (uint64_t)Integer);
337 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
340 Value = new DIEInteger(Integer);
341 ValuesSet.InsertNode(Value, Where);
342 Values.push_back(Value);
345 Die->AddValue(Attribute, Form, Value);
348 /// AddString - Add a string attribute data and value.
350 void DwarfDebug::AddString(DIE *Die, unsigned Attribute, unsigned Form,
351 const std::string &String) {
353 DIEString::Profile(ID, String);
355 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
358 Value = new DIEString(String);
359 ValuesSet.InsertNode(Value, Where);
360 Values.push_back(Value);
363 Die->AddValue(Attribute, Form, Value);
366 /// AddLabel - Add a Dwarf label attribute data and value.
368 void DwarfDebug::AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
369 const DWLabel &Label) {
371 DIEDwarfLabel::Profile(ID, Label);
373 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
376 Value = new DIEDwarfLabel(Label);
377 ValuesSet.InsertNode(Value, Where);
378 Values.push_back(Value);
381 Die->AddValue(Attribute, Form, Value);
384 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
386 void DwarfDebug::AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
387 const std::string &Label) {
389 DIEObjectLabel::Profile(ID, Label);
391 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
394 Value = new DIEObjectLabel(Label);
395 ValuesSet.InsertNode(Value, Where);
396 Values.push_back(Value);
399 Die->AddValue(Attribute, Form, Value);
402 /// AddSectionOffset - Add a section offset label attribute data and value.
404 void DwarfDebug::AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
405 const DWLabel &Label, const DWLabel &Section,
406 bool isEH, bool useSet) {
408 DIESectionOffset::Profile(ID, Label, Section);
410 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
413 Value = new DIESectionOffset(Label, Section, isEH, useSet);
414 ValuesSet.InsertNode(Value, Where);
415 Values.push_back(Value);
418 Die->AddValue(Attribute, Form, Value);
421 /// AddDelta - Add a label delta attribute data and value.
423 void DwarfDebug::AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
424 const DWLabel &Hi, const DWLabel &Lo) {
426 DIEDelta::Profile(ID, Hi, Lo);
428 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
431 Value = new DIEDelta(Hi, Lo);
432 ValuesSet.InsertNode(Value, Where);
433 Values.push_back(Value);
436 Die->AddValue(Attribute, Form, Value);
439 /// AddBlock - Add block data.
441 void DwarfDebug::AddBlock(DIE *Die, unsigned Attribute, unsigned Form,
443 Block->ComputeSize(TD);
447 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
451 ValuesSet.InsertNode(Value, Where);
452 Values.push_back(Value);
454 // Already exists, reuse the previous one.
456 Block = cast<DIEBlock>(Value);
459 Die->AddValue(Attribute, Block->BestForm(), Value);
462 /// AddSourceLine - Add location information to specified debug information
464 void DwarfDebug::AddSourceLine(DIE *Die, const DIVariable *V) {
465 // If there is no compile unit specified, don't add a line #.
466 if (V->getCompileUnit().isNull())
469 unsigned Line = V->getLineNumber();
470 unsigned FileID = FindCompileUnit(V->getCompileUnit()).getID();
471 assert(FileID && "Invalid file id");
472 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
473 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
476 /// AddSourceLine - Add location information to specified debug information
478 void DwarfDebug::AddSourceLine(DIE *Die, const DIGlobal *G) {
479 // If there is no compile unit specified, don't add a line #.
480 if (G->getCompileUnit().isNull())
483 unsigned Line = G->getLineNumber();
484 unsigned FileID = FindCompileUnit(G->getCompileUnit()).getID();
485 assert(FileID && "Invalid file id");
486 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
487 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
489 void DwarfDebug::AddSourceLine(DIE *Die, const DIType *Ty) {
490 // If there is no compile unit specified, don't add a line #.
491 DICompileUnit CU = Ty->getCompileUnit();
495 unsigned Line = Ty->getLineNumber();
496 unsigned FileID = FindCompileUnit(CU).getID();
497 assert(FileID && "Invalid file id");
498 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
499 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
502 /// AddAddress - Add an address attribute to a die based on the location
504 void DwarfDebug::AddAddress(DIE *Die, unsigned Attribute,
505 const MachineLocation &Location) {
506 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
507 DIEBlock *Block = new DIEBlock();
509 if (Location.isReg()) {
511 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
513 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
514 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
518 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
520 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
521 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
524 AddUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
527 AddBlock(Die, Attribute, 0, Block);
530 /// AddType - Add a new type attribute to the specified entity.
531 void DwarfDebug::AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
535 // Check for pre-existence.
536 DIEEntry *&Slot = DW_Unit->getDIEEntrySlotFor(Ty.getGV());
538 // If it exists then use the existing value.
540 Entity->AddValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Slot);
545 Slot = NewDIEEntry();
548 DIE Buffer(dwarf::DW_TAG_base_type);
549 if (Ty.isBasicType(Ty.getTag()))
550 ConstructTypeDIE(DW_Unit, Buffer, DIBasicType(Ty.getGV()));
551 else if (Ty.isDerivedType(Ty.getTag()))
552 ConstructTypeDIE(DW_Unit, Buffer, DIDerivedType(Ty.getGV()));
554 assert(Ty.isCompositeType(Ty.getTag()) && "Unknown kind of DIType");
555 ConstructTypeDIE(DW_Unit, Buffer, DICompositeType(Ty.getGV()));
558 // Add debug information entry to entity and appropriate context.
560 DIDescriptor Context = Ty.getContext();
561 if (!Context.isNull())
562 Die = DW_Unit->getDieMapSlotFor(Context.getGV());
565 DIE *Child = new DIE(Buffer);
566 Die->AddChild(Child);
568 SetDIEEntry(Slot, Child);
570 Die = DW_Unit->AddDie(Buffer);
571 SetDIEEntry(Slot, Die);
574 Entity->AddValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Slot);
577 /// ConstructTypeDIE - Construct basic type die from DIBasicType.
578 void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
580 // Get core information.
583 Buffer.setTag(dwarf::DW_TAG_base_type);
584 AddUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
587 // Add name if not anonymous or intermediate type.
589 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
590 uint64_t Size = BTy.getSizeInBits() >> 3;
591 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
594 /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
595 void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
597 // Get core information.
600 uint64_t Size = DTy.getSizeInBits() >> 3;
601 unsigned Tag = DTy.getTag();
603 // FIXME - Workaround for templates.
604 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
608 // Map to main type, void will not have a type.
609 DIType FromTy = DTy.getTypeDerivedFrom();
610 AddType(DW_Unit, &Buffer, FromTy);
612 // Add name if not anonymous or intermediate type.
614 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
616 // Add size if non-zero (derived types might be zero-sized.)
618 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
620 // Add source line info if available and TyDesc is not a forward declaration.
621 if (!DTy.isForwardDecl())
622 AddSourceLine(&Buffer, &DTy);
625 /// ConstructTypeDIE - Construct type DIE from DICompositeType.
626 void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
627 DICompositeType CTy) {
628 // Get core information.
632 uint64_t Size = CTy.getSizeInBits() >> 3;
633 unsigned Tag = CTy.getTag();
637 case dwarf::DW_TAG_vector_type:
638 case dwarf::DW_TAG_array_type:
639 ConstructArrayTypeDIE(DW_Unit, Buffer, &CTy);
641 case dwarf::DW_TAG_enumeration_type: {
642 DIArray Elements = CTy.getTypeArray();
644 // Add enumerators to enumeration type.
645 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
647 DIEnumerator Enum(Elements.getElement(i).getGV());
648 ElemDie = ConstructEnumTypeDIE(DW_Unit, &Enum);
649 Buffer.AddChild(ElemDie);
653 case dwarf::DW_TAG_subroutine_type: {
655 DIArray Elements = CTy.getTypeArray();
656 DIDescriptor RTy = Elements.getElement(0);
657 AddType(DW_Unit, &Buffer, DIType(RTy.getGV()));
659 // Add prototype flag.
660 AddUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
663 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
664 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
665 DIDescriptor Ty = Elements.getElement(i);
666 AddType(DW_Unit, Arg, DIType(Ty.getGV()));
667 Buffer.AddChild(Arg);
671 case dwarf::DW_TAG_structure_type:
672 case dwarf::DW_TAG_union_type:
673 case dwarf::DW_TAG_class_type: {
674 // Add elements to structure type.
675 DIArray Elements = CTy.getTypeArray();
677 // A forward struct declared type may not have elements available.
678 if (Elements.isNull())
681 // Add elements to structure type.
682 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
683 DIDescriptor Element = Elements.getElement(i);
685 if (Element.getTag() == dwarf::DW_TAG_subprogram)
686 ElemDie = CreateSubprogramDIE(DW_Unit,
687 DISubprogram(Element.getGV()));
688 else if (Element.getTag() == dwarf::DW_TAG_variable) // ??
689 ElemDie = CreateGlobalVariableDIE(DW_Unit,
690 DIGlobalVariable(Element.getGV()));
692 ElemDie = CreateMemberDIE(DW_Unit,
693 DIDerivedType(Element.getGV()));
694 Buffer.AddChild(ElemDie);
697 // FIXME: We'd like an API to register additional attributes for the
698 // frontend to use while synthesizing, and then we'd use that api in clang
700 if (Name == "__block_literal_generic")
701 AddUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
703 unsigned RLang = CTy.getRunTimeLang();
705 AddUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
706 dwarf::DW_FORM_data1, RLang);
713 // Add name if not anonymous or intermediate type.
715 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
717 if (Tag == dwarf::DW_TAG_enumeration_type ||
718 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
719 // Add size if non-zero (derived types might be zero-sized.)
721 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
723 // Add zero size if it is not a forward declaration.
724 if (CTy.isForwardDecl())
725 AddUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
727 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
730 // Add source line info if available.
731 if (!CTy.isForwardDecl())
732 AddSourceLine(&Buffer, &CTy);
736 /// ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
737 void DwarfDebug::ConstructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
738 int64_t L = SR.getLo();
739 int64_t H = SR.getHi();
740 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
743 AddDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
745 AddSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
746 AddSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
749 Buffer.AddChild(DW_Subrange);
752 /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
753 void DwarfDebug::ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
754 DICompositeType *CTy) {
755 Buffer.setTag(dwarf::DW_TAG_array_type);
756 if (CTy->getTag() == dwarf::DW_TAG_vector_type)
757 AddUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
759 // Emit derived type.
760 AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
761 DIArray Elements = CTy->getTypeArray();
763 // Construct an anonymous type for index type.
764 DIE IdxBuffer(dwarf::DW_TAG_base_type);
765 AddUInt(&IdxBuffer, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
766 AddUInt(&IdxBuffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
767 dwarf::DW_ATE_signed);
768 DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
770 // Add subranges to array type.
771 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
772 DIDescriptor Element = Elements.getElement(i);
773 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
774 ConstructSubrangeDIE(Buffer, DISubrange(Element.getGV()), IndexTy);
778 /// ConstructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
779 DIE *DwarfDebug::ConstructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) {
780 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
783 AddString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
784 int64_t Value = ETy->getEnumValue();
785 AddSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
789 /// CreateGlobalVariableDIE - Create new DIE using GV.
790 DIE *DwarfDebug::CreateGlobalVariableDIE(CompileUnit *DW_Unit,
791 const DIGlobalVariable &GV) {
792 DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
794 GV.getDisplayName(Name);
795 AddString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
796 std::string LinkageName;
797 GV.getLinkageName(LinkageName);
798 if (!LinkageName.empty())
799 AddString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
801 AddType(DW_Unit, GVDie, GV.getType());
802 if (!GV.isLocalToUnit())
803 AddUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
804 AddSourceLine(GVDie, &GV);
808 /// CreateMemberDIE - Create new member DIE.
809 DIE *DwarfDebug::CreateMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT){
810 DIE *MemberDie = new DIE(DT.getTag());
814 AddString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
816 AddType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
818 AddSourceLine(MemberDie, &DT);
820 uint64_t Size = DT.getSizeInBits();
821 uint64_t FieldSize = DT.getOriginalTypeSize();
823 if (Size != FieldSize) {
825 AddUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
826 AddUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
828 uint64_t Offset = DT.getOffsetInBits();
829 uint64_t FieldOffset = Offset;
830 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
831 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
832 FieldOffset = (HiMark - FieldSize);
833 Offset -= FieldOffset;
835 // Maybe we need to work from the other end.
836 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
837 AddUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
840 DIEBlock *Block = new DIEBlock();
841 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
842 AddUInt(Block, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
843 AddBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, Block);
845 if (DT.isProtected())
846 AddUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
847 dwarf::DW_ACCESS_protected);
848 else if (DT.isPrivate())
849 AddUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
850 dwarf::DW_ACCESS_private);
855 /// CreateSubprogramDIE - Create new DIE using SP.
856 DIE *DwarfDebug::CreateSubprogramDIE(CompileUnit *DW_Unit,
857 const DISubprogram &SP,
860 DIE *SPDie = new DIE(dwarf::DW_TAG_subprogram);
864 AddString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
866 std::string LinkageName;
867 SP.getLinkageName(LinkageName);
869 if (!LinkageName.empty())
870 AddString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
873 AddSourceLine(SPDie, &SP);
875 DICompositeType SPTy = SP.getType();
876 DIArray Args = SPTy.getTypeArray();
878 // Add prototyped tag, if C or ObjC.
879 unsigned Lang = SP.getCompileUnit().getLanguage();
880 if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
881 Lang == dwarf::DW_LANG_ObjC)
882 AddUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
885 unsigned SPTag = SPTy.getTag();
886 if (!IsConstructor) {
887 if (Args.isNull() || SPTag != dwarf::DW_TAG_subroutine_type)
888 AddType(DW_Unit, SPDie, SPTy);
890 AddType(DW_Unit, SPDie, DIType(Args.getElement(0).getGV()));
893 if (!SP.isDefinition()) {
894 AddUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
896 // Add arguments. Do not add arguments for subprogram definition. They will
897 // be handled through RecordVariable.
898 if (SPTag == dwarf::DW_TAG_subroutine_type)
899 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
900 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
901 AddType(DW_Unit, Arg, DIType(Args.getElement(i).getGV()));
902 AddUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1); // ??
903 SPDie->AddChild(Arg);
907 if (!SP.isLocalToUnit() && !IsInlined)
908 AddUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
910 // DW_TAG_inlined_subroutine may refer to this DIE.
911 DIE *&Slot = DW_Unit->getDieMapSlotFor(SP.getGV());
916 /// FindCompileUnit - Get the compile unit for the given descriptor.
918 CompileUnit &DwarfDebug::FindCompileUnit(DICompileUnit Unit) const {
919 DenseMap<Value *, CompileUnit *>::const_iterator I =
920 CompileUnitMap.find(Unit.getGV());
921 assert(I != CompileUnitMap.end() && "Missing compile unit.");
925 /// NewDbgScopeVariable - Create a new scope variable.
927 DIE *DwarfDebug::NewDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
928 // Get the descriptor.
929 const DIVariable &VD = DV->getVariable();
931 // Translate tag to proper Dwarf tag. The result variable is dropped for
934 switch (VD.getTag()) {
935 case dwarf::DW_TAG_return_variable:
937 case dwarf::DW_TAG_arg_variable:
938 Tag = dwarf::DW_TAG_formal_parameter;
940 case dwarf::DW_TAG_auto_variable: // fall thru
942 Tag = dwarf::DW_TAG_variable;
946 // Define variable debug information entry.
947 DIE *VariableDie = new DIE(Tag);
950 AddString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
952 // Add source line info if available.
953 AddSourceLine(VariableDie, &VD);
955 // Add variable type.
956 AddType(Unit, VariableDie, VD.getType());
958 // Add variable address.
959 MachineLocation Location;
960 Location.set(RI->getFrameRegister(*MF),
961 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
962 AddAddress(VariableDie, dwarf::DW_AT_location, Location);
967 /// getOrCreateScope - Returns the scope associated with the given descriptor.
969 DbgScope *DwarfDebug::getOrCreateScope(GlobalVariable *V) {
970 DbgScope *&Slot = DbgScopeMap[V];
971 if (Slot) return Slot;
973 DbgScope *Parent = NULL;
976 // Don't create a new scope if we already created one for an inlined function.
977 DenseMap<const GlobalVariable *, DbgScope *>::iterator
978 II = AbstractInstanceRootMap.find(V);
979 if (II != AbstractInstanceRootMap.end())
980 return LexicalScopeStack.back();
982 if (!Block.isNull()) {
983 DIDescriptor ParentDesc = Block.getContext();
985 ParentDesc.isNull() ? NULL : getOrCreateScope(ParentDesc.getGV());
988 Slot = new DbgScope(Parent, DIDescriptor(V));
991 Parent->AddScope(Slot);
993 // First function is top level function.
994 FunctionDbgScope = Slot;
999 /// ConstructDbgScope - Construct the components of a scope.
1001 void DwarfDebug::ConstructDbgScope(DbgScope *ParentScope,
1002 unsigned ParentStartID,
1003 unsigned ParentEndID,
1004 DIE *ParentDie, CompileUnit *Unit) {
1005 // Add variables to scope.
1006 SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
1007 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1008 DIE *VariableDie = NewDbgScopeVariable(Variables[i], Unit);
1009 if (VariableDie) ParentDie->AddChild(VariableDie);
1012 // Add concrete instances to scope.
1013 SmallVector<DbgConcreteScope *, 8> &ConcreteInsts =
1014 ParentScope->getConcreteInsts();
1015 for (unsigned i = 0, N = ConcreteInsts.size(); i < N; ++i) {
1016 DbgConcreteScope *ConcreteInst = ConcreteInsts[i];
1017 DIE *Die = ConcreteInst->getDie();
1019 unsigned StartID = ConcreteInst->getStartLabelID();
1020 unsigned EndID = ConcreteInst->getEndLabelID();
1022 // Add the scope bounds.
1024 AddLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1025 DWLabel("label", StartID));
1027 AddLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1028 DWLabel("func_begin", SubprogramCount));
1031 AddLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1032 DWLabel("label", EndID));
1034 AddLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1035 DWLabel("func_end", SubprogramCount));
1037 ParentDie->AddChild(Die);
1040 // Add nested scopes.
1041 SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
1042 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1043 // Define the Scope debug information entry.
1044 DbgScope *Scope = Scopes[j];
1046 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1047 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1049 // Ignore empty scopes.
1050 if (StartID == EndID && StartID != 0) continue;
1052 // Do not ignore inlined scopes even if they don't have any variables or
1054 if (Scope->getScopes().empty() && Scope->getVariables().empty() &&
1055 Scope->getConcreteInsts().empty())
1058 if (StartID == ParentStartID && EndID == ParentEndID) {
1059 // Just add stuff to the parent scope.
1060 ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
1062 DIE *ScopeDie = new DIE(dwarf::DW_TAG_lexical_block);
1064 // Add the scope bounds.
1066 AddLabel(ScopeDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1067 DWLabel("label", StartID));
1069 AddLabel(ScopeDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1070 DWLabel("func_begin", SubprogramCount));
1073 AddLabel(ScopeDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1074 DWLabel("label", EndID));
1076 AddLabel(ScopeDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1077 DWLabel("func_end", SubprogramCount));
1079 // Add the scope's contents.
1080 ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
1081 ParentDie->AddChild(ScopeDie);
1086 /// ConstructFunctionDbgScope - Construct the scope for the subprogram.
1088 void DwarfDebug::ConstructFunctionDbgScope(DbgScope *RootScope) {
1089 // Exit if there is no root scope.
1090 if (!RootScope) return;
1091 DIDescriptor Desc = RootScope->getDesc();
1095 // Get the subprogram debug information entry.
1096 DISubprogram SPD(Desc.getGV());
1098 // Get the compile unit context.
1099 CompileUnit *Unit = MainCU;
1101 Unit = &FindCompileUnit(SPD.getCompileUnit());
1103 // Get the subprogram die.
1104 DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
1105 assert(SPDie && "Missing subprogram descriptor");
1107 // Add the function bounds.
1108 AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1109 DWLabel("func_begin", SubprogramCount));
1110 AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1111 DWLabel("func_end", SubprogramCount));
1112 MachineLocation Location(RI->getFrameRegister(*MF));
1113 AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1115 ConstructDbgScope(RootScope, 0, 0, SPDie, Unit);
1118 /// ConstructFunctionDbgScope - Construct the scope for the abstract debug
1121 void DwarfDebug::ConstructAbstractDbgScope(DbgScope *AbsScope) {
1122 // Exit if there is no root scope.
1123 if (!AbsScope) return;
1125 DIDescriptor Desc = AbsScope->getDesc();
1129 // Get the subprogram debug information entry.
1130 DISubprogram SPD(Desc.getGV());
1132 // Get the compile unit context.
1133 CompileUnit *Unit = MainCU;
1135 Unit = &FindCompileUnit(SPD.getCompileUnit());
1137 // Get the subprogram die.
1138 DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
1139 assert(SPDie && "Missing subprogram descriptor");
1141 ConstructDbgScope(AbsScope, 0, 0, SPDie, Unit);
1144 /// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
1146 void DwarfDebug::ConstructDefaultDbgScope(MachineFunction *MF) {
1147 const char *FnName = MF->getFunction()->getNameStart();
1149 StringMap<DIE*> &Globals = MainCU->getGlobals();
1150 StringMap<DIE*>::iterator GI = Globals.find(FnName);
1151 if (GI != Globals.end()) {
1152 DIE *SPDie = GI->second;
1154 // Add the function bounds.
1155 AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1156 DWLabel("func_begin", SubprogramCount));
1157 AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1158 DWLabel("func_end", SubprogramCount));
1160 MachineLocation Location(RI->getFrameRegister(*MF));
1161 AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1165 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
1166 CompileUnit *Unit = CompileUnits[i];
1167 StringMap<DIE*> &Globals = Unit->getGlobals();
1168 StringMap<DIE*>::iterator GI = Globals.find(FnName);
1169 if (GI != Globals.end()) {
1170 DIE *SPDie = GI->second;
1172 // Add the function bounds.
1173 AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1174 DWLabel("func_begin", SubprogramCount));
1175 AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1176 DWLabel("func_end", SubprogramCount));
1178 MachineLocation Location(RI->getFrameRegister(*MF));
1179 AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1186 // FIXME: This is causing an abort because C++ mangled names are compared with
1187 // their unmangled counterparts. See PR2885. Don't do this assert.
1188 assert(0 && "Couldn't find DIE for machine function!");
1192 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
1193 /// tools to recognize the object file contains Dwarf information.
1194 void DwarfDebug::EmitInitial() {
1195 // Check to see if we already emitted intial headers.
1196 if (didInitial) return;
1199 // Dwarf sections base addresses.
1200 if (TAI->doesDwarfRequireFrameSection()) {
1201 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1202 EmitLabel("section_debug_frame", 0);
1205 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
1206 EmitLabel("section_info", 0);
1207 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
1208 EmitLabel("section_abbrev", 0);
1209 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
1210 EmitLabel("section_aranges", 0);
1212 if (TAI->doesSupportMacInfoSection()) {
1213 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
1214 EmitLabel("section_macinfo", 0);
1217 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
1218 EmitLabel("section_line", 0);
1219 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
1220 EmitLabel("section_loc", 0);
1221 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
1222 EmitLabel("section_pubnames", 0);
1223 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
1224 EmitLabel("section_str", 0);
1225 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
1226 EmitLabel("section_ranges", 0);
1228 Asm->SwitchToSection(TAI->getTextSection());
1229 EmitLabel("text_begin", 0);
1230 Asm->SwitchToSection(TAI->getDataSection());
1231 EmitLabel("data_begin", 0);
1234 /// EmitDIE - Recusively Emits a debug information entry.
1236 void DwarfDebug::EmitDIE(DIE *Die) {
1237 // Get the abbreviation for this DIE.
1238 unsigned AbbrevNumber = Die->getAbbrevNumber();
1239 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1243 // Emit the code (index) for the abbreviation.
1244 Asm->EmitULEB128Bytes(AbbrevNumber);
1246 if (Asm->isVerbose())
1247 Asm->EOL(std::string("Abbrev [" +
1248 utostr(AbbrevNumber) +
1249 "] 0x" + utohexstr(Die->getOffset()) +
1250 ":0x" + utohexstr(Die->getSize()) + " " +
1251 dwarf::TagString(Abbrev->getTag())));
1255 SmallVector<DIEValue*, 32> &Values = Die->getValues();
1256 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1258 // Emit the DIE attribute values.
1259 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1260 unsigned Attr = AbbrevData[i].getAttribute();
1261 unsigned Form = AbbrevData[i].getForm();
1262 assert(Form && "Too many attributes for DIE (check abbreviation)");
1265 case dwarf::DW_AT_sibling:
1266 Asm->EmitInt32(Die->SiblingOffset());
1268 case dwarf::DW_AT_abstract_origin: {
1269 DIEEntry *E = cast<DIEEntry>(Values[i]);
1270 DIE *Origin = E->getEntry();
1272 CompileUnitOffsets[Die->getAbstractCompileUnit()] +
1273 Origin->getOffset();
1275 Asm->EmitInt32(Addr);
1279 // Emit an attribute using the defined form.
1280 Values[i]->EmitValue(this, Form);
1284 Asm->EOL(dwarf::AttributeString(Attr));
1287 // Emit the DIE children if any.
1288 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1289 const std::vector<DIE *> &Children = Die->getChildren();
1291 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1292 EmitDIE(Children[j]);
1294 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
1298 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
1300 unsigned DwarfDebug::SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
1301 // Get the children.
1302 const std::vector<DIE *> &Children = Die->getChildren();
1304 // If not last sibling and has children then add sibling offset attribute.
1305 if (!Last && !Children.empty()) Die->AddSiblingOffset();
1307 // Record the abbreviation.
1308 AssignAbbrevNumber(Die->getAbbrev());
1310 // Get the abbreviation for this DIE.
1311 unsigned AbbrevNumber = Die->getAbbrevNumber();
1312 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1315 Die->setOffset(Offset);
1317 // Start the size with the size of abbreviation code.
1318 Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
1320 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1321 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1323 // Size the DIE attribute values.
1324 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1325 // Size attribute value.
1326 Offset += Values[i]->SizeOf(TD, AbbrevData[i].getForm());
1328 // Size the DIE children if any.
1329 if (!Children.empty()) {
1330 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1331 "Children flag not set");
1333 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1334 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
1336 // End of children marker.
1337 Offset += sizeof(int8_t);
1340 Die->setSize(Offset - Die->getOffset());
1344 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
1346 void DwarfDebug::SizeAndOffsets() {
1347 // Compute size of compile unit header.
1348 static unsigned Offset =
1349 sizeof(int32_t) + // Length of Compilation Unit Info
1350 sizeof(int16_t) + // DWARF version number
1351 sizeof(int32_t) + // Offset Into Abbrev. Section
1352 sizeof(int8_t); // Pointer Size (in bytes)
1354 // Process base compile unit.
1356 SizeAndOffsetDie(MainCU->getDie(), Offset, true);
1357 CompileUnitOffsets[MainCU] = 0;
1361 // Process all compile units.
1362 unsigned PrevOffset = 0;
1364 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
1365 CompileUnit *Unit = CompileUnits[i];
1366 CompileUnitOffsets[Unit] = PrevOffset;
1367 PrevOffset += SizeAndOffsetDie(Unit->getDie(), Offset, true)
1368 + sizeof(int32_t); // FIXME - extra pad for gdb bug.
1372 /// EmitDebugInfo / EmitDebugInfoPerCU - Emit the debug info section.
1374 void DwarfDebug::EmitDebugInfoPerCU(CompileUnit *Unit) {
1375 DIE *Die = Unit->getDie();
1377 // Emit the compile units header.
1378 EmitLabel("info_begin", Unit->getID());
1380 // Emit size of content not including length itself
1381 unsigned ContentSize = Die->getSize() +
1382 sizeof(int16_t) + // DWARF version number
1383 sizeof(int32_t) + // Offset Into Abbrev. Section
1384 sizeof(int8_t) + // Pointer Size (in bytes)
1385 sizeof(int32_t); // FIXME - extra pad for gdb bug.
1387 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
1388 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
1389 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
1390 Asm->EOL("Offset Into Abbrev. Section");
1391 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
1394 // FIXME - extra padding for gdb bug.
1395 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1396 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1397 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1398 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1399 EmitLabel("info_end", Unit->getID());
1404 void DwarfDebug::EmitDebugInfo() {
1405 // Start debug info section.
1406 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
1409 EmitDebugInfoPerCU(MainCU);
1413 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
1414 EmitDebugInfoPerCU(CompileUnits[i]);
1417 /// EmitAbbreviations - Emit the abbreviation section.
1419 void DwarfDebug::EmitAbbreviations() const {
1420 // Check to see if it is worth the effort.
1421 if (!Abbreviations.empty()) {
1422 // Start the debug abbrev section.
1423 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
1425 EmitLabel("abbrev_begin", 0);
1427 // For each abbrevation.
1428 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
1429 // Get abbreviation data
1430 const DIEAbbrev *Abbrev = Abbreviations[i];
1432 // Emit the abbrevations code (base 1 index.)
1433 Asm->EmitULEB128Bytes(Abbrev->getNumber());
1434 Asm->EOL("Abbreviation Code");
1436 // Emit the abbreviations data.
1442 // Mark end of abbreviations.
1443 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
1445 EmitLabel("abbrev_end", 0);
1450 /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
1451 /// the line matrix.
1453 void DwarfDebug::EmitEndOfLineMatrix(unsigned SectionEnd) {
1454 // Define last address of section.
1455 Asm->EmitInt8(0); Asm->EOL("Extended Op");
1456 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
1457 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
1458 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
1460 // Mark end of matrix.
1461 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
1462 Asm->EmitULEB128Bytes(1); Asm->EOL();
1463 Asm->EmitInt8(1); Asm->EOL();
1466 /// EmitDebugLines - Emit source line information.
1468 void DwarfDebug::EmitDebugLines() {
1469 // If the target is using .loc/.file, the assembler will be emitting the
1470 // .debug_line table automatically.
1471 if (TAI->hasDotLocAndDotFile())
1474 // Minimum line delta, thus ranging from -10..(255-10).
1475 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
1476 // Maximum line delta, thus ranging from -10..(255-10).
1477 const int MaxLineDelta = 255 + MinLineDelta;
1479 // Start the dwarf line section.
1480 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
1482 // Construct the section header.
1483 EmitDifference("line_end", 0, "line_begin", 0, true);
1484 Asm->EOL("Length of Source Line Info");
1485 EmitLabel("line_begin", 0);
1487 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
1489 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
1490 Asm->EOL("Prolog Length");
1491 EmitLabel("line_prolog_begin", 0);
1493 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
1495 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
1497 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
1499 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
1501 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
1503 // Line number standard opcode encodings argument count
1504 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
1505 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
1506 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
1507 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
1508 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
1509 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
1510 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
1511 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
1512 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
1514 // Emit directories.
1515 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
1516 Asm->EmitString(getSourceDirectoryName(DI));
1517 Asm->EOL("Directory");
1520 Asm->EmitInt8(0); Asm->EOL("End of directories");
1523 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
1524 // Remember source id starts at 1.
1525 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
1526 Asm->EmitString(getSourceFileName(Id.second));
1528 Asm->EmitULEB128Bytes(Id.first);
1529 Asm->EOL("Directory #");
1530 Asm->EmitULEB128Bytes(0);
1531 Asm->EOL("Mod date");
1532 Asm->EmitULEB128Bytes(0);
1533 Asm->EOL("File size");
1536 Asm->EmitInt8(0); Asm->EOL("End of files");
1538 EmitLabel("line_prolog_end", 0);
1540 // A sequence for each text section.
1541 unsigned SecSrcLinesSize = SectionSourceLines.size();
1543 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
1544 // Isolate current sections line info.
1545 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
1547 if (Asm->isVerbose()) {
1548 const Section* S = SectionMap[j + 1];
1549 O << '\t' << TAI->getCommentString() << " Section"
1550 << S->getName() << '\n';
1555 // Dwarf assumes we start with first line of first source file.
1556 unsigned Source = 1;
1559 // Construct rows of the address, source, line, column matrix.
1560 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
1561 const SrcLineInfo &LineInfo = LineInfos[i];
1562 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
1563 if (!LabelID) continue;
1565 if (!Asm->isVerbose())
1568 std::pair<unsigned, unsigned> SourceID =
1569 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
1570 O << '\t' << TAI->getCommentString() << ' '
1571 << getSourceDirectoryName(SourceID.first) << ' '
1572 << getSourceFileName(SourceID.second)
1573 <<" :" << utostr_32(LineInfo.getLine()) << '\n';
1576 // Define the line address.
1577 Asm->EmitInt8(0); Asm->EOL("Extended Op");
1578 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
1579 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
1580 EmitReference("label", LabelID); Asm->EOL("Location label");
1582 // If change of source, then switch to the new source.
1583 if (Source != LineInfo.getSourceID()) {
1584 Source = LineInfo.getSourceID();
1585 Asm->EmitInt8(dwarf::DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
1586 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
1589 // If change of line.
1590 if (Line != LineInfo.getLine()) {
1591 // Determine offset.
1592 int Offset = LineInfo.getLine() - Line;
1593 int Delta = Offset - MinLineDelta;
1596 Line = LineInfo.getLine();
1598 // If delta is small enough and in range...
1599 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
1600 // ... then use fast opcode.
1601 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
1603 // ... otherwise use long hand.
1604 Asm->EmitInt8(dwarf::DW_LNS_advance_line);
1605 Asm->EOL("DW_LNS_advance_line");
1606 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
1607 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
1610 // Copy the previous row (different address or source)
1611 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
1615 EmitEndOfLineMatrix(j + 1);
1618 if (SecSrcLinesSize == 0)
1619 // Because we're emitting a debug_line section, we still need a line
1620 // table. The linker and friends expect it to exist. If there's nothing to
1621 // put into it, emit an empty table.
1622 EmitEndOfLineMatrix(1);
1624 EmitLabel("line_end", 0);
1628 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
1630 void DwarfDebug::EmitCommonDebugFrame() {
1631 if (!TAI->doesDwarfRequireFrameSection())
1635 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
1636 TargetFrameInfo::StackGrowsUp ?
1637 TD->getPointerSize() : -TD->getPointerSize();
1639 // Start the dwarf frame section.
1640 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1642 EmitLabel("debug_frame_common", 0);
1643 EmitDifference("debug_frame_common_end", 0,
1644 "debug_frame_common_begin", 0, true);
1645 Asm->EOL("Length of Common Information Entry");
1647 EmitLabel("debug_frame_common_begin", 0);
1648 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
1649 Asm->EOL("CIE Identifier Tag");
1650 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
1651 Asm->EOL("CIE Version");
1652 Asm->EmitString("");
1653 Asm->EOL("CIE Augmentation");
1654 Asm->EmitULEB128Bytes(1);
1655 Asm->EOL("CIE Code Alignment Factor");
1656 Asm->EmitSLEB128Bytes(stackGrowth);
1657 Asm->EOL("CIE Data Alignment Factor");
1658 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
1659 Asm->EOL("CIE RA Column");
1661 std::vector<MachineMove> Moves;
1662 RI->getInitialFrameState(Moves);
1664 EmitFrameMoves(NULL, 0, Moves, false);
1666 Asm->EmitAlignment(2, 0, 0, false);
1667 EmitLabel("debug_frame_common_end", 0);
1672 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
1675 DwarfDebug::EmitFunctionDebugFrame(const FunctionDebugFrameInfo&DebugFrameInfo){
1676 if (!TAI->doesDwarfRequireFrameSection())
1679 // Start the dwarf frame section.
1680 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1682 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
1683 "debug_frame_begin", DebugFrameInfo.Number, true);
1684 Asm->EOL("Length of Frame Information Entry");
1686 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
1688 EmitSectionOffset("debug_frame_common", "section_debug_frame",
1690 Asm->EOL("FDE CIE offset");
1692 EmitReference("func_begin", DebugFrameInfo.Number);
1693 Asm->EOL("FDE initial location");
1694 EmitDifference("func_end", DebugFrameInfo.Number,
1695 "func_begin", DebugFrameInfo.Number);
1696 Asm->EOL("FDE address range");
1698 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
1701 Asm->EmitAlignment(2, 0, 0, false);
1702 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
1707 void DwarfDebug::EmitDebugPubNamesPerCU(CompileUnit *Unit) {
1708 EmitDifference("pubnames_end", Unit->getID(),
1709 "pubnames_begin", Unit->getID(), true);
1710 Asm->EOL("Length of Public Names Info");
1712 EmitLabel("pubnames_begin", Unit->getID());
1714 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF Version");
1716 EmitSectionOffset("info_begin", "section_info",
1717 Unit->getID(), 0, true, false);
1718 Asm->EOL("Offset of Compilation Unit Info");
1720 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
1722 Asm->EOL("Compilation Unit Length");
1724 StringMap<DIE*> &Globals = Unit->getGlobals();
1725 for (StringMap<DIE*>::const_iterator
1726 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1727 const char *Name = GI->getKeyData();
1728 DIE * Entity = GI->second;
1730 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
1731 Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
1734 Asm->EmitInt32(0); Asm->EOL("End Mark");
1735 EmitLabel("pubnames_end", Unit->getID());
1740 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
1742 void DwarfDebug::EmitDebugPubNames() {
1743 // Start the dwarf pubnames section.
1744 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
1747 EmitDebugPubNamesPerCU(MainCU);
1751 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
1752 EmitDebugPubNamesPerCU(CompileUnits[i]);
1755 /// EmitDebugStr - Emit visible names into a debug str section.
1757 void DwarfDebug::EmitDebugStr() {
1758 // Check to see if it is worth the effort.
1759 if (!StringPool.empty()) {
1760 // Start the dwarf str section.
1761 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
1763 // For each of strings in the string pool.
1764 for (unsigned StringID = 1, N = StringPool.size();
1765 StringID <= N; ++StringID) {
1766 // Emit a label for reference from debug information entries.
1767 EmitLabel("string", StringID);
1769 // Emit the string itself.
1770 const std::string &String = StringPool[StringID];
1771 Asm->EmitString(String); Asm->EOL();
1778 /// EmitDebugLoc - Emit visible names into a debug loc section.
1780 void DwarfDebug::EmitDebugLoc() {
1781 // Start the dwarf loc section.
1782 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
1786 /// EmitDebugARanges - Emit visible names into a debug aranges section.
1788 void DwarfDebug::EmitDebugARanges() {
1789 // Start the dwarf aranges section.
1790 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
1794 CompileUnit *Unit = GetBaseCompileUnit();
1796 // Don't include size of length
1797 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
1799 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
1801 EmitReference("info_begin", Unit->getID());
1802 Asm->EOL("Offset of Compilation Unit Info");
1804 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
1806 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
1808 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
1809 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
1812 EmitReference("text_begin", 0); Asm->EOL("Address");
1813 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
1815 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
1816 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
1822 /// EmitDebugRanges - Emit visible names into a debug ranges section.
1824 void DwarfDebug::EmitDebugRanges() {
1825 // Start the dwarf ranges section.
1826 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
1830 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
1832 void DwarfDebug::EmitDebugMacInfo() {
1833 if (TAI->doesSupportMacInfoSection()) {
1834 // Start the dwarf macinfo section.
1835 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
1840 /// EmitDebugInlineInfo - Emit inline info using following format.
1842 /// 1. length of section
1843 /// 2. Dwarf version number
1844 /// 3. address size.
1846 /// Entries (one "entry" for each function that was inlined):
1848 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
1849 /// otherwise offset into __debug_str for regular function name.
1850 /// 2. offset into __debug_str section for regular function name.
1851 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
1852 /// instances for the function.
1854 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
1855 /// inlined instance; the die_offset points to the inlined_subroutine die in the
1856 /// __debug_info section, and the low_pc is the starting address for the
1857 /// inlining instance.
1858 void DwarfDebug::EmitDebugInlineInfo() {
1859 if (!TAI->doesDwarfUsesInlineInfoSection())
1865 Asm->SwitchToDataSection(TAI->getDwarfDebugInlineSection());
1867 EmitDifference("debug_inlined_end", 1,
1868 "debug_inlined_begin", 1, true);
1869 Asm->EOL("Length of Debug Inlined Information Entry");
1871 EmitLabel("debug_inlined_begin", 1);
1873 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
1874 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
1876 for (DenseMap<GlobalVariable *, SmallVector<unsigned, 4> >::iterator
1877 I = InlineInfo.begin(), E = InlineInfo.end(); I != E; ++I) {
1878 GlobalVariable *GV = I->first;
1879 SmallVector<unsigned, 4> &Labels = I->second;
1880 DISubprogram SP(GV);
1884 SP.getLinkageName(LName);
1887 Asm->EmitString(LName.empty() ? Name : LName);
1888 Asm->EOL("MIPS linkage name");
1890 Asm->EmitString(Name); Asm->EOL("Function name");
1892 Asm->EmitULEB128Bytes(Labels.size()); Asm->EOL("Inline count");
1894 for (SmallVector<unsigned, 4>::iterator LI = Labels.begin(),
1895 LE = Labels.end(); LI != LE; ++LI) {
1896 DIE *SP = MainCU->getDieMapSlotFor(GV);
1897 Asm->EmitInt32(SP->getOffset()); Asm->EOL("DIE offset");
1899 if (TD->getPointerSize() == sizeof(int32_t))
1900 O << TAI->getData32bitsDirective();
1902 O << TAI->getData64bitsDirective();
1904 PrintLabelName("label", *LI); Asm->EOL("low_pc");
1908 EmitLabel("debug_inlined_end", 1);
1912 /// GetOrCreateSourceID - Look up the source id with the given directory and
1913 /// source file names. If none currently exists, create a new id and insert it
1914 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1916 unsigned DwarfDebug::GetOrCreateSourceID(const std::string &DirName,
1917 const std::string &FileName) {
1919 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1920 if (DI != DirectoryIdMap.end()) {
1921 DId = DI->getValue();
1923 DId = DirectoryNames.size() + 1;
1924 DirectoryIdMap[DirName] = DId;
1925 DirectoryNames.push_back(DirName);
1929 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1930 if (FI != SourceFileIdMap.end()) {
1931 FId = FI->getValue();
1933 FId = SourceFileNames.size() + 1;
1934 SourceFileIdMap[FileName] = FId;
1935 SourceFileNames.push_back(FileName);
1938 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1939 SourceIdMap.find(std::make_pair(DId, FId));
1940 if (SI != SourceIdMap.end())
1943 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
1944 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1945 SourceIds.push_back(std::make_pair(DId, FId));
1950 void DwarfDebug::ConstructCompileUnit(GlobalVariable *GV) {
1951 DICompileUnit DIUnit(GV);
1952 std::string Dir, FN, Prod;
1953 unsigned ID = GetOrCreateSourceID(DIUnit.getDirectory(Dir),
1954 DIUnit.getFilename(FN));
1956 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1957 AddSectionOffset(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
1958 DWLabel("section_line", 0), DWLabel("section_line", 0),
1960 AddString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1961 DIUnit.getProducer(Prod));
1962 AddUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1963 DIUnit.getLanguage());
1964 AddString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1967 AddString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1968 if (DIUnit.isOptimized())
1969 AddUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1972 DIUnit.getFlags(Flags);
1974 AddString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1976 unsigned RVer = DIUnit.getRunTimeVersion();
1978 AddUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1979 dwarf::DW_FORM_data1, RVer);
1981 CompileUnit *Unit = new CompileUnit(ID, Die);
1982 if (DIUnit.isMain()) {
1983 assert(!MainCU && "Multiple main compile units are found!");
1987 CompileUnitMap[DIUnit.getGV()] = Unit;
1988 CompileUnits.push_back(Unit);
1991 /// ConstructCompileUnits - Create a compile unit DIEs.
1992 void DwarfDebug::ConstructCompileUnits() {
1993 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.compile_units");
1996 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
1997 "Malformed compile unit descriptor anchor type");
1998 Constant *RootC = cast<Constant>(*Root->use_begin());
1999 assert(RootC->hasNUsesOrMore(1) &&
2000 "Malformed compile unit descriptor anchor type");
2002 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2004 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2005 UUI != UUE; ++UUI) {
2006 GlobalVariable *GV = cast<GlobalVariable>(*UUI);
2007 ConstructCompileUnit(GV);
2011 bool DwarfDebug::ConstructGlobalVariableDIE(GlobalVariable *GV) {
2012 DIGlobalVariable DI_GV(GV);
2013 CompileUnit *DW_Unit = MainCU;
2015 DW_Unit = &FindCompileUnit(DI_GV.getCompileUnit());
2017 // Check for pre-existence.
2018 DIE *&Slot = DW_Unit->getDieMapSlotFor(DI_GV.getGV());
2022 DIE *VariableDie = CreateGlobalVariableDIE(DW_Unit, DI_GV);
2025 DIEBlock *Block = new DIEBlock();
2026 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
2028 AddObjectLabel(Block, 0, dwarf::DW_FORM_udata,
2029 Asm->getGlobalLinkName(DI_GV.getGlobal(), GLN));
2030 AddBlock(VariableDie, dwarf::DW_AT_location, 0, Block);
2035 // Add to context owner.
2036 DW_Unit->getDie()->AddChild(VariableDie);
2038 // Expose as global. FIXME - need to check external flag.
2040 DW_Unit->AddGlobal(DI_GV.getName(Name), VariableDie);
2044 /// ConstructGlobalVariableDIEs - Create DIEs for each of the externally visible
2045 /// global variables. Return true if at least one global DIE is created.
2046 bool DwarfDebug::ConstructGlobalVariableDIEs() {
2047 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.global_variables");
2051 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2052 "Malformed global variable descriptor anchor type");
2053 Constant *RootC = cast<Constant>(*Root->use_begin());
2054 assert(RootC->hasNUsesOrMore(1) &&
2055 "Malformed global variable descriptor anchor type");
2057 bool Result = false;
2058 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2060 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2062 Result |= ConstructGlobalVariableDIE(cast<GlobalVariable>(*UUI));
2067 bool DwarfDebug::ConstructSubprogram(GlobalVariable *GV) {
2068 DISubprogram SP(GV);
2069 CompileUnit *Unit = MainCU;
2071 Unit = &FindCompileUnit(SP.getCompileUnit());
2073 // Check for pre-existence.
2074 DIE *&Slot = Unit->getDieMapSlotFor(GV);
2078 if (!SP.isDefinition())
2079 // This is a method declaration which will be handled while constructing
2083 DIE *SubprogramDie = CreateSubprogramDIE(Unit, SP);
2086 Slot = SubprogramDie;
2088 // Add to context owner.
2089 Unit->getDie()->AddChild(SubprogramDie);
2091 // Expose as global.
2093 Unit->AddGlobal(SP.getName(Name), SubprogramDie);
2097 /// ConstructSubprograms - Create DIEs for each of the externally visible
2098 /// subprograms. Return true if at least one subprogram DIE is created.
2099 bool DwarfDebug::ConstructSubprograms() {
2100 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.subprograms");
2104 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2105 "Malformed subprogram descriptor anchor type");
2106 Constant *RootC = cast<Constant>(*Root->use_begin());
2107 assert(RootC->hasNUsesOrMore(1) &&
2108 "Malformed subprogram descriptor anchor type");
2110 bool Result = false;
2111 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2113 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2115 Result |= ConstructSubprogram(cast<GlobalVariable>(*UUI));
2120 /// SetDebugInfo - Create global DIEs and emit initial debug info sections.
2121 /// This is inovked by the target AsmPrinter.
2122 void DwarfDebug::SetDebugInfo(MachineModuleInfo *mmi) {
2123 if (TimePassesIsEnabled)
2124 DebugTimer->startTimer();
2126 // Create all the compile unit DIEs.
2127 ConstructCompileUnits();
2129 if (CompileUnits.empty()) {
2130 if (TimePassesIsEnabled)
2131 DebugTimer->stopTimer();
2136 // Create DIEs for each of the externally visible global variables.
2137 bool globalDIEs = ConstructGlobalVariableDIEs();
2139 // Create DIEs for each of the externally visible subprograms.
2140 bool subprogramDIEs = ConstructSubprograms();
2142 // If there is not any debug info available for any global variables and any
2143 // subprograms then there is not any debug info to emit.
2144 if (!globalDIEs && !subprogramDIEs) {
2145 if (TimePassesIsEnabled)
2146 DebugTimer->stopTimer();
2153 MMI->setDebugInfoAvailability(true);
2155 // Prime section data.
2156 SectionMap.insert(TAI->getTextSection());
2158 // Print out .file directives to specify files for .loc directives. These are
2159 // printed out early so that they precede any .loc directives.
2160 if (TAI->hasDotLocAndDotFile()) {
2161 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
2162 // Remember source id starts at 1.
2163 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
2164 sys::Path FullPath(getSourceDirectoryName(Id.first));
2166 FullPath.appendComponent(getSourceFileName(Id.second));
2167 assert(AppendOk && "Could not append filename to directory!");
2169 Asm->EmitFile(i, FullPath.toString());
2174 // Emit initial sections
2177 if (TimePassesIsEnabled)
2178 DebugTimer->stopTimer();
2181 /// EndModule - Emit all Dwarf sections that should come after the content.
2183 void DwarfDebug::EndModule() {
2184 if (!ShouldEmitDwarfDebug())
2187 if (TimePassesIsEnabled)
2188 DebugTimer->startTimer();
2190 // Standard sections final addresses.
2191 Asm->SwitchToSection(TAI->getTextSection());
2192 EmitLabel("text_end", 0);
2193 Asm->SwitchToSection(TAI->getDataSection());
2194 EmitLabel("data_end", 0);
2196 // End text sections.
2197 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2198 Asm->SwitchToSection(SectionMap[i]);
2199 EmitLabel("section_end", i);
2202 // Emit common frame information.
2203 EmitCommonDebugFrame();
2205 // Emit function debug frame information
2206 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
2207 E = DebugFrames.end(); I != E; ++I)
2208 EmitFunctionDebugFrame(*I);
2210 // Compute DIE offsets and sizes.
2213 // Emit all the DIEs into a debug info section
2216 // Corresponding abbreviations into a abbrev section.
2217 EmitAbbreviations();
2219 // Emit source line correspondence into a debug line section.
2222 // Emit info into a debug pubnames section.
2223 EmitDebugPubNames();
2225 // Emit info into a debug str section.
2228 // Emit info into a debug loc section.
2231 // Emit info into a debug aranges section.
2234 // Emit info into a debug ranges section.
2237 // Emit info into a debug macinfo section.
2240 // Emit inline info.
2241 EmitDebugInlineInfo();
2243 if (TimePassesIsEnabled)
2244 DebugTimer->stopTimer();
2247 /// BeginFunction - Gather pre-function debug information. Assumes being
2248 /// emitted immediately after the function entry point.
2249 void DwarfDebug::BeginFunction(MachineFunction *MF) {
2252 if (!ShouldEmitDwarfDebug()) return;
2254 if (TimePassesIsEnabled)
2255 DebugTimer->startTimer();
2257 // Begin accumulating function debug information.
2258 MMI->BeginFunction(MF);
2260 // Assumes in correct section after the entry point.
2261 EmitLabel("func_begin", ++SubprogramCount);
2263 // Emit label for the implicitly defined dbg.stoppoint at the start of the
2265 DebugLoc FDL = MF->getDefaultDebugLoc();
2266 if (!FDL.isUnknown()) {
2267 DebugLocTuple DLT = MF->getDebugLocTuple(FDL);
2268 unsigned LabelID = RecordSourceLine(DLT.Line, DLT.Col,
2269 DICompileUnit(DLT.CompileUnit));
2270 Asm->printLabel(LabelID);
2273 if (TimePassesIsEnabled)
2274 DebugTimer->stopTimer();
2277 /// EndFunction - Gather and emit post-function debug information.
2279 void DwarfDebug::EndFunction(MachineFunction *MF) {
2280 if (!ShouldEmitDwarfDebug()) return;
2282 if (TimePassesIsEnabled)
2283 DebugTimer->startTimer();
2285 // Define end label for subprogram.
2286 EmitLabel("func_end", SubprogramCount);
2288 // Get function line info.
2289 if (!Lines.empty()) {
2290 // Get section line info.
2291 unsigned ID = SectionMap.insert(Asm->CurrentSection_);
2292 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2293 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2294 // Append the function info to section info.
2295 SectionLineInfos.insert(SectionLineInfos.end(),
2296 Lines.begin(), Lines.end());
2299 // Construct the DbgScope for abstract instances.
2300 for (SmallVector<DbgScope *, 32>::iterator
2301 I = AbstractInstanceRootList.begin(),
2302 E = AbstractInstanceRootList.end(); I != E; ++I)
2303 ConstructAbstractDbgScope(*I);
2305 // Construct scopes for subprogram.
2306 if (FunctionDbgScope)
2307 ConstructFunctionDbgScope(FunctionDbgScope);
2309 // FIXME: This is wrong. We are essentially getting past a problem with
2310 // debug information not being able to handle unreachable blocks that have
2311 // debug information in them. In particular, those unreachable blocks that
2312 // have "region end" info in them. That situation results in the "root
2313 // scope" not being created. If that's the case, then emit a "default"
2314 // scope, i.e., one that encompasses the whole function. This isn't
2315 // desirable. And a better way of handling this (and all of the debugging
2316 // information) needs to be explored.
2317 ConstructDefaultDbgScope(MF);
2319 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
2320 MMI->getFrameMoves()));
2323 if (FunctionDbgScope) {
2324 delete FunctionDbgScope;
2325 DbgScopeMap.clear();
2326 DbgAbstractScopeMap.clear();
2327 DbgConcreteScopeMap.clear();
2328 InlinedVariableScopes.clear();
2329 FunctionDbgScope = NULL;
2330 LexicalScopeStack.clear();
2331 AbstractInstanceRootList.clear();
2336 if (TimePassesIsEnabled)
2337 DebugTimer->stopTimer();
2340 /// RecordSourceLine - Records location information and associates it with a
2341 /// label. Returns a unique label ID used to generate a label and provide
2342 /// correspondence to the source line list.
2343 unsigned DwarfDebug::RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
2344 if (TimePassesIsEnabled)
2345 DebugTimer->startTimer();
2347 CompileUnit *Unit = CompileUnitMap[V];
2348 assert(Unit && "Unable to find CompileUnit");
2349 unsigned ID = MMI->NextLabelID();
2350 Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
2352 if (TimePassesIsEnabled)
2353 DebugTimer->stopTimer();
2358 /// RecordSourceLine - Records location information and associates it with a
2359 /// label. Returns a unique label ID used to generate a label and provide
2360 /// correspondence to the source line list.
2361 unsigned DwarfDebug::RecordSourceLine(unsigned Line, unsigned Col,
2363 if (TimePassesIsEnabled)
2364 DebugTimer->startTimer();
2366 std::string Dir, Fn;
2367 unsigned Src = GetOrCreateSourceID(CU.getDirectory(Dir),
2368 CU.getFilename(Fn));
2369 unsigned ID = MMI->NextLabelID();
2370 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
2372 if (TimePassesIsEnabled)
2373 DebugTimer->stopTimer();
2378 /// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
2379 /// timed. Look up the source id with the given directory and source file
2380 /// names. If none currently exists, create a new id and insert it in the
2381 /// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
2383 unsigned DwarfDebug::getOrCreateSourceID(const std::string &DirName,
2384 const std::string &FileName) {
2385 if (TimePassesIsEnabled)
2386 DebugTimer->startTimer();
2388 unsigned SrcId = GetOrCreateSourceID(DirName, FileName);
2390 if (TimePassesIsEnabled)
2391 DebugTimer->stopTimer();
2396 /// RecordRegionStart - Indicate the start of a region.
2397 unsigned DwarfDebug::RecordRegionStart(GlobalVariable *V) {
2398 if (TimePassesIsEnabled)
2399 DebugTimer->startTimer();
2401 DbgScope *Scope = getOrCreateScope(V);
2402 unsigned ID = MMI->NextLabelID();
2403 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
2404 LexicalScopeStack.push_back(Scope);
2406 if (TimePassesIsEnabled)
2407 DebugTimer->stopTimer();
2412 /// RecordRegionEnd - Indicate the end of a region.
2413 unsigned DwarfDebug::RecordRegionEnd(GlobalVariable *V) {
2414 if (TimePassesIsEnabled)
2415 DebugTimer->startTimer();
2417 DbgScope *Scope = getOrCreateScope(V);
2418 unsigned ID = MMI->NextLabelID();
2419 Scope->setEndLabelID(ID);
2420 if (LexicalScopeStack.size() != 0)
2421 LexicalScopeStack.pop_back();
2423 if (TimePassesIsEnabled)
2424 DebugTimer->stopTimer();
2429 /// RecordVariable - Indicate the declaration of a local variable.
2430 void DwarfDebug::RecordVariable(GlobalVariable *GV, unsigned FrameIndex,
2431 const MachineInstr *MI) {
2432 if (TimePassesIsEnabled)
2433 DebugTimer->startTimer();
2435 DIDescriptor Desc(GV);
2436 DbgScope *Scope = NULL;
2438 if (Desc.getTag() == dwarf::DW_TAG_variable) {
2439 // GV is a global variable.
2440 DIGlobalVariable DG(GV);
2441 Scope = getOrCreateScope(DG.getContext().getGV());
2443 DenseMap<const MachineInstr *, DbgScope *>::iterator
2444 SI = InlinedVariableScopes.find(MI);
2446 if (SI != InlinedVariableScopes.end()) {
2447 // or GV is an inlined local variable.
2451 GlobalVariable *V = DV.getContext().getGV();
2453 // FIXME: The code that checks for the inlined local variable is a hack!
2454 DenseMap<const GlobalVariable *, DbgScope *>::iterator
2455 AI = AbstractInstanceRootMap.find(V);
2457 if (AI != AbstractInstanceRootMap.end()) {
2458 // This method is called each time a DECLARE node is encountered. For an
2459 // inlined function, this could be many, many times. We don't want to
2460 // re-add variables to that DIE for each time. We just want to add them
2461 // once. Check to make sure that we haven't added them already.
2462 DenseMap<const GlobalVariable *,
2463 SmallSet<const GlobalVariable *, 32> >::iterator
2464 IP = InlinedParamMap.find(V);
2466 if (IP != InlinedParamMap.end()) {
2467 SmallSet<const GlobalVariable*, 32> &S = IP->second;
2469 if (S.count(GV) > 0) {
2470 if (TimePassesIsEnabled)
2471 DebugTimer->stopTimer();
2477 // or GV is an inlined local variable.
2479 InlinedParamMap[V].insert(GV);
2481 // or GV is a local variable.
2482 Scope = getOrCreateScope(V);
2487 assert(Scope && "Unable to find the variable's scope");
2488 DbgVariable *DV = new DbgVariable(DIVariable(GV), FrameIndex);
2489 Scope->AddVariable(DV);
2491 if (TimePassesIsEnabled)
2492 DebugTimer->stopTimer();
2495 //// RecordInlinedFnStart - Indicate the start of inlined subroutine.
2496 unsigned DwarfDebug::RecordInlinedFnStart(DISubprogram &SP, DICompileUnit CU,
2497 unsigned Line, unsigned Col) {
2498 unsigned LabelID = MMI->NextLabelID();
2500 if (!TAI->doesDwarfUsesInlineInfoSection())
2503 if (TimePassesIsEnabled)
2504 DebugTimer->startTimer();
2506 GlobalVariable *GV = SP.getGV();
2507 DenseMap<const GlobalVariable *, DbgScope *>::iterator
2508 II = AbstractInstanceRootMap.find(GV);
2510 if (II == AbstractInstanceRootMap.end()) {
2511 // Create an abstract instance entry for this inlined function if it doesn't
2513 DbgScope *Scope = new DbgScope(NULL, DIDescriptor(GV));
2515 // Get the compile unit context.
2516 CompileUnit *Unit = &FindCompileUnit(SP.getCompileUnit());
2517 DIE *SPDie = Unit->getDieMapSlotFor(GV);
2519 SPDie = CreateSubprogramDIE(Unit, SP, false, true);
2521 // Mark as being inlined. This makes this subprogram entry an abstract
2523 // FIXME: Our debugger doesn't care about the value of DW_AT_inline, only
2524 // that it's defined. That probably won't change in the future. However,
2525 // this could be more elegant.
2526 AddUInt(SPDie, dwarf::DW_AT_inline, 0, dwarf::DW_INL_declared_not_inlined);
2528 // Keep track of the abstract scope for this function.
2529 DbgAbstractScopeMap[GV] = Scope;
2531 AbstractInstanceRootMap[GV] = Scope;
2532 AbstractInstanceRootList.push_back(Scope);
2535 // Create a concrete inlined instance for this inlined function.
2536 DbgConcreteScope *ConcreteScope = new DbgConcreteScope(DIDescriptor(GV));
2537 DIE *ScopeDie = new DIE(dwarf::DW_TAG_inlined_subroutine);
2538 CompileUnit *Unit = &FindCompileUnit(SP.getCompileUnit());
2539 ScopeDie->setAbstractCompileUnit(Unit);
2541 DIE *Origin = Unit->getDieMapSlotFor(GV);
2542 AddDIEEntry(ScopeDie, dwarf::DW_AT_abstract_origin,
2543 dwarf::DW_FORM_ref4, Origin);
2544 AddUInt(ScopeDie, dwarf::DW_AT_call_file, 0, Unit->getID());
2545 AddUInt(ScopeDie, dwarf::DW_AT_call_line, 0, Line);
2546 AddUInt(ScopeDie, dwarf::DW_AT_call_column, 0, Col);
2548 ConcreteScope->setDie(ScopeDie);
2549 ConcreteScope->setStartLabelID(LabelID);
2550 MMI->RecordUsedDbgLabel(LabelID);
2552 LexicalScopeStack.back()->AddConcreteInst(ConcreteScope);
2554 // Keep track of the concrete scope that's inlined into this function.
2555 DenseMap<GlobalVariable *, SmallVector<DbgScope *, 8> >::iterator
2556 SI = DbgConcreteScopeMap.find(GV);
2558 if (SI == DbgConcreteScopeMap.end())
2559 DbgConcreteScopeMap[GV].push_back(ConcreteScope);
2561 SI->second.push_back(ConcreteScope);
2563 // Track the start label for this inlined function.
2564 DenseMap<GlobalVariable *, SmallVector<unsigned, 4> >::iterator
2565 I = InlineInfo.find(GV);
2567 if (I == InlineInfo.end())
2568 InlineInfo[GV].push_back(LabelID);
2570 I->second.push_back(LabelID);
2572 if (TimePassesIsEnabled)
2573 DebugTimer->stopTimer();
2578 /// RecordInlinedFnEnd - Indicate the end of inlined subroutine.
2579 unsigned DwarfDebug::RecordInlinedFnEnd(DISubprogram &SP) {
2580 if (!TAI->doesDwarfUsesInlineInfoSection())
2583 if (TimePassesIsEnabled)
2584 DebugTimer->startTimer();
2586 GlobalVariable *GV = SP.getGV();
2587 DenseMap<GlobalVariable *, SmallVector<DbgScope *, 8> >::iterator
2588 I = DbgConcreteScopeMap.find(GV);
2590 if (I == DbgConcreteScopeMap.end()) {
2591 // FIXME: Can this situation actually happen? And if so, should it?
2592 if (TimePassesIsEnabled)
2593 DebugTimer->stopTimer();
2598 SmallVector<DbgScope *, 8> &Scopes = I->second;
2599 assert(!Scopes.empty() && "We should have at least one debug scope!");
2600 DbgScope *Scope = Scopes.back(); Scopes.pop_back();
2601 unsigned ID = MMI->NextLabelID();
2602 MMI->RecordUsedDbgLabel(ID);
2603 Scope->setEndLabelID(ID);
2605 if (TimePassesIsEnabled)
2606 DebugTimer->stopTimer();
2611 /// RecordVariableScope - Record scope for the variable declared by
2612 /// DeclareMI. DeclareMI must describe TargetInstrInfo::DECLARE. Record scopes
2613 /// for only inlined subroutine variables. Other variables's scopes are
2614 /// determined during RecordVariable().
2615 void DwarfDebug::RecordVariableScope(DIVariable &DV,
2616 const MachineInstr *DeclareMI) {
2617 if (TimePassesIsEnabled)
2618 DebugTimer->startTimer();
2620 DISubprogram SP(DV.getContext().getGV());
2623 if (TimePassesIsEnabled)
2624 DebugTimer->stopTimer();
2629 DenseMap<GlobalVariable *, DbgScope *>::iterator
2630 I = DbgAbstractScopeMap.find(SP.getGV());
2631 if (I != DbgAbstractScopeMap.end())
2632 InlinedVariableScopes[DeclareMI] = I->second;
2634 if (TimePassesIsEnabled)
2635 DebugTimer->stopTimer();