previous | start | next

IA32 Assembler for: accessing array elements (2)

int swapElements(int a[], int i, int j)
{
  int tmp;
  tmp = a[i];
  a[i] = a[j];
  a[j] = tmp;
}

   

With optimization level 2, the compiler will try to keep values in registers when possible.

Here is a possible outline. (The return register %eax will be denoted by r1.)

 r4 = tmp
 r3 = address of array a, and then as a second temporary
 r2 = i                      
 r1 = j                      
 
 R[r2] = address of a[i]             
 R[r1] = address of a[j]             
 R[r4] = M[r2]  (i.e., R[r4] = a[i])  
 R[r3] = M[r1]  (i.e., R[r3] = a[j]) 
 M[r2] = R[r3]  (i.e., a[i] = R[r3]) 
 M[r1] = R[r4]  (i.e., a[j] = R[r4]) 


 return                              
      
   


previous | start | next