MIPS Assembly Alignment Align n

后端 未结 1 940
梦谈多话
梦谈多话 2020-12-07 02:34

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
             


        
相关标签:
1条回答
  • 2020-12-07 03:23

    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 
    
    0 讨论(0)
提交回复
热议问题