jit.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. import math
  2. import keyword
  3. from collections import defaultdict
  4. import modelverse_kernel.primitives as primitive_functions
  5. class ModelverseJit(object):
  6. """A high-level interface to the modelverse JIT compiler."""
  7. def __init__(self):
  8. self.todo_entry_points = set()
  9. self.jitted_parameters = {}
  10. self.jit_globals = {}
  11. # jitted_entry_points maps body ids to values in jit_globals.
  12. self.jitted_entry_points = {}
  13. # global_functions maps global value names to body ids.
  14. self.global_functions = {}
  15. # global_functions_inv maps body ids to global value names.
  16. self.global_functions_inv = {}
  17. # jitted_function_aliases maps body ids to known aliases.
  18. self.jitted_function_aliases = defaultdict(set)
  19. self.jit_count = 0
  20. self.compilation_dependencies = {}
  21. self.cache = {}
  22. def mark_entry_point(self, body_id):
  23. """Marks the node with the given identifier as a function entry point."""
  24. if body_id not in self.jitted_entry_points:
  25. self.todo_entry_points.add(body_id)
  26. def is_jittable_entry_point(self, body_id):
  27. """Tells if the node with the given identifier is a function entry point that
  28. has not been marked as non-jittable. This only returns `True` if the JIT
  29. is enabled and the function entry point has been marked jittable, or if
  30. the function has already been compiled."""
  31. return ((body_id in self.todo_entry_points) or (body_id in self.jitted_entry_points))
  32. def generate_name(self, infix, suggested_name=None):
  33. """Generates a new name or picks the suggested name if it is still
  34. available."""
  35. if suggested_name is not None \
  36. and suggested_name not in self.jit_globals \
  37. and not keyword.iskeyword(suggested_name):
  38. self.jit_count += 1
  39. return suggested_name
  40. else:
  41. function_name = 'jit_%s%d' % (infix, self.jit_count)
  42. self.jit_count += 1
  43. return function_name
  44. def generate_function_name(self, body_id, suggested_name=None):
  45. """Generates a new function name or picks the suggested name if it is still
  46. available."""
  47. if suggested_name is None:
  48. suggested_name = self.get_global_name(body_id)
  49. return self.generate_name('func', suggested_name)
  50. def register_global(self, body_id, global_name):
  51. """Associates the given body id with the given global name."""
  52. self.global_functions[global_name] = body_id
  53. self.global_functions_inv[body_id] = global_name
  54. def get_global_name(self, body_id):
  55. """Gets the name of the global function with the given body id.
  56. Returns None if no known global exists with the given id."""
  57. if body_id in self.global_functions_inv:
  58. return self.global_functions_inv[body_id]
  59. else:
  60. return None
  61. def get_global_body_id(self, global_name):
  62. """Gets the body id of the global function with the given name.
  63. Returns None if no known global exists with the given name."""
  64. if global_name in self.global_functions:
  65. return self.global_functions[global_name]
  66. else:
  67. return None
  68. def register_compiled(self, body_id, compiled_function, function_name=None):
  69. """Registers a compiled entry point with the JIT."""
  70. # Get the function's name.
  71. actual_function_name = self.generate_function_name(body_id, function_name)
  72. # Map the body id to the given parameter list.
  73. self.jitted_entry_points[body_id] = actual_function_name
  74. self.jit_globals[actual_function_name] = compiled_function
  75. if function_name is not None:
  76. self.register_global(body_id, function_name)
  77. if body_id in self.todo_entry_points:
  78. self.todo_entry_points.remove(body_id)
  79. def __lookup_compiled_body_impl(self, body_id):
  80. """Looks up a compiled function by body id. Returns a matching function,
  81. or None if no function was found."""
  82. if body_id is not None and body_id in self.jitted_entry_points:
  83. return self.jit_globals[self.jitted_entry_points[body_id]]
  84. else:
  85. return None
  86. def __lookup_external_body_impl(self, global_name, body_id):
  87. """Looks up an external function by global name. Returns a matching function,
  88. or None if no function was found."""
  89. if global_name is not None and self.compiled_function_lookup is not None:
  90. result = self.compiled_function_lookup(global_name)
  91. if result is not None and body_id is not None:
  92. self.register_compiled(body_id, result, global_name)
  93. return result
  94. else:
  95. return None
  96. def lookup_compiled_body(self, body_id):
  97. """Looks up a compiled function by body id. Returns a matching function,
  98. or None if no function was found."""
  99. result = self.__lookup_compiled_body_impl(body_id)
  100. if result is not None:
  101. return result
  102. else:
  103. global_name = self.get_global_name(body_id)
  104. return self.__lookup_external_body_impl(global_name, body_id)
  105. def lookup_compiled_function(self, global_name):
  106. """Looks up a compiled function by global name. Returns a matching function,
  107. or None if no function was found."""
  108. body_id = self.get_global_body_id(global_name)
  109. result = self.__lookup_compiled_body_impl(body_id)
  110. if result is not None:
  111. return result
  112. else:
  113. return self.__lookup_external_body_impl(global_name, body_id)
  114. def jit_signature(self, body_id):
  115. """Acquires the signature for the given body id node, which consists of the
  116. parameter variables, parameter name and a flag that tells if the given function
  117. is mutable."""
  118. if body_id not in self.jitted_parameters:
  119. signature_id, = yield [("RRD", [body_id, "body"])]
  120. signature_id = signature_id[0]
  121. param_set_id, is_mutable = yield [
  122. ("RD", [signature_id, "params"]),
  123. ("RD", [signature_id, "mutable"])]
  124. if param_set_id is None:
  125. self.jitted_parameters[body_id] = ([], [], is_mutable)
  126. else:
  127. param_name_ids, = yield [("RDK", [param_set_id])]
  128. param_names = yield [("RV", [n]) for n in param_name_ids]
  129. #NOTE Patch up strange links...
  130. param_names = [i for i in param_names if i is not None]
  131. param_vars = yield [("RD", [param_set_id, k]) for k in param_names]
  132. #NOTE that variables might not be in the correct order, as we just read them out!
  133. lst = sorted([(name, var) for name, var in zip(param_names, param_vars)])
  134. param_vars = [i[1] for i in lst]
  135. param_names = [i[0] for i in lst]
  136. self.jitted_parameters[body_id] = (param_vars, param_names, is_mutable)
  137. yield [("RETURN", [self.jitted_parameters[body_id]])]
  138. def check_jittable(self, body_id, suggested_name=None):
  139. """Checks if the function with the given body id is obviously non-jittable. If it's
  140. non-jittable, then a `JitCompilationFailedException` exception is thrown."""
  141. if body_id is None:
  142. raise ValueError('body_id cannot be None: ' + suggested_name)
  143. def jit_define_function(self, function_name, function_def):
  144. """Converts the given tree-IR function definition to Python code, defines it,
  145. and extracts the resulting function."""
  146. # The comment below makes pylint shut up about our (hopefully benign) use of exec here.
  147. # pylint: disable=I0011,W0122
  148. if self.jit_code_log_function is not None:
  149. self.jit_code_log_function(function_def)
  150. # Convert the function definition to Python code, and compile it.
  151. code_generator = tree_ir.PythonGenerator()
  152. function_def.generate_python_def(code_generator)
  153. source_map_name = self.get_source_map_name(function_name)
  154. if source_map_name is not None:
  155. self.jit_globals[source_map_name] = code_generator.source_map_builder.source_map
  156. exec(str(code_generator), self.jit_globals)
  157. # Extract the compiled function from the JIT global state.
  158. return self.jit_globals[function_name]
  159. def jit_delete_function(self, function_name):
  160. """Deletes the function with the given function name."""
  161. del self.jit_globals[function_name]
  162. import modelverse_kernel.primitives as primitive_functions
  163. class JitCompilationFailedException(Exception):
  164. """A type of exception that is raised when the jit fails to compile a function."""
  165. pass