Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do arithmetic with OpenCL vector types in host-side code?

Tags:

c

types

gcc

opencl

Here's my code:

#include <stdio.h>
#include <CL/cl.h>
#include <CL/cl_platform.h>

int main(){    
    cl_float3 f3 =  (cl_float3){1, 1, 1};
    cl_float3 f31 = (cl_float3) {2, 2, 2};
    cl_float3 f32 = (cl_float3) {2, 2, 2};
    f3 = f31 + f32;
    printf("%g %g %g \n", f3.x, f3.y, f3.z);
    return  0;
}

When compiling with gcc 4.6, it produces the error

test.c:14:11: error: invalid operands to binary + (have ‘cl_float3’ and ‘cl_float3’)

Very strange to me, because the OpenCL Specification demontrates in section 6.4 just that, an addition of two floatn. Do I need to include any other headers?

But even more strange is that when compiling with -std=c99 I get errors like

test.c:16:26: error: ‘cl_float3’ has no member named ‘x’

..for all components (x, y and z)...

like image 681
TeaOverflow Avatar asked Jun 11 '12 11:06

TeaOverflow


2 Answers

The reason for the compilation problem with structure subscripts can be seen in the implementation of the standard in the AMD SDK.

If you look at the <CL/cl_platform.h> header from AMD toolkit you could see how the structures are defined.

 typedef  cl_float4  cl_float3;

 typedef union
 {
    cl_float  CL_ALIGNED(16) s[4];
 #if (defined( __GNUC__) ||  defined( __IBMC__ )) && ! defined( __STRICT_ANSI__ )
   __extension__ struct{ cl_float   x, y, z, w; };
 ....
 #endif
 }cl_float4;

The #if clause is ignored when gcc is invoked with --std=c99.

To make your code work with --std=c99 you could replace references to f3.x with f3.s[0] and so on.

like image 159
Dmitri Chubarov Avatar answered Sep 30 '22 05:09

Dmitri Chubarov


OpenCL programs consist of two parts.

  1. A program which runs on the host. This is normally written in C or C++, but it's nothing special except that it uses the API described in sections 4 & 5 of the OpenCL Specification.
  2. A kernel which runs on the OpenCL device (normally a GPU). This is written in the language specified in section 6. This isn't C, but it's close. It adds things like vector operations (like you're trying to use). This is compiled by the host program passing a string which contains the kernel code to OpenCL via the API.

You've confused the two, and tried to use features of the kernel language in the host code.

like image 35
Paul S Avatar answered Sep 30 '22 06:09

Paul S