1 //===-- llvm/CodeGen/DwarfWriter.cpp - Dwarf Framework ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf info into asm files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/DwarfWriter.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/FoldingSet.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/UniqueVector.h"
20 #include "llvm/Module.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Constants.h"
23 #include "llvm/CodeGen/AsmPrinter.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineLocation.h"
27 #include "llvm/Analysis/DebugInfo.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/Dwarf.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/DataTypes.h"
32 #include "llvm/Support/Mangler.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/System/Path.h"
35 #include "llvm/Target/TargetAsmInfo.h"
36 #include "llvm/Target/TargetRegisterInfo.h"
37 #include "llvm/Target/TargetData.h"
38 #include "llvm/Target/TargetFrameInfo.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include "llvm/Target/TargetOptions.h"
45 using namespace llvm::dwarf;
47 static RegisterPass<DwarfWriter>
48 X("dwarfwriter", "DWARF Information Writer");
49 char DwarfWriter::ID = 0;
53 //===----------------------------------------------------------------------===//
55 /// Configuration values for initial hash set sizes (log2).
57 static const unsigned InitDiesSetSize = 9; // 512
58 static const unsigned InitAbbreviationsSetSize = 9; // 512
59 static const unsigned InitValuesSetSize = 9; // 512
61 //===----------------------------------------------------------------------===//
62 /// Forward declarations.
67 //===----------------------------------------------------------------------===//
70 /// getGlobalVariablesUsing - Return all of the GlobalVariables which have the
71 /// specified value in their initializer somewhere.
73 getGlobalVariablesUsing(Value *V, std::vector<GlobalVariable*> &Result) {
74 // Scan though value users.
75 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
76 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I)) {
77 // If the user is a GlobalVariable then add to result.
79 } else if (Constant *C = dyn_cast<Constant>(*I)) {
80 // If the user is a constant variable then scan its users
81 getGlobalVariablesUsing(C, Result);
86 /// getGlobalVariablesUsing - Return all of the GlobalVariables that use the
87 /// named GlobalVariable.
89 getGlobalVariablesUsing(Module &M, const std::string &RootName,
90 std::vector<GlobalVariable*> &Result) {
91 std::vector<const Type*> FieldTypes;
92 FieldTypes.push_back(Type::Int32Ty);
93 FieldTypes.push_back(Type::Int32Ty);
95 // Get the GlobalVariable root.
96 GlobalVariable *UseRoot = M.getGlobalVariable(RootName,
97 StructType::get(FieldTypes));
99 // If present and linkonce then scan for users.
100 if (UseRoot && UseRoot->hasLinkOnceLinkage())
101 getGlobalVariablesUsing(UseRoot, Result);
104 /// getGlobalVariable - Return either a direct or cast Global value.
106 static GlobalVariable *getGlobalVariable(Value *V) {
107 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
109 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
110 if (CE->getOpcode() == Instruction::BitCast) {
111 return dyn_cast<GlobalVariable>(CE->getOperand(0));
112 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
113 for (unsigned int i=1; i<CE->getNumOperands(); i++) {
114 if (!CE->getOperand(i)->isNullValue())
117 return dyn_cast<GlobalVariable>(CE->getOperand(0));
123 //===----------------------------------------------------------------------===//
124 /// DWLabel - Labels are used to track locations in the assembler file.
125 /// Labels appear in the form @verbatim <prefix><Tag><Number> @endverbatim,
126 /// where the tag is a category of label (Ex. location) and number is a value
127 /// unique in that category.
130 /// Tag - Label category tag. Should always be a staticly declared C string.
134 /// Number - Value to make label unique.
138 DWLabel(const char *T, unsigned N) : Tag(T), Number(N) {}
140 void Profile(FoldingSetNodeID &ID) const {
141 ID.AddString(std::string(Tag));
142 ID.AddInteger(Number);
146 void print(std::ostream *O) const {
149 void print(std::ostream &O) const {
151 if (Number) O << Number;
156 //===----------------------------------------------------------------------===//
157 /// DIEAbbrevData - Dwarf abbreviation data, describes the one attribute of a
158 /// Dwarf abbreviation.
159 class DIEAbbrevData {
161 /// Attribute - Dwarf attribute code.
165 /// Form - Dwarf form code.
170 DIEAbbrevData(unsigned A, unsigned F)
176 unsigned getAttribute() const { return Attribute; }
177 unsigned getForm() const { return Form; }
179 /// Profile - Used to gather unique data for the abbreviation folding set.
181 void Profile(FoldingSetNodeID &ID)const {
182 ID.AddInteger(Attribute);
187 //===----------------------------------------------------------------------===//
188 /// DIEAbbrev - Dwarf abbreviation, describes the organization of a debug
189 /// information object.
190 class DIEAbbrev : public FoldingSetNode {
192 /// Tag - Dwarf tag code.
196 /// Unique number for node.
200 /// ChildrenFlag - Dwarf children flag.
202 unsigned ChildrenFlag;
204 /// Data - Raw data bytes for abbreviation.
206 SmallVector<DIEAbbrevData, 8> Data;
210 DIEAbbrev(unsigned T, unsigned C)
218 unsigned getTag() const { return Tag; }
219 unsigned getNumber() const { return Number; }
220 unsigned getChildrenFlag() const { return ChildrenFlag; }
221 const SmallVector<DIEAbbrevData, 8> &getData() const { return Data; }
222 void setTag(unsigned T) { Tag = T; }
223 void setChildrenFlag(unsigned CF) { ChildrenFlag = CF; }
224 void setNumber(unsigned N) { Number = N; }
226 /// AddAttribute - Adds another set of attribute information to the
228 void AddAttribute(unsigned Attribute, unsigned Form) {
229 Data.push_back(DIEAbbrevData(Attribute, Form));
232 /// AddFirstAttribute - Adds a set of attribute information to the front
233 /// of the abbreviation.
234 void AddFirstAttribute(unsigned Attribute, unsigned Form) {
235 Data.insert(Data.begin(), DIEAbbrevData(Attribute, Form));
238 /// Profile - Used to gather unique data for the abbreviation folding set.
240 void Profile(FoldingSetNodeID &ID) {
242 ID.AddInteger(ChildrenFlag);
244 // For each attribute description.
245 for (unsigned i = 0, N = Data.size(); i < N; ++i)
249 /// Emit - Print the abbreviation using the specified Dwarf writer.
251 void Emit(const DwarfDebug &DD) const;
254 void print(std::ostream *O) {
257 void print(std::ostream &O);
262 //===----------------------------------------------------------------------===//
263 /// DIE - A structured debug information entry. Has an abbreviation which
264 /// describes it's organization.
265 class DIE : public FoldingSetNode {
267 /// Abbrev - Buffer for constructing abbreviation.
271 /// Offset - Offset in debug info section.
275 /// Size - Size of instance + children.
281 std::vector<DIE *> Children;
283 /// Attributes values.
285 SmallVector<DIEValue*, 32> Values;
288 explicit DIE(unsigned Tag)
289 : Abbrev(Tag, DW_CHILDREN_no)
298 DIEAbbrev &getAbbrev() { return Abbrev; }
299 unsigned getAbbrevNumber() const {
300 return Abbrev.getNumber();
302 unsigned getTag() const { return Abbrev.getTag(); }
303 unsigned getOffset() const { return Offset; }
304 unsigned getSize() const { return Size; }
305 const std::vector<DIE *> &getChildren() const { return Children; }
306 SmallVector<DIEValue*, 32> &getValues() { return Values; }
307 void setTag(unsigned Tag) { Abbrev.setTag(Tag); }
308 void setOffset(unsigned O) { Offset = O; }
309 void setSize(unsigned S) { Size = S; }
311 /// AddValue - Add a value and attributes to a DIE.
313 void AddValue(unsigned Attribute, unsigned Form, DIEValue *Value) {
314 Abbrev.AddAttribute(Attribute, Form);
315 Values.push_back(Value);
318 /// SiblingOffset - Return the offset of the debug information entry's
320 unsigned SiblingOffset() const { return Offset + Size; }
322 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
324 void AddSiblingOffset();
326 /// AddChild - Add a child to the DIE.
328 void AddChild(DIE *Child) {
329 Abbrev.setChildrenFlag(DW_CHILDREN_yes);
330 Children.push_back(Child);
333 /// Detach - Detaches objects connected to it after copying.
339 /// Profile - Used to gather unique data for the value folding set.
341 void Profile(FoldingSetNodeID &ID) ;
344 void print(std::ostream *O, unsigned IncIndent = 0) {
345 if (O) print(*O, IncIndent);
347 void print(std::ostream &O, unsigned IncIndent = 0);
352 //===----------------------------------------------------------------------===//
353 /// DIEValue - A debug information entry value.
355 class DIEValue : public FoldingSetNode {
368 /// Type - Type of data stored in the value.
372 explicit DIEValue(unsigned T)
375 virtual ~DIEValue() {}
378 unsigned getType() const { return Type; }
380 // Implement isa/cast/dyncast.
381 static bool classof(const DIEValue *) { return true; }
383 /// EmitValue - Emit value via the Dwarf writer.
385 virtual void EmitValue(DwarfDebug &DD, unsigned Form) = 0;
387 /// SizeOf - Return the size of a value in bytes.
389 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const = 0;
391 /// Profile - Used to gather unique data for the value folding set.
393 virtual void Profile(FoldingSetNodeID &ID) = 0;
396 void print(std::ostream *O) {
399 virtual void print(std::ostream &O) = 0;
404 //===----------------------------------------------------------------------===//
405 /// DWInteger - An integer value DIE.
407 class DIEInteger : public DIEValue {
412 explicit DIEInteger(uint64_t I) : DIEValue(isInteger), Integer(I) {}
414 // Implement isa/cast/dyncast.
415 static bool classof(const DIEInteger *) { return true; }
416 static bool classof(const DIEValue *I) { return I->Type == isInteger; }
418 /// BestForm - Choose the best form for integer.
420 static unsigned BestForm(bool IsSigned, uint64_t Integer) {
422 if ((char)Integer == (signed)Integer) return DW_FORM_data1;
423 if ((short)Integer == (signed)Integer) return DW_FORM_data2;
424 if ((int)Integer == (signed)Integer) return DW_FORM_data4;
426 if ((unsigned char)Integer == Integer) return DW_FORM_data1;
427 if ((unsigned short)Integer == Integer) return DW_FORM_data2;
428 if ((unsigned int)Integer == Integer) return DW_FORM_data4;
430 return DW_FORM_data8;
433 /// EmitValue - Emit integer of appropriate size.
435 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
437 /// SizeOf - Determine size of integer value in bytes.
439 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
441 /// Profile - Used to gather unique data for the value folding set.
443 static void Profile(FoldingSetNodeID &ID, unsigned Integer) {
444 ID.AddInteger(isInteger);
445 ID.AddInteger(Integer);
447 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Integer); }
450 virtual void print(std::ostream &O) {
451 O << "Int: " << (int64_t)Integer
452 << " 0x" << std::hex << Integer << std::dec;
457 //===----------------------------------------------------------------------===//
458 /// DIEString - A string value DIE.
460 class DIEString : public DIEValue {
462 const std::string String;
464 explicit DIEString(const std::string &S) : DIEValue(isString), String(S) {}
466 // Implement isa/cast/dyncast.
467 static bool classof(const DIEString *) { return true; }
468 static bool classof(const DIEValue *S) { return S->Type == isString; }
470 /// EmitValue - Emit string value.
472 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
474 /// SizeOf - Determine size of string value in bytes.
476 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
477 return String.size() + sizeof(char); // sizeof('\0');
480 /// Profile - Used to gather unique data for the value folding set.
482 static void Profile(FoldingSetNodeID &ID, const std::string &String) {
483 ID.AddInteger(isString);
484 ID.AddString(String);
486 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, String); }
489 virtual void print(std::ostream &O) {
490 O << "Str: \"" << String << "\"";
495 //===----------------------------------------------------------------------===//
496 /// DIEDwarfLabel - A Dwarf internal label expression DIE.
498 class DIEDwarfLabel : public DIEValue {
503 explicit DIEDwarfLabel(const DWLabel &L) : DIEValue(isLabel), Label(L) {}
505 // Implement isa/cast/dyncast.
506 static bool classof(const DIEDwarfLabel *) { return true; }
507 static bool classof(const DIEValue *L) { return L->Type == isLabel; }
509 /// EmitValue - Emit label value.
511 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
513 /// SizeOf - Determine size of label value in bytes.
515 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
517 /// Profile - Used to gather unique data for the value folding set.
519 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label) {
520 ID.AddInteger(isLabel);
523 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
526 virtual void print(std::ostream &O) {
534 //===----------------------------------------------------------------------===//
535 /// DIEObjectLabel - A label to an object in code or data.
537 class DIEObjectLabel : public DIEValue {
539 const std::string Label;
541 explicit DIEObjectLabel(const std::string &L)
542 : DIEValue(isAsIsLabel), Label(L) {}
544 // Implement isa/cast/dyncast.
545 static bool classof(const DIEObjectLabel *) { return true; }
546 static bool classof(const DIEValue *L) { return L->Type == isAsIsLabel; }
548 /// EmitValue - Emit label value.
550 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
552 /// SizeOf - Determine size of label value in bytes.
554 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
556 /// Profile - Used to gather unique data for the value folding set.
558 static void Profile(FoldingSetNodeID &ID, const std::string &Label) {
559 ID.AddInteger(isAsIsLabel);
562 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
565 virtual void print(std::ostream &O) {
566 O << "Obj: " << Label;
571 //===----------------------------------------------------------------------===//
572 /// DIESectionOffset - A section offset DIE.
574 class DIESectionOffset : public DIEValue {
577 const DWLabel Section;
581 DIESectionOffset(const DWLabel &Lab, const DWLabel &Sec,
582 bool isEH = false, bool useSet = true)
583 : DIEValue(isSectionOffset), Label(Lab), Section(Sec),
584 IsEH(isEH), UseSet(useSet) {}
586 // Implement isa/cast/dyncast.
587 static bool classof(const DIESectionOffset *) { return true; }
588 static bool classof(const DIEValue *D) { return D->Type == isSectionOffset; }
590 /// EmitValue - Emit section offset.
592 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
594 /// SizeOf - Determine size of section offset value in bytes.
596 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
598 /// Profile - Used to gather unique data for the value folding set.
600 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label,
601 const DWLabel &Section) {
602 ID.AddInteger(isSectionOffset);
605 // IsEH and UseSet are specific to the Label/Section that we will emit
606 // the offset for; so Label/Section are enough for uniqueness.
608 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label, Section); }
611 virtual void print(std::ostream &O) {
616 O << "-" << IsEH << "-" << UseSet;
621 //===----------------------------------------------------------------------===//
622 /// DIEDelta - A simple label difference DIE.
624 class DIEDelta : public DIEValue {
626 const DWLabel LabelHi;
627 const DWLabel LabelLo;
629 DIEDelta(const DWLabel &Hi, const DWLabel &Lo)
630 : DIEValue(isDelta), LabelHi(Hi), LabelLo(Lo) {}
632 // Implement isa/cast/dyncast.
633 static bool classof(const DIEDelta *) { return true; }
634 static bool classof(const DIEValue *D) { return D->Type == isDelta; }
636 /// EmitValue - Emit delta value.
638 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
640 /// SizeOf - Determine size of delta value in bytes.
642 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
644 /// Profile - Used to gather unique data for the value folding set.
646 static void Profile(FoldingSetNodeID &ID, const DWLabel &LabelHi,
647 const DWLabel &LabelLo) {
648 ID.AddInteger(isDelta);
652 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, LabelHi, LabelLo); }
655 virtual void print(std::ostream &O) {
664 //===----------------------------------------------------------------------===//
665 /// DIEntry - A pointer to another debug information entry. An instance of this
666 /// class can also be used as a proxy for a debug information entry not yet
667 /// defined (ie. types.)
668 class DIEntry : public DIEValue {
672 explicit DIEntry(DIE *E) : DIEValue(isEntry), Entry(E) {}
674 // Implement isa/cast/dyncast.
675 static bool classof(const DIEntry *) { return true; }
676 static bool classof(const DIEValue *E) { return E->Type == isEntry; }
678 /// EmitValue - Emit debug information entry offset.
680 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
682 /// SizeOf - Determine size of debug information entry in bytes.
684 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
685 return sizeof(int32_t);
688 /// Profile - Used to gather unique data for the value folding set.
690 static void Profile(FoldingSetNodeID &ID, DIE *Entry) {
691 ID.AddInteger(isEntry);
692 ID.AddPointer(Entry);
694 virtual void Profile(FoldingSetNodeID &ID) {
695 ID.AddInteger(isEntry);
698 ID.AddPointer(Entry);
705 virtual void print(std::ostream &O) {
706 O << "Die: 0x" << std::hex << (intptr_t)Entry << std::dec;
711 //===----------------------------------------------------------------------===//
712 /// DIEBlock - A block of values. Primarily used for location expressions.
714 class DIEBlock : public DIEValue, public DIE {
716 unsigned Size; // Size in bytes excluding size header.
726 // Implement isa/cast/dyncast.
727 static bool classof(const DIEBlock *) { return true; }
728 static bool classof(const DIEValue *E) { return E->Type == isBlock; }
730 /// ComputeSize - calculate the size of the block.
732 unsigned ComputeSize(DwarfDebug &DD);
734 /// BestForm - Choose the best form for data.
736 unsigned BestForm() const {
737 if ((unsigned char)Size == Size) return DW_FORM_block1;
738 if ((unsigned short)Size == Size) return DW_FORM_block2;
739 if ((unsigned int)Size == Size) return DW_FORM_block4;
740 return DW_FORM_block;
743 /// EmitValue - Emit block data.
745 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
747 /// SizeOf - Determine size of block data in bytes.
749 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
752 /// Profile - Used to gather unique data for the value folding set.
754 virtual void Profile(FoldingSetNodeID &ID) {
755 ID.AddInteger(isBlock);
760 virtual void print(std::ostream &O) {
767 //===----------------------------------------------------------------------===//
768 /// CompileUnit - This dwarf writer support class manages information associate
769 /// with a source file.
772 /// ID - File identifier for source.
776 /// Die - Compile unit debug information entry.
780 /// GVToDieMap - Tracks the mapping of unit level debug informaton
781 /// variables to debug information entries.
782 DenseMap<GlobalVariable *, DIE *> GVToDieMap;
784 /// GVToDIEntryMap - Tracks the mapping of unit level debug informaton
785 /// descriptors to debug information entries using a DIEntry proxy.
786 DenseMap<GlobalVariable *, DIEntry *> GVToDIEntryMap;
788 /// Globals - A map of globally visible named entities for this unit.
790 std::map<std::string, DIE *> Globals;
792 /// DiesSet - Used to uniquely define dies within the compile unit.
794 FoldingSet<DIE> DiesSet;
796 /// Dies - List of all dies in the compile unit.
798 std::vector<DIE *> Dies;
801 CompileUnit(unsigned I, DIE *D)
802 : ID(I), Die(D), GVToDieMap(),
803 GVToDIEntryMap(), Globals(), DiesSet(InitDiesSetSize), Dies()
809 for (unsigned i = 0, N = Dies.size(); i < N; ++i)
814 unsigned getID() const { return ID; }
815 DIE* getDie() const { return Die; }
816 std::map<std::string, DIE *> &getGlobals() { return Globals; }
818 /// hasContent - Return true if this compile unit has something to write out.
820 bool hasContent() const {
821 return !Die->getChildren().empty();
824 /// AddGlobal - Add a new global entity to the compile unit.
826 void AddGlobal(const std::string &Name, DIE *Die) {
830 /// getDieMapSlotFor - Returns the debug information entry map slot for the
831 /// specified debug variable.
832 DIE *&getDieMapSlotFor(GlobalVariable *GV) {
833 return GVToDieMap[GV];
836 /// getDIEntrySlotFor - Returns the debug information entry proxy slot for the
837 /// specified debug variable.
838 DIEntry *&getDIEntrySlotFor(GlobalVariable *GV) {
839 return GVToDIEntryMap[GV];
842 /// AddDie - Adds or interns the DIE to the compile unit.
844 DIE *AddDie(DIE &Buffer) {
848 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
851 Die = new DIE(Buffer);
852 DiesSet.InsertNode(Die, Where);
853 this->Die->AddChild(Die);
861 //===----------------------------------------------------------------------===//
862 /// Dwarf - Emits general Dwarf directives.
868 //===--------------------------------------------------------------------===//
869 // Core attributes used by the Dwarf writer.
873 /// O - Stream to .s file.
877 /// Asm - Target of Dwarf emission.
881 /// TAI - Target asm information.
882 const TargetAsmInfo *TAI;
884 /// TD - Target data.
885 const TargetData *TD;
887 /// RI - Register Information.
888 const TargetRegisterInfo *RI;
890 /// M - Current module.
894 /// MF - Current machine function.
898 /// MMI - Collected machine module information.
900 MachineModuleInfo *MMI;
902 /// SubprogramCount - The running count of functions being compiled.
904 unsigned SubprogramCount;
906 /// Flavor - A unique string indicating what dwarf producer this is, used to
908 const char * const Flavor;
911 Dwarf(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T,
916 , TD(Asm->TM.getTargetData())
917 , RI(Asm->TM.getRegisterInfo())
929 //===--------------------------------------------------------------------===//
932 AsmPrinter *getAsm() const { return Asm; }
933 MachineModuleInfo *getMMI() const { return MMI; }
934 const TargetAsmInfo *getTargetAsmInfo() const { return TAI; }
935 const TargetData *getTargetData() const { return TD; }
937 void PrintRelDirective(bool Force32Bit = false, bool isInSection = false)
939 if (isInSection && TAI->getDwarfSectionOffsetDirective())
940 O << TAI->getDwarfSectionOffsetDirective();
941 else if (Force32Bit || TD->getPointerSize() == sizeof(int32_t))
942 O << TAI->getData32bitsDirective();
944 O << TAI->getData64bitsDirective();
947 /// PrintLabelName - Print label name in form used by Dwarf writer.
949 void PrintLabelName(DWLabel Label) const {
950 PrintLabelName(Label.Tag, Label.Number);
952 void PrintLabelName(const char *Tag, unsigned Number) const {
953 O << TAI->getPrivateGlobalPrefix() << Tag;
954 if (Number) O << Number;
957 void PrintLabelName(const char *Tag, unsigned Number,
958 const char *Suffix) const {
959 O << TAI->getPrivateGlobalPrefix() << Tag;
960 if (Number) O << Number;
964 /// EmitLabel - Emit location label for internal use by Dwarf.
966 void EmitLabel(DWLabel Label) const {
967 EmitLabel(Label.Tag, Label.Number);
969 void EmitLabel(const char *Tag, unsigned Number) const {
970 PrintLabelName(Tag, Number);
974 /// EmitReference - Emit a reference to a label.
976 void EmitReference(DWLabel Label, bool IsPCRelative = false,
977 bool Force32Bit = false) const {
978 EmitReference(Label.Tag, Label.Number, IsPCRelative, Force32Bit);
980 void EmitReference(const char *Tag, unsigned Number,
981 bool IsPCRelative = false, bool Force32Bit = false) const {
982 PrintRelDirective(Force32Bit);
983 PrintLabelName(Tag, Number);
985 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
987 void EmitReference(const std::string &Name, bool IsPCRelative = false,
988 bool Force32Bit = false) const {
989 PrintRelDirective(Force32Bit);
993 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
996 /// EmitDifference - Emit the difference between two labels. Some
997 /// assemblers do not behave with absolute expressions with data directives,
998 /// so there is an option (needsSet) to use an intermediary set expression.
999 void EmitDifference(DWLabel LabelHi, DWLabel LabelLo,
1000 bool IsSmall = false) {
1001 EmitDifference(LabelHi.Tag, LabelHi.Number,
1002 LabelLo.Tag, LabelLo.Number,
1005 void EmitDifference(const char *TagHi, unsigned NumberHi,
1006 const char *TagLo, unsigned NumberLo,
1007 bool IsSmall = false) {
1008 if (TAI->needsSet()) {
1010 PrintLabelName("set", SetCounter, Flavor);
1012 PrintLabelName(TagHi, NumberHi);
1014 PrintLabelName(TagLo, NumberLo);
1017 PrintRelDirective(IsSmall);
1018 PrintLabelName("set", SetCounter, Flavor);
1021 PrintRelDirective(IsSmall);
1023 PrintLabelName(TagHi, NumberHi);
1025 PrintLabelName(TagLo, NumberLo);
1029 void EmitSectionOffset(const char* Label, const char* Section,
1030 unsigned LabelNumber, unsigned SectionNumber,
1031 bool IsSmall = false, bool isEH = false,
1032 bool useSet = true) {
1033 bool printAbsolute = false;
1035 printAbsolute = TAI->isAbsoluteEHSectionOffsets();
1037 printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
1039 if (TAI->needsSet() && useSet) {
1041 PrintLabelName("set", SetCounter, Flavor);
1043 PrintLabelName(Label, LabelNumber);
1045 if (!printAbsolute) {
1047 PrintLabelName(Section, SectionNumber);
1051 PrintRelDirective(IsSmall);
1053 PrintLabelName("set", SetCounter, Flavor);
1056 PrintRelDirective(IsSmall, true);
1058 PrintLabelName(Label, LabelNumber);
1060 if (!printAbsolute) {
1062 PrintLabelName(Section, SectionNumber);
1067 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
1069 void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
1070 const std::vector<MachineMove> &Moves, bool isEH) {
1072 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
1073 TargetFrameInfo::StackGrowsUp ?
1074 TD->getPointerSize() : -TD->getPointerSize();
1075 bool IsLocal = BaseLabel && strcmp(BaseLabel, "label") == 0;
1077 for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
1078 const MachineMove &Move = Moves[i];
1079 unsigned LabelID = Move.getLabelID();
1082 LabelID = MMI->MappedLabel(LabelID);
1084 // Throw out move if the label is invalid.
1085 if (!LabelID) continue;
1088 const MachineLocation &Dst = Move.getDestination();
1089 const MachineLocation &Src = Move.getSource();
1091 // Advance row if new location.
1092 if (BaseLabel && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
1093 Asm->EmitInt8(DW_CFA_advance_loc4);
1094 Asm->EOL("DW_CFA_advance_loc4");
1095 EmitDifference("label", LabelID, BaseLabel, BaseLabelID, true);
1098 BaseLabelID = LabelID;
1099 BaseLabel = "label";
1103 // If advancing cfa.
1104 if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
1106 if (Src.getReg() == MachineLocation::VirtualFP) {
1107 Asm->EmitInt8(DW_CFA_def_cfa_offset);
1108 Asm->EOL("DW_CFA_def_cfa_offset");
1110 Asm->EmitInt8(DW_CFA_def_cfa);
1111 Asm->EOL("DW_CFA_def_cfa");
1112 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getReg(), isEH));
1113 Asm->EOL("Register");
1116 int Offset = -Src.getOffset();
1118 Asm->EmitULEB128Bytes(Offset);
1121 assert(0 && "Machine move no supported yet.");
1123 } else if (Src.isReg() &&
1124 Src.getReg() == MachineLocation::VirtualFP) {
1126 Asm->EmitInt8(DW_CFA_def_cfa_register);
1127 Asm->EOL("DW_CFA_def_cfa_register");
1128 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getReg(), isEH));
1129 Asm->EOL("Register");
1131 assert(0 && "Machine move no supported yet.");
1134 unsigned Reg = RI->getDwarfRegNum(Src.getReg(), isEH);
1135 int Offset = Dst.getOffset() / stackGrowth;
1138 Asm->EmitInt8(DW_CFA_offset_extended_sf);
1139 Asm->EOL("DW_CFA_offset_extended_sf");
1140 Asm->EmitULEB128Bytes(Reg);
1142 Asm->EmitSLEB128Bytes(Offset);
1144 } else if (Reg < 64) {
1145 Asm->EmitInt8(DW_CFA_offset + Reg);
1147 Asm->EOL("DW_CFA_offset + Reg (" + utostr(Reg) + ")");
1150 Asm->EmitULEB128Bytes(Offset);
1153 Asm->EmitInt8(DW_CFA_offset_extended);
1154 Asm->EOL("DW_CFA_offset_extended");
1155 Asm->EmitULEB128Bytes(Reg);
1157 Asm->EmitULEB128Bytes(Offset);
1166 //===----------------------------------------------------------------------===//
1167 /// SrcLineInfo - This class is used to record source line correspondence.
1170 unsigned Line; // Source line number.
1171 unsigned Column; // Source column.
1172 unsigned SourceID; // Source ID number.
1173 unsigned LabelID; // Label in code ID number.
1175 SrcLineInfo(unsigned L, unsigned C, unsigned S, unsigned I)
1176 : Line(L), Column(C), SourceID(S), LabelID(I) {}
1179 unsigned getLine() const { return Line; }
1180 unsigned getColumn() const { return Column; }
1181 unsigned getSourceID() const { return SourceID; }
1182 unsigned getLabelID() const { return LabelID; }
1186 //===----------------------------------------------------------------------===//
1187 /// SrcFileInfo - This class is used to track source information.
1190 unsigned DirectoryID; // Directory ID number.
1191 std::string Name; // File name (not including directory.)
1193 SrcFileInfo(unsigned D, const std::string &N) : DirectoryID(D), Name(N) {}
1196 unsigned getDirectoryID() const { return DirectoryID; }
1197 const std::string &getName() const { return Name; }
1199 /// operator== - Used by UniqueVector to locate entry.
1201 bool operator==(const SrcFileInfo &SI) const {
1202 return getDirectoryID() == SI.getDirectoryID() && getName() == SI.getName();
1205 /// operator< - Used by UniqueVector to locate entry.
1207 bool operator<(const SrcFileInfo &SI) const {
1208 return getDirectoryID() < SI.getDirectoryID() ||
1209 (getDirectoryID() == SI.getDirectoryID() && getName() < SI.getName());
1213 //===----------------------------------------------------------------------===//
1214 /// DbgVariable - This class is used to track local variable information.
1218 DIVariable Var; // Variable Descriptor.
1219 unsigned FrameIndex; // Variable frame index.
1222 DbgVariable(DIVariable V, unsigned I) : Var(V), FrameIndex(I) {}
1225 DIVariable getVariable() const { return Var; }
1226 unsigned getFrameIndex() const { return FrameIndex; }
1229 //===----------------------------------------------------------------------===//
1230 /// DbgScope - This class is used to track scope information.
1234 DbgScope *Parent; // Parent to this scope.
1235 DIDescriptor Desc; // Debug info descriptor for scope.
1236 // Either subprogram or block.
1237 unsigned StartLabelID; // Label ID of the beginning of scope.
1238 unsigned EndLabelID; // Label ID of the end of scope.
1239 SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope.
1240 SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
1243 DbgScope(DbgScope *P, DIDescriptor D)
1244 : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0), Scopes(), Variables()
1247 for (unsigned i = 0, N = Scopes.size(); i < N; ++i) delete Scopes[i];
1248 for (unsigned j = 0, M = Variables.size(); j < M; ++j) delete Variables[j];
1252 DbgScope *getParent() const { return Parent; }
1253 DIDescriptor getDesc() const { return Desc; }
1254 unsigned getStartLabelID() const { return StartLabelID; }
1255 unsigned getEndLabelID() const { return EndLabelID; }
1256 SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
1257 SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
1258 void setStartLabelID(unsigned S) { StartLabelID = S; }
1259 void setEndLabelID(unsigned E) { EndLabelID = E; }
1261 /// AddScope - Add a scope to the scope.
1263 void AddScope(DbgScope *S) { Scopes.push_back(S); }
1265 /// AddVariable - Add a variable to the scope.
1267 void AddVariable(DbgVariable *V) { Variables.push_back(V); }
1270 //===----------------------------------------------------------------------===//
1271 /// DwarfDebug - Emits Dwarf debug directives.
1273 class DwarfDebug : public Dwarf {
1276 //===--------------------------------------------------------------------===//
1277 // Attributes used to construct specific Dwarf sections.
1280 /// CompileUnits - All the compile units involved in this build. The index
1281 /// of each entry in this vector corresponds to the sources in MMI.
1282 std::vector<CompileUnit *> CompileUnits;
1283 DenseMap<Value *, CompileUnit *> DW_CUs;
1285 /// AbbreviationsSet - Used to uniquely define abbreviations.
1287 FoldingSet<DIEAbbrev> AbbreviationsSet;
1289 /// Abbreviations - A list of all the unique abbreviations in use.
1291 std::vector<DIEAbbrev *> Abbreviations;
1293 /// Directories - Uniquing vector for directories.
1294 UniqueVector<std::string> Directories;
1296 /// SourceFiles - Uniquing vector for source files.
1297 UniqueVector<SrcFileInfo> SrcFiles;
1299 /// Lines - List of of source line correspondence.
1300 std::vector<SrcLineInfo> Lines;
1302 /// ValuesSet - Used to uniquely define values.
1304 FoldingSet<DIEValue> ValuesSet;
1306 /// Values - A list of all the unique values in use.
1308 std::vector<DIEValue *> Values;
1310 /// StringPool - A UniqueVector of strings used by indirect references.
1312 UniqueVector<std::string> StringPool;
1314 /// SectionMap - Provides a unique id per text section.
1316 UniqueVector<const Section*> SectionMap;
1318 /// SectionSourceLines - Tracks line numbers per text section.
1320 std::vector<std::vector<SrcLineInfo> > SectionSourceLines;
1322 /// didInitial - Flag to indicate if initial emission has been done.
1326 /// shouldEmit - Flag to indicate if debug information should be emitted.
1330 // RootDbgScope - Top level scope for the current function.
1332 DbgScope *RootDbgScope;
1334 // DbgScopeMap - Tracks the scopes in the current function.
1335 DenseMap<GlobalVariable *, DbgScope *> DbgScopeMap;
1337 struct FunctionDebugFrameInfo {
1339 std::vector<MachineMove> Moves;
1341 FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
1342 Number(Num), Moves(M) { }
1345 std::vector<FunctionDebugFrameInfo> DebugFrames;
1349 /// ShouldEmitDwarf - Returns true if Dwarf declarations should be made.
1351 bool ShouldEmitDwarf() const { return shouldEmit; }
1353 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1355 void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1356 // Profile the node so that we can make it unique.
1357 FoldingSetNodeID ID;
1360 // Check the set for priors.
1361 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1363 // If it's newly added.
1364 if (InSet == &Abbrev) {
1365 // Add to abbreviation list.
1366 Abbreviations.push_back(&Abbrev);
1367 // Assign the vector position + 1 as its number.
1368 Abbrev.setNumber(Abbreviations.size());
1370 // Assign existing abbreviation number.
1371 Abbrev.setNumber(InSet->getNumber());
1375 /// NewString - Add a string to the constant pool and returns a label.
1377 DWLabel NewString(const std::string &String) {
1378 unsigned StringID = StringPool.insert(String);
1379 return DWLabel("string", StringID);
1382 /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1384 DIEntry *NewDIEntry(DIE *Entry = NULL) {
1388 FoldingSetNodeID ID;
1389 DIEntry::Profile(ID, Entry);
1391 Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1393 if (Value) return Value;
1395 Value = new DIEntry(Entry);
1396 ValuesSet.InsertNode(Value, Where);
1398 Value = new DIEntry(Entry);
1401 Values.push_back(Value);
1405 /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1407 void SetDIEntry(DIEntry *Value, DIE *Entry) {
1408 Value->Entry = Entry;
1409 // Add to values set if not already there. If it is, we merely have a
1410 // duplicate in the values list (no harm.)
1411 ValuesSet.GetOrInsertNode(Value);
1414 /// AddUInt - Add an unsigned integer attribute data and value.
1416 void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1417 if (!Form) Form = DIEInteger::BestForm(false, Integer);
1419 FoldingSetNodeID ID;
1420 DIEInteger::Profile(ID, Integer);
1422 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1424 Value = new DIEInteger(Integer);
1425 ValuesSet.InsertNode(Value, Where);
1426 Values.push_back(Value);
1429 Die->AddValue(Attribute, Form, Value);
1432 /// AddSInt - Add an signed integer attribute data and value.
1434 void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1435 if (!Form) Form = DIEInteger::BestForm(true, Integer);
1437 FoldingSetNodeID ID;
1438 DIEInteger::Profile(ID, (uint64_t)Integer);
1440 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1442 Value = new DIEInteger(Integer);
1443 ValuesSet.InsertNode(Value, Where);
1444 Values.push_back(Value);
1447 Die->AddValue(Attribute, Form, Value);
1450 /// AddString - Add a std::string attribute data and value.
1452 void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1453 const std::string &String) {
1454 FoldingSetNodeID ID;
1455 DIEString::Profile(ID, String);
1457 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1459 Value = new DIEString(String);
1460 ValuesSet.InsertNode(Value, Where);
1461 Values.push_back(Value);
1464 Die->AddValue(Attribute, Form, Value);
1467 /// AddLabel - Add a Dwarf label attribute data and value.
1469 void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1470 const DWLabel &Label) {
1471 FoldingSetNodeID ID;
1472 DIEDwarfLabel::Profile(ID, Label);
1474 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1476 Value = new DIEDwarfLabel(Label);
1477 ValuesSet.InsertNode(Value, Where);
1478 Values.push_back(Value);
1481 Die->AddValue(Attribute, Form, Value);
1484 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1486 void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1487 const std::string &Label) {
1488 FoldingSetNodeID ID;
1489 DIEObjectLabel::Profile(ID, Label);
1491 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1493 Value = new DIEObjectLabel(Label);
1494 ValuesSet.InsertNode(Value, Where);
1495 Values.push_back(Value);
1498 Die->AddValue(Attribute, Form, Value);
1501 /// AddSectionOffset - Add a section offset label attribute data and value.
1503 void AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
1504 const DWLabel &Label, const DWLabel &Section,
1505 bool isEH = false, bool useSet = true) {
1506 FoldingSetNodeID ID;
1507 DIESectionOffset::Profile(ID, Label, Section);
1509 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1511 Value = new DIESectionOffset(Label, Section, isEH, useSet);
1512 ValuesSet.InsertNode(Value, Where);
1513 Values.push_back(Value);
1516 Die->AddValue(Attribute, Form, Value);
1519 /// AddDelta - Add a label delta attribute data and value.
1521 void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1522 const DWLabel &Hi, const DWLabel &Lo) {
1523 FoldingSetNodeID ID;
1524 DIEDelta::Profile(ID, Hi, Lo);
1526 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1528 Value = new DIEDelta(Hi, Lo);
1529 ValuesSet.InsertNode(Value, Where);
1530 Values.push_back(Value);
1533 Die->AddValue(Attribute, Form, Value);
1536 /// AddDIEntry - Add a DIE attribute data and value.
1538 void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1539 Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1542 /// AddBlock - Add block data.
1544 void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1545 Block->ComputeSize(*this);
1546 FoldingSetNodeID ID;
1549 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1552 ValuesSet.InsertNode(Value, Where);
1553 Values.push_back(Value);
1555 // Already exists, reuse the previous one.
1557 Block = cast<DIEBlock>(Value);
1560 Die->AddValue(Attribute, Block->BestForm(), Value);
1565 /// AddSourceLine - Add location information to specified debug information
1567 void AddSourceLine(DIE *Die, const DIVariable *V) {
1568 unsigned FileID = 0;
1569 unsigned Line = V->getLineNumber();
1570 if (V->getVersion() < DIDescriptor::Version7) {
1571 // Version6 or earlier. Use compile unit info to get file id.
1572 CompileUnit *Unit = FindCompileUnit(V->getCompileUnit());
1573 FileID = Unit->getID();
1575 // Version7 or newer, use filename and directory info from DIVariable
1577 unsigned DID = Directories.idFor(V->getDirectory());
1578 FileID = SrcFiles.idFor(SrcFileInfo(DID, V->getFilename()));
1580 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1581 AddUInt(Die, DW_AT_decl_line, 0, Line);
1584 /// AddSourceLine - Add location information to specified debug information
1586 void AddSourceLine(DIE *Die, const DIGlobal *G) {
1587 unsigned FileID = 0;
1588 unsigned Line = G->getLineNumber();
1589 if (G->getVersion() < DIDescriptor::Version7) {
1590 // Version6 or earlier. Use compile unit info to get file id.
1591 CompileUnit *Unit = FindCompileUnit(G->getCompileUnit());
1592 FileID = Unit->getID();
1594 // Version7 or newer, use filename and directory info from DIGlobal
1596 unsigned DID = Directories.idFor(G->getDirectory());
1597 FileID = SrcFiles.idFor(SrcFileInfo(DID, G->getFilename()));
1599 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1600 AddUInt(Die, DW_AT_decl_line, 0, Line);
1603 void AddSourceLine(DIE *Die, const DIType *Ty) {
1604 unsigned FileID = 0;
1605 unsigned Line = Ty->getLineNumber();
1606 if (Ty->getVersion() < DIDescriptor::Version7) {
1607 // Version6 or earlier. Use compile unit info to get file id.
1608 CompileUnit *Unit = FindCompileUnit(Ty->getCompileUnit());
1609 FileID = Unit->getID();
1611 // Version7 or newer, use filename and directory info from DIType
1613 unsigned DID = Directories.idFor(Ty->getDirectory());
1614 FileID = SrcFiles.idFor(SrcFileInfo(DID, Ty->getFilename()));
1616 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1617 AddUInt(Die, DW_AT_decl_line, 0, Line);
1620 /// AddAddress - Add an address attribute to a die based on the location
1622 void AddAddress(DIE *Die, unsigned Attribute,
1623 const MachineLocation &Location) {
1624 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
1625 DIEBlock *Block = new DIEBlock();
1627 if (Location.isReg()) {
1629 AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1631 AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1632 AddUInt(Block, 0, DW_FORM_udata, Reg);
1636 AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1638 AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1639 AddUInt(Block, 0, DW_FORM_udata, Reg);
1641 AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1644 AddBlock(Die, Attribute, 0, Block);
1647 /// AddBasicType - Add a new basic type attribute to the specified entity.
1649 void AddBasicType(DIE *Entity, CompileUnit *Unit,
1650 const std::string &Name,
1651 unsigned Encoding, unsigned Size) {
1653 DIE Buffer(DW_TAG_base_type);
1654 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1655 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, Encoding);
1656 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1657 DIE *BasicTypeDie = Unit->AddDie(Buffer);
1658 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, BasicTypeDie);
1661 /// AddPointerType - Add a new pointer type attribute to the specified entity.
1663 void AddPointerType(DIE *Entity, CompileUnit *Unit, const std::string &Name) {
1664 DIE Buffer(DW_TAG_pointer_type);
1665 AddUInt(&Buffer, DW_AT_byte_size, 0, TD->getPointerSize());
1666 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1667 DIE *PointerTypeDie = Unit->AddDie(Buffer);
1668 AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, PointerTypeDie);
1671 /// AddType - Add a new type attribute to the specified entity.
1672 void AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
1674 AddBasicType(Entity, DW_Unit, "", DW_ATE_signed, sizeof(int32_t));
1678 // Check for pre-existence.
1679 DIEntry *&Slot = DW_Unit->getDIEntrySlotFor(Ty.getGV());
1680 // If it exists then use the existing value.
1682 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1687 Slot = NewDIEntry();
1690 DIE Buffer(DW_TAG_base_type);
1691 if (Ty.isBasicType(Ty.getTag()))
1692 ConstructTypeDIE(DW_Unit, Buffer, DIBasicType(Ty.getGV()));
1693 else if (Ty.isDerivedType(Ty.getTag()))
1694 ConstructTypeDIE(DW_Unit, Buffer, DIDerivedType(Ty.getGV()));
1696 assert (Ty.isCompositeType(Ty.getTag()) && "Unknown kind of DIType");
1697 ConstructTypeDIE(DW_Unit, Buffer, DICompositeType(Ty.getGV()));
1700 // Add debug information entry to entity and unit.
1701 DIE *Die = DW_Unit->AddDie(Buffer);
1702 SetDIEntry(Slot, Die);
1703 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1706 /// ConstructTypeDIE - Construct basic type die from DIBasicType.
1707 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1710 // Get core information.
1711 const std::string &Name = BTy.getName();
1712 Buffer.setTag(DW_TAG_base_type);
1713 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BTy.getEncoding());
1714 // Add name if not anonymous or intermediate type.
1716 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1717 uint64_t Size = BTy.getSizeInBits() >> 3;
1718 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1721 /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
1722 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1723 DIDerivedType DTy) {
1725 // Get core information.
1726 const std::string &Name = DTy.getName();
1727 uint64_t Size = DTy.getSizeInBits() >> 3;
1728 unsigned Tag = DTy.getTag();
1729 // FIXME - Workaround for templates.
1730 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1733 // Map to main type, void will not have a type.
1734 DIType FromTy = DTy.getTypeDerivedFrom();
1735 AddType(DW_Unit, &Buffer, FromTy);
1737 // Add name if not anonymous or intermediate type.
1738 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1740 // Add size if non-zero (derived types might be zero-sized.)
1742 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1744 // Add source line info if available and TyDesc is not a forward
1746 // FIXME - Enable this. if (!DTy.isForwardDecl())
1747 // FIXME - Enable this. AddSourceLine(&Buffer, *DTy);
1750 /// ConstructTypeDIE - Construct type DIE from DICompositeType.
1751 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1752 DICompositeType CTy) {
1754 /// FIXME - Enable this asap.
1757 // Get core information.
1758 const std::string &Name = CTy.getName();
1759 uint64_t Size = CTy.getSizeInBits() >> 3;
1760 unsigned Tag = CTy.getTag();
1762 case DW_TAG_vector_type:
1763 case DW_TAG_array_type:
1764 ConstructArrayTypeDIE(DW_Unit, Buffer, &CTy);
1766 //FIXME - Enable this.
1767 // case DW_TAG_enumeration_type:
1768 // DIArray Elements = CTy.getTypeArray();
1769 // // Add enumerators to enumeration type.
1770 // for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i)
1771 // ConstructEnumTypeDIE(Buffer, &Elements.getElement(i));
1773 case DW_TAG_subroutine_type:
1775 // Add prototype flag.
1776 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1777 DIArray Elements = CTy.getTypeArray();
1779 DIDescriptor RTy = Elements.getElement(0);
1780 AddType(DW_Unit, &Buffer, DIType(RTy.getGV()));
1782 //AddType(DW_Unit, &Buffer, Elements.getElement(0));
1784 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1785 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1786 DIDescriptor Ty = Elements.getElement(i);
1787 AddType(DW_Unit, &Buffer, DIType(Ty.getGV()));
1788 Buffer.AddChild(Arg);
1792 case DW_TAG_structure_type:
1793 case DW_TAG_union_type:
1795 // Add elements to structure type.
1796 DIArray Elements = CTy.getTypeArray();
1798 // A forward struct declared type may not have elements available.
1799 if (Elements.isNull())
1802 // Add elements to structure type.
1803 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1804 DIDescriptor Element = Elements.getElement(i);
1805 if (Element.getTag() == dwarf::DW_TAG_subprogram)
1806 ConstructFieldTypeDIE(DW_Unit, Buffer, DISubprogram(Element.getGV()));
1807 else if (Element.getTag() == dwarf::DW_TAG_variable)
1808 ConstructFieldTypeDIE(DW_Unit, Buffer,
1809 DIGlobalVariable(Element.getGV()));
1811 DIDerivedType DT = DIDerivedType(Element.getGV());
1812 assert (DT.isDerivedType(DT.getTag()) && "Unexpected strcut element");
1813 ConstructFieldTypeDIE(DW_Unit, Buffer, DT);
1822 // Add name if not anonymous or intermediate type.
1823 if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1825 // Add size if non-zero (derived types might be zero-sized.)
1827 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1829 // Add zero size even if it is not a forward declaration.
1830 // FIXME - Enable this.
1831 // if (!CTy.isDefinition())
1832 // AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
1834 // AddUInt(&Buffer, DW_AT_byte_size, 0, 0);
1837 // Add source line info if available and TyDesc is not a forward
1839 // FIXME - Enable this.
1840 // if (CTy.isForwardDecl())
1841 // AddSourceLine(&Buffer, *CTy);
1844 // ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
1845 void ConstructSubrangeDIE (DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1846 int64_t L = SR.getLo();
1847 int64_t H = SR.getHi();
1848 DIE *DW_Subrange = new DIE(DW_TAG_subrange_type);
1850 AddDIEntry(DW_Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1852 AddSInt(DW_Subrange, DW_AT_lower_bound, 0, L);
1853 AddSInt(DW_Subrange, DW_AT_upper_bound, 0, H);
1855 Buffer.AddChild(DW_Subrange);
1858 /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
1859 void ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1860 DICompositeType *CTy) {
1861 Buffer.setTag(DW_TAG_array_type);
1862 if (CTy->getTag() == DW_TAG_vector_type)
1863 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1865 DIArray Elements = CTy->getTypeArray();
1866 // FIXME - Enable this.
1867 AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
1869 // Construct an anonymous type for index type.
1870 DIE IdxBuffer(DW_TAG_base_type);
1871 AddUInt(&IdxBuffer, DW_AT_byte_size, 0, sizeof(int32_t));
1872 AddUInt(&IdxBuffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
1873 DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
1875 // Add subranges to array type.
1876 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1877 DIDescriptor Element = Elements.getElement(i);
1878 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1879 ConstructSubrangeDIE(Buffer, DISubrange(Element.getGV()), IndexTy);
1883 /// ConstructEnumTypeDIE - Construct enum type DIE from
1885 void ConstructEnumTypeDIE(CompileUnit *DW_Unit,
1886 DIE &Buffer, DIEnumerator *ETy) {
1888 DIE *Enumerator = new DIE(DW_TAG_enumerator);
1889 AddString(Enumerator, DW_AT_name, DW_FORM_string, ETy->getName());
1890 int64_t Value = ETy->getEnumValue();
1891 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1892 Buffer.AddChild(Enumerator);
1895 /// ConstructFieldTypeDIE - Construct variable DIE for a struct field.
1896 void ConstructFieldTypeDIE(CompileUnit *DW_Unit,
1897 DIE &Buffer, DIGlobalVariable V) {
1899 DIE *VariableDie = new DIE(DW_TAG_variable);
1900 const std::string &LinkageName = V.getLinkageName();
1901 if (!LinkageName.empty())
1902 AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1904 // FIXME - Enable this. AddSourceLine(VariableDie, V);
1905 AddType(DW_Unit, VariableDie, V.getType());
1906 if (!V.isLocalToUnit())
1907 AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
1908 AddUInt(VariableDie, DW_AT_declaration, DW_FORM_flag, 1);
1909 Buffer.AddChild(VariableDie);
1912 /// ConstructFieldTypeDIE - Construct subprogram DIE for a struct field.
1913 void ConstructFieldTypeDIE(CompileUnit *DW_Unit,
1914 DIE &Buffer, DISubprogram SP,
1915 bool IsConstructor = false) {
1916 DIE *Method = new DIE(DW_TAG_subprogram);
1917 AddString(Method, DW_AT_name, DW_FORM_string, SP.getName());
1918 const std::string &LinkageName = SP.getLinkageName();
1919 if (!LinkageName.empty())
1920 AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string, LinkageName);
1921 // FIXME - Enable this. AddSourceLine(Method, SP);
1923 DICompositeType MTy = SP.getType();
1924 DIArray Args = MTy.getTypeArray();
1928 AddType(DW_Unit, Method, DIType(Args.getElement(0).getGV()));
1931 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1932 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1933 AddType(DW_Unit, Method, DIType(Args.getElement(i).getGV()));
1934 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1); // ???
1935 Method->AddChild(Arg);
1938 if (!SP.isLocalToUnit())
1939 AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);
1940 Buffer.AddChild(Method);
1943 /// ConstructFieldTypeDIE - Construct derived type DIE for a struct field.
1944 void ConstructFieldTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1945 DIDerivedType DTy) {
1946 unsigned Tag = DTy.getTag();
1947 DIE *MemberDie = new DIE(Tag);
1948 if (!DTy.getName().empty())
1949 AddString(MemberDie, DW_AT_name, DW_FORM_string, DTy.getName());
1950 // FIXME - Enable this. AddSourceLine(MemberDie, DTy);
1952 DIType FromTy = DTy.getTypeDerivedFrom();
1953 AddType(DW_Unit, MemberDie, FromTy);
1955 uint64_t Size = DTy.getSizeInBits();
1956 uint64_t Offset = DTy.getOffsetInBits();
1958 // FIXME Handle bitfields
1961 AddUInt(MemberDie, DW_AT_bit_size, 0, Size);
1962 // Add computation for offset.
1963 DIEBlock *Block = new DIEBlock();
1964 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1965 AddUInt(Block, 0, DW_FORM_udata, Offset >> 3);
1966 AddBlock(MemberDie, DW_AT_data_member_location, 0, Block);
1968 // FIXME Handle DW_AT_accessibility.
1970 Buffer.AddChild(MemberDie);
1973 /// FindCompileUnit - Get the compile unit for the given descriptor.
1975 CompileUnit *FindCompileUnit(DICompileUnit Unit) {
1976 CompileUnit *DW_Unit = DW_CUs[Unit.getGV()];
1977 assert(DW_Unit && "Missing compile unit.");
1981 /// NewDbgScopeVariable - Create a new scope variable.
1983 DIE *NewDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
1984 // Get the descriptor.
1985 const DIVariable &VD = DV->getVariable();
1987 // Translate tag to proper Dwarf tag. The result variable is dropped for
1990 switch (VD.getTag()) {
1991 case DW_TAG_return_variable: return NULL;
1992 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
1993 case DW_TAG_auto_variable: // fall thru
1994 default: Tag = DW_TAG_variable; break;
1997 // Define variable debug information entry.
1998 DIE *VariableDie = new DIE(Tag);
1999 AddString(VariableDie, DW_AT_name, DW_FORM_string, VD.getName());
2001 // Add source line info if available.
2002 AddSourceLine(VariableDie, &VD);
2004 // Add variable type.
2005 AddType(Unit, VariableDie, VD.getType());
2007 // Add variable address.
2008 MachineLocation Location;
2009 Location.set(RI->getFrameRegister(*MF),
2010 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
2011 AddAddress(VariableDie, DW_AT_location, Location);
2016 /// getOrCreateScope - Returns the scope associated with the given descriptor.
2018 DbgScope *getOrCreateScope(GlobalVariable *V) {
2019 DbgScope *&Slot = DbgScopeMap[V];
2021 // FIXME - breaks down when the context is an inlined function.
2022 DIDescriptor ParentDesc;
2023 DIDescriptor Desc(V);
2024 if (Desc.getTag() == dwarf::DW_TAG_lexical_block) {
2026 ParentDesc = Block.getContext();
2028 DbgScope *Parent = ParentDesc.isNull() ?
2029 NULL : getOrCreateScope(ParentDesc.getGV());
2030 Slot = new DbgScope(Parent, Desc);
2032 Parent->AddScope(Slot);
2033 } else if (RootDbgScope) {
2034 // FIXME - Add inlined function scopes to the root so we can delete
2035 // them later. Long term, handle inlined functions properly.
2036 RootDbgScope->AddScope(Slot);
2038 // First function is top level function.
2039 RootDbgScope = Slot;
2045 /// ConstructDbgScope - Construct the components of a scope.
2047 void ConstructDbgScope(DbgScope *ParentScope,
2048 unsigned ParentStartID, unsigned ParentEndID,
2049 DIE *ParentDie, CompileUnit *Unit) {
2050 // Add variables to scope.
2051 SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
2052 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2053 DIE *VariableDie = NewDbgScopeVariable(Variables[i], Unit);
2054 if (VariableDie) ParentDie->AddChild(VariableDie);
2057 // Add nested scopes.
2058 SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
2059 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
2060 // Define the Scope debug information entry.
2061 DbgScope *Scope = Scopes[j];
2062 // FIXME - Ignore inlined functions for the time being.
2063 if (!Scope->getParent()) continue;
2065 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
2066 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
2068 // Ignore empty scopes.
2069 if (StartID == EndID && StartID != 0) continue;
2070 if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
2072 if (StartID == ParentStartID && EndID == ParentEndID) {
2073 // Just add stuff to the parent scope.
2074 ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
2076 DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
2078 // Add the scope bounds.
2080 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2081 DWLabel("label", StartID));
2083 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2084 DWLabel("func_begin", SubprogramCount));
2087 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2088 DWLabel("label", EndID));
2090 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2091 DWLabel("func_end", SubprogramCount));
2094 // Add the scope contents.
2095 ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
2096 ParentDie->AddChild(ScopeDie);
2101 /// ConstructRootDbgScope - Construct the scope for the subprogram.
2103 void ConstructRootDbgScope(DbgScope *RootScope) {
2104 // Exit if there is no root scope.
2105 if (!RootScope) return;
2106 DIDescriptor Desc = RootScope->getDesc();
2110 // Get the subprogram debug information entry.
2111 DISubprogram SPD(Desc.getGV());
2113 // Get the compile unit context.
2114 CompileUnit *Unit = FindCompileUnit(SPD.getCompileUnit());
2116 // Get the subprogram die.
2117 DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
2118 assert(SPDie && "Missing subprogram descriptor");
2120 // Add the function bounds.
2121 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2122 DWLabel("func_begin", SubprogramCount));
2123 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2124 DWLabel("func_end", SubprogramCount));
2125 MachineLocation Location(RI->getFrameRegister(*MF));
2126 AddAddress(SPDie, DW_AT_frame_base, Location);
2128 ConstructDbgScope(RootScope, 0, 0, SPDie, Unit);
2131 /// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
2133 void ConstructDefaultDbgScope(MachineFunction *MF) {
2134 // Find the correct subprogram descriptor.
2135 std::string SPName = "llvm.dbg.subprograms";
2136 std::vector<GlobalVariable*> Result;
2137 getGlobalVariablesUsing(*M, SPName, Result);
2138 for (std::vector<GlobalVariable *>::iterator I = Result.begin(),
2139 E = Result.end(); I != E; ++I) {
2141 DISubprogram SPD(*I);
2143 if (SPD.getName() == MF->getFunction()->getName()) {
2144 // Get the compile unit context.
2145 CompileUnit *Unit = FindCompileUnit(SPD.getCompileUnit());
2147 // Get the subprogram die.
2148 DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
2149 assert(SPDie && "Missing subprogram descriptor");
2151 // Add the function bounds.
2152 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2153 DWLabel("func_begin", SubprogramCount));
2154 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2155 DWLabel("func_end", SubprogramCount));
2157 MachineLocation Location(RI->getFrameRegister(*MF));
2158 AddAddress(SPDie, DW_AT_frame_base, Location);
2163 // FIXME: This is causing an abort because C++ mangled names are compared
2164 // with their unmangled counterparts. See PR2885. Don't do this assert.
2165 assert(0 && "Couldn't find DIE for machine function!");
2169 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
2170 /// tools to recognize the object file contains Dwarf information.
2171 void EmitInitial() {
2172 // Check to see if we already emitted intial headers.
2173 if (didInitial) return;
2176 // Dwarf sections base addresses.
2177 if (TAI->doesDwarfRequireFrameSection()) {
2178 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2179 EmitLabel("section_debug_frame", 0);
2181 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2182 EmitLabel("section_info", 0);
2183 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2184 EmitLabel("section_abbrev", 0);
2185 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2186 EmitLabel("section_aranges", 0);
2187 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2188 EmitLabel("section_macinfo", 0);
2189 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2190 EmitLabel("section_line", 0);
2191 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2192 EmitLabel("section_loc", 0);
2193 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2194 EmitLabel("section_pubnames", 0);
2195 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2196 EmitLabel("section_str", 0);
2197 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2198 EmitLabel("section_ranges", 0);
2200 Asm->SwitchToSection(TAI->getTextSection());
2201 EmitLabel("text_begin", 0);
2202 Asm->SwitchToSection(TAI->getDataSection());
2203 EmitLabel("data_begin", 0);
2206 /// EmitDIE - Recusively Emits a debug information entry.
2208 void EmitDIE(DIE *Die) {
2209 // Get the abbreviation for this DIE.
2210 unsigned AbbrevNumber = Die->getAbbrevNumber();
2211 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2215 // Emit the code (index) for the abbreviation.
2216 Asm->EmitULEB128Bytes(AbbrevNumber);
2219 Asm->EOL(std::string("Abbrev [" +
2220 utostr(AbbrevNumber) +
2221 "] 0x" + utohexstr(Die->getOffset()) +
2222 ":0x" + utohexstr(Die->getSize()) + " " +
2223 TagString(Abbrev->getTag())));
2227 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2228 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2230 // Emit the DIE attribute values.
2231 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2232 unsigned Attr = AbbrevData[i].getAttribute();
2233 unsigned Form = AbbrevData[i].getForm();
2234 assert(Form && "Too many attributes for DIE (check abbreviation)");
2237 case DW_AT_sibling: {
2238 Asm->EmitInt32(Die->SiblingOffset());
2242 // Emit an attribute using the defined form.
2243 Values[i]->EmitValue(*this, Form);
2248 Asm->EOL(AttributeString(Attr));
2251 // Emit the DIE children if any.
2252 if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2253 const std::vector<DIE *> &Children = Die->getChildren();
2255 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2256 EmitDIE(Children[j]);
2259 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2263 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2265 unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2266 // Get the children.
2267 const std::vector<DIE *> &Children = Die->getChildren();
2269 // If not last sibling and has children then add sibling offset attribute.
2270 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2272 // Record the abbreviation.
2273 AssignAbbrevNumber(Die->getAbbrev());
2275 // Get the abbreviation for this DIE.
2276 unsigned AbbrevNumber = Die->getAbbrevNumber();
2277 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2280 Die->setOffset(Offset);
2282 // Start the size with the size of abbreviation code.
2283 Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
2285 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2286 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2288 // Size the DIE attribute values.
2289 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2290 // Size attribute value.
2291 Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2294 // Size the DIE children if any.
2295 if (!Children.empty()) {
2296 assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2297 "Children flag not set");
2299 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2300 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2303 // End of children marker.
2304 Offset += sizeof(int8_t);
2307 Die->setSize(Offset - Die->getOffset());
2311 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2313 void SizeAndOffsets() {
2314 // Process base compile unit.
2315 for (DenseMap<Value *, CompileUnit *>::iterator CI = DW_CUs.begin(),
2316 CE = DW_CUs.end(); CI != CE; ++CI) {
2317 CompileUnit *Unit = CI->second;
2318 // Compute size of compile unit header
2319 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2320 sizeof(int16_t) + // DWARF version number
2321 sizeof(int32_t) + // Offset Into Abbrev. Section
2322 sizeof(int8_t); // Pointer Size (in bytes)
2323 SizeAndOffsetDie(Unit->getDie(), Offset, true);
2327 /// EmitDebugInfo - Emit the debug info section.
2329 void EmitDebugInfo() {
2330 // Start debug info section.
2331 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2333 for (DenseMap<Value *, CompileUnit *>::iterator CI = DW_CUs.begin(),
2334 CE = DW_CUs.end(); CI != CE; ++CI) {
2335 CompileUnit *Unit = CI->second;
2336 DIE *Die = Unit->getDie();
2337 // Emit the compile units header.
2338 EmitLabel("info_begin", Unit->getID());
2339 // Emit size of content not including length itself
2340 unsigned ContentSize = Die->getSize() +
2341 sizeof(int16_t) + // DWARF version number
2342 sizeof(int32_t) + // Offset Into Abbrev. Section
2343 sizeof(int8_t) + // Pointer Size (in bytes)
2344 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2346 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2347 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2348 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2349 Asm->EOL("Offset Into Abbrev. Section");
2350 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2353 // FIXME - extra padding for gdb bug.
2354 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2355 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2356 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2357 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2358 EmitLabel("info_end", Unit->getID());
2364 /// EmitAbbreviations - Emit the abbreviation section.
2366 void EmitAbbreviations() const {
2367 // Check to see if it is worth the effort.
2368 if (!Abbreviations.empty()) {
2369 // Start the debug abbrev section.
2370 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2372 EmitLabel("abbrev_begin", 0);
2374 // For each abbrevation.
2375 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2376 // Get abbreviation data
2377 const DIEAbbrev *Abbrev = Abbreviations[i];
2379 // Emit the abbrevations code (base 1 index.)
2380 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2381 Asm->EOL("Abbreviation Code");
2383 // Emit the abbreviations data.
2384 Abbrev->Emit(*this);
2389 // Mark end of abbreviations.
2390 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2392 EmitLabel("abbrev_end", 0);
2398 /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
2399 /// the line matrix.
2401 void EmitEndOfLineMatrix(unsigned SectionEnd) {
2402 // Define last address of section.
2403 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2404 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2405 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2406 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2408 // Mark end of matrix.
2409 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2410 Asm->EmitULEB128Bytes(1); Asm->EOL();
2411 Asm->EmitInt8(1); Asm->EOL();
2414 /// EmitDebugLines - Emit source line information.
2416 void EmitDebugLines() {
2417 // If the target is using .loc/.file, the assembler will be emitting the
2418 // .debug_line table automatically.
2419 if (TAI->hasDotLocAndDotFile())
2422 // Minimum line delta, thus ranging from -10..(255-10).
2423 const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2424 // Maximum line delta, thus ranging from -10..(255-10).
2425 const int MaxLineDelta = 255 + MinLineDelta;
2427 // Start the dwarf line section.
2428 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2430 // Construct the section header.
2432 EmitDifference("line_end", 0, "line_begin", 0, true);
2433 Asm->EOL("Length of Source Line Info");
2434 EmitLabel("line_begin", 0);
2436 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2438 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2439 Asm->EOL("Prolog Length");
2440 EmitLabel("line_prolog_begin", 0);
2442 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2444 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2446 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2448 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2450 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2452 // Line number standard opcode encodings argument count
2453 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2454 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2455 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2456 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2457 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2458 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2459 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2460 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2461 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2463 // Emit directories.
2464 for (unsigned DirectoryID = 1, NDID = Directories.size();
2465 DirectoryID <= NDID; ++DirectoryID) {
2466 Asm->EmitString(Directories[DirectoryID]); Asm->EOL("Directory");
2468 Asm->EmitInt8(0); Asm->EOL("End of directories");
2471 for (unsigned SourceID = 1, NSID = SrcFiles.size();
2472 SourceID <= NSID; ++SourceID) {
2473 const SrcFileInfo &SourceFile = SrcFiles[SourceID];
2474 Asm->EmitString(SourceFile.getName());
2476 Asm->EmitULEB128Bytes(SourceFile.getDirectoryID());
2477 Asm->EOL("Directory #");
2478 Asm->EmitULEB128Bytes(0);
2479 Asm->EOL("Mod date");
2480 Asm->EmitULEB128Bytes(0);
2481 Asm->EOL("File size");
2483 Asm->EmitInt8(0); Asm->EOL("End of files");
2485 EmitLabel("line_prolog_end", 0);
2487 // A sequence for each text section.
2488 unsigned SecSrcLinesSize = SectionSourceLines.size();
2490 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2491 // Isolate current sections line info.
2492 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2495 const Section* S = SectionMap[j + 1];
2496 Asm->EOL(std::string("Section ") + S->getName());
2500 // Dwarf assumes we start with first line of first source file.
2501 unsigned Source = 1;
2504 // Construct rows of the address, source, line, column matrix.
2505 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2506 const SrcLineInfo &LineInfo = LineInfos[i];
2507 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2508 if (!LabelID) continue;
2510 unsigned SourceID = LineInfo.getSourceID();
2511 const SrcFileInfo &SourceFile = SrcFiles[SourceID];
2512 unsigned DirectoryID = SourceFile.getDirectoryID();
2514 Asm->EOL(Directories[DirectoryID]
2515 + SourceFile.getName()
2517 + utostr_32(LineInfo.getLine()));
2521 // Define the line address.
2522 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2523 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2524 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2525 EmitReference("label", LabelID); Asm->EOL("Location label");
2527 // If change of source, then switch to the new source.
2528 if (Source != LineInfo.getSourceID()) {
2529 Source = LineInfo.getSourceID();
2530 Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2531 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2534 // If change of line.
2535 if (Line != LineInfo.getLine()) {
2536 // Determine offset.
2537 int Offset = LineInfo.getLine() - Line;
2538 int Delta = Offset - MinLineDelta;
2541 Line = LineInfo.getLine();
2543 // If delta is small enough and in range...
2544 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2545 // ... then use fast opcode.
2546 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2548 // ... otherwise use long hand.
2549 Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
2550 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2551 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2554 // Copy the previous row (different address or source)
2555 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2559 EmitEndOfLineMatrix(j + 1);
2562 if (SecSrcLinesSize == 0)
2563 // Because we're emitting a debug_line section, we still need a line
2564 // table. The linker and friends expect it to exist. If there's nothing to
2565 // put into it, emit an empty table.
2566 EmitEndOfLineMatrix(1);
2568 EmitLabel("line_end", 0);
2573 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2575 void EmitCommonDebugFrame() {
2576 if (!TAI->doesDwarfRequireFrameSection())
2580 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2581 TargetFrameInfo::StackGrowsUp ?
2582 TD->getPointerSize() : -TD->getPointerSize();
2584 // Start the dwarf frame section.
2585 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2587 EmitLabel("debug_frame_common", 0);
2588 EmitDifference("debug_frame_common_end", 0,
2589 "debug_frame_common_begin", 0, true);
2590 Asm->EOL("Length of Common Information Entry");
2592 EmitLabel("debug_frame_common_begin", 0);
2593 Asm->EmitInt32((int)DW_CIE_ID);
2594 Asm->EOL("CIE Identifier Tag");
2595 Asm->EmitInt8(DW_CIE_VERSION);
2596 Asm->EOL("CIE Version");
2597 Asm->EmitString("");
2598 Asm->EOL("CIE Augmentation");
2599 Asm->EmitULEB128Bytes(1);
2600 Asm->EOL("CIE Code Alignment Factor");
2601 Asm->EmitSLEB128Bytes(stackGrowth);
2602 Asm->EOL("CIE Data Alignment Factor");
2603 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2604 Asm->EOL("CIE RA Column");
2606 std::vector<MachineMove> Moves;
2607 RI->getInitialFrameState(Moves);
2609 EmitFrameMoves(NULL, 0, Moves, false);
2611 Asm->EmitAlignment(2, 0, 0, false);
2612 EmitLabel("debug_frame_common_end", 0);
2617 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2619 void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2620 if (!TAI->doesDwarfRequireFrameSection())
2623 // Start the dwarf frame section.
2624 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2626 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2627 "debug_frame_begin", DebugFrameInfo.Number, true);
2628 Asm->EOL("Length of Frame Information Entry");
2630 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2632 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2634 Asm->EOL("FDE CIE offset");
2636 EmitReference("func_begin", DebugFrameInfo.Number);
2637 Asm->EOL("FDE initial location");
2638 EmitDifference("func_end", DebugFrameInfo.Number,
2639 "func_begin", DebugFrameInfo.Number);
2640 Asm->EOL("FDE address range");
2642 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves, false);
2644 Asm->EmitAlignment(2, 0, 0, false);
2645 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2650 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2652 void EmitDebugPubNames() {
2653 // Start the dwarf pubnames section.
2654 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2656 for (DenseMap<Value *, CompileUnit *>::iterator CI = DW_CUs.begin(),
2657 CE = DW_CUs.end(); CI != CE; ++CI) {
2658 CompileUnit *Unit = CI->second;
2660 EmitDifference("pubnames_end", Unit->getID(),
2661 "pubnames_begin", Unit->getID(), true);
2662 Asm->EOL("Length of Public Names Info");
2664 EmitLabel("pubnames_begin", Unit->getID());
2666 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
2668 EmitSectionOffset("info_begin", "section_info",
2669 Unit->getID(), 0, true, false);
2670 Asm->EOL("Offset of Compilation Unit Info");
2672 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),true);
2673 Asm->EOL("Compilation Unit Length");
2675 std::map<std::string, DIE *> &Globals = Unit->getGlobals();
2677 for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
2680 const std::string &Name = GI->first;
2681 DIE * Entity = GI->second;
2683 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2684 Asm->EmitString(Name); Asm->EOL("External Name");
2687 Asm->EmitInt32(0); Asm->EOL("End Mark");
2688 EmitLabel("pubnames_end", Unit->getID());
2694 /// EmitDebugStr - Emit visible names into a debug str section.
2696 void EmitDebugStr() {
2697 // Check to see if it is worth the effort.
2698 if (!StringPool.empty()) {
2699 // Start the dwarf str section.
2700 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2702 // For each of strings in the string pool.
2703 for (unsigned StringID = 1, N = StringPool.size();
2704 StringID <= N; ++StringID) {
2705 // Emit a label for reference from debug information entries.
2706 EmitLabel("string", StringID);
2707 // Emit the string itself.
2708 const std::string &String = StringPool[StringID];
2709 Asm->EmitString(String); Asm->EOL();
2716 /// EmitDebugLoc - Emit visible names into a debug loc section.
2718 void EmitDebugLoc() {
2719 // Start the dwarf loc section.
2720 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2725 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2727 void EmitDebugARanges() {
2728 // Start the dwarf aranges section.
2729 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2733 CompileUnit *Unit = GetBaseCompileUnit();
2735 // Don't include size of length
2736 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2738 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2740 EmitReference("info_begin", Unit->getID());
2741 Asm->EOL("Offset of Compilation Unit Info");
2743 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2745 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2747 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2748 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2751 EmitReference("text_begin", 0); Asm->EOL("Address");
2752 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2754 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2755 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2761 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2763 void EmitDebugRanges() {
2764 // Start the dwarf ranges section.
2765 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2770 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2772 void EmitDebugMacInfo() {
2773 // Start the dwarf macinfo section.
2774 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2779 /// ConstructCompileUnits - Create a compile unit DIEs.
2780 void ConstructCompileUnits() {
2781 std::string CUName = "llvm.dbg.compile_units";
2782 std::vector<GlobalVariable*> Result;
2783 getGlobalVariablesUsing(*M, CUName, Result);
2784 for (std::vector<GlobalVariable *>::iterator RI = Result.begin(),
2785 RE = Result.end(); RI != RE; ++RI) {
2786 DICompileUnit DIUnit(*RI);
2787 unsigned ID = RecordSource(DIUnit.getDirectory(),
2788 DIUnit.getFilename());
2790 DIE *Die = new DIE(DW_TAG_compile_unit);
2791 AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
2792 DWLabel("section_line", 0), DWLabel("section_line", 0),
2794 AddString(Die, DW_AT_producer, DW_FORM_string, DIUnit.getProducer());
2795 AddUInt(Die, DW_AT_language, DW_FORM_data1, DIUnit.getLanguage());
2796 AddString(Die, DW_AT_name, DW_FORM_string, DIUnit.getFilename());
2797 if (!DIUnit.getDirectory().empty())
2798 AddString(Die, DW_AT_comp_dir, DW_FORM_string, DIUnit.getDirectory());
2800 CompileUnit *Unit = new CompileUnit(ID, Die);
2801 DW_CUs[DIUnit.getGV()] = Unit;
2805 /// ConstructGlobalVariableDIEs - Create DIEs for each of the externally
2806 /// visible global variables.
2807 void ConstructGlobalVariableDIEs() {
2808 std::string GVName = "llvm.dbg.global_variables";
2809 std::vector<GlobalVariable*> Result;
2810 getGlobalVariablesUsing(*M, GVName, Result);
2811 for (std::vector<GlobalVariable *>::iterator GVI = Result.begin(),
2812 GVE = Result.end(); GVI != GVE; ++GVI) {
2813 DIGlobalVariable DI_GV(*GVI);
2814 CompileUnit *DW_Unit = FindCompileUnit(DI_GV.getCompileUnit());
2816 // Check for pre-existence.
2817 DIE *&Slot = DW_Unit->getDieMapSlotFor(DI_GV.getGV());
2820 DIE *VariableDie = new DIE(DW_TAG_variable);
2821 AddString(VariableDie, DW_AT_name, DW_FORM_string, DI_GV.getName());
2822 const std::string &LinkageName = DI_GV.getLinkageName();
2823 if (!LinkageName.empty())
2824 AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
2826 AddType(DW_Unit, VariableDie, DI_GV.getType());
2828 if (!DI_GV.isLocalToUnit())
2829 AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
2831 // Add source line info, if available.
2832 AddSourceLine(VariableDie, &DI_GV);
2835 DIEBlock *Block = new DIEBlock();
2836 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
2837 AddObjectLabel(Block, 0, DW_FORM_udata,
2838 Asm->getGlobalLinkName(DI_GV.getGV()));
2839 AddBlock(VariableDie, DW_AT_location, 0, Block);
2844 //Add to context owner.
2845 DW_Unit->getDie()->AddChild(VariableDie);
2847 //Expose as global. FIXME - need to check external flag.
2848 DW_Unit->AddGlobal(DI_GV.getName(), VariableDie);
2852 /// ConstructSubprograms - Create DIEs for each of the externally visible
2854 void ConstructSubprograms() {
2856 std::string SPName = "llvm.dbg.subprograms";
2857 std::vector<GlobalVariable*> Result;
2858 getGlobalVariablesUsing(*M, SPName, Result);
2859 for (std::vector<GlobalVariable *>::iterator RI = Result.begin(),
2860 RE = Result.end(); RI != RE; ++RI) {
2862 DISubprogram SP(*RI);
2863 CompileUnit *Unit = FindCompileUnit(SP.getCompileUnit());
2865 // Check for pre-existence.
2866 DIE *&Slot = Unit->getDieMapSlotFor(SP.getGV());
2869 DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
2870 AddString(SubprogramDie, DW_AT_name, DW_FORM_string, SP.getName());
2871 const std::string &LinkageName = SP.getLinkageName();
2872 if (!LinkageName.empty())
2873 AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
2875 DIType SPTy = SP.getType();
2876 AddType(Unit, SubprogramDie, SPTy);
2877 if (!SP.isLocalToUnit())
2878 AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
2879 AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
2881 AddSourceLine(SubprogramDie, &SP);
2883 Slot = SubprogramDie;
2884 //Add to context owner.
2885 Unit->getDie()->AddChild(SubprogramDie);
2887 Unit->AddGlobal(SP.getName(), SubprogramDie);
2892 //===--------------------------------------------------------------------===//
2893 // Main entry points.
2895 DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
2896 : Dwarf(OS, A, T, "dbg")
2898 , AbbreviationsSet(InitAbbreviationsSetSize)
2900 , ValuesSet(InitValuesSetSize)
2904 , SectionSourceLines()
2907 , RootDbgScope(NULL)
2910 virtual ~DwarfDebug() {
2911 for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i)
2912 delete CompileUnits[i];
2913 for (unsigned j = 0, M = Values.size(); j < M; ++j)
2917 /// SetDebugInfo - Create global DIEs and emit initial debug info sections.
2918 /// This is inovked by the target AsmPrinter.
2919 void SetDebugInfo(MachineModuleInfo *mmi) {
2921 // Create all the compile unit DIEs.
2922 ConstructCompileUnits();
2929 MMI->setDebugInfoAvailability(true);
2931 // Create DIEs for each of the externally visible global variables.
2932 ConstructGlobalVariableDIEs();
2934 // Create DIEs for each of the externally visible subprograms.
2935 ConstructSubprograms();
2937 // Prime section data.
2938 SectionMap.insert(TAI->getTextSection());
2940 // Print out .file directives to specify files for .loc directives. These
2941 // are printed out early so that they precede any .loc directives.
2942 if (TAI->hasDotLocAndDotFile()) {
2943 for (unsigned i = 1, e = SrcFiles.size(); i <= e; ++i) {
2944 sys::Path FullPath(Directories[SrcFiles[i].getDirectoryID()]);
2945 bool AppendOk = FullPath.appendComponent(SrcFiles[i].getName());
2946 assert(AppendOk && "Could not append filename to directory!");
2948 Asm->EmitFile(i, FullPath.toString());
2953 // Emit initial sections
2957 /// BeginModule - Emit all Dwarf sections that should come prior to the
2959 void BeginModule(Module *M) {
2963 /// EndModule - Emit all Dwarf sections that should come after the content.
2966 if (!ShouldEmitDwarf()) return;
2968 // Standard sections final addresses.
2969 Asm->SwitchToSection(TAI->getTextSection());
2970 EmitLabel("text_end", 0);
2971 Asm->SwitchToSection(TAI->getDataSection());
2972 EmitLabel("data_end", 0);
2974 // End text sections.
2975 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2976 Asm->SwitchToSection(SectionMap[i]);
2977 EmitLabel("section_end", i);
2980 // Emit common frame information.
2981 EmitCommonDebugFrame();
2983 // Emit function debug frame information
2984 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
2985 E = DebugFrames.end(); I != E; ++I)
2986 EmitFunctionDebugFrame(*I);
2988 // Compute DIE offsets and sizes.
2991 // Emit all the DIEs into a debug info section
2994 // Corresponding abbreviations into a abbrev section.
2995 EmitAbbreviations();
2997 // Emit source line correspondence into a debug line section.
3000 // Emit info into a debug pubnames section.
3001 EmitDebugPubNames();
3003 // Emit info into a debug str section.
3006 // Emit info into a debug loc section.
3009 // Emit info into a debug aranges section.
3012 // Emit info into a debug ranges section.
3015 // Emit info into a debug macinfo section.
3019 /// BeginFunction - Gather pre-function debug information. Assumes being
3020 /// emitted immediately after the function entry point.
3021 void BeginFunction(MachineFunction *MF) {
3024 if (!ShouldEmitDwarf()) return;
3026 // Begin accumulating function debug information.
3027 MMI->BeginFunction(MF);
3029 // Assumes in correct section after the entry point.
3030 EmitLabel("func_begin", ++SubprogramCount);
3032 // Emit label for the implicitly defined dbg.stoppoint at the start of
3034 if (!Lines.empty()) {
3035 const SrcLineInfo &LineInfo = Lines[0];
3036 Asm->printLabel(LineInfo.getLabelID());
3040 /// EndFunction - Gather and emit post-function debug information.
3042 void EndFunction(MachineFunction *MF) {
3043 if (!ShouldEmitDwarf()) return;
3045 // Define end label for subprogram.
3046 EmitLabel("func_end", SubprogramCount);
3048 // Get function line info.
3049 if (!Lines.empty()) {
3050 // Get section line info.
3051 unsigned ID = SectionMap.insert(Asm->CurrentSection_);
3052 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
3053 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
3054 // Append the function info to section info.
3055 SectionLineInfos.insert(SectionLineInfos.end(),
3056 Lines.begin(), Lines.end());
3059 // Construct scopes for subprogram.
3061 ConstructRootDbgScope(RootDbgScope);
3063 // FIXME: This is wrong. We are essentially getting past a problem with
3064 // debug information not being able to handle unreachable blocks that have
3065 // debug information in them. In particular, those unreachable blocks that
3066 // have "region end" info in them. That situation results in the "root
3067 // scope" not being created. If that's the case, then emit a "default"
3068 // scope, i.e., one that encompasses the whole function. This isn't
3069 // desirable. And a better way of handling this (and all of the debugging
3070 // information) needs to be explored.
3071 ConstructDefaultDbgScope(MF);
3073 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
3074 MMI->getFrameMoves()));
3078 delete RootDbgScope;
3079 DbgScopeMap.clear();
3080 RootDbgScope = NULL;
3087 /// ValidDebugInfo - Return true if V represents valid debug info value.
3088 bool ValidDebugInfo(Value *V) {
3093 GlobalVariable *GV = getGlobalVariable(V);
3097 if (GV->getLinkage() != GlobalValue::InternalLinkage
3098 && GV->getLinkage() != GlobalValue::LinkOnceLinkage)
3101 DIDescriptor DI(GV);
3102 // Check current version. Allow Version6 for now.
3103 unsigned Version = DI.getVersion();
3104 if (Version != DIDescriptor::Version7 && Version != DIDescriptor::Version6)
3107 //FIXME - Check individual descriptors.
3111 /// RecordSourceLine - Records location information and associates it with a
3112 /// label. Returns a unique label ID used to generate a label and provide
3113 /// correspondence to the source line list.
3114 unsigned RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
3115 CompileUnit *Unit = DW_CUs[V];
3116 assert (Unit && "Unable to find CompileUnit");
3117 unsigned ID = MMI->NextLabelID();
3118 Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
3122 /// RecordSourceLine - Records location information and associates it with a
3123 /// label. Returns a unique label ID used to generate a label and provide
3124 /// correspondence to the source line list.
3125 unsigned RecordSourceLine(unsigned Line, unsigned Col, unsigned Src) {
3126 unsigned ID = MMI->NextLabelID();
3127 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
3131 unsigned getRecordSourceLineCount() {
3132 return Lines.size();
3135 /// RecordSource - Register a source file with debug info. Returns an source
3137 unsigned RecordSource(const std::string &Directory,
3138 const std::string &File) {
3139 unsigned DID = Directories.insert(Directory);
3140 return SrcFiles.insert(SrcFileInfo(DID,File));
3143 /// RecordRegionStart - Indicate the start of a region.
3145 unsigned RecordRegionStart(GlobalVariable *V) {
3146 DbgScope *Scope = getOrCreateScope(V);
3147 unsigned ID = MMI->NextLabelID();
3148 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
3152 /// RecordRegionEnd - Indicate the end of a region.
3154 unsigned RecordRegionEnd(GlobalVariable *V) {
3155 DbgScope *Scope = getOrCreateScope(V);
3156 unsigned ID = MMI->NextLabelID();
3157 Scope->setEndLabelID(ID);
3161 /// RecordVariable - Indicate the declaration of a local variable.
3163 void RecordVariable(GlobalVariable *GV, unsigned FrameIndex) {
3164 DIDescriptor Desc(GV);
3165 DbgScope *Scope = NULL;
3166 if (Desc.getTag() == DW_TAG_variable) {
3167 // GV is a global variable.
3168 DIGlobalVariable DG(GV);
3169 Scope = getOrCreateScope(DG.getContext().getGV());
3171 // or GV is a local variable.
3173 Scope = getOrCreateScope(DV.getContext().getGV());
3175 assert (Scope && "Unable to find variable' scope");
3176 DbgVariable *DV = new DbgVariable(DIVariable(GV), FrameIndex);
3177 Scope->AddVariable(DV);
3181 //===----------------------------------------------------------------------===//
3182 /// DwarfException - Emits Dwarf exception handling directives.
3184 class DwarfException : public Dwarf {
3187 struct FunctionEHFrameInfo {
3190 unsigned PersonalityIndex;
3192 bool hasLandingPads;
3193 std::vector<MachineMove> Moves;
3194 const Function * function;
3196 FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
3198 const std::vector<MachineMove> &M,
3200 FnName(FN), Number(Num), PersonalityIndex(P),
3201 hasCalls(hC), hasLandingPads(hL), Moves(M), function (f) { }
3204 std::vector<FunctionEHFrameInfo> EHFrames;
3206 /// shouldEmitTable - Per-function flag to indicate if EH tables should
3208 bool shouldEmitTable;
3210 /// shouldEmitMoves - Per-function flag to indicate if frame moves info
3211 /// should be emitted.
3212 bool shouldEmitMoves;
3214 /// shouldEmitTableModule - Per-module flag to indicate if EH tables
3215 /// should be emitted.
3216 bool shouldEmitTableModule;
3218 /// shouldEmitFrameModule - Per-module flag to indicate if frame moves
3219 /// should be emitted.
3220 bool shouldEmitMovesModule;
3222 /// EmitCommonEHFrame - Emit the common eh unwind frame.
3224 void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
3225 // Size and sign of stack growth.
3227 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3228 TargetFrameInfo::StackGrowsUp ?
3229 TD->getPointerSize() : -TD->getPointerSize();
3231 // Begin eh frame section.
3232 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3234 if (!TAI->doesRequireNonLocalEHFrameLabel())
3235 O << TAI->getEHGlobalPrefix();
3236 O << "EH_frame" << Index << ":\n";
3237 EmitLabel("section_eh_frame", Index);
3239 // Define base labels.
3240 EmitLabel("eh_frame_common", Index);
3242 // Define the eh frame length.
3243 EmitDifference("eh_frame_common_end", Index,
3244 "eh_frame_common_begin", Index, true);
3245 Asm->EOL("Length of Common Information Entry");
3248 EmitLabel("eh_frame_common_begin", Index);
3249 Asm->EmitInt32((int)0);
3250 Asm->EOL("CIE Identifier Tag");
3251 Asm->EmitInt8(DW_CIE_VERSION);
3252 Asm->EOL("CIE Version");
3254 // The personality presence indicates that language specific information
3255 // will show up in the eh frame.
3256 Asm->EmitString(Personality ? "zPLR" : "zR");
3257 Asm->EOL("CIE Augmentation");
3259 // Round out reader.
3260 Asm->EmitULEB128Bytes(1);
3261 Asm->EOL("CIE Code Alignment Factor");
3262 Asm->EmitSLEB128Bytes(stackGrowth);
3263 Asm->EOL("CIE Data Alignment Factor");
3264 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
3265 Asm->EOL("CIE Return Address Column");
3267 // If there is a personality, we need to indicate the functions location.
3269 Asm->EmitULEB128Bytes(7);
3270 Asm->EOL("Augmentation Size");
3272 if (TAI->getNeedsIndirectEncoding()) {
3273 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4 | DW_EH_PE_indirect);
3274 Asm->EOL("Personality (pcrel sdata4 indirect)");
3276 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3277 Asm->EOL("Personality (pcrel sdata4)");
3280 PrintRelDirective(true);
3281 O << TAI->getPersonalityPrefix();
3282 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
3283 O << TAI->getPersonalitySuffix();
3284 if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
3285 O << "-" << TAI->getPCSymbol();
3286 Asm->EOL("Personality");
3288 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3289 Asm->EOL("LSDA Encoding (pcrel sdata4)");
3291 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3292 Asm->EOL("FDE Encoding (pcrel sdata4)");
3294 Asm->EmitULEB128Bytes(1);
3295 Asm->EOL("Augmentation Size");
3297 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3298 Asm->EOL("FDE Encoding (pcrel sdata4)");
3301 // Indicate locations of general callee saved registers in frame.
3302 std::vector<MachineMove> Moves;
3303 RI->getInitialFrameState(Moves);
3304 EmitFrameMoves(NULL, 0, Moves, true);
3306 // On Darwin the linker honors the alignment of eh_frame, which means it
3307 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3308 // you get holes which confuse readers of eh_frame.
3309 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3311 EmitLabel("eh_frame_common_end", Index);
3316 /// EmitEHFrame - Emit function exception frame information.
3318 void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
3319 Function::LinkageTypes linkage = EHFrameInfo.function->getLinkage();
3321 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3323 // Externally visible entry into the functions eh frame info.
3324 // If the corresponding function is static, this should not be
3325 // externally visible.
3326 if (linkage != Function::InternalLinkage &&
3327 linkage != Function::PrivateLinkage) {
3328 if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
3329 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
3332 // If corresponding function is weak definition, this should be too.
3333 if ((linkage == Function::WeakLinkage ||
3334 linkage == Function::LinkOnceLinkage) &&
3335 TAI->getWeakDefDirective())
3336 O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
3338 // If there are no calls then you can't unwind. This may mean we can
3339 // omit the EH Frame, but some environments do not handle weak absolute
3341 // If UnwindTablesMandatory is set we cannot do this optimization; the
3342 // unwind info is to be available for non-EH uses.
3343 if (!EHFrameInfo.hasCalls &&
3344 !UnwindTablesMandatory &&
3345 ((linkage != Function::WeakLinkage &&
3346 linkage != Function::LinkOnceLinkage) ||
3347 !TAI->getWeakDefDirective() ||
3348 TAI->getSupportsWeakOmittedEHFrame()))
3350 O << EHFrameInfo.FnName << " = 0\n";
3351 // This name has no connection to the function, so it might get
3352 // dead-stripped when the function is not, erroneously. Prohibit
3353 // dead-stripping unconditionally.
3354 if (const char *UsedDirective = TAI->getUsedDirective())
3355 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3357 O << EHFrameInfo.FnName << ":\n";
3360 EmitDifference("eh_frame_end", EHFrameInfo.Number,
3361 "eh_frame_begin", EHFrameInfo.Number, true);
3362 Asm->EOL("Length of Frame Information Entry");
3364 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
3366 if (TAI->doesRequireNonLocalEHFrameLabel()) {
3367 PrintRelDirective(true, true);
3368 PrintLabelName("eh_frame_begin", EHFrameInfo.Number);
3370 if (!TAI->isAbsoluteEHSectionOffsets())
3371 O << "-EH_frame" << EHFrameInfo.PersonalityIndex;
3373 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
3374 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
3378 Asm->EOL("FDE CIE offset");
3380 EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
3381 Asm->EOL("FDE initial location");
3382 EmitDifference("eh_func_end", EHFrameInfo.Number,
3383 "eh_func_begin", EHFrameInfo.Number, true);
3384 Asm->EOL("FDE address range");
3386 // If there is a personality and landing pads then point to the language
3387 // specific data area in the exception table.
3388 if (EHFrameInfo.PersonalityIndex) {
3389 Asm->EmitULEB128Bytes(4);
3390 Asm->EOL("Augmentation size");
3392 if (EHFrameInfo.hasLandingPads)
3393 EmitReference("exception", EHFrameInfo.Number, true, true);
3395 Asm->EmitInt32((int)0);
3396 Asm->EOL("Language Specific Data Area");
3398 Asm->EmitULEB128Bytes(0);
3399 Asm->EOL("Augmentation size");
3402 // Indicate locations of function specific callee saved registers in
3404 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves, true);
3406 // On Darwin the linker honors the alignment of eh_frame, which means it
3407 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3408 // you get holes which confuse readers of eh_frame.
3409 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3411 EmitLabel("eh_frame_end", EHFrameInfo.Number);
3413 // If the function is marked used, this table should be also. We cannot
3414 // make the mark unconditional in this case, since retaining the table
3415 // also retains the function in this case, and there is code around
3416 // that depends on unused functions (calling undefined externals) being
3417 // dead-stripped to link correctly. Yes, there really is.
3418 if (MMI->getUsedFunctions().count(EHFrameInfo.function))
3419 if (const char *UsedDirective = TAI->getUsedDirective())
3420 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3424 /// EmitExceptionTable - Emit landing pads and actions.
3426 /// The general organization of the table is complex, but the basic concepts
3427 /// are easy. First there is a header which describes the location and
3428 /// organization of the three components that follow.
3429 /// 1. The landing pad site information describes the range of code covered
3430 /// by the try. In our case it's an accumulation of the ranges covered
3431 /// by the invokes in the try. There is also a reference to the landing
3432 /// pad that handles the exception once processed. Finally an index into
3433 /// the actions table.
3434 /// 2. The action table, in our case, is composed of pairs of type ids
3435 /// and next action offset. Starting with the action index from the
3436 /// landing pad site, each type Id is checked for a match to the current
3437 /// exception. If it matches then the exception and type id are passed
3438 /// on to the landing pad. Otherwise the next action is looked up. This
3439 /// chain is terminated with a next action of zero. If no type id is
3440 /// found the the frame is unwound and handling continues.
3441 /// 3. Type id table contains references to all the C++ typeinfo for all
3442 /// catches in the function. This tables is reversed indexed base 1.
3444 /// SharedTypeIds - How many leading type ids two landing pads have in common.
3445 static unsigned SharedTypeIds(const LandingPadInfo *L,
3446 const LandingPadInfo *R) {
3447 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3448 unsigned LSize = LIds.size(), RSize = RIds.size();
3449 unsigned MinSize = LSize < RSize ? LSize : RSize;
3452 for (; Count != MinSize; ++Count)
3453 if (LIds[Count] != RIds[Count])
3459 /// PadLT - Order landing pads lexicographically by type id.
3460 static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
3461 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3462 unsigned LSize = LIds.size(), RSize = RIds.size();
3463 unsigned MinSize = LSize < RSize ? LSize : RSize;
3465 for (unsigned i = 0; i != MinSize; ++i)
3466 if (LIds[i] != RIds[i])
3467 return LIds[i] < RIds[i];
3469 return LSize < RSize;
3473 static inline unsigned getEmptyKey() { return -1U; }
3474 static inline unsigned getTombstoneKey() { return -2U; }
3475 static unsigned getHashValue(const unsigned &Key) { return Key; }
3476 static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
3477 static bool isPod() { return true; }
3480 /// ActionEntry - Structure describing an entry in the actions table.
3481 struct ActionEntry {
3482 int ValueForTypeID; // The value to write - may not be equal to the type id.
3484 struct ActionEntry *Previous;
3487 /// PadRange - Structure holding a try-range and the associated landing pad.
3489 // The index of the landing pad.
3491 // The index of the begin and end labels in the landing pad's label lists.
3492 unsigned RangeIndex;
3495 typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
3497 /// CallSiteEntry - Structure describing an entry in the call-site table.
3498 struct CallSiteEntry {
3499 // The 'try-range' is BeginLabel .. EndLabel.
3500 unsigned BeginLabel; // zero indicates the start of the function.
3501 unsigned EndLabel; // zero indicates the end of the function.
3502 // The landing pad starts at PadLabel.
3503 unsigned PadLabel; // zero indicates that there is no landing pad.
3507 void EmitExceptionTable() {
3508 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
3509 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
3510 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
3511 if (PadInfos.empty()) return;
3513 // Sort the landing pads in order of their type ids. This is used to fold
3514 // duplicate actions.
3515 SmallVector<const LandingPadInfo *, 64> LandingPads;
3516 LandingPads.reserve(PadInfos.size());
3517 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
3518 LandingPads.push_back(&PadInfos[i]);
3519 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
3521 // Negative type ids index into FilterIds, positive type ids index into
3522 // TypeInfos. The value written for a positive type id is just the type
3523 // id itself. For a negative type id, however, the value written is the
3524 // (negative) byte offset of the corresponding FilterIds entry. The byte
3525 // offset is usually equal to the type id, because the FilterIds entries
3526 // are written using a variable width encoding which outputs one byte per
3527 // entry as long as the value written is not too large, but can differ.
3528 // This kind of complication does not occur for positive type ids because
3529 // type infos are output using a fixed width encoding.
3530 // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
3531 SmallVector<int, 16> FilterOffsets;
3532 FilterOffsets.reserve(FilterIds.size());
3534 for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
3535 E = FilterIds.end(); I != E; ++I) {
3536 FilterOffsets.push_back(Offset);
3537 Offset -= TargetAsmInfo::getULEB128Size(*I);
3540 // Compute the actions table and gather the first action index for each
3541 // landing pad site.
3542 SmallVector<ActionEntry, 32> Actions;
3543 SmallVector<unsigned, 64> FirstActions;
3544 FirstActions.reserve(LandingPads.size());
3546 int FirstAction = 0;
3547 unsigned SizeActions = 0;
3548 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3549 const LandingPadInfo *LP = LandingPads[i];
3550 const std::vector<int> &TypeIds = LP->TypeIds;
3551 const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
3552 unsigned SizeSiteActions = 0;
3554 if (NumShared < TypeIds.size()) {
3555 unsigned SizeAction = 0;
3556 ActionEntry *PrevAction = 0;
3559 const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
3560 assert(Actions.size());
3561 PrevAction = &Actions.back();
3562 SizeAction = TargetAsmInfo::getSLEB128Size(PrevAction->NextAction) +
3563 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3564 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
3566 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3567 SizeAction += -PrevAction->NextAction;
3568 PrevAction = PrevAction->Previous;
3572 // Compute the actions.
3573 for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
3574 int TypeID = TypeIds[I];
3575 assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
3576 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
3577 unsigned SizeTypeID = TargetAsmInfo::getSLEB128Size(ValueForTypeID);
3579 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
3580 SizeAction = SizeTypeID + TargetAsmInfo::getSLEB128Size(NextAction);
3581 SizeSiteActions += SizeAction;
3583 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
3584 Actions.push_back(Action);
3586 PrevAction = &Actions.back();
3589 // Record the first action of the landing pad site.
3590 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
3591 } // else identical - re-use previous FirstAction
3593 FirstActions.push_back(FirstAction);
3595 // Compute this sites contribution to size.
3596 SizeActions += SizeSiteActions;
3599 // Compute the call-site table. The entry for an invoke has a try-range
3600 // containing the call, a non-zero landing pad and an appropriate action.
3601 // The entry for an ordinary call has a try-range containing the call and
3602 // zero for the landing pad and the action. Calls marked 'nounwind' have
3603 // no entry and must not be contained in the try-range of any entry - they
3604 // form gaps in the table. Entries must be ordered by try-range address.
3605 SmallVector<CallSiteEntry, 64> CallSites;
3607 RangeMapType PadMap;
3608 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
3609 // by try-range labels when lowered). Ordinary calls do not, so appropriate
3610 // try-ranges for them need be deduced.
3611 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3612 const LandingPadInfo *LandingPad = LandingPads[i];
3613 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
3614 unsigned BeginLabel = LandingPad->BeginLabels[j];
3615 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
3616 PadRange P = { i, j };
3617 PadMap[BeginLabel] = P;
3621 // The end label of the previous invoke or nounwind try-range.
3622 unsigned LastLabel = 0;
3624 // Whether there is a potentially throwing instruction (currently this means
3625 // an ordinary call) between the end of the previous try-range and now.
3626 bool SawPotentiallyThrowing = false;
3628 // Whether the last callsite entry was for an invoke.
3629 bool PreviousIsInvoke = false;
3631 // Visit all instructions in order of address.
3632 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
3634 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
3636 if (!MI->isLabel()) {
3637 SawPotentiallyThrowing |= MI->getDesc().isCall();
3641 unsigned BeginLabel = MI->getOperand(0).getImm();
3642 assert(BeginLabel && "Invalid label!");
3644 // End of the previous try-range?
3645 if (BeginLabel == LastLabel)
3646 SawPotentiallyThrowing = false;
3648 // Beginning of a new try-range?
3649 RangeMapType::iterator L = PadMap.find(BeginLabel);
3650 if (L == PadMap.end())
3651 // Nope, it was just some random label.
3654 PadRange P = L->second;
3655 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
3657 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
3658 "Inconsistent landing pad map!");
3660 // If some instruction between the previous try-range and this one may
3661 // throw, create a call-site entry with no landing pad for the region
3662 // between the try-ranges.
3663 if (SawPotentiallyThrowing) {
3664 CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
3665 CallSites.push_back(Site);
3666 PreviousIsInvoke = false;
3669 LastLabel = LandingPad->EndLabels[P.RangeIndex];
3670 assert(BeginLabel && LastLabel && "Invalid landing pad!");
3672 if (LandingPad->LandingPadLabel) {
3673 // This try-range is for an invoke.
3674 CallSiteEntry Site = {BeginLabel, LastLabel,
3675 LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
3677 // Try to merge with the previous call-site.
3678 if (PreviousIsInvoke) {
3679 CallSiteEntry &Prev = CallSites.back();
3680 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
3681 // Extend the range of the previous entry.
3682 Prev.EndLabel = Site.EndLabel;
3687 // Otherwise, create a new call-site.
3688 CallSites.push_back(Site);
3689 PreviousIsInvoke = true;
3692 PreviousIsInvoke = false;
3696 // If some instruction between the previous try-range and the end of the
3697 // function may throw, create a call-site entry with no landing pad for the
3698 // region following the try-range.
3699 if (SawPotentiallyThrowing) {
3700 CallSiteEntry Site = {LastLabel, 0, 0, 0};
3701 CallSites.push_back(Site);
3707 const unsigned SiteStartSize = sizeof(int32_t); // DW_EH_PE_udata4
3708 const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
3709 const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
3710 unsigned SizeSites = CallSites.size() * (SiteStartSize +
3713 for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
3714 SizeSites += TargetAsmInfo::getULEB128Size(CallSites[i].Action);
3717 const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
3718 unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
3720 unsigned TypeOffset = sizeof(int8_t) + // Call site format
3721 TargetAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
3722 SizeSites + SizeActions + SizeTypes;
3724 unsigned TotalSize = sizeof(int8_t) + // LPStart format
3725 sizeof(int8_t) + // TType format
3726 TargetAsmInfo::getULEB128Size(TypeOffset) + // TType base offset
3729 unsigned SizeAlign = (4 - TotalSize) & 3;
3731 // Begin the exception table.
3732 Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
3733 Asm->EmitAlignment(2, 0, 0, false);
3734 O << "GCC_except_table" << SubprogramCount << ":\n";
3735 for (unsigned i = 0; i != SizeAlign; ++i) {
3737 Asm->EOL("Padding");
3739 EmitLabel("exception", SubprogramCount);
3742 Asm->EmitInt8(DW_EH_PE_omit);
3743 Asm->EOL("LPStart format (DW_EH_PE_omit)");
3744 Asm->EmitInt8(DW_EH_PE_absptr);
3745 Asm->EOL("TType format (DW_EH_PE_absptr)");
3746 Asm->EmitULEB128Bytes(TypeOffset);
3747 Asm->EOL("TType base offset");
3748 Asm->EmitInt8(DW_EH_PE_udata4);
3749 Asm->EOL("Call site format (DW_EH_PE_udata4)");
3750 Asm->EmitULEB128Bytes(SizeSites);
3751 Asm->EOL("Call-site table length");
3753 // Emit the landing pad site information.
3754 for (unsigned i = 0; i < CallSites.size(); ++i) {
3755 CallSiteEntry &S = CallSites[i];
3756 const char *BeginTag;
3757 unsigned BeginNumber;
3759 if (!S.BeginLabel) {
3760 BeginTag = "eh_func_begin";
3761 BeginNumber = SubprogramCount;
3764 BeginNumber = S.BeginLabel;
3767 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
3769 Asm->EOL("Region start");
3772 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
3775 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
3777 Asm->EOL("Region length");
3782 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
3784 Asm->EOL("Landing pad");
3786 Asm->EmitULEB128Bytes(S.Action);
3790 // Emit the actions.
3791 for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
3792 ActionEntry &Action = Actions[I];
3794 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
3795 Asm->EOL("TypeInfo index");
3796 Asm->EmitSLEB128Bytes(Action.NextAction);
3797 Asm->EOL("Next action");
3800 // Emit the type ids.
3801 for (unsigned M = TypeInfos.size(); M; --M) {
3802 GlobalVariable *GV = TypeInfos[M - 1];
3804 PrintRelDirective();
3807 O << Asm->getGlobalLinkName(GV);
3811 Asm->EOL("TypeInfo");
3814 // Emit the filter typeids.
3815 for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
3816 unsigned TypeID = FilterIds[j];
3817 Asm->EmitULEB128Bytes(TypeID);
3818 Asm->EOL("Filter TypeInfo index");
3821 Asm->EmitAlignment(2, 0, 0, false);
3825 //===--------------------------------------------------------------------===//
3826 // Main entry points.
3828 DwarfException(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3829 : Dwarf(OS, A, T, "eh")
3830 , shouldEmitTable(false)
3831 , shouldEmitMoves(false)
3832 , shouldEmitTableModule(false)
3833 , shouldEmitMovesModule(false)
3836 virtual ~DwarfException() {}
3838 /// SetModuleInfo - Set machine module information when it's known that pass
3839 /// manager has created it. Set by the target AsmPrinter.
3840 void SetModuleInfo(MachineModuleInfo *mmi) {
3844 /// BeginModule - Emit all exception information that should come prior to the
3846 void BeginModule(Module *M) {
3850 /// EndModule - Emit all exception information that should come after the
3853 if (shouldEmitMovesModule || shouldEmitTableModule) {
3854 const std::vector<Function *> Personalities = MMI->getPersonalities();
3855 for (unsigned i =0; i < Personalities.size(); ++i)
3856 EmitCommonEHFrame(Personalities[i], i);
3858 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
3859 E = EHFrames.end(); I != E; ++I)
3864 /// BeginFunction - Gather pre-function exception information. Assumes being
3865 /// emitted immediately after the function entry point.
3866 void BeginFunction(MachineFunction *MF) {
3868 shouldEmitTable = shouldEmitMoves = false;
3869 if (MMI && TAI->doesSupportExceptionHandling()) {
3871 // Map all labels and get rid of any dead landing pads.
3872 MMI->TidyLandingPads();
3873 // If any landing pads survive, we need an EH table.
3874 if (MMI->getLandingPads().size())
3875 shouldEmitTable = true;
3877 // See if we need frame move info.
3878 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
3879 shouldEmitMoves = true;
3881 if (shouldEmitMoves || shouldEmitTable)
3882 // Assumes in correct section after the entry point.
3883 EmitLabel("eh_func_begin", ++SubprogramCount);
3885 shouldEmitTableModule |= shouldEmitTable;
3886 shouldEmitMovesModule |= shouldEmitMoves;
3889 /// EndFunction - Gather and emit post-function exception information.
3891 void EndFunction() {
3892 if (shouldEmitMoves || shouldEmitTable) {
3893 EmitLabel("eh_func_end", SubprogramCount);
3894 EmitExceptionTable();
3896 // Save EH frame information
3898 push_back(FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
3900 MMI->getPersonalityIndex(),
3901 MF->getFrameInfo()->hasCalls(),
3902 !MMI->getLandingPads().empty(),
3903 MMI->getFrameMoves(),
3904 MF->getFunction()));
3909 } // End of namespace llvm
3911 //===----------------------------------------------------------------------===//
3913 /// Emit - Print the abbreviation using the specified Dwarf writer.
3915 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
3916 // Emit its Dwarf tag type.
3917 DD.getAsm()->EmitULEB128Bytes(Tag);
3918 DD.getAsm()->EOL(TagString(Tag));
3920 // Emit whether it has children DIEs.
3921 DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
3922 DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
3924 // For each attribute description.
3925 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3926 const DIEAbbrevData &AttrData = Data[i];
3928 // Emit attribute type.
3929 DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
3930 DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
3933 DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
3934 DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
3937 // Mark end of abbreviation.
3938 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
3939 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
3943 void DIEAbbrev::print(std::ostream &O) {
3944 O << "Abbreviation @"
3945 << std::hex << (intptr_t)this << std::dec
3949 << ChildrenString(ChildrenFlag)
3952 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3954 << AttributeString(Data[i].getAttribute())
3956 << FormEncodingString(Data[i].getForm())
3960 void DIEAbbrev::dump() { print(cerr); }
3963 //===----------------------------------------------------------------------===//
3966 void DIEValue::dump() {
3971 //===----------------------------------------------------------------------===//
3973 /// EmitValue - Emit integer of appropriate size.
3975 void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
3977 case DW_FORM_flag: // Fall thru
3978 case DW_FORM_ref1: // Fall thru
3979 case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer); break;
3980 case DW_FORM_ref2: // Fall thru
3981 case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer); break;
3982 case DW_FORM_ref4: // Fall thru
3983 case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer); break;
3984 case DW_FORM_ref8: // Fall thru
3985 case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer); break;
3986 case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
3987 case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
3988 default: assert(0 && "DIE Value form not supported yet"); break;
3992 /// SizeOf - Determine size of integer value in bytes.
3994 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3996 case DW_FORM_flag: // Fall thru
3997 case DW_FORM_ref1: // Fall thru
3998 case DW_FORM_data1: return sizeof(int8_t);
3999 case DW_FORM_ref2: // Fall thru
4000 case DW_FORM_data2: return sizeof(int16_t);
4001 case DW_FORM_ref4: // Fall thru
4002 case DW_FORM_data4: return sizeof(int32_t);
4003 case DW_FORM_ref8: // Fall thru
4004 case DW_FORM_data8: return sizeof(int64_t);
4005 case DW_FORM_udata: return TargetAsmInfo::getULEB128Size(Integer);
4006 case DW_FORM_sdata: return TargetAsmInfo::getSLEB128Size(Integer);
4007 default: assert(0 && "DIE Value form not supported yet"); break;
4012 //===----------------------------------------------------------------------===//
4014 /// EmitValue - Emit string value.
4016 void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
4017 DD.getAsm()->EmitString(String);
4020 //===----------------------------------------------------------------------===//
4022 /// EmitValue - Emit label value.
4024 void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4025 bool IsSmall = Form == DW_FORM_data4;
4026 DD.EmitReference(Label, false, IsSmall);
4029 /// SizeOf - Determine size of label value in bytes.
4031 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4032 if (Form == DW_FORM_data4) return 4;
4033 return DD.getTargetData()->getPointerSize();
4036 //===----------------------------------------------------------------------===//
4038 /// EmitValue - Emit label value.
4040 void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4041 bool IsSmall = Form == DW_FORM_data4;
4042 DD.EmitReference(Label, false, IsSmall);
4045 /// SizeOf - Determine size of label value in bytes.
4047 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4048 if (Form == DW_FORM_data4) return 4;
4049 return DD.getTargetData()->getPointerSize();
4052 //===----------------------------------------------------------------------===//
4054 /// EmitValue - Emit delta value.
4056 void DIESectionOffset::EmitValue(DwarfDebug &DD, unsigned Form) {
4057 bool IsSmall = Form == DW_FORM_data4;
4058 DD.EmitSectionOffset(Label.Tag, Section.Tag,
4059 Label.Number, Section.Number, IsSmall, IsEH, UseSet);
4062 /// SizeOf - Determine size of delta value in bytes.
4064 unsigned DIESectionOffset::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4065 if (Form == DW_FORM_data4) return 4;
4066 return DD.getTargetData()->getPointerSize();
4069 //===----------------------------------------------------------------------===//
4071 /// EmitValue - Emit delta value.
4073 void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
4074 bool IsSmall = Form == DW_FORM_data4;
4075 DD.EmitDifference(LabelHi, LabelLo, IsSmall);
4078 /// SizeOf - Determine size of delta value in bytes.
4080 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4081 if (Form == DW_FORM_data4) return 4;
4082 return DD.getTargetData()->getPointerSize();
4085 //===----------------------------------------------------------------------===//
4087 /// EmitValue - Emit debug information entry offset.
4089 void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
4090 DD.getAsm()->EmitInt32(Entry->getOffset());
4093 //===----------------------------------------------------------------------===//
4095 /// ComputeSize - calculate the size of the block.
4097 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
4099 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4101 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4102 Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
4108 /// EmitValue - Emit block data.
4110 void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
4112 case DW_FORM_block1: DD.getAsm()->EmitInt8(Size); break;
4113 case DW_FORM_block2: DD.getAsm()->EmitInt16(Size); break;
4114 case DW_FORM_block4: DD.getAsm()->EmitInt32(Size); break;
4115 case DW_FORM_block: DD.getAsm()->EmitULEB128Bytes(Size); break;
4116 default: assert(0 && "Improper form for block"); break;
4119 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4121 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4123 Values[i]->EmitValue(DD, AbbrevData[i].getForm());
4127 /// SizeOf - Determine size of block data in bytes.
4129 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4131 case DW_FORM_block1: return Size + sizeof(int8_t);
4132 case DW_FORM_block2: return Size + sizeof(int16_t);
4133 case DW_FORM_block4: return Size + sizeof(int32_t);
4134 case DW_FORM_block: return Size + TargetAsmInfo::getULEB128Size(Size);
4135 default: assert(0 && "Improper form for block"); break;
4140 //===----------------------------------------------------------------------===//
4141 /// DIE Implementation
4144 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4148 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
4150 void DIE::AddSiblingOffset() {
4151 DIEInteger *DI = new DIEInteger(0);
4152 Values.insert(Values.begin(), DI);
4153 Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
4156 /// Profile - Used to gather unique data for the value folding set.
4158 void DIE::Profile(FoldingSetNodeID &ID) {
4161 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4162 ID.AddPointer(Children[i]);
4164 for (unsigned j = 0, M = Values.size(); j < M; ++j)
4165 ID.AddPointer(Values[j]);
4169 void DIE::print(std::ostream &O, unsigned IncIndent) {
4170 static unsigned IndentCount = 0;
4171 IndentCount += IncIndent;
4172 const std::string Indent(IndentCount, ' ');
4173 bool isBlock = Abbrev.getTag() == 0;
4178 << "0x" << std::hex << (intptr_t)this << std::dec
4179 << ", Offset: " << Offset
4180 << ", Size: " << Size
4184 << TagString(Abbrev.getTag())
4186 << ChildrenString(Abbrev.getChildrenFlag());
4188 O << "Size: " << Size;
4192 const SmallVector<DIEAbbrevData, 8> &Data = Abbrev.getData();
4195 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4199 O << AttributeString(Data[i].getAttribute());
4201 O << "Blk[" << i << "]";
4204 << FormEncodingString(Data[i].getForm())
4206 Values[i]->print(O);
4211 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
4212 Children[j]->print(O, 4);
4215 if (!isBlock) O << "\n";
4216 IndentCount -= IncIndent;
4224 //===----------------------------------------------------------------------===//
4225 /// DwarfWriter Implementation
4228 DwarfWriter::DwarfWriter() : ImmutablePass(&ID), DD(NULL), DE(NULL) {
4231 DwarfWriter::~DwarfWriter() {
4236 /// BeginModule - Emit all Dwarf sections that should come prior to the
4238 void DwarfWriter::BeginModule(Module *M,
4239 MachineModuleInfo *MMI,
4240 raw_ostream &OS, AsmPrinter *A,
4241 const TargetAsmInfo *T) {
4242 DE = new DwarfException(OS, A, T);
4243 DD = new DwarfDebug(OS, A, T);
4246 DD->SetDebugInfo(MMI);
4247 DE->SetModuleInfo(MMI);
4250 /// EndModule - Emit all Dwarf sections that should come after the content.
4252 void DwarfWriter::EndModule() {
4257 /// BeginFunction - Gather pre-function debug information. Assumes being
4258 /// emitted immediately after the function entry point.
4259 void DwarfWriter::BeginFunction(MachineFunction *MF) {
4260 DE->BeginFunction(MF);
4261 DD->BeginFunction(MF);
4264 /// EndFunction - Gather and emit post-function debug information.
4266 void DwarfWriter::EndFunction(MachineFunction *MF) {
4267 DD->EndFunction(MF);
4270 if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI())
4271 // Clear function debug information.
4275 /// ValidDebugInfo - Return true if V represents valid debug info value.
4276 bool DwarfWriter::ValidDebugInfo(Value *V) {
4277 return DD && DD->ValidDebugInfo(V);
4280 /// RecordSourceLine - Records location information and associates it with a
4281 /// label. Returns a unique label ID used to generate a label and provide
4282 /// correspondence to the source line list.
4283 unsigned DwarfWriter::RecordSourceLine(unsigned Line, unsigned Col,
4285 return DD->RecordSourceLine(Line, Col, Src);
4288 /// RecordSource - Register a source file with debug info. Returns an source
4290 unsigned DwarfWriter::RecordSource(const std::string &Dir,
4291 const std::string &File) {
4292 return DD->RecordSource(Dir, File);
4295 /// RecordRegionStart - Indicate the start of a region.
4296 unsigned DwarfWriter::RecordRegionStart(GlobalVariable *V) {
4297 return DD->RecordRegionStart(V);
4300 /// RecordRegionEnd - Indicate the end of a region.
4301 unsigned DwarfWriter::RecordRegionEnd(GlobalVariable *V) {
4302 return DD->RecordRegionEnd(V);
4305 /// getRecordSourceLineCount - Count source lines.
4306 unsigned DwarfWriter::getRecordSourceLineCount() {
4307 return DD->getRecordSourceLineCount();
4310 /// RecordVariable - Indicate the declaration of a local variable.
4312 void DwarfWriter::RecordVariable(GlobalVariable *GV, unsigned FrameIndex) {
4313 DD->RecordVariable(GV, FrameIndex);