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 #ifndef SOURCE_ID_DESCRIPTOR_H_
16 #define SOURCE_ID_DESCRIPTOR_H_
17 
18 #include <unordered_map>
19 #include <vector>
20 
21 #include "spirv-tools/libspirv.hpp"
22 
23 namespace spvtools {
24 
25 using CustomHashFunc = std::function<uint32_t(const std::vector<uint32_t>&)>;
26 
27 // Computes and stores id descriptors.
28 //
29 // Descriptors are computed as hash of all words in the instruction where ids
30 // were substituted with previously computed descriptors.
31 class IdDescriptorCollection {
32  public:
33   explicit IdDescriptorCollection(
34       CustomHashFunc custom_hash_func = CustomHashFunc())
custom_hash_func_(custom_hash_func)35       : custom_hash_func_(custom_hash_func) {
36     words_.reserve(16);
37   }
38 
39   // Computes descriptor for the result id of the given instruction and
40   // registers it in id_to_descriptor_. Returns the computed descriptor.
41   // This function needs to be sequentially called for every instruction in the
42   // module.
43   uint32_t ProcessInstruction(const spv_parsed_instruction_t& inst);
44 
45   // Returns a previously computed descriptor id.
GetDescriptor(uint32_t id)46   uint32_t GetDescriptor(uint32_t id) const {
47     const auto it = id_to_descriptor_.find(id);
48     if (it == id_to_descriptor_.end()) return 0;
49     return it->second;
50   }
51 
52  private:
53   std::unordered_map<uint32_t, uint32_t> id_to_descriptor_;
54 
55   std::function<uint32_t(const std::vector<uint32_t>&)> custom_hash_func_;
56 
57   // Scratch buffer used for hashing. Class member to optimize on allocation.
58   std::vector<uint32_t> words_;
59 };
60 
61 }  // namespace spvtools
62 
63 #endif  // SOURCE_ID_DESCRIPTOR_H_
64