1 // Copyright (c) 2020 André Perez Maselco
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/transformation_swap_commutable_operands.h"
16
17 #include "source/fuzz/fuzzer_util.h"
18 #include "source/fuzz/instruction_descriptor.h"
19
20 namespace spvtools {
21 namespace fuzz {
22
TransformationSwapCommutableOperands(const spvtools::fuzz::protobufs::TransformationSwapCommutableOperands & message)23 TransformationSwapCommutableOperands::TransformationSwapCommutableOperands(
24 const spvtools::fuzz::protobufs::TransformationSwapCommutableOperands&
25 message)
26 : message_(message) {}
27
TransformationSwapCommutableOperands(const protobufs::InstructionDescriptor & instruction_descriptor)28 TransformationSwapCommutableOperands::TransformationSwapCommutableOperands(
29 const protobufs::InstructionDescriptor& instruction_descriptor) {
30 *message_.mutable_instruction_descriptor() = instruction_descriptor;
31 }
32
IsApplicable(opt::IRContext * ir_context,const TransformationContext &) const33 bool TransformationSwapCommutableOperands::IsApplicable(
34 opt::IRContext* ir_context, const TransformationContext& /*unused*/
35 ) const {
36 auto instruction =
37 FindInstruction(message_.instruction_descriptor(), ir_context);
38 if (instruction == nullptr) return false;
39
40 SpvOp opcode = static_cast<SpvOp>(
41 message_.instruction_descriptor().target_instruction_opcode());
42 assert(instruction->opcode() == opcode &&
43 "The located instruction must have the same opcode as in the "
44 "descriptor.");
45 return spvOpcodeIsCommutativeBinaryOperator(opcode);
46 }
47
Apply(opt::IRContext * ir_context,TransformationContext *) const48 void TransformationSwapCommutableOperands::Apply(
49 opt::IRContext* ir_context, TransformationContext* /*unused*/
50 ) const {
51 auto instruction =
52 FindInstruction(message_.instruction_descriptor(), ir_context);
53 // By design, the instructions defined to be commutative have exactly two
54 // input parameters.
55 std::swap(instruction->GetInOperand(0), instruction->GetInOperand(1));
56 }
57
ToMessage() const58 protobufs::Transformation TransformationSwapCommutableOperands::ToMessage()
59 const {
60 protobufs::Transformation result;
61 *result.mutable_swap_commutable_operands() = message_;
62 return result;
63 }
64
65 } // namespace fuzz
66 } // namespace spvtools
67