1 //===-- llvm/CodeGen/DwarfWriter.cpp - Dwarf Framework ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by James M. Laskey and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf info into asm files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/DwarfWriter.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/FoldingSet.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/UniqueVector.h"
20 #include "llvm/Module.h"
21 #include "llvm/Type.h"
22 #include "llvm/CodeGen/AsmPrinter.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineLocation.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/Dwarf.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/DataTypes.h"
30 #include "llvm/Support/Mangler.h"
31 #include "llvm/Target/TargetAsmInfo.h"
32 #include "llvm/Target/MRegisterInfo.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Target/TargetFrameInfo.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
41 using namespace llvm::dwarf;
45 //===----------------------------------------------------------------------===//
47 /// Configuration values for initial hash set sizes (log2).
49 static const unsigned InitDiesSetSize = 9; // 512
50 static const unsigned InitAbbreviationsSetSize = 9; // 512
51 static const unsigned InitValuesSetSize = 9; // 512
53 //===----------------------------------------------------------------------===//
54 /// Forward declarations.
59 //===----------------------------------------------------------------------===//
60 /// DWLabel - Labels are used to track locations in the assembler file.
61 /// Labels appear in the form @verbatim <prefix><Tag><Number> @endverbatim,
62 /// where the tag is a category of label (Ex. location) and number is a value
63 /// unique in that category.
66 /// Tag - Label category tag. Should always be a staticly declared C string.
70 /// Number - Value to make label unique.
74 DWLabel(const char *T, unsigned N) : Tag(T), Number(N) {}
76 void Profile(FoldingSetNodeID &ID) const {
77 ID.AddString(std::string(Tag));
78 ID.AddInteger(Number);
82 void print(std::ostream *O) const {
85 void print(std::ostream &O) const {
87 if (Number) O << Number;
92 //===----------------------------------------------------------------------===//
93 /// DIEAbbrevData - Dwarf abbreviation data, describes the one attribute of a
94 /// Dwarf abbreviation.
97 /// Attribute - Dwarf attribute code.
101 /// Form - Dwarf form code.
106 DIEAbbrevData(unsigned A, unsigned F)
112 unsigned getAttribute() const { return Attribute; }
113 unsigned getForm() const { return Form; }
115 /// Profile - Used to gather unique data for the abbreviation folding set.
117 void Profile(FoldingSetNodeID &ID)const {
118 ID.AddInteger(Attribute);
123 //===----------------------------------------------------------------------===//
124 /// DIEAbbrev - Dwarf abbreviation, describes the organization of a debug
125 /// information object.
126 class DIEAbbrev : public FoldingSetNode {
128 /// Tag - Dwarf tag code.
132 /// Unique number for node.
136 /// ChildrenFlag - Dwarf children flag.
138 unsigned ChildrenFlag;
140 /// Data - Raw data bytes for abbreviation.
142 std::vector<DIEAbbrevData> Data;
146 DIEAbbrev(unsigned T, unsigned C)
154 unsigned getTag() const { return Tag; }
155 unsigned getNumber() const { return Number; }
156 unsigned getChildrenFlag() const { return ChildrenFlag; }
157 const std::vector<DIEAbbrevData> &getData() const { return Data; }
158 void setTag(unsigned T) { Tag = T; }
159 void setChildrenFlag(unsigned CF) { ChildrenFlag = CF; }
160 void setNumber(unsigned N) { Number = N; }
162 /// AddAttribute - Adds another set of attribute information to the
164 void AddAttribute(unsigned Attribute, unsigned Form) {
165 Data.push_back(DIEAbbrevData(Attribute, Form));
168 /// AddFirstAttribute - Adds a set of attribute information to the front
169 /// of the abbreviation.
170 void AddFirstAttribute(unsigned Attribute, unsigned Form) {
171 Data.insert(Data.begin(), DIEAbbrevData(Attribute, Form));
174 /// Profile - Used to gather unique data for the abbreviation folding set.
176 void Profile(FoldingSetNodeID &ID) {
178 ID.AddInteger(ChildrenFlag);
180 // For each attribute description.
181 for (unsigned i = 0, N = Data.size(); i < N; ++i)
185 /// Emit - Print the abbreviation using the specified Dwarf writer.
187 void Emit(const DwarfDebug &DD) const;
190 void print(std::ostream *O) {
193 void print(std::ostream &O);
198 //===----------------------------------------------------------------------===//
199 /// DIE - A structured debug information entry. Has an abbreviation which
200 /// describes it's organization.
201 class DIE : public FoldingSetNode {
203 /// Abbrev - Buffer for constructing abbreviation.
207 /// Offset - Offset in debug info section.
211 /// Size - Size of instance + children.
217 std::vector<DIE *> Children;
219 /// Attributes values.
221 std::vector<DIEValue *> Values;
224 explicit DIE(unsigned Tag)
225 : Abbrev(Tag, DW_CHILDREN_no)
234 DIEAbbrev &getAbbrev() { return Abbrev; }
235 unsigned getAbbrevNumber() const {
236 return Abbrev.getNumber();
238 unsigned getTag() const { return Abbrev.getTag(); }
239 unsigned getOffset() const { return Offset; }
240 unsigned getSize() const { return Size; }
241 const std::vector<DIE *> &getChildren() const { return Children; }
242 std::vector<DIEValue *> &getValues() { return Values; }
243 void setTag(unsigned Tag) { Abbrev.setTag(Tag); }
244 void setOffset(unsigned O) { Offset = O; }
245 void setSize(unsigned S) { Size = S; }
247 /// AddValue - Add a value and attributes to a DIE.
249 void AddValue(unsigned Attribute, unsigned Form, DIEValue *Value) {
250 Abbrev.AddAttribute(Attribute, Form);
251 Values.push_back(Value);
254 /// SiblingOffset - Return the offset of the debug information entry's
256 unsigned SiblingOffset() const { return Offset + Size; }
258 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
260 void AddSiblingOffset();
262 /// AddChild - Add a child to the DIE.
264 void AddChild(DIE *Child) {
265 Abbrev.setChildrenFlag(DW_CHILDREN_yes);
266 Children.push_back(Child);
269 /// Detach - Detaches objects connected to it after copying.
275 /// Profile - Used to gather unique data for the value folding set.
277 void Profile(FoldingSetNodeID &ID) ;
280 void print(std::ostream *O, unsigned IncIndent = 0) {
281 if (O) print(*O, IncIndent);
283 void print(std::ostream &O, unsigned IncIndent = 0);
288 //===----------------------------------------------------------------------===//
289 /// DIEValue - A debug information entry value.
291 class DIEValue : public FoldingSetNode {
303 /// Type - Type of data stored in the value.
307 explicit DIEValue(unsigned T)
310 virtual ~DIEValue() {}
313 unsigned getType() const { return Type; }
315 // Implement isa/cast/dyncast.
316 static bool classof(const DIEValue *) { return true; }
318 /// EmitValue - Emit value via the Dwarf writer.
320 virtual void EmitValue(DwarfDebug &DD, unsigned Form) = 0;
322 /// SizeOf - Return the size of a value in bytes.
324 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const = 0;
326 /// Profile - Used to gather unique data for the value folding set.
328 virtual void Profile(FoldingSetNodeID &ID) = 0;
331 void print(std::ostream *O) {
334 virtual void print(std::ostream &O) = 0;
339 //===----------------------------------------------------------------------===//
340 /// DWInteger - An integer value DIE.
342 class DIEInteger : public DIEValue {
347 explicit DIEInteger(uint64_t I) : DIEValue(isInteger), Integer(I) {}
349 // Implement isa/cast/dyncast.
350 static bool classof(const DIEInteger *) { return true; }
351 static bool classof(const DIEValue *I) { return I->Type == isInteger; }
353 /// BestForm - Choose the best form for integer.
355 static unsigned BestForm(bool IsSigned, uint64_t Integer) {
357 if ((char)Integer == (signed)Integer) return DW_FORM_data1;
358 if ((short)Integer == (signed)Integer) return DW_FORM_data2;
359 if ((int)Integer == (signed)Integer) return DW_FORM_data4;
361 if ((unsigned char)Integer == Integer) return DW_FORM_data1;
362 if ((unsigned short)Integer == Integer) return DW_FORM_data2;
363 if ((unsigned int)Integer == Integer) return DW_FORM_data4;
365 return DW_FORM_data8;
368 /// EmitValue - Emit integer of appropriate size.
370 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
372 /// SizeOf - Determine size of integer value in bytes.
374 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
376 /// Profile - Used to gather unique data for the value folding set.
378 static void Profile(FoldingSetNodeID &ID, unsigned Integer) {
379 ID.AddInteger(isInteger);
380 ID.AddInteger(Integer);
382 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Integer); }
385 virtual void print(std::ostream &O) {
386 O << "Int: " << (int64_t)Integer
387 << " 0x" << std::hex << Integer << std::dec;
392 //===----------------------------------------------------------------------===//
393 /// DIEString - A string value DIE.
395 class DIEString : public DIEValue {
397 const std::string String;
399 explicit DIEString(const std::string &S) : DIEValue(isString), String(S) {}
401 // Implement isa/cast/dyncast.
402 static bool classof(const DIEString *) { return true; }
403 static bool classof(const DIEValue *S) { return S->Type == isString; }
405 /// EmitValue - Emit string value.
407 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
409 /// SizeOf - Determine size of string value in bytes.
411 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
412 return String.size() + sizeof(char); // sizeof('\0');
415 /// Profile - Used to gather unique data for the value folding set.
417 static void Profile(FoldingSetNodeID &ID, const std::string &String) {
418 ID.AddInteger(isString);
419 ID.AddString(String);
421 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, String); }
424 virtual void print(std::ostream &O) {
425 O << "Str: \"" << String << "\"";
430 //===----------------------------------------------------------------------===//
431 /// DIEDwarfLabel - A Dwarf internal label expression DIE.
433 class DIEDwarfLabel : public DIEValue {
438 explicit DIEDwarfLabel(const DWLabel &L) : DIEValue(isLabel), Label(L) {}
440 // Implement isa/cast/dyncast.
441 static bool classof(const DIEDwarfLabel *) { return true; }
442 static bool classof(const DIEValue *L) { return L->Type == isLabel; }
444 /// EmitValue - Emit label value.
446 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
448 /// SizeOf - Determine size of label value in bytes.
450 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
452 /// Profile - Used to gather unique data for the value folding set.
454 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label) {
455 ID.AddInteger(isLabel);
458 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
461 virtual void print(std::ostream &O) {
469 //===----------------------------------------------------------------------===//
470 /// DIEObjectLabel - A label to an object in code or data.
472 class DIEObjectLabel : public DIEValue {
474 const std::string Label;
476 explicit DIEObjectLabel(const std::string &L)
477 : DIEValue(isAsIsLabel), Label(L) {}
479 // Implement isa/cast/dyncast.
480 static bool classof(const DIEObjectLabel *) { return true; }
481 static bool classof(const DIEValue *L) { return L->Type == isAsIsLabel; }
483 /// EmitValue - Emit label value.
485 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
487 /// SizeOf - Determine size of label value in bytes.
489 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
491 /// Profile - Used to gather unique data for the value folding set.
493 static void Profile(FoldingSetNodeID &ID, const std::string &Label) {
494 ID.AddInteger(isAsIsLabel);
497 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
500 virtual void print(std::ostream &O) {
501 O << "Obj: " << Label;
506 //===----------------------------------------------------------------------===//
507 /// DIEDelta - A simple label difference DIE.
509 class DIEDelta : public DIEValue {
511 const DWLabel LabelHi;
512 const DWLabel LabelLo;
514 DIEDelta(const DWLabel &Hi, const DWLabel &Lo)
515 : DIEValue(isDelta), LabelHi(Hi), LabelLo(Lo) {}
517 // Implement isa/cast/dyncast.
518 static bool classof(const DIEDelta *) { return true; }
519 static bool classof(const DIEValue *D) { return D->Type == isDelta; }
521 /// EmitValue - Emit delta value.
523 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
525 /// SizeOf - Determine size of delta value in bytes.
527 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
529 /// Profile - Used to gather unique data for the value folding set.
531 static void Profile(FoldingSetNodeID &ID, const DWLabel &LabelHi,
532 const DWLabel &LabelLo) {
533 ID.AddInteger(isDelta);
537 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, LabelHi, LabelLo); }
540 virtual void print(std::ostream &O) {
549 //===----------------------------------------------------------------------===//
550 /// DIEntry - A pointer to another debug information entry. An instance of this
551 /// class can also be used as a proxy for a debug information entry not yet
552 /// defined (ie. types.)
553 class DIEntry : public DIEValue {
557 explicit DIEntry(DIE *E) : DIEValue(isEntry), Entry(E) {}
559 // Implement isa/cast/dyncast.
560 static bool classof(const DIEntry *) { return true; }
561 static bool classof(const DIEValue *E) { return E->Type == isEntry; }
563 /// EmitValue - Emit debug information entry offset.
565 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
567 /// SizeOf - Determine size of debug information entry in bytes.
569 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
570 return sizeof(int32_t);
573 /// Profile - Used to gather unique data for the value folding set.
575 static void Profile(FoldingSetNodeID &ID, DIE *Entry) {
576 ID.AddInteger(isEntry);
577 ID.AddPointer(Entry);
579 virtual void Profile(FoldingSetNodeID &ID) {
580 ID.AddInteger(isEntry);
583 ID.AddPointer(Entry);
590 virtual void print(std::ostream &O) {
591 O << "Die: 0x" << std::hex << (intptr_t)Entry << std::dec;
596 //===----------------------------------------------------------------------===//
597 /// DIEBlock - A block of values. Primarily used for location expressions.
599 class DIEBlock : public DIEValue, public DIE {
601 unsigned Size; // Size in bytes excluding size header.
611 // Implement isa/cast/dyncast.
612 static bool classof(const DIEBlock *) { return true; }
613 static bool classof(const DIEValue *E) { return E->Type == isBlock; }
615 /// ComputeSize - calculate the size of the block.
617 unsigned ComputeSize(DwarfDebug &DD);
619 /// BestForm - Choose the best form for data.
621 unsigned BestForm() const {
622 if ((unsigned char)Size == Size) return DW_FORM_block1;
623 if ((unsigned short)Size == Size) return DW_FORM_block2;
624 if ((unsigned int)Size == Size) return DW_FORM_block4;
625 return DW_FORM_block;
628 /// EmitValue - Emit block data.
630 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
632 /// SizeOf - Determine size of block data in bytes.
634 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
637 /// Profile - Used to gather unique data for the value folding set.
639 virtual void Profile(FoldingSetNodeID &ID) {
640 ID.AddInteger(isBlock);
645 virtual void print(std::ostream &O) {
652 //===----------------------------------------------------------------------===//
653 /// CompileUnit - This dwarf writer support class manages information associate
654 /// with a source file.
657 /// Desc - Compile unit debug descriptor.
659 CompileUnitDesc *Desc;
661 /// ID - File identifier for source.
665 /// Die - Compile unit debug information entry.
669 /// DescToDieMap - Tracks the mapping of unit level debug informaton
670 /// descriptors to debug information entries.
671 std::map<DebugInfoDesc *, DIE *> DescToDieMap;
673 /// DescToDIEntryMap - Tracks the mapping of unit level debug informaton
674 /// descriptors to debug information entries using a DIEntry proxy.
675 std::map<DebugInfoDesc *, DIEntry *> DescToDIEntryMap;
677 /// Globals - A map of globally visible named entities for this unit.
679 std::map<std::string, DIE *> Globals;
681 /// DiesSet - Used to uniquely define dies within the compile unit.
683 FoldingSet<DIE> DiesSet;
685 /// Dies - List of all dies in the compile unit.
687 std::vector<DIE *> Dies;
690 CompileUnit(CompileUnitDesc *CUD, unsigned I, DIE *D)
697 , DiesSet(InitDiesSetSize)
704 for (unsigned i = 0, N = Dies.size(); i < N; ++i)
709 CompileUnitDesc *getDesc() const { return Desc; }
710 unsigned getID() const { return ID; }
711 DIE* getDie() const { return Die; }
712 std::map<std::string, DIE *> &getGlobals() { return Globals; }
714 /// hasContent - Return true if this compile unit has something to write out.
716 bool hasContent() const {
717 return !Die->getChildren().empty();
720 /// AddGlobal - Add a new global entity to the compile unit.
722 void AddGlobal(const std::string &Name, DIE *Die) {
726 /// getDieMapSlotFor - Returns the debug information entry map slot for the
727 /// specified debug descriptor.
728 DIE *&getDieMapSlotFor(DebugInfoDesc *DID) {
729 return DescToDieMap[DID];
732 /// getDIEntrySlotFor - Returns the debug information entry proxy slot for the
733 /// specified debug descriptor.
734 DIEntry *&getDIEntrySlotFor(DebugInfoDesc *DID) {
735 return DescToDIEntryMap[DID];
738 /// AddDie - Adds or interns the DIE to the compile unit.
740 DIE *AddDie(DIE &Buffer) {
744 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
747 Die = new DIE(Buffer);
748 DiesSet.InsertNode(Die, Where);
749 this->Die->AddChild(Die);
757 //===----------------------------------------------------------------------===//
758 /// Dwarf - Emits general Dwarf directives.
764 //===--------------------------------------------------------------------===//
765 // Core attributes used by the Dwarf writer.
769 /// O - Stream to .s file.
773 /// Asm - Target of Dwarf emission.
777 /// TAI - Target Asm Printer.
778 const TargetAsmInfo *TAI;
780 /// TD - Target data.
781 const TargetData *TD;
783 /// RI - Register Information.
784 const MRegisterInfo *RI;
786 /// M - Current module.
790 /// MF - Current machine function.
794 /// MMI - Collected machine module information.
796 MachineModuleInfo *MMI;
798 /// SubprogramCount - The running count of functions being compiled.
800 unsigned SubprogramCount;
803 Dwarf(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
807 , TD(Asm->TM.getTargetData())
808 , RI(Asm->TM.getRegisterInfo())
819 //===--------------------------------------------------------------------===//
822 AsmPrinter *getAsm() const { return Asm; }
823 MachineModuleInfo *getMMI() const { return MMI; }
824 const TargetAsmInfo *getTargetAsmInfo() const { return TAI; }
826 /// PrintLabelName - Print label name in form used by Dwarf writer.
828 void PrintLabelName(DWLabel Label) const {
829 PrintLabelName(Label.Tag, Label.Number);
831 void PrintLabelName(const char *Tag, unsigned Number,
832 bool isInSection = false) const {
833 if (isInSection && TAI->getDwarfSectionOffsetDirective())
834 O << TAI->getDwarfSectionOffsetDirective() << Tag;
836 O << TAI->getPrivateGlobalPrefix() << Tag;
837 if (Number) O << Number;
840 /// EmitLabel - Emit location label for internal use by Dwarf.
842 void EmitLabel(DWLabel Label) const {
843 EmitLabel(Label.Tag, Label.Number);
845 void EmitLabel(const char *Tag, unsigned Number) const {
846 PrintLabelName(Tag, Number);
850 /// EmitReference - Emit a reference to a label.
852 void EmitReference(DWLabel Label, bool IsPCRelative = false) const {
853 EmitReference(Label.Tag, Label.Number, IsPCRelative);
855 void EmitReference(const char *Tag, unsigned Number,
856 bool IsPCRelative = false) const {
857 if (TAI->getAddressSize() == sizeof(int32_t))
858 O << TAI->getData32bitsDirective();
860 O << TAI->getData64bitsDirective();
862 PrintLabelName(Tag, Number);
864 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
866 void EmitReference(const std::string &Name, bool IsPCRelative = false) const {
867 if (TAI->getAddressSize() == sizeof(int32_t))
868 O << TAI->getData32bitsDirective();
870 O << TAI->getData64bitsDirective();
874 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
877 /// EmitDifference - Emit the difference between two labels. Some
878 /// assemblers do not behave with absolute expressions with data directives,
879 /// so there is an option (needsSet) to use an intermediary set expression.
880 void EmitDifference(DWLabel LabelHi, DWLabel LabelLo,
881 bool IsSmall = false) {
882 EmitDifference(LabelHi.Tag, LabelHi.Number,
883 LabelLo.Tag, LabelLo.Number,
886 void EmitDifference(const char *TagHi, unsigned NumberHi,
887 const char *TagLo, unsigned NumberLo,
888 bool IsSmall = false) {
889 if (TAI->needsSet()) {
891 PrintLabelName("set", SetCounter);
893 PrintLabelName(TagHi, NumberHi);
895 PrintLabelName(TagLo, NumberLo);
898 if (IsSmall || TAI->getAddressSize() == sizeof(int32_t))
899 O << TAI->getData32bitsDirective();
901 O << TAI->getData64bitsDirective();
903 PrintLabelName("set", SetCounter);
907 if (IsSmall || TAI->getAddressSize() == sizeof(int32_t))
908 O << TAI->getData32bitsDirective();
910 O << TAI->getData64bitsDirective();
912 PrintLabelName(TagHi, NumberHi);
914 PrintLabelName(TagLo, NumberLo);
918 void EmitSectionOffset(const char* Label, const char* Section,
919 unsigned LabelNumber, unsigned SectionNumber,
920 bool IsSmall = false, bool isEH = false) {
921 bool printAbsolute = false;
922 if (TAI->needsSet()) {
924 PrintLabelName("set", SetCounter);
926 PrintLabelName(Label, LabelNumber, true);
929 printAbsolute = TAI->isAbsoluteEHSectionOffsets();
931 printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
933 if (!printAbsolute) {
935 PrintLabelName(Section, SectionNumber);
939 if (IsSmall || TAI->getAddressSize() == sizeof(int32_t))
940 O << TAI->getData32bitsDirective();
942 O << TAI->getData64bitsDirective();
944 PrintLabelName("set", SetCounter);
947 if (IsSmall || TAI->getAddressSize() == sizeof(int32_t))
948 O << TAI->getData32bitsDirective();
950 O << TAI->getData64bitsDirective();
952 PrintLabelName(Label, LabelNumber, true);
955 printAbsolute = TAI->isAbsoluteEHSectionOffsets();
957 printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
959 if (!printAbsolute) {
961 PrintLabelName(Section, SectionNumber);
966 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
968 void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
969 const std::vector<MachineMove> &Moves) {
971 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
972 TargetFrameInfo::StackGrowsUp ?
973 TAI->getAddressSize() : -TAI->getAddressSize();
974 bool IsLocal = BaseLabel && strcmp(BaseLabel, "label") == 0;
976 for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
977 const MachineMove &Move = Moves[i];
978 unsigned LabelID = Move.getLabelID();
981 LabelID = MMI->MappedLabel(LabelID);
983 // Throw out move if the label is invalid.
984 if (!LabelID) continue;
987 const MachineLocation &Dst = Move.getDestination();
988 const MachineLocation &Src = Move.getSource();
990 // Advance row if new location.
991 if (BaseLabel && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
992 Asm->EmitInt8(DW_CFA_advance_loc4);
993 Asm->EOL("DW_CFA_advance_loc4");
994 EmitDifference("label", LabelID, BaseLabel, BaseLabelID, true);
997 BaseLabelID = LabelID;
1002 // If advancing cfa.
1003 if (Dst.isRegister() && Dst.getRegister() == MachineLocation::VirtualFP) {
1004 if (!Src.isRegister()) {
1005 if (Src.getRegister() == MachineLocation::VirtualFP) {
1006 Asm->EmitInt8(DW_CFA_def_cfa_offset);
1007 Asm->EOL("DW_CFA_def_cfa_offset");
1009 Asm->EmitInt8(DW_CFA_def_cfa);
1010 Asm->EOL("DW_CFA_def_cfa");
1011 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getRegister()));
1012 Asm->EOL("Register");
1015 int Offset = -Src.getOffset();
1017 Asm->EmitULEB128Bytes(Offset);
1020 assert(0 && "Machine move no supported yet.");
1022 } else if (Src.isRegister() &&
1023 Src.getRegister() == MachineLocation::VirtualFP) {
1024 if (Dst.isRegister()) {
1025 Asm->EmitInt8(DW_CFA_def_cfa_register);
1026 Asm->EOL("DW_CFA_def_cfa_register");
1027 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getRegister()));
1028 Asm->EOL("Register");
1030 assert(0 && "Machine move no supported yet.");
1033 unsigned Reg = RI->getDwarfRegNum(Src.getRegister());
1034 int Offset = Dst.getOffset() / stackGrowth;
1037 Asm->EmitInt8(DW_CFA_offset_extended_sf);
1038 Asm->EOL("DW_CFA_offset_extended_sf");
1039 Asm->EmitULEB128Bytes(Reg);
1041 Asm->EmitSLEB128Bytes(Offset);
1043 } else if (Reg < 64) {
1044 Asm->EmitInt8(DW_CFA_offset + Reg);
1045 Asm->EOL("DW_CFA_offset + Reg (" + utostr(Reg) + ")");
1046 Asm->EmitULEB128Bytes(Offset);
1049 Asm->EmitInt8(DW_CFA_offset_extended);
1050 Asm->EOL("DW_CFA_offset_extended");
1051 Asm->EmitULEB128Bytes(Reg);
1053 Asm->EmitULEB128Bytes(Offset);
1062 //===----------------------------------------------------------------------===//
1063 /// DwarfDebug - Emits Dwarf debug directives.
1065 class DwarfDebug : public Dwarf {
1068 //===--------------------------------------------------------------------===//
1069 // Attributes used to construct specific Dwarf sections.
1072 /// CompileUnits - All the compile units involved in this build. The index
1073 /// of each entry in this vector corresponds to the sources in MMI.
1074 std::vector<CompileUnit *> CompileUnits;
1076 /// AbbreviationsSet - Used to uniquely define abbreviations.
1078 FoldingSet<DIEAbbrev> AbbreviationsSet;
1080 /// Abbreviations - A list of all the unique abbreviations in use.
1082 std::vector<DIEAbbrev *> Abbreviations;
1084 /// ValuesSet - Used to uniquely define values.
1086 FoldingSet<DIEValue> ValuesSet;
1088 /// Values - A list of all the unique values in use.
1090 std::vector<DIEValue *> Values;
1092 /// StringPool - A UniqueVector of strings used by indirect references.
1094 UniqueVector<std::string> StringPool;
1096 /// UnitMap - Map debug information descriptor to compile unit.
1098 std::map<DebugInfoDesc *, CompileUnit *> DescToUnitMap;
1100 /// SectionMap - Provides a unique id per text section.
1102 UniqueVector<std::string> SectionMap;
1104 /// SectionSourceLines - Tracks line numbers per text section.
1106 std::vector<std::vector<SourceLineInfo> > SectionSourceLines;
1108 /// didInitial - Flag to indicate if initial emission has been done.
1112 /// shouldEmit - Flag to indicate if debug information should be emitted.
1116 struct FunctionDebugFrameInfo {
1118 std::vector<MachineMove> Moves;
1120 FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
1121 Number(Num), Moves(M) { }
1124 std::vector<FunctionDebugFrameInfo> DebugFrames;
1128 /// ShouldEmitDwarf - Returns true if Dwarf declarations should be made.
1130 bool ShouldEmitDwarf() const { return shouldEmit; }
1132 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1134 void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1135 // Profile the node so that we can make it unique.
1136 FoldingSetNodeID ID;
1139 // Check the set for priors.
1140 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1142 // If it's newly added.
1143 if (InSet == &Abbrev) {
1144 // Add to abbreviation list.
1145 Abbreviations.push_back(&Abbrev);
1146 // Assign the vector position + 1 as its number.
1147 Abbrev.setNumber(Abbreviations.size());
1149 // Assign existing abbreviation number.
1150 Abbrev.setNumber(InSet->getNumber());
1154 /// NewString - Add a string to the constant pool and returns a label.
1156 DWLabel NewString(const std::string &String) {
1157 unsigned StringID = StringPool.insert(String);
1158 return DWLabel("string", StringID);
1161 /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1163 DIEntry *NewDIEntry(DIE *Entry = NULL) {
1167 FoldingSetNodeID ID;
1168 DIEntry::Profile(ID, Entry);
1170 Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1172 if (Value) return Value;
1174 Value = new DIEntry(Entry);
1175 ValuesSet.InsertNode(Value, Where);
1177 Value = new DIEntry(Entry);
1180 Values.push_back(Value);
1184 /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1186 void SetDIEntry(DIEntry *Value, DIE *Entry) {
1187 Value->Entry = Entry;
1188 // Add to values set if not already there. If it is, we merely have a
1189 // duplicate in the values list (no harm.)
1190 ValuesSet.GetOrInsertNode(Value);
1193 /// AddUInt - Add an unsigned integer attribute data and value.
1195 void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1196 if (!Form) Form = DIEInteger::BestForm(false, Integer);
1198 FoldingSetNodeID ID;
1199 DIEInteger::Profile(ID, Integer);
1201 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1203 Value = new DIEInteger(Integer);
1204 ValuesSet.InsertNode(Value, Where);
1205 Values.push_back(Value);
1208 Die->AddValue(Attribute, Form, Value);
1211 /// AddSInt - Add an signed integer attribute data and value.
1213 void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1214 if (!Form) Form = DIEInteger::BestForm(true, Integer);
1216 FoldingSetNodeID ID;
1217 DIEInteger::Profile(ID, (uint64_t)Integer);
1219 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1221 Value = new DIEInteger(Integer);
1222 ValuesSet.InsertNode(Value, Where);
1223 Values.push_back(Value);
1226 Die->AddValue(Attribute, Form, Value);
1229 /// AddString - Add a std::string attribute data and value.
1231 void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1232 const std::string &String) {
1233 FoldingSetNodeID ID;
1234 DIEString::Profile(ID, String);
1236 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1238 Value = new DIEString(String);
1239 ValuesSet.InsertNode(Value, Where);
1240 Values.push_back(Value);
1243 Die->AddValue(Attribute, Form, Value);
1246 /// AddLabel - Add a Dwarf label attribute data and value.
1248 void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1249 const DWLabel &Label) {
1250 FoldingSetNodeID ID;
1251 DIEDwarfLabel::Profile(ID, Label);
1253 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1255 Value = new DIEDwarfLabel(Label);
1256 ValuesSet.InsertNode(Value, Where);
1257 Values.push_back(Value);
1260 Die->AddValue(Attribute, Form, Value);
1263 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1265 void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1266 const std::string &Label) {
1267 FoldingSetNodeID ID;
1268 DIEObjectLabel::Profile(ID, Label);
1270 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1272 Value = new DIEObjectLabel(Label);
1273 ValuesSet.InsertNode(Value, Where);
1274 Values.push_back(Value);
1277 Die->AddValue(Attribute, Form, Value);
1280 /// AddDelta - Add a label delta attribute data and value.
1282 void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1283 const DWLabel &Hi, const DWLabel &Lo) {
1284 FoldingSetNodeID ID;
1285 DIEDelta::Profile(ID, Hi, Lo);
1287 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1289 Value = new DIEDelta(Hi, Lo);
1290 ValuesSet.InsertNode(Value, Where);
1291 Values.push_back(Value);
1294 Die->AddValue(Attribute, Form, Value);
1297 /// AddDIEntry - Add a DIE attribute data and value.
1299 void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1300 Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1303 /// AddBlock - Add block data.
1305 void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1306 Block->ComputeSize(*this);
1307 FoldingSetNodeID ID;
1310 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1313 ValuesSet.InsertNode(Value, Where);
1314 Values.push_back(Value);
1319 Die->AddValue(Attribute, Block->BestForm(), Value);
1324 /// AddSourceLine - Add location information to specified debug information
1326 void AddSourceLine(DIE *Die, CompileUnitDesc *File, unsigned Line) {
1328 CompileUnit *FileUnit = FindCompileUnit(File);
1329 unsigned FileID = FileUnit->getID();
1330 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1331 AddUInt(Die, DW_AT_decl_line, 0, Line);
1335 /// AddAddress - Add an address attribute to a die based on the location
1337 void AddAddress(DIE *Die, unsigned Attribute,
1338 const MachineLocation &Location) {
1339 unsigned Reg = RI->getDwarfRegNum(Location.getRegister());
1340 DIEBlock *Block = new DIEBlock();
1342 if (Location.isRegister()) {
1344 AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1346 AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1347 AddUInt(Block, 0, DW_FORM_udata, Reg);
1351 AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1353 AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1354 AddUInt(Block, 0, DW_FORM_udata, Reg);
1356 AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1359 AddBlock(Die, Attribute, 0, Block);
1362 /// AddBasicType - Add a new basic type attribute to the specified entity.
1364 void AddBasicType(DIE *Entity, CompileUnit *Unit,
1365 const std::string &Name,
1366 unsigned Encoding, unsigned Size) {
1367 DIE *Die = ConstructBasicType(Unit, Name, Encoding, Size);
1368 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, Die);
1371 /// ConstructBasicType - Construct a new basic type.
1373 DIE *ConstructBasicType(CompileUnit *Unit,
1374 const std::string &Name,
1375 unsigned Encoding, unsigned Size) {
1376 DIE Buffer(DW_TAG_base_type);
1377 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1378 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, Encoding);
1379 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1380 return Unit->AddDie(Buffer);
1383 /// AddPointerType - Add a new pointer type attribute to the specified entity.
1385 void AddPointerType(DIE *Entity, CompileUnit *Unit, const std::string &Name) {
1386 DIE *Die = ConstructPointerType(Unit, Name);
1387 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, Die);
1390 /// ConstructPointerType - Construct a new pointer type.
1392 DIE *ConstructPointerType(CompileUnit *Unit, const std::string &Name) {
1393 DIE Buffer(DW_TAG_pointer_type);
1394 AddUInt(&Buffer, DW_AT_byte_size, 0, TAI->getAddressSize());
1395 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1396 return Unit->AddDie(Buffer);
1399 /// AddType - Add a new type attribute to the specified entity.
1401 void AddType(DIE *Entity, TypeDesc *TyDesc, CompileUnit *Unit) {
1403 AddBasicType(Entity, Unit, "", DW_ATE_signed, sizeof(int32_t));
1405 // Check for pre-existence.
1406 DIEntry *&Slot = Unit->getDIEntrySlotFor(TyDesc);
1408 // If it exists then use the existing value.
1410 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1414 if (SubprogramDesc *SubprogramTy = dyn_cast<SubprogramDesc>(TyDesc)) {
1415 // FIXME - Not sure why programs and variables are coming through here.
1416 // Short cut for handling subprogram types (not really a TyDesc.)
1417 AddPointerType(Entity, Unit, SubprogramTy->getName());
1418 } else if (GlobalVariableDesc *GlobalTy =
1419 dyn_cast<GlobalVariableDesc>(TyDesc)) {
1420 // FIXME - Not sure why programs and variables are coming through here.
1421 // Short cut for handling global variable types (not really a TyDesc.)
1422 AddPointerType(Entity, Unit, GlobalTy->getName());
1425 Slot = NewDIEntry();
1428 DIE Buffer(DW_TAG_base_type);
1429 ConstructType(Buffer, TyDesc, Unit);
1431 // Add debug information entry to entity and unit.
1432 DIE *Die = Unit->AddDie(Buffer);
1433 SetDIEntry(Slot, Die);
1434 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1439 /// ConstructType - Adds all the required attributes to the type.
1441 void ConstructType(DIE &Buffer, TypeDesc *TyDesc, CompileUnit *Unit) {
1442 // Get core information.
1443 const std::string &Name = TyDesc->getName();
1444 uint64_t Size = TyDesc->getSize() >> 3;
1446 if (BasicTypeDesc *BasicTy = dyn_cast<BasicTypeDesc>(TyDesc)) {
1447 // Fundamental types like int, float, bool
1448 Buffer.setTag(DW_TAG_base_type);
1449 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BasicTy->getEncoding());
1450 } else if (DerivedTypeDesc *DerivedTy = dyn_cast<DerivedTypeDesc>(TyDesc)) {
1452 unsigned Tag = DerivedTy->getTag();
1453 // FIXME - Workaround for templates.
1454 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1455 // Pointers, typedefs et al.
1457 // Map to main type, void will not have a type.
1458 if (TypeDesc *FromTy = DerivedTy->getFromType())
1459 AddType(&Buffer, FromTy, Unit);
1460 } else if (CompositeTypeDesc *CompTy = dyn_cast<CompositeTypeDesc>(TyDesc)){
1462 unsigned Tag = CompTy->getTag();
1464 // Set tag accordingly.
1465 if (Tag == DW_TAG_vector_type)
1466 Buffer.setTag(DW_TAG_array_type);
1470 std::vector<DebugInfoDesc *> &Elements = CompTy->getElements();
1473 case DW_TAG_vector_type:
1474 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1476 case DW_TAG_array_type: {
1477 // Add element type.
1478 if (TypeDesc *FromTy = CompTy->getFromType())
1479 AddType(&Buffer, FromTy, Unit);
1481 // Don't emit size attribute.
1484 // Construct an anonymous type for index type.
1485 DIE *IndexTy = ConstructBasicType(Unit, "", DW_ATE_signed,
1488 // Add subranges to array type.
1489 for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1490 SubrangeDesc *SRD = cast<SubrangeDesc>(Elements[i]);
1491 int64_t Lo = SRD->getLo();
1492 int64_t Hi = SRD->getHi();
1493 DIE *Subrange = new DIE(DW_TAG_subrange_type);
1495 // If a range is available.
1497 AddDIEntry(Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1498 // Only add low if non-zero.
1499 if (Lo) AddSInt(Subrange, DW_AT_lower_bound, 0, Lo);
1500 AddSInt(Subrange, DW_AT_upper_bound, 0, Hi);
1503 Buffer.AddChild(Subrange);
1507 case DW_TAG_structure_type:
1508 case DW_TAG_union_type: {
1509 // Add elements to structure type.
1510 for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1511 DebugInfoDesc *Element = Elements[i];
1513 if (DerivedTypeDesc *MemberDesc = dyn_cast<DerivedTypeDesc>(Element)){
1514 // Add field or base class.
1516 unsigned Tag = MemberDesc->getTag();
1518 // Extract the basic information.
1519 const std::string &Name = MemberDesc->getName();
1520 uint64_t Size = MemberDesc->getSize();
1521 uint64_t Align = MemberDesc->getAlign();
1522 uint64_t Offset = MemberDesc->getOffset();
1524 // Construct member debug information entry.
1525 DIE *Member = new DIE(Tag);
1527 // Add name if not "".
1529 AddString(Member, DW_AT_name, DW_FORM_string, Name);
1530 // Add location if available.
1531 AddSourceLine(Member, MemberDesc->getFile(), MemberDesc->getLine());
1533 // Most of the time the field info is the same as the members.
1534 uint64_t FieldSize = Size;
1535 uint64_t FieldAlign = Align;
1536 uint64_t FieldOffset = Offset;
1538 // Set the member type.
1539 TypeDesc *FromTy = MemberDesc->getFromType();
1540 AddType(Member, FromTy, Unit);
1542 // Walk up typedefs until a real size is found.
1544 if (FromTy->getTag() != DW_TAG_typedef) {
1545 FieldSize = FromTy->getSize();
1546 FieldAlign = FromTy->getSize();
1550 FromTy = cast<DerivedTypeDesc>(FromTy)->getFromType();
1553 // Unless we have a bit field.
1554 if (Tag == DW_TAG_member && FieldSize != Size) {
1555 // Construct the alignment mask.
1556 uint64_t AlignMask = ~(FieldAlign - 1);
1557 // Determine the high bit + 1 of the declared size.
1558 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1559 // Work backwards to determine the base offset of the field.
1560 FieldOffset = HiMark - FieldSize;
1561 // Now normalize offset to the field.
1562 Offset -= FieldOffset;
1564 // Maybe we need to work from the other end.
1565 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1567 // Add size and offset.
1568 AddUInt(Member, DW_AT_byte_size, 0, FieldSize >> 3);
1569 AddUInt(Member, DW_AT_bit_size, 0, Size);
1570 AddUInt(Member, DW_AT_bit_offset, 0, Offset);
1573 // Add computation for offset.
1574 DIEBlock *Block = new DIEBlock();
1575 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1576 AddUInt(Block, 0, DW_FORM_udata, FieldOffset >> 3);
1577 AddBlock(Member, DW_AT_data_member_location, 0, Block);
1579 // Add accessibility (public default unless is base class.
1580 if (MemberDesc->isProtected()) {
1581 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_protected);
1582 } else if (MemberDesc->isPrivate()) {
1583 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_private);
1584 } else if (Tag == DW_TAG_inheritance) {
1585 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_public);
1588 Buffer.AddChild(Member);
1589 } else if (GlobalVariableDesc *StaticDesc =
1590 dyn_cast<GlobalVariableDesc>(Element)) {
1591 // Add static member.
1593 // Construct member debug information entry.
1594 DIE *Static = new DIE(DW_TAG_variable);
1596 // Add name and mangled name.
1597 const std::string &Name = StaticDesc->getName();
1598 const std::string &LinkageName = StaticDesc->getLinkageName();
1599 AddString(Static, DW_AT_name, DW_FORM_string, Name);
1600 if (!LinkageName.empty()) {
1601 AddString(Static, DW_AT_MIPS_linkage_name, DW_FORM_string,
1606 AddSourceLine(Static, StaticDesc->getFile(), StaticDesc->getLine());
1609 if (TypeDesc *StaticTy = StaticDesc->getType())
1610 AddType(Static, StaticTy, Unit);
1613 if (!StaticDesc->isStatic())
1614 AddUInt(Static, DW_AT_external, DW_FORM_flag, 1);
1615 AddUInt(Static, DW_AT_declaration, DW_FORM_flag, 1);
1617 Buffer.AddChild(Static);
1618 } else if (SubprogramDesc *MethodDesc =
1619 dyn_cast<SubprogramDesc>(Element)) {
1620 // Add member function.
1622 // Construct member debug information entry.
1623 DIE *Method = new DIE(DW_TAG_subprogram);
1625 // Add name and mangled name.
1626 const std::string &Name = MethodDesc->getName();
1627 const std::string &LinkageName = MethodDesc->getLinkageName();
1629 AddString(Method, DW_AT_name, DW_FORM_string, Name);
1630 bool IsCTor = TyDesc->getName() == Name;
1632 if (!LinkageName.empty()) {
1633 AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string,
1638 AddSourceLine(Method, MethodDesc->getFile(), MethodDesc->getLine());
1641 if (CompositeTypeDesc *MethodTy =
1642 dyn_cast_or_null<CompositeTypeDesc>(MethodDesc->getType())) {
1643 // Get argument information.
1644 std::vector<DebugInfoDesc *> &Args = MethodTy->getElements();
1649 AddType(Method, dyn_cast<TypeDesc>(Args[0]), Unit);
1653 for(unsigned i = 1, N = Args.size(); i < N; ++i) {
1654 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1655 AddType(Arg, cast<TypeDesc>(Args[i]), Unit);
1656 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1);
1657 Method->AddChild(Arg);
1662 if (!MethodDesc->isStatic())
1663 AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);
1664 AddUInt(Method, DW_AT_declaration, DW_FORM_flag, 1);
1666 Buffer.AddChild(Method);
1671 case DW_TAG_enumeration_type: {
1672 // Add enumerators to enumeration type.
1673 for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1674 EnumeratorDesc *ED = cast<EnumeratorDesc>(Elements[i]);
1675 const std::string &Name = ED->getName();
1676 int64_t Value = ED->getValue();
1677 DIE *Enumerator = new DIE(DW_TAG_enumerator);
1678 AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
1679 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1680 Buffer.AddChild(Enumerator);
1685 case DW_TAG_subroutine_type: {
1686 // Add prototype flag.
1687 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1689 AddType(&Buffer, dyn_cast<TypeDesc>(Elements[0]), Unit);
1692 for(unsigned i = 1, N = Elements.size(); i < N; ++i) {
1693 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1694 AddType(Arg, cast<TypeDesc>(Elements[i]), Unit);
1695 Buffer.AddChild(Arg);
1704 // Add size if non-zero (derived types don't have a size.)
1705 if (Size) AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1706 // Add name if not anonymous or intermediate type.
1707 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1708 // Add source line info if available.
1709 AddSourceLine(&Buffer, TyDesc->getFile(), TyDesc->getLine());
1712 /// NewCompileUnit - Create new compile unit and it's debug information entry.
1714 CompileUnit *NewCompileUnit(CompileUnitDesc *UnitDesc, unsigned ID) {
1715 // Construct debug information entry.
1716 DIE *Die = new DIE(DW_TAG_compile_unit);
1717 if (TAI->isAbsoluteDebugSectionOffsets())
1718 AddLabel(Die, DW_AT_stmt_list, DW_FORM_data4, DWLabel("section_line", 0));
1720 AddDelta(Die, DW_AT_stmt_list, DW_FORM_data4, DWLabel("section_line", 0),
1721 DWLabel("section_line", 0));
1722 AddString(Die, DW_AT_producer, DW_FORM_string, UnitDesc->getProducer());
1723 AddUInt (Die, DW_AT_language, DW_FORM_data1, UnitDesc->getLanguage());
1724 AddString(Die, DW_AT_name, DW_FORM_string, UnitDesc->getFileName());
1725 AddString(Die, DW_AT_comp_dir, DW_FORM_string, UnitDesc->getDirectory());
1727 // Construct compile unit.
1728 CompileUnit *Unit = new CompileUnit(UnitDesc, ID, Die);
1730 // Add Unit to compile unit map.
1731 DescToUnitMap[UnitDesc] = Unit;
1736 /// GetBaseCompileUnit - Get the main compile unit.
1738 CompileUnit *GetBaseCompileUnit() const {
1739 CompileUnit *Unit = CompileUnits[0];
1740 assert(Unit && "Missing compile unit.");
1744 /// FindCompileUnit - Get the compile unit for the given descriptor.
1746 CompileUnit *FindCompileUnit(CompileUnitDesc *UnitDesc) {
1747 CompileUnit *Unit = DescToUnitMap[UnitDesc];
1748 assert(Unit && "Missing compile unit.");
1752 /// NewGlobalVariable - Add a new global variable DIE.
1754 DIE *NewGlobalVariable(GlobalVariableDesc *GVD) {
1755 // Get the compile unit context.
1756 CompileUnitDesc *UnitDesc =
1757 static_cast<CompileUnitDesc *>(GVD->getContext());
1758 CompileUnit *Unit = GetBaseCompileUnit();
1760 // Check for pre-existence.
1761 DIE *&Slot = Unit->getDieMapSlotFor(GVD);
1762 if (Slot) return Slot;
1764 // Get the global variable itself.
1765 GlobalVariable *GV = GVD->getGlobalVariable();
1767 const std::string &Name = GVD->getName();
1768 const std::string &FullName = GVD->getFullName();
1769 const std::string &LinkageName = GVD->getLinkageName();
1770 // Create the global's variable DIE.
1771 DIE *VariableDie = new DIE(DW_TAG_variable);
1772 AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
1773 if (!LinkageName.empty()) {
1774 AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1777 AddType(VariableDie, GVD->getType(), Unit);
1778 if (!GVD->isStatic())
1779 AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
1781 // Add source line info if available.
1782 AddSourceLine(VariableDie, UnitDesc, GVD->getLine());
1785 DIEBlock *Block = new DIEBlock();
1786 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
1787 AddObjectLabel(Block, 0, DW_FORM_udata, Asm->getGlobalLinkName(GV));
1788 AddBlock(VariableDie, DW_AT_location, 0, Block);
1793 // Add to context owner.
1794 Unit->getDie()->AddChild(VariableDie);
1796 // Expose as global.
1797 // FIXME - need to check external flag.
1798 Unit->AddGlobal(FullName, VariableDie);
1803 /// NewSubprogram - Add a new subprogram DIE.
1805 DIE *NewSubprogram(SubprogramDesc *SPD) {
1806 // Get the compile unit context.
1807 CompileUnitDesc *UnitDesc =
1808 static_cast<CompileUnitDesc *>(SPD->getContext());
1809 CompileUnit *Unit = GetBaseCompileUnit();
1811 // Check for pre-existence.
1812 DIE *&Slot = Unit->getDieMapSlotFor(SPD);
1813 if (Slot) return Slot;
1815 // Gather the details (simplify add attribute code.)
1816 const std::string &Name = SPD->getName();
1817 const std::string &FullName = SPD->getFullName();
1818 const std::string &LinkageName = SPD->getLinkageName();
1820 DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
1821 AddString(SubprogramDie, DW_AT_name, DW_FORM_string, Name);
1822 if (!LinkageName.empty()) {
1823 AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1826 if (SPD->getType()) AddType(SubprogramDie, SPD->getType(), Unit);
1827 if (!SPD->isStatic())
1828 AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
1829 AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
1831 // Add source line info if available.
1832 AddSourceLine(SubprogramDie, UnitDesc, SPD->getLine());
1835 Slot = SubprogramDie;
1837 // Add to context owner.
1838 Unit->getDie()->AddChild(SubprogramDie);
1840 // Expose as global.
1841 Unit->AddGlobal(FullName, SubprogramDie);
1843 return SubprogramDie;
1846 /// NewScopeVariable - Create a new scope variable.
1848 DIE *NewScopeVariable(DebugVariable *DV, CompileUnit *Unit) {
1849 // Get the descriptor.
1850 VariableDesc *VD = DV->getDesc();
1852 // Translate tag to proper Dwarf tag. The result variable is dropped for
1855 switch (VD->getTag()) {
1856 case DW_TAG_return_variable: return NULL;
1857 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
1858 case DW_TAG_auto_variable: // fall thru
1859 default: Tag = DW_TAG_variable; break;
1862 // Define variable debug information entry.
1863 DIE *VariableDie = new DIE(Tag);
1864 AddString(VariableDie, DW_AT_name, DW_FORM_string, VD->getName());
1866 // Add source line info if available.
1867 AddSourceLine(VariableDie, VD->getFile(), VD->getLine());
1869 // Add variable type.
1870 AddType(VariableDie, VD->getType(), Unit);
1872 // Add variable address.
1873 MachineLocation Location;
1874 RI->getLocation(*MF, DV->getFrameIndex(), Location);
1875 AddAddress(VariableDie, DW_AT_location, Location);
1880 /// ConstructScope - Construct the components of a scope.
1882 void ConstructScope(DebugScope *ParentScope,
1883 unsigned ParentStartID, unsigned ParentEndID,
1884 DIE *ParentDie, CompileUnit *Unit) {
1885 // Add variables to scope.
1886 std::vector<DebugVariable *> &Variables = ParentScope->getVariables();
1887 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1888 DIE *VariableDie = NewScopeVariable(Variables[i], Unit);
1889 if (VariableDie) ParentDie->AddChild(VariableDie);
1892 // Add nested scopes.
1893 std::vector<DebugScope *> &Scopes = ParentScope->getScopes();
1894 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1895 // Define the Scope debug information entry.
1896 DebugScope *Scope = Scopes[j];
1897 // FIXME - Ignore inlined functions for the time being.
1898 if (!Scope->getParent()) continue;
1900 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1901 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1903 // Ignore empty scopes.
1904 if (StartID == EndID && StartID != 0) continue;
1905 if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
1907 if (StartID == ParentStartID && EndID == ParentEndID) {
1908 // Just add stuff to the parent scope.
1909 ConstructScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
1911 DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
1913 // Add the scope bounds.
1915 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1916 DWLabel("label", StartID));
1918 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1919 DWLabel("func_begin", SubprogramCount));
1922 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
1923 DWLabel("label", EndID));
1925 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
1926 DWLabel("func_end", SubprogramCount));
1929 // Add the scope contents.
1930 ConstructScope(Scope, StartID, EndID, ScopeDie, Unit);
1931 ParentDie->AddChild(ScopeDie);
1936 /// ConstructRootScope - Construct the scope for the subprogram.
1938 void ConstructRootScope(DebugScope *RootScope) {
1939 // Exit if there is no root scope.
1940 if (!RootScope) return;
1942 // Get the subprogram debug information entry.
1943 SubprogramDesc *SPD = cast<SubprogramDesc>(RootScope->getDesc());
1945 // Get the compile unit context.
1946 CompileUnit *Unit = GetBaseCompileUnit();
1948 // Get the subprogram die.
1949 DIE *SPDie = Unit->getDieMapSlotFor(SPD);
1950 assert(SPDie && "Missing subprogram descriptor");
1952 // Add the function bounds.
1953 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
1954 DWLabel("func_begin", SubprogramCount));
1955 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
1956 DWLabel("func_end", SubprogramCount));
1957 MachineLocation Location(RI->getFrameRegister(*MF));
1958 AddAddress(SPDie, DW_AT_frame_base, Location);
1960 ConstructScope(RootScope, 0, 0, SPDie, Unit);
1963 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
1964 /// tools to recognize the object file contains Dwarf information.
1965 void EmitInitial() {
1966 // Check to see if we already emitted intial headers.
1967 if (didInitial) return;
1970 // Dwarf sections base addresses.
1971 if (TAI->doesDwarfRequireFrameSection()) {
1972 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1973 EmitLabel("section_debug_frame", 0);
1975 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
1976 EmitLabel("section_info", 0);
1977 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
1978 EmitLabel("section_abbrev", 0);
1979 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
1980 EmitLabel("section_aranges", 0);
1981 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
1982 EmitLabel("section_macinfo", 0);
1983 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
1984 EmitLabel("section_line", 0);
1985 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
1986 EmitLabel("section_loc", 0);
1987 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
1988 EmitLabel("section_pubnames", 0);
1989 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
1990 EmitLabel("section_str", 0);
1991 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
1992 EmitLabel("section_ranges", 0);
1994 Asm->SwitchToTextSection(TAI->getTextSection());
1995 EmitLabel("text_begin", 0);
1996 Asm->SwitchToDataSection(TAI->getDataSection());
1997 EmitLabel("data_begin", 0);
2000 /// EmitDIE - Recusively Emits a debug information entry.
2002 void EmitDIE(DIE *Die) {
2003 // Get the abbreviation for this DIE.
2004 unsigned AbbrevNumber = Die->getAbbrevNumber();
2005 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2009 // Emit the code (index) for the abbreviation.
2010 Asm->EmitULEB128Bytes(AbbrevNumber);
2011 Asm->EOL(std::string("Abbrev [" +
2012 utostr(AbbrevNumber) +
2013 "] 0x" + utohexstr(Die->getOffset()) +
2014 ":0x" + utohexstr(Die->getSize()) + " " +
2015 TagString(Abbrev->getTag())));
2017 std::vector<DIEValue *> &Values = Die->getValues();
2018 const std::vector<DIEAbbrevData> &AbbrevData = Abbrev->getData();
2020 // Emit the DIE attribute values.
2021 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2022 unsigned Attr = AbbrevData[i].getAttribute();
2023 unsigned Form = AbbrevData[i].getForm();
2024 assert(Form && "Too many attributes for DIE (check abbreviation)");
2027 case DW_AT_sibling: {
2028 Asm->EmitInt32(Die->SiblingOffset());
2032 // Emit an attribute using the defined form.
2033 Values[i]->EmitValue(*this, Form);
2038 Asm->EOL(AttributeString(Attr));
2041 // Emit the DIE children if any.
2042 if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2043 const std::vector<DIE *> &Children = Die->getChildren();
2045 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2046 EmitDIE(Children[j]);
2049 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2053 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2055 unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2056 // Get the children.
2057 const std::vector<DIE *> &Children = Die->getChildren();
2059 // If not last sibling and has children then add sibling offset attribute.
2060 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2062 // Record the abbreviation.
2063 AssignAbbrevNumber(Die->getAbbrev());
2065 // Get the abbreviation for this DIE.
2066 unsigned AbbrevNumber = Die->getAbbrevNumber();
2067 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2070 Die->setOffset(Offset);
2072 // Start the size with the size of abbreviation code.
2073 Offset += Asm->SizeULEB128(AbbrevNumber);
2075 const std::vector<DIEValue *> &Values = Die->getValues();
2076 const std::vector<DIEAbbrevData> &AbbrevData = Abbrev->getData();
2078 // Size the DIE attribute values.
2079 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2080 // Size attribute value.
2081 Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2084 // Size the DIE children if any.
2085 if (!Children.empty()) {
2086 assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2087 "Children flag not set");
2089 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2090 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2093 // End of children marker.
2094 Offset += sizeof(int8_t);
2097 Die->setSize(Offset - Die->getOffset());
2101 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2103 void SizeAndOffsets() {
2104 // Process base compile unit.
2105 CompileUnit *Unit = GetBaseCompileUnit();
2106 // Compute size of compile unit header
2107 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2108 sizeof(int16_t) + // DWARF version number
2109 sizeof(int32_t) + // Offset Into Abbrev. Section
2110 sizeof(int8_t); // Pointer Size (in bytes)
2111 SizeAndOffsetDie(Unit->getDie(), Offset, true);
2114 /// EmitDebugInfo - Emit the debug info section.
2116 void EmitDebugInfo() {
2117 // Start debug info section.
2118 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2120 CompileUnit *Unit = GetBaseCompileUnit();
2121 DIE *Die = Unit->getDie();
2122 // Emit the compile units header.
2123 EmitLabel("info_begin", Unit->getID());
2124 // Emit size of content not including length itself
2125 unsigned ContentSize = Die->getSize() +
2126 sizeof(int16_t) + // DWARF version number
2127 sizeof(int32_t) + // Offset Into Abbrev. Section
2128 sizeof(int8_t) + // Pointer Size (in bytes)
2129 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2131 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2132 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2133 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2134 Asm->EOL("Offset Into Abbrev. Section");
2135 Asm->EmitInt8(TAI->getAddressSize()); Asm->EOL("Address Size (in bytes)");
2138 // FIXME - extra padding for gdb bug.
2139 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2140 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2141 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2142 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2143 EmitLabel("info_end", Unit->getID());
2148 /// EmitAbbreviations - Emit the abbreviation section.
2150 void EmitAbbreviations() const {
2151 // Check to see if it is worth the effort.
2152 if (!Abbreviations.empty()) {
2153 // Start the debug abbrev section.
2154 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2156 EmitLabel("abbrev_begin", 0);
2158 // For each abbrevation.
2159 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2160 // Get abbreviation data
2161 const DIEAbbrev *Abbrev = Abbreviations[i];
2163 // Emit the abbrevations code (base 1 index.)
2164 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2165 Asm->EOL("Abbreviation Code");
2167 // Emit the abbreviations data.
2168 Abbrev->Emit(*this);
2173 // Mark end of abbreviations.
2174 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2176 EmitLabel("abbrev_end", 0);
2182 /// EmitDebugLines - Emit source line information.
2184 void EmitDebugLines() {
2185 // Minimum line delta, thus ranging from -10..(255-10).
2186 const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2187 // Maximum line delta, thus ranging from -10..(255-10).
2188 const int MaxLineDelta = 255 + MinLineDelta;
2190 // Start the dwarf line section.
2191 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2193 // Construct the section header.
2195 EmitDifference("line_end", 0, "line_begin", 0, true);
2196 Asm->EOL("Length of Source Line Info");
2197 EmitLabel("line_begin", 0);
2199 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2201 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2202 Asm->EOL("Prolog Length");
2203 EmitLabel("line_prolog_begin", 0);
2205 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2207 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2209 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2211 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2213 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2215 // Line number standard opcode encodings argument count
2216 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2217 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2218 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2219 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2220 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2221 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2222 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2223 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2224 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2226 const UniqueVector<std::string> &Directories = MMI->getDirectories();
2227 const UniqueVector<SourceFileInfo>
2228 &SourceFiles = MMI->getSourceFiles();
2230 // Emit directories.
2231 for (unsigned DirectoryID = 1, NDID = Directories.size();
2232 DirectoryID <= NDID; ++DirectoryID) {
2233 Asm->EmitString(Directories[DirectoryID]); Asm->EOL("Directory");
2235 Asm->EmitInt8(0); Asm->EOL("End of directories");
2238 for (unsigned SourceID = 1, NSID = SourceFiles.size();
2239 SourceID <= NSID; ++SourceID) {
2240 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2241 Asm->EmitString(SourceFile.getName());
2243 Asm->EmitULEB128Bytes(SourceFile.getDirectoryID());
2244 Asm->EOL("Directory #");
2245 Asm->EmitULEB128Bytes(0);
2246 Asm->EOL("Mod date");
2247 Asm->EmitULEB128Bytes(0);
2248 Asm->EOL("File size");
2250 Asm->EmitInt8(0); Asm->EOL("End of files");
2252 EmitLabel("line_prolog_end", 0);
2254 // A sequence for each text section.
2255 for (unsigned j = 0, M = SectionSourceLines.size(); j < M; ++j) {
2256 // Isolate current sections line info.
2257 const std::vector<SourceLineInfo> &LineInfos = SectionSourceLines[j];
2259 Asm->EOL(std::string("Section ") + SectionMap[j + 1]);
2261 // Dwarf assumes we start with first line of first source file.
2262 unsigned Source = 1;
2265 // Construct rows of the address, source, line, column matrix.
2266 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2267 const SourceLineInfo &LineInfo = LineInfos[i];
2268 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2269 if (!LabelID) continue;
2271 unsigned SourceID = LineInfo.getSourceID();
2272 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2273 unsigned DirectoryID = SourceFile.getDirectoryID();
2274 Asm->EOL(Directories[DirectoryID]
2275 + SourceFile.getName()
2277 + utostr_32(LineInfo.getLine()));
2279 // Define the line address.
2280 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2281 Asm->EmitInt8(TAI->getAddressSize() + 1); Asm->EOL("Op size");
2282 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2283 EmitReference("label", LabelID); Asm->EOL("Location label");
2285 // If change of source, then switch to the new source.
2286 if (Source != LineInfo.getSourceID()) {
2287 Source = LineInfo.getSourceID();
2288 Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2289 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2292 // If change of line.
2293 if (Line != LineInfo.getLine()) {
2294 // Determine offset.
2295 int Offset = LineInfo.getLine() - Line;
2296 int Delta = Offset - MinLineDelta;
2299 Line = LineInfo.getLine();
2301 // If delta is small enough and in range...
2302 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2303 // ... then use fast opcode.
2304 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2306 // ... otherwise use long hand.
2307 Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
2308 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2309 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2312 // Copy the previous row (different address or source)
2313 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2317 // Define last address of section.
2318 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2319 Asm->EmitInt8(TAI->getAddressSize() + 1); Asm->EOL("Op size");
2320 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2321 EmitReference("section_end", j + 1); Asm->EOL("Section end label");
2323 // Mark end of matrix.
2324 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2325 Asm->EmitULEB128Bytes(1); Asm->EOL();
2326 Asm->EmitInt8(1); Asm->EOL();
2329 EmitLabel("line_end", 0);
2334 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2336 void EmitCommonDebugFrame() {
2337 if (!TAI->doesDwarfRequireFrameSection())
2341 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2342 TargetFrameInfo::StackGrowsUp ?
2343 TAI->getAddressSize() : -TAI->getAddressSize();
2345 // Start the dwarf frame section.
2346 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2348 EmitLabel("debug_frame_common", 0);
2349 EmitDifference("debug_frame_common_end", 0,
2350 "debug_frame_common_begin", 0, true);
2351 Asm->EOL("Length of Common Information Entry");
2353 EmitLabel("debug_frame_common_begin", 0);
2354 Asm->EmitInt32((int)DW_CIE_ID);
2355 Asm->EOL("CIE Identifier Tag");
2356 Asm->EmitInt8(DW_CIE_VERSION);
2357 Asm->EOL("CIE Version");
2358 Asm->EmitString("");
2359 Asm->EOL("CIE Augmentation");
2360 Asm->EmitULEB128Bytes(1);
2361 Asm->EOL("CIE Code Alignment Factor");
2362 Asm->EmitSLEB128Bytes(stackGrowth);
2363 Asm->EOL("CIE Data Alignment Factor");
2364 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister()));
2365 Asm->EOL("CIE RA Column");
2367 std::vector<MachineMove> Moves;
2368 RI->getInitialFrameState(Moves);
2370 EmitFrameMoves(NULL, 0, Moves);
2372 Asm->EmitAlignment(2);
2373 EmitLabel("debug_frame_common_end", 0);
2378 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2380 void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2381 if (!TAI->doesDwarfRequireFrameSection())
2384 // Start the dwarf frame section.
2385 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2387 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2388 "debug_frame_begin", DebugFrameInfo.Number, true);
2389 Asm->EOL("Length of Frame Information Entry");
2391 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2393 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2395 Asm->EOL("FDE CIE offset");
2397 EmitReference("func_begin", DebugFrameInfo.Number);
2398 Asm->EOL("FDE initial location");
2399 EmitDifference("func_end", DebugFrameInfo.Number,
2400 "func_begin", DebugFrameInfo.Number);
2401 Asm->EOL("FDE address range");
2403 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves);
2405 Asm->EmitAlignment(2);
2406 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2411 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2413 void EmitDebugPubNames() {
2414 // Start the dwarf pubnames section.
2415 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2417 CompileUnit *Unit = GetBaseCompileUnit();
2419 EmitDifference("pubnames_end", Unit->getID(),
2420 "pubnames_begin", Unit->getID(), true);
2421 Asm->EOL("Length of Public Names Info");
2423 EmitLabel("pubnames_begin", Unit->getID());
2425 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
2427 EmitSectionOffset("info_begin", "section_info",
2428 Unit->getID(), 0, true, false);
2429 Asm->EOL("Offset of Compilation Unit Info");
2431 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),true);
2432 Asm->EOL("Compilation Unit Length");
2434 std::map<std::string, DIE *> &Globals = Unit->getGlobals();
2436 for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
2439 const std::string &Name = GI->first;
2440 DIE * Entity = GI->second;
2442 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2443 Asm->EmitString(Name); Asm->EOL("External Name");
2446 Asm->EmitInt32(0); Asm->EOL("End Mark");
2447 EmitLabel("pubnames_end", Unit->getID());
2452 /// EmitDebugStr - Emit visible names into a debug str section.
2454 void EmitDebugStr() {
2455 // Check to see if it is worth the effort.
2456 if (!StringPool.empty()) {
2457 // Start the dwarf str section.
2458 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2460 // For each of strings in the string pool.
2461 for (unsigned StringID = 1, N = StringPool.size();
2462 StringID <= N; ++StringID) {
2463 // Emit a label for reference from debug information entries.
2464 EmitLabel("string", StringID);
2465 // Emit the string itself.
2466 const std::string &String = StringPool[StringID];
2467 Asm->EmitString(String); Asm->EOL();
2474 /// EmitDebugLoc - Emit visible names into a debug loc section.
2476 void EmitDebugLoc() {
2477 // Start the dwarf loc section.
2478 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2483 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2485 void EmitDebugARanges() {
2486 // Start the dwarf aranges section.
2487 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2491 CompileUnit *Unit = GetBaseCompileUnit();
2493 // Don't include size of length
2494 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2496 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2498 EmitReference("info_begin", Unit->getID());
2499 Asm->EOL("Offset of Compilation Unit Info");
2501 Asm->EmitInt8(TAI->getAddressSize()); Asm->EOL("Size of Address");
2503 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2505 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2506 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2509 EmitReference("text_begin", 0); Asm->EOL("Address");
2510 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2512 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2513 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2519 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2521 void EmitDebugRanges() {
2522 // Start the dwarf ranges section.
2523 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2528 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2530 void EmitDebugMacInfo() {
2531 // Start the dwarf macinfo section.
2532 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2537 /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
2539 void ConstructCompileUnitDIEs() {
2540 const UniqueVector<CompileUnitDesc *> CUW = MMI->getCompileUnits();
2542 for (unsigned i = 1, N = CUW.size(); i <= N; ++i) {
2543 unsigned ID = MMI->RecordSource(CUW[i]);
2544 CompileUnit *Unit = NewCompileUnit(CUW[i], ID);
2545 CompileUnits.push_back(Unit);
2549 /// ConstructGlobalDIEs - Create DIEs for each of the externally visible
2550 /// global variables.
2551 void ConstructGlobalDIEs() {
2552 std::vector<GlobalVariableDesc *> GlobalVariables =
2553 MMI->getAnchoredDescriptors<GlobalVariableDesc>(*M);
2555 for (unsigned i = 0, N = GlobalVariables.size(); i < N; ++i) {
2556 GlobalVariableDesc *GVD = GlobalVariables[i];
2557 NewGlobalVariable(GVD);
2561 /// ConstructSubprogramDIEs - Create DIEs for each of the externally visible
2563 void ConstructSubprogramDIEs() {
2564 std::vector<SubprogramDesc *> Subprograms =
2565 MMI->getAnchoredDescriptors<SubprogramDesc>(*M);
2567 for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
2568 SubprogramDesc *SPD = Subprograms[i];
2574 //===--------------------------------------------------------------------===//
2575 // Main entry points.
2577 DwarfDebug(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
2580 , AbbreviationsSet(InitAbbreviationsSetSize)
2582 , ValuesSet(InitValuesSetSize)
2587 , SectionSourceLines()
2592 virtual ~DwarfDebug() {
2593 for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i)
2594 delete CompileUnits[i];
2595 for (unsigned j = 0, M = Values.size(); j < M; ++j)
2599 /// SetModuleInfo - Set machine module information when it's known that pass
2600 /// manager has created it. Set by the target AsmPrinter.
2601 void SetModuleInfo(MachineModuleInfo *mmi) {
2602 // Make sure initial declarations are made.
2603 if (!MMI && mmi->hasDebugInfo()) {
2607 // Emit initial sections
2610 // Create all the compile unit DIEs.
2611 ConstructCompileUnitDIEs();
2613 // Create DIEs for each of the externally visible global variables.
2614 ConstructGlobalDIEs();
2616 // Create DIEs for each of the externally visible subprograms.
2617 ConstructSubprogramDIEs();
2619 // Prime section data.
2620 SectionMap.insert(TAI->getTextSection());
2624 /// BeginModule - Emit all Dwarf sections that should come prior to the
2626 void BeginModule(Module *M) {
2629 if (!ShouldEmitDwarf()) return;
2632 /// EndModule - Emit all Dwarf sections that should come after the content.
2635 if (!ShouldEmitDwarf()) return;
2637 // Standard sections final addresses.
2638 Asm->SwitchToTextSection(TAI->getTextSection());
2639 EmitLabel("text_end", 0);
2640 Asm->SwitchToDataSection(TAI->getDataSection());
2641 EmitLabel("data_end", 0);
2643 // End text sections.
2644 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2645 Asm->SwitchToTextSection(SectionMap[i].c_str());
2646 EmitLabel("section_end", i);
2649 // Emit common frame information.
2650 EmitCommonDebugFrame();
2652 // Emit function debug frame information
2653 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
2654 E = DebugFrames.end(); I != E; ++I)
2655 EmitFunctionDebugFrame(*I);
2657 // Compute DIE offsets and sizes.
2660 // Emit all the DIEs into a debug info section
2663 // Corresponding abbreviations into a abbrev section.
2664 EmitAbbreviations();
2666 // Emit source line correspondence into a debug line section.
2669 // Emit info into a debug pubnames section.
2670 EmitDebugPubNames();
2672 // Emit info into a debug str section.
2675 // Emit info into a debug loc section.
2678 // Emit info into a debug aranges section.
2681 // Emit info into a debug ranges section.
2684 // Emit info into a debug macinfo section.
2688 /// BeginFunction - Gather pre-function debug information. Assumes being
2689 /// emitted immediately after the function entry point.
2690 void BeginFunction(MachineFunction *MF) {
2693 if (!ShouldEmitDwarf()) return;
2695 // Begin accumulating function debug information.
2696 MMI->BeginFunction(MF);
2698 // Assumes in correct section after the entry point.
2699 EmitLabel("func_begin", ++SubprogramCount);
2702 /// EndFunction - Gather and emit post-function debug information.
2704 void EndFunction() {
2705 if (!ShouldEmitDwarf()) return;
2707 // Define end label for subprogram.
2708 EmitLabel("func_end", SubprogramCount);
2710 // Get function line info.
2711 const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
2713 if (!LineInfos.empty()) {
2714 // Get section line info.
2715 unsigned ID = SectionMap.insert(Asm->CurrentSection);
2716 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2717 std::vector<SourceLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2718 // Append the function info to section info.
2719 SectionLineInfos.insert(SectionLineInfos.end(),
2720 LineInfos.begin(), LineInfos.end());
2723 // Construct scopes for subprogram.
2724 ConstructRootScope(MMI->getRootScope());
2726 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
2727 MMI->getFrameMoves()));
2731 //===----------------------------------------------------------------------===//
2732 /// DwarfException - Emits Dwarf exception handling directives.
2734 class DwarfException : public Dwarf {
2737 struct FunctionEHFrameInfo {
2740 unsigned PersonalityIndex;
2742 bool hasLandingPads;
2743 std::vector<MachineMove> Moves;
2745 FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
2747 const std::vector<MachineMove> &M):
2748 FnName(FN), Number(Num), PersonalityIndex(P),
2749 hasCalls(hC), hasLandingPads(hL), Moves(M) { }
2752 std::vector<FunctionEHFrameInfo> EHFrames;
2754 /// shouldEmit - Flag to indicate if debug information should be emitted.
2758 /// EmitCommonEHFrame - Emit the common eh unwind frame.
2760 void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
2761 // Size and sign of stack growth.
2763 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2764 TargetFrameInfo::StackGrowsUp ?
2765 TAI->getAddressSize() : -TAI->getAddressSize();
2767 // Begin eh frame section.
2768 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
2769 O << "EH_frame" << Index << ":\n";
2770 EmitLabel("section_eh_frame", Index);
2772 // Define base labels.
2773 EmitLabel("eh_frame_common", Index);
2775 // Define the eh frame length.
2776 EmitDifference("eh_frame_common_end", Index,
2777 "eh_frame_common_begin", Index, true);
2778 Asm->EOL("Length of Common Information Entry");
2781 EmitLabel("eh_frame_common_begin", Index);
2782 Asm->EmitInt32((int)0);
2783 Asm->EOL("CIE Identifier Tag");
2784 Asm->EmitInt8(DW_CIE_VERSION);
2785 Asm->EOL("CIE Version");
2787 // The personality presence indicates that language specific information
2788 // will show up in the eh frame.
2789 Asm->EmitString(Personality ? "zPLR" : "zR");
2790 Asm->EOL("CIE Augmentation");
2792 // Round out reader.
2793 Asm->EmitULEB128Bytes(1);
2794 Asm->EOL("CIE Code Alignment Factor");
2795 Asm->EmitSLEB128Bytes(stackGrowth);
2796 Asm->EOL("CIE Data Alignment Factor");
2797 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister()));
2798 Asm->EOL("CIE RA Column");
2800 // If there is a personality, we need to indicate the functions location.
2802 Asm->EmitULEB128Bytes(7);
2803 Asm->EOL("Augmentation Size");
2804 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
2805 Asm->EOL("Personality (pcrel sdata4)");
2807 if (TAI->needsSet()) {
2809 PrintLabelName("set", SetCounter);
2811 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
2812 O << "-" << TAI->getPCSymbol();
2813 Asm->EOL("Set Personality");
2814 O << TAI->getData32bitsDirective();
2815 PrintLabelName("set", SetCounter);
2816 Asm->EOL("Personality");
2819 O << TAI->getData32bitsDirective();
2820 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
2821 O << "-" << TAI->getPCSymbol();
2822 Asm->EOL("Personality");
2825 Asm->EmitULEB128Bytes(DW_EH_PE_pcrel);
2826 Asm->EOL("LSDA Encoding (pcrel)");
2827 Asm->EmitULEB128Bytes(DW_EH_PE_pcrel);
2828 Asm->EOL("FDE Encoding (pcrel)");
2830 Asm->EmitULEB128Bytes(1);
2831 Asm->EOL("Augmentation Size");
2832 Asm->EmitULEB128Bytes(DW_EH_PE_pcrel);
2833 Asm->EOL("FDE Encoding (pcrel)");
2836 // Indicate locations of general callee saved registers in frame.
2837 std::vector<MachineMove> Moves;
2838 RI->getInitialFrameState(Moves);
2839 EmitFrameMoves(NULL, 0, Moves);
2841 Asm->EmitAlignment(2);
2842 EmitLabel("eh_frame_common_end", Index);
2847 /// EmitEHFrame - Emit function exception frame information.
2849 void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
2850 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
2852 // Externally visible entry into the functions eh frame info.
2853 if (const char *GlobalDirective = TAI->getGlobalDirective())
2854 O << GlobalDirective << EHFrameInfo.FnName << ".eh\n";
2856 // If there are no calls then you can't unwind.
2857 if (!EHFrameInfo.hasCalls) {
2858 O << EHFrameInfo.FnName << ".eh = 0\n";
2860 O << EHFrameInfo.FnName << ".eh:\n";
2863 EmitDifference("eh_frame_end", EHFrameInfo.Number,
2864 "eh_frame_begin", EHFrameInfo.Number, true);
2865 Asm->EOL("Length of Frame Information Entry");
2867 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
2869 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
2870 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
2872 Asm->EOL("FDE CIE offset");
2874 EmitReference("eh_func_begin", EHFrameInfo.Number, true);
2875 Asm->EOL("FDE initial location");
2876 EmitDifference("eh_func_end", EHFrameInfo.Number,
2877 "eh_func_begin", EHFrameInfo.Number);
2878 Asm->EOL("FDE address range");
2880 // If there is a personality and landing pads then point to the language
2881 // specific data area in the exception table.
2882 if (EHFrameInfo.PersonalityIndex) {
2883 Asm->EmitULEB128Bytes(4);
2884 Asm->EOL("Augmentation size");
2886 if (EHFrameInfo.hasLandingPads) {
2887 EmitReference("exception", EHFrameInfo.Number, true);
2888 } else if(TAI->getAddressSize() == 8) {
2889 Asm->EmitInt64((int)0);
2891 Asm->EmitInt32((int)0);
2893 Asm->EOL("Language Specific Data Area");
2895 Asm->EmitULEB128Bytes(0);
2896 Asm->EOL("Augmentation size");
2899 // Indicate locations of function specific callee saved registers in
2901 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves);
2903 Asm->EmitAlignment(2);
2904 EmitLabel("eh_frame_end", EHFrameInfo.Number);
2907 if (const char *UsedDirective = TAI->getUsedDirective())
2908 O << UsedDirective << EHFrameInfo.FnName << ".eh\n\n";
2911 /// EmitExceptionTable - Emit landpads and actions.
2913 /// The general organization of the table is complex, but the basic concepts
2914 /// are easy. First there is a header which describes the location and
2915 /// organization of the three components that follow.
2916 /// 1. The landing pad site information describes the range of code covered
2917 /// by the try. In our case it's an accumulation of the ranges covered
2918 /// by the invokes in the try. There is also a reference to the landing
2919 /// pad that handles the exception once processed. Finally an index into
2920 /// the actions table.
2921 /// 2. The action table, in our case, is composed of pairs of type ids
2922 /// and next action offset. Starting with the action index from the
2923 /// landing pad site, each type Id is checked for a match to the current
2924 /// exception. If it matches then the exception and type id are passed
2925 /// on to the landing pad. Otherwise the next action is looked up. This
2926 /// chain is terminated with a next action of zero. If no type id is
2927 /// found the the frame is unwound and handling continues.
2928 /// 3. Type id table contains references to all the C++ typeinfo for all
2929 /// catches in the function. This tables is reversed indexed base 1.
2931 /// SharedTypeIds - How many leading type ids two landing pads have in common.
2932 static unsigned SharedTypeIds(const LandingPadInfo *L,
2933 const LandingPadInfo *R) {
2934 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
2935 unsigned LSize = LIds.size(), RSize = RIds.size();
2936 unsigned MinSize = LSize < RSize ? LSize : RSize;
2939 for (; Count != MinSize; ++Count)
2940 if (LIds[Count] != RIds[Count])
2946 /// PadLT - Order landing pads lexicographically by type id.
2947 static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
2948 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
2949 unsigned LSize = LIds.size(), RSize = RIds.size();
2950 unsigned MinSize = LSize < RSize ? LSize : RSize;
2952 for (unsigned i = 0; i != MinSize; ++i)
2953 if (LIds[i] != RIds[i])
2954 return LIds[i] < RIds[i];
2956 return LSize < RSize;
2960 static inline unsigned getEmptyKey() { return -1U; }
2961 static inline unsigned getTombstoneKey() { return -2U; }
2962 static unsigned getHashValue(const unsigned &Key) { return Key; }
2963 static bool isPod() { return true; }
2971 typedef DenseMap<unsigned, PadSite, KeyInfo> PadMapType;
2973 struct ActionEntry {
2974 int ValueForTypeID; // The value to write - may not be equal to the type id.
2976 struct ActionEntry *Previous;
2979 void EmitExceptionTable() {
2980 // Map all labels and get rid of any dead landing pads.
2981 MMI->TidyLandingPads();
2983 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
2984 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
2985 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
2986 if (PadInfos.empty()) return;
2988 // Sort the landing pads in order of their type ids. This is used to fold
2989 // duplicate actions.
2990 SmallVector<const LandingPadInfo *, 64> LandingPads;
2991 LandingPads.reserve(PadInfos.size());
2992 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
2993 LandingPads.push_back(&PadInfos[i]);
2994 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
2996 // Gather first action index for each landing pad site.
2997 SmallVector<unsigned, 64> FirstActions;
2998 FirstActions.reserve(PadInfos.size());
3000 // The actions table.
3001 SmallVector<ActionEntry, 32> Actions;
3003 // Negative type ids index into FilterIds, positive type ids index into
3004 // TypeInfos. The value written for a positive type id is just the type
3005 // id itself. For a negative type id, however, the value written is the
3006 // (negative) byte offset of the corresponding FilterIds entry. The byte
3007 // offset is usually equal to the type id, because the FilterIds entries
3008 // are written using a variable width encoding which outputs one byte per
3009 // entry as long as the value written is not too large, but can differ.
3010 // This kind of complication does not occur for positive type ids because
3011 // type infos are output using a fixed width encoding.
3012 // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
3013 SmallVector<int, 16> FilterOffsets;
3014 FilterOffsets.reserve(FilterIds.size());
3016 for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
3017 E = FilterIds.end(); I != E; ++I) {
3018 FilterOffsets.push_back(Offset);
3019 Offset -= Asm->SizeULEB128(*I);
3022 // Compute sizes for exception table.
3023 unsigned SizeSites = 0;
3024 unsigned SizeActions = 0;
3026 // Look at each landing pad site to compute size. We need the size of each
3027 // landing pad site info and the size of the landing pad's actions.
3028 int FirstAction = 0;
3030 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3031 const LandingPadInfo *LP = LandingPads[i];
3032 const std::vector<int> &TypeIds = LP->TypeIds;
3033 const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
3034 unsigned SizeSiteActions = 0;
3036 if (NumShared < TypeIds.size()) {
3037 unsigned SizeAction = 0;
3038 ActionEntry *PrevAction = 0;
3041 const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
3042 assert(Actions.size());
3043 PrevAction = &Actions.back();
3044 SizeAction = Asm->SizeSLEB128(PrevAction->NextAction) +
3045 Asm->SizeSLEB128(PrevAction->ValueForTypeID);
3046 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
3047 SizeAction -= Asm->SizeSLEB128(PrevAction->ValueForTypeID);
3048 SizeAction += -PrevAction->NextAction;
3049 PrevAction = PrevAction->Previous;
3053 // Compute the actions.
3054 for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
3055 int TypeID = TypeIds[I];
3056 assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
3057 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
3058 unsigned SizeTypeID = Asm->SizeSLEB128(ValueForTypeID);
3060 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
3061 SizeAction = SizeTypeID + Asm->SizeSLEB128(NextAction);
3062 SizeSiteActions += SizeAction;
3064 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
3065 Actions.push_back(Action);
3067 PrevAction = &Actions.back();
3070 // Record the first action of the landing pad site.
3071 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
3072 } // else identical - re-use previous FirstAction
3074 FirstActions.push_back(FirstAction);
3076 // Compute this sites contribution to size.
3077 SizeActions += SizeSiteActions;
3078 unsigned M = LP->BeginLabels.size();
3079 SizeSites += M*(sizeof(int32_t) + // Site start.
3080 sizeof(int32_t) + // Site length.
3081 sizeof(int32_t) + // Landing pad.
3082 Asm->SizeULEB128(FirstAction)); // Action.
3086 unsigned SizeTypes = TypeInfos.size() * TAI->getAddressSize();
3088 unsigned TypeOffset = sizeof(int8_t) + // Call site format
3089 Asm->SizeULEB128(SizeSites) + // Call-site table length
3090 SizeSites + SizeActions + SizeTypes;
3092 unsigned TotalSize = sizeof(int8_t) + // LPStart format
3093 sizeof(int8_t) + // TType format
3094 Asm->SizeULEB128(TypeOffset) + // TType base offset
3097 unsigned SizeAlign = (4 - TotalSize) & 3;
3099 // Begin the exception table.
3100 Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
3101 O << "GCC_except_table" << SubprogramCount << ":\n";
3102 Asm->EmitAlignment(2);
3103 for (unsigned i = 0; i != SizeAlign; ++i) {
3105 Asm->EOL("Padding");
3107 EmitLabel("exception", SubprogramCount);
3110 Asm->EmitInt8(DW_EH_PE_omit);
3111 Asm->EOL("LPStart format (DW_EH_PE_omit)");
3112 Asm->EmitInt8(DW_EH_PE_absptr);
3113 Asm->EOL("TType format (DW_EH_PE_absptr)");
3114 Asm->EmitULEB128Bytes(TypeOffset);
3115 Asm->EOL("TType base offset");
3116 Asm->EmitInt8(DW_EH_PE_udata4);
3117 Asm->EOL("Call site format (DW_EH_PE_udata4)");
3118 Asm->EmitULEB128Bytes(SizeSites);
3119 Asm->EOL("Call-site table length");
3121 // Emit the landing pad site information in order of address.
3124 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3125 const LandingPadInfo *LandingPad = LandingPads[i];
3126 for (unsigned j=0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
3127 unsigned BeginLabel = LandingPad->BeginLabels[j];
3128 assert(!PadMap.count(BeginLabel) && "duplicate landing pad labels!");
3129 PadSite P = { i, j };
3130 PadMap[BeginLabel] = P;
3134 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
3136 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
3138 if (MI->getOpcode() != TargetInstrInfo::LABEL)
3141 unsigned BeginLabel = MI->getOperand(0).getImmedValue();
3142 PadMapType::iterator L = PadMap.find(BeginLabel);
3144 if (L == PadMap.end())
3147 PadSite P = L->second;
3148 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
3150 assert(BeginLabel == LandingPad->BeginLabels[P.SiteIndex] &&
3151 "Inconsistent landing pad map!");
3153 EmitSectionOffset("label", "eh_func_begin", BeginLabel, SubprogramCount,
3155 Asm->EOL("Region start");
3157 EmitDifference("label", LandingPad->EndLabels[P.SiteIndex],
3158 "label", BeginLabel);
3159 Asm->EOL("Region length");
3161 if (LandingPad->TypeIds.empty()) {
3162 if (TAI->getAddressSize() == sizeof(int32_t))
3167 EmitSectionOffset("label", "eh_func_begin",
3168 LandingPad->LandingPadLabel, SubprogramCount,
3171 Asm->EOL("Landing pad");
3173 Asm->EmitULEB128Bytes(FirstActions[P.PadIndex]);
3178 // Emit the actions.
3179 for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
3180 ActionEntry &Action = Actions[I];
3182 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
3183 Asm->EOL("TypeInfo index");
3184 Asm->EmitSLEB128Bytes(Action.NextAction);
3185 Asm->EOL("Next action");
3188 // Emit the type ids.
3189 for (unsigned M = TypeInfos.size(); M; --M) {
3190 GlobalVariable *GV = TypeInfos[M - 1];
3192 if (TAI->getAddressSize() == sizeof(int32_t))
3193 O << TAI->getData32bitsDirective();
3195 O << TAI->getData64bitsDirective();
3198 O << Asm->getGlobalLinkName(GV);
3202 Asm->EOL("TypeInfo");
3205 // Emit the filter typeids.
3206 for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
3207 unsigned TypeID = FilterIds[j];
3208 Asm->EmitULEB128Bytes(TypeID);
3209 Asm->EOL("Filter TypeInfo index");
3212 Asm->EmitAlignment(2);
3216 //===--------------------------------------------------------------------===//
3217 // Main entry points.
3219 DwarfException(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3224 virtual ~DwarfException() {}
3226 /// SetModuleInfo - Set machine module information when it's known that pass
3227 /// manager has created it. Set by the target AsmPrinter.
3228 void SetModuleInfo(MachineModuleInfo *mmi) {
3232 /// BeginModule - Emit all exception information that should come prior to the
3234 void BeginModule(Module *M) {
3238 /// EndModule - Emit all exception information that should come after the
3241 if (!shouldEmit) return;
3243 const std::vector<Function *> Personalities = MMI->getPersonalities();
3244 for (unsigned i =0; i < Personalities.size(); ++i)
3245 EmitCommonEHFrame(Personalities[i], i);
3247 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
3248 E = EHFrames.end(); I != E; ++I)
3252 /// BeginFunction - Gather pre-function exception information. Assumes being
3253 /// emitted immediately after the function entry point.
3254 void BeginFunction(MachineFunction *MF) {
3258 ExceptionHandling &&
3259 TAI->doesSupportExceptionHandling()) {
3261 // Assumes in correct section after the entry point.
3262 EmitLabel("eh_func_begin", ++SubprogramCount);
3266 /// EndFunction - Gather and emit post-function exception information.
3268 void EndFunction() {
3269 if (!shouldEmit) return;
3271 EmitLabel("eh_func_end", SubprogramCount);
3272 EmitExceptionTable();
3274 // Save EH frame information
3275 EHFrames.push_back(FunctionEHFrameInfo(getAsm()->CurrentFnName,
3277 MMI->getPersonalityIndex(),
3278 MF->getFrameInfo()->hasCalls(),
3279 !MMI->getLandingPads().empty(),
3280 MMI->getFrameMoves()));
3284 } // End of namespace llvm
3286 //===----------------------------------------------------------------------===//
3288 /// Emit - Print the abbreviation using the specified Dwarf writer.
3290 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
3291 // Emit its Dwarf tag type.
3292 DD.getAsm()->EmitULEB128Bytes(Tag);
3293 DD.getAsm()->EOL(TagString(Tag));
3295 // Emit whether it has children DIEs.
3296 DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
3297 DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
3299 // For each attribute description.
3300 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3301 const DIEAbbrevData &AttrData = Data[i];
3303 // Emit attribute type.
3304 DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
3305 DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
3308 DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
3309 DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
3312 // Mark end of abbreviation.
3313 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
3314 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
3318 void DIEAbbrev::print(std::ostream &O) {
3319 O << "Abbreviation @"
3320 << std::hex << (intptr_t)this << std::dec
3324 << ChildrenString(ChildrenFlag)
3327 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3329 << AttributeString(Data[i].getAttribute())
3331 << FormEncodingString(Data[i].getForm())
3335 void DIEAbbrev::dump() { print(cerr); }
3338 //===----------------------------------------------------------------------===//
3341 void DIEValue::dump() {
3346 //===----------------------------------------------------------------------===//
3348 /// EmitValue - Emit integer of appropriate size.
3350 void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
3352 case DW_FORM_flag: // Fall thru
3353 case DW_FORM_ref1: // Fall thru
3354 case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer); break;
3355 case DW_FORM_ref2: // Fall thru
3356 case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer); break;
3357 case DW_FORM_ref4: // Fall thru
3358 case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer); break;
3359 case DW_FORM_ref8: // Fall thru
3360 case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer); break;
3361 case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
3362 case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
3363 default: assert(0 && "DIE Value form not supported yet"); break;
3367 /// SizeOf - Determine size of integer value in bytes.
3369 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3371 case DW_FORM_flag: // Fall thru
3372 case DW_FORM_ref1: // Fall thru
3373 case DW_FORM_data1: return sizeof(int8_t);
3374 case DW_FORM_ref2: // Fall thru
3375 case DW_FORM_data2: return sizeof(int16_t);
3376 case DW_FORM_ref4: // Fall thru
3377 case DW_FORM_data4: return sizeof(int32_t);
3378 case DW_FORM_ref8: // Fall thru
3379 case DW_FORM_data8: return sizeof(int64_t);
3380 case DW_FORM_udata: return DD.getAsm()->SizeULEB128(Integer);
3381 case DW_FORM_sdata: return DD.getAsm()->SizeSLEB128(Integer);
3382 default: assert(0 && "DIE Value form not supported yet"); break;
3387 //===----------------------------------------------------------------------===//
3389 /// EmitValue - Emit string value.
3391 void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
3392 DD.getAsm()->EmitString(String);
3395 //===----------------------------------------------------------------------===//
3397 /// EmitValue - Emit label value.
3399 void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
3400 DD.EmitReference(Label);
3403 /// SizeOf - Determine size of label value in bytes.
3405 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3406 return DD.getTargetAsmInfo()->getAddressSize();
3409 //===----------------------------------------------------------------------===//
3411 /// EmitValue - Emit label value.
3413 void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
3414 DD.EmitReference(Label);
3417 /// SizeOf - Determine size of label value in bytes.
3419 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3420 return DD.getTargetAsmInfo()->getAddressSize();
3423 //===----------------------------------------------------------------------===//
3425 /// EmitValue - Emit delta value.
3427 void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
3428 bool IsSmall = Form == DW_FORM_data4;
3429 DD.EmitDifference(LabelHi, LabelLo, IsSmall);
3432 /// SizeOf - Determine size of delta value in bytes.
3434 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3435 if (Form == DW_FORM_data4) return 4;
3436 return DD.getTargetAsmInfo()->getAddressSize();
3439 //===----------------------------------------------------------------------===//
3441 /// EmitValue - Emit debug information entry offset.
3443 void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
3444 DD.getAsm()->EmitInt32(Entry->getOffset());
3447 //===----------------------------------------------------------------------===//
3449 /// ComputeSize - calculate the size of the block.
3451 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
3453 const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
3455 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3456 Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
3462 /// EmitValue - Emit block data.
3464 void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
3466 case DW_FORM_block1: DD.getAsm()->EmitInt8(Size); break;
3467 case DW_FORM_block2: DD.getAsm()->EmitInt16(Size); break;
3468 case DW_FORM_block4: DD.getAsm()->EmitInt32(Size); break;
3469 case DW_FORM_block: DD.getAsm()->EmitULEB128Bytes(Size); break;
3470 default: assert(0 && "Improper form for block"); break;
3473 const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
3475 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3477 Values[i]->EmitValue(DD, AbbrevData[i].getForm());
3481 /// SizeOf - Determine size of block data in bytes.
3483 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3485 case DW_FORM_block1: return Size + sizeof(int8_t);
3486 case DW_FORM_block2: return Size + sizeof(int16_t);
3487 case DW_FORM_block4: return Size + sizeof(int32_t);
3488 case DW_FORM_block: return Size + DD.getAsm()->SizeULEB128(Size);
3489 default: assert(0 && "Improper form for block"); break;
3494 //===----------------------------------------------------------------------===//
3495 /// DIE Implementation
3498 for (unsigned i = 0, N = Children.size(); i < N; ++i)
3502 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
3504 void DIE::AddSiblingOffset() {
3505 DIEInteger *DI = new DIEInteger(0);
3506 Values.insert(Values.begin(), DI);
3507 Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
3510 /// Profile - Used to gather unique data for the value folding set.
3512 void DIE::Profile(FoldingSetNodeID &ID) {
3515 for (unsigned i = 0, N = Children.size(); i < N; ++i)
3516 ID.AddPointer(Children[i]);
3518 for (unsigned j = 0, M = Values.size(); j < M; ++j)
3519 ID.AddPointer(Values[j]);
3523 void DIE::print(std::ostream &O, unsigned IncIndent) {
3524 static unsigned IndentCount = 0;
3525 IndentCount += IncIndent;
3526 const std::string Indent(IndentCount, ' ');
3527 bool isBlock = Abbrev.getTag() == 0;
3532 << "0x" << std::hex << (intptr_t)this << std::dec
3533 << ", Offset: " << Offset
3534 << ", Size: " << Size
3538 << TagString(Abbrev.getTag())
3540 << ChildrenString(Abbrev.getChildrenFlag());
3542 O << "Size: " << Size;
3546 const std::vector<DIEAbbrevData> &Data = Abbrev.getData();
3549 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3552 O << AttributeString(Data[i].getAttribute());
3554 O << "Blk[" << i << "]";
3557 << FormEncodingString(Data[i].getForm())
3559 Values[i]->print(O);
3564 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
3565 Children[j]->print(O, 4);
3568 if (!isBlock) O << "\n";
3569 IndentCount -= IncIndent;
3577 //===----------------------------------------------------------------------===//
3578 /// DwarfWriter Implementation
3581 DwarfWriter::DwarfWriter(std::ostream &OS, AsmPrinter *A,
3582 const TargetAsmInfo *T) {
3583 DE = new DwarfException(OS, A, T);
3584 DD = new DwarfDebug(OS, A, T);
3587 DwarfWriter::~DwarfWriter() {
3592 /// SetModuleInfo - Set machine module info when it's known that pass manager
3593 /// has created it. Set by the target AsmPrinter.
3594 void DwarfWriter::SetModuleInfo(MachineModuleInfo *MMI) {
3595 DD->SetModuleInfo(MMI);
3596 DE->SetModuleInfo(MMI);
3599 /// BeginModule - Emit all Dwarf sections that should come prior to the
3601 void DwarfWriter::BeginModule(Module *M) {
3606 /// EndModule - Emit all Dwarf sections that should come after the content.
3608 void DwarfWriter::EndModule() {
3613 /// BeginFunction - Gather pre-function debug information. Assumes being
3614 /// emitted immediately after the function entry point.
3615 void DwarfWriter::BeginFunction(MachineFunction *MF) {
3616 DE->BeginFunction(MF);
3617 DD->BeginFunction(MF);
3620 /// EndFunction - Gather and emit post-function debug information.
3622 void DwarfWriter::EndFunction() {
3626 if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI()) {
3627 // Clear function debug information.