Refactor. A subprogram is part of compile unit so let CompileUnit construct new subpr...
[oota-llvm.git] / lib / CodeGen / AsmPrinter / DwarfDebug.h
1 //===-- llvm/CodeGen/DwarfDebug.h - Dwarf Debug 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 debug info into asm files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef CODEGEN_ASMPRINTER_DWARFDEBUG_H__
15 #define CODEGEN_ASMPRINTER_DWARFDEBUG_H__
16
17 #include "llvm/CodeGen/AsmPrinter.h"
18 #include "llvm/CodeGen/LexicalScopes.h"
19 #include "llvm/MC/MachineLocation.h"
20 #include "llvm/Analysis/DebugInfo.h"
21 #include "DIE.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/FoldingSet.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/StringMap.h"
26 #include "llvm/ADT/UniqueVector.h"
27 #include "llvm/Support/Allocator.h"
28 #include "llvm/Support/DebugLoc.h"
29
30 namespace llvm {
31
32 class CompileUnit;
33 class DbgConcreteScope;
34 class DbgVariable;
35 class MachineFrameInfo;
36 class MachineModuleInfo;
37 class MachineOperand;
38 class MCAsmInfo;
39 class DIEAbbrev;
40 class DIE;
41 class DIEBlock;
42 class DIEEntry;
43
44 //===----------------------------------------------------------------------===//
45 /// SrcLineInfo - This class is used to record source line correspondence.
46 ///
47 class SrcLineInfo {
48   unsigned Line;                     // Source line number.
49   unsigned Column;                   // Source column.
50   unsigned SourceID;                 // Source ID number.
51   MCSymbol *Label;                   // Label in code ID number.
52 public:
53   SrcLineInfo(unsigned L, unsigned C, unsigned S, MCSymbol *label)
54     : Line(L), Column(C), SourceID(S), Label(label) {}
55
56   // Accessors
57   unsigned getLine() const { return Line; }
58   unsigned getColumn() const { return Column; }
59   unsigned getSourceID() const { return SourceID; }
60   MCSymbol *getLabel() const { return Label; }
61 };
62
63 /// DotDebugLocEntry - This struct describes location entries emitted in
64 /// .debug_loc section.
65 typedef struct DotDebugLocEntry {
66   const MCSymbol *Begin;
67   const MCSymbol *End;
68   MachineLocation Loc;
69   const MDNode *Variable;
70   bool Merged;
71   bool Constant;
72   enum EntryType {
73     E_Location,
74     E_Integer,
75     E_ConstantFP,
76     E_ConstantInt
77   };
78   enum EntryType EntryKind;
79
80   union {
81     int64_t Int;
82     const ConstantFP *CFP;
83     const ConstantInt *CIP;
84   } Constants;
85   DotDebugLocEntry() 
86     : Begin(0), End(0), Variable(0), Merged(false), 
87       Constant(false) { Constants.Int = 0;}
88   DotDebugLocEntry(const MCSymbol *B, const MCSymbol *E, MachineLocation &L,
89                    const MDNode *V) 
90     : Begin(B), End(E), Loc(L), Variable(V), Merged(false), 
91       Constant(false) { Constants.Int = 0; EntryKind = E_Location; }
92   DotDebugLocEntry(const MCSymbol *B, const MCSymbol *E, int64_t i)
93     : Begin(B), End(E), Variable(0), Merged(false), 
94       Constant(true) { Constants.Int = i; EntryKind = E_Integer; }
95   DotDebugLocEntry(const MCSymbol *B, const MCSymbol *E, const ConstantFP *FPtr)
96     : Begin(B), End(E), Variable(0), Merged(false), 
97       Constant(true) { Constants.CFP = FPtr; EntryKind = E_ConstantFP; }
98   DotDebugLocEntry(const MCSymbol *B, const MCSymbol *E, const ConstantInt *IPtr)
99     : Begin(B), End(E), Variable(0), Merged(false), 
100       Constant(true) { Constants.CIP = IPtr; EntryKind = E_ConstantInt; }
101
102   /// Empty entries are also used as a trigger to emit temp label. Such
103   /// labels are referenced is used to find debug_loc offset for a given DIE.
104   bool isEmpty() { return Begin == 0 && End == 0; }
105   bool isMerged() { return Merged; }
106   void Merge(DotDebugLocEntry *Next) {
107     if (!(Begin && Loc == Next->Loc && End == Next->Begin))
108       return;
109     Next->Begin = Begin;
110     Merged = true;
111   }
112   bool isLocation() const    { return EntryKind == E_Location; }
113   bool isInt() const         { return EntryKind == E_Integer; }
114   bool isConstantFP() const  { return EntryKind == E_ConstantFP; }
115   bool isConstantInt() const { return EntryKind == E_ConstantInt; }
116   int64_t getInt()                    { return Constants.Int; }
117   const ConstantFP *getConstantFP()   { return Constants.CFP; }
118   const ConstantInt *getConstantInt() { return Constants.CIP; }
119 } DotDebugLocEntry;
120
121 //===----------------------------------------------------------------------===//
122 /// DbgVariable - This class is used to track local variable information.
123 ///
124 class DbgVariable {
125   DIVariable Var;                    // Variable Descriptor.
126   DIE *TheDIE;                       // Variable DIE.
127   unsigned DotDebugLocOffset;        // Offset in DotDebugLocEntries.
128 public:
129   // AbsVar may be NULL.
130   DbgVariable(DIVariable V) : Var(V), TheDIE(0), DotDebugLocOffset(~0U) {}
131
132   // Accessors.
133   DIVariable getVariable()           const { return Var; }
134   void setDIE(DIE *D)                      { TheDIE = D; }
135   DIE *getDIE()                      const { return TheDIE; }
136   void setDotDebugLocOffset(unsigned O)    { DotDebugLocOffset = O; }
137   unsigned getDotDebugLocOffset()    const { return DotDebugLocOffset; }
138   StringRef getName()                const { return Var.getName(); }
139   unsigned getTag()                  const { return Var.getTag(); }
140   bool variableHasComplexAddress()   const {
141     assert(Var.Verify() && "Invalid complex DbgVariable!");
142     return Var.hasComplexAddress();
143   }
144   bool isBlockByrefVariable()        const {
145     assert(Var.Verify() && "Invalid complex DbgVariable!");
146     return Var.isBlockByrefVariable();
147   }
148   unsigned getNumAddrElements()      const { 
149     assert(Var.Verify() && "Invalid complex DbgVariable!");
150     return Var.getNumAddrElements();
151   }
152   uint64_t getAddrElement(unsigned i) const {
153     return Var.getAddrElement(i);
154   }
155   DIType getType() const;
156 };
157
158 class DwarfDebug {
159   /// Asm - Target of Dwarf emission.
160   AsmPrinter *Asm;
161
162   /// MMI - Collected machine module information.
163   MachineModuleInfo *MMI;
164
165   //===--------------------------------------------------------------------===//
166   // Attributes used to construct specific Dwarf sections.
167   //
168
169   CompileUnit *FirstCU;
170   DenseMap <const MDNode *, CompileUnit *> CUMap;
171
172   /// AbbreviationsSet - Used to uniquely define abbreviations.
173   ///
174   FoldingSet<DIEAbbrev> AbbreviationsSet;
175
176   /// Abbreviations - A list of all the unique abbreviations in use.
177   ///
178   std::vector<DIEAbbrev *> Abbreviations;
179
180   /// SourceIdMap - Source id map, i.e. pair of directory id and source file
181   /// id mapped to a unique id.
182   StringMap<unsigned> SourceIdMap;
183
184   /// StringPool - A String->Symbol mapping of strings used by indirect
185   /// references.
186   StringMap<std::pair<MCSymbol*, unsigned> > StringPool;
187   unsigned NextStringPoolNumber;
188   
189   MCSymbol *getStringPoolEntry(StringRef Str);
190
191   /// SectionMap - Provides a unique id per text section.
192   ///
193   UniqueVector<const MCSection*> SectionMap;
194
195   /// CurrentFnArguments - List of Arguments (DbgValues) for current function.
196   SmallVector<DbgVariable *, 8> CurrentFnArguments;
197
198   LexicalScopes LScopes;
199
200   /// AbstractSPDies - Collection of abstract subprogram DIEs.
201   DenseMap<const MDNode *, DIE *> AbstractSPDies;
202
203   /// ScopeVariables - Collection of dbg variables of a scope.
204   DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> > ScopeVariables;
205
206   /// AbstractVariables - Collection on abstract variables.
207   DenseMap<const MDNode *, DbgVariable *> AbstractVariables;
208
209   /// DbgVariableToFrameIndexMap - Tracks frame index used to find 
210   /// variable's value.
211   DenseMap<const DbgVariable *, int> DbgVariableToFrameIndexMap;
212
213   /// DbgVariableToDbgInstMap - Maps DbgVariable to corresponding DBG_VALUE
214   /// machine instruction.
215   DenseMap<const DbgVariable *, const MachineInstr *> DbgVariableToDbgInstMap;
216
217   /// DotDebugLocEntries - Collection of DotDebugLocEntry.
218   SmallVector<DotDebugLocEntry, 4> DotDebugLocEntries;
219
220   /// UseDotDebugLocEntry - DW_AT_location attributes for the DIEs in this set
221   /// idetifies corresponding .debug_loc entry offset.
222   SmallPtrSet<const DIE *, 4> UseDotDebugLocEntry;
223
224   /// VarToAbstractVarMap - Maps DbgVariable with corresponding Abstract
225   /// DbgVariable, if any.
226   DenseMap<const DbgVariable *, const DbgVariable *> VarToAbstractVarMap;
227
228   /// InliendSubprogramDIEs - Collection of subprgram DIEs that are marked
229   /// (at the end of the module) as DW_AT_inline.
230   SmallPtrSet<DIE *, 4> InlinedSubprogramDIEs;
231
232   /// InlineInfo - Keep track of inlined functions and their location.  This
233   /// information is used to populate debug_inlined section.
234   typedef std::pair<const MCSymbol *, DIE *> InlineInfoLabels;
235   DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> > InlineInfo;
236   SmallVector<const MDNode *, 4> InlinedSPNodes;
237
238   // ProcessedSPNodes - This is a collection of subprogram MDNodes that
239   // are processed to create DIEs.
240   SmallPtrSet<const MDNode *, 16> ProcessedSPNodes;
241
242   /// LabelsBeforeInsn - Maps instruction with label emitted before 
243   /// instruction.
244   DenseMap<const MachineInstr *, MCSymbol *> LabelsBeforeInsn;
245
246   /// LabelsAfterInsn - Maps instruction with label emitted after
247   /// instruction.
248   DenseMap<const MachineInstr *, MCSymbol *> LabelsAfterInsn;
249
250   /// UserVariables - Every user variable mentioned by a DBG_VALUE instruction
251   /// in order of appearance.
252   SmallVector<const MDNode*, 8> UserVariables;
253
254   /// DbgValues - For each user variable, keep a list of DBG_VALUE
255   /// instructions in order. The list can also contain normal instructions that
256   /// clobber the previous DBG_VALUE.
257   typedef DenseMap<const MDNode*, SmallVector<const MachineInstr*, 4> >
258     DbgValueHistoryMap;
259   DbgValueHistoryMap DbgValues;
260
261   SmallVector<const MCSymbol *, 8> DebugRangeSymbols;
262
263   /// Previous instruction's location information. This is used to determine
264   /// label location to indicate scope boundries in dwarf debug info.
265   DebugLoc PrevInstLoc;
266   MCSymbol *PrevLabel;
267
268   /// PrologEndLoc - This location indicates end of function prologue and
269   /// beginning of function body.
270   DebugLoc PrologEndLoc;
271
272   struct FunctionDebugFrameInfo {
273     unsigned Number;
274     std::vector<MachineMove> Moves;
275
276     FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M)
277       : Number(Num), Moves(M) {}
278   };
279
280   std::vector<FunctionDebugFrameInfo> DebugFrames;
281
282   // DIEValueAllocator - All DIEValues are allocated through this allocator.
283   BumpPtrAllocator DIEValueAllocator;
284
285   // Section Symbols: these are assembler temporary labels that are emitted at
286   // the beginning of each supported dwarf section.  These are used to form
287   // section offsets and are created by EmitSectionLabels.
288   MCSymbol *DwarfInfoSectionSym, *DwarfAbbrevSectionSym;
289   MCSymbol *DwarfStrSectionSym, *TextSectionSym, *DwarfDebugRangeSectionSym;
290   MCSymbol *DwarfDebugLocSectionSym;
291   MCSymbol *FunctionBeginSym, *FunctionEndSym;
292
293 private:
294
295   /// assignAbbrevNumber - Define a unique number for the abbreviation.
296   ///
297   void assignAbbrevNumber(DIEAbbrev &Abbrev);
298
299   void addScopeVariable(LexicalScope *LS, DbgVariable *Var);
300
301   /// findAbstractVariable - Find abstract variable associated with Var.
302   DbgVariable *findAbstractVariable(DIVariable &Var, DebugLoc Loc);
303
304   /// updateSubprogramScopeDIE - Find DIE for the given subprogram and 
305   /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
306   /// If there are global variables in this scope then create and insert
307   /// DIEs for these variables.
308   DIE *updateSubprogramScopeDIE(const MDNode *SPNode);
309
310   /// constructLexicalScope - Construct new DW_TAG_lexical_block 
311   /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
312   DIE *constructLexicalScopeDIE(LexicalScope *Scope);
313
314   /// constructInlinedScopeDIE - This scope represents inlined body of
315   /// a function. Construct DIE to represent this concrete inlined copy
316   /// of the function.
317   DIE *constructInlinedScopeDIE(LexicalScope *Scope);
318
319   /// constructVariableDIE - Construct a DIE for the given DbgVariable.
320   DIE *constructVariableDIE(DbgVariable *DV, LexicalScope *S);
321
322   /// constructScopeDIE - Construct a DIE for this scope.
323   DIE *constructScopeDIE(LexicalScope *Scope);
324
325   /// EmitSectionLabels - Emit initial Dwarf sections with a label at
326   /// the start of each one.
327   void EmitSectionLabels();
328
329   /// emitDIE - Recusively Emits a debug information entry.
330   ///
331   void emitDIE(DIE *Die);
332
333   /// computeSizeAndOffset - Compute the size and offset of a DIE.
334   ///
335   unsigned computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last);
336
337   /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
338   ///
339   void computeSizeAndOffsets();
340
341   /// EmitDebugInfo - Emit the debug info section.
342   ///
343   void emitDebugInfo();
344
345   /// emitAbbreviations - Emit the abbreviation section.
346   ///
347   void emitAbbreviations() const;
348
349   /// emitEndOfLineMatrix - Emit the last address of the section and the end of
350   /// the line matrix.
351   ///
352   void emitEndOfLineMatrix(unsigned SectionEnd);
353
354   /// emitDebugPubNames - Emit visible names into a debug pubnames section.
355   ///
356   void emitDebugPubNames();
357
358   /// emitDebugPubTypes - Emit visible types into a debug pubtypes section.
359   ///
360   void emitDebugPubTypes();
361
362   /// emitDebugStr - Emit visible names into a debug str section.
363   ///
364   void emitDebugStr();
365
366   /// emitDebugLoc - Emit visible names into a debug loc section.
367   ///
368   void emitDebugLoc();
369
370   /// EmitDebugARanges - Emit visible names into a debug aranges section.
371   ///
372   void EmitDebugARanges();
373
374   /// emitDebugRanges - Emit visible names into a debug ranges section.
375   ///
376   void emitDebugRanges();
377
378   /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
379   ///
380   void emitDebugMacInfo();
381
382   /// emitDebugInlineInfo - Emit inline info using following format.
383   /// Section Header:
384   /// 1. length of section
385   /// 2. Dwarf version number
386   /// 3. address size.
387   ///
388   /// Entries (one "entry" for each function that was inlined):
389   ///
390   /// 1. offset into __debug_str section for MIPS linkage name, if exists; 
391   ///   otherwise offset into __debug_str for regular function name.
392   /// 2. offset into __debug_str section for regular function name.
393   /// 3. an unsigned LEB128 number indicating the number of distinct inlining 
394   /// instances for the function.
395   /// 
396   /// The rest of the entry consists of a {die_offset, low_pc}  pair for each 
397   /// inlined instance; the die_offset points to the inlined_subroutine die in
398   /// the __debug_info section, and the low_pc is the starting address  for the
399   ///  inlining instance.
400   void emitDebugInlineInfo();
401
402   /// constructCompileUnit - Create new CompileUnit for the given 
403   /// metadata node with tag DW_TAG_compile_unit.
404   void constructCompileUnit(const MDNode *N);
405
406   /// getCompielUnit - Get CompileUnit DIE.
407   CompileUnit *getCompileUnit(const MDNode *N) const;
408
409   /// constructGlobalVariableDIE - Construct global variable DIE.
410   void constructGlobalVariableDIE(const MDNode *N);
411
412   /// construct SubprogramDIE - Construct subprogram DIE.
413   void constructSubprogramDIE(const MDNode *N);
414
415   /// recordSourceLine - Register a source line with debug info. Returns the
416   /// unique label that was emitted and which provides correspondence to
417   /// the source line list.
418   void recordSourceLine(unsigned Line, unsigned Col, const MDNode *Scope,
419                         unsigned Flags);
420   
421   /// recordVariableFrameIndex - Record a variable's index.
422   void recordVariableFrameIndex(const DbgVariable *V, int Index);
423
424   /// findVariableFrameIndex - Return true if frame index for the variable
425   /// is found. Update FI to hold value of the index.
426   bool findVariableFrameIndex(const DbgVariable *V, int *FI);
427
428   /// identifyScopeMarkers() - Indentify instructions that are marking
429   /// beginning of or end of a scope.
430   void identifyScopeMarkers();
431
432   /// addCurrentFnArgument - If Var is an current function argument that add
433   /// it in CurrentFnArguments list.
434   bool addCurrentFnArgument(const MachineFunction *MF,
435                             DbgVariable *Var, LexicalScope *Scope);
436
437   /// collectVariableInfo - Populate LexicalScope entries with variables' info.
438   void collectVariableInfo(const MachineFunction *,
439                            SmallPtrSet<const MDNode *, 16> &ProcessedVars);
440   
441   /// collectVariableInfoFromMMITable - Collect variable information from
442   /// side table maintained by MMI.
443   void collectVariableInfoFromMMITable(const MachineFunction * MF,
444                                        SmallPtrSet<const MDNode *, 16> &P);
445
446   /// requestLabelBeforeInsn - Ensure that a label will be emitted before MI.
447   void requestLabelBeforeInsn(const MachineInstr *MI) {
448     LabelsBeforeInsn.insert(std::make_pair(MI, (MCSymbol*)0));
449   }
450
451   /// getLabelBeforeInsn - Return Label preceding the instruction.
452   const MCSymbol *getLabelBeforeInsn(const MachineInstr *MI);
453
454   /// requestLabelAfterInsn - Ensure that a label will be emitted after MI.
455   void requestLabelAfterInsn(const MachineInstr *MI) {
456     LabelsAfterInsn.insert(std::make_pair(MI, (MCSymbol*)0));
457   }
458
459   /// getLabelAfterInsn - Return Label immediately following the instruction.
460   const MCSymbol *getLabelAfterInsn(const MachineInstr *MI);
461
462 public:
463   //===--------------------------------------------------------------------===//
464   // Main entry points.
465   //
466   DwarfDebug(AsmPrinter *A, Module *M);
467   ~DwarfDebug();
468
469   /// beginModule - Emit all Dwarf sections that should come prior to the
470   /// content.
471   void beginModule(Module *M);
472
473   /// endModule - Emit all Dwarf sections that should come after the content.
474   ///
475   void endModule();
476
477   /// beginFunction - Gather pre-function debug information.  Assumes being
478   /// emitted immediately after the function entry point.
479   void beginFunction(const MachineFunction *MF);
480
481   /// endFunction - Gather and emit post-function debug information.
482   ///
483   void endFunction(const MachineFunction *MF);
484
485   /// beginInstruction - Process beginning of an instruction.
486   void beginInstruction(const MachineInstr *MI);
487
488   /// endInstruction - Prcess end of an instruction.
489   void endInstruction(const MachineInstr *MI);
490
491   /// GetOrCreateSourceID - Look up the source id with the given directory and
492   /// source file names. If none currently exists, create a new id and insert it
493   /// in the SourceIds map.
494   unsigned GetOrCreateSourceID(StringRef DirName, StringRef FullName);
495
496   /// createSubprogramDIE - Create new DIE using SP.
497   DIE *createSubprogramDIE(DISubprogram SP);
498 };
499 } // End of namespace llvm
500
501 #endif