string-misc.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /* Miscellaneous functions used in string implementations. RISC-V version.
  2. Copyright (C) 2025-2026 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <http://www.gnu.org/licenses/>. */
  15. #ifndef _RISCV_STRING_MISC_H
  16. #define _RISCV_STRING_MISC_H 1
  17. #include <limits.h>
  18. #include <endian.h>
  19. #include <string-optype.h>
  20. #if defined __riscv_zbkb
  21. /* Extract the byte at index IDX from word X, with index 0 being the
  22. least significant byte. */
  23. static __always_inline unsigned char
  24. extractbyte (op_t x, unsigned int idx)
  25. {
  26. if (__BYTE_ORDER == __LITTLE_ENDIAN)
  27. return x >> (idx * CHAR_BIT);
  28. else
  29. return x >> (sizeof (x) - 1 - idx) * CHAR_BIT;
  30. }
  31. /* Setup an word with each byte being c_in. For instance, on a 64 bits
  32. machine with input as 0xce the functions returns 0xcececececececece. */
  33. static __always_inline op_t
  34. repeat_bytes (unsigned char c_in)
  35. {
  36. op_t c = c_in;
  37. #if __riscv_xlen == 64
  38. /* 8bit -> 16bit -> 32bit -> 64bit pattern replication */
  39. __asm__ ("packh %0, %1, %1\n\t"
  40. "packw %0, %0, %0\n\t"
  41. "pack %0, %0, %0"
  42. : "=r"(c) : "r"(c));
  43. #elif __riscv_xlen == 32
  44. /* 8bit -> 16bit -> 32bit pattern replication */
  45. __asm__ ("packh %0, %1, %1\n\t"
  46. "pack %0, %0, %0"
  47. : "=r"(c) : "r"(c));
  48. #else
  49. #error unsupported xlen
  50. #endif
  51. return c;
  52. }
  53. #else
  54. #include <sysdeps/generic/string-misc.h>
  55. #endif
  56. #endif /* _RISCV_STRING_MISC_H */