// Generated by decuda.
// OpenCL device code is the bulk of this file. The host-side calls
// (`cudaXxx`) have been rewritten to OpenCL equivalents inline// surrounding host program still needs a cl_context + cl_queue, not
// included here. Look for TODO(decuda) markers for items requiring
// manual attention.
// Complex fixture: tiled matrix transpose using a shared-memory tile.
//
// Exercises:
// - 2D grid and block (dim3 with two components)
// - __shared__ tile with __syncthreads barriers
// - blockIdx.{x,y} and threadIdx.{x,y} and blockDim.{x,y}
// - __global__ kernel with pointer + dimension args
// - cudaMalloc / cudaFree / cudaMemcpy
// - cuda_runtime.h header
#include <CL/cl.h> /* was: cuda_runtime.h */
#define TILE 16
__kernel void transpose(const float* in, float* out, int width, int height) {
__local float tile[TILE][TILE]
int x = get_group_id(0) * get_local_size(0) + get_local_id(0) int y = get_group_id(0) * get_local_size(0) + get_local_id(0)
// Load a tile from global memory into shared memory (coalesced read).
if (x < width && y < height) {
tile[get_local_id(0)][get_local_id(0)] = in[y * width + x] }
barrier(CLK_LOCAL_MEM_FENCE)
// Write the transposed tile back to global memory.
int ox = get_group_id(0) * get_local_size(0) + get_local_id(0) int oy = get_group_id(0) * get_local_size(0) + get_local_id(0) if (ox < height && oy < width) {
out[oy * height + ox] = tile[get_local_id(0)][get_local_id(0)] }
}
int main(void) {
const int W = 1024 const int H = 1024 float* d_in = nullptr float* d_out = nullptr
cudaMalloc((void**)&d_in, W * H * sizeof(float)) cudaMalloc((void**)&d_out, W * H * sizeof(float)) cudaMemcpy(d_in, d_in, W * H * sizeof(float), cudaMemcpyDeviceToDevice)
dim3 grid(W / TILE, H / TILE) dim3 block(TILE, TILE) clEnqueueNDRangeKernel(queue, transpose_kernel, 1, NULL, (size_t[1]){grid}, (size_t[1]){block}, 0, NULL, NULL) /* args: d_in, d_out, W, H */
cudaDeviceSynchronize() cudaFree(d_in) cudaFree(d_out) return 0}