compact_ids_pass.cpp 2.3 KB

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