bytecode_to_tree.py 31 KB

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