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
|
/*
* Copyright 2016 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.
*/
//
// Removes dead, i.e. unreachable, code.
//
// We keep a record of when control flow is reachable. When it isn't, we
// kill (turn into unreachable). We then fold away entire unreachable
// expressions.
//
// When dead code causes an operation to not happen, like a store, a call
// or an add, we replace with a block with a list of what does happen.
// That isn't necessarily smaller, but blocks are friendlier to other
// optimizations: blocks can be merged and eliminated, and they clearly
// have no side effects.
//
#include <wasm.h>
#include <pass.h>
#include <ast_utils.h>
namespace wasm {
struct DeadCodeElimination : public WalkerPass<PostWalker<DeadCodeElimination, Visitor<DeadCodeElimination>>> {
bool isFunctionParallel() override { return true; }
Pass* create() override { return new DeadCodeElimination; }
// whether the current code is actually reachable
bool reachable;
void doWalkFunction(Function* func) {
reachable = true;
walk(func->body);
}
std::set<Name> reachableBreaks;
void addBreak(Name name) {
assert(reachable);
reachableBreaks.insert(name);
}
bool isDead(Expression* curr) {
return curr && curr->is<Unreachable>();
}
// things that stop control flow
void visitBreak(Break* curr) {
if (isDead(curr->value)) {
// the condition is evaluated last, so if the value was unreachable, the whole thing is
replaceCurrent(curr->value);
return;
}
addBreak(curr->name);
if (!curr->condition) {
reachable = false;
}
}
void visitSwitch(Switch* curr) {
if (isDead(curr->value)) {
replaceCurrent(curr->value);
return;
}
for (auto target : curr->targets) {
addBreak(target);
}
addBreak(curr->default_);
reachable = false;
}
void visitReturn(Return* curr) {
if (isDead(curr->value)) {
replaceCurrent(curr->value);
return;
}
reachable = false;
}
void visitUnreachable(Unreachable* curr) {
reachable = false;
}
// we maintain a stack for blocks, as we visit each item, and the parameter is the index
std::vector<Index> blockStack; // index in current block
static void doPreBlock(DeadCodeElimination* self, Expression** currp) {
self->blockStack.push_back(0);
}
static void doAfterBlockElement(DeadCodeElimination* self, Expression** currp) {
auto* block = (*currp)->cast<Block>();
Index i = self->blockStack.back();
self->blockStack.back()++;
if (!self->reachable) {
// control flow ended in the middle of the block
// note that we still visit the rest, so if we already truncated, do not lengthen.
// note that it is ok that we visit the others even though the list was shortened;
// our arena vectors leave things as they are when shrinking.
if (block->list.size() > i + 1) {
block->list.resize(i + 1);
}
}
}
void visitBlock(Block* curr) {
blockStack.pop_back();
if (curr->name.is()) {
reachable = reachable || reachableBreaks.count(curr->name);
reachableBreaks.erase(curr->name);
}
if (curr->list.size() == 1 && isDead(curr->list[0])) {
replaceCurrent(curr->list[0]);
}
}
void visitLoop(Loop* curr) {
if (curr->in.is()) {
reachableBreaks.erase(curr->in);
}
if (curr->out.is()) {
reachable = reachable || reachableBreaks.count(curr->out);
reachableBreaks.erase(curr->out);
}
if (isDead(curr->body)) {
replaceCurrent(curr->body);
return;
}
}
// ifs need special handling
std::vector<bool> ifStack; // stack of reachable state, for forking and joining
static void doAfterIfCondition(DeadCodeElimination* self, Expression** currp) {
self->ifStack.push_back(self->reachable);
}
static void doAfterIfElseTrue(DeadCodeElimination* self, Expression** currp) {
assert((*currp)->cast<If>()->ifFalse);
bool reachableBefore = self->ifStack.back();
self->ifStack.pop_back();
self->ifStack.push_back(self->reachable);
self->reachable = reachableBefore;
}
void visitIf(If* curr) {
// the ifStack has the branch that joins us, either from before if just an if, or the ifTrue if an if-else
reachable = reachable || ifStack.back();
ifStack.pop_back();
if (isDead(curr->condition)) {
replaceCurrent(curr->condition);
}
}
static void scan(DeadCodeElimination* self, Expression** currp) {
if (!self->reachable) {
// convert to an unreachable. do this without UB, even though we have no destructors on AST nodes
#define DELEGATE(CLASS_TO_VISIT) \
{ ExpressionManipulator::convert<CLASS_TO_VISIT, Unreachable>(static_cast<CLASS_TO_VISIT*>(*currp)); break; }
switch ((*currp)->_id) {
case Expression::Id::BlockId: DELEGATE(Block);
case Expression::Id::IfId: DELEGATE(If);
case Expression::Id::LoopId: DELEGATE(Loop);
case Expression::Id::BreakId: DELEGATE(Break);
case Expression::Id::SwitchId: DELEGATE(Switch);
case Expression::Id::CallId: DELEGATE(Call);
case Expression::Id::CallImportId: DELEGATE(CallImport);
case Expression::Id::CallIndirectId: DELEGATE(CallIndirect);
case Expression::Id::GetLocalId: DELEGATE(GetLocal);
case Expression::Id::SetLocalId: DELEGATE(SetLocal);
case Expression::Id::LoadId: DELEGATE(Load);
case Expression::Id::StoreId: DELEGATE(Store);
case Expression::Id::ConstId: DELEGATE(Const);
case Expression::Id::UnaryId: DELEGATE(Unary);
case Expression::Id::BinaryId: DELEGATE(Binary);
case Expression::Id::SelectId: DELEGATE(Select);
case Expression::Id::ReturnId: DELEGATE(Return);
case Expression::Id::HostId: DELEGATE(Host);
case Expression::Id::NopId: DELEGATE(Nop);
case Expression::Id::UnreachableId: DELEGATE(Unreachable);
case Expression::Id::InvalidId:
default: WASM_UNREACHABLE();
}
#undef DELEGATE
return;
}
auto* curr =* currp;
if (curr->is<If>()) {
self->pushTask(DeadCodeElimination::doVisitIf, currp);
if (curr->cast<If>()->ifFalse) {
self->pushTask(DeadCodeElimination::scan, &curr->cast<If>()->ifFalse);
self->pushTask(DeadCodeElimination::doAfterIfElseTrue, currp);
}
self->pushTask(DeadCodeElimination::scan, &curr->cast<If>()->ifTrue);
self->pushTask(DeadCodeElimination::doAfterIfCondition, currp);
self->pushTask(DeadCodeElimination::scan, &curr->cast<If>()->condition);
} else if (curr->is<Block>()) {
self->pushTask(DeadCodeElimination::doVisitBlock, currp);
auto& list = curr->cast<Block>()->list;
for (int i = int(list.size()) - 1; i >= 0; i--) {
self->pushTask(DeadCodeElimination::doAfterBlockElement, currp);
self->pushTask(DeadCodeElimination::scan, &list[i]);
}
self->pushTask(DeadCodeElimination::doPreBlock, currp);
} else {
WalkerPass<PostWalker<DeadCodeElimination, Visitor<DeadCodeElimination>>>::scan(self, currp);
}
}
// other things
template<typename T>
void handleCall(T* curr, Expression* initial) {
for (Index i = 0; i < curr->operands.size(); i++) {
if (isDead(curr->operands[i])) {
if (i > 0 || initial != nullptr) {
auto* block = getModule()->allocator.alloc<Block>();
Index newSize = i + 1 + (initial ? 1 : 0);
block->list.resize(newSize);
Index j = 0;
if (initial) {
block->list[j] = initial;
j++;
}
for (; j < newSize; j++) {
block->list[j] = curr->operands[j - (initial ? 1 : 0)];
}
block->finalize();
replaceCurrent(block);
} else {
replaceCurrent(curr->operands[i]);
}
return;
}
}
}
void visitCall(Call* curr) {
handleCall(curr, nullptr);
}
void visitCallImport(CallImport* curr) {
handleCall(curr, nullptr);
}
void visitCallIndirect(CallIndirect* curr) {
if (isDead(curr->target)) {
replaceCurrent(curr->target);
return;
}
handleCall(curr, curr->target);
}
void visitSetLocal(SetLocal* curr) {
if (isDead(curr->value)) {
replaceCurrent(curr->value);
}
}
void visitLoad(Load* curr) {
if (isDead(curr->ptr)) {
replaceCurrent(curr->ptr);
}
}
void visitStore(Store* curr) {
if (isDead(curr->ptr)) {
replaceCurrent(curr->ptr);
return;
}
if (isDead(curr->value)) {
auto* block = getModule()->allocator.alloc<Block>();
block->list.resize(2);
block->list[0] = curr->ptr;
block->list[1] = curr->value;
block->finalize();
replaceCurrent(block);
}
}
void visitUnary(Unary* curr) {
if (isDead(curr->value)) {
replaceCurrent(curr->value);
}
}
void visitBinary(Binary* curr) {
if (isDead(curr->left)) {
replaceCurrent(curr->left);
return;
}
if (isDead(curr->right)) {
auto* block = getModule()->allocator.alloc<Block>();
block->list.resize(2);
block->list[0] = curr->left;
block->list[1] = curr->right;
block->finalize();
replaceCurrent(block);
}
}
void visitSelect(Select* curr) {
if (isDead(curr->ifTrue)) {
replaceCurrent(curr->ifTrue);
return;
}
if (isDead(curr->ifFalse)) {
auto* block = getModule()->allocator.alloc<Block>();
block->list.resize(2);
block->list[0] = curr->ifTrue;
block->list[1] = curr->ifFalse;
block->finalize();
replaceCurrent(block);
return;
}
if (isDead(curr->condition)) {
auto* block = getModule()->allocator.alloc<Block>();
block->list.resize(3);
block->list[0] = curr->ifTrue;
block->list[1] = curr->ifFalse;
block->list[2] = curr->condition;
block->finalize();
replaceCurrent(block);
return;
}
}
void visitHost(Host* curr) {
// TODO
}
void visitFunction(Function* curr) {
assert(reachableBreaks.size() == 0);
}
};
Pass *createDeadCodeEliminationPass() {
return new DeadCodeElimination();
}
} // namespace wasm
|