C stack, Arrays



m4

macros



C Example 1

int a, b;
char c1;
int c, d;
register int x, y, z;

x = 17; y = -5; for (z = 1; z < x + y; z++) for (a = z; a >= z * y; a -= 10) { d = a + z; c1 = d * b; c = a + y / z; } }


Notes:


Example could be any language compiled to assembly/machine code: C, Fortran, Cobol, Pascal, C++, etc.



Example Characterization



Variable Declarations

int a, b;
char c1;
int c, d;
register int x, y, z;

localvar var(as, 4) var(bs, 4) var(c1s, 1) var(cs, 4) var(ds, 4)

define(xr, l0) ! `xr l0' define(yr, l1) ! `yr l1' define(zr, l2) ! `zr l2'

beginmain



Nested for

loops
for (z = 1; ; z++)
  for (a = z; ; a -= 10)
    ...

ba outertest mov 1, %zr outer: ba innertest st %zr, [%fp + as] ! a = z inner: ... ininc: ld [%fp + as], %o0 sub %o0, 10, %o0 st %o0, [%fp + as] intest: bge inner nop outinc: add %zr, 1, %zr outtest: bl outer nop



Complex tests

for (z = 1; z <= x + y; z++)
  for (a = z; a >= z * y; a -= 10)

innertest: mov %zr, %o0 call mul ld [%fp + as, %o1] cmp %o1, %o0 bge inner nop

outerinc: add %zr, 1, %zr outertest: add %xr, %yr, %o0 cmp %zr, %o0 bl outer nop



1-D arrays

int a;
char c1;
int ary[5];

localvar var(as, 4) var(c1s, 1) var(arys, 4, 4 * 5)

After m4:
        as = -4
        c1s = -5
        arys = -28



1-D array access



More m4

Macros



C Example 2

int nums[100] = {1, 45, -16, 23,
                 38, 45, 17}
int n = 7;        /* elements in nums */
register int i;   /* index */
register int max; /* max found so far */

max = nums[0]; for (i = 1; i < n; i++) { if (nums[i] > max) max = nums[i]; }



Example Characterization



Array Declaration

int nums[100] = {1, 45, -16, 23,
                 38, 45, 17}
int n = 7;        /* elements in nums */
register int i;   /* index */
register int max; /* max found so far */
        localvar
        var(numss, 4, 100 * 4)
        var(ns, 4)
        define(ir, l0)  ! `ir l0'
        define(maxr, l1)! `maxr l1'
        beginmain
define(initialize, `   mov   2, %o0
        st %o0, [%fp+numss+1]
ifelse(3,,,`initialize(
eval(1+4),3,4, 5,6,7,8,9)')')
        initialize(0, 1, 45, -16, 23,
                   38, 45, 17)
        mov 7, %o0
        st %o0, [%fp + ns]
%



Array Access

max = nums[0];
for (i = 1; i < n; i++)
  if (nums[i] > max)
    max = nums[i];

ba fortest mov 1, %ir for: sll %ir, 2, %o0 ! i*4 add %fp, %o0, %o0 ld [%o0+nums], %o0 cmp %o0, %maxr ble keep nop keep: add %ir, 1, %ir fortest:ld [%fp+ns], %o0 cmp %ir, %o0 bl for nop



Optimizing the loop



Notes