summaryrefslogtreecommitdiffstats
path: root/vendor/golang.org/x/arch/x86/x86asm/decode.go
blob: 148870b73ddd01cdf9794efe3ea4b5f799a62226 (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
// Copyright 2014 The Go Authors.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Table-driven decoding of x86 instructions.

package x86asm

import (
	"encoding/binary"
	"errors"
	"fmt"
	"runtime"
)

// Set trace to true to cause the decoder to print the PC sequence
// of the executed instruction codes. This is typically only useful
// when you are running a test of a single input case.
const trace = false

// A decodeOp is a single instruction in the decoder bytecode program.
//
// The decodeOps correspond to consuming and conditionally branching
// on input bytes, consuming additional fields, and then interpreting
// consumed data as instruction arguments. The names of the xRead and xArg
// operations are taken from the Intel manual conventions, for example
// Volume 2, Section 3.1.1, page 487 of
// http://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-software-developer-manual-325462.pdf
//
// The actual decoding program is generated by ../x86map.
//
// TODO(rsc): We may be able to merge various of the memory operands
// since we don't care about, say, the distinction between m80dec and m80bcd.
// Similarly, mm and mm1 have identical meaning, as do xmm and xmm1.

type decodeOp uint16

const (
	xFail  decodeOp = iota // invalid instruction (return)
	xMatch                 // completed match
	xJump                  // jump to pc

	xCondByte     // switch on instruction byte value
	xCondSlashR   // read and switch on instruction /r value
	xCondPrefix   // switch on presence of instruction prefix
	xCondIs64     // switch on 64-bit processor mode
	xCondDataSize // switch on operand size
	xCondAddrSize // switch on address size
	xCondIsMem    // switch on memory vs register argument

	xSetOp // set instruction opcode

	xReadSlashR // read /r
	xReadIb     // read ib
	xReadIw     // read iw
	xReadId     // read id
	xReadIo     // read io
	xReadCb     // read cb
	xReadCw     // read cw
	xReadCd     // read cd
	xReadCp     // read cp
	xReadCm     // read cm

	xArg1            // arg 1
	xArg3            // arg 3
	xArgAL           // arg AL
	xArgAX           // arg AX
	xArgCL           // arg CL
	xArgCR0dashCR7   // arg CR0-CR7
	xArgCS           // arg CS
	xArgDR0dashDR7   // arg DR0-DR7
	xArgDS           // arg DS
	xArgDX           // arg DX
	xArgEAX          // arg EAX
	xArgEDX          // arg EDX
	xArgES           // arg ES
	xArgFS           // arg FS
	xArgGS           // arg GS
	xArgImm16        // arg imm16
	xArgImm32        // arg imm32
	xArgImm64        // arg imm64
	xArgImm8         // arg imm8
	xArgImm8u        // arg imm8 but record as unsigned
	xArgImm16u       // arg imm8 but record as unsigned
	xArgM            // arg m
	xArgM128         // arg m128
	xArgM256         // arg m256
	xArgM1428byte    // arg m14/28byte
	xArgM16          // arg m16
	xArgM16and16     // arg m16&16
	xArgM16and32     // arg m16&32
	xArgM16and64     // arg m16&64
	xArgM16colon16   // arg m16:16
	xArgM16colon32   // arg m16:32
	xArgM16colon64   // arg m16:64
	xArgM16int       // arg m16int
	xArgM2byte       // arg m2byte
	xArgM32          // arg m32
	xArgM32and32     // arg m32&32
	xArgM32fp        // arg m32fp
	xArgM32int       // arg m32int
	xArgM512byte     // arg m512byte
	xArgM64          // arg m64
	xArgM64fp        // arg m64fp
	xArgM64int       // arg m64int
	xArgM8           // arg m8
	xArgM80bcd       // arg m80bcd
	xArgM80dec       // arg m80dec
	xArgM80fp        // arg m80fp
	xArgM94108byte   // arg m94/108byte
	xArgMm           // arg mm
	xArgMm1          // arg mm1
	xArgMm2          // arg mm2
	xArgMm2M64       // arg mm2/m64
	xArgMmM32        // arg mm/m32
	xArgMmM64        // arg mm/m64
	xArgMem          // arg mem
	xArgMoffs16      // arg moffs16
	xArgMoffs32      // arg moffs32
	xArgMoffs64      // arg moffs64
	xArgMoffs8       // arg moffs8
	xArgPtr16colon16 // arg ptr16:16
	xArgPtr16colon32 // arg ptr16:32
	xArgR16          // arg r16
	xArgR16op        // arg r16 with +rw in opcode
	xArgR32          // arg r32
	xArgR32M16       // arg r32/m16
	xArgR32M8        // arg r32/m8
	xArgR32op        // arg r32 with +rd in opcode
	xArgR64          // arg r64
	xArgR64M16       // arg r64/m16
	xArgR64op        // arg r64 with +rd in opcode
	xArgR8           // arg r8
	xArgR8op         // arg r8 with +rb in opcode
	xArgRAX          // arg RAX
	xArgRDX          // arg RDX
	xArgRM           // arg r/m
	xArgRM16         // arg r/m16
	xArgRM32         // arg r/m32
	xArgRM64         // arg r/m64
	xArgRM8          // arg r/m8
	xArgReg          // arg reg
	xArgRegM16       // arg reg/m16
	xArgRegM32       // arg reg/m32
	xArgRegM8        // arg reg/m8
	xArgRel16        // arg rel16
	xArgRel32        // arg rel32
	xArgRel8         // arg rel8
	xArgSS           // arg SS
	xArgST           // arg ST, aka ST(0)
	xArgSTi          // arg ST(i) with +i in opcode
	xArgSreg         // arg Sreg
	xArgTR0dashTR7   // arg TR0-TR7
	xArgXmm          // arg xmm
	xArgXMM0         // arg <XMM0>
	xArgXmm1         // arg xmm1
	xArgXmm2         // arg xmm2
	xArgXmm2M128     // arg xmm2/m128
	xArgYmm2M256     // arg ymm2/m256
	xArgXmm2M16      // arg xmm2/m16
	xArgXmm2M32      // arg xmm2/m32
	xArgXmm2M64      // arg xmm2/m64
	xArgXmmM128      // arg xmm/m128
	xArgXmmM32       // arg xmm/m32
	xArgXmmM64       // arg xmm/m64
	xArgYmm1         // arg ymm1
	xArgRmf16        // arg r/m16 but force mod=3
	xArgRmf32        // arg r/m32 but force mod=3
	xArgRmf64        // arg r/m64 but force mod=3
)

// instPrefix returns an Inst describing just one prefix byte.
// It is only used if there is a prefix followed by an unintelligible
// or invalid instruction byte sequence.
func instPrefix(b byte, mode int) (Inst, error) {
	// When tracing it is useful to see what called instPrefix to report an error.
	if trace {
		_, file, line, _ := runtime.Caller(1)
		fmt.Printf("%s:%d\n", file, line)
	}
	p := Prefix(b)
	switch p {
	case PrefixDataSize:
		if mode == 16 {
			p = PrefixData32
		} else {
			p = PrefixData16
		}
	case PrefixAddrSize:
		if mode == 32 {
			p = PrefixAddr16
		} else {
			p = PrefixAddr32
		}
	}
	// Note: using composite literal with Prefix key confuses 'bundle' tool.
	inst := Inst{Len: 1}
	inst.Prefix = Prefixes{p}
	return inst, nil
}

// truncated reports a truncated instruction.
// For now we use instPrefix but perhaps later we will return
// a specific error here.
func truncated(src []byte, mode int) (Inst, error) {
	//	return Inst{}, len(src), ErrTruncated
	return instPrefix(src[0], mode) // too long
}

// These are the errors returned by Decode.
var (
	ErrInvalidMode  = errors.New("invalid x86 mode in Decode")
	ErrTruncated    = errors.New("truncated instruction")
	ErrUnrecognized = errors.New("unrecognized instruction")
)

// decoderCover records coverage information for which parts
// of the byte code have been executed.
// TODO(rsc): This is for testing. Only use this if a flag is given.
var decoderCover []bool

// Decode decodes the leading bytes in src as a single instruction.
// The mode arguments specifies the assumed processor mode:
// 16, 32, or 64 for 16-, 32-, and 64-bit execution modes.
func Decode(src []byte, mode int) (inst Inst, err error) {
	return decode1(src, mode, false)
}

// decode1 is the implementation of Decode but takes an extra
// gnuCompat flag to cause it to change its behavior to mimic
// bugs (or at least unique features) of GNU libopcodes as used
// by objdump. We don't believe that logic is the right thing to do
// in general, but when testing against libopcodes it simplifies the
// comparison if we adjust a few small pieces of logic.
// The affected logic is in the conditional branch for "mandatory" prefixes,
// case xCondPrefix.
func decode1(src []byte, mode int, gnuCompat bool) (Inst, error) {
	switch mode {
	case 16, 32, 64:
		// ok
		// TODO(rsc): 64-bit mode not tested, probably not working.
	default:
		return Inst{}, ErrInvalidMode
	}

	// Maximum instruction size is 15 bytes.
	// If we need to read more, return 'truncated instruction.
	if len(src) > 15 {
		src = src[:15]
	}

	var (
		// prefix decoding information
		pos           = 0    // position reading src
		nprefix       = 0    // number of prefixes
		lockIndex     = -1   // index of LOCK prefix in src and inst.Prefix
		repIndex      = -1   // index of REP/REPN prefix in src and inst.Prefix
		segIndex      = -1   // index of Group 2 prefix in src and inst.Prefix
		dataSizeIndex = -1   // index of Group 3 prefix in src and inst.Prefix
		addrSizeIndex = -1   // index of Group 4 prefix in src and inst.Prefix
		rex           Prefix // rex byte if present (or 0)
		rexUsed       Prefix // bits used in rex byte
		rexIndex      = -1   // index of rex byte
		vex           Prefix // use vex encoding
		vexIndex      = -1   // index of vex prefix

		addrMode = mode // address mode (width in bits)
		dataMode = mode // operand mode (width in bits)

		// decoded ModR/M fields
		haveModrm bool
		modrm     int
		mod       int
		regop     int
		rm        int

		// if ModR/M is memory reference, Mem form
		mem     Mem
		haveMem bool

		// decoded SIB fields
		haveSIB bool
		sib     int
		scale   int
		index   int
		base    int
		displen int
		dispoff int

		// decoded immediate values
		imm     int64
		imm8    int8
		immc    int64
		immcpos int

		// output
		opshift int
		inst    Inst
		narg    int // number of arguments written to inst
	)

	if mode == 64 {
		dataMode = 32
	}

	// Prefixes are certainly the most complex and underspecified part of
	// decoding x86 instructions. Although the manuals say things like
	// up to four prefixes, one from each group, nearly everyone seems to
	// agree that in practice as many prefixes as possible, including multiple
	// from a particular group or repetitions of a given prefix, can be used on
	// an instruction, provided the total instruction length including prefixes
	// does not exceed the agreed-upon maximum of 15 bytes.
	// Everyone also agrees that if one of these prefixes is the LOCK prefix
	// and the instruction is not one of the instructions that can be used with
	// the LOCK prefix or if the destination is not a memory operand,
	// then the instruction is invalid and produces the #UD exception.
	// However, that is the end of any semblance of agreement.
	//
	// What happens if prefixes are given that conflict with other prefixes?
	// For example, the memory segment overrides CS, DS, ES, FS, GS, SS
	// conflict with each other: only one segment can be in effect.
	// Disassemblers seem to agree that later prefixes take priority over
	// earlier ones. I have not taken the time to write assembly programs
	// to check to see if the hardware agrees.
	//
	// What happens if prefixes are given that have no meaning for the
	// specific instruction to which they are attached? It depends.
	// If they really have no meaning, they are ignored. However, a future
	// processor may assign a different meaning. As a disassembler, we
	// don't really know whether we're seeing a meaningless prefix or one
	// whose meaning we simply haven't been told yet.
	//
	// Combining the two questions, what happens when conflicting
	// extension prefixes are given? No one seems to know for sure.
	// For example, MOVQ is 66 0F D6 /r, MOVDQ2Q is F2 0F D6 /r,
	// and MOVQ2DQ is F3 0F D6 /r. What is '66 F2 F3 0F D6 /r'?
	// Which prefix wins? See the xCondPrefix prefix for more.
	//
	// Writing assembly test cases to divine which interpretation the
	// CPU uses might clarify the situation, but more likely it would
	// make the situation even less clear.

	// Read non-REX prefixes.
ReadPrefixes:
	for ; pos < len(src); pos++ {
		p := Prefix(src[pos])
		switch p {
		default:
			nprefix = pos
			break ReadPrefixes

		// Group 1 - lock and repeat prefixes
		// According to Intel, there should only be one from this set,
		// but according to AMD both can be present.
		case 0xF0:
			if lockIndex >= 0 {
				inst.Prefix[lockIndex] |= PrefixIgnored
			}
			lockIndex = pos
		case 0xF2, 0xF3:
			if repIndex >= 0 {
				inst.Prefix[repIndex] |= PrefixIgnored
			}
			repIndex = pos

		// Group 2 - segment override / branch hints
		case 0x26, 0x2E, 0x36, 0x3E:
			if mode == 64 {
				p |= PrefixIgnored
				break
			}
			fallthrough
		case 0x64, 0x65:
			if segIndex >= 0 {
				inst.Prefix[segIndex] |= PrefixIgnored
			}
			segIndex = pos

		// Group 3 - operand size override
		case 0x66:
			if mode == 16 {
				dataMode = 32
				p = PrefixData32
			} else {
				dataMode = 16
				p = PrefixData16
			}
			if dataSizeIndex >= 0 {
				inst.Prefix[dataSizeIndex] |= PrefixIgnored
			}
			dataSizeIndex = pos

		// Group 4 - address size override
		case 0x67:
			if mode == 32 {
				addrMode = 16
				p = PrefixAddr16
			} else {
				addrMode = 32
				p = PrefixAddr32
			}
			if addrSizeIndex >= 0 {
				inst.Prefix[addrSizeIndex] |= PrefixIgnored
			}
			addrSizeIndex = pos

		//Group 5 - Vex encoding
		case 0xC5:
			if pos == 0 && (mode == 64 || (mode == 32 && pos+1 < len(src) && src[pos+1]&0xc0 == 0xc0)) {
				vex = p
				vexIndex = pos
				inst.Prefix[pos] = p
				inst.Prefix[pos+1] = Prefix(src[pos+1])
				pos += 1
				continue
			} else {
				nprefix = pos
				break ReadPrefixes
			}
		case 0xC4:
			if pos == 0 && (mode == 64 || (mode == 32 && pos+2 < len(src) && src[pos+1]&0xc0 == 0xc0)) {
				vex = p
				vexIndex = pos
				inst.Prefix[pos] = p
				inst.Prefix[pos+1] = Prefix(src[pos+1])
				inst.Prefix[pos+2] = Prefix(src[pos+2])
				pos += 2
				continue
			} else {
				nprefix = pos
				break ReadPrefixes
			}
		}

		if pos >= len(inst.Prefix) {
			return instPrefix(src[0], mode) // too long
		}

		inst.Prefix[pos] = p
	}

	// Read REX prefix.
	if pos < len(src) && mode == 64 && Prefix(src[pos]).IsREX() && vex == 0 {
		rex = Prefix(src[pos])
		rexIndex = pos
		if pos >= len(inst.Prefix) {
			return instPrefix(src[0], mode) // too long
		}
		inst.Prefix[pos] = rex
		pos++
		if rex&PrefixREXW != 0 {
			dataMode = 64
			if dataSizeIndex >= 0 {
				inst.Prefix[dataSizeIndex] |= PrefixIgnored
			}
		}
	}

	// Decode instruction stream, interpreting decoding instructions.
	// opshift gives the shift to use when saving the next
	// opcode byte into inst.Opcode.
	opshift = 24
	if decoderCover == nil {
		decoderCover = make([]bool, len(decoder))
	}

	// Decode loop, executing decoder program.
	var oldPC, prevPC int
Decode:
	for pc := 1; ; { // TODO uint
		oldPC = prevPC
		prevPC = pc
		if trace {
			println("run", pc)
		}
		x := decoder[pc]
		decoderCover[pc] = true
		pc++

		// Read and decode ModR/M if needed by opcode.
		switch decodeOp(x) {
		case xCondSlashR, xReadSlashR:
			if haveModrm {
				return Inst{Len: pos}, errInternal
			}
			haveModrm = true
			if pos >= len(src) {
				return truncated(src, mode)
			}
			modrm = int(src[pos])
			pos++
			if opshift >= 0 {
				inst.Opcode |= uint32(modrm) << uint(opshift)
				opshift -= 8
			}
			mod = modrm >> 6
			regop = (modrm >> 3) & 07
			rm = modrm & 07
			if rex&PrefixREXR != 0 {
				rexUsed |= PrefixREXR
				regop |= 8
			}
			if addrMode == 16 {
				// 16-bit modrm form
				if mod != 3 {
					haveMem = true
					mem = addr16[rm]
					if rm == 6 && mod == 0 {
						mem.Base = 0
					}

					// Consume disp16 if present.
					if mod == 0 && rm == 6 || mod == 2 {
						if pos+2 > len(src) {
							return truncated(src, mode)
						}
						mem.Disp = int64(binary.LittleEndian.Uint16(src[pos:]))
						pos += 2
					}

					// Consume disp8 if present.
					if mod == 1 {
						if pos >= len(src) {
							return truncated(src, mode)
						}
						mem.Disp = int64(int8(src[pos]))
						pos++
					}
				}
			} else {
				haveMem = mod != 3

				// 32-bit or 64-bit form
				// Consume SIB encoding if present.
				if rm == 4 && mod != 3 {
					haveSIB = true
					if pos >= len(src) {
						return truncated(src, mode)
					}
					sib = int(src[pos])
					pos++
					if opshift >= 0 {
						inst.Opcode |= uint32(sib) << uint(opshift)
						opshift -= 8
					}
					scale = sib >> 6
					index = (sib >> 3) & 07
					base = sib & 07
					if rex&PrefixREXB != 0 || vex == 0xC4 && inst.Prefix[vexIndex+1]&0x20 == 0 {
						rexUsed |= PrefixREXB
						base |= 8
					}
					if rex&PrefixREXX != 0 || vex == 0xC4 && inst.Prefix[vexIndex+1]&0x40 == 0 {
						rexUsed |= PrefixREXX
						index |= 8
					}

					mem.Scale = 1 << uint(scale)
					if index == 4 {
						// no mem.Index
					} else {
						mem.Index = baseRegForBits(addrMode) + Reg(index)
					}
					if base&7 == 5 && mod == 0 {
						// no mem.Base
					} else {
						mem.Base = baseRegForBits(addrMode) + Reg(base)
					}
				} else {
					if rex&PrefixREXB != 0 {
						rexUsed |= PrefixREXB
						rm |= 8
					}
					if mod == 0 && rm&7 == 5 || rm&7 == 4 {
						// base omitted
					} else if mod != 3 {
						mem.Base = baseRegForBits(addrMode) + Reg(rm)
					}
				}

				// Consume disp32 if present.
				if mod == 0 && (rm&7 == 5 || haveSIB && base&7 == 5) || mod == 2 {
					if pos+4 > len(src) {
						return truncated(src, mode)
					}
					dispoff = pos
					displen = 4
					mem.Disp = int64(binary.LittleEndian.Uint32(src[pos:]))
					pos += 4
				}

				// Consume disp8 if present.
				if mod == 1 {
					if pos >= len(src) {
						return truncated(src, mode)
					}
					dispoff = pos
					displen = 1
					mem.Disp = int64(int8(src[pos]))
					pos++
				}

				// In 64-bit, mod=0 rm=5 is PC-relative instead of just disp.
				// See Vol 2A. Table 2-7.
				if mode == 64 && mod == 0 && rm&7 == 5 {
					if addrMode == 32 {
						mem.Base = EIP
					} else {
						mem.Base = RIP
					}
				}
			}

			if segIndex >= 0 {
				mem.Segment = prefixToSegment(inst.Prefix[segIndex])
			}
		}

		// Execute single opcode.
		switch decodeOp(x) {
		default:
			println("bad op", x, "at", pc-1, "from", oldPC)
			return Inst{Len: pos}, errInternal

		case xFail:
			inst.Op = 0
			break Decode

		case xMatch:
			break Decode

		case xJump:
			pc = int(decoder[pc])

		// Conditional branches.

		case xCondByte:
			if pos >= len(src) {
				return truncated(src, mode)
			}
			b := src[pos]
			n := int(decoder[pc])
			pc++
			for i := 0; i < n; i++ {
				xb, xpc := decoder[pc], int(decoder[pc+1])
				pc += 2
				if b == byte(xb) {
					pc = xpc
					pos++
					if opshift >= 0 {
						inst.Opcode |= uint32(b) << uint(opshift)
						opshift -= 8
					}
					continue Decode
				}
			}
			// xCondByte is the only conditional with a fall through,
			// so that it can be used to pick off special cases before
			// an xCondSlash. If the fallthrough instruction is xFail,
			// advance the position so that the decoded instruction
			// size includes the byte we just compared against.
			if decodeOp(decoder[pc]) == xJump {
				pc = int(decoder[pc+1])
			}
			if decodeOp(decoder[pc]) == xFail {
				pos++
			}

		case xCondIs64:
			if mode == 64 {
				pc = int(decoder[pc+1])
			} else {
				pc = int(decoder[pc])
			}

		case xCondIsMem:
			mem := haveMem
			if !haveModrm {
				if pos >= len(src) {
					return instPrefix(src[0], mode) // too long
				}
				mem = src[pos]>>6 != 3
			}
			if mem {
				pc = int(decoder[pc+1])
			} else {
				pc = int(decoder[pc])
			}

		case xCondDataSize:
			switch dataMode {
			case 16:
				if dataSizeIndex >= 0 {
					inst.Prefix[dataSizeIndex] |= PrefixImplicit
				}
				pc = int(decoder[pc])
			case 32:
				if dataSizeIndex >= 0 {
					inst.Prefix[dataSizeIndex] |= PrefixImplicit
				}
				pc = int(decoder[pc+1])
			case 64:
				rexUsed |= PrefixREXW
				pc = int(decoder[pc+2])
			}

		case xCondAddrSize:
			switch addrMode {
			case 16:
				if addrSizeIndex >= 0 {
					inst.Prefix[addrSizeIndex] |= PrefixImplicit
				}
				pc = int(decoder[pc])
			case 32:
				if addrSizeIndex >= 0 {
					inst.Prefix[addrSizeIndex] |= PrefixImplicit
				}
				pc = int(decoder[pc+1])
			case 64:
				pc = int(decoder[pc+2])
			}

		case xCondPrefix:
			// Conditional branch based on presence or absence of prefixes.
			// The conflict cases here are completely undocumented and
			// differ significantly between GNU libopcodes and Intel xed.
			// I have not written assembly code to divine what various CPUs
			// do, but it wouldn't surprise me if they are not consistent either.
			//
			// The basic idea is to switch on the presence of a prefix, so that
			// for example:
			//
			//	xCondPrefix, 4
			//	0xF3, 123,
			//	0xF2, 234,
			//	0x66, 345,
			//	0, 456
			//
			// branch to 123 if the F3 prefix is present, 234 if the F2 prefix
			// is present, 66 if the 345 prefix is present, and 456 otherwise.
			// The prefixes are given in descending order so that the 0 will be last.
			//
			// It is unclear what should happen if multiple conditions are
			// satisfied: what if F2 and F3 are both present, or if 66 and F2
			// are present, or if all three are present? The one chosen becomes
			// part of the opcode and the others do not. Perhaps the answer
			// depends on the specific opcodes in question.
			//
			// The only clear example is that CRC32 is F2 0F 38 F1 /r, and
			// it comes in 16-bit and 32-bit forms based on the 66 prefix,
			// so 66 F2 0F 38 F1 /r should be treated as F2 taking priority,
			// with the 66 being only an operand size override, and probably
			// F2 66 0F 38 F1 /r should be treated the same.
			// Perhaps that rule is specific to the case of CRC32, since no
			// 66 0F 38 F1 instruction is defined (today) (that we know of).
			// However, both libopcodes and xed seem to generalize this
			// example and choose F2/F3 in preference to 66, and we
			// do the same.
			//
			// Next, what if both F2 and F3 are present? Which wins?
			// The Intel xed rule, and ours, is that the one that occurs last wins.
			// The GNU libopcodes rule, which we implement only in gnuCompat mode,
			// is that F3 beats F2 unless F3 has no special meaning, in which
			// case F3 can be a modified on an F2 special meaning.
			//
			// Concretely,
			//	66 0F D6 /r is MOVQ
			//	F2 0F D6 /r is MOVDQ2Q
			//	F3 0F D6 /r is MOVQ2DQ.
			//
			//	F2 66 0F D6 /r is 66 + MOVDQ2Q always.
			//	66 F2 0F D6 /r is 66 + MOVDQ2Q always.
			//	F3 66 0F D6 /r is 66 + MOVQ2DQ always.
			//	66 F3 0F D6 /r is 66 + MOVQ2DQ always.
			//	F2 F3 0F D6 /r is F2 + MOVQ2DQ always.
			//	F3 F2 0F D6 /r is F3 + MOVQ2DQ in Intel xed, but F2 + MOVQ2DQ in GNU libopcodes.
			//	Adding 66 anywhere in the prefix section of the
			//	last two cases does not change the outcome.
			//
			// Finally, what if there is a variant in which 66 is a mandatory
			// prefix rather than an operand size override, but we know of
			// no corresponding F2/F3 form, and we see both F2/F3 and 66.
			// Does F2/F3 still take priority, so that the result is an unknown
			// instruction, or does the 66 take priority, so that the extended
			// 66 instruction should be interpreted as having a REP/REPN prefix?
			// Intel xed does the former and GNU libopcodes does the latter.
			// We side with Intel xed, unless we are trying to match libopcodes
			// more closely during the comparison-based test suite.
			//
			// In 64-bit mode REX.W is another valid prefix to test for, but
			// there is less ambiguity about that. When present, REX.W is
			// always the first entry in the table.
			n := int(decoder[pc])
			pc++
			sawF3 := false
			for j := 0; j < n; j++ {
				prefix := Prefix(decoder[pc+2*j])
				if prefix.IsREX() {
					rexUsed |= prefix
					if rex&prefix == prefix {
						pc = int(decoder[pc+2*j+1])
						continue Decode
					}
					continue
				}
				ok := false
				if prefix == 0 {
					ok = true
				} else if prefix.IsREX() {
					rexUsed |= prefix
					if rex&prefix == prefix {
						ok = true
					}
				} else if prefix == 0xC5 || prefix == 0xC4 {
					if vex == prefix {
						ok = true
					}
				} else if vex != 0 && (prefix == 0x0F || prefix == 0x0F38 || prefix == 0x0F3A ||
					prefix == 0x66 || prefix == 0xF2 || prefix == 0xF3) {
					var vexM, vexP Prefix
					if vex == 0xC5 {
						vexM = 1 // 2 byte vex always implies 0F
						vexP = inst.Prefix[vexIndex+1]
					} else {
						vexM = inst.Prefix[vexIndex+1]
						vexP = inst.Prefix[vexIndex+2]
					}
					switch prefix {
					case 0x66:
						ok = vexP&3 == 1
					case 0xF3:
						ok = vexP&3 == 2
					case 0xF2:
						ok = vexP&3 == 3
					case 0x0F:
						ok = vexM&3 == 1
					case 0x0F38:
						ok = vexM&3 == 2
					case 0x0F3A:
						ok = vexM&3 == 3
					}
				} else {
					if prefix == 0xF3 {
						sawF3 = true
					}
					switch prefix {
					case PrefixLOCK:
						if lockIndex >= 0 {
							inst.Prefix[lockIndex] |= PrefixImplicit
							ok = true
						}
					case PrefixREP, PrefixREPN:
						if repIndex >= 0 && inst.Prefix[repIndex]&0xFF == prefix {
							inst.Prefix[repIndex] |= PrefixImplicit
							ok = true
						}
						if gnuCompat && !ok && prefix == 0xF3 && repIndex >= 0 && (j+1 >= n || decoder[pc+2*(j+1)] != 0xF2) {
							// Check to see if earlier prefix F3 is present.
							for i := repIndex - 1; i >= 0; i-- {
								if inst.Prefix[i]&0xFF == prefix {
									inst.Prefix[i] |= PrefixImplicit
									ok = true
								}
							}
						}
						if gnuCompat && !ok && prefix == 0xF2 && repIndex >= 0 && !sawF3 && inst.Prefix[repIndex]&0xFF == 0xF3 {
							// Check to see if earlier prefix F2 is present.
							for i := repIndex - 1; i >= 0; i-- {
								if inst.Prefix[i]&0xFF == prefix {
									inst.Prefix[i] |= PrefixImplicit
									ok = true
								}
							}
						}
					case PrefixCS, PrefixDS, PrefixES, PrefixFS, PrefixGS, PrefixSS:
						if segIndex >= 0 && inst.Prefix[segIndex]&0xFF == prefix {
							inst.Prefix[segIndex] |= PrefixImplicit
							ok = true
						}
					case PrefixDataSize:
						// Looking for 66 mandatory prefix.
						// The F2/F3 mandatory prefixes take priority when both are present.
						// If we got this far in the xCondPrefix table and an F2/F3 is present,
						// it means the table didn't have any entry for that prefix. But if 66 has
						// special meaning, perhaps F2/F3 have special meaning that we don't know.
						// Intel xed works this way, treating the F2/F3 as inhibiting the 66.
						// GNU libopcodes allows the 66 to match. We do what Intel xed does
						// except in gnuCompat mode.
						if repIndex >= 0 && !gnuCompat {
							inst.Op = 0
							break Decode
						}
						if dataSizeIndex >= 0 {
							inst.Prefix[dataSizeIndex] |= PrefixImplicit
							ok = true
						}
					case PrefixAddrSize:
						if addrSizeIndex >= 0 {
							inst.Prefix[addrSizeIndex] |= PrefixImplicit
							ok = true
						}
					}
				}
				if ok {
					pc = int(decoder[pc+2*j+1])
					continue Decode
				}
			}
			inst.Op = 0
			break Decode

		case xCondSlashR:
			pc = int(decoder[pc+regop&7])

		// Input.

		case xReadSlashR:
			// done above

		case xReadIb:
			if pos >= len(src) {
				return truncated(src, mode)
			}
			imm8 = int8(src[pos])
			pos++

		case xReadIw:
			if pos+2 > len(src) {
				return truncated(src, mode)
			}
			imm = int64(binary.LittleEndian.Uint16(src[pos:]))
			pos += 2

		case xReadId:
			if pos+4 > len(src) {
				return truncated(src, mode)
			}
			imm = int64(binary.LittleEndian.Uint32(src[pos:]))
			pos += 4

		case xReadIo:
			if pos+8 > len(src) {
				return truncated(src, mode)
			}
			imm = int64(binary.LittleEndian.Uint64(src[pos:]))
			pos += 8

		case xReadCb:
			if pos >= len(src) {
				return truncated(src, mode)
			}
			immcpos = pos
			immc = int64(src[pos])
			pos++

		case xReadCw:
			if pos+2 > len(src) {
				return truncated(src, mode)
			}
			immcpos = pos
			immc = int64(binary.LittleEndian.Uint16(src[pos:]))
			pos += 2

		case xReadCm:
			immcpos = pos
			if addrMode == 16 {
				if pos+2 > len(src) {
					return truncated(src, mode)
				}
				immc = int64(binary.LittleEndian.Uint16(src[pos:]))
				pos += 2
			} else if addrMode == 32 {
				if pos+4 > len(src) {
					return truncated(src, mode)
				}
				immc = int64(binary.LittleEndian.Uint32(src[pos:]))
				pos += 4
			} else {
				if pos+8 > len(src) {
					return truncated(src, mode)
				}
				immc = int64(binary.LittleEndian.Uint64(src[pos:]))
				pos += 8
			}
		case xReadCd:
			immcpos = pos
			if pos+4 > len(src) {
				return truncated(src, mode)
			}
			immc = int64(binary.LittleEndian.Uint32(src[pos:]))
			pos += 4

		case xReadCp:
			immcpos = pos
			if pos+6 > len(src) {
				return truncated(src, mode)
			}
			w := binary.LittleEndian.Uint32(src[pos:])
			w2 := binary.LittleEndian.Uint16(src[pos+4:])
			immc = int64(w2)<<32 | int64(w)
			pos += 6

		// Output.

		case xSetOp:
			inst.Op = Op(decoder[pc])
			pc++

		case xArg1,
			xArg3,
			xArgAL,
			xArgAX,
			xArgCL,
			xArgCS,
			xArgDS,
			xArgDX,
			xArgEAX,
			xArgEDX,
			xArgES,
			xArgFS,
			xArgGS,
			xArgRAX,
			xArgRDX,
			xArgSS,
			xArgST,
			xArgXMM0:
			inst.Args[narg] = fixedArg[x]
			narg++

		case xArgImm8:
			inst.Args[narg] = Imm(imm8)
			narg++

		case xArgImm8u:
			inst.Args[narg] = Imm(uint8(imm8))
			narg++

		case xArgImm16:
			inst.Args[narg] = Imm(int16(imm))
			narg++

		case xArgImm16u:
			inst.Args[narg] = Imm(uint16(imm))
			narg++

		case xArgImm32:
			inst.Args[narg] = Imm(int32(imm))
			narg++

		case xArgImm64:
			inst.Args[narg] = Imm(imm)
			narg++

		case xArgM,
			xArgM128,
			xArgM256,
			xArgM1428byte,
			xArgM16,
			xArgM16and16,
			xArgM16and32,
			xArgM16and64,
			xArgM16colon16,
			xArgM16colon32,
			xArgM16colon64,
			xArgM16int,
			xArgM2byte,
			xArgM32,
			xArgM32and32,
			xArgM32fp,
			xArgM32int,
			xArgM512byte,
			xArgM64,
			xArgM64fp,
			xArgM64int,
			xArgM8,
			xArgM80bcd,
			xArgM80dec,
			xArgM80fp,
			xArgM94108byte,
			xArgMem:
			if !haveMem {
				inst.Op = 0
				break Decode
			}
			inst.Args[narg] = mem
			inst.MemBytes = int(memBytes[decodeOp(x)])
			if mem.Base == RIP {
				inst.PCRel = displen
				inst.PCRelOff = dispoff
			}
			narg++

		case xArgPtr16colon16:
			inst.Args[narg] = Imm(immc >> 16)
			inst.Args[narg+1] = Imm(immc & (1<<16 - 1))
			narg += 2

		case xArgPtr16colon32:
			inst.Args[narg] = Imm(immc >> 32)
			inst.Args[narg+1] = Imm(immc & (1<<32 - 1))
			narg += 2

		case xArgMoffs8, xArgMoffs16, xArgMoffs32, xArgMoffs64:
			// TODO(rsc): Can address be 64 bits?
			mem = Mem{Disp: int64(immc)}
			if segIndex >= 0 {
				mem.Segment = prefixToSegment(inst.Prefix[segIndex])
				inst.Prefix[segIndex] |= PrefixImplicit
			}
			inst.Args[narg] = mem
			inst.MemBytes = int(memBytes[decodeOp(x)])
			if mem.Base == RIP {
				inst.PCRel = displen
				inst.PCRelOff = dispoff
			}
			narg++

		case xArgYmm1:
			base := baseReg[x]
			index := Reg(regop)
			if inst.Prefix[vexIndex+1]&0x80 == 0 {
				index += 8
			}
			inst.Args[narg] = base + index
			narg++

		case xArgR8, xArgR16, xArgR32, xArgR64, xArgXmm, xArgXmm1, xArgDR0dashDR7:
			base := baseReg[x]
			index := Reg(regop)
			if rex != 0 && base == AL && index >= 4 {
				rexUsed |= PrefixREX
				index -= 4
				base = SPB
			}
			inst.Args[narg] = base + index
			narg++

		case xArgMm, xArgMm1, xArgTR0dashTR7:
			inst.Args[narg] = baseReg[x] + Reg(regop&7)
			narg++

		case xArgCR0dashCR7:
			// AMD documents an extension that the LOCK prefix
			// can be used in place of a REX prefix in order to access
			// CR8 from 32-bit mode. The LOCK prefix is allowed in
			// all modes, provided the corresponding CPUID bit is set.
			if lockIndex >= 0 {
				inst.Prefix[lockIndex] |= PrefixImplicit
				regop += 8
			}
			inst.Args[narg] = CR0 + Reg(regop)
			narg++

		case xArgSreg:
			regop &= 7
			if regop >= 6 {
				inst.Op = 0
				break Decode
			}
			inst.Args[narg] = ES + Reg(regop)
			narg++

		case xArgRmf16, xArgRmf32, xArgRmf64:
			base := baseReg[x]
			index := Reg(modrm & 07)
			if rex&PrefixREXB != 0 {
				rexUsed |= PrefixREXB
				index += 8
			}
			inst.Args[narg] = base + index
			narg++

		case xArgR8op, xArgR16op, xArgR32op, xArgR64op, xArgSTi:
			n := inst.Opcode >> uint(opshift+8) & 07
			base := baseReg[x]
			index := Reg(n)
			if rex&PrefixREXB != 0 && decodeOp(x) != xArgSTi {
				rexUsed |= PrefixREXB
				index += 8
			}
			if rex != 0 && base == AL && index >= 4 {
				rexUsed |= PrefixREX
				index -= 4
				base = SPB
			}
			inst.Args[narg] = base + index
			narg++
		case xArgRM8, xArgRM16, xArgRM32, xArgRM64, xArgR32M16, xArgR32M8, xArgR64M16,
			xArgMmM32, xArgMmM64, xArgMm2M64,
			xArgXmm2M16, xArgXmm2M32, xArgXmm2M64, xArgXmmM64, xArgXmmM128, xArgXmmM32, xArgXmm2M128,
			xArgYmm2M256:
			if haveMem {
				inst.Args[narg] = mem
				inst.MemBytes = int(memBytes[decodeOp(x)])
				if mem.Base == RIP {
					inst.PCRel = displen
					inst.PCRelOff = dispoff
				}
			} else {
				base := baseReg[x]
				index := Reg(rm)
				switch decodeOp(x) {
				case xArgMmM32, xArgMmM64, xArgMm2M64:
					// There are only 8 MMX registers, so these ignore the REX.X bit.
					index &= 7
				case xArgRM8:
					if rex != 0 && index >= 4 {
						rexUsed |= PrefixREX
						index -= 4
						base = SPB
					}
				case xArgYmm2M256:
					if vex == 0xC4 && inst.Prefix[vexIndex+1]&0x40 == 0x40 {
						index += 8
					}
				}
				inst.Args[narg] = base + index
			}
			narg++

		case xArgMm2: // register only; TODO(rsc): Handle with tag modrm_regonly tag
			if haveMem {
				inst.Op = 0
				break Decode
			}
			inst.Args[narg] = baseReg[x] + Reg(rm&7)
			narg++

		case xArgXmm2: // register only; TODO(rsc): Handle with tag modrm_regonly tag
			if haveMem {
				inst.Op = 0
				break Decode
			}
			inst.Args[narg] = baseReg[x] + Reg(rm)
			narg++

		case xArgRel8:
			inst.PCRelOff = immcpos
			inst.PCRel = 1
			inst.Args[narg] = Rel(int8(immc))
			narg++

		case xArgRel16:
			inst.PCRelOff = immcpos
			inst.PCRel = 2
			inst.Args[narg] = Rel(int16(immc))
			narg++

		case xArgRel32:
			inst.PCRelOff = immcpos
			inst.PCRel = 4
			inst.Args[narg] = Rel(int32(immc))
			narg++
		}
	}

	if inst.Op == 0 {
		// Invalid instruction.
		if nprefix > 0 {
			return instPrefix(src[0], mode) // invalid instruction
		}
		return Inst{Len: pos}, ErrUnrecognized
	}

	// Matched! Hooray!

	// 90 decodes as XCHG EAX, EAX but is NOP.
	// 66 90 decodes as XCHG AX, AX and is NOP too.
	// 48 90 decodes as XCHG RAX, RAX and is NOP too.
	// 43 90 decodes as XCHG R8D, EAX and is *not* NOP.
	// F3 90 decodes as REP XCHG EAX, EAX but is PAUSE.
	// It's all too special to handle in the decoding tables, at least for now.
	if inst.Op == XCHG && inst.Opcode>>24 == 0x90 {
		if inst.Args[0] == RAX || inst.Args[0] == EAX || inst.Args[0] == AX {
			inst.Op = NOP
			if dataSizeIndex >= 0 {
				inst.Prefix[dataSizeIndex] &^= PrefixImplicit
			}
			inst.Args[0] = nil
			inst.Args[1] = nil
		}
		if repIndex >= 0 && inst.Prefix[repIndex] == 0xF3 {
			inst.Prefix[repIndex] |= PrefixImplicit
			inst.Op = PAUSE
			inst.Args[0] = nil
			inst.Args[1] = nil
		} else if gnuCompat {
			for i := nprefix - 1; i >= 0; i-- {
				if inst.Prefix[i]&0xFF == 0xF3 {
					inst.Prefix[i] |= PrefixImplicit
					inst.Op = PAUSE
					inst.Args[0] = nil
					inst.Args[1] = nil
					break
				}
			}
		}
	}

	// defaultSeg returns the default segment for an implicit
	// memory reference: the final override if present, or else DS.
	defaultSeg := func() Reg {
		if segIndex >= 0 {
			inst.Prefix[segIndex] |= PrefixImplicit
			return prefixToSegment(inst.Prefix[segIndex])
		}
		return DS
	}

	// Add implicit arguments not present in the tables.
	// Normally we shy away from making implicit arguments explicit,
	// following the Intel manuals, but adding the arguments seems
	// the best way to express the effect of the segment override prefixes.
	// TODO(rsc): Perhaps add these to the tables and
	// create bytecode instructions for them.
	usedAddrSize := false
	switch inst.Op {
	case INSB, INSW, INSD:
		inst.Args[0] = Mem{Segment: ES, Base: baseRegForBits(addrMode) + DI - AX}
		inst.Args[1] = DX
		usedAddrSize = true

	case OUTSB, OUTSW, OUTSD:
		inst.Args[0] = DX
		inst.Args[1] = Mem{Segment: defaultSeg(), Base: baseRegForBits(addrMode) + SI - AX}
		usedAddrSize = true

	case MOVSB, MOVSW, MOVSD, MOVSQ:
		inst.Args[0] = Mem{Segment: ES, Base: baseRegForBits(addrMode) + DI - AX}
		inst.Args[1] = Mem{Segment: defaultSeg(), Base: baseRegForBits(addrMode) + SI - AX}
		usedAddrSize = true

	case CMPSB, CMPSW, CMPSD, CMPSQ:
		inst.Args[0] = Mem{Segment: defaultSeg(), Base: baseRegForBits(addrMode) + SI - AX}
		inst.Args[1] = Mem{Segment: ES, Base: baseRegForBits(addrMode) + DI - AX}
		usedAddrSize = true

	case LODSB, LODSW, LODSD, LODSQ:
		switch inst.Op {
		case LODSB:
			inst.Args[0] = AL
		case LODSW:
			inst.Args[0] = AX
		case LODSD:
			inst.Args[0] = EAX
		case LODSQ:
			inst.Args[0] = RAX
		}
		inst.Args[1] = Mem{Segment: defaultSeg(), Base: baseRegForBits(addrMode) + SI - AX}
		usedAddrSize = true

	case STOSB, STOSW, STOSD, STOSQ:
		inst.Args[0] = Mem{Segment: ES, Base: baseRegForBits(addrMode) + DI - AX}
		switch inst.Op {
		case STOSB:
			inst.Args[1] = AL
		case STOSW:
			inst.Args[1] = AX
		case STOSD:
			inst.Args[1] = EAX
		case STOSQ:
			inst.Args[1] = RAX
		}
		usedAddrSize = true

	case SCASB, SCASW, SCASD, SCASQ:
		inst.Args[1] = Mem{Segment: ES, Base: baseRegForBits(addrMode) + DI - AX}
		switch inst.Op {
		case SCASB:
			inst.Args[0] = AL
		case SCASW:
			inst.Args[0] = AX
		case SCASD:
			inst.Args[0] = EAX
		case SCASQ:
			inst.Args[0] = RAX
		}
		usedAddrSize = true

	case XLATB:
		inst.Args[0] = Mem{Segment: defaultSeg(), Base: baseRegForBits(addrMode) + BX - AX}
		usedAddrSize = true
	}

	// If we used the address size annotation to construct the
	// argument list, mark that prefix as implicit: it doesn't need
	// to be shown when printing the instruction.
	if haveMem || usedAddrSize {
		if addrSizeIndex >= 0 {
			inst.Prefix[addrSizeIndex] |= PrefixImplicit
		}
	}

	// Similarly, if there's some memory operand, the segment
	// will be shown there and doesn't need to be shown as an
	// explicit prefix.
	if haveMem {
		if segIndex >= 0 {
			inst.Prefix[segIndex] |= PrefixImplicit
		}
	}

	// Branch predict prefixes are overloaded segment prefixes,
	// since segment prefixes don't make sense on conditional jumps.
	// Rewrite final instance to prediction prefix.
	// The set of instructions to which the prefixes apply (other then the
	// Jcc conditional jumps) is not 100% clear from the manuals, but
	// the disassemblers seem to agree about the LOOP and JCXZ instructions,
	// so we'll follow along.
	// TODO(rsc): Perhaps this instruction class should be derived from the CSV.
	if isCondJmp[inst.Op] || isLoop[inst.Op] || inst.Op == JCXZ || inst.Op == JECXZ || inst.Op == JRCXZ {
	PredictLoop:
		for i := nprefix - 1; i >= 0; i-- {
			p := inst.Prefix[i]
			switch p & 0xFF {
			case PrefixCS:
				inst.Prefix[i] = PrefixPN
				break PredictLoop
			case PrefixDS:
				inst.Prefix[i] = PrefixPT
				break PredictLoop
			}
		}
	}

	// The BND prefix is part of the Intel Memory Protection Extensions (MPX).
	// A REPN applied to certain control transfers is a BND prefix to bound
	// the range of possible destinations. There's surprisingly little documentation
	// about this, so we just do what libopcodes and xed agree on.
	// In particular, it's unclear why a REPN applied to LOOP or JCXZ instructions
	// does not turn into a BND.
	// TODO(rsc): Perhaps this instruction class should be derived from the CSV.
	if isCondJmp[inst.Op] || inst.Op == JMP || inst.Op == CALL || inst.Op == RET {
		for i := nprefix - 1; i >= 0; i-- {
			p := inst.Prefix[i]
			if p&^PrefixIgnored == PrefixREPN {
				inst.Prefix[i] = PrefixBND
				break
			}
		}
	}

	// The LOCK prefix only applies to certain instructions, and then only
	// to instances of the instruction with a memory destination.
	// Other uses of LOCK are invalid and cause a processor exception,
	// in contrast to the "just ignore it" spirit applied to all other prefixes.
	// Mark invalid lock prefixes.
	hasLock := false
	if lockIndex >= 0 && inst.Prefix[lockIndex]&PrefixImplicit == 0 {
		switch inst.Op {
		// TODO(rsc): Perhaps this instruction class should be derived from the CSV.
		case ADD, ADC, AND, BTC, BTR, BTS, CMPXCHG, CMPXCHG8B, CMPXCHG16B, DEC, INC, NEG, NOT, OR, SBB, SUB, XOR, XADD, XCHG:
			if isMem(inst.Args[0]) {
				hasLock = true
				break
			}
			fallthrough
		default:
			inst.Prefix[lockIndex] |= PrefixInvalid
		}
	}

	// In certain cases, all of which require a memory destination,
	// the REPN and REP prefixes are interpreted as XACQUIRE and XRELEASE
	// from the Intel Transactional Synchroniation Extensions (TSX).
	//
	// The specific rules are:
	// (1) Any instruction with a valid LOCK prefix can have XACQUIRE or XRELEASE.
	// (2) Any XCHG, which always has an implicit LOCK, can have XACQUIRE or XRELEASE.
	// (3) Any 0x88-, 0x89-, 0xC6-, or 0xC7-opcode MOV can have XRELEASE.
	if isMem(inst.Args[0]) {
		if inst.Op == XCHG {
			hasLock = true
		}

		for i := len(inst.Prefix) - 1; i >= 0; i-- {
			p := inst.Prefix[i] &^ PrefixIgnored
			switch p {
			case PrefixREPN:
				if hasLock {
					inst.Prefix[i] = inst.Prefix[i]&PrefixIgnored | PrefixXACQUIRE
				}

			case PrefixREP:
				if hasLock {
					inst.Prefix[i] = inst.Prefix[i]&PrefixIgnored | PrefixXRELEASE
				}

				if inst.Op == MOV {
					op := (inst.Opcode >> 24) &^ 1
					if op == 0x88 || op == 0xC6 {
						inst.Prefix[i] = inst.Prefix[i]&PrefixIgnored | PrefixXRELEASE
					}
				}
			}
		}
	}

	// If REP is used on a non-REP-able instruction, mark the prefix as ignored.
	if repIndex >= 0 {
		switch inst.Prefix[repIndex] {
		case PrefixREP, PrefixREPN:
			switch inst.Op {
			// According to the manuals, the REP/REPE prefix applies to all of these,
			// while the REPN applies only to some of them. However, both libopcodes
			// and xed show both prefixes explicitly for all instructions, so we do the same.
			// TODO(rsc): Perhaps this instruction class should be derived from the CSV.
			case INSB, INSW, INSD,
				MOVSB, MOVSW, MOVSD, MOVSQ,
				OUTSB, OUTSW, OUTSD,
				LODSB, LODSW, LODSD, LODSQ,
				CMPSB, CMPSW, CMPSD, CMPSQ,
				SCASB, SCASW, SCASD, SCASQ,
				STOSB, STOSW, STOSD, STOSQ:
				// ok
			default:
				inst.Prefix[repIndex] |= PrefixIgnored
			}
		}
	}

	// If REX was present, mark implicit if all the 1 bits were consumed.
	if rexIndex >= 0 {
		if rexUsed != 0 {
			rexUsed |= PrefixREX
		}
		if rex&^rexUsed == 0 {
			inst.Prefix[rexIndex] |= PrefixImplicit
		}
	}

	inst.DataSize = dataMode
	inst.AddrSize = addrMode
	inst.Mode = mode
	inst.Len = pos
	return inst, nil
}

var errInternal = errors.New("internal error")

// addr16 records the eight 16-bit addressing modes.
var addr16 = [8]Mem{
	{Base: BX, Scale: 1, Index: SI},
	{Base: BX, Scale: 1, Index: DI},
	{Base: BP, Scale: 1, Index: SI},
	{Base: BP, Scale: 1, Index: DI},
	{Base: SI},
	{Base: DI},
	{Base: BP},
	{Base: BX},
}

// baseReg returns the base register for a given register size in bits.
func baseRegForBits(bits int) Reg {
	switch bits {
	case 8:
		return AL
	case 16:
		return AX
	case 32:
		return EAX
	case 64:
		return RAX
	}
	return 0
}

// baseReg records the base register for argument types that specify
// a range of registers indexed by op, regop, or rm.
var baseReg = [...]Reg{
	xArgDR0dashDR7: DR0,
	xArgMm1:        M0,
	xArgMm2:        M0,
	xArgMm2M64:     M0,
	xArgMm:         M0,
	xArgMmM32:      M0,
	xArgMmM64:      M0,
	xArgR16:        AX,
	xArgR16op:      AX,
	xArgR32:        EAX,
	xArgR32M16:     EAX,
	xArgR32M8:      EAX,
	xArgR32op:      EAX,
	xArgR64:        RAX,
	xArgR64M16:     RAX,
	xArgR64op:      RAX,
	xArgR8:         AL,
	xArgR8op:       AL,
	xArgRM16:       AX,
	xArgRM32:       EAX,
	xArgRM64:       RAX,
	xArgRM8:        AL,
	xArgRmf16:      AX,
	xArgRmf32:      EAX,
	xArgRmf64:      RAX,
	xArgSTi:        F0,
	xArgTR0dashTR7: TR0,
	xArgXmm1:       X0,
	xArgYmm1:       X0,
	xArgXmm2:       X0,
	xArgXmm2M128:   X0,
	xArgYmm2M256:   X0,
	xArgXmm2M16:    X0,
	xArgXmm2M32:    X0,
	xArgXmm2M64:    X0,
	xArgXmm:        X0,
	xArgXmmM128:    X0,
	xArgXmmM32:     X0,
	xArgXmmM64:     X0,
}

// prefixToSegment returns the segment register
// corresponding to a particular segment prefix.
func prefixToSegment(p Prefix) Reg {
	switch p &^ PrefixImplicit {
	case PrefixCS:
		return CS
	case PrefixDS:
		return DS
	case PrefixES:
		return ES
	case PrefixFS:
		return FS
	case PrefixGS:
		return GS
	case PrefixSS:
		return SS
	}
	return 0
}

// fixedArg records the fixed arguments corresponding to the given bytecodes.
var fixedArg = [...]Arg{
	xArg1:    Imm(1),
	xArg3:    Imm(3),
	xArgAL:   AL,
	xArgAX:   AX,
	xArgDX:   DX,
	xArgEAX:  EAX,
	xArgEDX:  EDX,
	xArgRAX:  RAX,
	xArgRDX:  RDX,
	xArgCL:   CL,
	xArgCS:   CS,
	xArgDS:   DS,
	xArgES:   ES,
	xArgFS:   FS,
	xArgGS:   GS,
	xArgSS:   SS,
	xArgST:   F0,
	xArgXMM0: X0,
}

// memBytes records the size of the memory pointed at
// by a memory argument of the given form.
var memBytes = [...]int8{
	xArgM128:       128 / 8,
	xArgM256:       256 / 8,
	xArgM16:        16 / 8,
	xArgM16and16:   (16 + 16) / 8,
	xArgM16colon16: (16 + 16) / 8,
	xArgM16colon32: (16 + 32) / 8,
	xArgM16int:     16 / 8,
	xArgM2byte:     2,
	xArgM32:        32 / 8,
	xArgM32and32:   (32 + 32) / 8,
	xArgM32fp:      32 / 8,
	xArgM32int:     32 / 8,
	xArgM64:        64 / 8,
	xArgM64fp:      64 / 8,
	xArgM64int:     64 / 8,
	xArgMm2M64:     64 / 8,
	xArgMmM32:      32 / 8,
	xArgMmM64:      64 / 8,
	xArgMoffs16:    16 / 8,
	xArgMoffs32:    32 / 8,
	xArgMoffs64:    64 / 8,
	xArgMoffs8:     8 / 8,
	xArgR32M16:     16 / 8,
	xArgR32M8:      8 / 8,
	xArgR64M16:     16 / 8,
	xArgRM16:       16 / 8,
	xArgRM32:       32 / 8,
	xArgRM64:       64 / 8,
	xArgRM8:        8 / 8,
	xArgXmm2M128:   128 / 8,
	xArgYmm2M256:   256 / 8,
	xArgXmm2M16:    16 / 8,
	xArgXmm2M32:    32 / 8,
	xArgXmm2M64:    64 / 8,
	xArgXmm:        128 / 8,
	xArgXmmM128:    128 / 8,
	xArgXmmM32:     32 / 8,
	xArgXmmM64:     64 / 8,
}

// isCondJmp records the conditional jumps.
var isCondJmp = [maxOp + 1]bool{
	JA:  true,
	JAE: true,
	JB:  true,
	JBE: true,
	JE:  true,
	JG:  true,
	JGE: true,
	JL:  true,
	JLE: true,
	JNE: true,
	JNO: true,
	JNP: true,
	JNS: true,
	JO:  true,
	JP:  true,
	JS:  true,
}

// isLoop records the loop operators.
var isLoop = [maxOp + 1]bool{
	LOOP:   true,
	LOOPE:  true,
	LOOPNE: true,
	JECXZ:  true,
	JRCXZ:  true,
}