[PATCH v7] malloc: Optimize small memory clearing for calloc

H.J. Lu hjl.tools@gmail.com
Tue Dec 3 04:42:03 GMT 2024


On Mon, Dec 2, 2024 at 8:50 PM H.J. Lu <hjl.tools@gmail.com> wrote:
>
> On Mon, Dec 2, 2024 at 8:17 PM Adhemerval Zanella Netto
> <adhemerval.zanella@linaro.org> wrote:
> >
> >
> >
> > On 02/12/24 09:05, Florian Weimer wrote:
> > > * Adhemerval Zanella Netto:
> > >
> > >>> +static __always_inline void *
> > >>> +clear_memory (void *mem, unsigned long clearsize)
> > >>> +{
> > >>> +  /* Unroll clear memory size up to 9 * INTERNAL_SIZE_T bytes.  We know
> > >>> +     that contents have an odd number of INTERNAL_SIZE_T-sized words;
> > >>> +     minimally 3 words.  */
> > >>> +  INTERNAL_SIZE_T *d = (INTERNAL_SIZE_T *) mem;
> > >>
> > >> I think this strictly UB and it might generate some issues on architecture
> > >> with strict alignment requirement (like sparc and some riscv chips). I
> > >> think we will need to use either some struct helper with __attribute__((packed))
> > >> or memcpy to avoid it.
> > >
> > > I think everything is properly aligned?  The “overlapping” comment is a
> > > bit misleading, it's about multiple stores to the same locations, not
> > > partially overlapping stores.
> >
> > So maybe then define 'mem' as 'INTERNAL_SIZE_T *'?
>
> Fixed in the v6 patch.  I also changed "overlapping" to "repeated".
>
> Add calloc-clear-memory.h to clear memory size up to 36 bytes (72 if 8byte
> sizes) for calloc.  Use repeated stores with 1 branch, instead of up to
> 3 branches.  On x860-64, it is faster than memset since calling memset
> needs 1 indirect branch, 1 broadcast, and up to 4 branches.
>
> OK for master?
>

Here is the v7 patch with

  /* NB: The VRP pass in GCC 14.2 will optimize it out.  */
  if (nclears < 3)
    __builtin_unreachable ();

  /* Use repeated stores with 1 branch, instead of up to 3.  */
  *(d + 0) = 0;
  *(d + 1) = 0;
  *(d + 2) = 0;
  *(d + nclears - 2) = 0;
  *(d + nclears - 2 + 1) = 0;

OK for master?

Thanks.

-- 
H.J.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: v7-0001-malloc-Optimize-small-memory-clearing-for-calloc.patch
Type: application/x-patch
Size: 4583 bytes
Desc: not available
URL: <https://sourceware.org/pipermail/libc-alpha/attachments/20241203/f5bfb8fb/attachment.bin>


More information about the Libc-alpha mailing list