Debian Codegraph @

rpython/translator/backendopt/test/test_inline.py

raw symbols SCIP
1 # XXX clean up these tests to use more uniform helpers
2 import py
3 from rpython.flowspace.model import Variable, Constant, checkgraph
4 from rpython.translator.backendopt import canraise
5 from rpython.translator.backendopt.inline import (simple_inline_function,
6 CannotInline, auto_inlining, Inliner, collect_called_graphs,
7 measure_median_execution_cost, instrument_inline_candidates,
8 auto_inline_graphs)
9 from rpython.translator.translator import TranslationContext, graphof
10 from rpython.rtyper.llinterp import LLInterpreter
11 from rpython.rtyper.test.tool import BaseRtypingTest
12 from rpython.rlib.rarithmetic import ovfcheck
13 from rpython.translator.test.snippet import is_perfect_number
14 from rpython.translator.backendopt.all import INLINE_THRESHOLD_FOR_TEST
15 from rpython.conftest import option
16 from rpython.translator.backendopt import removenoops
17 from rpython.flowspace.model import summary
18
19 def sanity_check(t):
20 # look for missing '.concretetype'
21 for graph in t.graphs:
22 checkgraph(graph)
23 for node in graph.iterblocks():
24 for v in node.inputargs:
25 assert hasattr(v, 'concretetype')
26 for op in node.operations:
27 for v in op.args:
28 assert hasattr(v, 'concretetype')
29 assert hasattr(op.result, 'concretetype')
30 for node in graph.iterlinks():
31 if node.exitcase is not None:
32 assert hasattr(node, 'llexitcase')
33 for v in node.args:
34 assert hasattr(v, 'concretetype')
35 if isinstance(node.last_exception, (Variable, Constant)):
36 assert hasattr(node.last_exception, 'concretetype')
37 if isinstance(node.last_exc_value, (Variable, Constant)):
38 assert hasattr(node.last_exc_value, 'concretetype')
39
40
41 class CustomError1(Exception):
42 def __init__(self):
43 self.data = 123
44
45 class CustomError2(Exception):
46 def __init__(self):
47 self.data2 = 456
48
49 class TestInline(BaseRtypingTest):
50 def translate(self, func, argtypes):
51 t = TranslationContext()
52 t.buildannotator().build_types(func, argtypes)
53 t.buildrtyper().specialize()
54 return t
55
56 def check_inline(self, func, in_func, sig, entry=None,
57 inline_guarded_calls=False,
58 graph=False):
59 if entry is None:
60 entry = in_func
61 t = self.translate(entry, sig)
62 # inline!
63 sanity_check(t) # also check before inlining (so we don't blame it)
64 if option.view:
65 t.view()
66 raise_analyzer = canraise.RaiseAnalyzer(t)
67 inliner = Inliner(t, graphof(t, in_func), func,
68 t.rtyper.lltype_to_classdef_mapping(),
69 inline_guarded_calls,
70 raise_analyzer=raise_analyzer)
71 inliner.inline_all()
72 if option.view:
73 t.view()
74 sanity_check(t)
75 interp = LLInterpreter(t.rtyper)
76 def eval_func(args):
77 return interp.eval_graph(graphof(t, entry), args)
78 if graph:
79 return eval_func, graphof(t, func)
80 return eval_func
81
82 def check_auto_inlining(self, func, sig, multiplier=None, call_count_check=False,
83 remove_same_as=False, heuristic=None, const_fold_first=False):
84 t = self.translate(func, sig)
85 if const_fold_first:
86 from rpython.translator.backendopt.constfold import constant_fold_graph
87 from rpython.translator.simplify import eliminate_empty_blocks
88 for graph in t.graphs:
89 constant_fold_graph(graph)
90 eliminate_empty_blocks(graph)
91 if option.view:
92 t.view()
93 # inline!
94 sanity_check(t) # also check before inlining (so we don't blame it)
95
96 threshold = INLINE_THRESHOLD_FOR_TEST
97 if multiplier is not None:
98 threshold *= multiplier
99
100 call_count_pred = None
101 if call_count_check:
102 call_count_pred = lambda lbl: True
103 instrument_inline_candidates(t.graphs, threshold)
104
105 if remove_same_as:
106 for graph in t.graphs:
107 removenoops.remove_same_as(graph)
108
109 if heuristic is not None:
110 kwargs = {"heuristic": heuristic}
111 else:
112 kwargs = {}
113 auto_inlining(t, threshold, call_count_pred=call_count_pred, **kwargs)
114
115 sanity_check(t)
116 if option.view:
117 t.view()
118 interp = LLInterpreter(t.rtyper)
119 def eval_func(args):
120 return interp.eval_graph(graphof(t, func), args)
121 return eval_func, t
122
123
124 def test_inline_simple(self):
125 def f(x, y):
126 return (g(x, y) + 1) * x
127 def g(x, y):
128 if x > 0:
129 return x * y
130 else:
131 return -x * y
132 eval_func = self.check_inline(g, f, [int, int])
133 result = eval_func([-1, 5])
134 assert result == f(-1, 5)
135 result = eval_func([2, 12])
136 assert result == f(2, 12)
137
138 def test_nothing_to_inline(self):
139 def f():
140 return 1
141 def g():
142 return 2
143 eval_func = self.check_inline(g, f, [])
144 assert eval_func([]) == 1
145
146 def test_inline_big(self):
147 def f(x):
148 result = []
149 for i in range(1, x+1):
150 if is_perfect_number(i):
151 result.append(i)
152 return result
153 eval_func = self.check_inline(is_perfect_number, f, [int])
154 result = eval_func([10])
155 result = self.ll_to_list(result)
156 assert len(result) == len(f(10))
157
158 def test_inline_raising(self):
159 def f(x):
160 if x == 1:
161 raise CustomError1
162 return x
163 def g(x):
164 a = f(x)
165 if x == 2:
166 raise CustomError2
167 def h(x):
168 try:
169 g(x)
170 except CustomError1:
171 return 1
172 except CustomError2:
173 return 2
174 return x
175 eval_func = self.check_inline(f,g, [int], entry=h)
176 result = eval_func([0])
177 assert result == 0
178 result = eval_func([1])
179 assert result == 1
180 result = eval_func([2])
181 assert result == 2
182
183 def test_inline_several_times(self):
184 def f(x):
185 return (x + 1) * 2
186 def g(x):
187 if x:
188 a = f(x) + f(x)
189 else:
190 a = f(x) + 1
191 return a + f(x)
192 eval_func = self.check_inline(f, g, [int])
193 result = eval_func([0])
194 assert result == g(0)
195 result = eval_func([42])
196 assert result == g(42)
197
198 def test_always_inline(self):
199 def f(x, y, z, k):
200 p = (((x, y), z), k)
201 return p[0][0][0] + p[-1]
202 f._always_inline_ = True
203
204 def g(x, y, z, k):
205 a = f(x, y, z, k)
206 return a
207 eval_func, t = self.check_auto_inlining(g, [int, int, int, int], multiplier=0.1)
208 graph = graphof(t, g)
209 s = summary(graph)
210 assert len(s) > 3
211
212 def test_inline_exceptions(self):
213 customError1 = CustomError1()
214 customError2 = CustomError2()
215 def f(x):
216 if x == 0:
217 raise customError1
218 if x == 1:
219 raise customError2
220 def g(x):
221 try:
222 f(x)
223 except CustomError1:
224 return 2
225 except CustomError2:
226 return x+2
227 return 1
228 eval_func = self.check_inline(f, g, [int])
229 result = eval_func([0])
230 assert result == 2
231 result = eval_func([1])
232 assert result == 3
233 result = eval_func([42])
234 assert result == 1
235
236 def test_inline_const_exceptions(self):
237 valueError = ValueError()
238 keyError = KeyError()
239 def f(x):
240 if x == 0:
241 raise valueError
242 if x == 1:
243 raise keyError
244 def g(x):
245 try:
246 f(x)
247 except ValueError:
248 return 2
249 except KeyError:
250 return x+2
251 return 1
252 eval_func = self.check_inline(f, g, [int])
253 result = eval_func([0])
254 assert result == 2
255 result = eval_func([1])
256 assert result == 3
257 result = eval_func([42])
258 assert result == 1
259
260 def test_inline_exception_guarded(self):
261 def h(x):
262 if x == 1:
263 raise CustomError1()
264 elif x == 2:
265 raise CustomError2()
266 return 1
267 def f(x):
268 try:
269 return h(x)
270 except:
271 return 87
272 def g(x):
273 try:
274 return f(x)
275 except CustomError1:
276 return 2
277 eval_func = self.check_inline(f, g, [int], inline_guarded_calls=True)
278 result = eval_func([0])
279 assert result == 1
280 result = eval_func([1])
281 assert result == 87
282 result = eval_func([2])
283 assert result == 87
284
285 def test_inline_with_raising_non_call_op(self):
286 class A:
287 pass
288 def f():
289 return A()
290 def g():
291 try:
292 a = f()
293 except MemoryError:
294 return 1
295 return 2
296 py.test.raises(CannotInline, self.check_inline, f, g, [])
297
298 def test_inline_var_exception(self):
299 def f(x):
300 e = None
301 if x == 0:
302 e = CustomError1()
303 elif x == 1:
304 e = KeyError()
305 if x == 0 or x == 1:
306 raise e
307 def g(x):
308 try:
309 f(x)
310 except CustomError1:
311 return 2
312 except KeyError:
313 return 3
314 return 1
315
316 eval_func, _ = self.check_auto_inlining(g, [int], multiplier=10)
317 result = eval_func([0])
318 assert result == 2
319 result = eval_func([1])
320 assert result == 3
321 result = eval_func([42])
322 assert result == 1
323
324 def test_inline_nonraising_into_catching(self):
325 def f(x):
326 return x+1
327 def g(x):
328 try:
329 return f(x)
330 except KeyError:
331 return 42
332 eval_func = self.check_inline(f, g, [int])
333 result = eval_func([7654])
334 assert result == 7655
335
336 def DONOTtest_call_call(self):
337 # for reference. Just remove this test if we decide not to support
338 # catching exceptions while inlining a graph that contains further
339 # direct_calls.
340 def e(x):
341 if x < 0:
342 raise KeyError
343 return x+1
344 def f(x):
345 return e(x)+2
346 def g(x):
347 try:
348 return f(x)+3
349 except KeyError:
350 return -1
351 eval_func = self.check_inline(f, g, [int])
352 result = eval_func([100])
353 assert result == 106
354 result = eval_func(g, [-100])
355 assert result == -1
356
357 def test_for_loop(self):
358 def f(x):
359 result = 0
360 for i in range(0, x):
361 result += i
362 return result
363 t = self.translate(f, [int])
364 sanity_check(t) # also check before inlining (so we don't blame it)
365 for graph in t.graphs:
366 if graph.name.startswith('ll_rangenext'):
367 break
368 else:
369 assert 0, "cannot find ll_rangenext_*() function"
370 simple_inline_function(t, graph, graphof(t, f))
371 sanity_check(t)
372 interp = LLInterpreter(t.rtyper)
373 result = interp.eval_graph(graphof(t, f), [10])
374 assert result == 45
375
376 def test_inline_constructor(self):
377 class A:
378 def __init__(self, x, y):
379 self.bounds = (x, y)
380 def area(self, height=10):
381 return height * (self.bounds[1] - self.bounds[0])
382 def f(i):
383 a = A(117, i)
384 return a.area()
385 eval_func = self.check_inline(A.__init__.im_func, f, [int])
386 result = eval_func([120])
387 assert result == 30
388
389 def test_cannot_inline_recursive_function(self):
390 def factorial(n):
391 if n > 1:
392 return n * factorial(n-1)
393 else:
394 return 1
395 def f(n):
396 return factorial(n//2)
397 py.test.raises(CannotInline, self.check_inline, factorial, f, [int])
398
399 def test_auto_inlining_small_call_big(self):
400 def leaf(n):
401 total = 0
402 i = 0
403 while i < n:
404 total += i
405 if total > 100:
406 raise OverflowError
407 i += 1
408 return total
409 def g(n):
410 return leaf(n)
411 def f(n):
412 try:
413 return g(n)
414 except OverflowError:
415 return -1
416 eval_func, t = self.check_auto_inlining(f, [int], multiplier=10)
417 f_graph = graphof(t, f)
418 assert len(collect_called_graphs(f_graph, t)) == 0
419
420 result = eval_func([10])
421 assert result == 45
422 result = eval_func([15])
423 assert result == -1
424
425 def test_auto_inlining_small_call_big_call_count(self):
426 def leaf(n):
427 total = 0
428 i = 0
429 while i < n:
430 total += i
431 if total > 100:
432 raise OverflowError
433 i += 1
434 return total
435 def g(n):
436 return leaf(n)
437 def f(n):
438 try:
439 return g(n)
440 except OverflowError:
441 return -1
442 eval_func, t = self.check_auto_inlining(f, [int], multiplier=10,
443 call_count_check=True)
444 f_graph = graphof(t, f)
445 assert len(collect_called_graphs(f_graph, t)) == 0
446
447 result = eval_func([10])
448 assert result == 45
449 result = eval_func([15])
450 assert result == -1
451
452 def test_inline_exception_catching(self):
453 def f3():
454 raise CustomError1
455 def f2():
456 try:
457 f3()
458 except CustomError1:
459 return True
460 else:
461 return False
462 def f():
463 return f2()
464 eval_func = self.check_inline(f2, f, [])
465 result = eval_func([])
466 assert result is True
467
468 def test_inline_catching_different_exception(self):
469 d = {1: 2}
470 def f2(n):
471 try:
472 return ovfcheck(n+1)
473 except OverflowError:
474 raise
475 def f(n):
476 try:
477 return f2(n)
478 except ValueError:
479 return -1
480 eval_func = self.check_inline(f2, f, [int])
481 result = eval_func([54])
482 assert result == 55
483
484 def test_inline_raiseonly(self):
485 c = CustomError1()
486 def f2(x):
487 raise c
488 def f(x):
489 try:
490 return f2(x)
491 except CustomError1:
492 return 42
493 eval_func = self.check_inline(f2, f, [int])
494 result = eval_func([98371])
495 assert result == 42
496
497 def test_measure_median_execution_cost(self):
498 def f(x):
499 x += 1
500 x += 1
501 x += 1
502 while True:
503 x += 1
504 x += 1
505 x += 1
506 if x: break
507 x += 1
508 x += 1
509 x += 1
510 x += 1
511 x += 1
512 x += 1
513 return x
514 t = TranslationContext()
515 graph = t.buildflowgraph(f)
516 res = measure_median_execution_cost(graph)
517 assert round(res, 5) == round(32.333333333, 5)
518
519 def test_indirect_call_with_exception(self):
520 class Dummy:
521 pass
522 def x1():
523 return Dummy() # can raise MemoryError
524 def x2():
525 return None
526 def x3(x):
527 if x:
528 f = x1
529 else:
530 f = x2
531 return f()
532 def x4():
533 try:
534 x3(0)
535 x3(1)
536 except CustomError2:
537 return 0
538 return 1
539 assert x4() == 1
540 py.test.raises(CannotInline, self.check_inline, x3, x4, [])
541
542 def test_list_iteration(self):
543 def f():
544 tot = 0
545 for item in [1,2,3]:
546 tot += item
547 return tot
548
549 eval_func, t = self.check_auto_inlining(f, [])
550 f_graph = graphof(t, f)
551 called_graphs = collect_called_graphs(f_graph, t)
552 assert len(called_graphs) == 0
553
554 result = eval_func([])
555 assert result == 6
556
557 def test_bug_in_find_exception_type(self):
558 def h():
559 pass
560 def g(i):
561 if i > 0:
562 raise IndexError
563 else:
564 h()
565 def f(i):
566 try:
567 g(i)
568 except IndexError:
569 pass
570
571 eval_func, t = self.check_auto_inlining(f, [int], remove_same_as=True,
572 const_fold_first=True)
573 eval_func([-66])
574 eval_func([282])
575
576 def test_correct_keepalive_placement(self):
577 def h(x):
578 if not x:
579 raise ValueError
580 return 1
581 def f(x):
582 s = "a %s" % (x, )
583 try:
584 h(len(s))
585 except ValueError:
586 pass
587 return -42
588 eval_func, t = self.check_auto_inlining(f, [int])
589 res = eval_func([42])
590 assert res == -42
591
592 def test_keepalive_hard_case(self):
593 from rpython.rtyper.lltypesystem import lltype
594 Y = lltype.Struct('y', ('n', lltype.Signed))
595 X = lltype.GcStruct('x', ('y', Y))
596 def g(x):
597 if x:
598 return 3
599 else:
600 return 4
601 def f():
602 x = lltype.malloc(X)
603 x.y.n = 2
604 y = x.y
605 z1 = g(y.n)
606 z = y.n
607 return z+z1
608 eval_func = self.check_inline(g, f, [])
609 res = eval_func([])
610 assert res == 5
611
612 def test_auto_inline_graphs_from_anywhere(self):
613 def leaf(n):
614 return n
615 def f(n):
616 return leaf(n)
617 t = self.translate(f, [int])
618 f_graph = graphof(t, f)
619 assert len(collect_called_graphs(f_graph, t)) == 1
620 auto_inline_graphs(t, [f_graph], 32)
621 assert len(collect_called_graphs(f_graph, t)) == 1
622 auto_inline_graphs(t, [f_graph], 32, inline_graph_from_anywhere=True)
623 assert len(collect_called_graphs(f_graph, t)) == 0
624
625 def test_inline_all(self):
626 def g(x):
627 return x + 1
628 def f(x):
629 return g(x) * g(x+1) * g(x+2) * g(x+3) * g(x+4) * g(x+5)
630 t = self.translate(f, [int])
631 sanity_check(t) # also check before inlining (so we don't blame it)
632 simple_inline_function(t, graphof(t, g), graphof(t, f))
633 sanity_check(t)
634 assert summary(graphof(t, f)) == {'int_add': 11, 'int_mul': 5}
635 interp = LLInterpreter(t.rtyper)
636 result = interp.eval_graph(graphof(t, f), [10])
637 assert result == f(10)
638
639 def test_inline_all_exc(self):
640 def g(x):
641 if x < -100:
642 raise ValueError
643 return x + 1
644 def f(x):
645 n1 = g(x) * g(x+1)
646 try:
647 n2 = g(x+2) * g(x+3)
648 except ValueError:
649 n2 = 1
650 n3 = g(x+4) * g(x+5)
651 return n1 * n2 * n3
652 t = self.translate(f, [int])
653 sanity_check(t) # also check before inlining (so we don't blame it)
654 simple_inline_function(t, graphof(t, g), graphof(t, f))
655 sanity_check(t)
656 assert summary(graphof(t, f)) == {'int_add': 11, 'int_mul': 5,
657 'cast_pointer': 12, 'getfield': 6,
658 'int_lt': 6}
659 interp = LLInterpreter(t.rtyper)
660 result = interp.eval_graph(graphof(t, f), [10])
661 assert result == f(10)