{{ message }}
Repository navigation
Expand file tree
/
Copy pathacorn-optimizer.mjs
More file actions
executable file
·1965 lines (1853 loc) · 62.8 KB
/
Copy pathacorn-optimizer.mjs
File metadata and controls
executable file
·1965 lines (1853 loc) · 62.8 KB
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 importPhases from 'acorn-import-phases';
import {minify_sync} from 'terser';
import * as fs from 'node:fs';
import assert from 'node:assert';
import {parseArgs} from 'node:util';
// Extend acorn to understand source-phase import syntax
// (`import source foo from './bar.wasm'`) emitted under -sSOURCE_PHASE_IMPORTS.
// The plugin annotates ImportDeclaration nodes with a `phase` field; terser
// carries this through from_mozilla_ast / to_mozilla_ast and emits it back on
// output.
const parser = acorn.Parser.extend(importPhases());
// Utilities
function read(x) {
return fs.readFileSync(x, 'utf-8');
}
function assertAt(condition, node, message = '') {
if (!condition) {
if (!process.env.EMCC_DEBUG_SAVE) {
message += ' (use EMCC_DEBUG_SAVE=1 to preserve temporary inputs)';
}
let err = new Error(message);
err['loc'] = acorn.getLineInfo(input, node.start);
throw err;
}
}
// 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 (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). If |pre| returns
// `false`, the node and its children will be skipped.
function fullWalk(node, c, pre) {
if (pre?.(node) !== false) {
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 setLiteralValue(item, value) {
item.value = value;
item.raw = null;
}
function isLiteralString(node) {
return node.type === 'Literal' && typeof node.value === 'string';
}
function dump(node) {
console.log(JSON.stringify(node, null, ' '));
}
// Traverse a pattern node (identifier, object/array pattern, etc) invoking onExpr on any nested expressions and onBoundIdent on any bound identifiers.
function walkPattern(node, onExpr, onBoundIdent) {
recursiveWalk(node, {
AssignmentPattern(node, c) {
c(node.left);
onExpr(node.right);
},
Property(node, c) {
if (node.computed) {
onExpr(node.key);
}
c(node.value);
},
Identifier({name}) {
onBoundIdent(name);
},
});
}
function hasSideEffects(node) {
// Conservative analysis.
let has = false;
fullWalk(
node,
(node) => {
switch (node.type) {
case 'ExpressionStatement':
if (node.directive) {
has = true;
}
break;
// TODO: go through all the ESTree spec
case 'Literal':
case 'Identifier':
case 'UnaryExpression':
case 'BinaryExpression':
case 'LogicalExpression':
case 'UpdateOperator':
case 'ConditionalExpression':
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;
}
}
},
(node) =>
// Ignore inner scopes.
!['FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression'].includes(node.type),
);
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, {
ForStatement(node, c) {
visitChildren(node, c);
// If we had `for (var x = ...; ...)` and we removed `x`, we need to change to `for (; ...)`.
if (node.init?.type === 'EmptyStatement') {
node.init = null;
}
},
ForInStatement(node, c) {
// We can't remove the var in a for-in, as that would result in an invalid syntax. Skip the LHS.
c(node.right);
c(node.body);
},
ForOfStatement(node, c) {
// We can't remove the var in a for-of, as that would result in an invalid syntax. Skip the LHS.
c(node.right);
c(node.body);
},
VariableDeclaration(node, _c) {
let removedHere = 0;
node.declarations = node.declarations.filter((node) => {
assert(node.type === 'VariableDeclarator');
let keep = node.init && hasSideEffects(node.init);
walkPattern(
node.id,
(value) => {
keep ||= hasSideEffects(value);
},
(boundName) => {
keep ||= !names.has(boundName);
},
);
if (!keep) removedHere = 1;
return keep;
});
removed += removedHere;
if (node.declarations.length === 0) {
emptyOut(node);
}
},
ExpressionStatement(node, _c) {
if (aggressive && !hasSideEffects(node)) {
emptyOut(node);
removed++;
}
},
FunctionDeclaration(node, _c) {
if (names.has(node.id.name)) {
removed++;
emptyOut(node);
return;
}
// do not recurse into other scopes
},
// do not recurse into other scopes
FunctionExpression() {},
ArrowFunctionExpression() {},
});
}
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);
for (const param of node.params) {
walkPattern(param, c, (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 = new Set();
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 eliminatable!
names.add(name);
}
}
cleanUp(node.body, names);
}
recursiveWalk(ast, {
VariableDeclarator(node, c) {
walkPattern(node.id, c, (name) => {
ensureData(scopes[scopes.length - 1], name).def = 1;
});
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 props).
if (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;
},
ExportDefaultDeclaration(node, c) {
const name = node.declaration.id.name;
ensureData(scopes[scopes.length - 1], name).use = 1;
c(node.declaration);
},
ExportNamedDeclaration(node, c) {
if (node.declaration) {
if (node.declaration.type == 'FunctionDeclaration') {
const name = node.declaration.id.name;
ensureData(scopes[scopes.length - 1], name).use = 1;
} else {
assert(node.declaration.type == 'VariableDeclaration');
for (const decl of node.declaration.declarations) {
const name = decl.id.name;
ensureData(scopes[scopes.length - 1], name).use = 1;
}
}
c(node.declaration);
} else {
for (const specifier of node.specifiers) {
const name = specifier.local.name;
ensureData(scopes[scopes.length - 1], name).use = 1;
}
}
},
});
// toplevel
const scope = scopes.pop();
assert(scopes.length === 0);
const names = new Set();
for (const [name, data] of Object.entries(scope)) {
if (data.def && !data.use) {
assert(!data.param); // can't be
// this is eliminatable!
names.add(name);
}
}
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;
}
}
// Under WASM_ESM_INTEGRATION the wasm exports are received as a native ES
// import from the wasm module itself:
// import { malloc as _malloc, memory } from './a.out.wasm';
function isImportFromWasm(node) {
return (
node.type === 'ImportDeclaration' &&
// Skip source/defer phase imports (e.g. `import source foo from './a.wasm'`
// under SOURCE_PHASE_IMPORTS), whose default specifier binds the module
// itself rather than wasm exports. Value-phase imports leave `phase` unset.
!node.phase &&
isLiteralString(node.source) &&
node.source.value.endsWith('.wasm')
);
}
// A sourceless `export { a as b, .. };` statement (not `export <decl>` and not
// a re-export `export {..} from '..'`).
function isExportSpecifierList(node) {
return (
node.type === 'ExportNamedDeclaration' && !node.declaration && !node.source
);
}
function isExportUse(node) {
// Match usages of symbols on the `wasmExports` object. e.g:
// wasmExports['X']
// `origExports` holds the unwrapped exports in applySignatureConversions.
return (
node.type === 'MemberExpression' &&
node.object.type === 'Identifier' &&
isLiteralString(node.property) &&
(node.object.name === 'wasmExports' || node.object.name === 'origExports')
);
}
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]);
}
} else if (isImportFromWasm(node)) {
// WASM_ESM_INTEGRATION: rename the wasm-facing name of each received
// export, e.g. `import { malloc as _malloc }` -> `import { a as _malloc }`.
// Replace the imported slot (rather than mutate it in place) since for an
// unaliased specifier acorn shares one node for both sides.
node.specifiers.forEach((spec) => {
const newName = mapping[spec.imported.name];
if (newName) {
spec.imported = makeIdentifier(newName);
}
});
} else if (isExportSpecifierList(node)) {
// WASM_ESM_INTEGRATION: rename the wasm-facing name of each JS function
// sent to wasm, e.g. `export { _fd_write as fd_write }` ->
// `export { _fd_write as a }`. Re-exports of wasm exports (`export {
// _main }`) carry a JS-local name that is never in the mapping, so they
// are left untouched.
node.specifiers.forEach((spec) => {
const newName = mapping[spec.exported.name];
if (newName) {
spec.exported = makeIdentifier(newName);
}
});
}
});
}
// 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_')
);
}
//
// 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
let foundWasmImportsAssign = false;
let foundMinimalRuntimeExports = false;
// Under WASM_ESM_INTEGRATION, JS names bound to wasm exports via an ES import
// from the wasm module. Lets us tell a re-export of a wasm export apart from a
// JS function that is itself exported to wasm (both are `export {..}`).
const wasmExportLocals = new Set();
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 (isImportFromWasm(node)) {
// WASM_ESM_INTEGRATION: wasm exports received as
// import { malloc as _malloc, memory } from './a.out.wasm';
// Each binding is a wasm export, exactly like `var _x = wasmExports['x']`.
node.specifiers.forEach((spec) => {
const jsName = spec.local.name; // JS-side name
const asmName = spec.imported.name; // wasm-provided name
if (exportNameToGraphName.hasOwnProperty(asmName)) {
// Another local already binds this wasm export (e.g. both `memory`
// and `memory as wasmMemory`): point this local at the same node so
// a use of either roots the one underlying export.
nameToGraphName[jsName] = exportNameToGraphName[asmName];
} else {
saveAsmExport(jsName, asmName);
}
wasmExportLocals.add(jsName);
});
// This ES form stands in for the `wasmImports`/`wasmExports` idioms the
// non-ESM build emits, so it satisfies the sanity check below.
foundWasmImportsAssign = true;
// Drop from the second pass: the local bindings must not be seen as
// top-level uses (that would root every export and defeat DCE).
emptyOut(node);
} else if (isExportSpecifierList(node)) {
// Sourceless `export {..}` statements come in three forms:
// (a) JS functions sent to wasm: export { _fd_write as fd_write };
// (b) re-exports of wasm exports: export { _main };
// (c) runtime/library exports: export { HEAP32, baz };
// Only (a) are wasm import edges (recorded and removed here). (b) and
// (c) are ordinary top-level uses left in place to root in the second
// pass. (a) is the only form written with an alias (`x as y`), which
// acorn represents with distinct local/exported nodes; bare specifiers
// reuse a single node for both sides.
const importEdges = node.specifiers.filter(
(spec) =>
spec.local !== spec.exported && !wasmExportLocals.has(spec.local.name),
);
if (importEdges.length) {
// (a) `export { jsName as nativeName }` - jsName implements the import.
importEdges.forEach((spec) => imports.push([spec.local.name, spec.exported.name]));
foundWasmImportsAssign = true;
emptyOut(node); // does not root; second pass ignores it
}
} 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 === '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: new Set(),
});
if (nameToGraphName.hasOwnProperty(jsName)) {
info.reaches.add(nameToGraphName[jsName]);
} // otherwise, it's a number, ignore
}
for (const [e, _] of Object.entries(exportNameToGraphName)) {
const name = exportNameToGraphName[e];
infos[name] = {
name: name,
export: e,
reaches: new Set(),
};
}
// 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.add(reached); // 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: new Set(),
});
fullWalk(defun.body, (node) => visitNode(node, info));
});
fullWalk(ast, (node) => visitNode(node, null));
// Final work: print out the graph
// sort for determinism
const graph = Object.entries(infos)
.sort(([name1], [name2]) => (name1 > name2 ? 1 : -1))
.map(([_name, info]) => ({
...info,
reaches: Array.from(info.reaches).sort(),
}));
dump(graph);
}
// 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 (isImportFromWasm(node)) {
// WASM_ESM_INTEGRATION: drop unused wasm exports from
// import { malloc as _malloc, .. } from './a.out.wasm';
node.specifiers = node.specifiers.filter((spec) => {
if (unusedExports.has(spec.imported.name)) {
foundUnusedExports.add(spec.imported.name);
return false;
}
return true;
});
You can’t perform that action at this time.
