#ifndef LLVM_LIBC_SRC_MEMORY_UTILS_UTILS_H
#define LLVM_LIBC_SRC_MEMORY_UTILS_UTILS_H
#include "src/__support/architectures.h"
#if defined(LLVM_LIBC_ARCH_AARCH64) || defined(LLVM_LIBC_ARCH_X86)
#define LLVM_LIBC_CACHELINE_SIZE 64
#elif defined(LLVM_LIBC_ARCH_ARM)
#define LLVM_LIBC_CACHELINE_SIZE 32
#else
#error "Unsupported platform for memory functions."
#endif
#include <stddef.h>
#include <stdint.h>
namespace __llvm_libc {
static constexpr bool is_power2_or_zero(size_t value) {
return (value & (value - 1U)) == 0;
}
static constexpr bool is_power2(size_t value) {
return value && is_power2_or_zero(value);
}
static constexpr size_t log2(size_t value) {
return (value == 0 || value == 1) ? 0 : 1 + log2(value / 2);
}
static constexpr size_t le_power2(size_t value) {
return value == 0 ? value : 1ULL << log2(value);
}
static constexpr size_t ge_power2(size_t value) {
return is_power2_or_zero(value) ? value : 1ULL << (log2(value) + 1);
}
template <size_t alignment> intptr_t offset_from_last_aligned(const void *ptr) {
static_assert(is_power2(alignment), "alignment must be a power of 2");
return reinterpret_cast<uintptr_t>(ptr) & (alignment - 1U);
}
template <size_t alignment> intptr_t offset_to_next_aligned(const void *ptr) {
static_assert(is_power2(alignment), "alignment must be a power of 2");
return -reinterpret_cast<uintptr_t>(ptr) & (alignment - 1U);
}
static inline intptr_t offset_to_next_cache_line(const void *ptr) {
return offset_to_next_aligned<LLVM_LIBC_CACHELINE_SIZE>(ptr);
}
template <size_t alignment, typename T> static T *assume_aligned(T *ptr) {
return reinterpret_cast<T *>(__builtin_assume_aligned(ptr, alignment));
}
}
#endif