forked from ethereum/solidity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPeepholeOptimiser.cpp
534 lines (498 loc) · 12.2 KB
/
PeepholeOptimiser.cpp
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
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* @file PeepholeOptimiser.cpp
* Performs local optimising code changes to assembly.
*/
#include <libevmasm/PeepholeOptimiser.h>
#include <libevmasm/AssemblyItem.h>
#include <libevmasm/SemanticInformation.h>
using namespace std;
using namespace solidity;
using namespace solidity::evmasm;
// TODO: Extend this to use the tools from ExpressionClasses.cpp
namespace
{
struct OptimiserState
{
AssemblyItems const& items;
size_t i;
back_insert_iterator<AssemblyItems> out;
};
template<typename FunctionType>
struct FunctionParameterCount;
template<typename R, typename... Args>
struct FunctionParameterCount<R(Args...)>
{
static constexpr auto value = sizeof...(Args);
};
template <class Method>
struct SimplePeepholeOptimizerMethod
{
template <size_t... Indices>
static bool applyRule(
AssemblyItems::const_iterator _in,
back_insert_iterator<AssemblyItems> _out,
index_sequence<Indices...>
)
{
return Method::applySimple(_in[Indices]..., _out);
}
static bool apply(OptimiserState& _state)
{
static constexpr size_t WindowSize = FunctionParameterCount<decltype(Method::applySimple)>::value - 1;
if (
_state.i + WindowSize <= _state.items.size() &&
applyRule(_state.items.begin() + static_cast<ptrdiff_t>(_state.i), _state.out, make_index_sequence<WindowSize>{})
)
{
_state.i += WindowSize;
return true;
}
else
return false;
}
};
struct Identity: SimplePeepholeOptimizerMethod<Identity>
{
static bool applySimple(
AssemblyItem const& _item,
back_insert_iterator<AssemblyItems> _out
)
{
*_out = _item;
return true;
}
};
struct PushPop: SimplePeepholeOptimizerMethod<PushPop>
{
static bool applySimple(
AssemblyItem const& _push,
AssemblyItem const& _pop,
back_insert_iterator<AssemblyItems>
)
{
auto t = _push.type();
return _pop == Instruction::POP && (
SemanticInformation::isDupInstruction(_push) ||
t == Push || t == PushTag || t == PushSub ||
t == PushSubSize || t == PushProgramSize || t == PushData || t == PushLibraryAddress
);
}
};
struct OpPop: SimplePeepholeOptimizerMethod<OpPop>
{
static bool applySimple(
AssemblyItem const& _op,
AssemblyItem const& _pop,
back_insert_iterator<AssemblyItems> _out
)
{
if (_pop == Instruction::POP && _op.type() == Operation)
{
Instruction instr = _op.instruction();
if (instructionInfo(instr, langutil::EVMVersion()).ret == 1 && !instructionInfo(instr, langutil::EVMVersion()).sideEffects)
{
for (int j = 0; j < instructionInfo(instr, langutil::EVMVersion()).args; j++)
*_out = {Instruction::POP, _op.location()};
return true;
}
}
return false;
}
};
struct OpStop: SimplePeepholeOptimizerMethod<OpStop>
{
static bool applySimple(
AssemblyItem const& _op,
AssemblyItem const& _stop,
back_insert_iterator<AssemblyItems> _out
)
{
if (_stop == Instruction::STOP)
{
if (_op.type() == Operation)
{
Instruction instr = _op.instruction();
if (!instructionInfo(instr, langutil::EVMVersion()).sideEffects)
{
*_out = {Instruction::STOP, _op.location()};
return true;
}
}
else if (_op.type() == Push)
{
*_out = {Instruction::STOP, _op.location()};
return true;
}
}
return false;
}
};
struct OpReturnRevert: SimplePeepholeOptimizerMethod<OpReturnRevert>
{
static bool applySimple(
AssemblyItem const& _op,
AssemblyItem const& _push,
AssemblyItem const& _pushOrDup,
AssemblyItem const& _returnRevert,
back_insert_iterator<AssemblyItems> _out
)
{
if (
(_returnRevert == Instruction::RETURN || _returnRevert == Instruction::REVERT) &&
_push.type() == Push &&
(_pushOrDup.type() == Push || _pushOrDup == dupInstruction(1))
)
if (
(_op.type() == Operation && !instructionInfo(_op.instruction(), langutil::EVMVersion()).sideEffects) ||
_op.type() == Push
)
{
*_out = _push;
*_out = _pushOrDup;
*_out = _returnRevert;
return true;
}
return false;
}
};
struct DoubleSwap: SimplePeepholeOptimizerMethod<DoubleSwap>
{
static size_t applySimple(
AssemblyItem const& _s1,
AssemblyItem const& _s2,
back_insert_iterator<AssemblyItems>
)
{
return _s1 == _s2 && SemanticInformation::isSwapInstruction(_s1);
}
};
struct DoublePush: SimplePeepholeOptimizerMethod<DoublePush>
{
static bool applySimple(
AssemblyItem const& _push1,
AssemblyItem const& _push2,
back_insert_iterator<AssemblyItems> _out
)
{
if (_push1.type() == Push && _push2.type() == Push && _push1.data() == _push2.data())
{
*_out = _push1;
*_out = {Instruction::DUP1, _push2.location()};
return true;
}
else
return false;
}
};
struct CommutativeSwap: SimplePeepholeOptimizerMethod<CommutativeSwap>
{
static bool applySimple(
AssemblyItem const& _swap,
AssemblyItem const& _op,
back_insert_iterator<AssemblyItems> _out
)
{
// Remove SWAP1 if following instruction is commutative
if (
_swap == Instruction::SWAP1 &&
SemanticInformation::isCommutativeOperation(_op)
)
{
*_out = _op;
return true;
}
else
return false;
}
};
struct SwapComparison: SimplePeepholeOptimizerMethod<SwapComparison>
{
static bool applySimple(
AssemblyItem const& _swap,
AssemblyItem const& _op,
back_insert_iterator<AssemblyItems> _out
)
{
static map<Instruction, Instruction> const swappableOps{
{ Instruction::LT, Instruction::GT },
{ Instruction::GT, Instruction::LT },
{ Instruction::SLT, Instruction::SGT },
{ Instruction::SGT, Instruction::SLT }
};
if (
_swap == Instruction::SWAP1 &&
_op.type() == Operation &&
swappableOps.count(_op.instruction())
)
{
*_out = swappableOps.at(_op.instruction());
return true;
}
else
return false;
}
};
/// Remove swapN after dupN
struct DupSwap: SimplePeepholeOptimizerMethod<DupSwap>
{
static size_t applySimple(
AssemblyItem const& _dupN,
AssemblyItem const& _swapN,
back_insert_iterator<AssemblyItems> _out
)
{
if (
SemanticInformation::isDupInstruction(_dupN) &&
SemanticInformation::isSwapInstruction(_swapN) &&
getDupNumber(_dupN.instruction()) == getSwapNumber(_swapN.instruction())
)
{
*_out = _dupN;
return true;
}
else
return false;
}
};
struct IsZeroIsZeroJumpI: SimplePeepholeOptimizerMethod<IsZeroIsZeroJumpI>
{
static size_t applySimple(
AssemblyItem const& _iszero1,
AssemblyItem const& _iszero2,
AssemblyItem const& _pushTag,
AssemblyItem const& _jumpi,
back_insert_iterator<AssemblyItems> _out
)
{
if (
_iszero1 == Instruction::ISZERO &&
_iszero2 == Instruction::ISZERO &&
_pushTag.type() == PushTag &&
_jumpi == Instruction::JUMPI
)
{
*_out = _pushTag;
*_out = _jumpi;
return true;
}
else
return false;
}
};
struct EqIsZeroJumpI: SimplePeepholeOptimizerMethod<EqIsZeroJumpI>
{
static size_t applySimple(
AssemblyItem const& _eq,
AssemblyItem const& _iszero,
AssemblyItem const& _pushTag,
AssemblyItem const& _jumpi,
back_insert_iterator<AssemblyItems> _out
)
{
if (
_eq == Instruction::EQ &&
_iszero == Instruction::ISZERO &&
_pushTag.type() == PushTag &&
_jumpi == Instruction::JUMPI
)
{
*_out = AssemblyItem(Instruction::SUB, _eq.location());
*_out = _pushTag;
*_out = _jumpi;
return true;
}
else
return false;
}
};
// push_tag_1 jumpi push_tag_2 jump tag_1: -> iszero push_tag_2 jumpi tag_1:
struct DoubleJump: SimplePeepholeOptimizerMethod<DoubleJump>
{
static size_t applySimple(
AssemblyItem const& _pushTag1,
AssemblyItem const& _jumpi,
AssemblyItem const& _pushTag2,
AssemblyItem const& _jump,
AssemblyItem const& _tag1,
back_insert_iterator<AssemblyItems> _out
)
{
if (
_pushTag1.type() == PushTag &&
_jumpi == Instruction::JUMPI &&
_pushTag2.type() == PushTag &&
_jump == Instruction::JUMP &&
_tag1.type() == Tag &&
_pushTag1.data() == _tag1.data()
)
{
*_out = AssemblyItem(Instruction::ISZERO, _jumpi.location());
*_out = _pushTag2;
*_out = _jumpi;
*_out = _tag1;
return true;
}
else
return false;
}
};
struct JumpToNext: SimplePeepholeOptimizerMethod<JumpToNext>
{
static size_t applySimple(
AssemblyItem const& _pushTag,
AssemblyItem const& _jump,
AssemblyItem const& _tag,
back_insert_iterator<AssemblyItems> _out
)
{
if (
_pushTag.type() == PushTag &&
(_jump == Instruction::JUMP || _jump == Instruction::JUMPI) &&
_tag.type() == Tag &&
_pushTag.data() == _tag.data()
)
{
if (_jump == Instruction::JUMPI)
*_out = AssemblyItem(Instruction::POP, _jump.location());
*_out = _tag;
return true;
}
else
return false;
}
};
struct TagConjunctions: SimplePeepholeOptimizerMethod<TagConjunctions>
{
static bool applySimple(
AssemblyItem const& _pushTag,
AssemblyItem const& _pushConstant,
AssemblyItem const& _and,
back_insert_iterator<AssemblyItems> _out
)
{
if (_and != Instruction::AND)
return false;
if (
_pushTag.type() == PushTag &&
_pushConstant.type() == Push &&
(_pushConstant.data() & u256(0xFFFFFFFF)) == u256(0xFFFFFFFF)
)
{
*_out = _pushTag;
return true;
}
else if (
// tag and constant are swapped
_pushConstant.type() == PushTag &&
_pushTag.type() == Push &&
(_pushTag.data() & u256(0xFFFFFFFF)) == u256(0xFFFFFFFF)
)
{
*_out = _pushConstant;
return true;
}
else
return false;
}
};
struct TruthyAnd: SimplePeepholeOptimizerMethod<TruthyAnd>
{
static bool applySimple(
AssemblyItem const& _push,
AssemblyItem const& _not,
AssemblyItem const& _and,
back_insert_iterator<AssemblyItems>
)
{
return (
_push.type() == Push && _push.data() == 0 &&
_not == Instruction::NOT &&
_and == Instruction::AND
);
}
};
/// Removes everything after a JUMP (or similar) until the next JUMPDEST.
struct UnreachableCode
{
static bool apply(OptimiserState& _state)
{
auto it = _state.items.begin() + static_cast<ptrdiff_t>(_state.i);
auto end = _state.items.end();
if (it == end)
return false;
if (
it[0] != Instruction::JUMP &&
it[0] != Instruction::RETURN &&
it[0] != Instruction::STOP &&
it[0] != Instruction::INVALID &&
it[0] != Instruction::SELFDESTRUCT &&
it[0] != Instruction::REVERT
)
return false;
ptrdiff_t i = 1;
while (it + i != end && it[i].type() != Tag)
i++;
if (i > 1)
{
*_state.out = it[0];
_state.i += static_cast<size_t>(i);
return true;
}
else
return false;
}
};
void applyMethods(OptimiserState&)
{
assertThrow(false, OptimizerException, "Peephole optimizer failed to apply identity.");
}
template <typename Method, typename... OtherMethods>
void applyMethods(OptimiserState& _state, Method, OtherMethods... _other)
{
if (!Method::apply(_state))
applyMethods(_state, _other...);
}
size_t numberOfPops(AssemblyItems const& _items)
{
return static_cast<size_t>(std::count(_items.begin(), _items.end(), Instruction::POP));
}
}
bool PeepholeOptimiser::optimise()
{
// Avoid referencing immutables too early by using approx. counting in bytesRequired()
auto const approx = evmasm::Precision::Approximate;
OptimiserState state {m_items, 0, back_inserter(m_optimisedItems)};
while (state.i < m_items.size())
applyMethods(
state,
PushPop(), OpPop(), OpStop(), OpReturnRevert(), DoublePush(), DoubleSwap(), CommutativeSwap(), SwapComparison(),
DupSwap(), IsZeroIsZeroJumpI(), EqIsZeroJumpI(), DoubleJump(), JumpToNext(), UnreachableCode(),
TagConjunctions(), TruthyAnd(), Identity()
);
if (m_optimisedItems.size() < m_items.size() || (
m_optimisedItems.size() == m_items.size() && (
evmasm::bytesRequired(m_optimisedItems, 3, approx) < evmasm::bytesRequired(m_items, 3, approx) ||
numberOfPops(m_optimisedItems) > numberOfPops(m_items)
)
))
{
m_items = std::move(m_optimisedItems);
return true;
}
else
return false;
}