Source

pypy / pypy / jit / metainterp / test / test_warmspot.py

The branch 'autoreds' does not exist.
Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
import py
from pypy.jit.metainterp.warmspot import get_stats
from pypy.rlib.jit import JitDriver, set_param, unroll_safe
from pypy.jit.backend.llgraph import runner

from pypy.jit.metainterp.test.support import LLJitMixin, OOJitMixin
from pypy.jit.metainterp.optimizeopt import ALL_OPTS_NAMES


class Exit(Exception):
    def __init__(self, result):
        self.result = result


class WarmspotTests(object):

    def test_basic(self):
        mydriver = JitDriver(reds=['a'],
                             greens=['i'])
        CODE_INCREASE = 0
        CODE_JUMP = 1
        lst = [CODE_INCREASE, CODE_INCREASE, CODE_JUMP]
        def interpreter_loop(a):
            i = 0
            while True:
                mydriver.jit_merge_point(i=i, a=a)
                if i >= len(lst):
                    break
                elem = lst[i]
                if elem == CODE_INCREASE:
                    a = a + 1
                    i += 1
                elif elem == CODE_JUMP:
                    if a < 20:
                        i = 0
                        mydriver.can_enter_jit(i=i, a=a)
                    else:
                        i += 1
                else:
                    pass
            raise Exit(a)

        def main(a):
            try:
                interpreter_loop(a)
            except Exit, e:
                return e.result

        res = self.meta_interp(main, [1])
        assert res == 21

    def test_reentry(self):
        mydriver = JitDriver(reds = ['n'], greens = [])

        def f(n):
            while n > 0:
                mydriver.can_enter_jit(n=n)
                mydriver.jit_merge_point(n=n)
                if n % 20 == 0:
                    n -= 2
                n -= 1

        res = self.meta_interp(f, [60])
        assert res == f(30)

    def test_location(self):
        def get_printable_location(n):
            return 'GREEN IS %d.' % n
        myjitdriver = JitDriver(greens=['n'], reds=['m'],
                                get_printable_location=get_printable_location)
        def f(n, m):
            while m > 0:
                myjitdriver.can_enter_jit(n=n, m=m)
                myjitdriver.jit_merge_point(n=n, m=m)
                m -= 1

        self.meta_interp(f, [123, 10])
        assert len(get_stats().locations) >= 4
        for loc in get_stats().locations:
            assert loc == (0, 0, 123)

    def test_set_param_enable_opts(self):
        from pypy.rpython.annlowlevel import llstr, hlstr

        myjitdriver = JitDriver(greens = [], reds = ['n'])
        class A(object):
            def m(self, n):
                return n-1

        def g(n):
            while n > 0:
                myjitdriver.can_enter_jit(n=n)
                myjitdriver.jit_merge_point(n=n)
                n = A().m(n)
            return n
        def f(n, enable_opts):
            set_param(None, 'enable_opts', hlstr(enable_opts))
            return g(n)

        # check that the set_param will override the default
        res = self.meta_interp(f, [10, llstr('')])
        assert res == 0
        self.check_resops(new_with_vtable=1)

        res = self.meta_interp(f, [10, llstr(ALL_OPTS_NAMES)],
                               enable_opts='')
        assert res == 0
        self.check_resops(new_with_vtable=0)

    def test_unwanted_loops(self):
        mydriver = JitDriver(reds = ['n', 'total', 'm'], greens = [])

        def loop1(n):
            # the jit should not look here, as there is a loop
            res = 0
            for i in range(n):
                res += i
            return res

        @unroll_safe
        def loop2(n):
            # the jit looks here, due to the decorator
            for i in range(5):
                n += 1
            return n

        def f(m):
            total = 0
            n = 0
            while n < m:
                mydriver.can_enter_jit(n=n, total=total, m=m)
                mydriver.jit_merge_point(n=n, total=total, m=m)
                total += loop1(n)
                n = loop2(n)
            return total
        self.meta_interp(f, [50])
        self.check_enter_count_at_most(2)

    def test_wanted_unrolling_and_preinlining(self):
        mydriver = JitDriver(reds = ['n', 'm'], greens = [])

        @unroll_safe
        def loop2(n):
            # the jit looks here, due to the decorator
            for i in range(5):
                n += 1
            return n
        loop2._always_inline_ = True

        def g(n):
            return loop2(n)
        g._dont_inline_ = True

        def f(m):
            n = 0
            while n < m:
                mydriver.can_enter_jit(n=n, m=m)
                mydriver.jit_merge_point(n=n, m=m)
                n = g(n)
            return n
        self.meta_interp(f, [50], backendopt=True)
        self.check_enter_count_at_most(2)
        self.check_resops(call=0)

    def test_loop_header(self):
        # artificial test: we enter into the JIT only when can_enter_jit()
        # is seen, but we close a loop in the JIT much more quickly
        # because of loop_header().
        mydriver = JitDriver(reds = ['n', 'm'], greens = [])

        def f(m):
            n = 0
            while True:
                mydriver.jit_merge_point(n=n, m=m)
                if n > m:
                    m -= 1
                    if m < 0:
                        return n
                    n = 0
                    mydriver.can_enter_jit(n=n, m=m)
                else:
                    n += 1
                    mydriver.loop_header()
        assert f(15) == 1
        res = self.meta_interp(f, [15], backendopt=True)
        assert res == 1
        self.check_resops(int_add=2)   # I get 13 without the loop_header()

    def test_omit_can_enter_jit(self):
        # Simple test comparing the effects of always giving a can_enter_jit(),
        # or not giving any.  Mostly equivalent, except that if given, it is
        # ignored the first time, and so it ends up taking one extra loop to
        # start JITting.
        mydriver = JitDriver(greens=[], reds=['m'])
        #
        for i2 in range(10):
            def f2(m):
                while m > 0:
                    mydriver.jit_merge_point(m=m)
                    m -= 1
            self.meta_interp(f2, [i2])
            try:
                self.check_jitcell_token_count(1)
                break
            except AssertionError:
                print "f2: no loop generated for i2==%d" % i2
        else:
            raise     # re-raise the AssertionError: check_loop_count never 1
        #
        for i1 in range(10):
            def f1(m):
                while m > 0:
                    mydriver.can_enter_jit(m=m)
                    mydriver.jit_merge_point(m=m)
                    m -= 1
            self.meta_interp(f1, [i1])
            try:
                self.check_jitcell_token_count(1)
                break
            except AssertionError:
                print "f1: no loop generated for i1==%d" % i1
        else:
            raise     # re-raise the AssertionError: check_loop_count never 1
        #
        assert i1 - 1 == i2

    def test_no_loop_at_all(self):
        mydriver = JitDriver(greens=[], reds=['m'])
        def f2(m):
            mydriver.jit_merge_point(m=m)
            return m - 1
        def f1(m):
            while m > 0:
                m = f2(m)
        self.meta_interp(f1, [8])
        # it should generate one "loop" only, which ends in a FINISH
        # corresponding to the return from f2.
        self.check_trace_count(1)
        self.check_resops(jump=0)

    def test_simple_loop(self):
        mydriver = JitDriver(greens=[], reds=['m'])
        def f1(m):
            while m > 0:
                mydriver.jit_merge_point(m=m)
                m = m - 1
        self.meta_interp(f1, [8])
        self.check_trace_count(1)
        self.check_resops({'jump': 1, 'guard_true': 2, 'int_gt': 2,
                           'int_sub': 2})

    def test_void_red_variable(self):
        mydriver = JitDriver(greens=[], reds=['m'])
        def f1(m):
            a = None
            while m > 0:
                mydriver.jit_merge_point(m=m)
                m = m - 1
                if m == 10:
                    pass   # other case
        self.meta_interp(f1, [18])

    def test_bug_constant_int(self):
        py.test.skip("crashes because a is a constant")
        from pypy.rpython.lltypesystem import lltype, rffi
        mydriver = JitDriver(greens=['a'], reds=['m'])
        def f1(m, a):
            while m > 0:
                mydriver.jit_merge_point(a=a, m=m)
                m = m - 1
        def entry(m):
            f1(m, 42)
        self.meta_interp(entry, [18])

    def test_bug_constant_instance(self):
        py.test.skip("crashes because a is a constant")
        from pypy.rpython.lltypesystem import lltype, rffi
        mydriver = JitDriver(greens=['a'], reds=['m'])
        class A(object):
            pass
        a1 = A()
        def f1(m, a):
            while m > 0:
                mydriver.jit_merge_point(a=a, m=m)
                m = m - 1
        def entry(m):
            f1(m, a1)
        self.meta_interp(entry, [18])

    def test_bug_constant_rawptrs(self):
        py.test.skip("crashes because a is a constant")
        from pypy.rpython.lltypesystem import lltype, rffi
        mydriver = JitDriver(greens=['a'], reds=['m'])
        def f1(m):
            a = lltype.nullptr(rffi.VOIDP.TO)
            while m > 0:
                mydriver.jit_merge_point(a=a, m=m)
                m = m - 1
        self.meta_interp(f1, [18])

    def test_bug_rawptrs(self):
        from pypy.rpython.lltypesystem import lltype, rffi
        mydriver = JitDriver(greens=['a'], reds=['m'])
        def f1(m):
            a = lltype.malloc(rffi.VOIDP.TO, 5, flavor='raw')
            while m > 0:
                mydriver.jit_merge_point(a=a, m=m)
                m = m - 1
                if m == 10:
                    pass
            lltype.free(a, flavor='raw')
        self.meta_interp(f1, [18])


    def test_loop_automatic_reds(self):
        myjitdriver = JitDriver(greens = ['m'], reds = 'auto')
        def f(n, m):
            res = 0
            # try to have lots of red vars, so that if there is an error in
            # the ordering of reds, there are low chances that the test passes
            # by chance
            a = b = c = d = n
            while n > 0:
                myjitdriver.jit_merge_point(m=m)
                n -= 1
                a += 1 # dummy unused red
                b += 2 # dummy unused red
                c += 3 # dummy unused red
                d += 4 # dummy unused red
                res += m*2
            return res
        expected = f(21, 5)
        res = self.meta_interp(f, [21, 5])
        assert res == expected
        self.check_resops(int_sub=2, int_mul=0, int_add=10)

    def test_loop_automatic_reds_with_floats_and_refs(self):
        myjitdriver = JitDriver(greens = ['m'], reds = 'auto')
        class MyObj(object):
            def __init__(self, val):
                self.val = val
        def f(n, m):
            res = 0
            # try to have lots of red vars, so that if there is an error in
            # the ordering of reds, there are low chances that the test passes
            # by chance
            i1 = i2 = i3 = i4 = n
            f1 = f2 = f3 = f4 = float(n)
            r1 = r2 = r3 = r4 = MyObj(n)
            while n > 0:
                myjitdriver.jit_merge_point(m=m)
                n -= 1
                i1 += 1 # dummy unused red
                i2 += 2 # dummy unused red
                i3 += 3 # dummy unused red
                i4 += 4 # dummy unused red
                f1 += 1 # dummy unused red
                f2 += 2 # dummy unused red
                f3 += 3 # dummy unused red
                f4 += 4 # dummy unused red
                r1.val += 1 # dummy unused red
                r2.val += 2 # dummy unused red
                r3.val += 3 # dummy unused red
                r4.val += 4 # dummy unused red
                res += m*2
            return res
        expected = f(21, 5)
        res = self.meta_interp(f, [21, 5])
        assert res == expected
        self.check_resops(int_sub=2, int_mul=0, int_add=18, float_add=8)

    def test_loop_automatic_reds_livevars_before_jit_merge_point(self):
        myjitdriver = JitDriver(greens = ['m'], reds = 'auto')
        def f(n, m):
            res = 0
            while n > 0:
                n -= 1
                myjitdriver.jit_merge_point(m=m)
                res += m*2
            return res
        expected = f(21, 5)
        res = self.meta_interp(f, [21, 5])
        assert res == expected
        self.check_resops(int_sub=2, int_mul=0, int_add=2)

    def test_inline_jit_merge_point(self):
        # test that the machinery to inline jit_merge_points in callers
        # works. The final user does not need to mess manually with the
        # _inline_jit_merge_point_ attribute and similar, it is all nicely
        # handled by @JitDriver.inline() (see next tests)
        myjitdriver = JitDriver(greens = ['a'], reds = 'auto')

        def jit_merge_point(a, b):
            myjitdriver.jit_merge_point(a=a)

        def add(a, b):
            jit_merge_point(a, b)
            return a+b
        add._inline_jit_merge_point_ = jit_merge_point
        myjitdriver.inline_jit_merge_point = True

        def calc(n):
            res = 0
            while res < 1000:
                res = add(n, res)
            return res

        def f():
            return calc(1) + calc(3)

        res = self.meta_interp(f, [])
        assert res == 1000 + 1002
        self.check_resops(int_add=4)

    def test_jitdriver_inline(self):
        myjitdriver = JitDriver(greens = [], reds = 'auto')
        class MyRange(object):
            def __init__(self, n):
                self.cur = 0
                self.n = n

            def __iter__(self):
                return self

            def jit_merge_point(self):
                myjitdriver.jit_merge_point()

            @myjitdriver.inline(jit_merge_point)
            def next(self):
                if self.cur == self.n:
                    raise StopIteration
                self.cur += 1
                return self.cur

        def f(n):
            res = 0
            for i in MyRange(n):
                res += i
            return res

        expected = f(21)
        res = self.meta_interp(f, [21])
        assert res == expected
        self.check_resops(int_eq=2, int_add=4)
        self.check_trace_count(1)

    def test_jitdriver_inline_twice(self):
        myjitdriver = JitDriver(greens = [], reds = 'auto')

        def jit_merge_point(a, b):
            myjitdriver.jit_merge_point()

        @myjitdriver.inline(jit_merge_point)
        def add(a, b):
            return a+b

        def one(n):
            res = 0
            while res < 1000:
                res = add(n, res)
            return res

        def two(n):
            res = 0
            while res < 2000:
                res = add(n, res)
            return res

        def f(n):
            return one(n) + two(n)

        res = self.meta_interp(f, [1])
        assert res == 3000
        self.check_resops(int_add=4)
        self.check_trace_count(2)


class TestLLWarmspot(WarmspotTests, LLJitMixin):
    CPUClass = runner.LLtypeCPU
    type_system = 'lltype'

class TestOOWarmspot(WarmspotTests, OOJitMixin):
    ##CPUClass = runner.OOtypeCPU
    type_system = 'ootype'

class TestWarmspotDirect(object):
    def setup_class(cls):
        from pypy.jit.metainterp.typesystem import llhelper
        from pypy.jit.codewriter.support import annotate
        from pypy.jit.metainterp.warmspot import WarmRunnerDesc
        from pypy.rpython.lltypesystem.rclass import OBJECT, OBJECT_VTABLE
        from pypy.rpython.lltypesystem import lltype, llmemory
        exc_vtable = lltype.malloc(OBJECT_VTABLE, immortal=True)
        cls.exc_vtable = exc_vtable

        class FakeFailDescr(object):
            def __init__(self, no):
                self.no = no
            def handle_fail(self, metainterp_sd, jitdrivers_sd):
                no = self.no
                if no == 0:
                    raise metainterp_sd.warmrunnerdesc.DoneWithThisFrameInt(3)
                if no == 1:
                    raise metainterp_sd.warmrunnerdesc.ContinueRunningNormally(
                        [0], [], [], [1], [], [])
                if no == 3:
                    exc = lltype.malloc(OBJECT)
                    exc.typeptr = exc_vtable
                    raise metainterp_sd.warmrunnerdesc.ExitFrameWithExceptionRef(
                        metainterp_sd.cpu,
                        lltype.cast_opaque_ptr(llmemory.GCREF, exc))
                assert 0

        class FakeDescr:
            def as_vtable_size_descr(self):
                return self

        class FakeCPU(object):
            supports_floats = False
            supports_longlong = False
            supports_singlefloats = False
            ts = llhelper
            translate_support_code = False
            stats = "stats"

            def get_fail_descr_number(self, d):
                return -1

            def __init__(self, *args, **kwds):
                pass

            def nodescr(self, *args, **kwds):
                return FakeDescr()
            fielddescrof = nodescr
            calldescrof  = nodescr
            sizeof       = nodescr

            def get_fail_descr_from_number(self, no):
                return FakeFailDescr(no)

            def make_execute_token(self, *ARGS):
                return "not callable"

        driver = JitDriver(reds = ['red'], greens = ['green'])

        def f(green):
            red = 0
            while red < 10:
                driver.can_enter_jit(red=red, green=green)
                driver.jit_merge_point(red=red, green=green)
                red += 1
            return red

        rtyper = annotate(f, [0])
        FakeCPU.rtyper = rtyper
        translator = rtyper.annotator.translator
        translator.config.translation.gc = 'hybrid'
        cls.desc = WarmRunnerDesc(translator, CPUClass=FakeCPU)

    def test_call_helper(self):
        from pypy.rpython.llinterp import LLException

        [jd] = self.desc.jitdrivers_sd
        assert jd._assembler_call_helper(0, 0) == 3
        assert jd._assembler_call_helper(1, 0) == 10
        try:
            jd._assembler_call_helper(3, 0)
        except LLException, lle:
            assert lle[0] == self.exc_vtable
        else:
            py.test.fail("DID NOT RAISE")