#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "sys/time.h"

#define DefNumPD 517	// Default Number of Points per Dimension
#define DefNumI 10		// Default Number of Iterations
#define DefExp 0		// Default Value to Export Data (0 = None, 1 = All, 2 = Last)

enum Data_Types { CHAR_TYPE, INT_TYPE, FLOAT_TYPE, DOUBLE_TYPE };

char* input_file = NULL;
int npd = DefNumPD;	// Number of Points per Dimension
int nk = DefNumI;	// Number of Iterations
int expi = DefExp;	// Export Data

struct timeval startwtime, endwtime;

void ising(int* G, double* w, int k, int n);
void help(int argc, char* argv[]);
void export_data(int* G, int elemNum);
void import_data(int* G);

int main(int argc, char* argv[])
{
	help(argc, argv);
	printf("Running with values n=%i, k=%i, o=%i\n", npd, nk, expi);

	srand((unsigned int)time(NULL));
	double p_time;

	// Generate random/Import point set
	int* G = (int*)malloc(npd * npd * sizeof(int));
	if (input_file == NULL) {
		printf("Generating random data set. ");
		gettimeofday(&startwtime, NULL);

		for (int i = 0; i < npd * npd; i++) {
			if (rand() < (RAND_MAX) / 2)
				*(G + i) = -1;
			else
				*(G + i) = 1;
		}
		gettimeofday(&endwtime, NULL);
		p_time = (double)((endwtime.tv_usec - startwtime.tv_usec) / 1.0e6 + endwtime.tv_sec - startwtime.tv_sec);
		printf("DONE in %fsec!\n", p_time);
	}
	else {
		gettimeofday(&startwtime, NULL);
		import_data(G);
		p_time = (double)((endwtime.tv_usec - startwtime.tv_usec) / 1.0e6 + endwtime.tv_sec - startwtime.tv_sec);
		printf("DONE in %fsec!\n", p_time);
	}

	double weight_matrix[5][5] = { {0.004, 0.016, 0.026, 0.016, 0.004},
									{0.016, 0.071, 0.117, 0.071, 0.016},
									{0.026, 0.117, 0.000, 0.117, 0.026},
									{0.016, 0.071, 0.117, 0.071, 0.016},
									{0.004, 0.016, 0.026, 0.016, 0.004} };

	// Run Ising model evolution
	printf("Running Ising Model Evolution. ");
	gettimeofday(&startwtime, NULL);
	if (!expi) {
		ising(G, &weight_matrix[0][0], nk, npd);
		gettimeofday(&endwtime, NULL);
		p_time = (double)((endwtime.tv_usec - startwtime.tv_usec) / 1.0e6 + endwtime.tv_sec - startwtime.tv_sec);
		printf("DONE in %fsec!\n", p_time);
	}
	else if (expi == 1) {	// export data
		printf("Saving data of each iteration. ");
		int* G_out = (int*)malloc(npd * npd * (nk + 1) * sizeof(int));
		memcpy(G_out, G, npd * npd * sizeof(int));	// copy data to export them later		
		for (int i = 1; i < (nk + 1); i++) {	// save data of each iteration to export them for animation
			ising(G, &weight_matrix[0][0], 1, npd);
			memcpy((G_out + i * npd * npd), G, npd * npd * sizeof(int));	// copy data to export them later			
		}
		//  Export data to output.bin
		export_data(G_out, npd * npd * (nk + 1));
		p_time = (double)((endwtime.tv_usec - startwtime.tv_usec) / 1.0e6 + endwtime.tv_sec - startwtime.tv_sec);
		printf("DONE in %fsec!\n", p_time);
		free(G_out);
	}
	else {
		ising(G, &weight_matrix[0][0], nk, npd);
		printf("Saving last iteration. ");
		export_data(G, npd * npd);
		p_time = (double)((endwtime.tv_usec - startwtime.tv_usec) / 1.0e6 + endwtime.tv_sec - startwtime.tv_sec);
		printf("DONE in %fsec!\n", p_time);
	}

	printf("Exiting\n");
	free(G);
	return 0;
}

void help(int argc, char* argv[])
{
	if (argc > 1) {
		for (int i = 1; i < argc; i += 2) {
			if (*argv[i] == '-') {
				if (*(argv[i] + 1) == 'f')
					input_file = argv[i + 1];
				else if (*(argv[i] + 1) == 'n')
					npd = atoi(argv[i + 1]);
				else if (*(argv[i] + 1) == 'k')
					nk = atoi(argv[i + 1]);
				else if (*(argv[i] + 1) == 'o')
					expi = atoi(argv[i + 1]);
			}
			else {
				help(1, argv);
				return;
			}
		}
		return;
	}
	printf("Flags to use:\n");
	printf("-f [File]\t:Input file of points\n");
	printf("-n [Number]\t:Number of points per dimension (default:%i)\n", DefNumPD);
	printf("-k [Iterations]\t:Number of iterations (default: %i)\n", DefNumI);
	printf("-o [0|1|2]\t:Export each iteration to output*.bin (0 = None(default), 1 = All, 2 = Last)\n");

}

void export_data(int* G, int totalSize)
{
	int tmp_k = nk + 1;
	char* out_file_name = (char*)calloc(100, sizeof(char));
	if (expi == 2)
		sprintf(out_file_name, "output-%i-%i-1.bin", npd, tmp_k);
	else
		sprintf(out_file_name, "output-%i-%i.bin", npd, tmp_k);
	printf("Exporting data to %s. ", out_file_name);
	FILE* f = fopen(out_file_name, "wb");
	fwrite(G, sizeof(int), totalSize, f);
	fclose(f);
	free(out_file_name);
}

void import_data(int* G)
{
	printf("Importing data from %s. ", input_file);
	FILE* f = fopen(input_file, "rb");
	fread(G, sizeof(int), npd * npd, f);
	fclose(f);
}

//////////////// Ising Code Here ////////////////
#include <cuda.h>
#include <cuda_runtime.h>
#include <device_launch_parameters.h>

#define WeightMatDim 5	// Weight Matrix Dimension
#define FloatError 1e-6	// Float error
#define TileSize 32		// Size of tiles partitioning the matrix - each tile calculates TileSize x TileSize moments
#define NumberOfRows 8	// Rows of each block of threads - each block is of size NumberOfRows x TileSi
#define RowsHelping (NumberOfRows + 4)	// Rows of global memory to be loaded into shared (for the exercise NumberOfRows + 4)
#define ColumnsHelping (TileSize + 4)	// Columns of global memory to be loaded into shared (for the exercise TileSize + 4)


__global__ void calculateFrameShared(int* G_d, int* GNext_d, double* w_d, int n, int* same_matrix_d)
{
	__shared__ double w_s[25]; // Shared matrix to hold weight table and accelerate access
	__shared__ int g_s[RowsHelping][ColumnsHelping]; // Shared matrix to hold moments needed for the current iteration

	// Copy w_d matrix from global to shared memory with optimal access of the former
	// as far as warps are concerned - indexing used is based only on block dims

	if ((threadIdx.x < 25) && (threadIdx.y == 0)) // Use only 25 initial threads of the first warp
		w_s[threadIdx.x] = w_d[threadIdx.x];

	/* Initialize thread coordinates to be used for global memory access*/
	int x = blockIdx.x * TileSize + threadIdx.x;
	int y = blockIdx.y * TileSize + threadIdx.y;

	// Do as many time needed to cover the whole area assigned to the block
	// Copy block elements for current iteration from global memory to shared in a warp
	// oriented manner copying a whole block of size [(NumberOfRows+4) x (TileSize+4)] in order to 
	// transfer all elements accessed during the iteration and thus gain in speed of execution

	for (int j = 0; j < TileSize; j += NumberOfRows) { // for every block chunk of tile in the y axis
		int counterY = 0; // variable to help with accessing rows of G_d table for copying
		// Copying moments for iteration j into shared memory
		for (int helperY = threadIdx.y; helperY < RowsHelping; helperY += NumberOfRows) { // for every row of the subtile to be loaded 		
			int counterX = 0; // variable to help with accessing columns of G_d table for copying
			int rowNumber = (y - 2 + counterY * NumberOfRows + n) % n; // Current Row of G_d to be dereferenced
			for (int helperX = threadIdx.x; helperX < ColumnsHelping; helperX += TileSize) {
				int columnNumber = (x - 2 + counterX * TileSize + n) % n; // Current Column of G_d to be dereferenced				
				g_s[helperY][helperX] = G_d[rowNumber * n + columnNumber]; // Dereference G_d and copy to shared memory
				++counterX; // increase helper counter for columns
			}
			++counterY; // increase helper counter for rows
		}
		__syncthreads(); // waiting for all threads to be done

		// Evaluating moments in subblock through g_s and w_s matrices
		if (x < n) {  // Check whether thread x coordinate is out of bounds
			if (y < n) { // Check whether thread y coordinate is out of bounds
				double influence = 0.0; // weighted influence of neighbors
				for (int i = -2; i <= 2; i++) {	// for every row of weight matrix
					int r = threadIdx.y + 2 + i;	// add 2 to y coordinate as is in block manner to "center" block in g_s dereferencing
					for (int t = -2; t <= 2; t++) {	// for every weight of a row in weight matrix
						int c = threadIdx.x + 2 + t;	// add 2 to x coordinate as is in block manner to "center" block in g_s dereferencing
						influence += g_s[r][c] * w_s[(i + 2) * WeightMatDim + (t + 2)];	// +2 cause of the i and t offset
					}// for t < WeightMatDim
				}// for i < WeightMatDim

				/*Update state for current point*/
				if (influence > FloatError)			// apply threshold for floating point error
					*(GNext_d + y * n + x) = 1;
				else if (influence < -FloatError)	// apply threshold for floating point error
					*(GNext_d + y * n + x) = -1;
				else								// stay the same
					*(GNext_d + y * n + x) = g_s[threadIdx.y + 2][threadIdx.x + 2];

				// Did the magnetic moment changed?
				if (*(GNext_d + y * n + x) != g_s[threadIdx.y + 2][threadIdx.x + 2])
					*same_matrix_d = 0;
			} // if (y < n)
		} // if (x < n)

		y += NumberOfRows; // Update y coordinate as we move down the tile
		__syncthreads(); // Synchronize threads for next iterartion
	} // for (j < TileSize)
}

void ising(int* G, double* w, int k, int n)
{
	/*Declare and initialize memory to use on device*/
	int* G_d, * GNext_d; double* w_d; // Pointers to use for matrix store on device
	int* same_matrix_d;	// device parameter to hold if iterations should proceed
	int same_matrix = 1;	// corresponding host parameter

	cudaMalloc((void**)&G_d, n * n * sizeof(int));
	cudaMalloc((void**)&GNext_d, n * n * sizeof(int));
	cudaMalloc((void**)&w_d, WeightMatDim * WeightMatDim * sizeof(double));
	cudaMalloc((void**)&same_matrix_d, sizeof(int));

	/*Create streams to overlap data transfers and gain in speed*/
	cudaStream_t stream1;
	cudaStream_t stream2;
	cudaStreamCreate(&stream1);
	cudaStreamCreate(&stream2);
	
	// Copy data
	cudaMemcpyAsync(G_d, G, n * n * sizeof(int), cudaMemcpyHostToDevice,stream1);     
	cudaMemcpyAsync(GNext_d, G, n * n * sizeof(int), cudaMemcpyHostToDevice,stream2);
	cudaMemcpy(w_d, w, WeightMatDim * WeightMatDim * sizeof(double), cudaMemcpyHostToDevice);

	// Destroy streams
	cudaStreamDestroy(stream1); 
	cudaStreamDestroy(stream2);

	/*Declare grid and block sizes and compensate for matrix not divided with block size*/
	dim3 dimBlock(TileSize, NumberOfRows);
	dim3 dimGrid((n + TileSize - 1) / TileSize, (n + TileSize - 1) / TileSize);

	/*--------------------------------------------------------------------------------*/
	for (int i = 0; i < k; ++i) { // For every iteration
		same_matrix = 1;
		cudaMemcpy(same_matrix_d, &same_matrix, sizeof(int), cudaMemcpyHostToDevice);
		calculateFrameShared <<< dimGrid, dimBlock >>> (G_d, GNext_d, w_d, n, same_matrix_d);

		cudaMemcpy(&same_matrix, same_matrix_d, sizeof(int), cudaMemcpyDeviceToHost); // Kernel to get flag indicating whether matrices are the same

		// Swap pointers
		int* ptri = G_d;
		G_d = GNext_d;
		GNext_d = ptri;

		// Exit if nothing changed
		if (same_matrix) {
			printf("Finished at %ith iteration. ", i);
			cudaFree(GNext_d);
			cudaFree(w_d);
			break;
		}
	}  // for every i < k

	// copy data from device and cleanup
	cudaMemcpy(G, G_d, n * n * sizeof(int), cudaMemcpyDeviceToHost);
	cudaFree(G_d);
}
/////////////////////////////////////////////////
	.file	"tmpxft_0022ee8a_00000000-6_kernel.cudafe1.cpp"
	.text
#APP

#NO_APP
	.type	_ZL26__cudaUnregisterBinaryUtilv, @function
_ZL26__cudaUnregisterBinaryUtilv:
.LFB2034:
	.cfi_startproc
	endbr64
	movq	_ZL20__cudaFatCubinHandle(%rip), %rdi
	jmp	__cudaUnregisterFatBinary@PLT
	.cfi_endproc
.LFE2034:
	.size	_ZL26__cudaUnregisterBinaryUtilv, .-_ZL26__cudaUnregisterBinaryUtilv
	.section	.rodata.str1.1,"aMS",@progbits,1
.LC1:
	.string	"Flags to use:\n"
.LC2:
	.string	"-f [File]\t:Input file of points\n"
.LC3:
	.string	"-n [Number]\t:Number of points per dimension (default:%i)\n"
.LC4:
	.string	"-k [Iterations]\t:Number of iterations (default: %i)\n"
.LC5:
	.string	"-o [0|1|2]\t:Export each iteration to output*.bin (0 = None(default), 1 = All, 2 = Last)\n"
	.text
	.globl	_Z4helpiPPc
	.type	_Z4helpiPPc, @function
_Z4helpiPPc:
.LFB2028:
	.cfi_startproc
	endbr64
	pushq	%r12
	.cfi_def_cfa_offset 16
	.cfi_offset 12, -16
	pushq	%rbp
	.cfi_def_cfa_offset 24
	.cfi_offset 6, -24
	pushq	%rbx
	.cfi_def_cfa_offset 32
	.cfi_offset 3, -32
	cmpl	$1, %edi
	jle	.L3
	movl	%edi, %r12d
	movq	%rsi, %rbp
	movl	$1, %ebx
.L8:
	movq	0(%rbp,%rbx,8), %rax
	cmpb	$45, (%rax)
	jne	.L3
	movb	1(%rax), %al
	cmpb	$102, %al
	jne	.L4
	movq	8(%rbp,%rbx,8), %rax
	movq	%rax, input_file(%rip)
	jmp	.L5
.L4:
	cmpb	$110, %al
	jne	.L6
	movq	8(%rbp,%rbx,8), %rdi
	call	atoi@PLT
	movl	%eax, npd(%rip)
	jmp	.L5
.L6:
	cmpb	$107, %al
	jne	.L7
	movq	8(%rbp,%rbx,8), %rdi
	call	atoi@PLT
	movl	%eax, nk(%rip)
	jmp	.L5
.L7:
	cmpb	$111, %al
	jne	.L5
	movq	8(%rbp,%rbx,8), %rdi
	call	atoi@PLT
	movl	%eax, expi(%rip)
.L5:
	addq	$2, %rbx
	cmpl	%ebx, %r12d
	jg	.L8
	popq	%rbx
	.cfi_remember_state
	.cfi_def_cfa_offset 24
	popq	%rbp
	.cfi_def_cfa_offset 16
	popq	%r12
	.cfi_def_cfa_offset 8
	ret
.L3:
	.cfi_restore_state
	leaq	.LC1(%rip), %rsi
	movl	$2, %edi
	xorl	%eax, %eax
	call	__printf_chk@PLT
	leaq	.LC2(%rip), %rsi
	movl	$2, %edi
	xorl	%eax, %eax
	call	__printf_chk@PLT
	movl	$517, %edx
	leaq	.LC3(%rip), %rsi
	xorl	%eax, %eax
	movl	$2, %edi
	call	__printf_chk@PLT
	leaq	.LC4(%rip), %rsi
	movl	$2, %edi
	xorl	%eax, %eax
	movl	$10, %edx
	call	__printf_chk@PLT
	popq	%rbx
	.cfi_def_cfa_offset 24
	leaq	.LC5(%rip), %rsi
	popq	%rbp
	.cfi_def_cfa_offset 16
	movl	$2, %edi
	xorl	%eax, %eax
	popq	%r12
	.cfi_def_cfa_offset 8
	jmp	__printf_chk@PLT
	.cfi_endproc
.LFE2028:
	.size	_Z4helpiPPc, .-_Z4helpiPPc
	.section	.rodata.str1.1
.LC6:
	.string	"output-%i-%i-1.bin"
.LC7:
	.string	"output-%i-%i.bin"
.LC8:
	.string	"Exporting data to %s. "
.LC9:
	.string	"wb"
	.text
	.globl	_Z11export_dataPii
	.type	_Z11export_dataPii, @function
_Z11export_dataPii:
.LFB2029:
	.cfi_startproc
	endbr64
	pushq	%r13
	.cfi_def_cfa_offset 16
	.cfi_offset 13, -16
	movq	%rdi, %r13
	movl	$100, %edi
	pushq	%r12
	.cfi_def_cfa_offset 24
	.cfi_offset 12, -24
	pushq	%rbp
	.cfi_def_cfa_offset 32
	.cfi_offset 6, -32
	movl	%esi, %ebp
	movl	$1, %esi
	pushq	%rbx
	.cfi_def_cfa_offset 40
	.cfi_offset 3, -40
	subq	$24, %rsp
	.cfi_def_cfa_offset 64
	movl	nk(%rip), %eax
	leal	1(%rax), %r9d
	movl	%r9d, 12(%rsp)
	call	calloc@PLT
	cmpl	$2, expi(%rip)
	movl	npd(%rip), %r8d
	leaq	.LC6(%rip), %rcx
	movl	12(%rsp), %r9d
	movq	%rax, %rbx
	je	.L18
	leaq	.LC7(%rip), %rcx
.L18:
	movq	%rbx, %rdi
	movl	$100, %edx
	movl	$2, %esi
	xorl	%eax, %eax
	call	__sprintf_chk@PLT
	movq	%rbx, %rdx
	movl	$2, %edi
	xorl	%eax, %eax
	leaq	.LC8(%rip), %rsi
	call	__printf_chk@PLT
	movq	%rbx, %rdi
	leaq	.LC9(%rip), %rsi
	call	fopen@PLT
	movslq	%ebp, %rdx
	movq	%r13, %rdi
	movl	$4, %esi
	movq	%rax, %r12
	movq	%rax, %rcx
	call	fwrite@PLT
	movq	%r12, %rdi
	call	fclose@PLT
	addq	$24, %rsp
	.cfi_def_cfa_offset 40
	movq	%rbx, %rdi
	popq	%rbx
	.cfi_def_cfa_offset 32
	popq	%rbp
	.cfi_def_cfa_offset 24
	popq	%r12
	.cfi_def_cfa_offset 16
	popq	%r13
	.cfi_def_cfa_offset 8
	jmp	free@PLT
	.cfi_endproc
.LFE2029:
	.size	_Z11export_dataPii, .-_Z11export_dataPii
	.section	.rodata.str1.1
.LC10:
	.string	"Importing data from %s. "
.LC11:
	.string	"rb"
	.text
	.globl	_Z11import_dataPi
	.type	_Z11import_dataPi, @function
_Z11import_dataPi:
.LFB2030:
	.cfi_startproc
	endbr64
	pushq	%rbp
	.cfi_def_cfa_offset 16
	.cfi_offset 6, -16
	movq	%rdi, %rbp
	leaq	.LC10(%rip), %rsi
	movl	$2, %edi
	pushq	%rbx
	.cfi_def_cfa_offset 24
	.cfi_offset 3, -24
	pushq	%rax
	.cfi_def_cfa_offset 32
	movq	input_file(%rip), %rdx
	xorl	%eax, %eax
	call	__printf_chk@PLT
	movq	input_file(%rip), %rdi
	leaq	.LC11(%rip), %rsi
	call	fopen@PLT
	movl	npd(%rip), %ecx
	movq	%rbp, %rdi
	orq	$-1, %rsi
	movq	%rax, %rbx
	movl	$4, %edx
	movq	%rax, %r8
	imull	%ecx, %ecx
	movslq	%ecx, %rcx
	call	__fread_chk@PLT
	popq	%rdx
	.cfi_def_cfa_offset 24
	movq	%rbx, %rdi
	popq	%rbx
	.cfi_def_cfa_offset 16
	popq	%rbp
	.cfi_def_cfa_offset 8
	jmp	fclose@PLT
	.cfi_endproc
.LFE2030:
	.size	_Z11import_dataPi, .-_Z11import_dataPi
	.globl	_Z47__device_stub__Z20calculateFrameSharedPiS_PdiS_PiS_PdiS_
	.type	_Z47__device_stub__Z20calculateFrameSharedPiS_PdiS_PiS_PdiS_, @function
_Z47__device_stub__Z20calculateFrameSharedPiS_PdiS_PiS_PdiS_:
.LFB2056:
	.cfi_startproc
	endbr64
	subq	$168, %rsp
	.cfi_def_cfa_offset 176
	movq	%rdi, 40(%rsp)
	leaq	64(%rsp), %rdi
	movq	%rsi, 32(%rsp)
	leaq	76(%rsp), %rsi
	movq	%rdx, 24(%rsp)
	leaq	48(%rsp), %rdx
	movl	%ecx, 20(%rsp)
	leaq	56(%rsp), %rcx
	movq	%r8, 8(%rsp)
	movq	%fs:40, %rax
	movq	%rax, 152(%rsp)
	xorl	%eax, %eax
	leaq	40(%rsp), %rax
	movl	$1, 72(%rsp)
	movq	%rax, 112(%rsp)
	leaq	32(%rsp), %rax
	movq	%rax, 120(%rsp)
	leaq	24(%rsp), %rax
	movq	%rax, 128(%rsp)
	leaq	20(%rsp), %rax
	movq	%rax, 136(%rsp)
	leaq	8(%rsp), %rax
	movq	%rax, 144(%rsp)
	movabsq	$4294967297, %rax
	movq	%rax, 64(%rsp)
	movq	%rax, 76(%rsp)
	movl	$1, 84(%rsp)
	call	__cudaPopCallConfiguration@PLT
	testl	%eax, %eax
	jne	.L21
	pushq	56(%rsp)
	.cfi_def_cfa_offset 184
	leaq	_Z20calculateFrameSharedPiS_PdiS_(%rip), %rdi
	pushq	56(%rsp)
	.cfi_def_cfa_offset 192
	movq	92(%rsp), %rcx
	movl	100(%rsp), %r8d
	movq	80(%rsp), %rsi
	movl	88(%rsp), %edx
	leaq	128(%rsp), %r9
	call	cudaLaunchKernel@PLT
	popq	%rax
	.cfi_def_cfa_offset 184
	popq	%rdx
	.cfi_def_cfa_offset 176
.L21:
	movq	152(%rsp), %rax
	subq	%fs:40, %rax
	je	.L23
	call	__stack_chk_fail@PLT
.L23:
	addq	$168, %rsp
	.cfi_def_cfa_offset 8
	ret
	.cfi_endproc
.LFE2056:
	.size	_Z47__device_stub__Z20calculateFrameSharedPiS_PdiS_PiS_PdiS_, .-_Z47__device_stub__Z20calculateFrameSharedPiS_PdiS_PiS_PdiS_
	.globl	_Z20calculateFrameSharedPiS_PdiS_
	.type	_Z20calculateFrameSharedPiS_PdiS_, @function
_Z20calculateFrameSharedPiS_PdiS_:
.LFB2057:
	.cfi_startproc
	endbr64
	jmp	_Z47__device_stub__Z20calculateFrameSharedPiS_PdiS_PiS_PdiS_
	.cfi_endproc
.LFE2057:
	.size	_Z20calculateFrameSharedPiS_PdiS_, .-_Z20calculateFrameSharedPiS_PdiS_
	.section	.rodata.str1.1
.LC12:
	.string	"Finished at %ith iteration. "
	.text
	.globl	_Z5isingPiPdii
	.type	_Z5isingPiPdii, @function
_Z5isingPiPdii:
.LFB2031:
	.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
	movq	%rsi, %r14
	pushq	%r13
	.cfi_def_cfa_offset 32
	.cfi_offset 13, -32
	movl	%edx, %r13d
	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
	movl	%ecx, %ebp
	pushq	%rbx
	.cfi_def_cfa_offset 56
	.cfi_offset 3, -56
	movl	%ecx, %ebx
	imull	%ecx, %ebx
	subq	$104, %rsp
	.cfi_def_cfa_offset 160
	movq	%fs:40, %rax
	movq	%rax, 88(%rsp)
	xorl	%eax, %eax
	movslq	%ebx, %rbx
	leaq	16(%rsp), %rdi
	leaq	12(%rsp), %r15
	salq	$2, %rbx
	movl	$1, 12(%rsp)
	movq	%rbx, %rsi
	call	cudaMalloc@PLT
	leaq	24(%rsp), %rdi
	movq	%rbx, %rsi
	call	cudaMalloc@PLT
	leaq	32(%rsp), %rdi
	movl	$200, %esi
	call	cudaMalloc@PLT
	movl	$4, %esi
	leaq	40(%rsp), %rdi
	call	cudaMalloc@PLT
	leaq	48(%rsp), %rdi
	call	cudaStreamCreate@PLT
	leaq	56(%rsp), %rdi
	call	cudaStreamCreate@PLT
	movq	48(%rsp), %r8
	movq	%rbx, %rdx
	movq	%r12, %rsi
	movq	16(%rsp), %rdi
	movl	$1, %ecx
	call	cudaMemcpyAsync@PLT
	movq	56(%rsp), %r8
	movq	%rbx, %rdx
	movq	%r12, %rsi
	movq	24(%rsp), %rdi
	movl	$1, %ecx
	call	cudaMemcpyAsync@PLT
	movq	32(%rsp), %rdi
	movl	$1, %ecx
	movq	%r14, %rsi
	movl	$200, %edx
	xorl	%r14d, %r14d
	call	cudaMemcpy@PLT
	movq	48(%rsp), %rdi
	call	cudaStreamDestroy@PLT
	movq	56(%rsp), %rdi
	call	cudaStreamDestroy@PLT
	movl	$1073741825, %eax
	movl	$32, %ecx
	movl	$1, 72(%rsp)
	salq	$5, %rax
	movl	$1, 84(%rsp)
	movq	%rax, 64(%rsp)
	leal	31(%rbp), %eax
	cltd
	idivl	%ecx
	movl	%eax, 76(%rsp)
	movl	%eax, 80(%rsp)
.L27:
	cmpl	%r13d, %r14d
	jge	.L30
	movq	40(%rsp), %rdi
	movl	$1, %ecx
	movl	$4, %edx
	movq	%r15, %rsi
	movl	$1, 12(%rsp)
	call	cudaMemcpy@PLT
	movl	72(%rsp), %ecx
	movl	84(%rsp), %esi
	xorl	%r9d, %r9d
	movq	64(%rsp), %rdx
	movq	76(%rsp), %rdi
	xorl	%r8d, %r8d
	call	__cudaPushCallConfiguration@PLT
	testl	%eax, %eax
	jne	.L28
	movq	40(%rsp), %r8
	movq	32(%rsp), %rdx
	movl	%ebp, %ecx
	movq	24(%rsp), %rsi
	movq	16(%rsp), %rdi
	call	_Z47__device_stub__Z20calculateFrameSharedPiS_PdiS_PiS_PdiS_
.L28:
	movq	40(%rsp), %rsi
	movl	$4, %edx
	movl	$2, %ecx
	movq	%r15, %rdi
	call	cudaMemcpy@PLT
	movq	16(%rsp), %rax
	movq	24(%rsp), %rdx
	cmpl	$0, 12(%rsp)
	movq	%rdx, 16(%rsp)
	movq	%rax, 24(%rsp)
	je	.L29
	movl	%r14d, %edx
	leaq	.LC12(%rip), %rsi
	movl	$2, %edi
	xorl	%eax, %eax
	call	__printf_chk@PLT
	movq	24(%rsp), %rdi
	call	cudaFree@PLT
	movq	32(%rsp), %rdi
	call	cudaFree@PLT
	jmp	.L30
.L29:
	incl	%r14d
	jmp	.L27
.L30:
	movq	16(%rsp), %rsi
	movq	%r12, %rdi
	movl	$2, %ecx
	movq	%rbx, %rdx
	call	cudaMemcpy@PLT
	movq	16(%rsp), %rdi
	call	cudaFree@PLT
	movq	88(%rsp), %rax
	subq	%fs:40, %rax
	je	.L32
	call	__stack_chk_fail@PLT
.L32:
	addq	$104, %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
.LFE2031:
	.size	_Z5isingPiPdii, .-_Z5isingPiPdii
	.section	.rodata.str1.1
.LC13:
	.string	"Running with values n=%i, k=%i, o=%i\n"
.LC14:
	.string	"Generating random data set. "
.LC16:
	.string	"DONE in %fsec!\n"
.LC17:
	.string	"Running Ising Model Evolution. "
.LC18:
	.string	"Saving data of each iteration. "
.LC19:
	.string	"Saving last iteration. "
.LC20:
	.string	"Exiting\n"
	.section	.rodata
	.align 32
.LC0:
	.long	-755914244
	.long	1064329805
	.long	-755914244
	.long	1066426957
	.long	1992864825
	.long	1067098046
	.long	-755914244
	.long	1066426957
	.long	-755914244
	.long	1064329805
	.long	-755914244
	.long	1066426957
	.long	1443109011
	.long	1068641550
	.long	1168231105
	.long	1069413302
	.long	1443109011
	.long	1068641550
	.long	-755914244
	.long	1066426957
	.long	1992864825
	.long	1067098046
	.long	1168231105
	.long	1069413302
	.long	0
	.long	0
	.long	1168231105
	.long	1069413302
	.long	1992864825
	.long	1067098046
	.long	-755914244
	.long	1066426957
	.long	1443109011
	.long	1068641550
	.long	1168231105
	.long	1069413302
	.long	1443109011
	.long	1068641550
	.long	-755914244
	.long	1066426957
	.long	-755914244
	.long	1064329805
	.long	-755914244
	.long	1066426957
	.long	1992864825
	.long	1067098046
	.long	-755914244
	.long	1066426957
	.long	-755914244
	.long	1064329805
	.section	.text.startup,"ax",@progbits
	.globl	main
	.type	main, @function
main:
.LFB2027:
	.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	startwtime(%rip), %rbx
	subq	$216, %rsp
	.cfi_def_cfa_offset 272
	movq	%fs:40, %rax
	movq	%rax, 200(%rsp)
	xorl	%eax, %eax
	call	_Z4helpiPPc
	movl	expi(%rip), %r8d
	xorl	%eax, %eax
	movl	nk(%rip), %ecx
	movl	npd(%rip), %edx
	leaq	.LC13(%rip), %rsi
	movl	$2, %edi
	call	__printf_chk@PLT
	xorl	%edi, %edi
	call	time@PLT
	movl	%eax, %edi
	call	srand@PLT
	movl	npd(%rip), %edi
	imull	%edi, %edi
	movslq	%edi, %rdi
	salq	$2, %rdi
	call	malloc@PLT
	cmpq	$0, input_file(%rip)
	movq	%rax, %rbp
	jne	.L35
	leaq	.LC14(%rip), %rsi
	movl	$2, %edi
	xorl	%eax, %eax
	xorl	%r12d, %r12d
	call	__printf_chk@PLT
	xorl	%esi, %esi
	movq	%rbx, %rdi
	call	gettimeofday@PLT
.L36:
	movl	npd(%rip), %eax
	imull	%eax, %eax
	cmpl	%r12d, %eax
	jle	.L50
	call	rand@PLT
	cmpl	$1073741822, %eax
	setg	%al
	movzbl	%al, %eax
	leal	-1(%rax,%rax), %eax
	movl	%eax, 0(%rbp,%r12,4)
	incq	%r12
	jmp	.L36
.L50:
	xorl	%esi, %esi
	leaq	endwtime(%rip), %rdi
	call	gettimeofday@PLT
	jmp	.L48
.L35:
	movq	%rbx, %rdi
	xorl	%esi, %esi
	call	gettimeofday@PLT
	movq	%rbp, %rdi
	call	_Z11import_dataPi
.L48:
	movq	8+endwtime(%rip), %rax
	subq	8+startwtime(%rip), %rax
	movl	$2, %edi
	movq	%rsp, %r14
	cvtsi2sdq	endwtime(%rip), %xmm1
	leaq	.LC16(%rip), %rsi
	cvtsi2sdq	%rax, %xmm0
	divsd	.LC15(%rip), %xmm0
	movb	$1, %al
	addsd	%xmm1, %xmm0
	cvtsi2sdq	startwtime(%rip), %xmm1
	subsd	%xmm1, %xmm0
	call	__printf_chk@PLT
	xorl	%eax, %eax
	movq	%rsp, %rdi
	movl	$50, %ecx
	leaq	.LC0(%rip), %rsi
	rep movsl
	leaq	.LC17(%rip), %rsi
	movl	$2, %edi
	call	__printf_chk@PLT
	xorl	%esi, %esi
	movq	%rbx, %rdi
	call	gettimeofday@PLT
	movl	expi(%rip), %r13d
	testl	%r13d, %r13d
	jne	.L40
	movl	npd(%rip), %ecx
	movl	nk(%rip), %edx
	movq	%r14, %rsi
	movq	%rbp, %rdi
	call	_Z5isingPiPdii
	xorl	%esi, %esi
	leaq	endwtime(%rip), %rdi
	call	gettimeofday@PLT
	jmp	.L49
.L40:
	cmpl	$1, %r13d
	jne	.L42
	leaq	.LC18(%rip), %rsi
	movl	$2, %edi
	xorl	%eax, %eax
	call	__printf_chk@PLT
	movl	npd(%rip), %r15d
	movl	nk(%rip), %eax
	imull	%r15d, %r15d
	leal	1(%rax), %ebx
	imull	%r15d, %ebx
	movslq	%ebx, %rbx
	salq	$2, %rbx
	movq	%rbx, %rdi
	call	malloc@PLT
	movslq	%r15d, %rdx
	movq	%rbx, %rcx
	movq	%rbp, %rsi
	salq	$2, %rdx
	movq	%rax, %rdi
	movq	%rax, %r12
	call	__memcpy_chk@PLT
.L43:
	movl	nk(%rip), %eax
	movl	npd(%rip), %ecx
	cmpl	%r13d, %eax
	jl	.L51
	movl	$1, %edx
	movq	%r14, %rsi
	movq	%rbp, %rdi
	call	_Z5isingPiPdii
	movl	npd(%rip), %edx
	movq	%rbp, %rsi
	movl	%edx, %edi
	imull	%r13d, %edi
	imull	%edx, %edi
	movslq	%edi, %rdi
	salq	$2, %rdi
	cmpq	%rdi, %rbx
	movq	%rdi, %rcx
	cmovnb	%rbx, %rcx
	imull	%edx, %edx
	incl	%r13d
	subq	%rdi, %rcx
	addq	%r12, %rdi
	movslq	%edx, %rdx
	salq	$2, %rdx
	call	__memcpy_chk@PLT
	jmp	.L43
.L51:
	imull	%ecx, %ecx
	incl	%eax
	movq	%r12, %rdi
	imull	%eax, %ecx
	movl	%ecx, %esi
	call	_Z11export_dataPii
	movq	8+endwtime(%rip), %rax
	movl	$2, %edi
	cvtsi2sdq	endwtime(%rip), %xmm1
	subq	8+startwtime(%rip), %rax
	leaq	.LC16(%rip), %rsi
	cvtsi2sdq	%rax, %xmm0
	divsd	.LC15(%rip), %xmm0
	movb	$1, %al
	addsd	%xmm1, %xmm0
	cvtsi2sdq	startwtime(%rip), %xmm1
	subsd	%xmm1, %xmm0
	call	__printf_chk@PLT
	movq	%r12, %rdi
	call	free@PLT
	jmp	.L41
.L42:
	movl	npd(%rip), %ecx
	movl	nk(%rip), %edx
	movq	%r14, %rsi
	movq	%rbp, %rdi
	call	_Z5isingPiPdii
	leaq	.LC19(%rip), %rsi
	movl	$2, %edi
	xorl	%eax, %eax
	call	__printf_chk@PLT
	movl	npd(%rip), %esi
	movq	%rbp, %rdi
	imull	%esi, %esi
	call	_Z11export_dataPii
.L49:
	cvtsi2sdq	endwtime(%rip), %xmm1
	movq	8+endwtime(%rip), %rax
	movl	$2, %edi
	leaq	.LC16(%rip), %rsi
	subq	8+startwtime(%rip), %rax
	cvtsi2sdq	%rax, %xmm0
	divsd	.LC15(%rip), %xmm0
	movb	$1, %al
	addsd	%xmm1, %xmm0
	cvtsi2sdq	startwtime(%rip), %xmm1
	subsd	%xmm1, %xmm0
	call	__printf_chk@PLT
.L41:
	movl	$2, %edi
	xorl	%eax, %eax
	leaq	.LC20(%rip), %rsi
	call	__printf_chk@PLT
	movq	%rbp, %rdi
	call	free@PLT
	movq	200(%rsp), %rax
	subq	%fs:40, %rax
	je	.L45
	call	__stack_chk_fail@PLT
.L45:
	addq	$216, %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
.LFE2027:
	.size	main, .-main
	.section	.rodata.str1.1
.LC22:
	.string	"_Z20calculateFrameSharedPiS_PdiS_"
	.section	.text.startup
	.type	_ZL24__sti____cudaRegisterAllv, @function
_ZL24__sti____cudaRegisterAllv:
.LFB2059:
	.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	.LC22(%rip), %rdx
	movq	%rax, %rdi
	leaq	_Z20calculateFrameSharedPiS_PdiS_(%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
.LFE2059:
	.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	endwtime
	.bss
	.align 16
	.type	endwtime, @object
	.size	endwtime, 16
endwtime:
	.zero	16
	.globl	startwtime
	.align 16
	.type	startwtime, @object
	.size	startwtime, 16
startwtime:
	.zero	16
	.globl	expi
	.align 4
	.type	expi, @object
	.size	expi, 4
expi:
	.zero	4
	.globl	nk
	.data
	.align 4
	.type	nk, @object
	.size	nk, 4
nk:
	.long	10
	.globl	npd
	.align 4
	.type	npd, @object
	.size	npd, 4
npd:
	.long	517
	.globl	input_file
	.bss
	.align 8
	.type	input_file, @object
	.size	input_file, 8
input_file:
	.zero	8
	.section	.rodata.cst8,"aM",@progbits,8
	.align 8
.LC15:
	.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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "sys/time.h"

#define DefNumPD 517	// Default Number of Points per Dimension
#define DefNumI 10		// Default Number of Iterations
#define DefExp 0		// Default Value to Export Data (0 = None, 1 = All, 2 = Last)

enum Data_Types { CHAR_TYPE, INT_TYPE, FLOAT_TYPE, DOUBLE_TYPE };

char* input_file = NULL;
int npd = DefNumPD;	// Number of Points per Dimension
int nk = DefNumI;	// Number of Iterations
int expi = DefExp;	// Export Data

struct timeval startwtime, endwtime;

void ising(int* G, double* w, int k, int n);
void help(int argc, char* argv[]);
void export_data(int* G, int elemNum);
void import_data(int* G);

int main(int argc, char* argv[])
{
	help(argc, argv);
	printf("Running with values n=%i, k=%i, o=%i\n", npd, nk, expi);

	srand((unsigned int)time(NULL));
	double p_time;

	// Generate random/Import point set
	int* G = (int*)malloc(npd * npd * sizeof(int));
	if (input_file == NULL) {
		printf("Generating random data set. ");
		gettimeofday(&startwtime, NULL);

		for (int i = 0; i < npd * npd; i++) {
			if (rand() < (RAND_MAX) / 2)
				*(G + i) = -1;
			else
				*(G + i) = 1;
		}
		gettimeofday(&endwtime, NULL);
		p_time = (double)((endwtime.tv_usec - startwtime.tv_usec) / 1.0e6 + endwtime.tv_sec - startwtime.tv_sec);
		printf("DONE in %fsec!\n", p_time);
	}
	else {
		gettimeofday(&startwtime, NULL);
		import_data(G);
		p_time = (double)((endwtime.tv_usec - startwtime.tv_usec) / 1.0e6 + endwtime.tv_sec - startwtime.tv_sec);
		printf("DONE in %fsec!\n", p_time);
	}

	double weight_matrix[5][5] = { {0.004, 0.016, 0.026, 0.016, 0.004},
									{0.016, 0.071, 0.117, 0.071, 0.016},
									{0.026, 0.117, 0.000, 0.117, 0.026},
									{0.016, 0.071, 0.117, 0.071, 0.016},
									{0.004, 0.016, 0.026, 0.016, 0.004} };

	// Run Ising model evolution
	printf("Running Ising Model Evolution. ");
	gettimeofday(&startwtime, NULL);
	if (!expi) {
		ising(G, &weight_matrix[0][0], nk, npd);
		gettimeofday(&endwtime, NULL);
		p_time = (double)((endwtime.tv_usec - startwtime.tv_usec) / 1.0e6 + endwtime.tv_sec - startwtime.tv_sec);
		printf("DONE in %fsec!\n", p_time);
	}
	else if (expi == 1) {	// export data
		printf("Saving data of each iteration. ");
		int* G_out = (int*)malloc(npd * npd * (nk + 1) * sizeof(int));
		memcpy(G_out, G, npd * npd * sizeof(int));	// copy data to export them later		
		for (int i = 1; i < (nk + 1); i++) {	// save data of each iteration to export them for animation
			ising(G, &weight_matrix[0][0], 1, npd);
			memcpy((G_out + i * npd * npd), G, npd * npd * sizeof(int));	// copy data to export them later			
		}
		//  Export data to output.bin
		export_data(G_out, npd * npd * (nk + 1));
		p_time = (double)((endwtime.tv_usec - startwtime.tv_usec) / 1.0e6 + endwtime.tv_sec - startwtime.tv_sec);
		printf("DONE in %fsec!\n", p_time);
		free(G_out);
	}
	else {
		ising(G, &weight_matrix[0][0], nk, npd);
		printf("Saving last iteration. ");
		export_data(G, npd * npd);
		p_time = (double)((endwtime.tv_usec - startwtime.tv_usec) / 1.0e6 + endwtime.tv_sec - startwtime.tv_sec);
		printf("DONE in %fsec!\n", p_time);
	}

	printf("Exiting\n");
	free(G);
	return 0;
}

void help(int argc, char* argv[])
{
	if (argc > 1) {
		for (int i = 1; i < argc; i += 2) {
			if (*argv[i] == '-') {
				if (*(argv[i] + 1) == 'f')
					input_file = argv[i + 1];
				else if (*(argv[i] + 1) == 'n')
					npd = atoi(argv[i + 1]);
				else if (*(argv[i] + 1) == 'k')
					nk = atoi(argv[i + 1]);
				else if (*(argv[i] + 1) == 'o')
					expi = atoi(argv[i + 1]);
			}
			else {
				help(1, argv);
				return;
			}
		}
		return;
	}
	printf("Flags to use:\n");
	printf("-f [File]\t:Input file of points\n");
	printf("-n [Number]\t:Number of points per dimension (default:%i)\n", DefNumPD);
	printf("-k [Iterations]\t:Number of iterations (default: %i)\n", DefNumI);
	printf("-o [0|1|2]\t:Export each iteration to output*.bin (0 = None(default), 1 = All, 2 = Last)\n");

}

void export_data(int* G, int totalSize)
{
	int tmp_k = nk + 1;
	char* out_file_name = (char*)calloc(100, sizeof(char));
	if (expi == 2)
		sprintf(out_file_name, "output-%i-%i-1.bin", npd, tmp_k);
	else
		sprintf(out_file_name, "output-%i-%i.bin", npd, tmp_k);
	printf("Exporting data to %s. ", out_file_name);
	FILE* f = fopen(out_file_name, "wb");
	fwrite(G, sizeof(int), totalSize, f);
	fclose(f);
	free(out_file_name);
}

void import_data(int* G)
{
	printf("Importing data from %s. ", input_file);
	FILE* f = fopen(input_file, "rb");
	fread(G, sizeof(int), npd * npd, f);
	fclose(f);
}

//////////////// Ising Code Here ////////////////
#include <hip/hip_runtime.h>



#define WeightMatDim 5	// Weight Matrix Dimension
#define FloatError 1e-6	// Float error
#define TileSize 32		// Size of tiles partitioning the matrix - each tile calculates TileSize x TileSize moments
#define NumberOfRows 8	// Rows of each block of threads - each block is of size NumberOfRows x TileSi
#define RowsHelping (NumberOfRows + 4)	// Rows of global memory to be loaded into shared (for the exercise NumberOfRows + 4)
#define ColumnsHelping (TileSize + 4)	// Columns of global memory to be loaded into shared (for the exercise TileSize + 4)


__global__ void calculateFrameShared(int* G_d, int* GNext_d, double* w_d, int n, int* same_matrix_d)
{
	__shared__ double w_s[25]; // Shared matrix to hold weight table and accelerate access
	__shared__ int g_s[RowsHelping][ColumnsHelping]; // Shared matrix to hold moments needed for the current iteration

	// Copy w_d matrix from global to shared memory with optimal access of the former
	// as far as warps are concerned - indexing used is based only on block dims

	if ((threadIdx.x < 25) && (threadIdx.y == 0)) // Use only 25 initial threads of the first warp
		w_s[threadIdx.x] = w_d[threadIdx.x];

	/* Initialize thread coordinates to be used for global memory access*/
	int x = blockIdx.x * TileSize + threadIdx.x;
	int y = blockIdx.y * TileSize + threadIdx.y;

	// Do as many time needed to cover the whole area assigned to the block
	// Copy block elements for current iteration from global memory to shared in a warp
	// oriented manner copying a whole block of size [(NumberOfRows+4) x (TileSize+4)] in order to 
	// transfer all elements accessed during the iteration and thus gain in speed of execution

	for (int j = 0; j < TileSize; j += NumberOfRows) { // for every block chunk of tile in the y axis
		int counterY = 0; // variable to help with accessing rows of G_d table for copying
		// Copying moments for iteration j into shared memory
		for (int helperY = threadIdx.y; helperY < RowsHelping; helperY += NumberOfRows) { // for every row of the subtile to be loaded 		
			int counterX = 0; // variable to help with accessing columns of G_d table for copying
			int rowNumber = (y - 2 + counterY * NumberOfRows + n) % n; // Current Row of G_d to be dereferenced
			for (int helperX = threadIdx.x; helperX < ColumnsHelping; helperX += TileSize) {
				int columnNumber = (x - 2 + counterX * TileSize + n) % n; // Current Column of G_d to be dereferenced				
				g_s[helperY][helperX] = G_d[rowNumber * n + columnNumber]; // Dereference G_d and copy to shared memory
				++counterX; // increase helper counter for columns
			}
			++counterY; // increase helper counter for rows
		}
		__syncthreads(); // waiting for all threads to be done

		// Evaluating moments in subblock through g_s and w_s matrices
		if (x < n) {  // Check whether thread x coordinate is out of bounds
			if (y < n) { // Check whether thread y coordinate is out of bounds
				double influence = 0.0; // weighted influence of neighbors
				for (int i = -2; i <= 2; i++) {	// for every row of weight matrix
					int r = threadIdx.y + 2 + i;	// add 2 to y coordinate as is in block manner to "center" block in g_s dereferencing
					for (int t = -2; t <= 2; t++) {	// for every weight of a row in weight matrix
						int c = threadIdx.x + 2 + t;	// add 2 to x coordinate as is in block manner to "center" block in g_s dereferencing
						influence += g_s[r][c] * w_s[(i + 2) * WeightMatDim + (t + 2)];	// +2 cause of the i and t offset
					}// for t < WeightMatDim
				}// for i < WeightMatDim

				/*Update state for current point*/
				if (influence > FloatError)			// apply threshold for floating point error
					*(GNext_d + y * n + x) = 1;
				else if (influence < -FloatError)	// apply threshold for floating point error
					*(GNext_d + y * n + x) = -1;
				else								// stay the same
					*(GNext_d + y * n + x) = g_s[threadIdx.y + 2][threadIdx.x + 2];

				// Did the magnetic moment changed?
				if (*(GNext_d + y * n + x) != g_s[threadIdx.y + 2][threadIdx.x + 2])
					*same_matrix_d = 0;
			} // if (y < n)
		} // if (x < n)

		y += NumberOfRows; // Update y coordinate as we move down the tile
		__syncthreads(); // Synchronize threads for next iterartion
	} // for (j < TileSize)
}

void ising(int* G, double* w, int k, int n)
{
	/*Declare and initialize memory to use on device*/
	int* G_d, * GNext_d; double* w_d; // Pointers to use for matrix store on device
	int* same_matrix_d;	// device parameter to hold if iterations should proceed
	int same_matrix = 1;	// corresponding host parameter

	hipMalloc((void**)&G_d, n * n * sizeof(int));
	hipMalloc((void**)&GNext_d, n * n * sizeof(int));
	hipMalloc((void**)&w_d, WeightMatDim * WeightMatDim * sizeof(double));
	hipMalloc((void**)&same_matrix_d, sizeof(int));

	/*Create streams to overlap data transfers and gain in speed*/
	hipStream_t stream1;
	hipStream_t stream2;
	hipStreamCreate(&stream1);
	hipStreamCreate(&stream2);
	
	// Copy data
	hipMemcpyAsync(G_d, G, n * n * sizeof(int), hipMemcpyHostToDevice,stream1);     
	hipMemcpyAsync(GNext_d, G, n * n * sizeof(int), hipMemcpyHostToDevice,stream2);
	hipMemcpy(w_d, w, WeightMatDim * WeightMatDim * sizeof(double), hipMemcpyHostToDevice);

	// Destroy streams
	hipStreamDestroy(stream1); 
	hipStreamDestroy(stream2);

	/*Declare grid and block sizes and compensate for matrix not divided with block size*/
	dim3 dimBlock(TileSize, NumberOfRows);
	dim3 dimGrid((n + TileSize - 1) / TileSize, (n + TileSize - 1) / TileSize);

	/*--------------------------------------------------------------------------------*/
	for (int i = 0; i < k; ++i) { // For every iteration
		same_matrix = 1;
		hipMemcpy(same_matrix_d, &same_matrix, sizeof(int), hipMemcpyHostToDevice);
		calculateFrameShared <<< dimGrid, dimBlock >>> (G_d, GNext_d, w_d, n, same_matrix_d);

		hipMemcpy(&same_matrix, same_matrix_d, sizeof(int), hipMemcpyDeviceToHost); // Kernel to get flag indicating whether matrices are the same

		// Swap pointers
		int* ptri = G_d;
		G_d = GNext_d;
		GNext_d = ptri;

		// Exit if nothing changed
		if (same_matrix) {
			printf("Finished at %ith iteration. ", i);
			hipFree(GNext_d);
			hipFree(w_d);
			break;
		}
	}  // for every i < k

	// copy data from device and cleanup
	hipMemcpy(G, G_d, n * n * sizeof(int), hipMemcpyDeviceToHost);
	hipFree(G_d);
}
/////////////////////////////////////////////////
	.text
	.file	"kernel.hip"
	.section	.rodata.cst8,"aM",@progbits,8
	.p2align	3, 0x0                          # -- Begin function main
.LCPI0_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	$216, %rsp
	.cfi_def_cfa_offset 272
	.cfi_offset %rbx, -56
	.cfi_offset %r12, -48
	.cfi_offset %r13, -40
	.cfi_offset %r14, -32
	.cfi_offset %r15, -24
	.cfi_offset %rbp, -16
	callq	_Z4helpiPPc
	movl	npd(%rip), %esi
	movl	nk(%rip), %edx
	movl	expi(%rip), %ecx
	movl	$.L.str, %edi
	xorl	%eax, %eax
	callq	printf
	xorl	%edi, %edi
	callq	time
	movl	%eax, %edi
	callq	srand
	movl	npd(%rip), %edi
	imull	%edi, %edi
	shlq	$2, %rdi
	callq	malloc
	movq	%rax, %rbx
	cmpq	$0, input_file(%rip)
	je	.LBB0_1
# %bb.5:
	movl	$startwtime, %edi
	xorl	%esi, %esi
	callq	gettimeofday
	movq	%rbx, %rdi
	callq	_Z11import_dataPi
	jmp	.LBB0_6
.LBB0_1:
	movl	$.L.str.1, %edi
	xorl	%eax, %eax
	callq	printf
	movl	$startwtime, %edi
	xorl	%esi, %esi
	callq	gettimeofday
	cmpl	$0, npd(%rip)
	je	.LBB0_4
# %bb.2:                                # %.lr.ph.preheader
	xorl	%r14d, %r14d
.LBB0_3:                                # %.lr.ph
                                        # =>This Inner Loop Header: Depth=1
	callq	rand
	xorl	%ecx, %ecx
	cmpl	$1073741823, %eax               # imm = 0x3FFFFFFF
	setge	%cl
	leal	-1(,%rcx,2), %eax
	movl	%eax, (%rbx,%r14,4)
	incq	%r14
	movl	npd(%rip), %eax
	imull	%eax, %eax
	cmpq	%rax, %r14
	jb	.LBB0_3
.LBB0_4:                                # %._crit_edge
	movl	$endwtime, %edi
	xorl	%esi, %esi
	callq	gettimeofday
.LBB0_6:
	movq	endwtime+8(%rip), %rax
	subq	startwtime+8(%rip), %rax
	cvtsi2sd	%rax, %xmm1
	divsd	.LCPI0_0(%rip), %xmm1
	cvtsi2sdq	endwtime(%rip), %xmm0
	addsd	%xmm1, %xmm0
	xorps	%xmm1, %xmm1
	cvtsi2sdq	startwtime(%rip), %xmm1
	subsd	%xmm1, %xmm0
	movl	$.L.str.2, %edi
	movb	$1, %al
	callq	printf
	leaq	16(%rsp), %rdi
	movl	$.L__const.main.weight_matrix, %esi
	movl	$200, %edx
	callq	memcpy@PLT
	movl	$.L.str.3, %edi
	xorl	%eax, %eax
	callq	printf
	movl	$startwtime, %edi
	xorl	%esi, %esi
	callq	gettimeofday
	movl	expi(%rip), %eax
	cmpl	$1, %eax
	je	.LBB0_9
# %bb.7:
	testl	%eax, %eax
	jne	.LBB0_14
# %bb.8:
	movl	nk(%rip), %edx
	movl	npd(%rip), %ecx
	leaq	16(%rsp), %rsi
	movq	%rbx, %rdi
	callq	_Z5isingPiPdii
	movl	$endwtime, %edi
	xorl	%esi, %esi
	callq	gettimeofday
	jmp	.LBB0_15
.LBB0_9:
	xorl	%r13d, %r13d
	movl	$.L.str.4, %edi
	xorl	%eax, %eax
	callq	printf
	movl	npd(%rip), %ebp
	movl	%ebp, %r12d
	imull	%r12d, %r12d
	movl	nk(%rip), %eax
	movq	%rax, 8(%rsp)                   # 8-byte Spill
	leal	1(%rax), %r15d
	movl	%r15d, %eax
	imull	%r12d, %eax
	movslq	%eax, %rdi
	shlq	$2, %rdi
	callq	malloc
	movq	%rax, %r14
	shlq	$2, %r12
	movq	%rax, %rdi
	movq	%rbx, %rsi
	movq	%r12, %rdx
	callq	memcpy@PLT
	cmpl	$0, 8(%rsp)                     # 4-byte Folded Reload
	jle	.LBB0_13
# %bb.10:                               # %.lr.ph35.preheader
	leaq	16(%rsp), %r12
.LBB0_11:                               # %.lr.ph35
                                        # =>This Inner Loop Header: Depth=1
	incl	%r13d
	movq	%rbx, %rdi
	movq	%r12, %rsi
	movl	$1, %edx
	movl	%ebp, %ecx
	callq	_Z5isingPiPdii
	movl	npd(%rip), %ebp
	movl	%ebp, %edx
	imull	%edx, %edx
	movl	%edx, %eax
	imull	%r13d, %eax
	cltq
	leaq	(%r14,%rax,4), %rdi
	shlq	$2, %rdx
	movq	%rbx, %rsi
	callq	memcpy@PLT
	movl	nk(%rip), %r15d
	cmpl	%r15d, %r13d
	jl	.LBB0_11
# %bb.12:                               # %._crit_edge36.loopexit
	incl	%r15d
.LBB0_13:                               # %._crit_edge36
	imull	%ebp, %r15d
	imull	%ebp, %r15d
	movq	%r14, %rdi
	movl	%r15d, %esi
	callq	_Z11export_dataPii
	movq	endwtime+8(%rip), %rax
	subq	startwtime+8(%rip), %rax
	xorps	%xmm1, %xmm1
	cvtsi2sd	%rax, %xmm1
	divsd	.LCPI0_0(%rip), %xmm1
	xorps	%xmm0, %xmm0
	cvtsi2sdq	endwtime(%rip), %xmm0
	addsd	%xmm1, %xmm0
	xorps	%xmm1, %xmm1
	cvtsi2sdq	startwtime(%rip), %xmm1
	subsd	%xmm1, %xmm0
	movl	$.L.str.2, %edi
	movb	$1, %al
	callq	printf
	movq	%r14, %rdi
	callq	free
	jmp	.LBB0_16
.LBB0_14:
	movl	nk(%rip), %edx
	movl	npd(%rip), %ecx
	leaq	16(%rsp), %rsi
	movq	%rbx, %rdi
	callq	_Z5isingPiPdii
	movl	$.L.str.5, %edi
	xorl	%eax, %eax
	callq	printf
	movl	npd(%rip), %esi
	imull	%esi, %esi
	movq	%rbx, %rdi
	callq	_Z11export_dataPii
.LBB0_15:
	movq	endwtime+8(%rip), %rax
	subq	startwtime+8(%rip), %rax
	xorps	%xmm1, %xmm1
	cvtsi2sd	%rax, %xmm1
	divsd	.LCPI0_0(%rip), %xmm1
	xorps	%xmm0, %xmm0
	cvtsi2sdq	endwtime(%rip), %xmm0
	addsd	%xmm1, %xmm0
	xorps	%xmm1, %xmm1
	cvtsi2sdq	startwtime(%rip), %xmm1
	subsd	%xmm1, %xmm0
	movl	$.L.str.2, %edi
	movb	$1, %al
	callq	printf
.LBB0_16:
	movl	$.Lstr, %edi
	callq	puts@PLT
	movq	%rbx, %rdi
	callq	free
	xorl	%eax, %eax
	addq	$216, %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_end0:
	.size	main, .Lfunc_end0-main
	.cfi_endproc
                                        # -- End function
	.globl	_Z4helpiPPc                     # -- Begin function _Z4helpiPPc
	.type	_Z4helpiPPc,@function
_Z4helpiPPc:                            # @_Z4helpiPPc
	.cfi_startproc
# %bb.0:
	pushq	%rbp
	.cfi_def_cfa_offset 16
	pushq	%r14
	.cfi_def_cfa_offset 24
	pushq	%rbx
	.cfi_def_cfa_offset 32
	.cfi_offset %rbx, -32
	.cfi_offset %r14, -24
	.cfi_offset %rbp, -16
	cmpl	$2, %edi
	jl	.LBB1_11
# %bb.1:                                # %.preheader.lr.ph.preheader
	movq	%rsi, %rbx
	movl	%edi, %ebp
	movl	$1, %r14d
.LBB1_2:                                # %.preheader.lr.ph
                                        # =>This Inner Loop Header: Depth=1
	movq	(%rbx,%r14,8), %rax
	cmpb	$45, (%rax)
	jne	.LBB1_11
# %bb.3:                                #   in Loop: Header=BB1_2 Depth=1
	movzbl	1(%rax), %eax
	addl	$-102, %eax
	cmpl	$9, %eax
	ja	.LBB1_9
# %bb.4:                                #   in Loop: Header=BB1_2 Depth=1
	jmpq	*.LJTI1_0(,%rax,8)
.LBB1_5:                                #   in Loop: Header=BB1_2 Depth=1
	movq	8(%rbx,%r14,8), %rax
	movq	%rax, input_file(%rip)
	jmp	.LBB1_9
.LBB1_6:                                #   in Loop: Header=BB1_2 Depth=1
	movq	8(%rbx,%r14,8), %rdi
	callq	atoi
	movl	%eax, npd(%rip)
	jmp	.LBB1_9
.LBB1_7:                                #   in Loop: Header=BB1_2 Depth=1
	movq	8(%rbx,%r14,8), %rdi
	callq	atoi
	movl	%eax, nk(%rip)
	jmp	.LBB1_9
.LBB1_8:                                #   in Loop: Header=BB1_2 Depth=1
	movq	8(%rbx,%r14,8), %rdi
	callq	atoi
	movl	%eax, expi(%rip)
.LBB1_9:                                #   in Loop: Header=BB1_2 Depth=1
	addq	$2, %r14
	cmpl	%ebp, %r14d
	jl	.LBB1_2
# %bb.10:                               # %.loopexit
	popq	%rbx
	.cfi_def_cfa_offset 24
	popq	%r14
	.cfi_def_cfa_offset 16
	popq	%rbp
	.cfi_def_cfa_offset 8
	retq
.LBB1_11:                               # %tailrecurse._crit_edge
	.cfi_def_cfa_offset 32
	movl	$.Lstr.1, %edi
	callq	puts@PLT
	movl	$.Lstr.2, %edi
	callq	puts@PLT
	movl	$.L.str.9, %edi
	movl	$517, %esi                      # imm = 0x205
	xorl	%eax, %eax
	callq	printf
	movl	$.L.str.10, %edi
	movl	$10, %esi
	xorl	%eax, %eax
	callq	printf
	movl	$.Lstr.3, %edi
	popq	%rbx
	.cfi_def_cfa_offset 24
	popq	%r14
	.cfi_def_cfa_offset 16
	popq	%rbp
	.cfi_def_cfa_offset 8
	jmp	puts@PLT                        # TAILCALL
.Lfunc_end1:
	.size	_Z4helpiPPc, .Lfunc_end1-_Z4helpiPPc
	.cfi_endproc
	.section	.rodata,"a",@progbits
	.p2align	3, 0x0
.LJTI1_0:
	.quad	.LBB1_5
	.quad	.LBB1_9
	.quad	.LBB1_9
	.quad	.LBB1_9
	.quad	.LBB1_9
	.quad	.LBB1_7
	.quad	.LBB1_9
	.quad	.LBB1_9
	.quad	.LBB1_6
	.quad	.LBB1_8
                                        # -- End function
	.text
	.globl	_Z11import_dataPi               # -- Begin function _Z11import_dataPi
	.type	_Z11import_dataPi,@function
_Z11import_dataPi:                      # @_Z11import_dataPi
	.cfi_startproc
# %bb.0:
	pushq	%r14
	.cfi_def_cfa_offset 16
	pushq	%rbx
	.cfi_def_cfa_offset 24
	pushq	%rax
	.cfi_def_cfa_offset 32
	.cfi_offset %rbx, -24
	.cfi_offset %r14, -16
	movq	%rdi, %rbx
	movq	input_file(%rip), %rsi
	movl	$.L.str.16, %edi
	xorl	%eax, %eax
	callq	printf
	movq	input_file(%rip), %rdi
	movl	$.L.str.17, %esi
	callq	fopen
	movq	%rax, %r14
	movl	npd(%rip), %edx
	imull	%edx, %edx
	movl	$4, %esi
	movq	%rbx, %rdi
	movq	%rax, %rcx
	callq	fread
	movq	%r14, %rdi
	addq	$8, %rsp
	.cfi_def_cfa_offset 24
	popq	%rbx
	.cfi_def_cfa_offset 16
	popq	%r14
	.cfi_def_cfa_offset 8
	jmp	fclose                          # TAILCALL
.Lfunc_end2:
	.size	_Z11import_dataPi, .Lfunc_end2-_Z11import_dataPi
	.cfi_endproc
                                        # -- End function
	.globl	_Z5isingPiPdii                  # -- Begin function _Z5isingPiPdii
	.type	_Z5isingPiPdii,@function
_Z5isingPiPdii:                         # @_Z5isingPiPdii
	.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	$72, %rsp
	.cfi_def_cfa_offset 128
	.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	%ecx, %r14d
	movl	%edx, %ebp
	movq	%rsi, 24(%rsp)                  # 8-byte Spill
	movq	%rdi, %r15
	movl	$1, 4(%rsp)
	movl	%ecx, %ebx
	imull	%ebx, %ebx
	shlq	$2, %rbx
	leaq	8(%rsp), %rdi
	movq	%rbx, %rsi
	callq	hipMalloc
	leaq	16(%rsp), %rdi
	movq	%rbx, %rsi
	callq	hipMalloc
	leaq	40(%rsp), %rdi
	movl	$200, %esi
	callq	hipMalloc
	leaq	32(%rsp), %rdi
	movl	$4, %esi
	callq	hipMalloc
	leaq	64(%rsp), %r13
	movq	%r13, %rdi
	callq	hipStreamCreate
	leaq	56(%rsp), %r12
	movq	%r12, %rdi
	callq	hipStreamCreate
	leaq	8(%rsp), %rax
	movq	(%rax), %rdi
	movq	(%r13), %r8
	movq	%r15, %rsi
	movq	%rbx, %rdx
	movl	$1, %ecx
	callq	hipMemcpyAsync
	leaq	16(%rsp), %rax
	movq	(%rax), %rdi
	movq	(%r12), %r8
	movq	%r15, 48(%rsp)                  # 8-byte Spill
	movq	%r15, %rsi
	movq	%rbx, %rdx
	movl	$1, %ecx
	callq	hipMemcpyAsync
	leaq	40(%rsp), %rax
	movq	(%rax), %rdi
	movl	$200, %edx
	movq	24(%rsp), %rsi                  # 8-byte Reload
	movl	$1, %ecx
	callq	hipMemcpy
	movq	(%r13), %rdi
	callq	hipStreamDestroy
	movq	(%r12), %rdi
	callq	hipStreamDestroy
	leal	31(%r14), %ecx
	movq	%r14, 24(%rsp)                  # 8-byte Spill
	leal	62(%r14), %eax
	testl	%ecx, %ecx
	cmovnsl	%ecx, %eax
	testl	%ebp, %ebp
	jle	.LBB3_7
# %bb.1:                                # %.lr.ph.preheader
	sarl	$5, %eax
	movq	%rax, %r13
	shlq	$32, %r13
	orq	%rax, %r13
	xorl	%r12d, %r12d
	leaq	4(%rsp), %r14
	movabsq	$34359738400, %r15              # imm = 0x800000020
.LBB3_2:                                # %.lr.ph
                                        # =>This Inner Loop Header: Depth=1
	movl	$1, 4(%rsp)
	movq	32(%rsp), %rdi
	movl	$4, %edx
	movq	%r14, %rsi
	movl	$1, %ecx
	callq	hipMemcpy
	movq	%r13, %rdi
	movl	$1, %esi
	movq	%r15, %rdx
	movl	$1, %ecx
	xorl	%r8d, %r8d
	xorl	%r9d, %r9d
	callq	__hipPushCallConfiguration
	testl	%eax, %eax
	jne	.LBB3_4
# %bb.3:                                #   in Loop: Header=BB3_2 Depth=1
	movq	8(%rsp), %rdi
	movq	16(%rsp), %rsi
	movq	40(%rsp), %rdx
	movq	32(%rsp), %r8
	movq	24(%rsp), %rcx                  # 8-byte Reload
                                        # kill: def $ecx killed $ecx killed $rcx
	callq	_Z35__device_stub__calculateFrameSharedPiS_PdiS_
.LBB3_4:                                #   in Loop: Header=BB3_2 Depth=1
	movq	32(%rsp), %rsi
	movl	$4, %edx
	movq	%r14, %rdi
	movl	$2, %ecx
	callq	hipMemcpy
	movq	8(%rsp), %rax
	movq	16(%rsp), %rcx
	movq	%rcx, 8(%rsp)
	movq	%rax, 16(%rsp)
	cmpl	$0, 4(%rsp)
	jne	.LBB3_5
# %bb.6:                                # %.critedge
                                        #   in Loop: Header=BB3_2 Depth=1
	incl	%r12d
	cmpl	%r12d, %ebp
	jne	.LBB3_2
	jmp	.LBB3_7
.LBB3_5:
	movl	$.L.str.18, %edi
	movl	%r12d, %esi
	xorl	%eax, %eax
	callq	printf
	movq	16(%rsp), %rdi
	callq	hipFree
	movq	40(%rsp), %rdi
	callq	hipFree
.LBB3_7:                                # %.loopexit
	movq	8(%rsp), %rsi
	movq	48(%rsp), %rdi                  # 8-byte Reload
	movq	%rbx, %rdx
	movl	$2, %ecx
	callq	hipMemcpy
	movq	8(%rsp), %rdi
	callq	hipFree
	addq	$72, %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_end3:
	.size	_Z5isingPiPdii, .Lfunc_end3-_Z5isingPiPdii
	.cfi_endproc
                                        # -- End function
	.globl	_Z11export_dataPii              # -- Begin function _Z11export_dataPii
	.type	_Z11export_dataPii,@function
_Z11export_dataPii:                     # @_Z11export_dataPii
	.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	nk(%rip), %r15d
	incl	%r15d
	movl	$100, %edi
	movl	$1, %esi
	callq	calloc
	movq	%rax, %r14
	cmpl	$2, expi(%rip)
	movl	npd(%rip), %edx
	movl	$.L.str.12, %eax
	movl	$.L.str.13, %esi
	cmoveq	%rax, %rsi
	movq	%r14, %rdi
	movl	%r15d, %ecx
	xorl	%eax, %eax
	callq	sprintf
	movl	$.L.str.14, %edi
	movq	%r14, %rsi
	xorl	%eax, %eax
	callq	printf
	movl	$.L.str.15, %esi
	movq	%r14, %rdi
	callq	fopen
	movq	%rax, %r15
	movslq	%ebp, %rdx
	movl	$4, %esi
	movq	%rbx, %rdi
	movq	%rax, %rcx
	callq	fwrite
	movq	%r15, %rdi
	callq	fclose
	movq	%r14, %rdi
	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	free                            # TAILCALL
.Lfunc_end4:
	.size	_Z11export_dataPii, .Lfunc_end4-_Z11export_dataPii
	.cfi_endproc
                                        # -- End function
	.globl	_Z35__device_stub__calculateFrameSharedPiS_PdiS_ # -- Begin function _Z35__device_stub__calculateFrameSharedPiS_PdiS_
	.type	_Z35__device_stub__calculateFrameSharedPiS_PdiS_,@function
_Z35__device_stub__calculateFrameSharedPiS_PdiS_: # @_Z35__device_stub__calculateFrameSharedPiS_PdiS_
	.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	$144, %rsp
	.cfi_def_cfa_offset 192
	.cfi_offset %rbx, -48
	.cfi_offset %r12, -40
	.cfi_offset %r13, -32
	.cfi_offset %r14, -24
	.cfi_offset %r15, -16
	leaq	56(%rsp), %rax
	movq	%rdi, (%rax)
	leaq	48(%rsp), %rdi
	movq	%rsi, (%rdi)
	leaq	40(%rsp), %rsi
	movq	%rdx, (%rsi)
	leaq	12(%rsp), %rdx
	movl	%ecx, (%rdx)
	leaq	32(%rsp), %rcx
	movq	%r8, (%rcx)
	leaq	96(%rsp), %rbx
	movq	%rax, (%rbx)
	movq	%rdi, 8(%rbx)
	movq	%rsi, 16(%rbx)
	movq	%rdx, 24(%rbx)
	movq	%rcx, 32(%rbx)
	leaq	80(%rsp), %r14
	leaq	64(%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	$_Z20calculateFrameSharedPiS_PdiS_, %edi
	movq	%rbx, %r9
	pushq	(%r13)
	.cfi_adjust_cfa_offset 8
	pushq	(%r12)
	.cfi_adjust_cfa_offset 8
	callq	hipLaunchKernel
	addq	$160, %rsp
	.cfi_adjust_cfa_offset -160
	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_end5:
	.size	_Z35__device_stub__calculateFrameSharedPiS_PdiS_, .Lfunc_end5-_Z35__device_stub__calculateFrameSharedPiS_PdiS_
	.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	.LBB6_2
# %bb.1:
	movl	$__hip_fatbin_wrapper, %edi
	callq	__hipRegisterFatBinary
	movq	%rax, %rdi
	movq	%rax, __hip_gpubin_handle(%rip)
.LBB6_2:
	xorps	%xmm0, %xmm0
	movups	%xmm0, 16(%rsp)
	movups	%xmm0, (%rsp)
	movl	$_Z20calculateFrameSharedPiS_PdiS_, %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_end6:
	.size	__hip_module_ctor, .Lfunc_end6-__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	.LBB7_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
.LBB7_2:
	retq
.Lfunc_end7:
	.size	__hip_module_dtor, .Lfunc_end7-__hip_module_dtor
	.cfi_endproc
                                        # -- End function
	.type	input_file,@object              # @input_file
	.bss
	.globl	input_file
	.p2align	3, 0x0
input_file:
	.quad	0
	.size	input_file, 8

	.type	npd,@object                     # @npd
	.data
	.globl	npd
	.p2align	2, 0x0
npd:
	.long	517                             # 0x205
	.size	npd, 4

	.type	nk,@object                      # @nk
	.globl	nk
	.p2align	2, 0x0
nk:
	.long	10                              # 0xa
	.size	nk, 4

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

	.type	startwtime,@object              # @startwtime
	.globl	startwtime
	.p2align	3, 0x0
startwtime:
	.zero	16
	.size	startwtime, 16

	.type	endwtime,@object                # @endwtime
	.globl	endwtime
	.p2align	3, 0x0
endwtime:
	.zero	16
	.size	endwtime, 16

	.type	.L.str,@object                  # @.str
	.section	.rodata.str1.1,"aMS",@progbits,1
.L.str:
	.asciz	"Running with values n=%i, k=%i, o=%i\n"
	.size	.L.str, 38

	.type	.L.str.1,@object                # @.str.1
.L.str.1:
	.asciz	"Generating random data set. "
	.size	.L.str.1, 29

	.type	.L.str.2,@object                # @.str.2
.L.str.2:
	.asciz	"DONE in %fsec!\n"
	.size	.L.str.2, 16

	.type	.L__const.main.weight_matrix,@object # @__const.main.weight_matrix
	.section	.rodata,"a",@progbits
	.p2align	4, 0x0
.L__const.main.weight_matrix:
	.quad	0x3f70624dd2f1a9fc              # double 0.0040000000000000001
	.quad	0x3f90624dd2f1a9fc              # double 0.016
	.quad	0x3f9a9fbe76c8b439              # double 0.025999999999999999
	.quad	0x3f90624dd2f1a9fc              # double 0.016
	.quad	0x3f70624dd2f1a9fc              # double 0.0040000000000000001
	.quad	0x3f90624dd2f1a9fc              # double 0.016
	.quad	0x3fb22d0e56041893              # double 0.070999999999999994
	.quad	0x3fbdf3b645a1cac1              # double 0.11700000000000001
	.quad	0x3fb22d0e56041893              # double 0.070999999999999994
	.quad	0x3f90624dd2f1a9fc              # double 0.016
	.quad	0x3f9a9fbe76c8b439              # double 0.025999999999999999
	.quad	0x3fbdf3b645a1cac1              # double 0.11700000000000001
	.quad	0x0000000000000000              # double 0
	.quad	0x3fbdf3b645a1cac1              # double 0.11700000000000001
	.quad	0x3f9a9fbe76c8b439              # double 0.025999999999999999
	.quad	0x3f90624dd2f1a9fc              # double 0.016
	.quad	0x3fb22d0e56041893              # double 0.070999999999999994
	.quad	0x3fbdf3b645a1cac1              # double 0.11700000000000001
	.quad	0x3fb22d0e56041893              # double 0.070999999999999994
	.quad	0x3f90624dd2f1a9fc              # double 0.016
	.quad	0x3f70624dd2f1a9fc              # double 0.0040000000000000001
	.quad	0x3f90624dd2f1a9fc              # double 0.016
	.quad	0x3f9a9fbe76c8b439              # double 0.025999999999999999
	.quad	0x3f90624dd2f1a9fc              # double 0.016
	.quad	0x3f70624dd2f1a9fc              # double 0.0040000000000000001
	.size	.L__const.main.weight_matrix, 200

	.type	.L.str.3,@object                # @.str.3
	.section	.rodata.str1.1,"aMS",@progbits,1
.L.str.3:
	.asciz	"Running Ising Model Evolution. "
	.size	.L.str.3, 32

	.type	.L.str.4,@object                # @.str.4
.L.str.4:
	.asciz	"Saving data of each iteration. "
	.size	.L.str.4, 32

	.type	.L.str.5,@object                # @.str.5
.L.str.5:
	.asciz	"Saving last iteration. "
	.size	.L.str.5, 24

	.type	.L.str.9,@object                # @.str.9
.L.str.9:
	.asciz	"-n [Number]\t:Number of points per dimension (default:%i)\n"
	.size	.L.str.9, 58

	.type	.L.str.10,@object               # @.str.10
.L.str.10:
	.asciz	"-k [Iterations]\t:Number of iterations (default: %i)\n"
	.size	.L.str.10, 53

	.type	.L.str.12,@object               # @.str.12
.L.str.12:
	.asciz	"output-%i-%i-1.bin"
	.size	.L.str.12, 19

	.type	.L.str.13,@object               # @.str.13
.L.str.13:
	.asciz	"output-%i-%i.bin"
	.size	.L.str.13, 17

	.type	.L.str.14,@object               # @.str.14
.L.str.14:
	.asciz	"Exporting data to %s. "
	.size	.L.str.14, 23

	.type	.L.str.15,@object               # @.str.15
.L.str.15:
	.asciz	"wb"
	.size	.L.str.15, 3

	.type	.L.str.16,@object               # @.str.16
.L.str.16:
	.asciz	"Importing data from %s. "
	.size	.L.str.16, 25

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

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

	.type	.L.str.18,@object               # @.str.18
	.section	.rodata.str1.1,"aMS",@progbits,1
.L.str.18:
	.asciz	"Finished at %ith iteration. "
	.size	.L.str.18, 29

	.type	.L__unnamed_1,@object           # @0
.L__unnamed_1:
	.asciz	"_Z20calculateFrameSharedPiS_PdiS_"
	.size	.L__unnamed_1, 34

	.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	"Exiting"
	.size	.Lstr, 8

	.type	.Lstr.1,@object                 # @str.1
.Lstr.1:
	.asciz	"Flags to use:"
	.size	.Lstr.1, 14

	.type	.Lstr.2,@object                 # @str.2
.Lstr.2:
	.asciz	"-f [File]\t:Input file of points"
	.size	.Lstr.2, 32

	.type	.Lstr.3,@object                 # @str.3
.Lstr.3:
	.asciz	"-o [0|1|2]\t:Export each iteration to output*.bin (0 = None(default), 1 = All, 2 = Last)"
	.size	.Lstr.3, 88

	.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 _Z35__device_stub__calculateFrameSharedPiS_PdiS_
	.addrsig_sym __hip_module_ctor
	.addrsig_sym __hip_module_dtor
	.addrsig_sym startwtime
	.addrsig_sym endwtime
	.addrsig_sym _Z20calculateFrameSharedPiS_PdiS_
	.addrsig_sym __hip_fatbin
	.addrsig_sym __hip_fatbin_wrapper
	.addrsig_sym __hip_cuid_

	.text
	.amdgcn_target "amdgcn-amd-amdhsa--gfx1100"
	.protected	_Z20calculateFrameSharedPiS_PdiS_ ; -- Begin function _Z20calculateFrameSharedPiS_PdiS_
	.globl	_Z20calculateFrameSharedPiS_PdiS_
	.p2align	8
	.type	_Z20calculateFrameSharedPiS_PdiS_,@function
_Z20calculateFrameSharedPiS_PdiS_:      ; @_Z20calculateFrameSharedPiS_PdiS_
; %bb.0:
	s_clause 0x1
	s_load_b128 s[4:7], s[0:1], 0x0
	s_load_b64 s[8:9], s[0:1], 0x10
	v_and_b32_e32 v2, 0x3ff, v0
	v_bfe_u32 v3, v0, 10, 10
	s_mov_b32 s12, 0
	s_delay_alu instid0(VALU_DEP_2) | instskip(NEXT) | instid1(VALU_DEP_2)
	v_cmp_gt_u32_e32 vcc_lo, 25, v2
	v_cmp_eq_u32_e64 s2, 0, v3
	s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(SALU_CYCLE_1)
	s_and_b32 s3, vcc_lo, s2
	s_and_saveexec_b32 s2, s3
	s_cbranch_execz .LBB0_2
; %bb.1:
	v_lshlrev_b32_e32 v4, 3, v2
	s_waitcnt lgkmcnt(0)
	global_load_b64 v[0:1], v4, s[8:9]
	s_waitcnt vmcnt(0)
	ds_store_b64 v4, v[0:1] offset:1728
.LBB0_2:
	s_or_b32 exec_lo, exec_lo, s2
	s_load_b32 s13, s[0:1], 0x18
	s_waitcnt lgkmcnt(0)
	s_load_b64 s[8:9], s[0:1], 0x20
	s_lshl_b32 s2, s14, 5
	v_lshlrev_b32_e32 v9, 2, v2
	v_lshl_add_u32 v4, s15, 5, v3
	v_cmp_gt_u32_e32 vcc_lo, 12, v3
	s_mov_b32 s10, 0xa0b5ed8d
	s_mov_b32 s11, 0x3eb0c6f7
	s_mov_b32 s3, 0xbeb0c6f7
	s_ashr_i32 s0, s13, 31
	s_delay_alu instid0(SALU_CYCLE_1) | instskip(NEXT) | instid1(SALU_CYCLE_1)
	s_add_i32 s1, s13, s0
	s_xor_b32 s16, s1, s0
	s_delay_alu instid0(SALU_CYCLE_1) | instskip(SKIP_1) | instid1(VALU_DEP_1)
	v_cvt_f32_u32_e32 v0, s16
	s_sub_i32 s0, 0, s16
	v_rcp_iflag_f32_e32 v0, v0
	s_waitcnt_depctr 0xfff
	v_dual_mul_f32 v1, 0x4f7ffffe, v0 :: v_dual_add_nc_u32 v0, s2, v2
	s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(VALU_DEP_2)
	v_cvt_u32_f32_e32 v8, v1
	v_ashrrev_i32_e32 v1, 31, v0
	s_delay_alu instid0(VALU_DEP_2) | instskip(NEXT) | instid1(VALU_DEP_2)
	v_mul_lo_u32 v5, s0, v8
	v_lshlrev_b64 v[6:7], 2, v[0:1]
	v_cmp_gt_u32_e64 s0, 36, v2
	s_delay_alu instid0(VALU_DEP_2) | instskip(NEXT) | instid1(VALU_DEP_4)
	v_add_co_u32 v6, s1, s6, v6
	v_mul_hi_u32 v1, v8, v5
	s_delay_alu instid0(VALU_DEP_4)
	v_add_co_ci_u32_e64 v7, s1, s7, v7, s1
	v_mad_u32_u24 v5, 0x90, v3, v9
	v_cmp_gt_i32_e64 s1, s13, v0
	s_add_i32 s6, s13, -2
	v_mov_b32_e32 v9, 0
	s_add_i32 s7, s6, s2
	v_add_nc_u32_e32 v8, v8, v1
.LBB0_3:                                ; %.preheader73
                                        ; =>This Loop Header: Depth=1
                                        ;     Child Loop BB0_5 Depth 2
                                        ;       Child Loop BB0_7 Depth 3
                                        ;     Child Loop BB0_11 Depth 2
                                        ;       Child Loop BB0_12 Depth 3
	s_and_saveexec_b32 s14, vcc_lo
	s_cbranch_execz .LBB0_9
; %bb.4:                                ; %.lr.ph78
                                        ;   in Loop: Header=BB0_3 Depth=1
	v_dual_mov_b32 v1, v5 :: v_dual_add_nc_u32 v0, s6, v4
	v_mov_b32_e32 v10, v3
	s_mov_b32 s15, 0
	s_mov_b32 s17, 0
.LBB0_5:                                ;   Parent Loop BB0_3 Depth=1
                                        ; =>  This Loop Header: Depth=2
                                        ;       Child Loop BB0_7 Depth 3
	s_and_saveexec_b32 s18, s0
	s_cbranch_execz .LBB0_8
; %bb.6:                                ; %.lr.ph
                                        ;   in Loop: Header=BB0_5 Depth=2
	v_lshl_add_u32 v11, s17, 3, v0
	s_mov_b32 s19, 0
	s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(VALU_DEP_1)
	v_ashrrev_i32_e32 v12, 31, v11
	v_add_nc_u32_e32 v11, v11, v12
	s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(VALU_DEP_1)
	v_xor_b32_e32 v11, v11, v12
	v_mul_hi_u32 v13, v11, v8
	s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(VALU_DEP_1)
	v_mul_lo_u32 v13, v13, s16
	v_sub_nc_u32_e32 v11, v11, v13
	s_delay_alu instid0(VALU_DEP_1) | instskip(SKIP_1) | instid1(VALU_DEP_1)
	v_subrev_nc_u32_e32 v13, s16, v11
	v_cmp_le_u32_e64 s2, s16, v11
	v_cndmask_b32_e64 v11, v11, v13, s2
	s_delay_alu instid0(VALU_DEP_1) | instskip(SKIP_1) | instid1(VALU_DEP_1)
	v_subrev_nc_u32_e32 v13, s16, v11
	v_cmp_le_u32_e64 s2, s16, v11
	v_cndmask_b32_e64 v11, v11, v13, s2
	v_mov_b32_e32 v13, v2
	s_delay_alu instid0(VALU_DEP_2) | instskip(NEXT) | instid1(VALU_DEP_1)
	v_xor_b32_e32 v11, v11, v12
	v_sub_nc_u32_e32 v11, v11, v12
	v_mov_b32_e32 v12, v1
	s_delay_alu instid0(VALU_DEP_2)
	v_mul_lo_u32 v11, v11, s13
.LBB0_7:                                ;   Parent Loop BB0_3 Depth=1
                                        ;     Parent Loop BB0_5 Depth=2
                                        ; =>    This Inner Loop Header: Depth=3
	v_add_nc_u32_e32 v14, s7, v13
	s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(VALU_DEP_1)
	v_ashrrev_i32_e32 v15, 31, v14
	v_add_nc_u32_e32 v14, v14, v15
	s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(VALU_DEP_1)
	v_xor_b32_e32 v14, v14, v15
	v_mul_hi_u32 v16, v14, v8
	s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(VALU_DEP_1)
	v_mul_lo_u32 v16, v16, s16
	v_sub_nc_u32_e32 v14, v14, v16
	s_delay_alu instid0(VALU_DEP_1) | instskip(SKIP_1) | instid1(VALU_DEP_1)
	v_subrev_nc_u32_e32 v16, s16, v14
	v_cmp_le_u32_e64 s2, s16, v14
	v_cndmask_b32_e64 v14, v14, v16, s2
	s_delay_alu instid0(VALU_DEP_1) | instskip(SKIP_1) | instid1(VALU_DEP_1)
	v_subrev_nc_u32_e32 v16, s16, v14
	v_cmp_le_u32_e64 s2, s16, v14
	v_cndmask_b32_e64 v14, v14, v16, s2
	s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(VALU_DEP_1)
	v_xor_b32_e32 v14, v14, v15
	v_sub_nc_u32_e32 v14, v14, v15
	s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(VALU_DEP_1)
	v_add_nc_u32_e32 v14, v14, v11
	v_ashrrev_i32_e32 v15, 31, v14
	s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(VALU_DEP_1)
	v_lshlrev_b64 v[14:15], 2, v[14:15]
	v_add_co_u32 v14, s2, s4, v14
	s_delay_alu instid0(VALU_DEP_1) | instskip(SKIP_4) | instid1(VALU_DEP_1)
	v_add_co_ci_u32_e64 v15, s2, s5, v15, s2
	v_cmp_lt_u32_e64 s2, 3, v13
	global_load_b32 v14, v[14:15], off
	v_add_nc_u32_e32 v15, 32, v13
	s_or_b32 s19, s2, s19
	v_mov_b32_e32 v13, v15
	s_waitcnt vmcnt(0)
	ds_store_b32 v12, v14
	v_add_nc_u32_e32 v12, 0x80, v12
	s_and_not1_b32 exec_lo, exec_lo, s19
	s_cbranch_execnz .LBB0_7
.LBB0_8:                                ; %Flow125
                                        ;   in Loop: Header=BB0_5 Depth=2
	s_or_b32 exec_lo, exec_lo, s18
	v_add_nc_u32_e32 v11, 8, v10
	v_cmp_lt_u32_e64 s2, 3, v10
	v_add_nc_u32_e32 v1, 0x480, v1
	s_add_i32 s17, s17, 1
	s_delay_alu instid0(VALU_DEP_3) | instskip(NEXT) | instid1(VALU_DEP_3)
	v_mov_b32_e32 v10, v11
	s_or_b32 s15, s2, s15
	s_delay_alu instid0(SALU_CYCLE_1)
	s_and_not1_b32 exec_lo, exec_lo, s15
	s_cbranch_execnz .LBB0_5
.LBB0_9:                                ; %Flow127
                                        ;   in Loop: Header=BB0_3 Depth=1
	s_or_b32 exec_lo, exec_lo, s14
	v_cmp_gt_i32_e64 s2, s13, v4
	s_waitcnt lgkmcnt(0)
	s_barrier
	buffer_gl0_inv
	s_and_b32 s2, s1, s2
	s_delay_alu instid0(SALU_CYCLE_1)
	s_and_saveexec_b32 s14, s2
	s_cbranch_execz .LBB0_20
; %bb.10:                               ; %.preheader.preheader
                                        ;   in Loop: Header=BB0_3 Depth=1
	v_mov_b32_e32 v0, 0
	v_dual_mov_b32 v1, 0 :: v_dual_mov_b32 v10, v5
	s_mov_b32 s2, -2
	s_movk_i32 s15, 0x6c0
.LBB0_11:                               ; %.preheader
                                        ;   Parent Loop BB0_3 Depth=1
                                        ; =>  This Loop Header: Depth=2
                                        ;       Child Loop BB0_12 Depth 3
	s_movk_i32 s17, 0xffec
	s_mov_b32 s18, s15
.LBB0_12:                               ;   Parent Loop BB0_3 Depth=1
                                        ;     Parent Loop BB0_11 Depth=2
                                        ; =>    This Inner Loop Header: Depth=3
	v_add_nc_u32_e32 v11, s17, v10
	v_mov_b32_e32 v13, s18
	s_add_i32 s17, s17, 4
	s_add_i32 s18, s18, 8
	s_cmp_eq_u32 s17, 0
	ds_load_b32 v11, v11 offset:20
	ds_load_b64 v[13:14], v13
	s_waitcnt lgkmcnt(1)
	v_cvt_f64_i32_e32 v[11:12], v11
	s_waitcnt lgkmcnt(0)
	s_delay_alu instid0(VALU_DEP_1)
	v_fma_f64 v[0:1], v[13:14], v[11:12], v[0:1]
	s_cbranch_scc0 .LBB0_12
; %bb.13:                               ;   in Loop: Header=BB0_11 Depth=2
	v_add_nc_u32_e32 v10, 0x90, v10
	s_add_i32 s2, s2, 1
	s_add_i32 s15, s15, 40
	s_cmp_eq_u32 s2, 3
	s_cbranch_scc0 .LBB0_11
; %bb.14:                               ;   in Loop: Header=BB0_3 Depth=1
	v_mov_b32_e32 v10, 1
	s_mov_b32 s15, exec_lo
	s_delay_alu instid0(VALU_DEP_3)
	v_cmpx_nlt_f64_e32 s[10:11], v[0:1]
	s_cbranch_execz .LBB0_18
; %bb.15:                               ;   in Loop: Header=BB0_3 Depth=1
	v_mov_b32_e32 v10, -1
	s_mov_b32 s2, s10
	s_mov_b32 s17, exec_lo
	v_cmpx_ngt_f64_e32 s[2:3], v[0:1]
	s_cbranch_execz .LBB0_17
; %bb.16:                               ;   in Loop: Header=BB0_3 Depth=1
	ds_load_b32 v10, v5 offset:296
.LBB0_17:                               ; %Flow122
                                        ;   in Loop: Header=BB0_3 Depth=1
	s_or_b32 exec_lo, exec_lo, s17
.LBB0_18:                               ;   in Loop: Header=BB0_3 Depth=1
	s_delay_alu instid0(SALU_CYCLE_1) | instskip(SKIP_3) | instid1(VALU_DEP_1)
	s_or_b32 exec_lo, exec_lo, s15
	v_mul_lo_u32 v0, v4, s13
	ds_load_b32 v11, v5 offset:296
	v_ashrrev_i32_e32 v1, 31, v0
	v_lshlrev_b64 v[0:1], 2, v[0:1]
	s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(VALU_DEP_1)
	v_add_co_u32 v0, s2, v6, v0
	v_add_co_ci_u32_e64 v1, s2, v7, v1, s2
	s_waitcnt lgkmcnt(0)
	v_cmp_ne_u32_e64 s2, v10, v11
	global_store_b32 v[0:1], v10, off
	s_and_b32 exec_lo, exec_lo, s2
	s_cbranch_execz .LBB0_20
; %bb.19:                               ;   in Loop: Header=BB0_3 Depth=1
	global_store_b32 v9, v9, s[8:9]
.LBB0_20:                               ; %Flow123
                                        ;   in Loop: Header=BB0_3 Depth=1
	s_or_b32 exec_lo, exec_lo, s14
	v_add_nc_u32_e32 v4, 8, v4
	s_add_i32 s2, s12, 8
	s_cmp_gt_u32 s12, 23
	s_mov_b32 s12, s2
	s_waitcnt_vscnt null, 0x0
	s_barrier
	buffer_gl0_inv
	s_cbranch_scc0 .LBB0_3
; %bb.21:
	s_endpgm
	.section	.rodata,"a",@progbits
	.p2align	6, 0x0
	.amdhsa_kernel _Z20calculateFrameSharedPiS_PdiS_
		.amdhsa_group_segment_fixed_size 1928
		.amdhsa_private_segment_fixed_size 0
		.amdhsa_kernarg_size 40
		.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 17
		.amdhsa_next_free_sgpr 20
		.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	_Z20calculateFrameSharedPiS_PdiS_, .Lfunc_end0-_Z20calculateFrameSharedPiS_PdiS_
                                        ; -- End function
	.section	.AMDGPU.csdata,"",@progbits
; Kernel info:
; codeLenInByte = 1104
; NumSgprs: 22
; NumVgprs: 17
; ScratchSize: 0
; MemoryBound: 0
; FloatMode: 240
; IeeeMode: 1
; LDSByteSize: 1928 bytes/workgroup (compile time only)
; SGPRBlocks: 2
; VGPRBlocks: 2
; NumSGPRsForWavesPerEU: 22
; NumVGPRsForWavesPerEU: 17
; Occupancy: 16
; WaveLimiterHint : 0
; 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
      - .address_space:  global
        .offset:         16
        .size:           8
        .value_kind:     global_buffer
      - .offset:         24
        .size:           4
        .value_kind:     by_value
      - .address_space:  global
        .offset:         32
        .size:           8
        .value_kind:     global_buffer
    .group_segment_fixed_size: 1928
    .kernarg_segment_align: 8
    .kernarg_segment_size: 40
    .language:       OpenCL C
    .language_version:
      - 2
      - 0
    .max_flat_workgroup_size: 1024
    .name:           _Z20calculateFrameSharedPiS_PdiS_
    .private_segment_fixed_size: 0
    .sgpr_count:     22
    .sgpr_spill_count: 0
    .symbol:         _Z20calculateFrameSharedPiS_PdiS_.kd
    .uniform_work_group_size: 1
    .uses_dynamic_stack: false
    .vgpr_count:     17
    .vgpr_spill_count: 0
    .wavefront_size: 32
    .workgroup_processor_mode: 1
amdhsa.target:   amdgcn-amd-amdhsa--gfx1100
amdhsa.version:
  - 1
  - 2
...

	.end_amdgpu_metadata
