Provide addc and subc
[llvm/msp430.git] / lib / CodeGen / AsmPrinter / DwarfWriter.cpp
blob848f45ea8c988c52fce16f79e26db7b91ac869bc
1 //===-- llvm/CodeGen/DwarfWriter.cpp - Dwarf Framework ----------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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"
42 #include <ostream>
43 #include <string>
44 using namespace llvm;
45 using namespace llvm::dwarf;
47 static RegisterPass<DwarfWriter>
48 X("dwarfwriter", "DWARF Information Writer");
49 char DwarfWriter::ID = 0;
51 static TimerGroup &getDwarfTimerGroup() {
52 static TimerGroup DwarfTimerGroup("Dwarf Exception and Debugging");
53 return DwarfTimerGroup;
56 namespace llvm {
58 //===----------------------------------------------------------------------===//
60 /// Configuration values for initial hash set sizes (log2).
61 ///
62 static const unsigned InitDiesSetSize = 9; // log2(512)
63 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
64 static const unsigned InitValuesSetSize = 9; // log2(512)
66 //===----------------------------------------------------------------------===//
67 /// Forward declarations.
68 ///
69 class DIE;
70 class DIEValue;
72 //===----------------------------------------------------------------------===//
73 /// DWLabel - Labels are used to track locations in the assembler file.
74 /// Labels appear in the form @verbatim <prefix><Tag><Number> @endverbatim,
75 /// where the tag is a category of label (Ex. location) and number is a value
76 /// unique in that category.
77 class DWLabel {
78 public:
79 /// Tag - Label category tag. Should always be a staticly declared C string.
80 ///
81 const char *Tag;
83 /// Number - Value to make label unique.
84 ///
85 unsigned Number;
87 DWLabel(const char *T, unsigned N) : Tag(T), Number(N) {}
89 void Profile(FoldingSetNodeID &ID) const {
90 ID.AddString(Tag);
91 ID.AddInteger(Number);
94 #ifndef NDEBUG
95 void print(std::ostream *O) const {
96 if (O) print(*O);
98 void print(std::ostream &O) const {
99 O << "." << Tag;
100 if (Number) O << Number;
102 #endif
105 //===----------------------------------------------------------------------===//
106 /// DIEAbbrevData - Dwarf abbreviation data, describes the one attribute of a
107 /// Dwarf abbreviation.
108 class DIEAbbrevData {
109 /// Attribute - Dwarf attribute code.
111 unsigned Attribute;
113 /// Form - Dwarf form code.
115 unsigned Form;
116 public:
117 DIEAbbrevData(unsigned A, unsigned F) : Attribute(A), Form(F) {}
119 // Accessors.
120 unsigned getAttribute() const { return Attribute; }
121 unsigned getForm() const { return Form; }
123 /// Profile - Used to gather unique data for the abbreviation folding set.
125 void Profile(FoldingSetNodeID &ID)const {
126 ID.AddInteger(Attribute);
127 ID.AddInteger(Form);
131 //===----------------------------------------------------------------------===//
132 /// DIEAbbrev - Dwarf abbreviation, describes the organization of a debug
133 /// information object.
134 class DIEAbbrev : public FoldingSetNode {
135 private:
136 /// Tag - Dwarf tag code.
138 unsigned Tag;
140 /// Unique number for node.
142 unsigned Number;
144 /// ChildrenFlag - Dwarf children flag.
146 unsigned ChildrenFlag;
148 /// Data - Raw data bytes for abbreviation.
150 SmallVector<DIEAbbrevData, 8> Data;
151 public:
152 DIEAbbrev(unsigned T, unsigned C) : Tag(T), ChildrenFlag(C), Data() {}
153 virtual ~DIEAbbrev() {}
155 // Accessors.
156 unsigned getTag() const { return Tag; }
157 unsigned getNumber() const { return Number; }
158 unsigned getChildrenFlag() const { return ChildrenFlag; }
159 const SmallVector<DIEAbbrevData, 8> &getData() const { return Data; }
160 void setTag(unsigned T) { Tag = T; }
161 void setChildrenFlag(unsigned CF) { ChildrenFlag = CF; }
162 void setNumber(unsigned N) { Number = N; }
164 /// AddAttribute - Adds another set of attribute information to the
165 /// abbreviation.
166 void AddAttribute(unsigned Attribute, unsigned Form) {
167 Data.push_back(DIEAbbrevData(Attribute, Form));
170 /// AddFirstAttribute - Adds a set of attribute information to the front
171 /// of the abbreviation.
172 void AddFirstAttribute(unsigned Attribute, unsigned Form) {
173 Data.insert(Data.begin(), DIEAbbrevData(Attribute, Form));
176 /// Profile - Used to gather unique data for the abbreviation folding set.
178 void Profile(FoldingSetNodeID &ID) {
179 ID.AddInteger(Tag);
180 ID.AddInteger(ChildrenFlag);
182 // For each attribute description.
183 for (unsigned i = 0, N = Data.size(); i < N; ++i)
184 Data[i].Profile(ID);
187 /// Emit - Print the abbreviation using the specified Dwarf writer.
189 void Emit(const DwarfDebug &DD) const;
191 #ifndef NDEBUG
192 void print(std::ostream *O) {
193 if (O) print(*O);
195 void print(std::ostream &O);
196 void dump();
197 #endif
200 //===----------------------------------------------------------------------===//
201 /// DIE - A structured debug information entry. Has an abbreviation which
202 /// describes it's organization.
203 class DIE : public FoldingSetNode {
204 protected:
205 /// Abbrev - Buffer for constructing abbreviation.
207 DIEAbbrev Abbrev;
209 /// Offset - Offset in debug info section.
211 unsigned Offset;
213 /// Size - Size of instance + children.
215 unsigned Size;
217 /// Children DIEs.
219 std::vector<DIE *> Children;
221 /// Attributes values.
223 SmallVector<DIEValue*, 32> Values;
225 public:
226 explicit DIE(unsigned Tag)
227 : Abbrev(Tag, DW_CHILDREN_no), Offset(0), Size(0), Children(), Values() {}
228 virtual ~DIE();
230 // Accessors.
231 DIEAbbrev &getAbbrev() { return Abbrev; }
232 unsigned getAbbrevNumber() const {
233 return Abbrev.getNumber();
235 unsigned getTag() const { return Abbrev.getTag(); }
236 unsigned getOffset() const { return Offset; }
237 unsigned getSize() const { return Size; }
238 const std::vector<DIE *> &getChildren() const { return Children; }
239 SmallVector<DIEValue*, 32> &getValues() { return Values; }
240 void setTag(unsigned Tag) { Abbrev.setTag(Tag); }
241 void setOffset(unsigned O) { Offset = O; }
242 void setSize(unsigned S) { Size = S; }
244 /// AddValue - Add a value and attributes to a DIE.
246 void AddValue(unsigned Attribute, unsigned Form, DIEValue *Value) {
247 Abbrev.AddAttribute(Attribute, Form);
248 Values.push_back(Value);
251 /// SiblingOffset - Return the offset of the debug information entry's
252 /// sibling.
253 unsigned SiblingOffset() const { return Offset + Size; }
255 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
257 void AddSiblingOffset();
259 /// AddChild - Add a child to the DIE.
261 void AddChild(DIE *Child) {
262 Abbrev.setChildrenFlag(DW_CHILDREN_yes);
263 Children.push_back(Child);
266 /// Detach - Detaches objects connected to it after copying.
268 void Detach() {
269 Children.clear();
272 /// Profile - Used to gather unique data for the value folding set.
274 void Profile(FoldingSetNodeID &ID) ;
276 #ifndef NDEBUG
277 void print(std::ostream *O, unsigned IncIndent = 0) {
278 if (O) print(*O, IncIndent);
280 void print(std::ostream &O, unsigned IncIndent = 0);
281 void dump();
282 #endif
285 //===----------------------------------------------------------------------===//
286 /// DIEValue - A debug information entry value.
288 class DIEValue : public FoldingSetNode {
289 public:
290 enum {
291 isInteger,
292 isString,
293 isLabel,
294 isAsIsLabel,
295 isSectionOffset,
296 isDelta,
297 isEntry,
298 isBlock
301 /// Type - Type of data stored in the value.
303 unsigned Type;
305 explicit DIEValue(unsigned T) : Type(T) {}
306 virtual ~DIEValue() {}
308 // Accessors
309 unsigned getType() const { return Type; }
311 // Implement isa/cast/dyncast.
312 static bool classof(const DIEValue *) { return true; }
314 /// EmitValue - Emit value via the Dwarf writer.
316 virtual void EmitValue(DwarfDebug &DD, unsigned Form) = 0;
318 /// SizeOf - Return the size of a value in bytes.
320 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const = 0;
322 /// Profile - Used to gather unique data for the value folding set.
324 virtual void Profile(FoldingSetNodeID &ID) = 0;
326 #ifndef NDEBUG
327 void print(std::ostream *O) {
328 if (O) print(*O);
330 virtual void print(std::ostream &O) = 0;
331 void dump();
332 #endif
335 //===----------------------------------------------------------------------===//
336 /// DWInteger - An integer value DIE.
338 class DIEInteger : public DIEValue {
339 private:
340 uint64_t Integer;
342 public:
343 explicit DIEInteger(uint64_t I) : DIEValue(isInteger), Integer(I) {}
345 // Implement isa/cast/dyncast.
346 static bool classof(const DIEInteger *) { return true; }
347 static bool classof(const DIEValue *I) { return I->Type == isInteger; }
349 /// BestForm - Choose the best form for integer.
351 static unsigned BestForm(bool IsSigned, uint64_t Integer) {
352 if (IsSigned) {
353 if ((char)Integer == (signed)Integer) return DW_FORM_data1;
354 if ((short)Integer == (signed)Integer) return DW_FORM_data2;
355 if ((int)Integer == (signed)Integer) return DW_FORM_data4;
356 } else {
357 if ((unsigned char)Integer == Integer) return DW_FORM_data1;
358 if ((unsigned short)Integer == Integer) return DW_FORM_data2;
359 if ((unsigned int)Integer == Integer) return DW_FORM_data4;
361 return DW_FORM_data8;
364 /// EmitValue - Emit integer of appropriate size.
366 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
368 /// SizeOf - Determine size of integer value in bytes.
370 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
372 /// Profile - Used to gather unique data for the value folding set.
374 static void Profile(FoldingSetNodeID &ID, unsigned Integer) {
375 ID.AddInteger(isInteger);
376 ID.AddInteger(Integer);
378 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Integer); }
380 #ifndef NDEBUG
381 virtual void print(std::ostream &O) {
382 O << "Int: " << (int64_t)Integer
383 << " 0x" << std::hex << Integer << std::dec;
385 #endif
388 //===----------------------------------------------------------------------===//
389 /// DIEString - A string value DIE.
391 class DIEString : public DIEValue {
392 const std::string Str;
393 public:
394 explicit DIEString(const std::string &S) : DIEValue(isString), Str(S) {}
396 // Implement isa/cast/dyncast.
397 static bool classof(const DIEString *) { return true; }
398 static bool classof(const DIEValue *S) { return S->Type == isString; }
400 /// EmitValue - Emit string value.
402 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
404 /// SizeOf - Determine size of string value in bytes.
406 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
407 return Str.size() + sizeof(char); // sizeof('\0');
410 /// Profile - Used to gather unique data for the value folding set.
412 static void Profile(FoldingSetNodeID &ID, const std::string &Str) {
413 ID.AddInteger(isString);
414 ID.AddString(Str);
416 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Str); }
418 #ifndef NDEBUG
419 virtual void print(std::ostream &O) {
420 O << "Str: \"" << Str << "\"";
422 #endif
425 //===----------------------------------------------------------------------===//
426 /// DIEDwarfLabel - A Dwarf internal label expression DIE.
428 class DIEDwarfLabel : public DIEValue {
429 const DWLabel Label;
430 public:
431 explicit DIEDwarfLabel(const DWLabel &L) : DIEValue(isLabel), Label(L) {}
433 // Implement isa/cast/dyncast.
434 static bool classof(const DIEDwarfLabel *) { return true; }
435 static bool classof(const DIEValue *L) { return L->Type == isLabel; }
437 /// EmitValue - Emit label value.
439 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
441 /// SizeOf - Determine size of label value in bytes.
443 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
445 /// Profile - Used to gather unique data for the value folding set.
447 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label) {
448 ID.AddInteger(isLabel);
449 Label.Profile(ID);
451 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
453 #ifndef NDEBUG
454 virtual void print(std::ostream &O) {
455 O << "Lbl: ";
456 Label.print(O);
458 #endif
461 //===----------------------------------------------------------------------===//
462 /// DIEObjectLabel - A label to an object in code or data.
464 class DIEObjectLabel : public DIEValue {
465 const std::string Label;
466 public:
467 explicit DIEObjectLabel(const std::string &L)
468 : DIEValue(isAsIsLabel), Label(L) {}
470 // Implement isa/cast/dyncast.
471 static bool classof(const DIEObjectLabel *) { return true; }
472 static bool classof(const DIEValue *L) { return L->Type == isAsIsLabel; }
474 /// EmitValue - Emit label value.
476 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
478 /// SizeOf - Determine size of label value in bytes.
480 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
482 /// Profile - Used to gather unique data for the value folding set.
484 static void Profile(FoldingSetNodeID &ID, const std::string &Label) {
485 ID.AddInteger(isAsIsLabel);
486 ID.AddString(Label);
488 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label.c_str()); }
490 #ifndef NDEBUG
491 virtual void print(std::ostream &O) {
492 O << "Obj: " << Label;
494 #endif
497 //===----------------------------------------------------------------------===//
498 /// DIESectionOffset - A section offset DIE.
500 class DIESectionOffset : public DIEValue {
501 const DWLabel Label;
502 const DWLabel Section;
503 bool IsEH : 1;
504 bool UseSet : 1;
505 public:
506 DIESectionOffset(const DWLabel &Lab, const DWLabel &Sec,
507 bool isEH = false, bool useSet = true)
508 : DIEValue(isSectionOffset), Label(Lab), Section(Sec),
509 IsEH(isEH), UseSet(useSet) {}
511 // Implement isa/cast/dyncast.
512 static bool classof(const DIESectionOffset *) { return true; }
513 static bool classof(const DIEValue *D) { return D->Type == isSectionOffset; }
515 /// EmitValue - Emit section offset.
517 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
519 /// SizeOf - Determine size of section offset value in bytes.
521 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
523 /// Profile - Used to gather unique data for the value folding set.
525 static void Profile(FoldingSetNodeID &ID, const DWLabel &Label,
526 const DWLabel &Section) {
527 ID.AddInteger(isSectionOffset);
528 Label.Profile(ID);
529 Section.Profile(ID);
530 // IsEH and UseSet are specific to the Label/Section that we will emit
531 // the offset for; so Label/Section are enough for uniqueness.
533 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label, Section); }
535 #ifndef NDEBUG
536 virtual void print(std::ostream &O) {
537 O << "Off: ";
538 Label.print(O);
539 O << "-";
540 Section.print(O);
541 O << "-" << IsEH << "-" << UseSet;
543 #endif
546 //===----------------------------------------------------------------------===//
547 /// DIEDelta - A simple label difference DIE.
549 class DIEDelta : public DIEValue {
550 const DWLabel LabelHi;
551 const DWLabel LabelLo;
552 public:
553 DIEDelta(const DWLabel &Hi, const DWLabel &Lo)
554 : DIEValue(isDelta), LabelHi(Hi), LabelLo(Lo) {}
556 // Implement isa/cast/dyncast.
557 static bool classof(const DIEDelta *) { return true; }
558 static bool classof(const DIEValue *D) { return D->Type == isDelta; }
560 /// EmitValue - Emit delta value.
562 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
564 /// SizeOf - Determine size of delta value in bytes.
566 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
568 /// Profile - Used to gather unique data for the value folding set.
570 static void Profile(FoldingSetNodeID &ID, const DWLabel &LabelHi,
571 const DWLabel &LabelLo) {
572 ID.AddInteger(isDelta);
573 LabelHi.Profile(ID);
574 LabelLo.Profile(ID);
576 virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, LabelHi, LabelLo); }
578 #ifndef NDEBUG
579 virtual void print(std::ostream &O) {
580 O << "Del: ";
581 LabelHi.print(O);
582 O << "-";
583 LabelLo.print(O);
585 #endif
588 //===----------------------------------------------------------------------===//
589 /// DIEntry - A pointer to another debug information entry. An instance of this
590 /// class can also be used as a proxy for a debug information entry not yet
591 /// defined (ie. types.)
592 class DIEntry : public DIEValue {
593 DIE *Entry;
594 public:
595 explicit DIEntry(DIE *E) : DIEValue(isEntry), Entry(E) {}
597 void setEntry(DIE *E) { Entry = E; }
599 // Implement isa/cast/dyncast.
600 static bool classof(const DIEntry *) { return true; }
601 static bool classof(const DIEValue *E) { return E->Type == isEntry; }
603 /// EmitValue - Emit debug information entry offset.
605 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
607 /// SizeOf - Determine size of debug information entry in bytes.
609 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
610 return sizeof(int32_t);
613 /// Profile - Used to gather unique data for the value folding set.
615 static void Profile(FoldingSetNodeID &ID, DIE *Entry) {
616 ID.AddInteger(isEntry);
617 ID.AddPointer(Entry);
619 virtual void Profile(FoldingSetNodeID &ID) {
620 ID.AddInteger(isEntry);
622 if (Entry) {
623 ID.AddPointer(Entry);
624 } else {
625 ID.AddPointer(this);
629 #ifndef NDEBUG
630 virtual void print(std::ostream &O) {
631 O << "Die: 0x" << std::hex << (intptr_t)Entry << std::dec;
633 #endif
636 //===----------------------------------------------------------------------===//
637 /// DIEBlock - A block of values. Primarily used for location expressions.
639 class DIEBlock : public DIEValue, public DIE {
640 unsigned Size; // Size in bytes excluding size header.
641 public:
642 DIEBlock()
643 : DIEValue(isBlock), DIE(0), Size(0) {}
644 virtual ~DIEBlock() {}
646 // Implement isa/cast/dyncast.
647 static bool classof(const DIEBlock *) { return true; }
648 static bool classof(const DIEValue *E) { return E->Type == isBlock; }
650 /// ComputeSize - calculate the size of the block.
652 unsigned ComputeSize(DwarfDebug &DD);
654 /// BestForm - Choose the best form for data.
656 unsigned BestForm() const {
657 if ((unsigned char)Size == Size) return DW_FORM_block1;
658 if ((unsigned short)Size == Size) return DW_FORM_block2;
659 if ((unsigned int)Size == Size) return DW_FORM_block4;
660 return DW_FORM_block;
663 /// EmitValue - Emit block data.
665 virtual void EmitValue(DwarfDebug &DD, unsigned Form);
667 /// SizeOf - Determine size of block data in bytes.
669 virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
671 /// Profile - Used to gather unique data for the value folding set.
673 virtual void Profile(FoldingSetNodeID &ID) {
674 ID.AddInteger(isBlock);
675 DIE::Profile(ID);
678 #ifndef NDEBUG
679 virtual void print(std::ostream &O) {
680 O << "Blk: ";
681 DIE::print(O, 5);
683 #endif
686 //===----------------------------------------------------------------------===//
687 /// CompileUnit - This dwarf writer support class manages information associate
688 /// with a source file.
689 class CompileUnit {
690 /// ID - File identifier for source.
692 unsigned ID;
694 /// Die - Compile unit debug information entry.
696 DIE *Die;
698 /// GVToDieMap - Tracks the mapping of unit level debug informaton
699 /// variables to debug information entries.
700 std::map<GlobalVariable *, DIE *> GVToDieMap;
702 /// GVToDIEntryMap - Tracks the mapping of unit level debug informaton
703 /// descriptors to debug information entries using a DIEntry proxy.
704 std::map<GlobalVariable *, DIEntry *> GVToDIEntryMap;
706 /// Globals - A map of globally visible named entities for this unit.
708 StringMap<DIE*> Globals;
710 /// DiesSet - Used to uniquely define dies within the compile unit.
712 FoldingSet<DIE> DiesSet;
713 public:
714 CompileUnit(unsigned I, DIE *D)
715 : ID(I), Die(D), GVToDieMap(),
716 GVToDIEntryMap(), Globals(), DiesSet(InitDiesSetSize)
719 ~CompileUnit() {
720 delete Die;
723 // Accessors.
724 unsigned getID() const { return ID; }
725 DIE* getDie() const { return Die; }
726 StringMap<DIE*> &getGlobals() { return Globals; }
728 /// hasContent - Return true if this compile unit has something to write out.
730 bool hasContent() const {
731 return !Die->getChildren().empty();
734 /// AddGlobal - Add a new global entity to the compile unit.
736 void AddGlobal(const std::string &Name, DIE *Die) {
737 Globals[Name] = Die;
740 /// getDieMapSlotFor - Returns the debug information entry map slot for the
741 /// specified debug variable.
742 DIE *&getDieMapSlotFor(GlobalVariable *GV) {
743 return GVToDieMap[GV];
746 /// getDIEntrySlotFor - Returns the debug information entry proxy slot for the
747 /// specified debug variable.
748 DIEntry *&getDIEntrySlotFor(GlobalVariable *GV) {
749 return GVToDIEntryMap[GV];
752 /// AddDie - Adds or interns the DIE to the compile unit.
754 DIE *AddDie(DIE &Buffer) {
755 FoldingSetNodeID ID;
756 Buffer.Profile(ID);
757 void *Where;
758 DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
760 if (!Die) {
761 Die = new DIE(Buffer);
762 DiesSet.InsertNode(Die, Where);
763 this->Die->AddChild(Die);
764 Buffer.Detach();
767 return Die;
771 //===----------------------------------------------------------------------===//
772 /// Dwarf - Emits general Dwarf directives.
774 class Dwarf {
775 protected:
776 //===--------------------------------------------------------------------===//
777 // Core attributes used by the Dwarf writer.
781 /// O - Stream to .s file.
783 raw_ostream &O;
785 /// Asm - Target of Dwarf emission.
787 AsmPrinter *Asm;
789 /// TAI - Target asm information.
790 const TargetAsmInfo *TAI;
792 /// TD - Target data.
793 const TargetData *TD;
795 /// RI - Register Information.
796 const TargetRegisterInfo *RI;
798 /// M - Current module.
800 Module *M;
802 /// MF - Current machine function.
804 MachineFunction *MF;
806 /// MMI - Collected machine module information.
808 MachineModuleInfo *MMI;
810 /// SubprogramCount - The running count of functions being compiled.
812 unsigned SubprogramCount;
814 /// Flavor - A unique string indicating what dwarf producer this is, used to
815 /// unique labels.
816 const char * const Flavor;
818 unsigned SetCounter;
819 Dwarf(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T,
820 const char *flavor)
821 : O(OS)
822 , Asm(A)
823 , TAI(T)
824 , TD(Asm->TM.getTargetData())
825 , RI(Asm->TM.getRegisterInfo())
826 , M(NULL)
827 , MF(NULL)
828 , MMI(NULL)
829 , SubprogramCount(0)
830 , Flavor(flavor)
831 , SetCounter(1)
835 public:
836 //===--------------------------------------------------------------------===//
837 // Accessors.
839 const AsmPrinter *getAsm() const { return Asm; }
840 MachineModuleInfo *getMMI() const { return MMI; }
841 const TargetAsmInfo *getTargetAsmInfo() const { return TAI; }
842 const TargetData *getTargetData() const { return TD; }
844 void PrintRelDirective(bool Force32Bit = false, bool isInSection = false)
845 const {
846 if (isInSection && TAI->getDwarfSectionOffsetDirective())
847 O << TAI->getDwarfSectionOffsetDirective();
848 else if (Force32Bit || TD->getPointerSize() == sizeof(int32_t))
849 O << TAI->getData32bitsDirective();
850 else
851 O << TAI->getData64bitsDirective();
854 /// PrintLabelName - Print label name in form used by Dwarf writer.
856 void PrintLabelName(DWLabel Label) const {
857 PrintLabelName(Label.Tag, Label.Number);
859 void PrintLabelName(const char *Tag, unsigned Number) const {
860 O << TAI->getPrivateGlobalPrefix() << Tag;
861 if (Number) O << Number;
864 void PrintLabelName(const char *Tag, unsigned Number,
865 const char *Suffix) const {
866 O << TAI->getPrivateGlobalPrefix() << Tag;
867 if (Number) O << Number;
868 O << Suffix;
871 /// EmitLabel - Emit location label for internal use by Dwarf.
873 void EmitLabel(DWLabel Label) const {
874 EmitLabel(Label.Tag, Label.Number);
876 void EmitLabel(const char *Tag, unsigned Number) const {
877 PrintLabelName(Tag, Number);
878 O << ":\n";
881 /// EmitReference - Emit a reference to a label.
883 void EmitReference(DWLabel Label, bool IsPCRelative = false,
884 bool Force32Bit = false) const {
885 EmitReference(Label.Tag, Label.Number, IsPCRelative, Force32Bit);
887 void EmitReference(const char *Tag, unsigned Number,
888 bool IsPCRelative = false, bool Force32Bit = false) const {
889 PrintRelDirective(Force32Bit);
890 PrintLabelName(Tag, Number);
892 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
894 void EmitReference(const std::string &Name, bool IsPCRelative = false,
895 bool Force32Bit = false) const {
896 PrintRelDirective(Force32Bit);
898 O << Name;
900 if (IsPCRelative) O << "-" << TAI->getPCSymbol();
903 /// EmitDifference - Emit the difference between two labels. Some
904 /// assemblers do not behave with absolute expressions with data directives,
905 /// so there is an option (needsSet) to use an intermediary set expression.
906 void EmitDifference(DWLabel LabelHi, DWLabel LabelLo,
907 bool IsSmall = false) {
908 EmitDifference(LabelHi.Tag, LabelHi.Number,
909 LabelLo.Tag, LabelLo.Number,
910 IsSmall);
912 void EmitDifference(const char *TagHi, unsigned NumberHi,
913 const char *TagLo, unsigned NumberLo,
914 bool IsSmall = false) {
915 if (TAI->needsSet()) {
916 O << "\t.set\t";
917 PrintLabelName("set", SetCounter, Flavor);
918 O << ",";
919 PrintLabelName(TagHi, NumberHi);
920 O << "-";
921 PrintLabelName(TagLo, NumberLo);
922 O << "\n";
924 PrintRelDirective(IsSmall);
925 PrintLabelName("set", SetCounter, Flavor);
926 ++SetCounter;
927 } else {
928 PrintRelDirective(IsSmall);
930 PrintLabelName(TagHi, NumberHi);
931 O << "-";
932 PrintLabelName(TagLo, NumberLo);
936 void EmitSectionOffset(const char* Label, const char* Section,
937 unsigned LabelNumber, unsigned SectionNumber,
938 bool IsSmall = false, bool isEH = false,
939 bool useSet = true) {
940 bool printAbsolute = false;
941 if (isEH)
942 printAbsolute = TAI->isAbsoluteEHSectionOffsets();
943 else
944 printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
946 if (TAI->needsSet() && useSet) {
947 O << "\t.set\t";
948 PrintLabelName("set", SetCounter, Flavor);
949 O << ",";
950 PrintLabelName(Label, LabelNumber);
952 if (!printAbsolute) {
953 O << "-";
954 PrintLabelName(Section, SectionNumber);
956 O << "\n";
958 PrintRelDirective(IsSmall);
960 PrintLabelName("set", SetCounter, Flavor);
961 ++SetCounter;
962 } else {
963 PrintRelDirective(IsSmall, true);
965 PrintLabelName(Label, LabelNumber);
967 if (!printAbsolute) {
968 O << "-";
969 PrintLabelName(Section, SectionNumber);
974 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
975 /// frame.
976 void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
977 const std::vector<MachineMove> &Moves, bool isEH) {
978 int stackGrowth =
979 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
980 TargetFrameInfo::StackGrowsUp ?
981 TD->getPointerSize() : -TD->getPointerSize();
982 bool IsLocal = BaseLabel && strcmp(BaseLabel, "label") == 0;
984 for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
985 const MachineMove &Move = Moves[i];
986 unsigned LabelID = Move.getLabelID();
988 if (LabelID) {
989 LabelID = MMI->MappedLabel(LabelID);
991 // Throw out move if the label is invalid.
992 if (!LabelID) continue;
995 const MachineLocation &Dst = Move.getDestination();
996 const MachineLocation &Src = Move.getSource();
998 // Advance row if new location.
999 if (BaseLabel && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
1000 Asm->EmitInt8(DW_CFA_advance_loc4);
1001 Asm->EOL("DW_CFA_advance_loc4");
1002 EmitDifference("label", LabelID, BaseLabel, BaseLabelID, true);
1003 Asm->EOL();
1005 BaseLabelID = LabelID;
1006 BaseLabel = "label";
1007 IsLocal = true;
1010 // If advancing cfa.
1011 if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
1012 if (!Src.isReg()) {
1013 if (Src.getReg() == MachineLocation::VirtualFP) {
1014 Asm->EmitInt8(DW_CFA_def_cfa_offset);
1015 Asm->EOL("DW_CFA_def_cfa_offset");
1016 } else {
1017 Asm->EmitInt8(DW_CFA_def_cfa);
1018 Asm->EOL("DW_CFA_def_cfa");
1019 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getReg(), isEH));
1020 Asm->EOL("Register");
1023 int Offset = -Src.getOffset();
1025 Asm->EmitULEB128Bytes(Offset);
1026 Asm->EOL("Offset");
1027 } else {
1028 assert(0 && "Machine move no supported yet.");
1030 } else if (Src.isReg() &&
1031 Src.getReg() == MachineLocation::VirtualFP) {
1032 if (Dst.isReg()) {
1033 Asm->EmitInt8(DW_CFA_def_cfa_register);
1034 Asm->EOL("DW_CFA_def_cfa_register");
1035 Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getReg(), isEH));
1036 Asm->EOL("Register");
1037 } else {
1038 assert(0 && "Machine move no supported yet.");
1040 } else {
1041 unsigned Reg = RI->getDwarfRegNum(Src.getReg(), isEH);
1042 int Offset = Dst.getOffset() / stackGrowth;
1044 if (Offset < 0) {
1045 Asm->EmitInt8(DW_CFA_offset_extended_sf);
1046 Asm->EOL("DW_CFA_offset_extended_sf");
1047 Asm->EmitULEB128Bytes(Reg);
1048 Asm->EOL("Reg");
1049 Asm->EmitSLEB128Bytes(Offset);
1050 Asm->EOL("Offset");
1051 } else if (Reg < 64) {
1052 Asm->EmitInt8(DW_CFA_offset + Reg);
1053 if (Asm->isVerbose())
1054 Asm->EOL("DW_CFA_offset + Reg (" + utostr(Reg) + ")");
1055 else
1056 Asm->EOL();
1057 Asm->EmitULEB128Bytes(Offset);
1058 Asm->EOL("Offset");
1059 } else {
1060 Asm->EmitInt8(DW_CFA_offset_extended);
1061 Asm->EOL("DW_CFA_offset_extended");
1062 Asm->EmitULEB128Bytes(Reg);
1063 Asm->EOL("Reg");
1064 Asm->EmitULEB128Bytes(Offset);
1065 Asm->EOL("Offset");
1073 //===----------------------------------------------------------------------===//
1074 /// SrcLineInfo - This class is used to record source line correspondence.
1076 class SrcLineInfo {
1077 unsigned Line; // Source line number.
1078 unsigned Column; // Source column.
1079 unsigned SourceID; // Source ID number.
1080 unsigned LabelID; // Label in code ID number.
1081 public:
1082 SrcLineInfo(unsigned L, unsigned C, unsigned S, unsigned I)
1083 : Line(L), Column(C), SourceID(S), LabelID(I) {}
1085 // Accessors
1086 unsigned getLine() const { return Line; }
1087 unsigned getColumn() const { return Column; }
1088 unsigned getSourceID() const { return SourceID; }
1089 unsigned getLabelID() const { return LabelID; }
1092 //===----------------------------------------------------------------------===//
1093 /// DbgVariable - This class is used to track local variable information.
1095 class DbgVariable {
1096 DIVariable Var; // Variable Descriptor.
1097 unsigned FrameIndex; // Variable frame index.
1098 public:
1099 DbgVariable(DIVariable V, unsigned I) : Var(V), FrameIndex(I) {}
1101 // Accessors.
1102 DIVariable getVariable() const { return Var; }
1103 unsigned getFrameIndex() const { return FrameIndex; }
1106 //===----------------------------------------------------------------------===//
1107 /// DbgScope - This class is used to track scope information.
1109 class DbgScope {
1110 DbgScope *Parent; // Parent to this scope.
1111 DIDescriptor Desc; // Debug info descriptor for scope.
1112 // Either subprogram or block.
1113 unsigned StartLabelID; // Label ID of the beginning of scope.
1114 unsigned EndLabelID; // Label ID of the end of scope.
1115 SmallVector<DbgScope *, 4> Scopes; // Scopes defined in scope.
1116 SmallVector<DbgVariable *, 8> Variables;// Variables declared in scope.
1117 public:
1118 DbgScope(DbgScope *P, DIDescriptor D)
1119 : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0), Scopes(), Variables()
1121 virtual ~DbgScope() {
1122 for (unsigned i = 0, N = Scopes.size(); i < N; ++i) delete Scopes[i];
1123 for (unsigned j = 0, M = Variables.size(); j < M; ++j) delete Variables[j];
1126 // Accessors.
1127 DbgScope *getParent() const { return Parent; }
1128 DIDescriptor getDesc() const { return Desc; }
1129 unsigned getStartLabelID() const { return StartLabelID; }
1130 unsigned getEndLabelID() const { return EndLabelID; }
1131 SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
1132 SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
1133 void setStartLabelID(unsigned S) { StartLabelID = S; }
1134 void setEndLabelID(unsigned E) { EndLabelID = E; }
1136 /// AddScope - Add a scope to the scope.
1138 void AddScope(DbgScope *S) { Scopes.push_back(S); }
1140 /// AddVariable - Add a variable to the scope.
1142 void AddVariable(DbgVariable *V) { Variables.push_back(V); }
1144 virtual bool isInlinedSubroutine() { return false; }
1145 virtual unsigned getLine() { assert ( 0 && "Unexpected scope!"); return 0; }
1146 virtual unsigned getColumn() { assert ( 0 && "Unexpected scope!"); return 0; }
1147 virtual unsigned getFile() { assert ( 0 && "Unexpected scope!"); return 0; }
1151 //===----------------------------------------------------------------------===//
1152 /// DbgInlinedSubroutineScope - This class is used to track inlined subroutine
1153 /// scope information.
1155 class DbgInlinedSubroutineScope : public DbgScope {
1156 unsigned Src;
1157 unsigned Line;
1158 unsigned Col;
1159 public:
1160 DbgInlinedSubroutineScope(DbgScope *P, DIDescriptor D,
1161 unsigned S, unsigned L, unsigned C)
1162 : DbgScope(P, D), Src(S), Line(L), Col(C)
1165 unsigned getLine() { return Line; }
1166 unsigned getColumn() { return Col; }
1167 unsigned getFile() { return Src; }
1168 bool isInlinedSubroutine() { return true; }
1171 //===----------------------------------------------------------------------===//
1172 /// DwarfDebug - Emits Dwarf debug directives.
1174 class DwarfDebug : public Dwarf {
1175 //===--------------------------------------------------------------------===//
1176 // Attributes used to construct specific Dwarf sections.
1179 /// CompileUnitMap - A map of global variables representing compile units to
1180 /// compile units.
1181 DenseMap<Value *, CompileUnit *> CompileUnitMap;
1183 /// CompileUnits - All the compile units in this module.
1185 SmallVector<CompileUnit *, 8> CompileUnits;
1187 /// MainCU - Some platform prefers one compile unit per .o file. In such
1188 /// cases, all dies are inserted in MainCU.
1189 CompileUnit *MainCU;
1191 /// AbbreviationsSet - Used to uniquely define abbreviations.
1193 FoldingSet<DIEAbbrev> AbbreviationsSet;
1195 /// Abbreviations - A list of all the unique abbreviations in use.
1197 std::vector<DIEAbbrev *> Abbreviations;
1199 /// DirectoryIdMap - Directory name to directory id map.
1201 StringMap<unsigned> DirectoryIdMap;
1203 /// DirectoryNames - A list of directory names.
1204 SmallVector<std::string, 8> DirectoryNames;
1206 /// SourceFileIdMap - Source file name to source file id map.
1208 StringMap<unsigned> SourceFileIdMap;
1210 /// SourceFileNames - A list of source file names.
1211 SmallVector<std::string, 8> SourceFileNames;
1213 /// SourceIdMap - Source id map, i.e. pair of directory id and source file
1214 /// id mapped to a unique id.
1215 DenseMap<std::pair<unsigned, unsigned>, unsigned> SourceIdMap;
1217 /// SourceIds - Reverse map from source id to directory id + file id pair.
1219 SmallVector<std::pair<unsigned, unsigned>, 8> SourceIds;
1221 /// Lines - List of of source line correspondence.
1222 std::vector<SrcLineInfo> Lines;
1224 /// ValuesSet - Used to uniquely define values.
1226 FoldingSet<DIEValue> ValuesSet;
1228 /// Values - A list of all the unique values in use.
1230 std::vector<DIEValue *> Values;
1232 /// StringPool - A UniqueVector of strings used by indirect references.
1234 UniqueVector<std::string> StringPool;
1236 /// SectionMap - Provides a unique id per text section.
1238 UniqueVector<const Section*> SectionMap;
1240 /// SectionSourceLines - Tracks line numbers per text section.
1242 std::vector<std::vector<SrcLineInfo> > SectionSourceLines;
1244 /// didInitial - Flag to indicate if initial emission has been done.
1246 bool didInitial;
1248 /// shouldEmit - Flag to indicate if debug information should be emitted.
1250 bool shouldEmit;
1252 // FunctionDbgScope - Top level scope for the current function.
1254 DbgScope *FunctionDbgScope;
1256 /// DbgScopeMap - Tracks the scopes in the current function.
1257 DenseMap<GlobalVariable *, DbgScope *> DbgScopeMap;
1259 /// DbgInlinedScopeMap - Tracks inlined scopes in the current function.
1260 DenseMap<GlobalVariable *, SmallVector<DbgScope *, 2> > DbgInlinedScopeMap;
1262 /// InlineInfo - Keep track of inlined functions and their location.
1263 /// This information is used to populate debug_inlined section.
1264 DenseMap<GlobalVariable *, SmallVector<unsigned, 4> > InlineInfo;
1266 /// InlinedVariableScopes - Scopes information for the inlined subroutine
1267 /// variables.
1268 DenseMap<const MachineInstr *, DbgScope *> InlinedVariableScopes;
1270 /// DebugTimer - Timer for the Dwarf debug writer.
1271 Timer *DebugTimer;
1273 struct FunctionDebugFrameInfo {
1274 unsigned Number;
1275 std::vector<MachineMove> Moves;
1277 FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
1278 Number(Num), Moves(M) { }
1281 std::vector<FunctionDebugFrameInfo> DebugFrames;
1283 private:
1284 /// getSourceDirectoryAndFileIds - Return the directory and file ids that
1285 /// maps to the source id. Source id starts at 1.
1286 std::pair<unsigned, unsigned>
1287 getSourceDirectoryAndFileIds(unsigned SId) const {
1288 return SourceIds[SId-1];
1291 /// getNumSourceDirectories - Return the number of source directories in the
1292 /// debug info.
1293 unsigned getNumSourceDirectories() const {
1294 return DirectoryNames.size();
1297 /// getSourceDirectoryName - Return the name of the directory corresponding
1298 /// to the id.
1299 const std::string &getSourceDirectoryName(unsigned Id) const {
1300 return DirectoryNames[Id - 1];
1303 /// getSourceFileName - Return the name of the source file corresponding
1304 /// to the id.
1305 const std::string &getSourceFileName(unsigned Id) const {
1306 return SourceFileNames[Id - 1];
1309 /// getNumSourceIds - Return the number of unique source ids.
1310 unsigned getNumSourceIds() const {
1311 return SourceIds.size();
1314 /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1316 void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1317 // Profile the node so that we can make it unique.
1318 FoldingSetNodeID ID;
1319 Abbrev.Profile(ID);
1321 // Check the set for priors.
1322 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1324 // If it's newly added.
1325 if (InSet == &Abbrev) {
1326 // Add to abbreviation list.
1327 Abbreviations.push_back(&Abbrev);
1328 // Assign the vector position + 1 as its number.
1329 Abbrev.setNumber(Abbreviations.size());
1330 } else {
1331 // Assign existing abbreviation number.
1332 Abbrev.setNumber(InSet->getNumber());
1336 /// NewString - Add a string to the constant pool and returns a label.
1338 DWLabel NewString(const std::string &String) {
1339 unsigned StringID = StringPool.insert(String);
1340 return DWLabel("string", StringID);
1343 /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1344 /// entry.
1345 DIEntry *NewDIEntry(DIE *Entry = NULL) {
1346 DIEntry *Value;
1348 if (Entry) {
1349 FoldingSetNodeID ID;
1350 DIEntry::Profile(ID, Entry);
1351 void *Where;
1352 Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1354 if (Value) return Value;
1356 Value = new DIEntry(Entry);
1357 ValuesSet.InsertNode(Value, Where);
1358 } else {
1359 Value = new DIEntry(Entry);
1362 Values.push_back(Value);
1363 return Value;
1366 /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1368 void SetDIEntry(DIEntry *Value, DIE *Entry) {
1369 Value->setEntry(Entry);
1370 // Add to values set if not already there. If it is, we merely have a
1371 // duplicate in the values list (no harm.)
1372 ValuesSet.GetOrInsertNode(Value);
1375 /// AddUInt - Add an unsigned integer attribute data and value.
1377 void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1378 if (!Form) Form = DIEInteger::BestForm(false, Integer);
1380 FoldingSetNodeID ID;
1381 DIEInteger::Profile(ID, Integer);
1382 void *Where;
1383 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1384 if (!Value) {
1385 Value = new DIEInteger(Integer);
1386 ValuesSet.InsertNode(Value, Where);
1387 Values.push_back(Value);
1390 Die->AddValue(Attribute, Form, Value);
1393 /// AddSInt - Add an signed integer attribute data and value.
1395 void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1396 if (!Form) Form = DIEInteger::BestForm(true, Integer);
1398 FoldingSetNodeID ID;
1399 DIEInteger::Profile(ID, (uint64_t)Integer);
1400 void *Where;
1401 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1402 if (!Value) {
1403 Value = new DIEInteger(Integer);
1404 ValuesSet.InsertNode(Value, Where);
1405 Values.push_back(Value);
1408 Die->AddValue(Attribute, Form, Value);
1411 /// AddString - Add a string attribute data and value.
1413 void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1414 const std::string &String) {
1415 FoldingSetNodeID ID;
1416 DIEString::Profile(ID, String);
1417 void *Where;
1418 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1419 if (!Value) {
1420 Value = new DIEString(String);
1421 ValuesSet.InsertNode(Value, Where);
1422 Values.push_back(Value);
1425 Die->AddValue(Attribute, Form, Value);
1428 /// AddLabel - Add a Dwarf label attribute data and value.
1430 void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1431 const DWLabel &Label) {
1432 FoldingSetNodeID ID;
1433 DIEDwarfLabel::Profile(ID, Label);
1434 void *Where;
1435 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1436 if (!Value) {
1437 Value = new DIEDwarfLabel(Label);
1438 ValuesSet.InsertNode(Value, Where);
1439 Values.push_back(Value);
1442 Die->AddValue(Attribute, Form, Value);
1445 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1447 void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1448 const std::string &Label) {
1449 FoldingSetNodeID ID;
1450 DIEObjectLabel::Profile(ID, Label);
1451 void *Where;
1452 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1453 if (!Value) {
1454 Value = new DIEObjectLabel(Label);
1455 ValuesSet.InsertNode(Value, Where);
1456 Values.push_back(Value);
1459 Die->AddValue(Attribute, Form, Value);
1462 /// AddSectionOffset - Add a section offset label attribute data and value.
1464 void AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
1465 const DWLabel &Label, const DWLabel &Section,
1466 bool isEH = false, bool useSet = true) {
1467 FoldingSetNodeID ID;
1468 DIESectionOffset::Profile(ID, Label, Section);
1469 void *Where;
1470 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1471 if (!Value) {
1472 Value = new DIESectionOffset(Label, Section, isEH, useSet);
1473 ValuesSet.InsertNode(Value, Where);
1474 Values.push_back(Value);
1477 Die->AddValue(Attribute, Form, Value);
1480 /// AddDelta - Add a label delta attribute data and value.
1482 void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1483 const DWLabel &Hi, const DWLabel &Lo) {
1484 FoldingSetNodeID ID;
1485 DIEDelta::Profile(ID, Hi, Lo);
1486 void *Where;
1487 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1488 if (!Value) {
1489 Value = new DIEDelta(Hi, Lo);
1490 ValuesSet.InsertNode(Value, Where);
1491 Values.push_back(Value);
1494 Die->AddValue(Attribute, Form, Value);
1497 /// AddDIEntry - Add a DIE attribute data and value.
1499 void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1500 Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1503 /// AddBlock - Add block data.
1505 void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1506 Block->ComputeSize(*this);
1507 FoldingSetNodeID ID;
1508 Block->Profile(ID);
1509 void *Where;
1510 DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1511 if (!Value) {
1512 Value = Block;
1513 ValuesSet.InsertNode(Value, Where);
1514 Values.push_back(Value);
1515 } else {
1516 // Already exists, reuse the previous one.
1517 delete Block;
1518 Block = cast<DIEBlock>(Value);
1521 Die->AddValue(Attribute, Block->BestForm(), Value);
1524 /// AddSourceLine - Add location information to specified debug information
1525 /// entry.
1526 void AddSourceLine(DIE *Die, const DIVariable *V) {
1527 unsigned FileID = 0;
1528 unsigned Line = V->getLineNumber();
1529 CompileUnit *Unit = FindCompileUnit(V->getCompileUnit());
1530 FileID = Unit->getID();
1531 assert (FileID && "Invalid file id");
1532 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1533 AddUInt(Die, DW_AT_decl_line, 0, Line);
1536 /// AddSourceLine - Add location information to specified debug information
1537 /// entry.
1538 void AddSourceLine(DIE *Die, const DIGlobal *G) {
1539 unsigned FileID = 0;
1540 unsigned Line = G->getLineNumber();
1541 CompileUnit *Unit = FindCompileUnit(G->getCompileUnit());
1542 FileID = Unit->getID();
1543 assert (FileID && "Invalid file id");
1544 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1545 AddUInt(Die, DW_AT_decl_line, 0, Line);
1548 void AddSourceLine(DIE *Die, const DIType *Ty) {
1549 unsigned FileID = 0;
1550 unsigned Line = Ty->getLineNumber();
1551 DICompileUnit CU = Ty->getCompileUnit();
1552 if (CU.isNull())
1553 return;
1554 CompileUnit *Unit = FindCompileUnit(CU);
1555 FileID = Unit->getID();
1556 assert (FileID && "Invalid file id");
1557 AddUInt(Die, DW_AT_decl_file, 0, FileID);
1558 AddUInt(Die, DW_AT_decl_line, 0, Line);
1561 /// AddAddress - Add an address attribute to a die based on the location
1562 /// provided.
1563 void AddAddress(DIE *Die, unsigned Attribute,
1564 const MachineLocation &Location) {
1565 unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
1566 DIEBlock *Block = new DIEBlock();
1568 if (Location.isReg()) {
1569 if (Reg < 32) {
1570 AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1571 } else {
1572 AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1573 AddUInt(Block, 0, DW_FORM_udata, Reg);
1575 } else {
1576 if (Reg < 32) {
1577 AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1578 } else {
1579 AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1580 AddUInt(Block, 0, DW_FORM_udata, Reg);
1582 AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1585 AddBlock(Die, Attribute, 0, Block);
1588 /// AddType - Add a new type attribute to the specified entity.
1589 void AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
1590 if (Ty.isNull())
1591 return;
1593 // Check for pre-existence.
1594 DIEntry *&Slot = DW_Unit->getDIEntrySlotFor(Ty.getGV());
1595 // If it exists then use the existing value.
1596 if (Slot) {
1597 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1598 return;
1601 // Set up proxy.
1602 Slot = NewDIEntry();
1604 // Construct type.
1605 DIE Buffer(DW_TAG_base_type);
1606 if (Ty.isBasicType(Ty.getTag()))
1607 ConstructTypeDIE(DW_Unit, Buffer, DIBasicType(Ty.getGV()));
1608 else if (Ty.isDerivedType(Ty.getTag()))
1609 ConstructTypeDIE(DW_Unit, Buffer, DIDerivedType(Ty.getGV()));
1610 else {
1611 assert(Ty.isCompositeType(Ty.getTag()) && "Unknown kind of DIType");
1612 ConstructTypeDIE(DW_Unit, Buffer, DICompositeType(Ty.getGV()));
1615 // Add debug information entry to entity and appropriate context.
1616 DIE *Die = NULL;
1617 DIDescriptor Context = Ty.getContext();
1618 if (!Context.isNull())
1619 Die = DW_Unit->getDieMapSlotFor(Context.getGV());
1621 if (Die) {
1622 DIE *Child = new DIE(Buffer);
1623 Die->AddChild(Child);
1624 Buffer.Detach();
1625 SetDIEntry(Slot, Child);
1626 } else {
1627 Die = DW_Unit->AddDie(Buffer);
1628 SetDIEntry(Slot, Die);
1631 Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1634 /// ConstructTypeDIE - Construct basic type die from DIBasicType.
1635 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1636 DIBasicType BTy) {
1638 // Get core information.
1639 std::string Name;
1640 BTy.getName(Name);
1641 Buffer.setTag(DW_TAG_base_type);
1642 AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, BTy.getEncoding());
1643 // Add name if not anonymous or intermediate type.
1644 if (!Name.empty())
1645 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1646 uint64_t Size = BTy.getSizeInBits() >> 3;
1647 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1650 /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
1651 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1652 DIDerivedType DTy) {
1654 // Get core information.
1655 std::string Name;
1656 DTy.getName(Name);
1657 uint64_t Size = DTy.getSizeInBits() >> 3;
1658 unsigned Tag = DTy.getTag();
1660 // FIXME - Workaround for templates.
1661 if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1663 Buffer.setTag(Tag);
1665 // Map to main type, void will not have a type.
1666 DIType FromTy = DTy.getTypeDerivedFrom();
1667 AddType(DW_Unit, &Buffer, FromTy);
1669 // Add name if not anonymous or intermediate type.
1670 if (!Name.empty())
1671 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1673 // Add size if non-zero (derived types might be zero-sized.)
1674 if (Size)
1675 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1677 // Add source line info if available and TyDesc is not a forward
1678 // declaration.
1679 if (!DTy.isForwardDecl())
1680 AddSourceLine(&Buffer, &DTy);
1683 /// ConstructTypeDIE - Construct type DIE from DICompositeType.
1684 void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1685 DICompositeType CTy) {
1686 // Get core information.
1687 std::string Name;
1688 CTy.getName(Name);
1690 uint64_t Size = CTy.getSizeInBits() >> 3;
1691 unsigned Tag = CTy.getTag();
1692 Buffer.setTag(Tag);
1694 switch (Tag) {
1695 case DW_TAG_vector_type:
1696 case DW_TAG_array_type:
1697 ConstructArrayTypeDIE(DW_Unit, Buffer, &CTy);
1698 break;
1699 case DW_TAG_enumeration_type:
1701 DIArray Elements = CTy.getTypeArray();
1702 // Add enumerators to enumeration type.
1703 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1704 DIE *ElemDie = NULL;
1705 DIEnumerator Enum(Elements.getElement(i).getGV());
1706 ElemDie = ConstructEnumTypeDIE(DW_Unit, &Enum);
1707 Buffer.AddChild(ElemDie);
1710 break;
1711 case DW_TAG_subroutine_type:
1713 // Add prototype flag.
1714 AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1715 DIArray Elements = CTy.getTypeArray();
1716 // Add return type.
1717 DIDescriptor RTy = Elements.getElement(0);
1718 AddType(DW_Unit, &Buffer, DIType(RTy.getGV()));
1720 // Add arguments.
1721 for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1722 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1723 DIDescriptor Ty = Elements.getElement(i);
1724 AddType(DW_Unit, Arg, DIType(Ty.getGV()));
1725 Buffer.AddChild(Arg);
1728 break;
1729 case DW_TAG_structure_type:
1730 case DW_TAG_union_type:
1731 case DW_TAG_class_type:
1733 // Add elements to structure type.
1734 DIArray Elements = CTy.getTypeArray();
1736 // A forward struct declared type may not have elements available.
1737 if (Elements.isNull())
1738 break;
1740 // Add elements to structure type.
1741 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1742 DIDescriptor Element = Elements.getElement(i);
1743 DIE *ElemDie = NULL;
1744 if (Element.getTag() == dwarf::DW_TAG_subprogram)
1745 ElemDie = CreateSubprogramDIE(DW_Unit,
1746 DISubprogram(Element.getGV()));
1747 else if (Element.getTag() == dwarf::DW_TAG_variable) // ???
1748 ElemDie = CreateGlobalVariableDIE(DW_Unit,
1749 DIGlobalVariable(Element.getGV()));
1750 else
1751 ElemDie = CreateMemberDIE(DW_Unit,
1752 DIDerivedType(Element.getGV()));
1753 Buffer.AddChild(ElemDie);
1755 unsigned RLang = CTy.getRunTimeLang();
1756 if (RLang)
1757 AddUInt(&Buffer, DW_AT_APPLE_runtime_class, DW_FORM_data1, RLang);
1759 break;
1760 default:
1761 break;
1764 // Add name if not anonymous or intermediate type.
1765 if (!Name.empty())
1766 AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1768 if (Tag == DW_TAG_enumeration_type || Tag == DW_TAG_structure_type
1769 || Tag == DW_TAG_union_type) {
1770 // Add size if non-zero (derived types might be zero-sized.)
1771 if (Size)
1772 AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1773 else {
1774 // Add zero size if it is not a forward declaration.
1775 if (CTy.isForwardDecl())
1776 AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
1777 else
1778 AddUInt(&Buffer, DW_AT_byte_size, 0, 0);
1781 // Add source line info if available.
1782 if (!CTy.isForwardDecl())
1783 AddSourceLine(&Buffer, &CTy);
1787 /// ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
1788 void ConstructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) {
1789 int64_t L = SR.getLo();
1790 int64_t H = SR.getHi();
1791 DIE *DW_Subrange = new DIE(DW_TAG_subrange_type);
1792 if (L != H) {
1793 AddDIEntry(DW_Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1794 if (L)
1795 AddSInt(DW_Subrange, DW_AT_lower_bound, 0, L);
1796 AddSInt(DW_Subrange, DW_AT_upper_bound, 0, H);
1798 Buffer.AddChild(DW_Subrange);
1801 /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
1802 void ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
1803 DICompositeType *CTy) {
1804 Buffer.setTag(DW_TAG_array_type);
1805 if (CTy->getTag() == DW_TAG_vector_type)
1806 AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1808 // Emit derived type.
1809 AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
1810 DIArray Elements = CTy->getTypeArray();
1812 // Construct an anonymous type for index type.
1813 DIE IdxBuffer(DW_TAG_base_type);
1814 AddUInt(&IdxBuffer, DW_AT_byte_size, 0, sizeof(int32_t));
1815 AddUInt(&IdxBuffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
1816 DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
1818 // Add subranges to array type.
1819 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1820 DIDescriptor Element = Elements.getElement(i);
1821 if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1822 ConstructSubrangeDIE(Buffer, DISubrange(Element.getGV()), IndexTy);
1826 /// ConstructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1827 DIE *ConstructEnumTypeDIE(CompileUnit *DW_Unit, DIEnumerator *ETy) {
1829 DIE *Enumerator = new DIE(DW_TAG_enumerator);
1830 std::string Name;
1831 ETy->getName(Name);
1832 AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
1833 int64_t Value = ETy->getEnumValue();
1834 AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1835 return Enumerator;
1838 /// CreateGlobalVariableDIE - Create new DIE using GV.
1839 DIE *CreateGlobalVariableDIE(CompileUnit *DW_Unit, const DIGlobalVariable &GV)
1841 DIE *GVDie = new DIE(DW_TAG_variable);
1842 std::string Name;
1843 GV.getDisplayName(Name);
1844 AddString(GVDie, DW_AT_name, DW_FORM_string, Name);
1845 std::string LinkageName;
1846 GV.getLinkageName(LinkageName);
1847 if (!LinkageName.empty())
1848 AddString(GVDie, DW_AT_MIPS_linkage_name, DW_FORM_string, LinkageName);
1849 AddType(DW_Unit, GVDie, GV.getType());
1850 if (!GV.isLocalToUnit())
1851 AddUInt(GVDie, DW_AT_external, DW_FORM_flag, 1);
1852 AddSourceLine(GVDie, &GV);
1853 return GVDie;
1856 /// CreateMemberDIE - Create new member DIE.
1857 DIE *CreateMemberDIE(CompileUnit *DW_Unit, const DIDerivedType &DT) {
1858 DIE *MemberDie = new DIE(DT.getTag());
1859 std::string Name;
1860 DT.getName(Name);
1861 if (!Name.empty())
1862 AddString(MemberDie, DW_AT_name, DW_FORM_string, Name);
1864 AddType(DW_Unit, MemberDie, DT.getTypeDerivedFrom());
1866 AddSourceLine(MemberDie, &DT);
1868 uint64_t Size = DT.getSizeInBits();
1869 uint64_t FieldSize = DT.getOriginalTypeSize();
1871 if (Size != FieldSize) {
1872 // Handle bitfield.
1873 AddUInt(MemberDie, DW_AT_byte_size, 0, DT.getOriginalTypeSize() >> 3);
1874 AddUInt(MemberDie, DW_AT_bit_size, 0, DT.getSizeInBits());
1876 uint64_t Offset = DT.getOffsetInBits();
1877 uint64_t FieldOffset = Offset;
1878 uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1879 uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1880 FieldOffset = (HiMark - FieldSize);
1881 Offset -= FieldOffset;
1882 // Maybe we need to work from the other end.
1883 if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1884 AddUInt(MemberDie, DW_AT_bit_offset, 0, Offset);
1886 DIEBlock *Block = new DIEBlock();
1887 AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1888 AddUInt(Block, 0, DW_FORM_udata, DT.getOffsetInBits() >> 3);
1889 AddBlock(MemberDie, DW_AT_data_member_location, 0, Block);
1891 if (DT.isProtected())
1892 AddUInt(MemberDie, DW_AT_accessibility, 0, DW_ACCESS_protected);
1893 else if (DT.isPrivate())
1894 AddUInt(MemberDie, DW_AT_accessibility, 0, DW_ACCESS_private);
1896 return MemberDie;
1899 /// CreateSubprogramDIE - Create new DIE using SP.
1900 DIE *CreateSubprogramDIE(CompileUnit *DW_Unit,
1901 const DISubprogram &SP,
1902 bool IsConstructor = false) {
1903 DIE *SPDie = new DIE(DW_TAG_subprogram);
1904 std::string Name;
1905 SP.getName(Name);
1906 AddString(SPDie, DW_AT_name, DW_FORM_string, Name);
1907 std::string LinkageName;
1908 SP.getLinkageName(LinkageName);
1909 if (!LinkageName.empty())
1910 AddString(SPDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1911 LinkageName);
1912 AddSourceLine(SPDie, &SP);
1914 DICompositeType SPTy = SP.getType();
1915 DIArray Args = SPTy.getTypeArray();
1917 // Add Return Type.
1918 unsigned SPTag = SPTy.getTag();
1919 if (!IsConstructor) {
1920 if (Args.isNull() || SPTag != DW_TAG_subroutine_type)
1921 AddType(DW_Unit, SPDie, SPTy);
1922 else
1923 AddType(DW_Unit, SPDie, DIType(Args.getElement(0).getGV()));
1926 if (!SP.isDefinition()) {
1927 AddUInt(SPDie, DW_AT_declaration, DW_FORM_flag, 1);
1928 // Add arguments.
1929 // Do not add arguments for subprogram definition. They will be
1930 // handled through RecordVariable.
1931 if (SPTag == DW_TAG_subroutine_type)
1932 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1933 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1934 AddType(DW_Unit, Arg, DIType(Args.getElement(i).getGV()));
1935 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1); // ???
1936 SPDie->AddChild(Arg);
1940 unsigned Lang = SP.getCompileUnit().getLanguage();
1941 if (Lang == DW_LANG_C99 || Lang == DW_LANG_C89
1942 || Lang == DW_LANG_ObjC)
1943 AddUInt(SPDie, DW_AT_prototyped, DW_FORM_flag, 1);
1945 if (!SP.isLocalToUnit())
1946 AddUInt(SPDie, DW_AT_external, DW_FORM_flag, 1);
1948 // DW_TAG_inlined_subroutine may refer to this DIE.
1949 DIE *&Slot = DW_Unit->getDieMapSlotFor(SP.getGV());
1950 Slot = SPDie;
1951 return SPDie;
1954 /// FindCompileUnit - Get the compile unit for the given descriptor.
1956 CompileUnit *FindCompileUnit(DICompileUnit Unit) {
1957 CompileUnit *DW_Unit = CompileUnitMap[Unit.getGV()];
1958 assert(DW_Unit && "Missing compile unit.");
1959 return DW_Unit;
1962 /// NewDbgScopeVariable - Create a new scope variable.
1964 DIE *NewDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
1965 // Get the descriptor.
1966 const DIVariable &VD = DV->getVariable();
1968 // Translate tag to proper Dwarf tag. The result variable is dropped for
1969 // now.
1970 unsigned Tag;
1971 switch (VD.getTag()) {
1972 case DW_TAG_return_variable: return NULL;
1973 case DW_TAG_arg_variable: Tag = DW_TAG_formal_parameter; break;
1974 case DW_TAG_auto_variable: // fall thru
1975 default: Tag = DW_TAG_variable; break;
1978 // Define variable debug information entry.
1979 DIE *VariableDie = new DIE(Tag);
1980 std::string Name;
1981 VD.getName(Name);
1982 AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
1984 // Add source line info if available.
1985 AddSourceLine(VariableDie, &VD);
1987 // Add variable type.
1988 AddType(Unit, VariableDie, VD.getType());
1990 // Add variable address.
1991 MachineLocation Location;
1992 Location.set(RI->getFrameRegister(*MF),
1993 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
1994 AddAddress(VariableDie, DW_AT_location, Location);
1996 return VariableDie;
1999 /// getOrCreateScope - Returns the scope associated with the given descriptor.
2001 DbgScope *getOrCreateScope(GlobalVariable *V) {
2002 DbgScope *&Slot = DbgScopeMap[V];
2003 if (Slot) return Slot;
2005 DbgScope *Parent = NULL;
2006 DIBlock Block(V);
2007 if (!Block.isNull()) {
2008 DIDescriptor ParentDesc = Block.getContext();
2009 Parent =
2010 ParentDesc.isNull() ? NULL : getOrCreateScope(ParentDesc.getGV());
2012 Slot = new DbgScope(Parent, DIDescriptor(V));
2014 if (Parent)
2015 Parent->AddScope(Slot);
2016 else
2017 // First function is top level function.
2018 FunctionDbgScope = Slot;
2020 return Slot;
2023 /// createInlinedSubroutineScope - Returns the scope associated with the
2024 /// inlined subroutine.
2026 DbgScope *createInlinedSubroutineScope(DISubprogram SP, unsigned Src,
2027 unsigned Line, unsigned Col) {
2028 DbgScope *Scope =
2029 new DbgInlinedSubroutineScope(NULL, SP, Src, Line, Col);
2031 // FIXME - Add inlined function scopes to the root so we can delete them
2032 // later.
2033 assert (FunctionDbgScope && "Function scope info missing!");
2034 FunctionDbgScope->AddScope(Scope);
2035 return Scope;
2038 /// ConstructDbgScope - Construct the components of a scope.
2040 void ConstructDbgScope(DbgScope *ParentScope,
2041 unsigned ParentStartID, unsigned ParentEndID,
2042 DIE *ParentDie, CompileUnit *Unit) {
2043 // Add variables to scope.
2044 SmallVector<DbgVariable *, 8> &Variables = ParentScope->getVariables();
2045 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2046 DIE *VariableDie = NewDbgScopeVariable(Variables[i], Unit);
2047 if (VariableDie) ParentDie->AddChild(VariableDie);
2050 // Add nested scopes.
2051 SmallVector<DbgScope *, 4> &Scopes = ParentScope->getScopes();
2052 for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
2053 // Define the Scope debug information entry.
2054 DbgScope *Scope = Scopes[j];
2056 unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
2057 unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
2059 // Ignore empty scopes.
2060 // Do not ignore inlined scope even if it does not have any
2061 // variables or scopes.
2062 if (StartID == EndID && StartID != 0) continue;
2063 if (!Scope->isInlinedSubroutine()
2064 && Scope->getScopes().empty() && Scope->getVariables().empty())
2065 continue;
2067 if (StartID == ParentStartID && EndID == ParentEndID) {
2068 // Just add stuff to the parent scope.
2069 ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
2070 } else {
2071 DIE *ScopeDie = NULL;
2072 if (MainCU && TAI->doesDwarfUsesInlineInfoSection()
2073 && Scope->isInlinedSubroutine()) {
2074 ScopeDie = new DIE(DW_TAG_inlined_subroutine);
2075 DIE *Origin = MainCU->getDieMapSlotFor(Scope->getDesc().getGV());
2076 AddDIEntry(ScopeDie, DW_AT_abstract_origin, DW_FORM_ref4, Origin);
2077 AddUInt(ScopeDie, DW_AT_call_file, 0, Scope->getFile());
2078 AddUInt(ScopeDie, DW_AT_call_line, 0, Scope->getLine());
2079 AddUInt(ScopeDie, DW_AT_call_column, 0, Scope->getColumn());
2080 } else {
2081 ScopeDie = new DIE(DW_TAG_lexical_block);
2084 // Add the scope bounds.
2085 if (StartID)
2086 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2087 DWLabel("label", StartID));
2088 else
2089 AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2090 DWLabel("func_begin", SubprogramCount));
2092 if (EndID)
2093 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2094 DWLabel("label", EndID));
2095 else
2096 AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2097 DWLabel("func_end", SubprogramCount));
2099 // Add the scope contents.
2100 ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
2101 ParentDie->AddChild(ScopeDie);
2106 /// ConstructFunctionDbgScope - Construct the scope for the subprogram.
2108 void ConstructFunctionDbgScope(DbgScope *RootScope) {
2109 // Exit if there is no root scope.
2110 if (!RootScope) return;
2111 DIDescriptor Desc = RootScope->getDesc();
2112 if (Desc.isNull())
2113 return;
2115 // Get the subprogram debug information entry.
2116 DISubprogram SPD(Desc.getGV());
2118 // Get the compile unit context.
2119 CompileUnit *Unit = MainCU;
2120 if (!Unit)
2121 Unit = FindCompileUnit(SPD.getCompileUnit());
2123 // Get the subprogram die.
2124 DIE *SPDie = Unit->getDieMapSlotFor(SPD.getGV());
2125 assert(SPDie && "Missing subprogram descriptor");
2127 // Add the function bounds.
2128 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2129 DWLabel("func_begin", SubprogramCount));
2130 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2131 DWLabel("func_end", SubprogramCount));
2132 MachineLocation Location(RI->getFrameRegister(*MF));
2133 AddAddress(SPDie, DW_AT_frame_base, Location);
2135 ConstructDbgScope(RootScope, 0, 0, SPDie, Unit);
2138 /// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
2140 void ConstructDefaultDbgScope(MachineFunction *MF) {
2141 const char *FnName = MF->getFunction()->getNameStart();
2142 if (MainCU) {
2143 StringMap<DIE*> &Globals = MainCU->getGlobals();
2144 StringMap<DIE*>::iterator GI = Globals.find(FnName);
2145 if (GI != Globals.end()) {
2146 DIE *SPDie = GI->second;
2148 // Add the function bounds.
2149 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2150 DWLabel("func_begin", SubprogramCount));
2151 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2152 DWLabel("func_end", SubprogramCount));
2154 MachineLocation Location(RI->getFrameRegister(*MF));
2155 AddAddress(SPDie, DW_AT_frame_base, Location);
2156 return;
2158 } else {
2159 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
2160 CompileUnit *Unit = CompileUnits[i];
2161 StringMap<DIE*> &Globals = Unit->getGlobals();
2162 StringMap<DIE*>::iterator GI = Globals.find(FnName);
2163 if (GI != Globals.end()) {
2164 DIE *SPDie = GI->second;
2166 // Add the function bounds.
2167 AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2168 DWLabel("func_begin", SubprogramCount));
2169 AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2170 DWLabel("func_end", SubprogramCount));
2172 MachineLocation Location(RI->getFrameRegister(*MF));
2173 AddAddress(SPDie, DW_AT_frame_base, Location);
2174 return;
2179 #if 0
2180 // FIXME: This is causing an abort because C++ mangled names are compared
2181 // with their unmangled counterparts. See PR2885. Don't do this assert.
2182 assert(0 && "Couldn't find DIE for machine function!");
2183 #endif
2184 return;
2187 /// EmitInitial - Emit initial Dwarf declarations. This is necessary for cc
2188 /// tools to recognize the object file contains Dwarf information.
2189 void EmitInitial() {
2190 // Check to see if we already emitted intial headers.
2191 if (didInitial) return;
2192 didInitial = true;
2194 // Dwarf sections base addresses.
2195 if (TAI->doesDwarfRequireFrameSection()) {
2196 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2197 EmitLabel("section_debug_frame", 0);
2199 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2200 EmitLabel("section_info", 0);
2201 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2202 EmitLabel("section_abbrev", 0);
2203 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2204 EmitLabel("section_aranges", 0);
2205 if (TAI->doesSupportMacInfoSection()) {
2206 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2207 EmitLabel("section_macinfo", 0);
2209 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2210 EmitLabel("section_line", 0);
2211 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2212 EmitLabel("section_loc", 0);
2213 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2214 EmitLabel("section_pubnames", 0);
2215 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2216 EmitLabel("section_str", 0);
2217 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2218 EmitLabel("section_ranges", 0);
2220 Asm->SwitchToSection(TAI->getTextSection());
2221 EmitLabel("text_begin", 0);
2222 Asm->SwitchToSection(TAI->getDataSection());
2223 EmitLabel("data_begin", 0);
2226 /// EmitDIE - Recusively Emits a debug information entry.
2228 void EmitDIE(DIE *Die) {
2229 // Get the abbreviation for this DIE.
2230 unsigned AbbrevNumber = Die->getAbbrevNumber();
2231 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2233 Asm->EOL();
2235 // Emit the code (index) for the abbreviation.
2236 Asm->EmitULEB128Bytes(AbbrevNumber);
2238 if (Asm->isVerbose())
2239 Asm->EOL(std::string("Abbrev [" +
2240 utostr(AbbrevNumber) +
2241 "] 0x" + utohexstr(Die->getOffset()) +
2242 ":0x" + utohexstr(Die->getSize()) + " " +
2243 TagString(Abbrev->getTag())));
2244 else
2245 Asm->EOL();
2247 SmallVector<DIEValue*, 32> &Values = Die->getValues();
2248 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2250 // Emit the DIE attribute values.
2251 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2252 unsigned Attr = AbbrevData[i].getAttribute();
2253 unsigned Form = AbbrevData[i].getForm();
2254 assert(Form && "Too many attributes for DIE (check abbreviation)");
2256 switch (Attr) {
2257 case DW_AT_sibling: {
2258 Asm->EmitInt32(Die->SiblingOffset());
2259 break;
2261 default: {
2262 // Emit an attribute using the defined form.
2263 Values[i]->EmitValue(*this, Form);
2264 break;
2268 Asm->EOL(AttributeString(Attr));
2271 // Emit the DIE children if any.
2272 if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2273 const std::vector<DIE *> &Children = Die->getChildren();
2275 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2276 EmitDIE(Children[j]);
2279 Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2283 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2285 unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2286 // Get the children.
2287 const std::vector<DIE *> &Children = Die->getChildren();
2289 // If not last sibling and has children then add sibling offset attribute.
2290 if (!Last && !Children.empty()) Die->AddSiblingOffset();
2292 // Record the abbreviation.
2293 AssignAbbrevNumber(Die->getAbbrev());
2295 // Get the abbreviation for this DIE.
2296 unsigned AbbrevNumber = Die->getAbbrevNumber();
2297 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2299 // Set DIE offset
2300 Die->setOffset(Offset);
2302 // Start the size with the size of abbreviation code.
2303 Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
2305 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2306 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2308 // Size the DIE attribute values.
2309 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2310 // Size attribute value.
2311 Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2314 // Size the DIE children if any.
2315 if (!Children.empty()) {
2316 assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2317 "Children flag not set");
2319 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2320 Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2323 // End of children marker.
2324 Offset += sizeof(int8_t);
2327 Die->setSize(Offset - Die->getOffset());
2328 return Offset;
2331 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2333 void SizeAndOffsets() {
2334 // Process base compile unit.
2335 if (MainCU) {
2336 // Compute size of compile unit header
2337 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2338 sizeof(int16_t) + // DWARF version number
2339 sizeof(int32_t) + // Offset Into Abbrev. Section
2340 sizeof(int8_t); // Pointer Size (in bytes)
2341 SizeAndOffsetDie(MainCU->getDie(), Offset, true);
2342 return;
2344 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i) {
2345 CompileUnit *Unit = CompileUnits[i];
2346 // Compute size of compile unit header
2347 unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2348 sizeof(int16_t) + // DWARF version number
2349 sizeof(int32_t) + // Offset Into Abbrev. Section
2350 sizeof(int8_t); // Pointer Size (in bytes)
2351 SizeAndOffsetDie(Unit->getDie(), Offset, true);
2355 /// EmitDebugInfo / EmitDebugInfoPerCU - Emit the debug info section.
2357 void EmitDebugInfoPerCU(CompileUnit *Unit) {
2358 DIE *Die = Unit->getDie();
2359 // Emit the compile units header.
2360 EmitLabel("info_begin", Unit->getID());
2361 // Emit size of content not including length itself
2362 unsigned ContentSize = Die->getSize() +
2363 sizeof(int16_t) + // DWARF version number
2364 sizeof(int32_t) + // Offset Into Abbrev. Section
2365 sizeof(int8_t) + // Pointer Size (in bytes)
2366 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2368 Asm->EmitInt32(ContentSize); Asm->EOL("Length of Compilation Unit Info");
2369 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2370 EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2371 Asm->EOL("Offset Into Abbrev. Section");
2372 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2374 EmitDIE(Die);
2375 // FIXME - extra padding for gdb bug.
2376 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2377 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2378 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2379 Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2380 EmitLabel("info_end", Unit->getID());
2382 Asm->EOL();
2385 void EmitDebugInfo() {
2386 // Start debug info section.
2387 Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2389 if (MainCU) {
2390 EmitDebugInfoPerCU(MainCU);
2391 return;
2394 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
2395 EmitDebugInfoPerCU(CompileUnits[i]);
2398 /// EmitAbbreviations - Emit the abbreviation section.
2400 void EmitAbbreviations() const {
2401 // Check to see if it is worth the effort.
2402 if (!Abbreviations.empty()) {
2403 // Start the debug abbrev section.
2404 Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2406 EmitLabel("abbrev_begin", 0);
2408 // For each abbrevation.
2409 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2410 // Get abbreviation data
2411 const DIEAbbrev *Abbrev = Abbreviations[i];
2413 // Emit the abbrevations code (base 1 index.)
2414 Asm->EmitULEB128Bytes(Abbrev->getNumber());
2415 Asm->EOL("Abbreviation Code");
2417 // Emit the abbreviations data.
2418 Abbrev->Emit(*this);
2420 Asm->EOL();
2423 // Mark end of abbreviations.
2424 Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2426 EmitLabel("abbrev_end", 0);
2428 Asm->EOL();
2432 /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
2433 /// the line matrix.
2435 void EmitEndOfLineMatrix(unsigned SectionEnd) {
2436 // Define last address of section.
2437 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2438 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2439 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2440 EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2442 // Mark end of matrix.
2443 Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2444 Asm->EmitULEB128Bytes(1); Asm->EOL();
2445 Asm->EmitInt8(1); Asm->EOL();
2448 /// EmitDebugLines - Emit source line information.
2450 void EmitDebugLines() {
2451 // If the target is using .loc/.file, the assembler will be emitting the
2452 // .debug_line table automatically.
2453 if (TAI->hasDotLocAndDotFile())
2454 return;
2456 // Minimum line delta, thus ranging from -10..(255-10).
2457 const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2458 // Maximum line delta, thus ranging from -10..(255-10).
2459 const int MaxLineDelta = 255 + MinLineDelta;
2461 // Start the dwarf line section.
2462 Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2464 // Construct the section header.
2466 EmitDifference("line_end", 0, "line_begin", 0, true);
2467 Asm->EOL("Length of Source Line Info");
2468 EmitLabel("line_begin", 0);
2470 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2472 EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2473 Asm->EOL("Prolog Length");
2474 EmitLabel("line_prolog_begin", 0);
2476 Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2478 Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2480 Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2482 Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2484 Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2486 // Line number standard opcode encodings argument count
2487 Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2488 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2489 Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2490 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2491 Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2492 Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2493 Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2494 Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2495 Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2497 // Emit directories.
2498 for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
2499 Asm->EmitString(getSourceDirectoryName(DI));
2500 Asm->EOL("Directory");
2502 Asm->EmitInt8(0); Asm->EOL("End of directories");
2504 // Emit files.
2505 for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
2506 // Remember source id starts at 1.
2507 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
2508 Asm->EmitString(getSourceFileName(Id.second));
2509 Asm->EOL("Source");
2510 Asm->EmitULEB128Bytes(Id.first);
2511 Asm->EOL("Directory #");
2512 Asm->EmitULEB128Bytes(0);
2513 Asm->EOL("Mod date");
2514 Asm->EmitULEB128Bytes(0);
2515 Asm->EOL("File size");
2517 Asm->EmitInt8(0); Asm->EOL("End of files");
2519 EmitLabel("line_prolog_end", 0);
2521 // A sequence for each text section.
2522 unsigned SecSrcLinesSize = SectionSourceLines.size();
2524 for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2525 // Isolate current sections line info.
2526 const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
2528 if (Asm->isVerbose()) {
2529 const Section* S = SectionMap[j + 1];
2530 O << '\t' << TAI->getCommentString() << " Section"
2531 << S->getName() << '\n';
2532 } else
2533 Asm->EOL();
2535 // Dwarf assumes we start with first line of first source file.
2536 unsigned Source = 1;
2537 unsigned Line = 1;
2539 // Construct rows of the address, source, line, column matrix.
2540 for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2541 const SrcLineInfo &LineInfo = LineInfos[i];
2542 unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2543 if (!LabelID) continue;
2545 if (!Asm->isVerbose())
2546 Asm->EOL();
2547 else {
2548 std::pair<unsigned, unsigned> SourceID =
2549 getSourceDirectoryAndFileIds(LineInfo.getSourceID());
2550 O << '\t' << TAI->getCommentString() << ' '
2551 << getSourceDirectoryName(SourceID.first) << ' '
2552 << getSourceFileName(SourceID.second)
2553 <<" :" << utostr_32(LineInfo.getLine()) << '\n';
2556 // Define the line address.
2557 Asm->EmitInt8(0); Asm->EOL("Extended Op");
2558 Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2559 Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2560 EmitReference("label", LabelID); Asm->EOL("Location label");
2562 // If change of source, then switch to the new source.
2563 if (Source != LineInfo.getSourceID()) {
2564 Source = LineInfo.getSourceID();
2565 Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2566 Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2569 // If change of line.
2570 if (Line != LineInfo.getLine()) {
2571 // Determine offset.
2572 int Offset = LineInfo.getLine() - Line;
2573 int Delta = Offset - MinLineDelta;
2575 // Update line.
2576 Line = LineInfo.getLine();
2578 // If delta is small enough and in range...
2579 if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2580 // ... then use fast opcode.
2581 Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2582 } else {
2583 // ... otherwise use long hand.
2584 Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
2585 Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2586 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2588 } else {
2589 // Copy the previous row (different address or source)
2590 Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2594 EmitEndOfLineMatrix(j + 1);
2597 if (SecSrcLinesSize == 0)
2598 // Because we're emitting a debug_line section, we still need a line
2599 // table. The linker and friends expect it to exist. If there's nothing to
2600 // put into it, emit an empty table.
2601 EmitEndOfLineMatrix(1);
2603 EmitLabel("line_end", 0);
2605 Asm->EOL();
2608 /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2610 void EmitCommonDebugFrame() {
2611 if (!TAI->doesDwarfRequireFrameSection())
2612 return;
2614 int stackGrowth =
2615 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2616 TargetFrameInfo::StackGrowsUp ?
2617 TD->getPointerSize() : -TD->getPointerSize();
2619 // Start the dwarf frame section.
2620 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2622 EmitLabel("debug_frame_common", 0);
2623 EmitDifference("debug_frame_common_end", 0,
2624 "debug_frame_common_begin", 0, true);
2625 Asm->EOL("Length of Common Information Entry");
2627 EmitLabel("debug_frame_common_begin", 0);
2628 Asm->EmitInt32((int)DW_CIE_ID);
2629 Asm->EOL("CIE Identifier Tag");
2630 Asm->EmitInt8(DW_CIE_VERSION);
2631 Asm->EOL("CIE Version");
2632 Asm->EmitString("");
2633 Asm->EOL("CIE Augmentation");
2634 Asm->EmitULEB128Bytes(1);
2635 Asm->EOL("CIE Code Alignment Factor");
2636 Asm->EmitSLEB128Bytes(stackGrowth);
2637 Asm->EOL("CIE Data Alignment Factor");
2638 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2639 Asm->EOL("CIE RA Column");
2641 std::vector<MachineMove> Moves;
2642 RI->getInitialFrameState(Moves);
2644 EmitFrameMoves(NULL, 0, Moves, false);
2646 Asm->EmitAlignment(2, 0, 0, false);
2647 EmitLabel("debug_frame_common_end", 0);
2649 Asm->EOL();
2652 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2653 /// section.
2654 void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2655 if (!TAI->doesDwarfRequireFrameSection())
2656 return;
2658 // Start the dwarf frame section.
2659 Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2661 EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2662 "debug_frame_begin", DebugFrameInfo.Number, true);
2663 Asm->EOL("Length of Frame Information Entry");
2665 EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2667 EmitSectionOffset("debug_frame_common", "section_debug_frame",
2668 0, 0, true, false);
2669 Asm->EOL("FDE CIE offset");
2671 EmitReference("func_begin", DebugFrameInfo.Number);
2672 Asm->EOL("FDE initial location");
2673 EmitDifference("func_end", DebugFrameInfo.Number,
2674 "func_begin", DebugFrameInfo.Number);
2675 Asm->EOL("FDE address range");
2677 EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves,
2678 false);
2680 Asm->EmitAlignment(2, 0, 0, false);
2681 EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2683 Asm->EOL();
2686 void EmitDebugPubNamesPerCU(CompileUnit *Unit) {
2687 EmitDifference("pubnames_end", Unit->getID(),
2688 "pubnames_begin", Unit->getID(), true);
2689 Asm->EOL("Length of Public Names Info");
2691 EmitLabel("pubnames_begin", Unit->getID());
2693 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
2695 EmitSectionOffset("info_begin", "section_info",
2696 Unit->getID(), 0, true, false);
2697 Asm->EOL("Offset of Compilation Unit Info");
2699 EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),
2700 true);
2701 Asm->EOL("Compilation Unit Length");
2703 StringMap<DIE*> &Globals = Unit->getGlobals();
2704 for (StringMap<DIE*>::const_iterator
2705 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2706 const char *Name = GI->getKeyData();
2707 DIE * Entity = GI->second;
2709 Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2710 Asm->EmitString(Name, strlen(Name)); Asm->EOL("External Name");
2713 Asm->EmitInt32(0); Asm->EOL("End Mark");
2714 EmitLabel("pubnames_end", Unit->getID());
2716 Asm->EOL();
2719 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2721 void EmitDebugPubNames() {
2722 // Start the dwarf pubnames section.
2723 Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2725 if (MainCU) {
2726 EmitDebugPubNamesPerCU(MainCU);
2727 return;
2730 for (unsigned i = 0, e = CompileUnits.size(); i != e; ++i)
2731 EmitDebugPubNamesPerCU(CompileUnits[i]);
2734 /// EmitDebugStr - Emit visible names into a debug str section.
2736 void EmitDebugStr() {
2737 // Check to see if it is worth the effort.
2738 if (!StringPool.empty()) {
2739 // Start the dwarf str section.
2740 Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2742 // For each of strings in the string pool.
2743 for (unsigned StringID = 1, N = StringPool.size();
2744 StringID <= N; ++StringID) {
2745 // Emit a label for reference from debug information entries.
2746 EmitLabel("string", StringID);
2747 // Emit the string itself.
2748 const std::string &String = StringPool[StringID];
2749 Asm->EmitString(String); Asm->EOL();
2752 Asm->EOL();
2756 /// EmitDebugLoc - Emit visible names into a debug loc section.
2758 void EmitDebugLoc() {
2759 // Start the dwarf loc section.
2760 Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2762 Asm->EOL();
2765 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2767 void EmitDebugARanges() {
2768 // Start the dwarf aranges section.
2769 Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2771 // FIXME - Mock up
2772 #if 0
2773 CompileUnit *Unit = GetBaseCompileUnit();
2775 // Don't include size of length
2776 Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2778 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2780 EmitReference("info_begin", Unit->getID());
2781 Asm->EOL("Offset of Compilation Unit Info");
2783 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2785 Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2787 Asm->EmitInt16(0); Asm->EOL("Pad (1)");
2788 Asm->EmitInt16(0); Asm->EOL("Pad (2)");
2790 // Range 1
2791 EmitReference("text_begin", 0); Asm->EOL("Address");
2792 EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2794 Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2795 Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2796 #endif
2798 Asm->EOL();
2801 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2803 void EmitDebugRanges() {
2804 // Start the dwarf ranges section.
2805 Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2807 Asm->EOL();
2810 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2812 void EmitDebugMacInfo() {
2813 if (TAI->doesSupportMacInfoSection()) {
2814 // Start the dwarf macinfo section.
2815 Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2817 Asm->EOL();
2821 /// EmitDebugInlineInfo - Emit inline info using following format.
2822 /// Section Header:
2823 /// 1. length of section
2824 /// 2. Dwarf version number
2825 /// 3. address size.
2827 /// Entries (one "entry" for each function that was inlined):
2829 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2830 /// otherwise offset into __debug_str for regular function name.
2831 /// 2. offset into __debug_str section for regular function name.
2832 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2833 /// instances for the function.
2834 ///
2835 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2836 /// inlined instance; the die_offset points to the inlined_subroutine die in
2837 /// the __debug_info section, and the low_pc is the starting address for the
2838 /// inlining instance.
2839 void EmitDebugInlineInfo() {
2840 if (!TAI->doesDwarfUsesInlineInfoSection())
2841 return;
2843 if (!MainCU)
2844 return;
2846 Asm->SwitchToDataSection(TAI->getDwarfDebugInlineSection());
2847 Asm->EOL();
2848 EmitDifference("debug_inlined_end", 1,
2849 "debug_inlined_begin", 1, true);
2850 Asm->EOL("Length of Debug Inlined Information Entry");
2852 EmitLabel("debug_inlined_begin", 1);
2854 Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2855 Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2857 for (DenseMap<GlobalVariable *, SmallVector<unsigned, 4> >::iterator
2858 I = InlineInfo.begin(), E = InlineInfo.end(); I != E; ++I) {
2859 GlobalVariable *GV = I->first;
2860 SmallVector<unsigned, 4> &Labels = I->second;
2861 DISubprogram SP(GV);
2862 std::string Name;
2863 std::string LName;
2865 SP.getLinkageName(LName);
2866 SP.getName(Name);
2868 Asm->EmitString(LName.empty() ? Name : LName);
2869 Asm->EOL("MIPS linkage name");
2871 Asm->EmitString(Name); Asm->EOL("Function name");
2873 Asm->EmitULEB128Bytes(Labels.size()); Asm->EOL("Inline count");
2875 for (SmallVector<unsigned, 4>::iterator LI = Labels.begin(),
2876 LE = Labels.end(); LI != LE; ++LI) {
2877 DIE *SP = MainCU->getDieMapSlotFor(GV);
2878 Asm->EmitInt32(SP->getOffset()); Asm->EOL("DIE offset");
2880 if (TD->getPointerSize() == sizeof(int32_t))
2881 O << TAI->getData32bitsDirective();
2882 else
2883 O << TAI->getData64bitsDirective();
2884 PrintLabelName("label", *LI); Asm->EOL("low_pc");
2888 EmitLabel("debug_inlined_end", 1);
2889 Asm->EOL();
2892 /// GetOrCreateSourceID - Look up the source id with the given directory and
2893 /// source file names. If none currently exists, create a new id and insert it
2894 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames maps
2895 /// as well.
2896 unsigned GetOrCreateSourceID(const std::string &DirName,
2897 const std::string &FileName) {
2898 unsigned DId;
2899 StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
2900 if (DI != DirectoryIdMap.end()) {
2901 DId = DI->getValue();
2902 } else {
2903 DId = DirectoryNames.size() + 1;
2904 DirectoryIdMap[DirName] = DId;
2905 DirectoryNames.push_back(DirName);
2908 unsigned FId;
2909 StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
2910 if (FI != SourceFileIdMap.end()) {
2911 FId = FI->getValue();
2912 } else {
2913 FId = SourceFileNames.size() + 1;
2914 SourceFileIdMap[FileName] = FId;
2915 SourceFileNames.push_back(FileName);
2918 DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
2919 SourceIdMap.find(std::make_pair(DId, FId));
2920 if (SI != SourceIdMap.end())
2921 return SI->second;
2923 unsigned SrcId = SourceIds.size() + 1; // DW_AT_decl_file cannot be 0.
2924 SourceIdMap[std::make_pair(DId, FId)] = SrcId;
2925 SourceIds.push_back(std::make_pair(DId, FId));
2927 return SrcId;
2930 void ConstructCompileUnit(GlobalVariable *GV) {
2931 DICompileUnit DIUnit(GV);
2932 std::string Dir, FN, Prod;
2933 unsigned ID = GetOrCreateSourceID(DIUnit.getDirectory(Dir),
2934 DIUnit.getFilename(FN));
2936 DIE *Die = new DIE(DW_TAG_compile_unit);
2937 AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
2938 DWLabel("section_line", 0), DWLabel("section_line", 0),
2939 false);
2940 AddString(Die, DW_AT_producer, DW_FORM_string, DIUnit.getProducer(Prod));
2941 AddUInt(Die, DW_AT_language, DW_FORM_data1, DIUnit.getLanguage());
2942 AddString(Die, DW_AT_name, DW_FORM_string, FN);
2943 if (!Dir.empty())
2944 AddString(Die, DW_AT_comp_dir, DW_FORM_string, Dir);
2945 if (DIUnit.isOptimized())
2946 AddUInt(Die, DW_AT_APPLE_optimized, DW_FORM_flag, 1);
2947 std::string Flags;
2948 DIUnit.getFlags(Flags);
2949 if (!Flags.empty())
2950 AddString(Die, DW_AT_APPLE_flags, DW_FORM_string, Flags);
2951 unsigned RVer = DIUnit.getRunTimeVersion();
2952 if (RVer)
2953 AddUInt(Die, DW_AT_APPLE_major_runtime_vers, DW_FORM_data1, RVer);
2955 CompileUnit *Unit = new CompileUnit(ID, Die);
2956 if (DIUnit.isMain()) {
2957 assert(!MainCU && "Multiple main compile units are found!");
2958 MainCU = Unit;
2960 CompileUnitMap[DIUnit.getGV()] = Unit;
2961 CompileUnits.push_back(Unit);
2964 /// ConstructCompileUnits - Create a compile unit DIEs.
2965 void ConstructCompileUnits() {
2966 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.compile_units");
2967 if (!Root)
2968 return;
2969 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
2970 "Malformed compile unit descriptor anchor type");
2971 Constant *RootC = cast<Constant>(*Root->use_begin());
2972 assert(RootC->hasNUsesOrMore(1) &&
2973 "Malformed compile unit descriptor anchor type");
2974 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
2975 UI != UE; ++UI)
2976 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
2977 UUI != UUE; ++UUI) {
2978 GlobalVariable *GV = cast<GlobalVariable>(*UUI);
2979 ConstructCompileUnit(GV);
2983 bool ConstructGlobalVariableDIE(GlobalVariable *GV) {
2984 DIGlobalVariable DI_GV(GV);
2985 CompileUnit *DW_Unit = MainCU;
2986 if (!DW_Unit)
2987 DW_Unit = FindCompileUnit(DI_GV.getCompileUnit());
2989 // Check for pre-existence.
2990 DIE *&Slot = DW_Unit->getDieMapSlotFor(DI_GV.getGV());
2991 if (Slot)
2992 return false;
2994 DIE *VariableDie = CreateGlobalVariableDIE(DW_Unit, DI_GV);
2996 // Add address.
2997 DIEBlock *Block = new DIEBlock();
2998 AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
2999 std::string GLN;
3000 AddObjectLabel(Block, 0, DW_FORM_udata,
3001 Asm->getGlobalLinkName(DI_GV.getGlobal(), GLN));
3002 AddBlock(VariableDie, DW_AT_location, 0, Block);
3004 // Add to map.
3005 Slot = VariableDie;
3006 // Add to context owner.
3007 DW_Unit->getDie()->AddChild(VariableDie);
3008 // Expose as global. FIXME - need to check external flag.
3009 std::string Name;
3010 DW_Unit->AddGlobal(DI_GV.getName(Name), VariableDie);
3011 return true;
3014 /// ConstructGlobalVariableDIEs - Create DIEs for each of the externally
3015 /// visible global variables. Return true if at least one global DIE is
3016 /// created.
3017 bool ConstructGlobalVariableDIEs() {
3018 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.global_variables");
3019 if (!Root)
3020 return false;
3022 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
3023 "Malformed global variable descriptor anchor type");
3024 Constant *RootC = cast<Constant>(*Root->use_begin());
3025 assert(RootC->hasNUsesOrMore(1) &&
3026 "Malformed global variable descriptor anchor type");
3028 bool Result = false;
3029 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
3030 UI != UE; ++UI)
3031 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
3032 UUI != UUE; ++UUI) {
3033 GlobalVariable *GV = cast<GlobalVariable>(*UUI);
3034 Result |= ConstructGlobalVariableDIE(GV);
3036 return Result;
3039 bool ConstructSubprogram(GlobalVariable *GV) {
3040 DISubprogram SP(GV);
3041 CompileUnit *Unit = MainCU;
3042 if (!Unit)
3043 Unit = FindCompileUnit(SP.getCompileUnit());
3045 // Check for pre-existence.
3046 DIE *&Slot = Unit->getDieMapSlotFor(GV);
3047 if (Slot)
3048 return false;
3050 if (!SP.isDefinition())
3051 // This is a method declaration which will be handled while
3052 // constructing class type.
3053 return false;
3055 DIE *SubprogramDie = CreateSubprogramDIE(Unit, SP);
3057 // Add to map.
3058 Slot = SubprogramDie;
3059 // Add to context owner.
3060 Unit->getDie()->AddChild(SubprogramDie);
3061 // Expose as global.
3062 std::string Name;
3063 Unit->AddGlobal(SP.getName(Name), SubprogramDie);
3064 return true;
3067 /// ConstructSubprograms - Create DIEs for each of the externally visible
3068 /// subprograms. Return true if at least one subprogram DIE is created.
3069 bool ConstructSubprograms() {
3070 GlobalVariable *Root = M->getGlobalVariable("llvm.dbg.subprograms");
3071 if (!Root)
3072 return false;
3074 assert(Root->hasLinkOnceLinkage() && Root->hasOneUse() &&
3075 "Malformed subprogram descriptor anchor type");
3076 Constant *RootC = cast<Constant>(*Root->use_begin());
3077 assert(RootC->hasNUsesOrMore(1) &&
3078 "Malformed subprogram descriptor anchor type");
3080 bool Result = false;
3081 for (Value::use_iterator UI = RootC->use_begin(), UE = Root->use_end();
3082 UI != UE; ++UI)
3083 for (Value::use_iterator UUI = UI->use_begin(), UUE = UI->use_end();
3084 UUI != UUE; ++UUI) {
3085 GlobalVariable *GV = cast<GlobalVariable>(*UUI);
3086 Result |= ConstructSubprogram(GV);
3088 return Result;
3091 public:
3092 //===--------------------------------------------------------------------===//
3093 // Main entry points.
3095 DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3096 : Dwarf(OS, A, T, "dbg"), MainCU(0),
3097 AbbreviationsSet(InitAbbreviationsSetSize), Abbreviations(),
3098 ValuesSet(InitValuesSetSize), Values(), StringPool(), SectionMap(),
3099 SectionSourceLines(), didInitial(false), shouldEmit(false),
3100 FunctionDbgScope(0), DebugTimer(0) {
3101 if (TimePassesIsEnabled)
3102 DebugTimer = new Timer("Dwarf Debug Writer",
3103 getDwarfTimerGroup());
3105 virtual ~DwarfDebug() {
3106 for (unsigned j = 0, M = Values.size(); j < M; ++j)
3107 delete Values[j];
3109 delete DebugTimer;
3112 /// ShouldEmitDwarfDebug - Returns true if Dwarf debugging declarations should
3113 /// be emitted.
3114 bool ShouldEmitDwarfDebug() const { return shouldEmit; }
3116 /// SetDebugInfo - Create global DIEs and emit initial debug info sections.
3117 /// This is inovked by the target AsmPrinter.
3118 void SetDebugInfo(MachineModuleInfo *mmi) {
3119 if (TimePassesIsEnabled)
3120 DebugTimer->startTimer();
3122 // Create all the compile unit DIEs.
3123 ConstructCompileUnits();
3125 if (CompileUnits.empty()) {
3126 if (TimePassesIsEnabled)
3127 DebugTimer->stopTimer();
3129 return;
3132 // Create DIEs for each of the externally visible global variables.
3133 bool globalDIEs = ConstructGlobalVariableDIEs();
3135 // Create DIEs for each of the externally visible subprograms.
3136 bool subprogramDIEs = ConstructSubprograms();
3138 // If there is not any debug info available for any global variables
3139 // and any subprograms then there is not any debug info to emit.
3140 if (!globalDIEs && !subprogramDIEs) {
3141 if (TimePassesIsEnabled)
3142 DebugTimer->stopTimer();
3144 return;
3147 MMI = mmi;
3148 shouldEmit = true;
3149 MMI->setDebugInfoAvailability(true);
3151 // Prime section data.
3152 SectionMap.insert(TAI->getTextSection());
3154 // Print out .file directives to specify files for .loc directives. These
3155 // are printed out early so that they precede any .loc directives.
3156 if (TAI->hasDotLocAndDotFile()) {
3157 for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
3158 // Remember source id starts at 1.
3159 std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
3160 sys::Path FullPath(getSourceDirectoryName(Id.first));
3161 bool AppendOk =
3162 FullPath.appendComponent(getSourceFileName(Id.second));
3163 assert(AppendOk && "Could not append filename to directory!");
3164 AppendOk = false;
3165 Asm->EmitFile(i, FullPath.toString());
3166 Asm->EOL();
3170 // Emit initial sections
3171 EmitInitial();
3173 if (TimePassesIsEnabled)
3174 DebugTimer->stopTimer();
3177 /// BeginModule - Emit all Dwarf sections that should come prior to the
3178 /// content.
3179 void BeginModule(Module *M) {
3180 this->M = M;
3183 /// EndModule - Emit all Dwarf sections that should come after the content.
3185 void EndModule() {
3186 if (!ShouldEmitDwarfDebug())
3187 return;
3189 if (TimePassesIsEnabled)
3190 DebugTimer->startTimer();
3192 // Standard sections final addresses.
3193 Asm->SwitchToSection(TAI->getTextSection());
3194 EmitLabel("text_end", 0);
3195 Asm->SwitchToSection(TAI->getDataSection());
3196 EmitLabel("data_end", 0);
3198 // End text sections.
3199 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
3200 Asm->SwitchToSection(SectionMap[i]);
3201 EmitLabel("section_end", i);
3204 // Emit common frame information.
3205 EmitCommonDebugFrame();
3207 // Emit function debug frame information
3208 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
3209 E = DebugFrames.end(); I != E; ++I)
3210 EmitFunctionDebugFrame(*I);
3212 // Compute DIE offsets and sizes.
3213 SizeAndOffsets();
3215 // Emit all the DIEs into a debug info section
3216 EmitDebugInfo();
3218 // Corresponding abbreviations into a abbrev section.
3219 EmitAbbreviations();
3221 // Emit source line correspondence into a debug line section.
3222 EmitDebugLines();
3224 // Emit info into a debug pubnames section.
3225 EmitDebugPubNames();
3227 // Emit info into a debug str section.
3228 EmitDebugStr();
3230 // Emit info into a debug loc section.
3231 EmitDebugLoc();
3233 // Emit info into a debug aranges section.
3234 EmitDebugARanges();
3236 // Emit info into a debug ranges section.
3237 EmitDebugRanges();
3239 // Emit info into a debug macinfo section.
3240 EmitDebugMacInfo();
3242 // Emit inline info.
3243 EmitDebugInlineInfo();
3245 if (TimePassesIsEnabled)
3246 DebugTimer->stopTimer();
3249 /// BeginFunction - Gather pre-function debug information. Assumes being
3250 /// emitted immediately after the function entry point.
3251 void BeginFunction(MachineFunction *MF) {
3252 this->MF = MF;
3254 if (!ShouldEmitDwarfDebug()) return;
3256 if (TimePassesIsEnabled)
3257 DebugTimer->startTimer();
3259 // Begin accumulating function debug information.
3260 MMI->BeginFunction(MF);
3262 // Assumes in correct section after the entry point.
3263 EmitLabel("func_begin", ++SubprogramCount);
3265 // Emit label for the implicitly defined dbg.stoppoint at the start of
3266 // the function.
3267 if (!Lines.empty()) {
3268 const SrcLineInfo &LineInfo = Lines[0];
3269 Asm->printLabel(LineInfo.getLabelID());
3272 if (TimePassesIsEnabled)
3273 DebugTimer->stopTimer();
3276 /// EndFunction - Gather and emit post-function debug information.
3278 void EndFunction(MachineFunction *MF) {
3279 if (!ShouldEmitDwarfDebug()) return;
3281 if (TimePassesIsEnabled)
3282 DebugTimer->startTimer();
3284 // Define end label for subprogram.
3285 EmitLabel("func_end", SubprogramCount);
3287 // Get function line info.
3288 if (!Lines.empty()) {
3289 // Get section line info.
3290 unsigned ID = SectionMap.insert(Asm->CurrentSection_);
3291 if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
3292 std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
3293 // Append the function info to section info.
3294 SectionLineInfos.insert(SectionLineInfos.end(),
3295 Lines.begin(), Lines.end());
3298 // Construct scopes for subprogram.
3299 if (FunctionDbgScope)
3300 ConstructFunctionDbgScope(FunctionDbgScope);
3301 else
3302 // FIXME: This is wrong. We are essentially getting past a problem with
3303 // debug information not being able to handle unreachable blocks that have
3304 // debug information in them. In particular, those unreachable blocks that
3305 // have "region end" info in them. That situation results in the "root
3306 // scope" not being created. If that's the case, then emit a "default"
3307 // scope, i.e., one that encompasses the whole function. This isn't
3308 // desirable. And a better way of handling this (and all of the debugging
3309 // information) needs to be explored.
3310 ConstructDefaultDbgScope(MF);
3312 DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
3313 MMI->getFrameMoves()));
3315 // Clear debug info
3316 if (FunctionDbgScope) {
3317 delete FunctionDbgScope;
3318 DbgScopeMap.clear();
3319 DbgInlinedScopeMap.clear();
3320 InlinedVariableScopes.clear();
3321 FunctionDbgScope = NULL;
3324 Lines.clear();
3326 if (TimePassesIsEnabled)
3327 DebugTimer->stopTimer();
3330 /// RecordSourceLine - Records location information and associates it with a
3331 /// label. Returns a unique label ID used to generate a label and provide
3332 /// correspondence to the source line list.
3333 unsigned RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
3334 if (TimePassesIsEnabled)
3335 DebugTimer->startTimer();
3337 CompileUnit *Unit = CompileUnitMap[V];
3338 assert(Unit && "Unable to find CompileUnit");
3339 unsigned ID = MMI->NextLabelID();
3340 Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
3342 if (TimePassesIsEnabled)
3343 DebugTimer->stopTimer();
3345 return ID;
3348 /// RecordSourceLine - Records location information and associates it with a
3349 /// label. Returns a unique label ID used to generate a label and provide
3350 /// correspondence to the source line list.
3351 unsigned RecordSourceLine(unsigned Line, unsigned Col, DICompileUnit CU) {
3352 if (TimePassesIsEnabled)
3353 DebugTimer->startTimer();
3355 std::string Dir, Fn;
3356 unsigned Src = GetOrCreateSourceID(CU.getDirectory(Dir),
3357 CU.getFilename(Fn));
3358 unsigned ID = MMI->NextLabelID();
3359 Lines.push_back(SrcLineInfo(Line, Col, Src, ID));
3361 if (TimePassesIsEnabled)
3362 DebugTimer->stopTimer();
3364 return ID;
3367 /// getRecordSourceLineCount - Return the number of source lines in the debug
3368 /// info.
3369 unsigned getRecordSourceLineCount() const {
3370 return Lines.size();
3373 /// getOrCreateSourceID - Public version of GetOrCreateSourceID. This can be
3374 /// timed. Look up the source id with the given directory and source file
3375 /// names. If none currently exists, create a new id and insert it in the
3376 /// SourceIds map. This can update DirectoryNames and SourceFileNames maps as
3377 /// well.
3378 unsigned getOrCreateSourceID(const std::string &DirName,
3379 const std::string &FileName) {
3380 if (TimePassesIsEnabled)
3381 DebugTimer->startTimer();
3383 unsigned SrcId = GetOrCreateSourceID(DirName, FileName);
3385 if (TimePassesIsEnabled)
3386 DebugTimer->stopTimer();
3388 return SrcId;
3391 /// RecordRegionStart - Indicate the start of a region.
3392 unsigned RecordRegionStart(GlobalVariable *V) {
3393 if (TimePassesIsEnabled)
3394 DebugTimer->startTimer();
3396 DbgScope *Scope = getOrCreateScope(V);
3397 unsigned ID = MMI->NextLabelID();
3398 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
3400 if (TimePassesIsEnabled)
3401 DebugTimer->stopTimer();
3403 return ID;
3406 /// RecordRegionEnd - Indicate the end of a region.
3407 unsigned RecordRegionEnd(GlobalVariable *V) {
3408 if (TimePassesIsEnabled)
3409 DebugTimer->startTimer();
3411 DbgScope *Scope = getOrCreateScope(V);
3412 unsigned ID = MMI->NextLabelID();
3413 Scope->setEndLabelID(ID);
3415 if (TimePassesIsEnabled)
3416 DebugTimer->stopTimer();
3418 return ID;
3421 /// RecordVariable - Indicate the declaration of a local variable.
3422 void RecordVariable(GlobalVariable *GV, unsigned FrameIndex,
3423 const MachineInstr *MI) {
3424 if (TimePassesIsEnabled)
3425 DebugTimer->startTimer();
3427 DIDescriptor Desc(GV);
3428 DbgScope *Scope = NULL;
3430 if (Desc.getTag() == DW_TAG_variable) {
3431 // GV is a global variable.
3432 DIGlobalVariable DG(GV);
3433 Scope = getOrCreateScope(DG.getContext().getGV());
3434 } else {
3435 DenseMap<const MachineInstr *, DbgScope *>::iterator
3436 SI = InlinedVariableScopes.find(MI);
3437 if (SI != InlinedVariableScopes.end()) {
3438 // or GV is an inlined local variable.
3439 Scope = SI->second;
3440 } else {
3441 // or GV is a local variable.
3442 DIVariable DV(GV);
3443 Scope = getOrCreateScope(DV.getContext().getGV());
3447 assert(Scope && "Unable to find variable' scope");
3448 DbgVariable *DV = new DbgVariable(DIVariable(GV), FrameIndex);
3449 Scope->AddVariable(DV);
3451 if (TimePassesIsEnabled)
3452 DebugTimer->stopTimer();
3455 //// RecordInlinedFnStart - Indicate the start of inlined subroutine.
3456 void RecordInlinedFnStart(Instruction *FSI, DISubprogram &SP, unsigned LabelID,
3457 DICompileUnit CU, unsigned Line, unsigned Col) {
3458 if (!TAI->doesDwarfUsesInlineInfoSection())
3459 return;
3461 if (TimePassesIsEnabled)
3462 DebugTimer->startTimer();
3464 std::string Dir, Fn;
3465 unsigned Src = GetOrCreateSourceID(CU.getDirectory(Dir),
3466 CU.getFilename(Fn));
3467 DbgScope *Scope = createInlinedSubroutineScope(SP, Src, Line, Col);
3468 Scope->setStartLabelID(LabelID);
3469 MMI->RecordUsedDbgLabel(LabelID);
3470 GlobalVariable *GV = SP.getGV();
3472 DenseMap<GlobalVariable *, SmallVector<DbgScope *, 2> >::iterator
3473 SI = DbgInlinedScopeMap.find(GV);
3475 if (SI == DbgInlinedScopeMap.end())
3476 DbgInlinedScopeMap[GV].push_back(Scope);
3477 else
3478 SI->second.push_back(Scope);
3480 DenseMap<GlobalVariable *, SmallVector<unsigned, 4> >::iterator
3481 I = InlineInfo.find(GV);
3482 if (I == InlineInfo.end())
3483 InlineInfo[GV].push_back(LabelID);
3484 else
3485 I->second.push_back(LabelID);
3487 if (TimePassesIsEnabled)
3488 DebugTimer->stopTimer();
3491 /// RecordInlinedFnEnd - Indicate the end of inlined subroutine.
3492 unsigned RecordInlinedFnEnd(DISubprogram &SP) {
3493 if (!TAI->doesDwarfUsesInlineInfoSection())
3494 return 0;
3496 if (TimePassesIsEnabled)
3497 DebugTimer->startTimer();
3499 GlobalVariable *GV = SP.getGV();
3500 DenseMap<GlobalVariable *, SmallVector<DbgScope *, 2> >::iterator
3501 I = DbgInlinedScopeMap.find(GV);
3502 if (I == DbgInlinedScopeMap.end()) {
3503 if (TimePassesIsEnabled)
3504 DebugTimer->stopTimer();
3506 return 0;
3509 SmallVector<DbgScope *, 2> &Scopes = I->second;
3510 assert(!Scopes.empty() && "We should have at least one debug scope!");
3511 DbgScope *Scope = Scopes.back(); Scopes.pop_back();
3512 unsigned ID = MMI->NextLabelID();
3513 MMI->RecordUsedDbgLabel(ID);
3514 Scope->setEndLabelID(ID);
3516 if (TimePassesIsEnabled)
3517 DebugTimer->stopTimer();
3519 return ID;
3522 /// RecordVariableScope - Record scope for the variable declared by
3523 /// DeclareMI. DeclareMI must describe TargetInstrInfo::DECLARE.
3524 /// Record scopes for only inlined subroutine variables. Other
3525 /// variables' scopes are determined during RecordVariable().
3526 void RecordVariableScope(DIVariable &DV, const MachineInstr *DeclareMI) {
3527 if (TimePassesIsEnabled)
3528 DebugTimer->startTimer();
3530 DISubprogram SP(DV.getContext().getGV());
3532 if (SP.isNull()) {
3533 if (TimePassesIsEnabled)
3534 DebugTimer->stopTimer();
3536 return;
3539 DenseMap<GlobalVariable *, SmallVector<DbgScope *, 2> >::iterator
3540 I = DbgInlinedScopeMap.find(SP.getGV());
3541 if (I != DbgInlinedScopeMap.end())
3542 InlinedVariableScopes[DeclareMI] = I->second.back();
3544 if (TimePassesIsEnabled)
3545 DebugTimer->stopTimer();
3549 //===----------------------------------------------------------------------===//
3550 /// DwarfException - Emits Dwarf exception handling directives.
3552 class DwarfException : public Dwarf {
3553 struct FunctionEHFrameInfo {
3554 std::string FnName;
3555 unsigned Number;
3556 unsigned PersonalityIndex;
3557 bool hasCalls;
3558 bool hasLandingPads;
3559 std::vector<MachineMove> Moves;
3560 const Function * function;
3562 FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
3563 bool hC, bool hL,
3564 const std::vector<MachineMove> &M,
3565 const Function *f):
3566 FnName(FN), Number(Num), PersonalityIndex(P),
3567 hasCalls(hC), hasLandingPads(hL), Moves(M), function (f) { }
3570 std::vector<FunctionEHFrameInfo> EHFrames;
3572 /// shouldEmitTable - Per-function flag to indicate if EH tables should
3573 /// be emitted.
3574 bool shouldEmitTable;
3576 /// shouldEmitMoves - Per-function flag to indicate if frame moves info
3577 /// should be emitted.
3578 bool shouldEmitMoves;
3580 /// shouldEmitTableModule - Per-module flag to indicate if EH tables
3581 /// should be emitted.
3582 bool shouldEmitTableModule;
3584 /// shouldEmitFrameModule - Per-module flag to indicate if frame moves
3585 /// should be emitted.
3586 bool shouldEmitMovesModule;
3588 /// ExceptionTimer - Timer for the Dwarf exception writer.
3589 Timer *ExceptionTimer;
3591 /// EmitCommonEHFrame - Emit the common eh unwind frame.
3593 void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
3594 // Size and sign of stack growth.
3595 int stackGrowth =
3596 Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3597 TargetFrameInfo::StackGrowsUp ?
3598 TD->getPointerSize() : -TD->getPointerSize();
3600 // Begin eh frame section.
3601 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3603 if (!TAI->doesRequireNonLocalEHFrameLabel())
3604 O << TAI->getEHGlobalPrefix();
3605 O << "EH_frame" << Index << ":\n";
3606 EmitLabel("section_eh_frame", Index);
3608 // Define base labels.
3609 EmitLabel("eh_frame_common", Index);
3611 // Define the eh frame length.
3612 EmitDifference("eh_frame_common_end", Index,
3613 "eh_frame_common_begin", Index, true);
3614 Asm->EOL("Length of Common Information Entry");
3616 // EH frame header.
3617 EmitLabel("eh_frame_common_begin", Index);
3618 Asm->EmitInt32((int)0);
3619 Asm->EOL("CIE Identifier Tag");
3620 Asm->EmitInt8(DW_CIE_VERSION);
3621 Asm->EOL("CIE Version");
3623 // The personality presence indicates that language specific information
3624 // will show up in the eh frame.
3625 Asm->EmitString(Personality ? "zPLR" : "zR");
3626 Asm->EOL("CIE Augmentation");
3628 // Round out reader.
3629 Asm->EmitULEB128Bytes(1);
3630 Asm->EOL("CIE Code Alignment Factor");
3631 Asm->EmitSLEB128Bytes(stackGrowth);
3632 Asm->EOL("CIE Data Alignment Factor");
3633 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
3634 Asm->EOL("CIE Return Address Column");
3636 // If there is a personality, we need to indicate the functions location.
3637 if (Personality) {
3638 Asm->EmitULEB128Bytes(7);
3639 Asm->EOL("Augmentation Size");
3641 if (TAI->getNeedsIndirectEncoding()) {
3642 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4 | DW_EH_PE_indirect);
3643 Asm->EOL("Personality (pcrel sdata4 indirect)");
3644 } else {
3645 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3646 Asm->EOL("Personality (pcrel sdata4)");
3649 PrintRelDirective(true);
3650 O << TAI->getPersonalityPrefix();
3651 Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
3652 O << TAI->getPersonalitySuffix();
3653 if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
3654 O << "-" << TAI->getPCSymbol();
3655 Asm->EOL("Personality");
3657 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3658 Asm->EOL("LSDA Encoding (pcrel sdata4)");
3660 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3661 Asm->EOL("FDE Encoding (pcrel sdata4)");
3662 } else {
3663 Asm->EmitULEB128Bytes(1);
3664 Asm->EOL("Augmentation Size");
3666 Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3667 Asm->EOL("FDE Encoding (pcrel sdata4)");
3670 // Indicate locations of general callee saved registers in frame.
3671 std::vector<MachineMove> Moves;
3672 RI->getInitialFrameState(Moves);
3673 EmitFrameMoves(NULL, 0, Moves, true);
3675 // On Darwin the linker honors the alignment of eh_frame, which means it
3676 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3677 // you get holes which confuse readers of eh_frame.
3678 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3679 0, 0, false);
3680 EmitLabel("eh_frame_common_end", Index);
3682 Asm->EOL();
3685 /// EmitEHFrame - Emit function exception frame information.
3687 void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
3688 Function::LinkageTypes linkage = EHFrameInfo.function->getLinkage();
3690 assert(!EHFrameInfo.function->hasAvailableExternallyLinkage() &&
3691 "Should not emit 'available externally' functions at all");
3693 Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3695 // Externally visible entry into the functions eh frame info.
3696 // If the corresponding function is static, this should not be
3697 // externally visible.
3698 if (linkage != Function::InternalLinkage &&
3699 linkage != Function::PrivateLinkage) {
3700 if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
3701 O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
3704 // If corresponding function is weak definition, this should be too.
3705 if ((linkage == Function::WeakAnyLinkage ||
3706 linkage == Function::WeakODRLinkage ||
3707 linkage == Function::LinkOnceAnyLinkage ||
3708 linkage == Function::LinkOnceODRLinkage) &&
3709 TAI->getWeakDefDirective())
3710 O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
3712 // If there are no calls then you can't unwind. This may mean we can
3713 // omit the EH Frame, but some environments do not handle weak absolute
3714 // symbols.
3715 // If UnwindTablesMandatory is set we cannot do this optimization; the
3716 // unwind info is to be available for non-EH uses.
3717 if (!EHFrameInfo.hasCalls &&
3718 !UnwindTablesMandatory &&
3719 ((linkage != Function::WeakAnyLinkage &&
3720 linkage != Function::WeakODRLinkage &&
3721 linkage != Function::LinkOnceAnyLinkage &&
3722 linkage != Function::LinkOnceODRLinkage) ||
3723 !TAI->getWeakDefDirective() ||
3724 TAI->getSupportsWeakOmittedEHFrame()))
3726 O << EHFrameInfo.FnName << " = 0\n";
3727 // This name has no connection to the function, so it might get
3728 // dead-stripped when the function is not, erroneously. Prohibit
3729 // dead-stripping unconditionally.
3730 if (const char *UsedDirective = TAI->getUsedDirective())
3731 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3732 } else {
3733 O << EHFrameInfo.FnName << ":\n";
3735 // EH frame header.
3736 EmitDifference("eh_frame_end", EHFrameInfo.Number,
3737 "eh_frame_begin", EHFrameInfo.Number, true);
3738 Asm->EOL("Length of Frame Information Entry");
3740 EmitLabel("eh_frame_begin", EHFrameInfo.Number);
3742 if (TAI->doesRequireNonLocalEHFrameLabel()) {
3743 PrintRelDirective(true, true);
3744 PrintLabelName("eh_frame_begin", EHFrameInfo.Number);
3746 if (!TAI->isAbsoluteEHSectionOffsets())
3747 O << "-EH_frame" << EHFrameInfo.PersonalityIndex;
3748 } else {
3749 EmitSectionOffset("eh_frame_begin", "eh_frame_common",
3750 EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
3751 true, true, false);
3754 Asm->EOL("FDE CIE offset");
3756 EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
3757 Asm->EOL("FDE initial location");
3758 EmitDifference("eh_func_end", EHFrameInfo.Number,
3759 "eh_func_begin", EHFrameInfo.Number, true);
3760 Asm->EOL("FDE address range");
3762 // If there is a personality and landing pads then point to the language
3763 // specific data area in the exception table.
3764 if (EHFrameInfo.PersonalityIndex) {
3765 Asm->EmitULEB128Bytes(4);
3766 Asm->EOL("Augmentation size");
3768 if (EHFrameInfo.hasLandingPads)
3769 EmitReference("exception", EHFrameInfo.Number, true, true);
3770 else
3771 Asm->EmitInt32((int)0);
3772 Asm->EOL("Language Specific Data Area");
3773 } else {
3774 Asm->EmitULEB128Bytes(0);
3775 Asm->EOL("Augmentation size");
3778 // Indicate locations of function specific callee saved registers in
3779 // frame.
3780 EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves,
3781 true);
3783 // On Darwin the linker honors the alignment of eh_frame, which means it
3784 // must be 8-byte on 64-bit targets to match what gcc does. Otherwise
3785 // you get holes which confuse readers of eh_frame.
3786 Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3787 0, 0, false);
3788 EmitLabel("eh_frame_end", EHFrameInfo.Number);
3790 // If the function is marked used, this table should be also. We cannot
3791 // make the mark unconditional in this case, since retaining the table
3792 // also retains the function in this case, and there is code around
3793 // that depends on unused functions (calling undefined externals) being
3794 // dead-stripped to link correctly. Yes, there really is.
3795 if (MMI->getUsedFunctions().count(EHFrameInfo.function))
3796 if (const char *UsedDirective = TAI->getUsedDirective())
3797 O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3801 /// EmitExceptionTable - Emit landing pads and actions.
3803 /// The general organization of the table is complex, but the basic concepts
3804 /// are easy. First there is a header which describes the location and
3805 /// organization of the three components that follow.
3806 /// 1. The landing pad site information describes the range of code covered
3807 /// by the try. In our case it's an accumulation of the ranges covered
3808 /// by the invokes in the try. There is also a reference to the landing
3809 /// pad that handles the exception once processed. Finally an index into
3810 /// the actions table.
3811 /// 2. The action table, in our case, is composed of pairs of type ids
3812 /// and next action offset. Starting with the action index from the
3813 /// landing pad site, each type Id is checked for a match to the current
3814 /// exception. If it matches then the exception and type id are passed
3815 /// on to the landing pad. Otherwise the next action is looked up. This
3816 /// chain is terminated with a next action of zero. If no type id is
3817 /// found the the frame is unwound and handling continues.
3818 /// 3. Type id table contains references to all the C++ typeinfo for all
3819 /// catches in the function. This tables is reversed indexed base 1.
3821 /// SharedTypeIds - How many leading type ids two landing pads have in common.
3822 static unsigned SharedTypeIds(const LandingPadInfo *L,
3823 const LandingPadInfo *R) {
3824 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3825 unsigned LSize = LIds.size(), RSize = RIds.size();
3826 unsigned MinSize = LSize < RSize ? LSize : RSize;
3827 unsigned Count = 0;
3829 for (; Count != MinSize; ++Count)
3830 if (LIds[Count] != RIds[Count])
3831 return Count;
3833 return Count;
3836 /// PadLT - Order landing pads lexicographically by type id.
3837 static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
3838 const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3839 unsigned LSize = LIds.size(), RSize = RIds.size();
3840 unsigned MinSize = LSize < RSize ? LSize : RSize;
3842 for (unsigned i = 0; i != MinSize; ++i)
3843 if (LIds[i] != RIds[i])
3844 return LIds[i] < RIds[i];
3846 return LSize < RSize;
3849 struct KeyInfo {
3850 static inline unsigned getEmptyKey() { return -1U; }
3851 static inline unsigned getTombstoneKey() { return -2U; }
3852 static unsigned getHashValue(const unsigned &Key) { return Key; }
3853 static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
3854 static bool isPod() { return true; }
3857 /// ActionEntry - Structure describing an entry in the actions table.
3858 struct ActionEntry {
3859 int ValueForTypeID; // The value to write - may not be equal to the type id.
3860 int NextAction;
3861 struct ActionEntry *Previous;
3864 /// PadRange - Structure holding a try-range and the associated landing pad.
3865 struct PadRange {
3866 // The index of the landing pad.
3867 unsigned PadIndex;
3868 // The index of the begin and end labels in the landing pad's label lists.
3869 unsigned RangeIndex;
3872 typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
3874 /// CallSiteEntry - Structure describing an entry in the call-site table.
3875 struct CallSiteEntry {
3876 // The 'try-range' is BeginLabel .. EndLabel.
3877 unsigned BeginLabel; // zero indicates the start of the function.
3878 unsigned EndLabel; // zero indicates the end of the function.
3879 // The landing pad starts at PadLabel.
3880 unsigned PadLabel; // zero indicates that there is no landing pad.
3881 unsigned Action;
3884 void EmitExceptionTable() {
3885 const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
3886 const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
3887 const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
3888 if (PadInfos.empty()) return;
3890 // Sort the landing pads in order of their type ids. This is used to fold
3891 // duplicate actions.
3892 SmallVector<const LandingPadInfo *, 64> LandingPads;
3893 LandingPads.reserve(PadInfos.size());
3894 for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
3895 LandingPads.push_back(&PadInfos[i]);
3896 std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
3898 // Negative type ids index into FilterIds, positive type ids index into
3899 // TypeInfos. The value written for a positive type id is just the type
3900 // id itself. For a negative type id, however, the value written is the
3901 // (negative) byte offset of the corresponding FilterIds entry. The byte
3902 // offset is usually equal to the type id, because the FilterIds entries
3903 // are written using a variable width encoding which outputs one byte per
3904 // entry as long as the value written is not too large, but can differ.
3905 // This kind of complication does not occur for positive type ids because
3906 // type infos are output using a fixed width encoding.
3907 // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
3908 SmallVector<int, 16> FilterOffsets;
3909 FilterOffsets.reserve(FilterIds.size());
3910 int Offset = -1;
3911 for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
3912 E = FilterIds.end(); I != E; ++I) {
3913 FilterOffsets.push_back(Offset);
3914 Offset -= TargetAsmInfo::getULEB128Size(*I);
3917 // Compute the actions table and gather the first action index for each
3918 // landing pad site.
3919 SmallVector<ActionEntry, 32> Actions;
3920 SmallVector<unsigned, 64> FirstActions;
3921 FirstActions.reserve(LandingPads.size());
3923 int FirstAction = 0;
3924 unsigned SizeActions = 0;
3925 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3926 const LandingPadInfo *LP = LandingPads[i];
3927 const std::vector<int> &TypeIds = LP->TypeIds;
3928 const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
3929 unsigned SizeSiteActions = 0;
3931 if (NumShared < TypeIds.size()) {
3932 unsigned SizeAction = 0;
3933 ActionEntry *PrevAction = 0;
3935 if (NumShared) {
3936 const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
3937 assert(Actions.size());
3938 PrevAction = &Actions.back();
3939 SizeAction = TargetAsmInfo::getSLEB128Size(PrevAction->NextAction) +
3940 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3941 for (unsigned j = NumShared; j != SizePrevIds; ++j) {
3942 SizeAction -=
3943 TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3944 SizeAction += -PrevAction->NextAction;
3945 PrevAction = PrevAction->Previous;
3949 // Compute the actions.
3950 for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
3951 int TypeID = TypeIds[I];
3952 assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
3953 int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
3954 unsigned SizeTypeID = TargetAsmInfo::getSLEB128Size(ValueForTypeID);
3956 int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
3957 SizeAction = SizeTypeID + TargetAsmInfo::getSLEB128Size(NextAction);
3958 SizeSiteActions += SizeAction;
3960 ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
3961 Actions.push_back(Action);
3963 PrevAction = &Actions.back();
3966 // Record the first action of the landing pad site.
3967 FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
3968 } // else identical - re-use previous FirstAction
3970 FirstActions.push_back(FirstAction);
3972 // Compute this sites contribution to size.
3973 SizeActions += SizeSiteActions;
3976 // Compute the call-site table. The entry for an invoke has a try-range
3977 // containing the call, a non-zero landing pad and an appropriate action.
3978 // The entry for an ordinary call has a try-range containing the call and
3979 // zero for the landing pad and the action. Calls marked 'nounwind' have
3980 // no entry and must not be contained in the try-range of any entry - they
3981 // form gaps in the table. Entries must be ordered by try-range address.
3982 SmallVector<CallSiteEntry, 64> CallSites;
3984 RangeMapType PadMap;
3985 // Invokes and nounwind calls have entries in PadMap (due to being bracketed
3986 // by try-range labels when lowered). Ordinary calls do not, so appropriate
3987 // try-ranges for them need be deduced.
3988 for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3989 const LandingPadInfo *LandingPad = LandingPads[i];
3990 for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
3991 unsigned BeginLabel = LandingPad->BeginLabels[j];
3992 assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
3993 PadRange P = { i, j };
3994 PadMap[BeginLabel] = P;
3998 // The end label of the previous invoke or nounwind try-range.
3999 unsigned LastLabel = 0;
4001 // Whether there is a potentially throwing instruction (currently this means
4002 // an ordinary call) between the end of the previous try-range and now.
4003 bool SawPotentiallyThrowing = false;
4005 // Whether the last callsite entry was for an invoke.
4006 bool PreviousIsInvoke = false;
4008 // Visit all instructions in order of address.
4009 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
4010 I != E; ++I) {
4011 for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
4012 MI != E; ++MI) {
4013 if (!MI->isLabel()) {
4014 SawPotentiallyThrowing |= MI->getDesc().isCall();
4015 continue;
4018 unsigned BeginLabel = MI->getOperand(0).getImm();
4019 assert(BeginLabel && "Invalid label!");
4021 // End of the previous try-range?
4022 if (BeginLabel == LastLabel)
4023 SawPotentiallyThrowing = false;
4025 // Beginning of a new try-range?
4026 RangeMapType::iterator L = PadMap.find(BeginLabel);
4027 if (L == PadMap.end())
4028 // Nope, it was just some random label.
4029 continue;
4031 PadRange P = L->second;
4032 const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
4034 assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
4035 "Inconsistent landing pad map!");
4037 // If some instruction between the previous try-range and this one may
4038 // throw, create a call-site entry with no landing pad for the region
4039 // between the try-ranges.
4040 if (SawPotentiallyThrowing) {
4041 CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
4042 CallSites.push_back(Site);
4043 PreviousIsInvoke = false;
4046 LastLabel = LandingPad->EndLabels[P.RangeIndex];
4047 assert(BeginLabel && LastLabel && "Invalid landing pad!");
4049 if (LandingPad->LandingPadLabel) {
4050 // This try-range is for an invoke.
4051 CallSiteEntry Site = {BeginLabel, LastLabel,
4052 LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
4054 // Try to merge with the previous call-site.
4055 if (PreviousIsInvoke) {
4056 CallSiteEntry &Prev = CallSites.back();
4057 if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
4058 // Extend the range of the previous entry.
4059 Prev.EndLabel = Site.EndLabel;
4060 continue;
4064 // Otherwise, create a new call-site.
4065 CallSites.push_back(Site);
4066 PreviousIsInvoke = true;
4067 } else {
4068 // Create a gap.
4069 PreviousIsInvoke = false;
4073 // If some instruction between the previous try-range and the end of the
4074 // function may throw, create a call-site entry with no landing pad for the
4075 // region following the try-range.
4076 if (SawPotentiallyThrowing) {
4077 CallSiteEntry Site = {LastLabel, 0, 0, 0};
4078 CallSites.push_back(Site);
4081 // Final tallies.
4083 // Call sites.
4084 const unsigned SiteStartSize = sizeof(int32_t); // DW_EH_PE_udata4
4085 const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
4086 const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
4087 unsigned SizeSites = CallSites.size() * (SiteStartSize +
4088 SiteLengthSize +
4089 LandingPadSize);
4090 for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
4091 SizeSites += TargetAsmInfo::getULEB128Size(CallSites[i].Action);
4093 // Type infos.
4094 const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
4095 unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
4097 unsigned TypeOffset = sizeof(int8_t) + // Call site format
4098 TargetAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
4099 SizeSites + SizeActions + SizeTypes;
4101 unsigned TotalSize = sizeof(int8_t) + // LPStart format
4102 sizeof(int8_t) + // TType format
4103 TargetAsmInfo::getULEB128Size(TypeOffset) + // TType base offset
4104 TypeOffset;
4106 unsigned SizeAlign = (4 - TotalSize) & 3;
4108 // Begin the exception table.
4109 Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
4110 Asm->EmitAlignment(2, 0, 0, false);
4111 O << "GCC_except_table" << SubprogramCount << ":\n";
4112 for (unsigned i = 0; i != SizeAlign; ++i) {
4113 Asm->EmitInt8(0);
4114 Asm->EOL("Padding");
4116 EmitLabel("exception", SubprogramCount);
4118 // Emit the header.
4119 Asm->EmitInt8(DW_EH_PE_omit);
4120 Asm->EOL("LPStart format (DW_EH_PE_omit)");
4121 Asm->EmitInt8(DW_EH_PE_absptr);
4122 Asm->EOL("TType format (DW_EH_PE_absptr)");
4123 Asm->EmitULEB128Bytes(TypeOffset);
4124 Asm->EOL("TType base offset");
4125 Asm->EmitInt8(DW_EH_PE_udata4);
4126 Asm->EOL("Call site format (DW_EH_PE_udata4)");
4127 Asm->EmitULEB128Bytes(SizeSites);
4128 Asm->EOL("Call-site table length");
4130 // Emit the landing pad site information.
4131 for (unsigned i = 0; i < CallSites.size(); ++i) {
4132 CallSiteEntry &S = CallSites[i];
4133 const char *BeginTag;
4134 unsigned BeginNumber;
4136 if (!S.BeginLabel) {
4137 BeginTag = "eh_func_begin";
4138 BeginNumber = SubprogramCount;
4139 } else {
4140 BeginTag = "label";
4141 BeginNumber = S.BeginLabel;
4144 EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
4145 true, true);
4146 Asm->EOL("Region start");
4148 if (!S.EndLabel) {
4149 EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
4150 true);
4151 } else {
4152 EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
4154 Asm->EOL("Region length");
4156 if (!S.PadLabel)
4157 Asm->EmitInt32(0);
4158 else
4159 EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
4160 true, true);
4161 Asm->EOL("Landing pad");
4163 Asm->EmitULEB128Bytes(S.Action);
4164 Asm->EOL("Action");
4167 // Emit the actions.
4168 for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
4169 ActionEntry &Action = Actions[I];
4171 Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
4172 Asm->EOL("TypeInfo index");
4173 Asm->EmitSLEB128Bytes(Action.NextAction);
4174 Asm->EOL("Next action");
4177 // Emit the type ids.
4178 for (unsigned M = TypeInfos.size(); M; --M) {
4179 GlobalVariable *GV = TypeInfos[M - 1];
4181 PrintRelDirective();
4183 if (GV) {
4184 std::string GLN;
4185 O << Asm->getGlobalLinkName(GV, GLN);
4186 } else {
4187 O << "0";
4190 Asm->EOL("TypeInfo");
4193 // Emit the filter typeids.
4194 for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
4195 unsigned TypeID = FilterIds[j];
4196 Asm->EmitULEB128Bytes(TypeID);
4197 Asm->EOL("Filter TypeInfo index");
4200 Asm->EmitAlignment(2, 0, 0, false);
4203 public:
4204 //===--------------------------------------------------------------------===//
4205 // Main entry points.
4207 DwarfException(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
4208 : Dwarf(OS, A, T, "eh"), shouldEmitTable(false), shouldEmitMoves(false),
4209 shouldEmitTableModule(false), shouldEmitMovesModule(false),
4210 ExceptionTimer(0) {
4211 if (TimePassesIsEnabled)
4212 ExceptionTimer = new Timer("Dwarf Exception Writer",
4213 getDwarfTimerGroup());
4216 virtual ~DwarfException() {
4217 delete ExceptionTimer;
4220 /// SetModuleInfo - Set machine module information when it's known that pass
4221 /// manager has created it. Set by the target AsmPrinter.
4222 void SetModuleInfo(MachineModuleInfo *mmi) {
4223 MMI = mmi;
4226 /// BeginModule - Emit all exception information that should come prior to the
4227 /// content.
4228 void BeginModule(Module *M) {
4229 this->M = M;
4232 /// EndModule - Emit all exception information that should come after the
4233 /// content.
4234 void EndModule() {
4235 if (TimePassesIsEnabled)
4236 ExceptionTimer->startTimer();
4238 if (shouldEmitMovesModule || shouldEmitTableModule) {
4239 const std::vector<Function *> Personalities = MMI->getPersonalities();
4240 for (unsigned i = 0; i < Personalities.size(); ++i)
4241 EmitCommonEHFrame(Personalities[i], i);
4243 for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
4244 E = EHFrames.end(); I != E; ++I)
4245 EmitEHFrame(*I);
4248 if (TimePassesIsEnabled)
4249 ExceptionTimer->stopTimer();
4252 /// BeginFunction - Gather pre-function exception information. Assumes being
4253 /// emitted immediately after the function entry point.
4254 void BeginFunction(MachineFunction *MF) {
4255 if (TimePassesIsEnabled)
4256 ExceptionTimer->startTimer();
4258 this->MF = MF;
4259 shouldEmitTable = shouldEmitMoves = false;
4261 if (MMI && TAI->doesSupportExceptionHandling()) {
4262 // Map all labels and get rid of any dead landing pads.
4263 MMI->TidyLandingPads();
4265 // If any landing pads survive, we need an EH table.
4266 if (MMI->getLandingPads().size())
4267 shouldEmitTable = true;
4269 // See if we need frame move info.
4270 if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
4271 shouldEmitMoves = true;
4273 if (shouldEmitMoves || shouldEmitTable)
4274 // Assumes in correct section after the entry point.
4275 EmitLabel("eh_func_begin", ++SubprogramCount);
4278 shouldEmitTableModule |= shouldEmitTable;
4279 shouldEmitMovesModule |= shouldEmitMoves;
4281 if (TimePassesIsEnabled)
4282 ExceptionTimer->stopTimer();
4285 /// EndFunction - Gather and emit post-function exception information.
4287 void EndFunction() {
4288 if (TimePassesIsEnabled)
4289 ExceptionTimer->startTimer();
4291 if (shouldEmitMoves || shouldEmitTable) {
4292 EmitLabel("eh_func_end", SubprogramCount);
4293 EmitExceptionTable();
4295 // Save EH frame information
4296 std::string Name;
4297 EHFrames.push_back(
4298 FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF, Name),
4299 SubprogramCount,
4300 MMI->getPersonalityIndex(),
4301 MF->getFrameInfo()->hasCalls(),
4302 !MMI->getLandingPads().empty(),
4303 MMI->getFrameMoves(),
4304 MF->getFunction()));
4307 if (TimePassesIsEnabled)
4308 ExceptionTimer->stopTimer();
4312 } // End of namespace llvm
4314 //===----------------------------------------------------------------------===//
4316 /// Emit - Print the abbreviation using the specified Dwarf writer.
4318 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
4319 // Emit its Dwarf tag type.
4320 DD.getAsm()->EmitULEB128Bytes(Tag);
4321 DD.getAsm()->EOL(TagString(Tag));
4323 // Emit whether it has children DIEs.
4324 DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
4325 DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
4327 // For each attribute description.
4328 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4329 const DIEAbbrevData &AttrData = Data[i];
4331 // Emit attribute type.
4332 DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
4333 DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
4335 // Emit form type.
4336 DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
4337 DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
4340 // Mark end of abbreviation.
4341 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
4342 DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
4345 #ifndef NDEBUG
4346 void DIEAbbrev::print(std::ostream &O) {
4347 O << "Abbreviation @"
4348 << std::hex << (intptr_t)this << std::dec
4349 << " "
4350 << TagString(Tag)
4351 << " "
4352 << ChildrenString(ChildrenFlag)
4353 << "\n";
4355 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4356 O << " "
4357 << AttributeString(Data[i].getAttribute())
4358 << " "
4359 << FormEncodingString(Data[i].getForm())
4360 << "\n";
4363 void DIEAbbrev::dump() { print(cerr); }
4364 #endif
4366 //===----------------------------------------------------------------------===//
4368 #ifndef NDEBUG
4369 void DIEValue::dump() {
4370 print(cerr);
4372 #endif
4374 //===----------------------------------------------------------------------===//
4376 /// EmitValue - Emit integer of appropriate size.
4378 void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
4379 switch (Form) {
4380 case DW_FORM_flag: // Fall thru
4381 case DW_FORM_ref1: // Fall thru
4382 case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer); break;
4383 case DW_FORM_ref2: // Fall thru
4384 case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer); break;
4385 case DW_FORM_ref4: // Fall thru
4386 case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer); break;
4387 case DW_FORM_ref8: // Fall thru
4388 case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer); break;
4389 case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
4390 case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
4391 default: assert(0 && "DIE Value form not supported yet"); break;
4395 /// SizeOf - Determine size of integer value in bytes.
4397 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4398 switch (Form) {
4399 case DW_FORM_flag: // Fall thru
4400 case DW_FORM_ref1: // Fall thru
4401 case DW_FORM_data1: return sizeof(int8_t);
4402 case DW_FORM_ref2: // Fall thru
4403 case DW_FORM_data2: return sizeof(int16_t);
4404 case DW_FORM_ref4: // Fall thru
4405 case DW_FORM_data4: return sizeof(int32_t);
4406 case DW_FORM_ref8: // Fall thru
4407 case DW_FORM_data8: return sizeof(int64_t);
4408 case DW_FORM_udata: return TargetAsmInfo::getULEB128Size(Integer);
4409 case DW_FORM_sdata: return TargetAsmInfo::getSLEB128Size(Integer);
4410 default: assert(0 && "DIE Value form not supported yet"); break;
4412 return 0;
4415 //===----------------------------------------------------------------------===//
4417 /// EmitValue - Emit string value.
4419 void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
4420 DD.getAsm()->EmitString(Str);
4423 //===----------------------------------------------------------------------===//
4425 /// EmitValue - Emit label value.
4427 void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4428 bool IsSmall = Form == DW_FORM_data4;
4429 DD.EmitReference(Label, false, IsSmall);
4432 /// SizeOf - Determine size of label value in bytes.
4434 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4435 if (Form == DW_FORM_data4) return 4;
4436 return DD.getTargetData()->getPointerSize();
4439 //===----------------------------------------------------------------------===//
4441 /// EmitValue - Emit label value.
4443 void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
4444 bool IsSmall = Form == DW_FORM_data4;
4445 DD.EmitReference(Label, false, IsSmall);
4448 /// SizeOf - Determine size of label value in bytes.
4450 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4451 if (Form == DW_FORM_data4) return 4;
4452 return DD.getTargetData()->getPointerSize();
4455 //===----------------------------------------------------------------------===//
4457 /// EmitValue - Emit delta value.
4459 void DIESectionOffset::EmitValue(DwarfDebug &DD, unsigned Form) {
4460 bool IsSmall = Form == DW_FORM_data4;
4461 DD.EmitSectionOffset(Label.Tag, Section.Tag,
4462 Label.Number, Section.Number, IsSmall, IsEH, UseSet);
4465 /// SizeOf - Determine size of delta value in bytes.
4467 unsigned DIESectionOffset::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4468 if (Form == DW_FORM_data4) return 4;
4469 return DD.getTargetData()->getPointerSize();
4472 //===----------------------------------------------------------------------===//
4474 /// EmitValue - Emit delta value.
4476 void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
4477 bool IsSmall = Form == DW_FORM_data4;
4478 DD.EmitDifference(LabelHi, LabelLo, IsSmall);
4481 /// SizeOf - Determine size of delta value in bytes.
4483 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4484 if (Form == DW_FORM_data4) return 4;
4485 return DD.getTargetData()->getPointerSize();
4488 //===----------------------------------------------------------------------===//
4490 /// EmitValue - Emit debug information entry offset.
4492 void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
4493 DD.getAsm()->EmitInt32(Entry->getOffset());
4496 //===----------------------------------------------------------------------===//
4498 /// ComputeSize - calculate the size of the block.
4500 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
4501 if (!Size) {
4502 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4504 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4505 Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
4508 return Size;
4511 /// EmitValue - Emit block data.
4513 void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
4514 switch (Form) {
4515 case DW_FORM_block1: DD.getAsm()->EmitInt8(Size); break;
4516 case DW_FORM_block2: DD.getAsm()->EmitInt16(Size); break;
4517 case DW_FORM_block4: DD.getAsm()->EmitInt32(Size); break;
4518 case DW_FORM_block: DD.getAsm()->EmitULEB128Bytes(Size); break;
4519 default: assert(0 && "Improper form for block"); break;
4522 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
4524 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
4525 DD.getAsm()->EOL();
4526 Values[i]->EmitValue(DD, AbbrevData[i].getForm());
4530 /// SizeOf - Determine size of block data in bytes.
4532 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
4533 switch (Form) {
4534 case DW_FORM_block1: return Size + sizeof(int8_t);
4535 case DW_FORM_block2: return Size + sizeof(int16_t);
4536 case DW_FORM_block4: return Size + sizeof(int32_t);
4537 case DW_FORM_block: return Size + TargetAsmInfo::getULEB128Size(Size);
4538 default: assert(0 && "Improper form for block"); break;
4540 return 0;
4543 //===----------------------------------------------------------------------===//
4544 /// DIE Implementation
4546 DIE::~DIE() {
4547 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4548 delete Children[i];
4551 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
4553 void DIE::AddSiblingOffset() {
4554 DIEInteger *DI = new DIEInteger(0);
4555 Values.insert(Values.begin(), DI);
4556 Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
4559 /// Profile - Used to gather unique data for the value folding set.
4561 void DIE::Profile(FoldingSetNodeID &ID) {
4562 Abbrev.Profile(ID);
4564 for (unsigned i = 0, N = Children.size(); i < N; ++i)
4565 ID.AddPointer(Children[i]);
4567 for (unsigned j = 0, M = Values.size(); j < M; ++j)
4568 ID.AddPointer(Values[j]);
4571 #ifndef NDEBUG
4572 void DIE::print(std::ostream &O, unsigned IncIndent) {
4573 static unsigned IndentCount = 0;
4574 IndentCount += IncIndent;
4575 const std::string Indent(IndentCount, ' ');
4576 bool isBlock = Abbrev.getTag() == 0;
4578 if (!isBlock) {
4579 O << Indent
4580 << "Die: "
4581 << "0x" << std::hex << (intptr_t)this << std::dec
4582 << ", Offset: " << Offset
4583 << ", Size: " << Size
4584 << "\n";
4586 O << Indent
4587 << TagString(Abbrev.getTag())
4588 << " "
4589 << ChildrenString(Abbrev.getChildrenFlag());
4590 } else {
4591 O << "Size: " << Size;
4593 O << "\n";
4595 const SmallVector<DIEAbbrevData, 8> &Data = Abbrev.getData();
4597 IndentCount += 2;
4598 for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4599 O << Indent;
4601 if (!isBlock)
4602 O << AttributeString(Data[i].getAttribute());
4603 else
4604 O << "Blk[" << i << "]";
4606 O << " "
4607 << FormEncodingString(Data[i].getForm())
4608 << " ";
4609 Values[i]->print(O);
4610 O << "\n";
4612 IndentCount -= 2;
4614 for (unsigned j = 0, M = Children.size(); j < M; ++j) {
4615 Children[j]->print(O, 4);
4618 if (!isBlock) O << "\n";
4619 IndentCount -= IncIndent;
4622 void DIE::dump() {
4623 print(cerr);
4625 #endif
4627 //===----------------------------------------------------------------------===//
4628 /// DwarfWriter Implementation
4631 DwarfWriter::DwarfWriter()
4632 : ImmutablePass(&ID), DD(0), DE(0) {}
4634 DwarfWriter::~DwarfWriter() {
4635 delete DE;
4636 delete DD;
4639 /// BeginModule - Emit all Dwarf sections that should come prior to the
4640 /// content.
4641 void DwarfWriter::BeginModule(Module *M,
4642 MachineModuleInfo *MMI,
4643 raw_ostream &OS, AsmPrinter *A,
4644 const TargetAsmInfo *T) {
4645 DE = new DwarfException(OS, A, T);
4646 DD = new DwarfDebug(OS, A, T);
4647 DE->BeginModule(M);
4648 DD->BeginModule(M);
4649 DD->SetDebugInfo(MMI);
4650 DE->SetModuleInfo(MMI);
4653 /// EndModule - Emit all Dwarf sections that should come after the content.
4655 void DwarfWriter::EndModule() {
4656 DE->EndModule();
4657 DD->EndModule();
4660 /// BeginFunction - Gather pre-function debug information. Assumes being
4661 /// emitted immediately after the function entry point.
4662 void DwarfWriter::BeginFunction(MachineFunction *MF) {
4663 DE->BeginFunction(MF);
4664 DD->BeginFunction(MF);
4667 /// EndFunction - Gather and emit post-function debug information.
4669 void DwarfWriter::EndFunction(MachineFunction *MF) {
4670 DD->EndFunction(MF);
4671 DE->EndFunction();
4673 if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI())
4674 // Clear function debug information.
4675 MMI->EndFunction();
4678 /// RecordSourceLine - Records location information and associates it with a
4679 /// label. Returns a unique label ID used to generate a label and provide
4680 /// correspondence to the source line list.
4681 unsigned DwarfWriter::RecordSourceLine(unsigned Line, unsigned Col,
4682 DICompileUnit CU) {
4683 return DD->RecordSourceLine(Line, Col, CU);
4686 /// RecordRegionStart - Indicate the start of a region.
4687 unsigned DwarfWriter::RecordRegionStart(GlobalVariable *V) {
4688 return DD->RecordRegionStart(V);
4691 /// RecordRegionEnd - Indicate the end of a region.
4692 unsigned DwarfWriter::RecordRegionEnd(GlobalVariable *V) {
4693 return DD->RecordRegionEnd(V);
4696 /// getRecordSourceLineCount - Count source lines.
4697 unsigned DwarfWriter::getRecordSourceLineCount() {
4698 return DD->getRecordSourceLineCount();
4701 /// RecordVariable - Indicate the declaration of a local variable.
4703 void DwarfWriter::RecordVariable(GlobalVariable *GV, unsigned FrameIndex,
4704 const MachineInstr *MI) {
4705 DD->RecordVariable(GV, FrameIndex, MI);
4708 /// ShouldEmitDwarfDebug - Returns true if Dwarf debugging declarations should
4709 /// be emitted.
4710 bool DwarfWriter::ShouldEmitDwarfDebug() const {
4711 return DD && DD->ShouldEmitDwarfDebug();
4714 //// RecordInlinedFnStart - Global variable GV is inlined at the location marked
4715 //// by LabelID label.
4716 void DwarfWriter::RecordInlinedFnStart(Instruction *I, DISubprogram &SP,
4717 unsigned LabelID, DICompileUnit CU,
4718 unsigned Line, unsigned Col) {
4719 DD->RecordInlinedFnStart(I, SP, LabelID, CU, Line, Col);
4722 /// RecordInlinedFnEnd - Indicate the end of inlined subroutine.
4723 unsigned DwarfWriter::RecordInlinedFnEnd(DISubprogram &SP) {
4724 return DD->RecordInlinedFnEnd(SP);
4727 /// RecordVariableScope - Record scope for the variable declared by
4728 /// DeclareMI. DeclareMI must describe TargetInstrInfo::DECLARE.
4729 void DwarfWriter::RecordVariableScope(DIVariable &DV,
4730 const MachineInstr *DeclareMI) {
4731 DD->RecordVariableScope(DV, DeclareMI);