workaround1209.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright (c) 2018 Google Inc.
  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/opt/workaround1209.h"
  15. #include <list>
  16. #include <memory>
  17. #include <stack>
  18. #include <utility>
  19. namespace spvtools {
  20. namespace opt {
  21. Pass::Status Workaround1209::Process() {
  22. bool modified = false;
  23. modified = RemoveOpUnreachableInLoops();
  24. return (modified ? Status::SuccessWithChange : Status::SuccessWithoutChange);
  25. }
  26. bool Workaround1209::RemoveOpUnreachableInLoops() {
  27. bool modified = false;
  28. for (auto& func : *get_module()) {
  29. std::list<BasicBlock*> structured_order;
  30. cfg()->ComputeStructuredOrder(&func, &*func.begin(), &structured_order);
  31. // Keep track of the loop merges. The top of the stack will always be the
  32. // loop merge for the loop that immediately contains the basic block being
  33. // processed.
  34. std::stack<uint32_t> loop_merges;
  35. for (BasicBlock* bb : structured_order) {
  36. if (!loop_merges.empty() && bb->id() == loop_merges.top()) {
  37. loop_merges.pop();
  38. }
  39. if (bb->tail()->opcode() == spv::Op::OpUnreachable) {
  40. if (!loop_merges.empty()) {
  41. // We found an OpUnreachable inside a loop.
  42. // Replace it with an unconditional branch to the loop merge.
  43. context()->KillInst(&*bb->tail());
  44. std::unique_ptr<Instruction> new_branch(
  45. new Instruction(context(), spv::Op::OpBranch, 0, 0,
  46. {{spv_operand_type_t::SPV_OPERAND_TYPE_ID,
  47. {loop_merges.top()}}}));
  48. context()->AnalyzeDefUse(&*new_branch);
  49. bb->AddInstruction(std::move(new_branch));
  50. modified = true;
  51. }
  52. } else {
  53. if (bb->GetLoopMergeInst()) {
  54. loop_merges.push(bb->MergeBlockIdIfAny());
  55. }
  56. }
  57. }
  58. }
  59. return modified;
  60. }
  61. } // namespace opt
  62. } // namespace spvtools