Code refactor: move more memory allocation logic into device API.
[blender.git] / intern / cycles / device / opencl / opencl_base.cpp
1 /*
2  * Copyright 2011-2013 Blender Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #ifdef WITH_OPENCL
18
19 #include "device/opencl/opencl.h"
20
21 #include "kernel/kernel_types.h"
22
23 #include "util/util_algorithm.h"
24 #include "util/util_foreach.h"
25 #include "util/util_logging.h"
26 #include "util/util_md5.h"
27 #include "util/util_path.h"
28 #include "util/util_time.h"
29
30 CCL_NAMESPACE_BEGIN
31
32 struct texture_slot_t {
33         texture_slot_t(const string& name, int slot)
34                 : name(name),
35                   slot(slot) {
36         }
37         string name;
38         int slot;
39 };
40
41 bool OpenCLDeviceBase::opencl_error(cl_int err)
42 {
43         if(err != CL_SUCCESS) {
44                 string message = string_printf("OpenCL error (%d): %s", err, clewErrorString(err));
45                 if(error_msg == "")
46                         error_msg = message;
47                 fprintf(stderr, "%s\n", message.c_str());
48                 return true;
49         }
50
51         return false;
52 }
53
54 void OpenCLDeviceBase::opencl_error(const string& message)
55 {
56         if(error_msg == "")
57                 error_msg = message;
58         fprintf(stderr, "%s\n", message.c_str());
59 }
60
61 void OpenCLDeviceBase::opencl_assert_err(cl_int err, const char* where)
62 {
63         if(err != CL_SUCCESS) {
64                 string message = string_printf("OpenCL error (%d): %s in %s", err, clewErrorString(err), where);
65                 if(error_msg == "")
66                         error_msg = message;
67                 fprintf(stderr, "%s\n", message.c_str());
68 #ifndef NDEBUG
69                 abort();
70 #endif
71         }
72 }
73
74 OpenCLDeviceBase::OpenCLDeviceBase(DeviceInfo& info, Stats &stats, bool background_)
75 : Device(info, stats, background_),
76   memory_manager(this),
77   texture_info(this, "__texture_info", MEM_TEXTURE)
78 {
79         cpPlatform = NULL;
80         cdDevice = NULL;
81         cxContext = NULL;
82         cqCommandQueue = NULL;
83         null_mem = 0;
84         device_initialized = false;
85         textures_need_update = true;
86
87         vector<OpenCLPlatformDevice> usable_devices;
88         OpenCLInfo::get_usable_devices(&usable_devices);
89         if(usable_devices.size() == 0) {
90                 opencl_error("OpenCL: no devices found.");
91                 return;
92         }
93         assert(info.num < usable_devices.size());
94         OpenCLPlatformDevice& platform_device = usable_devices[info.num];
95         cpPlatform = platform_device.platform_id;
96         cdDevice = platform_device.device_id;
97         platform_name = platform_device.platform_name;
98         device_name = platform_device.device_name;
99         VLOG(2) << "Creating new Cycles device for OpenCL platform "
100                 << platform_name << ", device "
101                 << device_name << ".";
102
103         {
104                 /* try to use cached context */
105                 thread_scoped_lock cache_locker;
106                 cxContext = OpenCLCache::get_context(cpPlatform, cdDevice, cache_locker);
107
108                 if(cxContext == NULL) {
109                         /* create context properties array to specify platform */
110                         const cl_context_properties context_props[] = {
111                                 CL_CONTEXT_PLATFORM, (cl_context_properties)cpPlatform,
112                                 0, 0
113                         };
114
115                         /* create context */
116                         cxContext = clCreateContext(context_props, 1, &cdDevice,
117                                 context_notify_callback, cdDevice, &ciErr);
118
119                         if(opencl_error(ciErr)) {
120                                 opencl_error("OpenCL: clCreateContext failed");
121                                 return;
122                         }
123
124                         /* cache it */
125                         OpenCLCache::store_context(cpPlatform, cdDevice, cxContext, cache_locker);
126                 }
127         }
128
129         cqCommandQueue = clCreateCommandQueue(cxContext, cdDevice, 0, &ciErr);
130         if(opencl_error(ciErr)) {
131                 opencl_error("OpenCL: Error creating command queue");
132                 return;
133         }
134
135         null_mem = (device_ptr)clCreateBuffer(cxContext, CL_MEM_READ_ONLY, 1, NULL, &ciErr);
136         if(opencl_error(ciErr)) {
137                 opencl_error("OpenCL: Error creating memory buffer for NULL");
138                 return;
139         }
140
141         /* Allocate this right away so that texture_info is placed at offset 0 in the device memory buffers */
142         texture_info.resize(1);
143         memory_manager.alloc("texture_info", texture_info);
144
145         fprintf(stderr, "Device init success\n");
146         device_initialized = true;
147 }
148
149 OpenCLDeviceBase::~OpenCLDeviceBase()
150 {
151         task_pool.stop();
152
153         memory_manager.free();
154
155         if(null_mem)
156                 clReleaseMemObject(CL_MEM_PTR(null_mem));
157
158         ConstMemMap::iterator mt;
159         for(mt = const_mem_map.begin(); mt != const_mem_map.end(); mt++) {
160                 delete mt->second;
161         }
162
163         base_program.release();
164         if(cqCommandQueue)
165                 clReleaseCommandQueue(cqCommandQueue);
166         if(cxContext)
167                 clReleaseContext(cxContext);
168 }
169
170 void CL_CALLBACK OpenCLDeviceBase::context_notify_callback(const char *err_info,
171         const void * /*private_info*/, size_t /*cb*/, void *user_data)
172 {
173         string device_name = OpenCLInfo::get_device_name((cl_device_id)user_data);
174         fprintf(stderr, "OpenCL error (%s): %s\n", device_name.c_str(), err_info);
175 }
176
177 bool OpenCLDeviceBase::opencl_version_check()
178 {
179         string error;
180         if(!OpenCLInfo::platform_version_check(cpPlatform, &error)) {
181                 opencl_error(error);
182                 return false;
183         }
184         if(!OpenCLInfo::device_version_check(cdDevice, &error)) {
185                 opencl_error(error);
186                 return false;
187         }
188         return true;
189 }
190
191 string OpenCLDeviceBase::device_md5_hash(string kernel_custom_build_options)
192 {
193         MD5Hash md5;
194         char version[256], driver[256], name[256], vendor[256];
195
196         clGetPlatformInfo(cpPlatform, CL_PLATFORM_VENDOR, sizeof(vendor), &vendor, NULL);
197         clGetDeviceInfo(cdDevice, CL_DEVICE_VERSION, sizeof(version), &version, NULL);
198         clGetDeviceInfo(cdDevice, CL_DEVICE_NAME, sizeof(name), &name, NULL);
199         clGetDeviceInfo(cdDevice, CL_DRIVER_VERSION, sizeof(driver), &driver, NULL);
200
201         md5.append((uint8_t*)vendor, strlen(vendor));
202         md5.append((uint8_t*)version, strlen(version));
203         md5.append((uint8_t*)name, strlen(name));
204         md5.append((uint8_t*)driver, strlen(driver));
205
206         string options = kernel_build_options();
207         options += kernel_custom_build_options;
208         md5.append((uint8_t*)options.c_str(), options.size());
209
210         return md5.get_hex();
211 }
212
213 bool OpenCLDeviceBase::load_kernels(const DeviceRequestedFeatures& requested_features)
214 {
215         VLOG(2) << "Loading kernels for platform " << platform_name
216                 << ", device " << device_name << ".";
217         /* Verify if device was initialized. */
218         if(!device_initialized) {
219                 fprintf(stderr, "OpenCL: failed to initialize device.\n");
220                 return false;
221         }
222
223         /* Verify we have right opencl version. */
224         if(!opencl_version_check())
225                 return false;
226
227         base_program = OpenCLProgram(this, "base", "kernel.cl", build_options_for_base_program(requested_features));
228         base_program.add_kernel(ustring("convert_to_byte"));
229         base_program.add_kernel(ustring("convert_to_half_float"));
230         base_program.add_kernel(ustring("displace"));
231         base_program.add_kernel(ustring("background"));
232         base_program.add_kernel(ustring("bake"));
233         base_program.add_kernel(ustring("zero_buffer"));
234
235         denoising_program = OpenCLProgram(this, "denoising", "filter.cl", "");
236         denoising_program.add_kernel(ustring("filter_divide_shadow"));
237         denoising_program.add_kernel(ustring("filter_get_feature"));
238         denoising_program.add_kernel(ustring("filter_detect_outliers"));
239         denoising_program.add_kernel(ustring("filter_combine_halves"));
240         denoising_program.add_kernel(ustring("filter_construct_transform"));
241         denoising_program.add_kernel(ustring("filter_nlm_calc_difference"));
242         denoising_program.add_kernel(ustring("filter_nlm_blur"));
243         denoising_program.add_kernel(ustring("filter_nlm_calc_weight"));
244         denoising_program.add_kernel(ustring("filter_nlm_update_output"));
245         denoising_program.add_kernel(ustring("filter_nlm_normalize"));
246         denoising_program.add_kernel(ustring("filter_nlm_construct_gramian"));
247         denoising_program.add_kernel(ustring("filter_finalize"));
248         denoising_program.add_kernel(ustring("filter_set_tiles"));
249
250         vector<OpenCLProgram*> programs;
251         programs.push_back(&base_program);
252         programs.push_back(&denoising_program);
253         /* Call actual class to fill the vector with its programs. */
254         if(!load_kernels(requested_features, programs)) {
255                 return false;
256         }
257
258         /* Parallel compilation is supported by Cycles, but currently all OpenCL frameworks
259          * serialize the calls internally, so it's not much use right now.
260          * Note: When enabling parallel compilation, use_stdout in the OpenCLProgram constructor
261          * should be set to false as well. */
262 #if 0
263         TaskPool task_pool;
264         foreach(OpenCLProgram *program, programs) {
265                 task_pool.push(function_bind(&OpenCLProgram::load, program));
266         }
267         task_pool.wait_work();
268
269         foreach(OpenCLProgram *program, programs) {
270                 VLOG(2) << program->get_log();
271                 if(!program->is_loaded()) {
272                         program->report_error();
273                         return false;
274                 }
275         }
276 #else
277         foreach(OpenCLProgram *program, programs) {
278                 program->load();
279                 if(!program->is_loaded()) {
280                         return false;
281                 }
282         }
283 #endif
284
285         return true;
286 }
287
288 void OpenCLDeviceBase::mem_alloc(device_memory& mem)
289 {
290         if(mem.name) {
291                 VLOG(1) << "Buffer allocate: " << mem.name << ", "
292                             << string_human_readable_number(mem.memory_size()) << " bytes. ("
293                             << string_human_readable_size(mem.memory_size()) << ")";
294         }
295
296         size_t size = mem.memory_size();
297
298         /* check there is enough memory available for the allocation */
299         cl_ulong max_alloc_size = 0;
300         clGetDeviceInfo(cdDevice, CL_DEVICE_MAX_MEM_ALLOC_SIZE, sizeof(cl_ulong), &max_alloc_size, NULL);
301
302         if(DebugFlags().opencl.mem_limit) {
303                 max_alloc_size = min(max_alloc_size,
304                                      cl_ulong(DebugFlags().opencl.mem_limit - stats.mem_used));
305         }
306
307         if(size > max_alloc_size) {
308                 string error = "Scene too complex to fit in available memory.";
309                 if(mem.name != NULL) {
310                         error += string_printf(" (allocating buffer %s failed.)", mem.name);
311                 }
312                 set_error(error);
313
314                 return;
315         }
316
317         cl_mem_flags mem_flag;
318         void *mem_ptr = NULL;
319
320         if(mem.type == MEM_READ_ONLY || mem.type == MEM_TEXTURE)
321                 mem_flag = CL_MEM_READ_ONLY;
322         else if(mem.type == MEM_WRITE_ONLY || mem.type == MEM_PIXELS)
323                 mem_flag = CL_MEM_WRITE_ONLY;
324         else
325                 mem_flag = CL_MEM_READ_WRITE;
326
327         /* Zero-size allocation might be invoked by render, but not really
328          * supported by OpenCL. Using NULL as device pointer also doesn't really
329          * work for some reason, so for the time being we'll use special case
330          * will null_mem buffer.
331          */
332         if(size != 0) {
333                 mem.device_pointer = (device_ptr)clCreateBuffer(cxContext,
334                                                                 mem_flag,
335                                                                 size,
336                                                                 mem_ptr,
337                                                                 &ciErr);
338                 opencl_assert_err(ciErr, "clCreateBuffer");
339         }
340         else {
341                 mem.device_pointer = null_mem;
342         }
343
344         stats.mem_alloc(size);
345         mem.device_size = size;
346 }
347
348 void OpenCLDeviceBase::mem_copy_to(device_memory& mem)
349 {
350         if(mem.type == MEM_TEXTURE) {
351                 tex_free(mem);
352                 tex_alloc(mem);
353         }
354         else {
355                 if(!mem.device_pointer) {
356                         mem_alloc(mem);
357                 }
358
359                 /* this is blocking */
360                 size_t size = mem.memory_size();
361                 if(size != 0) {
362                         opencl_assert(clEnqueueWriteBuffer(cqCommandQueue,
363                                                            CL_MEM_PTR(mem.device_pointer),
364                                                            CL_TRUE,
365                                                            0,
366                                                            size,
367                                                            (void*)mem.data_pointer,
368                                                            0,
369                                                            NULL, NULL));
370                 }
371         }
372 }
373
374 void OpenCLDeviceBase::mem_copy_from(device_memory& mem, int y, int w, int h, int elem)
375 {
376         size_t offset = elem*y*w;
377         size_t size = elem*w*h;
378         assert(size != 0);
379         opencl_assert(clEnqueueReadBuffer(cqCommandQueue,
380                                           CL_MEM_PTR(mem.device_pointer),
381                                           CL_TRUE,
382                                           offset,
383                                           size,
384                                           (uchar*)mem.data_pointer + offset,
385                                           0,
386                                           NULL, NULL));
387 }
388
389 void OpenCLDeviceBase::mem_zero_kernel(device_ptr mem, size_t size)
390 {
391         cl_kernel ckZeroBuffer = base_program(ustring("zero_buffer"));
392
393         size_t global_size[] = {1024, 1024};
394         size_t num_threads = global_size[0] * global_size[1];
395
396         cl_mem d_buffer = CL_MEM_PTR(mem);
397         cl_ulong d_offset = 0;
398         cl_ulong d_size = 0;
399
400         while(d_offset < size) {
401                 d_size = std::min<cl_ulong>(num_threads*sizeof(float4), size - d_offset);
402
403                 kernel_set_args(ckZeroBuffer, 0, d_buffer, d_size, d_offset);
404
405                 ciErr = clEnqueueNDRangeKernel(cqCommandQueue,
406                                                ckZeroBuffer,
407                                                2,
408                                                NULL,
409                                                global_size,
410                                                NULL,
411                                                0,
412                                                NULL,
413                                                NULL);
414                 opencl_assert_err(ciErr, "clEnqueueNDRangeKernel");
415
416                 d_offset += d_size;
417         }
418 }
419
420 void OpenCLDeviceBase::mem_zero(device_memory& mem)
421 {
422         if(!mem.device_pointer) {
423                 mem_alloc(mem);
424         }
425
426         if(mem.device_pointer) {
427                 if(base_program.is_loaded()) {
428                         mem_zero_kernel(mem.device_pointer, mem.memory_size());
429                 }
430
431                 if(mem.data_pointer) {
432                         memset((void*)mem.data_pointer, 0, mem.memory_size());
433                 }
434
435                 if(!base_program.is_loaded()) {
436                         void* zero = (void*)mem.data_pointer;
437
438                         if(!mem.data_pointer) {
439                                 zero = util_aligned_malloc(mem.memory_size(), 16);
440                                 memset(zero, 0, mem.memory_size());
441                         }
442
443                         opencl_assert(clEnqueueWriteBuffer(cqCommandQueue,
444                                                            CL_MEM_PTR(mem.device_pointer),
445                                                            CL_TRUE,
446                                                            0,
447                                                            mem.memory_size(),
448                                                            zero,
449                                                            0,
450                                                            NULL, NULL));
451
452                         if(!mem.data_pointer) {
453                                 util_aligned_free(zero);
454                         }
455                 }
456         }
457 }
458
459 void OpenCLDeviceBase::mem_free(device_memory& mem)
460 {
461         if(mem.type == MEM_TEXTURE) {
462                 tex_free(mem);
463         }
464         else {
465                 if(mem.device_pointer) {
466                         if(mem.device_pointer != null_mem) {
467                                 opencl_assert(clReleaseMemObject(CL_MEM_PTR(mem.device_pointer)));
468                         }
469                         mem.device_pointer = 0;
470
471                         stats.mem_free(mem.device_size);
472                         mem.device_size = 0;
473                 }
474         }
475 }
476
477 int OpenCLDeviceBase::mem_address_alignment()
478 {
479         return OpenCLInfo::mem_address_alignment(cdDevice);
480 }
481
482 device_ptr OpenCLDeviceBase::mem_alloc_sub_ptr(device_memory& mem, int offset, int size)
483 {
484         cl_mem_flags mem_flag;
485         if(mem.type == MEM_READ_ONLY || mem.type == MEM_TEXTURE)
486                 mem_flag = CL_MEM_READ_ONLY;
487         else if(mem.type == MEM_WRITE_ONLY || mem.type == MEM_PIXELS)
488                 mem_flag = CL_MEM_WRITE_ONLY;
489         else
490                 mem_flag = CL_MEM_READ_WRITE;
491
492         cl_buffer_region info;
493         info.origin = mem.memory_elements_size(offset);
494         info.size = mem.memory_elements_size(size);
495
496         device_ptr sub_buf = (device_ptr) clCreateSubBuffer(CL_MEM_PTR(mem.device_pointer),
497                                                             mem_flag,
498                                                             CL_BUFFER_CREATE_TYPE_REGION,
499                                                             &info,
500                                                             &ciErr);
501         opencl_assert_err(ciErr, "clCreateSubBuffer");
502         return sub_buf;
503 }
504
505 void OpenCLDeviceBase::mem_free_sub_ptr(device_ptr device_pointer)
506 {
507         if(device_pointer && device_pointer != null_mem) {
508                 opencl_assert(clReleaseMemObject(CL_MEM_PTR(device_pointer)));
509         }
510 }
511
512 void OpenCLDeviceBase::const_copy_to(const char *name, void *host, size_t size)
513 {
514         ConstMemMap::iterator i = const_mem_map.find(name);
515         device_vector<uchar> *data;
516
517         if(i == const_mem_map.end()) {
518                 data = new device_vector<uchar>(this, name, MEM_READ_ONLY);
519                 data->alloc(size);
520                 const_mem_map.insert(ConstMemMap::value_type(name, data));
521         }
522         else {
523                 data = i->second;
524         }
525
526         memcpy(data->get_data(), host, size);
527         data->copy_to_device();
528 }
529
530 void OpenCLDeviceBase::tex_alloc(device_memory& mem)
531 {
532         VLOG(1) << "Texture allocate: " << mem.name << ", "
533                 << string_human_readable_number(mem.memory_size()) << " bytes. ("
534                 << string_human_readable_size(mem.memory_size()) << ")";
535
536         memory_manager.alloc(mem.name, mem);
537         /* Set the pointer to non-null to keep code that inspects its value from thinking its unallocated. */
538         mem.device_pointer = 1;
539         textures[mem.name] = &mem;
540         textures_need_update = true;
541 }
542
543 void OpenCLDeviceBase::tex_free(device_memory& mem)
544 {
545         if(mem.device_pointer) {
546                 mem.device_pointer = 0;
547
548                 if(memory_manager.free(mem)) {
549                         textures_need_update = true;
550                 }
551
552                 foreach(TexturesMap::value_type& value, textures) {
553                         if(value.second == &mem) {
554                                 textures.erase(value.first);
555                                 break;
556                         }
557                 }
558         }
559 }
560
561 size_t OpenCLDeviceBase::global_size_round_up(int group_size, int global_size)
562 {
563         int r = global_size % group_size;
564         return global_size + ((r == 0)? 0: group_size - r);
565 }
566
567 void OpenCLDeviceBase::enqueue_kernel(cl_kernel kernel, size_t w, size_t h, size_t max_workgroup_size)
568 {
569         size_t workgroup_size, max_work_items[3];
570
571         clGetKernelWorkGroupInfo(kernel, cdDevice,
572                 CL_KERNEL_WORK_GROUP_SIZE, sizeof(size_t), &workgroup_size, NULL);
573         clGetDeviceInfo(cdDevice,
574                 CL_DEVICE_MAX_WORK_ITEM_SIZES, sizeof(size_t)*3, max_work_items, NULL);
575
576         if(max_workgroup_size > 0 && workgroup_size > max_workgroup_size) {
577                 workgroup_size = max_workgroup_size;
578         }
579
580         /* Try to divide evenly over 2 dimensions. */
581         size_t sqrt_workgroup_size = max((size_t)sqrt((double)workgroup_size), 1);
582         size_t local_size[2] = {sqrt_workgroup_size, sqrt_workgroup_size};
583
584         /* Some implementations have max size 1 on 2nd dimension. */
585         if(local_size[1] > max_work_items[1]) {
586                 local_size[0] = workgroup_size/max_work_items[1];
587                 local_size[1] = max_work_items[1];
588         }
589
590         size_t global_size[2] = {global_size_round_up(local_size[0], w),
591                                  global_size_round_up(local_size[1], h)};
592
593         /* Vertical size of 1 is coming from bake/shade kernels where we should
594          * not round anything up because otherwise we'll either be doing too
595          * much work per pixel (if we don't check global ID on Y axis) or will
596          * be checking for global ID to always have Y of 0.
597          */
598         if(h == 1) {
599                 global_size[h] = 1;
600         }
601
602         /* run kernel */
603         opencl_assert(clEnqueueNDRangeKernel(cqCommandQueue, kernel, 2, NULL, global_size, NULL, 0, NULL, NULL));
604         opencl_assert(clFlush(cqCommandQueue));
605 }
606
607 void OpenCLDeviceBase::set_kernel_arg_mem(cl_kernel kernel, cl_uint *narg, const char *name)
608 {
609         cl_mem ptr;
610
611         MemMap::iterator i = mem_map.find(name);
612         if(i != mem_map.end()) {
613                 ptr = CL_MEM_PTR(i->second);
614         }
615         else {
616                 /* work around NULL not working, even though the spec says otherwise */
617                 ptr = CL_MEM_PTR(null_mem);
618         }
619
620         opencl_assert(clSetKernelArg(kernel, (*narg)++, sizeof(ptr), (void*)&ptr));
621 }
622
623 void OpenCLDeviceBase::set_kernel_arg_buffers(cl_kernel kernel, cl_uint *narg)
624 {
625         flush_texture_buffers();
626
627         memory_manager.set_kernel_arg_buffers(kernel, narg);
628 }
629
630 void OpenCLDeviceBase::flush_texture_buffers()
631 {
632         if(!textures_need_update) {
633                 return;
634         }
635         textures_need_update = false;
636
637         /* Setup slots for textures. */
638         int num_slots = 0;
639
640         vector<texture_slot_t> texture_slots;
641
642 #define KERNEL_TEX(type, name) \
643         if(textures.find(#name) != textures.end()) { \
644                 texture_slots.push_back(texture_slot_t(#name, num_slots)); \
645         } \
646         num_slots++;
647 #include "kernel/kernel_textures.h"
648
649         int num_data_slots = num_slots;
650
651         foreach(TexturesMap::value_type& tex, textures) {
652                 string name = tex.first;
653
654                 if(string_startswith(name, "__tex_image")) {
655                         int pos = name.rfind("_");
656                         int id = atoi(name.data() + pos + 1);
657                         texture_slots.push_back(texture_slot_t(name,
658                                                                    num_data_slots + id));
659                         num_slots = max(num_slots, num_data_slots + id + 1);
660                 }
661         }
662
663         /* Realloc texture descriptors buffer. */
664         memory_manager.free(texture_info);
665         texture_info.resize(num_slots);
666         memory_manager.alloc("texture_info", texture_info);
667
668         /* Fill in descriptors */
669         foreach(texture_slot_t& slot, texture_slots) {
670                 TextureInfo& info = texture_info[slot.slot];
671
672                 MemoryManager::BufferDescriptor desc = memory_manager.get_descriptor(slot.name);
673                 info.data = desc.offset;
674                 info.cl_buffer = desc.device_buffer;
675
676                 if(string_startswith(slot.name, "__tex_image")) {
677                         device_memory *mem = textures[slot.name];
678
679                         info.width = mem->data_width;
680                         info.height = mem->data_height;
681                         info.depth = mem->data_depth;
682
683                         info.interpolation = mem->interpolation;
684                         info.extension = mem->extension;
685                 }
686         }
687
688         /* Force write of descriptors. */
689         memory_manager.free(texture_info);
690         memory_manager.alloc("texture_info", texture_info);
691 }
692
693 void OpenCLDeviceBase::film_convert(DeviceTask& task, device_ptr buffer, device_ptr rgba_byte, device_ptr rgba_half)
694 {
695         /* cast arguments to cl types */
696         cl_mem d_data = CL_MEM_PTR(const_mem_map["__data"]->device_pointer);
697         cl_mem d_rgba = (rgba_byte)? CL_MEM_PTR(rgba_byte): CL_MEM_PTR(rgba_half);
698         cl_mem d_buffer = CL_MEM_PTR(buffer);
699         cl_int d_x = task.x;
700         cl_int d_y = task.y;
701         cl_int d_w = task.w;
702         cl_int d_h = task.h;
703         cl_float d_sample_scale = 1.0f/(task.sample + 1);
704         cl_int d_offset = task.offset;
705         cl_int d_stride = task.stride;
706
707
708         cl_kernel ckFilmConvertKernel = (rgba_byte)? base_program(ustring("convert_to_byte")): base_program(ustring("convert_to_half_float"));
709
710         cl_uint start_arg_index =
711                 kernel_set_args(ckFilmConvertKernel,
712                                 0,
713                                 d_data,
714                                 d_rgba,
715                                 d_buffer);
716
717         set_kernel_arg_buffers(ckFilmConvertKernel, &start_arg_index);
718
719         start_arg_index += kernel_set_args(ckFilmConvertKernel,
720                                            start_arg_index,
721                                            d_sample_scale,
722                                            d_x,
723                                            d_y,
724                                            d_w,
725                                            d_h,
726                                            d_offset,
727                                            d_stride);
728
729         enqueue_kernel(ckFilmConvertKernel, d_w, d_h);
730 }
731
732 bool OpenCLDeviceBase::denoising_non_local_means(device_ptr image_ptr,
733                                                  device_ptr guide_ptr,
734                                                  device_ptr variance_ptr,
735                                                  device_ptr out_ptr,
736                                                  DenoisingTask *task)
737 {
738         int4 rect = task->rect;
739         int w = rect.z-rect.x;
740         int h = rect.w-rect.y;
741         int r = task->nlm_state.r;
742         int f = task->nlm_state.f;
743         float a = task->nlm_state.a;
744         float k_2 = task->nlm_state.k_2;
745
746         cl_mem difference     = CL_MEM_PTR(task->nlm_state.temporary_1_ptr);
747         cl_mem blurDifference = CL_MEM_PTR(task->nlm_state.temporary_2_ptr);
748         cl_mem weightAccum    = CL_MEM_PTR(task->nlm_state.temporary_3_ptr);
749
750         cl_mem image_mem = CL_MEM_PTR(image_ptr);
751         cl_mem guide_mem = CL_MEM_PTR(guide_ptr);
752         cl_mem variance_mem = CL_MEM_PTR(variance_ptr);
753         cl_mem out_mem = CL_MEM_PTR(out_ptr);
754
755         mem_zero_kernel(task->nlm_state.temporary_3_ptr, sizeof(float)*w*h);
756         mem_zero_kernel(out_ptr, sizeof(float)*w*h);
757
758         cl_kernel ckNLMCalcDifference = denoising_program(ustring("filter_nlm_calc_difference"));
759         cl_kernel ckNLMBlur           = denoising_program(ustring("filter_nlm_blur"));
760         cl_kernel ckNLMCalcWeight     = denoising_program(ustring("filter_nlm_calc_weight"));
761         cl_kernel ckNLMUpdateOutput   = denoising_program(ustring("filter_nlm_update_output"));
762         cl_kernel ckNLMNormalize      = denoising_program(ustring("filter_nlm_normalize"));
763
764         for(int i = 0; i < (2*r+1)*(2*r+1); i++) {
765                 int dy = i / (2*r+1) - r;
766                 int dx = i % (2*r+1) - r;
767                 int4 local_rect = make_int4(max(0, -dx), max(0, -dy), rect.z-rect.x - max(0, dx), rect.w-rect.y - max(0, dy));
768                 kernel_set_args(ckNLMCalcDifference, 0,
769                                 dx, dy, guide_mem, variance_mem,
770                                 difference, local_rect, w, 0, a, k_2);
771                 kernel_set_args(ckNLMBlur, 0,
772                                 difference, blurDifference, local_rect, w, f);
773                 kernel_set_args(ckNLMCalcWeight, 0,
774                                 blurDifference, difference, local_rect, w, f);
775                 kernel_set_args(ckNLMUpdateOutput, 0,
776                                 dx, dy, blurDifference, image_mem,
777                                 out_mem, weightAccum, local_rect, w, f);
778
779                 enqueue_kernel(ckNLMCalcDifference, w, h);
780                 enqueue_kernel(ckNLMBlur,           w, h);
781                 enqueue_kernel(ckNLMCalcWeight,     w, h);
782                 enqueue_kernel(ckNLMBlur,           w, h);
783                 enqueue_kernel(ckNLMUpdateOutput,   w, h);
784         }
785
786         int4 local_rect = make_int4(0, 0, w, h);
787         kernel_set_args(ckNLMNormalize, 0,
788                         out_mem, weightAccum, local_rect, w);
789         enqueue_kernel(ckNLMNormalize, w, h);
790
791         return true;
792 }
793
794 bool OpenCLDeviceBase::denoising_construct_transform(DenoisingTask *task)
795 {
796         cl_mem buffer_mem = CL_MEM_PTR(task->buffer.mem.device_pointer);
797         cl_mem transform_mem = CL_MEM_PTR(task->storage.transform.device_pointer);
798         cl_mem rank_mem = CL_MEM_PTR(task->storage.rank.device_pointer);
799
800         cl_kernel ckFilterConstructTransform = denoising_program(ustring("filter_construct_transform"));
801
802         kernel_set_args(ckFilterConstructTransform, 0,
803                         buffer_mem,
804                         transform_mem,
805                         rank_mem,
806                         task->filter_area,
807                         task->rect,
808                         task->buffer.pass_stride,
809                         task->radius,
810                         task->pca_threshold);
811
812         enqueue_kernel(ckFilterConstructTransform,
813                        task->storage.w,
814                        task->storage.h,
815                        256);
816
817         return true;
818 }
819
820 bool OpenCLDeviceBase::denoising_reconstruct(device_ptr color_ptr,
821                                              device_ptr color_variance_ptr,
822                                              device_ptr output_ptr,
823                                              DenoisingTask *task)
824 {
825         mem_zero(task->storage.XtWX);
826         mem_zero(task->storage.XtWY);
827
828         cl_mem color_mem = CL_MEM_PTR(color_ptr);
829         cl_mem color_variance_mem = CL_MEM_PTR(color_variance_ptr);
830         cl_mem output_mem = CL_MEM_PTR(output_ptr);
831
832         cl_mem buffer_mem = CL_MEM_PTR(task->buffer.mem.device_pointer);
833         cl_mem transform_mem = CL_MEM_PTR(task->storage.transform.device_pointer);
834         cl_mem rank_mem = CL_MEM_PTR(task->storage.rank.device_pointer);
835         cl_mem XtWX_mem = CL_MEM_PTR(task->storage.XtWX.device_pointer);
836         cl_mem XtWY_mem = CL_MEM_PTR(task->storage.XtWY.device_pointer);
837
838         cl_kernel ckNLMCalcDifference   = denoising_program(ustring("filter_nlm_calc_difference"));
839         cl_kernel ckNLMBlur             = denoising_program(ustring("filter_nlm_blur"));
840         cl_kernel ckNLMCalcWeight       = denoising_program(ustring("filter_nlm_calc_weight"));
841         cl_kernel ckNLMConstructGramian = denoising_program(ustring("filter_nlm_construct_gramian"));
842         cl_kernel ckFinalize            = denoising_program(ustring("filter_finalize"));
843
844         cl_mem difference     = CL_MEM_PTR(task->reconstruction_state.temporary_1_ptr);
845         cl_mem blurDifference = CL_MEM_PTR(task->reconstruction_state.temporary_2_ptr);
846
847         int r = task->radius;
848         int f = 4;
849         float a = 1.0f;
850         for(int i = 0; i < (2*r+1)*(2*r+1); i++) {
851                 int dy = i / (2*r+1) - r;
852                 int dx = i % (2*r+1) - r;
853
854                 int local_rect[4] = {max(0, -dx), max(0, -dy),
855                                      task->reconstruction_state.source_w - max(0, dx),
856                                      task->reconstruction_state.source_h - max(0, dy)};
857
858                 kernel_set_args(ckNLMCalcDifference, 0,
859                                 dx, dy,
860                                 color_mem,
861                                 color_variance_mem,
862                                 difference,
863                                 local_rect,
864                                 task->buffer.w,
865                                 task->buffer.pass_stride,
866                                 a, task->nlm_k_2);
867                 enqueue_kernel(ckNLMCalcDifference,
868                                task->reconstruction_state.source_w,
869                                task->reconstruction_state.source_h);
870
871                 kernel_set_args(ckNLMBlur, 0,
872                                 difference,
873                                 blurDifference,
874                                 local_rect,
875                                 task->buffer.w,
876                                 f);
877                 enqueue_kernel(ckNLMBlur,
878                                task->reconstruction_state.source_w,
879                                task->reconstruction_state.source_h);
880
881                 kernel_set_args(ckNLMCalcWeight, 0,
882                                 blurDifference,
883                                 difference,
884                                 local_rect,
885                                 task->buffer.w,
886                                 f);
887                 enqueue_kernel(ckNLMCalcWeight,
888                                task->reconstruction_state.source_w,
889                                task->reconstruction_state.source_h);
890
891                 /* Reuse previous arguments. */
892                 enqueue_kernel(ckNLMBlur,
893                                task->reconstruction_state.source_w,
894                                task->reconstruction_state.source_h);
895
896                 kernel_set_args(ckNLMConstructGramian, 0,
897                                 dx, dy,
898                                 blurDifference,
899                                 buffer_mem,
900                                 transform_mem,
901                                 rank_mem,
902                                 XtWX_mem,
903                                 XtWY_mem,
904                                 local_rect,
905                                 task->reconstruction_state.filter_rect,
906                                 task->buffer.w,
907                                 task->buffer.h,
908                                 f,
909                             task->buffer.pass_stride);
910                 enqueue_kernel(ckNLMConstructGramian,
911                                task->reconstruction_state.source_w,
912                                task->reconstruction_state.source_h,
913                                256);
914         }
915
916         kernel_set_args(ckFinalize, 0,
917                         task->buffer.w,
918                         task->buffer.h,
919                         output_mem,
920                         rank_mem,
921                         XtWX_mem,
922                         XtWY_mem,
923                         task->filter_area,
924                         task->reconstruction_state.buffer_params,
925                         task->render_buffer.samples);
926         enqueue_kernel(ckFinalize,
927                        task->reconstruction_state.source_w,
928                        task->reconstruction_state.source_h);
929
930         return true;
931 }
932
933 bool OpenCLDeviceBase::denoising_combine_halves(device_ptr a_ptr,
934                                                 device_ptr b_ptr,
935                                                 device_ptr mean_ptr,
936                                                 device_ptr variance_ptr,
937                                                 int r, int4 rect,
938                                                 DenoisingTask *task)
939 {
940         cl_mem a_mem = CL_MEM_PTR(a_ptr);
941         cl_mem b_mem = CL_MEM_PTR(b_ptr);
942         cl_mem mean_mem = CL_MEM_PTR(mean_ptr);
943         cl_mem variance_mem = CL_MEM_PTR(variance_ptr);
944
945         cl_kernel ckFilterCombineHalves = denoising_program(ustring("filter_combine_halves"));
946
947         kernel_set_args(ckFilterCombineHalves, 0,
948                         mean_mem,
949                         variance_mem,
950                         a_mem,
951                         b_mem,
952                         rect,
953                         r);
954         enqueue_kernel(ckFilterCombineHalves,
955                        task->rect.z-task->rect.x,
956                        task->rect.w-task->rect.y);
957
958         return true;
959 }
960
961 bool OpenCLDeviceBase::denoising_divide_shadow(device_ptr a_ptr,
962                                                device_ptr b_ptr,
963                                                device_ptr sample_variance_ptr,
964                                                device_ptr sv_variance_ptr,
965                                                device_ptr buffer_variance_ptr,
966                                                DenoisingTask *task)
967 {
968         cl_mem a_mem = CL_MEM_PTR(a_ptr);
969         cl_mem b_mem = CL_MEM_PTR(b_ptr);
970         cl_mem sample_variance_mem = CL_MEM_PTR(sample_variance_ptr);
971         cl_mem sv_variance_mem = CL_MEM_PTR(sv_variance_ptr);
972         cl_mem buffer_variance_mem = CL_MEM_PTR(buffer_variance_ptr);
973
974         cl_mem tiles_mem = CL_MEM_PTR(task->tiles_mem.device_pointer);
975
976         cl_kernel ckFilterDivideShadow = denoising_program(ustring("filter_divide_shadow"));
977
978         kernel_set_args(ckFilterDivideShadow, 0,
979                         task->render_buffer.samples,
980                         tiles_mem,
981                         a_mem,
982                         b_mem,
983                         sample_variance_mem,
984                         sv_variance_mem,
985                         buffer_variance_mem,
986                         task->rect,
987                         task->render_buffer.pass_stride,
988                         task->render_buffer.denoising_data_offset);
989         enqueue_kernel(ckFilterDivideShadow,
990                        task->rect.z-task->rect.x,
991                        task->rect.w-task->rect.y);
992
993         return true;
994 }
995
996 bool OpenCLDeviceBase::denoising_get_feature(int mean_offset,
997                                              int variance_offset,
998                                              device_ptr mean_ptr,
999                                              device_ptr variance_ptr,
1000                                              DenoisingTask *task)
1001 {
1002         cl_mem mean_mem = CL_MEM_PTR(mean_ptr);
1003         cl_mem variance_mem = CL_MEM_PTR(variance_ptr);
1004
1005         cl_mem tiles_mem = CL_MEM_PTR(task->tiles_mem.device_pointer);
1006
1007         cl_kernel ckFilterGetFeature = denoising_program(ustring("filter_get_feature"));
1008
1009         kernel_set_args(ckFilterGetFeature, 0,
1010                         task->render_buffer.samples,
1011                         tiles_mem,
1012                         mean_offset,
1013                         variance_offset,
1014                         mean_mem,
1015                         variance_mem,
1016                         task->rect,
1017                         task->render_buffer.pass_stride,
1018                         task->render_buffer.denoising_data_offset);
1019         enqueue_kernel(ckFilterGetFeature,
1020                        task->rect.z-task->rect.x,
1021                        task->rect.w-task->rect.y);
1022
1023         return true;
1024 }
1025
1026 bool OpenCLDeviceBase::denoising_detect_outliers(device_ptr image_ptr,
1027                                                  device_ptr variance_ptr,
1028                                                  device_ptr depth_ptr,
1029                                                  device_ptr output_ptr,
1030                                                  DenoisingTask *task)
1031 {
1032         cl_mem image_mem = CL_MEM_PTR(image_ptr);
1033         cl_mem variance_mem = CL_MEM_PTR(variance_ptr);
1034         cl_mem depth_mem = CL_MEM_PTR(depth_ptr);
1035         cl_mem output_mem = CL_MEM_PTR(output_ptr);
1036
1037         cl_kernel ckFilterDetectOutliers = denoising_program(ustring("filter_detect_outliers"));
1038
1039         kernel_set_args(ckFilterDetectOutliers, 0,
1040                         image_mem,
1041                         variance_mem,
1042                         depth_mem,
1043                         output_mem,
1044                         task->rect,
1045                         task->buffer.pass_stride);
1046         enqueue_kernel(ckFilterDetectOutliers,
1047                        task->rect.z-task->rect.x,
1048                        task->rect.w-task->rect.y);
1049
1050         return true;
1051 }
1052
1053 bool OpenCLDeviceBase::denoising_set_tiles(device_ptr *buffers,
1054                                            DenoisingTask *task)
1055 {
1056         task->tiles_mem.copy_to_device();
1057
1058         cl_mem tiles_mem = CL_MEM_PTR(task->tiles_mem.device_pointer);
1059
1060         cl_kernel ckFilterSetTiles = denoising_program(ustring("filter_set_tiles"));
1061
1062         kernel_set_args(ckFilterSetTiles, 0, tiles_mem);
1063         for(int i = 0; i < 9; i++) {
1064                 cl_mem buffer_mem = CL_MEM_PTR(buffers[i]);
1065                 kernel_set_args(ckFilterSetTiles, i+1, buffer_mem);
1066         }
1067
1068         enqueue_kernel(ckFilterSetTiles, 1, 1);
1069
1070         return true;
1071 }
1072
1073 void OpenCLDeviceBase::denoise(RenderTile &rtile, const DeviceTask &task)
1074 {
1075         DenoisingTask denoising(this);
1076
1077         denoising.functions.set_tiles = function_bind(&OpenCLDeviceBase::denoising_set_tiles, this, _1, &denoising);
1078         denoising.functions.construct_transform = function_bind(&OpenCLDeviceBase::denoising_construct_transform, this, &denoising);
1079         denoising.functions.reconstruct = function_bind(&OpenCLDeviceBase::denoising_reconstruct, this, _1, _2, _3, &denoising);
1080         denoising.functions.divide_shadow = function_bind(&OpenCLDeviceBase::denoising_divide_shadow, this, _1, _2, _3, _4, _5, &denoising);
1081         denoising.functions.non_local_means = function_bind(&OpenCLDeviceBase::denoising_non_local_means, this, _1, _2, _3, _4, &denoising);
1082         denoising.functions.combine_halves = function_bind(&OpenCLDeviceBase::denoising_combine_halves, this, _1, _2, _3, _4, _5, _6, &denoising);
1083         denoising.functions.get_feature = function_bind(&OpenCLDeviceBase::denoising_get_feature, this, _1, _2, _3, _4, &denoising);
1084         denoising.functions.detect_outliers = function_bind(&OpenCLDeviceBase::denoising_detect_outliers, this, _1, _2, _3, _4, &denoising);
1085
1086         denoising.filter_area = make_int4(rtile.x, rtile.y, rtile.w, rtile.h);
1087         denoising.render_buffer.samples = rtile.sample;
1088
1089         RenderTile rtiles[9];
1090         rtiles[4] = rtile;
1091         task.map_neighbor_tiles(rtiles, this);
1092         denoising.tiles_from_rendertiles(rtiles);
1093
1094         denoising.init_from_devicetask(task);
1095
1096         denoising.run_denoising();
1097
1098         task.unmap_neighbor_tiles(rtiles, this);
1099 }
1100
1101 void OpenCLDeviceBase::shader(DeviceTask& task)
1102 {
1103         /* cast arguments to cl types */
1104         cl_mem d_data = CL_MEM_PTR(const_mem_map["__data"]->device_pointer);
1105         cl_mem d_input = CL_MEM_PTR(task.shader_input);
1106         cl_mem d_output = CL_MEM_PTR(task.shader_output);
1107         cl_int d_shader_eval_type = task.shader_eval_type;
1108         cl_int d_shader_filter = task.shader_filter;
1109         cl_int d_shader_x = task.shader_x;
1110         cl_int d_shader_w = task.shader_w;
1111         cl_int d_offset = task.offset;
1112
1113         cl_kernel kernel;
1114
1115         if(task.shader_eval_type >= SHADER_EVAL_BAKE) {
1116                 kernel = base_program(ustring("bake"));
1117         }
1118         else if(task.shader_eval_type == SHADER_EVAL_DISPLACE) {
1119                 kernel = base_program(ustring("displace"));
1120         }
1121         else {
1122                 kernel = base_program(ustring("background"));
1123         }
1124
1125         cl_uint start_arg_index =
1126                 kernel_set_args(kernel,
1127                                 0,
1128                                 d_data,
1129                                 d_input,
1130                                 d_output);
1131
1132         set_kernel_arg_buffers(kernel, &start_arg_index);
1133
1134         start_arg_index += kernel_set_args(kernel,
1135                                            start_arg_index,
1136                                            d_shader_eval_type);
1137         if(task.shader_eval_type >= SHADER_EVAL_BAKE) {
1138                 start_arg_index += kernel_set_args(kernel,
1139                                                    start_arg_index,
1140                                                    d_shader_filter);
1141         }
1142         start_arg_index += kernel_set_args(kernel,
1143                                            start_arg_index,
1144                                            d_shader_x,
1145                                            d_shader_w,
1146                                            d_offset);
1147
1148         for(int sample = 0; sample < task.num_samples; sample++) {
1149
1150                 if(task.get_cancel())
1151                         break;
1152
1153                 kernel_set_args(kernel, start_arg_index, sample);
1154
1155                 enqueue_kernel(kernel, task.shader_w, 1);
1156
1157                 clFinish(cqCommandQueue);
1158
1159                 task.update_progress(NULL);
1160         }
1161 }
1162
1163 string OpenCLDeviceBase::kernel_build_options(const string *debug_src)
1164 {
1165         string build_options = "-cl-no-signed-zeros -cl-mad-enable ";
1166
1167         if(platform_name == "NVIDIA CUDA") {
1168                 build_options += "-D__KERNEL_OPENCL_NVIDIA__ "
1169                                  "-cl-nv-maxrregcount=32 "
1170                                  "-cl-nv-verbose ";
1171
1172                 uint compute_capability_major, compute_capability_minor;
1173                 clGetDeviceInfo(cdDevice, CL_DEVICE_COMPUTE_CAPABILITY_MAJOR_NV,
1174                                 sizeof(cl_uint), &compute_capability_major, NULL);
1175                 clGetDeviceInfo(cdDevice, CL_DEVICE_COMPUTE_CAPABILITY_MINOR_NV,
1176                                 sizeof(cl_uint), &compute_capability_minor, NULL);
1177
1178                 build_options += string_printf("-D__COMPUTE_CAPABILITY__=%u ",
1179                                                compute_capability_major * 100 +
1180                                                compute_capability_minor * 10);
1181         }
1182
1183         else if(platform_name == "Apple")
1184                 build_options += "-D__KERNEL_OPENCL_APPLE__ ";
1185
1186         else if(platform_name == "AMD Accelerated Parallel Processing")
1187                 build_options += "-D__KERNEL_OPENCL_AMD__ ";
1188
1189         else if(platform_name == "Intel(R) OpenCL") {
1190                 build_options += "-D__KERNEL_OPENCL_INTEL_CPU__ ";
1191
1192                 /* Options for gdb source level kernel debugging.
1193                  * this segfaults on linux currently.
1194                  */
1195                 if(OpenCLInfo::use_debug() && debug_src)
1196                         build_options += "-g -s \"" + *debug_src + "\" ";
1197         }
1198
1199         if(OpenCLInfo::use_debug())
1200                 build_options += "-D__KERNEL_OPENCL_DEBUG__ ";
1201
1202 #ifdef WITH_CYCLES_DEBUG
1203         build_options += "-D__KERNEL_DEBUG__ ";
1204 #endif
1205
1206         return build_options;
1207 }
1208
1209 /* TODO(sergey): In the future we can use variadic templates, once
1210  * C++0x is allowed. Should allow to clean this up a bit.
1211  */
1212 int OpenCLDeviceBase::kernel_set_args(cl_kernel kernel,
1213                     int start_argument_index,
1214                     const ArgumentWrapper& arg1,
1215                     const ArgumentWrapper& arg2,
1216                     const ArgumentWrapper& arg3,
1217                     const ArgumentWrapper& arg4,
1218                     const ArgumentWrapper& arg5,
1219                     const ArgumentWrapper& arg6,
1220                     const ArgumentWrapper& arg7,
1221                     const ArgumentWrapper& arg8,
1222                     const ArgumentWrapper& arg9,
1223                     const ArgumentWrapper& arg10,
1224                     const ArgumentWrapper& arg11,
1225                     const ArgumentWrapper& arg12,
1226                     const ArgumentWrapper& arg13,
1227                     const ArgumentWrapper& arg14,
1228                     const ArgumentWrapper& arg15,
1229                     const ArgumentWrapper& arg16,
1230                     const ArgumentWrapper& arg17,
1231                     const ArgumentWrapper& arg18,
1232                     const ArgumentWrapper& arg19,
1233                     const ArgumentWrapper& arg20,
1234                     const ArgumentWrapper& arg21,
1235                     const ArgumentWrapper& arg22,
1236                     const ArgumentWrapper& arg23,
1237                     const ArgumentWrapper& arg24,
1238                     const ArgumentWrapper& arg25,
1239                     const ArgumentWrapper& arg26,
1240                     const ArgumentWrapper& arg27,
1241                     const ArgumentWrapper& arg28,
1242                     const ArgumentWrapper& arg29,
1243                     const ArgumentWrapper& arg30,
1244                     const ArgumentWrapper& arg31,
1245                     const ArgumentWrapper& arg32,
1246                     const ArgumentWrapper& arg33)
1247 {
1248         int current_arg_index = 0;
1249 #define FAKE_VARARG_HANDLE_ARG(arg) \
1250         do { \
1251                 if(arg.pointer != NULL) { \
1252                         opencl_assert(clSetKernelArg( \
1253                                 kernel, \
1254                                 start_argument_index + current_arg_index, \
1255                                 arg.size, arg.pointer)); \
1256                         ++current_arg_index; \
1257                 } \
1258                 else { \
1259                         return current_arg_index; \
1260                 } \
1261         } while(false)
1262         FAKE_VARARG_HANDLE_ARG(arg1);
1263         FAKE_VARARG_HANDLE_ARG(arg2);
1264         FAKE_VARARG_HANDLE_ARG(arg3);
1265         FAKE_VARARG_HANDLE_ARG(arg4);
1266         FAKE_VARARG_HANDLE_ARG(arg5);
1267         FAKE_VARARG_HANDLE_ARG(arg6);
1268         FAKE_VARARG_HANDLE_ARG(arg7);
1269         FAKE_VARARG_HANDLE_ARG(arg8);
1270         FAKE_VARARG_HANDLE_ARG(arg9);
1271         FAKE_VARARG_HANDLE_ARG(arg10);
1272         FAKE_VARARG_HANDLE_ARG(arg11);
1273         FAKE_VARARG_HANDLE_ARG(arg12);
1274         FAKE_VARARG_HANDLE_ARG(arg13);
1275         FAKE_VARARG_HANDLE_ARG(arg14);
1276         FAKE_VARARG_HANDLE_ARG(arg15);
1277         FAKE_VARARG_HANDLE_ARG(arg16);
1278         FAKE_VARARG_HANDLE_ARG(arg17);
1279         FAKE_VARARG_HANDLE_ARG(arg18);
1280         FAKE_VARARG_HANDLE_ARG(arg19);
1281         FAKE_VARARG_HANDLE_ARG(arg20);
1282         FAKE_VARARG_HANDLE_ARG(arg21);
1283         FAKE_VARARG_HANDLE_ARG(arg22);
1284         FAKE_VARARG_HANDLE_ARG(arg23);
1285         FAKE_VARARG_HANDLE_ARG(arg24);
1286         FAKE_VARARG_HANDLE_ARG(arg25);
1287         FAKE_VARARG_HANDLE_ARG(arg26);
1288         FAKE_VARARG_HANDLE_ARG(arg27);
1289         FAKE_VARARG_HANDLE_ARG(arg28);
1290         FAKE_VARARG_HANDLE_ARG(arg29);
1291         FAKE_VARARG_HANDLE_ARG(arg30);
1292         FAKE_VARARG_HANDLE_ARG(arg31);
1293         FAKE_VARARG_HANDLE_ARG(arg32);
1294         FAKE_VARARG_HANDLE_ARG(arg33);
1295 #undef FAKE_VARARG_HANDLE_ARG
1296         return current_arg_index;
1297 }
1298
1299 void OpenCLDeviceBase::release_kernel_safe(cl_kernel kernel)
1300 {
1301         if(kernel) {
1302                 clReleaseKernel(kernel);
1303         }
1304 }
1305
1306 void OpenCLDeviceBase::release_mem_object_safe(cl_mem mem)
1307 {
1308         if(mem != NULL) {
1309                 clReleaseMemObject(mem);
1310         }
1311 }
1312
1313 void OpenCLDeviceBase::release_program_safe(cl_program program)
1314 {
1315         if(program) {
1316                 clReleaseProgram(program);
1317         }
1318 }
1319
1320 /* ** Those guys are for workign around some compiler-specific bugs ** */
1321
1322 cl_program OpenCLDeviceBase::load_cached_kernel(
1323         ustring key,
1324         thread_scoped_lock& cache_locker)
1325 {
1326         return OpenCLCache::get_program(cpPlatform,
1327                                         cdDevice,
1328                                         key,
1329                                         cache_locker);
1330 }
1331
1332 void OpenCLDeviceBase::store_cached_kernel(
1333         cl_program program,
1334         ustring key,
1335         thread_scoped_lock& cache_locker)
1336 {
1337         OpenCLCache::store_program(cpPlatform,
1338                                    cdDevice,
1339                                    program,
1340                                    key,
1341                                    cache_locker);
1342 }
1343
1344 string OpenCLDeviceBase::build_options_for_base_program(
1345         const DeviceRequestedFeatures& requested_features)
1346 {
1347         /* TODO(sergey): By default we compile all features, meaning
1348          * mega kernel is not getting feature-based optimizations.
1349          *
1350          * Ideally we need always compile kernel with as less features
1351          * enabled as possible to keep performance at it's max.
1352          */
1353
1354         /* For now disable baking when not in use as this has major
1355          * impact on kernel build times.
1356          */
1357         if(!requested_features.use_baking) {
1358                 return "-D__NO_BAKING__";
1359         }
1360
1361         return "";
1362 }
1363
1364 CCL_NAMESPACE_END
1365
1366 #endif