1 //===-- llvm/CodeGen/DwarfWriter.cpp - Dwarf Framework ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf 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/DerivedTypes.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/Analysis/DebugInfo.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/Dwarf.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/DataTypes.h"
31 #include "llvm/Support/Mangler.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/System/Path.h"
34 #include "llvm/Target/TargetAsmInfo.h"
35 #include "llvm/Target/TargetRegisterInfo.h"
36 #include "llvm/Target/TargetData.h"
37 #include "llvm/Target/TargetFrameInfo.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Target/TargetOptions.h"
44 using namespace llvm::dwarf;
48 //===----------------------------------------------------------------------===//
50 /// Configuration values for initial hash set sizes (log2).
52 static const unsigned InitDiesSetSize = 9; // 512
53 static const unsigned InitAbbreviationsSetSize = 9; // 512
54 static const unsigned InitValuesSetSize = 9; // 512
56 //===----------------------------------------------------------------------===//
57 /// Forward declarations.
62 //===----------------------------------------------------------------------===//
65 /// getGlobalVariablesUsing - Return all of the GlobalVariables which have the
66 /// specified value in their initializer somewhere.
68 getGlobalVariablesUsing(Value *V, std::vector<GlobalVariable*> &Result) {
69 // Scan though value users.
70 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
71 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I)) {
72 // If the user is a GlobalVariable then add to result.
74 } else if (Constant *C = dyn_cast<Constant>(*I)) {
75 // If the user is a constant variable then scan its users
76 getGlobalVariablesUsing(C, Result);
81 /// getGlobalVariablesUsing - Return all of the GlobalVariables that use the
82 /// named GlobalVariable.
84 getGlobalVariablesUsing(Module &M, const std::string &RootName,
85 std::vector<GlobalVariable*> &Result) {
86 std::vector<const Type*> FieldTypes;
87 FieldTypes.push_back(Type::Int32Ty);
88 FieldTypes.push_back(Type::Int32Ty);
90 // Get the GlobalVariable root.
91 GlobalVariable *UseRoot = M.getGlobalVariable(RootName,
92 StructType::get(FieldTypes));
94 // If present and linkonce then scan for users.
95 if (UseRoot && UseRoot->hasLinkOnceLinkage())
96 getGlobalVariablesUsing(UseRoot, Result);
99 //===----------------------------------------------------------------------===//
100 /// DWLabel - Labels are used to track locations in the assembler file.
101 /// Labels appear in the form @verbatim <prefix><Tag><Number> @endverbatim,
102 /// where the tag is a category of label (Ex. location) and number is a value
103 /// unique in that category.
106 /// Tag - Label category tag. Should always be a staticly declared C string.
110 /// Number - Value to make label unique.
114 DWLabel(const char *T, unsigned N) : Tag(T), Number(N) {}
116 void Profile(FoldingSetNodeID &ID) const {
117 ID.AddString(std::string(Tag));
118 ID.AddInteger(Number);
122 void print(std::ostream *O) const {
125 void print(std::ostream &O) const {
127 if (Number) O << Number;
132 //===----------------------------------------------------------------------===//
133 /// DIEAbbrevData - Dwarf abbreviation data, describes the one attribute of a
134 /// Dwarf abbreviation.
135 class DIEAbbrevData {
137 /// Attribute - Dwarf attribute code.
141 /// Form - Dwarf form code.
146 DIEAbbrevData(unsigned A, unsigned F)
152 unsigned getAttribute() const { return Attribute; }
153 unsigned getForm() const { return Form; }
155 /// Profile - Used to gather unique data for the abbreviation folding set.
157 void Profile(FoldingSetNodeID &ID)const {
158 ID.AddInteger(Attribute);
163 //===----------------------------------------------------------------------===//
164 /// DIEAbbrev - Dwarf abbreviation, describes the organization of a debug
165 /// information object.
166 class DIEAbbrev : public FoldingSetNode {
168 /// Tag - Dwarf tag code.
172 /// Unique number for node.
176 /// ChildrenFlag - Dwarf children flag.
178 unsigned ChildrenFlag;
180 /// Data - Raw data bytes for abbreviation.
182 SmallVector<DIEAbbrevData, 8> Data;
186 DIEAbbrev(unsigned T, unsigned C)
194 unsigned getTag() const { return Tag; }
195 unsigned getNumber() const { return Number; }
196 unsigned getChildrenFlag() const { return ChildrenFlag; }
197 const SmallVector<DIEAbbrevData, 8> &getData() const { return Data; }
198 void setTag(unsigned T) { Tag = T; }
199 void setChildrenFlag(unsigned CF) { ChildrenFlag = CF; }
200 void setNumber(unsigned N) { Number = N; }
202 /// AddAttribute - Adds another set of attribute information to the
204 void AddAttribute(unsigned Attribute, unsigned Form) {
205 Data.push_back(DIEAbbrevData(Attribute, Form));
208 /// AddFirstAttribute - Adds a set of attribute information to the front
209 /// of the abbreviation.
210 void AddFirstAttribute(unsigned Attribute, unsigned Form) {
211 Data.insert(Data.begin(), DIEAbbrevData(Attribute, Form));
214 /// Profile - Used to gather unique data for the abbreviation folding set.
216 void Profile(FoldingSetNodeID &ID) {
218 ID.AddInteger(ChildrenFlag);
220 // For each attribute description.
221 for (unsigned i = 0, N = Data.size(); i < N; ++i)
225 /// Emit - Print the abbreviation using the specified Dwarf writer.
227 void Emit(const DwarfDebug &DD) const;
230 void print(std::ostream *O) {
233 void print(std::ostream &O);
238 //===----------------------------------------------------------------------===//
239 /// DIE - A structured debug information entry. Has an abbreviation which
240 /// describes it's organization.
241 class DIE : public FoldingSetNode {
243 /// Abbrev - Buffer for constructing abbreviation.
247 /// Offset - Offset in debug info section.
251 /// Size - Size of instance + children.
257 std::vector<DIE *> Children;
259 /// Attributes values.
261 SmallVector<DIEValue*, 32> Values;
264 explicit DIE(unsigned Tag)
265 : Abbrev(Tag, DW_CHILDREN_no)
274 DIEAbbrev &getAbbrev() { return Abbrev; }
275 unsigned getAbbrevNumber() const {
276 return Abbrev.getNumber();
278 unsigned getTag() const { return Abbrev.getTag(); }
279 unsigned getOffset() const { return Offset; }
280 unsigned getSize() const { return Size; }
281 const std::vector<DIE *> &getChildren() const { return Children; }
282 SmallVector<DIEValue*, 32> &getValues() { return Values; }
283 void setTag(unsigned Tag) { Abbrev.setTag(Tag); }
284 void setOffset(unsigned O) { Offset = O; }
285 void setSize(unsigned S) { Size = S; }
287 /// AddValue - Add a value and attributes to a DIE.
289 void AddValue(unsigned Attribute, unsigned Form, DIEValue *Value) {
290 Abbrev.AddAttribute(Attribute, Form);
291 Values.push_back(Value);
294 /// SiblingOffset - Return the offset of the debug information entry's
296 unsigned SiblingOffset() const { return Offset + Size; }
298 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
300 void AddSiblingOffset();
302 /// AddChild - Add a child to the DIE.
304 void AddChild(DIE *Child) {
305 Abbrev.setChildrenFlag(DW_CHILDREN_yes);
306 Children.push_back(Child);
309 /// Detach - Detaches objects connected to it after copying.
315 /// Profile - Used to gather unique data for the value folding set.
317 void Profile(FoldingSetNodeID &ID) ;
320 void print(std::ostream *O, unsigned IncIndent = 0) {
321 if (O) print(*O, IncIndent);
323 void print(std::ostream &O, unsigned IncIndent = 0);
328 //===----------------------------------------------------------------------===//
329 /// DIEValue - A debug information entry value.
331 class DIEValue : public FoldingSetNode {
344 /// Type - Type of data stored in the value.
348 explicit DIEValue(unsigned T)
351 virtual ~DIEValue() {}
354 unsigned getType() const { return Type; }
356 // Implement isa/cast/dyncast.
357 static bool classof(const DIEValue *) { return true; }
359 /// EmitValue - Emit value via the Dwarf writer.
361 virtual void EmitValue(DwarfDebug &DD, unsigned Form) = 0;
363 /// SizeOf - Return the size of a value in bytes.
365 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const = 0;
367 /// Profile - Used to gather unique data for the value folding set.
369 virtual void Profile(FoldingSetNodeID &ID) = 0;
372 void print(std::ostream *O) {
375 virtual void print(std::ostream &O) = 0;
380 //===----------------------------------------------------------------------===//
381 /// DWInteger - An integer value DIE.
383 class DIEInteger : public DIEValue {
388 explicit DIEInteger(uint64_t I) : DIEValue(isInteger), Integer(I) {}
390 // Implement isa/cast/dyncast.
391 static bool classof(const DIEInteger *) { return true; }
392 static bool classof(const DIEValue *I) { return I->Type == isInteger; }
394 /// BestForm - Choose the best form for integer.
396 static unsigned BestForm(bool IsSigned, uint64_t Integer) {
398 if ((char)Integer == (signed)Integer) return DW_FORM_data1;
399 if ((short)Integer == (signed)Integer) return DW_FORM_data2;
400 if ((int)Integer == (signed)Integer) return DW_FORM_data4;
402 if ((unsigned char)Integer == Integer) return DW_FORM_data1;
403 if ((unsigned short)Integer == Integer) return DW_FORM_data2;
404 if ((unsigned int)Integer == Integer) return DW_FORM_data4;
406 return DW_FORM_data8;
409 /// EmitValue - Emit integer of appropriate size.
411 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
413 /// SizeOf - Determine size of integer value in bytes.
415 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
417 /// Profile - Used to gather unique data for the value folding set.
419 static void Profile(FoldingSetNodeID &ID, unsigned Integer) {
420 ID.AddInteger(isInteger);
421 ID.AddInteger(Integer);
423 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Integer); }
426 virtual void print(std::ostream &O) {
427 O << "Int: " << (int64_t)Integer
428 << " 0x" << std::hex << Integer << std::dec;
433 //===----------------------------------------------------------------------===//
434 /// DIEString - A string value DIE.
436 class DIEString : public DIEValue {
438 const std::string String;
440 explicit DIEString(const std::string &S) : DIEValue(isString), String(S) {}
442 // Implement isa/cast/dyncast.
443 static bool classof(const DIEString *) { return true; }
444 static bool classof(const DIEValue *S) { return S->Type == isString; }
446 /// EmitValue - Emit string value.
448 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
450 /// SizeOf - Determine size of string value in bytes.
452 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
453 return String.size() + sizeof(char); // sizeof('\0');
456 /// Profile - Used to gather unique data for the value folding set.
458 static void Profile(FoldingSetNodeID &ID, const std::string &String) {
459 ID.AddInteger(isString);
460 ID.AddString(String);
462 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, String); }
465 virtual void print(std::ostream &O) {
466 O << "Str: \"" << String << "\"";
471 //===----------------------------------------------------------------------===//
472 /// DIEDwarfLabel - A Dwarf internal label expression DIE.
474 class DIEDwarfLabel : public DIEValue {
479 explicit DIEDwarfLabel(const DWLabel &L) : DIEValue(isLabel), Label(L) {}
481 // Implement isa/cast/dyncast.
482 static bool classof(const DIEDwarfLabel *) { return true; }
483 static bool classof(const DIEValue *L) { return L->Type == isLabel; }
485 /// EmitValue - Emit label value.
487 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
489 /// SizeOf - Determine size of label value in bytes.
491 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
493 /// Profile - Used to gather unique data for the value folding set.
495 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label) {
496 ID.AddInteger(isLabel);
499 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
502 virtual void print(std::ostream &O) {
510 //===----------------------------------------------------------------------===//
511 /// DIEObjectLabel - A label to an object in code or data.
513 class DIEObjectLabel : public DIEValue {
515 const std::string Label;
517 explicit DIEObjectLabel(const std::string &L)
518 : DIEValue(isAsIsLabel), Label(L) {}
520 // Implement isa/cast/dyncast.
521 static bool classof(const DIEObjectLabel *) { return true; }
522 static bool classof(const DIEValue *L) { return L->Type == isAsIsLabel; }
524 /// EmitValue - Emit label value.
526 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
528 /// SizeOf - Determine size of label value in bytes.
530 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
532 /// Profile - Used to gather unique data for the value folding set.
534 static void Profile(FoldingSetNodeID &ID, const std::string &Label) {
535 ID.AddInteger(isAsIsLabel);
538 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
541 virtual void print(std::ostream &O) {
542 O << "Obj: " << Label;
547 //===----------------------------------------------------------------------===//
548 /// DIESectionOffset - A section offset DIE.
550 class DIESectionOffset : public DIEValue {
553 const DWLabel Section;
557 DIESectionOffset(const DWLabel &Lab, const DWLabel &Sec,
558 bool isEH = false, bool useSet = true)
559 : DIEValue(isSectionOffset), Label(Lab), Section(Sec),
560 IsEH(isEH), UseSet(useSet) {}
562 // Implement isa/cast/dyncast.
563 static bool classof(const DIESectionOffset *) { return true; }
564 static bool classof(const DIEValue *D) { return D->Type == isSectionOffset; }
566 /// EmitValue - Emit section offset.
568 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
570 /// SizeOf - Determine size of section offset value in bytes.
572 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
574 /// Profile - Used to gather unique data for the value folding set.
576 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label,
577 const DWLabel &Section) {
578 ID.AddInteger(isSectionOffset);
581 // IsEH and UseSet are specific to the Label/Section that we will emit
582 // the offset for; so Label/Section are enough for uniqueness.
584 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label, Section); }
587 virtual void print(std::ostream &O) {
592 O << "-" << IsEH << "-" << UseSet;
597 //===----------------------------------------------------------------------===//
598 /// DIEDelta - A simple label difference DIE.
600 class DIEDelta : public DIEValue {
602 const DWLabel LabelHi;
603 const DWLabel LabelLo;
605 DIEDelta(const DWLabel &Hi, const DWLabel &Lo)
606 : DIEValue(isDelta), LabelHi(Hi), LabelLo(Lo) {}
608 // Implement isa/cast/dyncast.
609 static bool classof(const DIEDelta *) { return true; }
610 static bool classof(const DIEValue *D) { return D->Type == isDelta; }
612 /// EmitValue - Emit delta value.
614 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
616 /// SizeOf - Determine size of delta value in bytes.
618 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
620 /// Profile - Used to gather unique data for the value folding set.
622 static void Profile(FoldingSetNodeID &ID, const DWLabel &LabelHi,
623 const DWLabel &LabelLo) {
624 ID.AddInteger(isDelta);
628 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, LabelHi, LabelLo); }
631 virtual void print(std::ostream &O) {
640 //===----------------------------------------------------------------------===//
641 /// DIEntry - A pointer to another debug information entry. An instance of this
642 /// class can also be used as a proxy for a debug information entry not yet
643 /// defined (ie. types.)
644 class DIEntry : public DIEValue {
648 explicit DIEntry(DIE *E) : DIEValue(isEntry), Entry(E) {}
650 // Implement isa/cast/dyncast.
651 static bool classof(const DIEntry *) { return true; }
652 static bool classof(const DIEValue *E) { return E->Type == isEntry; }
654 /// EmitValue - Emit debug information entry offset.
656 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
658 /// SizeOf - Determine size of debug information entry in bytes.
660 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
661 return sizeof(int32_t);
664 /// Profile - Used to gather unique data for the value folding set.
666 static void Profile(FoldingSetNodeID &ID, DIE *Entry) {
667 ID.AddInteger(isEntry);
668 ID.AddPointer(Entry);
670 virtual void Profile(FoldingSetNodeID &ID) {
671 ID.AddInteger(isEntry);
674 ID.AddPointer(Entry);
681 virtual void print(std::ostream &O) {
682 O << "Die: 0x" << std::hex << (intptr_t)Entry << std::dec;
687 //===----------------------------------------------------------------------===//
688 /// DIEBlock - A block of values. Primarily used for location expressions.
690 class DIEBlock : public DIEValue, public DIE {
692 unsigned Size; // Size in bytes excluding size header.
702 // Implement isa/cast/dyncast.
703 static bool classof(const DIEBlock *) { return true; }
704 static bool classof(const DIEValue *E) { return E->Type == isBlock; }
706 /// ComputeSize - calculate the size of the block.
708 unsigned ComputeSize(DwarfDebug &DD);
710 /// BestForm - Choose the best form for data.
712 unsigned BestForm() const {
713 if ((unsigned char)Size == Size) return DW_FORM_block1;
714 if ((unsigned short)Size == Size) return DW_FORM_block2;
715 if ((unsigned int)Size == Size) return DW_FORM_block4;
716 return DW_FORM_block;
719 /// EmitValue - Emit block data.
721 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
723 /// SizeOf - Determine size of block data in bytes.
725 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
728 /// Profile - Used to gather unique data for the value folding set.
730 virtual void Profile(FoldingSetNodeID &ID) {
731 ID.AddInteger(isBlock);
736 virtual void print(std::ostream &O) {
743 //===----------------------------------------------------------------------===//
744 /// CompileUnit - This dwarf writer support class manages information associate
745 /// with a source file.
748 /// Desc - Compile unit debug descriptor.
750 CompileUnitDesc *Desc;
752 /// ID - File identifier for source.
756 /// Die - Compile unit debug information entry.
760 /// DescToDieMap - Tracks the mapping of unit level debug informaton
761 /// descriptors to debug information entries.
762 std::map<DebugInfoDesc *, DIE *> DescToDieMap;
763 DenseMap<GlobalVariable *, DIE *> GVToDieMap;
765 /// DescToDIEntryMap - Tracks the mapping of unit level debug informaton
766 /// descriptors to debug information entries using a DIEntry proxy.
767 std::map<DebugInfoDesc *, DIEntry *> DescToDIEntryMap;
768 DenseMap<GlobalVariable *, DIEntry *> GVToDIEntryMap;
770 /// Globals - A map of globally visible named entities for this unit.
772 std::map<std::string, DIE *> Globals;
774 /// DiesSet - Used to uniquely define dies within the compile unit.
776 FoldingSet<DIE> DiesSet;
778 /// Dies - List of all dies in the compile unit.
780 std::vector<DIE *> Dies;
783 CompileUnit(unsigned I, DIE *D)
784 : ID(I), Die(D), DescToDieMap(), GVToDieMap(), DescToDIEntryMap(),
785 GVToDIEntryMap(), Globals(), DiesSet(InitDiesSetSize), Dies()
788 CompileUnit(CompileUnitDesc *CUD, unsigned I, DIE *D)
797 , DiesSet(InitDiesSetSize)
804 for (unsigned i = 0, N = Dies.size(); i < N; ++i)
809 CompileUnitDesc *getDesc() const { return Desc; }
810 unsigned getID() const { return ID; }
811 DIE* getDie() const { return Die; }
812 std::map<std::string, DIE *> &getGlobals() { return Globals; }
814 /// hasContent - Return true if this compile unit has something to write out.
816 bool hasContent() const {
817 return !Die->getChildren().empty();
820 /// AddGlobal - Add a new global entity to the compile unit.
822 void AddGlobal(const std::string &Name, DIE *Die) {
826 /// getDieMapSlotFor - Returns the debug information entry map slot for the
827 /// specified debug descriptor.
828 DIE *&getDieMapSlotFor(DebugInfoDesc *DID) {
829 return DescToDieMap[DID];
831 DIE *&getDieMapSlotFor(GlobalVariable *GV) {
832 return GVToDieMap[GV];
835 /// getDIEntrySlotFor - Returns the debug information entry proxy slot for the
836 /// specified debug descriptor.
837 DIEntry *&getDIEntrySlotFor(DebugInfoDesc *DID) {
838 return DescToDIEntryMap[DID];
840 DIEntry *&getDIEntrySlotFor(GlobalVariable *GV) {
841 return GVToDIEntryMap[GV];
844 /// AddDie - Adds or interns the DIE to the compile unit.
846 DIE *AddDie(DIE &Buffer) {
850 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
853 Die = new DIE(Buffer);
854 DiesSet.InsertNode(Die, Where);
855 this->Die->AddChild(Die);
863 //===----------------------------------------------------------------------===//
864 /// Dwarf - Emits general Dwarf directives.
870 //===--------------------------------------------------------------------===//
871 // Core attributes used by the Dwarf writer.
875 /// O - Stream to .s file.
879 /// Asm - Target of Dwarf emission.
883 /// TAI - Target asm information.
884 const TargetAsmInfo *TAI;
886 /// TD - Target data.
887 const TargetData *TD;
889 /// RI - Register Information.
890 const TargetRegisterInfo *RI;
892 /// M - Current module.
896 /// MF - Current machine function.
900 /// MMI - Collected machine module information.
902 MachineModuleInfo *MMI;
904 /// SubprogramCount - The running count of functions being compiled.
906 unsigned SubprogramCount;
908 /// Flavor - A unique string indicating what dwarf producer this is, used to
910 const char * const Flavor;
913 Dwarf(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T,
918 , TD(Asm->TM.getTargetData())
919 , RI(Asm->TM.getRegisterInfo())
931 //===--------------------------------------------------------------------===//
934 AsmPrinter *getAsm() const { return Asm; }
935 MachineModuleInfo *getMMI() const { return MMI; }
936 const TargetAsmInfo *getTargetAsmInfo() const { return TAI; }
937 const TargetData *getTargetData() const { return TD; }
939 void PrintRelDirective(bool Force32Bit = false, bool isInSection = false)
941 if (isInSection && TAI->getDwarfSectionOffsetDirective())
942 O << TAI->getDwarfSectionOffsetDirective();
943 else if (Force32Bit || TD->getPointerSize() == sizeof(int32_t))
944 O << TAI->getData32bitsDirective();
946 O << TAI->getData64bitsDirective();
949 /// PrintLabelName - Print label name in form used by Dwarf writer.
951 void PrintLabelName(DWLabel Label) const {
952 PrintLabelName(Label.Tag, Label.Number);
954 void PrintLabelName(const char *Tag, unsigned Number) const {
955 O << TAI->getPrivateGlobalPrefix() << Tag;
956 if (Number) O << Number;
959 void PrintLabelName(const char *Tag, unsigned Number,
960 const char *Suffix) const {
961 O << TAI->getPrivateGlobalPrefix() << Tag;
962 if (Number) O << Number;
966 /// EmitLabel - Emit location label for internal use by Dwarf.
968 void EmitLabel(DWLabel Label) const {
969 EmitLabel(Label.Tag, Label.Number);
971 void EmitLabel(const char *Tag, unsigned Number) const {
972 PrintLabelName(Tag, Number);
976 /// EmitReference - Emit a reference to a label.
978 void EmitReference(DWLabel Label, bool IsPCRelative = false,
979 bool Force32Bit = false) const {
980 EmitReference(Label.Tag, Label.Number, IsPCRelative, Force32Bit);
982 void EmitReference(const char *Tag, unsigned Number,
983 bool IsPCRelative = false, bool Force32Bit = false) const {
984 PrintRelDirective(Force32Bit);
985 PrintLabelName(Tag, Number);
987 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
989 void EmitReference(const std::string &Name, bool IsPCRelative = false,
990 bool Force32Bit = false) const {
991 PrintRelDirective(Force32Bit);
995 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
998 /// EmitDifference - Emit the difference between two labels. Some
999 /// assemblers do not behave with absolute expressions with data directives,
1000 /// so there is an option (needsSet) to use an intermediary set expression.
1001 void EmitDifference(DWLabel LabelHi, DWLabel LabelLo,
1002 bool IsSmall = false) {
1003 EmitDifference(LabelHi.Tag, LabelHi.Number,
1004 LabelLo.Tag, LabelLo.Number,
1007 void EmitDifference(const char *TagHi, unsigned NumberHi,
1008 const char *TagLo, unsigned NumberLo,
1009 bool IsSmall = false) {
1010 if (TAI->needsSet()) {
1012 PrintLabelName("set", SetCounter, Flavor);
1014 PrintLabelName(TagHi, NumberHi);
1016 PrintLabelName(TagLo, NumberLo);
1019 PrintRelDirective(IsSmall);
1020 PrintLabelName("set", SetCounter, Flavor);
1023 PrintRelDirective(IsSmall);
1025 PrintLabelName(TagHi, NumberHi);
1027 PrintLabelName(TagLo, NumberLo);
1031 void EmitSectionOffset(const char* Label, const char* Section,
1032 unsigned LabelNumber, unsigned SectionNumber,
1033 bool IsSmall = false, bool isEH = false,
1034 bool useSet = true) {
1035 bool printAbsolute = false;
1037 printAbsolute = TAI->isAbsoluteEHSectionOffsets();
1039 printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
1041 if (TAI->needsSet() && useSet) {
1043 PrintLabelName("set", SetCounter, Flavor);
1045 PrintLabelName(Label, LabelNumber);
1047 if (!printAbsolute) {
1049 PrintLabelName(Section, SectionNumber);
1053 PrintRelDirective(IsSmall);
1055 PrintLabelName("set", SetCounter, Flavor);
1058 PrintRelDirective(IsSmall, true);
1060 PrintLabelName(Label, LabelNumber);
1062 if (!printAbsolute) {
1064 PrintLabelName(Section, SectionNumber);
1069 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
1071 void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
1072 const std::vector<MachineMove> &Moves, bool isEH) {
1074 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
1075 TargetFrameInfo::StackGrowsUp ?
1076 TD->getPointerSize() : -TD->getPointerSize();
1077 bool IsLocal = BaseLabel && strcmp(BaseLabel, "label") == 0;
1079 for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
1080 const MachineMove &Move = Moves[i];
1081 unsigned LabelID = Move.getLabelID();
1084 LabelID = MMI->MappedLabel(LabelID);
1086 // Throw out move if the label is invalid.
1087 if (!LabelID) continue;
1090 const MachineLocation &Dst = Move.getDestination();
1091 const MachineLocation &Src = Move.getSource();
1093 // Advance row if new location.
1094 if (BaseLabel && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
1095 Asm->EmitInt8(DW_CFA_advance_loc4);
1096 Asm->EOL("DW_CFA_advance_loc4");
1097 EmitDifference("label", LabelID, BaseLabel, BaseLabelID, true);
1100 BaseLabelID = LabelID;
1101 BaseLabel = "label";
1105 // If advancing cfa.
1106 if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
1108 if (Src.getReg() == MachineLocation::VirtualFP) {
1109 Asm->EmitInt8(DW_CFA_def_cfa_offset);
1110 Asm->EOL("DW_CFA_def_cfa_offset");
1112 Asm->EmitInt8(DW_CFA_def_cfa);
1113 Asm->EOL("DW_CFA_def_cfa");
1114 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getReg(), isEH));
1115 Asm->EOL("Register");
1118 int Offset = -Src.getOffset();
1120 Asm->EmitULEB128Bytes(Offset);
1123 assert(0 && "Machine move no supported yet.");
1125 } else if (Src.isReg() &&
1126 Src.getReg() == MachineLocation::VirtualFP) {
1128 Asm->EmitInt8(DW_CFA_def_cfa_register);
1129 Asm->EOL("DW_CFA_def_cfa_register");
1130 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getReg(), isEH));
1131 Asm->EOL("Register");
1133 assert(0 && "Machine move no supported yet.");
1136 unsigned Reg = RI->getDwarfRegNum(Src.getReg(), isEH);
1137 int Offset = Dst.getOffset() / stackGrowth;
1140 Asm->EmitInt8(DW_CFA_offset_extended_sf);
1141 Asm->EOL("DW_CFA_offset_extended_sf");
1142 Asm->EmitULEB128Bytes(Reg);
1144 Asm->EmitSLEB128Bytes(Offset);
1146 } else if (Reg < 64) {
1147 Asm->EmitInt8(DW_CFA_offset + Reg);
1149 Asm->EOL("DW_CFA_offset + Reg (" + utostr(Reg) + ")");
1152 Asm->EmitULEB128Bytes(Offset);
1155 Asm->EmitInt8(DW_CFA_offset_extended);
1156 Asm->EOL("DW_CFA_offset_extended");
1157 Asm->EmitULEB128Bytes(Reg);
1159 Asm->EmitULEB128Bytes(Offset);
1168 //===----------------------------------------------------------------------===//
1169 /// SourceLineInfo - This class is used to record source line correspondence.
1172 unsigned Line; // Source line number.
1173 unsigned Column; // Source column.
1174 unsigned SourceID; // Source ID number.
1175 unsigned LabelID; // Label in code ID number.
1177 SrcLineInfo(unsigned L, unsigned C, unsigned S, unsigned I)
1178 : Line(L), Column(C), SourceID(S), LabelID(I) {}
1181 unsigned getLine() const { return Line; }
1182 unsigned getColumn() const { return Column; }
1183 unsigned getSourceID() const { return SourceID; }
1184 unsigned getLabelID() const { return LabelID; }
1188 //===----------------------------------------------------------------------===//
1189 /// SrcFileInfo - This class is used to track source information.
1192 unsigned DirectoryID; // Directory ID number.
1193 std::string Name; // File name (not including directory.)
1195 SrcFileInfo(unsigned D, const std::string &N) : DirectoryID(D), Name(N) {}
1198 unsigned getDirectoryID() const { return DirectoryID; }
1199 const std::string &getName() const { return Name; }
1201 /// operator== - Used by UniqueVector to locate entry.
1203 bool operator==(const SourceFileInfo &SI) const {
1204 return getDirectoryID() == SI.getDirectoryID() && getName() == SI.getName();
1207 /// operator< - Used by UniqueVector to locate entry.
1209 bool operator<(const SrcFileInfo &SI) const {
1210 return getDirectoryID() < SI.getDirectoryID() ||
1211 (getDirectoryID() == SI.getDirectoryID() && getName() < SI.getName());
1215 //===----------------------------------------------------------------------===//
1216 /// DbgVariable - This class is used to track local variable information.
1220 DIVariable *Var; // Variable Descriptor.
1221 unsigned FrameIndex; // Variable frame index.
1224 DbgVariable(DIVariable *V, unsigned I) : Var(V), FrameIndex(I) {}
1227 DIVariable *getVariable() const { return Var; }
1228 unsigned getFrameIndex() const { return FrameIndex; }
1231 //===----------------------------------------------------------------------===//
1232 /// DbgScope - This class is used to track scope information.
1236 DbgScope *Parent; // Parent to this scope.
1237 DIDescriptor *Desc; // Debug info descriptor for scope.
1238 // Either subprogram or block.
1239 unsigned StartLabelID; // Label ID of the beginning of scope.
1240 unsigned EndLabelID; // Label ID of the end of scope.
1241 SmallVector<DbgScope *, 8> Scopes; // Scopes defined in scope.
1242 SmallVector<DbgVariable *, 32> Variables;// Variables declared in scope.
1245 DbgScope(DbgScope *P, DIDescriptor *D)
1246 : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0), Scopes(), Variables()
1251 DbgScope *getParent() const { return Parent; }
1252 DIDescriptor *getDesc() const { return Desc; }
1253 unsigned getStartLabelID() const { return StartLabelID; }
1254 unsigned getEndLabelID() const { return EndLabelID; }
1255 SmallVector<DbgScope *, 8> &getScopes() { return Scopes; }
1256 SmallVector<DbgVariable *, 32> &getVariables() { return Variables; }
1257 void setStartLabelID(unsigned S) { StartLabelID = S; }
1258 void setEndLabelID(unsigned E) { EndLabelID = E; }
1260 /// AddScope - Add a scope to the scope.
1262 void AddScope(DbgScope *S) { Scopes.push_back(S); }
1264 /// AddVariable - Add a variable to the scope.
1266 void AddVariable(DbgVariable *V) { Variables.push_back(V); }
1269 //===----------------------------------------------------------------------===//
1270 /// DwarfDebug - Emits Dwarf debug directives.
1272 class DwarfDebug : public Dwarf {
1275 //===--------------------------------------------------------------------===//
1276 // Attributes used to construct specific Dwarf sections.
1279 /// CompileUnits - All the compile units involved in this build. The index
1280 /// of each entry in this vector corresponds to the sources in MMI.
1281 std::vector<CompileUnit *> CompileUnits;
1282 DenseMap<Value *, CompileUnit *> DW_CUs;
1284 /// AbbreviationsSet - Used to uniquely define abbreviations.
1286 FoldingSet<DIEAbbrev> AbbreviationsSet;
1288 /// Abbreviations - A list of all the unique abbreviations in use.
1290 std::vector<DIEAbbrev *> Abbreviations;
1292 /// ValuesSet - Used to uniquely define values.
1294 // Directories - Uniquing vector for directories.
1295 UniqueVector<std::string> Directories;
1297 // SourceFiles - Uniquing vector for source files.
1298 UniqueVector<SrcFileInfo> SrcFiles;
1300 // Lines - List of of source line correspondence.
1301 std::vector<SrcLineInfo> Lines;
1303 FoldingSet<DIEValue> ValuesSet;
1305 /// Values - A list of all the unique values in use.
1307 std::vector<DIEValue *> Values;
1309 /// StringPool - A UniqueVector of strings used by indirect references.
1311 UniqueVector<std::string> StringPool;
1313 /// UnitMap - Map debug information descriptor to compile unit.
1315 std::map<DebugInfoDesc *, CompileUnit *> DescToUnitMap;
1317 /// SectionMap - Provides a unique id per text section.
1319 UniqueVector<const Section*> SectionMap;
1321 /// SectionSourceLines - Tracks line numbers per text section.
1323 std::vector<std::vector<SourceLineInfo> > SectionSourceLines;
1325 /// didInitial - Flag to indicate if initial emission has been done.
1329 /// shouldEmit - Flag to indicate if debug information should be emitted.
1333 // RootScope - Top level scope for the current function.
1335 DbgScope *RootDbgScope;
1337 // DbgScopeMap - Tracks the scopes in the current function.
1338 DenseMap<GlobalVariable *, DbgScope *> DbgScopeMap;
1340 // DbgLabelIDList - One entry per assigned label. Normally the entry is equal to
1341 // the list index(+1). If the entry is zero then the label has been deleted.
1342 // Any other value indicates the label has been deleted by is mapped to
1344 SmallVector<unsigned, 32> DbgLabelIDList;
1346 /// NextLabelID - Return the next unique label id.
1348 unsigned NextLabelID() {
1349 unsigned ID = (unsigned)DbgLabelIDList.size() + 1;
1350 DbgLabelIDList.push_back(ID);
1354 /// RemapLabel - Indicate that a label has been merged into another.
1356 void RemapLabel(unsigned OldLabelID, unsigned NewLabelID) {
1357 assert(0 < OldLabelID && OldLabelID <= DbgLabelIDList.size() &&
1358 "Old label ID out of range.");
1359 assert(NewLabelID <= DbgLabelIDList.size() &&
1360 "New label ID out of range.");
1361 DbgLabelIDList[OldLabelID - 1] = NewLabelID;
1364 /// MappedLabel - Find out the label's final ID. Zero indicates deletion.
1365 /// ID != Mapped ID indicates that the label was folded into another label.
1366 unsigned MappedLabel(unsigned LabelID) const {
1367 assert(LabelID <= DbgLabelIDList.size() && "Debug label ID out of range.");
1368 return LabelID ? DbgLabelIDList[LabelID - 1] : 0;
1371 struct FunctionDebugFrameInfo {
1373 std::vector<MachineMove> Moves;
1375 FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
1376 Number(Num), Moves(M) { }
1379 std::vector<FunctionDebugFrameInfo> DebugFrames;
1383 /// ShouldEmitDwarf - Returns true if Dwarf declarations should be made.
1385 bool ShouldEmitDwarf() const { return shouldEmit; }
1387 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1389 void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1390 // Profile the node so that we can make it unique.
1391 FoldingSetNodeID ID;
1394 // Check the set for priors.
1395 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1397 // If it's newly added.
1398 if (InSet == &Abbrev) {
1399 // Add to abbreviation list.
1400 Abbreviations.push_back(&Abbrev);
1401 // Assign the vector position + 1 as its number.
1402 Abbrev.setNumber(Abbreviations.size());
1404 // Assign existing abbreviation number.
1405 Abbrev.setNumber(InSet->getNumber());
1409 /// NewString - Add a string to the constant pool and returns a label.
1411 DWLabel NewString(const std::string &String) {
1412 unsigned StringID = StringPool.insert(String);
1413 return DWLabel("string", StringID);
1416 /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1418 DIEntry *NewDIEntry(DIE *Entry = NULL) {
1422 FoldingSetNodeID ID;
1423 DIEntry::Profile(ID, Entry);
1425 Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1427 if (Value) return Value;
1429 Value = new DIEntry(Entry);
1430 ValuesSet.InsertNode(Value, Where);
1432 Value = new DIEntry(Entry);
1435 Values.push_back(Value);
1439 /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1441 void SetDIEntry(DIEntry *Value, DIE *Entry) {
1442 Value->Entry = Entry;
1443 // Add to values set if not already there. If it is, we merely have a
1444 // duplicate in the values list (no harm.)
1445 ValuesSet.GetOrInsertNode(Value);
1448 /// AddUInt - Add an unsigned integer attribute data and value.
1450 void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1451 if (!Form) Form = DIEInteger::BestForm(false, Integer);
1453 FoldingSetNodeID ID;
1454 DIEInteger::Profile(ID, Integer);
1456 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1458 Value = new DIEInteger(Integer);
1459 ValuesSet.InsertNode(Value, Where);
1460 Values.push_back(Value);
1463 Die->AddValue(Attribute, Form, Value);
1466 /// AddSInt - Add an signed integer attribute data and value.
1468 void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1469 if (!Form) Form = DIEInteger::BestForm(true, Integer);
1471 FoldingSetNodeID ID;
1472 DIEInteger::Profile(ID, (uint64_t)Integer);
1474 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1476 Value = new DIEInteger(Integer);
1477 ValuesSet.InsertNode(Value, Where);
1478 Values.push_back(Value);
1481 Die->AddValue(Attribute, Form, Value);
1484 /// AddString - Add a std::string attribute data and value.
1486 void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1487 const std::string &String) {
1488 FoldingSetNodeID ID;
1489 DIEString::Profile(ID, String);
1491 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1493 Value = new DIEString(String);
1494 ValuesSet.InsertNode(Value, Where);
1495 Values.push_back(Value);
1498 Die->AddValue(Attribute, Form, Value);
1501 /// AddLabel - Add a Dwarf label attribute data and value.
1503 void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1504 const DWLabel &Label) {
1505 FoldingSetNodeID ID;
1506 DIEDwarfLabel::Profile(ID, Label);
1508 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1510 Value = new DIEDwarfLabel(Label);
1511 ValuesSet.InsertNode(Value, Where);
1512 Values.push_back(Value);
1515 Die->AddValue(Attribute, Form, Value);
1518 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1520 void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1521 const std::string &Label) {
1522 FoldingSetNodeID ID;
1523 DIEObjectLabel::Profile(ID, Label);
1525 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1527 Value = new DIEObjectLabel(Label);
1528 ValuesSet.InsertNode(Value, Where);
1529 Values.push_back(Value);
1532 Die->AddValue(Attribute, Form, Value);
1535 /// AddSectionOffset - Add a section offset label attribute data and value.
1537 void AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
1538 const DWLabel &Label, const DWLabel &Section,
1539 bool isEH = false, bool useSet = true) {
1540 FoldingSetNodeID ID;
1541 DIESectionOffset::Profile(ID, Label, Section);
1543 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1545 Value = new DIESectionOffset(Label, Section, isEH, useSet);
1546 ValuesSet.InsertNode(Value, Where);
1547 Values.push_back(Value);
1550 Die->AddValue(Attribute, Form, Value);
1553 /// AddDelta - Add a label delta attribute data and value.
1555 void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1556 const DWLabel &Hi, const DWLabel &Lo) {
1557 FoldingSetNodeID ID;
1558 DIEDelta::Profile(ID, Hi, Lo);
1560 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1562 Value = new DIEDelta(Hi, Lo);
1563 ValuesSet.InsertNode(Value, Where);
1564 Values.push_back(Value);
1567 Die->AddValue(Attribute, Form, Value);
1570 /// AddDIEntry - Add a DIE attribute data and value.
1572 void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1573 Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1576 /// AddBlock - Add block data.
1578 void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1579 Block->ComputeSize(*this);
1580 FoldingSetNodeID ID;
1583 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1586 ValuesSet.InsertNode(Value, Where);
1587 Values.push_back(Value);
1589 // Already exists, reuse the previous one.
1591 Block = cast<DIEBlock>(Value);
1594 Die->AddValue(Attribute, Block->BestForm(), Value);
1599 /// AddSourceLine - Add location information to specified debug information
1601 void AddSourceLine(DIE *Die, CompileUnitDesc *File, unsigned Line) {
1603 CompileUnit *FileUnit = FindCompileUnit(File);
1604 unsigned FileID = FileUnit->getID();
1605 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1606 AddUInt(Die, DW_AT_decl_line, 0, Line);
1610 /// AddSourceLine - Add location information to specified debug information
1612 void AddSourceLine(DIE *Die, DIVariable *V) {
1613 unsigned FileID = 0;
1614 unsigned Line = V->getLineNumber();
1615 if (V->getVersion() < DIDescriptor::Version7) {
1616 // Version6 or earlier. Use compile unit info to get file id.
1617 CompileUnit *Unit = FindCompileUnit(V->getCompileUnit());
1618 FileID = Unit->getID();
1620 // Version7 or newer, use filename and directory info from DIVariable
1622 unsigned DID = Directories.idFor(V->getDirectory());
1623 FileID = SrcFiles.idFor(SrcFileInfo(DID, V->getFilename()));
1625 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1626 AddUInt(Die, DW_AT_decl_line, 0, Line);
1629 /// AddSourceLine - Add location information to specified debug information
1631 void AddSourceLine(DIE *Die, DIGlobal *G) {
1632 unsigned FileID = 0;
1633 unsigned Line = G->getLineNumber();
1634 if (G->getVersion() < DIDescriptor::Version7) {
1635 // Version6 or earlier. Use compile unit info to get file id.
1636 CompileUnit *Unit = FindCompileUnit(G->getCompileUnit());
1637 FileID = Unit->getID();
1639 // Version7 or newer, use filename and directory info from DIGlobal
1641 unsigned DID = Directories.idFor(G->getDirectory());
1642 FileID = SrcFiles.idFor(SrcFileInfo(DID, G->getFilename()));
1644 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1645 AddUInt(Die, DW_AT_decl_line, 0, Line);
1648 void AddSourceLine(DIE *Die, DIType *G) {
1649 unsigned FileID = 0;
1650 unsigned Line = G->getLineNumber();
1651 if (G->getVersion() < DIDescriptor::Version7) {
1652 // Version6 or earlier. Use compile unit info to get file id.
1653 CompileUnit *Unit = FindCompileUnit(G->getCompileUnit());
1654 FileID = Unit->getID();
1656 // Version7 or newer, use filename and directory info from DIGlobal
1658 unsigned DID = Directories.idFor(G->getDirectory());
1659 FileID = SrcFiles.idFor(SrcFileInfo(DID, G->getFilename()));
1661 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1662 AddUInt(Die, DW_AT_decl_line, 0, Line);
1665 /// AddAddress - Add an address attribute to a die based on the location
1667 void AddAddress(DIE *Die, unsigned Attribute,
1668 const MachineLocation &Location) {
1669 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
1670 DIEBlock *Block = new DIEBlock();
1672 if (Location.isReg()) {
1674 AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1676 AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1677 AddUInt(Block, 0, DW_FORM_udata, Reg);
1681 AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1683 AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1684 AddUInt(Block, 0, DW_FORM_udata, Reg);
1686 AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1689 AddBlock(Die, Attribute, 0, Block);
1692 /// AddBasicType - Add a new basic type attribute to the specified entity.
1694 void AddBasicType(DIE *Entity, CompileUnit *Unit,
1695 const std::string &Name,
1696 unsigned Encoding, unsigned Size) {
1698 DIE Buffer(DW_TAG_base_type);
1699 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1700 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, Encoding);
1701 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1702 DIE *BasicTypeDie = Unit->AddDie(Buffer);
1703 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, BasicTypeDie);
1706 /// AddPointerType - Add a new pointer type attribute to the specified entity.
1708 void AddPointerType(DIE *Entity, CompileUnit *Unit, const std::string &Name) {
1709 DIE Buffer(DW_TAG_pointer_type);
1710 AddUInt(&Buffer, DW_AT_byte_size, 0, TD->getPointerSize());
1711 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1712 DIE *PointerTypeDie = Unit->AddDie(Buffer);
1713 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, PointerTypeDie);
1716 /// AddType - Add a new type attribute to the specified entity.
1718 void AddType(DIE *Entity, TypeDesc *TyDesc, CompileUnit *Unit) {
1720 AddBasicType(Entity, Unit, "", DW_ATE_signed, sizeof(int32_t));
1722 // Check for pre-existence.
1723 DIEntry *&Slot = Unit->getDIEntrySlotFor(TyDesc);
1725 // If it exists then use the existing value.
1727 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1731 if (SubprogramDesc *SubprogramTy = dyn_cast<SubprogramDesc>(TyDesc)) {
1732 // FIXME - Not sure why programs and variables are coming through here.
1733 // Short cut for handling subprogram types (not really a TyDesc.)
1734 AddPointerType(Entity, Unit, SubprogramTy->getName());
1735 } else if (GlobalVariableDesc *GlobalTy =
1736 dyn_cast<GlobalVariableDesc>(TyDesc)) {
1737 // FIXME - Not sure why programs and variables are coming through here.
1738 // Short cut for handling global variable types (not really a TyDesc.)
1739 AddPointerType(Entity, Unit, GlobalTy->getName());
1742 Slot = NewDIEntry();
1745 DIE Buffer(DW_TAG_base_type);
1746 ConstructType(Buffer, TyDesc, Unit);
1748 // Add debug information entry to entity and unit.
1749 DIE *Die = Unit->AddDie(Buffer);
1750 SetDIEntry(Slot, Die);
1751 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1756 /// AddType - Add a new type attribute to the specified entity.
1757 void AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
1759 AddBasicType(Entity, DW_Unit, "", DW_ATE_signed, sizeof(int32_t));
1763 // Check for pre-existence.
1764 DIEntry *&Slot = DW_Unit->getDIEntrySlotFor(Ty.getGV());
1765 // If it exists then use the existing value.
1767 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1772 Slot = NewDIEntry();
1775 DIE Buffer(DW_TAG_base_type);
1776 if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
1777 ConstructTypeDIE(DW_Unit, Buffer, BT);
1778 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
1779 ConstructTypeDIE(DW_Unit, Buffer, DT);
1780 else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
1781 ConstructTypeDIE(DW_Unit, Buffer, CT);
1783 // Add debug information entry to entity and unit.
1784 DIE *Die = DW_Unit->AddDie(Buffer);
1785 SetDIEntry(Slot, Die);
1786 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1789 /// ConstructTypeDIE - Construct basic type die from DIBasicType.
1790 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1793 // Get core information.
1794 const std::string &Name = BTy->getName();
1795 Buffer.setTag(DW_TAG_base_type);
1796 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BTy->getEncoding());
1797 // Add name if not anonymous or intermediate type.
1799 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1800 uint64_t Size = BTy->getSizeInBits() >> 3;
1801 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1804 /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
1805 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1806 DIDerivedType *DTy) {
1808 // Get core information.
1809 const std::string &Name = DTy->getName();
1810 uint64_t Size = DTy->getSizeInBits() >> 3;
1811 unsigned Tag = DTy->getTag();
1812 // FIXME - Workaround for templates.
1813 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1816 // Map to main type, void will not have a type.
1817 DIType FromTy = DTy->getTypeDerivedFrom();
1818 AddType(DW_Unit, &Buffer, FromTy);
1820 // Add name if not anonymous or intermediate type.
1821 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1823 // Add size if non-zero (derived types might be zero-sized.)
1825 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1827 // Add source line info if available and TyDesc is not a forward
1829 // FIXME - Enable this. if (!DTy->isForwardDecl())
1830 // FIXME - Enable this. AddSourceLine(&Buffer, *DTy);
1833 /// ConstructTypeDIE - Construct type DIE from DICompositeType.
1834 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1835 DICompositeType *CTy) {
1837 // Get core information.
1838 const std::string &Name = CTy->getName();
1839 uint64_t Size = CTy->getSizeInBits() >> 3;
1840 unsigned Tag = CTy->getTag();
1842 case DW_TAG_vector_type:
1843 case DW_TAG_array_type:
1844 ConstructArrayTypeDIE(DW_Unit, Buffer, CTy);
1846 //FIXME - Enable this.
1847 // case DW_TAG_enumeration_type:
1848 // DIArray Elements = CTy->getTypeArray();
1849 // // Add enumerators to enumeration type.
1850 // for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i)
1851 // ConstructEnumTypeDIE(Buffer, &Elements.getElement(i));
1853 case DW_TAG_subroutine_type:
1855 // Add prototype flag.
1856 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1857 DIArray Elements = CTy->getTypeArray();
1859 DIDescriptor RTy = Elements.getElement(0);
1860 if (DIBasicType *BT = dyn_cast<DIBasicType>(&RTy))
1861 AddType(DW_Unit, &Buffer, *BT);
1862 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&RTy))
1863 AddType(DW_Unit, &Buffer, *DT);
1864 else if (DICompositeType *CT = dyn_cast<DICompositeType>(&RTy))
1865 AddType(DW_Unit, &Buffer, *CT);
1867 //AddType(DW_Unit, &Buffer, Elements.getElement(0));
1869 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1870 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1871 DIDescriptor Ty = Elements.getElement(i);
1872 if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
1873 AddType(DW_Unit, &Buffer, *BT);
1874 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
1875 AddType(DW_Unit, &Buffer, *DT);
1876 else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
1877 AddType(DW_Unit, &Buffer, *CT);
1878 Buffer.AddChild(Arg);
1882 case DW_TAG_structure_type:
1883 case DW_TAG_union_type:
1885 // Add elements to structure type.
1886 DIArray Elements = CTy->getTypeArray();
1887 // Add elements to structure type.
1888 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1889 DIDescriptor Element = Elements.getElement(i);
1890 if (DISubprogram *SP = dyn_cast<DISubprogram>(&Element))
1891 ConstructFieldTypeDIE(DW_Unit, Buffer, SP);
1892 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Element))
1893 ConstructFieldTypeDIE(DW_Unit, Buffer, DT);
1894 else if (DIGlobalVariable *GV = dyn_cast<DIGlobalVariable>(&Element))
1895 ConstructFieldTypeDIE(DW_Unit, Buffer, GV);
1903 // Add name if not anonymous or intermediate type.
1904 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1906 // Add size if non-zero (derived types might be zero-sized.)
1908 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1910 // Add zero size even if it is not a forward declaration.
1911 // FIXME - Enable this.
1912 // if (!CTy->isDefinition())
1913 // AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
1915 // AddUInt(&Buffer, DW_AT_byte_size, 0, 0);
1918 // Add source line info if available and TyDesc is not a forward
1920 // FIXME - Enable this.
1921 // if (CTy->isForwardDecl())
1922 // AddSourceLine(&Buffer, *CTy);
1925 // ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
1926 void ConstructSubrangeDIE (DIE &Buffer, DISubrange *SR, DIE *IndexTy) {
1927 int64_t L = SR->getLo();
1928 int64_t H = SR->getHi();
1929 DIE *DW_Subrange = new DIE(DW_TAG_subrange_type);
1931 AddDIEntry(DW_Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1933 AddSInt(DW_Subrange, DW_AT_lower_bound, 0, L);
1934 AddSInt(DW_Subrange, DW_AT_upper_bound, 0, H);
1936 Buffer.AddChild(DW_Subrange);
1939 /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
1940 void ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1941 DICompositeType *CTy) {
1942 Buffer.setTag(DW_TAG_array_type);
1943 if (CTy->getTag() == DW_TAG_vector_type)
1944 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1946 DIArray Elements = CTy->getTypeArray();
1947 // FIXME - Enable this.
1948 AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
1950 // Construct an anonymous type for index type.
1951 DIE IdxBuffer(DW_TAG_base_type);
1952 AddUInt(&IdxBuffer, DW_AT_byte_size, 0, sizeof(int32_t));
1953 AddUInt(&IdxBuffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
1954 DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
1956 // Add subranges to array type.
1957 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1958 DIDescriptor Element = Elements.getElement(i);
1959 if (DISubrange *SR = dyn_cast<DISubrange>(&Element))
1960 ConstructSubrangeDIE(Buffer, SR, IndexTy);
1964 /// ConstructEnumTypeDIE - Construct enum type DIE from
1966 void ConstructEnumTypeDIE(CompileUnit *DW_Unit,
1967 DIE &Buffer, DIEnumerator *ETy) {
1969 DIE *Enumerator = new DIE(DW_TAG_enumerator);
1970 AddString(Enumerator, DW_AT_name, DW_FORM_string, ETy->getName());
1971 int64_t Value = ETy->getEnumValue();
1972 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1973 Buffer.AddChild(Enumerator);
1976 /// ConstructFieldTypeDIE - Construct variable DIE for a struct field.
1977 void ConstructFieldTypeDIE(CompileUnit *DW_Unit,
1978 DIE &Buffer, DIGlobalVariable *V) {
1980 DIE *VariableDie = new DIE(DW_TAG_variable);
1981 const std::string &LinkageName = V->getLinkageName();
1982 if (!LinkageName.empty())
1983 AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1985 // FIXME - Enable this. AddSourceLine(VariableDie, V);
1986 AddType(DW_Unit, VariableDie, V->getType());
1987 if (!V->isLocalToUnit())
1988 AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
1989 AddUInt(VariableDie, DW_AT_declaration, DW_FORM_flag, 1);
1990 Buffer.AddChild(VariableDie);
1993 /// ConstructFieldTypeDIE - Construct subprogram DIE for a struct field.
1994 void ConstructFieldTypeDIE(CompileUnit *DW_Unit,
1995 DIE &Buffer, DISubprogram *SP,
1996 bool IsConstructor = false) {
1997 DIE *Method = new DIE(DW_TAG_subprogram);
1998 AddString(Method, DW_AT_name, DW_FORM_string, SP->getName());
1999 const std::string &LinkageName = SP->getLinkageName();
2000 if (!LinkageName.empty())
2001 AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string, LinkageName);
2002 // FIXME - Enable this. AddSourceLine(Method, SP);
2004 DICompositeType MTy = SP->getType();
2005 DIArray Args = MTy.getTypeArray();
2008 if (!IsConstructor) {
2009 DIDescriptor Ty = Args.getElement(0);
2010 if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
2011 AddType(DW_Unit, Method, *BT);
2012 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
2013 AddType(DW_Unit, Method, *DT);
2014 else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
2015 AddType(DW_Unit, Method, *CT);
2019 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
2020 DIE *Arg = new DIE(DW_TAG_formal_parameter);
2021 DIDescriptor Ty = Args.getElement(i);
2022 if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
2023 AddType(DW_Unit, Method, *BT);
2024 else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
2025 AddType(DW_Unit, Method, *DT);
2026 else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
2027 AddType(DW_Unit, Method, *CT);
2028 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1); // ???
2029 Method->AddChild(Arg);
2032 if (!SP->isLocalToUnit())
2033 AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);
2034 Buffer.AddChild(Method);
2037 /// COnstructFieldTypeDIE - Construct derived type DIE for a struct field.
2038 void ConstructFieldTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
2039 DIDerivedType *DTy) {
2040 unsigned Tag = DTy->getTag();
2041 DIE *MemberDie = new DIE(Tag);
2042 if (!DTy->getName().empty())
2043 AddString(MemberDie, DW_AT_name, DW_FORM_string, DTy->getName());
2044 // FIXME - Enable this. AddSourceLine(MemberDie, DTy);
2046 DIType FromTy = DTy->getTypeDerivedFrom();
2047 AddType(DW_Unit, MemberDie, FromTy);
2049 uint64_t Size = DTy->getSizeInBits();
2050 uint64_t Offset = DTy->getOffsetInBits();
2052 // FIXME Handle bitfields
2055 AddUInt(MemberDie, DW_AT_bit_size, 0, Size);
2056 // Add computation for offset.
2057 DIEBlock *Block = new DIEBlock();
2058 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
2059 AddUInt(Block, 0, DW_FORM_udata, Offset >> 3);
2060 AddBlock(MemberDie, DW_AT_data_member_location, 0, Block);
2062 // FIXME Handle DW_AT_accessibility.
2064 Buffer.AddChild(MemberDie);
2067 /// ConstructType - Adds all the required attributes to the type.
2069 void ConstructType(DIE &Buffer, TypeDesc *TyDesc, CompileUnit *Unit) {
2070 // Get core information.
2071 const std::string &Name = TyDesc->getName();
2072 uint64_t Size = TyDesc->getSize() >> 3;
2074 if (BasicTypeDesc *BasicTy = dyn_cast<BasicTypeDesc>(TyDesc)) {
2075 // Fundamental types like int, float, bool
2076 Buffer.setTag(DW_TAG_base_type);
2077 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BasicTy->getEncoding());
2078 } else if (DerivedTypeDesc *DerivedTy = dyn_cast<DerivedTypeDesc>(TyDesc)) {
2080 unsigned Tag = DerivedTy->getTag();
2081 // FIXME - Workaround for templates.
2082 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
2083 // Pointers, typedefs et al.
2085 // Map to main type, void will not have a type.
2086 if (TypeDesc *FromTy = DerivedTy->getFromType())
2087 AddType(&Buffer, FromTy, Unit);
2088 } else if (CompositeTypeDesc *CompTy = dyn_cast<CompositeTypeDesc>(TyDesc)){
2090 unsigned Tag = CompTy->getTag();
2092 // Set tag accordingly.
2093 if (Tag == DW_TAG_vector_type)
2094 Buffer.setTag(DW_TAG_array_type);
2098 std::vector<DebugInfoDesc *> &Elements = CompTy->getElements();
2101 case DW_TAG_vector_type:
2102 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
2104 case DW_TAG_array_type: {
2105 // Add element type.
2106 if (TypeDesc *FromTy = CompTy->getFromType())
2107 AddType(&Buffer, FromTy, Unit);
2109 // Don't emit size attribute.
2112 // Construct an anonymous type for index type.
2113 DIE Buffer(DW_TAG_base_type);
2114 AddUInt(&Buffer, DW_AT_byte_size, 0, sizeof(int32_t));
2115 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
2116 DIE *IndexTy = Unit->AddDie(Buffer);
2118 // Add subranges to array type.
2119 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
2120 SubrangeDesc *SRD = cast<SubrangeDesc>(Elements[i]);
2121 int64_t Lo = SRD->getLo();
2122 int64_t Hi = SRD->getHi();
2123 DIE *Subrange = new DIE(DW_TAG_subrange_type);
2125 // If a range is available.
2127 AddDIEntry(Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
2128 // Only add low if non-zero.
2129 if (Lo) AddSInt(Subrange, DW_AT_lower_bound, 0, Lo);
2130 AddSInt(Subrange, DW_AT_upper_bound, 0, Hi);
2133 Buffer.AddChild(Subrange);
2137 case DW_TAG_structure_type:
2138 case DW_TAG_union_type: {
2139 // Add elements to structure type.
2140 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
2141 DebugInfoDesc *Element = Elements[i];
2143 if (DerivedTypeDesc *MemberDesc = dyn_cast<DerivedTypeDesc>(Element)){
2144 // Add field or base class.
2145 unsigned Tag = MemberDesc->getTag();
2147 // Extract the basic information.
2148 const std::string &Name = MemberDesc->getName();
2149 uint64_t Size = MemberDesc->getSize();
2150 uint64_t Align = MemberDesc->getAlign();
2151 uint64_t Offset = MemberDesc->getOffset();
2153 // Construct member debug information entry.
2154 DIE *Member = new DIE(Tag);
2156 // Add name if not "".
2158 AddString(Member, DW_AT_name, DW_FORM_string, Name);
2160 // Add location if available.
2161 AddSourceLine(Member, MemberDesc->getFile(), MemberDesc->getLine());
2163 // Most of the time the field info is the same as the members.
2164 uint64_t FieldSize = Size;
2165 uint64_t FieldAlign = Align;
2166 uint64_t FieldOffset = Offset;
2168 // Set the member type.
2169 TypeDesc *FromTy = MemberDesc->getFromType();
2170 AddType(Member, FromTy, Unit);
2172 // Walk up typedefs until a real size is found.
2174 if (FromTy->getTag() != DW_TAG_typedef) {
2175 FieldSize = FromTy->getSize();
2176 FieldAlign = FromTy->getAlign();
2180 FromTy = cast<DerivedTypeDesc>(FromTy)->getFromType();
2183 // Unless we have a bit field.
2184 if (Tag == DW_TAG_member && FieldSize != Size) {
2185 // Construct the alignment mask.
2186 uint64_t AlignMask = ~(FieldAlign - 1);
2187 // Determine the high bit + 1 of the declared size.
2188 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
2189 // Work backwards to determine the base offset of the field.
2190 FieldOffset = HiMark - FieldSize;
2191 // Now normalize offset to the field.
2192 Offset -= FieldOffset;
2194 // Maybe we need to work from the other end.
2195 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
2197 // Add size and offset.
2198 AddUInt(Member, DW_AT_byte_size, 0, FieldSize >> 3);
2199 AddUInt(Member, DW_AT_bit_size, 0, Size);
2200 AddUInt(Member, DW_AT_bit_offset, 0, Offset);
2203 // Add computation for offset.
2204 DIEBlock *Block = new DIEBlock();
2205 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
2206 AddUInt(Block, 0, DW_FORM_udata, FieldOffset >> 3);
2207 AddBlock(Member, DW_AT_data_member_location, 0, Block);
2209 // Add accessibility (public default unless is base class.
2210 if (MemberDesc->isProtected()) {
2211 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_protected);
2212 } else if (MemberDesc->isPrivate()) {
2213 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_private);
2214 } else if (Tag == DW_TAG_inheritance) {
2215 AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_public);
2218 Buffer.AddChild(Member);
2219 } else if (GlobalVariableDesc *StaticDesc =
2220 dyn_cast<GlobalVariableDesc>(Element)) {
2221 // Add static member.
2223 // Construct member debug information entry.
2224 DIE *Static = new DIE(DW_TAG_variable);
2226 // Add name and mangled name.
2227 const std::string &Name = StaticDesc->getName();
2228 const std::string &LinkageName = StaticDesc->getLinkageName();
2229 AddString(Static, DW_AT_name, DW_FORM_string, Name);
2230 if (!LinkageName.empty()) {
2231 AddString(Static, DW_AT_MIPS_linkage_name, DW_FORM_string,
2236 AddSourceLine(Static, StaticDesc->getFile(), StaticDesc->getLine());
2239 if (TypeDesc *StaticTy = StaticDesc->getType())
2240 AddType(Static, StaticTy, Unit);
2243 if (!StaticDesc->isStatic())
2244 AddUInt(Static, DW_AT_external, DW_FORM_flag, 1);
2245 AddUInt(Static, DW_AT_declaration, DW_FORM_flag, 1);
2247 Buffer.AddChild(Static);
2248 } else if (SubprogramDesc *MethodDesc =
2249 dyn_cast<SubprogramDesc>(Element)) {
2250 // Add member function.
2252 // Construct member debug information entry.
2253 DIE *Method = new DIE(DW_TAG_subprogram);
2255 // Add name and mangled name.
2256 const std::string &Name = MethodDesc->getName();
2257 const std::string &LinkageName = MethodDesc->getLinkageName();
2259 AddString(Method, DW_AT_name, DW_FORM_string, Name);
2260 bool IsCTor = TyDesc->getName() == Name;
2262 if (!LinkageName.empty()) {
2263 AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string,
2268 AddSourceLine(Method, MethodDesc->getFile(), MethodDesc->getLine());
2271 if (CompositeTypeDesc *MethodTy =
2272 dyn_cast_or_null<CompositeTypeDesc>(MethodDesc->getType())) {
2273 // Get argument information.
2274 std::vector<DebugInfoDesc *> &Args = MethodTy->getElements();
2279 AddType(Method, dyn_cast<TypeDesc>(Args[0]), Unit);
2283 for (unsigned i = 1, N = Args.size(); i < N; ++i) {
2284 DIE *Arg = new DIE(DW_TAG_formal_parameter);
2285 AddType(Arg, cast<TypeDesc>(Args[i]), Unit);
2286 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1);
2287 Method->AddChild(Arg);
2292 if (!MethodDesc->isStatic())
2293 AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);
2294 AddUInt(Method, DW_AT_declaration, DW_FORM_flag, 1);
2296 Buffer.AddChild(Method);
2301 case DW_TAG_enumeration_type: {
2302 // Add enumerators to enumeration type.
2303 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
2304 EnumeratorDesc *ED = cast<EnumeratorDesc>(Elements[i]);
2305 const std::string &Name = ED->getName();
2306 int64_t Value = ED->getValue();
2307 DIE *Enumerator = new DIE(DW_TAG_enumerator);
2308 AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
2309 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
2310 Buffer.AddChild(Enumerator);
2315 case DW_TAG_subroutine_type: {
2316 // Add prototype flag.
2317 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
2319 AddType(&Buffer, dyn_cast<TypeDesc>(Elements[0]), Unit);
2322 for (unsigned i = 1, N = Elements.size(); i < N; ++i) {
2323 DIE *Arg = new DIE(DW_TAG_formal_parameter);
2324 AddType(Arg, cast<TypeDesc>(Elements[i]), Unit);
2325 Buffer.AddChild(Arg);
2334 // Add name if not anonymous or intermediate type.
2335 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
2337 // Add size if non-zero (derived types might be zero-sized.)
2339 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
2340 else if (isa<CompositeTypeDesc>(TyDesc)) {
2341 // If TyDesc is a composite type, then add size even if it's zero unless
2342 // it's a forward declaration.
2343 if (TyDesc->isForwardDecl())
2344 AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
2346 AddUInt(&Buffer, DW_AT_byte_size, 0, 0);
2349 // Add source line info if available and TyDesc is not a forward
2351 if (!TyDesc->isForwardDecl())
2352 AddSourceLine(&Buffer, TyDesc->getFile(), TyDesc->getLine());
2355 /// NewCompileUnit - Create new compile unit and it's debug information entry.
2357 CompileUnit *NewCompileUnit(CompileUnitDesc *UnitDesc, unsigned ID) {
2358 // Construct debug information entry.
2359 DIE *Die = new DIE(DW_TAG_compile_unit);
2360 AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
2361 DWLabel("section_line", 0), DWLabel("section_line", 0), false);
2362 AddString(Die, DW_AT_producer, DW_FORM_string, UnitDesc->getProducer());
2363 AddUInt (Die, DW_AT_language, DW_FORM_data1, UnitDesc->getLanguage());
2364 AddString(Die, DW_AT_name, DW_FORM_string, UnitDesc->getFileName());
2365 if (!UnitDesc->getDirectory().empty())
2366 AddString(Die, DW_AT_comp_dir, DW_FORM_string, UnitDesc->getDirectory());
2368 // Construct compile unit.
2369 CompileUnit *Unit = new CompileUnit(UnitDesc, ID, Die);
2371 // Add Unit to compile unit map.
2372 DescToUnitMap[UnitDesc] = Unit;
2377 /// GetBaseCompileUnit - Get the main compile unit.
2379 CompileUnit *GetBaseCompileUnit() const {
2380 CompileUnit *Unit = CompileUnits[0];
2381 assert(Unit && "Missing compile unit.");
2385 /// FindCompileUnit - Get the compile unit for the given descriptor.
2387 CompileUnit *FindCompileUnit(CompileUnitDesc *UnitDesc) {
2388 CompileUnit *Unit = DescToUnitMap[UnitDesc];
2389 assert(Unit && "Missing compile unit.");
2393 /// FindCompileUnit - Get the compile unit for the given descriptor.
2395 CompileUnit *FindCompileUnit(DICompileUnit Unit) {
2396 CompileUnit *DW_Unit = DW_CUs[Unit.getGV()];
2397 assert(DW_Unit && "Missing compile unit.");
2401 /// NewGlobalVariable - Add a new global variable DIE.
2403 DIE *NewGlobalVariable(GlobalVariableDesc *GVD) {
2404 // Get the compile unit context.
2405 CompileUnitDesc *UnitDesc =
2406 static_cast<CompileUnitDesc *>(GVD->getContext());
2407 CompileUnit *Unit = GetBaseCompileUnit();
2409 // Check for pre-existence.
2410 DIE *&Slot = Unit->getDieMapSlotFor(GVD);
2411 if (Slot) return Slot;
2413 // Get the global variable itself.
2414 GlobalVariable *GV = GVD->getGlobalVariable();
2416 const std::string &Name = GVD->getName();
2417 const std::string &FullName = GVD->getFullName();
2418 const std::string &LinkageName = GVD->getLinkageName();
2419 // Create the global's variable DIE.
2420 DIE *VariableDie = new DIE(DW_TAG_variable);
2421 AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
2422 if (!LinkageName.empty()) {
2423 AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
2426 AddType(VariableDie, GVD->getType(), Unit);
2427 if (!GVD->isStatic())
2428 AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
2430 // Add source line info if available.
2431 AddSourceLine(VariableDie, UnitDesc, GVD->getLine());
2434 DIEBlock *Block = new DIEBlock();
2435 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
2436 AddObjectLabel(Block, 0, DW_FORM_udata, Asm->getGlobalLinkName(GV));
2437 AddBlock(VariableDie, DW_AT_location, 0, Block);
2442 // Add to context owner.
2443 Unit->getDie()->AddChild(VariableDie);
2445 // Expose as global.
2446 // FIXME - need to check external flag.
2447 Unit->AddGlobal(FullName, VariableDie);
2452 /// NewSubprogram - Add a new subprogram DIE.
2454 DIE *NewSubprogram(SubprogramDesc *SPD) {
2455 // Get the compile unit context.
2456 CompileUnitDesc *UnitDesc =
2457 static_cast<CompileUnitDesc *>(SPD->getContext());
2458 CompileUnit *Unit = GetBaseCompileUnit();
2460 // Check for pre-existence.
2461 DIE *&Slot = Unit->getDieMapSlotFor(SPD);
2462 if (Slot) return Slot;
2464 // Gather the details (simplify add attribute code.)
2465 const std::string &Name = SPD->getName();
2466 const std::string &FullName = SPD->getFullName();
2467 const std::string &LinkageName = SPD->getLinkageName();
2469 DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
2470 AddString(SubprogramDie, DW_AT_name, DW_FORM_string, Name);
2471 if (!LinkageName.empty()) {
2472 AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
2475 if (SPD->getType()) AddType(SubprogramDie, SPD->getType(), Unit);
2476 if (!SPD->isStatic())
2477 AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
2478 AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
2480 // Add source line info if available.
2481 AddSourceLine(SubprogramDie, UnitDesc, SPD->getLine());
2484 Slot = SubprogramDie;
2486 // Add to context owner.
2487 Unit->getDie()->AddChild(SubprogramDie);
2489 // Expose as global.
2490 Unit->AddGlobal(FullName, SubprogramDie);
2492 return SubprogramDie;
2495 /// NewScopeVariable - Create a new scope variable.
2497 DIE *NewScopeVariable(DebugVariable *DV, CompileUnit *Unit) {
2498 // Get the descriptor.
2499 VariableDesc *VD = DV->getDesc();
2501 // Translate tag to proper Dwarf tag. The result variable is dropped for
2504 switch (VD->getTag()) {
2505 case DW_TAG_return_variable: return NULL;
2506 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
2507 case DW_TAG_auto_variable: // fall thru
2508 default: Tag = DW_TAG_variable; break;
2511 // Define variable debug information entry.
2512 DIE *VariableDie = new DIE(Tag);
2513 AddString(VariableDie, DW_AT_name, DW_FORM_string, VD->getName());
2515 // Add source line info if available.
2516 AddSourceLine(VariableDie, VD->getFile(), VD->getLine());
2518 // Add variable type.
2519 AddType(VariableDie, VD->getType(), Unit);
2521 // Add variable address.
2522 MachineLocation Location;
2523 Location.set(RI->getFrameRegister(*MF),
2524 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
2525 AddAddress(VariableDie, DW_AT_location, Location);
2530 /// NewScopeVariable - Create a new scope variable.
2532 DIE *NewDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
2533 // Get the descriptor.
2534 DIVariable *VD = DV->getVariable();
2536 // Translate tag to proper Dwarf tag. The result variable is dropped for
2539 switch (VD->getTag()) {
2540 case DW_TAG_return_variable: return NULL;
2541 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
2542 case DW_TAG_auto_variable: // fall thru
2543 default: Tag = DW_TAG_variable; break;
2546 // Define variable debug information entry.
2547 DIE *VariableDie = new DIE(Tag);
2548 AddString(VariableDie, DW_AT_name, DW_FORM_string, VD->getName());
2550 // Add source line info if available.
2551 AddSourceLine(VariableDie, VD);
2553 // Add variable type.
2554 AddType(Unit, VariableDie, VD->getType());
2556 // Add variable address.
2557 MachineLocation Location;
2558 Location.set(RI->getFrameRegister(*MF),
2559 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
2560 AddAddress(VariableDie, DW_AT_location, Location);
2565 unsigned RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
2566 CompileUnit *Unit = DW_CUs[V];
2567 assert (Unit && "Unable to find CompileUnit");
2568 unsigned ID = NextLabelID();
2569 Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
2573 unsigned getRecordSourceLineCount() {
2574 return Lines.size();
2577 unsigned RecordSource(const std::string &Directory,
2578 const std::string &File) {
2579 unsigned DID = Directories.insert(Directory);
2580 return SrcFiles.insert(SrcFileInfo(DID,File));
2583 /// RecordRegionStart - Indicate the start of a region.
2585 unsigned RecordRegionStart(GlobalVariable *V) {
2586 DbgScope *Scope = getOrCreateScope(V);
2587 unsigned ID = NextLabelID();
2588 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
2592 /// RecordRegionEnd - Indicate the end of a region.
2594 unsigned RecordRegionEnd(GlobalVariable *V) {
2595 DbgScope *Scope = getOrCreateScope(V);
2596 unsigned ID = NextLabelID();
2597 Scope->setEndLabelID(ID);
2601 /// RecordVariable - Indicate the declaration of a local variable.
2603 void RecordVariable(GlobalVariable *GV, unsigned FrameIndex) {
2604 DbgScope *Scope = getOrCreateScope(GV);
2605 DIVariable *VD = new DIVariable(GV);
2606 DbgVariable *DV = new DbgVariable(VD, FrameIndex);
2607 Scope->AddVariable(DV);
2610 /// getOrCreateScope - Returns the scope associated with the given descriptor.
2612 DbgScope *getOrCreateScope(GlobalVariable *V) {
2613 DbgScope *&Slot = DbgScopeMap[V];
2615 // FIXME - breaks down when the context is an inlined function.
2616 DIDescriptor ParentDesc;
2617 DIBlock *DB = new DIBlock(V);
2618 if (DIBlock *Block = dyn_cast<DIBlock>(DB)) {
2619 ParentDesc = Block->getContext();
2621 DbgScope *Parent = ParentDesc.isNull() ?
2622 getOrCreateScope(ParentDesc.getGV()) : NULL;
2623 Slot = new DbgScope(Parent, DB);
2625 Parent->AddScope(Slot);
2626 } else if (RootDbgScope) {
2627 // FIXME - Add inlined function scopes to the root so we can delete
2628 // them later. Long term, handle inlined functions properly.
2629 RootDbgScope->AddScope(Slot);
2631 // First function is top level function.
2632 RootDbgScope = Slot;
2638 /// ConstructDbgScope - Construct the components of a scope.
2640 void ConstructDbgScope(DbgScope *ParentScope,
2641 unsigned ParentStartID, unsigned ParentEndID,
2642 DIE *ParentDie, CompileUnit *Unit) {
2643 // Add variables to scope.
2644 SmallVector<DbgVariable *, 32> &Variables = ParentScope->getVariables();
2645 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2646 DIE *VariableDie = NewDbgScopeVariable(Variables[i], Unit);
2647 if (VariableDie) ParentDie->AddChild(VariableDie);
2650 // Add nested scopes.
2651 SmallVector<DbgScope *, 8> &Scopes = ParentScope->getScopes();
2652 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
2653 // Define the Scope debug information entry.
2654 DbgScope *Scope = Scopes[j];
2655 // FIXME - Ignore inlined functions for the time being.
2656 if (!Scope->getParent()) continue;
2658 unsigned StartID = MappedLabel(Scope->getStartLabelID());
2659 unsigned EndID = MappedLabel(Scope->getEndLabelID());
2661 // Ignore empty scopes.
2662 if (StartID == EndID && StartID != 0) continue;
2663 if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
2665 if (StartID == ParentStartID && EndID == ParentEndID) {
2666 // Just add stuff to the parent scope.
2667 ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
2669 DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
2671 // Add the scope bounds.
2673 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2674 DWLabel("label", StartID));
2676 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2677 DWLabel("func_begin", SubprogramCount));
2680 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2681 DWLabel("label", EndID));
2683 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2684 DWLabel("func_end", SubprogramCount));
2687 // Add the scope contents.
2688 ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
2689 ParentDie->AddChild(ScopeDie);
2694 /// ConstructRootDbgScope - Construct the scope for the subprogram.
2696 void ConstructRootDbgScope(DbgScope *RootScope) {
2697 // Exit if there is no root scope.
2698 if (!RootScope) return;
2700 // Get the subprogram debug information entry.
2701 DISubprogram *SPD = cast<DISubprogram>(RootScope->getDesc());
2703 // Get the compile unit context.
2704 CompileUnit *Unit = FindCompileUnit(SPD->getCompileUnit());
2706 // Get the subprogram die.
2707 DIE *SPDie = Unit->getDieMapSlotFor(SPD->getGV());
2708 assert(SPDie && "Missing subprogram descriptor");
2710 // Add the function bounds.
2711 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2712 DWLabel("func_begin", SubprogramCount));
2713 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2714 DWLabel("func_end", SubprogramCount));
2715 MachineLocation Location(RI->getFrameRegister(*MF));
2716 AddAddress(SPDie, DW_AT_frame_base, Location);
2718 ConstructDbgScope(RootScope, 0, 0, SPDie, Unit);
2721 /// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
2723 void ConstructDefaultDbgScope(MachineFunction *MF) {
2724 // Find the correct subprogram descriptor.
2725 std::string SPName = "llvm.dbg.subprograms";
2726 std::vector<GlobalVariable*> Result;
2727 getGlobalVariablesUsing(*M, SPName, Result);
2728 for (std::vector<GlobalVariable *>::iterator I = Result.begin(),
2729 E = Result.end(); I != E; ++I) {
2731 DISubprogram *SPD = new DISubprogram(*I);
2733 if (SPD->getName() == MF->getFunction()->getName()) {
2734 // Get the compile unit context.
2735 CompileUnit *Unit = FindCompileUnit(SPD->getCompileUnit());
2737 // Get the subprogram die.
2738 DIE *SPDie = Unit->getDieMapSlotFor(SPD->getGV());
2739 assert(SPDie && "Missing subprogram descriptor");
2741 // Add the function bounds.
2742 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2743 DWLabel("func_begin", SubprogramCount));
2744 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2745 DWLabel("func_end", SubprogramCount));
2747 MachineLocation Location(RI->getFrameRegister(*MF));
2748 AddAddress(SPDie, DW_AT_frame_base, Location);
2753 // FIXME: This is causing an abort because C++ mangled names are compared
2754 // with their unmangled counterparts. See PR2885. Don't do this assert.
2755 assert(0 && "Couldn't find DIE for machine function!");
2759 /// ConstructScope - Construct the components of a scope.
2761 void ConstructScope(DebugScope *ParentScope,
2762 unsigned ParentStartID, unsigned ParentEndID,
2763 DIE *ParentDie, CompileUnit *Unit) {
2764 // Add variables to scope.
2765 std::vector<DebugVariable *> &Variables = ParentScope->getVariables();
2766 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2767 DIE *VariableDie = NewScopeVariable(Variables[i], Unit);
2768 if (VariableDie) ParentDie->AddChild(VariableDie);
2771 // Add nested scopes.
2772 std::vector<DebugScope *> &Scopes = ParentScope->getScopes();
2773 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
2774 // Define the Scope debug information entry.
2775 DebugScope *Scope = Scopes[j];
2776 // FIXME - Ignore inlined functions for the time being.
2777 if (!Scope->getParent()) continue;
2779 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
2780 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
2782 // Ignore empty scopes.
2783 if (StartID == EndID && StartID != 0) continue;
2784 if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
2786 if (StartID == ParentStartID && EndID == ParentEndID) {
2787 // Just add stuff to the parent scope.
2788 ConstructScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
2790 DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
2792 // Add the scope bounds.
2794 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2795 DWLabel("label", StartID));
2797 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2798 DWLabel("func_begin", SubprogramCount));
2801 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2802 DWLabel("label", EndID));
2804 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2805 DWLabel("func_end", SubprogramCount));
2808 // Add the scope contents.
2809 ConstructScope(Scope, StartID, EndID, ScopeDie, Unit);
2810 ParentDie->AddChild(ScopeDie);
2815 /// ConstructRootScope - Construct the scope for the subprogram.
2817 void ConstructRootScope(DebugScope *RootScope) {
2818 // Exit if there is no root scope.
2819 if (!RootScope) return;
2821 // Get the subprogram debug information entry.
2822 SubprogramDesc *SPD = cast<SubprogramDesc>(RootScope->getDesc());
2824 // Get the compile unit context.
2825 CompileUnit *Unit = GetBaseCompileUnit();
2827 // Get the subprogram die.
2828 DIE *SPDie = Unit->getDieMapSlotFor(SPD);
2829 assert(SPDie && "Missing subprogram descriptor");
2831 // Add the function bounds.
2832 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2833 DWLabel("func_begin", SubprogramCount));
2834 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2835 DWLabel("func_end", SubprogramCount));
2836 MachineLocation Location(RI->getFrameRegister(*MF));
2837 AddAddress(SPDie, DW_AT_frame_base, Location);
2839 ConstructScope(RootScope, 0, 0, SPDie, Unit);
2842 /// ConstructDefaultScope - Construct a default scope for the subprogram.
2844 void ConstructDefaultScope(MachineFunction *MF) {
2845 // Find the correct subprogram descriptor.
2846 std::vector<SubprogramDesc *> Subprograms;
2847 MMI->getAnchoredDescriptors<SubprogramDesc>(*M, Subprograms);
2849 for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
2850 SubprogramDesc *SPD = Subprograms[i];
2852 if (SPD->getName() == MF->getFunction()->getName()) {
2853 // Get the compile unit context.
2854 CompileUnit *Unit = GetBaseCompileUnit();
2856 // Get the subprogram die.
2857 DIE *SPDie = Unit->getDieMapSlotFor(SPD);
2858 assert(SPDie && "Missing subprogram descriptor");
2860 // Add the function bounds.
2861 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2862 DWLabel("func_begin", SubprogramCount));
2863 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2864 DWLabel("func_end", SubprogramCount));
2866 MachineLocation Location(RI->getFrameRegister(*MF));
2867 AddAddress(SPDie, DW_AT_frame_base, Location);
2872 // FIXME: This is causing an abort because C++ mangled names are compared
2873 // with their unmangled counterparts. See PR2885. Don't do this assert.
2874 assert(0 && "Couldn't find DIE for machine function!");
2878 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
2879 /// tools to recognize the object file contains Dwarf information.
2880 void EmitInitial() {
2881 // Check to see if we already emitted intial headers.
2882 if (didInitial) return;
2885 // Dwarf sections base addresses.
2886 if (TAI->doesDwarfRequireFrameSection()) {
2887 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2888 EmitLabel("section_debug_frame", 0);
2890 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2891 EmitLabel("section_info", 0);
2892 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2893 EmitLabel("section_abbrev", 0);
2894 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2895 EmitLabel("section_aranges", 0);
2896 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2897 EmitLabel("section_macinfo", 0);
2898 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2899 EmitLabel("section_line", 0);
2900 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2901 EmitLabel("section_loc", 0);
2902 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2903 EmitLabel("section_pubnames", 0);
2904 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2905 EmitLabel("section_str", 0);
2906 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2907 EmitLabel("section_ranges", 0);
2909 Asm->SwitchToSection(TAI->getTextSection());
2910 EmitLabel("text_begin", 0);
2911 Asm->SwitchToSection(TAI->getDataSection());
2912 EmitLabel("data_begin", 0);
2915 /// EmitDIE - Recusively Emits a debug information entry.
2917 void EmitDIE(DIE *Die) {
2918 // Get the abbreviation for this DIE.
2919 unsigned AbbrevNumber = Die->getAbbrevNumber();
2920 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2924 // Emit the code (index) for the abbreviation.
2925 Asm->EmitULEB128Bytes(AbbrevNumber);
2928 Asm->EOL(std::string("Abbrev [" +
2929 utostr(AbbrevNumber) +
2930 "] 0x" + utohexstr(Die->getOffset()) +
2931 ":0x" + utohexstr(Die->getSize()) + " " +
2932 TagString(Abbrev->getTag())));
2936 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2937 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2939 // Emit the DIE attribute values.
2940 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2941 unsigned Attr = AbbrevData[i].getAttribute();
2942 unsigned Form = AbbrevData[i].getForm();
2943 assert(Form && "Too many attributes for DIE (check abbreviation)");
2946 case DW_AT_sibling: {
2947 Asm->EmitInt32(Die->SiblingOffset());
2951 // Emit an attribute using the defined form.
2952 Values[i]->EmitValue(*this, Form);
2957 Asm->EOL(AttributeString(Attr));
2960 // Emit the DIE children if any.
2961 if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2962 const std::vector<DIE *> &Children = Die->getChildren();
2964 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2965 EmitDIE(Children[j]);
2968 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2972 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2974 unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2975 // Get the children.
2976 const std::vector<DIE *> &Children = Die->getChildren();
2978 // If not last sibling and has children then add sibling offset attribute.
2979 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2981 // Record the abbreviation.
2982 AssignAbbrevNumber(Die->getAbbrev());
2984 // Get the abbreviation for this DIE.
2985 unsigned AbbrevNumber = Die->getAbbrevNumber();
2986 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2989 Die->setOffset(Offset);
2991 // Start the size with the size of abbreviation code.
2992 Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
2994 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2995 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2997 // Size the DIE attribute values.
2998 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2999 // Size attribute value.
3000 Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
3003 // Size the DIE children if any.
3004 if (!Children.empty()) {
3005 assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
3006 "Children flag not set");
3008 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
3009 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
3012 // End of children marker.
3013 Offset += sizeof(int8_t);
3016 Die->setSize(Offset - Die->getOffset());
3020 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
3022 void SizeAndOffsets() {
3023 // Process base compile unit.
3024 CompileUnit *Unit = GetBaseCompileUnit();
3025 // Compute size of compile unit header
3026 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
3027 sizeof(int16_t) + // DWARF version number
3028 sizeof(int32_t) + // Offset Into Abbrev. Section
3029 sizeof(int8_t); // Pointer Size (in bytes)
3030 SizeAndOffsetDie(Unit->getDie(), Offset, true);
3033 /// EmitDebugInfo - Emit the debug info section.
3035 void EmitDebugInfo() {
3036 // Start debug info section.
3037 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
3039 CompileUnit *Unit = GetBaseCompileUnit();
3040 DIE *Die = Unit->getDie();
3041 // Emit the compile units header.
3042 EmitLabel("info_begin", Unit->getID());
3043 // Emit size of content not including length itself
3044 unsigned ContentSize = Die->getSize() +
3045 sizeof(int16_t) + // DWARF version number
3046 sizeof(int32_t) + // Offset Into Abbrev. Section
3047 sizeof(int8_t) + // Pointer Size (in bytes)
3048 sizeof(int32_t); // FIXME - extra pad for gdb bug.
3050 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
3051 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
3052 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
3053 Asm->EOL("Offset Into Abbrev. Section");
3054 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
3057 // FIXME - extra padding for gdb bug.
3058 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
3059 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
3060 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
3061 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
3062 EmitLabel("info_end", Unit->getID());
3067 /// EmitAbbreviations - Emit the abbreviation section.
3069 void EmitAbbreviations() const {
3070 // Check to see if it is worth the effort.
3071 if (!Abbreviations.empty()) {
3072 // Start the debug abbrev section.
3073 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
3075 EmitLabel("abbrev_begin", 0);
3077 // For each abbrevation.
3078 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
3079 // Get abbreviation data
3080 const DIEAbbrev *Abbrev = Abbreviations[i];
3082 // Emit the abbrevations code (base 1 index.)
3083 Asm->EmitULEB128Bytes(Abbrev->getNumber());
3084 Asm->EOL("Abbreviation Code");
3086 // Emit the abbreviations data.
3087 Abbrev->Emit(*this);
3092 // Mark end of abbreviations.
3093 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
3095 EmitLabel("abbrev_end", 0);
3101 /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
3102 /// the line matrix.
3104 void EmitEndOfLineMatrix(unsigned SectionEnd) {
3105 // Define last address of section.
3106 Asm->EmitInt8(0); Asm->EOL("Extended Op");
3107 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
3108 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
3109 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
3111 // Mark end of matrix.
3112 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
3113 Asm->EmitULEB128Bytes(1); Asm->EOL();
3114 Asm->EmitInt8(1); Asm->EOL();
3117 /// EmitDebugLines - Emit source line information.
3119 void EmitDebugLines() {
3120 // If the target is using .loc/.file, the assembler will be emitting the
3121 // .debug_line table automatically.
3122 if (TAI->hasDotLocAndDotFile())
3125 // Minimum line delta, thus ranging from -10..(255-10).
3126 const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
3127 // Maximum line delta, thus ranging from -10..(255-10).
3128 const int MaxLineDelta = 255 + MinLineDelta;
3130 // Start the dwarf line section.
3131 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
3133 // Construct the section header.
3135 EmitDifference("line_end", 0, "line_begin", 0, true);
3136 Asm->EOL("Length of Source Line Info");
3137 EmitLabel("line_begin", 0);
3139 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
3141 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
3142 Asm->EOL("Prolog Length");
3143 EmitLabel("line_prolog_begin", 0);
3145 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
3147 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
3149 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
3151 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
3153 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
3155 // Line number standard opcode encodings argument count
3156 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
3157 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
3158 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
3159 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
3160 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
3161 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
3162 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
3163 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
3164 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
3166 const UniqueVector<std::string> &Directories = MMI->getDirectories();
3167 const UniqueVector<SourceFileInfo> &SourceFiles = MMI->getSourceFiles();
3169 // Emit directories.
3170 for (unsigned DirectoryID = 1, NDID = Directories.size();
3171 DirectoryID <= NDID; ++DirectoryID) {
3172 Asm->EmitString(Directories[DirectoryID]); Asm->EOL("Directory");
3174 Asm->EmitInt8(0); Asm->EOL("End of directories");
3177 for (unsigned SourceID = 1, NSID = SourceFiles.size();
3178 SourceID <= NSID; ++SourceID) {
3179 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
3180 Asm->EmitString(SourceFile.getName());
3182 Asm->EmitULEB128Bytes(SourceFile.getDirectoryID());
3183 Asm->EOL("Directory #");
3184 Asm->EmitULEB128Bytes(0);
3185 Asm->EOL("Mod date");
3186 Asm->EmitULEB128Bytes(0);
3187 Asm->EOL("File size");
3189 Asm->EmitInt8(0); Asm->EOL("End of files");
3191 EmitLabel("line_prolog_end", 0);
3193 // A sequence for each text section.
3194 unsigned SecSrcLinesSize = SectionSourceLines.size();
3196 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
3197 // Isolate current sections line info.
3198 const std::vector<SourceLineInfo> &LineInfos = SectionSourceLines[j];
3201 const Section* S = SectionMap[j + 1];
3202 Asm->EOL(std::string("Section ") + S->getName());
3206 // Dwarf assumes we start with first line of first source file.
3207 unsigned Source = 1;
3210 // Construct rows of the address, source, line, column matrix.
3211 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
3212 const SourceLineInfo &LineInfo = LineInfos[i];
3213 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
3214 if (!LabelID) continue;
3216 unsigned SourceID = LineInfo.getSourceID();
3217 const SourceFileInfo &SourceFile = SourceFiles[SourceID];
3218 unsigned DirectoryID = SourceFile.getDirectoryID();
3220 Asm->EOL(Directories[DirectoryID]
3221 + SourceFile.getName()
3223 + utostr_32(LineInfo.getLine()));
3227 // Define the line address.
3228 Asm->EmitInt8(0); Asm->EOL("Extended Op");
3229 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
3230 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
3231 EmitReference("label", LabelID); Asm->EOL("Location label");
3233 // If change of source, then switch to the new source.
3234 if (Source != LineInfo.getSourceID()) {
3235 Source = LineInfo.getSourceID();
3236 Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
3237 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
3240 // If change of line.
3241 if (Line != LineInfo.getLine()) {
3242 // Determine offset.
3243 int Offset = LineInfo.getLine() - Line;
3244 int Delta = Offset - MinLineDelta;
3247 Line = LineInfo.getLine();
3249 // If delta is small enough and in range...
3250 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
3251 // ... then use fast opcode.
3252 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
3254 // ... otherwise use long hand.
3255 Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
3256 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
3257 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
3260 // Copy the previous row (different address or source)
3261 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
3265 EmitEndOfLineMatrix(j + 1);
3268 if (SecSrcLinesSize == 0)
3269 // Because we're emitting a debug_line section, we still need a line
3270 // table. The linker and friends expect it to exist. If there's nothing to
3271 // put into it, emit an empty table.
3272 EmitEndOfLineMatrix(1);
3274 EmitLabel("line_end", 0);
3279 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
3281 void EmitCommonDebugFrame() {
3282 if (!TAI->doesDwarfRequireFrameSection())
3286 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3287 TargetFrameInfo::StackGrowsUp ?
3288 TD->getPointerSize() : -TD->getPointerSize();
3290 // Start the dwarf frame section.
3291 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
3293 EmitLabel("debug_frame_common", 0);
3294 EmitDifference("debug_frame_common_end", 0,
3295 "debug_frame_common_begin", 0, true);
3296 Asm->EOL("Length of Common Information Entry");
3298 EmitLabel("debug_frame_common_begin", 0);
3299 Asm->EmitInt32((int)DW_CIE_ID);
3300 Asm->EOL("CIE Identifier Tag");
3301 Asm->EmitInt8(DW_CIE_VERSION);
3302 Asm->EOL("CIE Version");
3303 Asm->EmitString("");
3304 Asm->EOL("CIE Augmentation");
3305 Asm->EmitULEB128Bytes(1);
3306 Asm->EOL("CIE Code Alignment Factor");
3307 Asm->EmitSLEB128Bytes(stackGrowth);
3308 Asm->EOL("CIE Data Alignment Factor");
3309 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
3310 Asm->EOL("CIE RA Column");
3312 std::vector<MachineMove> Moves;
3313 RI->getInitialFrameState(Moves);
3315 EmitFrameMoves(NULL, 0, Moves, false);
3317 Asm->EmitAlignment(2, 0, 0, false);
3318 EmitLabel("debug_frame_common_end", 0);
3323 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
3325 void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
3326 if (!TAI->doesDwarfRequireFrameSection())
3329 // Start the dwarf frame section.
3330 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
3332 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
3333 "debug_frame_begin", DebugFrameInfo.Number, true);
3334 Asm->EOL("Length of Frame Information Entry");
3336 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
3338 EmitSectionOffset("debug_frame_common", "section_debug_frame",
3340 Asm->EOL("FDE CIE offset");
3342 EmitReference("func_begin", DebugFrameInfo.Number);
3343 Asm->EOL("FDE initial location");
3344 EmitDifference("func_end", DebugFrameInfo.Number,
3345 "func_begin", DebugFrameInfo.Number);
3346 Asm->EOL("FDE address range");
3348 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves, false);
3350 Asm->EmitAlignment(2, 0, 0, false);
3351 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
3356 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
3358 void EmitDebugPubNames() {
3359 // Start the dwarf pubnames section.
3360 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
3362 CompileUnit *Unit = GetBaseCompileUnit();
3364 EmitDifference("pubnames_end", Unit->getID(),
3365 "pubnames_begin", Unit->getID(), true);
3366 Asm->EOL("Length of Public Names Info");
3368 EmitLabel("pubnames_begin", Unit->getID());
3370 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
3372 EmitSectionOffset("info_begin", "section_info",
3373 Unit->getID(), 0, true, false);
3374 Asm->EOL("Offset of Compilation Unit Info");
3376 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),true);
3377 Asm->EOL("Compilation Unit Length");
3379 std::map<std::string, DIE *> &Globals = Unit->getGlobals();
3381 for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
3384 const std::string &Name = GI->first;
3385 DIE * Entity = GI->second;
3387 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
3388 Asm->EmitString(Name); Asm->EOL("External Name");
3391 Asm->EmitInt32(0); Asm->EOL("End Mark");
3392 EmitLabel("pubnames_end", Unit->getID());
3397 /// EmitDebugStr - Emit visible names into a debug str section.
3399 void EmitDebugStr() {
3400 // Check to see if it is worth the effort.
3401 if (!StringPool.empty()) {
3402 // Start the dwarf str section.
3403 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
3405 // For each of strings in the string pool.
3406 for (unsigned StringID = 1, N = StringPool.size();
3407 StringID <= N; ++StringID) {
3408 // Emit a label for reference from debug information entries.
3409 EmitLabel("string", StringID);
3410 // Emit the string itself.
3411 const std::string &String = StringPool[StringID];
3412 Asm->EmitString(String); Asm->EOL();
3419 /// EmitDebugLoc - Emit visible names into a debug loc section.
3421 void EmitDebugLoc() {
3422 // Start the dwarf loc section.
3423 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
3428 /// EmitDebugARanges - Emit visible names into a debug aranges section.
3430 void EmitDebugARanges() {
3431 // Start the dwarf aranges section.
3432 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
3436 CompileUnit *Unit = GetBaseCompileUnit();
3438 // Don't include size of length
3439 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
3441 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
3443 EmitReference("info_begin", Unit->getID());
3444 Asm->EOL("Offset of Compilation Unit Info");
3446 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
3448 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
3450 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
3451 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
3454 EmitReference("text_begin", 0); Asm->EOL("Address");
3455 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
3457 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
3458 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
3464 /// EmitDebugRanges - Emit visible names into a debug ranges section.
3466 void EmitDebugRanges() {
3467 // Start the dwarf ranges section.
3468 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
3473 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
3475 void EmitDebugMacInfo() {
3476 // Start the dwarf macinfo section.
3477 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
3482 /// ConstructCompileUnits - Create a compile unit DIEs.
3483 void ConstructCompileUnits() {
3484 std::string CUName = "llvm.dbg.compile_units";
3485 std::vector<GlobalVariable*> Result;
3486 getGlobalVariablesUsing(*M, CUName, Result);
3487 for (std::vector<GlobalVariable *>::iterator RI = Result.begin(),
3488 RE = Result.end(); RI != RE; ++RI) {
3489 DICompileUnit *DIUnit = new DICompileUnit(*RI);
3490 unsigned ID = RecordSource(DIUnit->getDirectory(),
3491 DIUnit->getFilename());
3493 DIE *Die = new DIE(DW_TAG_compile_unit);
3494 AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
3495 DWLabel("section_line", 0), DWLabel("section_line", 0),
3497 AddString(Die, DW_AT_producer, DW_FORM_string, DIUnit->getProducer());
3498 AddUInt(Die, DW_AT_language, DW_FORM_data1, DIUnit->getLanguage());
3499 AddString(Die, DW_AT_name, DW_FORM_string, DIUnit->getFilename());
3500 if (!DIUnit->getDirectory().empty())
3501 AddString(Die, DW_AT_comp_dir, DW_FORM_string, DIUnit->getDirectory());
3503 CompileUnit *Unit = new CompileUnit(ID, Die);
3504 DW_CUs[DIUnit->getGV()] = Unit;
3508 /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
3510 void ConstructCompileUnitDIEs() {
3511 const UniqueVector<CompileUnitDesc *> CUW = MMI->getCompileUnits();
3513 for (unsigned i = 1, N = CUW.size(); i <= N; ++i) {
3514 unsigned ID = MMI->RecordSource(CUW[i]);
3515 CompileUnit *Unit = NewCompileUnit(CUW[i], ID);
3516 CompileUnits.push_back(Unit);
3520 /// ConstructGlobalVariableDIEs - Create DIEs for each of the externally
3521 /// visible global variables.
3522 void ConstructGlobalVariableDIEs() {
3523 std::string GVName = "llvm.dbg.global_variables";
3524 std::vector<GlobalVariable*> Result;
3525 getGlobalVariablesUsing(*M, GVName, Result);
3526 for (std::vector<GlobalVariable *>::iterator GVI = Result.begin(),
3527 GVE = Result.end(); GVI != GVE; ++GVI) {
3528 DIGlobalVariable *DI_GV = new DIGlobalVariable(*GVI);
3529 CompileUnit *DW_Unit = FindCompileUnit(DI_GV->getCompileUnit());
3531 // Check for pre-existence.
3532 DIE *&Slot = DW_Unit->getDieMapSlotFor(DI_GV->getGV());
3535 DIE *VariableDie = new DIE(DW_TAG_variable);
3536 AddString(VariableDie, DW_AT_name, DW_FORM_string, DI_GV->getName());
3537 const std::string &LinkageName = DI_GV->getLinkageName();
3538 if (!LinkageName.empty())
3539 AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
3541 AddType(DW_Unit, VariableDie, DI_GV->getType());
3543 if (!DI_GV->isLocalToUnit())
3544 AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
3546 // Add source line info, if available.
3547 AddSourceLine(VariableDie, DI_GV);
3550 DIEBlock *Block = new DIEBlock();
3551 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
3552 AddObjectLabel(Block, 0, DW_FORM_udata,
3553 Asm->getGlobalLinkName(DI_GV->getGV()));
3554 AddBlock(VariableDie, DW_AT_location, 0, Block);
3559 //Add to context owner.
3560 DW_Unit->getDie()->AddChild(VariableDie);
3562 //Expose as global. FIXME - need to check external flag.
3563 DW_Unit->AddGlobal(DI_GV->getName(), VariableDie);
3567 /// ConstructGlobalDIEs - Create DIEs for each of the externally visible
3568 /// global variables.
3569 void ConstructGlobalDIEs() {
3570 std::vector<GlobalVariableDesc *> GlobalVariables;
3571 MMI->getAnchoredDescriptors<GlobalVariableDesc>(*M, GlobalVariables);
3573 for (unsigned i = 0, N = GlobalVariables.size(); i < N; ++i) {
3574 GlobalVariableDesc *GVD = GlobalVariables[i];
3575 NewGlobalVariable(GVD);
3579 /// ConstructSubprograms - Create DIEs for each of the externally visible
3581 void ConstructSubprograms() {
3583 std::string SPName = "llvm.dbg.subprograms";
3584 std::vector<GlobalVariable*> Result;
3585 getGlobalVariablesUsing(*M, SPName, Result);
3586 for (std::vector<GlobalVariable *>::iterator RI = Result.begin(),
3587 RE = Result.end(); RI != RE; ++RI) {
3589 DISubprogram *SP = new DISubprogram(*RI);
3590 CompileUnit *Unit = FindCompileUnit(SP->getCompileUnit());
3592 // Check for pre-existence.
3593 DIE *&Slot = Unit->getDieMapSlotFor(SP->getGV());
3596 DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
3597 AddString(SubprogramDie, DW_AT_name, DW_FORM_string, SP->getName());
3598 const std::string &LinkageName = SP->getLinkageName();
3599 if (!LinkageName.empty())
3600 AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
3602 DIType SPTy = SP->getType();
3603 AddType(Unit, SubprogramDie, SPTy);
3604 if (!SP->isLocalToUnit())
3605 AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
3606 AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
3608 AddSourceLine(SubprogramDie, SP);
3610 Slot = SubprogramDie;
3611 //Add to context owner.
3612 Unit->getDie()->AddChild(SubprogramDie);
3614 Unit->AddGlobal(SP->getName(), SubprogramDie);
3618 /// ConstructSubprogramDIEs - Create DIEs for each of the externally visible
3620 void ConstructSubprogramDIEs() {
3621 std::vector<SubprogramDesc *> Subprograms;
3622 MMI->getAnchoredDescriptors<SubprogramDesc>(*M, Subprograms);
3624 for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
3625 SubprogramDesc *SPD = Subprograms[i];
3631 //===--------------------------------------------------------------------===//
3632 // Main entry points.
3634 DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3635 : Dwarf(OS, A, T, "dbg")
3637 , AbbreviationsSet(InitAbbreviationsSetSize)
3639 , ValuesSet(InitValuesSetSize)
3644 , SectionSourceLines()
3647 , RootDbgScope(NULL)
3650 virtual ~DwarfDebug() {
3651 for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i)
3652 delete CompileUnits[i];
3653 for (unsigned j = 0, M = Values.size(); j < M; ++j)
3657 /// SetDebugInfo - Create global DIEs and emit initial debug info sections.
3658 /// This is inovked by the target AsmPrinter.
3659 void SetDebugInfo() {
3660 // FIXME - Check if the module has debug info or not.
3661 // Create all the compile unit DIEs.
3662 ConstructCompileUnits();
3664 // Create DIEs for each of the externally visible global variables.
3665 ConstructGlobalVariableDIEs();
3667 // Create DIEs for each of the externally visible subprograms.
3668 ConstructSubprograms();
3670 // Prime section data.
3671 SectionMap.insert(TAI->getTextSection());
3673 // Print out .file directives to specify files for .loc directives. These
3674 // are printed out early so that they precede any .loc directives.
3675 if (TAI->hasDotLocAndDotFile()) {
3676 for (unsigned i = 1, e = SrcFiles.size(); i <= e; ++i) {
3677 sys::Path FullPath(Directories[SrcFiles[i].getDirectoryID()]);
3678 bool AppendOk = FullPath.appendComponent(SrcFiles[i].getName());
3679 assert(AppendOk && "Could not append filename to directory!");
3681 Asm->EmitFile(i, FullPath.toString());
3686 // Emit initial sections
3690 /// SetModuleInfo - Set machine module information when it's known that pass
3691 /// manager has created it. Set by the target AsmPrinter.
3692 void SetModuleInfo(MachineModuleInfo *mmi) {
3693 // Make sure initial declarations are made.
3694 if (!MMI && mmi->hasDebugInfo()) {
3698 // Create all the compile unit DIEs.
3699 ConstructCompileUnitDIEs();
3701 // Create DIEs for each of the externally visible global variables.
3702 ConstructGlobalDIEs();
3704 // Create DIEs for each of the externally visible subprograms.
3705 ConstructSubprogramDIEs();
3707 // Prime section data.
3708 SectionMap.insert(TAI->getTextSection());
3710 // Print out .file directives to specify files for .loc directives. These
3711 // are printed out early so that they precede any .loc directives.
3712 if (TAI->hasDotLocAndDotFile()) {
3713 const UniqueVector<SourceFileInfo> &SourceFiles = MMI->getSourceFiles();
3714 const UniqueVector<std::string> &Directories = MMI->getDirectories();
3715 for (unsigned i = 1, e = SourceFiles.size(); i <= e; ++i) {
3716 sys::Path FullPath(Directories[SourceFiles[i].getDirectoryID()]);
3717 bool AppendOk = FullPath.appendComponent(SourceFiles[i].getName());
3718 assert(AppendOk && "Could not append filename to directory!");
3720 Asm->EmitFile(i, FullPath.toString());
3725 // Emit initial sections
3730 /// BeginModule - Emit all Dwarf sections that should come prior to the
3732 void BeginModule(Module *M) {
3736 /// EndModule - Emit all Dwarf sections that should come after the content.
3739 if (!ShouldEmitDwarf()) return;
3741 // Standard sections final addresses.
3742 Asm->SwitchToSection(TAI->getTextSection());
3743 EmitLabel("text_end", 0);
3744 Asm->SwitchToSection(TAI->getDataSection());
3745 EmitLabel("data_end", 0);
3747 // End text sections.
3748 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
3749 Asm->SwitchToSection(SectionMap[i]);
3750 EmitLabel("section_end", i);
3753 // Emit common frame information.
3754 EmitCommonDebugFrame();
3756 // Emit function debug frame information
3757 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
3758 E = DebugFrames.end(); I != E; ++I)
3759 EmitFunctionDebugFrame(*I);
3761 // Compute DIE offsets and sizes.
3764 // Emit all the DIEs into a debug info section
3767 // Corresponding abbreviations into a abbrev section.
3768 EmitAbbreviations();
3770 // Emit source line correspondence into a debug line section.
3773 // Emit info into a debug pubnames section.
3774 EmitDebugPubNames();
3776 // Emit info into a debug str section.
3779 // Emit info into a debug loc section.
3782 // Emit info into a debug aranges section.
3785 // Emit info into a debug ranges section.
3788 // Emit info into a debug macinfo section.
3792 /// BeginFunction - Gather pre-function debug information. Assumes being
3793 /// emitted immediately after the function entry point.
3794 void BeginFunction(MachineFunction *MF) {
3797 if (!ShouldEmitDwarf()) return;
3799 // Begin accumulating function debug information.
3800 MMI->BeginFunction(MF);
3802 // Assumes in correct section after the entry point.
3803 EmitLabel("func_begin", ++SubprogramCount);
3805 // Emit label for the implicitly defined dbg.stoppoint at the start of
3807 const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
3808 if (!LineInfos.empty()) {
3809 const SourceLineInfo &LineInfo = LineInfos[0];
3810 Asm->printLabel(LineInfo.getLabelID());
3814 /// EndFunction - Gather and emit post-function debug information.
3816 void EndFunction(MachineFunction *MF) {
3817 if (!ShouldEmitDwarf()) return;
3819 // Define end label for subprogram.
3820 EmitLabel("func_end", SubprogramCount);
3822 // Get function line info.
3823 const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
3825 if (!LineInfos.empty()) {
3826 // Get section line info.
3827 unsigned ID = SectionMap.insert(Asm->CurrentSection_);
3828 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
3829 std::vector<SourceLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
3830 // Append the function info to section info.
3831 SectionLineInfos.insert(SectionLineInfos.end(),
3832 LineInfos.begin(), LineInfos.end());
3835 // Construct scopes for subprogram.
3836 if (MMI->getRootScope())
3837 ConstructRootScope(MMI->getRootScope());
3839 // FIXME: This is wrong. We are essentially getting past a problem with
3840 // debug information not being able to handle unreachable blocks that have
3841 // debug information in them. In particular, those unreachable blocks that
3842 // have "region end" info in them. That situation results in the "root
3843 // scope" not being created. If that's the case, then emit a "default"
3844 // scope, i.e., one that encompasses the whole function. This isn't
3845 // desirable. And a better way of handling this (and all of the debugging
3846 // information) needs to be explored.
3847 ConstructDefaultScope(MF);
3849 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
3850 MMI->getFrameMoves()));
3854 //===----------------------------------------------------------------------===//
3855 /// DwarfException - Emits Dwarf exception handling directives.
3857 class DwarfException : public Dwarf {
3860 struct FunctionEHFrameInfo {
3863 unsigned PersonalityIndex;
3865 bool hasLandingPads;
3866 std::vector<MachineMove> Moves;
3867 const Function * function;
3869 FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
3871 const std::vector<MachineMove> &M,
3873 FnName(FN), Number(Num), PersonalityIndex(P),
3874 hasCalls(hC), hasLandingPads(hL), Moves(M), function (f) { }
3877 std::vector<FunctionEHFrameInfo> EHFrames;
3879 /// shouldEmitTable - Per-function flag to indicate if EH tables should
3881 bool shouldEmitTable;
3883 /// shouldEmitMoves - Per-function flag to indicate if frame moves info
3884 /// should be emitted.
3885 bool shouldEmitMoves;
3887 /// shouldEmitTableModule - Per-module flag to indicate if EH tables
3888 /// should be emitted.
3889 bool shouldEmitTableModule;
3891 /// shouldEmitFrameModule - Per-module flag to indicate if frame moves
3892 /// should be emitted.
3893 bool shouldEmitMovesModule;
3895 /// EmitCommonEHFrame - Emit the common eh unwind frame.
3897 void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
3898 // Size and sign of stack growth.
3900 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3901 TargetFrameInfo::StackGrowsUp ?
3902 TD->getPointerSize() : -TD->getPointerSize();
3904 // Begin eh frame section.
3905 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3907 if (!TAI->doesRequireNonLocalEHFrameLabel())
3908 O << TAI->getEHGlobalPrefix();
3909 O << "EH_frame" << Index << ":\n";
3910 EmitLabel("section_eh_frame", Index);
3912 // Define base labels.
3913 EmitLabel("eh_frame_common", Index);
3915 // Define the eh frame length.
3916 EmitDifference("eh_frame_common_end", Index,
3917 "eh_frame_common_begin", Index, true);
3918 Asm->EOL("Length of Common Information Entry");
3921 EmitLabel("eh_frame_common_begin", Index);
3922 Asm->EmitInt32((int)0);
3923 Asm->EOL("CIE Identifier Tag");
3924 Asm->EmitInt8(DW_CIE_VERSION);
3925 Asm->EOL("CIE Version");
3927 // The personality presence indicates that language specific information
3928 // will show up in the eh frame.
3929 Asm->EmitString(Personality ? "zPLR" : "zR");
3930 Asm->EOL("CIE Augmentation");
3932 // Round out reader.
3933 Asm->EmitULEB128Bytes(1);
3934 Asm->EOL("CIE Code Alignment Factor");
3935 Asm->EmitSLEB128Bytes(stackGrowth);
3936 Asm->EOL("CIE Data Alignment Factor");
3937 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
3938 Asm->EOL("CIE Return Address Column");
3940 // If there is a personality, we need to indicate the functions location.
3942 Asm->EmitULEB128Bytes(7);
3943 Asm->EOL("Augmentation Size");
3945 if (TAI->getNeedsIndirectEncoding()) {
3946 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4 | DW_EH_PE_indirect);
3947 Asm->EOL("Personality (pcrel sdata4 indirect)");
3949 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3950 Asm->EOL("Personality (pcrel sdata4)");
3953 PrintRelDirective(true);
3954 O << TAI->getPersonalityPrefix();
3955 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
3956 O << TAI->getPersonalitySuffix();
3957 if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
3958 O << "-" << TAI->getPCSymbol();
3959 Asm->EOL("Personality");
3961 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3962 Asm->EOL("LSDA Encoding (pcrel sdata4)");
3964 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3965 Asm->EOL("FDE Encoding (pcrel sdata4)");
3967 Asm->EmitULEB128Bytes(1);
3968 Asm->EOL("Augmentation Size");
3970 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3971 Asm->EOL("FDE Encoding (pcrel sdata4)");
3974 // Indicate locations of general callee saved registers in frame.
3975 std::vector<MachineMove> Moves;
3976 RI->getInitialFrameState(Moves);
3977 EmitFrameMoves(NULL, 0, Moves, true);
3979 // On Darwin the linker honors the alignment of eh_frame, which means it
3980 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3981 // you get holes which confuse readers of eh_frame.
3982 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3984 EmitLabel("eh_frame_common_end", Index);
3989 /// EmitEHFrame - Emit function exception frame information.
3991 void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
3992 Function::LinkageTypes linkage = EHFrameInfo.function->getLinkage();
3994 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3996 // Externally visible entry into the functions eh frame info.
3997 // If the corresponding function is static, this should not be
3998 // externally visible.
3999 if (linkage != Function::InternalLinkage) {
4000 if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
4001 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
4004 // If corresponding function is weak definition, this should be too.
4005 if ((linkage == Function::WeakLinkage ||
4006 linkage == Function::LinkOnceLinkage) &&
4007 TAI->getWeakDefDirective())
4008 O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
4010 // If there are no calls then you can't unwind. This may mean we can
4011 // omit the EH Frame, but some environments do not handle weak absolute
4013 // If UnwindTablesMandatory is set we cannot do this optimization; the
4014 // unwind info is to be available for non-EH uses.
4015 if (!EHFrameInfo.hasCalls &&
4016 !UnwindTablesMandatory &&
4017 ((linkage != Function::WeakLinkage &&
4018 linkage != Function::LinkOnceLinkage) ||
4019 !TAI->getWeakDefDirective() ||
4020 TAI->getSupportsWeakOmittedEHFrame()))
4022 O << EHFrameInfo.FnName << " = 0\n";
4023 // This name has no connection to the function, so it might get
4024 // dead-stripped when the function is not, erroneously. Prohibit
4025 // dead-stripping unconditionally.
4026 if (const char *UsedDirective = TAI->getUsedDirective())
4027 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
4029 O << EHFrameInfo.FnName << ":\n";
4032 EmitDifference("eh_frame_end", EHFrameInfo.Number,
4033 "eh_frame_begin", EHFrameInfo.Number, true);
4034 Asm->EOL("Length of Frame Information Entry");
4036 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
4038 if (TAI->doesRequireNonLocalEHFrameLabel()) {
4039 PrintRelDirective(true, true);
4040 PrintLabelName("eh_frame_begin", EHFrameInfo.Number);
4042 if (!TAI->isAbsoluteEHSectionOffsets())
4043 O << "-EH_frame" << EHFrameInfo.PersonalityIndex;
4045 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
4046 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
4050 Asm->EOL("FDE CIE offset");
4052 EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
4053 Asm->EOL("FDE initial location");
4054 EmitDifference("eh_func_end", EHFrameInfo.Number,
4055 "eh_func_begin", EHFrameInfo.Number, true);
4056 Asm->EOL("FDE address range");
4058 // If there is a personality and landing pads then point to the language
4059 // specific data area in the exception table.
4060 if (EHFrameInfo.PersonalityIndex) {
4061 Asm->EmitULEB128Bytes(4);
4062 Asm->EOL("Augmentation size");
4064 if (EHFrameInfo.hasLandingPads)
4065 EmitReference("exception", EHFrameInfo.Number, true, true);
4067 Asm->EmitInt32((int)0);
4068 Asm->EOL("Language Specific Data Area");
4070 Asm->EmitULEB128Bytes(0);
4071 Asm->EOL("Augmentation size");
4074 // Indicate locations of function specific callee saved registers in
4076 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves, true);
4078 // On Darwin the linker honors the alignment of eh_frame, which means it
4079 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
4080 // you get holes which confuse readers of eh_frame.
4081 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
4083 EmitLabel("eh_frame_end", EHFrameInfo.Number);
4085 // If the function is marked used, this table should be also. We cannot
4086 // make the mark unconditional in this case, since retaining the table
4087 // also retains the function in this case, and there is code around
4088 // that depends on unused functions (calling undefined externals) being
4089 // dead-stripped to link correctly. Yes, there really is.
4090 if (MMI->getUsedFunctions().count(EHFrameInfo.function))
4091 if (const char *UsedDirective = TAI->getUsedDirective())
4092 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
4096 /// EmitExceptionTable - Emit landing pads and actions.
4098 /// The general organization of the table is complex, but the basic concepts
4099 /// are easy. First there is a header which describes the location and
4100 /// organization of the three components that follow.
4101 /// 1. The landing pad site information describes the range of code covered
4102 /// by the try. In our case it's an accumulation of the ranges covered
4103 /// by the invokes in the try. There is also a reference to the landing
4104 /// pad that handles the exception once processed. Finally an index into
4105 /// the actions table.
4106 /// 2. The action table, in our case, is composed of pairs of type ids
4107 /// and next action offset. Starting with the action index from the
4108 /// landing pad site, each type Id is checked for a match to the current
4109 /// exception. If it matches then the exception and type id are passed
4110 /// on to the landing pad. Otherwise the next action is looked up. This
4111 /// chain is terminated with a next action of zero. If no type id is
4112 /// found the the frame is unwound and handling continues.
4113 /// 3. Type id table contains references to all the C++ typeinfo for all
4114 /// catches in the function. This tables is reversed indexed base 1.
4116 /// SharedTypeIds - How many leading type ids two landing pads have in common.
4117 static unsigned SharedTypeIds(const LandingPadInfo *L,
4118 const LandingPadInfo *R) {
4119 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
4120 unsigned LSize = LIds.size(), RSize = RIds.size();
4121 unsigned MinSize = LSize < RSize ? LSize : RSize;
4124 for (; Count != MinSize; ++Count)
4125 if (LIds[Count] != RIds[Count])
4131 /// PadLT - Order landing pads lexicographically by type id.
4132 static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
4133 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
4134 unsigned LSize = LIds.size(), RSize = RIds.size();
4135 unsigned MinSize = LSize < RSize ? LSize : RSize;
4137 for (unsigned i = 0; i != MinSize; ++i)
4138 if (LIds[i] != RIds[i])
4139 return LIds[i] < RIds[i];
4141 return LSize < RSize;
4145 static inline unsigned getEmptyKey() { return -1U; }
4146 static inline unsigned getTombstoneKey() { return -2U; }
4147 static unsigned getHashValue(const unsigned &Key) { return Key; }
4148 static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
4149 static bool isPod() { return true; }
4152 /// ActionEntry - Structure describing an entry in the actions table.
4153 struct ActionEntry {
4154 int ValueForTypeID; // The value to write - may not be equal to the type id.
4156 struct ActionEntry *Previous;
4159 /// PadRange - Structure holding a try-range and the associated landing pad.
4161 // The index of the landing pad.
4163 // The index of the begin and end labels in the landing pad's label lists.
4164 unsigned RangeIndex;
4167 typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
4169 /// CallSiteEntry - Structure describing an entry in the call-site table.
4170 struct CallSiteEntry {
4171 // The 'try-range' is BeginLabel .. EndLabel.
4172 unsigned BeginLabel; // zero indicates the start of the function.
4173 unsigned EndLabel; // zero indicates the end of the function.
4174 // The landing pad starts at PadLabel.
4175 unsigned PadLabel; // zero indicates that there is no landing pad.
4179 void EmitExceptionTable() {
4180 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
4181 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
4182 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
4183 if (PadInfos.empty()) return;
4185 // Sort the landing pads in order of their type ids. This is used to fold
4186 // duplicate actions.
4187 SmallVector<const LandingPadInfo *, 64> LandingPads;
4188 LandingPads.reserve(PadInfos.size());
4189 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
4190 LandingPads.push_back(&PadInfos[i]);
4191 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
4193 // Negative type ids index into FilterIds, positive type ids index into
4194 // TypeInfos. The value written for a positive type id is just the type
4195 // id itself. For a negative type id, however, the value written is the
4196 // (negative) byte offset of the corresponding FilterIds entry. The byte
4197 // offset is usually equal to the type id, because the FilterIds entries
4198 // are written using a variable width encoding which outputs one byte per
4199 // entry as long as the value written is not too large, but can differ.
4200 // This kind of complication does not occur for positive type ids because
4201 // type infos are output using a fixed width encoding.
4202 // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
4203 SmallVector<int, 16> FilterOffsets;
4204 FilterOffsets.reserve(FilterIds.size());
4206 for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
4207 E = FilterIds.end(); I != E; ++I) {
4208 FilterOffsets.push_back(Offset);
4209 Offset -= TargetAsmInfo::getULEB128Size(*I);
4212 // Compute the actions table and gather the first action index for each
4213 // landing pad site.
4214 SmallVector<ActionEntry, 32> Actions;
4215 SmallVector<unsigned, 64> FirstActions;
4216 FirstActions.reserve(LandingPads.size());
4218 int FirstAction = 0;
4219 unsigned SizeActions = 0;
4220 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
4221 const LandingPadInfo *LP = LandingPads[i];
4222 const std::vector<int> &TypeIds = LP->TypeIds;
4223 const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
4224 unsigned SizeSiteActions = 0;
4226 if (NumShared < TypeIds.size()) {
4227 unsigned SizeAction = 0;
4228 ActionEntry *PrevAction = 0;
4231 const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
4232 assert(Actions.size());
4233 PrevAction = &Actions.back();
4234 SizeAction = TargetAsmInfo::getSLEB128Size(PrevAction->NextAction) +
4235 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
4236 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
4238 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
4239 SizeAction += -PrevAction->NextAction;
4240 PrevAction = PrevAction->Previous;
4244 // Compute the actions.
4245 for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
4246 int TypeID = TypeIds[I];
4247 assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
4248 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
4249 unsigned SizeTypeID = TargetAsmInfo::getSLEB128Size(ValueForTypeID);
4251 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
4252 SizeAction = SizeTypeID + TargetAsmInfo::getSLEB128Size(NextAction);
4253 SizeSiteActions += SizeAction;
4255 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
4256 Actions.push_back(Action);
4258 PrevAction = &Actions.back();
4261 // Record the first action of the landing pad site.
4262 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
4263 } // else identical - re-use previous FirstAction
4265 FirstActions.push_back(FirstAction);
4267 // Compute this sites contribution to size.
4268 SizeActions += SizeSiteActions;
4271 // Compute the call-site table. The entry for an invoke has a try-range
4272 // containing the call, a non-zero landing pad and an appropriate action.
4273 // The entry for an ordinary call has a try-range containing the call and
4274 // zero for the landing pad and the action. Calls marked 'nounwind' have
4275 // no entry and must not be contained in the try-range of any entry - they
4276 // form gaps in the table. Entries must be ordered by try-range address.
4277 SmallVector<CallSiteEntry, 64> CallSites;
4279 RangeMapType PadMap;
4280 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
4281 // by try-range labels when lowered). Ordinary calls do not, so appropriate
4282 // try-ranges for them need be deduced.
4283 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
4284 const LandingPadInfo *LandingPad = LandingPads[i];
4285 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
4286 unsigned BeginLabel = LandingPad->BeginLabels[j];
4287 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
4288 PadRange P = { i, j };
4289 PadMap[BeginLabel] = P;
4293 // The end label of the previous invoke or nounwind try-range.
4294 unsigned LastLabel = 0;
4296 // Whether there is a potentially throwing instruction (currently this means
4297 // an ordinary call) between the end of the previous try-range and now.
4298 bool SawPotentiallyThrowing = false;
4300 // Whether the last callsite entry was for an invoke.
4301 bool PreviousIsInvoke = false;
4303 // Visit all instructions in order of address.
4304 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
4306 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
4308 if (!MI->isLabel()) {
4309 SawPotentiallyThrowing |= MI->getDesc().isCall();
4313 unsigned BeginLabel = MI->getOperand(0).getImm();
4314 assert(BeginLabel && "Invalid label!");
4316 // End of the previous try-range?
4317 if (BeginLabel == LastLabel)
4318 SawPotentiallyThrowing = false;
4320 // Beginning of a new try-range?
4321 RangeMapType::iterator L = PadMap.find(BeginLabel);
4322 if (L == PadMap.end())
4323 // Nope, it was just some random label.
4326 PadRange P = L->second;
4327 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
4329 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
4330 "Inconsistent landing pad map!");
4332 // If some instruction between the previous try-range and this one may
4333 // throw, create a call-site entry with no landing pad for the region
4334 // between the try-ranges.
4335 if (SawPotentiallyThrowing) {
4336 CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
4337 CallSites.push_back(Site);
4338 PreviousIsInvoke = false;
4341 LastLabel = LandingPad->EndLabels[P.RangeIndex];
4342 assert(BeginLabel && LastLabel && "Invalid landing pad!");
4344 if (LandingPad->LandingPadLabel) {
4345 // This try-range is for an invoke.
4346 CallSiteEntry Site = {BeginLabel, LastLabel,
4347 LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
4349 // Try to merge with the previous call-site.
4350 if (PreviousIsInvoke) {
4351 CallSiteEntry &Prev = CallSites.back();
4352 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
4353 // Extend the range of the previous entry.
4354 Prev.EndLabel = Site.EndLabel;
4359 // Otherwise, create a new call-site.
4360 CallSites.push_back(Site);
4361 PreviousIsInvoke = true;
4364 PreviousIsInvoke = false;
4368 // If some instruction between the previous try-range and the end of the
4369 // function may throw, create a call-site entry with no landing pad for the
4370 // region following the try-range.
4371 if (SawPotentiallyThrowing) {
4372 CallSiteEntry Site = {LastLabel, 0, 0, 0};
4373 CallSites.push_back(Site);
4379 const unsigned SiteStartSize = sizeof(int32_t); // DW_EH_PE_udata4
4380 const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
4381 const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
4382 unsigned SizeSites = CallSites.size() * (SiteStartSize +
4385 for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
4386 SizeSites += TargetAsmInfo::getULEB128Size(CallSites[i].Action);
4389 const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
4390 unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
4392 unsigned TypeOffset = sizeof(int8_t) + // Call site format
4393 TargetAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
4394 SizeSites + SizeActions + SizeTypes;
4396 unsigned TotalSize = sizeof(int8_t) + // LPStart format
4397 sizeof(int8_t) + // TType format
4398 TargetAsmInfo::getULEB128Size(TypeOffset) + // TType base offset
4401 unsigned SizeAlign = (4 - TotalSize) & 3;
4403 // Begin the exception table.
4404 Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
4405 Asm->EmitAlignment(2, 0, 0, false);
4406 O << "GCC_except_table" << SubprogramCount << ":\n";
4407 for (unsigned i = 0; i != SizeAlign; ++i) {
4409 Asm->EOL("Padding");
4411 EmitLabel("exception", SubprogramCount);
4414 Asm->EmitInt8(DW_EH_PE_omit);
4415 Asm->EOL("LPStart format (DW_EH_PE_omit)");
4416 Asm->EmitInt8(DW_EH_PE_absptr);
4417 Asm->EOL("TType format (DW_EH_PE_absptr)");
4418 Asm->EmitULEB128Bytes(TypeOffset);
4419 Asm->EOL("TType base offset");
4420 Asm->EmitInt8(DW_EH_PE_udata4);
4421 Asm->EOL("Call site format (DW_EH_PE_udata4)");
4422 Asm->EmitULEB128Bytes(SizeSites);
4423 Asm->EOL("Call-site table length");
4425 // Emit the landing pad site information.
4426 for (unsigned i = 0; i < CallSites.size(); ++i) {
4427 CallSiteEntry &S = CallSites[i];
4428 const char *BeginTag;
4429 unsigned BeginNumber;
4431 if (!S.BeginLabel) {
4432 BeginTag = "eh_func_begin";
4433 BeginNumber = SubprogramCount;
4436 BeginNumber = S.BeginLabel;
4439 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
4441 Asm->EOL("Region start");
4444 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
4447 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
4449 Asm->EOL("Region length");
4454 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
4456 Asm->EOL("Landing pad");
4458 Asm->EmitULEB128Bytes(S.Action);
4462 // Emit the actions.
4463 for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
4464 ActionEntry &Action = Actions[I];
4466 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
4467 Asm->EOL("TypeInfo index");
4468 Asm->EmitSLEB128Bytes(Action.NextAction);
4469 Asm->EOL("Next action");
4472 // Emit the type ids.
4473 for (unsigned M = TypeInfos.size(); M; --M) {
4474 GlobalVariable *GV = TypeInfos[M - 1];
4476 PrintRelDirective();
4479 O << Asm->getGlobalLinkName(GV);
4483 Asm->EOL("TypeInfo");
4486 // Emit the filter typeids.
4487 for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
4488 unsigned TypeID = FilterIds[j];
4489 Asm->EmitULEB128Bytes(TypeID);
4490 Asm->EOL("Filter TypeInfo index");
4493 Asm->EmitAlignment(2, 0, 0, false);
4497 //===--------------------------------------------------------------------===//
4498 // Main entry points.
4500 DwarfException(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
4501 : Dwarf(OS, A, T, "eh")
4502 , shouldEmitTable(false)
4503 , shouldEmitMoves(false)
4504 , shouldEmitTableModule(false)
4505 , shouldEmitMovesModule(false)
4508 virtual ~DwarfException() {}
4510 /// SetModuleInfo - Set machine module information when it's known that pass
4511 /// manager has created it. Set by the target AsmPrinter.
4512 void SetModuleInfo(MachineModuleInfo *mmi) {
4516 /// BeginModule - Emit all exception information that should come prior to the
4518 void BeginModule(Module *M) {
4522 /// EndModule - Emit all exception information that should come after the
4525 if (shouldEmitMovesModule || shouldEmitTableModule) {
4526 const std::vector<Function *> Personalities = MMI->getPersonalities();
4527 for (unsigned i =0; i < Personalities.size(); ++i)
4528 EmitCommonEHFrame(Personalities[i], i);
4530 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
4531 E = EHFrames.end(); I != E; ++I)
4536 /// BeginFunction - Gather pre-function exception information. Assumes being
4537 /// emitted immediately after the function entry point.
4538 void BeginFunction(MachineFunction *MF) {
4540 shouldEmitTable = shouldEmitMoves = false;
4541 if (MMI && TAI->doesSupportExceptionHandling()) {
4543 // Map all labels and get rid of any dead landing pads.
4544 MMI->TidyLandingPads();
4545 // If any landing pads survive, we need an EH table.
4546 if (MMI->getLandingPads().size())
4547 shouldEmitTable = true;
4549 // See if we need frame move info.
4550 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
4551 shouldEmitMoves = true;
4553 if (shouldEmitMoves || shouldEmitTable)
4554 // Assumes in correct section after the entry point.
4555 EmitLabel("eh_func_begin", ++SubprogramCount);
4557 shouldEmitTableModule |= shouldEmitTable;
4558 shouldEmitMovesModule |= shouldEmitMoves;
4561 /// EndFunction - Gather and emit post-function exception information.
4563 void EndFunction() {
4564 if (shouldEmitMoves || shouldEmitTable) {
4565 EmitLabel("eh_func_end", SubprogramCount);
4566 EmitExceptionTable();
4568 // Save EH frame information
4570 push_back(FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
4572 MMI->getPersonalityIndex(),
4573 MF->getFrameInfo()->hasCalls(),
4574 !MMI->getLandingPads().empty(),
4575 MMI->getFrameMoves(),
4576 MF->getFunction()));
4581 } // End of namespace llvm
4583 //===----------------------------------------------------------------------===//
4585 /// Emit - Print the abbreviation using the specified Dwarf writer.
4587 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
4588 // Emit its Dwarf tag type.
4589 DD.getAsm()->EmitULEB128Bytes(Tag);
4590 DD.getAsm()->EOL(TagString(Tag));
4592 // Emit whether it has children DIEs.
4593 DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
4594 DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
4596 // For each attribute description.
4597 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4598 const DIEAbbrevData &AttrData = Data[i];
4600 // Emit attribute type.
4601 DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
4602 DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
4605 DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
4606 DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
4609 // Mark end of abbreviation.
4610 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
4611 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
4615 void DIEAbbrev::print(std::ostream &O) {
4616 O << "Abbreviation @"
4617 << std::hex << (intptr_t)this << std::dec
4621 << ChildrenString(ChildrenFlag)
4624 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4626 << AttributeString(Data[i].getAttribute())
4628 << FormEncodingString(Data[i].getForm())
4632 void DIEAbbrev::dump() { print(cerr); }
4635 //===----------------------------------------------------------------------===//
4638 void DIEValue::dump() {
4643 //===----------------------------------------------------------------------===//
4645 /// EmitValue - Emit integer of appropriate size.
4647 void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
4649 case DW_FORM_flag: // Fall thru
4650 case DW_FORM_ref1: // Fall thru
4651 case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer); break;
4652 case DW_FORM_ref2: // Fall thru
4653 case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer); break;
4654 case DW_FORM_ref4: // Fall thru
4655 case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer); break;
4656 case DW_FORM_ref8: // Fall thru
4657 case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer); break;
4658 case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
4659 case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
4660 default: assert(0 && "DIE Value form not supported yet"); break;
4664 /// SizeOf - Determine size of integer value in bytes.
4666 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4668 case DW_FORM_flag: // Fall thru
4669 case DW_FORM_ref1: // Fall thru
4670 case DW_FORM_data1: return sizeof(int8_t);
4671 case DW_FORM_ref2: // Fall thru
4672 case DW_FORM_data2: return sizeof(int16_t);
4673 case DW_FORM_ref4: // Fall thru
4674 case DW_FORM_data4: return sizeof(int32_t);
4675 case DW_FORM_ref8: // Fall thru
4676 case DW_FORM_data8: return sizeof(int64_t);
4677 case DW_FORM_udata: return TargetAsmInfo::getULEB128Size(Integer);
4678 case DW_FORM_sdata: return TargetAsmInfo::getSLEB128Size(Integer);
4679 default: assert(0 && "DIE Value form not supported yet"); break;
4684 //===----------------------------------------------------------------------===//
4686 /// EmitValue - Emit string value.
4688 void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
4689 DD.getAsm()->EmitString(String);
4692 //===----------------------------------------------------------------------===//
4694 /// EmitValue - Emit label value.
4696 void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4697 bool IsSmall = Form == DW_FORM_data4;
4698 DD.EmitReference(Label, false, IsSmall);
4701 /// SizeOf - Determine size of label value in bytes.
4703 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4704 if (Form == DW_FORM_data4) return 4;
4705 return DD.getTargetData()->getPointerSize();
4708 //===----------------------------------------------------------------------===//
4710 /// EmitValue - Emit label value.
4712 void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4713 bool IsSmall = Form == DW_FORM_data4;
4714 DD.EmitReference(Label, false, IsSmall);
4717 /// SizeOf - Determine size of label value in bytes.
4719 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4720 if (Form == DW_FORM_data4) return 4;
4721 return DD.getTargetData()->getPointerSize();
4724 //===----------------------------------------------------------------------===//
4726 /// EmitValue - Emit delta value.
4728 void DIESectionOffset::EmitValue(DwarfDebug &DD, unsigned Form) {
4729 bool IsSmall = Form == DW_FORM_data4;
4730 DD.EmitSectionOffset(Label.Tag, Section.Tag,
4731 Label.Number, Section.Number, IsSmall, IsEH, UseSet);
4734 /// SizeOf - Determine size of delta value in bytes.
4736 unsigned DIESectionOffset::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4737 if (Form == DW_FORM_data4) return 4;
4738 return DD.getTargetData()->getPointerSize();
4741 //===----------------------------------------------------------------------===//
4743 /// EmitValue - Emit delta value.
4745 void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
4746 bool IsSmall = Form == DW_FORM_data4;
4747 DD.EmitDifference(LabelHi, LabelLo, IsSmall);
4750 /// SizeOf - Determine size of delta value in bytes.
4752 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4753 if (Form == DW_FORM_data4) return 4;
4754 return DD.getTargetData()->getPointerSize();
4757 //===----------------------------------------------------------------------===//
4759 /// EmitValue - Emit debug information entry offset.
4761 void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
4762 DD.getAsm()->EmitInt32(Entry->getOffset());
4765 //===----------------------------------------------------------------------===//
4767 /// ComputeSize - calculate the size of the block.
4769 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
4771 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4773 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4774 Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
4780 /// EmitValue - Emit block data.
4782 void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
4784 case DW_FORM_block1: DD.getAsm()->EmitInt8(Size); break;
4785 case DW_FORM_block2: DD.getAsm()->EmitInt16(Size); break;
4786 case DW_FORM_block4: DD.getAsm()->EmitInt32(Size); break;
4787 case DW_FORM_block: DD.getAsm()->EmitULEB128Bytes(Size); break;
4788 default: assert(0 && "Improper form for block"); break;
4791 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4793 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4795 Values[i]->EmitValue(DD, AbbrevData[i].getForm());
4799 /// SizeOf - Determine size of block data in bytes.
4801 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4803 case DW_FORM_block1: return Size + sizeof(int8_t);
4804 case DW_FORM_block2: return Size + sizeof(int16_t);
4805 case DW_FORM_block4: return Size + sizeof(int32_t);
4806 case DW_FORM_block: return Size + TargetAsmInfo::getULEB128Size(Size);
4807 default: assert(0 && "Improper form for block"); break;
4812 //===----------------------------------------------------------------------===//
4813 /// DIE Implementation
4816 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4820 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
4822 void DIE::AddSiblingOffset() {
4823 DIEInteger *DI = new DIEInteger(0);
4824 Values.insert(Values.begin(), DI);
4825 Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
4828 /// Profile - Used to gather unique data for the value folding set.
4830 void DIE::Profile(FoldingSetNodeID &ID) {
4833 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4834 ID.AddPointer(Children[i]);
4836 for (unsigned j = 0, M = Values.size(); j < M; ++j)
4837 ID.AddPointer(Values[j]);
4841 void DIE::print(std::ostream &O, unsigned IncIndent) {
4842 static unsigned IndentCount = 0;
4843 IndentCount += IncIndent;
4844 const std::string Indent(IndentCount, ' ');
4845 bool isBlock = Abbrev.getTag() == 0;
4850 << "0x" << std::hex << (intptr_t)this << std::dec
4851 << ", Offset: " << Offset
4852 << ", Size: " << Size
4856 << TagString(Abbrev.getTag())
4858 << ChildrenString(Abbrev.getChildrenFlag());
4860 O << "Size: " << Size;
4864 const SmallVector<DIEAbbrevData, 8> &Data = Abbrev.getData();
4867 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4871 O << AttributeString(Data[i].getAttribute());
4873 O << "Blk[" << i << "]";
4876 << FormEncodingString(Data[i].getForm())
4878 Values[i]->print(O);
4883 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
4884 Children[j]->print(O, 4);
4887 if (!isBlock) O << "\n";
4888 IndentCount -= IncIndent;
4896 //===----------------------------------------------------------------------===//
4897 /// DwarfWriter Implementation
4900 DwarfWriter::DwarfWriter(raw_ostream &OS, AsmPrinter *A,
4901 const TargetAsmInfo *T) {
4902 DE = new DwarfException(OS, A, T);
4903 DD = new DwarfDebug(OS, A, T);
4906 DwarfWriter::~DwarfWriter() {
4911 /// SetModuleInfo - Set machine module info when it's known that pass manager
4912 /// has created it. Set by the target AsmPrinter.
4913 void DwarfWriter::SetModuleInfo(MachineModuleInfo *MMI) {
4914 DD->SetModuleInfo(MMI);
4915 DE->SetModuleInfo(MMI);
4918 /// BeginModule - Emit all Dwarf sections that should come prior to the
4920 void DwarfWriter::BeginModule(Module *M) {
4925 /// EndModule - Emit all Dwarf sections that should come after the content.
4927 void DwarfWriter::EndModule() {
4932 /// BeginFunction - Gather pre-function debug information. Assumes being
4933 /// emitted immediately after the function entry point.
4934 void DwarfWriter::BeginFunction(MachineFunction *MF) {
4935 DE->BeginFunction(MF);
4936 DD->BeginFunction(MF);
4939 /// EndFunction - Gather and emit post-function debug information.
4941 void DwarfWriter::EndFunction(MachineFunction *MF) {
4942 DD->EndFunction(MF);
4945 if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI())
4946 // Clear function debug information.