-
Notifications
You must be signed in to change notification settings - Fork 0
/
helper.h
97 lines (79 loc) · 2.51 KB
/
helper.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <iostream>
#include <fstream>
#include <OpenCL/opencl.h>
//#include <CL/opencl.h>
#include <arrayfire.h>
#include <af/opencl.h>
static std::string get_kernel_string(const char *file_name)
{
std::ifstream file(file_name);
std::string kernel;
std::string line;
if (!file.is_open()){
std::cout << "Cannot find file " << file_name << std::endl;
throw 1;
}
while(std::getline(file, line)) {
kernel = kernel + line;
kernel = kernel + "\n";
}
return kernel;
}
static cl_context get_context(cl_mem x)
{
cl_context context;
cl_int err = clGetMemObjectInfo(x, CL_MEM_CONTEXT, sizeof(cl_context), &context, NULL);
if (err != CL_SUCCESS) {
printf("OpenCL Error: Failed to get context from Memory object\n");
throw (err);
}
return context;
}
static cl_program build_program(cl_context context, std::string kernel_string)
{
cl_int err;
const char *source = kernel_string.c_str();
size_t length = kernel_string.size();
cl_program program = clCreateProgramWithSource(context, 1, &source, &length, &err);
if (err != CL_SUCCESS) {
printf("OpenCL Error: Failed to create program\n");
throw (err);
}
err = clBuildProgram(program, 0, NULL, "", NULL, NULL);
if (err != CL_SUCCESS) {
printf("OpenCL Error: Failed to build program\n");
size_t len;
cl_int ret = clGetProgramBuildInfo(program, 0, CL_PROGRAM_BUILD_LOG, 0, 0, &len);
char *out = new char[len];
ret = clGetProgramBuildInfo(program, 0, CL_PROGRAM_BUILD_LOG, len, out, 0);
printf("%d %s",ret, out);
delete[] out;
throw (err);
}
return program;
}
static cl_kernel create_kernel(cl_program program, const char *kernel_name)
{
cl_int err;
cl_kernel kernel = clCreateKernel(program, kernel_name, &err);
if (err != CL_SUCCESS) {
printf("OpenCL Error(%d): Failed to create kernel %s\n", err, kernel_name);
throw (err);
}
return kernel;
}
static cl_command_queue create_queue(cl_context context)
{
cl_device_id device;
cl_int err = clGetContextInfo(context, CL_CONTEXT_DEVICES, sizeof(cl_device_id), &device, NULL);
if (err != CL_SUCCESS) {
printf("OpenCL Error: Failed to get device from context\n");
throw (err);
}
cl_command_queue queue = clCreateCommandQueue(context, device, 0, &err);
if (err != CL_SUCCESS) {
printf("OpenCL Error: Failed to command queue\n");
throw (err);
}
return queue;
}