PageRenderTime 63ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/pypy/rlib/jit.py

http://github.com/pypy/pypy
Python | 934 lines | 929 code | 5 blank | 0 comment | 2 complexity | 83f126bd1b297f9bc02062e2170b83a6 MD5 | raw file
  1. import sys
  2. import py
  3. from pypy.rlib.nonconst import NonConstant
  4. from pypy.rlib.objectmodel import CDefinedIntSymbolic, keepalive_until_here, specialize
  5. from pypy.rlib.unroll import unrolling_iterable
  6. from pypy.rpython.extregistry import ExtRegistryEntry
  7. DEBUG_ELIDABLE_FUNCTIONS = False
  8. def elidable(func):
  9. """ Decorate a function as "trace-elidable". Usually this means simply that
  10. the function is constant-foldable, i.e. is pure and has no side-effects.
  11. In some situations it is ok to use this decorator if the function *has*
  12. side effects, as long as these side-effects are idempotent. A typical
  13. example for this would be a cache.
  14. To be totally precise:
  15. (1) the result of the call should not change if the arguments are
  16. the same (same numbers or same pointers)
  17. (2) it's fine to remove the call completely if we can guess the result
  18. according to rule 1
  19. (3) the function call can be moved around by optimizer,
  20. but only so it'll be called earlier and not later.
  21. Most importantly it doesn't mean that an elidable function has no observable
  22. side effect, but those side effects are idempotent (ie caching).
  23. If a particular call to this function ends up raising an exception, then it
  24. is handled like a normal function call (this decorator is ignored).
  25. """
  26. if DEBUG_ELIDABLE_FUNCTIONS:
  27. cache = {}
  28. oldfunc = func
  29. def func(*args):
  30. result = oldfunc(*args) # if it raises, no caching
  31. try:
  32. oldresult = cache.setdefault(args, result)
  33. except TypeError:
  34. pass # unhashable args
  35. else:
  36. assert oldresult == result
  37. return result
  38. func._elidable_function_ = True
  39. return func
  40. def purefunction(*args, **kwargs):
  41. import warnings
  42. warnings.warn("purefunction is deprecated, use elidable instead", DeprecationWarning)
  43. return elidable(*args, **kwargs)
  44. def hint(x, **kwds):
  45. """ Hint for the JIT
  46. possible arguments are:
  47. * promote - promote the argument from a variable into a constant
  48. * promote_string - same, but promote string by *value*
  49. * access_directly - directly access a virtualizable, as a structure
  50. and don't treat it as a virtualizable
  51. * fresh_virtualizable - means that virtualizable was just allocated.
  52. Useful in say Frame.__init__ when we do want
  53. to store things directly on it. Has to come with
  54. access_directly=True
  55. """
  56. return x
  57. @specialize.argtype(0)
  58. def promote(x):
  59. return hint(x, promote=True)
  60. def promote_string(x):
  61. return hint(x, promote_string=True)
  62. def dont_look_inside(func):
  63. """ Make sure the JIT does not trace inside decorated function
  64. (it becomes a call instead)
  65. """
  66. func._jit_look_inside_ = False
  67. return func
  68. def unroll_safe(func):
  69. """ JIT can safely unroll loops in this function and this will
  70. not lead to code explosion
  71. """
  72. func._jit_unroll_safe_ = True
  73. return func
  74. def loop_invariant(func):
  75. """ Describes a function with no argument that returns an object that
  76. is always the same in a loop.
  77. Use it only if you know what you're doing.
  78. """
  79. dont_look_inside(func)
  80. func._jit_loop_invariant_ = True
  81. return func
  82. def _get_args(func):
  83. import inspect
  84. args, varargs, varkw, defaults = inspect.getargspec(func)
  85. args = ["v%s" % (i, ) for i in range(len(args))]
  86. assert varargs is None and varkw is None
  87. assert not defaults
  88. return args
  89. def elidable_promote(promote_args='all'):
  90. """ A decorator that promotes all arguments and then calls the supplied
  91. function
  92. """
  93. def decorator(func):
  94. elidable(func)
  95. args = _get_args(func)
  96. argstring = ", ".join(args)
  97. code = ["def f(%s):\n" % (argstring, )]
  98. if promote_args != 'all':
  99. args = [('v%d' % int(i)) for i in promote_args.split(",")]
  100. for arg in args:
  101. code.append(" %s = hint(%s, promote=True)\n" % (arg, arg))
  102. code.append(" return func(%s)\n" % (argstring, ))
  103. d = {"func": func, "hint": hint}
  104. exec py.code.Source("\n".join(code)).compile() in d
  105. result = d["f"]
  106. result.func_name = func.func_name + "_promote"
  107. return result
  108. return decorator
  109. def purefunction_promote(*args, **kwargs):
  110. import warnings
  111. warnings.warn("purefunction_promote is deprecated, use elidable_promote instead", DeprecationWarning)
  112. return elidable_promote(*args, **kwargs)
  113. def look_inside_iff(predicate):
  114. """
  115. look inside (including unrolling loops) the target function, if and only if
  116. predicate(*args) returns True
  117. """
  118. def inner(func):
  119. func = unroll_safe(func)
  120. # When we return the new function, it might be specialized in some
  121. # way. We "propogate" this specialization by using
  122. # specialize:call_location on relevant functions.
  123. for thing in [func, predicate]:
  124. thing._annspecialcase_ = "specialize:call_location"
  125. args = _get_args(func)
  126. d = {
  127. "dont_look_inside": dont_look_inside,
  128. "predicate": predicate,
  129. "func": func,
  130. "we_are_jitted": we_are_jitted,
  131. }
  132. exec py.code.Source("""
  133. @dont_look_inside
  134. def trampoline(%(arguments)s):
  135. return func(%(arguments)s)
  136. if hasattr(func, "oopspec"):
  137. # XXX: This seems like it should be here, but it causes errors.
  138. # trampoline.oopspec = func.oopspec
  139. del func.oopspec
  140. trampoline.__name__ = func.__name__ + "_trampoline"
  141. trampoline._annspecialcase_ = "specialize:call_location"
  142. def f(%(arguments)s):
  143. if not we_are_jitted() or predicate(%(arguments)s):
  144. return func(%(arguments)s)
  145. else:
  146. return trampoline(%(arguments)s)
  147. f.__name__ = func.__name__ + "_look_inside_iff"
  148. """ % {"arguments": ", ".join(args)}).compile() in d
  149. return d["f"]
  150. return inner
  151. def oopspec(spec):
  152. def decorator(func):
  153. func.oopspec = spec
  154. return func
  155. return decorator
  156. @oopspec("jit.isconstant(value)")
  157. def isconstant(value):
  158. """
  159. While tracing, returns whether or not the value is currently known to be
  160. constant. This is not perfect, values can become constant later. Mostly for
  161. use with @look_inside_iff.
  162. This is for advanced usage only.
  163. """
  164. return NonConstant(False)
  165. isconstant._annspecialcase_ = "specialize:call_location"
  166. @oopspec("jit.isvirtual(value)")
  167. def isvirtual(value):
  168. """
  169. Returns if this value is virtual, while tracing, it's relatively
  170. conservative and will miss some cases.
  171. This is for advanced usage only.
  172. """
  173. return NonConstant(False)
  174. isvirtual._annspecialcase_ = "specialize:call_location"
  175. LIST_CUTOFF = 2
  176. @specialize.call_location()
  177. def loop_unrolling_heuristic(lst, size):
  178. """ In which cases iterating over items of lst can be unrolled
  179. """
  180. return isvirtual(lst) or (isconstant(size) and size <= LIST_CUTOFF)
  181. class Entry(ExtRegistryEntry):
  182. _about_ = hint
  183. def compute_result_annotation(self, s_x, **kwds_s):
  184. from pypy.annotation import model as annmodel
  185. s_x = annmodel.not_const(s_x)
  186. access_directly = 's_access_directly' in kwds_s
  187. fresh_virtualizable = 's_fresh_virtualizable' in kwds_s
  188. if access_directly or fresh_virtualizable:
  189. assert access_directly, "lone fresh_virtualizable hint"
  190. if isinstance(s_x, annmodel.SomeInstance):
  191. from pypy.objspace.flow.model import Constant
  192. classdesc = s_x.classdef.classdesc
  193. virtualizable = classdesc.read_attribute('_virtualizable2_',
  194. Constant(None)).value
  195. if virtualizable is not None:
  196. flags = s_x.flags.copy()
  197. flags['access_directly'] = True
  198. if fresh_virtualizable:
  199. flags['fresh_virtualizable'] = True
  200. s_x = annmodel.SomeInstance(s_x.classdef,
  201. s_x.can_be_None,
  202. flags)
  203. return s_x
  204. def specialize_call(self, hop, **kwds_i):
  205. from pypy.rpython.lltypesystem import lltype
  206. hints = {}
  207. for key, index in kwds_i.items():
  208. s_value = hop.args_s[index]
  209. if not s_value.is_constant():
  210. from pypy.rpython.error import TyperError
  211. raise TyperError("hint %r is not constant" % (key,))
  212. assert key.startswith('i_')
  213. hints[key[2:]] = s_value.const
  214. v = hop.inputarg(hop.args_r[0], arg=0)
  215. c_hint = hop.inputconst(lltype.Void, hints)
  216. hop.exception_cannot_occur()
  217. return hop.genop('hint', [v, c_hint], resulttype=v.concretetype)
  218. def we_are_jitted():
  219. """ Considered as true during tracing and blackholing,
  220. so its consquences are reflected into jitted code """
  221. return False
  222. _we_are_jitted = CDefinedIntSymbolic('0 /* we are not jitted here */',
  223. default=0)
  224. class Entry(ExtRegistryEntry):
  225. _about_ = we_are_jitted
  226. def compute_result_annotation(self):
  227. from pypy.annotation import model as annmodel
  228. return annmodel.SomeInteger(nonneg=True)
  229. def specialize_call(self, hop):
  230. from pypy.rpython.lltypesystem import lltype
  231. hop.exception_cannot_occur()
  232. return hop.inputconst(lltype.Signed, _we_are_jitted)
  233. def current_trace_length():
  234. """During JIT tracing, returns the current trace length (as a constant).
  235. If not tracing, returns -1."""
  236. if NonConstant(False):
  237. return 73
  238. return -1
  239. current_trace_length.oopspec = 'jit.current_trace_length()'
  240. def jit_debug(string, arg1=-sys.maxint-1, arg2=-sys.maxint-1,
  241. arg3=-sys.maxint-1, arg4=-sys.maxint-1):
  242. """When JITted, cause an extra operation JIT_DEBUG to appear in
  243. the graphs. Should not be left after debugging."""
  244. keepalive_until_here(string) # otherwise the whole function call is removed
  245. jit_debug.oopspec = 'jit.debug(string, arg1, arg2, arg3, arg4)'
  246. def assert_green(value):
  247. """Very strong assert: checks that 'value' is a green
  248. (a JIT compile-time constant)."""
  249. keepalive_until_here(value)
  250. assert_green._annspecialcase_ = 'specialize:argtype(0)'
  251. assert_green.oopspec = 'jit.assert_green(value)'
  252. class AssertGreenFailed(Exception):
  253. pass
  254. # ____________________________________________________________
  255. # VRefs
  256. def virtual_ref(x):
  257. """Creates a 'vref' object that contains a reference to 'x'. Calls
  258. to virtual_ref/virtual_ref_finish must be properly nested. The idea
  259. is that the object 'x' is supposed to be JITted as a virtual between
  260. the calls to virtual_ref and virtual_ref_finish, but the 'vref'
  261. object can escape at any point in time. If at runtime it is
  262. dereferenced (by the call syntax 'vref()'), it returns 'x', which is
  263. then forced."""
  264. return DirectJitVRef(x)
  265. virtual_ref.oopspec = 'virtual_ref(x)'
  266. def virtual_ref_finish(vref, x):
  267. """See docstring in virtual_ref(x)"""
  268. keepalive_until_here(x) # otherwise the whole function call is removed
  269. _virtual_ref_finish(vref, x)
  270. virtual_ref_finish.oopspec = 'virtual_ref_finish(x)'
  271. def non_virtual_ref(x):
  272. """Creates a 'vref' that just returns x when called; nothing more special.
  273. Used for None or for frames outside JIT scope."""
  274. return DirectVRef(x)
  275. class InvalidVirtualRef(Exception):
  276. """
  277. Raised if we try to call a non-forced virtualref after the call to
  278. virtual_ref_finish
  279. """
  280. # ---------- implementation-specific ----------
  281. class DirectVRef(object):
  282. def __init__(self, x):
  283. self._x = x
  284. self._state = 'non-forced'
  285. def __call__(self):
  286. if self._state == 'non-forced':
  287. self._state = 'forced'
  288. elif self._state == 'invalid':
  289. raise InvalidVirtualRef
  290. return self._x
  291. @property
  292. def virtual(self):
  293. """A property that is True if the vref contains a virtual that would
  294. be forced by the '()' operator."""
  295. return self._state == 'non-forced'
  296. def _finish(self):
  297. if self._state == 'non-forced':
  298. self._state = 'invalid'
  299. class DirectJitVRef(DirectVRef):
  300. def __init__(self, x):
  301. assert x is not None, "virtual_ref(None) is not allowed"
  302. DirectVRef.__init__(self, x)
  303. def _virtual_ref_finish(vref, x):
  304. assert vref._x is x, "Invalid call to virtual_ref_finish"
  305. vref._finish()
  306. class Entry(ExtRegistryEntry):
  307. _about_ = (non_virtual_ref, DirectJitVRef)
  308. def compute_result_annotation(self, s_obj):
  309. from pypy.rlib import _jit_vref
  310. return _jit_vref.SomeVRef(s_obj)
  311. def specialize_call(self, hop):
  312. return hop.r_result.specialize_call(hop)
  313. class Entry(ExtRegistryEntry):
  314. _type_ = DirectVRef
  315. def compute_annotation(self):
  316. from pypy.rlib import _jit_vref
  317. assert isinstance(self.instance, DirectVRef)
  318. s_obj = self.bookkeeper.immutablevalue(self.instance())
  319. return _jit_vref.SomeVRef(s_obj)
  320. class Entry(ExtRegistryEntry):
  321. _about_ = _virtual_ref_finish
  322. def compute_result_annotation(self, s_vref, s_obj):
  323. pass
  324. def specialize_call(self, hop):
  325. hop.exception_cannot_occur()
  326. vref_None = non_virtual_ref(None)
  327. # ____________________________________________________________
  328. # User interface for the warmspot JIT policy
  329. class JitHintError(Exception):
  330. """Inconsistency in the JIT hints."""
  331. ENABLE_ALL_OPTS = (
  332. 'intbounds:rewrite:virtualize:string:earlyforce:pure:heap:ffi:unroll')
  333. PARAMETER_DOCS = {
  334. 'threshold': 'number of times a loop has to run for it to become hot',
  335. 'function_threshold': 'number of times a function must run for it to become traced from start',
  336. 'trace_eagerness': 'number of times a guard has to fail before we start compiling a bridge',
  337. 'trace_limit': 'number of recorded operations before we abort tracing with ABORT_TOO_LONG',
  338. 'inlining': 'inline python functions or not (1/0)',
  339. 'loop_longevity': 'a parameter controlling how long loops will be kept before being freed, an estimate',
  340. 'retrace_limit': 'how many times we can try retracing before giving up',
  341. 'max_retrace_guards': 'number of extra guards a retrace can cause',
  342. 'max_unroll_loops': 'number of extra unrollings a loop can cause',
  343. 'enable_opts': 'INTERNAL USE ONLY (MAY NOT WORK OR LEAD TO CRASHES): '
  344. 'optimizations to enable, or all = %s' % ENABLE_ALL_OPTS,
  345. }
  346. PARAMETERS = {'threshold': 1039, # just above 1024, prime
  347. 'function_threshold': 1619, # slightly more than one above, also prime
  348. 'trace_eagerness': 200,
  349. 'trace_limit': 6000,
  350. 'inlining': 1,
  351. 'loop_longevity': 1000,
  352. 'retrace_limit': 5,
  353. 'max_retrace_guards': 15,
  354. 'max_unroll_loops': 4,
  355. 'enable_opts': 'all',
  356. }
  357. unroll_parameters = unrolling_iterable(PARAMETERS.items())
  358. DEFAULT = object()
  359. # ____________________________________________________________
  360. class JitDriver(object):
  361. """Base class to declare fine-grained user control on the JIT. So
  362. far, there must be a singleton instance of JitDriver. This style
  363. will allow us (later) to support a single RPython program with
  364. several independent JITting interpreters in it.
  365. """
  366. active = True # if set to False, this JitDriver is ignored
  367. virtualizables = []
  368. name = 'jitdriver'
  369. def __init__(self, greens=None, reds=None, virtualizables=None,
  370. get_jitcell_at=None, set_jitcell_at=None,
  371. get_printable_location=None, confirm_enter_jit=None,
  372. can_never_inline=None, should_unroll_one_iteration=None,
  373. name='jitdriver'):
  374. if greens is not None:
  375. self.greens = greens
  376. self.name = name
  377. if reds is not None:
  378. self.reds = reds
  379. if not hasattr(self, 'greens') or not hasattr(self, 'reds'):
  380. raise AttributeError("no 'greens' or 'reds' supplied")
  381. if virtualizables is not None:
  382. self.virtualizables = virtualizables
  383. for v in self.virtualizables:
  384. assert v in self.reds
  385. self._alllivevars = dict.fromkeys(
  386. [name for name in self.greens + self.reds if '.' not in name])
  387. self._heuristic_order = {} # check if 'reds' and 'greens' are ordered
  388. self._make_extregistryentries()
  389. self.get_jitcell_at = get_jitcell_at
  390. self.set_jitcell_at = set_jitcell_at
  391. self.get_printable_location = get_printable_location
  392. self.confirm_enter_jit = confirm_enter_jit
  393. self.can_never_inline = can_never_inline
  394. self.should_unroll_one_iteration = should_unroll_one_iteration
  395. def _freeze_(self):
  396. return True
  397. def _check_arguments(self, livevars):
  398. assert dict.fromkeys(livevars) == self._alllivevars
  399. # check heuristically that 'reds' and 'greens' are ordered as
  400. # the JIT will need them to be: first INTs, then REFs, then
  401. # FLOATs.
  402. if len(self._heuristic_order) < len(livevars):
  403. from pypy.rlib.rarithmetic import (r_singlefloat, r_longlong,
  404. r_ulonglong, r_uint)
  405. added = False
  406. for var, value in livevars.items():
  407. if var not in self._heuristic_order:
  408. if (r_ulonglong is not r_uint and
  409. isinstance(value, (r_longlong, r_ulonglong))):
  410. assert 0, ("should not pass a r_longlong argument for "
  411. "now, because on 32-bit machines it needs "
  412. "to be ordered as a FLOAT but on 64-bit "
  413. "machines as an INT")
  414. elif isinstance(value, (int, long, r_singlefloat)):
  415. kind = '1:INT'
  416. elif isinstance(value, float):
  417. kind = '3:FLOAT'
  418. elif isinstance(value, (str, unicode)) and len(value) != 1:
  419. kind = '2:REF'
  420. elif isinstance(value, (list, dict)):
  421. kind = '2:REF'
  422. elif (hasattr(value, '__class__')
  423. and value.__class__.__module__ != '__builtin__'):
  424. if hasattr(value, '_freeze_'):
  425. continue # value._freeze_() is better not called
  426. elif getattr(value, '_alloc_flavor_', 'gc') == 'gc':
  427. kind = '2:REF'
  428. else:
  429. kind = '1:INT'
  430. else:
  431. continue
  432. self._heuristic_order[var] = kind
  433. added = True
  434. if added:
  435. for color in ('reds', 'greens'):
  436. lst = getattr(self, color)
  437. allkinds = [self._heuristic_order.get(name, '?')
  438. for name in lst]
  439. kinds = [k for k in allkinds if k != '?']
  440. assert kinds == sorted(kinds), (
  441. "bad order of %s variables in the jitdriver: "
  442. "must be INTs, REFs, FLOATs; got %r" %
  443. (color, allkinds))
  444. def jit_merge_point(_self, **livevars):
  445. # special-cased by ExtRegistryEntry
  446. _self._check_arguments(livevars)
  447. def can_enter_jit(_self, **livevars):
  448. # special-cased by ExtRegistryEntry
  449. _self._check_arguments(livevars)
  450. def loop_header(self):
  451. # special-cased by ExtRegistryEntry
  452. pass
  453. def _make_extregistryentries(self):
  454. # workaround: we cannot declare ExtRegistryEntries for functions
  455. # used as methods of a frozen object, but we can attach the
  456. # bound methods back to 'self' and make ExtRegistryEntries
  457. # specifically for them.
  458. self.jit_merge_point = self.jit_merge_point
  459. self.can_enter_jit = self.can_enter_jit
  460. self.loop_header = self.loop_header
  461. class Entry(ExtEnterLeaveMarker):
  462. _about_ = (self.jit_merge_point, self.can_enter_jit)
  463. class Entry(ExtLoopHeader):
  464. _about_ = self.loop_header
  465. def _set_param(driver, name, value):
  466. # special-cased by ExtRegistryEntry
  467. # (internal, must receive a constant 'name')
  468. # if value is DEFAULT, sets the default value.
  469. assert name in PARAMETERS
  470. @specialize.arg(0, 1)
  471. def set_param(driver, name, value):
  472. """Set one of the tunable JIT parameter. Driver can be None, then all
  473. drivers have this set """
  474. _set_param(driver, name, value)
  475. @specialize.arg(0, 1)
  476. def set_param_to_default(driver, name):
  477. """Reset one of the tunable JIT parameters to its default value."""
  478. _set_param(driver, name, DEFAULT)
  479. def set_user_param(driver, text):
  480. """Set the tunable JIT parameters from a user-supplied string
  481. following the format 'param=value,param=value', or 'off' to
  482. disable the JIT. For programmatic setting of parameters, use
  483. directly JitDriver.set_param().
  484. """
  485. if text == 'off':
  486. set_param(driver, 'threshold', -1)
  487. set_param(driver, 'function_threshold', -1)
  488. return
  489. if text == 'default':
  490. for name1, _ in unroll_parameters:
  491. set_param_to_default(driver, name1)
  492. return
  493. for s in text.split(','):
  494. s = s.strip(' ')
  495. parts = s.split('=')
  496. if len(parts) != 2:
  497. raise ValueError
  498. name = parts[0]
  499. value = parts[1]
  500. if name == 'enable_opts':
  501. set_param(driver, 'enable_opts', value)
  502. else:
  503. for name1, _ in unroll_parameters:
  504. if name1 == name and name1 != 'enable_opts':
  505. try:
  506. set_param(driver, name1, int(value))
  507. except ValueError:
  508. raise
  509. break
  510. else:
  511. raise ValueError
  512. set_user_param._annspecialcase_ = 'specialize:arg(0)'
  513. # ____________________________________________________________
  514. #
  515. # Annotation and rtyping of some of the JitDriver methods
  516. class BaseJitCell(object):
  517. __slots__ = ()
  518. class ExtEnterLeaveMarker(ExtRegistryEntry):
  519. # Replace a call to myjitdriver.jit_merge_point(**livevars)
  520. # with an operation jit_marker('jit_merge_point', myjitdriver, livevars...)
  521. # Also works with can_enter_jit.
  522. def compute_result_annotation(self, **kwds_s):
  523. from pypy.annotation import model as annmodel
  524. if self.instance.__name__ == 'jit_merge_point':
  525. self.annotate_hooks(**kwds_s)
  526. driver = self.instance.im_self
  527. keys = kwds_s.keys()
  528. keys.sort()
  529. expected = ['s_' + name for name in driver.greens + driver.reds
  530. if '.' not in name]
  531. expected.sort()
  532. if keys != expected:
  533. raise JitHintError("%s expects the following keyword "
  534. "arguments: %s" % (self.instance,
  535. expected))
  536. try:
  537. cache = self.bookkeeper._jit_annotation_cache[driver]
  538. except AttributeError:
  539. cache = {}
  540. self.bookkeeper._jit_annotation_cache = {driver: cache}
  541. except KeyError:
  542. cache = {}
  543. self.bookkeeper._jit_annotation_cache[driver] = cache
  544. for key, s_value in kwds_s.items():
  545. s_previous = cache.get(key, annmodel.s_ImpossibleValue)
  546. s_value = annmodel.unionof(s_previous, s_value)
  547. if annmodel.isdegenerated(s_value):
  548. raise JitHintError("mixing incompatible types in argument %s"
  549. " of jit_merge_point/can_enter_jit" %
  550. key[2:])
  551. cache[key] = s_value
  552. # add the attribute _dont_reach_me_in_del_ (see pypy.rpython.rclass)
  553. try:
  554. graph = self.bookkeeper.position_key[0]
  555. graph.func._dont_reach_me_in_del_ = True
  556. except (TypeError, AttributeError):
  557. pass
  558. return annmodel.s_None
  559. def annotate_hooks(self, **kwds_s):
  560. driver = self.instance.im_self
  561. s_jitcell = self.bookkeeper.valueoftype(BaseJitCell)
  562. h = self.annotate_hook
  563. h(driver.get_jitcell_at, driver.greens, **kwds_s)
  564. h(driver.set_jitcell_at, driver.greens, [s_jitcell], **kwds_s)
  565. h(driver.get_printable_location, driver.greens, **kwds_s)
  566. def annotate_hook(self, func, variables, args_s=[], **kwds_s):
  567. if func is None:
  568. return
  569. bk = self.bookkeeper
  570. s_func = bk.immutablevalue(func)
  571. uniquekey = 'jitdriver.%s' % func.func_name
  572. args_s = args_s[:]
  573. for name in variables:
  574. if '.' not in name:
  575. s_arg = kwds_s['s_' + name]
  576. else:
  577. objname, fieldname = name.split('.')
  578. s_instance = kwds_s['s_' + objname]
  579. attrdef = s_instance.classdef.find_attribute(fieldname)
  580. position = self.bookkeeper.position_key
  581. attrdef.read_locations[position] = True
  582. s_arg = attrdef.getvalue()
  583. assert s_arg is not None
  584. args_s.append(s_arg)
  585. bk.emulate_pbc_call(uniquekey, s_func, args_s)
  586. def get_getfield_op(self, rtyper):
  587. if rtyper.type_system.name == 'ootypesystem':
  588. return 'oogetfield'
  589. else:
  590. return 'getfield'
  591. def specialize_call(self, hop, **kwds_i):
  592. # XXX to be complete, this could also check that the concretetype
  593. # of the variables are the same for each of the calls.
  594. from pypy.rpython.lltypesystem import lltype
  595. driver = self.instance.im_self
  596. greens_v = []
  597. reds_v = []
  598. for name in driver.greens:
  599. if '.' not in name:
  600. i = kwds_i['i_' + name]
  601. r_green = hop.args_r[i]
  602. v_green = hop.inputarg(r_green, arg=i)
  603. else:
  604. objname, fieldname = name.split('.') # see test_green_field
  605. assert objname in driver.reds
  606. i = kwds_i['i_' + objname]
  607. s_red = hop.args_s[i]
  608. r_red = hop.args_r[i]
  609. while True:
  610. try:
  611. mangled_name, r_field = r_red._get_field(fieldname)
  612. break
  613. except KeyError:
  614. pass
  615. assert r_red.rbase is not None, (
  616. "field %r not found in %r" % (name,
  617. r_red.lowleveltype.TO))
  618. r_red = r_red.rbase
  619. if hop.rtyper.type_system.name == 'ootypesystem':
  620. GTYPE = r_red.lowleveltype
  621. else:
  622. GTYPE = r_red.lowleveltype.TO
  623. assert GTYPE._immutable_field(mangled_name), (
  624. "field %r must be declared as immutable" % name)
  625. if not hasattr(driver, 'll_greenfields'):
  626. driver.ll_greenfields = {}
  627. driver.ll_greenfields[name] = GTYPE, mangled_name
  628. #
  629. v_red = hop.inputarg(r_red, arg=i)
  630. c_llname = hop.inputconst(lltype.Void, mangled_name)
  631. getfield_op = self.get_getfield_op(hop.rtyper)
  632. v_green = hop.genop(getfield_op, [v_red, c_llname],
  633. resulttype=r_field)
  634. s_green = s_red.classdef.about_attribute(fieldname)
  635. assert s_green is not None
  636. hop.rtyper.annotator.setbinding(v_green, s_green)
  637. greens_v.append(v_green)
  638. for name in driver.reds:
  639. i = kwds_i['i_' + name]
  640. r_red = hop.args_r[i]
  641. v_red = hop.inputarg(r_red, arg=i)
  642. reds_v.append(v_red)
  643. hop.exception_cannot_occur()
  644. vlist = [hop.inputconst(lltype.Void, self.instance.__name__),
  645. hop.inputconst(lltype.Void, driver)]
  646. vlist.extend(greens_v)
  647. vlist.extend(reds_v)
  648. return hop.genop('jit_marker', vlist,
  649. resulttype=lltype.Void)
  650. class ExtLoopHeader(ExtRegistryEntry):
  651. # Replace a call to myjitdriver.loop_header()
  652. # with an operation jit_marker('loop_header', myjitdriver).
  653. def compute_result_annotation(self, **kwds_s):
  654. from pypy.annotation import model as annmodel
  655. return annmodel.s_None
  656. def specialize_call(self, hop):
  657. from pypy.rpython.lltypesystem import lltype
  658. driver = self.instance.im_self
  659. hop.exception_cannot_occur()
  660. vlist = [hop.inputconst(lltype.Void, 'loop_header'),
  661. hop.inputconst(lltype.Void, driver)]
  662. return hop.genop('jit_marker', vlist,
  663. resulttype=lltype.Void)
  664. class ExtSetParam(ExtRegistryEntry):
  665. _about_ = _set_param
  666. def compute_result_annotation(self, s_driver, s_name, s_value):
  667. from pypy.annotation import model as annmodel
  668. assert s_name.is_constant()
  669. if not self.bookkeeper.immutablevalue(DEFAULT).contains(s_value):
  670. if s_name.const == 'enable_opts':
  671. assert annmodel.SomeString(can_be_None=True).contains(s_value)
  672. else:
  673. assert annmodel.SomeInteger().contains(s_value)
  674. return annmodel.s_None
  675. def specialize_call(self, hop):
  676. from pypy.rpython.lltypesystem import lltype
  677. from pypy.rpython.lltypesystem.rstr import string_repr
  678. from pypy.objspace.flow.model import Constant
  679. hop.exception_cannot_occur()
  680. driver = hop.inputarg(lltype.Void, arg=0)
  681. name = hop.args_s[1].const
  682. if name == 'enable_opts':
  683. repr = string_repr
  684. else:
  685. repr = lltype.Signed
  686. if (isinstance(hop.args_v[2], Constant) and
  687. hop.args_v[2].value is DEFAULT):
  688. value = PARAMETERS[name]
  689. v_value = hop.inputconst(repr, value)
  690. else:
  691. v_value = hop.inputarg(repr, arg=2)
  692. vlist = [hop.inputconst(lltype.Void, "set_param"),
  693. driver,
  694. hop.inputconst(lltype.Void, name),
  695. v_value]
  696. return hop.genop('jit_marker', vlist,
  697. resulttype=lltype.Void)
  698. class AsmInfo(object):
  699. """ An addition to JitDebugInfo concerning assembler. Attributes:
  700. ops_offset - dict of offsets of operations or None
  701. asmaddr - (int) raw address of assembler block
  702. asmlen - assembler block length
  703. """
  704. def __init__(self, ops_offset, asmaddr, asmlen):
  705. self.ops_offset = ops_offset
  706. self.asmaddr = asmaddr
  707. self.asmlen = asmlen
  708. class JitDebugInfo(object):
  709. """ An object representing debug info. Attributes meanings:
  710. greenkey - a list of green boxes or None for bridge
  711. logger - an instance of jit.metainterp.logger.LogOperations
  712. type - either 'loop', 'entry bridge' or 'bridge'
  713. looptoken - description of a loop
  714. fail_descr_no - number of failing descr for bridges, -1 otherwise
  715. asminfo - extra assembler information
  716. """
  717. asminfo = None
  718. def __init__(self, jitdriver_sd, logger, looptoken, operations, type,
  719. greenkey=None, fail_descr_no=-1):
  720. self.jitdriver_sd = jitdriver_sd
  721. self.logger = logger
  722. self.looptoken = looptoken
  723. self.operations = operations
  724. self.type = type
  725. if type == 'bridge':
  726. assert fail_descr_no != -1
  727. else:
  728. assert greenkey is not None
  729. self.greenkey = greenkey
  730. self.fail_descr_no = fail_descr_no
  731. def get_jitdriver(self):
  732. """ Return where the jitdriver on which the jitting started
  733. """
  734. return self.jitdriver_sd.jitdriver
  735. def get_greenkey_repr(self):
  736. """ Return the string repr of a greenkey
  737. """
  738. return self.jitdriver_sd.warmstate.get_location_str(self.greenkey)
  739. class JitHookInterface(object):
  740. """ This is the main connector between the JIT and the interpreter.
  741. Several methods on this class will be invoked at various stages
  742. of JIT running like JIT loops compiled, aborts etc.
  743. An instance of this class will be available as policy.jithookiface.
  744. """
  745. def on_abort(self, reason, jitdriver, greenkey, greenkey_repr):
  746. """ A hook called each time a loop is aborted with jitdriver and
  747. greenkey where it started, reason is a string why it got aborted
  748. """
  749. #def before_optimize(self, debug_info):
  750. # """ A hook called before optimizer is run, called with instance of
  751. # JitDebugInfo. Overwrite for custom behavior
  752. # """
  753. # DISABLED
  754. def before_compile(self, debug_info):
  755. """ A hook called after a loop is optimized, before compiling assembler,
  756. called with JitDebugInfo instance. Overwrite for custom behavior
  757. """
  758. def after_compile(self, debug_info):
  759. """ A hook called after a loop has compiled assembler,
  760. called with JitDebugInfo instance. Overwrite for custom behavior
  761. """
  762. #def before_optimize_bridge(self, debug_info):
  763. # operations, fail_descr_no):
  764. # """ A hook called before a bridge is optimized.
  765. # Called with JitDebugInfo instance, overwrite for
  766. # custom behavior
  767. # """
  768. # DISABLED
  769. def before_compile_bridge(self, debug_info):
  770. """ A hook called before a bridge is compiled, but after optimizations
  771. are performed. Called with instance of debug_info, overwrite for
  772. custom behavior
  773. """
  774. def after_compile_bridge(self, debug_info):
  775. """ A hook called after a bridge is compiled, called with JitDebugInfo
  776. instance, overwrite for custom behavior
  777. """
  778. def get_stats(self):
  779. """ Returns various statistics
  780. """
  781. raise NotImplementedError
  782. def record_known_class(value, cls):
  783. """
  784. Assure the JIT that value is an instance of cls. This is not a precise
  785. class check, unlike a guard_class.
  786. """
  787. assert isinstance(value, cls)
  788. class Entry(ExtRegistryEntry):
  789. _about_ = record_known_class
  790. def compute_result_annotation(self, s_inst, s_cls):
  791. from pypy.annotation import model as annmodel
  792. assert s_cls.is_constant()
  793. assert not s_inst.can_be_none()
  794. assert isinstance(s_inst, annmodel.SomeInstance)
  795. def specialize_call(self, hop):
  796. from pypy.rpython.lltypesystem import rclass, lltype
  797. classrepr = rclass.get_type_repr(hop.rtyper)
  798. hop.exception_cannot_occur()
  799. v_inst = hop.inputarg(hop.args_r[0], arg=0)
  800. v_cls = hop.inputarg(classrepr, arg=1)
  801. return hop.genop('jit_record_known_class', [v_inst, v_cls],
  802. resulttype=lltype.Void)