Page 98 - Introduction to Microcontrollers Architecture, Programming, and Interfacing of The Motorola 68HC12
P. 98
3,4 Stack Index Addressing, Reentrancy and Recursion 75
LEAS -3,SP allocate 3 bytes
LDAA #5 generate constant 5
STAA 0,SP store in allocated
LEAS -2,SP allocate 2 bytes
LDAA 2,SP read out the byte 5
LEAS -4,SP allocate 4 bytes
LDAA 6,SP read out the byte 5
LEAS 4,SP deallocate 4 bytes
LEAS 2,SP deallocate 2 bytes
LEAS 3,SP deallocate 3 bytes
a. Program Segment
Figure 3.16. A Stack Buffer for Nested Segments
The concept of storing data on the stack leads to nested allocation, access, and
deallocation of local variables. Nested segments are commonly used in C and C++
programs to call procedures; the outer segment holds parameters passed to the procedure,
and the inner segment stores some of the local variables of a procedure. Further, C and
C++ programs nest segments within a procedure to hold temporary variables needed to
evaluate a C statement. This concept is fully explained in terms of a program trace,
which is introduced first. Then we consider a simple trace, and then a nested trace.
One can record a program's instructions in the exact order they are executed to obtain
a trace. Simple program segments without branching statements are the same as their
traces. If a program has a loop that is executed five times, the trace has five copies of the
instruction sequence in the loop.
In a program trace, one can allocate local variables by pushing items on the stack,
and one can deallocate them by pulling them from the stack, as already illustrated in this
section. Once allocated, the data on the stack can be accessed by reading or writing the
contents as discussed above. Moreover, one can allocate several bytes in one instruction,
using the LEAS instruction. For instance, to allocate five bytes, execute LEAS -
5, SP. By moving the stack pointer SP five locations toward lower memory, five bytes
of data can be stored in these bytes that were skipped over. The LEAS instruction can
deallocate several words at a time. To deallocate five bytes, execute the instruction LEAS
5, SP. A stack is said to be balanced in a simple trace, which has no alternative
branches in it; so it is linear, if the number of allocated bytes equals the number of
deallocated bytes, and at no step in the trace, between allocation and deallocation, are
more bytes deallocated than were allocated. If, due to conditional branches, there are
several possible simple traces to take from when space has been allocated to a given