Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to understand the "align" attribute in WebAssembly?

Tags:

Why do those "load" and "store" operators need an "align" attribute, and how does it work with memory alignment?

BTW, why do we need this operator since the underlying system will do memory aligning for us automatically?

like image 559
Jason Yu Avatar asked Mar 18 '18 06:03

Jason Yu


2 Answers

It's a promise to VM that (baseAddr + memarg.offset) mod 2^memarg.align == 0 where baseAddr is argument form stack.

In other words, we virtually split our memory by blocks with size 2^memarg.align bytes and promise VM that our actual address (baseAddr + memarg.offset) will be at the start of any block, not in the middle.

Since the maximum value of memarg.align is 3 size of a block (in bytes) could be on of {1, 2, 4, 8} (1 = 2^0, .., 8 = 2^3).

Also, you can find a good detailed explanation here.

like image 50
bashor Avatar answered Sep 21 '22 13:09

bashor


The use of alignment is detailed in the spec:

The alignment memarg.𝖺𝗅𝗂𝗀𝗇 in load and store instructions does not affect the semantics. It is an indication that the offset ea at which the memory is accessed is intended to satisfy the property ea mod 2^memarg.𝖺𝗅𝗂𝗀𝗇=0. A WebAssembly implementation can use this hint to optimize for the intended use. Unaligned access violating that property is still allowed and must succeed regardless of the annotation. However, it may be substantially slower on some hardware.

There is no other semantic effect associated with alignment; misaligned and unaligned loads and stores still behave normally, it is simply a performance optimisation.

like image 23
ColinE Avatar answered Sep 19 '22 13:09

ColinE