Add a vector shuffle fuzzer.
[oota-llvm.git] / utils / shuffle_fuzz.py
1 #!/usr/bin/env python
2
3 """A shuffle vector fuzz tester.
4
5 This is a python program to fuzz test the LLVM shufflevector instruction. It
6 generates a function with a random sequnece of shufflevectors, maintaining the
7 element mapping accumulated across the function. It then generates a main
8 function which calls it with a different value in each element and checks that
9 the result matches the expected mapping.
10
11 Take the output IR printed to stdout, compile it to an executable using whatever
12 set of transforms you want to test, and run the program. If it crashes, it found
13 a bug.
14 """
15
16 import argparse
17 import itertools
18 import random
19 import sys
20
21 def main():
22   parser = argparse.ArgumentParser(description=__doc__)
23   parser.add_argument('seed',
24                       help='A string used to seed the RNG')
25   parser.add_argument('-v', '--verbose', action='store_true',
26                       help='Show verbose output')
27   parser.add_argument('--fixed-num-shuffles', type=int,
28                       help='Specify a fixed number of shuffles to test')
29   parser.add_argument('--triple',
30                       help='Specify a triple string to include in the IR')
31   args = parser.parse_args()
32
33   random.seed(args.seed)
34
35   width = random.choice([2, 4, 8, 16, 32, 64])
36   element_type = random.choice(['i8', 'i16', 'i32', 'i64', 'f32', 'f64'])
37
38   # FIXME: Support blends.
39   shuffle_indices = [-1] + range(width)
40
41   if args.fixed_num_shuffles is not None:
42     num_shuffles = args.fixed_num_shuffles
43   else:
44     num_shuffles = random.randint(0, 16)
45
46   shuffles = [[random.choice(shuffle_indices)
47                for _ in itertools.repeat(None, width)]
48               for _ in itertools.repeat(None, num_shuffles)]
49
50   if args.verbose:
51     # Print out the shuffle sequence in a compact form.
52     print >>sys.stderr, 'Testing shuffle sequence:'
53     for s in shuffles:
54       print >>sys.stderr, '  v%d%s: %s' % (width, element_type, s)
55     print >>sys.stderr, ''
56
57   # Compute a round-trip of the shuffle.
58   result = range(1, width + 1)
59   for s in shuffles:
60     result = [result[i] if i != -1 else -1 for i in s]
61
62   if args.verbose:
63     print >>sys.stderr, 'Which transforms:'
64     print >>sys.stderr, '  from: %s' % (range(1, width + 1),)
65     print >>sys.stderr, '  into: %s' % (result,)
66     print >>sys.stderr, ''
67
68   # The IR uses silly names for floating point types. We also need a same-size
69   # integer type.
70   integral_element_type = element_type
71   if element_type == 'f32':
72     integral_element_type = 'i32'
73     element_type = 'float'
74   elif element_type == 'f64':
75     integral_element_type = 'i64'
76     element_type = 'double'
77
78   # Now we need to generate IR for the shuffle function.
79   subst = {'N': width, 'T': element_type, 'IT': integral_element_type}
80   print """
81 define internal <%(N)d x %(T)s> @test(<%(N)d x %(T)s> %%v) noinline nounwind {
82 entry:""" % subst
83
84   for i, s in enumerate(shuffles):
85     print """
86   %%s%(i)d = shufflevector <%(N)d x %(T)s> %(I)s, <%(N)d x %(T)s> undef, <%(N)d x i32> <%(S)s>
87 """.strip() % dict(subst,
88                 i=i,
89                 I=('%%s%d' % (i - 1)) if i != 0 else '%v',
90                 S=', '.join(['i32 %s' % (str(si) if si != -1 else 'undef',)
91                              for si in s]))
92
93   print """
94   ret <%(N)d x %(T)s> %%s%(i)d
95 }
96 """ % dict(subst, i=len(shuffles) - 1)
97
98   # Generate some string constants that we can use to report errors.
99   for i, r in enumerate(result):
100     if r != -1:
101       s = ('FAIL(%(seed)s): lane %(lane)d, expected %(result)d, found %%d\\0A' %
102            {'seed': args.seed, 'lane': i, 'result': r})
103       s += ''.join(['\\00' for _ in itertools.repeat(None, 64 - len(s) + 2)])
104       print """
105 @error.%(i)d = private unnamed_addr global [64 x i8] c"%(s)s"
106 """.strip() % {'i': i, 's': s}
107
108   # Finally, generate a main function which will trap if any lanes are mapped
109   # incorrectly (in an observable way).
110   print """
111 define i32 @main() optnone noinline {
112 entry:
113   ; Create a scratch space to print error messages.
114   %%str = alloca [64 x i8]
115   %%str.ptr = getelementptr inbounds [64 x i8]* %%str, i32 0, i32 0
116
117   ; Build the input vector and call the test function.
118   %%input = bitcast <%(N)d x %(IT)s> <%(input)s> to <%(N)d x %(T)s>
119   %%v = call <%(N)d x %(T)s> @test(<%(N)d x %(T)s> %%input)
120   ; We need to cast this back to an integer type vector to easily check the
121   ; result.
122   %%v.cast = bitcast <%(N)d x %(T)s> %%v to <%(N)d x %(IT)s>
123   br label %%test.0
124 """ % dict(subst,
125            input=', '.join(['%(IT)s %(i)s' % dict(subst, i=i)
126                             for i in xrange(1, width + 1)]),
127            result=', '.join(['%(IT)s %(i)s' % dict(subst,
128                                                    i=i if i != -1 else 'undef')
129                              for i in result]))
130
131   # Test that each non-undef result lane contains the expected value.
132   for i, r in enumerate(result):
133     if r == -1:
134       print """
135 test.%(i)d:
136   ; Skip this lane, its value is undef.
137   br label %%test.%(next_i)d
138 """ % dict(subst, i=i, next_i=i + 1)
139     else:
140       print """
141 test.%(i)d:
142   %%v.%(i)d = extractelement <%(N)d x %(IT)s> %%v.cast, i32 %(i)d
143   %%cmp.%(i)d = icmp ne %(IT)s %%v.%(i)d, %(r)d
144   br i1 %%cmp.%(i)d, label %%die.%(i)d, label %%test.%(next_i)d
145
146 die.%(i)d:
147   ; Capture the actual value and print an error message.
148   %%tmp.%(i)d = zext %(IT)s %%v.%(i)d to i2048
149   %%bad.%(i)d = trunc i2048 %%tmp.%(i)d to i32
150   call i32 (i8*, i8*, ...)* @sprintf(i8* %%str.ptr, i8* getelementptr inbounds ([64 x i8]* @error.%(i)d, i32 0, i32 0), i32 %%bad.%(i)d)
151   %%length.%(i)d = call i32 @strlen(i8* %%str.ptr)
152   %%size.%(i)d = add i32 %%length.%(i)d, 1
153   call i32 @write(i32 2, i8* %%str.ptr, i32 %%size.%(i)d)
154   call void @llvm.trap()
155   unreachable
156 """ % dict(subst, i=i, next_i=i + 1, r=r)
157
158   print """
159 test.%d:
160   ret i32 0
161 }
162
163 declare i32 @strlen(i8*)
164 declare i32 @write(i32, i8*, i32)
165 declare i32 @sprintf(i8*, i8*, ...)
166 declare void @llvm.trap() noreturn nounwind
167 """ % (len(result),)
168
169 if __name__ == '__main__':
170   main()