jit.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  1. import keyword
  2. from collections import defaultdict
  3. import modelverse_kernel.primitives as primitive_functions
  4. import modelverse_jit.bytecode_parser as bytecode_parser
  5. import modelverse_jit.bytecode_to_tree as bytecode_to_tree
  6. import modelverse_jit.bytecode_to_cfg as bytecode_to_cfg
  7. import modelverse_jit.cfg_optimization as cfg_optimization
  8. import modelverse_jit.cfg_to_tree as cfg_to_tree
  9. import modelverse_jit.cfg_ir as cfg_ir
  10. import modelverse_jit.tree_ir as tree_ir
  11. import modelverse_jit.runtime as jit_runtime
  12. # Import JitCompilationFailedException because it used to be defined
  13. # in this module.
  14. JitCompilationFailedException = jit_runtime.JitCompilationFailedException
  15. def map_and_simplify_generator(function, instruction):
  16. """Applies the given mapping function to every instruction in the tree
  17. that has the given instruction as root, and simplifies it on-the-fly.
  18. This is at least as powerful as first mapping and then simplifying, as
  19. maps and simplifications are interspersed.
  20. This function assumes that function creates a generator that returns by
  21. raising a primitive_functions.PrimitiveFinished."""
  22. # First handle the children by mapping on them and then simplifying them.
  23. new_children = []
  24. for inst in instruction.get_children():
  25. new_inst, = yield [("CALL_ARGS", [map_and_simplify_generator, (function, inst)])]
  26. new_children.append(new_inst)
  27. # Then apply the function to the top-level node.
  28. transformed, = yield [("CALL_ARGS", [function, (instruction.create(new_children),)])]
  29. # Finally, simplify the transformed top-level node.
  30. raise primitive_functions.PrimitiveFinished(transformed.simplify_node())
  31. def expand_constant_read(instruction):
  32. """Tries to replace a read of a constant node by a literal."""
  33. if isinstance(instruction, tree_ir.ReadValueInstruction) and \
  34. isinstance(instruction.node_id, tree_ir.LiteralInstruction):
  35. val, = yield [("RV", [instruction.node_id.literal])]
  36. raise primitive_functions.PrimitiveFinished(tree_ir.LiteralInstruction(val))
  37. else:
  38. raise primitive_functions.PrimitiveFinished(instruction)
  39. def optimize_tree_ir(instruction):
  40. """Optimizes an IR tree."""
  41. return map_and_simplify_generator(expand_constant_read, instruction)
  42. def create_bare_function(function_name, parameter_list, function_body):
  43. """Creates a function definition from the given function name, parameter list
  44. and function body. No prolog is included."""
  45. # Wrap the IR in a function definition, give it a unique name.
  46. return tree_ir.DefineFunctionInstruction(
  47. function_name,
  48. parameter_list + ['**' + jit_runtime.KWARGS_PARAMETER_NAME],
  49. function_body)
  50. def create_function(
  51. function_name, parameter_list, param_dict,
  52. body_param_dict, function_body, source_map_name=None):
  53. """Creates a function from the given function name, parameter list,
  54. variable-to-parameter name map, variable-to-local name map and
  55. function body. An optional source map can be included, too."""
  56. # Write a prologue and prepend it to the generated function body.
  57. prolog_statements = []
  58. # If the source map is not None, then we should generate a "DEBUG_INFO"
  59. # request.
  60. if source_map_name is not None:
  61. prolog_statements.append(
  62. tree_ir.RegisterDebugInfoInstruction(
  63. tree_ir.LiteralInstruction(function_name),
  64. tree_ir.LoadGlobalInstruction(source_map_name),
  65. tree_ir.LiteralInstruction(jit_runtime.BASELINE_JIT_ORIGIN_NAME)))
  66. # Create a LOCALS_NODE_NAME node, and connect it to the user root.
  67. prolog_statements.append(
  68. tree_ir.create_new_local_node(
  69. jit_runtime.LOCALS_NODE_NAME,
  70. tree_ir.LoadIndexInstruction(
  71. tree_ir.LoadLocalInstruction(jit_runtime.KWARGS_PARAMETER_NAME),
  72. tree_ir.LiteralInstruction('task_root')),
  73. jit_runtime.LOCALS_EDGE_NAME))
  74. for (key, val) in param_dict.items():
  75. arg_ptr = tree_ir.create_new_local_node(
  76. body_param_dict[key],
  77. tree_ir.LoadLocalInstruction(jit_runtime.LOCALS_NODE_NAME))
  78. prolog_statements.append(arg_ptr)
  79. prolog_statements.append(
  80. tree_ir.CreateDictionaryEdgeInstruction(
  81. tree_ir.LoadLocalInstruction(body_param_dict[key]),
  82. tree_ir.LiteralInstruction('value'),
  83. tree_ir.LoadLocalInstruction(val)))
  84. constructed_body = tree_ir.create_block(
  85. *(prolog_statements + [function_body]))
  86. # Shield temporaries from the GC.
  87. constructed_body = tree_ir.protect_temporaries_from_gc(
  88. constructed_body, tree_ir.LoadLocalInstruction(jit_runtime.LOCALS_NODE_NAME))
  89. return create_bare_function(function_name, parameter_list, constructed_body)
  90. def print_value(val):
  91. """A thin wrapper around 'print'."""
  92. print(val)
  93. class ModelverseJit(object):
  94. """A high-level interface to the modelverse JIT compiler."""
  95. def __init__(self, max_instructions=None, compiled_function_lookup=None):
  96. self.todo_entry_points = set()
  97. self.no_jit_entry_points = set()
  98. self.jitted_parameters = {}
  99. self.jit_globals = {
  100. 'PrimitiveFinished' : primitive_functions.PrimitiveFinished,
  101. jit_runtime.CALL_FUNCTION_NAME : jit_runtime.call_function,
  102. jit_runtime.GET_INPUT_FUNCTION_NAME : jit_runtime.get_input,
  103. jit_runtime.JIT_THUNK_CONSTANT_FUNCTION_NAME : self.jit_thunk_constant_function,
  104. jit_runtime.JIT_THUNK_GLOBAL_FUNCTION_NAME : self.jit_thunk_global,
  105. jit_runtime.JIT_REJIT_FUNCTION_NAME : self.jit_rejit,
  106. jit_runtime.JIT_COMPILE_FUNCTION_BODY_FAST_FUNCTION_NAME : compile_function_body_fast,
  107. jit_runtime.UNREACHABLE_FUNCTION_NAME : jit_runtime.unreachable
  108. }
  109. # jitted_entry_points maps body ids to values in jit_globals.
  110. self.jitted_entry_points = {}
  111. # global_functions maps global value names to body ids.
  112. self.global_functions = {}
  113. # global_functions_inv maps body ids to global value names.
  114. self.global_functions_inv = {}
  115. # bytecode_graphs maps body ids to their parsed bytecode graphs.
  116. self.bytecode_graphs = {}
  117. # jitted_function_aliases maps body ids to known aliases.
  118. self.jitted_function_aliases = defaultdict(set)
  119. self.jit_count = 0
  120. self.max_instructions = max_instructions
  121. self.compiled_function_lookup = compiled_function_lookup
  122. # jit_intrinsics is a function name -> intrinsic map.
  123. self.jit_intrinsics = {}
  124. # cfg_jit_intrinsics is a function name -> intrinsic map.
  125. self.cfg_jit_intrinsics = {}
  126. self.compilation_dependencies = {}
  127. self.jit_enabled = True
  128. self.direct_calls_allowed = True
  129. self.tracing_enabled = False
  130. self.source_maps_enabled = True
  131. self.input_function_enabled = False
  132. self.nop_insertion_enabled = True
  133. self.thunks_enabled = True
  134. self.jit_success_log_function = None
  135. self.jit_code_log_function = None
  136. self.compile_function_body = compile_function_body_baseline
  137. def set_jit_enabled(self, is_enabled=True):
  138. """Enables or disables the JIT."""
  139. self.jit_enabled = is_enabled
  140. def allow_direct_calls(self, is_allowed=True):
  141. """Allows or disallows direct calls from jitted to jitted code."""
  142. self.direct_calls_allowed = is_allowed
  143. def use_input_function(self, is_enabled=True):
  144. """Configures the JIT to compile 'input' instructions as function calls."""
  145. self.input_function_enabled = is_enabled
  146. def enable_tracing(self, is_enabled=True):
  147. """Enables or disables tracing for jitted code."""
  148. self.tracing_enabled = is_enabled
  149. def enable_source_maps(self, is_enabled=True):
  150. """Enables or disables the creation of source maps for jitted code. Source maps
  151. convert lines in the generated code to debug information.
  152. Source maps are enabled by default."""
  153. self.source_maps_enabled = is_enabled
  154. def enable_nop_insertion(self, is_enabled=True):
  155. """Enables or disables nop insertion for jitted code. If enabled, the JIT will
  156. insert nops at loop back-edges. Inserting nops sacrifices performance to
  157. keep the jitted code from blocking the thread of execution and consuming
  158. all resources; nops give the Modelverse server an opportunity to interrupt
  159. the currently running code."""
  160. self.nop_insertion_enabled = is_enabled
  161. def enable_thunks(self, is_enabled=True):
  162. """Enables or disables thunks for jitted code. Thunks delay the compilation of
  163. functions until they are actually used. Thunks generally reduce start-up
  164. time.
  165. Thunks are enabled by default."""
  166. self.thunks_enabled = is_enabled
  167. def set_jit_success_log(self, log_function=print_value):
  168. """Configures this JIT instance with a function that prints output to a log.
  169. Success and failure messages for specific functions are then sent to said log."""
  170. self.jit_success_log_function = log_function
  171. def set_jit_code_log(self, log_function=print_value):
  172. """Configures this JIT instance with a function that prints output to a log.
  173. Function definitions of jitted functions are then sent to said log."""
  174. self.jit_code_log_function = log_function
  175. def set_function_body_compiler(self, compile_function_body):
  176. """Sets the function that the JIT uses to compile function bodies."""
  177. self.compile_function_body = compile_function_body
  178. def mark_entry_point(self, body_id):
  179. """Marks the node with the given identifier as a function entry point."""
  180. if body_id not in self.no_jit_entry_points and body_id not in self.jitted_entry_points:
  181. self.todo_entry_points.add(body_id)
  182. def is_entry_point(self, body_id):
  183. """Tells if the node with the given identifier is a function entry point."""
  184. return body_id in self.todo_entry_points or \
  185. body_id in self.no_jit_entry_points or \
  186. body_id in self.jitted_entry_points
  187. def is_jittable_entry_point(self, body_id):
  188. """Tells if the node with the given identifier is a function entry point that
  189. has not been marked as non-jittable. This only returns `True` if the JIT
  190. is enabled and the function entry point has been marked jittable, or if
  191. the function has already been compiled."""
  192. return ((self.jit_enabled and body_id in self.todo_entry_points) or
  193. self.has_compiled(body_id))
  194. def has_compiled(self, body_id):
  195. """Tests if the function belonging to the given body node has been compiled yet."""
  196. return body_id in self.jitted_entry_points
  197. def get_compiled_name(self, body_id):
  198. """Gets the name of the compiled version of the given body node in the JIT
  199. global state."""
  200. if body_id in self.jitted_entry_points:
  201. return self.jitted_entry_points[body_id]
  202. else:
  203. return None
  204. def mark_no_jit(self, body_id):
  205. """Informs the JIT that the node with the given identifier is a function entry
  206. point that must never be jitted."""
  207. self.no_jit_entry_points.add(body_id)
  208. if body_id in self.todo_entry_points:
  209. self.todo_entry_points.remove(body_id)
  210. def generate_name(self, infix, suggested_name=None):
  211. """Generates a new name or picks the suggested name if it is still
  212. available."""
  213. if suggested_name is not None \
  214. and suggested_name not in self.jit_globals \
  215. and not keyword.iskeyword(suggested_name):
  216. self.jit_count += 1
  217. return suggested_name
  218. else:
  219. function_name = 'jit_%s%d' % (infix, self.jit_count)
  220. self.jit_count += 1
  221. return function_name
  222. def generate_function_name(self, body_id, suggested_name=None):
  223. """Generates a new function name or picks the suggested name if it is still
  224. available."""
  225. if suggested_name is None:
  226. suggested_name = self.get_global_name(body_id)
  227. return self.generate_name('func', suggested_name)
  228. def register_global(self, body_id, global_name):
  229. """Associates the given body id with the given global name."""
  230. self.global_functions[global_name] = body_id
  231. self.global_functions_inv[body_id] = global_name
  232. def get_global_name(self, body_id):
  233. """Gets the name of the global function with the given body id.
  234. Returns None if no known global exists with the given id."""
  235. if body_id in self.global_functions_inv:
  236. return self.global_functions_inv[body_id]
  237. else:
  238. return None
  239. def get_global_body_id(self, global_name):
  240. """Gets the body id of the global function with the given name.
  241. Returns None if no known global exists with the given name."""
  242. if global_name in self.global_functions:
  243. return self.global_functions[global_name]
  244. else:
  245. return None
  246. def register_compiled(self, body_id, compiled_function, function_name=None):
  247. """Registers a compiled entry point with the JIT."""
  248. # Get the function's name.
  249. actual_function_name = self.generate_function_name(body_id, function_name)
  250. # Map the body id to the given parameter list.
  251. self.jitted_entry_points[body_id] = actual_function_name
  252. self.jit_globals[actual_function_name] = compiled_function
  253. if function_name is not None:
  254. self.register_global(body_id, function_name)
  255. if body_id in self.todo_entry_points:
  256. self.todo_entry_points.remove(body_id)
  257. def import_value(self, value, suggested_name=None):
  258. """Imports the given value into the JIT's global scope, with the given suggested name.
  259. The actual name of the value (within the JIT's global scope) is returned."""
  260. actual_name = self.generate_name('import', suggested_name)
  261. self.jit_globals[actual_name] = value
  262. return actual_name
  263. def __lookup_compiled_body_impl(self, body_id):
  264. """Looks up a compiled function by body id. Returns a matching function,
  265. or None if no function was found."""
  266. if body_id is not None and body_id in self.jitted_entry_points:
  267. return self.jit_globals[self.jitted_entry_points[body_id]]
  268. else:
  269. return None
  270. def __lookup_external_body_impl(self, global_name, body_id):
  271. """Looks up an external function by global name. Returns a matching function,
  272. or None if no function was found."""
  273. if global_name is not None and self.compiled_function_lookup is not None:
  274. result = self.compiled_function_lookup(global_name)
  275. if result is not None and body_id is not None:
  276. self.register_compiled(body_id, result, global_name)
  277. return result
  278. else:
  279. return None
  280. def lookup_compiled_body(self, body_id):
  281. """Looks up a compiled function by body id. Returns a matching function,
  282. or None if no function was found."""
  283. result = self.__lookup_compiled_body_impl(body_id)
  284. if result is not None:
  285. return result
  286. else:
  287. global_name = self.get_global_name(body_id)
  288. return self.__lookup_external_body_impl(global_name, body_id)
  289. def lookup_compiled_function(self, global_name):
  290. """Looks up a compiled function by global name. Returns a matching function,
  291. or None if no function was found."""
  292. body_id = self.get_global_body_id(global_name)
  293. result = self.__lookup_compiled_body_impl(body_id)
  294. if result is not None:
  295. return result
  296. else:
  297. return self.__lookup_external_body_impl(global_name, body_id)
  298. def get_intrinsic(self, name):
  299. """Tries to find an intrinsic version of the function with the
  300. given name."""
  301. if name in self.jit_intrinsics:
  302. return self.jit_intrinsics[name]
  303. else:
  304. return None
  305. def get_cfg_intrinsic(self, name):
  306. """Tries to find an intrinsic version of the function with the
  307. given name that is specialized for CFGs."""
  308. if name in self.cfg_jit_intrinsics:
  309. return self.cfg_jit_intrinsics[name]
  310. else:
  311. return None
  312. def register_intrinsic(self, name, intrinsic_function, cfg_intrinsic_function=None):
  313. """Registers the given intrisic with the JIT. This will make the JIT replace calls to
  314. the function with the given entry point by an application of the specified function."""
  315. self.jit_intrinsics[name] = intrinsic_function
  316. if cfg_intrinsic_function is not None:
  317. self.register_cfg_intrinsic(name, cfg_intrinsic_function)
  318. def register_cfg_intrinsic(self, name, cfg_intrinsic_function):
  319. """Registers the given intrisic with the JIT. This will make the JIT replace calls to
  320. the function with the given entry point by an application of the specified function."""
  321. self.cfg_jit_intrinsics[name] = cfg_intrinsic_function
  322. def register_binary_intrinsic(self, name, operator):
  323. """Registers an intrinsic with the JIT that represents the given binary operation."""
  324. self.register_intrinsic(
  325. name,
  326. lambda a, b:
  327. tree_ir.CreateNodeWithValueInstruction(
  328. tree_ir.BinaryInstruction(
  329. tree_ir.ReadValueInstruction(a),
  330. operator,
  331. tree_ir.ReadValueInstruction(b))),
  332. lambda original_def, a, b:
  333. original_def.redefine(
  334. cfg_ir.CreateNode(
  335. original_def.insert_before(
  336. cfg_ir.Binary(
  337. original_def.insert_before(cfg_ir.Read(a)),
  338. operator,
  339. original_def.insert_before(cfg_ir.Read(b)))))))
  340. def register_unary_intrinsic(self, name, operator):
  341. """Registers an intrinsic with the JIT that represents the given unary operation."""
  342. self.register_intrinsic(
  343. name,
  344. lambda a:
  345. tree_ir.CreateNodeWithValueInstruction(
  346. tree_ir.UnaryInstruction(
  347. operator,
  348. tree_ir.ReadValueInstruction(a))),
  349. lambda original_def, a:
  350. original_def.redefine(
  351. cfg_ir.CreateNode(
  352. original_def.insert_before(
  353. cfg_ir.Unary(
  354. operator,
  355. original_def.insert_before(cfg_ir.Read(a)))))))
  356. def register_cast_intrinsic(self, name, target_type):
  357. """Registers an intrinsic with the JIT that represents a unary conversion operator."""
  358. self.register_intrinsic(
  359. name,
  360. lambda a:
  361. tree_ir.CreateNodeWithValueInstruction(
  362. tree_ir.CallInstruction(
  363. tree_ir.LoadGlobalInstruction(target_type.__name__),
  364. [tree_ir.ReadValueInstruction(a)])),
  365. lambda original_def, a:
  366. original_def.redefine(
  367. cfg_ir.CreateNode(
  368. original_def.insert_before(
  369. cfg_ir.create_pure_simple_call(
  370. target_type.__name__,
  371. original_def.insert_before(cfg_ir.Read(a)))))))
  372. def jit_signature(self, body_id):
  373. """Acquires the signature for the given body id node, which consists of the
  374. parameter variables, parameter name and a flag that tells if the given function
  375. is mutable."""
  376. if body_id not in self.jitted_parameters:
  377. signature_id, = yield [("RRD", [body_id, jit_runtime.FUNCTION_BODY_KEY])]
  378. signature_id = signature_id[0]
  379. param_set_id, is_mutable = yield [
  380. ("RD", [signature_id, "params"]),
  381. ("RD", [signature_id, jit_runtime.MUTABLE_FUNCTION_KEY])]
  382. if param_set_id is None:
  383. self.jitted_parameters[body_id] = ([], [], is_mutable)
  384. else:
  385. param_name_ids, = yield [("RDK", [param_set_id])]
  386. param_names = yield [("RV", [n]) for n in param_name_ids]
  387. param_vars = yield [("RD", [param_set_id, k]) for k in param_names]
  388. self.jitted_parameters[body_id] = (param_vars, param_names, is_mutable)
  389. raise primitive_functions.PrimitiveFinished(self.jitted_parameters[body_id])
  390. def jit_parse_bytecode(self, body_id):
  391. """Parses the given function body as a bytecode graph."""
  392. if body_id in self.bytecode_graphs:
  393. raise primitive_functions.PrimitiveFinished(self.bytecode_graphs[body_id])
  394. parser = bytecode_parser.BytecodeParser()
  395. result, = yield [("CALL_ARGS", [parser.parse_instruction, (body_id,)])]
  396. self.bytecode_graphs[body_id] = result
  397. raise primitive_functions.PrimitiveFinished(result)
  398. def check_jittable(self, body_id, suggested_name=None):
  399. """Checks if the function with the given body id is obviously non-jittable. If it's
  400. non-jittable, then a `JitCompilationFailedException` exception is thrown."""
  401. if body_id is None:
  402. raise ValueError('body_id cannot be None')
  403. elif body_id in self.no_jit_entry_points:
  404. # We're not allowed to jit this function or have tried and failed before.
  405. raise JitCompilationFailedException(
  406. 'Cannot jit function %s at %d because it is marked non-jittable.' % (
  407. '' if suggested_name is None else "'" + suggested_name + "'",
  408. body_id))
  409. elif not self.jit_enabled:
  410. # We're not allowed to jit anything.
  411. raise JitCompilationFailedException(
  412. 'Cannot jit function %s at %d because the JIT has been disabled.' % (
  413. '' if suggested_name is None else "'" + suggested_name + "'",
  414. body_id))
  415. def jit_recompile(self, task_root, body_id, function_name, compile_function_body=None):
  416. """Replaces the function with the given name by compiling the bytecode at the given
  417. body id."""
  418. if compile_function_body is None:
  419. compile_function_body = self.compile_function_body
  420. self.check_jittable(body_id, function_name)
  421. # Generate a name for the function we're about to analyze, and pretend that
  422. # it already exists. (we need to do this for recursive functions)
  423. self.jitted_entry_points[body_id] = function_name
  424. self.jit_globals[function_name] = None
  425. (_, _, is_mutable), = yield [
  426. ("CALL_ARGS", [self.jit_signature, (body_id,)])]
  427. dependencies = set([body_id])
  428. self.compilation_dependencies[body_id] = dependencies
  429. def handle_jit_exception(exception):
  430. # If analysis fails, then a JitCompilationFailedException will be thrown.
  431. del self.compilation_dependencies[body_id]
  432. for dep in dependencies:
  433. self.mark_no_jit(dep)
  434. if dep in self.jitted_entry_points:
  435. del self.jitted_entry_points[dep]
  436. failure_message = "%s (function '%s' at %d)" % (
  437. exception.message, function_name, body_id)
  438. if self.jit_success_log_function is not None:
  439. self.jit_success_log_function('JIT compilation failed: %s' % failure_message)
  440. raise JitCompilationFailedException(failure_message)
  441. # Try to analyze the function's body.
  442. yield [("TRY", [])]
  443. yield [("CATCH", [JitCompilationFailedException, handle_jit_exception])]
  444. if is_mutable:
  445. # We can't just JIT mutable functions. That'd be dangerous.
  446. raise JitCompilationFailedException(
  447. "Function was marked '%s'." % jit_runtime.MUTABLE_FUNCTION_KEY)
  448. constructed_function, = yield [
  449. ("CALL_ARGS", [compile_function_body, (self, function_name, body_id, task_root)])]
  450. yield [("END_TRY", [])]
  451. del self.compilation_dependencies[body_id]
  452. # Convert the function definition to Python code, and compile it.
  453. compiled_function = self.jit_define_function(function_name, constructed_function)
  454. if self.jit_success_log_function is not None:
  455. self.jit_success_log_function(
  456. "JIT compilation successful: (function '%s' at %d)" % (function_name, body_id))
  457. raise primitive_functions.PrimitiveFinished(compiled_function)
  458. def get_source_map_name(self, function_name):
  459. """Gets the name of the given jitted function's source map. None is returned if source maps
  460. are disabled."""
  461. if self.source_maps_enabled:
  462. return function_name + "_source_map"
  463. else:
  464. return None
  465. def get_can_rejit_name(self, function_name):
  466. """Gets the name of the given jitted function's can-rejit flag."""
  467. return function_name + "_can_rejit"
  468. def jit_define_function(self, function_name, function_def):
  469. """Converts the given tree-IR function definition to Python code, defines it,
  470. and extracts the resulting function."""
  471. # The comment below makes pylint shut up about our (hopefully benign) use of exec here.
  472. # pylint: disable=I0011,W0122
  473. if self.jit_code_log_function is not None:
  474. self.jit_code_log_function(function_def)
  475. # Convert the function definition to Python code, and compile it.
  476. code_generator = tree_ir.PythonGenerator()
  477. function_def.generate_python_def(code_generator)
  478. source_map_name = self.get_source_map_name(function_name)
  479. if source_map_name is not None:
  480. self.jit_globals[source_map_name] = code_generator.source_map_builder.source_map
  481. exec(str(code_generator), self.jit_globals)
  482. # Extract the compiled function from the JIT global state.
  483. return self.jit_globals[function_name]
  484. def jit_delete_function(self, function_name):
  485. """Deletes the function with the given function name."""
  486. del self.jit_globals[function_name]
  487. def jit_compile(self, task_root, body_id, suggested_name=None):
  488. """Tries to jit the function defined by the given entry point id and parameter list."""
  489. if body_id is None:
  490. raise ValueError('body_id cannot be None')
  491. elif body_id in self.jitted_entry_points:
  492. # We have already compiled this function.
  493. raise primitive_functions.PrimitiveFinished(
  494. self.jit_globals[self.jitted_entry_points[body_id]])
  495. # Generate a name for the function we're about to analyze, and 're-compile'
  496. # it for the first time.
  497. function_name = self.generate_function_name(body_id, suggested_name)
  498. yield [("TAIL_CALL_ARGS", [self.jit_recompile, (task_root, body_id, function_name)])]
  499. def jit_rejit(self, task_root, body_id, function_name, compile_function_body=None):
  500. """Re-compiles the given function. If compilation fails, then the can-rejit
  501. flag is set to false."""
  502. old_jitted_func = self.jitted_entry_points[body_id]
  503. def __handle_jit_failed(_):
  504. self.jit_globals[self.get_can_rejit_name(function_name)] = False
  505. self.jitted_entry_points[body_id] = old_jitted_func
  506. self.no_jit_entry_points.remove(body_id)
  507. raise primitive_functions.PrimitiveFinished(None)
  508. yield [("TRY", [])]
  509. yield [("CATCH", [jit_runtime.JitCompilationFailedException, __handle_jit_failed])]
  510. jitted_function, = yield [
  511. ("CALL_ARGS",
  512. [self.jit_recompile, (task_root, body_id, function_name, compile_function_body)])]
  513. yield [("END_TRY", [])]
  514. # Update all aliases.
  515. for function_alias in self.jitted_function_aliases[body_id]:
  516. self.jit_globals[function_alias] = jitted_function
  517. def jit_thunk(self, get_function_body, global_name=None):
  518. """Creates a thunk from the given IR tree that computes the function's body id.
  519. This thunk is a function that will invoke the function whose body id is retrieved.
  520. The thunk's name in the JIT's global context is returned."""
  521. # The general idea is to first create a function that looks a bit like this:
  522. #
  523. # def jit_get_function_body(**kwargs):
  524. # raise primitive_functions.PrimitiveFinished(<get_function_body>)
  525. #
  526. get_function_body_name = self.generate_name('get_function_body')
  527. get_function_body_func_def = create_function(
  528. get_function_body_name, [], {}, {}, tree_ir.ReturnInstruction(get_function_body))
  529. get_function_body_func = self.jit_define_function(
  530. get_function_body_name, get_function_body_func_def)
  531. # Next, we want to create a thunk that invokes said function, and then replaces itself.
  532. thunk_name = self.generate_name('thunk', global_name)
  533. def __jit_thunk(**kwargs):
  534. # Compute the body id, and delete the function that computes the body id; we won't
  535. # be needing it anymore after this call.
  536. body_id, = yield [("CALL_KWARGS", [get_function_body_func, kwargs])]
  537. self.jit_delete_function(get_function_body_name)
  538. # Try to associate the global name with the body id, if that's at all possible.
  539. if global_name is not None:
  540. self.register_global(body_id, global_name)
  541. compiled_function = self.lookup_compiled_body(body_id)
  542. if compiled_function is not None:
  543. # Replace this thunk by the compiled function.
  544. self.jit_globals[thunk_name] = compiled_function
  545. self.jitted_function_aliases[body_id].add(thunk_name)
  546. else:
  547. def __handle_jit_exception(_):
  548. # Replace this thunk by a different thunk: one that calls the interpreter
  549. # directly, without checking if the function is jittable.
  550. (_, parameter_names, _), = yield [
  551. ("CALL_ARGS", [self.jit_signature, (body_id,)])]
  552. def __interpreter_thunk(**new_kwargs):
  553. named_arg_dict = {name : new_kwargs[name] for name in parameter_names}
  554. return jit_runtime.interpret_function_body(
  555. body_id, named_arg_dict, **new_kwargs)
  556. self.jit_globals[thunk_name] = __interpreter_thunk
  557. yield [("TRY", [])]
  558. yield [("CATCH", [JitCompilationFailedException, __handle_jit_exception])]
  559. compiled_function, = yield [
  560. ("CALL_ARGS",
  561. [self.jit_recompile, (kwargs['task_root'], body_id, thunk_name)])]
  562. yield [("END_TRY", [])]
  563. # Call the compiled function.
  564. yield [("TAIL_CALL_KWARGS", [compiled_function, kwargs])]
  565. self.jit_globals[thunk_name] = __jit_thunk
  566. return thunk_name
  567. def jit_thunk_constant_body(self, body_id):
  568. """Creates a thunk from the given body id.
  569. This thunk is a function that will invoke the function whose body id is given.
  570. The thunk's name in the JIT's global context is returned."""
  571. self.lookup_compiled_body(body_id)
  572. compiled_name = self.get_compiled_name(body_id)
  573. if compiled_name is not None:
  574. # We might have compiled the function with the given body id already. In that case,
  575. # we need not bother with constructing the thunk; we can return the compiled function
  576. # right away.
  577. return compiled_name
  578. else:
  579. # Looks like we'll just have to build that thunk after all.
  580. return self.jit_thunk(tree_ir.LiteralInstruction(body_id))
  581. def jit_thunk_constant_function(self, body_id):
  582. """Creates a thunk from the given function id.
  583. This thunk is a function that will invoke the function whose function id is given.
  584. The thunk's name in the JIT's global context is returned."""
  585. return self.jit_thunk(
  586. tree_ir.ReadDictionaryValueInstruction(
  587. tree_ir.LiteralInstruction(body_id),
  588. tree_ir.LiteralInstruction(jit_runtime.FUNCTION_BODY_KEY)))
  589. def jit_thunk_global(self, global_name):
  590. """Creates a thunk from given global name.
  591. This thunk is a function that will invoke the function whose body id is given.
  592. The thunk's name in the JIT's global context is returned."""
  593. # We might have compiled the function with the given name already. In that case,
  594. # we need not bother with constructing the thunk; we can return the compiled function
  595. # right away.
  596. body_id = self.get_global_body_id(global_name)
  597. if body_id is not None:
  598. self.lookup_compiled_body(body_id)
  599. compiled_name = self.get_compiled_name(body_id)
  600. if compiled_name is not None:
  601. return compiled_name
  602. # Looks like we'll just have to build that thunk after all.
  603. # We want to look up the global function like so
  604. #
  605. # _globals, = yield [("RD", [kwargs['task_root'], "globals"])]
  606. # global_var, = yield [("RD", [_globals, global_name])]
  607. # function_id, = yield [("RD", [global_var, "value"])]
  608. # body_id, = yield [("RD", [function_id, jit_runtime.FUNCTION_BODY_KEY])]
  609. #
  610. return self.jit_thunk(
  611. tree_ir.ReadDictionaryValueInstruction(
  612. tree_ir.ReadDictionaryValueInstruction(
  613. tree_ir.ReadDictionaryValueInstruction(
  614. tree_ir.ReadDictionaryValueInstruction(
  615. tree_ir.LoadIndexInstruction(
  616. tree_ir.LoadLocalInstruction(jit_runtime.KWARGS_PARAMETER_NAME),
  617. tree_ir.LiteralInstruction('task_root')),
  618. tree_ir.LiteralInstruction('globals')),
  619. tree_ir.LiteralInstruction(global_name)),
  620. tree_ir.LiteralInstruction('value')),
  621. tree_ir.LiteralInstruction(jit_runtime.FUNCTION_BODY_KEY)),
  622. global_name)
  623. def compile_function_body_baseline(jit, function_name, body_id, task_root, header=None):
  624. """Have the baseline JIT compile the function with the given name and body id."""
  625. (parameter_ids, parameter_list, _), = yield [
  626. ("CALL_ARGS", [jit.jit_signature, (body_id,)])]
  627. param_dict = dict(zip(parameter_ids, parameter_list))
  628. body_param_dict = dict(zip(parameter_ids, [p + "_ptr" for p in parameter_list]))
  629. body_bytecode, = yield [("CALL_ARGS", [jit.jit_parse_bytecode, (body_id,)])]
  630. state = bytecode_to_tree.AnalysisState(
  631. jit, body_id, task_root, body_param_dict,
  632. jit.max_instructions)
  633. constructed_body, = yield [("CALL_ARGS", [state.analyze, (body_bytecode,)])]
  634. if header is not None:
  635. constructed_body = tree_ir.create_block(header, constructed_body)
  636. # Optimize the function's body.
  637. constructed_body, = yield [("CALL_ARGS", [optimize_tree_ir, (constructed_body,)])]
  638. # Wrap the tree IR in a function definition.
  639. raise primitive_functions.PrimitiveFinished(
  640. create_function(
  641. function_name, parameter_list, param_dict,
  642. body_param_dict, constructed_body, jit.get_source_map_name(function_name)))
  643. def compile_function_body_fast(jit, function_name, body_id, _):
  644. """Have the fast JIT compile the function with the given name and body id."""
  645. (parameter_ids, parameter_list, _), = yield [
  646. ("CALL_ARGS", [jit.jit_signature, (body_id,)])]
  647. param_dict = dict(zip(parameter_ids, parameter_list))
  648. body_bytecode, = yield [("CALL_ARGS", [jit.jit_parse_bytecode, (body_id,)])]
  649. bytecode_analyzer = bytecode_to_cfg.AnalysisState(jit, function_name, param_dict)
  650. bytecode_analyzer.analyze(body_bytecode)
  651. entry_point, = yield [
  652. ("CALL_ARGS", [cfg_optimization.optimize, (bytecode_analyzer.entry_point, jit)])]
  653. if jit.jit_code_log_function is not None:
  654. jit.jit_code_log_function(
  655. "CFG for function '%s' at '%d':\n%s" % (
  656. function_name, body_id,
  657. '\n'.join(map(str, cfg_ir.get_all_reachable_blocks(entry_point)))))
  658. # Lower the CFG to tree IR.
  659. constructed_body = cfg_to_tree.lower_flow_graph(entry_point, jit)
  660. # Optimize the tree that was generated.
  661. constructed_body, = yield [("CALL_ARGS", [optimize_tree_ir, (constructed_body,)])]
  662. raise primitive_functions.PrimitiveFinished(
  663. create_bare_function(
  664. function_name, parameter_list,
  665. constructed_body))
  666. def favor_large_functions(body_bytecode):
  667. """Computes the initial temperature of a function based on the size of
  668. its body bytecode. Larger functions are favored and the temperature
  669. is incremented by one on every call."""
  670. # The rationale for this heuristic is that it does some damage control:
  671. # we can afford to decide (wrongly) not to fast-jit a small function,
  672. # because we can just fast-jit that function later on. Since the function
  673. # is so small, it will (hopefully) not be able to deal us a heavy blow in
  674. # terms of performance.
  675. #
  676. # If we decide not to fast-jit a large function however, we might end up
  677. # in a situation where said function runs for a long time before we
  678. # realize that we really should have jitted it. And that's exactly what
  679. # this heuristic tries to avoid.
  680. return (
  681. len(body_bytecode.get_reachable()),
  682. lambda old_value:
  683. tree_ir.BinaryInstruction(
  684. old_value,
  685. '+',
  686. tree_ir.LiteralInstruction(1)))
  687. def favor_small_functions(body_bytecode):
  688. """Computes the initial temperature of a function based on the size of
  689. its body bytecode. Smaller functions are favored and the temperature
  690. is incremented by one on every call."""
  691. # The rationale for this heuristic is that small functions are easy to
  692. # fast-jit, because they probably won't trigger the non-linear complexity
  693. # of fast-jit's algorithms. So it might be cheaper to fast-jit small
  694. # functions and get a performance boost from that than to fast-jit large
  695. # functions.
  696. return (
  697. ADAPTIVE_FAST_JIT_TEMPERATURE_THRESHOLD - len(body_bytecode.get_reachable()),
  698. lambda old_value:
  699. tree_ir.BinaryInstruction(
  700. old_value,
  701. '+',
  702. tree_ir.LiteralInstruction(1)))
  703. ADAPTIVE_FAST_JIT_TEMPERATURE_THRESHOLD = 200
  704. """The threshold temperature at which fast-jit will be used."""
  705. def compile_function_body_adaptive(
  706. jit, function_name, body_id, task_root,
  707. temperature_heuristic=favor_large_functions):
  708. """Compile the function with the given name and body id. An execution engine is picked
  709. automatically, and the function may be compiled again at a later time."""
  710. # The general idea behind this compilation technique is to first use the baseline JIT
  711. # to compile a function, and then switch to the fast JIT when we determine that doing
  712. # so would be a good idea. We maintain a 'temperature' counter, which has an initial value
  713. # and gets incremented every time the function is executed.
  714. body_bytecode, = yield [("CALL_ARGS", [jit.jit_parse_bytecode, (body_id,)])]
  715. initial_temperature, increment_temperature = temperature_heuristic(body_bytecode)
  716. if initial_temperature >= ADAPTIVE_FAST_JIT_TEMPERATURE_THRESHOLD:
  717. # Initial temperature exceeds the fast-jit threshold.
  718. # Compile this thing with fast-jit right away.
  719. yield [
  720. ("TAIL_CALL_ARGS",
  721. [compile_function_body_fast, (jit, function_name, body_id, task_root)])]
  722. (_, parameter_list, _), = yield [
  723. ("CALL_ARGS", [jit.jit_signature, (body_id,)])]
  724. temperature_counter_name = jit.import_value(
  725. initial_temperature, function_name + "_temperature_counter")
  726. can_rejit_name = jit.get_can_rejit_name(function_name)
  727. jit.jit_globals[can_rejit_name] = True
  728. # This tree represents the following logic:
  729. #
  730. # if can_rejit:
  731. # global temperature_counter
  732. # temperature_counter = increment_temperature(temperature_counter)
  733. # if temperature_counter >= ADAPTIVE_FAST_JIT_TEMPERATURE_THRESHOLD:
  734. # yield [("CALL_KWARGS", [jit_runtime.JIT_REJIT_FUNCTION_NAME, {...}])]
  735. # yield [("TAIL_CALL_KWARGS", [function_name, {...}])]
  736. header = tree_ir.SelectInstruction(
  737. tree_ir.LoadGlobalInstruction(can_rejit_name),
  738. tree_ir.create_block(
  739. tree_ir.DeclareGlobalInstruction(temperature_counter_name),
  740. tree_ir.IgnoreInstruction(
  741. tree_ir.StoreGlobalInstruction(
  742. temperature_counter_name,
  743. increment_temperature(
  744. tree_ir.LoadGlobalInstruction(temperature_counter_name)))),
  745. tree_ir.SelectInstruction(
  746. tree_ir.BinaryInstruction(
  747. tree_ir.LoadGlobalInstruction(temperature_counter_name),
  748. '>=',
  749. tree_ir.LiteralInstruction(ADAPTIVE_FAST_JIT_TEMPERATURE_THRESHOLD)),
  750. tree_ir.create_block(
  751. tree_ir.RunGeneratorFunctionInstruction(
  752. tree_ir.LoadGlobalInstruction(jit_runtime.JIT_REJIT_FUNCTION_NAME),
  753. tree_ir.DictionaryLiteralInstruction([
  754. (tree_ir.LiteralInstruction('task_root'),
  755. bytecode_to_tree.load_task_root()),
  756. (tree_ir.LiteralInstruction('body_id'),
  757. tree_ir.LiteralInstruction(body_id)),
  758. (tree_ir.LiteralInstruction('function_name'),
  759. tree_ir.LiteralInstruction(function_name)),
  760. (tree_ir.LiteralInstruction('compile_function_body'),
  761. tree_ir.LoadGlobalInstruction(
  762. jit_runtime.JIT_COMPILE_FUNCTION_BODY_FAST_FUNCTION_NAME))]),
  763. result_type=tree_ir.NO_RESULT_TYPE),
  764. tree_ir.create_jit_call(
  765. tree_ir.LoadGlobalInstruction(function_name),
  766. [(name, tree_ir.LoadLocalInstruction(name)) for name in parameter_list],
  767. tree_ir.LoadLocalInstruction(jit_runtime.KWARGS_PARAMETER_NAME),
  768. tree_ir.RunTailGeneratorFunctionInstruction)),
  769. tree_ir.EmptyInstruction())),
  770. tree_ir.EmptyInstruction())
  771. # Compile with the baseline JIT, and insert the header.
  772. yield [
  773. ("TAIL_CALL_ARGS",
  774. [compile_function_body_baseline,
  775. (jit, function_name, body_id, task_root, header)])]