cfg_ir.py 19 KB

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