DwarfDebug.h revision 024170f859112518adb5796060607574bf1e6015
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#include <map>
30
31namespace llvm {
32
33class CompileUnit;
34class DbgConcreteScope;
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  /// mapped to a unique id.
213  std::map<std::pair<std::string, std::string>, 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  MCSymbol *getStringPoolEntry(StringRef Str);
221
222  /// SectionMap - Provides a unique id per text section.
223  ///
224  UniqueVector<const MCSection*> SectionMap;
225
226  /// CurrentFnArguments - List of Arguments (DbgValues) for current function.
227  SmallVector<DbgVariable *, 8> CurrentFnArguments;
228
229  LexicalScopes LScopes;
230
231  /// AbstractSPDies - Collection of abstract subprogram DIEs.
232  DenseMap<const MDNode *, DIE *> AbstractSPDies;
233
234  /// ScopeVariables - Collection of dbg variables of a scope.
235  DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> > ScopeVariables;
236
237  /// AbstractVariables - Collection on abstract variables.
238  DenseMap<const MDNode *, DbgVariable *> AbstractVariables;
239
240  /// DotDebugLocEntries - Collection of DotDebugLocEntry.
241  SmallVector<DotDebugLocEntry, 4> DotDebugLocEntries;
242
243  /// InlinedSubprogramDIEs - Collection of subprgram DIEs that are marked
244  /// (at the end of the module) as DW_AT_inline.
245  SmallPtrSet<DIE *, 4> InlinedSubprogramDIEs;
246
247  /// InlineInfo - Keep track of inlined functions and their location.  This
248  /// information is used to populate debug_inlined section.
249  typedef std::pair<const MCSymbol *, DIE *> InlineInfoLabels;
250  DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> > InlineInfo;
251  SmallVector<const MDNode *, 4> InlinedSPNodes;
252
253  // ProcessedSPNodes - This is a collection of subprogram MDNodes that
254  // are processed to create DIEs.
255  SmallPtrSet<const MDNode *, 16> ProcessedSPNodes;
256
257  /// LabelsBeforeInsn - Maps instruction with label emitted before
258  /// instruction.
259  DenseMap<const MachineInstr *, MCSymbol *> LabelsBeforeInsn;
260
261  /// LabelsAfterInsn - Maps instruction with label emitted after
262  /// instruction.
263  DenseMap<const MachineInstr *, MCSymbol *> LabelsAfterInsn;
264
265  /// UserVariables - Every user variable mentioned by a DBG_VALUE instruction
266  /// in order of appearance.
267  SmallVector<const MDNode*, 8> UserVariables;
268
269  /// DbgValues - For each user variable, keep a list of DBG_VALUE
270  /// instructions in order. The list can also contain normal instructions that
271  /// clobber the previous DBG_VALUE.
272  typedef DenseMap<const MDNode*, SmallVector<const MachineInstr*, 4> >
273    DbgValueHistoryMap;
274  DbgValueHistoryMap DbgValues;
275
276  SmallVector<const MCSymbol *, 8> DebugRangeSymbols;
277
278  /// Previous instruction's location information. This is used to determine
279  /// label location to indicate scope boundries in dwarf debug info.
280  DebugLoc PrevInstLoc;
281  MCSymbol *PrevLabel;
282
283  /// PrologEndLoc - This location indicates end of function prologue and
284  /// beginning of function body.
285  DebugLoc PrologEndLoc;
286
287  struct FunctionDebugFrameInfo {
288    unsigned Number;
289    std::vector<MachineMove> Moves;
290
291    FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M)
292      : Number(Num), Moves(M) {}
293  };
294
295  std::vector<FunctionDebugFrameInfo> DebugFrames;
296
297  // DIEValueAllocator - All DIEValues are allocated through this allocator.
298  BumpPtrAllocator DIEValueAllocator;
299
300  // Section Symbols: these are assembler temporary labels that are emitted at
301  // the beginning of each supported dwarf section.  These are used to form
302  // section offsets and are created by EmitSectionLabels.
303  MCSymbol *DwarfInfoSectionSym, *DwarfAbbrevSectionSym;
304  MCSymbol *DwarfStrSectionSym, *TextSectionSym, *DwarfDebugRangeSectionSym;
305  MCSymbol *DwarfDebugLocSectionSym;
306  MCSymbol *FunctionBeginSym, *FunctionEndSym;
307
308private:
309
310  /// assignAbbrevNumber - Define a unique number for the abbreviation.
311  ///
312  void assignAbbrevNumber(DIEAbbrev &Abbrev);
313
314  void addScopeVariable(LexicalScope *LS, DbgVariable *Var);
315
316  /// findAbstractVariable - Find abstract variable associated with Var.
317  DbgVariable *findAbstractVariable(DIVariable &Var, DebugLoc Loc);
318
319  /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
320  /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
321  /// If there are global variables in this scope then create and insert
322  /// DIEs for these variables.
323  DIE *updateSubprogramScopeDIE(CompileUnit *SPCU, const MDNode *SPNode);
324
325  /// constructLexicalScope - Construct new DW_TAG_lexical_block
326  /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
327  DIE *constructLexicalScopeDIE(CompileUnit *TheCU, LexicalScope *Scope);
328
329  /// constructInlinedScopeDIE - This scope represents inlined body of
330  /// a function. Construct DIE to represent this concrete inlined copy
331  /// of the function.
332  DIE *constructInlinedScopeDIE(CompileUnit *TheCU, LexicalScope *Scope);
333
334  /// constructVariableDIE - Construct a DIE for the given DbgVariable.
335  DIE *constructVariableDIE(DbgVariable *DV, LexicalScope *S);
336
337  /// constructScopeDIE - Construct a DIE for this scope.
338  DIE *constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope);
339
340  /// EmitSectionLabels - Emit initial Dwarf sections with a label at
341  /// the start of each one.
342  void EmitSectionLabels();
343
344  /// emitDIE - Recursively Emits a debug information entry.
345  ///
346  void emitDIE(DIE *Die);
347
348  /// computeSizeAndOffset - Compute the size and offset of a DIE.
349  ///
350  unsigned computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last);
351
352  /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
353  ///
354  void computeSizeAndOffsets();
355
356  /// EmitDebugInfo - Emit the debug info section.
357  ///
358  void emitDebugInfo();
359
360  /// emitAbbreviations - Emit the abbreviation section.
361  ///
362  void emitAbbreviations() const;
363
364  /// emitEndOfLineMatrix - Emit the last address of the section and the end of
365  /// the line matrix.
366  ///
367  void emitEndOfLineMatrix(unsigned SectionEnd);
368
369  /// emitDebugPubNames - Emit visible names into a debug pubnames section.
370  ///
371  void emitDebugPubNames();
372
373  /// emitDebugPubTypes - Emit visible types into a debug pubtypes section.
374  ///
375  void emitDebugPubTypes();
376
377  /// emitDebugStr - Emit visible names into a debug str section.
378  ///
379  void emitDebugStr();
380
381  /// emitDebugLoc - Emit visible names into a debug loc section.
382  ///
383  void emitDebugLoc();
384
385  /// EmitDebugARanges - Emit visible names into a debug aranges section.
386  ///
387  void EmitDebugARanges();
388
389  /// emitDebugRanges - Emit visible names into a debug ranges section.
390  ///
391  void emitDebugRanges();
392
393  /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
394  ///
395  void emitDebugMacInfo();
396
397  /// emitDebugInlineInfo - Emit inline info using following format.
398  /// Section Header:
399  /// 1. length of section
400  /// 2. Dwarf version number
401  /// 3. address size.
402  ///
403  /// Entries (one "entry" for each function that was inlined):
404  ///
405  /// 1. offset into __debug_str section for MIPS linkage name, if exists;
406  ///   otherwise offset into __debug_str for regular function name.
407  /// 2. offset into __debug_str section for regular function name.
408  /// 3. an unsigned LEB128 number indicating the number of distinct inlining
409  /// instances for the function.
410  ///
411  /// The rest of the entry consists of a {die_offset, low_pc} pair for each
412  /// inlined instance; the die_offset points to the inlined_subroutine die in
413  /// the __debug_info section, and the low_pc is the starting address for the
414  /// inlining instance.
415  void emitDebugInlineInfo();
416
417  /// constructCompileUnit - Create new CompileUnit for the given
418  /// metadata node with tag DW_TAG_compile_unit.
419  CompileUnit *constructCompileUnit(const MDNode *N);
420
421  /// construct SubprogramDIE - Construct subprogram DIE.
422  void constructSubprogramDIE(CompileUnit *TheCU, const MDNode *N);
423
424  /// recordSourceLine - Register a source line with debug info. Returns the
425  /// unique label that was emitted and which provides correspondence to
426  /// the source line list.
427  void recordSourceLine(unsigned Line, unsigned Col, const MDNode *Scope,
428                        unsigned Flags);
429
430  /// identifyScopeMarkers() - Indentify instructions that are marking the
431  /// beginning of or ending of a scope.
432  void identifyScopeMarkers();
433
434  /// addCurrentFnArgument - If Var is an current function argument that add
435  /// it in CurrentFnArguments list.
436  bool addCurrentFnArgument(const MachineFunction *MF,
437                            DbgVariable *Var, LexicalScope *Scope);
438
439  /// collectVariableInfo - Populate LexicalScope entries with variables' info.
440  void collectVariableInfo(const MachineFunction *,
441                           SmallPtrSet<const MDNode *, 16> &ProcessedVars);
442
443  /// collectVariableInfoFromMMITable - Collect variable information from
444  /// side table maintained by MMI.
445  void collectVariableInfoFromMMITable(const MachineFunction * MF,
446                                       SmallPtrSet<const MDNode *, 16> &P);
447
448  /// requestLabelBeforeInsn - Ensure that a label will be emitted before MI.
449  void requestLabelBeforeInsn(const MachineInstr *MI) {
450    LabelsBeforeInsn.insert(std::make_pair(MI, (MCSymbol*)0));
451  }
452
453  /// getLabelBeforeInsn - Return Label preceding the instruction.
454  const MCSymbol *getLabelBeforeInsn(const MachineInstr *MI);
455
456  /// requestLabelAfterInsn - Ensure that a label will be emitted after MI.
457  void requestLabelAfterInsn(const MachineInstr *MI) {
458    LabelsAfterInsn.insert(std::make_pair(MI, (MCSymbol*)0));
459  }
460
461  /// getLabelAfterInsn - Return Label immediately following the instruction.
462  const MCSymbol *getLabelAfterInsn(const MachineInstr *MI);
463
464public:
465  //===--------------------------------------------------------------------===//
466  // Main entry points.
467  //
468  DwarfDebug(AsmPrinter *A, Module *M);
469  ~DwarfDebug();
470
471  /// collectInfoFromNamedMDNodes - Collect debug info from named mdnodes such
472  /// as llvm.dbg.enum and llvm.dbg.ty
473  void collectInfoFromNamedMDNodes(Module *M);
474
475  /// collectLegacyDebugInfo - Collect debug info using DebugInfoFinder.
476  /// FIXME - Remove this when DragonEgg switches to DIBuilder.
477  bool collectLegacyDebugInfo(Module *M);
478
479  /// beginModule - Emit all Dwarf sections that should come prior to the
480  /// content.
481  void beginModule(Module *M);
482
483  /// endModule - Emit all Dwarf sections that should come after the content.
484  ///
485  void endModule();
486
487  /// beginFunction - Gather pre-function debug information.  Assumes being
488  /// emitted immediately after the function entry point.
489  void beginFunction(const MachineFunction *MF);
490
491  /// endFunction - Gather and emit post-function debug information.
492  ///
493  void endFunction(const MachineFunction *MF);
494
495  /// beginInstruction - Process beginning of an instruction.
496  void beginInstruction(const MachineInstr *MI);
497
498  /// endInstruction - Prcess end of an instruction.
499  void endInstruction(const MachineInstr *MI);
500
501  /// GetOrCreateSourceID - Look up the source id with the given directory and
502  /// source file names. If none currently exists, create a new id and insert it
503  /// in the SourceIds map.
504  unsigned GetOrCreateSourceID(StringRef DirName, StringRef FullName);
505
506  /// createSubprogramDIE - Create new DIE using SP.
507  DIE *createSubprogramDIE(DISubprogram SP);
508};
509} // End of namespace llvm
510
511#endif
512