/
x86assembler.cpp
5114 lines (4172 loc) · 153 KB
/
x86assembler.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
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
277
278
279
280
281
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This file is part of AsmJit project <https://asmjit.com>
//
// See asmjit.h or LICENSE.md for license and copyright information
// SPDX-License-Identifier: Zlib
#include "../core/api-build_p.h"
#if !defined(ASMJIT_NO_X86)
#include "../core/assembler.h"
#include "../core/codewriter_p.h"
#include "../core/cpuinfo.h"
#include "../core/emitterutils_p.h"
#include "../core/formatter.h"
#include "../core/logger.h"
#include "../core/misc_p.h"
#include "../core/support.h"
#include "../x86/x86assembler.h"
#include "../x86/x86emithelper_p.h"
#include "../x86/x86instapi_p.h"
#include "../x86/x86instdb_p.h"
#include "../x86/x86formatter_p.h"
#include "../x86/x86opcode_p.h"
ASMJIT_BEGIN_SUB_NAMESPACE(x86)
typedef Support::FastUInt8 FastUInt8;
// x86::Assembler - Constants
// ==========================
//! X86 bytes used to encode important prefixes.
enum X86Byte : uint32_t {
//! 1-byte REX prefix mask.
kX86ByteRex = 0x40,
//! 1-byte REX.W component.
kX86ByteRexW = 0x08,
kX86ByteInvalidRex = 0x80,
//! 2-byte VEX prefix:
//! - `[0]` - `0xC5`.
//! - `[1]` - `RvvvvLpp`.
kX86ByteVex2 = 0xC5,
//! 3-byte VEX prefix:
//! - `[0]` - `0xC4`.
//! - `[1]` - `RXBmmmmm`.
//! - `[2]` - `WvvvvLpp`.
kX86ByteVex3 = 0xC4,
//! 3-byte XOP prefix:
//! - `[0]` - `0x8F`.
//! - `[1]` - `RXBmmmmm`.
//! - `[2]` - `WvvvvLpp`.
kX86ByteXop3 = 0x8F,
//! 4-byte EVEX prefix:
//! - `[0]` - `0x62`.
//! - `[1]` - Payload0 or `P[ 7: 0]` - `[R X B R' 0 m m m]`.
//! - `[2]` - Payload1 or `P[15: 8]` - `[W v v v v 1 p p]`.
//! - `[3]` - Payload2 or `P[23:16]` - `[z L' L b V' a a a]`.
//!
//! Payload:
//! - `P[ 2: 0]` - OPCODE: EVEX.mmmmm, only lowest 3 bits [2:0] used.
//! - `P[ 3]` - ______: Must be 0.
//! - `P[ 4]` - REG-ID: EVEX.R' - 5th bit of 'RRRRR'.
//! - `P[ 5]` - REG-ID: EVEX.B - 4th bit of 'BBBBB'.
//! - `P[ 6]` - REG-ID: EVEX.X - 5th bit of 'BBBBB' or 4th bit of 'XXXX' (with SIB).
//! - `P[ 7]` - REG-ID: EVEX.R - 4th bit of 'RRRRR'.
//! - `P[ 9: 8]` - OPCODE: EVEX.pp.
//! - `P[ 10]` - ______: Must be 1.
//! - `P[14:11]` - REG-ID: 4 bits of 'VVVV'.
//! - `P[ 15]` - OPCODE: EVEX.W.
//! - `P[18:16]` - REG-ID: K register k0...k7 (Merging/Zeroing Vector Ops).
//! - `P[ 19]` - REG-ID: 5th bit of 'VVVVV'.
//! - `P[ 20]` - OPCODE: Broadcast/Rounding Control/SAE bit.
//! - `P[22.21]` - OPCODE: Vector Length (L' and L) / Rounding Control.
//! - `P[ 23]` - OPCODE: Zeroing/Merging.
kX86ByteEvex = 0x62
};
// AsmJit specific (used to encode VVVVV field in XOP/VEX/EVEX).
enum VexVVVVV : uint32_t {
kVexVVVVVShift = 7,
kVexVVVVVMask = 0x1F << kVexVVVVVShift
};
//! Instruction 2-byte/3-byte opcode prefix definition.
struct X86OpcodeMM {
uint8_t size;
uint8_t data[3];
};
//! Mandatory prefixes used to encode legacy [66, F3, F2] or [9B] byte.
static const uint8_t x86OpcodePP[8] = { 0x00, 0x66, 0xF3, 0xF2, 0x00, 0x00, 0x00, 0x9B };
//! Instruction 2-byte/3-byte opcode prefix data.
static const X86OpcodeMM x86OpcodeMM[] = {
{ 0, { 0x00, 0x00, 0 } }, // #00 (0b0000).
{ 1, { 0x0F, 0x00, 0 } }, // #01 (0b0001).
{ 2, { 0x0F, 0x38, 0 } }, // #02 (0b0010).
{ 2, { 0x0F, 0x3A, 0 } }, // #03 (0b0011).
{ 2, { 0x0F, 0x01, 0 } }, // #04 (0b0100).
{ 0, { 0x00, 0x00, 0 } }, // #05 (0b0101).
{ 0, { 0x00, 0x00, 0 } }, // #06 (0b0110).
{ 0, { 0x00, 0x00, 0 } }, // #07 (0b0111).
{ 0, { 0x00, 0x00, 0 } }, // #08 (0b1000).
{ 0, { 0x00, 0x00, 0 } }, // #09 (0b1001).
{ 0, { 0x00, 0x00, 0 } }, // #0A (0b1010).
{ 0, { 0x00, 0x00, 0 } }, // #0B (0b1011).
{ 0, { 0x00, 0x00, 0 } }, // #0C (0b1100).
{ 0, { 0x00, 0x00, 0 } }, // #0D (0b1101).
{ 0, { 0x00, 0x00, 0 } }, // #0E (0b1110).
{ 0, { 0x00, 0x00, 0 } } // #0F (0b1111).
};
static const uint8_t x86SegmentPrefix[8] = {
0x00, // None.
0x26, // ES.
0x2E, // CS.
0x36, // SS.
0x3E, // DS.
0x64, // FS.
0x65 // GS.
};
static const uint32_t x86OpcodePushSReg[8] = {
Opcode::k000000 | 0x00, // None.
Opcode::k000000 | 0x06, // Push ES.
Opcode::k000000 | 0x0E, // Push CS.
Opcode::k000000 | 0x16, // Push SS.
Opcode::k000000 | 0x1E, // Push DS.
Opcode::k000F00 | 0xA0, // Push FS.
Opcode::k000F00 | 0xA8 // Push GS.
};
static const uint32_t x86OpcodePopSReg[8] = {
Opcode::k000000 | 0x00, // None.
Opcode::k000000 | 0x07, // Pop ES.
Opcode::k000000 | 0x00, // Pop CS.
Opcode::k000000 | 0x17, // Pop SS.
Opcode::k000000 | 0x1F, // Pop DS.
Opcode::k000F00 | 0xA1, // Pop FS.
Opcode::k000F00 | 0xA9 // Pop GS.
};
// x86::Assembler - X86MemInfo | X86VEXPrefix | X86LLByRegType | X86CDisp8Table
// ============================================================================
//! Memory operand's info bits.
//!
//! A lookup table that contains various information based on the BASE and INDEX information of a memory operand. This
//! is much better and safer than playing with IFs in the code and can check for errors must faster and better.
enum X86MemInfo_Enum {
kX86MemInfo_0 = 0x00,
kX86MemInfo_BaseGp = 0x01, //!< Has BASE reg, REX.B can be 1, compatible with REX.B byte.
kX86MemInfo_Index = 0x02, //!< Has INDEX reg, REX.X can be 1, compatible with REX.X byte.
kX86MemInfo_BaseLabel = 0x10, //!< Base is Label.
kX86MemInfo_BaseRip = 0x20, //!< Base is RIP.
kX86MemInfo_67H_X86 = 0x40, //!< Address-size override in 32-bit mode.
kX86MemInfo_67H_X64 = 0x80, //!< Address-size override in 64-bit mode.
kX86MemInfo_67H_Mask = 0xC0 //!< Contains all address-size override bits.
};
template<uint32_t X>
struct X86MemInfo_T {
enum : uint32_t {
B = (X ) & 0x1F,
I = (X >> 5) & 0x1F,
kBase = (B >= uint32_t(RegType::kX86_Gpw) && B <= uint32_t(RegType::kX86_Gpq)) ? kX86MemInfo_BaseGp :
(B == uint32_t(RegType::kX86_Rip) ) ? kX86MemInfo_BaseRip :
(B == uint32_t(RegType::kLabelTag) ) ? kX86MemInfo_BaseLabel : 0,
kIndex = (I >= uint32_t(RegType::kX86_Gpw) && I <= uint32_t(RegType::kX86_Gpq)) ? kX86MemInfo_Index :
(I >= uint32_t(RegType::kX86_Xmm) && I <= uint32_t(RegType::kX86_Zmm)) ? kX86MemInfo_Index : 0,
k67H = (B == uint32_t(RegType::kX86_Gpw) && I == uint32_t(RegType::kNone) ) ? kX86MemInfo_67H_X86 :
(B == uint32_t(RegType::kX86_Gpd) && I == uint32_t(RegType::kNone) ) ? kX86MemInfo_67H_X64 :
(B == uint32_t(RegType::kNone) && I == uint32_t(RegType::kX86_Gpw)) ? kX86MemInfo_67H_X86 :
(B == uint32_t(RegType::kNone) && I == uint32_t(RegType::kX86_Gpd)) ? kX86MemInfo_67H_X64 :
(B == uint32_t(RegType::kX86_Gpw) && I == uint32_t(RegType::kX86_Gpw)) ? kX86MemInfo_67H_X86 :
(B == uint32_t(RegType::kX86_Gpd) && I == uint32_t(RegType::kX86_Gpd)) ? kX86MemInfo_67H_X64 :
(B == uint32_t(RegType::kX86_Gpw) && I == uint32_t(RegType::kX86_Xmm)) ? kX86MemInfo_67H_X86 :
(B == uint32_t(RegType::kX86_Gpd) && I == uint32_t(RegType::kX86_Xmm)) ? kX86MemInfo_67H_X64 :
(B == uint32_t(RegType::kX86_Gpw) && I == uint32_t(RegType::kX86_Ymm)) ? kX86MemInfo_67H_X86 :
(B == uint32_t(RegType::kX86_Gpd) && I == uint32_t(RegType::kX86_Ymm)) ? kX86MemInfo_67H_X64 :
(B == uint32_t(RegType::kX86_Gpw) && I == uint32_t(RegType::kX86_Zmm)) ? kX86MemInfo_67H_X86 :
(B == uint32_t(RegType::kX86_Gpd) && I == uint32_t(RegType::kX86_Zmm)) ? kX86MemInfo_67H_X64 :
(B == uint32_t(RegType::kLabelTag) && I == uint32_t(RegType::kX86_Gpw)) ? kX86MemInfo_67H_X86 :
(B == uint32_t(RegType::kLabelTag) && I == uint32_t(RegType::kX86_Gpd)) ? kX86MemInfo_67H_X64 : 0,
kValue = kBase | kIndex | k67H | 0x04 | 0x08
};
};
// The result stored in the LUT is a combination of
// - 67H - Address override prefix - depends on BASE+INDEX register types and the target architecture.
// - REX - A possible combination of REX.[B|X|R|W] bits in REX prefix where REX.B and REX.X are possibly
// masked out, but REX.R and REX.W are kept as is.
#define VALUE(x) X86MemInfo_T<x>::kValue
static const uint8_t x86MemInfo[] = { ASMJIT_LOOKUP_TABLE_1024(VALUE, 0) };
#undef VALUE
// VEX3 or XOP xor bits applied to the opcode before emitted. The index to this table is 'mmmmm' value, which
// contains all we need. This is only used by a 3 BYTE VEX and XOP prefixes, 2 BYTE VEX prefix is handled differently.
// The idea is to minimize the difference between VEX3 vs XOP when encoding VEX or XOP instruction. This should
// minimize the code required to emit such instructions and should also make it faster as we don't need any branch to
// decide between VEX3 vs XOP.
// ____ ___
// [_OPCODE_|WvvvvLpp|RXBmmmmm|VEX3_XOP]
#define VALUE(x) ((x & 0x08) ? kX86ByteXop3 : kX86ByteVex3) | (0xF << 19) | (0x7 << 13)
static const uint32_t x86VEXPrefix[] = { ASMJIT_LOOKUP_TABLE_16(VALUE, 0) };
#undef VALUE
// Table that contains LL opcode field addressed by a register size / 16. It's used to propagate L.256 or L.512 when
// YMM or ZMM registers are used, respectively.
#define VALUE(x) (x & (64 >> 4)) ? Opcode::kLL_2 : \
(x & (32 >> 4)) ? Opcode::kLL_1 : Opcode::kLL_0
static const uint32_t x86LLBySizeDiv16[] = { ASMJIT_LOOKUP_TABLE_16(VALUE, 0) };
#undef VALUE
// Table that contains LL opcode field addressed by a register size / 16. It's used to propagate L.256 or L.512 when
// YMM or ZMM registers are used, respectively.
#define VALUE(x) x == uint32_t(RegType::kX86_Zmm) ? Opcode::kLL_2 : \
x == uint32_t(RegType::kX86_Ymm) ? Opcode::kLL_1 : Opcode::kLL_0
static const uint32_t x86LLByRegType[] = { ASMJIT_LOOKUP_TABLE_16(VALUE, 0) };
#undef VALUE
// Table that contains a scale (shift left) based on 'TTWLL' field and the instruction's tuple-type (TT) field. The
// scale is then applied to the BASE-N stored in each opcode to calculate the final compressed displacement used by
// all EVEX encoded instructions.
template<uint32_t X>
struct X86CDisp8SHL_T {
enum {
TT = (X >> 3) << Opcode::kCDTT_Shift,
LL = (X >> 0) & 0x3,
W = (X >> 2) & 0x1,
kValue = (TT == Opcode::kCDTT_None ? ((LL==0) ? 0 : (LL==1) ? 0 : 0 ) :
TT == Opcode::kCDTT_ByLL ? ((LL==0) ? 0 : (LL==1) ? 1 : 2 ) :
TT == Opcode::kCDTT_T1W ? ((LL==0) ? W : (LL==1) ? 1+W : 2+W) :
TT == Opcode::kCDTT_DUP ? ((LL==0) ? 0 : (LL==1) ? 2 : 3 ) : 0) << Opcode::kCDSHL_Shift
};
};
#define VALUE(x) X86CDisp8SHL_T<x>::kValue
static const uint32_t x86CDisp8SHL[] = { ASMJIT_LOOKUP_TABLE_32(VALUE, 0) };
#undef VALUE
// Table that contains MOD byte of a 16-bit [BASE + disp] address.
// 0xFF == Invalid.
static const uint8_t x86Mod16BaseTable[8] = {
0xFF, // AX -> N/A.
0xFF, // CX -> N/A.
0xFF, // DX -> N/A.
0x07, // BX -> 111.
0xFF, // SP -> N/A.
0x06, // BP -> 110.
0x04, // SI -> 100.
0x05 // DI -> 101.
};
// Table that contains MOD byte of a 16-bit [BASE + INDEX + disp] combination.
// 0xFF == Invalid.
template<uint32_t X>
struct X86Mod16BaseIndexTable_T {
enum {
B = X >> 3,
I = X & 0x7,
kValue = ((B == Gp::kIdBx && I == Gp::kIdSi) || (B == Gp::kIdSi && I == Gp::kIdBx)) ? 0x00 :
((B == Gp::kIdBx && I == Gp::kIdDi) || (B == Gp::kIdDi && I == Gp::kIdBx)) ? 0x01 :
((B == Gp::kIdBp && I == Gp::kIdSi) || (B == Gp::kIdSi && I == Gp::kIdBp)) ? 0x02 :
((B == Gp::kIdBp && I == Gp::kIdDi) || (B == Gp::kIdDi && I == Gp::kIdBp)) ? 0x03 : 0xFF
};
};
#define VALUE(x) X86Mod16BaseIndexTable_T<x>::kValue
static const uint8_t x86Mod16BaseIndexTable[] = { ASMJIT_LOOKUP_TABLE_64(VALUE, 0) };
#undef VALUE
// x86::Assembler - Helpers
// ========================
static ASMJIT_FORCE_INLINE bool x86IsJmpOrCall(InstId instId) noexcept {
return instId == Inst::kIdJmp || instId == Inst::kIdCall;
}
static ASMJIT_FORCE_INLINE bool x86IsImplicitMem(const Operand_& op, uint32_t base) noexcept {
return op.isMem() && op.as<Mem>().baseId() == base && !op.as<Mem>().hasOffset();
}
//! Combine `regId` and `vvvvvId` into a single value (used by AVX and AVX-512).
static ASMJIT_FORCE_INLINE uint32_t x86PackRegAndVvvvv(uint32_t regId, uint32_t vvvvvId) noexcept {
return regId + (vvvvvId << kVexVVVVVShift);
}
static ASMJIT_FORCE_INLINE uint32_t x86OpcodeLByVMem(const Operand_& op) noexcept {
return x86LLByRegType[size_t(op.as<Mem>().indexType())];
}
static ASMJIT_FORCE_INLINE uint32_t x86OpcodeLBySize(uint32_t size) noexcept {
return x86LLBySizeDiv16[size / 16];
}
//! Encode MOD byte.
static ASMJIT_FORCE_INLINE uint32_t x86EncodeMod(uint32_t m, uint32_t o, uint32_t rm) noexcept {
ASMJIT_ASSERT(m <= 3);
ASMJIT_ASSERT(o <= 7);
ASMJIT_ASSERT(rm <= 7);
return (m << 6) + (o << 3) + rm;
}
//! Encode SIB byte.
static ASMJIT_FORCE_INLINE uint32_t x86EncodeSib(uint32_t s, uint32_t i, uint32_t b) noexcept {
ASMJIT_ASSERT(s <= 3);
ASMJIT_ASSERT(i <= 7);
ASMJIT_ASSERT(b <= 7);
return (s << 6) + (i << 3) + b;
}
static ASMJIT_FORCE_INLINE bool x86IsRexInvalid(uint32_t rex) noexcept {
// Validates the following possibilities:
// REX == 0x00 -> OKAY (X86_32 / X86_64).
// REX == 0x40-0x4F -> OKAY (X86_64).
// REX == 0x80 -> OKAY (X86_32 mode, rex prefix not used).
// REX == 0x81-0xCF -> BAD (X86_32 mode, rex prefix used).
return rex > kX86ByteInvalidRex;
}
static ASMJIT_FORCE_INLINE uint32_t x86GetForceEvex3MaskInLastBit(InstOptions options) noexcept {
constexpr uint32_t kVex3Bit = Support::ConstCTZ<uint32_t(InstOptions::kX86_Vex3)>::value;
return uint32_t(options & InstOptions::kX86_Vex3) << (31 - kVex3Bit);
}
template<typename T>
static ASMJIT_FORCE_INLINE constexpr T x86SignExtendI32(T imm) noexcept { return T(int64_t(int32_t(imm & T(0xFFFFFFFF)))); }
static ASMJIT_FORCE_INLINE uint32_t x86AltOpcodeOf(const InstDB::InstInfo* info) noexcept {
return InstDB::_altOpcodeTable[info->_altOpcodeIndex];
}
// x86::Assembler - X86BufferWriter
// ================================
class X86BufferWriter : public CodeWriter {
public:
ASMJIT_FORCE_INLINE explicit X86BufferWriter(Assembler* a) noexcept
: CodeWriter(a) {}
ASMJIT_FORCE_INLINE void emitPP(uint32_t opcode) noexcept {
uint32_t ppIndex = (opcode >> Opcode::kPP_Shift) &
(Opcode::kPP_FPUMask >> Opcode::kPP_Shift) ;
emit8If(x86OpcodePP[ppIndex], ppIndex != 0);
}
ASMJIT_FORCE_INLINE void emitMMAndOpcode(uint32_t opcode) noexcept {
uint32_t mmIndex = (opcode & Opcode::kMM_Mask) >> Opcode::kMM_Shift;
const X86OpcodeMM& mmCode = x86OpcodeMM[mmIndex];
emit8If(mmCode.data[0], mmCode.size > 0);
emit8If(mmCode.data[1], mmCode.size > 1);
emit8(opcode);
}
ASMJIT_FORCE_INLINE void emitSegmentOverride(uint32_t segmentId) noexcept {
ASMJIT_ASSERT(segmentId < ASMJIT_ARRAY_SIZE(x86SegmentPrefix));
FastUInt8 prefix = x86SegmentPrefix[segmentId];
emit8If(prefix, prefix != 0);
}
template<typename CondT>
ASMJIT_FORCE_INLINE void emitAddressOverride(CondT condition) noexcept {
emit8If(0x67, condition);
}
ASMJIT_FORCE_INLINE void emitImmByteOrDWord(uint64_t immValue, FastUInt8 immSize) noexcept {
if (!immSize)
return;
ASMJIT_ASSERT(immSize == 1 || immSize == 4);
#if ASMJIT_ARCH_BITS >= 64
uint64_t imm = uint64_t(immValue);
#else
uint32_t imm = uint32_t(immValue & 0xFFFFFFFFu);
#endif
// Many instructions just use a single byte immediate, so make it fast.
emit8(imm & 0xFFu);
if (immSize == 1) return;
imm >>= 8;
emit8(imm & 0xFFu);
imm >>= 8;
emit8(imm & 0xFFu);
imm >>= 8;
emit8(imm & 0xFFu);
}
ASMJIT_FORCE_INLINE void emitImmediate(uint64_t immValue, FastUInt8 immSize) noexcept {
#if ASMJIT_ARCH_BITS >= 64
uint64_t imm = immValue;
if (immSize >= 4) {
emit32uLE(imm & 0xFFFFFFFFu);
imm >>= 32;
immSize = FastUInt8(immSize - 4u);
}
#else
uint32_t imm = uint32_t(immValue & 0xFFFFFFFFu);
if (immSize >= 4) {
emit32uLE(imm);
imm = uint32_t(immValue >> 32);
immSize = FastUInt8(immSize - 4u);
}
#endif
if (!immSize)
return;
emit8(imm & 0xFFu);
imm >>= 8;
if (--immSize == 0)
return;
emit8(imm & 0xFFu);
imm >>= 8;
if (--immSize == 0)
return;
emit8(imm & 0xFFu);
imm >>= 8;
if (--immSize == 0)
return;
emit8(imm & 0xFFu);
}
};
// If the operand is BPL|SPL|SIL|DIL|R8B-15B
// - Force REX prefix
// If the operand is AH|BH|CH|DH
// - patch its index from 0..3 to 4..7 as encoded by X86.
// - Disallow REX prefix.
#define FIXUP_GPB(REG_OP, REG_ID) \
do { \
if (!static_cast<const Gp&>(REG_OP).isGpbHi()) { \
options |= (REG_ID) >= 4 ? InstOptions::kX86_Rex \
: InstOptions::kNone; \
} \
else { \
options |= InstOptions::kX86_InvalidRex; \
REG_ID += 4; \
} \
} while (0)
#define ENC_OPS1(OP0) \
(uint32_t(OperandType::k##OP0))
#define ENC_OPS2(OP0, OP1) \
(uint32_t(OperandType::k##OP0) + \
(uint32_t(OperandType::k##OP1) << 3))
#define ENC_OPS3(OP0, OP1, OP2) \
(uint32_t(OperandType::k##OP0) + \
(uint32_t(OperandType::k##OP1) << 3) + \
(uint32_t(OperandType::k##OP2) << 6))
#define ENC_OPS4(OP0, OP1, OP2, OP3) \
(uint32_t(OperandType::k##OP0) + \
(uint32_t(OperandType::k##OP1) << 3) + \
(uint32_t(OperandType::k##OP2) << 6) + \
(uint32_t(OperandType::k##OP3) << 9))
// x86::Assembler - Movabs Heuristics
// ==================================
static ASMJIT_FORCE_INLINE uint32_t x86GetMovAbsInstSize64Bit(uint32_t regSize, InstOptions options, const Mem& rmRel) noexcept {
uint32_t segmentPrefixSize = rmRel.segmentId() != 0;
uint32_t _66hPrefixSize = regSize == 2;
uint32_t rexPrefixSize = regSize == 8 || Support::test(options, InstOptions::kX86_Rex);
uint32_t opCodeByteSize = 1;
uint32_t immediateSize = 8;
return segmentPrefixSize + _66hPrefixSize + rexPrefixSize + opCodeByteSize + immediateSize;
}
static ASMJIT_FORCE_INLINE bool x86ShouldUseMovabs(Assembler* self, X86BufferWriter& writer, uint32_t regSize, InstOptions options, const Mem& rmRel) noexcept {
if (self->is32Bit()) {
// There is no relative addressing, just decide whether to use MOV encoded with MOD R/M or absolute.
return !Support::test(options, InstOptions::kX86_ModMR | InstOptions::kX86_ModRM);
}
else {
// If the addressing type is REL or MOD R/M was specified then absolute mov won't be used.
if (rmRel.addrType() == Mem::AddrType::kRel || Support::test(options, InstOptions::kX86_ModMR | InstOptions::kX86_ModRM))
return false;
int64_t addrValue = rmRel.offset();
uint64_t baseAddress = self->code()->baseAddress();
// If the address type is default, it means to basically check whether relative addressing is possible. However,
// this is only possible when the base address is known - relative encoding uses RIP+N it has to be calculated.
if (rmRel.addrType() == Mem::AddrType::kDefault && baseAddress != Globals::kNoBaseAddress && !rmRel.hasSegment()) {
uint32_t instructionSize = x86GetMovAbsInstSize64Bit(regSize, options, rmRel);
uint64_t virtualOffset = uint64_t(writer.offsetFrom(self->_bufferData));
uint64_t rip64 = baseAddress + self->_section->offset() + virtualOffset + instructionSize;
uint64_t rel64 = uint64_t(addrValue) - rip64;
if (Support::isInt32(int64_t(rel64)))
return false;
}
else {
if (Support::isInt32(addrValue))
return false;
}
return uint64_t(addrValue) > 0xFFFFFFFFu;
}
}
// x86::Assembler - Construction & Destruction
// ===========================================
Assembler::Assembler(CodeHolder* code) noexcept : BaseAssembler() {
_archMask = (uint64_t(1) << uint32_t(Arch::kX86)) |
(uint64_t(1) << uint32_t(Arch::kX64)) ;
if (code)
code->attach(this);
}
Assembler::~Assembler() noexcept {}
// x86::Assembler - Emit (Low-Level)
// =================================
ASMJIT_FAVOR_SPEED Error Assembler::_emit(InstId instId, const Operand_& o0, const Operand_& o1, const Operand_& o2, const Operand_* opExt) {
constexpr uint32_t kVSHR_W = Opcode::kW_Shift - 23;
constexpr uint32_t kVSHR_PP = Opcode::kPP_Shift - 16;
constexpr uint32_t kVSHR_PP_EW = Opcode::kPP_Shift - 16;
constexpr InstOptions kRequiresSpecialHandling =
InstOptions::kReserved | // Logging/Validation/Error.
InstOptions::kX86_Rep | // REP/REPE prefix.
InstOptions::kX86_Repne | // REPNE prefix.
InstOptions::kX86_Lock | // LOCK prefix.
InstOptions::kX86_XAcquire | // XACQUIRE prefix.
InstOptions::kX86_XRelease ; // XRELEASE prefix.
Error err;
Opcode opcode; // Instruction opcode.
InstOptions options; // Instruction options.
uint32_t isign3; // A combined signature of first 3 operands.
const Operand_* rmRel; // Memory operand or operand that holds Label|Imm.
uint32_t rmInfo; // Memory operand's info based on x86MemInfo.
uint32_t rbReg = 0; // Memory base or modRM register.
uint32_t rxReg; // Memory index register.
uint32_t opReg; // ModR/M opcode or register id.
LabelEntry* label; // Label entry.
RelocEntry* re = nullptr; // Relocation entry.
int32_t relOffset; // Relative offset
FastUInt8 relSize = 0; // Relative size.
uint8_t* memOpAOMark = nullptr; // Marker that points before 'address-override prefix' is emitted.
int64_t immValue = 0; // Immediate value (must be 64-bit).
FastUInt8 immSize = 0; // Immediate size.
X86BufferWriter writer(this);
if (instId >= Inst::_kIdCount)
instId = 0;
const InstDB::InstInfo* instInfo = &InstDB::_instInfoTable[instId];
const InstDB::CommonInfo* commonInfo = &instInfo->commonInfo();
// Signature of the first 3 operands.
isign3 = (uint32_t(o0.opType()) ) +
(uint32_t(o1.opType()) << 3) +
(uint32_t(o2.opType()) << 6);
// Combine all instruction options and also check whether the instruction is valid. All options
// that require special handling (including invalid instruction) are handled by the next branch.
options = InstOptions((instId == 0) | ((size_t)(_bufferEnd - writer.cursor()) < 16)) | instOptions() | forcedInstOptions();
// Handle failure and rare cases first.
if (ASMJIT_UNLIKELY(Support::test(options, kRequiresSpecialHandling))) {
if (ASMJIT_UNLIKELY(!_code))
return reportError(DebugUtils::errored(kErrorNotInitialized));
// Unknown instruction.
if (ASMJIT_UNLIKELY(instId == 0))
goto InvalidInstruction;
// Grow request, happens rarely.
err = writer.ensureSpace(this, 16);
if (ASMJIT_UNLIKELY(err))
goto Failed;
#ifndef ASMJIT_NO_VALIDATION
// Strict validation.
if (hasDiagnosticOption(DiagnosticOptions::kValidateAssembler)) {
Operand_ opArray[Globals::kMaxOpCount];
EmitterUtils::opArrayFromEmitArgs(opArray, o0, o1, o2, opExt);
err = _funcs.validate(BaseInst(instId, options, _extraReg), opArray, Globals::kMaxOpCount, ValidationFlags::kNone);
if (ASMJIT_UNLIKELY(err))
goto Failed;
}
#endif
InstDB::InstFlags iFlags = instInfo->flags();
// LOCK, XACQUIRE, and XRELEASE prefixes.
if (Support::test(options, InstOptions::kX86_Lock)) {
bool xAcqRel = Support::test(options, InstOptions::kX86_XAcquire | InstOptions::kX86_XRelease);
if (ASMJIT_UNLIKELY(!Support::test(iFlags, InstDB::InstFlags::kLock) && !xAcqRel))
goto InvalidLockPrefix;
if (xAcqRel) {
if (ASMJIT_UNLIKELY(Support::test(options, InstOptions::kX86_XAcquire) && !Support::test(iFlags, InstDB::InstFlags::kXAcquire)))
goto InvalidXAcquirePrefix;
if (ASMJIT_UNLIKELY(Support::test(options, InstOptions::kX86_XRelease) && !Support::test(iFlags, InstDB::InstFlags::kXRelease)))
goto InvalidXReleasePrefix;
writer.emit8(Support::test(options, InstOptions::kX86_XAcquire) ? 0xF2 : 0xF3);
}
writer.emit8(0xF0);
}
// REP and REPNE prefixes.
if (Support::test(options, InstOptions::kX86_Rep | InstOptions::kX86_Repne)) {
if (ASMJIT_UNLIKELY(!Support::test(iFlags, InstDB::InstFlags::kRep)))
goto InvalidRepPrefix;
if (ASMJIT_UNLIKELY(_extraReg.isReg() && (_extraReg.group() != RegGroup::kGp || _extraReg.id() != Gp::kIdCx)))
goto InvalidRepPrefix;
writer.emit8(Support::test(options, InstOptions::kX86_Repne) ? 0xF2 : 0xF3);
}
}
// This sequence seems to be the fastest.
opcode = InstDB::_mainOpcodeTable[instInfo->_mainOpcodeIndex];
opReg = opcode.extractModO();
opcode |= instInfo->_mainOpcodeValue;
// Encoding Scope
// --------------
// How it works? Each case here represents a unique encoding of a group of instructions, which is handled
// separately. The handlers check instruction signature, possibly register types, etc, and process this
// information by writing some bits to opcode, opReg/rbReg, immValue/immSize, etc, and then at the end of
// the sequence it uses goto to jump into a lower level handler, that actually encodes the instruction.
switch (instInfo->_encoding) {
case InstDB::kEncodingNone:
goto EmitDone;
// Base Instructions
// -----------------
case InstDB::kEncodingX86Op:
goto EmitX86Op;
case InstDB::kEncodingX86Op_Mod11RM:
rbReg = opcode.extractModRM();
goto EmitX86R;
case InstDB::kEncodingX86Op_Mod11RM_I8:
// The first operand must be immediate, we don't care of other operands as they could be implicit.
if (!o0.isImm())
goto InvalidInstruction;
rbReg = opcode.extractModRM();
immValue = o0.as<Imm>().valueAs<uint8_t>();
immSize = 1;
goto EmitX86R;
case InstDB::kEncodingX86Op_xAddr:
if (ASMJIT_UNLIKELY(!o0.isReg()))
goto InvalidInstruction;
rmInfo = x86MemInfo[size_t(o0.as<Reg>().type())];
writer.emitAddressOverride((rmInfo & _addressOverrideMask()) != 0);
goto EmitX86Op;
case InstDB::kEncodingX86Op_xAX:
if (isign3 == 0)
goto EmitX86Op;
if (isign3 == ENC_OPS1(Reg) && o0.id() == Gp::kIdAx)
goto EmitX86Op;
break;
case InstDB::kEncodingX86Op_xDX_xAX:
if (isign3 == 0)
goto EmitX86Op;
if (isign3 == ENC_OPS2(Reg, Reg) && o0.id() == Gp::kIdDx && o1.id() == Gp::kIdAx)
goto EmitX86Op;
break;
case InstDB::kEncodingX86Op_MemZAX:
if (isign3 == 0)
goto EmitX86Op;
rmRel = &o0;
if (isign3 == ENC_OPS1(Mem) && x86IsImplicitMem(o0, Gp::kIdAx))
goto EmitX86OpImplicitMem;
break;
case InstDB::kEncodingX86I_xAX:
// Implicit form.
if (isign3 == ENC_OPS1(Imm)) {
immValue = o0.as<Imm>().valueAs<uint8_t>();
immSize = 1;
goto EmitX86Op;
}
// Explicit form.
if (isign3 == ENC_OPS2(Reg, Imm) && o0.id() == Gp::kIdAx) {
immValue = o1.as<Imm>().valueAs<uint8_t>();
immSize = 1;
goto EmitX86Op;
}
break;
case InstDB::kEncodingX86M_NoMemSize:
if (o0.isReg())
opcode.addPrefixBySize(o0.x86RmSize());
goto CaseX86M_NoSize;
case InstDB::kEncodingX86M:
opcode.addPrefixBySize(o0.x86RmSize());
ASMJIT_FALLTHROUGH;
case InstDB::kEncodingX86M_NoSize:
CaseX86M_NoSize:
rbReg = o0.id();
if (isign3 == ENC_OPS1(Reg))
goto EmitX86R;
rmRel = &o0;
if (isign3 == ENC_OPS1(Mem))
goto EmitX86M;
break;
case InstDB::kEncodingX86M_GPB_MulDiv:
CaseX86M_GPB_MulDiv:
// Explicit form?
if (isign3 > 0x7) {
// [AX] <- [AX] div|mul r8.
if (isign3 == ENC_OPS2(Reg, Reg)) {
if (ASMJIT_UNLIKELY(!Reg::isGpw(o0, Gp::kIdAx) || !Reg::isGpb(o1)))
goto InvalidInstruction;
rbReg = o1.id();
FIXUP_GPB(o1, rbReg);
goto EmitX86R;
}
// [AX] <- [AX] div|mul m8.
if (isign3 == ENC_OPS2(Reg, Mem)) {
if (ASMJIT_UNLIKELY(!Reg::isGpw(o0, Gp::kIdAx)))
goto InvalidInstruction;
rmRel = &o1;
goto EmitX86M;
}
// [?DX:?AX] <- [?DX:?AX] div|mul r16|r32|r64
if (isign3 == ENC_OPS3(Reg, Reg, Reg)) {
if (ASMJIT_UNLIKELY(o0.x86RmSize() != o1.x86RmSize()))
goto InvalidInstruction;
opcode.addArithBySize(o0.x86RmSize());
rbReg = o2.id();
goto EmitX86R;
}
// [?DX:?AX] <- [?DX:?AX] div|mul m16|m32|m64
if (isign3 == ENC_OPS3(Reg, Reg, Mem)) {
if (ASMJIT_UNLIKELY(o0.x86RmSize() != o1.x86RmSize()))
goto InvalidInstruction;
opcode.addArithBySize(o0.x86RmSize());
rmRel = &o2;
goto EmitX86M;
}
goto InvalidInstruction;
}
ASMJIT_FALLTHROUGH;
case InstDB::kEncodingX86M_GPB:
if (isign3 == ENC_OPS1(Reg)) {
opcode.addArithBySize(o0.x86RmSize());
rbReg = o0.id();
if (o0.x86RmSize() != 1)
goto EmitX86R;
FIXUP_GPB(o0, rbReg);
goto EmitX86R;
}
if (isign3 == ENC_OPS1(Mem)) {
if (ASMJIT_UNLIKELY(o0.x86RmSize() == 0))
goto AmbiguousOperandSize;
opcode.addArithBySize(o0.x86RmSize());
rmRel = &o0;
goto EmitX86M;
}
break;
case InstDB::kEncodingX86M_Only_EDX_EAX:
if (isign3 == ENC_OPS3(Mem, Reg, Reg) && Reg::isGpd(o1, Gp::kIdDx) && Reg::isGpd(o2, Gp::kIdAx)) {
rmRel = &o0;
goto EmitX86M;
}
ASMJIT_FALLTHROUGH;
case InstDB::kEncodingX86M_Only:
if (isign3 == ENC_OPS1(Mem)) {
rmRel = &o0;
goto EmitX86M;
}
break;
case InstDB::kEncodingX86M_Nop:
if (isign3 == ENC_OPS1(None))
goto EmitX86Op;
// Single operand NOP instruction "0F 1F /0".
opcode = Opcode::k000F00 | 0x1F;
opReg = 0;
if (isign3 == ENC_OPS1(Reg)) {
opcode.addPrefixBySize(o0.x86RmSize());
rbReg = o0.id();
goto EmitX86R;
}
if (isign3 == ENC_OPS1(Mem)) {
opcode.addPrefixBySize(o0.x86RmSize());
rmRel = &o0;
goto EmitX86M;
}
// Two operand NOP instruction "0F 1F /r".
opReg = o1.id();
opcode.addPrefixBySize(o1.x86RmSize());
if (isign3 == ENC_OPS2(Reg, Reg)) {
rbReg = o0.id();
goto EmitX86R;
}
if (isign3 == ENC_OPS2(Mem, Reg)) {
rmRel = &o0;
goto EmitX86M;
}
break;
case InstDB::kEncodingX86R_FromM:
if (isign3 == ENC_OPS1(Mem)) {
rmRel = &o0;
rbReg = o0.id();
goto EmitX86RFromM;
}
break;
case InstDB::kEncodingX86R32_EDX_EAX:
// Explicit form: R32, EDX, EAX.
if (isign3 == ENC_OPS3(Reg, Reg, Reg)) {
if (!Reg::isGpd(o1, Gp::kIdDx) || !Reg::isGpd(o2, Gp::kIdAx))
goto InvalidInstruction;
rbReg = o0.id();
goto EmitX86R;
}
// Implicit form: R32.
if (isign3 == ENC_OPS1(Reg)) {
if (!Reg::isGpd(o0))
goto InvalidInstruction;
rbReg = o0.id();
goto EmitX86R;
}
break;
case InstDB::kEncodingX86R_Native:
if (isign3 == ENC_OPS1(Reg)) {
rbReg = o0.id();
goto EmitX86R;
}
break;
case InstDB::kEncodingX86Rm:
opcode.addPrefixBySize(o0.x86RmSize());
ASMJIT_FALLTHROUGH;
case InstDB::kEncodingX86Rm_NoSize:
if (isign3 == ENC_OPS2(Reg, Reg)) {
opReg = o0.id();
rbReg = o1.id();
goto EmitX86R;
}
if (isign3 == ENC_OPS2(Reg, Mem)) {
opReg = o0.id();
rmRel = &o1;
goto EmitX86M;
}
break;
case InstDB::kEncodingX86Rm_Raw66H:
// We normally emit either [66|F2|F3], this instruction requires 66+[F2|F3].
if (isign3 == ENC_OPS2(Reg, Reg)) {
opReg = o0.id();
rbReg = o1.id();
if (o0.x86RmSize() == 2)
writer.emit8(0x66);
else
opcode.addWBySize(o0.x86RmSize());
goto EmitX86R;
}
if (isign3 == ENC_OPS2(Reg, Mem)) {
opReg = o0.id();
rmRel = &o1;
if (o0.x86RmSize() == 2)
writer.emit8(0x66);
else
opcode.addWBySize(o0.x86RmSize());
goto EmitX86M;
}
break;
case InstDB::kEncodingX86Mr:
opcode.addPrefixBySize(o1.x86RmSize());
ASMJIT_FALLTHROUGH;
case InstDB::kEncodingX86Mr_NoSize:
if (isign3 == ENC_OPS2(Reg, Reg)) {
rbReg = o0.id();
opReg = o1.id();
goto EmitX86R;
}
if (isign3 == ENC_OPS2(Mem, Reg)) {
rmRel = &o0;
opReg = o1.id();
goto EmitX86M;
}
break;
case InstDB::kEncodingX86Arith:
if (isign3 == ENC_OPS2(Reg, Reg)) {
opcode.addArithBySize(o0.x86RmSize());
if (o0.x86RmSize() != o1.x86RmSize())
goto OperandSizeMismatch;
rbReg = o0.id();
opReg = o1.id();
if (o0.x86RmSize() == 1) {
FIXUP_GPB(o0, rbReg);
FIXUP_GPB(o1, opReg);
}
// MOD/MR: The default encoding used if not instructed otherwise..
if (!Support::test(options, InstOptions::kX86_ModRM))
goto EmitX86R;
// MOD/RM: Alternative encoding selected via instruction options.
opcode += 2u;
std::swap(opReg, rbReg);
goto EmitX86R;
}
if (isign3 == ENC_OPS2(Reg, Mem)) {
opcode += 2u;
opcode.addArithBySize(o0.x86RmSize());
opReg = o0.id();