Coverage Report

Created: 2026-06-04 06:49

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/shaderc/third_party/spirv-tools/source/val/function.cpp
Line
Count
Source
1
// Copyright (c) 2015-2016 The Khronos Group 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/val/function.h"
16
17
#include <algorithm>
18
#include <cassert>
19
#include <sstream>
20
#include <unordered_map>
21
#include <utility>
22
23
#include "source/cfa.h"
24
#include "source/val/basic_block.h"
25
#include "source/val/construct.h"
26
#include "source/val/validate.h"
27
28
namespace spvtools {
29
namespace val {
30
31
// Universal Limit of ResultID + 1
32
static const uint32_t kInvalidId = 0x400000;
33
34
Function::Function(uint32_t function_id, uint32_t result_type_id,
35
                   spv::FunctionControlMask function_control,
36
                   uint32_t function_type_id)
37
196
    : id_(function_id),
38
196
      function_type_id_(function_type_id),
39
196
      result_type_id_(result_type_id),
40
196
      function_control_(function_control),
41
196
      declaration_type_(FunctionDecl::kFunctionDeclUnknown),
42
196
      end_has_been_registered_(false),
43
196
      blocks_(),
44
196
      current_block_(nullptr),
45
196
      pseudo_entry_block_(0),
46
196
      pseudo_exit_block_(kInvalidId),
47
196
      cfg_constructs_(),
48
196
      variable_ids_(),
49
196
      parameter_ids_() {}
50
51
684
bool Function::IsFirstBlock(uint32_t block_id) const {
52
684
  return !ordered_blocks_.empty() && *first_block() == block_id;
53
684
}
54
55
spv_result_t Function::RegisterFunctionParameter(uint32_t parameter_id,
56
116
                                                 uint32_t type_id) {
57
116
  assert(current_block_ == nullptr &&
58
116
         "RegisterFunctionParameter can only be called when parsing the binary "
59
116
         "outside of a block");
60
  // TODO(umar): Validate function parameter type order and count
61
  // TODO(umar): Use these variables to validate parameter type
62
116
  (void)parameter_id;
63
116
  (void)type_id;
64
116
  return SPV_SUCCESS;
65
116
}
66
67
spv_result_t Function::RegisterLoopMerge(uint32_t merge_id,
68
36
                                         uint32_t continue_id) {
69
36
  RegisterBlock(merge_id, false);
70
36
  RegisterBlock(continue_id, false);
71
36
  BasicBlock& merge_block = blocks_.at(merge_id);
72
36
  BasicBlock& continue_target_block = blocks_.at(continue_id);
73
36
  assert(current_block_ &&
74
36
         "RegisterLoopMerge must be called when called within a block");
75
36
  current_block_->RegisterStructuralSuccessor(&merge_block);
76
36
  current_block_->RegisterStructuralSuccessor(&continue_target_block);
77
78
36
  current_block_->set_type(kBlockTypeLoop);
79
36
  merge_block.set_type(kBlockTypeMerge);
80
36
  continue_target_block.set_type(kBlockTypeContinue);
81
36
  Construct& loop_construct =
82
36
      AddConstruct({ConstructType::kLoop, current_block_, &merge_block});
83
36
  Construct& continue_construct =
84
36
      AddConstruct({ConstructType::kContinue, &continue_target_block});
85
86
36
  continue_construct.set_corresponding_constructs({&loop_construct});
87
36
  loop_construct.set_corresponding_constructs({&continue_construct});
88
36
  merge_block_header_[&merge_block] = current_block_;
89
36
  if (continue_target_headers_.find(&continue_target_block) ==
90
36
      continue_target_headers_.end()) {
91
36
    continue_target_headers_[&continue_target_block] = {current_block_};
92
36
  } else {
93
0
    continue_target_headers_[&continue_target_block].push_back(current_block_);
94
0
  }
95
96
36
  return SPV_SUCCESS;
97
36
}
98
99
152
spv_result_t Function::RegisterSelectionMerge(uint32_t merge_id) {
100
152
  RegisterBlock(merge_id, false);
101
152
  BasicBlock& merge_block = blocks_.at(merge_id);
102
152
  current_block_->set_type(kBlockTypeSelection);
103
152
  merge_block.set_type(kBlockTypeMerge);
104
152
  merge_block_header_[&merge_block] = current_block_;
105
152
  current_block_->RegisterStructuralSuccessor(&merge_block);
106
107
152
  AddConstruct({ConstructType::kSelection, current_block(), &merge_block});
108
109
152
  return SPV_SUCCESS;
110
152
}
111
112
196
spv_result_t Function::RegisterSetFunctionDeclType(FunctionDecl type) {
113
196
  assert(declaration_type_ == FunctionDecl::kFunctionDeclUnknown);
114
196
  declaration_type_ = type;
115
196
  return SPV_SUCCESS;
116
196
}
117
118
900
spv_result_t Function::RegisterBlock(uint32_t block_id, bool is_definition) {
119
900
  assert(
120
900
      declaration_type_ == FunctionDecl::kFunctionDeclDefinition &&
121
900
      "RegisterBlocks can only be called after declaration_type_ is defined");
122
123
900
  std::unordered_map<uint32_t, BasicBlock>::iterator inserted_block;
124
900
  bool success = false;
125
900
  tie(inserted_block, success) =
126
900
      blocks_.insert({block_id, BasicBlock(block_id)});
127
900
  if (is_definition) {  // new block definition
128
676
    assert(current_block_ == nullptr &&
129
676
           "Register Block can only be called when parsing a binary outside of "
130
676
           "a BasicBlock");
131
132
676
    undefined_blocks_.erase(block_id);
133
676
    current_block_ = &inserted_block->second;
134
676
    ordered_blocks_.push_back(current_block_);
135
676
  } else if (success) {  // Block doesn't exist but this is not a definition
136
224
    undefined_blocks_.insert(block_id);
137
224
  }
138
139
900
  return SPV_SUCCESS;
140
900
}
141
142
668
void Function::RegisterBlockEnd(std::vector<uint32_t> next_list) {
143
668
  assert(
144
668
      current_block_ &&
145
668
      "RegisterBlockEnd can only be called when parsing a binary in a block");
146
668
  std::vector<BasicBlock*> next_blocks;
147
668
  next_blocks.reserve(next_list.size());
148
149
668
  std::unordered_map<uint32_t, BasicBlock>::iterator inserted_block;
150
668
  bool success;
151
684
  for (uint32_t successor_id : next_list) {
152
684
    tie(inserted_block, success) =
153
684
        blocks_.insert({successor_id, BasicBlock(successor_id)});
154
684
    if (success) {
155
272
      undefined_blocks_.insert(successor_id);
156
272
    }
157
684
    next_blocks.push_back(&inserted_block->second);
158
684
  }
159
160
668
  if (current_block_->is_type(kBlockTypeLoop)) {
161
    // For each loop header, record the set of its successors, and include
162
    // its continue target if the continue target is not the loop header
163
    // itself.
164
28
    std::vector<BasicBlock*>& next_blocks_plus_continue_target =
165
28
        loop_header_successors_plus_continue_target_map_[current_block_];
166
28
    next_blocks_plus_continue_target = next_blocks;
167
28
    auto continue_target =
168
28
        FindConstructForEntryBlock(current_block_, ConstructType::kLoop)
169
28
            .corresponding_constructs()
170
28
            .back()
171
28
            ->entry_block();
172
28
    if (continue_target != current_block_) {
173
28
      next_blocks_plus_continue_target.push_back(continue_target);
174
28
    }
175
28
  }
176
177
668
  current_block_->RegisterSuccessors(next_blocks);
178
668
  current_block_ = nullptr;
179
668
  return;
180
668
}
181
182
188
void Function::RegisterFunctionEnd() {
183
188
  if (!end_has_been_registered_) {
184
188
    end_has_been_registered_ = true;
185
186
188
    ComputeAugmentedCFG();
187
188
  }
188
188
}
189
190
452
size_t Function::block_count() const { return blocks_.size(); }
191
192
148
size_t Function::undefined_block_count() const {
193
148
  return undefined_blocks_.size();
194
148
}
195
196
0
const std::vector<BasicBlock*>& Function::ordered_blocks() const {
197
0
  return ordered_blocks_;
198
0
}
199
592
std::vector<BasicBlock*>& Function::ordered_blocks() { return ordered_blocks_; }
200
201
24.8k
const BasicBlock* Function::current_block() const { return current_block_; }
202
13.9k
BasicBlock* Function::current_block() { return current_block_; }
203
204
0
const std::list<Construct>& Function::constructs() const {
205
0
  return cfg_constructs_;
206
0
}
207
296
std::list<Construct>& Function::constructs() { return cfg_constructs_; }
208
209
684
const BasicBlock* Function::first_block() const {
210
684
  if (ordered_blocks_.empty()) return nullptr;
211
684
  return ordered_blocks_[0];
212
684
}
213
672
BasicBlock* Function::first_block() {
214
672
  if (ordered_blocks_.empty()) return nullptr;
215
672
  return ordered_blocks_[0];
216
672
}
217
218
208
bool Function::IsBlockType(uint32_t merge_block_id, BlockType type) const {
219
208
  bool ret = false;
220
208
  const BasicBlock* block;
221
208
  std::tie(block, std::ignore) = GetBlock(merge_block_id);
222
208
  if (block) {
223
20
    ret = block->is_type(type);
224
20
  }
225
208
  return ret;
226
208
}
227
228
452
std::pair<const BasicBlock*, bool> Function::GetBlock(uint32_t block_id) const {
229
452
  const auto b = blocks_.find(block_id);
230
452
  if (b != end(blocks_)) {
231
264
    const BasicBlock* block = &(b->second);
232
264
    bool defined =
233
264
        undefined_blocks_.find(block->id()) == std::end(undefined_blocks_);
234
264
    return std::make_pair(block, defined);
235
264
  } else {
236
188
    return std::make_pair(nullptr, false);
237
188
  }
238
452
}
239
240
196
std::pair<BasicBlock*, bool> Function::GetBlock(uint32_t block_id) {
241
196
  const BasicBlock* out;
242
196
  bool defined;
243
196
  std::tie(out, defined) =
244
196
      const_cast<const Function*>(this)->GetBlock(block_id);
245
196
  return std::make_pair(const_cast<BasicBlock*>(out), defined);
246
196
}
247
248
148
Function::GetBlocksFunction Function::AugmentedCFGSuccessorsFunction() const {
249
2.23k
  return [this](const BasicBlock* block) {
250
2.23k
    auto where = augmented_successors_map_.find(block);
251
2.23k
    return where == augmented_successors_map_.end() ? block->successors()
252
2.23k
                                                    : &(*where).second;
253
2.23k
  };
254
148
}
255
256
148
Function::GetBlocksFunction Function::AugmentedCFGPredecessorsFunction() const {
257
1.16k
  return [this](const BasicBlock* block) {
258
1.16k
    auto where = augmented_predecessors_map_.find(block);
259
1.16k
    return where == augmented_predecessors_map_.end() ? block->predecessors()
260
1.16k
                                                      : &(*where).second;
261
1.16k
  };
262
148
}
263
264
Function::GetBlocksFunction Function::AugmentedStructuralCFGSuccessorsFunction()
265
444
    const {
266
6.75k
  return [this](const BasicBlock* block) {
267
6.75k
    auto where = augmented_successors_map_.find(block);
268
6.75k
    return where == augmented_successors_map_.end()
269
6.75k
               ? block->structural_successors()
270
6.75k
               : &(*where).second;
271
6.75k
  };
272
444
}
273
274
Function::GetBlocksFunction
275
296
Function::AugmentedStructuralCFGPredecessorsFunction() const {
276
4.03k
  return [this](const BasicBlock* block) {
277
4.03k
    auto where = augmented_predecessors_map_.find(block);
278
4.03k
    return where == augmented_predecessors_map_.end()
279
4.03k
               ? block->structural_predecessors()
280
4.03k
               : &(*where).second;
281
4.03k
  };
282
296
}
283
284
188
void Function::ComputeAugmentedCFG() {
285
  // Compute the successors of the pseudo-entry block, and
286
  // the predecessors of the pseudo exit block.
287
2.87k
  auto succ_func = [](const BasicBlock* b) {
288
2.87k
    return b->structural_successors();
289
2.87k
  };
290
2.87k
  auto pred_func = [](const BasicBlock* b) {
291
2.87k
    return b->structural_predecessors();
292
2.87k
  };
293
188
  CFA<BasicBlock>::ComputeAugmentedCFG(
294
188
      ordered_blocks_, &pseudo_entry_block_, &pseudo_exit_block_,
295
188
      &augmented_successors_map_, &augmented_predecessors_map_, succ_func,
296
188
      pred_func);
297
188
}
298
299
224
Construct& Function::AddConstruct(const Construct& new_construct) {
300
224
  cfg_constructs_.push_back(new_construct);
301
224
  auto& result = cfg_constructs_.back();
302
224
  entry_block_to_construct_[std::make_pair(new_construct.entry_block(),
303
224
                                           new_construct.type())] = &result;
304
224
  return result;
305
224
}
306
307
Construct& Function::FindConstructForEntryBlock(const BasicBlock* entry_block,
308
28
                                                ConstructType type) {
309
28
  auto where =
310
28
      entry_block_to_construct_.find(std::make_pair(entry_block, type));
311
28
  assert(where != entry_block_to_construct_.end());
312
28
  auto construct_ptr = (*where).second;
313
28
  assert(construct_ptr);
314
28
  return *construct_ptr;
315
28
}
316
317
1.01k
int Function::GetBlockDepth(BasicBlock* bb) {
318
  // Guard against nullptr.
319
1.01k
  if (!bb) {
320
0
    return 0;
321
0
  }
322
  // Only calculate the depth if it's not already calculated.
323
  // This function uses memoization to avoid duplicate CFG depth calculations.
324
1.01k
  if (block_depth_.find(bb) != block_depth_.end()) {
325
432
    return block_depth_[bb];
326
432
  }
327
  // Avoid recursion. Something is wrong if the same block is encountered
328
  // multiple times.
329
580
  block_depth_[bb] = 0;
330
331
580
  BasicBlock* bb_dom = bb->immediate_dominator();
332
580
  if (!bb_dom || bb == bb_dom) {
333
    // This block has no dominator, so it's at depth 0.
334
148
    block_depth_[bb] = 0;
335
432
  } else if (bb->is_type(kBlockTypeContinue)) {
336
    // This rule must precede the rule for merge blocks in order to set up
337
    // depths correctly. If a block is both a merge and continue then the merge
338
    // is nested within the continue's loop (or the graph is incorrect).
339
    // The depth of the continue block entry point is 1 + loop header depth.
340
20
    Construct* continue_construct =
341
20
        entry_block_to_construct_[std::make_pair(bb, ConstructType::kContinue)];
342
20
    assert(continue_construct);
343
    // Continue construct has only 1 corresponding construct (loop header).
344
20
    Construct* loop_construct =
345
20
        continue_construct->corresponding_constructs()[0];
346
20
    assert(loop_construct);
347
20
    BasicBlock* loop_header = loop_construct->entry_block();
348
    // The continue target may be the loop itself (while 1).
349
    // In such cases, the depth of the continue block is: 1 + depth of the
350
    // loop's dominator block.
351
20
    if (loop_header == bb) {
352
0
      block_depth_[bb] = 1 + GetBlockDepth(bb_dom);
353
20
    } else {
354
20
      block_depth_[bb] = 1 + GetBlockDepth(loop_header);
355
20
    }
356
412
  } else if (bb->is_type(kBlockTypeMerge)) {
357
    // If this is a merge block, its depth is equal to the block before
358
    // branching.
359
172
    BasicBlock* header = merge_block_header_[bb];
360
172
    assert(header);
361
172
    block_depth_[bb] = GetBlockDepth(header);
362
240
  } else if (bb_dom->is_type(kBlockTypeSelection) ||
363
200
             bb_dom->is_type(kBlockTypeLoop)) {
364
    // The dominator of the given block is a header block. So, the nesting
365
    // depth of this block is: 1 + nesting depth of the header.
366
200
    block_depth_[bb] = 1 + GetBlockDepth(bb_dom);
367
200
  } else {
368
40
    block_depth_[bb] = GetBlockDepth(bb_dom);
369
40
  }
370
580
  return block_depth_[bb];
371
1.01k
}
372
373
void Function::RegisterExecutionModelLimitation(spv::ExecutionModel model,
374
0
                                                const std::string& message) {
375
0
  execution_model_limitations_.push_back(
376
0
      [model, message](spv::ExecutionModel in_model, std::string* out_message) {
377
0
        if (model != in_model) {
378
0
          if (out_message) {
379
0
            *out_message = message;
380
0
          }
381
0
          return false;
382
0
        }
383
0
        return true;
384
0
      });
385
0
}
386
387
bool Function::IsCompatibleWithExecutionModel(spv::ExecutionModel model,
388
148
                                              std::string* reason) const {
389
148
  bool return_value = true;
390
148
  std::stringstream ss_reason;
391
392
148
  for (const auto& is_compatible : execution_model_limitations_) {
393
144
    std::string message;
394
144
    if (!is_compatible(model, &message)) {
395
0
      if (!reason) return false;
396
0
      return_value = false;
397
0
      if (!message.empty()) {
398
0
        ss_reason << message << "\n";
399
0
      }
400
0
    }
401
144
  }
402
403
148
  if (!return_value && reason) {
404
0
    *reason = ss_reason.str();
405
0
  }
406
407
148
  return return_value;
408
148
}
409
410
bool Function::CheckLimitations(const ValidationState_t& _,
411
                                const Function* entry_point,
412
148
                                std::string* reason) const {
413
148
  bool return_value = true;
414
148
  std::stringstream ss_reason;
415
416
148
  for (const auto& is_compatible : limitations_) {
417
0
    std::string message;
418
0
    if (!is_compatible(_, entry_point, &message)) {
419
0
      if (!reason) return false;
420
0
      return_value = false;
421
0
      if (!message.empty()) {
422
0
        ss_reason << message << "\n";
423
0
      }
424
0
    }
425
0
  }
426
427
148
  if (!return_value && reason) {
428
0
    *reason = ss_reason.str();
429
0
  }
430
431
148
  return return_value;
432
148
}
433
434
}  // namespace val
435
}  // namespace spvtools