cfg_ir.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  1. """Defines control flow graph IR data structures."""
  2. from collections import defaultdict
  3. # Let's just agree to disagree on map vs list comprehensions, pylint.
  4. # pylint: disable=I0011,W0141
  5. class SharedCounter(object):
  6. """Defines a shared counter."""
  7. def __init__(self):
  8. self.index = 0
  9. def next_value(self):
  10. """Gets the next value for this counter."""
  11. result = self.index
  12. self.index += 1
  13. return result
  14. class BasicBlock(object):
  15. """Represents a basic block."""
  16. def __init__(self, counter):
  17. self.parameters = []
  18. self.definitions = []
  19. self.counter = counter
  20. self.index = counter.next_value()
  21. self.definition_counter = SharedCounter()
  22. self.flow = UnreachableFlow()
  23. def append_parameter(self, parameter):
  24. """Appends a parameter to this basic block."""
  25. if isinstance(parameter, Definition):
  26. assert isinstance(parameter.value, BlockParameter)
  27. else:
  28. assert isinstance(parameter, BlockParameter)
  29. result = self.create_definition(parameter)
  30. self.parameters.append(result)
  31. if len(self.definitions) > 0:
  32. self.renumber_definitions()
  33. return result
  34. def remove_parameter(self, parameter):
  35. """Removes the given parameter definition from this basic block."""
  36. return self.parameters.remove(parameter)
  37. def prepend_definition(self, value):
  38. """Defines the given value in this basic block."""
  39. result = self.create_definition(value)
  40. self.definitions.insert(0, result)
  41. self.renumber_definitions()
  42. return result
  43. def insert_definition_before(self, anchor, value):
  44. """Inserts the second definition or value before the first definition."""
  45. index = None
  46. for i, definition in enumerate(self.definitions):
  47. if definition.definition_index == anchor.definition_index:
  48. index = i
  49. if index is None:
  50. raise ValueError(
  51. 'Cannot insert a definition because the anchor '
  52. 'is not defined in this block.')
  53. result = self.create_definition(value)
  54. self.definitions.insert(index, result)
  55. self.renumber_definitions()
  56. return result
  57. def append_definition(self, value):
  58. """Defines the given value in this basic block."""
  59. result = self.create_definition(value)
  60. self.definitions.append(result)
  61. return result
  62. def create_definition(self, value=None):
  63. """Creates a definition, but does not assign it to this block yet."""
  64. if isinstance(value, Definition):
  65. value.block = self
  66. value.renumber(self.definition_counter.next_value())
  67. return value
  68. else:
  69. assert isinstance(value, Value) or value is None
  70. return Definition(
  71. self.counter.next_value(),
  72. self,
  73. self.definition_counter.next_value(),
  74. value)
  75. def remove_definition(self, definition):
  76. """Removes the given definition from this basic block."""
  77. return self.definitions.remove(definition)
  78. def renumber_definitions(self):
  79. """Re-numbers all definitions in this basic block."""
  80. self.definition_counter = SharedCounter()
  81. for definition in self.parameters:
  82. definition.renumber(self.definition_counter.next_value())
  83. for definition in self.definitions:
  84. definition.renumber(self.definition_counter.next_value())
  85. def __str__(self):
  86. prefix = '!%d(%s):' % (self.index, ', '.join(map(str, self.parameters)))
  87. return '\n'.join(
  88. [prefix] +
  89. [' ' * 4 + str(item) for item in self.definitions + [self.flow]])
  90. class Definition(object):
  91. """Maps a value to a variable."""
  92. def __init__(self, index, block, definition_index, value):
  93. self.index = index
  94. self.block = block
  95. self.definition_index = definition_index
  96. self.value = value
  97. if value is not None:
  98. assert isinstance(value, Value) or isinstance(value, Definition)
  99. def redefine(self, new_value):
  100. """Tweaks this definition to take on the given new value."""
  101. self.value = new_value
  102. if new_value is not None:
  103. assert isinstance(new_value, Value) or isinstance(new_value, Definition)
  104. def renumber(self, new_definition_index):
  105. """Updates this definition's index in the block that defines it."""
  106. self.definition_index = new_definition_index
  107. def get_all_dependencies(self):
  108. """Gets all definitions and instructions on which this definition depends,
  109. along with any dependencies of instruction dependencies."""
  110. if isinstance(self.value, Definition):
  111. return [self.value]
  112. else:
  113. return self.value.get_all_dependencies()
  114. def get_all_filtered_dependencies(self, function):
  115. """Gets all definitions and instructions on which this instruction depends,
  116. along with any dependencies of instruction dependencies. Dependency trees
  117. are filtered by a Boolean-returning function."""
  118. if isinstance(self.value, Definition):
  119. return list(filter(function, [self.value]))
  120. else:
  121. return self.value.get_all_filtered_dependencies(function)
  122. def has_side_effects(self):
  123. """Tests if this definition produces any side-effects."""
  124. return self.value.has_side_effects()
  125. def has_value(self):
  126. """Tells if this definition produces a result that is not None."""
  127. return self.value.has_value()
  128. def insert_before(self, value):
  129. """Inserts the given value or definition before this definition."""
  130. return self.block.insert_definition_before(self, value)
  131. def ref_str(self):
  132. """Gets a string that represents a reference to this definition."""
  133. return '$%d' % self.index
  134. def __str__(self):
  135. return '$%d = %s' % (self.index, self.value.ref_str())
  136. class Instruction(object):
  137. """Represents an instruction."""
  138. def get_dependencies(self):
  139. """Gets all definitions and instructions on which this instruction depends."""
  140. raise NotImplementedError()
  141. def create(self, new_dependencies):
  142. """Creates an instruction of this type from the given set of dependencies."""
  143. raise NotImplementedError()
  144. def get_all_dependencies(self):
  145. """Gets all definitions and instructions on which this instruction depends,
  146. along with any dependencies of instruction dependencies."""
  147. results = list(self.get_dependencies())
  148. for item in results:
  149. if not isinstance(item, Definition):
  150. results.extend(item.get_all_dependencies())
  151. return results
  152. def get_all_filtered_dependencies(self, function):
  153. """Gets all definitions and instructions on which this instruction depends,
  154. along with any dependencies of instruction dependencies. Dependency trees
  155. are filtered by a Boolean-returning function."""
  156. results = list(filter(function, self.get_dependencies()))
  157. for item in results:
  158. if not isinstance(item, Definition):
  159. results.extend(item.get_all_filtered_dependencies(function))
  160. return results
  161. class Branch(Instruction):
  162. """Represents a branch from one basic block to another."""
  163. def __init__(self, block, arguments=None):
  164. self.block = block
  165. assert isinstance(block, BasicBlock)
  166. if arguments is None:
  167. arguments = []
  168. self.arguments = arguments
  169. assert all([isinstance(arg, Definition) for arg in arguments])
  170. def get_dependencies(self):
  171. """Gets all definitions and instructions on which this instruction depends."""
  172. return self.arguments
  173. def create(self, new_dependencies):
  174. """Creates an instruction of this type from the given set of dependencies."""
  175. return Branch(self.block, new_dependencies)
  176. def __str__(self):
  177. return '!%d(%s)' % (self.block.index, ', '.join([arg.ref_str() for arg in self.arguments]))
  178. class FlowInstruction(Instruction):
  179. """Represents a control flow instruction which terminates a basic block."""
  180. def branches(self):
  181. """Gets a list of basic blocks targeted by this flow instruction."""
  182. raise NotImplementedError()
  183. def has_side_effects(self):
  184. """Tells if this instruction has side-effects."""
  185. # All flow-instructions have side-effects!
  186. return True
  187. class JumpFlow(FlowInstruction):
  188. """Represents a control flow instruction which jumps directly to a basic block."""
  189. def __init__(self, branch):
  190. FlowInstruction.__init__(self)
  191. self.branch = branch
  192. assert isinstance(branch, Branch)
  193. def get_dependencies(self):
  194. """Gets all definitions and instructions on which this instruction depends."""
  195. return self.branches()
  196. def create(self, new_dependencies):
  197. """Creates an instruction of this type from the given set of dependencies."""
  198. return JumpFlow(*new_dependencies)
  199. def branches(self):
  200. """Gets a list of basic blocks targeted by this flow instruction."""
  201. return [self.branch]
  202. def __str__(self):
  203. return 'jump %s' % self.branch
  204. class SelectFlow(FlowInstruction):
  205. """Represents a control flow instruction which jumps to one of two basic blocks depending
  206. on whether a condition is truthy or not."""
  207. def __init__(self, condition, if_branch, else_branch):
  208. FlowInstruction.__init__(self)
  209. self.condition = condition
  210. assert isinstance(condition, Definition)
  211. self.if_branch = if_branch
  212. assert isinstance(if_branch, Branch)
  213. self.else_branch = else_branch
  214. assert isinstance(else_branch, Branch)
  215. def get_dependencies(self):
  216. """Gets all definitions and instructions on which this instruction depends."""
  217. return [self.condition] + self.branches()
  218. def create(self, new_dependencies):
  219. """Creates an instruction of this type from the given set of dependencies."""
  220. return SelectFlow(*new_dependencies)
  221. def branches(self):
  222. """Gets a list of basic blocks targeted by this flow instruction."""
  223. return [self.if_branch, self.else_branch]
  224. def __str__(self):
  225. return 'select %s, %s, %s' % (self.condition.ref_str(), self.if_branch, self.else_branch)
  226. class ReturnFlow(FlowInstruction):
  227. """Represents a control flow instruction which terminates the execution of the current
  228. function and returns a value."""
  229. def __init__(self, value):
  230. FlowInstruction.__init__(self)
  231. self.value = value
  232. assert isinstance(value, Definition)
  233. def get_dependencies(self):
  234. """Gets all definitions and instructions on which this instruction depends."""
  235. return [self.value]
  236. def create(self, new_dependencies):
  237. """Creates an instruction of this type from the given set of dependencies."""
  238. return ReturnFlow(*new_dependencies)
  239. def branches(self):
  240. """Gets a list of basic blocks targeted by this flow instruction."""
  241. return []
  242. def __str__(self):
  243. return 'return %s' % self.value.ref_str()
  244. class ThrowFlow(FlowInstruction):
  245. """Represents a control flow instruction which throws an exception."""
  246. def __init__(self, exception):
  247. FlowInstruction.__init__(self)
  248. self.exception = exception
  249. assert isinstance(exception, Definition)
  250. def get_dependencies(self):
  251. """Gets all definitions and instructions on which this instruction depends."""
  252. return [self.exception]
  253. def create(self, new_dependencies):
  254. """Creates an instruction of this type from the given set of dependencies."""
  255. return ThrowFlow(*new_dependencies)
  256. def branches(self):
  257. """Gets a list of basic blocks targeted by this flow instruction."""
  258. return []
  259. def __str__(self):
  260. return 'throw %s' % self.exception.ref_str()
  261. class UnreachableFlow(FlowInstruction):
  262. """Represents a control flow instruction which is unreachable."""
  263. def get_dependencies(self):
  264. """Gets all definitions and instructions on which this instruction depends."""
  265. return []
  266. def create(self, new_dependencies):
  267. """Creates an instruction of this type from the given set of dependencies."""
  268. assert len(new_dependencies) == 0
  269. return self
  270. def branches(self):
  271. """Gets a list of basic blocks targeted by this flow instruction."""
  272. return []
  273. def __str__(self):
  274. return 'unreachable'
  275. class Value(Instruction):
  276. """A value: an instruction that produces some result."""
  277. def get_dependencies(self):
  278. """Gets all definitions and instructions on which this instruction depends."""
  279. raise NotImplementedError()
  280. def has_value(self):
  281. """Tells if this value produces a result that is not None."""
  282. return True
  283. def has_side_effects(self):
  284. """Tells if this instruction has side-effects."""
  285. return False
  286. def ref_str(self):
  287. """Gets a string that represents this value."""
  288. return str(self)
  289. class BlockParameter(Value):
  290. """A basic block parameter."""
  291. def get_dependencies(self):
  292. """Gets all definitions and instructions on which this instruction depends."""
  293. return []
  294. def create(self, new_dependencies):
  295. """Creates an instruction of this type from the given set of dependencies."""
  296. assert len(new_dependencies) == 0
  297. return BlockParameter()
  298. def __str__(self):
  299. return 'block-parameter'
  300. class FunctionParameter(Value):
  301. """A function parameter."""
  302. def __init__(self, name):
  303. Value.__init__(self)
  304. self.name = name
  305. def create(self, new_dependencies):
  306. """Creates an instruction of this type from the given set of dependencies."""
  307. assert len(new_dependencies) == 0
  308. return FunctionParameter(self.name)
  309. def get_dependencies(self):
  310. """Gets all definitions and instructions on which this instruction depends."""
  311. return []
  312. def __str__(self):
  313. return 'func-parameter %s' % self.name
  314. class Literal(Value):
  315. """A literal value."""
  316. def __init__(self, literal):
  317. Value.__init__(self)
  318. self.literal = literal
  319. def create(self, new_dependencies):
  320. """Creates an instruction of this type from the given set of dependencies."""
  321. assert len(new_dependencies) == 0
  322. return Literal(self.literal)
  323. def get_dependencies(self):
  324. """Gets all definitions and instructions on which this instruction depends."""
  325. return []
  326. def has_value(self):
  327. """Tells if this value produces a result that is not None."""
  328. return self.literal is not None
  329. def __str__(self):
  330. return 'literal %r' % self.literal
  331. class IndirectFunctionCall(Value):
  332. """A value that is the result of an indirect function call."""
  333. def __init__(self, target, argument_list):
  334. Value.__init__(self)
  335. assert isinstance(target, Definition)
  336. self.target = target
  337. assert all([isinstance(val, Definition) for _, val in argument_list])
  338. self.argument_list = argument_list
  339. def has_side_effects(self):
  340. """Tells if this instruction has side-effects."""
  341. return True
  342. def get_dependencies(self):
  343. """Gets all definitions and instructions on which this instruction depends."""
  344. return [self.target] + [val for _, val in self.argument_list]
  345. def create(self, new_dependencies):
  346. """Creates an instruction of this type from the given set of dependencies."""
  347. return IndirectFunctionCall(
  348. new_dependencies[0],
  349. [(name, new_val)
  350. for new_val, (name, _) in zip(new_dependencies[1:], self.argument_list)])
  351. def __str__(self):
  352. return 'indirect-call %s(%s)' % (
  353. self.target.ref_str(),
  354. ', '.join(['%s=%s' % (key, val.ref_str()) for key, val in self.argument_list]))
  355. SIMPLE_POSITIONAL_CALLING_CONVENTION = 'simple-positional'
  356. """The calling convention for functions that use 'return' statements to return.
  357. Arguments are matched to parameters based on position."""
  358. JIT_CALLING_CONVENTION = 'jit'
  359. """The calling convention for jitted functions."""
  360. MACRO_POSITIONAL_CALLING_CONVENTION = 'macro-positional'
  361. """The calling convention for well-known functions that are expanded as macros during codegen."""
  362. PRINT_MACRO_NAME = 'print'
  363. """The name of the 'print' macro."""
  364. class DirectFunctionCall(Value):
  365. """A value that is the result of a direct function call."""
  366. def __init__(
  367. self, target_name, argument_list,
  368. calling_convention=JIT_CALLING_CONVENTION,
  369. has_value=True,
  370. has_side_effects=True):
  371. Value.__init__(self)
  372. self.target_name = target_name
  373. assert all([isinstance(val, Definition) for _, val in argument_list])
  374. self.argument_list = argument_list
  375. self.calling_convention = calling_convention
  376. self.has_value_val = has_value
  377. self.has_side_effects_val = has_side_effects
  378. def has_side_effects(self):
  379. """Tells if this instruction has side-effects."""
  380. return self.has_side_effects_val
  381. def has_value(self):
  382. """Tells if this value produces a result that is not None."""
  383. return self.has_value_val
  384. def create(self, new_dependencies):
  385. """Creates an instruction of this type from the given set of dependencies."""
  386. return DirectFunctionCall(
  387. self.target_name,
  388. [(name, new_val)
  389. for new_val, (name, _) in zip(new_dependencies, self.argument_list)],
  390. self.calling_convention, self.has_value_val, self.has_side_effects_val)
  391. def get_dependencies(self):
  392. """Gets all definitions and instructions on which this instruction depends."""
  393. return [val for _, val in self.argument_list]
  394. def format_calling_convention_tuple(self):
  395. """Formats this direct function call's extended calling convention tuple.
  396. The result is a formatted string that consists of a calling convention,
  397. and optionally information that pertains to whether the function returns
  398. a value and has side-effects."""
  399. if self.has_side_effects() and self.has_value():
  400. return repr(self.calling_convention)
  401. contents = [repr(self.calling_convention)]
  402. if not self.has_side_effects():
  403. contents.append('pure')
  404. if not self.has_value():
  405. contents.append('void')
  406. return '(%s)' % ', '.join(contents)
  407. def __str__(self):
  408. return 'direct-call %s %s(%s)' % (
  409. self.format_calling_convention_tuple(),
  410. self.target_name,
  411. ', '.join(['%s=%s' % (key, val.ref_str()) for key, val in self.argument_list]))
  412. class AllocateRootNode(Value):
  413. """A value that produces a new root node. Typically used in function prologs."""
  414. def __init__(self):
  415. Value.__init__(self)
  416. def get_dependencies(self):
  417. """Gets all definitions and instructions on which this instruction depends."""
  418. return []
  419. def create(self, new_dependencies):
  420. """Creates an instruction of this type from the given set of dependencies."""
  421. assert len(new_dependencies) == 0
  422. return AllocateRootNode()
  423. def __str__(self):
  424. return 'alloc-root-node'
  425. class DeallocateRootNode(Value):
  426. """A value that deallocates a root node. Typically used in function epilogs."""
  427. def __init__(self, root_node):
  428. Value.__init__(self)
  429. assert isinstance(root_node, Definition)
  430. self.root_node = root_node
  431. def get_dependencies(self):
  432. """Gets all definitions and instructions on which this instruction depends."""
  433. return [self.root_node]
  434. def create(self, new_dependencies):
  435. """Creates an instruction of this type from the given set of dependencies."""
  436. return DeallocateRootNode(*new_dependencies)
  437. def has_value(self):
  438. """Tells if this value produces a result that is not None."""
  439. return False
  440. def has_side_effects(self):
  441. """Tells if this instruction has side-effects."""
  442. return True
  443. def __str__(self):
  444. return 'free-root-node %s' % self.root_node.ref_str()
  445. class DeclareLocal(Value):
  446. """A value that declares a local variable."""
  447. def __init__(self, variable, root_node):
  448. Value.__init__(self)
  449. self.variable = variable
  450. self.root_node = root_node
  451. def get_dependencies(self):
  452. """Gets all definitions and instructions on which this instruction depends."""
  453. return [self.root_node]
  454. def create(self, new_dependencies):
  455. """Creates an instruction of this type from the given set of dependencies."""
  456. root_node, = new_dependencies
  457. return DeclareLocal(self.variable, root_node)
  458. def has_value(self):
  459. """Tells if this value produces a result that is not None."""
  460. return False
  461. def has_side_effects(self):
  462. """Tells if this instruction has side-effects."""
  463. return True
  464. def __str__(self):
  465. return 'declare-local %s, %s' % (self.variable, self.root_node.ref_str())
  466. class DeclareGlobal(Value):
  467. """A value that declares a global variable."""
  468. def __init__(self, variable):
  469. Value.__init__(self)
  470. self.variable = variable
  471. def get_dependencies(self):
  472. """Gets all definitions and instructions on which this instruction depends."""
  473. return []
  474. def create(self, new_dependencies):
  475. """Creates an instruction of this type from the given set of dependencies."""
  476. return DeclareGlobal(self.variable)
  477. def has_value(self):
  478. """Tells if this value produces a result that is not None."""
  479. return False
  480. def has_side_effects(self):
  481. """Tells if this instruction has side-effects."""
  482. return True
  483. def __str__(self):
  484. return 'declare-global %s' % self.variable.name
  485. class CheckLocalExists(Value):
  486. """A value that checks if a local value has been defined (yet)."""
  487. def __init__(self, variable):
  488. Value.__init__(self)
  489. self.variable = variable
  490. def get_dependencies(self):
  491. """Gets all definitions and instructions on which this instruction depends."""
  492. return []
  493. def create(self, new_dependencies):
  494. """Creates an instruction of this type from the given set of dependencies."""
  495. return CheckLocalExists(self.variable)
  496. def __str__(self):
  497. return 'check-local-exists %s' % self.variable
  498. class ResolveLocal(Value):
  499. """A value that resolves a local as a pointer."""
  500. def __init__(self, variable):
  501. Value.__init__(self)
  502. self.variable = variable
  503. def get_dependencies(self):
  504. """Gets all definitions and instructions on which this instruction depends."""
  505. return []
  506. def create(self, new_dependencies):
  507. """Creates an instruction of this type from the given set of dependencies."""
  508. return ResolveLocal(self.variable)
  509. def __str__(self):
  510. return 'resolve-local %s' % self.variable
  511. class ResolveGlobal(Value):
  512. """A value that resolves a global as a pointer."""
  513. def __init__(self, variable):
  514. Value.__init__(self)
  515. self.variable = variable
  516. def get_dependencies(self):
  517. """Gets all definitions and instructions on which this instruction depends."""
  518. return []
  519. def create(self, new_dependencies):
  520. """Creates an instruction of this type from the given set of dependencies."""
  521. return ResolveGlobal(self.variable)
  522. def __str__(self):
  523. return 'resolve-global %s' % self.variable.name
  524. class LoadPointer(Value):
  525. """A value that loads the value assigned to a pointer."""
  526. def __init__(self, pointer):
  527. Value.__init__(self)
  528. self.pointer = pointer
  529. assert isinstance(pointer, Definition)
  530. def get_dependencies(self):
  531. """Gets all definitions and instructions on which this instruction depends."""
  532. return [self.pointer]
  533. def create(self, new_dependencies):
  534. """Creates an instruction of this type from the given set of dependencies."""
  535. return LoadPointer(*new_dependencies)
  536. def __str__(self):
  537. return 'load %s' % self.pointer.ref_str()
  538. class StoreAtPointer(Value):
  539. """A value that assigns a value to a pointer."""
  540. def __init__(self, pointer, value):
  541. Value.__init__(self)
  542. self.pointer = pointer
  543. assert isinstance(pointer, Definition)
  544. self.value = value
  545. assert isinstance(value, Definition)
  546. def get_dependencies(self):
  547. """Gets all definitions and instructions on which this instruction depends."""
  548. return [self.pointer, self.value]
  549. def create(self, new_dependencies):
  550. """Creates an instruction of this type from the given set of dependencies."""
  551. return StoreAtPointer(*new_dependencies)
  552. def has_value(self):
  553. """Tells if this value produces a result that is not None."""
  554. return False
  555. def has_side_effects(self):
  556. """Tells if this instruction has side-effects."""
  557. return True
  558. def __str__(self):
  559. return 'store %s, %s' % (self.pointer.ref_str(), self.value.ref_str())
  560. class Read(Value):
  561. """A value that reads the value stored in a node."""
  562. def __init__(self, node):
  563. Value.__init__(self)
  564. self.node = node
  565. assert isinstance(node, Definition)
  566. def get_dependencies(self):
  567. """Gets all definitions and instructions on which this instruction depends."""
  568. return [self.node]
  569. def create(self, new_dependencies):
  570. """Creates an instruction of this type from the given set of dependencies."""
  571. return Read(*new_dependencies)
  572. def __str__(self):
  573. return 'read %s' % (self.node.ref_str())
  574. class CreateNode(Value):
  575. """A value that creates a new node."""
  576. def __init__(self, value):
  577. Value.__init__(self)
  578. self.value = value
  579. assert isinstance(value, Definition)
  580. def get_dependencies(self):
  581. """Gets all definitions and instructions on which this instruction depends."""
  582. return [self.value]
  583. def create(self, new_dependencies):
  584. """Creates an instruction of this type from the given set of dependencies."""
  585. return CreateNode(*new_dependencies)
  586. def __str__(self):
  587. return 'create-node %s' % (self.value.ref_str())
  588. class Input(Value):
  589. """A value that pops a node from the input queue."""
  590. def get_dependencies(self):
  591. """Gets all definitions and instructions on which this instruction depends."""
  592. return []
  593. def create(self, new_dependencies):
  594. """Creates an instruction of this type from the given set of dependencies."""
  595. assert len(new_dependencies) == 0
  596. return Input()
  597. def has_side_effects(self):
  598. """Tells if this instruction has side-effects."""
  599. return True
  600. def __str__(self):
  601. return 'input'
  602. class Output(Value):
  603. """A value that pushes a node onto the output queue."""
  604. def __init__(self, value):
  605. Value.__init__(self)
  606. self.value = value
  607. assert isinstance(value, Definition)
  608. def get_dependencies(self):
  609. """Gets all definitions and instructions on which this instruction depends."""
  610. return [self.value]
  611. def create(self, new_dependencies):
  612. """Creates an instruction of this type from the given set of dependencies."""
  613. return Output(*new_dependencies)
  614. def has_value(self):
  615. """Tells if this value produces a result that is not None."""
  616. return False
  617. def has_side_effects(self):
  618. """Tells if this instruction has side-effects."""
  619. return True
  620. def __str__(self):
  621. return 'output %s' % self.value.ref_str()
  622. class Binary(Value):
  623. """A value that applies a binary operator to two other values."""
  624. def __init__(self, lhs, operator, rhs):
  625. Value.__init__(self)
  626. self.lhs = lhs
  627. assert isinstance(lhs, Definition)
  628. self.operator = operator
  629. self.rhs = rhs
  630. assert isinstance(rhs, Definition)
  631. def get_dependencies(self):
  632. """Gets all definitions and instructions on which this instruction depends."""
  633. return [self.lhs, self.rhs]
  634. def create(self, new_dependencies):
  635. """Creates an instruction of this type from the given set of dependencies."""
  636. lhs, rhs = new_dependencies
  637. return Binary(lhs, self.operator, rhs)
  638. def __str__(self):
  639. return 'binary %s, %r, %s' % (self.lhs.ref_str(), self.operator, self.rhs.ref_str())
  640. def create_jump(block, arguments=None):
  641. """Creates a jump to the given block with the given argument list."""
  642. return JumpFlow(Branch(block, arguments))
  643. def create_print(argument):
  644. """Creates a value that prints the specified argument."""
  645. return DirectFunctionCall(
  646. PRINT_MACRO_NAME, [('argument', argument)],
  647. calling_convention=MACRO_POSITIONAL_CALLING_CONVENTION,
  648. has_value=False)
  649. def get_def_value(def_or_value):
  650. """Returns the given value, or the underlying value of the given definition, whichever is
  651. appropriate."""
  652. if isinstance(def_or_value, Definition):
  653. return get_def_value(def_or_value.value)
  654. else:
  655. return def_or_value
  656. def apply_to_value(function, def_or_value):
  657. """Applies the given function to the specified value, or the underlying value of the
  658. given definition."""
  659. return function(get_def_value(def_or_value))
  660. def is_literal(value):
  661. """Tests if the given value is a literal."""
  662. return isinstance(value, Literal)
  663. def is_literal_def(def_or_value):
  664. """Tests if the given value is a literal or a definition with an underlying literal."""
  665. return apply_to_value(is_literal, def_or_value)
  666. def is_value_def(def_or_value, class_or_type_or_tuple=Value):
  667. """Tests if the given definition or value is a value of the given type."""
  668. return isinstance(get_def_value(def_or_value), class_or_type_or_tuple)
  669. def get_def_variable(def_or_value):
  670. """Gets the 'variable' attribute of the given value, or the underlying value of the given
  671. definition, whichever is appropriate."""
  672. return get_def_value(def_or_value).variable
  673. def get_literal_value(value):
  674. """Gets the value of the given literal value."""
  675. return value.literal
  676. def get_literal_def_value(def_or_value):
  677. """Gets the value of the given literal value or definition with an underlying literal."""
  678. return apply_to_value(get_literal_value, def_or_value)
  679. def get_all_predecessor_blocks(entry_point):
  680. """Creates a mapping of blocks to their direct predecessors for every block in the control-flow
  681. graph defined by the given entry point."""
  682. results = defaultdict(set)
  683. processed = set()
  684. def __find_predecessors_step(block):
  685. if block in processed:
  686. return
  687. processed.add(block)
  688. for branch in block.flow.branches():
  689. target_block = branch.block
  690. results[target_block].add(block)
  691. __find_predecessors_step(target_block)
  692. __find_predecessors_step(entry_point)
  693. return results
  694. def get_directly_reachable_blocks(block):
  695. """Gets the set of all blocks that can be reached by taking a single branch from the
  696. given block."""
  697. return [branch.block for branch in block.flow.branches()]
  698. def get_reachable_blocks(entry_point):
  699. """Constructs the set of all reachable vertices from the given block."""
  700. # This is a simple O(n^2) algorithm. Maybe a faster algorithm is more appropriate here.
  701. def __add_block_children(block, results):
  702. for child in get_directly_reachable_blocks(block):
  703. if child not in results:
  704. results.add(child)
  705. __add_block_children(child, results)
  706. return results
  707. return __add_block_children(entry_point, set())
  708. def get_all_reachable_blocks(entry_point):
  709. """Constructs the set of all reachable vertices, for every block that is
  710. reachable from the given entry point."""
  711. # This is a simple O(n^3) algorithm. Maybe a faster algorithm is more appropriate here.
  712. results = {}
  713. all_blocks = get_reachable_blocks(entry_point)
  714. results[entry_point] = all_blocks
  715. for block in all_blocks:
  716. if block not in results:
  717. results[block] = get_reachable_blocks(block)
  718. return results
  719. def get_all_blocks(entry_point):
  720. """Gets all basic blocks in the control-flow graph defined by the given entry point."""
  721. yield entry_point
  722. for block in get_reachable_blocks(entry_point):
  723. yield block
  724. def get_trivial_phi_value(parameter_def, values):
  725. """Tests if the given parameter definition is an alias for another definition.
  726. If so, then the other definition is returned; otherwise, None."""
  727. result = None
  728. for elem in values:
  729. if elem is not parameter_def:
  730. if result is None:
  731. result = elem
  732. else:
  733. return None
  734. return result
  735. def match_and_rewrite(entry_point, match_def, match_use, rewrite_def, rewrite_use):
  736. """Matches and rewrites chains of definitions and uses in the graph defined by
  737. the given entry point."""
  738. ineligible_defs = set()
  739. used_defs = defaultdict(set)
  740. all_blocks = list(get_all_blocks(entry_point))
  741. connected_defs = defaultdict(set)
  742. # Figure out which defs and which uses match.
  743. for block in all_blocks:
  744. for definition in block.definitions + [block.flow]:
  745. is_def_of_def = False
  746. if isinstance(definition, Definition):
  747. if isinstance(definition.value, Definition):
  748. is_def_of_def = True
  749. connected_defs[definition].add(definition.value)
  750. connected_defs[definition.value].add(definition)
  751. elif not match_def(definition):
  752. ineligible_defs.add(definition)
  753. else:
  754. ineligible_defs.add(definition)
  755. if not is_def_of_def:
  756. for dependency in definition.get_all_filtered_dependencies(
  757. lambda dep: not isinstance(dep, Branch)):
  758. if (isinstance(dependency, Definition)
  759. and dependency not in ineligible_defs):
  760. if match_use(definition, dependency):
  761. used_defs[definition].add(dependency)
  762. else:
  763. ineligible_defs.add(dependency)
  764. for branch in block.flow.branches():
  765. for param, arg in zip(branch.block.parameters, branch.arguments):
  766. connected_defs[arg].add(param)
  767. connected_defs[param].add(arg)
  768. def spread_ineligible(ineligible_definition):
  769. """Spreads 'ineligible' to all connected definitions."""
  770. for connected in connected_defs[ineligible_definition]:
  771. if connected not in ineligible_defs:
  772. ineligible_defs.add(connected)
  773. spread_ineligible(connected)
  774. ineligible_roots = list(ineligible_defs)
  775. for root in ineligible_roots:
  776. spread_ineligible(root)
  777. # Replace defs and uses.
  778. for block in all_blocks:
  779. for definition in block.definitions + [block.flow]:
  780. if (definition not in ineligible_defs
  781. and not isinstance(definition.value, Definition)):
  782. rewrite_def(definition)
  783. for dependency in used_defs[definition]:
  784. if dependency not in ineligible_defs:
  785. rewrite_use(definition, dependency)