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