What does the directive .align n
do in an array?
To be more specific let's say that I have the following part of code:
array: .align 2
.space 800
What's its importance and why not just skip it and use
.space 800
This is a school's assignment theory question.
Taken directly from MARS helping tooltips:
Consider this code
This is assembled into
showing that
array
is at address 0x10010003.Using an
.align
directive:Gives:
Now the address is 0x10010008.
The difference is that the latter address is aligned on double boundary.
A double is 8 bytes long and the address is a multiple of 8 bytes.
Alignment gives better performance because the CPU reads memory in chunks of words and this blocks starts at address multiple of four (0x0, 0x4, 0x8, ...).
If a word at 0x3 is requested, the CPU need to read the one at 0x0 and the one at 0x4 and merge the results.
Unaligned accesses are explicitly not supported in some architecture. If I recall correctly, MIPS is not such strict when it comes to data (but it is for code).
Pitfall
Beware that
.align n
align the next data item on 2n boundary, or equivalently (left as an exercise to the reader) it moves the data item to an address whose lower n bits are zero.MARS appears, contrary to most assembler, to "attach" labels to the next space allocating directive (e.g.
.byte
,.space
, etc.) and not the current location counter.Thus the label can be moved between the
.align
and.space
directives.