Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
1876 lines (1647 loc) · 68.9 KB

File metadata and controls

1876 lines (1647 loc) · 68.9 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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 2025 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.
*/
// Perform dead argument elimination based on a smallest fixed point analysis of
// used parameters. Traverse the module once to collect call graph information,
// used parameters, and "forwarded" parameters that are only used by being
// forwarded on to other function calls. Parameters are forwarded if their
// local.gets are consumed as parameters to function calls or if they are
// consumed by other side-effect-free instructions that are transitively
// forwarded to function calls. These forwarded parameters (and their
// intermediate users) can still be optimized out as long as they are unused in
// the callees they are forwarded to. Since we perform a fixed point analysis,
// cycles of forwarded parameters can still be removed.
//
// After finding used parameters, traverse the module once more to remove
// unused parameters and arguments. Finally, if we are able to optimize indirect
// calls and referenced functions, traverse the module one last time to globally
// update referenced function types. This may require first giving unreferenced
// functions replacement types to make sure they are not incorrectly updated by
// the global type rewriting.
//
// As a POC, only do the backward analysis to find unused parameters. To match
// and exceed the power of DAE, we will need to extend this backward analysis to
// find unused results as well, and also add a forward analysis that propagates
// constants and types through parameters and results.
#include <algorithm>
#include <memory>
#include <unordered_map>
#include <vector>
#include "analysis/lattices/bool.h"
#include "ir/effects.h"
#include "ir/eh-utils.h"
#include "ir/intrinsics.h"
#include "ir/label-utils.h"
#include "ir/local-graph.h"
#include "ir/module-utils.h"
#include "ir/type-updating.h"
#include "pass.h"
#include "support/index.h"
#include "support/mixed_arena.h"
#include "support/utilities.h"
#include "wasm-builder.h"
#include "wasm-traversal.h"
#include "wasm-type-shape.h"
#include "wasm-type.h"
#include "wasm.h"
#ifndef TIME_DAE
#define TIME_DAE 0
#endif
#ifndef DAE_STATS
#define DAE_STATS 0
#endif
#if TIME_DAE || DAE_STATS
#include <iostream>
#include "support/insert_ordered.h"
#include "support/strongly_connected_components.h"
#include "support/timing.h"
#endif // TIME_DAE || DAE_STATS
// TODO: Treat call_indirects more precisely than call_refs by taking the target
// table into account.
// TODO: Analyze stack switching instructions to remove their unused parameters.
namespace wasm {
namespace {
#if TIME_DAE
#define TIME(...) __VA_ARGS__
#else
#define TIME(...)
#endif // TIME_DAE
// Find the non-basic root of the subtyping hierarchy for a given HeapType.
HeapType getRootType(HeapType type) {
while (true) {
if (auto super = type.getDeclaredSuperType()) {
type = *super;
continue;
}
break;
}
return type;
}
// Analysis lattice: top/true = used, bot/false = unused.
using Used = analysis::Bool;
// Analysis results for each parameter of a function.
using Params = std::vector<Used::Element>;
// Function index and parameter index.
using FuncParamLoc = std::pair<Index, Index>;
// Function index identifying the function's result (we treat result tuples as a
// single value, so no index into the results is necessary).
using FuncResultLoc = Index;
// Function type and parameter index.
using TypeParamLoc = std::pair<HeapType, Index>;
// Function type identifying the function type's result (we treat result tuples
// as a single value, so no index into the results is necessary).
using TypeResultLoc = HeapType;
using Location =
std::variant<FuncParamLoc, FuncResultLoc, TypeParamLoc, TypeResultLoc>;
// A set of (source, destination) index pairs for parameters of a caller
// function being forwarded as arguments to a callee function.
using ForwardedParamSet = std::unordered_set<std::pair<Index, Index>>;
// Map param indices (in the outer vector) to lists of locations.
// TODO: Experiment with using a set in place of the inner vector.
using ParamLocations = std::vector<std::vector<Location>>;
using TypeMap = GlobalTypeRewriter::TypeMap;
// Analysis results and call graph information for a single function.
// This tracks how parameters are used within the function and how they
// are forwarded to other functions via direct and indirect calls.
struct FunctionInfo {
// Analysis results. For each parameter, whether it is used.
Params paramUsages;
// Analysis result for the function result. It will remain bot if there is no
// result.
Used::Element resultUsage;
// Map direct callee function names to the source locations forwarded to their
// parameters.
std::unordered_map<Name, ParamLocations> forwardedToDirectParams;
// Map the root supertypes of indirect callee types to the source locations
// forwarded to their parameters.
std::unordered_map<HeapType, ParamLocations> forwardedToIndirectParams;
// Locations forwarded to this function's result. These locations will become
// used if the result turns out ot be used.
std::vector<Location> resultSources;
// For each parameter of this function, the list of locations that will become
// used if the parameter turns out to be used. Computed by reversing the
// forwardedToDirectParams graph.
ParamLocations paramSources;
// Locations used in an observable way by the code in this function.
// Propagation of usage will begin at these locations.
// TODO: Experiment with making this a set.
std::vector<Location> usedLocations;
// The gets that may read from parameters. These are the gets that might be
// optimized out if their results are unused or forwarded to another function
// where they will be unused.
std::unordered_set<LocalGet*> paramGets;
// We do not yet analyze parameter or result usage in stack switching
// instructions. Collect the used continuation types so we can be sure not to
// modify their associated function types.
// TODO: Analyze stack switching.
std::unordered_set<HeapType> contTypes;
// Whether we need to additionally propagate param usage to and result usage
// from indirect callers of this function's type. Atomic because it can be set
// when visiting other functions in parallel.
std::atomic<bool> referenced = false;
// We cannot yet fully analyze and optimize call.without.effects, which would
// require creating new imports for new signatures, etc. Functions that are
// called via these intrinsics will not be optimized.
// TODO: Fix this.
std::atomic<bool> usedInIntrinsic = false;
// Unreferenced functions can be optimized separately from referenced
// functions with the same type. For unreferenced functions in that situation,
// this is the new type that should be applied before global type rewriting to
// prevent the function from getting the wrong optimizations.
std::optional<HeapType> replacementType;
// Functions that this function directly tail-calls.
std::vector<Index> tailCallees;
// Root function types that this function indirectly tail-calls.
std::vector<HeapType> tailCalleeTypes;
};
// Analysis results and call graph information for a tree of related function
// types. Every type in the tree must have matching used and unused parameters,
// so we can track information per-tree instead of per-type.
struct RootFuncTypeInfo {
// For each parameter in the type, whether it is used.
Params paramUsages;
// Analysis result for the function result.
Used::Element resultUsage;
// The list of referenced functions with types in this tree. When a parameter
// in this type tree is used, the parameter becomes used in these functions
// and vice versa.
std::vector<Index> referencedFuncs;
// For each parameter in this root function type, the list of locations that
// become used when the parameter in this root function type becomes used.
// Computed by reversing indirectForwardedParams from the function infos for
// functions with this root type.
ParamLocations paramSources;
// Tail-callers of this type tree. If this type tree's result is used,
// these callers' results must also be used. Normally, result usage only
// flows from types to their referenced functions, but tail calls require
// this reverse constraint.
std::vector<Location> resultSources;
RootFuncTypeInfo(Used& used, HeapType type)
: paramUsages(type.getSignature().params.size(), used.getBottom()),
resultUsage(used.getBottom()),
paramSources(type.getSignature().params.size()) {}
};
struct DAE2 : public Pass {
// Analysis lattice.
Used used;
Module* wasm = nullptr;
// Map function name to index.
std::unordered_map<Name, Index> funcIndices;
// Intermediate and final analysis results by function index.
std::vector<FunctionInfo> funcInfos;
// Intermediate and final analysis results for each function type tree, keyed
// by root type in the tree.
std::unordered_map<HeapType, RootFuncTypeInfo> typeTreeInfos;
RootFuncTypeInfo& getTypeTreeInfo(HeapType rootType) {
return typeTreeInfos.try_emplace(rootType, used, rootType).first->second;
}
// In general referenced functions may escape and be called externally in an
// open world, so we require a closed world to optimize referenced functions.
// Further, without GC we cannot differentiate the types of unreferenced and
// referenced functions before global type rewriting, so we cannot optimize
// them separately. Do not constrain the optimization of unreferenced
// functions by optimizing referenced functions in that case.
// TODO: Find a way to optimize referenced functions without GC enabled as
// long as traps never happen so call_indirect cannot distinguish separate
// types.
bool optimizeReferencedFuncs = false;
// Cache the public heap types to avoid gathering them more than once.
std::vector<HeapType> publicHeapTypes;
void run(Module* wasm) override {
this->wasm = wasm;
for (auto& func : wasm->functions) {
funcIndices.insert({func->name, funcIndices.size()});
}
optimizeReferencedFuncs =
getPassOptions().worldMode == WorldMode::Closed && wasm->features.hasGC();
TIME(Timer timer);
analyzeModule();
TIME(std::cerr << "analysis: " << timer.lastElapsed() << "\n");
prepareReverseGraph();
TIME(std::cerr << "prepare: " << timer.lastElapsed() << "\n");
computeFixedPoint();
TIME(std::cerr << "fixed point: " << timer.lastElapsed() << "\n");
#if DAE_STATS
collectStats();
TIME(std::cerr << "stats: " << timer.lastElapsed() << "\n");
#endif // DAE_STATS
optimize();
TIME(auto [last, total] = timer.elapsed());
TIME(std::cerr << "optimize: " << last << "\n");
TIME(std::cerr << "total: " << total << "\n");
}
void analyzeModule();
void prepareReverseGraph();
void computeFixedPoint();
void optimize();
template<typename F> void forEachSuccessor(Location loc, F&& f);
#if DAE_STATS
void collectStats();
#endif // DAE_STATS
void makeUnreferencedFunctionTypes(const std::vector<HeapType>& oldTypes,
const TypeMap& newTypes);
void markParamsUsed(Index funcIndex) {
auto& usages = funcInfos[funcIndex].paramUsages;
std::fill(usages.begin(), usages.end(), used.getTop());
}
void markParamsUsed(Name func) { markParamsUsed(funcIndices.at(func)); }
void markParamsUsed(HeapType rootType) {
auto& usages = getTypeTreeInfo(rootType).paramUsages;
std::fill(usages.begin(), usages.end(), used.getTop());
}
void markResultsUsed(Index funcIndex) {
funcInfos[funcIndex].resultUsage = used.getTop();
}
void markResultsUsed(Name func) { markResultsUsed(funcIndices.at(func)); }
void markResultsUsed(HeapType rootType) {
getTypeTreeInfo(rootType).resultUsage = used.getTop();
}
Used::Element& elem(Location loc) {
if (auto* l = std::get_if<FuncParamLoc>(&loc)) {
return funcInfos[l->first].paramUsages[l->second];
}
if (auto* l = std::get_if<FuncResultLoc>(&loc)) {
return funcInfos[*l].resultUsage;
}
if (auto* l = std::get_if<TypeParamLoc>(&loc)) {
assert(l->first == getRootType(l->first));
return getTypeTreeInfo(l->first).paramUsages[l->second];
}
if (auto* l = std::get_if<TypeResultLoc>(&loc)) {
assert(*l == getRootType(*l));
return getTypeTreeInfo(*l).resultUsage;
}
WASM_UNREACHABLE("unexpected location");
}
};
struct GraphBuilder : public WalkerPass<ExpressionStackWalker<GraphBuilder>> {
bool isFunctionParallel() override { return true; }
bool modifiesBinaryenIR() override { return false; }
// Analysis lattice.
const Used& used;
// The function info graph is stored as vectors accessed by function index.
// Map function names to their indices.
const std::unordered_map<Name, Index>& funcIndices;
// Vector of analysis info representing the analysis graph we are building.
// This is populated safely in parallel because the visitor for each function
// only modifies the entry for that function.
std::vector<FunctionInfo>& funcInfos;
// The index of the function we are currently walking.
Index index = -1;
// A use of a parameter local does not necessarily imply the use of the
// parameter value. We use a local graph to check where parameter values may
// be used.
std::optional<LazyLocalGraph> localGraph;
bool optimizeReferencedFuncs;
GraphBuilder(const Used& used,
const std::unordered_map<Name, Index>& funcIndices,
std::vector<FunctionInfo>& funcInfos,
bool optimizeReferencedFuncs)
: used(used), funcIndices(funcIndices), funcInfos(funcInfos),
optimizeReferencedFuncs(optimizeReferencedFuncs) {}
std::unique_ptr<Pass> create() override {
return std::make_unique<GraphBuilder>(
used, funcIndices, funcInfos, optimizeReferencedFuncs);
}
void runOnFunction(Module* wasm, Function* func) override {
assert(index == Index(-1));
index = funcIndices.at(func->name);
localGraph.emplace(func);
WalkerPass<ExpressionStackWalker<GraphBuilder>>::runOnFunction(wasm, func);
}
void visitRefFunc(RefFunc* curr) {
funcInfos[funcIndices.at(curr->func)].referenced = true;
}
void noteContinuation(Type type) {
if (type.isContinuation()) {
funcInfos[index].contTypes.insert(type.getHeapType());
}
}
void visitResumeHandlers(const ArenaVector<Name>& labels) {
for (Index i = 0; i < labels.size(); ++i) {
if (labels[i]) {
auto* target = findBreakTarget(labels[i]);
assert(target->type.size() >= 1);
auto newContType = target->type[target->type.size() - 1];
assert(newContType.isContinuation());
noteContinuation(newContType);
}
}
}
void visitResume(Resume* curr) {
noteContinuation(curr->cont->type);
visitResumeHandlers(curr->handlerBlocks);
}
void visitResumeThrow(ResumeThrow* curr) {
noteContinuation(curr->cont->type);
visitResumeHandlers(curr->handlerBlocks);
}
void visitStackSwitch(StackSwitch* curr) {
noteContinuation(curr->cont->type);
// Do not optimize the return continuation either because that would
// require us to update the type of the switch expression.
if (curr->cont->type.isContinuation()) {
auto retParams = curr->cont->type.getHeapType()
.getContinuation()
.type.getSignature()
.params;
noteContinuation(retParams[retParams.size() - 1]);
}
}
void visitContBind(ContBind* curr) {
noteContinuation(curr->cont->type);
noteContinuation(curr->type);
}
Index getArgIndex(const ExpressionList& operands, Expression* arg) {
for (Index i = 0; i < operands.size(); ++i) {
if (operands[i] == arg) {
return i;
}
}
WASM_UNREACHABLE("expected arg");
}
void forwardToDirectParam(Location source,
const ExpressionList& operands,
Expression* arg,
Name target) {
auto argIndex = getArgIndex(operands, arg);
auto& forwarded = funcInfos[index].forwardedToDirectParams[target];
if (forwarded.empty()) {
forwarded.resize(operands.size());
}
forwarded[argIndex].push_back(source);
}
void forwardToIndirectParam(Location source,
const ExpressionList& operands,
Expression* arg,
HeapType type) {
auto rootType = getRootType(type);
auto argIndex = getArgIndex(operands, arg);
auto& forwarded = funcInfos[index].forwardedToIndirectParams[rootType];
if (forwarded.empty()) {
forwarded.resize(operands.size());
}
forwarded[argIndex].push_back(source);
}
void forwardToResult(Location source) {
funcInfos[index].resultSources.push_back(source);
}
// Record the fact that `curr`'s result comes from `source`.
void getValueFromLocation(Expression* curr, Location source) {
// Look at the transitive users of this value (i.e. its parent and further
// ancestors) to see if it flows (possibly with transformations) into
// another location, `dest`. If it is, we say that `src` is "forwarded" to
// `dest`. We will create an edge in the analysis graph so that if `dest` is
// used, then `src` will be marked as used as well. We must make sure the
// current function doesn't first use `src` in other ways, though, for
// example by teeing it to a local or by performing a branching or trapping
// cast on it. As a conservative approximation, consider the `src` used if
// any of the expressions between `curr` and `dest` have non-removable side
// effects (even if those side effects do not depend on the value flowing
// from `curr`).
if (curr == getFunction()->body) {
// No parents to look at, but the result is forwarded to the function
// result.
forwardToResult(source);
return;
}
for (Index i = expressionStack.size() - 1; i > 0; --i) {
auto* expr = expressionStack[i];
auto* parent = expressionStack[i - 1];
// TODO: Experiment with caching the location (or lack of location, or
// use) reached from parent expressions so we can avoid traversing the
// same parents more than once.
if (auto* call = parent->dynCast<Call>()) {
forwardToDirectParam(source, call->operands, expr, call->target);
return;
}
if (auto* call = parent->dynCast<CallIndirect>();
call && expr != call->target && optimizeReferencedFuncs) {
forwardToIndirectParam(source, call->operands, expr, call->heapType);
return;
}
if (auto* call = parent->dynCast<CallRef>();
call && expr != call->target && optimizeReferencedFuncs) {
if (!call->target->type.isSignature()) {
// The call will never happen, so we don't need to consider it.
return;
}
auto heapType = call->target->type.getHeapType();
forwardToIndirectParam(source, call->operands, expr, heapType);
return;
}
if (parent->is<Return>()) {
forwardToResult(source);
return;
}
// TODO: Handle unconditional branches to blocks that fall through to the
// end of the function as well? Handle all unconditional branches to
// blocks in general?
// If the value flows into an If condition, we must consider it used
// because removing it may visibly change which arm of the If gets
// executed. This is not captured by the effects analysis below.
if (auto* iff = parent->dynCast<If>(); iff && expr == iff->condition) {
break;
}
// TODO: Skip the effects analysis below when we are flowing out of a
// block. Side effects earlier in the block don't matter.
// If the current parent expression has unremovable side effects, we
// conservatively treat the value as used.
EffectAnalyzer effects(getPassOptions(), *getModule());
effects.visit(parent);
if (effects.hasUnremovableSideEffects()) {
// Conservatively assume this expression uses the value in some way that
// prevents us from removing it.
break;
}
if (!parent->type.isConcrete()) {
// The value flows no further, so it is not used in an observable way.
return;
}
// If the value flows out of the function body, it is forwarded to this
// function's results.
if (parent == getFunction()->body) {
forwardToResult(source);
return;
}
}
// The value is used by something we aren't analyzing.
if (auto* l = std::get_if<FuncParamLoc>(&source)) {
// Parameter uses are local to the function and can be updated in
// parallel.
funcInfos[index].paramUsages[l->second] = used.getTop();
} else {
// Other locations will have to be handled later.
funcInfos[index].usedLocations.push_back(source);
}
}
void visitLocalGet(LocalGet* curr) {
if (!getFunction()->isParam(curr->index)) {
return;
}
// A use of a parameter local does not necessarily imply the use of the
// parameter value. Check where the parameter value may be used.
const auto& sets = localGraph->getSets(curr);
bool usesParam = std::any_of(
sets.begin(), sets.end(), [](LocalSet* set) { return set == nullptr; });
if (!usesParam) {
// The original parameter value does not reach here.
return;
}
funcInfos[index].paramGets.insert(curr);
getValueFromLocation(curr, FuncParamLoc{index, curr->index});
}
void visitCall(Call* curr) {
if (Intrinsics(*getModule()).isCallWithoutEffects(curr)) {
auto target = curr->operands.back()->cast<RefFunc>()->func;
funcInfos[funcIndices.at(target)].usedInIntrinsic = true;
}
auto* callee = getModule()->getFunction(curr->target);
if (callee->getResults().isConcrete()) {
Location source = FuncResultLoc{funcIndices.at(curr->target)};
if (curr->isReturn) {
forwardToResult(source);
funcInfos[index].tailCallees.push_back(funcIndices.at(curr->target));
} else {
getValueFromLocation(curr, source);
}
}
}
void handleIndirectCall(Expression* curr, HeapType type, bool isReturn) {
auto sig = type.getSignature();
if (sig.results.isConcrete()) {
HeapType rootType = getRootType(type);
Location source = TypeResultLoc{rootType};
if (isReturn) {
forwardToResult(source);
funcInfos[index].tailCalleeTypes.push_back(rootType);
} else if (optimizeReferencedFuncs) {
getValueFromLocation(curr, source);
}
}
}
void visitCallIndirect(CallIndirect* curr) {
handleIndirectCall(curr, curr->heapType, curr->isReturn);
}
void visitCallRef(CallRef* curr) {
auto targetType = curr->target->type;
if (targetType.isSignature()) {
handleIndirectCall(curr, targetType.getHeapType(), curr->isReturn);
}
}
};
void DAE2::analyzeModule() {
// Initialize the function infos. (The type infos are initialized
// on-demand instead.)
funcInfos = std::vector<FunctionInfo>(wasm->functions.size());
for (Index i = 0; i < funcInfos.size(); ++i) {
auto numParams = wasm->functions[i]->getNumParams();
funcInfos[i].paramUsages.resize(numParams, used.getBottom());
funcInfos[i].resultUsage = used.getBottom();
funcInfos[i].paramSources.resize(numParams);
}
// Analyze functions to find forwarded and used parameters as well as
// function references and other relevant information.
GraphBuilder builder(used, funcIndices, funcInfos, optimizeReferencedFuncs);
builder.run(getPassRunner(), wasm);
// Find additional function references at the module level.
builder.walkModuleCode(wasm);
// Update the locations for which we observed direct usage.
for (Index i = 0; i < wasm->functions.size(); ++i) {
auto& info = funcInfos[i];
for (auto loc : info.usedLocations) {
if (auto* l = std::get_if<FuncResultLoc>(&loc)) {
markResultsUsed(*l);
} else if (auto* l = std::get_if<TypeResultLoc>(&loc)) {
markResultsUsed(*l);
} else {
// Function parameter uses were already handled in parallel. It is
// impossible to directly use a type parameter since they are used only
// transitively through function parameters.
WASM_UNREACHABLE("unexpected location");
}
}
}
// Model imported and exported functions as referenced so that marking the
// parameters or results of their types as used will prevent optimizations of
// the functions themselves.
for (Index i = 0; i < wasm->functions.size(); ++i) {
if (wasm->functions[i]->imported()) {
funcInfos[i].referenced = true;
}
}
for (auto& export_ : wasm->exports) {
if (export_->kind == ExternalKind::Function) {
auto i = funcIndices.at(*export_->getInternalName());
funcInfos[i].referenced = true;
}
}
// Functions called with call.without.effects cannot yet be optimized. Mark
// their parameters and results as used.
for (Index i = 0; i < wasm->functions.size(); ++i) {
if (funcInfos[i].usedInIntrinsic) {
markParamsUsed(i);
markResultsUsed(i);
}
}
// JS-called functions will be called externally, so we cannot optimize out
// their parameters or results.
// TODO: Consider optimizing out a suffix of their parameters.
for (auto name : Intrinsics(*wasm).getJSCalledFunctions()) {
markParamsUsed(name);
markResultsUsed(name);
}
// If we're not optimizing referenced functions, mark all their parameters
// and results as used.
if (!optimizeReferencedFuncs) {
for (Index i = 0; i < wasm->functions.size(); ++i) {
if (funcInfos[i].referenced) {
markParamsUsed(i);
markResultsUsed(i);
}
}
}
// Additionally mark parameters of referenced functions with public types (or
// private subtypes of public types) as used because we cannot rewrite their
// types. Similarly, we do not rewrite tag types or function types used in
// continuations, so any referenced function whose type is in the same tree as
// a tag type or continuation function type will have its parameters marked as
// used.
//
// TODO: Consider analyzing whether we can rewrite the types of such
// referenced functions to new private types first. This would require
// analyzing whether they can escape the module.
//
// TODO: Analyze tags and remove their unused parameters.
std::unordered_set<HeapType> unrewritableRoots;
publicHeapTypes =
ModuleUtils::getPublicHeapTypes(*wasm, getPassOptions().worldMode);
for (auto type : publicHeapTypes) {
if (type.isSignature()) {
unrewritableRoots.insert(getRootType(type));
}
}
for (auto& tag : wasm->tags) {
unrewritableRoots.insert(getRootType(tag->type));
}
for (Index i = 0; i < wasm->functions.size(); ++i) {
for (auto type : funcInfos[i].contTypes) {
unrewritableRoots.insert(getRootType(type.getContinuation().type));
}
}
// The types of the call.without.effects imports are excluded from the set of
// public heap types, but until we can handle analyzing and updating them in
// this pass, we must treat them the same as any other imported function
// types.
for (auto& func : wasm->functions) {
if (Intrinsics(*wasm).isCallWithoutEffects(func.get())) {
unrewritableRoots.insert(getRootType(func->type.getHeapType()));
}
}
for (auto root : unrewritableRoots) {
markParamsUsed(root);
markResultsUsed(root);
}
}
void DAE2::prepareReverseGraph() {
// Compute the reverse graph used by the fixed point analysis from the
// forward graph we have built.
// Collect the referenced functions for each type tree.
for (Index i = 0; i < funcInfos.size(); ++i) {
funcInfos[i].paramSources.resize(funcInfos[i].paramUsages.size());
if (funcInfos[i].referenced) {
auto root = getRootType(wasm->functions[i]->type.getHeapType());
getTypeTreeInfo(root).referencedFuncs.push_back(i);
}
}
for (Index callerIndex = 0; callerIndex < funcInfos.size(); ++callerIndex) {
auto& callerInfo = funcInfos[callerIndex];
// Collect the source locations for direct callees.
for (auto& [callee, forwardedParams] : callerInfo.forwardedToDirectParams) {
auto& calleeInfo = funcInfos[funcIndices.at(callee)];
for (Index destParam = 0; destParam < forwardedParams.size();
++destParam) {
for (auto sourceLoc : forwardedParams[destParam]) {
calleeInfo.paramSources[destParam].push_back(sourceLoc);
}
}
}
// Collect the source locations for indirect callees.
for (auto& [calleeRootType, forwardedParams] :
callerInfo.forwardedToIndirectParams) {
assert(getRootType(calleeRootType) == calleeRootType);
auto& typeTreeInfo = getTypeTreeInfo(calleeRootType);
for (Index destParam = 0; destParam < forwardedParams.size();
++destParam) {
for (auto sourceLoc : forwardedParams[destParam]) {
typeTreeInfo.paramSources[destParam].push_back(sourceLoc);
}
}
}
// Collect the tail callers of each callee function and type tree.
Location callerResult = FuncResultLoc{callerIndex};
for (auto calleeIndex : callerInfo.tailCallees) {
funcInfos[calleeIndex].resultSources.push_back(callerResult);
}
for (auto calleeRootType : callerInfo.tailCalleeTypes) {
getTypeTreeInfo(calleeRootType).resultSources.push_back(callerResult);
}
}
}
template<typename F> void DAE2::forEachSuccessor(Location loc, F&& f) {
if (auto* l = std::get_if<TypeParamLoc>(&loc)) {
auto [rootType, paramIndex] = *l;
auto& typeTreeInfo = getTypeTreeInfo(rootType);
// Propagate usage back to locations forwarded from indirect callers.
for (auto source : typeTreeInfo.paramSources[paramIndex]) {
f(source);
}
// Propagate usage to referenced functions with types in the same type tree
// to ensure their types can all be updated uniformly.
for (auto funcIndex : typeTreeInfo.referencedFuncs) {
f(FuncParamLoc{funcIndex, paramIndex});
}
} else if (auto* l = std::get_if<TypeResultLoc>(&loc)) {
auto& typeTreeInfo = getTypeTreeInfo(*l);
// Propagate usage to referenced functions with types in the same type tree
// to ensure their types can all be updated uniformly.
for (auto funcIndex : typeTreeInfo.referencedFuncs) {
f(FuncResultLoc{funcIndex});
}
// Propagate to tail callers.
for (auto source : typeTreeInfo.resultSources) {
f(source);
}
} else if (auto* l = std::get_if<FuncParamLoc>(&loc)) {
auto [calleeIndex, calleeParamIndex] = *l;
auto& calleeInfo = funcInfos[calleeIndex];
// Propagate usage back to locations forwarded from direct callers.
for (auto source : calleeInfo.paramSources[calleeParamIndex]) {
f(source);
}
if (calleeInfo.referenced) {
// Propagate the use to the function type. It will be propagated from
// there to indirect callers and other functions of this type.
auto calleeType = wasm->functions[calleeIndex]->type.getHeapType();
f(TypeParamLoc{getRootType(calleeType), calleeParamIndex});
}
} else if (auto* l = std::get_if<FuncResultLoc>(&loc)) {
auto calleeIndex = *l;
auto& calleeInfo = funcInfos[calleeIndex];
// Propagate usage back to sources of this result, including tail callers.
for (auto source : calleeInfo.resultSources) {
f(source);
}
if (calleeInfo.referenced) {
// Propagate the use to the function type. It will be propagated from
// there to other functions of this type.
auto calleeType = wasm->functions[calleeIndex]->type.getHeapType();
f(TypeResultLoc{getRootType(calleeType)});
}
} else {
WASM_UNREACHABLE("unexpected location");
}
}
// Performs a smallest fixed-point analysis to propagate parameter usage
// information through the reverse call graph. If a parameter is used in a
// function, then any caller parameters that were forwarded to the parameter are
// also used. Cycles of forwarded arguments will not be marked used unless
// one of the arguments starts out as used or there is some source of usage
// outside the cycle.
void DAE2::computeFixedPoint() {
// List of destination locations (i.e. params and results, either of functions
// or root function types) from which we may need to propagate usage
// information. Initialized with all locations we have observed to be used in
// the IR.
// TODO: Consider propagating by connected components instead.
std::vector<Location> work;
for (Index i = 0; i < funcInfos.size(); ++i) {
for (Index j = 0; j < funcInfos[i].paramUsages.size(); ++j) {
if (funcInfos[i].paramUsages[j]) {
work.push_back(FuncParamLoc{i, j});
}
}
if (funcInfos[i].resultUsage) {
work.push_back(FuncResultLoc{i});
}
}
for (auto& [rootType, info] : typeTreeInfos) {
for (Index i = 0; i < info.paramUsages.size(); ++i) {
if (info.paramUsages[i]) {
work.push_back(TypeParamLoc{rootType, i});
}
}
if (info.resultUsage) {
work.push_back(TypeResultLoc{rootType});
}
}
while (!work.empty()) {
auto loc = work.back();
work.pop_back();
auto& e = elem(loc);
assert(e && "unexpected unused location");
forEachSuccessor(loc, [&](Location succ) {
if (used.join(elem(succ), e)) {
work.push_back(succ);
}
});
}
}
// Updates function signatures throughout the module. Ensures that all functions
// within the same subtyping tree have the same parameters removed, maintaining
// the validity of the subtyping hierarchy.
struct DAETypeUpdater : GlobalTypeRewriter {
DAE2& parent;
DAETypeUpdater(DAE2& parent)
: GlobalTypeRewriter(*parent.wasm, parent.getPassOptions().worldMode),
parent(parent) {}
void modifySignature(HeapType oldType, Signature& sig) override {
// All signature types in a type tree will have the same parameters removed
// to keep subtyping valid. Look up which parameters to keep by the root
// type in the tree.
auto& info = parent.getTypeTreeInfo(getRootType(oldType));
auto& usages = info.paramUsages;
bool hasRemoved = std::any_of(
usages.begin(), usages.end(), [&](auto& use) { return !use; });
if (hasRemoved) {
std::vector<Type> keptParams;
keptParams.reserve(usages.size());
for (Index i = 0; i < usages.size(); ++i) {
if (usages[i]) {
keptParams.push_back(sig.params[i]);
}
}
sig.params = getTempTupleType(std::move(keptParams));
}
if (!info.resultUsage) {
sig.results = Type::none;
}
}
// Return the sorted list of old types (used for deterministic ordering) and
// the unordered map from old to new types.
std::pair<std::vector<HeapType>, TypeMap> rebuildTypes() {
auto types = getSortedTypes(getPrivatePredecessors());
auto map = GlobalTypeRewriter::rebuildTypes(types);
return {std::move(types), std::move(map)};
}
};
// Optimize functions in parallel using the DAE2 analysis results.
struct Optimizer
: public WalkerPass<
ExpressionStackWalker<Optimizer, UnifiedExpressionVisitor<Optimizer>>> {
using Super = WalkerPass<
ExpressionStackWalker<Optimizer, UnifiedExpressionVisitor<Optimizer>>>;
bool isFunctionParallel() override { return true; }
// We handle non-nullable local fixups in the pass itself. If we ran the
// fixups after the pass, they could get confused and produce invalid code
// because this pass updates local indices but does not always update function
// types to match. Function types are updated after this pass runs.
bool requiresNonNullableLocalFixups() override { return false; }
const DAE2& parent;
// The info for the function we are running on.
const FunctionInfo* funcInfo = nullptr;
// Map old local indices to new local indices for the function we are
// currently optimizing. Kept parameters and locals may need to have their
// indices shifted down to account for removed parameters, and removed
// parameters will need to be mapped to their new replacement locals.
std::vector<Index> newIndices;
Morty Proxy This is a proxified and sanitized view of the page, visit original site.