jit.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  1. import modelverse_kernel.primitives as primitive_functions
  2. import modelverse_jit.tree_ir as tree_ir
  3. import modelverse_jit.runtime as jit_runtime
  4. import keyword
  5. # Import JitCompilationFailedException because it used to be defined
  6. # in this module.
  7. JitCompilationFailedException = jit_runtime.JitCompilationFailedException
  8. KWARGS_PARAMETER_NAME = "kwargs"
  9. """The name of the kwargs parameter in jitted functions."""
  10. CALL_FUNCTION_NAME = "__call_function"
  11. """The name of the '__call_function' function, in the jitted function scope."""
  12. GET_INPUT_FUNCTION_NAME = "__get_input"
  13. """The name of the '__get_input' function, in the jitted function scope."""
  14. def get_parameter_names(compiled_function):
  15. """Gets the given compiled function's parameter names."""
  16. if hasattr(compiled_function, '__code__'):
  17. return compiled_function.__code__.co_varnames[
  18. :compiled_function.__code__.co_argcount]
  19. elif hasattr(compiled_function, '__init__'):
  20. return get_parameter_names(compiled_function.__init__)[1:]
  21. else:
  22. raise ValueError("'compiled_function' must be a function or a type.")
  23. def apply_intrinsic(intrinsic_function, named_args):
  24. """Applies the given intrinsic to the given sequence of named arguments."""
  25. param_names = get_parameter_names(intrinsic_function)
  26. if tuple(param_names) == tuple([n for n, _ in named_args]):
  27. # Perfect match. Yay!
  28. return intrinsic_function(**dict(named_args))
  29. else:
  30. # We'll have to store the arguments into locals to preserve
  31. # the order of evaluation.
  32. stored_args = [(name, tree_ir.StoreLocalInstruction(None, arg)) for name, arg in named_args]
  33. arg_value_dict = dict([(name, arg.create_load()) for name, arg in stored_args])
  34. store_instructions = [instruction for _, instruction in stored_args]
  35. return tree_ir.CompoundInstruction(
  36. tree_ir.create_block(*store_instructions),
  37. intrinsic_function(**arg_value_dict))
  38. def map_and_simplify_generator(function, instruction):
  39. """Applies the given mapping function to every instruction in the tree
  40. that has the given instruction as root, and simplifies it on-the-fly.
  41. This is at least as powerful as first mapping and then simplifying, as
  42. maps and simplifications are interspersed.
  43. This function assumes that function creates a generator that returns by
  44. raising a primitive_functions.PrimitiveFinished."""
  45. # First handle the children by mapping on them and then simplifying them.
  46. new_children = []
  47. for inst in instruction.get_children():
  48. new_inst, = yield [("CALL_ARGS", [map_and_simplify_generator, (function, inst)])]
  49. new_children.append(new_inst)
  50. # Then apply the function to the top-level node.
  51. transformed, = yield [("CALL_ARGS", [function, (instruction.create(new_children),)])]
  52. # Finally, simplify the transformed top-level node.
  53. raise primitive_functions.PrimitiveFinished(transformed.simplify_node())
  54. def expand_constant_read(instruction):
  55. """Tries to replace a read of a constant node by a literal."""
  56. if isinstance(instruction, tree_ir.ReadValueInstruction) and \
  57. isinstance(instruction.node_id, tree_ir.LiteralInstruction):
  58. val, = yield [("RV", [instruction.node_id.literal])]
  59. raise primitive_functions.PrimitiveFinished(tree_ir.LiteralInstruction(val))
  60. else:
  61. raise primitive_functions.PrimitiveFinished(instruction)
  62. def optimize_tree_ir(instruction):
  63. """Optimizes an IR tree."""
  64. return map_and_simplify_generator(expand_constant_read, instruction)
  65. class ModelverseJit(object):
  66. """A high-level interface to the modelverse JIT compiler."""
  67. def __init__(self, max_instructions=None, compiled_function_lookup=None):
  68. self.todo_entry_points = set()
  69. self.no_jit_entry_points = set()
  70. self.jitted_entry_points = {}
  71. self.jitted_parameters = {}
  72. self.jit_globals = {
  73. 'PrimitiveFinished' : primitive_functions.PrimitiveFinished,
  74. CALL_FUNCTION_NAME : jit_runtime.call_function,
  75. GET_INPUT_FUNCTION_NAME : jit_runtime.get_input
  76. }
  77. self.jit_count = 0
  78. self.max_instructions = max_instructions
  79. self.compiled_function_lookup = compiled_function_lookup
  80. # jit_intrinsics is a function name -> intrinsic map.
  81. self.jit_intrinsics = {}
  82. self.compilation_dependencies = {}
  83. self.jit_enabled = True
  84. self.direct_calls_allowed = True
  85. self.tracing_enabled = False
  86. self.input_function_enabled = False
  87. def set_jit_enabled(self, is_enabled=True):
  88. """Enables or disables the JIT."""
  89. self.jit_enabled = is_enabled
  90. def allow_direct_calls(self, is_allowed=True):
  91. """Allows or disallows direct calls from jitted to jitted code."""
  92. self.direct_calls_allowed = is_allowed
  93. def use_input_function(self, is_enabled=True):
  94. """Configures the JIT to compile 'input' instructions as function calls."""
  95. self.input_function_enabled = is_enabled
  96. def enable_tracing(self, is_enabled=True):
  97. """Enables or disables tracing for jitted code."""
  98. self.tracing_enabled = is_enabled
  99. def mark_entry_point(self, body_id):
  100. """Marks the node with the given identifier as a function entry point."""
  101. if body_id not in self.no_jit_entry_points and body_id not in self.jitted_entry_points:
  102. self.todo_entry_points.add(body_id)
  103. def is_entry_point(self, body_id):
  104. """Tells if the node with the given identifier is a function entry point."""
  105. return body_id in self.todo_entry_points or \
  106. body_id in self.no_jit_entry_points or \
  107. body_id in self.jitted_entry_points
  108. def is_jittable_entry_point(self, body_id):
  109. """Tells if the node with the given identifier is a function entry point that
  110. has not been marked as non-jittable. This only returns `True` if the JIT
  111. is enabled and the function entry point has been marked jittable, or if
  112. the function has already been compiled."""
  113. return ((self.jit_enabled and body_id in self.todo_entry_points) or
  114. self.has_compiled(body_id))
  115. def has_compiled(self, body_id):
  116. """Tests if the function belonging to the given body node has been compiled yet."""
  117. return body_id in self.jitted_entry_points
  118. def get_compiled_name(self, body_id):
  119. """Gets the name of the compiled version of the given body node in the JIT
  120. global state."""
  121. return self.jitted_entry_points[body_id]
  122. def mark_no_jit(self, body_id):
  123. """Informs the JIT that the node with the given identifier is a function entry
  124. point that must never be jitted."""
  125. self.no_jit_entry_points.add(body_id)
  126. if body_id in self.todo_entry_points:
  127. self.todo_entry_points.remove(body_id)
  128. def generate_function_name(self, suggested_name=None):
  129. """Generates a new function name or picks the suggested name if it is still
  130. available."""
  131. if suggested_name is not None \
  132. and suggested_name not in self.jit_globals \
  133. and not keyword.iskeyword(suggested_name):
  134. self.jit_count += 1
  135. return suggested_name
  136. else:
  137. function_name = 'jit_func%d' % self.jit_count
  138. self.jit_count += 1
  139. return function_name
  140. def register_compiled(self, body_id, compiled_function, function_name=None):
  141. """Registers a compiled entry point with the JIT."""
  142. # Get the function's name.
  143. function_name = self.generate_function_name(function_name)
  144. # Map the body id to the given parameter list.
  145. self.jitted_entry_points[body_id] = function_name
  146. self.jit_globals[function_name] = compiled_function
  147. if body_id in self.todo_entry_points:
  148. self.todo_entry_points.remove(body_id)
  149. def lookup_compiled_function(self, name):
  150. """Looks up a compiled function by name. Returns a matching function,
  151. or None if no function was found."""
  152. if name is None:
  153. return None
  154. elif name in self.jit_globals:
  155. return self.jit_globals[name]
  156. elif self.compiled_function_lookup is not None:
  157. return self.compiled_function_lookup(name)
  158. else:
  159. return None
  160. def get_intrinsic(self, name):
  161. """Tries to find an intrinsic version of the function with the
  162. given name."""
  163. if name in self.jit_intrinsics:
  164. return self.jit_intrinsics[name]
  165. else:
  166. return None
  167. def register_intrinsic(self, name, intrinsic_function):
  168. """Registers the given intrisic with the JIT. This will make the JIT replace calls to
  169. the function with the given entry point by an application of the specified function."""
  170. self.jit_intrinsics[name] = intrinsic_function
  171. def register_binary_intrinsic(self, name, operator):
  172. """Registers an intrinsic with the JIT that represents the given binary operation."""
  173. self.register_intrinsic(name, lambda a, b: tree_ir.CreateNodeWithValueInstruction(
  174. tree_ir.BinaryInstruction(
  175. tree_ir.ReadValueInstruction(a),
  176. operator,
  177. tree_ir.ReadValueInstruction(b))))
  178. def register_unary_intrinsic(self, name, operator):
  179. """Registers an intrinsic with the JIT that represents the given unary operation."""
  180. self.register_intrinsic(name, lambda a: tree_ir.CreateNodeWithValueInstruction(
  181. tree_ir.UnaryInstruction(
  182. operator,
  183. tree_ir.ReadValueInstruction(a))))
  184. def jit_parameters(self, body_id):
  185. """Acquires the parameter list for the given body id node."""
  186. if body_id not in self.jitted_parameters:
  187. signature_id, = yield [("RRD", [body_id, "body"])]
  188. signature_id = signature_id[0]
  189. param_set_id, = yield [("RD", [signature_id, "params"])]
  190. if param_set_id is None:
  191. self.jitted_parameters[body_id] = ([], [])
  192. else:
  193. param_name_ids, = yield [("RDK", [param_set_id])]
  194. param_names = yield [("RV", [n]) for n in param_name_ids]
  195. param_vars = yield [("RD", [param_set_id, k]) for k in param_names]
  196. self.jitted_parameters[body_id] = (param_vars, param_names)
  197. raise primitive_functions.PrimitiveFinished(self.jitted_parameters[body_id])
  198. def jit_compile(self, user_root, body_id, suggested_name=None):
  199. """Tries to jit the function defined by the given entry point id and parameter list."""
  200. # The comment below makes pylint shut up about our (hopefully benign) use of exec here.
  201. # pylint: disable=I0011,W0122
  202. if body_id is None:
  203. raise ValueError('body_id cannot be None')
  204. elif body_id in self.jitted_entry_points:
  205. # We have already compiled this function.
  206. raise primitive_functions.PrimitiveFinished(
  207. self.jit_globals[self.jitted_entry_points[body_id]])
  208. elif body_id in self.no_jit_entry_points:
  209. # We're not allowed to jit this function or have tried and failed before.
  210. raise JitCompilationFailedException(
  211. 'Cannot jit function %s at %d because it is marked non-jittable.' % (
  212. '' if suggested_name is None else "'" + suggested_name + "'",
  213. body_id))
  214. elif not self.jit_enabled:
  215. # We're not allowed to jit anything.
  216. raise JitCompilationFailedException(
  217. 'Cannot jit function %s at %d because the JIT has been disabled.' % (
  218. '' if suggested_name is None else "'" + suggested_name + "'",
  219. body_id))
  220. # Generate a name for the function we're about to analyze, and pretend that
  221. # it already exists. (we need to do this for recursive functions)
  222. function_name = self.generate_function_name(suggested_name)
  223. self.jitted_entry_points[body_id] = function_name
  224. self.jit_globals[function_name] = None
  225. (parameter_ids, parameter_list), = yield [("CALL_ARGS", [self.jit_parameters, (body_id,)])]
  226. param_dict = dict(zip(parameter_ids, parameter_list))
  227. body_param_dict = dict(zip(parameter_ids, [p + "_ptr" for p in parameter_list]))
  228. dependencies = set([body_id])
  229. self.compilation_dependencies[body_id] = dependencies
  230. def handle_jit_exception(exception):
  231. # If analysis fails, then a JitCompilationFailedException will be thrown.
  232. del self.compilation_dependencies[body_id]
  233. for dep in dependencies:
  234. self.mark_no_jit(dep)
  235. if dep in self.jitted_entry_points:
  236. del self.jitted_entry_points[dep]
  237. raise JitCompilationFailedException(
  238. "%s (function '%s' at %d)" % (exception.message, function_name, body_id))
  239. # Try to analyze the function's body.
  240. yield [("TRY", [])]
  241. yield [("CATCH", [JitCompilationFailedException, handle_jit_exception])]
  242. state = AnalysisState(
  243. self, body_id, user_root, body_param_dict,
  244. self.max_instructions)
  245. constructed_body, = yield [("CALL_ARGS", [state.analyze, (body_id,)])]
  246. yield [("END_TRY", [])]
  247. del self.compilation_dependencies[body_id]
  248. # Write a prologue and prepend it to the generated function body.
  249. prologue_statements = []
  250. for (key, val) in param_dict.items():
  251. arg_ptr = tree_ir.StoreLocalInstruction(
  252. body_param_dict[key],
  253. tree_ir.CreateNodeInstruction())
  254. prologue_statements.append(arg_ptr)
  255. prologue_statements.append(
  256. tree_ir.CreateDictionaryEdgeInstruction(
  257. arg_ptr.create_load(),
  258. tree_ir.LiteralInstruction('value'),
  259. tree_ir.LoadLocalInstruction(val)))
  260. constructed_body = tree_ir.create_block(
  261. *(prologue_statements + [constructed_body]))
  262. # Optimize the function's body.
  263. constructed_body, = yield [("CALL_ARGS", [optimize_tree_ir, (constructed_body,)])]
  264. # Wrap the IR in a function definition, give it a unique name.
  265. constructed_function = tree_ir.DefineFunctionInstruction(
  266. function_name,
  267. parameter_list + ['**' + KWARGS_PARAMETER_NAME],
  268. constructed_body)
  269. # Convert the function definition to Python code, and compile it.
  270. exec(str(constructed_function), self.jit_globals)
  271. # Extract the compiled function from the JIT global state.
  272. compiled_function = self.jit_globals[function_name]
  273. # print(constructed_function)
  274. raise primitive_functions.PrimitiveFinished(compiled_function)
  275. class AnalysisState(object):
  276. """The state of a bytecode analysis call graph."""
  277. def __init__(self, jit, body_id, user_root, local_mapping, max_instructions=None):
  278. self.analyzed_instructions = set()
  279. self.function_vars = set()
  280. self.local_vars = set()
  281. self.body_id = body_id
  282. self.max_instructions = max_instructions
  283. self.user_root = user_root
  284. self.jit = jit
  285. self.local_mapping = local_mapping
  286. self.function_name = jit.jitted_entry_points[body_id]
  287. def get_local_name(self, local_id):
  288. """Gets the name for a local with the given id."""
  289. if local_id not in self.local_mapping:
  290. self.local_mapping[local_id] = 'local%d' % local_id
  291. return self.local_mapping[local_id]
  292. def register_local_var(self, local_id):
  293. """Registers the given variable node id as a local."""
  294. if local_id in self.function_vars:
  295. raise JitCompilationFailedException(
  296. "Local is used as target of function call.")
  297. self.local_vars.add(local_id)
  298. def register_function_var(self, local_id):
  299. """Registers the given variable node id as a function."""
  300. if local_id in self.local_vars:
  301. raise JitCompilationFailedException(
  302. "Local is used as target of function call.")
  303. self.function_vars.add(local_id)
  304. def retrieve_user_root(self):
  305. """Creates an instruction that stores the user_root variable
  306. in a local."""
  307. return tree_ir.StoreLocalInstruction(
  308. 'user_root',
  309. tree_ir.LoadIndexInstruction(
  310. tree_ir.LoadLocalInstruction(KWARGS_PARAMETER_NAME),
  311. tree_ir.LiteralInstruction('user_root')))
  312. def load_kernel(self):
  313. """Creates an instruction that loads the Modelverse kernel."""
  314. return tree_ir.LoadIndexInstruction(
  315. tree_ir.LoadLocalInstruction(KWARGS_PARAMETER_NAME),
  316. tree_ir.LiteralInstruction('mvk'))
  317. def analyze(self, instruction_id):
  318. """Tries to build an intermediate representation from the instruction with the
  319. given id."""
  320. # Check the analyzed_instructions set for instruction_id to avoid
  321. # infinite loops.
  322. if instruction_id in self.analyzed_instructions:
  323. raise JitCompilationFailedException('Cannot jit non-tree instruction graph.')
  324. elif (self.max_instructions is not None and
  325. len(self.analyzed_instructions) > self.max_instructions):
  326. raise JitCompilationFailedException('Maximum number of instructions exceeded.')
  327. self.analyzed_instructions.add(instruction_id)
  328. instruction_val, = yield [("RV", [instruction_id])]
  329. instruction_val = instruction_val["value"]
  330. if instruction_val in self.instruction_analyzers:
  331. # If tracing is enabled, then this would be an appropriate time to
  332. # retrieve the debug information.
  333. if self.jit.tracing_enabled:
  334. debug_info, = yield [("RD", [instruction_id, "__debug"])]
  335. if debug_info is not None:
  336. debug_info, = yield [("RV", [debug_info])]
  337. # Analyze the instruction itself.
  338. outer_result, = yield [
  339. ("CALL_ARGS", [self.instruction_analyzers[instruction_val], (self, instruction_id)])]
  340. if self.jit.tracing_enabled:
  341. outer_result = tree_ir.with_debug_info_trace(outer_result, debug_info, self.function_name)
  342. # Check if the instruction has a 'next' instruction.
  343. next_instr, = yield [("RD", [instruction_id, "next"])]
  344. if next_instr is None:
  345. raise primitive_functions.PrimitiveFinished(outer_result)
  346. else:
  347. next_result, = yield [("CALL_ARGS", [self.analyze, (next_instr,)])]
  348. raise primitive_functions.PrimitiveFinished(
  349. tree_ir.CompoundInstruction(
  350. outer_result,
  351. next_result))
  352. else:
  353. raise JitCompilationFailedException(
  354. "Unknown instruction type: '%s'" % (instruction_val))
  355. def analyze_all(self, instruction_ids):
  356. """Tries to compile a list of IR trees from the given list of instruction ids."""
  357. results = []
  358. for inst in instruction_ids:
  359. analyzed_inst, = yield [("CALL_ARGS", [self.analyze, (inst,)])]
  360. results.append(analyzed_inst)
  361. raise primitive_functions.PrimitiveFinished(results)
  362. def analyze_return(self, instruction_id):
  363. """Tries to analyze the given 'return' instruction."""
  364. retval_id, = yield [("RD", [instruction_id, 'value'])]
  365. if retval_id is None:
  366. raise primitive_functions.PrimitiveFinished(
  367. tree_ir.ReturnInstruction(
  368. tree_ir.EmptyInstruction()))
  369. else:
  370. retval, = yield [("CALL_ARGS", [self.analyze, (retval_id,)])]
  371. raise primitive_functions.PrimitiveFinished(
  372. tree_ir.ReturnInstruction(retval))
  373. def analyze_if(self, instruction_id):
  374. """Tries to analyze the given 'if' instruction."""
  375. cond, true, false = yield [
  376. ("RD", [instruction_id, "cond"]),
  377. ("RD", [instruction_id, "then"]),
  378. ("RD", [instruction_id, "else"])]
  379. analysis_results, = yield [("CALL_ARGS", [self.analyze_all, (
  380. [cond, true]
  381. if false is None
  382. else [cond, true, false],)])]
  383. if false is None:
  384. cond_r, true_r = analysis_results
  385. false_r = tree_ir.EmptyInstruction()
  386. else:
  387. cond_r, true_r, false_r = analysis_results
  388. raise primitive_functions.PrimitiveFinished(
  389. tree_ir.SelectInstruction(
  390. tree_ir.ReadValueInstruction(cond_r),
  391. true_r,
  392. false_r))
  393. def analyze_while(self, instruction_id):
  394. """Tries to analyze the given 'while' instruction."""
  395. cond, body = yield [
  396. ("RD", [instruction_id, "cond"]),
  397. ("RD", [instruction_id, "body"])]
  398. (cond_r, body_r), = yield [("CALL_ARGS", [self.analyze_all, ([cond, body],)])]
  399. raise primitive_functions.PrimitiveFinished(
  400. tree_ir.LoopInstruction(
  401. tree_ir.CompoundInstruction(
  402. tree_ir.SelectInstruction(
  403. tree_ir.ReadValueInstruction(cond_r),
  404. tree_ir.EmptyInstruction(),
  405. tree_ir.BreakInstruction()),
  406. body_r)))
  407. def analyze_constant(self, instruction_id):
  408. """Tries to analyze the given 'constant' (literal) instruction."""
  409. node_id, = yield [("RD", [instruction_id, "node"])]
  410. raise primitive_functions.PrimitiveFinished(
  411. tree_ir.LiteralInstruction(node_id))
  412. def analyze_output(self, instruction_id):
  413. """Tries to analyze the given 'output' instruction."""
  414. # The plan is to basically generate this tree:
  415. #
  416. # value = <some tree>
  417. # last_output, last_output_link, new_last_output = \
  418. # yield [("RD", [user_root, "last_output"]),
  419. # ("RDE", [user_root, "last_output"]),
  420. # ("CN", []),
  421. # ]
  422. # _, _, _, _ = \
  423. # yield [("CD", [last_output, "value", value]),
  424. # ("CD", [last_output, "next", new_last_output]),
  425. # ("CD", [user_root, "last_output", new_last_output]),
  426. # ("DE", [last_output_link])
  427. # ]
  428. # yield None
  429. value_id, = yield [("RD", [instruction_id, "value"])]
  430. value_val, = yield [("CALL_ARGS", [self.analyze, (value_id,)])]
  431. value_local = tree_ir.StoreLocalInstruction('value', value_val)
  432. store_user_root = self.retrieve_user_root()
  433. last_output = tree_ir.StoreLocalInstruction(
  434. 'last_output',
  435. tree_ir.ReadDictionaryValueInstruction(
  436. store_user_root.create_load(),
  437. tree_ir.LiteralInstruction('last_output')))
  438. last_output_link = tree_ir.StoreLocalInstruction(
  439. 'last_output_link',
  440. tree_ir.ReadDictionaryEdgeInstruction(
  441. store_user_root.create_load(),
  442. tree_ir.LiteralInstruction('last_output')))
  443. new_last_output = tree_ir.StoreLocalInstruction(
  444. 'new_last_output',
  445. tree_ir.CreateNodeInstruction())
  446. result = tree_ir.create_block(
  447. value_local,
  448. store_user_root,
  449. last_output,
  450. last_output_link,
  451. new_last_output,
  452. tree_ir.CreateDictionaryEdgeInstruction(
  453. last_output.create_load(),
  454. tree_ir.LiteralInstruction('value'),
  455. value_local.create_load()),
  456. tree_ir.CreateDictionaryEdgeInstruction(
  457. last_output.create_load(),
  458. tree_ir.LiteralInstruction('next'),
  459. new_last_output.create_load()),
  460. tree_ir.CreateDictionaryEdgeInstruction(
  461. store_user_root.create_load(),
  462. tree_ir.LiteralInstruction('last_output'),
  463. new_last_output.create_load()),
  464. tree_ir.DeleteEdgeInstruction(last_output_link.create_load()),
  465. tree_ir.NopInstruction())
  466. raise primitive_functions.PrimitiveFinished(result)
  467. def analyze_input(self, _):
  468. """Tries to analyze the given 'input' instruction."""
  469. # Possible alternative to the explicit syntax tree:
  470. if self.jit.input_function_enabled:
  471. raise primitive_functions.PrimitiveFinished(
  472. tree_ir.create_jit_call(
  473. tree_ir.LoadGlobalInstruction(GET_INPUT_FUNCTION_NAME),
  474. [],
  475. tree_ir.LoadLocalInstruction(KWARGS_PARAMETER_NAME)))
  476. # The plan is to generate this tree:
  477. #
  478. # value = None
  479. # while True:
  480. # _input = yield [("RD", [user_root, "input"])]
  481. # value = yield [("RD", [_input, "value"])]
  482. #
  483. # if value is None:
  484. # kwargs['mvk'].success = False # to avoid blocking
  485. # yield None # nop/interrupt
  486. # else:
  487. # break
  488. #
  489. # _next = yield [("RD", [_input, "next"])]
  490. # yield [("CD", [user_root, "input", _next])]
  491. # yield [("DN", [_input])]
  492. user_root = self.retrieve_user_root()
  493. _input = tree_ir.StoreLocalInstruction(
  494. None,
  495. tree_ir.ReadDictionaryValueInstruction(
  496. user_root.create_load(),
  497. tree_ir.LiteralInstruction('input')))
  498. value = tree_ir.StoreLocalInstruction(
  499. None,
  500. tree_ir.ReadDictionaryValueInstruction(
  501. _input.create_load(),
  502. tree_ir.LiteralInstruction('value')))
  503. raise primitive_functions.PrimitiveFinished(
  504. tree_ir.CompoundInstruction(
  505. tree_ir.create_block(
  506. user_root,
  507. value.create_store(tree_ir.LiteralInstruction(None)),
  508. tree_ir.LoopInstruction(
  509. tree_ir.create_block(
  510. _input,
  511. value,
  512. tree_ir.SelectInstruction(
  513. tree_ir.BinaryInstruction(
  514. value.create_load(),
  515. 'is',
  516. tree_ir.LiteralInstruction(None)),
  517. tree_ir.create_block(
  518. tree_ir.StoreMemberInstruction(
  519. self.load_kernel(),
  520. 'success',
  521. tree_ir.LiteralInstruction(False)),
  522. tree_ir.NopInstruction()),
  523. tree_ir.BreakInstruction()))),
  524. tree_ir.CreateDictionaryEdgeInstruction(
  525. user_root.create_load(),
  526. tree_ir.LiteralInstruction('input'),
  527. tree_ir.ReadDictionaryValueInstruction(
  528. _input.create_load(),
  529. tree_ir.LiteralInstruction('next'))),
  530. tree_ir.DeleteNodeInstruction(_input.create_load())),
  531. value.create_load()))
  532. def analyze_resolve(self, instruction_id):
  533. """Tries to analyze the given 'resolve' instruction."""
  534. var_id, = yield [("RD", [instruction_id, "var"])]
  535. var_name, = yield [("RV", [var_id])]
  536. # To resolve a variable, we'll do something along the
  537. # lines of:
  538. #
  539. # if 'local_var' in locals():
  540. # tmp = local_var
  541. # else:
  542. # _globals, = yield [("RD", [user_root, "globals"])]
  543. # global_var, = yield [("RD", [_globals, var_name])]
  544. #
  545. # if global_var is None:
  546. # raise Exception("Not found as global: %s" % (var_name))
  547. #
  548. # tmp = global_var
  549. name = self.get_local_name(var_id)
  550. if var_name is None:
  551. raise primitive_functions.PrimitiveFinished(
  552. tree_ir.LoadLocalInstruction(name))
  553. user_root = self.retrieve_user_root()
  554. global_var = tree_ir.StoreLocalInstruction(
  555. 'global_var',
  556. tree_ir.ReadDictionaryValueInstruction(
  557. tree_ir.ReadDictionaryValueInstruction(
  558. user_root.create_load(),
  559. tree_ir.LiteralInstruction('globals')),
  560. tree_ir.LiteralInstruction(var_name)))
  561. err_block = tree_ir.SelectInstruction(
  562. tree_ir.BinaryInstruction(
  563. global_var.create_load(),
  564. 'is',
  565. tree_ir.LiteralInstruction(None)),
  566. tree_ir.RaiseInstruction(
  567. tree_ir.CallInstruction(
  568. tree_ir.LoadGlobalInstruction('Exception'),
  569. [tree_ir.LiteralInstruction(
  570. "Not found as global: %s" % var_name)
  571. ])),
  572. tree_ir.EmptyInstruction())
  573. raise primitive_functions.PrimitiveFinished(
  574. tree_ir.SelectInstruction(
  575. tree_ir.LocalExistsInstruction(name),
  576. tree_ir.LoadLocalInstruction(name),
  577. tree_ir.CompoundInstruction(
  578. tree_ir.create_block(
  579. user_root,
  580. global_var,
  581. err_block),
  582. global_var.create_load())))
  583. def analyze_declare(self, instruction_id):
  584. """Tries to analyze the given 'declare' function."""
  585. var_id, = yield [("RD", [instruction_id, "var"])]
  586. self.register_local_var(var_id)
  587. name = self.get_local_name(var_id)
  588. # The following logic declares a local:
  589. #
  590. # if 'local_name' not in locals():
  591. # local_name, = yield [("CN", [])]
  592. raise primitive_functions.PrimitiveFinished(
  593. tree_ir.SelectInstruction(
  594. tree_ir.LocalExistsInstruction(name),
  595. tree_ir.EmptyInstruction(),
  596. tree_ir.StoreLocalInstruction(
  597. name,
  598. tree_ir.CreateNodeInstruction())))
  599. def analyze_global(self, instruction_id):
  600. """Tries to analyze the given 'global' (declaration) instruction."""
  601. var_id, = yield [("RD", [instruction_id, "var"])]
  602. var_name, = yield [("RV", [var_id])]
  603. # To resolve a variable, we'll do something along the
  604. # lines of:
  605. #
  606. # _globals, = yield [("RD", [user_root, "globals"])]
  607. # global_var = yield [("RD", [_globals, var_name])]
  608. #
  609. # if global_var is None:
  610. # global_var, = yield [("CN", [])]
  611. # yield [("CD", [_globals, var_name, global_var])]
  612. #
  613. # tmp = global_var
  614. user_root = self.retrieve_user_root()
  615. _globals = tree_ir.StoreLocalInstruction(
  616. '_globals',
  617. tree_ir.ReadDictionaryValueInstruction(
  618. user_root.create_load(),
  619. tree_ir.LiteralInstruction('globals')))
  620. global_var = tree_ir.StoreLocalInstruction(
  621. 'global_var',
  622. tree_ir.ReadDictionaryValueInstruction(
  623. _globals.create_load(),
  624. tree_ir.LiteralInstruction(var_name)))
  625. raise primitive_functions.PrimitiveFinished(
  626. tree_ir.CompoundInstruction(
  627. tree_ir.create_block(
  628. user_root,
  629. _globals,
  630. global_var,
  631. tree_ir.SelectInstruction(
  632. tree_ir.BinaryInstruction(
  633. global_var.create_load(),
  634. 'is',
  635. tree_ir.LiteralInstruction(None)),
  636. tree_ir.create_block(
  637. global_var.create_store(
  638. tree_ir.CreateNodeInstruction()),
  639. tree_ir.CreateDictionaryEdgeInstruction(
  640. _globals.create_load(),
  641. tree_ir.LiteralInstruction(var_name),
  642. global_var.create_load())),
  643. tree_ir.EmptyInstruction())),
  644. global_var.create_load()))
  645. def analyze_assign(self, instruction_id):
  646. """Tries to analyze the given 'assign' instruction."""
  647. var_id, value_id = yield [("RD", [instruction_id, "var"]),
  648. ("RD", [instruction_id, "value"])]
  649. (var_r, value_r), = yield [("CALL_ARGS", [self.analyze_all, ([var_id, value_id],)])]
  650. # Assignments work like this:
  651. #
  652. # value_link = yield [("RDE", [variable, "value"])]
  653. # _, _ = yield [("CD", [variable, "value", value]),
  654. # ("DE", [value_link])]
  655. variable = tree_ir.StoreLocalInstruction(None, var_r)
  656. value = tree_ir.StoreLocalInstruction(None, value_r)
  657. value_link = tree_ir.StoreLocalInstruction(
  658. 'value_link',
  659. tree_ir.ReadDictionaryEdgeInstruction(
  660. variable.create_load(),
  661. tree_ir.LiteralInstruction('value')))
  662. raise primitive_functions.PrimitiveFinished(
  663. tree_ir.create_block(
  664. variable,
  665. value,
  666. value_link,
  667. tree_ir.CreateDictionaryEdgeInstruction(
  668. variable.create_load(),
  669. tree_ir.LiteralInstruction('value'),
  670. value.create_load()),
  671. tree_ir.DeleteEdgeInstruction(
  672. value_link.create_load())))
  673. def analyze_access(self, instruction_id):
  674. """Tries to analyze the given 'access' instruction."""
  675. var_id, = yield [("RD", [instruction_id, "var"])]
  676. var_r, = yield [("CALL_ARGS", [self.analyze, (var_id,)])]
  677. # Accessing a variable is pretty easy. It really just boils
  678. # down to reading the value corresponding to the 'value' key
  679. # of the variable.
  680. #
  681. # value, = yield [("RD", [returnvalue, "value"])]
  682. raise primitive_functions.PrimitiveFinished(
  683. tree_ir.ReadDictionaryValueInstruction(
  684. var_r,
  685. tree_ir.LiteralInstruction('value')))
  686. def analyze_direct_call(self, callee_id, callee_name, first_parameter_id):
  687. """Tries to analyze a direct 'call' instruction."""
  688. self.register_function_var(callee_id)
  689. body_id, = yield [("RD", [callee_id, "body"])]
  690. # Make this function dependent on the callee.
  691. if body_id in self.jit.compilation_dependencies:
  692. self.jit.compilation_dependencies[body_id].add(self.body_id)
  693. # Figure out if the function might be an intrinsic.
  694. intrinsic = self.jit.get_intrinsic(callee_name)
  695. if intrinsic is None:
  696. compiled_func = self.jit.lookup_compiled_function(callee_name)
  697. if compiled_func is None:
  698. # Compile the callee.
  699. yield [("CALL_ARGS", [self.jit.jit_compile, (self.user_root, body_id, callee_name)])]
  700. else:
  701. self.jit.register_compiled(body_id, compiled_func, callee_name)
  702. # Get the callee's name.
  703. compiled_func_name = self.jit.get_compiled_name(body_id)
  704. # This handles the corner case where a constant node is called, like
  705. # 'call(constant(9), ...)'. In this case, `callee_name` is `None`
  706. # because 'constant(9)' doesn't give us a name. However, we can look up
  707. # the name of the function at a specific node. If that turns out to be
  708. # an intrinsic, then we still want to pick the intrinsic over a call.
  709. intrinsic = self.jit.get_intrinsic(compiled_func_name)
  710. # Analyze the argument dictionary.
  711. named_args, = yield [("CALL_ARGS", [self.analyze_arguments, (first_parameter_id,)])]
  712. if intrinsic is not None:
  713. raise primitive_functions.PrimitiveFinished(
  714. apply_intrinsic(intrinsic, named_args))
  715. else:
  716. raise primitive_functions.PrimitiveFinished(
  717. tree_ir.create_jit_call(
  718. tree_ir.LoadGlobalInstruction(compiled_func_name),
  719. named_args,
  720. tree_ir.LoadLocalInstruction(KWARGS_PARAMETER_NAME)))
  721. def analyze_arguments(self, first_argument_id):
  722. """Analyzes the parameter-to-argument mapping started by the specified first argument
  723. node."""
  724. next_param = first_argument_id
  725. named_args = []
  726. while next_param is not None:
  727. param_name_id, = yield [("RD", [next_param, "name"])]
  728. param_name, = yield [("RV", [param_name_id])]
  729. param_val_id, = yield [("RD", [next_param, "value"])]
  730. param_val, = yield [("CALL_ARGS", [self.analyze, (param_val_id,)])]
  731. named_args.append((param_name, param_val))
  732. next_param, = yield [("RD", [next_param, "next_param"])]
  733. raise primitive_functions.PrimitiveFinished(named_args)
  734. def analyze_indirect_call(self, func_id, first_arg_id):
  735. """Analyzes a call to an unknown function."""
  736. # First off, let's analyze the callee and the argument list.
  737. func_val, = yield [("CALL_ARGS", [self.analyze, (func_id,)])]
  738. named_args, = yield [("CALL_ARGS", [self.analyze_arguments, (first_arg_id,)])]
  739. # Call the __call_function function to run the interpreter, like so:
  740. #
  741. # __call_function(function_id, { first_param_name : first_param_val, ... }, **kwargs)
  742. #
  743. dict_literal = tree_ir.DictionaryLiteralInstruction(
  744. [(tree_ir.LiteralInstruction(key), val) for key, val in named_args])
  745. raise primitive_functions.PrimitiveFinished(
  746. tree_ir.create_jit_call(
  747. tree_ir.LoadGlobalInstruction(CALL_FUNCTION_NAME),
  748. [('function_id', func_val), ('named_arguments', dict_literal)],
  749. tree_ir.LoadLocalInstruction(KWARGS_PARAMETER_NAME)))
  750. def try_analyze_direct_call(self, func_id, first_param_id):
  751. """Tries to analyze the given 'call' instruction as a direct call."""
  752. if not self.jit.direct_calls_allowed:
  753. raise JitCompilationFailedException('Direct calls are not allowed by the JIT.')
  754. # Figure out what the 'func' instruction's type is.
  755. func_instruction_op, = yield [("RV", [func_id])]
  756. if func_instruction_op['value'] == 'access':
  757. # 'access(resolve(var))' instructions are translated to direct calls.
  758. access_value_id, = yield [("RD", [func_id, "var"])]
  759. access_value_op, = yield [("RV", [access_value_id])]
  760. if access_value_op['value'] == 'resolve':
  761. resolved_var_id, = yield [("RD", [access_value_id, "var"])]
  762. resolved_var_name, = yield [("RV", [resolved_var_id])]
  763. # Try to look up the name as a global.
  764. _globals, = yield [("RD", [self.user_root, "globals"])]
  765. global_var, = yield [("RD", [_globals, resolved_var_name])]
  766. global_val, = yield [("RD", [global_var, "value"])]
  767. if global_val is not None:
  768. result, = yield [("CALL_ARGS", [self.analyze_direct_call, (
  769. global_val, resolved_var_name, first_param_id)])]
  770. raise primitive_functions.PrimitiveFinished(result)
  771. elif func_instruction_op['value'] == 'constant':
  772. # 'const(func_id)' instructions are also translated to direct calls.
  773. function_val_id, = yield [("RD", [func_id, "node"])]
  774. result, = yield [("CALL_ARGS", [self.analyze_direct_call, (
  775. function_val_id, None, first_param_id)])]
  776. raise primitive_functions.PrimitiveFinished(result)
  777. raise JitCompilationFailedException(
  778. "Cannot JIT function calls that target an unknown value as direct calls.")
  779. def analyze_call(self, instruction_id):
  780. """Tries to analyze the given 'call' instruction."""
  781. func_id, first_param_id, = yield [("RD", [instruction_id, "func"]),
  782. ("RD", [instruction_id, "params"])]
  783. def handle_exception(exception):
  784. # Looks like we'll have to compile it as an indirect call.
  785. gen = self.analyze_indirect_call(func_id, first_param_id)
  786. result, = yield [("CALL", [gen])]
  787. raise primitive_functions.PrimitiveFinished(result)
  788. # Try to analyze the call as a direct call.
  789. yield [("TRY", [])]
  790. yield [("CATCH", [JitCompilationFailedException, handle_exception])]
  791. result, = yield [("CALL_ARGS", [self.try_analyze_direct_call, (func_id, first_param_id)])]
  792. yield [("END_TRY", [])]
  793. raise primitive_functions.PrimitiveFinished(result)
  794. instruction_analyzers = {
  795. 'if' : analyze_if,
  796. 'while' : analyze_while,
  797. 'return' : analyze_return,
  798. 'constant' : analyze_constant,
  799. 'resolve' : analyze_resolve,
  800. 'declare' : analyze_declare,
  801. 'global' : analyze_global,
  802. 'assign' : analyze_assign,
  803. 'access' : analyze_access,
  804. 'output' : analyze_output,
  805. 'input' : analyze_input,
  806. 'call' : analyze_call
  807. }