/*
 * dgemm_gpu_shared.cu
 *
 * compile with: make dgemm_gpu_shared
 *    -> nvcc -O3 -arch=sm_20 -o dgemm_gpu_shared dgemm_gpu_shared.cu -lcudart
 *
 * Matrices are stored as array in row-major order: 
 * A[row][col] = A[row * N + col]
 *
 * Use shared memory to speed up the matrix multiplication. We can reuse
 * the memory if we load a block of the matrix and have a thread block 
 * calculate a sub matrix.
 */


#include <stdio.h>
#include <assert.h>
#include <cuda.h>

// Thread block size: BLOCK_SIZE * BLOCK_SIZE
#define BLOCK_SIZE 16

// Declaration of helper functions (see bottom of file for details)
void checkError (const char* action);
float getGflops (int, float);

/*
 *  Matrix multiplication kernel called by matrixMulOnDevice() 
 */
__global__ void dgemm_gpu_shared(double* a, double* b, double* c, int n){
    
    // TODO: Allocate shared memory for the two blocks aSub and bSub.
    //       Use two-dimensional matrices of size BLOCK_SIZE * BLOCK_SIZE 
    __shared__ double aSub[BLOCK_SIZE][BLOCK_SIZE];
    __shared__ double bSub[BLOCK_SIZE][BLOCK_SIZE];
    
    // TODO: Calculate global thread index 
    int idxX = blockIdx.x * BLOCK_SIZE + threadIdx.x;
    int idxY = blockIdx.y * BLOCK_SIZE + threadIdx.y;

    // For the matrix multiplication, we need to multiply all the elements of 
    // the idxYth row of a with all the elements of the idXth column of b and 
    // sum up the results.
    double sum = 0;

    // TODO: Calculate global offset of upper left corner of thread block.
    int blockaY = blockIdx.y * BLOCK_SIZE;
    int blockbX = blockIdx.x * BLOCK_SIZE;

    for (int block = 0; block < gridDim.x; ++block){
      // Get the two sub matrices
      int blockaX = block * (BLOCK_SIZE);
      int blockbY = block * (BLOCK_SIZE);
      if (((blockaY + threadIdx.y) < n) && (blockaX + threadIdx.x) < n) {
        // TODO: Copy block into shared memory
        aSub[threadIdx.y][threadIdx.x] = a[(blockaY + threadIdx.y) * n + blockaX + threadIdx.x];
      } else {
        aSub[threadIdx.y][threadIdx.x] = 0;
      }

      if (((blockbY + threadIdx.y) < n) && (blockbX + threadIdx.x) < n) {
        bSub[threadIdx.y][threadIdx.x] = b[(blockbY + threadIdx.y) * n + blockbX + threadIdx.x];
      } else {
        bSub[threadIdx.y][threadIdx.x] = 0;
      }
	
	    // TODO: Synchronize threads to make sure all threads are done copying
      __syncthreads();
    
      if ((idxX < n) && (idxY < n))
      {
        for (int i=0; i < blockDim.x; ++i){ //assumes that we use square blocks
          sum += aSub[threadIdx.y][i] * bSub[i][threadIdx.x];
        }
      }
	    // TODO: Synchronize threads to make sure all threads are done with the data
      __syncthreads();
    }

    if ((idxX < n) && (idxY < n)){    
      c[idxY * n + idxX] = sum;
    }
}



/*
 *  Matrix multiplication host function called by main() 
 */

void matrixMulOnDevice(double* a, double* b, double* c, int n)
{
    int size = n * n * sizeof(double);
    int xGrid, yGrid;
    double *d_a, *d_b, *d_c;
    float time;

    // Define events for timing
    cudaEvent_t start, stop;
  
    cudaEventCreate(&start);
    cudaEventCreate(&stop);
    
    // TODO
    // Allocate memory for d_a, d_b and d_c on device
    cudaMalloc((void **)&d_a, size );
    checkError("cudaMalloc: d_a");
    cudaMalloc((void **)&d_b, size );
    checkError("cudaMalloc: d_b");  
    cudaMalloc((void **)&d_c, size );
    checkError("cudaMalloc: d_c");
    
    
    // First calculate grid size by dividing n by BLOCK_SIZE = 16
    xGrid = (n % BLOCK_SIZE == 0) ? (n / BLOCK_SIZE) : (n / BLOCK_SIZE + 1);
    yGrid = (n % BLOCK_SIZE == 0) ? (n / BLOCK_SIZE) : (n / BLOCK_SIZE + 1);
    dim3 gridDim(xGrid, yGrid);
    dim3 blockDim(BLOCK_SIZE, BLOCK_SIZE);

    printf("Grid: %d, %d; block:%d, %d\n", xGrid , yGrid , BLOCK_SIZE, BLOCK_SIZE);
    
    // Invoke kernel and measure execution time 
    cudaEventRecord( start, 0 );
    
    // TODO
    // Copy data for a and b from host to device
    cudaMemcpy(d_a, a, size, cudaMemcpyHostToDevice);
    checkError("copying data of A from host to device");
    cudaMemcpy(d_b, b, size, cudaMemcpyHostToDevice);
    checkError("copying data of B from host to device");
  
    // TODO: Call the kernel 
    dgemm_gpu_shared<<<gridDim, blockDim>>>( d_a, d_b, d_c, n);
    
    // TODO
    // Read restults from device memory to C 
    cudaMemcpy(c, d_c, size, cudaMemcpyDeviceToHost);
    checkError("cudaMemcpyDeviceToHost");
    
    // Get elapsed time for kernel execution
    cudaEventRecord( stop, 0 );
    cudaEventSynchronize( stop );
    checkError("executing Kernel");
    cudaEventElapsedTime( &time, start, stop );
    cudaEventDestroy( start );
    cudaEventDestroy( stop );

    printf ("\nKernel Execution Time: %f ms (dim C: %d * %d)", time, n, n);
    printf ("\nThis corresponds to: %4.4f GFLOPS", getGflops(n, time));
  
    
    // Free device memory 
    cudaFree(d_a);
    checkError("Freeing d_a");
    cudaFree(d_b);
    checkError("Freeing d_b");
    cudaFree(d_c);
    checkError("Freeing d_c");

}

int main(int argc, char** argv)
{
  int n = 1024;
  double *a, *b, *c;
  int row, col;
  double absError, maxAbsError = 0.0, sumAbsError = 0.0;
 
  if (argc > 1) {
    n = atoi(argv[1]);
  }

    
  // show banner
  printf ("\n\n     Matrix-Multiplication \n");
  printf (    "     ==========================================\n");
  printf (  "\n     Simple DGEMM implemantation on GPU");  

  // echo device data
  int idevice = 0;
  cudaSetDevice(idevice);
  cudaDeviceProp dprops;
  cudaGetDeviceProperties( &dprops, idevice );
  printf ("\n     Device name = %s, with compute capability %d.%d \n", 
	  dprops.name, dprops.major, dprops.minor);
  printf (  "\n     Matrix size %d x %d", n, n);
  
    
  // Allocate memory for matrices on host
  assert ( a = (double*) malloc (n * n * sizeof(double)) );
  assert ( b = (double*) malloc (n * n * sizeof(double)) );
  assert ( c = (double*) malloc (n * n * sizeof(double)) );
    
  // Init matrices A and B: A = E so result will be B
#pragma omp parallel for private(row, col)
  for (row = 0; row < n; ++row){
    for (col = 0; col < n; col++){
	    a[row * n + col] = (row == col) ? 1.0 : 0.0;
	    b[row * n + col] = row * n + col;
     }
  }

    // do matrix multiplication on device
    matrixMulOnDevice(a, b, c, n);
     
    // Compare results
  for ( row = 0; row < n; ++row){
    for ( col = 0; col < n; ++col) {
	
	    absError = fabs ( c[row * n + col] - b[row * n + col]);
	    sumAbsError += absError;
	
	    if (absError > maxAbsError)
	      maxAbsError = absError;
      }
    }
    // Free memory on host
    free (a);
    free (b);
    free (c);
  
    printf ("\nmaxAbsError: %4.4f, sumAbsError: %4.4f", maxAbsError, sumAbsError);
    if (maxAbsError < 2.0e-5) {
      printf ("\n\nProgram terminated SUCCESSFULLY.\n\n");
    } else {
      printf ("\n\nProgram terminated UNSUCCESSFULLY.\n\n");
    }
    return 0;
}

/*
 *  Some helper functions
 */

// get compute performance
float getGflops (int n, float time) {

	float gf = (2.0e-6 * n * n* n / time);

	return gf;
}

// Simple error checking function for CUDA actions

void checkError (const char* action) {
  
  cudaError_t error;
  error = cudaGetLastError(); 

  if (error != cudaSuccess) {
    printf ("\nError while '%s': %s\nprogram terminated ...\n\n", action, cudaGetErrorString(error));
    exit (EXIT_FAILURE);
  }
}

	.file	"tmpxft_0036d472_00000000-6_dgemm_gpu_shared.cudafe1.cpp"
	.text
#APP

#NO_APP
	.type	_ZL26__cudaUnregisterBinaryUtilv, @function
_ZL26__cudaUnregisterBinaryUtilv:
.LFB2033:
	.cfi_startproc
	endbr64
	movq	_ZL20__cudaFatCubinHandle(%rip), %rdi
	jmp	__cudaUnregisterFatBinary@PLT
	.cfi_endproc
.LFE2033:
	.size	_ZL26__cudaUnregisterBinaryUtilv, .-_ZL26__cudaUnregisterBinaryUtilv
	.globl	_Z9getGflopsif
	.type	_Z9getGflopsif, @function
_Z9getGflopsif:
.LFB2029:
	.cfi_startproc
	endbr64
	cvtsi2sdl	%edi, %xmm2
	movaps	%xmm0, %xmm1
	movsd	.LC0(%rip), %xmm0
	cvtss2sd	%xmm1, %xmm1
	mulsd	%xmm2, %xmm0
	mulsd	%xmm2, %xmm0
	mulsd	%xmm2, %xmm0
	divsd	%xmm1, %xmm0
	cvtsd2ss	%xmm0, %xmm0
	ret
	.cfi_endproc
.LFE2029:
	.size	_Z9getGflopsif, .-_Z9getGflopsif
	.section	.rodata.str1.1,"aMS",@progbits,1
.LC1:
	.string	"\nError while '%s': %s\nprogram terminated ...\n\n"
	.text
	.globl	_Z10checkErrorPKc
	.type	_Z10checkErrorPKc, @function
_Z10checkErrorPKc:
.LFB2030:
	.cfi_startproc
	endbr64
	pushq	%rbx
	.cfi_def_cfa_offset 16
	.cfi_offset 3, -16
	movq	%rdi, %rbx
	call	cudaGetLastError@PLT
	testl	%eax, %eax
	je	.L3
	movl	%eax, %edi
	call	cudaGetErrorString@PLT
	movl	$2, %edi
	movq	%rbx, %rdx
	leaq	.LC1(%rip), %rsi
	movq	%rax, %rcx
	xorl	%eax, %eax
	call	__printf_chk@PLT
	movl	$1, %edi
	call	exit@PLT
.L3:
	popq	%rbx
	.cfi_def_cfa_offset 8
	ret
	.cfi_endproc
.LFE2030:
	.size	_Z10checkErrorPKc, .-_Z10checkErrorPKc
	.globl	_Z41__device_stub__Z16dgemm_gpu_sharedPdS_S_iPdS_S_i
	.type	_Z41__device_stub__Z16dgemm_gpu_sharedPdS_S_iPdS_S_i, @function
_Z41__device_stub__Z16dgemm_gpu_sharedPdS_S_iPdS_S_i:
.LFB2055:
	.cfi_startproc
	endbr64
	subq	$152, %rsp
	.cfi_def_cfa_offset 160
	movq	%rdi, 24(%rsp)
	leaq	56(%rsp), %rdi
	movq	%rsi, 16(%rsp)
	leaq	68(%rsp), %rsi
	movq	%rdx, 8(%rsp)
	leaq	40(%rsp), %rdx
	movl	%ecx, 4(%rsp)
	leaq	48(%rsp), %rcx
	movq	%fs:40, %rax
	movq	%rax, 136(%rsp)
	xorl	%eax, %eax
	leaq	24(%rsp), %rax
	movl	$1, 64(%rsp)
	movq	%rax, 104(%rsp)
	leaq	16(%rsp), %rax
	movq	%rax, 112(%rsp)
	leaq	8(%rsp), %rax
	movq	%rax, 120(%rsp)
	leaq	4(%rsp), %rax
	movq	%rax, 128(%rsp)
	movabsq	$4294967297, %rax
	movq	%rax, 56(%rsp)
	movq	%rax, 68(%rsp)
	movl	$1, 76(%rsp)
	call	__cudaPopCallConfiguration@PLT
	testl	%eax, %eax
	jne	.L7
	pushq	48(%rsp)
	.cfi_def_cfa_offset 168
	leaq	_Z16dgemm_gpu_sharedPdS_S_i(%rip), %rdi
	pushq	48(%rsp)
	.cfi_def_cfa_offset 176
	movq	84(%rsp), %rcx
	movl	92(%rsp), %r8d
	movq	72(%rsp), %rsi
	movl	80(%rsp), %edx
	leaq	120(%rsp), %r9
	call	cudaLaunchKernel@PLT
	popq	%rax
	.cfi_def_cfa_offset 168
	popq	%rdx
	.cfi_def_cfa_offset 160
.L7:
	movq	136(%rsp), %rax
	subq	%fs:40, %rax
	je	.L9
	call	__stack_chk_fail@PLT
.L9:
	addq	$152, %rsp
	.cfi_def_cfa_offset 8
	ret
	.cfi_endproc
.LFE2055:
	.size	_Z41__device_stub__Z16dgemm_gpu_sharedPdS_S_iPdS_S_i, .-_Z41__device_stub__Z16dgemm_gpu_sharedPdS_S_iPdS_S_i
	.globl	_Z16dgemm_gpu_sharedPdS_S_i
	.type	_Z16dgemm_gpu_sharedPdS_S_i, @function
_Z16dgemm_gpu_sharedPdS_S_i:
.LFB2056:
	.cfi_startproc
	endbr64
	jmp	_Z41__device_stub__Z16dgemm_gpu_sharedPdS_S_iPdS_S_i
	.cfi_endproc
.LFE2056:
	.size	_Z16dgemm_gpu_sharedPdS_S_i, .-_Z16dgemm_gpu_sharedPdS_S_i
	.section	.rodata.str1.1
.LC2:
	.string	"cudaMalloc: d_a"
.LC3:
	.string	"cudaMalloc: d_b"
.LC4:
	.string	"cudaMalloc: d_c"
.LC5:
	.string	"Grid: %d, %d; block:%d, %d\n"
.LC6:
	.string	"copying data of A from host to device"
.LC7:
	.string	"copying data of B from host to device"
.LC8:
	.string	"cudaMemcpyDeviceToHost"
.LC9:
	.string	"executing Kernel"
.LC10:
	.string	"\nKernel Execution Time: %f ms (dim C: %d * %d)"
.LC11:
	.string	"\nThis corresponds to: %4.4f GFLOPS"
.LC12:
	.string	"Freeing d_a"
.LC13:
	.string	"Freeing d_b"
.LC14:
	.string	"Freeing d_c"
	.text
	.globl	_Z17matrixMulOnDevicePdS_S_i
	.type	_Z17matrixMulOnDevicePdS_S_i, @function
_Z17matrixMulOnDevicePdS_S_i:
.LFB2027:
	.cfi_startproc
	endbr64
	pushq	%r14
	.cfi_def_cfa_offset 16
	.cfi_offset 14, -16
	movq	%rdi, %r14
	pushq	%r13
	.cfi_def_cfa_offset 24
	.cfi_offset 13, -24
	movq	%rsi, %r13
	pushq	%r12
	.cfi_def_cfa_offset 32
	.cfi_offset 12, -32
	movq	%rdx, %r12
	pushq	%rbp
	.cfi_def_cfa_offset 40
	.cfi_offset 6, -40
	pushq	%rbx
	.cfi_def_cfa_offset 48
	.cfi_offset 3, -48
	movl	%ecx, %ebx
	movl	%ebx, %ebp
	imull	%ebx, %ebp
	subq	$80, %rsp
	.cfi_def_cfa_offset 128
	movq	%fs:40, %rax
	movq	%rax, 72(%rsp)
	xorl	%eax, %eax
	leaq	32(%rsp), %rdi
	call	cudaEventCreate@PLT
	sall	$3, %ebp
	leaq	40(%rsp), %rdi
	call	cudaEventCreate@PLT
	movslq	%ebp, %rbp
	leaq	8(%rsp), %rdi
	movq	%rbp, %rsi
	call	cudaMalloc@PLT
	leaq	.LC2(%rip), %rdi
	call	_Z10checkErrorPKc
	movq	%rbp, %rsi
	leaq	16(%rsp), %rdi
	call	cudaMalloc@PLT
	leaq	.LC3(%rip), %rdi
	call	_Z10checkErrorPKc
	movq	%rbp, %rsi
	leaq	24(%rsp), %rdi
	call	cudaMalloc@PLT
	leaq	.LC4(%rip), %rdi
	call	_Z10checkErrorPKc
	movl	%ebx, %eax
	movl	$16, %ecx
	movl	$16, %r9d
	cltd
	movl	$16, %r8d
	leaq	.LC5(%rip), %rsi
	movl	$2, %edi
	idivl	%ecx
	movl	$1, 56(%rsp)
	movl	$1, 68(%rsp)
	movl	%ebx, %edx
	andl	$15, %edx
	cmpl	$1, %edx
	sbbl	$-1, %eax
	movl	%eax, %edx
	movl	%eax, 48(%rsp)
	movl	%eax, 52(%rsp)
	movl	%edx, %ecx
	movabsq	$68719476752, %rax
	movq	%rax, 60(%rsp)
	xorl	%eax, %eax
	call	__printf_chk@PLT
	movq	32(%rsp), %rdi
	xorl	%esi, %esi
	call	cudaEventRecord@PLT
	movq	8(%rsp), %rdi
	movq	%rbp, %rdx
	movq	%r14, %rsi
	movl	$1, %ecx
	call	cudaMemcpy@PLT
	leaq	.LC6(%rip), %rdi
	call	_Z10checkErrorPKc
	movq	16(%rsp), %rdi
	movq	%rbp, %rdx
	movq	%r13, %rsi
	movl	$1, %ecx
	call	cudaMemcpy@PLT
	leaq	.LC7(%rip), %rdi
	call	_Z10checkErrorPKc
	movl	68(%rsp), %ecx
	movl	56(%rsp), %esi
	xorl	%r9d, %r9d
	movq	60(%rsp), %rdx
	movq	48(%rsp), %rdi
	xorl	%r8d, %r8d
	call	__cudaPushCallConfiguration@PLT
	testl	%eax, %eax
	jne	.L14
	movq	24(%rsp), %rdx
	movq	16(%rsp), %rsi
	movl	%ebx, %ecx
	movq	8(%rsp), %rdi
	call	_Z41__device_stub__Z16dgemm_gpu_sharedPdS_S_iPdS_S_i
.L14:
	movq	24(%rsp), %rsi
	movl	$2, %ecx
	movq	%rbp, %rdx
	movq	%r12, %rdi
	call	cudaMemcpy@PLT
	leaq	.LC8(%rip), %rdi
	call	_Z10checkErrorPKc
	movq	40(%rsp), %rdi
	xorl	%esi, %esi
	call	cudaEventRecord@PLT
	movq	40(%rsp), %rdi
	call	cudaEventSynchronize@PLT
	leaq	.LC9(%rip), %rdi
	call	_Z10checkErrorPKc
	movq	40(%rsp), %rdx
	movq	32(%rsp), %rsi
	leaq	4(%rsp), %rdi
	call	cudaEventElapsedTime@PLT
	movq	32(%rsp), %rdi
	call	cudaEventDestroy@PLT
	movq	40(%rsp), %rdi
	call	cudaEventDestroy@PLT
	movl	%ebx, %ecx
	movl	%ebx, %edx
	leaq	.LC10(%rip), %rsi
	movl	$2, %edi
	movb	$1, %al
	cvtss2sd	4(%rsp), %xmm0
	call	__printf_chk@PLT
	movss	4(%rsp), %xmm0
	movl	%ebx, %edi
	movb	$1, %al
	leaq	.LC11(%rip), %rsi
	call	_Z9getGflopsif
	movl	$2, %edi
	cvtss2sd	%xmm0, %xmm0
	call	__printf_chk@PLT
	movq	8(%rsp), %rdi
	call	cudaFree@PLT
	leaq	.LC12(%rip), %rdi
	call	_Z10checkErrorPKc
	movq	16(%rsp), %rdi
	call	cudaFree@PLT
	leaq	.LC13(%rip), %rdi
	call	_Z10checkErrorPKc
	movq	24(%rsp), %rdi
	call	cudaFree@PLT
	leaq	.LC14(%rip), %rdi
	call	_Z10checkErrorPKc
	movq	72(%rsp), %rax
	subq	%fs:40, %rax
	je	.L15
	call	__stack_chk_fail@PLT
.L15:
	addq	$80, %rsp
	.cfi_def_cfa_offset 48
	popq	%rbx
	.cfi_def_cfa_offset 40
	popq	%rbp
	.cfi_def_cfa_offset 32
	popq	%r12
	.cfi_def_cfa_offset 24
	popq	%r13
	.cfi_def_cfa_offset 16
	popq	%r14
	.cfi_def_cfa_offset 8
	ret
	.cfi_endproc
.LFE2027:
	.size	_Z17matrixMulOnDevicePdS_S_i, .-_Z17matrixMulOnDevicePdS_S_i
	.section	.rodata.str1.1
.LC17:
	.string	"\n\n     Matrix-Multiplication \n"
.LC18:
	.string	"     ==========================================\n"
.LC19:
	.string	"\n     Simple DGEMM implemantation on GPU"
.LC20:
	.string	"\n     Device name = %s, with compute capability %d.%d \n"
.LC21:
	.string	"\n     Matrix size %d x %d"
.LC22:
	.string	"\nmaxAbsError: %4.4f, sumAbsError: %4.4f"
.LC23:
	.string	"\n\nProgram terminated SUCCESSFULLY.\n\n"
	.section	.text.startup,"ax",@progbits
	.globl	main
	.type	main, @function
main:
.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
	movl	$1024, %ebx
	subq	$1040, %rsp
	.cfi_def_cfa_offset 1072
	movq	%fs:40, %rax
	movq	%rax, 1032(%rsp)
	xorl	%eax, %eax
	decl	%edi
	jle	.L20
	movq	8(%rsi), %rdi
	call	atoi@PLT
	movl	%eax, %ebx
.L20:
	leaq	.LC17(%rip), %rsi
	movl	$2, %edi
	xorl	%eax, %eax
	movq	%rsp, %rbp
	call	__printf_chk@PLT
	leaq	.LC18(%rip), %rsi
	movl	$2, %edi
	xorl	%eax, %eax
	call	__printf_chk@PLT
	leaq	.LC19(%rip), %rsi
	movl	$2, %edi
	xorl	%eax, %eax
	call	__printf_chk@PLT
	xorl	%edi, %edi
	call	cudaSetDevice@PLT
	xorl	%esi, %esi
	movq	%rbp, %rdi
	call	cudaGetDeviceProperties_v2@PLT
	movq	%rbp, %rdx
	movl	$2, %edi
	xorl	%eax, %eax
	movl	364(%rsp), %r8d
	movl	360(%rsp), %ecx
	leaq	.LC20(%rip), %rsi
	call	__printf_chk@PLT
	movl	%ebx, %edx
	leaq	.LC21(%rip), %rsi
	movl	%ebx, %ecx
	movl	$2, %edi
	xorl	%eax, %eax
	call	__printf_chk@PLT
	movslq	%ebx, %r8
	xorl	%edi, %edi
	xorl	%esi, %esi
	salq	$3, %r8
	xorl	%edx, %edx
.L21:
	cmpl	%edx, %ebx
	jle	.L31
	movq	%rdi, %rcx
	xorl	%eax, %eax
.L23:
	leal	(%rax,%rsi), %r9d
	incl	%eax
	addq	$8, %rcx
	cvtsi2sdl	%r9d, %xmm0
	movsd	%xmm0, -8(%rcx)
	cmpl	%eax, %ebx
	jne	.L23
	incl	%edx
	addl	%ebx, %esi
	addq	%r8, %rdi
	jmp	.L21
.L31:
	movl	%ebx, %ecx
	xorl	%ebp, %ebp
	xorl	%ebx, %ebx
	xorl	%r12d, %r12d
	movq	%rbx, %rdx
	movq	%rbp, %rsi
	movq	%r12, %rdi
	call	_Z17matrixMulOnDevicePdS_S_i
	movq	%r12, %rdi
	call	free@PLT
	movq	%rbp, %rdi
	call	free@PLT
	movq	%rbx, %rdi
	call	free@PLT
	xorps	%xmm1, %xmm1
	movl	$2, %edi
	movb	$2, %al
	leaq	.LC22(%rip), %rsi
	movaps	%xmm1, %xmm0
	call	__printf_chk@PLT
	xorl	%eax, %eax
	movl	$2, %edi
	leaq	.LC23(%rip), %rsi
	call	__printf_chk@PLT
	movq	1032(%rsp), %rax
	subq	%fs:40, %rax
	je	.L24
	call	__stack_chk_fail@PLT
.L24:
	addq	$1040, %rsp
	.cfi_def_cfa_offset 32
	xorl	%eax, %eax
	popq	%rbx
	.cfi_def_cfa_offset 24
	popq	%rbp
	.cfi_def_cfa_offset 16
	popq	%r12
	.cfi_def_cfa_offset 8
	ret
	.cfi_endproc
.LFE2028:
	.size	main, .-main
	.section	.rodata.str1.1
.LC24:
	.string	"_Z16dgemm_gpu_sharedPdS_S_i"
	.section	.text.startup
	.type	_ZL24__sti____cudaRegisterAllv, @function
_ZL24__sti____cudaRegisterAllv:
.LFB2058:
	.cfi_startproc
	endbr64
	pushq	%rax
	.cfi_def_cfa_offset 16
	leaq	_ZL15__fatDeviceText(%rip), %rdi
	call	__cudaRegisterFatBinary@PLT
	pushq	$0
	.cfi_def_cfa_offset 24
	xorl	%r9d, %r9d
	orl	$-1, %r8d
	pushq	$0
	.cfi_def_cfa_offset 32
	leaq	.LC24(%rip), %rdx
	movq	%rax, %rdi
	leaq	_Z16dgemm_gpu_sharedPdS_S_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
.LFE2058:
	.size	_ZL24__sti____cudaRegisterAllv, .-_ZL24__sti____cudaRegisterAllv
	.section	.init_array,"aw"
	.align 8
	.quad	_ZL24__sti____cudaRegisterAllv
	.section	.nvFatBinSegment,"aw"
	.align 8
	.type	_ZL15__fatDeviceText, @object
	.size	_ZL15__fatDeviceText, 24
_ZL15__fatDeviceText:
	.long	1180844977
	.long	1
	.quad	fatbinData
	.quad	0
	.local	_ZL20__cudaFatCubinHandle
	.comm	_ZL20__cudaFatCubinHandle,8,8
	.section	.rodata.cst8,"aM",@progbits,8
	.align 8
.LC0:
	.long	-1598689907
	.long	1052821239
	.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:

/*
 * dgemm_gpu_shared.cu
 *
 * compile with: make dgemm_gpu_shared
 *    -> nvcc -O3 -arch=sm_20 -o dgemm_gpu_shared dgemm_gpu_shared.cu -lcudart
 *
 * Matrices are stored as array in row-major order: 
 * A[row][col] = A[row * N + col]
 *
 * Use shared memory to speed up the matrix multiplication. We can reuse
 * the memory if we load a block of the matrix and have a thread block 
 * calculate a sub matrix.
 */


#include <stdio.h>
#include <assert.h>
#include <hip/hip_runtime.h>

// Thread block size: BLOCK_SIZE * BLOCK_SIZE
#define BLOCK_SIZE 16

// Declaration of helper functions (see bottom of file for details)
void checkError (const char* action);
float getGflops (int, float);

/*
 *  Matrix multiplication kernel called by matrixMulOnDevice() 
 */
__global__ void dgemm_gpu_shared(double* a, double* b, double* c, int n){
    
    // TODO: Allocate shared memory for the two blocks aSub and bSub.
    //       Use two-dimensional matrices of size BLOCK_SIZE * BLOCK_SIZE 
    __shared__ double aSub[BLOCK_SIZE][BLOCK_SIZE];
    __shared__ double bSub[BLOCK_SIZE][BLOCK_SIZE];
    
    // TODO: Calculate global thread index 
    int idxX = blockIdx.x * BLOCK_SIZE + threadIdx.x;
    int idxY = blockIdx.y * BLOCK_SIZE + threadIdx.y;

    // For the matrix multiplication, we need to multiply all the elements of 
    // the idxYth row of a with all the elements of the idXth column of b and 
    // sum up the results.
    double sum = 0;

    // TODO: Calculate global offset of upper left corner of thread block.
    int blockaY = blockIdx.y * BLOCK_SIZE;
    int blockbX = blockIdx.x * BLOCK_SIZE;

    for (int block = 0; block < gridDim.x; ++block){
      // Get the two sub matrices
      int blockaX = block * (BLOCK_SIZE);
      int blockbY = block * (BLOCK_SIZE);
      if (((blockaY + threadIdx.y) < n) && (blockaX + threadIdx.x) < n) {
        // TODO: Copy block into shared memory
        aSub[threadIdx.y][threadIdx.x] = a[(blockaY + threadIdx.y) * n + blockaX + threadIdx.x];
      } else {
        aSub[threadIdx.y][threadIdx.x] = 0;
      }

      if (((blockbY + threadIdx.y) < n) && (blockbX + threadIdx.x) < n) {
        bSub[threadIdx.y][threadIdx.x] = b[(blockbY + threadIdx.y) * n + blockbX + threadIdx.x];
      } else {
        bSub[threadIdx.y][threadIdx.x] = 0;
      }
	
	    // TODO: Synchronize threads to make sure all threads are done copying
      __syncthreads();
    
      if ((idxX < n) && (idxY < n))
      {
        for (int i=0; i < blockDim.x; ++i){ //assumes that we use square blocks
          sum += aSub[threadIdx.y][i] * bSub[i][threadIdx.x];
        }
      }
	    // TODO: Synchronize threads to make sure all threads are done with the data
      __syncthreads();
    }

    if ((idxX < n) && (idxY < n)){    
      c[idxY * n + idxX] = sum;
    }
}



/*
 *  Matrix multiplication host function called by main() 
 */

void matrixMulOnDevice(double* a, double* b, double* c, int n)
{
    int size = n * n * sizeof(double);
    int xGrid, yGrid;
    double *d_a, *d_b, *d_c;
    float time;

    // Define events for timing
    hipEvent_t start, stop;
  
    hipEventCreate(&start);
    hipEventCreate(&stop);
    
    // TODO
    // Allocate memory for d_a, d_b and d_c on device
    hipMalloc((void **)&d_a, size );
    checkError("cudaMalloc: d_a");
    hipMalloc((void **)&d_b, size );
    checkError("cudaMalloc: d_b");  
    hipMalloc((void **)&d_c, size );
    checkError("cudaMalloc: d_c");
    
    
    // First calculate grid size by dividing n by BLOCK_SIZE = 16
    xGrid = (n % BLOCK_SIZE == 0) ? (n / BLOCK_SIZE) : (n / BLOCK_SIZE + 1);
    yGrid = (n % BLOCK_SIZE == 0) ? (n / BLOCK_SIZE) : (n / BLOCK_SIZE + 1);
    dim3 gridDim(xGrid, yGrid);
    dim3 blockDim(BLOCK_SIZE, BLOCK_SIZE);

    printf("Grid: %d, %d; block:%d, %d\n", xGrid , yGrid , BLOCK_SIZE, BLOCK_SIZE);
    
    // Invoke kernel and measure execution time 
    hipEventRecord( start, 0 );
    
    // TODO
    // Copy data for a and b from host to device
    hipMemcpy(d_a, a, size, hipMemcpyHostToDevice);
    checkError("copying data of A from host to device");
    hipMemcpy(d_b, b, size, hipMemcpyHostToDevice);
    checkError("copying data of B from host to device");
  
    // TODO: Call the kernel 
    dgemm_gpu_shared<<<gridDim, blockDim>>>( d_a, d_b, d_c, n);
    
    // TODO
    // Read restults from device memory to C 
    hipMemcpy(c, d_c, size, hipMemcpyDeviceToHost);
    checkError("hipMemcpyDeviceToHost");
    
    // Get elapsed time for kernel execution
    hipEventRecord( stop, 0 );
    hipEventSynchronize( stop );
    checkError("executing Kernel");
    hipEventElapsedTime( &time, start, stop );
    hipEventDestroy( start );
    hipEventDestroy( stop );

    printf ("\nKernel Execution Time: %f ms (dim C: %d * %d)", time, n, n);
    printf ("\nThis corresponds to: %4.4f GFLOPS", getGflops(n, time));
  
    
    // Free device memory 
    hipFree(d_a);
    checkError("Freeing d_a");
    hipFree(d_b);
    checkError("Freeing d_b");
    hipFree(d_c);
    checkError("Freeing d_c");

}

int main(int argc, char** argv)
{
  int n = 1024;
  double *a, *b, *c;
  int row, col;
  double absError, maxAbsError = 0.0, sumAbsError = 0.0;
 
  if (argc > 1) {
    n = atoi(argv[1]);
  }

    
  // show banner
  printf ("\n\n     Matrix-Multiplication \n");
  printf (    "     ==========================================\n");
  printf (  "\n     Simple DGEMM implemantation on GPU");  

  // echo device data
  int idevice = 0;
  hipSetDevice(idevice);
  hipDeviceProp_t dprops;
  hipGetDeviceProperties( &dprops, idevice );
  printf ("\n     Device name = %s, with compute capability %d.%d \n", 
	  dprops.name, dprops.major, dprops.minor);
  printf (  "\n     Matrix size %d x %d", n, n);
  
    
  // Allocate memory for matrices on host
  assert ( a = (double*) malloc (n * n * sizeof(double)) );
  assert ( b = (double*) malloc (n * n * sizeof(double)) );
  assert ( c = (double*) malloc (n * n * sizeof(double)) );
    
  // Init matrices A and B: A = E so result will be B
#pragma omp parallel for private(row, col)
  for (row = 0; row < n; ++row){
    for (col = 0; col < n; col++){
	    a[row * n + col] = (row == col) ? 1.0 : 0.0;
	    b[row * n + col] = row * n + col;
     }
  }

    // do matrix multiplication on device
    matrixMulOnDevice(a, b, c, n);
     
    // Compare results
  for ( row = 0; row < n; ++row){
    for ( col = 0; col < n; ++col) {
	
	    absError = fabs ( c[row * n + col] - b[row * n + col]);
	    sumAbsError += absError;
	
	    if (absError > maxAbsError)
	      maxAbsError = absError;
      }
    }
    // Free memory on host
    free (a);
    free (b);
    free (c);
  
    printf ("\nmaxAbsError: %4.4f, sumAbsError: %4.4f", maxAbsError, sumAbsError);
    if (maxAbsError < 2.0e-5) {
      printf ("\n\nProgram terminated SUCCESSFULLY.\n\n");
    } else {
      printf ("\n\nProgram terminated UNSUCCESSFULLY.\n\n");
    }
    return 0;
}

/*
 *  Some helper functions
 */

// get compute performance
float getGflops (int n, float time) {

	float gf = (2.0e-6 * n * n* n / time);

	return gf;
}

// Simple error checking function for CUDA actions

void checkError (const char* action) {
  
  hipError_t error;
  error = hipGetLastError(); 

  if (error != hipSuccess) {
    printf ("\nError while '%s': %s\nprogram terminated ...\n\n", action, hipGetErrorString(error));
    exit (EXIT_FAILURE);
  }
}

	.text
	.file	"dgemm_gpu_shared.hip"
	.globl	_Z31__device_stub__dgemm_gpu_sharedPdS_S_i # -- Begin function _Z31__device_stub__dgemm_gpu_sharedPdS_S_i
	.type	_Z31__device_stub__dgemm_gpu_sharedPdS_S_i,@function
_Z31__device_stub__dgemm_gpu_sharedPdS_S_i: # @_Z31__device_stub__dgemm_gpu_sharedPdS_S_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), %rdi
	movq	%rsi, (%rdi)
	leaq	24(%rsp), %rsi
	movq	%rdx, (%rsi)
	leaq	4(%rsp), %rdx
	movl	%ecx, (%rdx)
	leaq	80(%rsp), %rbx
	movq	%rax, (%rbx)
	movq	%rdi, 8(%rbx)
	movq	%rsi, 16(%rbx)
	movq	%rdx, 24(%rbx)
	leaq	64(%rsp), %r14
	leaq	48(%rsp), %r15
	leaq	16(%rsp), %r12
	leaq	8(%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	$_Z16dgemm_gpu_sharedPdS_S_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_end0:
	.size	_Z31__device_stub__dgemm_gpu_sharedPdS_S_i, .Lfunc_end0-_Z31__device_stub__dgemm_gpu_sharedPdS_S_i
	.cfi_endproc
                                        # -- End function
	.section	.rodata.cst8,"aM",@progbits,8
	.p2align	3, 0x0                          # -- Begin function _Z17matrixMulOnDevicePdS_S_i
.LCPI1_0:
	.quad	0x3ec0c6f7a0b5ed8d              # double 1.9999999999999999E-6
	.text
	.globl	_Z17matrixMulOnDevicePdS_S_i
	.type	_Z17matrixMulOnDevicePdS_S_i,@function
_Z17matrixMulOnDevicePdS_S_i:           # @_Z17matrixMulOnDevicePdS_S_i
	.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	$56, %rsp
	.cfi_def_cfa_offset 112
	.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, %ebx
	movq	%rdx, %r14
	movq	%rsi, %r12
	movq	%rdi, %r13
	movl	%ecx, %ebp
	imull	%ecx, %ebp
	shll	$3, %ebp
	leaq	16(%rsp), %rdi
	callq	hipEventCreate
	leaq	8(%rsp), %rdi
	callq	hipEventCreate
	movslq	%ebp, %r15
	leaq	40(%rsp), %rdi
	movq	%r15, %rsi
	callq	hipMalloc
	movl	$.L.str, %edi
	callq	_Z10checkErrorPKc
	leaq	32(%rsp), %rdi
	movq	%r15, %rsi
	callq	hipMalloc
	movl	$.L.str.1, %edi
	callq	_Z10checkErrorPKc
	leaq	24(%rsp), %rdi
	movq	%r15, %rsi
	callq	hipMalloc
	movl	$.L.str.2, %edi
	callq	_Z10checkErrorPKc
	testb	$15, %bl
	je	.LBB1_1
# %bb.2:
	leal	15(%rbx), %edx
	testl	%ebx, %ebx
	cmovnsl	%ebx, %edx
	sarl	$4, %edx
	incl	%edx
	jmp	.LBB1_3
.LBB1_1:
	movl	%ebx, %edx
	sarl	$4, %edx
.LBB1_3:
	movl	%edx, %eax
	movq	%rax, %rbp
	shlq	$32, %rbp
	orq	%rax, %rbp
	movl	$.L.str.3, %edi
	movl	%edx, %esi
	movl	$16, %ecx
	movl	$16, %r8d
	xorl	%eax, %eax
	callq	printf
	movq	16(%rsp), %rdi
	xorl	%esi, %esi
	callq	hipEventRecord
	movq	40(%rsp), %rdi
	movq	%r13, %rsi
	movq	%r15, %rdx
	movl	$1, %ecx
	callq	hipMemcpy
	movl	$.L.str.4, %edi
	callq	_Z10checkErrorPKc
	movq	32(%rsp), %rdi
	movq	%r12, %rsi
	movq	%r15, %rdx
	movl	$1, %ecx
	callq	hipMemcpy
	movl	$.L.str.5, %edi
	callq	_Z10checkErrorPKc
	movabsq	$68719476752, %rdx              # imm = 0x1000000010
	movq	%rbp, %rdi
	movl	$1, %esi
	movl	$1, %ecx
	xorl	%r8d, %r8d
	xorl	%r9d, %r9d
	callq	__hipPushCallConfiguration
	testl	%eax, %eax
	jne	.LBB1_5
# %bb.4:
	movq	40(%rsp), %rdi
	movq	32(%rsp), %rsi
	movq	24(%rsp), %rdx
	movl	%ebx, %ecx
	callq	_Z31__device_stub__dgemm_gpu_sharedPdS_S_i
.LBB1_5:
	movq	24(%rsp), %rsi
	movq	%r14, %rdi
	movq	%r15, %rdx
	movl	$2, %ecx
	callq	hipMemcpy
	movl	$.L.str.6, %edi
	callq	_Z10checkErrorPKc
	movq	8(%rsp), %rdi
	xorl	%esi, %esi
	callq	hipEventRecord
	movq	8(%rsp), %rdi
	callq	hipEventSynchronize
	movl	$.L.str.7, %edi
	callq	_Z10checkErrorPKc
	movq	16(%rsp), %rsi
	movq	8(%rsp), %rdx
	leaq	52(%rsp), %r14
	movq	%r14, %rdi
	callq	hipEventElapsedTime
	movq	16(%rsp), %rdi
	callq	hipEventDestroy
	movq	8(%rsp), %rdi
	callq	hipEventDestroy
	cvtss2sd	(%r14), %xmm0
	movl	$.L.str.8, %edi
	movl	%ebx, %esi
	movl	%ebx, %edx
	movb	$1, %al
	callq	printf
	xorps	%xmm0, %xmm0
	cvtsi2sd	%ebx, %xmm0
	movsd	.LCPI1_0(%rip), %xmm1           # xmm1 = mem[0],zero
	mulsd	%xmm0, %xmm1
	mulsd	%xmm0, %xmm1
	mulsd	%xmm0, %xmm1
	xorps	%xmm0, %xmm0
	cvtss2sd	(%r14), %xmm0
	divsd	%xmm0, %xmm1
	xorps	%xmm0, %xmm0
	cvtsd2ss	%xmm1, %xmm0
	cvtss2sd	%xmm0, %xmm0
	movl	$.L.str.9, %edi
	movb	$1, %al
	callq	printf
	movq	40(%rsp), %rdi
	callq	hipFree
	movl	$.L.str.10, %edi
	callq	_Z10checkErrorPKc
	movq	32(%rsp), %rdi
	callq	hipFree
	movl	$.L.str.11, %edi
	callq	_Z10checkErrorPKc
	movq	24(%rsp), %rdi
	callq	hipFree
	movl	$.L.str.12, %edi
	callq	_Z10checkErrorPKc
	addq	$56, %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_end1:
	.size	_Z17matrixMulOnDevicePdS_S_i, .Lfunc_end1-_Z17matrixMulOnDevicePdS_S_i
	.cfi_endproc
                                        # -- End function
	.globl	_Z10checkErrorPKc               # -- Begin function _Z10checkErrorPKc
	.type	_Z10checkErrorPKc,@function
_Z10checkErrorPKc:                      # @_Z10checkErrorPKc
	.cfi_startproc
# %bb.0:
	pushq	%rbx
	.cfi_def_cfa_offset 16
	.cfi_offset %rbx, -16
	movq	%rdi, %rbx
	callq	hipGetLastError
	testl	%eax, %eax
	jne	.LBB2_2
# %bb.1:
	popq	%rbx
	.cfi_def_cfa_offset 8
	retq
.LBB2_2:
	.cfi_def_cfa_offset 16
	movl	%eax, %edi
	callq	hipGetErrorString
	movl	$.L.str.21, %edi
	movq	%rbx, %rsi
	movq	%rax, %rdx
	xorl	%eax, %eax
	callq	printf
	movl	$1, %edi
	callq	exit
.Lfunc_end2:
	.size	_Z10checkErrorPKc, .Lfunc_end2-_Z10checkErrorPKc
	.cfi_endproc
                                        # -- End function
	.section	.rodata.cst8,"aM",@progbits,8
	.p2align	3, 0x0                          # -- Begin function _Z9getGflopsif
.LCPI3_0:
	.quad	0x3ec0c6f7a0b5ed8d              # double 1.9999999999999999E-6
	.text
	.globl	_Z9getGflopsif
	.type	_Z9getGflopsif,@function
_Z9getGflopsif:                         # @_Z9getGflopsif
	.cfi_startproc
# %bb.0:
	cvtsi2sd	%edi, %xmm1
	movsd	.LCPI3_0(%rip), %xmm2           # xmm2 = mem[0],zero
	mulsd	%xmm1, %xmm2
	mulsd	%xmm1, %xmm2
	mulsd	%xmm1, %xmm2
	cvtss2sd	%xmm0, %xmm0
	divsd	%xmm0, %xmm2
	xorps	%xmm0, %xmm0
	cvtsd2ss	%xmm2, %xmm0
	retq
.Lfunc_end3:
	.size	_Z9getGflopsif, .Lfunc_end3-_Z9getGflopsif
	.cfi_endproc
                                        # -- End function
	.globl	main                            # -- Begin function main
	.type	main,@function
main:                                   # @main
	.cfi_startproc
# %bb.0:
	pushq	%r14
	.cfi_def_cfa_offset 16
	pushq	%rbx
	.cfi_def_cfa_offset 24
	subq	$1480, %rsp                     # imm = 0x5C8
	.cfi_def_cfa_offset 1504
	.cfi_offset %rbx, -24
	.cfi_offset %r14, -16
	movl	$1024, %ebx                     # imm = 0x400
	cmpl	$2, %edi
	jl	.LBB4_2
# %bb.1:
	movq	8(%rsi), %rdi
	callq	atoi
	movl	%eax, %ebx
.LBB4_2:                                # %._crit_edge74.thread
	movl	$.Lstr, %edi
	callq	puts@PLT
	movl	$.Lstr.1, %edi
	callq	puts@PLT
	movl	$.L.str.15, %edi
	xorl	%eax, %eax
	callq	printf
	xorl	%edi, %edi
	callq	hipSetDevice
	leaq	8(%rsp), %r14
	movq	%r14, %rdi
	xorl	%esi, %esi
	callq	hipGetDevicePropertiesR0600
	movl	360(%r14), %edx
	movl	364(%r14), %ecx
	movl	$.L.str.16, %edi
	movq	%r14, %rsi
	xorl	%eax, %eax
	callq	printf
	movl	$.L.str.17, %edi
	movl	%ebx, %esi
	movl	%ebx, %edx
	xorl	%eax, %eax
	callq	printf
	movl	%ebx, %ecx
	callq	_Z17matrixMulOnDevicePdS_S_i
	movl	$.L.str.18, %edi
	xorps	%xmm0, %xmm0
	xorps	%xmm1, %xmm1
	movb	$2, %al
	callq	printf
	movl	$.Lstr.3, %edi
	callq	puts@PLT
	xorl	%eax, %eax
	addq	$1480, %rsp                     # imm = 0x5C8
	.cfi_def_cfa_offset 24
	popq	%rbx
	.cfi_def_cfa_offset 16
	popq	%r14
	.cfi_def_cfa_offset 8
	retq
.Lfunc_end4:
	.size	main, .Lfunc_end4-main
	.cfi_endproc
                                        # -- End function
	.p2align	4, 0x90                         # -- Begin function __hip_module_ctor
	.type	__hip_module_ctor,@function
__hip_module_ctor:                      # @__hip_module_ctor
	.cfi_startproc
# %bb.0:
	subq	$40, %rsp
	.cfi_def_cfa_offset 48
	movq	__hip_gpubin_handle(%rip), %rdi
	testq	%rdi, %rdi
	jne	.LBB5_2
# %bb.1:
	movl	$__hip_fatbin_wrapper, %edi
	callq	__hipRegisterFatBinary
	movq	%rax, %rdi
	movq	%rax, __hip_gpubin_handle(%rip)
.LBB5_2:
	xorps	%xmm0, %xmm0
	movups	%xmm0, 16(%rsp)
	movups	%xmm0, (%rsp)
	movl	$_Z16dgemm_gpu_sharedPdS_S_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_end5:
	.size	__hip_module_ctor, .Lfunc_end5-__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	.LBB6_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
.LBB6_2:
	retq
.Lfunc_end6:
	.size	__hip_module_dtor, .Lfunc_end6-__hip_module_dtor
	.cfi_endproc
                                        # -- End function
	.type	_Z16dgemm_gpu_sharedPdS_S_i,@object # @_Z16dgemm_gpu_sharedPdS_S_i
	.section	.rodata,"a",@progbits
	.globl	_Z16dgemm_gpu_sharedPdS_S_i
	.p2align	3, 0x0
_Z16dgemm_gpu_sharedPdS_S_i:
	.quad	_Z31__device_stub__dgemm_gpu_sharedPdS_S_i
	.size	_Z16dgemm_gpu_sharedPdS_S_i, 8

	.type	.L.str,@object                  # @.str
	.section	.rodata.str1.1,"aMS",@progbits,1
.L.str:
	.asciz	"cudaMalloc: d_a"
	.size	.L.str, 16

	.type	.L.str.1,@object                # @.str.1
.L.str.1:
	.asciz	"cudaMalloc: d_b"
	.size	.L.str.1, 16

	.type	.L.str.2,@object                # @.str.2
.L.str.2:
	.asciz	"cudaMalloc: d_c"
	.size	.L.str.2, 16

	.type	.L.str.3,@object                # @.str.3
.L.str.3:
	.asciz	"Grid: %d, %d; block:%d, %d\n"
	.size	.L.str.3, 28

	.type	.L.str.4,@object                # @.str.4
.L.str.4:
	.asciz	"copying data of A from host to device"
	.size	.L.str.4, 38

	.type	.L.str.5,@object                # @.str.5
.L.str.5:
	.asciz	"copying data of B from host to device"
	.size	.L.str.5, 38

	.type	.L.str.6,@object                # @.str.6
.L.str.6:
	.asciz	"hipMemcpyDeviceToHost"
	.size	.L.str.6, 22

	.type	.L.str.7,@object                # @.str.7
.L.str.7:
	.asciz	"executing Kernel"
	.size	.L.str.7, 17

	.type	.L.str.8,@object                # @.str.8
.L.str.8:
	.asciz	"\nKernel Execution Time: %f ms (dim C: %d * %d)"
	.size	.L.str.8, 47

	.type	.L.str.9,@object                # @.str.9
.L.str.9:
	.asciz	"\nThis corresponds to: %4.4f GFLOPS"
	.size	.L.str.9, 35

	.type	.L.str.10,@object               # @.str.10
.L.str.10:
	.asciz	"Freeing d_a"
	.size	.L.str.10, 12

	.type	.L.str.11,@object               # @.str.11
.L.str.11:
	.asciz	"Freeing d_b"
	.size	.L.str.11, 12

	.type	.L.str.12,@object               # @.str.12
.L.str.12:
	.asciz	"Freeing d_c"
	.size	.L.str.12, 12

	.type	.L.str.15,@object               # @.str.15
.L.str.15:
	.asciz	"\n     Simple DGEMM implemantation on GPU"
	.size	.L.str.15, 41

	.type	.L.str.16,@object               # @.str.16
.L.str.16:
	.asciz	"\n     Device name = %s, with compute capability %d.%d \n"
	.size	.L.str.16, 56

	.type	.L.str.17,@object               # @.str.17
.L.str.17:
	.asciz	"\n     Matrix size %d x %d"
	.size	.L.str.17, 26

	.type	.L.str.18,@object               # @.str.18
.L.str.18:
	.asciz	"\nmaxAbsError: %4.4f, sumAbsError: %4.4f"
	.size	.L.str.18, 40

	.type	.L.str.21,@object               # @.str.21
.L.str.21:
	.asciz	"\nError while '%s': %s\nprogram terminated ...\n\n"
	.size	.L.str.21, 47

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

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

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

	.type	.Lstr,@object                   # @str
	.section	.rodata.str1.1,"aMS",@progbits,1
.Lstr:
	.asciz	"\n\n     Matrix-Multiplication "
	.size	.Lstr, 30

	.type	.Lstr.1,@object                 # @str.1
.Lstr.1:
	.asciz	"     =========================================="
	.size	.Lstr.1, 48

	.type	.Lstr.3,@object                 # @str.3
.Lstr.3:
	.asciz	"\n\nProgram terminated SUCCESSFULLY.\n"
	.size	.Lstr.3, 36

	.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 _Z31__device_stub__dgemm_gpu_sharedPdS_S_i
	.addrsig_sym __hip_module_ctor
	.addrsig_sym __hip_module_dtor
	.addrsig_sym _Z16dgemm_gpu_sharedPdS_S_i
	.addrsig_sym __hip_fatbin
	.addrsig_sym __hip_fatbin_wrapper
	.addrsig_sym __hip_cuid_

	.text
	.amdgcn_target "amdgcn-amd-amdhsa--gfx1100"
	.protected	_Z16dgemm_gpu_sharedPdS_S_i ; -- Begin function _Z16dgemm_gpu_sharedPdS_S_i
	.globl	_Z16dgemm_gpu_sharedPdS_S_i
	.p2align	8
	.type	_Z16dgemm_gpu_sharedPdS_S_i,@function
_Z16dgemm_gpu_sharedPdS_S_i:            ; @_Z16dgemm_gpu_sharedPdS_S_i
; %bb.0:
	s_clause 0x3
	s_load_b32 s3, s[0:1], 0x18
	s_load_b32 s12, s[0:1], 0x20
	s_load_b128 s[4:7], s[0:1], 0x0
	s_load_b64 s[8:9], s[0:1], 0x10
	v_and_b32_e32 v13, 0x3ff, v0
	v_bfe_u32 v14, v0, 10, 10
	s_add_u32 s10, s0, 32
	s_addc_u32 s11, s1, 0
	s_mov_b32 s13, 0
	v_lshl_add_u32 v0, s14, 4, v13
	v_lshl_add_u32 v11, s15, 4, v14
	s_delay_alu instid0(VALU_DEP_1) | instskip(SKIP_1) | instid1(VALU_DEP_1)
	v_max_i32_e32 v12, v0, v11
	s_waitcnt lgkmcnt(0)
	v_cmp_gt_i32_e32 vcc_lo, s3, v12
	s_cmp_eq_u32 s12, 0
	s_cbranch_scc1 .LBB0_10
; %bb.1:                                ; %.lr.ph54
	v_lshlrev_b32_e32 v1, 3, v13
	v_mov_b32_e32 v3, 0
	v_dual_mov_b32 v6, 0 :: v_dual_lshlrev_b32 v15, 7, v14
	v_mov_b32_e32 v4, 0
	s_delay_alu instid0(VALU_DEP_4)
	v_add_nc_u32_e32 v16, 0x800, v1
	v_mul_lo_u32 v17, v11, s3
	v_cmp_gt_u32_e64 s0, s3, v11
	v_cmp_gt_u32_e64 s1, s3, v0
	v_add_nc_u32_e32 v18, v15, v1
	v_add_nc_u32_e32 v19, v16, v15
	v_dual_mov_b32 v1, v3 :: v_dual_mov_b32 v2, v4
.LBB0_2:                                ; =>This Loop Header: Depth=1
                                        ;     Child Loop BB0_8 Depth 2
	s_lshl_b32 s14, s13, 4
	s_delay_alu instid0(SALU_CYCLE_1) | instskip(SKIP_1) | instid1(VALU_DEP_2)
	v_dual_mov_b32 v8, v4 :: v_dual_add_nc_u32 v5, s14, v13
	v_mov_b32_e32 v7, v3
	v_cmp_gt_u32_e64 s2, s3, v5
	s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(SALU_CYCLE_1)
	s_and_b32 s2, s0, s2
	s_and_saveexec_b32 s15, s2
	s_cbranch_execz .LBB0_4
; %bb.3:                                ;   in Loop: Header=BB0_2 Depth=1
	v_add_nc_u32_e32 v5, v5, v17
	s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(VALU_DEP_1)
	v_lshlrev_b64 v[7:8], 3, v[5:6]
	v_add_co_u32 v7, s2, s4, v7
	s_delay_alu instid0(VALU_DEP_1)
	v_add_co_ci_u32_e64 v8, s2, s5, v8, s2
	global_load_b64 v[7:8], v[7:8], off
.LBB0_4:                                ;   in Loop: Header=BB0_2 Depth=1
	s_or_b32 exec_lo, exec_lo, s15
	v_add_nc_u32_e32 v5, s14, v14
	v_mov_b32_e32 v9, 0
	v_mov_b32_e32 v10, 0
	s_waitcnt vmcnt(0)
	ds_store_b64 v18, v[7:8]
	v_cmp_gt_u32_e64 s2, s3, v5
	s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(SALU_CYCLE_1)
	s_and_b32 s2, s1, s2
	s_and_saveexec_b32 s14, s2
	s_cbranch_execz .LBB0_6
; %bb.5:                                ;   in Loop: Header=BB0_2 Depth=1
	v_mad_u64_u32 v[7:8], null, v5, s3, v[0:1]
	v_mov_b32_e32 v8, v6
	s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(VALU_DEP_1)
	v_lshlrev_b64 v[7:8], 3, v[7:8]
	v_add_co_u32 v7, s2, s6, v7
	s_delay_alu instid0(VALU_DEP_1)
	v_add_co_ci_u32_e64 v8, s2, s7, v8, s2
	global_load_b64 v[9:10], v[7:8], off
.LBB0_6:                                ;   in Loop: Header=BB0_2 Depth=1
	s_or_b32 exec_lo, exec_lo, s14
	s_waitcnt vmcnt(0)
	ds_store_b64 v19, v[9:10]
	s_waitcnt lgkmcnt(0)
	s_barrier
	buffer_gl0_inv
	s_and_saveexec_b32 s2, vcc_lo
	s_cbranch_execz .LBB0_9
; %bb.7:                                ; %.preheader
                                        ;   in Loop: Header=BB0_2 Depth=1
	s_load_b32 s14, s[10:11], 0xc
	v_mov_b32_e32 v5, v16
	v_mov_b32_e32 v7, v15
	s_waitcnt lgkmcnt(0)
	s_and_b32 s14, s14, 0xffff
	s_delay_alu instid0(SALU_CYCLE_1)
	s_cmp_eq_u32 s14, 0
	s_cbranch_scc1 .LBB0_9
.LBB0_8:                                ; %.lr.ph
                                        ;   Parent Loop BB0_2 Depth=1
                                        ; =>  This Inner Loop Header: Depth=2
	ds_load_b64 v[8:9], v7
	ds_load_b64 v[20:21], v5
	v_add_nc_u32_e32 v7, 8, v7
	v_add_nc_u32_e32 v5, 0x80, v5
	s_add_i32 s14, s14, -1
	s_delay_alu instid0(SALU_CYCLE_1)
	s_cmp_lg_u32 s14, 0
	s_waitcnt lgkmcnt(0)
	v_fma_f64 v[1:2], v[8:9], v[20:21], v[1:2]
	s_cbranch_scc1 .LBB0_8
.LBB0_9:                                ; %.loopexit
                                        ;   in Loop: Header=BB0_2 Depth=1
	s_or_b32 exec_lo, exec_lo, s2
	s_add_i32 s13, s13, 1
	s_delay_alu instid0(SALU_CYCLE_1)
	s_cmp_eq_u32 s13, s12
	s_barrier
	buffer_gl0_inv
	s_cbranch_scc0 .LBB0_2
	s_branch .LBB0_11
.LBB0_10:
	v_mov_b32_e32 v1, 0
	v_mov_b32_e32 v2, 0
.LBB0_11:                               ; %Flow76
	s_mov_b32 s0, exec_lo
	v_cmpx_gt_i32_e64 s3, v12
	s_cbranch_execz .LBB0_13
; %bb.12:
	v_mad_u64_u32 v[3:4], null, v11, s3, v[0:1]
	s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(VALU_DEP_1)
	v_ashrrev_i32_e32 v4, 31, v3
	v_lshlrev_b64 v[3:4], 3, v[3:4]
	s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(VALU_DEP_2)
	v_add_co_u32 v3, vcc_lo, s8, v3
	v_add_co_ci_u32_e32 v4, vcc_lo, s9, v4, vcc_lo
	global_store_b64 v[3:4], v[1:2], off
.LBB0_13:
	s_nop 0
	s_sendmsg sendmsg(MSG_DEALLOC_VGPRS)
	s_endpgm
	.section	.rodata,"a",@progbits
	.p2align	6, 0x0
	.amdhsa_kernel _Z16dgemm_gpu_sharedPdS_S_i
		.amdhsa_group_segment_fixed_size 4096
		.amdhsa_private_segment_fixed_size 0
		.amdhsa_kernarg_size 288
		.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 22
		.amdhsa_next_free_sgpr 16
		.amdhsa_float_round_mode_32 0
		.amdhsa_float_round_mode_16_64 0
		.amdhsa_float_denorm_mode_32 3
		.amdhsa_float_denorm_mode_16_64 3
		.amdhsa_dx10_clamp 1
		.amdhsa_ieee_mode 1
		.amdhsa_fp16_overflow 0
		.amdhsa_workgroup_processor_mode 1
		.amdhsa_memory_ordered 1
		.amdhsa_forward_progress 0
		.amdhsa_shared_vgpr_count 0
		.amdhsa_exception_fp_ieee_invalid_op 0
		.amdhsa_exception_fp_denorm_src 0
		.amdhsa_exception_fp_ieee_div_zero 0
		.amdhsa_exception_fp_ieee_overflow 0
		.amdhsa_exception_fp_ieee_underflow 0
		.amdhsa_exception_fp_ieee_inexact 0
		.amdhsa_exception_int_div_zero 0
	.end_amdhsa_kernel
	.text
.Lfunc_end0:
	.size	_Z16dgemm_gpu_sharedPdS_S_i, .Lfunc_end0-_Z16dgemm_gpu_sharedPdS_S_i
                                        ; -- End function
	.section	.AMDGPU.csdata,"",@progbits
; Kernel info:
; codeLenInByte = 624
; NumSgprs: 18
; NumVgprs: 22
; ScratchSize: 0
; MemoryBound: 0
; FloatMode: 240
; IeeeMode: 1
; LDSByteSize: 4096 bytes/workgroup (compile time only)
; SGPRBlocks: 2
; VGPRBlocks: 2
; NumSGPRsForWavesPerEU: 18
; NumVGPRsForWavesPerEU: 22
; 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
      - .offset:         32
        .size:           4
        .value_kind:     hidden_block_count_x
      - .offset:         36
        .size:           4
        .value_kind:     hidden_block_count_y
      - .offset:         40
        .size:           4
        .value_kind:     hidden_block_count_z
      - .offset:         44
        .size:           2
        .value_kind:     hidden_group_size_x
      - .offset:         46
        .size:           2
        .value_kind:     hidden_group_size_y
      - .offset:         48
        .size:           2
        .value_kind:     hidden_group_size_z
      - .offset:         50
        .size:           2
        .value_kind:     hidden_remainder_x
      - .offset:         52
        .size:           2
        .value_kind:     hidden_remainder_y
      - .offset:         54
        .size:           2
        .value_kind:     hidden_remainder_z
      - .offset:         72
        .size:           8
        .value_kind:     hidden_global_offset_x
      - .offset:         80
        .size:           8
        .value_kind:     hidden_global_offset_y
      - .offset:         88
        .size:           8
        .value_kind:     hidden_global_offset_z
      - .offset:         96
        .size:           2
        .value_kind:     hidden_grid_dims
    .group_segment_fixed_size: 4096
    .kernarg_segment_align: 8
    .kernarg_segment_size: 288
    .language:       OpenCL C
    .language_version:
      - 2
      - 0
    .max_flat_workgroup_size: 1024
    .name:           _Z16dgemm_gpu_sharedPdS_S_i
    .private_segment_fixed_size: 0
    .sgpr_count:     18
    .sgpr_spill_count: 0
    .symbol:         _Z16dgemm_gpu_sharedPdS_S_i.kd
    .uniform_work_group_size: 1
    .uses_dynamic_stack: false
    .vgpr_count:     22
    .vgpr_spill_count: 0
    .wavefront_size: 32
    .workgroup_processor_mode: 1
amdhsa.target:   amdgcn-amd-amdhsa--gfx1100
amdhsa.version:
  - 1
  - 2
...

	.end_amdgpu_metadata
