cfg_ir.py 21 KB

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