Implement C23 memalignment

Wilco Dijkstra Wilco.Dijkstra@arm.com
Thu Oct 2 18:51:51 GMT 2025


Hi,

> It's helpful to document it because memalignment is a new primitive
> which has a purpose that is not entirely clear to many programmers, and
> which has dicey performance in what would naively be a common use case.

Nobody could be using it since neither compilers nor libraries support it.
Compilers and libraries typically add support around the same time.
Now if you use a new GLIBC with an older GCC then it will not inline it - however
this is true for many similar functions (such as recently added uabs()).
If we care about such scenarios then we could provide inline implementations.

> I wish this kind of documementation were not needed, but we're stuck
> with memalignment as standardized, and should document its gotchas.

There is no gotcha. There are countless similar tiny functions in GLIBC.
These functions are never called because compilers always inline them.
And memalignment() won't be any different. 

> I also don't think the manual should be in the business of lecturing people
> about how to do pointer arithmetic correctly, especially not as an aside to
> reference documentation for specific functions.  (I'd welcome a "how to code
> defensively in C" chapter if someone wanted to write it.)

Agreed.

> The performance issues can and should be addressed by making this function
> into a compiler intrinsic.  Meanwhile, I suggest this wording instead:

Absolutely. I believe this is a non-issue since GCC will just inline it.

| On all presently supported systems, when @var{A} is a power of two,
| @code{memalignment (@var{P}) == @var{A}} is equivalent to
| @code{((uintptr_t) @var{P}) & (@var{A - 1})}.  If @var{A} is certain
| to be a power of two, it may be more efficient to use this formula
| instead of calling @code{memalignment}, especially with compilers
| that don't recognize @code{memalignment} as a built-in function
| like @code{alignof}.

If 'a' is a power of 2 (ie non-zero!), then

memalignment (p) >= a

is equivalent to:

 p != NULL && (p & (a-1)) == 0
 
If we know 'p' is non-null, and 'a' is a constant, this saves 2 instructions on most ISAs.

Compilers could also optimize:

memalignment (p) == a

to:

(p & (2*a-1)) == a

However writing this is likely a bug since we are typically interested in minimum
alignment rather than exact alignment.

Cheers,
Wilco


More information about the Libc-alpha mailing list