| 1 |
import py |
| 2 |
import sys |
| 3 |
import re |
| 4 |
import os.path |
| 5 |
try: |
| 6 |
from _pytest.assertion import newinterpret |
| 7 |
except ImportError: |
| 8 |
newinterpret = None |
| 9 |
from rpython.tool.jitlogparser.parser import (SimpleParser, Function, |
| 10 |
TraceForOpcode) |
| 11 |
from rpython.tool.jitlogparser.storage import LoopStorage |
| 12 |
|
| 13 |
|
| 14 |
def find_id_linenos(code): |
| 15 |
""" |
| 16 |
Parse the given function and return a dictionary mapping "ids" to |
| 17 |
"line number". Ids are identified by comments with a special syntax:: |
| 18 |
|
| 19 |
# "myid" corresponds to the whole line |
| 20 |
print 'foo' # ID: myid |
| 21 |
""" |
| 22 |
result = {} |
| 23 |
start_lineno = code.startlineno |
| 24 |
for i, line in enumerate(py.code.Source(code.source)): |
| 25 |
m = re.search('# ID: (\w+)', line) |
| 26 |
if m: |
| 27 |
name = m.group(1) |
| 28 |
lineno = start_lineno+i |
| 29 |
result.setdefault(name, lineno) |
| 30 |
return result |
| 31 |
|
| 32 |
|
| 33 |
class Log(object): |
| 34 |
def __init__(self, rawtraces): |
| 35 |
storage = LoopStorage() |
| 36 |
traces = [SimpleParser.parse_from_input(rawtrace) for rawtrace in rawtraces] |
| 37 |
traces = storage.reconnect_loops(traces) |
| 38 |
self.loops = [TraceWithIds.from_trace(trace, storage) for trace in traces] |
| 39 |
|
| 40 |
def _filter(self, loop, is_entry_bridge=False): |
| 41 |
if is_entry_bridge == '*': |
| 42 |
return loop |
| 43 |
assert is_entry_bridge in (True, False) |
| 44 |
return PartialTraceWithIds(loop, is_entry_bridge) |
| 45 |
|
| 46 |
def loops_by_filename(self, filename, **kwds): |
| 47 |
""" |
| 48 |
Return all loops which start in the file ``filename`` |
| 49 |
""" |
| 50 |
return [self._filter(loop, **kwds) for loop in self.loops |
| 51 |
if loop.filename == filename] |
| 52 |
|
| 53 |
def loops_by_id(self, id, **kwds): |
| 54 |
""" |
| 55 |
Return all loops which contain the ID ``id`` |
| 56 |
""" |
| 57 |
return [self._filter(loop, **kwds) for loop in self.loops |
| 58 |
if loop.has_id(id)] |
| 59 |
|
| 60 |
@classmethod |
| 61 |
def opnames(self, oplist): |
| 62 |
return [op.name for op in oplist] |
| 63 |
|
| 64 |
class TraceWithIds(Function): |
| 65 |
|
| 66 |
def __init__(self, *args, **kwds): |
| 67 |
Function.__init__(self, *args, **kwds) |
| 68 |
self.ids = {} |
| 69 |
self.code = self.chunks[0].getcode() |
| 70 |
if not self.code and len(self.chunks)>1 and \ |
| 71 |
isinstance(self.chunks[1], TraceForOpcode): |
| 72 |
|
| 73 |
self.code = self.chunks[1].getcode() |
| 74 |
if self.code: |
| 75 |
self.compute_ids(self.ids) |
| 76 |
|
| 77 |
@classmethod |
| 78 |
def from_trace(cls, trace, storage): |
| 79 |
res = cls.from_operations(trace.operations, storage) |
| 80 |
return res |
| 81 |
|
| 82 |
def flatten_chunks(self): |
| 83 |
""" |
| 84 |
return a flat sequence of TraceForOpcode objects, including the ones |
| 85 |
inside inlined functions |
| 86 |
""" |
| 87 |
for chunk in self.chunks: |
| 88 |
if isinstance(chunk, TraceForOpcode): |
| 89 |
yield chunk |
| 90 |
else: |
| 91 |
for subchunk in chunk.flatten_chunks(): |
| 92 |
yield subchunk |
| 93 |
|
| 94 |
def compute_ids(self, ids): |
| 95 |
|
| 96 |
|
| 97 |
id2lineno = find_id_linenos(self.code) |
| 98 |
all_my_tracecodes = self.get_list_of_tracecodes() |
| 99 |
for id, lineno in id2lineno.iteritems(): |
| 100 |
seen = set() |
| 101 |
opcodes = [] |
| 102 |
for tracecode in all_my_tracecodes: |
| 103 |
if tracecode.lineno == lineno: |
| 104 |
opcode = tracecode.getopcode() |
| 105 |
if opcode not in seen: |
| 106 |
seen.add(opcode) |
| 107 |
opcodes.append(opcode) |
| 108 |
if opcodes: |
| 109 |
ids[id] = opcodes |
| 110 |
|
| 111 |
|
| 112 |
for chunk in self.chunks: |
| 113 |
if isinstance(chunk, TraceWithIds) and chunk.code: |
| 114 |
chunk.compute_ids(ids) |
| 115 |
|
| 116 |
def get_list_of_tracecodes(self): |
| 117 |
result = [] |
| 118 |
for chunk in self.chunks: |
| 119 |
if isinstance(chunk, TraceForOpcode): |
| 120 |
result.append(chunk) |
| 121 |
return result |
| 122 |
|
| 123 |
def has_id(self, id): |
| 124 |
return id in self.ids |
| 125 |
|
| 126 |
def _ops_for_chunk(self, chunk, include_guard_not_invalidated): |
| 127 |
for op in chunk.operations: |
| 128 |
if op.name not in ('debug_merge_point', 'enter_portal_frame', |
| 129 |
'leave_portal_frame') and \ |
| 130 |
(op.name != 'guard_not_invalidated' or include_guard_not_invalidated): |
| 131 |
yield op |
| 132 |
|
| 133 |
def _allops(self, opcode=None, include_guard_not_invalidated=True): |
| 134 |
opcode_name = opcode |
| 135 |
for chunk in self.flatten_chunks(): |
| 136 |
opcode = chunk.getopcode() |
| 137 |
if opcode_name is None or \ |
| 138 |
(opcode and opcode.match_name(opcode_name)): |
| 139 |
for op in self._ops_for_chunk(chunk, include_guard_not_invalidated): |
| 140 |
yield op |
| 141 |
else: |
| 142 |
for op in chunk.operations: |
| 143 |
if op.name == 'label': |
| 144 |
yield op |
| 145 |
|
| 146 |
def allops(self, *args, **kwds): |
| 147 |
return list(self._allops(*args, **kwds)) |
| 148 |
|
| 149 |
def format_ops(self, id=None, **kwds): |
| 150 |
if id is None: |
| 151 |
ops = self.allops(**kwds) |
| 152 |
else: |
| 153 |
ops = self.ops_by_id(id, **kwds) |
| 154 |
return '\n'.join(map(str, ops)) |
| 155 |
|
| 156 |
def print_ops(self, *args, **kwds): |
| 157 |
print self.format_ops(*args, **kwds) |
| 158 |
|
| 159 |
def _ops_by_id(self, id, include_guard_not_invalidated=True, opcode=None): |
| 160 |
opcode_name = opcode |
| 161 |
target_opcodes = self.ids[id] |
| 162 |
loop_ops = self.allops(opcode) |
| 163 |
for chunk in self.flatten_chunks(): |
| 164 |
opcode = chunk.getopcode() |
| 165 |
if opcode in target_opcodes and (opcode_name is None or |
| 166 |
opcode.match_name(opcode_name)): |
| 167 |
for op in self._ops_for_chunk(chunk, include_guard_not_invalidated): |
| 168 |
if op in loop_ops: |
| 169 |
yield op |
| 170 |
|
| 171 |
def ops_by_id(self, *args, **kwds): |
| 172 |
return list(self._ops_by_id(*args, **kwds)) |
| 173 |
|
| 174 |
def match(self, expected_src, **kwds): |
| 175 |
ops = self.allops() |
| 176 |
matcher = OpMatcher(ops) |
| 177 |
return matcher.match(expected_src, **kwds) |
| 178 |
|
| 179 |
def match_by_id(self, id, expected_src, ignore_ops=[], **kwds): |
| 180 |
ops = list(self.ops_by_id(id, **kwds)) |
| 181 |
matcher = OpMatcher(ops, id) |
| 182 |
return matcher.match(expected_src, ignore_ops=ignore_ops) |
| 183 |
|
| 184 |
class PartialTraceWithIds(TraceWithIds): |
| 185 |
def __init__(self, trace, is_entry_bridge=False): |
| 186 |
self.trace = trace |
| 187 |
self.is_entry_bridge = is_entry_bridge |
| 188 |
|
| 189 |
def allops(self, *args, **kwds): |
| 190 |
if self.is_entry_bridge: |
| 191 |
return self.entry_bridge_ops(*args, **kwds) |
| 192 |
else: |
| 193 |
return self.simple_loop_ops(*args, **kwds) |
| 194 |
|
| 195 |
def simple_loop_ops(self, *args, **kwds): |
| 196 |
ops = list(self._allops(*args, **kwds)) |
| 197 |
labels = [op for op in ops if op.name == 'label'] |
| 198 |
jumpop = self.chunks[-1].operations[-1] |
| 199 |
assert jumpop.name == 'jump' |
| 200 |
assert jumpop.getdescr() == labels[-1].getdescr() |
| 201 |
i = ops.index(labels[-1]) |
| 202 |
return ops[i+1:] |
| 203 |
|
| 204 |
def entry_bridge_ops(self, *args, **kwds): |
| 205 |
ops = list(self._allops(*args, **kwds)) |
| 206 |
labels = [op for op in ops if op.name == 'label'] |
| 207 |
i0 = ops.index(labels[0]) |
| 208 |
i1 = ops.index(labels[1]) |
| 209 |
return ops[i0+1:i1] |
| 210 |
|
| 211 |
@property |
| 212 |
def chunks(self): |
| 213 |
return self.trace.chunks |
| 214 |
|
| 215 |
@property |
| 216 |
def ids(self): |
| 217 |
return self.trace.ids |
| 218 |
|
| 219 |
@property |
| 220 |
def filename(self): |
| 221 |
return self.trace.filename |
| 222 |
|
| 223 |
@property |
| 224 |
def code(self): |
| 225 |
return self.trace.code |
| 226 |
|
| 227 |
|
| 228 |
class InvalidMatch(Exception): |
| 229 |
opindex = None |
| 230 |
|
| 231 |
def __init__(self, message, frame): |
| 232 |
Exception.__init__(self, message) |
| 233 |
|
| 234 |
f = py.code.Frame(frame) |
| 235 |
try: |
| 236 |
source = f.code.fullsource |
| 237 |
if source is not None: |
| 238 |
try: |
| 239 |
source = source.getstatement(f.lineno) |
| 240 |
except IndexError: |
| 241 |
source = None |
| 242 |
else: |
| 243 |
source = str(source.deindent()).strip() |
| 244 |
except py.error.ENOENT: |
| 245 |
source = None |
| 246 |
if source and source.startswith('self._assert(') and newinterpret: |
| 247 |
|
| 248 |
source = source.replace('self._assert(', 'assert ') |
| 249 |
source = source[:-1] |
| 250 |
self.msg = newinterpret.interpret(source, f, should_fail=True) |
| 251 |
else: |
| 252 |
self.msg = "<could not determine information>" |
| 253 |
|
| 254 |
|
| 255 |
class OpMatcher(object): |
| 256 |
|
| 257 |
def __init__(self, ops, id=None): |
| 258 |
self.ops = ops |
| 259 |
self.id = id |
| 260 |
self.src = '\n'.join(map(str, ops)) |
| 261 |
self.alpha_map = {} |
| 262 |
|
| 263 |
@classmethod |
| 264 |
def parse_ops(cls, src): |
| 265 |
ops = [cls.parse_op(line) for line in src.splitlines()] |
| 266 |
ops.append(('--end--', None, [], '...', True)) |
| 267 |
return [op for op in ops if op is not None] |
| 268 |
|
| 269 |
@classmethod |
| 270 |
def parse_op(cls, line): |
| 271 |
|
| 272 |
if '#' in line: |
| 273 |
nested = 0 |
| 274 |
for i, c in enumerate(line): |
| 275 |
if c == '(': |
| 276 |
nested += 1 |
| 277 |
elif c == ')': |
| 278 |
assert nested > 0, "more ')' than '(' in %r" % (line,) |
| 279 |
nested -= 1 |
| 280 |
elif c == '#' and nested == 0: |
| 281 |
line = line[:i] |
| 282 |
break |
| 283 |
|
| 284 |
if line.strip() == 'guard_not_invalidated?': |
| 285 |
return 'guard_not_invalidated', None, [], '...', False |
| 286 |
if line.strip() == 'dummy_get_utf8?': |
| 287 |
|
| 288 |
|
| 289 |
|
| 290 |
return None |
| 291 |
|
| 292 |
|
| 293 |
if ' = ' in line: |
| 294 |
resvar, _, line = line.partition(' = ') |
| 295 |
resvar = resvar.strip() |
| 296 |
else: |
| 297 |
resvar = None |
| 298 |
line = line.strip() |
| 299 |
if not line: |
| 300 |
return None |
| 301 |
if line in ('...', '{{{', '}}}'): |
| 302 |
return line |
| 303 |
opname, _, args = line.partition('(') |
| 304 |
opname = opname.strip() |
| 305 |
assert args.endswith(')') |
| 306 |
args = args[:-1] |
| 307 |
args = args.split(',') |
| 308 |
args = map(str.strip, args) |
| 309 |
if args == ['']: |
| 310 |
args = [] |
| 311 |
if args and args[-1].startswith('descr='): |
| 312 |
descr = args.pop() |
| 313 |
descr = descr[len('descr='):] |
| 314 |
else: |
| 315 |
descr = None |
| 316 |
return opname, resvar, args, descr, True |
| 317 |
|
| 318 |
@classmethod |
| 319 |
def preprocess_expected_src(cls, src): |
| 320 |
|
| 321 |
|
| 322 |
|
| 323 |
|
| 324 |
ticker_check = """ |
| 325 |
guard_not_invalidated? |
| 326 |
ticker0 = getfield_raw_i(#, descr=<FieldS pypysig_long_struct_inner.c_value .*>) |
| 327 |
ticker_cond0 = int_lt(ticker0, 0) |
| 328 |
guard_false(ticker_cond0, descr=...) |
| 329 |
""" |
| 330 |
src = src.replace('--TICK--', ticker_check) |
| 331 |
|
| 332 |
|
| 333 |
thread_ticker_check = """ |
| 334 |
guard_not_invalidated? |
| 335 |
ticker0 = getfield_raw_i(#, descr=<FieldS pypysig_long_struct_inner.c_value .*>) |
| 336 |
ticker1 = int_sub(ticker0, #) |
| 337 |
setfield_raw(#, ticker1, descr=<FieldS pypysig_long_struct_inner.c_value .*>) |
| 338 |
ticker_cond0 = int_lt(ticker1, 0) |
| 339 |
guard_false(ticker_cond0, descr=...) |
| 340 |
""" |
| 341 |
src = src.replace('--THREAD-TICK--', thread_ticker_check) |
| 342 |
|
| 343 |
|
| 344 |
exc_ticker_check = """ |
| 345 |
ticker2 = getfield_raw_i(#, descr=<FieldS pypysig_long_struct_inner.c_value .*>) |
| 346 |
ticker_cond1 = int_lt(ticker2, 0) |
| 347 |
guard_false(ticker_cond1, descr=...) |
| 348 |
""" |
| 349 |
src = src.replace('--EXC-TICK--', exc_ticker_check) |
| 350 |
|
| 351 |
|
| 352 |
r = re.compile('(\w+) = --ISINF--[(](\w+)[)]') |
| 353 |
src = r.sub(r'\2\B999 = float_add(\2, ...)\n\1 = float_eq(\2\B999, \2)', |
| 354 |
src) |
| 355 |
return src |
| 356 |
|
| 357 |
@classmethod |
| 358 |
def is_const(cls, v1): |
| 359 |
return isinstance(v1, str) and v1.startswith('ConstClass(') |
| 360 |
|
| 361 |
@staticmethod |
| 362 |
def as_numeric_const(v1): |
| 363 |
|
| 364 |
try: |
| 365 |
return ('int', int(v1)) |
| 366 |
except ValueError: |
| 367 |
pass |
| 368 |
if '.' in v1: |
| 369 |
try: |
| 370 |
return ('float', float(v1)) |
| 371 |
except ValueError: |
| 372 |
pass |
| 373 |
return None |
| 374 |
|
| 375 |
def match_var(self, v1, exp_v2): |
| 376 |
assert v1 != '_' |
| 377 |
if exp_v2 == '_': |
| 378 |
return True |
| 379 |
if exp_v2 is None: |
| 380 |
return v1 is None |
| 381 |
assert exp_v2 != '...' |
| 382 |
n1 = self.as_numeric_const(v1) |
| 383 |
if exp_v2 == '#': |
| 384 |
return n1 is not None |
| 385 |
n2 = self.as_numeric_const(exp_v2) |
| 386 |
if n1 is not None or n2 is not None: |
| 387 |
|
| 388 |
return n1 == n2 |
| 389 |
if self.is_const(v1) or self.is_const(exp_v2): |
| 390 |
return v1[:-1].startswith(exp_v2[:-1]) |
| 391 |
if v1 not in self.alpha_map: |
| 392 |
self.alpha_map[v1] = exp_v2 |
| 393 |
return self.alpha_map[v1] == exp_v2 |
| 394 |
|
| 395 |
def match_descr(self, descr, exp_descr): |
| 396 |
if descr == exp_descr or exp_descr == '...': |
| 397 |
return True |
| 398 |
self._assert(exp_descr is not None and re.match(exp_descr, descr), "descr mismatch") |
| 399 |
|
| 400 |
def _assert(self, cond, message): |
| 401 |
if not cond: |
| 402 |
raise InvalidMatch(message, frame=sys._getframe(1)) |
| 403 |
|
| 404 |
def match_op(self, op, (exp_opname, exp_res, exp_args, exp_descr, _)): |
| 405 |
if exp_opname == '--end--': |
| 406 |
self._assert(op == '--end--', 'got more ops than expected') |
| 407 |
return |
| 408 |
self._assert(op != '--end--', 'got less ops than expected') |
| 409 |
self._assert(op.name == exp_opname, "operation mismatch") |
| 410 |
self.match_var(op.res, exp_res) |
| 411 |
if exp_args[-1:] == ['...']: |
| 412 |
exp_args = exp_args[:-1] |
| 413 |
self._assert(len(op.args) >= len(exp_args), "not enough arguments") |
| 414 |
else: |
| 415 |
self._assert(len(op.args) == len(exp_args), "wrong number of arguments") |
| 416 |
for arg, exp_arg in zip(op.args, exp_args): |
| 417 |
self._assert(self.match_var(arg, exp_arg), "variable mismatch: %r instead of %r" % (arg, exp_arg)) |
| 418 |
self.match_descr(op.descr, exp_descr) |
| 419 |
|
| 420 |
|
| 421 |
def _next_op(self, iter_ops, ignore_ops=set()): |
| 422 |
try: |
| 423 |
while True: |
| 424 |
op = iter_ops.next() |
| 425 |
if op.name not in ignore_ops: |
| 426 |
break |
| 427 |
except StopIteration: |
| 428 |
return '--end--' |
| 429 |
return op |
| 430 |
|
| 431 |
def try_match(self, op, exp_op): |
| 432 |
try: |
| 433 |
|
| 434 |
|
| 435 |
alpha_map = self.alpha_map.copy() |
| 436 |
self.match_op(op, exp_op) |
| 437 |
except InvalidMatch: |
| 438 |
|
| 439 |
self.alpha_map = alpha_map |
| 440 |
return False |
| 441 |
else: |
| 442 |
return True |
| 443 |
|
| 444 |
def match_until(self, until_op, iter_ops): |
| 445 |
while True: |
| 446 |
op = self._next_op(iter_ops) |
| 447 |
if self.try_match(op, until_op): |
| 448 |
|
| 449 |
return op |
| 450 |
self._assert(op != '--end--', |
| 451 |
'nothing in the end of the loop matches %r' % |
| 452 |
(until_op,)) |
| 453 |
|
| 454 |
def match_any_order(self, iter_exp_ops, iter_ops, ignore_ops): |
| 455 |
exp_ops = [] |
| 456 |
for exp_op in iter_exp_ops: |
| 457 |
if exp_op == '}}}': |
| 458 |
break |
| 459 |
exp_ops.append(exp_op) |
| 460 |
else: |
| 461 |
assert 0, "'{{{' not followed by '}}}'" |
| 462 |
while exp_ops: |
| 463 |
op = self._next_op(iter_ops, ignore_ops=ignore_ops) |
| 464 |
|
| 465 |
|
| 466 |
for i, exp_op in enumerate(exp_ops): |
| 467 |
if self.try_match(op, exp_op): |
| 468 |
del exp_ops[i] |
| 469 |
break |
| 470 |
else: |
| 471 |
self._assert(0, \ |
| 472 |
"operation %r not found within the {{{ }}} block" % (op,)) |
| 473 |
|
| 474 |
def match_loop(self, expected_ops, ignore_ops): |
| 475 |
""" |
| 476 |
A note about partial matching: the '...' operator is non-greedy, |
| 477 |
i.e. it matches all the operations until it finds one that matches |
| 478 |
what is after the '...'. The '{{{' and '}}}' operators mark a |
| 479 |
group of lines that can match in any order. |
| 480 |
""" |
| 481 |
iter_exp_ops = iter(expected_ops) |
| 482 |
iter_ops = RevertableIterator(self.ops) |
| 483 |
for exp_op in iter_exp_ops: |
| 484 |
try: |
| 485 |
if exp_op == '...': |
| 486 |
|
| 487 |
try: |
| 488 |
exp_op = iter_exp_ops.next() |
| 489 |
except StopIteration: |
| 490 |
|
| 491 |
|
| 492 |
return |
| 493 |
op = self.match_until(exp_op, iter_ops) |
| 494 |
elif exp_op == '{{{': |
| 495 |
self.match_any_order(iter_exp_ops, iter_ops, ignore_ops) |
| 496 |
continue |
| 497 |
else: |
| 498 |
op = self._next_op(iter_ops, ignore_ops=ignore_ops) |
| 499 |
try: |
| 500 |
self.match_op(op, exp_op) |
| 501 |
except InvalidMatch: |
| 502 |
if type(exp_op) is str or exp_op[4] is not False: |
| 503 |
raise |
| 504 |
|
| 505 |
iter_ops.revert_one() |
| 506 |
continue |
| 507 |
except InvalidMatch as e: |
| 508 |
e.opindex = iter_ops.index - 1 |
| 509 |
raise |
| 510 |
|
| 511 |
def match(self, expected_src, ignore_ops=[]): |
| 512 |
def format(src, opindex=None): |
| 513 |
if src is None: |
| 514 |
return '' |
| 515 |
text = str(py.code.Source(src).deindent().indent()) |
| 516 |
lines = text.splitlines(True) |
| 517 |
if opindex is not None and 0 <= opindex <= len(lines): |
| 518 |
lines.insert(opindex, '\n\t===== HERE =====\n') |
| 519 |
return ''.join(lines) |
| 520 |
|
| 521 |
expected_src = self.preprocess_expected_src(expected_src) |
| 522 |
expected_ops = self.parse_ops(expected_src) |
| 523 |
try: |
| 524 |
self.match_loop(expected_ops, ignore_ops) |
| 525 |
except InvalidMatch as e: |
| 526 |
print '@' * 40 |
| 527 |
print "Loops don't match" |
| 528 |
print "=================" |
| 529 |
print 'loop id = %r' % (self.id,) |
| 530 |
print e.args |
| 531 |
print e.msg |
| 532 |
print |
| 533 |
print "Ignore ops:", ignore_ops |
| 534 |
print "Got:" |
| 535 |
print format(self.src, e.opindex) |
| 536 |
print |
| 537 |
print "Expected:" |
| 538 |
print format(expected_src) |
| 539 |
raise |
| 540 |
else: |
| 541 |
return True |
| 542 |
|
| 543 |
|
| 544 |
class RevertableIterator(object): |
| 545 |
def __init__(self, sequence): |
| 546 |
self.sequence = sequence |
| 547 |
self.index = 0 |
| 548 |
def __iter__(self): |
| 549 |
return self |
| 550 |
def next(self): |
| 551 |
index = self.index |
| 552 |
self.index = index + 1 |
| 553 |
if index >= len(self.sequence): |
| 554 |
raise StopIteration |
| 555 |
return self.sequence[index] |
| 556 |
def revert_one(self): |
| 557 |
self.index -= 1 |