3.66 Multiple Dimension Array III

Consider the following source code, where NR and NC are macro expressions declared with #define that compute the dimensions of array A in terms of parameter n. This code computes the sum of the elements of column j of the array.

long sum_col(long n, long A[NR(n)][NC(n)], long j) {
    long i;
    long result = 0;
    for (i = 0; i < NR[n]; i++) {
        result += A[i][j];
    }
    return result;
}

In compiling this program, GCC generates the following assembly code:

; n in %rdi, A in %rsi, j in %rdx
sum_col:
    leaq     1(,%rdi,4), %r8            ; Compute 4n+1 to %r8
    leaq     (%rdi,%rdi,2), %rax        ; Compute 3n to %rax
    movq     %rax, %rdi                ; Move %rax to %rdi
    testq     %rax, %rax                ; test %rax
    jle     .L4
    salq     $3, %r8                    ; Compute 8*(4n+1) to %r8
    leaq     (%rsi,%rdx,8), %rcx        ; Compute A+8*j to %rcx
    movl     $0, %eax
    movl     $0, %edx
.L3:
    addq     (%rcx), %rax            ; Retrive A[0][j] to %rax
    addq     $1, %rdx                ; Add 1 to %rdx
    addq     %r8, %rcx                ; Add 8*(4*n+1) to %rcx, so NC(n)=4*n+1
    cmpq     %rdi, %rdx                ; Compare i:3n, so NR(n)=3*n
    jne     .L3
    rep; ret
.L4:
    movl     $0, %eax
    ret

Use your reverse engineering skills to determine the definitions of NR and NC.

NR(n) = 3*n;
NC(n) = 4*n + 1;

Last updated