bytecode_to_tree.py 31 KB

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