Reland 196270 "Generalize debug info / EH emission in AsmPrinter"
[oota-llvm.git] / include / llvm / CodeGen / AsmPrinter.h
1 //===-- llvm/CodeGen/AsmPrinter.h - AsmPrinter 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 a class to be used as the base class for target specific
11 // asm writers.  This class primarily handles common functionality used by
12 // all asm writers.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_CODEGEN_ASMPRINTER_H
17 #define LLVM_CODEGEN_ASMPRINTER_H
18
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/IR/InlineAsm.h"
21 #include "llvm/Support/DataTypes.h"
22 #include "llvm/Support/ErrorHandling.h"
23
24 namespace llvm {
25   class AsmPrinterHandler;
26   class BlockAddress;
27   class GCStrategy;
28   class Constant;
29   class ConstantArray;
30   class GCMetadataPrinter;
31   class GlobalValue;
32   class GlobalVariable;
33   class MachineBasicBlock;
34   class MachineFunction;
35   class MachineInstr;
36   class MachineLocation;
37   class MachineLoopInfo;
38   class MachineLoop;
39   class MachineConstantPoolValue;
40   class MachineJumpTableInfo;
41   class MachineModuleInfo;
42   class MCAsmInfo;
43   class MCCFIInstruction;
44   class MCContext;
45   class MCInstrInfo;
46   class MCSection;
47   class MCStreamer;
48   class MCSymbol;
49   class MDNode;
50   class DwarfDebug;
51   class DwarfException;
52   class Mangler;
53   class TargetLoweringObjectFile;
54   class DataLayout;
55   class TargetMachine;
56
57   /// AsmPrinter - This class is intended to be used as a driving class for all
58   /// asm writers.
59   class AsmPrinter : public MachineFunctionPass {
60   public:
61     /// Target machine description.
62     ///
63     TargetMachine &TM;
64
65     /// Target Asm Printer information.
66     ///
67     const MCAsmInfo *MAI;
68
69     const MCInstrInfo *MII;
70     /// OutContext - This is the context for the output file that we are
71     /// streaming.  This owns all of the global MC-related objects for the
72     /// generated translation unit.
73     MCContext &OutContext;
74
75     /// OutStreamer - This is the MCStreamer object for the file we are
76     /// generating.  This contains the transient state for the current
77     /// translation unit that we are generating (such as the current section
78     /// etc).
79     MCStreamer &OutStreamer;
80
81     /// The current machine function.
82     const MachineFunction *MF;
83
84     /// MMI - This is a pointer to the current MachineModuleInfo.
85     MachineModuleInfo *MMI;
86
87     /// Name-mangler for global names.
88     ///
89     Mangler *Mang;
90
91     /// The symbol for the current function. This is recalculated at the
92     /// beginning of each call to runOnMachineFunction().
93     ///
94     MCSymbol *CurrentFnSym;
95
96     /// The symbol used to represent the start of the current function for the
97     /// purpose of calculating its size (e.g. using the .size directive). By
98     /// default, this is equal to CurrentFnSym.
99     MCSymbol *CurrentFnSymForSize;
100
101   private:
102     // GCMetadataPrinters - The garbage collection metadata printer table.
103     void *GCMetadataPrinters;  // Really a DenseMap.
104
105     /// VerboseAsm - Emit comments in assembly output if this is true.
106     ///
107     bool VerboseAsm;
108     static char ID;
109
110     /// If VerboseAsm is set, a pointer to the loop info for this
111     /// function.
112     MachineLoopInfo *LI;
113
114     struct HandlerInfo {
115       AsmPrinterHandler *Handler;
116       const char *TimerName, *TimerGroupName;
117       HandlerInfo(AsmPrinterHandler *Handler, const char *TimerName,
118                   const char *TimerGroupName)
119           : Handler(Handler), TimerName(TimerName),
120             TimerGroupName(TimerGroupName) {}
121     };
122     /// Handlers - a vector of all debug/EH info emitters we should use.
123     /// This vector maintains ownership of the emitters.
124     SmallVector<HandlerInfo, 1> Handlers;
125
126     /// DD - If the target supports dwarf debug info, this pointer is non-null.
127     DwarfDebug *DD;
128
129   protected:
130     explicit AsmPrinter(TargetMachine &TM, MCStreamer &Streamer);
131
132   public:
133     virtual ~AsmPrinter();
134
135     const DwarfDebug *getDwarfDebug() const { return DD; }
136
137     /// isVerbose - Return true if assembly output should contain comments.
138     ///
139     bool isVerbose() const { return VerboseAsm; }
140
141     /// getFunctionNumber - Return a unique ID for the current function.
142     ///
143     unsigned getFunctionNumber() const;
144
145     /// getObjFileLowering - Return information about object file lowering.
146     const TargetLoweringObjectFile &getObjFileLowering() const;
147
148     /// getDataLayout - Return information about data layout.
149     const DataLayout &getDataLayout() const;
150
151     /// getTargetTriple - Return the target triple string.
152     StringRef getTargetTriple() const;
153
154     /// getCurrentSection() - Return the current section we are emitting to.
155     const MCSection *getCurrentSection() const;
156
157     MCSymbol *getSymbol(const GlobalValue *GV) const;
158
159     //===------------------------------------------------------------------===//
160     // MachineFunctionPass Implementation.
161     //===------------------------------------------------------------------===//
162
163     /// getAnalysisUsage - Record analysis usage.
164     ///
165     void getAnalysisUsage(AnalysisUsage &AU) const;
166
167     /// doInitialization - Set up the AsmPrinter when we are working on a new
168     /// module.  If your pass overrides this, it must make sure to explicitly
169     /// call this implementation.
170     bool doInitialization(Module &M);
171
172     /// doFinalization - Shut down the asmprinter.  If you override this in your
173     /// pass, you must make sure to call it explicitly.
174     bool doFinalization(Module &M);
175
176     /// runOnMachineFunction - Emit the specified function out to the
177     /// OutStreamer.
178     virtual bool runOnMachineFunction(MachineFunction &MF) {
179       SetupMachineFunction(MF);
180       EmitFunctionHeader();
181       EmitFunctionBody();
182       return false;
183     }
184
185     //===------------------------------------------------------------------===//
186     // Coarse grained IR lowering routines.
187     //===------------------------------------------------------------------===//
188
189     /// SetupMachineFunction - This should be called when a new MachineFunction
190     /// is being processed from runOnMachineFunction.
191     void SetupMachineFunction(MachineFunction &MF);
192
193     /// EmitFunctionHeader - This method emits the header for the current
194     /// function.
195     void EmitFunctionHeader();
196
197     /// EmitFunctionBody - This method emits the body and trailer for a
198     /// function.
199     void EmitFunctionBody();
200
201     void emitPrologLabel(const MachineInstr &MI);
202
203     enum CFIMoveType {
204       CFI_M_None,
205       CFI_M_EH,
206       CFI_M_Debug
207     };
208     CFIMoveType needsCFIMoves();
209
210     bool needsSEHMoves();
211
212     /// needsRelocationsForDwarfStringPool - Specifies whether the object format
213     /// expects to use relocations to refer to debug entries. Alternatively we
214     /// emit section offsets in bytes from the start of the string pool.
215     bool needsRelocationsForDwarfStringPool() const;
216
217     /// EmitConstantPool - Print to the current output stream assembly
218     /// representations of the constants in the constant pool MCP. This is
219     /// used to print out constants which have been "spilled to memory" by
220     /// the code generator.
221     ///
222     virtual void EmitConstantPool();
223
224     /// EmitJumpTableInfo - Print assembly representations of the jump tables
225     /// used by the current function to the current output stream.
226     ///
227     void EmitJumpTableInfo();
228
229     /// EmitGlobalVariable - Emit the specified global variable to the .s file.
230     virtual void EmitGlobalVariable(const GlobalVariable *GV);
231
232     /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
233     /// special global used by LLVM.  If so, emit it and return true, otherwise
234     /// do nothing and return false.
235     bool EmitSpecialLLVMGlobal(const GlobalVariable *GV);
236
237     /// EmitAlignment - Emit an alignment directive to the specified power of
238     /// two boundary.  For example, if you pass in 3 here, you will get an 8
239     /// byte alignment.  If a global value is specified, and if that global has
240     /// an explicit alignment requested, it will override the alignment request
241     /// if required for correctness.
242     ///
243     void EmitAlignment(unsigned NumBits, const GlobalValue *GV = 0) const;
244
245     /// EmitBasicBlockStart - This method prints the label for the specified
246     /// MachineBasicBlock, an alignment (if present) and a comment describing
247     /// it if appropriate.
248     void EmitBasicBlockStart(const MachineBasicBlock *MBB) const;
249
250     /// \brief Print a general LLVM constant to the .s file.
251     void EmitGlobalConstant(const Constant *CV);
252
253
254     //===------------------------------------------------------------------===//
255     // Overridable Hooks
256     //===------------------------------------------------------------------===//
257
258     // Targets can, or in the case of EmitInstruction, must implement these to
259     // customize output.
260
261     /// EmitStartOfAsmFile - This virtual method can be overridden by targets
262     /// that want to emit something at the start of their file.
263     virtual void EmitStartOfAsmFile(Module &) {}
264
265     /// EmitEndOfAsmFile - This virtual method can be overridden by targets that
266     /// want to emit something at the end of their file.
267     virtual void EmitEndOfAsmFile(Module &) {}
268
269     /// EmitFunctionBodyStart - Targets can override this to emit stuff before
270     /// the first basic block in the function.
271     virtual void EmitFunctionBodyStart() {}
272
273     /// EmitFunctionBodyEnd - Targets can override this to emit stuff after
274     /// the last basic block in the function.
275     virtual void EmitFunctionBodyEnd() {}
276
277     /// EmitInstruction - Targets should implement this to emit instructions.
278     virtual void EmitInstruction(const MachineInstr *) {
279       llvm_unreachable("EmitInstruction not implemented");
280     }
281
282     virtual void EmitFunctionEntryLabel();
283
284     virtual void EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV);
285
286     /// EmitXXStructor - Targets can override this to change how global
287     /// constants that are part of a C++ static/global constructor list are
288     /// emitted.
289     virtual void EmitXXStructor(const Constant *CV) {
290       EmitGlobalConstant(CV);
291     }
292
293     /// isBlockOnlyReachableByFallthough - Return true if the basic block has
294     /// exactly one predecessor and the control transfer mechanism between
295     /// the predecessor and this block is a fall-through.
296     virtual bool
297     isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const;
298
299     /// emitImplicitDef - Targets can override this to customize the output of
300     /// IMPLICIT_DEF instructions in verbose mode.
301     virtual void emitImplicitDef(const MachineInstr *MI) const;
302
303     //===------------------------------------------------------------------===//
304     // Symbol Lowering Routines.
305     //===------------------------------------------------------------------===//
306   public:
307
308     /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
309     /// temporary label with the specified stem and unique ID.
310     MCSymbol *GetTempSymbol(StringRef Name, unsigned ID) const;
311
312     /// GetTempSymbol - Return an assembler temporary label with the specified
313     /// stem.
314     MCSymbol *GetTempSymbol(StringRef Name) const;
315
316     /// Return the MCSymbol for a private symbol with global value name as its
317     /// base, with the specified suffix.
318     MCSymbol *getSymbolWithGlobalValueBase(const GlobalValue *GV,
319                                            StringRef Suffix) const;
320
321     /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
322     /// ExternalSymbol.
323     MCSymbol *GetExternalSymbolSymbol(StringRef Sym) const;
324
325     /// GetCPISymbol - Return the symbol for the specified constant pool entry.
326     MCSymbol *GetCPISymbol(unsigned CPID) const;
327
328     /// GetJTISymbol - Return the symbol for the specified jump table entry.
329     MCSymbol *GetJTISymbol(unsigned JTID, bool isLinkerPrivate = false) const;
330
331     /// GetJTSetSymbol - Return the symbol for the specified jump table .set
332     /// FIXME: privatize to AsmPrinter.
333     MCSymbol *GetJTSetSymbol(unsigned UID, unsigned MBBID) const;
334
335     /// GetBlockAddressSymbol - Return the MCSymbol used to satisfy BlockAddress
336     /// uses of the specified basic block.
337     MCSymbol *GetBlockAddressSymbol(const BlockAddress *BA) const;
338     MCSymbol *GetBlockAddressSymbol(const BasicBlock *BB) const;
339
340     //===------------------------------------------------------------------===//
341     // Emission Helper Routines.
342     //===------------------------------------------------------------------===//
343   public:
344     /// printOffset - This is just convenient handler for printing offsets.
345     void printOffset(int64_t Offset, raw_ostream &OS) const;
346
347     /// EmitInt8 - Emit a byte directive and value.
348     ///
349     void EmitInt8(int Value) const;
350
351     /// EmitInt16 - Emit a short directive and value.
352     ///
353     void EmitInt16(int Value) const;
354
355     /// EmitInt32 - Emit a long directive and value.
356     ///
357     void EmitInt32(int Value) const;
358
359     /// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
360     /// in bytes of the directive is specified by Size and Hi/Lo specify the
361     /// labels.  This implicitly uses .set if it is available.
362     void EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
363                              unsigned Size) const;
364
365     /// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
366     /// where the size in bytes of the directive is specified by Size and Hi/Lo
367     /// specify the labels.  This implicitly uses .set if it is available.
368     void EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
369                                    const MCSymbol *Lo, unsigned Size) const;
370
371     /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
372     /// where the size in bytes of the directive is specified by Size and Label
373     /// specifies the label.  This implicitly uses .set if it is available.
374     void EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
375                              unsigned Size,
376                              bool IsSectionRelative = false) const;
377
378     /// EmitLabelReference - Emit something like ".long Label"
379     /// where the size in bytes of the directive is specified by Size and Label
380     /// specifies the label.
381     void EmitLabelReference(const MCSymbol *Label, unsigned Size,
382                             bool IsSectionRelative = false) const {
383       EmitLabelPlusOffset(Label, 0, Size, IsSectionRelative);
384     }
385
386     //===------------------------------------------------------------------===//
387     // Dwarf Emission Helper Routines
388     //===------------------------------------------------------------------===//
389
390     /// EmitSLEB128 - emit the specified signed leb128 value.
391     void EmitSLEB128(int64_t Value, const char *Desc = 0) const;
392
393     /// EmitULEB128 - emit the specified unsigned leb128 value.
394     void EmitULEB128(uint64_t Value, const char *Desc = 0,
395                      unsigned PadTo = 0) const;
396
397     /// EmitCFAByte - Emit a .byte 42 directive for a DW_CFA_xxx value.
398     void EmitCFAByte(unsigned Val) const;
399
400     /// EmitEncodingByte - Emit a .byte 42 directive that corresponds to an
401     /// encoding.  If verbose assembly output is enabled, we output comments
402     /// describing the encoding.  Desc is a string saying what the encoding is
403     /// specifying (e.g. "LSDA").
404     void EmitEncodingByte(unsigned Val, const char *Desc = 0) const;
405
406     /// GetSizeOfEncodedValue - Return the size of the encoding in bytes.
407     unsigned GetSizeOfEncodedValue(unsigned Encoding) const;
408
409     /// EmitReference - Emit reference to a ttype global with a specified encoding.
410     void EmitTTypeReference(const GlobalValue *GV, unsigned Encoding) const;
411
412     /// EmitSectionOffset - Emit the 4-byte offset of Label from the start of
413     /// its section.  This can be done with a special directive if the target
414     /// supports it (e.g. cygwin) or by emitting it as an offset from a label at
415     /// the start of the section.
416     ///
417     /// SectionLabel is a temporary label emitted at the start of the section
418     /// that Label lives in.
419     void EmitSectionOffset(const MCSymbol *Label,
420                            const MCSymbol *SectionLabel) const;
421
422     /// getISAEncoding - Get the value for DW_AT_APPLE_isa. Zero if no isa
423     /// encoding specified.
424     virtual unsigned getISAEncoding() { return 0; }
425
426     /// EmitDwarfRegOp - Emit dwarf register operation.
427     virtual void EmitDwarfRegOp(const MachineLocation &MLoc,
428                                 bool Indirect) const;
429
430     //===------------------------------------------------------------------===//
431     // Dwarf Lowering Routines
432     //===------------------------------------------------------------------===//
433
434     /// \brief Emit frame instruction to describe the layout of the frame.
435     void emitCFIInstruction(const MCCFIInstruction &Inst) const;
436
437     //===------------------------------------------------------------------===//
438     // Inline Asm Support
439     //===------------------------------------------------------------------===//
440   public:
441     // These are hooks that targets can override to implement inline asm
442     // support.  These should probably be moved out of AsmPrinter someday.
443
444     /// PrintSpecial - Print information related to the specified machine instr
445     /// that is independent of the operand, and may be independent of the instr
446     /// itself.  This can be useful for portably encoding the comment character
447     /// or other bits of target-specific knowledge into the asmstrings.  The
448     /// syntax used is ${:comment}.  Targets can override this to add support
449     /// for their own strange codes.
450     virtual void PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
451                               const char *Code) const;
452
453     /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
454     /// instruction, using the specified assembler variant.  Targets should
455     /// override this to format as appropriate.  This method can return true if
456     /// the operand is erroneous.
457     virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
458                                  unsigned AsmVariant, const char *ExtraCode,
459                                  raw_ostream &OS);
460
461     /// PrintAsmMemoryOperand - Print the specified operand of MI, an INLINEASM
462     /// instruction, using the specified assembler variant as an address.
463     /// Targets should override this to format as appropriate.  This method can
464     /// return true if the operand is erroneous.
465     virtual bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
466                                        unsigned AsmVariant,
467                                        const char *ExtraCode, raw_ostream &OS);
468
469   private:
470     /// Private state for PrintSpecial()
471     // Assign a unique ID to this machine instruction.
472     mutable const MachineInstr *LastMI;
473     mutable unsigned LastFn;
474     mutable unsigned Counter;
475     mutable unsigned SetCounter;
476
477     /// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
478     void EmitInlineAsm(StringRef Str, const MDNode *LocMDNode = 0,
479                        InlineAsm::AsmDialect AsmDialect =
480                            InlineAsm::AD_ATT) const;
481
482     /// EmitInlineAsm - This method formats and emits the specified machine
483     /// instruction that is an inline asm.
484     void EmitInlineAsm(const MachineInstr *MI) const;
485
486     //===------------------------------------------------------------------===//
487     // Internal Implementation Details
488     //===------------------------------------------------------------------===//
489
490     /// EmitVisibility - This emits visibility information about symbol, if
491     /// this is suported by the target.
492     void EmitVisibility(MCSymbol *Sym, unsigned Visibility,
493                         bool IsDefinition = true) const;
494
495     void EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const;
496
497     void EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
498                             const MachineBasicBlock *MBB, unsigned uid) const;
499     void EmitLLVMUsedList(const ConstantArray *InitList);
500     /// Emit llvm.ident metadata in an '.ident' directive.
501     void EmitModuleIdents(Module &M);
502     void EmitXXStructorList(const Constant *List, bool isCtor);
503     GCMetadataPrinter *GetOrCreateGCPrinter(GCStrategy *C);
504   };
505 }
506
507 #endif