Debian Codegraph @

rpython/jit/metainterp/optimizeopt/optimizer.py

raw symbols SCIP
1 from rpython.jit.metainterp import jitprof, resume, compile
2 from rpython.jit.metainterp.executor import execute_nonspec_const
3 from rpython.jit.metainterp.history import (
4 Const, ConstInt, CONST_NULL, new_ref_dict)
5 from rpython.jit.metainterp.optimizeopt.intutils import IntBound
6 from rpython.jit.metainterp.optimizeopt.util import (
7 make_dispatcher_method, get_box_replacement)
8 from rpython.jit.metainterp.optimizeopt.bridgeopt import (
9 deserialize_optimizer_knowledge)
10 from rpython.jit.metainterp.resoperation import (
11 rop, AbstractResOp, GuardResOp, OpHelpers)
12 from .info import getrawptrinfo, getptrinfo
13 from rpython.jit.metainterp.optimizeopt import info
14 from rpython.jit.metainterp.optimize import InvalidLoop
15 from rpython.rlib.objectmodel import specialize, we_are_translated
16 from rpython.rlib.debug import have_debug_prints_for
17 from rpython.rtyper import rclass
18 from rpython.rtyper.lltypesystem import llmemory
19 from rpython.jit.metainterp.optimize import SpeculativeError
20
21
22
23
24 CONST_0 = ConstInt(0)
25 CONST_1 = ConstInt(1)
26 CONST_ZERO_FLOAT = Const._new(0.0)
27 REMOVED = AbstractResOp()
28
29 class LoopInfo(object):
30 label_op = None
31
32 class BasicLoopInfo(LoopInfo):
33 def __init__(self, inputargs, quasi_immutable_deps, jump_op):
34 self.inputargs = inputargs
35 self.jump_op = jump_op
36 self.quasi_immutable_deps = quasi_immutable_deps
37 self.extra_same_as = []
38 self.extra_before_label = []
39
40 def final(self):
41 return True
42
43 def post_loop_compilation(self, loop, jitdriver_sd, metainterp, jitcell_token):
44 pass
45
46
47 class OptimizationResult(object):
48 def __init__(self, opt, op):
49 self.opt = opt
50 self.op = op
51
52 def callback(self):
53 self.opt.propagate_postprocess(self.op)
54
55 PASS_OP_ON = OptimizationResult(None, None)
56
57 @specialize.memo()
58 def have_postprocess(cls):
59 return cls.propagate_postprocess.im_func is not Optimization.propagate_postprocess.im_func
60
61 class Optimization(object):
62 next_optimization = None
63 potential_extra_ops = None
64
65 def __init__(self):
66 pass # make rpython happy
67
68 def propagate_forward(self, op):
69 raise NotImplementedError
70
71 def propagate_postprocess(self, op):
72 pass
73
74 def have_postprocess(self):
75 return have_postprocess(self.__class__)
76
77 def have_postprocess_op(self, opnum):
78 # default implementation, usually overridden
79 return self.have_postprocess()
80
81 def emit_operation(self, op):
82 assert False, "This should never be called."
83
84 def emit(self, op):
85 if not self.have_postprocess_op(op.getopnum()):
86 self.last_emitted_operation = op
87 return PASS_OP_ON # no allocation
88 return self.emit_result(OptimizationResult(self, op))
89
90 def emit_result(self, opt_result):
91 self.last_emitted_operation = opt_result.op
92 return opt_result
93
94 def emit_extra(self, op, emit=True):
95 if emit:
96 self.emit(op)
97 self.optimizer.send_extra_operation(op, self.next_optimization)
98
99 def getintbound(self, op):
100 assert op.type == 'i'
101 op = get_box_replacement(op)
102 if isinstance(op, ConstInt):
103 return IntBound.from_constant(op.getint())
104 fw = op.get_forwarded()
105 if fw is not None:
106 if isinstance(fw, IntBound):
107 return fw
108 # rare case: fw might be a RawBufferPtrInfo
109 return IntBound.unbounded()
110 assert op.type == 'i'
111 intbound = IntBound.unbounded()
112 op.set_forwarded(intbound)
113 return intbound
114
115 def setintbound(self, op, bound):
116 assert op.type == 'i'
117 op = get_box_replacement(op)
118 if op.is_constant():
119 return
120 cur = op.get_forwarded()
121 if cur is not None:
122 if isinstance(cur, IntBound):
123 cur.intersect(bound)
124 else:
125 op.set_forwarded(bound)
126
127 def getnullness(self, op):
128 if op.type == 'r' or self.is_raw_ptr(op):
129 ptrinfo = getptrinfo(op)
130 if ptrinfo is None:
131 return info.INFO_UNKNOWN
132 return ptrinfo.getnullness()
133 elif op.type == 'i':
134 return self.getintbound(op).getnullness()
135 assert False
136
137 def make_constant_class(self, op, class_const, update_last_guard=True):
138 op = op.get_box_replacement()
139 opinfo = op.get_forwarded()
140 if isinstance(opinfo, info.InstancePtrInfo):
141 opinfo._known_class = class_const
142 else:
143 if opinfo is not None:
144 last_guard_pos = opinfo.get_last_guard_pos()
145 else:
146 last_guard_pos = -1
147 opinfo = info.InstancePtrInfo(None, class_const)
148 opinfo.last_guard_pos = last_guard_pos
149 op.set_forwarded(opinfo)
150 if update_last_guard:
151 opinfo.mark_last_guard(self.optimizer)
152 return opinfo
153
154 def is_raw_ptr(self, op):
155 fw = get_box_replacement(op).get_forwarded()
156 if isinstance(fw, info.AbstractRawPtrInfo):
157 return True
158 return False
159
160 def replace_op_with(self, op, newopnum, args=None, descr=None):
161 return self.optimizer.replace_op_with(op, newopnum, args, descr)
162
163 def ensure_ptr_info_arg0(self, op):
164 return self.optimizer.ensure_ptr_info_arg0(op)
165
166 def ensure_ptr_info_arg0_array(self, op):
167 return self.optimizer.ensure_ptr_info_arg0_array(op)
168
169 def make_constant(self, box, constbox):
170 return self.optimizer.make_constant(box, constbox)
171
172 def make_constant_int(self, box, intconst):
173 return self.optimizer.make_constant_int(box, intconst)
174
175 def make_equal_to(self, box, value):
176 return self.optimizer.make_equal_to(box, value)
177
178 def make_nonnull(self, op):
179 return self.optimizer.make_nonnull(op)
180
181 def make_nonnull_str(self, op, mode):
182 return self.optimizer.make_nonnull_str(op, mode)
183
184 def get_constant_box(self, box):
185 return self.optimizer.get_constant_box(box)
186
187 def pure(self, opnum, result):
188 if self.optimizer.optpure:
189 self.optimizer.optpure.pure(opnum, result)
190
191 def pure_from_args(self, opnum, args, op, descr=None):
192 if self.optimizer.optpure:
193 self.optimizer.optpure.pure_from_args(opnum, args, op, descr)
194
195 def pure_from_args2(self, opnum, arg0, arg1, op):
196 if self.optimizer.optpure:
197 self.optimizer.optpure.pure_from_args2(opnum, arg0, arg1, op)
198
199 def pure_from_args1(self, opnum, arg0, op):
200 if self.optimizer.optpure:
201 self.optimizer.optpure.pure_from_args1(opnum, arg0, op)
202
203 def get_pure_result(self, key):
204 if self.optimizer.optpure:
205 return self.optimizer.optpure.get_pure_result(key)
206 return None
207
208 def setup(self):
209 pass
210
211 # Called after last operation has been propagated to flush out any posponed ops
212 def flush(self):
213 pass
214
215 def produce_potential_short_preamble_ops(self, potential_ops):
216 pass
217
218 def _can_optimize_call_pure(self, op, start_index=0):
219 arg_consts = []
220 for i in range(start_index, op.numargs()):
221 arg = op.getarg(i)
222 const = self.optimizer.get_constant_box(arg)
223 if const is None:
224 return None
225 arg_consts.append(const)
226 else:
227 # all constant arguments: check if we already know the result
228 try:
229 return self.optimizer.call_pure_results[arg_consts]
230 except KeyError:
231 return None
232
233
234 class Optimizer(Optimization):
235
236 def __init__(self, metainterp_sd, jitdriver_sd, optimizations=None):
237 self.metainterp_sd = metainterp_sd
238 self.jitdriver_sd = jitdriver_sd
239 self.cpu = metainterp_sd.cpu
240 self.resumedata_memo = resume.ResumeDataLoopMemo(metainterp_sd)
241 self.pendingfields = None # set temporarily to a list, normally by
242 # heap.py, as we're about to generate a guard
243 self.quasi_immutable_deps = None
244 self.replaces_guard = {}
245 self._newoperations = []
246 self._emittedoperations = {}
247 self.optimizer = self
248 self.optpure = None
249 self.optheap = None
250 self.optrewrite = None
251 self.optearlyforce = None
252 self.optunroll = None
253 self._really_emitted_operation = None
254
255 self._last_guard_op = None
256
257 self.can_replace_guards = True
258
259 self.set_optimizations(optimizations)
260 self.setup()
261 if have_debug_prints_for("jit-log-intbounds"):
262 from rpython.jit.metainterp.optimizeopt.intbounds import IntegerAnalysisLogger
263
264 self.log_operations_intbounds = IntegerAnalysisLogger(self)
265 else:
266 self.log_operations_intbounds = None
267
268
269 def set_optimizations(self, optimizations):
270 if optimizations:
271 self.first_optimization = optimizations[0]
272 for i in range(1, len(optimizations)):
273 optimizations[i - 1].next_optimization = optimizations[i]
274 optimizations[-1].next_optimization = self
275 for o in optimizations:
276 o.optimizer = self
277 o.last_emitted_operation = None
278 o.setup()
279 else:
280 optimizations = []
281 self.first_optimization = self
282
283 self.optimizations = optimizations
284
285 def optimize_loop(self, trace, resumestorage, call_pure_results):
286 traceiter = trace.get_iter()
287 if resumestorage:
288 frontend_inputargs = trace.inputargs
289 deserialize_optimizer_knowledge(
290 self, resumestorage, frontend_inputargs, traceiter.inputargs)
291 return self.propagate_all_forward(traceiter, call_pure_results)
292
293 def force_op_from_preamble(self, op):
294 return op
295
296 def notice_guard_future_condition(self, op):
297 self.patchguardop = op
298
299 def cant_replace_guards(self):
300 return CantReplaceGuards(self)
301
302 def replace_guard(self, op, value):
303 assert self.can_replace_guards
304 assert isinstance(value, info.NonNullPtrInfo)
305 if value.last_guard_pos == -1:
306 return
307 self.replaces_guard[op] = value.last_guard_pos
308
309 def force_box_for_end_of_preamble(self, box):
310 if box.type == 'r':
311 info = getptrinfo(box)
312 if info is not None and info.is_virtual():
313 rec = {}
314 return info.force_at_the_end_of_preamble(box,
315 self.optearlyforce, rec)
316 return box
317 if box.type == 'i':
318 info = getrawptrinfo(box)
319 if info is not None:
320 return info.force_at_the_end_of_preamble(box,
321 self.optearlyforce, None)
322 return box
323
324 def flush(self):
325 for o in self.optimizations:
326 o.flush()
327
328 def produce_potential_short_preamble_ops(self, sb):
329 for opt in self.optimizations:
330 opt.produce_potential_short_preamble_ops(sb)
331
332 def getinfo(self, op):
333 if op.type == 'r':
334 return getptrinfo(op)
335 elif op.type == 'i':
336 if self.is_raw_ptr(op):
337 return getptrinfo(op)
338 return self.getintbound(op)
339 elif op.type == 'f':
340 if get_box_replacement(op).is_constant():
341 return info.FloatConstInfo(get_box_replacement(op))
342
343 def get_box_replacement(self, op):
344 if op is None:
345 return op
346 return op.get_box_replacement()
347
348 def force_box(self, op, optforce=None):
349 op = get_box_replacement(op)
350 if optforce is None:
351 #import pdb; pdb.set_trace()
352 optforce = self
353 info = op.get_forwarded()
354 if self.optunroll and self.optunroll.potential_extra_ops:
355 # XXX hack
356 try:
357 preamble_op = self.optunroll.potential_extra_ops.pop(op)
358 except KeyError:
359 pass
360 else:
361 sb = self.optunroll.short_preamble_producer
362 sb.add_preamble_op(preamble_op)
363 if info is not None:
364 if op.type == 'i' and info.is_constant():
365 return ConstInt(info.get_constant_int())
366 return info.force_box(op, optforce)
367 return op
368
369 def as_operation(self, op, required_opnum=-1):
370 # You should never check "isinstance(op, AbstractResOp" directly.
371 # Instead, use this helper.
372 if isinstance(op, AbstractResOp):
373 if required_opnum != -1 and op.opnum != required_opnum:
374 return None # fast return if the opnum is wrong
375 if op in self._emittedoperations:
376 return op
377 return None
378
379 def get_constant_box(self, box):
380 box = get_box_replacement(box)
381 if isinstance(box, Const):
382 return box
383 if box.type == 'i':
384 info = box.get_forwarded()
385 if isinstance(info, IntBound) and info.is_constant():
386 return ConstInt(info.get_constant_int())
387 return None
388 #self.ensure_imported(value)
389
390 def make_equal_to(self, op, newop):
391 op = get_box_replacement(op)
392 if op is newop:
393 return
394 opinfo = op.get_forwarded()
395 if opinfo is not None:
396 assert isinstance(opinfo, info.AbstractInfo)
397 op.set_forwarded(newop)
398 if not isinstance(newop, Const):
399 newop.set_forwarded(opinfo)
400 else:
401 op.set_forwarded(newop)
402
403 def replace_op_with(self, op, newopnum, args=None, descr=None):
404 newop = op.copy_and_change(newopnum, args, descr)
405 if newop.type != 'v':
406 op = get_box_replacement(op)
407 opinfo = op.get_forwarded()
408 if opinfo is not None:
409 newop.set_forwarded(opinfo)
410 op.set_forwarded(newop)
411 return newop
412
413 def make_constant(self, box, constbox):
414 assert isinstance(constbox, Const)
415 box = get_box_replacement(box)
416 # safety-check: if the constant is outside the bounds for the
417 # box, then it is an invalid loop
418 if (box.get_forwarded() is not None and
419 isinstance(constbox, ConstInt)):
420 info = box.get_forwarded()
421 if isinstance(info, IntBound):
422 if not info.contains(constbox.getint()):
423 raise InvalidLoop("a box is turned into constant that is "
424 "outside the range allowed for that box")
425 else:
426 value = constbox.getint()
427 if isinstance(value, int):
428 # make the range constant, it could be shared with e.g. an arrayinfo's length
429 info.make_eq_const(value)
430 if box.is_constant():
431 return
432 if box.type == 'r' and box.get_forwarded() is not None:
433 opinfo = box.get_forwarded()
434 opinfo.copy_fields_to_const(getptrinfo(constbox), self.optheap)
435 box.set_forwarded(constbox)
436
437 def make_constant_int(self, box, intvalue):
438 self.make_constant(box, ConstInt(intvalue))
439
440 def make_nonnull(self, op):
441 op = self.get_box_replacement(op)
442 if op.is_constant():
443 return
444 if op.type == 'i':
445 # raw pointers
446 return
447 opinfo = op.get_forwarded()
448 if opinfo is not None:
449 assert opinfo.is_nonnull()
450 return
451 op.set_forwarded(info.NonNullPtrInfo())
452
453 def make_nonnull_str(self, op, mode):
454 from rpython.jit.metainterp.optimizeopt import vstring
455
456 op = self.get_box_replacement(op)
457 if op.is_constant():
458 return
459 opinfo = op.get_forwarded()
460 if isinstance(opinfo, vstring.StrPtrInfo):
461 return
462 op.set_forwarded(vstring.StrPtrInfo(mode))
463
464 def ensure_ptr_info_arg0(self, op):
465 from rpython.jit.metainterp.optimizeopt import vstring
466
467 arg0 = self.get_box_replacement(op.getarg(0))
468 if arg0.is_constant():
469 return info.ConstPtrInfo(arg0)
470 opinfo = arg0.get_forwarded()
471 if isinstance(opinfo, info.AbstractVirtualPtrInfo):
472 return opinfo
473 elif opinfo is not None:
474 last_guard_pos = opinfo.get_last_guard_pos()
475 else:
476 last_guard_pos = -1
477 assert opinfo is None or opinfo.__class__ is info.NonNullPtrInfo
478 opnum = op.opnum
479 if (rop.is_getfield(opnum) or opnum == rop.SETFIELD_GC or
480 opnum == rop.QUASIIMMUT_FIELD):
481 descr = op.getdescr()
482 parent_descr = descr.get_parent_descr()
483 if parent_descr.is_object():
484 opinfo = info.InstancePtrInfo(parent_descr)
485 else:
486 opinfo = info.StructPtrInfo(parent_descr)
487 opinfo.init_fields(parent_descr, descr.get_index())
488 elif (rop.is_getarrayitem(opnum) or opnum == rop.SETARRAYITEM_GC or
489 opnum == rop.ARRAYLEN_GC):
490 opinfo = info.ArrayPtrInfo(op.getdescr())
491 elif opnum in (rop.GUARD_CLASS, rop.GUARD_NONNULL_CLASS):
492 opinfo = info.InstancePtrInfo()
493 elif opnum in (rop.STRLEN,):
494 opinfo = vstring.StrPtrInfo(vstring.mode_string)
495 elif opnum in (rop.UNICODELEN,):
496 opinfo = vstring.StrPtrInfo(vstring.mode_unicode)
497 else:
498 assert False, "operations %s unsupported" % op
499 assert isinstance(opinfo, info.NonNullPtrInfo)
500 opinfo.last_guard_pos = last_guard_pos
501 arg0.set_forwarded(opinfo)
502 return opinfo
503
504 def ensure_ptr_info_arg0_array(self, op):
505 # like ensure_ptr_info_arg0, but calling getlenbound on the result is
506 # safe
507 from rpython.jit.metainterp.optimizeopt import vstring
508
509 arg0 = self.get_box_replacement(op.getarg(0))
510 if arg0.is_constant():
511 return info.ConstPtrInfo(arg0)
512 opinfo = arg0.get_forwarded()
513 if isinstance(opinfo, info.ArrayPtrInfo):
514 return opinfo
515 if isinstance(opinfo, info.AbstractStructPtrInfo):
516 raise InvalidLoop("trying to use a struct in place of an array")
517 assert opinfo is None or opinfo.__class__ is info.NonNullPtrInfo
518 opnum = op.opnum
519 if (rop.is_getarrayitem(opnum) or opnum == rop.SETARRAYITEM_GC or
520 opnum == rop.ARRAYLEN_GC):
521 opinfo = info.ArrayPtrInfo(op.getdescr())
522 else:
523 assert False, "operations %s unsupported" % op
524 assert isinstance(opinfo, info.ArrayPtrInfo)
525 arg0.set_forwarded(opinfo)
526 return opinfo
527
528 def new_const(self, fieldofs):
529 if fieldofs.is_pointer_field():
530 return CONST_NULL
531 elif fieldofs.is_float_field():
532 return CONST_ZERO_FLOAT
533 else:
534 return CONST_0
535
536 def new_const_item(self, arraydescr):
537 if arraydescr.is_array_of_pointers():
538 return CONST_NULL
539 elif arraydescr.is_array_of_floats():
540 return CONST_ZERO_FLOAT
541 else:
542 return CONST_0
543
544 def propagate_all_forward(self, trace, call_pure_results=None, flush=True):
545 from rpython.rlib.debug import debug_start, debug_stop
546 debug_start("jit-log-intbounds")
547 try:
548 return self._propagate_all_forward(trace, call_pure_results, flush)
549 finally:
550 debug_stop("jit-log-intbounds")
551
552 def _propagate_all_forward(self, trace, call_pure_results, flush):
553 self.trace = trace
554 if self.log_operations_intbounds:
555 self.log_operations_intbounds.log_inputargs(trace.inputargs)
556 #deadranges = trace.get_dead_ranges()
557 self.call_pure_results = call_pure_results
558 last_op = None
559 i = 0
560 while not trace.done():
561 self._really_emitted_operation = None
562 op = trace.next()
563 if op.getopnum() in (rop.FINISH, rop.JUMP):
564 last_op = op
565 break
566 self.send_extra_operation(op)
567 #trace.kill_cache_at(deadranges[i + trace.start_index])
568 if op.type != 'v':
569 i += 1
570 newop = self.get_box_replacement(op)
571 if newop is not op:
572 trace.replace_last_cached(op, newop)
573 if self.log_operations_intbounds and self._really_emitted_operation is op:
574 # logging the result cannot be done in _emit_operation, because
575 # at that point the postprocess functions have not been called,
576 # so the bounds aren't known yet
577 self.log_operations_intbounds.log_result(op)
578
579 # accumulate counters
580 if flush:
581 self.flush()
582 if last_op:
583 self.send_extra_operation(last_op)
584 self.resumedata_memo.update_counters(self.metainterp_sd.profiler)
585
586 return (BasicLoopInfo(trace.inputargs, self.quasi_immutable_deps, last_op),
587 self._newoperations)
588
589 def _clean_optimization_info(self, lst):
590 for op in lst:
591 if op.get_forwarded() is not None:
592 op.set_forwarded(None)
593
594 def send_extra_operation(self, op, opt=None):
595 if opt is None:
596 opt = self.first_optimization
597 opt_results = None
598 while opt is not None:
599 opt_result = opt.propagate_forward(op)
600 if opt_result is None:
601 op = None
602 break
603 if opt_result is not PASS_OP_ON:
604 if opt_results is None:
605 opt_results = [opt_result]
606 else:
607 opt_results.append(opt_result)
608 op = opt_result.op
609 else:
610 op = opt.last_emitted_operation
611 opt = opt.next_optimization
612 if opt_results is not None:
613 index = len(opt_results) - 1
614 while index >= 0:
615 opt_results[index].callback()
616 index -= 1
617
618 def propagate_forward(self, op):
619 dispatch_opt(self, op)
620
621 def emit_extra(self, op, emit=True):
622 # no forwarding, because we're at the end of the chain
623 self.emit(op)
624
625 def emit(self, op):
626 # this actually emits the operation instead of forwarding it
627 if rop.returns_bool_result(op.opnum):
628 self.getintbound(op).make_bool()
629 self._emit_operation(op)
630 op = self.get_box_replacement(op)
631 if op.type == 'i':
632 opinfo = op.get_forwarded()
633 if opinfo is not None:
634 assert isinstance(opinfo, IntBound)
635 if opinfo.is_constant():
636 #if not we_are_translated():
637 # import pdb; pdb.set_trace()
638 op.set_forwarded(ConstInt(opinfo.get_constant_int()))
639
640 @specialize.argtype(0)
641 def _emit_operation(self, op):
642 assert not rop.is_call_pure(op.getopnum())
643 orig_op = op
644 op = self.get_box_replacement(op)
645 if op.is_constant():
646 return # can happen e.g. if we postpone the operation that becomes
647 # constant
648 # XXX kill, requires thinking
649 #op = self.replace_op_with(op, op.opnum)
650 for i in range(op.numargs()):
651 arg = self.force_box(op.getarg(i))
652 op.setarg(i, arg)
653 self.metainterp_sd.profiler.count(jitprof.Counters.OPT_OPS)
654 if rop.is_guard(op.opnum):
655 assert isinstance(op, GuardResOp)
656 self.metainterp_sd.profiler.count(jitprof.Counters.OPT_GUARDS)
657 pendingfields = self.pendingfields
658 self.pendingfields = None
659 if self.replaces_guard and orig_op in self.replaces_guard:
660 self.replace_guard_op(self.replaces_guard[orig_op], op)
661 del self.replaces_guard[orig_op]
662 return
663 else:
664 op = self.emit_guard_operation(op, pendingfields)
665 opnum = op.opnum
666 if ((rop.has_no_side_effect(opnum) or rop.is_guard(opnum) or
667 rop.is_jit_debug(opnum) or
668 rop.is_ovf(opnum)) and not self.is_call_pure_pure_canraise(op)):
669 pass
670 else:
671 self._last_guard_op = None
672 self._really_emitted_operation = op
673 self._newoperations.append(op)
674 self._emittedoperations[op] = None
675 if self.log_operations_intbounds:
676 self.log_operations_intbounds.log_op(op)
677
678
679 def emit_guard_operation(self, op, pendingfields):
680 guard_op = op # self.replace_op_with(op, op.getopnum())
681 opnum = guard_op.getopnum()
682 # If guard_(no)_exception is merged with another previous guard, then
683 # it *should* be in "some_call;guard_not_forced;guard_(no)_exception".
684 # The guard_(no)_exception can also occur at different places,
685 # but these should not be preceeded immediately by another guard.
686 # Sadly, asserting this seems to fail in rare cases. So instead,
687 # we simply give up sharing.
688 if (opnum in (rop.GUARD_NO_EXCEPTION, rop.GUARD_EXCEPTION) and
689 self._last_guard_op is not None and
690 self._last_guard_op.getopnum() != rop.GUARD_NOT_FORCED):
691 self._last_guard_op = None
692 if opnum == rop.GUARD_ALWAYS_FAILS:
693 # GUARD_ALWAYS_FAILS must never share resume data with a previous
694 # guard. otherwise it's possible that we never make progress and
695 # recompile the same bytecodes again and again. see
696 # test_bug_segmented_trace_makes_no_progress
697 self._last_guard_op = None
698 #
699 if (self._last_guard_op and guard_op.getdescr() is None):
700 self.metainterp_sd.profiler.count_ops(opnum,
701 jitprof.Counters.OPT_GUARDS_SHARED)
702 op = self._copy_resume_data_from(guard_op,
703 self._last_guard_op)
704 else:
705 op = self.store_final_boxes_in_guard(guard_op, pendingfields)
706 self._last_guard_op = op
707 # for unrolling
708 for farg in op.getfailargs():
709 if farg:
710 self.force_box(farg)
711 if op.getopnum() == rop.GUARD_EXCEPTION:
712 self._last_guard_op = None
713 return op
714
715 def _copy_resume_data_from(self, guard_op, last_guard_op):
716 last_descr = last_guard_op.getdescr()
717 descr = compile.invent_fail_descr_for_op(guard_op.getopnum(), self, last_descr)
718 assert isinstance(last_descr, compile.ResumeGuardDescr)
719 if not isinstance(descr, compile.ResumeGuardCopiedDescr):
720 descr.copy_all_attributes_from(last_descr)
721 guard_op.setdescr(descr)
722 guard_op.setfailargs(last_guard_op.getfailargs())
723 descr.store_hash(self.metainterp_sd)
724 assert isinstance(guard_op, GuardResOp)
725 if guard_op.getopnum() == rop.GUARD_VALUE:
726 guard_op = self._maybe_replace_guard_value(guard_op, descr)
727 return guard_op
728
729 def getlastop(self):
730 return self._really_emitted_operation
731
732 def is_call_pure_pure_canraise(self, op):
733 if not rop.is_call_pure(op.getopnum()):
734 return False
735 effectinfo = op.getdescr().get_extra_info()
736 if effectinfo.check_can_raise(ignore_memoryerror=True):
737 return True
738 return False
739
740 def replace_guard_op(self, old_op_pos, new_op):
741 old_op = self._newoperations[old_op_pos]
742 assert old_op.is_guard()
743 old_descr = old_op.getdescr()
744 new_descr = new_op.getdescr()
745 new_descr.copy_all_attributes_from(old_descr)
746 self._newoperations[old_op_pos] = new_op
747 self._emittedoperations[new_op] = None
748
749 def store_final_boxes_in_guard(self, op, pendingfields):
750 assert pendingfields is not None
751 if op.getdescr() is not None:
752 descr = op.getdescr()
753 assert isinstance(descr, compile.ResumeGuardDescr)
754 else:
755 descr = compile.invent_fail_descr_for_op(op.getopnum(), self)
756 op.setdescr(descr)
757 assert isinstance(descr, compile.ResumeGuardDescr)
758 assert isinstance(op, GuardResOp)
759 modifier = resume.ResumeDataVirtualAdder(self, descr, op, self.trace,
760 self.resumedata_memo)
761 try:
762 newboxes = modifier.finish(pendingfields)
763 if (newboxes is not None and
764 len(newboxes) > self.metainterp_sd.options.failargs_limit):
765 raise resume.TagOverflow
766 except resume.TagOverflow:
767 raise compile.giveup()
768 # check no duplicates
769 #if not we_are_translated():
770 seen = {}
771 for box in newboxes:
772 if box is not None:
773 assert box not in seen
774 seen[box] = None
775 descr.store_final_boxes(op, newboxes, self.metainterp_sd)
776 #
777 if op.getopnum() == rop.GUARD_VALUE:
778 op = self._maybe_replace_guard_value(op, descr)
779 return op
780
781 def _maybe_replace_guard_value(self, op, descr):
782 if op.getarg(0).type == 'i':
783 b = self.getintbound(op.getarg(0))
784 if b.is_bool():
785 # Hack: turn guard_value(bool) into guard_true/guard_false.
786 # This is done after the operation is emitted to let
787 # store_final_boxes_in_guard set the guard_opnum field of
788 # the descr to the original rop.GUARD_VALUE.
789 constvalue = op.getarg(1).getint()
790 if constvalue == 0:
791 opnum = rop.GUARD_FALSE
792 elif constvalue == 1:
793 opnum = rop.GUARD_TRUE
794 else:
795 # Issue #3128: there might be rare cases where strange
796 # code is produced. That issue hits the assert from
797 # OptUnroll.inline_short_preamble's send_extra_operation().
798 # Better just disable this optimization than crash with
799 # an AssertionError here. Note also that such code might
800 # trigger an InvalidLoop to be raised later---so we must
801 # not crash here.
802 return op
803 newop = self.replace_op_with(op, opnum, [op.getarg(0)], descr)
804 return newop
805 return op
806
807 def optimize_default(self, op):
808 self.emit(op)
809
810 def constant_fold(self, op):
811 self.protect_speculative_operation(op)
812 argboxes = [self.get_constant_box(op.getarg(i))
813 for i in range(op.numargs())]
814 return execute_nonspec_const(self.cpu, None,
815 op.getopnum(), argboxes,
816 op.getdescr(), op.type)
817
818 def protect_speculative_operation(self, op):
819 """When constant-folding a pure operation that reads memory from
820 a gcref, make sure that the gcref is non-null and of a valid type.
821 Otherwise, raise SpeculativeError. This should only occur when
822 unrolling and optimizing the unrolled loop. Note that if
823 cpu.supports_guard_gc_type is false, we can't really do this
824 check at all, but then we don't unroll in that case.
825 """
826 opnum = op.getopnum()
827 cpu = self.cpu
828
829 if OpHelpers.is_pure_getfield(opnum, op.getdescr()):
830 fielddescr = op.getdescr()
831 ref = self.get_constant_box(op.getarg(0)).getref_base()
832 cpu.protect_speculative_field(ref, fielddescr)
833 return
834
835 elif (opnum == rop.GETARRAYITEM_GC_PURE_I or
836 opnum == rop.GETARRAYITEM_GC_PURE_R or
837 opnum == rop.GETARRAYITEM_GC_PURE_F or
838 opnum == rop.ARRAYLEN_GC):
839 arraydescr = op.getdescr()
840 array = self.get_constant_box(op.getarg(0)).getref_base()
841 cpu.protect_speculative_array(array, arraydescr)
842 if opnum == rop.ARRAYLEN_GC:
843 return
844 arraylength = cpu.bh_arraylen_gc(array, arraydescr)
845
846 elif (opnum == rop.STRGETITEM or
847 opnum == rop.STRLEN):
848 string = self.get_constant_box(op.getarg(0)).getref_base()
849 cpu.protect_speculative_string(string)
850 if opnum == rop.STRLEN:
851 return
852 arraylength = cpu.bh_strlen(string)
853
854 elif (opnum == rop.UNICODEGETITEM or
855 opnum == rop.UNICODELEN):
856 unicode = self.get_constant_box(op.getarg(0)).getref_base()
857 cpu.protect_speculative_unicode(unicode)
858 if opnum == rop.UNICODELEN:
859 return
860 arraylength = cpu.bh_unicodelen(unicode)
861
862 else:
863 return
864
865 index = self.get_constant_box(op.getarg(1)).getint()
866 if not (0 <= index < arraylength):
867 raise SpeculativeError
868
869 @staticmethod
870 def _check_subclass(vtable1, vtable2): # checks that vtable1 is a subclass of vtable2
871 known_class = llmemory.cast_adr_to_ptr(
872 llmemory.cast_int_to_adr(vtable1),
873 rclass.CLASSTYPE)
874 expected_class = llmemory.cast_adr_to_ptr(
875 llmemory.cast_int_to_adr(vtable2),
876 rclass.CLASSTYPE)
877 # note: the test is for a range including 'max', but 'max'
878 # should never be used for actual classes. Including it makes
879 # it easier to pass artificial tests.
880 return (expected_class.subclassrange_min
881 <= known_class.subclassrange_min
882 <= expected_class.subclassrange_max)
883
884 def is_virtual(self, op):
885 opinfo = getptrinfo(op)
886 return opinfo is not None and opinfo.is_virtual()
887
888 # These are typically removed already by OptRewrite, but it can be
889 # dissabled and unrolling emits some SAME_AS ops to setup the
890 # optimizier state. These needs to always be optimized out.
891 def optimize_SAME_AS_I(self, op):
892 self.make_equal_to(op, op.getarg(0))
893 optimize_SAME_AS_R = optimize_SAME_AS_I
894 optimize_SAME_AS_F = optimize_SAME_AS_I
895
896 dispatch_opt = make_dispatcher_method(Optimizer, 'optimize_',
897 default=Optimizer.optimize_default)
898
899
900 class CantReplaceGuards(object):
901 def __init__(self, optimizer):
902 self.optimizer = optimizer
903
904 def __enter__(self, *args):
905 self.oldval = self.optimizer.can_replace_guards
906 self.optimizer.can_replace_guards = False
907
908 def __exit__(self, *args):
909 self.optimizer.can_replace_guards = self.oldval
910
911