#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <math.h>


#define COMMENT "Histogram_GPU"
#define RGB_COMPONENT_COLOR 255
#define HISTOGRAM_SIZE 64
#define TILE_WITDH 16

typedef struct {
    unsigned char red, green, blue;
} PPMPixel;

typedef struct {
    int x, y;
    PPMPixel *data;
} PPMImage;

double rtclock()
{
    struct timezone Tzp;
    struct timeval Tp;
    int stat;
    stat = gettimeofday (&Tp, &Tzp);
    if (stat != 0) printf("Error return from gettimeofday: %d",stat);
    return(Tp.tv_sec + Tp.tv_usec*1.0e-6);
}


static PPMImage *readPPM(const char *filename) {
    char buff[16];
    PPMImage *img;
    FILE *fp;
    int c, rgb_comp_color;
    fp = fopen(filename, "rb");
    if (!fp) {
        fprintf(stderr, "Unable to open file '%s'\n", filename);
        exit(1);
    }

    if (!fgets(buff, sizeof(buff), fp)) {
        perror(filename);
        exit(1);
    }

    if (buff[0] != 'P' || buff[1] != '6') {
        fprintf(stderr, "Invalid image format (must be 'P6')\n");
        exit(1);
    }

    img = (PPMImage *) malloc(sizeof(PPMImage));
    if (!img) {
        fprintf(stderr, "Unable to allocate memory\n");
        exit(1);
    }

    c = getc(fp);
    while (c == '#') {
        while (getc(fp) != '\n')
            ;
        c = getc(fp);
    }

    ungetc(c, fp);
    if (fscanf(fp, "%d %d", &img->x, &img->y) != 2) {
        fprintf(stderr, "Invalid image size (error loading '%s')\n", filename);
        exit(1);
    }

    if (fscanf(fp, "%d", &rgb_comp_color) != 1) {
        fprintf(stderr, "Invalid rgb component (error loading '%s')\n",
                filename);
        exit(1);
    }

    if (rgb_comp_color != RGB_COMPONENT_COLOR) {
        fprintf(stderr, "'%s' does not have 8-bits components\n", filename);
        exit(1);
    }

    while (fgetc(fp) != '\n')
        ;
    img->data = (PPMPixel*) malloc(img->x * img->y * sizeof(PPMPixel));

    if (!img) {
        fprintf(stderr, "Unable to allocate memory\n");
        exit(1);
    }

    if (fread(img->data, 3 * img->x, img->y, fp) != img->y) {
        fprintf(stderr, "Error loading image '%s'\n", filename);
        exit(1);
    }

    fclose(fp);
    return img;
}


__global__ void add_to_hist(PPMImage *d_image, float* hist) {
    __shared__ float private_hist[HISTOGRAM_SIZE];
    float size = d_image->y*d_image->x*1.0;


    if(threadIdx.x * TILE_WITDH + threadIdx.y < HISTOGRAM_SIZE) private_hist[threadIdx.x * TILE_WITDH + threadIdx.y] = 0;
    __syncthreads();

    // Get col
    int col = blockDim.x * blockIdx.x + threadIdx.x;
    // Get row
    int row = blockDim.y * blockIdx.y + threadIdx.y;
    // Get index
    int index = row * d_image->x + col;
    if((row < d_image->y && col < d_image->x) && (index < d_image->x*d_image->y)) {
        // Sum
        atomicAdd(&(private_hist[16*d_image->data[index].red + 4 * d_image->data[index].green + d_image->data[index].blue]), 1);

    }

    __syncthreads();
    if(threadIdx.x * TILE_WITDH + threadIdx.y < HISTOGRAM_SIZE) {
        atomicAdd(&(hist[threadIdx.x * TILE_WITDH + threadIdx.y]), (private_hist[threadIdx.x * TILE_WITDH + threadIdx.y]/size));
    }
}



void Histogram(PPMImage *image, float *h) {

    //Init variables;
    int i;
    unsigned int rows, cols, img_size;
    PPMImage *d_image;
    PPMPixel *d_pixels;
    float *d_hist;

    // CUDA TIMERS
    /*
    cudaEvent_t start, stop;
    cudaEventCreate(&start);
    cudaEventCreate(&stop);
    float tbuffer, tenviar, tk, treceber, ttotal;
    */

    // Get data
    cols = image->x;
    rows = image->y;
    img_size = cols * rows;

    //Preprocess data
    for (i = 0; i < img_size; i++) {
        image->data[i].red = floor((image->data[i].red * 4) / 256);
        image->data[i].blue = floor((image->data[i].blue * 4) / 256);
        image->data[i].green = floor((image->data[i].green * 4) / 256);
    }


    //cudaEventRecord(start);
    // Alloc structure to devise
    cudaMalloc((void **)&d_image, sizeof(PPMImage));

    // Alloc image to devise
    cudaMalloc((void **)&d_pixels, sizeof(PPMPixel) * img_size);

    //alloc histogram to devise
    cudaMalloc((void **)&d_hist, HISTOGRAM_SIZE*sizeof(float));

    /*
    cudaEventRecord(stop);
    cudaEventSynchronize(stop);
    cudaEventElapsedTime(&tbuffer, start, stop);
    printf("Alloc Time: %f ", tbuffer);
    */


    //cudaEventRecord(start);
    // cpy stucture to devise
    cudaMemcpy(d_image, image, sizeof(PPMImage), cudaMemcpyHostToDevice);
    cudaMemcpy(d_pixels, image->data, sizeof(PPMPixel) * img_size, cudaMemcpyHostToDevice);
    cudaMemcpy(&(d_image->data), &d_pixels, sizeof(PPMPixel *), cudaMemcpyHostToDevice);

    // cpy histogram to devise
    cudaMemcpy(d_hist, h, HISTOGRAM_SIZE*sizeof(float), cudaMemcpyHostToDevice);
    /*
    cudaEventRecord(stop);
    cudaEventSynchronize(stop);
    cudaEventElapsedTime(&tenviar, start, stop);
    printf("copy Time: %f ", tenviar);
    */


    //Init dimGrid and dimBlocks
    //cudaEventRecord(start);
    dim3 dimGrid(ceil((float)cols / TILE_WITDH), ceil((float)rows / TILE_WITDH), 1);
    dim3 dimBlock(TILE_WITDH, TILE_WITDH, 1);

    // Call function
    add_to_hist<<<dimGrid, dimBlock>>>(d_image, d_hist);
    /*
    cudaEventRecord(stop);

    cudaEventSynchronize(stop);
    cudaEventElapsedTime(&tk, start, stop);
    printf("CUDA KERNEL: %f\n", tk);
    */


    //cudaEventRecord(start);
    // Copy result to local array
    cudaMemcpy(h, d_hist, HISTOGRAM_SIZE*sizeof(float), cudaMemcpyDeviceToHost);

    /*
    cudaEventRecord(stop);
    cudaEventSynchronize(stop);
    cudaEventElapsedTime(&treceber, start, stop);
    printf("receber Time: %f ", treceber);

    ttotal = tbuffer + tenviar + tk + treceber;
    printf("Total: %f\n", ttotal);
    */

    //Free memory
    cudaFree(d_image);
    cudaFree(d_pixels);
    cudaFree(d_hist);
    /*
    cudaEventDestroy(start);
    cudaEventDestroy(stop);
    */
}

int main(int argc, char *argv[]) {

    if( argc != 2 ) {
        printf("Too many or no one arguments supplied.\n");
    }

    double t_start, t_end;
    int i;
    char *filename = argv[1];

    PPMImage *image = readPPM(filename);

    float *h = (float*)malloc(sizeof(float) * 64);

    //Inicializar h
    for(i=0; i < 64; i++) h[i] = 0.0;

    t_start = rtclock();
    Histogram(image, h);
    t_end = rtclock();

    for (i = 0; i < 64; i++){
        printf("%0.3f ", h[i]);
    }

    printf("\n");
    fprintf(stdout, "%0.6lf\n", t_end - t_start);
    free(h);

    return (0);
}



/*

ts = tempo_serial
tbuffer = tempo_GPU_criar_buffer
tenviar = tempo_GPU_offload_enviar
tk = tempo_kernel
treceber = tempo_GPU_offload_receber
ttotal = GPU_total
speedup = speedup (tempo_serial / GPU_total).


arqX |    ts      |   tbuffer  |   tenviar  |      tk    |  treceber   |  GPU_total   | speedup |
-------------------------------------------------------------------------------------------------
arq1 | 0.320540 s | 1.62240 ms | 0.80217 ms | 0.67052 ms |  0.02444 ms |  3.11955 ms  | 102.751 |
-------------------------------------------------------------------------------------------------
arq2 | 0.585691 s | 1.29168 ms | 1.07040 ms | 1.83283 ms |  0.02112 ms |  4.21603 ms  | 138.920 |
-------------------------------------------------------------------------------------------------
arq3 | 1.676812 s | 1.30262 ms | 3.99257 ms | 7.15699 ms |  0.02096 ms | 12.47315 ms  | 134.433 |
-------------------------------------------------------------------------------------------------


*/

	.file	"tmpxft_00323f85_00000000-6_histogram.cudafe1.cpp"
	.text
#APP

#NO_APP
	.type	_ZL26__cudaUnregisterBinaryUtilv, @function
_ZL26__cudaUnregisterBinaryUtilv:
.LFB2033:
	.cfi_startproc
	endbr64
	movq	_ZL20__cudaFatCubinHandle(%rip), %rdi
	jmp	__cudaUnregisterFatBinary@PLT
	.cfi_endproc
.LFE2033:
	.size	_ZL26__cudaUnregisterBinaryUtilv, .-_ZL26__cudaUnregisterBinaryUtilv
	.section	.rodata.str1.1,"aMS",@progbits,1
.LC0:
	.string	"Error return from gettimeofday: %d"
	.text
	.globl	_Z7rtclockv
	.type	_Z7rtclockv, @function
_Z7rtclockv:
.LFB2027:
	.cfi_startproc
	endbr64
	subq	$40, %rsp
	.cfi_def_cfa_offset 48
	movq	%fs:40, %rax
	movq	%rax, 24(%rsp)
	xorl	%eax, %eax
	movq	%rsp, %rsi
	leaq	8(%rsp), %rdi
	call	gettimeofday@PLT
	testl	%eax, %eax
	je	.L3
	movl	%eax, %edx
	leaq	.LC0(%rip), %rsi
	movl	$2, %edi
	xorl	%eax, %eax
	call	__printf_chk@PLT
.L3:
	cvtsi2sdq	16(%rsp), %xmm0
	mulsd	.LC1(%rip), %xmm0
	cvtsi2sdq	8(%rsp), %xmm1
	addsd	%xmm1, %xmm0
	movq	24(%rsp), %rax
	subq	%fs:40, %rax
	je	.L4
	call	__stack_chk_fail@PLT
.L4:
	addq	$40, %rsp
	.cfi_def_cfa_offset 8
	ret
	.cfi_endproc
.LFE2027:
	.size	_Z7rtclockv, .-_Z7rtclockv
	.globl	_Z41__device_stub__Z11add_to_histP8PPMImagePfP8PPMImagePf
	.type	_Z41__device_stub__Z11add_to_histP8PPMImagePfP8PPMImagePf, @function
_Z41__device_stub__Z11add_to_histP8PPMImagePfP8PPMImagePf:
.LFB2055:
	.cfi_startproc
	endbr64
	subq	$120, %rsp
	.cfi_def_cfa_offset 128
	movq	%rdi, 8(%rsp)
	leaq	32(%rsp), %rcx
	leaq	24(%rsp), %rdx
	movq	%rsi, (%rsp)
	leaq	40(%rsp), %rdi
	leaq	52(%rsp), %rsi
	movq	%fs:40, %rax
	movq	%rax, 104(%rsp)
	xorl	%eax, %eax
	leaq	8(%rsp), %rax
	movl	$1, 48(%rsp)
	movq	%rax, 88(%rsp)
	movq	%rsp, %rax
	movq	%rax, 96(%rsp)
	movabsq	$4294967297, %rax
	movq	%rax, 40(%rsp)
	movq	%rax, 52(%rsp)
	movl	$1, 60(%rsp)
	call	__cudaPopCallConfiguration@PLT
	testl	%eax, %eax
	jne	.L10
	pushq	32(%rsp)
	.cfi_def_cfa_offset 136
	leaq	_Z11add_to_histP8PPMImagePf(%rip), %rdi
	pushq	32(%rsp)
	.cfi_def_cfa_offset 144
	movq	68(%rsp), %rcx
	movl	76(%rsp), %r8d
	movq	56(%rsp), %rsi
	movl	64(%rsp), %edx
	leaq	104(%rsp), %r9
	call	cudaLaunchKernel@PLT
	popq	%rax
	.cfi_def_cfa_offset 136
	popq	%rdx
	.cfi_def_cfa_offset 128
.L10:
	movq	104(%rsp), %rax
	subq	%fs:40, %rax
	je	.L12
	call	__stack_chk_fail@PLT
.L12:
	addq	$120, %rsp
	.cfi_def_cfa_offset 8
	ret
	.cfi_endproc
.LFE2055:
	.size	_Z41__device_stub__Z11add_to_histP8PPMImagePfP8PPMImagePf, .-_Z41__device_stub__Z11add_to_histP8PPMImagePfP8PPMImagePf
	.globl	_Z11add_to_histP8PPMImagePf
	.type	_Z11add_to_histP8PPMImagePf, @function
_Z11add_to_histP8PPMImagePf:
.LFB2056:
	.cfi_startproc
	endbr64
	jmp	_Z41__device_stub__Z11add_to_histP8PPMImagePfP8PPMImagePf
	.cfi_endproc
.LFE2056:
	.size	_Z11add_to_histP8PPMImagePf, .-_Z11add_to_histP8PPMImagePf
	.globl	_Z9HistogramP8PPMImagePf
	.type	_Z9HistogramP8PPMImagePf, @function
_Z9HistogramP8PPMImagePf:
.LFB2029:
	.cfi_startproc
	endbr64
	pushq	%r15
	.cfi_def_cfa_offset 16
	.cfi_offset 15, -16
	xorl	%edx, %edx
	pushq	%r14
	.cfi_def_cfa_offset 24
	.cfi_offset 14, -24
	pushq	%r13
	.cfi_def_cfa_offset 32
	.cfi_offset 13, -32
	pushq	%r12
	.cfi_def_cfa_offset 40
	.cfi_offset 12, -40
	movq	%rdi, %r12
	pushq	%rbp
	.cfi_def_cfa_offset 48
	.cfi_offset 6, -48
	movq	%rsi, %rbp
	pushq	%rbx
	.cfi_def_cfa_offset 56
	.cfi_offset 3, -56
	subq	$72, %rsp
	.cfi_def_cfa_offset 128
	movl	(%rdi), %r13d
	movl	4(%rdi), %r14d
	movq	%fs:40, %rax
	movq	%rax, 56(%rsp)
	xorl	%eax, %eax
	movl	%r13d, %ebx
	imull	%r14d, %ebx
.L16:
	cmpl	%ebx, %edx
	jnb	.L25
	leaq	(%rdx,%rdx,2), %rax
	addq	8(%r12), %rax
	incq	%rdx
	shrb	$6, (%rax)
	shrb	$6, 2(%rax)
	shrb	$6, 1(%rax)
	jmp	.L16
.L25:
	leaq	(%rbx,%rbx,2), %rbx
	leaq	8(%rsp), %rdi
	movl	$16, %esi
	call	cudaMalloc@PLT
	leaq	16(%rsp), %r15
	movq	%rbx, %rsi
	movq	%r15, %rdi
	call	cudaMalloc@PLT
	leaq	24(%rsp), %rdi
	movl	$256, %esi
	call	cudaMalloc@PLT
	movq	8(%rsp), %rdi
	movl	$1, %ecx
	movq	%r12, %rsi
	movl	$16, %edx
	call	cudaMemcpy@PLT
	movq	8(%r12), %rsi
	movq	16(%rsp), %rdi
	movq	%rbx, %rdx
	movl	$1, %ecx
	call	cudaMemcpy@PLT
	movq	8(%rsp), %rax
	movl	$1, %ecx
	movq	%r15, %rsi
	movl	$8, %edx
	leaq	8(%rax), %rdi
	call	cudaMemcpy@PLT
	movq	24(%rsp), %rdi
	movl	$1, %ecx
	movq	%rbp, %rsi
	movl	$256, %edx
	call	cudaMemcpy@PLT
	movl	%r14d, %eax
	cvtsi2ssq	%rax, %xmm0
	mulss	.LC2(%rip), %xmm0
	call	ceilf@PLT
	movl	%r13d, %eax
	movd	%xmm0, %ebx
	cvtsi2ssq	%rax, %xmm0
	mulss	.LC2(%rip), %xmm0
	call	ceilf@PLT
	movd	%ebx, %xmm1
	xorl	%r9d, %r9d
	xorl	%r8d, %r8d
	cvttss2siq	%xmm0, %rax
	movl	$1, %ecx
	movl	$1, %esi
	movabsq	$68719476752, %rdx
	movl	%eax, 32(%rsp)
	cvttss2siq	%xmm1, %rax
	movl	%eax, 36(%rsp)
	movq	32(%rsp), %rdi
	call	__cudaPushCallConfiguration@PLT
	testl	%eax, %eax
	jne	.L22
	movq	24(%rsp), %rsi
	movq	8(%rsp), %rdi
	call	_Z41__device_stub__Z11add_to_histP8PPMImagePfP8PPMImagePf
.L22:
	movq	24(%rsp), %rsi
	movl	$2, %ecx
	movl	$256, %edx
	movq	%rbp, %rdi
	call	cudaMemcpy@PLT
	movq	8(%rsp), %rdi
	call	cudaFree@PLT
	movq	16(%rsp), %rdi
	call	cudaFree@PLT
	movq	24(%rsp), %rdi
	call	cudaFree@PLT
	movq	56(%rsp), %rax
	subq	%fs:40, %rax
	je	.L23
	call	__stack_chk_fail@PLT
.L23:
	addq	$72, %rsp
	.cfi_def_cfa_offset 56
	popq	%rbx
	.cfi_def_cfa_offset 48
	popq	%rbp
	.cfi_def_cfa_offset 40
	popq	%r12
	.cfi_def_cfa_offset 32
	popq	%r13
	.cfi_def_cfa_offset 24
	popq	%r14
	.cfi_def_cfa_offset 16
	popq	%r15
	.cfi_def_cfa_offset 8
	ret
	.cfi_endproc
.LFE2029:
	.size	_Z9HistogramP8PPMImagePf, .-_Z9HistogramP8PPMImagePf
	.section	.rodata.str1.1
.LC3:
	.string	"Too many or no one arguments supplied.\n"
.LC4:
	.string	"rb"
.LC5:
	.string	"Unable to open file '%s'\n"
.LC6:
	.string	"Invalid image format (must be 'P6')\n"
.LC7:
	.string	"Unable to allocate memory\n"
.LC8:
	.string	"%d %d"
.LC9:
	.string	"Invalid image size (error loading '%s')\n"
.LC10:
	.string	"%d"
.LC11:
	.string	"Invalid rgb component (error loading '%s')\n"
.LC12:
	.string	"'%s' does not have 8-bits components\n"
.LC13:
	.string	"Error loading image '%s'\n"
.LC14:
	.string	"%0.3f "
.LC15:
	.string	"\n"
.LC16:
	.string	"%0.6lf\n"
	.section	.text.startup,"ax",@progbits
	.globl	main
	.type	main, @function
main:
.LFB2030:
	.cfi_startproc
	endbr64
	pushq	%r15
	.cfi_def_cfa_offset 16
	.cfi_offset 15, -16
	pushq	%r14
	.cfi_def_cfa_offset 24
	.cfi_offset 14, -24
	pushq	%r13
	.cfi_def_cfa_offset 32
	.cfi_offset 13, -32
	pushq	%r12
	.cfi_def_cfa_offset 40
	.cfi_offset 12, -40
	pushq	%rbp
	.cfi_def_cfa_offset 48
	.cfi_offset 6, -48
	pushq	%rbx
	.cfi_def_cfa_offset 56
	.cfi_offset 3, -56
	movq	%rsi, %rbx
	subq	$56, %rsp
	.cfi_def_cfa_offset 112
	movq	%fs:40, %rax
	movq	%rax, 40(%rsp)
	xorl	%eax, %eax
	cmpl	$2, %edi
	je	.L27
	leaq	.LC3(%rip), %rsi
	movl	$2, %edi
	call	__printf_chk@PLT
.L27:
	movq	8(%rbx), %r12
	leaq	.LC4(%rip), %rsi
	movq	%r12, %rdi
	call	fopen@PLT
	movq	%r12, %rcx
	leaq	.LC5(%rip), %rdx
	movq	%rax, %rbx
	testq	%rax, %rax
	je	.L53
	leaq	24(%rsp), %rdi
	movq	%rax, %rcx
	movl	$16, %edx
	movl	$16, %esi
	call	__fgets_chk@PLT
	testq	%rax, %rax
	jne	.L29
	movq	%r12, %rdi
	call	perror@PLT
.L52:
	movl	$1, %edi
	call	exit@PLT
.L29:
	cmpb	$80, 24(%rsp)
	jne	.L30
	cmpb	$54, 25(%rsp)
	je	.L31
.L30:
	leaq	.LC6(%rip), %rdx
	jmp	.L54
.L31:
	movl	$16, %edi
	call	malloc@PLT
	movq	%rax, %rbp
	testq	%rax, %rax
	jne	.L51
	leaq	.LC7(%rip), %rdx
.L54:
	movq	stderr(%rip), %rdi
	movl	$2, %esi
	xorl	%eax, %eax
	call	__fprintf_chk@PLT
	jmp	.L52
.L34:
	movq	%rbx, %rdi
	call	getc@PLT
	cmpl	$10, %eax
	jne	.L34
.L51:
	movq	%rbx, %rdi
	call	getc@PLT
	cmpl	$35, %eax
	je	.L34
	movq	%rbx, %rsi
	movl	%eax, %edi
	call	ungetc@PLT
	leaq	4(%rbp), %rcx
	movq	%rbp, %rdx
	movq	%rbx, %rdi
	leaq	.LC8(%rip), %rsi
	xorl	%eax, %eax
	call	__isoc23_fscanf@PLT
	movq	%r12, %rcx
	leaq	.LC9(%rip), %rdx
	cmpl	$2, %eax
	jne	.L53
	leaq	20(%rsp), %rdx
	xorl	%eax, %eax
	leaq	.LC10(%rip), %rsi
	movq	%rbx, %rdi
	call	__isoc23_fscanf@PLT
	movq	%r12, %rcx
	leaq	.LC11(%rip), %rdx
	decl	%eax
	jne	.L53
	cmpl	$255, 20(%rsp)
	leaq	.LC12(%rip), %rdx
	jne	.L53
.L37:
	movq	%rbx, %rdi
	call	fgetc@PLT
	cmpl	$10, %eax
	jne	.L37
	movl	0(%rbp), %r14d
	movl	4(%rbp), %r15d
	movl	%r14d, %r13d
	imull	%r15d, %r13d
	movslq	%r13d, %r13
	leaq	0(%r13,%r13,2), %r13
	movq	%r13, %rdi
	call	malloc@PLT
	leal	(%r14,%r14,2), %edx
	movslq	%r15d, %rcx
	movq	%rbx, %r8
	movq	%rax, 8(%rbp)
	movslq	%edx, %rdx
	movq	%rax, %rdi
	movq	%r13, %rsi
	call	__fread_chk@PLT
	movq	%rax, %rdx
	movslq	4(%rbp), %rax
	cmpq	%rax, %rdx
	je	.L38
	movq	%r12, %rcx
	leaq	.LC13(%rip), %rdx
.L53:
	movq	stderr(%rip), %rdi
	movl	$2, %esi
	xorl	%eax, %eax
	call	__fprintf_chk@PLT
	jmp	.L52
.L38:
	movq	%rbx, %rdi
	xorl	%r12d, %r12d
	leaq	.LC14(%rip), %r13
	call	fclose@PLT
	movl	$256, %edi
	call	malloc@PLT
	movl	$64, %ecx
	movq	%rax, %rbx
	xorl	%eax, %eax
	movq	%rbx, %rdi
	rep stosl
	call	_Z7rtclockv
	movq	%rbp, %rdi
	movq	%rbx, %rsi
	movsd	%xmm0, 8(%rsp)
	call	_Z9HistogramP8PPMImagePf
	call	_Z7rtclockv
	movq	%xmm0, %rbp
.L39:
	cvtss2sd	(%rbx,%r12,4), %xmm0
	movq	%r13, %rsi
	movl	$2, %edi
	movb	$1, %al
	call	__printf_chk@PLT
	incq	%r12
	cmpq	$64, %r12
	jne	.L39
	leaq	.LC15(%rip), %rsi
	movl	$2, %edi
	xorl	%eax, %eax
	call	__printf_chk@PLT
	movq	%rbp, %xmm0
	subsd	8(%rsp), %xmm0
	movb	$1, %al
	movq	stdout(%rip), %rdi
	leaq	.LC16(%rip), %rdx
	movl	$2, %esi
	call	__fprintf_chk@PLT
	movq	%rbx, %rdi
	call	free@PLT
	movq	40(%rsp), %rax
	subq	%fs:40, %rax
	je	.L40
	call	__stack_chk_fail@PLT
.L40:
	addq	$56, %rsp
	.cfi_def_cfa_offset 56
	xorl	%eax, %eax
	popq	%rbx
	.cfi_def_cfa_offset 48
	popq	%rbp
	.cfi_def_cfa_offset 40
	popq	%r12
	.cfi_def_cfa_offset 32
	popq	%r13
	.cfi_def_cfa_offset 24
	popq	%r14
	.cfi_def_cfa_offset 16
	popq	%r15
	.cfi_def_cfa_offset 8
	ret
	.cfi_endproc
.LFE2030:
	.size	main, .-main
	.section	.rodata.str1.1
.LC17:
	.string	"_Z11add_to_histP8PPMImagePf"
	.section	.text.startup
	.type	_ZL24__sti____cudaRegisterAllv, @function
_ZL24__sti____cudaRegisterAllv:
.LFB2058:
	.cfi_startproc
	endbr64
	pushq	%rax
	.cfi_def_cfa_offset 16
	leaq	_ZL15__fatDeviceText(%rip), %rdi
	call	__cudaRegisterFatBinary@PLT
	pushq	$0
	.cfi_def_cfa_offset 24
	xorl	%r9d, %r9d
	orl	$-1, %r8d
	pushq	$0
	.cfi_def_cfa_offset 32
	leaq	.LC17(%rip), %rdx
	movq	%rax, %rdi
	leaq	_Z11add_to_histP8PPMImagePf(%rip), %rsi
	pushq	$0
	.cfi_def_cfa_offset 40
	movq	%rdx, %rcx
	pushq	$0
	.cfi_def_cfa_offset 48
	movq	%rax, _ZL20__cudaFatCubinHandle(%rip)
	call	__cudaRegisterFunction@PLT
	movq	_ZL20__cudaFatCubinHandle(%rip), %rdi
	addq	$32, %rsp
	.cfi_def_cfa_offset 16
	call	__cudaRegisterFatBinaryEnd@PLT
	leaq	_ZL26__cudaUnregisterBinaryUtilv(%rip), %rdi
	popq	%rdx
	.cfi_def_cfa_offset 8
	jmp	atexit@PLT
	.cfi_endproc
.LFE2058:
	.size	_ZL24__sti____cudaRegisterAllv, .-_ZL24__sti____cudaRegisterAllv
	.section	.init_array,"aw"
	.align 8
	.quad	_ZL24__sti____cudaRegisterAllv
	.section	.nvFatBinSegment,"aw"
	.align 8
	.type	_ZL15__fatDeviceText, @object
	.size	_ZL15__fatDeviceText, 24
_ZL15__fatDeviceText:
	.long	1180844977
	.long	1
	.quad	fatbinData
	.quad	0
	.local	_ZL20__cudaFatCubinHandle
	.comm	_ZL20__cudaFatCubinHandle,8,8
	.section	.rodata.cst8,"aM",@progbits,8
	.align 8
.LC1:
	.long	-1598689907
	.long	1051772663
	.section	.rodata.cst4,"aM",@progbits,4
	.align 4
.LC2:
	.long	1031798784
	.ident	"GCC: (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0"
	.section	.note.GNU-stack,"",@progbits
	.section	.note.gnu.property,"a"
	.align 8
	.long	1f - 0f
	.long	4f - 1f
	.long	5
0:
	.string	"GNU"
1:
	.align 8
	.long	0xc0000002
	.long	3f - 2f
2:
	.long	0x3
3:
	.align 8
4:


#include <hip/hip_runtime.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <math.h>


#define COMMENT "Histogram_GPU"
#define RGB_COMPONENT_COLOR 255
#define HISTOGRAM_SIZE 64
#define TILE_WITDH 16

typedef struct {
    unsigned char red, green, blue;
} PPMPixel;

typedef struct {
    int x, y;
    PPMPixel *data;
} PPMImage;

double rtclock()
{
    struct timezone Tzp;
    struct timeval Tp;
    int stat;
    stat = gettimeofday (&Tp, &Tzp);
    if (stat != 0) printf("Error return from gettimeofday: %d",stat);
    return(Tp.tv_sec + Tp.tv_usec*1.0e-6);
}


static PPMImage *readPPM(const char *filename) {
    char buff[16];
    PPMImage *img;
    FILE *fp;
    int c, rgb_comp_color;
    fp = fopen(filename, "rb");
    if (!fp) {
        fprintf(stderr, "Unable to open file '%s'\n", filename);
        exit(1);
    }

    if (!fgets(buff, sizeof(buff), fp)) {
        perror(filename);
        exit(1);
    }

    if (buff[0] != 'P' || buff[1] != '6') {
        fprintf(stderr, "Invalid image format (must be 'P6')\n");
        exit(1);
    }

    img = (PPMImage *) malloc(sizeof(PPMImage));
    if (!img) {
        fprintf(stderr, "Unable to allocate memory\n");
        exit(1);
    }

    c = getc(fp);
    while (c == '#') {
        while (getc(fp) != '\n')
            ;
        c = getc(fp);
    }

    ungetc(c, fp);
    if (fscanf(fp, "%d %d", &img->x, &img->y) != 2) {
        fprintf(stderr, "Invalid image size (error loading '%s')\n", filename);
        exit(1);
    }

    if (fscanf(fp, "%d", &rgb_comp_color) != 1) {
        fprintf(stderr, "Invalid rgb component (error loading '%s')\n",
                filename);
        exit(1);
    }

    if (rgb_comp_color != RGB_COMPONENT_COLOR) {
        fprintf(stderr, "'%s' does not have 8-bits components\n", filename);
        exit(1);
    }

    while (fgetc(fp) != '\n')
        ;
    img->data = (PPMPixel*) malloc(img->x * img->y * sizeof(PPMPixel));

    if (!img) {
        fprintf(stderr, "Unable to allocate memory\n");
        exit(1);
    }

    if (fread(img->data, 3 * img->x, img->y, fp) != img->y) {
        fprintf(stderr, "Error loading image '%s'\n", filename);
        exit(1);
    }

    fclose(fp);
    return img;
}


__global__ void add_to_hist(PPMImage *d_image, float* hist) {
    __shared__ float private_hist[HISTOGRAM_SIZE];
    float size = d_image->y*d_image->x*1.0;


    if(threadIdx.x * TILE_WITDH + threadIdx.y < HISTOGRAM_SIZE) private_hist[threadIdx.x * TILE_WITDH + threadIdx.y] = 0;
    __syncthreads();

    // Get col
    int col = blockDim.x * blockIdx.x + threadIdx.x;
    // Get row
    int row = blockDim.y * blockIdx.y + threadIdx.y;
    // Get index
    int index = row * d_image->x + col;
    if((row < d_image->y && col < d_image->x) && (index < d_image->x*d_image->y)) {
        // Sum
        atomicAdd(&(private_hist[16*d_image->data[index].red + 4 * d_image->data[index].green + d_image->data[index].blue]), 1);

    }

    __syncthreads();
    if(threadIdx.x * TILE_WITDH + threadIdx.y < HISTOGRAM_SIZE) {
        atomicAdd(&(hist[threadIdx.x * TILE_WITDH + threadIdx.y]), (private_hist[threadIdx.x * TILE_WITDH + threadIdx.y]/size));
    }
}



void Histogram(PPMImage *image, float *h) {

    //Init variables;
    int i;
    unsigned int rows, cols, img_size;
    PPMImage *d_image;
    PPMPixel *d_pixels;
    float *d_hist;

    // CUDA TIMERS
    /*
    cudaEvent_t start, stop;
    cudaEventCreate(&start);
    cudaEventCreate(&stop);
    float tbuffer, tenviar, tk, treceber, ttotal;
    */

    // Get data
    cols = image->x;
    rows = image->y;
    img_size = cols * rows;

    //Preprocess data
    for (i = 0; i < img_size; i++) {
        image->data[i].red = floor((image->data[i].red * 4) / 256);
        image->data[i].blue = floor((image->data[i].blue * 4) / 256);
        image->data[i].green = floor((image->data[i].green * 4) / 256);
    }


    //cudaEventRecord(start);
    // Alloc structure to devise
    hipMalloc((void **)&d_image, sizeof(PPMImage));

    // Alloc image to devise
    hipMalloc((void **)&d_pixels, sizeof(PPMPixel) * img_size);

    //alloc histogram to devise
    hipMalloc((void **)&d_hist, HISTOGRAM_SIZE*sizeof(float));

    /*
    cudaEventRecord(stop);
    cudaEventSynchronize(stop);
    cudaEventElapsedTime(&tbuffer, start, stop);
    printf("Alloc Time: %f ", tbuffer);
    */


    //cudaEventRecord(start);
    // cpy stucture to devise
    hipMemcpy(d_image, image, sizeof(PPMImage), hipMemcpyHostToDevice);
    hipMemcpy(d_pixels, image->data, sizeof(PPMPixel) * img_size, hipMemcpyHostToDevice);
    hipMemcpy(&(d_image->data), &d_pixels, sizeof(PPMPixel *), hipMemcpyHostToDevice);

    // cpy histogram to devise
    hipMemcpy(d_hist, h, HISTOGRAM_SIZE*sizeof(float), hipMemcpyHostToDevice);
    /*
    cudaEventRecord(stop);
    cudaEventSynchronize(stop);
    cudaEventElapsedTime(&tenviar, start, stop);
    printf("copy Time: %f ", tenviar);
    */


    //Init dimGrid and dimBlocks
    //cudaEventRecord(start);
    dim3 dimGrid(ceil((float)cols / TILE_WITDH), ceil((float)rows / TILE_WITDH), 1);
    dim3 dimBlock(TILE_WITDH, TILE_WITDH, 1);

    // Call function
    add_to_hist<<<dimGrid, dimBlock>>>(d_image, d_hist);
    /*
    cudaEventRecord(stop);

    cudaEventSynchronize(stop);
    cudaEventElapsedTime(&tk, start, stop);
    printf("CUDA KERNEL: %f\n", tk);
    */


    //cudaEventRecord(start);
    // Copy result to local array
    hipMemcpy(h, d_hist, HISTOGRAM_SIZE*sizeof(float), hipMemcpyDeviceToHost);

    /*
    cudaEventRecord(stop);
    cudaEventSynchronize(stop);
    cudaEventElapsedTime(&treceber, start, stop);
    printf("receber Time: %f ", treceber);

    ttotal = tbuffer + tenviar + tk + treceber;
    printf("Total: %f\n", ttotal);
    */

    //Free memory
    hipFree(d_image);
    hipFree(d_pixels);
    hipFree(d_hist);
    /*
    cudaEventDestroy(start);
    cudaEventDestroy(stop);
    */
}

int main(int argc, char *argv[]) {

    if( argc != 2 ) {
        printf("Too many or no one arguments supplied.\n");
    }

    double t_start, t_end;
    int i;
    char *filename = argv[1];

    PPMImage *image = readPPM(filename);

    float *h = (float*)malloc(sizeof(float) * 64);

    //Inicializar h
    for(i=0; i < 64; i++) h[i] = 0.0;

    t_start = rtclock();
    Histogram(image, h);
    t_end = rtclock();

    for (i = 0; i < 64; i++){
        printf("%0.3f ", h[i]);
    }

    printf("\n");
    fprintf(stdout, "%0.6lf\n", t_end - t_start);
    free(h);

    return (0);
}



/*

ts = tempo_serial
tbuffer = tempo_GPU_criar_buffer
tenviar = tempo_GPU_offload_enviar
tk = tempo_kernel
treceber = tempo_GPU_offload_receber
ttotal = GPU_total
speedup = speedup (tempo_serial / GPU_total).


arqX |    ts      |   tbuffer  |   tenviar  |      tk    |  treceber   |  GPU_total   | speedup |
-------------------------------------------------------------------------------------------------
arq1 | 0.320540 s | 1.62240 ms | 0.80217 ms | 0.67052 ms |  0.02444 ms |  3.11955 ms  | 102.751 |
-------------------------------------------------------------------------------------------------
arq2 | 0.585691 s | 1.29168 ms | 1.07040 ms | 1.83283 ms |  0.02112 ms |  4.21603 ms  | 138.920 |
-------------------------------------------------------------------------------------------------
arq3 | 1.676812 s | 1.30262 ms | 3.99257 ms | 7.15699 ms |  0.02096 ms | 12.47315 ms  | 134.433 |
-------------------------------------------------------------------------------------------------


*/

	.text
	.file	"histogram.hip"
	.section	.rodata.cst8,"aM",@progbits,8
	.p2align	3, 0x0                          # -- Begin function _Z7rtclockv
.LCPI0_0:
	.quad	0x3eb0c6f7a0b5ed8d              # double 9.9999999999999995E-7
	.text
	.globl	_Z7rtclockv
	.type	_Z7rtclockv,@function
_Z7rtclockv:                            # @_Z7rtclockv
	.cfi_startproc
# %bb.0:
	subq	$24, %rsp
	.cfi_def_cfa_offset 32
	movq	%rsp, %rdi
	leaq	16(%rsp), %rsi
	callq	gettimeofday
	testl	%eax, %eax
	je	.LBB0_2
# %bb.1:
	movl	$.L.str, %edi
	movl	%eax, %esi
	xorl	%eax, %eax
	callq	printf
.LBB0_2:
	cvtsi2sdq	(%rsp), %xmm1
	cvtsi2sdq	8(%rsp), %xmm0
	mulsd	.LCPI0_0(%rip), %xmm0
	addsd	%xmm1, %xmm0
	addq	$24, %rsp
	.cfi_def_cfa_offset 8
	retq
.Lfunc_end0:
	.size	_Z7rtclockv, .Lfunc_end0-_Z7rtclockv
	.cfi_endproc
                                        # -- End function
	.globl	_Z26__device_stub__add_to_histP8PPMImagePf # -- Begin function _Z26__device_stub__add_to_histP8PPMImagePf
	.type	_Z26__device_stub__add_to_histP8PPMImagePf,@function
_Z26__device_stub__add_to_histP8PPMImagePf: # @_Z26__device_stub__add_to_histP8PPMImagePf
	.cfi_startproc
# %bb.0:
	pushq	%r15
	.cfi_def_cfa_offset 16
	pushq	%r14
	.cfi_def_cfa_offset 24
	pushq	%r13
	.cfi_def_cfa_offset 32
	pushq	%r12
	.cfi_def_cfa_offset 40
	pushq	%rbx
	.cfi_def_cfa_offset 48
	subq	$80, %rsp
	.cfi_def_cfa_offset 128
	.cfi_offset %rbx, -48
	.cfi_offset %r12, -40
	.cfi_offset %r13, -32
	.cfi_offset %r14, -24
	.cfi_offset %r15, -16
	leaq	24(%rsp), %rax
	movq	%rdi, (%rax)
	leaq	16(%rsp), %rcx
	movq	%rsi, (%rcx)
	leaq	64(%rsp), %rbx
	movq	%rax, (%rbx)
	movq	%rcx, 8(%rbx)
	leaq	48(%rsp), %r14
	leaq	32(%rsp), %r15
	leaq	8(%rsp), %r12
	movq	%rsp, %r13
	movq	%r14, %rdi
	movq	%r15, %rsi
	movq	%r12, %rdx
	movq	%r13, %rcx
	callq	__hipPopCallConfiguration
	movq	(%r14), %rsi
	movl	8(%r14), %edx
	movq	(%r15), %rcx
	movl	8(%r15), %r8d
	movl	$_Z11add_to_histP8PPMImagePf, %edi
	movq	%rbx, %r9
	pushq	(%r13)
	.cfi_adjust_cfa_offset 8
	pushq	(%r12)
	.cfi_adjust_cfa_offset 8
	callq	hipLaunchKernel
	addq	$96, %rsp
	.cfi_adjust_cfa_offset -96
	popq	%rbx
	.cfi_def_cfa_offset 40
	popq	%r12
	.cfi_def_cfa_offset 32
	popq	%r13
	.cfi_def_cfa_offset 24
	popq	%r14
	.cfi_def_cfa_offset 16
	popq	%r15
	.cfi_def_cfa_offset 8
	retq
.Lfunc_end1:
	.size	_Z26__device_stub__add_to_histP8PPMImagePf, .Lfunc_end1-_Z26__device_stub__add_to_histP8PPMImagePf
	.cfi_endproc
                                        # -- End function
	.section	.rodata.cst4,"aM",@progbits,4
	.p2align	2, 0x0                          # -- Begin function _Z9HistogramP8PPMImagePf
.LCPI2_0:
	.long	0x3d800000                      # float 0.0625
	.text
	.globl	_Z9HistogramP8PPMImagePf
	.type	_Z9HistogramP8PPMImagePf,@function
_Z9HistogramP8PPMImagePf:               # @_Z9HistogramP8PPMImagePf
	.cfi_startproc
# %bb.0:
	pushq	%rbp
	.cfi_def_cfa_offset 16
	pushq	%r15
	.cfi_def_cfa_offset 24
	pushq	%r14
	.cfi_def_cfa_offset 32
	pushq	%r13
	.cfi_def_cfa_offset 40
	pushq	%r12
	.cfi_def_cfa_offset 48
	pushq	%rbx
	.cfi_def_cfa_offset 56
	subq	$40, %rsp
	.cfi_def_cfa_offset 96
	.cfi_offset %rbx, -56
	.cfi_offset %r12, -48
	.cfi_offset %r13, -40
	.cfi_offset %r14, -32
	.cfi_offset %r15, -24
	.cfi_offset %rbp, -16
	movq	%rsi, 24(%rsp)                  # 8-byte Spill
	movq	%rdi, %r14
	movl	(%rdi), %ebx
	movl	4(%rdi), %ecx
	movl	%ecx, 12(%rsp)                  # 4-byte Spill
	imull	%ebx, %ecx
	testl	%ecx, %ecx
	je	.LBB2_1
# %bb.2:                                # %.lr.ph
	movq	8(%r14), %rax
	movl	%ecx, %ecx
	leaq	(%rcx,%rcx,2), %r15
	xorl	%ecx, %ecx
.LBB2_3:                                # =>This Inner Loop Header: Depth=1
	shrb	$6, (%rax,%rcx)
	shrb	$6, 2(%rax,%rcx)
	shrb	$6, 1(%rax,%rcx)
	addq	$3, %rcx
	cmpq	%rcx, %r15
	jne	.LBB2_3
	jmp	.LBB2_4
.LBB2_1:
	xorl	%r15d, %r15d
.LBB2_4:                                # %._crit_edge
	leaq	16(%rsp), %r12
	movl	$16, %esi
	movq	%r12, %rdi
	callq	hipMalloc
	leaq	32(%rsp), %r13
	movq	%r13, %rdi
	movq	%r15, %rsi
	callq	hipMalloc
	movq	%rsp, %rbp
	movl	$256, %esi                      # imm = 0x100
	movq	%rbp, %rdi
	callq	hipMalloc
	movq	(%r12), %rdi
	movl	$16, %edx
	movq	%r14, %rsi
	movl	$1, %ecx
	callq	hipMemcpy
	movq	(%r13), %rdi
	movq	8(%r14), %rsi
	movq	%r15, %rdx
	movl	$1, %ecx
	callq	hipMemcpy
	movq	(%r12), %rdi
	addq	$8, %rdi
	movl	$8, %edx
	movq	%r13, %rsi
	movl	$1, %ecx
	callq	hipMemcpy
	movq	(%rbp), %rdi
	movl	$256, %edx                      # imm = 0x100
	movq	24(%rsp), %r14                  # 8-byte Reload
	movq	%r14, %rsi
	movl	$1, %ecx
	callq	hipMemcpy
	movl	%ebx, %eax
	cvtsi2ss	%rax, %xmm0
	mulss	.LCPI2_0(%rip), %xmm0
	callq	ceilf@PLT
	cvttss2si	%xmm0, %rbx
	movl	12(%rsp), %eax                  # 4-byte Reload
	xorps	%xmm0, %xmm0
	cvtsi2ss	%rax, %xmm0
	mulss	.LCPI2_0(%rip), %xmm0
	callq	ceilf@PLT
	cvttss2si	%xmm0, %rdi
	movl	%ebx, %eax
	shlq	$32, %rdi
	orq	%rax, %rdi
	movabsq	$68719476752, %rdx              # imm = 0x1000000010
	movl	$1, %esi
	movl	$1, %ecx
	xorl	%r8d, %r8d
	xorl	%r9d, %r9d
	callq	__hipPushCallConfiguration
	testl	%eax, %eax
	jne	.LBB2_6
# %bb.5:
	movq	16(%rsp), %rdi
	movq	(%rsp), %rsi
	callq	_Z26__device_stub__add_to_histP8PPMImagePf
.LBB2_6:
	movq	(%rsp), %rsi
	movl	$256, %edx                      # imm = 0x100
	movq	%r14, %rdi
	movl	$2, %ecx
	callq	hipMemcpy
	movq	16(%rsp), %rdi
	callq	hipFree
	movq	32(%rsp), %rdi
	callq	hipFree
	movq	(%rsp), %rdi
	callq	hipFree
	addq	$40, %rsp
	.cfi_def_cfa_offset 56
	popq	%rbx
	.cfi_def_cfa_offset 48
	popq	%r12
	.cfi_def_cfa_offset 40
	popq	%r13
	.cfi_def_cfa_offset 32
	popq	%r14
	.cfi_def_cfa_offset 24
	popq	%r15
	.cfi_def_cfa_offset 16
	popq	%rbp
	.cfi_def_cfa_offset 8
	retq
.Lfunc_end2:
	.size	_Z9HistogramP8PPMImagePf, .Lfunc_end2-_Z9HistogramP8PPMImagePf
	.cfi_endproc
                                        # -- End function
	.globl	main                            # -- Begin function main
	.type	main,@function
main:                                   # @main
	.cfi_startproc
# %bb.0:
	pushq	%r15
	.cfi_def_cfa_offset 16
	pushq	%r14
	.cfi_def_cfa_offset 24
	pushq	%r13
	.cfi_def_cfa_offset 32
	pushq	%r12
	.cfi_def_cfa_offset 40
	pushq	%rbx
	.cfi_def_cfa_offset 48
	subq	$48, %rsp
	.cfi_def_cfa_offset 96
	.cfi_offset %rbx, -48
	.cfi_offset %r12, -40
	.cfi_offset %r13, -32
	.cfi_offset %r14, -24
	.cfi_offset %r15, -16
	movq	%rsi, %rbx
	cmpl	$2, %edi
	je	.LBB3_2
# %bb.1:
	movl	$.Lstr, %edi
	callq	puts@PLT
.LBB3_2:
	movq	8(%rbx), %rbx
	movl	$.L.str.5, %esi
	movq	%rbx, %rdi
	callq	fopen
	testq	%rax, %rax
	je	.LBB3_18
# %bb.3:
	movq	%rax, %r14
	leaq	32(%rsp), %rdi
	movl	$16, %esi
	movq	%rax, %rdx
	callq	fgets
	testq	%rax, %rax
	je	.LBB3_19
# %bb.4:
	cmpb	$80, 32(%rsp)
	jne	.LBB3_20
# %bb.5:
	cmpb	$54, 33(%rsp)
	jne	.LBB3_20
# %bb.6:
	movl	$16, %edi
	callq	malloc
	testq	%rax, %rax
	je	.LBB3_21
# %bb.7:
	movq	%rax, %r15
.LBB3_8:                                # =>This Loop Header: Depth=1
                                        #     Child Loop BB3_9 Depth 2
	movq	%r14, %rdi
	callq	getc
	cmpl	$35, %eax
	jne	.LBB3_10
.LBB3_9:                                # %.preheader44.i
                                        #   Parent Loop BB3_8 Depth=1
                                        # =>  This Inner Loop Header: Depth=2
	movq	%r14, %rdi
	callq	getc
	cmpl	$10, %eax
	jne	.LBB3_9
	jmp	.LBB3_8
.LBB3_10:                               # %._crit_edge.i
	movl	%eax, %edi
	movq	%r14, %rsi
	callq	ungetc
	movq	%r15, %rcx
	addq	$4, %rcx
	movl	$.L.str.9, %esi
	movq	%r14, %rdi
	movq	%r15, %rdx
	xorl	%eax, %eax
	callq	__isoc23_fscanf
	cmpl	$2, %eax
	jne	.LBB3_24
# %bb.11:
	leaq	12(%rsp), %rdx
	movl	$.L.str.11, %esi
	movq	%r14, %rdi
	xorl	%eax, %eax
	callq	__isoc23_fscanf
	cmpl	$1, %eax
	jne	.LBB3_25
# %bb.12:
	cmpl	$255, 12(%rsp)
	jne	.LBB3_26
.LBB3_13:                               # %.preheader.i
                                        # =>This Inner Loop Header: Depth=1
	movq	%r14, %rdi
	callq	fgetc
	cmpl	$10, %eax
	jne	.LBB3_13
# %bb.14:
	movslq	(%r15), %rax
	movslq	4(%r15), %r12
	leaq	(%rax,%rax,2), %r13
	movq	%r13, %rdi
	imulq	%r12, %rdi
	callq	malloc
	movq	%rax, 8(%r15)
	movq	%rax, %rdi
	movq	%r13, %rsi
	movq	%r12, %rdx
	movq	%r14, %rcx
	callq	fread
	movslq	4(%r15), %rcx
	cmpq	%rcx, %rax
	jne	.LBB3_27
# %bb.15:                               # %_ZL7readPPMPKc.exit
	movq	%r14, %rdi
	callq	fclose
	movl	$1, %edi
	movl	$256, %esi                      # imm = 0x100
	callq	calloc@PLT
	movq	%rax, %rbx
	callq	_Z7rtclockv
	movsd	%xmm0, 24(%rsp)                 # 8-byte Spill
	movq	%r15, %rdi
	movq	%rbx, %rsi
	callq	_Z9HistogramP8PPMImagePf
	xorl	%r14d, %r14d
	callq	_Z7rtclockv
	movsd	%xmm0, 16(%rsp)                 # 8-byte Spill
.LBB3_16:                               # =>This Inner Loop Header: Depth=1
	xorps	%xmm0, %xmm0
	cvtss2sd	(%rbx,%r14,4), %xmm0
	movl	$.L.str.2, %edi
	movb	$1, %al
	callq	printf
	incq	%r14
	cmpq	$64, %r14
	jne	.LBB3_16
# %bb.17:
	movl	$10, %edi
	callq	putchar@PLT
	movq	stdout(%rip), %rdi
	movsd	16(%rsp), %xmm0                 # 8-byte Reload
                                        # xmm0 = mem[0],zero
	subsd	24(%rsp), %xmm0                 # 8-byte Folded Reload
	movl	$.L.str.4, %esi
	movb	$1, %al
	callq	fprintf
	movq	%rbx, %rdi
	callq	free
	xorl	%eax, %eax
	addq	$48, %rsp
	.cfi_def_cfa_offset 48
	popq	%rbx
	.cfi_def_cfa_offset 40
	popq	%r12
	.cfi_def_cfa_offset 32
	popq	%r13
	.cfi_def_cfa_offset 24
	popq	%r14
	.cfi_def_cfa_offset 16
	popq	%r15
	.cfi_def_cfa_offset 8
	retq
.LBB3_18:
	.cfi_def_cfa_offset 96
	movq	stderr(%rip), %rdi
	movl	$.L.str.6, %esi
	jmp	.LBB3_28
.LBB3_19:
	movq	%rbx, %rdi
	callq	perror
	jmp	.LBB3_23
.LBB3_20:
	movq	stderr(%rip), %rcx
	movl	$.L.str.7, %edi
	movl	$36, %esi
	jmp	.LBB3_22
.LBB3_21:
	movq	stderr(%rip), %rcx
	movl	$.L.str.8, %edi
	movl	$26, %esi
.LBB3_22:
	movl	$1, %edx
	callq	fwrite@PLT
	jmp	.LBB3_23
.LBB3_24:
	movq	stderr(%rip), %rdi
	movl	$.L.str.10, %esi
	jmp	.LBB3_28
.LBB3_25:
	movq	stderr(%rip), %rdi
	movl	$.L.str.12, %esi
	jmp	.LBB3_28
.LBB3_26:
	movq	stderr(%rip), %rdi
	movl	$.L.str.13, %esi
	jmp	.LBB3_28
.LBB3_27:
	movq	stderr(%rip), %rdi
	movl	$.L.str.14, %esi
.LBB3_28:
	movq	%rbx, %rdx
	xorl	%eax, %eax
	callq	fprintf
.LBB3_23:
	movl	$1, %edi
	callq	exit
.Lfunc_end3:
	.size	main, .Lfunc_end3-main
	.cfi_endproc
                                        # -- End function
	.p2align	4, 0x90                         # -- Begin function __hip_module_ctor
	.type	__hip_module_ctor,@function
__hip_module_ctor:                      # @__hip_module_ctor
	.cfi_startproc
# %bb.0:
	subq	$40, %rsp
	.cfi_def_cfa_offset 48
	movq	__hip_gpubin_handle(%rip), %rdi
	testq	%rdi, %rdi
	jne	.LBB4_2
# %bb.1:
	movl	$__hip_fatbin_wrapper, %edi
	callq	__hipRegisterFatBinary
	movq	%rax, %rdi
	movq	%rax, __hip_gpubin_handle(%rip)
.LBB4_2:
	xorps	%xmm0, %xmm0
	movups	%xmm0, 16(%rsp)
	movups	%xmm0, (%rsp)
	movl	$_Z11add_to_histP8PPMImagePf, %esi
	movl	$.L__unnamed_1, %edx
	movl	$.L__unnamed_1, %ecx
	movl	$-1, %r8d
	xorl	%r9d, %r9d
	callq	__hipRegisterFunction
	movl	$__hip_module_dtor, %edi
	addq	$40, %rsp
	.cfi_def_cfa_offset 8
	jmp	atexit                          # TAILCALL
.Lfunc_end4:
	.size	__hip_module_ctor, .Lfunc_end4-__hip_module_ctor
	.cfi_endproc
                                        # -- End function
	.p2align	4, 0x90                         # -- Begin function __hip_module_dtor
	.type	__hip_module_dtor,@function
__hip_module_dtor:                      # @__hip_module_dtor
	.cfi_startproc
# %bb.0:
	movq	__hip_gpubin_handle(%rip), %rdi
	testq	%rdi, %rdi
	je	.LBB5_2
# %bb.1:
	pushq	%rax
	.cfi_def_cfa_offset 16
	callq	__hipUnregisterFatBinary
	movq	$0, __hip_gpubin_handle(%rip)
	addq	$8, %rsp
	.cfi_def_cfa_offset 8
.LBB5_2:
	retq
.Lfunc_end5:
	.size	__hip_module_dtor, .Lfunc_end5-__hip_module_dtor
	.cfi_endproc
                                        # -- End function
	.type	.L.str,@object                  # @.str
	.section	.rodata.str1.1,"aMS",@progbits,1
.L.str:
	.asciz	"Error return from gettimeofday: %d"
	.size	.L.str, 35

	.type	_Z11add_to_histP8PPMImagePf,@object # @_Z11add_to_histP8PPMImagePf
	.section	.rodata,"a",@progbits
	.globl	_Z11add_to_histP8PPMImagePf
	.p2align	3, 0x0
_Z11add_to_histP8PPMImagePf:
	.quad	_Z26__device_stub__add_to_histP8PPMImagePf
	.size	_Z11add_to_histP8PPMImagePf, 8

	.type	.L.str.2,@object                # @.str.2
	.section	.rodata.str1.1,"aMS",@progbits,1
.L.str.2:
	.asciz	"%0.3f "
	.size	.L.str.2, 7

	.type	.L.str.4,@object                # @.str.4
.L.str.4:
	.asciz	"%0.6lf\n"
	.size	.L.str.4, 8

	.type	.L.str.5,@object                # @.str.5
.L.str.5:
	.asciz	"rb"
	.size	.L.str.5, 3

	.type	.L.str.6,@object                # @.str.6
.L.str.6:
	.asciz	"Unable to open file '%s'\n"
	.size	.L.str.6, 26

	.type	.L.str.7,@object                # @.str.7
.L.str.7:
	.asciz	"Invalid image format (must be 'P6')\n"
	.size	.L.str.7, 37

	.type	.L.str.8,@object                # @.str.8
.L.str.8:
	.asciz	"Unable to allocate memory\n"
	.size	.L.str.8, 27

	.type	.L.str.9,@object                # @.str.9
.L.str.9:
	.asciz	"%d %d"
	.size	.L.str.9, 6

	.type	.L.str.10,@object               # @.str.10
.L.str.10:
	.asciz	"Invalid image size (error loading '%s')\n"
	.size	.L.str.10, 41

	.type	.L.str.11,@object               # @.str.11
.L.str.11:
	.asciz	"%d"
	.size	.L.str.11, 3

	.type	.L.str.12,@object               # @.str.12
.L.str.12:
	.asciz	"Invalid rgb component (error loading '%s')\n"
	.size	.L.str.12, 44

	.type	.L.str.13,@object               # @.str.13
.L.str.13:
	.asciz	"'%s' does not have 8-bits components\n"
	.size	.L.str.13, 38

	.type	.L.str.14,@object               # @.str.14
.L.str.14:
	.asciz	"Error loading image '%s'\n"
	.size	.L.str.14, 26

	.type	.L__unnamed_1,@object           # @0
.L__unnamed_1:
	.asciz	"_Z11add_to_histP8PPMImagePf"
	.size	.L__unnamed_1, 28

	.type	__hip_fatbin_wrapper,@object    # @__hip_fatbin_wrapper
	.section	.hipFatBinSegment,"a",@progbits
	.p2align	3, 0x0
__hip_fatbin_wrapper:
	.long	1212764230                      # 0x48495046
	.long	1                               # 0x1
	.quad	__hip_fatbin
	.quad	0
	.size	__hip_fatbin_wrapper, 24

	.type	__hip_gpubin_handle,@object     # @__hip_gpubin_handle
	.local	__hip_gpubin_handle
	.comm	__hip_gpubin_handle,8,8
	.section	.init_array,"aw",@init_array
	.p2align	3, 0x0
	.quad	__hip_module_ctor
	.type	__hip_cuid_,@object             # @__hip_cuid_
	.bss
	.globl	__hip_cuid_
__hip_cuid_:
	.byte	0                               # 0x0
	.size	__hip_cuid_, 1

	.type	.Lstr,@object                   # @str
	.section	.rodata.str1.1,"aMS",@progbits,1
.Lstr:
	.asciz	"Too many or no one arguments supplied."
	.size	.Lstr, 39

	.ident	"AMD clang version 18.0.0git (https://github.com/RadeonOpenCompute/llvm-project roc-6.3.2 25012 e5bf7e55c91490b07c49d8960fa7983d864936c4)"
	.section	".note.GNU-stack","",@progbits
	.addrsig
	.addrsig_sym _Z26__device_stub__add_to_histP8PPMImagePf
	.addrsig_sym __hip_module_ctor
	.addrsig_sym __hip_module_dtor
	.addrsig_sym _Z11add_to_histP8PPMImagePf
	.addrsig_sym __hip_fatbin
	.addrsig_sym __hip_fatbin_wrapper
	.addrsig_sym __hip_cuid_

	.text
	.amdgcn_target "amdgcn-amd-amdhsa--gfx1100"
	.protected	_Z11add_to_histP8PPMImagePf ; -- Begin function _Z11add_to_histP8PPMImagePf
	.globl	_Z11add_to_histP8PPMImagePf
	.p2align	8
	.type	_Z11add_to_histP8PPMImagePf,@function
_Z11add_to_histP8PPMImagePf:            ; @_Z11add_to_histP8PPMImagePf
; %bb.0:
	s_load_b128 s[4:7], s[0:1], 0x0
	v_and_b32_e32 v1, 0x3ff, v0
	v_bfe_u32 v0, v0, 10, 10
	s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(VALU_DEP_1)
	v_lshl_add_u32 v2, v1, 4, v0
	v_cmp_gt_u32_e32 vcc_lo, 64, v2
	v_lshlrev_b32_e32 v2, 2, v2
	s_and_saveexec_b32 s2, vcc_lo
	s_cbranch_execz .LBB0_2
; %bb.1:
	v_mov_b32_e32 v3, 0
	ds_store_b32 v2, v3
.LBB0_2:
	s_or_b32 exec_lo, exec_lo, s2
	s_waitcnt lgkmcnt(0)
	s_load_b64 s[8:9], s[4:5], 0x0
	s_waitcnt lgkmcnt(0)
	s_barrier
	buffer_gl0_inv
	s_load_b32 s0, s[0:1], 0x1c
	s_load_b64 s[2:3], s[4:5], 0x0
	s_waitcnt lgkmcnt(0)
	s_lshr_b32 s1, s0, 16
	s_and_b32 s0, s0, 0xffff
	s_delay_alu instid0(SALU_CYCLE_1) | instskip(SKIP_1) | instid1(VALU_DEP_2)
	v_mad_u64_u32 v[3:4], null, s14, s0, v[1:2]
	v_mad_u64_u32 v[4:5], null, s15, s1, v[0:1]
	v_cmp_gt_i32_e64 s1, s2, v3
	s_delay_alu instid0(VALU_DEP_2) | instskip(SKIP_2) | instid1(VALU_DEP_1)
	v_mad_u64_u32 v[0:1], null, v4, s2, v[3:4]
	v_cmp_gt_i32_e64 s0, s3, v4
	s_mul_i32 s2, s3, s2
	s_and_b32 s0, s0, s1
	s_delay_alu instid0(VALU_DEP_2) | instskip(NEXT) | instid1(VALU_DEP_1)
	v_cmp_gt_i32_e64 s2, s2, v0
	s_and_b32 s1, s0, s2
	s_delay_alu instid0(SALU_CYCLE_1)
	s_and_saveexec_b32 s0, s1
	s_cbranch_execz .LBB0_4
; %bb.3:
	s_load_b64 s[2:3], s[4:5], 0x8
	s_waitcnt lgkmcnt(0)
	v_mad_i64_i32 v[3:4], null, v0, 3, s[2:3]
	s_clause 0x1
	global_load_u16 v0, v[3:4], off
	global_load_u8 v1, v[3:4], off offset:2
	s_waitcnt vmcnt(1)
	v_lshrrev_b32_e32 v3, 6, v0
	v_and_b32_e32 v0, 0xff, v0
	s_delay_alu instid0(VALU_DEP_2) | instskip(NEXT) | instid1(VALU_DEP_1)
	v_and_b32_e32 v3, 0x3fc, v3
	v_lshl_add_u32 v0, v0, 4, v3
	s_waitcnt vmcnt(0)
	s_delay_alu instid0(VALU_DEP_1)
	v_add_lshl_u32 v0, v0, v1, 2
	v_mov_b32_e32 v1, 1.0
	ds_add_f32 v0, v1
.LBB0_4:
	s_or_b32 exec_lo, exec_lo, s0
	s_waitcnt lgkmcnt(0)
	s_barrier
	buffer_gl0_inv
	s_and_saveexec_b32 s0, vcc_lo
	s_cbranch_execz .LBB0_7
; %bb.5:
	global_load_b32 v1, v2, s[6:7]
	ds_load_b32 v0, v2
	s_mul_i32 s0, s8, s9
	s_delay_alu instid0(SALU_CYCLE_1) | instskip(SKIP_2) | instid1(VALU_DEP_2)
	v_cvt_f32_i32_e32 v4, s0
	v_add_co_u32 v2, s0, s6, v2
	s_waitcnt lgkmcnt(0)
	v_div_scale_f32 v3, null, v4, v4, v0
	s_delay_alu instid0(VALU_DEP_1) | instskip(SKIP_2) | instid1(VALU_DEP_1)
	v_rcp_f32_e32 v5, v3
	s_waitcnt_depctr 0xfff
	v_fma_f32 v6, -v3, v5, 1.0
	v_fmac_f32_e32 v5, v6, v5
	v_div_scale_f32 v6, vcc_lo, v0, v4, v0
	s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(VALU_DEP_1)
	v_mul_f32_e32 v7, v6, v5
	v_fma_f32 v8, -v3, v7, v6
	s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(VALU_DEP_1)
	v_fmac_f32_e32 v7, v8, v5
	v_fma_f32 v3, -v3, v7, v6
	s_delay_alu instid0(VALU_DEP_1) | instskip(SKIP_2) | instid1(VALU_DEP_2)
	v_div_fmas_f32 v5, v3, v5, v7
	v_add_co_ci_u32_e64 v3, null, s7, 0, s0
	s_mov_b32 s0, 0
	v_div_fixup_f32 v4, v5, v4, v0
.LBB0_6:                                ; %atomicrmw.start
                                        ; =>This Inner Loop Header: Depth=1
	s_waitcnt vmcnt(0)
	s_delay_alu instid0(VALU_DEP_1)
	v_add_f32_e32 v0, v1, v4
	global_atomic_cmpswap_b32 v0, v[2:3], v[0:1], off glc
	s_waitcnt vmcnt(0)
	v_cmp_eq_u32_e32 vcc_lo, v0, v1
	v_mov_b32_e32 v1, v0
	s_or_b32 s0, vcc_lo, s0
	s_delay_alu instid0(SALU_CYCLE_1)
	s_and_not1_b32 exec_lo, exec_lo, s0
	s_cbranch_execnz .LBB0_6
.LBB0_7:
	s_endpgm
	.section	.rodata,"a",@progbits
	.p2align	6, 0x0
	.amdhsa_kernel _Z11add_to_histP8PPMImagePf
		.amdhsa_group_segment_fixed_size 256
		.amdhsa_private_segment_fixed_size 0
		.amdhsa_kernarg_size 272
		.amdhsa_user_sgpr_count 14
		.amdhsa_user_sgpr_dispatch_ptr 0
		.amdhsa_user_sgpr_queue_ptr 0
		.amdhsa_user_sgpr_kernarg_segment_ptr 1
		.amdhsa_user_sgpr_dispatch_id 0
		.amdhsa_user_sgpr_private_segment_size 0
		.amdhsa_wavefront_size32 1
		.amdhsa_uses_dynamic_stack 0
		.amdhsa_enable_private_segment 0
		.amdhsa_system_sgpr_workgroup_id_x 1
		.amdhsa_system_sgpr_workgroup_id_y 1
		.amdhsa_system_sgpr_workgroup_id_z 0
		.amdhsa_system_sgpr_workgroup_info 0
		.amdhsa_system_vgpr_workitem_id 1
		.amdhsa_next_free_vgpr 9
		.amdhsa_next_free_sgpr 16
		.amdhsa_float_round_mode_32 0
		.amdhsa_float_round_mode_16_64 0
		.amdhsa_float_denorm_mode_32 3
		.amdhsa_float_denorm_mode_16_64 3
		.amdhsa_dx10_clamp 1
		.amdhsa_ieee_mode 1
		.amdhsa_fp16_overflow 0
		.amdhsa_workgroup_processor_mode 1
		.amdhsa_memory_ordered 1
		.amdhsa_forward_progress 0
		.amdhsa_shared_vgpr_count 0
		.amdhsa_exception_fp_ieee_invalid_op 0
		.amdhsa_exception_fp_denorm_src 0
		.amdhsa_exception_fp_ieee_div_zero 0
		.amdhsa_exception_fp_ieee_overflow 0
		.amdhsa_exception_fp_ieee_underflow 0
		.amdhsa_exception_fp_ieee_inexact 0
		.amdhsa_exception_int_div_zero 0
	.end_amdhsa_kernel
	.text
.Lfunc_end0:
	.size	_Z11add_to_histP8PPMImagePf, .Lfunc_end0-_Z11add_to_histP8PPMImagePf
                                        ; -- End function
	.section	.AMDGPU.csdata,"",@progbits
; Kernel info:
; codeLenInByte = 540
; NumSgprs: 18
; NumVgprs: 9
; ScratchSize: 0
; MemoryBound: 0
; FloatMode: 240
; IeeeMode: 1
; LDSByteSize: 256 bytes/workgroup (compile time only)
; SGPRBlocks: 2
; VGPRBlocks: 1
; NumSGPRsForWavesPerEU: 18
; NumVGPRsForWavesPerEU: 9
; Occupancy: 16
; WaveLimiterHint : 1
; COMPUTE_PGM_RSRC2:SCRATCH_EN: 0
; COMPUTE_PGM_RSRC2:USER_SGPR: 14
; COMPUTE_PGM_RSRC2:TRAP_HANDLER: 0
; COMPUTE_PGM_RSRC2:TGID_X_EN: 1
; COMPUTE_PGM_RSRC2:TGID_Y_EN: 1
; COMPUTE_PGM_RSRC2:TGID_Z_EN: 0
; COMPUTE_PGM_RSRC2:TIDIG_COMP_CNT: 1
	.text
	.p2alignl 7, 3214868480
	.fill 96, 4, 3214868480
	.type	__hip_cuid_,@object             ; @__hip_cuid_
	.section	.bss,"aw",@nobits
	.globl	__hip_cuid_
__hip_cuid_:
	.byte	0                               ; 0x0
	.size	__hip_cuid_, 1

	.ident	"AMD clang version 18.0.0git (https://github.com/RadeonOpenCompute/llvm-project roc-6.3.2 25012 e5bf7e55c91490b07c49d8960fa7983d864936c4)"
	.section	".note.GNU-stack","",@progbits
	.addrsig
	.addrsig_sym __hip_cuid_
	.amdgpu_metadata
---
amdhsa.kernels:
  - .args:
      - .address_space:  global
        .offset:         0
        .size:           8
        .value_kind:     global_buffer
      - .address_space:  global
        .offset:         8
        .size:           8
        .value_kind:     global_buffer
      - .offset:         16
        .size:           4
        .value_kind:     hidden_block_count_x
      - .offset:         20
        .size:           4
        .value_kind:     hidden_block_count_y
      - .offset:         24
        .size:           4
        .value_kind:     hidden_block_count_z
      - .offset:         28
        .size:           2
        .value_kind:     hidden_group_size_x
      - .offset:         30
        .size:           2
        .value_kind:     hidden_group_size_y
      - .offset:         32
        .size:           2
        .value_kind:     hidden_group_size_z
      - .offset:         34
        .size:           2
        .value_kind:     hidden_remainder_x
      - .offset:         36
        .size:           2
        .value_kind:     hidden_remainder_y
      - .offset:         38
        .size:           2
        .value_kind:     hidden_remainder_z
      - .offset:         56
        .size:           8
        .value_kind:     hidden_global_offset_x
      - .offset:         64
        .size:           8
        .value_kind:     hidden_global_offset_y
      - .offset:         72
        .size:           8
        .value_kind:     hidden_global_offset_z
      - .offset:         80
        .size:           2
        .value_kind:     hidden_grid_dims
    .group_segment_fixed_size: 256
    .kernarg_segment_align: 8
    .kernarg_segment_size: 272
    .language:       OpenCL C
    .language_version:
      - 2
      - 0
    .max_flat_workgroup_size: 1024
    .name:           _Z11add_to_histP8PPMImagePf
    .private_segment_fixed_size: 0
    .sgpr_count:     18
    .sgpr_spill_count: 0
    .symbol:         _Z11add_to_histP8PPMImagePf.kd
    .uniform_work_group_size: 1
    .uses_dynamic_stack: false
    .vgpr_count:     9
    .vgpr_spill_count: 0
    .wavefront_size: 32
    .workgroup_processor_mode: 1
amdhsa.target:   amdgcn-amd-amdhsa--gfx1100
amdhsa.version:
  - 1
  - 2
...

	.end_amdgpu_metadata
