1 //===-- llvm/CodeGen/DwarfWriter.cpp - Dwarf Framework ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf info into asm files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/DwarfWriter.h"
15 #include "llvm/Module.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Constants.h"
18 #include "llvm/CodeGen/AsmPrinter.h"
19 #include "llvm/CodeGen/MachineModuleInfo.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineLocation.h"
22 #include "llvm/Analysis/DebugInfo.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/Dwarf.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/DataTypes.h"
27 #include "llvm/Support/Mangler.h"
28 #include "llvm/Support/Timer.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/System/Path.h"
31 #include "llvm/Target/TargetAsmInfo.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Target/TargetFrameInfo.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/ADT/DenseMap.h"
39 #include "llvm/ADT/FoldingSet.h"
40 #include "llvm/ADT/StringExtras.h"
41 #include "llvm/ADT/StringMap.h"
45 using namespace llvm::dwarf;
47 static RegisterPass<DwarfWriter>
48 X("dwarfwriter", "DWARF Information Writer");
49 char DwarfWriter::ID = 0;
53 static TimerGroup *DwarfTimerGroup = 0;
54 static TimerGroup *getDwarfTimerGroup() {
55 if (DwarfTimerGroup) return DwarfTimerGroup;
56 return DwarfTimerGroup = new TimerGroup("Dwarf Exception and Debugging");
59 } // end anonymous namespace
63 //===----------------------------------------------------------------------===//
65 /// Configuration values for initial hash set sizes (log2).
67 static const unsigned InitDiesSetSize = 9; // log2(512)
68 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
69 static const unsigned InitValuesSetSize = 9; // log2(512)
71 //===----------------------------------------------------------------------===//
72 /// Forward declarations.
77 //===----------------------------------------------------------------------===//
80 /// getGlobalVariable - Return either a direct or cast Global value.
82 static GlobalVariable *getGlobalVariable(Value *V) {
83 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
85 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
86 if (CE->getOpcode() == Instruction::BitCast) {
87 return dyn_cast<GlobalVariable>(CE->getOperand(0));
88 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
89 for (unsigned int i=1; i<CE->getNumOperands(); i++) {
90 if (!CE->getOperand(i)->isNullValue())
93 return dyn_cast<GlobalVariable>(CE->getOperand(0));
99 //===----------------------------------------------------------------------===//
100 /// DWLabel - Labels are used to track locations in the assembler file.
101 /// Labels appear in the form @verbatim <prefix><Tag><Number> @endverbatim,
102 /// where the tag is a category of label (Ex. location) and number is a value
103 /// unique in that category.
106 /// Tag - Label category tag. Should always be a staticly declared C string.
110 /// Number - Value to make label unique.
114 DWLabel(const char *T, unsigned N) : Tag(T), Number(N) {}
116 void Profile(FoldingSetNodeID &ID) const {
118 ID.AddInteger(Number);
122 void print(std::ostream *O) const {
125 void print(std::ostream &O) const {
127 if (Number) O << Number;
132 //===----------------------------------------------------------------------===//
133 /// DIEAbbrevData - Dwarf abbreviation data, describes the one attribute of a
134 /// Dwarf abbreviation.
135 class DIEAbbrevData {
137 /// Attribute - Dwarf attribute code.
141 /// Form - Dwarf form code.
146 DIEAbbrevData(unsigned A, unsigned F)
152 unsigned getAttribute() const { return Attribute; }
153 unsigned getForm() const { return Form; }
155 /// Profile - Used to gather unique data for the abbreviation folding set.
157 void Profile(FoldingSetNodeID &ID)const {
158 ID.AddInteger(Attribute);
163 //===----------------------------------------------------------------------===//
164 /// DIEAbbrev - Dwarf abbreviation, describes the organization of a debug
165 /// information object.
166 class DIEAbbrev : public FoldingSetNode {
168 /// Tag - Dwarf tag code.
172 /// Unique number for node.
176 /// ChildrenFlag - Dwarf children flag.
178 unsigned ChildrenFlag;
180 /// Data - Raw data bytes for abbreviation.
182 SmallVector<DIEAbbrevData, 8> Data;
186 DIEAbbrev(unsigned T, unsigned C)
194 unsigned getTag() const { return Tag; }
195 unsigned getNumber() const { return Number; }
196 unsigned getChildrenFlag() const { return ChildrenFlag; }
197 const SmallVector<DIEAbbrevData, 8> &getData() const { return Data; }
198 void setTag(unsigned T) { Tag = T; }
199 void setChildrenFlag(unsigned CF) { ChildrenFlag = CF; }
200 void setNumber(unsigned N) { Number = N; }
202 /// AddAttribute - Adds another set of attribute information to the
204 void AddAttribute(unsigned Attribute, unsigned Form) {
205 Data.push_back(DIEAbbrevData(Attribute, Form));
208 /// AddFirstAttribute - Adds a set of attribute information to the front
209 /// of the abbreviation.
210 void AddFirstAttribute(unsigned Attribute, unsigned Form) {
211 Data.insert(Data.begin(), DIEAbbrevData(Attribute, Form));
214 /// Profile - Used to gather unique data for the abbreviation folding set.
216 void Profile(FoldingSetNodeID &ID) {
218 ID.AddInteger(ChildrenFlag);
220 // For each attribute description.
221 for (unsigned i = 0, N = Data.size(); i < N; ++i)
225 /// Emit - Print the abbreviation using the specified Dwarf writer.
227 void Emit(const DwarfDebug &DD) const;
230 void print(std::ostream *O) {
233 void print(std::ostream &O);
238 //===----------------------------------------------------------------------===//
239 /// DIE - A structured debug information entry. Has an abbreviation which
240 /// describes it's organization.
241 class DIE : public FoldingSetNode {
243 /// Abbrev - Buffer for constructing abbreviation.
247 /// Offset - Offset in debug info section.
251 /// Size - Size of instance + children.
257 std::vector<DIE *> Children;
259 /// Attributes values.
261 SmallVector<DIEValue*, 32> Values;
264 explicit DIE(unsigned Tag)
265 : Abbrev(Tag, DW_CHILDREN_no)
274 DIEAbbrev &getAbbrev() { return Abbrev; }
275 unsigned getAbbrevNumber() const {
276 return Abbrev.getNumber();
278 unsigned getTag() const { return Abbrev.getTag(); }
279 unsigned getOffset() const { return Offset; }
280 unsigned getSize() const { return Size; }
281 const std::vector<DIE *> &getChildren() const { return Children; }
282 SmallVector<DIEValue*, 32> &getValues() { return Values; }
283 void setTag(unsigned Tag) { Abbrev.setTag(Tag); }
284 void setOffset(unsigned O) { Offset = O; }
285 void setSize(unsigned S) { Size = S; }
287 /// AddValue - Add a value and attributes to a DIE.
289 void AddValue(unsigned Attribute, unsigned Form, DIEValue *Value) {
290 Abbrev.AddAttribute(Attribute, Form);
291 Values.push_back(Value);
294 /// SiblingOffset - Return the offset of the debug information entry's
296 unsigned SiblingOffset() const { return Offset + Size; }
298 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
300 void AddSiblingOffset();
302 /// AddChild - Add a child to the DIE.
304 void AddChild(DIE *Child) {
305 Abbrev.setChildrenFlag(DW_CHILDREN_yes);
306 Children.push_back(Child);
309 /// Detach - Detaches objects connected to it after copying.
315 /// Profile - Used to gather unique data for the value folding set.
317 void Profile(FoldingSetNodeID &ID) ;
320 void print(std::ostream *O, unsigned IncIndent = 0) {
321 if (O) print(*O, IncIndent);
323 void print(std::ostream &O, unsigned IncIndent = 0);
328 //===----------------------------------------------------------------------===//
329 /// DIEValue - A debug information entry value.
331 class DIEValue : public FoldingSetNode {
344 /// Type - Type of data stored in the value.
348 explicit DIEValue(unsigned T)
351 virtual ~DIEValue() {}
354 unsigned getType() const { return Type; }
356 // Implement isa/cast/dyncast.
357 static bool classof(const DIEValue *) { return true; }
359 /// EmitValue - Emit value via the Dwarf writer.
361 virtual void EmitValue(DwarfDebug &DD, unsigned Form) = 0;
363 /// SizeOf - Return the size of a value in bytes.
365 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const = 0;
367 /// Profile - Used to gather unique data for the value folding set.
369 virtual void Profile(FoldingSetNodeID &ID) = 0;
372 void print(std::ostream *O) {
375 virtual void print(std::ostream &O) = 0;
380 //===----------------------------------------------------------------------===//
381 /// DWInteger - An integer value DIE.
383 class DIEInteger : public DIEValue {
388 explicit DIEInteger(uint64_t I) : DIEValue(isInteger), Integer(I) {}
390 // Implement isa/cast/dyncast.
391 static bool classof(const DIEInteger *) { return true; }
392 static bool classof(const DIEValue *I) { return I->Type == isInteger; }
394 /// BestForm - Choose the best form for integer.
396 static unsigned BestForm(bool IsSigned, uint64_t Integer) {
398 if ((char)Integer == (signed)Integer) return DW_FORM_data1;
399 if ((short)Integer == (signed)Integer) return DW_FORM_data2;
400 if ((int)Integer == (signed)Integer) return DW_FORM_data4;
402 if ((unsigned char)Integer == Integer) return DW_FORM_data1;
403 if ((unsigned short)Integer == Integer) return DW_FORM_data2;
404 if ((unsigned int)Integer == Integer) return DW_FORM_data4;
406 return DW_FORM_data8;
409 /// EmitValue - Emit integer of appropriate size.
411 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
413 /// SizeOf - Determine size of integer value in bytes.
415 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
417 /// Profile - Used to gather unique data for the value folding set.
419 static void Profile(FoldingSetNodeID &ID, unsigned Integer) {
420 ID.AddInteger(isInteger);
421 ID.AddInteger(Integer);
423 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Integer); }
426 virtual void print(std::ostream &O) {
427 O << "Int: " << (int64_t)Integer
428 << " 0x" << std::hex << Integer << std::dec;
433 //===----------------------------------------------------------------------===//
434 /// DIEString - A string value DIE.
436 class DIEString : public DIEValue {
438 const std::string String;
440 explicit DIEString(const std::string &S) : DIEValue(isString), String(S) {}
442 // Implement isa/cast/dyncast.
443 static bool classof(const DIEString *) { return true; }
444 static bool classof(const DIEValue *S) { return S->Type == isString; }
446 /// EmitValue - Emit string value.
448 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
450 /// SizeOf - Determine size of string value in bytes.
452 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
453 return String.size() + sizeof(char); // sizeof('\0');
456 /// Profile - Used to gather unique data for the value folding set.
458 static void Profile(FoldingSetNodeID &ID, const std::string &String) {
459 ID.AddInteger(isString);
460 ID.AddString(String);
462 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, String); }
465 virtual void print(std::ostream &O) {
466 O << "Str: \"" << String << "\"";
471 //===----------------------------------------------------------------------===//
472 /// DIEDwarfLabel - A Dwarf internal label expression DIE.
474 class DIEDwarfLabel : public DIEValue {
479 explicit DIEDwarfLabel(const DWLabel &L) : DIEValue(isLabel), Label(L) {}
481 // Implement isa/cast/dyncast.
482 static bool classof(const DIEDwarfLabel *) { return true; }
483 static bool classof(const DIEValue *L) { return L->Type == isLabel; }
485 /// EmitValue - Emit label value.
487 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
489 /// SizeOf - Determine size of label value in bytes.
491 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
493 /// Profile - Used to gather unique data for the value folding set.
495 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label) {
496 ID.AddInteger(isLabel);
499 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
502 virtual void print(std::ostream &O) {
510 //===----------------------------------------------------------------------===//
511 /// DIEObjectLabel - A label to an object in code or data.
513 class DIEObjectLabel : public DIEValue {
515 const std::string Label;
517 explicit DIEObjectLabel(const std::string &L)
518 : DIEValue(isAsIsLabel), Label(L) {}
520 // Implement isa/cast/dyncast.
521 static bool classof(const DIEObjectLabel *) { return true; }
522 static bool classof(const DIEValue *L) { return L->Type == isAsIsLabel; }
524 /// EmitValue - Emit label value.
526 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
528 /// SizeOf - Determine size of label value in bytes.
530 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
532 /// Profile - Used to gather unique data for the value folding set.
534 static void Profile(FoldingSetNodeID &ID, const std::string &Label) {
535 ID.AddInteger(isAsIsLabel);
538 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label.c_str()); }
541 virtual void print(std::ostream &O) {
542 O << "Obj: " << Label;
547 //===----------------------------------------------------------------------===//
548 /// DIESectionOffset - A section offset DIE.
550 class DIESectionOffset : public DIEValue {
553 const DWLabel Section;
557 DIESectionOffset(const DWLabel &Lab, const DWLabel &Sec,
558 bool isEH = false, bool useSet = true)
559 : DIEValue(isSectionOffset), Label(Lab), Section(Sec),
560 IsEH(isEH), UseSet(useSet) {}
562 // Implement isa/cast/dyncast.
563 static bool classof(const DIESectionOffset *) { return true; }
564 static bool classof(const DIEValue *D) { return D->Type == isSectionOffset; }
566 /// EmitValue - Emit section offset.
568 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
570 /// SizeOf - Determine size of section offset value in bytes.
572 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
574 /// Profile - Used to gather unique data for the value folding set.
576 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label,
577 const DWLabel &Section) {
578 ID.AddInteger(isSectionOffset);
581 // IsEH and UseSet are specific to the Label/Section that we will emit
582 // the offset for; so Label/Section are enough for uniqueness.
584 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label, Section); }
587 virtual void print(std::ostream &O) {
592 O << "-" << IsEH << "-" << UseSet;
597 //===----------------------------------------------------------------------===//
598 /// DIEDelta - A simple label difference DIE.
600 class DIEDelta : public DIEValue {
602 const DWLabel LabelHi;
603 const DWLabel LabelLo;
605 DIEDelta(const DWLabel &Hi, const DWLabel &Lo)
606 : DIEValue(isDelta), LabelHi(Hi), LabelLo(Lo) {}
608 // Implement isa/cast/dyncast.
609 static bool classof(const DIEDelta *) { return true; }
610 static bool classof(const DIEValue *D) { return D->Type == isDelta; }
612 /// EmitValue - Emit delta value.
614 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
616 /// SizeOf - Determine size of delta value in bytes.
618 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
620 /// Profile - Used to gather unique data for the value folding set.
622 static void Profile(FoldingSetNodeID &ID, const DWLabel &LabelHi,
623 const DWLabel &LabelLo) {
624 ID.AddInteger(isDelta);
628 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, LabelHi, LabelLo); }
631 virtual void print(std::ostream &O) {
640 //===----------------------------------------------------------------------===//
641 /// DIEntry - A pointer to another debug information entry. An instance of this
642 /// class can also be used as a proxy for a debug information entry not yet
643 /// defined (ie. types.)
644 class DIEntry : public DIEValue {
648 explicit DIEntry(DIE *E) : DIEValue(isEntry), Entry(E) {}
650 // Implement isa/cast/dyncast.
651 static bool classof(const DIEntry *) { return true; }
652 static bool classof(const DIEValue *E) { return E->Type == isEntry; }
654 /// EmitValue - Emit debug information entry offset.
656 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
658 /// SizeOf - Determine size of debug information entry in bytes.
660 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
661 return sizeof(int32_t);
664 /// Profile - Used to gather unique data for the value folding set.
666 static void Profile(FoldingSetNodeID &ID, DIE *Entry) {
667 ID.AddInteger(isEntry);
668 ID.AddPointer(Entry);
670 virtual void Profile(FoldingSetNodeID &ID) {
671 ID.AddInteger(isEntry);
674 ID.AddPointer(Entry);
681 virtual void print(std::ostream &O) {
682 O << "Die: 0x" << std::hex << (intptr_t)Entry << std::dec;
687 //===----------------------------------------------------------------------===//
688 /// DIEBlock - A block of values. Primarily used for location expressions.
690 class DIEBlock : public DIEValue, public DIE {
692 unsigned Size; // Size in bytes excluding size header.
702 // Implement isa/cast/dyncast.
703 static bool classof(const DIEBlock *) { return true; }
704 static bool classof(const DIEValue *E) { return E->Type == isBlock; }
706 /// ComputeSize - calculate the size of the block.
708 unsigned ComputeSize(DwarfDebug &DD);
710 /// BestForm - Choose the best form for data.
712 unsigned BestForm() const {
713 if ((unsigned char)Size == Size) return DW_FORM_block1;
714 if ((unsigned short)Size == Size) return DW_FORM_block2;
715 if ((unsigned int)Size == Size) return DW_FORM_block4;
716 return DW_FORM_block;
719 /// EmitValue - Emit block data.
721 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
723 /// SizeOf - Determine size of block data in bytes.
725 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
728 /// Profile - Used to gather unique data for the value folding set.
730 virtual void Profile(FoldingSetNodeID &ID) {
731 ID.AddInteger(isBlock);
736 virtual void print(std::ostream &O) {
743 //===----------------------------------------------------------------------===//
744 /// CompileUnit - This dwarf writer support class manages information associate
745 /// with a source file.
748 /// ID - File identifier for source.
752 /// Die - Compile unit debug information entry.
756 /// GVToDieMap - Tracks the mapping of unit level debug informaton
757 /// variables to debug information entries.
758 std::map<GlobalVariable *, DIE *> GVToDieMap;
760 /// GVToDIEntryMap - Tracks the mapping of unit level debug informaton
761 /// descriptors to debug information entries using a DIEntry proxy.
762 std::map<GlobalVariable *, DIEntry *> GVToDIEntryMap;
764 /// Globals - A map of globally visible named entities for this unit.
766 std::map<std::string, DIE *> Globals;
768 /// DiesSet - Used to uniquely define dies within the compile unit.
770 FoldingSet<DIE> DiesSet;
773 CompileUnit(unsigned I, DIE *D)
774 : ID(I), Die(D), GVToDieMap(),
775 GVToDIEntryMap(), Globals(), DiesSet(InitDiesSetSize)
783 unsigned getID() const { return ID; }
784 DIE* getDie() const { return Die; }
785 std::map<std::string, DIE *> &getGlobals() { return Globals; }
787 /// hasContent - Return true if this compile unit has something to write out.
789 bool hasContent() const {
790 return !Die->getChildren().empty();
793 /// AddGlobal - Add a new global entity to the compile unit.
795 void AddGlobal(const std::string &Name, DIE *Die) {
799 /// getDieMapSlotFor - Returns the debug information entry map slot for the
800 /// specified debug variable.
801 DIE *&getDieMapSlotFor(GlobalVariable *GV) {
802 return GVToDieMap[GV];
805 /// getDIEntrySlotFor - Returns the debug information entry proxy slot for the
806 /// specified debug variable.
807 DIEntry *&getDIEntrySlotFor(GlobalVariable *GV) {
808 return GVToDIEntryMap[GV];
811 /// AddDie - Adds or interns the DIE to the compile unit.
813 DIE *AddDie(DIE &Buffer) {
817 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
820 Die = new DIE(Buffer);
821 DiesSet.InsertNode(Die, Where);
822 this->Die->AddChild(Die);
830 //===----------------------------------------------------------------------===//
831 /// Dwarf - Emits general Dwarf directives.
835 //===--------------------------------------------------------------------===//
836 // Core attributes used by the Dwarf writer.
840 /// O - Stream to .s file.
844 /// Asm - Target of Dwarf emission.
848 /// TAI - Target asm information.
849 const TargetAsmInfo *TAI;
851 /// TD - Target data.
852 const TargetData *TD;
854 /// RI - Register Information.
855 const TargetRegisterInfo *RI;
857 /// M - Current module.
861 /// MF - Current machine function.
865 /// MMI - Collected machine module information.
867 MachineModuleInfo *MMI;
869 /// SubprogramCount - The running count of functions being compiled.
871 unsigned SubprogramCount;
873 /// Flavor - A unique string indicating what dwarf producer this is, used to
875 const char * const Flavor;
878 Dwarf(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T,
883 , TD(Asm->TM.getTargetData())
884 , RI(Asm->TM.getRegisterInfo())
895 //===--------------------------------------------------------------------===//
898 AsmPrinter *getAsm() const { return Asm; }
899 MachineModuleInfo *getMMI() const { return MMI; }
900 const TargetAsmInfo *getTargetAsmInfo() const { return TAI; }
901 const TargetData *getTargetData() const { return TD; }
903 void PrintRelDirective(bool Force32Bit = false, bool isInSection = false)
905 if (isInSection && TAI->getDwarfSectionOffsetDirective())
906 O << TAI->getDwarfSectionOffsetDirective();
907 else if (Force32Bit || TD->getPointerSize() == sizeof(int32_t))
908 O << TAI->getData32bitsDirective();
910 O << TAI->getData64bitsDirective();
913 /// PrintLabelName - Print label name in form used by Dwarf writer.
915 void PrintLabelName(DWLabel Label) const {
916 PrintLabelName(Label.Tag, Label.Number);
918 void PrintLabelName(const char *Tag, unsigned Number) const {
919 O << TAI->getPrivateGlobalPrefix() << Tag;
920 if (Number) O << Number;
923 void PrintLabelName(const char *Tag, unsigned Number,
924 const char *Suffix) const {
925 O << TAI->getPrivateGlobalPrefix() << Tag;
926 if (Number) O << Number;
930 /// EmitLabel - Emit location label for internal use by Dwarf.
932 void EmitLabel(DWLabel Label) const {
933 EmitLabel(Label.Tag, Label.Number);
935 void EmitLabel(const char *Tag, unsigned Number) const {
936 PrintLabelName(Tag, Number);
940 /// EmitReference - Emit a reference to a label.
942 void EmitReference(DWLabel Label, bool IsPCRelative = false,
943 bool Force32Bit = false) const {
944 EmitReference(Label.Tag, Label.Number, IsPCRelative, Force32Bit);
946 void EmitReference(const char *Tag, unsigned Number,
947 bool IsPCRelative = false, bool Force32Bit = false) const {
948 PrintRelDirective(Force32Bit);
949 PrintLabelName(Tag, Number);
951 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
953 void EmitReference(const std::string &Name, bool IsPCRelative = false,
954 bool Force32Bit = false) const {
955 PrintRelDirective(Force32Bit);
959 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
962 /// EmitDifference - Emit the difference between two labels. Some
963 /// assemblers do not behave with absolute expressions with data directives,
964 /// so there is an option (needsSet) to use an intermediary set expression.
965 void EmitDifference(DWLabel LabelHi, DWLabel LabelLo,
966 bool IsSmall = false) {
967 EmitDifference(LabelHi.Tag, LabelHi.Number,
968 LabelLo.Tag, LabelLo.Number,
971 void EmitDifference(const char *TagHi, unsigned NumberHi,
972 const char *TagLo, unsigned NumberLo,
973 bool IsSmall = false) {
974 if (TAI->needsSet()) {
976 PrintLabelName("set", SetCounter, Flavor);
978 PrintLabelName(TagHi, NumberHi);
980 PrintLabelName(TagLo, NumberLo);
983 PrintRelDirective(IsSmall);
984 PrintLabelName("set", SetCounter, Flavor);
987 PrintRelDirective(IsSmall);
989 PrintLabelName(TagHi, NumberHi);
991 PrintLabelName(TagLo, NumberLo);
995 void EmitSectionOffset(const char* Label, const char* Section,
996 unsigned LabelNumber, unsigned SectionNumber,
997 bool IsSmall = false, bool isEH = false,
998 bool useSet = true) {
999 bool printAbsolute = false;
1001 printAbsolute = TAI->isAbsoluteEHSectionOffsets();
1003 printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
1005 if (TAI->needsSet() && useSet) {
1007 PrintLabelName("set", SetCounter, Flavor);
1009 PrintLabelName(Label, LabelNumber);
1011 if (!printAbsolute) {
1013 PrintLabelName(Section, SectionNumber);
1017 PrintRelDirective(IsSmall);
1019 PrintLabelName("set", SetCounter, Flavor);
1022 PrintRelDirective(IsSmall, true);
1024 PrintLabelName(Label, LabelNumber);
1026 if (!printAbsolute) {
1028 PrintLabelName(Section, SectionNumber);
1033 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
1035 void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
1036 const std::vector<MachineMove> &Moves, bool isEH) {
1038 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
1039 TargetFrameInfo::StackGrowsUp ?
1040 TD->getPointerSize() : -TD->getPointerSize();
1041 bool IsLocal = BaseLabel && strcmp(BaseLabel, "label") == 0;
1043 for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
1044 const MachineMove &Move = Moves[i];
1045 unsigned LabelID = Move.getLabelID();
1048 LabelID = MMI->MappedLabel(LabelID);
1050 // Throw out move if the label is invalid.
1051 if (!LabelID) continue;
1054 const MachineLocation &Dst = Move.getDestination();
1055 const MachineLocation &Src = Move.getSource();
1057 // Advance row if new location.
1058 if (BaseLabel && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
1059 Asm->EmitInt8(DW_CFA_advance_loc4);
1060 Asm->EOL("DW_CFA_advance_loc4");
1061 EmitDifference("label", LabelID, BaseLabel, BaseLabelID, true);
1064 BaseLabelID = LabelID;
1065 BaseLabel = "label";
1069 // If advancing cfa.
1070 if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
1072 if (Src.getReg() == MachineLocation::VirtualFP) {
1073 Asm->EmitInt8(DW_CFA_def_cfa_offset);
1074 Asm->EOL("DW_CFA_def_cfa_offset");
1076 Asm->EmitInt8(DW_CFA_def_cfa);
1077 Asm->EOL("DW_CFA_def_cfa");
1078 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getReg(), isEH));
1079 Asm->EOL("Register");
1082 int Offset = -Src.getOffset();
1084 Asm->EmitULEB128Bytes(Offset);
1087 assert(0 && "Machine move no supported yet.");
1089 } else if (Src.isReg() &&
1090 Src.getReg() == MachineLocation::VirtualFP) {
1092 Asm->EmitInt8(DW_CFA_def_cfa_register);
1093 Asm->EOL("DW_CFA_def_cfa_register");
1094 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getReg(), isEH));
1095 Asm->EOL("Register");
1097 assert(0 && "Machine move no supported yet.");
1100 unsigned Reg = RI->getDwarfRegNum(Src.getReg(), isEH);
1101 int Offset = Dst.getOffset() / stackGrowth;
1104 Asm->EmitInt8(DW_CFA_offset_extended_sf);
1105 Asm->EOL("DW_CFA_offset_extended_sf");
1106 Asm->EmitULEB128Bytes(Reg);
1108 Asm->EmitSLEB128Bytes(Offset);
1110 } else if (Reg < 64) {
1111 Asm->EmitInt8(DW_CFA_offset + Reg);
1113 Asm->EOL("DW_CFA_offset + Reg (" + utostr(Reg) + ")");
1116 Asm->EmitULEB128Bytes(Offset);
1119 Asm->EmitInt8(DW_CFA_offset_extended);
1120 Asm->EOL("DW_CFA_offset_extended");
1121 Asm->EmitULEB128Bytes(Reg);
1123 Asm->EmitULEB128Bytes(Offset);
1132 //===----------------------------------------------------------------------===//
1133 /// SrcLineInfo - This class is used to record source line correspondence.
1136 unsigned Line; // Source line number.
1137 unsigned Column; // Source column.
1138 unsigned SourceID; // Source ID number.
1139 unsigned LabelID; // Label in code ID number.
1141 SrcLineInfo(unsigned L, unsigned C, unsigned S, unsigned I)
1142 : Line(L), Column(C), SourceID(S), LabelID(I) {}
1145 unsigned getLine() const { return Line; }
1146 unsigned getColumn() const { return Column; }
1147 unsigned getSourceID() const { return SourceID; }
1148 unsigned getLabelID() const { return LabelID; }
1151 //===----------------------------------------------------------------------===//
1152 /// DbgVariable - This class is used to track local variable information.
1155 DIVariable Var; // Variable Descriptor.
1156 unsigned FrameIndex; // Variable frame index.
1158 DbgVariable(DIVariable V, unsigned I) : Var(V), FrameIndex(I) {}
1161 DIVariable getVariable() const { return Var; }
1162 unsigned getFrameIndex() const { return FrameIndex; }
1165 //===----------------------------------------------------------------------===//
1166 /// DbgScope - This class is used to track scope information.
1169 DbgScope *Parent; // Parent to this scope.
1170 DIDescriptor Desc; // Debug info descriptor for scope.
1171 // Either subprogram or block.
1172 unsigned StartLabelID; // Label ID of the beginning of scope.
1173 unsigned EndLabelID; // Label ID of the end of scope.
1174 SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope.
1175 SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
1177 DbgScope(DbgScope *P, DIDescriptor D)
1178 : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0), Scopes(), Variables()
1181 for (unsigned i = 0, N = Scopes.size(); i < N; ++i) delete Scopes[i];
1182 for (unsigned j = 0, M = Variables.size(); j < M; ++j) delete Variables[j];
1186 DbgScope *getParent() const { return Parent; }
1187 DIDescriptor getDesc() const { return Desc; }
1188 unsigned getStartLabelID() const { return StartLabelID; }
1189 unsigned getEndLabelID() const { return EndLabelID; }
1190 SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
1191 SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
1192 void setStartLabelID(unsigned S) { StartLabelID = S; }
1193 void setEndLabelID(unsigned E) { EndLabelID = E; }
1195 /// AddScope - Add a scope to the scope.
1197 void AddScope(DbgScope *S) { Scopes.push_back(S); }
1199 /// AddVariable - Add a variable to the scope.
1201 void AddVariable(DbgVariable *V) { Variables.push_back(V); }
1204 //===----------------------------------------------------------------------===//
1205 /// DwarfDebug - Emits Dwarf debug directives.
1207 class DwarfDebug : public Dwarf {
1208 //===--------------------------------------------------------------------===//
1209 // Attributes used to construct specific Dwarf sections.
1212 /// CompileUnitMap - A map of global variables representing compile units to
1214 DenseMap<Value *, CompileUnit *> CompileUnitMap;
1216 /// CompileUnits - All the compile units in this module.
1218 SmallVector<CompileUnit *, 8> CompileUnits;
1220 /// MainCU - Some platform prefers one compile unit per .o file. In such
1221 /// cases, all dies are inserted in MainCU.
1222 CompileUnit *MainCU;
1224 /// AbbreviationsSet - Used to uniquely define abbreviations.
1226 FoldingSet<DIEAbbrev> AbbreviationsSet;
1228 /// Abbreviations - A list of all the unique abbreviations in use.
1230 std::vector<DIEAbbrev *> Abbreviations;
1232 /// DirectoryIdMap - Directory name to directory id map.
1234 StringMap<unsigned> DirectoryIdMap;
1236 /// DirectoryNames - A list of directory names.
1237 SmallVector<std::string, 8> DirectoryNames;
1239 /// SourceFileIdMap - Source file name to source file id map.
1241 StringMap<unsigned> SourceFileIdMap;
1243 /// SourceFileNames - A list of source file names.
1244 SmallVector<std::string, 8> SourceFileNames;
1246 /// SourceIdMap - Source id map, i.e. pair of directory id and source file
1247 /// id mapped to a unique id.
1248 DenseMap<std::pair<unsigned, unsigned>, unsigned> SourceIdMap;
1250 /// SourceIds - Reverse map from source id to directory id + file id pair.
1252 SmallVector<std::pair<unsigned, unsigned>, 8> SourceIds;
1254 /// Lines - List of of source line correspondence.
1255 std::vector<SrcLineInfo> Lines;
1257 /// ValuesSet - Used to uniquely define values.
1259 FoldingSet<DIEValue> ValuesSet;
1261 /// Values - A list of all the unique values in use.
1263 std::vector<DIEValue *> Values;
1265 /// StringPool - A UniqueVector of strings used by indirect references.
1267 UniqueVector<std::string> StringPool;
1269 /// SectionMap - Provides a unique id per text section.
1271 UniqueVector<const Section*> SectionMap;
1273 /// SectionSourceLines - Tracks line numbers per text section.
1275 std::vector<std::vector<SrcLineInfo> > SectionSourceLines;
1277 /// didInitial - Flag to indicate if initial emission has been done.
1281 /// shouldEmit - Flag to indicate if debug information should be emitted.
1285 // RootDbgScope - Top level scope for the current function.
1287 DbgScope *RootDbgScope;
1289 /// DbgScopeMap - Tracks the scopes in the current function.
1290 DenseMap<GlobalVariable *, DbgScope *> DbgScopeMap;
1292 /// DebugTimer - Timer for the Dwarf debug writer.
1295 struct FunctionDebugFrameInfo {
1297 std::vector<MachineMove> Moves;
1299 FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
1300 Number(Num), Moves(M) { }
1303 std::vector<FunctionDebugFrameInfo> DebugFrames;
1306 /// getSourceDirectoryAndFileIds - Return the directory and file ids that
1307 /// maps to the source id. Source id starts at 1.
1308 std::pair<unsigned, unsigned>
1309 getSourceDirectoryAndFileIds(unsigned SId) const {
1310 return SourceIds[SId-1];
1313 /// getNumSourceDirectories - Return the number of source directories in the
1315 unsigned getNumSourceDirectories() const {
1316 return DirectoryNames.size();
1319 /// getSourceDirectoryName - Return the name of the directory corresponding
1321 const std::string &getSourceDirectoryName(unsigned Id) const {
1322 return DirectoryNames[Id - 1];
1325 /// getSourceFileName - Return the name of the source file corresponding
1327 const std::string &getSourceFileName(unsigned Id) const {
1328 return SourceFileNames[Id - 1];
1331 /// getNumSourceIds - Return the number of unique source ids.
1332 unsigned getNumSourceIds() const {
1333 return SourceIds.size();
1336 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1338 void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1339 // Profile the node so that we can make it unique.
1340 FoldingSetNodeID ID;
1343 // Check the set for priors.
1344 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1346 // If it's newly added.
1347 if (InSet == &Abbrev) {
1348 // Add to abbreviation list.
1349 Abbreviations.push_back(&Abbrev);
1350 // Assign the vector position + 1 as its number.
1351 Abbrev.setNumber(Abbreviations.size());
1353 // Assign existing abbreviation number.
1354 Abbrev.setNumber(InSet->getNumber());
1358 /// NewString - Add a string to the constant pool and returns a label.
1360 DWLabel NewString(const std::string &String) {
1361 unsigned StringID = StringPool.insert(String);
1362 return DWLabel("string", StringID);
1365 /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1367 DIEntry *NewDIEntry(DIE *Entry = NULL) {
1371 FoldingSetNodeID ID;
1372 DIEntry::Profile(ID, Entry);
1374 Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1376 if (Value) return Value;
1378 Value = new DIEntry(Entry);
1379 ValuesSet.InsertNode(Value, Where);
1381 Value = new DIEntry(Entry);
1384 Values.push_back(Value);
1388 /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1390 void SetDIEntry(DIEntry *Value, DIE *Entry) {
1391 Value->Entry = Entry;
1392 // Add to values set if not already there. If it is, we merely have a
1393 // duplicate in the values list (no harm.)
1394 ValuesSet.GetOrInsertNode(Value);
1397 /// AddUInt - Add an unsigned integer attribute data and value.
1399 void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1400 if (!Form) Form = DIEInteger::BestForm(false, Integer);
1402 FoldingSetNodeID ID;
1403 DIEInteger::Profile(ID, Integer);
1405 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1407 Value = new DIEInteger(Integer);
1408 ValuesSet.InsertNode(Value, Where);
1409 Values.push_back(Value);
1412 Die->AddValue(Attribute, Form, Value);
1415 /// AddSInt - Add an signed integer attribute data and value.
1417 void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1418 if (!Form) Form = DIEInteger::BestForm(true, Integer);
1420 FoldingSetNodeID ID;
1421 DIEInteger::Profile(ID, (uint64_t)Integer);
1423 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1425 Value = new DIEInteger(Integer);
1426 ValuesSet.InsertNode(Value, Where);
1427 Values.push_back(Value);
1430 Die->AddValue(Attribute, Form, Value);
1433 /// AddString - Add a string attribute data and value.
1435 void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1436 const std::string &String) {
1437 FoldingSetNodeID ID;
1438 DIEString::Profile(ID, String);
1440 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1442 Value = new DIEString(String);
1443 ValuesSet.InsertNode(Value, Where);
1444 Values.push_back(Value);
1447 Die->AddValue(Attribute, Form, Value);
1450 /// AddLabel - Add a Dwarf label attribute data and value.
1452 void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1453 const DWLabel &Label) {
1454 FoldingSetNodeID ID;
1455 DIEDwarfLabel::Profile(ID, Label);
1457 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1459 Value = new DIEDwarfLabel(Label);
1460 ValuesSet.InsertNode(Value, Where);
1461 Values.push_back(Value);
1464 Die->AddValue(Attribute, Form, Value);
1467 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1469 void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1470 const std::string &Label) {
1471 FoldingSetNodeID ID;
1472 DIEObjectLabel::Profile(ID, Label);
1474 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1476 Value = new DIEObjectLabel(Label);
1477 ValuesSet.InsertNode(Value, Where);
1478 Values.push_back(Value);
1481 Die->AddValue(Attribute, Form, Value);
1484 /// AddSectionOffset - Add a section offset label attribute data and value.
1486 void AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
1487 const DWLabel &Label, const DWLabel &Section,
1488 bool isEH = false, bool useSet = true) {
1489 FoldingSetNodeID ID;
1490 DIESectionOffset::Profile(ID, Label, Section);
1492 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1494 Value = new DIESectionOffset(Label, Section, isEH, useSet);
1495 ValuesSet.InsertNode(Value, Where);
1496 Values.push_back(Value);
1499 Die->AddValue(Attribute, Form, Value);
1502 /// AddDelta - Add a label delta attribute data and value.
1504 void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1505 const DWLabel &Hi, const DWLabel &Lo) {
1506 FoldingSetNodeID ID;
1507 DIEDelta::Profile(ID, Hi, Lo);
1509 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1511 Value = new DIEDelta(Hi, Lo);
1512 ValuesSet.InsertNode(Value, Where);
1513 Values.push_back(Value);
1516 Die->AddValue(Attribute, Form, Value);
1519 /// AddDIEntry - Add a DIE attribute data and value.
1521 void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1522 Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1525 /// AddBlock - Add block data.
1527 void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1528 Block->ComputeSize(*this);
1529 FoldingSetNodeID ID;
1532 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1535 ValuesSet.InsertNode(Value, Where);
1536 Values.push_back(Value);
1538 // Already exists, reuse the previous one.
1540 Block = cast<DIEBlock>(Value);
1543 Die->AddValue(Attribute, Block->BestForm(), Value);
1546 /// AddSourceLine - Add location information to specified debug information
1548 void AddSourceLine(DIE *Die, const DIVariable *V) {
1549 unsigned FileID = 0;
1550 unsigned Line = V->getLineNumber();
1551 CompileUnit *Unit = FindCompileUnit(V->getCompileUnit());
1552 FileID = Unit->getID();
1553 assert (FileID && "Invalid file id");
1554 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1555 AddUInt(Die, DW_AT_decl_line, 0, Line);
1558 /// AddSourceLine - Add location information to specified debug information
1560 void AddSourceLine(DIE *Die, const DIGlobal *G) {
1561 unsigned FileID = 0;
1562 unsigned Line = G->getLineNumber();
1563 CompileUnit *Unit = FindCompileUnit(G->getCompileUnit());
1564 FileID = Unit->getID();
1565 assert (FileID && "Invalid file id");
1566 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1567 AddUInt(Die, DW_AT_decl_line, 0, Line);
1570 void AddSourceLine(DIE *Die, const DIType *Ty) {
1571 unsigned FileID = 0;
1572 unsigned Line = Ty->getLineNumber();
1573 DICompileUnit CU = Ty->getCompileUnit();
1576 CompileUnit *Unit = FindCompileUnit(CU);
1577 FileID = Unit->getID();
1578 assert (FileID && "Invalid file id");
1579 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1580 AddUInt(Die, DW_AT_decl_line, 0, Line);
1583 /// AddAddress - Add an address attribute to a die based on the location
1585 void AddAddress(DIE *Die, unsigned Attribute,
1586 const MachineLocation &Location) {
1587 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
1588 DIEBlock *Block = new DIEBlock();
1590 if (Location.isReg()) {
1592 AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1594 AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1595 AddUInt(Block, 0, DW_FORM_udata, Reg);
1599 AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1601 AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1602 AddUInt(Block, 0, DW_FORM_udata, Reg);
1604 AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1607 AddBlock(Die, Attribute, 0, Block);
1610 /// AddType - Add a new type attribute to the specified entity.
1611 void AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
1615 // Check for pre-existence.
1616 DIEntry *&Slot = DW_Unit->getDIEntrySlotFor(Ty.getGV());
1617 // If it exists then use the existing value.
1619 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1624 Slot = NewDIEntry();
1627 DIE Buffer(DW_TAG_base_type);
1628 if (Ty.isBasicType(Ty.getTag()))
1629 ConstructTypeDIE(DW_Unit, Buffer, DIBasicType(Ty.getGV()));
1630 else if (Ty.isDerivedType(Ty.getTag()))
1631 ConstructTypeDIE(DW_Unit, Buffer, DIDerivedType(Ty.getGV()));
1633 assert(Ty.isCompositeType(Ty.getTag()) && "Unknown kind of DIType");
1634 ConstructTypeDIE(DW_Unit, Buffer, DICompositeType(Ty.getGV()));
1637 // Add debug information entry to entity and appropriate context.
1639 DIDescriptor Context = Ty.getContext();
1640 if (!Context.isNull())
1641 Die = DW_Unit->getDieMapSlotFor(Context.getGV());
1644 DIE *Child = new DIE(Buffer);
1645 Die->AddChild(Child);
1647 SetDIEntry(Slot, Child);
1649 Die = DW_Unit->AddDie(Buffer);
1650 SetDIEntry(Slot, Die);
1653 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1656 /// ConstructTypeDIE - Construct basic type die from DIBasicType.
1657 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1660 // Get core information.
1663 Buffer.setTag(DW_TAG_base_type);
1664 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BTy.getEncoding());
1665 // Add name if not anonymous or intermediate type.
1667 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1668 uint64_t Size = BTy.getSizeInBits() >> 3;
1669 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1672 /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
1673 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1674 DIDerivedType DTy) {
1676 // Get core information.
1679 uint64_t Size = DTy.getSizeInBits() >> 3;
1680 unsigned Tag = DTy.getTag();
1682 // FIXME - Workaround for templates.
1683 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1687 // Map to main type, void will not have a type.
1688 DIType FromTy = DTy.getTypeDerivedFrom();
1689 AddType(DW_Unit, &Buffer, FromTy);
1691 // Add name if not anonymous or intermediate type.
1693 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1695 // Add size if non-zero (derived types might be zero-sized.)
1697 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1699 // Add source line info if available and TyDesc is not a forward
1701 if (!DTy.isForwardDecl())
1702 AddSourceLine(&Buffer, &DTy);
1705 /// ConstructTypeDIE - Construct type DIE from DICompositeType.
1706 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1707 DICompositeType CTy) {
1708 // Get core information.
1712 uint64_t Size = CTy.getSizeInBits() >> 3;
1713 unsigned Tag = CTy.getTag();
1717 case DW_TAG_vector_type:
1718 case DW_TAG_array_type:
1719 ConstructArrayTypeDIE(DW_Unit, Buffer, &CTy);
1721 case DW_TAG_enumeration_type:
1723 DIArray Elements = CTy.getTypeArray();
1724 // Add enumerators to enumeration type.
1725 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1726 DIE *ElemDie = NULL;
1727 DIEnumerator Enum(Elements.getElement(i).getGV());
1728 ElemDie = ConstructEnumTypeDIE(DW_Unit, &Enum);
1729 Buffer.AddChild(ElemDie);
1733 case DW_TAG_subroutine_type:
1735 // Add prototype flag.
1736 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1737 DIArray Elements = CTy.getTypeArray();
1739 DIDescriptor RTy = Elements.getElement(0);
1740 AddType(DW_Unit, &Buffer, DIType(RTy.getGV()));
1743 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1744 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1745 DIDescriptor Ty = Elements.getElement(i);
1746 AddType(DW_Unit, Arg, DIType(Ty.getGV()));
1747 Buffer.AddChild(Arg);
1751 case DW_TAG_structure_type:
1752 case DW_TAG_union_type:
1754 // Add elements to structure type.
1755 DIArray Elements = CTy.getTypeArray();
1757 // A forward struct declared type may not have elements available.
1758 if (Elements.isNull())
1761 // Add elements to structure type.
1762 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1763 DIDescriptor Element = Elements.getElement(i);
1764 DIE *ElemDie = NULL;
1765 if (Element.getTag() == dwarf::DW_TAG_subprogram)
1766 ElemDie = CreateSubprogramDIE(DW_Unit,
1767 DISubprogram(Element.getGV()));
1768 else if (Element.getTag() == dwarf::DW_TAG_variable) // ???
1769 ElemDie = CreateGlobalVariableDIE(DW_Unit,
1770 DIGlobalVariable(Element.getGV()));
1772 ElemDie = CreateMemberDIE(DW_Unit,
1773 DIDerivedType(Element.getGV()));
1774 Buffer.AddChild(ElemDie);
1776 unsigned RLang = CTy.getRunTimeLang();
1778 AddUInt(&Buffer, DW_AT_APPLE_runtime_class, DW_FORM_data1, RLang);
1785 // Add name if not anonymous or intermediate type.
1787 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1789 if (Tag == DW_TAG_enumeration_type || Tag == DW_TAG_structure_type
1790 || Tag == DW_TAG_union_type) {
1791 // Add size if non-zero (derived types might be zero-sized.)
1793 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1795 // Add zero size if it is not a forward declaration.
1796 if (CTy.isForwardDecl())
1797 AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
1799 AddUInt(&Buffer, DW_AT_byte_size, 0, 0);
1802 // Add source line info if available.
1803 if (!CTy.isForwardDecl())
1804 AddSourceLine(&Buffer, &CTy);
1808 /// ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
1809 void ConstructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1810 int64_t L = SR.getLo();
1811 int64_t H = SR.getHi();
1812 DIE *DW_Subrange = new DIE(DW_TAG_subrange_type);
1814 AddDIEntry(DW_Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1816 AddSInt(DW_Subrange, DW_AT_lower_bound, 0, L);
1817 AddSInt(DW_Subrange, DW_AT_upper_bound, 0, H);
1819 Buffer.AddChild(DW_Subrange);
1822 /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
1823 void ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1824 DICompositeType *CTy) {
1825 Buffer.setTag(DW_TAG_array_type);
1826 if (CTy->getTag() == DW_TAG_vector_type)
1827 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1829 // Emit derived type.
1830 AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
1831 DIArray Elements = CTy->getTypeArray();
1833 // Construct an anonymous type for index type.
1834 DIE IdxBuffer(DW_TAG_base_type);
1835 AddUInt(&IdxBuffer, DW_AT_byte_size, 0, sizeof(int32_t));
1836 AddUInt(&IdxBuffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
1837 DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
1839 // Add subranges to array type.
1840 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1841 DIDescriptor Element = Elements.getElement(i);
1842 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1843 ConstructSubrangeDIE(Buffer, DISubrange(Element.getGV()), IndexTy);
1847 /// ConstructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1848 DIE *ConstructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) {
1850 DIE *Enumerator = new DIE(DW_TAG_enumerator);
1853 AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
1854 int64_t Value = ETy->getEnumValue();
1855 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1859 /// CreateGlobalVariableDIE - Create new DIE using GV.
1860 DIE *CreateGlobalVariableDIE(CompileUnit *DW_Unit, const DIGlobalVariable &GV)
1862 DIE *GVDie = new DIE(DW_TAG_variable);
1864 GV.getDisplayName(Name);
1865 AddString(GVDie, DW_AT_name, DW_FORM_string, Name);
1866 std::string LinkageName;
1867 GV.getLinkageName(LinkageName);
1868 if (!LinkageName.empty())
1869 AddString(GVDie, DW_AT_MIPS_linkage_name, DW_FORM_string, LinkageName);
1870 AddType(DW_Unit, GVDie, GV.getType());
1871 if (!GV.isLocalToUnit())
1872 AddUInt(GVDie, DW_AT_external, DW_FORM_flag, 1);
1873 AddSourceLine(GVDie, &GV);
1877 /// CreateMemberDIE - Create new member DIE.
1878 DIE *CreateMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT) {
1879 DIE *MemberDie = new DIE(DT.getTag());
1883 AddString(MemberDie, DW_AT_name, DW_FORM_string, Name);
1885 AddType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
1887 AddSourceLine(MemberDie, &DT);
1889 uint64_t Size = DT.getSizeInBits();
1890 uint64_t FieldSize = DT.getOriginalTypeSize();
1892 if (Size != FieldSize) {
1894 AddUInt(MemberDie, DW_AT_byte_size, 0, DT.getOriginalTypeSize() >> 3);
1895 AddUInt(MemberDie, DW_AT_bit_size, 0, DT.getSizeInBits());
1897 uint64_t Offset = DT.getOffsetInBits();
1898 uint64_t FieldOffset = Offset;
1899 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1900 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1901 FieldOffset = (HiMark - FieldSize);
1902 Offset -= FieldOffset;
1903 // Maybe we need to work from the other end.
1904 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1905 AddUInt(MemberDie, DW_AT_bit_offset, 0, Offset);
1907 DIEBlock *Block = new DIEBlock();
1908 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1909 AddUInt(Block, 0, DW_FORM_udata, DT.getOffsetInBits() >> 3);
1910 AddBlock(MemberDie, DW_AT_data_member_location, 0, Block);
1912 if (DT.isProtected())
1913 AddUInt(MemberDie, DW_AT_accessibility, 0, DW_ACCESS_protected);
1914 else if (DT.isPrivate())
1915 AddUInt(MemberDie, DW_AT_accessibility, 0, DW_ACCESS_private);
1920 /// CreateSubprogramDIE - Create new DIE using SP.
1921 DIE *CreateSubprogramDIE(CompileUnit *DW_Unit,
1922 const DISubprogram &SP,
1923 bool IsConstructor = false) {
1924 DIE *SPDie = new DIE(DW_TAG_subprogram);
1927 AddString(SPDie, DW_AT_name, DW_FORM_string, Name);
1928 std::string LinkageName;
1929 SP.getLinkageName(LinkageName);
1930 if (!LinkageName.empty())
1931 AddString(SPDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1933 AddSourceLine(SPDie, &SP);
1935 DICompositeType SPTy = SP.getType();
1936 DIArray Args = SPTy.getTypeArray();
1939 if (!IsConstructor) {
1941 AddType(DW_Unit, SPDie, SPTy);
1943 AddType(DW_Unit, SPDie, DIType(Args.getElement(0).getGV()));
1946 if (!SP.isDefinition()) {
1947 AddUInt(SPDie, DW_AT_declaration, DW_FORM_flag, 1);
1949 // Do not add arguments for subprogram definition. They will be
1950 // handled through RecordVariable.
1952 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1953 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1954 AddType(DW_Unit, Arg, DIType(Args.getElement(i).getGV()));
1955 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1); // ???
1956 SPDie->AddChild(Arg);
1960 unsigned Lang = SP.getCompileUnit().getLanguage();
1961 if (Lang == DW_LANG_C99 || Lang == DW_LANG_C89
1962 || Lang == DW_LANG_ObjC)
1963 AddUInt(SPDie, DW_AT_prototyped, DW_FORM_flag, 1);
1965 if (!SP.isLocalToUnit())
1966 AddUInt(SPDie, DW_AT_external, DW_FORM_flag, 1);
1970 /// FindCompileUnit - Get the compile unit for the given descriptor.
1972 CompileUnit *FindCompileUnit(DICompileUnit Unit) {
1973 CompileUnit *DW_Unit = CompileUnitMap[Unit.getGV()];
1974 assert(DW_Unit && "Missing compile unit.");
1978 /// NewDbgScopeVariable - Create a new scope variable.
1980 DIE *NewDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
1981 // Get the descriptor.
1982 const DIVariable &VD = DV->getVariable();
1984 // Translate tag to proper Dwarf tag. The result variable is dropped for
1987 switch (VD.getTag()) {
1988 case DW_TAG_return_variable: return NULL;
1989 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
1990 case DW_TAG_auto_variable: // fall thru
1991 default: Tag = DW_TAG_variable; break;
1994 // Define variable debug information entry.
1995 DIE *VariableDie = new DIE(Tag);
1998 AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
2000 // Add source line info if available.
2001 AddSourceLine(VariableDie, &VD);
2003 // Add variable type.
2004 AddType(Unit, VariableDie, VD.getType());
2006 // Add variable address.
2007 MachineLocation Location;
2008 Location.set(RI->getFrameRegister(*MF),
2009 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
2010 AddAddress(VariableDie, DW_AT_location, Location);
2015 /// getOrCreateScope - Returns the scope associated with the given descriptor.
2017 DbgScope *getOrCreateScope(GlobalVariable *V) {
2018 DbgScope *&Slot = DbgScopeMap[V];
2019 if (Slot) return Slot;
2021 // FIXME - breaks down when the context is an inlined function.
2022 DIDescriptor ParentDesc;
2023 DIDescriptor Desc(V);
2025 if (Desc.getTag() == dwarf::DW_TAG_lexical_block) {
2027 ParentDesc = Block.getContext();
2030 DbgScope *Parent = ParentDesc.isNull() ?
2031 NULL : getOrCreateScope(ParentDesc.getGV());
2032 Slot = new DbgScope(Parent, Desc);
2035 Parent->AddScope(Slot);
2036 } else if (RootDbgScope) {
2037 // FIXME - Add inlined function scopes to the root so we can delete them
2038 // later. Long term, handle inlined functions properly.
2039 RootDbgScope->AddScope(Slot);
2041 // First function is top level function.
2042 RootDbgScope = Slot;
2048 /// ConstructDbgScope - Construct the components of a scope.
2050 void ConstructDbgScope(DbgScope *ParentScope,
2051 unsigned ParentStartID, unsigned ParentEndID,
2052 DIE *ParentDie, CompileUnit *Unit) {
2053 // Add variables to scope.
2054 SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
2055 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2056 DIE *VariableDie = NewDbgScopeVariable(Variables[i], Unit);
2057 if (VariableDie) ParentDie->AddChild(VariableDie);
2060 // Add nested scopes.
2061 SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
2062 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
2063 // Define the Scope debug information entry.
2064 DbgScope *Scope = Scopes[j];
2065 // FIXME - Ignore inlined functions for the time being.
2066 if (!Scope->getParent()) continue;
2068 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
2069 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
2071 // Ignore empty scopes.
2072 if (StartID == EndID && StartID != 0) continue;
2073 if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
2075 if (StartID == ParentStartID && EndID == ParentEndID) {
2076 // Just add stuff to the parent scope.
2077 ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
2079 DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
2081 // Add the scope bounds.
2083 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2084 DWLabel("label", StartID));
2086 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2087 DWLabel("func_begin", SubprogramCount));
2090 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2091 DWLabel("label", EndID));
2093 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2094 DWLabel("func_end", SubprogramCount));
2097 // Add the scope contents.
2098 ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
2099 ParentDie->AddChild(ScopeDie);
2104 /// ConstructRootDbgScope - Construct the scope for the subprogram.
2106 void ConstructRootDbgScope(DbgScope *RootScope) {
2107 // Exit if there is no root scope.
2108 if (!RootScope) return;
2109 DIDescriptor Desc = RootScope->getDesc();
2113 // Get the subprogram debug information entry.
2114 DISubprogram SPD(Desc.getGV());
2116 // Get the compile unit context.
2117 CompileUnit *Unit = MainCU;
2119 Unit = FindCompileUnit(SPD.getCompileUnit());
2121 // Get the subprogram die.
2122 DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
2123 assert(SPDie && "Missing subprogram descriptor");
2125 // Add the function bounds.
2126 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2127 DWLabel("func_begin", SubprogramCount));
2128 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2129 DWLabel("func_end", SubprogramCount));
2130 MachineLocation Location(RI->getFrameRegister(*MF));
2131 AddAddress(SPDie, DW_AT_frame_base, Location);
2133 ConstructDbgScope(RootScope, 0, 0, SPDie, Unit);
2136 /// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
2138 void ConstructDefaultDbgScope(MachineFunction *MF) {
2139 const char *FnName = MF->getFunction()->getNameStart();
2141 std::map<std::string, DIE*> &Globals = MainCU->getGlobals();
2142 std::map<std::string, DIE*>::iterator GI = Globals.find(FnName);
2143 if (GI != Globals.end()) {
2144 DIE *SPDie = GI->second;
2146 // Add the function bounds.
2147 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2148 DWLabel("func_begin", SubprogramCount));
2149 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2150 DWLabel("func_end", SubprogramCount));
2152 MachineLocation Location(RI->getFrameRegister(*MF));
2153 AddAddress(SPDie, DW_AT_frame_base, Location);
2157 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
2158 CompileUnit *Unit = CompileUnits[i];
2159 std::map<std::string, DIE*> &Globals = Unit->getGlobals();
2160 std::map<std::string, DIE*>::iterator GI = Globals.find(FnName);
2161 if (GI != Globals.end()) {
2162 DIE *SPDie = GI->second;
2164 // Add the function bounds.
2165 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2166 DWLabel("func_begin", SubprogramCount));
2167 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2168 DWLabel("func_end", SubprogramCount));
2170 MachineLocation Location(RI->getFrameRegister(*MF));
2171 AddAddress(SPDie, DW_AT_frame_base, Location);
2178 // FIXME: This is causing an abort because C++ mangled names are compared
2179 // with their unmangled counterparts. See PR2885. Don't do this assert.
2180 assert(0 && "Couldn't find DIE for machine function!");
2185 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
2186 /// tools to recognize the object file contains Dwarf information.
2187 void EmitInitial() {
2188 // Check to see if we already emitted intial headers.
2189 if (didInitial) return;
2192 // Dwarf sections base addresses.
2193 if (TAI->doesDwarfRequireFrameSection()) {
2194 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2195 EmitLabel("section_debug_frame", 0);
2197 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2198 EmitLabel("section_info", 0);
2199 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2200 EmitLabel("section_abbrev", 0);
2201 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2202 EmitLabel("section_aranges", 0);
2203 if (TAI->doesSupportMacInfoSection()) {
2204 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2205 EmitLabel("section_macinfo", 0);
2207 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2208 EmitLabel("section_line", 0);
2209 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2210 EmitLabel("section_loc", 0);
2211 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2212 EmitLabel("section_pubnames", 0);
2213 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2214 EmitLabel("section_str", 0);
2215 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2216 EmitLabel("section_ranges", 0);
2218 Asm->SwitchToSection(TAI->getTextSection());
2219 EmitLabel("text_begin", 0);
2220 Asm->SwitchToSection(TAI->getDataSection());
2221 EmitLabel("data_begin", 0);
2224 /// EmitDIE - Recusively Emits a debug information entry.
2226 void EmitDIE(DIE *Die) {
2227 // Get the abbreviation for this DIE.
2228 unsigned AbbrevNumber = Die->getAbbrevNumber();
2229 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2233 // Emit the code (index) for the abbreviation.
2234 Asm->EmitULEB128Bytes(AbbrevNumber);
2237 Asm->EOL(std::string("Abbrev [" +
2238 utostr(AbbrevNumber) +
2239 "] 0x" + utohexstr(Die->getOffset()) +
2240 ":0x" + utohexstr(Die->getSize()) + " " +
2241 TagString(Abbrev->getTag())));
2245 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2246 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2248 // Emit the DIE attribute values.
2249 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2250 unsigned Attr = AbbrevData[i].getAttribute();
2251 unsigned Form = AbbrevData[i].getForm();
2252 assert(Form && "Too many attributes for DIE (check abbreviation)");
2255 case DW_AT_sibling: {
2256 Asm->EmitInt32(Die->SiblingOffset());
2260 // Emit an attribute using the defined form.
2261 Values[i]->EmitValue(*this, Form);
2266 Asm->EOL(AttributeString(Attr));
2269 // Emit the DIE children if any.
2270 if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2271 const std::vector<DIE *> &Children = Die->getChildren();
2273 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2274 EmitDIE(Children[j]);
2277 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2281 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2283 unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2284 // Get the children.
2285 const std::vector<DIE *> &Children = Die->getChildren();
2287 // If not last sibling and has children then add sibling offset attribute.
2288 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2290 // Record the abbreviation.
2291 AssignAbbrevNumber(Die->getAbbrev());
2293 // Get the abbreviation for this DIE.
2294 unsigned AbbrevNumber = Die->getAbbrevNumber();
2295 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2298 Die->setOffset(Offset);
2300 // Start the size with the size of abbreviation code.
2301 Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
2303 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2304 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2306 // Size the DIE attribute values.
2307 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2308 // Size attribute value.
2309 Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2312 // Size the DIE children if any.
2313 if (!Children.empty()) {
2314 assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2315 "Children flag not set");
2317 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2318 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2321 // End of children marker.
2322 Offset += sizeof(int8_t);
2325 Die->setSize(Offset - Die->getOffset());
2329 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2331 void SizeAndOffsets() {
2332 // Process base compile unit.
2334 // Compute size of compile unit header
2335 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2336 sizeof(int16_t) + // DWARF version number
2337 sizeof(int32_t) + // Offset Into Abbrev. Section
2338 sizeof(int8_t); // Pointer Size (in bytes)
2339 SizeAndOffsetDie(MainCU->getDie(), Offset, true);
2342 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
2343 CompileUnit *Unit = CompileUnits[i];
2344 // Compute size of compile unit header
2345 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2346 sizeof(int16_t) + // DWARF version number
2347 sizeof(int32_t) + // Offset Into Abbrev. Section
2348 sizeof(int8_t); // Pointer Size (in bytes)
2349 SizeAndOffsetDie(Unit->getDie(), Offset, true);
2353 /// EmitDebugInfo / EmitDebugInfoPerCU - Emit the debug info section.
2355 void EmitDebugInfoPerCU(CompileUnit *Unit) {
2356 DIE *Die = Unit->getDie();
2357 // Emit the compile units header.
2358 EmitLabel("info_begin", Unit->getID());
2359 // Emit size of content not including length itself
2360 unsigned ContentSize = Die->getSize() +
2361 sizeof(int16_t) + // DWARF version number
2362 sizeof(int32_t) + // Offset Into Abbrev. Section
2363 sizeof(int8_t) + // Pointer Size (in bytes)
2364 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2366 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2367 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2368 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2369 Asm->EOL("Offset Into Abbrev. Section");
2370 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2373 // FIXME - extra padding for gdb bug.
2374 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2375 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2376 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2377 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2378 EmitLabel("info_end", Unit->getID());
2383 void EmitDebugInfo() {
2384 // Start debug info section.
2385 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2388 EmitDebugInfoPerCU(MainCU);
2392 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
2393 EmitDebugInfoPerCU(CompileUnits[i]);
2396 /// EmitAbbreviations - Emit the abbreviation section.
2398 void EmitAbbreviations() const {
2399 // Check to see if it is worth the effort.
2400 if (!Abbreviations.empty()) {
2401 // Start the debug abbrev section.
2402 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2404 EmitLabel("abbrev_begin", 0);
2406 // For each abbrevation.
2407 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2408 // Get abbreviation data
2409 const DIEAbbrev *Abbrev = Abbreviations[i];
2411 // Emit the abbrevations code (base 1 index.)
2412 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2413 Asm->EOL("Abbreviation Code");
2415 // Emit the abbreviations data.
2416 Abbrev->Emit(*this);
2421 // Mark end of abbreviations.
2422 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2424 EmitLabel("abbrev_end", 0);
2430 /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
2431 /// the line matrix.
2433 void EmitEndOfLineMatrix(unsigned SectionEnd) {
2434 // Define last address of section.
2435 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2436 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2437 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2438 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2440 // Mark end of matrix.
2441 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2442 Asm->EmitULEB128Bytes(1); Asm->EOL();
2443 Asm->EmitInt8(1); Asm->EOL();
2446 /// EmitDebugLines - Emit source line information.
2448 void EmitDebugLines() {
2449 // If the target is using .loc/.file, the assembler will be emitting the
2450 // .debug_line table automatically.
2451 if (TAI->hasDotLocAndDotFile())
2454 // Minimum line delta, thus ranging from -10..(255-10).
2455 const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2456 // Maximum line delta, thus ranging from -10..(255-10).
2457 const int MaxLineDelta = 255 + MinLineDelta;
2459 // Start the dwarf line section.
2460 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2462 // Construct the section header.
2464 EmitDifference("line_end", 0, "line_begin", 0, true);
2465 Asm->EOL("Length of Source Line Info");
2466 EmitLabel("line_begin", 0);
2468 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2470 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2471 Asm->EOL("Prolog Length");
2472 EmitLabel("line_prolog_begin", 0);
2474 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2476 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2478 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2480 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2482 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2484 // Line number standard opcode encodings argument count
2485 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2486 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2487 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2488 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2489 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2490 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2491 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2492 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2493 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2495 // Emit directories.
2496 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2497 Asm->EmitString(getSourceDirectoryName(DI));
2498 Asm->EOL("Directory");
2500 Asm->EmitInt8(0); Asm->EOL("End of directories");
2503 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2504 // Remember source id starts at 1.
2505 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2506 Asm->EmitString(getSourceFileName(Id.second));
2508 Asm->EmitULEB128Bytes(Id.first);
2509 Asm->EOL("Directory #");
2510 Asm->EmitULEB128Bytes(0);
2511 Asm->EOL("Mod date");
2512 Asm->EmitULEB128Bytes(0);
2513 Asm->EOL("File size");
2515 Asm->EmitInt8(0); Asm->EOL("End of files");
2517 EmitLabel("line_prolog_end", 0);
2519 // A sequence for each text section.
2520 unsigned SecSrcLinesSize = SectionSourceLines.size();
2522 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2523 // Isolate current sections line info.
2524 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2527 const Section* S = SectionMap[j + 1];
2528 O << '\t' << TAI->getCommentString() << " Section"
2529 << S->getName() << '\n';
2533 // Dwarf assumes we start with first line of first source file.
2534 unsigned Source = 1;
2537 // Construct rows of the address, source, line, column matrix.
2538 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2539 const SrcLineInfo &LineInfo = LineInfos[i];
2540 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2541 if (!LabelID) continue;
2546 std::pair<unsigned, unsigned> SourceID =
2547 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2548 O << '\t' << TAI->getCommentString() << ' '
2549 << getSourceDirectoryName(SourceID.first) << ' '
2550 << getSourceFileName(SourceID.second)
2551 <<" :" << utostr_32(LineInfo.getLine()) << '\n';
2554 // Define the line address.
2555 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2556 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2557 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2558 EmitReference("label", LabelID); Asm->EOL("Location label");
2560 // If change of source, then switch to the new source.
2561 if (Source != LineInfo.getSourceID()) {
2562 Source = LineInfo.getSourceID();
2563 Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2564 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2567 // If change of line.
2568 if (Line != LineInfo.getLine()) {
2569 // Determine offset.
2570 int Offset = LineInfo.getLine() - Line;
2571 int Delta = Offset - MinLineDelta;
2574 Line = LineInfo.getLine();
2576 // If delta is small enough and in range...
2577 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2578 // ... then use fast opcode.
2579 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2581 // ... otherwise use long hand.
2582 Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
2583 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2584 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2587 // Copy the previous row (different address or source)
2588 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2592 EmitEndOfLineMatrix(j + 1);
2595 if (SecSrcLinesSize == 0)
2596 // Because we're emitting a debug_line section, we still need a line
2597 // table. The linker and friends expect it to exist. If there's nothing to
2598 // put into it, emit an empty table.
2599 EmitEndOfLineMatrix(1);
2601 EmitLabel("line_end", 0);
2606 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2608 void EmitCommonDebugFrame() {
2609 if (!TAI->doesDwarfRequireFrameSection())
2613 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2614 TargetFrameInfo::StackGrowsUp ?
2615 TD->getPointerSize() : -TD->getPointerSize();
2617 // Start the dwarf frame section.
2618 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2620 EmitLabel("debug_frame_common", 0);
2621 EmitDifference("debug_frame_common_end", 0,
2622 "debug_frame_common_begin", 0, true);
2623 Asm->EOL("Length of Common Information Entry");
2625 EmitLabel("debug_frame_common_begin", 0);
2626 Asm->EmitInt32((int)DW_CIE_ID);
2627 Asm->EOL("CIE Identifier Tag");
2628 Asm->EmitInt8(DW_CIE_VERSION);
2629 Asm->EOL("CIE Version");
2630 Asm->EmitString("");
2631 Asm->EOL("CIE Augmentation");
2632 Asm->EmitULEB128Bytes(1);
2633 Asm->EOL("CIE Code Alignment Factor");
2634 Asm->EmitSLEB128Bytes(stackGrowth);
2635 Asm->EOL("CIE Data Alignment Factor");
2636 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2637 Asm->EOL("CIE RA Column");
2639 std::vector<MachineMove> Moves;
2640 RI->getInitialFrameState(Moves);
2642 EmitFrameMoves(NULL, 0, Moves, false);
2644 Asm->EmitAlignment(2, 0, 0, false);
2645 EmitLabel("debug_frame_common_end", 0);
2650 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2652 void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2653 if (!TAI->doesDwarfRequireFrameSection())
2656 // Start the dwarf frame section.
2657 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2659 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2660 "debug_frame_begin", DebugFrameInfo.Number, true);
2661 Asm->EOL("Length of Frame Information Entry");
2663 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2665 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2667 Asm->EOL("FDE CIE offset");
2669 EmitReference("func_begin", DebugFrameInfo.Number);
2670 Asm->EOL("FDE initial location");
2671 EmitDifference("func_end", DebugFrameInfo.Number,
2672 "func_begin", DebugFrameInfo.Number);
2673 Asm->EOL("FDE address range");
2675 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
2678 Asm->EmitAlignment(2, 0, 0, false);
2679 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2684 void EmitDebugPubNamesPerCU(CompileUnit *Unit) {
2685 EmitDifference("pubnames_end", Unit->getID(),
2686 "pubnames_begin", Unit->getID(), true);
2687 Asm->EOL("Length of Public Names Info");
2689 EmitLabel("pubnames_begin", Unit->getID());
2691 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
2693 EmitSectionOffset("info_begin", "section_info",
2694 Unit->getID(), 0, true, false);
2695 Asm->EOL("Offset of Compilation Unit Info");
2697 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
2699 Asm->EOL("Compilation Unit Length");
2701 std::map<std::string, DIE *> &Globals = Unit->getGlobals();
2702 for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
2703 GE = Globals.end(); GI != GE; ++GI) {
2704 const std::string &Name = GI->first;
2705 DIE * Entity = GI->second;
2707 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2708 Asm->EmitString(Name); Asm->EOL("External Name");
2711 Asm->EmitInt32(0); Asm->EOL("End Mark");
2712 EmitLabel("pubnames_end", Unit->getID());
2717 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2719 void EmitDebugPubNames() {
2720 // Start the dwarf pubnames section.
2721 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2724 EmitDebugPubNamesPerCU(MainCU);
2728 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
2729 EmitDebugPubNamesPerCU(CompileUnits[i]);
2732 /// EmitDebugStr - Emit visible names into a debug str section.
2734 void EmitDebugStr() {
2735 // Check to see if it is worth the effort.
2736 if (!StringPool.empty()) {
2737 // Start the dwarf str section.
2738 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2740 // For each of strings in the string pool.
2741 for (unsigned StringID = 1, N = StringPool.size();
2742 StringID <= N; ++StringID) {
2743 // Emit a label for reference from debug information entries.
2744 EmitLabel("string", StringID);
2745 // Emit the string itself.
2746 const std::string &String = StringPool[StringID];
2747 Asm->EmitString(String); Asm->EOL();
2754 /// EmitDebugLoc - Emit visible names into a debug loc section.
2756 void EmitDebugLoc() {
2757 // Start the dwarf loc section.
2758 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2763 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2765 void EmitDebugARanges() {
2766 // Start the dwarf aranges section.
2767 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2771 CompileUnit *Unit = GetBaseCompileUnit();
2773 // Don't include size of length
2774 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2776 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2778 EmitReference("info_begin", Unit->getID());
2779 Asm->EOL("Offset of Compilation Unit Info");
2781 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2783 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2785 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2786 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2789 EmitReference("text_begin", 0); Asm->EOL("Address");
2790 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2792 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2793 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2799 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2801 void EmitDebugRanges() {
2802 // Start the dwarf ranges section.
2803 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2808 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2810 void EmitDebugMacInfo() {
2811 if (TAI->doesSupportMacInfoSection()) {
2812 // Start the dwarf macinfo section.
2813 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2819 /// GetOrCreateSourceID - Look up the source id with the given directory and
2820 /// source file names. If none currently exists, create a new id and insert it
2821 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames maps
2823 unsigned GetOrCreateSourceID(const std::string &DirName,
2824 const std::string &FileName) {
2826 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
2827 if (DI != DirectoryIdMap.end()) {
2828 DId = DI->getValue();
2830 DId = DirectoryNames.size() + 1;
2831 DirectoryIdMap[DirName] = DId;
2832 DirectoryNames.push_back(DirName);
2836 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
2837 if (FI != SourceFileIdMap.end()) {
2838 FId = FI->getValue();
2840 FId = SourceFileNames.size() + 1;
2841 SourceFileIdMap[FileName] = FId;
2842 SourceFileNames.push_back(FileName);
2845 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
2846 SourceIdMap.find(std::make_pair(DId, FId));
2847 if (SI != SourceIdMap.end())
2850 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
2851 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
2852 SourceIds.push_back(std::make_pair(DId, FId));
2857 void ConstructCompileUnit(GlobalVariable *GV) {
2858 DICompileUnit DIUnit(GV);
2859 std::string Dir, FN, Prod;
2860 unsigned ID = GetOrCreateSourceID(DIUnit.getDirectory(Dir),
2861 DIUnit.getFilename(FN));
2863 DIE *Die = new DIE(DW_TAG_compile_unit);
2864 AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
2865 DWLabel("section_line", 0), DWLabel("section_line", 0),
2867 AddString(Die, DW_AT_producer, DW_FORM_string, DIUnit.getProducer(Prod));
2868 AddUInt(Die, DW_AT_language, DW_FORM_data1, DIUnit.getLanguage());
2869 AddString(Die, DW_AT_name, DW_FORM_string, FN);
2871 AddString(Die, DW_AT_comp_dir, DW_FORM_string, Dir);
2872 if (DIUnit.isOptimized())
2873 AddUInt(Die, DW_AT_APPLE_optimized, DW_FORM_flag, 1);
2875 DIUnit.getFlags(Flags);
2877 AddString(Die, DW_AT_APPLE_flags, DW_FORM_string, Flags);
2878 unsigned RVer = DIUnit.getRunTimeVersion();
2880 AddUInt(Die, DW_AT_APPLE_major_runtime_vers, DW_FORM_data1, RVer);
2882 CompileUnit *Unit = new CompileUnit(ID, Die);
2883 if (DIUnit.isMain()) {
2884 assert(!MainCU && "Multiple main compile units are found!");
2887 CompileUnitMap[DIUnit.getGV()] = Unit;
2888 CompileUnits.push_back(Unit);
2891 /// ConstructCompileUnits - Create a compile unit DIEs.
2892 void ConstructCompileUnits() {
2893 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.compile_units");
2896 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2897 "Malformed compile unit descriptor anchor type");
2898 Constant *RootC = cast<Constant>(*Root->use_begin());
2899 assert(RootC->hasNUsesOrMore(1) &&
2900 "Malformed compile unit descriptor anchor type");
2901 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2903 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2904 UUI != UUE; ++UUI) {
2905 GlobalVariable *GV = cast<GlobalVariable>(*UUI);
2906 ConstructCompileUnit(GV);
2910 bool ConstructGlobalVariableDIE(GlobalVariable *GV) {
2911 DIGlobalVariable DI_GV(GV);
2912 CompileUnit *DW_Unit = MainCU;
2914 DW_Unit = FindCompileUnit(DI_GV.getCompileUnit());
2916 // Check for pre-existence.
2917 DIE *&Slot = DW_Unit->getDieMapSlotFor(DI_GV.getGV());
2921 DIE *VariableDie = CreateGlobalVariableDIE(DW_Unit, DI_GV);
2924 DIEBlock *Block = new DIEBlock();
2925 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
2926 AddObjectLabel(Block, 0, DW_FORM_udata,
2927 Asm->getGlobalLinkName(DI_GV.getGlobal()));
2928 AddBlock(VariableDie, DW_AT_location, 0, Block);
2932 // Add to context owner.
2933 DW_Unit->getDie()->AddChild(VariableDie);
2934 // Expose as global. FIXME - need to check external flag.
2936 DW_Unit->AddGlobal(DI_GV.getName(Name), VariableDie);
2940 /// ConstructGlobalVariableDIEs - Create DIEs for each of the externally
2941 /// visible global variables. Return true if at least one global DIE is
2943 bool ConstructGlobalVariableDIEs() {
2944 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.global_variables");
2948 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2949 "Malformed global variable descriptor anchor type");
2950 Constant *RootC = cast<Constant>(*Root->use_begin());
2951 assert(RootC->hasNUsesOrMore(1) &&
2952 "Malformed global variable descriptor anchor type");
2954 bool Result = false;
2955 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2957 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2958 UUI != UUE; ++UUI) {
2959 GlobalVariable *GV = cast<GlobalVariable>(*UUI);
2960 Result |= ConstructGlobalVariableDIE(GV);
2965 bool ConstructSubprogram(GlobalVariable *GV) {
2966 DISubprogram SP(GV);
2967 CompileUnit *Unit = MainCU;
2969 Unit = FindCompileUnit(SP.getCompileUnit());
2971 // Check for pre-existence.
2972 DIE *&Slot = Unit->getDieMapSlotFor(GV);
2976 if (!SP.isDefinition())
2977 // This is a method declaration which will be handled while
2978 // constructing class type.
2981 DIE *SubprogramDie = CreateSubprogramDIE(Unit, SP);
2984 Slot = SubprogramDie;
2985 // Add to context owner.
2986 Unit->getDie()->AddChild(SubprogramDie);
2987 // Expose as global.
2989 Unit->AddGlobal(SP.getName(Name), SubprogramDie);
2993 /// ConstructSubprograms - Create DIEs for each of the externally visible
2994 /// subprograms. Return true if at least one subprogram DIE is created.
2995 bool ConstructSubprograms() {
2996 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.subprograms");
3000 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
3001 "Malformed subprogram descriptor anchor type");
3002 Constant *RootC = cast<Constant>(*Root->use_begin());
3003 assert(RootC->hasNUsesOrMore(1) &&
3004 "Malformed subprogram descriptor anchor type");
3006 bool Result = false;
3007 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
3009 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
3010 UUI != UUE; ++UUI) {
3011 GlobalVariable *GV = cast<GlobalVariable>(*UUI);
3012 Result |= ConstructSubprogram(GV);
3018 //===--------------------------------------------------------------------===//
3019 // Main entry points.
3021 DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3022 : Dwarf(OS, A, T, "dbg"), MainCU(0),
3023 AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(),
3024 ValuesSet(InitValuesSetSize), Values(), StringPool(), SectionMap(),
3025 SectionSourceLines(), didInitial(false), shouldEmit(false),
3026 RootDbgScope(0), DebugTimer(0) {
3027 if (TimePassesIsEnabled)
3028 DebugTimer = new Timer("Dwarf Debug Writer",
3029 *getDwarfTimerGroup());
3031 virtual ~DwarfDebug() {
3032 for (unsigned j = 0, M = Values.size(); j < M; ++j)
3038 /// ShouldEmitDwarfDebug - Returns true if Dwarf debugging declarations should
3040 bool ShouldEmitDwarfDebug() const { return shouldEmit; }
3042 /// SetDebugInfo - Create global DIEs and emit initial debug info sections.
3043 /// This is inovked by the target AsmPrinter.
3044 void SetDebugInfo(MachineModuleInfo *mmi) {
3045 if (TimePassesIsEnabled)
3046 DebugTimer->startTimer();
3048 // Create all the compile unit DIEs.
3049 ConstructCompileUnits();
3051 if (CompileUnits.empty()) {
3052 if (TimePassesIsEnabled)
3053 DebugTimer->stopTimer();
3058 // Create DIEs for each of the externally visible global variables.
3059 bool globalDIEs = ConstructGlobalVariableDIEs();
3061 // Create DIEs for each of the externally visible subprograms.
3062 bool subprogramDIEs = ConstructSubprograms();
3064 // If there is not any debug info available for any global variables
3065 // and any subprograms then there is not any debug info to emit.
3066 if (!globalDIEs && !subprogramDIEs) {
3067 if (TimePassesIsEnabled)
3068 DebugTimer->stopTimer();
3075 MMI->setDebugInfoAvailability(true);
3077 // Prime section data.
3078 SectionMap.insert(TAI->getTextSection());
3080 // Print out .file directives to specify files for .loc directives. These
3081 // are printed out early so that they precede any .loc directives.
3082 if (TAI->hasDotLocAndDotFile()) {
3083 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
3084 // Remember source id starts at 1.
3085 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
3086 sys::Path FullPath(getSourceDirectoryName(Id.first));
3088 FullPath.appendComponent(getSourceFileName(Id.second));
3089 assert(AppendOk && "Could not append filename to directory!");
3091 Asm->EmitFile(i, FullPath.toString());
3096 // Emit initial sections
3099 if (TimePassesIsEnabled)
3100 DebugTimer->stopTimer();
3103 /// BeginModule - Emit all Dwarf sections that should come prior to the
3105 void BeginModule(Module *M) {
3109 /// EndModule - Emit all Dwarf sections that should come after the content.
3112 if (!ShouldEmitDwarfDebug())
3115 if (TimePassesIsEnabled)
3116 DebugTimer->startTimer();
3118 // Standard sections final addresses.
3119 Asm->SwitchToSection(TAI->getTextSection());
3120 EmitLabel("text_end", 0);
3121 Asm->SwitchToSection(TAI->getDataSection());
3122 EmitLabel("data_end", 0);
3124 // End text sections.
3125 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
3126 Asm->SwitchToSection(SectionMap[i]);
3127 EmitLabel("section_end", i);
3130 // Emit common frame information.
3131 EmitCommonDebugFrame();
3133 // Emit function debug frame information
3134 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
3135 E = DebugFrames.end(); I != E; ++I)
3136 EmitFunctionDebugFrame(*I);
3138 // Compute DIE offsets and sizes.
3141 // Emit all the DIEs into a debug info section
3144 // Corresponding abbreviations into a abbrev section.
3145 EmitAbbreviations();
3147 // Emit source line correspondence into a debug line section.
3150 // Emit info into a debug pubnames section.
3151 EmitDebugPubNames();
3153 // Emit info into a debug str section.
3156 // Emit info into a debug loc section.
3159 // Emit info into a debug aranges section.
3162 // Emit info into a debug ranges section.
3165 // Emit info into a debug macinfo section.
3168 if (TimePassesIsEnabled)
3169 DebugTimer->stopTimer();
3172 /// BeginFunction - Gather pre-function debug information. Assumes being
3173 /// emitted immediately after the function entry point.
3174 void BeginFunction(MachineFunction *MF) {
3175 if (!ShouldEmitDwarfDebug()) return;
3177 if (TimePassesIsEnabled)
3178 DebugTimer->startTimer();
3182 // Begin accumulating function debug information.
3183 MMI->BeginFunction(MF);
3185 // Assumes in correct section after the entry point.
3186 EmitLabel("func_begin", ++SubprogramCount);
3188 // Emit label for the implicitly defined dbg.stoppoint at the start of
3190 if (!Lines.empty()) {
3191 const SrcLineInfo &LineInfo = Lines[0];
3192 Asm->printLabel(LineInfo.getLabelID());
3195 if (TimePassesIsEnabled)
3196 DebugTimer->stopTimer();
3199 /// EndFunction - Gather and emit post-function debug information.
3201 void EndFunction(MachineFunction *MF) {
3202 if (!ShouldEmitDwarfDebug()) return;
3204 if (TimePassesIsEnabled)
3205 DebugTimer->startTimer();
3207 // Define end label for subprogram.
3208 EmitLabel("func_end", SubprogramCount);
3210 // Get function line info.
3211 if (!Lines.empty()) {
3212 // Get section line info.
3213 unsigned ID = SectionMap.insert(Asm->CurrentSection_);
3214 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
3215 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
3216 // Append the function info to section info.
3217 SectionLineInfos.insert(SectionLineInfos.end(),
3218 Lines.begin(), Lines.end());
3221 // Construct scopes for subprogram.
3223 ConstructRootDbgScope(RootDbgScope);
3225 // FIXME: This is wrong. We are essentially getting past a problem with
3226 // debug information not being able to handle unreachable blocks that have
3227 // debug information in them. In particular, those unreachable blocks that
3228 // have "region end" info in them. That situation results in the "root
3229 // scope" not being created. If that's the case, then emit a "default"
3230 // scope, i.e., one that encompasses the whole function. This isn't
3231 // desirable. And a better way of handling this (and all of the debugging
3232 // information) needs to be explored.
3233 ConstructDefaultDbgScope(MF);
3235 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
3236 MMI->getFrameMoves()));
3240 delete RootDbgScope;
3241 DbgScopeMap.clear();
3242 RootDbgScope = NULL;
3247 if (TimePassesIsEnabled)
3248 DebugTimer->stopTimer();
3251 /// ValidDebugInfo - Return true if V represents valid debug info value.
3252 bool ValidDebugInfo(Value *V) {
3259 GlobalVariable *GV = getGlobalVariable(V);
3263 if (!GV->hasInternalLinkage () && !GV->hasLinkOnceLinkage())
3266 if (TimePassesIsEnabled)
3267 DebugTimer->startTimer();
3269 DIDescriptor DI(GV);
3271 // Check current version. Allow Version6 for now.
3272 unsigned Version = DI.getVersion();
3273 if (Version != LLVMDebugVersion && Version != LLVMDebugVersion6) {
3274 if (TimePassesIsEnabled)
3275 DebugTimer->stopTimer();
3280 unsigned Tag = DI.getTag();
3282 case DW_TAG_variable:
3283 assert(DIVariable(GV).Verify() && "Invalid DebugInfo value");
3285 case DW_TAG_compile_unit:
3286 assert(DICompileUnit(GV).Verify() && "Invalid DebugInfo value");
3288 case DW_TAG_subprogram:
3289 assert(DISubprogram(GV).Verify() && "Invalid DebugInfo value");
3295 if (TimePassesIsEnabled)
3296 DebugTimer->stopTimer();
3301 /// RecordSourceLine - Records location information and associates it with a
3302 /// label. Returns a unique label ID used to generate a label and provide
3303 /// correspondence to the source line list.
3304 unsigned RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
3305 if (TimePassesIsEnabled)
3306 DebugTimer->startTimer();
3308 CompileUnit *Unit = CompileUnitMap[V];
3309 assert(Unit && "Unable to find CompileUnit");
3310 unsigned ID = MMI->NextLabelID();
3311 Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
3313 if (TimePassesIsEnabled)
3314 DebugTimer->stopTimer();
3319 /// RecordSourceLine - Records location information and associates it with a
3320 /// label. Returns a unique label ID used to generate a label and provide
3321 /// correspondence to the source line list.
3322 unsigned RecordSourceLine(unsigned Line, unsigned Col, unsigned Src) {
3323 if (TimePassesIsEnabled)
3324 DebugTimer->startTimer();
3326 unsigned ID = MMI->NextLabelID();
3327 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
3329 if (TimePassesIsEnabled)
3330 DebugTimer->stopTimer();
3335 /// getRecordSourceLineCount - Return the number of source lines in the debug
3337 unsigned getRecordSourceLineCount() const {
3338 return Lines.size();
3341 /// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
3342 /// timed. Look up the source id with the given directory and source file
3343 /// names. If none currently exists, create a new id and insert it in the
3344 /// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
3346 unsigned getOrCreateSourceID(const std::string &DirName,
3347 const std::string &FileName) {
3348 if (TimePassesIsEnabled)
3349 DebugTimer->startTimer();
3351 unsigned SrcId = GetOrCreateSourceID(DirName, FileName);
3353 if (TimePassesIsEnabled)
3354 DebugTimer->stopTimer();
3359 /// RecordRegionStart - Indicate the start of a region.
3360 unsigned RecordRegionStart(GlobalVariable *V) {
3361 if (TimePassesIsEnabled)
3362 DebugTimer->startTimer();
3364 DbgScope *Scope = getOrCreateScope(V);
3365 unsigned ID = MMI->NextLabelID();
3366 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
3368 if (TimePassesIsEnabled)
3369 DebugTimer->stopTimer();
3374 /// RecordRegionEnd - Indicate the end of a region.
3375 unsigned RecordRegionEnd(GlobalVariable *V) {
3376 if (TimePassesIsEnabled)
3377 DebugTimer->startTimer();
3379 DbgScope *Scope = getOrCreateScope(V);
3380 unsigned ID = MMI->NextLabelID();
3381 Scope->setEndLabelID(ID);
3383 if (TimePassesIsEnabled)
3384 DebugTimer->stopTimer();
3389 /// RecordVariable - Indicate the declaration of a local variable.
3390 void RecordVariable(GlobalVariable *GV, unsigned FrameIndex) {
3391 if (TimePassesIsEnabled)
3392 DebugTimer->startTimer();
3394 DIDescriptor Desc(GV);
3395 DbgScope *Scope = NULL;
3397 if (Desc.getTag() == DW_TAG_variable) {
3398 // GV is a global variable.
3399 DIGlobalVariable DG(GV);
3400 Scope = getOrCreateScope(DG.getContext().getGV());
3402 // or GV is a local variable.
3404 Scope = getOrCreateScope(DV.getContext().getGV());
3407 assert(Scope && "Unable to find variable' scope");
3408 DbgVariable *DV = new DbgVariable(DIVariable(GV), FrameIndex);
3409 Scope->AddVariable(DV);
3411 if (TimePassesIsEnabled)
3412 DebugTimer->stopTimer();
3416 //===----------------------------------------------------------------------===//
3417 /// DwarfException - Emits Dwarf exception handling directives.
3419 class DwarfException : public Dwarf {
3420 struct FunctionEHFrameInfo {
3423 unsigned PersonalityIndex;
3425 bool hasLandingPads;
3426 std::vector<MachineMove> Moves;
3427 const Function * function;
3429 FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
3431 const std::vector<MachineMove> &M,
3433 FnName(FN), Number(Num), PersonalityIndex(P),
3434 hasCalls(hC), hasLandingPads(hL), Moves(M), function (f) { }
3437 std::vector<FunctionEHFrameInfo> EHFrames;
3439 /// shouldEmitTable - Per-function flag to indicate if EH tables should
3441 bool shouldEmitTable;
3443 /// shouldEmitMoves - Per-function flag to indicate if frame moves info
3444 /// should be emitted.
3445 bool shouldEmitMoves;
3447 /// shouldEmitTableModule - Per-module flag to indicate if EH tables
3448 /// should be emitted.
3449 bool shouldEmitTableModule;
3451 /// shouldEmitFrameModule - Per-module flag to indicate if frame moves
3452 /// should be emitted.
3453 bool shouldEmitMovesModule;
3455 /// ExceptionTimer - Timer for the Dwarf exception writer.
3456 Timer *ExceptionTimer;
3458 /// EmitCommonEHFrame - Emit the common eh unwind frame.
3460 void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
3461 // Size and sign of stack growth.
3463 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3464 TargetFrameInfo::StackGrowsUp ?
3465 TD->getPointerSize() : -TD->getPointerSize();
3467 // Begin eh frame section.
3468 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3470 if (!TAI->doesRequireNonLocalEHFrameLabel())
3471 O << TAI->getEHGlobalPrefix();
3472 O << "EH_frame" << Index << ":\n";
3473 EmitLabel("section_eh_frame", Index);
3475 // Define base labels.
3476 EmitLabel("eh_frame_common", Index);
3478 // Define the eh frame length.
3479 EmitDifference("eh_frame_common_end", Index,
3480 "eh_frame_common_begin", Index, true);
3481 Asm->EOL("Length of Common Information Entry");
3484 EmitLabel("eh_frame_common_begin", Index);
3485 Asm->EmitInt32((int)0);
3486 Asm->EOL("CIE Identifier Tag");
3487 Asm->EmitInt8(DW_CIE_VERSION);
3488 Asm->EOL("CIE Version");
3490 // The personality presence indicates that language specific information
3491 // will show up in the eh frame.
3492 Asm->EmitString(Personality ? "zPLR" : "zR");
3493 Asm->EOL("CIE Augmentation");
3495 // Round out reader.
3496 Asm->EmitULEB128Bytes(1);
3497 Asm->EOL("CIE Code Alignment Factor");
3498 Asm->EmitSLEB128Bytes(stackGrowth);
3499 Asm->EOL("CIE Data Alignment Factor");
3500 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
3501 Asm->EOL("CIE Return Address Column");
3503 // If there is a personality, we need to indicate the functions location.
3505 Asm->EmitULEB128Bytes(7);
3506 Asm->EOL("Augmentation Size");
3508 if (TAI->getNeedsIndirectEncoding()) {
3509 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4 | DW_EH_PE_indirect);
3510 Asm->EOL("Personality (pcrel sdata4 indirect)");
3512 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3513 Asm->EOL("Personality (pcrel sdata4)");
3516 PrintRelDirective(true);
3517 O << TAI->getPersonalityPrefix();
3518 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
3519 O << TAI->getPersonalitySuffix();
3520 if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
3521 O << "-" << TAI->getPCSymbol();
3522 Asm->EOL("Personality");
3524 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3525 Asm->EOL("LSDA Encoding (pcrel sdata4)");
3527 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3528 Asm->EOL("FDE Encoding (pcrel sdata4)");
3530 Asm->EmitULEB128Bytes(1);
3531 Asm->EOL("Augmentation Size");
3533 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3534 Asm->EOL("FDE Encoding (pcrel sdata4)");
3537 // Indicate locations of general callee saved registers in frame.
3538 std::vector<MachineMove> Moves;
3539 RI->getInitialFrameState(Moves);
3540 EmitFrameMoves(NULL, 0, Moves, true);
3542 // On Darwin the linker honors the alignment of eh_frame, which means it
3543 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3544 // you get holes which confuse readers of eh_frame.
3545 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3547 EmitLabel("eh_frame_common_end", Index);
3552 /// EmitEHFrame - Emit function exception frame information.
3554 void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
3555 Function::LinkageTypes linkage = EHFrameInfo.function->getLinkage();
3557 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3559 // Externally visible entry into the functions eh frame info.
3560 // If the corresponding function is static, this should not be
3561 // externally visible.
3562 if (linkage != Function::InternalLinkage &&
3563 linkage != Function::PrivateLinkage) {
3564 if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
3565 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
3568 // If corresponding function is weak definition, this should be too.
3569 if ((linkage == Function::WeakAnyLinkage ||
3570 linkage == Function::WeakODRLinkage ||
3571 linkage == Function::LinkOnceAnyLinkage ||
3572 linkage == Function::LinkOnceODRLinkage) &&
3573 TAI->getWeakDefDirective())
3574 O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
3576 // If there are no calls then you can't unwind. This may mean we can
3577 // omit the EH Frame, but some environments do not handle weak absolute
3579 // If UnwindTablesMandatory is set we cannot do this optimization; the
3580 // unwind info is to be available for non-EH uses.
3581 if (!EHFrameInfo.hasCalls &&
3582 !UnwindTablesMandatory &&
3583 ((linkage != Function::WeakAnyLinkage &&
3584 linkage != Function::WeakODRLinkage &&
3585 linkage != Function::LinkOnceAnyLinkage &&
3586 linkage != Function::LinkOnceODRLinkage) ||
3587 !TAI->getWeakDefDirective() ||
3588 TAI->getSupportsWeakOmittedEHFrame()))
3590 O << EHFrameInfo.FnName << " = 0\n";
3591 // This name has no connection to the function, so it might get
3592 // dead-stripped when the function is not, erroneously. Prohibit
3593 // dead-stripping unconditionally.
3594 if (const char *UsedDirective = TAI->getUsedDirective())
3595 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3597 O << EHFrameInfo.FnName << ":\n";
3600 EmitDifference("eh_frame_end", EHFrameInfo.Number,
3601 "eh_frame_begin", EHFrameInfo.Number, true);
3602 Asm->EOL("Length of Frame Information Entry");
3604 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
3606 if (TAI->doesRequireNonLocalEHFrameLabel()) {
3607 PrintRelDirective(true, true);
3608 PrintLabelName("eh_frame_begin", EHFrameInfo.Number);
3610 if (!TAI->isAbsoluteEHSectionOffsets())
3611 O << "-EH_frame" << EHFrameInfo.PersonalityIndex;
3613 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
3614 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
3618 Asm->EOL("FDE CIE offset");
3620 EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
3621 Asm->EOL("FDE initial location");
3622 EmitDifference("eh_func_end", EHFrameInfo.Number,
3623 "eh_func_begin", EHFrameInfo.Number, true);
3624 Asm->EOL("FDE address range");
3626 // If there is a personality and landing pads then point to the language
3627 // specific data area in the exception table.
3628 if (EHFrameInfo.PersonalityIndex) {
3629 Asm->EmitULEB128Bytes(4);
3630 Asm->EOL("Augmentation size");
3632 if (EHFrameInfo.hasLandingPads)
3633 EmitReference("exception", EHFrameInfo.Number, true, true);
3635 Asm->EmitInt32((int)0);
3636 Asm->EOL("Language Specific Data Area");
3638 Asm->EmitULEB128Bytes(0);
3639 Asm->EOL("Augmentation size");
3642 // Indicate locations of function specific callee saved registers in
3644 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves,
3647 // On Darwin the linker honors the alignment of eh_frame, which means it
3648 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3649 // you get holes which confuse readers of eh_frame.
3650 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3652 EmitLabel("eh_frame_end", EHFrameInfo.Number);
3654 // If the function is marked used, this table should be also. We cannot
3655 // make the mark unconditional in this case, since retaining the table
3656 // also retains the function in this case, and there is code around
3657 // that depends on unused functions (calling undefined externals) being
3658 // dead-stripped to link correctly. Yes, there really is.
3659 if (MMI->getUsedFunctions().count(EHFrameInfo.function))
3660 if (const char *UsedDirective = TAI->getUsedDirective())
3661 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3665 /// EmitExceptionTable - Emit landing pads and actions.
3667 /// The general organization of the table is complex, but the basic concepts
3668 /// are easy. First there is a header which describes the location and
3669 /// organization of the three components that follow.
3670 /// 1. The landing pad site information describes the range of code covered
3671 /// by the try. In our case it's an accumulation of the ranges covered
3672 /// by the invokes in the try. There is also a reference to the landing
3673 /// pad that handles the exception once processed. Finally an index into
3674 /// the actions table.
3675 /// 2. The action table, in our case, is composed of pairs of type ids
3676 /// and next action offset. Starting with the action index from the
3677 /// landing pad site, each type Id is checked for a match to the current
3678 /// exception. If it matches then the exception and type id are passed
3679 /// on to the landing pad. Otherwise the next action is looked up. This
3680 /// chain is terminated with a next action of zero. If no type id is
3681 /// found the the frame is unwound and handling continues.
3682 /// 3. Type id table contains references to all the C++ typeinfo for all
3683 /// catches in the function. This tables is reversed indexed base 1.
3685 /// SharedTypeIds - How many leading type ids two landing pads have in common.
3686 static unsigned SharedTypeIds(const LandingPadInfo *L,
3687 const LandingPadInfo *R) {
3688 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3689 unsigned LSize = LIds.size(), RSize = RIds.size();
3690 unsigned MinSize = LSize < RSize ? LSize : RSize;
3693 for (; Count != MinSize; ++Count)
3694 if (LIds[Count] != RIds[Count])
3700 /// PadLT - Order landing pads lexicographically by type id.
3701 static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
3702 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3703 unsigned LSize = LIds.size(), RSize = RIds.size();
3704 unsigned MinSize = LSize < RSize ? LSize : RSize;
3706 for (unsigned i = 0; i != MinSize; ++i)
3707 if (LIds[i] != RIds[i])
3708 return LIds[i] < RIds[i];
3710 return LSize < RSize;
3714 static inline unsigned getEmptyKey() { return -1U; }
3715 static inline unsigned getTombstoneKey() { return -2U; }
3716 static unsigned getHashValue(const unsigned &Key) { return Key; }
3717 static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
3718 static bool isPod() { return true; }
3721 /// ActionEntry - Structure describing an entry in the actions table.
3722 struct ActionEntry {
3723 int ValueForTypeID; // The value to write - may not be equal to the type id.
3725 struct ActionEntry *Previous;
3728 /// PadRange - Structure holding a try-range and the associated landing pad.
3730 // The index of the landing pad.
3732 // The index of the begin and end labels in the landing pad's label lists.
3733 unsigned RangeIndex;
3736 typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
3738 /// CallSiteEntry - Structure describing an entry in the call-site table.
3739 struct CallSiteEntry {
3740 // The 'try-range' is BeginLabel .. EndLabel.
3741 unsigned BeginLabel; // zero indicates the start of the function.
3742 unsigned EndLabel; // zero indicates the end of the function.
3743 // The landing pad starts at PadLabel.
3744 unsigned PadLabel; // zero indicates that there is no landing pad.
3748 void EmitExceptionTable() {
3749 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
3750 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
3751 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
3752 if (PadInfos.empty()) return;
3754 // Sort the landing pads in order of their type ids. This is used to fold
3755 // duplicate actions.
3756 SmallVector<const LandingPadInfo *, 64> LandingPads;
3757 LandingPads.reserve(PadInfos.size());
3758 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
3759 LandingPads.push_back(&PadInfos[i]);
3760 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
3762 // Negative type ids index into FilterIds, positive type ids index into
3763 // TypeInfos. The value written for a positive type id is just the type
3764 // id itself. For a negative type id, however, the value written is the
3765 // (negative) byte offset of the corresponding FilterIds entry. The byte
3766 // offset is usually equal to the type id, because the FilterIds entries
3767 // are written using a variable width encoding which outputs one byte per
3768 // entry as long as the value written is not too large, but can differ.
3769 // This kind of complication does not occur for positive type ids because
3770 // type infos are output using a fixed width encoding.
3771 // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
3772 SmallVector<int, 16> FilterOffsets;
3773 FilterOffsets.reserve(FilterIds.size());
3775 for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
3776 E = FilterIds.end(); I != E; ++I) {
3777 FilterOffsets.push_back(Offset);
3778 Offset -= TargetAsmInfo::getULEB128Size(*I);
3781 // Compute the actions table and gather the first action index for each
3782 // landing pad site.
3783 SmallVector<ActionEntry, 32> Actions;
3784 SmallVector<unsigned, 64> FirstActions;
3785 FirstActions.reserve(LandingPads.size());
3787 int FirstAction = 0;
3788 unsigned SizeActions = 0;
3789 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3790 const LandingPadInfo *LP = LandingPads[i];
3791 const std::vector<int> &TypeIds = LP->TypeIds;
3792 const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
3793 unsigned SizeSiteActions = 0;
3795 if (NumShared < TypeIds.size()) {
3796 unsigned SizeAction = 0;
3797 ActionEntry *PrevAction = 0;
3800 const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
3801 assert(Actions.size());
3802 PrevAction = &Actions.back();
3803 SizeAction = TargetAsmInfo::getSLEB128Size(PrevAction->NextAction) +
3804 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3805 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
3807 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3808 SizeAction += -PrevAction->NextAction;
3809 PrevAction = PrevAction->Previous;
3813 // Compute the actions.
3814 for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
3815 int TypeID = TypeIds[I];
3816 assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
3817 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
3818 unsigned SizeTypeID = TargetAsmInfo::getSLEB128Size(ValueForTypeID);
3820 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
3821 SizeAction = SizeTypeID + TargetAsmInfo::getSLEB128Size(NextAction);
3822 SizeSiteActions += SizeAction;
3824 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
3825 Actions.push_back(Action);
3827 PrevAction = &Actions.back();
3830 // Record the first action of the landing pad site.
3831 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
3832 } // else identical - re-use previous FirstAction
3834 FirstActions.push_back(FirstAction);
3836 // Compute this sites contribution to size.
3837 SizeActions += SizeSiteActions;
3840 // Compute the call-site table. The entry for an invoke has a try-range
3841 // containing the call, a non-zero landing pad and an appropriate action.
3842 // The entry for an ordinary call has a try-range containing the call and
3843 // zero for the landing pad and the action. Calls marked 'nounwind' have
3844 // no entry and must not be contained in the try-range of any entry - they
3845 // form gaps in the table. Entries must be ordered by try-range address.
3846 SmallVector<CallSiteEntry, 64> CallSites;
3848 RangeMapType PadMap;
3849 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
3850 // by try-range labels when lowered). Ordinary calls do not, so appropriate
3851 // try-ranges for them need be deduced.
3852 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3853 const LandingPadInfo *LandingPad = LandingPads[i];
3854 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
3855 unsigned BeginLabel = LandingPad->BeginLabels[j];
3856 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
3857 PadRange P = { i, j };
3858 PadMap[BeginLabel] = P;
3862 // The end label of the previous invoke or nounwind try-range.
3863 unsigned LastLabel = 0;
3865 // Whether there is a potentially throwing instruction (currently this means
3866 // an ordinary call) between the end of the previous try-range and now.
3867 bool SawPotentiallyThrowing = false;
3869 // Whether the last callsite entry was for an invoke.
3870 bool PreviousIsInvoke = false;
3872 // Visit all instructions in order of address.
3873 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
3875 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
3877 if (!MI->isLabel()) {
3878 SawPotentiallyThrowing |= MI->getDesc().isCall();
3882 unsigned BeginLabel = MI->getOperand(0).getImm();
3883 assert(BeginLabel && "Invalid label!");
3885 // End of the previous try-range?
3886 if (BeginLabel == LastLabel)
3887 SawPotentiallyThrowing = false;
3889 // Beginning of a new try-range?
3890 RangeMapType::iterator L = PadMap.find(BeginLabel);
3891 if (L == PadMap.end())
3892 // Nope, it was just some random label.
3895 PadRange P = L->second;
3896 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
3898 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
3899 "Inconsistent landing pad map!");
3901 // If some instruction between the previous try-range and this one may
3902 // throw, create a call-site entry with no landing pad for the region
3903 // between the try-ranges.
3904 if (SawPotentiallyThrowing) {
3905 CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
3906 CallSites.push_back(Site);
3907 PreviousIsInvoke = false;
3910 LastLabel = LandingPad->EndLabels[P.RangeIndex];
3911 assert(BeginLabel && LastLabel && "Invalid landing pad!");
3913 if (LandingPad->LandingPadLabel) {
3914 // This try-range is for an invoke.
3915 CallSiteEntry Site = {BeginLabel, LastLabel,
3916 LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
3918 // Try to merge with the previous call-site.
3919 if (PreviousIsInvoke) {
3920 CallSiteEntry &Prev = CallSites.back();
3921 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
3922 // Extend the range of the previous entry.
3923 Prev.EndLabel = Site.EndLabel;
3928 // Otherwise, create a new call-site.
3929 CallSites.push_back(Site);
3930 PreviousIsInvoke = true;
3933 PreviousIsInvoke = false;
3937 // If some instruction between the previous try-range and the end of the
3938 // function may throw, create a call-site entry with no landing pad for the
3939 // region following the try-range.
3940 if (SawPotentiallyThrowing) {
3941 CallSiteEntry Site = {LastLabel, 0, 0, 0};
3942 CallSites.push_back(Site);
3948 const unsigned SiteStartSize = sizeof(int32_t); // DW_EH_PE_udata4
3949 const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
3950 const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
3951 unsigned SizeSites = CallSites.size() * (SiteStartSize +
3954 for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
3955 SizeSites += TargetAsmInfo::getULEB128Size(CallSites[i].Action);
3958 const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
3959 unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
3961 unsigned TypeOffset = sizeof(int8_t) + // Call site format
3962 TargetAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
3963 SizeSites + SizeActions + SizeTypes;
3965 unsigned TotalSize = sizeof(int8_t) + // LPStart format
3966 sizeof(int8_t) + // TType format
3967 TargetAsmInfo::getULEB128Size(TypeOffset) + // TType base offset
3970 unsigned SizeAlign = (4 - TotalSize) & 3;
3972 // Begin the exception table.
3973 Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
3974 Asm->EmitAlignment(2, 0, 0, false);
3975 O << "GCC_except_table" << SubprogramCount << ":\n";
3976 for (unsigned i = 0; i != SizeAlign; ++i) {
3978 Asm->EOL("Padding");
3980 EmitLabel("exception", SubprogramCount);
3983 Asm->EmitInt8(DW_EH_PE_omit);
3984 Asm->EOL("LPStart format (DW_EH_PE_omit)");
3985 Asm->EmitInt8(DW_EH_PE_absptr);
3986 Asm->EOL("TType format (DW_EH_PE_absptr)");
3987 Asm->EmitULEB128Bytes(TypeOffset);
3988 Asm->EOL("TType base offset");
3989 Asm->EmitInt8(DW_EH_PE_udata4);
3990 Asm->EOL("Call site format (DW_EH_PE_udata4)");
3991 Asm->EmitULEB128Bytes(SizeSites);
3992 Asm->EOL("Call-site table length");
3994 // Emit the landing pad site information.
3995 for (unsigned i = 0; i < CallSites.size(); ++i) {
3996 CallSiteEntry &S = CallSites[i];
3997 const char *BeginTag;
3998 unsigned BeginNumber;
4000 if (!S.BeginLabel) {
4001 BeginTag = "eh_func_begin";
4002 BeginNumber = SubprogramCount;
4005 BeginNumber = S.BeginLabel;
4008 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
4010 Asm->EOL("Region start");
4013 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
4016 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
4018 Asm->EOL("Region length");
4023 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
4025 Asm->EOL("Landing pad");
4027 Asm->EmitULEB128Bytes(S.Action);
4031 // Emit the actions.
4032 for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
4033 ActionEntry &Action = Actions[I];
4035 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
4036 Asm->EOL("TypeInfo index");
4037 Asm->EmitSLEB128Bytes(Action.NextAction);
4038 Asm->EOL("Next action");
4041 // Emit the type ids.
4042 for (unsigned M = TypeInfos.size(); M; --M) {
4043 GlobalVariable *GV = TypeInfos[M - 1];
4045 PrintRelDirective();
4048 O << Asm->getGlobalLinkName(GV);
4052 Asm->EOL("TypeInfo");
4055 // Emit the filter typeids.
4056 for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
4057 unsigned TypeID = FilterIds[j];
4058 Asm->EmitULEB128Bytes(TypeID);
4059 Asm->EOL("Filter TypeInfo index");
4062 Asm->EmitAlignment(2, 0, 0, false);
4066 //===--------------------------------------------------------------------===//
4067 // Main entry points.
4069 DwarfException(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
4070 : Dwarf(OS, A, T, "eh"), shouldEmitTable(false), shouldEmitMoves(false),
4071 shouldEmitTableModule(false), shouldEmitMovesModule(false),
4073 if (TimePassesIsEnabled)
4074 ExceptionTimer = new Timer("Dwarf Exception Writer",
4075 *getDwarfTimerGroup());
4078 virtual ~DwarfException() {
4079 delete ExceptionTimer;
4082 /// SetModuleInfo - Set machine module information when it's known that pass
4083 /// manager has created it. Set by the target AsmPrinter.
4084 void SetModuleInfo(MachineModuleInfo *mmi) {
4088 /// BeginModule - Emit all exception information that should come prior to the
4090 void BeginModule(Module *M) {
4094 /// EndModule - Emit all exception information that should come after the
4097 if (TimePassesIsEnabled)
4098 ExceptionTimer->startTimer();
4100 if (shouldEmitMovesModule || shouldEmitTableModule) {
4101 const std::vector<Function *> Personalities = MMI->getPersonalities();
4102 for (unsigned i = 0; i < Personalities.size(); ++i)
4103 EmitCommonEHFrame(Personalities[i], i);
4105 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
4106 E = EHFrames.end(); I != E; ++I)
4110 if (TimePassesIsEnabled)
4111 ExceptionTimer->stopTimer();
4114 /// BeginFunction - Gather pre-function exception information. Assumes being
4115 /// emitted immediately after the function entry point.
4116 void BeginFunction(MachineFunction *MF) {
4117 if (TimePassesIsEnabled)
4118 ExceptionTimer->startTimer();
4121 shouldEmitTable = shouldEmitMoves = false;
4123 if (MMI && TAI->doesSupportExceptionHandling()) {
4124 // Map all labels and get rid of any dead landing pads.
4125 MMI->TidyLandingPads();
4127 // If any landing pads survive, we need an EH table.
4128 if (MMI->getLandingPads().size())
4129 shouldEmitTable = true;
4131 // See if we need frame move info.
4132 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
4133 shouldEmitMoves = true;
4135 if (shouldEmitMoves || shouldEmitTable)
4136 // Assumes in correct section after the entry point.
4137 EmitLabel("eh_func_begin", ++SubprogramCount);
4140 shouldEmitTableModule |= shouldEmitTable;
4141 shouldEmitMovesModule |= shouldEmitMoves;
4143 if (TimePassesIsEnabled)
4144 ExceptionTimer->stopTimer();
4147 /// EndFunction - Gather and emit post-function exception information.
4149 void EndFunction() {
4150 if (TimePassesIsEnabled)
4151 ExceptionTimer->startTimer();
4153 if (shouldEmitMoves || shouldEmitTable) {
4154 EmitLabel("eh_func_end", SubprogramCount);
4155 EmitExceptionTable();
4157 // Save EH frame information
4159 push_back(FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
4161 MMI->getPersonalityIndex(),
4162 MF->getFrameInfo()->hasCalls(),
4163 !MMI->getLandingPads().empty(),
4164 MMI->getFrameMoves(),
4165 MF->getFunction()));
4168 if (TimePassesIsEnabled)
4169 ExceptionTimer->stopTimer();
4173 } // End of namespace llvm
4175 //===----------------------------------------------------------------------===//
4177 /// Emit - Print the abbreviation using the specified Dwarf writer.
4179 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
4180 // Emit its Dwarf tag type.
4181 DD.getAsm()->EmitULEB128Bytes(Tag);
4182 DD.getAsm()->EOL(TagString(Tag));
4184 // Emit whether it has children DIEs.
4185 DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
4186 DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
4188 // For each attribute description.
4189 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4190 const DIEAbbrevData &AttrData = Data[i];
4192 // Emit attribute type.
4193 DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
4194 DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
4197 DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
4198 DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
4201 // Mark end of abbreviation.
4202 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
4203 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
4207 void DIEAbbrev::print(std::ostream &O) {
4208 O << "Abbreviation @"
4209 << std::hex << (intptr_t)this << std::dec
4213 << ChildrenString(ChildrenFlag)
4216 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4218 << AttributeString(Data[i].getAttribute())
4220 << FormEncodingString(Data[i].getForm())
4224 void DIEAbbrev::dump() { print(cerr); }
4227 //===----------------------------------------------------------------------===//
4230 void DIEValue::dump() {
4235 //===----------------------------------------------------------------------===//
4237 /// EmitValue - Emit integer of appropriate size.
4239 void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
4241 case DW_FORM_flag: // Fall thru
4242 case DW_FORM_ref1: // Fall thru
4243 case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer); break;
4244 case DW_FORM_ref2: // Fall thru
4245 case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer); break;
4246 case DW_FORM_ref4: // Fall thru
4247 case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer); break;
4248 case DW_FORM_ref8: // Fall thru
4249 case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer); break;
4250 case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
4251 case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
4252 default: assert(0 && "DIE Value form not supported yet"); break;
4256 /// SizeOf - Determine size of integer value in bytes.
4258 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4260 case DW_FORM_flag: // Fall thru
4261 case DW_FORM_ref1: // Fall thru
4262 case DW_FORM_data1: return sizeof(int8_t);
4263 case DW_FORM_ref2: // Fall thru
4264 case DW_FORM_data2: return sizeof(int16_t);
4265 case DW_FORM_ref4: // Fall thru
4266 case DW_FORM_data4: return sizeof(int32_t);
4267 case DW_FORM_ref8: // Fall thru
4268 case DW_FORM_data8: return sizeof(int64_t);
4269 case DW_FORM_udata: return TargetAsmInfo::getULEB128Size(Integer);
4270 case DW_FORM_sdata: return TargetAsmInfo::getSLEB128Size(Integer);
4271 default: assert(0 && "DIE Value form not supported yet"); break;
4276 //===----------------------------------------------------------------------===//
4278 /// EmitValue - Emit string value.
4280 void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
4281 DD.getAsm()->EmitString(String);
4284 //===----------------------------------------------------------------------===//
4286 /// EmitValue - Emit label value.
4288 void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4289 bool IsSmall = Form == DW_FORM_data4;
4290 DD.EmitReference(Label, false, IsSmall);
4293 /// SizeOf - Determine size of label value in bytes.
4295 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4296 if (Form == DW_FORM_data4) return 4;
4297 return DD.getTargetData()->getPointerSize();
4300 //===----------------------------------------------------------------------===//
4302 /// EmitValue - Emit label value.
4304 void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4305 bool IsSmall = Form == DW_FORM_data4;
4306 DD.EmitReference(Label, false, IsSmall);
4309 /// SizeOf - Determine size of label value in bytes.
4311 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4312 if (Form == DW_FORM_data4) return 4;
4313 return DD.getTargetData()->getPointerSize();
4316 //===----------------------------------------------------------------------===//
4318 /// EmitValue - Emit delta value.
4320 void DIESectionOffset::EmitValue(DwarfDebug &DD, unsigned Form) {
4321 bool IsSmall = Form == DW_FORM_data4;
4322 DD.EmitSectionOffset(Label.Tag, Section.Tag,
4323 Label.Number, Section.Number, IsSmall, IsEH, UseSet);
4326 /// SizeOf - Determine size of delta value in bytes.
4328 unsigned DIESectionOffset::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4329 if (Form == DW_FORM_data4) return 4;
4330 return DD.getTargetData()->getPointerSize();
4333 //===----------------------------------------------------------------------===//
4335 /// EmitValue - Emit delta value.
4337 void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
4338 bool IsSmall = Form == DW_FORM_data4;
4339 DD.EmitDifference(LabelHi, LabelLo, IsSmall);
4342 /// SizeOf - Determine size of delta value in bytes.
4344 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4345 if (Form == DW_FORM_data4) return 4;
4346 return DD.getTargetData()->getPointerSize();
4349 //===----------------------------------------------------------------------===//
4351 /// EmitValue - Emit debug information entry offset.
4353 void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
4354 DD.getAsm()->EmitInt32(Entry->getOffset());
4357 //===----------------------------------------------------------------------===//
4359 /// ComputeSize - calculate the size of the block.
4361 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
4363 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4365 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4366 Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
4372 /// EmitValue - Emit block data.
4374 void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
4376 case DW_FORM_block1: DD.getAsm()->EmitInt8(Size); break;
4377 case DW_FORM_block2: DD.getAsm()->EmitInt16(Size); break;
4378 case DW_FORM_block4: DD.getAsm()->EmitInt32(Size); break;
4379 case DW_FORM_block: DD.getAsm()->EmitULEB128Bytes(Size); break;
4380 default: assert(0 && "Improper form for block"); break;
4383 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4385 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4387 Values[i]->EmitValue(DD, AbbrevData[i].getForm());
4391 /// SizeOf - Determine size of block data in bytes.
4393 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4395 case DW_FORM_block1: return Size + sizeof(int8_t);
4396 case DW_FORM_block2: return Size + sizeof(int16_t);
4397 case DW_FORM_block4: return Size + sizeof(int32_t);
4398 case DW_FORM_block: return Size + TargetAsmInfo::getULEB128Size(Size);
4399 default: assert(0 && "Improper form for block"); break;
4404 //===----------------------------------------------------------------------===//
4405 /// DIE Implementation
4408 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4412 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
4414 void DIE::AddSiblingOffset() {
4415 DIEInteger *DI = new DIEInteger(0);
4416 Values.insert(Values.begin(), DI);
4417 Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
4420 /// Profile - Used to gather unique data for the value folding set.
4422 void DIE::Profile(FoldingSetNodeID &ID) {
4425 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4426 ID.AddPointer(Children[i]);
4428 for (unsigned j = 0, M = Values.size(); j < M; ++j)
4429 ID.AddPointer(Values[j]);
4433 void DIE::print(std::ostream &O, unsigned IncIndent) {
4434 static unsigned IndentCount = 0;
4435 IndentCount += IncIndent;
4436 const std::string Indent(IndentCount, ' ');
4437 bool isBlock = Abbrev.getTag() == 0;
4442 << "0x" << std::hex << (intptr_t)this << std::dec
4443 << ", Offset: " << Offset
4444 << ", Size: " << Size
4448 << TagString(Abbrev.getTag())
4450 << ChildrenString(Abbrev.getChildrenFlag());
4452 O << "Size: " << Size;
4456 const SmallVector<DIEAbbrevData, 8> &Data = Abbrev.getData();
4459 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4463 O << AttributeString(Data[i].getAttribute());
4465 O << "Blk[" << i << "]";
4468 << FormEncodingString(Data[i].getForm())
4470 Values[i]->print(O);
4475 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
4476 Children[j]->print(O, 4);
4479 if (!isBlock) O << "\n";
4480 IndentCount -= IncIndent;
4488 //===----------------------------------------------------------------------===//
4489 /// DwarfWriter Implementation
4492 DwarfWriter::DwarfWriter()
4493 : ImmutablePass(&ID), DD(0), DE(0) {}
4495 DwarfWriter::~DwarfWriter() {
4498 delete DwarfTimerGroup; DwarfTimerGroup = 0;
4501 /// BeginModule - Emit all Dwarf sections that should come prior to the
4503 void DwarfWriter::BeginModule(Module *M,
4504 MachineModuleInfo *MMI,
4505 raw_ostream &OS, AsmPrinter *A,
4506 const TargetAsmInfo *T) {
4507 DE = new DwarfException(OS, A, T);
4508 DD = new DwarfDebug(OS, A, T);
4511 DD->SetDebugInfo(MMI);
4512 DE->SetModuleInfo(MMI);
4515 /// EndModule - Emit all Dwarf sections that should come after the content.
4517 void DwarfWriter::EndModule() {
4522 /// BeginFunction - Gather pre-function debug information. Assumes being
4523 /// emitted immediately after the function entry point.
4524 void DwarfWriter::BeginFunction(MachineFunction *MF) {
4525 DE->BeginFunction(MF);
4526 DD->BeginFunction(MF);
4529 /// EndFunction - Gather and emit post-function debug information.
4531 void DwarfWriter::EndFunction(MachineFunction *MF) {
4532 DD->EndFunction(MF);
4535 if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI())
4536 // Clear function debug information.
4540 /// ValidDebugInfo - Return true if V represents valid debug info value.
4541 bool DwarfWriter::ValidDebugInfo(Value *V) {
4542 return DD && DD->ValidDebugInfo(V);
4545 /// RecordSourceLine - Records location information and associates it with a
4546 /// label. Returns a unique label ID used to generate a label and provide
4547 /// correspondence to the source line list.
4548 unsigned DwarfWriter::RecordSourceLine(unsigned Line, unsigned Col,
4550 return DD->RecordSourceLine(Line, Col, Src);
4553 /// getOrCreateSourceID - Look up the source id with the given directory and
4554 /// source file names. If none currently exists, create a new id and insert it
4555 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames maps
4557 unsigned DwarfWriter::getOrCreateSourceID(const std::string &DirName,
4558 const std::string &FileName) {
4559 return DD->getOrCreateSourceID(DirName, FileName);
4562 /// RecordRegionStart - Indicate the start of a region.
4563 unsigned DwarfWriter::RecordRegionStart(GlobalVariable *V) {
4564 return DD->RecordRegionStart(V);
4567 /// RecordRegionEnd - Indicate the end of a region.
4568 unsigned DwarfWriter::RecordRegionEnd(GlobalVariable *V) {
4569 return DD->RecordRegionEnd(V);
4572 /// getRecordSourceLineCount - Count source lines.
4573 unsigned DwarfWriter::getRecordSourceLineCount() {
4574 return DD->getRecordSourceLineCount();
4577 /// RecordVariable - Indicate the declaration of a local variable.
4579 void DwarfWriter::RecordVariable(GlobalVariable *GV, unsigned FrameIndex) {
4580 DD->RecordVariable(GV, FrameIndex);
4583 /// ShouldEmitDwarfDebug - Returns true if Dwarf debugging declarations should
4585 bool DwarfWriter::ShouldEmitDwarfDebug() const {
4586 return DD->ShouldEmitDwarfDebug();