1 //===- llvm/MC/MCAsmBackend.h - MC Asm Backend ------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef LLVM_MC_MCASMBACKEND_H
10 #define LLVM_MC_MCASMBACKEND_H
11 
12 #include "llvm/ADT/ArrayRef.h"
13 #include "llvm/ADT/Optional.h"
14 #include "llvm/ADT/StringRef.h"
15 #include "llvm/MC/MCDirectives.h"
16 #include "llvm/MC/MCFixup.h"
17 #include "llvm/MC/MCFragment.h"
18 #include "llvm/Support/Endian.h"
19 #include <cstdint>
20 
21 namespace llvm {
22 
23 class MCAsmLayout;
24 class MCAssembler;
25 class MCCFIInstruction;
26 struct MCFixupKindInfo;
27 class MCFragment;
28 class MCInst;
29 class MCObjectStreamer;
30 class MCObjectTargetWriter;
31 class MCObjectWriter;
32 class MCRelaxableFragment;
33 class MCSubtargetInfo;
34 class MCValue;
35 class raw_pwrite_stream;
36 
37 /// Generic interface to target specific assembler backends.
38 class MCAsmBackend {
39 protected: // Can only create subclasses.
40   MCAsmBackend(support::endianness Endian);
41 
42 public:
43   MCAsmBackend(const MCAsmBackend &) = delete;
44   MCAsmBackend &operator=(const MCAsmBackend &) = delete;
45   virtual ~MCAsmBackend();
46 
47   const support::endianness Endian;
48 
49   /// Return true if this target might automatically pad instructions and thus
50   /// need to emit padding enable/disable directives around sensative code.
allowAutoPadding()51   virtual bool allowAutoPadding() const { return false; }
52 
53   /// Give the target a chance to manipulate state related to instruction
54   /// alignment (e.g. padding for optimization) before and after actually
55   /// emitting the instruction.
alignBranchesBegin(MCObjectStreamer & OS,const MCInst & Inst)56   virtual void alignBranchesBegin(MCObjectStreamer &OS, const MCInst &Inst) {}
alignBranchesEnd(MCObjectStreamer & OS,const MCInst & Inst)57   virtual void alignBranchesEnd(MCObjectStreamer &OS, const MCInst &Inst) {}
58 
59   /// lifetime management
reset()60   virtual void reset() {}
61 
62   /// Create a new MCObjectWriter instance for use by the assembler backend to
63   /// emit the final object file.
64   std::unique_ptr<MCObjectWriter>
65   createObjectWriter(raw_pwrite_stream &OS) const;
66 
67   /// Create an MCObjectWriter that writes two object files: a .o file which is
68   /// linked into the final program and a .dwo file which is used by debuggers.
69   /// This function is only supported with ELF targets.
70   std::unique_ptr<MCObjectWriter>
71   createDwoObjectWriter(raw_pwrite_stream &OS, raw_pwrite_stream &DwoOS) const;
72 
73   virtual std::unique_ptr<MCObjectTargetWriter>
74   createObjectTargetWriter() const = 0;
75 
76   /// \name Target Fixup Interfaces
77   /// @{
78 
79   /// Get the number of target specific fixup kinds.
80   virtual unsigned getNumFixupKinds() const = 0;
81 
82   /// Map a relocation name used in .reloc to a fixup kind.
83   virtual Optional<MCFixupKind> getFixupKind(StringRef Name) const;
84 
85   /// Get information on a fixup kind.
86   virtual const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const;
87 
88   /// Hook to check if a relocation is needed for some target specific reason.
shouldForceRelocation(const MCAssembler & Asm,const MCFixup & Fixup,const MCValue & Target)89   virtual bool shouldForceRelocation(const MCAssembler &Asm,
90                                      const MCFixup &Fixup,
91                                      const MCValue &Target) {
92     return false;
93   }
94 
95   /// Hook to check if extra nop bytes must be inserted for alignment directive.
96   /// For some targets this may be necessary in order to support linker
97   /// relaxation. The number of bytes to insert are returned in Size.
shouldInsertExtraNopBytesForCodeAlign(const MCAlignFragment & AF,unsigned & Size)98   virtual bool shouldInsertExtraNopBytesForCodeAlign(const MCAlignFragment &AF,
99                                                      unsigned &Size) {
100     return false;
101   }
102 
103   /// Hook which indicates if the target requires a fixup to be generated when
104   /// handling an align directive in an executable section
shouldInsertFixupForCodeAlign(MCAssembler & Asm,const MCAsmLayout & Layout,MCAlignFragment & AF)105   virtual bool shouldInsertFixupForCodeAlign(MCAssembler &Asm,
106                                              const MCAsmLayout &Layout,
107                                              MCAlignFragment &AF) {
108     return false;
109   }
110 
evaluateTargetFixup(const MCAssembler & Asm,const MCAsmLayout & Layout,const MCFixup & Fixup,const MCFragment * DF,const MCValue & Target,uint64_t & Value,bool & WasForced)111   virtual bool evaluateTargetFixup(const MCAssembler &Asm,
112                                    const MCAsmLayout &Layout,
113                                    const MCFixup &Fixup, const MCFragment *DF,
114                                    const MCValue &Target, uint64_t &Value,
115                                    bool &WasForced) {
116     llvm_unreachable("Need to implement hook if target has custom fixups");
117   }
118 
119   /// Apply the \p Value for given \p Fixup into the provided data fragment, at
120   /// the offset specified by the fixup and following the fixup kind as
121   /// appropriate. Errors (such as an out of range fixup value) should be
122   /// reported via \p Ctx.
123   /// The  \p STI is present only for fragments of type MCRelaxableFragment and
124   /// MCDataFragment with hasInstructions() == true.
125   virtual void applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,
126                           const MCValue &Target, MutableArrayRef<char> Data,
127                           uint64_t Value, bool IsResolved,
128                           const MCSubtargetInfo *STI) const = 0;
129 
130   /// Check whether the given target requires emitting differences of two
131   /// symbols as a set of relocations.
requiresDiffExpressionRelocations()132   virtual bool requiresDiffExpressionRelocations() const { return false; }
133 
134   /// @}
135 
136   /// \name Target Relaxation Interfaces
137   /// @{
138 
139   /// Check whether the given instruction may need relaxation.
140   ///
141   /// \param Inst - The instruction to test.
142   /// \param STI - The MCSubtargetInfo in effect when the instruction was
143   /// encoded.
144   virtual bool mayNeedRelaxation(const MCInst &Inst,
145                                  const MCSubtargetInfo &STI) const = 0;
146 
147   /// Target specific predicate for whether a given fixup requires the
148   /// associated instruction to be relaxed.
149   virtual bool fixupNeedsRelaxationAdvanced(const MCFixup &Fixup, bool Resolved,
150                                             uint64_t Value,
151                                             const MCRelaxableFragment *DF,
152                                             const MCAsmLayout &Layout,
153                                             const bool WasForced) const;
154 
155   /// Simple predicate for targets where !Resolved implies requiring relaxation
156   virtual bool fixupNeedsRelaxation(const MCFixup &Fixup, uint64_t Value,
157                                     const MCRelaxableFragment *DF,
158                                     const MCAsmLayout &Layout) const = 0;
159 
160   /// Relax the instruction in the given fragment to the next wider instruction.
161   ///
162   /// \param Inst The instruction to relax, which may be the same as the
163   /// output.
164   /// \param STI the subtarget information for the associated instruction.
165   /// \param [out] Res On return, the relaxed instruction.
166   virtual void relaxInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
167                                 MCInst &Res) const = 0;
168 
169   /// @}
170 
171   /// Returns the minimum size of a nop in bytes on this target. The assembler
172   /// will use this to emit excess padding in situations where the padding
173   /// required for simple alignment would be less than the minimum nop size.
174   ///
getMinimumNopSize()175   virtual unsigned getMinimumNopSize() const { return 1; }
176 
177   /// Write an (optimal) nop sequence of Count bytes to the given output. If the
178   /// target cannot generate such a sequence, it should return an error.
179   ///
180   /// \return - True on success.
181   virtual bool writeNopData(raw_ostream &OS, uint64_t Count) const = 0;
182 
183   /// Give backend an opportunity to finish layout after relaxation
finishLayout(MCAssembler const & Asm,MCAsmLayout & Layout)184   virtual void finishLayout(MCAssembler const &Asm,
185                             MCAsmLayout &Layout) const {}
186 
187   /// Handle any target-specific assembler flags. By default, do nothing.
handleAssemblerFlag(MCAssemblerFlag Flag)188   virtual void handleAssemblerFlag(MCAssemblerFlag Flag) {}
189 
190   /// Generate the compact unwind encoding for the CFI instructions.
191   virtual uint32_t
generateCompactUnwindEncoding(ArrayRef<MCCFIInstruction>)192       generateCompactUnwindEncoding(ArrayRef<MCCFIInstruction>) const {
193     return 0;
194   }
195 
196   /// Check whether a given symbol has been flagged with MICROMIPS flag.
isMicroMips(const MCSymbol * Sym)197   virtual bool isMicroMips(const MCSymbol *Sym) const {
198     return false;
199   }
200 };
201 
202 } // end namespace llvm
203 
204 #endif // LLVM_MC_MCASMBACKEND_H
205