reduction_util.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright (c) 2018 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. #include "source/reduce/reduction_util.h"
  15. #include "source/opt/ir_context.h"
  16. namespace spvtools {
  17. namespace reduce {
  18. using opt::IRContext;
  19. using opt::Instruction;
  20. const uint32_t kTrueBranchOperandIndex = 1;
  21. const uint32_t kFalseBranchOperandIndex = 2;
  22. uint32_t FindOrCreateGlobalUndef(IRContext* context, uint32_t type_id) {
  23. for (auto& inst : context->module()->types_values()) {
  24. if (inst.opcode() != SpvOpUndef) {
  25. continue;
  26. }
  27. if (inst.type_id() == type_id) {
  28. return inst.result_id();
  29. }
  30. }
  31. // TODO(2182): this is adapted from MemPass::Type2Undef. In due course it
  32. // would be good to factor out this duplication.
  33. const uint32_t undef_id = context->TakeNextId();
  34. std::unique_ptr<Instruction> undef_inst(
  35. new Instruction(context, SpvOpUndef, type_id, undef_id, {}));
  36. assert(undef_id == undef_inst->result_id());
  37. context->module()->AddGlobalValue(std::move(undef_inst));
  38. return undef_id;
  39. }
  40. void AdaptPhiInstructionsForRemovedEdge(uint32_t from_id,
  41. opt::BasicBlock* to_block) {
  42. to_block->ForEachPhiInst([&from_id](Instruction* phi_inst) {
  43. Instruction::OperandList new_in_operands;
  44. // Go through the OpPhi's input operands in (variable, parent) pairs.
  45. for (uint32_t index = 0; index < phi_inst->NumInOperands(); index += 2) {
  46. // Keep all pairs where the parent is not the block from which the edge
  47. // is being removed.
  48. if (phi_inst->GetInOperand(index + 1).words[0] != from_id) {
  49. new_in_operands.push_back(phi_inst->GetInOperand(index));
  50. new_in_operands.push_back(phi_inst->GetInOperand(index + 1));
  51. }
  52. }
  53. phi_inst->SetInOperands(std::move(new_in_operands));
  54. });
  55. }
  56. } // namespace reduce
  57. } // namespace spvtools