PageRenderTime 54ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/pypy/rlib/jit.py

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