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;
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.
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 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 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 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 DIEObjectLabel(const std::string &L) : DIEValue(isAsIsLabel), Label(L) {}
478 // Implement isa/cast/dyncast.
479 static bool classof(const DIEObjectLabel *) { return true; }
480 static bool classof(const DIEValue *L) { return L->Type == isAsIsLabel; }
482 /// EmitValue - Emit label value.
484 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
486 /// SizeOf - Determine size of label value in bytes.
488 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
490 /// Profile - Used to gather unique data for the value folding set.
492 static void Profile(FoldingSetNodeID &ID, const std::string &Label) {
493 ID.AddInteger(isAsIsLabel);
496 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
499 virtual void print(std::ostream &O) {
500 O << "Obj: " << Label;
505 //===----------------------------------------------------------------------===//
506 /// DIEDelta - A simple label difference DIE.
508 class DIEDelta : public DIEValue {
510 const DWLabel LabelHi;
511 const DWLabel LabelLo;
513 DIEDelta(const DWLabel &Hi, const DWLabel &Lo)
514 : DIEValue(isDelta), LabelHi(Hi), LabelLo(Lo) {}
516 // Implement isa/cast/dyncast.
517 static bool classof(const DIEDelta *) { return true; }
518 static bool classof(const DIEValue *D) { return D->Type == isDelta; }
520 /// EmitValue - Emit delta value.
522 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
524 /// SizeOf - Determine size of delta value in bytes.
526 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
528 /// Profile - Used to gather unique data for the value folding set.
530 static void Profile(FoldingSetNodeID &ID, const DWLabel &LabelHi,
531 const DWLabel &LabelLo) {
532 ID.AddInteger(isDelta);
536 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, LabelHi, LabelLo); }
539 virtual void print(std::ostream &O) {
548 //===----------------------------------------------------------------------===//
549 /// DIEntry - A pointer to another debug information entry. An instance of this
550 /// class can also be used as a proxy for a debug information entry not yet
551 /// defined (ie. types.)
552 class DIEntry : public DIEValue {
556 DIEntry(DIE *E) : DIEValue(isEntry), Entry(E) {}
558 // Implement isa/cast/dyncast.
559 static bool classof(const DIEntry *) { return true; }
560 static bool classof(const DIEValue *E) { return E->Type == isEntry; }
562 /// EmitValue - Emit debug information entry offset.
564 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
566 /// SizeOf - Determine size of debug information entry in bytes.
568 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
569 return sizeof(int32_t);
572 /// Profile - Used to gather unique data for the value folding set.
574 static void Profile(FoldingSetNodeID &ID, DIE *Entry) {
575 ID.AddInteger(isEntry);
576 ID.AddPointer(Entry);
578 virtual void Profile(FoldingSetNodeID &ID) {
579 ID.AddInteger(isEntry);
582 ID.AddPointer(Entry);
589 virtual void print(std::ostream &O) {
590 O << "Die: 0x" << std::hex << (intptr_t)Entry << std::dec;
595 //===----------------------------------------------------------------------===//
596 /// DIEBlock - A block of values. Primarily used for location expressions.
598 class DIEBlock : public DIEValue, public DIE {
600 unsigned Size; // Size in bytes excluding size header.
610 // Implement isa/cast/dyncast.
611 static bool classof(const DIEBlock *) { return true; }
612 static bool classof(const DIEValue *E) { return E->Type == isBlock; }
614 /// ComputeSize - calculate the size of the block.
616 unsigned ComputeSize(DwarfDebug &DD);
618 /// BestForm - Choose the best form for data.
620 unsigned BestForm() const {
621 if ((unsigned char)Size == Size) return DW_FORM_block1;
622 if ((unsigned short)Size == Size) return DW_FORM_block2;
623 if ((unsigned int)Size == Size) return DW_FORM_block4;
624 return DW_FORM_block;
627 /// EmitValue - Emit block data.
629 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
631 /// SizeOf - Determine size of block data in bytes.
633 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
636 /// Profile - Used to gather unique data for the value folding set.
638 virtual void Profile(FoldingSetNodeID &ID) {
639 ID.AddInteger(isBlock);
644 virtual void print(std::ostream &O) {
651 //===----------------------------------------------------------------------===//
652 /// CompileUnit - This dwarf writer support class manages information associate
653 /// with a source file.
656 /// Desc - Compile unit debug descriptor.
658 CompileUnitDesc *Desc;
660 /// ID - File identifier for source.
664 /// Die - Compile unit debug information entry.
668 /// DescToDieMap - Tracks the mapping of unit level debug informaton
669 /// descriptors to debug information entries.
670 std::map<DebugInfoDesc *, DIE *> DescToDieMap;
672 /// DescToDIEntryMap - Tracks the mapping of unit level debug informaton
673 /// descriptors to debug information entries using a DIEntry proxy.
674 std::map<DebugInfoDesc *, DIEntry *> DescToDIEntryMap;
676 /// Globals - A map of globally visible named entities for this unit.
678 std::map<std::string, DIE *> Globals;
680 /// DiesSet - Used to uniquely define dies within the compile unit.
682 FoldingSet<DIE> DiesSet;
684 /// Dies - List of all dies in the compile unit.
686 std::vector<DIE *> Dies;
689 CompileUnit(CompileUnitDesc *CUD, unsigned I, DIE *D)
696 , DiesSet(InitDiesSetSize)
703 for (unsigned i = 0, N = Dies.size(); i < N; ++i)
708 CompileUnitDesc *getDesc() const { return Desc; }
709 unsigned getID() const { return ID; }
710 DIE* getDie() const { return Die; }
711 std::map<std::string, DIE *> &getGlobals() { return Globals; }
713 /// hasContent - Return true if this compile unit has something to write out.
715 bool hasContent() const {
716 return !Die->getChildren().empty();
719 /// AddGlobal - Add a new global entity to the compile unit.
721 void AddGlobal(const std::string &Name, DIE *Die) {
725 /// getDieMapSlotFor - Returns the debug information entry map slot for the
726 /// specified debug descriptor.
727 DIE *&getDieMapSlotFor(DebugInfoDesc *DID) {
728 return DescToDieMap[DID];
731 /// getDIEntrySlotFor - Returns the debug information entry proxy slot for the
732 /// specified debug descriptor.
733 DIEntry *&getDIEntrySlotFor(DebugInfoDesc *DID) {
734 return DescToDIEntryMap[DID];
737 /// AddDie - Adds or interns the DIE to the compile unit.
739 DIE *AddDie(DIE &Buffer) {
743 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
746 Die = new DIE(Buffer);
747 DiesSet.InsertNode(Die, Where);
748 this->Die->AddChild(Die);
756 //===----------------------------------------------------------------------===//
757 /// Dwarf - Emits general Dwarf directives.
763 //===--------------------------------------------------------------------===//
764 // Core attributes used by the Dwarf writer.
768 /// O - Stream to .s file.
772 /// Asm - Target of Dwarf emission.
776 /// TAI - Target Asm Printer.
777 const TargetAsmInfo *TAI;
779 /// TD - Target data.
780 const TargetData *TD;
782 /// RI - Register Information.
783 const MRegisterInfo *RI;
785 /// M - Current module.
789 /// MF - Current machine function.
793 /// MMI - Collected machine module information.
795 MachineModuleInfo *MMI;
797 /// SubprogramCount - The running count of functions being compiled.
799 unsigned SubprogramCount;
802 Dwarf(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
806 , TD(Asm->TM.getTargetData())
807 , RI(Asm->TM.getRegisterInfo())
818 //===--------------------------------------------------------------------===//
821 AsmPrinter *getAsm() const { return Asm; }
822 MachineModuleInfo *getMMI() const { return MMI; }
823 const TargetAsmInfo *getTargetAsmInfo() const { return TAI; }
825 /// PrintLabelName - Print label name in form used by Dwarf writer.
827 void PrintLabelName(DWLabel Label) const {
828 PrintLabelName(Label.Tag, Label.Number);
830 void PrintLabelName(const char *Tag, unsigned Number,
831 bool isInSection = false) const {
832 if (isInSection && TAI->getDwarfSectionOffsetDirective())
833 O << TAI->getDwarfSectionOffsetDirective() << Tag;
835 O << TAI->getPrivateGlobalPrefix() << Tag;
836 if (Number) O << Number;
839 /// EmitLabel - Emit location label for internal use by Dwarf.
841 void EmitLabel(DWLabel Label) const {
842 EmitLabel(Label.Tag, Label.Number);
844 void EmitLabel(const char *Tag, unsigned Number) const {
845 PrintLabelName(Tag, Number);
849 /// EmitReference - Emit a reference to a label.
851 void EmitReference(DWLabel Label, bool IsPCRelative = false) const {
852 EmitReference(Label.Tag, Label.Number, IsPCRelative);
854 void EmitReference(const char *Tag, unsigned Number,
855 bool IsPCRelative = false) const {
856 if (TAI->getAddressSize() == sizeof(int32_t))
857 O << TAI->getData32bitsDirective();
859 O << TAI->getData64bitsDirective();
861 PrintLabelName(Tag, Number);
863 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
865 void EmitReference(const std::string &Name, bool IsPCRelative = false) const {
866 if (TAI->getAddressSize() == sizeof(int32_t))
867 O << TAI->getData32bitsDirective();
869 O << TAI->getData64bitsDirective();
873 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
876 /// EmitDifference - Emit the difference between two labels. Some
877 /// assemblers do not behave with absolute expressions with data directives,
878 /// so there is an option (needsSet) to use an intermediary set expression.
879 void EmitDifference(DWLabel LabelHi, DWLabel LabelLo,
880 bool IsSmall = false) {
881 EmitDifference(LabelHi.Tag, LabelHi.Number,
882 LabelLo.Tag, LabelLo.Number,
885 void EmitDifference(const char *TagHi, unsigned NumberHi,
886 const char *TagLo, unsigned NumberLo,
887 bool IsSmall = false) {
888 if (TAI->needsSet()) {
890 PrintLabelName("set", SetCounter);
892 PrintLabelName(TagHi, NumberHi);
894 PrintLabelName(TagLo, NumberLo);
897 if (IsSmall || TAI->getAddressSize() == sizeof(int32_t))
898 O << TAI->getData32bitsDirective();
900 O << TAI->getData64bitsDirective();
902 PrintLabelName("set", SetCounter);
906 if (IsSmall || TAI->getAddressSize() == sizeof(int32_t))
907 O << TAI->getData32bitsDirective();
909 O << TAI->getData64bitsDirective();
911 PrintLabelName(TagHi, NumberHi);
913 PrintLabelName(TagLo, NumberLo);
917 void EmitSectionOffset(const char* Label, const char* Section,
918 unsigned LabelNumber, unsigned SectionNumber,
919 bool IsSmall = false, bool isEH = false) {
920 bool printAbsolute = false;
921 if (TAI->needsSet()) {
923 PrintLabelName("set", SetCounter);
925 PrintLabelName(Label, LabelNumber, true);
928 printAbsolute = TAI->isAbsoluteEHSectionOffsets();
930 printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
932 if (!printAbsolute) {
934 PrintLabelName(Section, SectionNumber);
938 if (IsSmall || TAI->getAddressSize() == sizeof(int32_t))
939 O << TAI->getData32bitsDirective();
941 O << TAI->getData64bitsDirective();
943 PrintLabelName("set", SetCounter);
946 if (IsSmall || TAI->getAddressSize() == sizeof(int32_t))
947 O << TAI->getData32bitsDirective();
949 O << TAI->getData64bitsDirective();
951 PrintLabelName(Label, LabelNumber, true);
954 printAbsolute = TAI->isAbsoluteEHSectionOffsets();
956 printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
958 if (!printAbsolute) {
960 PrintLabelName(Section, SectionNumber);
965 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
967 void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
968 const std::vector<MachineMove> &Moves) {
970 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
971 TargetFrameInfo::StackGrowsUp ?
972 TAI->getAddressSize() : -TAI->getAddressSize();
973 bool IsLocal = BaseLabel && strcmp(BaseLabel, "label") == 0;
975 for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
976 const MachineMove &Move = Moves[i];
977 unsigned LabelID = Move.getLabelID();
980 LabelID = MMI->MappedLabel(LabelID);
982 // Throw out move if the label is invalid.
983 if (!LabelID) continue;
986 const MachineLocation &Dst = Move.getDestination();
987 const MachineLocation &Src = Move.getSource();
989 // Advance row if new location.
990 if (BaseLabel && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
991 Asm->EmitInt8(DW_CFA_advance_loc4);
992 Asm->EOL("DW_CFA_advance_loc4");
993 EmitDifference("label", LabelID, BaseLabel, BaseLabelID, true);
996 BaseLabelID = LabelID;
1001 // If advancing cfa.
1002 if (Dst.isRegister() && Dst.getRegister() == MachineLocation::VirtualFP) {
1003 if (!Src.isRegister()) {
1004 if (Src.getRegister() == MachineLocation::VirtualFP) {
1005 Asm->EmitInt8(DW_CFA_def_cfa_offset);
1006 Asm->EOL("DW_CFA_def_cfa_offset");
1008 Asm->EmitInt8(DW_CFA_def_cfa);
1009 Asm->EOL("DW_CFA_def_cfa");
1010 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getRegister()));
1011 Asm->EOL("Register");
1014 int Offset = -Src.getOffset();
1016 Asm->EmitULEB128Bytes(Offset);
1019 assert(0 && "Machine move no supported yet.");
1021 } else if (Src.isRegister() &&
1022 Src.getRegister() == MachineLocation::VirtualFP) {
1023 if (Dst.isRegister()) {
1024 Asm->EmitInt8(DW_CFA_def_cfa_register);
1025 Asm->EOL("DW_CFA_def_cfa_register");
1026 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getRegister()));
1027 Asm->EOL("Register");
1029 assert(0 && "Machine move no supported yet.");
1032 unsigned Reg = RI->getDwarfRegNum(Src.getRegister());
1033 int Offset = Dst.getOffset() / stackGrowth;
1036 Asm->EmitInt8(DW_CFA_offset_extended_sf);
1037 Asm->EOL("DW_CFA_offset_extended_sf");
1038 Asm->EmitULEB128Bytes(Reg);
1040 Asm->EmitSLEB128Bytes(Offset);
1042 } else if (Reg < 64) {
1043 Asm->EmitInt8(DW_CFA_offset + Reg);
1044 Asm->EOL("DW_CFA_offset + Reg (" + utostr(Reg) + ")");
1045 Asm->EmitULEB128Bytes(Offset);
1048 Asm->EmitInt8(DW_CFA_offset_extended);
1049 Asm->EOL("DW_CFA_offset_extended");
1050 Asm->EmitULEB128Bytes(Reg);
1052 Asm->EmitULEB128Bytes(Offset);
1061 //===----------------------------------------------------------------------===//
1062 /// DwarfDebug - Emits Dwarf debug directives.
1064 class DwarfDebug : public Dwarf {
1067 //===--------------------------------------------------------------------===//
1068 // Attributes used to construct specific Dwarf sections.
1071 /// CompileUnits - All the compile units involved in this build. The index
1072 /// of each entry in this vector corresponds to the sources in MMI.
1073 std::vector<CompileUnit *> CompileUnits;
1075 /// AbbreviationsSet - Used to uniquely define abbreviations.
1077 FoldingSet<DIEAbbrev> AbbreviationsSet;
1079 /// Abbreviations - A list of all the unique abbreviations in use.
1081 std::vector<DIEAbbrev *> Abbreviations;
1083 /// ValuesSet - Used to uniquely define values.
1085 FoldingSet<DIEValue> ValuesSet;
1087 /// Values - A list of all the unique values in use.
1089 std::vector<DIEValue *> Values;
1091 /// StringPool - A UniqueVector of strings used by indirect references.
1093 UniqueVector<std::string> StringPool;
1095 /// UnitMap - Map debug information descriptor to compile unit.
1097 std::map<DebugInfoDesc *, CompileUnit *> DescToUnitMap;
1099 /// SectionMap - Provides a unique id per text section.
1101 UniqueVector<std::string> SectionMap;
1103 /// SectionSourceLines - Tracks line numbers per text section.
1105 std::vector<std::vector<SourceLineInfo> > SectionSourceLines;
1107 /// didInitial - Flag to indicate if initial emission has been done.
1111 /// shouldEmit - Flag to indicate if debug information should be emitted.
1115 struct FunctionDebugFrameInfo {
1117 std::vector<MachineMove> Moves;
1119 FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
1120 Number(Num), Moves(M) { };
1123 std::vector<FunctionDebugFrameInfo> DebugFrames;
1127 /// ShouldEmitDwarf - Returns true if Dwarf declarations should be made.
1129 bool ShouldEmitDwarf() const { return shouldEmit; }
1131 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1133 void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1134 // Profile the node so that we can make it unique.
1135 FoldingSetNodeID ID;
1138 // Check the set for priors.
1139 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1141 // If it's newly added.
1142 if (InSet == &Abbrev) {
1143 // Add to abbreviation list.
1144 Abbreviations.push_back(&Abbrev);
1145 // Assign the vector position + 1 as its number.
1146 Abbrev.setNumber(Abbreviations.size());
1148 // Assign existing abbreviation number.
1149 Abbrev.setNumber(InSet->getNumber());
1153 /// NewString - Add a string to the constant pool and returns a label.
1155 DWLabel NewString(const std::string &String) {
1156 unsigned StringID = StringPool.insert(String);
1157 return DWLabel("string", StringID);
1160 /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1162 DIEntry *NewDIEntry(DIE *Entry = NULL) {
1166 FoldingSetNodeID ID;
1167 DIEntry::Profile(ID, Entry);
1169 Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1171 if (Value) return Value;
1173 Value = new DIEntry(Entry);
1174 ValuesSet.InsertNode(Value, Where);
1176 Value = new DIEntry(Entry);
1179 Values.push_back(Value);
1183 /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1185 void SetDIEntry(DIEntry *Value, DIE *Entry) {
1186 Value->Entry = Entry;
1187 // Add to values set if not already there. If it is, we merely have a
1188 // duplicate in the values list (no harm.)
1189 ValuesSet.GetOrInsertNode(Value);
1192 /// AddUInt - Add an unsigned integer attribute data and value.
1194 void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1195 if (!Form) Form = DIEInteger::BestForm(false, Integer);
1197 FoldingSetNodeID ID;
1198 DIEInteger::Profile(ID, Integer);
1200 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1202 Value = new DIEInteger(Integer);
1203 ValuesSet.InsertNode(Value, Where);
1204 Values.push_back(Value);
1207 Die->AddValue(Attribute, Form, Value);
1210 /// AddSInt - Add an signed integer attribute data and value.
1212 void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1213 if (!Form) Form = DIEInteger::BestForm(true, Integer);
1215 FoldingSetNodeID ID;
1216 DIEInteger::Profile(ID, (uint64_t)Integer);
1218 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1220 Value = new DIEInteger(Integer);
1221 ValuesSet.InsertNode(Value, Where);
1222 Values.push_back(Value);
1225 Die->AddValue(Attribute, Form, Value);
1228 /// AddString - Add a std::string attribute data and value.
1230 void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1231 const std::string &String) {
1232 FoldingSetNodeID ID;
1233 DIEString::Profile(ID, String);
1235 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1237 Value = new DIEString(String);
1238 ValuesSet.InsertNode(Value, Where);
1239 Values.push_back(Value);
1242 Die->AddValue(Attribute, Form, Value);
1245 /// AddLabel - Add a Dwarf label attribute data and value.
1247 void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1248 const DWLabel &Label) {
1249 FoldingSetNodeID ID;
1250 DIEDwarfLabel::Profile(ID, Label);
1252 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1254 Value = new DIEDwarfLabel(Label);
1255 ValuesSet.InsertNode(Value, Where);
1256 Values.push_back(Value);
1259 Die->AddValue(Attribute, Form, Value);
1262 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1264 void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1265 const std::string &Label) {
1266 FoldingSetNodeID ID;
1267 DIEObjectLabel::Profile(ID, Label);
1269 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1271 Value = new DIEObjectLabel(Label);
1272 ValuesSet.InsertNode(Value, Where);
1273 Values.push_back(Value);
1276 Die->AddValue(Attribute, Form, Value);
1279 /// AddDelta - Add a label delta attribute data and value.
1281 void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1282 const DWLabel &Hi, const DWLabel &Lo) {
1283 FoldingSetNodeID ID;
1284 DIEDelta::Profile(ID, Hi, Lo);
1286 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1288 Value = new DIEDelta(Hi, Lo);
1289 ValuesSet.InsertNode(Value, Where);
1290 Values.push_back(Value);
1293 Die->AddValue(Attribute, Form, Value);
1296 /// AddDIEntry - Add a DIE attribute data and value.
1298 void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1299 Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1302 /// AddBlock - Add block data.
1304 void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1305 Block->ComputeSize(*this);
1306 FoldingSetNodeID ID;
1309 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1312 ValuesSet.InsertNode(Value, Where);
1313 Values.push_back(Value);
1318 Die->AddValue(Attribute, Block->BestForm(), Value);
1323 /// AddSourceLine - Add location information to specified debug information
1325 void AddSourceLine(DIE *Die, CompileUnitDesc *File, unsigned Line) {
1327 CompileUnit *FileUnit = FindCompileUnit(File);
1328 unsigned FileID = FileUnit->getID();
1329 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1330 AddUInt(Die, DW_AT_decl_line, 0, Line);
1334 /// AddAddress - Add an address attribute to a die based on the location
1336 void AddAddress(DIE *Die, unsigned Attribute,
1337 const MachineLocation &Location) {
1338 unsigned Reg = RI->getDwarfRegNum(Location.getRegister());
1339 DIEBlock *Block = new DIEBlock();
1341 if (Location.isRegister()) {
1343 AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1345 AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1346 AddUInt(Block, 0, DW_FORM_udata, Reg);
1350 AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1352 AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1353 AddUInt(Block, 0, DW_FORM_udata, Reg);
1355 AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1358 AddBlock(Die, Attribute, 0, Block);
1361 /// AddBasicType - Add a new basic type attribute to the specified entity.
1363 void AddBasicType(DIE *Entity, CompileUnit *Unit,
1364 const std::string &Name,
1365 unsigned Encoding, unsigned Size) {
1366 DIE *Die = ConstructBasicType(Unit, Name, Encoding, Size);
1367 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, Die);
1370 /// ConstructBasicType - Construct a new basic type.
1372 DIE *ConstructBasicType(CompileUnit *Unit,
1373 const std::string &Name,
1374 unsigned Encoding, unsigned Size) {
1375 DIE Buffer(DW_TAG_base_type);
1376 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1377 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, Encoding);
1378 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1379 return Unit->AddDie(Buffer);
1382 /// AddPointerType - Add a new pointer type attribute to the specified entity.
1384 void AddPointerType(DIE *Entity, CompileUnit *Unit, const std::string &Name) {
1385 DIE *Die = ConstructPointerType(Unit, Name);
1386 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, Die);
1389 /// ConstructPointerType - Construct a new pointer type.
1391 DIE *ConstructPointerType(CompileUnit *Unit, const std::string &Name) {
1392 DIE Buffer(DW_TAG_pointer_type);
1393 AddUInt(&Buffer, DW_AT_byte_size, 0, TAI->getAddressSize());
1394 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1395 return Unit->AddDie(Buffer);
1398 /// AddType - Add a new type attribute to the specified entity.
1400 void AddType(DIE *Entity, TypeDesc *TyDesc, CompileUnit *Unit) {
1402 AddBasicType(Entity, Unit, "", DW_ATE_signed, sizeof(int32_t));
1404 // Check for pre-existence.
1405 DIEntry *&Slot = Unit->getDIEntrySlotFor(TyDesc);
1407 // If it exists then use the existing value.
1409 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1413 if (SubprogramDesc *SubprogramTy = dyn_cast<SubprogramDesc>(TyDesc)) {
1414 // FIXME - Not sure why programs and variables are coming through here.
1415 // Short cut for handling subprogram types (not really a TyDesc.)
1416 AddPointerType(Entity, Unit, SubprogramTy->getName());
1417 } else if (GlobalVariableDesc *GlobalTy =
1418 dyn_cast<GlobalVariableDesc>(TyDesc)) {
1419 // FIXME - Not sure why programs and variables are coming through here.
1420 // Short cut for handling global variable types (not really a TyDesc.)
1421 AddPointerType(Entity, Unit, GlobalTy->getName());
1424 Slot = NewDIEntry();
1427 DIE Buffer(DW_TAG_base_type);
1428 ConstructType(Buffer, TyDesc, Unit);
1430 // Add debug information entry to entity and unit.
1431 DIE *Die = Unit->AddDie(Buffer);
1432 SetDIEntry(Slot, Die);
1433 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1438 /// ConstructType - Adds all the required attributes to the type.
1440 void ConstructType(DIE &Buffer, TypeDesc *TyDesc, CompileUnit *Unit) {
1441 // Get core information.
1442 const std::string &Name = TyDesc->getName();
1443 uint64_t Size = TyDesc->getSize() >> 3;
1445 if (BasicTypeDesc *BasicTy = dyn_cast<BasicTypeDesc>(TyDesc)) {
1446 // Fundamental types like int, float, bool
1447 Buffer.setTag(DW_TAG_base_type);
1448 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BasicTy->getEncoding());
1449 } else if (DerivedTypeDesc *DerivedTy = dyn_cast<DerivedTypeDesc>(TyDesc)) {
1451 unsigned Tag = DerivedTy->getTag();
1452 // FIXME - Workaround for templates.
1453 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1454 // Pointers, typedefs et al.
1456 // Map to main type, void will not have a type.
1457 if (TypeDesc *FromTy = DerivedTy->getFromType())
1458 AddType(&Buffer, FromTy, Unit);
1459 } else if (CompositeTypeDesc *CompTy = dyn_cast<CompositeTypeDesc>(TyDesc)){
1461 unsigned Tag = CompTy->getTag();
1463 // Set tag accordingly.
1464 if (Tag == DW_TAG_vector_type)
1465 Buffer.setTag(DW_TAG_array_type);
1469 std::vector<DebugInfoDesc *> &Elements = CompTy->getElements();
1472 case DW_TAG_vector_type:
1473 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1475 case DW_TAG_array_type: {
1476 // Add element type.
1477 if (TypeDesc *FromTy = CompTy->getFromType())
1478 AddType(&Buffer, FromTy, Unit);
1480 // Don't emit size attribute.
1483 // Construct an anonymous type for index type.
1484 DIE *IndexTy = ConstructBasicType(Unit, "", DW_ATE_signed,
1487 // Add subranges to array type.
1488 for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1489 SubrangeDesc *SRD = cast<SubrangeDesc>(Elements[i]);
1490 int64_t Lo = SRD->getLo();
1491 int64_t Hi = SRD->getHi();
1492 DIE *Subrange = new DIE(DW_TAG_subrange_type);
1494 // If a range is available.
1496 AddDIEntry(Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1497 // Only add low if non-zero.
1498 if (Lo) AddSInt(Subrange, DW_AT_lower_bound, 0, Lo);
1499 AddSInt(Subrange, DW_AT_upper_bound, 0, Hi);
1502 Buffer.AddChild(Subrange);
1506 case DW_TAG_structure_type:
1507 case DW_TAG_union_type: {
1508 // Add elements to structure type.
1509 for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1510 DebugInfoDesc *Element = Elements[i];
1512 if (DerivedTypeDesc *MemberDesc = dyn_cast<DerivedTypeDesc>(Element)){
1513 // Add field or base class.
1515 unsigned Tag = MemberDesc->getTag();
1517 // Extract the basic information.
1518 const std::string &Name = MemberDesc->getName();
1519 uint64_t Size = MemberDesc->getSize();
1520 uint64_t Align = MemberDesc->getAlign();
1521 uint64_t Offset = MemberDesc->getOffset();
1523 // Construct member debug information entry.
1524 DIE *Member = new DIE(Tag);
1526 // Add name if not "".
1528 AddString(Member, DW_AT_name, DW_FORM_string, Name);
1529 // Add location if available.
1530 AddSourceLine(Member, MemberDesc->getFile(), MemberDesc->getLine());
1532 // Most of the time the field info is the same as the members.
1533 uint64_t FieldSize = Size;
1534 uint64_t FieldAlign = Align;
1535 uint64_t FieldOffset = Offset;
1537 // Set the member type.
1538 TypeDesc *FromTy = MemberDesc->getFromType();
1539 AddType(Member, FromTy, Unit);
1541 // Walk up typedefs until a real size is found.
1543 if (FromTy->getTag() != DW_TAG_typedef) {
1544 FieldSize = FromTy->getSize();
1545 FieldAlign = FromTy->getSize();
1549 FromTy = cast<DerivedTypeDesc>(FromTy)->getFromType();
1552 // Unless we have a bit field.
1553 if (Tag == DW_TAG_member && FieldSize != Size) {
1554 // Construct the alignment mask.
1555 uint64_t AlignMask = ~(FieldAlign - 1);
1556 // Determine the high bit + 1 of the declared size.
1557 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1558 // Work backwards to determine the base offset of the field.
1559 FieldOffset = HiMark - FieldSize;
1560 // Now normalize offset to the field.
1561 Offset -= FieldOffset;
1563 // Maybe we need to work from the other end.
1564 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1566 // Add size and offset.
1567 AddUInt(Member, DW_AT_byte_size, 0, FieldSize >> 3);
1568 AddUInt(Member, DW_AT_bit_size, 0, Size);
1569 AddUInt(Member, DW_AT_bit_offset, 0, Offset);
1572 // Add computation for offset.
1573 DIEBlock *Block = new DIEBlock();
1574 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1575 AddUInt(Block, 0, DW_FORM_udata, FieldOffset >> 3);
1576 AddBlock(Member, DW_AT_data_member_location, 0, Block);
1578 // Add accessibility (public default unless is base class.
1579 if (MemberDesc->isProtected()) {
1580 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_protected);
1581 } else if (MemberDesc->isPrivate()) {
1582 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_private);
1583 } else if (Tag == DW_TAG_inheritance) {
1584 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_public);
1587 Buffer.AddChild(Member);
1588 } else if (GlobalVariableDesc *StaticDesc =
1589 dyn_cast<GlobalVariableDesc>(Element)) {
1590 // Add static member.
1592 // Construct member debug information entry.
1593 DIE *Static = new DIE(DW_TAG_variable);
1595 // Add name and mangled name.
1596 const std::string &Name = StaticDesc->getName();
1597 const std::string &LinkageName = StaticDesc->getLinkageName();
1598 AddString(Static, DW_AT_name, DW_FORM_string, Name);
1599 if (!LinkageName.empty()) {
1600 AddString(Static, DW_AT_MIPS_linkage_name, DW_FORM_string,
1605 AddSourceLine(Static, StaticDesc->getFile(), StaticDesc->getLine());
1608 if (TypeDesc *StaticTy = StaticDesc->getType())
1609 AddType(Static, StaticTy, Unit);
1612 if (!StaticDesc->isStatic())
1613 AddUInt(Static, DW_AT_external, DW_FORM_flag, 1);
1614 AddUInt(Static, DW_AT_declaration, DW_FORM_flag, 1);
1616 Buffer.AddChild(Static);
1617 } else if (SubprogramDesc *MethodDesc =
1618 dyn_cast<SubprogramDesc>(Element)) {
1619 // Add member function.
1621 // Construct member debug information entry.
1622 DIE *Method = new DIE(DW_TAG_subprogram);
1624 // Add name and mangled name.
1625 const std::string &Name = MethodDesc->getName();
1626 const std::string &LinkageName = MethodDesc->getLinkageName();
1628 AddString(Method, DW_AT_name, DW_FORM_string, Name);
1629 bool IsCTor = TyDesc->getName() == Name;
1631 if (!LinkageName.empty()) {
1632 AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string,
1637 AddSourceLine(Method, MethodDesc->getFile(), MethodDesc->getLine());
1640 if (CompositeTypeDesc *MethodTy =
1641 dyn_cast_or_null<CompositeTypeDesc>(MethodDesc->getType())) {
1642 // Get argument information.
1643 std::vector<DebugInfoDesc *> &Args = MethodTy->getElements();
1648 AddType(Method, dyn_cast<TypeDesc>(Args[0]), Unit);
1652 for(unsigned i = 1, N = Args.size(); i < N; ++i) {
1653 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1654 AddType(Arg, cast<TypeDesc>(Args[i]), Unit);
1655 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1);
1656 Method->AddChild(Arg);
1661 if (!MethodDesc->isStatic())
1662 AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);
1663 AddUInt(Method, DW_AT_declaration, DW_FORM_flag, 1);
1665 Buffer.AddChild(Method);
1670 case DW_TAG_enumeration_type: {
1671 // Add enumerators to enumeration type.
1672 for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1673 EnumeratorDesc *ED = cast<EnumeratorDesc>(Elements[i]);
1674 const std::string &Name = ED->getName();
1675 int64_t Value = ED->getValue();
1676 DIE *Enumerator = new DIE(DW_TAG_enumerator);
1677 AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
1678 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1679 Buffer.AddChild(Enumerator);
1684 case DW_TAG_subroutine_type: {
1685 // Add prototype flag.
1686 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1688 AddType(&Buffer, dyn_cast<TypeDesc>(Elements[0]), Unit);
1691 for(unsigned i = 1, N = Elements.size(); i < N; ++i) {
1692 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1693 AddType(Arg, cast<TypeDesc>(Elements[i]), Unit);
1694 Buffer.AddChild(Arg);
1703 // Add size if non-zero (derived types don't have a size.)
1704 if (Size) AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1705 // Add name if not anonymous or intermediate type.
1706 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1707 // Add source line info if available.
1708 AddSourceLine(&Buffer, TyDesc->getFile(), TyDesc->getLine());
1711 /// NewCompileUnit - Create new compile unit and it's debug information entry.
1713 CompileUnit *NewCompileUnit(CompileUnitDesc *UnitDesc, unsigned ID) {
1714 // Construct debug information entry.
1715 DIE *Die = new DIE(DW_TAG_compile_unit);
1716 if (TAI->isAbsoluteDebugSectionOffsets())
1717 AddLabel(Die, DW_AT_stmt_list, DW_FORM_data4, DWLabel("section_line", 0));
1719 AddDelta(Die, DW_AT_stmt_list, DW_FORM_data4, DWLabel("section_line", 0),
1720 DWLabel("section_line", 0));
1721 AddString(Die, DW_AT_producer, DW_FORM_string, UnitDesc->getProducer());
1722 AddUInt (Die, DW_AT_language, DW_FORM_data1, UnitDesc->getLanguage());
1723 AddString(Die, DW_AT_name, DW_FORM_string, UnitDesc->getFileName());
1724 AddString(Die, DW_AT_comp_dir, DW_FORM_string, UnitDesc->getDirectory());
1726 // Construct compile unit.
1727 CompileUnit *Unit = new CompileUnit(UnitDesc, ID, Die);
1729 // Add Unit to compile unit map.
1730 DescToUnitMap[UnitDesc] = Unit;
1735 /// GetBaseCompileUnit - Get the main compile unit.
1737 CompileUnit *GetBaseCompileUnit() const {
1738 CompileUnit *Unit = CompileUnits[0];
1739 assert(Unit && "Missing compile unit.");
1743 /// FindCompileUnit - Get the compile unit for the given descriptor.
1745 CompileUnit *FindCompileUnit(CompileUnitDesc *UnitDesc) {
1746 CompileUnit *Unit = DescToUnitMap[UnitDesc];
1747 assert(Unit && "Missing compile unit.");
1751 /// NewGlobalVariable - Add a new global variable DIE.
1753 DIE *NewGlobalVariable(GlobalVariableDesc *GVD) {
1754 // Get the compile unit context.
1755 CompileUnitDesc *UnitDesc =
1756 static_cast<CompileUnitDesc *>(GVD->getContext());
1757 CompileUnit *Unit = GetBaseCompileUnit();
1759 // Check for pre-existence.
1760 DIE *&Slot = Unit->getDieMapSlotFor(GVD);
1761 if (Slot) return Slot;
1763 // Get the global variable itself.
1764 GlobalVariable *GV = GVD->getGlobalVariable();
1766 const std::string &Name = GVD->getName();
1767 const std::string &FullName = GVD->getFullName();
1768 const std::string &LinkageName = GVD->getLinkageName();
1769 // Create the global's variable DIE.
1770 DIE *VariableDie = new DIE(DW_TAG_variable);
1771 AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
1772 if (!LinkageName.empty()) {
1773 AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1776 AddType(VariableDie, GVD->getType(), Unit);
1777 if (!GVD->isStatic())
1778 AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
1780 // Add source line info if available.
1781 AddSourceLine(VariableDie, UnitDesc, GVD->getLine());
1784 DIEBlock *Block = new DIEBlock();
1785 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
1786 AddObjectLabel(Block, 0, DW_FORM_udata, Asm->getGlobalLinkName(GV));
1787 AddBlock(VariableDie, DW_AT_location, 0, Block);
1792 // Add to context owner.
1793 Unit->getDie()->AddChild(VariableDie);
1795 // Expose as global.
1796 // FIXME - need to check external flag.
1797 Unit->AddGlobal(FullName, VariableDie);
1802 /// NewSubprogram - Add a new subprogram DIE.
1804 DIE *NewSubprogram(SubprogramDesc *SPD) {
1805 // Get the compile unit context.
1806 CompileUnitDesc *UnitDesc =
1807 static_cast<CompileUnitDesc *>(SPD->getContext());
1808 CompileUnit *Unit = GetBaseCompileUnit();
1810 // Check for pre-existence.
1811 DIE *&Slot = Unit->getDieMapSlotFor(SPD);
1812 if (Slot) return Slot;
1814 // Gather the details (simplify add attribute code.)
1815 const std::string &Name = SPD->getName();
1816 const std::string &FullName = SPD->getFullName();
1817 const std::string &LinkageName = SPD->getLinkageName();
1819 DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
1820 AddString(SubprogramDie, DW_AT_name, DW_FORM_string, Name);
1821 if (!LinkageName.empty()) {
1822 AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1825 if (SPD->getType()) AddType(SubprogramDie, SPD->getType(), Unit);
1826 if (!SPD->isStatic())
1827 AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
1828 AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
1830 // Add source line info if available.
1831 AddSourceLine(SubprogramDie, UnitDesc, SPD->getLine());
1834 Slot = SubprogramDie;
1836 // Add to context owner.
1837 Unit->getDie()->AddChild(SubprogramDie);
1839 // Expose as global.
1840 Unit->AddGlobal(FullName, SubprogramDie);
1842 return SubprogramDie;
1845 /// NewScopeVariable - Create a new scope variable.
1847 DIE *NewScopeVariable(DebugVariable *DV, CompileUnit *Unit) {
1848 // Get the descriptor.
1849 VariableDesc *VD = DV->getDesc();
1851 // Translate tag to proper Dwarf tag. The result variable is dropped for
1854 switch (VD->getTag()) {
1855 case DW_TAG_return_variable: return NULL;
1856 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
1857 case DW_TAG_auto_variable: // fall thru
1858 default: Tag = DW_TAG_variable; break;
1861 // Define variable debug information entry.
1862 DIE *VariableDie = new DIE(Tag);
1863 AddString(VariableDie, DW_AT_name, DW_FORM_string, VD->getName());
1865 // Add source line info if available.
1866 AddSourceLine(VariableDie, VD->getFile(), VD->getLine());
1868 // Add variable type.
1869 AddType(VariableDie, VD->getType(), Unit);
1871 // Add variable address.
1872 MachineLocation Location;
1873 RI->getLocation(*MF, DV->getFrameIndex(), Location);
1874 AddAddress(VariableDie, DW_AT_location, Location);
1879 /// ConstructScope - Construct the components of a scope.
1881 void ConstructScope(DebugScope *ParentScope,
1882 unsigned ParentStartID, unsigned ParentEndID,
1883 DIE *ParentDie, CompileUnit *Unit) {
1884 // Add variables to scope.
1885 std::vector<DebugVariable *> &Variables = ParentScope->getVariables();
1886 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1887 DIE *VariableDie = NewScopeVariable(Variables[i], Unit);
1888 if (VariableDie) ParentDie->AddChild(VariableDie);
1891 // Add nested scopes.
1892 std::vector<DebugScope *> &Scopes = ParentScope->getScopes();
1893 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1894 // Define the Scope debug information entry.
1895 DebugScope *Scope = Scopes[j];
1896 // FIXME - Ignore inlined functions for the time being.
1897 if (!Scope->getParent()) continue;
1899 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1900 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1902 // Ignore empty scopes.
1903 if (StartID == EndID && StartID != 0) continue;
1904 if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
1906 if (StartID == ParentStartID && EndID == ParentEndID) {
1907 // Just add stuff to the parent scope.
1908 ConstructScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
1910 DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
1912 // Add the scope bounds.
1914 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1915 DWLabel("label", StartID));
1917 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1918 DWLabel("func_begin", SubprogramCount));
1921 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
1922 DWLabel("label", EndID));
1924 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
1925 DWLabel("func_end", SubprogramCount));
1928 // Add the scope contents.
1929 ConstructScope(Scope, StartID, EndID, ScopeDie, Unit);
1930 ParentDie->AddChild(ScopeDie);
1935 /// ConstructRootScope - Construct the scope for the subprogram.
1937 void ConstructRootScope(DebugScope *RootScope) {
1938 // Exit if there is no root scope.
1939 if (!RootScope) return;
1941 // Get the subprogram debug information entry.
1942 SubprogramDesc *SPD = cast<SubprogramDesc>(RootScope->getDesc());
1944 // Get the compile unit context.
1945 CompileUnit *Unit = GetBaseCompileUnit();
1947 // Get the subprogram die.
1948 DIE *SPDie = Unit->getDieMapSlotFor(SPD);
1949 assert(SPDie && "Missing subprogram descriptor");
1951 // Add the function bounds.
1952 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
1953 DWLabel("func_begin", SubprogramCount));
1954 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
1955 DWLabel("func_end", SubprogramCount));
1956 MachineLocation Location(RI->getFrameRegister(*MF));
1957 AddAddress(SPDie, DW_AT_frame_base, Location);
1959 ConstructScope(RootScope, 0, 0, SPDie, Unit);
1962 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
1963 /// tools to recognize the object file contains Dwarf information.
1964 void EmitInitial() {
1965 // Check to see if we already emitted intial headers.
1966 if (didInitial) return;
1969 // Dwarf sections base addresses.
1970 if (TAI->doesDwarfRequireFrameSection()) {
1971 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1972 EmitLabel("section_debug_frame", 0);
1974 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
1975 EmitLabel("section_info", 0);
1976 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
1977 EmitLabel("section_abbrev", 0);
1978 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
1979 EmitLabel("section_aranges", 0);
1980 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
1981 EmitLabel("section_macinfo", 0);
1982 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
1983 EmitLabel("section_line", 0);
1984 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
1985 EmitLabel("section_loc", 0);
1986 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
1987 EmitLabel("section_pubnames", 0);
1988 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
1989 EmitLabel("section_str", 0);
1990 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
1991 EmitLabel("section_ranges", 0);
1993 Asm->SwitchToTextSection(TAI->getTextSection());
1994 EmitLabel("text_begin", 0);
1995 Asm->SwitchToDataSection(TAI->getDataSection());
1996 EmitLabel("data_begin", 0);
1999 /// EmitDIE - Recusively Emits a debug information entry.
2001 void EmitDIE(DIE *Die) {
2002 // Get the abbreviation for this DIE.
2003 unsigned AbbrevNumber = Die->getAbbrevNumber();
2004 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2008 // Emit the code (index) for the abbreviation.
2009 Asm->EmitULEB128Bytes(AbbrevNumber);
2010 Asm->EOL(std::string("Abbrev [" +
2011 utostr(AbbrevNumber) +
2012 "] 0x" + utohexstr(Die->getOffset()) +
2013 ":0x" + utohexstr(Die->getSize()) + " " +
2014 TagString(Abbrev->getTag())));
2016 std::vector<DIEValue *> &Values = Die->getValues();
2017 const std::vector<DIEAbbrevData> &AbbrevData = Abbrev->getData();
2019 // Emit the DIE attribute values.
2020 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2021 unsigned Attr = AbbrevData[i].getAttribute();
2022 unsigned Form = AbbrevData[i].getForm();
2023 assert(Form && "Too many attributes for DIE (check abbreviation)");
2026 case DW_AT_sibling: {
2027 Asm->EmitInt32(Die->SiblingOffset());
2031 // Emit an attribute using the defined form.
2032 Values[i]->EmitValue(*this, Form);
2037 Asm->EOL(AttributeString(Attr));
2040 // Emit the DIE children if any.
2041 if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2042 const std::vector<DIE *> &Children = Die->getChildren();
2044 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2045 EmitDIE(Children[j]);
2048 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2052 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2054 unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2055 // Get the children.
2056 const std::vector<DIE *> &Children = Die->getChildren();
2058 // If not last sibling and has children then add sibling offset attribute.
2059 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2061 // Record the abbreviation.
2062 AssignAbbrevNumber(Die->getAbbrev());
2064 // Get the abbreviation for this DIE.
2065 unsigned AbbrevNumber = Die->getAbbrevNumber();
2066 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2069 Die->setOffset(Offset);
2071 // Start the size with the size of abbreviation code.
2072 Offset += Asm->SizeULEB128(AbbrevNumber);
2074 const std::vector<DIEValue *> &Values = Die->getValues();
2075 const std::vector<DIEAbbrevData> &AbbrevData = Abbrev->getData();
2077 // Size the DIE attribute values.
2078 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2079 // Size attribute value.
2080 Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2083 // Size the DIE children if any.
2084 if (!Children.empty()) {
2085 assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2086 "Children flag not set");
2088 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2089 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2092 // End of children marker.
2093 Offset += sizeof(int8_t);
2096 Die->setSize(Offset - Die->getOffset());
2100 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2102 void SizeAndOffsets() {
2103 // Process base compile unit.
2104 CompileUnit *Unit = GetBaseCompileUnit();
2105 // Compute size of compile unit header
2106 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2107 sizeof(int16_t) + // DWARF version number
2108 sizeof(int32_t) + // Offset Into Abbrev. Section
2109 sizeof(int8_t); // Pointer Size (in bytes)
2110 SizeAndOffsetDie(Unit->getDie(), Offset, true);
2113 /// EmitDebugInfo - Emit the debug info section.
2115 void EmitDebugInfo() {
2116 // Start debug info section.
2117 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2119 CompileUnit *Unit = GetBaseCompileUnit();
2120 DIE *Die = Unit->getDie();
2121 // Emit the compile units header.
2122 EmitLabel("info_begin", Unit->getID());
2123 // Emit size of content not including length itself
2124 unsigned ContentSize = Die->getSize() +
2125 sizeof(int16_t) + // DWARF version number
2126 sizeof(int32_t) + // Offset Into Abbrev. Section
2127 sizeof(int8_t) + // Pointer Size (in bytes)
2128 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2130 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2131 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2132 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2133 Asm->EOL("Offset Into Abbrev. Section");
2134 Asm->EmitInt8(TAI->getAddressSize()); Asm->EOL("Address Size (in bytes)");
2137 // FIXME - extra padding for gdb bug.
2138 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
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 EmitLabel("info_end", Unit->getID());
2147 /// EmitAbbreviations - Emit the abbreviation section.
2149 void EmitAbbreviations() const {
2150 // Check to see if it is worth the effort.
2151 if (!Abbreviations.empty()) {
2152 // Start the debug abbrev section.
2153 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2155 EmitLabel("abbrev_begin", 0);
2157 // For each abbrevation.
2158 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2159 // Get abbreviation data
2160 const DIEAbbrev *Abbrev = Abbreviations[i];
2162 // Emit the abbrevations code (base 1 index.)
2163 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2164 Asm->EOL("Abbreviation Code");
2166 // Emit the abbreviations data.
2167 Abbrev->Emit(*this);
2172 // Mark end of abbreviations.
2173 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2175 EmitLabel("abbrev_end", 0);
2181 /// EmitDebugLines - Emit source line information.
2183 void EmitDebugLines() {
2184 // Minimum line delta, thus ranging from -10..(255-10).
2185 const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2186 // Maximum line delta, thus ranging from -10..(255-10).
2187 const int MaxLineDelta = 255 + MinLineDelta;
2189 // Start the dwarf line section.
2190 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2192 // Construct the section header.
2194 EmitDifference("line_end", 0, "line_begin", 0, true);
2195 Asm->EOL("Length of Source Line Info");
2196 EmitLabel("line_begin", 0);
2198 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2200 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2201 Asm->EOL("Prolog Length");
2202 EmitLabel("line_prolog_begin", 0);
2204 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2206 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2208 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2210 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2212 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2214 // Line number standard opcode encodings argument count
2215 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2216 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2217 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2218 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2219 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2220 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2221 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2222 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2223 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2225 const UniqueVector<std::string> &Directories = MMI->getDirectories();
2226 const UniqueVector<SourceFileInfo>
2227 &SourceFiles = MMI->getSourceFiles();
2229 // Emit directories.
2230 for (unsigned DirectoryID = 1, NDID = Directories.size();
2231 DirectoryID <= NDID; ++DirectoryID) {
2232 Asm->EmitString(Directories[DirectoryID]); Asm->EOL("Directory");
2234 Asm->EmitInt8(0); Asm->EOL("End of directories");
2237 for (unsigned SourceID = 1, NSID = SourceFiles.size();
2238 SourceID <= NSID; ++SourceID) {
2239 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2240 Asm->EmitString(SourceFile.getName());
2242 Asm->EmitULEB128Bytes(SourceFile.getDirectoryID());
2243 Asm->EOL("Directory #");
2244 Asm->EmitULEB128Bytes(0);
2245 Asm->EOL("Mod date");
2246 Asm->EmitULEB128Bytes(0);
2247 Asm->EOL("File size");
2249 Asm->EmitInt8(0); Asm->EOL("End of files");
2251 EmitLabel("line_prolog_end", 0);
2253 // A sequence for each text section.
2254 for (unsigned j = 0, M = SectionSourceLines.size(); j < M; ++j) {
2255 // Isolate current sections line info.
2256 const std::vector<SourceLineInfo> &LineInfos = SectionSourceLines[j];
2258 Asm->EOL(std::string("Section ") + SectionMap[j + 1]);
2260 // Dwarf assumes we start with first line of first source file.
2261 unsigned Source = 1;
2264 // Construct rows of the address, source, line, column matrix.
2265 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2266 const SourceLineInfo &LineInfo = LineInfos[i];
2267 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2268 if (!LabelID) continue;
2270 unsigned SourceID = LineInfo.getSourceID();
2271 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2272 unsigned DirectoryID = SourceFile.getDirectoryID();
2273 Asm->EOL(Directories[DirectoryID]
2274 + SourceFile.getName()
2276 + utostr_32(LineInfo.getLine()));
2278 // Define the line address.
2279 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2280 Asm->EmitInt8(TAI->getAddressSize() + 1); Asm->EOL("Op size");
2281 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2282 EmitReference("label", LabelID); Asm->EOL("Location label");
2284 // If change of source, then switch to the new source.
2285 if (Source != LineInfo.getSourceID()) {
2286 Source = LineInfo.getSourceID();
2287 Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2288 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2291 // If change of line.
2292 if (Line != LineInfo.getLine()) {
2293 // Determine offset.
2294 int Offset = LineInfo.getLine() - Line;
2295 int Delta = Offset - MinLineDelta;
2298 Line = LineInfo.getLine();
2300 // If delta is small enough and in range...
2301 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2302 // ... then use fast opcode.
2303 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2305 // ... otherwise use long hand.
2306 Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
2307 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2308 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2311 // Copy the previous row (different address or source)
2312 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2316 // Define last address of section.
2317 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2318 Asm->EmitInt8(TAI->getAddressSize() + 1); Asm->EOL("Op size");
2319 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2320 EmitReference("section_end", j + 1); Asm->EOL("Section end label");
2322 // Mark end of matrix.
2323 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2324 Asm->EmitULEB128Bytes(1); Asm->EOL();
2325 Asm->EmitInt8(1); Asm->EOL();
2328 EmitLabel("line_end", 0);
2333 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2335 void EmitCommonDebugFrame() {
2336 if (!TAI->doesDwarfRequireFrameSection())
2340 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2341 TargetFrameInfo::StackGrowsUp ?
2342 TAI->getAddressSize() : -TAI->getAddressSize();
2344 // Start the dwarf frame section.
2345 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2347 EmitLabel("debug_frame_common", 0);
2348 EmitDifference("debug_frame_common_end", 0,
2349 "debug_frame_common_begin", 0, true);
2350 Asm->EOL("Length of Common Information Entry");
2352 EmitLabel("debug_frame_common_begin", 0);
2353 Asm->EmitInt32((int)DW_CIE_ID);
2354 Asm->EOL("CIE Identifier Tag");
2355 Asm->EmitInt8(DW_CIE_VERSION);
2356 Asm->EOL("CIE Version");
2357 Asm->EmitString("");
2358 Asm->EOL("CIE Augmentation");
2359 Asm->EmitULEB128Bytes(1);
2360 Asm->EOL("CIE Code Alignment Factor");
2361 Asm->EmitSLEB128Bytes(stackGrowth);
2362 Asm->EOL("CIE Data Alignment Factor");
2363 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister()));
2364 Asm->EOL("CIE RA Column");
2366 std::vector<MachineMove> Moves;
2367 RI->getInitialFrameState(Moves);
2369 EmitFrameMoves(NULL, 0, Moves);
2371 Asm->EmitAlignment(2);
2372 EmitLabel("debug_frame_common_end", 0);
2377 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2379 void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2380 if (!TAI->doesDwarfRequireFrameSection())
2383 // Start the dwarf frame section.
2384 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2386 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2387 "debug_frame_begin", DebugFrameInfo.Number, true);
2388 Asm->EOL("Length of Frame Information Entry");
2390 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2392 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2394 Asm->EOL("FDE CIE offset");
2396 EmitReference("func_begin", DebugFrameInfo.Number);
2397 Asm->EOL("FDE initial location");
2398 EmitDifference("func_end", DebugFrameInfo.Number,
2399 "func_begin", DebugFrameInfo.Number);
2400 Asm->EOL("FDE address range");
2402 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves);
2404 Asm->EmitAlignment(2);
2405 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2410 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2412 void EmitDebugPubNames() {
2413 // Start the dwarf pubnames section.
2414 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2416 CompileUnit *Unit = GetBaseCompileUnit();
2418 EmitDifference("pubnames_end", Unit->getID(),
2419 "pubnames_begin", Unit->getID(), true);
2420 Asm->EOL("Length of Public Names Info");
2422 EmitLabel("pubnames_begin", Unit->getID());
2424 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
2426 EmitSectionOffset("info_begin", "section_info",
2427 Unit->getID(), 0, true, false);
2428 Asm->EOL("Offset of Compilation Unit Info");
2430 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),true);
2431 Asm->EOL("Compilation Unit Length");
2433 std::map<std::string, DIE *> &Globals = Unit->getGlobals();
2435 for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
2438 const std::string &Name = GI->first;
2439 DIE * Entity = GI->second;
2441 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2442 Asm->EmitString(Name); Asm->EOL("External Name");
2445 Asm->EmitInt32(0); Asm->EOL("End Mark");
2446 EmitLabel("pubnames_end", Unit->getID());
2451 /// EmitDebugStr - Emit visible names into a debug str section.
2453 void EmitDebugStr() {
2454 // Check to see if it is worth the effort.
2455 if (!StringPool.empty()) {
2456 // Start the dwarf str section.
2457 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2459 // For each of strings in the string pool.
2460 for (unsigned StringID = 1, N = StringPool.size();
2461 StringID <= N; ++StringID) {
2462 // Emit a label for reference from debug information entries.
2463 EmitLabel("string", StringID);
2464 // Emit the string itself.
2465 const std::string &String = StringPool[StringID];
2466 Asm->EmitString(String); Asm->EOL();
2473 /// EmitDebugLoc - Emit visible names into a debug loc section.
2475 void EmitDebugLoc() {
2476 // Start the dwarf loc section.
2477 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2482 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2484 void EmitDebugARanges() {
2485 // Start the dwarf aranges section.
2486 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2490 CompileUnit *Unit = GetBaseCompileUnit();
2492 // Don't include size of length
2493 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2495 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2497 EmitReference("info_begin", Unit->getID());
2498 Asm->EOL("Offset of Compilation Unit Info");
2500 Asm->EmitInt8(TAI->getAddressSize()); Asm->EOL("Size of Address");
2502 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2504 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2505 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2508 EmitReference("text_begin", 0); Asm->EOL("Address");
2509 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2511 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2512 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2518 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2520 void EmitDebugRanges() {
2521 // Start the dwarf ranges section.
2522 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2527 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2529 void EmitDebugMacInfo() {
2530 // Start the dwarf macinfo section.
2531 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2536 /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
2538 void ConstructCompileUnitDIEs() {
2539 const UniqueVector<CompileUnitDesc *> CUW = MMI->getCompileUnits();
2541 for (unsigned i = 1, N = CUW.size(); i <= N; ++i) {
2542 unsigned ID = MMI->RecordSource(CUW[i]);
2543 CompileUnit *Unit = NewCompileUnit(CUW[i], ID);
2544 CompileUnits.push_back(Unit);
2548 /// ConstructGlobalDIEs - Create DIEs for each of the externally visible
2549 /// global variables.
2550 void ConstructGlobalDIEs() {
2551 std::vector<GlobalVariableDesc *> GlobalVariables =
2552 MMI->getAnchoredDescriptors<GlobalVariableDesc>(*M);
2554 for (unsigned i = 0, N = GlobalVariables.size(); i < N; ++i) {
2555 GlobalVariableDesc *GVD = GlobalVariables[i];
2556 NewGlobalVariable(GVD);
2560 /// ConstructSubprogramDIEs - Create DIEs for each of the externally visible
2562 void ConstructSubprogramDIEs() {
2563 std::vector<SubprogramDesc *> Subprograms =
2564 MMI->getAnchoredDescriptors<SubprogramDesc>(*M);
2566 for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
2567 SubprogramDesc *SPD = Subprograms[i];
2573 //===--------------------------------------------------------------------===//
2574 // Main entry points.
2576 DwarfDebug(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
2579 , AbbreviationsSet(InitAbbreviationsSetSize)
2581 , ValuesSet(InitValuesSetSize)
2586 , SectionSourceLines()
2591 virtual ~DwarfDebug() {
2592 for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i)
2593 delete CompileUnits[i];
2594 for (unsigned j = 0, M = Values.size(); j < M; ++j)
2598 /// SetModuleInfo - Set machine module information when it's known that pass
2599 /// manager has created it. Set by the target AsmPrinter.
2600 void SetModuleInfo(MachineModuleInfo *mmi) {
2601 // Make sure initial declarations are made.
2602 if (!MMI && mmi->hasDebugInfo()) {
2606 // Emit initial sections
2609 // Create all the compile unit DIEs.
2610 ConstructCompileUnitDIEs();
2612 // Create DIEs for each of the externally visible global variables.
2613 ConstructGlobalDIEs();
2615 // Create DIEs for each of the externally visible subprograms.
2616 ConstructSubprogramDIEs();
2618 // Prime section data.
2619 SectionMap.insert(TAI->getTextSection());
2623 /// BeginModule - Emit all Dwarf sections that should come prior to the
2625 void BeginModule(Module *M) {
2628 if (!ShouldEmitDwarf()) return;
2631 /// EndModule - Emit all Dwarf sections that should come after the content.
2634 if (!ShouldEmitDwarf()) return;
2636 // Standard sections final addresses.
2637 Asm->SwitchToTextSection(TAI->getTextSection());
2638 EmitLabel("text_end", 0);
2639 Asm->SwitchToDataSection(TAI->getDataSection());
2640 EmitLabel("data_end", 0);
2642 // End text sections.
2643 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2644 Asm->SwitchToTextSection(SectionMap[i].c_str());
2645 EmitLabel("section_end", i);
2648 // Emit common frame information.
2649 EmitCommonDebugFrame();
2651 // Emit function debug frame information
2652 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
2653 E = DebugFrames.end(); I != E; ++I)
2654 EmitFunctionDebugFrame(*I);
2656 // Compute DIE offsets and sizes.
2659 // Emit all the DIEs into a debug info section
2662 // Corresponding abbreviations into a abbrev section.
2663 EmitAbbreviations();
2665 // Emit source line correspondence into a debug line section.
2668 // Emit info into a debug pubnames section.
2669 EmitDebugPubNames();
2671 // Emit info into a debug str section.
2674 // Emit info into a debug loc section.
2677 // Emit info into a debug aranges section.
2680 // Emit info into a debug ranges section.
2683 // Emit info into a debug macinfo section.
2687 /// BeginFunction - Gather pre-function debug information. Assumes being
2688 /// emitted immediately after the function entry point.
2689 void BeginFunction(MachineFunction *MF) {
2692 if (!ShouldEmitDwarf()) return;
2694 // Begin accumulating function debug information.
2695 MMI->BeginFunction(MF);
2697 // Assumes in correct section after the entry point.
2698 EmitLabel("func_begin", ++SubprogramCount);
2701 /// EndFunction - Gather and emit post-function debug information.
2703 void EndFunction() {
2704 if (!ShouldEmitDwarf()) return;
2706 // Define end label for subprogram.
2707 EmitLabel("func_end", SubprogramCount);
2709 // Get function line info.
2710 const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
2712 if (!LineInfos.empty()) {
2713 // Get section line info.
2714 unsigned ID = SectionMap.insert(Asm->CurrentSection);
2715 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2716 std::vector<SourceLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2717 // Append the function info to section info.
2718 SectionLineInfos.insert(SectionLineInfos.end(),
2719 LineInfos.begin(), LineInfos.end());
2722 // Construct scopes for subprogram.
2723 ConstructRootScope(MMI->getRootScope());
2725 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
2726 MMI->getFrameMoves()));
2730 //===----------------------------------------------------------------------===//
2731 /// DwarfException - Emits Dwarf exception handling directives.
2733 class DwarfException : public Dwarf {
2736 struct FunctionEHFrameInfo {
2739 unsigned PersonalityIndex;
2741 bool hasLandingPads;
2742 std::vector<MachineMove> Moves;
2744 FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
2746 const std::vector<MachineMove> &M):
2747 FnName(FN), Number(Num), PersonalityIndex(P),
2748 hasCalls(hC), hasLandingPads(hL), Moves(M) { };
2751 std::vector<FunctionEHFrameInfo> EHFrames;
2753 /// shouldEmit - Flag to indicate if debug information should be emitted.
2757 /// EmitCommonEHFrame - Emit the common eh unwind frame.
2759 void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
2760 // Size and sign of stack growth.
2762 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2763 TargetFrameInfo::StackGrowsUp ?
2764 TAI->getAddressSize() : -TAI->getAddressSize();
2766 // Begin eh frame section.
2767 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
2768 O << "EH_frame" << Index << ":\n";
2769 EmitLabel("section_eh_frame", Index);
2771 // Define base labels.
2772 EmitLabel("eh_frame_common", Index);
2774 // Define the eh frame length.
2775 EmitDifference("eh_frame_common_end", Index,
2776 "eh_frame_common_begin", Index, true);
2777 Asm->EOL("Length of Common Information Entry");
2780 EmitLabel("eh_frame_common_begin", Index);
2781 Asm->EmitInt32((int)0);
2782 Asm->EOL("CIE Identifier Tag");
2783 Asm->EmitInt8(DW_CIE_VERSION);
2784 Asm->EOL("CIE Version");
2786 // The personality presence indicates that language specific information
2787 // will show up in the eh frame.
2788 Asm->EmitString(Personality ? "zPLR" : "zR");
2789 Asm->EOL("CIE Augmentation");
2791 // Round out reader.
2792 Asm->EmitULEB128Bytes(1);
2793 Asm->EOL("CIE Code Alignment Factor");
2794 Asm->EmitSLEB128Bytes(stackGrowth);
2795 Asm->EOL("CIE Data Alignment Factor");
2796 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister()));
2797 Asm->EOL("CIE RA Column");
2799 // If there is a personality, we need to indicate the functions location.
2801 Asm->EmitULEB128Bytes(7);
2802 Asm->EOL("Augmentation Size");
2803 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
2804 Asm->EOL("Personality (pcrel sdata4)");
2806 O << TAI->getData32bitsDirective();
2807 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
2808 O << "-" << TAI->getPCSymbol();
2809 Asm->EOL("Personality");
2811 Asm->EmitULEB128Bytes(DW_EH_PE_pcrel);
2812 Asm->EOL("LSDA Encoding (pcrel)");
2813 Asm->EmitULEB128Bytes(DW_EH_PE_pcrel);
2814 Asm->EOL("FDE Encoding (pcrel)");
2816 Asm->EmitULEB128Bytes(1);
2817 Asm->EOL("Augmentation Size");
2818 Asm->EmitULEB128Bytes(DW_EH_PE_pcrel);
2819 Asm->EOL("FDE Encoding (pcrel)");
2822 // Indicate locations of general callee saved registers in frame.
2823 std::vector<MachineMove> Moves;
2824 RI->getInitialFrameState(Moves);
2825 EmitFrameMoves(NULL, 0, Moves);
2827 Asm->EmitAlignment(2);
2828 EmitLabel("eh_frame_common_end", Index);
2833 /// EmitEHFrame - Emit function exception frame information.
2835 void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
2836 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
2838 // Externally visible entry into the functions eh frame info.
2839 if (const char *GlobalDirective = TAI->getGlobalDirective())
2840 O << GlobalDirective << EHFrameInfo.FnName << ".eh\n";
2842 // If there are no calls then you can't unwind.
2843 if (!EHFrameInfo.hasCalls) {
2844 O << EHFrameInfo.FnName << ".eh = 0\n";
2846 O << EHFrameInfo.FnName << ".eh:\n";
2849 EmitDifference("eh_frame_end", EHFrameInfo.Number,
2850 "eh_frame_begin", EHFrameInfo.Number, true);
2851 Asm->EOL("Length of Frame Information Entry");
2853 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
2855 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
2856 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
2858 Asm->EOL("FDE CIE offset");
2860 EmitReference("eh_func_begin", EHFrameInfo.Number, true);
2861 Asm->EOL("FDE initial location");
2862 EmitDifference("eh_func_end", EHFrameInfo.Number,
2863 "eh_func_begin", EHFrameInfo.Number);
2864 Asm->EOL("FDE address range");
2866 // If there is a personality and landing pads then point to the language
2867 // specific data area in the exception table.
2868 if (EHFrameInfo.PersonalityIndex) {
2869 Asm->EmitULEB128Bytes(4);
2870 Asm->EOL("Augmentation size");
2872 if (EHFrameInfo.hasLandingPads) {
2873 EmitReference("exception", EHFrameInfo.Number, true);
2874 } else if(TAI->getAddressSize() == 8) {
2875 Asm->EmitInt64((int)0);
2877 Asm->EmitInt32((int)0);
2879 Asm->EOL("Language Specific Data Area");
2881 Asm->EmitULEB128Bytes(0);
2882 Asm->EOL("Augmentation size");
2885 // Indicate locations of function specific callee saved registers in
2887 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves);
2889 Asm->EmitAlignment(2);
2890 EmitLabel("eh_frame_end", EHFrameInfo.Number);
2893 if (const char *UsedDirective = TAI->getUsedDirective())
2894 O << UsedDirective << EHFrameInfo.FnName << ".eh\n\n";
2897 /// EmitExceptionTable - Emit landpads and actions.
2899 /// The general organization of the table is complex, but the basic concepts
2900 /// are easy. First there is a header which describes the location and
2901 /// organization of the three components that follow.
2902 /// 1. The landing pad site information describes the range of code covered
2903 /// by the try. In our case it's an accumulation of the ranges covered
2904 /// by the invokes in the try. There is also a reference to the landing
2905 /// pad that handles the exception once processed. Finally an index into
2906 /// the actions table.
2907 /// 2. The action table, in our case, is composed of pairs of type ids
2908 /// and next action offset. Starting with the action index from the
2909 /// landing pad site, each type Id is checked for a match to the current
2910 /// exception. If it matches then the exception and type id are passed
2911 /// on to the landing pad. Otherwise the next action is looked up. This
2912 /// chain is terminated with a next action of zero. If no type id is
2913 /// found the the frame is unwound and handling continues.
2914 /// 3. Type id table contains references to all the C++ typeinfo for all
2915 /// catches in the function. This tables is reversed indexed base 1.
2917 /// SharedTypeIds - How many leading type ids two landing pads have in common.
2918 static unsigned SharedTypeIds(const LandingPadInfo *L,
2919 const LandingPadInfo *R) {
2920 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
2921 unsigned LSize = LIds.size(), RSize = RIds.size();
2922 unsigned MinSize = LSize < RSize ? LSize : RSize;
2925 for (; Count != MinSize; ++Count)
2926 if (LIds[Count] != RIds[Count])
2932 /// PadLT - Order landing pads lexicographically by type id.
2933 static bool PadLT(const LandingPadInfo *L, 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;
2938 for (unsigned i = 0; i != MinSize; ++i)
2939 if (LIds[i] != RIds[i])
2940 return LIds[i] < RIds[i];
2942 return LSize < RSize;
2946 static inline unsigned getEmptyKey() { return -1U; }
2947 static inline unsigned getTombstoneKey() { return -2U; }
2948 static unsigned getHashValue(const unsigned &Key) { return Key; }
2949 static bool isPod() { return true; }
2957 typedef DenseMap<unsigned, PadSite, KeyInfo> PadMapType;
2959 struct ActionEntry {
2960 int ValueForTypeID; // The value to write - may not be equal to the type id.
2962 struct ActionEntry *Previous;
2965 void EmitExceptionTable() {
2966 // Map all labels and get rid of any dead landing pads.
2967 MMI->TidyLandingPads();
2969 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
2970 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
2971 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
2972 if (PadInfos.empty()) return;
2974 // Sort the landing pads in order of their type ids. This is used to fold
2975 // duplicate actions.
2976 SmallVector<const LandingPadInfo *, 64> LandingPads;
2977 LandingPads.reserve(PadInfos.size());
2978 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
2979 LandingPads.push_back(&PadInfos[i]);
2980 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
2982 // Gather first action index for each landing pad site.
2983 SmallVector<unsigned, 64> FirstActions;
2984 FirstActions.reserve(PadInfos.size());
2986 // The actions table.
2987 SmallVector<ActionEntry, 32> Actions;
2989 // Negative type ids index into FilterIds, positive type ids index into
2990 // TypeInfos. The value written for a positive type id is just the type
2991 // id itself. For a negative type id, however, the value written is the
2992 // (negative) byte offset of the corresponding FilterIds entry. The byte
2993 // offset is usually equal to the type id, because the FilterIds entries
2994 // are written using a variable width encoding which outputs one byte per
2995 // entry as long as the value written is not too large, but can differ.
2996 // This kind of complication does not occur for positive type ids because
2997 // type infos are output using a fixed width encoding.
2998 // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
2999 SmallVector<int, 16> FilterOffsets;
3000 FilterOffsets.reserve(FilterIds.size());
3002 for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
3003 E = FilterIds.end(); I != E; ++I) {
3004 FilterOffsets.push_back(Offset);
3005 Offset -= Asm->SizeULEB128(*I);
3008 // Compute sizes for exception table.
3009 unsigned SizeSites = 0;
3010 unsigned SizeActions = 0;
3012 // Look at each landing pad site to compute size. We need the size of each
3013 // landing pad site info and the size of the landing pad's actions.
3014 int FirstAction = 0;
3016 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3017 const LandingPadInfo *LP = LandingPads[i];
3018 const std::vector<int> &TypeIds = LP->TypeIds;
3019 const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
3020 unsigned SizeSiteActions = 0;
3022 if (NumShared < TypeIds.size()) {
3023 unsigned SizeAction = 0;
3024 ActionEntry *PrevAction = 0;
3027 const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
3028 assert(Actions.size());
3029 PrevAction = &Actions.back();
3030 SizeAction = Asm->SizeSLEB128(PrevAction->NextAction) +
3031 Asm->SizeSLEB128(PrevAction->ValueForTypeID);
3032 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
3033 SizeAction -= Asm->SizeSLEB128(PrevAction->ValueForTypeID);
3034 SizeAction += -PrevAction->NextAction;
3035 PrevAction = PrevAction->Previous;
3039 // Compute the actions.
3040 for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
3041 int TypeID = TypeIds[I];
3042 assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
3043 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
3044 unsigned SizeTypeID = Asm->SizeSLEB128(ValueForTypeID);
3046 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
3047 SizeAction = SizeTypeID + Asm->SizeSLEB128(NextAction);
3048 SizeSiteActions += SizeAction;
3050 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
3051 Actions.push_back(Action);
3053 PrevAction = &Actions.back();
3056 // Record the first action of the landing pad site.
3057 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
3058 } // else identical - re-use previous FirstAction
3060 FirstActions.push_back(FirstAction);
3062 // Compute this sites contribution to size.
3063 SizeActions += SizeSiteActions;
3064 unsigned M = LP->BeginLabels.size();
3065 SizeSites += M*(sizeof(int32_t) + // Site start.
3066 sizeof(int32_t) + // Site length.
3067 sizeof(int32_t) + // Landing pad.
3068 Asm->SizeULEB128(FirstAction)); // Action.
3072 unsigned SizeTypes = TypeInfos.size() * TAI->getAddressSize();
3074 unsigned TypeOffset = sizeof(int8_t) + // Call site format
3075 Asm->SizeULEB128(SizeSites) + // Call-site table length
3076 SizeSites + SizeActions + SizeTypes;
3078 unsigned TotalSize = sizeof(int8_t) + // LPStart format
3079 sizeof(int8_t) + // TType format
3080 Asm->SizeULEB128(TypeOffset) + // TType base offset
3083 unsigned SizeAlign = (4 - TotalSize) & 3;
3085 // Begin the exception table.
3086 Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
3087 O << "GCC_except_table" << SubprogramCount << ":\n";
3088 Asm->EmitAlignment(2);
3089 for (unsigned i = 0; i != SizeAlign; ++i) {
3091 Asm->EOL("Padding");
3093 EmitLabel("exception", SubprogramCount);
3096 Asm->EmitInt8(DW_EH_PE_omit);
3097 Asm->EOL("LPStart format (DW_EH_PE_omit)");
3098 Asm->EmitInt8(DW_EH_PE_absptr);
3099 Asm->EOL("TType format (DW_EH_PE_absptr)");
3100 Asm->EmitULEB128Bytes(TypeOffset);
3101 Asm->EOL("TType base offset");
3102 Asm->EmitInt8(DW_EH_PE_udata4);
3103 Asm->EOL("Call site format (DW_EH_PE_udata4)");
3104 Asm->EmitULEB128Bytes(SizeSites);
3105 Asm->EOL("Call-site table length");
3107 // Emit the landing pad site information in order of address.
3110 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3111 const LandingPadInfo *LandingPad = LandingPads[i];
3112 for (unsigned j=0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
3113 unsigned BeginLabel = LandingPad->BeginLabels[j];
3114 assert(!PadMap.count(BeginLabel) && "duplicate landing pad labels!");
3115 PadSite P = { i, j };
3116 PadMap[BeginLabel] = P;
3120 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
3122 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
3124 if (MI->getOpcode() != TargetInstrInfo::LABEL)
3127 unsigned BeginLabel = MI->getOperand(0).getImmedValue();
3128 PadMapType::iterator L = PadMap.find(BeginLabel);
3130 if (L == PadMap.end())
3133 PadSite P = L->second;
3134 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
3136 assert(BeginLabel == LandingPad->BeginLabels[P.SiteIndex] &&
3137 "Inconsistent landing pad map!");
3139 EmitSectionOffset("label", "eh_func_begin", BeginLabel, SubprogramCount,
3141 Asm->EOL("Region start");
3143 EmitDifference("label", LandingPad->EndLabels[P.SiteIndex],
3144 "label", BeginLabel);
3145 Asm->EOL("Region length");
3147 if (LandingPad->TypeIds.empty()) {
3148 if (TAI->getAddressSize() == sizeof(int32_t))
3153 EmitSectionOffset("label", "eh_func_begin",
3154 LandingPad->LandingPadLabel, SubprogramCount,
3157 Asm->EOL("Landing pad");
3159 Asm->EmitULEB128Bytes(FirstActions[P.PadIndex]);
3164 // Emit the actions.
3165 for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
3166 ActionEntry &Action = Actions[I];
3168 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
3169 Asm->EOL("TypeInfo index");
3170 Asm->EmitSLEB128Bytes(Action.NextAction);
3171 Asm->EOL("Next action");
3174 // Emit the type ids.
3175 for (unsigned M = TypeInfos.size(); M; --M) {
3176 GlobalVariable *GV = TypeInfos[M - 1];
3178 if (TAI->getAddressSize() == sizeof(int32_t))
3179 O << TAI->getData32bitsDirective();
3181 O << TAI->getData64bitsDirective();
3184 O << Asm->getGlobalLinkName(GV);
3188 Asm->EOL("TypeInfo");
3191 // Emit the filter typeids.
3192 for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
3193 unsigned TypeID = FilterIds[j];
3194 Asm->EmitULEB128Bytes(TypeID);
3195 Asm->EOL("Filter TypeInfo index");
3198 Asm->EmitAlignment(2);
3202 //===--------------------------------------------------------------------===//
3203 // Main entry points.
3205 DwarfException(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3210 virtual ~DwarfException() {}
3212 /// SetModuleInfo - Set machine module information when it's known that pass
3213 /// manager has created it. Set by the target AsmPrinter.
3214 void SetModuleInfo(MachineModuleInfo *mmi) {
3218 /// BeginModule - Emit all exception information that should come prior to the
3220 void BeginModule(Module *M) {
3224 /// EndModule - Emit all exception information that should come after the
3227 if (!shouldEmit) return;
3229 const std::vector<Function *> Personalities = MMI->getPersonalities();
3230 for (unsigned i =0; i < Personalities.size(); ++i)
3231 EmitCommonEHFrame(Personalities[i], i);
3233 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
3234 E = EHFrames.end(); I != E; ++I)
3238 /// BeginFunction - Gather pre-function exception information. Assumes being
3239 /// emitted immediately after the function entry point.
3240 void BeginFunction(MachineFunction *MF) {
3244 ExceptionHandling &&
3245 TAI->doesSupportExceptionHandling()) {
3247 // Assumes in correct section after the entry point.
3248 EmitLabel("eh_func_begin", ++SubprogramCount);
3252 /// EndFunction - Gather and emit post-function exception information.
3254 void EndFunction() {
3255 if (!shouldEmit) return;
3257 EmitLabel("eh_func_end", SubprogramCount);
3258 EmitExceptionTable();
3260 // Save EH frame information
3261 EHFrames.push_back(FunctionEHFrameInfo(getAsm()->CurrentFnName,
3263 MMI->getPersonalityIndex(),
3264 MF->getFrameInfo()->hasCalls(),
3265 !MMI->getLandingPads().empty(),
3266 MMI->getFrameMoves()));
3270 } // End of namespace llvm
3272 //===----------------------------------------------------------------------===//
3274 /// Emit - Print the abbreviation using the specified Dwarf writer.
3276 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
3277 // Emit its Dwarf tag type.
3278 DD.getAsm()->EmitULEB128Bytes(Tag);
3279 DD.getAsm()->EOL(TagString(Tag));
3281 // Emit whether it has children DIEs.
3282 DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
3283 DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
3285 // For each attribute description.
3286 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3287 const DIEAbbrevData &AttrData = Data[i];
3289 // Emit attribute type.
3290 DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
3291 DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
3294 DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
3295 DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
3298 // Mark end of abbreviation.
3299 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
3300 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
3304 void DIEAbbrev::print(std::ostream &O) {
3305 O << "Abbreviation @"
3306 << std::hex << (intptr_t)this << std::dec
3310 << ChildrenString(ChildrenFlag)
3313 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3315 << AttributeString(Data[i].getAttribute())
3317 << FormEncodingString(Data[i].getForm())
3321 void DIEAbbrev::dump() { print(cerr); }
3324 //===----------------------------------------------------------------------===//
3327 void DIEValue::dump() {
3332 //===----------------------------------------------------------------------===//
3334 /// EmitValue - Emit integer of appropriate size.
3336 void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
3338 case DW_FORM_flag: // Fall thru
3339 case DW_FORM_ref1: // Fall thru
3340 case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer); break;
3341 case DW_FORM_ref2: // Fall thru
3342 case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer); break;
3343 case DW_FORM_ref4: // Fall thru
3344 case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer); break;
3345 case DW_FORM_ref8: // Fall thru
3346 case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer); break;
3347 case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
3348 case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
3349 default: assert(0 && "DIE Value form not supported yet"); break;
3353 /// SizeOf - Determine size of integer value in bytes.
3355 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3357 case DW_FORM_flag: // Fall thru
3358 case DW_FORM_ref1: // Fall thru
3359 case DW_FORM_data1: return sizeof(int8_t);
3360 case DW_FORM_ref2: // Fall thru
3361 case DW_FORM_data2: return sizeof(int16_t);
3362 case DW_FORM_ref4: // Fall thru
3363 case DW_FORM_data4: return sizeof(int32_t);
3364 case DW_FORM_ref8: // Fall thru
3365 case DW_FORM_data8: return sizeof(int64_t);
3366 case DW_FORM_udata: return DD.getAsm()->SizeULEB128(Integer);
3367 case DW_FORM_sdata: return DD.getAsm()->SizeSLEB128(Integer);
3368 default: assert(0 && "DIE Value form not supported yet"); break;
3373 //===----------------------------------------------------------------------===//
3375 /// EmitValue - Emit string value.
3377 void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
3378 DD.getAsm()->EmitString(String);
3381 //===----------------------------------------------------------------------===//
3383 /// EmitValue - Emit label value.
3385 void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
3386 DD.EmitReference(Label);
3389 /// SizeOf - Determine size of label value in bytes.
3391 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3392 return DD.getTargetAsmInfo()->getAddressSize();
3395 //===----------------------------------------------------------------------===//
3397 /// EmitValue - Emit label value.
3399 void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
3400 DD.EmitReference(Label);
3403 /// SizeOf - Determine size of label value in bytes.
3405 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3406 return DD.getTargetAsmInfo()->getAddressSize();
3409 //===----------------------------------------------------------------------===//
3411 /// EmitValue - Emit delta value.
3413 void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
3414 bool IsSmall = Form == DW_FORM_data4;
3415 DD.EmitDifference(LabelHi, LabelLo, IsSmall);
3418 /// SizeOf - Determine size of delta value in bytes.
3420 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3421 if (Form == DW_FORM_data4) return 4;
3422 return DD.getTargetAsmInfo()->getAddressSize();
3425 //===----------------------------------------------------------------------===//
3427 /// EmitValue - Emit debug information entry offset.
3429 void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
3430 DD.getAsm()->EmitInt32(Entry->getOffset());
3433 //===----------------------------------------------------------------------===//
3435 /// ComputeSize - calculate the size of the block.
3437 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
3439 const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
3441 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3442 Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
3448 /// EmitValue - Emit block data.
3450 void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
3452 case DW_FORM_block1: DD.getAsm()->EmitInt8(Size); break;
3453 case DW_FORM_block2: DD.getAsm()->EmitInt16(Size); break;
3454 case DW_FORM_block4: DD.getAsm()->EmitInt32(Size); break;
3455 case DW_FORM_block: DD.getAsm()->EmitULEB128Bytes(Size); break;
3456 default: assert(0 && "Improper form for block"); break;
3459 const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
3461 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3463 Values[i]->EmitValue(DD, AbbrevData[i].getForm());
3467 /// SizeOf - Determine size of block data in bytes.
3469 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3471 case DW_FORM_block1: return Size + sizeof(int8_t);
3472 case DW_FORM_block2: return Size + sizeof(int16_t);
3473 case DW_FORM_block4: return Size + sizeof(int32_t);
3474 case DW_FORM_block: return Size + DD.getAsm()->SizeULEB128(Size);
3475 default: assert(0 && "Improper form for block"); break;
3480 //===----------------------------------------------------------------------===//
3481 /// DIE Implementation
3484 for (unsigned i = 0, N = Children.size(); i < N; ++i)
3488 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
3490 void DIE::AddSiblingOffset() {
3491 DIEInteger *DI = new DIEInteger(0);
3492 Values.insert(Values.begin(), DI);
3493 Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
3496 /// Profile - Used to gather unique data for the value folding set.
3498 void DIE::Profile(FoldingSetNodeID &ID) {
3501 for (unsigned i = 0, N = Children.size(); i < N; ++i)
3502 ID.AddPointer(Children[i]);
3504 for (unsigned j = 0, M = Values.size(); j < M; ++j)
3505 ID.AddPointer(Values[j]);
3509 void DIE::print(std::ostream &O, unsigned IncIndent) {
3510 static unsigned IndentCount = 0;
3511 IndentCount += IncIndent;
3512 const std::string Indent(IndentCount, ' ');
3513 bool isBlock = Abbrev.getTag() == 0;
3518 << "0x" << std::hex << (intptr_t)this << std::dec
3519 << ", Offset: " << Offset
3520 << ", Size: " << Size
3524 << TagString(Abbrev.getTag())
3526 << ChildrenString(Abbrev.getChildrenFlag());
3528 O << "Size: " << Size;
3532 const std::vector<DIEAbbrevData> &Data = Abbrev.getData();
3535 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3538 O << AttributeString(Data[i].getAttribute());
3540 O << "Blk[" << i << "]";
3543 << FormEncodingString(Data[i].getForm())
3545 Values[i]->print(O);
3550 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
3551 Children[j]->print(O, 4);
3554 if (!isBlock) O << "\n";
3555 IndentCount -= IncIndent;
3563 //===----------------------------------------------------------------------===//
3564 /// DwarfWriter Implementation
3567 DwarfWriter::DwarfWriter(std::ostream &OS, AsmPrinter *A,
3568 const TargetAsmInfo *T) {
3569 DE = new DwarfException(OS, A, T);
3570 DD = new DwarfDebug(OS, A, T);
3573 DwarfWriter::~DwarfWriter() {
3578 /// SetModuleInfo - Set machine module info when it's known that pass manager
3579 /// has created it. Set by the target AsmPrinter.
3580 void DwarfWriter::SetModuleInfo(MachineModuleInfo *MMI) {
3581 DD->SetModuleInfo(MMI);
3582 DE->SetModuleInfo(MMI);
3585 /// BeginModule - Emit all Dwarf sections that should come prior to the
3587 void DwarfWriter::BeginModule(Module *M) {
3592 /// EndModule - Emit all Dwarf sections that should come after the content.
3594 void DwarfWriter::EndModule() {
3599 /// BeginFunction - Gather pre-function debug information. Assumes being
3600 /// emitted immediately after the function entry point.
3601 void DwarfWriter::BeginFunction(MachineFunction *MF) {
3602 DE->BeginFunction(MF);
3603 DD->BeginFunction(MF);
3606 /// EndFunction - Gather and emit post-function debug information.
3608 void DwarfWriter::EndFunction() {
3612 if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI()) {
3613 // Clear function debug information.