sliver__

2.13 A C Sort Exampleto Put It All Together 본문

CS/컴퓨터 구조

2.13 A C Sort Exampleto Put It All Together

sliver__ 2023. 10. 21. 16:48
728x90

Swap C code를 assembly code로 바꾸기 !

void swap(int v[], int k) 
{
 int temp;
 temp = v[k]; 
 v[k] = v[k+1]; 
 v[k+1] = temp; 
}

 

The Procedure swap

 

3 steps of C to assembly code

 

Register Allocation for swap

 

v : $a0, k : $a1

temp : $t0

 

Code for the Body of the Procedure swap

 

v의 array에 접근하기 전 ! int는 4bytes 이므로 k * 4를 수행해 접근해야한다 !

sll   $t1, $a1,2     # reg $t1 = k * 4
add   $t1, $a0,$t1   # reg $t1 = v + (k * 4) 
                     # reg $t1 has the address of v[k]
                     
lw    $t0, 0($t1)    # reg $t0 (temp) = v[k]
lw    $t2, 4($t1)    # reg $t2 = v[k + 1] 
                     # refers to next element of v

sw    $t2, 0($t1)    # v[k] = reg $t2
sw    $t0, 4($t1)    # v[k+1] = reg $t0 (temp)

 

The Full Swap Procedure

swap: sll   $t1, $a1, 2 
add   $t1, $a0, $t1 
lw $t0, 0($t1) 
lw $t2, 4($t1) 
sw $t2, 0($t1) 
sw $t0, 4($t1)
jr    $ra

 

The Procedure sort

void sort (int v[], int n) 
{
    int i, j;
    for (i = 0; i < n; i += 1) {
        for (j = i – 1; j >= 0 && v[j] > v[j + 1]; j =1) { 
        	swap(v,j);
        } 
    }
}

 

Register Allocation for sort

 

v : $a0, n : $a1

i : $s0, j : $s1

 

The Full Procedure Sort

Sort assembly code
Performance of versus gcc optimization

 

Compare the performance of C vs Java

728x90
Comments