b2437de7e1774667aa6e766dc2d1952eecd13bb5
[profile/ivi/opencv.git] / modules / core / src / opencl / gemm.cl
1 // This file is part of OpenCV project.
2 // It is subject to the license terms in the LICENSE file found in the top-level directory
3 // of this distribution and at http://opencv.org/license.html.
4
5 // Copyright (C) 2014, Itseez, Inc., all rights reserved.
6 // Third party copyrights are property of their respective owners.
7
8 #ifdef DOUBLE_SUPPORT
9 #ifdef cl_amd_fp64
10 #pragma OPENCL EXTENSION cl_amd_fp64:enable
11 #elif defined (cl_khr_fp64)
12 #pragma OPENCL EXTENSION cl_khr_fp64:enable
13 #endif
14 #endif
15
16 #define TSIZE (int)sizeof(T)
17
18 #define IND_A mad24(y, A_step, A_offset)
19 #define STEP_A 1
20
21 #define IND_B mad24(x, TSIZE, B_offset)
22 #define STEP_B B_step / TSIZE
23
24 #if cn==2
25 #define MUL(i, a, b)\
26     {\
27     sum.x += fma(a.x, b.x, - a.y * b.y);\
28     sum.y += fma(a.x, b.y, a.y * b.x);\
29     }
30 #else
31 #define MUL(i, a, b) sum = fma(a, b, sum);
32 #endif
33
34
35 __kernel void gemm(__global const uchar * A_ptr, int A_step, int A_offset,
36                    __global const uchar * B_ptr, int B_step, int B_offset,
37                    __global uchar * D_ptr, int D_step, int D_offset, int D_rows, int D_cols,
38                    int n, T1 alpha, T1 beta)
39 {
40     int x = get_global_id(0);
41     int y = get_global_id(1);
42
43     int lidx = get_local_id(0);
44     int lidy = get_local_id(1);
45
46     __global const T* A = (__global const T*)(A_ptr + IND_A);
47     __global const T* B = (__global const T*)(B_ptr + IND_B);
48
49     T sum = (T)(0);
50     __local T a_local[LOCAL_SIZE*LOCAL_SIZE];
51     __local T b_local[LOCAL_SIZE*LOCAL_SIZE];
52
53     for (int p = 0; p < (n+LOCAL_SIZE-1)/LOCAL_SIZE; ++p)
54     {
55         a_local[mad24(lidy, LOCAL_SIZE, lidx)] = A[mad24(p, LOCAL_SIZE, lidx)];
56         b_local[mad24(lidy, LOCAL_SIZE, lidx)] = B[mad24(p, LOCAL_SIZE, lidy)*STEP_B];
57
58         barrier(CLK_LOCAL_MEM_FENCE);
59
60         if (x < D_cols && y < D_rows)
61         {
62             for (int i = 0; i < LOCAL_SIZE && p * LOCAL_SIZE + i < n; ++i)
63                 MUL(i, a_local[mad24(lidy, LOCAL_SIZE, i)], b_local[mad24(i, LOCAL_SIZE, lidx)]);
64         }
65
66         barrier(CLK_LOCAL_MEM_FENCE);
67     }
68
69     if (x < D_cols && y < D_rows)
70     {
71         __global T* D = (__global T*)(D_ptr + mad24(y, D_step, mad24(x, TSIZE, D_offset)));
72 #if HAVE_C
73         D[0] = mad(alpha, sum, D[0]*beta);
74 #else
75         D[0] = alpha * sum;
76 #endif
77     }
78 }