utils.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. import re
  2. class Statement:
  3. def __init__(self, stype, name, *args, **kwargs):
  4. self.stype = stype
  5. self.name = name
  6. self.args = args
  7. self.options = kwargs
  8. def __getitem__(self, n):
  9. """Get an argument."""
  10. return self.args[n]
  11. def __eq__(self, other):
  12. """Check if two statements are equal by comparing their type, name and
  13. arguments."""
  14. return self.stype == other.stype and self.name == other.name \
  15. and self.args == other.args
  16. def __str__(self): # pragma: nocover
  17. return '<Statement type=%s name=%s args=%s>' \
  18. % (self.stype, self.name, self.args)
  19. def __repr__(self): # pragma: nocover
  20. return str(self)
  21. def is_comment(self):
  22. return self.stype == 'comment'
  23. def is_inline_comment(self):
  24. return self.is_comment() and self.options['inline']
  25. def is_directive(self):
  26. return self.stype == 'directive'
  27. def is_label(self):
  28. return self.stype == 'label'
  29. def is_command(self):
  30. return self.stype == 'command'
  31. def is_jump(self):
  32. """Check if the statement is a jump."""
  33. return self.is_command() \
  34. and re.match('^j|jal|beq|bne|blez|bgtz|bltz|bgez|bct|bcf$', \
  35. self.name)
  36. def is_shift(self):
  37. """Check if the statement is a shift operation."""
  38. return self.is_command() and re.match('^s(ll|la|rl|ra)$', self.name)
  39. def is_load(self):
  40. """Check if the statement is a load instruction."""
  41. return self.is_command() and self.name in ['lw', 'dlw', 'l.s', 'l.d']
  42. def is_arith(self):
  43. """Check if the statement is an arithmetic operation."""
  44. return self.is_command() \
  45. and re.match('^(add|sub|mult|div|abs|neg)(u|\.d)?$', self.name)
  46. def jump_target(self):
  47. """Get the jump target of this statement."""
  48. if self.is_jump():
  49. return self[-1]
  50. else:
  51. raise Exception('Command "%s" has no jump target' % self.name)
  52. def get_def(self):
  53. """Get the def[S] of this statement."""
  54. if not self.is_command():
  55. return []
  56. if self.is_load() or self.is_arith():
  57. return [self[0]]
  58. def get_use(self):
  59. """Get the use[S] of this statement."""
  60. return []
  61. def defines(self, var):
  62. """Check if a variable is defined by this statement."""
  63. return var in self.get_def()
  64. def uses(self, var):
  65. """Check if a variable is used by this statement."""
  66. return var in self.get_use()
  67. class Block:
  68. def __init__(self, statements=[]):
  69. self.statements = statements
  70. self.pointer = 0
  71. def __iter__(self):
  72. return iter(self.statements)
  73. def __len__(self):
  74. return len(self.statements)
  75. def read(self, count=1):
  76. """Read the statement at the current pointer position and move the
  77. pointer one position to the right."""
  78. s = self.statements[self.pointer]
  79. self.pointer += 1
  80. return s
  81. def end(self):
  82. """Check if the pointer is at the end of the statement list."""
  83. return self.pointer == len(self)
  84. def peek(self, count=1):
  85. """Read the statements until an offset from the current pointer
  86. position."""
  87. return self.statements[self.pointer] if count == 1 \
  88. else self.statements[self.pointer:self.pointer + count]
  89. def replace(self, count, replacement, start=None):
  90. """Replace the given range start-(start + count) with the given
  91. statement list, and move the pointer to the first statement after the
  92. replacement."""
  93. if start == None:
  94. start = self.pointer
  95. before = self.statements[:start]
  96. after = self.statements[start + count:]
  97. self.statements = before + replacement + after
  98. self.pointer = start + len(replacement)
  99. def apply_filter(self, callback):
  100. """Apply a filter to the statement list. If the callback returns True,
  101. the statement will remain in the list.."""
  102. self.statements = filter(callback, self.statements)
  103. def find_leaders(statements):
  104. """Determine the leaders, which are:
  105. 1. The first statement.
  106. 2. Any statement that is the target of a jump.
  107. 3. Any statement that follows directly follows a jump."""
  108. leaders = [0]
  109. jump_target_labels = []
  110. # Append statements following jumps and save jump target labels
  111. for i, statement in enumerate(statements[1:]):
  112. if statement.is_jump():
  113. leaders.append(i + 2)
  114. jump_target_labels.append(statement[-1])
  115. # Append jump targets
  116. for i, statement in enumerate(statements[1:]):
  117. if i + 1 not in leaders \
  118. and statement.is_label() \
  119. and statement.name in jump_target_labels:
  120. leaders.append(i + 1)
  121. leaders.sort()
  122. return leaders
  123. def find_basic_blocks(statements):
  124. """Divide a statement list into basic blocks. Returns a list of basic
  125. blocks, which are also statement lists."""
  126. leaders = find_leaders(statements)
  127. blocks = []
  128. for i in range(len(leaders) - 1):
  129. blocks.append(Block(statements[leaders[i]:leaders[i + 1]]))
  130. blocks.append(Block(statements[leaders[-1]:]))
  131. return blocks