-
Notifications
You must be signed in to change notification settings - Fork 1
/
ajs.cpp
2145 lines (1926 loc) · 74.5 KB
/
ajs.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
#include "config.h"
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
#include <sstream>
#include <vector>
#include <map>
#include <list>
#include <assert.h>
#include <asmjit/asmjit.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <csignal>
#include <getopt.h>
#include <sched.h>
#include <unistd.h>
#include <cmath>
#include <alloca.h>
#include "gmp.h"
#include "line.h"
#include "transform.h"
#include "utils.h"
#include "rdtsc.h"
#include "ajs_parsing.h"
#include "eval.h"
#define debug_print(fmt, ...) \
do { fprintf(stderr, "# %s:%d:%s(): " fmt, __FILE__, \
__LINE__, __func__, __VA_ARGS__); } while (0)
#define stringify( x ) static_cast< std::ostringstream & >( \
( std::ostringstream() << std::dec << x ) ).str()
using namespace asmjit;
using namespace x86;
using namespace std;
// In order to run 'funcPtr' it has to be cast to the desired type.
// Typedef is a recommended and safe way to create a function-type.
typedef int (*FuncType)(uint64_t, uint64_t, uint64_t, uint64_t, uint64_t,
uint64_t);
static void repeat_func_call(FuncType callableFunc, unsigned repeats, uint64_t arg1,
uint64_t arg2, uint64_t arg3, uint64_t arg4, uint64_t arg5, uint64_t arg6)
#if NOINLINE_REPEAT
/* Optionally don't inline for easier break-point setting */
__attribute__((noinline));
#else
;
#endif
static void repeat_func_call(FuncType callableFunc, unsigned repeats, uint64_t arg1,
uint64_t arg2, uint64_t arg3, uint64_t arg4, uint64_t arg5, uint64_t arg6)
{
for (unsigned long r = 0; r < repeats; r++)
callableFunc(arg1, arg2, arg3, arg4, arg5, arg6);
}
class ajs {
public:
static int exiting; // boolean: whether or not ajs should be stopping, (set by interupt handler)
static JitRuntime runtime;
static X86Assembler assembler;
static FileLogger logger;
static int verbose;
static FILE *permfile;
static referenceResult<uint64_t> *reference;
static int *times;
static Imm getValAsImm(string val) {
return Imm(getVal(val));
}
// Parses expressions of the form disp(base,index,scalar) or
// [base+index*scale+disp] into asmjit's X86Mem
static X86Mem getPtrFromAddress(string addr, uint32_t const size,
const int intelSyntax)
{
if (!intelSyntax) // GAS syntax
{
size_t i = addr.find('(');
int32_t disp = 0;
if (i > 0)
{
string d = addr.substr(0, i);
disp = getVal(d);
}
vector<string> bis = split(addr.substr(i + 1, addr.size() - 2 - i), ',');
X86GpReg base;
if (trim(bis[0]).length() != 0) // no base register
base = getGpRegFromName(trim(bis[0]).substr(1));
if (bis.size() > 1)
{
X86GpReg index = getGpRegFromName(trim(bis[1]).substr(1));
uint32_t scalar;
if (bis.size() > 2 && bis[2].length() != 0)
scalar = getVal(bis[2]);
else
scalar = 1;
uint32_t shift =
(scalar == 1) ? 0 :
(scalar == 2) ? 1 :
(scalar == 4) ? 2 :
(scalar == 8) ? 3 : -1;
if (trim(bis[0]).length() == 0)
return ptr_abs(0, index, shift, disp, size);
return ptr(base, index, shift, disp, size);
}
if (trim(bis[0]).length() == 0)
return ptr_abs(0, disp, size);
return ptr(base, disp, size);
}
else // Intel syntax
{
return parse_pointer_intel(addr, size);
}
}
// returns the operand represented by a string i.e. an immediate value,
// label, register, or memory location
static Operand getOpFromStr(string op, map<string, Label>& labels,
map<string, int>& useCounts, uint32_t size, int intelSyntax)
{
// bracket style depends on syntax used
const char openBracket = intelSyntax ? '[' : '(';
op = trim(op);
if (count(op.begin(), op.end(), openBracket) > 0)
return getPtrFromAddress(op, size, intelSyntax);
if (!intelSyntax) // GAS syntax
{
string sub = op.substr(1);
if (op.at(0) == '%')
return getRegFromName(sub);
if (op.at(0) == '$')
return getValAsImm(sub);
if (op.length() > 0)
{
if (labels.count(op) == 0)
{
labels[op] = assembler.newLabel();
useCounts[op] = 0;
}
useCounts[op]++;
return labels[op];
}
}
else // Intel syntax
{
X86Reg reg = getRegFromName(op);
if (reg != noGpReg) // Is it a register?
return reg;
// Is it an immediate?
const char *op_str = op.c_str(), *endp;
int32_t imm_value = eval(op_str, &endp);
if (false) {
cout << "# Evaluating \"" << op << "\" produced " << imm_value
<< " with rest \"" << endp << "\"" << endl;
}
if (endp == op_str + strlen(op_str)) {
return Imm(imm_value);
}
// If we parsed a number other than 0 and text remains on the line,
// signal a parsing error
if (imm_value != 0) {
cout << "Error parsing \"" << op << "\"" << endl;
abort();
}
if (op.length() > 0) // No, it's a label!
{
if (labels.count(op) == 0)
{
labels[op] = assembler.newLabel();
useCounts[op] = 0;
}
useCounts[op]++;
return labels[op];
}
}
assert(0);
return noOperand;
}
// returns the intersection of two vectors of registers
static vector<X86Reg> intersection(const vector<X86Reg>& v1,
const vector<X86Reg>& v2)
{
vector<X86Reg> in;
for (vector<X86Reg>::const_iterator ci1 = v1.begin(); ci1 != v1.end();
++ci1)
for (vector<X86Reg>::const_iterator ci2 = v2.begin(); ci2 != v2.end();
++ci2)
if (*ci1 == *ci2)
in.push_back(*ci2);
return in;
}
// returns whether Line a depends on Line b or not
// i.e. if a followed b originally whether swapping is permissible in general
static bool dependsOn(vector<Line>::const_iterator ai,
vector<Line>::const_iterator bi, vector<Line>& func)
{
Line a = *ai, b = *bi;
// labels, align and byte statements should have all possible dependencies
if (a.isLabel())
return true;
if (b.isLabel())
return true;
if (a.isAlign())
return true;
if (b.isAlign())
return true;
if (a.isByte())
return true;
if (b.isByte())
return true;
const X86InstInfo& ainfo = X86Util::getInstInfo(a.getInstruction()),
&binfo = X86Util::getInstInfo(b.getInstruction());
// if a or b are control flow instructions there is always a dependency
if (ainfo.getExtendedInfo().isFlow())
return true;
if (binfo.getExtendedInfo().isFlow())
return true;
// if a or b are marked as volatile there is always a dependency
if (ainfo.getExtendedInfo().hasFlag(kX86InstFlagVolatile))
return true;
if (binfo.getExtendedInfo().hasFlag(kX86InstFlagVolatile))
return true;
// if a reads flags set by b there is a dependency
if (ainfo.getEFlagsIn() & binfo.getEFlagsOut())
return true;
// if a sets flags read by b there is a dependency
if (ainfo.getEFlagsOut() & binfo.getEFlagsIn())
return true;
// if a sets flags also set by b there is possibly a dependency
// unless another set happens before the next read of the same register
if (ainfo.getEFlagsOut() & binfo.getEFlagsOut())
{
uint32_t flags = ainfo.getEFlagsOut() & binfo.getEFlagsOut();
vector<Line>::const_iterator li;
for (li = ai + 1; li != func.end(); ++li)
{
if (!li->isInstruction())
continue;
const X86InstInfo& liinfo = X86Util::getInstInfo(li->getInstruction());
if (flags & liinfo.getEFlagsIn())
return true;
flags = flags - (flags & liinfo.getEFlagsOut());
}
}
vector<X86Reg> in;
// if a reads a register written to by b there is a dependency
in = intersection(a.getRegsIn(), b.getRegsOut());
// TODO poss change to if len
for (vector<X86Reg>::const_iterator ci = in.begin(); ci != in.end(); ++ci)
{
return true;
}
// if a writes to a register read by b there is a dependency
in = intersection(a.getRegsOut(), b.getRegsIn());
for (vector<X86Reg>::const_iterator ci = in.begin(); ci != in.end(); ++ci)
{
return true;
}
// if a writes to a register written by b there is possibly a dependency
// unless another write happens before the next read of the same register
in = intersection(a.getRegsOut(), b.getRegsOut());
for (vector<X86Reg>::const_iterator ci = in.begin(); ci != in.end(); ++ci)
{
vector<Line>::const_iterator li;
for (li = ai + 1; li != func.end(); ++li)
{
if (std::find(li->getRegsIn().begin(), li->getRegsIn().end(), *ci) !=
li->getRegsIn().end())
return true;
if (std::find(li->getRegsOut().begin(), li->getRegsOut().end(), *ci)
!= li->getRegsOut().end())
break;
}
if (li == func.end())
return true;
}
return false;
}
// adds the registers read from by a Line to Line
// there will not be any for non-instruction lines
static void addRegsRead(Line& l)
{
if (!l.isInstruction())
return;
if ((l.getInstruction() == X86Util::getInstIdByName("div"))
|| (l.getInstruction() == X86Util::getInstIdByName("idiv"))
|| (l.getInstruction() == X86Util::getInstIdByName("mul"))
|| (l.getInstruction() == X86Util::getInstIdByName("sahf")))
l.addRegIn(rax);
if ((l.getInstruction() == X86Util::getInstIdByName("div"))
|| (l.getInstruction() == X86Util::getInstIdByName("idiv"))
|| (l.getInstruction() == X86Util::getInstIdByName("mulx")))
l.addRegIn(rdx);
if ((l.getInstruction() == X86Util::getInstIdByName("pop"))
|| (l.getInstruction() == X86Util::getInstIdByName("push")))
l.addRegIn(rsp);
for (int i = 0; i < MAX_OPS; i++)
{
if (l.getOp(i).isReg())
{
if (i == 0)
{
const X86InstInfo& info = X86Util::getInstInfo(l.getInstruction());
// Some instructions do not read first op
if (info.getExtendedInfo().isWO())
continue;
// Pop does not read first op TODO: this is probably covered by above now, check
if (l.getInstruction() == X86Util::getInstIdByName("pop"))
continue;
}
l.addRegIn(*static_cast<const X86Reg*>(l.getOpPtr(i)));
}
if (l.getOp(i).isMem())
{
const X86Mem* m = static_cast<const X86Mem*>(l.getOpPtr(i));
if (m->hasIndex())
{
X86GpReg r;
r.setIndex(m->getIndex());
r.setType(kX86RegTypeGpq);
r.setSize(8); // TODO this better, maybe 32 bit regs are needed
l.addRegIn(r);
}
if (m->hasBase())
{
X86GpReg r;
r.setIndex(m->getBase());
r.setType(kX86RegTypeGpq);
r.setSize(8); // TODO this better, maybe 32 bit regs are needed
l.addRegIn(r);
}
}
}
}
// adds the registers written to by a Line
// there will not be any for non-instruction lines
static void addRegsWritten(Line& l)
{
if (!l.isInstruction())
return;
if (l.getOp(0).isReg())
{
int opWritten = 1;
// many instructions write to their first operand, but some do not
if (l.getInstruction() == X86Util::getInstIdByName("push"))
opWritten = 0;
if (opWritten)
l.addRegOut(*static_cast<const X86Reg*>(l.getOpPtr(0)));
}
if ((l.getInstruction() == X86Util::getInstIdByName("lahf"))
|| (l.getInstruction() == X86Util::getInstIdByName("mul"))
|| (l.getInstruction() == X86Util::getInstIdByName("div"))
|| (l.getInstruction() == X86Util::getInstIdByName("idiv")))
l.addRegOut(rax);
if ((l.getInstruction() == X86Util::getInstIdByName("mul"))
|| (l.getInstruction() == X86Util::getInstIdByName("div"))
|| (l.getInstruction() == X86Util::getInstIdByName("idiv")))
l.addRegOut(rdx);
if ((l.getInstruction() == X86Util::getInstIdByName("pop"))
|| (l.getInstruction() == X86Util::getInstIdByName("push")))
l.addRegOut(rsp);
// mulx writes to two outputs
if (l.getInstruction() == X86Util::getInstIdByName("mulx"))
l.addRegOut(*static_cast<const X86Reg*>(l.getOpPtr(1)));
// xchg writes to both outputs
if (l.getInstruction() == X86Util::getInstIdByName("xchg") && l.getOp(1).isReg())
l.addRegOut(*static_cast<const X86Reg*>(l.getOpPtr(1)));
}
// if Line1 and Line2 can be transforming swapped adds the corresponding
// Transform to transforms and returns 1
// Currently only lea/mov instructions can be transformed with add/sub/inc/dec
static int addTransformBy(Line& line1, int index1, Line& line2, int index2,
vector<Transform>& transforms)
{
if (!line1.isInstruction() || !line2.isInstruction())
return 0;
X86Mem* mem = nullptr;
if (line1.getInstruction() == X86Util::getInstIdByName("lea"))
mem = static_cast<X86Mem*>(line1.getOpPtr(1));
if (line1.getInstruction() == X86Util::getInstIdByName("mov"))
{
if (line1.getOp(0).isMem())
mem = static_cast<X86Mem*>(line1.getOpPtr(0));
else if (line1.getOp(1).isMem())
mem = static_cast<X86Mem*>(line1.getOpPtr(1));
}
if (mem != nullptr)
{
int32_t base = 0;
if (line2.getInstruction() == X86Util::getInstIdByName("inc"))
base = 1;
if (line2.getInstruction() == X86Util::getInstIdByName("dec"))
base = -1;
if (line2.getInstruction() == X86Util::getInstIdByName("add") &&
line2.getOpPtr(1)->isImm())
base = static_cast<Imm*>(line2.getOpPtr(1))->getInt32();
if (line2.getInstruction() == X86Util::getInstIdByName("sub") &&
line2.getOpPtr(1)->isImm())
base = -static_cast<Imm*>(line2.getOpPtr(1))->getInt32();
if (base == 0)
return 0;
if (index1 < index2)
base = -base;
int32_t adjustment = 0;
X86GpReg* reg = static_cast<X86GpReg*>(line2.getOpPtr(0));
if (mem->getBase() == reg->getRegIndex())
adjustment += base;
if (mem->getIndex() == reg->getRegIndex())
adjustment += base << mem->getShift();
if (adjustment != 0)
{
transforms.push_back(Transform(index1, index2, Transform::changeDisp, adjustment));
return 1;
}
}
return 0;
}
// add dependency and transform info to lines in func
static void addDepsAndTransforms(vector<Line>& func, vector<Transform>& transforms)
{
int index2 = 0;
for (vector<Line>::iterator line2 = func.begin(); line2 != func.end();
++line2, index2++)
{
// try to determine other dependencies
int index1 = 0;
for (vector<Line>::iterator line1 = func.begin(); line1 != line2;
++line1, index1++)
{
if (addTransformBy(*line1, index1, *line2, index2, transforms))
continue;
if (addTransformBy(*line2, index2, *line1, index1, transforms))
continue;
if (dependsOn(line2, line1, func))
{
if (find(line2->getDependencies().begin(),
line2->getDependencies().end(), index1) ==
line2->getDependencies().end())
{
line2->addDependency(index1);
// we can now remove any of prevLine's dependencies from newLine
// TODO does this make things faster?
std::vector<int>::iterator position =
line2->getDependencies().begin();
for (vector<int>::iterator ci2 =
line1->getDependencies().begin(); ci2 !=
line1->getDependencies().end(); ++ci2)
{
position = std::find(position, line2->getDependencies().end(), *ci2);
if (position != line2->getDependencies().end())
position = line2->getDependencies().erase(position);
}
}
}
}
}
}
static void removeTransforms(vector<Transform>& transforms, int index)
{
for (vector<Transform>::iterator i = transforms.begin(); i != transforms.end(); ++i)
{
//vector<int>& v = i->getDependencies();
//v.erase(std::remove_if(v.begin(), v.end(), std::bind1st(std::equal_to<int>(), index)), v.end());
}
}
static void removeDeps(vector<Line>::iterator start, vector<Line>::iterator end,
int index)
{
for (vector<Line>::iterator i = start; i != end; ++i)
{
vector<int>* v = &(i->getDependencies());
v->erase(std::remove(v->begin(), v->end(), index), v->end());
}
}
static void shiftDeps(vector<Line>::iterator start, vector<Line>::iterator end,
int index, int shift)
{
for (vector<Line>::iterator i = start; i != end; ++i)
{
for (vector<int>::iterator dep = i->getDependencies().begin(); dep != i->getDependencies().end(); ++dep)
{
if (*dep >= index)
(*dep) += shift;
}
}
}
static void shiftTransforms(vector<Transform>& transforms, int index, int shift)
{
for (vector<Transform>::iterator i = transforms.begin(); i != transforms.end(); ++i)
{
if (i->a >= index)
(i->a) += shift;
if (i->b >= index)
(i->b) += shift;
}
}
// core parsing function, loads lines from either the filename given in
// input or stdin if this is null and converts them to Lines which are
// returned in func
static int loadFunc(vector<Line>& func, const char* input,
const int intelSyntax, vector<Transform>& transforms, int removeLabels)
{
map<string, Label> labels; // map of label names to Label objects
map<string, int> useCounts;
map<int, vector<int>> depGroups;
// if we are given a file path use it, otherwise try stdin.
ifstream ifs;
if (input != NULL)
ifs.open(input);
istream& is = input != NULL ? ifs : cin;
string str;
if (is.fail())
{
printf("# error: opening file failed, is filename correct?\n");
return -1;
}
assembler.reset();
if (verbose >= 2) {
assembler.setLogger(&logger);
}
// set which chars define which line types based on intelSyntax flag
const char commentChar = intelSyntax ? ';' : '#';
const char directiveChar = intelSyntax ? '[' : '.';
while (getline(is, str))
{
str = trim(str);
if (str.length() == 0)
continue;
std::vector<string> parsed = split2(str, '\t', ' ');
while (parsed.size() > 0)
{
parsed[0] = trim(parsed[0]);
if (parsed[0].length() == 0)
{
parsed.erase(parsed.begin());
continue;
}
// first char is the comment character so we have a comment
if (parsed[0].at(0) == commentChar)
break;
// first char is the %, the nasm syntax macro character, ignore
if (parsed[0].at(0) == '%')
break;
Line newLine;
if (*parsed[0].rbegin() == ':') // last character of first token is colon, so we are at a label
{
string label = parsed[0].substr(0, parsed[0].size() - 1);
if (labels.count(label) == 0)
{
labels[label] = assembler.newLabel();
useCounts[label] = 0;
}
newLine.setLabel(labels[label].getId());
parsed.erase(parsed.begin());
}
else if (parsed[0].at(0) == directiveChar) // first char is the directive character so we have a directive
{
if (parsed[0].substr(1, 5) == "align") {
parsed.erase(parsed.begin());
std::vector<std::string> args = split(parsed[0], ',');
while (parsed.size() > 0) // done with this line
parsed.erase(parsed.begin());
newLine.setAlign(getVal(args[0]));
}
else if (parsed[0] == ".byte") {
parsed.erase(parsed.begin());
std::vector<std::string> args = split(parsed[0], ',');
while (parsed.size() > 0) // done with this line
parsed.erase(parsed.begin());
newLine.setByte(getVal(args[0]));
}
else // ignore non-align/byte directives
{
break;
}
}
else if (intelSyntax && parsed[0] == "db") // yasm pseudo instructions TODO check for more
{
parsed.erase(parsed.begin());
std::vector<std::string> args = split(parsed[0], ',');
while (parsed.size() > 0) // done with this line
parsed.erase(parsed.begin());
newLine.setByte(getVal(args[0]));
}
else // normal instruction
{
if (parsed[0] == "ASM_START") // TODO this probably shouldn't be in any files at all...
break;
if (parsed[0] == "GLOBAL_FUNC") // TODO this probably shouldn't be in any files at all...
break;
if (parsed[0] == "end") // a fake instruction sometimes in nasm syntax files, ignored
break;
if (parsed[0].substr(0, 8) == "prefetch") // prefetch instructions should be given extra arguments for asmjit
{
char c = parsed[0].at(9) + 1;
if (c == 't' + 1) // prefetchnta
c = '0';
parsed[1] = (string("$") + c + ',') + parsed[1];
parsed[0] = "prefetch";
}
if (parsed[0] == "jrcxz" || parsed[0] == "jecxz") // add extra arg to jr/ecx instrs
{
if (intelSyntax) {
parsed[1] = parsed[0].substr(1, 3) + ',' + parsed[1];
}
else {
parsed[1] = parsed[1] + ",%" + parsed[0].substr(1, 3);
}
parsed[0] = "jecxz";
}
if (0 && parsed[0] == "movq")
parsed[0] = "mov";
uint32_t id = X86Util::getInstIdByName(parsed[0].c_str());
uint32_t size = 0;
if (id == kInstIdNone)
{
size = 1;
// last character of instruction is q,l,w,b try removing it
switch (*parsed[0].rbegin())
{
case 'q':
size *= 2;
case 'l':
size *= 2;
case 'w':
size *= 2;
case 'b':
id = X86Util::getInstIdByName(parsed[0].substr(0, parsed[0].size() - 1).c_str());
}
}
newLine.setInstruction(id, str.c_str());
parsed.erase(parsed.begin());
while (parsed.size() >= 2)
{
if (!parsed[1].size())
{
parsed.erase(parsed.begin() + 1);
continue;
}
if (parsed[1].at(0) == commentChar)
break;
parsed[0] += parsed[1];
parsed.erase(parsed.begin() + 1);
}
if (parsed.size() > 0)
{
std::vector<std::string> args = split(parsed[0], ',');
parsed.erase(parsed.begin());
// stick bracketed expressions back together again
for (size_t j = 0; j < args.size(); j++)
{
string arg = args[j];
if (count(arg.begin(), arg.end(), '(') != count(arg.begin(), arg.end(), ')'))
{
assert(j < args.size() - 1);
args[j] = args[j] + "," + args[j + 1];
args.erase(args.begin() + j + 1);
j--;
}
}
if (!intelSyntax)
reverse(args.begin(), args.end());
// if we have shr/shl with only a single argument add the argument 1 for asmjit
if (args.size() == 1 && (id == X86Util::getInstIdByName("shr") ||
id == X86Util::getInstIdByName("shl")))
args.push_back(intelSyntax ? "1" : "$1");
for (size_t i = 0; i < args.size(); i++)
newLine.setOp(i, getOpFromStr(args[i], labels, useCounts, size, intelSyntax));
}
addRegsRead(newLine);
addRegsWritten(newLine);
}
// check for dependencies annotated in the source
if (parsed.size() > 0 && parsed[0].size() > 0 && parsed[0].at(0) == commentChar) {
// Drop the comment char
parsed[0].erase(0, 1);
/* If there was any whitespace after the comment char, skip to next word */
while (parsed.size() > 0 && parsed[0].size() == 0) {
parsed.erase(parsed.begin());
}
if (parsed.size() > 0 && parsed[0].size() > 4 && parsed[0].substr(0, 4) == "ajs:")
{
std::vector<std::string> deps = split(parsed[0].substr(4), ',');
parsed.erase(parsed.begin());
for (vector<string>::const_iterator ci = deps.begin(); ci != deps.end(); ++ci)
{
if(ci->compare("notshortform") == 0) {
if (X86Util::getInstInfo(newLine.getInstruction()).getExtendedInfo().isFlow()) {
newLine.addOption(Line::OptNotShortForm);
} else {
printf ("# Warning: the following line has ajs:notshortform annotation but is not control flow. "
"Ignoring annotation.\n# %s\n", str.c_str());
}
continue;
}
int group = atoi(ci->c_str());
if (depGroups.count(group) == 0)
depGroups[group] = vector<int>();
for (vector<int>::iterator dep = depGroups[group].begin(); dep != depGroups[group].end(); ++dep)
newLine.addDependency(*dep);
depGroups[group].push_back(func.size());
}
}
}
if (!newLine.isValid()) {
cout << "Error parsing: " << str << endl;
assert(newLine.isValid());
}
func.push_back(newLine);
if (verbose >= 2) {
cout << "# Parsed line " << func.size() << ": " << str << endl;
if (newLine.isInstruction()) {
assembler.emit(newLine.getInstruction(), newLine.getOp(0), newLine.getOp(1),
newLine.getOp(2), newLine.getOp(3));
} else if (newLine.isLabel()) {
cout << "L" << newLine.getLabel() << ":" << endl;
}
}
}
}
assembler.reset();
// Remove unused labels
for (map<string, Label>::iterator i = labels.begin(); removeLabels &&
i != labels.end(); ++i)
{
if (useCounts[i->first] == 0)
{
int index = 0;
vector<Line>::iterator j = func.begin();
for (; j != func.end(); index++, ++j)
{
if (j->isLabel() && (j->getLabel() == i->second.getId()))
{
j = func.erase(j);
break;
}
}
removeDeps(j, func.end(), index);
shiftDeps(j, func.end(), index, -1);
}
}
addDepsAndTransforms(func, transforms);
return labels.size();
}
// integer compare
static int comp(const void * a, const void * b)
{
return *(int*)a - *(int*)b;
}
// calls the function given by funcPtr and returns the approximate number
// of cycles taken
static double callFunc(void* funcPtr,
const double overhead, uint64_t arg1,
uint64_t arg2, uint64_t arg3, uint64_t arg4, uint64_t arg5, uint64_t arg6)
{
double total;
int k = 0;
// Using asmjit_cast is purely optional, it's basically a C-style cast
// that tries to make it visible that a function-type is returned.
FuncType callableFunc = asmjit_cast<FuncType>(funcPtr);
/* Call function a few times to fetch code and data into caches,
* set up branch prediction, etc. */
repeat_func_call(callableFunc, PREFETCH_CALLS, arg1, arg2, arg3, arg4, arg5, arg6);
total = -1;
for (int i = 0; i < TRIALS; i++)
{
for (k = 0; k < LOOPSIZE; k++)
{
start_timing();
repeat_func_call(callableFunc, REPEATS, arg1, arg2, arg3, arg4, arg5, arg6);
end_timing();
times[i] = get_diff_timing();
}
}
qsort(times, TRIALS, sizeof(int), comp);
total = 0.;
const size_t min_freq = 100 / sqrt(REPEATS);
unsigned long total_sum = 0, total_weight = 0;
size_t cur_idx = 0;
for (size_t i = 1 ; i <= TRIALS; i++) {
if (i == TRIALS || times[i] != times[cur_idx]) {
unsigned long count = i - cur_idx;
if (count >= min_freq) {
total_sum += count * times[cur_idx];
total_weight += count;
}
cur_idx = i;
}
}
if (total_weight > 0) {
total = (double) total_sum / (double) total_weight / (double) REPEATS;
} else {
total = -1.;
if (verbose >= 1) {
cout << "# No conclusive timings: total=" << total << ", ";
print_histogram(times, TRIALS);
cout << endl;
}
}
if (verbose && 0) {
printf("# Timing resulted in %f cycles of which %f are overhead\n", total, overhead);
print_histogram(times, TRIALS);
cout << endl;
}
return round(total);
}
// adds the function func with the permutation perm applied to the X86Assembler
static void addFunc(vector<Line>& func, list<int>& perm, int numLabels, vector<Transform>* transforms)
{
Label labels[numLabels];
for (int i = 0; i < numLabels; i++)
labels[i] = assembler.newLabel();
for (list<int>::iterator ci = perm.begin(); ci != perm.end(); ++ci)
{
Line curLine = func[*ci];
if (transforms != NULL) {
for (vector<Transform>::const_iterator ti = transforms->begin(); ti != transforms->end(); ++ti)
{
if (*ci == ti->a) // possibly have a transform to make
{
if ((find(perm.begin(), ci, ti->b) != ci) ^ (ti->b < ti->a)) // have a transform to make
ti->apply(curLine);
}
}
}
if (curLine.isAlign()) {
assembler.align(kAlignCode, curLine.getAlign());
}
if (curLine.isLabel()) {
assembler.bind(labels[curLine.getLabel()]);
numLabels--;
}
if (curLine.isByte()) {
uint8_t* cursor = assembler.getCursor();
if ((size_t)(assembler._end - cursor) < 16)
{
assembler._grow(16);
cursor = assembler.getCursor();
}
cursor[0] = curLine.getByte();
cursor += 1;
if (assembler.hasLogger())
assembler.getLogger()->logFormat(Logger::kStyleDefault,"\t.byte\t%d\n", curLine.getByte());
}
if (!curLine.isInstruction())
continue;
for (int i = 0; i < MAX_OPS; i++)
{
if (curLine.getOp(i).isLabel()) {
curLine.setOp(i, labels[curLine.getOp(i).getId()]);
}
}
if (verbose && assembler.hasLogger()) {
assembler.getLogger()->logFormat(Logger::kStyleComment,"# %s\n", curLine.getOrigLine());
}
if (X86Util::getInstInfo(curLine.getInstruction()).getExtendedInfo().isFlow()) {
if (curLine.hasOption(Line::OptNotShortForm)) {
/* FIXME: ugly hack! Assembler has no accessor functions, though :( */
assembler._comment = "ajs:notshortform";
} else {
assembler.setInstOptions(kInstOptionShortForm);
}
}
asmjit::Error error = assembler.emit(curLine.getInstruction(), curLine.getOp(0),
curLine.getOp(1), curLine.getOp(2), curLine.getOp(3));
if (error != 0) {
cout << "asmjit Error: " << error << ", input line was: " << curLine.getOrigLine() << endl;
abort();
}
}
if (0 && numLabels > 0)
{
printf("error: %d label(s) not bound, are all label names correct?\n", numLabels);
exit(EXIT_FAILURE);
}
}
// makes a callable function using assembler then times the generated function with callFunc.
static double timeFunc(vector<Line>& func, list<int>& perm,
int numLabels, double overhead, const bool doCheckResult,
vector<Transform>* transforms,
uint64_t arg1, uint64_t arg2, uint64_t arg3, uint64_t arg4,
uint64_t arg5, uint64_t arg6)
{
static void *last_funcPtr = NULL;
assembler.reset();
addFunc(func, perm, numLabels, transforms);
void* funcPtr = assembler.make();
asmjit::Error error = assembler.getLastError();
if (error != 0) {
cout << "asmjit error: " << error << endl;
abort();
}
assert(funcPtr != NULL);
if (funcPtr != last_funcPtr) {
printf("# funcPtr = %p\n", funcPtr);
last_funcPtr = funcPtr;
}
double times;
long nivcsw = 0;