cfg_ir.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. """Defines control flow graph IR data structures."""
  2. # Let's just agree to disagree on map vs list comprehensions, pylint.
  3. # pylint: disable=I0011,W0141
  4. class SharedCounter(object):
  5. """Defines a shared counter."""
  6. def __init__(self):
  7. self.index = 0
  8. def next_value(self):
  9. """Gets the next value for this counter."""
  10. result = self.index
  11. self.index += 1
  12. return result
  13. class BasicBlock(object):
  14. """Represents a basic block."""
  15. def __init__(self, counter):
  16. self.parameters = []
  17. self.definitions = []
  18. self.counter = counter
  19. self.index = counter.next_value()
  20. self.flow = UnreachableFlow()
  21. def append_parameter(self, parameter):
  22. """Appends a parameter to this basic block."""
  23. result = self.create_definition(parameter)
  24. self.parameters.append(result)
  25. return result
  26. def prepend_definition(self, value):
  27. """Defines the given value in this basic block."""
  28. result = self.create_definition(value)
  29. self.definitions.insert(0, result)
  30. return result
  31. def append_definition(self, value):
  32. """Defines the given value in this basic block."""
  33. result = self.create_definition(value)
  34. self.definitions.append(result)
  35. return result
  36. def create_definition(self, value=None):
  37. """Creates a definition, but does not assign it to this block yet."""
  38. if isinstance(value, Definition):
  39. return value
  40. else:
  41. assert isinstance(value, Value) or value is None
  42. return Definition(self.counter.next_value(), value)
  43. def remove_definition(self, definition):
  44. """Removes the given definition from this basic block."""
  45. return self.definitions.remove(definition)
  46. def __str__(self):
  47. prefix = '!%d(%s):' % (self.index, ', '.join(map(str, self.parameters)))
  48. return '\n'.join(
  49. [prefix] +
  50. [' ' * 4 + str(item) for item in self.definitions + [self.flow]])
  51. class Definition(object):
  52. """Maps a value to a variable."""
  53. def __init__(self, index, value):
  54. self.index = index
  55. self.value = value
  56. if value is not None:
  57. assert isinstance(value, Value)
  58. def redefine(self, new_value):
  59. """Tweaks this definition to take on the given new value."""
  60. self.value = new_value
  61. if new_value is not None:
  62. assert isinstance(new_value, Value)
  63. def ref_str(self):
  64. """Gets a string that represents a reference to this definition."""
  65. return '$%d' % self.index
  66. def __str__(self):
  67. return '$%d = %s' % (self.index, str(self.value))
  68. class Instruction(object):
  69. """Represents an instruction."""
  70. def get_dependencies(self):
  71. """Gets all definitions and instructions on which this instruction depends."""
  72. raise NotImplementedError()
  73. def get_all_dependencies(self):
  74. """Gets all definitions and instructions on which this instruction depends,
  75. along with any dependencies of dependencies."""
  76. results = list(self.get_dependencies())
  77. for item in results:
  78. results.extend(item.get_all_dependencies())
  79. return results
  80. class Branch(Instruction):
  81. """Represents a branch from one basic block to another."""
  82. def __init__(self, block, arguments=None):
  83. self.block = block
  84. assert isinstance(block, BasicBlock)
  85. if arguments is None:
  86. arguments = []
  87. self.arguments = arguments
  88. assert all([isinstance(arg, Definition) for arg in arguments])
  89. def get_dependencies(self):
  90. """Gets all definitions and instructions on which this instruction depends."""
  91. return self.arguments
  92. def __str__(self):
  93. return '!%d(%s)' % (self.block.index, ', '.join([arg.ref_str() for arg in self.arguments]))
  94. class FlowInstruction(Instruction):
  95. """Represents a control flow instruction which terminates a basic block."""
  96. def branches(self):
  97. """Gets a list of basic blocks targeted by this flow instruction."""
  98. raise NotImplementedError()
  99. class JumpFlow(FlowInstruction):
  100. """Represents a control flow instruction which jumps directly to a basic block."""
  101. def __init__(self, branch):
  102. FlowInstruction.__init__(self)
  103. self.branch = branch
  104. assert isinstance(branch, Branch)
  105. def get_dependencies(self):
  106. """Gets all definitions and instructions on which this instruction depends."""
  107. return self.branches()
  108. def branches(self):
  109. """Gets a list of basic blocks targeted by this flow instruction."""
  110. return [self.branch]
  111. def __str__(self):
  112. return 'jump %s' % self.branch
  113. class SelectFlow(FlowInstruction):
  114. """Represents a control flow instruction which jumps to one of two basic blocks depending
  115. on whether a condition is truthy or not."""
  116. def __init__(self, condition, if_branch, else_branch):
  117. FlowInstruction.__init__(self)
  118. self.condition = condition
  119. assert isinstance(condition, Definition)
  120. self.if_branch = if_branch
  121. assert isinstance(if_branch, Branch)
  122. self.else_branch = else_branch
  123. assert isinstance(else_branch, Branch)
  124. def get_dependencies(self):
  125. """Gets all definitions and instructions on which this instruction depends."""
  126. return [self.condition] + self.branches()
  127. def branches(self):
  128. """Gets a list of basic blocks targeted by this flow instruction."""
  129. return [self.if_branch, self.else_branch]
  130. def __str__(self):
  131. return 'select %s, %s, %s' % (self.condition.ref_str(), self.if_branch, self.else_branch)
  132. class ReturnFlow(FlowInstruction):
  133. """Represents a control flow instruction which terminates the execution of the current
  134. function and returns a value."""
  135. def __init__(self, value):
  136. FlowInstruction.__init__(self)
  137. self.value = value
  138. assert isinstance(value, Definition)
  139. def get_dependencies(self):
  140. """Gets all definitions and instructions on which this instruction depends."""
  141. return [self.value]
  142. def branches(self):
  143. """Gets a list of basic blocks targeted by this flow instruction."""
  144. return []
  145. def __str__(self):
  146. return 'return %s' % self.value.ref_str()
  147. class UnreachableFlow(FlowInstruction):
  148. """Represents a control flow instruction which is unreachable."""
  149. def get_dependencies(self):
  150. """Gets all definitions and instructions on which this instruction depends."""
  151. return []
  152. def branches(self):
  153. """Gets a list of basic blocks targeted by this flow instruction."""
  154. return []
  155. def __str__(self):
  156. return 'unreachable'
  157. class Value(Instruction):
  158. """A value: an instruction that produces some result."""
  159. def get_dependencies(self):
  160. """Gets all definitions and instructions on which this instruction depends."""
  161. raise NotImplementedError()
  162. def has_value(self):
  163. """Tells if this value produces a result that is not None."""
  164. return True
  165. def has_side_effects(self):
  166. """Tells if this instruction has side-effects."""
  167. return False
  168. class BlockParameter(Value):
  169. """A basic block parameter."""
  170. def get_dependencies(self):
  171. """Gets all definitions and instructions on which this instruction depends."""
  172. return []
  173. def __str__(self):
  174. return 'block-parameter'
  175. class FunctionParameter(Value):
  176. """A function parameter."""
  177. def __init__(self, name):
  178. Value.__init__(self)
  179. self.name = name
  180. def get_dependencies(self):
  181. """Gets all definitions and instructions on which this instruction depends."""
  182. return []
  183. def __str__(self):
  184. return 'func-parameter %s' % self.name
  185. class Literal(Value):
  186. """A literal value."""
  187. def __init__(self, literal):
  188. Value.__init__(self)
  189. self.literal = literal
  190. def get_dependencies(self):
  191. """Gets all definitions and instructions on which this instruction depends."""
  192. return []
  193. def has_value(self):
  194. """Tells if this value produces a result that is not None."""
  195. return self.literal is not None
  196. def __str__(self):
  197. return 'literal %r' % self.literal
  198. class JitFunctionCall(Value):
  199. """A value that is the result of a function call."""
  200. def __init__(self, target, argument_list):
  201. Value.__init__(self)
  202. assert isinstance(target, Definition)
  203. self.target = target
  204. assert all([isinstance(val, Definition) for _, val in argument_list])
  205. self.argument_list = argument_list
  206. def has_side_effects(self):
  207. """Tells if this instruction has side-effects."""
  208. return True
  209. def get_dependencies(self):
  210. """Gets all definitions and instructions on which this instruction depends."""
  211. return [self.target] + [val for _, val in self.argument_list]
  212. def __str__(self):
  213. return 'call %s(%s)' % (
  214. self.target.ref_str(),
  215. ', '.join(['%s=%s' % (key, val.ref_str()) for key, val in self.argument_list]))
  216. class AllocateRootNode(Value):
  217. """A value that produces a new root node. Typically used in function prologs."""
  218. def __init__(self):
  219. Value.__init__(self)
  220. def get_dependencies(self):
  221. """Gets all definitions and instructions on which this instruction depends."""
  222. return []
  223. def __str__(self):
  224. return 'alloc-root-node'
  225. class DeallocateRootNode(Value):
  226. """A value that deallocates a root node. Typically used in function epilogs."""
  227. def __init__(self, root_node):
  228. Value.__init__(self)
  229. assert isinstance(root_node, Definition)
  230. self.root_node = root_node
  231. def get_dependencies(self):
  232. """Gets all definitions and instructions on which this instruction depends."""
  233. return []
  234. def __str__(self):
  235. return 'free-root-node %s' % self.root_node.ref_str()
  236. class DeclareLocal(Value):
  237. """A value that declares a local variable."""
  238. def __init__(self, variable, root_node):
  239. Value.__init__(self)
  240. self.variable = variable
  241. self.root_node = root_node
  242. def get_dependencies(self):
  243. """Gets all definitions and instructions on which this instruction depends."""
  244. return []
  245. def has_value(self):
  246. """Tells if this value produces a result that is not None."""
  247. return False
  248. def has_side_effects(self):
  249. """Tells if this instruction has side-effects."""
  250. return True
  251. def __str__(self):
  252. return 'declare-local %s, %s' % (self.variable, self.root_node.ref_str())
  253. class DeclareGlobal(Value):
  254. """A value that declares a global variable."""
  255. def __init__(self, variable):
  256. Value.__init__(self)
  257. self.variable = variable
  258. def get_dependencies(self):
  259. """Gets all definitions and instructions on which this instruction depends."""
  260. return []
  261. def has_value(self):
  262. """Tells if this value produces a result that is not None."""
  263. return False
  264. def has_side_effects(self):
  265. """Tells if this instruction has side-effects."""
  266. return True
  267. def __str__(self):
  268. return 'declare-global %s' % self.variable.name
  269. class CheckLocalExists(Value):
  270. """A value that checks if a local value has been defined (yet)."""
  271. def __init__(self, variable):
  272. Value.__init__(self)
  273. self.variable = variable
  274. def get_dependencies(self):
  275. """Gets all definitions and instructions on which this instruction depends."""
  276. return []
  277. def __str__(self):
  278. return 'check-local-exists %s' % self.variable
  279. class ResolveLocal(Value):
  280. """A value that resolves a local as a pointer."""
  281. def __init__(self, variable):
  282. Value.__init__(self)
  283. self.variable = variable
  284. def get_dependencies(self):
  285. """Gets all definitions and instructions on which this instruction depends."""
  286. return []
  287. def __str__(self):
  288. return 'resolve-local %s' % self.variable
  289. class ResolveGlobal(Value):
  290. """A value that resolves a global as a pointer."""
  291. def __init__(self, variable):
  292. Value.__init__(self)
  293. self.variable = variable
  294. def get_dependencies(self):
  295. """Gets all definitions and instructions on which this instruction depends."""
  296. return []
  297. def __str__(self):
  298. return 'resolve-global %s' % self.variable.name
  299. class LoadPointer(Value):
  300. """A value that loads the value assigned to a pointer."""
  301. def __init__(self, pointer):
  302. Value.__init__(self)
  303. self.pointer = pointer
  304. assert isinstance(pointer, Definition)
  305. def get_dependencies(self):
  306. """Gets all definitions and instructions on which this instruction depends."""
  307. return [self.pointer]
  308. def __str__(self):
  309. return 'load %s' % self.pointer.ref_str()
  310. class StoreAtPointer(Value):
  311. """A value that assigns a value to a pointer."""
  312. def __init__(self, pointer, value):
  313. Value.__init__(self)
  314. self.pointer = pointer
  315. assert isinstance(pointer, Definition)
  316. self.value = value
  317. assert isinstance(value, Definition)
  318. def get_dependencies(self):
  319. """Gets all definitions and instructions on which this instruction depends."""
  320. return [self.pointer, self.value]
  321. def has_value(self):
  322. """Tells if this value produces a result that is not None."""
  323. return False
  324. def has_side_effects(self):
  325. """Tells if this instruction has side-effects."""
  326. return True
  327. def __str__(self):
  328. return 'store %s, %s' % (self.pointer.ref_str(), self.value.ref_str())
  329. class Input(Value):
  330. """A value that pops a node from the input queue."""
  331. def get_dependencies(self):
  332. """Gets all definitions and instructions on which this instruction depends."""
  333. return []
  334. def has_side_effects(self):
  335. """Tells if this instruction has side-effects."""
  336. return True
  337. def __str__(self):
  338. return 'input'
  339. class Output(Value):
  340. """A value that pushes a node onto the output queue."""
  341. def __init__(self, value):
  342. Value.__init__(self)
  343. self.value = value
  344. assert isinstance(value, Definition)
  345. def get_dependencies(self):
  346. """Gets all definitions and instructions on which this instruction depends."""
  347. return [self.value]
  348. def has_value(self):
  349. """Tells if this value produces a result that is not None."""
  350. return False
  351. def has_side_effects(self):
  352. """Tells if this instruction has side-effects."""
  353. return True
  354. def __str__(self):
  355. return 'output %s' % self.value.ref_str()
  356. def create_jump(block, arguments=None):
  357. """Creates a jump to the given block with the given argument list."""
  358. return JumpFlow(Branch(block, arguments))