PageRenderTime 62ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/pypy/rlib/jit.py

https://bitbucket.org/shomah4a/pypy
Python | 767 lines | 762 code | 5 blank | 0 comment | 1 complexity | 1c70ed3b798734872e641b07a1159734 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 func_with_new_name
  8. DEBUG_ELIDABLE_FUNCTIONS = False
  9. def elidable(func):
  10. """ Decorate a function as "trace-elidable". This means precisely that:
  11. (1) the result of the call should not change if the arguments are
  12. the same (same numbers or same pointers)
  13. (2) it's fine to remove the call completely if we can guess the result
  14. according to rule 1
  15. (3) the function call can be moved around by optimizer,
  16. but only so it'll be called earlier and not later.
  17. Most importantly it doesn't mean that an elidable function has no observable
  18. side effect, but those side effects are idempotent (ie caching).
  19. If a particular call to this function ends up raising an exception, then it
  20. is handled like a normal function call (this decorator is ignored).
  21. """
  22. if DEBUG_ELIDABLE_FUNCTIONS:
  23. cache = {}
  24. oldfunc = func
  25. def func(*args):
  26. result = oldfunc(*args) # if it raises, no caching
  27. try:
  28. oldresult = cache.setdefault(args, result)
  29. except TypeError:
  30. pass # unhashable args
  31. else:
  32. assert oldresult == result
  33. return result
  34. func._elidable_function_ = True
  35. return func
  36. def purefunction(*args, **kwargs):
  37. import warnings
  38. warnings.warn("purefunction is deprecated, use elidable instead", DeprecationWarning)
  39. return elidable(*args, **kwargs)
  40. def hint(x, **kwds):
  41. """ Hint for the JIT
  42. possible arguments are:
  43. * promote - promote the argument from a variable into a constant
  44. * promote_string - same, but promote string by *value*
  45. * access_directly - directly access a virtualizable, as a structure
  46. and don't treat it as a virtualizable
  47. * fresh_virtualizable - means that virtualizable was just allocated.
  48. Useful in say Frame.__init__ when we do want
  49. to store things directly on it. Has to come with
  50. access_directly=True
  51. """
  52. return x
  53. @specialize.argtype(0)
  54. def promote(x):
  55. return hint(x, promote=True)
  56. def promote_string(x):
  57. return hint(x, promote_string=True)
  58. def dont_look_inside(func):
  59. """ Make sure the JIT does not trace inside decorated function
  60. (it becomes a call instead)
  61. """
  62. func._jit_look_inside_ = False
  63. return func
  64. def unroll_safe(func):
  65. """ JIT can safely unroll loops in this function and this will
  66. not lead to code explosion
  67. """
  68. func._jit_unroll_safe_ = True
  69. return func
  70. def loop_invariant(func):
  71. """ Describes a function with no argument that returns an object that
  72. is always the same in a loop.
  73. Use it only if you know what you're doing.
  74. """
  75. dont_look_inside(func)
  76. func._jit_loop_invariant_ = True
  77. return func
  78. def _get_args(func):
  79. import inspect
  80. args, varargs, varkw, defaults = inspect.getargspec(func)
  81. args = ["v%s" % (i, ) for i in range(len(args))]
  82. assert varargs is None and varkw is None
  83. assert not defaults
  84. return args
  85. def elidable_promote(promote_args='all'):
  86. """ A decorator that promotes all arguments and then calls the supplied
  87. function
  88. """
  89. def decorator(func):
  90. elidable(func)
  91. args = _get_args(func)
  92. argstring = ", ".join(args)
  93. code = ["def f(%s):\n" % (argstring, )]
  94. if promote_args != 'all':
  95. args = [('v%d' % int(i)) for i in promote_args.split(",")]
  96. for arg in args:
  97. code.append(" %s = hint(%s, promote=True)\n" % (arg, arg))
  98. code.append(" return func(%s)\n" % (argstring, ))
  99. d = {"func": func, "hint": hint}
  100. exec py.code.Source("\n".join(code)).compile() in d
  101. result = d["f"]
  102. result.func_name = func.func_name + "_promote"
  103. return result
  104. return decorator
  105. def purefunction_promote(*args, **kwargs):
  106. import warnings
  107. warnings.warn("purefunction_promote is deprecated, use elidable_promote instead", DeprecationWarning)
  108. return elidable_promote(*args, **kwargs)
  109. def look_inside_iff(predicate):
  110. """
  111. look inside (including unrolling loops) the target function, if and only if
  112. predicate(*args) returns True
  113. """
  114. def inner(func):
  115. func = unroll_safe(func)
  116. # When we return the new function, it might be specialized in some
  117. # way. We "propogate" this specialization by using
  118. # specialize:call_location on relevant functions.
  119. for thing in [func, predicate]:
  120. thing._annspecialcase_ = "specialize:call_location"
  121. args = _get_args(func)
  122. d = {
  123. "dont_look_inside": dont_look_inside,
  124. "predicate": predicate,
  125. "func": func,
  126. "we_are_jitted": we_are_jitted,
  127. }
  128. exec py.code.Source("""
  129. @dont_look_inside
  130. def trampoline(%(arguments)s):
  131. return func(%(arguments)s)
  132. if hasattr(func, "oopspec"):
  133. # XXX: This seems like it should be here, but it causes errors.
  134. # trampoline.oopspec = func.oopspec
  135. del func.oopspec
  136. trampoline.__name__ = func.__name__ + "_trampoline"
  137. trampoline._annspecialcase_ = "specialize:call_location"
  138. def f(%(arguments)s):
  139. if not we_are_jitted() or predicate(%(arguments)s):
  140. return func(%(arguments)s)
  141. else:
  142. return trampoline(%(arguments)s)
  143. f.__name__ = func.__name__ + "_look_inside_iff"
  144. """ % {"arguments": ", ".join(args)}).compile() in d
  145. return d["f"]
  146. return inner
  147. def oopspec(spec):
  148. def decorator(func):
  149. func.oopspec = spec
  150. return func
  151. return decorator
  152. @oopspec("jit.isconstant(value)")
  153. def isconstant(value):
  154. """
  155. While tracing, returns whether or not the value is currently known to be
  156. constant. This is not perfect, values can become constant later. Mostly for
  157. use with @look_inside_iff.
  158. This is for advanced usage only.
  159. """
  160. return NonConstant(False)
  161. isconstant._annspecialcase_ = "specialize:call_location"
  162. @oopspec("jit.isvirtual(value)")
  163. def isvirtual(value):
  164. """
  165. Returns if this value is virtual, while tracing, it's relatively
  166. conservative and will miss some cases.
  167. This is for advanced usage only.
  168. """
  169. return NonConstant(False)
  170. isvirtual._annspecialcase_ = "specialize:call_location"
  171. class Entry(ExtRegistryEntry):
  172. _about_ = hint
  173. def compute_result_annotation(self, s_x, **kwds_s):
  174. from pypy.annotation import model as annmodel
  175. s_x = annmodel.not_const(s_x)
  176. access_directly = 's_access_directly' in kwds_s
  177. fresh_virtualizable = 's_fresh_virtualizable' in kwds_s
  178. if access_directly or fresh_virtualizable:
  179. assert access_directly, "lone fresh_virtualizable hint"
  180. if isinstance(s_x, annmodel.SomeInstance):
  181. from pypy.objspace.flow.model import Constant
  182. classdesc = s_x.classdef.classdesc
  183. virtualizable = classdesc.read_attribute('_virtualizable2_',
  184. Constant(None)).value
  185. if virtualizable is not None:
  186. flags = s_x.flags.copy()
  187. flags['access_directly'] = True
  188. if fresh_virtualizable:
  189. flags['fresh_virtualizable'] = True
  190. s_x = annmodel.SomeInstance(s_x.classdef,
  191. s_x.can_be_None,
  192. flags)
  193. return s_x
  194. def specialize_call(self, hop, **kwds_i):
  195. from pypy.rpython.lltypesystem import lltype
  196. hints = {}
  197. for key, index in kwds_i.items():
  198. s_value = hop.args_s[index]
  199. if not s_value.is_constant():
  200. from pypy.rpython.error import TyperError
  201. raise TyperError("hint %r is not constant" % (key,))
  202. assert key.startswith('i_')
  203. hints[key[2:]] = s_value.const
  204. v = hop.inputarg(hop.args_r[0], arg=0)
  205. c_hint = hop.inputconst(lltype.Void, hints)
  206. hop.exception_cannot_occur()
  207. return hop.genop('hint', [v, c_hint], resulttype=v.concretetype)
  208. def we_are_jitted():
  209. """ Considered as true during tracing and blackholing,
  210. so its consquences are reflected into jitted code """
  211. return False
  212. _we_are_jitted = CDefinedIntSymbolic('0 /* we are not jitted here */',
  213. default=0)
  214. class Entry(ExtRegistryEntry):
  215. _about_ = we_are_jitted
  216. def compute_result_annotation(self):
  217. from pypy.annotation import model as annmodel
  218. return annmodel.SomeInteger(nonneg=True)
  219. def specialize_call(self, hop):
  220. from pypy.rpython.lltypesystem import lltype
  221. hop.exception_cannot_occur()
  222. return hop.inputconst(lltype.Signed, _we_are_jitted)
  223. def current_trace_length():
  224. """During JIT tracing, returns the current trace length (as a constant).
  225. If not tracing, returns -1."""
  226. if NonConstant(False):
  227. return 73
  228. return -1
  229. current_trace_length.oopspec = 'jit.current_trace_length()'
  230. def jit_debug(string, arg1=-sys.maxint-1, arg2=-sys.maxint-1,
  231. arg3=-sys.maxint-1, arg4=-sys.maxint-1):
  232. """When JITted, cause an extra operation JIT_DEBUG to appear in
  233. the graphs. Should not be left after debugging."""
  234. keepalive_until_here(string) # otherwise the whole function call is removed
  235. jit_debug.oopspec = 'jit.debug(string, arg1, arg2, arg3, arg4)'
  236. def assert_green(value):
  237. """Very strong assert: checks that 'value' is a green
  238. (a JIT compile-time constant)."""
  239. keepalive_until_here(value)
  240. assert_green._annspecialcase_ = 'specialize:argtype(0)'
  241. assert_green.oopspec = 'jit.assert_green(value)'
  242. class AssertGreenFailed(Exception):
  243. pass
  244. # ____________________________________________________________
  245. # VRefs
  246. def virtual_ref(x):
  247. """Creates a 'vref' object that contains a reference to 'x'. Calls
  248. to virtual_ref/virtual_ref_finish must be properly nested. The idea
  249. is that the object 'x' is supposed to be JITted as a virtual between
  250. the calls to virtual_ref and virtual_ref_finish, but the 'vref'
  251. object can escape at any point in time. If at runtime it is
  252. dereferenced (by the call syntax 'vref()'), it returns 'x', which is
  253. then forced."""
  254. return DirectJitVRef(x)
  255. virtual_ref.oopspec = 'virtual_ref(x)'
  256. def virtual_ref_finish(vref, x):
  257. """See docstring in virtual_ref(x)"""
  258. keepalive_until_here(x) # otherwise the whole function call is removed
  259. _virtual_ref_finish(vref, x)
  260. virtual_ref_finish.oopspec = 'virtual_ref_finish(x)'
  261. def non_virtual_ref(x):
  262. """Creates a 'vref' that just returns x when called; nothing more special.
  263. Used for None or for frames outside JIT scope."""
  264. return DirectVRef(x)
  265. class InvalidVirtualRef(Exception):
  266. """
  267. Raised if we try to call a non-forced virtualref after the call to
  268. virtual_ref_finish
  269. """
  270. # ---------- implementation-specific ----------
  271. class DirectVRef(object):
  272. def __init__(self, x):
  273. self._x = x
  274. self._state = 'non-forced'
  275. def __call__(self):
  276. if self._state == 'non-forced':
  277. self._state = 'forced'
  278. elif self._state == 'invalid':
  279. raise InvalidVirtualRef
  280. return self._x
  281. @property
  282. def virtual(self):
  283. """A property that is True if the vref contains a virtual that would
  284. be forced by the '()' operator."""
  285. return self._state == 'non-forced'
  286. def _finish(self):
  287. if self._state == 'non-forced':
  288. self._state = 'invalid'
  289. class DirectJitVRef(DirectVRef):
  290. def __init__(self, x):
  291. assert x is not None, "virtual_ref(None) is not allowed"
  292. DirectVRef.__init__(self, x)
  293. def _virtual_ref_finish(vref, x):
  294. assert vref._x is x, "Invalid call to virtual_ref_finish"
  295. vref._finish()
  296. class Entry(ExtRegistryEntry):
  297. _about_ = (non_virtual_ref, DirectJitVRef)
  298. def compute_result_annotation(self, s_obj):
  299. from pypy.rlib import _jit_vref
  300. return _jit_vref.SomeVRef(s_obj)
  301. def specialize_call(self, hop):
  302. return hop.r_result.specialize_call(hop)
  303. class Entry(ExtRegistryEntry):
  304. _type_ = DirectVRef
  305. def compute_annotation(self):
  306. from pypy.rlib import _jit_vref
  307. assert isinstance(self.instance, DirectVRef)
  308. s_obj = self.bookkeeper.immutablevalue(self.instance())
  309. return _jit_vref.SomeVRef(s_obj)
  310. class Entry(ExtRegistryEntry):
  311. _about_ = _virtual_ref_finish
  312. def compute_result_annotation(self, s_vref, s_obj):
  313. pass
  314. def specialize_call(self, hop):
  315. pass
  316. vref_None = non_virtual_ref(None)
  317. # ____________________________________________________________
  318. # User interface for the warmspot JIT policy
  319. class JitHintError(Exception):
  320. """Inconsistency in the JIT hints."""
  321. PARAMETERS = {'threshold': 1039, # just above 1024, prime
  322. 'function_threshold': 1619, # slightly more than one above, also prime
  323. 'trace_eagerness': 200,
  324. 'trace_limit': 6000,
  325. 'inlining': 1,
  326. 'loop_longevity': 1000,
  327. 'retrace_limit': 5,
  328. 'max_retrace_guards': 15,
  329. 'enable_opts': 'all',
  330. 'decay_halflife': 40,
  331. }
  332. unroll_parameters = unrolling_iterable(PARAMETERS.items())
  333. DEFAULT = object()
  334. # ____________________________________________________________
  335. class JitDriver(object):
  336. """Base class to declare fine-grained user control on the JIT. So
  337. far, there must be a singleton instance of JitDriver. This style
  338. will allow us (later) to support a single RPython program with
  339. several independent JITting interpreters in it.
  340. """
  341. active = True # if set to False, this JitDriver is ignored
  342. virtualizables = []
  343. def __init__(self, greens=None, reds=None, virtualizables=None,
  344. get_jitcell_at=None, set_jitcell_at=None,
  345. get_printable_location=None, confirm_enter_jit=None,
  346. can_never_inline=None, should_unroll_one_iteration=None):
  347. if greens is not None:
  348. self.greens = greens
  349. if reds is not None:
  350. self.reds = reds
  351. if not hasattr(self, 'greens') or not hasattr(self, 'reds'):
  352. raise AttributeError("no 'greens' or 'reds' supplied")
  353. if virtualizables is not None:
  354. self.virtualizables = virtualizables
  355. for v in self.virtualizables:
  356. assert v in self.reds
  357. self._alllivevars = dict.fromkeys(
  358. [name for name in self.greens + self.reds if '.' not in name])
  359. self._make_extregistryentries()
  360. self.get_jitcell_at = get_jitcell_at
  361. self.set_jitcell_at = set_jitcell_at
  362. self.get_printable_location = get_printable_location
  363. self.confirm_enter_jit = confirm_enter_jit
  364. self.can_never_inline = can_never_inline
  365. self.should_unroll_one_iteration = should_unroll_one_iteration
  366. def _freeze_(self):
  367. return True
  368. def jit_merge_point(_self, **livevars):
  369. # special-cased by ExtRegistryEntry
  370. assert dict.fromkeys(livevars) == _self._alllivevars
  371. def can_enter_jit(_self, **livevars):
  372. # special-cased by ExtRegistryEntry
  373. assert dict.fromkeys(livevars) == _self._alllivevars
  374. def loop_header(self):
  375. # special-cased by ExtRegistryEntry
  376. pass
  377. def on_compile(self, logger, looptoken, operations, type, *greenargs):
  378. """ A hook called when loop is compiled. Overwrite
  379. for your own jitdriver if you want to do something special, like
  380. call applevel code
  381. """
  382. def on_compile_bridge(self, logger, orig_looptoken, operations, n):
  383. """ A hook called when a bridge is compiled. Overwrite
  384. for your own jitdriver if you want to do something special
  385. """
  386. # note: if you overwrite this functions with the above signature it'll
  387. # work, but the *greenargs is different for each jitdriver, so we
  388. # can't share the same methods
  389. del on_compile
  390. del on_compile_bridge
  391. def _make_extregistryentries(self):
  392. # workaround: we cannot declare ExtRegistryEntries for functions
  393. # used as methods of a frozen object, but we can attach the
  394. # bound methods back to 'self' and make ExtRegistryEntries
  395. # specifically for them.
  396. self.jit_merge_point = self.jit_merge_point
  397. self.can_enter_jit = self.can_enter_jit
  398. self.loop_header = self.loop_header
  399. class Entry(ExtEnterLeaveMarker):
  400. _about_ = (self.jit_merge_point, self.can_enter_jit)
  401. class Entry(ExtLoopHeader):
  402. _about_ = self.loop_header
  403. def _set_param(driver, name, value):
  404. # special-cased by ExtRegistryEntry
  405. # (internal, must receive a constant 'name')
  406. # if value is DEFAULT, sets the default value.
  407. assert name in PARAMETERS
  408. @specialize.arg(0, 1)
  409. def set_param(driver, name, value):
  410. """Set one of the tunable JIT parameter. Driver can be None, then all
  411. drivers have this set """
  412. _set_param(driver, name, value)
  413. @specialize.arg(0, 1)
  414. def set_param_to_default(driver, name):
  415. """Reset one of the tunable JIT parameters to its default value."""
  416. _set_param(driver, name, DEFAULT)
  417. def set_user_param(driver, text):
  418. """Set the tunable JIT parameters from a user-supplied string
  419. following the format 'param=value,param=value', or 'off' to
  420. disable the JIT. For programmatic setting of parameters, use
  421. directly JitDriver.set_param().
  422. """
  423. if text == 'off':
  424. set_param(driver, 'threshold', -1)
  425. set_param(driver, 'function_threshold', -1)
  426. return
  427. if text == 'default':
  428. for name1, _ in unroll_parameters:
  429. set_param_to_default(driver, name1)
  430. return
  431. for s in text.split(','):
  432. s = s.strip(' ')
  433. parts = s.split('=')
  434. if len(parts) != 2:
  435. raise ValueError
  436. name = parts[0]
  437. value = parts[1]
  438. if name == 'enable_opts':
  439. set_param(driver, 'enable_opts', value)
  440. else:
  441. for name1, _ in unroll_parameters:
  442. if name1 == name and name1 != 'enable_opts':
  443. try:
  444. set_param(driver, name1, int(value))
  445. except ValueError:
  446. raise
  447. set_user_param._annspecialcase_ = 'specialize:arg(0)'
  448. # ____________________________________________________________
  449. #
  450. # Annotation and rtyping of some of the JitDriver methods
  451. class BaseJitCell(object):
  452. __slots__ = ()
  453. class ExtEnterLeaveMarker(ExtRegistryEntry):
  454. # Replace a call to myjitdriver.jit_merge_point(**livevars)
  455. # with an operation jit_marker('jit_merge_point', myjitdriver, livevars...)
  456. # Also works with can_enter_jit.
  457. def compute_result_annotation(self, **kwds_s):
  458. from pypy.annotation import model as annmodel
  459. if self.instance.__name__ == 'jit_merge_point':
  460. self.annotate_hooks(**kwds_s)
  461. driver = self.instance.im_self
  462. keys = kwds_s.keys()
  463. keys.sort()
  464. expected = ['s_' + name for name in driver.greens + driver.reds
  465. if '.' not in name]
  466. expected.sort()
  467. if keys != expected:
  468. raise JitHintError("%s expects the following keyword "
  469. "arguments: %s" % (self.instance,
  470. expected))
  471. try:
  472. cache = self.bookkeeper._jit_annotation_cache[driver]
  473. except AttributeError:
  474. cache = {}
  475. self.bookkeeper._jit_annotation_cache = {driver: cache}
  476. except KeyError:
  477. cache = {}
  478. self.bookkeeper._jit_annotation_cache[driver] = cache
  479. for key, s_value in kwds_s.items():
  480. s_previous = cache.get(key, annmodel.s_ImpossibleValue)
  481. s_value = annmodel.unionof(s_previous, s_value)
  482. if annmodel.isdegenerated(s_value):
  483. raise JitHintError("mixing incompatible types in argument %s"
  484. " of jit_merge_point/can_enter_jit" %
  485. key[2:])
  486. cache[key] = s_value
  487. # add the attribute _dont_reach_me_in_del_ (see pypy.rpython.rclass)
  488. try:
  489. graph = self.bookkeeper.position_key[0]
  490. graph.func._dont_reach_me_in_del_ = True
  491. except (TypeError, AttributeError):
  492. pass
  493. return annmodel.s_None
  494. def annotate_hooks(self, **kwds_s):
  495. driver = self.instance.im_self
  496. s_jitcell = self.bookkeeper.valueoftype(BaseJitCell)
  497. h = self.annotate_hook
  498. h(driver.get_jitcell_at, driver.greens, **kwds_s)
  499. h(driver.set_jitcell_at, driver.greens, [s_jitcell], **kwds_s)
  500. h(driver.get_printable_location, driver.greens, **kwds_s)
  501. def annotate_hook(self, func, variables, args_s=[], **kwds_s):
  502. if func is None:
  503. return
  504. bk = self.bookkeeper
  505. s_func = bk.immutablevalue(func)
  506. uniquekey = 'jitdriver.%s' % func.func_name
  507. args_s = args_s[:]
  508. for name in variables:
  509. if '.' not in name:
  510. s_arg = kwds_s['s_' + name]
  511. else:
  512. objname, fieldname = name.split('.')
  513. s_instance = kwds_s['s_' + objname]
  514. attrdef = s_instance.classdef.find_attribute(fieldname)
  515. position = self.bookkeeper.position_key
  516. attrdef.read_locations[position] = True
  517. s_arg = attrdef.getvalue()
  518. assert s_arg is not None
  519. args_s.append(s_arg)
  520. bk.emulate_pbc_call(uniquekey, s_func, args_s)
  521. def get_getfield_op(self, rtyper):
  522. if rtyper.type_system.name == 'ootypesystem':
  523. return 'oogetfield'
  524. else:
  525. return 'getfield'
  526. def specialize_call(self, hop, **kwds_i):
  527. # XXX to be complete, this could also check that the concretetype
  528. # of the variables are the same for each of the calls.
  529. from pypy.rpython.error import TyperError
  530. from pypy.rpython.lltypesystem import lltype
  531. driver = self.instance.im_self
  532. greens_v = []
  533. reds_v = []
  534. for name in driver.greens:
  535. if '.' not in name:
  536. i = kwds_i['i_' + name]
  537. r_green = hop.args_r[i]
  538. v_green = hop.inputarg(r_green, arg=i)
  539. else:
  540. objname, fieldname = name.split('.') # see test_green_field
  541. assert objname in driver.reds
  542. i = kwds_i['i_' + objname]
  543. s_red = hop.args_s[i]
  544. r_red = hop.args_r[i]
  545. while True:
  546. try:
  547. mangled_name, r_field = r_red._get_field(fieldname)
  548. break
  549. except KeyError:
  550. pass
  551. assert r_red.rbase is not None, (
  552. "field %r not found in %r" % (name,
  553. r_red.lowleveltype.TO))
  554. r_red = r_red.rbase
  555. if hop.rtyper.type_system.name == 'ootypesystem':
  556. GTYPE = r_red.lowleveltype
  557. else:
  558. GTYPE = r_red.lowleveltype.TO
  559. assert GTYPE._immutable_field(mangled_name), (
  560. "field %r must be declared as immutable" % name)
  561. if not hasattr(driver, 'll_greenfields'):
  562. driver.ll_greenfields = {}
  563. driver.ll_greenfields[name] = GTYPE, mangled_name
  564. #
  565. v_red = hop.inputarg(r_red, arg=i)
  566. c_llname = hop.inputconst(lltype.Void, mangled_name)
  567. getfield_op = self.get_getfield_op(hop.rtyper)
  568. v_green = hop.genop(getfield_op, [v_red, c_llname],
  569. resulttype=r_field)
  570. s_green = s_red.classdef.about_attribute(fieldname)
  571. assert s_green is not None
  572. hop.rtyper.annotator.setbinding(v_green, s_green)
  573. greens_v.append(v_green)
  574. for name in driver.reds:
  575. i = kwds_i['i_' + name]
  576. r_red = hop.args_r[i]
  577. v_red = hop.inputarg(r_red, arg=i)
  578. reds_v.append(v_red)
  579. hop.exception_cannot_occur()
  580. vlist = [hop.inputconst(lltype.Void, self.instance.__name__),
  581. hop.inputconst(lltype.Void, driver)]
  582. vlist.extend(greens_v)
  583. vlist.extend(reds_v)
  584. return hop.genop('jit_marker', vlist,
  585. resulttype=lltype.Void)
  586. class ExtLoopHeader(ExtRegistryEntry):
  587. # Replace a call to myjitdriver.loop_header()
  588. # with an operation jit_marker('loop_header', myjitdriver).
  589. def compute_result_annotation(self, **kwds_s):
  590. from pypy.annotation import model as annmodel
  591. return annmodel.s_None
  592. def specialize_call(self, hop):
  593. from pypy.rpython.lltypesystem import lltype
  594. driver = self.instance.im_self
  595. hop.exception_cannot_occur()
  596. vlist = [hop.inputconst(lltype.Void, 'loop_header'),
  597. hop.inputconst(lltype.Void, driver)]
  598. return hop.genop('jit_marker', vlist,
  599. resulttype=lltype.Void)
  600. class ExtSetParam(ExtRegistryEntry):
  601. _about_ = _set_param
  602. def compute_result_annotation(self, s_driver, s_name, s_value):
  603. from pypy.annotation import model as annmodel
  604. assert s_name.is_constant()
  605. if not self.bookkeeper.immutablevalue(DEFAULT).contains(s_value):
  606. if s_name.const == 'enable_opts':
  607. assert annmodel.SomeString(can_be_None=True).contains(s_value)
  608. else:
  609. assert annmodel.SomeInteger().contains(s_value)
  610. return annmodel.s_None
  611. def specialize_call(self, hop):
  612. from pypy.rpython.lltypesystem import lltype
  613. from pypy.rpython.lltypesystem.rstr import string_repr
  614. from pypy.objspace.flow.model import Constant
  615. hop.exception_cannot_occur()
  616. driver = hop.inputarg(lltype.Void, arg=0)
  617. name = hop.args_s[1].const
  618. if name == 'enable_opts':
  619. repr = string_repr
  620. else:
  621. repr = lltype.Signed
  622. if (isinstance(hop.args_v[2], Constant) and
  623. hop.args_v[2].value is DEFAULT):
  624. value = PARAMETERS[name]
  625. v_value = hop.inputconst(repr, value)
  626. else:
  627. v_value = hop.inputarg(repr, arg=2)
  628. vlist = [hop.inputconst(lltype.Void, "set_param"),
  629. driver,
  630. hop.inputconst(lltype.Void, name),
  631. v_value]
  632. return hop.genop('jit_marker', vlist,
  633. resulttype=lltype.Void)
  634. def record_known_class(value, cls):
  635. """
  636. Assure the JIT that value is an instance of cls. This is not a precise
  637. class check, unlike a guard_class.
  638. """
  639. assert isinstance(value, cls)
  640. class Entry(ExtRegistryEntry):
  641. _about_ = record_known_class
  642. def compute_result_annotation(self, s_inst, s_cls):
  643. from pypy.annotation import model as annmodel
  644. assert s_cls.is_constant()
  645. assert not s_inst.can_be_none()
  646. assert isinstance(s_inst, annmodel.SomeInstance)
  647. def specialize_call(self, hop):
  648. from pypy.rpython.lltypesystem import lltype, rclass
  649. classrepr = rclass.get_type_repr(hop.rtyper)
  650. hop.exception_cannot_occur()
  651. v_inst = hop.inputarg(hop.args_r[0], arg=0)
  652. v_cls = hop.inputarg(classrepr, arg=1)
  653. return hop.genop('jit_record_known_class', [v_inst, v_cls],
  654. resulttype=lltype.Void)