| 35 | |
| 36 | |
| 37 | bool BlockDeduplicator::deduplicate() |
| 38 | { |
| 39 | // Compares indices based on the suffix that starts there, ignoring tags and stopping at |
| 40 | // opcodes that stop the control flow. |
| 41 | |
| 42 | // Virtual tag that signifies "the current block" and which is used to optimise loops. |
| 43 | // We abort if this virtual tag actually exists. |
| 44 | AssemblyItem pushSelf{PushTag, u256(-4)}; |
| 45 | if ( |
| 46 | std::count(m_items.cbegin(), m_items.cend(), pushSelf.tag()) || |
| 47 | std::count(m_items.cbegin(), m_items.cend(), pushSelf.pushTag()) |
| 48 | ) |
| 49 | return false; |
| 50 | |
| 51 | std::function<bool(size_t, size_t)> comparator = [&](size_t _i, size_t _j) |
| 52 | { |
| 53 | if (_i == _j) |
| 54 | return false; |
| 55 | |
| 56 | // To compare recursive loops, we have to already unify PushTag opcodes of the |
| 57 | // block's own tag. |
| 58 | AssemblyItem pushFirstTag{pushSelf}; |
| 59 | AssemblyItem pushSecondTag{pushSelf}; |
| 60 | |
| 61 | if (_i < m_items.size() && m_items.at(_i).type() == Tag) |
| 62 | pushFirstTag = m_items.at(_i).pushTag(); |
| 63 | if (_j < m_items.size() && m_items.at(_j).type() == Tag) |
| 64 | pushSecondTag = m_items.at(_j).pushTag(); |
| 65 | |
| 66 | using diff_type = BlockIterator::difference_type; |
| 67 | BlockIterator first{m_items.begin() + diff_type(_i), m_items.end(), &pushFirstTag, &pushSelf}; |
| 68 | BlockIterator second{m_items.begin() + diff_type(_j), m_items.end(), &pushSecondTag, &pushSelf}; |
| 69 | BlockIterator end{m_items.end(), m_items.end()}; |
| 70 | |
| 71 | if (first != end && (*first).type() == Tag) |
| 72 | ++first; |
| 73 | if (second != end && (*second).type() == Tag) |
| 74 | ++second; |
| 75 | |
| 76 | return std::lexicographical_compare(first, end, second, end); |
| 77 | }; |
| 78 | |
| 79 | size_t iterations = 0; |
| 80 | for (; ; ++iterations) |
| 81 | { |
| 82 | //@todo this should probably be optimized. |
| 83 | std::set<size_t, std::function<bool(size_t, size_t)>> blocksSeen(comparator); |
| 84 | for (size_t i = 0; i < m_items.size(); ++i) |
| 85 | { |
| 86 | if (m_items.at(i).type() != Tag) |
| 87 | continue; |
| 88 | auto it = blocksSeen.find(i); |
| 89 | if (it == blocksSeen.end()) |
| 90 | blocksSeen.insert(i); |
| 91 | else |
| 92 | m_replacedTags[m_items.at(i).data()] = m_items.at(*it).data(); |
| 93 | } |
| 94 | |