Home | History | Annotate | Download | only in MC
      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/ArrayRef.h"
     18 #include "llvm/ADT/DenseMap.h"
     19 #include "llvm/ADT/SmallVector.h"
     20 #include "llvm/ADT/StringRef.h"
     21 #include "llvm/MC/MCDirectives.h"
     22 #include "llvm/MC/MCDwarf.h"
     23 #include "llvm/MC/MCLinkerOptimizationHint.h"
     24 #include "llvm/MC/MCSymbol.h"
     25 #include "llvm/MC/MCWinEH.h"
     26 #include "llvm/Support/SMLoc.h"
     27 #include "llvm/Support/TargetParser.h"
     28 #include <cassert>
     29 #include <cstdint>
     30 #include <memory>
     31 #include <string>
     32 #include <utility>
     33 #include <vector>
     34 
     35 namespace llvm {
     36 
     37 class AssemblerConstantPools;
     38 class formatted_raw_ostream;
     39 class MCAsmBackend;
     40 class MCCodeEmitter;
     41 class MCContext;
     42 class MCExpr;
     43 class MCInst;
     44 class MCInstPrinter;
     45 class MCSection;
     46 class MCStreamer;
     47 class MCSymbolRefExpr;
     48 class MCSubtargetInfo;
     49 class raw_ostream;
     50 class Twine;
     51 
     52 using MCSectionSubPair = std::pair<MCSection *, const MCExpr *>;
     53 
     54 /// Target specific streamer interface. This is used so that targets can
     55 /// implement support for target specific assembly directives.
     56 ///
     57 /// If target foo wants to use this, it should implement 3 classes:
     58 /// * FooTargetStreamer : public MCTargetStreamer
     59 /// * FooTargetAsmStreamer : public FooTargetStreamer
     60 /// * FooTargetELFStreamer : public FooTargetStreamer
     61 ///
     62 /// FooTargetStreamer should have a pure virtual method for each directive. For
     63 /// example, for a ".bar symbol_name" directive, it should have
     64 /// virtual emitBar(const MCSymbol &Symbol) = 0;
     65 ///
     66 /// The FooTargetAsmStreamer and FooTargetELFStreamer classes implement the
     67 /// method. The assembly streamer just prints ".bar symbol_name". The object
     68 /// streamer does whatever is needed to implement .bar in the object file.
     69 ///
     70 /// In the assembly printer and parser the target streamer can be used by
     71 /// calling getTargetStreamer and casting it to FooTargetStreamer:
     72 ///
     73 /// MCTargetStreamer &TS = OutStreamer.getTargetStreamer();
     74 /// FooTargetStreamer &ATS = static_cast<FooTargetStreamer &>(TS);
     75 ///
     76 /// The base classes FooTargetAsmStreamer and FooTargetELFStreamer should
     77 /// *never* be treated differently. Callers should always talk to a
     78 /// FooTargetStreamer.
     79 class MCTargetStreamer {
     80 protected:
     81   MCStreamer &Streamer;
     82 
     83 public:
     84   MCTargetStreamer(MCStreamer &S);
     85   virtual ~MCTargetStreamer();
     86 
     87   MCStreamer &getStreamer() { return Streamer; }
     88 
     89   // Allow a target to add behavior to the EmitLabel of MCStreamer.
     90   virtual void emitLabel(MCSymbol *Symbol);
     91   // Allow a target to add behavior to the emitAssignment of MCStreamer.
     92   virtual void emitAssignment(MCSymbol *Symbol, const MCExpr *Value);
     93 
     94   virtual void prettyPrintAsm(MCInstPrinter &InstPrinter, raw_ostream &OS,
     95                               const MCInst &Inst, const MCSubtargetInfo &STI);
     96 
     97   virtual void finish();
     98 };
     99 
    100 // FIXME: declared here because it is used from
    101 // lib/CodeGen/AsmPrinter/ARMException.cpp.
    102 class ARMTargetStreamer : public MCTargetStreamer {
    103 public:
    104   ARMTargetStreamer(MCStreamer &S);
    105   ~ARMTargetStreamer() override;
    106 
    107   virtual void emitFnStart();
    108   virtual void emitFnEnd();
    109   virtual void emitCantUnwind();
    110   virtual void emitPersonality(const MCSymbol *Personality);
    111   virtual void emitPersonalityIndex(unsigned Index);
    112   virtual void emitHandlerData();
    113   virtual void emitSetFP(unsigned FpReg, unsigned SpReg,
    114                          int64_t Offset = 0);
    115   virtual void emitMovSP(unsigned Reg, int64_t Offset = 0);
    116   virtual void emitPad(int64_t Offset);
    117   virtual void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
    118                            bool isVector);
    119   virtual void emitUnwindRaw(int64_t StackOffset,
    120                              const SmallVectorImpl<uint8_t> &Opcodes);
    121 
    122   virtual void switchVendor(StringRef Vendor);
    123   virtual void emitAttribute(unsigned Attribute, unsigned Value);
    124   virtual void emitTextAttribute(unsigned Attribute, StringRef String);
    125   virtual void emitIntTextAttribute(unsigned Attribute, unsigned IntValue,
    126                                     StringRef StringValue = "");
    127   virtual void emitFPU(unsigned FPU);
    128   virtual void emitArch(ARM::ArchKind Arch);
    129   virtual void emitArchExtension(unsigned ArchExt);
    130   virtual void emitObjectArch(ARM::ArchKind Arch);
    131   void emitTargetAttributes(const MCSubtargetInfo &STI);
    132   virtual void finishAttributeSection();
    133   virtual void emitInst(uint32_t Inst, char Suffix = '\0');
    134 
    135   virtual void AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *SRE);
    136 
    137   virtual void emitThumbSet(MCSymbol *Symbol, const MCExpr *Value);
    138 
    139   void finish() override;
    140 
    141   /// Reset any state between object emissions, i.e. the equivalent of
    142   /// MCStreamer's reset method.
    143   virtual void reset();
    144 
    145   /// Callback used to implement the ldr= pseudo.
    146   /// Add a new entry to the constant pool for the current section and return an
    147   /// MCExpr that can be used to refer to the constant pool location.
    148   const MCExpr *addConstantPoolEntry(const MCExpr *, SMLoc Loc);
    149 
    150   /// Callback used to implemnt the .ltorg directive.
    151   /// Emit contents of constant pool for the current section.
    152   void emitCurrentConstantPool();
    153 
    154 private:
    155   std::unique_ptr<AssemblerConstantPools> ConstantPools;
    156 };
    157 
    158 /// \brief Streaming machine code generation interface.
    159 ///
    160 /// This interface is intended to provide a programatic interface that is very
    161 /// similar to the level that an assembler .s file provides.  It has callbacks
    162 /// to emit bytes, handle directives, etc.  The implementation of this interface
    163 /// retains state to know what the current section is etc.
    164 ///
    165 /// There are multiple implementations of this interface: one for writing out
    166 /// a .s file, and implementations that write out .o files of various formats.
    167 ///
    168 class MCStreamer {
    169   MCContext &Context;
    170   std::unique_ptr<MCTargetStreamer> TargetStreamer;
    171 
    172   std::vector<MCDwarfFrameInfo> DwarfFrameInfos;
    173   MCDwarfFrameInfo *getCurrentDwarfFrameInfo();
    174 
    175   /// Similar to DwarfFrameInfos, but for SEH unwind info. Chained frames may
    176   /// refer to each other, so use std::unique_ptr to provide pointer stability.
    177   std::vector<std::unique_ptr<WinEH::FrameInfo>> WinFrameInfos;
    178 
    179   WinEH::FrameInfo *CurrentWinFrameInfo;
    180 
    181   /// Retreive the current frame info if one is available and it is not yet
    182   /// closed. Otherwise, issue an error and return null.
    183   WinEH::FrameInfo *EnsureValidWinFrameInfo(SMLoc Loc);
    184 
    185   /// \brief Tracks an index to represent the order a symbol was emitted in.
    186   /// Zero means we did not emit that symbol.
    187   DenseMap<const MCSymbol *, unsigned> SymbolOrdering;
    188 
    189   /// \brief This is stack of current and previous section values saved by
    190   /// PushSection.
    191   SmallVector<std::pair<MCSectionSubPair, MCSectionSubPair>, 4> SectionStack;
    192 
    193   /// The next unique ID to use when creating a WinCFI-related section (.pdata
    194   /// or .xdata). This ID ensures that we have a one-to-one mapping from
    195   /// code section to unwind info section, which MSVC's incremental linker
    196   /// requires.
    197   unsigned NextWinCFIID = 0;
    198 
    199 protected:
    200   MCStreamer(MCContext &Ctx);
    201 
    202   virtual void EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame);
    203   virtual void EmitCFIEndProcImpl(MCDwarfFrameInfo &CurFrame);
    204 
    205   /// When emitting an object file, create and emit a real label. When emitting
    206   /// textual assembly, this should do nothing to avoid polluting our output.
    207   virtual MCSymbol *EmitCFILabel();
    208 
    209   WinEH::FrameInfo *getCurrentWinFrameInfo() {
    210     return CurrentWinFrameInfo;
    211   }
    212 
    213   virtual void EmitWindowsUnwindTables();
    214 
    215   virtual void EmitRawTextImpl(StringRef String);
    216 
    217 public:
    218   MCStreamer(const MCStreamer &) = delete;
    219   MCStreamer &operator=(const MCStreamer &) = delete;
    220   virtual ~MCStreamer();
    221 
    222   void visitUsedExpr(const MCExpr &Expr);
    223   virtual void visitUsedSymbol(const MCSymbol &Sym);
    224 
    225   void setTargetStreamer(MCTargetStreamer *TS) {
    226     TargetStreamer.reset(TS);
    227   }
    228 
    229   /// State management
    230   ///
    231   virtual void reset();
    232 
    233   MCContext &getContext() const { return Context; }
    234 
    235   MCTargetStreamer *getTargetStreamer() {
    236     return TargetStreamer.get();
    237   }
    238 
    239   unsigned getNumFrameInfos() { return DwarfFrameInfos.size(); }
    240   ArrayRef<MCDwarfFrameInfo> getDwarfFrameInfos() const {
    241     return DwarfFrameInfos;
    242   }
    243 
    244   bool hasUnfinishedDwarfFrameInfo();
    245 
    246   unsigned getNumWinFrameInfos() { return WinFrameInfos.size(); }
    247   ArrayRef<std::unique_ptr<WinEH::FrameInfo>> getWinFrameInfos() const {
    248     return WinFrameInfos;
    249   }
    250 
    251   void generateCompactUnwindEncodings(MCAsmBackend *MAB);
    252 
    253   /// \name Assembly File Formatting.
    254   /// @{
    255 
    256   /// \brief Return true if this streamer supports verbose assembly and if it is
    257   /// enabled.
    258   virtual bool isVerboseAsm() const { return false; }
    259 
    260   /// \brief Return true if this asm streamer supports emitting unformatted text
    261   /// to the .s file with EmitRawText.
    262   virtual bool hasRawTextSupport() const { return false; }
    263 
    264   /// \brief Is the integrated assembler required for this streamer to function
    265   /// correctly?
    266   virtual bool isIntegratedAssemblerRequired() const { return false; }
    267 
    268   /// \brief Add a textual comment.
    269   ///
    270   /// Typically for comments that can be emitted to the generated .s
    271   /// file if applicable as a QoI issue to make the output of the compiler
    272   /// more readable.  This only affects the MCAsmStreamer, and only when
    273   /// verbose assembly output is enabled.
    274   ///
    275   /// If the comment includes embedded \n's, they will each get the comment
    276   /// prefix as appropriate.  The added comment should not end with a \n.
    277   /// By default, each comment is terminated with an end of line, i.e. the
    278   /// EOL param is set to true by default. If one prefers not to end the
    279   /// comment with a new line then the EOL param should be passed
    280   /// with a false value.
    281   virtual void AddComment(const Twine &T, bool EOL = true) {}
    282 
    283   /// \brief Return a raw_ostream that comments can be written to. Unlike
    284   /// AddComment, you are required to terminate comments with \n if you use this
    285   /// method.
    286   virtual raw_ostream &GetCommentOS();
    287 
    288   /// \brief Print T and prefix it with the comment string (normally #) and
    289   /// optionally a tab. This prints the comment immediately, not at the end of
    290   /// the current line. It is basically a safe version of EmitRawText: since it
    291   /// only prints comments, the object streamer ignores it instead of asserting.
    292   virtual void emitRawComment(const Twine &T, bool TabPrefix = true);
    293 
    294   /// \brief Add explicit comment T. T is required to be a valid
    295   /// comment in the output and does not need to be escaped.
    296   virtual void addExplicitComment(const Twine &T);
    297 
    298   /// \brief Emit added explicit comments.
    299   virtual void emitExplicitComments();
    300 
    301   /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
    302   virtual void AddBlankLine() {}
    303 
    304   /// @}
    305 
    306   /// \name Symbol & Section Management
    307   /// @{
    308 
    309   /// \brief Return the current section that the streamer is emitting code to.
    310   MCSectionSubPair getCurrentSection() const {
    311     if (!SectionStack.empty())
    312       return SectionStack.back().first;
    313     return MCSectionSubPair();
    314   }
    315   MCSection *getCurrentSectionOnly() const { return getCurrentSection().first; }
    316 
    317   /// \brief Return the previous section that the streamer is emitting code to.
    318   MCSectionSubPair getPreviousSection() const {
    319     if (!SectionStack.empty())
    320       return SectionStack.back().second;
    321     return MCSectionSubPair();
    322   }
    323 
    324   /// \brief Returns an index to represent the order a symbol was emitted in.
    325   /// (zero if we did not emit that symbol)
    326   unsigned GetSymbolOrder(const MCSymbol *Sym) const {
    327     return SymbolOrdering.lookup(Sym);
    328   }
    329 
    330   /// \brief Update streamer for a new active section.
    331   ///
    332   /// This is called by PopSection and SwitchSection, if the current
    333   /// section changes.
    334   virtual void ChangeSection(MCSection *, const MCExpr *);
    335 
    336   /// \brief Save the current and previous section on the section stack.
    337   void PushSection() {
    338     SectionStack.push_back(
    339         std::make_pair(getCurrentSection(), getPreviousSection()));
    340   }
    341 
    342   /// \brief Restore the current and previous section from the section stack.
    343   /// Calls ChangeSection as needed.
    344   ///
    345   /// Returns false if the stack was empty.
    346   bool PopSection() {
    347     if (SectionStack.size() <= 1)
    348       return false;
    349     auto I = SectionStack.end();
    350     --I;
    351     MCSectionSubPair OldSection = I->first;
    352     --I;
    353     MCSectionSubPair NewSection = I->first;
    354 
    355     if (OldSection != NewSection)
    356       ChangeSection(NewSection.first, NewSection.second);
    357     SectionStack.pop_back();
    358     return true;
    359   }
    360 
    361   bool SubSection(const MCExpr *Subsection) {
    362     if (SectionStack.empty())
    363       return false;
    364 
    365     SwitchSection(SectionStack.back().first.first, Subsection);
    366     return true;
    367   }
    368 
    369   /// Set the current section where code is being emitted to \p Section.  This
    370   /// is required to update CurSection.
    371   ///
    372   /// This corresponds to assembler directives like .section, .text, etc.
    373   virtual void SwitchSection(MCSection *Section,
    374                              const MCExpr *Subsection = nullptr);
    375 
    376   /// \brief Set the current section where code is being emitted to \p Section.
    377   /// This is required to update CurSection. This version does not call
    378   /// ChangeSection.
    379   void SwitchSectionNoChange(MCSection *Section,
    380                              const MCExpr *Subsection = nullptr) {
    381     assert(Section && "Cannot switch to a null section!");
    382     MCSectionSubPair curSection = SectionStack.back().first;
    383     SectionStack.back().second = curSection;
    384     if (MCSectionSubPair(Section, Subsection) != curSection)
    385       SectionStack.back().first = MCSectionSubPair(Section, Subsection);
    386   }
    387 
    388   /// \brief Create the default sections and set the initial one.
    389   virtual void InitSections(bool NoExecStack);
    390 
    391   MCSymbol *endSection(MCSection *Section);
    392 
    393   /// \brief Sets the symbol's section.
    394   ///
    395   /// Each emitted symbol will be tracked in the ordering table,
    396   /// so we can sort on them later.
    397   void AssignFragment(MCSymbol *Symbol, MCFragment *Fragment);
    398 
    399   /// \brief Emit a label for \p Symbol into the current section.
    400   ///
    401   /// This corresponds to an assembler statement such as:
    402   ///   foo:
    403   ///
    404   /// \param Symbol - The symbol to emit. A given symbol should only be
    405   /// emitted as a label once, and symbols emitted as a label should never be
    406   /// used in an assignment.
    407   // FIXME: These emission are non-const because we mutate the symbol to
    408   // add the section we're emitting it to later.
    409   virtual void EmitLabel(MCSymbol *Symbol, SMLoc Loc = SMLoc());
    410 
    411   virtual void EmitEHSymAttributes(const MCSymbol *Symbol, MCSymbol *EHSymbol);
    412 
    413   /// \brief Note in the output the specified \p Flag.
    414   virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
    415 
    416   /// \brief Emit the given list \p Options of strings as linker
    417   /// options into the output.
    418   virtual void EmitLinkerOptions(ArrayRef<std::string> Kind) {}
    419 
    420   /// \brief Note in the output the specified region \p Kind.
    421   virtual void EmitDataRegion(MCDataRegionType Kind) {}
    422 
    423   /// \brief Specify the MachO minimum deployment target version.
    424   virtual void EmitVersionMin(MCVersionMinType, unsigned Major, unsigned Minor,
    425                               unsigned Update) {}
    426 
    427   /// \brief Note in the output that the specified \p Func is a Thumb mode
    428   /// function (ARM target only).
    429   virtual void EmitThumbFunc(MCSymbol *Func);
    430 
    431   /// \brief Emit an assignment of \p Value to \p Symbol.
    432   ///
    433   /// This corresponds to an assembler statement such as:
    434   ///  symbol = value
    435   ///
    436   /// The assignment generates no code, but has the side effect of binding the
    437   /// value in the current context. For the assembly streamer, this prints the
    438   /// binding into the .s file.
    439   ///
    440   /// \param Symbol - The symbol being assigned to.
    441   /// \param Value - The value for the symbol.
    442   virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
    443 
    444   /// \brief Emit an weak reference from \p Alias to \p Symbol.
    445   ///
    446   /// This corresponds to an assembler statement such as:
    447   ///  .weakref alias, symbol
    448   ///
    449   /// \param Alias - The alias that is being created.
    450   /// \param Symbol - The symbol being aliased.
    451   virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol);
    452 
    453   /// \brief Add the given \p Attribute to \p Symbol.
    454   virtual bool EmitSymbolAttribute(MCSymbol *Symbol,
    455                                    MCSymbolAttr Attribute) = 0;
    456 
    457   /// \brief Set the \p DescValue for the \p Symbol.
    458   ///
    459   /// \param Symbol - The symbol to have its n_desc field set.
    460   /// \param DescValue - The value to set into the n_desc field.
    461   virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
    462 
    463   /// \brief Start emitting COFF symbol definition
    464   ///
    465   /// \param Symbol - The symbol to have its External & Type fields set.
    466   virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol);
    467 
    468   /// \brief Emit the storage class of the symbol.
    469   ///
    470   /// \param StorageClass - The storage class the symbol should have.
    471   virtual void EmitCOFFSymbolStorageClass(int StorageClass);
    472 
    473   /// \brief Emit the type of the symbol.
    474   ///
    475   /// \param Type - A COFF type identifier (see COFF::SymbolType in X86COFF.h)
    476   virtual void EmitCOFFSymbolType(int Type);
    477 
    478   /// \brief Marks the end of the symbol definition.
    479   virtual void EndCOFFSymbolDef();
    480 
    481   virtual void EmitCOFFSafeSEH(MCSymbol const *Symbol);
    482 
    483   /// \brief Emits a COFF section index.
    484   ///
    485   /// \param Symbol - Symbol the section number relocation should point to.
    486   virtual void EmitCOFFSectionIndex(MCSymbol const *Symbol);
    487 
    488   /// \brief Emits a COFF section relative relocation.
    489   ///
    490   /// \param Symbol - Symbol the section relative relocation should point to.
    491   virtual void EmitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset);
    492 
    493   /// \brief Emit an ELF .size directive.
    494   ///
    495   /// This corresponds to an assembler statement such as:
    496   ///  .size symbol, expression
    497   virtual void emitELFSize(MCSymbol *Symbol, const MCExpr *Value);
    498 
    499   /// \brief Emit an ELF .symver directive.
    500   ///
    501   /// This corresponds to an assembler statement such as:
    502   ///  .symver _start, foo@@SOME_VERSION
    503   /// \param Alias - The versioned alias (i.e. "foo@@SOME_VERSION")
    504   /// \param Aliasee - The aliased symbol (i.e. "_start")
    505   virtual void emitELFSymverDirective(MCSymbol *Alias, const MCSymbol *Aliasee);
    506 
    507   /// \brief Emit a Linker Optimization Hint (LOH) directive.
    508   /// \param Args - Arguments of the LOH.
    509   virtual void EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) {}
    510 
    511   /// \brief Emit a common symbol.
    512   ///
    513   /// \param Symbol - The common symbol to emit.
    514   /// \param Size - The size of the common symbol.
    515   /// \param ByteAlignment - The alignment of the symbol if
    516   /// non-zero. This must be a power of 2.
    517   virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
    518                                 unsigned ByteAlignment) = 0;
    519 
    520   /// \brief Emit a local common (.lcomm) symbol.
    521   ///
    522   /// \param Symbol - The common symbol to emit.
    523   /// \param Size - The size of the common symbol.
    524   /// \param ByteAlignment - The alignment of the common symbol in bytes.
    525   virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
    526                                      unsigned ByteAlignment);
    527 
    528   /// \brief Emit the zerofill section and an optional symbol.
    529   ///
    530   /// \param Section - The zerofill section to create and or to put the symbol
    531   /// \param Symbol - The zerofill symbol to emit, if non-NULL.
    532   /// \param Size - The size of the zerofill symbol.
    533   /// \param ByteAlignment - The alignment of the zerofill symbol if
    534   /// non-zero. This must be a power of 2 on some targets.
    535   virtual void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
    536                             uint64_t Size = 0, unsigned ByteAlignment = 0) = 0;
    537 
    538   /// \brief Emit a thread local bss (.tbss) symbol.
    539   ///
    540   /// \param Section - The thread local common section.
    541   /// \param Symbol - The thread local common symbol to emit.
    542   /// \param Size - The size of the symbol.
    543   /// \param ByteAlignment - The alignment of the thread local common symbol
    544   /// if non-zero.  This must be a power of 2 on some targets.
    545   virtual void EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
    546                               uint64_t Size, unsigned ByteAlignment = 0);
    547 
    548   /// @}
    549   /// \name Generating Data
    550   /// @{
    551 
    552   /// \brief Emit the bytes in \p Data into the output.
    553   ///
    554   /// This is used to implement assembler directives such as .byte, .ascii,
    555   /// etc.
    556   virtual void EmitBytes(StringRef Data);
    557 
    558   /// Functionally identical to EmitBytes. When emitting textual assembly, this
    559   /// method uses .byte directives instead of .ascii or .asciz for readability.
    560   virtual void EmitBinaryData(StringRef Data);
    561 
    562   /// \brief Emit the expression \p Value into the output as a native
    563   /// integer of the given \p Size bytes.
    564   ///
    565   /// This is used to implement assembler directives such as .word, .quad,
    566   /// etc.
    567   ///
    568   /// \param Value - The value to emit.
    569   /// \param Size - The size of the integer (in bytes) to emit. This must
    570   /// match a native machine width.
    571   /// \param Loc - The location of the expression for error reporting.
    572   virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
    573                              SMLoc Loc = SMLoc());
    574 
    575   void EmitValue(const MCExpr *Value, unsigned Size, SMLoc Loc = SMLoc());
    576 
    577   /// \brief Special case of EmitValue that avoids the client having
    578   /// to pass in a MCExpr for constant integers.
    579   virtual void EmitIntValue(uint64_t Value, unsigned Size);
    580 
    581   virtual void EmitULEB128Value(const MCExpr *Value);
    582 
    583   virtual void EmitSLEB128Value(const MCExpr *Value);
    584 
    585   /// \brief Special case of EmitULEB128Value that avoids the client having to
    586   /// pass in a MCExpr for constant integers.
    587   void EmitULEB128IntValue(uint64_t Value);
    588 
    589   /// \brief Like EmitULEB128Value but pads the output to specific number of
    590   /// bytes.
    591   void EmitPaddedULEB128IntValue(uint64_t Value, unsigned PadTo);
    592 
    593   /// \brief Special case of EmitSLEB128Value that avoids the client having to
    594   /// pass in a MCExpr for constant integers.
    595   void EmitSLEB128IntValue(int64_t Value);
    596 
    597   /// \brief Special case of EmitValue that avoids the client having to pass in
    598   /// a MCExpr for MCSymbols.
    599   void EmitSymbolValue(const MCSymbol *Sym, unsigned Size,
    600                        bool IsSectionRelative = false);
    601 
    602   /// \brief Emit the expression \p Value into the output as a dtprel
    603   /// (64-bit DTP relative) value.
    604   ///
    605   /// This is used to implement assembler directives such as .dtpreldword on
    606   /// targets that support them.
    607   virtual void EmitDTPRel64Value(const MCExpr *Value);
    608 
    609   /// \brief Emit the expression \p Value into the output as a dtprel
    610   /// (32-bit DTP relative) value.
    611   ///
    612   /// This is used to implement assembler directives such as .dtprelword on
    613   /// targets that support them.
    614   virtual void EmitDTPRel32Value(const MCExpr *Value);
    615 
    616   /// \brief Emit the expression \p Value into the output as a tprel
    617   /// (64-bit TP relative) value.
    618   ///
    619   /// This is used to implement assembler directives such as .tpreldword on
    620   /// targets that support them.
    621   virtual void EmitTPRel64Value(const MCExpr *Value);
    622 
    623   /// \brief Emit the expression \p Value into the output as a tprel
    624   /// (32-bit TP relative) value.
    625   ///
    626   /// This is used to implement assembler directives such as .tprelword on
    627   /// targets that support them.
    628   virtual void EmitTPRel32Value(const MCExpr *Value);
    629 
    630   /// \brief Emit the expression \p Value into the output as a gprel64 (64-bit
    631   /// GP relative) value.
    632   ///
    633   /// This is used to implement assembler directives such as .gpdword on
    634   /// targets that support them.
    635   virtual void EmitGPRel64Value(const MCExpr *Value);
    636 
    637   /// \brief Emit the expression \p Value into the output as a gprel32 (32-bit
    638   /// GP relative) value.
    639   ///
    640   /// This is used to implement assembler directives such as .gprel32 on
    641   /// targets that support them.
    642   virtual void EmitGPRel32Value(const MCExpr *Value);
    643 
    644   /// \brief Emit NumBytes bytes worth of the value specified by FillValue.
    645   /// This implements directives such as '.space'.
    646   void emitFill(uint64_t NumBytes, uint8_t FillValue);
    647 
    648   /// \brief Emit \p Size bytes worth of the value specified by \p FillValue.
    649   ///
    650   /// This is used to implement assembler directives such as .space or .skip.
    651   ///
    652   /// \param NumBytes - The number of bytes to emit.
    653   /// \param FillValue - The value to use when filling bytes.
    654   /// \param Loc - The location of the expression for error reporting.
    655   virtual void emitFill(const MCExpr &NumBytes, uint64_t FillValue,
    656                         SMLoc Loc = SMLoc());
    657 
    658   /// \brief Emit \p NumValues copies of \p Size bytes. Each \p Size bytes is
    659   /// taken from the lowest order 4 bytes of \p Expr expression.
    660   ///
    661   /// This is used to implement assembler directives such as .fill.
    662   ///
    663   /// \param NumValues - The number of copies of \p Size bytes to emit.
    664   /// \param Size - The size (in bytes) of each repeated value.
    665   /// \param Expr - The expression from which \p Size bytes are used.
    666   virtual void emitFill(uint64_t NumValues, int64_t Size, int64_t Expr);
    667   virtual void emitFill(const MCExpr &NumValues, int64_t Size, int64_t Expr,
    668                         SMLoc Loc = SMLoc());
    669 
    670   /// \brief Emit NumBytes worth of zeros.
    671   /// This function properly handles data in virtual sections.
    672   void EmitZeros(uint64_t NumBytes);
    673 
    674   /// \brief Emit some number of copies of \p Value until the byte alignment \p
    675   /// ByteAlignment is reached.
    676   ///
    677   /// If the number of bytes need to emit for the alignment is not a multiple
    678   /// of \p ValueSize, then the contents of the emitted fill bytes is
    679   /// undefined.
    680   ///
    681   /// This used to implement the .align assembler directive.
    682   ///
    683   /// \param ByteAlignment - The alignment to reach. This must be a power of
    684   /// two on some targets.
    685   /// \param Value - The value to use when filling bytes.
    686   /// \param ValueSize - The size of the integer (in bytes) to emit for
    687   /// \p Value. This must match a native machine width.
    688   /// \param MaxBytesToEmit - The maximum numbers of bytes to emit, or 0. If
    689   /// the alignment cannot be reached in this many bytes, no bytes are
    690   /// emitted.
    691   virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
    692                                     unsigned ValueSize = 1,
    693                                     unsigned MaxBytesToEmit = 0);
    694 
    695   /// \brief Emit nops until the byte alignment \p ByteAlignment is reached.
    696   ///
    697   /// This used to align code where the alignment bytes may be executed.  This
    698   /// can emit different bytes for different sizes to optimize execution.
    699   ///
    700   /// \param ByteAlignment - The alignment to reach. This must be a power of
    701   /// two on some targets.
    702   /// \param MaxBytesToEmit - The maximum numbers of bytes to emit, or 0. If
    703   /// the alignment cannot be reached in this many bytes, no bytes are
    704   /// emitted.
    705   virtual void EmitCodeAlignment(unsigned ByteAlignment,
    706                                  unsigned MaxBytesToEmit = 0);
    707 
    708   /// \brief Emit some number of copies of \p Value until the byte offset \p
    709   /// Offset is reached.
    710   ///
    711   /// This is used to implement assembler directives such as .org.
    712   ///
    713   /// \param Offset - The offset to reach. This may be an expression, but the
    714   /// expression must be associated with the current section.
    715   /// \param Value - The value to use when filling bytes.
    716   virtual void emitValueToOffset(const MCExpr *Offset, unsigned char Value,
    717                                  SMLoc Loc);
    718 
    719   /// @}
    720 
    721   /// \brief Switch to a new logical file.  This is used to implement the '.file
    722   /// "foo.c"' assembler directive.
    723   virtual void EmitFileDirective(StringRef Filename);
    724 
    725   /// \brief Emit the "identifiers" directive.  This implements the
    726   /// '.ident "version foo"' assembler directive.
    727   virtual void EmitIdent(StringRef IdentString) {}
    728 
    729   /// \brief Associate a filename with a specified logical file number.  This
    730   /// implements the DWARF2 '.file 4 "foo.c"' assembler directive.
    731   virtual unsigned EmitDwarfFileDirective(unsigned FileNo, StringRef Directory,
    732                                           StringRef Filename,
    733                                           unsigned CUID = 0);
    734 
    735   /// \brief This implements the DWARF2 '.loc fileno lineno ...' assembler
    736   /// directive.
    737   virtual void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
    738                                      unsigned Column, unsigned Flags,
    739                                      unsigned Isa, unsigned Discriminator,
    740                                      StringRef FileName);
    741 
    742   /// Associate a filename with a specified logical file number, and also
    743   /// specify that file's checksum information.  This implements the '.cv_file 4
    744   /// "foo.c"' assembler directive. Returns true on success.
    745   virtual bool EmitCVFileDirective(unsigned FileNo, StringRef Filename,
    746                                    ArrayRef<uint8_t> Checksum,
    747                                    unsigned ChecksumKind);
    748 
    749   /// \brief Introduces a function id for use with .cv_loc.
    750   virtual bool EmitCVFuncIdDirective(unsigned FunctionId);
    751 
    752   /// \brief Introduces an inline call site id for use with .cv_loc. Includes
    753   /// extra information for inline line table generation.
    754   virtual bool EmitCVInlineSiteIdDirective(unsigned FunctionId, unsigned IAFunc,
    755                                            unsigned IAFile, unsigned IALine,
    756                                            unsigned IACol, SMLoc Loc);
    757 
    758   /// \brief This implements the CodeView '.cv_loc' assembler directive.
    759   virtual void EmitCVLocDirective(unsigned FunctionId, unsigned FileNo,
    760                                   unsigned Line, unsigned Column,
    761                                   bool PrologueEnd, bool IsStmt,
    762                                   StringRef FileName, SMLoc Loc);
    763 
    764   /// \brief This implements the CodeView '.cv_linetable' assembler directive.
    765   virtual void EmitCVLinetableDirective(unsigned FunctionId,
    766                                         const MCSymbol *FnStart,
    767                                         const MCSymbol *FnEnd);
    768 
    769   /// \brief This implements the CodeView '.cv_inline_linetable' assembler
    770   /// directive.
    771   virtual void EmitCVInlineLinetableDirective(unsigned PrimaryFunctionId,
    772                                               unsigned SourceFileId,
    773                                               unsigned SourceLineNum,
    774                                               const MCSymbol *FnStartSym,
    775                                               const MCSymbol *FnEndSym);
    776 
    777   /// \brief This implements the CodeView '.cv_def_range' assembler
    778   /// directive.
    779   virtual void EmitCVDefRangeDirective(
    780       ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
    781       StringRef FixedSizePortion);
    782 
    783   /// \brief This implements the CodeView '.cv_stringtable' assembler directive.
    784   virtual void EmitCVStringTableDirective() {}
    785 
    786   /// \brief This implements the CodeView '.cv_filechecksums' assembler directive.
    787   virtual void EmitCVFileChecksumsDirective() {}
    788 
    789   /// This implements the CodeView '.cv_filechecksumoffset' assembler
    790   /// directive.
    791   virtual void EmitCVFileChecksumOffsetDirective(unsigned FileNo) {}
    792 
    793   /// This implements the CodeView '.cv_fpo_data' assembler directive.
    794   virtual void EmitCVFPOData(const MCSymbol *ProcSym, SMLoc Loc = {}) {}
    795 
    796   /// Emit the absolute difference between two symbols.
    797   ///
    798   /// \pre Offset of \c Hi is greater than the offset \c Lo.
    799   virtual void emitAbsoluteSymbolDiff(const MCSymbol *Hi, const MCSymbol *Lo,
    800                                       unsigned Size);
    801 
    802   virtual MCSymbol *getDwarfLineTableSymbol(unsigned CUID);
    803   virtual void EmitCFISections(bool EH, bool Debug);
    804   void EmitCFIStartProc(bool IsSimple);
    805   void EmitCFIEndProc();
    806   virtual void EmitCFIDefCfa(int64_t Register, int64_t Offset);
    807   virtual void EmitCFIDefCfaOffset(int64_t Offset);
    808   virtual void EmitCFIDefCfaRegister(int64_t Register);
    809   virtual void EmitCFIOffset(int64_t Register, int64_t Offset);
    810   virtual void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding);
    811   virtual void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding);
    812   virtual void EmitCFIRememberState();
    813   virtual void EmitCFIRestoreState();
    814   virtual void EmitCFISameValue(int64_t Register);
    815   virtual void EmitCFIRestore(int64_t Register);
    816   virtual void EmitCFIRelOffset(int64_t Register, int64_t Offset);
    817   virtual void EmitCFIAdjustCfaOffset(int64_t Adjustment);
    818   virtual void EmitCFIEscape(StringRef Values);
    819   virtual void EmitCFIReturnColumn(int64_t Register);
    820   virtual void EmitCFIGnuArgsSize(int64_t Size);
    821   virtual void EmitCFISignalFrame();
    822   virtual void EmitCFIUndefined(int64_t Register);
    823   virtual void EmitCFIRegister(int64_t Register1, int64_t Register2);
    824   virtual void EmitCFIWindowSave();
    825 
    826   virtual void EmitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc = SMLoc());
    827   virtual void EmitWinCFIEndProc(SMLoc Loc = SMLoc());
    828   virtual void EmitWinCFIStartChained(SMLoc Loc = SMLoc());
    829   virtual void EmitWinCFIEndChained(SMLoc Loc = SMLoc());
    830   virtual void EmitWinCFIPushReg(unsigned Register, SMLoc Loc = SMLoc());
    831   virtual void EmitWinCFISetFrame(unsigned Register, unsigned Offset,
    832                                   SMLoc Loc = SMLoc());
    833   virtual void EmitWinCFIAllocStack(unsigned Size, SMLoc Loc = SMLoc());
    834   virtual void EmitWinCFISaveReg(unsigned Register, unsigned Offset,
    835                                  SMLoc Loc = SMLoc());
    836   virtual void EmitWinCFISaveXMM(unsigned Register, unsigned Offset,
    837                                  SMLoc Loc = SMLoc());
    838   virtual void EmitWinCFIPushFrame(bool Code, SMLoc Loc = SMLoc());
    839   virtual void EmitWinCFIEndProlog(SMLoc Loc = SMLoc());
    840   virtual void EmitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except,
    841                                 SMLoc Loc = SMLoc());
    842   virtual void EmitWinEHHandlerData(SMLoc Loc = SMLoc());
    843 
    844   /// Get the .pdata section used for the given section. Typically the given
    845   /// section is either the main .text section or some other COMDAT .text
    846   /// section, but it may be any section containing code.
    847   MCSection *getAssociatedPDataSection(const MCSection *TextSec);
    848 
    849   /// Get the .xdata section used for the given section.
    850   MCSection *getAssociatedXDataSection(const MCSection *TextSec);
    851 
    852   virtual void EmitSyntaxDirective();
    853 
    854   /// \brief Emit a .reloc directive.
    855   /// Returns true if the relocation could not be emitted because Name is not
    856   /// known.
    857   virtual bool EmitRelocDirective(const MCExpr &Offset, StringRef Name,
    858                                   const MCExpr *Expr, SMLoc Loc) {
    859     return true;
    860   }
    861 
    862   /// \brief Emit the given \p Instruction into the current section.
    863   /// PrintSchedInfo == true then schedul comment should be added to output
    864   virtual void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
    865                                bool PrintSchedInfo = false);
    866 
    867   /// \brief Set the bundle alignment mode from now on in the section.
    868   /// The argument is the power of 2 to which the alignment is set. The
    869   /// value 0 means turn the bundle alignment off.
    870   virtual void EmitBundleAlignMode(unsigned AlignPow2);
    871 
    872   /// \brief The following instructions are a bundle-locked group.
    873   ///
    874   /// \param AlignToEnd - If true, the bundle-locked group will be aligned to
    875   ///                     the end of a bundle.
    876   virtual void EmitBundleLock(bool AlignToEnd);
    877 
    878   /// \brief Ends a bundle-locked group.
    879   virtual void EmitBundleUnlock();
    880 
    881   /// \brief If this file is backed by a assembly streamer, this dumps the
    882   /// specified string in the output .s file.  This capability is indicated by
    883   /// the hasRawTextSupport() predicate.  By default this aborts.
    884   void EmitRawText(const Twine &String);
    885 
    886   /// \brief Streamer specific finalization.
    887   virtual void FinishImpl();
    888   /// \brief Finish emission of machine code.
    889   void Finish();
    890 
    891   virtual bool mayHaveInstructions(MCSection &Sec) const { return true; }
    892 };
    893 
    894 /// Create a dummy machine code streamer, which does nothing. This is useful for
    895 /// timing the assembler front end.
    896 MCStreamer *createNullStreamer(MCContext &Ctx);
    897 
    898 /// Create a machine code streamer which will print out assembly for the native
    899 /// target, suitable for compiling with a native assembler.
    900 ///
    901 /// \param InstPrint - If given, the instruction printer to use. If not given
    902 /// the MCInst representation will be printed.  This method takes ownership of
    903 /// InstPrint.
    904 ///
    905 /// \param CE - If given, a code emitter to use to show the instruction
    906 /// encoding inline with the assembly. This method takes ownership of \p CE.
    907 ///
    908 /// \param TAB - If given, a target asm backend to use to show the fixup
    909 /// information in conjunction with encoding information. This method takes
    910 /// ownership of \p TAB.
    911 ///
    912 /// \param ShowInst - Whether to show the MCInst representation inline with
    913 /// the assembly.
    914 MCStreamer *createAsmStreamer(MCContext &Ctx,
    915                               std::unique_ptr<formatted_raw_ostream> OS,
    916                               bool isVerboseAsm, bool useDwarfDirectory,
    917                               MCInstPrinter *InstPrint, MCCodeEmitter *CE,
    918                               MCAsmBackend *TAB, bool ShowInst);
    919 
    920 } // end namespace llvm
    921 
    922 #endif // LLVM_MC_MCSTREAMER_H
    923