#include "source/reduce/reduction_util.h"
#include "source/opt/ir_context.h"
#include "source/util/make_unique.h"
namespace spvtools {
namespace reduce {
const uint32_t kTrueBranchOperandIndex = 1;
const uint32_t kFalseBranchOperandIndex = 2;
uint32_t FindOrCreateGlobalVariable(opt::IRContext* context,
uint32_t pointer_type_id) {
for (auto& inst : context->module()->types_values()) {
if (inst.opcode() != spv::Op::OpVariable) {
continue;
}
if (inst.type_id() == pointer_type_id) {
return inst.result_id();
}
}
const uint32_t variable_id = context->TakeNextId();
auto variable_inst = MakeUnique<opt::Instruction>(
context, spv::Op::OpVariable, pointer_type_id, variable_id,
opt::Instruction::OperandList(
{{SPV_OPERAND_TYPE_STORAGE_CLASS,
{static_cast<uint32_t>(context->get_type_mgr()
->GetType(pointer_type_id)
->AsPointer()
->storage_class())}}}));
context->module()->AddGlobalValue(std::move(variable_inst));
return variable_id;
}
uint32_t FindOrCreateFunctionVariable(opt::IRContext* context,
opt::Function* function,
uint32_t pointer_type_id) {
assert(context->get_type_mgr()
->GetType(pointer_type_id)
->AsPointer()
->storage_class() == spv::StorageClass::Function);
opt::BasicBlock::iterator iter = function->begin()->begin();
for (;; ++iter) {
assert(iter != function->begin()->end());
if (iter->opcode() != spv::Op::OpVariable) {
break;
}
if (iter->type_id() == pointer_type_id) {
return iter->result_id();
}
}
const uint32_t variable_id = context->TakeNextId();
auto variable_inst = MakeUnique<opt::Instruction>(
context, spv::Op::OpVariable, pointer_type_id, variable_id,
opt::Instruction::OperandList(
{{SPV_OPERAND_TYPE_STORAGE_CLASS,
{uint32_t(spv::StorageClass::Function)}}}));
iter->InsertBefore(std::move(variable_inst));
return variable_id;
}
uint32_t FindOrCreateGlobalUndef(opt::IRContext* context, uint32_t type_id) {
for (auto& inst : context->module()->types_values()) {
if (inst.opcode() != spv::Op::OpUndef) {
continue;
}
if (inst.type_id() == type_id) {
return inst.result_id();
}
}
const uint32_t undef_id = context->TakeNextId();
auto undef_inst =
MakeUnique<opt::Instruction>(context, spv::Op::OpUndef, type_id, undef_id,
opt::Instruction::OperandList());
assert(undef_id == undef_inst->result_id());
context->module()->AddGlobalValue(std::move(undef_inst));
return undef_id;
}
void AdaptPhiInstructionsForRemovedEdge(uint32_t from_id,
opt::BasicBlock* to_block) {
to_block->ForEachPhiInst([&from_id](opt::Instruction* phi_inst) {
opt::Instruction::OperandList new_in_operands;
for (uint32_t index = 0; index < phi_inst->NumInOperands(); index += 2) {
if (phi_inst->GetInOperand(index + 1).words[0] != from_id) {
new_in_operands.push_back(phi_inst->GetInOperand(index));
new_in_operands.push_back(phi_inst->GetInOperand(index + 1));
}
}
phi_inst->SetInOperands(std::move(new_in_operands));
});
}
}
}