3.72 Variable-Size Stack

★★

Below(a) shows the code for a function that is similar to function vfunct (Figure 3.43(a)). We used vfunct to illustrate the use of a frame pointer in managing variable-size stack frames. The new function aframe allocates space for local array p by calling library function alloca. This function is similar to the more commonly used function malloc, except that it allocates space on the run-time stack. The space is automatically deallocated when the executing procedure returns.

Below(b) shows the part of the assembly code that sets up the frame pointer and allocates space for local variables i and p. It is very similar to the corresponding code for vframe. Let us use the same notation as in Problem 3.49: The stack pointer is set to values s1 at line 4 and s2 at line 7. The start address of array p is set to value p at line 9. Extra space e2 may arise between s2 and p, and extra space e1 may arise between the end of array p and s1.

a:

#include <alloca.h>

long aframe(long n, long idx, long *q) {
    long i;
    long **p = alloca(n * sizeof(long *));
    p[0] = &i;
    for (i = 1; i < n; i++)
        p[i] = q;
    return *p[idx];
}

b:

aframe:
    pushq     %rbp
    movq     %rsp, %rbp
    subq     $16, %rsp             ; Allocate space for i (%rsp = s1)
    leaq     30(,%rdi,8), %rax
    andq     $-16, %rax
    subq     %rax, %rsp             ; Allocate space for array p (%rsp = s2)
    leaq     15(%rsp), %r8
    andq     $-16, %r8             ; Set %r8 to &p[0]

A. Explain, in mathematical terms, the logic in the computation of s2.

s2=s1(30+8×n)&0XFFFFFFF0s_2=s_1-(30+8\times n)\&0XFFFFFFF0

when n is odd:

s2=s1(24+8×n)s_2=s_1-(24+8\times n)

when n is even:

s2=s1(16+8×n)s_2=s_1-(16+8\times n)

B. Explain, in mathematical terms, the logic in the computation of p.

p=(15+s2)&0xFFFFFFF0p=(15+s_2)\& 0xFFFFFFF0

p is the least multiple of 16 that is greater than s2.

C. Find values of n and s1 that lead to minimum and maximum values of e1.

item

e1

n

s1

least

1

even

n%16==1

greatest

24

odd

n%16==0

D. What alignment properties does this code guarantee for the values of s2 and p?

p is aligned by 16

s2 is the least multiple of 16 that preserve 8*n size space

Last updated