| 1 | #!/bin/sh |
| 2 | set -ex |
| 3 | trap 'rm o' 0 |
| 4 | cflags=$(pkg-config --cflags --libs libhwy) |
| 5 | c++ -x c++ - -o o -static-libasan -fsanitize=address -Wall -Wextra -Wpedantic $cflags <<EOF |
| 6 | #include <hwy/highway.h> |
| 7 | #include <cstring> |
| 8 | #include <stdio.h> |
| 9 | #include <time.h> |
| 10 | #include <stdlib.h> |
| 11 | |
| 12 | namespace hn = hwy::HWY_NAMESPACE; |
| 13 | using T = int; |
| 14 | void MulAddLoop(const T* HWY_RESTRICT mul_array, |
| 15 | const T* HWY_RESTRICT add_array, |
| 16 | const size_t size, T* HWY_RESTRICT x_array) { |
| 17 | const hn::ScalableTag<T> d; |
| 18 | for (size_t i = 0; i < size; i += hn::Lanes(d)) { |
| 19 | const auto mul = hn::Load(d, mul_array + i); |
| 20 | const auto add = hn::Load(d, add_array + i); |
| 21 | auto x = hn::Load(d, x_array + i); |
| 22 | x = hn::MulAdd(mul, x, add); |
| 23 | hn::Store(x, d, x_array + i); |
| 24 | } |
| 25 | } |
| 26 | int main(){ |
| 27 | /* Initialize arrays with random small integers. */ |
| 28 | srand(time(NULL)); |
| 29 | const hn::ScalableTag<T> d; |
| 30 | size_t size = hn::Lanes(d)*3; |
| 31 | T *a = (T*)malloc(size*sizeof(T)); |
| 32 | T *b = (T*)malloc(size*sizeof(T)); |
| 33 | T *c = (T*)malloc(size*sizeof(T)); |
| 34 | T *c_orig = (T*)malloc(size*sizeof(T)); |
| 35 | for(size_t i=0; i<size; i++) { |
| 36 | a[i] = rand()%9-4; |
| 37 | b[i] = rand()%9-4; |
| 38 | c[i] = rand()%9-4; |
| 39 | } |
| 40 | memcpy(c_orig, c, size*sizeof(T)); |
| 41 | |
| 42 | /* Run MulAdd on them. */ |
| 43 | MulAddLoop(a, b, size, c); |
| 44 | |
| 45 | /* Check that the SIMD function gives the same result as the |
| 46 | * unserialized math. */ |
| 47 | int ret = 0; |
| 48 | for(size_t i=0; i<size; i++) { |
| 49 | auto expected = c_orig[i]*a[i]+b[i]; |
| 50 | printf("%zuth element is %d (%d expected); (a,b,c_orig)=(%d,%d,%d).\n", |
| 51 | i, c[i], expected, a[i], b[i], c_orig[i]); |
| 52 | ret += expected != c[i]; |
| 53 | } |
| 54 | |
| 55 | free(c_orig); |
| 56 | free(c); |
| 57 | free(b); |
| 58 | free(a); |
| 59 | printf("Got %d unexpected results.\n", ret); |
| 60 | return ret; |
| 61 | } |
| 62 | EOF |
| 63 | ./o |