File: fuzzer_pass_outline_functions.cpp

package info (click to toggle)
spirv-tools 2023.1-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 25,608 kB
  • sloc: cpp: 408,882; javascript: 5,890; python: 2,847; ansic: 403; sh: 385; ruby: 88; makefile: 17; lisp: 9
file content (195 lines) | stat: -rw-r--r-- 7,615 bytes parent folder | download | duplicates (15)
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
// Copyright (c) 2019 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/fuzz/fuzzer_pass_outline_functions.h"

#include <vector>

#include "source/fuzz/fuzzer_util.h"
#include "source/fuzz/instruction_descriptor.h"
#include "source/fuzz/transformation_outline_function.h"
#include "source/fuzz/transformation_split_block.h"

namespace spvtools {
namespace fuzz {

FuzzerPassOutlineFunctions::FuzzerPassOutlineFunctions(
    opt::IRContext* ir_context, TransformationContext* transformation_context,
    FuzzerContext* fuzzer_context,
    protobufs::TransformationSequence* transformations,
    bool ignore_inapplicable_transformations)
    : FuzzerPass(ir_context, transformation_context, fuzzer_context,
                 transformations, ignore_inapplicable_transformations) {}

void FuzzerPassOutlineFunctions::Apply() {
  std::vector<opt::Function*> original_functions;
  for (auto& function : *GetIRContext()->module()) {
    original_functions.push_back(&function);
  }
  for (auto& function : original_functions) {
    if (!GetFuzzerContext()->ChoosePercentage(
            GetFuzzerContext()->GetChanceOfOutliningFunction())) {
      continue;
    }
    std::vector<opt::BasicBlock*> blocks;
    for (auto& block : *function) {
      blocks.push_back(&block);
    }
    auto entry_block = MaybeGetEntryBlockSuitableForOutlining(
        blocks[GetFuzzerContext()->RandomIndex(blocks)]);

    if (!entry_block) {
      // The chosen block is not suitable to be the entry block of a region that
      // will be outlined.
      continue;
    }

    auto dominator_analysis = GetIRContext()->GetDominatorAnalysis(function);
    auto postdominator_analysis =
        GetIRContext()->GetPostDominatorAnalysis(function);
    std::vector<opt::BasicBlock*> candidate_exit_blocks;
    for (auto postdominates_entry_block = entry_block;
         postdominates_entry_block != nullptr;
         postdominates_entry_block = postdominator_analysis->ImmediateDominator(
             postdominates_entry_block)) {
      // Consider the block if it is dominated by the entry block, ignore it if
      // it is a continue target.
      if (dominator_analysis->Dominates(entry_block,
                                        postdominates_entry_block) &&
          !GetIRContext()->GetStructuredCFGAnalysis()->IsContinueBlock(
              postdominates_entry_block->id())) {
        candidate_exit_blocks.push_back(postdominates_entry_block);
      }
    }
    if (candidate_exit_blocks.empty()) {
      continue;
    }
    auto exit_block = MaybeGetExitBlockSuitableForOutlining(
        candidate_exit_blocks[GetFuzzerContext()->RandomIndex(
            candidate_exit_blocks)]);

    if (!exit_block) {
      // The block chosen is not suitable
      continue;
    }

    auto region_blocks = TransformationOutlineFunction::GetRegionBlocks(
        GetIRContext(), entry_block, exit_block);
    std::map<uint32_t, uint32_t> input_id_to_fresh_id;
    for (auto id : TransformationOutlineFunction::GetRegionInputIds(
             GetIRContext(), region_blocks, exit_block)) {
      input_id_to_fresh_id[id] = GetFuzzerContext()->GetFreshId();
    }
    std::map<uint32_t, uint32_t> output_id_to_fresh_id;
    for (auto id : TransformationOutlineFunction::GetRegionOutputIds(
             GetIRContext(), region_blocks, exit_block)) {
      output_id_to_fresh_id[id] = GetFuzzerContext()->GetFreshId();
    }
    TransformationOutlineFunction transformation(
        entry_block->id(), exit_block->id(),
        /*new_function_struct_return_type_id*/
        GetFuzzerContext()->GetFreshId(),
        /*new_function_type_id*/ GetFuzzerContext()->GetFreshId(),
        /*new_function_id*/ GetFuzzerContext()->GetFreshId(),
        /*new_function_region_entry_block*/
        GetFuzzerContext()->GetFreshId(),
        /*new_caller_result_id*/ GetFuzzerContext()->GetFreshId(),
        /*new_callee_result_id*/ GetFuzzerContext()->GetFreshId(),
        /*input_id_to_fresh_id*/ input_id_to_fresh_id,
        /*output_id_to_fresh_id*/ output_id_to_fresh_id);
    MaybeApplyTransformation(transformation);
  }
}

opt::BasicBlock*
FuzzerPassOutlineFunctions::MaybeGetEntryBlockSuitableForOutlining(
    opt::BasicBlock* entry_block) {
  // If the entry block is a loop header, we need to get or create its
  // preheader and make it the entry block, if possible.
  if (entry_block->IsLoopHeader()) {
    auto predecessors =
        GetIRContext()->cfg()->preds(entry_block->GetLabel()->result_id());

    if (predecessors.size() < 2) {
      // The header only has one predecessor (the back-edge block) and thus
      // it is unreachable. The block cannot be adjusted to be suitable for
      // outlining.
      return nullptr;
    }

    // Get or create a suitable preheader and make it become the entry block.
    entry_block =
        GetOrCreateSimpleLoopPreheader(entry_block->GetLabel()->result_id());
  }

  assert(!entry_block->IsLoopHeader() &&
         "The entry block cannot be a loop header at this point.");

  // If the entry block starts with OpPhi or OpVariable, try to split it.
  if (entry_block->begin()->opcode() == spv::Op::OpPhi ||
      entry_block->begin()->opcode() == spv::Op::OpVariable) {
    // Find the first non-OpPhi and non-OpVariable instruction.
    auto non_phi_or_var_inst = &*entry_block->begin();
    while (non_phi_or_var_inst->opcode() == spv::Op::OpPhi ||
           non_phi_or_var_inst->opcode() == spv::Op::OpVariable) {
      non_phi_or_var_inst = non_phi_or_var_inst->NextNode();
    }

    // Split the block.
    uint32_t new_block_id = GetFuzzerContext()->GetFreshId();
    ApplyTransformation(TransformationSplitBlock(
        MakeInstructionDescriptor(GetIRContext(), non_phi_or_var_inst),
        new_block_id));

    // The new entry block is the newly-created block.
    entry_block = &*entry_block->GetParent()->FindBlock(new_block_id);
  }

  return entry_block;
}

opt::BasicBlock*
FuzzerPassOutlineFunctions::MaybeGetExitBlockSuitableForOutlining(
    opt::BasicBlock* exit_block) {
  // The exit block must not be a continue target.
  assert(!GetIRContext()->GetStructuredCFGAnalysis()->IsContinueBlock(
             exit_block->id()) &&
         "A candidate exit block cannot be a continue target.");

  // If the exit block is a merge block, try to split it and return the second
  // block in the pair as the exit block.
  if (GetIRContext()->GetStructuredCFGAnalysis()->IsMergeBlock(
          exit_block->id())) {
    uint32_t new_block_id = GetFuzzerContext()->GetFreshId();

    // Find the first non-OpPhi instruction, after which to split.
    auto split_before = &*exit_block->begin();
    while (split_before->opcode() == spv::Op::OpPhi) {
      split_before = split_before->NextNode();
    }

    if (!MaybeApplyTransformation(TransformationSplitBlock(
            MakeInstructionDescriptor(GetIRContext(), split_before),
            new_block_id))) {
      return nullptr;
    }

    return &*exit_block->GetParent()->FindBlock(new_block_id);
  }

  return exit_block;
}

}  // namespace fuzz
}  // namespace spvtools