[libc-commits] [libc] [libc] [search] implement hcreate(_r)/hsearch(_r)/hdestroy(_r) (PR #73469)
Schrodinger ZHU Yifan via libc-commits
libc-commits at lists.llvm.org
Sun Nov 26 19:36:12 PST 2023
================
@@ -0,0 +1,161 @@
+//===-- Portable string hash function ---------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_SRC___SUPPORT_HASH_H
+#define LLVM_LIBC_SRC___SUPPORT_HASH_H
+
+#include "src/__support/UInt128.h" // UInt128
+#include "src/__support/macros/attributes.h"
+#include <stdint.h> // For uint64_t
+
+namespace LIBC_NAMESPACE {
+namespace internal {
+
+// Folded multiplication.
+// This function multiplies two 64-bit integers and xor the high and
+// low 64-bit parts of the result.
+LIBC_INLINE static uint64_t folded_multiply(uint64_t x, uint64_t y) {
+ UInt128 mask = static_cast<UInt128>(0xffffffffffffffff);
+ UInt128 p = static_cast<UInt128>(x) * static_cast<UInt128>(y);
+ uint64_t low = static_cast<uint64_t>(p & mask);
+ uint64_t high = static_cast<uint64_t>(p >> 64);
+ return low ^ high;
+}
+
+// Read as little endian.
+// Shift-and-or implementation does not give a satisfactory code on aarch64.
+// Therefore, we use a union to read the value.
+template <typename T> LIBC_INLINE static T read_little_endian(const void *ptr) {
----------------
SchrodingerZhu wrote:
I tested two ways of writing shift-and-or:
```c++
T res;
for(int i = 0; i < sizeof(T); ++i) {
res = res | (bytes[i] << (i * 8));
}
```
and
```c++
T res;
for(int i = 1; i <= sizeof(T); ++i) {
res = (res << 8) | bytes[sizeof(T) - i];
}
```
Neither of them gives satisfactory codegen with GCC (clang is fine):
The first one is very bad on both x64 and aarch64 even when being compiled along.
The second one is bad on aarch64 when used in some other code.
https://github.com/llvm/llvm-project/pull/73469
More information about the libc-commits
mailing list