1// Copyright (c) 2017 Google Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#include "source/opt/local_redundancy_elimination.h"
16
17#include "source/opt/value_number_table.h"
18
19namespace spvtools {
20namespace opt {
21
22Pass::Status LocalRedundancyEliminationPass::Process() {
23 bool modified = false;
24 ValueNumberTable vnTable(context());
25
26 for (auto& func : *get_module()) {
27 for (auto& bb : func) {
28 // Keeps track of all ids that contain a given value number. We keep
29 // track of multiple values because they could have the same value, but
30 // different decorations.
31 std::map<uint32_t, uint32_t> value_to_ids;
32 if (EliminateRedundanciesInBB(&bb, vnTable, &value_to_ids))
33 modified = true;
34 }
35 }
36 return (modified ? Status::SuccessWithChange : Status::SuccessWithoutChange);
37}
38
39bool LocalRedundancyEliminationPass::EliminateRedundanciesInBB(
40 BasicBlock* block, const ValueNumberTable& vnTable,
41 std::map<uint32_t, uint32_t>* value_to_ids) {
42 bool modified = false;
43
44 auto func = [this, &vnTable, &modified, value_to_ids](Instruction* inst) {
45 if (inst->result_id() == 0) {
46 return;
47 }
48
49 uint32_t value = vnTable.GetValueNumber(inst);
50
51 if (value == 0) {
52 return;
53 }
54
55 auto candidate = value_to_ids->insert({value, inst->result_id()});
56 if (!candidate.second) {
57 context()->KillNamesAndDecorates(inst);
58 context()->ReplaceAllUsesWith(inst->result_id(), candidate.first->second);
59 context()->KillInst(inst);
60 modified = true;
61 }
62 };
63 block->ForEachInst(func);
64 return modified;
65}
66} // namespace opt
67} // namespace spvtools
68