1//===-- llvm/CodeGen/JITCodeEmitter.h - Code emission ----------*- 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 defines an abstract interface that is used by the machine code
11// emission framework to output the code.  This allows machine code emission to
12// be separated from concerns such as resolution of call targets, and where the
13// machine code will be written (memory or disk, f.e.).
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_CODEGEN_JITCODEEMITTER_H
18#define LLVM_CODEGEN_JITCODEEMITTER_H
19
20#include <string>
21#include "llvm/Support/DataTypes.h"
22#include "llvm/Support/MathExtras.h"
23#include "llvm/CodeGen/MachineCodeEmitter.h"
24#include "llvm/ADT/DenseMap.h"
25
26namespace llvm {
27
28class MachineBasicBlock;
29class MachineConstantPool;
30class MachineJumpTableInfo;
31class MachineFunction;
32class MachineModuleInfo;
33class MachineRelocation;
34class Value;
35class GlobalValue;
36class Function;
37
38/// JITCodeEmitter - This class defines two sorts of methods: those for
39/// emitting the actual bytes of machine code, and those for emitting auxiliary
40/// structures, such as jump tables, relocations, etc.
41///
42/// Emission of machine code is complicated by the fact that we don't (in
43/// general) know the size of the machine code that we're about to emit before
44/// we emit it.  As such, we preallocate a certain amount of memory, and set the
45/// BufferBegin/BufferEnd pointers to the start and end of the buffer.  As we
46/// emit machine instructions, we advance the CurBufferPtr to indicate the
47/// location of the next byte to emit.  In the case of a buffer overflow (we
48/// need to emit more machine code than we have allocated space for), the
49/// CurBufferPtr will saturate to BufferEnd and ignore stores.  Once the entire
50/// function has been emitted, the overflow condition is checked, and if it has
51/// occurred, more memory is allocated, and we reemit the code into it.
52///
53class JITCodeEmitter : public MachineCodeEmitter {
54  virtual void anchor();
55public:
56  virtual ~JITCodeEmitter() {}
57
58  /// startFunction - This callback is invoked when the specified function is
59  /// about to be code generated.  This initializes the BufferBegin/End/Ptr
60  /// fields.
61  ///
62  virtual void startFunction(MachineFunction &F) = 0;
63
64  /// finishFunction - This callback is invoked when the specified function has
65  /// finished code generation.  If a buffer overflow has occurred, this method
66  /// returns true (the callee is required to try again), otherwise it returns
67  /// false.
68  ///
69  virtual bool finishFunction(MachineFunction &F) = 0;
70
71  /// allocIndirectGV - Allocates and fills storage for an indirect
72  /// GlobalValue, and returns the address.
73  virtual void *allocIndirectGV(const GlobalValue *GV,
74                                const uint8_t *Buffer, size_t Size,
75                                unsigned Alignment) = 0;
76
77  /// emitByte - This callback is invoked when a byte needs to be written to the
78  /// output stream.
79  ///
80  void emitByte(uint8_t B) {
81    if (CurBufferPtr != BufferEnd)
82      *CurBufferPtr++ = B;
83  }
84
85  /// emitWordLE - This callback is invoked when a 32-bit word needs to be
86  /// written to the output stream in little-endian format.
87  ///
88  void emitWordLE(uint32_t W) {
89    if (4 <= BufferEnd-CurBufferPtr) {
90      *CurBufferPtr++ = (uint8_t)(W >>  0);
91      *CurBufferPtr++ = (uint8_t)(W >>  8);
92      *CurBufferPtr++ = (uint8_t)(W >> 16);
93      *CurBufferPtr++ = (uint8_t)(W >> 24);
94    } else {
95      CurBufferPtr = BufferEnd;
96    }
97  }
98
99  /// emitWordBE - This callback is invoked when a 32-bit word needs to be
100  /// written to the output stream in big-endian format.
101  ///
102  void emitWordBE(uint32_t W) {
103    if (4 <= BufferEnd-CurBufferPtr) {
104      *CurBufferPtr++ = (uint8_t)(W >> 24);
105      *CurBufferPtr++ = (uint8_t)(W >> 16);
106      *CurBufferPtr++ = (uint8_t)(W >>  8);
107      *CurBufferPtr++ = (uint8_t)(W >>  0);
108    } else {
109      CurBufferPtr = BufferEnd;
110    }
111  }
112
113  /// emitDWordLE - This callback is invoked when a 64-bit word needs to be
114  /// written to the output stream in little-endian format.
115  ///
116  void emitDWordLE(uint64_t W) {
117    if (8 <= BufferEnd-CurBufferPtr) {
118      *CurBufferPtr++ = (uint8_t)(W >>  0);
119      *CurBufferPtr++ = (uint8_t)(W >>  8);
120      *CurBufferPtr++ = (uint8_t)(W >> 16);
121      *CurBufferPtr++ = (uint8_t)(W >> 24);
122      *CurBufferPtr++ = (uint8_t)(W >> 32);
123      *CurBufferPtr++ = (uint8_t)(W >> 40);
124      *CurBufferPtr++ = (uint8_t)(W >> 48);
125      *CurBufferPtr++ = (uint8_t)(W >> 56);
126    } else {
127      CurBufferPtr = BufferEnd;
128    }
129  }
130
131  /// emitDWordBE - This callback is invoked when a 64-bit word needs to be
132  /// written to the output stream in big-endian format.
133  ///
134  void emitDWordBE(uint64_t W) {
135    if (8 <= BufferEnd-CurBufferPtr) {
136      *CurBufferPtr++ = (uint8_t)(W >> 56);
137      *CurBufferPtr++ = (uint8_t)(W >> 48);
138      *CurBufferPtr++ = (uint8_t)(W >> 40);
139      *CurBufferPtr++ = (uint8_t)(W >> 32);
140      *CurBufferPtr++ = (uint8_t)(W >> 24);
141      *CurBufferPtr++ = (uint8_t)(W >> 16);
142      *CurBufferPtr++ = (uint8_t)(W >>  8);
143      *CurBufferPtr++ = (uint8_t)(W >>  0);
144    } else {
145      CurBufferPtr = BufferEnd;
146    }
147  }
148
149  /// emitAlignment - Move the CurBufferPtr pointer up to the specified
150  /// alignment (saturated to BufferEnd of course).
151  void emitAlignment(unsigned Alignment) {
152    if (Alignment == 0) Alignment = 1;
153    uint8_t *NewPtr = (uint8_t*)RoundUpToAlignment((uintptr_t)CurBufferPtr,
154                                                   Alignment);
155    CurBufferPtr = std::min(NewPtr, BufferEnd);
156  }
157
158  /// emitAlignmentWithFill - Similar to emitAlignment, except that the
159  /// extra bytes are filled with the provided byte.
160  void emitAlignmentWithFill(unsigned Alignment, uint8_t Fill) {
161    if (Alignment == 0) Alignment = 1;
162    uint8_t *NewPtr = (uint8_t*)RoundUpToAlignment((uintptr_t)CurBufferPtr,
163                                                   Alignment);
164    // Fail if we don't have room.
165    if (NewPtr > BufferEnd) {
166      CurBufferPtr = BufferEnd;
167      return;
168    }
169    while (CurBufferPtr < NewPtr) {
170      *CurBufferPtr++ = Fill;
171    }
172  }
173
174  /// emitULEB128Bytes - This callback is invoked when a ULEB128 needs to be
175  /// written to the output stream.
176  void emitULEB128Bytes(uint64_t Value, unsigned PadTo = 0) {
177    do {
178      uint8_t Byte = Value & 0x7f;
179      Value >>= 7;
180      if (Value || PadTo != 0) Byte |= 0x80;
181      emitByte(Byte);
182    } while (Value);
183
184    if (PadTo) {
185      do {
186        uint8_t Byte = (PadTo > 1) ? 0x80 : 0x0;
187        emitByte(Byte);
188      } while (--PadTo);
189    }
190  }
191
192  /// emitSLEB128Bytes - This callback is invoked when a SLEB128 needs to be
193  /// written to the output stream.
194  void emitSLEB128Bytes(int64_t Value) {
195    int32_t Sign = Value >> (8 * sizeof(Value) - 1);
196    bool IsMore;
197
198    do {
199      uint8_t Byte = Value & 0x7f;
200      Value >>= 7;
201      IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
202      if (IsMore) Byte |= 0x80;
203      emitByte(Byte);
204    } while (IsMore);
205  }
206
207  /// emitString - This callback is invoked when a String needs to be
208  /// written to the output stream.
209  void emitString(const std::string &String) {
210    for (unsigned i = 0, N = static_cast<unsigned>(String.size());
211         i < N; ++i) {
212      uint8_t C = String[i];
213      emitByte(C);
214    }
215    emitByte(0);
216  }
217
218  /// emitInt32 - Emit a int32 directive.
219  void emitInt32(uint32_t Value) {
220    if (4 <= BufferEnd-CurBufferPtr) {
221      *((uint32_t*)CurBufferPtr) = Value;
222      CurBufferPtr += 4;
223    } else {
224      CurBufferPtr = BufferEnd;
225    }
226  }
227
228  /// emitInt64 - Emit a int64 directive.
229  void emitInt64(uint64_t Value) {
230    if (8 <= BufferEnd-CurBufferPtr) {
231      *((uint64_t*)CurBufferPtr) = Value;
232      CurBufferPtr += 8;
233    } else {
234      CurBufferPtr = BufferEnd;
235    }
236  }
237
238  /// emitInt32At - Emit the Int32 Value in Addr.
239  void emitInt32At(uintptr_t *Addr, uintptr_t Value) {
240    if (Addr >= (uintptr_t*)BufferBegin && Addr < (uintptr_t*)BufferEnd)
241      (*(uint32_t*)Addr) = (uint32_t)Value;
242  }
243
244  /// emitInt64At - Emit the Int64 Value in Addr.
245  void emitInt64At(uintptr_t *Addr, uintptr_t Value) {
246    if (Addr >= (uintptr_t*)BufferBegin && Addr < (uintptr_t*)BufferEnd)
247      (*(uint64_t*)Addr) = (uint64_t)Value;
248  }
249
250
251  /// emitLabel - Emits a label
252  virtual void emitLabel(MCSymbol *Label) = 0;
253
254  /// allocateSpace - Allocate a block of space in the current output buffer,
255  /// returning null (and setting conditions to indicate buffer overflow) on
256  /// failure.  Alignment is the alignment in bytes of the buffer desired.
257  virtual void *allocateSpace(uintptr_t Size, unsigned Alignment) {
258    emitAlignment(Alignment);
259    void *Result;
260
261    // Check for buffer overflow.
262    if (Size >= (uintptr_t)(BufferEnd-CurBufferPtr)) {
263      CurBufferPtr = BufferEnd;
264      Result = 0;
265    } else {
266      // Allocate the space.
267      Result = CurBufferPtr;
268      CurBufferPtr += Size;
269    }
270
271    return Result;
272  }
273
274  /// allocateGlobal - Allocate memory for a global.  Unlike allocateSpace,
275  /// this method does not allocate memory in the current output buffer,
276  /// because a global may live longer than the current function.
277  virtual void *allocateGlobal(uintptr_t Size, unsigned Alignment) = 0;
278
279  /// StartMachineBasicBlock - This should be called by the target when a new
280  /// basic block is about to be emitted.  This way the MCE knows where the
281  /// start of the block is, and can implement getMachineBasicBlockAddress.
282  virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) = 0;
283
284  /// getCurrentPCValue - This returns the address that the next emitted byte
285  /// will be output to.
286  ///
287  virtual uintptr_t getCurrentPCValue() const {
288    return (uintptr_t)CurBufferPtr;
289  }
290
291  /// getCurrentPCOffset - Return the offset from the start of the emitted
292  /// buffer that we are currently writing to.
293  uintptr_t getCurrentPCOffset() const {
294    return CurBufferPtr-BufferBegin;
295  }
296
297  /// earlyResolveAddresses - True if the code emitter can use symbol addresses
298  /// during code emission time. The JIT is capable of doing this because it
299  /// creates jump tables or constant pools in memory on the fly while the
300  /// object code emitters rely on a linker to have real addresses and should
301  /// use relocations instead.
302  bool earlyResolveAddresses() const { return true; }
303
304  /// addRelocation - Whenever a relocatable address is needed, it should be
305  /// noted with this interface.
306  virtual void addRelocation(const MachineRelocation &MR) = 0;
307
308  /// FIXME: These should all be handled with relocations!
309
310  /// getConstantPoolEntryAddress - Return the address of the 'Index' entry in
311  /// the constant pool that was last emitted with the emitConstantPool method.
312  ///
313  virtual uintptr_t getConstantPoolEntryAddress(unsigned Index) const = 0;
314
315  /// getJumpTableEntryAddress - Return the address of the jump table with index
316  /// 'Index' in the function that last called initJumpTableInfo.
317  ///
318  virtual uintptr_t getJumpTableEntryAddress(unsigned Index) const = 0;
319
320  /// getMachineBasicBlockAddress - Return the address of the specified
321  /// MachineBasicBlock, only usable after the label for the MBB has been
322  /// emitted.
323  ///
324  virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const= 0;
325
326  /// getLabelAddress - Return the address of the specified Label, only usable
327  /// after the Label has been emitted.
328  ///
329  virtual uintptr_t getLabelAddress(MCSymbol *Label) const = 0;
330
331  /// Specifies the MachineModuleInfo object. This is used for exception handling
332  /// purposes.
333  virtual void setModuleInfo(MachineModuleInfo* Info) = 0;
334
335  /// getLabelLocations - Return the label locations map of the label IDs to
336  /// their address.
337  virtual DenseMap<MCSymbol*, uintptr_t> *getLabelLocations() { return 0; }
338};
339
340} // End llvm namespace
341
342#endif
343