Coverage Report

Created: 2026-12-01 07:22

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
1.08k
    : id_(function_id),
38
1.08k
      function_type_id_(function_type_id),
39
1.08k
      result_type_id_(result_type_id),
40
1.08k
      function_control_(function_control),
41
1.08k
      declaration_type_(FunctionDecl::kFunctionDeclUnknown),
42
1.08k
      end_has_been_registered_(false),
43
1.08k
      blocks_(),
44
1.08k
      current_block_(nullptr),
45
1.08k
      pseudo_entry_block_(0),
46
1.08k
      pseudo_exit_block_(kInvalidId),
47
1.08k
      cfg_constructs_(),
48
1.08k
      variable_ids_(),
49
1.08k
      parameter_ids_() {}
50
51
13.3k
bool Function::IsFirstBlock(uint32_t block_id) const {
52
13.3k
  return !ordered_blocks_.empty() && *first_block() == block_id;
53
13.3k
}
54
55
spv_result_t Function::RegisterFunctionParameter(uint32_t parameter_id,
56
1.15k
                                                 uint32_t type_id) {
57
1.15k
  assert(current_block_ == nullptr &&
58
1.15k
         "RegisterFunctionParameter can only be called when parsing the binary "
59
1.15k
         "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
1.15k
  (void)parameter_id;
63
1.15k
  (void)type_id;
64
1.15k
  return SPV_SUCCESS;
65
1.15k
}
66
67
spv_result_t Function::RegisterLoopMerge(uint32_t merge_id,
68
630
                                         uint32_t continue_id) {
69
630
  RegisterBlock(merge_id, false);
70
630
  RegisterBlock(continue_id, false);
71
630
  BasicBlock& merge_block = blocks_.at(merge_id);
72
630
  BasicBlock& continue_target_block = blocks_.at(continue_id);
73
630
  assert(current_block_ &&
74
630
         "RegisterLoopMerge must be called when called within a block");
75
630
  current_block_->RegisterStructuralSuccessor(&merge_block);
76
630
  current_block_->RegisterStructuralSuccessor(&continue_target_block);
77
78
630
  current_block_->set_type(kBlockTypeLoop);
79
630
  merge_block.set_type(kBlockTypeMerge);
80
630
  continue_target_block.set_type(kBlockTypeContinue);
81
630
  Construct& loop_construct =
82
630
      AddConstruct({ConstructType::kLoop, current_block_, &merge_block});
83
630
  Construct& continue_construct =
84
630
      AddConstruct({ConstructType::kContinue, &continue_target_block});
85
86
630
  continue_construct.set_corresponding_constructs({&loop_construct});
87
630
  loop_construct.set_corresponding_constructs({&continue_construct});
88
630
  merge_block_header_[&merge_block] = current_block_;
89
630
  if (continue_target_headers_.find(&continue_target_block) ==
90
630
      continue_target_headers_.end()) {
91
630
    continue_target_headers_[&continue_target_block] = {current_block_};
92
630
  } else {
93
0
    continue_target_headers_[&continue_target_block].push_back(current_block_);
94
0
  }
95
96
630
  return SPV_SUCCESS;
97
630
}
98
99
2.70k
spv_result_t Function::RegisterSelectionMerge(uint32_t merge_id) {
100
2.70k
  RegisterBlock(merge_id, false);
101
2.70k
  BasicBlock& merge_block = blocks_.at(merge_id);
102
2.70k
  current_block_->set_type(kBlockTypeSelection);
103
2.70k
  merge_block.set_type(kBlockTypeMerge);
104
2.70k
  merge_block_header_[&merge_block] = current_block_;
105
2.70k
  current_block_->RegisterStructuralSuccessor(&merge_block);
106
107
2.70k
  AddConstruct({ConstructType::kSelection, current_block(), &merge_block});
108
109
2.70k
  return SPV_SUCCESS;
110
2.70k
}
111
112
1.08k
spv_result_t Function::RegisterSetFunctionDeclType(FunctionDecl type) {
113
1.08k
  assert(declaration_type_ == FunctionDecl::kFunctionDeclUnknown);
114
1.08k
  declaration_type_ = type;
115
1.08k
  return SPV_SUCCESS;
116
1.08k
}
117
118
14.4k
spv_result_t Function::RegisterBlock(uint32_t block_id, bool is_definition) {
119
14.4k
  assert(
120
14.4k
      declaration_type_ == FunctionDecl::kFunctionDeclDefinition &&
121
14.4k
      "RegisterBlocks can only be called after declaration_type_ is defined");
122
123
14.4k
  std::unordered_map<uint32_t, BasicBlock>::iterator inserted_block;
124
14.4k
  bool success = false;
125
14.4k
  tie(inserted_block, success) =
126
14.4k
      blocks_.insert({block_id, BasicBlock(block_id)});
127
14.4k
  if (is_definition) {  // new block definition
128
10.4k
    assert(current_block_ == nullptr &&
129
10.4k
           "Register Block can only be called when parsing a binary outside of "
130
10.4k
           "a BasicBlock");
131
132
10.4k
    undefined_blocks_.erase(block_id);
133
10.4k
    current_block_ = &inserted_block->second;
134
10.4k
    ordered_blocks_.push_back(current_block_);
135
10.4k
  } else if (success) {  // Block doesn't exist but this is not a definition
136
3.96k
    undefined_blocks_.insert(block_id);
137
3.96k
  }
138
139
14.4k
  return SPV_SUCCESS;
140
14.4k
}
141
142
10.4k
void Function::RegisterBlockEnd(std::vector<uint32_t> next_list) {
143
10.4k
  assert(
144
10.4k
      current_block_ &&
145
10.4k
      "RegisterBlockEnd can only be called when parsing a binary in a block");
146
10.4k
  std::vector<BasicBlock*> next_blocks;
147
10.4k
  next_blocks.reserve(next_list.size());
148
149
10.4k
  std::unordered_map<uint32_t, BasicBlock>::iterator inserted_block;
150
10.4k
  bool success;
151
13.3k
  for (uint32_t successor_id : next_list) {
152
13.3k
    tie(inserted_block, success) =
153
13.3k
        blocks_.insert({successor_id, BasicBlock(successor_id)});
154
13.3k
    if (success) {
155
5.42k
      undefined_blocks_.insert(successor_id);
156
5.42k
    }
157
13.3k
    next_blocks.push_back(&inserted_block->second);
158
13.3k
  }
159
160
10.4k
  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
622
    std::vector<BasicBlock*>& next_blocks_plus_continue_target =
165
622
        loop_header_successors_plus_continue_target_map_[current_block_];
166
622
    next_blocks_plus_continue_target = next_blocks;
167
622
    auto continue_target =
168
622
        FindConstructForEntryBlock(current_block_, ConstructType::kLoop)
169
622
            .corresponding_constructs()
170
622
            .back()
171
622
            ->entry_block();
172
622
    if (continue_target != current_block_) {
173
622
      next_blocks_plus_continue_target.push_back(continue_target);
174
622
    }
175
622
  }
176
177
10.4k
  current_block_->RegisterSuccessors(next_blocks);
178
10.4k
  current_block_ = nullptr;
179
10.4k
  return;
180
10.4k
}
181
182
1.08k
void Function::RegisterFunctionEnd() {
183
1.08k
  if (!end_has_been_registered_) {
184
1.08k
    end_has_been_registered_ = true;
185
186
1.08k
    ComputeAugmentedCFG();
187
1.08k
  }
188
1.08k
}
189
190
3.27k
size_t Function::block_count() const { return blocks_.size(); }
191
192
1.04k
size_t Function::undefined_block_count() const {
193
1.04k
  return undefined_blocks_.size();
194
1.04k
}
195
196
0
const std::vector<BasicBlock*>& Function::ordered_blocks() const {
197
0
  return ordered_blocks_;
198
0
}
199
4.17k
std::vector<BasicBlock*>& Function::ordered_blocks() { return ordered_blocks_; }
200
201
277k
const BasicBlock* Function::current_block() const { return current_block_; }
202
162k
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
2.08k
std::list<Construct>& Function::constructs() { return cfg_constructs_; }
208
209
13.3k
const BasicBlock* Function::first_block() const {
210
13.3k
  if (ordered_blocks_.empty()) return nullptr;
211
13.3k
  return ordered_blocks_[0];
212
13.3k
}
213
4.24k
BasicBlock* Function::first_block() {
214
4.24k
  if (ordered_blocks_.empty()) return nullptr;
215
4.24k
  return ordered_blocks_[0];
216
4.24k
}
217
218
3.95k
bool Function::IsBlockType(uint32_t merge_block_id, BlockType type) const {
219
3.95k
  bool ret = false;
220
3.95k
  const BasicBlock* block;
221
3.95k
  std::tie(block, std::ignore) = GetBlock(merge_block_id);
222
3.95k
  if (block) {
223
614
    ret = block->is_type(type);
224
614
  }
225
3.95k
  return ret;
226
3.95k
}
227
228
8.73k
std::pair<const BasicBlock*, bool> Function::GetBlock(uint32_t block_id) const {
229
8.73k
  const auto b = blocks_.find(block_id);
230
8.73k
  if (b != end(blocks_)) {
231
5.40k
    const BasicBlock* block = &(b->second);
232
5.40k
    bool defined =
233
5.40k
        undefined_blocks_.find(block->id()) == std::end(undefined_blocks_);
234
5.40k
    return std::make_pair(block, defined);
235
5.40k
  } else {
236
3.33k
    return std::make_pair(nullptr, false);
237
3.33k
  }
238
8.73k
}
239
240
4.09k
std::pair<BasicBlock*, bool> Function::GetBlock(uint32_t block_id) {
241
4.09k
  const BasicBlock* out;
242
4.09k
  bool defined;
243
4.09k
  std::tie(out, defined) =
244
4.09k
      const_cast<const Function*>(this)->GetBlock(block_id);
245
4.09k
  return std::make_pair(const_cast<BasicBlock*>(out), defined);
246
4.09k
}
247
248
1.04k
Function::GetBlocksFunction Function::AugmentedCFGSuccessorsFunction() const {
249
37.3k
  return [this](const BasicBlock* block) {
250
37.3k
    auto where = augmented_successors_map_.find(block);
251
37.3k
    return where == augmented_successors_map_.end() ? block->successors()
252
37.3k
                                                    : &(*where).second;
253
37.3k
  };
254
1.04k
}
255
256
1.04k
Function::GetBlocksFunction Function::AugmentedCFGPredecessorsFunction() const {
257
20.7k
  return [this](const BasicBlock* block) {
258
20.7k
    auto where = augmented_predecessors_map_.find(block);
259
20.7k
    return where == augmented_predecessors_map_.end() ? block->predecessors()
260
20.7k
                                                      : &(*where).second;
261
20.7k
  };
262
1.04k
}
263
264
Function::GetBlocksFunction Function::AugmentedStructuralCFGSuccessorsFunction()
265
3.13k
    const {
266
108k
  return [this](const BasicBlock* block) {
267
108k
    auto where = augmented_successors_map_.find(block);
268
108k
    return where == augmented_successors_map_.end()
269
108k
               ? block->structural_successors()
270
108k
               : &(*where).second;
271
108k
  };
272
3.13k
}
273
274
Function::GetBlocksFunction
275
2.08k
Function::AugmentedStructuralCFGPredecessorsFunction() const {
276
65.1k
  return [this](const BasicBlock* block) {
277
65.1k
    auto where = augmented_predecessors_map_.find(block);
278
65.1k
    return where == augmented_predecessors_map_.end()
279
65.1k
               ? block->structural_predecessors()
280
65.1k
               : &(*where).second;
281
65.1k
  };
282
2.08k
}
283
284
1.08k
void Function::ComputeAugmentedCFG() {
285
  // Compute the successors of the pseudo-entry block, and
286
  // the predecessors of the pseudo exit block.
287
49.7k
  auto succ_func = [](const BasicBlock* b) {
288
49.7k
    return b->structural_successors();
289
49.7k
  };
290
49.8k
  auto pred_func = [](const BasicBlock* b) {
291
49.8k
    return b->structural_predecessors();
292
49.8k
  };
293
1.08k
  CFA<BasicBlock>::ComputeAugmentedCFG(
294
1.08k
      ordered_blocks_, &pseudo_entry_block_, &pseudo_exit_block_,
295
1.08k
      &augmented_successors_map_, &augmented_predecessors_map_, succ_func,
296
1.08k
      pred_func);
297
1.08k
}
298
299
3.96k
Construct& Function::AddConstruct(const Construct& new_construct) {
300
3.96k
  cfg_constructs_.push_back(new_construct);
301
3.96k
  auto& result = cfg_constructs_.back();
302
3.96k
  entry_block_to_construct_[std::make_pair(new_construct.entry_block(),
303
3.96k
                                           new_construct.type())] = &result;
304
3.96k
  return result;
305
3.96k
}
306
307
Construct& Function::FindConstructForEntryBlock(const BasicBlock* entry_block,
308
622
                                                ConstructType type) {
309
622
  auto where =
310
622
      entry_block_to_construct_.find(std::make_pair(entry_block, type));
311
622
  assert(where != entry_block_to_construct_.end());
312
622
  auto construct_ptr = (*where).second;
313
622
  assert(construct_ptr);
314
622
  return *construct_ptr;
315
622
}
316
317
19.6k
int Function::GetBlockDepth(BasicBlock* bb) {
318
  // Guard against nullptr.
319
19.6k
  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
19.6k
  if (block_depth_.find(bb) != block_depth_.end()) {
325
9.32k
    return block_depth_[bb];
326
9.32k
  }
327
  // Avoid recursion. Something is wrong if the same block is encountered
328
  // multiple times.
329
10.3k
  block_depth_[bb] = 0;
330
331
10.3k
  BasicBlock* bb_dom = bb->immediate_dominator();
332
10.3k
  if (!bb_dom || bb == bb_dom) {
333
    // This block has no dominator, so it's at depth 0.
334
1.04k
    block_depth_[bb] = 0;
335
9.32k
  } 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
614
    Construct* continue_construct =
341
614
        entry_block_to_construct_[std::make_pair(bb, ConstructType::kContinue)];
342
614
    assert(continue_construct);
343
    // Continue construct has only 1 corresponding construct (loop header).
344
614
    Construct* loop_construct =
345
614
        continue_construct->corresponding_constructs()[0];
346
614
    assert(loop_construct);
347
614
    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
614
    if (loop_header == bb) {
352
0
      block_depth_[bb] = 1 + GetBlockDepth(bb_dom);
353
614
    } else {
354
614
      block_depth_[bb] = 1 + GetBlockDepth(loop_header);
355
614
    }
356
8.70k
  } else if (bb->is_type(kBlockTypeMerge)) {
357
    // If this is a merge block, its depth is equal to the block before
358
    // branching.
359
3.32k
    BasicBlock* header = merge_block_header_[bb];
360
3.32k
    assert(header);
361
3.32k
    block_depth_[bb] = GetBlockDepth(header);
362
5.38k
  } else if (bb_dom->is_type(kBlockTypeSelection) ||
363
4.16k
             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
4.16k
    block_depth_[bb] = 1 + GetBlockDepth(bb_dom);
367
4.16k
  } else {
368
1.22k
    block_depth_[bb] = GetBlockDepth(bb_dom);
369
1.22k
  }
370
10.3k
  return block_depth_[bb];
371
19.6k
}
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
1.04k
                                              std::string* reason) const {
389
1.04k
  bool return_value = true;
390
1.04k
  std::stringstream ss_reason;
391
392
5.61k
  for (const auto& is_compatible : execution_model_limitations_) {
393
5.61k
    std::string message;
394
5.61k
    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
5.61k
  }
402
403
1.04k
  if (!return_value && reason) {
404
0
    *reason = ss_reason.str();
405
0
  }
406
407
1.04k
  return return_value;
408
1.04k
}
409
410
bool Function::CheckLimitations(const ValidationState_t& _,
411
                                const Function* entry_point,
412
1.04k
                                std::string* reason) const {
413
1.04k
  bool return_value = true;
414
1.04k
  std::stringstream ss_reason;
415
416
1.04k
  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
1.04k
  if (!return_value && reason) {
428
0
    *reason = ss_reason.str();
429
0
  }
430
431
1.04k
  return return_value;
432
1.04k
}
433
434
void Function::RegisterExecutionModelLimitation(
435
5.68k
    std::function<bool(spv::ExecutionModel, std::string*)> is_compatible) {
436
5.68k
  execution_model_limitations_.push_back(is_compatible);
437
5.68k
}
438
439
void Function::RegisterLimitation(
440
    std::function<bool(const ValidationState_t& _, const Function*,
441
                       std::string*)>
442
0
        is_compatible) {
443
0
  limitations_.push_back(is_compatible);
444
0
}
445
446
2.13k
void Function::AddFunctionCallTarget(uint32_t call_target_id) {
447
2.13k
  function_call_targets_.insert(call_target_id);
448
2.13k
}
449
450
3.07k
const std::set<uint32_t> Function::function_call_targets() const {
451
3.07k
  return function_call_targets_;
452
3.07k
}
453
454
0
BasicBlock* Function::GetMergeHeader(BasicBlock* merge_block) {
455
0
  return merge_block_header_[merge_block];
456
0
}
457
458
std::vector<BasicBlock*> Function::GetContinueHeaders(
459
0
    BasicBlock* continue_target) {
460
0
  if (continue_target_headers_.find(continue_target) ==
461
0
      continue_target_headers_.end()) {
462
0
    return {};
463
0
  }
464
0
  return continue_target_headers_[continue_target];
465
0
}
466
467
}  // namespace val
468
}  // namespace spvtools