MCStreamer.h revision f1a5c7ec04002769f1638e64f7439589f0f926e6
1//===- MCStreamer.h - High-level Streaming Machine Code Output --*- 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 declares the MCStreamer class.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_MC_MCSTREAMER_H
15#define LLVM_MC_MCSTREAMER_H
16
17#include "llvm/ADT/SmallVector.h"
18#include "llvm/Support/DataTypes.h"
19#include "llvm/MC/MCDirectives.h"
20#include "llvm/MC/MCDwarf.h"
21
22namespace llvm {
23  class MCAsmInfo;
24  class MCCodeEmitter;
25  class MCContext;
26  class MCExpr;
27  class MCInst;
28  class MCInstPrinter;
29  class MCSection;
30  class MCSymbol;
31  class StringRef;
32  class TargetAsmBackend;
33  class TargetLoweringObjectFile;
34  class Twine;
35  class raw_ostream;
36  class formatted_raw_ostream;
37
38  /// MCStreamer - Streaming machine code generation interface.  This interface
39  /// is intended to provide a programatic interface that is very similar to the
40  /// level that an assembler .s file provides.  It has callbacks to emit bytes,
41  /// handle directives, etc.  The implementation of this interface retains
42  /// state to know what the current section is etc.
43  ///
44  /// There are multiple implementations of this interface: one for writing out
45  /// a .s file, and implementations that write out .o files of various formats.
46  ///
47  class MCStreamer {
48    MCContext &Context;
49
50    MCStreamer(const MCStreamer&); // DO NOT IMPLEMENT
51    MCStreamer &operator=(const MCStreamer&); // DO NOT IMPLEMENT
52
53    void EmitSymbolValue(const MCSymbol *Sym, unsigned Size,
54                         bool isPCRel, unsigned AddrSpace);
55
56    std::vector<MCDwarfFrameInfo> FrameInfos;
57    MCDwarfFrameInfo *getCurrentFrameInfo();
58    void EnsureValidFrame();
59
60    const MCSymbol* LastNonPrivate;
61
62    /// SectionStack - This is stack of current and previous section
63    /// values saved by PushSection.
64    SmallVector<std::pair<const MCSection *,
65                const MCSection *>, 4> SectionStack;
66
67  protected:
68    MCStreamer(MCContext &Ctx);
69
70    const MCExpr *BuildSymbolDiff(MCContext &Context, const MCSymbol *A,
71                                  const MCSymbol *B);
72
73    const MCExpr *ForceExpAbs(MCStreamer *Streamer, MCContext &Context,
74                              const MCExpr* Expr);
75
76  public:
77    virtual ~MCStreamer();
78
79    MCContext &getContext() const { return Context; }
80
81    unsigned getNumFrameInfos() {
82      return FrameInfos.size();
83    }
84
85    const MCDwarfFrameInfo &getFrameInfo(unsigned i) {
86      return FrameInfos[i];
87    }
88
89    /// @name Assembly File Formatting.
90    /// @{
91
92    /// isVerboseAsm - Return true if this streamer supports verbose assembly
93    /// and if it is enabled.
94    virtual bool isVerboseAsm() const { return false; }
95
96    /// hasRawTextSupport - Return true if this asm streamer supports emitting
97    /// unformatted text to the .s file with EmitRawText.
98    virtual bool hasRawTextSupport() const { return false; }
99
100    /// AddComment - Add a comment that can be emitted to the generated .s
101    /// file if applicable as a QoI issue to make the output of the compiler
102    /// more readable.  This only affects the MCAsmStreamer, and only when
103    /// verbose assembly output is enabled.
104    ///
105    /// If the comment includes embedded \n's, they will each get the comment
106    /// prefix as appropriate.  The added comment should not end with a \n.
107    virtual void AddComment(const Twine &T) {}
108
109    /// GetCommentOS - Return a raw_ostream that comments can be written to.
110    /// Unlike AddComment, you are required to terminate comments with \n if you
111    /// use this method.
112    virtual raw_ostream &GetCommentOS();
113
114    /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
115    virtual void AddBlankLine() {}
116
117    /// @}
118
119    /// @name Symbol & Section Management
120    /// @{
121
122    /// getCurrentSection - Return the current section that the streamer is
123    /// emitting code to.
124    const MCSection *getCurrentSection() const {
125      if (!SectionStack.empty())
126        return SectionStack.back().first;
127      return NULL;
128    }
129
130    /// getPreviousSection - Return the previous section that the streamer is
131    /// emitting code to.
132    const MCSection *getPreviousSection() const {
133      if (!SectionStack.empty())
134        return SectionStack.back().second;
135      return NULL;
136    }
137
138    /// ChangeSection - Update streamer for a new active section.
139    ///
140    /// This is called by PopSection and SwitchSection, if the current
141    /// section changes.
142    virtual void ChangeSection(const MCSection *) = 0;
143
144    /// pushSection - Save the current and previous section on the
145    /// section stack.
146    void PushSection() {
147      SectionStack.push_back(std::make_pair(getCurrentSection(),
148                                            getPreviousSection()));
149    }
150
151    /// popSection - Restore the current and previous section from
152    /// the section stack.  Calls ChangeSection as needed.
153    ///
154    /// Returns false if the stack was empty.
155    bool PopSection() {
156      if (SectionStack.size() <= 1)
157        return false;
158      const MCSection *oldSection = SectionStack.pop_back_val().first;
159      const MCSection *curSection = SectionStack.back().first;
160
161      if (oldSection != curSection)
162        ChangeSection(curSection);
163      return true;
164    }
165
166    /// SwitchSection - Set the current section where code is being emitted to
167    /// @p Section.  This is required to update CurSection.
168    ///
169    /// This corresponds to assembler directives like .section, .text, etc.
170    void SwitchSection(const MCSection *Section) {
171      assert(Section && "Cannot switch to a null section!");
172      const MCSection *curSection = SectionStack.back().first;
173      SectionStack.back().second = curSection;
174      if (Section != curSection) {
175        SectionStack.back().first = Section;
176        ChangeSection(Section);
177      }
178    }
179
180    /// InitSections - Create the default sections and set the initial one.
181    virtual void InitSections() = 0;
182
183    /// EmitLabel - Emit a label for @p Symbol into the current section.
184    ///
185    /// This corresponds to an assembler statement such as:
186    ///   foo:
187    ///
188    /// @param Symbol - The symbol to emit. A given symbol should only be
189    /// emitted as a label once, and symbols emitted as a label should never be
190    /// used in an assignment.
191    virtual void EmitLabel(MCSymbol *Symbol);
192
193    virtual void EmitEHSymAttributes(const MCSymbol *Symbol,
194                                     MCSymbol *EHSymbol);
195
196    /// EmitAssemblerFlag - Note in the output the specified @p Flag
197    virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) = 0;
198
199    /// EmitThumbFunc - Note in the output that the specified @p Func is
200    /// a Thumb mode function (ARM target only).
201    virtual void EmitThumbFunc(MCSymbol *Func) = 0;
202
203    /// EmitAssignment - Emit an assignment of @p Value to @p Symbol.
204    ///
205    /// This corresponds to an assembler statement such as:
206    ///  symbol = value
207    ///
208    /// The assignment generates no code, but has the side effect of binding the
209    /// value in the current context. For the assembly streamer, this prints the
210    /// binding into the .s file.
211    ///
212    /// @param Symbol - The symbol being assigned to.
213    /// @param Value - The value for the symbol.
214    virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) = 0;
215
216    /// EmitWeakReference - Emit an weak reference from @p Alias to @p Symbol.
217    ///
218    /// This corresponds to an assembler statement such as:
219    ///  .weakref alias, symbol
220    ///
221    /// @param Alias - The alias that is being created.
222    /// @param Symbol - The symbol being aliased.
223    virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) = 0;
224
225    /// EmitSymbolAttribute - Add the given @p Attribute to @p Symbol.
226    virtual void EmitSymbolAttribute(MCSymbol *Symbol,
227                                     MCSymbolAttr Attribute) = 0;
228
229    /// EmitSymbolDesc - Set the @p DescValue for the @p Symbol.
230    ///
231    /// @param Symbol - The symbol to have its n_desc field set.
232    /// @param DescValue - The value to set into the n_desc field.
233    virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) = 0;
234
235    /// BeginCOFFSymbolDef - Start emitting COFF symbol definition
236    ///
237    /// @param Symbol - The symbol to have its External & Type fields set.
238    virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) = 0;
239
240    /// EmitCOFFSymbolStorageClass - Emit the storage class of the symbol.
241    ///
242    /// @param StorageClass - The storage class the symbol should have.
243    virtual void EmitCOFFSymbolStorageClass(int StorageClass) = 0;
244
245    /// EmitCOFFSymbolType - Emit the type of the symbol.
246    ///
247    /// @param Type - A COFF type identifier (see COFF::SymbolType in X86COFF.h)
248    virtual void EmitCOFFSymbolType(int Type) = 0;
249
250    /// EndCOFFSymbolDef - Marks the end of the symbol definition.
251    virtual void EndCOFFSymbolDef() = 0;
252
253    /// EmitELFSize - Emit an ELF .size directive.
254    ///
255    /// This corresponds to an assembler statement such as:
256    ///  .size symbol, expression
257    ///
258    virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) = 0;
259
260    /// EmitCommonSymbol - Emit a common symbol.
261    ///
262    /// @param Symbol - The common symbol to emit.
263    /// @param Size - The size of the common symbol.
264    /// @param ByteAlignment - The alignment of the symbol if
265    /// non-zero. This must be a power of 2.
266    virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
267                                  unsigned ByteAlignment) = 0;
268
269    /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
270    ///
271    /// @param Symbol - The common symbol to emit.
272    /// @param Size - The size of the common symbol.
273    virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) = 0;
274
275    /// EmitZerofill - Emit the zerofill section and an optional symbol.
276    ///
277    /// @param Section - The zerofill section to create and or to put the symbol
278    /// @param Symbol - The zerofill symbol to emit, if non-NULL.
279    /// @param Size - The size of the zerofill symbol.
280    /// @param ByteAlignment - The alignment of the zerofill symbol if
281    /// non-zero. This must be a power of 2 on some targets.
282    virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
283                              unsigned Size = 0,unsigned ByteAlignment = 0) = 0;
284
285    /// EmitTBSSSymbol - Emit a thread local bss (.tbss) symbol.
286    ///
287    /// @param Section - The thread local common section.
288    /// @param Symbol - The thread local common symbol to emit.
289    /// @param Size - The size of the symbol.
290    /// @param ByteAlignment - The alignment of the thread local common symbol
291    /// if non-zero.  This must be a power of 2 on some targets.
292    virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
293                                uint64_t Size, unsigned ByteAlignment = 0) = 0;
294    /// @}
295    /// @name Generating Data
296    /// @{
297
298    /// EmitBytes - Emit the bytes in \arg Data into the output.
299    ///
300    /// This is used to implement assembler directives such as .byte, .ascii,
301    /// etc.
302    virtual void EmitBytes(StringRef Data, unsigned AddrSpace) = 0;
303
304    /// EmitValue - Emit the expression @p Value into the output as a native
305    /// integer of the given @p Size bytes.
306    ///
307    /// This is used to implement assembler directives such as .word, .quad,
308    /// etc.
309    ///
310    /// @param Value - The value to emit.
311    /// @param Size - The size of the integer (in bytes) to emit. This must
312    /// match a native machine width.
313    virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
314                               bool isPCRel, unsigned AddrSpace) = 0;
315
316    void EmitValue(const MCExpr *Value, unsigned Size, unsigned AddrSpace = 0);
317
318    void EmitPCRelValue(const MCExpr *Value, unsigned Size,
319                        unsigned AddrSpace = 0);
320
321    /// EmitIntValue - Special case of EmitValue that avoids the client having
322    /// to pass in a MCExpr for constant integers.
323    virtual void EmitIntValue(uint64_t Value, unsigned Size,
324                              unsigned AddrSpace = 0);
325
326    /// EmitAbsValue - Emit the Value, but try to avoid relocations. On MachO
327    /// this is done by producing
328    /// foo = value
329    /// .long foo
330    void EmitAbsValue(const MCExpr *Value, unsigned Size,
331                      unsigned AddrSpace = 0);
332
333    virtual void EmitULEB128Value(const MCExpr *Value) = 0;
334
335    virtual void EmitSLEB128Value(const MCExpr *Value) = 0;
336
337    /// EmitULEB128Value - Special case of EmitULEB128Value that avoids the
338    /// client having to pass in a MCExpr for constant integers.
339    void EmitULEB128IntValue(uint64_t Value, unsigned AddrSpace = 0);
340
341    /// EmitSLEB128Value - Special case of EmitSLEB128Value that avoids the
342    /// client having to pass in a MCExpr for constant integers.
343    void EmitSLEB128IntValue(int64_t Value, unsigned AddrSpace = 0);
344
345    /// EmitSymbolValue - Special case of EmitValue that avoids the client
346    /// having to pass in a MCExpr for MCSymbols.
347    void EmitSymbolValue(const MCSymbol *Sym, unsigned Size,
348                         unsigned AddrSpace = 0);
349
350    void EmitPCRelSymbolValue(const MCSymbol *Sym, unsigned Size,
351                              unsigned AddrSpace = 0);
352
353    /// EmitGPRel32Value - Emit the expression @p Value into the output as a
354    /// gprel32 (32-bit GP relative) value.
355    ///
356    /// This is used to implement assembler directives such as .gprel32 on
357    /// targets that support them.
358    virtual void EmitGPRel32Value(const MCExpr *Value);
359
360    /// EmitFill - Emit NumBytes bytes worth of the value specified by
361    /// FillValue.  This implements directives such as '.space'.
362    virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue,
363                          unsigned AddrSpace);
364
365    /// EmitZeros - Emit NumBytes worth of zeros.  This is a convenience
366    /// function that just wraps EmitFill.
367    void EmitZeros(uint64_t NumBytes, unsigned AddrSpace) {
368      EmitFill(NumBytes, 0, AddrSpace);
369    }
370
371
372    /// EmitValueToAlignment - Emit some number of copies of @p Value until
373    /// the byte alignment @p ByteAlignment is reached.
374    ///
375    /// If the number of bytes need to emit for the alignment is not a multiple
376    /// of @p ValueSize, then the contents of the emitted fill bytes is
377    /// undefined.
378    ///
379    /// This used to implement the .align assembler directive.
380    ///
381    /// @param ByteAlignment - The alignment to reach. This must be a power of
382    /// two on some targets.
383    /// @param Value - The value to use when filling bytes.
384    /// @param ValueSize - The size of the integer (in bytes) to emit for
385    /// @p Value. This must match a native machine width.
386    /// @param MaxBytesToEmit - The maximum numbers of bytes to emit, or 0. If
387    /// the alignment cannot be reached in this many bytes, no bytes are
388    /// emitted.
389    virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
390                                      unsigned ValueSize = 1,
391                                      unsigned MaxBytesToEmit = 0) = 0;
392
393    /// EmitCodeAlignment - Emit nops until the byte alignment @p ByteAlignment
394    /// is reached.
395    ///
396    /// This used to align code where the alignment bytes may be executed.  This
397    /// can emit different bytes for different sizes to optimize execution.
398    ///
399    /// @param ByteAlignment - The alignment to reach. This must be a power of
400    /// two on some targets.
401    /// @param MaxBytesToEmit - The maximum numbers of bytes to emit, or 0. If
402    /// the alignment cannot be reached in this many bytes, no bytes are
403    /// emitted.
404    virtual void EmitCodeAlignment(unsigned ByteAlignment,
405                                   unsigned MaxBytesToEmit = 0) = 0;
406
407    /// EmitValueToOffset - Emit some number of copies of @p Value until the
408    /// byte offset @p Offset is reached.
409    ///
410    /// This is used to implement assembler directives such as .org.
411    ///
412    /// @param Offset - The offset to reach. This may be an expression, but the
413    /// expression must be associated with the current section.
414    /// @param Value - The value to use when filling bytes.
415    virtual void EmitValueToOffset(const MCExpr *Offset,
416                                   unsigned char Value = 0) = 0;
417
418    /// @}
419
420    /// EmitFileDirective - Switch to a new logical file.  This is used to
421    /// implement the '.file "foo.c"' assembler directive.
422    virtual void EmitFileDirective(StringRef Filename) = 0;
423
424    /// EmitDwarfFileDirective - Associate a filename with a specified logical
425    /// file number.  This implements the DWARF2 '.file 4 "foo.c"' assembler
426    /// directive.
427    virtual bool EmitDwarfFileDirective(unsigned FileNo,StringRef Filename);
428
429    /// EmitDwarfLocDirective - This implements the DWARF2
430    // '.loc fileno lineno ...' assembler directive.
431    virtual void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
432                                       unsigned Column, unsigned Flags,
433                                       unsigned Isa,
434                                       unsigned Discriminator,
435                                       StringRef FileName);
436
437    virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
438                                          const MCSymbol *LastLabel,
439                                          const MCSymbol *Label) = 0;
440
441    virtual void EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
442                                           const MCSymbol *Label) {
443    }
444
445    void EmitDwarfSetLineAddr(int64_t LineDelta, const MCSymbol *Label,
446                              int PointerSize);
447
448    virtual void EmitCFIStartProc();
449    virtual void EmitCFIEndProc();
450    virtual void EmitCFIDefCfa(int64_t Register, int64_t Offset);
451    virtual void EmitCFIDefCfaOffset(int64_t Offset);
452    virtual void EmitCFIDefCfaRegister(int64_t Register);
453    virtual void EmitCFIOffset(int64_t Register, int64_t Offset);
454    virtual void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding);
455    virtual void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding);
456    virtual void EmitCFIRememberState();
457    virtual void EmitCFIRestoreState();
458    virtual void EmitCFISameValue(int64_t Register);
459    virtual void EmitCFIRelOffset(int64_t Register, int64_t Offset);
460    virtual void EmitCFIAdjustCfaOffset(int64_t Adjustment);
461
462    /// EmitInstruction - Emit the given @p Instruction into the current
463    /// section.
464    virtual void EmitInstruction(const MCInst &Inst) = 0;
465
466    /// EmitRawText - If this file is backed by a assembly streamer, this dumps
467    /// the specified string in the output .s file.  This capability is
468    /// indicated by the hasRawTextSupport() predicate.  By default this aborts.
469    virtual void EmitRawText(StringRef String);
470    void EmitRawText(const Twine &String);
471
472    /// ARM-related methods.
473    /// FIXME: Eventually we should have some "target MC streamer" and move
474    /// these methods there.
475    virtual void EmitFnStart();
476    virtual void EmitFnEnd();
477    virtual void EmitCantUnwind();
478    virtual void EmitPersonality(const MCSymbol *Personality);
479    virtual void EmitHandlerData();
480    virtual void EmitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0);
481    virtual void EmitPad(int64_t Offset);
482    virtual void EmitRegSave(const SmallVectorImpl<unsigned> &RegList,
483                             bool isVector);
484
485    /// Finish - Finish emission of machine code.
486    virtual void Finish() = 0;
487  };
488
489  /// createNullStreamer - Create a dummy machine code streamer, which does
490  /// nothing. This is useful for timing the assembler front end.
491  MCStreamer *createNullStreamer(MCContext &Ctx);
492
493  /// createAsmStreamer - Create a machine code streamer which will print out
494  /// assembly for the native target, suitable for compiling with a native
495  /// assembler.
496  ///
497  /// \param InstPrint - If given, the instruction printer to use. If not given
498  /// the MCInst representation will be printed.  This method takes ownership of
499  /// InstPrint.
500  ///
501  /// \param CE - If given, a code emitter to use to show the instruction
502  /// encoding inline with the assembly. This method takes ownership of \arg CE.
503  ///
504  /// \param TAB - If given, a target asm backend to use to show the fixup
505  /// information in conjunction with encoding information. This method takes
506  /// ownership of \arg TAB.
507  ///
508  /// \param ShowInst - Whether to show the MCInst representation inline with
509  /// the assembly.
510  MCStreamer *createAsmStreamer(MCContext &Ctx, formatted_raw_ostream &OS,
511                                bool isVerboseAsm,
512                                bool useLoc,
513                                bool useCFI,
514                                MCInstPrinter *InstPrint = 0,
515                                MCCodeEmitter *CE = 0,
516                                TargetAsmBackend *TAB = 0,
517                                bool ShowInst = false);
518
519  /// createMachOStreamer - Create a machine code streamer which will generate
520  /// Mach-O format object files.
521  ///
522  /// Takes ownership of \arg TAB and \arg CE.
523  MCStreamer *createMachOStreamer(MCContext &Ctx, TargetAsmBackend &TAB,
524                                  raw_ostream &OS, MCCodeEmitter *CE,
525                                  bool RelaxAll = false);
526
527  /// createWinCOFFStreamer - Create a machine code streamer which will
528  /// generate Microsoft COFF format object files.
529  ///
530  /// Takes ownership of \arg TAB and \arg CE.
531  MCStreamer *createWinCOFFStreamer(MCContext &Ctx,
532                                    TargetAsmBackend &TAB,
533                                    MCCodeEmitter &CE, raw_ostream &OS,
534                                    bool RelaxAll = false);
535
536  /// createELFStreamer - Create a machine code streamer which will generate
537  /// ELF format object files.
538  MCStreamer *createELFStreamer(MCContext &Ctx, TargetAsmBackend &TAB,
539				raw_ostream &OS, MCCodeEmitter *CE,
540				bool RelaxAll, bool NoExecStack);
541
542  /// createLoggingStreamer - Create a machine code streamer which just logs the
543  /// API calls and then dispatches to another streamer.
544  ///
545  /// The new streamer takes ownership of the \arg Child.
546  MCStreamer *createLoggingStreamer(MCStreamer *Child, raw_ostream &OS);
547
548  /// createPureStreamer - Create a machine code streamer which will generate
549  /// "pure" MC object files, for use with MC-JIT and testing tools.
550  ///
551  /// Takes ownership of \arg TAB and \arg CE.
552  MCStreamer *createPureStreamer(MCContext &Ctx, TargetAsmBackend &TAB,
553                                 raw_ostream &OS, MCCodeEmitter *CE);
554
555} // end namespace llvm
556
557#endif
558