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