-
Notifications
You must be signed in to change notification settings - Fork 0
/
brainfuck_jit.cpp
219 lines (184 loc) · 6.23 KB
/
brainfuck_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
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
//#define ASMJIT_STATIC
#ifdef _MSC_VER
#pragma warning(disable: 4996)
#endif
#include <stdio.h>
#include <time.h>
#include <vector>
#include "asmjit/x86.h"
using namespace asmjit;
#define MAX_STACK 1024
#define MAX_LOOP 64
class Brainfuck
{
private:
const char *name;
const char *prog;
// JIT runtime
JitRuntime rt;
CodeHolder code;
// Product
void (*func)() = nullptr;
// Loop
struct Loop {
Label start;
Label end;
Loop(x86::Compiler &cc)
: start(cc.newLabel()),
end(cc.newLabel()) {}
};
static int consumeOps(const char * &prog) {
int n = 1;
char op = *prog;
while (*prog++) {
switch (*prog) {
case '.': case ',':
case '[': case ']':
return n;
case '+': case '-':
case '>': case '<':
if (op != *prog) return n;
n++;
break;
}
}
return n;
}
public:
Brainfuck(const char *name, const char *prog)
: name(name), prog(prog) {}
~Brainfuck() {
if (func != nullptr) rt.release(func);
}
void execute() {
if (func != nullptr) {
func();
fflush(stdout);
}
}
bool compile() {
// Init env, compiler
code.init(rt.environment());
x86::Compiler cc(&code);
// Add function signature -> void (*func)()
cc.addFunc(FuncSignatureT<void>());
// Invokable
InvokeNode *invk;
// Loop stack
std::vector<Loop> loops;
// Main stack // char stack[MAX_STACK]
x86::Mem stack = cc.newStack(MAX_STACK, sizeof(void *));
// Stack pointer
x86::Gp sp = cc.newGpz(); // size_t sp
// Temp (u8)
x86::Gp tmp = cc.newGpb(); // char tmp
// Stack index (&idx := stack[sp])
x86::Mem idx(stack);
idx.setIndex(sp);
idx.setSize(sizeof(char));
// Clear the stack (memset zero)
cc.mov(sp, 0); // sp = 0
Label loop = cc.newLabel(); // loop:
cc.bind(loop);
cc.mov(idx, 0); // stack[i] = 0
cc.inc(sp); // sp++
cc.cmp(sp, MAX_STACK); // if sp < MAX_STACK then
cc.jb(loop); // goto loop
// Clear sp by xor
cc.xor_(sp, sp); // sp = 0
// Optimize for same + - > <
int n;
while (*prog) {
switch (*prog) {
case '>':
//cc.inc(sp); // sp++
// Same '>', eg: ">> >>> some comment >>"
// so n = 7, then we got "sp += 7"
n = consumeOps(prog);
cc.add(sp, n); // sp += [n]
continue;
case '<':
//cc.dec(sp); // sp--
n = consumeOps(prog);
cc.sub(sp, n); // sp -= [n]
continue;
case '+':
//cc.inc(idx); // stack[sp]++
n = consumeOps(prog);
cc.add(idx, n); // stack[sp] += [n]
continue;
case '-':
//cc.dec(idx); // stack[sp]--
n = consumeOps(prog);
cc.sub(idx, n); // stack[sp] -= [n]
continue;
case '.':
cc.mov(tmp, idx); // tmp = stack[sp]
cc.invoke(&invk, imm(&putchar),
FuncSignatureT<void, char>());
invk->setArg(0, tmp); // putchar(tmp)
break;
case ',':
cc.invoke(&invk, imm(&getchar),
FuncSignatureT<char>());
invk->setRet(0, tmp); // tmp = getchar()
cc.mov(idx, tmp); // stack[sp] = tmp
break;
case '[':
// Check loop depth
if (loops.size() >= MAX_LOOP) {
printf("[%s] compile error: Too many loops!\n", name);
return false;
}
loops.push_back(Loop(cc));
cc.bind(loops.back().start); // start:
cc.cmp(idx, 0); // if stack[sp] == 0 then
cc.je(loops.back().end); // goto end
break;
case ']':
// Check unmatched loop
if (loops.size() <= 0) {
printf("[%s] compile error: Unmatched loop!\n", name);
return false;
}
cc.jmp(loops.back().start); // goto start
cc.bind(loops.back().end); // end:
loops.pop_back();
break;
}
++prog;
}
cc.endFunc();
cc.finalize();
// Generate code
if (rt.add(&func, &code) != kErrorOk) {
printf("[%s] compile error: Couldn't generate code!\n", name);
return false;
}
return true;
}
};
int main(int argc, char **argv)
{
if (argc < 2) {
printf("Please enter file name!\n");
return 0;
}
FILE *fp = fopen(argv[argc - 1], "rb");
if (fp == nullptr) {
printf("Couldn't open file `%s`!\n", argv[argc - 1]);
return 0;
}
fseek(fp, 0, SEEK_END);
size_t fileSize = ftell(fp);
rewind(fp);
char *code = new char[fileSize + 1];
size_t bytesRead = fread(code, sizeof(char), fileSize, fp);
code[bytesRead] = '\0';
Brainfuck bf_main("main", code);
if (bf_main.compile()) {
bf_main.execute();
}
delete[] code;
return 0;
}