-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
Copy pathacorn-optimizer.mjs
executable file
·2117 lines (1996 loc) · 64.4 KB
/
acorn-optimizer.mjs
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
#!/usr/bin/env node
import * as acorn from 'acorn';
import * as terser from '../third_party/terser/terser.js';
import * as fs from 'node:fs';
// Utilities
function print(x) {
process.stdout.write(x + '\n');
}
function read(x) {
return fs.readFileSync(x).toString();
}
function assert(condition, text) {
if (!condition) {
throw new Error(text);
}
}
function assertAt(condition, node, message = '') {
if (!condition) {
const loc = acorn.getLineInfo(input, node.start);
throw new Error(
`${infile}:${loc.line}: ${message} (use EMCC_DEBUG_SAVE=1 to preserve temporary inputs)`,
);
}
}
// Visits and walks
// (We don't use acorn-walk because it ignores x in 'x = y'.)
function visitChildren(node, c) {
// emptyOut() and temporary ignoring may mark nodes as empty,
// while they have properties with children we should ignore.
if (node.type === 'EmptyStatement') {
return;
}
function maybeChild(child) {
if (child && typeof child === 'object' && typeof child.type === 'string') {
c(child);
return true;
}
return false;
}
for (const child of Object.values(node)) {
// Check for a child.
if (!maybeChild(child)) {
// Check for an array of children.
if (Array.isArray(child)) {
child.forEach(maybeChild);
}
}
}
}
// Simple post-order walk, calling properties on an object by node type,
// if the type exists.
function simpleWalk(node, cs) {
visitChildren(node, (child) => simpleWalk(child, cs));
if (node.type in cs) {
cs[node.type](node);
}
}
// Full post-order walk, calling a single function for all types. If |pre| is
// provided, it is called in pre-order (before children).
function fullWalk(node, c, pre) {
if (pre) {
pre(node);
}
visitChildren(node, (child) => fullWalk(child, c, pre));
c(node);
}
// Recursive post-order walk, calling properties on an object by node type,
// if the type exists, and if so leaving recursion to that function.
function recursiveWalk(node, cs) {
(function c(node) {
if (!(node.type in cs)) {
visitChildren(node, (child) => recursiveWalk(child, cs));
} else {
cs[node.type](node, c);
}
})(node);
}
// AST Utilities
function emptyOut(node) {
node.type = 'EmptyStatement';
}
function convertToNullStatement(node) {
node.type = 'ExpressionStatement';
node.expression = {
type: 'Literal',
value: null,
raw: 'null',
start: 0,
end: 0,
};
node.start = 0;
node.end = 0;
}
function isNull(node) {
return node.type === 'Literal' && node.raw === 'null';
}
function isUseStrict(node) {
return node.type === 'Literal' && node.value === 'use strict';
}
function setLiteralValue(item, value) {
item.value = value;
item.raw = "'" + value + "'";
}
function isLiteralString(node) {
return node.type === 'Literal' && (node.raw[0] === '"' || node.raw[0] === "'");
}
function dump(node, text) {
if (text) print(text);
print(JSON.stringify(node, null, ' '));
}
// Mark inner scopes temporarily as empty statements. Returns
// a special object that must be used to restore them.
function ignoreInnerScopes(node) {
const map = new WeakMap();
function ignore(node) {
map.set(node, node.type);
node.type = 'EmptyStatement';
}
simpleWalk(node, {
FunctionDeclaration(node) {
ignore(node);
},
FunctionExpression(node) {
ignore(node);
},
ArrowFunctionExpression(node) {
ignore(node);
},
// TODO: arrow etc.
});
return map;
}
// Mark inner scopes temporarily as empty statements.
function restoreInnerScopes(node, map) {
fullWalk(node, (node) => {
if (map.has(node)) {
node.type = map.get(node);
map.delete(node);
restoreInnerScopes(node, map);
}
});
}
// If we empty out a var from
// for (var i in x) {}
// for (var j = 0;;) {}
// then it will be invalid. We saved it on the side;
// restore it here.
function restoreForVars(node) {
let restored = 0;
function fix(init) {
if (init && init.type === 'EmptyStatement') {
assertAt(init.oldDeclarations, init);
init.type = 'VariableDeclaration';
init.declarations = init.oldDeclarations;
restored++;
}
}
simpleWalk(node, {
ForStatement(node) {
fix(node.init);
},
ForInStatement(node) {
fix(node.left);
},
ForOfStatement(node) {
fix(node.left);
},
});
return restored;
}
function hasSideEffects(node) {
// Conservative analysis.
const map = ignoreInnerScopes(node);
let has = false;
fullWalk(node, (node) => {
switch (node.type) {
// TODO: go through all the ESTree spec
case 'Literal':
case 'Identifier':
case 'UnaryExpression':
case 'BinaryExpression':
case 'LogicalExpression':
case 'ExpressionStatement':
case 'UpdateOperator':
case 'ConditionalExpression':
case 'FunctionDeclaration':
case 'FunctionExpression':
case 'ArrowFunctionExpression':
case 'VariableDeclaration':
case 'VariableDeclarator':
case 'ObjectExpression':
case 'Property':
case 'SpreadElement':
case 'BlockStatement':
case 'ArrayExpression':
case 'EmptyStatement': {
break; // safe
}
case 'MemberExpression': {
// safe if on Math (or other familiar objects, TODO)
if (node.object.type !== 'Identifier' || node.object.name !== 'Math') {
// console.error('because member on ' + node.object.name);
has = true;
}
break;
}
case 'NewExpression': {
// default to unsafe, but can be safe on some familiar objects
if (node.callee.type === 'Identifier') {
const name = node.callee.name;
if (
name === 'TextDecoder' ||
name === 'ArrayBuffer' ||
name === 'Int8Array' ||
name === 'Uint8Array' ||
name === 'Int16Array' ||
name === 'Uint16Array' ||
name === 'Int32Array' ||
name === 'Uint32Array' ||
name === 'Float32Array' ||
name === 'Float64Array'
) {
// no side effects, but the arguments might (we walk them in
// full walk as well)
break;
}
}
// not one of the safe cases
has = true;
break;
}
default: {
has = true;
}
}
});
restoreInnerScopes(node, map);
return has;
}
// Passes
// Removes obviously-unused code. Similar to closure compiler in its rules -
// export e.g. by Module['..'] = theThing; , or use it somewhere, otherwise
// it goes away.
//
// Note that this is somewhat conservative, since the ESTree AST does not
// have a simple separation between definitions and uses, e.g.
// Identifier is used both for the x in function foo(x) {
// and for y = x + 1 . That means we need to consider new ES6+ constructs
// as they appear (like ArrowFunctionExpression). Instead, we do a conservative
// analysis here.
function JSDCE(ast, aggressive) {
function iteration() {
let removed = 0;
const scopes = [{}]; // begin with empty toplevel scope
function ensureData(scope, name) {
if (Object.prototype.hasOwnProperty.call(scope, name)) return scope[name];
scope[name] = {
def: 0,
use: 0,
param: 0, // true for function params, which cannot be eliminated
};
return scope[name];
}
function cleanUp(ast, names) {
recursiveWalk(ast, {
VariableDeclaration(node, _c) {
const old = node.declarations;
let removedHere = 0;
node.declarations = node.declarations.filter((node) => {
assert(node.type === 'VariableDeclarator');
const id = node.id;
if (id.type === 'ObjectPattern' || id.type === 'ArrayPattern') {
// TODO: DCE into object patterns, that is, things like
// let { a, b } = ..
// let [ a, b ] = ..
return true;
}
assert(id.type === 'Identifier');
const curr = id.name;
const value = node.init;
const keep = !(curr in names) || (value && hasSideEffects(value));
if (!keep) removedHere = 1;
return keep;
});
removed += removedHere;
if (node.declarations.length === 0) {
emptyOut(node);
// If this is in a for, we may need to restore it.
node.oldDeclarations = old;
}
},
ExpressionStatement(node, _c) {
if (aggressive && !hasSideEffects(node)) {
if (!isNull(node.expression) && !isUseStrict(node.expression)) {
convertToNullStatement(node);
removed++;
}
}
},
FunctionDeclaration(node, _c) {
if (Object.prototype.hasOwnProperty.call(names, node.id.name)) {
removed++;
emptyOut(node);
return;
}
// do not recurse into other scopes
},
// do not recurse into other scopes
FunctionExpression() {},
ArrowFunctionExpression() {},
});
removed -= restoreForVars(ast);
}
function handleFunction(node, c, defun) {
// defun names matter - function names (the y in var x = function y() {..}) are just for stack traces.
if (defun) {
ensureData(scopes[scopes.length - 1], node.id.name).def = 1;
}
const scope = {};
scopes.push(scope);
node.params.forEach(function traverse(param) {
if (param.type === 'RestElement') {
param = param.argument;
}
if (param.type === 'AssignmentPattern') {
c(param.right);
param = param.left;
}
if (param.type === 'ArrayPattern') {
for (var elem of param.elements) {
if (elem) traverse(elem);
}
} else if (param.type === 'ObjectPattern') {
for (var prop of param.properties) {
traverse(prop.key);
}
} else {
assert(param.type === 'Identifier', param.type);
const name = param.name;
ensureData(scope, name).def = 1;
scope[name].param = 1;
}
});
c(node.body);
// we can ignore self-references, i.e., references to ourselves inside
// ourselves, for named defined (defun) functions
const ownName = defun ? node.id.name : '';
const names = {};
for (const name in scopes.pop()) {
if (name === ownName) continue;
const data = scope[name];
if (data.use && !data.def) {
// this is used from a higher scope, propagate the use down
ensureData(scopes[scopes.length - 1], name).use = 1;
continue;
}
if (data.def && !data.use && !data.param) {
// this is eliminateable!
names[name] = 0;
}
}
cleanUp(node.body, names);
}
recursiveWalk(ast, {
VariableDeclarator(node, c) {
function traverse(id) {
if (id.type === 'ObjectPattern') {
for (const prop of id.properties) {
traverse(prop.value);
}
} else if (id.type === 'ArrayPattern') {
for (const elem of id.elements) {
if (elem) traverse(elem);
}
} else {
assertAt(id.type === 'Identifier', id, `expected Identifier but found ${id.type}`);
const name = id.name;
ensureData(scopes[scopes.length - 1], name).def = 1;
}
}
traverse(node.id);
if (node.init) c(node.init);
},
ObjectExpression(node, c) {
// ignore the property identifiers
node.properties.forEach((node) => {
if (node.value) {
c(node.value);
} else if (node.argument) {
c(node.argument);
}
});
},
MemberExpression(node, c) {
c(node.object);
// Ignore a property identifier (a.X), but notice a[X] (computed
// is true) and a["X"] (it will be a Literal and not Identifier).
if (node.property.type !== 'Identifier' || node.computed) {
c(node.property);
}
},
FunctionDeclaration(node, c) {
handleFunction(node, c, true /* defun */);
},
FunctionExpression(node, c) {
handleFunction(node, c);
},
ArrowFunctionExpression(node, c) {
handleFunction(node, c);
},
Identifier(node, _c) {
const name = node.name;
ensureData(scopes[scopes.length - 1], name).use = 1;
},
});
// toplevel
const scope = scopes.pop();
assert(scopes.length === 0);
const names = {};
for (const [name, data] of Object.entries(scope)) {
if (data.def && !data.use) {
assert(!data.param); // can't be
// this is eliminateable!
names[name] = 0;
}
}
cleanUp(ast, names);
return removed;
}
while (iteration() && aggressive) {} // eslint-disable-line no-empty
}
// Aggressive JSDCE - multiple iterations
function AJSDCE(ast) {
JSDCE(ast, /* aggressive= */ true);
}
function isWasmImportsAssign(node) {
// var wasmImports = ..
// or
// wasmImports = ..
if (
node.type === 'AssignmentExpression' &&
node.left.name == 'wasmImports' &&
node.right.type == 'ObjectExpression'
) {
return true;
}
return (
node.type === 'VariableDeclaration' &&
node.declarations.length === 1 &&
node.declarations[0].id.name === 'wasmImports' &&
node.declarations[0].init &&
node.declarations[0].init.type === 'ObjectExpression'
);
}
function getWasmImportsValue(node) {
if (node.declarations) {
return node.declarations[0].init;
} else {
return node.right;
}
}
function isExportUse(node) {
// Match usages of symbols on the `wasmExports` object. e.g:
// wasmExports['X']
return (
node.type === 'MemberExpression' &&
node.object.type === 'Identifier' &&
isLiteralString(node.property) &&
node.object.name === 'wasmExports'
);
}
function getExportOrModuleUseName(node) {
return node.property.value;
}
function isModuleUse(node) {
return (
node.type === 'MemberExpression' && // Module['X']
node.object.type === 'Identifier' &&
node.object.name === 'Module' &&
isLiteralString(node.property)
);
}
// Apply import/export name changes (after minifying them)
function applyImportAndExportNameChanges(ast) {
const mapping = extraInfo.mapping;
fullWalk(ast, (node) => {
if (isWasmImportsAssign(node)) {
const assignedObject = getWasmImportsValue(node);
assignedObject.properties.forEach((item) => {
if (mapping[item.key.name]) {
item.key.name = mapping[item.key.name];
}
});
} else if (node.type === 'AssignmentExpression') {
const value = node.right;
if (isExportUse(value)) {
const name = value.property.value;
if (mapping[name]) {
setLiteralValue(value.property, mapping[name]);
}
}
} else if (node.type === 'CallExpression' && isExportUse(node.callee)) {
// wasmExports["___wasm_call_ctors"](); -> wasmExports["M"]();
const callee = node.callee;
const name = callee.property.value;
if (mapping[name]) {
setLiteralValue(callee.property, mapping[name]);
}
} else if (isExportUse(node)) {
const prop = node.property;
const name = prop.value;
if (mapping[name]) {
setLiteralValue(prop, mapping[name]);
}
}
});
}
// A static dyncall is dynCall('vii', ..), which is actually static even
// though we call dynCall() - we see the string signature statically.
function isStaticDynCall(node) {
return (
node.type === 'CallExpression' &&
node.callee.type === 'Identifier' &&
node.callee.name === 'dynCall' &&
isLiteralString(node.arguments[0])
);
}
function getStaticDynCallName(node) {
return 'dynCall_' + node.arguments[0].value;
}
// a dynamic dyncall is one in which all we know is *some* dynCall may
// be called, but not who. This can be either
// dynCall(*not a string*, ..)
// or, to be conservative,
// "dynCall_"
// as that prefix means we may be constructing a dynamic dyncall name
// (dynCall and embind's requireFunction do this internally).
function isDynamicDynCall(node) {
return (
(node.type === 'CallExpression' &&
node.callee.type === 'Identifier' &&
node.callee.name === 'dynCall' &&
!isLiteralString(node.arguments[0])) ||
(isLiteralString(node) && node.value === 'dynCall_')
);
}
//
// Matches the wasm export wrappers generated by emcc (see make_export_wrappers
// in emscripten.py). For example, the right hand side of these assignments:
//
// var _foo = (a0, a1) => (_foo = wasmExports['foo'])(a0, a1):
//
// or
//
// var _foo = (a0, a1) => (_foo = Module['_foo'] = wasmExports['foo'])(a0, a1):
//
function isExportWrapperFunction(f) {
if (f.body.type != 'CallExpression') return null;
let callee = f.body.callee;
if (callee.type == 'ParenthesizedExpression') {
callee = callee.expression;
}
if (callee.type != 'AssignmentExpression') return null;
var rhs = callee.right;
if (rhs.type == 'AssignmentExpression') {
rhs = rhs.right;
}
if (rhs.type != 'MemberExpression' || !isExportUse(rhs)) return null;
return getExportOrModuleUseName(rhs);
}
//
// Emit the DCE graph, to help optimize the combined JS+wasm.
// This finds where JS depends on wasm, and where wasm depends
// on JS, and prints that out.
//
// The analysis here is simplified, and not completely general. It
// is enough to optimize the common case of JS library and runtime
// functions involved in loops with wasm, but not more complicated
// things like JS objects and sub-functions. Specifically we
// analyze as follows:
//
// * We consider (1) the toplevel scope, and (2) the scopes of toplevel defined
// functions (defun, not function; i.e., function X() {} where
// X can be called later, and not y = function Z() {} where Z is
// just a name for stack traces). We also consider the wasm, which
// we can see things going to and arriving from.
// * Anything used in a defun creates a link in the DCE graph, either
// to another defun, or the wasm.
// * Anything used in the toplevel scope is rooted, as it is code
// we assume will execute. The exceptions are
// * when we receive something from wasm; those are "free" and
// do not cause rooting. (They will become roots if they are
// exported, the metadce logic will handle that.)
// * when we send something to wasm; sending a defun causes a
// link in the DCE graph.
// * Anything not in the toplevel or not in a toplevel defun is
// considering rooted. We don't optimize those cases.
//
// Special handling:
//
// * dynCall('vii', ..) are dynamic dynCalls, but we analyze them
// statically, to preserve the dynCall_vii etc. method they depend on.
// Truly dynamic dynCalls (not to a string constant) will not work,
// and require the user to export them.
// * Truly dynamic dynCalls are assumed to reach any dynCall_*.
//
// XXX this modifies the input AST. if you want to keep using it,
// that should be fixed. Currently the main use case here does
// not require that. TODO FIXME
//
function emitDCEGraph(ast) {
// First pass: find the wasm imports and exports, and the toplevel
// defuns, and save them on the side, removing them from the AST,
// which makes the second pass simpler.
//
// The imports that wasm receives look like this:
//
// var wasmImports = { "abort": abort, "assert": assert, [..] };
//
// The exports are trickier, as they have a different form whether or not
// async compilation is enabled. It can be either:
//
// var _malloc = Module['_malloc'] = wasmExports['_malloc'];
//
// or
//
// var _malloc = wasmExports['_malloc'];
//
// or
//
// var _malloc = Module['_malloc'] = (x) => wasmExports['_malloc'](x);
//
// or, in the minimal runtime, it looks like
//
// function assignWasmExports(wasmExports)
// ..
// _malloc = wasmExports["malloc"];
// ..
// });
const imports = [];
const defuns = [];
const dynCallNames = [];
const nameToGraphName = {};
const modulePropertyToGraphName = {};
const exportNameToGraphName = {}; // identical to wasmExports['..'] nameToGraphName
const graph = [];
let foundWasmImportsAssign = false;
let foundMinimalRuntimeExports = false;
function saveAsmExport(name, asmName) {
// the asmName is what the wasm provides directly; the outside JS
// name may be slightly different (extra "_" in wasm backend)
const graphName = getGraphName(name, 'export');
nameToGraphName[name] = graphName;
modulePropertyToGraphName[name] = graphName;
exportNameToGraphName[asmName] = graphName;
if (/^dynCall_/.test(name)) {
dynCallNames.push(graphName);
}
}
// We track defined functions very carefully, so that we can remove them and
// the things they call, but other function scopes (like arrow functions and
// object methods) are trickier to track (object methods require knowing what
// object a function name is called on), so we do not track those. We consider
// all content inside them as top-level, which means it is used.
var specialScopes = 0;
fullWalk(
ast,
(node) => {
if (isWasmImportsAssign(node)) {
const assignedObject = getWasmImportsValue(node);
assignedObject.properties.forEach((item) => {
let value = item.value;
if (value.type === 'Literal' || value.type === 'FunctionExpression') {
return; // if it's a numeric or function literal, nothing to do here
}
if (value.type === 'LogicalExpression') {
// We may have something like wasmMemory || Module.wasmMemory in pthreads code;
// use the left hand identifier.
value = value.left;
}
assertAt(value.type === 'Identifier', value);
const nativeName = item.key.type == 'Literal' ? item.key.value : item.key.name;
assert(nativeName);
imports.push([value.name, nativeName]);
});
foundWasmImportsAssign = true;
emptyOut(node); // ignore this in the second pass; this does not root
} else if (node.type === 'AssignmentExpression') {
const target = node.left;
// Ignore assignment to the wasmExports object (as happens in
// applySignatureConversions).
if (isExportUse(target)) {
emptyOut(node);
}
} else if (node.type === 'VariableDeclaration') {
if (node.declarations.length === 1) {
const item = node.declarations[0];
const name = item.id.name;
const value = item.init;
if (value && isExportUse(value)) {
const asmName = getExportOrModuleUseName(value);
// this is:
// var _x = wasmExports['x'];
saveAsmExport(name, asmName);
emptyOut(node);
} else if (value && value.type === 'ArrowFunctionExpression') {
// this is
// () => (x = wasmExports['x'])(..)
// or
// () => (x = Module['_x'] = wasmExports['x'])(..)
let asmName = isExportWrapperFunction(value);
if (asmName) {
saveAsmExport(name, asmName);
emptyOut(node);
}
} else if (value && value.type === 'AssignmentExpression') {
const assigned = value.left;
if (isModuleUse(assigned) && getExportOrModuleUseName(assigned) === name) {
// this is
// var x = Module['x'] = ?
// which looks like a wasm export being received. confirm with the asm use
let found = 0;
let asmName;
fullWalk(value.right, (node) => {
if (isExportUse(node)) {
found++;
asmName = getExportOrModuleUseName(node);
}
});
// in the wasm backend, the asm name may have one fewer "_" prefixed
if (found === 1) {
// this is indeed an export
// the asmName is what the wasm provides directly; the outside JS
// name may be slightly different (extra "_" in wasm backend)
saveAsmExport(name, asmName);
emptyOut(node); // ignore this in the second pass; this does not root
return;
}
if (value.right.type === 'Literal') {
// this is
// var x = Module['x'] = 1234;
// this form occurs when global addresses are exported from the
// module. It doesn't constitute a usage.
assertAt(typeof value.right.value === 'number', value.right);
emptyOut(node);
}
}
}
}
// A variable declaration that has no initial values can be ignored in
// the second pass, these are just declarations, not roots - an actual
// use must be found in order to root.
if (!node.declarations.reduce((hasInit, decl) => hasInit || !!decl.init, false)) {
emptyOut(node);
}
} else if (node.type === 'FunctionDeclaration') {
const name = node.id.name;
// Check if this is the minimal runtime exports function, which looks like
// function assignWasmExports(wasmExports)
if (
name == 'assignWasmExports' &&
node.params.length === 1 &&
node.params[0].type === 'Identifier' &&
node.params[0].name === 'wasmExports'
) {
// This looks very much like what we are looking for.
const body = node.body.body;
assert(!foundMinimalRuntimeExports);
foundMinimalRuntimeExports = true;
for (let i = 0; i < body.length; i++) {
const item = body[i];
if (
item.type === 'ExpressionStatement' &&
item.expression.type === 'AssignmentExpression' &&
item.expression.operator === '=' &&
item.expression.left.type === 'Identifier' &&
item.expression.right.type === 'MemberExpression' &&
item.expression.right.object.type === 'Identifier' &&
item.expression.right.object.name === 'wasmExports' &&
item.expression.right.property.type === 'Literal'
) {
const name = item.expression.left.name;
const asmName = item.expression.right.property.value;
saveAsmExport(name, asmName);
emptyOut(item); // ignore all this in the second pass; this does not root
}
}
} else if (!specialScopes) {
defuns.push(node);
nameToGraphName[name] = getGraphName(name, 'defun');
emptyOut(node); // ignore this in the second pass; we scan defuns separately
}
} else if (node.type === 'ArrowFunctionExpression') {
assert(specialScopes > 0);
specialScopes--;
} else if (node.type === 'Property' && node.method) {
assert(specialScopes > 0);
specialScopes--;
}
},
(node) => {
// Pre-walking logic. We note special scopes (see above).
if (node.type === 'ArrowFunctionExpression' || (node.type === 'Property' && node.method)) {
specialScopes++;
}
},
);
// Scoping must balance out.
assert(specialScopes === 0);
// We must have found the info we need.
assert(
foundWasmImportsAssign,
'could not find the assignment to "wasmImports". perhaps --pre-js or --post-js code moved it out of the global scope? (things like that should be done after emcc runs, as they do not need to be run through the optimizer which is the special thing about --pre-js/--post-js code)',
);
// Read exports that were declared in extraInfo
if (extraInfo) {
for (const exp of extraInfo.exports) {
saveAsmExport(exp[0], exp[1]);
}
}
// Second pass: everything used in the toplevel scope is rooted;
// things used in defun scopes create links
function getGraphName(name, what) {
return 'emcc$' + what + '$' + name;
}
const infos = {}; // the graph name of the item => info for it
for (const [jsName, nativeName] of imports) {
const name = getGraphName(jsName, 'import');
const info = (infos[name] = {
name: name,
import: ['env', nativeName],
reaches: {},
});
if (nameToGraphName.hasOwnProperty(jsName)) {
info.reaches[nameToGraphName[jsName]] = 1;
} // otherwise, it's a number, ignore
}
for (const [e, _] of Object.entries(exportNameToGraphName)) {
const name = exportNameToGraphName[e];
infos[name] = {
name: name,
export: e,
reaches: {},
};
}
// a function that handles a node we visit, in either a defun or
// the toplevel scope (in which case the second param is not provided)
function visitNode(node, defunInfo) {
// TODO: scope awareness here. for now we just assume all uses are
// from the top scope, which might create more uses than needed
let reached;
if (node.type === 'Identifier') {
const name = node.name;
if (nameToGraphName.hasOwnProperty(name)) {
reached = nameToGraphName[name];
}
} else if (isModuleUse(node)) {
const name = getExportOrModuleUseName(node);
if (modulePropertyToGraphName.hasOwnProperty(name)) {
reached = modulePropertyToGraphName[name];
}
} else if (isStaticDynCall(node)) {
reached = getGraphName(getStaticDynCallName(node), 'export');
} else if (isDynamicDynCall(node)) {
// this can reach *all* dynCall_* targets, we can't narrow it down
reached = dynCallNames;
} else if (isExportUse(node)) {
// any remaining asm uses are always rooted in any case
const name = getExportOrModuleUseName(node);
if (exportNameToGraphName.hasOwnProperty(name)) {
infos[exportNameToGraphName[name]].root = true;
}
return;
}
if (reached) {
function addReach(reached) {
if (defunInfo) {
defunInfo.reaches[reached] = 1; // defun reaches it
} else {
if (infos[reached]) {
infos[reached].root = true; // in global scope, root it
} else {
// An info might not exist for the identifier if it is missing, for
// example, we might call Module.dynCall_vi in library code, but it
// won't exist in a standalone (non-JS) build anyhow. We can ignore
// it in that case as the JS won't be used, but warn to be safe.
trace('metadce: missing declaration for ' + reached);
}
}
}
if (typeof reached === 'string') {
addReach(reached);
} else {
reached.forEach(addReach);
}
}
}
defuns.forEach((defun) => {
const name = getGraphName(defun.id.name, 'defun');
const info = (infos[name] = {
name: name,
reaches: {},
});
fullWalk(defun.body, (node) => visitNode(node, info));
});
fullWalk(ast, (node) => visitNode(node, null));
// Final work: print out the graph
// sort for determinism
function sortedNamesFromMap(map) {
const names = [];
for (const name of Object.keys(map)) {
names.push(name);
}
names.sort();
return names;
}
sortedNamesFromMap(infos).forEach((name) => {
const info = infos[name];
info.reaches = sortedNamesFromMap(info.reaches);
graph.push(info);
});
print(JSON.stringify(graph, null, ' '));
}
// Apply graph removals from running wasm-metadce. This only removes imports and
// exports from JS side, effectively disentangling the wasm and JS sides that
// way (and we leave further DCE on the JS and wasm sides to their respective
// optimizers, closure compiler and binaryen).
function applyDCEGraphRemovals(ast) {
const unusedExports = new Set(extraInfo.unusedExports);
const unusedImports = new Set(extraInfo.unusedImports);
const foundUnusedImports = new Set();
const foundUnusedExports = new Set();
trace('unusedExports:', unusedExports);
trace('unusedImports:', unusedImports);
fullWalk(ast, (node) => {
if (isWasmImportsAssign(node)) {
const assignedObject = getWasmImportsValue(node);
assignedObject.properties = assignedObject.properties.filter((item) => {
const name = item.key.name;
const value = item.value;
if (unusedImports.has(name)) {
foundUnusedImports.add(name);
return hasSideEffects(value);
}
return true;
});
} else if (node.type === 'VariableDeclaration') {
// Handle the various ways in which we extract wasmExports:
// 1. var _x = wasmExports['x'];
// or
// 2. var _x = Module['_x'] = wasmExports['x'];
//