1 // Copyright (c) 2020 Google LLC
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/fuzz/fuzzer_pass_add_loop_preheaders.h"
16
17 #include "source/fuzz/fuzzer_util.h"
18 #include "source/fuzz/transformation_add_loop_preheader.h"
19
20 namespace spvtools {
21 namespace fuzz {
22
FuzzerPassAddLoopPreheaders(opt::IRContext * ir_context,TransformationContext * transformation_context,FuzzerContext * fuzzer_context,protobufs::TransformationSequence * transformations)23 FuzzerPassAddLoopPreheaders::FuzzerPassAddLoopPreheaders(
24 opt::IRContext* ir_context, TransformationContext* transformation_context,
25 FuzzerContext* fuzzer_context,
26 protobufs::TransformationSequence* transformations)
27 : FuzzerPass(ir_context, transformation_context, fuzzer_context,
28 transformations) {}
29
Apply()30 void FuzzerPassAddLoopPreheaders::Apply() {
31 for (auto& function : *GetIRContext()->module()) {
32 // Keep track of all the loop headers we want to add a preheader to.
33 std::vector<uint32_t> loop_header_ids_to_consider;
34 for (auto& block : function) {
35 // We only care about loop headers.
36 if (!block.IsLoopHeader()) {
37 continue;
38 }
39
40 // Randomly decide whether to consider this header.
41 if (!GetFuzzerContext()->ChoosePercentage(
42 GetFuzzerContext()->GetChanceOfAddingLoopPreheader())) {
43 continue;
44 }
45
46 // We exclude loop headers with just one predecessor (the back-edge block)
47 // because they are unreachable.
48 if (GetIRContext()->cfg()->preds(block.id()).size() < 2) {
49 continue;
50 }
51
52 loop_header_ids_to_consider.push_back(block.id());
53 }
54
55 for (uint32_t header_id : loop_header_ids_to_consider) {
56 // If not already present, add a preheader which is not also a loop
57 // header.
58 GetOrCreateSimpleLoopPreheader(header_id);
59 }
60 }
61 }
62
63 } // namespace fuzz
64 } // namespace spvtools
65