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