test_dataflow.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import unittest
  2. from src.statement import Statement as S
  3. from src.dataflow import BasicBlock as B, find_leaders, find_basic_blocks, \
  4. generate_flow_graph
  5. class TestDataflow(unittest.TestCase):
  6. def setUp(self):
  7. add = S('command', 'add', '$1', '$2', '$3')
  8. self.statements = [add, S('command', 'j', 'foo'), add, add, \
  9. S('label', 'foo')]
  10. def tearDown(self):
  11. del self.statements
  12. def test_find_leaders(self):
  13. self.assertEqual(find_leaders(self.statements), [0, 2, 4])
  14. def test_find_basic_blocks(self):
  15. s = self.statements
  16. self.assertEqual(map(lambda b: b.statements, find_basic_blocks(s)), \
  17. [B(s[:2]).statements, B(s[2:4]).statements, \
  18. B(s[4:]).statements])
  19. # def test_get_gen(self):
  20. # b1 = B([S('command', 'add', '$1', '$2', '$3'), \
  21. # S('command', 'add', '$2', '$3', '$4'), \
  22. # S('command', 'add', '$1', '$4', '$5')])
  23. #
  24. # self.assertEqual(b1.get_gen(), ['$1', '$2'])
  25. # def test_get_out(self):
  26. # b1 = B([S('command', 'add', '$1', '$2', '$3'), \
  27. # S('command', 'add', '$2', '$3', '$4'), \
  28. # S('command', 'add', '$1', '$4', '$5'), \
  29. # S('command', 'j', 'b2')])
  30. #
  31. # b2 = B([S('command', 'add', '$3', '$5', '$6'), \
  32. # S('command', 'add', '$1', '$2', '$3'), \
  33. # S('command', 'add', '$6', '$4', '$5')])
  34. #
  35. # blocks = [b1, b2]
  36. #
  37. # for block in blocks:
  38. # block.out_set = block.get_gen()
  39. # print 'block.out_set', block.out_set
  40. # generate_flow_graph(blocks)
  41. # print b1.get_gen()
  42. # print b2.get_gen()
  43. # print b2.get_out()
  44. def test_generate_flow_graph_simple(self):
  45. b1 = B([S('command', 'foo'), S('command', 'j', 'b2')])
  46. b2 = B([S('label', 'b2'), S('command', 'bar')])
  47. generate_flow_graph([b1, b2])
  48. self.assertEqual(b1.edges_to, [b2])
  49. self.assertEqual(b2.edges_from, [b1])
  50. def test_generate_flow_graph_branch(self):
  51. b1 = B([S('command', 'foo'), S('command', 'beq', '$1', '$2', 'b3')])
  52. b2 = B([S('command', 'bar')])
  53. b3 = B([S('label', 'b3'), S('command', 'baz')])
  54. generate_flow_graph([b1, b2, b3])
  55. self.assertIn(b2, b1.edges_to)
  56. self.assertIn(b3, b1.edges_to)
  57. self.assertEqual(b2.edges_from, [b1])
  58. self.assertEqual(b2.edges_to, [b3])
  59. self.assertIn(b1, b3.edges_from)
  60. self.assertIn(b2, b3.edges_from)