Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Clang-Tidy suggest a larger alignment?

Given the following c language struct definition:

typedef struct PackTest {
    long long a;
    int b;
    int c;
} PackTest;

Clang-Tidy gives the following message:

Accessing fields in struct 'PackTest' is inefficient due to poor alignment; currently aligned to 8 bytes, but recommended alignment is 16 bytes

I know why the struct is aligned to 8 bytes, but I don't know if the suggestion is valid and why.

like image 277
yixiang Avatar asked Oct 27 '20 03:10

yixiang


Video Answer


2 Answers

Some particular specialized assembly instructions might have alignment requirements (for example, x86 non-scalar SSE instructions strictly require alignment to 16 bytes boundaries). Other instructions might have lower throughput when used on data that is not aligned to 16 byte boundaries (for example, x86 SSE2).

These kind of instructions are usually used to perform aggressive optimizations based on the hardware features of the processor. Overall, the message you get is only useful in those scenarios (i.e. if you are actually planning to take advantage of such instructions).

See also:

  • What does alignment to 16-byte boundary mean in x86
  • Why and where align 16 is used for SSE alignment for instructions?

Finally I'll just quote Rich from the above comment since they make a really good point:

There is nothing "untidy" about having standard structs that are not ridiculously over-aligned. For very specialized purposes you might want an over-aligned object, but if it's flagging this then most things it's flagging are just wrong, and encouraging you to write code that's inefficient and gratuitously nonstandard.

like image 108
Marco Bonelli Avatar answered Oct 06 '22 18:10

Marco Bonelli


you can add -altera-struct-pack-align for Clang-Tidy to disable this warning

source: https://www.mail-archive.com/[email protected]/msg171275.html

like image 3
wusheng Avatar answered Oct 06 '22 17:10

wusheng