jit.py 50 KB

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