-
Notifications
You must be signed in to change notification settings - Fork 720
/
wasm2js.h
3134 lines (2932 loc) · 111 KB
/
wasm2js.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.
*/
//
// WebAssembly-to-JS code translator. Converts wasm functions into
// valid JavaScript (with a somewhat asm.js-ish flavor).
//
#ifndef wasm_wasm2js_h
#define wasm_wasm2js_h
#include <cmath>
#include <numeric>
#include "abi/js.h"
#include "asm_v_wasm.h"
#include "asmjs/asmangle.h"
#include "asmjs/shared-constants.h"
#include "emscripten-optimizer/optimizer.h"
#include "ir/branch-utils.h"
#include "ir/effects.h"
#include "ir/element-utils.h"
#include "ir/find_all.h"
#include "ir/import-utils.h"
#include "ir/load-utils.h"
#include "ir/module-utils.h"
#include "ir/names.h"
#include "ir/table-utils.h"
#include "ir/utils.h"
#include "mixed_arena.h"
#include "passes/passes.h"
#include "support/base64.h"
#include "support/file.h"
#include "wasm-builder.h"
#include "wasm-io.h"
#include "wasm-validator.h"
#include "wasm.h"
namespace wasm {
using namespace cashew;
static IString importObject("imports");
// Appends extra to block, flattening out if extra is a block as well
void flattenAppend(Ref ast, Ref extra) {
int index;
if (ast[0] == BLOCK || ast[0] == TOPLEVEL) {
index = 1;
} else if (ast[0] == DEFUN) {
index = 3;
} else {
abort();
}
if (extra->isArray() && extra[0] == BLOCK) {
for (size_t i = 0; i < extra[1]->size(); i++) {
ast[index]->push_back(extra[1][i]);
}
} else {
ast[index]->push_back(extra);
}
}
// Appends extra to a chain of sequence elements
void sequenceAppend(Ref& ast, Ref extra) {
if (!ast.get()) {
ast = extra;
return;
}
ast = ValueBuilder::makeSeq(ast, extra);
}
bool isTableExported(Module& wasm) {
if (wasm.tables.empty() || wasm.tables[0]->imported()) {
return false;
}
for (auto& ex : wasm.exports) {
if (ex->kind == ExternalKind::Table && ex->value == wasm.tables[0]->name) {
return true;
}
}
return false;
}
bool hasActiveSegments(Module& wasm) {
for (Index i = 0; i < wasm.dataSegments.size(); i++) {
if (!wasm.dataSegments[i]->isPassive) {
return true;
}
}
return false;
}
bool needsBufferView(Module& wasm) {
if (wasm.memories.empty()) {
return false;
}
// If there are any active segments, initActiveSegments needs access
// to bufferView.
if (hasActiveSegments(wasm)) {
return true;
}
// The special support functions are emitted as part of the JS glue, if we
// need them.
bool need = false;
ModuleUtils::iterImportedFunctions(wasm, [&](Function* import) {
if (ABI::wasm2js::isHelper(import->base)) {
need = true;
}
});
return need;
}
IString stringToIString(std::string str) { return IString(str.c_str(), false); }
// Used when taking a wasm name and generating a JS identifier. Each scope here
// is used to ensure that all names have a unique name but the same wasm name
// within a scope always resolves to the same symbol.
//
// Export: Export names
// Top: The main scope which contains functions and globals
// Local: Local variables in a function.
// Label: Label identifiers in a function
enum class NameScope {
Export,
Top,
Local,
Label,
Max,
};
//
// Wasm2JSBuilder - converts a WebAssembly module's functions into JS
//
// Wasm-to-JS is tricky because wasm doesn't distinguish
// statements and expressions, or in other words, things like `break` and `if`
// can show up in places where JS can't handle them, like inside an a loop's
// condition check. For that reason we use flat IR here.
// We do optimize it later, to allow some nesting, but we avoid
// non-JS-compatible nesting like block return values control flow in an if
// condition, etc.
//
class Wasm2JSBuilder {
public:
struct Flags {
// see wasm2js.cpp for details
bool debug = false;
bool pedantic = false;
bool allowAsserts = false;
bool emscripten = false;
bool deterministic = false;
std::string symbolsFile;
};
// Map data segment names to indices.
std::unordered_map<Name, Index> dataIndices;
Wasm2JSBuilder(Flags f, PassOptions options_) : flags(f), options(options_) {
// We don't try to model wasm's trapping precisely - if we did, each load
// and store would need to do a check. Given that, we can just ignore
// implicit traps like those when optimizing. (When not optimizing, it's
// nice to see codegen that matches wasm more precisely.)
// It is also important to prevent the optimizer from adding new things that
// require additional lowering, as we could hit a cycle.
if (options.optimizeLevel > 0) {
options.ignoreImplicitTraps = true;
options.targetJS = true;
}
}
Ref processWasm(Module* wasm, Name funcName = ASM_FUNC);
Ref processFunction(Module* wasm, Function* func, bool standalone = false);
Ref processStandaloneFunction(Module* wasm, Function* func) {
return processFunction(wasm, func, true);
}
// The second pass on an expression: process it fully, generating
// JS
Ref processExpression(Expression* curr,
Module* m,
Function* func = nullptr,
bool standalone = false);
Index getDataIndex(Name segment) {
auto it = dataIndices.find(segment);
assert(it != dataIndices.end());
return it->second;
}
// Get a temp var.
IString getTemp(Type type, Function* func) {
IString ret;
// TODO: handle tuples
assert(!type.isTuple() && "Unexpected tuple type");
if (frees[type].size() > 0) {
ret = frees[type].back();
frees[type].pop_back();
} else {
auto index = temps[type]++;
ret = IString((std::string("wasm2js_") + type.toString() + "$" +
std::to_string(index))
.c_str(),
false);
ret = fromName(ret, NameScope::Local);
}
if (func->localIndices.find(ret) == func->localIndices.end()) {
Builder::addVar(func, ret, type);
}
return ret;
}
// Free a temp var.
void freeTemp(Type type, IString temp) {
// TODO: handle tuples
assert(!type.isTuple() && "Unexpected tuple type");
frees[type].push_back(temp);
}
// Generates a mangled name from `name` within the specified scope.
//
// The goal of this function is to ensure that all identifiers in JS ar
// unique. Otherwise there can be clashes with locals and functions and cause
// unwanted name shadowing.
//
// The returned string from this function is constant for a particular `name`
// within a `scope`. Or in other words, the same `name` and `scope` pair will
// always return the same result. If `scope` changes, however, the return
// value may differ even if the same `name` is passed in.
IString fromName(Name name, NameScope scope) {
// TODO: checking names do not collide after mangling
// First up check our cached of mangled names to avoid doing extra work
// below
auto& map = wasmNameToMangledName[(int)scope];
auto it = map.find(name.str.data());
if (it != map.end()) {
return it->second;
}
// The mangled names in our scope.
auto& scopeMangledNames = mangledNames[(int)scope];
// In some cases (see below) we need to also check the Top scope.
auto& topMangledNames = mangledNames[int(NameScope::Top)];
// This is the first time we've seen the `name` and `scope` pair. Generate a
// globally unique name based on `name` and then register that in our cache
// and return it.
//
// Identifiers here generated are of the form `${name}_${n}` where `_${n}`
// is omitted if `n==0` and otherwise `n` is just looped over to find the
// next unused identifier.
IString ret;
for (int i = 0;; i++) {
std::ostringstream out;
out << name;
if (i > 0) {
out << "_" << i;
}
auto mangled = asmangle(out.str());
ret = stringToIString(mangled);
if (scopeMangledNames.count(ret)) {
// When export names collide things may be confusing, as this is
// observable externally by the person using the JS. Report a warning.
if (scope == NameScope::Export) {
std::cerr << "wasm2js: warning: export names colliding: " << mangled
<< '\n';
}
continue;
}
// The Local scope is special: a Local name must not collide with a Top
// name, as they are in a single namespace in JS and can conflict:
//
// function foo(bar) {
// var bar = 0;
// }
// function bar() { ..
if (scope == NameScope::Local && topMangledNames.count(ret)) {
continue;
}
// We found a good name, use it.
scopeMangledNames.insert(ret);
map[name.str.data()] = ret;
return ret;
}
}
private:
Flags flags;
PassOptions options;
// How many temp vars we need for each type (type => num).
std::unordered_map<Type, Index> temps;
// Which temp vars are currently free to use for each type (type => freelist).
std::unordered_map<Type, std::vector<IString>> frees;
// Mangled names cache by interned names.
// Utilizes the usually reused underlying cstring's pointer as the key.
std::unordered_map<const void*, IString>
wasmNameToMangledName[(int)NameScope::Max];
// Set of all mangled names in each scope.
std::unordered_set<IString> mangledNames[(int)NameScope::Max];
std::unordered_set<IString> seenModuleImports;
// If a function is callable from outside, we'll need to cast the inputs
// and our return value. Otherwise, internally, casts are only needed
// on operations.
std::unordered_set<Name> functionsCallableFromOutside;
void ensureModuleVar(Ref ast, const Importable& imp);
Ref getImportName(const Importable& imp);
void addBasics(Ref ast, Module* wasm);
void addFunctionImport(Ref ast, Function* import);
void addGlobalImport(Ref ast, Global* import);
void addTable(Ref ast, Module* wasm);
void addStart(Ref ast, Module* wasm);
void addExports(Ref ast, Module* wasm);
void addGlobal(Ref ast, Global* global, Module* module);
void addMemoryFuncs(Ref ast, Module* wasm);
void addMemoryGrowFunc(Ref ast, Module* wasm);
Wasm2JSBuilder() = delete;
Wasm2JSBuilder(const Wasm2JSBuilder&) = delete;
Wasm2JSBuilder& operator=(const Wasm2JSBuilder&) = delete;
};
Ref Wasm2JSBuilder::processWasm(Module* wasm, Name funcName) {
// Scan the wasm for important things.
for (auto& exp : wasm->exports) {
if (exp->kind == ExternalKind::Function) {
functionsCallableFromOutside.insert(exp->value);
}
}
ElementUtils::iterAllElementFunctionNames(
wasm, [&](Name name) { functionsCallableFromOutside.insert(name); });
// Collect passive data segment indices.
for (Index i = 0; i < wasm->dataSegments.size(); ++i) {
dataIndices[wasm->dataSegments[i]->name] = i;
}
// Ensure the scratch memory helpers.
// If later on they aren't needed, we'll clean them up.
ABI::wasm2js::ensureHelpers(wasm);
// Process the code, and optimize if relevant.
// First, do the lowering to a JS-friendly subset.
{
PassRunner runner(wasm, options);
runner.add(std::make_unique<AutoDrop>());
// TODO: only legalize if necessary - emscripten would already do so, and
// likely other toolchains. but spec test suite needs that.
runner.add("legalize-js-interface");
// Before lowering non-JS operations we can optimize some instructions which
// may simplify next passes
if (options.optimizeLevel > 0) {
runner.add("optimize-for-js");
}
// First up remove as many non-JS operations we can, including things like
// 64-bit integer multiplication/division, `f32.nearest` instructions, etc.
// This may inject intrinsics which use i64 so it needs to be run before the
// i64-to-i32 lowering pass.
runner.add("remove-non-js-ops");
// Currently the i64-to-32 lowering pass requires that `flatten` be run
// before it to produce correct code. For some more details about this see
// #1480
runner.add("flatten");
runner.add("i64-to-i32-lowering");
runner.add("alignment-lowering");
// Next, optimize that as best we can. This should not generate
// non-JS-friendly things.
if (options.optimizeLevel > 0) {
// It is especially import to propagate constants after the lowering.
// However, this can be a slow operation, especially after flattening;
// some local simplification helps.
if (options.optimizeLevel >= 3 || options.shrinkLevel >= 1) {
runner.add("simplify-locals-nonesting");
runner.add("precompute-propagate");
// Avoiding reinterpretation is helped by propagation. We also run
// it later down as default optimizations help as well.
runner.add("avoid-reinterprets");
}
runner.addDefaultOptimizationPasses();
runner.add("avoid-reinterprets");
}
// Finally, get the code into the flat form we need for wasm2js itself, and
// optimize that a little in a way that keeps that property.
runner.add("flatten");
// Regardless of optimization level, run some simple optimizations to undo
// some of the effects of flattening.
runner.add("simplify-locals-notee-nostructure");
// Some operations can be very slow if we didn't run full optimizations
// earlier, so don't run them automatically.
if (options.optimizeLevel > 0) {
runner.add("remove-unused-names");
runner.add("merge-blocks");
runner.add("reorder-locals");
runner.add("coalesce-locals");
}
runner.add("reorder-locals");
runner.add("vacuum");
runner.add("remove-unused-module-elements");
// DCE at the end to make sure all IR nodes have valid types for conversion
// to JS, and not unreachable.
runner.add("dce");
runner.setDebug(flags.debug);
runner.run();
}
if (flags.symbolsFile.size() > 0) {
Output out(flags.symbolsFile, wasm::Flags::Text);
Index i = 0;
for (auto& func : wasm->functions) {
out.getStream() << i++ << ':' << func->name.str << '\n';
}
}
#ifndef NDEBUG
if (!WasmValidator().validate(*wasm)) {
std::cout << *wasm << '\n';
Fatal() << "error in validating wasm2js output";
}
#endif
Ref ret = ValueBuilder::makeToplevel();
Ref asmFunc = ValueBuilder::makeFunction(funcName);
ret[1]->push_back(asmFunc);
ValueBuilder::appendArgumentToFunction(asmFunc, importObject);
// add memory import
if (!wasm->memories.empty()) {
if (wasm->memories[0]->imported()) {
ensureModuleVar(asmFunc[3], *wasm->memories[0]);
// find memory and buffer in imports
Ref theVar = ValueBuilder::makeVar();
asmFunc[3]->push_back(theVar);
ValueBuilder::appendToVar(
theVar, "memory", getImportName(*wasm->memories[0]));
// Assign `buffer = memory.buffer`
Ref buf = ValueBuilder::makeVar();
asmFunc[3]->push_back(buf);
ValueBuilder::appendToVar(
buf,
BUFFER,
ValueBuilder::makeDot(ValueBuilder::makeName("memory"),
ValueBuilder::makeName("buffer")));
// If memory is growable, override the imported memory's grow method to
// ensure so that when grow is called from the output it works as expected
if (wasm->memories[0]->max > wasm->memories[0]->initial) {
asmFunc[3]->push_back(
ValueBuilder::makeStatement(ValueBuilder::makeBinary(
ValueBuilder::makeDot(ValueBuilder::makeName("memory"),
ValueBuilder::makeName("grow")),
SET,
ValueBuilder::makeName(WASM_MEMORY_GROW))));
}
} else {
Ref theVar = ValueBuilder::makeVar();
asmFunc[3]->push_back(theVar);
ValueBuilder::appendToVar(
theVar,
BUFFER,
ValueBuilder::makeNew(ValueBuilder::makeCall(
ValueBuilder::makeName("ArrayBuffer"),
ValueBuilder::makeInt(Address::address32_t(
wasm->memories[0]->initial.addr * Memory::kPageSize)))));
}
}
// add imported tables
ModuleUtils::iterImportedTables(*wasm, [&](Table* table) {
ensureModuleVar(asmFunc[3], *table);
Ref theVar = ValueBuilder::makeVar();
asmFunc[3]->push_back(theVar);
ValueBuilder::appendToVar(theVar, FUNCTION_TABLE, getImportName(*table));
});
// create heaps, etc
addBasics(asmFunc[3], wasm);
ModuleUtils::iterImportedFunctions(
*wasm, [&](Function* import) { addFunctionImport(asmFunc[3], import); });
ModuleUtils::iterImportedGlobals(
*wasm, [&](Global* import) { addGlobalImport(asmFunc[3], import); });
// Note the names of functions. We need to do this here as when generating
// mangled local names we need them not to conflict with these (see fromName)
// so we can't wait until we parse each function to note its name.
for (auto& f : wasm->functions) {
fromName(f->name, NameScope::Top);
}
// globals
bool generateFetchHighBits = false;
ModuleUtils::iterDefinedGlobals(*wasm, [&](Global* global) {
addGlobal(asmFunc[3], global, wasm);
if (flags.allowAsserts && global->name == INT64_TO_32_HIGH_BITS) {
generateFetchHighBits = true;
}
});
if (flags.emscripten) {
asmFunc[3]->push_back(
ValueBuilder::makeName("// EMSCRIPTEN_START_FUNCS\n"));
}
// functions
ModuleUtils::iterDefinedFunctions(*wasm, [&](Function* func) {
asmFunc[3]->push_back(processFunction(wasm, func));
});
if (generateFetchHighBits) {
Builder builder(*wasm);
asmFunc[3]->push_back(
processFunction(wasm,
wasm->addFunction(builder.makeFunction(
WASM_FETCH_HIGH_BITS,
Signature(Type::none, Type::i32),
{},
builder.makeReturn(builder.makeGlobalGet(
INT64_TO_32_HIGH_BITS, Type::i32))))));
auto e = new Export();
e->name = WASM_FETCH_HIGH_BITS;
e->value = WASM_FETCH_HIGH_BITS;
e->kind = ExternalKind::Function;
wasm->addExport(e);
}
if (flags.emscripten) {
asmFunc[3]->push_back(ValueBuilder::makeName("// EMSCRIPTEN_END_FUNCS\n"));
}
if (needsBufferView(*wasm)) {
asmFunc[3]->push_back(
ValueBuilder::makeBinary(ValueBuilder::makeName("bufferView"),
SET,
ValueBuilder::makeName(HEAPU8)));
}
if (hasActiveSegments(*wasm)) {
asmFunc[3]->push_back(
ValueBuilder::makeCall(ValueBuilder::makeName("initActiveSegments"),
ValueBuilder::makeName(importObject)));
}
addTable(asmFunc[3], wasm);
addStart(asmFunc[3], wasm);
addExports(asmFunc[3], wasm);
return ret;
}
void Wasm2JSBuilder::addBasics(Ref ast, Module* wasm) {
if (!wasm->memories.empty()) {
// heaps, var HEAP8 = new global.Int8Array(buffer); etc
auto addHeap = [&](IString name, IString view) {
Ref theVar = ValueBuilder::makeVar();
ast->push_back(theVar);
ValueBuilder::appendToVar(theVar,
name,
ValueBuilder::makeNew(ValueBuilder::makeCall(
view, ValueBuilder::makeName(BUFFER))));
};
addHeap(HEAP8, INT8ARRAY);
addHeap(HEAP16, INT16ARRAY);
addHeap(HEAP32, INT32ARRAY);
addHeap(HEAPU8, UINT8ARRAY);
addHeap(HEAPU16, UINT16ARRAY);
addHeap(HEAPU32, UINT32ARRAY);
addHeap(HEAPF32, FLOAT32ARRAY);
addHeap(HEAPF64, FLOAT64ARRAY);
}
// core asm.js imports
auto addMath = [&](IString name, IString base) {
Ref theVar = ValueBuilder::makeVar();
ast->push_back(theVar);
ValueBuilder::appendToVar(
theVar, name, ValueBuilder::makeDot(ValueBuilder::makeName(MATH), base));
};
addMath(MATH_IMUL, IMUL);
addMath(MATH_FROUND, FROUND);
addMath(MATH_ABS, ABS);
addMath(MATH_CLZ32, CLZ32);
addMath(MATH_MIN, MIN);
addMath(MATH_MAX, MAX);
addMath(MATH_FLOOR, FLOOR);
addMath(MATH_CEIL, CEIL);
addMath(MATH_TRUNC, TRUNC);
addMath(MATH_SQRT, SQRT);
}
static bool needsQuoting(Name name) {
auto mangled = asmangle(name.toString());
return mangled != name.str;
}
void Wasm2JSBuilder::ensureModuleVar(Ref ast, const Importable& imp) {
if (seenModuleImports.count(imp.module) > 0) {
return;
}
Ref theVar = ValueBuilder::makeVar();
ast->push_back(theVar);
Ref rhs;
if (needsQuoting(imp.module)) {
rhs = ValueBuilder::makeSub(ValueBuilder::makeName(importObject),
ValueBuilder::makeString(imp.module));
} else {
rhs = ValueBuilder::makeDot(ValueBuilder::makeName(importObject),
ValueBuilder::makeName(imp.module));
}
ValueBuilder::appendToVar(theVar, fromName(imp.module, NameScope::Top), rhs);
seenModuleImports.insert(imp.module);
}
Ref Wasm2JSBuilder::getImportName(const Importable& imp) {
if (needsQuoting(imp.base)) {
return ValueBuilder::makeSub(
ValueBuilder::makeName(fromName(imp.module, NameScope::Top)),
ValueBuilder::makeString(imp.base));
} else {
return ValueBuilder::makeDot(
ValueBuilder::makeName(fromName(imp.module, NameScope::Top)),
ValueBuilder::makeName(imp.base));
}
}
void Wasm2JSBuilder::addFunctionImport(Ref ast, Function* import) {
// The scratch memory helpers are emitted in the glue, see code and comments
// below.
if (ABI::wasm2js::isHelper(import->base)) {
return;
}
ensureModuleVar(ast, *import);
Ref theVar = ValueBuilder::makeVar();
ast->push_back(theVar);
ValueBuilder::appendToVar(
theVar, fromName(import->name, NameScope::Top), getImportName(*import));
}
void Wasm2JSBuilder::addGlobalImport(Ref ast, Global* import) {
ensureModuleVar(ast, *import);
Ref theVar = ValueBuilder::makeVar();
ast->push_back(theVar);
Ref value = getImportName(*import);
if (import->type == Type::i32) {
value = makeJsCoercion(value, JS_INT);
}
ValueBuilder::appendToVar(
theVar, fromName(import->name, NameScope::Top), value);
}
void Wasm2JSBuilder::addTable(Ref ast, Module* wasm) {
if (wasm->tables.size() == 0) {
return;
}
bool perElementInit = false;
// Emit a simple flat table as a JS array literal. Otherwise,
// emit assignments separately for each index.
Ref theArray = ValueBuilder::makeArray();
for (auto& table : wasm->tables) {
if (!table->type.isFunction()) {
Fatal() << "wasm2js doesn't support non-function tables\n";
}
if (!table->imported()) {
TableUtils::FlatTable flat(*wasm, *table);
if (flat.valid) {
for (auto& name : flat.names) {
if (name.is()) {
name = fromName(name, NameScope::Top);
} else {
name = NULL_;
}
ValueBuilder::appendToArray(theArray, ValueBuilder::makeName(name));
}
} else {
perElementInit = true;
Ref initial =
ValueBuilder::makeInt(Address::address32_t(table->initial.addr));
theArray = ValueBuilder::makeNew(
ValueBuilder::makeCall(IString("Array"), initial));
}
} else {
perElementInit = true;
}
if (isTableExported(*wasm)) {
// If the table is exported use a fake WebAssembly.Table object
// We don't handle the case where a table is both imported and exported.
if (table->imported()) {
Fatal() << "wasm2js doesn't support a table that is both imported and "
"exported\n";
}
Ref theVar = ValueBuilder::makeVar();
ast->push_back(theVar);
Ref table = ValueBuilder::makeCall(IString("Table"), theArray);
ValueBuilder::appendToVar(theVar, FUNCTION_TABLE, table);
} else if (!table->imported()) {
// Otherwise if the table is internal (neither imported not exported).
// Just use a plain array in this case, avoiding the Table.
Ref theVar = ValueBuilder::makeVar();
ast->push_back(theVar);
ValueBuilder::appendToVar(theVar, FUNCTION_TABLE, theArray);
}
if (perElementInit) {
// TODO: optimize for size
ModuleUtils::iterTableSegments(
*wasm, table->name, [&](ElementSegment* segment) {
auto offset = segment->offset;
ElementUtils::iterElementSegmentFunctionNames(
segment, [&](Name entry, Index i) {
Ref index;
if (auto* c = offset->dynCast<Const>()) {
index = ValueBuilder::makeInt(c->value.geti32() + i);
} else if (auto* get = offset->dynCast<GlobalGet>()) {
index = ValueBuilder::makeBinary(
ValueBuilder::makeName(
stringToIString(asmangle(get->name.toString()))),
PLUS,
ValueBuilder::makeNum(i));
} else {
WASM_UNREACHABLE("unexpected expr type");
}
ast->push_back(
ValueBuilder::makeStatement(ValueBuilder::makeBinary(
ValueBuilder::makeSub(ValueBuilder::makeName(FUNCTION_TABLE),
index),
SET,
ValueBuilder::makeName(fromName(entry, NameScope::Top)))));
});
});
}
}
}
void Wasm2JSBuilder::addStart(Ref ast, Module* wasm) {
if (wasm->start.is()) {
ast->push_back(
ValueBuilder::makeCall(fromName(wasm->start, NameScope::Top)));
}
}
void Wasm2JSBuilder::addExports(Ref ast, Module* wasm) {
Ref exports = ValueBuilder::makeObject();
for (auto& export_ : wasm->exports) {
switch (export_->kind) {
case ExternalKind::Function: {
ValueBuilder::appendToObjectWithQuotes(
exports,
fromName(export_->name, NameScope::Export),
ValueBuilder::makeName(fromName(export_->value, NameScope::Top)));
break;
}
case ExternalKind::Memory: {
Ref descs = ValueBuilder::makeObject();
Ref growDesc = ValueBuilder::makeObject();
ValueBuilder::appendToObjectWithQuotes(
descs, IString("grow"), growDesc);
if (wasm->memories[0]->max > wasm->memories[0]->initial) {
ValueBuilder::appendToObjectWithQuotes(
growDesc,
IString("value"),
ValueBuilder::makeName(WASM_MEMORY_GROW));
}
Ref bufferDesc = ValueBuilder::makeObject();
Ref bufferGetter = ValueBuilder::makeFunction(IString(""));
bufferGetter[3]->push_back(
ValueBuilder::makeReturn(ValueBuilder::makeName(BUFFER)));
ValueBuilder::appendToObjectWithQuotes(
bufferDesc, IString("get"), bufferGetter);
ValueBuilder::appendToObjectWithQuotes(
descs, IString("buffer"), bufferDesc);
Ref memory = ValueBuilder::makeCall(
ValueBuilder::makeDot(ValueBuilder::makeName(IString("Object")),
IString("create")),
ValueBuilder::makeDot(ValueBuilder::makeName(IString("Object")),
IString("prototype")));
ValueBuilder::appendToCall(memory, descs);
ValueBuilder::appendToObjectWithQuotes(
exports, fromName(export_->name, NameScope::Export), memory);
break;
}
case ExternalKind::Table: {
ValueBuilder::appendToObjectWithQuotes(
exports,
fromName(export_->name, NameScope::Export),
ValueBuilder::makeName(FUNCTION_TABLE));
break;
}
case ExternalKind::Global: {
Ref object = ValueBuilder::makeObject();
IString identName = fromName(export_->value, NameScope::Top);
// getter
{
Ref block = ValueBuilder::makeBlock();
block[1]->push_back(
ValueBuilder::makeReturn(ValueBuilder::makeName(identName)));
ValueBuilder::appendToObjectAsGetter(object, IString("value"), block);
}
// setter
{
std::ostringstream buffer;
buffer << '_' << identName;
auto setterParam = stringToIString(buffer.str());
auto block = ValueBuilder::makeBlock();
block[1]->push_back(
ValueBuilder::makeBinary(ValueBuilder::makeName(identName),
SET,
ValueBuilder::makeName(setterParam)));
ValueBuilder::appendToObjectAsSetter(
object, IString("value"), setterParam, block);
}
ValueBuilder::appendToObjectWithQuotes(
exports, fromName(export_->name, NameScope::Export), object);
break;
}
case ExternalKind::Tag:
case ExternalKind::Invalid:
Fatal() << "unsupported export type: " << export_->name << "\n";
}
}
if (!wasm->memories.empty()) {
addMemoryFuncs(ast, wasm);
}
ast->push_back(
ValueBuilder::makeStatement(ValueBuilder::makeReturn(exports)));
}
void Wasm2JSBuilder::addGlobal(Ref ast, Global* global, Module* module) {
Ref theVar = ValueBuilder::makeVar();
ast->push_back(theVar);
Ref init = processExpression(global->init, module);
ValueBuilder::appendToVar(
theVar, fromName(global->name, NameScope::Top), init);
}
Ref Wasm2JSBuilder::processFunction(Module* m,
Function* func,
bool standaloneFunction) {
if (standaloneFunction) {
// We are only printing a function, not a whole module. Prepare it for
// translation now (if there were a module, we'd have done this for all
// functions in parallel, earlier).
PassRunner runner(m);
// We only run a subset of all passes here. TODO: create a full valid module
// for each assertion body.
runner.add("flatten");
runner.add("simplify-locals-notee-nostructure");
runner.add("reorder-locals");
runner.add("remove-unused-names");
runner.add("vacuum");
runner.runOnFunction(func);
}
// We process multiple functions from a single Wasm2JSBuilder instance, so
// clean up the function-specific local state before each function.
frees.clear();
temps.clear();
// We will be symbolically referring to all variables in the function, so make
// sure that everything has a name and it's unique.
Names::ensureNames(func);
Ref ret = ValueBuilder::makeFunction(fromName(func->name, NameScope::Top));
// arguments
bool needCoercions = options.optimizeLevel == 0 || standaloneFunction ||
functionsCallableFromOutside.count(func->name);
for (Index i = 0; i < func->getNumParams(); i++) {
IString name = fromName(func->getLocalNameOrGeneric(i), NameScope::Local);
ValueBuilder::appendArgumentToFunction(ret, name);
if (needCoercions) {
auto jsType = wasmToJsType(func->getLocalType(i));
if (needsJsCoercion(jsType)) {
ret[3]->push_back(ValueBuilder::makeStatement(ValueBuilder::makeBinary(
ValueBuilder::makeName(name),
SET,
makeJsCoercion(ValueBuilder::makeName(name), jsType))));
}
}
}
Ref theVar = ValueBuilder::makeVar();
size_t theVarIndex = ret[3]->size();
ret[3]->push_back(theVar);
// body
flattenAppend(ret,
processExpression(func->body, m, func, standaloneFunction));
// vars, including new temp vars
for (Index i = func->getVarIndexBase(); i < func->getNumLocals(); i++) {
ValueBuilder::appendToVar(
theVar,
fromName(func->getLocalNameOrGeneric(i), NameScope::Local),
makeJsCoercedZero(wasmToJsType(func->getLocalType(i))));
}
if (theVar[1]->size() == 0) {
ret[3]->splice(theVarIndex, 1);
}
return ret;
}
Ref Wasm2JSBuilder::processExpression(Expression* curr,
Module* m,
Function* func,
bool standaloneFunction) {
// Switches are tricky to handle - in wasm they often come with
// massively-nested "towers" of blocks, which if naively translated
// to JS may exceed parse recursion limits of VMs. Therefore even when
// not optimizing we work hard to emit minimal and minimally-nested
// switches.
// We do so by pre-scanning for br_tables and noting which of their
// targets can be hoisted up into them, e.g.
//
// (block $a
// (block $b
// (block $c
// (block $d
// (block $e
// (br_table $a $b $c $d $e (..))
// )
// ;; code X (for block $e)
// ;; implicit fallthrough - can be done in the switch too
// )
// ;; code Y
// (br $c) ;; branch which is identical to a fallthrough
// )
// ;; code Z
// (br $a) ;; skip some blocks - can't do this in a switch!
// )
// ;; code W
// )
//
// Every branch we see is a potential hazard - all targets must not
// be optimized into the switch, since they must be reached normally,
// unless they happen to be right after us, in which case it's just
// a fallthrough anyhow.
struct SwitchProcessor : public ExpressionStackWalker<SwitchProcessor> {
// A list of expressions we don't need to emit, as we are handling them
// in another way.
std::set<Expression*> unneededExpressions;
struct SwitchCase {
Name target;
std::vector<Expression*> code;
SwitchCase(Name target) : target(target) {}
};
// The switch cases we found that we can hoist up.
std::map<Switch*, std::vector<SwitchCase>> hoistedSwitchCases;
void visitSwitch(Switch* brTable) {
Index i = expressionStack.size() - 1;
assert(expressionStack[i] == brTable);
// A set of names we must stop at, since we've seen branches to them.
std::set<Name> namesBranchedTo;
while (1) {
// Stop if we are at the top level.
if (i == 0) {
break;
}
i--;
auto* child = expressionStack[i + 1];
auto* curr = expressionStack[i];
// Stop if the current node is not a block with the child in the
// first position, i.e., the classic switch pattern.
auto* block = curr->dynCast<Block>();
if (!block || block->list[0] != child) {
break;
}
// Ignore the case of a name-less block for simplicity (merge-blocks
// would have removed it).
if (!block->name.is()) {
break;
}
// If we have already seen this block, stop here.
if (unneededExpressions.count(block)) {
// XXX FIXME we should probably abort the entire optimization
break;