x86compiler.cpp 12 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
// [AsmJit]
// Complete x86/x64 JIT and Remote Assembler for C++.
//
// [License]
// Zlib - See LICENSE.md file in the package.

// [Export]
#define ASMJIT_EXPORTS

// [Guard]
11
12
#include "../asmjit_build.h"
#if defined(ASMJIT_BUILD_X86) && !defined(ASMJIT_DISABLE_COMPILER)
13

14
15
// [Dependencies]
#include "../base/utils.h"
16
#include "../x86/x86compiler.h"
17
#include "../x86/x86regalloc_p.h"
18
19

// [Api-Begin]
20
#include "../asmjit_apibegin.h"
21
22
23
24

namespace asmjit {

// ============================================================================
25
// [asmjit::X86Compiler - Construction / Destruction]
26
27
// ============================================================================

28
29
30
31
32
X86Compiler::X86Compiler(CodeHolder* code) noexcept : CodeCompiler() {
  if (code)
    code->attach(this);
}
X86Compiler::~X86Compiler() noexcept {}
33
34

// ============================================================================
35
// [asmjit::X86Compiler - Events]
36
37
// ============================================================================

38
39
40
41
Error X86Compiler::onAttach(CodeHolder* code) noexcept {
  uint32_t archType = code->getArchType();
  if (!ArchInfo::isX86Family(archType))
    return DebugUtils::errored(kErrorInvalidArch);
42

43
44
  ASMJIT_PROPAGATE(_cbPasses.willGrow(&_cbHeap, 1));
  ASMJIT_PROPAGATE(Base::onAttach(code));
45

46
47
48
49
50
  if (archType == ArchInfo::kTypeX86)
    _nativeGpArray = x86OpData.gpd;
  else
    _nativeGpArray = x86OpData.gpq;
  _nativeGpReg = _nativeGpArray[0];
51

52
  return addPassT<X86RAPass>();
53
54
55
}

// ============================================================================
56
// [asmjit::X86Compiler - Finalize]
57
58
// ============================================================================

59
60
Error X86Compiler::finalize() {
  if (_lastError) return _lastError;
61

62
63
64
65
  // Flush the global constant pool.
  if (_globalConstPool) {
    addNode(_globalConstPool);
    _globalConstPool = nullptr;
66
67
  }

68
69
  Error err = kErrorOk;
  ZoneVector<CBPass*>& passes = _cbPasses;
70

71
72
73
74
75
  for (size_t i = 0, len = passes.getLength(); i < len; i++) {
    CBPass* pass = passes[i];
    err = pass->process(&_cbPassZone);
    _cbPassZone.reset();
    if (err) break;
76
77
  }

78
79
  _cbPassZone.reset();
  if (ASMJIT_UNLIKELY(err)) return setLastError(err);
80

81
82
83
  // TODO: There must be possibility to attach more assemblers, this is not so nice.
  if (_code->_cgAsm) {
    return serialize(_code->_cgAsm);
84
  }
85
86
87
  else {
    X86Assembler a(_code);
    return serialize(&a);
88
89
90
91
  }
}

// ============================================================================
92
// [asmjit::X86Compiler - Inst]
93
94
// ============================================================================

95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
static ASMJIT_INLINE bool isJumpInst(uint32_t instId) noexcept {
  return (instId >= X86Inst::kIdJa   && instId <= X86Inst::kIdJz    ) ||
         (instId >= X86Inst::kIdLoop && instId <= X86Inst::kIdLoopne) ;
}

Error X86Compiler::_emit(uint32_t instId, const Operand_& o0, const Operand_& o1, const Operand_& o2, const Operand_& o3) {
  uint32_t options = getOptions() | getGlobalOptions();
  const char* inlineComment = getInlineComment();

  uint32_t opCount = static_cast<uint32_t>(!o0.isNone()) +
                     static_cast<uint32_t>(!o1.isNone()) +
                     static_cast<uint32_t>(!o2.isNone()) +
                     static_cast<uint32_t>(!o3.isNone()) ;

  // Handle failure and rare cases first.
  const uint32_t kErrorsAndSpecialCases = kOptionMaybeFailureCase | // CodeEmitter is in error state.
                                          kOptionStrictValidation ; // Strict validation.

  if (ASMJIT_UNLIKELY(options & kErrorsAndSpecialCases)) {
    // Don't do anything if we are in error state.
    if (_lastError) return _lastError;

#if !defined(ASMJIT_DISABLE_VALIDATION)
    // Strict validation.
    if (options & kOptionStrictValidation) {
      Operand opArray[] = {
        Operand(o0),
        Operand(o1),
        Operand(o2),
        Operand(o3)
      };

      Inst::Detail instDetail(instId, options, _extraReg);
      Error err = Inst::validate(getArchType(), instDetail, opArray, opCount);

      if (err) {
#if !defined(ASMJIT_DISABLE_LOGGING)
        StringBuilderTmp<256> sb;
        sb.appendString(DebugUtils::errorAsString(err));
        sb.appendString(": ");
        Logging::formatInstruction(sb, 0, this, getArchType(), instDetail, opArray, opCount);
        return setLastError(err, sb.getData());
#else
        return setLastError(err);
#endif
      }
141

142
143
144
145
      // Clear it as it must be enabled explicitly on assembler side.
      options &= ~kOptionStrictValidation;
    }
#endif // ASMJIT_DISABLE_VALIDATION
146
147
  }

148
149
  resetOptions();
  resetInlineComment();
150

151
152
153
154
  // decide between `CBInst` and `CBJump`.
  if (isJumpInst(instId)) {
    CBJump* node = _cbHeap.allocT<CBJump>(sizeof(CBJump) + opCount * sizeof(Operand));
    Operand* opArray = reinterpret_cast<Operand*>(reinterpret_cast<uint8_t*>(node) + sizeof(CBJump));
155

156
157
    if (ASMJIT_UNLIKELY(!node))
      return setLastError(DebugUtils::errored(kErrorNoHeapMemory));
158

159
160
161
162
    if (opCount > 0) opArray[0].copyFrom(o0);
    if (opCount > 1) opArray[1].copyFrom(o1);
    if (opCount > 2) opArray[2].copyFrom(o2);
    if (opCount > 3) opArray[3].copyFrom(o3);
163

164
165
166
    new(node) CBJump(this, instId, options, opArray, opCount);
    node->_instDetail.extraReg = _extraReg;
    _extraReg.reset();
167

168
169
170
171
172
173
174
175
176
177
178
    CBLabel* jTarget = nullptr;
    if (!(options & kOptionUnfollow)) {
      if (opArray[0].isLabel()) {
        Error err = getCBLabel(&jTarget, static_cast<Label&>(opArray[0]));
        if (err) return setLastError(err);
      }
      else {
        options |= kOptionUnfollow;
      }
    }
    node->setOptions(options);
179

180
    node->orFlags(instId == X86Inst::kIdJmp ? CBNode::kFlagIsJmp | CBNode::kFlagIsTaken : CBNode::kFlagIsJcc);
181
    node->_target = jTarget;
182
    node->_jumpNext = nullptr;
183

184
185
186
187
188
    if (jTarget) {
      node->_jumpNext = static_cast<CBJump*>(jTarget->_from);
      jTarget->_from = node;
      jTarget->addNumRefs();
    }
189
190

    // The 'jmp' is always taken, conditional jump can contain hint, we detect it.
191
192
193
194
195
196
197
198
199
    if (instId == X86Inst::kIdJmp)
      node->orFlags(CBNode::kFlagIsTaken);
    else if (options & X86Inst::kOptionTaken)
      node->orFlags(CBNode::kFlagIsTaken);

    if (inlineComment) {
      inlineComment = static_cast<char*>(_cbDataZone.dup(inlineComment, ::strlen(inlineComment), true));
      node->setInlineComment(inlineComment);
    }
200

201
202
    addNode(node);
    return kErrorOk;
203
204
  }
  else {
205
206
    CBInst* node = _cbHeap.allocT<CBInst>(sizeof(CBInst) + opCount * sizeof(Operand));
    Operand* opArray = reinterpret_cast<Operand*>(reinterpret_cast<uint8_t*>(node) + sizeof(CBInst));
207

208
209
    if (ASMJIT_UNLIKELY(!node))
      return setLastError(DebugUtils::errored(kErrorNoHeapMemory));
210

211
212
213
214
    if (opCount > 0) opArray[0].copyFrom(o0);
    if (opCount > 1) opArray[1].copyFrom(o1);
    if (opCount > 2) opArray[2].copyFrom(o2);
    if (opCount > 3) opArray[3].copyFrom(o3);
215

216
217
218
    node = new(node) CBInst(this, instId, options, opArray, opCount);
    node->_instDetail.extraReg = _extraReg;
    _extraReg.reset();
219

220
221
222
223
    if (inlineComment) {
      inlineComment = static_cast<char*>(_cbDataZone.dup(inlineComment, ::strlen(inlineComment), true));
      node->setInlineComment(inlineComment);
    }
224

225
226
    addNode(node);
    return kErrorOk;
227
228
229
  }
}

230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
Error X86Compiler::_emit(uint32_t instId, const Operand_& o0, const Operand_& o1, const Operand_& o2, const Operand_& o3, const Operand_& o4, const Operand_& o5) {
  uint32_t options = getOptions() | getGlobalOptions();
  const char* inlineComment = getInlineComment();

  uint32_t opCount = static_cast<uint32_t>(!o0.isNone()) +
                     static_cast<uint32_t>(!o1.isNone()) +
                     static_cast<uint32_t>(!o2.isNone()) +
                     static_cast<uint32_t>(!o3.isNone()) ;

  // Count 5th and 6th operands.
  if (!o4.isNone()) opCount = 5;
  if (!o5.isNone()) opCount = 6;

  // Handle failure and rare cases first.
  const uint32_t kErrorsAndSpecialCases = kOptionMaybeFailureCase | // CodeEmitter in error state.
                                          kOptionStrictValidation ; // Strict validation.

  if (ASMJIT_UNLIKELY(options & kErrorsAndSpecialCases)) {
    // Don't do anything if we are in error state.
    if (_lastError) return _lastError;

#if !defined(ASMJIT_DISABLE_VALIDATION)
    // Strict validation.
    if (options & kOptionStrictValidation) {
      Operand opArray[] = {
        Operand(o0),
        Operand(o1),
        Operand(o2),
        Operand(o3),
        Operand(o4),
        Operand(o5)
      };

      Inst::Detail instDetail(instId, options, _extraReg);
      Error err = Inst::validate(getArchType(), instDetail, opArray, opCount);

      if (err) {
#if !defined(ASMJIT_DISABLE_LOGGING)
        StringBuilderTmp<256> sb;
        sb.appendString(DebugUtils::errorAsString(err));
        sb.appendString(": ");
        Logging::formatInstruction(sb, 0, this, getArchType(), instDetail, opArray, opCount);
        return setLastError(err, sb.getData());
#else
        return setLastError(err);
#endif
      }
277

278
279
280
281
      // Clear it as it must be enabled explicitly on assembler side.
      options &= ~kOptionStrictValidation;
    }
#endif // ASMJIT_DISABLE_VALIDATION
282
283
  }

284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
  resetOptions();
  resetInlineComment();

  // decide between `CBInst` and `CBJump`.
  if (isJumpInst(instId)) {
    CBJump* node = _cbHeap.allocT<CBJump>(sizeof(CBJump) + opCount * sizeof(Operand));
    Operand* opArray = reinterpret_cast<Operand*>(reinterpret_cast<uint8_t*>(node) + sizeof(CBJump));

    if (ASMJIT_UNLIKELY(!node))
      return setLastError(DebugUtils::errored(kErrorNoHeapMemory));

    if (opCount > 0) opArray[0].copyFrom(o0);
    if (opCount > 1) opArray[1].copyFrom(o1);
    if (opCount > 2) opArray[2].copyFrom(o2);
    if (opCount > 3) opArray[3].copyFrom(o3);
    if (opCount > 4) opArray[4].copyFrom(o4);
    if (opCount > 5) opArray[5].copyFrom(o5);

    new(node) CBJump(this, instId, options, opArray, opCount);
    node->_instDetail.extraReg = _extraReg;
    _extraReg.reset();

    CBLabel* jTarget = nullptr;
    if (!(options & kOptionUnfollow)) {
      if (opArray[0].isLabel()) {
        Error err = getCBLabel(&jTarget, static_cast<Label&>(opArray[0]));
        if (err) return setLastError(err);
      }
      else {
        options |= kOptionUnfollow;
      }
    }
    node->setOptions(options);
317

318
319
320
    node->orFlags(instId == X86Inst::kIdJmp ? CBNode::kFlagIsJmp | CBNode::kFlagIsTaken : CBNode::kFlagIsJcc);
    node->_target = jTarget;
    node->_jumpNext = nullptr;
321

322
323
324
325
326
    if (jTarget) {
      node->_jumpNext = static_cast<CBJump*>(jTarget->_from);
      jTarget->_from = node;
      jTarget->addNumRefs();
    }
327

328
329
330
331
332
333
334
335
336
337
    // The 'jmp' is always taken, conditional jump can contain hint, we detect it.
    if (instId == X86Inst::kIdJmp)
      node->orFlags(CBNode::kFlagIsTaken);
    else if (options & X86Inst::kOptionTaken)
      node->orFlags(CBNode::kFlagIsTaken);

    if (inlineComment) {
      inlineComment = static_cast<char*>(_cbDataZone.dup(inlineComment, ::strlen(inlineComment), true));
      node->setInlineComment(inlineComment);
    }
338

339
340
    addNode(node);
    return kErrorOk;
341
342
  }
  else {
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
    CBInst* node = _cbHeap.allocT<CBInst>(sizeof(CBInst) + opCount * sizeof(Operand));
    Operand* opArray = reinterpret_cast<Operand*>(reinterpret_cast<uint8_t*>(node) + sizeof(CBInst));

    if (ASMJIT_UNLIKELY(!node))
      return setLastError(DebugUtils::errored(kErrorNoHeapMemory));

    if (opCount > 0) opArray[0].copyFrom(o0);
    if (opCount > 1) opArray[1].copyFrom(o1);
    if (opCount > 2) opArray[2].copyFrom(o2);
    if (opCount > 3) opArray[3].copyFrom(o3);
    if (opCount > 4) opArray[4].copyFrom(o4);
    if (opCount > 5) opArray[5].copyFrom(o5);

    node = new(node) CBInst(this, instId, options, opArray, opCount);
    node->_instDetail.extraReg = _extraReg;
    _extraReg.reset();

    if (inlineComment) {
      inlineComment = static_cast<char*>(_cbDataZone.dup(inlineComment, ::strlen(inlineComment), true));
      node->setInlineComment(inlineComment);
363
364
    }

365
366
367
    addNode(node);
    return kErrorOk;
  }
368
369
370
371
372
}

} // asmjit namespace

// [Api-End]
373
#include "../asmjit_apiend.h"
374
375

// [Guard]
376
#endif // ASMJIT_BUILD_X86 && !ASMJIT_DISABLE_COMPILER