I am taking an introduction to embedded systems class and am having some difficulty grasping the concept of Aligned vs. Unaligned memory.
We are primarily using Assembly level programming.
Okay, so this is what I currently understand: Aligned is used to specify to the instructions that the assembler will use that all of the data is of the same length. Its all word length or halfword length or double wordlength.
Unaligned means that the data is not defined as being any particular length.
Is this correct? What is the significance of unaligned vs aligned? When would one benefit from using one compared to another?
My apologies for the novice question.
4 byte alignment or 32 bit alignment means addresses that are an integral multiple of 4 bytes, so 0x000, 0x004, 0x008, 0x00C, etc. Another way to view this is 4 = 2 to the power 2, so the lower two address bits need to be zero to be aligned. 8 byte aligned, 64 bits, 8 = 2 to the power 3, so the lower 3 bits need to be a zero to be 8 byte aligned. 2 byte, 2 to the power 1, so even numbered addresses are aligned, odd numbered addresses are unaligned for 2 byte transfers. Byte based transfers are always aligned, no problems there. (2 to the power 0, 0 bits need to be zero to be aligned).
All systems have penalties for unaligned transfers, some more so than others. One of the performance features of RISC platforms is to discourage or prevent unaligned transfers, so MIPS, ARM, etc fall into the stronger penalties category (to the point of preventing them all together). ARM now has memory controllers that allow for unaligned transfers without rotation or anything strange, not sure about MIPS. As a general rule though you should try to avoid unaligned transfers, no matter what system you are on.
Memory alignment refers to the placement of data in address space.
For example, an address having its two least significant bits clear (i.e. a multiple of 4) would be word aligned on a 32-bit word system. Similarly an address with the least significant bit clear is halfword aligned. If the address of some data is not aligned to whatever boundary is required by the instruction, data bus, or some other factor, it's unaligned.
Some processors (e.g. ARM) require data to be aligned to the size of the data (a word should be word aligned, and so on). Trying to access unaligned data can result in rotated data, or undefined behavior.
Other processors might allow unaligned memory accesses and handle them internally, but at a performance loss due to extra memory accesses.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With