Debian Codegraph @

rpython/jit/metainterp/test/test_zvector.py

raw symbols SCIP
1 import py
2 import sys
3 import pytest
4 import math
5 import functools
6 from hypothesis import given, note, strategies as st, settings
7 from rpython.jit.metainterp.warmspot import ll_meta_interp, get_stats
8 from rpython.jit.metainterp.test.support import LLJitMixin
9 from rpython.jit.codewriter.policy import StopAtXPolicy
10 from rpython.jit.metainterp.resoperation import rop
11 from rpython.jit.metainterp import history
12 from rpython.rlib.jit import JitDriver, hint, set_param
13 from rpython.rlib.objectmodel import compute_hash
14 from rpython.rtyper.lltypesystem import lltype, rffi
15 from rpython.rlib.rarithmetic import r_uint, intmask, r_int
16 from rpython.rlib.rawstorage import (alloc_raw_storage, raw_storage_setitem,
17 free_raw_storage, raw_storage_getitem)
18 from rpython.rlib.objectmodel import (specialize, is_annotation_constant,
19 always_inline)
20 from rpython.jit.backend.detect_cpu import getcpuclass
21 from rpython.jit.tool.oparser import parse
22 from rpython.jit.metainterp.history import (AbstractFailDescr,
23 AbstractDescr,
24 BasicFailDescr, BasicFinalDescr,
25 JitCellToken, TargetToken,
26 ConstInt, ConstPtr,
27 Const, ConstFloat)
28
29 CPU = getcpuclass()
30
31 if sys.maxint == 2**31-1:
32 pytest.skip("32bit platforms are not supported")
33
34 @specialize.argtype(0,1)
35 def malloc(T,n):
36 return lltype.malloc(T, n, flavor='raw', zero=True)
37 def free(mem):
38 lltype.free(mem, flavor='raw')
39
40 def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
41 return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) \
42 or (math.isnan(a) and math.isnan(b)) or \
43 (math.isinf(a) and math.isinf(b) and \
44 (a < 0.0 and b < 0.0) or \
45 (a > 0.0 and b > 0.0))
46
47 class RawStorage(object):
48 def __init__(self):
49 self.arrays = []
50
51 def new(self, values, type, size=None, zero=True):
52 bytecount = rffi.sizeof(type)
53 if not values:
54 array = alloc_raw_storage(size*bytecount, zero=zero)
55 self.arrays.append(array)
56 return array
57 else:
58 size = len(values)*bytecount
59 array = alloc_raw_storage(size, zero=zero)
60 for i,v in enumerate(values):
61 raw_storage_setitem(array, i*bytecount, rffi.cast(type,v))
62 self.arrays.append(array)
63 return array
64
65 def clear(self):
66 while self.arrays:
67 array = self.arrays.pop()
68 free_raw_storage(array)
69
70 @pytest.fixture(scope='function')
71 def rawstorage(request):
72 rs = RawStorage()
73 request.addfinalizer(rs.clear)
74 request.cls.a
75 return rs
76
77 class VectorizeTests(object):
78 enable_opts = 'intbounds:rewrite:virtualize:string:earlyforce:pure:heap:unroll'
79
80 def setup_method(self, method):
81 if not self.supports_vector_ext():
82 py.test.skip("this cpu %s has no implemented vector backend" % CPU)
83
84 # FLOAT UNARY
85
86 @pytest.mark.parametrize('func',
87 [lambda v: abs(v), lambda v: -v],
88 ids=['abs', 'neg'])
89 @given(la=st.lists(st.floats(), min_size=10, max_size=150))
90 def test_vector_float_unary(self, func, la):
91 func = always_inline(func)
92 tp = rffi.DOUBLE
93
94 size = rffi.sizeof(tp)
95 myjitdriver = JitDriver(greens=[], reds='auto', vectorize=True)
96
97 def f(bytecount, va, vc):
98 i = 0
99 while i < bytecount:
100 myjitdriver.jit_merge_point()
101 a = raw_storage_getitem(tp, va, i)
102 c = func(a)
103 raw_storage_setitem(vc, i, rffi.cast(tp, c))
104 i += size
105
106 l = len(la)
107 rawstorage = RawStorage()
108 va = rawstorage.new(la, tp)
109 vc = rawstorage.new(None, tp, size=l)
110 self.meta_interp(f, [l * size, va, vc], vec=True)
111
112 for i in range(l):
113 c = raw_storage_getitem(tp, vc, i * size)
114 r = func(la[i])
115 assert isclose(r, c)
116
117 rawstorage.clear()
118
119 # FLOAT BINARY
120
121 def _vector_simple_float(self, func, type, data):
122 func = always_inline(func)
123
124 size = rffi.sizeof(rffi.DOUBLE)
125 myjitdriver = JitDriver(greens = [], reds = 'auto', vectorize=True)
126 def f(bytecount, va, vb, vc):
127 i = 0
128 while i < bytecount:
129 myjitdriver.jit_merge_point()
130 a = raw_storage_getitem(type,va,i)
131 b = raw_storage_getitem(type,vb,i)
132 c = func(a,b)
133 raw_storage_setitem(vc, i, rffi.cast(type,c))
134 i += size
135
136 la = data.draw(st.lists(st.floats(), min_size=10, max_size=150))
137 l = len(la)
138 lb = data.draw(st.lists(st.floats(), min_size=l, max_size=l))
139
140 rawstorage = RawStorage()
141 va = rawstorage.new(la, type)
142 vb = rawstorage.new(lb, type)
143 vc = rawstorage.new(None, type, size=l)
144 self.meta_interp(f, [l*size, va, vb, vc], vec=True)
145
146 for i in range(l):
147 c = raw_storage_getitem(type,vc,i*size)
148 r = rffi.cast(type, func(la[i], lb[i]))
149 assert isclose(r, c)
150
151 rawstorage.clear()
152
153 def _vec_float_binary(test_func, func, type):
154 return pytest.mark.parametrize('func,type', [
155 (func, type)
156 ])(given(data=st.data())(test_func))
157
158 vec_float_binary = functools.partial(_vec_float_binary, _vector_simple_float)
159
160 test_vec_float_add = \
161 vec_float_binary(lambda a,b: a+b, rffi.DOUBLE)
162 test_vec_float_sub = \
163 vec_float_binary(lambda a,b: a-b, rffi.DOUBLE)
164 test_vec_float_mul = \
165 vec_float_binary(lambda a,b: a*b, rffi.DOUBLE)
166
167 test_vec_float_cmp_eq = \
168 vec_float_binary(lambda a,b: a == b, rffi.DOUBLE)
169 test_vec_float_cmp_ne = \
170 vec_float_binary(lambda a,b: a != b, rffi.DOUBLE)
171
172 def _vector_simple_int(self, func, type, la):
173 oldfunc = func
174 func = always_inline(func)
175
176 size = rffi.sizeof(type)
177 myjitdriver = JitDriver(greens = [], reds = 'auto', vectorize=True)
178 def f(bytecount, va, vb, vc):
179 i = 0
180 while i < bytecount:
181 myjitdriver.jit_merge_point()
182 a = raw_storage_getitem(type,va,i)
183 b = raw_storage_getitem(type,vb,i)
184 c = func(a,b)
185 raw_storage_setitem(vc, i, rffi.cast(type,c))
186 i += size
187
188 l = len(la)
189 lb = list(reversed(la))[:]
190
191 rawstorage = RawStorage()
192 va = rawstorage.new(la, type)
193 vb = rawstorage.new(lb, type)
194 vc = rawstorage.new(None, type, size=l)
195 self.meta_interp(f, [l*size, va, vb, vc], vec=True)
196
197 for i in range(l):
198 c = raw_storage_getitem(type,vc,i*size)
199 assert rffi.cast(type, oldfunc(la[i], lb[i])) == c
200
201 rawstorage.clear()
202
203 def vec_int_arith(test_func, arith_func, type):
204 size = rffi.sizeof(type)
205 bits = size*8
206 assert 0 <= bits <= 64
207 integers = st.integers(min_value=-2**(bits-1), max_value=2**(bits-1)-1)
208 @given(st.lists(integers, min_size=10, max_size=15))
209 @settings(max_examples=20)
210 def tf(self, la):
211 return test_func(self, arith_func, type, la)
212 return tf
213
214 vec_int_arith = functools.partial(vec_int_arith, _vector_simple_int)
215
216 test_vec_simple_int_signed_add = \
217 vec_int_arith(lambda a,b: intmask(a+b), rffi.SIGNED)
218 test_vec_simple_int_int_add = \
219 vec_int_arith(lambda a,b: intmask(r_int(a)+r_int(b)), rffi.INT)
220 test_vec_simple_int_short_add = \
221 vec_int_arith(lambda a,b: intmask(r_int(a)+r_int(b)), rffi.SHORT)
222
223 test_vec_simple_int_signed_sub = \
224 vec_int_arith(lambda a,b: intmask(a-b), rffi.SIGNED)
225 test_vec_simple_int_sub_int = \
226 vec_int_arith(lambda a,b: intmask(r_int(a)-r_int(b)), rffi.INT)
227 test_vec_simple_int_sub_short = \
228 vec_int_arith(lambda a,b: intmask(r_int(a)-r_int(b)), rffi.SHORT)
229
230 test_vec_simple_int_signed_and = \
231 vec_int_arith(lambda a,b: intmask(a)&intmask(b), rffi.SIGNED)
232 test_vec_simple_int_int_and = \
233 vec_int_arith(lambda a,b: intmask(a)&intmask(b), rffi.INT)
234 test_vec_simple_int_short_and = \
235 vec_int_arith(lambda a,b: intmask(a)&intmask(b), rffi.SHORT)
236
237 test_vec_simple_int_or_signed = \
238 vec_int_arith(lambda a,b: intmask(a)|intmask(b), rffi.SIGNED)
239 test_vec_simple_int_or_int = \
240 vec_int_arith(lambda a,b: intmask(a)|intmask(b), rffi.INT)
241 test_vec_simple_int_or_short = \
242 vec_int_arith(lambda a,b: intmask(a)|intmask(b), rffi.SHORT)
243
244 test_vec_simple_int_xor_signed = \
245 vec_int_arith(lambda a,b: intmask(a)^intmask(b), rffi.SIGNED)
246 test_vec_simple_int_xor_int = \
247 vec_int_arith(lambda a,b: intmask(a)^intmask(b), rffi.INT)
248 test_vec_simple_int_xor_short = \
249 vec_int_arith(lambda a,b: intmask(a)^intmask(b), rffi.SHORT)
250
251 test_vec_simple_int_int_cmp_eq = \
252 vec_int_arith(lambda a,b: a == b, rffi.SIGNED)
253 test_vec_simple_int_int_cmp_ne = \
254 vec_int_arith(lambda a,b: a == b, rffi.SIGNED)
255
256 @py.test.mark.parametrize('i',[1,2,3,4,9])
257 def test_vec_register_too_small_vector(self, i):
258 myjitdriver = JitDriver(greens = [],
259 reds = 'auto',
260 vectorize=True)
261 T = lltype.Array(rffi.SHORT, hints={'nolength': True})
262
263 def g(d, va, vb):
264 i = 0
265 while i < d:
266 myjitdriver.jit_merge_point()
267 a = va[i]
268 b = vb[i]
269 ec = intmask(intmask(a) + intmask(b))
270 va[i] = rffi.r_short(ec)
271 i += 1
272
273 def f(d):
274 i = 0
275 va = lltype.malloc(T, d+100, flavor='raw', zero=True)
276 vb = lltype.malloc(T, d+100, flavor='raw', zero=True)
277 for j in range(d+100):
278 va[j] = rffi.r_short(1)
279 vb[j] = rffi.r_short(2)
280
281 g(d+100, va, vb)
282 g(d, va, vb) # this iteration might not fit into the vector register
283
284 res = intmask(va[d])
285 lltype.free(va, flavor='raw')
286 lltype.free(vb, flavor='raw')
287 return res
288 res = self.meta_interp(f, [i], vec=True)
289 assert res == f(i) == 3
290
291 def test_vec_max(self):
292 myjitdriver = JitDriver(greens = [],
293 reds = 'auto',
294 vectorize=True)
295 def fmax(v1, v2):
296 return v1 if v1 >= v2 or math.isnan(v2) else v2
297 T = lltype.Array(rffi.DOUBLE, hints={'nolength': True})
298 def f(d):
299 i = 0
300 va = lltype.malloc(T, d, flavor='raw', zero=True)
301 for j in range(d):
302 va[j] = float(j)
303 va[13] = 128.0
304 m = -128.0
305 while i < d:
306 myjitdriver.jit_merge_point()
307 a = va[i]
308 m = fmax(a, m)
309 i += 1
310 lltype.free(va, flavor='raw')
311 return m
312 res = self.meta_interp(f, [30], vec=True)
313 assert res == f(30) == 128
314
315 @py.test.mark.parametrize('type,func,init,insert,at,count,breaks',
316 # all
317 [(rffi.DOUBLE, lambda x: not bool(x), 1.0, None, -1,32, False),
318 (rffi.DOUBLE, lambda x: x == 0.0, 1.0, None, -1,33, False),
319 (rffi.DOUBLE, lambda x: x == 0.0, 1.0, 0.0, 33,34, True),
320 (rffi.DOUBLE, lambda x: x == 0.0, 1.0, 0.1, 4,34, False),
321 (lltype.Signed, lambda x: not bool(x), 1, None, -1,32, False),
322 (lltype.Signed, lambda x: not bool(x), 1, 0, 14,32, True),
323 (lltype.Signed, lambda x: not bool(x), 1, 0, 15,31, True),
324 (lltype.Signed, lambda x: not bool(x), 1, 0, 4,30, True),
325 (lltype.Signed, lambda x: x == 0, 1, None, -1,33, False),
326 (lltype.Signed, lambda x: x == 0, 1, 0, 33,34, True),
327 # any
328 (rffi.DOUBLE, lambda x: x != 0.0, 0.0, 1.0, 33,35, True),
329 (rffi.DOUBLE, lambda x: x != 0.0, 0.0, 1.0, -1,36, False),
330 (rffi.DOUBLE, lambda x: bool(x), 0.0, 1.0, 33,37, True),
331 (rffi.DOUBLE, lambda x: bool(x), 0.0, 1.0, -1,38, False),
332 (lltype.Signed, lambda x: x != 0, 0, 1, 33,35, True),
333 (lltype.Signed, lambda x: x != 0, 0, 1, -1,36, False),
334 (lltype.Signed, lambda x: bool(x), 0, 1, 33,37, True),
335 (lltype.Signed, lambda x: bool(x), 0, 1, -1,38, False),
336 (rffi.INT, lambda x: intmask(x) != 0, rffi.r_int(0), rffi.r_int(1), 33,35, True),
337 (rffi.INT, lambda x: intmask(x) != 0, rffi.r_int(0), rffi.r_int(1), -1,36, False),
338 (rffi.INT, lambda x: bool(intmask(x)), rffi.r_int(0), rffi.r_int(1), 33,37, True),
339 (rffi.INT, lambda x: bool(intmask(x)), rffi.r_int(0), rffi.r_int(1), -1,38, False),
340 ])
341 def test_bool_reduction(self, type, func, init, insert, at, count, breaks):
342 myjitdriver = JitDriver(greens = [], reds = 'auto', vectorize=True)
343 T = lltype.Array(type, hints={'nolength': True})
344 def f(d):
345 va = lltype.malloc(T, d, flavor='raw', zero=True)
346 for i in range(d): va[i] = init
347 if at != -1:
348 va[at] = insert
349 i = 0 ; nobreak = False
350 while i < d:
351 myjitdriver.jit_merge_point()
352 b = func(va[i])
353 if b:
354 assert b
355 break
356 i += 1
357 else:
358 nobreak = True
359 lltype.free(va, flavor='raw')
360 return not nobreak
361 res = self.meta_interp(f, [count], vec=True)
362 assert res == f(count) == breaks
363
364 def vec_reduce(strat, arith_func, tp):
365 @pytest.mark.parametrize('func, tp', [
366 (arith_func, tp)
367 ])
368 @given(la=st.lists(strat, min_size=11, max_size=150))
369 def _vec_reduce(self, func, tp, la):
370 func = always_inline(func)
371
372 size = rffi.sizeof(tp)
373 myjitdriver = JitDriver(greens=[], reds='auto', vectorize=True)
374
375 def f(accum, bytecount, v):
376 i = 0
377 while i < bytecount:
378 myjitdriver.jit_merge_point()
379 e = raw_storage_getitem(tp, v, i)
380 accum = func(accum, e)
381 i += size
382 return accum
383
384 accum = la[0]
385 la = la[1:]
386 l = len(la)
387 rawstorage = RawStorage()
388 va = rawstorage.new(la, tp)
389 res = self.meta_interp(f, [accum, l * size, va], vec=True)
390
391 assert isclose(rffi.cast(tp, res), f(accum, l * size, va))
392
393 rawstorage.clear()
394 return _vec_reduce
395
396 test_vec_int_sum = vec_reduce(st.integers(min_value=-2**(64-1), max_value=2**(64-1)-1),
397 lambda a,b: lltype.intmask(lltype.intmask(a)+lltype.intmask(b)), lltype.Signed)
398 small_floats = st.floats(min_value=-100, max_value=100, allow_nan=False, allow_infinity=False)
399 test_vec_float_sum = vec_reduce(small_floats, lambda a,b: a+b, rffi.DOUBLE)
400 # PRECISION loss, because the numbers are accumulated (associative, commutative properties must hold)
401 # you can end up a small number and a huge number that is finally multiplied losing precision
402 # test_vec_float_prod = vec_reduce(small_floats, lambda a,b: a*b, rffi.DOUBLE)
403
404
405 def test_constant_expand(self):
406 myjitdriver = JitDriver(greens = [], reds = 'auto', vectorize=True)
407 T = lltype.Array(rffi.DOUBLE, hints={'nolength': True})
408 def f(d):
409 va = lltype.malloc(T, d, flavor='raw', zero=True)
410 i = 0
411 while i < d:
412 myjitdriver.jit_merge_point()
413 va[i] = va[i] + 34.5
414 i += 1
415 val = va[0]
416 lltype.free(va, flavor='raw')
417 return val
418 res = self.meta_interp(f, [60], vec=True)
419 assert res == f(60) == 34.5
420
421 def test_constant_expand_vec_all(self):
422 myjitdriver = JitDriver(greens = [], reds = 'auto')
423 T = lltype.Array(rffi.DOUBLE, hints={'nolength': True})
424 def f(d):
425 va = lltype.malloc(T, d, flavor='raw', zero=True)
426 i = 0
427 while i < d:
428 myjitdriver.jit_merge_point()
429 if not (i < d):
430 raise IndexError
431 va[i] = va[i] + 34.5
432 i += 1
433 val = va[0]
434 lltype.free(va, flavor='raw')
435 return val
436 res = self.meta_interp(f, [60], vec=True, vec_all=True)
437 assert res == f(60) == 34.5
438
439 @py.test.mark.parametrize('type,value', [(rffi.DOUBLE, 58.4547),
440 (lltype.Signed, 2300000), (rffi.INT, 4321),
441 (rffi.SHORT, 9922), (rffi.SIGNEDCHAR, -127)])
442 def test_variable_expand(self, type, value):
443 myjitdriver = JitDriver(greens = [], reds = 'auto', vectorize=True)
444 T = lltype.Array(type, hints={'nolength': True})
445 def f(d,variable):
446 va = lltype.malloc(T, d, flavor='raw', zero=True)
447 i = 0
448 while i < d:
449 myjitdriver.jit_merge_point()
450 va[i] = rffi.cast(type, variable)
451 i += 1
452 val = va[d//2]
453 lltype.free(va, flavor='raw')
454 return val
455 res = self.meta_interp(f, [60,value], vec=True)
456 assert res == f(60,value) == value
457
458 @py.test.mark.parametrize('vec,vec_all',[(False,True),(True,False),(True,True),(False,False)])
459 def test_accum(self, vec, vec_all):
460 myjitdriver = JitDriver(greens = [], reds = 'auto', vectorize=vec)
461 T = lltype.Array(rffi.DOUBLE)
462 def f(d, value):
463 va = lltype.malloc(T, d, flavor='raw', zero=True)
464 for i in range(d):
465 va[i] = value
466 r = 0
467 i = 0
468 k = d + 2
469 # in this case a guard k <= d is inserted which fails right away!
470 while i < d:
471 myjitdriver.jit_merge_point()
472 if not(i < k):
473 k -= 1
474 r += va[i]
475 i += 1
476 lltype.free(va, flavor='raw')
477 return r
478 res = self.meta_interp(f, [60,0.5], vec=vec, vec_all=vec_all)
479 assert res == f(60,0.5) == 60*0.5
480
481
482 @py.test.mark.parametrize('i',[15])
483 def test_array_bounds_check_elimination(self,i):
484 myjitdriver = JitDriver(greens = [],
485 reds = 'auto',
486 vectorize=True)
487 T = lltype.Array(rffi.INT, hints={'nolength': True})
488 def f(d):
489 va = lltype.malloc(T, d, flavor='raw', zero=True)
490 vb = lltype.malloc(T, d, flavor='raw', zero=True)
491 for j in range(d):
492 va[j] = rffi.r_int(j)
493 vb[j] = rffi.r_int(j)
494 i = 0
495 while i < d:
496 myjitdriver.jit_merge_point()
497
498 if i < 0:
499 raise IndexError
500 if i >= d:
501 raise IndexError
502 a = va[i]
503 if i < 0:
504 raise IndexError
505 if i >= d:
506 raise IndexError
507 b = vb[i]
508 ec = intmask(a)+intmask(b)
509 if i < 0:
510 raise IndexError
511 if i >= d:
512 raise IndexError
513 va[i] = rffi.r_int(ec)
514
515 i += 1
516 lltype.free(va, flavor='raw')
517 lltype.free(vb, flavor='raw')
518 return 0
519 res = self.meta_interp(f, [i], vec=True)
520 assert res == f(i)
521
522
523 @py.test.mark.parametrize('size',[12])
524 def test_body_multiple_accesses(self, size):
525 myjitdriver = JitDriver(greens = [], reds = 'auto')
526 T = lltype.Array(rffi.CHAR, hints={'nolength': True})
527 def f(size):
528 vector_a = malloc(T, size)
529 vector_b = malloc(T, size)
530 i = 0
531 while i < size:
532 myjitdriver.jit_merge_point()
533 # should unroll and group them correctly
534 c1 = vector_a[i]
535 c2 = vector_a[i+1]
536 c3 = vector_a[i+2]
537 #
538 vector_b[i] = c1
539 vector_b[i+1] = c2
540 vector_b[i+2] = c3
541 i += 3
542 free(vector_a)
543 free(vector_b)
544 return 0
545 res = self.meta_interp(f, [size], vec=True, vec_all=True)
546 assert res == f(size)
547
548 def test_max_byte(self):
549 myjitdriver = JitDriver(greens = [], reds = 'auto')
550 T = lltype.Array(rffi.SIGNEDCHAR, hints={'nolength': True})
551 def f(size):
552 vector_a = malloc(T, size)
553 for i in range(size):
554 vector_a[i] = rffi.r_signedchar(1)
555 for i in range(size/2,size):
556 vector_a[i] = rffi.r_signedchar(i)
557 i = 0
558 max = -127
559 while i < size:
560 myjitdriver.jit_merge_point()
561 a = intmask(vector_a[i])
562 a = a & 255
563 if a > max:
564 max = a
565 i += 1
566 free(vector_a)
567 return max
568 res = self.meta_interp(f, [128], vec=True, vec_all=True)
569 assert res == f(128)
570
571
572 def combinations(types, operators):
573 import itertools
574 size = 22
575
576 class Typ(object):
577 def __init__(self, type, storecast, loadcast):
578 self.type = type
579 self.storecast = storecast
580 self.loadcast = loadcast
581 def __repr__(self):
582 return self.type.replace(".","_")
583
584 sizes = [22]
585 for t1, t2, t3, op, size in itertools.product(types, types, types, operators, sizes):
586 yield (size, Typ(*t1), Typ(*t2), Typ(*t3), op[0], op[1])
587 types = [('rffi.DOUBLE', 'float', 'float'),
588 ('rffi.SIGNED', 'int', 'int'),
589 #('rffi.FLOAT', 'rffi.r_singlefloat', 'float'),
590 ]
591 operators = [('add', '+'),
592 ]
593 for size, typ1, typ2, typ3, opname, op in combinations(types, operators):
594 _source = """
595 def test_binary_operations_{name}(self):
596 myjitdriver = JitDriver(greens = [], reds = 'auto')
597 T1 = lltype.Array({type_a}, hints={{'nolength': True}})
598 T2 = lltype.Array({type_b}, hints={{'nolength': True}})
599 T3 = lltype.Array({type_c}, hints={{'nolength': True}})
600 def f(size):
601 vector_a = lltype.malloc(T1, size, flavor='raw')
602 vector_b = lltype.malloc(T2, size, flavor='raw')
603 vector_c = lltype.malloc(T3, size, flavor='raw')
604 for i in range(size):
605 vector_a[i] = {type_a_storecast}(1)
606 for i in range(size):
607 vector_b[i] = {type_b_storecast}(1)
608 for i in range(size):
609 vector_c[i] = {type_c_storecast}(1)
610 i = 0
611 while i < size:
612 myjitdriver.jit_merge_point()
613 a = {type_a_loadcast}(vector_a[i])
614 b = {type_b_loadcast}(vector_b[i])
615 c = (a {op} b)
616 vector_c[i] = {type_c_storecast}(c)
617 i += 1
618 lltype.free(vector_a, flavor='raw')
619 lltype.free(vector_b, flavor='raw')
620 c = {type_c_loadcast}(0.0)
621 for i in range(size):
622 c += {type_c_loadcast}(vector_c[i])
623 lltype.free(vector_c, flavor='raw')
624 return c
625 res = self.meta_interp(f, [{size}], vec=True, vec_all=True)
626 assert res == f({size})
627 """
628 env = {
629 'type_a': typ1.type,
630 'type_b': typ2.type,
631 'type_c': typ3.type,
632 'type_a_loadcast': typ1.loadcast,
633 'type_b_loadcast': typ2.loadcast,
634 'type_c_loadcast': typ3.loadcast,
635 'type_a_storecast': typ1.storecast,
636 'type_b_storecast': typ2.storecast,
637 'type_c_storecast': typ3.storecast,
638 'size': size,
639 'name': str(typ1) + '__' + str(typ2) + '__' + str(typ3) + \
640 '__' + str(size) + '__' + opname,
641 'op': op,
642 }
643 formatted = _source.format(**env)
644 exec(py.code.Source(formatted).compile())
645
646 def test_binary_operations_aa(self):
647 myjitdriver = JitDriver(greens = [], reds = 'auto')
648 T1 = lltype.Array(rffi.DOUBLE, hints={'nolength': True})
649 T3 = lltype.Array(rffi.SIGNED, hints={'nolength': True})
650 def f(size):
651 vector_a = lltype.malloc(T1, size, flavor='raw', zero=True)
652 vector_b = lltype.malloc(T1, size, flavor='raw', zero=True)
653 vector_c = lltype.malloc(T3, size, flavor='raw', zero=True)
654 i = 0
655 while i < size:
656 myjitdriver.jit_merge_point()
657 a = (vector_a[i])
658 b = (vector_b[i])
659 c = (a + b)
660 vector_c[i] = int(c)
661 i += 1
662 free(vector_a)
663 free(vector_b)
664 #c = 0.0
665 #for i in range(size):
666 # c += vector_c[i]
667 lltype.free(vector_c, flavor='raw')
668 return 0
669 res = self.meta_interp(f, [22], vec=True, vec_all=True)
670 assert res == f(22)
671
672 def test_guard_test_location_assert(self):
673 myjitdriver = JitDriver(greens = [], reds = 'auto')
674 T1 = lltype.Array(rffi.SIGNED, hints={'nolength': True})
675 def f(size):
676 vector_a = lltype.malloc(T1, size, flavor='raw', zero=True)
677 for i in range(size):
678 vector_a[i] = 0
679 i = 0
680 breaks = 0
681 while i < size:
682 myjitdriver.jit_merge_point()
683 a = vector_a[i]
684 if a:
685 breaks = 1
686 break
687 del a
688 i += 1
689 lltype.free(vector_a, flavor='raw')
690 return breaks
691 res = self.meta_interp(f, [22], vec=True, vec_all=True)
692 assert res == f(22)
693
694 def run_unpack(self, unpack, vector_type, assignments, float=True):
695 vars = {'v':0,'f':0,'i':0}
696 def newvar(type):
697 c = vars[type]
698 vars[type] = c + 1
699 if type == 'v':
700 return type + str(c) + vector_type
701 return type + str(c)
702 targettoken = TargetToken()
703 finaldescr = BasicFinalDescr(1)
704 args = []
705 args_values = []
706 pack = []
707 suffix = 'f' if float else 'i'
708 for var, vals in assignments.items():
709 v = newvar('v')
710 pack.append('%s = vec_%s()' % (v, suffix))
711 for i,val in enumerate(vals):
712 args_values.append(val)
713 f = newvar(suffix)
714 args.append(f)
715 count = 1
716 # create a new variable
717 vo = v
718 v = newvar('v')
719 pack.append('%s = vec_pack_%s(%s, %s, %d, %d)' % \
720 (v, suffix, vo, f, i, count))
721 vars['x'] = v
722 packs = '\n '.join(pack)
723 resvar = suffix + '{'+suffix+'}'
724
725 # format the resoperations, take care that the lhs of =
726 # is formated later with a new variable name
727 unpackops = unpack
728 if isinstance(unpack, str):
729 unpackops = [unpack]
730 unpacksf = []
731 for up in unpackops:
732 lhs, rhs = up.split("=")
733 rhsf = rhs.format(**vars)
734 newvar('i'); newvar('f'); newvar('v')
735 lhsf = lhs.format(**vars)
736 unpacksf.append(lhsf + '=' + rhsf)
737 unpacks = '\n '.join(unpacksf)
738
739 source = '''
740 [{args}]
741 label({args}, descr=targettoken)
742 {packs}
743 {unpacks}
744 finish({resvar}, descr=finaldescr)
745 '''.format(args=','.join(args),packs=packs, unpacks=unpacks,
746 resvar=resvar.format(**vars))
747 print(source)
748 return self._compile_and_run(source, args_values, float,
749 ns={'targettoken': targettoken, 'finaldescr': finaldescr})
750
751
752 def _compile_and_run(self, source, args_values, float=True, ns={}):
753 loop = parse(source, namespace=ns)
754 cpu = self.CPUClass(rtyper=None, stats=None)
755 cpu.setup_once()
756 #
757 looptoken = JitCellToken()
758 cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
759 #import pdb; pdb.set_trace()
760 deadframe = cpu.execute_token(looptoken, *args_values)
761 print(source)
762 if float:
763 return cpu.get_float_value(deadframe, 0)
764 else:
765 return cpu.get_int_value(deadframe, 0)
766
767 def test_unpack_f(self):
768 # double unpack
769 assert self.run_unpack("f{f} = vec_unpack_f({x}, 0, 1)",
770 "[2xf64]", {'x': (1.2,-1.0)}) == 1.2
771 assert self.run_unpack("f{f} = vec_unpack_f({x}, 1, 1)",
772 "[2xf64]", {'x': (50.33,4321.0)}) == 4321.0
773 def test_unpack_i64(self):
774 # int64
775 assert self.run_unpack("i{i} = vec_unpack_i({x}, 1, 1)",
776 "[2xi64]", {'x': (14,15)}, float=False) == 15
777 assert self.run_unpack("i{i} = vec_unpack_i({x}, 0, 1)",
778 "[2xi64]", {'x': (11,12)}, float=False) == 11
779
780 def test_unpack_i(self):
781 for i in range(16):
782 # i8
783 op = "i{i} = vec_unpack_i({x}, %d, 1)" % i
784 assert self.run_unpack(op, "[16xi8]", {'x': [127,1]*8}, float=False) == \
785 (127 if i%2==0 else 1)
786 # i16
787 if i < 8:
788 assert self.run_unpack(op, "[8xi16]", {'x': [2**15-1,0]*4}, float=False) == \
789 (2**15-1 if i%2==0 else 0)
790 # i32
791 if i < 4:
792 assert self.run_unpack(op, "[4xi32]", {'x': [2**31-1,0]*4}, float=False) == \
793 (2**31-1 if i%2==0 else 0)
794
795 def test_unpack_several(self):
796 values = [1,2,3,4]
797 for i,v in enumerate(values):
798 j = (i // 2) * 2
799 op = ["v{v}[2xi32] = vec_unpack_i({x}, %d, 2)" % j,
800 "i{i} = vec_unpack_i(v{v}[2xi32], %d, 1)" % (i % 2)]
801 assert self.run_unpack(op, "[4xi32]", {'x': values}, float=False) == v
802
803 values = [1,2,3,4,5,6,7,8]
804 for i,v in enumerate(values):
805 j = (i // 4) * 4
806 op = ["v{v}[4xi16] = vec_unpack_i({x}, %d, 4)" % j,
807 "i{i} = vec_unpack_i(v{v}[4xi16], %d, 1)" % (i % 4)]
808 assert self.run_unpack(op, "[8xi16]", {'x': values}, float=False) == v
809
810 values = [1,2,3,4,5,6,7,8] * 2
811 for i,v in enumerate(values):
812 j = (i // 8) * 8
813 op = ["v{v}[8xi8] = vec_unpack_i({x}, %d, 8)" % j,
814 "i{i} = vec_unpack_i(v{v}[8xi8], %d, 1)" % (i % 8)]
815 assert self.run_unpack(op, "[16xi8]", {'x': values}, float=False) == v
816
817 def test_int32_float_casts(self):
818 myjitdriver = JitDriver(greens = [], reds = 'auto', vectorize=True)
819 def f(bytecount, va, vb, vc):
820 i = 0
821 j = 0
822 while i < bytecount:
823 myjitdriver.jit_merge_point()
824 a = raw_storage_getitem(rffi.INT,va,j)
825 b = raw_storage_getitem(rffi.DOUBLE,vb,i)
826 c = rffi.cast(rffi.DOUBLE,a)+b
827 raw_storage_setitem(vc, i, c)
828 j += 4
829 i += 8
830
831 count = 32
832 va = alloc_raw_storage(4*count, zero=True)
833 vb = alloc_raw_storage(8*count, zero=True)
834 for i,v in enumerate([1,2,3,4]*(count/4)):
835 raw_storage_setitem(va, i*4, rffi.cast(rffi.INT,v))
836 for i,v in enumerate([-1.0,-2.0,-3.0,-4.0]*(count/4)):
837 raw_storage_setitem(vb, i*8, rffi.cast(rffi.DOUBLE,v))
838 vc = alloc_raw_storage(8*count, zero=True)
839 self.meta_interp(f, [8*count, va, vb, vc], vec=True)
840
841 for i in range(count):
842 assert raw_storage_getitem(rffi.DOUBLE,vc,i*8) == 0.0
843
844 free_raw_storage(va)
845 free_raw_storage(vb)
846 free_raw_storage(vc)
847
848 def test_float_int32_casts(self):
849 myjitdriver = JitDriver(greens = [], reds = 'auto', vectorize=True)
850 def f(bytecount, va, vb, vc):
851 i = 0
852 j = 0
853 while j < bytecount:
854 myjitdriver.jit_merge_point()
855 a = raw_storage_getitem(rffi.DOUBLE,va,j)
856 b = raw_storage_getitem(rffi.INT,vb,i)
857 c = a+rffi.cast(rffi.DOUBLE,b)
858 raw_storage_setitem(vc, j, c)
859 i += 4
860 j += 8
861
862 count = 32
863 va = alloc_raw_storage(8*count, zero=True)
864 vb = alloc_raw_storage(4*count, zero=True)
865 for i,v in enumerate([1.0,2.0,3.0,4.0]*(count/4)):
866 raw_storage_setitem(va, i*8, rffi.cast(rffi.DOUBLE,v))
867 for i,v in enumerate([-1,-2,-3,-4]*(count/4)):
868 raw_storage_setitem(vb, i*4, rffi.cast(rffi.INT,v))
869 vc = alloc_raw_storage(8*count, zero=True)
870 self.meta_interp(f, [8*count, va, vb, vc], vec=True)
871
872 for i in range(count):
873 assert raw_storage_getitem(rffi.DOUBLE,vc,i*8) == 0.0
874
875 free_raw_storage(va)
876 free_raw_storage(vb)
877 free_raw_storage(vc)
878
879
880 class TestLLtype(LLJitMixin, VectorizeTests):
881 # skip some tests on this backend
882 def test_unpack_f(self):
883 pass
884 def test_unpack_i64(self):
885 pass
886 def test_unpack_i(self):
887 pass
888 def test_unpack_several(self):
889 pass
890 def test_vec_int_sum(self):
891 pass