cfg_ir.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  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 has_side_effects(self):
  115. """Tests if this definition produces any side-effects."""
  116. return self.value.has_side_effects()
  117. def has_value(self):
  118. """Tells if this definition produces a result that is not None."""
  119. return self.value.has_value()
  120. def insert_before(self, value):
  121. """Inserts the given value or definition before this definition."""
  122. return self.block.insert_definition_before(self, value)
  123. def ref_str(self):
  124. """Gets a string that represents a reference to this definition."""
  125. return '$%d' % self.index
  126. def __str__(self):
  127. return '$%d = %s' % (self.index, self.value.ref_str())
  128. class Instruction(object):
  129. """Represents an instruction."""
  130. def get_dependencies(self):
  131. """Gets all definitions and instructions on which this instruction depends."""
  132. raise NotImplementedError()
  133. def create(self, new_dependencies):
  134. """Creates an instruction of this type from the given set of dependencies."""
  135. raise NotImplementedError()
  136. def get_all_dependencies(self):
  137. """Gets all definitions and instructions on which this instruction depends,
  138. along with any dependencies of instruction dependencies."""
  139. results = list(self.get_dependencies())
  140. for item in results:
  141. if not isinstance(item, Definition):
  142. results.extend(item.get_all_dependencies())
  143. return results
  144. class Branch(Instruction):
  145. """Represents a branch from one basic block to another."""
  146. def __init__(self, block, arguments=None):
  147. self.block = block
  148. assert isinstance(block, BasicBlock)
  149. if arguments is None:
  150. arguments = []
  151. self.arguments = arguments
  152. assert all([isinstance(arg, Definition) for arg in arguments])
  153. def get_dependencies(self):
  154. """Gets all definitions and instructions on which this instruction depends."""
  155. return self.arguments
  156. def create(self, new_dependencies):
  157. """Creates an instruction of this type from the given set of dependencies."""
  158. return Branch(self.block, new_dependencies)
  159. def __str__(self):
  160. return '!%d(%s)' % (self.block.index, ', '.join([arg.ref_str() for arg in self.arguments]))
  161. class FlowInstruction(Instruction):
  162. """Represents a control flow instruction which terminates a basic block."""
  163. def branches(self):
  164. """Gets a list of basic blocks targeted by this flow instruction."""
  165. raise NotImplementedError()
  166. def has_side_effects(self):
  167. """Tells if this instruction has side-effects."""
  168. # All flow-instructions have side-effects!
  169. return True
  170. class JumpFlow(FlowInstruction):
  171. """Represents a control flow instruction which jumps directly to a basic block."""
  172. def __init__(self, branch):
  173. FlowInstruction.__init__(self)
  174. self.branch = branch
  175. assert isinstance(branch, Branch)
  176. def get_dependencies(self):
  177. """Gets all definitions and instructions on which this instruction depends."""
  178. return self.branches()
  179. def create(self, new_dependencies):
  180. """Creates an instruction of this type from the given set of dependencies."""
  181. return JumpFlow(*new_dependencies)
  182. def branches(self):
  183. """Gets a list of basic blocks targeted by this flow instruction."""
  184. return [self.branch]
  185. def __str__(self):
  186. return 'jump %s' % self.branch
  187. class SelectFlow(FlowInstruction):
  188. """Represents a control flow instruction which jumps to one of two basic blocks depending
  189. on whether a condition is truthy or not."""
  190. def __init__(self, condition, if_branch, else_branch):
  191. FlowInstruction.__init__(self)
  192. self.condition = condition
  193. assert isinstance(condition, Definition)
  194. self.if_branch = if_branch
  195. assert isinstance(if_branch, Branch)
  196. self.else_branch = else_branch
  197. assert isinstance(else_branch, Branch)
  198. def get_dependencies(self):
  199. """Gets all definitions and instructions on which this instruction depends."""
  200. return [self.condition] + self.branches()
  201. def create(self, new_dependencies):
  202. """Creates an instruction of this type from the given set of dependencies."""
  203. return SelectFlow(*new_dependencies)
  204. def branches(self):
  205. """Gets a list of basic blocks targeted by this flow instruction."""
  206. return [self.if_branch, self.else_branch]
  207. def __str__(self):
  208. return 'select %s, %s, %s' % (self.condition.ref_str(), self.if_branch, self.else_branch)
  209. class ReturnFlow(FlowInstruction):
  210. """Represents a control flow instruction which terminates the execution of the current
  211. function and returns a value."""
  212. def __init__(self, value):
  213. FlowInstruction.__init__(self)
  214. self.value = value
  215. assert isinstance(value, Definition)
  216. def get_dependencies(self):
  217. """Gets all definitions and instructions on which this instruction depends."""
  218. return [self.value]
  219. def create(self, new_dependencies):
  220. """Creates an instruction of this type from the given set of dependencies."""
  221. return ReturnFlow(*new_dependencies)
  222. def branches(self):
  223. """Gets a list of basic blocks targeted by this flow instruction."""
  224. return []
  225. def __str__(self):
  226. return 'return %s' % self.value.ref_str()
  227. class ThrowFlow(FlowInstruction):
  228. """Represents a control flow instruction which throws an exception."""
  229. def __init__(self, exception):
  230. FlowInstruction.__init__(self)
  231. self.exception = exception
  232. assert isinstance(exception, Definition)
  233. def get_dependencies(self):
  234. """Gets all definitions and instructions on which this instruction depends."""
  235. return [self.exception]
  236. def create(self, new_dependencies):
  237. """Creates an instruction of this type from the given set of dependencies."""
  238. return ThrowFlow(*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 'throw %s' % self.exception.ref_str()
  244. class UnreachableFlow(FlowInstruction):
  245. """Represents a control flow instruction which is unreachable."""
  246. def get_dependencies(self):
  247. """Gets all definitions and instructions on which this instruction depends."""
  248. return []
  249. def create(self, new_dependencies):
  250. """Creates an instruction of this type from the given set of dependencies."""
  251. assert len(new_dependencies) == 0
  252. return self
  253. def branches(self):
  254. """Gets a list of basic blocks targeted by this flow instruction."""
  255. return []
  256. def __str__(self):
  257. return 'unreachable'
  258. class Value(Instruction):
  259. """A value: an instruction that produces some result."""
  260. def get_dependencies(self):
  261. """Gets all definitions and instructions on which this instruction depends."""
  262. raise NotImplementedError()
  263. def has_value(self):
  264. """Tells if this value produces a result that is not None."""
  265. return True
  266. def has_side_effects(self):
  267. """Tells if this instruction has side-effects."""
  268. return False
  269. def ref_str(self):
  270. """Gets a string that represents this value."""
  271. return str(self)
  272. class BlockParameter(Value):
  273. """A basic block parameter."""
  274. def get_dependencies(self):
  275. """Gets all definitions and instructions on which this instruction depends."""
  276. return []
  277. def create(self, new_dependencies):
  278. """Creates an instruction of this type from the given set of dependencies."""
  279. assert len(new_dependencies) == 0
  280. return BlockParameter()
  281. def __str__(self):
  282. return 'block-parameter'
  283. class FunctionParameter(Value):
  284. """A function parameter."""
  285. def __init__(self, name):
  286. Value.__init__(self)
  287. self.name = name
  288. def create(self, new_dependencies):
  289. """Creates an instruction of this type from the given set of dependencies."""
  290. assert len(new_dependencies) == 0
  291. return FunctionParameter(self.name)
  292. def get_dependencies(self):
  293. """Gets all definitions and instructions on which this instruction depends."""
  294. return []
  295. def __str__(self):
  296. return 'func-parameter %s' % self.name
  297. class Literal(Value):
  298. """A literal value."""
  299. def __init__(self, literal):
  300. Value.__init__(self)
  301. self.literal = literal
  302. def create(self, new_dependencies):
  303. """Creates an instruction of this type from the given set of dependencies."""
  304. assert len(new_dependencies) == 0
  305. return Literal(self.literal)
  306. def get_dependencies(self):
  307. """Gets all definitions and instructions on which this instruction depends."""
  308. return []
  309. def has_value(self):
  310. """Tells if this value produces a result that is not None."""
  311. return self.literal is not None
  312. def __str__(self):
  313. return 'literal %r' % self.literal
  314. class IndirectFunctionCall(Value):
  315. """A value that is the result of an indirect function call."""
  316. def __init__(self, target, argument_list):
  317. Value.__init__(self)
  318. assert isinstance(target, Definition)
  319. self.target = target
  320. assert all([isinstance(val, Definition) for _, val in argument_list])
  321. self.argument_list = argument_list
  322. def has_side_effects(self):
  323. """Tells if this instruction has side-effects."""
  324. return True
  325. def get_dependencies(self):
  326. """Gets all definitions and instructions on which this instruction depends."""
  327. return [self.target] + [val for _, val in self.argument_list]
  328. def create(self, new_dependencies):
  329. """Creates an instruction of this type from the given set of dependencies."""
  330. return IndirectFunctionCall(
  331. new_dependencies[0],
  332. [(name, new_val)
  333. for new_val, (name, _) in zip(new_dependencies[1:], self.argument_list)])
  334. def __str__(self):
  335. return 'indirect-call %s(%s)' % (
  336. self.target.ref_str(),
  337. ', '.join(['%s=%s' % (key, val.ref_str()) for key, val in self.argument_list]))
  338. SIMPLE_POSITIONAL_CALLING_CONVENTION = 'simple-positional'
  339. """The calling convention for functions that use 'return' statements to return.
  340. Arguments are matched to parameters based on position."""
  341. JIT_CALLING_CONVENTION = 'jit'
  342. """The calling convention for jitted functions."""
  343. MACRO_POSITIONAL_CALLING_CONVENTION = 'macro-positional'
  344. """The calling convention for well-known functions that are expanded as macros during codegen."""
  345. PRINT_MACRO_NAME = 'print'
  346. """The name of the 'print' macro."""
  347. class DirectFunctionCall(Value):
  348. """A value that is the result of a direct function call."""
  349. def __init__(
  350. self, target_name, argument_list,
  351. calling_convention=JIT_CALLING_CONVENTION,
  352. has_value=True,
  353. has_side_effects=True):
  354. Value.__init__(self)
  355. self.target_name = target_name
  356. assert all([isinstance(val, Definition) for _, val in argument_list])
  357. self.argument_list = argument_list
  358. self.calling_convention = calling_convention
  359. self.has_value_val = has_value
  360. self.has_side_effects_val = has_side_effects
  361. def has_side_effects(self):
  362. """Tells if this instruction has side-effects."""
  363. return self.has_side_effects_val
  364. def has_value(self):
  365. """Tells if this value produces a result that is not None."""
  366. return self.has_value_val
  367. def create(self, new_dependencies):
  368. """Creates an instruction of this type from the given set of dependencies."""
  369. return DirectFunctionCall(
  370. self.target_name,
  371. [(name, new_val)
  372. for new_val, (name, _) in zip(new_dependencies, self.argument_list)],
  373. self.calling_convention, self.has_value_val, self.has_side_effects_val)
  374. def get_dependencies(self):
  375. """Gets all definitions and instructions on which this instruction depends."""
  376. return [val for _, val in self.argument_list]
  377. def __str__(self):
  378. return 'direct-call %r %s(%s)' % (
  379. self.calling_convention,
  380. self.target_name,
  381. ', '.join(['%s=%s' % (key, val.ref_str()) for key, val in self.argument_list]))
  382. class AllocateRootNode(Value):
  383. """A value that produces a new root node. Typically used in function prologs."""
  384. def __init__(self):
  385. Value.__init__(self)
  386. def get_dependencies(self):
  387. """Gets all definitions and instructions on which this instruction depends."""
  388. return []
  389. def create(self, new_dependencies):
  390. """Creates an instruction of this type from the given set of dependencies."""
  391. assert len(new_dependencies) == 0
  392. return AllocateRootNode()
  393. def __str__(self):
  394. return 'alloc-root-node'
  395. class DeallocateRootNode(Value):
  396. """A value that deallocates a root node. Typically used in function epilogs."""
  397. def __init__(self, root_node):
  398. Value.__init__(self)
  399. assert isinstance(root_node, Definition)
  400. self.root_node = root_node
  401. def get_dependencies(self):
  402. """Gets all definitions and instructions on which this instruction depends."""
  403. return [self.root_node]
  404. def create(self, new_dependencies):
  405. """Creates an instruction of this type from the given set of dependencies."""
  406. return DeallocateRootNode(*new_dependencies)
  407. def has_value(self):
  408. """Tells if this value produces a result that is not None."""
  409. return False
  410. def has_side_effects(self):
  411. """Tells if this instruction has side-effects."""
  412. return True
  413. def __str__(self):
  414. return 'free-root-node %s' % self.root_node.ref_str()
  415. class DeclareLocal(Value):
  416. """A value that declares a local variable."""
  417. def __init__(self, variable, root_node):
  418. Value.__init__(self)
  419. self.variable = variable
  420. self.root_node = root_node
  421. def get_dependencies(self):
  422. """Gets all definitions and instructions on which this instruction depends."""
  423. return [self.root_node]
  424. def create(self, new_dependencies):
  425. """Creates an instruction of this type from the given set of dependencies."""
  426. root_node, = new_dependencies
  427. return DeclareLocal(self.variable, root_node)
  428. def has_value(self):
  429. """Tells if this value produces a result that is not None."""
  430. return False
  431. def has_side_effects(self):
  432. """Tells if this instruction has side-effects."""
  433. return True
  434. def __str__(self):
  435. return 'declare-local %s, %s' % (self.variable, self.root_node.ref_str())
  436. class DeclareGlobal(Value):
  437. """A value that declares a global variable."""
  438. def __init__(self, variable):
  439. Value.__init__(self)
  440. self.variable = variable
  441. def get_dependencies(self):
  442. """Gets all definitions and instructions on which this instruction depends."""
  443. return []
  444. def create(self, new_dependencies):
  445. """Creates an instruction of this type from the given set of dependencies."""
  446. return DeclareGlobal(self.variable)
  447. def has_value(self):
  448. """Tells if this value produces a result that is not None."""
  449. return False
  450. def has_side_effects(self):
  451. """Tells if this instruction has side-effects."""
  452. return True
  453. def __str__(self):
  454. return 'declare-global %s' % self.variable.name
  455. class CheckLocalExists(Value):
  456. """A value that checks if a local value has been defined (yet)."""
  457. def __init__(self, variable):
  458. Value.__init__(self)
  459. self.variable = variable
  460. def get_dependencies(self):
  461. """Gets all definitions and instructions on which this instruction depends."""
  462. return []
  463. def create(self, new_dependencies):
  464. """Creates an instruction of this type from the given set of dependencies."""
  465. return CheckLocalExists(self.variable)
  466. def __str__(self):
  467. return 'check-local-exists %s' % self.variable
  468. class ResolveLocal(Value):
  469. """A value that resolves a local as a pointer."""
  470. def __init__(self, variable):
  471. Value.__init__(self)
  472. self.variable = variable
  473. def get_dependencies(self):
  474. """Gets all definitions and instructions on which this instruction depends."""
  475. return []
  476. def create(self, new_dependencies):
  477. """Creates an instruction of this type from the given set of dependencies."""
  478. return ResolveLocal(self.variable)
  479. def __str__(self):
  480. return 'resolve-local %s' % self.variable
  481. class ResolveGlobal(Value):
  482. """A value that resolves a global as a pointer."""
  483. def __init__(self, variable):
  484. Value.__init__(self)
  485. self.variable = variable
  486. def get_dependencies(self):
  487. """Gets all definitions and instructions on which this instruction depends."""
  488. return []
  489. def create(self, new_dependencies):
  490. """Creates an instruction of this type from the given set of dependencies."""
  491. return ResolveGlobal(self.variable)
  492. def __str__(self):
  493. return 'resolve-global %s' % self.variable.name
  494. class LoadPointer(Value):
  495. """A value that loads the value assigned to a pointer."""
  496. def __init__(self, pointer):
  497. Value.__init__(self)
  498. self.pointer = pointer
  499. assert isinstance(pointer, Definition)
  500. def get_dependencies(self):
  501. """Gets all definitions and instructions on which this instruction depends."""
  502. return [self.pointer]
  503. def create(self, new_dependencies):
  504. """Creates an instruction of this type from the given set of dependencies."""
  505. return LoadPointer(*new_dependencies)
  506. def __str__(self):
  507. return 'load %s' % self.pointer.ref_str()
  508. class StoreAtPointer(Value):
  509. """A value that assigns a value to a pointer."""
  510. def __init__(self, pointer, value):
  511. Value.__init__(self)
  512. self.pointer = pointer
  513. assert isinstance(pointer, Definition)
  514. self.value = value
  515. assert isinstance(value, Definition)
  516. def get_dependencies(self):
  517. """Gets all definitions and instructions on which this instruction depends."""
  518. return [self.pointer, self.value]
  519. def create(self, new_dependencies):
  520. """Creates an instruction of this type from the given set of dependencies."""
  521. return StoreAtPointer(*new_dependencies)
  522. def has_value(self):
  523. """Tells if this value produces a result that is not None."""
  524. return False
  525. def has_side_effects(self):
  526. """Tells if this instruction has side-effects."""
  527. return True
  528. def __str__(self):
  529. return 'store %s, %s' % (self.pointer.ref_str(), self.value.ref_str())
  530. class Read(Value):
  531. """A value that reads the value stored in a node."""
  532. def __init__(self, node):
  533. Value.__init__(self)
  534. self.node = node
  535. assert isinstance(node, Definition)
  536. def get_dependencies(self):
  537. """Gets all definitions and instructions on which this instruction depends."""
  538. return [self.node]
  539. def create(self, new_dependencies):
  540. """Creates an instruction of this type from the given set of dependencies."""
  541. return Read(*new_dependencies)
  542. def __str__(self):
  543. return 'read %s' % (self.node.ref_str())
  544. class CreateNode(Value):
  545. """A value that creates a new node."""
  546. def __init__(self, value):
  547. Value.__init__(self)
  548. self.value = value
  549. assert isinstance(value, Definition)
  550. def get_dependencies(self):
  551. """Gets all definitions and instructions on which this instruction depends."""
  552. return [self.value]
  553. def create(self, new_dependencies):
  554. """Creates an instruction of this type from the given set of dependencies."""
  555. return CreateNode(*new_dependencies)
  556. def __str__(self):
  557. return 'create-node %s' % (self.value.ref_str())
  558. class Input(Value):
  559. """A value that pops a node from the input queue."""
  560. def get_dependencies(self):
  561. """Gets all definitions and instructions on which this instruction depends."""
  562. return []
  563. def create(self, new_dependencies):
  564. """Creates an instruction of this type from the given set of dependencies."""
  565. assert len(new_dependencies) == 0
  566. return Input()
  567. def has_side_effects(self):
  568. """Tells if this instruction has side-effects."""
  569. return True
  570. def __str__(self):
  571. return 'input'
  572. class Output(Value):
  573. """A value that pushes a node onto the output queue."""
  574. def __init__(self, value):
  575. Value.__init__(self)
  576. self.value = value
  577. assert isinstance(value, Definition)
  578. def get_dependencies(self):
  579. """Gets all definitions and instructions on which this instruction depends."""
  580. return [self.value]
  581. def create(self, new_dependencies):
  582. """Creates an instruction of this type from the given set of dependencies."""
  583. return Output(*new_dependencies)
  584. def has_value(self):
  585. """Tells if this value produces a result that is not None."""
  586. return False
  587. def has_side_effects(self):
  588. """Tells if this instruction has side-effects."""
  589. return True
  590. def __str__(self):
  591. return 'output %s' % self.value.ref_str()
  592. class Binary(Value):
  593. """A value that applies a binary operator to two other values."""
  594. def __init__(self, lhs, operator, rhs):
  595. Value.__init__(self)
  596. self.lhs = lhs
  597. assert isinstance(lhs, Definition)
  598. self.operator = operator
  599. self.rhs = rhs
  600. assert isinstance(rhs, Definition)
  601. def get_dependencies(self):
  602. """Gets all definitions and instructions on which this instruction depends."""
  603. return [self.lhs, self.rhs]
  604. def create(self, new_dependencies):
  605. """Creates an instruction of this type from the given set of dependencies."""
  606. lhs, rhs = new_dependencies
  607. return Binary(lhs, self.operator, rhs)
  608. def __str__(self):
  609. return 'binary %s, %r, %s' % (self.lhs.ref_str(), self.operator, self.rhs.ref_str())
  610. def create_jump(block, arguments=None):
  611. """Creates a jump to the given block with the given argument list."""
  612. return JumpFlow(Branch(block, arguments))
  613. def create_print(argument):
  614. """Creates a value that prints the specified argument."""
  615. return DirectFunctionCall(
  616. PRINT_MACRO_NAME, [('argument', argument)],
  617. calling_convention=MACRO_POSITIONAL_CALLING_CONVENTION,
  618. has_value=False)
  619. def get_def_value(def_or_value):
  620. """Returns the given value, or the underlying value of the given definition, whichever is
  621. appropriate."""
  622. if isinstance(def_or_value, Definition):
  623. return get_def_value(def_or_value.value)
  624. else:
  625. return def_or_value
  626. def apply_to_value(function, def_or_value):
  627. """Applies the given function to the specified value, or the underlying value of the
  628. given definition."""
  629. return function(get_def_value(def_or_value))
  630. def is_literal(value):
  631. """Tests if the given value is a literal."""
  632. return isinstance(value, Literal)
  633. def is_literal_def(def_or_value):
  634. """Tests if the given value is a literal or a definition with an underlying literal."""
  635. return apply_to_value(is_literal, def_or_value)
  636. def is_value_def(def_or_value, class_or_type_or_tuple=Value):
  637. """Tests if the given definition or value is a value of the given type."""
  638. return isinstance(get_def_value(def_or_value), class_or_type_or_tuple)
  639. def get_def_variable(def_or_value):
  640. """Gets the 'variable' attribute of the given value, or the underlying value of the given
  641. definition, whichever is appropriate."""
  642. return get_def_value(def_or_value).variable
  643. def get_literal_value(value):
  644. """Gets the value of the given literal value."""
  645. return value.literal
  646. def get_literal_def_value(def_or_value):
  647. """Gets the value of the given literal value or definition with an underlying literal."""
  648. return apply_to_value(get_literal_value, def_or_value)
  649. def get_all_predecessor_blocks(entry_point):
  650. """Creates a mapping of blocks to their direct predecessors for every block in the control-flow
  651. graph defined by the given entry point."""
  652. results = defaultdict(set)
  653. processed = set()
  654. def __find_predecessors_step(block):
  655. if block in processed:
  656. return
  657. processed.add(block)
  658. for branch in block.flow.branches():
  659. target_block = branch.block
  660. results[target_block].add(block)
  661. __find_predecessors_step(target_block)
  662. __find_predecessors_step(entry_point)
  663. return results
  664. def get_directly_reachable_blocks(block):
  665. """Gets the set of all blocks that can be reached by taking a single branch from the
  666. given block."""
  667. return [branch.block for branch in block.flow.branches()]
  668. def get_reachable_blocks(entry_point):
  669. """Constructs the set of all reachable vertices from the given block."""
  670. # This is a simple O(n^2) algorithm. Maybe a faster algorithm is more appropriate here.
  671. def __add_block_children(block, results):
  672. for child in get_directly_reachable_blocks(block):
  673. if child not in results:
  674. results.add(child)
  675. __add_block_children(child, results)
  676. return results
  677. return __add_block_children(entry_point, set())
  678. def get_all_reachable_blocks(entry_point):
  679. """Constructs the set of all reachable vertices, for every block that is
  680. reachable from the given entry point."""
  681. # This is a simple O(n^3) algorithm. Maybe a faster algorithm is more appropriate here.
  682. results = {}
  683. all_blocks = get_reachable_blocks(entry_point)
  684. results[entry_point] = all_blocks
  685. for block in all_blocks:
  686. if block not in results:
  687. results[block] = get_reachable_blocks(block)
  688. return results
  689. def get_all_blocks(entry_point):
  690. """Gets all basic blocks in the control-flow graph defined by the given entry point."""
  691. yield entry_point
  692. for block in get_reachable_blocks(entry_point):
  693. yield block
  694. def get_trivial_phi_value(parameter_def, values):
  695. """Tests if the given parameter definition is an alias for another definition.
  696. If so, then the other definition is returned; otherwise, None."""
  697. result = None
  698. for elem in values:
  699. if elem is not parameter_def:
  700. if result is None:
  701. result = elem
  702. else:
  703. return None
  704. return result