-
Notifications
You must be signed in to change notification settings - Fork 851
Expand file tree
/
Copy pathHeap2Local.cpp
More file actions
1696 lines (1513 loc) · 65.3 KB
/
Heap2Local.cpp
File metadata and controls
1696 lines (1513 loc) · 65.3 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
/*
* Copyright 2021 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.
*/
//
// Find heap allocations that never escape the current function, and lower the
// allocation's data into locals. That is, avoid allocating a GC object, and
// instead use one local for each of its fields.
//
// To get a sense for what this pass does, here is an example to clarify. First,
// in pseudocode:
//
// ref = new Int(42)
// do {
// ref.set(ref.get() + 1)
// } while (import(ref.get())
//
// That is, we allocate an int on the heap and use it as a counter.
// Unnecessarily, as it could be a normal int on the stack.
//
// Wat:
//
// (module
// ;; A boxed integer: an entire struct just to hold an int.
// (type $boxed-int (struct (field (mut i32))))
//
// (import "env" "import" (func $import (param i32) (result i32)))
//
// (func $example
// (local $ref (ref null $boxed-int))
//
// ;; Allocate a boxed integer of 42 and save the reference to it.
// (local.set $ref
// (struct.new $boxed-int
// (i32.const 42)
// )
// )
//
// ;; Increment the integer in a loop, looking for some condition.
// (loop $loop
// (struct.set $boxed-int 0
// (local.get $ref)
// (i32.add
// (struct.get $boxed-int 0
// (local.get $ref)
// )
// (i32.const 1)
// )
// )
// (br_if $loop
// (call $import
// (struct.get $boxed-int 0
// (local.get $ref)
// )
// )
// )
// )
// )
// )
//
// Before this pass, the optimizer could do essentially nothing with this. Even
// with this pass, running -O1 has no effect, as the pass is only used in -O2+.
// However, running --heap2local -O1 leads to this:
//
// (func $0
// (local $0 i32)
// (local.set $0
// (i32.const 42)
// )
// (loop $loop
// (br_if $loop
// (call $import
// (local.tee $0
// (i32.add
// (local.get $0)
// (i32.const 1)
// )
// )
// )
// )
// )
// )
//
// All the GC heap operations have been removed, and we just have a plain int
// now, allowing a bunch of other opts to run.
//
// For us to replace an allocation with locals, we need to prove two things:
//
// * It must not escape from the function. If it escapes, we must pass out a
// reference anyhow. (In theory we could do a whole-program transformation
// to replace the reference with parameters in some cases, but inlining can
// hopefully let us optimize most cases.)
// * It must be used "exclusively", without overlap. That is, we cannot
// handle the case where a local.get might return our allocation, but might
// also get some other value. We also cannot handle a select where one arm
// is our allocation and another is something else. If the use is exclusive
// then we have a simple guarantee of being able to replace the heap
// allocation with the locals.
//
// Non-exclusive uses are optimizable too, but they require more work and add
// overhead. For example, here is a non-exclusive use:
//
// var x;
// if (..) {
// x = new Something(); // the allocation we want to optimize
// } else {
// x = something_else;
// }
// // 'x' here is not used exclusively by our allocation
// return x.field0;
//
// To optimize x.field0, we'd need to check if it contains our allocation or
// not, perhaps marking a boolean as true when it is, then doing an if on that
// local, etc.:
//
// var x_is_our_alloc; // whether x is our allocation
// var x; // keep x around for when it is not our allocation
// var x_field0; // the value of field0 on x, when x is our allocation
// if (..) {
// x_field0 = ..default value for the type..
// x_is_our_alloc = true;
// } else {
// x = something_else;
// x_is_our_alloc = false;
// }
// return x_is_our_alloc ? x_field0 : x.field0;
//
// (node splitting/code duplication is another possible approach). On the other
// hand, if the allocation is used exclusively in all places (the if-else above
// does not have an else any more) then we can do this:
//
// var x_field0; // the value of field0 on x
// if (..) {
// x_field0 = ..default value for the type..
// }
// return x_field0;
//
// This optimization focuses on such cases.
//
#include "ir/abstract.h"
#include "ir/bits.h"
#include "ir/branch-utils.h"
#include "ir/eh-utils.h"
#include "ir/local-graph.h"
#include "ir/parents.h"
#include "ir/properties.h"
#include "ir/utils.h"
#include "pass.h"
#include "support/unique_deferring_queue.h"
#include "wasm-builder.h"
#include "wasm-type.h"
#include "wasm.h"
namespace wasm {
namespace {
// Interactions between a child and a parent, with regard to the behavior of the
// allocation.
enum class ParentChildInteraction : int8_t {
// The parent lets the child escape. E.g. the parent is a call.
Escapes,
// The parent fully consumes the child in a safe, non-escaping way, and
// after consuming it nothing remains to flow further through the parent.
// E.g. the parent is a struct.get, which reads from the allocated heap
// value and does nothing more with the reference.
FullyConsumes,
// The parent flows the child out, that is, the child is the single value
// that can flow out from the parent. E.g. the parent is a block with no
// branches and the child is the final value that is returned.
Flows,
// The parent does not consume the child completely, so the child's value
// can be used through it. However the child does not flow cleanly through.
// E.g. the parent is a block with branches, and the value on them may be
// returned from the block and not only the child. This means the allocation
// is not used in an exclusive way, and we cannot optimize it.
Mixes,
// No interaction (not relevant to the analysis).
None,
};
// When we insert scratch locals, we sometimes need to record the flow between
// their set and subsequent get.
using ScratchInfo = std::unordered_map<LocalSet*, LocalGet*>;
// Core analysis that provides an escapes() method to check if an allocation
// escapes in a way that prevents optimizing it away as described above. It also
// stashes information about the relevant expressions as it goes, which helps
// optimization later (|reached|).
struct EscapeAnalyzer {
// To find what escapes, we need to follow where values flow, both up to
// parents, and via branches, and through locals.
//
// We use a lazy graph here because we only need this for reference locals,
// and even among them, only ones we see an allocation is stored to. The
// LocalGraph is is augmented by ScratchInfo, since the LocalGraph does not
// know about scratch locals we add. We currently only record scratch locals
// that might possibly have another optimized allocation flowing through them.
// If it's not possible for another optimized allocation to flow through the
// scratch local, then we will never look at it again after creating it and do
// not need to record it here.
const LazyLocalGraph& localGraph;
ScratchInfo& scratchInfo;
Parents& parents;
const BranchUtils::BranchTargets& branchTargets;
const PassOptions& passOptions;
Module& wasm;
EscapeAnalyzer(const LazyLocalGraph& localGraph,
ScratchInfo& scratchInfo,
Parents& parents,
const BranchUtils::BranchTargets& branchTargets,
const PassOptions& passOptions,
Module& wasm)
: localGraph(localGraph), scratchInfo(scratchInfo), parents(parents),
branchTargets(branchTargets), passOptions(passOptions), wasm(wasm) {}
// We must track all the local.sets that write the allocation, to verify
// exclusivity.
std::unordered_set<LocalSet*> sets;
// A map of every expression we reached during the flow analysis (which is
// exactly all the places where our allocation is used) to the interaction of
// the allocation there. If we optimize, anything in this map will be fixed up
// at the end, and how we fix it up may depend on the interaction,
// specifically, it can matter if the allocations flows out of here (Flows,
// which is the case for e.g. a Block that we flow through) or if it is fully
// consumed (FullyConsumes, e.g. for a struct.get). We do not store irrelevant
// things here (that is, anything not in the map has the interaction |None|,
// implicitly).
std::unordered_map<Expression*, ParentChildInteraction> reachedInteractions;
// Analyze an allocation to see if it escapes or not.
bool escapes(Expression* allocation) {
// A queue of flows from children to parents. When something is in the queue
// here then it assumed that it is ok for the allocation to be at the child
// (that is, we have already checked the child before placing it in the
// queue), and we need to check if it is ok to be at the parent, and to flow
// from the child to the parent. We will analyze that (see
// ParentChildInteraction, above) and continue accordingly.
using ChildAndParent = std::pair<Expression*, Expression*>;
UniqueNonrepeatingDeferredQueue<ChildAndParent> flows;
// Start the flow from the allocation itself to its parent.
flows.push({allocation, parents.getParent(allocation)});
// Keep flowing while we can.
while (!flows.empty()) {
auto flow = flows.pop();
auto* child = flow.first;
auto* parent = flow.second;
auto interaction = getParentChildInteraction(allocation, parent, child);
if (interaction == ParentChildInteraction::Escapes ||
interaction == ParentChildInteraction::Mixes) {
// If the parent may let us escape, or the parent mixes other values
// up with us, give up.
return true;
}
// The parent either fully consumes us, or flows us onwards; either way,
// we can proceed here, hopefully.
assert(interaction == ParentChildInteraction::FullyConsumes ||
interaction == ParentChildInteraction::Flows);
// We can proceed, as the parent interacts with us properly, and we are
// the only allocation to get here.
if (interaction == ParentChildInteraction::Flows) {
// The value flows through the parent; we need to look further at the
// grandparent.
flows.push({parent, parents.getParent(parent)});
}
if (auto* set = parent->dynCast<LocalSet>()) {
// We must also look at how the value flows from those gets. Check the
// scratchInfo first because it contains sets that localGraph doesn't
// know about.
if (auto it = scratchInfo.find(set); it != scratchInfo.end()) {
auto* get = it->second;
flows.push({get, parents.getParent(get)});
} else {
// This is one of the sets we are written to, and so we must check for
// exclusive use of our allocation by all the gets that read the
// value. Note the set, and we will check the gets at the end once we
// know all of our sets. (For scratch locals above, we know all the
// sets are already accounted for.)
sets.insert(set);
for (auto* get : localGraph.getSetInfluences(set)) {
flows.push({get, parents.getParent(get)});
}
}
}
// If the parent may send us on a branch, we will need to look at the flow
// to the branch target(s).
for (auto name : branchesSentByParent(child, parent)) {
flows.push({child, branchTargets.getTarget(name)});
}
// If we got to here, then we can continue to hope that we can optimize
// this allocation. Mark the parent and child as reached by it, and
// continue. The child flows the value to the parent, and the parent's
// behavior was computed before.
reachedInteractions[child] = ParentChildInteraction::Flows;
reachedInteractions[parent] = interaction;
}
// We finished the loop over the flows. Do the final checks.
if (!getsAreExclusiveToSets()) {
return true;
}
// Nothing escapes, hurray!
return false;
}
ParentChildInteraction getParentChildInteraction(Expression* allocation,
Expression* parent,
Expression* child) const {
// If there is no parent then we are the body of the function, and that
// means we escape by flowing to the caller.
if (!parent) {
return ParentChildInteraction::Escapes;
}
struct Checker : public Visitor<Checker> {
Expression* allocation;
Expression* child;
// Assume escaping (or some other problem we cannot analyze) unless we are
// certain otherwise.
bool escapes = true;
// Assume we do not fully consume the value unless we are certain
// otherwise. If this is set to true, then we do not need to check any
// further. If it remains false, then we will analyze the value that
// falls through later to check for mixing.
//
// Note that this does not need to be set for expressions if their type
// proves that the value does not continue onwards (e.g. if their type is
// none, or not a reference type), but for clarity some do still mark this
// field as true when it is clearly so.
bool fullyConsumes = false;
// General operations
void visitBlock(Block* curr) {
escapes = false;
// We do not mark fullyConsumes as the value may continue through this
// and other control flow structures.
}
// Note that If is not supported here, because for our value to flow
// through it there must be an if-else, and that means there is no single
// value falling through anyhow.
void visitLoop(Loop* curr) { escapes = false; }
void visitDrop(Drop* curr) {
escapes = false;
fullyConsumes = true;
}
void visitBreak(Break* curr) { escapes = false; }
void visitSwitch(Switch* curr) { escapes = false; }
// Local operations. Locals by themselves do not escape; the analysis
// tracks where locals are used.
void visitLocalGet(LocalGet* curr) { escapes = false; }
void visitLocalSet(LocalSet* curr) { escapes = false; }
// Reference operations. TODO add more
void visitRefIsNull(RefIsNull* curr) {
// The reference is compared to null, but nothing more.
escapes = false;
fullyConsumes = true;
}
void visitRefEq(RefEq* curr) {
// The reference is compared for identity, but nothing more.
escapes = false;
fullyConsumes = true;
}
void visitRefAs(RefAs* curr) {
// TODO General OptimizeInstructions integration, that is, since we know
// that our allocation is what flows into this RefAs, we can
// know the exact outcome of the operation.
if (curr->op == RefAsNonNull) {
// As it is our allocation that flows through here, we know it is not
// null (so there is no trap), and we can continue to (hopefully)
// optimize this allocation.
escapes = false;
}
}
void visitRefTest(RefTest* curr) {
escapes = false;
fullyConsumes = true;
}
void visitRefCast(RefCast* curr) {
// Whether the cast succeeds or fails, it does not escape.
escapes = false;
if (curr->ref == child) {
// If the cast fails then the allocation is fully consumed and does
// not flow any further (instead, we trap).
if (!Type::isSubType(allocation->type, curr->type)) {
fullyConsumes = true;
}
} else {
// Either the child is the descriptor, in which case we consume it, or
// we have already optimized this ref.cast_desc_eq for an allocation
// that flowed through as its `ref`. In the latter case the current
// child must have originally been the descriptor, so we can still say
// it's fully consumed, but we cannot assert that curr->desc == child.
fullyConsumes = true;
}
}
void visitRefGetDesc(RefGetDesc* curr) {
escapes = false;
fullyConsumes = true;
}
// GC operations.
void visitStructSet(StructSet* curr) {
// The reference does not escape (but the value is stored to memory and
// therefore might).
if (curr->ref == child) {
escapes = false;
fullyConsumes = true;
}
}
void visitStructGet(StructGet* curr) {
escapes = false;
fullyConsumes = true;
}
void visitStructRMW(StructRMW* curr) {
if (curr->ref == child) {
escapes = false;
fullyConsumes = true;
}
}
void visitStructCmpxchg(StructCmpxchg* curr) {
if (curr->ref == child || curr->expected == child) {
escapes = false;
fullyConsumes = true;
}
}
void visitArraySet(ArraySet* curr) {
// Arrays flowing into array operations on nonconstant indexes do not
// escape in the normal sense, but they do escape from our being able to
// analyze them, so stop as soon as we see one.
if (child == curr->ref && curr->index->is<Const>()) {
escapes = false;
fullyConsumes = true;
}
}
void visitArrayGet(ArrayGet* curr) {
if (child == curr->ref && curr->index->is<Const>()) {
escapes = false;
fullyConsumes = true;
}
}
void visitArrayRMW(ArrayRMW* curr) {
if (child == curr->ref && curr->index->is<Const>()) {
escapes = false;
fullyConsumes = true;
}
}
void visitArrayCmpxchg(ArrayCmpxchg* curr) {
// Allocations flowing into `expected` are fully consumed and
// optimizable even if the index is not constant.
if (child == curr->expected ||
(child == curr->ref && curr->index->is<Const>())) {
escapes = false;
fullyConsumes = true;
}
}
// TODO other GC operations
} checker;
checker.allocation = allocation;
checker.child = child;
checker.visit(parent);
if (checker.escapes) {
return ParentChildInteraction::Escapes;
}
// If the parent returns a type that is not a reference, then by definition
// it fully consumes the value as it does not flow our allocation onward.
if (checker.fullyConsumes || !parent->type.isRef()) {
return ParentChildInteraction::FullyConsumes;
}
// Finally, check for mixing. If the child is the immediate fallthrough
// of the parent then no other values can be mixed in.
if (Properties::getImmediateFallthrough(parent, passOptions, wasm) ==
child) {
return ParentChildInteraction::Flows;
}
// Likewise, if the child branches to the parent, and it is the sole branch,
// with no other value exiting the block (in particular, no final value at
// the end that flows out), then there is no mixing.
auto branches =
branchTargets.getBranches(BranchUtils::getDefinedName(parent));
if (branches.size() == 1 &&
BranchUtils::getSentValue(*branches.begin()) == child) {
// TODO: support more types of branch targets.
if (auto* parentAsBlock = parent->dynCast<Block>()) {
if (parentAsBlock->list.back()->type == Type::unreachable) {
return ParentChildInteraction::Flows;
}
}
}
// TODO: Also check for safe merges where our allocation is in all places,
// like two if or select arms, or branches.
return ParentChildInteraction::Mixes;
}
const BranchUtils::NameSet branchesSentByParent(Expression* child,
Expression* parent) {
BranchUtils::NameSet names;
BranchUtils::operateOnScopeNameUsesAndSentValues(
parent, [&](Name name, Expression* value) {
if (value == child) {
names.insert(name);
}
});
return names;
}
// Verify exclusivity of all the gets for a bunch of sets. That is, assuming
// the sets are exclusive (they all write exactly our allocation, and nothing
// else), we need to check whether all the gets that read that value cannot
// read anything else (which would be the case if another set writes to that
// local, in the right live range).
bool getsAreExclusiveToSets() {
// Find all the relevant gets (which may overlap between the sets).
std::unordered_set<LocalGet*> gets;
for (auto* set : sets) {
for (auto* get : localGraph.getSetInfluences(set)) {
gets.insert(get);
}
}
// Check that the gets can only read from the specific known sets.
for (auto* get : gets) {
for (auto* set : localGraph.getSets(get)) {
if (!sets.contains(set)) {
return false;
}
}
}
return true;
}
// Helper function for Struct2Local and Array2Struct. Given an old expression
// that is being replaced by a new one, add the proper interaction for the
// replacement.
void applyOldInteractionToReplacement(Expression* old, Expression* rep) {
// We can only replace something relevant that we found in the analysis.
// (Not only would anything else be invalid to process, but also we wouldn't
// know what interaction to give the replacement.)
assert(reachedInteractions.contains(old));
// The replacement should have the same interaction as the thing it
// replaces, since it is a drop-in replacement for it. The one exception is
// when we replace with something unreachable, which is the result of us
// figuring out that some code will trap at runtime. In that case, we've
// made the code unreachable and the allocation does not interact with that
// code at all.
if (rep->type != Type::unreachable) {
reachedInteractions[rep] = reachedInteractions[old];
}
}
// Get the interaction of an expression.
ParentChildInteraction getInteraction(Expression* curr) {
auto iter = reachedInteractions.find(curr);
if (iter == reachedInteractions.end()) {
// This is not interacted with.
return ParentChildInteraction::None;
}
return iter->second;
}
};
// An optimizer that handles the rewriting to turn a struct allocation into
// locals. We run this after proving that allocation does not escape.
//
// TODO: Doing a single rewrite walk at the end (for all structs) would be more
// efficient, but it would need to be more complex.
struct Struct2Local : PostWalker<Struct2Local> {
StructNew* allocation;
// The analyzer is not |const| because we update
// |analyzer.reachedInteractions| as we go (see replaceCurrent, below).
EscapeAnalyzer& analyzer;
Function* func;
Module& wasm;
Builder builder;
const FieldList& fields;
// The descriptor can arrive as nullable, but we trap if it is null, so there
// is only something to store if it is non-nullable, and we store it that way.
Type descType;
Struct2Local(StructNew* allocation,
EscapeAnalyzer& analyzer,
Function* func,
Module& wasm)
: allocation(allocation), analyzer(analyzer), func(func), wasm(wasm),
builder(wasm), fields(allocation->type.getHeapType().getStruct().fields) {
// Allocate locals to store the allocation's fields and descriptor in.
for (auto field : fields) {
localIndexes.push_back(builder.addVar(func, field.type));
}
if (allocation->desc) {
descType = allocation->desc->type.with(NonNullable);
localIndexes.push_back(builder.addVar(func, descType));
}
// Replace the things we need to using the visit* methods.
walk(func->body);
if (refinalize) {
ReFinalize().walkFunctionInModule(func, &wasm);
}
}
// Maps indexes in the struct to the local index that will replace them.
std::vector<Index> localIndexes;
// In rare cases we may need to refinalize, see below.
bool refinalize = false;
Expression* replaceCurrent(Expression* expression) {
analyzer.applyOldInteractionToReplacement(getCurrent(), expression);
PostWalker<Struct2Local>::replaceCurrent(expression);
return expression;
}
// Rewrite the code in visit* methods. The general approach taken is to
// replace the allocation with a null reference (which may require changing
// types in some places, like making a block return value nullable), and to
// remove all uses of it as much as possible, using the information we have
// (for example, when our allocation reaches a RefAsNonNull we can simply
// remove that operation as we know it would not throw). Some things are
// left to other passes, like getting rid of dropped code without side
// effects.
// Adjust the type that flows through an expression, updating that type as
// necessary.
void adjustTypeFlowingThrough(Expression* curr) {
if (analyzer.getInteraction(curr) != ParentChildInteraction::Flows) {
return;
}
// Our allocation passes through this expr. We must turn its type into a
// nullable one, because we will remove things like RefAsNonNull of it,
// which means we may no longer have a non-nullable value as our input,
// and we could fail to validate. It is safe to make this change in terms
// of our parent, since we know very specifically that only safe things
// will end up using our value, like a StructGet or a Drop, which do not
// care about non-nullability.
assert(curr->type.isRef());
curr->type = Type(curr->type.getHeapType(), Nullable);
}
void visitBlock(Block* curr) { adjustTypeFlowingThrough(curr); }
void visitLoop(Loop* curr) { adjustTypeFlowingThrough(curr); }
void visitLocalSet(LocalSet* curr) {
if (analyzer.getInteraction(curr) == ParentChildInteraction::None) {
return;
}
// We don't need any sets of the reference to any of the locals it
// originally was written to.
if (curr->isTee()) {
replaceCurrent(curr->value);
} else {
replaceCurrent(builder.makeDrop(curr->value));
}
}
void visitLocalGet(LocalGet* curr) {
if (analyzer.getInteraction(curr) == ParentChildInteraction::None) {
return;
}
// Uses of this get will drop it, so the value does not matter. Replace it
// with something else, which avoids issues with non-nullability (when
// non-nullable locals are enabled), which could happen like this:
//
// (local $x (ref $foo))
// (local.set $x ..)
// (.. (local.get $x))
//
// If we remove the set but not the get then the get would appear to read
// the default value of a non-nullable local, which is not allowed.
//
// For simplicity, replace the get with a null. We anyhow have null types
// in the places where our allocation was earlier, see notes on
// visitBlock, and so using a null here adds no extra complexity.
replaceCurrent(builder.makeRefNull(curr->type.getHeapType()));
}
void visitBreak(Break* curr) {
if (analyzer.getInteraction(curr) == ParentChildInteraction::None) {
return;
}
// Breaks that our allocation flows through may change type, as we now
// have a nullable type there.
curr->finalize();
}
void visitStructNew(StructNew* curr) {
if (curr != allocation) {
return;
}
// First, assign the initial values to the new locals.
std::vector<Expression*> contents;
// We might be in a loop, so the locals representing the struct fields might
// already have values. Furthermore, the computation of the new field values
// might depend on the old field values. If we naively assign the new values
// to the locals as they are computed, the computation of a later field may
// use the new value of an earlier field where it should have used the old
// value of the earlier field. To avoid this problem, we store all the
// nontrivial new values in temp locals, and only once they have fully been
// computed do we copy them into the locals representing the fields.
std::vector<Index> tempIndexes;
Index numTemps =
(curr->isWithDefault() ? 0 : fields.size()) + bool(curr->desc);
tempIndexes.reserve(numTemps);
// Create the temp variables.
if (!curr->isWithDefault()) {
for (auto field : fields) {
tempIndexes.push_back(builder.addVar(func, field.type));
}
}
if (curr->desc) {
tempIndexes.push_back(builder.addVar(func, descType));
}
// Store the initial values into the temp locals.
if (!curr->isWithDefault()) {
for (Index i = 0; i < fields.size(); i++) {
contents.push_back(
builder.makeLocalSet(tempIndexes[i], curr->operands[i]));
}
}
if (curr->desc) {
// Preserve the trapping on null descriptors by inserting a
// ref.as_non_null.
Expression* desc = curr->desc;
if (curr->desc->type.isNullable()) {
desc = builder.makeRefAs(RefAsNonNull, desc);
}
contents.push_back(builder.makeLocalSet(tempIndexes[numTemps - 1], desc));
}
// Store the values into the locals representing the fields.
for (Index i = 0; i < fields.size(); ++i) {
auto* val =
curr->isWithDefault()
? builder.makeConstantExpression(Literal::makeZero(fields[i].type))
: builder.makeLocalGet(tempIndexes[i], fields[i].type);
contents.push_back(builder.makeLocalSet(localIndexes[i], val));
}
if (curr->desc) {
auto* val = builder.makeLocalGet(tempIndexes[numTemps - 1], descType);
contents.push_back(
builder.makeLocalSet(localIndexes[fields.size()], val));
}
// Replace the allocation with a null reference. This changes the type
// from non-nullable to nullable, but as we optimize away the code that
// the allocation reaches, we will handle that.
contents.push_back(builder.makeRefNull(allocation->type.getHeapType()));
replaceCurrent(builder.makeBlock(contents));
}
void visitRefIsNull(RefIsNull* curr) {
if (analyzer.getInteraction(curr) == ParentChildInteraction::None) {
return;
}
if (curr->type == Type::unreachable) {
// The result does not matter. Leave things as they are (and let DCE
// handle it).
return;
}
// The result must be 0, since the allocation is not null. Drop the RefIs
// and append that.
replaceCurrent(builder.makeSequence(
builder.makeDrop(curr), builder.makeConst(Literal(int32_t(0)))));
}
void visitRefEq(RefEq* curr) {
if (analyzer.getInteraction(curr) == ParentChildInteraction::None) {
return;
}
if (curr->type == Type::unreachable) {
// The result does not matter. Leave things as they are (and let DCE
// handle it).
return;
}
// If our reference is compared to itself, the result is 1. If it is
// compared to something else, the result must be 0, as our reference does
// not escape to any other place.
int32_t result =
analyzer.getInteraction(curr->left) == ParentChildInteraction::Flows &&
analyzer.getInteraction(curr->right) == ParentChildInteraction::Flows;
replaceCurrent(builder.makeBlock({builder.makeDrop(curr->left),
builder.makeDrop(curr->right),
builder.makeConst(Literal(result))}));
}
void visitRefAs(RefAs* curr) {
if (analyzer.getInteraction(curr) == ParentChildInteraction::None) {
return;
}
// It is safe to optimize out this RefAsNonNull, since we proved it
// contains our allocation, and so cannot trap.
assert(curr->op == RefAsNonNull);
replaceCurrent(curr->value);
}
void visitRefTest(RefTest* curr) {
if (analyzer.getInteraction(curr) == ParentChildInteraction::None) {
return;
}
// This test operates on the allocation, which means we can compute whether
// it will succeed statically. We do not even need
// GCTypeUtils::evaluateCastCheck because we know the allocation's type
// precisely (it cannot be a strict subtype of the type - it is the type).
int32_t result = Type::isSubType(allocation->type, curr->castType);
// Remove the RefTest and leave only its reference child. If we kept it,
// we'd need to refinalize (as the input to the test changes, since the
// reference becomes a null, which has a different type).
replaceCurrent(builder.makeSequence(builder.makeDrop(curr->ref),
builder.makeConst(Literal(result))));
}
void visitRefCast(RefCast* curr) {
if (analyzer.getInteraction(curr) == ParentChildInteraction::None) {
return;
}
if (curr->desc) {
auto descTrap = [&]() {
replaceCurrent(builder.blockify(builder.makeDrop(curr->ref),
builder.makeDrop(curr->desc),
builder.makeUnreachable()));
};
// If we are doing a ref.cast_desc_eq of the optimized allocation, but the
// allocation does not have a descriptor, then we know the cast must fail.
// We also know the cast must fail (except for nulls it might let through)
// if the optimized allocation flows in as the descriptor, since it cannot
// possibly have been used in the allocation of the cast value without
// having been considered to escape.
bool allocIsCastRef =
analyzer.getInteraction(curr->ref) == ParentChildInteraction::Flows;
bool allocIsCastDescEq =
analyzer.getInteraction(curr->desc) == ParentChildInteraction::Flows;
if (!allocation->desc || allocIsCastDescEq) {
// It would seem convenient to use ChildLocalizer here, but we cannot.
// ChildLocalizer would create a local.set for a desc operand with
// side effects, but that local.set would not be reflected in the parent
// map, so it would not be updated if the allocation flowing through
// that desc operand were later optimized.
if (allocIsCastDescEq && !allocIsCastRef && curr->type.isNullable()) {
// There might be a null value to let through. Reuse curr as a cast to
// null. Use a scratch local to move the reference value past the desc
// value.
Index scratch = builder.addVar(func, curr->ref->type);
replaceCurrent(
builder.blockify(builder.makeLocalSet(scratch, curr->ref),
builder.makeDrop(curr->desc),
curr));
curr->desc = nullptr;
curr->type = curr->type.with(curr->type.getHeapType().getBottom());
curr->ref = builder.makeLocalGet(scratch, curr->ref->type);
} else {
// Either the cast does not allow nulls or we know the value isn't
// null anyway, so the cast certainly fails.
descTrap();
}
} else if (allocIsCastRef) {
if (!Type::isSubType(allocation->type, curr->type)) {
// The cast fails, so it must trap. We mark such failing casts as
// fully consuming their inputs, so we cannot just emit the explicit
// descriptor equality check below because it would appear to be able
// to propagate the optimized allocation on to the parent (as a null
// value, which might not validate).
descTrap();
} else {
// The cast succeeds iff the optimized allocation's descriptor is the
// same as the given descriptor and traps otherwise.
replaceCurrent(builder.blockify(
builder.makeDrop(curr->ref),
builder.makeIf(
builder.makeRefEq(
curr->desc,
builder.makeLocalGet(localIndexes[fields.size()], descType)),
builder.makeRefNull(allocation->type.getHeapType()),
builder.makeUnreachable())));
}
} else {
// The allocation is neither the ref nor the descriptor inputs to this
// cast. This can happen if a previous operation led to the StructNew
// being dropped, as a result if it being used in unreachable code (it
// ends up happening because some of the initial analysis, like Parents,
// is stale; we could also recompute Parents after each Struct2Local,
// but it is simple enough to handle this with a trap).
assert(curr->type == Type::unreachable);
descTrap();
}
} else {
// We know this RefCast receives our allocation, so we can see whether it
// succeeds or fails.
if (Type::isSubType(allocation->type, curr->type)) {
// The cast succeeds, so it is a no-op, and we can skip it, since after
// we remove the allocation it will not even be needed for validation.
replaceCurrent(curr->ref);
} else {
// The cast fails, so this must trap.
replaceCurrent(builder.makeSequence(builder.makeDrop(curr->ref),
builder.makeUnreachable()));
}
}
// In any case, we need to refinalize here (we either added an unreachable,
// or we replaced a cast with the value being cast, which may have a less-
// refined type - it will not be used after we remove the allocation, but we
// must still fix that up for validation).
refinalize = true;
}
void visitRefGetDesc(RefGetDesc* curr) {
if (analyzer.getInteraction(curr) == ParentChildInteraction::None) {
return;
}
if (curr->type == Type::unreachable) {
// We must not modify unreachable code here, as we will replace it with a
// local.get, which has a concrete type (another option could be to run
// DCE and not only ReFinalize - DCE will propagate an unreachable out of
// a concrete block, like we emit here - but we can just ignore such
// code).
return;
}
auto descIndex = localIndexes[fields.size()];
Expression* value = builder.makeLocalGet(descIndex, descType);
replaceCurrent(builder.blockify(builder.makeDrop(curr->ref), value));
// After removing the ref.get_desc, a null may be falling through,
// requiring refinalization to update parents.
refinalize = true;
}
void visitStructSet(StructSet* curr) {
if (analyzer.getInteraction(curr) == ParentChildInteraction::None) {
return;
}