Author pablogsal
Recipients pablogsal
Date 2019-06-14.01:58:30
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1560477510.59.0.491449903314.issue37271@roundup.psfhosted.org>
In-reply-to
Content
The peephole optimizer currently does not optimize the result of its own optimization when its possible. For example, consider the following code:

    if a:
        if b:
            if (c or d):
                foo()
        else:
            bar()
    else:
        baz()

The bytecode for this is:

  2           0 LOAD_GLOBAL              0 (a)
              2 POP_JUMP_IF_FALSE       32

  4           4 LOAD_GLOBAL              1 (b)
              6 POP_JUMP_IF_FALSE       24

  5           8 LOAD_GLOBAL              2 (c)
             10 POP_JUMP_IF_TRUE        16

  6          12 LOAD_GLOBAL              3 (d)
             14 POP_JUMP_IF_FALSE       30

  7     >>   16 LOAD_GLOBAL              4 (foo)
             18 CALL_FUNCTION            0
             20 POP_TOP
             22 JUMP_ABSOLUTE           38

  9     >>   24 LOAD_GLOBAL              5 (bar)
             26 CALL_FUNCTION            0
             28 POP_TOP
        >>   30 JUMP_FORWARD             6 (to 38)

 11     >>   32 LOAD_GLOBAL              6 (baz)
             34 CALL_FUNCTION            0
             36 POP_TOP
        >>   38 LOAD_CONST               0 (None)
             40 RETURN_VALUE

Notice that the 14 POP_JUMP_IF_FALSE 30 jumps to another jump (30 JUMP_FORWARD 6 (to 38)). If we repeat the optimizations until the resulting bytecode does not change more we get:

  2           0 LOAD_GLOBAL              0 (a)
              2 POP_JUMP_IF_FALSE       32

  4           4 LOAD_GLOBAL              1 (b)
              6 POP_JUMP_IF_FALSE       24

  5           8 LOAD_GLOBAL              2 (c)
             10 POP_JUMP_IF_TRUE        16

  6          12 LOAD_GLOBAL              3 (d)

  5          14 POP_JUMP_IF_FALSE       38

  7     >>   16 LOAD_GLOBAL              4 (foo)
             18 CALL_FUNCTION            0
             20 POP_TOP
             22 JUMP_ABSOLUTE           38

  9     >>   24 LOAD_GLOBAL              5 (bar)
             26 CALL_FUNCTION            0
             28 POP_TOP
             30 JUMP_FORWARD             6 (to 38)

 11     >>   32 LOAD_GLOBAL              6 (baz)
             34 CALL_FUNCTION            0
             36 POP_TOP
        >>   38 LOAD_CONST              

Notice that in this example the original instruction now is (14 POP_JUMP_IF_FALSE  38).
History
Date User Action Args
2019-06-14 01:58:30pablogsalsetrecipients: + pablogsal
2019-06-14 01:58:30pablogsalsetmessageid: <1560477510.59.0.491449903314.issue37271@roundup.psfhosted.org>
2019-06-14 01:58:30pablogsallinkissue37271 messages
2019-06-14 01:58:30pablogsalcreate