File: resolve_binding_conflicts_pass.cpp

package info (click to toggle)
spirv-tools 2025.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 28,588 kB
  • sloc: cpp: 470,407; javascript: 5,893; python: 3,326; ansic: 488; sh: 450; ruby: 88; makefile: 18; lisp: 9
file content (328 lines) | stat: -rw-r--r-- 11,903 bytes parent folder | download | duplicates (11)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
// Copyright (c) 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "source/opt/resolve_binding_conflicts_pass.h"

#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <vector>

#include "source/opt/decoration_manager.h"
#include "source/opt/def_use_manager.h"
#include "source/opt/instruction.h"
#include "source/opt/ir_builder.h"
#include "source/opt/ir_context.h"
#include "spirv/unified1/spirv.h"

namespace spvtools {
namespace opt {

// A VarBindingInfo contains the binding information for a single resource
// variable.
//
// Exactly one such object is created per resource variable in the
// module. In particular, when a resource variable is statically used by
// more than one entry point, those entry points share the same VarBindingInfo
// object for that variable.
struct VarBindingInfo {
  const Instruction* const var;
  const uint32_t descriptor_set;
  Instruction* const binding_decoration;

  // Returns the binding number.
  uint32_t binding() const {
    return binding_decoration->GetSingleWordInOperand(2);
  }
  // Sets the binding number to 'b'.
  void updateBinding(uint32_t b) { binding_decoration->SetOperand(2, {b}); }
};

// The bindings in the same descriptor set that are used by an entry point.
using BindingList = std::vector<VarBindingInfo*>;
// A map from descriptor set number to the list of bindings in that descriptor
// set, as used by a particular entry point.
using DescriptorSets = std::unordered_map<uint32_t, BindingList>;

IRContext::Analysis ResolveBindingConflictsPass::GetPreservedAnalyses() {
  // All analyses are kept up to date.
  // At most this modifies the Binding numbers on variables.
  return IRContext::kAnalysisDefUse | IRContext::kAnalysisInstrToBlockMapping |
         IRContext::kAnalysisDecorations | IRContext::kAnalysisCombinators |
         IRContext::kAnalysisCFG | IRContext::kAnalysisDominatorAnalysis |
         IRContext::kAnalysisLoopAnalysis | IRContext::kAnalysisNameMap |
         IRContext::kAnalysisScalarEvolution |
         IRContext::kAnalysisRegisterPressure |
         IRContext::kAnalysisValueNumberTable |
         IRContext::kAnalysisStructuredCFG | IRContext::kAnalysisBuiltinVarId |
         IRContext::kAnalysisIdToFuncMapping | IRContext::kAnalysisConstants |
         IRContext::kAnalysisTypes | IRContext::kAnalysisDebugInfo |
         IRContext::kAnalysisLiveness;
}

// Orders variable binding info objects.
// * The binding number is most signficant;
// * Then a sampler-like object compares greater than non-sampler like object.
// * Otherwise compare based on variable ID.
// This provides a total order among bindings in a descriptor set for a valid
// Vulkan module.
bool Less(const VarBindingInfo* const lhs, const VarBindingInfo* const rhs) {
  if (lhs->binding() < rhs->binding()) return true;
  if (lhs->binding() > rhs->binding()) return false;

  // Examine types.
  // In valid Vulkan the only conflict can occur between
  // images and samplers.  We only care about a specific
  // comparison when one is a image-like thing and the other
  // is a sampler-like thing of the same shape.  So unwrap
  // types until we hit one of those two.

  auto* def_use_mgr = lhs->var->context()->get_def_use_mgr();

  // Returns the type found by iteratively following pointer pointee type,
  // or array element type.
  auto unwrap = [&def_use_mgr](Instruction* ty) {
    bool keep_going = true;
    do {
      switch (ty->opcode()) {
        case spv::Op::OpTypePointer:
          ty = def_use_mgr->GetDef(ty->GetSingleWordInOperand(1));
          break;
        case spv::Op::OpTypeArray:
        case spv::Op::OpTypeRuntimeArray:
          ty = def_use_mgr->GetDef(ty->GetSingleWordInOperand(0));
          break;
        default:
          keep_going = false;
          break;
      }
    } while (keep_going);
    return ty;
  };

  auto* lhs_ty = unwrap(def_use_mgr->GetDef(lhs->var->type_id()));
  auto* rhs_ty = unwrap(def_use_mgr->GetDef(rhs->var->type_id()));
  if (lhs_ty->opcode() == rhs_ty->opcode()) {
    // Pick based on variable ID.
    return lhs->var->result_id() < rhs->var->result_id();
  }
  // A sampler is always greater than an image.
  if (lhs_ty->opcode() == spv::Op::OpTypeSampler) {
    return false;
  }
  if (rhs_ty->opcode() == spv::Op::OpTypeSampler) {
    return true;
  }
  // Pick based on variable ID.
  return lhs->var->result_id() < rhs->var->result_id();
}

// Summarizes the caller-callee relationships between functions in a module.
class CallGraph {
 public:
  // Returns the list of all functions statically reachable from entry points,
  // where callees precede callers.
  const std::vector<uint32_t>& CalleesBeforeCallers() const {
    return visit_order_;
  }
  // Returns the list functions called from a given function.
  const std::unordered_set<uint32_t>& Callees(uint32_t caller) {
    return calls_[caller];
  }

  CallGraph(IRContext& context) {
    // Populate calls_.
    std::queue<uint32_t> callee_queue;
    for (const auto& fn : *context.module()) {
      auto& callees = calls_[fn.result_id()];
      context.AddCalls(&fn, &callee_queue);
      while (!callee_queue.empty()) {
        callees.insert(callee_queue.front());
        callee_queue.pop();
      }
    }

    // Perform depth-first search, starting from each entry point.
    // Populates visit_order_.
    for (const auto& ep : context.module()->entry_points()) {
      Visit(ep.GetSingleWordInOperand(1));
    }
  }

 private:
  // Visits a function, recursively visiting its callees. Adds this ID
  // to the visit_order after all callees have been visited.
  void Visit(uint32_t func_id) {
    if (visited_.count(func_id)) {
      return;
    }
    visited_.insert(func_id);
    for (auto callee_id : calls_[func_id]) {
      Visit(callee_id);
    }
    visit_order_.push_back(func_id);
  }

  // Maps the ID of a function to the IDs of functions it calls.
  std::unordered_map<uint32_t, std::unordered_set<uint32_t>> calls_;

  // IDs of visited functions;
  std::unordered_set<uint32_t> visited_;
  // IDs of functions, where callees precede callers.
  std::vector<uint32_t> visit_order_;
};

// Returns vector binding info for all resource variables in the module.
auto GetVarBindings(IRContext& context) {
  std::vector<VarBindingInfo> vars;
  auto* deco_mgr = context.get_decoration_mgr();
  for (auto& inst : context.module()->types_values()) {
    if (inst.opcode() == spv::Op::OpVariable) {
      Instruction* descriptor_set_deco = nullptr;
      Instruction* binding_deco = nullptr;
      for (auto* deco : deco_mgr->GetDecorationsFor(inst.result_id(), false)) {
        switch (static_cast<spv::Decoration>(deco->GetSingleWordInOperand(1))) {
          case spv::Decoration::DescriptorSet:
            assert(!descriptor_set_deco);
            descriptor_set_deco = deco;
            break;
          case spv::Decoration::Binding:
            assert(!binding_deco);
            binding_deco = deco;
            break;
          default:
            break;
        }
      }
      if (descriptor_set_deco && binding_deco) {
        vars.push_back({&inst, descriptor_set_deco->GetSingleWordInOperand(2),
                        binding_deco});
      }
    }
  }
  return vars;
}

// Merges the bindings from source into sink. Maintains order and uniqueness
// within a list of bindings.
void Merge(DescriptorSets& sink, const DescriptorSets& source) {
  for (auto index_and_bindings : source) {
    const uint32_t index = index_and_bindings.first;
    const BindingList& src1 = index_and_bindings.second;
    const BindingList& src2 = sink[index];
    BindingList merged;
    merged.resize(src1.size() + src2.size());
    auto merged_end = std::merge(src1.begin(), src1.end(), src2.begin(),
                                 src2.end(), merged.begin(), Less);
    auto unique_end = std::unique(merged.begin(), merged_end);
    merged.resize(unique_end - merged.begin());
    sink[index] = std::move(merged);
  }
}

// Resolves conflicts within this binding list, so the binding number on an
// item is at least one more than the binding number on the previous item.
// When this does not yet hold, increase the binding number on the second
// item in the pair. Returns true if any changes were applied.
bool ResolveConflicts(BindingList& bl) {
  bool changed = false;
  for (size_t i = 1; i < bl.size(); i++) {
    const auto prev_num = bl[i - 1]->binding();
    if (prev_num >= bl[i]->binding()) {
      bl[i]->updateBinding(prev_num + 1);
      changed = true;
    }
  }
  return changed;
}

Pass::Status ResolveBindingConflictsPass::Process() {
  // Assumes the descriptor set and binding decorations are not provided
  // via decoration groups.  Decoration groups were deprecated in SPIR-V 1.3
  // Revision 6.  I have not seen any compiler generate them. --dneto

  auto vars = GetVarBindings(*context());

  // Maps a function ID to the variables used directly or indirectly by the
  // function, organized into descriptor sets. Each descriptor set
  // consists of a BindingList of distinct variables.
  std::unordered_map<uint32_t, DescriptorSets> used_vars;

  // Determine variables directly used by functions.
  auto* def_use_mgr = context()->get_def_use_mgr();
  for (auto& var : vars) {
    std::unordered_set<uint32_t> visited_functions_for_var;
    def_use_mgr->ForEachUser(var.var, [&](Instruction* user) {
      if (auto* block = context()->get_instr_block(user)) {
        auto* fn = block->GetParent();
        assert(fn);
        const auto fn_id = fn->result_id();
        if (visited_functions_for_var.insert(fn_id).second) {
          used_vars[fn_id][var.descriptor_set].push_back(&var);
        }
      }
    });
  }

  // Sort within a descriptor set by binding number.
  for (auto& sets_for_fn : used_vars) {
    for (auto& ds : sets_for_fn.second) {
      BindingList& bindings = ds.second;
      std::stable_sort(bindings.begin(), bindings.end(), Less);
    }
  }

  // Propagate from callees to callers.
  CallGraph call_graph(*context());
  for (const uint32_t caller : call_graph.CalleesBeforeCallers()) {
    DescriptorSets& caller_ds = used_vars[caller];
    for (const uint32_t callee : call_graph.Callees(caller)) {
      Merge(caller_ds, used_vars[callee]);
    }
  }

  // At this point, the descriptor sets associated with each entry point
  // capture exactly the set of resource variables statically used
  // by the static call tree of that entry point.

  // Resolve conflicts.
  // VarBindingInfo objects may be shared between the bindings lists.
  // Updating a binding in one list can require updating another list later.
  // So repeat updates until settling.

  // The union of BindingLists across all entry points.
  std::vector<BindingList*> ep_bindings;

  for (auto& ep : context()->module()->entry_points()) {
    for (auto& ds : used_vars[ep.GetSingleWordInOperand(1)]) {
      BindingList& bindings = ds.second;
      ep_bindings.push_back(&bindings);
    }
  }
  bool modified = false;
  bool found_conflict;
  do {
    found_conflict = false;
    for (BindingList* bl : ep_bindings) {
      found_conflict |= ResolveConflicts(*bl);
    }
    modified |= found_conflict;
  } while (found_conflict);

  return modified ? Pass::Status::SuccessWithChange
                  : Pass::Status::SuccessWithoutChange;
}

}  // namespace opt
}  // namespace spvtools