1 //===-- llvm/CodeGen/DwarfWriter.cpp - Dwarf Framework ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf info into asm files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/DwarfWriter.h"
15 #include "llvm/Module.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Constants.h"
18 #include "llvm/CodeGen/AsmPrinter.h"
19 #include "llvm/CodeGen/MachineModuleInfo.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineLocation.h"
22 #include "llvm/Analysis/DebugInfo.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/Dwarf.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/DataTypes.h"
27 #include "llvm/Support/Mangler.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/System/Path.h"
30 #include "llvm/Target/TargetAsmInfo.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include "llvm/Target/TargetData.h"
33 #include "llvm/Target/TargetFrameInfo.h"
34 #include "llvm/Target/TargetInstrInfo.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/ADT/DenseMap.h"
38 #include "llvm/ADT/FoldingSet.h"
39 #include "llvm/ADT/StringExtras.h"
40 #include "llvm/ADT/StringMap.h"
44 using namespace llvm::dwarf;
46 static RegisterPass<DwarfWriter>
47 X("dwarfwriter", "DWARF Information Writer");
48 char DwarfWriter::ID = 0;
52 //===----------------------------------------------------------------------===//
54 /// Configuration values for initial hash set sizes (log2).
56 static const unsigned InitDiesSetSize = 9; // log2(512)
57 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
58 static const unsigned InitValuesSetSize = 9; // log2(512)
60 //===----------------------------------------------------------------------===//
61 /// Forward declarations.
66 //===----------------------------------------------------------------------===//
69 /// getGlobalVariable - Return either a direct or cast Global value.
71 static GlobalVariable *getGlobalVariable(Value *V) {
72 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
74 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
75 if (CE->getOpcode() == Instruction::BitCast) {
76 return dyn_cast<GlobalVariable>(CE->getOperand(0));
77 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
78 for (unsigned int i=1; i<CE->getNumOperands(); i++) {
79 if (!CE->getOperand(i)->isNullValue())
82 return dyn_cast<GlobalVariable>(CE->getOperand(0));
88 //===----------------------------------------------------------------------===//
89 /// DWLabel - Labels are used to track locations in the assembler file.
90 /// Labels appear in the form @verbatim <prefix><Tag><Number> @endverbatim,
91 /// where the tag is a category of label (Ex. location) and number is a value
92 /// unique in that category.
95 /// Tag - Label category tag. Should always be a staticly declared C string.
99 /// Number - Value to make label unique.
103 DWLabel(const char *T, unsigned N) : Tag(T), Number(N) {}
105 void Profile(FoldingSetNodeID &ID) const {
107 ID.AddInteger(Number);
111 void print(std::ostream *O) const {
114 void print(std::ostream &O) const {
116 if (Number) O << Number;
121 //===----------------------------------------------------------------------===//
122 /// DIEAbbrevData - Dwarf abbreviation data, describes the one attribute of a
123 /// Dwarf abbreviation.
124 class DIEAbbrevData {
126 /// Attribute - Dwarf attribute code.
130 /// Form - Dwarf form code.
135 DIEAbbrevData(unsigned A, unsigned F)
141 unsigned getAttribute() const { return Attribute; }
142 unsigned getForm() const { return Form; }
144 /// Profile - Used to gather unique data for the abbreviation folding set.
146 void Profile(FoldingSetNodeID &ID)const {
147 ID.AddInteger(Attribute);
152 //===----------------------------------------------------------------------===//
153 /// DIEAbbrev - Dwarf abbreviation, describes the organization of a debug
154 /// information object.
155 class DIEAbbrev : public FoldingSetNode {
157 /// Tag - Dwarf tag code.
161 /// Unique number for node.
165 /// ChildrenFlag - Dwarf children flag.
167 unsigned ChildrenFlag;
169 /// Data - Raw data bytes for abbreviation.
171 SmallVector<DIEAbbrevData, 8> Data;
175 DIEAbbrev(unsigned T, unsigned C)
183 unsigned getTag() const { return Tag; }
184 unsigned getNumber() const { return Number; }
185 unsigned getChildrenFlag() const { return ChildrenFlag; }
186 const SmallVector<DIEAbbrevData, 8> &getData() const { return Data; }
187 void setTag(unsigned T) { Tag = T; }
188 void setChildrenFlag(unsigned CF) { ChildrenFlag = CF; }
189 void setNumber(unsigned N) { Number = N; }
191 /// AddAttribute - Adds another set of attribute information to the
193 void AddAttribute(unsigned Attribute, unsigned Form) {
194 Data.push_back(DIEAbbrevData(Attribute, Form));
197 /// AddFirstAttribute - Adds a set of attribute information to the front
198 /// of the abbreviation.
199 void AddFirstAttribute(unsigned Attribute, unsigned Form) {
200 Data.insert(Data.begin(), DIEAbbrevData(Attribute, Form));
203 /// Profile - Used to gather unique data for the abbreviation folding set.
205 void Profile(FoldingSetNodeID &ID) {
207 ID.AddInteger(ChildrenFlag);
209 // For each attribute description.
210 for (unsigned i = 0, N = Data.size(); i < N; ++i)
214 /// Emit - Print the abbreviation using the specified Dwarf writer.
216 void Emit(const DwarfDebug &DD) const;
219 void print(std::ostream *O) {
222 void print(std::ostream &O);
227 //===----------------------------------------------------------------------===//
228 /// DIE - A structured debug information entry. Has an abbreviation which
229 /// describes it's organization.
230 class DIE : public FoldingSetNode {
232 /// Abbrev - Buffer for constructing abbreviation.
236 /// Offset - Offset in debug info section.
240 /// Size - Size of instance + children.
246 std::vector<DIE *> Children;
248 /// Attributes values.
250 SmallVector<DIEValue*, 32> Values;
253 explicit DIE(unsigned Tag)
254 : Abbrev(Tag, DW_CHILDREN_no)
263 DIEAbbrev &getAbbrev() { return Abbrev; }
264 unsigned getAbbrevNumber() const {
265 return Abbrev.getNumber();
267 unsigned getTag() const { return Abbrev.getTag(); }
268 unsigned getOffset() const { return Offset; }
269 unsigned getSize() const { return Size; }
270 const std::vector<DIE *> &getChildren() const { return Children; }
271 SmallVector<DIEValue*, 32> &getValues() { return Values; }
272 void setTag(unsigned Tag) { Abbrev.setTag(Tag); }
273 void setOffset(unsigned O) { Offset = O; }
274 void setSize(unsigned S) { Size = S; }
276 /// AddValue - Add a value and attributes to a DIE.
278 void AddValue(unsigned Attribute, unsigned Form, DIEValue *Value) {
279 Abbrev.AddAttribute(Attribute, Form);
280 Values.push_back(Value);
283 /// SiblingOffset - Return the offset of the debug information entry's
285 unsigned SiblingOffset() const { return Offset + Size; }
287 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
289 void AddSiblingOffset();
291 /// AddChild - Add a child to the DIE.
293 void AddChild(DIE *Child) {
294 Abbrev.setChildrenFlag(DW_CHILDREN_yes);
295 Children.push_back(Child);
298 /// Detach - Detaches objects connected to it after copying.
304 /// Profile - Used to gather unique data for the value folding set.
306 void Profile(FoldingSetNodeID &ID) ;
309 void print(std::ostream *O, unsigned IncIndent = 0) {
310 if (O) print(*O, IncIndent);
312 void print(std::ostream &O, unsigned IncIndent = 0);
317 //===----------------------------------------------------------------------===//
318 /// DIEValue - A debug information entry value.
320 class DIEValue : public FoldingSetNode {
333 /// Type - Type of data stored in the value.
337 explicit DIEValue(unsigned T)
340 virtual ~DIEValue() {}
343 unsigned getType() const { return Type; }
345 // Implement isa/cast/dyncast.
346 static bool classof(const DIEValue *) { return true; }
348 /// EmitValue - Emit value via the Dwarf writer.
350 virtual void EmitValue(DwarfDebug &DD, unsigned Form) = 0;
352 /// SizeOf - Return the size of a value in bytes.
354 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const = 0;
356 /// Profile - Used to gather unique data for the value folding set.
358 virtual void Profile(FoldingSetNodeID &ID) = 0;
361 void print(std::ostream *O) {
364 virtual void print(std::ostream &O) = 0;
369 //===----------------------------------------------------------------------===//
370 /// DWInteger - An integer value DIE.
372 class DIEInteger : public DIEValue {
377 explicit DIEInteger(uint64_t I) : DIEValue(isInteger), Integer(I) {}
379 // Implement isa/cast/dyncast.
380 static bool classof(const DIEInteger *) { return true; }
381 static bool classof(const DIEValue *I) { return I->Type == isInteger; }
383 /// BestForm - Choose the best form for integer.
385 static unsigned BestForm(bool IsSigned, uint64_t Integer) {
387 if ((char)Integer == (signed)Integer) return DW_FORM_data1;
388 if ((short)Integer == (signed)Integer) return DW_FORM_data2;
389 if ((int)Integer == (signed)Integer) return DW_FORM_data4;
391 if ((unsigned char)Integer == Integer) return DW_FORM_data1;
392 if ((unsigned short)Integer == Integer) return DW_FORM_data2;
393 if ((unsigned int)Integer == Integer) return DW_FORM_data4;
395 return DW_FORM_data8;
398 /// EmitValue - Emit integer of appropriate size.
400 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
402 /// SizeOf - Determine size of integer value in bytes.
404 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
406 /// Profile - Used to gather unique data for the value folding set.
408 static void Profile(FoldingSetNodeID &ID, unsigned Integer) {
409 ID.AddInteger(isInteger);
410 ID.AddInteger(Integer);
412 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Integer); }
415 virtual void print(std::ostream &O) {
416 O << "Int: " << (int64_t)Integer
417 << " 0x" << std::hex << Integer << std::dec;
422 //===----------------------------------------------------------------------===//
423 /// DIEString - A string value DIE.
425 class DIEString : public DIEValue {
427 const std::string String;
429 explicit DIEString(const std::string &S) : DIEValue(isString), String(S) {}
431 // Implement isa/cast/dyncast.
432 static bool classof(const DIEString *) { return true; }
433 static bool classof(const DIEValue *S) { return S->Type == isString; }
435 /// EmitValue - Emit string value.
437 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
439 /// SizeOf - Determine size of string value in bytes.
441 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
442 return String.size() + sizeof(char); // sizeof('\0');
445 /// Profile - Used to gather unique data for the value folding set.
447 static void Profile(FoldingSetNodeID &ID, const std::string &String) {
448 ID.AddInteger(isString);
449 ID.AddString(String);
451 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, String); }
454 virtual void print(std::ostream &O) {
455 O << "Str: \"" << String << "\"";
460 //===----------------------------------------------------------------------===//
461 /// DIEDwarfLabel - A Dwarf internal label expression DIE.
463 class DIEDwarfLabel : public DIEValue {
468 explicit DIEDwarfLabel(const DWLabel &L) : DIEValue(isLabel), Label(L) {}
470 // Implement isa/cast/dyncast.
471 static bool classof(const DIEDwarfLabel *) { return true; }
472 static bool classof(const DIEValue *L) { return L->Type == isLabel; }
474 /// EmitValue - Emit label value.
476 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
478 /// SizeOf - Determine size of label value in bytes.
480 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
482 /// Profile - Used to gather unique data for the value folding set.
484 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label) {
485 ID.AddInteger(isLabel);
488 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
491 virtual void print(std::ostream &O) {
499 //===----------------------------------------------------------------------===//
500 /// DIEObjectLabel - A label to an object in code or data.
502 class DIEObjectLabel : public DIEValue {
504 const std::string Label;
506 explicit DIEObjectLabel(const std::string &L)
507 : DIEValue(isAsIsLabel), Label(L) {}
509 // Implement isa/cast/dyncast.
510 static bool classof(const DIEObjectLabel *) { return true; }
511 static bool classof(const DIEValue *L) { return L->Type == isAsIsLabel; }
513 /// EmitValue - Emit label value.
515 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
517 /// SizeOf - Determine size of label value in bytes.
519 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
521 /// Profile - Used to gather unique data for the value folding set.
523 static void Profile(FoldingSetNodeID &ID, const std::string &Label) {
524 ID.AddInteger(isAsIsLabel);
527 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label.c_str()); }
530 virtual void print(std::ostream &O) {
531 O << "Obj: " << Label;
536 //===----------------------------------------------------------------------===//
537 /// DIESectionOffset - A section offset DIE.
539 class DIESectionOffset : public DIEValue {
542 const DWLabel Section;
546 DIESectionOffset(const DWLabel &Lab, const DWLabel &Sec,
547 bool isEH = false, bool useSet = true)
548 : DIEValue(isSectionOffset), Label(Lab), Section(Sec),
549 IsEH(isEH), UseSet(useSet) {}
551 // Implement isa/cast/dyncast.
552 static bool classof(const DIESectionOffset *) { return true; }
553 static bool classof(const DIEValue *D) { return D->Type == isSectionOffset; }
555 /// EmitValue - Emit section offset.
557 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
559 /// SizeOf - Determine size of section offset value in bytes.
561 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
563 /// Profile - Used to gather unique data for the value folding set.
565 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label,
566 const DWLabel &Section) {
567 ID.AddInteger(isSectionOffset);
570 // IsEH and UseSet are specific to the Label/Section that we will emit
571 // the offset for; so Label/Section are enough for uniqueness.
573 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label, Section); }
576 virtual void print(std::ostream &O) {
581 O << "-" << IsEH << "-" << UseSet;
586 //===----------------------------------------------------------------------===//
587 /// DIEDelta - A simple label difference DIE.
589 class DIEDelta : public DIEValue {
591 const DWLabel LabelHi;
592 const DWLabel LabelLo;
594 DIEDelta(const DWLabel &Hi, const DWLabel &Lo)
595 : DIEValue(isDelta), LabelHi(Hi), LabelLo(Lo) {}
597 // Implement isa/cast/dyncast.
598 static bool classof(const DIEDelta *) { return true; }
599 static bool classof(const DIEValue *D) { return D->Type == isDelta; }
601 /// EmitValue - Emit delta value.
603 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
605 /// SizeOf - Determine size of delta value in bytes.
607 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
609 /// Profile - Used to gather unique data for the value folding set.
611 static void Profile(FoldingSetNodeID &ID, const DWLabel &LabelHi,
612 const DWLabel &LabelLo) {
613 ID.AddInteger(isDelta);
617 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, LabelHi, LabelLo); }
620 virtual void print(std::ostream &O) {
629 //===----------------------------------------------------------------------===//
630 /// DIEntry - A pointer to another debug information entry. An instance of this
631 /// class can also be used as a proxy for a debug information entry not yet
632 /// defined (ie. types.)
633 class DIEntry : public DIEValue {
637 explicit DIEntry(DIE *E) : DIEValue(isEntry), Entry(E) {}
639 // Implement isa/cast/dyncast.
640 static bool classof(const DIEntry *) { return true; }
641 static bool classof(const DIEValue *E) { return E->Type == isEntry; }
643 /// EmitValue - Emit debug information entry offset.
645 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
647 /// SizeOf - Determine size of debug information entry in bytes.
649 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
650 return sizeof(int32_t);
653 /// Profile - Used to gather unique data for the value folding set.
655 static void Profile(FoldingSetNodeID &ID, DIE *Entry) {
656 ID.AddInteger(isEntry);
657 ID.AddPointer(Entry);
659 virtual void Profile(FoldingSetNodeID &ID) {
660 ID.AddInteger(isEntry);
663 ID.AddPointer(Entry);
670 virtual void print(std::ostream &O) {
671 O << "Die: 0x" << std::hex << (intptr_t)Entry << std::dec;
676 //===----------------------------------------------------------------------===//
677 /// DIEBlock - A block of values. Primarily used for location expressions.
679 class DIEBlock : public DIEValue, public DIE {
681 unsigned Size; // Size in bytes excluding size header.
691 // Implement isa/cast/dyncast.
692 static bool classof(const DIEBlock *) { return true; }
693 static bool classof(const DIEValue *E) { return E->Type == isBlock; }
695 /// ComputeSize - calculate the size of the block.
697 unsigned ComputeSize(DwarfDebug &DD);
699 /// BestForm - Choose the best form for data.
701 unsigned BestForm() const {
702 if ((unsigned char)Size == Size) return DW_FORM_block1;
703 if ((unsigned short)Size == Size) return DW_FORM_block2;
704 if ((unsigned int)Size == Size) return DW_FORM_block4;
705 return DW_FORM_block;
708 /// EmitValue - Emit block data.
710 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
712 /// SizeOf - Determine size of block data in bytes.
714 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
717 /// Profile - Used to gather unique data for the value folding set.
719 virtual void Profile(FoldingSetNodeID &ID) {
720 ID.AddInteger(isBlock);
725 virtual void print(std::ostream &O) {
732 //===----------------------------------------------------------------------===//
733 /// CompileUnit - This dwarf writer support class manages information associate
734 /// with a source file.
737 /// ID - File identifier for source.
741 /// Die - Compile unit debug information entry.
745 /// GVToDieMap - Tracks the mapping of unit level debug informaton
746 /// variables to debug information entries.
747 std::map<GlobalVariable *, DIE *> GVToDieMap;
749 /// GVToDIEntryMap - Tracks the mapping of unit level debug informaton
750 /// descriptors to debug information entries using a DIEntry proxy.
751 std::map<GlobalVariable *, DIEntry *> GVToDIEntryMap;
753 /// Globals - A map of globally visible named entities for this unit.
755 std::map<std::string, DIE *> Globals;
757 /// DiesSet - Used to uniquely define dies within the compile unit.
759 FoldingSet<DIE> DiesSet;
762 CompileUnit(unsigned I, DIE *D)
763 : ID(I), Die(D), GVToDieMap(),
764 GVToDIEntryMap(), Globals(), DiesSet(InitDiesSetSize)
772 unsigned getID() const { return ID; }
773 DIE* getDie() const { return Die; }
774 std::map<std::string, DIE *> &getGlobals() { return Globals; }
776 /// hasContent - Return true if this compile unit has something to write out.
778 bool hasContent() const {
779 return !Die->getChildren().empty();
782 /// AddGlobal - Add a new global entity to the compile unit.
784 void AddGlobal(const std::string &Name, DIE *Die) {
788 /// getDieMapSlotFor - Returns the debug information entry map slot for the
789 /// specified debug variable.
790 DIE *&getDieMapSlotFor(GlobalVariable *GV) {
791 return GVToDieMap[GV];
794 /// getDIEntrySlotFor - Returns the debug information entry proxy slot for the
795 /// specified debug variable.
796 DIEntry *&getDIEntrySlotFor(GlobalVariable *GV) {
797 return GVToDIEntryMap[GV];
800 /// AddDie - Adds or interns the DIE to the compile unit.
802 DIE *AddDie(DIE &Buffer) {
806 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
809 Die = new DIE(Buffer);
810 DiesSet.InsertNode(Die, Where);
811 this->Die->AddChild(Die);
819 //===----------------------------------------------------------------------===//
820 /// Dwarf - Emits general Dwarf directives.
824 //===--------------------------------------------------------------------===//
825 // Core attributes used by the Dwarf writer.
829 /// O - Stream to .s file.
833 /// Asm - Target of Dwarf emission.
837 /// TAI - Target asm information.
838 const TargetAsmInfo *TAI;
840 /// TD - Target data.
841 const TargetData *TD;
843 /// RI - Register Information.
844 const TargetRegisterInfo *RI;
846 /// M - Current module.
850 /// MF - Current machine function.
854 /// MMI - Collected machine module information.
856 MachineModuleInfo *MMI;
858 /// SubprogramCount - The running count of functions being compiled.
860 unsigned SubprogramCount;
862 /// Flavor - A unique string indicating what dwarf producer this is, used to
864 const char * const Flavor;
867 Dwarf(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T,
872 , TD(Asm->TM.getTargetData())
873 , RI(Asm->TM.getRegisterInfo())
884 //===--------------------------------------------------------------------===//
887 AsmPrinter *getAsm() const { return Asm; }
888 MachineModuleInfo *getMMI() const { return MMI; }
889 const TargetAsmInfo *getTargetAsmInfo() const { return TAI; }
890 const TargetData *getTargetData() const { return TD; }
892 void PrintRelDirective(bool Force32Bit = false, bool isInSection = false)
894 if (isInSection && TAI->getDwarfSectionOffsetDirective())
895 O << TAI->getDwarfSectionOffsetDirective();
896 else if (Force32Bit || TD->getPointerSize() == sizeof(int32_t))
897 O << TAI->getData32bitsDirective();
899 O << TAI->getData64bitsDirective();
902 /// PrintLabelName - Print label name in form used by Dwarf writer.
904 void PrintLabelName(DWLabel Label) const {
905 PrintLabelName(Label.Tag, Label.Number);
907 void PrintLabelName(const char *Tag, unsigned Number) const {
908 O << TAI->getPrivateGlobalPrefix() << Tag;
909 if (Number) O << Number;
912 void PrintLabelName(const char *Tag, unsigned Number,
913 const char *Suffix) const {
914 O << TAI->getPrivateGlobalPrefix() << Tag;
915 if (Number) O << Number;
919 /// EmitLabel - Emit location label for internal use by Dwarf.
921 void EmitLabel(DWLabel Label) const {
922 EmitLabel(Label.Tag, Label.Number);
924 void EmitLabel(const char *Tag, unsigned Number) const {
925 PrintLabelName(Tag, Number);
929 /// EmitReference - Emit a reference to a label.
931 void EmitReference(DWLabel Label, bool IsPCRelative = false,
932 bool Force32Bit = false) const {
933 EmitReference(Label.Tag, Label.Number, IsPCRelative, Force32Bit);
935 void EmitReference(const char *Tag, unsigned Number,
936 bool IsPCRelative = false, bool Force32Bit = false) const {
937 PrintRelDirective(Force32Bit);
938 PrintLabelName(Tag, Number);
940 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
942 void EmitReference(const std::string &Name, bool IsPCRelative = false,
943 bool Force32Bit = false) const {
944 PrintRelDirective(Force32Bit);
948 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
951 /// EmitDifference - Emit the difference between two labels. Some
952 /// assemblers do not behave with absolute expressions with data directives,
953 /// so there is an option (needsSet) to use an intermediary set expression.
954 void EmitDifference(DWLabel LabelHi, DWLabel LabelLo,
955 bool IsSmall = false) {
956 EmitDifference(LabelHi.Tag, LabelHi.Number,
957 LabelLo.Tag, LabelLo.Number,
960 void EmitDifference(const char *TagHi, unsigned NumberHi,
961 const char *TagLo, unsigned NumberLo,
962 bool IsSmall = false) {
963 if (TAI->needsSet()) {
965 PrintLabelName("set", SetCounter, Flavor);
967 PrintLabelName(TagHi, NumberHi);
969 PrintLabelName(TagLo, NumberLo);
972 PrintRelDirective(IsSmall);
973 PrintLabelName("set", SetCounter, Flavor);
976 PrintRelDirective(IsSmall);
978 PrintLabelName(TagHi, NumberHi);
980 PrintLabelName(TagLo, NumberLo);
984 void EmitSectionOffset(const char* Label, const char* Section,
985 unsigned LabelNumber, unsigned SectionNumber,
986 bool IsSmall = false, bool isEH = false,
987 bool useSet = true) {
988 bool printAbsolute = false;
990 printAbsolute = TAI->isAbsoluteEHSectionOffsets();
992 printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
994 if (TAI->needsSet() && useSet) {
996 PrintLabelName("set", SetCounter, Flavor);
998 PrintLabelName(Label, LabelNumber);
1000 if (!printAbsolute) {
1002 PrintLabelName(Section, SectionNumber);
1006 PrintRelDirective(IsSmall);
1008 PrintLabelName("set", SetCounter, Flavor);
1011 PrintRelDirective(IsSmall, true);
1013 PrintLabelName(Label, LabelNumber);
1015 if (!printAbsolute) {
1017 PrintLabelName(Section, SectionNumber);
1022 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
1024 void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
1025 const std::vector<MachineMove> &Moves, bool isEH) {
1027 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
1028 TargetFrameInfo::StackGrowsUp ?
1029 TD->getPointerSize() : -TD->getPointerSize();
1030 bool IsLocal = BaseLabel && strcmp(BaseLabel, "label") == 0;
1032 for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
1033 const MachineMove &Move = Moves[i];
1034 unsigned LabelID = Move.getLabelID();
1037 LabelID = MMI->MappedLabel(LabelID);
1039 // Throw out move if the label is invalid.
1040 if (!LabelID) continue;
1043 const MachineLocation &Dst = Move.getDestination();
1044 const MachineLocation &Src = Move.getSource();
1046 // Advance row if new location.
1047 if (BaseLabel && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
1048 Asm->EmitInt8(DW_CFA_advance_loc4);
1049 Asm->EOL("DW_CFA_advance_loc4");
1050 EmitDifference("label", LabelID, BaseLabel, BaseLabelID, true);
1053 BaseLabelID = LabelID;
1054 BaseLabel = "label";
1058 // If advancing cfa.
1059 if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
1061 if (Src.getReg() == MachineLocation::VirtualFP) {
1062 Asm->EmitInt8(DW_CFA_def_cfa_offset);
1063 Asm->EOL("DW_CFA_def_cfa_offset");
1065 Asm->EmitInt8(DW_CFA_def_cfa);
1066 Asm->EOL("DW_CFA_def_cfa");
1067 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getReg(), isEH));
1068 Asm->EOL("Register");
1071 int Offset = -Src.getOffset();
1073 Asm->EmitULEB128Bytes(Offset);
1076 assert(0 && "Machine move no supported yet.");
1078 } else if (Src.isReg() &&
1079 Src.getReg() == MachineLocation::VirtualFP) {
1081 Asm->EmitInt8(DW_CFA_def_cfa_register);
1082 Asm->EOL("DW_CFA_def_cfa_register");
1083 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getReg(), isEH));
1084 Asm->EOL("Register");
1086 assert(0 && "Machine move no supported yet.");
1089 unsigned Reg = RI->getDwarfRegNum(Src.getReg(), isEH);
1090 int Offset = Dst.getOffset() / stackGrowth;
1093 Asm->EmitInt8(DW_CFA_offset_extended_sf);
1094 Asm->EOL("DW_CFA_offset_extended_sf");
1095 Asm->EmitULEB128Bytes(Reg);
1097 Asm->EmitSLEB128Bytes(Offset);
1099 } else if (Reg < 64) {
1100 Asm->EmitInt8(DW_CFA_offset + Reg);
1102 Asm->EOL("DW_CFA_offset + Reg (" + utostr(Reg) + ")");
1105 Asm->EmitULEB128Bytes(Offset);
1108 Asm->EmitInt8(DW_CFA_offset_extended);
1109 Asm->EOL("DW_CFA_offset_extended");
1110 Asm->EmitULEB128Bytes(Reg);
1112 Asm->EmitULEB128Bytes(Offset);
1121 //===----------------------------------------------------------------------===//
1122 /// SrcLineInfo - This class is used to record source line correspondence.
1125 unsigned Line; // Source line number.
1126 unsigned Column; // Source column.
1127 unsigned SourceID; // Source ID number.
1128 unsigned LabelID; // Label in code ID number.
1130 SrcLineInfo(unsigned L, unsigned C, unsigned S, unsigned I)
1131 : Line(L), Column(C), SourceID(S), LabelID(I) {}
1134 unsigned getLine() const { return Line; }
1135 unsigned getColumn() const { return Column; }
1136 unsigned getSourceID() const { return SourceID; }
1137 unsigned getLabelID() const { return LabelID; }
1140 //===----------------------------------------------------------------------===//
1141 /// DbgVariable - This class is used to track local variable information.
1144 DIVariable Var; // Variable Descriptor.
1145 unsigned FrameIndex; // Variable frame index.
1147 DbgVariable(DIVariable V, unsigned I) : Var(V), FrameIndex(I) {}
1150 DIVariable getVariable() const { return Var; }
1151 unsigned getFrameIndex() const { return FrameIndex; }
1154 //===----------------------------------------------------------------------===//
1155 /// DbgScope - This class is used to track scope information.
1158 DbgScope *Parent; // Parent to this scope.
1159 DIDescriptor Desc; // Debug info descriptor for scope.
1160 // Either subprogram or block.
1161 unsigned StartLabelID; // Label ID of the beginning of scope.
1162 unsigned EndLabelID; // Label ID of the end of scope.
1163 SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope.
1164 SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
1166 DbgScope(DbgScope *P, DIDescriptor D)
1167 : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0), Scopes(), Variables()
1170 for (unsigned i = 0, N = Scopes.size(); i < N; ++i) delete Scopes[i];
1171 for (unsigned j = 0, M = Variables.size(); j < M; ++j) delete Variables[j];
1175 DbgScope *getParent() const { return Parent; }
1176 DIDescriptor getDesc() const { return Desc; }
1177 unsigned getStartLabelID() const { return StartLabelID; }
1178 unsigned getEndLabelID() const { return EndLabelID; }
1179 SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
1180 SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
1181 void setStartLabelID(unsigned S) { StartLabelID = S; }
1182 void setEndLabelID(unsigned E) { EndLabelID = E; }
1184 /// AddScope - Add a scope to the scope.
1186 void AddScope(DbgScope *S) { Scopes.push_back(S); }
1188 /// AddVariable - Add a variable to the scope.
1190 void AddVariable(DbgVariable *V) { Variables.push_back(V); }
1193 //===----------------------------------------------------------------------===//
1194 /// DwarfDebug - Emits Dwarf debug directives.
1196 class DwarfDebug : public Dwarf {
1197 //===--------------------------------------------------------------------===//
1198 // Attributes used to construct specific Dwarf sections.
1201 /// CompileUnitMap - A map of global variables representing compile units to
1203 DenseMap<Value *, CompileUnit *> CompileUnitMap;
1205 /// CompileUnits - All the compile units in this module.
1207 SmallVector<CompileUnit *, 8> CompileUnits;
1209 /// MainCU - Some platform prefers one compile unit per .o file. In such
1210 /// cases, all dies are inserted in MainCU.
1211 CompileUnit *MainCU;
1213 /// AbbreviationsSet - Used to uniquely define abbreviations.
1215 FoldingSet<DIEAbbrev> AbbreviationsSet;
1217 /// Abbreviations - A list of all the unique abbreviations in use.
1219 std::vector<DIEAbbrev *> Abbreviations;
1221 /// DirectoryIdMap - Directory name to directory id map.
1223 StringMap<unsigned> DirectoryIdMap;
1225 /// DirectoryNames - A list of directory names.
1226 SmallVector<std::string, 8> DirectoryNames;
1228 /// SourceFileIdMap - Source file name to source file id map.
1230 StringMap<unsigned> SourceFileIdMap;
1232 /// SourceFileNames - A list of source file names.
1233 SmallVector<std::string, 8> SourceFileNames;
1235 /// SourceIdMap - Source id map, i.e. pair of directory id and source file
1236 /// id mapped to a unique id.
1237 DenseMap<std::pair<unsigned, unsigned>, unsigned> SourceIdMap;
1239 /// SourceIds - Reverse map from source id to directory id + file id pair.
1241 SmallVector<std::pair<unsigned, unsigned>, 8> SourceIds;
1243 /// Lines - List of of source line correspondence.
1244 std::vector<SrcLineInfo> Lines;
1246 /// ValuesSet - Used to uniquely define values.
1248 FoldingSet<DIEValue> ValuesSet;
1250 /// Values - A list of all the unique values in use.
1252 std::vector<DIEValue *> Values;
1254 /// StringPool - A UniqueVector of strings used by indirect references.
1256 UniqueVector<std::string> StringPool;
1258 /// SectionMap - Provides a unique id per text section.
1260 UniqueVector<const Section*> SectionMap;
1262 /// SectionSourceLines - Tracks line numbers per text section.
1264 std::vector<std::vector<SrcLineInfo> > SectionSourceLines;
1266 /// didInitial - Flag to indicate if initial emission has been done.
1270 /// shouldEmit - Flag to indicate if debug information should be emitted.
1274 // RootDbgScope - Top level scope for the current function.
1276 DbgScope *RootDbgScope;
1278 // DbgScopeMap - Tracks the scopes in the current function.
1279 DenseMap<GlobalVariable *, DbgScope *> DbgScopeMap;
1281 struct FunctionDebugFrameInfo {
1283 std::vector<MachineMove> Moves;
1285 FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
1286 Number(Num), Moves(M) { }
1289 std::vector<FunctionDebugFrameInfo> DebugFrames;
1293 /// ShouldEmitDwarfDebug - Returns true if Dwarf debugging declarations should
1296 bool ShouldEmitDwarfDebug() const { return shouldEmit; }
1298 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1300 void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1301 // Profile the node so that we can make it unique.
1302 FoldingSetNodeID ID;
1305 // Check the set for priors.
1306 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1308 // If it's newly added.
1309 if (InSet == &Abbrev) {
1310 // Add to abbreviation list.
1311 Abbreviations.push_back(&Abbrev);
1312 // Assign the vector position + 1 as its number.
1313 Abbrev.setNumber(Abbreviations.size());
1315 // Assign existing abbreviation number.
1316 Abbrev.setNumber(InSet->getNumber());
1320 /// NewString - Add a string to the constant pool and returns a label.
1322 DWLabel NewString(const std::string &String) {
1323 unsigned StringID = StringPool.insert(String);
1324 return DWLabel("string", StringID);
1327 /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1329 DIEntry *NewDIEntry(DIE *Entry = NULL) {
1333 FoldingSetNodeID ID;
1334 DIEntry::Profile(ID, Entry);
1336 Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1338 if (Value) return Value;
1340 Value = new DIEntry(Entry);
1341 ValuesSet.InsertNode(Value, Where);
1343 Value = new DIEntry(Entry);
1346 Values.push_back(Value);
1350 /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1352 void SetDIEntry(DIEntry *Value, DIE *Entry) {
1353 Value->Entry = Entry;
1354 // Add to values set if not already there. If it is, we merely have a
1355 // duplicate in the values list (no harm.)
1356 ValuesSet.GetOrInsertNode(Value);
1359 /// AddUInt - Add an unsigned integer attribute data and value.
1361 void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1362 if (!Form) Form = DIEInteger::BestForm(false, Integer);
1364 FoldingSetNodeID ID;
1365 DIEInteger::Profile(ID, Integer);
1367 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1369 Value = new DIEInteger(Integer);
1370 ValuesSet.InsertNode(Value, Where);
1371 Values.push_back(Value);
1374 Die->AddValue(Attribute, Form, Value);
1377 /// AddSInt - Add an signed integer attribute data and value.
1379 void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1380 if (!Form) Form = DIEInteger::BestForm(true, Integer);
1382 FoldingSetNodeID ID;
1383 DIEInteger::Profile(ID, (uint64_t)Integer);
1385 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1387 Value = new DIEInteger(Integer);
1388 ValuesSet.InsertNode(Value, Where);
1389 Values.push_back(Value);
1392 Die->AddValue(Attribute, Form, Value);
1395 /// AddString - Add a string attribute data and value.
1397 void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1398 const std::string &String) {
1399 FoldingSetNodeID ID;
1400 DIEString::Profile(ID, String);
1402 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1404 Value = new DIEString(String);
1405 ValuesSet.InsertNode(Value, Where);
1406 Values.push_back(Value);
1409 Die->AddValue(Attribute, Form, Value);
1412 /// AddLabel - Add a Dwarf label attribute data and value.
1414 void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1415 const DWLabel &Label) {
1416 FoldingSetNodeID ID;
1417 DIEDwarfLabel::Profile(ID, Label);
1419 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1421 Value = new DIEDwarfLabel(Label);
1422 ValuesSet.InsertNode(Value, Where);
1423 Values.push_back(Value);
1426 Die->AddValue(Attribute, Form, Value);
1429 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1431 void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1432 const std::string &Label) {
1433 FoldingSetNodeID ID;
1434 DIEObjectLabel::Profile(ID, Label);
1436 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1438 Value = new DIEObjectLabel(Label);
1439 ValuesSet.InsertNode(Value, Where);
1440 Values.push_back(Value);
1443 Die->AddValue(Attribute, Form, Value);
1446 /// AddSectionOffset - Add a section offset label attribute data and value.
1448 void AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
1449 const DWLabel &Label, const DWLabel &Section,
1450 bool isEH = false, bool useSet = true) {
1451 FoldingSetNodeID ID;
1452 DIESectionOffset::Profile(ID, Label, Section);
1454 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1456 Value = new DIESectionOffset(Label, Section, isEH, useSet);
1457 ValuesSet.InsertNode(Value, Where);
1458 Values.push_back(Value);
1461 Die->AddValue(Attribute, Form, Value);
1464 /// AddDelta - Add a label delta attribute data and value.
1466 void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1467 const DWLabel &Hi, const DWLabel &Lo) {
1468 FoldingSetNodeID ID;
1469 DIEDelta::Profile(ID, Hi, Lo);
1471 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1473 Value = new DIEDelta(Hi, Lo);
1474 ValuesSet.InsertNode(Value, Where);
1475 Values.push_back(Value);
1478 Die->AddValue(Attribute, Form, Value);
1481 /// AddDIEntry - Add a DIE attribute data and value.
1483 void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1484 Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1487 /// AddBlock - Add block data.
1489 void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1490 Block->ComputeSize(*this);
1491 FoldingSetNodeID ID;
1494 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1497 ValuesSet.InsertNode(Value, Where);
1498 Values.push_back(Value);
1500 // Already exists, reuse the previous one.
1502 Block = cast<DIEBlock>(Value);
1505 Die->AddValue(Attribute, Block->BestForm(), Value);
1510 /// AddSourceLine - Add location information to specified debug information
1512 void AddSourceLine(DIE *Die, const DIVariable *V) {
1513 unsigned FileID = 0;
1514 unsigned Line = V->getLineNumber();
1515 CompileUnit *Unit = FindCompileUnit(V->getCompileUnit());
1516 FileID = Unit->getID();
1517 assert (FileID && "Invalid file id");
1518 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1519 AddUInt(Die, DW_AT_decl_line, 0, Line);
1522 /// AddSourceLine - Add location information to specified debug information
1524 void AddSourceLine(DIE *Die, const DIGlobal *G) {
1525 unsigned FileID = 0;
1526 unsigned Line = G->getLineNumber();
1527 CompileUnit *Unit = FindCompileUnit(G->getCompileUnit());
1528 FileID = Unit->getID();
1529 assert (FileID && "Invalid file id");
1530 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1531 AddUInt(Die, DW_AT_decl_line, 0, Line);
1534 void AddSourceLine(DIE *Die, const DIType *Ty) {
1535 unsigned FileID = 0;
1536 unsigned Line = Ty->getLineNumber();
1537 DICompileUnit CU = Ty->getCompileUnit();
1540 CompileUnit *Unit = FindCompileUnit(CU);
1541 FileID = Unit->getID();
1542 assert (FileID && "Invalid file id");
1543 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1544 AddUInt(Die, DW_AT_decl_line, 0, Line);
1547 /// AddAddress - Add an address attribute to a die based on the location
1549 void AddAddress(DIE *Die, unsigned Attribute,
1550 const MachineLocation &Location) {
1551 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
1552 DIEBlock *Block = new DIEBlock();
1554 if (Location.isReg()) {
1556 AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1558 AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1559 AddUInt(Block, 0, DW_FORM_udata, Reg);
1563 AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1565 AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1566 AddUInt(Block, 0, DW_FORM_udata, Reg);
1568 AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1571 AddBlock(Die, Attribute, 0, Block);
1574 /// AddType - Add a new type attribute to the specified entity.
1575 void AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
1579 // Check for pre-existence.
1580 DIEntry *&Slot = DW_Unit->getDIEntrySlotFor(Ty.getGV());
1581 // If it exists then use the existing value.
1583 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1588 Slot = NewDIEntry();
1591 DIE Buffer(DW_TAG_base_type);
1592 if (Ty.isBasicType(Ty.getTag()))
1593 ConstructTypeDIE(DW_Unit, Buffer, DIBasicType(Ty.getGV()));
1594 else if (Ty.isDerivedType(Ty.getTag()))
1595 ConstructTypeDIE(DW_Unit, Buffer, DIDerivedType(Ty.getGV()));
1597 assert(Ty.isCompositeType(Ty.getTag()) && "Unknown kind of DIType");
1598 ConstructTypeDIE(DW_Unit, Buffer, DICompositeType(Ty.getGV()));
1601 // Add debug information entry to entity and appropriate context.
1603 DIDescriptor Context = Ty.getContext();
1604 if (!Context.isNull())
1605 Die = DW_Unit->getDieMapSlotFor(Context.getGV());
1608 DIE *Child = new DIE(Buffer);
1609 Die->AddChild(Child);
1611 SetDIEntry(Slot, Child);
1613 Die = DW_Unit->AddDie(Buffer);
1614 SetDIEntry(Slot, Die);
1617 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1620 /// ConstructTypeDIE - Construct basic type die from DIBasicType.
1621 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1624 // Get core information.
1625 const std::string &Name = BTy.getName();
1626 Buffer.setTag(DW_TAG_base_type);
1627 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BTy.getEncoding());
1628 // Add name if not anonymous or intermediate type.
1630 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1631 uint64_t Size = BTy.getSizeInBits() >> 3;
1632 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1635 /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
1636 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1637 DIDerivedType DTy) {
1639 // Get core information.
1640 const std::string &Name = DTy.getName();
1641 uint64_t Size = DTy.getSizeInBits() >> 3;
1642 unsigned Tag = DTy.getTag();
1643 // FIXME - Workaround for templates.
1644 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1647 // Map to main type, void will not have a type.
1648 DIType FromTy = DTy.getTypeDerivedFrom();
1649 AddType(DW_Unit, &Buffer, FromTy);
1651 // Add name if not anonymous or intermediate type.
1653 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1655 // Add size if non-zero (derived types might be zero-sized.)
1657 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1659 // Add source line info if available and TyDesc is not a forward
1661 if (!DTy.isForwardDecl())
1662 AddSourceLine(&Buffer, &DTy);
1665 /// ConstructTypeDIE - Construct type DIE from DICompositeType.
1666 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1667 DICompositeType CTy) {
1669 // Get core information.
1670 const std::string &Name = CTy.getName();
1671 uint64_t Size = CTy.getSizeInBits() >> 3;
1672 unsigned Tag = CTy.getTag();
1675 case DW_TAG_vector_type:
1676 case DW_TAG_array_type:
1677 ConstructArrayTypeDIE(DW_Unit, Buffer, &CTy);
1679 case DW_TAG_enumeration_type:
1681 DIArray Elements = CTy.getTypeArray();
1682 // Add enumerators to enumeration type.
1683 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1684 DIE *ElemDie = NULL;
1685 DIEnumerator Enum(Elements.getElement(i).getGV());
1686 ElemDie = ConstructEnumTypeDIE(DW_Unit, &Enum);
1687 Buffer.AddChild(ElemDie);
1691 case DW_TAG_subroutine_type:
1693 // Add prototype flag.
1694 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1695 DIArray Elements = CTy.getTypeArray();
1697 DIDescriptor RTy = Elements.getElement(0);
1698 AddType(DW_Unit, &Buffer, DIType(RTy.getGV()));
1701 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1702 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1703 DIDescriptor Ty = Elements.getElement(i);
1704 AddType(DW_Unit, Arg, DIType(Ty.getGV()));
1705 Buffer.AddChild(Arg);
1709 case DW_TAG_structure_type:
1710 case DW_TAG_union_type:
1712 // Add elements to structure type.
1713 DIArray Elements = CTy.getTypeArray();
1715 // A forward struct declared type may not have elements available.
1716 if (Elements.isNull())
1719 // Add elements to structure type.
1720 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1721 DIDescriptor Element = Elements.getElement(i);
1722 DIE *ElemDie = NULL;
1723 if (Element.getTag() == dwarf::DW_TAG_subprogram)
1724 ElemDie = CreateSubprogramDIE(DW_Unit,
1725 DISubprogram(Element.getGV()));
1726 else if (Element.getTag() == dwarf::DW_TAG_variable) // ???
1727 ElemDie = CreateGlobalVariableDIE(DW_Unit,
1728 DIGlobalVariable(Element.getGV()));
1730 ElemDie = CreateMemberDIE(DW_Unit,
1731 DIDerivedType(Element.getGV()));
1732 Buffer.AddChild(ElemDie);
1734 unsigned RLang = CTy.getRunTimeLang();
1736 AddUInt(&Buffer, DW_AT_APPLE_runtime_class, DW_FORM_data1, RLang);
1743 // Add name if not anonymous or intermediate type.
1745 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1747 if (Tag == DW_TAG_enumeration_type || Tag == DW_TAG_structure_type
1748 || Tag == DW_TAG_union_type) {
1749 // Add size if non-zero (derived types might be zero-sized.)
1751 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1753 // Add zero size if it is not a forward declaration.
1754 if (CTy.isForwardDecl())
1755 AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
1757 AddUInt(&Buffer, DW_AT_byte_size, 0, 0);
1760 // Add source line info if available.
1761 if (!CTy.isForwardDecl())
1762 AddSourceLine(&Buffer, &CTy);
1766 /// ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
1767 void ConstructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1768 int64_t L = SR.getLo();
1769 int64_t H = SR.getHi();
1770 DIE *DW_Subrange = new DIE(DW_TAG_subrange_type);
1772 AddDIEntry(DW_Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1774 AddSInt(DW_Subrange, DW_AT_lower_bound, 0, L);
1775 AddSInt(DW_Subrange, DW_AT_upper_bound, 0, H);
1777 Buffer.AddChild(DW_Subrange);
1780 /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
1781 void ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1782 DICompositeType *CTy) {
1783 Buffer.setTag(DW_TAG_array_type);
1784 if (CTy->getTag() == DW_TAG_vector_type)
1785 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1787 // Emit derived type.
1788 AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
1789 DIArray Elements = CTy->getTypeArray();
1791 // Construct an anonymous type for index type.
1792 DIE IdxBuffer(DW_TAG_base_type);
1793 AddUInt(&IdxBuffer, DW_AT_byte_size, 0, sizeof(int32_t));
1794 AddUInt(&IdxBuffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
1795 DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
1797 // Add subranges to array type.
1798 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1799 DIDescriptor Element = Elements.getElement(i);
1800 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1801 ConstructSubrangeDIE(Buffer, DISubrange(Element.getGV()), IndexTy);
1805 /// ConstructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1806 DIE *ConstructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) {
1808 DIE *Enumerator = new DIE(DW_TAG_enumerator);
1809 const std::string &Name = ETy->getName();
1810 AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
1811 int64_t Value = ETy->getEnumValue();
1812 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1816 /// CreateGlobalVariableDIE - Create new DIE using GV.
1817 DIE *CreateGlobalVariableDIE(CompileUnit *DW_Unit, const DIGlobalVariable &GV)
1819 DIE *GVDie = new DIE(DW_TAG_variable);
1820 const std::string &Name = GV.getDisplayName();
1821 AddString(GVDie, DW_AT_name, DW_FORM_string, Name);
1822 const std::string &LinkageName = GV.getLinkageName();
1823 if (!LinkageName.empty())
1824 AddString(GVDie, DW_AT_MIPS_linkage_name, DW_FORM_string, LinkageName);
1825 AddType(DW_Unit, GVDie, GV.getType());
1826 if (!GV.isLocalToUnit())
1827 AddUInt(GVDie, DW_AT_external, DW_FORM_flag, 1);
1828 AddSourceLine(GVDie, &GV);
1832 /// CreateMemberDIE - Create new member DIE.
1833 DIE *CreateMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT) {
1834 DIE *MemberDie = new DIE(DT.getTag());
1835 const std::string &Name = DT.getName();
1837 AddString(MemberDie, DW_AT_name, DW_FORM_string, Name);
1839 AddType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
1841 AddSourceLine(MemberDie, &DT);
1843 uint64_t Size = DT.getSizeInBits();
1844 uint64_t FieldSize = DT.getOriginalTypeSize();
1846 if (Size != FieldSize) {
1848 AddUInt(MemberDie, DW_AT_byte_size, 0, DT.getOriginalTypeSize() >> 3);
1849 AddUInt(MemberDie, DW_AT_bit_size, 0, DT.getSizeInBits());
1851 uint64_t Offset = DT.getOffsetInBits();
1852 uint64_t FieldOffset = Offset;
1853 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1854 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1855 FieldOffset = (HiMark - FieldSize);
1856 Offset -= FieldOffset;
1857 // Maybe we need to work from the other end.
1858 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1859 AddUInt(MemberDie, DW_AT_bit_offset, 0, Offset);
1861 DIEBlock *Block = new DIEBlock();
1862 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1863 AddUInt(Block, 0, DW_FORM_udata, DT.getOffsetInBits() >> 3);
1864 AddBlock(MemberDie, DW_AT_data_member_location, 0, Block);
1866 if (DT.isProtected())
1867 AddUInt(MemberDie, DW_AT_accessibility, 0, DW_ACCESS_protected);
1868 else if (DT.isPrivate())
1869 AddUInt(MemberDie, DW_AT_accessibility, 0, DW_ACCESS_private);
1874 /// CreateSubprogramDIE - Create new DIE using SP.
1875 DIE *CreateSubprogramDIE(CompileUnit *DW_Unit,
1876 const DISubprogram &SP,
1877 bool IsConstructor = false) {
1878 DIE *SPDie = new DIE(DW_TAG_subprogram);
1879 const std::string &Name = SP.getName();
1880 AddString(SPDie, DW_AT_name, DW_FORM_string, Name);
1881 const std::string &LinkageName = SP.getLinkageName();
1882 if (!LinkageName.empty())
1883 AddString(SPDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1885 AddSourceLine(SPDie, &SP);
1887 DICompositeType SPTy = SP.getType();
1888 DIArray Args = SPTy.getTypeArray();
1891 if (!IsConstructor) {
1893 AddType(DW_Unit, SPDie, SPTy);
1895 AddType(DW_Unit, SPDie, DIType(Args.getElement(0).getGV()));
1898 if (!SP.isDefinition()) {
1899 AddUInt(SPDie, DW_AT_declaration, DW_FORM_flag, 1);
1901 // Do not add arguments for subprogram definition. They will be
1902 // handled through RecordVariable.
1904 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1905 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1906 AddType(DW_Unit, Arg, DIType(Args.getElement(i).getGV()));
1907 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1); // ???
1908 SPDie->AddChild(Arg);
1912 unsigned Lang = SP.getCompileUnit().getLanguage();
1913 if (Lang == DW_LANG_C99 || Lang == DW_LANG_C89
1914 || Lang == DW_LANG_ObjC)
1915 AddUInt(SPDie, DW_AT_prototyped, DW_FORM_flag, 1);
1917 if (!SP.isLocalToUnit())
1918 AddUInt(SPDie, DW_AT_external, DW_FORM_flag, 1);
1922 /// FindCompileUnit - Get the compile unit for the given descriptor.
1924 CompileUnit *FindCompileUnit(DICompileUnit Unit) {
1925 CompileUnit *DW_Unit = CompileUnitMap[Unit.getGV()];
1926 assert(DW_Unit && "Missing compile unit.");
1930 /// NewDbgScopeVariable - Create a new scope variable.
1932 DIE *NewDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
1933 // Get the descriptor.
1934 const DIVariable &VD = DV->getVariable();
1936 // Translate tag to proper Dwarf tag. The result variable is dropped for
1939 switch (VD.getTag()) {
1940 case DW_TAG_return_variable: return NULL;
1941 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
1942 case DW_TAG_auto_variable: // fall thru
1943 default: Tag = DW_TAG_variable; break;
1946 // Define variable debug information entry.
1947 DIE *VariableDie = new DIE(Tag);
1948 const std::string &Name = VD.getName();
1949 AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
1951 // Add source line info if available.
1952 AddSourceLine(VariableDie, &VD);
1954 // Add variable type.
1955 AddType(Unit, VariableDie, VD.getType());
1957 // Add variable address.
1958 MachineLocation Location;
1959 Location.set(RI->getFrameRegister(*MF),
1960 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
1961 AddAddress(VariableDie, DW_AT_location, Location);
1966 /// getOrCreateScope - Returns the scope associated with the given descriptor.
1968 DbgScope *getOrCreateScope(GlobalVariable *V) {
1969 DbgScope *&Slot = DbgScopeMap[V];
1970 if (Slot) return Slot;
1972 // FIXME - breaks down when the context is an inlined function.
1973 DIDescriptor ParentDesc;
1974 DIDescriptor Desc(V);
1976 if (Desc.getTag() == dwarf::DW_TAG_lexical_block) {
1978 ParentDesc = Block.getContext();
1981 DbgScope *Parent = ParentDesc.isNull() ?
1982 NULL : getOrCreateScope(ParentDesc.getGV());
1983 Slot = new DbgScope(Parent, Desc);
1986 Parent->AddScope(Slot);
1987 } else if (RootDbgScope) {
1988 // FIXME - Add inlined function scopes to the root so we can delete them
1989 // later. Long term, handle inlined functions properly.
1990 RootDbgScope->AddScope(Slot);
1992 // First function is top level function.
1993 RootDbgScope = Slot;
1999 /// ConstructDbgScope - Construct the components of a scope.
2001 void ConstructDbgScope(DbgScope *ParentScope,
2002 unsigned ParentStartID, unsigned ParentEndID,
2003 DIE *ParentDie, CompileUnit *Unit) {
2004 // Add variables to scope.
2005 SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
2006 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2007 DIE *VariableDie = NewDbgScopeVariable(Variables[i], Unit);
2008 if (VariableDie) ParentDie->AddChild(VariableDie);
2011 // Add nested scopes.
2012 SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
2013 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
2014 // Define the Scope debug information entry.
2015 DbgScope *Scope = Scopes[j];
2016 // FIXME - Ignore inlined functions for the time being.
2017 if (!Scope->getParent()) continue;
2019 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
2020 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
2022 // Ignore empty scopes.
2023 if (StartID == EndID && StartID != 0) continue;
2024 if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
2026 if (StartID == ParentStartID && EndID == ParentEndID) {
2027 // Just add stuff to the parent scope.
2028 ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
2030 DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
2032 // Add the scope bounds.
2034 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2035 DWLabel("label", StartID));
2037 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2038 DWLabel("func_begin", SubprogramCount));
2041 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2042 DWLabel("label", EndID));
2044 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2045 DWLabel("func_end", SubprogramCount));
2048 // Add the scope contents.
2049 ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
2050 ParentDie->AddChild(ScopeDie);
2055 /// ConstructRootDbgScope - Construct the scope for the subprogram.
2057 void ConstructRootDbgScope(DbgScope *RootScope) {
2058 // Exit if there is no root scope.
2059 if (!RootScope) return;
2060 DIDescriptor Desc = RootScope->getDesc();
2064 // Get the subprogram debug information entry.
2065 DISubprogram SPD(Desc.getGV());
2067 // Get the compile unit context.
2068 CompileUnit *Unit = MainCU;
2070 Unit = FindCompileUnit(SPD.getCompileUnit());
2072 // Get the subprogram die.
2073 DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
2074 assert(SPDie && "Missing subprogram descriptor");
2076 // Add the function bounds.
2077 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2078 DWLabel("func_begin", SubprogramCount));
2079 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2080 DWLabel("func_end", SubprogramCount));
2081 MachineLocation Location(RI->getFrameRegister(*MF));
2082 AddAddress(SPDie, DW_AT_frame_base, Location);
2084 ConstructDbgScope(RootScope, 0, 0, SPDie, Unit);
2087 /// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
2089 void ConstructDefaultDbgScope(MachineFunction *MF) {
2090 const char *FnName = MF->getFunction()->getNameStart();
2092 std::map<std::string, DIE*> &Globals = MainCU->getGlobals();
2093 std::map<std::string, DIE*>::iterator GI = Globals.find(FnName);
2094 if (GI != Globals.end()) {
2095 DIE *SPDie = GI->second;
2097 // Add the function bounds.
2098 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2099 DWLabel("func_begin", SubprogramCount));
2100 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2101 DWLabel("func_end", SubprogramCount));
2103 MachineLocation Location(RI->getFrameRegister(*MF));
2104 AddAddress(SPDie, DW_AT_frame_base, Location);
2108 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
2109 CompileUnit *Unit = CompileUnits[i];
2110 std::map<std::string, DIE*> &Globals = Unit->getGlobals();
2111 std::map<std::string, DIE*>::iterator GI = Globals.find(FnName);
2112 if (GI != Globals.end()) {
2113 DIE *SPDie = GI->second;
2115 // Add the function bounds.
2116 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2117 DWLabel("func_begin", SubprogramCount));
2118 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2119 DWLabel("func_end", SubprogramCount));
2121 MachineLocation Location(RI->getFrameRegister(*MF));
2122 AddAddress(SPDie, DW_AT_frame_base, Location);
2129 // FIXME: This is causing an abort because C++ mangled names are compared
2130 // with their unmangled counterparts. See PR2885. Don't do this assert.
2131 assert(0 && "Couldn't find DIE for machine function!");
2136 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
2137 /// tools to recognize the object file contains Dwarf information.
2138 void EmitInitial() {
2139 // Check to see if we already emitted intial headers.
2140 if (didInitial) return;
2143 // Dwarf sections base addresses.
2144 if (TAI->doesDwarfRequireFrameSection()) {
2145 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2146 EmitLabel("section_debug_frame", 0);
2148 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2149 EmitLabel("section_info", 0);
2150 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2151 EmitLabel("section_abbrev", 0);
2152 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2153 EmitLabel("section_aranges", 0);
2154 if (TAI->doesSupportMacInfoSection()) {
2155 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2156 EmitLabel("section_macinfo", 0);
2158 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2159 EmitLabel("section_line", 0);
2160 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2161 EmitLabel("section_loc", 0);
2162 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2163 EmitLabel("section_pubnames", 0);
2164 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2165 EmitLabel("section_str", 0);
2166 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2167 EmitLabel("section_ranges", 0);
2169 Asm->SwitchToSection(TAI->getTextSection());
2170 EmitLabel("text_begin", 0);
2171 Asm->SwitchToSection(TAI->getDataSection());
2172 EmitLabel("data_begin", 0);
2175 /// EmitDIE - Recusively Emits a debug information entry.
2177 void EmitDIE(DIE *Die) {
2178 // Get the abbreviation for this DIE.
2179 unsigned AbbrevNumber = Die->getAbbrevNumber();
2180 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2184 // Emit the code (index) for the abbreviation.
2185 Asm->EmitULEB128Bytes(AbbrevNumber);
2188 Asm->EOL(std::string("Abbrev [" +
2189 utostr(AbbrevNumber) +
2190 "] 0x" + utohexstr(Die->getOffset()) +
2191 ":0x" + utohexstr(Die->getSize()) + " " +
2192 TagString(Abbrev->getTag())));
2196 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2197 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2199 // Emit the DIE attribute values.
2200 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2201 unsigned Attr = AbbrevData[i].getAttribute();
2202 unsigned Form = AbbrevData[i].getForm();
2203 assert(Form && "Too many attributes for DIE (check abbreviation)");
2206 case DW_AT_sibling: {
2207 Asm->EmitInt32(Die->SiblingOffset());
2211 // Emit an attribute using the defined form.
2212 Values[i]->EmitValue(*this, Form);
2217 Asm->EOL(AttributeString(Attr));
2220 // Emit the DIE children if any.
2221 if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2222 const std::vector<DIE *> &Children = Die->getChildren();
2224 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2225 EmitDIE(Children[j]);
2228 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2232 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2234 unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2235 // Get the children.
2236 const std::vector<DIE *> &Children = Die->getChildren();
2238 // If not last sibling and has children then add sibling offset attribute.
2239 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2241 // Record the abbreviation.
2242 AssignAbbrevNumber(Die->getAbbrev());
2244 // Get the abbreviation for this DIE.
2245 unsigned AbbrevNumber = Die->getAbbrevNumber();
2246 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2249 Die->setOffset(Offset);
2251 // Start the size with the size of abbreviation code.
2252 Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
2254 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2255 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2257 // Size the DIE attribute values.
2258 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2259 // Size attribute value.
2260 Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2263 // Size the DIE children if any.
2264 if (!Children.empty()) {
2265 assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2266 "Children flag not set");
2268 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2269 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2272 // End of children marker.
2273 Offset += sizeof(int8_t);
2276 Die->setSize(Offset - Die->getOffset());
2280 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2282 void SizeAndOffsets() {
2283 // Process base compile unit.
2285 // Compute size of compile unit header
2286 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2287 sizeof(int16_t) + // DWARF version number
2288 sizeof(int32_t) + // Offset Into Abbrev. Section
2289 sizeof(int8_t); // Pointer Size (in bytes)
2290 SizeAndOffsetDie(MainCU->getDie(), Offset, true);
2293 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
2294 CompileUnit *Unit = CompileUnits[i];
2295 // Compute size of compile unit header
2296 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2297 sizeof(int16_t) + // DWARF version number
2298 sizeof(int32_t) + // Offset Into Abbrev. Section
2299 sizeof(int8_t); // Pointer Size (in bytes)
2300 SizeAndOffsetDie(Unit->getDie(), Offset, true);
2304 /// EmitDebugInfo / EmitDebugInfoPerCU - Emit the debug info section.
2306 void EmitDebugInfoPerCU(CompileUnit *Unit) {
2307 DIE *Die = Unit->getDie();
2308 // Emit the compile units header.
2309 EmitLabel("info_begin", Unit->getID());
2310 // Emit size of content not including length itself
2311 unsigned ContentSize = Die->getSize() +
2312 sizeof(int16_t) + // DWARF version number
2313 sizeof(int32_t) + // Offset Into Abbrev. Section
2314 sizeof(int8_t) + // Pointer Size (in bytes)
2315 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2317 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2318 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2319 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2320 Asm->EOL("Offset Into Abbrev. Section");
2321 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2324 // FIXME - extra padding for gdb bug.
2325 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2326 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2327 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2328 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2329 EmitLabel("info_end", Unit->getID());
2334 void EmitDebugInfo() {
2335 // Start debug info section.
2336 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2339 EmitDebugInfoPerCU(MainCU);
2343 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
2344 EmitDebugInfoPerCU(CompileUnits[i]);
2347 /// EmitAbbreviations - Emit the abbreviation section.
2349 void EmitAbbreviations() const {
2350 // Check to see if it is worth the effort.
2351 if (!Abbreviations.empty()) {
2352 // Start the debug abbrev section.
2353 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2355 EmitLabel("abbrev_begin", 0);
2357 // For each abbrevation.
2358 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2359 // Get abbreviation data
2360 const DIEAbbrev *Abbrev = Abbreviations[i];
2362 // Emit the abbrevations code (base 1 index.)
2363 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2364 Asm->EOL("Abbreviation Code");
2366 // Emit the abbreviations data.
2367 Abbrev->Emit(*this);
2372 // Mark end of abbreviations.
2373 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2375 EmitLabel("abbrev_end", 0);
2381 /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
2382 /// the line matrix.
2384 void EmitEndOfLineMatrix(unsigned SectionEnd) {
2385 // Define last address of section.
2386 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2387 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2388 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2389 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2391 // Mark end of matrix.
2392 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2393 Asm->EmitULEB128Bytes(1); Asm->EOL();
2394 Asm->EmitInt8(1); Asm->EOL();
2397 /// EmitDebugLines - Emit source line information.
2399 void EmitDebugLines() {
2400 // If the target is using .loc/.file, the assembler will be emitting the
2401 // .debug_line table automatically.
2402 if (TAI->hasDotLocAndDotFile())
2405 // Minimum line delta, thus ranging from -10..(255-10).
2406 const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2407 // Maximum line delta, thus ranging from -10..(255-10).
2408 const int MaxLineDelta = 255 + MinLineDelta;
2410 // Start the dwarf line section.
2411 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2413 // Construct the section header.
2415 EmitDifference("line_end", 0, "line_begin", 0, true);
2416 Asm->EOL("Length of Source Line Info");
2417 EmitLabel("line_begin", 0);
2419 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2421 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2422 Asm->EOL("Prolog Length");
2423 EmitLabel("line_prolog_begin", 0);
2425 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2427 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2429 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2431 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2433 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2435 // Line number standard opcode encodings argument count
2436 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2437 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2438 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2439 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2440 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2441 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2442 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2443 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2444 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2446 // Emit directories.
2447 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2448 Asm->EmitString(getSourceDirectoryName(DI));
2449 Asm->EOL("Directory");
2451 Asm->EmitInt8(0); Asm->EOL("End of directories");
2454 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2455 // Remember source id starts at 1.
2456 std::pair<unsigned, unsigned> Id = getSourceDirsectoryAndFileIds(SI);
2457 Asm->EmitString(getSourceFileName(Id.second));
2459 Asm->EmitULEB128Bytes(Id.first);
2460 Asm->EOL("Directory #");
2461 Asm->EmitULEB128Bytes(0);
2462 Asm->EOL("Mod date");
2463 Asm->EmitULEB128Bytes(0);
2464 Asm->EOL("File size");
2466 Asm->EmitInt8(0); Asm->EOL("End of files");
2468 EmitLabel("line_prolog_end", 0);
2470 // A sequence for each text section.
2471 unsigned SecSrcLinesSize = SectionSourceLines.size();
2473 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2474 // Isolate current sections line info.
2475 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2478 const Section* S = SectionMap[j + 1];
2479 O << '\t' << TAI->getCommentString() << " Section"
2480 << S->getName() << '\n';
2484 // Dwarf assumes we start with first line of first source file.
2485 unsigned Source = 1;
2488 // Construct rows of the address, source, line, column matrix.
2489 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2490 const SrcLineInfo &LineInfo = LineInfos[i];
2491 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2492 if (!LabelID) continue;
2497 std::pair<unsigned, unsigned> SourceID =
2498 getSourceDirsectoryAndFileIds(LineInfo.getSourceID());
2499 O << '\t' << TAI->getCommentString() << ' '
2500 << getSourceDirectoryName(SourceID.first) << ' '
2501 << getSourceFileName(SourceID.second)
2502 <<" :" << utostr_32(LineInfo.getLine()) << '\n';
2505 // Define the line address.
2506 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2507 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2508 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2509 EmitReference("label", LabelID); Asm->EOL("Location label");
2511 // If change of source, then switch to the new source.
2512 if (Source != LineInfo.getSourceID()) {
2513 Source = LineInfo.getSourceID();
2514 Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2515 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2518 // If change of line.
2519 if (Line != LineInfo.getLine()) {
2520 // Determine offset.
2521 int Offset = LineInfo.getLine() - Line;
2522 int Delta = Offset - MinLineDelta;
2525 Line = LineInfo.getLine();
2527 // If delta is small enough and in range...
2528 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2529 // ... then use fast opcode.
2530 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2532 // ... otherwise use long hand.
2533 Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
2534 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2535 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2538 // Copy the previous row (different address or source)
2539 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2543 EmitEndOfLineMatrix(j + 1);
2546 if (SecSrcLinesSize == 0)
2547 // Because we're emitting a debug_line section, we still need a line
2548 // table. The linker and friends expect it to exist. If there's nothing to
2549 // put into it, emit an empty table.
2550 EmitEndOfLineMatrix(1);
2552 EmitLabel("line_end", 0);
2557 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2559 void EmitCommonDebugFrame() {
2560 if (!TAI->doesDwarfRequireFrameSection())
2564 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2565 TargetFrameInfo::StackGrowsUp ?
2566 TD->getPointerSize() : -TD->getPointerSize();
2568 // Start the dwarf frame section.
2569 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2571 EmitLabel("debug_frame_common", 0);
2572 EmitDifference("debug_frame_common_end", 0,
2573 "debug_frame_common_begin", 0, true);
2574 Asm->EOL("Length of Common Information Entry");
2576 EmitLabel("debug_frame_common_begin", 0);
2577 Asm->EmitInt32((int)DW_CIE_ID);
2578 Asm->EOL("CIE Identifier Tag");
2579 Asm->EmitInt8(DW_CIE_VERSION);
2580 Asm->EOL("CIE Version");
2581 Asm->EmitString("");
2582 Asm->EOL("CIE Augmentation");
2583 Asm->EmitULEB128Bytes(1);
2584 Asm->EOL("CIE Code Alignment Factor");
2585 Asm->EmitSLEB128Bytes(stackGrowth);
2586 Asm->EOL("CIE Data Alignment Factor");
2587 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2588 Asm->EOL("CIE RA Column");
2590 std::vector<MachineMove> Moves;
2591 RI->getInitialFrameState(Moves);
2593 EmitFrameMoves(NULL, 0, Moves, false);
2595 Asm->EmitAlignment(2, 0, 0, false);
2596 EmitLabel("debug_frame_common_end", 0);
2601 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2603 void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2604 if (!TAI->doesDwarfRequireFrameSection())
2607 // Start the dwarf frame section.
2608 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2610 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2611 "debug_frame_begin", DebugFrameInfo.Number, true);
2612 Asm->EOL("Length of Frame Information Entry");
2614 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2616 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2618 Asm->EOL("FDE CIE offset");
2620 EmitReference("func_begin", DebugFrameInfo.Number);
2621 Asm->EOL("FDE initial location");
2622 EmitDifference("func_end", DebugFrameInfo.Number,
2623 "func_begin", DebugFrameInfo.Number);
2624 Asm->EOL("FDE address range");
2626 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
2629 Asm->EmitAlignment(2, 0, 0, false);
2630 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2635 void EmitDebugPubNamesPerCU(CompileUnit *Unit) {
2636 EmitDifference("pubnames_end", Unit->getID(),
2637 "pubnames_begin", Unit->getID(), true);
2638 Asm->EOL("Length of Public Names Info");
2640 EmitLabel("pubnames_begin", Unit->getID());
2642 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
2644 EmitSectionOffset("info_begin", "section_info",
2645 Unit->getID(), 0, true, false);
2646 Asm->EOL("Offset of Compilation Unit Info");
2648 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
2650 Asm->EOL("Compilation Unit Length");
2652 std::map<std::string, DIE *> &Globals = Unit->getGlobals();
2653 for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
2654 GE = Globals.end(); GI != GE; ++GI) {
2655 const std::string &Name = GI->first;
2656 DIE * Entity = GI->second;
2658 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2659 Asm->EmitString(Name); Asm->EOL("External Name");
2662 Asm->EmitInt32(0); Asm->EOL("End Mark");
2663 EmitLabel("pubnames_end", Unit->getID());
2668 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2670 void EmitDebugPubNames() {
2671 // Start the dwarf pubnames section.
2672 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2675 EmitDebugPubNamesPerCU(MainCU);
2679 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
2680 EmitDebugPubNamesPerCU(CompileUnits[i]);
2683 /// EmitDebugStr - Emit visible names into a debug str section.
2685 void EmitDebugStr() {
2686 // Check to see if it is worth the effort.
2687 if (!StringPool.empty()) {
2688 // Start the dwarf str section.
2689 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2691 // For each of strings in the string pool.
2692 for (unsigned StringID = 1, N = StringPool.size();
2693 StringID <= N; ++StringID) {
2694 // Emit a label for reference from debug information entries.
2695 EmitLabel("string", StringID);
2696 // Emit the string itself.
2697 const std::string &String = StringPool[StringID];
2698 Asm->EmitString(String); Asm->EOL();
2705 /// EmitDebugLoc - Emit visible names into a debug loc section.
2707 void EmitDebugLoc() {
2708 // Start the dwarf loc section.
2709 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2714 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2716 void EmitDebugARanges() {
2717 // Start the dwarf aranges section.
2718 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2722 CompileUnit *Unit = GetBaseCompileUnit();
2724 // Don't include size of length
2725 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2727 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2729 EmitReference("info_begin", Unit->getID());
2730 Asm->EOL("Offset of Compilation Unit Info");
2732 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2734 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2736 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2737 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2740 EmitReference("text_begin", 0); Asm->EOL("Address");
2741 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2743 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2744 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2750 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2752 void EmitDebugRanges() {
2753 // Start the dwarf ranges section.
2754 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2759 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2761 void EmitDebugMacInfo() {
2762 if (TAI->doesSupportMacInfoSection()) {
2763 // Start the dwarf macinfo section.
2764 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2770 void ConstructCompileUnit(GlobalVariable *GV) {
2771 DICompileUnit DIUnit(GV);
2772 unsigned ID = getOrCreateSourceID(DIUnit.getDirectory(),
2773 DIUnit.getFilename());
2775 DIE *Die = new DIE(DW_TAG_compile_unit);
2776 AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
2777 DWLabel("section_line", 0), DWLabel("section_line", 0),
2779 AddString(Die, DW_AT_producer, DW_FORM_string, DIUnit.getProducer());
2780 AddUInt(Die, DW_AT_language, DW_FORM_data1, DIUnit.getLanguage());
2781 AddString(Die, DW_AT_name, DW_FORM_string, DIUnit.getFilename());
2782 if (!DIUnit.getDirectory().empty())
2783 AddString(Die, DW_AT_comp_dir, DW_FORM_string, DIUnit.getDirectory());
2784 if (DIUnit.isOptimized())
2785 AddUInt(Die, DW_AT_APPLE_optimized, DW_FORM_flag, 1);
2786 const std::string &Flags = DIUnit.getFlags();
2788 AddString(Die, DW_AT_APPLE_flags, DW_FORM_string, Flags);
2789 unsigned RVer = DIUnit.getRunTimeVersion();
2791 AddUInt(Die, DW_AT_APPLE_major_runtime_vers, DW_FORM_data1, RVer);
2793 CompileUnit *Unit = new CompileUnit(ID, Die);
2794 if (DIUnit.isMain()) {
2795 assert(!MainCU && "Multiple main compile units are found!");
2798 CompileUnitMap[DIUnit.getGV()] = Unit;
2799 CompileUnits.push_back(Unit);
2802 /// ConstructCompileUnits - Create a compile unit DIEs.
2803 void ConstructCompileUnits() {
2804 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.compile_units");
2807 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2808 "Malformed compile unit descriptor anchor type");
2809 Constant *RootC = cast<Constant>(*Root->use_begin());
2810 assert(RootC->hasNUsesOrMore(1) &&
2811 "Malformed compile unit descriptor anchor type");
2812 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2814 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2815 UUI != UUE; ++UUI) {
2816 GlobalVariable *GV = cast<GlobalVariable>(*UUI);
2817 ConstructCompileUnit(GV);
2821 bool ConstructGlobalVariableDIE(GlobalVariable *GV) {
2822 DIGlobalVariable DI_GV(GV);
2823 CompileUnit *DW_Unit = MainCU;
2825 DW_Unit = FindCompileUnit(DI_GV.getCompileUnit());
2827 // Check for pre-existence.
2828 DIE *&Slot = DW_Unit->getDieMapSlotFor(DI_GV.getGV());
2832 DIE *VariableDie = CreateGlobalVariableDIE(DW_Unit, 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.getGlobal()));
2839 AddBlock(VariableDie, DW_AT_location, 0, Block);
2843 // Add to context owner.
2844 DW_Unit->getDie()->AddChild(VariableDie);
2845 // Expose as global. FIXME - need to check external flag.
2846 DW_Unit->AddGlobal(DI_GV.getName(), VariableDie);
2850 /// ConstructGlobalVariableDIEs - Create DIEs for each of the externally
2851 /// visible global variables. Return true if at least one global DIE is
2853 bool ConstructGlobalVariableDIEs() {
2854 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.global_variables");
2858 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2859 "Malformed global variable descriptor anchor type");
2860 Constant *RootC = cast<Constant>(*Root->use_begin());
2861 assert(RootC->hasNUsesOrMore(1) &&
2862 "Malformed global variable descriptor anchor type");
2864 bool Result = false;
2865 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2867 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2868 UUI != UUE; ++UUI) {
2869 GlobalVariable *GV = cast<GlobalVariable>(*UUI);
2870 Result |= ConstructGlobalVariableDIE(GV);
2875 bool ConstructSubprogram(GlobalVariable *GV) {
2876 DISubprogram SP(GV);
2877 CompileUnit *Unit = MainCU;
2879 Unit = FindCompileUnit(SP.getCompileUnit());
2881 // Check for pre-existence.
2882 DIE *&Slot = Unit->getDieMapSlotFor(GV);
2886 if (!SP.isDefinition())
2887 // This is a method declaration which will be handled while
2888 // constructing class type.
2891 DIE *SubprogramDie = CreateSubprogramDIE(Unit, SP);
2894 Slot = SubprogramDie;
2895 // Add to context owner.
2896 Unit->getDie()->AddChild(SubprogramDie);
2897 // Expose as global.
2898 Unit->AddGlobal(SP.getName(), SubprogramDie);
2902 /// ConstructSubprograms - Create DIEs for each of the externally visible
2903 /// subprograms. Return true if at least one subprogram DIE is created.
2904 bool ConstructSubprograms() {
2905 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.subprograms");
2909 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2910 "Malformed subprogram descriptor anchor type");
2911 Constant *RootC = cast<Constant>(*Root->use_begin());
2912 assert(RootC->hasNUsesOrMore(1) &&
2913 "Malformed subprogram descriptor anchor type");
2915 bool Result = false;
2916 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2918 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2919 UUI != UUE; ++UUI) {
2920 GlobalVariable *GV = cast<GlobalVariable>(*UUI);
2921 Result |= ConstructSubprogram(GV);
2927 //===--------------------------------------------------------------------===//
2928 // Main entry points.
2930 DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
2931 : Dwarf(OS, A, T, "dbg")
2933 , AbbreviationsSet(InitAbbreviationsSetSize)
2935 , ValuesSet(InitValuesSetSize)
2939 , SectionSourceLines()
2942 , RootDbgScope(NULL)
2945 virtual ~DwarfDebug() {
2946 for (unsigned j = 0, M = Values.size(); j < M; ++j)
2950 /// SetDebugInfo - Create global DIEs and emit initial debug info sections.
2951 /// This is inovked by the target AsmPrinter.
2952 void SetDebugInfo(MachineModuleInfo *mmi) {
2953 // Create all the compile unit DIEs.
2954 ConstructCompileUnits();
2956 if (CompileUnits.empty())
2959 // Create DIEs for each of the externally visible global variables.
2960 bool globalDIEs = ConstructGlobalVariableDIEs();
2962 // Create DIEs for each of the externally visible subprograms.
2963 bool subprogramDIEs = ConstructSubprograms();
2965 // If there is not any debug info available for any global variables
2966 // and any subprograms then there is not any debug info to emit.
2967 if (!globalDIEs && !subprogramDIEs)
2972 MMI->setDebugInfoAvailability(true);
2974 // Prime section data.
2975 SectionMap.insert(TAI->getTextSection());
2977 // Print out .file directives to specify files for .loc directives. These
2978 // are printed out early so that they precede any .loc directives.
2979 if (TAI->hasDotLocAndDotFile()) {
2980 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
2981 // Remember source id starts at 1.
2982 std::pair<unsigned, unsigned> Id = getSourceDirsectoryAndFileIds(i);
2983 sys::Path FullPath(getSourceDirectoryName(Id.first));
2985 FullPath.appendComponent(getSourceFileName(Id.second));
2986 assert(AppendOk && "Could not append filename to directory!");
2988 Asm->EmitFile(i, FullPath.toString());
2993 // Emit initial sections
2997 /// BeginModule - Emit all Dwarf sections that should come prior to the
2999 void BeginModule(Module *M) {
3003 /// EndModule - Emit all Dwarf sections that should come after the content.
3006 if (!ShouldEmitDwarfDebug()) return;
3008 // Standard sections final addresses.
3009 Asm->SwitchToSection(TAI->getTextSection());
3010 EmitLabel("text_end", 0);
3011 Asm->SwitchToSection(TAI->getDataSection());
3012 EmitLabel("data_end", 0);
3014 // End text sections.
3015 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
3016 Asm->SwitchToSection(SectionMap[i]);
3017 EmitLabel("section_end", i);
3020 // Emit common frame information.
3021 EmitCommonDebugFrame();
3023 // Emit function debug frame information
3024 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
3025 E = DebugFrames.end(); I != E; ++I)
3026 EmitFunctionDebugFrame(*I);
3028 // Compute DIE offsets and sizes.
3031 // Emit all the DIEs into a debug info section
3034 // Corresponding abbreviations into a abbrev section.
3035 EmitAbbreviations();
3037 // Emit source line correspondence into a debug line section.
3040 // Emit info into a debug pubnames section.
3041 EmitDebugPubNames();
3043 // Emit info into a debug str section.
3046 // Emit info into a debug loc section.
3049 // Emit info into a debug aranges section.
3052 // Emit info into a debug ranges section.
3055 // Emit info into a debug macinfo section.
3059 /// BeginFunction - Gather pre-function debug information. Assumes being
3060 /// emitted immediately after the function entry point.
3061 void BeginFunction(MachineFunction *MF) {
3064 if (!ShouldEmitDwarfDebug()) return;
3066 // Begin accumulating function debug information.
3067 MMI->BeginFunction(MF);
3069 // Assumes in correct section after the entry point.
3070 EmitLabel("func_begin", ++SubprogramCount);
3072 // Emit label for the implicitly defined dbg.stoppoint at the start of
3074 if (!Lines.empty()) {
3075 const SrcLineInfo &LineInfo = Lines[0];
3076 Asm->printLabel(LineInfo.getLabelID());
3080 /// EndFunction - Gather and emit post-function debug information.
3082 void EndFunction(MachineFunction *MF) {
3083 if (!ShouldEmitDwarfDebug()) return;
3085 // Define end label for subprogram.
3086 EmitLabel("func_end", SubprogramCount);
3088 // Get function line info.
3089 if (!Lines.empty()) {
3090 // Get section line info.
3091 unsigned ID = SectionMap.insert(Asm->CurrentSection_);
3092 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
3093 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
3094 // Append the function info to section info.
3095 SectionLineInfos.insert(SectionLineInfos.end(),
3096 Lines.begin(), Lines.end());
3099 // Construct scopes for subprogram.
3101 ConstructRootDbgScope(RootDbgScope);
3103 // FIXME: This is wrong. We are essentially getting past a problem with
3104 // debug information not being able to handle unreachable blocks that have
3105 // debug information in them. In particular, those unreachable blocks that
3106 // have "region end" info in them. That situation results in the "root
3107 // scope" not being created. If that's the case, then emit a "default"
3108 // scope, i.e., one that encompasses the whole function. This isn't
3109 // desirable. And a better way of handling this (and all of the debugging
3110 // information) needs to be explored.
3111 ConstructDefaultDbgScope(MF);
3113 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
3114 MMI->getFrameMoves()));
3118 delete RootDbgScope;
3119 DbgScopeMap.clear();
3120 RootDbgScope = NULL;
3127 /// ValidDebugInfo - Return true if V represents valid debug info value.
3128 bool ValidDebugInfo(Value *V) {
3135 GlobalVariable *GV = getGlobalVariable(V);
3139 if (!GV->hasInternalLinkage () && !GV->hasLinkOnceLinkage())
3142 DIDescriptor DI(GV);
3143 // Check current version. Allow Version6 for now.
3144 unsigned Version = DI.getVersion();
3145 if (Version != LLVMDebugVersion && Version != LLVMDebugVersion6)
3148 unsigned Tag = DI.getTag();
3150 case DW_TAG_variable:
3151 assert(DIVariable(GV).Verify() && "Invalid DebugInfo value");
3153 case DW_TAG_compile_unit:
3154 assert(DICompileUnit(GV).Verify() && "Invalid DebugInfo value");
3156 case DW_TAG_subprogram:
3157 assert(DISubprogram(GV).Verify() && "Invalid DebugInfo value");
3166 /// RecordSourceLine - Records location information and associates it with a
3167 /// label. Returns a unique label ID used to generate a label and provide
3168 /// correspondence to the source line list.
3169 unsigned RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
3170 CompileUnit *Unit = CompileUnitMap[V];
3171 assert(Unit && "Unable to find CompileUnit");
3172 unsigned ID = MMI->NextLabelID();
3173 Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
3177 /// RecordSourceLine - Records location information and associates it with a
3178 /// label. Returns a unique label ID used to generate a label and provide
3179 /// correspondence to the source line list.
3180 unsigned RecordSourceLine(unsigned Line, unsigned Col, unsigned Src) {
3181 unsigned ID = MMI->NextLabelID();
3182 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
3186 unsigned getRecordSourceLineCount() {
3187 return Lines.size();
3190 /// getNumSourceDirectories - Return the number of source directories in the
3192 unsigned getNumSourceDirectories() const {
3193 return DirectoryNames.size();
3196 /// getSourceDirectoryName - Return the name of the directory corresponding
3198 const std::string &getSourceDirectoryName(unsigned Id) const {
3199 return DirectoryNames[Id - 1];
3202 /// getNumSourceFiles - Return the number of source files in the debug info.
3204 unsigned getNumSourceFiles() const {
3205 return SourceFileNames.size();
3208 /// getSourceFileName - Return the name of the source file corresponding
3210 const std::string &getSourceFileName(unsigned Id) const {
3211 return SourceFileNames[Id - 1];
3214 /// getNumSourceIds - Return the number of unique source ids.
3216 unsigned getNumSourceIds() const {
3217 return SourceIds.size();
3220 /// getSourceDirsectoryAndFileIds - Return the directory and file ids that
3221 /// maps to the source id. Source id starts at 1.
3222 std::pair<unsigned, unsigned>
3223 getSourceDirsectoryAndFileIds(unsigned SId) const {
3224 return SourceIds[SId-1];
3227 /// getOrCreateSourceID - Look up the source id with the given directory and
3228 /// source file names. If none currently exists, create a new id and insert it
3229 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames maps
3231 unsigned getOrCreateSourceID(const std::string &DirName,
3232 const std::string &FileName) {
3234 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
3235 if (DI != DirectoryIdMap.end())
3236 DId = DI->getValue();
3238 DId = DirectoryNames.size() + 1;
3239 DirectoryIdMap[DirName] = DId;
3240 DirectoryNames.push_back(DirName);
3244 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
3245 if (FI != SourceFileIdMap.end())
3246 FId = FI->getValue();
3248 FId = SourceFileNames.size() + 1;
3249 SourceFileIdMap[FileName] = FId;
3250 SourceFileNames.push_back(FileName);
3253 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
3254 SourceIdMap.find(std::make_pair(DId, FId));
3255 if (SI != SourceIdMap.end())
3257 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
3258 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
3259 SourceIds.push_back(std::make_pair(DId, FId));
3263 /// RecordRegionStart - Indicate the start of a region.
3265 unsigned RecordRegionStart(GlobalVariable *V) {
3266 DbgScope *Scope = getOrCreateScope(V);
3267 unsigned ID = MMI->NextLabelID();
3268 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
3272 /// RecordRegionEnd - Indicate the end of a region.
3274 unsigned RecordRegionEnd(GlobalVariable *V) {
3275 DbgScope *Scope = getOrCreateScope(V);
3276 unsigned ID = MMI->NextLabelID();
3277 Scope->setEndLabelID(ID);
3281 /// RecordVariable - Indicate the declaration of a local variable.
3283 void RecordVariable(GlobalVariable *GV, unsigned FrameIndex) {
3284 DIDescriptor Desc(GV);
3285 DbgScope *Scope = NULL;
3286 if (Desc.getTag() == DW_TAG_variable) {
3287 // GV is a global variable.
3288 DIGlobalVariable DG(GV);
3289 Scope = getOrCreateScope(DG.getContext().getGV());
3291 // or GV is a local variable.
3293 Scope = getOrCreateScope(DV.getContext().getGV());
3295 assert(Scope && "Unable to find variable' scope");
3296 DbgVariable *DV = new DbgVariable(DIVariable(GV), FrameIndex);
3297 Scope->AddVariable(DV);
3301 //===----------------------------------------------------------------------===//
3302 /// DwarfException - Emits Dwarf exception handling directives.
3304 class DwarfException : public Dwarf {
3305 struct FunctionEHFrameInfo {
3308 unsigned PersonalityIndex;
3310 bool hasLandingPads;
3311 std::vector<MachineMove> Moves;
3312 const Function * function;
3314 FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
3316 const std::vector<MachineMove> &M,
3318 FnName(FN), Number(Num), PersonalityIndex(P),
3319 hasCalls(hC), hasLandingPads(hL), Moves(M), function (f) { }
3322 std::vector<FunctionEHFrameInfo> EHFrames;
3324 /// shouldEmitTable - Per-function flag to indicate if EH tables should
3326 bool shouldEmitTable;
3328 /// shouldEmitMoves - Per-function flag to indicate if frame moves info
3329 /// should be emitted.
3330 bool shouldEmitMoves;
3332 /// shouldEmitTableModule - Per-module flag to indicate if EH tables
3333 /// should be emitted.
3334 bool shouldEmitTableModule;
3336 /// shouldEmitFrameModule - Per-module flag to indicate if frame moves
3337 /// should be emitted.
3338 bool shouldEmitMovesModule;
3340 /// EmitCommonEHFrame - Emit the common eh unwind frame.
3342 void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
3343 // Size and sign of stack growth.
3345 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3346 TargetFrameInfo::StackGrowsUp ?
3347 TD->getPointerSize() : -TD->getPointerSize();
3349 // Begin eh frame section.
3350 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3352 if (!TAI->doesRequireNonLocalEHFrameLabel())
3353 O << TAI->getEHGlobalPrefix();
3354 O << "EH_frame" << Index << ":\n";
3355 EmitLabel("section_eh_frame", Index);
3357 // Define base labels.
3358 EmitLabel("eh_frame_common", Index);
3360 // Define the eh frame length.
3361 EmitDifference("eh_frame_common_end", Index,
3362 "eh_frame_common_begin", Index, true);
3363 Asm->EOL("Length of Common Information Entry");
3366 EmitLabel("eh_frame_common_begin", Index);
3367 Asm->EmitInt32((int)0);
3368 Asm->EOL("CIE Identifier Tag");
3369 Asm->EmitInt8(DW_CIE_VERSION);
3370 Asm->EOL("CIE Version");
3372 // The personality presence indicates that language specific information
3373 // will show up in the eh frame.
3374 Asm->EmitString(Personality ? "zPLR" : "zR");
3375 Asm->EOL("CIE Augmentation");
3377 // Round out reader.
3378 Asm->EmitULEB128Bytes(1);
3379 Asm->EOL("CIE Code Alignment Factor");
3380 Asm->EmitSLEB128Bytes(stackGrowth);
3381 Asm->EOL("CIE Data Alignment Factor");
3382 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
3383 Asm->EOL("CIE Return Address Column");
3385 // If there is a personality, we need to indicate the functions location.
3387 Asm->EmitULEB128Bytes(7);
3388 Asm->EOL("Augmentation Size");
3390 if (TAI->getNeedsIndirectEncoding()) {
3391 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4 | DW_EH_PE_indirect);
3392 Asm->EOL("Personality (pcrel sdata4 indirect)");
3394 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3395 Asm->EOL("Personality (pcrel sdata4)");
3398 PrintRelDirective(true);
3399 O << TAI->getPersonalityPrefix();
3400 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
3401 O << TAI->getPersonalitySuffix();
3402 if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
3403 O << "-" << TAI->getPCSymbol();
3404 Asm->EOL("Personality");
3406 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3407 Asm->EOL("LSDA Encoding (pcrel sdata4)");
3409 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3410 Asm->EOL("FDE Encoding (pcrel sdata4)");
3412 Asm->EmitULEB128Bytes(1);
3413 Asm->EOL("Augmentation Size");
3415 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3416 Asm->EOL("FDE Encoding (pcrel sdata4)");
3419 // Indicate locations of general callee saved registers in frame.
3420 std::vector<MachineMove> Moves;
3421 RI->getInitialFrameState(Moves);
3422 EmitFrameMoves(NULL, 0, Moves, true);
3424 // On Darwin the linker honors the alignment of eh_frame, which means it
3425 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3426 // you get holes which confuse readers of eh_frame.
3427 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3429 EmitLabel("eh_frame_common_end", Index);
3434 /// EmitEHFrame - Emit function exception frame information.
3436 void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
3437 Function::LinkageTypes linkage = EHFrameInfo.function->getLinkage();
3439 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3441 // Externally visible entry into the functions eh frame info.
3442 // If the corresponding function is static, this should not be
3443 // externally visible.
3444 if (linkage != Function::InternalLinkage &&
3445 linkage != Function::PrivateLinkage) {
3446 if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
3447 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
3450 // If corresponding function is weak definition, this should be too.
3451 if ((linkage == Function::WeakAnyLinkage ||
3452 linkage == Function::WeakODRLinkage ||
3453 linkage == Function::LinkOnceAnyLinkage ||
3454 linkage == Function::LinkOnceODRLinkage) &&
3455 TAI->getWeakDefDirective())
3456 O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
3458 // If there are no calls then you can't unwind. This may mean we can
3459 // omit the EH Frame, but some environments do not handle weak absolute
3461 // If UnwindTablesMandatory is set we cannot do this optimization; the
3462 // unwind info is to be available for non-EH uses.
3463 if (!EHFrameInfo.hasCalls &&
3464 !UnwindTablesMandatory &&
3465 ((linkage != Function::WeakAnyLinkage &&
3466 linkage != Function::WeakODRLinkage &&
3467 linkage != Function::LinkOnceAnyLinkage &&
3468 linkage != Function::LinkOnceODRLinkage) ||
3469 !TAI->getWeakDefDirective() ||
3470 TAI->getSupportsWeakOmittedEHFrame()))
3472 O << EHFrameInfo.FnName << " = 0\n";
3473 // This name has no connection to the function, so it might get
3474 // dead-stripped when the function is not, erroneously. Prohibit
3475 // dead-stripping unconditionally.
3476 if (const char *UsedDirective = TAI->getUsedDirective())
3477 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3479 O << EHFrameInfo.FnName << ":\n";
3482 EmitDifference("eh_frame_end", EHFrameInfo.Number,
3483 "eh_frame_begin", EHFrameInfo.Number, true);
3484 Asm->EOL("Length of Frame Information Entry");
3486 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
3488 if (TAI->doesRequireNonLocalEHFrameLabel()) {
3489 PrintRelDirective(true, true);
3490 PrintLabelName("eh_frame_begin", EHFrameInfo.Number);
3492 if (!TAI->isAbsoluteEHSectionOffsets())
3493 O << "-EH_frame" << EHFrameInfo.PersonalityIndex;
3495 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
3496 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
3500 Asm->EOL("FDE CIE offset");
3502 EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
3503 Asm->EOL("FDE initial location");
3504 EmitDifference("eh_func_end", EHFrameInfo.Number,
3505 "eh_func_begin", EHFrameInfo.Number, true);
3506 Asm->EOL("FDE address range");
3508 // If there is a personality and landing pads then point to the language
3509 // specific data area in the exception table.
3510 if (EHFrameInfo.PersonalityIndex) {
3511 Asm->EmitULEB128Bytes(4);
3512 Asm->EOL("Augmentation size");
3514 if (EHFrameInfo.hasLandingPads)
3515 EmitReference("exception", EHFrameInfo.Number, true, true);
3517 Asm->EmitInt32((int)0);
3518 Asm->EOL("Language Specific Data Area");
3520 Asm->EmitULEB128Bytes(0);
3521 Asm->EOL("Augmentation size");
3524 // Indicate locations of function specific callee saved registers in
3526 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves,
3529 // On Darwin the linker honors the alignment of eh_frame, which means it
3530 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3531 // you get holes which confuse readers of eh_frame.
3532 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3534 EmitLabel("eh_frame_end", EHFrameInfo.Number);
3536 // If the function is marked used, this table should be also. We cannot
3537 // make the mark unconditional in this case, since retaining the table
3538 // also retains the function in this case, and there is code around
3539 // that depends on unused functions (calling undefined externals) being
3540 // dead-stripped to link correctly. Yes, there really is.
3541 if (MMI->getUsedFunctions().count(EHFrameInfo.function))
3542 if (const char *UsedDirective = TAI->getUsedDirective())
3543 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3547 /// EmitExceptionTable - Emit landing pads and actions.
3549 /// The general organization of the table is complex, but the basic concepts
3550 /// are easy. First there is a header which describes the location and
3551 /// organization of the three components that follow.
3552 /// 1. The landing pad site information describes the range of code covered
3553 /// by the try. In our case it's an accumulation of the ranges covered
3554 /// by the invokes in the try. There is also a reference to the landing
3555 /// pad that handles the exception once processed. Finally an index into
3556 /// the actions table.
3557 /// 2. The action table, in our case, is composed of pairs of type ids
3558 /// and next action offset. Starting with the action index from the
3559 /// landing pad site, each type Id is checked for a match to the current
3560 /// exception. If it matches then the exception and type id are passed
3561 /// on to the landing pad. Otherwise the next action is looked up. This
3562 /// chain is terminated with a next action of zero. If no type id is
3563 /// found the the frame is unwound and handling continues.
3564 /// 3. Type id table contains references to all the C++ typeinfo for all
3565 /// catches in the function. This tables is reversed indexed base 1.
3567 /// SharedTypeIds - How many leading type ids two landing pads have in common.
3568 static unsigned SharedTypeIds(const LandingPadInfo *L,
3569 const LandingPadInfo *R) {
3570 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3571 unsigned LSize = LIds.size(), RSize = RIds.size();
3572 unsigned MinSize = LSize < RSize ? LSize : RSize;
3575 for (; Count != MinSize; ++Count)
3576 if (LIds[Count] != RIds[Count])
3582 /// PadLT - Order landing pads lexicographically by type id.
3583 static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
3584 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3585 unsigned LSize = LIds.size(), RSize = RIds.size();
3586 unsigned MinSize = LSize < RSize ? LSize : RSize;
3588 for (unsigned i = 0; i != MinSize; ++i)
3589 if (LIds[i] != RIds[i])
3590 return LIds[i] < RIds[i];
3592 return LSize < RSize;
3596 static inline unsigned getEmptyKey() { return -1U; }
3597 static inline unsigned getTombstoneKey() { return -2U; }
3598 static unsigned getHashValue(const unsigned &Key) { return Key; }
3599 static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
3600 static bool isPod() { return true; }
3603 /// ActionEntry - Structure describing an entry in the actions table.
3604 struct ActionEntry {
3605 int ValueForTypeID; // The value to write - may not be equal to the type id.
3607 struct ActionEntry *Previous;
3610 /// PadRange - Structure holding a try-range and the associated landing pad.
3612 // The index of the landing pad.
3614 // The index of the begin and end labels in the landing pad's label lists.
3615 unsigned RangeIndex;
3618 typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
3620 /// CallSiteEntry - Structure describing an entry in the call-site table.
3621 struct CallSiteEntry {
3622 // The 'try-range' is BeginLabel .. EndLabel.
3623 unsigned BeginLabel; // zero indicates the start of the function.
3624 unsigned EndLabel; // zero indicates the end of the function.
3625 // The landing pad starts at PadLabel.
3626 unsigned PadLabel; // zero indicates that there is no landing pad.
3630 void EmitExceptionTable() {
3631 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
3632 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
3633 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
3634 if (PadInfos.empty()) return;
3636 // Sort the landing pads in order of their type ids. This is used to fold
3637 // duplicate actions.
3638 SmallVector<const LandingPadInfo *, 64> LandingPads;
3639 LandingPads.reserve(PadInfos.size());
3640 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
3641 LandingPads.push_back(&PadInfos[i]);
3642 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
3644 // Negative type ids index into FilterIds, positive type ids index into
3645 // TypeInfos. The value written for a positive type id is just the type
3646 // id itself. For a negative type id, however, the value written is the
3647 // (negative) byte offset of the corresponding FilterIds entry. The byte
3648 // offset is usually equal to the type id, because the FilterIds entries
3649 // are written using a variable width encoding which outputs one byte per
3650 // entry as long as the value written is not too large, but can differ.
3651 // This kind of complication does not occur for positive type ids because
3652 // type infos are output using a fixed width encoding.
3653 // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
3654 SmallVector<int, 16> FilterOffsets;
3655 FilterOffsets.reserve(FilterIds.size());
3657 for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
3658 E = FilterIds.end(); I != E; ++I) {
3659 FilterOffsets.push_back(Offset);
3660 Offset -= TargetAsmInfo::getULEB128Size(*I);
3663 // Compute the actions table and gather the first action index for each
3664 // landing pad site.
3665 SmallVector<ActionEntry, 32> Actions;
3666 SmallVector<unsigned, 64> FirstActions;
3667 FirstActions.reserve(LandingPads.size());
3669 int FirstAction = 0;
3670 unsigned SizeActions = 0;
3671 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3672 const LandingPadInfo *LP = LandingPads[i];
3673 const std::vector<int> &TypeIds = LP->TypeIds;
3674 const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
3675 unsigned SizeSiteActions = 0;
3677 if (NumShared < TypeIds.size()) {
3678 unsigned SizeAction = 0;
3679 ActionEntry *PrevAction = 0;
3682 const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
3683 assert(Actions.size());
3684 PrevAction = &Actions.back();
3685 SizeAction = TargetAsmInfo::getSLEB128Size(PrevAction->NextAction) +
3686 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3687 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
3689 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3690 SizeAction += -PrevAction->NextAction;
3691 PrevAction = PrevAction->Previous;
3695 // Compute the actions.
3696 for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
3697 int TypeID = TypeIds[I];
3698 assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
3699 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
3700 unsigned SizeTypeID = TargetAsmInfo::getSLEB128Size(ValueForTypeID);
3702 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
3703 SizeAction = SizeTypeID + TargetAsmInfo::getSLEB128Size(NextAction);
3704 SizeSiteActions += SizeAction;
3706 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
3707 Actions.push_back(Action);
3709 PrevAction = &Actions.back();
3712 // Record the first action of the landing pad site.
3713 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
3714 } // else identical - re-use previous FirstAction
3716 FirstActions.push_back(FirstAction);
3718 // Compute this sites contribution to size.
3719 SizeActions += SizeSiteActions;
3722 // Compute the call-site table. The entry for an invoke has a try-range
3723 // containing the call, a non-zero landing pad and an appropriate action.
3724 // The entry for an ordinary call has a try-range containing the call and
3725 // zero for the landing pad and the action. Calls marked 'nounwind' have
3726 // no entry and must not be contained in the try-range of any entry - they
3727 // form gaps in the table. Entries must be ordered by try-range address.
3728 SmallVector<CallSiteEntry, 64> CallSites;
3730 RangeMapType PadMap;
3731 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
3732 // by try-range labels when lowered). Ordinary calls do not, so appropriate
3733 // try-ranges for them need be deduced.
3734 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3735 const LandingPadInfo *LandingPad = LandingPads[i];
3736 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
3737 unsigned BeginLabel = LandingPad->BeginLabels[j];
3738 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
3739 PadRange P = { i, j };
3740 PadMap[BeginLabel] = P;
3744 // The end label of the previous invoke or nounwind try-range.
3745 unsigned LastLabel = 0;
3747 // Whether there is a potentially throwing instruction (currently this means
3748 // an ordinary call) between the end of the previous try-range and now.
3749 bool SawPotentiallyThrowing = false;
3751 // Whether the last callsite entry was for an invoke.
3752 bool PreviousIsInvoke = false;
3754 // Visit all instructions in order of address.
3755 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
3757 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
3759 if (!MI->isLabel()) {
3760 SawPotentiallyThrowing |= MI->getDesc().isCall();
3764 unsigned BeginLabel = MI->getOperand(0).getImm();
3765 assert(BeginLabel && "Invalid label!");
3767 // End of the previous try-range?
3768 if (BeginLabel == LastLabel)
3769 SawPotentiallyThrowing = false;
3771 // Beginning of a new try-range?
3772 RangeMapType::iterator L = PadMap.find(BeginLabel);
3773 if (L == PadMap.end())
3774 // Nope, it was just some random label.
3777 PadRange P = L->second;
3778 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
3780 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
3781 "Inconsistent landing pad map!");
3783 // If some instruction between the previous try-range and this one may
3784 // throw, create a call-site entry with no landing pad for the region
3785 // between the try-ranges.
3786 if (SawPotentiallyThrowing) {
3787 CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
3788 CallSites.push_back(Site);
3789 PreviousIsInvoke = false;
3792 LastLabel = LandingPad->EndLabels[P.RangeIndex];
3793 assert(BeginLabel && LastLabel && "Invalid landing pad!");
3795 if (LandingPad->LandingPadLabel) {
3796 // This try-range is for an invoke.
3797 CallSiteEntry Site = {BeginLabel, LastLabel,
3798 LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
3800 // Try to merge with the previous call-site.
3801 if (PreviousIsInvoke) {
3802 CallSiteEntry &Prev = CallSites.back();
3803 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
3804 // Extend the range of the previous entry.
3805 Prev.EndLabel = Site.EndLabel;
3810 // Otherwise, create a new call-site.
3811 CallSites.push_back(Site);
3812 PreviousIsInvoke = true;
3815 PreviousIsInvoke = false;
3819 // If some instruction between the previous try-range and the end of the
3820 // function may throw, create a call-site entry with no landing pad for the
3821 // region following the try-range.
3822 if (SawPotentiallyThrowing) {
3823 CallSiteEntry Site = {LastLabel, 0, 0, 0};
3824 CallSites.push_back(Site);
3830 const unsigned SiteStartSize = sizeof(int32_t); // DW_EH_PE_udata4
3831 const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
3832 const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
3833 unsigned SizeSites = CallSites.size() * (SiteStartSize +
3836 for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
3837 SizeSites += TargetAsmInfo::getULEB128Size(CallSites[i].Action);
3840 const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
3841 unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
3843 unsigned TypeOffset = sizeof(int8_t) + // Call site format
3844 TargetAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
3845 SizeSites + SizeActions + SizeTypes;
3847 unsigned TotalSize = sizeof(int8_t) + // LPStart format
3848 sizeof(int8_t) + // TType format
3849 TargetAsmInfo::getULEB128Size(TypeOffset) + // TType base offset
3852 unsigned SizeAlign = (4 - TotalSize) & 3;
3854 // Begin the exception table.
3855 Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
3856 Asm->EmitAlignment(2, 0, 0, false);
3857 O << "GCC_except_table" << SubprogramCount << ":\n";
3858 for (unsigned i = 0; i != SizeAlign; ++i) {
3860 Asm->EOL("Padding");
3862 EmitLabel("exception", SubprogramCount);
3865 Asm->EmitInt8(DW_EH_PE_omit);
3866 Asm->EOL("LPStart format (DW_EH_PE_omit)");
3867 Asm->EmitInt8(DW_EH_PE_absptr);
3868 Asm->EOL("TType format (DW_EH_PE_absptr)");
3869 Asm->EmitULEB128Bytes(TypeOffset);
3870 Asm->EOL("TType base offset");
3871 Asm->EmitInt8(DW_EH_PE_udata4);
3872 Asm->EOL("Call site format (DW_EH_PE_udata4)");
3873 Asm->EmitULEB128Bytes(SizeSites);
3874 Asm->EOL("Call-site table length");
3876 // Emit the landing pad site information.
3877 for (unsigned i = 0; i < CallSites.size(); ++i) {
3878 CallSiteEntry &S = CallSites[i];
3879 const char *BeginTag;
3880 unsigned BeginNumber;
3882 if (!S.BeginLabel) {
3883 BeginTag = "eh_func_begin";
3884 BeginNumber = SubprogramCount;
3887 BeginNumber = S.BeginLabel;
3890 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
3892 Asm->EOL("Region start");
3895 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
3898 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
3900 Asm->EOL("Region length");
3905 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
3907 Asm->EOL("Landing pad");
3909 Asm->EmitULEB128Bytes(S.Action);
3913 // Emit the actions.
3914 for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
3915 ActionEntry &Action = Actions[I];
3917 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
3918 Asm->EOL("TypeInfo index");
3919 Asm->EmitSLEB128Bytes(Action.NextAction);
3920 Asm->EOL("Next action");
3923 // Emit the type ids.
3924 for (unsigned M = TypeInfos.size(); M; --M) {
3925 GlobalVariable *GV = TypeInfos[M - 1];
3927 PrintRelDirective();
3930 O << Asm->getGlobalLinkName(GV);
3934 Asm->EOL("TypeInfo");
3937 // Emit the filter typeids.
3938 for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
3939 unsigned TypeID = FilterIds[j];
3940 Asm->EmitULEB128Bytes(TypeID);
3941 Asm->EOL("Filter TypeInfo index");
3944 Asm->EmitAlignment(2, 0, 0, false);
3948 //===--------------------------------------------------------------------===//
3949 // Main entry points.
3951 DwarfException(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3952 : Dwarf(OS, A, T, "eh")
3953 , shouldEmitTable(false)
3954 , shouldEmitMoves(false)
3955 , shouldEmitTableModule(false)
3956 , shouldEmitMovesModule(false)
3959 virtual ~DwarfException() {}
3961 /// SetModuleInfo - Set machine module information when it's known that pass
3962 /// manager has created it. Set by the target AsmPrinter.
3963 void SetModuleInfo(MachineModuleInfo *mmi) {
3967 /// BeginModule - Emit all exception information that should come prior to the
3969 void BeginModule(Module *M) {
3973 /// EndModule - Emit all exception information that should come after the
3976 if (shouldEmitMovesModule || shouldEmitTableModule) {
3977 const std::vector<Function *> Personalities = MMI->getPersonalities();
3978 for (unsigned i = 0; i < Personalities.size(); ++i)
3979 EmitCommonEHFrame(Personalities[i], i);
3981 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
3982 E = EHFrames.end(); I != E; ++I)
3987 /// BeginFunction - Gather pre-function exception information. Assumes being
3988 /// emitted immediately after the function entry point.
3989 void BeginFunction(MachineFunction *MF) {
3991 shouldEmitTable = shouldEmitMoves = false;
3992 if (MMI && TAI->doesSupportExceptionHandling()) {
3994 // Map all labels and get rid of any dead landing pads.
3995 MMI->TidyLandingPads();
3996 // If any landing pads survive, we need an EH table.
3997 if (MMI->getLandingPads().size())
3998 shouldEmitTable = true;
4000 // See if we need frame move info.
4001 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
4002 shouldEmitMoves = true;
4004 if (shouldEmitMoves || shouldEmitTable)
4005 // Assumes in correct section after the entry point.
4006 EmitLabel("eh_func_begin", ++SubprogramCount);
4008 shouldEmitTableModule |= shouldEmitTable;
4009 shouldEmitMovesModule |= shouldEmitMoves;
4012 /// EndFunction - Gather and emit post-function exception information.
4014 void EndFunction() {
4015 if (shouldEmitMoves || shouldEmitTable) {
4016 EmitLabel("eh_func_end", SubprogramCount);
4017 EmitExceptionTable();
4019 // Save EH frame information
4021 push_back(FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
4023 MMI->getPersonalityIndex(),
4024 MF->getFrameInfo()->hasCalls(),
4025 !MMI->getLandingPads().empty(),
4026 MMI->getFrameMoves(),
4027 MF->getFunction()));
4032 } // End of namespace llvm
4034 //===----------------------------------------------------------------------===//
4036 /// Emit - Print the abbreviation using the specified Dwarf writer.
4038 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
4039 // Emit its Dwarf tag type.
4040 DD.getAsm()->EmitULEB128Bytes(Tag);
4041 DD.getAsm()->EOL(TagString(Tag));
4043 // Emit whether it has children DIEs.
4044 DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
4045 DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
4047 // For each attribute description.
4048 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4049 const DIEAbbrevData &AttrData = Data[i];
4051 // Emit attribute type.
4052 DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
4053 DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
4056 DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
4057 DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
4060 // Mark end of abbreviation.
4061 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
4062 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
4066 void DIEAbbrev::print(std::ostream &O) {
4067 O << "Abbreviation @"
4068 << std::hex << (intptr_t)this << std::dec
4072 << ChildrenString(ChildrenFlag)
4075 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4077 << AttributeString(Data[i].getAttribute())
4079 << FormEncodingString(Data[i].getForm())
4083 void DIEAbbrev::dump() { print(cerr); }
4086 //===----------------------------------------------------------------------===//
4089 void DIEValue::dump() {
4094 //===----------------------------------------------------------------------===//
4096 /// EmitValue - Emit integer of appropriate size.
4098 void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
4100 case DW_FORM_flag: // Fall thru
4101 case DW_FORM_ref1: // Fall thru
4102 case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer); break;
4103 case DW_FORM_ref2: // Fall thru
4104 case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer); break;
4105 case DW_FORM_ref4: // Fall thru
4106 case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer); break;
4107 case DW_FORM_ref8: // Fall thru
4108 case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer); break;
4109 case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
4110 case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
4111 default: assert(0 && "DIE Value form not supported yet"); break;
4115 /// SizeOf - Determine size of integer value in bytes.
4117 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4119 case DW_FORM_flag: // Fall thru
4120 case DW_FORM_ref1: // Fall thru
4121 case DW_FORM_data1: return sizeof(int8_t);
4122 case DW_FORM_ref2: // Fall thru
4123 case DW_FORM_data2: return sizeof(int16_t);
4124 case DW_FORM_ref4: // Fall thru
4125 case DW_FORM_data4: return sizeof(int32_t);
4126 case DW_FORM_ref8: // Fall thru
4127 case DW_FORM_data8: return sizeof(int64_t);
4128 case DW_FORM_udata: return TargetAsmInfo::getULEB128Size(Integer);
4129 case DW_FORM_sdata: return TargetAsmInfo::getSLEB128Size(Integer);
4130 default: assert(0 && "DIE Value form not supported yet"); break;
4135 //===----------------------------------------------------------------------===//
4137 /// EmitValue - Emit string value.
4139 void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
4140 DD.getAsm()->EmitString(String);
4143 //===----------------------------------------------------------------------===//
4145 /// EmitValue - Emit label value.
4147 void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4148 bool IsSmall = Form == DW_FORM_data4;
4149 DD.EmitReference(Label, false, IsSmall);
4152 /// SizeOf - Determine size of label value in bytes.
4154 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4155 if (Form == DW_FORM_data4) return 4;
4156 return DD.getTargetData()->getPointerSize();
4159 //===----------------------------------------------------------------------===//
4161 /// EmitValue - Emit label value.
4163 void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4164 bool IsSmall = Form == DW_FORM_data4;
4165 DD.EmitReference(Label, false, IsSmall);
4168 /// SizeOf - Determine size of label value in bytes.
4170 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4171 if (Form == DW_FORM_data4) return 4;
4172 return DD.getTargetData()->getPointerSize();
4175 //===----------------------------------------------------------------------===//
4177 /// EmitValue - Emit delta value.
4179 void DIESectionOffset::EmitValue(DwarfDebug &DD, unsigned Form) {
4180 bool IsSmall = Form == DW_FORM_data4;
4181 DD.EmitSectionOffset(Label.Tag, Section.Tag,
4182 Label.Number, Section.Number, IsSmall, IsEH, UseSet);
4185 /// SizeOf - Determine size of delta value in bytes.
4187 unsigned DIESectionOffset::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4188 if (Form == DW_FORM_data4) return 4;
4189 return DD.getTargetData()->getPointerSize();
4192 //===----------------------------------------------------------------------===//
4194 /// EmitValue - Emit delta value.
4196 void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
4197 bool IsSmall = Form == DW_FORM_data4;
4198 DD.EmitDifference(LabelHi, LabelLo, IsSmall);
4201 /// SizeOf - Determine size of delta value in bytes.
4203 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4204 if (Form == DW_FORM_data4) return 4;
4205 return DD.getTargetData()->getPointerSize();
4208 //===----------------------------------------------------------------------===//
4210 /// EmitValue - Emit debug information entry offset.
4212 void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
4213 DD.getAsm()->EmitInt32(Entry->getOffset());
4216 //===----------------------------------------------------------------------===//
4218 /// ComputeSize - calculate the size of the block.
4220 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
4222 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4224 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4225 Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
4231 /// EmitValue - Emit block data.
4233 void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
4235 case DW_FORM_block1: DD.getAsm()->EmitInt8(Size); break;
4236 case DW_FORM_block2: DD.getAsm()->EmitInt16(Size); break;
4237 case DW_FORM_block4: DD.getAsm()->EmitInt32(Size); break;
4238 case DW_FORM_block: DD.getAsm()->EmitULEB128Bytes(Size); break;
4239 default: assert(0 && "Improper form for block"); break;
4242 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4244 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4246 Values[i]->EmitValue(DD, AbbrevData[i].getForm());
4250 /// SizeOf - Determine size of block data in bytes.
4252 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4254 case DW_FORM_block1: return Size + sizeof(int8_t);
4255 case DW_FORM_block2: return Size + sizeof(int16_t);
4256 case DW_FORM_block4: return Size + sizeof(int32_t);
4257 case DW_FORM_block: return Size + TargetAsmInfo::getULEB128Size(Size);
4258 default: assert(0 && "Improper form for block"); break;
4263 //===----------------------------------------------------------------------===//
4264 /// DIE Implementation
4267 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4271 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
4273 void DIE::AddSiblingOffset() {
4274 DIEInteger *DI = new DIEInteger(0);
4275 Values.insert(Values.begin(), DI);
4276 Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
4279 /// Profile - Used to gather unique data for the value folding set.
4281 void DIE::Profile(FoldingSetNodeID &ID) {
4284 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4285 ID.AddPointer(Children[i]);
4287 for (unsigned j = 0, M = Values.size(); j < M; ++j)
4288 ID.AddPointer(Values[j]);
4292 void DIE::print(std::ostream &O, unsigned IncIndent) {
4293 static unsigned IndentCount = 0;
4294 IndentCount += IncIndent;
4295 const std::string Indent(IndentCount, ' ');
4296 bool isBlock = Abbrev.getTag() == 0;
4301 << "0x" << std::hex << (intptr_t)this << std::dec
4302 << ", Offset: " << Offset
4303 << ", Size: " << Size
4307 << TagString(Abbrev.getTag())
4309 << ChildrenString(Abbrev.getChildrenFlag());
4311 O << "Size: " << Size;
4315 const SmallVector<DIEAbbrevData, 8> &Data = Abbrev.getData();
4318 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4322 O << AttributeString(Data[i].getAttribute());
4324 O << "Blk[" << i << "]";
4327 << FormEncodingString(Data[i].getForm())
4329 Values[i]->print(O);
4334 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
4335 Children[j]->print(O, 4);
4338 if (!isBlock) O << "\n";
4339 IndentCount -= IncIndent;
4347 //===----------------------------------------------------------------------===//
4348 /// DwarfWriter Implementation
4351 DwarfWriter::DwarfWriter() : ImmutablePass(&ID), DD(NULL), DE(NULL) {
4354 DwarfWriter::~DwarfWriter() {
4359 /// BeginModule - Emit all Dwarf sections that should come prior to the
4361 void DwarfWriter::BeginModule(Module *M,
4362 MachineModuleInfo *MMI,
4363 raw_ostream &OS, AsmPrinter *A,
4364 const TargetAsmInfo *T) {
4365 DE = new DwarfException(OS, A, T);
4366 DD = new DwarfDebug(OS, A, T);
4369 DD->SetDebugInfo(MMI);
4370 DE->SetModuleInfo(MMI);
4373 /// EndModule - Emit all Dwarf sections that should come after the content.
4375 void DwarfWriter::EndModule() {
4380 /// BeginFunction - Gather pre-function debug information. Assumes being
4381 /// emitted immediately after the function entry point.
4382 void DwarfWriter::BeginFunction(MachineFunction *MF) {
4383 DE->BeginFunction(MF);
4384 DD->BeginFunction(MF);
4387 /// EndFunction - Gather and emit post-function debug information.
4389 void DwarfWriter::EndFunction(MachineFunction *MF) {
4390 DD->EndFunction(MF);
4393 if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI())
4394 // Clear function debug information.
4398 /// ValidDebugInfo - Return true if V represents valid debug info value.
4399 bool DwarfWriter::ValidDebugInfo(Value *V) {
4400 return DD && DD->ValidDebugInfo(V);
4403 /// RecordSourceLine - Records location information and associates it with a
4404 /// label. Returns a unique label ID used to generate a label and provide
4405 /// correspondence to the source line list.
4406 unsigned DwarfWriter::RecordSourceLine(unsigned Line, unsigned Col,
4408 return DD->RecordSourceLine(Line, Col, Src);
4411 /// getOrCreateSourceID - Look up the source id with the given directory and
4412 /// source file names. If none currently exists, create a new id and insert it
4413 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames maps
4415 unsigned DwarfWriter::getOrCreateSourceID(const std::string &DirName,
4416 const std::string &FileName) {
4417 return DD->getOrCreateSourceID(DirName, FileName);
4420 /// RecordRegionStart - Indicate the start of a region.
4421 unsigned DwarfWriter::RecordRegionStart(GlobalVariable *V) {
4422 return DD->RecordRegionStart(V);
4425 /// RecordRegionEnd - Indicate the end of a region.
4426 unsigned DwarfWriter::RecordRegionEnd(GlobalVariable *V) {
4427 return DD->RecordRegionEnd(V);
4430 /// getRecordSourceLineCount - Count source lines.
4431 unsigned DwarfWriter::getRecordSourceLineCount() {
4432 return DD->getRecordSourceLineCount();
4435 /// RecordVariable - Indicate the declaration of a local variable.
4437 void DwarfWriter::RecordVariable(GlobalVariable *GV, unsigned FrameIndex) {
4438 DD->RecordVariable(GV, FrameIndex);
4441 /// ShouldEmitDwarfDebug - Returns true if Dwarf debugging declarations should
4443 bool DwarfWriter::ShouldEmitDwarfDebug() const {
4444 return DD->ShouldEmitDwarfDebug();