/**
 * Copyright 1993-2012 NVIDIA Corporation.  All rights reserved.
 *
 * Please refer to the NVIDIA end user license agreement (EULA) associated
 * with this source code for terms and conditions that govern your use of
 * this software. Any use, reproduction, disclosure, or distribution of
 * this software and related documentation outside the terms of the EULA
 * is strictly prohibited.
 */
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <utility>
#include <iostream>
#include <bitset>
#include <math.h>
#include <time.h>
#include <chrono>
#include <cuda.h>

/**
 * This macro checks return value of the CUDA runtime call and exits
 * the application if the call failed.
 *
 * See cuda.h for error code descriptions.
 */

#ifndef BLOCK_SIZE
#define BLOCK_SIZE 1024
#endif

#ifndef ELAPSED_TIME
#define ELAPSED_TIME 0
#endif

#ifndef EXP_BITS_SIZE
#define EXP_BITS_SIZE 10
#endif

void print(int* h_data, int n) {
	std::cout << "\n";
	for (int i = 0; i < n; i++) {
		std::cout << h_data[i] << " ";
	}
	std::cout << "\n";
}

void cudaTest(cudaError_t error) {
	if (error != cudaSuccess) {
		printf("cuda returned error %s (code %d), line(%d)\n",
				cudaGetErrorString(error), error, __LINE__);
		exit(EXIT_FAILURE);
	}
}



/*
 * 256 threads per block
 * 4 elements per thread
 * = 1024 elements per block
 * = n/1024 blocks
 */

template<int BITS_NUMBER = 64>
__global__ void radix_sort(int *d_vec, int *d_seg, int num_segments) {

	int bx = blockIdx.x;
	int tx = threadIdx.x;

	int begin = d_seg[bx];
	int end = d_seg[bx + 1];
	int size = end - begin;

	__shared__ int s_vec[BLOCK_SIZE];
	__shared__ int s_aux[BLOCK_SIZE];
	__shared__ int s_pref_sum_one[BLOCK_SIZE];
	__shared__ int s_pref_sum_zero[BLOCK_SIZE];

	for (int k = 0; k < size; k += BLOCK_SIZE) {
		int threadIndexGlobal = begin + k + tx;

		int block = BLOCK_SIZE;
		if(BLOCK_SIZE+k > size)
			block = size-k;

		if (threadIndexGlobal < end) {
			s_vec[tx] = d_vec[threadIndexGlobal];
			__syncthreads();

			int i, j;
			int exp = 0;

			for (j = 0; j < BITS_NUMBER; j++) {

				int x = (s_vec[tx] >> exp) & 1;
				s_pref_sum_one[tx] = x;
				s_pref_sum_zero[tx] = 1-x;
				__syncthreads();

				for (i = 1; i < block; i*=2) {
					int index = tx + i;
					if (index < block) {
						int one = s_pref_sum_one[tx] + s_pref_sum_one[index];
						int zero = s_pref_sum_zero[tx] + s_pref_sum_zero[index];
						__syncthreads();
						s_pref_sum_one[index] = one;
						s_pref_sum_zero[index] = zero;
						__syncthreads();
					}
				}

				x = (s_vec[tx] >> exp) & 1;
				int index = (x) * (s_pref_sum_one[tx] + s_pref_sum_zero[block-1] - 1)
						+ (1 - x) * (s_pref_sum_zero[tx] - 1);
				s_aux[index] = s_vec[tx];
				__syncthreads();

				s_vec[tx] = s_aux[tx];
				__syncthreads();

				exp++;
			}
			d_vec[threadIndexGlobal] = s_aux[tx];
		}
	}
}

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

	int num_of_segments;
	int num_of_elements;
	int i;

	scanf("%d", &num_of_segments);
	int mem_size_seg = sizeof(int) * (num_of_segments + 1);
	int *h_seg = (int *) malloc(mem_size_seg);
	for (i = 0; i < num_of_segments + 1; i++)
		scanf("%d", &h_seg[i]);

	scanf("%d", &num_of_elements);
	int mem_size_vec = sizeof(int) * num_of_elements;
	int *h_vec = (int *) malloc(mem_size_vec);
	for (i = 0; i < num_of_elements; i++)
		scanf("%d", &h_vec[i]);

//	print(h_seg, num_of_segments + 1);	print(h_vec, num_of_elements);

// Allocate device memory
	int *d_seg, *d_vec;

	cudaTest(cudaMalloc((void **) &d_seg, mem_size_seg));
	cudaTest(cudaMalloc((void **) &d_vec, mem_size_vec));
//cudaTest(cudaMalloc((void **) &d_aux, mem_size_vec));

// copy host memory to device
	cudaTest(cudaMemcpy(d_seg, h_seg, mem_size_seg, cudaMemcpyHostToDevice));
	cudaTest(cudaMemcpy(d_vec, h_vec, mem_size_vec, cudaMemcpyHostToDevice));

	// Setup execution parameters
//	int devID = 0;
//	cudaDeviceProp deviceProp;
//	cudaTest(cudaGetDeviceProperties(&deviceProp, devID));
//	unsigned int multiprocessor_number = deviceProp.multiProcessorCount;
//	//unsigned int grid_blocks_max_x = deviceProp.maxGridSize[0];
//	//unsigned int sharedMemoryTotal = deviceProp.sharedMemPerBlock/(sizeof(int));
//
	int blocksize = BLOCK_SIZE; //num_of_elements / num_of_segments;
	//if (blocksize > 1024)
	//	blocksize = 1024;

	dim3 threads(blocksize, 1);
	//dim3 grid(num_of_segments / blocksize + 1, 1);
	dim3 grid(num_of_segments, 1);

	std::chrono::high_resolution_clock::time_point start =
			std::chrono::high_resolution_clock::now();

	radix_sort<EXP_BITS_SIZE> <<<grid, threads>>>(d_vec, d_seg,
			num_of_segments);
	cudaDeviceSynchronize();
	std::chrono::high_resolution_clock::time_point stop =
			std::chrono::high_resolution_clock::now();
	cudaTest(cudaPeekAtLastError());
	std::chrono::duration<double> time_span = std::chrono::duration_cast<
			std::chrono::duration<double>>(stop - start);

	cudaTest(cudaMemcpy(h_seg, d_seg, mem_size_seg, cudaMemcpyDeviceToHost));
	cudaTest(cudaMemcpy(h_vec, d_vec, mem_size_vec, cudaMemcpyDeviceToHost));

	//print(h_seg, num_of_segments + 1);
	//print(h_vec, num_of_elements);
	//print(h_seg, 10);
	//print(h_vec, 1000);
	if (ELAPSED_TIME == 1)
//		std::cout << "It took me " << time_span.count() * 1000
//				<< " miliseconds.\n";
		;
	else
		print(h_vec, num_of_elements);

	// cudaDeviceReset causes the driver to clean up all state. While
	// not mandatory in normal operation, it is good practice.  It is also
	// needed to ensure correct operation when the application is being
	// profiled. Calling cudaDeviceReset causes all profile data to be
	// flushed before the application exits
	cudaDeviceReset();

	free(h_seg);
	free(h_vec);
	cudaFree(d_seg);
	cudaFree(d_vec);

	return 0;
}

/**
 * 	// cudaDeviceReset causes the driver to clean up all state. While
 // not mandatory in normal operation, it is good practice.  It is also
 // needed to ensure correct operation when the application is being
 // profiled. Calling cudaDeviceReset causes all profile data to be
 // flushed before the application exits
 cudaDeviceReset();
 */

/*
 printf("thread=%d | aux=%d %d %d %d\n", bx * blockDim.x + tx, d_aux[begin], d_aux[begin + 1], d_aux[begin + 2],	d_aux[begin + 3]);
 int devID = 0;
 cudaDeviceProp deviceProp;
 cudaTest(cudaGetDeviceProperties(&deviceProp, devID));
 unsigned int multiprocessorNumber = deviceProp.multiProcessorCount;
 unsigned int sharedMemoryTotal = deviceProp.sharedMemPerBlock/(sizeof(int));
 std::cout << "multiprocessorNumber: " << multiprocessorNumber << "\n";
 std::cout << "sharedMemoryTotal: " << sharedMemoryTotal << "\n";
 std::cout << "numberOfSegmentsPerBlock: " << sharedMemoryTotal << "\n";
 */

	.file	"tmpxft_0025e6d7_00000000-6_sharev1.cudafe1.cpp"
	.text
#APP
	.globl _ZSt21ios_base_library_initv

#NO_APP
	.type	_ZL26__cudaUnregisterBinaryUtilv, @function
_ZL26__cudaUnregisterBinaryUtilv:
.LFB4158:
	.cfi_startproc
	endbr64
	movq	_ZL20__cudaFatCubinHandle(%rip), %rdi
	jmp	__cudaUnregisterFatBinary@PLT
	.cfi_endproc
.LFE4158:
	.size	_ZL26__cudaUnregisterBinaryUtilv, .-_ZL26__cudaUnregisterBinaryUtilv
	.type	_ZL42__device_stub__Z10radix_sortILi10EEvPiS0_iPiS_i, @function
_ZL42__device_stub__Z10radix_sortILi10EEvPiS0_iPiS_i:
.LFB4180:
	.cfi_startproc
	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	.L2
	pushq	40(%rsp)
	.cfi_def_cfa_offset 152
	leaq	_Z10radix_sortILi10EEvPiS0_i(%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
.L2:
	movq	120(%rsp), %rax
	subq	%fs:40, %rax
	je	.L4
	call	__stack_chk_fail@PLT
.L4:
	addq	$136, %rsp
	.cfi_def_cfa_offset 8
	ret
	.cfi_endproc
.LFE4180:
	.size	_ZL42__device_stub__Z10radix_sortILi10EEvPiS0_iPiS_i, .-_ZL42__device_stub__Z10radix_sortILi10EEvPiS0_iPiS_i
	.section	.text._Z10radix_sortILi10EEvPiS0_i,"axG",@progbits,_Z10radix_sortILi10EEvPiS0_i,comdat
	.weak	_Z10radix_sortILi10EEvPiS0_i
	.type	_Z10radix_sortILi10EEvPiS0_i, @function
_Z10radix_sortILi10EEvPiS0_i:
.LFB4511:
	.cfi_startproc
	endbr64
	jmp	_ZL42__device_stub__Z10radix_sortILi10EEvPiS0_iPiS_i
	.cfi_endproc
.LFE4511:
	.size	_Z10radix_sortILi10EEvPiS0_i, .-_Z10radix_sortILi10EEvPiS0_i
	.section	.rodata.str1.1,"aMS",@progbits,1
.LC0:
	.string	"\n"
.LC1:
	.string	" "
	.text
	.globl	_Z5printPii
	.type	_Z5printPii, @function
_Z5printPii:
.LFB4149:
	.cfi_startproc
	endbr64
	pushq	%r15
	.cfi_def_cfa_offset 16
	.cfi_offset 15, -16
	leaq	.LC1(%rip), %r15
	pushq	%r14
	.cfi_def_cfa_offset 24
	.cfi_offset 14, -24
	leaq	.LC0(%rip), %r14
	pushq	%r13
	.cfi_def_cfa_offset 32
	.cfi_offset 13, -32
	movq	%rdi, %r13
	pushq	%r12
	.cfi_def_cfa_offset 40
	.cfi_offset 12, -40
	movl	%esi, %r12d
	movq	%r14, %rsi
	pushq	%rbp
	.cfi_def_cfa_offset 48
	.cfi_offset 6, -48
	leaq	_ZSt4cout(%rip), %rbp
	pushq	%rbx
	.cfi_def_cfa_offset 56
	.cfi_offset 3, -56
	movq	%rbp, %rdi
	xorl	%ebx, %ebx
	pushq	%rdx
	.cfi_def_cfa_offset 64
	movl	$1, %edx
	call	_ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_PKS3_l@PLT
.L9:
	cmpl	%ebx, %r12d
	jle	.L12
	movl	0(%r13,%rbx,4), %esi
	movq	%rbp, %rdi
	incq	%rbx
	call	_ZNSolsEi@PLT
	movl	$1, %edx
	movq	%r15, %rsi
	movq	%rax, %rdi
	call	_ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_PKS3_l@PLT
	jmp	.L9
.L12:
	popq	%rax
	.cfi_def_cfa_offset 56
	movq	%r14, %rsi
	popq	%rbx
	.cfi_def_cfa_offset 48
	movq	%rbp, %rdi
	movl	$1, %edx
	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
	jmp	_ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_PKS3_l@PLT
	.cfi_endproc
.LFE4149:
	.size	_Z5printPii, .-_Z5printPii
	.section	.rodata.str1.1
.LC2:
	.string	"cuda returned error %s (code %d), line(%d)\n"
	.text
	.globl	_Z8cudaTest9cudaError
	.type	_Z8cudaTest9cudaError, @function
_Z8cudaTest9cudaError:
.LFB4150:
	.cfi_startproc
	endbr64
	testl	%edi, %edi
	je	.L13
	pushq	%rbx
	.cfi_def_cfa_offset 16
	.cfi_offset 3, -16
	movl	%edi, %ebx
	call	cudaGetErrorString@PLT
	movl	$2, %edi
	movl	%ebx, %ecx
	movl	$51, %r8d
	movq	%rax, %rdx
	leaq	.LC2(%rip), %rsi
	xorl	%eax, %eax
	call	__printf_chk@PLT
	movl	$1, %edi
	call	exit@PLT
.L13:
	.cfi_def_cfa_offset 8
	.cfi_restore 3
	ret
	.cfi_endproc
.LFE4150:
	.size	_Z8cudaTest9cudaError, .-_Z8cudaTest9cudaError
	.section	.rodata.str1.1
.LC3:
	.string	"%d"
	.section	.text.startup,"ax",@progbits
	.globl	main
	.type	main, @function
main:
.LFB4153:
	.cfi_startproc
	endbr64
	pushq	%r15
	.cfi_def_cfa_offset 16
	.cfi_offset 15, -16
	leaq	.LC3(%rip), %rdi
	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
	xorl	%ebx, %ebx
	subq	$72, %rsp
	.cfi_def_cfa_offset 128
	movq	%fs:40, %rax
	movq	%rax, 56(%rsp)
	xorl	%eax, %eax
	leaq	8(%rsp), %rsi
	call	__isoc23_scanf@PLT
	movl	8(%rsp), %eax
	leal	4(,%rax,4), %r13d
	movslq	%r13d, %r13
	movq	%r13, %rdi
	call	malloc@PLT
	movq	%rax, %r12
	movq	%rax, %rbp
.L19:
	cmpl	%ebx, 8(%rsp)
	jl	.L26
	movq	%rbp, %rsi
	leaq	.LC3(%rip), %rdi
	xorl	%eax, %eax
	incl	%ebx
	call	__isoc23_scanf@PLT
	addq	$4, %rbp
	jmp	.L19
.L26:
	leaq	12(%rsp), %rsi
	leaq	.LC3(%rip), %rdi
	xorl	%eax, %eax
	xorl	%r15d, %r15d
	call	__isoc23_scanf@PLT
	movl	12(%rsp), %eax
	leal	0(,%rax,4), %ebx
	movslq	%ebx, %rbx
	movq	%rbx, %rdi
	call	malloc@PLT
	movq	%rax, %rbp
	movq	%rax, %r14
.L21:
	cmpl	%r15d, 12(%rsp)
	jle	.L27
	movq	%r14, %rsi
	leaq	.LC3(%rip), %rdi
	xorl	%eax, %eax
	incl	%r15d
	call	__isoc23_scanf@PLT
	addq	$4, %r14
	jmp	.L21
.L27:
	movq	%r13, %rsi
	leaq	16(%rsp), %rdi
	call	cudaMalloc@PLT
	movl	%eax, %edi
	call	_Z8cudaTest9cudaError
	movq	%rbx, %rsi
	leaq	24(%rsp), %rdi
	call	cudaMalloc@PLT
	movl	%eax, %edi
	call	_Z8cudaTest9cudaError
	movq	16(%rsp), %rdi
	movq	%r13, %rdx
	movq	%r12, %rsi
	movl	$1, %ecx
	call	cudaMemcpy@PLT
	movl	%eax, %edi
	call	_Z8cudaTest9cudaError
	movq	24(%rsp), %rdi
	movq	%rbx, %rdx
	movq	%rbp, %rsi
	movl	$1, %ecx
	call	cudaMemcpy@PLT
	movl	%eax, %edi
	call	_Z8cudaTest9cudaError
	movl	$4194305, %eax
	movl	$1, 40(%rsp)
	salq	$10, %rax
	movq	%rax, 32(%rsp)
	movl	8(%rsp), %eax
	movl	%eax, 44(%rsp)
	movabsq	$4294967297, %rax
	movq	%rax, 48(%rsp)
	call	_ZNSt6chrono3_V212system_clock3nowEv@PLT
	movl	40(%rsp), %ecx
	movl	52(%rsp), %esi
	xorl	%r9d, %r9d
	movq	32(%rsp), %rdx
	movq	44(%rsp), %rdi
	xorl	%r8d, %r8d
	call	__cudaPushCallConfiguration@PLT
	testl	%eax, %eax
	jne	.L23
	movl	8(%rsp), %edx
	movq	16(%rsp), %rsi
	movq	24(%rsp), %rdi
	call	_ZL42__device_stub__Z10radix_sortILi10EEvPiS0_iPiS_i
.L23:
	call	cudaDeviceSynchronize@PLT
	call	_ZNSt6chrono3_V212system_clock3nowEv@PLT
	call	cudaPeekAtLastError@PLT
	movl	%eax, %edi
	call	_Z8cudaTest9cudaError
	movq	16(%rsp), %rsi
	movq	%r13, %rdx
	movq	%r12, %rdi
	movl	$2, %ecx
	call	cudaMemcpy@PLT
	movl	%eax, %edi
	call	_Z8cudaTest9cudaError
	movq	24(%rsp), %rsi
	movq	%rbx, %rdx
	movq	%rbp, %rdi
	movl	$2, %ecx
	call	cudaMemcpy@PLT
	movl	%eax, %edi
	call	_Z8cudaTest9cudaError
	movl	12(%rsp), %esi
	movq	%rbp, %rdi
	call	_Z5printPii
	call	cudaDeviceReset@PLT
	movq	%r12, %rdi
	call	free@PLT
	movq	%rbp, %rdi
	call	free@PLT
	movq	16(%rsp), %rdi
	call	cudaFree@PLT
	movq	24(%rsp), %rdi
	call	cudaFree@PLT
	movq	56(%rsp), %rax
	subq	%fs:40, %rax
	je	.L24
	call	__stack_chk_fail@PLT
.L24:
	addq	$72, %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
.LFE4153:
	.size	main, .-main
	.section	.rodata.str1.1
.LC4:
	.string	"_Z10radix_sortILi10EEvPiS0_i"
	.section	.text.startup
	.type	_ZL24__sti____cudaRegisterAllv, @function
_ZL24__sti____cudaRegisterAllv:
.LFB4183:
	.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	.LC4(%rip), %rdx
	movq	%rax, %rdi
	leaq	_Z10radix_sortILi10EEvPiS0_i(%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
.LFE4183:
	.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
	.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:

/**
 * Copyright 1993-2012 NVIDIA Corporation.  All rights reserved.
 *
 * Please refer to the NVIDIA end user license agreement (EULA) associated
 * with this source code for terms and conditions that govern your use of
 * this software. Any use, reproduction, disclosure, or distribution of
 * this software and related documentation outside the terms of the EULA
 * is strictly prohibited.
 */
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <utility>
#include <iostream>
#include <bitset>
#include <math.h>
#include <time.h>
#include <chrono>
#include <hip/hip_runtime.h>

/**
 * This macro checks return value of the CUDA runtime call and exits
 * the application if the call failed.
 *
 * See cuda.h for error code descriptions.
 */

#ifndef BLOCK_SIZE
#define BLOCK_SIZE 1024
#endif

#ifndef ELAPSED_TIME
#define ELAPSED_TIME 0
#endif

#ifndef EXP_BITS_SIZE
#define EXP_BITS_SIZE 10
#endif

void print(int* h_data, int n) {
	std::cout << "\n";
	for (int i = 0; i < n; i++) {
		std::cout << h_data[i] << " ";
	}
	std::cout << "\n";
}

void cudaTest(hipError_t error) {
	if (error != hipSuccess) {
		printf("cuda returned error %s (code %d), line(%d)\n",
				hipGetErrorString(error), error, __LINE__);
		exit(EXIT_FAILURE);
	}
}



/*
 * 256 threads per block
 * 4 elements per thread
 * = 1024 elements per block
 * = n/1024 blocks
 */

template<int BITS_NUMBER = 64>
__global__ void radix_sort(int *d_vec, int *d_seg, int num_segments) {

	int bx = blockIdx.x;
	int tx = threadIdx.x;

	int begin = d_seg[bx];
	int end = d_seg[bx + 1];
	int size = end - begin;

	__shared__ int s_vec[BLOCK_SIZE];
	__shared__ int s_aux[BLOCK_SIZE];
	__shared__ int s_pref_sum_one[BLOCK_SIZE];
	__shared__ int s_pref_sum_zero[BLOCK_SIZE];

	for (int k = 0; k < size; k += BLOCK_SIZE) {
		int threadIndexGlobal = begin + k + tx;

		int block = BLOCK_SIZE;
		if(BLOCK_SIZE+k > size)
			block = size-k;

		if (threadIndexGlobal < end) {
			s_vec[tx] = d_vec[threadIndexGlobal];
			__syncthreads();

			int i, j;
			int exp = 0;

			for (j = 0; j < BITS_NUMBER; j++) {

				int x = (s_vec[tx] >> exp) & 1;
				s_pref_sum_one[tx] = x;
				s_pref_sum_zero[tx] = 1-x;
				__syncthreads();

				for (i = 1; i < block; i*=2) {
					int index = tx + i;
					if (index < block) {
						int one = s_pref_sum_one[tx] + s_pref_sum_one[index];
						int zero = s_pref_sum_zero[tx] + s_pref_sum_zero[index];
						__syncthreads();
						s_pref_sum_one[index] = one;
						s_pref_sum_zero[index] = zero;
						__syncthreads();
					}
				}

				x = (s_vec[tx] >> exp) & 1;
				int index = (x) * (s_pref_sum_one[tx] + s_pref_sum_zero[block-1] - 1)
						+ (1 - x) * (s_pref_sum_zero[tx] - 1);
				s_aux[index] = s_vec[tx];
				__syncthreads();

				s_vec[tx] = s_aux[tx];
				__syncthreads();

				exp++;
			}
			d_vec[threadIndexGlobal] = s_aux[tx];
		}
	}
}

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

	int num_of_segments;
	int num_of_elements;
	int i;

	scanf("%d", &num_of_segments);
	int mem_size_seg = sizeof(int) * (num_of_segments + 1);
	int *h_seg = (int *) malloc(mem_size_seg);
	for (i = 0; i < num_of_segments + 1; i++)
		scanf("%d", &h_seg[i]);

	scanf("%d", &num_of_elements);
	int mem_size_vec = sizeof(int) * num_of_elements;
	int *h_vec = (int *) malloc(mem_size_vec);
	for (i = 0; i < num_of_elements; i++)
		scanf("%d", &h_vec[i]);

//	print(h_seg, num_of_segments + 1);	print(h_vec, num_of_elements);

// Allocate device memory
	int *d_seg, *d_vec;

	cudaTest(hipMalloc((void **) &d_seg, mem_size_seg));
	cudaTest(hipMalloc((void **) &d_vec, mem_size_vec));
//cudaTest(cudaMalloc((void **) &d_aux, mem_size_vec));

// copy host memory to device
	cudaTest(hipMemcpy(d_seg, h_seg, mem_size_seg, hipMemcpyHostToDevice));
	cudaTest(hipMemcpy(d_vec, h_vec, mem_size_vec, hipMemcpyHostToDevice));

	// Setup execution parameters
//	int devID = 0;
//	cudaDeviceProp deviceProp;
//	cudaTest(cudaGetDeviceProperties(&deviceProp, devID));
//	unsigned int multiprocessor_number = deviceProp.multiProcessorCount;
//	//unsigned int grid_blocks_max_x = deviceProp.maxGridSize[0];
//	//unsigned int sharedMemoryTotal = deviceProp.sharedMemPerBlock/(sizeof(int));
//
	int blocksize = BLOCK_SIZE; //num_of_elements / num_of_segments;
	//if (blocksize > 1024)
	//	blocksize = 1024;

	dim3 threads(blocksize, 1);
	//dim3 grid(num_of_segments / blocksize + 1, 1);
	dim3 grid(num_of_segments, 1);

	std::chrono::high_resolution_clock::time_point start =
			std::chrono::high_resolution_clock::now();

	radix_sort<EXP_BITS_SIZE> <<<grid, threads>>>(d_vec, d_seg,
			num_of_segments);
	hipDeviceSynchronize();
	std::chrono::high_resolution_clock::time_point stop =
			std::chrono::high_resolution_clock::now();
	cudaTest(hipPeekAtLastError());
	std::chrono::duration<double> time_span = std::chrono::duration_cast<
			std::chrono::duration<double>>(stop - start);

	cudaTest(hipMemcpy(h_seg, d_seg, mem_size_seg, hipMemcpyDeviceToHost));
	cudaTest(hipMemcpy(h_vec, d_vec, mem_size_vec, hipMemcpyDeviceToHost));

	//print(h_seg, num_of_segments + 1);
	//print(h_vec, num_of_elements);
	//print(h_seg, 10);
	//print(h_vec, 1000);
	if (ELAPSED_TIME == 1)
//		std::cout << "It took me " << time_span.count() * 1000
//				<< " miliseconds.\n";
		;
	else
		print(h_vec, num_of_elements);

	// cudaDeviceReset causes the driver to clean up all state. While
	// not mandatory in normal operation, it is good practice.  It is also
	// needed to ensure correct operation when the application is being
	// profiled. Calling cudaDeviceReset causes all profile data to be
	// flushed before the application exits
	hipDeviceReset();

	free(h_seg);
	free(h_vec);
	hipFree(d_seg);
	hipFree(d_vec);

	return 0;
}

/**
 * 	// cudaDeviceReset causes the driver to clean up all state. While
 // not mandatory in normal operation, it is good practice.  It is also
 // needed to ensure correct operation when the application is being
 // profiled. Calling cudaDeviceReset causes all profile data to be
 // flushed before the application exits
 cudaDeviceReset();
 */

/*
 printf("thread=%d | aux=%d %d %d %d\n", bx * blockDim.x + tx, d_aux[begin], d_aux[begin + 1], d_aux[begin + 2],	d_aux[begin + 3]);
 int devID = 0;
 cudaDeviceProp deviceProp;
 cudaTest(cudaGetDeviceProperties(&deviceProp, devID));
 unsigned int multiprocessorNumber = deviceProp.multiProcessorCount;
 unsigned int sharedMemoryTotal = deviceProp.sharedMemPerBlock/(sizeof(int));
 std::cout << "multiprocessorNumber: " << multiprocessorNumber << "\n";
 std::cout << "sharedMemoryTotal: " << sharedMemoryTotal << "\n";
 std::cout << "numberOfSegmentsPerBlock: " << sharedMemoryTotal << "\n";
 */

	.text
	.file	"sharev1.hip"
                                        # Start of file scope inline assembly
	.globl	_ZSt21ios_base_library_initv

                                        # End of file scope inline assembly
	.globl	_Z5printPii                     # -- Begin function _Z5printPii
	.type	_Z5printPii,@function
_Z5printPii:                            # @_Z5printPii
	.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	%rbx
	.cfi_def_cfa_offset 40
	pushq	%rax
	.cfi_def_cfa_offset 48
	.cfi_offset %rbx, -40
	.cfi_offset %r14, -32
	.cfi_offset %r15, -24
	.cfi_offset %rbp, -16
	movl	%esi, %ebp
	movq	%rdi, %rbx
	movl	$_ZSt4cout, %edi
	movl	$.L.str, %esi
	movl	$1, %edx
	callq	_ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_PKS3_l
	testl	%ebp, %ebp
	jle	.LBB0_3
# %bb.1:                                # %.lr.ph.preheader
	movl	%ebp, %r14d
	xorl	%r15d, %r15d
.LBB0_2:                                # %.lr.ph
                                        # =>This Inner Loop Header: Depth=1
	movl	(%rbx,%r15,4), %esi
	movl	$_ZSt4cout, %edi
	callq	_ZNSolsEi
	movl	$.L.str.1, %esi
	movl	$1, %edx
	movq	%rax, %rdi
	callq	_ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_PKS3_l
	incq	%r15
	cmpq	%r15, %r14
	jne	.LBB0_2
.LBB0_3:                                # %._crit_edge
	movl	$_ZSt4cout, %edi
	movl	$.L.str, %esi
	movl	$1, %edx
	addq	$8, %rsp
	.cfi_def_cfa_offset 40
	popq	%rbx
	.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
	jmp	_ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_PKS3_l # TAILCALL
.Lfunc_end0:
	.size	_Z5printPii, .Lfunc_end0-_Z5printPii
	.cfi_endproc
                                        # -- End function
	.globl	_Z8cudaTest10hipError_t         # -- Begin function _Z8cudaTest10hipError_t
	.type	_Z8cudaTest10hipError_t,@function
_Z8cudaTest10hipError_t:                # @_Z8cudaTest10hipError_t
	.cfi_startproc
# %bb.0:
	testl	%edi, %edi
	jne	.LBB1_2
# %bb.1:
	retq
.LBB1_2:
	pushq	%rbx
	.cfi_def_cfa_offset 16
	.cfi_offset %rbx, -16
	movl	%edi, %ebx
	callq	hipGetErrorString
	movl	$.L.str.2, %edi
	movq	%rax, %rsi
	movl	%ebx, %edx
	movl	$51, %ecx
	xorl	%eax, %eax
	callq	printf
	movl	$1, %edi
	callq	exit
.Lfunc_end1:
	.size	_Z8cudaTest10hipError_t, .Lfunc_end1-_Z8cudaTest10hipError_t
	.cfi_endproc
                                        # -- End function
	.globl	main                            # -- Begin function 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	$24, %rsp
	.cfi_def_cfa_offset 80
	.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	%rsp, %rbx
	movl	$.L.str.3, %edi
	movq	%rbx, %rsi
	xorl	%eax, %eax
	callq	__isoc23_scanf
	movl	(%rbx), %r15d
	leal	4(,%r15,4), %eax
	movslq	%eax, %r14
	movq	%r14, %rdi
	callq	malloc
	movq	%rax, %rbx
	testl	%r15d, %r15d
	js	.LBB2_3
# %bb.1:                                # %.lr.ph.preheader
	movq	$-1, %r12
	movq	%rbx, %r15
.LBB2_2:                                # %.lr.ph
                                        # =>This Inner Loop Header: Depth=1
	movl	$.L.str.3, %edi
	movq	%r15, %rsi
	xorl	%eax, %eax
	callq	__isoc23_scanf
	movslq	(%rsp), %rax
	incq	%r12
	addq	$4, %r15
	cmpq	%rax, %r12
	jl	.LBB2_2
.LBB2_3:                                # %._crit_edge
	leaq	4(%rsp), %r15
	movl	$.L.str.3, %edi
	movq	%r15, %rsi
	xorl	%eax, %eax
	callq	__isoc23_scanf
	movl	(%r15), %r13d
	leal	(,%r13,4), %eax
	movslq	%eax, %r12
	movq	%r12, %rdi
	callq	malloc
	movq	%rax, %r15
	testl	%r13d, %r13d
	jle	.LBB2_6
# %bb.4:                                # %.lr.ph40.preheader
	movq	%r15, %r13
	xorl	%ebp, %ebp
.LBB2_5:                                # %.lr.ph40
                                        # =>This Inner Loop Header: Depth=1
	movl	$.L.str.3, %edi
	movq	%r13, %rsi
	xorl	%eax, %eax
	callq	__isoc23_scanf
	incq	%rbp
	movslq	4(%rsp), %rax
	addq	$4, %r13
	cmpq	%rax, %rbp
	jl	.LBB2_5
.LBB2_6:                                # %._crit_edge41
	leaq	16(%rsp), %r13
	movq	%r13, %rdi
	movq	%r14, %rsi
	callq	hipMalloc
	movl	%eax, %edi
	callq	_Z8cudaTest10hipError_t
	leaq	8(%rsp), %rbp
	movq	%rbp, %rdi
	movq	%r12, %rsi
	callq	hipMalloc
	movl	%eax, %edi
	callq	_Z8cudaTest10hipError_t
	movq	(%r13), %rdi
	movq	%rbx, %rsi
	movq	%r14, %rdx
	movl	$1, %ecx
	callq	hipMemcpy
	movl	%eax, %edi
	callq	_Z8cudaTest10hipError_t
	movq	(%rbp), %rdi
	movq	%r15, %rsi
	movq	%r12, %rdx
	movl	$1, %ecx
	callq	hipMemcpy
	movl	%eax, %edi
	callq	_Z8cudaTest10hipError_t
	movl	(%rsp), %r13d
	btsq	$32, %r13
	callq	_ZNSt6chrono3_V212system_clock3nowEv
	movabsq	$4294967296, %rdx               # imm = 0x100000000
	orq	$1024, %rdx                     # imm = 0x400
	movq	%r13, %rdi
	movl	$1, %esi
	movl	$1, %ecx
	xorl	%r8d, %r8d
	xorl	%r9d, %r9d
	callq	__hipPushCallConfiguration
	testl	%eax, %eax
	jne	.LBB2_8
# %bb.7:
	movq	8(%rsp), %rdi
	movq	16(%rsp), %rsi
	movl	(%rsp), %edx
	callq	_Z25__device_stub__radix_sortILi10EEvPiS0_i
.LBB2_8:
	callq	hipDeviceSynchronize
	callq	_ZNSt6chrono3_V212system_clock3nowEv
	callq	hipPeekAtLastError
	movl	%eax, %edi
	callq	_Z8cudaTest10hipError_t
	movq	16(%rsp), %rsi
	movq	%rbx, %rdi
	movq	%r14, %rdx
	movl	$2, %ecx
	callq	hipMemcpy
	movl	%eax, %edi
	callq	_Z8cudaTest10hipError_t
	movq	8(%rsp), %rsi
	movq	%r15, %rdi
	movq	%r12, %rdx
	movl	$2, %ecx
	callq	hipMemcpy
	movl	%eax, %edi
	callq	_Z8cudaTest10hipError_t
	movl	4(%rsp), %esi
	movq	%r15, %rdi
	callq	_Z5printPii
	callq	hipDeviceReset
	movq	%rbx, %rdi
	callq	free
	movq	%r15, %rdi
	callq	free
	movq	16(%rsp), %rdi
	callq	hipFree
	movq	8(%rsp), %rdi
	callq	hipFree
	xorl	%eax, %eax
	addq	$24, %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	main, .Lfunc_end2-main
	.cfi_endproc
                                        # -- End function
	.section	.text._Z25__device_stub__radix_sortILi10EEvPiS0_i,"axG",@progbits,_Z25__device_stub__radix_sortILi10EEvPiS0_i,comdat
	.weak	_Z25__device_stub__radix_sortILi10EEvPiS0_i # -- Begin function _Z25__device_stub__radix_sortILi10EEvPiS0_i
	.type	_Z25__device_stub__radix_sortILi10EEvPiS0_i,@function
_Z25__device_stub__radix_sortILi10EEvPiS0_i: # @_Z25__device_stub__radix_sortILi10EEvPiS0_i
	.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	$_Z10radix_sortILi10EEvPiS0_i, %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_end3:
	.size	_Z25__device_stub__radix_sortILi10EEvPiS0_i, .Lfunc_end3-_Z25__device_stub__radix_sortILi10EEvPiS0_i
	.cfi_endproc
                                        # -- End function
	.text
	.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	$_Z10radix_sortILi10EEvPiS0_i, %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	"\n"
	.size	.L.str, 2

	.type	.L.str.1,@object                # @.str.1
.L.str.1:
	.asciz	" "
	.size	.L.str.1, 2

	.type	.L.str.2,@object                # @.str.2
.L.str.2:
	.asciz	"cuda returned error %s (code %d), line(%d)\n"
	.size	.L.str.2, 44

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

	.type	_Z10radix_sortILi10EEvPiS0_i,@object # @_Z10radix_sortILi10EEvPiS0_i
	.section	.rodata._Z10radix_sortILi10EEvPiS0_i,"aG",@progbits,_Z10radix_sortILi10EEvPiS0_i,comdat
	.weak	_Z10radix_sortILi10EEvPiS0_i
	.p2align	3, 0x0
_Z10radix_sortILi10EEvPiS0_i:
	.quad	_Z25__device_stub__radix_sortILi10EEvPiS0_i
	.size	_Z10radix_sortILi10EEvPiS0_i, 8

	.type	.L__unnamed_1,@object           # @0
	.section	.rodata.str1.1,"aMS",@progbits,1
.L__unnamed_1:
	.asciz	"_Z10radix_sortILi10EEvPiS0_i"
	.size	.L__unnamed_1, 29

	.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

	.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 _Z25__device_stub__radix_sortILi10EEvPiS0_i
	.addrsig_sym __hip_module_ctor
	.addrsig_sym __hip_module_dtor
	.addrsig_sym _ZSt4cout
	.addrsig_sym _Z10radix_sortILi10EEvPiS0_i
	.addrsig_sym __hip_fatbin
	.addrsig_sym __hip_fatbin_wrapper
	.addrsig_sym __hip_cuid_

	.text
	.amdgcn_target "amdgcn-amd-amdhsa--gfx1100"
	.section	.text._Z10radix_sortILi10EEvPiS0_i,"axG",@progbits,_Z10radix_sortILi10EEvPiS0_i,comdat
	.protected	_Z10radix_sortILi10EEvPiS0_i ; -- Begin function _Z10radix_sortILi10EEvPiS0_i
	.globl	_Z10radix_sortILi10EEvPiS0_i
	.p2align	8
	.type	_Z10radix_sortILi10EEvPiS0_i,@function
_Z10radix_sortILi10EEvPiS0_i:           ; @_Z10radix_sortILi10EEvPiS0_i
; %bb.0:
	s_load_b128 s[0:3], s[0:1], 0x0
	s_mov_b32 s4, s15
	s_ashr_i32 s5, s15, 31
	s_delay_alu instid0(SALU_CYCLE_1)
	s_lshl_b64 s[4:5], s[4:5], 2
	s_waitcnt lgkmcnt(0)
	s_add_u32 s2, s2, s4
	s_addc_u32 s3, s3, s5
	s_load_b64 s[2:3], s[2:3], 0x0
	s_waitcnt lgkmcnt(0)
	s_sub_i32 s4, s3, s2
	s_delay_alu instid0(SALU_CYCLE_1)
	s_cmp_lt_i32 s4, 1
	s_cbranch_scc1 .LBB0_12
; %bb.1:                                ; %.lr.ph72
	v_lshlrev_b32_e32 v3, 2, v0
	v_add_nc_u32_e32 v4, s2, v0
	s_mov_b32 s6, 0
	s_delay_alu instid0(VALU_DEP_2)
	v_or_b32_e32 v5, 0x3000, v3
	v_or_b32_e32 v6, 0x1000, v3
	v_or_b32_e32 v7, 0x2000, v3
.LBB0_2:                                ; =>This Loop Header: Depth=1
                                        ;     Child Loop BB0_4 Depth 2
                                        ;       Child Loop BB0_6 Depth 3
	v_add_nc_u32_e32 v1, s6, v4
	s_add_i32 s2, s6, 0x400
	s_mov_b32 s5, exec_lo
	s_delay_alu instid0(VALU_DEP_1)
	v_cmpx_gt_i32_e64 s3, v1
	s_cbranch_execz .LBB0_11
; %bb.3:                                ;   in Loop: Header=BB0_2 Depth=1
	v_ashrrev_i32_e32 v2, 31, v1
	s_sub_i32 s6, s4, s6
	s_cmp_gt_i32 s2, s4
	s_mov_b32 s8, 0
	s_cselect_b32 s6, s6, 0x400
	v_lshlrev_b64 v[1:2], 2, v[1:2]
	s_cmp_gt_i32 s6, 1
	s_cselect_b32 s7, -1, 0
	s_lshl_b32 s9, s6, 2
	s_delay_alu instid0(SALU_CYCLE_1) | instskip(NEXT) | instid1(VALU_DEP_1)
	s_addk_i32 s9, 0xffc
	v_add_co_u32 v1, vcc_lo, s0, v1
	v_add_co_ci_u32_e32 v2, vcc_lo, s1, v2, vcc_lo
	v_mov_b32_e32 v8, s9
	global_load_b32 v9, v[1:2], off
	s_waitcnt vmcnt(0)
	ds_store_b32 v5, v9
	s_waitcnt lgkmcnt(0)
	s_waitcnt_vscnt null, 0x0
	s_barrier
	buffer_gl0_inv
.LBB0_4:                                ;   Parent Loop BB0_2 Depth=1
                                        ; =>  This Loop Header: Depth=2
                                        ;       Child Loop BB0_6 Depth 3
	ds_load_b32 v9, v5
	s_and_not1_b32 vcc_lo, exec_lo, s7
	s_waitcnt lgkmcnt(0)
	v_bfe_u32 v9, v9, s8, 1
	s_delay_alu instid0(VALU_DEP_1)
	v_xor_b32_e32 v10, 1, v9
	ds_store_b32 v3, v9
	ds_store_b32 v6, v10
	s_waitcnt lgkmcnt(0)
	s_barrier
	buffer_gl0_inv
	s_cbranch_vccnz .LBB0_9
; %bb.5:                                ; %.lr.ph.preheader
                                        ;   in Loop: Header=BB0_4 Depth=2
	s_mov_b32 s9, 1
.LBB0_6:                                ; %.lr.ph
                                        ;   Parent Loop BB0_2 Depth=1
                                        ;     Parent Loop BB0_4 Depth=2
                                        ; =>    This Inner Loop Header: Depth=3
	s_delay_alu instid0(SALU_CYCLE_1) | instskip(SKIP_1) | instid1(VALU_DEP_1)
	v_add_nc_u32_e32 v9, s9, v0
	s_mov_b32 s10, exec_lo
	v_cmpx_gt_i32_e64 s6, v9
	s_cbranch_execz .LBB0_8
; %bb.7:                                ;   in Loop: Header=BB0_6 Depth=3
	s_lshl_b32 s11, s9, 2
	s_delay_alu instid0(SALU_CYCLE_1)
	v_add_nc_u32_e32 v9, s11, v6
	v_add_nc_u32_e32 v10, s11, v3
	ds_load_b32 v11, v3
	ds_load_b32 v12, v9
	ds_load_b32 v13, v10
	ds_load_b32 v14, v6
	s_waitcnt lgkmcnt(0)
	s_barrier
	buffer_gl0_inv
	v_add_nc_u32_e32 v11, v13, v11
	v_add_nc_u32_e32 v12, v12, v14
	ds_store_b32 v10, v11
	ds_store_b32 v9, v12
	s_waitcnt lgkmcnt(0)
	s_barrier
	buffer_gl0_inv
.LBB0_8:                                ;   in Loop: Header=BB0_6 Depth=3
	s_or_b32 exec_lo, exec_lo, s10
	s_lshl_b32 s9, s9, 1
	s_delay_alu instid0(SALU_CYCLE_1)
	s_cmp_lt_i32 s9, s6
	s_cbranch_scc1 .LBB0_6
.LBB0_9:                                ; %._crit_edge
                                        ;   in Loop: Header=BB0_4 Depth=2
	ds_load_b32 v9, v5
	ds_load_b32 v10, v3
	ds_load_b32 v11, v8
	ds_load_b32 v12, v6
	s_waitcnt lgkmcnt(3)
	v_bfe_u32 v13, v9, s8, 1
	s_add_i32 s8, s8, 1
	s_waitcnt lgkmcnt(1)
	v_add3_u32 v10, v10, v11, -1
	s_waitcnt lgkmcnt(0)
	v_add_nc_u32_e32 v11, -1, v12
	s_cmp_lg_u32 s8, 10
	v_xor_b32_e32 v12, 1, v13
	v_mul_lo_u32 v10, v10, v13
	s_delay_alu instid0(VALU_DEP_2) | instskip(NEXT) | instid1(VALU_DEP_1)
	v_mul_lo_u32 v11, v11, v12
	v_add_lshl_u32 v10, v11, v10, 2
	ds_store_b32 v10, v9 offset:8192
	s_waitcnt lgkmcnt(0)
	s_barrier
	buffer_gl0_inv
	ds_load_b32 v9, v7
	s_waitcnt lgkmcnt(0)
	ds_store_b32 v5, v9
	s_waitcnt lgkmcnt(0)
	s_barrier
	buffer_gl0_inv
	s_cbranch_scc1 .LBB0_4
; %bb.10:                               ;   in Loop: Header=BB0_2 Depth=1
	ds_load_b32 v8, v7
	s_waitcnt lgkmcnt(0)
	global_store_b32 v[1:2], v8, off
.LBB0_11:                               ; %Flow80
                                        ;   in Loop: Header=BB0_2 Depth=1
	s_or_b32 exec_lo, exec_lo, s5
	s_cmp_ge_i32 s2, s4
	s_mov_b32 s6, s2
	s_cbranch_scc0 .LBB0_2
.LBB0_12:                               ; %._crit_edge73
	s_nop 0
	s_sendmsg sendmsg(MSG_DEALLOC_VGPRS)
	s_endpgm
	.section	.rodata,"a",@progbits
	.p2align	6, 0x0
	.amdhsa_kernel _Z10radix_sortILi10EEvPiS0_i
		.amdhsa_group_segment_fixed_size 16384
		.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 15
		.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
	.section	.text._Z10radix_sortILi10EEvPiS0_i,"axG",@progbits,_Z10radix_sortILi10EEvPiS0_i,comdat
.Lfunc_end0:
	.size	_Z10radix_sortILi10EEvPiS0_i, .Lfunc_end0-_Z10radix_sortILi10EEvPiS0_i
                                        ; -- End function
	.section	.AMDGPU.csdata,"",@progbits
; Kernel info:
; codeLenInByte = 680
; NumSgprs: 18
; NumVgprs: 15
; ScratchSize: 0
; MemoryBound: 0
; FloatMode: 240
; IeeeMode: 1
; LDSByteSize: 16384 bytes/workgroup (compile time only)
; SGPRBlocks: 2
; VGPRBlocks: 1
; NumSGPRsForWavesPerEU: 18
; NumVGPRsForWavesPerEU: 15
; Occupancy: 16
; WaveLimiterHint : 1
; 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: 16384
    .kernarg_segment_align: 8
    .kernarg_segment_size: 20
    .language:       OpenCL C
    .language_version:
      - 2
      - 0
    .max_flat_workgroup_size: 1024
    .name:           _Z10radix_sortILi10EEvPiS0_i
    .private_segment_fixed_size: 0
    .sgpr_count:     18
    .sgpr_spill_count: 0
    .symbol:         _Z10radix_sortILi10EEvPiS0_i.kd
    .uniform_work_group_size: 1
    .uses_dynamic_stack: false
    .vgpr_count:     15
    .vgpr_spill_count: 0
    .wavefront_size: 32
    .workgroup_processor_mode: 1
amdhsa.target:   amdgcn-amd-amdhsa--gfx1100
amdhsa.version:
  - 1
  - 2
...

	.end_amdgpu_metadata
