1 // Copyright (c) 2019 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/instruction_message.h"
16
17 #include "source/fuzz/fuzzer_util.h"
18
19 namespace spvtools {
20 namespace fuzz {
21
MakeInstructionMessage(SpvOp opcode,uint32_t result_type_id,uint32_t result_id,const opt::Instruction::OperandList & input_operands)22 protobufs::Instruction MakeInstructionMessage(
23 SpvOp opcode, uint32_t result_type_id, uint32_t result_id,
24 const opt::Instruction::OperandList& input_operands) {
25 protobufs::Instruction result;
26 result.set_opcode(opcode);
27 result.set_result_type_id(result_type_id);
28 result.set_result_id(result_id);
29 for (auto& operand : input_operands) {
30 auto operand_message = result.add_input_operand();
31 operand_message->set_operand_type(static_cast<uint32_t>(operand.type));
32 for (auto operand_word : operand.words) {
33 operand_message->add_operand_data(operand_word);
34 }
35 }
36 return result;
37 }
38
InstructionFromMessage(opt::IRContext * ir_context,const protobufs::Instruction & instruction_message)39 std::unique_ptr<opt::Instruction> InstructionFromMessage(
40 opt::IRContext* ir_context,
41 const protobufs::Instruction& instruction_message) {
42 // First, update the module's id bound with respect to the new instruction,
43 // if it has a result id.
44 if (instruction_message.result_id()) {
45 fuzzerutil::UpdateModuleIdBound(ir_context,
46 instruction_message.result_id());
47 }
48 // Now create a sequence of input operands from the input operand data in the
49 // protobuf message.
50 opt::Instruction::OperandList in_operands;
51 for (auto& operand_message : instruction_message.input_operand()) {
52 opt::Operand::OperandData operand_data;
53 for (auto& word : operand_message.operand_data()) {
54 operand_data.push_back(word);
55 }
56 in_operands.push_back(
57 {static_cast<spv_operand_type_t>(operand_message.operand_type()),
58 operand_data});
59 }
60 // Create and return the instruction.
61 return MakeUnique<opt::Instruction>(
62 ir_context, static_cast<SpvOp>(instruction_message.opcode()),
63 instruction_message.result_type_id(), instruction_message.result_id(),
64 in_operands);
65 }
66
67 } // namespace fuzz
68 } // namespace spvtools
69