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 "compact_ids_pass.h" 16 17 #include <cassert> 18 #include <unordered_map> 19 20 namespace spvtools { 21 namespace opt { 22 23 using ir::Instruction; 24 using ir::Operand; 25 26 Pass::Status CompactIdsPass::Process(ir::Module* module) { 27 bool modified = false; 28 std::unordered_map<uint32_t, uint32_t> result_id_mapping; 29 30 module->ForEachInst([&result_id_mapping, &modified] (Instruction* inst) { 31 auto operand = inst->begin(); 32 while (operand != inst->end()) { 33 if (spvIsIdType(operand->type)) { 34 assert(operand->words.size() == 1); 35 uint32_t& id = operand->words[0]; 36 auto it = result_id_mapping.find(id); 37 if (it == result_id_mapping.end()) { 38 const uint32_t new_id = 39 static_cast<uint32_t>(result_id_mapping.size()) + 1; 40 const auto insertion_result = result_id_mapping.emplace(id, new_id); 41 it = insertion_result.first; 42 assert(insertion_result.second); 43 } 44 if (id != it->second) { 45 modified = true; 46 id = it->second; 47 } 48 } 49 ++operand; 50 } 51 }, true); 52 53 return modified ? Status::SuccessWithChange : Status::SuccessWithoutChange; 54 } 55 56 } // namespace opt 57 } // namespace spvtools 58