cfg_optimization.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334
  1. """Optimizes and analyzes CFG-IR."""
  2. import modelverse_jit.cfg_ir as cfg_ir
  3. def get_directly_reachable_blocks(block):
  4. """Gets the set of all blocks that can be reached by taking a single branch from the
  5. given block."""
  6. return [branch.block for branch in block.flow.branches()]
  7. def get_reachable_blocks(entry_point):
  8. """Constructs the set of all reachable vertices from the given block."""
  9. # This is a simple O(n^2) algorithm. Maybe a faster algorithm is more appropriate here.
  10. def __add_block_children(block, results):
  11. for child in get_directly_reachable_blocks(block):
  12. if child not in results:
  13. results.add(child)
  14. __add_block_children(child, results)
  15. return results
  16. return __add_block_children(entry_point, set())
  17. def get_all_reachable_blocks(entry_point):
  18. """Constructs the set of all reachable vertices, for every block that is
  19. reachable from the given entry point."""
  20. # This is a simple O(n^3) algorithm. Maybe a faster algorithm is more appropriate here.
  21. results = {}
  22. all_blocks = get_reachable_blocks(entry_point)
  23. results[entry_point] = all_blocks
  24. for block in all_blocks:
  25. if block not in results:
  26. results[block] = get_reachable_blocks(block)
  27. return results