How to use __builtin_assume_aligned in C
Asked Answered
X

1

7

In my C code I have

complex float M[n][n];
complex float *delta = malloc(n * sizeof *delta);
complex float *v = malloc(n * sizeof *v);
for (i = 0; i < n; i++) {
    v[i] -= 2.*delta[j]*M[j][i];
}

where i and n are ints.

It was suggested I use __builtin_assume_aligned to make sure these are aligned in order to help auto-vectorization. However, having looked at the docs I don't understand how to do that.

How would you use it for this code?


The code in this question is extracted from How to help gcc vectorize C code . This is also why I want to try to align things.

Xenos answered 14/1, 2017 at 9:43 Comment(2)
I assume this is pseudo-ish code and that in the real code you initialize M, delta and v before you use them?Andy
@Someprogrammerdude Yes absolutely. The question comes from #41640154 .Xenos
A
8

__builtin_assume_aligned is just a hint for gcc that the pointer is already aligned, so that it can typically vectorize the following code; it's not a directive to either malloc or any other memory allocation mechanism, so you might be lying to gcc.

To ensure that you have actually aligned pointers, it's your responsibility to use appropriate mechanisms. So you have to:

  • either malloc and then roundup to the next multiple of your granularity (if not already there)
  • or use __attribute__((aligned(N))) in your declarations (working for sure for heap-allocated, and possibly for stack-allocated variables)
  • or use aligning memory allocation calls like posix_memalign
Aldas answered 16/6, 2017 at 6:52 Comment(3)
"__builtin_assume_aligned is just a hint." -- I think it's wrong to call it a "hint". It's a promise.Pepe
I think that “hint” as in “compilation hint” is quite common usage, but if I'm wrong your comment will help others disambiguate the meaning. Thanks for the feedback!Aldas
There are compiler hints, like __builtin_expect. That's why it's a common usage. But that doesn't make everything a hint.Pepe

© 2022 - 2024 — McMap. All rights reserved.