Subject: bug#65491: [PATCH] Improve performance allocating vectors

From: Po Lu <[email-masked]>
Date: Sun, 17 Sep 2023 11:02:47 +0800

Mattias Engdegård <[email-masked]> writes:

> 16 sep. 2023 kl. 18.54 skrev Eli Zaretskii <[email-masked]>:
>
>> It does, but LISP_WORD_TAG(type) is a 64=bit type with the only bits
>> set above 32 bit, so how casting it to uintptr_t is TRT?
>
> Because XUNTAG is used to get the pointer part; we don't want the tag bits. 
>
>> Why did you need to change the original cast in the first place?
>
> The commit message tried to explain that, but in essence, the old code
> untagged a Lisp_Object value by casting it to char *, then do pointer
> arithmetic on that, and then cast the result to whatever pointer we
> want.
>
> The C standard severely restricts pointer arithmetic: in particular,
> for P+X where X is an integer and P is a pointer, P cannot be null
> (nor will P+X, since both P and P+X must be pointers to objects in the
> same array).
>
> This means that XUNTAG could never reliably untag a null pointer and
> this did cause mayhem in some places. We have just been lucky not to
> trigger it so far but I noticed when attempting to make some
> innocent-looking changes.

Within Standard C, the result of converting a pointer value to an
integer and vice versa is also implementation defined behavior.  GCC
regards converting an integer derived from a pointer value back to a
pointer as undefined behavior, should the resulting pointer point to an
object outside that which the pointer value that gave rise to the
original integer references.  From `(gcc)Arrays and Pointers':

     When casting from pointer to integer and back again, the resulting
     pointer must reference the same object as the original pointer,
     otherwise the behavior is undefined.  That is, one may not use
     integer arithmetic to avoid the undefined behavior of pointer
     arithmetic as proscribed in C99 and C11 6.5.6/8.

So whether pointer or integer arithmetic is employed in XUNTAG makes no
real difference to us, where undefined behavior is concerned, inasmuch
as other compilers only afford us even more latitude.  For example,
Sun's C compiler documentation actively encourages using pointer
arithmetic in lieu of integer arithmetic, and speaks nothing of pointer
arithmetic between different objects being forbidden.  And all other
things being equal, I would rather see existing, time-tested, almost
primordial code preserved intact.