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