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 StringMap<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 StringMap<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 const 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);
1075 if (Asm->isVerbose())
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()
1143 virtual ~DbgScope() {
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); }
1166 virtual bool isInlinedSubroutine() { return false; }
1167 virtual unsigned getLine() { assert ( 0 && "Unexpected scope!"); return 0; }
1168 virtual unsigned getColumn() { assert ( 0 && "Unexpected scope!"); return 0; }
1169 virtual unsigned getFile() { assert ( 0 && "Unexpected scope!"); return 0; }
1173 //===----------------------------------------------------------------------===//
1174 /// DbgInlinedSubroutineScope - This class is used to track inlined subroutine
1175 /// scope information.
1177 class DbgInlinedSubroutineScope : public DbgScope {
1182 DbgInlinedSubroutineScope(DbgScope *P, DIDescriptor D,
1183 unsigned S, unsigned L, unsigned C)
1184 : DbgScope(P, D), Src(S), Line(L), Col(C)
1187 unsigned getLine() { return Line; }
1188 unsigned getColumn() { return Col; }
1189 unsigned getFile() { return Src; }
1190 bool isInlinedSubroutine() { return true; }
1193 //===----------------------------------------------------------------------===//
1194 /// DwarfDebug - Emits Dwarf debug directives.
1196 class DwarfDebug : public Dwarf {
1197 //===--------------------------------------------------------------------===//
1198 // Attributes used to construct specific Dwarf sections.
1201 /// CompileUnitMap - A map of global variables representing compile units to
1203 DenseMap<Value *, CompileUnit *> CompileUnitMap;
1205 /// CompileUnits - All the compile units in this module.
1207 SmallVector<CompileUnit *, 8> CompileUnits;
1209 /// MainCU - Some platform prefers one compile unit per .o file. In such
1210 /// cases, all dies are inserted in MainCU.
1211 CompileUnit *MainCU;
1213 /// AbbreviationsSet - Used to uniquely define abbreviations.
1215 FoldingSet<DIEAbbrev> AbbreviationsSet;
1217 /// Abbreviations - A list of all the unique abbreviations in use.
1219 std::vector<DIEAbbrev *> Abbreviations;
1221 /// DirectoryIdMap - Directory name to directory id map.
1223 StringMap<unsigned> DirectoryIdMap;
1225 /// DirectoryNames - A list of directory names.
1226 SmallVector<std::string, 8> DirectoryNames;
1228 /// SourceFileIdMap - Source file name to source file id map.
1230 StringMap<unsigned> SourceFileIdMap;
1232 /// SourceFileNames - A list of source file names.
1233 SmallVector<std::string, 8> SourceFileNames;
1235 /// SourceIdMap - Source id map, i.e. pair of directory id and source file
1236 /// id mapped to a unique id.
1237 DenseMap<std::pair<unsigned, unsigned>, unsigned> SourceIdMap;
1239 /// SourceIds - Reverse map from source id to directory id + file id pair.
1241 SmallVector<std::pair<unsigned, unsigned>, 8> SourceIds;
1243 /// Lines - List of of source line correspondence.
1244 std::vector<SrcLineInfo> Lines;
1246 /// ValuesSet - Used to uniquely define values.
1248 FoldingSet<DIEValue> ValuesSet;
1250 /// Values - A list of all the unique values in use.
1252 std::vector<DIEValue *> Values;
1254 /// StringPool - A UniqueVector of strings used by indirect references.
1256 UniqueVector<std::string> StringPool;
1258 /// SectionMap - Provides a unique id per text section.
1260 UniqueVector<const Section*> SectionMap;
1262 /// SectionSourceLines - Tracks line numbers per text section.
1264 std::vector<std::vector<SrcLineInfo> > SectionSourceLines;
1266 /// didInitial - Flag to indicate if initial emission has been done.
1270 /// shouldEmit - Flag to indicate if debug information should be emitted.
1274 // FunctionDbgScope - Top level scope for the current function.
1276 DbgScope *FunctionDbgScope;
1278 /// DbgScopeMap - Tracks the scopes in the current function.
1279 DenseMap<GlobalVariable *, DbgScope *> DbgScopeMap;
1281 /// DbgInlinedScopeMap - Tracks inlined scopes in the current function.
1282 DenseMap<GlobalVariable *, SmallVector<DbgScope *, 2> > DbgInlinedScopeMap;
1284 /// InlineInfo - Keep track of inlined functions and their location.
1285 /// This information is used to populate debug_inlined section.
1286 DenseMap<GlobalVariable *, SmallVector<unsigned, 4> > InlineInfo;
1288 /// InlinedVariableScopes - Scopes information for the inlined subroutine
1290 DenseMap<const MachineInstr *, DbgScope *> InlinedVariableScopes;
1292 /// DebugTimer - Timer for the Dwarf debug writer.
1295 struct FunctionDebugFrameInfo {
1297 std::vector<MachineMove> Moves;
1299 FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
1300 Number(Num), Moves(M) { }
1303 std::vector<FunctionDebugFrameInfo> DebugFrames;
1306 /// getSourceDirectoryAndFileIds - Return the directory and file ids that
1307 /// maps to the source id. Source id starts at 1.
1308 std::pair<unsigned, unsigned>
1309 getSourceDirectoryAndFileIds(unsigned SId) const {
1310 return SourceIds[SId-1];
1313 /// getNumSourceDirectories - Return the number of source directories in the
1315 unsigned getNumSourceDirectories() const {
1316 return DirectoryNames.size();
1319 /// getSourceDirectoryName - Return the name of the directory corresponding
1321 const std::string &getSourceDirectoryName(unsigned Id) const {
1322 return DirectoryNames[Id - 1];
1325 /// getSourceFileName - Return the name of the source file corresponding
1327 const std::string &getSourceFileName(unsigned Id) const {
1328 return SourceFileNames[Id - 1];
1331 /// getNumSourceIds - Return the number of unique source ids.
1332 unsigned getNumSourceIds() const {
1333 return SourceIds.size();
1336 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1338 void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1339 // Profile the node so that we can make it unique.
1340 FoldingSetNodeID ID;
1343 // Check the set for priors.
1344 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1346 // If it's newly added.
1347 if (InSet == &Abbrev) {
1348 // Add to abbreviation list.
1349 Abbreviations.push_back(&Abbrev);
1350 // Assign the vector position + 1 as its number.
1351 Abbrev.setNumber(Abbreviations.size());
1353 // Assign existing abbreviation number.
1354 Abbrev.setNumber(InSet->getNumber());
1358 /// NewString - Add a string to the constant pool and returns a label.
1360 DWLabel NewString(const std::string &String) {
1361 unsigned StringID = StringPool.insert(String);
1362 return DWLabel("string", StringID);
1365 /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1367 DIEntry *NewDIEntry(DIE *Entry = NULL) {
1371 FoldingSetNodeID ID;
1372 DIEntry::Profile(ID, Entry);
1374 Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1376 if (Value) return Value;
1378 Value = new DIEntry(Entry);
1379 ValuesSet.InsertNode(Value, Where);
1381 Value = new DIEntry(Entry);
1384 Values.push_back(Value);
1388 /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1390 void SetDIEntry(DIEntry *Value, DIE *Entry) {
1391 Value->setEntry(Entry);
1392 // Add to values set if not already there. If it is, we merely have a
1393 // duplicate in the values list (no harm.)
1394 ValuesSet.GetOrInsertNode(Value);
1397 /// AddUInt - Add an unsigned integer attribute data and value.
1399 void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1400 if (!Form) Form = DIEInteger::BestForm(false, Integer);
1402 FoldingSetNodeID ID;
1403 DIEInteger::Profile(ID, Integer);
1405 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1407 Value = new DIEInteger(Integer);
1408 ValuesSet.InsertNode(Value, Where);
1409 Values.push_back(Value);
1412 Die->AddValue(Attribute, Form, Value);
1415 /// AddSInt - Add an signed integer attribute data and value.
1417 void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1418 if (!Form) Form = DIEInteger::BestForm(true, Integer);
1420 FoldingSetNodeID ID;
1421 DIEInteger::Profile(ID, (uint64_t)Integer);
1423 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1425 Value = new DIEInteger(Integer);
1426 ValuesSet.InsertNode(Value, Where);
1427 Values.push_back(Value);
1430 Die->AddValue(Attribute, Form, Value);
1433 /// AddString - Add a string attribute data and value.
1435 void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1436 const std::string &String) {
1437 FoldingSetNodeID ID;
1438 DIEString::Profile(ID, String);
1440 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1442 Value = new DIEString(String);
1443 ValuesSet.InsertNode(Value, Where);
1444 Values.push_back(Value);
1447 Die->AddValue(Attribute, Form, Value);
1450 /// AddLabel - Add a Dwarf label attribute data and value.
1452 void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1453 const DWLabel &Label) {
1454 FoldingSetNodeID ID;
1455 DIEDwarfLabel::Profile(ID, Label);
1457 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1459 Value = new DIEDwarfLabel(Label);
1460 ValuesSet.InsertNode(Value, Where);
1461 Values.push_back(Value);
1464 Die->AddValue(Attribute, Form, Value);
1467 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1469 void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1470 const std::string &Label) {
1471 FoldingSetNodeID ID;
1472 DIEObjectLabel::Profile(ID, Label);
1474 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1476 Value = new DIEObjectLabel(Label);
1477 ValuesSet.InsertNode(Value, Where);
1478 Values.push_back(Value);
1481 Die->AddValue(Attribute, Form, Value);
1484 /// AddSectionOffset - Add a section offset label attribute data and value.
1486 void AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
1487 const DWLabel &Label, const DWLabel &Section,
1488 bool isEH = false, bool useSet = true) {
1489 FoldingSetNodeID ID;
1490 DIESectionOffset::Profile(ID, Label, Section);
1492 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1494 Value = new DIESectionOffset(Label, Section, isEH, useSet);
1495 ValuesSet.InsertNode(Value, Where);
1496 Values.push_back(Value);
1499 Die->AddValue(Attribute, Form, Value);
1502 /// AddDelta - Add a label delta attribute data and value.
1504 void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1505 const DWLabel &Hi, const DWLabel &Lo) {
1506 FoldingSetNodeID ID;
1507 DIEDelta::Profile(ID, Hi, Lo);
1509 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1511 Value = new DIEDelta(Hi, Lo);
1512 ValuesSet.InsertNode(Value, Where);
1513 Values.push_back(Value);
1516 Die->AddValue(Attribute, Form, Value);
1519 /// AddDIEntry - Add a DIE attribute data and value.
1521 void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1522 Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1525 /// AddBlock - Add block data.
1527 void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1528 Block->ComputeSize(*this);
1529 FoldingSetNodeID ID;
1532 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1535 ValuesSet.InsertNode(Value, Where);
1536 Values.push_back(Value);
1538 // Already exists, reuse the previous one.
1540 Block = cast<DIEBlock>(Value);
1543 Die->AddValue(Attribute, Block->BestForm(), Value);
1546 /// AddSourceLine - Add location information to specified debug information
1548 void AddSourceLine(DIE *Die, const DIVariable *V) {
1549 unsigned FileID = 0;
1550 unsigned Line = V->getLineNumber();
1551 CompileUnit *Unit = FindCompileUnit(V->getCompileUnit());
1552 FileID = Unit->getID();
1553 assert (FileID && "Invalid file id");
1554 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1555 AddUInt(Die, DW_AT_decl_line, 0, Line);
1558 /// AddSourceLine - Add location information to specified debug information
1560 void AddSourceLine(DIE *Die, const DIGlobal *G) {
1561 unsigned FileID = 0;
1562 unsigned Line = G->getLineNumber();
1563 CompileUnit *Unit = FindCompileUnit(G->getCompileUnit());
1564 FileID = Unit->getID();
1565 assert (FileID && "Invalid file id");
1566 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1567 AddUInt(Die, DW_AT_decl_line, 0, Line);
1570 void AddSourceLine(DIE *Die, const DIType *Ty) {
1571 unsigned FileID = 0;
1572 unsigned Line = Ty->getLineNumber();
1573 DICompileUnit CU = Ty->getCompileUnit();
1576 CompileUnit *Unit = FindCompileUnit(CU);
1577 FileID = Unit->getID();
1578 assert (FileID && "Invalid file id");
1579 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1580 AddUInt(Die, DW_AT_decl_line, 0, Line);
1583 /// AddAddress - Add an address attribute to a die based on the location
1585 void AddAddress(DIE *Die, unsigned Attribute,
1586 const MachineLocation &Location) {
1587 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
1588 DIEBlock *Block = new DIEBlock();
1590 if (Location.isReg()) {
1592 AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1594 AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1595 AddUInt(Block, 0, DW_FORM_udata, Reg);
1599 AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1601 AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1602 AddUInt(Block, 0, DW_FORM_udata, Reg);
1604 AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1607 AddBlock(Die, Attribute, 0, Block);
1610 /// AddType - Add a new type attribute to the specified entity.
1611 void AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
1615 // Check for pre-existence.
1616 DIEntry *&Slot = DW_Unit->getDIEntrySlotFor(Ty.getGV());
1617 // If it exists then use the existing value.
1619 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1624 Slot = NewDIEntry();
1627 DIE Buffer(DW_TAG_base_type);
1628 if (Ty.isBasicType(Ty.getTag()))
1629 ConstructTypeDIE(DW_Unit, Buffer, DIBasicType(Ty.getGV()));
1630 else if (Ty.isDerivedType(Ty.getTag()))
1631 ConstructTypeDIE(DW_Unit, Buffer, DIDerivedType(Ty.getGV()));
1633 assert(Ty.isCompositeType(Ty.getTag()) && "Unknown kind of DIType");
1634 ConstructTypeDIE(DW_Unit, Buffer, DICompositeType(Ty.getGV()));
1637 // Add debug information entry to entity and appropriate context.
1639 DIDescriptor Context = Ty.getContext();
1640 if (!Context.isNull())
1641 Die = DW_Unit->getDieMapSlotFor(Context.getGV());
1644 DIE *Child = new DIE(Buffer);
1645 Die->AddChild(Child);
1647 SetDIEntry(Slot, Child);
1649 Die = DW_Unit->AddDie(Buffer);
1650 SetDIEntry(Slot, Die);
1653 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1656 /// ConstructTypeDIE - Construct basic type die from DIBasicType.
1657 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1660 // Get core information.
1663 Buffer.setTag(DW_TAG_base_type);
1664 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BTy.getEncoding());
1665 // Add name if not anonymous or intermediate type.
1667 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1668 uint64_t Size = BTy.getSizeInBits() >> 3;
1669 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1672 /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
1673 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1674 DIDerivedType DTy) {
1676 // Get core information.
1679 uint64_t Size = DTy.getSizeInBits() >> 3;
1680 unsigned Tag = DTy.getTag();
1682 // FIXME - Workaround for templates.
1683 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1687 // Map to main type, void will not have a type.
1688 DIType FromTy = DTy.getTypeDerivedFrom();
1689 AddType(DW_Unit, &Buffer, FromTy);
1691 // Add name if not anonymous or intermediate type.
1693 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1695 // Add size if non-zero (derived types might be zero-sized.)
1697 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1699 // Add source line info if available and TyDesc is not a forward
1701 if (!DTy.isForwardDecl())
1702 AddSourceLine(&Buffer, &DTy);
1705 /// ConstructTypeDIE - Construct type DIE from DICompositeType.
1706 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1707 DICompositeType CTy) {
1708 // Get core information.
1712 uint64_t Size = CTy.getSizeInBits() >> 3;
1713 unsigned Tag = CTy.getTag();
1717 case DW_TAG_vector_type:
1718 case DW_TAG_array_type:
1719 ConstructArrayTypeDIE(DW_Unit, Buffer, &CTy);
1721 case DW_TAG_enumeration_type:
1723 DIArray Elements = CTy.getTypeArray();
1724 // Add enumerators to enumeration type.
1725 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1726 DIE *ElemDie = NULL;
1727 DIEnumerator Enum(Elements.getElement(i).getGV());
1728 ElemDie = ConstructEnumTypeDIE(DW_Unit, &Enum);
1729 Buffer.AddChild(ElemDie);
1733 case DW_TAG_subroutine_type:
1735 // Add prototype flag.
1736 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1737 DIArray Elements = CTy.getTypeArray();
1739 DIDescriptor RTy = Elements.getElement(0);
1740 AddType(DW_Unit, &Buffer, DIType(RTy.getGV()));
1743 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1744 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1745 DIDescriptor Ty = Elements.getElement(i);
1746 AddType(DW_Unit, Arg, DIType(Ty.getGV()));
1747 Buffer.AddChild(Arg);
1751 case DW_TAG_structure_type:
1752 case DW_TAG_union_type:
1753 case DW_TAG_class_type:
1755 // Add elements to structure type.
1756 DIArray Elements = CTy.getTypeArray();
1758 // A forward struct declared type may not have elements available.
1759 if (Elements.isNull())
1762 // Add elements to structure type.
1763 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1764 DIDescriptor Element = Elements.getElement(i);
1765 DIE *ElemDie = NULL;
1766 if (Element.getTag() == dwarf::DW_TAG_subprogram)
1767 ElemDie = CreateSubprogramDIE(DW_Unit,
1768 DISubprogram(Element.getGV()));
1769 else if (Element.getTag() == dwarf::DW_TAG_variable) // ???
1770 ElemDie = CreateGlobalVariableDIE(DW_Unit,
1771 DIGlobalVariable(Element.getGV()));
1773 ElemDie = CreateMemberDIE(DW_Unit,
1774 DIDerivedType(Element.getGV()));
1775 Buffer.AddChild(ElemDie);
1777 unsigned RLang = CTy.getRunTimeLang();
1779 AddUInt(&Buffer, DW_AT_APPLE_runtime_class, DW_FORM_data1, RLang);
1786 // Add name if not anonymous or intermediate type.
1788 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1790 if (Tag == DW_TAG_enumeration_type || Tag == DW_TAG_structure_type
1791 || Tag == DW_TAG_union_type) {
1792 // Add size if non-zero (derived types might be zero-sized.)
1794 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1796 // Add zero size if it is not a forward declaration.
1797 if (CTy.isForwardDecl())
1798 AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
1800 AddUInt(&Buffer, DW_AT_byte_size, 0, 0);
1803 // Add source line info if available.
1804 if (!CTy.isForwardDecl())
1805 AddSourceLine(&Buffer, &CTy);
1809 /// ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
1810 void ConstructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1811 int64_t L = SR.getLo();
1812 int64_t H = SR.getHi();
1813 DIE *DW_Subrange = new DIE(DW_TAG_subrange_type);
1815 AddDIEntry(DW_Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1817 AddSInt(DW_Subrange, DW_AT_lower_bound, 0, L);
1818 AddSInt(DW_Subrange, DW_AT_upper_bound, 0, H);
1820 Buffer.AddChild(DW_Subrange);
1823 /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
1824 void ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1825 DICompositeType *CTy) {
1826 Buffer.setTag(DW_TAG_array_type);
1827 if (CTy->getTag() == DW_TAG_vector_type)
1828 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1830 // Emit derived type.
1831 AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
1832 DIArray Elements = CTy->getTypeArray();
1834 // Construct an anonymous type for index type.
1835 DIE IdxBuffer(DW_TAG_base_type);
1836 AddUInt(&IdxBuffer, DW_AT_byte_size, 0, sizeof(int32_t));
1837 AddUInt(&IdxBuffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
1838 DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
1840 // Add subranges to array type.
1841 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1842 DIDescriptor Element = Elements.getElement(i);
1843 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1844 ConstructSubrangeDIE(Buffer, DISubrange(Element.getGV()), IndexTy);
1848 /// ConstructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1849 DIE *ConstructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) {
1851 DIE *Enumerator = new DIE(DW_TAG_enumerator);
1854 AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
1855 int64_t Value = ETy->getEnumValue();
1856 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1860 /// CreateGlobalVariableDIE - Create new DIE using GV.
1861 DIE *CreateGlobalVariableDIE(CompileUnit *DW_Unit, const DIGlobalVariable &GV)
1863 DIE *GVDie = new DIE(DW_TAG_variable);
1865 GV.getDisplayName(Name);
1866 AddString(GVDie, DW_AT_name, DW_FORM_string, Name);
1867 std::string LinkageName;
1868 GV.getLinkageName(LinkageName);
1869 if (!LinkageName.empty())
1870 AddString(GVDie, DW_AT_MIPS_linkage_name, DW_FORM_string, LinkageName);
1871 AddType(DW_Unit, GVDie, GV.getType());
1872 if (!GV.isLocalToUnit())
1873 AddUInt(GVDie, DW_AT_external, DW_FORM_flag, 1);
1874 AddSourceLine(GVDie, &GV);
1878 /// CreateMemberDIE - Create new member DIE.
1879 DIE *CreateMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT) {
1880 DIE *MemberDie = new DIE(DT.getTag());
1884 AddString(MemberDie, DW_AT_name, DW_FORM_string, Name);
1886 AddType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
1888 AddSourceLine(MemberDie, &DT);
1890 uint64_t Size = DT.getSizeInBits();
1891 uint64_t FieldSize = DT.getOriginalTypeSize();
1893 if (Size != FieldSize) {
1895 AddUInt(MemberDie, DW_AT_byte_size, 0, DT.getOriginalTypeSize() >> 3);
1896 AddUInt(MemberDie, DW_AT_bit_size, 0, DT.getSizeInBits());
1898 uint64_t Offset = DT.getOffsetInBits();
1899 uint64_t FieldOffset = Offset;
1900 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1901 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1902 FieldOffset = (HiMark - FieldSize);
1903 Offset -= FieldOffset;
1904 // Maybe we need to work from the other end.
1905 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1906 AddUInt(MemberDie, DW_AT_bit_offset, 0, Offset);
1908 DIEBlock *Block = new DIEBlock();
1909 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1910 AddUInt(Block, 0, DW_FORM_udata, DT.getOffsetInBits() >> 3);
1911 AddBlock(MemberDie, DW_AT_data_member_location, 0, Block);
1913 if (DT.isProtected())
1914 AddUInt(MemberDie, DW_AT_accessibility, 0, DW_ACCESS_protected);
1915 else if (DT.isPrivate())
1916 AddUInt(MemberDie, DW_AT_accessibility, 0, DW_ACCESS_private);
1921 /// CreateSubprogramDIE - Create new DIE using SP.
1922 DIE *CreateSubprogramDIE(CompileUnit *DW_Unit,
1923 const DISubprogram &SP,
1924 bool IsConstructor = false) {
1925 DIE *SPDie = new DIE(DW_TAG_subprogram);
1928 AddString(SPDie, DW_AT_name, DW_FORM_string, Name);
1929 std::string LinkageName;
1930 SP.getLinkageName(LinkageName);
1931 if (!LinkageName.empty())
1932 AddString(SPDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1934 AddSourceLine(SPDie, &SP);
1936 DICompositeType SPTy = SP.getType();
1937 DIArray Args = SPTy.getTypeArray();
1940 unsigned SPTag = SPTy.getTag();
1941 if (!IsConstructor) {
1942 if (Args.isNull() || SPTag != DW_TAG_subroutine_type)
1943 AddType(DW_Unit, SPDie, SPTy);
1945 AddType(DW_Unit, SPDie, DIType(Args.getElement(0).getGV()));
1948 if (!SP.isDefinition()) {
1949 AddUInt(SPDie, DW_AT_declaration, DW_FORM_flag, 1);
1951 // Do not add arguments for subprogram definition. They will be
1952 // handled through RecordVariable.
1953 if (SPTag == DW_TAG_subroutine_type)
1954 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1955 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1956 AddType(DW_Unit, Arg, DIType(Args.getElement(i).getGV()));
1957 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1); // ???
1958 SPDie->AddChild(Arg);
1962 unsigned Lang = SP.getCompileUnit().getLanguage();
1963 if (Lang == DW_LANG_C99 || Lang == DW_LANG_C89
1964 || Lang == DW_LANG_ObjC)
1965 AddUInt(SPDie, DW_AT_prototyped, DW_FORM_flag, 1);
1967 if (!SP.isLocalToUnit())
1968 AddUInt(SPDie, DW_AT_external, DW_FORM_flag, 1);
1970 // DW_TAG_inlined_subroutine may refer to this DIE.
1971 DIE *&Slot = DW_Unit->getDieMapSlotFor(SP.getGV());
1976 /// FindCompileUnit - Get the compile unit for the given descriptor.
1978 CompileUnit *FindCompileUnit(DICompileUnit Unit) {
1979 CompileUnit *DW_Unit = CompileUnitMap[Unit.getGV()];
1980 assert(DW_Unit && "Missing compile unit.");
1984 /// NewDbgScopeVariable - Create a new scope variable.
1986 DIE *NewDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
1987 // Get the descriptor.
1988 const DIVariable &VD = DV->getVariable();
1990 // Translate tag to proper Dwarf tag. The result variable is dropped for
1993 switch (VD.getTag()) {
1994 case DW_TAG_return_variable: return NULL;
1995 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
1996 case DW_TAG_auto_variable: // fall thru
1997 default: Tag = DW_TAG_variable; break;
2000 // Define variable debug information entry.
2001 DIE *VariableDie = new DIE(Tag);
2004 AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
2006 // Add source line info if available.
2007 AddSourceLine(VariableDie, &VD);
2009 // Add variable type.
2010 AddType(Unit, VariableDie, VD.getType());
2012 // Add variable address.
2013 MachineLocation Location;
2014 Location.set(RI->getFrameRegister(*MF),
2015 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
2016 AddAddress(VariableDie, DW_AT_location, Location);
2021 /// getOrCreateScope - Returns the scope associated with the given descriptor.
2023 DbgScope *getOrCreateScope(GlobalVariable *V) {
2024 DbgScope *&Slot = DbgScopeMap[V];
2025 if (Slot) return Slot;
2027 DbgScope *Parent = NULL;
2029 if (!Block.isNull()) {
2030 DIDescriptor ParentDesc = Block.getContext();
2032 ParentDesc.isNull() ? NULL : getOrCreateScope(ParentDesc.getGV());
2034 Slot = new DbgScope(Parent, DIDescriptor(V));
2037 Parent->AddScope(Slot);
2039 // First function is top level function.
2040 FunctionDbgScope = Slot;
2045 /// createInlinedSubroutineScope - Returns the scope associated with the
2046 /// inlined subroutine.
2048 DbgScope *createInlinedSubroutineScope(DISubprogram SP, unsigned Src,
2049 unsigned Line, unsigned Col) {
2051 new DbgInlinedSubroutineScope(NULL, SP, Src, Line, Col);
2053 // FIXME - Add inlined function scopes to the root so we can delete them
2055 assert (FunctionDbgScope && "Function scope info missing!");
2056 FunctionDbgScope->AddScope(Scope);
2060 /// ConstructDbgScope - Construct the components of a scope.
2062 void ConstructDbgScope(DbgScope *ParentScope,
2063 unsigned ParentStartID, unsigned ParentEndID,
2064 DIE *ParentDie, CompileUnit *Unit) {
2065 // Add variables to scope.
2066 SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
2067 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2068 DIE *VariableDie = NewDbgScopeVariable(Variables[i], Unit);
2069 if (VariableDie) ParentDie->AddChild(VariableDie);
2072 // Add nested scopes.
2073 SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
2074 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
2075 // Define the Scope debug information entry.
2076 DbgScope *Scope = Scopes[j];
2078 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
2079 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
2081 // Ignore empty scopes.
2082 // Do not ignore inlined scope even if it does not have any
2083 // variables or scopes.
2084 if (StartID == EndID && StartID != 0) continue;
2085 if (!Scope->isInlinedSubroutine()
2086 && Scope->getScopes().empty() && Scope->getVariables().empty())
2089 if (StartID == ParentStartID && EndID == ParentEndID) {
2090 // Just add stuff to the parent scope.
2091 ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
2093 DIE *ScopeDie = NULL;
2094 if (MainCU && TAI->doesDwarfUsesInlineInfoSection()
2095 && Scope->isInlinedSubroutine()) {
2096 ScopeDie = new DIE(DW_TAG_inlined_subroutine);
2097 DIE *Origin = MainCU->getDieMapSlotFor(Scope->getDesc().getGV());
2098 AddDIEntry(ScopeDie, DW_AT_abstract_origin, DW_FORM_ref4, Origin);
2099 AddUInt(ScopeDie, DW_AT_call_file, 0, Scope->getFile());
2100 AddUInt(ScopeDie, DW_AT_call_line, 0, Scope->getLine());
2101 AddUInt(ScopeDie, DW_AT_call_column, 0, Scope->getColumn());
2103 ScopeDie = new DIE(DW_TAG_lexical_block);
2106 // Add the scope bounds.
2108 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2109 DWLabel("label", StartID));
2111 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2112 DWLabel("func_begin", SubprogramCount));
2115 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2116 DWLabel("label", EndID));
2118 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2119 DWLabel("func_end", SubprogramCount));
2121 // Add the scope contents.
2122 ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
2123 ParentDie->AddChild(ScopeDie);
2128 /// ConstructFunctionDbgScope - Construct the scope for the subprogram.
2130 void ConstructFunctionDbgScope(DbgScope *RootScope) {
2131 // Exit if there is no root scope.
2132 if (!RootScope) return;
2133 DIDescriptor Desc = RootScope->getDesc();
2137 // Get the subprogram debug information entry.
2138 DISubprogram SPD(Desc.getGV());
2140 // Get the compile unit context.
2141 CompileUnit *Unit = MainCU;
2143 Unit = FindCompileUnit(SPD.getCompileUnit());
2145 // Get the subprogram die.
2146 DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
2147 assert(SPDie && "Missing subprogram descriptor");
2149 // Add the function bounds.
2150 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2151 DWLabel("func_begin", SubprogramCount));
2152 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2153 DWLabel("func_end", SubprogramCount));
2154 MachineLocation Location(RI->getFrameRegister(*MF));
2155 AddAddress(SPDie, DW_AT_frame_base, Location);
2157 ConstructDbgScope(RootScope, 0, 0, SPDie, Unit);
2160 /// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
2162 void ConstructDefaultDbgScope(MachineFunction *MF) {
2163 const char *FnName = MF->getFunction()->getNameStart();
2165 StringMap<DIE*> &Globals = MainCU->getGlobals();
2166 StringMap<DIE*>::iterator GI = Globals.find(FnName);
2167 if (GI != Globals.end()) {
2168 DIE *SPDie = GI->second;
2170 // Add the function bounds.
2171 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2172 DWLabel("func_begin", SubprogramCount));
2173 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2174 DWLabel("func_end", SubprogramCount));
2176 MachineLocation Location(RI->getFrameRegister(*MF));
2177 AddAddress(SPDie, DW_AT_frame_base, Location);
2181 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
2182 CompileUnit *Unit = CompileUnits[i];
2183 StringMap<DIE*> &Globals = Unit->getGlobals();
2184 StringMap<DIE*>::iterator GI = Globals.find(FnName);
2185 if (GI != Globals.end()) {
2186 DIE *SPDie = GI->second;
2188 // Add the function bounds.
2189 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2190 DWLabel("func_begin", SubprogramCount));
2191 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2192 DWLabel("func_end", SubprogramCount));
2194 MachineLocation Location(RI->getFrameRegister(*MF));
2195 AddAddress(SPDie, DW_AT_frame_base, Location);
2202 // FIXME: This is causing an abort because C++ mangled names are compared
2203 // with their unmangled counterparts. See PR2885. Don't do this assert.
2204 assert(0 && "Couldn't find DIE for machine function!");
2209 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
2210 /// tools to recognize the object file contains Dwarf information.
2211 void EmitInitial() {
2212 // Check to see if we already emitted intial headers.
2213 if (didInitial) return;
2216 // Dwarf sections base addresses.
2217 if (TAI->doesDwarfRequireFrameSection()) {
2218 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2219 EmitLabel("section_debug_frame", 0);
2221 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2222 EmitLabel("section_info", 0);
2223 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2224 EmitLabel("section_abbrev", 0);
2225 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2226 EmitLabel("section_aranges", 0);
2227 if (TAI->doesSupportMacInfoSection()) {
2228 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2229 EmitLabel("section_macinfo", 0);
2231 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2232 EmitLabel("section_line", 0);
2233 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2234 EmitLabel("section_loc", 0);
2235 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2236 EmitLabel("section_pubnames", 0);
2237 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2238 EmitLabel("section_str", 0);
2239 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2240 EmitLabel("section_ranges", 0);
2242 Asm->SwitchToSection(TAI->getTextSection());
2243 EmitLabel("text_begin", 0);
2244 Asm->SwitchToSection(TAI->getDataSection());
2245 EmitLabel("data_begin", 0);
2248 /// EmitDIE - Recusively Emits a debug information entry.
2250 void EmitDIE(DIE *Die) {
2251 // Get the abbreviation for this DIE.
2252 unsigned AbbrevNumber = Die->getAbbrevNumber();
2253 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2257 // Emit the code (index) for the abbreviation.
2258 Asm->EmitULEB128Bytes(AbbrevNumber);
2260 if (Asm->isVerbose())
2261 Asm->EOL(std::string("Abbrev [" +
2262 utostr(AbbrevNumber) +
2263 "] 0x" + utohexstr(Die->getOffset()) +
2264 ":0x" + utohexstr(Die->getSize()) + " " +
2265 TagString(Abbrev->getTag())));
2269 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2270 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2272 // Emit the DIE attribute values.
2273 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2274 unsigned Attr = AbbrevData[i].getAttribute();
2275 unsigned Form = AbbrevData[i].getForm();
2276 assert(Form && "Too many attributes for DIE (check abbreviation)");
2279 case DW_AT_sibling: {
2280 Asm->EmitInt32(Die->SiblingOffset());
2284 // Emit an attribute using the defined form.
2285 Values[i]->EmitValue(*this, Form);
2290 Asm->EOL(AttributeString(Attr));
2293 // Emit the DIE children if any.
2294 if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2295 const std::vector<DIE *> &Children = Die->getChildren();
2297 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2298 EmitDIE(Children[j]);
2301 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2305 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2307 unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2308 // Get the children.
2309 const std::vector<DIE *> &Children = Die->getChildren();
2311 // If not last sibling and has children then add sibling offset attribute.
2312 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2314 // Record the abbreviation.
2315 AssignAbbrevNumber(Die->getAbbrev());
2317 // Get the abbreviation for this DIE.
2318 unsigned AbbrevNumber = Die->getAbbrevNumber();
2319 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2322 Die->setOffset(Offset);
2324 // Start the size with the size of abbreviation code.
2325 Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
2327 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2328 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2330 // Size the DIE attribute values.
2331 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2332 // Size attribute value.
2333 Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2336 // Size the DIE children if any.
2337 if (!Children.empty()) {
2338 assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2339 "Children flag not set");
2341 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2342 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2345 // End of children marker.
2346 Offset += sizeof(int8_t);
2349 Die->setSize(Offset - Die->getOffset());
2353 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2355 void SizeAndOffsets() {
2356 // Process base compile unit.
2358 // Compute size of compile unit header
2359 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2360 sizeof(int16_t) + // DWARF version number
2361 sizeof(int32_t) + // Offset Into Abbrev. Section
2362 sizeof(int8_t); // Pointer Size (in bytes)
2363 SizeAndOffsetDie(MainCU->getDie(), Offset, true);
2366 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
2367 CompileUnit *Unit = CompileUnits[i];
2368 // Compute size of compile unit header
2369 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2370 sizeof(int16_t) + // DWARF version number
2371 sizeof(int32_t) + // Offset Into Abbrev. Section
2372 sizeof(int8_t); // Pointer Size (in bytes)
2373 SizeAndOffsetDie(Unit->getDie(), Offset, true);
2377 /// EmitDebugInfo / EmitDebugInfoPerCU - Emit the debug info section.
2379 void EmitDebugInfoPerCU(CompileUnit *Unit) {
2380 DIE *Die = Unit->getDie();
2381 // Emit the compile units header.
2382 EmitLabel("info_begin", Unit->getID());
2383 // Emit size of content not including length itself
2384 unsigned ContentSize = Die->getSize() +
2385 sizeof(int16_t) + // DWARF version number
2386 sizeof(int32_t) + // Offset Into Abbrev. Section
2387 sizeof(int8_t) + // Pointer Size (in bytes)
2388 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2390 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2391 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2392 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2393 Asm->EOL("Offset Into Abbrev. Section");
2394 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2397 // FIXME - extra padding for gdb bug.
2398 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2399 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2400 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2401 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2402 EmitLabel("info_end", Unit->getID());
2407 void EmitDebugInfo() {
2408 // Start debug info section.
2409 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2412 EmitDebugInfoPerCU(MainCU);
2416 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
2417 EmitDebugInfoPerCU(CompileUnits[i]);
2420 /// EmitAbbreviations - Emit the abbreviation section.
2422 void EmitAbbreviations() const {
2423 // Check to see if it is worth the effort.
2424 if (!Abbreviations.empty()) {
2425 // Start the debug abbrev section.
2426 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2428 EmitLabel("abbrev_begin", 0);
2430 // For each abbrevation.
2431 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2432 // Get abbreviation data
2433 const DIEAbbrev *Abbrev = Abbreviations[i];
2435 // Emit the abbrevations code (base 1 index.)
2436 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2437 Asm->EOL("Abbreviation Code");
2439 // Emit the abbreviations data.
2440 Abbrev->Emit(*this);
2445 // Mark end of abbreviations.
2446 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2448 EmitLabel("abbrev_end", 0);
2454 /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
2455 /// the line matrix.
2457 void EmitEndOfLineMatrix(unsigned SectionEnd) {
2458 // Define last address of section.
2459 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2460 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2461 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2462 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2464 // Mark end of matrix.
2465 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2466 Asm->EmitULEB128Bytes(1); Asm->EOL();
2467 Asm->EmitInt8(1); Asm->EOL();
2470 /// EmitDebugLines - Emit source line information.
2472 void EmitDebugLines() {
2473 // If the target is using .loc/.file, the assembler will be emitting the
2474 // .debug_line table automatically.
2475 if (TAI->hasDotLocAndDotFile())
2478 // Minimum line delta, thus ranging from -10..(255-10).
2479 const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2480 // Maximum line delta, thus ranging from -10..(255-10).
2481 const int MaxLineDelta = 255 + MinLineDelta;
2483 // Start the dwarf line section.
2484 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2486 // Construct the section header.
2488 EmitDifference("line_end", 0, "line_begin", 0, true);
2489 Asm->EOL("Length of Source Line Info");
2490 EmitLabel("line_begin", 0);
2492 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2494 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2495 Asm->EOL("Prolog Length");
2496 EmitLabel("line_prolog_begin", 0);
2498 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2500 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2502 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2504 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2506 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2508 // Line number standard opcode encodings argument count
2509 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2510 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2511 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2512 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2513 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2514 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2515 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2516 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2517 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2519 // Emit directories.
2520 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2521 Asm->EmitString(getSourceDirectoryName(DI));
2522 Asm->EOL("Directory");
2524 Asm->EmitInt8(0); Asm->EOL("End of directories");
2527 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2528 // Remember source id starts at 1.
2529 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2530 Asm->EmitString(getSourceFileName(Id.second));
2532 Asm->EmitULEB128Bytes(Id.first);
2533 Asm->EOL("Directory #");
2534 Asm->EmitULEB128Bytes(0);
2535 Asm->EOL("Mod date");
2536 Asm->EmitULEB128Bytes(0);
2537 Asm->EOL("File size");
2539 Asm->EmitInt8(0); Asm->EOL("End of files");
2541 EmitLabel("line_prolog_end", 0);
2543 // A sequence for each text section.
2544 unsigned SecSrcLinesSize = SectionSourceLines.size();
2546 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2547 // Isolate current sections line info.
2548 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2550 if (Asm->isVerbose()) {
2551 const Section* S = SectionMap[j + 1];
2552 O << '\t' << TAI->getCommentString() << " Section"
2553 << S->getName() << '\n';
2557 // Dwarf assumes we start with first line of first source file.
2558 unsigned Source = 1;
2561 // Construct rows of the address, source, line, column matrix.
2562 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2563 const SrcLineInfo &LineInfo = LineInfos[i];
2564 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2565 if (!LabelID) continue;
2567 if (!Asm->isVerbose())
2570 std::pair<unsigned, unsigned> SourceID =
2571 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2572 O << '\t' << TAI->getCommentString() << ' '
2573 << getSourceDirectoryName(SourceID.first) << ' '
2574 << getSourceFileName(SourceID.second)
2575 <<" :" << utostr_32(LineInfo.getLine()) << '\n';
2578 // Define the line address.
2579 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2580 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2581 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2582 EmitReference("label", LabelID); Asm->EOL("Location label");
2584 // If change of source, then switch to the new source.
2585 if (Source != LineInfo.getSourceID()) {
2586 Source = LineInfo.getSourceID();
2587 Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2588 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2591 // If change of line.
2592 if (Line != LineInfo.getLine()) {
2593 // Determine offset.
2594 int Offset = LineInfo.getLine() - Line;
2595 int Delta = Offset - MinLineDelta;
2598 Line = LineInfo.getLine();
2600 // If delta is small enough and in range...
2601 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2602 // ... then use fast opcode.
2603 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2605 // ... otherwise use long hand.
2606 Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
2607 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2608 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2611 // Copy the previous row (different address or source)
2612 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2616 EmitEndOfLineMatrix(j + 1);
2619 if (SecSrcLinesSize == 0)
2620 // Because we're emitting a debug_line section, we still need a line
2621 // table. The linker and friends expect it to exist. If there's nothing to
2622 // put into it, emit an empty table.
2623 EmitEndOfLineMatrix(1);
2625 EmitLabel("line_end", 0);
2630 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2632 void EmitCommonDebugFrame() {
2633 if (!TAI->doesDwarfRequireFrameSection())
2637 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2638 TargetFrameInfo::StackGrowsUp ?
2639 TD->getPointerSize() : -TD->getPointerSize();
2641 // Start the dwarf frame section.
2642 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2644 EmitLabel("debug_frame_common", 0);
2645 EmitDifference("debug_frame_common_end", 0,
2646 "debug_frame_common_begin", 0, true);
2647 Asm->EOL("Length of Common Information Entry");
2649 EmitLabel("debug_frame_common_begin", 0);
2650 Asm->EmitInt32((int)DW_CIE_ID);
2651 Asm->EOL("CIE Identifier Tag");
2652 Asm->EmitInt8(DW_CIE_VERSION);
2653 Asm->EOL("CIE Version");
2654 Asm->EmitString("");
2655 Asm->EOL("CIE Augmentation");
2656 Asm->EmitULEB128Bytes(1);
2657 Asm->EOL("CIE Code Alignment Factor");
2658 Asm->EmitSLEB128Bytes(stackGrowth);
2659 Asm->EOL("CIE Data Alignment Factor");
2660 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2661 Asm->EOL("CIE RA Column");
2663 std::vector<MachineMove> Moves;
2664 RI->getInitialFrameState(Moves);
2666 EmitFrameMoves(NULL, 0, Moves, false);
2668 Asm->EmitAlignment(2, 0, 0, false);
2669 EmitLabel("debug_frame_common_end", 0);
2674 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2676 void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2677 if (!TAI->doesDwarfRequireFrameSection())
2680 // Start the dwarf frame section.
2681 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2683 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2684 "debug_frame_begin", DebugFrameInfo.Number, true);
2685 Asm->EOL("Length of Frame Information Entry");
2687 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2689 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2691 Asm->EOL("FDE CIE offset");
2693 EmitReference("func_begin", DebugFrameInfo.Number);
2694 Asm->EOL("FDE initial location");
2695 EmitDifference("func_end", DebugFrameInfo.Number,
2696 "func_begin", DebugFrameInfo.Number);
2697 Asm->EOL("FDE address range");
2699 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
2702 Asm->EmitAlignment(2, 0, 0, false);
2703 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2708 void EmitDebugPubNamesPerCU(CompileUnit *Unit) {
2709 EmitDifference("pubnames_end", Unit->getID(),
2710 "pubnames_begin", Unit->getID(), true);
2711 Asm->EOL("Length of Public Names Info");
2713 EmitLabel("pubnames_begin", Unit->getID());
2715 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
2717 EmitSectionOffset("info_begin", "section_info",
2718 Unit->getID(), 0, true, false);
2719 Asm->EOL("Offset of Compilation Unit Info");
2721 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
2723 Asm->EOL("Compilation Unit Length");
2725 StringMap<DIE*> &Globals = Unit->getGlobals();
2726 for (StringMap<DIE*>::const_iterator
2727 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2728 const char *Name = GI->getKeyData();
2729 DIE * Entity = GI->second;
2731 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2732 Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
2735 Asm->EmitInt32(0); Asm->EOL("End Mark");
2736 EmitLabel("pubnames_end", Unit->getID());
2741 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2743 void EmitDebugPubNames() {
2744 // Start the dwarf pubnames section.
2745 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2748 EmitDebugPubNamesPerCU(MainCU);
2752 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
2753 EmitDebugPubNamesPerCU(CompileUnits[i]);
2756 /// EmitDebugStr - Emit visible names into a debug str section.
2758 void EmitDebugStr() {
2759 // Check to see if it is worth the effort.
2760 if (!StringPool.empty()) {
2761 // Start the dwarf str section.
2762 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2764 // For each of strings in the string pool.
2765 for (unsigned StringID = 1, N = StringPool.size();
2766 StringID <= N; ++StringID) {
2767 // Emit a label for reference from debug information entries.
2768 EmitLabel("string", StringID);
2769 // Emit the string itself.
2770 const std::string &String = StringPool[StringID];
2771 Asm->EmitString(String); Asm->EOL();
2778 /// EmitDebugLoc - Emit visible names into a debug loc section.
2780 void EmitDebugLoc() {
2781 // Start the dwarf loc section.
2782 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2787 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2789 void EmitDebugARanges() {
2790 // Start the dwarf aranges section.
2791 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2795 CompileUnit *Unit = GetBaseCompileUnit();
2797 // Don't include size of length
2798 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2800 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2802 EmitReference("info_begin", Unit->getID());
2803 Asm->EOL("Offset of Compilation Unit Info");
2805 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2807 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2809 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2810 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2813 EmitReference("text_begin", 0); Asm->EOL("Address");
2814 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2816 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2817 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2823 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2825 void EmitDebugRanges() {
2826 // Start the dwarf ranges section.
2827 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2832 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2834 void EmitDebugMacInfo() {
2835 if (TAI->doesSupportMacInfoSection()) {
2836 // Start the dwarf macinfo section.
2837 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2843 /// EmitDebugInlineInfo - Emit inline info using following format.
2845 /// 1. length of section
2846 /// 2. Dwarf version number
2847 /// 3. address size.
2849 /// Entries (one "entry" for each function that was inlined):
2851 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2852 /// otherwise offset into __debug_str for regular function name.
2853 /// 2. offset into __debug_str section for regular function name.
2854 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2855 /// instances for the function.
2857 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2858 /// inlined instance; the die_offset points to the inlined_subroutine die in
2859 /// the __debug_info section, and the low_pc is the starting address for the
2860 /// inlining instance.
2861 void EmitDebugInlineInfo() {
2862 if (!TAI->doesDwarfUsesInlineInfoSection())
2868 Asm->SwitchToDataSection(TAI->getDwarfDebugInlineSection());
2870 EmitDifference("debug_inlined_end", 1,
2871 "debug_inlined_begin", 1, true);
2872 Asm->EOL("Length of Debug Inlined Information Entry");
2874 EmitLabel("debug_inlined_begin", 1);
2876 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2877 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2879 for (DenseMap<GlobalVariable *, SmallVector<unsigned, 4> >::iterator
2880 I = InlineInfo.begin(), E = InlineInfo.end(); I != E; ++I) {
2881 GlobalVariable *GV = I->first;
2882 SmallVector<unsigned, 4> &Labels = I->second;
2883 DISubprogram SP(GV);
2887 SP.getLinkageName(LName);
2890 Asm->EmitString(LName.empty() ? Name : LName);
2891 Asm->EOL("MIPS linkage name");
2893 Asm->EmitString(Name); Asm->EOL("Function name");
2895 Asm->EmitULEB128Bytes(Labels.size()); Asm->EOL("Inline count");
2897 for (SmallVector<unsigned, 4>::iterator LI = Labels.begin(),
2898 LE = Labels.end(); LI != LE; ++LI) {
2899 DIE *SP = MainCU->getDieMapSlotFor(GV);
2900 Asm->EmitInt32(SP->getOffset()); Asm->EOL("DIE offset");
2902 if (TD->getPointerSize() == sizeof(int32_t))
2903 O << TAI->getData32bitsDirective();
2905 O << TAI->getData64bitsDirective();
2906 PrintLabelName("label", *LI); Asm->EOL("low_pc");
2910 EmitLabel("debug_inlined_end", 1);
2914 /// GetOrCreateSourceID - Look up the source id with the given directory and
2915 /// source file names. If none currently exists, create a new id and insert it
2916 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames maps
2918 unsigned GetOrCreateSourceID(const std::string &DirName,
2919 const std::string &FileName) {
2921 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
2922 if (DI != DirectoryIdMap.end()) {
2923 DId = DI->getValue();
2925 DId = DirectoryNames.size() + 1;
2926 DirectoryIdMap[DirName] = DId;
2927 DirectoryNames.push_back(DirName);
2931 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
2932 if (FI != SourceFileIdMap.end()) {
2933 FId = FI->getValue();
2935 FId = SourceFileNames.size() + 1;
2936 SourceFileIdMap[FileName] = FId;
2937 SourceFileNames.push_back(FileName);
2940 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
2941 SourceIdMap.find(std::make_pair(DId, FId));
2942 if (SI != SourceIdMap.end())
2945 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
2946 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
2947 SourceIds.push_back(std::make_pair(DId, FId));
2952 void ConstructCompileUnit(GlobalVariable *GV) {
2953 DICompileUnit DIUnit(GV);
2954 std::string Dir, FN, Prod;
2955 unsigned ID = GetOrCreateSourceID(DIUnit.getDirectory(Dir),
2956 DIUnit.getFilename(FN));
2958 DIE *Die = new DIE(DW_TAG_compile_unit);
2959 AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
2960 DWLabel("section_line", 0), DWLabel("section_line", 0),
2962 AddString(Die, DW_AT_producer, DW_FORM_string, DIUnit.getProducer(Prod));
2963 AddUInt(Die, DW_AT_language, DW_FORM_data1, DIUnit.getLanguage());
2964 AddString(Die, DW_AT_name, DW_FORM_string, FN);
2966 AddString(Die, DW_AT_comp_dir, DW_FORM_string, Dir);
2967 if (DIUnit.isOptimized())
2968 AddUInt(Die, DW_AT_APPLE_optimized, DW_FORM_flag, 1);
2970 DIUnit.getFlags(Flags);
2972 AddString(Die, DW_AT_APPLE_flags, DW_FORM_string, Flags);
2973 unsigned RVer = DIUnit.getRunTimeVersion();
2975 AddUInt(Die, DW_AT_APPLE_major_runtime_vers, DW_FORM_data1, RVer);
2977 CompileUnit *Unit = new CompileUnit(ID, Die);
2978 if (DIUnit.isMain()) {
2979 assert(!MainCU && "Multiple main compile units are found!");
2982 CompileUnitMap[DIUnit.getGV()] = Unit;
2983 CompileUnits.push_back(Unit);
2986 /// ConstructCompileUnits - Create a compile unit DIEs.
2987 void ConstructCompileUnits() {
2988 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.compile_units");
2991 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2992 "Malformed compile unit descriptor anchor type");
2993 Constant *RootC = cast<Constant>(*Root->use_begin());
2994 assert(RootC->hasNUsesOrMore(1) &&
2995 "Malformed compile unit descriptor anchor type");
2996 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2998 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2999 UUI != UUE; ++UUI) {
3000 GlobalVariable *GV = cast<GlobalVariable>(*UUI);
3001 ConstructCompileUnit(GV);
3005 bool ConstructGlobalVariableDIE(GlobalVariable *GV) {
3006 DIGlobalVariable DI_GV(GV);
3007 CompileUnit *DW_Unit = MainCU;
3009 DW_Unit = FindCompileUnit(DI_GV.getCompileUnit());
3011 // Check for pre-existence.
3012 DIE *&Slot = DW_Unit->getDieMapSlotFor(DI_GV.getGV());
3016 DIE *VariableDie = CreateGlobalVariableDIE(DW_Unit, DI_GV);
3019 DIEBlock *Block = new DIEBlock();
3020 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
3022 AddObjectLabel(Block, 0, DW_FORM_udata,
3023 Asm->getGlobalLinkName(DI_GV.getGlobal(), GLN));
3024 AddBlock(VariableDie, DW_AT_location, 0, Block);
3028 // Add to context owner.
3029 DW_Unit->getDie()->AddChild(VariableDie);
3030 // Expose as global. FIXME - need to check external flag.
3032 DW_Unit->AddGlobal(DI_GV.getName(Name), VariableDie);
3036 /// ConstructGlobalVariableDIEs - Create DIEs for each of the externally
3037 /// visible global variables. Return true if at least one global DIE is
3039 bool ConstructGlobalVariableDIEs() {
3040 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.global_variables");
3044 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
3045 "Malformed global variable descriptor anchor type");
3046 Constant *RootC = cast<Constant>(*Root->use_begin());
3047 assert(RootC->hasNUsesOrMore(1) &&
3048 "Malformed global variable descriptor anchor type");
3050 bool Result = false;
3051 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
3053 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
3054 UUI != UUE; ++UUI) {
3055 GlobalVariable *GV = cast<GlobalVariable>(*UUI);
3056 Result |= ConstructGlobalVariableDIE(GV);
3061 bool ConstructSubprogram(GlobalVariable *GV) {
3062 DISubprogram SP(GV);
3063 CompileUnit *Unit = MainCU;
3065 Unit = FindCompileUnit(SP.getCompileUnit());
3067 // Check for pre-existence.
3068 DIE *&Slot = Unit->getDieMapSlotFor(GV);
3072 if (!SP.isDefinition())
3073 // This is a method declaration which will be handled while
3074 // constructing class type.
3077 DIE *SubprogramDie = CreateSubprogramDIE(Unit, SP);
3080 Slot = SubprogramDie;
3081 // Add to context owner.
3082 Unit->getDie()->AddChild(SubprogramDie);
3083 // Expose as global.
3085 Unit->AddGlobal(SP.getName(Name), SubprogramDie);
3089 /// ConstructSubprograms - Create DIEs for each of the externally visible
3090 /// subprograms. Return true if at least one subprogram DIE is created.
3091 bool ConstructSubprograms() {
3092 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.subprograms");
3096 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
3097 "Malformed subprogram descriptor anchor type");
3098 Constant *RootC = cast<Constant>(*Root->use_begin());
3099 assert(RootC->hasNUsesOrMore(1) &&
3100 "Malformed subprogram descriptor anchor type");
3102 bool Result = false;
3103 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
3105 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
3106 UUI != UUE; ++UUI) {
3107 GlobalVariable *GV = cast<GlobalVariable>(*UUI);
3108 Result |= ConstructSubprogram(GV);
3114 //===--------------------------------------------------------------------===//
3115 // Main entry points.
3117 DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3118 : Dwarf(OS, A, T, "dbg"), MainCU(0),
3119 AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(),
3120 ValuesSet(InitValuesSetSize), Values(), StringPool(), SectionMap(),
3121 SectionSourceLines(), didInitial(false), shouldEmit(false),
3122 FunctionDbgScope(0), DebugTimer(0) {
3123 if (TimePassesIsEnabled)
3124 DebugTimer = new Timer("Dwarf Debug Writer",
3125 getDwarfTimerGroup());
3127 virtual ~DwarfDebug() {
3128 for (unsigned j = 0, M = Values.size(); j < M; ++j)
3134 /// ShouldEmitDwarfDebug - Returns true if Dwarf debugging declarations should
3136 bool ShouldEmitDwarfDebug() const { return shouldEmit; }
3138 /// SetDebugInfo - Create global DIEs and emit initial debug info sections.
3139 /// This is inovked by the target AsmPrinter.
3140 void SetDebugInfo(MachineModuleInfo *mmi) {
3141 if (TimePassesIsEnabled)
3142 DebugTimer->startTimer();
3144 // Create all the compile unit DIEs.
3145 ConstructCompileUnits();
3147 if (CompileUnits.empty()) {
3148 if (TimePassesIsEnabled)
3149 DebugTimer->stopTimer();
3154 // Create DIEs for each of the externally visible global variables.
3155 bool globalDIEs = ConstructGlobalVariableDIEs();
3157 // Create DIEs for each of the externally visible subprograms.
3158 bool subprogramDIEs = ConstructSubprograms();
3160 // If there is not any debug info available for any global variables
3161 // and any subprograms then there is not any debug info to emit.
3162 if (!globalDIEs && !subprogramDIEs) {
3163 if (TimePassesIsEnabled)
3164 DebugTimer->stopTimer();
3171 MMI->setDebugInfoAvailability(true);
3173 // Prime section data.
3174 SectionMap.insert(TAI->getTextSection());
3176 // Print out .file directives to specify files for .loc directives. These
3177 // are printed out early so that they precede any .loc directives.
3178 if (TAI->hasDotLocAndDotFile()) {
3179 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
3180 // Remember source id starts at 1.
3181 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
3182 sys::Path FullPath(getSourceDirectoryName(Id.first));
3184 FullPath.appendComponent(getSourceFileName(Id.second));
3185 assert(AppendOk && "Could not append filename to directory!");
3187 Asm->EmitFile(i, FullPath.toString());
3192 // Emit initial sections
3195 if (TimePassesIsEnabled)
3196 DebugTimer->stopTimer();
3199 /// BeginModule - Emit all Dwarf sections that should come prior to the
3201 void BeginModule(Module *M) {
3205 /// EndModule - Emit all Dwarf sections that should come after the content.
3208 if (!ShouldEmitDwarfDebug())
3211 if (TimePassesIsEnabled)
3212 DebugTimer->startTimer();
3214 // Standard sections final addresses.
3215 Asm->SwitchToSection(TAI->getTextSection());
3216 EmitLabel("text_end", 0);
3217 Asm->SwitchToSection(TAI->getDataSection());
3218 EmitLabel("data_end", 0);
3220 // End text sections.
3221 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
3222 Asm->SwitchToSection(SectionMap[i]);
3223 EmitLabel("section_end", i);
3226 // Emit common frame information.
3227 EmitCommonDebugFrame();
3229 // Emit function debug frame information
3230 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
3231 E = DebugFrames.end(); I != E; ++I)
3232 EmitFunctionDebugFrame(*I);
3234 // Compute DIE offsets and sizes.
3237 // Emit all the DIEs into a debug info section
3240 // Corresponding abbreviations into a abbrev section.
3241 EmitAbbreviations();
3243 // Emit source line correspondence into a debug line section.
3246 // Emit info into a debug pubnames section.
3247 EmitDebugPubNames();
3249 // Emit info into a debug str section.
3252 // Emit info into a debug loc section.
3255 // Emit info into a debug aranges section.
3258 // Emit info into a debug ranges section.
3261 // Emit info into a debug macinfo section.
3264 // Emit inline info.
3265 EmitDebugInlineInfo();
3267 if (TimePassesIsEnabled)
3268 DebugTimer->stopTimer();
3271 /// BeginFunction - Gather pre-function debug information. Assumes being
3272 /// emitted immediately after the function entry point.
3273 void BeginFunction(MachineFunction *MF) {
3276 if (!ShouldEmitDwarfDebug()) return;
3278 if (TimePassesIsEnabled)
3279 DebugTimer->startTimer();
3281 // Begin accumulating function debug information.
3282 MMI->BeginFunction(MF);
3284 // Assumes in correct section after the entry point.
3285 EmitLabel("func_begin", ++SubprogramCount);
3287 // Emit label for the implicitly defined dbg.stoppoint at the start of
3289 if (!Lines.empty()) {
3290 const SrcLineInfo &LineInfo = Lines[0];
3291 Asm->printLabel(LineInfo.getLabelID());
3294 if (TimePassesIsEnabled)
3295 DebugTimer->stopTimer();
3298 /// EndFunction - Gather and emit post-function debug information.
3300 void EndFunction(MachineFunction *MF) {
3301 if (!ShouldEmitDwarfDebug()) return;
3303 if (TimePassesIsEnabled)
3304 DebugTimer->startTimer();
3306 // Define end label for subprogram.
3307 EmitLabel("func_end", SubprogramCount);
3309 // Get function line info.
3310 if (!Lines.empty()) {
3311 // Get section line info.
3312 unsigned ID = SectionMap.insert(Asm->CurrentSection_);
3313 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
3314 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
3315 // Append the function info to section info.
3316 SectionLineInfos.insert(SectionLineInfos.end(),
3317 Lines.begin(), Lines.end());
3320 // Construct scopes for subprogram.
3321 if (FunctionDbgScope)
3322 ConstructFunctionDbgScope(FunctionDbgScope);
3324 // FIXME: This is wrong. We are essentially getting past a problem with
3325 // debug information not being able to handle unreachable blocks that have
3326 // debug information in them. In particular, those unreachable blocks that
3327 // have "region end" info in them. That situation results in the "root
3328 // scope" not being created. If that's the case, then emit a "default"
3329 // scope, i.e., one that encompasses the whole function. This isn't
3330 // desirable. And a better way of handling this (and all of the debugging
3331 // information) needs to be explored.
3332 ConstructDefaultDbgScope(MF);
3334 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
3335 MMI->getFrameMoves()));
3338 if (FunctionDbgScope) {
3339 delete FunctionDbgScope;
3340 DbgScopeMap.clear();
3341 DbgInlinedScopeMap.clear();
3342 InlinedVariableScopes.clear();
3343 FunctionDbgScope = NULL;
3348 if (TimePassesIsEnabled)
3349 DebugTimer->stopTimer();
3352 /// ValidDebugInfo - Return true if V represents valid debug info value.
3353 bool ValidDebugInfo(Value *V, CodeGenOpt::Level OptLevel) {
3360 GlobalVariable *GV = getGlobalVariable(V);
3364 if (!GV->hasInternalLinkage () && !GV->hasLinkOnceLinkage())
3367 if (TimePassesIsEnabled)
3368 DebugTimer->startTimer();
3370 DIDescriptor DI(GV);
3372 // Check current version. Allow Version6 for now.
3373 unsigned Version = DI.getVersion();
3374 if (Version != LLVMDebugVersion && Version != LLVMDebugVersion6) {
3375 if (TimePassesIsEnabled)
3376 DebugTimer->stopTimer();
3381 unsigned Tag = DI.getTag();
3383 case DW_TAG_variable:
3384 assert(DIVariable(GV).Verify() && "Invalid DebugInfo value");
3386 case DW_TAG_compile_unit:
3387 assert(DICompileUnit(GV).Verify() && "Invalid DebugInfo value");
3389 case DW_TAG_subprogram:
3390 assert(DISubprogram(GV).Verify() && "Invalid DebugInfo value");
3392 case DW_TAG_lexical_block:
3393 /// FIXME. This interfers with the qualitfy of generated code when
3394 /// during optimization.
3395 if (OptLevel != CodeGenOpt::None)
3401 if (TimePassesIsEnabled)
3402 DebugTimer->stopTimer();
3407 /// RecordSourceLine - Records location information and associates it with a
3408 /// label. Returns a unique label ID used to generate a label and provide
3409 /// correspondence to the source line list.
3410 unsigned RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
3411 if (TimePassesIsEnabled)
3412 DebugTimer->startTimer();
3414 CompileUnit *Unit = CompileUnitMap[V];
3415 assert(Unit && "Unable to find CompileUnit");
3416 unsigned ID = MMI->NextLabelID();
3417 Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
3419 if (TimePassesIsEnabled)
3420 DebugTimer->stopTimer();
3425 /// RecordSourceLine - Records location information and associates it with a
3426 /// label. Returns a unique label ID used to generate a label and provide
3427 /// correspondence to the source line list.
3428 unsigned RecordSourceLine(unsigned Line, unsigned Col, DICompileUnit CU) {
3429 if (TimePassesIsEnabled)
3430 DebugTimer->startTimer();
3432 std::string Dir, Fn;
3433 unsigned Src = GetOrCreateSourceID(CU.getDirectory(Dir),
3434 CU.getFilename(Fn));
3435 unsigned ID = MMI->NextLabelID();
3436 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
3438 if (TimePassesIsEnabled)
3439 DebugTimer->stopTimer();
3444 /// getRecordSourceLineCount - Return the number of source lines in the debug
3446 unsigned getRecordSourceLineCount() const {
3447 return Lines.size();
3450 /// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
3451 /// timed. Look up the source id with the given directory and source file
3452 /// names. If none currently exists, create a new id and insert it in the
3453 /// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
3455 unsigned getOrCreateSourceID(const std::string &DirName,
3456 const std::string &FileName) {
3457 if (TimePassesIsEnabled)
3458 DebugTimer->startTimer();
3460 unsigned SrcId = GetOrCreateSourceID(DirName, FileName);
3462 if (TimePassesIsEnabled)
3463 DebugTimer->stopTimer();
3468 /// RecordRegionStart - Indicate the start of a region.
3469 unsigned RecordRegionStart(GlobalVariable *V) {
3470 if (TimePassesIsEnabled)
3471 DebugTimer->startTimer();
3473 DbgScope *Scope = getOrCreateScope(V);
3474 unsigned ID = MMI->NextLabelID();
3475 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
3477 if (TimePassesIsEnabled)
3478 DebugTimer->stopTimer();
3483 /// RecordRegionEnd - Indicate the end of a region.
3484 unsigned RecordRegionEnd(GlobalVariable *V) {
3485 if (TimePassesIsEnabled)
3486 DebugTimer->startTimer();
3488 DbgScope *Scope = getOrCreateScope(V);
3489 unsigned ID = MMI->NextLabelID();
3490 Scope->setEndLabelID(ID);
3492 if (TimePassesIsEnabled)
3493 DebugTimer->stopTimer();
3498 /// RecordVariable - Indicate the declaration of a local variable.
3499 void RecordVariable(GlobalVariable *GV, unsigned FrameIndex,
3500 const MachineInstr *MI) {
3501 if (TimePassesIsEnabled)
3502 DebugTimer->startTimer();
3504 DIDescriptor Desc(GV);
3505 DbgScope *Scope = NULL;
3507 if (Desc.getTag() == DW_TAG_variable) {
3508 // GV is a global variable.
3509 DIGlobalVariable DG(GV);
3510 Scope = getOrCreateScope(DG.getContext().getGV());
3512 DenseMap<const MachineInstr *, DbgScope *>::iterator
3513 SI = InlinedVariableScopes.find(MI);
3514 if (SI != InlinedVariableScopes.end()) {
3515 // or GV is an inlined local variable.
3518 // or GV is a local variable.
3520 Scope = getOrCreateScope(DV.getContext().getGV());
3524 assert(Scope && "Unable to find variable' scope");
3525 DbgVariable *DV = new DbgVariable(DIVariable(GV), FrameIndex);
3526 Scope->AddVariable(DV);
3528 if (TimePassesIsEnabled)
3529 DebugTimer->stopTimer();
3532 //// RecordInlinedFnStart - Indicate the start of inlined subroutine.
3533 void RecordInlinedFnStart(Instruction *FSI, DISubprogram &SP, unsigned LabelID,
3534 DICompileUnit CU, unsigned Line, unsigned Col) {
3535 if (!TAI->doesDwarfUsesInlineInfoSection())
3538 std::string Dir, Fn;
3539 unsigned Src = GetOrCreateSourceID(CU.getDirectory(Dir),
3540 CU.getFilename(Fn));
3541 DbgScope *Scope = createInlinedSubroutineScope(SP, Src, Line, Col);
3542 Scope->setStartLabelID(LabelID);
3543 MMI->RecordUsedDbgLabel(LabelID);
3544 GlobalVariable *GV = SP.getGV();
3546 DenseMap<GlobalVariable *, SmallVector<DbgScope *, 2> >::iterator
3547 SI = DbgInlinedScopeMap.find(GV);
3549 if (SI == DbgInlinedScopeMap.end())
3550 DbgInlinedScopeMap[GV].push_back(Scope);
3552 SI->second.push_back(Scope);
3554 DenseMap<GlobalVariable *, SmallVector<unsigned, 4> >::iterator
3555 I = InlineInfo.find(GV);
3556 if (I == InlineInfo.end()) {
3557 SmallVector<unsigned, 4> Labels;
3558 Labels.push_back(LabelID);
3559 InlineInfo[GV] = Labels;
3563 SmallVector<unsigned, 4> &Labels = I->second;
3564 Labels.push_back(LabelID);
3567 /// RecordInlinedFnEnd - Indicate the end of inlined subroutine.
3568 unsigned RecordInlinedFnEnd(DISubprogram &SP) {
3569 if (!TAI->doesDwarfUsesInlineInfoSection())
3572 GlobalVariable *GV = SP.getGV();
3573 DenseMap<GlobalVariable *, SmallVector<DbgScope *, 2> >::iterator
3574 I = DbgInlinedScopeMap.find(GV);
3575 if (I == DbgInlinedScopeMap.end())
3578 SmallVector<DbgScope *, 2> &Scopes = I->second;
3579 assert(!Scopes.empty() && "We should have at least one debug scope!");
3580 DbgScope *Scope = Scopes.back(); Scopes.pop_back();
3581 unsigned ID = MMI->NextLabelID();
3582 MMI->RecordUsedDbgLabel(ID);
3583 Scope->setEndLabelID(ID);
3587 /// RecordVariableScope - Record scope for the variable declared by
3588 /// DeclareMI. DeclareMI must describe TargetInstrInfo::DECLARE.
3589 /// Record scopes for only inlined subroutine variables. Other
3590 /// variables' scopes are determined during RecordVariable().
3591 void RecordVariableScope(DIVariable &DV, const MachineInstr *DeclareMI) {
3592 DISubprogram SP(DV.getContext().getGV());
3595 DenseMap<GlobalVariable *, SmallVector<DbgScope *, 2> >::iterator
3596 I = DbgInlinedScopeMap.find(SP.getGV());
3597 if (I == DbgInlinedScopeMap.end())
3600 SmallVector<DbgScope *, 2> &Scopes = I->second;
3601 InlinedVariableScopes[DeclareMI] = Scopes.back();
3606 //===----------------------------------------------------------------------===//
3607 /// DwarfException - Emits Dwarf exception handling directives.
3609 class DwarfException : public Dwarf {
3610 struct FunctionEHFrameInfo {
3613 unsigned PersonalityIndex;
3615 bool hasLandingPads;
3616 std::vector<MachineMove> Moves;
3617 const Function * function;
3619 FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
3621 const std::vector<MachineMove> &M,
3623 FnName(FN), Number(Num), PersonalityIndex(P),
3624 hasCalls(hC), hasLandingPads(hL), Moves(M), function (f) { }
3627 std::vector<FunctionEHFrameInfo> EHFrames;
3629 /// shouldEmitTable - Per-function flag to indicate if EH tables should
3631 bool shouldEmitTable;
3633 /// shouldEmitMoves - Per-function flag to indicate if frame moves info
3634 /// should be emitted.
3635 bool shouldEmitMoves;
3637 /// shouldEmitTableModule - Per-module flag to indicate if EH tables
3638 /// should be emitted.
3639 bool shouldEmitTableModule;
3641 /// shouldEmitFrameModule - Per-module flag to indicate if frame moves
3642 /// should be emitted.
3643 bool shouldEmitMovesModule;
3645 /// ExceptionTimer - Timer for the Dwarf exception writer.
3646 Timer *ExceptionTimer;
3648 /// EmitCommonEHFrame - Emit the common eh unwind frame.
3650 void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
3651 // Size and sign of stack growth.
3653 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3654 TargetFrameInfo::StackGrowsUp ?
3655 TD->getPointerSize() : -TD->getPointerSize();
3657 // Begin eh frame section.
3658 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3660 if (!TAI->doesRequireNonLocalEHFrameLabel())
3661 O << TAI->getEHGlobalPrefix();
3662 O << "EH_frame" << Index << ":\n";
3663 EmitLabel("section_eh_frame", Index);
3665 // Define base labels.
3666 EmitLabel("eh_frame_common", Index);
3668 // Define the eh frame length.
3669 EmitDifference("eh_frame_common_end", Index,
3670 "eh_frame_common_begin", Index, true);
3671 Asm->EOL("Length of Common Information Entry");
3674 EmitLabel("eh_frame_common_begin", Index);
3675 Asm->EmitInt32((int)0);
3676 Asm->EOL("CIE Identifier Tag");
3677 Asm->EmitInt8(DW_CIE_VERSION);
3678 Asm->EOL("CIE Version");
3680 // The personality presence indicates that language specific information
3681 // will show up in the eh frame.
3682 Asm->EmitString(Personality ? "zPLR" : "zR");
3683 Asm->EOL("CIE Augmentation");
3685 // Round out reader.
3686 Asm->EmitULEB128Bytes(1);
3687 Asm->EOL("CIE Code Alignment Factor");
3688 Asm->EmitSLEB128Bytes(stackGrowth);
3689 Asm->EOL("CIE Data Alignment Factor");
3690 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
3691 Asm->EOL("CIE Return Address Column");
3693 // If there is a personality, we need to indicate the functions location.
3695 Asm->EmitULEB128Bytes(7);
3696 Asm->EOL("Augmentation Size");
3698 if (TAI->getNeedsIndirectEncoding()) {
3699 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4 | DW_EH_PE_indirect);
3700 Asm->EOL("Personality (pcrel sdata4 indirect)");
3702 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3703 Asm->EOL("Personality (pcrel sdata4)");
3706 PrintRelDirective(true);
3707 O << TAI->getPersonalityPrefix();
3708 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
3709 O << TAI->getPersonalitySuffix();
3710 if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
3711 O << "-" << TAI->getPCSymbol();
3712 Asm->EOL("Personality");
3714 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3715 Asm->EOL("LSDA Encoding (pcrel sdata4)");
3717 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3718 Asm->EOL("FDE Encoding (pcrel sdata4)");
3720 Asm->EmitULEB128Bytes(1);
3721 Asm->EOL("Augmentation Size");
3723 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3724 Asm->EOL("FDE Encoding (pcrel sdata4)");
3727 // Indicate locations of general callee saved registers in frame.
3728 std::vector<MachineMove> Moves;
3729 RI->getInitialFrameState(Moves);
3730 EmitFrameMoves(NULL, 0, Moves, true);
3732 // On Darwin the linker honors the alignment of eh_frame, which means it
3733 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3734 // you get holes which confuse readers of eh_frame.
3735 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3737 EmitLabel("eh_frame_common_end", Index);
3742 /// EmitEHFrame - Emit function exception frame information.
3744 void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
3745 Function::LinkageTypes linkage = EHFrameInfo.function->getLinkage();
3747 assert(!EHFrameInfo.function->hasAvailableExternallyLinkage() &&
3748 "Should not emit 'available externally' functions at all");
3750 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3752 // Externally visible entry into the functions eh frame info.
3753 // If the corresponding function is static, this should not be
3754 // externally visible.
3755 if (linkage != Function::InternalLinkage &&
3756 linkage != Function::PrivateLinkage) {
3757 if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
3758 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
3761 // If corresponding function is weak definition, this should be too.
3762 if ((linkage == Function::WeakAnyLinkage ||
3763 linkage == Function::WeakODRLinkage ||
3764 linkage == Function::LinkOnceAnyLinkage ||
3765 linkage == Function::LinkOnceODRLinkage) &&
3766 TAI->getWeakDefDirective())
3767 O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
3769 // If there are no calls then you can't unwind. This may mean we can
3770 // omit the EH Frame, but some environments do not handle weak absolute
3772 // If UnwindTablesMandatory is set we cannot do this optimization; the
3773 // unwind info is to be available for non-EH uses.
3774 if (!EHFrameInfo.hasCalls &&
3775 !UnwindTablesMandatory &&
3776 ((linkage != Function::WeakAnyLinkage &&
3777 linkage != Function::WeakODRLinkage &&
3778 linkage != Function::LinkOnceAnyLinkage &&
3779 linkage != Function::LinkOnceODRLinkage) ||
3780 !TAI->getWeakDefDirective() ||
3781 TAI->getSupportsWeakOmittedEHFrame()))
3783 O << EHFrameInfo.FnName << " = 0\n";
3784 // This name has no connection to the function, so it might get
3785 // dead-stripped when the function is not, erroneously. Prohibit
3786 // dead-stripping unconditionally.
3787 if (const char *UsedDirective = TAI->getUsedDirective())
3788 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3790 O << EHFrameInfo.FnName << ":\n";
3793 EmitDifference("eh_frame_end", EHFrameInfo.Number,
3794 "eh_frame_begin", EHFrameInfo.Number, true);
3795 Asm->EOL("Length of Frame Information Entry");
3797 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
3799 if (TAI->doesRequireNonLocalEHFrameLabel()) {
3800 PrintRelDirective(true, true);
3801 PrintLabelName("eh_frame_begin", EHFrameInfo.Number);
3803 if (!TAI->isAbsoluteEHSectionOffsets())
3804 O << "-EH_frame" << EHFrameInfo.PersonalityIndex;
3806 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
3807 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
3811 Asm->EOL("FDE CIE offset");
3813 EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
3814 Asm->EOL("FDE initial location");
3815 EmitDifference("eh_func_end", EHFrameInfo.Number,
3816 "eh_func_begin", EHFrameInfo.Number, true);
3817 Asm->EOL("FDE address range");
3819 // If there is a personality and landing pads then point to the language
3820 // specific data area in the exception table.
3821 if (EHFrameInfo.PersonalityIndex) {
3822 Asm->EmitULEB128Bytes(4);
3823 Asm->EOL("Augmentation size");
3825 if (EHFrameInfo.hasLandingPads)
3826 EmitReference("exception", EHFrameInfo.Number, true, true);
3828 Asm->EmitInt32((int)0);
3829 Asm->EOL("Language Specific Data Area");
3831 Asm->EmitULEB128Bytes(0);
3832 Asm->EOL("Augmentation size");
3835 // Indicate locations of function specific callee saved registers in
3837 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves,
3840 // On Darwin the linker honors the alignment of eh_frame, which means it
3841 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3842 // you get holes which confuse readers of eh_frame.
3843 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3845 EmitLabel("eh_frame_end", EHFrameInfo.Number);
3847 // If the function is marked used, this table should be also. We cannot
3848 // make the mark unconditional in this case, since retaining the table
3849 // also retains the function in this case, and there is code around
3850 // that depends on unused functions (calling undefined externals) being
3851 // dead-stripped to link correctly. Yes, there really is.
3852 if (MMI->getUsedFunctions().count(EHFrameInfo.function))
3853 if (const char *UsedDirective = TAI->getUsedDirective())
3854 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3858 /// EmitExceptionTable - Emit landing pads and actions.
3860 /// The general organization of the table is complex, but the basic concepts
3861 /// are easy. First there is a header which describes the location and
3862 /// organization of the three components that follow.
3863 /// 1. The landing pad site information describes the range of code covered
3864 /// by the try. In our case it's an accumulation of the ranges covered
3865 /// by the invokes in the try. There is also a reference to the landing
3866 /// pad that handles the exception once processed. Finally an index into
3867 /// the actions table.
3868 /// 2. The action table, in our case, is composed of pairs of type ids
3869 /// and next action offset. Starting with the action index from the
3870 /// landing pad site, each type Id is checked for a match to the current
3871 /// exception. If it matches then the exception and type id are passed
3872 /// on to the landing pad. Otherwise the next action is looked up. This
3873 /// chain is terminated with a next action of zero. If no type id is
3874 /// found the the frame is unwound and handling continues.
3875 /// 3. Type id table contains references to all the C++ typeinfo for all
3876 /// catches in the function. This tables is reversed indexed base 1.
3878 /// SharedTypeIds - How many leading type ids two landing pads have in common.
3879 static unsigned SharedTypeIds(const LandingPadInfo *L,
3880 const LandingPadInfo *R) {
3881 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3882 unsigned LSize = LIds.size(), RSize = RIds.size();
3883 unsigned MinSize = LSize < RSize ? LSize : RSize;
3886 for (; Count != MinSize; ++Count)
3887 if (LIds[Count] != RIds[Count])
3893 /// PadLT - Order landing pads lexicographically by type id.
3894 static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
3895 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3896 unsigned LSize = LIds.size(), RSize = RIds.size();
3897 unsigned MinSize = LSize < RSize ? LSize : RSize;
3899 for (unsigned i = 0; i != MinSize; ++i)
3900 if (LIds[i] != RIds[i])
3901 return LIds[i] < RIds[i];
3903 return LSize < RSize;
3907 static inline unsigned getEmptyKey() { return -1U; }
3908 static inline unsigned getTombstoneKey() { return -2U; }
3909 static unsigned getHashValue(const unsigned &Key) { return Key; }
3910 static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
3911 static bool isPod() { return true; }
3914 /// ActionEntry - Structure describing an entry in the actions table.
3915 struct ActionEntry {
3916 int ValueForTypeID; // The value to write - may not be equal to the type id.
3918 struct ActionEntry *Previous;
3921 /// PadRange - Structure holding a try-range and the associated landing pad.
3923 // The index of the landing pad.
3925 // The index of the begin and end labels in the landing pad's label lists.
3926 unsigned RangeIndex;
3929 typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
3931 /// CallSiteEntry - Structure describing an entry in the call-site table.
3932 struct CallSiteEntry {
3933 // The 'try-range' is BeginLabel .. EndLabel.
3934 unsigned BeginLabel; // zero indicates the start of the function.
3935 unsigned EndLabel; // zero indicates the end of the function.
3936 // The landing pad starts at PadLabel.
3937 unsigned PadLabel; // zero indicates that there is no landing pad.
3941 void EmitExceptionTable() {
3942 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
3943 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
3944 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
3945 if (PadInfos.empty()) return;
3947 // Sort the landing pads in order of their type ids. This is used to fold
3948 // duplicate actions.
3949 SmallVector<const LandingPadInfo *, 64> LandingPads;
3950 LandingPads.reserve(PadInfos.size());
3951 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
3952 LandingPads.push_back(&PadInfos[i]);
3953 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
3955 // Negative type ids index into FilterIds, positive type ids index into
3956 // TypeInfos. The value written for a positive type id is just the type
3957 // id itself. For a negative type id, however, the value written is the
3958 // (negative) byte offset of the corresponding FilterIds entry. The byte
3959 // offset is usually equal to the type id, because the FilterIds entries
3960 // are written using a variable width encoding which outputs one byte per
3961 // entry as long as the value written is not too large, but can differ.
3962 // This kind of complication does not occur for positive type ids because
3963 // type infos are output using a fixed width encoding.
3964 // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
3965 SmallVector<int, 16> FilterOffsets;
3966 FilterOffsets.reserve(FilterIds.size());
3968 for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
3969 E = FilterIds.end(); I != E; ++I) {
3970 FilterOffsets.push_back(Offset);
3971 Offset -= TargetAsmInfo::getULEB128Size(*I);
3974 // Compute the actions table and gather the first action index for each
3975 // landing pad site.
3976 SmallVector<ActionEntry, 32> Actions;
3977 SmallVector<unsigned, 64> FirstActions;
3978 FirstActions.reserve(LandingPads.size());
3980 int FirstAction = 0;
3981 unsigned SizeActions = 0;
3982 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3983 const LandingPadInfo *LP = LandingPads[i];
3984 const std::vector<int> &TypeIds = LP->TypeIds;
3985 const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
3986 unsigned SizeSiteActions = 0;
3988 if (NumShared < TypeIds.size()) {
3989 unsigned SizeAction = 0;
3990 ActionEntry *PrevAction = 0;
3993 const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
3994 assert(Actions.size());
3995 PrevAction = &Actions.back();
3996 SizeAction = TargetAsmInfo::getSLEB128Size(PrevAction->NextAction) +
3997 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3998 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
4000 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
4001 SizeAction += -PrevAction->NextAction;
4002 PrevAction = PrevAction->Previous;
4006 // Compute the actions.
4007 for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
4008 int TypeID = TypeIds[I];
4009 assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
4010 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
4011 unsigned SizeTypeID = TargetAsmInfo::getSLEB128Size(ValueForTypeID);
4013 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
4014 SizeAction = SizeTypeID + TargetAsmInfo::getSLEB128Size(NextAction);
4015 SizeSiteActions += SizeAction;
4017 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
4018 Actions.push_back(Action);
4020 PrevAction = &Actions.back();
4023 // Record the first action of the landing pad site.
4024 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
4025 } // else identical - re-use previous FirstAction
4027 FirstActions.push_back(FirstAction);
4029 // Compute this sites contribution to size.
4030 SizeActions += SizeSiteActions;
4033 // Compute the call-site table. The entry for an invoke has a try-range
4034 // containing the call, a non-zero landing pad and an appropriate action.
4035 // The entry for an ordinary call has a try-range containing the call and
4036 // zero for the landing pad and the action. Calls marked 'nounwind' have
4037 // no entry and must not be contained in the try-range of any entry - they
4038 // form gaps in the table. Entries must be ordered by try-range address.
4039 SmallVector<CallSiteEntry, 64> CallSites;
4041 RangeMapType PadMap;
4042 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
4043 // by try-range labels when lowered). Ordinary calls do not, so appropriate
4044 // try-ranges for them need be deduced.
4045 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
4046 const LandingPadInfo *LandingPad = LandingPads[i];
4047 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
4048 unsigned BeginLabel = LandingPad->BeginLabels[j];
4049 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
4050 PadRange P = { i, j };
4051 PadMap[BeginLabel] = P;
4055 // The end label of the previous invoke or nounwind try-range.
4056 unsigned LastLabel = 0;
4058 // Whether there is a potentially throwing instruction (currently this means
4059 // an ordinary call) between the end of the previous try-range and now.
4060 bool SawPotentiallyThrowing = false;
4062 // Whether the last callsite entry was for an invoke.
4063 bool PreviousIsInvoke = false;
4065 // Visit all instructions in order of address.
4066 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
4068 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
4070 if (!MI->isLabel()) {
4071 SawPotentiallyThrowing |= MI->getDesc().isCall();
4075 unsigned BeginLabel = MI->getOperand(0).getImm();
4076 assert(BeginLabel && "Invalid label!");
4078 // End of the previous try-range?
4079 if (BeginLabel == LastLabel)
4080 SawPotentiallyThrowing = false;
4082 // Beginning of a new try-range?
4083 RangeMapType::iterator L = PadMap.find(BeginLabel);
4084 if (L == PadMap.end())
4085 // Nope, it was just some random label.
4088 PadRange P = L->second;
4089 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
4091 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
4092 "Inconsistent landing pad map!");
4094 // If some instruction between the previous try-range and this one may
4095 // throw, create a call-site entry with no landing pad for the region
4096 // between the try-ranges.
4097 if (SawPotentiallyThrowing) {
4098 CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
4099 CallSites.push_back(Site);
4100 PreviousIsInvoke = false;
4103 LastLabel = LandingPad->EndLabels[P.RangeIndex];
4104 assert(BeginLabel && LastLabel && "Invalid landing pad!");
4106 if (LandingPad->LandingPadLabel) {
4107 // This try-range is for an invoke.
4108 CallSiteEntry Site = {BeginLabel, LastLabel,
4109 LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
4111 // Try to merge with the previous call-site.
4112 if (PreviousIsInvoke) {
4113 CallSiteEntry &Prev = CallSites.back();
4114 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
4115 // Extend the range of the previous entry.
4116 Prev.EndLabel = Site.EndLabel;
4121 // Otherwise, create a new call-site.
4122 CallSites.push_back(Site);
4123 PreviousIsInvoke = true;
4126 PreviousIsInvoke = false;
4130 // If some instruction between the previous try-range and the end of the
4131 // function may throw, create a call-site entry with no landing pad for the
4132 // region following the try-range.
4133 if (SawPotentiallyThrowing) {
4134 CallSiteEntry Site = {LastLabel, 0, 0, 0};
4135 CallSites.push_back(Site);
4141 const unsigned SiteStartSize = sizeof(int32_t); // DW_EH_PE_udata4
4142 const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
4143 const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
4144 unsigned SizeSites = CallSites.size() * (SiteStartSize +
4147 for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
4148 SizeSites += TargetAsmInfo::getULEB128Size(CallSites[i].Action);
4151 const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
4152 unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
4154 unsigned TypeOffset = sizeof(int8_t) + // Call site format
4155 TargetAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
4156 SizeSites + SizeActions + SizeTypes;
4158 unsigned TotalSize = sizeof(int8_t) + // LPStart format
4159 sizeof(int8_t) + // TType format
4160 TargetAsmInfo::getULEB128Size(TypeOffset) + // TType base offset
4163 unsigned SizeAlign = (4 - TotalSize) & 3;
4165 // Begin the exception table.
4166 Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
4167 Asm->EmitAlignment(2, 0, 0, false);
4168 O << "GCC_except_table" << SubprogramCount << ":\n";
4169 for (unsigned i = 0; i != SizeAlign; ++i) {
4171 Asm->EOL("Padding");
4173 EmitLabel("exception", SubprogramCount);
4176 Asm->EmitInt8(DW_EH_PE_omit);
4177 Asm->EOL("LPStart format (DW_EH_PE_omit)");
4178 Asm->EmitInt8(DW_EH_PE_absptr);
4179 Asm->EOL("TType format (DW_EH_PE_absptr)");
4180 Asm->EmitULEB128Bytes(TypeOffset);
4181 Asm->EOL("TType base offset");
4182 Asm->EmitInt8(DW_EH_PE_udata4);
4183 Asm->EOL("Call site format (DW_EH_PE_udata4)");
4184 Asm->EmitULEB128Bytes(SizeSites);
4185 Asm->EOL("Call-site table length");
4187 // Emit the landing pad site information.
4188 for (unsigned i = 0; i < CallSites.size(); ++i) {
4189 CallSiteEntry &S = CallSites[i];
4190 const char *BeginTag;
4191 unsigned BeginNumber;
4193 if (!S.BeginLabel) {
4194 BeginTag = "eh_func_begin";
4195 BeginNumber = SubprogramCount;
4198 BeginNumber = S.BeginLabel;
4201 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
4203 Asm->EOL("Region start");
4206 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
4209 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
4211 Asm->EOL("Region length");
4216 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
4218 Asm->EOL("Landing pad");
4220 Asm->EmitULEB128Bytes(S.Action);
4224 // Emit the actions.
4225 for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
4226 ActionEntry &Action = Actions[I];
4228 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
4229 Asm->EOL("TypeInfo index");
4230 Asm->EmitSLEB128Bytes(Action.NextAction);
4231 Asm->EOL("Next action");
4234 // Emit the type ids.
4235 for (unsigned M = TypeInfos.size(); M; --M) {
4236 GlobalVariable *GV = TypeInfos[M - 1];
4238 PrintRelDirective();
4242 O << Asm->getGlobalLinkName(GV, GLN);
4247 Asm->EOL("TypeInfo");
4250 // Emit the filter typeids.
4251 for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
4252 unsigned TypeID = FilterIds[j];
4253 Asm->EmitULEB128Bytes(TypeID);
4254 Asm->EOL("Filter TypeInfo index");
4257 Asm->EmitAlignment(2, 0, 0, false);
4261 //===--------------------------------------------------------------------===//
4262 // Main entry points.
4264 DwarfException(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
4265 : Dwarf(OS, A, T, "eh"), shouldEmitTable(false), shouldEmitMoves(false),
4266 shouldEmitTableModule(false), shouldEmitMovesModule(false),
4268 if (TimePassesIsEnabled)
4269 ExceptionTimer = new Timer("Dwarf Exception Writer",
4270 getDwarfTimerGroup());
4273 virtual ~DwarfException() {
4274 delete ExceptionTimer;
4277 /// SetModuleInfo - Set machine module information when it's known that pass
4278 /// manager has created it. Set by the target AsmPrinter.
4279 void SetModuleInfo(MachineModuleInfo *mmi) {
4283 /// BeginModule - Emit all exception information that should come prior to the
4285 void BeginModule(Module *M) {
4289 /// EndModule - Emit all exception information that should come after the
4292 if (TimePassesIsEnabled)
4293 ExceptionTimer->startTimer();
4295 if (shouldEmitMovesModule || shouldEmitTableModule) {
4296 const std::vector<Function *> Personalities = MMI->getPersonalities();
4297 for (unsigned i = 0; i < Personalities.size(); ++i)
4298 EmitCommonEHFrame(Personalities[i], i);
4300 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
4301 E = EHFrames.end(); I != E; ++I)
4305 if (TimePassesIsEnabled)
4306 ExceptionTimer->stopTimer();
4309 /// BeginFunction - Gather pre-function exception information. Assumes being
4310 /// emitted immediately after the function entry point.
4311 void BeginFunction(MachineFunction *MF) {
4312 if (TimePassesIsEnabled)
4313 ExceptionTimer->startTimer();
4316 shouldEmitTable = shouldEmitMoves = false;
4318 if (MMI && TAI->doesSupportExceptionHandling()) {
4319 // Map all labels and get rid of any dead landing pads.
4320 MMI->TidyLandingPads();
4322 // If any landing pads survive, we need an EH table.
4323 if (MMI->getLandingPads().size())
4324 shouldEmitTable = true;
4326 // See if we need frame move info.
4327 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
4328 shouldEmitMoves = true;
4330 if (shouldEmitMoves || shouldEmitTable)
4331 // Assumes in correct section after the entry point.
4332 EmitLabel("eh_func_begin", ++SubprogramCount);
4335 shouldEmitTableModule |= shouldEmitTable;
4336 shouldEmitMovesModule |= shouldEmitMoves;
4338 if (TimePassesIsEnabled)
4339 ExceptionTimer->stopTimer();
4342 /// EndFunction - Gather and emit post-function exception information.
4344 void EndFunction() {
4345 if (TimePassesIsEnabled)
4346 ExceptionTimer->startTimer();
4348 if (shouldEmitMoves || shouldEmitTable) {
4349 EmitLabel("eh_func_end", SubprogramCount);
4350 EmitExceptionTable();
4352 // Save EH frame information
4355 FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF, Name),
4357 MMI->getPersonalityIndex(),
4358 MF->getFrameInfo()->hasCalls(),
4359 !MMI->getLandingPads().empty(),
4360 MMI->getFrameMoves(),
4361 MF->getFunction()));
4364 if (TimePassesIsEnabled)
4365 ExceptionTimer->stopTimer();
4369 } // End of namespace llvm
4371 //===----------------------------------------------------------------------===//
4373 /// Emit - Print the abbreviation using the specified Dwarf writer.
4375 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
4376 // Emit its Dwarf tag type.
4377 DD.getAsm()->EmitULEB128Bytes(Tag);
4378 DD.getAsm()->EOL(TagString(Tag));
4380 // Emit whether it has children DIEs.
4381 DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
4382 DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
4384 // For each attribute description.
4385 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4386 const DIEAbbrevData &AttrData = Data[i];
4388 // Emit attribute type.
4389 DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
4390 DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
4393 DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
4394 DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
4397 // Mark end of abbreviation.
4398 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
4399 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
4403 void DIEAbbrev::print(std::ostream &O) {
4404 O << "Abbreviation @"
4405 << std::hex << (intptr_t)this << std::dec
4409 << ChildrenString(ChildrenFlag)
4412 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4414 << AttributeString(Data[i].getAttribute())
4416 << FormEncodingString(Data[i].getForm())
4420 void DIEAbbrev::dump() { print(cerr); }
4423 //===----------------------------------------------------------------------===//
4426 void DIEValue::dump() {
4431 //===----------------------------------------------------------------------===//
4433 /// EmitValue - Emit integer of appropriate size.
4435 void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
4437 case DW_FORM_flag: // Fall thru
4438 case DW_FORM_ref1: // Fall thru
4439 case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer); break;
4440 case DW_FORM_ref2: // Fall thru
4441 case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer); break;
4442 case DW_FORM_ref4: // Fall thru
4443 case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer); break;
4444 case DW_FORM_ref8: // Fall thru
4445 case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer); break;
4446 case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
4447 case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
4448 default: assert(0 && "DIE Value form not supported yet"); break;
4452 /// SizeOf - Determine size of integer value in bytes.
4454 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4456 case DW_FORM_flag: // Fall thru
4457 case DW_FORM_ref1: // Fall thru
4458 case DW_FORM_data1: return sizeof(int8_t);
4459 case DW_FORM_ref2: // Fall thru
4460 case DW_FORM_data2: return sizeof(int16_t);
4461 case DW_FORM_ref4: // Fall thru
4462 case DW_FORM_data4: return sizeof(int32_t);
4463 case DW_FORM_ref8: // Fall thru
4464 case DW_FORM_data8: return sizeof(int64_t);
4465 case DW_FORM_udata: return TargetAsmInfo::getULEB128Size(Integer);
4466 case DW_FORM_sdata: return TargetAsmInfo::getSLEB128Size(Integer);
4467 default: assert(0 && "DIE Value form not supported yet"); break;
4472 //===----------------------------------------------------------------------===//
4474 /// EmitValue - Emit string value.
4476 void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
4477 DD.getAsm()->EmitString(Str);
4480 //===----------------------------------------------------------------------===//
4482 /// EmitValue - Emit label value.
4484 void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4485 bool IsSmall = Form == DW_FORM_data4;
4486 DD.EmitReference(Label, false, IsSmall);
4489 /// SizeOf - Determine size of label value in bytes.
4491 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4492 if (Form == DW_FORM_data4) return 4;
4493 return DD.getTargetData()->getPointerSize();
4496 //===----------------------------------------------------------------------===//
4498 /// EmitValue - Emit label value.
4500 void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4501 bool IsSmall = Form == DW_FORM_data4;
4502 DD.EmitReference(Label, false, IsSmall);
4505 /// SizeOf - Determine size of label value in bytes.
4507 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4508 if (Form == DW_FORM_data4) return 4;
4509 return DD.getTargetData()->getPointerSize();
4512 //===----------------------------------------------------------------------===//
4514 /// EmitValue - Emit delta value.
4516 void DIESectionOffset::EmitValue(DwarfDebug &DD, unsigned Form) {
4517 bool IsSmall = Form == DW_FORM_data4;
4518 DD.EmitSectionOffset(Label.Tag, Section.Tag,
4519 Label.Number, Section.Number, IsSmall, IsEH, UseSet);
4522 /// SizeOf - Determine size of delta value in bytes.
4524 unsigned DIESectionOffset::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4525 if (Form == DW_FORM_data4) return 4;
4526 return DD.getTargetData()->getPointerSize();
4529 //===----------------------------------------------------------------------===//
4531 /// EmitValue - Emit delta value.
4533 void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
4534 bool IsSmall = Form == DW_FORM_data4;
4535 DD.EmitDifference(LabelHi, LabelLo, IsSmall);
4538 /// SizeOf - Determine size of delta value in bytes.
4540 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4541 if (Form == DW_FORM_data4) return 4;
4542 return DD.getTargetData()->getPointerSize();
4545 //===----------------------------------------------------------------------===//
4547 /// EmitValue - Emit debug information entry offset.
4549 void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
4550 DD.getAsm()->EmitInt32(Entry->getOffset());
4553 //===----------------------------------------------------------------------===//
4555 /// ComputeSize - calculate the size of the block.
4557 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
4559 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4561 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4562 Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
4568 /// EmitValue - Emit block data.
4570 void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
4572 case DW_FORM_block1: DD.getAsm()->EmitInt8(Size); break;
4573 case DW_FORM_block2: DD.getAsm()->EmitInt16(Size); break;
4574 case DW_FORM_block4: DD.getAsm()->EmitInt32(Size); break;
4575 case DW_FORM_block: DD.getAsm()->EmitULEB128Bytes(Size); break;
4576 default: assert(0 && "Improper form for block"); break;
4579 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4581 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4583 Values[i]->EmitValue(DD, AbbrevData[i].getForm());
4587 /// SizeOf - Determine size of block data in bytes.
4589 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4591 case DW_FORM_block1: return Size + sizeof(int8_t);
4592 case DW_FORM_block2: return Size + sizeof(int16_t);
4593 case DW_FORM_block4: return Size + sizeof(int32_t);
4594 case DW_FORM_block: return Size + TargetAsmInfo::getULEB128Size(Size);
4595 default: assert(0 && "Improper form for block"); break;
4600 //===----------------------------------------------------------------------===//
4601 /// DIE Implementation
4604 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4608 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
4610 void DIE::AddSiblingOffset() {
4611 DIEInteger *DI = new DIEInteger(0);
4612 Values.insert(Values.begin(), DI);
4613 Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
4616 /// Profile - Used to gather unique data for the value folding set.
4618 void DIE::Profile(FoldingSetNodeID &ID) {
4621 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4622 ID.AddPointer(Children[i]);
4624 for (unsigned j = 0, M = Values.size(); j < M; ++j)
4625 ID.AddPointer(Values[j]);
4629 void DIE::print(std::ostream &O, unsigned IncIndent) {
4630 static unsigned IndentCount = 0;
4631 IndentCount += IncIndent;
4632 const std::string Indent(IndentCount, ' ');
4633 bool isBlock = Abbrev.getTag() == 0;
4638 << "0x" << std::hex << (intptr_t)this << std::dec
4639 << ", Offset: " << Offset
4640 << ", Size: " << Size
4644 << TagString(Abbrev.getTag())
4646 << ChildrenString(Abbrev.getChildrenFlag());
4648 O << "Size: " << Size;
4652 const SmallVector<DIEAbbrevData, 8> &Data = Abbrev.getData();
4655 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4659 O << AttributeString(Data[i].getAttribute());
4661 O << "Blk[" << i << "]";
4664 << FormEncodingString(Data[i].getForm())
4666 Values[i]->print(O);
4671 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
4672 Children[j]->print(O, 4);
4675 if (!isBlock) O << "\n";
4676 IndentCount -= IncIndent;
4684 //===----------------------------------------------------------------------===//
4685 /// DwarfWriter Implementation
4688 DwarfWriter::DwarfWriter()
4689 : ImmutablePass(&ID), DD(0), DE(0) {}
4691 DwarfWriter::~DwarfWriter() {
4696 /// BeginModule - Emit all Dwarf sections that should come prior to the
4698 void DwarfWriter::BeginModule(Module *M,
4699 MachineModuleInfo *MMI,
4700 raw_ostream &OS, AsmPrinter *A,
4701 const TargetAsmInfo *T) {
4702 DE = new DwarfException(OS, A, T);
4703 DD = new DwarfDebug(OS, A, T);
4706 DD->SetDebugInfo(MMI);
4707 DE->SetModuleInfo(MMI);
4710 /// EndModule - Emit all Dwarf sections that should come after the content.
4712 void DwarfWriter::EndModule() {
4717 /// BeginFunction - Gather pre-function debug information. Assumes being
4718 /// emitted immediately after the function entry point.
4719 void DwarfWriter::BeginFunction(MachineFunction *MF) {
4720 DE->BeginFunction(MF);
4721 DD->BeginFunction(MF);
4724 /// EndFunction - Gather and emit post-function debug information.
4726 void DwarfWriter::EndFunction(MachineFunction *MF) {
4727 DD->EndFunction(MF);
4730 if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI())
4731 // Clear function debug information.
4735 /// ValidDebugInfo - Return true if V represents valid debug info value.
4736 bool DwarfWriter::ValidDebugInfo(Value *V, CodeGenOpt::Level OptLevel) {
4737 return DD && DD->ValidDebugInfo(V, OptLevel);
4740 /// RecordSourceLine - Records location information and associates it with a
4741 /// label. Returns a unique label ID used to generate a label and provide
4742 /// correspondence to the source line list.
4743 unsigned DwarfWriter::RecordSourceLine(unsigned Line, unsigned Col,
4745 return DD->RecordSourceLine(Line, Col, CU);
4748 /// RecordRegionStart - Indicate the start of a region.
4749 unsigned DwarfWriter::RecordRegionStart(GlobalVariable *V) {
4750 return DD->RecordRegionStart(V);
4753 /// RecordRegionEnd - Indicate the end of a region.
4754 unsigned DwarfWriter::RecordRegionEnd(GlobalVariable *V) {
4755 return DD->RecordRegionEnd(V);
4758 /// getRecordSourceLineCount - Count source lines.
4759 unsigned DwarfWriter::getRecordSourceLineCount() {
4760 return DD->getRecordSourceLineCount();
4763 /// RecordVariable - Indicate the declaration of a local variable.
4765 void DwarfWriter::RecordVariable(GlobalVariable *GV, unsigned FrameIndex,
4766 const MachineInstr *MI) {
4767 DD->RecordVariable(GV, FrameIndex, MI);
4770 /// ShouldEmitDwarfDebug - Returns true if Dwarf debugging declarations should
4772 bool DwarfWriter::ShouldEmitDwarfDebug() const {
4773 return DD->ShouldEmitDwarfDebug();
4776 //// RecordInlinedFnStart - Global variable GV is inlined at the location marked
4777 //// by LabelID label.
4778 void DwarfWriter::RecordInlinedFnStart(Instruction *I, DISubprogram &SP,
4779 unsigned LabelID, DICompileUnit CU,
4780 unsigned Line, unsigned Col) {
4781 DD->RecordInlinedFnStart(I, SP, LabelID, CU, Line, Col);
4784 /// RecordInlinedFnEnd - Indicate the end of inlined subroutine.
4785 unsigned DwarfWriter::RecordInlinedFnEnd(DISubprogram &SP) {
4786 return DD->RecordInlinedFnEnd(SP);
4789 /// RecordVariableScope - Record scope for the variable declared by
4790 /// DeclareMI. DeclareMI must describe TargetInstrInfo::DECLARE.
4791 void DwarfWriter::RecordVariableScope(DIVariable &DV,
4792 const MachineInstr *DeclareMI) {
4793 DD->RecordVariableScope(DV, DeclareMI);