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