Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between "minimum alignment" and "preferred alignment"?

Recently I observed that on Clang 9.0 alignof and __alignof are returning different values for unsigned long long and the same has been discussed at https://reviews.llvm.org/D54814:

Starting in Clang 8.0 and GCC 8.0, alignof and __alignof return different values in same cases. Specifically alignof and _Alignof return the minimum alignment for a type, where as __alignof returns the preferred alignment.

I know about type alignment but never came across "minimum alignment" and "preferred alignment".

Could somebody please help me understand what exactly these are and what is the difference? Thanks.

like image 274
Pendyala Avatar asked Nov 06 '22 10:11

Pendyala


1 Answers

The minimal alignment is (on a given platform) the one which won't give crashes. On x86-64 it is one byte. On PowerPC or Sparc or RISC-V it is probably 4 or 8 bytes.

The preferred alignment is the one which is usual, e.g. because of processor bus or CPU caches. On x86-64 for unsigned long long it probably is 8 bytes. Any less aligned access has a performance penalty.

Details are target processor and ABI specific (for example, see this). Think of cross-compilers.

The semantics of C or of C++ is not perfectly defined and not fully formalized. Look into the C++ draft standard: it is written in English, not formalized. But see also Frama-C (it has an experimental front end for C++) and CompCert. Read about undefined behavior.

like image 131
Basile Starynkevitch Avatar answered Nov 14 '22 21:11

Basile Starynkevitch