cfg_ir.py 22 KB

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