bytecode_to_tree.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  1. """Naively converts bytecode IR to tree IR."""
  2. import modelverse_jit.bytecode_ir as bytecode_ir
  3. import modelverse_jit.tree_ir as tree_ir
  4. import modelverse_jit.runtime as jit_runtime
  5. import modelverse_kernel.primitives as primitive_functions
  6. def get_parameter_names(compiled_function):
  7. """Gets the given compiled function's parameter names."""
  8. if hasattr(compiled_function, '__code__'):
  9. return compiled_function.__code__.co_varnames[
  10. :compiled_function.__code__.co_argcount]
  11. elif hasattr(compiled_function, '__init__'):
  12. return get_parameter_names(compiled_function.__init__)[1:]
  13. else:
  14. raise ValueError("'compiled_function' must be a function or a type.")
  15. def apply_intrinsic(intrinsic_function, named_args):
  16. """Applies the given intrinsic to the given sequence of named arguments."""
  17. param_names = get_parameter_names(intrinsic_function)
  18. if tuple(param_names) == tuple([n for n, _ in named_args]):
  19. # Perfect match. Yay!
  20. return intrinsic_function(**dict(named_args))
  21. else:
  22. # We'll have to store the arguments into locals to preserve
  23. # the order of evaluation.
  24. stored_args = [(name, tree_ir.StoreLocalInstruction(None, arg)) for name, arg in named_args]
  25. arg_value_dict = dict([(name, arg.create_load()) for name, arg in stored_args])
  26. store_instructions = [instruction for _, instruction in stored_args]
  27. return tree_ir.CompoundInstruction(
  28. tree_ir.create_block(*store_instructions),
  29. intrinsic_function(**arg_value_dict))
  30. def retrieve_task_root():
  31. """Creates an instruction that stores the task_root variable in a local."""
  32. return tree_ir.StoreLocalInstruction(
  33. 'task_root',
  34. tree_ir.LoadIndexInstruction(
  35. tree_ir.LoadLocalInstruction(jit_runtime.KWARGS_PARAMETER_NAME),
  36. tree_ir.LiteralInstruction('task_root')))
  37. def load_kernel():
  38. """Creates an instruction that loads the Modelverse kernel."""
  39. return tree_ir.LoadIndexInstruction(
  40. tree_ir.LoadLocalInstruction(jit_runtime.KWARGS_PARAMETER_NAME),
  41. tree_ir.LiteralInstruction('mvk'))
  42. def create_access(pointer):
  43. """Creates a tree that loads the given pointer's value."""
  44. # Accessing a variable is pretty easy. It really just boils
  45. # down to reading the value corresponding to the 'value' key
  46. # of the variable.
  47. #
  48. # value, = yield [("RD", [returnvalue, "value"])]
  49. #
  50. return tree_ir.ReadDictionaryValueInstruction(
  51. pointer,
  52. tree_ir.LiteralInstruction('value'))
  53. def create_assign(pointer, value):
  54. """Creates a tree that assigns the given value to the given pointer."""
  55. # Assignments work like this:
  56. #
  57. # value_link = yield [("RDE", [variable, "value"])]
  58. # _, _ = yield [("CD", [variable, "value", value]),
  59. # ("DE", [value_link])]
  60. #
  61. variable = tree_ir.StoreLocalInstruction(None, pointer)
  62. value = tree_ir.StoreLocalInstruction(None, value)
  63. value_link = tree_ir.StoreLocalInstruction(
  64. 'value_link',
  65. tree_ir.ReadDictionaryEdgeInstruction(
  66. variable.create_load(),
  67. tree_ir.LiteralInstruction('value')))
  68. return tree_ir.create_block(
  69. variable,
  70. value,
  71. value_link,
  72. tree_ir.CreateDictionaryEdgeInstruction(
  73. variable.create_load(),
  74. tree_ir.LiteralInstruction('value'),
  75. value.create_load()),
  76. tree_ir.DeleteEdgeInstruction(
  77. value_link.create_load()))
  78. def create_input(use_input_function=False):
  79. """Creates an instruction that pops a value from the input queue."""
  80. # Possible alternative to the explicit syntax tree: just call the jit_runtime.__get_input
  81. # function.
  82. if use_input_function:
  83. return tree_ir.create_jit_call(
  84. tree_ir.LoadGlobalInstruction(jit_runtime.GET_INPUT_FUNCTION_NAME),
  85. [],
  86. tree_ir.LoadLocalInstruction(jit_runtime.KWARGS_PARAMETER_NAME))
  87. # The plan is to generate this tree:
  88. #
  89. # value = None
  90. # while True:
  91. # _input = yield [("RD", [task_root, "input"])]
  92. # value = yield [("RD", [_input, "value"])]
  93. #
  94. # if value is None:
  95. # kwargs['mvk'].success = False # to avoid blocking
  96. # yield None # nop/interrupt
  97. # else:
  98. # break
  99. #
  100. # _next = yield [("RD", [_input, "next"])]
  101. # yield [("CD", [task_root, "input", _next])]
  102. # yield [("CE", [jit_locals, value])]
  103. # yield [("DN", [_input])]
  104. task_root = retrieve_task_root()
  105. _input = tree_ir.StoreLocalInstruction(
  106. None,
  107. tree_ir.ReadDictionaryValueInstruction(
  108. task_root.create_load(),
  109. tree_ir.LiteralInstruction('input')))
  110. value = tree_ir.StoreLocalInstruction(
  111. None,
  112. tree_ir.ReadDictionaryValueInstruction(
  113. _input.create_load(),
  114. tree_ir.LiteralInstruction('value')))
  115. raise primitive_functions.PrimitiveFinished(
  116. tree_ir.CompoundInstruction(
  117. tree_ir.create_block(
  118. task_root,
  119. value.create_store(tree_ir.LiteralInstruction(None)),
  120. tree_ir.LoopInstruction(
  121. tree_ir.create_block(
  122. _input,
  123. value,
  124. tree_ir.SelectInstruction(
  125. tree_ir.BinaryInstruction(
  126. value.create_load(),
  127. 'is',
  128. tree_ir.LiteralInstruction(None)),
  129. tree_ir.create_block(
  130. tree_ir.StoreMemberInstruction(
  131. load_kernel(),
  132. 'success',
  133. tree_ir.LiteralInstruction(False)),
  134. tree_ir.NopInstruction()),
  135. tree_ir.BreakInstruction()))),
  136. tree_ir.CreateDictionaryEdgeInstruction(
  137. task_root.create_load(),
  138. tree_ir.LiteralInstruction('input'),
  139. tree_ir.ReadDictionaryValueInstruction(
  140. _input.create_load(),
  141. tree_ir.LiteralInstruction('next'))),
  142. tree_ir.CreateEdgeInstruction(
  143. tree_ir.LoadLocalInstruction(jit_runtime.LOCALS_NODE_NAME),
  144. value.create_load()),
  145. tree_ir.DeleteNodeInstruction(_input.create_load())),
  146. value.create_load()))
  147. def create_output(output_value):
  148. """Creates an output instruction that outputs the given value."""
  149. # The plan is to basically generate this tree:
  150. #
  151. # value = <some tree>
  152. # last_output, last_output_link, new_last_output = \
  153. # yield [("RD", [task_root, "last_output"]),
  154. # ("RDE", [task_root, "last_output"]),
  155. # ("CN", []),
  156. # ]
  157. # _, _, _, _ = \
  158. # yield [("CD", [last_output, "value", value]),
  159. # ("CD", [last_output, "next", new_last_output]),
  160. # ("CD", [task_root, "last_output", new_last_output]),
  161. # ("DE", [last_output_link])
  162. # ]
  163. # yield None
  164. value_local = tree_ir.StoreLocalInstruction('value', output_value)
  165. store_task_root = retrieve_task_root()
  166. last_output = tree_ir.StoreLocalInstruction(
  167. 'last_output',
  168. tree_ir.ReadDictionaryValueInstruction(
  169. store_task_root.create_load(),
  170. tree_ir.LiteralInstruction('last_output')))
  171. last_output_link = tree_ir.StoreLocalInstruction(
  172. 'last_output_link',
  173. tree_ir.ReadDictionaryEdgeInstruction(
  174. store_task_root.create_load(),
  175. tree_ir.LiteralInstruction('last_output')))
  176. new_last_output = tree_ir.StoreLocalInstruction(
  177. 'new_last_output',
  178. tree_ir.CreateNodeInstruction())
  179. return tree_ir.create_block(
  180. value_local,
  181. store_task_root,
  182. last_output,
  183. last_output_link,
  184. new_last_output,
  185. tree_ir.CreateDictionaryEdgeInstruction(
  186. last_output.create_load(),
  187. tree_ir.LiteralInstruction('value'),
  188. value_local.create_load()),
  189. tree_ir.CreateDictionaryEdgeInstruction(
  190. last_output.create_load(),
  191. tree_ir.LiteralInstruction('next'),
  192. new_last_output.create_load()),
  193. tree_ir.CreateDictionaryEdgeInstruction(
  194. store_task_root.create_load(),
  195. tree_ir.LiteralInstruction('last_output'),
  196. new_last_output.create_load()),
  197. tree_ir.DeleteEdgeInstruction(last_output_link.create_load()),
  198. tree_ir.NopInstruction())
  199. class LocalNameMap(object):
  200. """A map that converts local variable nodes to identifiers."""
  201. def __init__(self, local_mapping=None):
  202. if local_mapping is None:
  203. local_mapping = {}
  204. self.local_mapping = local_mapping
  205. def get_local_name(self, local_variable_id):
  206. """Gets the name for the local variable node with the given id."""
  207. if local_variable_id not in self.local_mapping:
  208. self.local_mapping[local_variable_id] = 'local%d' % local_variable_id
  209. return self.local_mapping[local_variable_id]
  210. class AnalysisState(object):
  211. """The state of a bytecode analysis call graph."""
  212. def __init__(self, jit, body_id, task_root, local_mapping, max_instructions=None):
  213. self.analyzed_instructions = set()
  214. self.function_vars = set()
  215. self.local_vars = set()
  216. self.body_id = body_id
  217. self.max_instructions = max_instructions
  218. self.task_root = task_root
  219. self.jit = jit
  220. self.local_name_map = LocalNameMap(local_mapping)
  221. self.function_name = jit.jitted_entry_points[body_id]
  222. self.enclosing_loop_instruction = None
  223. def register_local_var(self, local_id):
  224. """Registers the given variable node id as a local."""
  225. if local_id in self.function_vars:
  226. raise jit_runtime.JitCompilationFailedException(
  227. "Local is used as target of function call.")
  228. self.local_vars.add(local_id)
  229. def register_function_var(self, local_id):
  230. """Registers the given variable node id as a function."""
  231. if local_id in self.local_vars:
  232. raise jit_runtime.JitCompilationFailedException(
  233. "Local is used as target of function call.")
  234. self.function_vars.add(local_id)
  235. def analyze(self, instruction):
  236. """Tries to build an intermediate representation from the instruction with the
  237. given id."""
  238. # Check the analyzed_instructions set for instruction_id to avoid
  239. # infinite loops.
  240. if instruction in self.analyzed_instructions:
  241. raise jit_runtime.JitCompilationFailedException(
  242. 'Cannot jit non-tree instruction graph.')
  243. elif (self.max_instructions is not None and
  244. len(self.analyzed_instructions) > self.max_instructions):
  245. raise jit_runtime.JitCompilationFailedException(
  246. 'Maximum number of instructions exceeded.')
  247. self.analyzed_instructions.add(instruction)
  248. instruction_type = type(instruction)
  249. if instruction_type in self.instruction_analyzers:
  250. # Analyze the instruction itself.
  251. outer_result, = yield [
  252. ("CALL_ARGS", [self.instruction_analyzers[instruction_type], (self, instruction)])]
  253. if self.jit.tracing_enabled and instruction.debug_information is not None:
  254. outer_result = tree_ir.with_debug_info_trace(
  255. outer_result, instruction.debug_information, self.function_name)
  256. # Check if the instruction has a 'next' instruction.
  257. if instruction.next_instruction is None:
  258. raise primitive_functions.PrimitiveFinished(outer_result)
  259. else:
  260. next_result, = yield [
  261. ("CALL_ARGS", [self.analyze, (instruction.next_instruction,)])]
  262. raise primitive_functions.PrimitiveFinished(
  263. tree_ir.CompoundInstruction(
  264. outer_result,
  265. next_result))
  266. else:
  267. raise jit_runtime.JitCompilationFailedException(
  268. "Unknown instruction type: '%s'" % type(instruction))
  269. def analyze_all(self, instruction_ids):
  270. """Tries to compile a list of IR trees from the given list of instruction ids."""
  271. results = []
  272. for inst in instruction_ids:
  273. analyzed_inst, = yield [("CALL_ARGS", [self.analyze, (inst,)])]
  274. results.append(analyzed_inst)
  275. raise primitive_functions.PrimitiveFinished(results)
  276. def analyze_return(self, instruction):
  277. """Tries to analyze the given 'return' instruction."""
  278. def create_return(return_value):
  279. return tree_ir.ReturnInstruction(
  280. tree_ir.CompoundInstruction(
  281. return_value,
  282. tree_ir.DeleteEdgeInstruction(
  283. tree_ir.LoadLocalInstruction(jit_runtime.LOCALS_EDGE_NAME))))
  284. if instruction.value is None:
  285. raise primitive_functions.PrimitiveFinished(
  286. create_return(
  287. tree_ir.EmptyInstruction()))
  288. else:
  289. retval, = yield [("CALL_ARGS", [self.analyze, (instruction.value,)])]
  290. raise primitive_functions.PrimitiveFinished(
  291. create_return(retval))
  292. def analyze_if(self, instruction):
  293. """Tries to analyze the given 'if' instruction."""
  294. if instruction.else_clause is None:
  295. (cond_r, true_r), = yield [
  296. ("CALL_ARGS",
  297. [self.analyze_all,
  298. ([instruction.condition, instruction.if_clause],)])]
  299. false_r = tree_ir.EmptyInstruction()
  300. else:
  301. (cond_r, true_r, false_r), = yield [
  302. ("CALL_ARGS",
  303. [self.analyze_all,
  304. ([instruction.condition, instruction.if_clause, instruction.else_clause],)])]
  305. raise primitive_functions.PrimitiveFinished(
  306. tree_ir.SelectInstruction(
  307. tree_ir.ReadValueInstruction(cond_r),
  308. true_r,
  309. false_r))
  310. def analyze_while(self, instruction):
  311. """Tries to analyze the given 'while' instruction."""
  312. # Analyze the condition.
  313. cond_r, = yield [("CALL_ARGS", [self.analyze, (instruction.condition,)])]
  314. # Store the old enclosing loop on the stack, and make this loop the
  315. # new enclosing loop.
  316. old_loop_instruction = self.enclosing_loop_instruction
  317. self.enclosing_loop_instruction = instruction
  318. body_r, = yield [("CALL_ARGS", [self.analyze, (instruction.body,)])]
  319. # Restore hte old enclosing loop.
  320. self.enclosing_loop_instruction = old_loop_instruction
  321. if self.jit.nop_insertion_enabled:
  322. create_loop_body = lambda check, body: tree_ir.create_block(
  323. check,
  324. body_r,
  325. tree_ir.NopInstruction())
  326. else:
  327. create_loop_body = tree_ir.CompoundInstruction
  328. raise primitive_functions.PrimitiveFinished(
  329. tree_ir.LoopInstruction(
  330. create_loop_body(
  331. tree_ir.SelectInstruction(
  332. tree_ir.ReadValueInstruction(cond_r),
  333. tree_ir.EmptyInstruction(),
  334. tree_ir.BreakInstruction()),
  335. body_r)))
  336. def analyze_constant(self, instruction):
  337. """Tries to analyze the given 'constant' (literal) instruction."""
  338. raise primitive_functions.PrimitiveFinished(
  339. tree_ir.LiteralInstruction(instruction.constant_id))
  340. def analyze_output(self, instruction):
  341. """Tries to analyze the given 'output' instruction."""
  342. value_val, = yield [("CALL_ARGS", [self.analyze, (instruction.value,)])]
  343. raise primitive_functions.PrimitiveFinished(create_output(value_val))
  344. def analyze_input(self, _):
  345. """Tries to analyze the given 'input' instruction."""
  346. raise primitive_functions.PrimitiveFinished(create_input(self.jit.input_function_enabled))
  347. def analyze_resolve(self, instruction):
  348. """Tries to analyze the given 'resolve' instruction."""
  349. # To resolve a variable, we'll do something along the
  350. # lines of:
  351. #
  352. # if 'local_var' in locals():
  353. # tmp = local_var
  354. # else:
  355. # _globals, = yield [("RD", [task_root, "globals"])]
  356. # global_var, = yield [("RD", [_globals, var_name])]
  357. #
  358. # if global_var is None:
  359. # raise Exception("Not found as global: %s" % (var_name))
  360. #
  361. # tmp = global_var
  362. name = self.local_name_map.get_local_name(instruction.variable.node_id)
  363. if instruction.variable.name is None:
  364. raise primitive_functions.PrimitiveFinished(
  365. tree_ir.LoadLocalInstruction(name))
  366. task_root = retrieve_task_root()
  367. global_var = tree_ir.StoreLocalInstruction(
  368. 'global_var',
  369. tree_ir.ReadDictionaryValueInstruction(
  370. tree_ir.ReadDictionaryValueInstruction(
  371. task_root.create_load(),
  372. tree_ir.LiteralInstruction('globals')),
  373. tree_ir.LiteralInstruction(instruction.variable.name)))
  374. err_block = tree_ir.SelectInstruction(
  375. tree_ir.BinaryInstruction(
  376. global_var.create_load(),
  377. 'is',
  378. tree_ir.LiteralInstruction(None)),
  379. tree_ir.RaiseInstruction(
  380. tree_ir.CallInstruction(
  381. tree_ir.LoadGlobalInstruction('Exception'),
  382. [tree_ir.LiteralInstruction(
  383. "Not found as global: %s" % instruction.variable.name)
  384. ])),
  385. tree_ir.EmptyInstruction())
  386. raise primitive_functions.PrimitiveFinished(
  387. tree_ir.SelectInstruction(
  388. tree_ir.LocalExistsInstruction(name),
  389. tree_ir.LoadLocalInstruction(name),
  390. tree_ir.CompoundInstruction(
  391. tree_ir.create_block(
  392. task_root,
  393. global_var,
  394. err_block),
  395. global_var.create_load())))
  396. def analyze_declare(self, instruction):
  397. """Tries to analyze the given 'declare' function."""
  398. self.register_local_var(instruction.variable.node_id)
  399. name = self.local_name_map.get_local_name(instruction.variable.node_id)
  400. # The following logic declares a local:
  401. #
  402. # if 'local_name' not in locals():
  403. # local_name, = yield [("CN", [])]
  404. # yield [("CE", [LOCALS_NODE_NAME, local_name])]
  405. raise primitive_functions.PrimitiveFinished(
  406. tree_ir.SelectInstruction(
  407. tree_ir.LocalExistsInstruction(name),
  408. tree_ir.EmptyInstruction(),
  409. tree_ir.create_new_local_node(
  410. name,
  411. tree_ir.LoadLocalInstruction(jit_runtime.LOCALS_NODE_NAME))))
  412. def analyze_global(self, instruction):
  413. """Tries to analyze the given 'global' (declaration) instruction."""
  414. # To declare a variable, we'll do something along the
  415. # lines of:
  416. #
  417. # _globals, = yield [("RD", [task_root, "globals"])]
  418. # global_var = yield [("RD", [_globals, var_name])]
  419. #
  420. # if global_var is None:
  421. # global_var, = yield [("CN", [])]
  422. # yield [("CD", [_globals, var_name, global_var])]
  423. #
  424. # tmp = global_var
  425. task_root = retrieve_task_root()
  426. _globals = tree_ir.StoreLocalInstruction(
  427. '_globals',
  428. tree_ir.ReadDictionaryValueInstruction(
  429. task_root.create_load(),
  430. tree_ir.LiteralInstruction('globals')))
  431. global_var = tree_ir.StoreLocalInstruction(
  432. 'global_var',
  433. tree_ir.ReadDictionaryValueInstruction(
  434. _globals.create_load(),
  435. tree_ir.LiteralInstruction(instruction.variable.name)))
  436. raise primitive_functions.PrimitiveFinished(
  437. tree_ir.CompoundInstruction(
  438. tree_ir.create_block(
  439. task_root,
  440. _globals,
  441. global_var,
  442. tree_ir.SelectInstruction(
  443. tree_ir.BinaryInstruction(
  444. global_var.create_load(),
  445. 'is',
  446. tree_ir.LiteralInstruction(None)),
  447. tree_ir.create_block(
  448. global_var.create_store(
  449. tree_ir.CreateNodeInstruction()),
  450. tree_ir.CreateDictionaryEdgeInstruction(
  451. _globals.create_load(),
  452. tree_ir.LiteralInstruction(
  453. instruction.variable.name),
  454. global_var.create_load())),
  455. tree_ir.EmptyInstruction())),
  456. global_var.create_load()))
  457. def analyze_assign(self, instruction):
  458. """Tries to analyze the given 'assign' instruction."""
  459. (var_r, value_r), = yield [
  460. ("CALL_ARGS", [self.analyze_all, ([instruction.pointer, instruction.value],)])]
  461. raise primitive_functions.PrimitiveFinished(create_assign(var_r, value_r))
  462. def analyze_access(self, instruction):
  463. """Tries to analyze the given 'access' instruction."""
  464. var_r, = yield [("CALL_ARGS", [self.analyze, (instruction.pointer,)])]
  465. raise primitive_functions.PrimitiveFinished(create_access(var_r))
  466. def analyze_direct_call(self, callee_id, callee_name, argument_list):
  467. """Tries to analyze a direct 'call' instruction."""
  468. body_id, = yield [("RD", [callee_id, jit_runtime.FUNCTION_BODY_KEY])]
  469. # Make this function dependent on the callee.
  470. if body_id in self.jit.compilation_dependencies:
  471. self.jit.compilation_dependencies[body_id].add(self.body_id)
  472. # Figure out if the function might be an intrinsic.
  473. intrinsic = self.jit.get_intrinsic(callee_name)
  474. if intrinsic is None:
  475. if callee_name is not None:
  476. self.jit.register_global(body_id, callee_name)
  477. compiled_func = self.jit.lookup_compiled_function(callee_name)
  478. else:
  479. compiled_func = None
  480. if compiled_func is None:
  481. # Compile the callee.
  482. yield [
  483. ("CALL_ARGS", [self.jit.jit_compile, (self.task_root, body_id, callee_name)])]
  484. # Get the callee's name.
  485. compiled_func_name = self.jit.get_compiled_name(body_id)
  486. # This handles the corner case where a constant node is called, like
  487. # 'call(constant(9), ...)'. In this case, `callee_name` is `None`
  488. # because 'constant(9)' doesn't give us a name. However, we can look up
  489. # the name of the function at a specific node. If that turns out to be
  490. # an intrinsic, then we still want to pick the intrinsic over a call.
  491. intrinsic = self.jit.get_intrinsic(compiled_func_name)
  492. # Analyze the argument dictionary.
  493. named_args, = yield [("CALL_ARGS", [self.analyze_arguments, (argument_list,)])]
  494. if intrinsic is not None:
  495. raise primitive_functions.PrimitiveFinished(
  496. apply_intrinsic(intrinsic, named_args))
  497. else:
  498. raise primitive_functions.PrimitiveFinished(
  499. tree_ir.create_jit_call(
  500. tree_ir.LoadGlobalInstruction(compiled_func_name),
  501. named_args,
  502. tree_ir.LoadLocalInstruction(jit_runtime.KWARGS_PARAMETER_NAME)))
  503. def analyze_arguments(self, argument_list):
  504. """Analyzes the given parameter-to-value mapping."""
  505. named_args = []
  506. for param_name, arg in argument_list:
  507. param_val, = yield [("CALL_ARGS", [self.analyze, (arg,)])]
  508. named_args.append((param_name, param_val))
  509. raise primitive_functions.PrimitiveFinished(named_args)
  510. def analyze_indirect_call(self, target, argument_list):
  511. """Analyzes a call to an unknown function."""
  512. # First off, let's analyze the callee and the argument list.
  513. func_val, = yield [("CALL_ARGS", [self.analyze, (target,)])]
  514. named_args, = yield [("CALL_ARGS", [self.analyze_arguments, (argument_list,)])]
  515. # Call the __call_function function to run the interpreter, like so:
  516. #
  517. # __call_function(function_id, { first_param_name : first_param_val, ... }, **kwargs)
  518. #
  519. dict_literal = tree_ir.DictionaryLiteralInstruction(
  520. [(tree_ir.LiteralInstruction(key), val) for key, val in named_args])
  521. raise primitive_functions.PrimitiveFinished(
  522. tree_ir.create_jit_call(
  523. tree_ir.LoadGlobalInstruction(jit_runtime.CALL_FUNCTION_NAME),
  524. [('function_id', func_val), ('named_arguments', dict_literal)],
  525. tree_ir.LoadLocalInstruction(jit_runtime.KWARGS_PARAMETER_NAME)))
  526. def try_analyze_direct_call(self, target, argument_list):
  527. """Tries to analyze the given 'call' instruction as a direct call."""
  528. if not self.jit.direct_calls_allowed:
  529. raise jit_runtime.JitCompilationFailedException(
  530. 'Direct calls are not allowed by the JIT.')
  531. # Figure out what the 'func' instruction's type is.
  532. if isinstance(target, bytecode_ir.AccessInstruction):
  533. # 'access(resolve(var))' instructions are translated to direct calls.
  534. if isinstance(target.pointer, bytecode_ir.ResolveInstruction):
  535. self.register_function_var(target.pointer.variable.node_id)
  536. resolved_var_name = target.pointer.variable.name
  537. if self.jit.thunks_enabled:
  538. # Analyze the argument dictionary.
  539. named_args, = yield [("CALL_ARGS", [self.analyze_arguments, (argument_list,)])]
  540. # Try to resolve the callee as an intrinsic.
  541. intrinsic = self.jit.get_intrinsic(resolved_var_name)
  542. if intrinsic is not None:
  543. raise primitive_functions.PrimitiveFinished(
  544. apply_intrinsic(intrinsic, named_args))
  545. # Otherwise, build a thunk.
  546. thunk_name = self.jit.jit_thunk_global(target.pointer.variable.name)
  547. raise primitive_functions.PrimitiveFinished(
  548. tree_ir.create_jit_call(
  549. tree_ir.LoadGlobalInstruction(thunk_name),
  550. named_args,
  551. tree_ir.LoadLocalInstruction(jit_runtime.KWARGS_PARAMETER_NAME)))
  552. else:
  553. # Try to look up the name as a global.
  554. _globals, = yield [("RD", [self.task_root, "globals"])]
  555. global_var, = yield [("RD", [_globals, resolved_var_name])]
  556. global_val, = yield [("RD", [global_var, "value"])]
  557. if global_val is not None:
  558. result, = yield [("CALL_ARGS", [self.analyze_direct_call, (
  559. global_val, resolved_var_name, argument_list)])]
  560. raise primitive_functions.PrimitiveFinished(result)
  561. elif isinstance(target, bytecode_ir.ConstantInstruction):
  562. # 'const(func_id)' instructions are also translated to direct calls.
  563. result, = yield [("CALL_ARGS", [self.analyze_direct_call, (
  564. target.constant_id, None, argument_list)])]
  565. raise primitive_functions.PrimitiveFinished(result)
  566. raise jit_runtime.JitCompilationFailedException(
  567. "Cannot JIT function calls that target an unknown value as direct calls.")
  568. def analyze_call(self, instruction):
  569. """Tries to analyze the given 'call' instruction."""
  570. def handle_exception(_):
  571. # Looks like we'll have to compile it as an indirect call.
  572. gen = self.analyze_indirect_call(instruction.target, instruction.argument_list)
  573. result, = yield [("CALL", [gen])]
  574. raise primitive_functions.PrimitiveFinished(result)
  575. # Try to analyze the call as a direct call.
  576. yield [("TRY", [])]
  577. yield [("CATCH", [jit_runtime.JitCompilationFailedException, handle_exception])]
  578. result, = yield [
  579. ("CALL_ARGS",
  580. [self.try_analyze_direct_call, (instruction.target, instruction.argument_list)])]
  581. yield [("END_TRY", [])]
  582. raise primitive_functions.PrimitiveFinished(result)
  583. def analyze_break(self, instruction):
  584. """Tries to analyze the given 'break' instruction."""
  585. if instruction.loop == self.enclosing_loop_instruction:
  586. raise primitive_functions.PrimitiveFinished(tree_ir.BreakInstruction())
  587. else:
  588. raise jit_runtime.JitCompilationFailedException(
  589. "Multilevel 'break' is not supported by the baseline JIT.")
  590. def analyze_continue(self, instruction):
  591. """Tries to analyze the given 'continue' instruction."""
  592. if instruction.loop == self.enclosing_loop_instruction:
  593. raise primitive_functions.PrimitiveFinished(tree_ir.ContinueInstruction())
  594. else:
  595. raise jit_runtime.JitCompilationFailedException(
  596. "Multilevel 'continue' is not supported by the baseline JIT.")
  597. instruction_analyzers = {
  598. bytecode_ir.SelectInstruction : analyze_if,
  599. bytecode_ir.WhileInstruction : analyze_while,
  600. bytecode_ir.ReturnInstruction : analyze_return,
  601. bytecode_ir.ConstantInstruction : analyze_constant,
  602. bytecode_ir.ResolveInstruction : analyze_resolve,
  603. bytecode_ir.DeclareInstruction : analyze_declare,
  604. bytecode_ir.GlobalInstruction : analyze_global,
  605. bytecode_ir.AssignInstruction : analyze_assign,
  606. bytecode_ir.AccessInstruction : analyze_access,
  607. bytecode_ir.OutputInstruction : analyze_output,
  608. bytecode_ir.InputInstruction : analyze_input,
  609. bytecode_ir.CallInstruction : analyze_call,
  610. bytecode_ir.BreakInstruction : analyze_break,
  611. bytecode_ir.ContinueInstruction : analyze_continue
  612. }