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 &getDwarfTimerGroup() {
52 static TimerGroup DwarfTimerGroup("Dwarf Exception and Debugging");
53 return DwarfTimerGroup;
58 //===----------------------------------------------------------------------===//
60 /// Configuration values for initial hash set sizes (log2).
62 static const unsigned InitDiesSetSize = 9; // log2(512)
63 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
64 static const unsigned InitValuesSetSize = 9; // log2(512)
66 //===----------------------------------------------------------------------===//
67 /// Forward declarations.
72 //===----------------------------------------------------------------------===//
75 /// getGlobalVariable - Return either a direct or cast Global value.
77 static GlobalVariable *getGlobalVariable(Value *V) {
78 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
80 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
81 if (CE->getOpcode() == Instruction::BitCast) {
82 return dyn_cast<GlobalVariable>(CE->getOperand(0));
83 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
84 for (unsigned int i=1; i<CE->getNumOperands(); i++) {
85 if (!CE->getOperand(i)->isNullValue())
88 return dyn_cast<GlobalVariable>(CE->getOperand(0));
94 //===----------------------------------------------------------------------===//
95 /// DWLabel - Labels are used to track locations in the assembler file.
96 /// Labels appear in the form @verbatim <prefix><Tag><Number> @endverbatim,
97 /// where the tag is a category of label (Ex. location) and number is a value
98 /// unique in that category.
101 /// Tag - Label category tag. Should always be a staticly declared C string.
105 /// Number - Value to make label unique.
109 DWLabel(const char *T, unsigned N) : Tag(T), Number(N) {}
111 void Profile(FoldingSetNodeID &ID) const {
113 ID.AddInteger(Number);
117 void print(std::ostream *O) const {
120 void print(std::ostream &O) const {
122 if (Number) O << Number;
127 //===----------------------------------------------------------------------===//
128 /// DIEAbbrevData - Dwarf abbreviation data, describes the one attribute of a
129 /// Dwarf abbreviation.
130 class DIEAbbrevData {
131 /// Attribute - Dwarf attribute code.
135 /// Form - Dwarf form code.
139 DIEAbbrevData(unsigned A, unsigned F) : Attribute(A), Form(F) {}
142 unsigned getAttribute() const { return Attribute; }
143 unsigned getForm() const { return Form; }
145 /// Profile - Used to gather unique data for the abbreviation folding set.
147 void Profile(FoldingSetNodeID &ID)const {
148 ID.AddInteger(Attribute);
153 //===----------------------------------------------------------------------===//
154 /// DIEAbbrev - Dwarf abbreviation, describes the organization of a debug
155 /// information object.
156 class DIEAbbrev : public FoldingSetNode {
158 /// Tag - Dwarf tag code.
162 /// Unique number for node.
166 /// ChildrenFlag - Dwarf children flag.
168 unsigned ChildrenFlag;
170 /// Data - Raw data bytes for abbreviation.
172 SmallVector<DIEAbbrevData, 8> Data;
174 DIEAbbrev(unsigned T, unsigned C) : Tag(T), ChildrenFlag(C), Data() {}
175 virtual ~DIEAbbrev() {}
178 unsigned getTag() const { return Tag; }
179 unsigned getNumber() const { return Number; }
180 unsigned getChildrenFlag() const { return ChildrenFlag; }
181 const SmallVector<DIEAbbrevData, 8> &getData() const { return Data; }
182 void setTag(unsigned T) { Tag = T; }
183 void setChildrenFlag(unsigned CF) { ChildrenFlag = CF; }
184 void setNumber(unsigned N) { Number = N; }
186 /// AddAttribute - Adds another set of attribute information to the
188 void AddAttribute(unsigned Attribute, unsigned Form) {
189 Data.push_back(DIEAbbrevData(Attribute, Form));
192 /// AddFirstAttribute - Adds a set of attribute information to the front
193 /// of the abbreviation.
194 void AddFirstAttribute(unsigned Attribute, unsigned Form) {
195 Data.insert(Data.begin(), DIEAbbrevData(Attribute, Form));
198 /// Profile - Used to gather unique data for the abbreviation folding set.
200 void Profile(FoldingSetNodeID &ID) {
202 ID.AddInteger(ChildrenFlag);
204 // For each attribute description.
205 for (unsigned i = 0, N = Data.size(); i < N; ++i)
209 /// Emit - Print the abbreviation using the specified Dwarf writer.
211 void Emit(const DwarfDebug &DD) const;
214 void print(std::ostream *O) {
217 void print(std::ostream &O);
222 //===----------------------------------------------------------------------===//
223 /// DIE - A structured debug information entry. Has an abbreviation which
224 /// describes it's organization.
225 class DIE : public FoldingSetNode {
227 /// Abbrev - Buffer for constructing abbreviation.
231 /// Offset - Offset in debug info section.
235 /// Size - Size of instance + children.
241 std::vector<DIE *> Children;
243 /// Attributes values.
245 SmallVector<DIEValue*, 32> Values;
248 explicit DIE(unsigned Tag)
249 : Abbrev(Tag, DW_CHILDREN_no), Offset(0), Size(0), Children(), Values() {}
253 DIEAbbrev &getAbbrev() { return Abbrev; }
254 unsigned getAbbrevNumber() const {
255 return Abbrev.getNumber();
257 unsigned getTag() const { return Abbrev.getTag(); }
258 unsigned getOffset() const { return Offset; }
259 unsigned getSize() const { return Size; }
260 const std::vector<DIE *> &getChildren() const { return Children; }
261 SmallVector<DIEValue*, 32> &getValues() { return Values; }
262 void setTag(unsigned Tag) { Abbrev.setTag(Tag); }
263 void setOffset(unsigned O) { Offset = O; }
264 void setSize(unsigned S) { Size = S; }
266 /// AddValue - Add a value and attributes to a DIE.
268 void AddValue(unsigned Attribute, unsigned Form, DIEValue *Value) {
269 Abbrev.AddAttribute(Attribute, Form);
270 Values.push_back(Value);
273 /// SiblingOffset - Return the offset of the debug information entry's
275 unsigned SiblingOffset() const { return Offset + Size; }
277 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
279 void AddSiblingOffset();
281 /// AddChild - Add a child to the DIE.
283 void AddChild(DIE *Child) {
284 Abbrev.setChildrenFlag(DW_CHILDREN_yes);
285 Children.push_back(Child);
288 /// Detach - Detaches objects connected to it after copying.
294 /// Profile - Used to gather unique data for the value folding set.
296 void Profile(FoldingSetNodeID &ID) ;
299 void print(std::ostream *O, unsigned IncIndent = 0) {
300 if (O) print(*O, IncIndent);
302 void print(std::ostream &O, unsigned IncIndent = 0);
307 //===----------------------------------------------------------------------===//
308 /// DIEValue - A debug information entry value.
310 class DIEValue : public FoldingSetNode {
323 /// Type - Type of data stored in the value.
327 explicit DIEValue(unsigned T) : Type(T) {}
328 virtual ~DIEValue() {}
331 unsigned getType() const { return Type; }
333 // Implement isa/cast/dyncast.
334 static bool classof(const DIEValue *) { return true; }
336 /// EmitValue - Emit value via the Dwarf writer.
338 virtual void EmitValue(DwarfDebug &DD, unsigned Form) = 0;
340 /// SizeOf - Return the size of a value in bytes.
342 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const = 0;
344 /// Profile - Used to gather unique data for the value folding set.
346 virtual void Profile(FoldingSetNodeID &ID) = 0;
349 void print(std::ostream *O) {
352 virtual void print(std::ostream &O) = 0;
357 //===----------------------------------------------------------------------===//
358 /// DWInteger - An integer value DIE.
360 class DIEInteger : public DIEValue {
365 explicit DIEInteger(uint64_t I) : DIEValue(isInteger), Integer(I) {}
367 // Implement isa/cast/dyncast.
368 static bool classof(const DIEInteger *) { return true; }
369 static bool classof(const DIEValue *I) { return I->Type == isInteger; }
371 /// BestForm - Choose the best form for integer.
373 static unsigned BestForm(bool IsSigned, uint64_t Integer) {
375 if ((char)Integer == (signed)Integer) return DW_FORM_data1;
376 if ((short)Integer == (signed)Integer) return DW_FORM_data2;
377 if ((int)Integer == (signed)Integer) return DW_FORM_data4;
379 if ((unsigned char)Integer == Integer) return DW_FORM_data1;
380 if ((unsigned short)Integer == Integer) return DW_FORM_data2;
381 if ((unsigned int)Integer == Integer) return DW_FORM_data4;
383 return DW_FORM_data8;
386 /// EmitValue - Emit integer of appropriate size.
388 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
390 /// SizeOf - Determine size of integer value in bytes.
392 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
394 /// Profile - Used to gather unique data for the value folding set.
396 static void Profile(FoldingSetNodeID &ID, unsigned Integer) {
397 ID.AddInteger(isInteger);
398 ID.AddInteger(Integer);
400 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Integer); }
403 virtual void print(std::ostream &O) {
404 O << "Int: " << (int64_t)Integer
405 << " 0x" << std::hex << Integer << std::dec;
410 //===----------------------------------------------------------------------===//
411 /// DIEString - A string value DIE.
413 class DIEString : public DIEValue {
414 const std::string Str;
416 explicit DIEString(const std::string &S) : DIEValue(isString), Str(S) {}
418 // Implement isa/cast/dyncast.
419 static bool classof(const DIEString *) { return true; }
420 static bool classof(const DIEValue *S) { return S->Type == isString; }
422 /// EmitValue - Emit string value.
424 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
426 /// SizeOf - Determine size of string value in bytes.
428 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
429 return Str.size() + sizeof(char); // sizeof('\0');
432 /// Profile - Used to gather unique data for the value folding set.
434 static void Profile(FoldingSetNodeID &ID, const std::string &Str) {
435 ID.AddInteger(isString);
438 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Str); }
441 virtual void print(std::ostream &O) {
442 O << "Str: \"" << Str << "\"";
447 //===----------------------------------------------------------------------===//
448 /// DIEDwarfLabel - A Dwarf internal label expression DIE.
450 class DIEDwarfLabel : public DIEValue {
453 explicit DIEDwarfLabel(const DWLabel &L) : DIEValue(isLabel), Label(L) {}
455 // Implement isa/cast/dyncast.
456 static bool classof(const DIEDwarfLabel *) { return true; }
457 static bool classof(const DIEValue *L) { return L->Type == isLabel; }
459 /// EmitValue - Emit label value.
461 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
463 /// SizeOf - Determine size of label value in bytes.
465 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
467 /// Profile - Used to gather unique data for the value folding set.
469 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label) {
470 ID.AddInteger(isLabel);
473 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
476 virtual void print(std::ostream &O) {
483 //===----------------------------------------------------------------------===//
484 /// DIEObjectLabel - A label to an object in code or data.
486 class DIEObjectLabel : public DIEValue {
487 const std::string Label;
489 explicit DIEObjectLabel(const std::string &L)
490 : DIEValue(isAsIsLabel), Label(L) {}
492 // Implement isa/cast/dyncast.
493 static bool classof(const DIEObjectLabel *) { return true; }
494 static bool classof(const DIEValue *L) { return L->Type == isAsIsLabel; }
496 /// EmitValue - Emit label value.
498 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
500 /// SizeOf - Determine size of label value in bytes.
502 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
504 /// Profile - Used to gather unique data for the value folding set.
506 static void Profile(FoldingSetNodeID &ID, const std::string &Label) {
507 ID.AddInteger(isAsIsLabel);
510 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label.c_str()); }
513 virtual void print(std::ostream &O) {
514 O << "Obj: " << Label;
519 //===----------------------------------------------------------------------===//
520 /// DIESectionOffset - A section offset DIE.
522 class DIESectionOffset : public DIEValue {
524 const DWLabel Section;
528 DIESectionOffset(const DWLabel &Lab, const DWLabel &Sec,
529 bool isEH = false, bool useSet = true)
530 : DIEValue(isSectionOffset), Label(Lab), Section(Sec),
531 IsEH(isEH), UseSet(useSet) {}
533 // Implement isa/cast/dyncast.
534 static bool classof(const DIESectionOffset *) { return true; }
535 static bool classof(const DIEValue *D) { return D->Type == isSectionOffset; }
537 /// EmitValue - Emit section offset.
539 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
541 /// SizeOf - Determine size of section offset value in bytes.
543 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
545 /// Profile - Used to gather unique data for the value folding set.
547 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label,
548 const DWLabel &Section) {
549 ID.AddInteger(isSectionOffset);
552 // IsEH and UseSet are specific to the Label/Section that we will emit
553 // the offset for; so Label/Section are enough for uniqueness.
555 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label, Section); }
558 virtual void print(std::ostream &O) {
563 O << "-" << IsEH << "-" << UseSet;
568 //===----------------------------------------------------------------------===//
569 /// DIEDelta - A simple label difference DIE.
571 class DIEDelta : public DIEValue {
572 const DWLabel LabelHi;
573 const DWLabel LabelLo;
575 DIEDelta(const DWLabel &Hi, const DWLabel &Lo)
576 : DIEValue(isDelta), LabelHi(Hi), LabelLo(Lo) {}
578 // Implement isa/cast/dyncast.
579 static bool classof(const DIEDelta *) { return true; }
580 static bool classof(const DIEValue *D) { return D->Type == isDelta; }
582 /// EmitValue - Emit delta value.
584 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
586 /// SizeOf - Determine size of delta value in bytes.
588 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
590 /// Profile - Used to gather unique data for the value folding set.
592 static void Profile(FoldingSetNodeID &ID, const DWLabel &LabelHi,
593 const DWLabel &LabelLo) {
594 ID.AddInteger(isDelta);
598 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, LabelHi, LabelLo); }
601 virtual void print(std::ostream &O) {
610 //===----------------------------------------------------------------------===//
611 /// DIEntry - A pointer to another debug information entry. An instance of this
612 /// class can also be used as a proxy for a debug information entry not yet
613 /// defined (ie. types.)
614 class DIEntry : public DIEValue {
617 explicit DIEntry(DIE *E) : DIEValue(isEntry), Entry(E) {}
619 void setEntry(DIE *E) { Entry = E; }
621 // Implement isa/cast/dyncast.
622 static bool classof(const DIEntry *) { return true; }
623 static bool classof(const DIEValue *E) { return E->Type == isEntry; }
625 /// EmitValue - Emit debug information entry offset.
627 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
629 /// SizeOf - Determine size of debug information entry in bytes.
631 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
632 return sizeof(int32_t);
635 /// Profile - Used to gather unique data for the value folding set.
637 static void Profile(FoldingSetNodeID &ID, DIE *Entry) {
638 ID.AddInteger(isEntry);
639 ID.AddPointer(Entry);
641 virtual void Profile(FoldingSetNodeID &ID) {
642 ID.AddInteger(isEntry);
645 ID.AddPointer(Entry);
652 virtual void print(std::ostream &O) {
653 O << "Die: 0x" << std::hex << (intptr_t)Entry << std::dec;
658 //===----------------------------------------------------------------------===//
659 /// DIEBlock - A block of values. Primarily used for location expressions.
661 class DIEBlock : public DIEValue, public DIE {
662 unsigned Size; // Size in bytes excluding size header.
665 : DIEValue(isBlock), DIE(0), Size(0) {}
666 virtual ~DIEBlock() {}
668 // Implement isa/cast/dyncast.
669 static bool classof(const DIEBlock *) { return true; }
670 static bool classof(const DIEValue *E) { return E->Type == isBlock; }
672 /// ComputeSize - calculate the size of the block.
674 unsigned ComputeSize(DwarfDebug &DD);
676 /// BestForm - Choose the best form for data.
678 unsigned BestForm() const {
679 if ((unsigned char)Size == Size) return DW_FORM_block1;
680 if ((unsigned short)Size == Size) return DW_FORM_block2;
681 if ((unsigned int)Size == Size) return DW_FORM_block4;
682 return DW_FORM_block;
685 /// EmitValue - Emit block data.
687 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
689 /// SizeOf - Determine size of block data in bytes.
691 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
693 /// Profile - Used to gather unique data for the value folding set.
695 virtual void Profile(FoldingSetNodeID &ID) {
696 ID.AddInteger(isBlock);
701 virtual void print(std::ostream &O) {
708 //===----------------------------------------------------------------------===//
709 /// CompileUnit - This dwarf writer support class manages information associate
710 /// with a source file.
712 /// ID - File identifier for source.
716 /// Die - Compile unit debug information entry.
720 /// GVToDieMap - Tracks the mapping of unit level debug informaton
721 /// variables to debug information entries.
722 std::map<GlobalVariable *, DIE *> GVToDieMap;
724 /// GVToDIEntryMap - Tracks the mapping of unit level debug informaton
725 /// descriptors to debug information entries using a DIEntry proxy.
726 std::map<GlobalVariable *, DIEntry *> GVToDIEntryMap;
728 /// Globals - A map of globally visible named entities for this unit.
730 std::map<std::string, DIE *> Globals;
732 /// DiesSet - Used to uniquely define dies within the compile unit.
734 FoldingSet<DIE> DiesSet;
736 CompileUnit(unsigned I, DIE *D)
737 : ID(I), Die(D), GVToDieMap(),
738 GVToDIEntryMap(), Globals(), DiesSet(InitDiesSetSize)
746 unsigned getID() const { return ID; }
747 DIE* getDie() const { return Die; }
748 std::map<std::string, DIE *> &getGlobals() { return Globals; }
750 /// hasContent - Return true if this compile unit has something to write out.
752 bool hasContent() const {
753 return !Die->getChildren().empty();
756 /// AddGlobal - Add a new global entity to the compile unit.
758 void AddGlobal(const std::string &Name, DIE *Die) {
762 /// getDieMapSlotFor - Returns the debug information entry map slot for the
763 /// specified debug variable.
764 DIE *&getDieMapSlotFor(GlobalVariable *GV) {
765 return GVToDieMap[GV];
768 /// getDIEntrySlotFor - Returns the debug information entry proxy slot for the
769 /// specified debug variable.
770 DIEntry *&getDIEntrySlotFor(GlobalVariable *GV) {
771 return GVToDIEntryMap[GV];
774 /// AddDie - Adds or interns the DIE to the compile unit.
776 DIE *AddDie(DIE &Buffer) {
780 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
783 Die = new DIE(Buffer);
784 DiesSet.InsertNode(Die, Where);
785 this->Die->AddChild(Die);
793 //===----------------------------------------------------------------------===//
794 /// Dwarf - Emits general Dwarf directives.
798 //===--------------------------------------------------------------------===//
799 // Core attributes used by the Dwarf writer.
803 /// O - Stream to .s file.
807 /// Asm - Target of Dwarf emission.
811 /// TAI - Target asm information.
812 const TargetAsmInfo *TAI;
814 /// TD - Target data.
815 const TargetData *TD;
817 /// RI - Register Information.
818 const TargetRegisterInfo *RI;
820 /// M - Current module.
824 /// MF - Current machine function.
828 /// MMI - Collected machine module information.
830 MachineModuleInfo *MMI;
832 /// SubprogramCount - The running count of functions being compiled.
834 unsigned SubprogramCount;
836 /// Flavor - A unique string indicating what dwarf producer this is, used to
838 const char * const Flavor;
841 Dwarf(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T,
846 , TD(Asm->TM.getTargetData())
847 , RI(Asm->TM.getRegisterInfo())
858 //===--------------------------------------------------------------------===//
861 AsmPrinter *getAsm() const { return Asm; }
862 MachineModuleInfo *getMMI() const { return MMI; }
863 const TargetAsmInfo *getTargetAsmInfo() const { return TAI; }
864 const TargetData *getTargetData() const { return TD; }
866 void PrintRelDirective(bool Force32Bit = false, bool isInSection = false)
868 if (isInSection && TAI->getDwarfSectionOffsetDirective())
869 O << TAI->getDwarfSectionOffsetDirective();
870 else if (Force32Bit || TD->getPointerSize() == sizeof(int32_t))
871 O << TAI->getData32bitsDirective();
873 O << TAI->getData64bitsDirective();
876 /// PrintLabelName - Print label name in form used by Dwarf writer.
878 void PrintLabelName(DWLabel Label) const {
879 PrintLabelName(Label.Tag, Label.Number);
881 void PrintLabelName(const char *Tag, unsigned Number) const {
882 O << TAI->getPrivateGlobalPrefix() << Tag;
883 if (Number) O << Number;
886 void PrintLabelName(const char *Tag, unsigned Number,
887 const char *Suffix) const {
888 O << TAI->getPrivateGlobalPrefix() << Tag;
889 if (Number) O << Number;
893 /// EmitLabel - Emit location label for internal use by Dwarf.
895 void EmitLabel(DWLabel Label) const {
896 EmitLabel(Label.Tag, Label.Number);
898 void EmitLabel(const char *Tag, unsigned Number) const {
899 PrintLabelName(Tag, Number);
903 /// EmitReference - Emit a reference to a label.
905 void EmitReference(DWLabel Label, bool IsPCRelative = false,
906 bool Force32Bit = false) const {
907 EmitReference(Label.Tag, Label.Number, IsPCRelative, Force32Bit);
909 void EmitReference(const char *Tag, unsigned Number,
910 bool IsPCRelative = false, bool Force32Bit = false) const {
911 PrintRelDirective(Force32Bit);
912 PrintLabelName(Tag, Number);
914 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
916 void EmitReference(const std::string &Name, bool IsPCRelative = false,
917 bool Force32Bit = false) const {
918 PrintRelDirective(Force32Bit);
922 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
925 /// EmitDifference - Emit the difference between two labels. Some
926 /// assemblers do not behave with absolute expressions with data directives,
927 /// so there is an option (needsSet) to use an intermediary set expression.
928 void EmitDifference(DWLabel LabelHi, DWLabel LabelLo,
929 bool IsSmall = false) {
930 EmitDifference(LabelHi.Tag, LabelHi.Number,
931 LabelLo.Tag, LabelLo.Number,
934 void EmitDifference(const char *TagHi, unsigned NumberHi,
935 const char *TagLo, unsigned NumberLo,
936 bool IsSmall = false) {
937 if (TAI->needsSet()) {
939 PrintLabelName("set", SetCounter, Flavor);
941 PrintLabelName(TagHi, NumberHi);
943 PrintLabelName(TagLo, NumberLo);
946 PrintRelDirective(IsSmall);
947 PrintLabelName("set", SetCounter, Flavor);
950 PrintRelDirective(IsSmall);
952 PrintLabelName(TagHi, NumberHi);
954 PrintLabelName(TagLo, NumberLo);
958 void EmitSectionOffset(const char* Label, const char* Section,
959 unsigned LabelNumber, unsigned SectionNumber,
960 bool IsSmall = false, bool isEH = false,
961 bool useSet = true) {
962 bool printAbsolute = false;
964 printAbsolute = TAI->isAbsoluteEHSectionOffsets();
966 printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
968 if (TAI->needsSet() && useSet) {
970 PrintLabelName("set", SetCounter, Flavor);
972 PrintLabelName(Label, LabelNumber);
974 if (!printAbsolute) {
976 PrintLabelName(Section, SectionNumber);
980 PrintRelDirective(IsSmall);
982 PrintLabelName("set", SetCounter, Flavor);
985 PrintRelDirective(IsSmall, true);
987 PrintLabelName(Label, LabelNumber);
989 if (!printAbsolute) {
991 PrintLabelName(Section, SectionNumber);
996 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
998 void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
999 const std::vector<MachineMove> &Moves, bool isEH) {
1001 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
1002 TargetFrameInfo::StackGrowsUp ?
1003 TD->getPointerSize() : -TD->getPointerSize();
1004 bool IsLocal = BaseLabel && strcmp(BaseLabel, "label") == 0;
1006 for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
1007 const MachineMove &Move = Moves[i];
1008 unsigned LabelID = Move.getLabelID();
1011 LabelID = MMI->MappedLabel(LabelID);
1013 // Throw out move if the label is invalid.
1014 if (!LabelID) continue;
1017 const MachineLocation &Dst = Move.getDestination();
1018 const MachineLocation &Src = Move.getSource();
1020 // Advance row if new location.
1021 if (BaseLabel && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
1022 Asm->EmitInt8(DW_CFA_advance_loc4);
1023 Asm->EOL("DW_CFA_advance_loc4");
1024 EmitDifference("label", LabelID, BaseLabel, BaseLabelID, true);
1027 BaseLabelID = LabelID;
1028 BaseLabel = "label";
1032 // If advancing cfa.
1033 if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
1035 if (Src.getReg() == MachineLocation::VirtualFP) {
1036 Asm->EmitInt8(DW_CFA_def_cfa_offset);
1037 Asm->EOL("DW_CFA_def_cfa_offset");
1039 Asm->EmitInt8(DW_CFA_def_cfa);
1040 Asm->EOL("DW_CFA_def_cfa");
1041 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getReg(), isEH));
1042 Asm->EOL("Register");
1045 int Offset = -Src.getOffset();
1047 Asm->EmitULEB128Bytes(Offset);
1050 assert(0 && "Machine move no supported yet.");
1052 } else if (Src.isReg() &&
1053 Src.getReg() == MachineLocation::VirtualFP) {
1055 Asm->EmitInt8(DW_CFA_def_cfa_register);
1056 Asm->EOL("DW_CFA_def_cfa_register");
1057 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getReg(), isEH));
1058 Asm->EOL("Register");
1060 assert(0 && "Machine move no supported yet.");
1063 unsigned Reg = RI->getDwarfRegNum(Src.getReg(), isEH);
1064 int Offset = Dst.getOffset() / stackGrowth;
1067 Asm->EmitInt8(DW_CFA_offset_extended_sf);
1068 Asm->EOL("DW_CFA_offset_extended_sf");
1069 Asm->EmitULEB128Bytes(Reg);
1071 Asm->EmitSLEB128Bytes(Offset);
1073 } else if (Reg < 64) {
1074 Asm->EmitInt8(DW_CFA_offset + Reg);
1076 Asm->EOL("DW_CFA_offset + Reg (" + utostr(Reg) + ")");
1079 Asm->EmitULEB128Bytes(Offset);
1082 Asm->EmitInt8(DW_CFA_offset_extended);
1083 Asm->EOL("DW_CFA_offset_extended");
1084 Asm->EmitULEB128Bytes(Reg);
1086 Asm->EmitULEB128Bytes(Offset);
1095 //===----------------------------------------------------------------------===//
1096 /// SrcLineInfo - This class is used to record source line correspondence.
1099 unsigned Line; // Source line number.
1100 unsigned Column; // Source column.
1101 unsigned SourceID; // Source ID number.
1102 unsigned LabelID; // Label in code ID number.
1104 SrcLineInfo(unsigned L, unsigned C, unsigned S, unsigned I)
1105 : Line(L), Column(C), SourceID(S), LabelID(I) {}
1108 unsigned getLine() const { return Line; }
1109 unsigned getColumn() const { return Column; }
1110 unsigned getSourceID() const { return SourceID; }
1111 unsigned getLabelID() const { return LabelID; }
1114 //===----------------------------------------------------------------------===//
1115 /// DbgVariable - This class is used to track local variable information.
1118 DIVariable Var; // Variable Descriptor.
1119 unsigned FrameIndex; // Variable frame index.
1121 DbgVariable(DIVariable V, unsigned I) : Var(V), FrameIndex(I) {}
1124 DIVariable getVariable() const { return Var; }
1125 unsigned getFrameIndex() const { return FrameIndex; }
1128 //===----------------------------------------------------------------------===//
1129 /// DbgScope - This class is used to track scope information.
1132 DbgScope *Parent; // Parent to this scope.
1133 DIDescriptor Desc; // Debug info descriptor for scope.
1134 // Either subprogram or block.
1135 unsigned StartLabelID; // Label ID of the beginning of scope.
1136 unsigned EndLabelID; // Label ID of the end of scope.
1137 SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope.
1138 SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
1140 DbgScope(DbgScope *P, DIDescriptor D)
1141 : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0), Scopes(), Variables()
1144 for (unsigned i = 0, N = Scopes.size(); i < N; ++i) delete Scopes[i];
1145 for (unsigned j = 0, M = Variables.size(); j < M; ++j) delete Variables[j];
1149 DbgScope *getParent() const { return Parent; }
1150 DIDescriptor getDesc() const { return Desc; }
1151 unsigned getStartLabelID() const { return StartLabelID; }
1152 unsigned getEndLabelID() const { return EndLabelID; }
1153 SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
1154 SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
1155 void setStartLabelID(unsigned S) { StartLabelID = S; }
1156 void setEndLabelID(unsigned E) { EndLabelID = E; }
1158 /// AddScope - Add a scope to the scope.
1160 void AddScope(DbgScope *S) { Scopes.push_back(S); }
1162 /// AddVariable - Add a variable to the scope.
1164 void AddVariable(DbgVariable *V) { Variables.push_back(V); }
1167 //===----------------------------------------------------------------------===//
1168 /// DwarfDebug - Emits Dwarf debug directives.
1170 class DwarfDebug : public Dwarf {
1171 //===--------------------------------------------------------------------===//
1172 // Attributes used to construct specific Dwarf sections.
1175 /// CompileUnitMap - A map of global variables representing compile units to
1177 DenseMap<Value *, CompileUnit *> CompileUnitMap;
1179 /// CompileUnits - All the compile units in this module.
1181 SmallVector<CompileUnit *, 8> CompileUnits;
1183 /// MainCU - Some platform prefers one compile unit per .o file. In such
1184 /// cases, all dies are inserted in MainCU.
1185 CompileUnit *MainCU;
1187 /// AbbreviationsSet - Used to uniquely define abbreviations.
1189 FoldingSet<DIEAbbrev> AbbreviationsSet;
1191 /// Abbreviations - A list of all the unique abbreviations in use.
1193 std::vector<DIEAbbrev *> Abbreviations;
1195 /// DirectoryIdMap - Directory name to directory id map.
1197 StringMap<unsigned> DirectoryIdMap;
1199 /// DirectoryNames - A list of directory names.
1200 SmallVector<std::string, 8> DirectoryNames;
1202 /// SourceFileIdMap - Source file name to source file id map.
1204 StringMap<unsigned> SourceFileIdMap;
1206 /// SourceFileNames - A list of source file names.
1207 SmallVector<std::string, 8> SourceFileNames;
1209 /// SourceIdMap - Source id map, i.e. pair of directory id and source file
1210 /// id mapped to a unique id.
1211 DenseMap<std::pair<unsigned, unsigned>, unsigned> SourceIdMap;
1213 /// SourceIds - Reverse map from source id to directory id + file id pair.
1215 SmallVector<std::pair<unsigned, unsigned>, 8> SourceIds;
1217 /// Lines - List of of source line correspondence.
1218 std::vector<SrcLineInfo> Lines;
1220 /// ValuesSet - Used to uniquely define values.
1222 FoldingSet<DIEValue> ValuesSet;
1224 /// Values - A list of all the unique values in use.
1226 std::vector<DIEValue *> Values;
1228 /// StringPool - A UniqueVector of strings used by indirect references.
1230 UniqueVector<std::string> StringPool;
1232 /// SectionMap - Provides a unique id per text section.
1234 UniqueVector<const Section*> SectionMap;
1236 /// SectionSourceLines - Tracks line numbers per text section.
1238 std::vector<std::vector<SrcLineInfo> > SectionSourceLines;
1240 /// didInitial - Flag to indicate if initial emission has been done.
1244 /// shouldEmit - Flag to indicate if debug information should be emitted.
1248 // RootDbgScope - Top level scope for the current function.
1250 DbgScope *RootDbgScope;
1252 /// DbgScopeMap - Tracks the scopes in the current function.
1253 DenseMap<GlobalVariable *, DbgScope *> DbgScopeMap;
1255 /// DebugTimer - Timer for the Dwarf debug writer.
1258 struct FunctionDebugFrameInfo {
1260 std::vector<MachineMove> Moves;
1262 FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
1263 Number(Num), Moves(M) { }
1266 std::vector<FunctionDebugFrameInfo> DebugFrames;
1269 /// getSourceDirectoryAndFileIds - Return the directory and file ids that
1270 /// maps to the source id. Source id starts at 1.
1271 std::pair<unsigned, unsigned>
1272 getSourceDirectoryAndFileIds(unsigned SId) const {
1273 return SourceIds[SId-1];
1276 /// getNumSourceDirectories - Return the number of source directories in the
1278 unsigned getNumSourceDirectories() const {
1279 return DirectoryNames.size();
1282 /// getSourceDirectoryName - Return the name of the directory corresponding
1284 const std::string &getSourceDirectoryName(unsigned Id) const {
1285 return DirectoryNames[Id - 1];
1288 /// getSourceFileName - Return the name of the source file corresponding
1290 const std::string &getSourceFileName(unsigned Id) const {
1291 return SourceFileNames[Id - 1];
1294 /// getNumSourceIds - Return the number of unique source ids.
1295 unsigned getNumSourceIds() const {
1296 return SourceIds.size();
1299 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1301 void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1302 // Profile the node so that we can make it unique.
1303 FoldingSetNodeID ID;
1306 // Check the set for priors.
1307 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1309 // If it's newly added.
1310 if (InSet == &Abbrev) {
1311 // Add to abbreviation list.
1312 Abbreviations.push_back(&Abbrev);
1313 // Assign the vector position + 1 as its number.
1314 Abbrev.setNumber(Abbreviations.size());
1316 // Assign existing abbreviation number.
1317 Abbrev.setNumber(InSet->getNumber());
1321 /// NewString - Add a string to the constant pool and returns a label.
1323 DWLabel NewString(const std::string &String) {
1324 unsigned StringID = StringPool.insert(String);
1325 return DWLabel("string", StringID);
1328 /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1330 DIEntry *NewDIEntry(DIE *Entry = NULL) {
1334 FoldingSetNodeID ID;
1335 DIEntry::Profile(ID, Entry);
1337 Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1339 if (Value) return Value;
1341 Value = new DIEntry(Entry);
1342 ValuesSet.InsertNode(Value, Where);
1344 Value = new DIEntry(Entry);
1347 Values.push_back(Value);
1351 /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1353 void SetDIEntry(DIEntry *Value, DIE *Entry) {
1354 Value->setEntry(Entry);
1355 // Add to values set if not already there. If it is, we merely have a
1356 // duplicate in the values list (no harm.)
1357 ValuesSet.GetOrInsertNode(Value);
1360 /// AddUInt - Add an unsigned integer attribute data and value.
1362 void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1363 if (!Form) Form = DIEInteger::BestForm(false, Integer);
1365 FoldingSetNodeID ID;
1366 DIEInteger::Profile(ID, Integer);
1368 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1370 Value = new DIEInteger(Integer);
1371 ValuesSet.InsertNode(Value, Where);
1372 Values.push_back(Value);
1375 Die->AddValue(Attribute, Form, Value);
1378 /// AddSInt - Add an signed integer attribute data and value.
1380 void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1381 if (!Form) Form = DIEInteger::BestForm(true, Integer);
1383 FoldingSetNodeID ID;
1384 DIEInteger::Profile(ID, (uint64_t)Integer);
1386 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1388 Value = new DIEInteger(Integer);
1389 ValuesSet.InsertNode(Value, Where);
1390 Values.push_back(Value);
1393 Die->AddValue(Attribute, Form, Value);
1396 /// AddString - Add a string attribute data and value.
1398 void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1399 const std::string &String) {
1400 FoldingSetNodeID ID;
1401 DIEString::Profile(ID, String);
1403 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1405 Value = new DIEString(String);
1406 ValuesSet.InsertNode(Value, Where);
1407 Values.push_back(Value);
1410 Die->AddValue(Attribute, Form, Value);
1413 /// AddLabel - Add a Dwarf label attribute data and value.
1415 void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1416 const DWLabel &Label) {
1417 FoldingSetNodeID ID;
1418 DIEDwarfLabel::Profile(ID, Label);
1420 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1422 Value = new DIEDwarfLabel(Label);
1423 ValuesSet.InsertNode(Value, Where);
1424 Values.push_back(Value);
1427 Die->AddValue(Attribute, Form, Value);
1430 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1432 void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1433 const std::string &Label) {
1434 FoldingSetNodeID ID;
1435 DIEObjectLabel::Profile(ID, Label);
1437 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1439 Value = new DIEObjectLabel(Label);
1440 ValuesSet.InsertNode(Value, Where);
1441 Values.push_back(Value);
1444 Die->AddValue(Attribute, Form, Value);
1447 /// AddSectionOffset - Add a section offset label attribute data and value.
1449 void AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
1450 const DWLabel &Label, const DWLabel &Section,
1451 bool isEH = false, bool useSet = true) {
1452 FoldingSetNodeID ID;
1453 DIESectionOffset::Profile(ID, Label, Section);
1455 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1457 Value = new DIESectionOffset(Label, Section, isEH, useSet);
1458 ValuesSet.InsertNode(Value, Where);
1459 Values.push_back(Value);
1462 Die->AddValue(Attribute, Form, Value);
1465 /// AddDelta - Add a label delta attribute data and value.
1467 void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1468 const DWLabel &Hi, const DWLabel &Lo) {
1469 FoldingSetNodeID ID;
1470 DIEDelta::Profile(ID, Hi, Lo);
1472 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1474 Value = new DIEDelta(Hi, Lo);
1475 ValuesSet.InsertNode(Value, Where);
1476 Values.push_back(Value);
1479 Die->AddValue(Attribute, Form, Value);
1482 /// AddDIEntry - Add a DIE attribute data and value.
1484 void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1485 Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1488 /// AddBlock - Add block data.
1490 void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1491 Block->ComputeSize(*this);
1492 FoldingSetNodeID ID;
1495 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1498 ValuesSet.InsertNode(Value, Where);
1499 Values.push_back(Value);
1501 // Already exists, reuse the previous one.
1503 Block = cast<DIEBlock>(Value);
1506 Die->AddValue(Attribute, Block->BestForm(), Value);
1509 /// AddSourceLine - Add location information to specified debug information
1511 void AddSourceLine(DIE *Die, const DIVariable *V) {
1512 unsigned FileID = 0;
1513 unsigned Line = V->getLineNumber();
1514 CompileUnit *Unit = FindCompileUnit(V->getCompileUnit());
1515 FileID = Unit->getID();
1516 assert (FileID && "Invalid file id");
1517 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1518 AddUInt(Die, DW_AT_decl_line, 0, Line);
1521 /// AddSourceLine - Add location information to specified debug information
1523 void AddSourceLine(DIE *Die, const DIGlobal *G) {
1524 unsigned FileID = 0;
1525 unsigned Line = G->getLineNumber();
1526 CompileUnit *Unit = FindCompileUnit(G->getCompileUnit());
1527 FileID = Unit->getID();
1528 assert (FileID && "Invalid file id");
1529 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1530 AddUInt(Die, DW_AT_decl_line, 0, Line);
1533 void AddSourceLine(DIE *Die, const DIType *Ty) {
1534 unsigned FileID = 0;
1535 unsigned Line = Ty->getLineNumber();
1536 DICompileUnit CU = Ty->getCompileUnit();
1539 CompileUnit *Unit = FindCompileUnit(CU);
1540 FileID = Unit->getID();
1541 assert (FileID && "Invalid file id");
1542 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1543 AddUInt(Die, DW_AT_decl_line, 0, Line);
1546 /// AddAddress - Add an address attribute to a die based on the location
1548 void AddAddress(DIE *Die, unsigned Attribute,
1549 const MachineLocation &Location) {
1550 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
1551 DIEBlock *Block = new DIEBlock();
1553 if (Location.isReg()) {
1555 AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1557 AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1558 AddUInt(Block, 0, DW_FORM_udata, Reg);
1562 AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1564 AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1565 AddUInt(Block, 0, DW_FORM_udata, Reg);
1567 AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1570 AddBlock(Die, Attribute, 0, Block);
1573 /// AddType - Add a new type attribute to the specified entity.
1574 void AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
1578 // Check for pre-existence.
1579 DIEntry *&Slot = DW_Unit->getDIEntrySlotFor(Ty.getGV());
1580 // If it exists then use the existing value.
1582 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1587 Slot = NewDIEntry();
1590 DIE Buffer(DW_TAG_base_type);
1591 if (Ty.isBasicType(Ty.getTag()))
1592 ConstructTypeDIE(DW_Unit, Buffer, DIBasicType(Ty.getGV()));
1593 else if (Ty.isDerivedType(Ty.getTag()))
1594 ConstructTypeDIE(DW_Unit, Buffer, DIDerivedType(Ty.getGV()));
1596 assert(Ty.isCompositeType(Ty.getTag()) && "Unknown kind of DIType");
1597 ConstructTypeDIE(DW_Unit, Buffer, DICompositeType(Ty.getGV()));
1600 // Add debug information entry to entity and appropriate context.
1602 DIDescriptor Context = Ty.getContext();
1603 if (!Context.isNull())
1604 Die = DW_Unit->getDieMapSlotFor(Context.getGV());
1607 DIE *Child = new DIE(Buffer);
1608 Die->AddChild(Child);
1610 SetDIEntry(Slot, Child);
1612 Die = DW_Unit->AddDie(Buffer);
1613 SetDIEntry(Slot, Die);
1616 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1619 /// ConstructTypeDIE - Construct basic type die from DIBasicType.
1620 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1622 // Get core information.
1623 const char *Name = BTy.getName();
1624 Buffer.setTag(DW_TAG_base_type);
1625 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BTy.getEncoding());
1626 // Add name if not anonymous or intermediate type.
1628 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1629 uint64_t Size = BTy.getSizeInBits() >> 3;
1630 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1633 /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
1634 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1635 DIDerivedType DTy) {
1636 // Get core information.
1637 const char *Name = DTy.getName();
1638 uint64_t Size = DTy.getSizeInBits() >> 3;
1639 unsigned Tag = DTy.getTag();
1641 // FIXME - Workaround for templates.
1642 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1646 // Map to main type, void will not have a type.
1647 DIType FromTy = DTy.getTypeDerivedFrom();
1648 AddType(DW_Unit, &Buffer, FromTy);
1650 // Add name if not anonymous or intermediate type.
1652 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1654 // Add size if non-zero (derived types might be zero-sized.)
1656 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1658 // Add source line info if available and TyDesc is not a forward
1660 if (!DTy.isForwardDecl())
1661 AddSourceLine(&Buffer, &DTy);
1664 /// ConstructTypeDIE - Construct type DIE from DICompositeType.
1665 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1666 DICompositeType CTy) {
1667 // Get core information.
1668 const char *Name = CTy.getName();
1670 uint64_t Size = CTy.getSizeInBits() >> 3;
1671 unsigned Tag = CTy.getTag();
1675 case DW_TAG_vector_type:
1676 case DW_TAG_array_type:
1677 ConstructArrayTypeDIE(DW_Unit, Buffer, &CTy);
1679 case DW_TAG_enumeration_type:
1681 DIArray Elements = CTy.getTypeArray();
1682 // Add enumerators to enumeration type.
1683 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1684 DIE *ElemDie = NULL;
1685 DIEnumerator Enum(Elements.getElement(i).getGV());
1686 ElemDie = ConstructEnumTypeDIE(DW_Unit, &Enum);
1687 Buffer.AddChild(ElemDie);
1691 case DW_TAG_subroutine_type:
1693 // Add prototype flag.
1694 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1695 DIArray Elements = CTy.getTypeArray();
1697 DIDescriptor RTy = Elements.getElement(0);
1698 AddType(DW_Unit, &Buffer, DIType(RTy.getGV()));
1701 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1702 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1703 DIDescriptor Ty = Elements.getElement(i);
1704 AddType(DW_Unit, Arg, DIType(Ty.getGV()));
1705 Buffer.AddChild(Arg);
1709 case DW_TAG_structure_type:
1710 case DW_TAG_union_type:
1712 // Add elements to structure type.
1713 DIArray Elements = CTy.getTypeArray();
1715 // A forward struct declared type may not have elements available.
1716 if (Elements.isNull())
1719 // Add elements to structure type.
1720 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1721 DIDescriptor Element = Elements.getElement(i);
1722 DIE *ElemDie = NULL;
1723 if (Element.getTag() == dwarf::DW_TAG_subprogram)
1724 ElemDie = CreateSubprogramDIE(DW_Unit,
1725 DISubprogram(Element.getGV()));
1726 else if (Element.getTag() == dwarf::DW_TAG_variable) // ???
1727 ElemDie = CreateGlobalVariableDIE(DW_Unit,
1728 DIGlobalVariable(Element.getGV()));
1730 ElemDie = CreateMemberDIE(DW_Unit,
1731 DIDerivedType(Element.getGV()));
1732 Buffer.AddChild(ElemDie);
1734 unsigned RLang = CTy.getRunTimeLang();
1736 AddUInt(&Buffer, DW_AT_APPLE_runtime_class, DW_FORM_data1, RLang);
1743 // Add name if not anonymous or intermediate type.
1745 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1747 if (Tag == DW_TAG_enumeration_type || Tag == DW_TAG_structure_type
1748 || Tag == DW_TAG_union_type) {
1749 // Add size if non-zero (derived types might be zero-sized.)
1751 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1753 // Add zero size if it is not a forward declaration.
1754 if (CTy.isForwardDecl())
1755 AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
1757 AddUInt(&Buffer, DW_AT_byte_size, 0, 0);
1760 // Add source line info if available.
1761 if (!CTy.isForwardDecl())
1762 AddSourceLine(&Buffer, &CTy);
1766 /// ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
1767 void ConstructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1768 int64_t L = SR.getLo();
1769 int64_t H = SR.getHi();
1770 DIE *DW_Subrange = new DIE(DW_TAG_subrange_type);
1772 AddDIEntry(DW_Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1774 AddSInt(DW_Subrange, DW_AT_lower_bound, 0, L);
1775 AddSInt(DW_Subrange, DW_AT_upper_bound, 0, H);
1777 Buffer.AddChild(DW_Subrange);
1780 /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
1781 void ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1782 DICompositeType *CTy) {
1783 Buffer.setTag(DW_TAG_array_type);
1784 if (CTy->getTag() == DW_TAG_vector_type)
1785 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1787 // Emit derived type.
1788 AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
1789 DIArray Elements = CTy->getTypeArray();
1791 // Construct an anonymous type for index type.
1792 DIE IdxBuffer(DW_TAG_base_type);
1793 AddUInt(&IdxBuffer, DW_AT_byte_size, 0, sizeof(int32_t));
1794 AddUInt(&IdxBuffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
1795 DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
1797 // Add subranges to array type.
1798 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1799 DIDescriptor Element = Elements.getElement(i);
1800 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1801 ConstructSubrangeDIE(Buffer, DISubrange(Element.getGV()), IndexTy);
1805 /// ConstructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1806 DIE *ConstructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) {
1808 DIE *Enumerator = new DIE(DW_TAG_enumerator);
1809 const char *Name = ETy->getName();
1810 AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
1811 int64_t Value = ETy->getEnumValue();
1812 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1816 /// CreateGlobalVariableDIE - Create new DIE using GV.
1817 DIE *CreateGlobalVariableDIE(CompileUnit *DW_Unit, const DIGlobalVariable &GV)
1819 DIE *GVDie = new DIE(DW_TAG_variable);
1820 const char *Name = GV.getDisplayName();
1821 AddString(GVDie, DW_AT_name, DW_FORM_string, Name);
1822 const char *LinkageName = GV.getLinkageName();
1824 AddString(GVDie, DW_AT_MIPS_linkage_name, DW_FORM_string, LinkageName);
1825 AddType(DW_Unit, GVDie, GV.getType());
1826 if (!GV.isLocalToUnit())
1827 AddUInt(GVDie, DW_AT_external, DW_FORM_flag, 1);
1828 AddSourceLine(GVDie, &GV);
1832 /// CreateMemberDIE - Create new member DIE.
1833 DIE *CreateMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT) {
1834 DIE *MemberDie = new DIE(DT.getTag());
1835 const char *Name = DT.getName();
1837 AddString(MemberDie, DW_AT_name, DW_FORM_string, Name);
1839 AddType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
1841 AddSourceLine(MemberDie, &DT);
1843 uint64_t Size = DT.getSizeInBits();
1844 uint64_t FieldSize = DT.getOriginalTypeSize();
1846 if (Size != FieldSize) {
1848 AddUInt(MemberDie, DW_AT_byte_size, 0, DT.getOriginalTypeSize() >> 3);
1849 AddUInt(MemberDie, DW_AT_bit_size, 0, DT.getSizeInBits());
1851 uint64_t Offset = DT.getOffsetInBits();
1852 uint64_t FieldOffset = Offset;
1853 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1854 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1855 FieldOffset = (HiMark - FieldSize);
1856 Offset -= FieldOffset;
1857 // Maybe we need to work from the other end.
1858 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1859 AddUInt(MemberDie, DW_AT_bit_offset, 0, Offset);
1861 DIEBlock *Block = new DIEBlock();
1862 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1863 AddUInt(Block, 0, DW_FORM_udata, DT.getOffsetInBits() >> 3);
1864 AddBlock(MemberDie, DW_AT_data_member_location, 0, Block);
1866 if (DT.isProtected())
1867 AddUInt(MemberDie, DW_AT_accessibility, 0, DW_ACCESS_protected);
1868 else if (DT.isPrivate())
1869 AddUInt(MemberDie, DW_AT_accessibility, 0, DW_ACCESS_private);
1874 /// CreateSubprogramDIE - Create new DIE using SP.
1875 DIE *CreateSubprogramDIE(CompileUnit *DW_Unit,
1876 const DISubprogram &SP,
1877 bool IsConstructor = false) {
1878 DIE *SPDie = new DIE(DW_TAG_subprogram);
1879 const char *Name = SP.getName();
1880 AddString(SPDie, DW_AT_name, DW_FORM_string, Name);
1881 const char *LinkageName = SP.getLinkageName();
1883 AddString(SPDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1885 AddSourceLine(SPDie, &SP);
1887 DICompositeType SPTy = SP.getType();
1888 DIArray Args = SPTy.getTypeArray();
1891 if (!IsConstructor) {
1893 AddType(DW_Unit, SPDie, SPTy);
1895 AddType(DW_Unit, SPDie, DIType(Args.getElement(0).getGV()));
1898 if (!SP.isDefinition()) {
1899 AddUInt(SPDie, DW_AT_declaration, DW_FORM_flag, 1);
1901 // Do not add arguments for subprogram definition. They will be
1902 // handled through RecordVariable.
1904 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1905 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1906 AddType(DW_Unit, Arg, DIType(Args.getElement(i).getGV()));
1907 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1); // ???
1908 SPDie->AddChild(Arg);
1912 unsigned Lang = SP.getCompileUnit().getLanguage();
1913 if (Lang == DW_LANG_C99 || Lang == DW_LANG_C89
1914 || Lang == DW_LANG_ObjC)
1915 AddUInt(SPDie, DW_AT_prototyped, DW_FORM_flag, 1);
1917 if (!SP.isLocalToUnit())
1918 AddUInt(SPDie, DW_AT_external, DW_FORM_flag, 1);
1922 /// FindCompileUnit - Get the compile unit for the given descriptor.
1924 CompileUnit *FindCompileUnit(DICompileUnit Unit) {
1925 CompileUnit *DW_Unit = CompileUnitMap[Unit.getGV()];
1926 assert(DW_Unit && "Missing compile unit.");
1930 /// NewDbgScopeVariable - Create a new scope variable.
1932 DIE *NewDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
1933 // Get the descriptor.
1934 const DIVariable &VD = DV->getVariable();
1936 // Translate tag to proper Dwarf tag. The result variable is dropped for
1939 switch (VD.getTag()) {
1940 case DW_TAG_return_variable: return NULL;
1941 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
1942 case DW_TAG_auto_variable: // fall thru
1943 default: Tag = DW_TAG_variable; break;
1946 // Define variable debug information entry.
1947 DIE *VariableDie = new DIE(Tag);
1948 const char *Name = VD.getName();
1949 AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
1951 // Add source line info if available.
1952 AddSourceLine(VariableDie, &VD);
1954 // Add variable type.
1955 AddType(Unit, VariableDie, VD.getType());
1957 // Add variable address.
1958 MachineLocation Location;
1959 Location.set(RI->getFrameRegister(*MF),
1960 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
1961 AddAddress(VariableDie, DW_AT_location, Location);
1966 /// getOrCreateScope - Returns the scope associated with the given descriptor.
1968 DbgScope *getOrCreateScope(GlobalVariable *V) {
1969 DbgScope *&Slot = DbgScopeMap[V];
1970 if (Slot) return Slot;
1972 // FIXME - breaks down when the context is an inlined function.
1973 DIDescriptor ParentDesc;
1974 DIDescriptor Desc(V);
1976 if (Desc.getTag() == dwarf::DW_TAG_lexical_block) {
1978 ParentDesc = Block.getContext();
1981 DbgScope *Parent = ParentDesc.isNull() ?
1982 NULL : getOrCreateScope(ParentDesc.getGV());
1983 Slot = new DbgScope(Parent, Desc);
1986 Parent->AddScope(Slot);
1987 } else if (RootDbgScope) {
1988 // FIXME - Add inlined function scopes to the root so we can delete them
1989 // later. Long term, handle inlined functions properly.
1990 RootDbgScope->AddScope(Slot);
1992 // First function is top level function.
1993 RootDbgScope = Slot;
1999 /// ConstructDbgScope - Construct the components of a scope.
2001 void ConstructDbgScope(DbgScope *ParentScope,
2002 unsigned ParentStartID, unsigned ParentEndID,
2003 DIE *ParentDie, CompileUnit *Unit) {
2004 // Add variables to scope.
2005 SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
2006 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2007 DIE *VariableDie = NewDbgScopeVariable(Variables[i], Unit);
2008 if (VariableDie) ParentDie->AddChild(VariableDie);
2011 // Add nested scopes.
2012 SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
2013 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
2014 // Define the Scope debug information entry.
2015 DbgScope *Scope = Scopes[j];
2016 // FIXME - Ignore inlined functions for the time being.
2017 if (!Scope->getParent()) continue;
2019 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
2020 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
2022 // Ignore empty scopes.
2023 if (StartID == EndID && StartID != 0) continue;
2024 if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
2026 if (StartID == ParentStartID && EndID == ParentEndID) {
2027 // Just add stuff to the parent scope.
2028 ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
2030 DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
2032 // Add the scope bounds.
2034 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2035 DWLabel("label", StartID));
2037 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2038 DWLabel("func_begin", SubprogramCount));
2041 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2042 DWLabel("label", EndID));
2044 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2045 DWLabel("func_end", SubprogramCount));
2048 // Add the scope contents.
2049 ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
2050 ParentDie->AddChild(ScopeDie);
2055 /// ConstructRootDbgScope - Construct the scope for the subprogram.
2057 void ConstructRootDbgScope(DbgScope *RootScope) {
2058 // Exit if there is no root scope.
2059 if (!RootScope) return;
2060 DIDescriptor Desc = RootScope->getDesc();
2064 // Get the subprogram debug information entry.
2065 DISubprogram SPD(Desc.getGV());
2067 // Get the compile unit context.
2068 CompileUnit *Unit = MainCU;
2070 Unit = FindCompileUnit(SPD.getCompileUnit());
2072 // Get the subprogram die.
2073 DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
2074 assert(SPDie && "Missing subprogram descriptor");
2076 // Add the function bounds.
2077 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2078 DWLabel("func_begin", SubprogramCount));
2079 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2080 DWLabel("func_end", SubprogramCount));
2081 MachineLocation Location(RI->getFrameRegister(*MF));
2082 AddAddress(SPDie, DW_AT_frame_base, Location);
2084 ConstructDbgScope(RootScope, 0, 0, SPDie, Unit);
2087 /// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
2089 void ConstructDefaultDbgScope(MachineFunction *MF) {
2090 const char *FnName = MF->getFunction()->getNameStart();
2092 std::map<std::string, DIE*> &Globals = MainCU->getGlobals();
2093 std::map<std::string, DIE*>::iterator GI = Globals.find(FnName);
2094 if (GI != Globals.end()) {
2095 DIE *SPDie = GI->second;
2097 // Add the function bounds.
2098 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2099 DWLabel("func_begin", SubprogramCount));
2100 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2101 DWLabel("func_end", SubprogramCount));
2103 MachineLocation Location(RI->getFrameRegister(*MF));
2104 AddAddress(SPDie, DW_AT_frame_base, Location);
2108 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
2109 CompileUnit *Unit = CompileUnits[i];
2110 std::map<std::string, DIE*> &Globals = Unit->getGlobals();
2111 std::map<std::string, DIE*>::iterator GI = Globals.find(FnName);
2112 if (GI != Globals.end()) {
2113 DIE *SPDie = GI->second;
2115 // Add the function bounds.
2116 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2117 DWLabel("func_begin", SubprogramCount));
2118 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2119 DWLabel("func_end", SubprogramCount));
2121 MachineLocation Location(RI->getFrameRegister(*MF));
2122 AddAddress(SPDie, DW_AT_frame_base, Location);
2129 // FIXME: This is causing an abort because C++ mangled names are compared
2130 // with their unmangled counterparts. See PR2885. Don't do this assert.
2131 assert(0 && "Couldn't find DIE for machine function!");
2136 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
2137 /// tools to recognize the object file contains Dwarf information.
2138 void EmitInitial() {
2139 // Check to see if we already emitted intial headers.
2140 if (didInitial) return;
2143 // Dwarf sections base addresses.
2144 if (TAI->doesDwarfRequireFrameSection()) {
2145 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2146 EmitLabel("section_debug_frame", 0);
2148 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2149 EmitLabel("section_info", 0);
2150 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2151 EmitLabel("section_abbrev", 0);
2152 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2153 EmitLabel("section_aranges", 0);
2154 if (TAI->doesSupportMacInfoSection()) {
2155 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2156 EmitLabel("section_macinfo", 0);
2158 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2159 EmitLabel("section_line", 0);
2160 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2161 EmitLabel("section_loc", 0);
2162 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2163 EmitLabel("section_pubnames", 0);
2164 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2165 EmitLabel("section_str", 0);
2166 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2167 EmitLabel("section_ranges", 0);
2169 Asm->SwitchToSection(TAI->getTextSection());
2170 EmitLabel("text_begin", 0);
2171 Asm->SwitchToSection(TAI->getDataSection());
2172 EmitLabel("data_begin", 0);
2175 /// EmitDIE - Recusively Emits a debug information entry.
2177 void EmitDIE(DIE *Die) {
2178 // Get the abbreviation for this DIE.
2179 unsigned AbbrevNumber = Die->getAbbrevNumber();
2180 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2184 // Emit the code (index) for the abbreviation.
2185 Asm->EmitULEB128Bytes(AbbrevNumber);
2188 Asm->EOL(std::string("Abbrev [" +
2189 utostr(AbbrevNumber) +
2190 "] 0x" + utohexstr(Die->getOffset()) +
2191 ":0x" + utohexstr(Die->getSize()) + " " +
2192 TagString(Abbrev->getTag())));
2196 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2197 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2199 // Emit the DIE attribute values.
2200 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2201 unsigned Attr = AbbrevData[i].getAttribute();
2202 unsigned Form = AbbrevData[i].getForm();
2203 assert(Form && "Too many attributes for DIE (check abbreviation)");
2206 case DW_AT_sibling: {
2207 Asm->EmitInt32(Die->SiblingOffset());
2211 // Emit an attribute using the defined form.
2212 Values[i]->EmitValue(*this, Form);
2217 Asm->EOL(AttributeString(Attr));
2220 // Emit the DIE children if any.
2221 if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2222 const std::vector<DIE *> &Children = Die->getChildren();
2224 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2225 EmitDIE(Children[j]);
2228 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2232 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2234 unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2235 // Get the children.
2236 const std::vector<DIE *> &Children = Die->getChildren();
2238 // If not last sibling and has children then add sibling offset attribute.
2239 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2241 // Record the abbreviation.
2242 AssignAbbrevNumber(Die->getAbbrev());
2244 // Get the abbreviation for this DIE.
2245 unsigned AbbrevNumber = Die->getAbbrevNumber();
2246 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2249 Die->setOffset(Offset);
2251 // Start the size with the size of abbreviation code.
2252 Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
2254 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2255 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2257 // Size the DIE attribute values.
2258 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2259 // Size attribute value.
2260 Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2263 // Size the DIE children if any.
2264 if (!Children.empty()) {
2265 assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2266 "Children flag not set");
2268 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2269 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2272 // End of children marker.
2273 Offset += sizeof(int8_t);
2276 Die->setSize(Offset - Die->getOffset());
2280 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2282 void SizeAndOffsets() {
2283 // Process base compile unit.
2285 // Compute size of compile unit header
2286 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2287 sizeof(int16_t) + // DWARF version number
2288 sizeof(int32_t) + // Offset Into Abbrev. Section
2289 sizeof(int8_t); // Pointer Size (in bytes)
2290 SizeAndOffsetDie(MainCU->getDie(), Offset, true);
2293 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
2294 CompileUnit *Unit = CompileUnits[i];
2295 // Compute size of compile unit header
2296 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2297 sizeof(int16_t) + // DWARF version number
2298 sizeof(int32_t) + // Offset Into Abbrev. Section
2299 sizeof(int8_t); // Pointer Size (in bytes)
2300 SizeAndOffsetDie(Unit->getDie(), Offset, true);
2304 /// EmitDebugInfo / EmitDebugInfoPerCU - Emit the debug info section.
2306 void EmitDebugInfoPerCU(CompileUnit *Unit) {
2307 DIE *Die = Unit->getDie();
2308 // Emit the compile units header.
2309 EmitLabel("info_begin", Unit->getID());
2310 // Emit size of content not including length itself
2311 unsigned ContentSize = Die->getSize() +
2312 sizeof(int16_t) + // DWARF version number
2313 sizeof(int32_t) + // Offset Into Abbrev. Section
2314 sizeof(int8_t) + // Pointer Size (in bytes)
2315 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2317 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2318 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2319 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2320 Asm->EOL("Offset Into Abbrev. Section");
2321 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2324 // FIXME - extra padding for gdb bug.
2325 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2326 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2327 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2328 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2329 EmitLabel("info_end", Unit->getID());
2334 void EmitDebugInfo() {
2335 // Start debug info section.
2336 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2339 EmitDebugInfoPerCU(MainCU);
2343 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
2344 EmitDebugInfoPerCU(CompileUnits[i]);
2347 /// EmitAbbreviations - Emit the abbreviation section.
2349 void EmitAbbreviations() const {
2350 // Check to see if it is worth the effort.
2351 if (!Abbreviations.empty()) {
2352 // Start the debug abbrev section.
2353 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2355 EmitLabel("abbrev_begin", 0);
2357 // For each abbrevation.
2358 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2359 // Get abbreviation data
2360 const DIEAbbrev *Abbrev = Abbreviations[i];
2362 // Emit the abbrevations code (base 1 index.)
2363 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2364 Asm->EOL("Abbreviation Code");
2366 // Emit the abbreviations data.
2367 Abbrev->Emit(*this);
2372 // Mark end of abbreviations.
2373 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2375 EmitLabel("abbrev_end", 0);
2381 /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
2382 /// the line matrix.
2384 void EmitEndOfLineMatrix(unsigned SectionEnd) {
2385 // Define last address of section.
2386 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2387 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2388 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2389 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2391 // Mark end of matrix.
2392 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2393 Asm->EmitULEB128Bytes(1); Asm->EOL();
2394 Asm->EmitInt8(1); Asm->EOL();
2397 /// EmitDebugLines - Emit source line information.
2399 void EmitDebugLines() {
2400 // If the target is using .loc/.file, the assembler will be emitting the
2401 // .debug_line table automatically.
2402 if (TAI->hasDotLocAndDotFile())
2405 // Minimum line delta, thus ranging from -10..(255-10).
2406 const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2407 // Maximum line delta, thus ranging from -10..(255-10).
2408 const int MaxLineDelta = 255 + MinLineDelta;
2410 // Start the dwarf line section.
2411 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2413 // Construct the section header.
2415 EmitDifference("line_end", 0, "line_begin", 0, true);
2416 Asm->EOL("Length of Source Line Info");
2417 EmitLabel("line_begin", 0);
2419 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2421 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2422 Asm->EOL("Prolog Length");
2423 EmitLabel("line_prolog_begin", 0);
2425 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2427 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2429 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2431 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2433 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2435 // Line number standard opcode encodings argument count
2436 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2437 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2438 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2439 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2440 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2441 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2442 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2443 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2444 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2446 // Emit directories.
2447 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2448 Asm->EmitString(getSourceDirectoryName(DI));
2449 Asm->EOL("Directory");
2451 Asm->EmitInt8(0); Asm->EOL("End of directories");
2454 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2455 // Remember source id starts at 1.
2456 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2457 Asm->EmitString(getSourceFileName(Id.second));
2459 Asm->EmitULEB128Bytes(Id.first);
2460 Asm->EOL("Directory #");
2461 Asm->EmitULEB128Bytes(0);
2462 Asm->EOL("Mod date");
2463 Asm->EmitULEB128Bytes(0);
2464 Asm->EOL("File size");
2466 Asm->EmitInt8(0); Asm->EOL("End of files");
2468 EmitLabel("line_prolog_end", 0);
2470 // A sequence for each text section.
2471 unsigned SecSrcLinesSize = SectionSourceLines.size();
2473 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2474 // Isolate current sections line info.
2475 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2478 const Section* S = SectionMap[j + 1];
2479 O << '\t' << TAI->getCommentString() << " Section"
2480 << S->getName() << '\n';
2484 // Dwarf assumes we start with first line of first source file.
2485 unsigned Source = 1;
2488 // Construct rows of the address, source, line, column matrix.
2489 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2490 const SrcLineInfo &LineInfo = LineInfos[i];
2491 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2492 if (!LabelID) continue;
2497 std::pair<unsigned, unsigned> SourceID =
2498 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2499 O << '\t' << TAI->getCommentString() << ' '
2500 << getSourceDirectoryName(SourceID.first) << ' '
2501 << getSourceFileName(SourceID.second)
2502 <<" :" << utostr_32(LineInfo.getLine()) << '\n';
2505 // Define the line address.
2506 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2507 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2508 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2509 EmitReference("label", LabelID); Asm->EOL("Location label");
2511 // If change of source, then switch to the new source.
2512 if (Source != LineInfo.getSourceID()) {
2513 Source = LineInfo.getSourceID();
2514 Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2515 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2518 // If change of line.
2519 if (Line != LineInfo.getLine()) {
2520 // Determine offset.
2521 int Offset = LineInfo.getLine() - Line;
2522 int Delta = Offset - MinLineDelta;
2525 Line = LineInfo.getLine();
2527 // If delta is small enough and in range...
2528 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2529 // ... then use fast opcode.
2530 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2532 // ... otherwise use long hand.
2533 Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
2534 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2535 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2538 // Copy the previous row (different address or source)
2539 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2543 EmitEndOfLineMatrix(j + 1);
2546 if (SecSrcLinesSize == 0)
2547 // Because we're emitting a debug_line section, we still need a line
2548 // table. The linker and friends expect it to exist. If there's nothing to
2549 // put into it, emit an empty table.
2550 EmitEndOfLineMatrix(1);
2552 EmitLabel("line_end", 0);
2557 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2559 void EmitCommonDebugFrame() {
2560 if (!TAI->doesDwarfRequireFrameSection())
2564 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2565 TargetFrameInfo::StackGrowsUp ?
2566 TD->getPointerSize() : -TD->getPointerSize();
2568 // Start the dwarf frame section.
2569 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2571 EmitLabel("debug_frame_common", 0);
2572 EmitDifference("debug_frame_common_end", 0,
2573 "debug_frame_common_begin", 0, true);
2574 Asm->EOL("Length of Common Information Entry");
2576 EmitLabel("debug_frame_common_begin", 0);
2577 Asm->EmitInt32((int)DW_CIE_ID);
2578 Asm->EOL("CIE Identifier Tag");
2579 Asm->EmitInt8(DW_CIE_VERSION);
2580 Asm->EOL("CIE Version");
2581 Asm->EmitString("");
2582 Asm->EOL("CIE Augmentation");
2583 Asm->EmitULEB128Bytes(1);
2584 Asm->EOL("CIE Code Alignment Factor");
2585 Asm->EmitSLEB128Bytes(stackGrowth);
2586 Asm->EOL("CIE Data Alignment Factor");
2587 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2588 Asm->EOL("CIE RA Column");
2590 std::vector<MachineMove> Moves;
2591 RI->getInitialFrameState(Moves);
2593 EmitFrameMoves(NULL, 0, Moves, false);
2595 Asm->EmitAlignment(2, 0, 0, false);
2596 EmitLabel("debug_frame_common_end", 0);
2601 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2603 void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2604 if (!TAI->doesDwarfRequireFrameSection())
2607 // Start the dwarf frame section.
2608 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2610 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2611 "debug_frame_begin", DebugFrameInfo.Number, true);
2612 Asm->EOL("Length of Frame Information Entry");
2614 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2616 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2618 Asm->EOL("FDE CIE offset");
2620 EmitReference("func_begin", DebugFrameInfo.Number);
2621 Asm->EOL("FDE initial location");
2622 EmitDifference("func_end", DebugFrameInfo.Number,
2623 "func_begin", DebugFrameInfo.Number);
2624 Asm->EOL("FDE address range");
2626 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
2629 Asm->EmitAlignment(2, 0, 0, false);
2630 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2635 void EmitDebugPubNamesPerCU(CompileUnit *Unit) {
2636 EmitDifference("pubnames_end", Unit->getID(),
2637 "pubnames_begin", Unit->getID(), true);
2638 Asm->EOL("Length of Public Names Info");
2640 EmitLabel("pubnames_begin", Unit->getID());
2642 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
2644 EmitSectionOffset("info_begin", "section_info",
2645 Unit->getID(), 0, true, false);
2646 Asm->EOL("Offset of Compilation Unit Info");
2648 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
2650 Asm->EOL("Compilation Unit Length");
2652 std::map<std::string, DIE *> &Globals = Unit->getGlobals();
2653 for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
2654 GE = Globals.end(); GI != GE; ++GI) {
2655 const std::string &Name = GI->first;
2656 DIE * Entity = GI->second;
2658 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2659 Asm->EmitString(Name); Asm->EOL("External Name");
2662 Asm->EmitInt32(0); Asm->EOL("End Mark");
2663 EmitLabel("pubnames_end", Unit->getID());
2668 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2670 void EmitDebugPubNames() {
2671 // Start the dwarf pubnames section.
2672 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2675 EmitDebugPubNamesPerCU(MainCU);
2679 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
2680 EmitDebugPubNamesPerCU(CompileUnits[i]);
2683 /// EmitDebugStr - Emit visible names into a debug str section.
2685 void EmitDebugStr() {
2686 // Check to see if it is worth the effort.
2687 if (!StringPool.empty()) {
2688 // Start the dwarf str section.
2689 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2691 // For each of strings in the string pool.
2692 for (unsigned StringID = 1, N = StringPool.size();
2693 StringID <= N; ++StringID) {
2694 // Emit a label for reference from debug information entries.
2695 EmitLabel("string", StringID);
2696 // Emit the string itself.
2697 const std::string &String = StringPool[StringID];
2698 Asm->EmitString(String); Asm->EOL();
2705 /// EmitDebugLoc - Emit visible names into a debug loc section.
2707 void EmitDebugLoc() {
2708 // Start the dwarf loc section.
2709 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2714 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2716 void EmitDebugARanges() {
2717 // Start the dwarf aranges section.
2718 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2722 CompileUnit *Unit = GetBaseCompileUnit();
2724 // Don't include size of length
2725 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2727 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2729 EmitReference("info_begin", Unit->getID());
2730 Asm->EOL("Offset of Compilation Unit Info");
2732 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2734 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2736 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2737 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2740 EmitReference("text_begin", 0); Asm->EOL("Address");
2741 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2743 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2744 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2750 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2752 void EmitDebugRanges() {
2753 // Start the dwarf ranges section.
2754 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2759 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2761 void EmitDebugMacInfo() {
2762 if (TAI->doesSupportMacInfoSection()) {
2763 // Start the dwarf macinfo section.
2764 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2770 /// GetOrCreateSourceID - Look up the source id with the given directory and
2771 /// source file names. If none currently exists, create a new id and insert it
2772 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames maps
2774 unsigned GetOrCreateSourceID(const std::string &DirName,
2775 const std::string &FileName) {
2777 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
2778 if (DI != DirectoryIdMap.end()) {
2779 DId = DI->getValue();
2781 DId = DirectoryNames.size() + 1;
2782 DirectoryIdMap[DirName] = DId;
2783 DirectoryNames.push_back(DirName);
2787 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
2788 if (FI != SourceFileIdMap.end()) {
2789 FId = FI->getValue();
2791 FId = SourceFileNames.size() + 1;
2792 SourceFileIdMap[FileName] = FId;
2793 SourceFileNames.push_back(FileName);
2796 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
2797 SourceIdMap.find(std::make_pair(DId, FId));
2798 if (SI != SourceIdMap.end())
2801 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
2802 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
2803 SourceIds.push_back(std::make_pair(DId, FId));
2808 void ConstructCompileUnit(GlobalVariable *GV) {
2809 DICompileUnit DIUnit(GV);
2810 const char *Dir = DIUnit.getDirectory();
2811 const char *FN = DIUnit.getFilename();
2812 unsigned ID = GetOrCreateSourceID(Dir, FN);
2814 DIE *Die = new DIE(DW_TAG_compile_unit);
2815 AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
2816 DWLabel("section_line", 0), DWLabel("section_line", 0),
2818 AddString(Die, DW_AT_producer, DW_FORM_string, DIUnit.getProducer());
2819 AddUInt(Die, DW_AT_language, DW_FORM_data1, DIUnit.getLanguage());
2820 AddString(Die, DW_AT_name, DW_FORM_string, FN);
2822 AddString(Die, DW_AT_comp_dir, DW_FORM_string, Dir);
2823 if (DIUnit.isOptimized())
2824 AddUInt(Die, DW_AT_APPLE_optimized, DW_FORM_flag, 1);
2825 const char *Flags = DIUnit.getFlags();
2827 AddString(Die, DW_AT_APPLE_flags, DW_FORM_string, Flags);
2828 unsigned RVer = DIUnit.getRunTimeVersion();
2830 AddUInt(Die, DW_AT_APPLE_major_runtime_vers, DW_FORM_data1, RVer);
2832 CompileUnit *Unit = new CompileUnit(ID, Die);
2833 if (DIUnit.isMain()) {
2834 assert(!MainCU && "Multiple main compile units are found!");
2837 CompileUnitMap[DIUnit.getGV()] = Unit;
2838 CompileUnits.push_back(Unit);
2841 /// ConstructCompileUnits - Create a compile unit DIEs.
2842 void ConstructCompileUnits() {
2843 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.compile_units");
2846 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2847 "Malformed compile unit descriptor anchor type");
2848 Constant *RootC = cast<Constant>(*Root->use_begin());
2849 assert(RootC->hasNUsesOrMore(1) &&
2850 "Malformed compile unit descriptor anchor type");
2851 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2853 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2854 UUI != UUE; ++UUI) {
2855 GlobalVariable *GV = cast<GlobalVariable>(*UUI);
2856 ConstructCompileUnit(GV);
2860 bool ConstructGlobalVariableDIE(GlobalVariable *GV) {
2861 DIGlobalVariable DI_GV(GV);
2862 CompileUnit *DW_Unit = MainCU;
2864 DW_Unit = FindCompileUnit(DI_GV.getCompileUnit());
2866 // Check for pre-existence.
2867 DIE *&Slot = DW_Unit->getDieMapSlotFor(DI_GV.getGV());
2871 DIE *VariableDie = CreateGlobalVariableDIE(DW_Unit, DI_GV);
2874 DIEBlock *Block = new DIEBlock();
2875 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
2876 AddObjectLabel(Block, 0, DW_FORM_udata,
2877 Asm->getGlobalLinkName(DI_GV.getGlobal()));
2878 AddBlock(VariableDie, DW_AT_location, 0, Block);
2882 // Add to context owner.
2883 DW_Unit->getDie()->AddChild(VariableDie);
2884 // Expose as global. FIXME - need to check external flag.
2885 DW_Unit->AddGlobal(DI_GV.getName(), VariableDie);
2889 /// ConstructGlobalVariableDIEs - Create DIEs for each of the externally
2890 /// visible global variables. Return true if at least one global DIE is
2892 bool ConstructGlobalVariableDIEs() {
2893 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.global_variables");
2897 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2898 "Malformed global variable descriptor anchor type");
2899 Constant *RootC = cast<Constant>(*Root->use_begin());
2900 assert(RootC->hasNUsesOrMore(1) &&
2901 "Malformed global variable descriptor anchor type");
2903 bool Result = false;
2904 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2906 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2907 UUI != UUE; ++UUI) {
2908 GlobalVariable *GV = cast<GlobalVariable>(*UUI);
2909 Result |= ConstructGlobalVariableDIE(GV);
2914 bool ConstructSubprogram(GlobalVariable *GV) {
2915 DISubprogram SP(GV);
2916 CompileUnit *Unit = MainCU;
2918 Unit = FindCompileUnit(SP.getCompileUnit());
2920 // Check for pre-existence.
2921 DIE *&Slot = Unit->getDieMapSlotFor(GV);
2925 if (!SP.isDefinition())
2926 // This is a method declaration which will be handled while
2927 // constructing class type.
2930 DIE *SubprogramDie = CreateSubprogramDIE(Unit, SP);
2933 Slot = SubprogramDie;
2934 // Add to context owner.
2935 Unit->getDie()->AddChild(SubprogramDie);
2936 // Expose as global.
2937 Unit->AddGlobal(SP.getName(), SubprogramDie);
2941 /// ConstructSubprograms - Create DIEs for each of the externally visible
2942 /// subprograms. Return true if at least one subprogram DIE is created.
2943 bool ConstructSubprograms() {
2944 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.subprograms");
2948 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2949 "Malformed subprogram descriptor anchor type");
2950 Constant *RootC = cast<Constant>(*Root->use_begin());
2951 assert(RootC->hasNUsesOrMore(1) &&
2952 "Malformed subprogram descriptor anchor type");
2954 bool Result = false;
2955 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2957 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2958 UUI != UUE; ++UUI) {
2959 GlobalVariable *GV = cast<GlobalVariable>(*UUI);
2960 Result |= ConstructSubprogram(GV);
2966 //===--------------------------------------------------------------------===//
2967 // Main entry points.
2969 DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
2970 : Dwarf(OS, A, T, "dbg"), MainCU(0),
2971 AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(),
2972 ValuesSet(InitValuesSetSize), Values(), StringPool(), SectionMap(),
2973 SectionSourceLines(), didInitial(false), shouldEmit(false),
2974 RootDbgScope(0), DebugTimer(0) {
2975 if (TimePassesIsEnabled)
2976 DebugTimer = new Timer("Dwarf Debug Writer",
2977 getDwarfTimerGroup());
2979 virtual ~DwarfDebug() {
2980 for (unsigned j = 0, M = Values.size(); j < M; ++j)
2986 /// ShouldEmitDwarfDebug - Returns true if Dwarf debugging declarations should
2988 bool ShouldEmitDwarfDebug() const { return shouldEmit; }
2990 /// SetDebugInfo - Create global DIEs and emit initial debug info sections.
2991 /// This is inovked by the target AsmPrinter.
2992 void SetDebugInfo(MachineModuleInfo *mmi) {
2993 if (TimePassesIsEnabled)
2994 DebugTimer->startTimer();
2996 // Create all the compile unit DIEs.
2997 ConstructCompileUnits();
2999 if (CompileUnits.empty()) {
3000 if (TimePassesIsEnabled)
3001 DebugTimer->stopTimer();
3006 // Create DIEs for each of the externally visible global variables.
3007 bool globalDIEs = ConstructGlobalVariableDIEs();
3009 // Create DIEs for each of the externally visible subprograms.
3010 bool subprogramDIEs = ConstructSubprograms();
3012 // If there is not any debug info available for any global variables
3013 // and any subprograms then there is not any debug info to emit.
3014 if (!globalDIEs && !subprogramDIEs) {
3015 if (TimePassesIsEnabled)
3016 DebugTimer->stopTimer();
3023 MMI->setDebugInfoAvailability(true);
3025 // Prime section data.
3026 SectionMap.insert(TAI->getTextSection());
3028 // Print out .file directives to specify files for .loc directives. These
3029 // are printed out early so that they precede any .loc directives.
3030 if (TAI->hasDotLocAndDotFile()) {
3031 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
3032 // Remember source id starts at 1.
3033 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
3034 sys::Path FullPath(getSourceDirectoryName(Id.first));
3036 FullPath.appendComponent(getSourceFileName(Id.second));
3037 assert(AppendOk && "Could not append filename to directory!");
3039 Asm->EmitFile(i, FullPath.toString());
3044 // Emit initial sections
3047 if (TimePassesIsEnabled)
3048 DebugTimer->stopTimer();
3051 /// BeginModule - Emit all Dwarf sections that should come prior to the
3053 void BeginModule(Module *M) {
3057 /// EndModule - Emit all Dwarf sections that should come after the content.
3060 if (!ShouldEmitDwarfDebug())
3063 if (TimePassesIsEnabled)
3064 DebugTimer->startTimer();
3066 // Standard sections final addresses.
3067 Asm->SwitchToSection(TAI->getTextSection());
3068 EmitLabel("text_end", 0);
3069 Asm->SwitchToSection(TAI->getDataSection());
3070 EmitLabel("data_end", 0);
3072 // End text sections.
3073 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
3074 Asm->SwitchToSection(SectionMap[i]);
3075 EmitLabel("section_end", i);
3078 // Emit common frame information.
3079 EmitCommonDebugFrame();
3081 // Emit function debug frame information
3082 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
3083 E = DebugFrames.end(); I != E; ++I)
3084 EmitFunctionDebugFrame(*I);
3086 // Compute DIE offsets and sizes.
3089 // Emit all the DIEs into a debug info section
3092 // Corresponding abbreviations into a abbrev section.
3093 EmitAbbreviations();
3095 // Emit source line correspondence into a debug line section.
3098 // Emit info into a debug pubnames section.
3099 EmitDebugPubNames();
3101 // Emit info into a debug str section.
3104 // Emit info into a debug loc section.
3107 // Emit info into a debug aranges section.
3110 // Emit info into a debug ranges section.
3113 // Emit info into a debug macinfo section.
3116 if (TimePassesIsEnabled)
3117 DebugTimer->stopTimer();
3120 /// BeginFunction - Gather pre-function debug information. Assumes being
3121 /// emitted immediately after the function entry point.
3122 void BeginFunction(MachineFunction *MF) {
3125 if (!ShouldEmitDwarfDebug()) return;
3127 if (TimePassesIsEnabled)
3128 DebugTimer->startTimer();
3130 // Begin accumulating function debug information.
3131 MMI->BeginFunction(MF);
3133 // Assumes in correct section after the entry point.
3134 EmitLabel("func_begin", ++SubprogramCount);
3136 // Emit label for the implicitly defined dbg.stoppoint at the start of
3138 if (!Lines.empty()) {
3139 const SrcLineInfo &LineInfo = Lines[0];
3140 Asm->printLabel(LineInfo.getLabelID());
3143 if (TimePassesIsEnabled)
3144 DebugTimer->stopTimer();
3147 /// EndFunction - Gather and emit post-function debug information.
3149 void EndFunction(MachineFunction *MF) {
3150 if (!ShouldEmitDwarfDebug()) return;
3152 if (TimePassesIsEnabled)
3153 DebugTimer->startTimer();
3155 // Define end label for subprogram.
3156 EmitLabel("func_end", SubprogramCount);
3158 // Get function line info.
3159 if (!Lines.empty()) {
3160 // Get section line info.
3161 unsigned ID = SectionMap.insert(Asm->CurrentSection_);
3162 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
3163 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
3164 // Append the function info to section info.
3165 SectionLineInfos.insert(SectionLineInfos.end(),
3166 Lines.begin(), Lines.end());
3169 // Construct scopes for subprogram.
3171 ConstructRootDbgScope(RootDbgScope);
3173 // FIXME: This is wrong. We are essentially getting past a problem with
3174 // debug information not being able to handle unreachable blocks that have
3175 // debug information in them. In particular, those unreachable blocks that
3176 // have "region end" info in them. That situation results in the "root
3177 // scope" not being created. If that's the case, then emit a "default"
3178 // scope, i.e., one that encompasses the whole function. This isn't
3179 // desirable. And a better way of handling this (and all of the debugging
3180 // information) needs to be explored.
3181 ConstructDefaultDbgScope(MF);
3183 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
3184 MMI->getFrameMoves()));
3188 delete RootDbgScope;
3189 DbgScopeMap.clear();
3190 RootDbgScope = NULL;
3195 if (TimePassesIsEnabled)
3196 DebugTimer->stopTimer();
3199 /// ValidDebugInfo - Return true if V represents valid debug info value.
3200 bool ValidDebugInfo(Value *V) {
3207 GlobalVariable *GV = getGlobalVariable(V);
3211 if (!GV->hasInternalLinkage () && !GV->hasLinkOnceLinkage())
3214 if (TimePassesIsEnabled)
3215 DebugTimer->startTimer();
3217 DIDescriptor DI(GV);
3219 // Check current version. Allow Version6 for now.
3220 unsigned Version = DI.getVersion();
3221 if (Version != LLVMDebugVersion && Version != LLVMDebugVersion6) {
3222 if (TimePassesIsEnabled)
3223 DebugTimer->stopTimer();
3228 unsigned Tag = DI.getTag();
3230 case DW_TAG_variable:
3231 assert(DIVariable(GV).Verify() && "Invalid DebugInfo value");
3233 case DW_TAG_compile_unit:
3234 assert(DICompileUnit(GV).Verify() && "Invalid DebugInfo value");
3236 case DW_TAG_subprogram:
3237 assert(DISubprogram(GV).Verify() && "Invalid DebugInfo value");
3243 if (TimePassesIsEnabled)
3244 DebugTimer->stopTimer();
3249 /// RecordSourceLine - Records location information and associates it with a
3250 /// label. Returns a unique label ID used to generate a label and provide
3251 /// correspondence to the source line list.
3252 unsigned RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
3253 if (TimePassesIsEnabled)
3254 DebugTimer->startTimer();
3256 CompileUnit *Unit = CompileUnitMap[V];
3257 assert(Unit && "Unable to find CompileUnit");
3258 unsigned ID = MMI->NextLabelID();
3259 Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
3261 if (TimePassesIsEnabled)
3262 DebugTimer->stopTimer();
3267 /// RecordSourceLine - Records location information and associates it with a
3268 /// label. Returns a unique label ID used to generate a label and provide
3269 /// correspondence to the source line list.
3270 unsigned RecordSourceLine(unsigned Line, unsigned Col, unsigned Src) {
3271 if (TimePassesIsEnabled)
3272 DebugTimer->startTimer();
3274 unsigned ID = MMI->NextLabelID();
3275 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
3277 if (TimePassesIsEnabled)
3278 DebugTimer->stopTimer();
3283 /// getRecordSourceLineCount - Return the number of source lines in the debug
3285 unsigned getRecordSourceLineCount() const {
3286 return Lines.size();
3289 /// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
3290 /// timed. Look up the source id with the given directory and source file
3291 /// names. If none currently exists, create a new id and insert it in the
3292 /// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
3294 unsigned getOrCreateSourceID(const std::string &DirName,
3295 const std::string &FileName) {
3296 if (TimePassesIsEnabled)
3297 DebugTimer->startTimer();
3299 unsigned SrcId = GetOrCreateSourceID(DirName, FileName);
3301 if (TimePassesIsEnabled)
3302 DebugTimer->stopTimer();
3307 /// RecordRegionStart - Indicate the start of a region.
3308 unsigned RecordRegionStart(GlobalVariable *V) {
3309 if (TimePassesIsEnabled)
3310 DebugTimer->startTimer();
3312 DbgScope *Scope = getOrCreateScope(V);
3313 unsigned ID = MMI->NextLabelID();
3314 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
3316 if (TimePassesIsEnabled)
3317 DebugTimer->stopTimer();
3322 /// RecordRegionEnd - Indicate the end of a region.
3323 unsigned RecordRegionEnd(GlobalVariable *V) {
3324 if (TimePassesIsEnabled)
3325 DebugTimer->startTimer();
3327 DbgScope *Scope = getOrCreateScope(V);
3328 unsigned ID = MMI->NextLabelID();
3329 Scope->setEndLabelID(ID);
3331 if (TimePassesIsEnabled)
3332 DebugTimer->stopTimer();
3337 /// RecordVariable - Indicate the declaration of a local variable.
3338 void RecordVariable(GlobalVariable *GV, unsigned FrameIndex) {
3339 if (TimePassesIsEnabled)
3340 DebugTimer->startTimer();
3342 DIDescriptor Desc(GV);
3343 DbgScope *Scope = NULL;
3345 if (Desc.getTag() == DW_TAG_variable) {
3346 // GV is a global variable.
3347 DIGlobalVariable DG(GV);
3348 Scope = getOrCreateScope(DG.getContext().getGV());
3350 // or GV is a local variable.
3352 Scope = getOrCreateScope(DV.getContext().getGV());
3355 assert(Scope && "Unable to find variable' scope");
3356 DbgVariable *DV = new DbgVariable(DIVariable(GV), FrameIndex);
3357 Scope->AddVariable(DV);
3359 if (TimePassesIsEnabled)
3360 DebugTimer->stopTimer();
3364 //===----------------------------------------------------------------------===//
3365 /// DwarfException - Emits Dwarf exception handling directives.
3367 class DwarfException : public Dwarf {
3368 struct FunctionEHFrameInfo {
3371 unsigned PersonalityIndex;
3373 bool hasLandingPads;
3374 std::vector<MachineMove> Moves;
3375 const Function * function;
3377 FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
3379 const std::vector<MachineMove> &M,
3381 FnName(FN), Number(Num), PersonalityIndex(P),
3382 hasCalls(hC), hasLandingPads(hL), Moves(M), function (f) { }
3385 std::vector<FunctionEHFrameInfo> EHFrames;
3387 /// shouldEmitTable - Per-function flag to indicate if EH tables should
3389 bool shouldEmitTable;
3391 /// shouldEmitMoves - Per-function flag to indicate if frame moves info
3392 /// should be emitted.
3393 bool shouldEmitMoves;
3395 /// shouldEmitTableModule - Per-module flag to indicate if EH tables
3396 /// should be emitted.
3397 bool shouldEmitTableModule;
3399 /// shouldEmitFrameModule - Per-module flag to indicate if frame moves
3400 /// should be emitted.
3401 bool shouldEmitMovesModule;
3403 /// ExceptionTimer - Timer for the Dwarf exception writer.
3404 Timer *ExceptionTimer;
3406 /// EmitCommonEHFrame - Emit the common eh unwind frame.
3408 void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
3409 // Size and sign of stack growth.
3411 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3412 TargetFrameInfo::StackGrowsUp ?
3413 TD->getPointerSize() : -TD->getPointerSize();
3415 // Begin eh frame section.
3416 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3418 if (!TAI->doesRequireNonLocalEHFrameLabel())
3419 O << TAI->getEHGlobalPrefix();
3420 O << "EH_frame" << Index << ":\n";
3421 EmitLabel("section_eh_frame", Index);
3423 // Define base labels.
3424 EmitLabel("eh_frame_common", Index);
3426 // Define the eh frame length.
3427 EmitDifference("eh_frame_common_end", Index,
3428 "eh_frame_common_begin", Index, true);
3429 Asm->EOL("Length of Common Information Entry");
3432 EmitLabel("eh_frame_common_begin", Index);
3433 Asm->EmitInt32((int)0);
3434 Asm->EOL("CIE Identifier Tag");
3435 Asm->EmitInt8(DW_CIE_VERSION);
3436 Asm->EOL("CIE Version");
3438 // The personality presence indicates that language specific information
3439 // will show up in the eh frame.
3440 Asm->EmitString(Personality ? "zPLR" : "zR");
3441 Asm->EOL("CIE Augmentation");
3443 // Round out reader.
3444 Asm->EmitULEB128Bytes(1);
3445 Asm->EOL("CIE Code Alignment Factor");
3446 Asm->EmitSLEB128Bytes(stackGrowth);
3447 Asm->EOL("CIE Data Alignment Factor");
3448 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
3449 Asm->EOL("CIE Return Address Column");
3451 // If there is a personality, we need to indicate the functions location.
3453 Asm->EmitULEB128Bytes(7);
3454 Asm->EOL("Augmentation Size");
3456 if (TAI->getNeedsIndirectEncoding()) {
3457 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4 | DW_EH_PE_indirect);
3458 Asm->EOL("Personality (pcrel sdata4 indirect)");
3460 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3461 Asm->EOL("Personality (pcrel sdata4)");
3464 PrintRelDirective(true);
3465 O << TAI->getPersonalityPrefix();
3466 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
3467 O << TAI->getPersonalitySuffix();
3468 if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
3469 O << "-" << TAI->getPCSymbol();
3470 Asm->EOL("Personality");
3472 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3473 Asm->EOL("LSDA Encoding (pcrel sdata4)");
3475 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3476 Asm->EOL("FDE Encoding (pcrel sdata4)");
3478 Asm->EmitULEB128Bytes(1);
3479 Asm->EOL("Augmentation Size");
3481 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3482 Asm->EOL("FDE Encoding (pcrel sdata4)");
3485 // Indicate locations of general callee saved registers in frame.
3486 std::vector<MachineMove> Moves;
3487 RI->getInitialFrameState(Moves);
3488 EmitFrameMoves(NULL, 0, Moves, true);
3490 // On Darwin the linker honors the alignment of eh_frame, which means it
3491 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3492 // you get holes which confuse readers of eh_frame.
3493 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3495 EmitLabel("eh_frame_common_end", Index);
3500 /// EmitEHFrame - Emit function exception frame information.
3502 void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
3503 Function::LinkageTypes linkage = EHFrameInfo.function->getLinkage();
3505 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3507 // Externally visible entry into the functions eh frame info.
3508 // If the corresponding function is static, this should not be
3509 // externally visible.
3510 if (linkage != Function::InternalLinkage &&
3511 linkage != Function::PrivateLinkage) {
3512 if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
3513 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
3516 // If corresponding function is weak definition, this should be too.
3517 if ((linkage == Function::WeakAnyLinkage ||
3518 linkage == Function::WeakODRLinkage ||
3519 linkage == Function::LinkOnceAnyLinkage ||
3520 linkage == Function::LinkOnceODRLinkage) &&
3521 TAI->getWeakDefDirective())
3522 O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
3524 // If there are no calls then you can't unwind. This may mean we can
3525 // omit the EH Frame, but some environments do not handle weak absolute
3527 // If UnwindTablesMandatory is set we cannot do this optimization; the
3528 // unwind info is to be available for non-EH uses.
3529 if (!EHFrameInfo.hasCalls &&
3530 !UnwindTablesMandatory &&
3531 ((linkage != Function::WeakAnyLinkage &&
3532 linkage != Function::WeakODRLinkage &&
3533 linkage != Function::LinkOnceAnyLinkage &&
3534 linkage != Function::LinkOnceODRLinkage) ||
3535 !TAI->getWeakDefDirective() ||
3536 TAI->getSupportsWeakOmittedEHFrame()))
3538 O << EHFrameInfo.FnName << " = 0\n";
3539 // This name has no connection to the function, so it might get
3540 // dead-stripped when the function is not, erroneously. Prohibit
3541 // dead-stripping unconditionally.
3542 if (const char *UsedDirective = TAI->getUsedDirective())
3543 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3545 O << EHFrameInfo.FnName << ":\n";
3548 EmitDifference("eh_frame_end", EHFrameInfo.Number,
3549 "eh_frame_begin", EHFrameInfo.Number, true);
3550 Asm->EOL("Length of Frame Information Entry");
3552 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
3554 if (TAI->doesRequireNonLocalEHFrameLabel()) {
3555 PrintRelDirective(true, true);
3556 PrintLabelName("eh_frame_begin", EHFrameInfo.Number);
3558 if (!TAI->isAbsoluteEHSectionOffsets())
3559 O << "-EH_frame" << EHFrameInfo.PersonalityIndex;
3561 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
3562 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
3566 Asm->EOL("FDE CIE offset");
3568 EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
3569 Asm->EOL("FDE initial location");
3570 EmitDifference("eh_func_end", EHFrameInfo.Number,
3571 "eh_func_begin", EHFrameInfo.Number, true);
3572 Asm->EOL("FDE address range");
3574 // If there is a personality and landing pads then point to the language
3575 // specific data area in the exception table.
3576 if (EHFrameInfo.PersonalityIndex) {
3577 Asm->EmitULEB128Bytes(4);
3578 Asm->EOL("Augmentation size");
3580 if (EHFrameInfo.hasLandingPads)
3581 EmitReference("exception", EHFrameInfo.Number, true, true);
3583 Asm->EmitInt32((int)0);
3584 Asm->EOL("Language Specific Data Area");
3586 Asm->EmitULEB128Bytes(0);
3587 Asm->EOL("Augmentation size");
3590 // Indicate locations of function specific callee saved registers in
3592 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves,
3595 // On Darwin the linker honors the alignment of eh_frame, which means it
3596 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3597 // you get holes which confuse readers of eh_frame.
3598 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3600 EmitLabel("eh_frame_end", EHFrameInfo.Number);
3602 // If the function is marked used, this table should be also. We cannot
3603 // make the mark unconditional in this case, since retaining the table
3604 // also retains the function in this case, and there is code around
3605 // that depends on unused functions (calling undefined externals) being
3606 // dead-stripped to link correctly. Yes, there really is.
3607 if (MMI->getUsedFunctions().count(EHFrameInfo.function))
3608 if (const char *UsedDirective = TAI->getUsedDirective())
3609 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3613 /// EmitExceptionTable - Emit landing pads and actions.
3615 /// The general organization of the table is complex, but the basic concepts
3616 /// are easy. First there is a header which describes the location and
3617 /// organization of the three components that follow.
3618 /// 1. The landing pad site information describes the range of code covered
3619 /// by the try. In our case it's an accumulation of the ranges covered
3620 /// by the invokes in the try. There is also a reference to the landing
3621 /// pad that handles the exception once processed. Finally an index into
3622 /// the actions table.
3623 /// 2. The action table, in our case, is composed of pairs of type ids
3624 /// and next action offset. Starting with the action index from the
3625 /// landing pad site, each type Id is checked for a match to the current
3626 /// exception. If it matches then the exception and type id are passed
3627 /// on to the landing pad. Otherwise the next action is looked up. This
3628 /// chain is terminated with a next action of zero. If no type id is
3629 /// found the the frame is unwound and handling continues.
3630 /// 3. Type id table contains references to all the C++ typeinfo for all
3631 /// catches in the function. This tables is reversed indexed base 1.
3633 /// SharedTypeIds - How many leading type ids two landing pads have in common.
3634 static unsigned SharedTypeIds(const LandingPadInfo *L,
3635 const LandingPadInfo *R) {
3636 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3637 unsigned LSize = LIds.size(), RSize = RIds.size();
3638 unsigned MinSize = LSize < RSize ? LSize : RSize;
3641 for (; Count != MinSize; ++Count)
3642 if (LIds[Count] != RIds[Count])
3648 /// PadLT - Order landing pads lexicographically by type id.
3649 static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
3650 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3651 unsigned LSize = LIds.size(), RSize = RIds.size();
3652 unsigned MinSize = LSize < RSize ? LSize : RSize;
3654 for (unsigned i = 0; i != MinSize; ++i)
3655 if (LIds[i] != RIds[i])
3656 return LIds[i] < RIds[i];
3658 return LSize < RSize;
3662 static inline unsigned getEmptyKey() { return -1U; }
3663 static inline unsigned getTombstoneKey() { return -2U; }
3664 static unsigned getHashValue(const unsigned &Key) { return Key; }
3665 static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
3666 static bool isPod() { return true; }
3669 /// ActionEntry - Structure describing an entry in the actions table.
3670 struct ActionEntry {
3671 int ValueForTypeID; // The value to write - may not be equal to the type id.
3673 struct ActionEntry *Previous;
3676 /// PadRange - Structure holding a try-range and the associated landing pad.
3678 // The index of the landing pad.
3680 // The index of the begin and end labels in the landing pad's label lists.
3681 unsigned RangeIndex;
3684 typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
3686 /// CallSiteEntry - Structure describing an entry in the call-site table.
3687 struct CallSiteEntry {
3688 // The 'try-range' is BeginLabel .. EndLabel.
3689 unsigned BeginLabel; // zero indicates the start of the function.
3690 unsigned EndLabel; // zero indicates the end of the function.
3691 // The landing pad starts at PadLabel.
3692 unsigned PadLabel; // zero indicates that there is no landing pad.
3696 void EmitExceptionTable() {
3697 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
3698 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
3699 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
3700 if (PadInfos.empty()) return;
3702 // Sort the landing pads in order of their type ids. This is used to fold
3703 // duplicate actions.
3704 SmallVector<const LandingPadInfo *, 64> LandingPads;
3705 LandingPads.reserve(PadInfos.size());
3706 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
3707 LandingPads.push_back(&PadInfos[i]);
3708 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
3710 // Negative type ids index into FilterIds, positive type ids index into
3711 // TypeInfos. The value written for a positive type id is just the type
3712 // id itself. For a negative type id, however, the value written is the
3713 // (negative) byte offset of the corresponding FilterIds entry. The byte
3714 // offset is usually equal to the type id, because the FilterIds entries
3715 // are written using a variable width encoding which outputs one byte per
3716 // entry as long as the value written is not too large, but can differ.
3717 // This kind of complication does not occur for positive type ids because
3718 // type infos are output using a fixed width encoding.
3719 // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
3720 SmallVector<int, 16> FilterOffsets;
3721 FilterOffsets.reserve(FilterIds.size());
3723 for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
3724 E = FilterIds.end(); I != E; ++I) {
3725 FilterOffsets.push_back(Offset);
3726 Offset -= TargetAsmInfo::getULEB128Size(*I);
3729 // Compute the actions table and gather the first action index for each
3730 // landing pad site.
3731 SmallVector<ActionEntry, 32> Actions;
3732 SmallVector<unsigned, 64> FirstActions;
3733 FirstActions.reserve(LandingPads.size());
3735 int FirstAction = 0;
3736 unsigned SizeActions = 0;
3737 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3738 const LandingPadInfo *LP = LandingPads[i];
3739 const std::vector<int> &TypeIds = LP->TypeIds;
3740 const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
3741 unsigned SizeSiteActions = 0;
3743 if (NumShared < TypeIds.size()) {
3744 unsigned SizeAction = 0;
3745 ActionEntry *PrevAction = 0;
3748 const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
3749 assert(Actions.size());
3750 PrevAction = &Actions.back();
3751 SizeAction = TargetAsmInfo::getSLEB128Size(PrevAction->NextAction) +
3752 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3753 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
3755 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3756 SizeAction += -PrevAction->NextAction;
3757 PrevAction = PrevAction->Previous;
3761 // Compute the actions.
3762 for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
3763 int TypeID = TypeIds[I];
3764 assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
3765 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
3766 unsigned SizeTypeID = TargetAsmInfo::getSLEB128Size(ValueForTypeID);
3768 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
3769 SizeAction = SizeTypeID + TargetAsmInfo::getSLEB128Size(NextAction);
3770 SizeSiteActions += SizeAction;
3772 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
3773 Actions.push_back(Action);
3775 PrevAction = &Actions.back();
3778 // Record the first action of the landing pad site.
3779 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
3780 } // else identical - re-use previous FirstAction
3782 FirstActions.push_back(FirstAction);
3784 // Compute this sites contribution to size.
3785 SizeActions += SizeSiteActions;
3788 // Compute the call-site table. The entry for an invoke has a try-range
3789 // containing the call, a non-zero landing pad and an appropriate action.
3790 // The entry for an ordinary call has a try-range containing the call and
3791 // zero for the landing pad and the action. Calls marked 'nounwind' have
3792 // no entry and must not be contained in the try-range of any entry - they
3793 // form gaps in the table. Entries must be ordered by try-range address.
3794 SmallVector<CallSiteEntry, 64> CallSites;
3796 RangeMapType PadMap;
3797 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
3798 // by try-range labels when lowered). Ordinary calls do not, so appropriate
3799 // try-ranges for them need be deduced.
3800 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3801 const LandingPadInfo *LandingPad = LandingPads[i];
3802 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
3803 unsigned BeginLabel = LandingPad->BeginLabels[j];
3804 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
3805 PadRange P = { i, j };
3806 PadMap[BeginLabel] = P;
3810 // The end label of the previous invoke or nounwind try-range.
3811 unsigned LastLabel = 0;
3813 // Whether there is a potentially throwing instruction (currently this means
3814 // an ordinary call) between the end of the previous try-range and now.
3815 bool SawPotentiallyThrowing = false;
3817 // Whether the last callsite entry was for an invoke.
3818 bool PreviousIsInvoke = false;
3820 // Visit all instructions in order of address.
3821 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
3823 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
3825 if (!MI->isLabel()) {
3826 SawPotentiallyThrowing |= MI->getDesc().isCall();
3830 unsigned BeginLabel = MI->getOperand(0).getImm();
3831 assert(BeginLabel && "Invalid label!");
3833 // End of the previous try-range?
3834 if (BeginLabel == LastLabel)
3835 SawPotentiallyThrowing = false;
3837 // Beginning of a new try-range?
3838 RangeMapType::iterator L = PadMap.find(BeginLabel);
3839 if (L == PadMap.end())
3840 // Nope, it was just some random label.
3843 PadRange P = L->second;
3844 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
3846 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
3847 "Inconsistent landing pad map!");
3849 // If some instruction between the previous try-range and this one may
3850 // throw, create a call-site entry with no landing pad for the region
3851 // between the try-ranges.
3852 if (SawPotentiallyThrowing) {
3853 CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
3854 CallSites.push_back(Site);
3855 PreviousIsInvoke = false;
3858 LastLabel = LandingPad->EndLabels[P.RangeIndex];
3859 assert(BeginLabel && LastLabel && "Invalid landing pad!");
3861 if (LandingPad->LandingPadLabel) {
3862 // This try-range is for an invoke.
3863 CallSiteEntry Site = {BeginLabel, LastLabel,
3864 LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
3866 // Try to merge with the previous call-site.
3867 if (PreviousIsInvoke) {
3868 CallSiteEntry &Prev = CallSites.back();
3869 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
3870 // Extend the range of the previous entry.
3871 Prev.EndLabel = Site.EndLabel;
3876 // Otherwise, create a new call-site.
3877 CallSites.push_back(Site);
3878 PreviousIsInvoke = true;
3881 PreviousIsInvoke = false;
3885 // If some instruction between the previous try-range and the end of the
3886 // function may throw, create a call-site entry with no landing pad for the
3887 // region following the try-range.
3888 if (SawPotentiallyThrowing) {
3889 CallSiteEntry Site = {LastLabel, 0, 0, 0};
3890 CallSites.push_back(Site);
3896 const unsigned SiteStartSize = sizeof(int32_t); // DW_EH_PE_udata4
3897 const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
3898 const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
3899 unsigned SizeSites = CallSites.size() * (SiteStartSize +
3902 for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
3903 SizeSites += TargetAsmInfo::getULEB128Size(CallSites[i].Action);
3906 const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
3907 unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
3909 unsigned TypeOffset = sizeof(int8_t) + // Call site format
3910 TargetAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
3911 SizeSites + SizeActions + SizeTypes;
3913 unsigned TotalSize = sizeof(int8_t) + // LPStart format
3914 sizeof(int8_t) + // TType format
3915 TargetAsmInfo::getULEB128Size(TypeOffset) + // TType base offset
3918 unsigned SizeAlign = (4 - TotalSize) & 3;
3920 // Begin the exception table.
3921 Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
3922 Asm->EmitAlignment(2, 0, 0, false);
3923 O << "GCC_except_table" << SubprogramCount << ":\n";
3924 for (unsigned i = 0; i != SizeAlign; ++i) {
3926 Asm->EOL("Padding");
3928 EmitLabel("exception", SubprogramCount);
3931 Asm->EmitInt8(DW_EH_PE_omit);
3932 Asm->EOL("LPStart format (DW_EH_PE_omit)");
3933 Asm->EmitInt8(DW_EH_PE_absptr);
3934 Asm->EOL("TType format (DW_EH_PE_absptr)");
3935 Asm->EmitULEB128Bytes(TypeOffset);
3936 Asm->EOL("TType base offset");
3937 Asm->EmitInt8(DW_EH_PE_udata4);
3938 Asm->EOL("Call site format (DW_EH_PE_udata4)");
3939 Asm->EmitULEB128Bytes(SizeSites);
3940 Asm->EOL("Call-site table length");
3942 // Emit the landing pad site information.
3943 for (unsigned i = 0; i < CallSites.size(); ++i) {
3944 CallSiteEntry &S = CallSites[i];
3945 const char *BeginTag;
3946 unsigned BeginNumber;
3948 if (!S.BeginLabel) {
3949 BeginTag = "eh_func_begin";
3950 BeginNumber = SubprogramCount;
3953 BeginNumber = S.BeginLabel;
3956 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
3958 Asm->EOL("Region start");
3961 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
3964 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
3966 Asm->EOL("Region length");
3971 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
3973 Asm->EOL("Landing pad");
3975 Asm->EmitULEB128Bytes(S.Action);
3979 // Emit the actions.
3980 for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
3981 ActionEntry &Action = Actions[I];
3983 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
3984 Asm->EOL("TypeInfo index");
3985 Asm->EmitSLEB128Bytes(Action.NextAction);
3986 Asm->EOL("Next action");
3989 // Emit the type ids.
3990 for (unsigned M = TypeInfos.size(); M; --M) {
3991 GlobalVariable *GV = TypeInfos[M - 1];
3993 PrintRelDirective();
3996 O << Asm->getGlobalLinkName(GV);
4000 Asm->EOL("TypeInfo");
4003 // Emit the filter typeids.
4004 for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
4005 unsigned TypeID = FilterIds[j];
4006 Asm->EmitULEB128Bytes(TypeID);
4007 Asm->EOL("Filter TypeInfo index");
4010 Asm->EmitAlignment(2, 0, 0, false);
4014 //===--------------------------------------------------------------------===//
4015 // Main entry points.
4017 DwarfException(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
4018 : Dwarf(OS, A, T, "eh"), shouldEmitTable(false), shouldEmitMoves(false),
4019 shouldEmitTableModule(false), shouldEmitMovesModule(false),
4021 if (TimePassesIsEnabled)
4022 ExceptionTimer = new Timer("Dwarf Exception Writer",
4023 getDwarfTimerGroup());
4026 virtual ~DwarfException() {
4027 delete ExceptionTimer;
4030 /// SetModuleInfo - Set machine module information when it's known that pass
4031 /// manager has created it. Set by the target AsmPrinter.
4032 void SetModuleInfo(MachineModuleInfo *mmi) {
4036 /// BeginModule - Emit all exception information that should come prior to the
4038 void BeginModule(Module *M) {
4042 /// EndModule - Emit all exception information that should come after the
4045 if (TimePassesIsEnabled)
4046 ExceptionTimer->startTimer();
4048 if (shouldEmitMovesModule || shouldEmitTableModule) {
4049 const std::vector<Function *> Personalities = MMI->getPersonalities();
4050 for (unsigned i = 0; i < Personalities.size(); ++i)
4051 EmitCommonEHFrame(Personalities[i], i);
4053 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
4054 E = EHFrames.end(); I != E; ++I)
4058 if (TimePassesIsEnabled)
4059 ExceptionTimer->stopTimer();
4062 /// BeginFunction - Gather pre-function exception information. Assumes being
4063 /// emitted immediately after the function entry point.
4064 void BeginFunction(MachineFunction *MF) {
4065 if (TimePassesIsEnabled)
4066 ExceptionTimer->startTimer();
4069 shouldEmitTable = shouldEmitMoves = false;
4071 if (MMI && TAI->doesSupportExceptionHandling()) {
4072 // Map all labels and get rid of any dead landing pads.
4073 MMI->TidyLandingPads();
4075 // If any landing pads survive, we need an EH table.
4076 if (MMI->getLandingPads().size())
4077 shouldEmitTable = true;
4079 // See if we need frame move info.
4080 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
4081 shouldEmitMoves = true;
4083 if (shouldEmitMoves || shouldEmitTable)
4084 // Assumes in correct section after the entry point.
4085 EmitLabel("eh_func_begin", ++SubprogramCount);
4088 shouldEmitTableModule |= shouldEmitTable;
4089 shouldEmitMovesModule |= shouldEmitMoves;
4091 if (TimePassesIsEnabled)
4092 ExceptionTimer->stopTimer();
4095 /// EndFunction - Gather and emit post-function exception information.
4097 void EndFunction() {
4098 if (TimePassesIsEnabled)
4099 ExceptionTimer->startTimer();
4101 if (shouldEmitMoves || shouldEmitTable) {
4102 EmitLabel("eh_func_end", SubprogramCount);
4103 EmitExceptionTable();
4105 // Save EH frame information
4107 push_back(FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
4109 MMI->getPersonalityIndex(),
4110 MF->getFrameInfo()->hasCalls(),
4111 !MMI->getLandingPads().empty(),
4112 MMI->getFrameMoves(),
4113 MF->getFunction()));
4116 if (TimePassesIsEnabled)
4117 ExceptionTimer->stopTimer();
4121 } // End of namespace llvm
4123 //===----------------------------------------------------------------------===//
4125 /// Emit - Print the abbreviation using the specified Dwarf writer.
4127 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
4128 // Emit its Dwarf tag type.
4129 DD.getAsm()->EmitULEB128Bytes(Tag);
4130 DD.getAsm()->EOL(TagString(Tag));
4132 // Emit whether it has children DIEs.
4133 DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
4134 DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
4136 // For each attribute description.
4137 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4138 const DIEAbbrevData &AttrData = Data[i];
4140 // Emit attribute type.
4141 DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
4142 DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
4145 DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
4146 DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
4149 // Mark end of abbreviation.
4150 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
4151 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
4155 void DIEAbbrev::print(std::ostream &O) {
4156 O << "Abbreviation @"
4157 << std::hex << (intptr_t)this << std::dec
4161 << ChildrenString(ChildrenFlag)
4164 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4166 << AttributeString(Data[i].getAttribute())
4168 << FormEncodingString(Data[i].getForm())
4172 void DIEAbbrev::dump() { print(cerr); }
4175 //===----------------------------------------------------------------------===//
4178 void DIEValue::dump() {
4183 //===----------------------------------------------------------------------===//
4185 /// EmitValue - Emit integer of appropriate size.
4187 void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
4189 case DW_FORM_flag: // Fall thru
4190 case DW_FORM_ref1: // Fall thru
4191 case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer); break;
4192 case DW_FORM_ref2: // Fall thru
4193 case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer); break;
4194 case DW_FORM_ref4: // Fall thru
4195 case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer); break;
4196 case DW_FORM_ref8: // Fall thru
4197 case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer); break;
4198 case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
4199 case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
4200 default: assert(0 && "DIE Value form not supported yet"); break;
4204 /// SizeOf - Determine size of integer value in bytes.
4206 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4208 case DW_FORM_flag: // Fall thru
4209 case DW_FORM_ref1: // Fall thru
4210 case DW_FORM_data1: return sizeof(int8_t);
4211 case DW_FORM_ref2: // Fall thru
4212 case DW_FORM_data2: return sizeof(int16_t);
4213 case DW_FORM_ref4: // Fall thru
4214 case DW_FORM_data4: return sizeof(int32_t);
4215 case DW_FORM_ref8: // Fall thru
4216 case DW_FORM_data8: return sizeof(int64_t);
4217 case DW_FORM_udata: return TargetAsmInfo::getULEB128Size(Integer);
4218 case DW_FORM_sdata: return TargetAsmInfo::getSLEB128Size(Integer);
4219 default: assert(0 && "DIE Value form not supported yet"); break;
4224 //===----------------------------------------------------------------------===//
4226 /// EmitValue - Emit string value.
4228 void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
4229 DD.getAsm()->EmitString(Str);
4232 //===----------------------------------------------------------------------===//
4234 /// EmitValue - Emit label value.
4236 void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4237 bool IsSmall = Form == DW_FORM_data4;
4238 DD.EmitReference(Label, false, IsSmall);
4241 /// SizeOf - Determine size of label value in bytes.
4243 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4244 if (Form == DW_FORM_data4) return 4;
4245 return DD.getTargetData()->getPointerSize();
4248 //===----------------------------------------------------------------------===//
4250 /// EmitValue - Emit label value.
4252 void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4253 bool IsSmall = Form == DW_FORM_data4;
4254 DD.EmitReference(Label, false, IsSmall);
4257 /// SizeOf - Determine size of label value in bytes.
4259 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4260 if (Form == DW_FORM_data4) return 4;
4261 return DD.getTargetData()->getPointerSize();
4264 //===----------------------------------------------------------------------===//
4266 /// EmitValue - Emit delta value.
4268 void DIESectionOffset::EmitValue(DwarfDebug &DD, unsigned Form) {
4269 bool IsSmall = Form == DW_FORM_data4;
4270 DD.EmitSectionOffset(Label.Tag, Section.Tag,
4271 Label.Number, Section.Number, IsSmall, IsEH, UseSet);
4274 /// SizeOf - Determine size of delta value in bytes.
4276 unsigned DIESectionOffset::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4277 if (Form == DW_FORM_data4) return 4;
4278 return DD.getTargetData()->getPointerSize();
4281 //===----------------------------------------------------------------------===//
4283 /// EmitValue - Emit delta value.
4285 void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
4286 bool IsSmall = Form == DW_FORM_data4;
4287 DD.EmitDifference(LabelHi, LabelLo, IsSmall);
4290 /// SizeOf - Determine size of delta value in bytes.
4292 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4293 if (Form == DW_FORM_data4) return 4;
4294 return DD.getTargetData()->getPointerSize();
4297 //===----------------------------------------------------------------------===//
4299 /// EmitValue - Emit debug information entry offset.
4301 void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
4302 DD.getAsm()->EmitInt32(Entry->getOffset());
4305 //===----------------------------------------------------------------------===//
4307 /// ComputeSize - calculate the size of the block.
4309 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
4311 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4313 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4314 Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
4320 /// EmitValue - Emit block data.
4322 void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
4324 case DW_FORM_block1: DD.getAsm()->EmitInt8(Size); break;
4325 case DW_FORM_block2: DD.getAsm()->EmitInt16(Size); break;
4326 case DW_FORM_block4: DD.getAsm()->EmitInt32(Size); break;
4327 case DW_FORM_block: DD.getAsm()->EmitULEB128Bytes(Size); break;
4328 default: assert(0 && "Improper form for block"); break;
4331 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4333 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4335 Values[i]->EmitValue(DD, AbbrevData[i].getForm());
4339 /// SizeOf - Determine size of block data in bytes.
4341 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4343 case DW_FORM_block1: return Size + sizeof(int8_t);
4344 case DW_FORM_block2: return Size + sizeof(int16_t);
4345 case DW_FORM_block4: return Size + sizeof(int32_t);
4346 case DW_FORM_block: return Size + TargetAsmInfo::getULEB128Size(Size);
4347 default: assert(0 && "Improper form for block"); break;
4352 //===----------------------------------------------------------------------===//
4353 /// DIE Implementation
4356 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4360 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
4362 void DIE::AddSiblingOffset() {
4363 DIEInteger *DI = new DIEInteger(0);
4364 Values.insert(Values.begin(), DI);
4365 Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
4368 /// Profile - Used to gather unique data for the value folding set.
4370 void DIE::Profile(FoldingSetNodeID &ID) {
4373 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4374 ID.AddPointer(Children[i]);
4376 for (unsigned j = 0, M = Values.size(); j < M; ++j)
4377 ID.AddPointer(Values[j]);
4381 void DIE::print(std::ostream &O, unsigned IncIndent) {
4382 static unsigned IndentCount = 0;
4383 IndentCount += IncIndent;
4384 const std::string Indent(IndentCount, ' ');
4385 bool isBlock = Abbrev.getTag() == 0;
4390 << "0x" << std::hex << (intptr_t)this << std::dec
4391 << ", Offset: " << Offset
4392 << ", Size: " << Size
4396 << TagString(Abbrev.getTag())
4398 << ChildrenString(Abbrev.getChildrenFlag());
4400 O << "Size: " << Size;
4404 const SmallVector<DIEAbbrevData, 8> &Data = Abbrev.getData();
4407 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4411 O << AttributeString(Data[i].getAttribute());
4413 O << "Blk[" << i << "]";
4416 << FormEncodingString(Data[i].getForm())
4418 Values[i]->print(O);
4423 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
4424 Children[j]->print(O, 4);
4427 if (!isBlock) O << "\n";
4428 IndentCount -= IncIndent;
4436 //===----------------------------------------------------------------------===//
4437 /// DwarfWriter Implementation
4440 DwarfWriter::DwarfWriter()
4441 : ImmutablePass(&ID), DD(0), DE(0) {}
4443 DwarfWriter::~DwarfWriter() {
4448 /// BeginModule - Emit all Dwarf sections that should come prior to the
4450 void DwarfWriter::BeginModule(Module *M,
4451 MachineModuleInfo *MMI,
4452 raw_ostream &OS, AsmPrinter *A,
4453 const TargetAsmInfo *T) {
4454 DE = new DwarfException(OS, A, T);
4455 DD = new DwarfDebug(OS, A, T);
4458 DD->SetDebugInfo(MMI);
4459 DE->SetModuleInfo(MMI);
4462 /// EndModule - Emit all Dwarf sections that should come after the content.
4464 void DwarfWriter::EndModule() {
4469 /// BeginFunction - Gather pre-function debug information. Assumes being
4470 /// emitted immediately after the function entry point.
4471 void DwarfWriter::BeginFunction(MachineFunction *MF) {
4472 DE->BeginFunction(MF);
4473 DD->BeginFunction(MF);
4476 /// EndFunction - Gather and emit post-function debug information.
4478 void DwarfWriter::EndFunction(MachineFunction *MF) {
4479 DD->EndFunction(MF);
4482 if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI())
4483 // Clear function debug information.
4487 /// ValidDebugInfo - Return true if V represents valid debug info value.
4488 bool DwarfWriter::ValidDebugInfo(Value *V) {
4489 return DD && DD->ValidDebugInfo(V);
4492 /// RecordSourceLine - Records location information and associates it with a
4493 /// label. Returns a unique label ID used to generate a label and provide
4494 /// correspondence to the source line list.
4495 unsigned DwarfWriter::RecordSourceLine(unsigned Line, unsigned Col,
4497 return DD->RecordSourceLine(Line, Col, Src);
4500 /// getOrCreateSourceID - Look up the source id with the given directory and
4501 /// source file names. If none currently exists, create a new id and insert it
4502 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames maps
4504 unsigned DwarfWriter::getOrCreateSourceID(const std::string &DirName,
4505 const std::string &FileName) {
4506 return DD->getOrCreateSourceID(DirName, FileName);
4509 /// RecordRegionStart - Indicate the start of a region.
4510 unsigned DwarfWriter::RecordRegionStart(GlobalVariable *V) {
4511 return DD->RecordRegionStart(V);
4514 /// RecordRegionEnd - Indicate the end of a region.
4515 unsigned DwarfWriter::RecordRegionEnd(GlobalVariable *V) {
4516 return DD->RecordRegionEnd(V);
4519 /// getRecordSourceLineCount - Count source lines.
4520 unsigned DwarfWriter::getRecordSourceLineCount() {
4521 return DD->getRecordSourceLineCount();
4524 /// RecordVariable - Indicate the declaration of a local variable.
4526 void DwarfWriter::RecordVariable(GlobalVariable *GV, unsigned FrameIndex) {
4527 DD->RecordVariable(GV, FrameIndex);
4530 /// ShouldEmitDwarfDebug - Returns true if Dwarf debugging declarations should
4532 bool DwarfWriter::ShouldEmitDwarfDebug() const {
4533 return DD->ShouldEmitDwarfDebug();