cfg_ir.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  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.definition_counter = SharedCounter()
  21. self.flow = UnreachableFlow()
  22. def append_parameter(self, parameter):
  23. """Appends a parameter to this basic block."""
  24. result = self.create_definition(parameter)
  25. self.parameters.append(result)
  26. if len(self.definitions) > 0:
  27. self.renumber_definitions()
  28. return result
  29. def remove_parameter(self, parameter):
  30. """Removes the given parameter definition from this basic block."""
  31. return self.parameters.remove(parameter)
  32. def prepend_definition(self, value):
  33. """Defines the given value in this basic block."""
  34. result = self.create_definition(value)
  35. self.definitions.insert(0, result)
  36. self.renumber_definitions()
  37. return result
  38. def append_definition(self, value):
  39. """Defines the given value in this basic block."""
  40. result = self.create_definition(value)
  41. self.definitions.append(result)
  42. return result
  43. def create_definition(self, value=None):
  44. """Creates a definition, but does not assign it to this block yet."""
  45. if isinstance(value, Definition):
  46. value.block = self
  47. value.renumber(self.definition_counter.next_value())
  48. return value
  49. else:
  50. assert isinstance(value, Value) or value is None
  51. return Definition(
  52. self.counter.next_value(),
  53. self,
  54. self.definition_counter.next_value(),
  55. value)
  56. def remove_definition(self, definition):
  57. """Removes the given definition from this basic block."""
  58. return self.definitions.remove(definition)
  59. def renumber_definitions(self):
  60. """Re-numbers all definitions in this basic block."""
  61. self.definition_counter = SharedCounter()
  62. for definition in self.parameters:
  63. definition.renumber(self.definition_counter.next_value())
  64. for definition in self.definitions:
  65. definition.renumber(self.definition_counter.next_value())
  66. def __str__(self):
  67. prefix = '!%d(%s):' % (self.index, ', '.join(map(str, self.parameters)))
  68. return '\n'.join(
  69. [prefix] +
  70. [' ' * 4 + str(item) for item in self.definitions + [self.flow]])
  71. class Definition(object):
  72. """Maps a value to a variable."""
  73. def __init__(self, index, block, definition_index, value):
  74. self.index = index
  75. self.block = block
  76. self.definition_index = definition_index
  77. self.value = value
  78. if value is not None:
  79. assert isinstance(value, Value) or isinstance(value, Definition)
  80. def redefine(self, new_value):
  81. """Tweaks this definition to take on the given new value."""
  82. self.value = new_value
  83. if new_value is not None:
  84. assert isinstance(new_value, Value) or isinstance(new_value, Definition)
  85. def renumber(self, new_definition_index):
  86. """Updates this definition's index in the block that defines it."""
  87. self.definition_index = new_definition_index
  88. def get_all_dependencies(self):
  89. """Gets all definitions and instructions on which this definition depends,
  90. along with any dependencies of instruction dependencies."""
  91. return self.value.get_all_dependencies()
  92. def has_side_effects(self):
  93. """Tests if this definition produces any side-effects."""
  94. return self.value.has_side_effects()
  95. def ref_str(self):
  96. """Gets a string that represents a reference to this definition."""
  97. return '$%d' % self.index
  98. def __str__(self):
  99. return '$%d = %s' % (self.index, self.value.ref_str())
  100. class Instruction(object):
  101. """Represents an instruction."""
  102. def get_dependencies(self):
  103. """Gets all definitions and instructions on which this instruction depends."""
  104. raise NotImplementedError()
  105. def get_all_dependencies(self):
  106. """Gets all definitions and instructions on which this instruction depends,
  107. along with any dependencies of instruction dependencies."""
  108. results = list(self.get_dependencies())
  109. for item in results:
  110. if not isinstance(item, Definition):
  111. results.extend(item.get_all_dependencies())
  112. return results
  113. class Branch(Instruction):
  114. """Represents a branch from one basic block to another."""
  115. def __init__(self, block, arguments=None):
  116. self.block = block
  117. assert isinstance(block, BasicBlock)
  118. if arguments is None:
  119. arguments = []
  120. self.arguments = arguments
  121. assert all([isinstance(arg, Definition) for arg in arguments])
  122. def get_dependencies(self):
  123. """Gets all definitions and instructions on which this instruction depends."""
  124. return self.arguments
  125. def __str__(self):
  126. return '!%d(%s)' % (self.block.index, ', '.join([arg.ref_str() for arg in self.arguments]))
  127. class FlowInstruction(Instruction):
  128. """Represents a control flow instruction which terminates a basic block."""
  129. def branches(self):
  130. """Gets a list of basic blocks targeted by this flow instruction."""
  131. raise NotImplementedError()
  132. class JumpFlow(FlowInstruction):
  133. """Represents a control flow instruction which jumps directly to a basic block."""
  134. def __init__(self, branch):
  135. FlowInstruction.__init__(self)
  136. self.branch = branch
  137. assert isinstance(branch, Branch)
  138. def get_dependencies(self):
  139. """Gets all definitions and instructions on which this instruction depends."""
  140. return self.branches()
  141. def branches(self):
  142. """Gets a list of basic blocks targeted by this flow instruction."""
  143. return [self.branch]
  144. def __str__(self):
  145. return 'jump %s' % self.branch
  146. class SelectFlow(FlowInstruction):
  147. """Represents a control flow instruction which jumps to one of two basic blocks depending
  148. on whether a condition is truthy or not."""
  149. def __init__(self, condition, if_branch, else_branch):
  150. FlowInstruction.__init__(self)
  151. self.condition = condition
  152. assert isinstance(condition, Definition)
  153. self.if_branch = if_branch
  154. assert isinstance(if_branch, Branch)
  155. self.else_branch = else_branch
  156. assert isinstance(else_branch, Branch)
  157. def get_dependencies(self):
  158. """Gets all definitions and instructions on which this instruction depends."""
  159. return [self.condition] + self.branches()
  160. def branches(self):
  161. """Gets a list of basic blocks targeted by this flow instruction."""
  162. return [self.if_branch, self.else_branch]
  163. def __str__(self):
  164. return 'select %s, %s, %s' % (self.condition.ref_str(), self.if_branch, self.else_branch)
  165. class ReturnFlow(FlowInstruction):
  166. """Represents a control flow instruction which terminates the execution of the current
  167. function and returns a value."""
  168. def __init__(self, value):
  169. FlowInstruction.__init__(self)
  170. self.value = value
  171. assert isinstance(value, Definition)
  172. def get_dependencies(self):
  173. """Gets all definitions and instructions on which this instruction depends."""
  174. return [self.value]
  175. def branches(self):
  176. """Gets a list of basic blocks targeted by this flow instruction."""
  177. return []
  178. def __str__(self):
  179. return 'return %s' % self.value.ref_str()
  180. class ThrowFlow(FlowInstruction):
  181. """Represents a control flow instruction which throws an exception."""
  182. def __init__(self, exception):
  183. FlowInstruction.__init__(self)
  184. self.exception = exception
  185. assert isinstance(exception, Definition)
  186. def get_dependencies(self):
  187. """Gets all definitions and instructions on which this instruction depends."""
  188. return [self.exception]
  189. def branches(self):
  190. """Gets a list of basic blocks targeted by this flow instruction."""
  191. return []
  192. def __str__(self):
  193. return 'throw %s' % self.exception.ref_str()
  194. class UnreachableFlow(FlowInstruction):
  195. """Represents a control flow instruction which is unreachable."""
  196. def get_dependencies(self):
  197. """Gets all definitions and instructions on which this instruction depends."""
  198. return []
  199. def branches(self):
  200. """Gets a list of basic blocks targeted by this flow instruction."""
  201. return []
  202. def __str__(self):
  203. return 'unreachable'
  204. class Value(Instruction):
  205. """A value: an instruction that produces some result."""
  206. def get_dependencies(self):
  207. """Gets all definitions and instructions on which this instruction depends."""
  208. raise NotImplementedError()
  209. def has_value(self):
  210. """Tells if this value produces a result that is not None."""
  211. return True
  212. def has_side_effects(self):
  213. """Tells if this instruction has side-effects."""
  214. return False
  215. def ref_str(self):
  216. """Gets a string that represents this value."""
  217. return str(self)
  218. class BlockParameter(Value):
  219. """A basic block parameter."""
  220. def get_dependencies(self):
  221. """Gets all definitions and instructions on which this instruction depends."""
  222. return []
  223. def __str__(self):
  224. return 'block-parameter'
  225. class FunctionParameter(Value):
  226. """A function parameter."""
  227. def __init__(self, name):
  228. Value.__init__(self)
  229. self.name = name
  230. def get_dependencies(self):
  231. """Gets all definitions and instructions on which this instruction depends."""
  232. return []
  233. def __str__(self):
  234. return 'func-parameter %s' % self.name
  235. class Literal(Value):
  236. """A literal value."""
  237. def __init__(self, literal):
  238. Value.__init__(self)
  239. self.literal = literal
  240. def get_dependencies(self):
  241. """Gets all definitions and instructions on which this instruction depends."""
  242. return []
  243. def has_value(self):
  244. """Tells if this value produces a result that is not None."""
  245. return self.literal is not None
  246. def __str__(self):
  247. return 'literal %r' % self.literal
  248. class IndirectFunctionCall(Value):
  249. """A value that is the result of an indirect function call."""
  250. def __init__(self, target, argument_list):
  251. Value.__init__(self)
  252. assert isinstance(target, Definition)
  253. self.target = target
  254. assert all([isinstance(val, Definition) for _, val in argument_list])
  255. self.argument_list = argument_list
  256. def has_side_effects(self):
  257. """Tells if this instruction has side-effects."""
  258. return True
  259. def get_dependencies(self):
  260. """Gets all definitions and instructions on which this instruction depends."""
  261. return [self.target] + [val for _, val in self.argument_list]
  262. def __str__(self):
  263. return 'indirect-call %s(%s)' % (
  264. self.target.ref_str(),
  265. ', '.join(['%s=%s' % (key, val.ref_str()) for key, val in self.argument_list]))
  266. SIMPLE_POSITIONAL_CALLING_CONVENTION = 'simple-positional'
  267. """The calling convention for functions that use 'return' statements to return.
  268. Arguments are matched to parameters based on position."""
  269. JIT_CALLING_CONVENTION = 'jit'
  270. """The calling convention for jitted functions."""
  271. class DirectFunctionCall(Value):
  272. """A value that is the result of a direct function call."""
  273. def __init__(self, target_name, argument_list, calling_convention=JIT_CALLING_CONVENTION):
  274. Value.__init__(self)
  275. self.target_name = target_name
  276. assert all([isinstance(val, Definition) for _, val in argument_list])
  277. self.argument_list = argument_list
  278. self.calling_convention = calling_convention
  279. def has_side_effects(self):
  280. """Tells if this instruction has side-effects."""
  281. return True
  282. def get_dependencies(self):
  283. """Gets all definitions and instructions on which this instruction depends."""
  284. return [val for _, val in self.argument_list]
  285. def __str__(self):
  286. return 'direct-call %r %s(%s)' % (
  287. self.calling_convention,
  288. self.target_name,
  289. ', '.join(['%s=%s' % (key, val.ref_str()) for key, val in self.argument_list]))
  290. class AllocateRootNode(Value):
  291. """A value that produces a new root node. Typically used in function prologs."""
  292. def __init__(self):
  293. Value.__init__(self)
  294. def get_dependencies(self):
  295. """Gets all definitions and instructions on which this instruction depends."""
  296. return []
  297. def __str__(self):
  298. return 'alloc-root-node'
  299. class DeallocateRootNode(Value):
  300. """A value that deallocates a root node. Typically used in function epilogs."""
  301. def __init__(self, root_node):
  302. Value.__init__(self)
  303. assert isinstance(root_node, Definition)
  304. self.root_node = root_node
  305. def get_dependencies(self):
  306. """Gets all definitions and instructions on which this instruction depends."""
  307. return [self.root_node]
  308. def has_side_effects(self):
  309. """Tells if this instruction has side-effects."""
  310. return True
  311. def __str__(self):
  312. return 'free-root-node %s' % self.root_node.ref_str()
  313. class DeclareLocal(Value):
  314. """A value that declares a local variable."""
  315. def __init__(self, variable, root_node):
  316. Value.__init__(self)
  317. self.variable = variable
  318. self.root_node = root_node
  319. def get_dependencies(self):
  320. """Gets all definitions and instructions on which this instruction depends."""
  321. return []
  322. def has_value(self):
  323. """Tells if this value produces a result that is not None."""
  324. return False
  325. def has_side_effects(self):
  326. """Tells if this instruction has side-effects."""
  327. return True
  328. def __str__(self):
  329. return 'declare-local %s, %s' % (self.variable, self.root_node.ref_str())
  330. class DeclareGlobal(Value):
  331. """A value that declares a global variable."""
  332. def __init__(self, variable):
  333. Value.__init__(self)
  334. self.variable = variable
  335. def get_dependencies(self):
  336. """Gets all definitions and instructions on which this instruction depends."""
  337. return []
  338. def has_value(self):
  339. """Tells if this value produces a result that is not None."""
  340. return False
  341. def has_side_effects(self):
  342. """Tells if this instruction has side-effects."""
  343. return True
  344. def __str__(self):
  345. return 'declare-global %s' % self.variable.name
  346. class CheckLocalExists(Value):
  347. """A value that checks if a local value has been defined (yet)."""
  348. def __init__(self, variable):
  349. Value.__init__(self)
  350. self.variable = variable
  351. def get_dependencies(self):
  352. """Gets all definitions and instructions on which this instruction depends."""
  353. return []
  354. def __str__(self):
  355. return 'check-local-exists %s' % self.variable
  356. class ResolveLocal(Value):
  357. """A value that resolves a local as a pointer."""
  358. def __init__(self, variable):
  359. Value.__init__(self)
  360. self.variable = variable
  361. def get_dependencies(self):
  362. """Gets all definitions and instructions on which this instruction depends."""
  363. return []
  364. def __str__(self):
  365. return 'resolve-local %s' % self.variable
  366. class ResolveGlobal(Value):
  367. """A value that resolves a global as a pointer."""
  368. def __init__(self, variable):
  369. Value.__init__(self)
  370. self.variable = variable
  371. def get_dependencies(self):
  372. """Gets all definitions and instructions on which this instruction depends."""
  373. return []
  374. def __str__(self):
  375. return 'resolve-global %s' % self.variable.name
  376. class LoadPointer(Value):
  377. """A value that loads the value assigned to a pointer."""
  378. def __init__(self, pointer):
  379. Value.__init__(self)
  380. self.pointer = pointer
  381. assert isinstance(pointer, Definition)
  382. def get_dependencies(self):
  383. """Gets all definitions and instructions on which this instruction depends."""
  384. return [self.pointer]
  385. def __str__(self):
  386. return 'load %s' % self.pointer.ref_str()
  387. class StoreAtPointer(Value):
  388. """A value that assigns a value to a pointer."""
  389. def __init__(self, pointer, value):
  390. Value.__init__(self)
  391. self.pointer = pointer
  392. assert isinstance(pointer, Definition)
  393. self.value = value
  394. assert isinstance(value, Definition)
  395. def get_dependencies(self):
  396. """Gets all definitions and instructions on which this instruction depends."""
  397. return [self.pointer, self.value]
  398. def has_value(self):
  399. """Tells if this value produces a result that is not None."""
  400. return False
  401. def has_side_effects(self):
  402. """Tells if this instruction has side-effects."""
  403. return True
  404. def __str__(self):
  405. return 'store %s, %s' % (self.pointer.ref_str(), self.value.ref_str())
  406. class Read(Value):
  407. """A value that reads the value stored in a node."""
  408. def __init__(self, node):
  409. Value.__init__(self)
  410. self.node = node
  411. assert isinstance(node, Definition)
  412. def get_dependencies(self):
  413. """Gets all definitions and instructions on which this instruction depends."""
  414. return [self.node]
  415. def __str__(self):
  416. return 'read %s' % (self.node.ref_str())
  417. class Input(Value):
  418. """A value that pops a node from the input queue."""
  419. def get_dependencies(self):
  420. """Gets all definitions and instructions on which this instruction depends."""
  421. return []
  422. def has_side_effects(self):
  423. """Tells if this instruction has side-effects."""
  424. return True
  425. def __str__(self):
  426. return 'input'
  427. class Output(Value):
  428. """A value that pushes a node onto the output queue."""
  429. def __init__(self, value):
  430. Value.__init__(self)
  431. self.value = value
  432. assert isinstance(value, Definition)
  433. def get_dependencies(self):
  434. """Gets all definitions and instructions on which this instruction depends."""
  435. return [self.value]
  436. def has_value(self):
  437. """Tells if this value produces a result that is not None."""
  438. return False
  439. def has_side_effects(self):
  440. """Tells if this instruction has side-effects."""
  441. return True
  442. def __str__(self):
  443. return 'output %s' % self.value.ref_str()
  444. class Binary(Value):
  445. """A value that applies a binary operator to two other values."""
  446. def __init__(self, lhs, operator, rhs):
  447. Value.__init__(self)
  448. self.lhs = lhs
  449. assert isinstance(lhs, Definition)
  450. self.operator = operator
  451. self.rhs = rhs
  452. assert isinstance(rhs, Definition)
  453. def get_dependencies(self):
  454. """Gets all definitions and instructions on which this instruction depends."""
  455. return [self.lhs, self.rhs]
  456. def __str__(self):
  457. return 'binary %s, %r, %s' % (self.lhs.ref_str(), self.operator, self.rhs.ref_str())
  458. def create_jump(block, arguments=None):
  459. """Creates a jump to the given block with the given argument list."""
  460. return JumpFlow(Branch(block, arguments))
  461. def get_def_value(def_or_value):
  462. """Returns the given value, or the underlying value of the given definition, whichever is
  463. appropriate."""
  464. if isinstance(def_or_value, Definition):
  465. return get_def_value(def_or_value.value)
  466. else:
  467. return def_or_value
  468. def apply_to_value(function, def_or_value):
  469. """Applies the given function to the specified value, or the underlying value of the
  470. given definition."""
  471. return function(get_def_value(def_or_value))
  472. def is_literal(value):
  473. """Tests if the given value is a literal."""
  474. return isinstance(value, Literal)
  475. def is_literal_def(def_or_value):
  476. """Tests if the given value is a literal or a definition with an underlying literal."""
  477. return apply_to_value(is_literal, def_or_value)
  478. def is_value_def(def_or_value, class_or_type_or_tuple=Value):
  479. """Tests if the given definition or value is a value of the given type."""
  480. return isinstance(get_def_value(def_or_value), class_or_type_or_tuple)
  481. def get_def_variable(def_or_value):
  482. """Gets the 'variable' attribute of the given value, or the underlying value of the given
  483. definition, whichever is appropriate."""
  484. return get_def_value(def_or_value).variable
  485. def get_literal_value(value):
  486. """Gets the value of the given literal value."""
  487. return value.literal
  488. def get_literal_def_value(def_or_value):
  489. """Gets the value of the given literal value or definition with an underlying literal."""
  490. return apply_to_value(get_literal_value, def_or_value)