cfg_ir.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  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, str(self.value))
  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. class BlockParameter(Value):
  212. """A basic block parameter."""
  213. def get_dependencies(self):
  214. """Gets all definitions and instructions on which this instruction depends."""
  215. return []
  216. def __str__(self):
  217. return 'block-parameter'
  218. class FunctionParameter(Value):
  219. """A function parameter."""
  220. def __init__(self, name):
  221. Value.__init__(self)
  222. self.name = name
  223. def get_dependencies(self):
  224. """Gets all definitions and instructions on which this instruction depends."""
  225. return []
  226. def __str__(self):
  227. return 'func-parameter %s' % self.name
  228. class Literal(Value):
  229. """A literal value."""
  230. def __init__(self, literal):
  231. Value.__init__(self)
  232. self.literal = literal
  233. def get_dependencies(self):
  234. """Gets all definitions and instructions on which this instruction depends."""
  235. return []
  236. def has_value(self):
  237. """Tells if this value produces a result that is not None."""
  238. return self.literal is not None
  239. def __str__(self):
  240. return 'literal %r' % self.literal
  241. class IndirectFunctionCall(Value):
  242. """A value that is the result of an indirect function call."""
  243. def __init__(self, target, argument_list):
  244. Value.__init__(self)
  245. assert isinstance(target, Definition)
  246. self.target = target
  247. assert all([isinstance(val, Definition) for _, val in argument_list])
  248. self.argument_list = argument_list
  249. def has_side_effects(self):
  250. """Tells if this instruction has side-effects."""
  251. return True
  252. def get_dependencies(self):
  253. """Gets all definitions and instructions on which this instruction depends."""
  254. return [self.target] + [val for _, val in self.argument_list]
  255. def __str__(self):
  256. return 'indirect-call %s(%s)' % (
  257. self.target.ref_str(),
  258. ', '.join(['%s=%s' % (key, val.ref_str()) for key, val in self.argument_list]))
  259. SIMPLE_POSITIONAL_CALLING_CONVENTION = 'simple-positional'
  260. """The calling convention for functions that use 'return' statements to return.
  261. Arguments are matched to parameters based on position."""
  262. JIT_CALLING_CONVENTION = 'jit'
  263. """The calling convention for jitted functions."""
  264. class DirectFunctionCall(Value):
  265. """A value that is the result of a direct function call."""
  266. def __init__(self, target_name, argument_list, calling_convention=JIT_CALLING_CONVENTION):
  267. Value.__init__(self)
  268. self.target_name = target_name
  269. assert all([isinstance(val, Definition) for _, val in argument_list])
  270. self.argument_list = argument_list
  271. self.calling_convention = calling_convention
  272. def has_side_effects(self):
  273. """Tells if this instruction has side-effects."""
  274. return True
  275. def get_dependencies(self):
  276. """Gets all definitions and instructions on which this instruction depends."""
  277. return [val for _, val in self.argument_list]
  278. def __str__(self):
  279. return 'direct-call %r %s(%s)' % (
  280. self.calling_convention,
  281. self.target_name,
  282. ', '.join(['%s=%s' % (key, val.ref_str()) for key, val in self.argument_list]))
  283. class AllocateRootNode(Value):
  284. """A value that produces a new root node. Typically used in function prologs."""
  285. def __init__(self):
  286. Value.__init__(self)
  287. def get_dependencies(self):
  288. """Gets all definitions and instructions on which this instruction depends."""
  289. return []
  290. def __str__(self):
  291. return 'alloc-root-node'
  292. class DeallocateRootNode(Value):
  293. """A value that deallocates a root node. Typically used in function epilogs."""
  294. def __init__(self, root_node):
  295. Value.__init__(self)
  296. assert isinstance(root_node, Definition)
  297. self.root_node = root_node
  298. def get_dependencies(self):
  299. """Gets all definitions and instructions on which this instruction depends."""
  300. return [self.root_node]
  301. def has_side_effects(self):
  302. """Tells if this instruction has side-effects."""
  303. return True
  304. def __str__(self):
  305. return 'free-root-node %s' % self.root_node.ref_str()
  306. class DeclareLocal(Value):
  307. """A value that declares a local variable."""
  308. def __init__(self, variable, root_node):
  309. Value.__init__(self)
  310. self.variable = variable
  311. self.root_node = root_node
  312. def get_dependencies(self):
  313. """Gets all definitions and instructions on which this instruction depends."""
  314. return []
  315. def has_value(self):
  316. """Tells if this value produces a result that is not None."""
  317. return False
  318. def has_side_effects(self):
  319. """Tells if this instruction has side-effects."""
  320. return True
  321. def __str__(self):
  322. return 'declare-local %s, %s' % (self.variable, self.root_node.ref_str())
  323. class DeclareGlobal(Value):
  324. """A value that declares a global variable."""
  325. def __init__(self, variable):
  326. Value.__init__(self)
  327. self.variable = variable
  328. def get_dependencies(self):
  329. """Gets all definitions and instructions on which this instruction depends."""
  330. return []
  331. def has_value(self):
  332. """Tells if this value produces a result that is not None."""
  333. return False
  334. def has_side_effects(self):
  335. """Tells if this instruction has side-effects."""
  336. return True
  337. def __str__(self):
  338. return 'declare-global %s' % self.variable.name
  339. class CheckLocalExists(Value):
  340. """A value that checks if a local value has been defined (yet)."""
  341. def __init__(self, variable):
  342. Value.__init__(self)
  343. self.variable = variable
  344. def get_dependencies(self):
  345. """Gets all definitions and instructions on which this instruction depends."""
  346. return []
  347. def __str__(self):
  348. return 'check-local-exists %s' % self.variable
  349. class ResolveLocal(Value):
  350. """A value that resolves a local as a pointer."""
  351. def __init__(self, variable):
  352. Value.__init__(self)
  353. self.variable = variable
  354. def get_dependencies(self):
  355. """Gets all definitions and instructions on which this instruction depends."""
  356. return []
  357. def __str__(self):
  358. return 'resolve-local %s' % self.variable
  359. class ResolveGlobal(Value):
  360. """A value that resolves a global as a pointer."""
  361. def __init__(self, variable):
  362. Value.__init__(self)
  363. self.variable = variable
  364. def get_dependencies(self):
  365. """Gets all definitions and instructions on which this instruction depends."""
  366. return []
  367. def __str__(self):
  368. return 'resolve-global %s' % self.variable.name
  369. class LoadPointer(Value):
  370. """A value that loads the value assigned to a pointer."""
  371. def __init__(self, pointer):
  372. Value.__init__(self)
  373. self.pointer = pointer
  374. assert isinstance(pointer, Definition)
  375. def get_dependencies(self):
  376. """Gets all definitions and instructions on which this instruction depends."""
  377. return [self.pointer]
  378. def __str__(self):
  379. return 'load %s' % self.pointer.ref_str()
  380. class StoreAtPointer(Value):
  381. """A value that assigns a value to a pointer."""
  382. def __init__(self, pointer, value):
  383. Value.__init__(self)
  384. self.pointer = pointer
  385. assert isinstance(pointer, Definition)
  386. self.value = value
  387. assert isinstance(value, Definition)
  388. def get_dependencies(self):
  389. """Gets all definitions and instructions on which this instruction depends."""
  390. return [self.pointer, self.value]
  391. def has_value(self):
  392. """Tells if this value produces a result that is not None."""
  393. return False
  394. def has_side_effects(self):
  395. """Tells if this instruction has side-effects."""
  396. return True
  397. def __str__(self):
  398. return 'store %s, %s' % (self.pointer.ref_str(), self.value.ref_str())
  399. class Read(Value):
  400. """A value that reads the value stored in a node."""
  401. def __init__(self, node):
  402. Value.__init__(self)
  403. self.node = node
  404. assert isinstance(node, Definition)
  405. def get_dependencies(self):
  406. """Gets all definitions and instructions on which this instruction depends."""
  407. return [self.node]
  408. def __str__(self):
  409. return 'read %s' % (self.node.ref_str())
  410. class Input(Value):
  411. """A value that pops a node from the input queue."""
  412. def get_dependencies(self):
  413. """Gets all definitions and instructions on which this instruction depends."""
  414. return []
  415. def has_side_effects(self):
  416. """Tells if this instruction has side-effects."""
  417. return True
  418. def __str__(self):
  419. return 'input'
  420. class Output(Value):
  421. """A value that pushes a node onto the output queue."""
  422. def __init__(self, value):
  423. Value.__init__(self)
  424. self.value = value
  425. assert isinstance(value, Definition)
  426. def get_dependencies(self):
  427. """Gets all definitions and instructions on which this instruction depends."""
  428. return [self.value]
  429. def has_value(self):
  430. """Tells if this value produces a result that is not None."""
  431. return False
  432. def has_side_effects(self):
  433. """Tells if this instruction has side-effects."""
  434. return True
  435. def __str__(self):
  436. return 'output %s' % self.value.ref_str()
  437. class Binary(Value):
  438. """A value that applies a binary operator to two other values."""
  439. def __init__(self, lhs, operator, rhs):
  440. Value.__init__(self)
  441. self.lhs = lhs
  442. assert isinstance(lhs, Definition)
  443. self.operator = operator
  444. self.rhs = rhs
  445. assert isinstance(rhs, Definition)
  446. def get_dependencies(self):
  447. """Gets all definitions and instructions on which this instruction depends."""
  448. return [self.lhs, self.rhs]
  449. def __str__(self):
  450. return 'binary %s, %r, %s' % (self.lhs.ref_str(), self.operator, self.rhs.ref_str())
  451. def create_jump(block, arguments=None):
  452. """Creates a jump to the given block with the given argument list."""
  453. return JumpFlow(Branch(block, arguments))
  454. def apply_to_value(function, def_or_value):
  455. """Applies the given function to the specified value, or the underlying value of the
  456. given definition."""
  457. if isinstance(def_or_value, Definition):
  458. return apply_to_value(function, def_or_value.value)
  459. else:
  460. return function(def_or_value)
  461. def is_literal(value):
  462. """Tests if the given value is a literal."""
  463. return isinstance(value, Literal)
  464. def is_literal_def(def_or_value):
  465. """Tests if the given value is a literal or a definition with an underlying literal."""
  466. return apply_to_value(is_literal, def_or_value)
  467. def is_value_def(def_or_value, class_or_type_or_tuple=Value):
  468. """Tests if the given definition or value is a value of the given type."""
  469. if isinstance(def_or_value, Definition):
  470. return is_value_def(def_or_value.value, class_or_type_or_tuple)
  471. else:
  472. return isinstance(def_or_value, class_or_type_or_tuple)
  473. def get_def_variable(def_or_value):
  474. """Gets the 'variable' attribute of the given value, or the underlying value of the given
  475. definition, whichever is appropriate."""
  476. if isinstance(def_or_value, Definition):
  477. return get_def_variable(def_or_value.value)
  478. else:
  479. return def_or_value.variable
  480. def get_literal_value(value):
  481. """Gets the value of the given literal value."""
  482. return value.literal
  483. def get_literal_def_value(def_or_value):
  484. """Gets the value of the given literal value or definition with an underlying literal."""
  485. return apply_to_value(get_literal_value, def_or_value)