-
Notifications
You must be signed in to change notification settings - Fork 1
/
bf-jit.cpp
79 lines (71 loc) · 2.04 KB
/
bf-jit.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
#include <stdio.h>
#include <stack>
#define MEMSIZE 30000
#define CODESIZE 50000
#include <xbyak/xbyak.h>
char* toLabel(char ch, int num) {
static char labelbuf[BUFSIZ];
snprintf(labelbuf, sizeof(labelbuf), "%c%d", ch, num);
return labelbuf;
}
void parse(Xbyak::CodeGenerator &gen, FILE *input, int membuf[MEMSIZE]) {
gen.push(gen.ebx);
Xbyak::Reg32 memreg = gen.ebx;
Xbyak::Address mem = gen.dword[memreg];
gen.mov(memreg, (Xbyak::uint32) membuf);
std::stack<int> labelStack;
int labelNum = 0;
int ch;
while((ch=getc(input)) != EOF) {
switch (ch) {
case '+':
gen.inc(mem);
break;
case '-':
gen.dec(mem);
break;
case '>':
gen.add(memreg, 4);
break;
case '<':
gen.add(memreg, -4);
break;
case ',':
gen.call((void*) getchar);
gen.mov(mem, gen.eax);
break;
case '.':
gen.push(mem);
gen.call((void*) putchar);
gen.pop(gen.eax);
break;
case '[':
gen.L(toLabel('L', labelNum));
gen.mov(gen.eax, mem);
gen.test(gen.eax, gen.eax);
gen.jz(toLabel('R', labelNum), Xbyak::CodeGenerator::T_NEAR);
labelStack.push(labelNum);
++labelNum;
break;
case ']':
int beginNum = labelStack.top();
labelStack.pop();
gen.jmp(toLabel('L', beginNum), Xbyak::CodeGenerator::T_NEAR);
gen.L(toLabel('R', beginNum));
break;
}
}
gen.pop(gen.ebx);
gen.ret();
}
void execute(Xbyak::CodeGenerator &gen) {
void (*codes)() = (void (*)()) gen.getCode();
codes();
}
int main() {
static int membuf[MEMSIZE];
Xbyak::CodeGenerator gen(CODESIZE);
parse(gen, stdin, membuf);
execute(gen);
return 0;
}