1 // Copyright (c) 2019 Google LLC 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 #ifndef SOURCE_FUZZ_EQUIVALENCE_RELATION_H_ 16 #define SOURCE_FUZZ_EQUIVALENCE_RELATION_H_ 17 18 #include <memory> 19 #include <unordered_map> 20 #include <unordered_set> 21 #include <vector> 22 23 #include "source/util/make_unique.h" 24 25 namespace spvtools { 26 namespace fuzz { 27 28 // A class for representing an equivalence relation on objects of type |T|, 29 // which should be a value type. The type |T| is required to have a copy 30 // constructor, and |PointerHashT| and |PointerEqualsT| must be functors 31 // providing hashing and equality testing functionality for pointers to objects 32 // of type |T|. 33 // 34 // A disjoint-set (a.k.a. union-find or merge-find) data structure is used to 35 // represent the equivalence relation. Path compression is used. Union by 36 // rank/size is not used. 37 // 38 // Each disjoint set is represented as a tree, rooted at the representative 39 // of the set. 40 // 41 // Getting the representative of a value simply requires chasing parent pointers 42 // from the value until you reach the root. 43 // 44 // Checking equivalence of two elements requires checking that the 45 // representatives are equal. 46 // 47 // Traversing the tree rooted at a value's representative visits the value's 48 // equivalence class. 49 // 50 // |PointerHashT| and |PointerEqualsT| are used to define *equality* between 51 // values, and otherwise are *not* used to define the equivalence relation 52 // (except that equal values are equivalent). The equivalence relation is 53 // constructed by repeatedly adding pairs of (typically non-equal) values that 54 // are deemed to be equivalent. 55 // 56 // For example in an equivalence relation on integers, 1 and 5 might be added 57 // as equivalent, so that IsEquivalent(1, 5) holds, because they represent 58 // IDs in a SPIR-V binary that are known to contain the same value at run time, 59 // but clearly 1 != 5. Since 1 and 1 are equal, IsEquivalent(1, 1) will also 60 // hold. 61 // 62 // Each unique (up to equality) value added to the relation is copied into 63 // |owned_values_|, so there is one canonical memory address per unique value. 64 // Uniqueness is ensured by storing (and checking) a set of pointers to these 65 // values in |value_set_|, which uses |PointerHashT| and |PointerEqualsT|. 66 // 67 // |parent_| and |children_| encode the equivalence relation, i.e., the trees. 68 template <typename T, typename PointerHashT, typename PointerEqualsT> 69 class EquivalenceRelation { 70 public: 71 // Merges the equivalence classes associated with |value1| and |value2|. 72 // If any of these values was not previously in the equivalence relation, it 73 // is added to the pool of values known to be in the relation. MakeEquivalent(const T & value1,const T & value2)74 void MakeEquivalent(const T& value1, const T& value2) { 75 // Register each value if necessary. 76 for (auto value : {value1, value2}) { 77 if (!Exists(value)) { 78 // Register the value in the equivalence relation. This relies on 79 // T having a copy constructor. 80 auto unique_pointer_to_value = MakeUnique<T>(value); 81 auto pointer_to_value = unique_pointer_to_value.get(); 82 owned_values_.push_back(std::move(unique_pointer_to_value)); 83 value_set_.insert(pointer_to_value); 84 85 // Initially say that the value is its own parent and that it has no 86 // children. 87 assert(pointer_to_value && "Representatives should never be null."); 88 parent_[pointer_to_value] = pointer_to_value; 89 children_[pointer_to_value] = std::vector<const T*>(); 90 } 91 } 92 93 // Look up canonical pointers to each of the values in the value pool. 94 const T* value1_ptr = *value_set_.find(&value1); 95 const T* value2_ptr = *value_set_.find(&value2); 96 97 // If the values turn out to be identical, they are already in the same 98 // equivalence class so there is nothing to do. 99 if (value1_ptr == value2_ptr) { 100 return; 101 } 102 103 // Find the representative for each value's equivalence class, and if they 104 // are not already in the same class, make one the parent of the other. 105 const T* representative1 = Find(value1_ptr); 106 const T* representative2 = Find(value2_ptr); 107 assert(representative1 && "Representatives should never be null."); 108 assert(representative2 && "Representatives should never be null."); 109 if (representative1 != representative2) { 110 parent_[representative1] = representative2; 111 children_[representative2].push_back(representative1); 112 } 113 } 114 115 // Returns exactly one representative per equivalence class. GetEquivalenceClassRepresentatives()116 std::vector<const T*> GetEquivalenceClassRepresentatives() const { 117 std::vector<const T*> result; 118 for (auto& value : owned_values_) { 119 if (parent_[value.get()] == value.get()) { 120 result.push_back(value.get()); 121 } 122 } 123 return result; 124 } 125 126 // Returns pointers to all values in the equivalence class of |value|, which 127 // must already be part of the equivalence relation. GetEquivalenceClass(const T & value)128 std::vector<const T*> GetEquivalenceClass(const T& value) const { 129 assert(Exists(value)); 130 131 std::vector<const T*> result; 132 133 // Traverse the tree of values rooted at the representative of the 134 // equivalence class to which |value| belongs, and collect up all the values 135 // that are encountered. This constitutes the whole equivalence class. 136 std::vector<const T*> stack; 137 stack.push_back(Find(*value_set_.find(&value))); 138 while (!stack.empty()) { 139 const T* item = stack.back(); 140 result.push_back(item); 141 stack.pop_back(); 142 for (auto child : children_[item]) { 143 stack.push_back(child); 144 } 145 } 146 return result; 147 } 148 149 // Returns true if and only if |value1| and |value2| are in the same 150 // equivalence class. Both values must already be known to the equivalence 151 // relation. IsEquivalent(const T & value1,const T & value2)152 bool IsEquivalent(const T& value1, const T& value2) const { 153 return Find(&value1) == Find(&value2); 154 } 155 156 // Returns all values known to be part of the equivalence relation. GetAllKnownValues()157 std::vector<const T*> GetAllKnownValues() const { 158 std::vector<const T*> result; 159 for (auto& value : owned_values_) { 160 result.push_back(value.get()); 161 } 162 return result; 163 } 164 165 // Returns true if and only if |value| is known to be part of the equivalence 166 // relation. Exists(const T & value)167 bool Exists(const T& value) const { 168 return value_set_.find(&value) != value_set_.end(); 169 } 170 171 private: 172 // Returns the representative of the equivalence class of |value|, which must 173 // already be known to the equivalence relation. This is the 'Find' operation 174 // in a classic union-find data structure. Find(const T * value)175 const T* Find(const T* value) const { 176 assert(Exists(*value)); 177 178 // Get the canonical pointer to the value from the value pool. 179 const T* known_value = *value_set_.find(value); 180 assert(parent_[known_value] && "Every known value should have a parent."); 181 182 // Compute the result by chasing parents until we find a value that is its 183 // own parent. 184 const T* result = known_value; 185 while (parent_[result] != result) { 186 result = parent_[result]; 187 } 188 assert(result && "Representatives should never be null."); 189 190 // At this point, |result| is the representative of the equivalence class. 191 // Now perform the 'path compression' optimization by doing another pass up 192 // the parent chain, setting the parent of each node to be the 193 // representative, and rewriting children correspondingly. 194 const T* current = known_value; 195 while (parent_[current] != result) { 196 const T* next = parent_[current]; 197 parent_[current] = result; 198 children_[result].push_back(current); 199 auto child_iterator = 200 std::find(children_[next].begin(), children_[next].end(), current); 201 assert(child_iterator != children_[next].end() && 202 "'next' is the parent of 'current', so 'current' should be a " 203 "child of 'next'"); 204 children_[next].erase(child_iterator); 205 current = next; 206 } 207 return result; 208 } 209 210 // Maps every value to a parent. The representative of an equivalence class 211 // is its own parent. A value's representative can be found by walking its 212 // chain of ancestors. 213 // 214 // Mutable because the intuitively const method, 'Find', performs path 215 // compression. 216 mutable std::unordered_map<const T*, const T*> parent_; 217 218 // Stores the children of each value. This allows the equivalence class of 219 // a value to be calculated by traversing all descendents of the class's 220 // representative. 221 // 222 // Mutable because the intuitively const method, 'Find', performs path 223 // compression. 224 mutable std::unordered_map<const T*, std::vector<const T*>> children_; 225 226 // The values known to the equivalence relation are allocated in 227 // |owned_values_|, and |value_pool_| provides (via |PointerHashT| and 228 // |PointerEqualsT|) a means for mapping a value of interest to a pointer 229 // into an equivalent value in |owned_values_|. 230 std::unordered_set<const T*, PointerHashT, PointerEqualsT> value_set_; 231 std::vector<std::unique_ptr<T>> owned_values_; 232 }; 233 234 } // namespace fuzz 235 } // namespace spvtools 236 237 #endif // SOURCE_FUZZ_EQUIVALENCE_RELATION_H_ 238