bytecode_to_cfg.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. """Converts bytecode IR to CFG IR."""
  2. import modelverse_jit.bytecode_ir as bytecode_ir
  3. import modelverse_jit.cfg_ir as cfg_ir
  4. import modelverse_jit.runtime as jit_runtime
  5. class AnalysisState(object):
  6. """State that is common to the bytecode->CFG transformation of a function."""
  7. def __init__(self):
  8. self.counter = cfg_ir.SharedCounter()
  9. self.analyzed_instructions = set()
  10. self.loop_instructions = {}
  11. self.entry_point = cfg_ir.BasicBlock(self.counter)
  12. self.current_block = self.entry_point
  13. self.root_node = None
  14. self.__write_prolog()
  15. def __write_prolog(self):
  16. # Write a prolog in CFG IR.
  17. # We want to create the following definition:
  18. #
  19. # !entry_point():
  20. # $jit_locals = alloc-root-node
  21. #
  22. # We also want to store '$jit_locals' in an attribute, so we can
  23. # use it to shield locals from the GC.
  24. self.root_node = self.current_block.append_definition(cfg_ir.AllocateRootNode())
  25. def analyze(self, instruction):
  26. """Analyzes the given instruction as a basic block."""
  27. if instruction in self.analyzed_instructions:
  28. raise jit_runtime.JitCompilationFailedException(
  29. 'Cannot jit non-tree instruction graph.')
  30. self.analyzed_instructions.add(instruction)
  31. # Find an analyzer.
  32. instruction_type = type(instruction)
  33. if instruction_type in self.instruction_analyzers:
  34. # Analyze the instruction.
  35. result = self.instruction_analyzers[instruction_type](self, instruction)
  36. # Check if the instruction has a 'next' instruction. If so, analyze it!
  37. if instruction.next_instruction is not None:
  38. next_result = self.analyze(instruction.next_instruction)
  39. if next_result.value.has_value() or (not result.value.has_value()):
  40. result = next_result
  41. return result
  42. else:
  43. raise jit_runtime.JitCompilationFailedException(
  44. "Unknown instruction type: '%s'" % type(instruction))
  45. def emit_select(self, create_condition, create_if_body, create_else_body):
  46. """Emits a 'select' instruction."""
  47. # Create blocks that look like this:
  48. #
  49. # !current_block(...):
  50. # ...
  51. # $cond = <condition>
  52. # select $cond, !if_block(), !else_block()
  53. #
  54. # !if_block():
  55. # $if_result = <if-body>
  56. # jump !phi_block($if_result)
  57. #
  58. # !else_block():
  59. # $else_result = <else-body>
  60. # jump !phi_block($else_result)
  61. #
  62. # !phi_block($result = block-parameter):
  63. # ...
  64. #
  65. if_block = cfg_ir.BasicBlock(self.counter)
  66. else_block = cfg_ir.BasicBlock(self.counter)
  67. phi_block = cfg_ir.BasicBlock(self.counter)
  68. param_def = phi_block.append_parameter(cfg_ir.BlockParameter())
  69. condition = create_condition()
  70. self.current_block.flow = cfg_ir.SelectFlow(
  71. condition, cfg_ir.Branch(if_block), cfg_ir.Branch(else_block))
  72. self.current_block = if_block
  73. if_result = create_if_body()
  74. self.current_block.flow = cfg_ir.create_jump(phi_block, [if_result])
  75. self.current_block = else_block
  76. else_result = create_else_body()
  77. self.current_block.flow = cfg_ir.create_jump(phi_block, [else_result])
  78. self.current_block = phi_block
  79. return param_def
  80. def analyze_if(self, instruction):
  81. """Analyzes an 'if' instruction."""
  82. return self.emit_select(
  83. lambda: self.analyze(instruction.condition),
  84. lambda: self.analyze(instruction.if_clause),
  85. lambda:
  86. self.current_block.append_definition(cfg_ir.Literal(None))
  87. if instruction.else_clause is None
  88. else self.analyze(instruction.else_clause))
  89. def analyze_while(self, instruction):
  90. """Analyzes a 'while' instruction."""
  91. # Create blocks that look like this:
  92. #
  93. # !current_block(...):
  94. # ...
  95. # jump !loop_condition()
  96. #
  97. # !loop_condition():
  98. # $condition = <condition>
  99. # select $condition, !loop_body(), !loop_exit()
  100. #
  101. # !loop_body():
  102. # $result = <body>
  103. # jump !loop_condition()
  104. #
  105. # !loop_exit():
  106. # $nothing = literal None
  107. # ...
  108. loop_condition_block = cfg_ir.BasicBlock(self.counter)
  109. loop_body_block = cfg_ir.BasicBlock(self.counter)
  110. loop_exit_block = cfg_ir.BasicBlock(self.counter)
  111. self.loop_instructions[instruction] = (loop_condition_block, loop_exit_block)
  112. self.current_block.flow = cfg_ir.create_jump(loop_condition_block)
  113. self.current_block = loop_condition_block
  114. condition_value = self.analyze(instruction.condition)
  115. self.current_block.flow = cfg_ir.SelectFlow(
  116. condition_value, cfg_ir.Branch(loop_body_block), cfg_ir.Branch(loop_exit_block))
  117. self.current_block = loop_body_block
  118. self.analyze(instruction.body)
  119. self.current_block.flow = cfg_ir.create_jump(loop_condition_block)
  120. self.current_block = loop_exit_block
  121. return loop_exit_block.append_definition(cfg_ir.Literal(None))
  122. def analyze_return(self, instruction):
  123. """Analyzes a 'return' instruction."""
  124. if instruction.value is None:
  125. return_value = self.current_block.append_definition(cfg_ir.Literal(None))
  126. else:
  127. return_value = self.analyze(instruction.value)
  128. # Don't forget to deallocate the root node.
  129. self.current_block.append_definition(cfg_ir.DeallocateRootNode(self.root_node))
  130. self.current_block.flow = cfg_ir.ReturnFlow(return_value)
  131. self.current_block = cfg_ir.BasicBlock(self.counter)
  132. return self.current_block.append_definition(cfg_ir.Literal(None))
  133. def analyze_constant(self, instruction):
  134. """Analyzes a 'constant' instruction."""
  135. return self.current_block.append_definition(cfg_ir.Literal(instruction.constant_id))
  136. def analyze_resolve(self, instruction):
  137. """Analyzes a 'resolve' instruction."""
  138. def __resolve_global_carefully():
  139. # We might be resolving a global that does not exist. In that case, we
  140. # need to throw. We want to create the following blocks:
  141. #
  142. # !current_block(...):
  143. # ...
  144. # $resolved_global = resolve-global global
  145. # $nothing = literal None
  146. # $condition = binary $resolved_global, 'is', $nothing
  147. # select $condition, !no_global_block(), !global_exists_block()
  148. #
  149. # !no_global_block():
  150. # $message = literal <GLOBAL_NOT_FOUND_MESSAGE_FORMAT % instruction.variable.name>
  151. # $exception = direct-call "simple-positional" Exception(message=$message)
  152. # throw $exception
  153. #
  154. # !global_exists_block():
  155. # ...
  156. #
  157. no_global_block = cfg_ir.BasicBlock(self.counter)
  158. global_exists_block = cfg_ir.BasicBlock(self.counter)
  159. resolved_global = self.current_block.append_definition(
  160. cfg_ir.ResolveGlobal(instruction.variable))
  161. nothing = self.current_block.append_definition(cfg_ir.Literal(None))
  162. condition = self.current_block.append_definition(
  163. cfg_ir.Binary(resolved_global, 'is', nothing))
  164. self.current_block.flow = cfg_ir.SelectFlow(
  165. condition, cfg_ir.Branch(no_global_block), cfg_ir.Branch(global_exists_block))
  166. message = no_global_block.append_definition(
  167. cfg_ir.Literal(
  168. jit_runtime.GLOBAL_NOT_FOUND_MESSAGE_FORMAT % instruction.variable.name))
  169. exception = no_global_block.append_definition(
  170. cfg_ir.DirectFunctionCall(
  171. 'Exception',
  172. [('message', message)],
  173. cfg_ir.SIMPLE_POSITIONAL_CALLING_CONVENTION))
  174. no_global_block.flow = cfg_ir.ThrowFlow(exception)
  175. self.current_block = global_exists_block
  176. return resolved_global
  177. return self.emit_select(
  178. lambda:
  179. self.current_block.append_definition(
  180. cfg_ir.CheckLocalExists(instruction.variable)),
  181. lambda:
  182. self.current_block.append_definition(
  183. cfg_ir.ResolveLocal(instruction.variable)),
  184. __resolve_global_carefully)
  185. def analyze_declare(self, instruction):
  186. """Analyzes a 'declare' instruction."""
  187. return self.current_block.append_definition(
  188. cfg_ir.DeclareLocal(instruction.variable, self.root_node))
  189. def analyze_global(self, instruction):
  190. """Analyzes a 'global' instruction."""
  191. resolved_global = self.current_block.append_definition(
  192. cfg_ir.ResolveGlobal(instruction.variable))
  193. nothing = self.current_block.append_definition(cfg_ir.Literal(None))
  194. return self.emit_select(
  195. lambda:
  196. self.current_block.append_definition(
  197. cfg_ir.Binary(resolved_global, 'is', nothing)),
  198. lambda:
  199. self.current_block.append_definition(
  200. cfg_ir.DeclareGlobal(instruction.variable)),
  201. lambda: resolved_global)
  202. def analyze_assign(self, instruction):
  203. """Analyzes an 'assign' instruction."""
  204. pointer_result = self.analyze(instruction.pointer)
  205. value_result = self.analyze(instruction.value)
  206. return self.current_block.append_definition(
  207. cfg_ir.StoreAtPointer(pointer_result, value_result))
  208. def analyze_access(self, instruction):
  209. """Analyzes an 'access' instruction."""
  210. pointer_result = self.analyze(instruction.pointer)
  211. return self.current_block.append_definition(cfg_ir.LoadPointer(pointer_result))
  212. def analyze_output(self, instruction):
  213. """Analyzes an 'output' instruction."""
  214. value_result = self.analyze(instruction.value)
  215. return self.current_block.append_definition(cfg_ir.Output(value_result))
  216. def analyze_input(self, _):
  217. """Analyzes an 'input' instruction."""
  218. return self.current_block.append_definition(cfg_ir.Input())
  219. def analyze_break(self, instruction):
  220. """Analyzes a 'break' instruction."""
  221. if instruction.loop not in self.loop_instructions:
  222. raise jit_runtime.JitCompilationFailedException(
  223. "'break' instruction targets a 'while' loop that has not been defined yet.")
  224. _, exit_block = self.loop_instructions[instruction.loop]
  225. self.current_block.flow = cfg_ir.create_jump(exit_block)
  226. self.current_block = cfg_ir.BasicBlock(self.counter)
  227. return self.current_block.append_definition(cfg_ir.Literal(None))
  228. def analyze_continue(self, instruction):
  229. """Analyzes a 'continue' instruction."""
  230. if instruction.loop not in self.loop_instructions:
  231. raise jit_runtime.JitCompilationFailedException(
  232. "'continue' instruction targets a 'while' loop that has not been defined yet.")
  233. cond_block, _ = self.loop_instructions[instruction.loop]
  234. self.current_block.flow = cfg_ir.create_jump(cond_block)
  235. self.current_block = cfg_ir.BasicBlock(self.counter)
  236. return self.current_block.append_definition(cfg_ir.Literal(None))
  237. def analyze_call(self, instruction):
  238. """Analyzes the given 'call' instruction."""
  239. target = self.analyze(instruction.target)
  240. arg_list = []
  241. for key, arg_instruction in instruction.argument_list:
  242. arg_list.append((key, self.analyze(arg_instruction)))
  243. return self.current_block.append_definition(cfg_ir.IndirectFunctionCall(target, arg_list))
  244. instruction_analyzers = {
  245. bytecode_ir.SelectInstruction : analyze_if,
  246. bytecode_ir.WhileInstruction : analyze_while,
  247. bytecode_ir.ReturnInstruction : analyze_return,
  248. bytecode_ir.ConstantInstruction : analyze_constant,
  249. bytecode_ir.ResolveInstruction : analyze_resolve,
  250. bytecode_ir.DeclareInstruction : analyze_declare,
  251. bytecode_ir.GlobalInstruction : analyze_global,
  252. bytecode_ir.AssignInstruction : analyze_assign,
  253. bytecode_ir.AccessInstruction : analyze_access,
  254. bytecode_ir.OutputInstruction : analyze_output,
  255. bytecode_ir.InputInstruction : analyze_input,
  256. bytecode_ir.CallInstruction : analyze_call,
  257. bytecode_ir.BreakInstruction : analyze_break,
  258. bytecode_ir.ContinueInstruction : analyze_continue
  259. }