Home | History | Annotate | Download | only in nir
      1 #! /usr/bin/env python
      2 #
      3 # Copyright (C) 2014 Intel Corporation
      4 #
      5 # Permission is hereby granted, free of charge, to any person obtaining a
      6 # copy of this software and associated documentation files (the "Software"),
      7 # to deal in the Software without restriction, including without limitation
      8 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
      9 # and/or sell copies of the Software, and to permit persons to whom the
     10 # Software is furnished to do so, subject to the following conditions:
     11 #
     12 # The above copyright notice and this permission notice (including the next
     13 # paragraph) shall be included in all copies or substantial portions of the
     14 # Software.
     15 #
     16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
     17 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     18 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
     19 # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
     20 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
     21 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
     22 # IN THE SOFTWARE.
     23 #
     24 # Authors:
     25 #    Jason Ekstrand (jason (at] jlekstrand.net)
     26 
     27 import nir_algebraic
     28 
     29 # Convenience variables
     30 a = 'a'
     31 b = 'b'
     32 c = 'c'
     33 d = 'd'
     34 
     35 # Written in the form (<search>, <replace>) where <search> is an expression
     36 # and <replace> is either an expression or a value.  An expression is
     37 # defined as a tuple of the form ([~]<op>, <src0>, <src1>, <src2>, <src3>)
     38 # where each source is either an expression or a value.  A value can be
     39 # either a numeric constant or a string representing a variable name.
     40 #
     41 # If the opcode in a search expression is prefixed by a '~' character, this
     42 # indicates that the operation is inexact.  Such operations will only get
     43 # applied to SSA values that do not have the exact bit set.  This should be
     44 # used by by any optimizations that are not bit-for-bit exact.  It should not,
     45 # however, be used for backend-requested lowering operations as those need to
     46 # happen regardless of precision.
     47 #
     48 # Variable names are specified as "[#]name[@type][(cond)]" where "#" inicates
     49 # that the given variable will only match constants and the type indicates that
     50 # the given variable will only match values from ALU instructions with the
     51 # given output type, and (cond) specifies an additional condition function
     52 # (see nir_search_helpers.h).
     53 #
     54 # For constants, you have to be careful to make sure that it is the right
     55 # type because python is unaware of the source and destination types of the
     56 # opcodes.
     57 #
     58 # All expression types can have a bit-size specified.  For opcodes, this
     59 # looks like "op@32", for variables it is "a@32" or "a@uint32" to specify a
     60 # type and size, and for literals, you can write "2.0@32".  In the search half
     61 # of the expression this indicates that it should only match that particular
     62 # bit-size.  In the replace half of the expression this indicates that the
     63 # constructed value should have that bit-size.
     64 
     65 optimizations = [
     66 
     67    (('imul', a, '#b@32(is_pos_power_of_two)'), ('ishl', a, ('find_lsb', b))),
     68    (('imul', a, '#b@32(is_neg_power_of_two)'), ('ineg', ('ishl', a, ('find_lsb', ('iabs', b))))),
     69    (('udiv', a, 1), a),
     70    (('idiv', a, 1), a),
     71    (('umod', a, 1), 0),
     72    (('imod', a, 1), 0),
     73    (('udiv', a, '#b@32(is_pos_power_of_two)'), ('ushr', a, ('find_lsb', b))),
     74    (('idiv', a, '#b@32(is_pos_power_of_two)'), ('imul', ('isign', a), ('ushr', ('iabs', a), ('find_lsb', b))), 'options->lower_idiv'),
     75    (('idiv', a, '#b@32(is_neg_power_of_two)'), ('ineg', ('imul', ('isign', a), ('ushr', ('iabs', a), ('find_lsb', ('iabs', b))))), 'options->lower_idiv'),
     76    (('umod', a, '#b(is_pos_power_of_two)'),    ('iand', a, ('isub', b, 1))),
     77 
     78    (('fneg', ('fneg', a)), a),
     79    (('ineg', ('ineg', a)), a),
     80    (('fabs', ('fabs', a)), ('fabs', a)),
     81    (('fabs', ('fneg', a)), ('fabs', a)),
     82    (('fabs', ('u2f', a)), ('u2f', a)),
     83    (('iabs', ('iabs', a)), ('iabs', a)),
     84    (('iabs', ('ineg', a)), ('iabs', a)),
     85    (('~fadd', a, 0.0), a),
     86    (('iadd', a, 0), a),
     87    (('usadd_4x8', a, 0), a),
     88    (('usadd_4x8', a, ~0), ~0),
     89    (('~fadd', ('fmul', a, b), ('fmul', a, c)), ('fmul', a, ('fadd', b, c))),
     90    (('iadd', ('imul', a, b), ('imul', a, c)), ('imul', a, ('iadd', b, c))),
     91    (('~fadd', ('fneg', a), a), 0.0),
     92    (('iadd', ('ineg', a), a), 0),
     93    (('iadd', ('ineg', a), ('iadd', a, b)), b),
     94    (('iadd', a, ('iadd', ('ineg', a), b)), b),
     95    (('~fadd', ('fneg', a), ('fadd', a, b)), b),
     96    (('~fadd', a, ('fadd', ('fneg', a), b)), b),
     97    (('~fmul', a, 0.0), 0.0),
     98    (('imul', a, 0), 0),
     99    (('umul_unorm_4x8', a, 0), 0),
    100    (('umul_unorm_4x8', a, ~0), a),
    101    (('fmul', a, 1.0), a),
    102    (('imul', a, 1), a),
    103    (('fmul', a, -1.0), ('fneg', a)),
    104    (('imul', a, -1), ('ineg', a)),
    105    (('~ffma', 0.0, a, b), b),
    106    (('~ffma', a, 0.0, b), b),
    107    (('~ffma', a, b, 0.0), ('fmul', a, b)),
    108    (('ffma', a, 1.0, b), ('fadd', a, b)),
    109    (('ffma', 1.0, a, b), ('fadd', a, b)),
    110    (('~flrp', a, b, 0.0), a),
    111    (('~flrp', a, b, 1.0), b),
    112    (('~flrp', a, a, b), a),
    113    (('~flrp', 0.0, a, b), ('fmul', a, b)),
    114    (('~flrp', a, b, ('b2f', c)), ('bcsel', c, b, a), 'options->lower_flrp32'),
    115    (('~flrp', a, 0.0, c), ('fadd', ('fmul', ('fneg', a), c), a)),
    116    (('flrp@32', a, b, c), ('fadd', ('fmul', c, ('fsub', b, a)), a), 'options->lower_flrp32'),
    117    (('flrp@64', a, b, c), ('fadd', ('fmul', c, ('fsub', b, a)), a), 'options->lower_flrp64'),
    118    (('ffract', a), ('fsub', a, ('ffloor', a)), 'options->lower_ffract'),
    119    (('~fadd', ('fmul', a, ('fadd', 1.0, ('fneg', ('b2f', c)))), ('fmul', b, ('b2f', c))), ('bcsel', c, b, a), 'options->lower_flrp32'),
    120    (('~fadd@32', ('fmul', a, ('fadd', 1.0, ('fneg',         c ))), ('fmul', b,         c )), ('flrp', a, b, c), '!options->lower_flrp32'),
    121    (('~fadd@64', ('fmul', a, ('fadd', 1.0, ('fneg',         c ))), ('fmul', b,         c )), ('flrp', a, b, c), '!options->lower_flrp64'),
    122    (('~fadd', a, ('fmul', ('b2f', c), ('fadd', b, ('fneg', a)))), ('bcsel', c, b, a), 'options->lower_flrp32'),
    123    (('~fadd@32', a, ('fmul',         c , ('fadd', b, ('fneg', a)))), ('flrp', a, b, c), '!options->lower_flrp32'),
    124    (('~fadd@64', a, ('fmul',         c , ('fadd', b, ('fneg', a)))), ('flrp', a, b, c), '!options->lower_flrp64'),
    125    (('ffma', a, b, c), ('fadd', ('fmul', a, b), c), 'options->lower_ffma'),
    126    (('~fadd', ('fmul', a, b), c), ('ffma', a, b, c), 'options->fuse_ffma'),
    127 
    128    # (a * #b + #c) << #d
    129    # ((a * #b) << #d) + (#c << #d)
    130    # (a * (#b << #d)) + (#c << #d)
    131    (('ishl', ('iadd', ('imul', a, '#b'), '#c'), '#d'),
    132     ('iadd', ('imul', a, ('ishl', b, d)), ('ishl', c, d))),
    133 
    134    # (a * #b) << #c
    135    # a * (#b << #c)
    136    (('ishl', ('imul', a, '#b'), '#c'), ('imul', a, ('ishl', b, c))),
    137 
    138    # Comparison simplifications
    139    (('~inot', ('flt', a, b)), ('fge', a, b)),
    140    (('~inot', ('fge', a, b)), ('flt', a, b)),
    141    (('~inot', ('feq', a, b)), ('fne', a, b)),
    142    (('~inot', ('fne', a, b)), ('feq', a, b)),
    143    (('inot', ('ilt', a, b)), ('ige', a, b)),
    144    (('inot', ('ige', a, b)), ('ilt', a, b)),
    145    (('inot', ('ieq', a, b)), ('ine', a, b)),
    146    (('inot', ('ine', a, b)), ('ieq', a, b)),
    147 
    148    # 0.0 >= b2f(a)
    149    # b2f(a) <= 0.0
    150    # b2f(a) == 0.0 because b2f(a) can only be 0 or 1
    151    # inot(a)
    152    (('fge', 0.0, ('b2f', a)), ('inot', a)),
    153 
    154    (('fge', ('fneg', ('b2f', a)), 0.0), ('inot', a)),
    155 
    156    # 0.0 < fabs(a)
    157    # fabs(a) > 0.0
    158    # fabs(a) != 0.0 because fabs(a) must be >= 0
    159    # a != 0.0
    160    (('flt', 0.0, ('fabs', a)), ('fne', a, 0.0)),
    161 
    162    (('fge', ('fneg', ('fabs', a)), 0.0), ('feq', a, 0.0)),
    163    (('bcsel', ('flt', b, a), b, a), ('fmin', a, b)),
    164    (('bcsel', ('flt', a, b), b, a), ('fmax', a, b)),
    165    (('bcsel', ('inot', a), b, c), ('bcsel', a, c, b)),
    166    (('bcsel', a, ('bcsel', a, b, c), d), ('bcsel', a, b, d)),
    167    (('bcsel', a, True, 'b@bool'), ('ior', a, b)),
    168    (('fmin', a, a), a),
    169    (('fmax', a, a), a),
    170    (('imin', a, a), a),
    171    (('imax', a, a), a),
    172    (('umin', a, a), a),
    173    (('umax', a, a), a),
    174    (('~fmin', ('fmax', a, 0.0), 1.0), ('fsat', a), '!options->lower_fsat'),
    175    (('~fmax', ('fmin', a, 1.0), 0.0), ('fsat', a), '!options->lower_fsat'),
    176    (('fsat', a), ('fmin', ('fmax', a, 0.0), 1.0), 'options->lower_fsat'),
    177    (('fsat', ('fsat', a)), ('fsat', a)),
    178    (('fmin', ('fmax', ('fmin', ('fmax', a, b), c), b), c), ('fmin', ('fmax', a, b), c)),
    179    (('imin', ('imax', ('imin', ('imax', a, b), c), b), c), ('imin', ('imax', a, b), c)),
    180    (('umin', ('umax', ('umin', ('umax', a, b), c), b), c), ('umin', ('umax', a, b), c)),
    181    (('fmax', ('fsat', a), '#b@32(is_zero_to_one)'), ('fsat', ('fmax', a, b))),
    182    (('fmin', ('fsat', a), '#b@32(is_zero_to_one)'), ('fsat', ('fmin', a, b))),
    183    (('extract_u8', ('imin', ('imax', a, 0), 0xff), 0), ('imin', ('imax', a, 0), 0xff)),
    184    (('~ior', ('flt', a, b), ('flt', a, c)), ('flt', a, ('fmax', b, c))),
    185    (('~ior', ('flt', a, c), ('flt', b, c)), ('flt', ('fmin', a, b), c)),
    186    (('~ior', ('fge', a, b), ('fge', a, c)), ('fge', a, ('fmin', b, c))),
    187    (('~ior', ('fge', a, c), ('fge', b, c)), ('fge', ('fmax', a, b), c)),
    188    (('fabs', ('slt', a, b)), ('slt', a, b)),
    189    (('fabs', ('sge', a, b)), ('sge', a, b)),
    190    (('fabs', ('seq', a, b)), ('seq', a, b)),
    191    (('fabs', ('sne', a, b)), ('sne', a, b)),
    192    (('slt', a, b), ('b2f', ('flt', a, b)), 'options->lower_scmp'),
    193    (('sge', a, b), ('b2f', ('fge', a, b)), 'options->lower_scmp'),
    194    (('seq', a, b), ('b2f', ('feq', a, b)), 'options->lower_scmp'),
    195    (('sne', a, b), ('b2f', ('fne', a, b)), 'options->lower_scmp'),
    196    (('fne', ('fneg', a), a), ('fne', a, 0.0)),
    197    (('feq', ('fneg', a), a), ('feq', a, 0.0)),
    198    # Emulating booleans
    199    (('imul', ('b2i', a), ('b2i', b)), ('b2i', ('iand', a, b))),
    200    (('fmul', ('b2f', a), ('b2f', b)), ('b2f', ('iand', a, b))),
    201    (('fsat', ('fadd', ('b2f', a), ('b2f', b))), ('b2f', ('ior', a, b))),
    202    (('iand', 'a@bool', 1.0), ('b2f', a)),
    203    # True/False are ~0 and 0 in NIR.  b2i of True is 1, and -1 is ~0 (True).
    204    (('ineg', ('b2i', a)), a),
    205    (('flt', ('fneg', ('b2f', a)), 0), a), # Generated by TGSI KILL_IF.
    206    (('flt', ('fsub', 0.0, ('b2f', a)), 0), a), # Generated by TGSI KILL_IF.
    207    # Comparison with the same args.  Note that these are not done for
    208    # the float versions because NaN always returns false on float
    209    # inequalities.
    210    (('ilt', a, a), False),
    211    (('ige', a, a), True),
    212    (('ieq', a, a), True),
    213    (('ine', a, a), False),
    214    (('ult', a, a), False),
    215    (('uge', a, a), True),
    216    # Logical and bit operations
    217    (('fand', a, 0.0), 0.0),
    218    (('iand', a, a), a),
    219    (('iand', a, ~0), a),
    220    (('iand', a, 0), 0),
    221    (('ior', a, a), a),
    222    (('ior', a, 0), a),
    223    (('ior', a, True), True),
    224    (('fxor', a, a), 0.0),
    225    (('ixor', a, a), 0),
    226    (('ixor', a, 0), a),
    227    (('inot', ('inot', a)), a),
    228    # DeMorgan's Laws
    229    (('iand', ('inot', a), ('inot', b)), ('inot', ('ior',  a, b))),
    230    (('ior',  ('inot', a), ('inot', b)), ('inot', ('iand', a, b))),
    231    # Shift optimizations
    232    (('ishl', 0, a), 0),
    233    (('ishl', a, 0), a),
    234    (('ishr', 0, a), 0),
    235    (('ishr', a, 0), a),
    236    (('ushr', 0, a), 0),
    237    (('ushr', a, 0), a),
    238    (('iand', 0xff, ('ushr', a, 24)), ('ushr', a, 24)),
    239    (('iand', 0xffff, ('ushr', a, 16)), ('ushr', a, 16)),
    240    # Exponential/logarithmic identities
    241    (('~fexp2', ('flog2', a)), a), # 2^lg2(a) = a
    242    (('~flog2', ('fexp2', a)), a), # lg2(2^a) = a
    243    (('fpow', a, b), ('fexp2', ('fmul', ('flog2', a), b)), 'options->lower_fpow'), # a^b = 2^(lg2(a)*b)
    244    (('~fexp2', ('fmul', ('flog2', a), b)), ('fpow', a, b), '!options->lower_fpow'), # 2^(lg2(a)*b) = a^b
    245    (('~fexp2', ('fadd', ('fmul', ('flog2', a), b), ('fmul', ('flog2', c), d))),
    246     ('~fmul', ('fpow', a, b), ('fpow', c, d)), '!options->lower_fpow'), # 2^(lg2(a) * b + lg2(c) + d) = a^b * c^d
    247    (('~fpow', a, 1.0), a),
    248    (('~fpow', a, 2.0), ('fmul', a, a)),
    249    (('~fpow', a, 4.0), ('fmul', ('fmul', a, a), ('fmul', a, a))),
    250    (('~fpow', 2.0, a), ('fexp2', a)),
    251    (('~fpow', ('fpow', a, 2.2), 0.454545), a),
    252    (('~fpow', ('fabs', ('fpow', a, 2.2)), 0.454545), ('fabs', a)),
    253    (('~fsqrt', ('fexp2', a)), ('fexp2', ('fmul', 0.5, a))),
    254    (('~frcp', ('fexp2', a)), ('fexp2', ('fneg', a))),
    255    (('~frsq', ('fexp2', a)), ('fexp2', ('fmul', -0.5, a))),
    256    (('~flog2', ('fsqrt', a)), ('fmul', 0.5, ('flog2', a))),
    257    (('~flog2', ('frcp', a)), ('fneg', ('flog2', a))),
    258    (('~flog2', ('frsq', a)), ('fmul', -0.5, ('flog2', a))),
    259    (('~flog2', ('fpow', a, b)), ('fmul', b, ('flog2', a))),
    260    (('~fmul', ('fexp2', a), ('fexp2', b)), ('fexp2', ('fadd', a, b))),
    261    # Division and reciprocal
    262    (('~fdiv', 1.0, a), ('frcp', a)),
    263    (('fdiv', a, b), ('fmul', a, ('frcp', b)), 'options->lower_fdiv'),
    264    (('~frcp', ('frcp', a)), a),
    265    (('~frcp', ('fsqrt', a)), ('frsq', a)),
    266    (('fsqrt', a), ('frcp', ('frsq', a)), 'options->lower_fsqrt'),
    267    (('~frcp', ('frsq', a)), ('fsqrt', a), '!options->lower_fsqrt'),
    268    # Boolean simplifications
    269    (('ieq', 'a@bool', True), a),
    270    (('ine(is_not_used_by_if)', 'a@bool', True), ('inot', a)),
    271    (('ine', 'a@bool', False), a),
    272    (('ieq(is_not_used_by_if)', 'a@bool', False), ('inot', 'a')),
    273    (('bcsel', a, True, False), a),
    274    (('bcsel', a, False, True), ('inot', a)),
    275    (('bcsel@32', a, 1.0, 0.0), ('b2f', a)),
    276    (('bcsel@32', a, 0.0, 1.0), ('b2f', ('inot', a))),
    277    (('bcsel@32', a, -1.0, -0.0), ('fneg', ('b2f', a))),
    278    (('bcsel@32', a, -0.0, -1.0), ('fneg', ('b2f', ('inot', a)))),
    279    (('bcsel', True, b, c), b),
    280    (('bcsel', False, b, c), c),
    281    # The result of this should be hit by constant propagation and, in the
    282    # next round of opt_algebraic, get picked up by one of the above two.
    283    (('bcsel', '#a', b, c), ('bcsel', ('ine', 'a', 0), b, c)),
    284 
    285    (('bcsel', a, b, b), b),
    286    (('fcsel', a, b, b), b),
    287 
    288    # Conversions
    289    (('i2b', ('b2i', a)), a),
    290    (('f2i', ('ftrunc', a)), ('f2i', a)),
    291    (('f2u', ('ftrunc', a)), ('f2u', a)),
    292    (('i2b', ('ineg', a)), ('i2b', a)),
    293    (('i2b', ('iabs', a)), ('i2b', a)),
    294    (('fabs', ('b2f', a)), ('b2f', a)),
    295    (('iabs', ('b2i', a)), ('b2i', a)),
    296 
    297    # Byte extraction
    298    (('ushr', a, 24), ('extract_u8', a, 3), '!options->lower_extract_byte'),
    299    (('iand', 0xff, ('ushr', a, 16)), ('extract_u8', a, 2), '!options->lower_extract_byte'),
    300    (('iand', 0xff, ('ushr', a,  8)), ('extract_u8', a, 1), '!options->lower_extract_byte'),
    301    (('iand', 0xff, a), ('extract_u8', a, 0), '!options->lower_extract_byte'),
    302 
    303     # Word extraction
    304    (('ushr', a, 16), ('extract_u16', a, 1), '!options->lower_extract_word'),
    305    (('iand', 0xffff, a), ('extract_u16', a, 0), '!options->lower_extract_word'),
    306 
    307    # Subtracts
    308    (('~fsub', a, ('fsub', 0.0, b)), ('fadd', a, b)),
    309    (('isub', a, ('isub', 0, b)), ('iadd', a, b)),
    310    (('ussub_4x8', a, 0), a),
    311    (('ussub_4x8', a, ~0), 0),
    312    (('fsub', a, b), ('fadd', a, ('fneg', b)), 'options->lower_sub'),
    313    (('isub', a, b), ('iadd', a, ('ineg', b)), 'options->lower_sub'),
    314    (('fneg', a), ('fsub', 0.0, a), 'options->lower_negate'),
    315    (('ineg', a), ('isub', 0, a), 'options->lower_negate'),
    316    (('~fadd', a, ('fsub', 0.0, b)), ('fsub', a, b)),
    317    (('iadd', a, ('isub', 0, b)), ('isub', a, b)),
    318    (('fabs', ('fsub', 0.0, a)), ('fabs', a)),
    319    (('iabs', ('isub', 0, a)), ('iabs', a)),
    320 
    321    # Propagate negation up multiplication chains
    322    (('fmul', ('fneg', a), b), ('fneg', ('fmul', a, b))),
    323    (('imul', ('ineg', a), b), ('ineg', ('imul', a, b))),
    324 
    325    # Reassociate constants in add/mul chains so they can be folded together.
    326    # For now, we only handle cases where the constants are separated by
    327    # a single non-constant.  We could do better eventually.
    328    (('~fmul', '#a', ('fmul', b, '#c')), ('fmul', ('fmul', a, c), b)),
    329    (('imul', '#a', ('imul', b, '#c')), ('imul', ('imul', a, c), b)),
    330    (('~fadd', '#a', ('fadd', b, '#c')), ('fadd', ('fadd', a, c), b)),
    331    (('iadd', '#a', ('iadd', b, '#c')), ('iadd', ('iadd', a, c), b)),
    332 
    333    # Misc. lowering
    334    (('fmod@32', a, b), ('fsub', a, ('fmul', b, ('ffloor', ('fdiv', a, b)))), 'options->lower_fmod32'),
    335    (('fmod@64', a, b), ('fsub', a, ('fmul', b, ('ffloor', ('fdiv', a, b)))), 'options->lower_fmod64'),
    336    (('frem', a, b), ('fsub', a, ('fmul', b, ('ftrunc', ('fdiv', a, b)))), 'options->lower_fmod32'),
    337    (('uadd_carry@32', a, b), ('b2i', ('ult', ('iadd', a, b), a)), 'options->lower_uadd_carry'),
    338    (('usub_borrow@32', a, b), ('b2i', ('ult', a, b)), 'options->lower_usub_borrow'),
    339 
    340    (('bitfield_insert', 'base', 'insert', 'offset', 'bits'),
    341     ('bcsel', ('ilt', 31, 'bits'), 'insert',
    342               ('bfi', ('bfm', 'bits', 'offset'), 'insert', 'base')),
    343     'options->lower_bitfield_insert'),
    344 
    345    (('ibitfield_extract', 'value', 'offset', 'bits'),
    346     ('bcsel', ('ilt', 31, 'bits'), 'value',
    347               ('ibfe', 'value', 'offset', 'bits')),
    348     'options->lower_bitfield_extract'),
    349 
    350    (('ubitfield_extract', 'value', 'offset', 'bits'),
    351     ('bcsel', ('ult', 31, 'bits'), 'value',
    352               ('ubfe', 'value', 'offset', 'bits')),
    353     'options->lower_bitfield_extract'),
    354 
    355    (('extract_i8', a, b),
    356     ('ishr', ('ishl', a, ('imul', ('isub', 3, b), 8)), 24),
    357     'options->lower_extract_byte'),
    358 
    359    (('extract_u8', a, b),
    360     ('iand', ('ushr', a, ('imul', b, 8)), 0xff),
    361     'options->lower_extract_byte'),
    362 
    363    (('extract_i16', a, b),
    364     ('ishr', ('ishl', a, ('imul', ('isub', 1, b), 16)), 16),
    365     'options->lower_extract_word'),
    366 
    367    (('extract_u16', a, b),
    368     ('iand', ('ushr', a, ('imul', b, 16)), 0xffff),
    369     'options->lower_extract_word'),
    370 
    371     (('pack_unorm_2x16', 'v'),
    372      ('pack_uvec2_to_uint',
    373         ('f2u', ('fround_even', ('fmul', ('fsat', 'v'), 65535.0)))),
    374      'options->lower_pack_unorm_2x16'),
    375 
    376     (('pack_unorm_4x8', 'v'),
    377      ('pack_uvec4_to_uint',
    378         ('f2u', ('fround_even', ('fmul', ('fsat', 'v'), 255.0)))),
    379      'options->lower_pack_unorm_4x8'),
    380 
    381     (('pack_snorm_2x16', 'v'),
    382      ('pack_uvec2_to_uint',
    383         ('f2i', ('fround_even', ('fmul', ('fmin', 1.0, ('fmax', -1.0, 'v')), 32767.0)))),
    384      'options->lower_pack_snorm_2x16'),
    385 
    386     (('pack_snorm_4x8', 'v'),
    387      ('pack_uvec4_to_uint',
    388         ('f2i', ('fround_even', ('fmul', ('fmin', 1.0, ('fmax', -1.0, 'v')), 127.0)))),
    389      'options->lower_pack_snorm_4x8'),
    390 
    391     (('unpack_unorm_2x16', 'v'),
    392      ('fdiv', ('u2f', ('vec2', ('extract_u16', 'v', 0),
    393                                ('extract_u16', 'v', 1))),
    394               65535.0),
    395      'options->lower_unpack_unorm_2x16'),
    396 
    397     (('unpack_unorm_4x8', 'v'),
    398      ('fdiv', ('u2f', ('vec4', ('extract_u8', 'v', 0),
    399                                ('extract_u8', 'v', 1),
    400                                ('extract_u8', 'v', 2),
    401                                ('extract_u8', 'v', 3))),
    402               255.0),
    403      'options->lower_unpack_unorm_4x8'),
    404 
    405     (('unpack_snorm_2x16', 'v'),
    406      ('fmin', 1.0, ('fmax', -1.0, ('fdiv', ('i2f', ('vec2', ('extract_i16', 'v', 0),
    407                                                             ('extract_i16', 'v', 1))),
    408                                            32767.0))),
    409      'options->lower_unpack_snorm_2x16'),
    410 
    411     (('unpack_snorm_4x8', 'v'),
    412      ('fmin', 1.0, ('fmax', -1.0, ('fdiv', ('i2f', ('vec4', ('extract_i8', 'v', 0),
    413                                                             ('extract_i8', 'v', 1),
    414                                                             ('extract_i8', 'v', 2),
    415                                                             ('extract_i8', 'v', 3))),
    416                                            127.0))),
    417      'options->lower_unpack_snorm_4x8'),
    418 ]
    419 
    420 def fexp2i(exp, bits):
    421    # We assume that exp is already in the right range.
    422    if bits == 32:
    423       return ('ishl', ('iadd', exp, 127), 23)
    424    elif bits == 64:
    425       return ('pack_double_2x32_split', 0, ('ishl', ('iadd', exp, 1023), 20))
    426    else:
    427       assert False
    428 
    429 def ldexp(f, exp, bits):
    430    # First, we clamp exp to a reasonable range.  The maximum possible range
    431    # for a normal exponent is [-126, 127] and, throwing in denormals, you get
    432    # a maximum range of [-149, 127].  This means that we can potentially have
    433    # a swing of +-276.  If you start with FLT_MAX, you actually have to do
    434    # ldexp(FLT_MAX, -278) to get it to flush all the way to zero.  The GLSL
    435    # spec, on the other hand, only requires that we handle an exponent value
    436    # in the range [-126, 128].  This implementation is *mostly* correct; it
    437    # handles a range on exp of [-252, 254] which allows you to create any
    438    # value (including denorms if the hardware supports it) and to adjust the
    439    # exponent of any normal value to anything you want.
    440    if bits == 32:
    441       exp = ('imin', ('imax', exp, -252), 254)
    442    elif bits == 64:
    443       exp = ('imin', ('imax', exp, -2044), 2046)
    444    else:
    445       assert False
    446 
    447    # Now we compute two powers of 2, one for exp/2 and one for exp-exp/2.
    448    # (We use ishr which isn't the same for -1, but the -1 case still works
    449    # since we use exp-exp/2 as the second exponent.)  While the spec
    450    # technically defines ldexp as f * 2.0^exp, simply multiplying once doesn't
    451    # work with denormals and doesn't allow for the full swing in exponents
    452    # that you can get with normalized values.  Instead, we create two powers
    453    # of two and multiply by them each in turn.  That way the effective range
    454    # of our exponent is doubled.
    455    pow2_1 = fexp2i(('ishr', exp, 1), bits)
    456    pow2_2 = fexp2i(('isub', exp, ('ishr', exp, 1)), bits)
    457    return ('fmul', ('fmul', f, pow2_1), pow2_2)
    458 
    459 optimizations += [
    460    (('ldexp@32', 'x', 'exp'), ldexp('x', 'exp', 32)),
    461    (('ldexp@64', 'x', 'exp'), ldexp('x', 'exp', 64)),
    462 ]
    463 
    464 # Unreal Engine 4 demo applications open-codes bitfieldReverse()
    465 def bitfield_reverse(u):
    466     step1 = ('ior', ('ishl', u, 16), ('ushr', u, 16))
    467     step2 = ('ior', ('ishl', ('iand', step1, 0x00ff00ff), 8), ('ushr', ('iand', step1, 0xff00ff00), 8))
    468     step3 = ('ior', ('ishl', ('iand', step2, 0x0f0f0f0f), 4), ('ushr', ('iand', step2, 0xf0f0f0f0), 4))
    469     step4 = ('ior', ('ishl', ('iand', step3, 0x33333333), 2), ('ushr', ('iand', step3, 0xcccccccc), 2))
    470     step5 = ('ior', ('ishl', ('iand', step4, 0x55555555), 1), ('ushr', ('iand', step4, 0xaaaaaaaa), 1))
    471 
    472     return step5
    473 
    474 optimizations += [(bitfield_reverse('x@32'), ('bitfield_reverse', 'x'))]
    475 
    476 # For any float comparison operation, "cmp", if you have "a == a && a cmp b"
    477 # then the "a == a" is redundant because it's equivalent to "a is not NaN"
    478 # and, if a is a NaN then the second comparison will fail anyway.
    479 for op in ['flt', 'fge', 'feq']:
    480    optimizations += [
    481       (('iand', ('feq', a, a), (op, a, b)), (op, a, b)),
    482       (('iand', ('feq', a, a), (op, b, a)), (op, b, a)),
    483    ]
    484 
    485 # Add optimizations to handle the case where the result of a ternary is
    486 # compared to a constant.  This way we can take things like
    487 #
    488 # (a ? 0 : 1) > 0
    489 #
    490 # and turn it into
    491 #
    492 # a ? (0 > 0) : (1 > 0)
    493 #
    494 # which constant folding will eat for lunch.  The resulting ternary will
    495 # further get cleaned up by the boolean reductions above and we will be
    496 # left with just the original variable "a".
    497 for op in ['flt', 'fge', 'feq', 'fne',
    498            'ilt', 'ige', 'ieq', 'ine', 'ult', 'uge']:
    499    optimizations += [
    500       ((op, ('bcsel', 'a', '#b', '#c'), '#d'),
    501        ('bcsel', 'a', (op, 'b', 'd'), (op, 'c', 'd'))),
    502       ((op, '#d', ('bcsel', a, '#b', '#c')),
    503        ('bcsel', 'a', (op, 'd', 'b'), (op, 'd', 'c'))),
    504    ]
    505 
    506 # This section contains "late" optimizations that should be run after the
    507 # regular optimizations have finished.  Optimizations should go here if
    508 # they help code generation but do not necessarily produce code that is
    509 # more easily optimizable.
    510 late_optimizations = [
    511    # Most of these optimizations aren't quite safe when you get infinity or
    512    # Nan involved but the first one should be fine.
    513    (('flt', ('fadd', a, b), 0.0), ('flt', a, ('fneg', b))),
    514    (('~fge', ('fadd', a, b), 0.0), ('fge', a, ('fneg', b))),
    515    (('~feq', ('fadd', a, b), 0.0), ('feq', a, ('fneg', b))),
    516    (('~fne', ('fadd', a, b), 0.0), ('fne', a, ('fneg', b))),
    517 
    518    (('fdot2', a, b), ('fdot_replicated2', a, b), 'options->fdot_replicates'),
    519    (('fdot3', a, b), ('fdot_replicated3', a, b), 'options->fdot_replicates'),
    520    (('fdot4', a, b), ('fdot_replicated4', a, b), 'options->fdot_replicates'),
    521    (('fdph', a, b), ('fdph_replicated', a, b), 'options->fdot_replicates'),
    522 
    523    (('b2f(is_used_more_than_once)', ('inot', a)), ('bcsel', a, 0.0, 1.0)),
    524    (('fneg(is_used_more_than_once)', ('b2f', ('inot', a))), ('bcsel', a, -0.0, -1.0)),
    525 
    526    # we do these late so that we don't get in the way of creating ffmas
    527    (('fmin', ('fadd(is_used_once)', '#c', a), ('fadd(is_used_once)', '#c', b)), ('fadd', c, ('fmin', a, b))),
    528    (('fmax', ('fadd(is_used_once)', '#c', a), ('fadd(is_used_once)', '#c', b)), ('fadd', c, ('fmax', a, b))),
    529 ]
    530 
    531 print nir_algebraic.AlgebraicPass("nir_opt_algebraic", optimizations).render()
    532 print nir_algebraic.AlgebraicPass("nir_opt_algebraic_late",
    533                                   late_optimizations).render()
    534