Why should code be aligned to even-address boundaries on x86?

后端 未结 3 780
我寻月下人不归
我寻月下人不归 2020-12-08 08:13

I am working through Kip Irvine\'s \"Assembly Language for x86 Processors, sixth edition\" and am really enjoying it.

I have just read about the NOP

3条回答
  •  孤城傲影
    2020-12-08 08:26

    Because the (16 bit) processor can fetch values from memory only at even addresses, due to its particular layout: it is divided in two "banks" of 1 byte each, so half of the data bus is connected to the first bank and the other half to the other bank. Now, suppose these banks are aligned (as in my picture), the processor can fetch values that are on the same "row".

      bank 1   bank 2
    +--------+--------+
    |  8 bit | 8 bit  |
    +--------+--------+
    |        |        |
    +--------+--------+
    | 4      | 5      | <-- the CPU can fetch only values on the same "row"
    +--------+--------+
    | 2      | 3      |
    +--------+--------+
    | 0      | 1      |
    +--------+--------+
     \      / \      /
      |    |   |    |
      |    |   |    |
    
     data bus  (to uP)
    

    Now, since this fetch limitation, if the cpu is forced to fetch values which are located on an odd address (suppose 3), it has to fetch values at 2 and 3, then values at 4 and 5, throw away values 2 and 5 then join 4 and 3 (you are talking about x86, which as a little endian memory layout).
    That's why is better having code (and data!) on even addresses.

    PS: On 32 bit processors, code and data should be aligned on addresses which are divisible by 4 (since there are 4 banks).

    Hope I was clear. :)

提交回复
热议问题