Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MIPS Assembly Alignment Align n

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.

like image 827
Konstantinos T. Pantelis Avatar asked Dec 28 '16 09:12

Konstantinos T. Pantelis


1 Answers

Taken directly from MARS helping tooltips:

Align next data item on specified byte boundary (0=byte, 1=halfword, 2=word, 3=double)

Consider this code

  la $t0, array

.data
  .space 3

array: 
  .space 12

This is assembled into

lui $at, 0x1001
ori $t0, $at, 0x0003          #$t0 = 0x10010003

showing that array is at address 0x10010003.


Using an .align directive:

  la $t0, array

.data
  .space 3

array:
  .align 3 
  .space 12

Gives:

lui $at, 0x1001
ori $t0, $at, 0x0008          #$t0 = 0x10010008

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.

  .align 2            |    array: 
array:                |      .align 2
  .space 12           |      .space 12 
like image 88
Margaret Bloom Avatar answered Sep 19 '22 06:09

Margaret Bloom