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