bytecode_to_tree.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  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. class LocalNameMap(object):
  215. """A map that converts local variable nodes to identifiers."""
  216. def __init__(self, local_mapping=None):
  217. if local_mapping is None:
  218. local_mapping = {}
  219. self.local_mapping = local_mapping
  220. def get_local_name(self, local_variable_id):
  221. """Gets the name for the local variable node with the given id."""
  222. if local_variable_id not in self.local_mapping:
  223. self.local_mapping[local_variable_id] = 'local%d' % local_variable_id
  224. return self.local_mapping[local_variable_id]
  225. class AnalysisState(object):
  226. """The state of a bytecode analysis call graph."""
  227. def __init__(self, jit, body_id, task_root, local_mapping, max_instructions=None):
  228. self.analyzed_instructions = set()
  229. self.function_vars = set()
  230. self.local_vars = set()
  231. self.body_id = body_id
  232. self.max_instructions = max_instructions
  233. self.task_root = task_root
  234. self.jit = jit
  235. self.local_name_map = LocalNameMap(local_mapping)
  236. self.function_name = jit.jitted_entry_points[body_id]
  237. self.enclosing_loop_instruction = None
  238. def register_local_var(self, local_id):
  239. """Registers the given variable node id as a local."""
  240. if local_id in self.function_vars:
  241. raise jit_runtime.JitCompilationFailedException(
  242. "Local is used as target of function call.")
  243. self.local_vars.add(local_id)
  244. def register_function_var(self, local_id):
  245. """Registers the given variable node id as a function."""
  246. if local_id in self.local_vars:
  247. raise jit_runtime.JitCompilationFailedException(
  248. "Local is used as target of function call.")
  249. self.function_vars.add(local_id)
  250. def analyze(self, instruction):
  251. """Tries to build an intermediate representation from the instruction with the
  252. given id."""
  253. # Check the analyzed_instructions set for instruction_id to avoid
  254. # infinite loops.
  255. if instruction in self.analyzed_instructions:
  256. raise jit_runtime.JitCompilationFailedException(
  257. 'Cannot jit non-tree instruction graph.')
  258. elif (self.max_instructions is not None and
  259. len(self.analyzed_instructions) > self.max_instructions):
  260. raise jit_runtime.JitCompilationFailedException(
  261. 'Maximum number of instructions exceeded.')
  262. self.analyzed_instructions.add(instruction)
  263. instruction_type = type(instruction)
  264. if instruction_type in self.instruction_analyzers:
  265. # Analyze the instruction itself.
  266. outer_result, = yield [
  267. ("CALL_ARGS", [self.instruction_analyzers[instruction_type], (self, instruction)])]
  268. if self.jit.tracing_enabled and instruction.debug_information is not None:
  269. outer_result = tree_ir.with_debug_info_trace(
  270. outer_result, instruction.debug_information, self.function_name)
  271. # Check if the instruction has a 'next' instruction.
  272. if instruction.next_instruction is None:
  273. raise primitive_functions.PrimitiveFinished(outer_result)
  274. else:
  275. next_result, = yield [
  276. ("CALL_ARGS", [self.analyze, (instruction.next_instruction,)])]
  277. raise primitive_functions.PrimitiveFinished(
  278. tree_ir.CompoundInstruction(
  279. outer_result,
  280. next_result))
  281. else:
  282. raise jit_runtime.JitCompilationFailedException(
  283. "Unknown instruction type: '%s'" % type(instruction))
  284. def analyze_all(self, instruction_ids):
  285. """Tries to compile a list of IR trees from the given list of instruction ids."""
  286. results = []
  287. for inst in instruction_ids:
  288. analyzed_inst, = yield [("CALL_ARGS", [self.analyze, (inst,)])]
  289. results.append(analyzed_inst)
  290. raise primitive_functions.PrimitiveFinished(results)
  291. def analyze_return(self, instruction):
  292. """Tries to analyze the given 'return' instruction."""
  293. def create_return(return_value):
  294. return tree_ir.ReturnInstruction(
  295. tree_ir.CompoundInstruction(
  296. return_value,
  297. tree_ir.DeleteEdgeInstruction(
  298. tree_ir.LoadLocalInstruction(jit_runtime.LOCALS_EDGE_NAME))))
  299. if instruction.value is None:
  300. raise primitive_functions.PrimitiveFinished(
  301. create_return(
  302. tree_ir.EmptyInstruction()))
  303. else:
  304. retval, = yield [("CALL_ARGS", [self.analyze, (instruction.value,)])]
  305. raise primitive_functions.PrimitiveFinished(
  306. create_return(retval))
  307. def analyze_if(self, instruction):
  308. """Tries to analyze the given 'if' instruction."""
  309. if instruction.else_clause is None:
  310. (cond_r, true_r), = yield [
  311. ("CALL_ARGS",
  312. [self.analyze_all,
  313. ([instruction.condition, instruction.if_clause],)])]
  314. false_r = tree_ir.EmptyInstruction()
  315. else:
  316. (cond_r, true_r, false_r), = yield [
  317. ("CALL_ARGS",
  318. [self.analyze_all,
  319. ([instruction.condition, instruction.if_clause, instruction.else_clause],)])]
  320. raise primitive_functions.PrimitiveFinished(
  321. tree_ir.SelectInstruction(
  322. tree_ir.ReadValueInstruction(cond_r),
  323. true_r,
  324. false_r))
  325. def analyze_while(self, instruction):
  326. """Tries to analyze the given 'while' instruction."""
  327. # Analyze the condition.
  328. cond_r, = yield [("CALL_ARGS", [self.analyze, (instruction.condition,)])]
  329. # Store the old enclosing loop on the stack, and make this loop the
  330. # new enclosing loop.
  331. old_loop_instruction = self.enclosing_loop_instruction
  332. self.enclosing_loop_instruction = instruction
  333. body_r, = yield [("CALL_ARGS", [self.analyze, (instruction.body,)])]
  334. # Restore hte old enclosing loop.
  335. self.enclosing_loop_instruction = old_loop_instruction
  336. if self.jit.nop_insertion_enabled:
  337. create_loop_body = lambda check, body: tree_ir.create_block(
  338. check,
  339. body_r,
  340. tree_ir.NopInstruction())
  341. else:
  342. create_loop_body = tree_ir.CompoundInstruction
  343. raise primitive_functions.PrimitiveFinished(
  344. tree_ir.LoopInstruction(
  345. create_loop_body(
  346. tree_ir.SelectInstruction(
  347. tree_ir.ReadValueInstruction(cond_r),
  348. tree_ir.EmptyInstruction(),
  349. tree_ir.BreakInstruction()),
  350. body_r)))
  351. def analyze_constant(self, instruction):
  352. """Tries to analyze the given 'constant' (literal) instruction."""
  353. raise primitive_functions.PrimitiveFinished(
  354. tree_ir.LiteralInstruction(instruction.constant_id))
  355. def analyze_output(self, instruction):
  356. """Tries to analyze the given 'output' instruction."""
  357. value_val, = yield [("CALL_ARGS", [self.analyze, (instruction.value,)])]
  358. raise primitive_functions.PrimitiveFinished(create_output(value_val))
  359. def analyze_input(self, _):
  360. """Tries to analyze the given 'input' instruction."""
  361. raise primitive_functions.PrimitiveFinished(create_input(self.jit.input_function_enabled))
  362. def analyze_resolve(self, instruction):
  363. """Tries to analyze the given 'resolve' instruction."""
  364. # To resolve a variable, we'll do something along the
  365. # lines of:
  366. #
  367. # if 'local_var' in locals():
  368. # tmp = local_var
  369. # else:
  370. # _globals, = yield [("RD", [task_root, "globals"])]
  371. # global_var, = yield [("RD", [_globals, var_name])]
  372. #
  373. # if global_var is None:
  374. # raise Exception("Not found as global: %s" % (var_name))
  375. #
  376. # tmp = global_var
  377. name = self.local_name_map.get_local_name(instruction.variable.node_id)
  378. if instruction.variable.name is None:
  379. raise primitive_functions.PrimitiveFinished(
  380. tree_ir.LoadLocalInstruction(name))
  381. task_root = retrieve_task_root()
  382. global_var = tree_ir.StoreLocalInstruction(
  383. 'global_var',
  384. tree_ir.ReadDictionaryValueInstruction(
  385. tree_ir.ReadDictionaryValueInstruction(
  386. task_root.create_load(),
  387. tree_ir.LiteralInstruction('globals')),
  388. tree_ir.LiteralInstruction(instruction.variable.name)))
  389. err_block = tree_ir.SelectInstruction(
  390. tree_ir.BinaryInstruction(
  391. global_var.create_load(),
  392. 'is',
  393. tree_ir.LiteralInstruction(None)),
  394. tree_ir.RaiseInstruction(
  395. tree_ir.CallInstruction(
  396. tree_ir.LoadGlobalInstruction('Exception'),
  397. [tree_ir.LiteralInstruction(
  398. jit_runtime.GLOBAL_NOT_FOUND_MESSAGE_FORMAT % instruction.variable.name)
  399. ])),
  400. tree_ir.EmptyInstruction())
  401. raise primitive_functions.PrimitiveFinished(
  402. tree_ir.SelectInstruction(
  403. tree_ir.LocalExistsInstruction(name),
  404. tree_ir.LoadLocalInstruction(name),
  405. tree_ir.CompoundInstruction(
  406. tree_ir.create_block(
  407. task_root,
  408. global_var,
  409. err_block),
  410. global_var.create_load())))
  411. def analyze_declare(self, instruction):
  412. """Tries to analyze the given 'declare' function."""
  413. self.register_local_var(instruction.variable.node_id)
  414. name = self.local_name_map.get_local_name(instruction.variable.node_id)
  415. # The following logic declares a local:
  416. #
  417. # if 'local_name' not in locals():
  418. # local_name, = yield [("CN", [])]
  419. # yield [("CE", [LOCALS_NODE_NAME, local_name])]
  420. raise primitive_functions.PrimitiveFinished(
  421. tree_ir.SelectInstruction(
  422. tree_ir.LocalExistsInstruction(name),
  423. tree_ir.EmptyInstruction(),
  424. tree_ir.create_new_local_node(
  425. name,
  426. tree_ir.LoadLocalInstruction(jit_runtime.LOCALS_NODE_NAME))))
  427. def analyze_global(self, instruction):
  428. """Tries to analyze the given 'global' (declaration) instruction."""
  429. # To declare a variable, we'll do something along the
  430. # lines of:
  431. #
  432. # _globals, = yield [("RD", [task_root, "globals"])]
  433. # global_var = yield [("RD", [_globals, var_name])]
  434. #
  435. # if global_var is None:
  436. # global_var, = yield [("CN", [])]
  437. # yield [("CD", [_globals, var_name, global_var])]
  438. #
  439. # tmp = global_var
  440. task_root = retrieve_task_root()
  441. _globals = tree_ir.StoreLocalInstruction(
  442. '_globals',
  443. tree_ir.ReadDictionaryValueInstruction(
  444. task_root.create_load(),
  445. tree_ir.LiteralInstruction('globals')))
  446. global_var = tree_ir.StoreLocalInstruction(
  447. 'global_var',
  448. tree_ir.ReadDictionaryValueInstruction(
  449. _globals.create_load(),
  450. tree_ir.LiteralInstruction(instruction.variable.name)))
  451. raise primitive_functions.PrimitiveFinished(
  452. tree_ir.CompoundInstruction(
  453. tree_ir.create_block(
  454. task_root,
  455. _globals,
  456. global_var,
  457. tree_ir.SelectInstruction(
  458. tree_ir.BinaryInstruction(
  459. global_var.create_load(),
  460. 'is',
  461. tree_ir.LiteralInstruction(None)),
  462. tree_ir.create_block(
  463. global_var.create_store(
  464. tree_ir.CreateNodeInstruction()),
  465. tree_ir.CreateDictionaryEdgeInstruction(
  466. _globals.create_load(),
  467. tree_ir.LiteralInstruction(
  468. instruction.variable.name),
  469. global_var.create_load())),
  470. tree_ir.EmptyInstruction())),
  471. global_var.create_load()))
  472. def analyze_assign(self, instruction):
  473. """Tries to analyze the given 'assign' instruction."""
  474. (var_r, value_r), = yield [
  475. ("CALL_ARGS", [self.analyze_all, ([instruction.pointer, instruction.value],)])]
  476. raise primitive_functions.PrimitiveFinished(create_assign(var_r, value_r))
  477. def analyze_access(self, instruction):
  478. """Tries to analyze the given 'access' instruction."""
  479. var_r, = yield [("CALL_ARGS", [self.analyze, (instruction.pointer,)])]
  480. raise primitive_functions.PrimitiveFinished(create_access(var_r))
  481. def analyze_direct_call(self, callee_id, callee_name, argument_list):
  482. """Tries to analyze a direct 'call' instruction."""
  483. body_id, = yield [("RD", [callee_id, jit_runtime.FUNCTION_BODY_KEY])]
  484. # Make this function dependent on the callee.
  485. if body_id in self.jit.compilation_dependencies:
  486. self.jit.compilation_dependencies[body_id].add(self.body_id)
  487. # Figure out if the function might be an intrinsic.
  488. intrinsic = self.jit.get_intrinsic(callee_name)
  489. if intrinsic is None:
  490. if callee_name is not None:
  491. self.jit.register_global(body_id, callee_name)
  492. compiled_func = self.jit.lookup_compiled_function(callee_name)
  493. else:
  494. compiled_func = None
  495. if compiled_func is None:
  496. # Compile the callee.
  497. yield [
  498. ("CALL_ARGS", [self.jit.jit_compile, (self.task_root, body_id, callee_name)])]
  499. # Get the callee's name.
  500. compiled_func_name = self.jit.get_compiled_name(body_id)
  501. # This handles the corner case where a constant node is called, like
  502. # 'call(constant(9), ...)'. In this case, `callee_name` is `None`
  503. # because 'constant(9)' doesn't give us a name. However, we can look up
  504. # the name of the function at a specific node. If that turns out to be
  505. # an intrinsic, then we still want to pick the intrinsic over a call.
  506. intrinsic = self.jit.get_intrinsic(compiled_func_name)
  507. # Analyze the argument dictionary.
  508. named_args, = yield [("CALL_ARGS", [self.analyze_arguments, (argument_list,)])]
  509. if intrinsic is not None:
  510. raise primitive_functions.PrimitiveFinished(
  511. apply_intrinsic(intrinsic, named_args))
  512. else:
  513. raise primitive_functions.PrimitiveFinished(
  514. tree_ir.create_jit_call(
  515. tree_ir.LoadGlobalInstruction(compiled_func_name),
  516. named_args,
  517. tree_ir.LoadLocalInstruction(jit_runtime.KWARGS_PARAMETER_NAME)))
  518. def analyze_arguments(self, argument_list):
  519. """Analyzes the given parameter-to-value mapping."""
  520. named_args = []
  521. for param_name, arg in argument_list:
  522. param_val, = yield [("CALL_ARGS", [self.analyze, (arg,)])]
  523. named_args.append((param_name, param_val))
  524. raise primitive_functions.PrimitiveFinished(named_args)
  525. def analyze_indirect_call(self, target, argument_list):
  526. """Analyzes a call to an unknown function."""
  527. # First off, let's analyze the callee and the argument list.
  528. func_val, = yield [("CALL_ARGS", [self.analyze, (target,)])]
  529. named_args, = yield [("CALL_ARGS", [self.analyze_arguments, (argument_list,)])]
  530. func_val = tree_ir.StoreLocalInstruction(None, func_val)
  531. raise primitive_functions.PrimitiveFinished(
  532. tree_ir.create_block(
  533. func_val,
  534. create_indirect_call(func_val.create_load(), named_args)))
  535. def try_analyze_direct_call(self, target, argument_list):
  536. """Tries to analyze the given 'call' instruction as a direct call."""
  537. if not self.jit.direct_calls_allowed:
  538. raise jit_runtime.JitCompilationFailedException(
  539. 'Direct calls are not allowed by the JIT.')
  540. # Figure out what the 'func' instruction's type is.
  541. if isinstance(target, bytecode_ir.AccessInstruction):
  542. # 'access(resolve(var))' instructions are translated to direct calls.
  543. if isinstance(target.pointer, bytecode_ir.ResolveInstruction):
  544. self.register_function_var(target.pointer.variable.node_id)
  545. resolved_var_name = target.pointer.variable.name
  546. if self.jit.thunks_enabled:
  547. # Analyze the argument dictionary.
  548. named_args, = yield [("CALL_ARGS", [self.analyze_arguments, (argument_list,)])]
  549. # Try to resolve the callee as an intrinsic.
  550. intrinsic = self.jit.get_intrinsic(resolved_var_name)
  551. if intrinsic is not None:
  552. raise primitive_functions.PrimitiveFinished(
  553. apply_intrinsic(intrinsic, named_args))
  554. # Otherwise, build a thunk.
  555. thunk_name = self.jit.jit_thunk_global(target.pointer.variable.name)
  556. raise primitive_functions.PrimitiveFinished(
  557. tree_ir.create_jit_call(
  558. tree_ir.LoadGlobalInstruction(thunk_name),
  559. named_args,
  560. tree_ir.LoadLocalInstruction(jit_runtime.KWARGS_PARAMETER_NAME)))
  561. else:
  562. # Try to look up the name as a global.
  563. _globals, = yield [("RD", [self.task_root, "globals"])]
  564. global_var, = yield [("RD", [_globals, resolved_var_name])]
  565. global_val, = yield [("RD", [global_var, "value"])]
  566. if global_val is not None:
  567. result, = yield [("CALL_ARGS", [self.analyze_direct_call, (
  568. global_val, resolved_var_name, argument_list)])]
  569. raise primitive_functions.PrimitiveFinished(result)
  570. elif isinstance(target, bytecode_ir.ConstantInstruction):
  571. # 'const(func_id)' instructions are also translated to direct calls.
  572. result, = yield [("CALL_ARGS", [self.analyze_direct_call, (
  573. target.constant_id, None, argument_list)])]
  574. raise primitive_functions.PrimitiveFinished(result)
  575. raise jit_runtime.JitCompilationFailedException(
  576. "Cannot JIT function calls that target an unknown value as direct calls.")
  577. def analyze_call(self, instruction):
  578. """Tries to analyze the given 'call' instruction."""
  579. def handle_exception(_):
  580. # Looks like we'll have to compile it as an indirect call.
  581. gen = self.analyze_indirect_call(instruction.target, instruction.argument_list)
  582. result, = yield [("CALL", [gen])]
  583. raise primitive_functions.PrimitiveFinished(result)
  584. # Try to analyze the call as a direct call.
  585. yield [("TRY", [])]
  586. yield [("CATCH", [jit_runtime.JitCompilationFailedException, handle_exception])]
  587. result, = yield [
  588. ("CALL_ARGS",
  589. [self.try_analyze_direct_call, (instruction.target, instruction.argument_list)])]
  590. yield [("END_TRY", [])]
  591. raise primitive_functions.PrimitiveFinished(result)
  592. def analyze_break(self, instruction):
  593. """Tries to analyze the given 'break' instruction."""
  594. if instruction.loop == self.enclosing_loop_instruction:
  595. raise primitive_functions.PrimitiveFinished(tree_ir.BreakInstruction())
  596. else:
  597. raise jit_runtime.JitCompilationFailedException(
  598. "Multilevel 'break' is not supported by the baseline JIT.")
  599. def analyze_continue(self, instruction):
  600. """Tries to analyze the given 'continue' instruction."""
  601. if instruction.loop == self.enclosing_loop_instruction:
  602. raise primitive_functions.PrimitiveFinished(tree_ir.ContinueInstruction())
  603. else:
  604. raise jit_runtime.JitCompilationFailedException(
  605. "Multilevel 'continue' is not supported by the baseline JIT.")
  606. instruction_analyzers = {
  607. bytecode_ir.SelectInstruction : analyze_if,
  608. bytecode_ir.WhileInstruction : analyze_while,
  609. bytecode_ir.ReturnInstruction : analyze_return,
  610. bytecode_ir.ConstantInstruction : analyze_constant,
  611. bytecode_ir.ResolveInstruction : analyze_resolve,
  612. bytecode_ir.DeclareInstruction : analyze_declare,
  613. bytecode_ir.GlobalInstruction : analyze_global,
  614. bytecode_ir.AssignInstruction : analyze_assign,
  615. bytecode_ir.AccessInstruction : analyze_access,
  616. bytecode_ir.OutputInstruction : analyze_output,
  617. bytecode_ir.InputInstruction : analyze_input,
  618. bytecode_ir.CallInstruction : analyze_call,
  619. bytecode_ir.BreakInstruction : analyze_break,
  620. bytecode_ir.ContinueInstruction : analyze_continue
  621. }