Make comment names match function names.
[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/SetVector.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/StringMap.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 (getType().isArtificial())
163       return true;
164     return false;
165   }
166
167   bool isObjectPointer()             const {
168     if (Var.isObjectPointer())
169       return true;
170     if (getType().isObjectPointer())
171       return true;
172     return false;
173   }
174
175   bool variableHasComplexAddress()   const {
176     assert(Var.Verify() && "Invalid complex DbgVariable!");
177     return Var.hasComplexAddress();
178   }
179   bool isBlockByrefVariable()        const {
180     assert(Var.Verify() && "Invalid complex DbgVariable!");
181     return Var.isBlockByrefVariable();
182   }
183   unsigned getNumAddrElements()      const {
184     assert(Var.Verify() && "Invalid complex DbgVariable!");
185     return Var.getNumAddrElements();
186   }
187   uint64_t getAddrElement(unsigned i) const {
188     return Var.getAddrElement(i);
189   }
190   DIType getType() const;
191 };
192
193 class DwarfDebug {
194   /// Asm - Target of Dwarf emission.
195   AsmPrinter *Asm;
196
197   /// MMI - Collected machine module information.
198   MachineModuleInfo *MMI;
199
200   /// DIEValueAllocator - All DIEValues are allocated through this allocator.
201   BumpPtrAllocator DIEValueAllocator;
202
203   //===--------------------------------------------------------------------===//
204   // Attributes used to construct specific Dwarf sections.
205   //
206
207   CompileUnit *FirstCU;
208
209   /// Maps MDNode with its corresponding CompileUnit.
210   DenseMap <const MDNode *, CompileUnit *> CUMap;
211
212   /// Maps subprogram MDNode with its corresponding CompileUnit.
213   DenseMap <const MDNode *, CompileUnit *> SPMap;
214
215   /// AbbreviationsSet - Used to uniquely define abbreviations.
216   ///
217   FoldingSet<DIEAbbrev> AbbreviationsSet;
218
219   /// Abbreviations - A list of all the unique abbreviations in use.
220   ///
221   std::vector<DIEAbbrev *> Abbreviations;
222
223   /// SourceIdMap - Source id map, i.e. pair of source filename and directory,
224   /// separated by a zero byte, mapped to a unique id.
225   StringMap<unsigned, BumpPtrAllocator&> SourceIdMap;
226
227   /// StringPool - A String->Symbol mapping of strings used by indirect
228   /// references.
229   StringMap<std::pair<MCSymbol*, unsigned>, BumpPtrAllocator&> StringPool;
230   unsigned NextStringPoolNumber;
231
232   /// SectionMap - Provides a unique id per text section.
233   ///
234   SetVector<const MCSection*> SectionMap;
235
236   /// CurrentFnArguments - List of Arguments (DbgValues) for current function.
237   SmallVector<DbgVariable *, 8> CurrentFnArguments;
238
239   LexicalScopes LScopes;
240
241   /// AbstractSPDies - Collection of abstract subprogram DIEs.
242   DenseMap<const MDNode *, DIE *> AbstractSPDies;
243
244   /// ScopeVariables - Collection of dbg variables of a scope.
245   DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> > ScopeVariables;
246
247   /// AbstractVariables - Collection of abstract variables.
248   DenseMap<const MDNode *, DbgVariable *> AbstractVariables;
249
250   /// DotDebugLocEntries - Collection of DotDebugLocEntry.
251   SmallVector<DotDebugLocEntry, 4> DotDebugLocEntries;
252
253   /// InlinedSubprogramDIEs - Collection of subprogram DIEs that are marked
254   /// (at the end of the module) as DW_AT_inline.
255   SmallPtrSet<DIE *, 4> InlinedSubprogramDIEs;
256
257   /// InlineInfo - Keep track of inlined functions and their location.  This
258   /// information is used to populate the debug_inlined section.
259   typedef std::pair<const MCSymbol *, DIE *> InlineInfoLabels;
260   DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> > InlineInfo;
261   SmallVector<const MDNode *, 4> InlinedSPNodes;
262
263   // ProcessedSPNodes - This is a collection of subprogram MDNodes that
264   // are processed to create DIEs.
265   SmallPtrSet<const MDNode *, 16> ProcessedSPNodes;
266
267   /// LabelsBeforeInsn - Maps instruction with label emitted before
268   /// instruction.
269   DenseMap<const MachineInstr *, MCSymbol *> LabelsBeforeInsn;
270
271   /// LabelsAfterInsn - Maps instruction with label emitted after
272   /// instruction.
273   DenseMap<const MachineInstr *, MCSymbol *> LabelsAfterInsn;
274
275   /// UserVariables - Every user variable mentioned by a DBG_VALUE instruction
276   /// in order of appearance.
277   SmallVector<const MDNode*, 8> UserVariables;
278
279   /// DbgValues - For each user variable, keep a list of DBG_VALUE
280   /// instructions in order. The list can also contain normal instructions that
281   /// clobber the previous DBG_VALUE.
282   typedef DenseMap<const MDNode*, SmallVector<const MachineInstr*, 4> >
283     DbgValueHistoryMap;
284   DbgValueHistoryMap DbgValues;
285
286   SmallVector<const MCSymbol *, 8> DebugRangeSymbols;
287
288   /// Previous instruction's location information. This is used to determine
289   /// label location to indicate scope boundries in dwarf debug info.
290   DebugLoc PrevInstLoc;
291   MCSymbol *PrevLabel;
292
293   /// PrologEndLoc - This location indicates end of function prologue and
294   /// beginning of function body.
295   DebugLoc PrologEndLoc;
296
297   struct FunctionDebugFrameInfo {
298     unsigned Number;
299     std::vector<MachineMove> Moves;
300
301     FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M)
302       : Number(Num), Moves(M) {}
303   };
304
305   std::vector<FunctionDebugFrameInfo> DebugFrames;
306
307   // Section Symbols: these are assembler temporary labels that are emitted at
308   // the beginning of each supported dwarf section.  These are used to form
309   // section offsets and are created by EmitSectionLabels.
310   MCSymbol *DwarfInfoSectionSym, *DwarfAbbrevSectionSym;
311   MCSymbol *DwarfStrSectionSym, *TextSectionSym, *DwarfDebugRangeSectionSym;
312   MCSymbol *DwarfDebugLocSectionSym;
313   MCSymbol *FunctionBeginSym, *FunctionEndSym;
314
315   // As an optimization, there is no need to emit an entry in the directory
316   // table for the same directory as DW_at_comp_dir.
317   StringRef CompilationDir;
318
319   // Holders for the various debug information flags that we might need to
320   // have exposed. See accessor functions below for description.
321   bool IsDarwinGDBCompat;
322   bool HasDwarfAccelTables;
323   bool HasDwarfFission;
324 private:
325
326   /// assignAbbrevNumber - Define a unique number for the abbreviation.
327   ///
328   void assignAbbrevNumber(DIEAbbrev &Abbrev);
329
330   void addScopeVariable(LexicalScope *LS, DbgVariable *Var);
331
332   /// findAbstractVariable - Find abstract variable associated with Var.
333   DbgVariable *findAbstractVariable(DIVariable &Var, DebugLoc Loc);
334
335   /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
336   /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
337   /// If there are global variables in this scope then create and insert
338   /// DIEs for these variables.
339   DIE *updateSubprogramScopeDIE(CompileUnit *SPCU, const MDNode *SPNode);
340
341   /// constructLexicalScope - Construct new DW_TAG_lexical_block
342   /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
343   DIE *constructLexicalScopeDIE(CompileUnit *TheCU, LexicalScope *Scope);
344
345   /// constructInlinedScopeDIE - This scope represents inlined body of
346   /// a function. Construct DIE to represent this concrete inlined copy
347   /// of the function.
348   DIE *constructInlinedScopeDIE(CompileUnit *TheCU, LexicalScope *Scope);
349
350   /// constructScopeDIE - Construct a DIE for this scope.
351   DIE *constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope);
352
353   /// emitSectionLabels - Emit initial Dwarf sections with a label at
354   /// the start of each one.
355   void emitSectionLabels();
356
357   /// emitDIE - Recursively Emits a debug information entry.
358   ///
359   void emitDIE(DIE *Die);
360
361   /// computeSizeAndOffset - Compute the size and offset of a DIE given
362   /// an incoming Offset.
363   ///
364   unsigned computeSizeAndOffset(DIE *Die, unsigned Offset);
365
366   /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
367   ///
368   void computeSizeAndOffsets();
369
370   /// computeInlinedDIEs - Attach DW_AT_inline attribute with inlined
371   /// subprogram DIEs.
372   void computeInlinedDIEs();
373
374   /// collectDeadVariables - Collect info for variables that were optimized out.
375   void collectDeadVariables();
376
377   /// finalizeModuleInfo - Finish off debug information after all functions
378   /// have been processed.
379   void finalizeModuleInfo();
380
381   /// endSections - Emit labels to close any remaining sections that have
382   /// been left open.
383   void endSections();
384
385   /// emitDebugInfo - Emit the debug info section.
386   ///
387   void emitDebugInfo();
388
389   /// emitAbbreviations - Emit the abbreviation section.
390   ///
391   void emitAbbreviations();
392
393   /// emitEndOfLineMatrix - Emit the last address of the section and the end of
394   /// the line matrix.
395   ///
396   void emitEndOfLineMatrix(unsigned SectionEnd);
397
398   /// emitAccelNames - Emit visible names into a hashed accelerator table
399   /// section.
400   void emitAccelNames();
401
402   /// emitAccelObjC - Emit objective C classes and categories into a hashed
403   /// accelerator table section.
404   void emitAccelObjC();
405
406   /// emitAccelNamespace - Emit namespace dies into a hashed accelerator
407   /// table.
408   void emitAccelNamespaces();
409
410   /// emitAccelTypes() - Emit type dies into a hashed accelerator table.
411   ///
412   void emitAccelTypes();
413
414   /// emitDebugPubTypes - Emit visible types into a debug pubtypes section.
415   ///
416   void emitDebugPubTypes();
417
418   /// emitDebugStr - Emit visible names into a debug str section.
419   ///
420   void emitDebugStr();
421
422   /// emitDebugLoc - Emit visible names into a debug loc section.
423   ///
424   void emitDebugLoc();
425
426   /// emitDebugARanges - Emit visible names into a debug aranges section.
427   ///
428   void emitDebugARanges();
429
430   /// emitDebugRanges - Emit visible names into a debug ranges section.
431   ///
432   void emitDebugRanges();
433
434   /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
435   ///
436   void emitDebugMacInfo();
437
438   /// emitDebugInlineInfo - Emit inline info using following format.
439   /// Section Header:
440   /// 1. length of section
441   /// 2. Dwarf version number
442   /// 3. address size.
443   ///
444   /// Entries (one "entry" for each function that was inlined):
445   ///
446   /// 1. offset into __debug_str section for MIPS linkage name, if exists;
447   ///   otherwise offset into __debug_str for regular function name.
448   /// 2. offset into __debug_str section for regular function name.
449   /// 3. an unsigned LEB128 number indicating the number of distinct inlining
450   /// instances for the function.
451   ///
452   /// The rest of the entry consists of a {die_offset, low_pc} pair for each
453   /// inlined instance; the die_offset points to the inlined_subroutine die in
454   /// the __debug_info section, and the low_pc is the starting address for the
455   /// inlining instance.
456   void emitDebugInlineInfo();
457
458   /// constructCompileUnit - Create new CompileUnit for the given
459   /// metadata node with tag DW_TAG_compile_unit.
460   CompileUnit *constructCompileUnit(const MDNode *N);
461
462   /// construct SubprogramDIE - Construct subprogram DIE.
463   void constructSubprogramDIE(CompileUnit *TheCU, const MDNode *N);
464
465   /// recordSourceLine - Register a source line with debug info. Returns the
466   /// unique label that was emitted and which provides correspondence to
467   /// the source line list.
468   void recordSourceLine(unsigned Line, unsigned Col, const MDNode *Scope,
469                         unsigned Flags);
470
471   /// identifyScopeMarkers() - Indentify instructions that are marking the
472   /// beginning of or ending of a scope.
473   void identifyScopeMarkers();
474
475   /// addCurrentFnArgument - If Var is an current function argument that add
476   /// it in CurrentFnArguments list.
477   bool addCurrentFnArgument(const MachineFunction *MF,
478                             DbgVariable *Var, LexicalScope *Scope);
479
480   /// collectVariableInfo - Populate LexicalScope entries with variables' info.
481   void collectVariableInfo(const MachineFunction *,
482                            SmallPtrSet<const MDNode *, 16> &ProcessedVars);
483
484   /// collectVariableInfoFromMMITable - Collect variable information from
485   /// side table maintained by MMI.
486   void collectVariableInfoFromMMITable(const MachineFunction * MF,
487                                        SmallPtrSet<const MDNode *, 16> &P);
488
489   /// requestLabelBeforeInsn - Ensure that a label will be emitted before MI.
490   void requestLabelBeforeInsn(const MachineInstr *MI) {
491     LabelsBeforeInsn.insert(std::make_pair(MI, (MCSymbol*)0));
492   }
493
494   /// getLabelBeforeInsn - Return Label preceding the instruction.
495   const MCSymbol *getLabelBeforeInsn(const MachineInstr *MI);
496
497   /// requestLabelAfterInsn - Ensure that a label will be emitted after MI.
498   void requestLabelAfterInsn(const MachineInstr *MI) {
499     LabelsAfterInsn.insert(std::make_pair(MI, (MCSymbol*)0));
500   }
501
502   /// getLabelAfterInsn - Return Label immediately following the instruction.
503   const MCSymbol *getLabelAfterInsn(const MachineInstr *MI);
504
505 public:
506   //===--------------------------------------------------------------------===//
507   // Main entry points.
508   //
509   DwarfDebug(AsmPrinter *A, Module *M);
510   ~DwarfDebug();
511
512   /// collectInfoFromNamedMDNodes - Collect debug info from named mdnodes such
513   /// as llvm.dbg.enum and llvm.dbg.ty
514   void collectInfoFromNamedMDNodes(const Module *M);
515
516   /// collectLegacyDebugInfo - Collect debug info using DebugInfoFinder.
517   /// FIXME - Remove this when DragonEgg switches to DIBuilder.
518   bool collectLegacyDebugInfo(const Module *M);
519
520   /// beginModule - Emit all Dwarf sections that should come prior to the
521   /// content.
522   void beginModule();
523
524   /// endModule - Emit all Dwarf sections that should come after the content.
525   ///
526   void endModule();
527
528   /// beginFunction - Gather pre-function debug information.  Assumes being
529   /// emitted immediately after the function entry point.
530   void beginFunction(const MachineFunction *MF);
531
532   /// endFunction - Gather and emit post-function debug information.
533   ///
534   void endFunction(const MachineFunction *MF);
535
536   /// beginInstruction - Process beginning of an instruction.
537   void beginInstruction(const MachineInstr *MI);
538
539   /// endInstruction - Prcess end of an instruction.
540   void endInstruction(const MachineInstr *MI);
541
542   /// getOrCreateSourceID - Look up the source id with the given directory and
543   /// source file names. If none currently exists, create a new id and insert it
544   /// in the SourceIds map.
545   unsigned getOrCreateSourceID(StringRef DirName, StringRef FullName);
546
547   /// getStringPool - returns the entry into the start of the pool.
548   MCSymbol *getStringPool();
549
550   /// getStringPoolEntry - returns an entry into the string pool with the given
551   /// string text.
552   MCSymbol *getStringPoolEntry(StringRef Str);
553
554   /// useDarwinGDBCompat - returns whether or not to limit some of our debug
555   /// output to the limitations of darwin gdb.
556   bool useDarwinGDBCompat() { return IsDarwinGDBCompat; }
557
558   // Experimental DWARF5 features.
559
560   /// useDwarfAccelTables - returns whether or not to emit tables that
561   /// dwarf consumers can use to accelerate lookup.
562   bool useDwarfAccelTables() { return HasDwarfAccelTables; }
563
564   /// useDwarfFission - returns whether or not to change the current debug
565   /// info for the fission proposal support.
566   bool useDwarfFission() { return HasDwarfFission; }
567 };
568 } // End of namespace llvm
569
570 #endif