feat(string): implement core string/memory functions (level 1)
Word-at-a-time memcpy/memmove/memset/strlen/strcmp implementing the level-1 string slice. memcpy carries an optimize(no-tree-loop- distribute-patterns) attribute: GCC's loop-distribution pass rewrites its word-copy loop into a self-recursive memcpy@plt call at -O2/-O3 otherwise. Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent) Co-authored-by: Sisyphus <[email protected]>
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
#ifdef HAVE_CONFIG_H
|
||||
#include <config.h>
|
||||
#endif
|
||||
|
||||
#include <string.h>
|
||||
|
||||
/*
|
||||
* Copy n bytes from src to dst. The regions must not overlap (restrict).
|
||||
* Word-at-a-time: copy whole unsigned long words once dst is aligned, with
|
||||
* a byte head and tail. Word loads and stores go through __builtin_memcpy
|
||||
* so unaligned src is handled without undefined behavior.
|
||||
*
|
||||
* The word-copy loop below is the canonical memcpy idiom; GCC's
|
||||
* -ftree-loop-distribute-patterns (on by default at -O2 and -O3) rewrites
|
||||
* it into a call to memcpy() — this very function — causing infinite
|
||||
* self-recursion and stack overflow. Disable that one transformation for
|
||||
* this function only.
|
||||
*/
|
||||
__attribute__((optimize("no-tree-loop-distribute-patterns")))
|
||||
void *
|
||||
memcpy(void *restrict dst, const void *restrict src, size_t n)
|
||||
{
|
||||
const unsigned long word = sizeof(unsigned long);
|
||||
unsigned char *d = dst;
|
||||
const unsigned char *s = src;
|
||||
|
||||
/* Copy the unaligned head byte-wise. */
|
||||
for (; (unsigned long)d % word != 0 && n != 0; n--)
|
||||
{
|
||||
*d++ = *s++;
|
||||
}
|
||||
|
||||
/* Copy whole words. */
|
||||
while (n >= word)
|
||||
{
|
||||
unsigned long w;
|
||||
|
||||
__builtin_memcpy(&w, s, sizeof w);
|
||||
__builtin_memcpy(d, &w, sizeof w);
|
||||
d += word;
|
||||
s += word;
|
||||
n -= word;
|
||||
}
|
||||
|
||||
/* Copy the remaining tail byte-wise. */
|
||||
while (n != 0)
|
||||
{
|
||||
*d++ = *s++;
|
||||
n--;
|
||||
}
|
||||
|
||||
return dst;
|
||||
}
|
||||
Reference in New Issue
Block a user