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"
15 #include "llvm/Module.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Constants.h"
18 #include "llvm/CodeGen/AsmPrinter.h"
19 #include "llvm/CodeGen/MachineModuleInfo.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineLocation.h"
22 #include "llvm/Analysis/DebugInfo.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/Dwarf.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/DataTypes.h"
27 #include "llvm/Support/Mangler.h"
28 #include "llvm/Support/Timer.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/System/Path.h"
31 #include "llvm/Target/TargetAsmInfo.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Target/TargetFrameInfo.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/ADT/DenseMap.h"
39 #include "llvm/ADT/FoldingSet.h"
40 #include "llvm/ADT/StringExtras.h"
41 #include "llvm/ADT/StringMap.h"
45 using namespace llvm::dwarf;
47 static RegisterPass<DwarfWriter>
48 X("dwarfwriter", "DWARF Information Writer");
49 char DwarfWriter::ID = 0;
51 static TimerGroup *DwarfTimerGroup = 0;
52 static TimerGroup *getDwarfTimerGroup() {
53 if (DwarfTimerGroup) return DwarfTimerGroup;
54 return DwarfTimerGroup = new TimerGroup("Dwarf Exception and Debugging");
59 //===----------------------------------------------------------------------===//
61 /// Configuration values for initial hash set sizes (log2).
63 static const unsigned InitDiesSetSize = 9; // log2(512)
64 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
65 static const unsigned InitValuesSetSize = 9; // log2(512)
67 //===----------------------------------------------------------------------===//
68 /// Forward declarations.
73 //===----------------------------------------------------------------------===//
76 /// getGlobalVariable - Return either a direct or cast Global value.
78 static GlobalVariable *getGlobalVariable(Value *V) {
79 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
81 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
82 if (CE->getOpcode() == Instruction::BitCast) {
83 return dyn_cast<GlobalVariable>(CE->getOperand(0));
84 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
85 for (unsigned int i=1; i<CE->getNumOperands(); i++) {
86 if (!CE->getOperand(i)->isNullValue())
89 return dyn_cast<GlobalVariable>(CE->getOperand(0));
95 //===----------------------------------------------------------------------===//
96 /// DWLabel - Labels are used to track locations in the assembler file.
97 /// Labels appear in the form @verbatim <prefix><Tag><Number> @endverbatim,
98 /// where the tag is a category of label (Ex. location) and number is a value
99 /// unique in that category.
102 /// Tag - Label category tag. Should always be a staticly declared C string.
106 /// Number - Value to make label unique.
110 DWLabel(const char *T, unsigned N) : Tag(T), Number(N) {}
112 void Profile(FoldingSetNodeID &ID) const {
114 ID.AddInteger(Number);
118 void print(std::ostream *O) const {
121 void print(std::ostream &O) const {
123 if (Number) O << Number;
128 //===----------------------------------------------------------------------===//
129 /// DIEAbbrevData - Dwarf abbreviation data, describes the one attribute of a
130 /// Dwarf abbreviation.
131 class DIEAbbrevData {
133 /// Attribute - Dwarf attribute code.
137 /// Form - Dwarf form code.
142 DIEAbbrevData(unsigned A, unsigned F)
148 unsigned getAttribute() const { return Attribute; }
149 unsigned getForm() const { return Form; }
151 /// Profile - Used to gather unique data for the abbreviation folding set.
153 void Profile(FoldingSetNodeID &ID)const {
154 ID.AddInteger(Attribute);
159 //===----------------------------------------------------------------------===//
160 /// DIEAbbrev - Dwarf abbreviation, describes the organization of a debug
161 /// information object.
162 class DIEAbbrev : public FoldingSetNode {
164 /// Tag - Dwarf tag code.
168 /// Unique number for node.
172 /// ChildrenFlag - Dwarf children flag.
174 unsigned ChildrenFlag;
176 /// Data - Raw data bytes for abbreviation.
178 SmallVector<DIEAbbrevData, 8> Data;
182 DIEAbbrev(unsigned T, unsigned C)
190 unsigned getTag() const { return Tag; }
191 unsigned getNumber() const { return Number; }
192 unsigned getChildrenFlag() const { return ChildrenFlag; }
193 const SmallVector<DIEAbbrevData, 8> &getData() const { return Data; }
194 void setTag(unsigned T) { Tag = T; }
195 void setChildrenFlag(unsigned CF) { ChildrenFlag = CF; }
196 void setNumber(unsigned N) { Number = N; }
198 /// AddAttribute - Adds another set of attribute information to the
200 void AddAttribute(unsigned Attribute, unsigned Form) {
201 Data.push_back(DIEAbbrevData(Attribute, Form));
204 /// AddFirstAttribute - Adds a set of attribute information to the front
205 /// of the abbreviation.
206 void AddFirstAttribute(unsigned Attribute, unsigned Form) {
207 Data.insert(Data.begin(), DIEAbbrevData(Attribute, Form));
210 /// Profile - Used to gather unique data for the abbreviation folding set.
212 void Profile(FoldingSetNodeID &ID) {
214 ID.AddInteger(ChildrenFlag);
216 // For each attribute description.
217 for (unsigned i = 0, N = Data.size(); i < N; ++i)
221 /// Emit - Print the abbreviation using the specified Dwarf writer.
223 void Emit(const DwarfDebug &DD) const;
226 void print(std::ostream *O) {
229 void print(std::ostream &O);
234 //===----------------------------------------------------------------------===//
235 /// DIE - A structured debug information entry. Has an abbreviation which
236 /// describes it's organization.
237 class DIE : public FoldingSetNode {
239 /// Abbrev - Buffer for constructing abbreviation.
243 /// Offset - Offset in debug info section.
247 /// Size - Size of instance + children.
253 std::vector<DIE *> Children;
255 /// Attributes values.
257 SmallVector<DIEValue*, 32> Values;
260 explicit DIE(unsigned Tag)
261 : Abbrev(Tag, DW_CHILDREN_no)
270 DIEAbbrev &getAbbrev() { return Abbrev; }
271 unsigned getAbbrevNumber() const {
272 return Abbrev.getNumber();
274 unsigned getTag() const { return Abbrev.getTag(); }
275 unsigned getOffset() const { return Offset; }
276 unsigned getSize() const { return Size; }
277 const std::vector<DIE *> &getChildren() const { return Children; }
278 SmallVector<DIEValue*, 32> &getValues() { return Values; }
279 void setTag(unsigned Tag) { Abbrev.setTag(Tag); }
280 void setOffset(unsigned O) { Offset = O; }
281 void setSize(unsigned S) { Size = S; }
283 /// AddValue - Add a value and attributes to a DIE.
285 void AddValue(unsigned Attribute, unsigned Form, DIEValue *Value) {
286 Abbrev.AddAttribute(Attribute, Form);
287 Values.push_back(Value);
290 /// SiblingOffset - Return the offset of the debug information entry's
292 unsigned SiblingOffset() const { return Offset + Size; }
294 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
296 void AddSiblingOffset();
298 /// AddChild - Add a child to the DIE.
300 void AddChild(DIE *Child) {
301 Abbrev.setChildrenFlag(DW_CHILDREN_yes);
302 Children.push_back(Child);
305 /// Detach - Detaches objects connected to it after copying.
311 /// Profile - Used to gather unique data for the value folding set.
313 void Profile(FoldingSetNodeID &ID) ;
316 void print(std::ostream *O, unsigned IncIndent = 0) {
317 if (O) print(*O, IncIndent);
319 void print(std::ostream &O, unsigned IncIndent = 0);
324 //===----------------------------------------------------------------------===//
325 /// DIEValue - A debug information entry value.
327 class DIEValue : public FoldingSetNode {
340 /// Type - Type of data stored in the value.
344 explicit DIEValue(unsigned T)
347 virtual ~DIEValue() {}
350 unsigned getType() const { return Type; }
352 // Implement isa/cast/dyncast.
353 static bool classof(const DIEValue *) { return true; }
355 /// EmitValue - Emit value via the Dwarf writer.
357 virtual void EmitValue(DwarfDebug &DD, unsigned Form) = 0;
359 /// SizeOf - Return the size of a value in bytes.
361 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const = 0;
363 /// Profile - Used to gather unique data for the value folding set.
365 virtual void Profile(FoldingSetNodeID &ID) = 0;
368 void print(std::ostream *O) {
371 virtual void print(std::ostream &O) = 0;
376 //===----------------------------------------------------------------------===//
377 /// DWInteger - An integer value DIE.
379 class DIEInteger : public DIEValue {
384 explicit DIEInteger(uint64_t I) : DIEValue(isInteger), Integer(I) {}
386 // Implement isa/cast/dyncast.
387 static bool classof(const DIEInteger *) { return true; }
388 static bool classof(const DIEValue *I) { return I->Type == isInteger; }
390 /// BestForm - Choose the best form for integer.
392 static unsigned BestForm(bool IsSigned, uint64_t Integer) {
394 if ((char)Integer == (signed)Integer) return DW_FORM_data1;
395 if ((short)Integer == (signed)Integer) return DW_FORM_data2;
396 if ((int)Integer == (signed)Integer) return DW_FORM_data4;
398 if ((unsigned char)Integer == Integer) return DW_FORM_data1;
399 if ((unsigned short)Integer == Integer) return DW_FORM_data2;
400 if ((unsigned int)Integer == Integer) return DW_FORM_data4;
402 return DW_FORM_data8;
405 /// EmitValue - Emit integer of appropriate size.
407 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
409 /// SizeOf - Determine size of integer value in bytes.
411 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
413 /// Profile - Used to gather unique data for the value folding set.
415 static void Profile(FoldingSetNodeID &ID, unsigned Integer) {
416 ID.AddInteger(isInteger);
417 ID.AddInteger(Integer);
419 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Integer); }
422 virtual void print(std::ostream &O) {
423 O << "Int: " << (int64_t)Integer
424 << " 0x" << std::hex << Integer << std::dec;
429 //===----------------------------------------------------------------------===//
430 /// DIEString - A string value DIE.
432 class DIEString : public DIEValue {
434 const std::string String;
436 explicit DIEString(const std::string &S) : DIEValue(isString), String(S) {}
438 // Implement isa/cast/dyncast.
439 static bool classof(const DIEString *) { return true; }
440 static bool classof(const DIEValue *S) { return S->Type == isString; }
442 /// EmitValue - Emit string value.
444 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
446 /// SizeOf - Determine size of string value in bytes.
448 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
449 return String.size() + sizeof(char); // sizeof('\0');
452 /// Profile - Used to gather unique data for the value folding set.
454 static void Profile(FoldingSetNodeID &ID, const std::string &String) {
455 ID.AddInteger(isString);
456 ID.AddString(String);
458 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, String); }
461 virtual void print(std::ostream &O) {
462 O << "Str: \"" << String << "\"";
467 //===----------------------------------------------------------------------===//
468 /// DIEDwarfLabel - A Dwarf internal label expression DIE.
470 class DIEDwarfLabel : public DIEValue {
475 explicit DIEDwarfLabel(const DWLabel &L) : DIEValue(isLabel), Label(L) {}
477 // Implement isa/cast/dyncast.
478 static bool classof(const DIEDwarfLabel *) { return true; }
479 static bool classof(const DIEValue *L) { return L->Type == isLabel; }
481 /// EmitValue - Emit label value.
483 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
485 /// SizeOf - Determine size of label value in bytes.
487 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
489 /// Profile - Used to gather unique data for the value folding set.
491 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label) {
492 ID.AddInteger(isLabel);
495 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
498 virtual void print(std::ostream &O) {
506 //===----------------------------------------------------------------------===//
507 /// DIEObjectLabel - A label to an object in code or data.
509 class DIEObjectLabel : public DIEValue {
511 const std::string Label;
513 explicit DIEObjectLabel(const std::string &L)
514 : DIEValue(isAsIsLabel), Label(L) {}
516 // Implement isa/cast/dyncast.
517 static bool classof(const DIEObjectLabel *) { return true; }
518 static bool classof(const DIEValue *L) { return L->Type == isAsIsLabel; }
520 /// EmitValue - Emit label value.
522 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
524 /// SizeOf - Determine size of label value in bytes.
526 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
528 /// Profile - Used to gather unique data for the value folding set.
530 static void Profile(FoldingSetNodeID &ID, const std::string &Label) {
531 ID.AddInteger(isAsIsLabel);
534 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label.c_str()); }
537 virtual void print(std::ostream &O) {
538 O << "Obj: " << Label;
543 //===----------------------------------------------------------------------===//
544 /// DIESectionOffset - A section offset DIE.
546 class DIESectionOffset : public DIEValue {
549 const DWLabel Section;
553 DIESectionOffset(const DWLabel &Lab, const DWLabel &Sec,
554 bool isEH = false, bool useSet = true)
555 : DIEValue(isSectionOffset), Label(Lab), Section(Sec),
556 IsEH(isEH), UseSet(useSet) {}
558 // Implement isa/cast/dyncast.
559 static bool classof(const DIESectionOffset *) { return true; }
560 static bool classof(const DIEValue *D) { return D->Type == isSectionOffset; }
562 /// EmitValue - Emit section offset.
564 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
566 /// SizeOf - Determine size of section offset value in bytes.
568 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
570 /// Profile - Used to gather unique data for the value folding set.
572 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label,
573 const DWLabel &Section) {
574 ID.AddInteger(isSectionOffset);
577 // IsEH and UseSet are specific to the Label/Section that we will emit
578 // the offset for; so Label/Section are enough for uniqueness.
580 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label, Section); }
583 virtual void print(std::ostream &O) {
588 O << "-" << IsEH << "-" << UseSet;
593 //===----------------------------------------------------------------------===//
594 /// DIEDelta - A simple label difference DIE.
596 class DIEDelta : public DIEValue {
598 const DWLabel LabelHi;
599 const DWLabel LabelLo;
601 DIEDelta(const DWLabel &Hi, const DWLabel &Lo)
602 : DIEValue(isDelta), LabelHi(Hi), LabelLo(Lo) {}
604 // Implement isa/cast/dyncast.
605 static bool classof(const DIEDelta *) { return true; }
606 static bool classof(const DIEValue *D) { return D->Type == isDelta; }
608 /// EmitValue - Emit delta value.
610 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
612 /// SizeOf - Determine size of delta value in bytes.
614 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
616 /// Profile - Used to gather unique data for the value folding set.
618 static void Profile(FoldingSetNodeID &ID, const DWLabel &LabelHi,
619 const DWLabel &LabelLo) {
620 ID.AddInteger(isDelta);
624 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, LabelHi, LabelLo); }
627 virtual void print(std::ostream &O) {
636 //===----------------------------------------------------------------------===//
637 /// DIEntry - A pointer to another debug information entry. An instance of this
638 /// class can also be used as a proxy for a debug information entry not yet
639 /// defined (ie. types.)
640 class DIEntry : public DIEValue {
644 explicit DIEntry(DIE *E) : DIEValue(isEntry), Entry(E) {}
646 // Implement isa/cast/dyncast.
647 static bool classof(const DIEntry *) { return true; }
648 static bool classof(const DIEValue *E) { return E->Type == isEntry; }
650 /// EmitValue - Emit debug information entry offset.
652 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
654 /// SizeOf - Determine size of debug information entry in bytes.
656 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
657 return sizeof(int32_t);
660 /// Profile - Used to gather unique data for the value folding set.
662 static void Profile(FoldingSetNodeID &ID, DIE *Entry) {
663 ID.AddInteger(isEntry);
664 ID.AddPointer(Entry);
666 virtual void Profile(FoldingSetNodeID &ID) {
667 ID.AddInteger(isEntry);
670 ID.AddPointer(Entry);
677 virtual void print(std::ostream &O) {
678 O << "Die: 0x" << std::hex << (intptr_t)Entry << std::dec;
683 //===----------------------------------------------------------------------===//
684 /// DIEBlock - A block of values. Primarily used for location expressions.
686 class DIEBlock : public DIEValue, public DIE {
688 unsigned Size; // Size in bytes excluding size header.
698 // Implement isa/cast/dyncast.
699 static bool classof(const DIEBlock *) { return true; }
700 static bool classof(const DIEValue *E) { return E->Type == isBlock; }
702 /// ComputeSize - calculate the size of the block.
704 unsigned ComputeSize(DwarfDebug &DD);
706 /// BestForm - Choose the best form for data.
708 unsigned BestForm() const {
709 if ((unsigned char)Size == Size) return DW_FORM_block1;
710 if ((unsigned short)Size == Size) return DW_FORM_block2;
711 if ((unsigned int)Size == Size) return DW_FORM_block4;
712 return DW_FORM_block;
715 /// EmitValue - Emit block data.
717 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
719 /// SizeOf - Determine size of block data in bytes.
721 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
724 /// Profile - Used to gather unique data for the value folding set.
726 virtual void Profile(FoldingSetNodeID &ID) {
727 ID.AddInteger(isBlock);
732 virtual void print(std::ostream &O) {
739 //===----------------------------------------------------------------------===//
740 /// CompileUnit - This dwarf writer support class manages information associate
741 /// with a source file.
744 /// ID - File identifier for source.
748 /// Die - Compile unit debug information entry.
752 /// GVToDieMap - Tracks the mapping of unit level debug informaton
753 /// variables to debug information entries.
754 std::map<GlobalVariable *, DIE *> GVToDieMap;
756 /// GVToDIEntryMap - Tracks the mapping of unit level debug informaton
757 /// descriptors to debug information entries using a DIEntry proxy.
758 std::map<GlobalVariable *, DIEntry *> GVToDIEntryMap;
760 /// Globals - A map of globally visible named entities for this unit.
762 std::map<std::string, DIE *> Globals;
764 /// DiesSet - Used to uniquely define dies within the compile unit.
766 FoldingSet<DIE> DiesSet;
769 CompileUnit(unsigned I, DIE *D)
770 : ID(I), Die(D), GVToDieMap(),
771 GVToDIEntryMap(), Globals(), DiesSet(InitDiesSetSize)
779 unsigned getID() const { return ID; }
780 DIE* getDie() const { return Die; }
781 std::map<std::string, DIE *> &getGlobals() { return Globals; }
783 /// hasContent - Return true if this compile unit has something to write out.
785 bool hasContent() const {
786 return !Die->getChildren().empty();
789 /// AddGlobal - Add a new global entity to the compile unit.
791 void AddGlobal(const std::string &Name, DIE *Die) {
795 /// getDieMapSlotFor - Returns the debug information entry map slot for the
796 /// specified debug variable.
797 DIE *&getDieMapSlotFor(GlobalVariable *GV) {
798 return GVToDieMap[GV];
801 /// getDIEntrySlotFor - Returns the debug information entry proxy slot for the
802 /// specified debug variable.
803 DIEntry *&getDIEntrySlotFor(GlobalVariable *GV) {
804 return GVToDIEntryMap[GV];
807 /// AddDie - Adds or interns the DIE to the compile unit.
809 DIE *AddDie(DIE &Buffer) {
813 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
816 Die = new DIE(Buffer);
817 DiesSet.InsertNode(Die, Where);
818 this->Die->AddChild(Die);
826 //===----------------------------------------------------------------------===//
827 /// Dwarf - Emits general Dwarf directives.
831 //===--------------------------------------------------------------------===//
832 // Core attributes used by the Dwarf writer.
836 /// O - Stream to .s file.
840 /// Asm - Target of Dwarf emission.
844 /// TAI - Target asm information.
845 const TargetAsmInfo *TAI;
847 /// TD - Target data.
848 const TargetData *TD;
850 /// RI - Register Information.
851 const TargetRegisterInfo *RI;
853 /// M - Current module.
857 /// MF - Current machine function.
861 /// MMI - Collected machine module information.
863 MachineModuleInfo *MMI;
865 /// SubprogramCount - The running count of functions being compiled.
867 unsigned SubprogramCount;
869 /// Flavor - A unique string indicating what dwarf producer this is, used to
871 const char * const Flavor;
874 Dwarf(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T,
879 , TD(Asm->TM.getTargetData())
880 , RI(Asm->TM.getRegisterInfo())
891 //===--------------------------------------------------------------------===//
894 AsmPrinter *getAsm() const { return Asm; }
895 MachineModuleInfo *getMMI() const { return MMI; }
896 const TargetAsmInfo *getTargetAsmInfo() const { return TAI; }
897 const TargetData *getTargetData() const { return TD; }
899 void PrintRelDirective(bool Force32Bit = false, bool isInSection = false)
901 if (isInSection && TAI->getDwarfSectionOffsetDirective())
902 O << TAI->getDwarfSectionOffsetDirective();
903 else if (Force32Bit || TD->getPointerSize() == sizeof(int32_t))
904 O << TAI->getData32bitsDirective();
906 O << TAI->getData64bitsDirective();
909 /// PrintLabelName - Print label name in form used by Dwarf writer.
911 void PrintLabelName(DWLabel Label) const {
912 PrintLabelName(Label.Tag, Label.Number);
914 void PrintLabelName(const char *Tag, unsigned Number) const {
915 O << TAI->getPrivateGlobalPrefix() << Tag;
916 if (Number) O << Number;
919 void PrintLabelName(const char *Tag, unsigned Number,
920 const char *Suffix) const {
921 O << TAI->getPrivateGlobalPrefix() << Tag;
922 if (Number) O << Number;
926 /// EmitLabel - Emit location label for internal use by Dwarf.
928 void EmitLabel(DWLabel Label) const {
929 EmitLabel(Label.Tag, Label.Number);
931 void EmitLabel(const char *Tag, unsigned Number) const {
932 PrintLabelName(Tag, Number);
936 /// EmitReference - Emit a reference to a label.
938 void EmitReference(DWLabel Label, bool IsPCRelative = false,
939 bool Force32Bit = false) const {
940 EmitReference(Label.Tag, Label.Number, IsPCRelative, Force32Bit);
942 void EmitReference(const char *Tag, unsigned Number,
943 bool IsPCRelative = false, bool Force32Bit = false) const {
944 PrintRelDirective(Force32Bit);
945 PrintLabelName(Tag, Number);
947 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
949 void EmitReference(const std::string &Name, bool IsPCRelative = false,
950 bool Force32Bit = false) const {
951 PrintRelDirective(Force32Bit);
955 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
958 /// EmitDifference - Emit the difference between two labels. Some
959 /// assemblers do not behave with absolute expressions with data directives,
960 /// so there is an option (needsSet) to use an intermediary set expression.
961 void EmitDifference(DWLabel LabelHi, DWLabel LabelLo,
962 bool IsSmall = false) {
963 EmitDifference(LabelHi.Tag, LabelHi.Number,
964 LabelLo.Tag, LabelLo.Number,
967 void EmitDifference(const char *TagHi, unsigned NumberHi,
968 const char *TagLo, unsigned NumberLo,
969 bool IsSmall = false) {
970 if (TAI->needsSet()) {
972 PrintLabelName("set", SetCounter, Flavor);
974 PrintLabelName(TagHi, NumberHi);
976 PrintLabelName(TagLo, NumberLo);
979 PrintRelDirective(IsSmall);
980 PrintLabelName("set", SetCounter, Flavor);
983 PrintRelDirective(IsSmall);
985 PrintLabelName(TagHi, NumberHi);
987 PrintLabelName(TagLo, NumberLo);
991 void EmitSectionOffset(const char* Label, const char* Section,
992 unsigned LabelNumber, unsigned SectionNumber,
993 bool IsSmall = false, bool isEH = false,
994 bool useSet = true) {
995 bool printAbsolute = false;
997 printAbsolute = TAI->isAbsoluteEHSectionOffsets();
999 printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
1001 if (TAI->needsSet() && useSet) {
1003 PrintLabelName("set", SetCounter, Flavor);
1005 PrintLabelName(Label, LabelNumber);
1007 if (!printAbsolute) {
1009 PrintLabelName(Section, SectionNumber);
1013 PrintRelDirective(IsSmall);
1015 PrintLabelName("set", SetCounter, Flavor);
1018 PrintRelDirective(IsSmall, true);
1020 PrintLabelName(Label, LabelNumber);
1022 if (!printAbsolute) {
1024 PrintLabelName(Section, SectionNumber);
1029 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
1031 void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
1032 const std::vector<MachineMove> &Moves, bool isEH) {
1034 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
1035 TargetFrameInfo::StackGrowsUp ?
1036 TD->getPointerSize() : -TD->getPointerSize();
1037 bool IsLocal = BaseLabel && strcmp(BaseLabel, "label") == 0;
1039 for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
1040 const MachineMove &Move = Moves[i];
1041 unsigned LabelID = Move.getLabelID();
1044 LabelID = MMI->MappedLabel(LabelID);
1046 // Throw out move if the label is invalid.
1047 if (!LabelID) continue;
1050 const MachineLocation &Dst = Move.getDestination();
1051 const MachineLocation &Src = Move.getSource();
1053 // Advance row if new location.
1054 if (BaseLabel && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
1055 Asm->EmitInt8(DW_CFA_advance_loc4);
1056 Asm->EOL("DW_CFA_advance_loc4");
1057 EmitDifference("label", LabelID, BaseLabel, BaseLabelID, true);
1060 BaseLabelID = LabelID;
1061 BaseLabel = "label";
1065 // If advancing cfa.
1066 if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
1068 if (Src.getReg() == MachineLocation::VirtualFP) {
1069 Asm->EmitInt8(DW_CFA_def_cfa_offset);
1070 Asm->EOL("DW_CFA_def_cfa_offset");
1072 Asm->EmitInt8(DW_CFA_def_cfa);
1073 Asm->EOL("DW_CFA_def_cfa");
1074 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getReg(), isEH));
1075 Asm->EOL("Register");
1078 int Offset = -Src.getOffset();
1080 Asm->EmitULEB128Bytes(Offset);
1083 assert(0 && "Machine move no supported yet.");
1085 } else if (Src.isReg() &&
1086 Src.getReg() == MachineLocation::VirtualFP) {
1088 Asm->EmitInt8(DW_CFA_def_cfa_register);
1089 Asm->EOL("DW_CFA_def_cfa_register");
1090 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getReg(), isEH));
1091 Asm->EOL("Register");
1093 assert(0 && "Machine move no supported yet.");
1096 unsigned Reg = RI->getDwarfRegNum(Src.getReg(), isEH);
1097 int Offset = Dst.getOffset() / stackGrowth;
1100 Asm->EmitInt8(DW_CFA_offset_extended_sf);
1101 Asm->EOL("DW_CFA_offset_extended_sf");
1102 Asm->EmitULEB128Bytes(Reg);
1104 Asm->EmitSLEB128Bytes(Offset);
1106 } else if (Reg < 64) {
1107 Asm->EmitInt8(DW_CFA_offset + Reg);
1109 Asm->EOL("DW_CFA_offset + Reg (" + utostr(Reg) + ")");
1112 Asm->EmitULEB128Bytes(Offset);
1115 Asm->EmitInt8(DW_CFA_offset_extended);
1116 Asm->EOL("DW_CFA_offset_extended");
1117 Asm->EmitULEB128Bytes(Reg);
1119 Asm->EmitULEB128Bytes(Offset);
1128 //===----------------------------------------------------------------------===//
1129 /// SrcLineInfo - This class is used to record source line correspondence.
1132 unsigned Line; // Source line number.
1133 unsigned Column; // Source column.
1134 unsigned SourceID; // Source ID number.
1135 unsigned LabelID; // Label in code ID number.
1137 SrcLineInfo(unsigned L, unsigned C, unsigned S, unsigned I)
1138 : Line(L), Column(C), SourceID(S), LabelID(I) {}
1141 unsigned getLine() const { return Line; }
1142 unsigned getColumn() const { return Column; }
1143 unsigned getSourceID() const { return SourceID; }
1144 unsigned getLabelID() const { return LabelID; }
1147 //===----------------------------------------------------------------------===//
1148 /// DbgVariable - This class is used to track local variable information.
1151 DIVariable Var; // Variable Descriptor.
1152 unsigned FrameIndex; // Variable frame index.
1154 DbgVariable(DIVariable V, unsigned I) : Var(V), FrameIndex(I) {}
1157 DIVariable getVariable() const { return Var; }
1158 unsigned getFrameIndex() const { return FrameIndex; }
1161 //===----------------------------------------------------------------------===//
1162 /// DbgScope - This class is used to track scope information.
1165 DbgScope *Parent; // Parent to this scope.
1166 DIDescriptor Desc; // Debug info descriptor for scope.
1167 // Either subprogram or block.
1168 unsigned StartLabelID; // Label ID of the beginning of scope.
1169 unsigned EndLabelID; // Label ID of the end of scope.
1170 SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope.
1171 SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
1173 DbgScope(DbgScope *P, DIDescriptor D)
1174 : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0), Scopes(), Variables()
1177 for (unsigned i = 0, N = Scopes.size(); i < N; ++i) delete Scopes[i];
1178 for (unsigned j = 0, M = Variables.size(); j < M; ++j) delete Variables[j];
1182 DbgScope *getParent() const { return Parent; }
1183 DIDescriptor getDesc() const { return Desc; }
1184 unsigned getStartLabelID() const { return StartLabelID; }
1185 unsigned getEndLabelID() const { return EndLabelID; }
1186 SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
1187 SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
1188 void setStartLabelID(unsigned S) { StartLabelID = S; }
1189 void setEndLabelID(unsigned E) { EndLabelID = E; }
1191 /// AddScope - Add a scope to the scope.
1193 void AddScope(DbgScope *S) { Scopes.push_back(S); }
1195 /// AddVariable - Add a variable to the scope.
1197 void AddVariable(DbgVariable *V) { Variables.push_back(V); }
1200 //===----------------------------------------------------------------------===//
1201 /// DwarfDebug - Emits Dwarf debug directives.
1203 class DwarfDebug : public Dwarf {
1204 //===--------------------------------------------------------------------===//
1205 // Attributes used to construct specific Dwarf sections.
1208 /// CompileUnitMap - A map of global variables representing compile units to
1210 DenseMap<Value *, CompileUnit *> CompileUnitMap;
1212 /// CompileUnits - All the compile units in this module.
1214 SmallVector<CompileUnit *, 8> CompileUnits;
1216 /// MainCU - Some platform prefers one compile unit per .o file. In such
1217 /// cases, all dies are inserted in MainCU.
1218 CompileUnit *MainCU;
1220 /// AbbreviationsSet - Used to uniquely define abbreviations.
1222 FoldingSet<DIEAbbrev> AbbreviationsSet;
1224 /// Abbreviations - A list of all the unique abbreviations in use.
1226 std::vector<DIEAbbrev *> Abbreviations;
1228 /// DirectoryIdMap - Directory name to directory id map.
1230 StringMap<unsigned> DirectoryIdMap;
1232 /// DirectoryNames - A list of directory names.
1233 SmallVector<std::string, 8> DirectoryNames;
1235 /// SourceFileIdMap - Source file name to source file id map.
1237 StringMap<unsigned> SourceFileIdMap;
1239 /// SourceFileNames - A list of source file names.
1240 SmallVector<std::string, 8> SourceFileNames;
1242 /// SourceIdMap - Source id map, i.e. pair of directory id and source file
1243 /// id mapped to a unique id.
1244 DenseMap<std::pair<unsigned, unsigned>, unsigned> SourceIdMap;
1246 /// SourceIds - Reverse map from source id to directory id + file id pair.
1248 SmallVector<std::pair<unsigned, unsigned>, 8> SourceIds;
1250 /// Lines - List of of source line correspondence.
1251 std::vector<SrcLineInfo> Lines;
1253 /// ValuesSet - Used to uniquely define values.
1255 FoldingSet<DIEValue> ValuesSet;
1257 /// Values - A list of all the unique values in use.
1259 std::vector<DIEValue *> Values;
1261 /// StringPool - A UniqueVector of strings used by indirect references.
1263 UniqueVector<std::string> StringPool;
1265 /// SectionMap - Provides a unique id per text section.
1267 UniqueVector<const Section*> SectionMap;
1269 /// SectionSourceLines - Tracks line numbers per text section.
1271 std::vector<std::vector<SrcLineInfo> > SectionSourceLines;
1273 /// didInitial - Flag to indicate if initial emission has been done.
1277 /// shouldEmit - Flag to indicate if debug information should be emitted.
1281 // RootDbgScope - Top level scope for the current function.
1283 DbgScope *RootDbgScope;
1285 /// DbgScopeMap - Tracks the scopes in the current function.
1286 DenseMap<GlobalVariable *, DbgScope *> DbgScopeMap;
1288 /// DebugTimer - Timer for the Dwarf debug writer.
1291 struct FunctionDebugFrameInfo {
1293 std::vector<MachineMove> Moves;
1295 FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
1296 Number(Num), Moves(M) { }
1299 std::vector<FunctionDebugFrameInfo> DebugFrames;
1302 /// getSourceDirectoryAndFileIds - Return the directory and file ids that
1303 /// maps to the source id. Source id starts at 1.
1304 std::pair<unsigned, unsigned>
1305 getSourceDirectoryAndFileIds(unsigned SId) const {
1306 return SourceIds[SId-1];
1309 /// getNumSourceDirectories - Return the number of source directories in the
1311 unsigned getNumSourceDirectories() const {
1312 return DirectoryNames.size();
1315 /// getSourceDirectoryName - Return the name of the directory corresponding
1317 const std::string &getSourceDirectoryName(unsigned Id) const {
1318 return DirectoryNames[Id - 1];
1321 /// getSourceFileName - Return the name of the source file corresponding
1323 const std::string &getSourceFileName(unsigned Id) const {
1324 return SourceFileNames[Id - 1];
1327 /// getNumSourceIds - Return the number of unique source ids.
1328 unsigned getNumSourceIds() const {
1329 return SourceIds.size();
1332 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1334 void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1335 // Profile the node so that we can make it unique.
1336 FoldingSetNodeID ID;
1339 // Check the set for priors.
1340 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1342 // If it's newly added.
1343 if (InSet == &Abbrev) {
1344 // Add to abbreviation list.
1345 Abbreviations.push_back(&Abbrev);
1346 // Assign the vector position + 1 as its number.
1347 Abbrev.setNumber(Abbreviations.size());
1349 // Assign existing abbreviation number.
1350 Abbrev.setNumber(InSet->getNumber());
1354 /// NewString - Add a string to the constant pool and returns a label.
1356 DWLabel NewString(const std::string &String) {
1357 unsigned StringID = StringPool.insert(String);
1358 return DWLabel("string", StringID);
1361 /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1363 DIEntry *NewDIEntry(DIE *Entry = NULL) {
1367 FoldingSetNodeID ID;
1368 DIEntry::Profile(ID, Entry);
1370 Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1372 if (Value) return Value;
1374 Value = new DIEntry(Entry);
1375 ValuesSet.InsertNode(Value, Where);
1377 Value = new DIEntry(Entry);
1380 Values.push_back(Value);
1384 /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1386 void SetDIEntry(DIEntry *Value, DIE *Entry) {
1387 Value->Entry = Entry;
1388 // Add to values set if not already there. If it is, we merely have a
1389 // duplicate in the values list (no harm.)
1390 ValuesSet.GetOrInsertNode(Value);
1393 /// AddUInt - Add an unsigned integer attribute data and value.
1395 void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1396 if (!Form) Form = DIEInteger::BestForm(false, Integer);
1398 FoldingSetNodeID ID;
1399 DIEInteger::Profile(ID, Integer);
1401 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1403 Value = new DIEInteger(Integer);
1404 ValuesSet.InsertNode(Value, Where);
1405 Values.push_back(Value);
1408 Die->AddValue(Attribute, Form, Value);
1411 /// AddSInt - Add an signed integer attribute data and value.
1413 void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1414 if (!Form) Form = DIEInteger::BestForm(true, Integer);
1416 FoldingSetNodeID ID;
1417 DIEInteger::Profile(ID, (uint64_t)Integer);
1419 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1421 Value = new DIEInteger(Integer);
1422 ValuesSet.InsertNode(Value, Where);
1423 Values.push_back(Value);
1426 Die->AddValue(Attribute, Form, Value);
1429 /// AddString - Add a string attribute data and value.
1431 void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1432 const std::string &String) {
1433 FoldingSetNodeID ID;
1434 DIEString::Profile(ID, String);
1436 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1438 Value = new DIEString(String);
1439 ValuesSet.InsertNode(Value, Where);
1440 Values.push_back(Value);
1443 Die->AddValue(Attribute, Form, Value);
1446 /// AddLabel - Add a Dwarf label attribute data and value.
1448 void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1449 const DWLabel &Label) {
1450 FoldingSetNodeID ID;
1451 DIEDwarfLabel::Profile(ID, Label);
1453 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1455 Value = new DIEDwarfLabel(Label);
1456 ValuesSet.InsertNode(Value, Where);
1457 Values.push_back(Value);
1460 Die->AddValue(Attribute, Form, Value);
1463 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1465 void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1466 const std::string &Label) {
1467 FoldingSetNodeID ID;
1468 DIEObjectLabel::Profile(ID, Label);
1470 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1472 Value = new DIEObjectLabel(Label);
1473 ValuesSet.InsertNode(Value, Where);
1474 Values.push_back(Value);
1477 Die->AddValue(Attribute, Form, Value);
1480 /// AddSectionOffset - Add a section offset label attribute data and value.
1482 void AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
1483 const DWLabel &Label, const DWLabel &Section,
1484 bool isEH = false, bool useSet = true) {
1485 FoldingSetNodeID ID;
1486 DIESectionOffset::Profile(ID, Label, Section);
1488 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1490 Value = new DIESectionOffset(Label, Section, isEH, useSet);
1491 ValuesSet.InsertNode(Value, Where);
1492 Values.push_back(Value);
1495 Die->AddValue(Attribute, Form, Value);
1498 /// AddDelta - Add a label delta attribute data and value.
1500 void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1501 const DWLabel &Hi, const DWLabel &Lo) {
1502 FoldingSetNodeID ID;
1503 DIEDelta::Profile(ID, Hi, Lo);
1505 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1507 Value = new DIEDelta(Hi, Lo);
1508 ValuesSet.InsertNode(Value, Where);
1509 Values.push_back(Value);
1512 Die->AddValue(Attribute, Form, Value);
1515 /// AddDIEntry - Add a DIE attribute data and value.
1517 void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1518 Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1521 /// AddBlock - Add block data.
1523 void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1524 Block->ComputeSize(*this);
1525 FoldingSetNodeID ID;
1528 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1531 ValuesSet.InsertNode(Value, Where);
1532 Values.push_back(Value);
1534 // Already exists, reuse the previous one.
1536 Block = cast<DIEBlock>(Value);
1539 Die->AddValue(Attribute, Block->BestForm(), Value);
1542 /// AddSourceLine - Add location information to specified debug information
1544 void AddSourceLine(DIE *Die, const DIVariable *V) {
1545 unsigned FileID = 0;
1546 unsigned Line = V->getLineNumber();
1547 CompileUnit *Unit = FindCompileUnit(V->getCompileUnit());
1548 FileID = Unit->getID();
1549 assert (FileID && "Invalid file id");
1550 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1551 AddUInt(Die, DW_AT_decl_line, 0, Line);
1554 /// AddSourceLine - Add location information to specified debug information
1556 void AddSourceLine(DIE *Die, const DIGlobal *G) {
1557 unsigned FileID = 0;
1558 unsigned Line = G->getLineNumber();
1559 CompileUnit *Unit = FindCompileUnit(G->getCompileUnit());
1560 FileID = Unit->getID();
1561 assert (FileID && "Invalid file id");
1562 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1563 AddUInt(Die, DW_AT_decl_line, 0, Line);
1566 void AddSourceLine(DIE *Die, const DIType *Ty) {
1567 unsigned FileID = 0;
1568 unsigned Line = Ty->getLineNumber();
1569 DICompileUnit CU = Ty->getCompileUnit();
1572 CompileUnit *Unit = FindCompileUnit(CU);
1573 FileID = Unit->getID();
1574 assert (FileID && "Invalid file id");
1575 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1576 AddUInt(Die, DW_AT_decl_line, 0, Line);
1579 /// AddAddress - Add an address attribute to a die based on the location
1581 void AddAddress(DIE *Die, unsigned Attribute,
1582 const MachineLocation &Location) {
1583 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
1584 DIEBlock *Block = new DIEBlock();
1586 if (Location.isReg()) {
1588 AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1590 AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1591 AddUInt(Block, 0, DW_FORM_udata, Reg);
1595 AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1597 AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1598 AddUInt(Block, 0, DW_FORM_udata, Reg);
1600 AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1603 AddBlock(Die, Attribute, 0, Block);
1606 /// AddType - Add a new type attribute to the specified entity.
1607 void AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
1611 // Check for pre-existence.
1612 DIEntry *&Slot = DW_Unit->getDIEntrySlotFor(Ty.getGV());
1613 // If it exists then use the existing value.
1615 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1620 Slot = NewDIEntry();
1623 DIE Buffer(DW_TAG_base_type);
1624 if (Ty.isBasicType(Ty.getTag()))
1625 ConstructTypeDIE(DW_Unit, Buffer, DIBasicType(Ty.getGV()));
1626 else if (Ty.isDerivedType(Ty.getTag()))
1627 ConstructTypeDIE(DW_Unit, Buffer, DIDerivedType(Ty.getGV()));
1629 assert(Ty.isCompositeType(Ty.getTag()) && "Unknown kind of DIType");
1630 ConstructTypeDIE(DW_Unit, Buffer, DICompositeType(Ty.getGV()));
1633 // Add debug information entry to entity and appropriate context.
1635 DIDescriptor Context = Ty.getContext();
1636 if (!Context.isNull())
1637 Die = DW_Unit->getDieMapSlotFor(Context.getGV());
1640 DIE *Child = new DIE(Buffer);
1641 Die->AddChild(Child);
1643 SetDIEntry(Slot, Child);
1645 Die = DW_Unit->AddDie(Buffer);
1646 SetDIEntry(Slot, Die);
1649 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1652 /// ConstructTypeDIE - Construct basic type die from DIBasicType.
1653 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1656 // Get core information.
1659 Buffer.setTag(DW_TAG_base_type);
1660 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BTy.getEncoding());
1661 // Add name if not anonymous or intermediate type.
1663 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1664 uint64_t Size = BTy.getSizeInBits() >> 3;
1665 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1668 /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
1669 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1670 DIDerivedType DTy) {
1672 // Get core information.
1675 uint64_t Size = DTy.getSizeInBits() >> 3;
1676 unsigned Tag = DTy.getTag();
1678 // FIXME - Workaround for templates.
1679 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1683 // Map to main type, void will not have a type.
1684 DIType FromTy = DTy.getTypeDerivedFrom();
1685 AddType(DW_Unit, &Buffer, FromTy);
1687 // Add name if not anonymous or intermediate type.
1689 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1691 // Add size if non-zero (derived types might be zero-sized.)
1693 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1695 // Add source line info if available and TyDesc is not a forward
1697 if (!DTy.isForwardDecl())
1698 AddSourceLine(&Buffer, &DTy);
1701 /// ConstructTypeDIE - Construct type DIE from DICompositeType.
1702 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1703 DICompositeType CTy) {
1704 // Get core information.
1708 uint64_t Size = CTy.getSizeInBits() >> 3;
1709 unsigned Tag = CTy.getTag();
1713 case DW_TAG_vector_type:
1714 case DW_TAG_array_type:
1715 ConstructArrayTypeDIE(DW_Unit, Buffer, &CTy);
1717 case DW_TAG_enumeration_type:
1719 DIArray Elements = CTy.getTypeArray();
1720 // Add enumerators to enumeration type.
1721 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1722 DIE *ElemDie = NULL;
1723 DIEnumerator Enum(Elements.getElement(i).getGV());
1724 ElemDie = ConstructEnumTypeDIE(DW_Unit, &Enum);
1725 Buffer.AddChild(ElemDie);
1729 case DW_TAG_subroutine_type:
1731 // Add prototype flag.
1732 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1733 DIArray Elements = CTy.getTypeArray();
1735 DIDescriptor RTy = Elements.getElement(0);
1736 AddType(DW_Unit, &Buffer, DIType(RTy.getGV()));
1739 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1740 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1741 DIDescriptor Ty = Elements.getElement(i);
1742 AddType(DW_Unit, Arg, DIType(Ty.getGV()));
1743 Buffer.AddChild(Arg);
1747 case DW_TAG_structure_type:
1748 case DW_TAG_union_type:
1750 // Add elements to structure type.
1751 DIArray Elements = CTy.getTypeArray();
1753 // A forward struct declared type may not have elements available.
1754 if (Elements.isNull())
1757 // Add elements to structure type.
1758 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1759 DIDescriptor Element = Elements.getElement(i);
1760 DIE *ElemDie = NULL;
1761 if (Element.getTag() == dwarf::DW_TAG_subprogram)
1762 ElemDie = CreateSubprogramDIE(DW_Unit,
1763 DISubprogram(Element.getGV()));
1764 else if (Element.getTag() == dwarf::DW_TAG_variable) // ???
1765 ElemDie = CreateGlobalVariableDIE(DW_Unit,
1766 DIGlobalVariable(Element.getGV()));
1768 ElemDie = CreateMemberDIE(DW_Unit,
1769 DIDerivedType(Element.getGV()));
1770 Buffer.AddChild(ElemDie);
1772 unsigned RLang = CTy.getRunTimeLang();
1774 AddUInt(&Buffer, DW_AT_APPLE_runtime_class, DW_FORM_data1, RLang);
1781 // Add name if not anonymous or intermediate type.
1783 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1785 if (Tag == DW_TAG_enumeration_type || Tag == DW_TAG_structure_type
1786 || Tag == DW_TAG_union_type) {
1787 // Add size if non-zero (derived types might be zero-sized.)
1789 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1791 // Add zero size if it is not a forward declaration.
1792 if (CTy.isForwardDecl())
1793 AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
1795 AddUInt(&Buffer, DW_AT_byte_size, 0, 0);
1798 // Add source line info if available.
1799 if (!CTy.isForwardDecl())
1800 AddSourceLine(&Buffer, &CTy);
1804 /// ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
1805 void ConstructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1806 int64_t L = SR.getLo();
1807 int64_t H = SR.getHi();
1808 DIE *DW_Subrange = new DIE(DW_TAG_subrange_type);
1810 AddDIEntry(DW_Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1812 AddSInt(DW_Subrange, DW_AT_lower_bound, 0, L);
1813 AddSInt(DW_Subrange, DW_AT_upper_bound, 0, H);
1815 Buffer.AddChild(DW_Subrange);
1818 /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
1819 void ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1820 DICompositeType *CTy) {
1821 Buffer.setTag(DW_TAG_array_type);
1822 if (CTy->getTag() == DW_TAG_vector_type)
1823 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1825 // Emit derived type.
1826 AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
1827 DIArray Elements = CTy->getTypeArray();
1829 // Construct an anonymous type for index type.
1830 DIE IdxBuffer(DW_TAG_base_type);
1831 AddUInt(&IdxBuffer, DW_AT_byte_size, 0, sizeof(int32_t));
1832 AddUInt(&IdxBuffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
1833 DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
1835 // Add subranges to array type.
1836 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1837 DIDescriptor Element = Elements.getElement(i);
1838 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1839 ConstructSubrangeDIE(Buffer, DISubrange(Element.getGV()), IndexTy);
1843 /// ConstructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1844 DIE *ConstructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) {
1846 DIE *Enumerator = new DIE(DW_TAG_enumerator);
1849 AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
1850 int64_t Value = ETy->getEnumValue();
1851 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1855 /// CreateGlobalVariableDIE - Create new DIE using GV.
1856 DIE *CreateGlobalVariableDIE(CompileUnit *DW_Unit, const DIGlobalVariable &GV)
1858 DIE *GVDie = new DIE(DW_TAG_variable);
1860 GV.getDisplayName(Name);
1861 AddString(GVDie, DW_AT_name, DW_FORM_string, Name);
1862 std::string LinkageName;
1863 GV.getLinkageName(LinkageName);
1864 if (!LinkageName.empty())
1865 AddString(GVDie, DW_AT_MIPS_linkage_name, DW_FORM_string, LinkageName);
1866 AddType(DW_Unit, GVDie, GV.getType());
1867 if (!GV.isLocalToUnit())
1868 AddUInt(GVDie, DW_AT_external, DW_FORM_flag, 1);
1869 AddSourceLine(GVDie, &GV);
1873 /// CreateMemberDIE - Create new member DIE.
1874 DIE *CreateMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT) {
1875 DIE *MemberDie = new DIE(DT.getTag());
1879 AddString(MemberDie, DW_AT_name, DW_FORM_string, Name);
1881 AddType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
1883 AddSourceLine(MemberDie, &DT);
1885 uint64_t Size = DT.getSizeInBits();
1886 uint64_t FieldSize = DT.getOriginalTypeSize();
1888 if (Size != FieldSize) {
1890 AddUInt(MemberDie, DW_AT_byte_size, 0, DT.getOriginalTypeSize() >> 3);
1891 AddUInt(MemberDie, DW_AT_bit_size, 0, DT.getSizeInBits());
1893 uint64_t Offset = DT.getOffsetInBits();
1894 uint64_t FieldOffset = Offset;
1895 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1896 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1897 FieldOffset = (HiMark - FieldSize);
1898 Offset -= FieldOffset;
1899 // Maybe we need to work from the other end.
1900 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1901 AddUInt(MemberDie, DW_AT_bit_offset, 0, Offset);
1903 DIEBlock *Block = new DIEBlock();
1904 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1905 AddUInt(Block, 0, DW_FORM_udata, DT.getOffsetInBits() >> 3);
1906 AddBlock(MemberDie, DW_AT_data_member_location, 0, Block);
1908 if (DT.isProtected())
1909 AddUInt(MemberDie, DW_AT_accessibility, 0, DW_ACCESS_protected);
1910 else if (DT.isPrivate())
1911 AddUInt(MemberDie, DW_AT_accessibility, 0, DW_ACCESS_private);
1916 /// CreateSubprogramDIE - Create new DIE using SP.
1917 DIE *CreateSubprogramDIE(CompileUnit *DW_Unit,
1918 const DISubprogram &SP,
1919 bool IsConstructor = false) {
1920 DIE *SPDie = new DIE(DW_TAG_subprogram);
1923 AddString(SPDie, DW_AT_name, DW_FORM_string, Name);
1924 std::string LinkageName;
1925 SP.getLinkageName(LinkageName);
1926 if (!LinkageName.empty())
1927 AddString(SPDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1929 AddSourceLine(SPDie, &SP);
1931 DICompositeType SPTy = SP.getType();
1932 DIArray Args = SPTy.getTypeArray();
1935 if (!IsConstructor) {
1937 AddType(DW_Unit, SPDie, SPTy);
1939 AddType(DW_Unit, SPDie, DIType(Args.getElement(0).getGV()));
1942 if (!SP.isDefinition()) {
1943 AddUInt(SPDie, DW_AT_declaration, DW_FORM_flag, 1);
1945 // Do not add arguments for subprogram definition. They will be
1946 // handled through RecordVariable.
1948 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1949 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1950 AddType(DW_Unit, Arg, DIType(Args.getElement(i).getGV()));
1951 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1); // ???
1952 SPDie->AddChild(Arg);
1956 unsigned Lang = SP.getCompileUnit().getLanguage();
1957 if (Lang == DW_LANG_C99 || Lang == DW_LANG_C89
1958 || Lang == DW_LANG_ObjC)
1959 AddUInt(SPDie, DW_AT_prototyped, DW_FORM_flag, 1);
1961 if (!SP.isLocalToUnit())
1962 AddUInt(SPDie, DW_AT_external, DW_FORM_flag, 1);
1966 /// FindCompileUnit - Get the compile unit for the given descriptor.
1968 CompileUnit *FindCompileUnit(DICompileUnit Unit) {
1969 CompileUnit *DW_Unit = CompileUnitMap[Unit.getGV()];
1970 assert(DW_Unit && "Missing compile unit.");
1974 /// NewDbgScopeVariable - Create a new scope variable.
1976 DIE *NewDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
1977 // Get the descriptor.
1978 const DIVariable &VD = DV->getVariable();
1980 // Translate tag to proper Dwarf tag. The result variable is dropped for
1983 switch (VD.getTag()) {
1984 case DW_TAG_return_variable: return NULL;
1985 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
1986 case DW_TAG_auto_variable: // fall thru
1987 default: Tag = DW_TAG_variable; break;
1990 // Define variable debug information entry.
1991 DIE *VariableDie = new DIE(Tag);
1994 AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
1996 // Add source line info if available.
1997 AddSourceLine(VariableDie, &VD);
1999 // Add variable type.
2000 AddType(Unit, VariableDie, VD.getType());
2002 // Add variable address.
2003 MachineLocation Location;
2004 Location.set(RI->getFrameRegister(*MF),
2005 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
2006 AddAddress(VariableDie, DW_AT_location, Location);
2011 /// getOrCreateScope - Returns the scope associated with the given descriptor.
2013 DbgScope *getOrCreateScope(GlobalVariable *V) {
2014 DbgScope *&Slot = DbgScopeMap[V];
2015 if (Slot) return Slot;
2017 // FIXME - breaks down when the context is an inlined function.
2018 DIDescriptor ParentDesc;
2019 DIDescriptor Desc(V);
2021 if (Desc.getTag() == dwarf::DW_TAG_lexical_block) {
2023 ParentDesc = Block.getContext();
2026 DbgScope *Parent = ParentDesc.isNull() ?
2027 NULL : getOrCreateScope(ParentDesc.getGV());
2028 Slot = new DbgScope(Parent, Desc);
2031 Parent->AddScope(Slot);
2032 } else if (RootDbgScope) {
2033 // FIXME - Add inlined function scopes to the root so we can delete them
2034 // later. Long term, handle inlined functions properly.
2035 RootDbgScope->AddScope(Slot);
2037 // First function is top level function.
2038 RootDbgScope = Slot;
2044 /// ConstructDbgScope - Construct the components of a scope.
2046 void ConstructDbgScope(DbgScope *ParentScope,
2047 unsigned ParentStartID, unsigned ParentEndID,
2048 DIE *ParentDie, CompileUnit *Unit) {
2049 // Add variables to scope.
2050 SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
2051 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2052 DIE *VariableDie = NewDbgScopeVariable(Variables[i], Unit);
2053 if (VariableDie) ParentDie->AddChild(VariableDie);
2056 // Add nested scopes.
2057 SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
2058 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
2059 // Define the Scope debug information entry.
2060 DbgScope *Scope = Scopes[j];
2061 // FIXME - Ignore inlined functions for the time being.
2062 if (!Scope->getParent()) continue;
2064 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
2065 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
2067 // Ignore empty scopes.
2068 if (StartID == EndID && StartID != 0) continue;
2069 if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
2071 if (StartID == ParentStartID && EndID == ParentEndID) {
2072 // Just add stuff to the parent scope.
2073 ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
2075 DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
2077 // Add the scope bounds.
2079 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2080 DWLabel("label", StartID));
2082 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2083 DWLabel("func_begin", SubprogramCount));
2086 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2087 DWLabel("label", EndID));
2089 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2090 DWLabel("func_end", SubprogramCount));
2093 // Add the scope contents.
2094 ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
2095 ParentDie->AddChild(ScopeDie);
2100 /// ConstructRootDbgScope - Construct the scope for the subprogram.
2102 void ConstructRootDbgScope(DbgScope *RootScope) {
2103 // Exit if there is no root scope.
2104 if (!RootScope) return;
2105 DIDescriptor Desc = RootScope->getDesc();
2109 // Get the subprogram debug information entry.
2110 DISubprogram SPD(Desc.getGV());
2112 // Get the compile unit context.
2113 CompileUnit *Unit = MainCU;
2115 Unit = FindCompileUnit(SPD.getCompileUnit());
2117 // Get the subprogram die.
2118 DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
2119 assert(SPDie && "Missing subprogram descriptor");
2121 // Add the function bounds.
2122 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2123 DWLabel("func_begin", SubprogramCount));
2124 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2125 DWLabel("func_end", SubprogramCount));
2126 MachineLocation Location(RI->getFrameRegister(*MF));
2127 AddAddress(SPDie, DW_AT_frame_base, Location);
2129 ConstructDbgScope(RootScope, 0, 0, SPDie, Unit);
2132 /// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
2134 void ConstructDefaultDbgScope(MachineFunction *MF) {
2135 const char *FnName = MF->getFunction()->getNameStart();
2137 std::map<std::string, DIE*> &Globals = MainCU->getGlobals();
2138 std::map<std::string, DIE*>::iterator GI = Globals.find(FnName);
2139 if (GI != Globals.end()) {
2140 DIE *SPDie = GI->second;
2142 // Add the function bounds.
2143 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2144 DWLabel("func_begin", SubprogramCount));
2145 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2146 DWLabel("func_end", SubprogramCount));
2148 MachineLocation Location(RI->getFrameRegister(*MF));
2149 AddAddress(SPDie, DW_AT_frame_base, Location);
2153 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
2154 CompileUnit *Unit = CompileUnits[i];
2155 std::map<std::string, DIE*> &Globals = Unit->getGlobals();
2156 std::map<std::string, DIE*>::iterator GI = Globals.find(FnName);
2157 if (GI != Globals.end()) {
2158 DIE *SPDie = GI->second;
2160 // Add the function bounds.
2161 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2162 DWLabel("func_begin", SubprogramCount));
2163 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2164 DWLabel("func_end", SubprogramCount));
2166 MachineLocation Location(RI->getFrameRegister(*MF));
2167 AddAddress(SPDie, DW_AT_frame_base, Location);
2174 // FIXME: This is causing an abort because C++ mangled names are compared
2175 // with their unmangled counterparts. See PR2885. Don't do this assert.
2176 assert(0 && "Couldn't find DIE for machine function!");
2181 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
2182 /// tools to recognize the object file contains Dwarf information.
2183 void EmitInitial() {
2184 // Check to see if we already emitted intial headers.
2185 if (didInitial) return;
2188 // Dwarf sections base addresses.
2189 if (TAI->doesDwarfRequireFrameSection()) {
2190 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2191 EmitLabel("section_debug_frame", 0);
2193 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2194 EmitLabel("section_info", 0);
2195 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2196 EmitLabel("section_abbrev", 0);
2197 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2198 EmitLabel("section_aranges", 0);
2199 if (TAI->doesSupportMacInfoSection()) {
2200 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2201 EmitLabel("section_macinfo", 0);
2203 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2204 EmitLabel("section_line", 0);
2205 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2206 EmitLabel("section_loc", 0);
2207 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2208 EmitLabel("section_pubnames", 0);
2209 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2210 EmitLabel("section_str", 0);
2211 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2212 EmitLabel("section_ranges", 0);
2214 Asm->SwitchToSection(TAI->getTextSection());
2215 EmitLabel("text_begin", 0);
2216 Asm->SwitchToSection(TAI->getDataSection());
2217 EmitLabel("data_begin", 0);
2220 /// EmitDIE - Recusively Emits a debug information entry.
2222 void EmitDIE(DIE *Die) {
2223 // Get the abbreviation for this DIE.
2224 unsigned AbbrevNumber = Die->getAbbrevNumber();
2225 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2229 // Emit the code (index) for the abbreviation.
2230 Asm->EmitULEB128Bytes(AbbrevNumber);
2233 Asm->EOL(std::string("Abbrev [" +
2234 utostr(AbbrevNumber) +
2235 "] 0x" + utohexstr(Die->getOffset()) +
2236 ":0x" + utohexstr(Die->getSize()) + " " +
2237 TagString(Abbrev->getTag())));
2241 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2242 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2244 // Emit the DIE attribute values.
2245 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2246 unsigned Attr = AbbrevData[i].getAttribute();
2247 unsigned Form = AbbrevData[i].getForm();
2248 assert(Form && "Too many attributes for DIE (check abbreviation)");
2251 case DW_AT_sibling: {
2252 Asm->EmitInt32(Die->SiblingOffset());
2256 // Emit an attribute using the defined form.
2257 Values[i]->EmitValue(*this, Form);
2262 Asm->EOL(AttributeString(Attr));
2265 // Emit the DIE children if any.
2266 if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2267 const std::vector<DIE *> &Children = Die->getChildren();
2269 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2270 EmitDIE(Children[j]);
2273 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2277 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2279 unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2280 // Get the children.
2281 const std::vector<DIE *> &Children = Die->getChildren();
2283 // If not last sibling and has children then add sibling offset attribute.
2284 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2286 // Record the abbreviation.
2287 AssignAbbrevNumber(Die->getAbbrev());
2289 // Get the abbreviation for this DIE.
2290 unsigned AbbrevNumber = Die->getAbbrevNumber();
2291 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2294 Die->setOffset(Offset);
2296 // Start the size with the size of abbreviation code.
2297 Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
2299 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2300 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2302 // Size the DIE attribute values.
2303 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2304 // Size attribute value.
2305 Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2308 // Size the DIE children if any.
2309 if (!Children.empty()) {
2310 assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2311 "Children flag not set");
2313 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2314 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2317 // End of children marker.
2318 Offset += sizeof(int8_t);
2321 Die->setSize(Offset - Die->getOffset());
2325 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2327 void SizeAndOffsets() {
2328 // Process base compile unit.
2330 // Compute size of compile unit header
2331 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2332 sizeof(int16_t) + // DWARF version number
2333 sizeof(int32_t) + // Offset Into Abbrev. Section
2334 sizeof(int8_t); // Pointer Size (in bytes)
2335 SizeAndOffsetDie(MainCU->getDie(), Offset, true);
2338 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
2339 CompileUnit *Unit = CompileUnits[i];
2340 // Compute size of compile unit header
2341 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2342 sizeof(int16_t) + // DWARF version number
2343 sizeof(int32_t) + // Offset Into Abbrev. Section
2344 sizeof(int8_t); // Pointer Size (in bytes)
2345 SizeAndOffsetDie(Unit->getDie(), Offset, true);
2349 /// EmitDebugInfo / EmitDebugInfoPerCU - Emit the debug info section.
2351 void EmitDebugInfoPerCU(CompileUnit *Unit) {
2352 DIE *Die = Unit->getDie();
2353 // Emit the compile units header.
2354 EmitLabel("info_begin", Unit->getID());
2355 // Emit size of content not including length itself
2356 unsigned ContentSize = Die->getSize() +
2357 sizeof(int16_t) + // DWARF version number
2358 sizeof(int32_t) + // Offset Into Abbrev. Section
2359 sizeof(int8_t) + // Pointer Size (in bytes)
2360 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2362 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2363 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2364 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2365 Asm->EOL("Offset Into Abbrev. Section");
2366 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2369 // FIXME - extra padding for gdb bug.
2370 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2371 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2372 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2373 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2374 EmitLabel("info_end", Unit->getID());
2379 void EmitDebugInfo() {
2380 // Start debug info section.
2381 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2384 EmitDebugInfoPerCU(MainCU);
2388 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
2389 EmitDebugInfoPerCU(CompileUnits[i]);
2392 /// EmitAbbreviations - Emit the abbreviation section.
2394 void EmitAbbreviations() const {
2395 // Check to see if it is worth the effort.
2396 if (!Abbreviations.empty()) {
2397 // Start the debug abbrev section.
2398 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2400 EmitLabel("abbrev_begin", 0);
2402 // For each abbrevation.
2403 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2404 // Get abbreviation data
2405 const DIEAbbrev *Abbrev = Abbreviations[i];
2407 // Emit the abbrevations code (base 1 index.)
2408 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2409 Asm->EOL("Abbreviation Code");
2411 // Emit the abbreviations data.
2412 Abbrev->Emit(*this);
2417 // Mark end of abbreviations.
2418 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2420 EmitLabel("abbrev_end", 0);
2426 /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
2427 /// the line matrix.
2429 void EmitEndOfLineMatrix(unsigned SectionEnd) {
2430 // Define last address of section.
2431 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2432 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2433 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2434 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2436 // Mark end of matrix.
2437 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2438 Asm->EmitULEB128Bytes(1); Asm->EOL();
2439 Asm->EmitInt8(1); Asm->EOL();
2442 /// EmitDebugLines - Emit source line information.
2444 void EmitDebugLines() {
2445 // If the target is using .loc/.file, the assembler will be emitting the
2446 // .debug_line table automatically.
2447 if (TAI->hasDotLocAndDotFile())
2450 // Minimum line delta, thus ranging from -10..(255-10).
2451 const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2452 // Maximum line delta, thus ranging from -10..(255-10).
2453 const int MaxLineDelta = 255 + MinLineDelta;
2455 // Start the dwarf line section.
2456 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2458 // Construct the section header.
2460 EmitDifference("line_end", 0, "line_begin", 0, true);
2461 Asm->EOL("Length of Source Line Info");
2462 EmitLabel("line_begin", 0);
2464 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2466 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2467 Asm->EOL("Prolog Length");
2468 EmitLabel("line_prolog_begin", 0);
2470 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2472 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2474 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2476 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2478 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2480 // Line number standard opcode encodings argument count
2481 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2482 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2483 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2484 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2485 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2486 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2487 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2488 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2489 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2491 // Emit directories.
2492 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2493 Asm->EmitString(getSourceDirectoryName(DI));
2494 Asm->EOL("Directory");
2496 Asm->EmitInt8(0); Asm->EOL("End of directories");
2499 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2500 // Remember source id starts at 1.
2501 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2502 Asm->EmitString(getSourceFileName(Id.second));
2504 Asm->EmitULEB128Bytes(Id.first);
2505 Asm->EOL("Directory #");
2506 Asm->EmitULEB128Bytes(0);
2507 Asm->EOL("Mod date");
2508 Asm->EmitULEB128Bytes(0);
2509 Asm->EOL("File size");
2511 Asm->EmitInt8(0); Asm->EOL("End of files");
2513 EmitLabel("line_prolog_end", 0);
2515 // A sequence for each text section.
2516 unsigned SecSrcLinesSize = SectionSourceLines.size();
2518 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2519 // Isolate current sections line info.
2520 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2523 const Section* S = SectionMap[j + 1];
2524 O << '\t' << TAI->getCommentString() << " Section"
2525 << S->getName() << '\n';
2529 // Dwarf assumes we start with first line of first source file.
2530 unsigned Source = 1;
2533 // Construct rows of the address, source, line, column matrix.
2534 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2535 const SrcLineInfo &LineInfo = LineInfos[i];
2536 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2537 if (!LabelID) continue;
2542 std::pair<unsigned, unsigned> SourceID =
2543 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2544 O << '\t' << TAI->getCommentString() << ' '
2545 << getSourceDirectoryName(SourceID.first) << ' '
2546 << getSourceFileName(SourceID.second)
2547 <<" :" << utostr_32(LineInfo.getLine()) << '\n';
2550 // Define the line address.
2551 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2552 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2553 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2554 EmitReference("label", LabelID); Asm->EOL("Location label");
2556 // If change of source, then switch to the new source.
2557 if (Source != LineInfo.getSourceID()) {
2558 Source = LineInfo.getSourceID();
2559 Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2560 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2563 // If change of line.
2564 if (Line != LineInfo.getLine()) {
2565 // Determine offset.
2566 int Offset = LineInfo.getLine() - Line;
2567 int Delta = Offset - MinLineDelta;
2570 Line = LineInfo.getLine();
2572 // If delta is small enough and in range...
2573 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2574 // ... then use fast opcode.
2575 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2577 // ... otherwise use long hand.
2578 Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
2579 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2580 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2583 // Copy the previous row (different address or source)
2584 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2588 EmitEndOfLineMatrix(j + 1);
2591 if (SecSrcLinesSize == 0)
2592 // Because we're emitting a debug_line section, we still need a line
2593 // table. The linker and friends expect it to exist. If there's nothing to
2594 // put into it, emit an empty table.
2595 EmitEndOfLineMatrix(1);
2597 EmitLabel("line_end", 0);
2602 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2604 void EmitCommonDebugFrame() {
2605 if (!TAI->doesDwarfRequireFrameSection())
2609 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2610 TargetFrameInfo::StackGrowsUp ?
2611 TD->getPointerSize() : -TD->getPointerSize();
2613 // Start the dwarf frame section.
2614 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2616 EmitLabel("debug_frame_common", 0);
2617 EmitDifference("debug_frame_common_end", 0,
2618 "debug_frame_common_begin", 0, true);
2619 Asm->EOL("Length of Common Information Entry");
2621 EmitLabel("debug_frame_common_begin", 0);
2622 Asm->EmitInt32((int)DW_CIE_ID);
2623 Asm->EOL("CIE Identifier Tag");
2624 Asm->EmitInt8(DW_CIE_VERSION);
2625 Asm->EOL("CIE Version");
2626 Asm->EmitString("");
2627 Asm->EOL("CIE Augmentation");
2628 Asm->EmitULEB128Bytes(1);
2629 Asm->EOL("CIE Code Alignment Factor");
2630 Asm->EmitSLEB128Bytes(stackGrowth);
2631 Asm->EOL("CIE Data Alignment Factor");
2632 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2633 Asm->EOL("CIE RA Column");
2635 std::vector<MachineMove> Moves;
2636 RI->getInitialFrameState(Moves);
2638 EmitFrameMoves(NULL, 0, Moves, false);
2640 Asm->EmitAlignment(2, 0, 0, false);
2641 EmitLabel("debug_frame_common_end", 0);
2646 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2648 void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2649 if (!TAI->doesDwarfRequireFrameSection())
2652 // Start the dwarf frame section.
2653 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2655 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2656 "debug_frame_begin", DebugFrameInfo.Number, true);
2657 Asm->EOL("Length of Frame Information Entry");
2659 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2661 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2663 Asm->EOL("FDE CIE offset");
2665 EmitReference("func_begin", DebugFrameInfo.Number);
2666 Asm->EOL("FDE initial location");
2667 EmitDifference("func_end", DebugFrameInfo.Number,
2668 "func_begin", DebugFrameInfo.Number);
2669 Asm->EOL("FDE address range");
2671 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
2674 Asm->EmitAlignment(2, 0, 0, false);
2675 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2680 void EmitDebugPubNamesPerCU(CompileUnit *Unit) {
2681 EmitDifference("pubnames_end", Unit->getID(),
2682 "pubnames_begin", Unit->getID(), true);
2683 Asm->EOL("Length of Public Names Info");
2685 EmitLabel("pubnames_begin", Unit->getID());
2687 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
2689 EmitSectionOffset("info_begin", "section_info",
2690 Unit->getID(), 0, true, false);
2691 Asm->EOL("Offset of Compilation Unit Info");
2693 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
2695 Asm->EOL("Compilation Unit Length");
2697 std::map<std::string, DIE *> &Globals = Unit->getGlobals();
2698 for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
2699 GE = Globals.end(); GI != GE; ++GI) {
2700 const std::string &Name = GI->first;
2701 DIE * Entity = GI->second;
2703 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2704 Asm->EmitString(Name); Asm->EOL("External Name");
2707 Asm->EmitInt32(0); Asm->EOL("End Mark");
2708 EmitLabel("pubnames_end", Unit->getID());
2713 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2715 void EmitDebugPubNames() {
2716 // Start the dwarf pubnames section.
2717 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2720 EmitDebugPubNamesPerCU(MainCU);
2724 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
2725 EmitDebugPubNamesPerCU(CompileUnits[i]);
2728 /// EmitDebugStr - Emit visible names into a debug str section.
2730 void EmitDebugStr() {
2731 // Check to see if it is worth the effort.
2732 if (!StringPool.empty()) {
2733 // Start the dwarf str section.
2734 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2736 // For each of strings in the string pool.
2737 for (unsigned StringID = 1, N = StringPool.size();
2738 StringID <= N; ++StringID) {
2739 // Emit a label for reference from debug information entries.
2740 EmitLabel("string", StringID);
2741 // Emit the string itself.
2742 const std::string &String = StringPool[StringID];
2743 Asm->EmitString(String); Asm->EOL();
2750 /// EmitDebugLoc - Emit visible names into a debug loc section.
2752 void EmitDebugLoc() {
2753 // Start the dwarf loc section.
2754 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2759 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2761 void EmitDebugARanges() {
2762 // Start the dwarf aranges section.
2763 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2767 CompileUnit *Unit = GetBaseCompileUnit();
2769 // Don't include size of length
2770 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2772 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2774 EmitReference("info_begin", Unit->getID());
2775 Asm->EOL("Offset of Compilation Unit Info");
2777 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2779 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2781 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2782 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2785 EmitReference("text_begin", 0); Asm->EOL("Address");
2786 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2788 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2789 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2795 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2797 void EmitDebugRanges() {
2798 // Start the dwarf ranges section.
2799 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2804 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2806 void EmitDebugMacInfo() {
2807 if (TAI->doesSupportMacInfoSection()) {
2808 // Start the dwarf macinfo section.
2809 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2815 /// GetOrCreateSourceID - Look up the source id with the given directory and
2816 /// source file names. If none currently exists, create a new id and insert it
2817 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames maps
2819 unsigned GetOrCreateSourceID(const std::string &DirName,
2820 const std::string &FileName) {
2822 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
2823 if (DI != DirectoryIdMap.end()) {
2824 DId = DI->getValue();
2826 DId = DirectoryNames.size() + 1;
2827 DirectoryIdMap[DirName] = DId;
2828 DirectoryNames.push_back(DirName);
2832 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
2833 if (FI != SourceFileIdMap.end()) {
2834 FId = FI->getValue();
2836 FId = SourceFileNames.size() + 1;
2837 SourceFileIdMap[FileName] = FId;
2838 SourceFileNames.push_back(FileName);
2841 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
2842 SourceIdMap.find(std::make_pair(DId, FId));
2843 if (SI != SourceIdMap.end())
2846 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
2847 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
2848 SourceIds.push_back(std::make_pair(DId, FId));
2853 void ConstructCompileUnit(GlobalVariable *GV) {
2854 DICompileUnit DIUnit(GV);
2855 std::string Dir, FN, Prod;
2856 unsigned ID = GetOrCreateSourceID(DIUnit.getDirectory(Dir),
2857 DIUnit.getFilename(FN));
2859 DIE *Die = new DIE(DW_TAG_compile_unit);
2860 AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
2861 DWLabel("section_line", 0), DWLabel("section_line", 0),
2863 AddString(Die, DW_AT_producer, DW_FORM_string, DIUnit.getProducer(Prod));
2864 AddUInt(Die, DW_AT_language, DW_FORM_data1, DIUnit.getLanguage());
2865 AddString(Die, DW_AT_name, DW_FORM_string, FN);
2867 AddString(Die, DW_AT_comp_dir, DW_FORM_string, Dir);
2868 if (DIUnit.isOptimized())
2869 AddUInt(Die, DW_AT_APPLE_optimized, DW_FORM_flag, 1);
2871 DIUnit.getFlags(Flags);
2873 AddString(Die, DW_AT_APPLE_flags, DW_FORM_string, Flags);
2874 unsigned RVer = DIUnit.getRunTimeVersion();
2876 AddUInt(Die, DW_AT_APPLE_major_runtime_vers, DW_FORM_data1, RVer);
2878 CompileUnit *Unit = new CompileUnit(ID, Die);
2879 if (DIUnit.isMain()) {
2880 assert(!MainCU && "Multiple main compile units are found!");
2883 CompileUnitMap[DIUnit.getGV()] = Unit;
2884 CompileUnits.push_back(Unit);
2887 /// ConstructCompileUnits - Create a compile unit DIEs.
2888 void ConstructCompileUnits() {
2889 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.compile_units");
2892 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2893 "Malformed compile unit descriptor anchor type");
2894 Constant *RootC = cast<Constant>(*Root->use_begin());
2895 assert(RootC->hasNUsesOrMore(1) &&
2896 "Malformed compile unit descriptor anchor type");
2897 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2899 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2900 UUI != UUE; ++UUI) {
2901 GlobalVariable *GV = cast<GlobalVariable>(*UUI);
2902 ConstructCompileUnit(GV);
2906 bool ConstructGlobalVariableDIE(GlobalVariable *GV) {
2907 DIGlobalVariable DI_GV(GV);
2908 CompileUnit *DW_Unit = MainCU;
2910 DW_Unit = FindCompileUnit(DI_GV.getCompileUnit());
2912 // Check for pre-existence.
2913 DIE *&Slot = DW_Unit->getDieMapSlotFor(DI_GV.getGV());
2917 DIE *VariableDie = CreateGlobalVariableDIE(DW_Unit, DI_GV);
2920 DIEBlock *Block = new DIEBlock();
2921 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
2922 AddObjectLabel(Block, 0, DW_FORM_udata,
2923 Asm->getGlobalLinkName(DI_GV.getGlobal()));
2924 AddBlock(VariableDie, DW_AT_location, 0, Block);
2928 // Add to context owner.
2929 DW_Unit->getDie()->AddChild(VariableDie);
2930 // Expose as global. FIXME - need to check external flag.
2932 DW_Unit->AddGlobal(DI_GV.getName(Name), VariableDie);
2936 /// ConstructGlobalVariableDIEs - Create DIEs for each of the externally
2937 /// visible global variables. Return true if at least one global DIE is
2939 bool ConstructGlobalVariableDIEs() {
2940 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.global_variables");
2944 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2945 "Malformed global variable descriptor anchor type");
2946 Constant *RootC = cast<Constant>(*Root->use_begin());
2947 assert(RootC->hasNUsesOrMore(1) &&
2948 "Malformed global variable descriptor anchor type");
2950 bool Result = false;
2951 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2953 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2954 UUI != UUE; ++UUI) {
2955 GlobalVariable *GV = cast<GlobalVariable>(*UUI);
2956 Result |= ConstructGlobalVariableDIE(GV);
2961 bool ConstructSubprogram(GlobalVariable *GV) {
2962 DISubprogram SP(GV);
2963 CompileUnit *Unit = MainCU;
2965 Unit = FindCompileUnit(SP.getCompileUnit());
2967 // Check for pre-existence.
2968 DIE *&Slot = Unit->getDieMapSlotFor(GV);
2972 if (!SP.isDefinition())
2973 // This is a method declaration which will be handled while
2974 // constructing class type.
2977 DIE *SubprogramDie = CreateSubprogramDIE(Unit, SP);
2980 Slot = SubprogramDie;
2981 // Add to context owner.
2982 Unit->getDie()->AddChild(SubprogramDie);
2983 // Expose as global.
2985 Unit->AddGlobal(SP.getName(Name), SubprogramDie);
2989 /// ConstructSubprograms - Create DIEs for each of the externally visible
2990 /// subprograms. Return true if at least one subprogram DIE is created.
2991 bool ConstructSubprograms() {
2992 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.subprograms");
2996 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2997 "Malformed subprogram descriptor anchor type");
2998 Constant *RootC = cast<Constant>(*Root->use_begin());
2999 assert(RootC->hasNUsesOrMore(1) &&
3000 "Malformed subprogram descriptor anchor type");
3002 bool Result = false;
3003 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
3005 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
3006 UUI != UUE; ++UUI) {
3007 GlobalVariable *GV = cast<GlobalVariable>(*UUI);
3008 Result |= ConstructSubprogram(GV);
3014 //===--------------------------------------------------------------------===//
3015 // Main entry points.
3017 DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3018 : Dwarf(OS, A, T, "dbg"), MainCU(0),
3019 AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(),
3020 ValuesSet(InitValuesSetSize), Values(), StringPool(), SectionMap(),
3021 SectionSourceLines(), didInitial(false), shouldEmit(false),
3022 RootDbgScope(0), DebugTimer(0) {
3023 if (TimePassesIsEnabled)
3024 DebugTimer = new Timer("Dwarf Debug Writer",
3025 *getDwarfTimerGroup());
3027 virtual ~DwarfDebug() {
3028 for (unsigned j = 0, M = Values.size(); j < M; ++j)
3034 /// ShouldEmitDwarfDebug - Returns true if Dwarf debugging declarations should
3036 bool ShouldEmitDwarfDebug() const { return shouldEmit; }
3038 /// SetDebugInfo - Create global DIEs and emit initial debug info sections.
3039 /// This is inovked by the target AsmPrinter.
3040 void SetDebugInfo(MachineModuleInfo *mmi) {
3041 if (TimePassesIsEnabled)
3042 DebugTimer->startTimer();
3044 // Create all the compile unit DIEs.
3045 ConstructCompileUnits();
3047 if (CompileUnits.empty()) {
3048 if (TimePassesIsEnabled)
3049 DebugTimer->stopTimer();
3054 // Create DIEs for each of the externally visible global variables.
3055 bool globalDIEs = ConstructGlobalVariableDIEs();
3057 // Create DIEs for each of the externally visible subprograms.
3058 bool subprogramDIEs = ConstructSubprograms();
3060 // If there is not any debug info available for any global variables
3061 // and any subprograms then there is not any debug info to emit.
3062 if (!globalDIEs && !subprogramDIEs) {
3063 if (TimePassesIsEnabled)
3064 DebugTimer->stopTimer();
3071 MMI->setDebugInfoAvailability(true);
3073 // Prime section data.
3074 SectionMap.insert(TAI->getTextSection());
3076 // Print out .file directives to specify files for .loc directives. These
3077 // are printed out early so that they precede any .loc directives.
3078 if (TAI->hasDotLocAndDotFile()) {
3079 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
3080 // Remember source id starts at 1.
3081 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
3082 sys::Path FullPath(getSourceDirectoryName(Id.first));
3084 FullPath.appendComponent(getSourceFileName(Id.second));
3085 assert(AppendOk && "Could not append filename to directory!");
3087 Asm->EmitFile(i, FullPath.toString());
3092 // Emit initial sections
3095 if (TimePassesIsEnabled)
3096 DebugTimer->stopTimer();
3099 /// BeginModule - Emit all Dwarf sections that should come prior to the
3101 void BeginModule(Module *M) {
3105 /// EndModule - Emit all Dwarf sections that should come after the content.
3108 if (!ShouldEmitDwarfDebug())
3111 if (TimePassesIsEnabled)
3112 DebugTimer->startTimer();
3114 // Standard sections final addresses.
3115 Asm->SwitchToSection(TAI->getTextSection());
3116 EmitLabel("text_end", 0);
3117 Asm->SwitchToSection(TAI->getDataSection());
3118 EmitLabel("data_end", 0);
3120 // End text sections.
3121 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
3122 Asm->SwitchToSection(SectionMap[i]);
3123 EmitLabel("section_end", i);
3126 // Emit common frame information.
3127 EmitCommonDebugFrame();
3129 // Emit function debug frame information
3130 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
3131 E = DebugFrames.end(); I != E; ++I)
3132 EmitFunctionDebugFrame(*I);
3134 // Compute DIE offsets and sizes.
3137 // Emit all the DIEs into a debug info section
3140 // Corresponding abbreviations into a abbrev section.
3141 EmitAbbreviations();
3143 // Emit source line correspondence into a debug line section.
3146 // Emit info into a debug pubnames section.
3147 EmitDebugPubNames();
3149 // Emit info into a debug str section.
3152 // Emit info into a debug loc section.
3155 // Emit info into a debug aranges section.
3158 // Emit info into a debug ranges section.
3161 // Emit info into a debug macinfo section.
3164 if (TimePassesIsEnabled)
3165 DebugTimer->stopTimer();
3168 /// BeginFunction - Gather pre-function debug information. Assumes being
3169 /// emitted immediately after the function entry point.
3170 void BeginFunction(MachineFunction *MF) {
3171 if (!ShouldEmitDwarfDebug()) return;
3173 if (TimePassesIsEnabled)
3174 DebugTimer->startTimer();
3178 // Begin accumulating function debug information.
3179 MMI->BeginFunction(MF);
3181 // Assumes in correct section after the entry point.
3182 EmitLabel("func_begin", ++SubprogramCount);
3184 // Emit label for the implicitly defined dbg.stoppoint at the start of
3186 if (!Lines.empty()) {
3187 const SrcLineInfo &LineInfo = Lines[0];
3188 Asm->printLabel(LineInfo.getLabelID());
3191 if (TimePassesIsEnabled)
3192 DebugTimer->stopTimer();
3195 /// EndFunction - Gather and emit post-function debug information.
3197 void EndFunction(MachineFunction *MF) {
3198 if (!ShouldEmitDwarfDebug()) return;
3200 if (TimePassesIsEnabled)
3201 DebugTimer->startTimer();
3203 // Define end label for subprogram.
3204 EmitLabel("func_end", SubprogramCount);
3206 // Get function line info.
3207 if (!Lines.empty()) {
3208 // Get section line info.
3209 unsigned ID = SectionMap.insert(Asm->CurrentSection_);
3210 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
3211 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
3212 // Append the function info to section info.
3213 SectionLineInfos.insert(SectionLineInfos.end(),
3214 Lines.begin(), Lines.end());
3217 // Construct scopes for subprogram.
3219 ConstructRootDbgScope(RootDbgScope);
3221 // FIXME: This is wrong. We are essentially getting past a problem with
3222 // debug information not being able to handle unreachable blocks that have
3223 // debug information in them. In particular, those unreachable blocks that
3224 // have "region end" info in them. That situation results in the "root
3225 // scope" not being created. If that's the case, then emit a "default"
3226 // scope, i.e., one that encompasses the whole function. This isn't
3227 // desirable. And a better way of handling this (and all of the debugging
3228 // information) needs to be explored.
3229 ConstructDefaultDbgScope(MF);
3231 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
3232 MMI->getFrameMoves()));
3236 delete RootDbgScope;
3237 DbgScopeMap.clear();
3238 RootDbgScope = NULL;
3243 if (TimePassesIsEnabled)
3244 DebugTimer->stopTimer();
3247 /// ValidDebugInfo - Return true if V represents valid debug info value.
3248 bool ValidDebugInfo(Value *V) {
3255 GlobalVariable *GV = getGlobalVariable(V);
3259 if (!GV->hasInternalLinkage () && !GV->hasLinkOnceLinkage())
3262 if (TimePassesIsEnabled)
3263 DebugTimer->startTimer();
3265 DIDescriptor DI(GV);
3267 // Check current version. Allow Version6 for now.
3268 unsigned Version = DI.getVersion();
3269 if (Version != LLVMDebugVersion && Version != LLVMDebugVersion6) {
3270 if (TimePassesIsEnabled)
3271 DebugTimer->stopTimer();
3276 unsigned Tag = DI.getTag();
3278 case DW_TAG_variable:
3279 assert(DIVariable(GV).Verify() && "Invalid DebugInfo value");
3281 case DW_TAG_compile_unit:
3282 assert(DICompileUnit(GV).Verify() && "Invalid DebugInfo value");
3284 case DW_TAG_subprogram:
3285 assert(DISubprogram(GV).Verify() && "Invalid DebugInfo value");
3291 if (TimePassesIsEnabled)
3292 DebugTimer->stopTimer();
3297 /// RecordSourceLine - Records location information and associates it with a
3298 /// label. Returns a unique label ID used to generate a label and provide
3299 /// correspondence to the source line list.
3300 unsigned RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
3301 if (TimePassesIsEnabled)
3302 DebugTimer->startTimer();
3304 CompileUnit *Unit = CompileUnitMap[V];
3305 assert(Unit && "Unable to find CompileUnit");
3306 unsigned ID = MMI->NextLabelID();
3307 Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
3309 if (TimePassesIsEnabled)
3310 DebugTimer->stopTimer();
3315 /// RecordSourceLine - Records location information and associates it with a
3316 /// label. Returns a unique label ID used to generate a label and provide
3317 /// correspondence to the source line list.
3318 unsigned RecordSourceLine(unsigned Line, unsigned Col, unsigned Src) {
3319 if (TimePassesIsEnabled)
3320 DebugTimer->startTimer();
3322 unsigned ID = MMI->NextLabelID();
3323 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
3325 if (TimePassesIsEnabled)
3326 DebugTimer->stopTimer();
3331 /// getRecordSourceLineCount - Return the number of source lines in the debug
3333 unsigned getRecordSourceLineCount() const {
3334 return Lines.size();
3337 /// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
3338 /// timed. Look up the source id with the given directory and source file
3339 /// names. If none currently exists, create a new id and insert it in the
3340 /// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
3342 unsigned getOrCreateSourceID(const std::string &DirName,
3343 const std::string &FileName) {
3344 if (TimePassesIsEnabled)
3345 DebugTimer->startTimer();
3347 unsigned SrcId = GetOrCreateSourceID(DirName, FileName);
3349 if (TimePassesIsEnabled)
3350 DebugTimer->stopTimer();
3355 /// RecordRegionStart - Indicate the start of a region.
3356 unsigned RecordRegionStart(GlobalVariable *V) {
3357 if (TimePassesIsEnabled)
3358 DebugTimer->startTimer();
3360 DbgScope *Scope = getOrCreateScope(V);
3361 unsigned ID = MMI->NextLabelID();
3362 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
3364 if (TimePassesIsEnabled)
3365 DebugTimer->stopTimer();
3370 /// RecordRegionEnd - Indicate the end of a region.
3371 unsigned RecordRegionEnd(GlobalVariable *V) {
3372 if (TimePassesIsEnabled)
3373 DebugTimer->startTimer();
3375 DbgScope *Scope = getOrCreateScope(V);
3376 unsigned ID = MMI->NextLabelID();
3377 Scope->setEndLabelID(ID);
3379 if (TimePassesIsEnabled)
3380 DebugTimer->stopTimer();
3385 /// RecordVariable - Indicate the declaration of a local variable.
3386 void RecordVariable(GlobalVariable *GV, unsigned FrameIndex) {
3387 if (TimePassesIsEnabled)
3388 DebugTimer->startTimer();
3390 DIDescriptor Desc(GV);
3391 DbgScope *Scope = NULL;
3393 if (Desc.getTag() == DW_TAG_variable) {
3394 // GV is a global variable.
3395 DIGlobalVariable DG(GV);
3396 Scope = getOrCreateScope(DG.getContext().getGV());
3398 // or GV is a local variable.
3400 Scope = getOrCreateScope(DV.getContext().getGV());
3403 assert(Scope && "Unable to find variable' scope");
3404 DbgVariable *DV = new DbgVariable(DIVariable(GV), FrameIndex);
3405 Scope->AddVariable(DV);
3407 if (TimePassesIsEnabled)
3408 DebugTimer->stopTimer();
3412 //===----------------------------------------------------------------------===//
3413 /// DwarfException - Emits Dwarf exception handling directives.
3415 class DwarfException : public Dwarf {
3416 struct FunctionEHFrameInfo {
3419 unsigned PersonalityIndex;
3421 bool hasLandingPads;
3422 std::vector<MachineMove> Moves;
3423 const Function * function;
3425 FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
3427 const std::vector<MachineMove> &M,
3429 FnName(FN), Number(Num), PersonalityIndex(P),
3430 hasCalls(hC), hasLandingPads(hL), Moves(M), function (f) { }
3433 std::vector<FunctionEHFrameInfo> EHFrames;
3435 /// shouldEmitTable - Per-function flag to indicate if EH tables should
3437 bool shouldEmitTable;
3439 /// shouldEmitMoves - Per-function flag to indicate if frame moves info
3440 /// should be emitted.
3441 bool shouldEmitMoves;
3443 /// shouldEmitTableModule - Per-module flag to indicate if EH tables
3444 /// should be emitted.
3445 bool shouldEmitTableModule;
3447 /// shouldEmitFrameModule - Per-module flag to indicate if frame moves
3448 /// should be emitted.
3449 bool shouldEmitMovesModule;
3451 /// ExceptionTimer - Timer for the Dwarf exception writer.
3452 Timer *ExceptionTimer;
3454 /// EmitCommonEHFrame - Emit the common eh unwind frame.
3456 void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
3457 // Size and sign of stack growth.
3459 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3460 TargetFrameInfo::StackGrowsUp ?
3461 TD->getPointerSize() : -TD->getPointerSize();
3463 // Begin eh frame section.
3464 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3466 if (!TAI->doesRequireNonLocalEHFrameLabel())
3467 O << TAI->getEHGlobalPrefix();
3468 O << "EH_frame" << Index << ":\n";
3469 EmitLabel("section_eh_frame", Index);
3471 // Define base labels.
3472 EmitLabel("eh_frame_common", Index);
3474 // Define the eh frame length.
3475 EmitDifference("eh_frame_common_end", Index,
3476 "eh_frame_common_begin", Index, true);
3477 Asm->EOL("Length of Common Information Entry");
3480 EmitLabel("eh_frame_common_begin", Index);
3481 Asm->EmitInt32((int)0);
3482 Asm->EOL("CIE Identifier Tag");
3483 Asm->EmitInt8(DW_CIE_VERSION);
3484 Asm->EOL("CIE Version");
3486 // The personality presence indicates that language specific information
3487 // will show up in the eh frame.
3488 Asm->EmitString(Personality ? "zPLR" : "zR");
3489 Asm->EOL("CIE Augmentation");
3491 // Round out reader.
3492 Asm->EmitULEB128Bytes(1);
3493 Asm->EOL("CIE Code Alignment Factor");
3494 Asm->EmitSLEB128Bytes(stackGrowth);
3495 Asm->EOL("CIE Data Alignment Factor");
3496 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
3497 Asm->EOL("CIE Return Address Column");
3499 // If there is a personality, we need to indicate the functions location.
3501 Asm->EmitULEB128Bytes(7);
3502 Asm->EOL("Augmentation Size");
3504 if (TAI->getNeedsIndirectEncoding()) {
3505 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4 | DW_EH_PE_indirect);
3506 Asm->EOL("Personality (pcrel sdata4 indirect)");
3508 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3509 Asm->EOL("Personality (pcrel sdata4)");
3512 PrintRelDirective(true);
3513 O << TAI->getPersonalityPrefix();
3514 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
3515 O << TAI->getPersonalitySuffix();
3516 if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
3517 O << "-" << TAI->getPCSymbol();
3518 Asm->EOL("Personality");
3520 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3521 Asm->EOL("LSDA Encoding (pcrel sdata4)");
3523 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3524 Asm->EOL("FDE Encoding (pcrel sdata4)");
3526 Asm->EmitULEB128Bytes(1);
3527 Asm->EOL("Augmentation Size");
3529 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3530 Asm->EOL("FDE Encoding (pcrel sdata4)");
3533 // Indicate locations of general callee saved registers in frame.
3534 std::vector<MachineMove> Moves;
3535 RI->getInitialFrameState(Moves);
3536 EmitFrameMoves(NULL, 0, Moves, true);
3538 // On Darwin the linker honors the alignment of eh_frame, which means it
3539 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3540 // you get holes which confuse readers of eh_frame.
3541 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3543 EmitLabel("eh_frame_common_end", Index);
3548 /// EmitEHFrame - Emit function exception frame information.
3550 void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
3551 Function::LinkageTypes linkage = EHFrameInfo.function->getLinkage();
3553 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3555 // Externally visible entry into the functions eh frame info.
3556 // If the corresponding function is static, this should not be
3557 // externally visible.
3558 if (linkage != Function::InternalLinkage &&
3559 linkage != Function::PrivateLinkage) {
3560 if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
3561 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
3564 // If corresponding function is weak definition, this should be too.
3565 if ((linkage == Function::WeakAnyLinkage ||
3566 linkage == Function::WeakODRLinkage ||
3567 linkage == Function::LinkOnceAnyLinkage ||
3568 linkage == Function::LinkOnceODRLinkage) &&
3569 TAI->getWeakDefDirective())
3570 O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
3572 // If there are no calls then you can't unwind. This may mean we can
3573 // omit the EH Frame, but some environments do not handle weak absolute
3575 // If UnwindTablesMandatory is set we cannot do this optimization; the
3576 // unwind info is to be available for non-EH uses.
3577 if (!EHFrameInfo.hasCalls &&
3578 !UnwindTablesMandatory &&
3579 ((linkage != Function::WeakAnyLinkage &&
3580 linkage != Function::WeakODRLinkage &&
3581 linkage != Function::LinkOnceAnyLinkage &&
3582 linkage != Function::LinkOnceODRLinkage) ||
3583 !TAI->getWeakDefDirective() ||
3584 TAI->getSupportsWeakOmittedEHFrame()))
3586 O << EHFrameInfo.FnName << " = 0\n";
3587 // This name has no connection to the function, so it might get
3588 // dead-stripped when the function is not, erroneously. Prohibit
3589 // dead-stripping unconditionally.
3590 if (const char *UsedDirective = TAI->getUsedDirective())
3591 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3593 O << EHFrameInfo.FnName << ":\n";
3596 EmitDifference("eh_frame_end", EHFrameInfo.Number,
3597 "eh_frame_begin", EHFrameInfo.Number, true);
3598 Asm->EOL("Length of Frame Information Entry");
3600 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
3602 if (TAI->doesRequireNonLocalEHFrameLabel()) {
3603 PrintRelDirective(true, true);
3604 PrintLabelName("eh_frame_begin", EHFrameInfo.Number);
3606 if (!TAI->isAbsoluteEHSectionOffsets())
3607 O << "-EH_frame" << EHFrameInfo.PersonalityIndex;
3609 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
3610 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
3614 Asm->EOL("FDE CIE offset");
3616 EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
3617 Asm->EOL("FDE initial location");
3618 EmitDifference("eh_func_end", EHFrameInfo.Number,
3619 "eh_func_begin", EHFrameInfo.Number, true);
3620 Asm->EOL("FDE address range");
3622 // If there is a personality and landing pads then point to the language
3623 // specific data area in the exception table.
3624 if (EHFrameInfo.PersonalityIndex) {
3625 Asm->EmitULEB128Bytes(4);
3626 Asm->EOL("Augmentation size");
3628 if (EHFrameInfo.hasLandingPads)
3629 EmitReference("exception", EHFrameInfo.Number, true, true);
3631 Asm->EmitInt32((int)0);
3632 Asm->EOL("Language Specific Data Area");
3634 Asm->EmitULEB128Bytes(0);
3635 Asm->EOL("Augmentation size");
3638 // Indicate locations of function specific callee saved registers in
3640 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves,
3643 // On Darwin the linker honors the alignment of eh_frame, which means it
3644 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3645 // you get holes which confuse readers of eh_frame.
3646 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3648 EmitLabel("eh_frame_end", EHFrameInfo.Number);
3650 // If the function is marked used, this table should be also. We cannot
3651 // make the mark unconditional in this case, since retaining the table
3652 // also retains the function in this case, and there is code around
3653 // that depends on unused functions (calling undefined externals) being
3654 // dead-stripped to link correctly. Yes, there really is.
3655 if (MMI->getUsedFunctions().count(EHFrameInfo.function))
3656 if (const char *UsedDirective = TAI->getUsedDirective())
3657 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3661 /// EmitExceptionTable - Emit landing pads and actions.
3663 /// The general organization of the table is complex, but the basic concepts
3664 /// are easy. First there is a header which describes the location and
3665 /// organization of the three components that follow.
3666 /// 1. The landing pad site information describes the range of code covered
3667 /// by the try. In our case it's an accumulation of the ranges covered
3668 /// by the invokes in the try. There is also a reference to the landing
3669 /// pad that handles the exception once processed. Finally an index into
3670 /// the actions table.
3671 /// 2. The action table, in our case, is composed of pairs of type ids
3672 /// and next action offset. Starting with the action index from the
3673 /// landing pad site, each type Id is checked for a match to the current
3674 /// exception. If it matches then the exception and type id are passed
3675 /// on to the landing pad. Otherwise the next action is looked up. This
3676 /// chain is terminated with a next action of zero. If no type id is
3677 /// found the the frame is unwound and handling continues.
3678 /// 3. Type id table contains references to all the C++ typeinfo for all
3679 /// catches in the function. This tables is reversed indexed base 1.
3681 /// SharedTypeIds - How many leading type ids two landing pads have in common.
3682 static unsigned SharedTypeIds(const LandingPadInfo *L,
3683 const LandingPadInfo *R) {
3684 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3685 unsigned LSize = LIds.size(), RSize = RIds.size();
3686 unsigned MinSize = LSize < RSize ? LSize : RSize;
3689 for (; Count != MinSize; ++Count)
3690 if (LIds[Count] != RIds[Count])
3696 /// PadLT - Order landing pads lexicographically by type id.
3697 static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
3698 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3699 unsigned LSize = LIds.size(), RSize = RIds.size();
3700 unsigned MinSize = LSize < RSize ? LSize : RSize;
3702 for (unsigned i = 0; i != MinSize; ++i)
3703 if (LIds[i] != RIds[i])
3704 return LIds[i] < RIds[i];
3706 return LSize < RSize;
3710 static inline unsigned getEmptyKey() { return -1U; }
3711 static inline unsigned getTombstoneKey() { return -2U; }
3712 static unsigned getHashValue(const unsigned &Key) { return Key; }
3713 static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
3714 static bool isPod() { return true; }
3717 /// ActionEntry - Structure describing an entry in the actions table.
3718 struct ActionEntry {
3719 int ValueForTypeID; // The value to write - may not be equal to the type id.
3721 struct ActionEntry *Previous;
3724 /// PadRange - Structure holding a try-range and the associated landing pad.
3726 // The index of the landing pad.
3728 // The index of the begin and end labels in the landing pad's label lists.
3729 unsigned RangeIndex;
3732 typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
3734 /// CallSiteEntry - Structure describing an entry in the call-site table.
3735 struct CallSiteEntry {
3736 // The 'try-range' is BeginLabel .. EndLabel.
3737 unsigned BeginLabel; // zero indicates the start of the function.
3738 unsigned EndLabel; // zero indicates the end of the function.
3739 // The landing pad starts at PadLabel.
3740 unsigned PadLabel; // zero indicates that there is no landing pad.
3744 void EmitExceptionTable() {
3745 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
3746 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
3747 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
3748 if (PadInfos.empty()) return;
3750 // Sort the landing pads in order of their type ids. This is used to fold
3751 // duplicate actions.
3752 SmallVector<const LandingPadInfo *, 64> LandingPads;
3753 LandingPads.reserve(PadInfos.size());
3754 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
3755 LandingPads.push_back(&PadInfos[i]);
3756 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
3758 // Negative type ids index into FilterIds, positive type ids index into
3759 // TypeInfos. The value written for a positive type id is just the type
3760 // id itself. For a negative type id, however, the value written is the
3761 // (negative) byte offset of the corresponding FilterIds entry. The byte
3762 // offset is usually equal to the type id, because the FilterIds entries
3763 // are written using a variable width encoding which outputs one byte per
3764 // entry as long as the value written is not too large, but can differ.
3765 // This kind of complication does not occur for positive type ids because
3766 // type infos are output using a fixed width encoding.
3767 // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
3768 SmallVector<int, 16> FilterOffsets;
3769 FilterOffsets.reserve(FilterIds.size());
3771 for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
3772 E = FilterIds.end(); I != E; ++I) {
3773 FilterOffsets.push_back(Offset);
3774 Offset -= TargetAsmInfo::getULEB128Size(*I);
3777 // Compute the actions table and gather the first action index for each
3778 // landing pad site.
3779 SmallVector<ActionEntry, 32> Actions;
3780 SmallVector<unsigned, 64> FirstActions;
3781 FirstActions.reserve(LandingPads.size());
3783 int FirstAction = 0;
3784 unsigned SizeActions = 0;
3785 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3786 const LandingPadInfo *LP = LandingPads[i];
3787 const std::vector<int> &TypeIds = LP->TypeIds;
3788 const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
3789 unsigned SizeSiteActions = 0;
3791 if (NumShared < TypeIds.size()) {
3792 unsigned SizeAction = 0;
3793 ActionEntry *PrevAction = 0;
3796 const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
3797 assert(Actions.size());
3798 PrevAction = &Actions.back();
3799 SizeAction = TargetAsmInfo::getSLEB128Size(PrevAction->NextAction) +
3800 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3801 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
3803 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3804 SizeAction += -PrevAction->NextAction;
3805 PrevAction = PrevAction->Previous;
3809 // Compute the actions.
3810 for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
3811 int TypeID = TypeIds[I];
3812 assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
3813 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
3814 unsigned SizeTypeID = TargetAsmInfo::getSLEB128Size(ValueForTypeID);
3816 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
3817 SizeAction = SizeTypeID + TargetAsmInfo::getSLEB128Size(NextAction);
3818 SizeSiteActions += SizeAction;
3820 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
3821 Actions.push_back(Action);
3823 PrevAction = &Actions.back();
3826 // Record the first action of the landing pad site.
3827 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
3828 } // else identical - re-use previous FirstAction
3830 FirstActions.push_back(FirstAction);
3832 // Compute this sites contribution to size.
3833 SizeActions += SizeSiteActions;
3836 // Compute the call-site table. The entry for an invoke has a try-range
3837 // containing the call, a non-zero landing pad and an appropriate action.
3838 // The entry for an ordinary call has a try-range containing the call and
3839 // zero for the landing pad and the action. Calls marked 'nounwind' have
3840 // no entry and must not be contained in the try-range of any entry - they
3841 // form gaps in the table. Entries must be ordered by try-range address.
3842 SmallVector<CallSiteEntry, 64> CallSites;
3844 RangeMapType PadMap;
3845 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
3846 // by try-range labels when lowered). Ordinary calls do not, so appropriate
3847 // try-ranges for them need be deduced.
3848 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3849 const LandingPadInfo *LandingPad = LandingPads[i];
3850 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
3851 unsigned BeginLabel = LandingPad->BeginLabels[j];
3852 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
3853 PadRange P = { i, j };
3854 PadMap[BeginLabel] = P;
3858 // The end label of the previous invoke or nounwind try-range.
3859 unsigned LastLabel = 0;
3861 // Whether there is a potentially throwing instruction (currently this means
3862 // an ordinary call) between the end of the previous try-range and now.
3863 bool SawPotentiallyThrowing = false;
3865 // Whether the last callsite entry was for an invoke.
3866 bool PreviousIsInvoke = false;
3868 // Visit all instructions in order of address.
3869 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
3871 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
3873 if (!MI->isLabel()) {
3874 SawPotentiallyThrowing |= MI->getDesc().isCall();
3878 unsigned BeginLabel = MI->getOperand(0).getImm();
3879 assert(BeginLabel && "Invalid label!");
3881 // End of the previous try-range?
3882 if (BeginLabel == LastLabel)
3883 SawPotentiallyThrowing = false;
3885 // Beginning of a new try-range?
3886 RangeMapType::iterator L = PadMap.find(BeginLabel);
3887 if (L == PadMap.end())
3888 // Nope, it was just some random label.
3891 PadRange P = L->second;
3892 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
3894 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
3895 "Inconsistent landing pad map!");
3897 // If some instruction between the previous try-range and this one may
3898 // throw, create a call-site entry with no landing pad for the region
3899 // between the try-ranges.
3900 if (SawPotentiallyThrowing) {
3901 CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
3902 CallSites.push_back(Site);
3903 PreviousIsInvoke = false;
3906 LastLabel = LandingPad->EndLabels[P.RangeIndex];
3907 assert(BeginLabel && LastLabel && "Invalid landing pad!");
3909 if (LandingPad->LandingPadLabel) {
3910 // This try-range is for an invoke.
3911 CallSiteEntry Site = {BeginLabel, LastLabel,
3912 LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
3914 // Try to merge with the previous call-site.
3915 if (PreviousIsInvoke) {
3916 CallSiteEntry &Prev = CallSites.back();
3917 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
3918 // Extend the range of the previous entry.
3919 Prev.EndLabel = Site.EndLabel;
3924 // Otherwise, create a new call-site.
3925 CallSites.push_back(Site);
3926 PreviousIsInvoke = true;
3929 PreviousIsInvoke = false;
3933 // If some instruction between the previous try-range and the end of the
3934 // function may throw, create a call-site entry with no landing pad for the
3935 // region following the try-range.
3936 if (SawPotentiallyThrowing) {
3937 CallSiteEntry Site = {LastLabel, 0, 0, 0};
3938 CallSites.push_back(Site);
3944 const unsigned SiteStartSize = sizeof(int32_t); // DW_EH_PE_udata4
3945 const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
3946 const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
3947 unsigned SizeSites = CallSites.size() * (SiteStartSize +
3950 for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
3951 SizeSites += TargetAsmInfo::getULEB128Size(CallSites[i].Action);
3954 const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
3955 unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
3957 unsigned TypeOffset = sizeof(int8_t) + // Call site format
3958 TargetAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
3959 SizeSites + SizeActions + SizeTypes;
3961 unsigned TotalSize = sizeof(int8_t) + // LPStart format
3962 sizeof(int8_t) + // TType format
3963 TargetAsmInfo::getULEB128Size(TypeOffset) + // TType base offset
3966 unsigned SizeAlign = (4 - TotalSize) & 3;
3968 // Begin the exception table.
3969 Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
3970 Asm->EmitAlignment(2, 0, 0, false);
3971 O << "GCC_except_table" << SubprogramCount << ":\n";
3972 for (unsigned i = 0; i != SizeAlign; ++i) {
3974 Asm->EOL("Padding");
3976 EmitLabel("exception", SubprogramCount);
3979 Asm->EmitInt8(DW_EH_PE_omit);
3980 Asm->EOL("LPStart format (DW_EH_PE_omit)");
3981 Asm->EmitInt8(DW_EH_PE_absptr);
3982 Asm->EOL("TType format (DW_EH_PE_absptr)");
3983 Asm->EmitULEB128Bytes(TypeOffset);
3984 Asm->EOL("TType base offset");
3985 Asm->EmitInt8(DW_EH_PE_udata4);
3986 Asm->EOL("Call site format (DW_EH_PE_udata4)");
3987 Asm->EmitULEB128Bytes(SizeSites);
3988 Asm->EOL("Call-site table length");
3990 // Emit the landing pad site information.
3991 for (unsigned i = 0; i < CallSites.size(); ++i) {
3992 CallSiteEntry &S = CallSites[i];
3993 const char *BeginTag;
3994 unsigned BeginNumber;
3996 if (!S.BeginLabel) {
3997 BeginTag = "eh_func_begin";
3998 BeginNumber = SubprogramCount;
4001 BeginNumber = S.BeginLabel;
4004 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
4006 Asm->EOL("Region start");
4009 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
4012 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
4014 Asm->EOL("Region length");
4019 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
4021 Asm->EOL("Landing pad");
4023 Asm->EmitULEB128Bytes(S.Action);
4027 // Emit the actions.
4028 for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
4029 ActionEntry &Action = Actions[I];
4031 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
4032 Asm->EOL("TypeInfo index");
4033 Asm->EmitSLEB128Bytes(Action.NextAction);
4034 Asm->EOL("Next action");
4037 // Emit the type ids.
4038 for (unsigned M = TypeInfos.size(); M; --M) {
4039 GlobalVariable *GV = TypeInfos[M - 1];
4041 PrintRelDirective();
4044 O << Asm->getGlobalLinkName(GV);
4048 Asm->EOL("TypeInfo");
4051 // Emit the filter typeids.
4052 for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
4053 unsigned TypeID = FilterIds[j];
4054 Asm->EmitULEB128Bytes(TypeID);
4055 Asm->EOL("Filter TypeInfo index");
4058 Asm->EmitAlignment(2, 0, 0, false);
4062 //===--------------------------------------------------------------------===//
4063 // Main entry points.
4065 DwarfException(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
4066 : Dwarf(OS, A, T, "eh"), shouldEmitTable(false), shouldEmitMoves(false),
4067 shouldEmitTableModule(false), shouldEmitMovesModule(false),
4069 if (TimePassesIsEnabled)
4070 ExceptionTimer = new Timer("Dwarf Exception Writer",
4071 *getDwarfTimerGroup());
4074 virtual ~DwarfException() {
4075 delete ExceptionTimer;
4078 /// SetModuleInfo - Set machine module information when it's known that pass
4079 /// manager has created it. Set by the target AsmPrinter.
4080 void SetModuleInfo(MachineModuleInfo *mmi) {
4084 /// BeginModule - Emit all exception information that should come prior to the
4086 void BeginModule(Module *M) {
4090 /// EndModule - Emit all exception information that should come after the
4093 if (TimePassesIsEnabled)
4094 ExceptionTimer->startTimer();
4096 if (shouldEmitMovesModule || shouldEmitTableModule) {
4097 const std::vector<Function *> Personalities = MMI->getPersonalities();
4098 for (unsigned i = 0; i < Personalities.size(); ++i)
4099 EmitCommonEHFrame(Personalities[i], i);
4101 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
4102 E = EHFrames.end(); I != E; ++I)
4106 if (TimePassesIsEnabled)
4107 ExceptionTimer->stopTimer();
4110 /// BeginFunction - Gather pre-function exception information. Assumes being
4111 /// emitted immediately after the function entry point.
4112 void BeginFunction(MachineFunction *MF) {
4113 if (TimePassesIsEnabled)
4114 ExceptionTimer->startTimer();
4117 shouldEmitTable = shouldEmitMoves = false;
4119 if (MMI && TAI->doesSupportExceptionHandling()) {
4120 // Map all labels and get rid of any dead landing pads.
4121 MMI->TidyLandingPads();
4123 // If any landing pads survive, we need an EH table.
4124 if (MMI->getLandingPads().size())
4125 shouldEmitTable = true;
4127 // See if we need frame move info.
4128 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
4129 shouldEmitMoves = true;
4131 if (shouldEmitMoves || shouldEmitTable)
4132 // Assumes in correct section after the entry point.
4133 EmitLabel("eh_func_begin", ++SubprogramCount);
4136 shouldEmitTableModule |= shouldEmitTable;
4137 shouldEmitMovesModule |= shouldEmitMoves;
4139 if (TimePassesIsEnabled)
4140 ExceptionTimer->stopTimer();
4143 /// EndFunction - Gather and emit post-function exception information.
4145 void EndFunction() {
4146 if (TimePassesIsEnabled)
4147 ExceptionTimer->startTimer();
4149 if (shouldEmitMoves || shouldEmitTable) {
4150 EmitLabel("eh_func_end", SubprogramCount);
4151 EmitExceptionTable();
4153 // Save EH frame information
4155 push_back(FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
4157 MMI->getPersonalityIndex(),
4158 MF->getFrameInfo()->hasCalls(),
4159 !MMI->getLandingPads().empty(),
4160 MMI->getFrameMoves(),
4161 MF->getFunction()));
4164 if (TimePassesIsEnabled)
4165 ExceptionTimer->stopTimer();
4169 } // End of namespace llvm
4171 //===----------------------------------------------------------------------===//
4173 /// Emit - Print the abbreviation using the specified Dwarf writer.
4175 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
4176 // Emit its Dwarf tag type.
4177 DD.getAsm()->EmitULEB128Bytes(Tag);
4178 DD.getAsm()->EOL(TagString(Tag));
4180 // Emit whether it has children DIEs.
4181 DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
4182 DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
4184 // For each attribute description.
4185 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4186 const DIEAbbrevData &AttrData = Data[i];
4188 // Emit attribute type.
4189 DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
4190 DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
4193 DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
4194 DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
4197 // Mark end of abbreviation.
4198 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
4199 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
4203 void DIEAbbrev::print(std::ostream &O) {
4204 O << "Abbreviation @"
4205 << std::hex << (intptr_t)this << std::dec
4209 << ChildrenString(ChildrenFlag)
4212 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4214 << AttributeString(Data[i].getAttribute())
4216 << FormEncodingString(Data[i].getForm())
4220 void DIEAbbrev::dump() { print(cerr); }
4223 //===----------------------------------------------------------------------===//
4226 void DIEValue::dump() {
4231 //===----------------------------------------------------------------------===//
4233 /// EmitValue - Emit integer of appropriate size.
4235 void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
4237 case DW_FORM_flag: // Fall thru
4238 case DW_FORM_ref1: // Fall thru
4239 case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer); break;
4240 case DW_FORM_ref2: // Fall thru
4241 case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer); break;
4242 case DW_FORM_ref4: // Fall thru
4243 case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer); break;
4244 case DW_FORM_ref8: // Fall thru
4245 case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer); break;
4246 case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
4247 case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
4248 default: assert(0 && "DIE Value form not supported yet"); break;
4252 /// SizeOf - Determine size of integer value in bytes.
4254 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4256 case DW_FORM_flag: // Fall thru
4257 case DW_FORM_ref1: // Fall thru
4258 case DW_FORM_data1: return sizeof(int8_t);
4259 case DW_FORM_ref2: // Fall thru
4260 case DW_FORM_data2: return sizeof(int16_t);
4261 case DW_FORM_ref4: // Fall thru
4262 case DW_FORM_data4: return sizeof(int32_t);
4263 case DW_FORM_ref8: // Fall thru
4264 case DW_FORM_data8: return sizeof(int64_t);
4265 case DW_FORM_udata: return TargetAsmInfo::getULEB128Size(Integer);
4266 case DW_FORM_sdata: return TargetAsmInfo::getSLEB128Size(Integer);
4267 default: assert(0 && "DIE Value form not supported yet"); break;
4272 //===----------------------------------------------------------------------===//
4274 /// EmitValue - Emit string value.
4276 void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
4277 DD.getAsm()->EmitString(String);
4280 //===----------------------------------------------------------------------===//
4282 /// EmitValue - Emit label value.
4284 void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4285 bool IsSmall = Form == DW_FORM_data4;
4286 DD.EmitReference(Label, false, IsSmall);
4289 /// SizeOf - Determine size of label value in bytes.
4291 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4292 if (Form == DW_FORM_data4) return 4;
4293 return DD.getTargetData()->getPointerSize();
4296 //===----------------------------------------------------------------------===//
4298 /// EmitValue - Emit label value.
4300 void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4301 bool IsSmall = Form == DW_FORM_data4;
4302 DD.EmitReference(Label, false, IsSmall);
4305 /// SizeOf - Determine size of label value in bytes.
4307 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4308 if (Form == DW_FORM_data4) return 4;
4309 return DD.getTargetData()->getPointerSize();
4312 //===----------------------------------------------------------------------===//
4314 /// EmitValue - Emit delta value.
4316 void DIESectionOffset::EmitValue(DwarfDebug &DD, unsigned Form) {
4317 bool IsSmall = Form == DW_FORM_data4;
4318 DD.EmitSectionOffset(Label.Tag, Section.Tag,
4319 Label.Number, Section.Number, IsSmall, IsEH, UseSet);
4322 /// SizeOf - Determine size of delta value in bytes.
4324 unsigned DIESectionOffset::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4325 if (Form == DW_FORM_data4) return 4;
4326 return DD.getTargetData()->getPointerSize();
4329 //===----------------------------------------------------------------------===//
4331 /// EmitValue - Emit delta value.
4333 void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
4334 bool IsSmall = Form == DW_FORM_data4;
4335 DD.EmitDifference(LabelHi, LabelLo, IsSmall);
4338 /// SizeOf - Determine size of delta value in bytes.
4340 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4341 if (Form == DW_FORM_data4) return 4;
4342 return DD.getTargetData()->getPointerSize();
4345 //===----------------------------------------------------------------------===//
4347 /// EmitValue - Emit debug information entry offset.
4349 void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
4350 DD.getAsm()->EmitInt32(Entry->getOffset());
4353 //===----------------------------------------------------------------------===//
4355 /// ComputeSize - calculate the size of the block.
4357 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
4359 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4361 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4362 Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
4368 /// EmitValue - Emit block data.
4370 void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
4372 case DW_FORM_block1: DD.getAsm()->EmitInt8(Size); break;
4373 case DW_FORM_block2: DD.getAsm()->EmitInt16(Size); break;
4374 case DW_FORM_block4: DD.getAsm()->EmitInt32(Size); break;
4375 case DW_FORM_block: DD.getAsm()->EmitULEB128Bytes(Size); break;
4376 default: assert(0 && "Improper form for block"); break;
4379 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4381 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4383 Values[i]->EmitValue(DD, AbbrevData[i].getForm());
4387 /// SizeOf - Determine size of block data in bytes.
4389 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4391 case DW_FORM_block1: return Size + sizeof(int8_t);
4392 case DW_FORM_block2: return Size + sizeof(int16_t);
4393 case DW_FORM_block4: return Size + sizeof(int32_t);
4394 case DW_FORM_block: return Size + TargetAsmInfo::getULEB128Size(Size);
4395 default: assert(0 && "Improper form for block"); break;
4400 //===----------------------------------------------------------------------===//
4401 /// DIE Implementation
4404 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4408 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
4410 void DIE::AddSiblingOffset() {
4411 DIEInteger *DI = new DIEInteger(0);
4412 Values.insert(Values.begin(), DI);
4413 Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
4416 /// Profile - Used to gather unique data for the value folding set.
4418 void DIE::Profile(FoldingSetNodeID &ID) {
4421 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4422 ID.AddPointer(Children[i]);
4424 for (unsigned j = 0, M = Values.size(); j < M; ++j)
4425 ID.AddPointer(Values[j]);
4429 void DIE::print(std::ostream &O, unsigned IncIndent) {
4430 static unsigned IndentCount = 0;
4431 IndentCount += IncIndent;
4432 const std::string Indent(IndentCount, ' ');
4433 bool isBlock = Abbrev.getTag() == 0;
4438 << "0x" << std::hex << (intptr_t)this << std::dec
4439 << ", Offset: " << Offset
4440 << ", Size: " << Size
4444 << TagString(Abbrev.getTag())
4446 << ChildrenString(Abbrev.getChildrenFlag());
4448 O << "Size: " << Size;
4452 const SmallVector<DIEAbbrevData, 8> &Data = Abbrev.getData();
4455 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4459 O << AttributeString(Data[i].getAttribute());
4461 O << "Blk[" << i << "]";
4464 << FormEncodingString(Data[i].getForm())
4466 Values[i]->print(O);
4471 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
4472 Children[j]->print(O, 4);
4475 if (!isBlock) O << "\n";
4476 IndentCount -= IncIndent;
4484 //===----------------------------------------------------------------------===//
4485 /// DwarfWriter Implementation
4488 DwarfWriter::DwarfWriter()
4489 : ImmutablePass(&ID), DD(0), DE(0) {}
4491 DwarfWriter::~DwarfWriter() {
4494 delete DwarfTimerGroup; DwarfTimerGroup = 0;
4497 /// BeginModule - Emit all Dwarf sections that should come prior to the
4499 void DwarfWriter::BeginModule(Module *M,
4500 MachineModuleInfo *MMI,
4501 raw_ostream &OS, AsmPrinter *A,
4502 const TargetAsmInfo *T) {
4503 DE = new DwarfException(OS, A, T);
4504 DD = new DwarfDebug(OS, A, T);
4507 DD->SetDebugInfo(MMI);
4508 DE->SetModuleInfo(MMI);
4511 /// EndModule - Emit all Dwarf sections that should come after the content.
4513 void DwarfWriter::EndModule() {
4518 /// BeginFunction - Gather pre-function debug information. Assumes being
4519 /// emitted immediately after the function entry point.
4520 void DwarfWriter::BeginFunction(MachineFunction *MF) {
4521 DE->BeginFunction(MF);
4522 DD->BeginFunction(MF);
4525 /// EndFunction - Gather and emit post-function debug information.
4527 void DwarfWriter::EndFunction(MachineFunction *MF) {
4528 DD->EndFunction(MF);
4531 if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI())
4532 // Clear function debug information.
4536 /// ValidDebugInfo - Return true if V represents valid debug info value.
4537 bool DwarfWriter::ValidDebugInfo(Value *V) {
4538 return DD && DD->ValidDebugInfo(V);
4541 /// RecordSourceLine - Records location information and associates it with a
4542 /// label. Returns a unique label ID used to generate a label and provide
4543 /// correspondence to the source line list.
4544 unsigned DwarfWriter::RecordSourceLine(unsigned Line, unsigned Col,
4546 return DD->RecordSourceLine(Line, Col, Src);
4549 /// getOrCreateSourceID - Look up the source id with the given directory and
4550 /// source file names. If none currently exists, create a new id and insert it
4551 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames maps
4553 unsigned DwarfWriter::getOrCreateSourceID(const std::string &DirName,
4554 const std::string &FileName) {
4555 return DD->getOrCreateSourceID(DirName, FileName);
4558 /// RecordRegionStart - Indicate the start of a region.
4559 unsigned DwarfWriter::RecordRegionStart(GlobalVariable *V) {
4560 return DD->RecordRegionStart(V);
4563 /// RecordRegionEnd - Indicate the end of a region.
4564 unsigned DwarfWriter::RecordRegionEnd(GlobalVariable *V) {
4565 return DD->RecordRegionEnd(V);
4568 /// getRecordSourceLineCount - Count source lines.
4569 unsigned DwarfWriter::getRecordSourceLineCount() {
4570 return DD->getRecordSourceLineCount();
4573 /// RecordVariable - Indicate the declaration of a local variable.
4575 void DwarfWriter::RecordVariable(GlobalVariable *GV, unsigned FrameIndex) {
4576 DD->RecordVariable(GV, FrameIndex);
4579 /// ShouldEmitDwarfDebug - Returns true if Dwarf debugging declarations should
4581 bool DwarfWriter::ShouldEmitDwarfDebug() const {
4582 return DD->ShouldEmitDwarfDebug();