bytecode_to_tree.py 32 KB

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