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"
25 static TimerGroup &getDwarfTimerGroup() {
26 static TimerGroup DwarfTimerGroup("Dwarf Debugging");
27 return DwarfTimerGroup;
30 //===----------------------------------------------------------------------===//
32 /// Configuration values for initial hash set sizes (log2).
34 static const unsigned InitDiesSetSize = 9; // log2(512)
35 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
36 static const unsigned InitValuesSetSize = 9; // log2(512)
40 //===----------------------------------------------------------------------===//
41 /// CompileUnit - This dwarf writer support class manages information associate
42 /// with a source file.
43 class VISIBILITY_HIDDEN CompileUnit {
44 /// ID - File identifier for source.
48 /// Die - Compile unit debug information entry.
52 /// GVToDieMap - Tracks the mapping of unit level debug informaton
53 /// variables to debug information entries.
54 std::map<GlobalVariable *, DIE *> GVToDieMap;
56 /// GVToDIEEntryMap - Tracks the mapping of unit level debug informaton
57 /// descriptors to debug information entries using a DIEEntry proxy.
58 std::map<GlobalVariable *, DIEEntry *> GVToDIEEntryMap;
60 /// Globals - A map of globally visible named entities for this unit.
62 StringMap<DIE*> Globals;
64 /// DiesSet - Used to uniquely define dies within the compile unit.
66 FoldingSet<DIE> DiesSet;
68 CompileUnit(unsigned I, DIE *D)
69 : ID(I), Die(D), DiesSet(InitDiesSetSize) {}
70 ~CompileUnit() { delete Die; }
73 unsigned getID() const { return ID; }
74 DIE* getDie() const { return Die; }
75 StringMap<DIE*> &getGlobals() { return Globals; }
77 /// hasContent - Return true if this compile unit has something to write out.
79 bool hasContent() const { return !Die->getChildren().empty(); }
81 /// AddGlobal - Add a new global entity to the compile unit.
83 void AddGlobal(const std::string &Name, DIE *Die) { Globals[Name] = Die; }
85 /// getDieMapSlotFor - Returns the debug information entry map slot for the
86 /// specified debug variable.
87 DIE *&getDieMapSlotFor(GlobalVariable *GV) { return GVToDieMap[GV]; }
89 /// getDIEEntrySlotFor - Returns the debug information entry proxy slot for
90 /// the specified debug variable.
91 DIEEntry *&getDIEEntrySlotFor(GlobalVariable *GV) {
92 return GVToDIEEntryMap[GV];
95 /// AddDie - Adds or interns the DIE to the compile unit.
97 DIE *AddDie(DIE &Buffer) {
101 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
104 Die = new DIE(Buffer);
105 DiesSet.InsertNode(Die, Where);
106 this->Die->AddChild(Die);
114 //===----------------------------------------------------------------------===//
115 /// DbgVariable - This class is used to track local variable information.
117 class VISIBILITY_HIDDEN DbgVariable {
118 DIVariable Var; // Variable Descriptor.
119 unsigned FrameIndex; // Variable frame index.
120 bool InlinedFnVar; // Variable for an inlined function.
122 DbgVariable(DIVariable V, unsigned I, bool IFV)
123 : Var(V), FrameIndex(I), InlinedFnVar(IFV) {}
126 DIVariable getVariable() const { return Var; }
127 unsigned getFrameIndex() const { return FrameIndex; }
128 bool isInlinedFnVar() const { return InlinedFnVar; }
131 //===----------------------------------------------------------------------===//
132 /// DbgScope - This class is used to track scope information.
134 class DbgConcreteScope;
135 class VISIBILITY_HIDDEN DbgScope {
136 DbgScope *Parent; // Parent to this scope.
137 DIDescriptor Desc; // Debug info descriptor for scope.
138 // Either subprogram or block.
139 unsigned StartLabelID; // Label ID of the beginning of scope.
140 unsigned EndLabelID; // Label ID of the end of scope.
141 SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope.
142 SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
143 SmallVector<DbgConcreteScope *, 8> ConcreteInsts;// Concrete insts of funcs.
145 // Private state for dump()
146 mutable unsigned IndentLevel;
148 DbgScope(DbgScope *P, DIDescriptor D)
149 : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0), IndentLevel(0) {}
153 DbgScope *getParent() const { return Parent; }
154 DIDescriptor getDesc() const { return Desc; }
155 unsigned getStartLabelID() const { return StartLabelID; }
156 unsigned getEndLabelID() const { return EndLabelID; }
157 SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
158 SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
159 SmallVector<DbgConcreteScope*,8> &getConcreteInsts() { return ConcreteInsts; }
160 void setStartLabelID(unsigned S) { StartLabelID = S; }
161 void setEndLabelID(unsigned E) { EndLabelID = E; }
163 /// AddScope - Add a scope to the scope.
165 void AddScope(DbgScope *S) { Scopes.push_back(S); }
167 /// AddVariable - Add a variable to the scope.
169 void AddVariable(DbgVariable *V) { Variables.push_back(V); }
171 /// AddConcreteInst - Add a concrete instance to the scope.
173 void AddConcreteInst(DbgConcreteScope *C) { ConcreteInsts.push_back(C); }
181 void DbgScope::dump() const {
182 std::string Indent(IndentLevel, ' ');
184 cerr << Indent; Desc.dump();
185 cerr << " [" << StartLabelID << ", " << EndLabelID << "]\n";
189 for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
190 if (Scopes[i] != this)
197 //===----------------------------------------------------------------------===//
198 /// DbgConcreteScope - This class is used to track a scope that holds concrete
199 /// instance information.
201 class VISIBILITY_HIDDEN DbgConcreteScope : public DbgScope {
203 DIE *Die; // Debug info for this concrete scope.
205 DbgConcreteScope(DIDescriptor D) : DbgScope(NULL, D) {}
208 DIE *getDie() const { return Die; }
209 void setDie(DIE *D) { Die = D; }
212 DbgScope::~DbgScope() {
213 for (unsigned i = 0, N = Scopes.size(); i < N; ++i)
215 for (unsigned j = 0, M = Variables.size(); j < M; ++j)
217 for (unsigned k = 0, O = ConcreteInsts.size(); k < O; ++k)
218 delete ConcreteInsts[k];
221 } // end llvm namespace
223 DwarfDebug::DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
224 : Dwarf(OS, A, T, "dbg"), ModuleCU(0),
225 AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(),
226 ValuesSet(InitValuesSetSize), Values(), StringPool(), SectionMap(),
227 SectionSourceLines(), didInitial(false), shouldEmit(false),
228 FunctionDbgScope(0), DebugTimer(0) {
229 if (TimePassesIsEnabled)
230 DebugTimer = new Timer("Dwarf Debug Writer",
231 getDwarfTimerGroup());
233 DwarfDebug::~DwarfDebug() {
234 for (unsigned j = 0, M = Values.size(); j < M; ++j)
237 for (DenseMap<const GlobalVariable *, DbgScope *>::iterator
238 I = AbstractInstanceRootMap.begin(),
239 E = AbstractInstanceRootMap.end(); I != E;++I)
245 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
247 void DwarfDebug::AssignAbbrevNumber(DIEAbbrev &Abbrev) {
248 // Profile the node so that we can make it unique.
252 // Check the set for priors.
253 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
255 // If it's newly added.
256 if (InSet == &Abbrev) {
257 // Add to abbreviation list.
258 Abbreviations.push_back(&Abbrev);
260 // Assign the vector position + 1 as its number.
261 Abbrev.setNumber(Abbreviations.size());
263 // Assign existing abbreviation number.
264 Abbrev.setNumber(InSet->getNumber());
268 /// CreateDIEEntry - Creates a new DIEEntry to be a proxy for a debug
269 /// information entry.
270 DIEEntry *DwarfDebug::CreateDIEEntry(DIE *Entry) {
275 DIEEntry::Profile(ID, Entry);
277 Value = static_cast<DIEEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
279 if (Value) return Value;
281 Value = new DIEEntry(Entry);
282 ValuesSet.InsertNode(Value, Where);
284 Value = new DIEEntry(Entry);
287 Values.push_back(Value);
291 /// SetDIEEntry - Set a DIEEntry once the debug information entry is defined.
293 void DwarfDebug::SetDIEEntry(DIEEntry *Value, DIE *Entry) {
294 Value->setEntry(Entry);
296 // Add to values set if not already there. If it is, we merely have a
297 // duplicate in the values list (no harm.)
298 ValuesSet.GetOrInsertNode(Value);
301 /// AddUInt - Add an unsigned integer attribute data and value.
303 void DwarfDebug::AddUInt(DIE *Die, unsigned Attribute,
304 unsigned Form, uint64_t Integer) {
305 if (!Form) Form = DIEInteger::BestForm(false, Integer);
308 DIEInteger::Profile(ID, Integer);
310 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
313 Value = new DIEInteger(Integer);
314 ValuesSet.InsertNode(Value, Where);
315 Values.push_back(Value);
318 Die->AddValue(Attribute, Form, Value);
321 /// AddSInt - Add an signed integer attribute data and value.
323 void DwarfDebug::AddSInt(DIE *Die, unsigned Attribute,
324 unsigned Form, int64_t Integer) {
325 if (!Form) Form = DIEInteger::BestForm(true, Integer);
328 DIEInteger::Profile(ID, (uint64_t)Integer);
330 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
333 Value = new DIEInteger(Integer);
334 ValuesSet.InsertNode(Value, Where);
335 Values.push_back(Value);
338 Die->AddValue(Attribute, Form, Value);
341 /// AddString - Add a string attribute data and value.
343 void DwarfDebug::AddString(DIE *Die, unsigned Attribute, unsigned Form,
344 const std::string &String) {
346 DIEString::Profile(ID, String);
348 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
351 Value = new DIEString(String);
352 ValuesSet.InsertNode(Value, Where);
353 Values.push_back(Value);
356 Die->AddValue(Attribute, Form, Value);
359 /// AddLabel - Add a Dwarf label attribute data and value.
361 void DwarfDebug::AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
362 const DWLabel &Label) {
364 DIEDwarfLabel::Profile(ID, Label);
366 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
369 Value = new DIEDwarfLabel(Label);
370 ValuesSet.InsertNode(Value, Where);
371 Values.push_back(Value);
374 Die->AddValue(Attribute, Form, Value);
377 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
379 void DwarfDebug::AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
380 const std::string &Label) {
382 DIEObjectLabel::Profile(ID, Label);
384 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
387 Value = new DIEObjectLabel(Label);
388 ValuesSet.InsertNode(Value, Where);
389 Values.push_back(Value);
392 Die->AddValue(Attribute, Form, Value);
395 /// AddSectionOffset - Add a section offset label attribute data and value.
397 void DwarfDebug::AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
398 const DWLabel &Label, const DWLabel &Section,
399 bool isEH, bool useSet) {
401 DIESectionOffset::Profile(ID, Label, Section);
403 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
406 Value = new DIESectionOffset(Label, Section, isEH, useSet);
407 ValuesSet.InsertNode(Value, Where);
408 Values.push_back(Value);
411 Die->AddValue(Attribute, Form, Value);
414 /// AddDelta - Add a label delta attribute data and value.
416 void DwarfDebug::AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
417 const DWLabel &Hi, const DWLabel &Lo) {
419 DIEDelta::Profile(ID, Hi, Lo);
421 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
424 Value = new DIEDelta(Hi, Lo);
425 ValuesSet.InsertNode(Value, Where);
426 Values.push_back(Value);
429 Die->AddValue(Attribute, Form, Value);
432 /// AddBlock - Add block data.
434 void DwarfDebug::AddBlock(DIE *Die, unsigned Attribute, unsigned Form,
436 Block->ComputeSize(TD);
440 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
444 ValuesSet.InsertNode(Value, Where);
445 Values.push_back(Value);
447 // Already exists, reuse the previous one.
449 Block = cast<DIEBlock>(Value);
452 Die->AddValue(Attribute, Block->BestForm(), Value);
455 /// AddSourceLine - Add location information to specified debug information
457 void DwarfDebug::AddSourceLine(DIE *Die, const DIVariable *V) {
458 // If there is no compile unit specified, don't add a line #.
459 if (V->getCompileUnit().isNull())
462 unsigned Line = V->getLineNumber();
463 unsigned FileID = FindCompileUnit(V->getCompileUnit()).getID();
464 assert(FileID && "Invalid file id");
465 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
466 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
469 /// AddSourceLine - Add location information to specified debug information
471 void DwarfDebug::AddSourceLine(DIE *Die, const DIGlobal *G) {
472 // If there is no compile unit specified, don't add a line #.
473 if (G->getCompileUnit().isNull())
476 unsigned Line = G->getLineNumber();
477 unsigned FileID = FindCompileUnit(G->getCompileUnit()).getID();
478 assert(FileID && "Invalid file id");
479 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
480 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
482 void DwarfDebug::AddSourceLine(DIE *Die, const DIType *Ty) {
483 // If there is no compile unit specified, don't add a line #.
484 DICompileUnit CU = Ty->getCompileUnit();
488 unsigned Line = Ty->getLineNumber();
489 unsigned FileID = FindCompileUnit(CU).getID();
490 assert(FileID && "Invalid file id");
491 AddUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
492 AddUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
495 /// AddAddress - Add an address attribute to a die based on the location
497 void DwarfDebug::AddAddress(DIE *Die, unsigned Attribute,
498 const MachineLocation &Location) {
499 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
500 DIEBlock *Block = new DIEBlock();
502 if (Location.isReg()) {
504 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
506 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
507 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
511 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
513 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
514 AddUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
517 AddUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
520 AddBlock(Die, Attribute, 0, Block);
523 /// AddType - Add a new type attribute to the specified entity.
524 void DwarfDebug::AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
528 // Check for pre-existence.
529 DIEEntry *&Slot = DW_Unit->getDIEEntrySlotFor(Ty.getGV());
531 // If it exists then use the existing value.
533 Entity->AddValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Slot);
538 Slot = CreateDIEEntry();
541 DIE Buffer(dwarf::DW_TAG_base_type);
542 if (Ty.isBasicType(Ty.getTag()))
543 ConstructTypeDIE(DW_Unit, Buffer, DIBasicType(Ty.getGV()));
544 else if (Ty.isDerivedType(Ty.getTag()))
545 ConstructTypeDIE(DW_Unit, Buffer, DIDerivedType(Ty.getGV()));
547 assert(Ty.isCompositeType(Ty.getTag()) && "Unknown kind of DIType");
548 ConstructTypeDIE(DW_Unit, Buffer, DICompositeType(Ty.getGV()));
551 // Add debug information entry to entity and appropriate context.
553 DIDescriptor Context = Ty.getContext();
554 if (!Context.isNull())
555 Die = DW_Unit->getDieMapSlotFor(Context.getGV());
558 DIE *Child = new DIE(Buffer);
559 Die->AddChild(Child);
561 SetDIEEntry(Slot, Child);
563 Die = DW_Unit->AddDie(Buffer);
564 SetDIEEntry(Slot, Die);
567 Entity->AddValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Slot);
570 /// ConstructTypeDIE - Construct basic type die from DIBasicType.
571 void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
573 // Get core information.
576 Buffer.setTag(dwarf::DW_TAG_base_type);
577 AddUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
580 // Add name if not anonymous or intermediate type.
582 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
583 uint64_t Size = BTy.getSizeInBits() >> 3;
584 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
587 /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
588 void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
590 // Get core information.
593 uint64_t Size = DTy.getSizeInBits() >> 3;
594 unsigned Tag = DTy.getTag();
596 // FIXME - Workaround for templates.
597 if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
601 // Map to main type, void will not have a type.
602 DIType FromTy = DTy.getTypeDerivedFrom();
603 AddType(DW_Unit, &Buffer, FromTy);
605 // Add name if not anonymous or intermediate type.
607 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
609 // Add size if non-zero (derived types might be zero-sized.)
611 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
613 // Add source line info if available and TyDesc is not a forward declaration.
614 if (!DTy.isForwardDecl())
615 AddSourceLine(&Buffer, &DTy);
618 /// ConstructTypeDIE - Construct type DIE from DICompositeType.
619 void DwarfDebug::ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
620 DICompositeType CTy) {
621 // Get core information.
625 uint64_t Size = CTy.getSizeInBits() >> 3;
626 unsigned Tag = CTy.getTag();
630 case dwarf::DW_TAG_vector_type:
631 case dwarf::DW_TAG_array_type:
632 ConstructArrayTypeDIE(DW_Unit, Buffer, &CTy);
634 case dwarf::DW_TAG_enumeration_type: {
635 DIArray Elements = CTy.getTypeArray();
637 // Add enumerators to enumeration type.
638 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
640 DIEnumerator Enum(Elements.getElement(i).getGV());
641 ElemDie = ConstructEnumTypeDIE(DW_Unit, &Enum);
642 Buffer.AddChild(ElemDie);
646 case dwarf::DW_TAG_subroutine_type: {
648 DIArray Elements = CTy.getTypeArray();
649 DIDescriptor RTy = Elements.getElement(0);
650 AddType(DW_Unit, &Buffer, DIType(RTy.getGV()));
652 // Add prototype flag.
653 AddUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
656 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
657 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
658 DIDescriptor Ty = Elements.getElement(i);
659 AddType(DW_Unit, Arg, DIType(Ty.getGV()));
660 Buffer.AddChild(Arg);
664 case dwarf::DW_TAG_structure_type:
665 case dwarf::DW_TAG_union_type:
666 case dwarf::DW_TAG_class_type: {
667 // Add elements to structure type.
668 DIArray Elements = CTy.getTypeArray();
670 // A forward struct declared type may not have elements available.
671 if (Elements.isNull())
674 // Add elements to structure type.
675 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
676 DIDescriptor Element = Elements.getElement(i);
678 if (Element.getTag() == dwarf::DW_TAG_subprogram)
679 ElemDie = CreateSubprogramDIE(DW_Unit,
680 DISubprogram(Element.getGV()));
682 ElemDie = CreateMemberDIE(DW_Unit,
683 DIDerivedType(Element.getGV()));
684 Buffer.AddChild(ElemDie);
687 // FIXME: We'd like an API to register additional attributes for the
688 // frontend to use while synthesizing, and then we'd use that api in clang
690 if (Name == "__block_literal_generic")
691 AddUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
693 unsigned RLang = CTy.getRunTimeLang();
695 AddUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
696 dwarf::DW_FORM_data1, RLang);
703 // Add name if not anonymous or intermediate type.
705 AddString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
707 if (Tag == dwarf::DW_TAG_enumeration_type ||
708 Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
709 // Add size if non-zero (derived types might be zero-sized.)
711 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
713 // Add zero size if it is not a forward declaration.
714 if (CTy.isForwardDecl())
715 AddUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
717 AddUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
720 // Add source line info if available.
721 if (!CTy.isForwardDecl())
722 AddSourceLine(&Buffer, &CTy);
726 /// ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
727 void DwarfDebug::ConstructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
728 int64_t L = SR.getLo();
729 int64_t H = SR.getHi();
730 DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
733 AddDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
735 AddSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
736 AddSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
739 Buffer.AddChild(DW_Subrange);
742 /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
743 void DwarfDebug::ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
744 DICompositeType *CTy) {
745 Buffer.setTag(dwarf::DW_TAG_array_type);
746 if (CTy->getTag() == dwarf::DW_TAG_vector_type)
747 AddUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
749 // Emit derived type.
750 AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
751 DIArray Elements = CTy->getTypeArray();
753 // Construct an anonymous type for index type.
754 DIE IdxBuffer(dwarf::DW_TAG_base_type);
755 AddUInt(&IdxBuffer, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
756 AddUInt(&IdxBuffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
757 dwarf::DW_ATE_signed);
758 DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
760 // Add subranges to array type.
761 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
762 DIDescriptor Element = Elements.getElement(i);
763 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
764 ConstructSubrangeDIE(Buffer, DISubrange(Element.getGV()), IndexTy);
768 /// ConstructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
769 DIE *DwarfDebug::ConstructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) {
770 DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
773 AddString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
774 int64_t Value = ETy->getEnumValue();
775 AddSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
779 /// CreateGlobalVariableDIE - Create new DIE using GV.
780 DIE *DwarfDebug::CreateGlobalVariableDIE(CompileUnit *DW_Unit,
781 const DIGlobalVariable &GV) {
782 DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
784 GV.getDisplayName(Name);
785 AddString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
786 std::string LinkageName;
787 GV.getLinkageName(LinkageName);
788 if (!LinkageName.empty()) {
789 // Skip special LLVM prefix that is used to inform the asm printer to not emit
790 // usual symbol prefix before the symbol name. This happens for Objective-C
791 // symbol names and symbol whose name is replaced using GCC's __asm__ attribute.
792 if (LinkageName[0] == 1)
793 LinkageName = &LinkageName[1];
794 AddString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
797 AddType(DW_Unit, GVDie, GV.getType());
798 if (!GV.isLocalToUnit())
799 AddUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
800 AddSourceLine(GVDie, &GV);
804 /// CreateMemberDIE - Create new member DIE.
805 DIE *DwarfDebug::CreateMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT){
806 DIE *MemberDie = new DIE(DT.getTag());
810 AddString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
812 AddType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
814 AddSourceLine(MemberDie, &DT);
816 uint64_t Size = DT.getSizeInBits();
817 uint64_t FieldSize = DT.getOriginalTypeSize();
819 if (Size != FieldSize) {
821 AddUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
822 AddUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
824 uint64_t Offset = DT.getOffsetInBits();
825 uint64_t FieldOffset = Offset;
826 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
827 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
828 FieldOffset = (HiMark - FieldSize);
829 Offset -= FieldOffset;
831 // Maybe we need to work from the other end.
832 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
833 AddUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
836 DIEBlock *Block = new DIEBlock();
837 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
838 AddUInt(Block, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
839 AddBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, Block);
841 if (DT.isProtected())
842 AddUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
843 dwarf::DW_ACCESS_protected);
844 else if (DT.isPrivate())
845 AddUInt(MemberDie, dwarf::DW_AT_accessibility, 0,
846 dwarf::DW_ACCESS_private);
851 /// CreateSubprogramDIE - Create new DIE using SP.
852 DIE *DwarfDebug::CreateSubprogramDIE(CompileUnit *DW_Unit,
853 const DISubprogram &SP,
856 DIE *SPDie = new DIE(dwarf::DW_TAG_subprogram);
860 AddString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
862 std::string LinkageName;
863 SP.getLinkageName(LinkageName);
864 if (!LinkageName.empty()) {
865 // Skip special LLVM prefix that is used to inform the asm printer to not emit
866 // usual symbol prefix before the symbol name. This happens for Objective-C
867 // symbol names and symbol whose name is replaced using GCC's __asm__ attribute.
868 if (LinkageName[0] == 1)
869 LinkageName = &LinkageName[1];
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 /// CreateDbgScopeVariable - Create a new scope variable.
927 DIE *DwarfDebug::CreateDbgScopeVariable(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 if (!DV->isInlinedFnVar()) {
960 // Variables for abstract instances of inlined functions don't get a
962 MachineLocation Location;
963 Location.set(RI->getFrameRegister(*MF),
964 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
965 AddAddress(VariableDie, dwarf::DW_AT_location, Location);
971 /// getOrCreateScope - Returns the scope associated with the given descriptor.
973 DbgScope *DwarfDebug::getOrCreateScope(GlobalVariable *V) {
974 DbgScope *&Slot = DbgScopeMap[V];
975 if (Slot) return Slot;
977 DbgScope *Parent = NULL;
980 // Don't create a new scope if we already created one for an inlined function.
981 DenseMap<const GlobalVariable *, DbgScope *>::iterator
982 II = AbstractInstanceRootMap.find(V);
983 if (II != AbstractInstanceRootMap.end())
984 return LexicalScopeStack.back();
986 if (!Block.isNull()) {
987 DIDescriptor ParentDesc = Block.getContext();
989 ParentDesc.isNull() ? NULL : getOrCreateScope(ParentDesc.getGV());
992 Slot = new DbgScope(Parent, DIDescriptor(V));
995 Parent->AddScope(Slot);
997 // First function is top level function.
998 FunctionDbgScope = Slot;
1003 /// ConstructDbgScope - Construct the components of a scope.
1005 void DwarfDebug::ConstructDbgScope(DbgScope *ParentScope,
1006 unsigned ParentStartID,
1007 unsigned ParentEndID,
1008 DIE *ParentDie, CompileUnit *Unit) {
1009 // Add variables to scope.
1010 SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
1011 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1012 DIE *VariableDie = CreateDbgScopeVariable(Variables[i], Unit);
1013 if (VariableDie) ParentDie->AddChild(VariableDie);
1016 // Add concrete instances to scope.
1017 SmallVector<DbgConcreteScope *, 8> &ConcreteInsts =
1018 ParentScope->getConcreteInsts();
1019 for (unsigned i = 0, N = ConcreteInsts.size(); i < N; ++i) {
1020 DbgConcreteScope *ConcreteInst = ConcreteInsts[i];
1021 DIE *Die = ConcreteInst->getDie();
1023 unsigned StartID = ConcreteInst->getStartLabelID();
1024 unsigned EndID = ConcreteInst->getEndLabelID();
1026 // Add the scope bounds.
1028 AddLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1029 DWLabel("label", StartID));
1031 AddLabel(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1032 DWLabel("func_begin", SubprogramCount));
1035 AddLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1036 DWLabel("label", EndID));
1038 AddLabel(Die, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1039 DWLabel("func_end", SubprogramCount));
1041 ParentDie->AddChild(Die);
1044 // Add nested scopes.
1045 SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
1046 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1047 // Define the Scope debug information entry.
1048 DbgScope *Scope = Scopes[j];
1050 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1051 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1053 // Ignore empty scopes.
1054 if (StartID == EndID && StartID != 0) continue;
1056 // Do not ignore inlined scopes even if they don't have any variables or
1058 if (Scope->getScopes().empty() && Scope->getVariables().empty() &&
1059 Scope->getConcreteInsts().empty())
1062 if (StartID == ParentStartID && EndID == ParentEndID) {
1063 // Just add stuff to the parent scope.
1064 ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
1066 DIE *ScopeDie = new DIE(dwarf::DW_TAG_lexical_block);
1068 // Add the scope bounds.
1070 AddLabel(ScopeDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1071 DWLabel("label", StartID));
1073 AddLabel(ScopeDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1074 DWLabel("func_begin", SubprogramCount));
1077 AddLabel(ScopeDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1078 DWLabel("label", EndID));
1080 AddLabel(ScopeDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1081 DWLabel("func_end", SubprogramCount));
1083 // Add the scope's contents.
1084 ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
1085 ParentDie->AddChild(ScopeDie);
1090 /// ConstructFunctionDbgScope - Construct the scope for the subprogram.
1092 void DwarfDebug::ConstructFunctionDbgScope(DbgScope *RootScope,
1093 bool AbstractScope) {
1094 // Exit if there is no root scope.
1095 if (!RootScope) return;
1096 DIDescriptor Desc = RootScope->getDesc();
1100 // Get the subprogram debug information entry.
1101 DISubprogram SPD(Desc.getGV());
1103 // Get the subprogram die.
1104 DIE *SPDie = ModuleCU->getDieMapSlotFor(SPD.getGV());
1105 assert(SPDie && "Missing subprogram descriptor");
1107 if (!AbstractScope) {
1108 // Add the function bounds.
1109 AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1110 DWLabel("func_begin", SubprogramCount));
1111 AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1112 DWLabel("func_end", SubprogramCount));
1113 MachineLocation Location(RI->getFrameRegister(*MF));
1114 AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1117 ConstructDbgScope(RootScope, 0, 0, SPDie, ModuleCU);
1120 /// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
1122 void DwarfDebug::ConstructDefaultDbgScope(MachineFunction *MF) {
1123 const char *FnName = MF->getFunction()->getNameStart();
1124 StringMap<DIE*> &Globals = ModuleCU->getGlobals();
1125 StringMap<DIE*>::iterator GI = Globals.find(FnName);
1126 if (GI != Globals.end()) {
1127 DIE *SPDie = GI->second;
1129 // Add the function bounds.
1130 AddLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1131 DWLabel("func_begin", SubprogramCount));
1132 AddLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1133 DWLabel("func_end", SubprogramCount));
1135 MachineLocation Location(RI->getFrameRegister(*MF));
1136 AddAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1140 /// GetOrCreateSourceID - Look up the source id with the given directory and
1141 /// source file names. If none currently exists, create a new id and insert it
1142 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1144 unsigned DwarfDebug::GetOrCreateSourceID(const std::string &DirName,
1145 const std::string &FileName) {
1147 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1148 if (DI != DirectoryIdMap.end()) {
1149 DId = DI->getValue();
1151 DId = DirectoryNames.size() + 1;
1152 DirectoryIdMap[DirName] = DId;
1153 DirectoryNames.push_back(DirName);
1157 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1158 if (FI != SourceFileIdMap.end()) {
1159 FId = FI->getValue();
1161 FId = SourceFileNames.size() + 1;
1162 SourceFileIdMap[FileName] = FId;
1163 SourceFileNames.push_back(FileName);
1166 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1167 SourceIdMap.find(std::make_pair(DId, FId));
1168 if (SI != SourceIdMap.end())
1171 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
1172 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1173 SourceIds.push_back(std::make_pair(DId, FId));
1178 void DwarfDebug::ConstructCompileUnit(GlobalVariable *GV) {
1179 DICompileUnit DIUnit(GV);
1180 std::string Dir, FN, Prod;
1181 unsigned ID = GetOrCreateSourceID(DIUnit.getDirectory(Dir),
1182 DIUnit.getFilename(FN));
1184 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1185 AddSectionOffset(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
1186 DWLabel("section_line", 0), DWLabel("section_line", 0),
1188 AddString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1189 DIUnit.getProducer(Prod));
1190 AddUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1191 DIUnit.getLanguage());
1192 AddString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1195 AddString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1196 if (DIUnit.isOptimized())
1197 AddUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1200 DIUnit.getFlags(Flags);
1202 AddString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1204 unsigned RVer = DIUnit.getRunTimeVersion();
1206 AddUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1207 dwarf::DW_FORM_data1, RVer);
1209 CompileUnit *Unit = new CompileUnit(ID, Die);
1210 if (!ModuleCU && DIUnit.isMain()) {
1211 // Use first compile unit marked as isMain as the compile unit
1216 CompileUnitMap[DIUnit.getGV()] = Unit;
1217 CompileUnits.push_back(Unit);
1220 void DwarfDebug::ConstructGlobalVariableDIE(GlobalVariable *GV) {
1221 DIGlobalVariable DI_GV(GV);
1223 // Check for pre-existence.
1224 DIE *&Slot = ModuleCU->getDieMapSlotFor(DI_GV.getGV());
1228 DIE *VariableDie = CreateGlobalVariableDIE(ModuleCU, DI_GV);
1231 DIEBlock *Block = new DIEBlock();
1232 AddUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1234 AddObjectLabel(Block, 0, dwarf::DW_FORM_udata,
1235 Asm->getGlobalLinkName(DI_GV.getGlobal(), GLN));
1236 AddBlock(VariableDie, dwarf::DW_AT_location, 0, Block);
1241 // Add to context owner.
1242 ModuleCU->getDie()->AddChild(VariableDie);
1244 // Expose as global. FIXME - need to check external flag.
1246 ModuleCU->AddGlobal(DI_GV.getName(Name), VariableDie);
1250 void DwarfDebug::ConstructSubprogram(GlobalVariable *GV) {
1251 DISubprogram SP(GV);
1253 // Check for pre-existence.
1254 DIE *&Slot = ModuleCU->getDieMapSlotFor(GV);
1258 if (!SP.isDefinition())
1259 // This is a method declaration which will be handled while constructing
1263 DIE *SubprogramDie = CreateSubprogramDIE(ModuleCU, SP);
1266 Slot = SubprogramDie;
1268 // Add to context owner.
1269 ModuleCU->getDie()->AddChild(SubprogramDie);
1271 // Expose as global.
1273 ModuleCU->AddGlobal(SP.getName(Name), SubprogramDie);
1277 /// BeginModule - Emit all Dwarf sections that should come prior to the
1278 /// content. Create global DIEs and emit initial debug info sections.
1279 /// This is inovked by the target AsmPrinter.
1280 void DwarfDebug::BeginModule(Module *M, MachineModuleInfo *mmi) {
1283 if (TimePassesIsEnabled)
1284 DebugTimer->startTimer();
1286 SmallVector<GlobalVariable *, 2> CUs;
1287 SmallVector<GlobalVariable *, 4> GVs;
1288 SmallVector<GlobalVariable *, 4> SPs;
1289 CollectDebugInfoAnchors(*M, CUs, GVs, SPs);
1291 // Create all the compile unit DIEs.
1292 for (SmallVector<GlobalVariable *, 2>::iterator I = CUs.begin(),
1293 E = CUs.end(); I != E; ++I)
1294 ConstructCompileUnit(*I);
1296 if (CompileUnits.empty()) {
1297 if (TimePassesIsEnabled)
1298 DebugTimer->stopTimer();
1303 // If main compile unit for this module is not seen than randomly
1304 // select first compile unit.
1306 ModuleCU = CompileUnits[0];
1308 // If there is not any debug info available for any global variables and any
1309 // subprograms then there is not any debug info to emit.
1310 if (GVs.empty() && SPs.empty()) {
1311 if (TimePassesIsEnabled)
1312 DebugTimer->stopTimer();
1317 // Create DIEs for each of the externally visible global variables.
1318 for (SmallVector<GlobalVariable *, 4>::iterator I = GVs.begin(),
1319 E = GVs.end(); I != E; ++I)
1320 ConstructGlobalVariableDIE(*I);
1322 // Create DIEs for each of the externally visible subprograms.
1323 for (SmallVector<GlobalVariable *, 4>::iterator I = SPs.begin(),
1324 E = SPs.end(); I != E; ++I)
1325 ConstructSubprogram(*I);
1329 MMI->setDebugInfoAvailability(true);
1331 // Prime section data.
1332 SectionMap.insert(TAI->getTextSection());
1334 // Print out .file directives to specify files for .loc directives. These are
1335 // printed out early so that they precede any .loc directives.
1336 if (TAI->hasDotLocAndDotFile()) {
1337 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
1338 // Remember source id starts at 1.
1339 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
1340 sys::Path FullPath(getSourceDirectoryName(Id.first));
1342 FullPath.appendComponent(getSourceFileName(Id.second));
1343 assert(AppendOk && "Could not append filename to directory!");
1345 Asm->EmitFile(i, FullPath.toString());
1350 // Emit initial sections
1353 if (TimePassesIsEnabled)
1354 DebugTimer->stopTimer();
1357 /// EndModule - Emit all Dwarf sections that should come after the content.
1359 void DwarfDebug::EndModule() {
1360 if (!ShouldEmitDwarfDebug())
1363 if (TimePassesIsEnabled)
1364 DebugTimer->startTimer();
1366 // Standard sections final addresses.
1367 Asm->SwitchToSection(TAI->getTextSection());
1368 EmitLabel("text_end", 0);
1369 Asm->SwitchToSection(TAI->getDataSection());
1370 EmitLabel("data_end", 0);
1372 // End text sections.
1373 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1374 Asm->SwitchToSection(SectionMap[i]);
1375 EmitLabel("section_end", i);
1378 // Emit common frame information.
1379 EmitCommonDebugFrame();
1381 // Emit function debug frame information
1382 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1383 E = DebugFrames.end(); I != E; ++I)
1384 EmitFunctionDebugFrame(*I);
1386 // Compute DIE offsets and sizes.
1389 // Emit all the DIEs into a debug info section
1392 // Corresponding abbreviations into a abbrev section.
1393 EmitAbbreviations();
1395 // Emit source line correspondence into a debug line section.
1398 // Emit info into a debug pubnames section.
1399 EmitDebugPubNames();
1401 // Emit info into a debug str section.
1404 // Emit info into a debug loc section.
1407 // Emit info into a debug aranges section.
1410 // Emit info into a debug ranges section.
1413 // Emit info into a debug macinfo section.
1416 // Emit inline info.
1417 EmitDebugInlineInfo();
1419 if (TimePassesIsEnabled)
1420 DebugTimer->stopTimer();
1423 /// BeginFunction - Gather pre-function debug information. Assumes being
1424 /// emitted immediately after the function entry point.
1425 void DwarfDebug::BeginFunction(MachineFunction *MF) {
1428 if (!ShouldEmitDwarfDebug()) return;
1430 if (TimePassesIsEnabled)
1431 DebugTimer->startTimer();
1433 // Begin accumulating function debug information.
1434 MMI->BeginFunction(MF);
1436 // Assumes in correct section after the entry point.
1437 EmitLabel("func_begin", ++SubprogramCount);
1439 // Emit label for the implicitly defined dbg.stoppoint at the start of the
1441 DebugLoc FDL = MF->getDefaultDebugLoc();
1442 if (!FDL.isUnknown()) {
1443 DebugLocTuple DLT = MF->getDebugLocTuple(FDL);
1444 unsigned LabelID = RecordSourceLine(DLT.Line, DLT.Col,
1445 DICompileUnit(DLT.CompileUnit));
1446 Asm->printLabel(LabelID);
1449 if (TimePassesIsEnabled)
1450 DebugTimer->stopTimer();
1453 /// EndFunction - Gather and emit post-function debug information.
1455 void DwarfDebug::EndFunction(MachineFunction *MF) {
1456 if (!ShouldEmitDwarfDebug()) return;
1458 if (TimePassesIsEnabled)
1459 DebugTimer->startTimer();
1461 // Define end label for subprogram.
1462 EmitLabel("func_end", SubprogramCount);
1464 // Get function line info.
1465 if (!Lines.empty()) {
1466 // Get section line info.
1467 unsigned ID = SectionMap.insert(Asm->CurrentSection_);
1468 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
1469 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
1470 // Append the function info to section info.
1471 SectionLineInfos.insert(SectionLineInfos.end(),
1472 Lines.begin(), Lines.end());
1475 // Construct the DbgScope for abstract instances.
1476 for (SmallVector<DbgScope *, 32>::iterator
1477 I = AbstractInstanceRootList.begin(),
1478 E = AbstractInstanceRootList.end(); I != E; ++I)
1479 ConstructFunctionDbgScope(*I);
1481 // Construct scopes for subprogram.
1482 if (FunctionDbgScope)
1483 ConstructFunctionDbgScope(FunctionDbgScope);
1485 // FIXME: This is wrong. We are essentially getting past a problem with
1486 // debug information not being able to handle unreachable blocks that have
1487 // debug information in them. In particular, those unreachable blocks that
1488 // have "region end" info in them. That situation results in the "root
1489 // scope" not being created. If that's the case, then emit a "default"
1490 // scope, i.e., one that encompasses the whole function. This isn't
1491 // desirable. And a better way of handling this (and all of the debugging
1492 // information) needs to be explored.
1493 ConstructDefaultDbgScope(MF);
1495 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
1496 MMI->getFrameMoves()));
1499 if (FunctionDbgScope) {
1500 delete FunctionDbgScope;
1501 DbgScopeMap.clear();
1502 DbgAbstractScopeMap.clear();
1503 DbgConcreteScopeMap.clear();
1504 InlinedVariableScopes.clear();
1505 FunctionDbgScope = NULL;
1506 LexicalScopeStack.clear();
1507 AbstractInstanceRootList.clear();
1508 AbstractInstanceRootMap.clear();
1513 if (TimePassesIsEnabled)
1514 DebugTimer->stopTimer();
1517 /// RecordSourceLine - Records location information and associates it with a
1518 /// label. Returns a unique label ID used to generate a label and provide
1519 /// correspondence to the source line list.
1520 unsigned DwarfDebug::RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
1521 if (TimePassesIsEnabled)
1522 DebugTimer->startTimer();
1524 CompileUnit *Unit = CompileUnitMap[V];
1525 assert(Unit && "Unable to find CompileUnit");
1526 unsigned ID = MMI->NextLabelID();
1527 Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
1529 if (TimePassesIsEnabled)
1530 DebugTimer->stopTimer();
1535 /// RecordSourceLine - Records location information and associates it with a
1536 /// label. Returns a unique label ID used to generate a label and provide
1537 /// correspondence to the source line list.
1538 unsigned DwarfDebug::RecordSourceLine(unsigned Line, unsigned Col,
1540 if (TimePassesIsEnabled)
1541 DebugTimer->startTimer();
1543 std::string Dir, Fn;
1544 unsigned Src = GetOrCreateSourceID(CU.getDirectory(Dir),
1545 CU.getFilename(Fn));
1546 unsigned ID = MMI->NextLabelID();
1547 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
1549 if (TimePassesIsEnabled)
1550 DebugTimer->stopTimer();
1555 /// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
1556 /// timed. Look up the source id with the given directory and source file
1557 /// names. If none currently exists, create a new id and insert it in the
1558 /// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
1560 unsigned DwarfDebug::getOrCreateSourceID(const std::string &DirName,
1561 const std::string &FileName) {
1562 if (TimePassesIsEnabled)
1563 DebugTimer->startTimer();
1565 unsigned SrcId = GetOrCreateSourceID(DirName, FileName);
1567 if (TimePassesIsEnabled)
1568 DebugTimer->stopTimer();
1573 /// RecordRegionStart - Indicate the start of a region.
1574 unsigned DwarfDebug::RecordRegionStart(GlobalVariable *V) {
1575 if (TimePassesIsEnabled)
1576 DebugTimer->startTimer();
1578 DbgScope *Scope = getOrCreateScope(V);
1579 unsigned ID = MMI->NextLabelID();
1580 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
1581 LexicalScopeStack.push_back(Scope);
1583 if (TimePassesIsEnabled)
1584 DebugTimer->stopTimer();
1589 /// RecordRegionEnd - Indicate the end of a region.
1590 unsigned DwarfDebug::RecordRegionEnd(GlobalVariable *V) {
1591 if (TimePassesIsEnabled)
1592 DebugTimer->startTimer();
1594 DbgScope *Scope = getOrCreateScope(V);
1595 unsigned ID = MMI->NextLabelID();
1596 Scope->setEndLabelID(ID);
1597 // FIXME : region.end() may not be in the last basic block.
1598 // For now, do not pop last lexical scope because next basic
1599 // block may start new inlined function's body.
1600 unsigned LSSize = LexicalScopeStack.size();
1601 if (LSSize != 0 && LSSize != 1)
1602 LexicalScopeStack.pop_back();
1604 if (TimePassesIsEnabled)
1605 DebugTimer->stopTimer();
1610 /// RecordVariable - Indicate the declaration of a local variable.
1611 void DwarfDebug::RecordVariable(GlobalVariable *GV, unsigned FrameIndex,
1612 const MachineInstr *MI) {
1613 if (TimePassesIsEnabled)
1614 DebugTimer->startTimer();
1616 DIDescriptor Desc(GV);
1617 DbgScope *Scope = NULL;
1618 bool InlinedFnVar = false;
1620 if (Desc.getTag() == dwarf::DW_TAG_variable) {
1621 // GV is a global variable.
1622 DIGlobalVariable DG(GV);
1623 Scope = getOrCreateScope(DG.getContext().getGV());
1625 DenseMap<const MachineInstr *, DbgScope *>::iterator
1626 SI = InlinedVariableScopes.find(MI);
1628 if (SI != InlinedVariableScopes.end()) {
1629 // or GV is an inlined local variable.
1631 InlinedFnVar = true;
1634 GlobalVariable *V = DV.getContext().getGV();
1636 // or GV is a local variable.
1637 Scope = getOrCreateScope(V);
1641 assert(Scope && "Unable to find the variable's scope");
1642 DbgVariable *DV = new DbgVariable(DIVariable(GV), FrameIndex, InlinedFnVar);
1643 Scope->AddVariable(DV);
1645 if (TimePassesIsEnabled)
1646 DebugTimer->stopTimer();
1649 //// RecordInlinedFnStart - Indicate the start of inlined subroutine.
1650 unsigned DwarfDebug::RecordInlinedFnStart(DISubprogram &SP, DICompileUnit CU,
1651 unsigned Line, unsigned Col) {
1652 unsigned LabelID = MMI->NextLabelID();
1654 if (!TAI->doesDwarfUsesInlineInfoSection())
1657 if (TimePassesIsEnabled)
1658 DebugTimer->startTimer();
1660 GlobalVariable *GV = SP.getGV();
1661 DenseMap<const GlobalVariable *, DbgScope *>::iterator
1662 II = AbstractInstanceRootMap.find(GV);
1664 if (II == AbstractInstanceRootMap.end()) {
1665 // Create an abstract instance entry for this inlined function if it doesn't
1667 DbgScope *Scope = new DbgScope(NULL, DIDescriptor(GV));
1669 // Get the compile unit context.
1670 DIE *SPDie = ModuleCU->getDieMapSlotFor(GV);
1672 SPDie = CreateSubprogramDIE(ModuleCU, SP, false, true);
1674 // Mark as being inlined. This makes this subprogram entry an abstract
1676 // FIXME: Our debugger doesn't care about the value of DW_AT_inline, only
1677 // that it's defined. That probably won't change in the future. However,
1678 // this could be more elegant.
1679 AddUInt(SPDie, dwarf::DW_AT_inline, 0, dwarf::DW_INL_declared_not_inlined);
1681 // Keep track of the abstract scope for this function.
1682 DbgAbstractScopeMap[GV] = Scope;
1684 AbstractInstanceRootMap[GV] = Scope;
1685 AbstractInstanceRootList.push_back(Scope);
1688 // Create a concrete inlined instance for this inlined function.
1689 DbgConcreteScope *ConcreteScope = new DbgConcreteScope(DIDescriptor(GV));
1690 DIE *ScopeDie = new DIE(dwarf::DW_TAG_inlined_subroutine);
1691 ScopeDie->setAbstractCompileUnit(ModuleCU);
1693 DIE *Origin = ModuleCU->getDieMapSlotFor(GV);
1694 AddDIEEntry(ScopeDie, dwarf::DW_AT_abstract_origin,
1695 dwarf::DW_FORM_ref4, Origin);
1696 AddUInt(ScopeDie, dwarf::DW_AT_call_file, 0, ModuleCU->getID());
1697 AddUInt(ScopeDie, dwarf::DW_AT_call_line, 0, Line);
1698 AddUInt(ScopeDie, dwarf::DW_AT_call_column, 0, Col);
1700 ConcreteScope->setDie(ScopeDie);
1701 ConcreteScope->setStartLabelID(LabelID);
1702 MMI->RecordUsedDbgLabel(LabelID);
1704 LexicalScopeStack.back()->AddConcreteInst(ConcreteScope);
1706 // Keep track of the concrete scope that's inlined into this function.
1707 DenseMap<GlobalVariable *, SmallVector<DbgScope *, 8> >::iterator
1708 SI = DbgConcreteScopeMap.find(GV);
1710 if (SI == DbgConcreteScopeMap.end())
1711 DbgConcreteScopeMap[GV].push_back(ConcreteScope);
1713 SI->second.push_back(ConcreteScope);
1715 // Track the start label for this inlined function.
1716 DenseMap<GlobalVariable *, SmallVector<unsigned, 4> >::iterator
1717 I = InlineInfo.find(GV);
1719 if (I == InlineInfo.end())
1720 InlineInfo[GV].push_back(LabelID);
1722 I->second.push_back(LabelID);
1724 if (TimePassesIsEnabled)
1725 DebugTimer->stopTimer();
1730 /// RecordInlinedFnEnd - Indicate the end of inlined subroutine.
1731 unsigned DwarfDebug::RecordInlinedFnEnd(DISubprogram &SP) {
1732 if (!TAI->doesDwarfUsesInlineInfoSection())
1735 if (TimePassesIsEnabled)
1736 DebugTimer->startTimer();
1738 GlobalVariable *GV = SP.getGV();
1739 DenseMap<GlobalVariable *, SmallVector<DbgScope *, 8> >::iterator
1740 I = DbgConcreteScopeMap.find(GV);
1742 if (I == DbgConcreteScopeMap.end()) {
1743 // FIXME: Can this situation actually happen? And if so, should it?
1744 if (TimePassesIsEnabled)
1745 DebugTimer->stopTimer();
1750 SmallVector<DbgScope *, 8> &Scopes = I->second;
1751 if (Scopes.empty()) {
1752 // Returned ID is 0 if this is unbalanced "end of inlined
1753 // scope". This could happen if optimizer eats dbg intrinsics
1754 // or "beginning of inlined scope" is not recoginized due to
1755 // missing location info. In such cases, ignore this region.end.
1759 DbgScope *Scope = Scopes.back(); Scopes.pop_back();
1760 unsigned ID = MMI->NextLabelID();
1761 MMI->RecordUsedDbgLabel(ID);
1762 Scope->setEndLabelID(ID);
1764 if (TimePassesIsEnabled)
1765 DebugTimer->stopTimer();
1770 /// RecordVariableScope - Record scope for the variable declared by
1771 /// DeclareMI. DeclareMI must describe TargetInstrInfo::DECLARE. Record scopes
1772 /// for only inlined subroutine variables. Other variables's scopes are
1773 /// determined during RecordVariable().
1774 void DwarfDebug::RecordVariableScope(DIVariable &DV,
1775 const MachineInstr *DeclareMI) {
1776 if (TimePassesIsEnabled)
1777 DebugTimer->startTimer();
1779 DISubprogram SP(DV.getContext().getGV());
1782 if (TimePassesIsEnabled)
1783 DebugTimer->stopTimer();
1788 DenseMap<GlobalVariable *, DbgScope *>::iterator
1789 I = DbgAbstractScopeMap.find(SP.getGV());
1790 if (I != DbgAbstractScopeMap.end())
1791 InlinedVariableScopes[DeclareMI] = I->second;
1793 if (TimePassesIsEnabled)
1794 DebugTimer->stopTimer();
1797 //===----------------------------------------------------------------------===//
1799 //===----------------------------------------------------------------------===//
1801 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
1803 unsigned DwarfDebug::SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
1804 // Get the children.
1805 const std::vector<DIE *> &Children = Die->getChildren();
1807 // If not last sibling and has children then add sibling offset attribute.
1808 if (!Last && !Children.empty()) Die->AddSiblingOffset();
1810 // Record the abbreviation.
1811 AssignAbbrevNumber(Die->getAbbrev());
1813 // Get the abbreviation for this DIE.
1814 unsigned AbbrevNumber = Die->getAbbrevNumber();
1815 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1818 Die->setOffset(Offset);
1820 // Start the size with the size of abbreviation code.
1821 Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
1823 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1824 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1826 // Size the DIE attribute values.
1827 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1828 // Size attribute value.
1829 Offset += Values[i]->SizeOf(TD, AbbrevData[i].getForm());
1831 // Size the DIE children if any.
1832 if (!Children.empty()) {
1833 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1834 "Children flag not set");
1836 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1837 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
1839 // End of children marker.
1840 Offset += sizeof(int8_t);
1843 Die->setSize(Offset - Die->getOffset());
1847 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
1849 void DwarfDebug::SizeAndOffsets() {
1850 // Compute size of compile unit header.
1851 static unsigned Offset =
1852 sizeof(int32_t) + // Length of Compilation Unit Info
1853 sizeof(int16_t) + // DWARF version number
1854 sizeof(int32_t) + // Offset Into Abbrev. Section
1855 sizeof(int8_t); // Pointer Size (in bytes)
1857 SizeAndOffsetDie(ModuleCU->getDie(), Offset, true);
1858 CompileUnitOffsets[ModuleCU] = 0;
1861 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
1862 /// tools to recognize the object file contains Dwarf information.
1863 void DwarfDebug::EmitInitial() {
1864 // Check to see if we already emitted intial headers.
1865 if (didInitial) return;
1868 // Dwarf sections base addresses.
1869 if (TAI->doesDwarfRequireFrameSection()) {
1870 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1871 EmitLabel("section_debug_frame", 0);
1874 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
1875 EmitLabel("section_info", 0);
1876 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
1877 EmitLabel("section_abbrev", 0);
1878 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
1879 EmitLabel("section_aranges", 0);
1881 if (const char *LineInfoDirective = TAI->getDwarfMacroInfoSection()) {
1882 Asm->SwitchToDataSection(LineInfoDirective);
1883 EmitLabel("section_macinfo", 0);
1886 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
1887 EmitLabel("section_line", 0);
1888 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
1889 EmitLabel("section_loc", 0);
1890 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
1891 EmitLabel("section_pubnames", 0);
1892 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
1893 EmitLabel("section_str", 0);
1894 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
1895 EmitLabel("section_ranges", 0);
1897 Asm->SwitchToSection(TAI->getTextSection());
1898 EmitLabel("text_begin", 0);
1899 Asm->SwitchToSection(TAI->getDataSection());
1900 EmitLabel("data_begin", 0);
1903 /// EmitDIE - Recusively Emits a debug information entry.
1905 void DwarfDebug::EmitDIE(DIE *Die) {
1906 // Get the abbreviation for this DIE.
1907 unsigned AbbrevNumber = Die->getAbbrevNumber();
1908 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1912 // Emit the code (index) for the abbreviation.
1913 Asm->EmitULEB128Bytes(AbbrevNumber);
1915 if (Asm->isVerbose())
1916 Asm->EOL(std::string("Abbrev [" +
1917 utostr(AbbrevNumber) +
1918 "] 0x" + utohexstr(Die->getOffset()) +
1919 ":0x" + utohexstr(Die->getSize()) + " " +
1920 dwarf::TagString(Abbrev->getTag())));
1924 SmallVector<DIEValue*, 32> &Values = Die->getValues();
1925 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1927 // Emit the DIE attribute values.
1928 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1929 unsigned Attr = AbbrevData[i].getAttribute();
1930 unsigned Form = AbbrevData[i].getForm();
1931 assert(Form && "Too many attributes for DIE (check abbreviation)");
1934 case dwarf::DW_AT_sibling:
1935 Asm->EmitInt32(Die->SiblingOffset());
1937 case dwarf::DW_AT_abstract_origin: {
1938 DIEEntry *E = cast<DIEEntry>(Values[i]);
1939 DIE *Origin = E->getEntry();
1941 CompileUnitOffsets[Die->getAbstractCompileUnit()] +
1942 Origin->getOffset();
1944 Asm->EmitInt32(Addr);
1948 // Emit an attribute using the defined form.
1949 Values[i]->EmitValue(this, Form);
1953 Asm->EOL(dwarf::AttributeString(Attr));
1956 // Emit the DIE children if any.
1957 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1958 const std::vector<DIE *> &Children = Die->getChildren();
1960 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1961 EmitDIE(Children[j]);
1963 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
1967 /// EmitDebugInfo / EmitDebugInfoPerCU - Emit the debug info section.
1969 void DwarfDebug::EmitDebugInfoPerCU(CompileUnit *Unit) {
1970 DIE *Die = Unit->getDie();
1972 // Emit the compile units header.
1973 EmitLabel("info_begin", Unit->getID());
1975 // Emit size of content not including length itself
1976 unsigned ContentSize = Die->getSize() +
1977 sizeof(int16_t) + // DWARF version number
1978 sizeof(int32_t) + // Offset Into Abbrev. Section
1979 sizeof(int8_t) + // Pointer Size (in bytes)
1980 sizeof(int32_t); // FIXME - extra pad for gdb bug.
1982 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
1983 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
1984 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
1985 Asm->EOL("Offset Into Abbrev. Section");
1986 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
1989 // FIXME - extra padding for gdb bug.
1990 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1991 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1992 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1993 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
1994 EmitLabel("info_end", Unit->getID());
1999 void DwarfDebug::EmitDebugInfo() {
2000 // Start debug info section.
2001 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2003 EmitDebugInfoPerCU(ModuleCU);
2006 /// EmitAbbreviations - Emit the abbreviation section.
2008 void DwarfDebug::EmitAbbreviations() const {
2009 // Check to see if it is worth the effort.
2010 if (!Abbreviations.empty()) {
2011 // Start the debug abbrev section.
2012 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2014 EmitLabel("abbrev_begin", 0);
2016 // For each abbrevation.
2017 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2018 // Get abbreviation data
2019 const DIEAbbrev *Abbrev = Abbreviations[i];
2021 // Emit the abbrevations code (base 1 index.)
2022 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2023 Asm->EOL("Abbreviation Code");
2025 // Emit the abbreviations data.
2031 // Mark end of abbreviations.
2032 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2034 EmitLabel("abbrev_end", 0);
2039 /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
2040 /// the line matrix.
2042 void DwarfDebug::EmitEndOfLineMatrix(unsigned SectionEnd) {
2043 // Define last address of section.
2044 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2045 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2046 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2047 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2049 // Mark end of matrix.
2050 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2051 Asm->EmitULEB128Bytes(1); Asm->EOL();
2052 Asm->EmitInt8(1); Asm->EOL();
2055 /// EmitDebugLines - Emit source line information.
2057 void DwarfDebug::EmitDebugLines() {
2058 // If the target is using .loc/.file, the assembler will be emitting the
2059 // .debug_line table automatically.
2060 if (TAI->hasDotLocAndDotFile())
2063 // Minimum line delta, thus ranging from -10..(255-10).
2064 const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
2065 // Maximum line delta, thus ranging from -10..(255-10).
2066 const int MaxLineDelta = 255 + MinLineDelta;
2068 // Start the dwarf line section.
2069 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2071 // Construct the section header.
2072 EmitDifference("line_end", 0, "line_begin", 0, true);
2073 Asm->EOL("Length of Source Line Info");
2074 EmitLabel("line_begin", 0);
2076 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF version number");
2078 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2079 Asm->EOL("Prolog Length");
2080 EmitLabel("line_prolog_begin", 0);
2082 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2084 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2086 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2088 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2090 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2092 // Line number standard opcode encodings argument count
2093 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2094 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2095 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2096 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2097 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2098 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2099 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2100 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2101 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2103 // Emit directories.
2104 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2105 Asm->EmitString(getSourceDirectoryName(DI));
2106 Asm->EOL("Directory");
2109 Asm->EmitInt8(0); Asm->EOL("End of directories");
2112 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2113 // Remember source id starts at 1.
2114 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2115 Asm->EmitString(getSourceFileName(Id.second));
2117 Asm->EmitULEB128Bytes(Id.first);
2118 Asm->EOL("Directory #");
2119 Asm->EmitULEB128Bytes(0);
2120 Asm->EOL("Mod date");
2121 Asm->EmitULEB128Bytes(0);
2122 Asm->EOL("File size");
2125 Asm->EmitInt8(0); Asm->EOL("End of files");
2127 EmitLabel("line_prolog_end", 0);
2129 // A sequence for each text section.
2130 unsigned SecSrcLinesSize = SectionSourceLines.size();
2132 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2133 // Isolate current sections line info.
2134 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2136 if (Asm->isVerbose()) {
2137 const Section* S = SectionMap[j + 1];
2138 O << '\t' << TAI->getCommentString() << " Section"
2139 << S->getName() << '\n';
2144 // Dwarf assumes we start with first line of first source file.
2145 unsigned Source = 1;
2148 // Construct rows of the address, source, line, column matrix.
2149 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2150 const SrcLineInfo &LineInfo = LineInfos[i];
2151 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2152 if (!LabelID) continue;
2154 if (!Asm->isVerbose())
2157 std::pair<unsigned, unsigned> SourceID =
2158 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2159 O << '\t' << TAI->getCommentString() << ' '
2160 << getSourceDirectoryName(SourceID.first) << ' '
2161 << getSourceFileName(SourceID.second)
2162 <<" :" << utostr_32(LineInfo.getLine()) << '\n';
2165 // Define the line address.
2166 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2167 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2168 Asm->EmitInt8(dwarf::DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2169 EmitReference("label", LabelID); Asm->EOL("Location label");
2171 // If change of source, then switch to the new source.
2172 if (Source != LineInfo.getSourceID()) {
2173 Source = LineInfo.getSourceID();
2174 Asm->EmitInt8(dwarf::DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2175 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2178 // If change of line.
2179 if (Line != LineInfo.getLine()) {
2180 // Determine offset.
2181 int Offset = LineInfo.getLine() - Line;
2182 int Delta = Offset - MinLineDelta;
2185 Line = LineInfo.getLine();
2187 // If delta is small enough and in range...
2188 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2189 // ... then use fast opcode.
2190 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2192 // ... otherwise use long hand.
2193 Asm->EmitInt8(dwarf::DW_LNS_advance_line);
2194 Asm->EOL("DW_LNS_advance_line");
2195 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2196 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2199 // Copy the previous row (different address or source)
2200 Asm->EmitInt8(dwarf::DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2204 EmitEndOfLineMatrix(j + 1);
2207 if (SecSrcLinesSize == 0)
2208 // Because we're emitting a debug_line section, we still need a line
2209 // table. The linker and friends expect it to exist. If there's nothing to
2210 // put into it, emit an empty table.
2211 EmitEndOfLineMatrix(1);
2213 EmitLabel("line_end", 0);
2217 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2219 void DwarfDebug::EmitCommonDebugFrame() {
2220 if (!TAI->doesDwarfRequireFrameSection())
2224 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2225 TargetFrameInfo::StackGrowsUp ?
2226 TD->getPointerSize() : -TD->getPointerSize();
2228 // Start the dwarf frame section.
2229 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2231 EmitLabel("debug_frame_common", 0);
2232 EmitDifference("debug_frame_common_end", 0,
2233 "debug_frame_common_begin", 0, true);
2234 Asm->EOL("Length of Common Information Entry");
2236 EmitLabel("debug_frame_common_begin", 0);
2237 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
2238 Asm->EOL("CIE Identifier Tag");
2239 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
2240 Asm->EOL("CIE Version");
2241 Asm->EmitString("");
2242 Asm->EOL("CIE Augmentation");
2243 Asm->EmitULEB128Bytes(1);
2244 Asm->EOL("CIE Code Alignment Factor");
2245 Asm->EmitSLEB128Bytes(stackGrowth);
2246 Asm->EOL("CIE Data Alignment Factor");
2247 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2248 Asm->EOL("CIE RA Column");
2250 std::vector<MachineMove> Moves;
2251 RI->getInitialFrameState(Moves);
2253 EmitFrameMoves(NULL, 0, Moves, false);
2255 Asm->EmitAlignment(2, 0, 0, false);
2256 EmitLabel("debug_frame_common_end", 0);
2261 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2264 DwarfDebug::EmitFunctionDebugFrame(const FunctionDebugFrameInfo&DebugFrameInfo){
2265 if (!TAI->doesDwarfRequireFrameSection())
2268 // Start the dwarf frame section.
2269 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2271 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2272 "debug_frame_begin", DebugFrameInfo.Number, true);
2273 Asm->EOL("Length of Frame Information Entry");
2275 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2277 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2279 Asm->EOL("FDE CIE offset");
2281 EmitReference("func_begin", DebugFrameInfo.Number);
2282 Asm->EOL("FDE initial location");
2283 EmitDifference("func_end", DebugFrameInfo.Number,
2284 "func_begin", DebugFrameInfo.Number);
2285 Asm->EOL("FDE address range");
2287 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
2290 Asm->EmitAlignment(2, 0, 0, false);
2291 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2296 void DwarfDebug::EmitDebugPubNamesPerCU(CompileUnit *Unit) {
2297 EmitDifference("pubnames_end", Unit->getID(),
2298 "pubnames_begin", Unit->getID(), true);
2299 Asm->EOL("Length of Public Names Info");
2301 EmitLabel("pubnames_begin", Unit->getID());
2303 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("DWARF Version");
2305 EmitSectionOffset("info_begin", "section_info",
2306 Unit->getID(), 0, true, false);
2307 Asm->EOL("Offset of Compilation Unit Info");
2309 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
2311 Asm->EOL("Compilation Unit Length");
2313 StringMap<DIE*> &Globals = Unit->getGlobals();
2314 for (StringMap<DIE*>::const_iterator
2315 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2316 const char *Name = GI->getKeyData();
2317 DIE * Entity = GI->second;
2319 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2320 Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
2323 Asm->EmitInt32(0); Asm->EOL("End Mark");
2324 EmitLabel("pubnames_end", Unit->getID());
2329 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2331 void DwarfDebug::EmitDebugPubNames() {
2332 // Start the dwarf pubnames section.
2333 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2335 EmitDebugPubNamesPerCU(ModuleCU);
2338 /// EmitDebugStr - Emit visible names into a debug str section.
2340 void DwarfDebug::EmitDebugStr() {
2341 // Check to see if it is worth the effort.
2342 if (!StringPool.empty()) {
2343 // Start the dwarf str section.
2344 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2346 // For each of strings in the string pool.
2347 for (unsigned StringID = 1, N = StringPool.size();
2348 StringID <= N; ++StringID) {
2349 // Emit a label for reference from debug information entries.
2350 EmitLabel("string", StringID);
2352 // Emit the string itself.
2353 const std::string &String = StringPool[StringID];
2354 Asm->EmitString(String); Asm->EOL();
2361 /// EmitDebugLoc - Emit visible names into a debug loc section.
2363 void DwarfDebug::EmitDebugLoc() {
2364 // Start the dwarf loc section.
2365 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2369 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2371 void DwarfDebug::EmitDebugARanges() {
2372 // Start the dwarf aranges section.
2373 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2377 CompileUnit *Unit = GetBaseCompileUnit();
2379 // Don't include size of length
2380 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2382 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2384 EmitReference("info_begin", Unit->getID());
2385 Asm->EOL("Offset of Compilation Unit Info");
2387 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2389 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2391 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2392 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2395 EmitReference("text_begin", 0); Asm->EOL("Address");
2396 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2398 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2399 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2405 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2407 void DwarfDebug::EmitDebugRanges() {
2408 // Start the dwarf ranges section.
2409 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2413 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2415 void DwarfDebug::EmitDebugMacInfo() {
2416 if (const char *LineInfoDirective = TAI->getDwarfMacroInfoSection()) {
2417 // Start the dwarf macinfo section.
2418 Asm->SwitchToDataSection(LineInfoDirective);
2423 /// EmitDebugInlineInfo - Emit inline info using following format.
2425 /// 1. length of section
2426 /// 2. Dwarf version number
2427 /// 3. address size.
2429 /// Entries (one "entry" for each function that was inlined):
2431 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2432 /// otherwise offset into __debug_str for regular function name.
2433 /// 2. offset into __debug_str section for regular function name.
2434 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2435 /// instances for the function.
2437 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2438 /// inlined instance; the die_offset points to the inlined_subroutine die in the
2439 /// __debug_info section, and the low_pc is the starting address for the
2440 /// inlining instance.
2441 void DwarfDebug::EmitDebugInlineInfo() {
2442 if (!TAI->doesDwarfUsesInlineInfoSection())
2448 Asm->SwitchToDataSection(TAI->getDwarfDebugInlineSection());
2450 EmitDifference("debug_inlined_end", 1,
2451 "debug_inlined_begin", 1, true);
2452 Asm->EOL("Length of Debug Inlined Information Entry");
2454 EmitLabel("debug_inlined_begin", 1);
2456 Asm->EmitInt16(dwarf::DWARF_VERSION); Asm->EOL("Dwarf Version");
2457 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2459 for (DenseMap<GlobalVariable *, SmallVector<unsigned, 4> >::iterator
2460 I = InlineInfo.begin(), E = InlineInfo.end(); I != E; ++I) {
2461 GlobalVariable *GV = I->first;
2462 SmallVector<unsigned, 4> &Labels = I->second;
2463 DISubprogram SP(GV);
2467 SP.getLinkageName(LName);
2471 Asm->EmitString(Name);
2473 // Skip special LLVM prefix that is used to inform the asm printer to not emit
2474 // usual symbol prefix before the symbol name. This happens for Objective-C
2475 // symbol names and symbol whose name is replaced using GCC's __asm__ attribute.
2478 Asm->EmitString(LName);
2480 Asm->EOL("MIPS linkage name");
2482 Asm->EmitString(Name); Asm->EOL("Function name");
2484 Asm->EmitULEB128Bytes(Labels.size()); Asm->EOL("Inline count");
2486 for (SmallVector<unsigned, 4>::iterator LI = Labels.begin(),
2487 LE = Labels.end(); LI != LE; ++LI) {
2488 DIE *SP = ModuleCU->getDieMapSlotFor(GV);
2489 Asm->EmitInt32(SP->getOffset()); Asm->EOL("DIE offset");
2491 if (TD->getPointerSize() == sizeof(int32_t))
2492 O << TAI->getData32bitsDirective();
2494 O << TAI->getData64bitsDirective();
2496 PrintLabelName("label", *LI); Asm->EOL("low_pc");
2500 EmitLabel("debug_inlined_end", 1);