dominator_analysis.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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/opt/dominator_analysis.h"
  15. #include <unordered_set>
  16. #include "source/opt/ir_context.h"
  17. namespace spvtools {
  18. namespace opt {
  19. BasicBlock* DominatorAnalysisBase::CommonDominator(BasicBlock* b1,
  20. BasicBlock* b2) const {
  21. if (!b1 || !b2) return nullptr;
  22. std::unordered_set<BasicBlock*> seen;
  23. BasicBlock* block = b1;
  24. while (block && seen.insert(block).second) {
  25. block = ImmediateDominator(block);
  26. }
  27. block = b2;
  28. while (block && !seen.count(block)) {
  29. block = ImmediateDominator(block);
  30. }
  31. return block;
  32. }
  33. bool DominatorAnalysisBase::Dominates(Instruction* a, Instruction* b) const {
  34. if (!a || !b) {
  35. return false;
  36. }
  37. if (a == b) {
  38. return true;
  39. }
  40. BasicBlock* bb_a = a->context()->get_instr_block(a);
  41. BasicBlock* bb_b = b->context()->get_instr_block(b);
  42. if (bb_a != bb_b) {
  43. return tree_.Dominates(bb_a, bb_b);
  44. }
  45. Instruction* current_inst = a;
  46. while ((current_inst = current_inst->NextNode())) {
  47. if (current_inst == b) {
  48. return true;
  49. }
  50. }
  51. return false;
  52. }
  53. } // namespace opt
  54. } // namespace spvtools