forked from WebAssembly/binaryen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paths2wasm.h
1547 lines (1467 loc) · 48.9 KB
/
s2wasm.h
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
/*
* Copyright 2015 WebAssembly Community Group participants
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// .s to WebAssembly translator.
//
#ifndef wasm_s2wasm_h
#define wasm_s2wasm_h
#include <limits.h>
#include "wasm.h"
#include "parsing.h"
#include "pass.h"
#include "asm_v_wasm.h"
#include "wasm-builder.h"
#include "wasm-linker.h"
namespace wasm {
//
// S2WasmBuilder - parses a .s file into WebAssembly
//
class S2WasmBuilder {
const char* inputStart;
const char* s;
bool debug;
Module* wasm;
MixedArena* allocator;
LinkerObject* linkerObj;
std::unique_ptr<LinkerObject::SymbolInfo> symbolInfo;
std::unordered_map<uint32_t, uint32_t> fileIndexMap;
public:
S2WasmBuilder(const char* input, bool debug)
: inputStart(input),
s(input),
debug(debug),
wasm(nullptr),
allocator(nullptr),
linkerObj(nullptr)
{}
void build(LinkerObject *obj) {
// If getSymbolInfo has not already been called, populate the symbol
// info now.
if (!symbolInfo) symbolInfo.reset(getSymbolInfo());
linkerObj = obj;
wasm = &obj->wasm;
allocator = &wasm->allocator;
s = inputStart;
process();
}
// getSymbolInfo scans the .s file to determine what symbols it defines
// and references.
LinkerObject::SymbolInfo* getSymbolInfo() {
if (!symbolInfo) {
symbolInfo = make_unique<LinkerObject::SymbolInfo>();
scan(symbolInfo.get());
}
return symbolInfo.get();
}
private:
// utilities
void skipWhitespace() {
while (1) {
while (*s && isspace(*s)) s++;
if (*s != '#') break;
while (*s != '\n') s++;
}
}
void skipToEOL() {
s = strchr(s, '\n');
assert(s);
}
bool skipComma() {
skipWhitespace();
if (*s != ',') return false;
s++;
skipWhitespace();
return true;
}
bool skipEqual() {
skipWhitespace();
if (*s != '=') return false;
s++;
skipWhitespace();
return true;
}
#define abort_on(why) { \
dump(why ":"); \
abort(); \
}
bool peek(const char *pattern) {
return strncmp(s, pattern, strlen(pattern)) == 0;
}
// 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);
if (!matched) {
std::cerr << "<< " << pattern << " >>\n";
abort_on("bad mustMatch");
}
}
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; // TODO: optimize this and the other get* methods
while (*s && !isspace(*s)) {
str += *s;
s++;
}
return cashew::IString(str.c_str(), false);
}
void skipToSep() {
while (*s && !isspace(*s) && *s != ',' && *s != '(' && *s != ')' && *s != ':' && *s != '+' && *s != '-') {
s++;
}
}
Name getStrToSep() {
std::string str;
while (*s && !isspace(*s) && *s != ',' && *s != '(' && *s != ')' && *s != ':' && *s != '+' && *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);
}
// get an int
int32_t getInt() {
const char* loc = s;
uint32_t value = 0;
bool neg = false;
if (*loc == '-') {
neg = true;
loc++;
}
while (isdigit(*loc)) {
uint32_t digit = *loc - '0';
if (value > std::numeric_limits<uint32_t>::max() / 10) {
abort_on("uint32_t overflow");
}
value *= 10;
if (value > std::numeric_limits<uint32_t>::max() - digit) {
abort_on("uint32_t overflow");
}
value += digit;
loc++;
}
if (neg) {
uint32_t positive_int_min =
(uint32_t) - (1 + std::numeric_limits<int32_t>::min()) + (uint32_t)1;
if (value > positive_int_min) {
abort_on("negative int32_t overflow");
}
s = loc;
return -value;
}
s = loc;
return value;
}
// get an int from an arbitrary string, with our full error handling
int32_t getInt(const char *from) {
const char *before = s;
s = from;
auto ret = getInt();
s = before;
return ret;
}
// gets a constant, which may be a relocation for later.
// returns whether this is a relocation
// TODO: Clean up this and the way relocs are created from parsed objects
LinkerObject::Relocation* getRelocatableConst(uint32_t* target) {
if (isdigit(*s) || *s == '-') {
int32_t val = getInt();
memcpy(target, &val, sizeof(val));
return nullptr;
}
// a global constant, we need to fix it up later
Name name = getStrToSep();
LinkerObject::Relocation::Kind kind = isFunctionName(name) ?
LinkerObject::Relocation::kFunction :
LinkerObject::Relocation::kData;
int offset = 0;
if (*s == '+') {
s++;
offset = getInt();
} else if (*s == '-') {
s++;
offset = -getInt();
}
return new LinkerObject::Relocation(
kind, target, fixEmLongjmp(cleanFunction(name)), offset);
}
Expression* relocationToGetGlobal(LinkerObject::Relocation* relocation) {
if (!relocation) {
return nullptr;
}
auto name = relocation->symbol;
auto g = allocator->alloc<GetGlobal>();
g->name = name;
g->type = i32;
// Optimization: store any nonnegative addends in their natural place.
// Only do this for positive addends because load/store offsets cannot be
// negative.
if (relocation->addend >= 0) {
*relocation->data = relocation->addend;
return g;
}
auto c = allocator->alloc<Const>();
c->type = i32;
c->value = Literal(relocation->addend);
auto add = allocator->alloc<Binary>();
add->type = i32;
add->op = AddInt32;
add->left = c;
add->right = g;
return add;
}
Expression* getRelocatableExpression(uint32_t* target) {
auto relocation = std::unique_ptr<LinkerObject::Relocation>(getRelocatableConst(target));
if (!relocation) {
return nullptr;
}
if (linkerObj->isObjectImplemented(relocation->symbol)) {
linkerObj->addRelocation(relocation.release());
return nullptr;
}
return relocationToGetGlobal(relocation.get());
}
int64_t getInt64() {
const char* loc = s;
uint64_t value = 0;
bool neg = false;
if (*loc == '-') {
neg = true;
loc++;
}
while (isdigit(*loc)) {
uint64_t digit = *loc - '0';
if (value > std::numeric_limits<uint64_t>::max() / 10) {
abort_on("uint64_t overflow");
}
value *= 10;
if (value > std::numeric_limits<uint64_t>::max() - digit) {
abort_on("uint64_t overflow");
}
value += digit;
loc++;
}
if (neg) {
uint64_t positive_int_min =
(uint64_t) - (1 + std::numeric_limits<int64_t>::min()) + (uint64_t)1;
if (value > positive_int_min) {
abort_on("negative int64_t overflow");
}
s = loc;
return -value;
}
s = loc;
return value;
}
Name getSeparated(char separator) {
skipWhitespace();
std::string str;
while (*s && *s != separator && *s != '\n') {
str += *s;
s++;
}
skipWhitespace();
return cashew::IString(str.c_str(), false);
}
Name getCommaSeparated() { return getSeparated(','); }
Name getAtSeparated() { return getSeparated('@'); }
Name getAssign() {
skipWhitespace();
if (*s != '$') return Name();
const char *before = s;
s++;
std::string str;
while (*s && *s != '=' && *s != '\n' && *s != ',') {
str += *s;
s++;
}
if (*s != '=') { // not an assign
s = before;
return Name();
}
s++;
skipComma();
return cashew::IString(str.c_str(), false);
}
std::vector<char> getQuoted() {
assert(*s == '"');
s++;
std::vector<char> str;
while (*s && *s != '\"') {
if (s[0] == '\\') {
switch (s[1]) {
case 'n': str.push_back('\n'); s += 2; continue;
case 'r': str.push_back('\r'); s += 2; continue;
case 't': str.push_back('\t'); s += 2; continue;
case 'f': str.push_back('\f'); s += 2; continue;
case 'b': str.push_back('\b'); s += 2; continue;
case '\\': str.push_back('\\'); s += 2; continue;
case '"': str.push_back('"'); s += 2; continue;
default: {
if (isdigit(s[1])) {
int code = (s[1] - '0')*8*8 + (s[2] - '0')*8 + (s[3] - '0');
str.push_back(char(code));
s += 4;
continue;
} else abort_on("getQuoted-escape");
}
}
}
str.push_back(*s);
s++;
}
s++;
skipWhitespace();
return str;
}
WasmType tryGetType() {
if (match("i32")) return i32;
if (match("i64")) return i64;
if (match("f32")) return f32;
if (match("f64")) return f64;
return none;
}
WasmType tryGetTypeWithoutNewline() {
const char* saved = s;
WasmType type = tryGetType();
if (type != none && strchr(saved, '\n') > s) {
s = saved;
type = none;
}
return type;
}
WasmType getType() {
WasmType t = tryGetType();
if (t != none) {
return t;
}
abort_on("getType");
}
// The LLVM backend emits function names as name@FUNCTION.
bool isFunctionName(Name name) {
return !!strstr(name.str, "@FUNCTION");
}
// Drop the @ and after it.
Name cleanFunction(Name name) {
if (!strchr(name.str, '@')) return name;
char *temp = strdup(name.str);
*strchr(temp, '@') = 0;
Name ret = cashew::IString(temp, false);
free(temp);
return ret;
}
// processors
void scan(LinkerObject::SymbolInfo* info) {
s = inputStart;
while (*s) {
skipWhitespace();
// add function definitions and aliases
if (match(".type")) {
Name name = getCommaSeparated();
skipComma();
if (!match("@function")) continue;
if (match(".hidden")) mustMatch(name.str);
mustMatch(name.str);
if (match(":")) {
info->implementedFunctions.insert(name);
} else if (match("=")) {
Name alias = getAtSeparated();
mustMatch("@FUNCTION");
auto ret = info->aliasedSymbols.insert({name, LinkerObject::SymbolAlias(alias, LinkerObject::Relocation::kFunction, 0)});
if (!ret.second) std::cerr << "Unsupported data alias redefinition: " << name << ", skipping...\n";
} else {
abort_on("unknown directive");
}
} else if (match(".import_global")) {
Name name = getStr();
info->importedObjects.insert(name);
s = strchr(s, '\n');
} else {
// add data aliases
Name lhs = getStrToSep();
// When the current line contains only one word, e.g.".text"
if (match("\n"))
continue;
// When the current line contains more than one word
if (!skipEqual()){
s = strchr(s, '\n');
if (!s) break;
continue;
}
// get the original name
Name rhs = getStrToSep();
assert(!isFunctionName(rhs));
Offset offset = 0;
if (*s == '+') {
s++;
offset = getInt();
}
// check if the rhs is already an alias
const auto alias = symbolInfo->aliasedSymbols.find(rhs);
if (alias != symbolInfo->aliasedSymbols.end() && alias->second.kind == LinkerObject::Relocation::kData) {
offset += alias->second.offset;
rhs = alias->second.symbol;
}
// add the new alias
auto ret = symbolInfo->aliasedSymbols.insert({lhs, LinkerObject::SymbolAlias(rhs,
LinkerObject::Relocation::kData, offset)});
if (!ret.second) std::cerr << "Unsupported function alias redefinition: " << lhs << ", skipping...\n";
}
}
}
void process() {
while (*s) {
skipWhitespace();
if (debug) dump("process");
if (!*s) break;
if (*s != '.') skipObjectAlias(false);
s++;
if (match("text")) parseText();
else if (match("type")) parseType();
else if (match("weak") || match("hidden") || match("protected") || match("internal")) getStr(); // contents are in the content that follows
else if (match("imports")) skipImports();
else if (match("data")) {}
else if (match("ident")) skipToEOL();
else if (match("section")) parseToplevelSection();
else if (match("align") || match("p2align")) skipToEOL();
else if (match("import_global")) {
skipToEOL();
skipWhitespace();
if (match(".size")) {
skipToEOL();
}
}
else if (match("globl")) parseGlobl();
else if (match("functype")) parseFuncType();
else skipObjectAlias(true);
}
}
void skipObjectAlias(bool prefix) {
if (debug) dump("object_alias");
// grab the dot that was consumed earlier
if (prefix) s--;
Name lhs = getStrToSep();
WASM_UNUSED(lhs);
if (!skipEqual()) abort_on("object_alias");
Name rhs = getStr();
WASM_UNUSED(rhs);
skipWhitespace();
// if no size attribute (e.g. weak symbol), skip
if (!match(".size")) return;
mustMatch(lhs.str);
mustMatch(",");
Name size = getStr();
WASM_UNUSED(size);
skipWhitespace();
}
void parseToplevelSection() {
auto section = getCommaSeparated();
// Skipping .debug_ sections
if (!strncmp(section.c_str(), ".debug_", strlen(".debug_"))) {
const char *next = strstr(s, ".section");
s = !next ? s + strlen(s) : next;
return;
}
// Initializers are anything in a section whose name begins with .init_array
if (!strncmp(section.c_str(), ".init_array", strlen(".init_array") - 1)) {
parseInitializer();
return;
}
s = strchr(s, '\n');
}
void parseInitializer() {
// Ignore the rest of the .section line
skipToEOL();
skipWhitespace();
// The section may start with .p2align
if (match(".p2align")) {
skipToEOL();
skipWhitespace();
}
mustMatch(".int32");
do {
linkerObj->addInitializerFunction(cleanFunction(getStr()));
skipWhitespace();
} while (match(".int32"));
}
void parseText() {
while (*s) {
skipWhitespace();
if (!*s) break;
if (*s != '.') break;
s++;
if (parseVersionMin());
else if (match("file")) parseFile();
else if (match("globl")) parseGlobl();
else if (match("type")) parseType();
else {
s--;
break;
}
}
}
void parseFile() {
if (*s != '"') {
// TODO: optimize, see recordFile below
size_t fileId = getInt();
skipWhitespace();
auto quoted = getQuoted();
uint32_t index = wasm->debugInfoFileNames.size();
fileIndexMap[fileId] = index;
wasm->debugInfoFileNames.push_back(std::string(quoted.begin(), quoted.end()));
s = strchr(s, '\n');
return;
}
// '.file' without first index argument points to bc-file
s++;
std::string filename;
while (*s != '"') {
filename += *s;
s++;
}
s++;
WASM_UNUSED(filename); // TODO: use the filename
}
void parseGlobl() {
linkerObj->addGlobal(getStr());
skipWhitespace();
}
void parseFuncType() {
auto decl = make_unique<FunctionType>();
Name rawName = getCommaSeparated();
skipComma();
if(match("void")) {
decl->result = none;
} else {
decl->result = getType();
}
while (*s && skipComma()) decl->params.push_back(getType());
std::string sig = getSig(decl.get());
decl->name = "FUNCSIG$" + sig;
FunctionType *ty = wasm->getFunctionTypeOrNull(decl->name);
Name name = fixEmEHSjLjNames(rawName, sig);
if (!ty) {
// The wasm module takes ownership of the FunctionType if we insert it.
// Otherwise it's already in the module and ours is freed.
ty = decl.release();
wasm->addFunctionType(ty);
}
linkerObj->addExternType(name, ty);
}
bool parseVersionMin() {
if (match("watchos_version_min") || match("tvos_version_min") || match("ios_version_min") || match("macosx_version_min")) {
s = strchr(s, '\n');
skipWhitespace();
return true;
} else
return false;
}
void parseFunction() {
if (debug) dump("func");
Name name = getStrToSep();
if (match(" =")) {
/* alias = */ getAtSeparated();
mustMatch("@FUNCTION");
return;
}
mustMatch(":");
Function::DebugLocation debugLocation = { 0, 0, 0 };
bool useDebugLocation = false;
auto recordFile = [&]() {
if (debug) dump("file");
size_t fileId = getInt();
skipWhitespace();
auto quoted = getQuoted();
uint32_t index = wasm->debugInfoFileNames.size();
fileIndexMap[fileId] = index;
wasm->debugInfoFileNames.push_back(std::string(quoted.begin(), quoted.end()));
s = strchr(s, '\n');
};
auto recordLoc = [&]() {
if (debug) dump("loc");
size_t fileId = getInt();
skipWhitespace();
uint32_t row = getInt();
skipWhitespace();
uint32_t column = getInt();
auto iter = fileIndexMap.find(fileId);
if (iter == fileIndexMap.end()) {
abort_on("idx");
}
useDebugLocation = true;
debugLocation = { iter->second, row, column };
s = strchr(s, '\n');
};
auto recordLabel = [&]() {
if (debug) dump("label");
Name label = getStrToSep();
// TODO: track and create map of labels and their ranges for our AST
WASM_UNUSED(label);
s = strchr(s, '\n');
};
unsigned nextId = 0;
auto getNextId = [&nextId]() {
return cashew::IString(std::to_string(nextId++).c_str(), false);
};
wasm::Builder builder(*wasm);
std::vector<NameType> params;
WasmType resultType = none;
std::vector<NameType> vars;
std::map<Name, WasmType> localTypes;
// params and result
while (1) {
if (match(".param")) {
while (1) {
Name name = getNextId();
WasmType type = getType();
params.emplace_back(name, type);
localTypes[name] = type;
skipWhitespace();
if (!match(",")) break;
}
} else if (match(".result")) {
resultType = getType();
} else if (match(".indidx")) {
int64_t indirectIndex = getInt64();
skipWhitespace();
if (indirectIndex < 0) {
abort_on("indidx");
}
linkerObj->addIndirectIndex(name, indirectIndex);
} else if (match(".local")) {
while (1) {
Name name = getNextId();
WasmType type = getType();
vars.emplace_back(name, type);
localTypes[name] = type;
skipWhitespace();
if (!match(",")) break;
}
} else if (match(".file")) {
recordFile();
skipWhitespace();
} else if (match(".loc")) {
recordLoc();
skipWhitespace();
} else if (peek(".Lfunc_begin")) {
recordLabel();
skipWhitespace();
} else break;
}
Function* func = builder.makeFunction(name, std::move(params), resultType, std::move(vars));
// parse body
func->body = allocator->alloc<Block>();
std::vector<Expression*> bstack;
auto addToBlock = [&](Expression* curr) {
if (useDebugLocation) {
func->debugLocations[curr] = debugLocation;
}
Expression* last = bstack.back();
if (last->is<Loop>()) {
last = last->cast<Loop>()->body;
}
last->cast<Block>()->list.push_back(curr);
};
bstack.push_back(func->body);
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 getNumInputs = [&]() {
int ret = 1;
const char *t = s;
while (*t != '\n') {
if (*t == ',') ret++;
t++;
}
return ret;
};
auto getInputs = [&](int num) {
// we may have $pop, $0, $pop, $1 etc., which are getlocals
// interleaved with stack pops, and the stack pops must be done in
// *reverse* order, i.e., that input should turn into
// lastpop, getlocal(0), firstpop, getlocal(1)
std::vector<Expression*> inputs; // TODO: optimize (if .s format doesn't change)
inputs.resize(num);
for (int i = 0; i < num; i++) {
if (match("$pop")) {
skipToSep();
inputs[i] = nullptr;
} else if (*s == '$') {
s++;
auto curr = allocator->alloc<GetLocal>();
curr->index = func->getLocalIndex(getStrToSep());
curr->type = func->getLocalType(curr->index);
inputs[i] = curr;
} else {
abort_on("bad input register");
}
if (*s == ')') s++; // tolerate 0(argument) syntax, where we started at the 'a'
if (*s == ':') { // tolerate :attribute=value syntax (see getAttributes)
s++;
skipToSep();
}
if (i < num - 1) skipComma();
}
for (int i = num-1; i >= 0; i--) {
if (inputs[i] == nullptr) inputs[i] = pop();
}
return inputs;
};
auto getInput = [&]() {
return getInputs(1)[0];
};
auto setOutput = [&](Expression* curr, Name assign) {
if (assign.isNull() || assign.str[0] == 'd') { // drop
auto* add = curr;
if (isConcreteWasmType(curr->type)) {
add = builder.makeDrop(curr);
}
addToBlock(add);
} else if (assign.str[0] == 'p') { // push
push(curr);
} else { // set to a local
auto set = allocator->alloc<SetLocal>();
set->index = func->getLocalIndex(assign);
set->value = curr;
set->type = curr->type;
set->setTee(false);
addToBlock(set);
}
};
auto getAttributes = [&](int num) {
const char *before = s;
std::vector<const char*> attributes; // TODO: optimize (if .s format doesn't change)
attributes.resize(num);
for (int i = 0; i < num; i++) {
skipToSep();
if (*s == ')') s++; // tolerate 0(argument) syntax, where we started at the 'a'
if (*s == ':') {
attributes[i] = s + 1;
} else {
attributes[i] = nullptr;
}
if (i < num - 1) skipComma();
}
s = before;
return attributes;
};
//
auto makeBinary = [&](BinaryOp op, WasmType type) {
Name assign = getAssign();
skipComma();
auto curr = allocator->alloc<Binary>();
curr->op = op;
auto inputs = getInputs(2);
curr->left = inputs[0];
curr->right = inputs[1];
curr->finalize();
assert(curr->type == type);
setOutput(curr, assign);
};
auto makeUnary = [&](UnaryOp op, WasmType type) {
Name assign = getAssign();
skipComma();
auto curr = allocator->alloc<Unary>();
curr->op = op;
curr->value = getInput();
curr->type = type;
curr->finalize();
setOutput(curr, assign);
};
auto makeHost = [&](HostOp op) {
Name assign = getAssign();
auto curr = allocator->alloc<Host>();
curr->op = op;
curr->finalize();
setOutput(curr, assign);
};
auto makeHost1 = [&](HostOp op) {
Name assign = getAssign();
auto curr = allocator->alloc<Host>();
curr->op = op;
curr->operands.push_back(getInput());
curr->finalize();
setOutput(curr, assign);
};
auto useRelocationExpression = [&](Expression *expr, Expression *reloc) {
if (!reloc) {
return expr;
}
// Optimization: if the given expr is (i32.const 0), ignore it
if (expr->_id == Expression::ConstId &&
((Const*)expr)->value.getInteger() == 0) {
return reloc;
}
// Otherwise, need to add relocation expr to given expr
auto add = allocator->alloc<Binary>();
add->type = i32;
add->op = AddInt32;
add->left = expr;
add->right = reloc;
return (Expression*)add;
};
auto makeLoad = [&](WasmType type) {
skipComma();
auto curr = allocator->alloc<Load>();
curr->type = type;
int32_t bytes = getInt() / CHAR_BIT;
curr->bytes = bytes > 0 ? bytes : getWasmTypeSize(type);
curr->signed_ = match("_s");
match("_u");
Name assign = getAssign();
auto relocation = getRelocatableExpression(&curr->offset.addr);
mustMatch("(");
auto attributes = getAttributes(1);
curr->ptr = useRelocationExpression(getInput(), relocation);
curr->align = curr->bytes;
if (attributes[0]) {
assert(strncmp(attributes[0], "p2align=", 8) == 0);
curr->align = 1U << getInt(attributes[0] + 8);
}
setOutput(curr, assign);
};
auto makeStore = [&](WasmType type) {
auto curr = allocator->alloc<Store>();
curr->valueType = type;
s += strlen("store");
if(!isspace(*s)) {
curr->bytes = getInt() / CHAR_BIT;
} else {
curr->bytes = getWasmTypeSize(type);
}
skipWhitespace();
auto relocation = getRelocatableExpression(&curr->offset.addr);
mustMatch("(");
auto attributes = getAttributes(2);
auto inputs = getInputs(2);
curr->ptr = useRelocationExpression(inputs[0], relocation);
curr->align = curr->bytes;
if (attributes[0]) {
assert(strncmp(attributes[0], "p2align=", 8) == 0);
curr->align = 1U << getInt(attributes[0] + 8);
}
curr->value = inputs[1];
curr->finalize();
addToBlock(curr);
};
auto makeSelect = [&](WasmType type) {
Name assign = getAssign();
skipComma();
auto curr = allocator->alloc<Select>();
auto inputs = getInputs(3);
curr->ifTrue = inputs[0];
curr->ifFalse = inputs[1];
curr->condition = inputs[2];
assert(curr->condition->type == i32);
curr->type = type;
setOutput(curr, assign);
};
auto makeCall = [&](WasmType type) {
if (match("_indirect")) {
// indirect call
Name assign = getAssign();
int num = getNumInputs();
auto inputs = getInputs(num);
auto* target = *(inputs.end() - 1);
std::vector<Expression*> operands(inputs.begin(), inputs.end() - 1);
auto* funcType = ensureFunctionType(getSig(type, operands), wasm);
assert(type == funcType->result);
auto* indirect = builder.makeCallIndirect(funcType, target, std::move(operands));
setOutput(indirect, assign);
} else {
// non-indirect call
Name assign = getAssign();
Name rawTarget = cleanFunction(getCommaSeparated());
Call* curr = allocator->alloc<Call>();
curr->type = type;
skipWhitespace();
if (*s == ',') {
skipComma();
int num = getNumInputs();
auto inputs = getInputs(num);
for (int i = 0; i < num; i++) {
curr->operands.push_back(inputs[i]);