#include "cuda.h" /* CUDA runtime API */
#include "cstdio"
#include "math.h"
#include <sys/time.h>


/*****************************************************************************/
/***                      local definition                        ************/
/*****************************************************************************/
#define    MAX_NUMBER            (1000000000)
#define    NEEDED_PRIME_NUM      (5)

/* Make sure the following definition satisfy the condition:
** (CPU_CALC_END * CPU_CALC_END) > MAX_NUMBER
** CPU runs the sieve arithmetic for the range [2, CPU_CALC_END)
** and GPU runs the remain part [CPU_CALC_END, MAX_NUMBER]    */
#define    CPU_CALC_END          (32000)
#define    BLOCK_SIZE            (512)


typedef struct
{
    int smallPrime;
    int largePrime;
    int distance;
} primeInfo;

/*****************************************************************************/
/***                    Static Databases/Variables                       *****/
/*****************************************************************************/
/* The biggest NEEDED_PRIME_NUM distances between continuous prime number in
** sorted list. The largest distance will be saved at the first one
** primeList[0]. Here, one more item is defined for simplify the calculation
** in loop.                                                                  */
primeInfo primeList[NEEDED_PRIME_NUM+1];
/* The number of found prime number. Range: 0 ~ NEEDED_PRIME_NUM */
int foundPrimeNum;


/* Function insertNewDistance(int distance, int smallerPrime, int largePrime)
*******************************************************************************
* Function description: getPrimeCUDA() is used to insert the found new large
* distance.
*
* Inputs:
*   distance: the new distance between smaller prime and larger prime
*   smallerPrime: small prime
*   largerPrime: large prime
*
* Output:
*   Save the data to array primeList[] and update variable 'foundPrimeNum'
*
* Return:
*   None
*
******************************************************************************/
void insertNewDistance(int distance, int smallPrime, int largePrime)
{
    int j;

    for (j=foundPrimeNum; j>=0; j--)
    {
        /* Save the new result to the sorted place */
        /* Note: 6 items are defined in array primeList to avoid overrun */
        if ( (0 == j) || (distance <= primeList[j - 1].distance))
        {
            primeList[j].smallPrime = smallPrime;
            primeList[j].largePrime = largePrime;
            primeList[j].distance = distance;
            break;
        }
        else if (NEEDED_PRIME_NUM != j)
        {
            /* Move the item */
            primeList[j].smallPrime = primeList[j-1].smallPrime;
            primeList[j].largePrime = primeList[j-1].largePrime;
            primeList[j].distance = primeList[j-1].distance;
        }
    }

    /* Maximum 5 largest distances are kept. Update the number of distances */
    if (foundPrimeNum < NEEDED_PRIME_NUM)
    {
        foundPrimeNum++;
    }
}

/* Function getPrimeCUDA()
*******************************************************************************
* Function description: getPrimeCUDA() is used to find out all the primes.
*
* Inputs:
*   dev: the pointer to whole buffer in device [0, 1000000000]
*   prm: the array where the prime numbers in [2, CPU_CALC_END] found were save.
*   limit: the prime numbers found by CPU (cuda limit)
*
* Output:
*   The result is saved in the memory through pointer dev
*
* Return:
*   None
*
******************************************************************************/
__global__  void getPrimeCUDA(unsigned char* dev, int* prm, int limit)
{
    int j, k;
    int testPrime;
    int x;
    int start, end;
    int range;

    x = threadIdx.x;
    range = (MAX_NUMBER - CPU_CALC_END) / BLOCK_SIZE;

    start = CPU_CALC_END + range * x;
    end = start + range;

    if ((BLOCK_SIZE-1) == x)
    {
        end = MAX_NUMBER;
    }

    for (k=0; k<limit; k++)
    {
        testPrime = prm[k];

        j = start -(start % testPrime);

        if (j < start)
        {
            j += testPrime;
        }

        for (; j<end; j+=testPrime)
        {
            dev[j]=0;
        }
    }
}


int main()
{
    unsigned char* sieve;
    unsigned char* devA;
    /* Save the found prime and pass them to cuda. The length is estimated: 1-1/2-1/3 = 1/6 */
    int primeByCPU[CPU_CALC_END/6];
    int* devPrimes;

    int foundByCPU = 0;
    int i;
    int j;
    int totalSize;
    struct timeval  startTime; /* Record the start time */
    struct timeval  currentTime;  /* Record the current time */

    int recSmallDist = 0;           /* Smallest distance in the 5 recorded distance */
    int lastPrime = 2;               /* Record of last prime */
    int currDistance;

    /* Verify setting for searching primes between [2, MAX_NUMBER]. */
    if ((CPU_CALC_END * CPU_CALC_END) <= MAX_NUMBER)
    {
       printf("The CPU_CALC_END * CPU_CALC_END is too small.\n", CPU_CALC_END);

       j = 2;
       while ((j*j) < MAX_NUMBER)
       {
          j++;
       }
       printf("Please change definition of  from (%d) to value no less than (%d).\n", CPU_CALC_END, j);
       return 0;
    }

    totalSize = sizeof(unsigned char)*MAX_NUMBER;
    sieve = (unsigned char*)malloc(totalSize);

    /* allocate arrays on device */
    cudaMalloc((void **) &devA, totalSize);

    for (i=2; i<MAX_NUMBER; i++)
    {
        sieve[i]=1; //initialize
    }

    gettimeofday(&startTime, NULL);

    for (i=2; i<CPU_CALC_END; i++)
    {
        if(0 == sieve[i])
        {
            continue;
        }

        for (j=i+i;j<CPU_CALC_END;j=j+i)
        {
            sieve[j]=0;
        }

        primeByCPU[foundByCPU++] = i;

        currDistance = i - lastPrime;

        /* The current distance is larger than the smallest record distance. Save it. */
        if (currDistance >= recSmallDist)
        {
            insertNewDistance(currDistance, lastPrime, i);

            /* Update the current smallest distance */
            recSmallDist = primeList[foundPrimeNum - 1].distance;
        }

        lastPrime = i;
    }
    gettimeofday(&currentTime, NULL);
    printf ("First time taken by CPU:  %f seconds\n",
             (double) (currentTime.tv_usec - startTime.tv_usec) / 1000000 +
             (double) (currentTime.tv_sec - startTime.tv_sec));

    /* allocate arrays on device */
    cudaMalloc((void **) &devPrimes, foundByCPU*sizeof(int));

    /* copy arrays to device memory (synchronous) */
    cudaMemcpy(devA, sieve, totalSize, cudaMemcpyHostToDevice);

    /* copy arrays to device memory (synchronous) */
    cudaMemcpy(devPrimes, primeByCPU, foundByCPU*sizeof(int), cudaMemcpyHostToDevice);
    /* guarantee synchronization */
    cudaDeviceSynchronize();

    /* execute kernel (asynchronous!) */
    getPrimeCUDA<<<1, BLOCK_SIZE>>>(devA, devPrimes, foundByCPU);

    /* retrieve results from device (synchronous) */
    cudaMemcpy(&sieve[CPU_CALC_END], &devA[CPU_CALC_END], totalSize-CPU_CALC_END, cudaMemcpyDeviceToHost);

    /* guarantee synchronization */
    cudaDeviceSynchronize();

    for (i=CPU_CALC_END; i<MAX_NUMBER; i++)
    {
        if(sieve[i]==0)
        {
            continue;
        }

        currDistance = i - lastPrime;

        /* The current distance is larger than the smallest record distance. Save it. */
        if (currDistance >= recSmallDist)
        {
            insertNewDistance(currDistance, lastPrime, i);

            /* Update the current smallest distance */
            recSmallDist = primeList[foundPrimeNum - 1].distance;
        }

        lastPrime = i;
    }

    gettimeofday(&currentTime, NULL);
    printf("Largest prime number is %d. \n", lastPrime);
    printf("Now, print the 5 biggest distances between two continue prime numbers.\n");
    for(i=0;i<NEEDED_PRIME_NUM;i++)
    {
        printf("Between continue prime number (%d) and (%d), the distance is (%d). \n", primeList[i].smallPrime, primeList[i].largePrime, primeList[i].distance);
    }
    printf ("Total time taken by CPU:  %f seconds\n",
             (double) (currentTime.tv_usec - startTime.tv_usec) / 1000000 +
             (double) (currentTime.tv_sec - startTime.tv_sec));
    free(sieve);
    return 0;
}

	.file	"tmpxft_002e6c51_00000000-6_CP631_Final_cuda.cudafe1.cpp"
	.text
#APP

#NO_APP
	.type	_ZL26__cudaUnregisterBinaryUtilv, @function
_ZL26__cudaUnregisterBinaryUtilv:
.LFB2031:
	.cfi_startproc
	endbr64
	movq	_ZL20__cudaFatCubinHandle(%rip), %rdi
	jmp	__cudaUnregisterFatBinary@PLT
	.cfi_endproc
.LFE2031:
	.size	_ZL26__cudaUnregisterBinaryUtilv, .-_ZL26__cudaUnregisterBinaryUtilv
	.globl	_Z17insertNewDistanceiii
	.type	_Z17insertNewDistanceiii, @function
_Z17insertNewDistanceiii:
.LFB2027:
	.cfi_startproc
	endbr64
	movl	foundPrimeNum(%rip), %ecx
	testl	%ecx, %ecx
	js	.L22
	pushq	%rbx
	.cfi_def_cfa_offset 16
	.cfi_offset 3, -16
	movl	%edx, %r8d
	movslq	%ecx, %rax
	leaq	primeList(%rip), %r9
.L3:
	testl	%eax, %eax
	je	.L7
.L6:
	leal	-1(%rax), %r10d
	movslq	%r10d, %rdx
	imulq	$12, %rdx, %rdx
	addq	%r9, %rdx
	movl	8(%rdx), %r11d
	cmpl	%edi, %r11d
	jge	.L7
	cmpl	$5, %eax
	jne	.L23
	movl	$4, %eax
	jmp	.L6
.L23:
	imulq	$12, %rax, %rax
	movl	(%rdx), %ebx
	movl	4(%rdx), %edx
	addq	%r9, %rax
	movl	%ebx, (%rax)
	movl	%edx, 4(%rax)
	movl	%r11d, 8(%rax)
	movslq	%r10d, %rax
	jmp	.L3
.L7:
	imulq	$12, %rax, %rax
	addq	%r9, %rax
	movl	%esi, (%rax)
	movl	%r8d, 4(%rax)
	movl	%edi, 8(%rax)
	cmpl	$4, %ecx
	jg	.L2
	incl	%ecx
	movl	%ecx, foundPrimeNum(%rip)
.L2:
	popq	%rbx
	.cfi_def_cfa_offset 8
	ret
.L22:
	.cfi_restore 3
	cmpl	$4, %ecx
	jg	.L19
	incl	%ecx
	movl	%ecx, foundPrimeNum(%rip)
	ret
.L19:
	ret
	.cfi_endproc
.LFE2027:
	.size	_Z17insertNewDistanceiii, .-_Z17insertNewDistanceiii
	.globl	_Z35__device_stub__Z12getPrimeCUDAPhPiiPhPii
	.type	_Z35__device_stub__Z12getPrimeCUDAPhPiiPhPii, @function
_Z35__device_stub__Z12getPrimeCUDAPhPiiPhPii:
.LFB2053:
	.cfi_startproc
	endbr64
	subq	$136, %rsp
	.cfi_def_cfa_offset 144
	movq	%rdi, 24(%rsp)
	leaq	40(%rsp), %rcx
	leaq	48(%rsp), %rdi
	movq	%rsi, 16(%rsp)
	leaq	60(%rsp), %rsi
	movl	%edx, 12(%rsp)
	leaq	32(%rsp), %rdx
	movq	%fs:40, %rax
	movq	%rax, 120(%rsp)
	xorl	%eax, %eax
	leaq	24(%rsp), %rax
	movl	$1, 56(%rsp)
	movq	%rax, 96(%rsp)
	leaq	16(%rsp), %rax
	movq	%rax, 104(%rsp)
	leaq	12(%rsp), %rax
	movq	%rax, 112(%rsp)
	movabsq	$4294967297, %rax
	movq	%rax, 48(%rsp)
	movq	%rax, 60(%rsp)
	movl	$1, 68(%rsp)
	call	__cudaPopCallConfiguration@PLT
	testl	%eax, %eax
	jne	.L24
	pushq	40(%rsp)
	.cfi_def_cfa_offset 152
	leaq	_Z12getPrimeCUDAPhPii(%rip), %rdi
	pushq	40(%rsp)
	.cfi_def_cfa_offset 160
	movq	76(%rsp), %rcx
	movl	84(%rsp), %r8d
	movq	64(%rsp), %rsi
	movl	72(%rsp), %edx
	leaq	112(%rsp), %r9
	call	cudaLaunchKernel@PLT
	popq	%rax
	.cfi_def_cfa_offset 152
	popq	%rdx
	.cfi_def_cfa_offset 144
.L24:
	movq	120(%rsp), %rax
	subq	%fs:40, %rax
	je	.L26
	call	__stack_chk_fail@PLT
.L26:
	addq	$136, %rsp
	.cfi_def_cfa_offset 8
	ret
	.cfi_endproc
.LFE2053:
	.size	_Z35__device_stub__Z12getPrimeCUDAPhPiiPhPii, .-_Z35__device_stub__Z12getPrimeCUDAPhPiiPhPii
	.globl	_Z12getPrimeCUDAPhPii
	.type	_Z12getPrimeCUDAPhPii, @function
_Z12getPrimeCUDAPhPii:
.LFB2054:
	.cfi_startproc
	endbr64
	jmp	_Z35__device_stub__Z12getPrimeCUDAPhPiiPhPii
	.cfi_endproc
.LFE2054:
	.size	_Z12getPrimeCUDAPhPii, .-_Z12getPrimeCUDAPhPii
	.section	.rodata.str1.1,"aMS",@progbits,1
.LC1:
	.string	"First time taken by CPU:  %f seconds\n"
.LC2:
	.string	"Largest prime number is %d. \n"
.LC3:
	.string	"Now, print the 5 biggest distances between two continue prime numbers.\n"
.LC4:
	.string	"Between continue prime number (%d) and (%d), the distance is (%d). \n"
.LC5:
	.string	"Total time taken by CPU:  %f seconds\n"
	.section	.text.startup,"ax",@progbits
	.globl	main
	.type	main, @function
main:
.LFB2028:
	.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
	leaq	-20480(%rsp), %r11
	.cfi_def_cfa 11, 20536
.LPSRL0:
	subq	$4096, %rsp
	orq	$0, (%rsp)
	cmpq	%r11, %rsp
	jne	.LPSRL0
	.cfi_def_cfa_register 7
	subq	$968, %rsp
	.cfi_def_cfa_offset 21504
	movl	$1000000000, %edi
	movl	$2, %ebx
	xorl	%r13d, %r13d
	movl	$2, %r12d
	xorl	%r15d, %r15d
	movq	%fs:40, %rax
	movq	%rax, 21432(%rsp)
	xorl	%eax, %eax
	call	malloc@PLT
	leaq	24(%rsp), %rdi
	movl	$1000000000, %esi
	movq	%rax, %rbp
	call	cudaMalloc@PLT
	leaq	2(%rbp), %rdx
	movb	$1, %al
	movl	$999999998, %ecx
	movq	%rdx, %rdi
	xorl	%esi, %esi
	rep stosb
	leaq	64(%rsp), %rdi
	call	gettimeofday@PLT
.L33:
	cmpb	$0, 0(%rbp,%rbx)
	leaq	(%rbx,%rbx), %rax
	je	.L30
.L31:
	cmpl	$31999, %eax
	jg	.L45
	movb	$0, 0(%rbp,%rax)
	addq	%rbx, %rax
	jmp	.L31
.L45:
	movl	%ebx, %edi
	movslq	%r15d, %r10
	leal	1(%r15), %r14d
	movl	%ebx, %edx
	subl	%r12d, %edi
	movl	%ebx, 100(%rsp,%r10,4)
	cmpl	%r13d, %edi
	jl	.L39
	movl	%r12d, %esi
	call	_Z17insertNewDistanceiii
	movl	foundPrimeNum(%rip), %eax
	leaq	primeList(%rip), %rcx
	decl	%eax
	cltq
	imulq	$12, %rax, %rax
	movl	8(%rcx,%rax), %r13d
.L39:
	movl	%ebx, %r12d
	movl	%r14d, %r15d
.L30:
	incq	%rbx
	cmpq	$32000, %rbx
	jne	.L33
	leaq	80(%rsp), %rax
	xorl	%esi, %esi
	movslq	%r15d, %r14
	movq	%rax, %rdi
	movq	%rax, 8(%rsp)
	salq	$2, %r14
	call	gettimeofday@PLT
	movq	88(%rsp), %rax
	subq	72(%rsp), %rax
	leaq	.LC1(%rip), %rsi
	cvtsi2sdq	%rax, %xmm0
	movq	80(%rsp), %rax
	subq	64(%rsp), %rax
	divsd	.LC0(%rip), %xmm0
	cvtsi2sdq	%rax, %xmm1
	movl	$2, %edi
	movb	$1, %al
	addsd	%xmm1, %xmm0
	call	__printf_chk@PLT
	leaq	32(%rsp), %rdi
	movq	%r14, %rsi
	call	cudaMalloc@PLT
	movq	24(%rsp), %rdi
	movl	$1, %ecx
	movq	%rbp, %rsi
	movl	$1000000000, %edx
	call	cudaMemcpy@PLT
	movq	32(%rsp), %rdi
	leaq	100(%rsp), %rsi
	movq	%r14, %rdx
	movl	$1, %ecx
	call	cudaMemcpy@PLT
	call	cudaDeviceSynchronize@PLT
	movl	$8388609, %edx
	xorl	%r9d, %r9d
	xorl	%r8d, %r8d
	salq	$9, %rdx
	movl	$1, %ecx
	movl	$1, %esi
	movabsq	$4294967297, %rdi
	call	__cudaPushCallConfiguration@PLT
	testl	%eax, %eax
	jne	.L34
	movq	32(%rsp), %rsi
	movq	24(%rsp), %rdi
	movl	%r15d, %edx
	call	_Z35__device_stub__Z12getPrimeCUDAPhPiiPhPii
.L34:
	movq	24(%rsp), %rax
	movl	$2, %ecx
	leaq	32000(%rbp), %rdi
	movl	$999968000, %edx
	leaq	primeList(%rip), %r14
	leaq	32000(%rax), %rsi
	call	cudaMemcpy@PLT
	call	cudaDeviceSynchronize@PLT
.L36:
	cmpb	$0, 0(%rbp,%rbx)
	je	.L35
	movl	%ebx, %edi
	movl	%ebx, %edx
	subl	%r12d, %edi
	cmpl	%r13d, %edi
	jl	.L40
	movl	%r12d, %esi
	call	_Z17insertNewDistanceiii
	movl	foundPrimeNum(%rip), %eax
	decl	%eax
	cltq
	imulq	$12, %rax, %rax
	movl	8(%r14,%rax), %r13d
.L40:
	movl	%ebx, %r12d
.L35:
	incq	%rbx
	cmpq	$1000000000, %rbx
	jne	.L36
	movq	8(%rsp), %rdi
	xorl	%esi, %esi
	leaq	primeList(%rip), %rbx
	leaq	.LC4(%rip), %r13
	call	gettimeofday@PLT
	movl	%r12d, %edx
	movl	$2, %edi
	xorl	%eax, %eax
	leaq	.LC2(%rip), %rsi
	leaq	60(%rbx), %r12
	call	__printf_chk@PLT
	leaq	.LC3(%rip), %rsi
	movl	$2, %edi
	xorl	%eax, %eax
	call	__printf_chk@PLT
.L37:
	movl	4(%rbx), %ecx
	movl	8(%rbx), %r8d
	movq	%r13, %rsi
	movl	$2, %edi
	movl	(%rbx), %edx
	xorl	%eax, %eax
	addq	$12, %rbx
	call	__printf_chk@PLT
	cmpq	%rbx, %r12
	jne	.L37
	movq	88(%rsp), %rax
	subq	72(%rsp), %rax
	movl	$2, %edi
	leaq	.LC5(%rip), %rsi
	cvtsi2sdq	%rax, %xmm0
	movq	80(%rsp), %rax
	subq	64(%rsp), %rax
	divsd	.LC0(%rip), %xmm0
	cvtsi2sdq	%rax, %xmm1
	movb	$1, %al
	addsd	%xmm1, %xmm0
	call	__printf_chk@PLT
	movq	%rbp, %rdi
	call	free@PLT
	movq	21432(%rsp), %rax
	subq	%fs:40, %rax
	je	.L38
	call	__stack_chk_fail@PLT
.L38:
	addq	$21448, %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
.LFE2028:
	.size	main, .-main
	.section	.rodata.str1.1
.LC6:
	.string	"_Z12getPrimeCUDAPhPii"
	.section	.text.startup
	.type	_ZL24__sti____cudaRegisterAllv, @function
_ZL24__sti____cudaRegisterAllv:
.LFB2056:
	.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	.LC6(%rip), %rdx
	movq	%rax, %rdi
	leaq	_Z12getPrimeCUDAPhPii(%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
.LFE2056:
	.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
	.globl	foundPrimeNum
	.bss
	.align 4
	.type	foundPrimeNum, @object
	.size	foundPrimeNum, 4
foundPrimeNum:
	.zero	4
	.globl	primeList
	.align 32
	.type	primeList, @object
	.size	primeList, 72
primeList:
	.zero	72
	.section	.rodata.cst8,"aM",@progbits,8
	.align 8
.LC0:
	.long	0
	.long	1093567616
	.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" /* CUDA runtime API */
#include "cstdio"
#include "math.h"
#include <sys/time.h>


/*****************************************************************************/
/***                      local definition                        ************/
/*****************************************************************************/
#define    MAX_NUMBER            (1000000000)
#define    NEEDED_PRIME_NUM      (5)

/* Make sure the following definition satisfy the condition:
** (CPU_CALC_END * CPU_CALC_END) > MAX_NUMBER
** CPU runs the sieve arithmetic for the range [2, CPU_CALC_END)
** and GPU runs the remain part [CPU_CALC_END, MAX_NUMBER]    */
#define    CPU_CALC_END          (32000)
#define    BLOCK_SIZE            (512)


typedef struct
{
    int smallPrime;
    int largePrime;
    int distance;
} primeInfo;

/*****************************************************************************/
/***                    Static Databases/Variables                       *****/
/*****************************************************************************/
/* The biggest NEEDED_PRIME_NUM distances between continuous prime number in
** sorted list. The largest distance will be saved at the first one
** primeList[0]. Here, one more item is defined for simplify the calculation
** in loop.                                                                  */
primeInfo primeList[NEEDED_PRIME_NUM+1];
/* The number of found prime number. Range: 0 ~ NEEDED_PRIME_NUM */
int foundPrimeNum;


/* Function insertNewDistance(int distance, int smallerPrime, int largePrime)
*******************************************************************************
* Function description: getPrimeCUDA() is used to insert the found new large
* distance.
*
* Inputs:
*   distance: the new distance between smaller prime and larger prime
*   smallerPrime: small prime
*   largerPrime: large prime
*
* Output:
*   Save the data to array primeList[] and update variable 'foundPrimeNum'
*
* Return:
*   None
*
******************************************************************************/
void insertNewDistance(int distance, int smallPrime, int largePrime)
{
    int j;

    for (j=foundPrimeNum; j>=0; j--)
    {
        /* Save the new result to the sorted place */
        /* Note: 6 items are defined in array primeList to avoid overrun */
        if ( (0 == j) || (distance <= primeList[j - 1].distance))
        {
            primeList[j].smallPrime = smallPrime;
            primeList[j].largePrime = largePrime;
            primeList[j].distance = distance;
            break;
        }
        else if (NEEDED_PRIME_NUM != j)
        {
            /* Move the item */
            primeList[j].smallPrime = primeList[j-1].smallPrime;
            primeList[j].largePrime = primeList[j-1].largePrime;
            primeList[j].distance = primeList[j-1].distance;
        }
    }

    /* Maximum 5 largest distances are kept. Update the number of distances */
    if (foundPrimeNum < NEEDED_PRIME_NUM)
    {
        foundPrimeNum++;
    }
}

/* Function getPrimeCUDA()
*******************************************************************************
* Function description: getPrimeCUDA() is used to find out all the primes.
*
* Inputs:
*   dev: the pointer to whole buffer in device [0, 1000000000]
*   prm: the array where the prime numbers in [2, CPU_CALC_END] found were save.
*   limit: the prime numbers found by CPU (cuda limit)
*
* Output:
*   The result is saved in the memory through pointer dev
*
* Return:
*   None
*
******************************************************************************/
__global__  void getPrimeCUDA(unsigned char* dev, int* prm, int limit)
{
    int j, k;
    int testPrime;
    int x;
    int start, end;
    int range;

    x = threadIdx.x;
    range = (MAX_NUMBER - CPU_CALC_END) / BLOCK_SIZE;

    start = CPU_CALC_END + range * x;
    end = start + range;

    if ((BLOCK_SIZE-1) == x)
    {
        end = MAX_NUMBER;
    }

    for (k=0; k<limit; k++)
    {
        testPrime = prm[k];

        j = start -(start % testPrime);

        if (j < start)
        {
            j += testPrime;
        }

        for (; j<end; j+=testPrime)
        {
            dev[j]=0;
        }
    }
}


int main()
{
    unsigned char* sieve;
    unsigned char* devA;
    /* Save the found prime and pass them to cuda. The length is estimated: 1-1/2-1/3 = 1/6 */
    int primeByCPU[CPU_CALC_END/6];
    int* devPrimes;

    int foundByCPU = 0;
    int i;
    int j;
    int totalSize;
    struct timeval  startTime; /* Record the start time */
    struct timeval  currentTime;  /* Record the current time */

    int recSmallDist = 0;           /* Smallest distance in the 5 recorded distance */
    int lastPrime = 2;               /* Record of last prime */
    int currDistance;

    /* Verify setting for searching primes between [2, MAX_NUMBER]. */
    if ((CPU_CALC_END * CPU_CALC_END) <= MAX_NUMBER)
    {
       printf("The CPU_CALC_END * CPU_CALC_END is too small.\n", CPU_CALC_END);

       j = 2;
       while ((j*j) < MAX_NUMBER)
       {
          j++;
       }
       printf("Please change definition of  from (%d) to value no less than (%d).\n", CPU_CALC_END, j);
       return 0;
    }

    totalSize = sizeof(unsigned char)*MAX_NUMBER;
    sieve = (unsigned char*)malloc(totalSize);

    /* allocate arrays on device */
    hipMalloc((void **) &devA, totalSize);

    for (i=2; i<MAX_NUMBER; i++)
    {
        sieve[i]=1; //initialize
    }

    gettimeofday(&startTime, NULL);

    for (i=2; i<CPU_CALC_END; i++)
    {
        if(0 == sieve[i])
        {
            continue;
        }

        for (j=i+i;j<CPU_CALC_END;j=j+i)
        {
            sieve[j]=0;
        }

        primeByCPU[foundByCPU++] = i;

        currDistance = i - lastPrime;

        /* The current distance is larger than the smallest record distance. Save it. */
        if (currDistance >= recSmallDist)
        {
            insertNewDistance(currDistance, lastPrime, i);

            /* Update the current smallest distance */
            recSmallDist = primeList[foundPrimeNum - 1].distance;
        }

        lastPrime = i;
    }
    gettimeofday(&currentTime, NULL);
    printf ("First time taken by CPU:  %f seconds\n",
             (double) (currentTime.tv_usec - startTime.tv_usec) / 1000000 +
             (double) (currentTime.tv_sec - startTime.tv_sec));

    /* allocate arrays on device */
    hipMalloc((void **) &devPrimes, foundByCPU*sizeof(int));

    /* copy arrays to device memory (synchronous) */
    hipMemcpy(devA, sieve, totalSize, hipMemcpyHostToDevice);

    /* copy arrays to device memory (synchronous) */
    hipMemcpy(devPrimes, primeByCPU, foundByCPU*sizeof(int), hipMemcpyHostToDevice);
    /* guarantee synchronization */
    hipDeviceSynchronize();

    /* execute kernel (asynchronous!) */
    getPrimeCUDA<<<1, BLOCK_SIZE>>>(devA, devPrimes, foundByCPU);

    /* retrieve results from device (synchronous) */
    hipMemcpy(&sieve[CPU_CALC_END], &devA[CPU_CALC_END], totalSize-CPU_CALC_END, hipMemcpyDeviceToHost);

    /* guarantee synchronization */
    hipDeviceSynchronize();

    for (i=CPU_CALC_END; i<MAX_NUMBER; i++)
    {
        if(sieve[i]==0)
        {
            continue;
        }

        currDistance = i - lastPrime;

        /* The current distance is larger than the smallest record distance. Save it. */
        if (currDistance >= recSmallDist)
        {
            insertNewDistance(currDistance, lastPrime, i);

            /* Update the current smallest distance */
            recSmallDist = primeList[foundPrimeNum - 1].distance;
        }

        lastPrime = i;
    }

    gettimeofday(&currentTime, NULL);
    printf("Largest prime number is %d. \n", lastPrime);
    printf("Now, print the 5 biggest distances between two continue prime numbers.\n");
    for(i=0;i<NEEDED_PRIME_NUM;i++)
    {
        printf("Between continue prime number (%d) and (%d), the distance is (%d). \n", primeList[i].smallPrime, primeList[i].largePrime, primeList[i].distance);
    }
    printf ("Total time taken by CPU:  %f seconds\n",
             (double) (currentTime.tv_usec - startTime.tv_usec) / 1000000 +
             (double) (currentTime.tv_sec - startTime.tv_sec));
    free(sieve);
    return 0;
}

	.text
	.file	"CP631_Final_cuda.hip"
	.globl	_Z17insertNewDistanceiii        # -- Begin function _Z17insertNewDistanceiii
	.type	_Z17insertNewDistanceiii,@function
_Z17insertNewDistanceiii:               # @_Z17insertNewDistanceiii
	.cfi_startproc
# %bb.0:
	movl	foundPrimeNum(%rip), %eax
	testl	%eax, %eax
	js	.LBB0_8
# %bb.1:                                # %.lr.ph.preheader
	movq	%rax, %rcx
	testq	%rax, %rax
	je	.LBB0_7
# %bb.2:                                # %.lr.ph25.preheader
	leaq	(%rax,%rax,2), %rcx
	leaq	primeList(,%rcx,4), %r8
	movq	%rax, %rcx
.LBB0_3:                                # %.lr.ph25
                                        # =>This Inner Loop Header: Depth=1
	movl	-4(%r8), %r9d
	cmpl	%edi, %r9d
	jge	.LBB0_7
# %bb.4:                                #   in Loop: Header=BB0_3 Depth=1
	cmpq	$5, %rcx
	je	.LBB0_6
# %bb.5:                                #   in Loop: Header=BB0_3 Depth=1
	movq	-12(%r8), %r10
	movq	%r10, (%r8)
	movl	%r9d, 8(%r8)
.LBB0_6:                                # %.lr.ph
                                        #   in Loop: Header=BB0_3 Depth=1
	decq	%rcx
	addq	$-12, %r8
	testq	%rcx, %rcx
	jne	.LBB0_3
.LBB0_7:                                # %.loopexit
	movl	%ecx, %ecx
	shlq	$2, %rcx
	movl	%esi, primeList(%rcx,%rcx,2)
	movl	%edx, primeList+4(%rcx,%rcx,2)
	movl	%edi, primeList+8(%rcx,%rcx,2)
	cmpl	$4, %eax
	jg	.LBB0_9
.LBB0_8:                                # %.loopexit.thread
	incl	%eax
	movl	%eax, foundPrimeNum(%rip)
.LBB0_9:
	retq
.Lfunc_end0:
	.size	_Z17insertNewDistanceiii, .Lfunc_end0-_Z17insertNewDistanceiii
	.cfi_endproc
                                        # -- End function
	.globl	_Z27__device_stub__getPrimeCUDAPhPii # -- Begin function _Z27__device_stub__getPrimeCUDAPhPii
	.type	_Z27__device_stub__getPrimeCUDAPhPii,@function
_Z27__device_stub__getPrimeCUDAPhPii:   # @_Z27__device_stub__getPrimeCUDAPhPii
	.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	$112, %rsp
	.cfi_def_cfa_offset 160
	.cfi_offset %rbx, -48
	.cfi_offset %r12, -40
	.cfi_offset %r13, -32
	.cfi_offset %r14, -24
	.cfi_offset %r15, -16
	leaq	40(%rsp), %rax
	movq	%rdi, (%rax)
	leaq	32(%rsp), %rcx
	movq	%rsi, (%rcx)
	leaq	12(%rsp), %rsi
	movl	%edx, (%rsi)
	leaq	80(%rsp), %rbx
	movq	%rax, (%rbx)
	movq	%rcx, 8(%rbx)
	movq	%rsi, 16(%rbx)
	leaq	64(%rsp), %r14
	leaq	48(%rsp), %r15
	leaq	24(%rsp), %r12
	leaq	16(%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	$_Z12getPrimeCUDAPhPii, %edi
	movq	%rbx, %r9
	pushq	(%r13)
	.cfi_adjust_cfa_offset 8
	pushq	(%r12)
	.cfi_adjust_cfa_offset 8
	callq	hipLaunchKernel
	addq	$128, %rsp
	.cfi_adjust_cfa_offset -128
	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	_Z27__device_stub__getPrimeCUDAPhPii, .Lfunc_end1-_Z27__device_stub__getPrimeCUDAPhPii
	.cfi_endproc
                                        # -- End function
	.section	.rodata.cst8,"aM",@progbits,8
	.p2align	3, 0x0                          # -- Begin function main
.LCPI2_0:
	.quad	0x412e848000000000              # double 1.0E+6
	.text
	.globl	main
	.type	main,@function
main:                                   # @main
	.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	$21400, %rsp                    # imm = 0x5398
	.cfi_def_cfa_offset 21456
	.cfi_offset %rbx, -56
	.cfi_offset %r12, -48
	.cfi_offset %r13, -40
	.cfi_offset %r14, -32
	.cfi_offset %r15, -24
	.cfi_offset %rbp, -16
	movl	$1000000000, %edi               # imm = 0x3B9ACA00
	callq	malloc
	movq	%rax, %rbx
	movq	%rsp, %rdi
	movl	$1000000000, %esi               # imm = 0x3B9ACA00
	callq	hipMalloc
	leaq	2(%rbx), %rdi
	movl	$999999998, %edx                # imm = 0x3B9AC9FE
	movl	$1, %esi
	callq	memset@PLT
	xorl	%r14d, %r14d
	leaq	48(%rsp), %rdi
	xorl	%esi, %esi
	callq	gettimeofday
	movl	$2, %ebp
	movl	$4, %r12d
	movl	$2, %r15d
	xorl	%r13d, %r13d
.LBB2_1:                                # =>This Loop Header: Depth=1
                                        #     Child Loop BB2_4 Depth 2
	cmpb	$0, (%rbx,%r15)
	je	.LBB2_8
# %bb.2:                                #   in Loop: Header=BB2_1 Depth=1
	cmpq	$15999, %r15                    # imm = 0x3E7F
	ja	.LBB2_5
# %bb.3:                                # %.lr.ph.preheader
                                        #   in Loop: Header=BB2_1 Depth=1
	movq	%r12, %rax
.LBB2_4:                                # %.lr.ph
                                        #   Parent Loop BB2_1 Depth=1
                                        # =>  This Inner Loop Header: Depth=2
	movb	$0, (%rbx,%rax)
	addq	%r15, %rax
	cmpq	$32000, %rax                    # imm = 0x7D00
	jb	.LBB2_4
.LBB2_5:                                # %._crit_edge
                                        #   in Loop: Header=BB2_1 Depth=1
	movslq	%r14d, %rax
	incl	%r14d
	movl	%r15d, 64(%rsp,%rax,4)
	movl	%r15d, %edi
	subl	%ebp, %edi
	cmpl	%r13d, %edi
	jl	.LBB2_7
# %bb.6:                                #   in Loop: Header=BB2_1 Depth=1
	movl	%ebp, %esi
	movl	%r15d, %edx
	callq	_Z17insertNewDistanceiii
	movslq	foundPrimeNum(%rip), %rax
	leaq	(%rax,%rax,2), %rax
	movl	primeList-4(,%rax,4), %r13d
.LBB2_7:                                #   in Loop: Header=BB2_1 Depth=1
	movl	%r15d, %ebp
.LBB2_8:                                #   in Loop: Header=BB2_1 Depth=1
	incq	%r15
	addq	$2, %r12
	cmpq	$32000, %r15                    # imm = 0x7D00
	jne	.LBB2_1
# %bb.9:
	leaq	24(%rsp), %r15
	movq	%r15, %rdi
	xorl	%esi, %esi
	callq	gettimeofday
	movq	(%r15), %rax
	movq	8(%r15), %rcx
	movq	48(%rsp), %rdx
	movq	56(%rsp), %rsi
	movq	%rsi, 8(%rsp)                   # 8-byte Spill
	subq	%rsi, %rcx
	cvtsi2sd	%rcx, %xmm1
	divsd	.LCPI2_0(%rip), %xmm1
	movq	%rdx, 16(%rsp)                  # 8-byte Spill
	subq	%rdx, %rax
	cvtsi2sd	%rax, %xmm0
	addsd	%xmm1, %xmm0
	movl	$.L.str, %edi
	movb	$1, %al
	callq	printf
	movslq	%r14d, %r15
	shlq	$2, %r15
	leaq	40(%rsp), %r12
	movq	%r12, %rdi
	movq	%r15, %rsi
	callq	hipMalloc
	movq	(%rsp), %rdi
	movl	$1000000000, %edx               # imm = 0x3B9ACA00
	movq	%rbx, %rsi
	movl	$1, %ecx
	callq	hipMemcpy
	movq	(%r12), %rdi
	leaq	64(%rsp), %rsi
	movq	%r15, %rdx
	movl	$1, %ecx
	callq	hipMemcpy
	callq	hipDeviceSynchronize
	movabsq	$4294967297, %rdi               # imm = 0x100000001
	leaq	511(%rdi), %rdx
	movl	$1, %esi
	movl	$1, %ecx
	xorl	%r8d, %r8d
	xorl	%r9d, %r9d
	callq	__hipPushCallConfiguration
	testl	%eax, %eax
	jne	.LBB2_11
# %bb.10:
	movq	(%rsp), %rdi
	movq	40(%rsp), %rsi
	movl	%r14d, %edx
	callq	_Z27__device_stub__getPrimeCUDAPhPii
.LBB2_11:
	movl	$32000, %r14d                   # imm = 0x7D00
	movq	%rbx, %rdi
	addq	%r14, %rdi
	movq	(%rsp), %rsi
	addq	%r14, %rsi
	movl	$999968000, %edx                # imm = 0x3B9A4D00
	movl	$2, %ecx
	callq	hipMemcpy
	callq	hipDeviceSynchronize
.LBB2_12:                               # =>This Inner Loop Header: Depth=1
	cmpb	$0, (%rbx,%r14)
	je	.LBB2_16
# %bb.13:                               #   in Loop: Header=BB2_12 Depth=1
	movl	%ebp, %edi
	negl	%edi
	addq	%r14, %rdi
	cmpl	%r13d, %edi
	jl	.LBB2_15
# %bb.14:                               #   in Loop: Header=BB2_12 Depth=1
                                        # kill: def $edi killed $edi killed $rdi
	movl	%ebp, %esi
	movl	%r14d, %edx
	callq	_Z17insertNewDistanceiii
	movslq	foundPrimeNum(%rip), %rax
	leaq	(%rax,%rax,2), %rax
	movl	primeList-4(,%rax,4), %r13d
.LBB2_15:                               #   in Loop: Header=BB2_12 Depth=1
	movl	%r14d, %ebp
.LBB2_16:                               #   in Loop: Header=BB2_12 Depth=1
	incq	%r14
	cmpq	$1000000000, %r14               # imm = 0x3B9ACA00
	jne	.LBB2_12
# %bb.17:
	leaq	24(%rsp), %rdi
	xorl	%esi, %esi
	callq	gettimeofday
	movl	$.L.str.1, %edi
	movl	%ebp, %esi
	xorl	%eax, %eax
	callq	printf
	movl	$.Lstr, %edi
	callq	puts@PLT
	movq	$-60, %r14
.LBB2_18:                               # =>This Inner Loop Header: Depth=1
	movl	primeList+60(%r14), %esi
	movl	primeList+64(%r14), %edx
	movl	primeList+68(%r14), %ecx
	movl	$.L.str.3, %edi
	xorl	%eax, %eax
	callq	printf
	addq	$12, %r14
	jne	.LBB2_18
# %bb.19:
	movq	24(%rsp), %rax
	movq	32(%rsp), %rcx
	subq	8(%rsp), %rcx                   # 8-byte Folded Reload
	cvtsi2sd	%rcx, %xmm1
	divsd	.LCPI2_0(%rip), %xmm1
	subq	16(%rsp), %rax                  # 8-byte Folded Reload
	cvtsi2sd	%rax, %xmm0
	addsd	%xmm1, %xmm0
	movl	$.L.str.4, %edi
	movb	$1, %al
	callq	printf
	movq	%rbx, %rdi
	callq	free
	xorl	%eax, %eax
	addq	$21400, %rsp                    # imm = 0x5398
	.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	main, .Lfunc_end2-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	.LBB3_2
# %bb.1:
	movl	$__hip_fatbin_wrapper, %edi
	callq	__hipRegisterFatBinary
	movq	%rax, %rdi
	movq	%rax, __hip_gpubin_handle(%rip)
.LBB3_2:
	xorps	%xmm0, %xmm0
	movups	%xmm0, 16(%rsp)
	movups	%xmm0, (%rsp)
	movl	$_Z12getPrimeCUDAPhPii, %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_end3:
	.size	__hip_module_ctor, .Lfunc_end3-__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	.LBB4_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
.LBB4_2:
	retq
.Lfunc_end4:
	.size	__hip_module_dtor, .Lfunc_end4-__hip_module_dtor
	.cfi_endproc
                                        # -- End function
	.type	primeList,@object               # @primeList
	.bss
	.globl	primeList
	.p2align	4, 0x0
primeList:
	.zero	72
	.size	primeList, 72

	.type	foundPrimeNum,@object           # @foundPrimeNum
	.globl	foundPrimeNum
	.p2align	2, 0x0
foundPrimeNum:
	.long	0                               # 0x0
	.size	foundPrimeNum, 4

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

	.type	.L.str,@object                  # @.str
	.section	.rodata.str1.1,"aMS",@progbits,1
.L.str:
	.asciz	"First time taken by CPU:  %f seconds\n"
	.size	.L.str, 38

	.type	.L.str.1,@object                # @.str.1
.L.str.1:
	.asciz	"Largest prime number is %d. \n"
	.size	.L.str.1, 30

	.type	.L.str.3,@object                # @.str.3
.L.str.3:
	.asciz	"Between continue prime number (%d) and (%d), the distance is (%d). \n"
	.size	.L.str.3, 69

	.type	.L.str.4,@object                # @.str.4
.L.str.4:
	.asciz	"Total time taken by CPU:  %f seconds\n"
	.size	.L.str.4, 38

	.type	.L__unnamed_1,@object           # @0
.L__unnamed_1:
	.asciz	"_Z12getPrimeCUDAPhPii"
	.size	.L__unnamed_1, 22

	.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	"Now, print the 5 biggest distances between two continue prime numbers."
	.size	.Lstr, 71

	.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 _Z27__device_stub__getPrimeCUDAPhPii
	.addrsig_sym __hip_module_ctor
	.addrsig_sym __hip_module_dtor
	.addrsig_sym _Z12getPrimeCUDAPhPii
	.addrsig_sym __hip_fatbin
	.addrsig_sym __hip_fatbin_wrapper
	.addrsig_sym __hip_cuid_

	.text
	.amdgcn_target "amdgcn-amd-amdhsa--gfx1100"
	.protected	_Z12getPrimeCUDAPhPii   ; -- Begin function _Z12getPrimeCUDAPhPii
	.globl	_Z12getPrimeCUDAPhPii
	.p2align	8
	.type	_Z12getPrimeCUDAPhPii,@function
_Z12getPrimeCUDAPhPii:                  ; @_Z12getPrimeCUDAPhPii
; %bb.0:
	s_load_b32 s8, s[0:1], 0x10
	s_waitcnt lgkmcnt(0)
	s_cmp_lt_i32 s8, 1
	s_cbranch_scc1 .LBB0_6
; %bb.1:                                ; %.lr.ph30.preheader
	s_load_b128 s[4:7], s[0:1], 0x0
	s_mov_b32 s0, 0x1e4a26
	v_cmp_ne_u32_e32 vcc_lo, 0x1ff, v0
	v_mad_u32_u24 v1, 0x1dcd26, v0, s0
	s_mov_b32 s0, 0x1dcd26
	s_mov_b32 s3, 0
	v_mad_u32_u24 v2, v0, s0, 0x7d00
	s_delay_alu instid0(VALU_DEP_2)
	v_dual_mov_b32 v4, 0 :: v_dual_cndmask_b32 v3, 0x3b9aca00, v1
	s_mov_b32 s2, s3
.LBB0_2:                                ; %.lr.ph30
                                        ; =>This Loop Header: Depth=1
                                        ;     Child Loop BB0_4 Depth 2
	s_delay_alu instid0(SALU_CYCLE_1)
	s_lshl_b64 s[0:1], s[2:3], 2
	s_waitcnt lgkmcnt(0)
	s_add_u32 s0, s6, s0
	s_addc_u32 s1, s7, s1
	global_load_b32 v5, v4, s[0:1]
	s_mov_b32 s1, exec_lo
	s_waitcnt vmcnt(0)
	v_ashrrev_i32_e32 v6, 31, v5
	s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(VALU_DEP_1)
	v_add_nc_u32_e32 v0, v5, v6
	v_xor_b32_e32 v0, v0, v6
	s_delay_alu instid0(VALU_DEP_1) | instskip(SKIP_1) | instid1(VALU_DEP_2)
	v_cvt_f32_u32_e32 v1, v0
	v_sub_nc_u32_e32 v7, 0, v0
	v_rcp_iflag_f32_e32 v1, v1
	s_waitcnt_depctr 0xfff
	v_mul_f32_e32 v1, 0x4f7ffffe, v1
	s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(VALU_DEP_1)
	v_cvt_u32_f32_e32 v1, v1
	v_mul_lo_u32 v7, v7, v1
	s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(VALU_DEP_1)
	v_mul_hi_u32 v7, v1, v7
	v_add_nc_u32_e32 v1, v1, v7
	s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(VALU_DEP_1)
	v_mul_hi_u32 v1, v2, v1
	v_mul_lo_u32 v1, v1, v0
	s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(VALU_DEP_1)
	v_sub_nc_u32_e32 v1, v2, v1
	v_sub_nc_u32_e32 v7, v1, v0
	v_cmp_ge_u32_e32 vcc_lo, v1, v0
	s_delay_alu instid0(VALU_DEP_2) | instskip(NEXT) | instid1(VALU_DEP_1)
	v_cndmask_b32_e32 v1, v1, v7, vcc_lo
	v_sub_nc_u32_e32 v7, v1, v0
	v_cmp_ge_u32_e32 vcc_lo, v1, v0
	s_delay_alu instid0(VALU_DEP_2) | instskip(SKIP_1) | instid1(VALU_DEP_2)
	v_cndmask_b32_e32 v0, v1, v7, vcc_lo
	v_add_nc_u32_e32 v1, v5, v2
	v_cmp_eq_u32_e32 vcc_lo, 0, v0
	s_delay_alu instid0(VALU_DEP_2) | instskip(NEXT) | instid1(VALU_DEP_1)
	v_sub_nc_u32_e32 v1, v1, v0
	v_cndmask_b32_e32 v7, v1, v2, vcc_lo
	s_delay_alu instid0(VALU_DEP_1)
	v_cmpx_lt_i32_e64 v7, v3
	s_cbranch_execz .LBB0_5
; %bb.3:                                ; %.lr.ph.preheader
                                        ;   in Loop: Header=BB0_2 Depth=1
	v_ashrrev_i32_e32 v1, 31, v7
	v_add_co_u32 v0, vcc_lo, s4, v7
	s_mov_b32 s9, 0
	s_delay_alu instid0(VALU_DEP_2)
	v_add_co_ci_u32_e32 v1, vcc_lo, s5, v1, vcc_lo
.LBB0_4:                                ; %.lr.ph
                                        ;   Parent Loop BB0_2 Depth=1
                                        ; =>  This Inner Loop Header: Depth=2
	v_add_nc_u32_e32 v7, v7, v5
	global_store_b8 v[0:1], v4, off
	v_add_co_u32 v0, s0, v0, v5
	s_delay_alu instid0(VALU_DEP_1) | instskip(SKIP_2) | instid1(SALU_CYCLE_1)
	v_add_co_ci_u32_e64 v1, s0, v1, v6, s0
	v_cmp_ge_i32_e32 vcc_lo, v7, v3
	s_or_b32 s9, vcc_lo, s9
	s_and_not1_b32 exec_lo, exec_lo, s9
	s_cbranch_execnz .LBB0_4
.LBB0_5:                                ; %Flow40
                                        ;   in Loop: Header=BB0_2 Depth=1
	s_or_b32 exec_lo, exec_lo, s1
	s_add_i32 s2, s2, 1
	s_delay_alu instid0(SALU_CYCLE_1)
	s_cmp_lg_u32 s2, s8
	s_cbranch_scc1 .LBB0_2
.LBB0_6:                                ; %._crit_edge31
	s_nop 0
	s_sendmsg sendmsg(MSG_DEALLOC_VGPRS)
	s_endpgm
	.section	.rodata,"a",@progbits
	.p2align	6, 0x0
	.amdhsa_kernel _Z12getPrimeCUDAPhPii
		.amdhsa_group_segment_fixed_size 0
		.amdhsa_private_segment_fixed_size 0
		.amdhsa_kernarg_size 20
		.amdhsa_user_sgpr_count 15
		.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 0
		.amdhsa_system_sgpr_workgroup_id_z 0
		.amdhsa_system_sgpr_workgroup_info 0
		.amdhsa_system_vgpr_workitem_id 0
		.amdhsa_next_free_vgpr 8
		.amdhsa_next_free_sgpr 10
		.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	_Z12getPrimeCUDAPhPii, .Lfunc_end0-_Z12getPrimeCUDAPhPii
                                        ; -- End function
	.section	.AMDGPU.csdata,"",@progbits
; Kernel info:
; codeLenInByte = 412
; NumSgprs: 12
; NumVgprs: 8
; ScratchSize: 0
; MemoryBound: 0
; FloatMode: 240
; IeeeMode: 1
; LDSByteSize: 0 bytes/workgroup (compile time only)
; SGPRBlocks: 1
; VGPRBlocks: 0
; NumSGPRsForWavesPerEU: 12
; NumVGPRsForWavesPerEU: 8
; Occupancy: 16
; WaveLimiterHint : 0
; COMPUTE_PGM_RSRC2:SCRATCH_EN: 0
; COMPUTE_PGM_RSRC2:USER_SGPR: 15
; COMPUTE_PGM_RSRC2:TRAP_HANDLER: 0
; COMPUTE_PGM_RSRC2:TGID_X_EN: 1
; COMPUTE_PGM_RSRC2:TGID_Y_EN: 0
; COMPUTE_PGM_RSRC2:TGID_Z_EN: 0
; COMPUTE_PGM_RSRC2:TIDIG_COMP_CNT: 0
	.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:     by_value
    .group_segment_fixed_size: 0
    .kernarg_segment_align: 8
    .kernarg_segment_size: 20
    .language:       OpenCL C
    .language_version:
      - 2
      - 0
    .max_flat_workgroup_size: 1024
    .name:           _Z12getPrimeCUDAPhPii
    .private_segment_fixed_size: 0
    .sgpr_count:     12
    .sgpr_spill_count: 0
    .symbol:         _Z12getPrimeCUDAPhPii.kd
    .uniform_work_group_size: 1
    .uses_dynamic_stack: false
    .vgpr_count:     8
    .vgpr_spill_count: 0
    .wavefront_size: 32
    .workgroup_processor_mode: 1
amdhsa.target:   amdgcn-amd-amdhsa--gfx1100
amdhsa.version:
  - 1
  - 2
...

	.end_amdgpu_metadata
