1 // Copyright (c) 2016 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/unify_const_pass.h"
16
17 #include <memory>
18 #include <unordered_map>
19 #include <utility>
20 #include <vector>
21
22 #include "source/opt/def_use_manager.h"
23 #include "source/util/make_unique.h"
24
25 namespace spvtools {
26 namespace opt {
27 namespace {
28
29 // The trie that stores a bunch of result ids and, for a given instruction,
30 // searches the result id that has been defined with the same opcode, type and
31 // operands.
32 class ResultIdTrie {
33 public:
ResultIdTrie()34 ResultIdTrie() : root_(new Node) {}
35
36 // For a given instruction, extracts its opcode, type id and operand words
37 // as an array of keys, looks up the trie to find a result id which is stored
38 // with the same opcode, type id and operand words. If none of such result id
39 // is found, creates a trie node with those keys, stores the instruction's
40 // result id and returns that result id. If an existing result id is found,
41 // returns the existing result id.
LookupEquivalentResultFor(const Instruction & inst)42 uint32_t LookupEquivalentResultFor(const Instruction& inst) {
43 auto keys = GetLookUpKeys(inst);
44 auto* node = root_.get();
45 for (uint32_t key : keys) {
46 node = node->GetOrCreateTrieNodeFor(key);
47 }
48 if (node->result_id() == 0) {
49 node->SetResultId(inst.result_id());
50 }
51 return node->result_id();
52 }
53
54 private:
55 // The trie node to store result ids.
56 class Node {
57 public:
58 using TrieNodeMap = std::unordered_map<uint32_t, std::unique_ptr<Node>>;
59
Node()60 Node() : result_id_(0), next_() {}
result_id() const61 uint32_t result_id() const { return result_id_; }
62
63 // Sets the result id stored in this node.
SetResultId(uint32_t id)64 void SetResultId(uint32_t id) { result_id_ = id; }
65
66 // Searches for the child trie node with the given key. If the node is
67 // found, returns that node. Otherwise creates an empty child node with
68 // that key and returns that newly created node.
GetOrCreateTrieNodeFor(uint32_t key)69 Node* GetOrCreateTrieNodeFor(uint32_t key) {
70 auto iter = next_.find(key);
71 if (iter == next_.end()) {
72 // insert a new node and return the node.
73 return next_.insert(std::make_pair(key, MakeUnique<Node>()))
74 .first->second.get();
75 }
76 return iter->second.get();
77 }
78
79 private:
80 // The result id stored in this node. 0 means this node is empty.
81 uint32_t result_id_;
82 // The mapping from the keys to the child nodes of this node.
83 TrieNodeMap next_;
84 };
85
86 // Returns a vector of the opcode followed by the words in the raw SPIR-V
87 // instruction encoding but without the result id.
GetLookUpKeys(const Instruction & inst)88 std::vector<uint32_t> GetLookUpKeys(const Instruction& inst) {
89 std::vector<uint32_t> keys;
90 // Need to use the opcode, otherwise there might be a conflict with the
91 // following case when <op>'s binary value equals xx's id:
92 // OpSpecConstantOp tt <op> yy zz
93 // OpSpecConstantComposite tt xx yy zz;
94 keys.push_back(static_cast<uint32_t>(inst.opcode()));
95 for (const auto& operand : inst) {
96 if (operand.type == SPV_OPERAND_TYPE_RESULT_ID) continue;
97 keys.insert(keys.end(), operand.words.cbegin(), operand.words.cend());
98 }
99 return keys;
100 }
101
102 std::unique_ptr<Node> root_; // The root node of the trie.
103 };
104 } // namespace
105
Process()106 Pass::Status UnifyConstantPass::Process() {
107 bool modified = false;
108 ResultIdTrie defined_constants;
109
110 for (Instruction *next_instruction,
111 *inst = &*(context()->types_values_begin());
112 inst; inst = next_instruction) {
113 next_instruction = inst->NextNode();
114
115 // Do not handle the instruction when there are decorations upon the result
116 // id.
117 if (get_def_use_mgr()->GetAnnotations(inst->result_id()).size() != 0) {
118 continue;
119 }
120
121 // The overall algorithm is to store the result ids of all the eligible
122 // constants encountered so far in a trie. For a constant defining
123 // instruction under consideration, use its opcode, result type id and
124 // words in operands as an array of keys to lookup the trie. If a result id
125 // can be found for that array of keys, a constant with exactly the same
126 // value must has been defined before, the constant under processing
127 // should be replaced by the constant previously defined. If no such result
128 // id can be found for that array of keys, this must be the first time a
129 // constant with its value be defined, we then create a new trie node to
130 // store the result id with the keys. When replacing a duplicated constant
131 // with a previously defined constant, all the uses of the duplicated
132 // constant, which must be placed after the duplicated constant defining
133 // instruction, will be updated. This way, the descendants of the
134 // previously defined constant and the duplicated constant will both refer
135 // to the previously defined constant. So that the operand ids which are
136 // used in key arrays will be the ids of the unified constants, when
137 // processing is up to a descendant. This makes comparing the key array
138 // always valid for judging duplication.
139 switch (inst->opcode()) {
140 case spv::Op::OpConstantTrue:
141 case spv::Op::OpConstantFalse:
142 case spv::Op::OpConstant:
143 case spv::Op::OpConstantNull:
144 case spv::Op::OpConstantSampler:
145 case spv::Op::OpConstantComposite:
146 // Only spec constants defined with OpSpecConstantOp and
147 // OpSpecConstantComposite should be processed in this pass. Spec
148 // constants defined with OpSpecConstant{|True|False} are decorated with
149 // 'SpecId' decoration and all of them should be treated as unique.
150 // 'SpecId' is not applicable to SpecConstants defined with
151 // OpSpecConstant{Op|Composite}, their values are not necessary to be
152 // unique. When all the operands/components are the same between two
153 // OpSpecConstant{Op|Composite} results, their result values must be the
154 // same so are unifiable.
155 case spv::Op::OpSpecConstantOp:
156 case spv::Op::OpSpecConstantComposite: {
157 uint32_t id = defined_constants.LookupEquivalentResultFor(*inst);
158 if (id != inst->result_id()) {
159 // The constant is a duplicated one, use the cached constant to
160 // replace the uses of this duplicated one, then turn it to nop.
161 context()->ReplaceAllUsesWith(inst->result_id(), id);
162 context()->KillInst(inst);
163 modified = true;
164 }
165 break;
166 }
167 default:
168 break;
169 }
170 }
171 return modified ? Status::SuccessWithChange : Status::SuccessWithoutChange;
172 }
173
174 } // namespace opt
175 } // namespace spvtools
176