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
|
//
// .s to WebAssembly translator.
//
#include "wasm.h"
#include "parsing.h"
namespace wasm {
extern int debug; // wasm::debug is set in main(), typically from an env var
//
// S2WasmBuilder - parses a .s file into WebAssembly
//
class S2WasmBuilder {
AllocatingModule& wasm;
MixedArena& allocator;
char *s;
public:
S2WasmBuilder(AllocatingModule& wasm, char *s) : wasm(wasm), allocator(wasm.allocator), s(s) {
process();
}
private:
// utilities
void skipWhitespace() {
while (1) {
while (*s && isspace(*s)) s++;
if (*s != '#') break;
while (*s != '\n') s++;
}
}
bool skipComma() {
skipWhitespace();
if (*s != ',') return false;
s++;
skipWhitespace();
return true;
}
void findComma() {
while (*s && *s != ',') s++;
s++;
skipWhitespace();
}
// match and skip the pattern, if matched
bool match(const char *pattern) {
size_t size = strlen(pattern);
if (strncmp(s, pattern, size) == 0) {
s += size;
skipWhitespace();
return true;
}
return false;
}
void mustMatch(const char *pattern) {
bool matched = match(pattern);
assert(matched);
}
#define abort_on(why) { \
printf("%s : %20s\n", why, s); \
abort(); \
}
void dump(const char *text) {
std::cerr << "[[" << text << "]]:\n==========\n";
for (size_t i = 0; i < 60; i++) {
if (!s[i]) break;
std::cerr << s[i];
}
std::cerr << "\n==========\n";
}
void unget(Name str) {
s -= strlen(str.str);
}
Name getStr() {
std::string str;
while (*s && !isspace(*s)) {
str += *s;
s++;
}
return cashew::IString(str.c_str(), false);
}
Name getStrToComma() {
std::string str;
while (*s && !isspace(*s) && *s != ',') {
str += *s;
s++;
}
return cashew::IString(str.c_str(), false);
}
Name getStrToColon() {
std::string str;
while (*s && !isspace(*s) && *s != ':') {
str += *s;
s++;
}
return cashew::IString(str.c_str(), false);
}
Name getCommaSeparated() {
skipWhitespace();
std::string str;
while (*s && *s != ',') {
str += *s;
s++;
}
skipWhitespace();
return cashew::IString(str.c_str(), false);
}
Name getAssign() {
skipWhitespace();
std::string str;
while (*s && *s != '=') {
str += *s;
s++;
}
s++;
skipComma();
return cashew::IString(str.c_str(), false);
}
Name getQuoted() { // TODO: support 0 in the middle, etc., use a raw buffer, etc.
assert(*s == '"');
s++;
std::string str;
while (*s && *s != '\"') {
str += *s;
s++;
}
skipWhitespace();
return cashew::IString(str.c_str(), false);
}
WasmType getType() {
if (match("i32")) return i32;
if (match("i64")) return i64;
if (match("f32")) return f32;
if (match("f64")) return f64;
abort_on("getType");
}
// processors
void process() {
while (*s) {
skipWhitespace();
if (!*s) break;
if (*s != '.') break;
s++;
if (match("text")) parseText();
else if (match("type")) parseType();
else abort_on(s);
}
}
void parseText() {
while (*s) {
skipWhitespace();
if (!*s) break;
if (*s != '.') break;
s++;
if (match("file")) parseFile();
else if (match("globl")) parseGlobl();
else break;
}
}
void parseFile() {
assert(*s == '"');
s++;
std::string filename;
while (*s != '"') {
filename += *s;
s++;
}
s++;
// TODO: use the filename?
}
void parseGlobl() {
unsigned nextId = 0;
auto getNextId = [&nextId]() {
return cashew::IString(('$' + std::to_string(nextId++)).c_str(), false);
};
Name name = getStr();
skipWhitespace();
mustMatch(".type");
mustMatch(name.str);
mustMatch(",@function");
mustMatch(name.str);
mustMatch(":");
auto func = allocator.alloc<Function>();
std::map<Name, WasmType> localTypes;
// params and result
while (1) {
if (match(".param")) {
while (1) {
Name name = getNextId();
WasmType type = getType();
func->params.emplace_back(name, type);
localTypes[name] = type;
skipWhitespace();
if (!match(",")) break;
}
} else if (match(".result")) {
func->result = getType();
} else break;
}
// parse body
func->body = allocator.alloc<Block>();
std::vector<Block*> bstack;
bstack.push_back(func->body->dyn_cast<Block>());
std::vector<Expression*> estack;
auto push = [&](Expression* curr) {
//std::cerr << "push " << curr << '\n';
estack.push_back(curr);
};
auto pop = [&]() {
assert(!estack.empty());
Expression* ret = estack.back();
assert(ret);
estack.pop_back();
//std::cerr << "pop " << ret << '\n';
return ret;
};
auto getInput = [&]() {
//dump("getinput");
if (match("$pop")) {
while (isdigit(*s)) s++;
return pop();
} else {
auto curr = allocator.alloc<GetLocal>();
curr->name = getStrToComma();
curr->type = localTypes[curr->name];
return (Expression*)curr;
}
};
auto setOutput = [&](Expression* curr, Name assign) {
if (assign.str[1] == 'p') { // push
estack.push_back(curr);
} else if (assign.str[1] == 'd') { // discard
bstack.back()->list.push_back(curr);
} else { // set to a local
auto set = allocator.alloc<SetLocal>();
set->name = assign;
set->value = curr;
set->type = curr->type;
bstack.back()->list.push_back(set);
}
};
auto makeBinary = [&](BinaryOp op, WasmType type) {
Name assign = getAssign();
skipComma();
auto curr = allocator.alloc<Binary>();
curr->op = op;
curr->right = getInput();
skipComma();
curr->left = getInput();
curr->finalize();
assert(curr->type == type);
setOutput(curr, assign);
};
// fixups
typedef std::pair<Const*, Name> Addressing;
std::vector<Addressing> addressings;
std::vector<Block*> loopBlocks; // we need to clear their names
std::set<Name> seenLabels; // if we already used a label, we don't need it in a loop (there is a block above it, with that label)
// main loop
while (1) {
skipWhitespace();
//dump("main function loop");
if (match("i32.")) {
switch (*s) {
case 'a': {
if (match("add")) makeBinary(BinaryOp::Add, i32);
else if (match("and")) makeBinary(BinaryOp::And, i32);
else abort_on("i32.a");
break;
}
case 'c': {
if (match("const")) {
mustMatch("$push");
findComma();
if (*s == '.') {
// global address
auto curr = allocator.alloc<Const>();
curr->type = i32;
addressings.emplace_back(curr, getStr());
push(curr);
} else {
// constant
push(parseConst(getStr(), i32, allocator));
}
} else abort_on("i32.c");
break;
}
case 'e': {
if (match("eq")) makeBinary(BinaryOp::Eq, i32);
break;
}
case 'g': {
if (match("gt_s")) makeBinary(BinaryOp::GtS, i32);
else if (match("gt_u")) makeBinary(BinaryOp::GtU, i32);
else abort_on("i32.g");
break;
}
case 'n': {
if (match("ne")) makeBinary(BinaryOp::Ne, i32);
else abort_on("i32.n");
break;
}
case 'r': {
if (match("rem_s")) makeBinary(BinaryOp::RemS, i32);
else if (match("rem_u")) makeBinary(BinaryOp::RemU, i32);
else abort_on("i32.n");
break;
}
case 's': {
if (match("shr_s")) makeBinary(BinaryOp::ShrS, i32);
else if (match("shr_u")) makeBinary(BinaryOp::ShrU, i32);
else if (match("sub")) makeBinary(BinaryOp::Sub, i32);
else abort_on("i32.s");
break;
}
default: abort_on("i32.?");
}
} else if (match("call")) {
Name assign = getAssign();
skipComma();
auto curr = allocator.alloc<Call>();
curr->target = getCommaSeparated();
while (1) {
if (!skipComma()) break;
curr->operands.push_back(getInput());
}
std::reverse(curr->operands.begin(), curr->operands.end());
setOutput(curr, assign);
} else if (match("block")) {
auto curr = allocator.alloc<Block>();
curr->name = getStr();
bstack.back()->list.push_back(curr);
bstack.push_back(curr);
seenLabels.insert(curr->name);
} else if (match("BB")) {
s -= 2;
Name name = getStrToColon();
s++;
skipWhitespace();
// pop all blocks/loops that reach this target
// pop all targets with this label
while (!bstack.empty()) {
auto curr = bstack.back();
if (curr->name == name) {
bstack.pop_back();
continue;
}
break;
}
// this may also be a loop beginning
if (*s == 'l') {
auto curr = allocator.alloc<Loop>();
bstack.back()->list.push_back(curr);
curr->in = name;
mustMatch("loop");
Name out = getStr();
if (seenLabels.count(out) == 0) {
curr->out = out;
}
auto block = allocator.alloc<Block>();
block->name = out; // temporary, fake
curr->body = block;
loopBlocks.push_back(block);
bstack.push_back(block);
}
} else if (match("br")) {
auto curr = allocator.alloc<Break>();
if (*s == '_') {
mustMatch("_if");
curr->condition = getInput();
skipComma();
}
curr->name = getStr();
bstack.back()->list.push_back(curr);
} else if (match("return")) {
Block *temp;
if (!(func->body && (temp = func->body->dyn_cast<Block>()) && temp->name == FAKE_RETURN)) {
Expression* old = func->body;
temp = allocator.alloc<Block>();
temp->name = FAKE_RETURN;
if (old) temp->list.push_back(old);
func->body = temp;
}
auto curr = allocator.alloc<Break>();
curr->name = FAKE_RETURN;
if (*s == '$') {
curr->value = getInput();
}
bstack.back()->list.push_back(curr);
} else if (match("func_end0:")) {
mustMatch(".size");
mustMatch("main,");
mustMatch("func_end0-main");
break; // the function is done
} else {
abort_on("function element");
}
}
// finishing touches
bstack.pop_back(); // remove the base block for the function body
assert(bstack.empty());
assert(estack.empty());
for (auto block : loopBlocks) {
block->name = Name();
}
wasm.addFunction(func);
}
void parseType() {
Name name = getStrToComma();
mustMatch("@object");
mustMatch(name.str);
mustMatch(":");
mustMatch(".asciz");
Name buffer = getQuoted();
mustMatch(".size");
mustMatch(name.str);
mustMatch(",");
Name size = getStr();
}
};
} // namespace wasm
|