| 1 |
import sys |
| 2 |
|
| 3 |
import py |
| 4 |
|
| 5 |
from rpython.rlib.nonconst import NonConstant |
| 6 |
from rpython.rlib.objectmodel import CDefinedIntSymbolic, keepalive_until_here, specialize, not_rpython, we_are_translated |
| 7 |
from rpython.rlib.unroll import unrolling_iterable |
| 8 |
from rpython.rtyper.extregistry import ExtRegistryEntry |
| 9 |
from rpython.tool.sourcetools import rpython_wrapper |
| 10 |
|
| 11 |
DEBUG_ELIDABLE_FUNCTIONS = False |
| 12 |
|
| 13 |
|
| 14 |
def elidable(func): |
| 15 |
""" Decorate a function as "trace-elidable". Usually this means simply that |
| 16 |
the function is constant-foldable, i.e. is pure and has no side-effects. |
| 17 |
This also has the effect that the inside of the function will never be |
| 18 |
traced. |
| 19 |
|
| 20 |
In some situations it is ok to use this decorator if the function *has* |
| 21 |
side effects, as long as these side-effects are idempotent. A typical |
| 22 |
example for this would be a cache. |
| 23 |
|
| 24 |
To be totally precise: |
| 25 |
|
| 26 |
(1) the result of the call should not change if the arguments are |
| 27 |
the same (same numbers or same pointers) |
| 28 |
(2) it's fine to remove the call completely if we can guess the result |
| 29 |
according to rule 1 |
| 30 |
(3) the function call can be moved around by optimizer, |
| 31 |
but only so it'll be called earlier and not later. |
| 32 |
|
| 33 |
Most importantly it doesn't mean that an elidable function has no observable |
| 34 |
side effect, but those side effects are idempotent (ie caching). |
| 35 |
If a particular call to this function ends up raising an exception, then it |
| 36 |
is handled like a normal function call (this decorator is ignored). |
| 37 |
|
| 38 |
Note also that this optimisation will only take effect if the arguments |
| 39 |
to the function are proven constant. By this we mean each argument |
| 40 |
is either: |
| 41 |
|
| 42 |
1) a constant from the RPython source code (e.g. "x = 2") |
| 43 |
2) easily shown to be constant by the tracer |
| 44 |
3) a promoted variable (see @jit.promote) |
| 45 |
|
| 46 |
Examples of condition 2: |
| 47 |
|
| 48 |
* i1 = int_eq(i0, 0), guard_true(i1) |
| 49 |
* i1 = getfield_pc_pure(<constant>, "immutable_field") |
| 50 |
|
| 51 |
In both cases, the tracer will deduce that i1 is constant. |
| 52 |
|
| 53 |
Failing the above conditions, the function is not traced into (as if the |
| 54 |
function were decorated with @jit.dont_look_inside). Generally speaking, |
| 55 |
it is a bad idea to liberally sprinkle @jit.elidable without a concrete |
| 56 |
need. |
| 57 |
""" |
| 58 |
if DEBUG_ELIDABLE_FUNCTIONS: |
| 59 |
cache = {} |
| 60 |
oldfunc = func |
| 61 |
def func(*args): |
| 62 |
result = oldfunc(*args) |
| 63 |
try: |
| 64 |
oldresult = cache.setdefault(args, result) |
| 65 |
except TypeError: |
| 66 |
pass |
| 67 |
else: |
| 68 |
assert oldresult == result |
| 69 |
return result |
| 70 |
if getattr(func, '_jit_unroll_safe_', False): |
| 71 |
raise TypeError("it does not make sense for %s to be both elidable and unroll_safe" % func) |
| 72 |
func._elidable_function_ = True |
| 73 |
return func |
| 74 |
|
| 75 |
def purefunction(*args, **kwargs): |
| 76 |
import warnings |
| 77 |
warnings.warn("purefunction is deprecated, use elidable instead", DeprecationWarning) |
| 78 |
return elidable(*args, **kwargs) |
| 79 |
|
| 80 |
def hint(x, **kwds): |
| 81 |
""" Hint for the JIT |
| 82 |
|
| 83 |
possible arguments are: |
| 84 |
|
| 85 |
* promote - promote the argument from a variable into a constant |
| 86 |
* promote_string - same, but promote string by *value* |
| 87 |
* promote_unicode - same, but promote unicode string by *value* |
| 88 |
* access_directly - directly access a virtualizable, as a structure |
| 89 |
and don't treat it as a virtualizable |
| 90 |
* fresh_virtualizable - means that virtualizable was just allocated. |
| 91 |
Useful in say Frame.__init__ when we do want |
| 92 |
to store things directly on it. Has to come with |
| 93 |
access_directly=True |
| 94 |
* force_virtualizable - a performance hint to force the virtualizable early |
| 95 |
(useful e.g. for python generators that are going |
| 96 |
to be read later anyway) |
| 97 |
""" |
| 98 |
return x |
| 99 |
|
| 100 |
@specialize.argtype(0) |
| 101 |
def promote(x): |
| 102 |
""" |
| 103 |
Promotes a variable in a trace to a constant. |
| 104 |
|
| 105 |
When a variable is promoted, a guard is inserted that assumes the value |
| 106 |
of the variable is constant. In other words, the value of the variable |
| 107 |
is checked to be the same as it was at trace collection time. Once the |
| 108 |
variable is assumed constant, more aggressive constant folding may be |
| 109 |
possible. |
| 110 |
|
| 111 |
If however, the guard fails frequently, a bridge will be generated |
| 112 |
this time assuming the constancy of the variable under its new value. |
| 113 |
This optimisation should be used carefully, as in extreme cases, where |
| 114 |
the promoted variable is not very constant at all, code explosion can |
| 115 |
occur. In turn this leads to poor performance. |
| 116 |
|
| 117 |
Overpromotion is characterised by a cascade of bridges branching from |
| 118 |
very similar guard_value opcodes, each guarding the same variable under |
| 119 |
a different value. |
| 120 |
|
| 121 |
Note that promoting a string with @jit.promote will promote by pointer. |
| 122 |
To promote a string by value, see @jit.promote_string. |
| 123 |
|
| 124 |
""" |
| 125 |
return hint(x, promote=True) |
| 126 |
|
| 127 |
def promote_string(x): |
| 128 |
return hint(x, promote_string=True) |
| 129 |
|
| 130 |
def promote_unicode(x): |
| 131 |
return hint(x, promote_unicode=True) |
| 132 |
|
| 133 |
def dont_look_inside(func): |
| 134 |
""" Make sure the JIT does not trace inside decorated function |
| 135 |
(it becomes a call instead) |
| 136 |
""" |
| 137 |
if getattr(func, '_jit_unroll_safe_', False): |
| 138 |
raise TypeError("it does not make sense for %s to be both dont_look_inside and unroll_safe" % func) |
| 139 |
func._jit_look_inside_ = False |
| 140 |
return func |
| 141 |
|
| 142 |
def look_inside(func): |
| 143 |
""" Make sure the JIT traces inside decorated function, even |
| 144 |
if the rest of the module is not visible to the JIT |
| 145 |
""" |
| 146 |
import warnings |
| 147 |
warnings.warn("look_inside is deprecated", DeprecationWarning) |
| 148 |
func._jit_look_inside_ = True |
| 149 |
return func |
| 150 |
|
| 151 |
def unroll_safe(func): |
| 152 |
""" JIT can safely unroll loops in this function and this will |
| 153 |
not lead to code explosion |
| 154 |
""" |
| 155 |
if getattr(func, '_elidable_function_', False): |
| 156 |
raise TypeError("it does not make sense for %s to be both elidable and unroll_safe" % func) |
| 157 |
if not getattr(func, '_jit_look_inside_', True): |
| 158 |
raise TypeError("it does not make sense for %s to be both unroll_safe and dont_look_inside" % func) |
| 159 |
func._jit_unroll_safe_ = True |
| 160 |
return func |
| 161 |
|
| 162 |
def loop_invariant(func): |
| 163 |
""" Describes a function with no argument that returns an object that |
| 164 |
is always the same in a loop. |
| 165 |
|
| 166 |
Use it only if you know what you're doing. |
| 167 |
""" |
| 168 |
dont_look_inside(func) |
| 169 |
func._jit_loop_invariant_ = True |
| 170 |
return func |
| 171 |
|
| 172 |
def _get_args(func): |
| 173 |
import inspect |
| 174 |
|
| 175 |
args, varargs, varkw, defaults = inspect.getargspec(func) |
| 176 |
assert varargs is None and varkw is None |
| 177 |
assert not defaults |
| 178 |
return args |
| 179 |
|
| 180 |
def elidable_promote(promote_args='all'): |
| 181 |
""" A decorator that promotes all arguments and then calls the supplied |
| 182 |
function |
| 183 |
""" |
| 184 |
def decorator(func): |
| 185 |
elidable(func) |
| 186 |
args = _get_args(func) |
| 187 |
argstring = ", ".join(args) |
| 188 |
code = ["def f(%s):\n" % (argstring, )] |
| 189 |
if promote_args != 'all': |
| 190 |
args = [args[int(i)] for i in promote_args.split(",")] |
| 191 |
for arg in args: |
| 192 |
code.append( |
| 193 |
" %s = hint(%s, promote=True, promote_string=True)\n" % |
| 194 |
(arg, arg)) |
| 195 |
code.append(" return _orig_func_unlikely_name(%s)\n" % (argstring, )) |
| 196 |
d = {"_orig_func_unlikely_name": func, "hint": hint} |
| 197 |
exec py.code.Source("\n".join(code)).compile() in d |
| 198 |
result = d["f"] |
| 199 |
result.__name__ = func.__name__ + "_promote" |
| 200 |
return result |
| 201 |
return decorator |
| 202 |
|
| 203 |
def purefunction_promote(*args, **kwargs): |
| 204 |
import warnings |
| 205 |
warnings.warn("purefunction_promote is deprecated, use elidable_promote instead", DeprecationWarning) |
| 206 |
return elidable_promote(*args, **kwargs) |
| 207 |
|
| 208 |
def look_inside_iff(predicate): |
| 209 |
""" |
| 210 |
look inside (including unrolling loops) the target function, if and only if |
| 211 |
predicate(*args) returns True |
| 212 |
""" |
| 213 |
def inner(func): |
| 214 |
func = unroll_safe(func) |
| 215 |
|
| 216 |
|
| 217 |
|
| 218 |
for thing in [func, predicate]: |
| 219 |
thing._annspecialcase_ = "specialize:call_location" |
| 220 |
|
| 221 |
args = _get_args(func) |
| 222 |
predicateargs = _get_args(predicate) |
| 223 |
assert len(args) == len(predicateargs), "%s and predicate %s need the same numbers of arguments" % (func, predicate) |
| 224 |
d = { |
| 225 |
"dont_look_inside": dont_look_inside, |
| 226 |
"predicate": predicate, |
| 227 |
"func": func, |
| 228 |
"we_are_jitted": we_are_jitted, |
| 229 |
} |
| 230 |
exec py.code.Source(""" |
| 231 |
@dont_look_inside |
| 232 |
def trampoline(%(arguments)s): |
| 233 |
return func(%(arguments)s) |
| 234 |
if hasattr(func, "oopspec"): |
| 235 |
trampoline.oopspec = func.oopspec |
| 236 |
del func.oopspec |
| 237 |
trampoline.__name__ = func.__name__ + "_trampoline" |
| 238 |
trampoline._annspecialcase_ = "specialize:call_location" |
| 239 |
|
| 240 |
def f(%(arguments)s): |
| 241 |
if not we_are_jitted() or predicate(%(arguments)s): |
| 242 |
return func(%(arguments)s) |
| 243 |
else: |
| 244 |
return trampoline(%(arguments)s) |
| 245 |
f.__name__ = func.__name__ + "_look_inside_iff" |
| 246 |
""" % {"arguments": ", ".join(args)}).compile() in d |
| 247 |
return d["f"] |
| 248 |
return inner |
| 249 |
|
| 250 |
def oopspec(spec): |
| 251 |
""" The JIT compiler won't look inside this decorated function, |
| 252 |
but instead during translation, rewrites it according to the handler in |
| 253 |
rpython/jit/codewriter/jtransform.py. |
| 254 |
""" |
| 255 |
def decorator(func): |
| 256 |
func.oopspec = spec |
| 257 |
return func |
| 258 |
return decorator |
| 259 |
|
| 260 |
def not_in_trace(func): |
| 261 |
"""A decorator for a function with no return value. It makes the |
| 262 |
function call disappear from the jit traces. It is still called in |
| 263 |
interpreted mode, and by the jit tracing and blackholing, but not |
| 264 |
by the final assembler.""" |
| 265 |
func.oopspec = "jit.not_in_trace()" |
| 266 |
return func |
| 267 |
|
| 268 |
|
| 269 |
@oopspec("jit.isconstant(value)") |
| 270 |
@specialize.call_location() |
| 271 |
def isconstant(value): |
| 272 |
""" |
| 273 |
While tracing, returns whether or not the value is currently known to be |
| 274 |
constant. This is not perfect, values can become constant later. Mostly for |
| 275 |
use with @look_inside_iff. |
| 276 |
|
| 277 |
This is for advanced usage only. |
| 278 |
""" |
| 279 |
return NonConstant(False) |
| 280 |
|
| 281 |
@oopspec("jit.isvirtual(value)") |
| 282 |
@specialize.call_location() |
| 283 |
def isvirtual(value): |
| 284 |
""" |
| 285 |
Returns if this value is virtual, while tracing. can be wrong in both |
| 286 |
directions. it tries to be conservative by default, but can also sometimes |
| 287 |
return True for something that does not end up completely virtual (eg a |
| 288 |
resizable list). |
| 289 |
|
| 290 |
This is for advanced usage only. |
| 291 |
""" |
| 292 |
return NonConstant(False) |
| 293 |
|
| 294 |
@specialize.call_location() |
| 295 |
def loop_unrolling_heuristic(lst, size, cutoff=2): |
| 296 |
""" In which cases iterating over items of lst can be unrolled |
| 297 |
""" |
| 298 |
|
| 299 |
|
| 300 |
|
| 301 |
return size == 0 or (isconstant(size) and (isvirtual(lst) or size <= cutoff)) |
| 302 |
|
| 303 |
class Entry(ExtRegistryEntry): |
| 304 |
_about_ = hint |
| 305 |
|
| 306 |
def compute_result_annotation(self, s_x, **kwds_s): |
| 307 |
from rpython.annotator import model as annmodel |
| 308 |
s_x = annmodel.not_const(s_x) |
| 309 |
s_access_directly = kwds_s.get('s_access_directly') |
| 310 |
fresh_virtualizable = 's_fresh_virtualizable' in kwds_s |
| 311 |
if s_access_directly or fresh_virtualizable: |
| 312 |
assert isinstance(s_access_directly, annmodel.SomeBool) and s_access_directly.is_constant() |
| 313 |
assert s_access_directly, "lone fresh_virtualizable hint" |
| 314 |
if isinstance(s_x, annmodel.SomeInstance): |
| 315 |
from rpython.flowspace.model import Constant |
| 316 |
classdesc = s_x.classdef.classdesc |
| 317 |
virtualizable = classdesc.get_param('_virtualizable_') |
| 318 |
if s_access_directly.const == True and virtualizable is not None: |
| 319 |
flags = s_x.flags.copy() |
| 320 |
flags['access_directly'] = True |
| 321 |
if fresh_virtualizable: |
| 322 |
flags['fresh_virtualizable'] = True |
| 323 |
s_x = annmodel.SomeInstance(s_x.classdef, |
| 324 |
s_x.can_be_None, |
| 325 |
flags) |
| 326 |
else: |
| 327 |
assert s_access_directly.const == False or virtualizable is None |
| 328 |
if 'access_directly' in s_x.flags or 'fresh_virtualizable' in s_x.flags: |
| 329 |
flags = s_x.flags.copy() |
| 330 |
if 'access_directly' in flags: |
| 331 |
del flags['access_directly'] |
| 332 |
if 'fresh_virtualizable' in flags: |
| 333 |
del flags['fresh_virtualizable'] |
| 334 |
s_x = annmodel.SomeInstance(s_x.classdef, |
| 335 |
s_x.can_be_None, |
| 336 |
flags) |
| 337 |
return s_x |
| 338 |
|
| 339 |
def specialize_call(self, hop, **kwds_i): |
| 340 |
from rpython.rtyper.lltypesystem import lltype |
| 341 |
hints = {} |
| 342 |
for key, index in kwds_i.items(): |
| 343 |
s_value = hop.args_s[index] |
| 344 |
if not s_value.is_constant(): |
| 345 |
from rpython.rtyper.error import TyperError |
| 346 |
raise TyperError("hint %r is not constant" % (key,)) |
| 347 |
assert key.startswith('i_') |
| 348 |
hints[key[2:]] = s_value.const |
| 349 |
v = hop.inputarg(hop.args_r[0], arg=0) |
| 350 |
c_hint = hop.inputconst(lltype.Void, hints) |
| 351 |
hop.exception_cannot_occur() |
| 352 |
return hop.genop('hint', [v, c_hint], resulttype=v.concretetype) |
| 353 |
|
| 354 |
|
| 355 |
def we_are_jitted(): |
| 356 |
""" Considered as true during tracing and blackholing, |
| 357 |
so its consquences are reflected into jitted code """ |
| 358 |
return False |
| 359 |
|
| 360 |
_we_are_jitted = CDefinedIntSymbolic('0 /* we are not jitted here */', |
| 361 |
default=0) |
| 362 |
|
| 363 |
def _get_virtualizable_token(frame): |
| 364 |
""" An obscure API to get vable token. |
| 365 |
Used by _vmprof |
| 366 |
""" |
| 367 |
from rpython.rtyper.lltypesystem import lltype, llmemory |
| 368 |
|
| 369 |
return lltype.nullptr(llmemory.GCREF.TO) |
| 370 |
|
| 371 |
class GetVirtualizableTokenEntry(ExtRegistryEntry): |
| 372 |
_about_ = _get_virtualizable_token |
| 373 |
|
| 374 |
def compute_result_annotation(self, s_arg): |
| 375 |
from rpython.rtyper.llannotation import SomePtr |
| 376 |
from rpython.rtyper.lltypesystem import llmemory |
| 377 |
return SomePtr(llmemory.GCREF) |
| 378 |
|
| 379 |
def specialize_call(self, hop): |
| 380 |
from rpython.rtyper.lltypesystem import lltype, llmemory |
| 381 |
|
| 382 |
hop.exception_cannot_occur() |
| 383 |
T = hop.args_r[0].lowleveltype.TO |
| 384 |
v = hop.inputarg(hop.args_r[0], arg=0) |
| 385 |
while not hasattr(T, 'vable_token'): |
| 386 |
if not hasattr(T, 'super'): |
| 387 |
|
| 388 |
return hop.inputconst(llmemory.GCREF, |
| 389 |
lltype.nullptr(llmemory.GCREF.TO)) |
| 390 |
T = T.super |
| 391 |
v = hop.genop('cast_pointer', [v], resulttype=lltype.Ptr(T)) |
| 392 |
c_vable_token = hop.inputconst(lltype.Void, 'vable_token') |
| 393 |
return hop.genop('getfield', [v, c_vable_token], |
| 394 |
resulttype=llmemory.GCREF) |
| 395 |
|
| 396 |
class Entry(ExtRegistryEntry): |
| 397 |
_about_ = we_are_jitted |
| 398 |
|
| 399 |
def compute_result_annotation(self): |
| 400 |
from rpython.annotator import model as annmodel |
| 401 |
return annmodel.SomeInteger(nonneg=True) |
| 402 |
|
| 403 |
def specialize_call(self, hop): |
| 404 |
from rpython.rtyper.lltypesystem import lltype |
| 405 |
hop.exception_cannot_occur() |
| 406 |
return hop.inputconst(lltype.Signed, _we_are_jitted) |
| 407 |
|
| 408 |
@oopspec('jit.current_trace_length()') |
| 409 |
def current_trace_length(): |
| 410 |
"""During JIT tracing, returns the current trace length (as a constant). |
| 411 |
If not tracing, returns -1.""" |
| 412 |
if NonConstant(False): |
| 413 |
return 73 |
| 414 |
return -1 |
| 415 |
|
| 416 |
@oopspec('jit.debug(string, arg1, arg2, arg3, arg4)') |
| 417 |
def jit_debug(string, arg1=-sys.maxint-1, arg2=-sys.maxint-1, |
| 418 |
arg3=-sys.maxint-1, arg4=-sys.maxint-1): |
| 419 |
"""When JITted, cause an extra operation JIT_DEBUG to appear in |
| 420 |
the graphs. Should not be left after debugging.""" |
| 421 |
keepalive_until_here(string) |
| 422 |
|
| 423 |
@oopspec('jit.assert_green(value)') |
| 424 |
@specialize.argtype(0) |
| 425 |
def assert_green(value): |
| 426 |
"""Very strong assert: checks that 'value' is a green |
| 427 |
(a JIT compile-time constant).""" |
| 428 |
keepalive_until_here(value) |
| 429 |
|
| 430 |
class AssertGreenFailed(Exception): |
| 431 |
pass |
| 432 |
|
| 433 |
|
| 434 |
def jit_callback(name): |
| 435 |
"""Use as a decorator for C callback functions, to insert a |
| 436 |
jitdriver.jit_merge_point() at the start. Only for callbacks |
| 437 |
that typically invoke more app-level Python code. |
| 438 |
""" |
| 439 |
def decorate(func): |
| 440 |
from rpython.tool.sourcetools import compile2 |
| 441 |
|
| 442 |
def get_printable_location(): |
| 443 |
return name |
| 444 |
jitdriver = JitDriver(get_printable_location=get_printable_location, |
| 445 |
greens=[], reds='auto', name=name) |
| 446 |
|
| 447 |
args = ','.join(['a%d' % i for i in range(func.__code__.co_argcount)]) |
| 448 |
source = """def callback_with_jitdriver(%(args)s): |
| 449 |
jitdriver.jit_merge_point() |
| 450 |
return real_callback(%(args)s)""" % locals() |
| 451 |
miniglobals = { |
| 452 |
'jitdriver': jitdriver, |
| 453 |
'real_callback': func, |
| 454 |
} |
| 455 |
exec compile2(source) in miniglobals |
| 456 |
return miniglobals['callback_with_jitdriver'] |
| 457 |
return decorate |
| 458 |
|
| 459 |
|
| 460 |
|
| 461 |
|
| 462 |
|
| 463 |
@oopspec('virtual_ref(x)') |
| 464 |
@specialize.argtype(0) |
| 465 |
def virtual_ref(x): |
| 466 |
"""Creates a 'vref' object that contains a reference to 'x'. Calls |
| 467 |
to virtual_ref/virtual_ref_finish must be properly nested. The idea |
| 468 |
is that the object 'x' is supposed to be JITted as a virtual between |
| 469 |
the calls to virtual_ref and virtual_ref_finish, but the 'vref' |
| 470 |
object can escape at any point in time. If at runtime it is |
| 471 |
dereferenced (by the call syntax 'vref()'), it returns 'x', which is |
| 472 |
then forced.""" |
| 473 |
return DirectJitVRef(x) |
| 474 |
|
| 475 |
@oopspec('virtual_ref_finish(x)') |
| 476 |
@specialize.argtype(1) |
| 477 |
def virtual_ref_finish(vref, x): |
| 478 |
"""See docstring in virtual_ref(x)""" |
| 479 |
keepalive_until_here(x) |
| 480 |
_virtual_ref_finish(vref, x) |
| 481 |
|
| 482 |
def non_virtual_ref(x): |
| 483 |
"""Creates a 'vref' that just returns x when called; nothing more special. |
| 484 |
Used for None or for frames outside JIT scope.""" |
| 485 |
return DirectVRef(x) |
| 486 |
|
| 487 |
class InvalidVirtualRef(Exception): |
| 488 |
""" |
| 489 |
Raised if we try to call a non-forced virtualref after the call to |
| 490 |
virtual_ref_finish |
| 491 |
""" |
| 492 |
|
| 493 |
|
| 494 |
|
| 495 |
class DirectVRef(object): |
| 496 |
def __init__(self, x): |
| 497 |
self._x = x |
| 498 |
self._state = 'non-forced' |
| 499 |
|
| 500 |
def __call__(self): |
| 501 |
if self._state == 'non-forced': |
| 502 |
self._state = 'forced' |
| 503 |
elif self._state == 'invalid': |
| 504 |
raise InvalidVirtualRef |
| 505 |
return self._x |
| 506 |
|
| 507 |
@property |
| 508 |
def virtual(self): |
| 509 |
"""A property that is True if the vref contains a virtual that would |
| 510 |
be forced by the '()' operator.""" |
| 511 |
return self._state == 'non-forced' |
| 512 |
|
| 513 |
def _finish(self): |
| 514 |
if self._state == 'non-forced': |
| 515 |
self._state = 'invalid' |
| 516 |
|
| 517 |
class DirectJitVRef(DirectVRef): |
| 518 |
def __init__(self, x): |
| 519 |
assert x is not None, "virtual_ref(None) is not allowed" |
| 520 |
DirectVRef.__init__(self, x) |
| 521 |
|
| 522 |
def _virtual_ref_finish(vref, x): |
| 523 |
assert vref._x is x, "Invalid call to virtual_ref_finish" |
| 524 |
vref._finish() |
| 525 |
|
| 526 |
class Entry(ExtRegistryEntry): |
| 527 |
_about_ = (non_virtual_ref, DirectJitVRef) |
| 528 |
|
| 529 |
def compute_result_annotation(self, s_obj): |
| 530 |
from rpython.rlib import _jit_vref |
| 531 |
return _jit_vref.SomeVRef(s_obj) |
| 532 |
|
| 533 |
def specialize_call(self, hop): |
| 534 |
return hop.r_result.specialize_call(hop) |
| 535 |
|
| 536 |
class Entry(ExtRegistryEntry): |
| 537 |
_type_ = DirectVRef |
| 538 |
|
| 539 |
def compute_annotation(self): |
| 540 |
from rpython.rlib import _jit_vref |
| 541 |
assert isinstance(self.instance, DirectVRef) |
| 542 |
s_obj = self.bookkeeper.immutablevalue(self.instance()) |
| 543 |
return _jit_vref.SomeVRef(s_obj) |
| 544 |
|
| 545 |
class Entry(ExtRegistryEntry): |
| 546 |
_about_ = _virtual_ref_finish |
| 547 |
|
| 548 |
def compute_result_annotation(self, s_vref, s_obj): |
| 549 |
pass |
| 550 |
|
| 551 |
def specialize_call(self, hop): |
| 552 |
hop.exception_cannot_occur() |
| 553 |
|
| 554 |
vref_None = non_virtual_ref(None) |
| 555 |
|
| 556 |
|
| 557 |
|
| 558 |
|
| 559 |
class JitHintError(Exception): |
| 560 |
"""Inconsistency in the JIT hints.""" |
| 561 |
|
| 562 |
ENABLE_ALL_OPTS = ( |
| 563 |
'intbounds:rewrite:virtualize:string:pure:earlyforce:heap:unroll') |
| 564 |
|
| 565 |
PARAMETER_DOCS = { |
| 566 |
'threshold': 'number of times a loop has to run for it to become hot', |
| 567 |
'function_threshold': 'number of times a function must run for it to become traced from start', |
| 568 |
'trace_eagerness': 'number of times a guard has to fail before we start compiling a bridge', |
| 569 |
'decay': 'amount to regularly decay counters by (0=none, 1000=max)', |
| 570 |
'trace_limit': 'number of recorded operations before we abort tracing with ABORT_TOO_LONG', |
| 571 |
'inlining': 'inline python functions or not (1/0)', |
| 572 |
'loop_longevity': 'a parameter controlling how long loops will be kept before being freed, an estimate', |
| 573 |
'retrace_limit': 'how many times we can try retracing before giving up', |
| 574 |
'pureop_historylength': 'how many pure operations the optimizer should remember for CSE (internal)', |
| 575 |
'max_retrace_guards': 'number of extra guards a retrace can cause', |
| 576 |
'max_unroll_loops': 'number of extra unrollings a loop can cause', |
| 577 |
'disable_unrolling': 'after how many operations we should not unroll', |
| 578 |
'enable_opts': 'INTERNAL USE ONLY (MAY NOT WORK OR LEAD TO CRASHES): ' |
| 579 |
'optimizations to enable, or all = %s' % ENABLE_ALL_OPTS, |
| 580 |
'max_unroll_recursion': 'how many levels deep to unroll a recursive function', |
| 581 |
'vec': 'turn on the vectorization optimization (vecopt). ' \ |
| 582 |
'Supports x86 (SSE 4.1), powerpc (SVX), s390x SIMD', |
| 583 |
'vec_cost': 'threshold for which traces to bail. Unpacking increases the counter,'\ |
| 584 |
' vector operation decrease the cost', |
| 585 |
'vec_all': 'try to vectorize trace loops that occur outside of the numpypy library', |
| 586 |
} |
| 587 |
|
| 588 |
PARAMETERS = {'threshold': 1039, |
| 589 |
'function_threshold': 1619, |
| 590 |
'trace_eagerness': 200, |
| 591 |
'decay': 40, |
| 592 |
'trace_limit': 6000, |
| 593 |
'inlining': 1, |
| 594 |
'loop_longevity': 1000, |
| 595 |
'retrace_limit': 0, |
| 596 |
'pureop_historylength': 16, |
| 597 |
'max_retrace_guards': 15, |
| 598 |
'max_unroll_loops': 0, |
| 599 |
'disable_unrolling': 200, |
| 600 |
'enable_opts': 'all', |
| 601 |
'max_unroll_recursion': 7, |
| 602 |
'vec': 0, |
| 603 |
'vec_all': 0, |
| 604 |
'vec_cost': 0, |
| 605 |
} |
| 606 |
unroll_parameters = unrolling_iterable(PARAMETERS.items()) |
| 607 |
|
| 608 |
|
| 609 |
|
| 610 |
class JitDriver(object): |
| 611 |
"""Base class to declare fine-grained user control on the JIT. So |
| 612 |
far, there must be a singleton instance of JitDriver. This style |
| 613 |
will allow us (later) to support a single RPython program with |
| 614 |
several independent JITting interpreters in it. |
| 615 |
""" |
| 616 |
|
| 617 |
active = True |
| 618 |
virtualizables = [] |
| 619 |
name = 'jitdriver' |
| 620 |
inline_jit_merge_point = False |
| 621 |
_store_last_enter_jit = None |
| 622 |
|
| 623 |
@not_rpython |
| 624 |
def __init__(self, greens=None, reds=None, virtualizables=None, |
| 625 |
get_jitcell_at=None, set_jitcell_at=None, |
| 626 |
get_printable_location=None, confirm_enter_jit=None, |
| 627 |
can_never_inline=None, should_unroll_one_iteration=None, |
| 628 |
name='jitdriver', check_untranslated=True, vectorize=False, |
| 629 |
get_unique_id=None, is_recursive=False, get_location=None): |
| 630 |
"""get_location: |
| 631 |
The return value is designed to provide enough information to express the |
| 632 |
state of an interpreter when invoking jit_merge_point. |
| 633 |
For a bytecode interperter such as PyPy this includes, filename, line number, |
| 634 |
function name, and more information. However, it should also be able to express |
| 635 |
the same state for an interpreter that evaluates an AST. |
| 636 |
return paremter: |
| 637 |
0 -> filename. An absolute path specifying the file the interpreter invoked. |
| 638 |
If the input source is no file it should start with the |
| 639 |
prefix: "string://<name>" |
| 640 |
1 -> line number. The line number in filename. This should at least point to |
| 641 |
the enclosing name. It can however point to the specific |
| 642 |
source line of the instruction executed by the interpreter. |
| 643 |
2 -> enclosing name. E.g. the function name. |
| 644 |
3 -> index. 64 bit number indicating the execution progress. It can either be |
| 645 |
an offset to byte code, or an index to the node in an AST |
| 646 |
4 -> operation name. a name further describing the current program counter. |
| 647 |
this can be either a byte code name or the name of an AST node |
| 648 |
""" |
| 649 |
if greens is not None: |
| 650 |
self.greens = greens |
| 651 |
self.name = name |
| 652 |
if reds == 'auto': |
| 653 |
self.autoreds = True |
| 654 |
self.reds = [] |
| 655 |
self.numreds = None |
| 656 |
assert confirm_enter_jit is None, ( |
| 657 |
"reds='auto' is not compatible with confirm_enter_jit") |
| 658 |
else: |
| 659 |
if reds is not None: |
| 660 |
self.reds = reds |
| 661 |
self.autoreds = False |
| 662 |
self.numreds = len(self.reds) |
| 663 |
if not hasattr(self, 'greens') or not hasattr(self, 'reds'): |
| 664 |
raise AttributeError("no 'greens' or 'reds' supplied") |
| 665 |
if virtualizables is not None: |
| 666 |
self.virtualizables = virtualizables |
| 667 |
for v in self.virtualizables: |
| 668 |
assert v in self.reds |
| 669 |
|
| 670 |
|
| 671 |
|
| 672 |
self._somelivevars = set([name for name in |
| 673 |
self.greens + (self.reds or []) |
| 674 |
if '.' not in name]) |
| 675 |
self._heuristic_order = {} |
| 676 |
self._make_extregistryentries() |
| 677 |
assert get_jitcell_at is None, "get_jitcell_at no longer used" |
| 678 |
assert set_jitcell_at is None, "set_jitcell_at no longer used" |
| 679 |
for green in self.greens: |
| 680 |
if "." in green: |
| 681 |
raise ValueError("green fields are buggy! if you need them fixed, please talk to us") |
| 682 |
self.get_printable_location = get_printable_location |
| 683 |
self.get_location = get_location |
| 684 |
self.has_unique_id = (get_unique_id is not None) |
| 685 |
if get_unique_id is None: |
| 686 |
get_unique_id = lambda *args: 0 |
| 687 |
self.get_unique_id = get_unique_id |
| 688 |
self.confirm_enter_jit = confirm_enter_jit |
| 689 |
self.can_never_inline = can_never_inline |
| 690 |
self.should_unroll_one_iteration = should_unroll_one_iteration |
| 691 |
self.check_untranslated = check_untranslated |
| 692 |
self.is_recursive = is_recursive |
| 693 |
self.vec = vectorize |
| 694 |
|
| 695 |
def _freeze_(self): |
| 696 |
return True |
| 697 |
|
| 698 |
def _check_arguments(self, livevars, is_merge_point): |
| 699 |
assert set(livevars) == self._somelivevars |
| 700 |
|
| 701 |
|
| 702 |
|
| 703 |
if len(self._heuristic_order) < len(livevars): |
| 704 |
from rpython.rlib.rarithmetic import (r_singlefloat, r_longlong, |
| 705 |
r_ulonglong, r_uint) |
| 706 |
added = False |
| 707 |
for var, value in livevars.items(): |
| 708 |
if var not in self._heuristic_order: |
| 709 |
if (r_ulonglong is not r_uint and |
| 710 |
isinstance(value, (r_longlong, r_ulonglong))): |
| 711 |
assert 0, ("should not pass a r_longlong argument for " |
| 712 |
"now, because on 32-bit machines it needs " |
| 713 |
"to be ordered as a FLOAT but on 64-bit " |
| 714 |
"machines as an INT") |
| 715 |
elif isinstance(value, (int, long, r_singlefloat)): |
| 716 |
kind = '1:INT' |
| 717 |
elif isinstance(value, float): |
| 718 |
kind = '3:FLOAT' |
| 719 |
elif isinstance(value, (str, unicode)) and len(value) != 1: |
| 720 |
kind = '2:REF' |
| 721 |
elif isinstance(value, (list, dict)): |
| 722 |
kind = '2:REF' |
| 723 |
elif (hasattr(value, '__class__') |
| 724 |
and value.__class__.__module__ != '__builtin__'): |
| 725 |
if hasattr(value, '_freeze_'): |
| 726 |
continue |
| 727 |
elif getattr(value, '_alloc_flavor_', 'gc') == 'gc': |
| 728 |
kind = '2:REF' |
| 729 |
else: |
| 730 |
kind = '1:INT' |
| 731 |
else: |
| 732 |
continue |
| 733 |
self._heuristic_order[var] = kind |
| 734 |
added = True |
| 735 |
if added: |
| 736 |
for color in ('reds', 'greens'): |
| 737 |
lst = getattr(self, color) |
| 738 |
allkinds = [self._heuristic_order.get(name, '?') |
| 739 |
for name in lst] |
| 740 |
kinds = [k for k in allkinds if k != '?'] |
| 741 |
assert kinds == sorted(kinds), ( |
| 742 |
"bad order of %s variables in the jitdriver: " |
| 743 |
"must be INTs, REFs, FLOATs; got %r" % |
| 744 |
(color, allkinds)) |
| 745 |
|
| 746 |
if is_merge_point: |
| 747 |
if self._store_last_enter_jit: |
| 748 |
if livevars != self._store_last_enter_jit: |
| 749 |
raise JitHintError( |
| 750 |
"Bad can_enter_jit() placement: there should *not* " |
| 751 |
"be any code in between can_enter_jit() -> jit_merge_point()" ) |
| 752 |
self._store_last_enter_jit = None |
| 753 |
else: |
| 754 |
self._store_last_enter_jit = livevars |
| 755 |
|
| 756 |
def jit_merge_point(_self, **livevars): |
| 757 |
|
| 758 |
if _self.check_untranslated: |
| 759 |
_self._check_arguments(livevars, True) |
| 760 |
|
| 761 |
def can_enter_jit(_self, **livevars): |
| 762 |
if _self.autoreds: |
| 763 |
raise TypeError("Cannot call can_enter_jit on a driver with reds='auto'") |
| 764 |
|
| 765 |
if _self.check_untranslated: |
| 766 |
_self._check_arguments(livevars, False) |
| 767 |
|
| 768 |
def loop_header(self): |
| 769 |
|
| 770 |
pass |
| 771 |
|
| 772 |
def inline(self, call_jit_merge_point): |
| 773 |
assert False, "@inline off: see skipped failures in test_warmspot." |
| 774 |
|
| 775 |
assert self.autoreds, "@inline works only with reds='auto'" |
| 776 |
self.inline_jit_merge_point = True |
| 777 |
def decorate(func): |
| 778 |
template = """ |
| 779 |
def {name}({arglist}): |
| 780 |
{call_jit_merge_point}({arglist}) |
| 781 |
return {original}({arglist}) |
| 782 |
""" |
| 783 |
templateargs = {'call_jit_merge_point': call_jit_merge_point.__name__} |
| 784 |
globaldict = {call_jit_merge_point.__name__: call_jit_merge_point} |
| 785 |
result = rpython_wrapper(func, template, templateargs, **globaldict) |
| 786 |
result._inline_jit_merge_point_ = call_jit_merge_point |
| 787 |
return result |
| 788 |
|
| 789 |
return decorate |
| 790 |
|
| 791 |
|
| 792 |
def clone(self): |
| 793 |
assert self.inline_jit_merge_point, 'JitDriver.clone works only after @inline' |
| 794 |
newdriver = object.__new__(self.__class__) |
| 795 |
newdriver.__dict__ = self.__dict__.copy() |
| 796 |
return newdriver |
| 797 |
|
| 798 |
def _make_extregistryentries(self): |
| 799 |
|
| 800 |
|
| 801 |
|
| 802 |
|
| 803 |
self.jit_merge_point = self.jit_merge_point |
| 804 |
self.can_enter_jit = self.can_enter_jit |
| 805 |
self.loop_header = self.loop_header |
| 806 |
class Entry(ExtEnterLeaveMarker): |
| 807 |
_about_ = (self.jit_merge_point, self.can_enter_jit) |
| 808 |
|
| 809 |
class Entry(ExtLoopHeader): |
| 810 |
_about_ = self.loop_header |
| 811 |
|
| 812 |
def _set_param(driver, name, value): |
| 813 |
|
| 814 |
|
| 815 |
|
| 816 |
assert name in PARAMETERS |
| 817 |
|
| 818 |
@specialize.arg(0, 1) |
| 819 |
def set_param(driver, name, value): |
| 820 |
"""Set one of the tunable JIT parameter. Driver can be None, then all |
| 821 |
drivers have this set """ |
| 822 |
_set_param(driver, name, value) |
| 823 |
|
| 824 |
@specialize.arg(0, 1) |
| 825 |
def set_param_to_default(driver, name): |
| 826 |
"""Reset one of the tunable JIT parameters to its default value.""" |
| 827 |
_set_param(driver, name, None) |
| 828 |
|
| 829 |
class TraceLimitTooHigh(Exception): |
| 830 |
""" This is raised when the trace limit is too high for the chosen |
| 831 |
opencoder model, recompile your interpreter with 'big' as |
| 832 |
jit_opencoder_model |
| 833 |
""" |
| 834 |
|
| 835 |
@specialize.arg(0) |
| 836 |
def set_user_param(driver, text): |
| 837 |
"""Set the tunable JIT parameters from a user-supplied string |
| 838 |
following the format 'param=value,param=value', or 'off' to |
| 839 |
disable the JIT. For programmatic setting of parameters, use |
| 840 |
directly JitDriver.set_param(). |
| 841 |
""" |
| 842 |
if text == 'off': |
| 843 |
set_param(driver, 'threshold', -1) |
| 844 |
set_param(driver, 'function_threshold', -1) |
| 845 |
return |
| 846 |
if text == 'default': |
| 847 |
for name1, _ in unroll_parameters: |
| 848 |
set_param_to_default(driver, name1) |
| 849 |
return |
| 850 |
for s in text.split(','): |
| 851 |
s = s.strip(' ') |
| 852 |
parts = s.split('=') |
| 853 |
if len(parts) != 2: |
| 854 |
raise ValueError |
| 855 |
name = parts[0] |
| 856 |
value = parts[1] |
| 857 |
if name == 'enable_opts': |
| 858 |
set_param(driver, 'enable_opts', value) |
| 859 |
else: |
| 860 |
for name1, _ in unroll_parameters: |
| 861 |
if name1 == name and name1 != 'enable_opts': |
| 862 |
try: |
| 863 |
ivalue = int(value) |
| 864 |
except ValueError: |
| 865 |
raise |
| 866 |
try: |
| 867 |
set_param(driver, name1, ivalue) |
| 868 |
except ValueError: |
| 869 |
if name1 == 'trace_limit' and ivalue >= 0: |
| 870 |
|
| 871 |
raise TraceLimitTooHigh |
| 872 |
break |
| 873 |
else: |
| 874 |
raise ValueError |
| 875 |
|
| 876 |
|
| 877 |
|
| 878 |
|
| 879 |
|
| 880 |
|
| 881 |
class ExtEnterLeaveMarker(ExtRegistryEntry): |
| 882 |
|
| 883 |
|
| 884 |
|
| 885 |
|
| 886 |
def compute_result_annotation(self, **kwds_s): |
| 887 |
from rpython.annotator import model as annmodel |
| 888 |
|
| 889 |
if self.instance.__name__ == 'jit_merge_point': |
| 890 |
self.annotate_hooks(**kwds_s) |
| 891 |
|
| 892 |
driver = self.instance.im_self |
| 893 |
keys = kwds_s.keys() |
| 894 |
keys.sort() |
| 895 |
expected = ['s_' + name for name in driver.greens + driver.reds |
| 896 |
if '.' not in name] |
| 897 |
expected.sort() |
| 898 |
if keys != expected: |
| 899 |
raise JitHintError("%s expects the following keyword " |
| 900 |
"arguments: %s" % (self.instance, |
| 901 |
expected)) |
| 902 |
|
| 903 |
try: |
| 904 |
cache = self.bookkeeper._jit_annotation_cache[driver] |
| 905 |
except AttributeError: |
| 906 |
cache = {} |
| 907 |
self.bookkeeper._jit_annotation_cache = {driver: cache} |
| 908 |
except KeyError: |
| 909 |
cache = {} |
| 910 |
self.bookkeeper._jit_annotation_cache[driver] = cache |
| 911 |
for key, s_value in kwds_s.items(): |
| 912 |
s_previous = cache.get(key, annmodel.s_ImpossibleValue) |
| 913 |
s_value = annmodel.unionof(s_previous, s_value) |
| 914 |
cache[key] = s_value |
| 915 |
|
| 916 |
|
| 917 |
try: |
| 918 |
graph = self.bookkeeper.position_key[0] |
| 919 |
graph.func._dont_reach_me_in_del_ = True |
| 920 |
except (TypeError, AttributeError): |
| 921 |
pass |
| 922 |
|
| 923 |
return annmodel.s_None |
| 924 |
|
| 925 |
def annotate_hooks(self, **kwds_s): |
| 926 |
driver = self.instance.im_self |
| 927 |
h = self.annotate_hook |
| 928 |
h(driver.get_printable_location, driver.greens, **kwds_s) |
| 929 |
h(driver.get_location, driver.greens, **kwds_s) |
| 930 |
|
| 931 |
def annotate_hook(self, func, variables, args_s=[], **kwds_s): |
| 932 |
if func is None: |
| 933 |
return |
| 934 |
bk = self.bookkeeper |
| 935 |
s_func = bk.immutablevalue(func) |
| 936 |
uniquekey = 'jitdriver.%s' % func.__name__ |
| 937 |
args_s = args_s[:] |
| 938 |
for name in variables: |
| 939 |
if '.' not in name: |
| 940 |
s_arg = kwds_s['s_' + name] |
| 941 |
else: |
| 942 |
objname, fieldname = name.split('.') |
| 943 |
s_instance = kwds_s['s_' + objname] |
| 944 |
classdesc = s_instance.classdef.classdesc |
| 945 |
bk.record_getattr(classdesc, fieldname) |
| 946 |
attrdef = s_instance.classdef.find_attribute(fieldname) |
| 947 |
s_arg = attrdef.s_value |
| 948 |
assert s_arg is not None |
| 949 |
args_s.append(s_arg) |
| 950 |
bk.emulate_pbc_call(uniquekey, s_func, args_s) |
| 951 |
|
| 952 |
def specialize_call(self, hop, **kwds_i): |
| 953 |
|
| 954 |
|
| 955 |
from rpython.rtyper.lltypesystem import lltype |
| 956 |
driver = self.instance.im_self |
| 957 |
greens_v = [] |
| 958 |
reds_v = [] |
| 959 |
for name in driver.greens: |
| 960 |
if '.' not in name: |
| 961 |
i = kwds_i['i_' + name] |
| 962 |
r_green = hop.args_r[i] |
| 963 |
v_green = hop.inputarg(r_green, arg=i) |
| 964 |
else: |
| 965 |
objname, fieldname = name.split('.') |
| 966 |
assert objname in driver.reds |
| 967 |
i = kwds_i['i_' + objname] |
| 968 |
s_red = hop.args_s[i] |
| 969 |
r_red = hop.args_r[i] |
| 970 |
while True: |
| 971 |
try: |
| 972 |
mangled_name, r_field = r_red._get_field(fieldname) |
| 973 |
break |
| 974 |
except KeyError: |
| 975 |
pass |
| 976 |
assert r_red.rbase is not None, ( |
| 977 |
"field %r not found in %r" % (name, |
| 978 |
r_red.lowleveltype.TO)) |
| 979 |
r_red = r_red.rbase |
| 980 |
GTYPE = r_red.lowleveltype.TO |
| 981 |
assert GTYPE._immutable_field(mangled_name), ( |
| 982 |
"field %r must be declared as immutable" % name) |
| 983 |
if not hasattr(driver, 'll_greenfields'): |
| 984 |
driver.ll_greenfields = {} |
| 985 |
driver.ll_greenfields[name] = GTYPE, mangled_name |
| 986 |
|
| 987 |
v_red = hop.inputarg(r_red, arg=i) |
| 988 |
c_llname = hop.inputconst(lltype.Void, mangled_name) |
| 989 |
v_green = hop.genop('getfield', [v_red, c_llname], |
| 990 |
resulttype=r_field) |
| 991 |
s_green = s_red.classdef.about_attribute(fieldname) |
| 992 |
assert s_green is not None |
| 993 |
hop.rtyper.annotator.setbinding(v_green, s_green) |
| 994 |
greens_v.append(v_green) |
| 995 |
for name in driver.reds: |
| 996 |
i = kwds_i['i_' + name] |
| 997 |
r_red = hop.args_r[i] |
| 998 |
v_red = hop.inputarg(r_red, arg=i) |
| 999 |
reds_v.append(v_red) |
| 1000 |
hop.exception_cannot_occur() |
| 1001 |
vlist = [hop.inputconst(lltype.Void, self.instance.__name__), |
| 1002 |
hop.inputconst(lltype.Void, driver)] |
| 1003 |
vlist.extend(greens_v) |
| 1004 |
vlist.extend(reds_v) |
| 1005 |
return hop.genop('jit_marker', vlist, |
| 1006 |
resulttype=lltype.Void) |
| 1007 |
|
| 1008 |
class ExtLoopHeader(ExtRegistryEntry): |
| 1009 |
|
| 1010 |
|
| 1011 |
|
| 1012 |
def compute_result_annotation(self, **kwds_s): |
| 1013 |
from rpython.annotator import model as annmodel |
| 1014 |
return annmodel.s_None |
| 1015 |
|
| 1016 |
def specialize_call(self, hop): |
| 1017 |
from rpython.rtyper.lltypesystem import lltype |
| 1018 |
driver = self.instance.im_self |
| 1019 |
hop.exception_cannot_occur() |
| 1020 |
vlist = [hop.inputconst(lltype.Void, 'loop_header'), |
| 1021 |
hop.inputconst(lltype.Void, driver)] |
| 1022 |
return hop.genop('jit_marker', vlist, |
| 1023 |
resulttype=lltype.Void) |
| 1024 |
|
| 1025 |
class ExtSetParam(ExtRegistryEntry): |
| 1026 |
_about_ = _set_param |
| 1027 |
|
| 1028 |
def compute_result_annotation(self, s_driver, s_name, s_value): |
| 1029 |
from rpython.annotator import model as annmodel |
| 1030 |
assert s_name.is_constant() |
| 1031 |
if s_name.const == 'enable_opts': |
| 1032 |
assert annmodel.SomeString(can_be_None=True).contains(s_value) |
| 1033 |
else: |
| 1034 |
assert (s_value == annmodel.s_None or |
| 1035 |
annmodel.SomeInteger().contains(s_value)) |
| 1036 |
return annmodel.s_None |
| 1037 |
|
| 1038 |
def specialize_call(self, hop): |
| 1039 |
from rpython.rtyper.lltypesystem import lltype |
| 1040 |
from rpython.rtyper.lltypesystem.rstr import string_repr |
| 1041 |
from rpython.flowspace.model import Constant |
| 1042 |
|
| 1043 |
hop.exception_cannot_occur() |
| 1044 |
driver = hop.inputarg(lltype.Void, arg=0) |
| 1045 |
name = hop.args_s[1].const |
| 1046 |
if name == 'enable_opts': |
| 1047 |
repr = string_repr |
| 1048 |
else: |
| 1049 |
repr = lltype.Signed |
| 1050 |
if (isinstance(hop.args_v[2], Constant) and |
| 1051 |
hop.args_v[2].value is None): |
| 1052 |
value = PARAMETERS[name] |
| 1053 |
v_value = hop.inputconst(repr, value) |
| 1054 |
else: |
| 1055 |
v_value = hop.inputarg(repr, arg=2) |
| 1056 |
vlist = [hop.inputconst(lltype.Void, "set_param"), |
| 1057 |
driver, |
| 1058 |
hop.inputconst(lltype.Void, name), |
| 1059 |
v_value] |
| 1060 |
return hop.genop('jit_marker', vlist, |
| 1061 |
resulttype=lltype.Void) |
| 1062 |
|
| 1063 |
class AsmInfo(object): |
| 1064 |
""" An addition to JitDebugInfo concerning assembler. Attributes: |
| 1065 |
|
| 1066 |
ops_offset - dict of offsets of operations or None |
| 1067 |
asmaddr - (int) raw address of assembler block |
| 1068 |
asmlen - assembler block length |
| 1069 |
rawstart - address a guard can jump to |
| 1070 |
""" |
| 1071 |
def __init__(self, ops_offset, asmaddr, asmlen, rawstart=0): |
| 1072 |
self.ops_offset = ops_offset |
| 1073 |
self.asmaddr = asmaddr |
| 1074 |
self.asmlen = asmlen |
| 1075 |
self.rawstart = rawstart |
| 1076 |
|
| 1077 |
class JitDebugInfo(object): |
| 1078 |
""" An object representing debug info. Attributes meanings: |
| 1079 |
|
| 1080 |
greenkey - a list of green boxes or None for bridge |
| 1081 |
logger - an instance of jit.metainterp.logger.LogOperations |
| 1082 |
type - either 'loop', 'entry bridge' or 'bridge' |
| 1083 |
looptoken - description of a loop |
| 1084 |
fail_descr - fail descr or None |
| 1085 |
asminfo - extra assembler information |
| 1086 |
""" |
| 1087 |
|
| 1088 |
asminfo = None |
| 1089 |
def __init__(self, jitdriver_sd, logger, looptoken, operations, type, |
| 1090 |
greenkey=None, fail_descr=None): |
| 1091 |
self.jitdriver_sd = jitdriver_sd |
| 1092 |
self.logger = logger |
| 1093 |
self.looptoken = looptoken |
| 1094 |
self.operations = operations |
| 1095 |
self.type = type |
| 1096 |
if type == 'bridge': |
| 1097 |
assert fail_descr is not None |
| 1098 |
else: |
| 1099 |
assert greenkey is not None |
| 1100 |
self.greenkey = greenkey |
| 1101 |
self.fail_descr = fail_descr |
| 1102 |
|
| 1103 |
def get_jitdriver(self): |
| 1104 |
""" Return where the jitdriver on which the jitting started |
| 1105 |
""" |
| 1106 |
return self.jitdriver_sd.jitdriver |
| 1107 |
|
| 1108 |
def get_greenkey_repr(self): |
| 1109 |
""" Return the string repr of a greenkey |
| 1110 |
""" |
| 1111 |
return self.jitdriver_sd.warmstate.get_location_str(self.greenkey) |
| 1112 |
|
| 1113 |
class JitHookInterface(object): |
| 1114 |
""" This is the main connector between the JIT and the interpreter. |
| 1115 |
Several methods on this class will be invoked at various stages |
| 1116 |
of JIT running like JIT loops compiled, aborts etc. |
| 1117 |
An instance of this class has to be passed into the JitPolicy constructor |
| 1118 |
(and will then be available as policy.jithookiface). |
| 1119 |
""" |
| 1120 |
|
| 1121 |
|
| 1122 |
|
| 1123 |
|
| 1124 |
|
| 1125 |
|
| 1126 |
|
| 1127 |
|
| 1128 |
def are_hooks_enabled(self): |
| 1129 |
""" A hook that is called to check whether the interpreter's hooks are |
| 1130 |
enabled at all. Only if this function returns True, are the other hooks |
| 1131 |
called. Otherwise, nothing happens. This is done because constructing |
| 1132 |
some of the hooks' arguments is expensive, so we'd rather not do it.""" |
| 1133 |
return True |
| 1134 |
|
| 1135 |
def on_abort(self, reason, jitdriver, greenkey, greenkey_repr, logops, operations): |
| 1136 |
""" A hook called each time a loop is aborted with jitdriver and |
| 1137 |
greenkey where it started, reason is a string why it got aborted |
| 1138 |
""" |
| 1139 |
|
| 1140 |
def on_trace_too_long(self, jitdriver, greenkey, greenkey_repr): |
| 1141 |
""" A hook called each time we abort the trace because it's too |
| 1142 |
long with the greenkey being the one responsible for the |
| 1143 |
disabled function |
| 1144 |
""" |
| 1145 |
|
| 1146 |
|
| 1147 |
|
| 1148 |
|
| 1149 |
|
| 1150 |
|
| 1151 |
|
| 1152 |
def before_compile(self, debug_info): |
| 1153 |
""" A hook called after a loop is optimized, before compiling assembler, |
| 1154 |
called with JitDebugInfo instance. Overwrite for custom behavior |
| 1155 |
""" |
| 1156 |
|
| 1157 |
def after_compile(self, debug_info): |
| 1158 |
""" A hook called after a loop has compiled assembler, |
| 1159 |
called with JitDebugInfo instance. Overwrite for custom behavior |
| 1160 |
""" |
| 1161 |
|
| 1162 |
|
| 1163 |
|
| 1164 |
|
| 1165 |
|
| 1166 |
|
| 1167 |
|
| 1168 |
|
| 1169 |
|
| 1170 |
def before_compile_bridge(self, debug_info): |
| 1171 |
""" A hook called before a bridge is compiled, but after optimizations |
| 1172 |
are performed. Called with instance of debug_info, overwrite for |
| 1173 |
custom behavior |
| 1174 |
""" |
| 1175 |
|
| 1176 |
def after_compile_bridge(self, debug_info): |
| 1177 |
""" A hook called after a bridge is compiled, called with JitDebugInfo |
| 1178 |
instance, overwrite for custom behavior |
| 1179 |
""" |
| 1180 |
|
| 1181 |
def record_exact_class(value, cls): |
| 1182 |
""" |
| 1183 |
Assure the JIT that value is an instance of cls. This is a precise |
| 1184 |
class check, like a guard_class. |
| 1185 |
|
| 1186 |
See also debug.ll_assert_not_none(x), which asserts that x is not None |
| 1187 |
and also assures the JIT that it is the case. |
| 1188 |
""" |
| 1189 |
assert type(value) is cls |
| 1190 |
|
| 1191 |
def ll_record_exact_class(ll_value, ll_cls): |
| 1192 |
from rpython.rlib.debug import ll_assert |
| 1193 |
from rpython.rtyper.lltypesystem.lloperation import llop |
| 1194 |
from rpython.rtyper.lltypesystem import lltype |
| 1195 |
from rpython.rtyper.rclass import ll_type |
| 1196 |
ll_assert(ll_value != lltype.nullptr(lltype.typeOf(ll_value).TO), "record_exact_class called with None argument") |
| 1197 |
ll_assert(ll_type(ll_value) is ll_cls, "record_exact_class called with invalid arguments") |
| 1198 |
llop.jit_record_exact_class(lltype.Void, ll_value, ll_cls) |
| 1199 |
|
| 1200 |
|
| 1201 |
class Entry(ExtRegistryEntry): |
| 1202 |
_about_ = record_exact_class |
| 1203 |
|
| 1204 |
def compute_result_annotation(self, s_inst, s_cls): |
| 1205 |
from rpython.annotator import model as annmodel |
| 1206 |
assert not s_inst.can_be_none() |
| 1207 |
assert isinstance(s_inst, annmodel.SomeInstance) |
| 1208 |
|
| 1209 |
def specialize_call(self, hop): |
| 1210 |
from rpython.rtyper.lltypesystem import lltype |
| 1211 |
from rpython.rtyper import rclass |
| 1212 |
|
| 1213 |
classrepr = rclass.get_type_repr(hop.rtyper) |
| 1214 |
v_inst = hop.inputarg(hop.args_r[0], arg=0) |
| 1215 |
v_cls = hop.inputarg(classrepr, arg=1) |
| 1216 |
hop.exception_is_here() |
| 1217 |
return hop.gendirectcall(ll_record_exact_class, v_inst, v_cls) |
| 1218 |
|
| 1219 |
|
| 1220 |
def _jit_record_known_result(result, function, *args): |
| 1221 |
pass |
| 1222 |
|
| 1223 |
|
| 1224 |
@specialize.arg(1) |
| 1225 |
def record_known_result(result, func, *args): |
| 1226 |
""" Assure the JIT that func(*args) will produce result. func must be an |
| 1227 |
elidable function. """ |
| 1228 |
from rpython.rtyper.lltypesystem.lloperation import llop |
| 1229 |
if not we_are_translated(): |
| 1230 |
|
| 1231 |
assert func(*args) == result |
| 1232 |
assert func._elidable_function_ |
| 1233 |
return |
| 1234 |
if not we_are_jitted(): |
| 1235 |
return |
| 1236 |
|
| 1237 |
if NonConstant(False): |
| 1238 |
func(*args) |
| 1239 |
return _jit_record_known_result(result, func, *args) |
| 1240 |
|
| 1241 |
class Entry(ExtRegistryEntry): |
| 1242 |
_about_ = _jit_record_known_result |
| 1243 |
|
| 1244 |
def compute_result_annotation(self, *args_s): |
| 1245 |
from rpython.annotator import model as annmodel |
| 1246 |
self.bookkeeper.emulate_pbc_call(self.bookkeeper.position_key, |
| 1247 |
args_s[1], args_s[2:]) |
| 1248 |
return annmodel.SomeNone() |
| 1249 |
|
| 1250 |
def specialize_call(self, hop): |
| 1251 |
from rpython.rtyper.lltypesystem import lltype |
| 1252 |
|
| 1253 |
args_v = hop.inputargs(hop.args_r[0], lltype.Void, *hop.args_r[2:]) |
| 1254 |
args_v[1] = hop.args_r[1].get_concrete_llfn(hop.args_s[1], |
| 1255 |
hop.args_s[2:], hop.spaceop) |
| 1256 |
hop.exception_cannot_occur() |
| 1257 |
return hop.genop("jit_record_known_result", args_v, resulttype=lltype.Void) |
| 1258 |
|
| 1259 |
|
| 1260 |
def record_exact_value(value, const_value): |
| 1261 |
""" |
| 1262 |
Assure the JIT that value is the same as const_value |
| 1263 |
""" |
| 1264 |
assert value == const_value |
| 1265 |
return const_value |
| 1266 |
|
| 1267 |
def ll_record_exact_value(ll_value, ll_const_value): |
| 1268 |
from rpython.rlib.debug import ll_assert |
| 1269 |
from rpython.rtyper.lltypesystem.lloperation import llop |
| 1270 |
from rpython.rtyper.lltypesystem import lltype |
| 1271 |
ll_assert(ll_value == ll_const_value, "record_exact_value called with two different arguments") |
| 1272 |
llop.jit_record_exact_value(lltype.Void, ll_value, ll_const_value) |
| 1273 |
return ll_const_value |
| 1274 |
|
| 1275 |
class Entry(ExtRegistryEntry): |
| 1276 |
_about_ = record_exact_value |
| 1277 |
|
| 1278 |
def compute_result_annotation(self, s_val, s_const_val): |
| 1279 |
from rpython.annotator import model as annmodel |
| 1280 |
|
| 1281 |
s_common = annmodel.unionof(s_val, s_const_val) |
| 1282 |
|
| 1283 |
|
| 1284 |
return s_common |
| 1285 |
|
| 1286 |
def specialize_call(self, hop): |
| 1287 |
from rpython.rtyper.lltypesystem import lltype |
| 1288 |
from rpython.rtyper import rclass |
| 1289 |
|
| 1290 |
r_common = hop.r_result |
| 1291 |
v_inst = hop.inputarg(r_common, arg=0) |
| 1292 |
v_const_inst = hop.inputarg(r_common, arg=1) |
| 1293 |
hop.exception_is_here() |
| 1294 |
return hop.gendirectcall(ll_record_exact_value, v_inst, v_const_inst) |
| 1295 |
|
| 1296 |
|
| 1297 |
def _jit_conditional_call(condition, function, *args): |
| 1298 |
pass |
| 1299 |
|
| 1300 |
@specialize.call_location() |
| 1301 |
def conditional_call(condition, function, *args): |
| 1302 |
"""Does the same as: |
| 1303 |
|
| 1304 |
if condition: |
| 1305 |
function(*args) |
| 1306 |
|
| 1307 |
but is better for the JIT, in case the condition is often false |
| 1308 |
but could be true occasionally. It allows the JIT to always produce |
| 1309 |
bridge-free code. The function is never looked inside. |
| 1310 |
""" |
| 1311 |
if we_are_jitted(): |
| 1312 |
_jit_conditional_call(condition, function, *args) |
| 1313 |
else: |
| 1314 |
if condition: |
| 1315 |
function(*args) |
| 1316 |
conditional_call._always_inline_ = 'try' |
| 1317 |
|
| 1318 |
def _jit_conditional_call_value(value, function, *args): |
| 1319 |
return value |
| 1320 |
|
| 1321 |
@specialize.call_location() |
| 1322 |
def conditional_call_elidable(value, function, *args): |
| 1323 |
"""Does the same as: |
| 1324 |
|
| 1325 |
if value == <0 or None or NULL>: |
| 1326 |
value = function(*args) |
| 1327 |
return value |
| 1328 |
|
| 1329 |
For the JIT. Allows one branch which doesn't create a bridge, |
| 1330 |
typically used for caching. The value and the function's return |
| 1331 |
type must match and cannot be a float: they must be either regular |
| 1332 |
'int', or something that turns into a pointer. |
| 1333 |
|
| 1334 |
Even if the function is not marked @elidable, it is still treated |
| 1335 |
mostly like one. The only difference is that (in heapcache.py) |
| 1336 |
we don't assume this function won't change anything observable. |
| 1337 |
This is useful for caches, as you can write: |
| 1338 |
|
| 1339 |
def _compute_and_cache(...): |
| 1340 |
self.cache = ...compute... |
| 1341 |
return self.cache |
| 1342 |
|
| 1343 |
x = jit.conditional_call_elidable(self.cache, _compute_and_cache, ...) |
| 1344 |
|
| 1345 |
""" |
| 1346 |
if we_are_translated() and we_are_jitted(): |
| 1347 |
|
| 1348 |
return _jit_conditional_call_value(value, function, *args) |
| 1349 |
else: |
| 1350 |
if isinstance(value, int): |
| 1351 |
if value == 0: |
| 1352 |
value = function(*args) |
| 1353 |
assert isinstance(value, int) |
| 1354 |
else: |
| 1355 |
if not isinstance(value, list) and not value: |
| 1356 |
value = function(*args) |
| 1357 |
assert not isinstance(value, int) |
| 1358 |
return value |
| 1359 |
conditional_call_elidable._always_inline_ = 'try' |
| 1360 |
|
| 1361 |
class ConditionalCallEntry(ExtRegistryEntry): |
| 1362 |
_about_ = _jit_conditional_call, _jit_conditional_call_value |
| 1363 |
|
| 1364 |
def compute_result_annotation(self, *args_s): |
| 1365 |
s_res = self.bookkeeper.emulate_pbc_call(self.bookkeeper.position_key, |
| 1366 |
args_s[1], args_s[2:]) |
| 1367 |
if self.instance == _jit_conditional_call_value: |
| 1368 |
from rpython.annotator import model as annmodel |
| 1369 |
|
| 1370 |
|
| 1371 |
|
| 1372 |
|
| 1373 |
|
| 1374 |
|
| 1375 |
return annmodel.unionof(s_res, args_s[0].nonnoneify()) |
| 1376 |
|
| 1377 |
def specialize_call(self, hop): |
| 1378 |
from rpython.rtyper.lltypesystem import lltype |
| 1379 |
|
| 1380 |
if self.instance == _jit_conditional_call: |
| 1381 |
opname = 'jit_conditional_call' |
| 1382 |
COND = lltype.Bool |
| 1383 |
resulttype = None |
| 1384 |
elif self.instance == _jit_conditional_call_value: |
| 1385 |
opname = 'jit_conditional_call_value' |
| 1386 |
COND = hop.r_result |
| 1387 |
resulttype = hop.r_result.lowleveltype |
| 1388 |
else: |
| 1389 |
assert False |
| 1390 |
args_v = hop.inputargs(COND, lltype.Void, *hop.args_r[2:]) |
| 1391 |
args_v[1] = hop.args_r[1].get_concrete_llfn(hop.args_s[1], |
| 1392 |
hop.args_s[2:], hop.spaceop) |
| 1393 |
hop.exception_is_here() |
| 1394 |
return hop.genop(opname, args_v, resulttype=resulttype) |
| 1395 |
|
| 1396 |
def enter_portal_frame(unique_id): |
| 1397 |
"""call this when starting to interpret a function. calling this is not |
| 1398 |
necessary for almost all interpreters. The only exception is stackless |
| 1399 |
interpreters where the portal never calls itself. |
| 1400 |
""" |
| 1401 |
from rpython.rtyper.lltypesystem import lltype |
| 1402 |
from rpython.rtyper.lltypesystem.lloperation import llop |
| 1403 |
llop.jit_enter_portal_frame(lltype.Void, unique_id) |
| 1404 |
|
| 1405 |
def leave_portal_frame(): |
| 1406 |
"""call this after the end of executing a function. calling this is not |
| 1407 |
necessary for almost all interpreters. The only exception is stackless |
| 1408 |
interpreters where the portal never calls itself. |
| 1409 |
""" |
| 1410 |
from rpython.rtyper.lltypesystem import lltype |
| 1411 |
from rpython.rtyper.lltypesystem.lloperation import llop |
| 1412 |
llop.jit_leave_portal_frame(lltype.Void) |
| 1413 |
|
| 1414 |
class Counters(object): |
| 1415 |
counters=""" |
| 1416 |
TRACING |
| 1417 |
BACKEND |
| 1418 |
OPS |
| 1419 |
HEAPCACHED_OPS |
| 1420 |
RECORDED_OPS |
| 1421 |
GUARDS |
| 1422 |
OPT_OPS |
| 1423 |
OPT_GUARDS |
| 1424 |
OPT_GUARDS_SHARED |
| 1425 |
OPT_FORCINGS |
| 1426 |
OPT_VECTORIZE_TRY |
| 1427 |
OPT_VECTORIZED |
| 1428 |
ABORT_TOO_LONG |
| 1429 |
ABORT_BRIDGE |
| 1430 |
ABORT_BAD_LOOP |
| 1431 |
ABORT_ESCAPE |
| 1432 |
ABORT_FORCE_QUASIIMMUT |
| 1433 |
ABORT_SEGMENTED_TRACE |
| 1434 |
FORCE_VIRTUALIZABLES |
| 1435 |
NVIRTUALS |
| 1436 |
NVHOLES |
| 1437 |
NVREUSED |
| 1438 |
TOTAL_COMPILED_LOOPS |
| 1439 |
TOTAL_COMPILED_BRIDGES |
| 1440 |
TOTAL_FREED_LOOPS |
| 1441 |
TOTAL_FREED_BRIDGES |
| 1442 |
""" |
| 1443 |
|
| 1444 |
counter_names = [] |
| 1445 |
|
| 1446 |
@staticmethod |
| 1447 |
def _setup(): |
| 1448 |
names = Counters.counters.split() |
| 1449 |
for i, name in enumerate(names): |
| 1450 |
setattr(Counters, name, i) |
| 1451 |
Counters.counter_names.append(name) |
| 1452 |
Counters.ncounters = len(names) |
| 1453 |
|
| 1454 |
Counters._setup() |