diff --git a/absl/base/attributes.h b/absl/base/attributes.h index 32af1dd..b68c52c 100644 --- a/absl/base/attributes.h +++ b/absl/base/attributes.h
@@ -287,6 +287,9 @@ // out of bounds or does other scary things with memory. // NOTE: GCC supports AddressSanitizer(asan) since 4.8. // https://gcc.gnu.org/gcc-4.8/changes.html +// NOTE: When active on Clang/GCC, this macro expands to a C++11 `[[...]]` +// attribute and must precede GNU `__attribute__((...))` macros such as +// `ABSL_ATTRIBUTE_NOINLINE` on declarations. #if defined(ABSL_HAVE_ADDRESS_SANITIZER) && \ ABSL_HAVE_ATTRIBUTE(no_sanitize_address) #if ABSL_HAVE_CPP_ATTRIBUTE(gnu::no_sanitize_address) @@ -305,6 +308,8 @@ // https://gcc.gnu.org/gcc-11/changes.html #if ABSL_HAVE_CPP_ATTRIBUTE(gnu::no_sanitize) #define ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS [[gnu::no_sanitize("hwaddress")]] +#elif ABSL_HAVE_CPP_ATTRIBUTE(clang::no_sanitize) +#define ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS [[clang::no_sanitize("hwaddress")]] #else #define ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS \ __attribute__((no_sanitize("hwaddress")))
diff --git a/absl/base/attributes_test.cc b/absl/base/attributes_test.cc index deabd5d..a014a06 100644 --- a/absl/base/attributes_test.cc +++ b/absl/base/attributes_test.cc
@@ -105,4 +105,41 @@ EXPECT_EQ(NoSanitizeCfiCall([](int x) { return x + 1; }, 41), 42); } +// Verifies compile-time appertainment when C++11 `[[...]]` sanitizer/cold +// attributes are stacked together and before GNU `__attribute__((noinline))` on +// class member functions and member function templates. +class StackedNoSanitizeTarget { + public: + ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY int + AddressAndMemory(int value) const { + return value + 1; + } + +#if !defined(_MSC_VER) || defined(__clang__) + // On native MSVC under ASan, ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS expands to + // __declspec(no_sanitize_address) while ABSL_ATTRIBUTE_NOINLINE expands to + // [[msvc::noinline]], which cannot follow __declspec. + ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS ABSL_ATTRIBUTE_NOINLINE int + AddressAndNoInline(int value) const { + return value + 2; + } + + template <typename T> + ABSL_ATTRIBUTE_COLD ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS ABSL_ATTRIBUTE_NOINLINE + T + ColdAddressAndNoInline(T value) const { + return value + 3; + } +#endif +}; + +TEST(Attributes, StackedNoSanitizeMemberFunctions) { + StackedNoSanitizeTarget target; + EXPECT_EQ(target.AddressAndMemory(10), 11); +#if !defined(_MSC_VER) || defined(__clang__) + EXPECT_EQ(target.AddressAndNoInline(20), 22); + EXPECT_EQ(target.ColdAddressAndNoInline(30), 33); +#endif +} + } // namespace
diff --git a/absl/base/internal/cpu_detect.cc b/absl/base/internal/cpu_detect.cc index e6858e3..218a5c5 100644 --- a/absl/base/internal/cpu_detect.cc +++ b/absl/base/internal/cpu_detect.cc
@@ -35,6 +35,21 @@ #if defined(_WIN32) || defined(_WIN64) #include <intrin.h> +#if defined(__aarch64__) || defined(_M_ARM64) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include <windows.h> +#ifndef PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE +#define PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE 30 +#endif +#ifndef PF_ARM_V8_CRC32_INSTRUCTIONS_AVAILABLE +#define PF_ARM_V8_CRC32_INSTRUCTIONS_AVAILABLE 31 +#endif +#ifndef PF_ARM_SHA3_INSTRUCTIONS_AVAILABLE +#define PF_ARM_SHA3_INSTRUCTIONS_AVAILABLE 64 +#endif +#endif // defined(__aarch64__) || defined(_M_ARM64) #endif #if defined(__x86_64__) || defined(_M_X64) @@ -242,6 +257,23 @@ } } +// Reads extended control register 0 (XCR0). The caller must verify via CPUID +// that the CPU and OS support OSXSAVE before calling this function. +uint64_t ReadXcr0() { +#if defined(_MSC_VER) + return _xgetbv(0); +#elif defined(__GNUC__) || defined(__clang__) + uint32_t eax = 0; + uint32_t edx = 0; + // Use the raw opcode for xgetbv (0F 01 D0) so this compiles without -mxsave + // and on assemblers that do not recognize the xgetbv mnemonic. + __asm__ volatile(".byte 0x0f, 0x01, 0xd0" : "=a"(eax), "=d"(edx) : "c"(0)); + return (static_cast<uint64_t>(edx) << 32) | eax; +#else + return 0; +#endif +} + } // namespace CpuType GetCpuType() { @@ -257,6 +289,31 @@ bool SupportsArmCRC32PMULL() { return false; } +bool SupportsArmSHA3() { return false; } + +bool SupportsAvx2() { + // Query CPUID and XCR0 directly instead of using __builtin_cpu_supports(), + // which pulls in a static initializer (__cpu_indicator_init) from the + // compiler runtime. + int cpu_info[4]; + __cpuid(cpu_info, 0); + if (cpu_info[0] < 7) { + return false; + } + __cpuid(cpu_info, 1); + constexpr int kOsxsaveAndAvx = (1 << 27) | (1 << 28); + if ((cpu_info[2] & kOsxsaveAndAvx) != kOsxsaveAndAvx) { + return false; + } + // Check that the OS saves both XMM (bit 1) and YMM (bit 2) state. + constexpr uint64_t kXmmAndYmmState = 0x6; + if ((ReadXcr0() & kXmmAndYmmState) != kXmmAndYmmState) { + return false; + } + __cpuidex(cpu_info, 7, 0); + return (cpu_info[1] & (1 << 5)) != 0; +} + bool SupportsBmi2() { int cpu_info[4]; __cpuid(cpu_info, 0); @@ -341,13 +398,27 @@ bool SupportsArmCRC32PMULL() { #if defined(HWCAP_CRC32) && defined(HWCAP_PMULL) - uint64_t hwcaps = getauxval(AT_HWCAP); - return (hwcaps & HWCAP_CRC32) && (hwcaps & HWCAP_PMULL); + static const bool supported = []() { + uint64_t hwcaps = getauxval(AT_HWCAP); + return (hwcaps & HWCAP_CRC32) && (hwcaps & HWCAP_PMULL); + }(); + return supported; #else return false; #endif } +bool SupportsArmSHA3() { +#if defined(HWCAP_SHA3) + static const bool supported = (getauxval(AT_HWCAP) & HWCAP_SHA3) != 0; + return supported; +#else + return false; +#endif +} + +bool SupportsAvx2() { return false; } + bool SupportsBmi2() { return false; } #elif defined(__aarch64__) && defined(__APPLE__) @@ -396,6 +467,42 @@ return supported; } +bool SupportsArmSHA3() { + static const bool supported = []() { +#if defined(CAP_BIT_FEAT_SHA3) + const std::optional<uint64_t> caps = + ReadSysctlByName<uint64_t>("hw.optional.arm.caps"); + if (caps.has_value()) { + return (*caps & (uint64_t{1} << CAP_BIT_FEAT_SHA3)) != 0; + } +#endif + const std::optional<int> feat_sha3 = + ReadSysctlByName<int>("hw.optional.armv8_2_sha3"); + return feat_sha3.value_or(0) != 0; + }(); + return supported; +} + +bool SupportsAvx2() { return false; } + +bool SupportsBmi2() { return false; } + +#elif (defined(__aarch64__) || defined(_M_ARM64)) && \ + (defined(_WIN32) || defined(_WIN64)) + +CpuType GetCpuType() { return CpuType::kUnknown; } + +bool SupportsArmCRC32PMULL() { + return IsProcessorFeaturePresent(PF_ARM_V8_CRC32_INSTRUCTIONS_AVAILABLE) && + IsProcessorFeaturePresent(PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE); +} + +bool SupportsArmSHA3() { + return IsProcessorFeaturePresent(PF_ARM_SHA3_INSTRUCTIONS_AVAILABLE); +} + +bool SupportsAvx2() { return false; } + bool SupportsBmi2() { return false; } #else @@ -404,6 +511,10 @@ bool SupportsArmCRC32PMULL() { return false; } +bool SupportsArmSHA3() { return false; } + +bool SupportsAvx2() { return false; } + bool SupportsBmi2() { return false; } #endif
diff --git a/absl/base/internal/cpu_detect.h b/absl/base/internal/cpu_detect.h index 1ce3eba..c247e27 100644 --- a/absl/base/internal/cpu_detect.h +++ b/absl/base/internal/cpu_detect.h
@@ -68,6 +68,12 @@ // tuning. bool SupportsArmCRC32PMULL(); +// Returns whether the host CPU supports ARM SHA3 instructions (e.g., EOR3). +bool SupportsArmSHA3(); + +// Returns whether the host CPU and OS support AVX2 instructions. +bool SupportsAvx2(); + // Returns whether the host CPU supports BMI2 instructions. bool SupportsBmi2();
diff --git a/absl/base/internal/cpu_detect_test.cc b/absl/base/internal/cpu_detect_test.cc index 80b8b87..1bfc831 100644 --- a/absl/base/internal/cpu_detect_test.cc +++ b/absl/base/internal/cpu_detect_test.cc
@@ -22,6 +22,26 @@ namespace base_internal { namespace { +TEST(CpuDetectTest, SupportsArmSHA3) { +#if defined(__aarch64__) || defined(_M_ARM64) + (void)SupportsArmSHA3(); +#else + EXPECT_FALSE(SupportsArmSHA3()); +#endif +} + +TEST(CpuDetectTest, SupportsAvx2) { +#if defined(__x86_64__) || defined(_M_X64) +#if ABSL_HAVE_BUILTIN(__builtin_cpu_supports) && defined(__linux__) + EXPECT_EQ(SupportsAvx2(), __builtin_cpu_supports("avx2") != 0); +#else + (void)SupportsAvx2(); +#endif +#else + EXPECT_FALSE(SupportsAvx2()); +#endif +} + TEST(CpuDetectTest, SupportsBmi2) { #if defined(__x86_64__) || defined(_M_X64) #if ABSL_HAVE_BUILTIN(__builtin_cpu_supports) && defined(__linux__)
diff --git a/absl/base/internal/low_level_alloc.h b/absl/base/internal/low_level_alloc.h index 23218dd..47d4899 100644 --- a/absl/base/internal/low_level_alloc.h +++ b/absl/base/internal/low_level_alloc.h
@@ -69,16 +69,16 @@ // Returns 0 if passed request==0. // Does not return 0 under other circumstances; it crashes if memory // is not available. - static void *Alloc(size_t request) ABSL_ATTRIBUTE_SECTION(malloc_hook); - static void *AllocWithArena(size_t request, Arena *arena) - ABSL_ATTRIBUTE_SECTION(malloc_hook); + ABSL_ATTRIBUTE_SECTION(malloc_hook) static void* Alloc(size_t request); + ABSL_ATTRIBUTE_SECTION(malloc_hook) + static void* AllocWithArena(size_t request, Arena* arena); // Deallocates a region of memory that was previously allocated with // Alloc(). Does nothing if passed 0. "s" must be either 0, // or must have been returned from a call to Alloc() and not yet passed to // Free() since that call to Alloc(). The space is returned to the arena // from which it was allocated. - static void Free(void *s) ABSL_ATTRIBUTE_SECTION(malloc_hook); + ABSL_ATTRIBUTE_SECTION(malloc_hook) static void Free(void* s); // ABSL_ATTRIBUTE_SECTION(malloc_hook) for Alloc* and Free // are to put all callers of MallocHook::Invoke* in this module
diff --git a/absl/base/optimization.h b/absl/base/optimization.h index 8247ef2..83a7533 100644 --- a/absl/base/optimization.h +++ b/absl/base/optimization.h
@@ -120,18 +120,12 @@ // Cacheline aligning objects properly allows constructive memory sharing and // prevents destructive (or "false") memory sharing. // -// NOTE: callers should replace uses of this macro with `alignas()` using -// `std::hardware_constructive_interference_size` and/or -// `std::hardware_destructive_interference_size` when C++17 becomes available to -// them. +// Deprecated. Callers should replace uses of this macro with +// `alignas(ABSL_CACHELINE_SIZE)`. // // See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0154r1.html // for more information. // -// On some compilers, `ABSL_CACHELINE_ALIGNED` expands to an `__attribute__` -// or `__declspec` attribute. For compilers where this is not known to work, -// the macro expands to nothing. -// // No further guarantees are made here. The result of applying the macro // to variables and types is always implementation-defined. // @@ -155,13 +149,7 @@ // the generated machine code. // 3) Prefer applying this attribute to individual variables. Avoid // applying it to types. This tends to localize the effect. -#if defined(__clang__) || defined(__GNUC__) -#define ABSL_CACHELINE_ALIGNED __attribute__((aligned(ABSL_CACHELINE_SIZE))) -#elif defined(_MSC_VER) -#define ABSL_CACHELINE_ALIGNED __declspec(align(ABSL_CACHELINE_SIZE)) -#else -#define ABSL_CACHELINE_ALIGNED -#endif +#define ABSL_CACHELINE_ALIGNED alignas(ABSL_CACHELINE_SIZE) // ABSL_PREDICT_TRUE, ABSL_PREDICT_FALSE //
diff --git a/absl/container/internal/container_memory.h b/absl/container/internal/container_memory.h index e09b880..54cde80 100644 --- a/absl/container/internal/container_memory.h +++ b/absl/container/internal/container_memory.h
@@ -318,6 +318,30 @@ return std::forward<F>(f)(key, std::forward<Arg>(arg)); } +// SFINAE probe checking that `PassedKey` can be hashed and compared against +// `ContainerKey`. +template <class ContainerKey, class Hash, class Eq> +struct RequireUsableKey { + template <class PassedKey, class... Args> + std::pair< + decltype(std::declval<const Hash&>()(std::declval<const PassedKey&>())), + decltype(std::declval<const Eq&>()(std::declval<const ContainerKey&>(), + std::declval<const PassedKey&>()))>* + operator()(const PassedKey&, const Args&...) const; +}; + +// True if `Policy::apply` can extract a key from `Ts...` that satisfies +// `RequireUsableKey<Policy::key_type, Hash, Eq>`. +template <class E, class Policy, class Hash, class Eq, class... Ts> +struct IsDecomposable : std::false_type {}; + +template <class Policy, class Hash, class Eq, class... Ts> +struct IsDecomposable< + std::void_t<decltype(Policy::apply( + RequireUsableKey<typename Policy::key_type, Hash, Eq>(), + std::declval<Ts>()...))>, + Policy, Hash, Eq, Ts...> : std::true_type {}; + // Helper functions for asan and msan. inline void SanitizerPoisonMemoryRegion(const void* m, size_t s) { #ifdef ABSL_HAVE_ADDRESS_SANITIZER
diff --git a/absl/container/internal/hashtablez_sampler.cc b/absl/container/internal/hashtablez_sampler.cc index 82929bb..a25788b 100644 --- a/absl/container/internal/hashtablez_sampler.cc +++ b/absl/container/internal/hashtablez_sampler.cc
@@ -61,6 +61,30 @@ if (listener != nullptr) listener(); } +// Sampled SOO tables allocate a `NextCapacity(soo_capacity)` (3-slot) backing +// array on the heap to store `HashtablezInfoHandle`, while reporting +// `capacity == soo_capacity` until grown or reserved past `soo_capacity`. +constexpr size_t SampledSooAllocatedCapacity(size_t soo_capacity) { + return 2 * soo_capacity + 1; +} + +// Returns true when `info` represents a sampled SOO table that is still +// reporting `soo_capacity`. `PrepareForSampling` initializes `capacity` to 0, +// and the initial `RecordStorageChangedSlow` call clamps the 3-slot heap +// capacity to `soo_capacity` so this becomes true until `LeaveSooCapacity`. +bool IsReportingSooCapacity(const HashtablezInfo* info) { + return info->soo_capacity > 0 && + info->capacity.load(std::memory_order_relaxed) == info->soo_capacity; +} + +// Transitions `info` from reporting `soo_capacity` to reporting its actual +// 3-slot heap capacity and records the logical SOO-to-heap growth rehash. +void LeaveSooCapacity(HashtablezInfo* info) { + info->capacity.store(SampledSooAllocatedCapacity(info->soo_capacity), + std::memory_order_relaxed); + RecordRehashSlow(info, /*total_probe_length=*/0); +} + } // namespace #if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE) @@ -195,6 +219,7 @@ } void RecordRehashSlow(HashtablezInfo* info, size_t total_probe_length) { + if (IsReportingSooCapacity(info)) return; #ifdef ABSL_INTERNAL_HAVE_SSE2 total_probe_length /= 16; #else @@ -210,6 +235,10 @@ } void RecordReservationSlow(HashtablezInfo* info, size_t target_capacity) { + if (target_capacity <= info->soo_capacity) return; + if (IsReportingSooCapacity(info)) { + LeaveSooCapacity(info); + } info->max_reserve.store( (std::max)(info->max_reserve.load(std::memory_order_relaxed), target_capacity), @@ -222,6 +251,11 @@ void RecordStorageChangedSlow(HashtablezInfo* info, size_t size, size_t capacity) { + if (info->soo_capacity > 0 && size <= info->soo_capacity && + capacity == SampledSooAllocatedCapacity(info->soo_capacity) && + info->capacity.load(std::memory_order_relaxed) <= info->soo_capacity) { + capacity = info->soo_capacity; + } info->size.store(size, std::memory_order_relaxed); info->capacity.store(capacity, std::memory_order_relaxed); if (size == 0) { @@ -233,6 +267,10 @@ void RecordInsertMissSlow(HashtablezInfo* info, size_t hash, size_t distance_from_desired) { + if (IsReportingSooCapacity(info) && + info->size.load(std::memory_order_relaxed) >= info->soo_capacity) { + LeaveSooCapacity(info); + } // SwissTables probe in groups of 16, so scale this to count items probes and // not offset from desired. size_t probe_length = distance_from_desired;
diff --git a/absl/container/internal/hashtablez_sampler.h b/absl/container/internal/hashtablez_sampler.h index 540205e..4ad5e5f 100644 --- a/absl/container/internal/hashtablez_sampler.h +++ b/absl/container/internal/hashtablez_sampler.h
@@ -99,9 +99,10 @@ absl::Time create_time; uint32_t depth; // The SOO capacity for this table in elements (not bytes). Note that sampled - // tables are never SOO because we need to store the infoz handle on the heap. - // Tables that would be SOO if not sampled should have: soo_capacity > 0 && - // size <= soo_capacity && max_reserve <= soo_capacity. + // tables are never SOO because we need to store the infoz handle on the heap, + // but tables that would be SOO if not sampled report `capacity == + // soo_capacity` (and have `soo_capacity > 0 && size <= soo_capacity && + // max_reserve <= soo_capacity`). uint16_t soo_capacity; void* stack[kMaxStackDepth]; size_t inline_element_size; // How big is the slot in bytes?
diff --git a/absl/container/internal/raw_hash_map.h b/absl/container/internal/raw_hash_map.h index b85accf..bbb227e 100644 --- a/absl/container/internal/raw_hash_map.h +++ b/absl/container/internal/raw_hash_map.h
@@ -310,7 +310,7 @@ template <class K = key_type, class P = Policy> MappedReference<P> at(const_key_arg<K> key) ABSL_ATTRIBUTE_LIFETIME_BOUND { auto it = this->find(key); - if (this->unchecked_equals(it, this->end())) { + if (this->unchecked_is_end(it)) { ThrowStdOutOfRange("absl::container_internal::raw_hash_map<>::at"); } return Policy::value(&this->unchecked_deref(it)); @@ -320,7 +320,7 @@ MappedConstReference<P> at(const_key_arg<K> key) const ABSL_ATTRIBUTE_LIFETIME_BOUND { auto it = this->find(key); - if (this->unchecked_equals(it, this->end())) { + if (this->unchecked_is_end(it)) { ThrowStdOutOfRange("absl::container_internal::raw_hash_map<>::at"); } return Policy::value(&this->unchecked_deref(it));
diff --git a/absl/container/internal/raw_hash_set.cc b/absl/container/internal/raw_hash_set.cc index bd36659..85a34a3 100644 --- a/absl/container/internal/raw_hash_set.cc +++ b/absl/container/internal/raw_hash_set.cc
@@ -843,6 +843,15 @@ // new_ctrl after 2nd store = EHNSEHNEEEE } +size_t AllocatedCapacityForInfoz(const CommonFields& c) { + return c.capacity() - c.blocked_element_count(); +} + +ABSL_ATTRIBUTE_COLD ABSL_ATTRIBUTE_NOINLINE void ReportClearToInfoz( + CommonFields& c) { + c.infoz().RecordStorageChanged(0, AllocatedCapacityForInfoz(c)); +} + // Clears the backing array and sets the common fields to the default values for // empty non-allocated tables. REQUIRES: c.capacity > policy.soo_capacity. void ClearBackingArrayNoReuse(CommonFields& c, @@ -952,7 +961,9 @@ ResetCtrl(cap, ctrl, slot_array, policy.slot_size, blocked_element_count); ResetGrowthLeft(cap, blocked_element_count, c); ABSL_SWISSTABLE_ASSERT(c.blocked_element_count() == blocked_element_count); - c.infoz().RecordStorageChanged(0, c.capacity()); + if (c.has_infoz()) { + ReportClearToInfoz(c); + } } else { ClearBackingArrayNoReuse(c, policy); } @@ -995,6 +1006,11 @@ destroy_slot(&c, SingleSlotAddress<kSooEnabled>(c)); } DecrementSmallSize<kSooEnabled>(c); + if constexpr (!kSooEnabled) { + c.increment_generation(); + SanitizerPoisonMemoryRegion( + SingleSlotAddress</*kSooEnabled=*/false>(c), policy.slot_size); + } c.infoz().RecordStorageChanged(0, cap); } } else { @@ -1129,7 +1145,8 @@ ABSL_ATTRIBUTE_COLD ABSL_ATTRIBUTE_NOINLINE void ReportGrowthToInfozImpl( CommonFields& common, HashtablezInfoHandle infoz, size_t hash, size_t total_probe_length, size_t distance_from_desired) { - infoz.RecordStorageChanged(common.size() - 1, common.capacity()); + infoz.RecordStorageChanged(common.size() - 1, + AllocatedCapacityForInfoz(common)); infoz.RecordRehash(total_probe_length); infoz.RecordInsertMiss(hash, distance_from_desired); common.set_has_infoz(); @@ -1201,30 +1218,25 @@ total_probe_length, distance_from_desired); } -// Passed as `total_probe_length` to `ReportResizeToInfoz` when the resize must -// not be reported as a rehash. -constexpr size_t kNoRehash = ~size_t{}; - ABSL_ATTRIBUTE_COLD ABSL_ATTRIBUTE_NOINLINE void ReportResizeToInfoz( CommonFields& common, HashtablezInfoHandle infoz, size_t total_probe_length) { - infoz.RecordStorageChanged(common.size(), common.capacity()); - if (total_probe_length != kNoRehash) { - infoz.RecordRehash(total_probe_length); - } + infoz.RecordStorageChanged(common.size(), AllocatedCapacityForInfoz(common)); + infoz.RecordRehash(total_probe_length); common.set_has_infoz(); common.set_infoz(infoz); } ABSL_ATTRIBUTE_COLD ABSL_ATTRIBUTE_NOINLINE void -ReportResizeToInfozAndForceSample( - CommonFields& common, const AllocPolicy& __restrict policy, - size_t total_probe_length) { - HashtablezInfoHandle infoz = ForcedTrySample(policy); - infoz.RecordStorageChanged(common.size(), common.capacity()); - infoz.RecordRehash(total_probe_length); - common.set_has_infoz(); - common.set_infoz(infoz); +ReportResizeToInfozAndForceSample(CommonFields& common, + const AllocPolicy& __restrict policy) { + ReportResizeToInfoz(common, ForcedTrySample(policy), + /*total_probe_length=*/0); +} + +ABSL_ATTRIBUTE_COLD ABSL_ATTRIBUTE_NOINLINE void ReportReserveToInfoz( + CommonFields& common, size_t new_size) { + common.infoz().RecordReservation(new_size); } struct BackingArrayPtrs { @@ -1290,7 +1302,7 @@ ResetGrowthLeft(new_capacity, blocked_element_count, common); if (ABSL_PREDICT_FALSE(has_infoz)) { - ReportResizeToInfozAndForceSample(common, policy, 0); + ReportResizeToInfozAndForceSample(common, policy); } } @@ -1391,9 +1403,7 @@ } ResetGrowthLeft(new_capacity, common.size(), common); if (ABSL_PREDICT_FALSE(has_infoz)) { - // Forced sampling of a full SOO table is not reported as a rehash. - ReportResizeToInfoz(common, infoz, - force_sample_soo ? kNoRehash : total_probe_length); + ReportResizeToInfoz(common, infoz, total_probe_length); } } @@ -2083,6 +2093,7 @@ ABSL_SWISSTABLE_ASSERT(!policy.alloc_policy->soo_enabled); const bool is_empty = common.empty_when_small(); if (common.capacity() == 1 && is_empty) { + common.maybe_increment_generation_on_insert(); IncrementSmallSizeNonSoo(common, *policy.alloc_policy); // Compute before `RecordInsertMissCold` to avoid reloading `control_`. void* res = common.single_non_soo_slot(); @@ -2292,7 +2303,9 @@ /*force_infoz=*/false); // This is after resize, to ensure that we have completed the allocation // and have potentially sampled the hashtable. - common.infoz().RecordReservation(new_size); + if (common.has_infoz()) { + ReportReserveToInfoz(common, new_size); + } } // Type erased version of raw_hash_set::reserve for tables that have an @@ -2313,7 +2326,9 @@ // TODO(b/382423690): consider using GrowToNextCapacity, when applicable. ResizeTableWithSeedChangeImpl(common, policy, new_capacity, /*force_sample_soo=*/false); - common.infoz().RecordReservation(new_size); + if (common.has_infoz()) { + ReportReserveToInfoz(common, new_size); + } } // Grows a full SOO table to the next capacity and forces it to be sampled. SOO @@ -2476,9 +2491,12 @@ ResizeTableWithSeedChangeImpl(common, policy, new_capacity, /*force_sample_soo=*/false); } - // This is after resize, to ensure that we have completed the allocation - // and have potentially sampled the hashtable. - common.infoz().RecordReservation(n); + } + // This is after resize, to ensure that we have completed the allocation and + // have potentially sampled the hashtable. Also record when `new_capacity <= + // cap` so sampled SOO tables report leaving SOO capacity. + if (common.has_infoz()) { + ReportReserveToInfoz(common, n); } } @@ -2575,6 +2593,9 @@ ? cap : common.size() + common.GetGrowthLeftTotalSlow(cap); if (new_size <= max_size_before_growth) { + if (common.has_infoz()) { + ReportReserveToInfoz(common, new_size); + } return; } ReserveAllocatedTable(common, policy, new_size);
diff --git a/absl/container/internal/raw_hash_set.h b/absl/container/internal/raw_hash_set.h index a59d09b..ae7692e 100644 --- a/absl/container/internal/raw_hash_set.h +++ b/absl/container/internal/raw_hash_set.h
@@ -378,26 +378,6 @@ template <typename AllocType> void CopyAlloc(AllocType&, AllocType&, std::false_type /* propagate_alloc */) {} -template <class ContainerKey, class Hash, class Eq> -struct RequireUsableKey { - template <class PassedKey, class... Args> - std::pair< - decltype(std::declval<const Hash&>()(std::declval<const PassedKey&>())), - decltype(std::declval<const Eq&>()(std::declval<const ContainerKey&>(), - std::declval<const PassedKey&>()))>* - operator()(const PassedKey&, const Args&...) const; -}; - -template <class E, class Policy, class Hash, class Eq, class... Ts> -struct IsDecomposable : std::false_type {}; - -template <class Policy, class Hash, class Eq, class... Ts> -struct IsDecomposable< - std::void_t<decltype(Policy::apply( - RequireUsableKey<typename Policy::key_type, Hash, Eq>(), - std::declval<Ts>()...))>, - Policy, Hash, Eq, Ts...> : std::true_type {}; - template <typename T, template <typename...> class Template> struct is_instance_of : std::false_type {}; template <template <typename...> class Template, typename... Args> @@ -1384,7 +1364,9 @@ ctrl_t* control() const { ABSL_SWISSTABLE_ASSERT(capacity() > 0); - ABSL_SWISSTABLE_IGNORE_UNINITIALIZED_RETURN(heap_or_soo_.control().get()); + ctrl_t* ctrl = heap_or_soo_.control().get(); + ABSL_SWISSTABLE_IGNORE_UNINITIALIZED(ABSL_ASSUME(ctrl != nullptr)); + ABSL_SWISSTABLE_IGNORE_UNINITIALIZED_RETURN(ctrl); } void set_control(ctrl_t* c) { heap_or_soo_.control().set(c); } @@ -1936,19 +1918,13 @@ AssertSameContainer(ctrl_, b.ctrl_, slot_, b.slot_, generation_ptr(), b.generation_ptr()); } - return unchecked_equals(b); + return slot_ == b.slot_; } - // An equality check which skips ABSL Hardening iterator invalidation - // checks. - // Should be used when the lifetimes of the iterators are well-enough - // understood to prove that they cannot be invalid. - // Note: `b` is passed by reference because `HashSetIteratorBase` has an - // anonymous union member (`ctrl_`), which causes Clang to lower by-value - // copies as `memcpy` that affects compiler inlining decisions. - ABSL_ATTRIBUTE_ALWAYS_INLINE bool unchecked_equals( - const HashSetIteratorBase& b) const { - return slot_ == b.slot_; + // Returns true if this iterator is at the end sentinel, skipping hardening + // iterator invalidation checks when iterator lifetimes are known to be valid. + ABSL_ATTRIBUTE_ALWAYS_INLINE bool unchecked_is_end() const { + return slot_ == nullptr; } ctrl_t* control() const { return ctrl_; } @@ -2318,11 +2294,15 @@ // other optimizations for tables with small keys. template <size_t kSizeOfSizeT = sizeof(size_t)> -constexpr size_t MaxSizeAtMaxValidCapacity(size_t slot_size) { +constexpr size_t MaxValidCapacity() { using SizeT = std::conditional_t<kSizeOfSizeT == 4, uint32_t, uint64_t>; // We shift right by 2 for a safe margin against overflow. - constexpr SizeT kMaxValidCapacity = ~SizeT{} >> 2; - return CapacityToGrowth(kMaxValidCapacity) / slot_size; + return ~SizeT{} >> 2; +} + +template <size_t kSizeOfSizeT = sizeof(size_t)> +constexpr size_t MaxSizeAtMaxValidCapacity(size_t slot_size) { + return CapacityToGrowth(MaxValidCapacity<kSizeOfSizeT>()) / slot_size; } constexpr size_t MaxStorableSize() { @@ -2343,8 +2323,11 @@ template <size_t kSizeOfSizeT = sizeof(size_t)> constexpr size_t MaxValidSizeForSlotSize(size_t slot_size) { if constexpr (kSizeOfSizeT == 8) { - // For small slot sizes we are limited by HashtableStackData::kSizeBitCount. - if (slot_size < size_t{1} << (64 - HashtableInlineData::kSizeBitCount)) { + // For small slot sizes we are limited by + // HashtableInlineData::kSizeBitCount. + constexpr size_t kMaxSlotSizeForMaxStorableSize = + CapacityToGrowth(MaxValidCapacity<kSizeOfSizeT>()) / MaxStorableSize(); + if (ABSL_PREDICT_TRUE(slot_size <= kMaxSlotSizeForMaxStorableSize)) { return MaxStorableSize(); } } @@ -2701,6 +2684,16 @@ // Asserts that the capacity is not a sentinel invalid value. void AssertNotDebugCapacity() const { common().AssertNotDebugCapacity(); } + ABSL_ATTRIBUTE_ALWAYS_INLINE HashSetIteratorBase + iterator_at_ptr(ctrl_t* ctrl, void* slot) ABSL_ATTRIBUTE_LIFETIME_BOUND { + return {ctrl, slot, common().generation_ptr()}; + } + ABSL_ATTRIBUTE_ALWAYS_INLINE HashSetIteratorBase iterator_base_end() + ABSL_ATTRIBUTE_LIFETIME_BOUND { + AssertNotDebugCapacity(); + return HashSetIteratorBase(common().generation_ptr()); + } + template <bool kIsDefaultAlloc> ctrl_t* control() const { ctrl_t* ctrl = common().control(); @@ -2730,6 +2723,11 @@ // the separate storage assumption in control(). return common().slot_array(control<kIsDefaultAlloc>(), capacity); } + template <size_t kSlotSize, bool kIsDefaultAlloc> + ABSL_ATTRIBUTE_ALWAYS_INLINE auto* sized_slot_array(size_t capacity) const { + using SlotBytes = char[kSlotSize]; + return static_cast<SlotBytes*>(slot_array<kIsDefaultAlloc>(capacity)); + } // Prefetch the heap-allocated memory region to resolve potential TLB and // cache misses. This is intended to overlap with execution of calculating the @@ -2742,6 +2740,12 @@ #endif } + ABSL_ATTRIBUTE_ALWAYS_INLINE static void prefetch_slot(const void* slot) { +#ifndef ABSL_HAVE_MEMORY_SANITIZER + absl::PrefetchToLocalCache(slot); +#endif + } + // Whether this table is in SOO mode or non-SOO mode. template <bool kSooEnabled> bool is_soo() const { @@ -2800,13 +2804,11 @@ } template <size_t kSlotSize, bool kIsDefaultAlloc> void erase_meta_only_large(const HashSetIteratorBase& it) { - using SlotBytes = char[kSlotSize]; const size_t cap = common().capacity(); - const auto* slot_ptr = - static_cast<const SlotBytes*>(slot_array<kIsDefaultAlloc>(cap)); + const auto* slot_ptr = sized_slot_array<kSlotSize, kIsDefaultAlloc>(cap); // `it` can be non-iterable iterator, so we can't use it.control(). - const size_t index = - static_cast<size_t>(static_cast<const SlotBytes*>(it.slot_) - slot_ptr); + const size_t index = static_cast<size_t>( + static_cast<decltype(slot_ptr)>(it.slot_) - slot_ptr); EraseMetaOnlyLarge(common(), index, kSlotSize); } @@ -2851,6 +2853,46 @@ absl::remove_cvref_t<SlotKey>>>; }; + template <class SlotKey, class Hash, size_t kHasherOffset, class K> + ABSL_ATTRIBUTE_ALWAYS_INLINE size_t hash_of(const K& key) const { + using Params = HashParams<Hash, SlotKey>; + const Hash& hash_ref = *reinterpret_cast<const Hash*>( + reinterpret_cast<const char*>(this) + kHasherOffset); + return HashElement<Hash, Params::kIsAbsl, Params::kSeedShift>{ + hash_ref, common().seed().seed()}(key); + } + + template <class Key, size_t kSlotSize, bool kIsDefaultAlloc, class Hash, + size_t kHasherOffset, class Eq, size_t kEqOffset, class SlotEq> + HashSetIteratorBase find_large(Key key) { + prefetch_heap_block<kIsDefaultAlloc>(); + const Eq& eq_ref = *reinterpret_cast<const Eq*>( + reinterpret_cast<const char*>(this) + kEqOffset); + const size_t hash = + hash_of<typename SlotEq::SlotKeyType, Hash, kHasherOffset>(key); + const size_t cap = common().capacity(); + ABSL_ASSUME(cap > kMaxSmallCapacity); + auto seq = probe(ProbeCapacity{cap}, hash); + const h2_t h2 = H2(hash); + ctrl_t* ctrl = control<kIsDefaultAlloc>(); + auto* slot_array = sized_slot_array<kSlotSize, kIsDefaultAlloc>(cap); + while (true) { + // Loading the group before slot prefetch decreases critical path latency. + Group g{ctrl + seq.offset()}; + prefetch_slot(slot_array + seq.offset()); + // Predict one iteration (common case for find-hit). + if (auto match = g.Match(h2); ABSL_PREDICT_TRUE(match)) { + do { + const size_t offset = seq.offset(*match); + if (ABSL_PREDICT_TRUE(SlotEq{}(eq_ref, slot_array + offset, key))) + return iterator_at_ptr(ctrl + offset, slot_array + offset); + } while (ABSL_PREDICT_FALSE(++match)); + } + if (ABSL_PREDICT_TRUE(g.MaskEmpty())) return iterator_base_end(); + seq.next(); + } + } + // `policy` is a runtime argument so that tables that differ only in other // policy functions share one instantiation. template <class Key, size_t kSlotSize, bool kIsDefaultAlloc, bool kSooEnabled, @@ -2859,28 +2901,20 @@ std::pair<void*, bool> find_or_prepare_insert_large( const PolicyFunctions& policy, Key key) { using SlotKeyType = typename SlotEq::SlotKeyType; - using Params = HashParams<Hash, SlotKeyType>; prefetch_heap_block<kIsDefaultAlloc>(); - const Hash& hash_ref = *reinterpret_cast<const Hash*>( - reinterpret_cast<const char*>(this) + kHasherOffset); const Eq& eq_ref = *reinterpret_cast<const Eq*>( reinterpret_cast<const char*>(this) + kEqOffset); - const size_t hash = HashElement<Hash, Params::kIsAbsl, Params::kSeedShift>{ - hash_ref, common().seed().seed()}(key); + const size_t hash = hash_of<SlotKeyType, Hash, kHasherOffset>(key); const size_t cap = capacity<sizeof(SlotKeyType), kSlotSize, kSooEnabled>(); auto seq = probe(ProbeCapacity{cap}, hash); const h2_t h2 = H2(hash); const ctrl_t* ctrl = control<kIsDefaultAlloc>(); - using SlotBytes = char[kSlotSize]; - auto* slot_array = - static_cast<SlotBytes*>(this->slot_array<kIsDefaultAlloc>(cap)); + auto* slot_array = sized_slot_array<kSlotSize, kIsDefaultAlloc>(cap); while (true) { // Loading the group before slot prefetch decreases critical path latency. Group g{ctrl + seq.offset()}; -#ifndef ABSL_HAVE_MEMORY_SANITIZER - absl::PrefetchToLocalCache(slot_array + seq.offset()); -#endif + prefetch_slot(slot_array + seq.offset()); // Predict one iteration (common case for insert-hit). if (auto match = g.Match(h2); ABSL_PREDICT_TRUE(match)) { do { @@ -2894,7 +2928,10 @@ size_t target_group_offset = seq.offset(); void* slot; if constexpr (SwisstableGenerationsEnabled()) { - using Hasher = typename Params::template HashKeyFor<Key>; + using Hasher = + typename HashParams<Hash, SlotKeyType>::template HashKeyFor<Key>; + const Hash& hash_ref = *reinterpret_cast<const Hash*>( + reinterpret_cast<const char*>(this) + kHasherOffset); Hasher hash_key{hash_ref, key}; slot = PrepareInsertLargeGenerationsEnabled( common(), policy, hash, mask_empty, target_group_offset, @@ -3136,6 +3173,8 @@ private: using Base::Base; + using Base::unchecked_is_end; + ABSL_ATTRIBUTE_ALWAYS_INLINE explicit iterator(const Base& b) : Base(b) {} // Dereferences the iterator without ABSL Hardening iterator invalidation // checks. @@ -3182,9 +3221,8 @@ } private: - ABSL_ATTRIBUTE_ALWAYS_INLINE bool unchecked_equals( - const const_iterator& b) const { - return inner_.unchecked_equals(b.inner_); + ABSL_ATTRIBUTE_ALWAYS_INLINE bool unchecked_is_end() const { + return inner_.unchecked_is_end(); } ABSL_ATTRIBUTE_ALWAYS_INLINE reference unchecked_deref() const { return inner_.unchecked_deref(); @@ -3435,8 +3473,7 @@ return it; } iterator end() ABSL_ATTRIBUTE_LIFETIME_BOUND { - AssertNotDebugCapacity(); - return iterator(common().generation_ptr()); + return iterator(iterator_base_end()); } const_iterator begin() const ABSL_ATTRIBUTE_LIFETIME_BOUND { @@ -3726,7 +3763,7 @@ template <class K = key_type> size_type erase(const_key_arg<K> key) { auto it = find(key); - if (it.unchecked_equals(end())) return 0; + if (it.unchecked_is_end()) return 0; erase(it); return 1; } @@ -3798,7 +3835,7 @@ src.template erase_meta_only_small<SooEnabled(), sizeof(slot_type)>(); return; } - for (auto it = src.begin(), e = src.end(); it != e;) { + for (auto it = src.begin(); !it.unchecked_is_end();) { auto next = std::next(it); if (insert_slot(it.slot())) src.template erase_meta_only_large<sizeof(slot_type), @@ -3829,8 +3866,7 @@ std::enable_if_t<!std::is_same_v<K, iterator>, int> = 0> node_type extract(const_key_arg<K> key) { auto it = find(key); - return it.unchecked_equals(end()) ? node_type() - : extract(const_iterator{it}); + return it.unchecked_is_end() ? node_type() : extract(const_iterator{it}); } void swap(raw_hash_set& that) noexcept( @@ -3916,25 +3952,21 @@ template <class K = key_type> bool contains(const_key_arg<K> key) const { - // Here neither the iterator returned by `find()` nor `end()` can be invalid - // outside of potential thread-safety issues. - // `find()`'s return value is constructed, used, and then destructed - // all in this context. - return !find(key).unchecked_equals(end()); + return !find(key).unchecked_is_end(); } template <class K = key_type> std::pair<iterator, iterator> equal_range(const_key_arg<K> key) ABSL_ATTRIBUTE_LIFETIME_BOUND { auto it = find(key); - if (!it.unchecked_equals(end())) return {it, std::next(it)}; + if (!it.unchecked_is_end()) return {it, std::next(it)}; return {it, it}; } template <class K = key_type> std::pair<const_iterator, const_iterator> equal_range( const_key_arg<K> key) const ABSL_ATTRIBUTE_LIFETIME_BOUND { auto it = find(key); - if (!it.unchecked_equals(end())) return {it, std::next(it)}; + if (!it.unchecked_is_end()) return {it, std::next(it)}; return {it, it}; } @@ -3951,7 +3983,7 @@ if (outer->capacity() > inner->capacity()) std::swap(outer, inner); for (const value_type& elem : *outer) { auto it = PolicyTraits::apply(FindElement{*inner}, elem); - if (unchecked_equals(it, inner->end())) return false; + if (unchecked_is_end(it)) return false; // Note: we used key_equal to check for key equality in FindElement, but // we may need to do an additional comparison using // value_type::operator==. E.g. the keys could be equal and the @@ -4058,31 +4090,11 @@ template <class K> iterator find_large(absl::type_identity_t<K> key) { static_assert(std::is_same_v<K, FindLargeKey<K>>); - prefetch_heap_block(); - const size_t hash = hash_of(key); - const size_t cap = common().capacity(); - ABSL_ASSUME(cap > kMaxSmallCapacity); - auto seq = probe(ProbeCapacity{cap}, hash); - const h2_t h2 = H2(hash); - ctrl_t* ctrl = control(); - slot_type* slot_array = this->slot_array(cap); - while (true) { - // Loading the group before slot prefetch decreases critical path latency. - Group g{ctrl + seq.offset()}; -#ifndef ABSL_HAVE_MEMORY_SANITIZER - absl::PrefetchToLocalCache(slot_array + seq.offset()); -#endif - // Predict one iteration (common case for find-hit). - if (auto match = g.Match(h2); ABSL_PREDICT_TRUE(match)) { - do { - const size_t offset = seq.offset(*match); - if (ABSL_PREDICT_TRUE(equal_to<K>(key, slot_array + offset))) - return iterator_at_ptr(ctrl + offset, slot_array + offset); - } while (ABSL_PREDICT_FALSE(++match)); - } - if (ABSL_PREDICT_TRUE(g.MaskEmpty())) return end(); - seq.next(); - } + return iterator( + raw_hash_set_base::find_large<K, sizeof(slot_type), kIsDefaultAlloc, + hasher, HasherOffset(), key_equal, + EqOffset(), + typename PolicyTraits::SlotEq>(key)); } // Returns true if the table needs to be sampled. This keeps track of whether @@ -4157,8 +4169,7 @@ } template <class K> ABSL_ATTRIBUTE_ALWAYS_INLINE size_t hash_of(const K& key) const { - return HashElement<hasher, kIsAbslHash, kSeedShift>{ - hash_ref(), common().seed().seed()}(key); + return raw_hash_set_base::hash_of<key_type, hasher, HasherOffset()>(key); } ABSL_ATTRIBUTE_ALWAYS_INLINE size_t hash_of(slot_type* slot) const { return PolicyTraits::apply( @@ -4191,18 +4202,19 @@ // aren't allowed to do so. void swap_common(raw_hash_set& that) { using std::swap; - if (PolicyTraits::transfer_uses_memcpy()) { + if constexpr (!SooEnabled() || PolicyTraits::transfer_uses_memcpy()) { swap(common(), that.common()); - return; + } else { + if (ABSL_PREDICT_FALSE(this == &that)) return; + CommonFields tmp = CommonFields(uninitialized_tag_t{}); + const bool that_is_full_soo = that.is_full_soo(); + move_common(that_is_full_soo, that.char_alloc_ref(), tmp, + std::move(that.common())); + move_common(is_full_soo(), char_alloc_ref(), that.common(), + std::move(common())); + move_common(that_is_full_soo, that.char_alloc_ref(), common(), + std::move(tmp)); } - CommonFields tmp = CommonFields(uninitialized_tag_t{}); - const bool that_is_full_soo = that.is_full_soo(); - move_common(that_is_full_soo, that.char_alloc_ref(), tmp, - std::move(that.common())); - move_common(is_full_soo(), char_alloc_ref(), that.common(), - std::move(common())); - move_common(that_is_full_soo, that.char_alloc_ref(), common(), - std::move(tmp)); } // Only references `GetPolicyFunctions()` when generations are enabled, so @@ -4216,10 +4228,15 @@ template <bool propagate_alloc> raw_hash_set& assign_impl(raw_hash_set&& that) { - // We don't bother checking for this/that aliasing. We just need to avoid - // breaking the invariants in that case. + // We don't bother checking for this/that aliasing unless move_common() + // could transfer the inline SOO slot that destructor_impl() just destroyed. + // Otherwise, we just need to avoid breaking the invariants in that case. destructor_impl(); - move_common(that.is_full_soo(), that.char_alloc_ref(), common(), + bool that_is_full_soo = that.is_full_soo(); + if constexpr (SooEnabled() && !PolicyTraits::transfer_uses_memcpy()) { + that_is_full_soo = that_is_full_soo && ABSL_PREDICT_TRUE(this != &that); + } + move_common(that_is_full_soo, that.char_alloc_ref(), common(), std::move(that.common())); hash_ref() = that.hash_ref(); eq_ref() = that.eq_ref(); @@ -4234,7 +4251,7 @@ const size_t size = that.size(); if (size == 0) return *this; reserve(size); - for (iterator it = that.begin(); it != that.end(); ++it) { + for (iterator it = that.begin(); !it.unchecked_is_end(); ++it) { insert(std::move(PolicyTraits::element(it.slot()))); that.destroy(it.slot()); } @@ -4390,8 +4407,10 @@ absl::type_identity_t<K> key) { static_assert(std::is_same_v<K, KeyParam<K>>); AssertOnFind<K>(key); - return is_small() ? find_or_prepare_insert_small<K>(key) - : find_or_prepare_insert_large<FindLargeKey<K>>(key); + if (is_small()) return find_or_prepare_insert_small<K>(key); + auto res = find_or_prepare_insert_large<FindLargeKey<K>>(key); + ABSL_ASSUME(res.first != nullptr); + return res; } // Constructs the value in the space pointed by the iterator. This only works @@ -4433,10 +4452,6 @@ } return {InsertIteratorControl(), slot, common().generation_ptr()}; } - iterator iterator_at_ptr(ctrl_t* ctrl, void* slot) - ABSL_ATTRIBUTE_LIFETIME_BOUND { - return {ctrl, slot, common().generation_ptr()}; - } // For use in raw_hash_map and friend functions. ABSL_ATTRIBUTE_ALWAYS_INLINE static decltype(auto) unchecked_deref( @@ -4448,8 +4463,8 @@ return it.unchecked_deref(); } template <class Iter> - ABSL_ATTRIBUTE_ALWAYS_INLINE static bool unchecked_equals(Iter a, Iter b) { - return a.unchecked_equals(b); + ABSL_ATTRIBUTE_ALWAYS_INLINE static bool unchecked_is_end(const Iter& it) { + return it.unchecked_is_end(); } private: @@ -4821,7 +4836,7 @@ if (per_slot != ~size_t{}) { m += per_slot * c.size(); } else { - for (auto it = c.begin(); it != c.end(); ++it) { + for (auto it = c.begin(); !it.unchecked_is_end(); ++it) { m += Traits::space_used(it.slot()); } }
diff --git a/absl/container/internal/raw_hash_set_test.cc b/absl/container/internal/raw_hash_set_test.cc index a62adf5..970420e 100644 --- a/absl/container/internal/raw_hash_set_test.cc +++ b/absl/container/internal/raw_hash_set_test.cc
@@ -97,6 +97,16 @@ } }; +#if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE) +class HashtablezInfoHandlePeer { + public: + template <typename C> + static const HashtablezInfo* GetInfo(C& c) { + return RawHashSetTestOnlyAccess::GetCommon(c).infoz().info_; + } +}; +#endif // defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE) + namespace { using ::testing::ElementsAre; @@ -2928,6 +2938,10 @@ return *this; } + friend bool operator==(const DecomposeType& a, const DecomposeType& b) { + return a.i == b.i; + } + template <typename H> friend H AbslHashValue(H h, const DecomposeType& d) { return H::combine(std::move(h), d.i); @@ -2987,9 +3001,6 @@ const int one = 1; const char* three_p = "3"; const auto& three = three_p; - const int elem_vector_count = 256; - std::vector<DecomposeType> elem_vector(elem_vector_count, DecomposeType{0}); - std::iota(elem_vector.begin(), elem_vector.end(), 0); using DecomposeSet = raw_hash_set<DecomposePolicy, Hash, Eq, std::allocator<int>>; @@ -3004,25 +3015,28 @@ EXPECT_EQ(++expected_constructed, decompose_constructed); set1.emplace("3"); EXPECT_EQ(++expected_constructed, decompose_constructed); - EXPECT_EQ(expected_constructed, decompose_constructed); - { // insert(T&&) + { // insert(T&&) / insert(const T&) / insert(hint, ...) set1.insert(1); EXPECT_EQ(expected_constructed, decompose_constructed); - } - - { // insert(const T&) set1.insert(one); EXPECT_EQ(expected_constructed, decompose_constructed); - } - - { // insert(hint, T&&) set1.insert(set1.begin(), 1); EXPECT_EQ(expected_constructed, decompose_constructed); + set1.insert(set1.begin(), one); + EXPECT_EQ(expected_constructed, decompose_constructed); } - { // insert(hint, const T&) - set1.insert(set1.begin(), one); + { // insert(const init_type&) via derived type and reference_wrapper + struct DerivedDecomposeType : DecomposeType { + using DecomposeType::DecomposeType; + }; + const DerivedDecomposeType derived(0); + ++expected_constructed; + EXPECT_FALSE(set1.insert(derived).second); + EXPECT_EQ(set1.insert(set1.begin(), derived)->i, 0); + EXPECT_FALSE(set1.insert(std::cref(elem)).second); + EXPECT_NE(set1.find(derived), set1.end()); EXPECT_EQ(expected_constructed, decompose_constructed); } @@ -3051,6 +3065,16 @@ expected_constructed += construct_three; EXPECT_EQ(expected_constructed, decompose_constructed); } +} + +template <typename Hash, typename Eq> +void TestDecomposeRangeInsert() { + const int elem_vector_count = 256; + std::vector<DecomposeType> elem_vector(elem_vector_count, DecomposeType{0}); + std::iota(elem_vector.begin(), elem_vector.end(), 0); + + using DecomposeSet = + raw_hash_set<DecomposePolicy, Hash, Eq, std::allocator<int>>; decompose_copy_constructed = 0; decompose_copy_assigned = 0; @@ -3083,8 +3107,6 @@ EXPECT_GE(expected_move_constructed, decompose_move_constructed); EXPECT_EQ(0, decompose_move_assigned); EXPECT_EQ(0, decompose_copy_assigned); - expected_copy_constructed = decompose_copy_constructed; - expected_move_constructed = decompose_move_constructed; } { // insert(first, last) @@ -3100,28 +3122,25 @@ EXPECT_GE(expected_move_constructed, decompose_move_constructed); EXPECT_EQ(0, decompose_move_assigned); EXPECT_EQ(0, decompose_copy_assigned); - expected_copy_constructed = decompose_copy_constructed; - expected_move_constructed = decompose_move_constructed; } } -TEST(Table, Decompose) { - if (SwisstableGenerationsEnabled()) { - GTEST_SKIP() << "Generations being enabled causes extra rehashes."; +struct TransparentHashIntOverload { + size_t operator()(const DecomposeType& a) const { + return static_cast<size_t>(a.i); } + size_t operator()(int a) const { return static_cast<size_t>(a); } +}; +struct TransparentEqIntOverload { + bool operator()(const DecomposeType& a, const DecomposeType& b) const { + return a.i == b.i; + } + bool operator()(const DecomposeType& a, int b) const { return a.i == b; } +}; + +TEST(Table, Decompose) { TestDecompose<DecomposeHash, DecomposeEq>(false); - - struct TransparentHashIntOverload { - size_t operator()(const DecomposeType& a) const { return a.i; } - size_t operator()(int a) const { return a; } - }; - struct TransparentEqIntOverload { - bool operator()(const DecomposeType& a, const DecomposeType& b) const { - return a.i == b.i; - } - bool operator()(const DecomposeType& a, int b) const { return a.i == b; } - }; TestDecompose<TransparentHashIntOverload, DecomposeEq>(true); TestDecompose<TransparentHashIntOverload, TransparentEqIntOverload>(true); TestDecompose<DecomposeHash, TransparentEqIntOverload>(true); @@ -3129,6 +3148,125 @@ TransparentEqIntOverload>(true); } +template <typename Hash, typename Eq> +void TestDecomposeNonTransparent() { + using Set = raw_hash_set<DecomposePolicy, Hash, Eq, std::allocator<int>>; + Set set; + set.insert(DecomposeType{0}); + set.insert(DecomposeType{2}); + + decompose_constructed = 0; + // Miss converts for lookup and constructs once in the slot. + set.insert(1); + EXPECT_GE(decompose_constructed, 2); + + const int one = 1; + // TODO(b/413633804): Tighten to EXPECT_EQ(..., 1) once EmplaceDecomposable + // converts non-transparent keys at the lookup boundary. + auto check_hit = [&](absl::FunctionRef<void(Set&, int)> fn) { + decompose_constructed = 0; + fn(set, one); + EXPECT_GE(decompose_constructed, 1); + }; + check_hit([](Set& s, int) { s.insert(1); }); + check_hit([](Set& s, int v) { s.insert(v); }); + check_hit([](Set& s, int) { s.insert(s.begin(), 1); }); + check_hit([](Set& s, int v) { s.insert(s.begin(), v); }); + check_hit([](Set& s, int) { s.emplace(1); }); + check_hit([](Set& s, int v) { s.emplace(v); }); + check_hit([](Set& s, int) { s.emplace_hint(s.begin(), 1); }); + check_hit([](Set& s, int v) { s.emplace_hint(s.begin(), v); }); +} + +TEST(Table, DecomposeNonTransparentSingleConversion) { + struct NonTransparentHash { + size_t operator()(const DecomposeType& a) const { + // Force collisions so per-probe key conversions would increase the + // construction count. + return static_cast<size_t>(a.i) % 2; + } + }; + struct NonTransparentEq { + bool operator()(const DecomposeType& a, const DecomposeType& b) const { + return a.i == b.i; + } + }; + TestDecomposeNonTransparent<NonTransparentHash, DecomposeEq>(); + TestDecomposeNonTransparent<NonTransparentHash, NonTransparentEq>(); + TestDecomposeNonTransparent<DecomposeHash, NonTransparentEq>(); +} + +TEST(Table, EmplaceHeterogeneousKeyHitDoesNotMoveValue) { + absl::flat_hash_map<int64_t, std::unique_ptr<int>> m; + m.emplace(int64_t{1}, std::make_unique<int>(42)); + auto p = std::make_unique<int>(99); + EXPECT_FALSE(m.emplace(1, std::move(p)).second); + EXPECT_NE(p, nullptr); + EXPECT_EQ(*m[1], 42); +} + +TEST(Table, DecomposeRangeInsert) { + if (SwisstableGenerationsEnabled()) { + GTEST_SKIP() << "Generations being enabled causes extra rehashes."; + } + + TestDecomposeRangeInsert<DecomposeHash, DecomposeEq>(); + TestDecomposeRangeInsert<TransparentHashIntOverload, DecomposeEq>(); + TestDecomposeRangeInsert<TransparentHashIntOverload, + TransparentEqIntOverload>(); + TestDecomposeRangeInsert<DecomposeHash, TransparentEqIntOverload>(); + TestDecomposeRangeInsert<absl::TransparentHash<DecomposeType, int>, + TransparentEqIntOverload>(); +} + +TEST(Table, DerivedKeyMap) { + struct DerivedDecomposeType : DecomposeType { + using DecomposeType::DecomposeType; + }; + const DerivedDecomposeType d(2); + absl::flat_hash_map<DecomposeType, int> map; + std::pair<DerivedDecomposeType, int> p(DerivedDecomposeType(10), 100); + EXPECT_TRUE(map.insert(p).second); + EXPECT_TRUE(map.insert({d, 200}).second); + EXPECT_FALSE(map.try_emplace(d, 300).second); + EXPECT_EQ(map.find(d)->second, 200); + EXPECT_EQ(map[d], 200); +} + +TEST(Table, DerivedKeyTrivialSet) { + struct TrivialBase { + int v; + }; + struct TrivialDerived : TrivialBase {}; + struct TrivialHash { + size_t operator()(TrivialBase k) const { return static_cast<size_t>(k.v); } + }; + struct TrivialEq { + bool operator()(TrivialBase a, TrivialBase b) const { return a.v == b.v; } + }; + absl::flat_hash_set<TrivialBase, TrivialHash, TrivialEq> set; + const TrivialDerived td{{7}}; + EXPECT_TRUE(set.insert(td).second); + EXPECT_EQ(set.insert(set.begin(), td)->v, 7); +} + +struct TemplatedConversionProxy { + int v; + template <typename T> + operator T() const { // NOLINT(google-explicit-constructor) + static_assert(std::is_same_v<T, int>); + return T(v); + } +}; + +TEST(Table, InsertTemplatedConversionOperator) { + absl::flat_hash_set<int> set; + const TemplatedConversionProxy p{42}; + EXPECT_TRUE(set.insert(p).second); + EXPECT_EQ(*set.insert(set.begin(), TemplatedConversionProxy{42}), 42); + EXPECT_THAT(set, ElementsAre(42)); +} + struct Modulo1000Hash { size_t operator()(int64_t x) const { return static_cast<size_t>(x) % 1000; } }; @@ -4282,10 +4420,11 @@ ASSERT_EQ(info->inline_element_size, sizeof(typename SooInt32Table::value_type)); ASSERT_EQ(info->soo_capacity, SooCapacity()); - ASSERT_EQ(info->capacity, NextCapacity(SooCapacity())); + ASSERT_EQ(info->capacity, SooCapacity()); ASSERT_EQ(info->size, 1); ASSERT_EQ(info->max_reserve, 0); ASSERT_EQ(info->num_erases, 0); + ASSERT_EQ(info->num_rehashes, 0); ASSERT_EQ(info->max_probe_length, 0); ASSERT_EQ(info->total_probe_length, 0); } @@ -4323,6 +4462,11 @@ t.erase(1); } }); + for (const HashtablezInfo* info : infos) { + EXPECT_EQ(info->soo_capacity, SooCapacity()); + ASSERT_EQ(info->capacity, SooCapacity()); + ASSERT_EQ(info->size, 0); + } // SampleSooMutation checks EXPECT_NEAR(sampled/total, 1%, 0.5%). // If the sampling logic is incorrectly evaluated on every 0->1 element @@ -4416,7 +4560,8 @@ ASSERT_EQ(info->inline_element_size, sizeof(typename SooInt32Table::value_type)); ASSERT_EQ(info->soo_capacity, SooCapacity()); - ASSERT_GE(info->capacity, 100); + ASSERT_EQ(info->capacity, + SizeToCapacity(100) - kMaxBlockedElementsForLargeTables); ASSERT_EQ(info->size, 0); ASSERT_EQ(info->max_reserve, 100); ASSERT_EQ(info->num_erases, 0); @@ -4467,8 +4612,9 @@ ASSERT_EQ(info->inline_element_size, sizeof(typename SooInt32Table::value_type)); ASSERT_EQ(info->soo_capacity, SooCapacity()); - ASSERT_EQ(info->capacity, NextCapacity(SooCapacity())); + ASSERT_EQ(info->capacity, SooCapacity()); ASSERT_EQ(info->size, 1); + ASSERT_EQ(info->num_rehashes, 0); } } @@ -4570,6 +4716,135 @@ EXPECT_EQ(final_size, start_size + 1); ASSERT_NE(latest_info, nullptr); EXPECT_EQ(latest_info->size.load(std::memory_order_relaxed), 2); + EXPECT_EQ(latest_info->capacity.load(std::memory_order_relaxed), + NextCapacity(SooCapacity())); +} + +struct SampleEveryTable { + SampleEveryTable() { + SetHashtablezEnabled(true); + SetHashtablezSampleParameter(1); + TestOnlyRefreshSamplingStateForCurrentThread(); + } + ~SampleEveryTable() { DisableSampling(); } +}; + +class RawHashSooSamplerTest : public testing::Test { + protected: + void SetUp() override { + if (SooInt32Table().capacity() != SooCapacity()) { + CHECK_LT(sizeof(void*), 8) << "missing SOO coverage"; + GTEST_SKIP() << "not SOO on this platform"; + } + } + + SampleEveryTable sample_all_; +}; + +TEST_F(RawHashSooSamplerTest, StaysSooCapacityWithoutGrowthOrReserve) { + SooInt32Table t; + t.insert(1); + const HashtablezInfo* info = HashtablezInfoHandlePeer::GetInfo(t); + ASSERT_NE(info, nullptr); + EXPECT_EQ(info->capacity, SooCapacity()); + + auto expect_stays_soo = [&](auto op) { + op(); + EXPECT_EQ(info->capacity, SooCapacity()); + }; + + // These operations don't change reported capacity to non-SOO. + expect_stays_soo([&] { t.erase(t.begin(), t.end()); }); + EXPECT_EQ(info->size, 0); + expect_stays_soo([&] { t.insert(2); }); + expect_stays_soo([&] { t.rehash(0); }); + expect_stays_soo([&] { t.rehash(1); }); + expect_stays_soo([&] { t.reserve(1); }); + std::optional<SooInt32Table> moved; + expect_stays_soo([&] { moved.emplace(std::move(t)); }); + EXPECT_EQ(info->size, 1); + EXPECT_EQ(info->max_reserve, 0); + EXPECT_EQ(info->num_rehashes, 0); +} + +TEST_F(RawHashSooSamplerTest, LeavesSooCapacityOnGrowth) { + SooInt32Table t; + t.insert(1); + const HashtablezInfo* info = HashtablezInfoHandlePeer::GetInfo(t); + ASSERT_NE(info, nullptr); + EXPECT_EQ(info->capacity, SooCapacity()); + + // Growing to 2 elements transitions reported capacity to 3, and subsequent + // erases or rehash(0) keep capacity 3 because the table was resized. + t.insert(2); + EXPECT_EQ(info->capacity, NextCapacity(SooCapacity())); + EXPECT_EQ(info->size, 2); + EXPECT_EQ(info->num_rehashes, 1); + + t.erase(2); + t.rehash(0); + EXPECT_EQ(info->capacity, NextCapacity(SooCapacity())); + EXPECT_EQ(info->size, 1); + + t.erase(t.begin(), t.end()); + EXPECT_EQ(info->capacity, NextCapacity(SooCapacity())); + EXPECT_EQ(info->size, 0); +} + +TEST_F(RawHashSooSamplerTest, LeavesSooCapacityOnReserveOrRehash) { + // Reserving or rehashing for >1 capacity on a size-1 sampled SOO table + // transitions reported capacity out of SOO even when heap capacity is 3. + for (bool use_rehash : {false, true}) { + SooInt32Table s; + s.insert(1); + use_rehash ? s.rehash(2) : s.reserve(2); + const HashtablezInfo* s_info = HashtablezInfoHandlePeer::GetInfo(s); + ASSERT_NE(s_info, nullptr); + EXPECT_EQ(s_info->capacity, NextCapacity(SooCapacity())); + EXPECT_EQ(s_info->max_reserve, 2); + EXPECT_EQ(s_info->num_rehashes, 1); + } + + SooInt32Table reserved_three; + reserved_three.reserve(3); + const HashtablezInfo* r3_info = + HashtablezInfoHandlePeer::GetInfo(reserved_three); + ASSERT_NE(r3_info, nullptr); + EXPECT_EQ(r3_info->capacity, NextCapacity(SooCapacity())); + EXPECT_EQ(r3_info->max_reserve, 3); + EXPECT_EQ(r3_info->num_rehashes, 1); +} + +TYPED_TEST(RawHashSamplerTest, ReportsCapacityMinusBlockedElements) { + SampleEveryTable sample_all; + + TypeParam t; + t.reserve(2); + const HashtablezInfo* info = HashtablezInfoHandlePeer::GetInfo(t); + ASSERT_NE(info, nullptr); + // SizeToCapacity(2) == 3 with 1 blocked element, so allocated slots == 2. + EXPECT_EQ(info->capacity, 2); + + t.insert({1, 2}); + EXPECT_EQ(info->capacity, 2); + EXPECT_EQ(info->size, 2); + + t.erase(t.begin(), t.end()); + EXPECT_EQ(info->capacity, 2); + EXPECT_EQ(info->size, 0); + + // Growing past reserved size clears blocked elements. + t.insert({1, 2, 3}); + EXPECT_EQ(info->capacity, 7); + EXPECT_EQ(info->size, 3); + + // Copy-constructing a 2-element table reserves exact size 2 (3 - 1 blocked). + TypeParam src = {10, 20}; + TypeParam copy(src); + const HashtablezInfo* copy_info = HashtablezInfoHandlePeer::GetInfo(copy); + ASSERT_NE(copy_info, nullptr); + EXPECT_EQ(copy_info->capacity, 2); + EXPECT_EQ(copy_info->size, 2); } #endif // ABSL_INTERNAL_HASHTABLEZ_SAMPLE @@ -4643,6 +4918,17 @@ t.erase(0); EXPECT_TRUE(__asan_address_is_poisoned(&v)); } + +TEST(Sanitizer, PoisoningOnClear) { + NonSooIntTable t; + auto& v = *t.insert(0).first; + ASSERT_EQ(t.capacity(), 1); + + EXPECT_FALSE(__asan_address_is_poisoned(&v)); + t.clear(); + ASSERT_EQ(t.capacity(), 1); + EXPECT_TRUE(__asan_address_is_poisoned(&v)); +} #endif // ABSL_HAVE_ADDRESS_SANITIZER template <typename T> @@ -4694,6 +4980,44 @@ } } +TEST(Iterator, InvalidUseAfterClearSmallNonSooCrashesWithSanitizers) { + if (!SwisstableGenerationsEnabled()) GTEST_SKIP() << "Generations disabled."; + + NonSooIntTable t; + t.insert(1); + ASSERT_EQ(t.capacity(), 1); + auto it = t.begin(); + t.clear(); + EXPECT_DEATH_IF_SUPPORTED(*it, InvalidIteratorMatcher()); + EXPECT_DEATH_IF_SUPPORTED(void(it == t.begin()), InvalidIteratorMatcher()); +} + +TEST(Iterator, InvalidUseAfterEraseAndInsertSmallNonSooCrashesWithSanitizers) { + if (!SwisstableGenerationsEnabled()) GTEST_SKIP() << "Generations disabled."; + + NonSooIntTable t; + t.insert(1); + ASSERT_EQ(t.capacity(), 1); + auto it = t.begin(); + t.erase(it); + t.insert(2); + ASSERT_EQ(t.capacity(), 1); + EXPECT_DEATH_IF_SUPPORTED(*it, InvalidIteratorMatcher()); + EXPECT_DEATH_IF_SUPPORTED(void(it == t.begin()), InvalidIteratorMatcher()); + + // Verify that reserved 1-element insertion and post-increment erase keep + // end() valid. + NonSooIntTable reserved; + reserved.reserve(1); + auto end_it = reserved.end(); + reserved.insert(10); + EXPECT_NE(reserved.begin(), end_it); + for (auto cur = reserved.begin(); cur != end_it;) { + reserved.erase(cur++); + } + EXPECT_EQ(reserved.begin(), end_it); +} + TEST(Iterator, InvalidUseWithReserveCrashesWithSanitizers) { if (!SwisstableGenerationsEnabled()) GTEST_SKIP() << "Generations disabled."; @@ -4807,6 +5131,49 @@ EXPECT_EQ(tracker.live_instances(), 0); } +TYPED_TEST(InstanceTrackerTest, SelfMoveAssignAndSelfSwap) { + static_assert(sizeof(void*) < 8 || + FitsInSooSlot(sizeof(CopyableMovableInstance), + alignof(CopyableMovableInstance)), + "missing SOO coverage on 64-bit"); + if (!FitsInSooSlot(sizeof(CopyableMovableInstance), + alignof(CopyableMovableInstance))) { + GTEST_SKIP() << "CopyableMovableInstance does not fit in SOO slot"; + } + using Table = TypeParam; + static_assert( + !absl::is_trivially_relocatable<CopyableMovableInstance>::value); + + InstanceTracker tracker; + for (int size : {0, 1, 10}) { + SCOPED_TRACE(size); + Table t; + for (int i = 0; i < size; ++i) t.emplace(i); + + tracker.ResetCopiesMovesSwaps(); + t.swap(t); + using std::swap; + swap(t, t); + EXPECT_EQ(tracker.copies(), 0); + EXPECT_EQ(tracker.moves(), 0); + EXPECT_EQ(tracker.instances(), size); + EXPECT_EQ(tracker.live_instances(), size); + EXPECT_EQ(t.size(), size); + + tracker.ResetCopiesMovesSwaps(); + t = std::move(*&t); + EXPECT_EQ(tracker.copies(), 0); + EXPECT_EQ(tracker.moves(), 0); + EXPECT_EQ(tracker.instances(), 0); + EXPECT_EQ(tracker.live_instances(), 0); + if (SwisstableGenerationsEnabled()) { + // NOLINTNEXTLINE(bugprone-use-after-move) + EXPECT_DEATH_IF_SUPPORTED(t.contains(CopyableMovableInstance(0)), + "self-move-assigned"); + } + } +} + TEST(Table, EraseBeginEndResetsReservedGrowth) { bool frozen = false; BadHashFreezableIntTable t{FreezableAlloc<int64_t>(&frozen)}; @@ -5373,6 +5740,7 @@ size_t key_size = slot_size; size_t max_size = MaxValidSize(key_size, slot_size); ASSERT_LT(max_size, uint64_t{1} << 60); + size_t max_capacity = SizeToCapacity(max_size); if (key_size <= 4) { ASSERT_EQ(max_size, uint64_t{1} << 8 * key_size); } else if (i <= 21) { @@ -5380,9 +5748,23 @@ ASSERT_GE(max_size, (uint64_t{1} << HashtableInlineData::kSizeBitCount) - 1); } + ASSERT_LE(max_size, MaxSizeAtMaxValidCapacity(slot_size)); ASSERT_LE(max_size, uint64_t{1} << HashtableInlineData::kSizeBitCount); ASSERT_LT(absl::uint128(max_size) * slot_size, uint64_t{1} << 63); + ASSERT_LT(absl::uint128(max_capacity) * slot_size, uint64_t{1} << 63); + if (max_capacity > 0) { + RawHashSetLayout layout(max_capacity, slot_size, /*slot_align_mask=*/0, + /*has_infoz=*/true, + /*blocked_element_count=*/0); + ASSERT_GT(layout.alloc_size(), layout.slot_offset()); + } } + constexpr size_t kThresholdSlotSize = + CapacityToGrowth(MaxValidCapacity()) / MaxStorableSize(); + EXPECT_EQ(MaxValidSize(kThresholdSlotSize, kThresholdSlotSize), + MaxStorableSize()); + EXPECT_LT(MaxValidSize(kThresholdSlotSize + 1, kThresholdSlotSize + 1), + MaxStorableSize()); } EXPECT_LT(MaxValidSize</*kSizeOfSizeT=*/4>(1, 1), 1 << 30); EXPECT_LT(MaxValidSize</*kSizeOfSizeT=*/4>(2, 2), 1 << 29);
diff --git a/absl/crc/internal/crc32_x86_arm_combined_simd.h b/absl/crc/internal/crc32_x86_arm_combined_simd.h index 3615c36..dc9d441 100644 --- a/absl/crc/internal/crc32_x86_arm_combined_simd.h +++ b/absl/crc/internal/crc32_x86_arm_combined_simd.h
@@ -49,10 +49,21 @@ #include <intrin.h> #define ABSL_CRC_INTERNAL_HAVE_X86_SIMD -#elif defined(__aarch64__) && defined(__LITTLE_ENDIAN__) && \ - defined(__ARM_FEATURE_CRC32) && defined(ABSL_INTERNAL_HAVE_ARM_NEON) && \ - defined(__ARM_FEATURE_CRYPTO) +#elif defined(__aarch64__) && defined(__LITTLE_ENDIAN__) && \ + defined(ABSL_INTERNAL_HAVE_ARM_NEON) && \ + ((defined(__ARM_FEATURE_CRC32) && defined(__ARM_FEATURE_CRYPTO)) || \ + defined(__clang__) || defined(__GNUC__)) +// Enable ARM64 CRC32 + PMULL when either: +// 1. Both extensions are enabled by the compiler target +// (-march=...+crc+crypto), providing standard ACLE intrinsics +// (__crc32c*, vmull_p64), or +// 2. Building with Clang or GCC, where GNU inline assembly with +// .arch_extension directives can emit CRC32 and PMULL instructions on +// baseline -march=armv8-a targets (e.g., Android, Windows clang-cl, and +// default open-source Linux builds) for runtime dispatch via +// SupportsArmCRC32PMULL(). Visual C++ (MSVC) does not support GNU inline +// assembly on ARM64. #include <arm_acle.h> #include <arm_neon.h> #define ABSL_CRC_INTERNAL_HAVE_ARM_SIMD @@ -75,6 +86,16 @@ #define ABSL_INTERNAL_ATTRIBUTE_AVX #endif +#if defined(ABSL_CRC_INTERNAL_HAVE_X86_SIMD) && \ + (defined(__AVX__) || defined(ABSL_INTERNAL_CAN_FORCE_AVX)) +#define ABSL_CRC_INTERNAL_HAVE_X86_V256 1 +#endif + +#if defined(ABSL_CRC_INTERNAL_HAVE_X86_V256) && \ + (!defined(_MSC_VER) || defined(__clang__)) +#define ABSL_CRC_INTERNAL_HAVE_VPCLMUL 1 +#endif + namespace absl { ABSL_NAMESPACE_BEGIN namespace crc_internal { @@ -100,8 +121,7 @@ using V128 = std::array<uint64_t, 2>; #endif -#if (defined(__AVX__) || defined(ABSL_INTERNAL_CAN_FORCE_AVX)) && \ - defined(ABSL_CRC_INTERNAL_HAVE_X86_SIMD) +#if defined(ABSL_CRC_INTERNAL_HAVE_X86_V256) using V256 = __m256i; #else // Placeholder for V256 when AVX is not available. @@ -178,8 +198,7 @@ // DebugReportNonTemporalStore() and DebugReportStoreFence() in crc.h. void NonTemporalStoreFence(); -#if (defined(__AVX__) || defined(ABSL_INTERNAL_CAN_FORCE_AVX)) && \ - defined(ABSL_CRC_INTERNAL_HAVE_X86_SIMD) +#if defined(ABSL_CRC_INTERNAL_HAVE_X86_V256) ABSL_INTERNAL_ATTRIBUTE_AVX inline V256 V256_LoadU(const void* src); ABSL_INTERNAL_ATTRIBUTE_AVX inline V256 V256_Broadcast128(const V128* src); ABSL_INTERNAL_ATTRIBUTE_AVX inline void V256_StoreU(void* dst, V256 data); @@ -279,6 +298,7 @@ } #elif defined(ABSL_CRC_INTERNAL_HAVE_ARM_SIMD) +#ifdef __ARM_FEATURE_CRC32 inline uint32_t CRC32_u8(uint32_t crc, uint8_t v) { return __crc32cb(crc, v); } inline uint32_t CRC32_u16(uint32_t crc, uint16_t v) { @@ -292,6 +312,51 @@ inline uint32_t CRC32_u64(uint32_t crc, uint64_t v) { return __crc32cd(crc, v); } +#else +inline uint32_t CRC32_u8(uint32_t crc, uint8_t v) { + uint32_t res; + __asm__( + ".arch_extension crc \n\t" + "crc32cb %w0, %w1, %w2 \n\t" + ".arch_extension nocrc \n\t" + : "=r"(res) + : "r"(crc), "r"(static_cast<uint32_t>(v))); + return res; +} + +inline uint32_t CRC32_u16(uint32_t crc, uint16_t v) { + uint32_t res; + __asm__( + ".arch_extension crc \n\t" + "crc32ch %w0, %w1, %w2 \n\t" + ".arch_extension nocrc \n\t" + : "=r"(res) + : "r"(crc), "r"(static_cast<uint32_t>(v))); + return res; +} + +inline uint32_t CRC32_u32(uint32_t crc, uint32_t v) { + uint32_t res; + __asm__( + ".arch_extension crc \n\t" + "crc32cw %w0, %w1, %w2 \n\t" + ".arch_extension nocrc \n\t" + : "=r"(res) + : "r"(crc), "r"(v)); + return res; +} + +inline uint32_t CRC32_u64(uint32_t crc, uint64_t v) { + uint32_t res; + __asm__( + ".arch_extension crc \n\t" + "crc32cx %w0, %w1, %2 \n\t" + ".arch_extension nocrc \n\t" + : "=r"(res) + : "r"(crc), "r"(v)); + return res; +} +#endif inline V128 V128_Load(const V128* src) { return vld1q_u64(reinterpret_cast<const uint64_t*>(src)); @@ -311,9 +376,16 @@ // using intrinsics instead of inline assembly. inline V128 V128_PMulHi(const V128 l, const V128 r) { uint64x2_t res; - __asm__ __volatile__("pmull2 %0.1q, %1.2d, %2.2d \n\t" - : "=w"(res) - : "w"(l), "w"(r)); + __asm__ __volatile__( +#ifndef __ARM_FEATURE_CRYPTO + ".arch_extension crypto \n\t" +#endif + "pmull2 %0.1q, %1.2d, %2.2d \n\t" +#ifndef __ARM_FEATURE_CRYPTO + ".arch_extension nocrypto \n\t" +#endif + : "=w"(res) + : "w"(l), "w"(r)); return res; } @@ -321,22 +393,37 @@ // loop multiplicands from GPR to Neon registers every loop iteration. inline V128 V128_PMulLow(const V128 l, const V128 r) { uint64x2_t res; - __asm__ __volatile__("pmull %0.1q, %1.1d, %2.1d \n\t" - : "=w"(res) - : "w"(l), "w"(r)); + __asm__ __volatile__( +#ifndef __ARM_FEATURE_CRYPTO + ".arch_extension crypto \n\t" +#endif + "pmull %0.1q, %1.1d, %2.1d \n\t" +#ifndef __ARM_FEATURE_CRYPTO + ".arch_extension nocrypto \n\t" +#endif + : "=w"(res) + : "w"(l), "w"(r)); return res; } inline V128 V128_PMul01(const V128 l, const V128 r) { +#ifdef __ARM_FEATURE_CRYPTO return reinterpret_cast<V128>(vmull_p64( reinterpret_cast<poly64_t>(vget_high_p64(vreinterpretq_p64_u64(l))), reinterpret_cast<poly64_t>(vget_low_p64(vreinterpretq_p64_u64(r))))); +#else + return V128_PMulLow(vextq_u64(l, l, 1), r); +#endif } inline V128 V128_PMul10(const V128 l, const V128 r) { +#ifdef __ARM_FEATURE_CRYPTO return reinterpret_cast<V128>(vmull_p64( reinterpret_cast<poly64_t>(vget_low_p64(vreinterpretq_p64_u64(l))), reinterpret_cast<poly64_t>(vget_high_p64(vreinterpretq_p64_u64(r))))); +#else + return V128_PMulLow(l, vextq_u64(r, r, 1)); +#endif } inline V128 V128_Xor(const V128 l, const V128 r) { return veorq_u64(l, r); } @@ -394,8 +481,7 @@ DebugReportStoreFence(); } -#if (defined(__AVX__) || defined(ABSL_INTERNAL_CAN_FORCE_AVX)) && \ - defined(ABSL_CRC_INTERNAL_HAVE_X86_SIMD) +#if defined(ABSL_CRC_INTERNAL_HAVE_X86_V256) ABSL_INTERNAL_ATTRIBUTE_AVX inline V256 V256_LoadU(const void* src) { return _mm256_loadu_si256(reinterpret_cast<const __m256i*>(src)); } @@ -441,8 +527,7 @@ std::memcpy(dst, &data, sizeof(T)); DebugReportNonTemporalStore(); } -#endif // (defined(__AVX__) || defined(ABSL_INTERNAL_CAN_FORCE_AVX)) && - // defined(ABSL_CRC_INTERNAL_HAVE_X86_SIMD) +#endif // defined(ABSL_CRC_INTERNAL_HAVE_X86_V256) ABSL_INTERNAL_ATTRIBUTE_AVX inline void V256_LoadPairU(const void* src, V256* v0, V256* v1) {
diff --git a/absl/crc/internal/crc32c_inline.h b/absl/crc/internal/crc32c_inline.h index e117c86..1792b4b 100644 --- a/absl/crc/internal/crc32c_inline.h +++ b/absl/crc/internal/crc32c_inline.h
@@ -19,6 +19,7 @@ #include <cstdint> #include "absl/base/config.h" +#include "absl/base/internal/cpu_detect.h" #include "absl/base/internal/endian.h" #include "absl/crc/internal/crc32_x86_arm_combined_simd.h" @@ -32,6 +33,11 @@ inline bool ExtendCrc32cInline(uint32_t* crc, const char* p, size_t n) { #if defined(ABSL_CRC_INTERNAL_HAVE_ARM_SIMD) || \ defined(ABSL_CRC_INTERNAL_HAVE_X86_SIMD) +#if defined(ABSL_CRC_INTERNAL_HAVE_ARM_SIMD) && !defined(__ARM_FEATURE_CRC32) + if (!absl::base_internal::SupportsArmCRC32PMULL()) { + return false; + } +#endif constexpr uint32_t kCrc32Xor = 0xffffffffU; *crc ^= kCrc32Xor; if (n & 1) {
diff --git a/absl/crc/internal/crc_x86_arm_combined.cc b/absl/crc/internal/crc_x86_arm_combined.cc index 5fe704f..99df29d 100644 --- a/absl/crc/internal/crc_x86_arm_combined.cc +++ b/absl/crc/internal/crc_x86_arm_combined.cc
@@ -27,6 +27,7 @@ #include "absl/base/config.h" #include "absl/base/internal/cpu_detect.h" #include "absl/base/internal/endian.h" +#include "absl/base/macros.h" #include "absl/base/optimization.h" #include "absl/base/prefetch.h" #include "absl/crc/internal/crc32_x86_arm_combined_simd.h" @@ -47,6 +48,9 @@ using ::absl::base_internal::GetCpuType; #if defined(__aarch64__) using ::absl::base_internal::SupportsArmCRC32PMULL; +using ::absl::base_internal::SupportsArmSHA3; +#else +using ::absl::base_internal::SupportsAvx2; #endif #if defined(ABSL_INTERNAL_CAN_USE_SIMD_CRC32C) @@ -267,6 +271,45 @@ } } + // Copies n < 64 bytes from `src` to `dst`. Fixed-size `std::memcpy()` calls + // compile to inline loads and stores, while a variable-length one compiles to + // a call that measurably slows down short head and tail copies and forces a + // stack frame in callers. + ABSL_ATTRIBUTE_ALWAYS_INLINE static void CopyLessThan64Bytes( + char* dst, const uint8_t* src, size_t n) { + ABSL_ASSERT(n < 64); + if (n >= 32) { + CopyInTwoChunksInline<32>(dst, src, n); + } else if (n >= 16) { + CopyInTwoChunksInline<16>(dst, src, n); + } else if (n >= 8) { + CopyInTwoChunksInline<8>(dst, src, n); + } else if (n >= 4) { + CopyInTwoChunksInline<4>(dst, src, n); + } else if (n >= 2) { + CopyInTwoChunksInline<2>(dst, src, n); + } else if (n == 1) { + *dst = static_cast<char>(*src); + } + } + + // Copies `n` bytes from `src` to `dst`, with two possibly overlapping copies + // (the first kBytesPerCopy bytes of src and the last kBytesPerCopy bytes of + // src). Since the copies are of a fixed size, we must have kBytesPerCopy <= n + // <= 2 * kBytesPerCopy. This is faster than `std::memcpy()` for small, + // variable-sized copies, because it compiles to 2 simple loads and stores, + // instead of branching on the value of `n` and it is easily inlined. + template <size_t kBytesPerCopy> + ABSL_ATTRIBUTE_ALWAYS_INLINE static void CopyInTwoChunksInline(char* dst, + const uint8_t* src, + size_t n) { + ABSL_ASSERT(n <= 2 * kBytesPerCopy); + ABSL_ASSERT(n >= kBytesPerCopy); + std::memcpy(dst, src, kBytesPerCopy); + std::memcpy(dst + n - kBytesPerCopy, src + n - kBytesPerCopy, + kBytesPerCopy); + } + // Update a single 128-bit element of partialCRC with crc of 16 byte block. // Calling FinalizePclmulStream would produce a single crc checksum, but it is // expensive. PCLMULQDQ has a high latency, so we run 4 128-bit partial @@ -408,9 +451,7 @@ return crc; } -#if defined(ABSL_CRC_INTERNAL_HAVE_X86_SIMD) && \ - (defined(__AVX__) || defined(ABSL_INTERNAL_CAN_FORCE_AVX)) && \ - (!defined(_MSC_VER) || defined(__clang__)) +#if defined(ABSL_CRC_INTERNAL_HAVE_VPCLMUL) // This is only used if we have vector version of PCLMULQDQ. // We don't have it on arm, and it isn't supported by default // compiler targets on x86. If we want to use it, we need to either use @@ -485,9 +526,7 @@ ABSL_ATTRIBUTE_ALWAYS_INLINE static uint64_t FinalizeVpclmulStream(V256*) { return 0; } -#endif // defined(ABSL_CRC_INTERNAL_HAVE_X86_SIMD) && (defined(__AVX__) || - // defined(ABSL_INTERNAL_CAN_FORCE_AVX)) && (!defined(_MSC_VER) || - // defined(__clang__)) +#endif // defined(ABSL_CRC_INTERNAL_HAVE_VPCLMUL) // Constants generated by './scripts/gen-crc-consts.py x86_pclmul // crc32_lsb_0x82f63b78' from the Linux kernel. @@ -706,7 +745,7 @@ uintptr_t dst_addr = reinterpret_cast<uintptr_t>(d); size_t bytes_to_align = (kAlignment - (dst_addr & (kAlignment - 1))) & (kAlignment - 1); - std::memcpy(d, p, bytes_to_align); + CopyLessThan64Bytes(d, p, bytes_to_align); d += bytes_to_align; while (bytes_to_align >= 8) { ABSL_INTERNAL_STEP8(l, p); @@ -927,15 +966,11 @@ if constexpr (copy_type != CopyType::kNone) { d = reinterpret_cast<char*>( dst_pclmul_streams[kNumActivePclmulStreams - 1]); - size_t remaining_to_copy = static_cast<size_t>(e - p); - std::memcpy(d, p, remaining_to_copy); } } else { p = crc_streams[kNumActiveCrcStreams - 1]; if constexpr (copy_type != CopyType::kNone) { d = reinterpret_cast<char*>(dst_crc_streams[kNumActiveCrcStreams - 1]); - size_t remaining_to_copy = static_cast<size_t>(e - p); - std::memcpy(d, p, remaining_to_copy); } } @@ -963,15 +998,24 @@ *crc = l; - if constexpr (copy_type == CopyType::kNonTemporal) { - // According to the Intel 64 Software Developer's Manual - // (https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html), - // non-temporal stores are weakly ordered due to bypassing caches, so - // they have to be fenced before the copy is visible to other threads. - // Regular stores are ordered and need no fence. Note that the fence is - // placed after all stores, to avoid unnecessary serialization and a - // performance hit. - NonTemporalStoreFence(); + if constexpr (copy_type != CopyType::kNone) { + const uint8_t* copy_src = e - remaining_bytes; + while (e - copy_src >= 64) { + Copy64Bytes<copy_type>(reinterpret_cast<uint8_t*>(d), copy_src); + d += 64; + copy_src += 64; + } + CopyLessThan64Bytes(d, copy_src, static_cast<size_t>(e - copy_src)); + if constexpr (copy_type == CopyType::kNonTemporal) { + // According to the Intel 64 Software Developer's Manual + // (https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html), + // non-temporal stores are weakly ordered due to bypassing caches, so + // they have to be fenced before the copy is visible to other threads. + // Regular stores are ordered and need no fence. Note that the fence is + // placed after all stores, to avoid unnecessary serialization and a + // performance hit. + NonTemporalStoreFence(); + } } } @@ -1164,11 +1208,7 @@ case CpuType::kAmdSiena: case CpuType::kAmdTurin: case CpuType::kAmdVenice: -#if defined(ABSL_CRC_INTERNAL_HAVE_X86_SIMD) && \ - (defined(__AVX__) || defined(ABSL_INTERNAL_CAN_FORCE_AVX)) && \ - (!defined(_MSC_VER) || defined(__clang__)) - // We don't have vector pclmul on arm, but this still needs to - // compile. +#if defined(ABSL_CRC_INTERNAL_HAVE_VPCLMUL) return new CRC32AcceleratedX86ARMCombinedMultipleStreams< 2, 3, PclmulStreamType::VPCLMUL>(); #else @@ -1178,9 +1218,7 @@ case CpuType::kIntelSapphirerapids: case CpuType::kIntelEmeraldrapids: case CpuType::kIntelGraniterapids: -#if defined(ABSL_CRC_INTERNAL_HAVE_X86_SIMD) && \ - (defined(__AVX__) || defined(ABSL_INTERNAL_CAN_FORCE_AVX)) && \ - (!defined(_MSC_VER) || defined(__clang__)) +#if defined(ABSL_CRC_INTERNAL_HAVE_VPCLMUL) return new CRC32AcceleratedX86ARMCombinedMultipleStreams< 3, 3, PclmulStreamType::VPCLMUL>(); #else @@ -1226,9 +1264,17 @@ // before trying to use an accelerated implementation. if (SupportsArmCRC32PMULL()) { #if defined(__APPLE__) + if (SupportsArmSHA3()) { + return new CRC32AcceleratedX86ARMCombinedMultipleStreams< + 3, 3, PclmulStreamType::NEON_PCLMUL_EOR3>(); + } return new CRC32AcceleratedX86ARMCombinedMultipleStreams< 3, 3, PclmulStreamType::NEON_PCLMUL>(); #else + if (SupportsArmSHA3()) { + return new CRC32AcceleratedX86ARMCombinedMultipleStreams< + 1, 1, PclmulStreamType::NEON_PCLMUL_EOR3>(); + } return new CRC32AcceleratedX86ARMCombinedMultipleStreams< 1, 1, PclmulStreamType::NEON_PCLMUL>(); #endif @@ -1237,6 +1283,14 @@ } #else default: + // Use AVX2 support as a heuristic for modern x86_64 CPUs with fast + // PCLMULQDQ (Haswell and newer) when the microarchitecture is + // unrecognized (e.g., client CPUs, open-source builds, or other OSes), + // not because this path uses AVX2 instructions. + if (SupportsAvx2()) { + return new CRC32AcceleratedX86ARMCombinedMultipleStreams< + 3, 1, PclmulStreamType::PCLMUL>(); + } // Something else, play it safe and assume slow PCLMULQDQ. return new CRC32AcceleratedX86ARMCombinedMultipleStreams< 3, 0, PclmulStreamType::NONE>();
diff --git a/absl/debugging/internal/stacktrace_aarch64-inl.inc b/absl/debugging/internal/stacktrace_aarch64-inl.inc index 79d6858..b5bf60e 100644 --- a/absl/debugging/internal/stacktrace_aarch64-inl.inc +++ b/absl/debugging/internal/stacktrace_aarch64-inl.inc
@@ -193,12 +193,12 @@ } template <bool IS_STACK_FRAMES, bool IS_WITH_CONTEXT> -// We count on the bottom frame being this one. See the comment -// at prev_return_address -ABSL_ATTRIBUTE_NOINLINE ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS // May read random elements from stack. ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY // May read random elements from stack. ABSL_ATTRIBUTE_NO_SANITIZE_THREAD // May read random elements from stack. +// We count on the bottom frame being this one. See the comment +// at prev_return_address +ABSL_ATTRIBUTE_NOINLINE static int UnwindImpl(void **result, uintptr_t *frames, int *sizes, int max_depth, int skip_count, const void *ucp, int *min_dropped_frames) {
diff --git a/absl/debugging/internal/vdso_support.cc b/absl/debugging/internal/vdso_support.cc index 6bc679d..fb9d359 100644 --- a/absl/debugging/internal/vdso_support.cc +++ b/absl/debugging/internal/vdso_support.cc
@@ -181,6 +181,7 @@ } // Use fast __vdso_getcpu if available. +ABSL_ATTRIBUTE_NO_SANITIZE_CFI long VDSOSupport::InitAndGetCPU(unsigned *cpu, // NOLINT(runtime/int) void *x, void *y) { Init();
diff --git a/absl/numeric/bits.h b/absl/numeric/bits.h index 8eca392..902b2d2 100644 --- a/absl/numeric/bits.h +++ b/absl/numeric/bits.h
@@ -136,11 +136,29 @@ #endif +// https://github.com/abseil/abseil-cpp/issues/1890 +// libstdc++ had the wrong return type for std::bit_width prior to version 13. +#if (defined(__cpp_lib_int_pow2) && __cpp_lib_int_pow2 >= 202002L) && \ + (!defined(_GLIBCXX_RELEASE) || _GLIBCXX_RELEASE >= 13) + +using std::bit_width; + +#else + +// Returns: If x == 0, 0; otherwise one plus the base-2 logarithm of x, with any +// fractional part discarded. +template <class T> +ABSL_INTERNAL_CONSTEXPR_CLZ inline std::enable_if_t<std::is_unsigned_v<T>, int> +bit_width(T x) noexcept { + return std::numeric_limits<T>::digits - countl_zero(x); +} + +#endif + #if (defined(__cpp_lib_int_pow2) && __cpp_lib_int_pow2 >= 202002L) using std::bit_ceil; using std::bit_floor; -using std::bit_width; using std::has_single_bit; #else @@ -152,14 +170,6 @@ return x != 0 && (x & (x - 1)) == 0; } -// Returns: If x == 0, 0; otherwise one plus the base-2 logarithm of x, with any -// fractional part discarded. -template <class T> -ABSL_INTERNAL_CONSTEXPR_CLZ inline std::enable_if_t<std::is_unsigned_v<T>, int> -bit_width(T x) noexcept { - return std::numeric_limits<T>::digits - countl_zero(x); -} - // Returns: If x == 0, 0; otherwise the maximal value y such that // has_single_bit(y) is true and y <= x. template <class T>
diff --git a/absl/random/CMakeLists.txt b/absl/random/CMakeLists.txt index b2c3fa2..700c271 100644 --- a/absl/random/CMakeLists.txt +++ b/absl/random/CMakeLists.txt
@@ -971,6 +971,7 @@ ${ABSL_DEFAULT_LINKOPTS} DEPS absl::random_internal_distribution_test_util + GTest::gmock GTest::gtest_main ) @@ -1035,6 +1036,7 @@ DEPS absl::core_headers absl::random_internal_distribution_test_util + GTest::gmock GTest::gtest_main )
diff --git a/absl/random/internal/chi_square.cc b/absl/random/internal/chi_square.cc index 481c1c3..2dd4a71 100644 --- a/absl/random/internal/chi_square.cc +++ b/absl/random/internal/chi_square.cc
@@ -14,6 +14,7 @@ #include "absl/random/internal/chi_square.h" +#include <algorithm> #include <cmath> #include "absl/base/config.h" @@ -24,103 +25,40 @@ namespace random_internal { namespace { -#if defined(__EMSCRIPTEN__) -// Workaround __EMSCRIPTEN__ error: llvm_fma_f64 not found. -inline double fma(double x, double y, double z) { return (x * y) + z; } -#endif +constexpr int kLargeDOF = 150; -// Use Horner's method to evaluate a polynomial. -template <typename T, unsigned N> -inline T EvaluatePolynomial(T x, const T (&poly)[N]) { -#if !defined(__EMSCRIPTEN__) - using std::fma; -#endif - T p = poly[N - 1]; - for (unsigned i = 2; i <= N; i++) { - p = fma(p, x, poly[N - i]); - } - return p; -} +// 1 / sqrt(2). Defined explicitly instead of non-standard M_SQRT1_2 for +// portability (e.g. Windows/MSVC). +constexpr double kSqrt1_2 = 0.70710678118654752440084436210485; -static constexpr int kLargeDOF = 150; - -// Returns the probability of a normal z-value. -// -// Adapted from the POZ function in: -// Ibbetson D, Algorithm 209 -// Collected Algorithms of the CACM 1963 p. 616 -// -double POZ(double z) { - static constexpr double kP1[] = { - 0.797884560593, -0.531923007300, 0.319152932694, - -0.151968751364, 0.059054035642, -0.019198292004, - 0.005198775019, -0.001075204047, 0.000124818987, - }; - static constexpr double kP2[] = { - 0.999936657524, 0.000535310849, -0.002141268741, 0.005353579108, - -0.009279453341, 0.011630447319, -0.010557625006, 0.006549791214, - -0.002034254874, -0.000794620820, 0.001390604284, -0.000676904986, - -0.000019538132, 0.000152529290, -0.000045255659, - }; - - const double kZMax = 6.0; // Maximum meaningful z-value. - if (z == 0.0) { - return 0.5; - } - double x; - double y = 0.5 * std::fabs(z); - if (y >= (kZMax * 0.5)) { - x = 1.0; - } else if (y < 1.0) { - double w = y * y; - x = EvaluatePolynomial(w, kP1) * y * 2.0; - } else { - y -= 2.0; - x = EvaluatePolynomial(y, kP2); - } - return z > 0.0 ? ((x + 1.0) * 0.5) : ((1.0 - x) * 0.5); -} - -// Approximates the survival function of the normal distribution. -// -// Algorithm 26.2.18, from: -// [Abramowitz and Stegun, Handbook of Mathematical Functions,p.932] -// http://people.math.sfu.ca/~cbm/aands/abramowitz_and_stegun.pdf -// -double normal_survival(double z) { - // Maybe replace with the alternate formulation. - // 0.5 * erfc((x - mean)/(sqrt(2) * sigma)) - static constexpr double kR[] = { - 1.0, 0.196854, 0.115194, 0.000344, 0.019527, - }; - double r = EvaluatePolynomial(z, kR); - r *= r; - return 0.5 / (r * r); -} +// Returns the survival function of the standard normal distribution: +// P(Z > z) = 1 - Phi(z) = 0.5 * erfc(z / sqrt(2)). +double normal_survival(double z) { return 0.5 * std::erfc(z * kSqrt1_2); } } // namespace -// Calculates the critical chi-square value given degrees-of-freedom and a -// p-value, usually using bisection. Also known by the name CRITCHI. +// Calculates the critical chi-square value x given degrees of freedom and +// cumulative probability p = P(X <= x) (upper-tail p-value 1 - p), using +// Wilson-Hilferty for large dof and bisection otherwise. Also known as CRITCHI. double ChiSquareValue(int dof, double p) { static constexpr double kChiEpsilon = 0.000001; // Accuracy of the approximation. static constexpr double kChiMax = 99999.0; // Maximum chi-squared value. const double p_value = 1.0 - p; - if (dof < 1 || p_value > 1.0) { + if (dof < 1 || p_value >= 1.0) { return 0.0; } if (dof > kLargeDOF) { - // For large degrees of freedom, use the normal approximation by - // Wilson, E. B. and Hilferty, M. M. (1931) - // chi^2 - mean - // Z = -------------- - // stddev + // For large degrees of freedom, use the Wilson-Hilferty (1931) cube-root + // normal approximation: + // (chi^2 / dof)^(1/3) - mean + // Z = ---------------------------- + // stddev const double z = InverseNormalSurvival(p_value); - const double mean = 1 - 2.0 / (9 * dof); - const double variance = 2.0 / (9 * dof); + const double mean = 1 - 2.0 / (9.0 * dof); + const double variance = 2.0 / (9.0 * dof); // Cannot use this method if the variance is 0. if (variance != 0) { double term = z * std::sqrt(variance) + mean; @@ -133,7 +71,7 @@ // Otherwise search for the p value by bisection double min_chisq = 0.0; double max_chisq = kChiMax; - double current = dof / std::sqrt(p_value); + double current = std::min(dof / std::sqrt(p_value), max_chisq); while ((max_chisq - min_chisq) > kChiEpsilon) { if (ChiSquarePValue(current, dof) < p_value) { max_chisq = current; @@ -158,30 +96,6 @@ static constexpr double kInverseSqrtPi = 0.5641895835477562869480795; // 1/(Sqrt[Pi]) - // For large degrees of freedom, use the normal approximation by - // Wilson, E. B. and Hilferty, M. M. (1931) - // Via Wikipedia: - // By the Central Limit Theorem, because the chi-square distribution is the - // sum of k independent random variables with finite mean and variance, it - // converges to a normal distribution for large k. - if (dof > kLargeDOF) { - // Re-scale everything. - const double chi_square_scaled = std::pow(chi_square / dof, 1.0 / 3); - const double mean = 1 - 2.0 / (9 * dof); - const double variance = 2.0 / (9 * dof); - // If variance is 0, this method cannot be used. - if (variance != 0) { - const double z = (chi_square_scaled - mean) / std::sqrt(variance); - if (z > 0) { - return normal_survival(z); - } else if (z < 0) { - return 1.0 - normal_survival(-z); - } else { - return 0.5; - } - } - } - // The chi square function is >= 0 for any degrees of freedom. // In other words, probability that the chi square function >= 0 is 1. if (chi_square <= 0.0) return 1.0; @@ -189,15 +103,34 @@ // If the degrees of freedom is zero, the chi square function is always 0 by // definition. In other words, the probability that the chi square function // is > 0 is zero (chi square values <= 0 have been filtered above). - if (dof < 1) return 0; + if (dof < 1) return 0.0; - auto capped_exp = [](double x) { return x < -20 ? 0.0 : std::exp(x); }; + // For large degrees of freedom, use the Wilson-Hilferty (1931) cube-root + // normal approximation: (chi^2 / dof)^(1/3) ~ N(1 - 2/(9*dof), 2/(9*dof)). + if (dof > kLargeDOF) { + // Re-scale everything. + const double chi_square_scaled = std::pow(chi_square / dof, 1.0 / 3); + const double mean = 1 - 2.0 / (9.0 * dof); + const double variance = 2.0 / (9.0 * dof); + // If variance is 0, this method cannot be used. + if (variance != 0) { + const double z = (chi_square_scaled - mean) / std::sqrt(variance); + return normal_survival(z); + } + } + + if (std::isinf(chi_square)) return 0.0; + + // Above kBigX, sum terms in log-space to avoid a^k / k! overflow in the + // direct recurrence below. static constexpr double kBigX = 20; double a = 0.5 * chi_square; + if (a == 0.0) return 1.0; const bool even = !(dof & 1); // True if dof is an even number. - const double y = capped_exp(-a); - double s = even ? y : (2.0 * POZ(-std::sqrt(chi_square))); + const double y = std::exp(-a); + // For odd dof, P(chi^2_1 > chi_square) = erfc(sqrt(chi_square / 2)). + double s = even ? y : std::erfc(std::sqrt(a)); if (dof <= 2) { return s; @@ -210,7 +143,7 @@ double c = std::log(a); while (z <= chi_square) { e = std::log(z) + e; - s += capped_exp(c * z - a - e); + s += std::exp(c * z - a - e); z += 1.0; } return s;
diff --git a/absl/random/internal/chi_square.h b/absl/random/internal/chi_square.h index 07f4fbe..bb0fa81 100644 --- a/absl/random/internal/chi_square.h +++ b/absl/random/internal/chi_square.h
@@ -60,7 +60,7 @@ assert(*eit > 0); } double e = static_cast<double>(*eit); - double d = static_cast<double>(*it - *eit); + double d = static_cast<double>(*it) - e; if (d != 0) { assert(e > 0); chi_square += (d * d) / e; @@ -74,9 +74,9 @@ // The following methods can be used for an arbitrary significance level. // -// Calculates critical chi-square values to produce the given p-value using a -// bisection search for a value within epsilon, relying on the monotonicity of -// ChiSquarePValue(). +// Calculates the critical chi-square value x such that P(X <= x) = p +// (i.e., upper-tail p-value 1 - p), using Wilson-Hilferty for large dof +// (> 150) and bisection over ChiSquarePValue() otherwise. double ChiSquareValue(int dof, double p); // Calculates the p-value (probability) of a given chi-square value.
diff --git a/absl/random/internal/chi_square_test.cc b/absl/random/internal/chi_square_test.cc index 964cd22..b91ab6e 100644 --- a/absl/random/internal/chi_square_test.cc +++ b/absl/random/internal/chi_square_test.cc
@@ -15,12 +15,15 @@ #include "absl/random/internal/chi_square.h" #include <algorithm> +#include <cmath> #include <cstddef> #include <cstdint> #include <iterator> +#include <limits> #include <numeric> #include <vector> +#include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/algorithm/container.h" #include "absl/base/macros.h" @@ -29,6 +32,8 @@ using absl::random_internal::ChiSquarePValue; using absl::random_internal::ChiSquareValue; using absl::random_internal::ChiSquareWithExpected; +using ::testing::DoubleEq; +using ::testing::DoubleNear; namespace { @@ -362,4 +367,121 @@ EXPECT_NEAR(p_b, 0.4528180, 1e-5); // Accept the null hypothesis. } +double WilsonHilfertyChiSquare(int dof, double z) { + const double mean = 1.0 - 2.0 / (9.0 * dof); + const double stddev = std::sqrt(2.0 / (9.0 * dof)); + const double term = mean + z * stddev; + return dof * (term * term * term); +} + +TEST(ChiSquareTest, LargeDofNormalSurvivalTails) { + constexpr int kDof = 200; + EXPECT_THAT(ChiSquarePValue(WilsonHilfertyChiSquare(kDof, -5.0), kDof), + DoubleNear(0.99999971334842808, 1e-12)); + EXPECT_THAT(ChiSquarePValue(WilsonHilfertyChiSquare(kDof, -2.0), kDof), + DoubleNear(0.97724986805182079, 1e-12)); + EXPECT_THAT(ChiSquarePValue(WilsonHilfertyChiSquare(kDof, 0.0), kDof), + DoubleNear(0.5, 1e-12)); + // Extreme upper-tail z-scores (normal_survival uses std::erfc). + EXPECT_THAT(ChiSquarePValue(WilsonHilfertyChiSquare(kDof, 5.0), kDof), + DoubleNear(2.8665157187919455e-7, 1e-12)); + EXPECT_THAT(ChiSquarePValue(WilsonHilfertyChiSquare(kDof, 8.0), kDof), + DoubleNear(6.2209605742718204e-16, 1e-20)); + EXPECT_THAT(ChiSquarePValue(WilsonHilfertyChiSquare(kDof, 20.0), kDof), + DoubleNear(2.7536241186063318e-89, 1e-95)); + + EXPECT_THAT(ChiSquarePValue(std::numeric_limits<double>::infinity(), kDof), + DoubleEq(0.0)); + EXPECT_THAT(ChiSquarePValue(-std::numeric_limits<double>::infinity(), kDof), + DoubleEq(1.0)); + EXPECT_THAT(ChiSquarePValue(-1.0, kDof), DoubleEq(1.0)); +} + +TEST(ChiSquareTest, ExtremeTailNoCliffs) { + // Extreme upper tails beyond |z| = 6 (dof = 1) and exp(-20) (dof = 2). + EXPECT_THAT(ChiSquareValue(1, 1.0 - 1e-10), DoubleNear(41.821456, 1e-4)); + EXPECT_THAT(ChiSquareValue(1, 1.0 - 1e-12), DoubleNear(50.844128, 1e-4)); + EXPECT_THAT(ChiSquareValue(2, 1.0 - 1e-10), DoubleNear(46.051702, 1e-4)); + EXPECT_THAT(ChiSquareValue(5, 1.0 - 1e-10), DoubleNear(55.562399, 1e-4)); + + // Matching p-values in the extreme upper tail should not underflow to 0.0. + EXPECT_THAT(ChiSquarePValue(41.821456, 1), DoubleNear(1e-10, 1e-13)); + EXPECT_THAT(ChiSquarePValue(41.61, 1), DoubleNear(1.11421889e-10, 1e-13)); + EXPECT_THAT(ChiSquarePValue(46.051702, 2), DoubleNear(1e-10, 1e-13)); + EXPECT_THAT(ChiSquarePValue(55.562399, 5), DoubleNear(1e-10, 1e-13)); + + // Large dof extreme tail round-trip. + const double large_dof_val = ChiSquareValue(200, 1.0 - 1e-10); + EXPECT_THAT(ChiSquarePValue(large_dof_val, 200), DoubleNear(1e-10, 1e-14)); + + // Infinite inputs for small dof. + EXPECT_THAT(ChiSquarePValue(std::numeric_limits<double>::infinity(), 1), + DoubleEq(0.0)); + EXPECT_THAT(ChiSquarePValue(std::numeric_limits<double>::infinity(), 10), + DoubleEq(0.0)); + EXPECT_THAT(ChiSquarePValue(-std::numeric_limits<double>::infinity(), 1), + DoubleEq(1.0)); +} + +TEST(ChiSquareTest, UnsignedIteratorsActualLessThanExpected) { + const std::vector<uint64_t> actual_u64 = {10, 20, 30}; + const std::vector<uint64_t> expected_u64 = {20, 20, 20}; + EXPECT_THAT(ChiSquare(actual_u64.begin(), actual_u64.end(), + expected_u64.begin(), expected_u64.end()), + DoubleNear(10.0, 1e-12)); + + const std::vector<size_t> actual_sz = {5, 10, 15}; + const std::vector<size_t> expected_sz = {10, 20, 30}; + EXPECT_THAT(ChiSquare(actual_sz.begin(), actual_sz.end(), expected_sz.begin(), + expected_sz.end()), + DoubleNear(15.0, 1e-12)); + + const std::vector<uint32_t> actual_u32 = {100, 999}; + const std::vector<uint32_t> expected_u32 = {200, 1000}; + EXPECT_THAT(ChiSquare(actual_u32.begin(), actual_u32.end(), + expected_u32.begin(), expected_u32.end()), + DoubleNear(50.001, 1e-12)); +} + +TEST(ChiSquareTest, SubnormalChiSquarePValue) { + const double kDenormMin = std::numeric_limits<double>::denorm_min(); + const double kMinNormal = std::numeric_limits<double>::min(); + + // When 0.5 * chi_square underflows to 0.0, odd dof in [3, 150] must return + // 1.0 rather than NaN from (+inf) * 0.0. + EXPECT_THAT(ChiSquarePValue(kDenormMin, 1), DoubleEq(1.0)); + EXPECT_THAT(ChiSquarePValue(kDenormMin, 2), DoubleEq(1.0)); + EXPECT_THAT(ChiSquarePValue(kDenormMin, 3), DoubleEq(1.0)); + EXPECT_THAT(ChiSquarePValue(kDenormMin, 5), DoubleEq(1.0)); + EXPECT_THAT(ChiSquarePValue(kDenormMin, 7), DoubleEq(1.0)); + EXPECT_THAT(ChiSquarePValue(kDenormMin, 149), DoubleEq(1.0)); + EXPECT_THAT(ChiSquarePValue(kDenormMin, 150), DoubleEq(1.0)); + EXPECT_THAT(ChiSquarePValue(kDenormMin, 200), DoubleEq(1.0)); + + EXPECT_THAT(ChiSquarePValue(2.0 * kDenormMin, 3), DoubleEq(1.0)); + EXPECT_THAT(ChiSquarePValue(kMinNormal, 3), DoubleEq(1.0)); + EXPECT_THAT(ChiSquarePValue(kMinNormal, 149), DoubleEq(1.0)); +} + +TEST(ChiSquareTest, VeryLargeDofNoSignedOverflow) { + constexpr int kOverflowDof = std::numeric_limits<int>::max() / 9 + 1; + constexpr int kMaxDof = std::numeric_limits<int>::max(); + + EXPECT_THAT( + ChiSquarePValue(WilsonHilfertyChiSquare(kOverflowDof, 0.0), kOverflowDof), + DoubleNear(0.5, 1e-12)); + EXPECT_THAT( + ChiSquarePValue(WilsonHilfertyChiSquare(kOverflowDof, 2.0), kOverflowDof), + DoubleNear(0.02275013194817921, 1e-12)); + EXPECT_THAT(ChiSquareValue(kOverflowDof, 0.5), + DoubleNear(WilsonHilfertyChiSquare(kOverflowDof, 0.0), 1e-3)); + + EXPECT_THAT(ChiSquarePValue(ChiSquareValue(kMaxDof, 0.5), kMaxDof), + DoubleNear(0.5, 1e-8)); + EXPECT_THAT(ChiSquarePValue(ChiSquareValue(kMaxDof, 0.95), kMaxDof), + DoubleNear(0.05, 1e-8)); + EXPECT_THAT(ChiSquarePValue(ChiSquareValue(kMaxDof, 0.999), kMaxDof), + DoubleNear(0.001, 1e-8)); +} + } // namespace
diff --git a/absl/random/internal/distribution_test_util.cc b/absl/random/internal/distribution_test_util.cc index 4ae6fcb..e342499 100644 --- a/absl/random/internal/distribution_test_util.cc +++ b/absl/random/internal/distribution_test_util.cc
@@ -14,7 +14,6 @@ #include "absl/random/internal/distribution_test_util.h" -#include <algorithm> #include <cassert> #include <cmath> #include <limits> @@ -34,11 +33,93 @@ namespace random_internal { namespace { -#if defined(__EMSCRIPTEN__) -// Workaround __EMSCRIPTEN__ error: llvm_fma_f64 not found. -inline double fma(double x, double y, double z) { return (x * y) + z; } +// Use std::fma only when hardware FMA is available, avoiding software libm +// fma() overhead and Emscripten llvm_fma_f64 link issues. +#if defined(FP_FAST_FMA) || defined(__FP_FAST_FMA) || defined(__FMA__) || \ + defined(__aarch64__) || defined(_M_ARM64) +inline double Fma(double a, double b, double c) { return std::fma(a, b, c); } +#else +inline double Fma(double a, double b, double c) { return a * b + c; } #endif +constexpr double kPi = 3.1415926535897932384626433832795; +constexpr double kSqrt2 = 1.4142135623730950488016887242097; +constexpr double kSqrt1_2 = 0.70710678118654752440084436210485; +constexpr double kInvSqrt2Pi = 0.39894228040143267793994605993438; + +// Evaluates the polynomial factor p(w) for Giles's erfinv(x) = p(w) * x, +// where w = -log((1 - x) * (1 + x)) is in [0, ~36]. +double ErfInvPoly(double w) { + double p = 0.0; + if (w < 6.250000) { + w = w - 3.125000; + p = -3.6444120640178196996e-21; + p = Fma(p, w, -1.685059138182016589e-19); + p = Fma(p, w, 1.2858480715256400167e-18); + p = Fma(p, w, 1.115787767802518096e-17); + p = Fma(p, w, -1.333171662854620906e-16); + p = Fma(p, w, 2.0972767875968561637e-17); + p = Fma(p, w, 6.6376381343583238325e-15); + p = Fma(p, w, -4.0545662729752068639e-14); + p = Fma(p, w, -8.1519341976054721522e-14); + p = Fma(p, w, 2.6335093153082322977e-12); + p = Fma(p, w, -1.2975133253453532498e-11); + p = Fma(p, w, -5.4154120542946279317e-11); + p = Fma(p, w, 1.051212273321532285e-09); + p = Fma(p, w, -4.1126339803469836976e-09); + p = Fma(p, w, -2.9070369957882005086e-08); + p = Fma(p, w, 4.2347877827932403518e-07); + p = Fma(p, w, -1.3654692000834678645e-06); + p = Fma(p, w, -1.3882523362786468719e-05); + p = Fma(p, w, 0.0001867342080340571352); + p = Fma(p, w, -0.00074070253416626697512); + p = Fma(p, w, -0.0060336708714301490533); + p = Fma(p, w, 0.24015818242558961693); + p = Fma(p, w, 1.6536545626831027356); + } else if (w < 16.000000) { + w = std::sqrt(w) - 3.250000; + p = 2.2137376921775787049e-09; + p = Fma(p, w, 9.0756561938885390979e-08); + p = Fma(p, w, -2.7517406297064545428e-07); + p = Fma(p, w, 1.8239629214389227755e-08); + p = Fma(p, w, 1.5027403968909827627e-06); + p = Fma(p, w, -4.013867526981545969e-06); + p = Fma(p, w, 2.9234449089955446044e-06); + p = Fma(p, w, 1.2475304481671778723e-05); + p = Fma(p, w, -4.7318229009055733981e-05); + p = Fma(p, w, 6.8284851459573175448e-05); + p = Fma(p, w, 2.4031110387097893999e-05); + p = Fma(p, w, -0.0003550375203628474796); + p = Fma(p, w, 0.00095328937973738049703); + p = Fma(p, w, -0.0016882755560235047313); + p = Fma(p, w, 0.0024914420961078508066); + p = Fma(p, w, -0.0037512085075692412107); + p = Fma(p, w, 0.005370914553590063617); + p = Fma(p, w, 1.0052589676941592334); + p = Fma(p, w, 3.0838856104922207635); + } else { + w = std::sqrt(w) - 5.000000; + p = -2.7109920616438573243e-11; + p = Fma(p, w, -2.5556418169965252055e-10); + p = Fma(p, w, 1.5076572693500548083e-09); + p = Fma(p, w, -3.7894654401267369937e-09); + p = Fma(p, w, 7.6157012080783393804e-09); + p = Fma(p, w, -1.4960026627149240478e-08); + p = Fma(p, w, 2.9147953450901080826e-08); + p = Fma(p, w, -6.7711997758452339498e-08); + p = Fma(p, w, 2.2900482228026654717e-07); + p = Fma(p, w, -9.9298272942317002539e-07); + p = Fma(p, w, 4.5260625972231537039e-06); + p = Fma(p, w, -1.9681778105531670567e-05); + p = Fma(p, w, 7.5995277030017761139e-05); + p = Fma(p, w, -0.00021503011930044477347); + p = Fma(p, w, -0.00013871931833623122026); + p = Fma(p, w, 1.0103004648645343977); + p = Fma(p, w, 4.8499064014085844221); + } + return p; +} + } // namespace DistributionMoments ComputeDistributionMoments( @@ -83,9 +164,44 @@ } double InverseNormalSurvival(double x) { - // inv_sf(u) = -sqrt(2) * erfinv(2u-1) - static constexpr double kSqrt2 = 1.4142135623730950488; - return -kSqrt2 * absl::random_internal::erfinv(2 * x - 1.0); + if (std::isnan(x) || x < 0.0 || x > 1.0) { + return std::numeric_limits<double>::quiet_NaN(); + } + if (x == 0.0) return std::numeric_limits<double>::infinity(); + if (x == 1.0) return -std::numeric_limits<double>::infinity(); + if (x == 0.5) return 0.0; + + // Use symmetry: inv_sf(1 - u) = -inv_sf(u), with u in (0, 0.5). + const bool upper = x < 0.5; + const double u = upper ? x : (1.0 - x); + double z; + if (u >= 1e-15) { + // inv_sf(u) = sqrt(2) * erfinv(1 - 2u) = sqrt(2) * ErfInvPoly(w) * (1 - 2u) + // where w = -log(1 - (1 - 2u)^2) = -log(4u(1 - u)). + // Split at u = 0.25 to avoid -log(4u) - log1p(-u) cancellation near + // u = 0.5 and precision loss in t = 1 - 2u (and t * t) as u -> 0. + const double t = 1.0 - 2.0 * u; + const double w = (u >= 0.25) ? -std::log1p(-t * t) + : (-std::log(4.0 * u) - std::log1p(-u)); + z = kSqrt2 * ErfInvPoly(w) * t; + } else { + // Giles's third interval is fitted up to w ~= 36 (u ~= 5.8e-17) and loses + // accuracy beyond it. For extreme tails (u < 1e-15), start from the + // asymptotic expansion and refine with Halley's method against + // 0.5 * erfc(z / sqrt(2)). + const double log_inv_u = -std::log(u); + z = std::sqrt(2.0 * log_inv_u - std::log(4.0 * kPi * log_inv_u)); + for (int i = 0; i < 6; ++i) { + const double sf = 0.5 * std::erfc(z * kSqrt1_2); + const double pdf = kInvSqrt2Pi * std::exp(-0.5 * z * z); + if (pdf == 0.0) break; + const double delta = (sf - u) / pdf; + const double step = delta / (1.0 - 0.5 * z * delta); + z += step; + if (std::fabs(step) <= 1e-15 * z) break; + } + } + return upper ? z : -z; } bool Near(absl::string_view msg, double actual, double expected, double bound) { @@ -113,80 +229,13 @@ // Approximation to inverse of the Error Function in double precision. // (http://people.maths.ox.ac.uk/gilesm/files/gems_erfinv.pdf) double erfinv(double x) { -#if !defined(__EMSCRIPTEN__) - using std::fma; -#endif - - double w = 0.0; - double p = 0.0; - w = -std::log((1.0 - x) * (1.0 + x)); - if (w < 6.250000) { - w = w - 3.125000; - p = -3.6444120640178196996e-21; - p = fma(p, w, -1.685059138182016589e-19); - p = fma(p, w, 1.2858480715256400167e-18); - p = fma(p, w, 1.115787767802518096e-17); - p = fma(p, w, -1.333171662854620906e-16); - p = fma(p, w, 2.0972767875968561637e-17); - p = fma(p, w, 6.6376381343583238325e-15); - p = fma(p, w, -4.0545662729752068639e-14); - p = fma(p, w, -8.1519341976054721522e-14); - p = fma(p, w, 2.6335093153082322977e-12); - p = fma(p, w, -1.2975133253453532498e-11); - p = fma(p, w, -5.4154120542946279317e-11); - p = fma(p, w, 1.051212273321532285e-09); - p = fma(p, w, -4.1126339803469836976e-09); - p = fma(p, w, -2.9070369957882005086e-08); - p = fma(p, w, 4.2347877827932403518e-07); - p = fma(p, w, -1.3654692000834678645e-06); - p = fma(p, w, -1.3882523362786468719e-05); - p = fma(p, w, 0.0001867342080340571352); - p = fma(p, w, -0.00074070253416626697512); - p = fma(p, w, -0.0060336708714301490533); - p = fma(p, w, 0.24015818242558961693); - p = fma(p, w, 1.6536545626831027356); - } else if (w < 16.000000) { - w = std::sqrt(w) - 3.250000; - p = 2.2137376921775787049e-09; - p = fma(p, w, 9.0756561938885390979e-08); - p = fma(p, w, -2.7517406297064545428e-07); - p = fma(p, w, 1.8239629214389227755e-08); - p = fma(p, w, 1.5027403968909827627e-06); - p = fma(p, w, -4.013867526981545969e-06); - p = fma(p, w, 2.9234449089955446044e-06); - p = fma(p, w, 1.2475304481671778723e-05); - p = fma(p, w, -4.7318229009055733981e-05); - p = fma(p, w, 6.8284851459573175448e-05); - p = fma(p, w, 2.4031110387097893999e-05); - p = fma(p, w, -0.0003550375203628474796); - p = fma(p, w, 0.00095328937973738049703); - p = fma(p, w, -0.0016882755560235047313); - p = fma(p, w, 0.0024914420961078508066); - p = fma(p, w, -0.0037512085075692412107); - p = fma(p, w, 0.005370914553590063617); - p = fma(p, w, 1.0052589676941592334); - p = fma(p, w, 3.0838856104922207635); - } else { - w = std::sqrt(w) - 5.000000; - p = -2.7109920616438573243e-11; - p = fma(p, w, -2.5556418169965252055e-10); - p = fma(p, w, 1.5076572693500548083e-09); - p = fma(p, w, -3.7894654401267369937e-09); - p = fma(p, w, 7.6157012080783393804e-09); - p = fma(p, w, -1.4960026627149240478e-08); - p = fma(p, w, 2.9147953450901080826e-08); - p = fma(p, w, -6.7711997758452339498e-08); - p = fma(p, w, 2.2900482228026654717e-07); - p = fma(p, w, -9.9298272942317002539e-07); - p = fma(p, w, 4.5260625972231537039e-06); - p = fma(p, w, -1.9681778105531670567e-05); - p = fma(p, w, 7.5995277030017761139e-05); - p = fma(p, w, -0.00021503011930044477347); - p = fma(p, w, -0.00013871931833623122026); - p = fma(p, w, 1.0103004648645343977); - p = fma(p, w, 4.8499064014085844221); + if (x == 1.0) return std::numeric_limits<double>::infinity(); + if (x == -1.0) return -std::numeric_limits<double>::infinity(); + if (!(x > -1.0 && x < 1.0)) { + return std::numeric_limits<double>::quiet_NaN(); } - return p * x; + const double w = -std::log((1.0 - x) * (1.0 + x)); + return ErfInvPoly(w) * x; } namespace { @@ -248,7 +297,7 @@ // https://archive.org/details/DTIC_ADA261511/page/n75 } -// Direct implementation of AS109, XINBTA(p, q, beta, alpha) +// Adapted from AS109, XINBTA(p, q, beta, alpha) // https://www.jstor.org/stable/2346798?read-now=1&seq=4#page_scan_tab_contents // https://www.jstor.org/stable/2346887?seq=1#page_scan_tab_contents // @@ -260,7 +309,7 @@ // double BetaIncompleteInvImpl(const double p, const double q, const double beta, const double alpha) { - if (alpha < 0.5) { + if (alpha > 0.5) { // Inverse Incomplete beta function is symmetrical, return the complement. return 1. - BetaIncompleteInvImpl(q, p, beta, 1. - alpha); } @@ -269,17 +318,20 @@ // Compute the initial estimate. { - double r = std::sqrt(-std::log(alpha * alpha)); + double r = std::sqrt(-2.0 * std::log(alpha)); double y = - r - fma(r, 0.27061, 2.30753) / fma(r, fma(r, 0.04481, 0.99229), 1.0); + r - Fma(r, 0.27061, 2.30753) / Fma(r, Fma(r, 0.04481, 0.99229), 1.0); if (p > 1. && q > 1.) { r = (y * y - 3.) / 6.; double s = 1. / (p + p - 1.); double t = 1. / (q + q - 1.); - double h = 2. / s + t; + double h = 2. / (s + t); double w = - y * std::sqrt(h + r) / h - (t - s) * (r + 5. / 6. - t / (3. * h)); + y * std::sqrt(h + r) / h - (t - s) * (r + 5. / 6. - 2. / (3. * h)); value = p / (p + q * std::exp(w + w)); + if (value == 0.0) { + value = std::numeric_limits<double>::min(); + } } else { r = q + q; double t = 1.0 / (9. * q); @@ -291,6 +343,9 @@ t = (4.0 * p + r - 2.0) / t; if (t <= 1) { value = std::exp((std::log(alpha * p) + beta) / p); + if (value == 0.0) { + value = std::numeric_limits<double>::min(); + } } else { value = 1.0 - 2.0 / (t + 1.0); } @@ -298,60 +353,62 @@ } } - // Solve for x using a modified newton-raphson method using the function - // BetaIncomplete. + // Solve for x using modified Newton-Raphson iteration over + // BetaIncompleteImpl. { - value = std::max(value, kErr); - value = std::min(value, 1.0 - kErr); + if (!std::isfinite(value) || value <= 0.0) { + value = kErr; + } else if (value >= 1.0) { + value = 1.0 - kErr; + } else if (value < std::numeric_limits<double>::min()) { + value = std::numeric_limits<double>::min(); + } const double r = 1.0 - p; const double t = 1.0 - q; - double y; - double yprev = 0; - double sq = 1; - double prev = 1; + double yprev = 0.0; + double sq = 1.0; + double prev = 1.0; for (;;) { - if (value < 0 || value > 1.0) { - // Error case; value went infinite. - return std::numeric_limits<double>::infinity(); - } else if (value == 0 || value == 1) { - y = value; - } else { - y = BetaIncompleteImpl(value, p, q, beta); - if (!std::isfinite(y)) { - return y; - } + const double cdf = BetaIncompleteImpl(value, p, q, beta); + if (!std::isfinite(cdf)) { + return cdf; } - y = (y - alpha) * - std::exp(beta + r * std::log(value) + t * std::log(1.0 - value)); - if (y * yprev <= 0) { - prev = std::max(sq, std::numeric_limits<double>::min()); + const double err = cdf - alpha; + if (err == 0.0) { + return value; + } + double y = err * std::exp(beta + r * std::log(value) + + t * std::log(1.0 - value)); + if (std::isnan(y)) { + return y; + } + if (yprev == 0.0 || std::signbit(y) != std::signbit(yprev)) { + prev = sq; + } + if (std::isinf(y)) { + // Avoid infinity when the density underflows in an extreme tail. + y = std::copysign(0.5 * prev, err); + } + const double tol = kErr * value; + if (prev <= tol) { + return value; } double g = 1.0; for (;;) { const double adj = g * y; - const double adj_sq = adj * adj; - if (adj_sq >= prev) { - g = g / 3.0; + sq = std::fabs(adj); + if (sq >= prev) { + g /= 3.0; continue; } const double tx = value - adj; - if (tx < 0 || tx > 1) { - g = g / 3.0; + if (!(tx > 0.0 && tx < 1.0)) { + g /= 3.0; continue; } - if (prev < kErr) { - return value; - } - if (y * y < kErr) { - return value; - } - if (tx == value) { - return value; - } - if (tx == 0 || tx == 1) { - g = g / 3.0; - continue; + if (sq <= tol || tx == value) { + return tx; } value = tx; yprev = y; @@ -371,7 +428,11 @@ double BetaIncomplete(const double x, const double p, const double q) { // Error cases. - if (p < 0 || q < 0 || x < 0 || x > 1.0) { + if (std::isnan(x) || std::isnan(p) || std::isnan(q)) { + return std::numeric_limits<double>::quiet_NaN(); + } + if (p <= 0.0 || q <= 0.0 || std::isinf(p) || std::isinf(q) || x < 0.0 || + x > 1.0) { return std::numeric_limits<double>::infinity(); } if (x == 0 || x == 1) { @@ -379,12 +440,19 @@ } // ln(Beta(p, q)) double beta = std::lgamma(p) + std::lgamma(q) - std::lgamma(p + q); + if (!std::isfinite(beta)) { + return std::numeric_limits<double>::quiet_NaN(); + } return BetaIncompleteImpl(x, p, q, beta); } double BetaIncompleteInv(const double p, const double q, const double alpha) { // Error cases. - if (p < 0 || q < 0 || alpha < 0 || alpha > 1.0) { + if (std::isnan(p) || std::isnan(q) || std::isnan(alpha)) { + return std::numeric_limits<double>::quiet_NaN(); + } + if (p <= 0.0 || q <= 0.0 || std::isinf(p) || std::isinf(q) || alpha < 0.0 || + alpha > 1.0) { return std::numeric_limits<double>::infinity(); } if (alpha == 0 || alpha == 1) { @@ -392,15 +460,24 @@ } // ln(Beta(p, q)) double beta = std::lgamma(p) + std::lgamma(q) - std::lgamma(p + q); + if (!std::isfinite(beta)) { + return std::numeric_limits<double>::quiet_NaN(); + } return BetaIncompleteInvImpl(p, q, beta, alpha); } // Given `num_trials` trials each with probability `p` of success, the -// probability of no failures is `p^k`. To ensure the probability of a failure -// is no more than `p_fail`, it must be that `p^k == 1 - p_fail`. This function -// computes `p` from that equation. +// probability of no failures is `p^num_trials`. To ensure the probability of +// at least one failure is no more than `p_fail`, we solve +// `p^num_trials == 1 - p_fail`. double RequiredSuccessProbability(const double p_fail, const int num_trials) { - double p = std::exp(std::log(1.0 - p_fail) / static_cast<double>(num_trials)); + double p = std::exp(std::log1p(-p_fail) / static_cast<double>(num_trials)); + if (p_fail > 0.0 && p >= 1.0) { + // Prevent rounding to 1.0 when p_fail / num_trials <= 2^-54, which would + // cause MaxErrorTolerance(p) to return +inf and make Z-tests pass + // unconditionally. + p = std::nextafter(1.0, 0.0); + } ABSL_ASSERT(p > 0); return p; } @@ -412,8 +489,10 @@ } double MaxErrorTolerance(double acceptance_probability) { - double one_sided_pvalue = 0.5 * (1.0 - acceptance_probability); - const double max_err = InverseNormalSurvival(one_sided_pvalue); + const double max_err = + (acceptance_probability <= 0.5) + ? kSqrt2 * absl::random_internal::erfinv(acceptance_probability) + : InverseNormalSurvival(0.5 * (1.0 - acceptance_probability)); ABSL_ASSERT(max_err > 0); return max_err; }
diff --git a/absl/random/internal/distribution_test_util.h b/absl/random/internal/distribution_test_util.h index 1189340..e6e3544 100644 --- a/absl/random/internal/distribution_test_util.h +++ b/absl/random/internal/distribution_test_util.h
@@ -22,7 +22,7 @@ #include "absl/strings/string_view.h" #include "absl/types/span.h" -// NOTE: The functions in this file are test only, and are should not be used in +// NOTE: The functions in this file are test only, and should not be used in // non-test code. namespace absl { @@ -55,15 +55,14 @@ // than `p_fail`. double RequiredSuccessProbability(double p_fail, int num_trials); -// Computes the maximum distance from the mean tolerable, for Z-Tests that are -// expected to pass with `acceptance_probability`. Will terminate if the -// resulting tolerance is zero (due to passing in 0.0 for -// `acceptance_probability` or rounding errors). +// Computes the maximum tolerable Z-score magnitude (in standard errors) for +// two-sided Z-tests expected to pass with `acceptance_probability`. Asserts in +// debug builds that the resulting tolerance is positive. // -// For example, -// MaxErrorTolerance(0.001) = 0.0 -// MaxErrorTolerance(0.5) = ~0.47 -// MaxErrorTolerance(1.0) = inf +// For example: +// MaxErrorTolerance(0.001) ~= 0.00125 +// MaxErrorTolerance(0.5) ~= 0.6745 +// MaxErrorTolerance(1.0) = inf double MaxErrorTolerance(double acceptance_probability); // Approximation to inverse of the Error Function in double precision. @@ -73,7 +72,8 @@ // Beta(p, q) = Gamma(p) * Gamma(q) / Gamma(p+q) double beta(double p, double q); -// The inverse of the normal survival function. +// Inverse of the standard normal survival function: returns z such that +// P(Z > z) = x for x in [0, 1], or NaN outside [0, 1]. double InverseNormalSurvival(double x); // Returns whether actual is "near" expected, based on the bound. @@ -91,19 +91,18 @@ // double BetaIncomplete(double x, double p, double q); -// Implements the inverse of the incomplete regularized beta function, AS109, -// XINBTA. +// Implements the inverse of the incomplete regularized beta function, adapted +// from AS109, XINBTA. // https://www.jstor.org/stable/2346798 // https://www.jstor.org/stable/2346887 // -// BetaIncompleteInv(p, q, beta, alpha) +// BetaIncompleteInv(p, q, alpha) // `p` is beta parameter p, `q` is beta parameter q. // `alpha` is the value of the lower tail area. // -// NOTE: This is a test-only function and, when successful, is only accurate to -// within ~1e-6 of the actual value; there are some cases where it diverges from -// the actual value by much more than that. The function uses Newton's method, -// and thus the runtime is highly variable. +// NOTE: This is a test-only function using modified Newton-Raphson iteration +// over BetaIncomplete(), targeting ~1e-13 relative accuracy where the CDF is +// not flat to double precision. double BetaIncompleteInv(double p, double q, double alpha); } // namespace random_internal
diff --git a/absl/random/internal/distribution_test_util_test.cc b/absl/random/internal/distribution_test_util_test.cc index 1b66879..f614e42 100644 --- a/absl/random/internal/distribution_test_util_test.cc +++ b/absl/random/internal/distribution_test_util_test.cc
@@ -14,13 +14,30 @@ #include "absl/random/internal/distribution_test_util.h" +#include <cmath> +#include <limits> #include <utility> #include <vector> +#include "gmock/gmock.h" #include "gtest/gtest.h" namespace { +using absl::random_internal::BetaIncomplete; +using absl::random_internal::BetaIncompleteInv; +using absl::random_internal::erfinv; +using absl::random_internal::InverseNormalSurvival; +using absl::random_internal::MaxErrorTolerance; +using absl::random_internal::RequiredSuccessProbability; +using ::testing::AllOf; +using ::testing::DoubleEq; +using ::testing::DoubleNear; +using ::testing::Gt; +using ::testing::IsNan; +using ::testing::Le; +using ::testing::Lt; + TEST(TestUtil, InverseErf) { const struct { const double z; @@ -193,4 +210,210 @@ m.variance = 100; EXPECT_NEAR(absl::random_internal::ZScore(-4, m), -10, 1e-12); } + +MATCHER_P4(InvertsBetaIncompleteNear, p, q, expected_alpha, tol, "") { + const double actual_alpha = BetaIncomplete(arg, p, q); + if (std::fabs(actual_alpha - expected_alpha) <= tol) { + return true; + } + *result_listener << "BetaIncomplete(" << arg << ", " << p << ", " << q + << ") = " << actual_alpha << " (expected " << expected_alpha + << ", diff " << std::fabs(actual_alpha - expected_alpha) + << ")"; + return false; +} + +MATCHER_P2(HasNormalSurvivalNear, expected_u, rel_tol, "") { + constexpr double kSqrt1_2 = 0.70710678118654752440084436210485; + const double actual_u = 0.5 * std::erfc(arg * kSqrt1_2); + if (std::fabs(actual_u - expected_u) <= rel_tol * expected_u) { + return true; + } + *result_listener << "normal_survival(" << arg << ") = " << actual_u + << " (expected " << expected_u << ")"; + return false; +} + +TEST(BetaTest, BetaIncompleteInvHighPrecision) { + // Exact closed-form Beta quantiles should invert to near double precision. + EXPECT_THAT(BetaIncompleteInv(2.0, 2.0, 0.028), DoubleNear(0.1, 1e-13)); + EXPECT_THAT(BetaIncompleteInv(2.0, 2.0, 0.216), DoubleNear(0.3, 1e-13)); + EXPECT_THAT(BetaIncompleteInv(2.0, 2.0, 0.784), DoubleNear(0.7, 1e-13)); + EXPECT_THAT(BetaIncompleteInv(2.0, 2.0, 0.972), DoubleNear(0.9, 1e-13)); + EXPECT_THAT(BetaIncompleteInv(1.0, 5.0, 0.67232), DoubleNear(0.2, 1e-13)); + EXPECT_THAT(BetaIncompleteInv(5.0, 2.0, 0.010935), DoubleNear(0.3, 1e-13)); + EXPECT_THAT(BetaIncompleteInv(10.0, 5.0, 0.08978271484375), + DoubleNear(0.5, 1e-13)); + + // Skewed and symmetric distributions at interior and extreme-tail quantiles. + EXPECT_THAT(BetaIncompleteInv(20.0, 5.0, 0.4598773297575791), + DoubleNear(0.8, 1e-13)); + EXPECT_THAT(BetaIncompleteInv(30.0, 10.0, 0.2241297491808366), + DoubleNear(0.7, 1e-13)); + EXPECT_THAT(BetaIncompleteInv(40.0, 20.0, 0.7001783247477069), + DoubleNear(0.7, 1e-13)); + EXPECT_THAT(BetaIncompleteInv(0.5, 0.5, 1e-8), + AllOf(DoubleNear(2.46740110027234e-16, 1e-28), + InvertsBetaIncompleteNear(0.5, 0.5, 1e-8, 1e-20))); + EXPECT_THAT(BetaIncompleteInv(2.0, 5.0, 1e-12), + InvertsBetaIncompleteNear(2.0, 5.0, 1e-12, 1e-24)); + EXPECT_THAT(BetaIncompleteInv(2.0, 5.0, 1.0 - 1e-12), + InvertsBetaIncompleteNear(2.0, 5.0, 1.0 - 1e-12, 1e-13)); + EXPECT_THAT(BetaIncompleteInv(5.0, 2.0, 1e-12), + InvertsBetaIncompleteNear(5.0, 2.0, 1e-12, 1e-24)); + EXPECT_THAT(BetaIncompleteInv(5.0, 2.0, 1.0 - 1e-12), + InvertsBetaIncompleteNear(5.0, 2.0, 1.0 - 1e-12, 1e-13)); + EXPECT_THAT(BetaIncompleteInv(100.0, 100.0, 1e-12), + InvertsBetaIncompleteNear(100.0, 100.0, 1e-12, 1e-24)); + EXPECT_THAT(BetaIncompleteInv(100.0, 100.0, 1.0 - 1e-12), + InvertsBetaIncompleteNear(100.0, 100.0, 1.0 - 1e-12, 1e-13)); + EXPECT_THAT(BetaIncompleteInv(0.1, 10.0, 1e-10), + InvertsBetaIncompleteNear(0.1, 10.0, 1e-10, 1e-22)); + EXPECT_THAT(BetaIncompleteInv(10.0, 0.1, 1e-10), + InvertsBetaIncompleteNear(10.0, 0.1, 1e-10, 1e-22)); + EXPECT_THAT(BetaIncompleteInv(1000.0, 1000.0, 1e-12), + InvertsBetaIncompleteNear(1000.0, 1000.0, 1e-12, 1e-24)); +} + +TEST(BetaTest, BetaIncompleteInvExtremeTailAndUnderflowRegressions) { + const double kMinNormal = std::numeric_limits<double>::min(); + + // Quantiles in [DBL_MIN, DBL_MIN / kErr) where tol = kErr * value < DBL_MIN. + EXPECT_THAT(BetaIncompleteInv(0.001, 1.0, 0.5), + AllOf(DoubleNear(std::ldexp(1.0, -1000), 1e-312), + InvertsBetaIncompleteNear(0.001, 1.0, 0.5, 1e-13))); + EXPECT_THAT(BetaIncompleteInv(0.05, 1.0, 1e-15), + AllOf(DoubleNear(1e-300, 1e-311), + InvertsBetaIncompleteNear(0.05, 1.0, 1e-15, 1e-28))); + EXPECT_THAT(BetaIncompleteInv(0.05, 2.0, 1e-15), + AllOf(Gt(0.0), Lt(1e-299), + InvertsBetaIncompleteNear(0.05, 2.0, 1e-15, 1e-28))); + EXPECT_THAT(BetaIncompleteInv(0.05, 0.05, 1e-15), + AllOf(Gt(0.0), Lt(1e-293), + InvertsBetaIncompleteNear(0.05, 0.05, 1e-15, 1e-28))); + + // Positive initial-estimate underflow branches (both p > 1 && q > 1 and + // t <= 1) clamp to DBL_MIN and converge without stalling. + EXPECT_THAT(BetaIncompleteInv(1.1, 100.0, 1e-300), + AllOf(Gt(0.0), Lt(1e-270), + InvertsBetaIncompleteNear(1.1, 100.0, 1e-300, 1e-312))); + EXPECT_THAT(BetaIncompleteInv(0.05, 2.0, 1e-20), + AllOf(Gt(0.0), Le(kMinNormal))); + EXPECT_THAT(BetaIncompleteInv(0.001, 1.0, 0.48), + AllOf(Gt(0.0), Le(kMinNormal))); + + // Quantiles pressed against 0 / 1 terminate cleanly (including under x87). + EXPECT_THAT(BetaIncompleteInv(1e-5, 1.0, 0.75), AllOf(Gt(0.0), Lt(1e-13))); + EXPECT_THAT(BetaIncompleteInv(1.0, 1e-5, 0.25), + AllOf(Gt(1.0 - 1e-13), Lt(1.0))); +} + +TEST(BetaTest, InvalidAndBoundaryInputs) { + const double kInf = std::numeric_limits<double>::infinity(); + const double kNan = std::numeric_limits<double>::quiet_NaN(); + + EXPECT_THAT(BetaIncomplete(kNan, 1.0, 1.0), IsNan()); + EXPECT_THAT(BetaIncomplete(0.5, kNan, 1.0), IsNan()); + EXPECT_THAT(BetaIncomplete(0.5, 1.0, kNan), IsNan()); + EXPECT_THAT(BetaIncomplete(0.0, kNan, 1.0), IsNan()); + + EXPECT_THAT(BetaIncomplete(0.5, 0.0, 1.0), DoubleEq(kInf)); + EXPECT_THAT(BetaIncomplete(0.5, 1.0, 0.0), DoubleEq(kInf)); + EXPECT_THAT(BetaIncomplete(0.5, -1.0, 1.0), DoubleEq(kInf)); + EXPECT_THAT(BetaIncomplete(0.5, 1.0, -1.0), DoubleEq(kInf)); + EXPECT_THAT(BetaIncomplete(0.5, kInf, 1.0), DoubleEq(kInf)); + EXPECT_THAT(BetaIncomplete(0.5, 1.0, kInf), DoubleEq(kInf)); + EXPECT_THAT(BetaIncomplete(-0.1, 1.0, 1.0), DoubleEq(kInf)); + EXPECT_THAT(BetaIncomplete(1.1, 1.0, 1.0), DoubleEq(kInf)); + EXPECT_THAT(BetaIncomplete(0.0, 0.0, 1.0), DoubleEq(kInf)); + + EXPECT_THAT(BetaIncompleteInv(kNan, 1.0, 0.5), IsNan()); + EXPECT_THAT(BetaIncompleteInv(1.0, kNan, 0.5), IsNan()); + EXPECT_THAT(BetaIncompleteInv(1.0, 1.0, kNan), IsNan()); + EXPECT_THAT(BetaIncompleteInv(kNan, 1.0, 0.0), IsNan()); + + EXPECT_THAT(BetaIncompleteInv(0.0, 1.0, 0.25), DoubleEq(kInf)); + EXPECT_THAT(BetaIncompleteInv(1.0, 0.0, 0.25), DoubleEq(kInf)); + EXPECT_THAT(BetaIncompleteInv(-1.0, 1.0, 0.5), DoubleEq(kInf)); + EXPECT_THAT(BetaIncompleteInv(1.0, -1.0, 0.5), DoubleEq(kInf)); + EXPECT_THAT(BetaIncompleteInv(kInf, 1.0, 0.5), DoubleEq(kInf)); + EXPECT_THAT(BetaIncompleteInv(1.0, kInf, 0.5), DoubleEq(kInf)); + EXPECT_THAT(BetaIncompleteInv(1.0, 1.0, -0.1), DoubleEq(kInf)); + EXPECT_THAT(BetaIncompleteInv(1.0, 1.0, 1.1), DoubleEq(kInf)); + EXPECT_THAT(BetaIncompleteInv(0.0, 1.0, 0.0), DoubleEq(kInf)); +} + +TEST(TestUtil, RequiredSuccessProbabilityAndMaxErrorTolerance) { + const double kInf = std::numeric_limits<double>::infinity(); + + // Small p_fail where naive 1.0 - p_fail loses ~40 bits of precision. + const double p_1e12_100 = RequiredSuccessProbability(1e-12, 100); + EXPECT_THAT(p_1e12_100, AllOf(Lt(1.0), DoubleNear(1.0 - 1e-14, 1e-15))); + EXPECT_THAT(MaxErrorTolerance(p_1e12_100), DoubleNear(7.739358, 1e-4)); + + // When p_fail / num_trials <= 2^-54, RequiredSuccessProbability clamps below + // 1.0 so MaxErrorTolerance remains finite. + const double p_1e12_100k = RequiredSuccessProbability(1e-12, 100000); + EXPECT_THAT(p_1e12_100k, Lt(1.0)); + EXPECT_THAT(MaxErrorTolerance(p_1e12_100k), + AllOf(Gt(8.0), Lt(kInf), DoubleNear(8.292361, 1e-4))); + + const double p_1e15_100 = RequiredSuccessProbability(1e-15, 100); + EXPECT_THAT(p_1e15_100, Lt(1.0)); + EXPECT_THAT(MaxErrorTolerance(p_1e15_100), + AllOf(Gt(8.0), Lt(kInf), DoubleNear(8.292361, 1e-4))); + + EXPECT_THAT(RequiredSuccessProbability(0.0, 100), DoubleEq(1.0)); + EXPECT_THAT(MaxErrorTolerance(1.0), DoubleEq(kInf)); + + // Very small acceptance probability without 1 - p cancellation near 0. + EXPECT_THAT(MaxErrorTolerance(1e-12), + DoubleNear(1.2533141373155002e-12, 1e-20)); +} + +TEST(TestUtil, InverseNormalSurvivalExtremeTailsAndBoundaries) { + const double kInf = std::numeric_limits<double>::infinity(); + const double kNan = std::numeric_limits<double>::quiet_NaN(); + + EXPECT_THAT(InverseNormalSurvival(0.0), DoubleEq(kInf)); + EXPECT_THAT(InverseNormalSurvival(1.0), DoubleEq(-kInf)); + EXPECT_THAT(InverseNormalSurvival(0.5), DoubleEq(0.0)); + EXPECT_THAT(InverseNormalSurvival(-0.1), IsNan()); + EXPECT_THAT(InverseNormalSurvival(1.1), IsNan()); + EXPECT_THAT(InverseNormalSurvival(kNan), IsNan()); + + EXPECT_THAT(InverseNormalSurvival(1e-10), + HasNormalSurvivalNear(1e-10, 1e-12)); + EXPECT_THAT(InverseNormalSurvival(1e-15), + HasNormalSurvivalNear(1e-15, 1e-12)); + EXPECT_THAT(InverseNormalSurvival(std::ldexp(1.0, -54)), + AllOf(DoubleNear(8.292361075813595, 1e-12), + HasNormalSurvivalNear(std::ldexp(1.0, -54), 1e-12))); + EXPECT_THAT(InverseNormalSurvival(1e-20), + HasNormalSurvivalNear(1e-20, 1e-12)); + EXPECT_THAT(InverseNormalSurvival(1e-50), + HasNormalSurvivalNear(1e-50, 1e-12)); + EXPECT_THAT(InverseNormalSurvival(1e-100), + HasNormalSurvivalNear(1e-100, 1e-12)); + EXPECT_THAT(InverseNormalSurvival(1e-300), + HasNormalSurvivalNear(1e-300, 1e-12)); + + // Anti-symmetry across 0.5 using an exact dyadic fraction so 1 - u is exact. + const double kDyadic = std::ldexp(1.0, -33); + EXPECT_THAT(InverseNormalSurvival(1.0 - kDyadic), + DoubleEq(-InverseNormalSurvival(kDyadic))); +} + +TEST(TestUtil, InverseErfBoundaries) { + const double kInf = std::numeric_limits<double>::infinity(); + const double kNan = std::numeric_limits<double>::quiet_NaN(); + + EXPECT_THAT(erfinv(1.0), DoubleEq(kInf)); + EXPECT_THAT(erfinv(-1.0), DoubleEq(-kInf)); + EXPECT_THAT(erfinv(0.0), DoubleEq(0.0)); + EXPECT_THAT(erfinv(1.5), IsNan()); + EXPECT_THAT(erfinv(-1.5), IsNan()); + EXPECT_THAT(erfinv(kNan), IsNan()); +} + } // namespace
diff --git a/absl/random/internal/fastmath_test.cc b/absl/random/internal/fastmath_test.cc index cd33d7a..563bb80 100644 --- a/absl/random/internal/fastmath_test.cc +++ b/absl/random/internal/fastmath_test.cc
@@ -89,9 +89,11 @@ EXPECT_NEAR(StirlingLogFactorial(1.50), 0.284683, 1e-3); EXPECT_NEAR(StirlingLogFactorial(2.0), 0.69314718056, 1e-4); + double log_factorial = 0.0; for (int i = 2; i < 50; i++) { double d = static_cast<double>(i); - EXPECT_NEAR(StirlingLogFactorial(d), std::lgamma(d + 1), 3e-5); + log_factorial += std::log(d); + EXPECT_NEAR(StirlingLogFactorial(d), log_factorial, 3e-5); } }
diff --git a/absl/random/internal/randen_engine.h b/absl/random/internal/randen_engine.h index c2a8f54..91a6025 100644 --- a/absl/random/internal/randen_engine.h +++ b/absl/random/internal/randen_engine.h
@@ -25,6 +25,7 @@ #include <limits> #include <ostream> #include <type_traits> +#include <utility> #include "absl/base/config.h" #include "absl/base/internal/endian.h" @@ -62,7 +63,7 @@ return (std::numeric_limits<result_type>::max)(); } - randen_engine() : randen_engine(0) {} + randen_engine() : randen_engine(result_type{0}) {} explicit randen_engine(result_type seed_value) { seed(seed_value); } template <class SeedSequence, @@ -78,6 +79,9 @@ std::memcpy(state(), other.state(), kStateSizeT * sizeof(result_type)); } randen_engine& operator=(const randen_engine& other) { + if (this == &other) { + return *this; + } next_ = other.next_; impl_ = other.impl_; std::memcpy(state(), other.state(), kStateSizeT * sizeof(result_type)); @@ -103,13 +107,14 @@ reseed(seq); } - void seed(result_type seed_value = 0) { + void seed(result_type seed_value = result_type{0}) { next_ = kStateSizeT; // Zeroes the inner state and fills the outer state with seed_value to // mimic the behaviour of reseed auto* begin = state(); - std::fill(begin, begin + kCapacityT, 0); - std::fill(begin + kCapacityT, begin + kStateSizeT, seed_value); + std::fill(begin, begin + kCapacityT, result_type{0}); + std::fill(begin + kCapacityT, begin + kStateSizeT, + little_endian::FromHost(seed_value)); } // Inserts entropy into (part of) the state. Calling this periodically with @@ -135,13 +140,6 @@ const size_t requested_entropy = (entropy_size == 0) ? 8u : entropy_size; std::fill(buffer + requested_entropy, buffer + kBufferSize, 0); seq.generate(buffer, buffer + requested_entropy); -#ifdef ABSL_IS_BIG_ENDIAN - // Randen expects the seed buffer to be in Little Endian; reverse it on - // Big Endian platforms. - for (sequence_result_type& e : buffer) { - e = absl::little_endian::FromHost(e); - } -#endif // The Randen paper suggests preferentially initializing even-numbered // 128-bit vectors of the randen state (there are 16 such vectors). // The seed data is merged into the state offset by 128-bits, which @@ -162,6 +160,13 @@ } else { seq.generate(buffer, buffer + kBufferSize); } +#ifdef ABSL_IS_BIG_ENDIAN + // Randen expects the seed buffer to be in Little Endian; reverse it on + // Big Endian platforms. + for (sequence_result_type& e : buffer) { + e = absl::little_endian::FromHost(e); + } +#endif impl_.Absorb(buffer, state()); // Generate will be called when operator() is called @@ -169,15 +174,16 @@ } void discard(uint64_t count) { - uint64_t step = std::min<uint64_t>(kStateSizeT - next_, count); + uint64_t step = + (std::min)(static_cast<uint64_t>(kStateSizeT - next_), count); count -= step; constexpr uint64_t kRateT = kStateSizeT - kCapacityT; auto* begin = state(); while (count > 0) { next_ = kCapacityT; - impl_.Generate(*reinterpret_cast<result_type(*)[kStateSizeT]>(begin)); - step = std::min<uint64_t>(kRateT, count); + impl_.Generate(begin); + step = (std::min)(kRateT, count); count -= step; } next_ += step; @@ -255,7 +261,7 @@ // raw state array, manually aligned in state(). This overallocates // by 8 bytes since C++ does not guarantee extended heap alignment. - alignas(8) char raw_state_[Randen::kStateBytes + 8]; + alignas(8) unsigned char raw_state_[Randen::kStateBytes + 8]; size_t next_; // index within state() Randen impl_; };
diff --git a/absl/random/internal/randen_engine_test.cc b/absl/random/internal/randen_engine_test.cc index 5488bd5..73afaf3 100644 --- a/absl/random/internal/randen_engine_test.cc +++ b/absl/random/internal/randen_engine_test.cc
@@ -22,6 +22,7 @@ #include <random> #include <sstream> #include <type_traits> +#include <utility> #include "gtest/gtest.h" #include "absl/log/log.h" @@ -234,6 +235,26 @@ "return type of operator== must be bool"); } +TYPED_TEST(RandenEngineTypedTest, SelfAssignmentPreservesState) { + using randen = typename absl::random_internal::randen_engine<TypeParam>; + + ExplicitSeedSeq seed_sequence{12, 34, 56}; + randen engine(seed_sequence); + engine.discard(5); + randen expected = engine; + + randen* self_ptr = &engine; + engine = *self_ptr; + EXPECT_TRUE(engine == expected); + + engine = std::move(*self_ptr); + EXPECT_TRUE(engine == expected); + + for (int i = 0; i < 16; ++i) { + EXPECT_EQ(engine(), expected()); + } +} + TYPED_TEST(RandenEngineTypedTest, RandenEngineSFINAETest) { using randen = typename absl::random_internal::randen_engine<TypeParam>; using result_type = typename randen::result_type;
diff --git a/absl/random/internal/randen_hwaes.cc b/absl/random/internal/randen_hwaes.cc index b632aa9..291b049 100644 --- a/absl/random/internal/randen_hwaes.cc +++ b/absl/random/internal/randen_hwaes.cc
@@ -134,12 +134,14 @@ using Vector128 = __vector unsigned long long; // NOLINT(runtime/int) namespace { +#if defined(ABSL_IS_LITTLE_ENDIAN) ABSL_TARGET_CRYPTO inline Vector128 ReverseBytes(const Vector128& v) { // Reverses the bytes of the vector. const __vector unsigned char perm = {15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; return vec_perm(v, v, perm); } +#endif // WARNING: these load/store in native byte order. It is OK to load and then // store an unchanged vector, but interpreting the bits as a number or input @@ -159,11 +161,17 @@ return Vector128(__builtin_crypto_vcipher(state, round_key)); } -// Enables native loads in the round loop by pre-swapping. +// Enables native loads in the round loop by pre-swapping on little-endian PPC. +// On big-endian PPC, vec_vsx_ld already loads bytes in the big-endian order +// expected by __builtin_crypto_vcipher. ABSL_TARGET_CRYPTO inline void SwapEndian(absl::uint128* state) { +#if defined(ABSL_IS_LITTLE_ENDIAN) for (uint32_t block = 0; block < RandenTraits::kFeistelBlocks; ++block) { Vector128Store(ReverseBytes(Vector128Load(state + block)), state + block); } +#else + (void)state; +#endif } } // namespace @@ -418,7 +426,7 @@ ABSL_TARGET_CRYPTO const void* RandenHwAes::GetKeys() { // Round keys for one AES per Feistel round and branch. // The canonical implementation uses first digits of Pi. -#if defined(ABSL_ARCH_PPC) +#if defined(ABSL_ARCH_PPC) && defined(ABSL_IS_LITTLE_ENDIAN) return kRandenRoundKeysBE; #else return kRandenRoundKeys;
diff --git a/absl/random/internal/randen_slow.cc b/absl/random/internal/randen_slow.cc index 12aa4b1..f8dd87c 100644 --- a/absl/random/internal/randen_slow.cc +++ b/absl/random/internal/randen_slow.cc
@@ -346,14 +346,14 @@ // per 16 bytes (vs. 10 for AES-CTR). Computing eight round functions in // parallel hides the 7-cycle AESNI latency on HSW. Note that the Feistel // XORs are 'free' (included in the second AES instruction). -ABSL_ATTRIBUTE_ALWAYS_INLINE inline const absl::uint128* FeistelRound( +ABSL_ATTRIBUTE_ALWAYS_INLINE inline const uint8_t* FeistelRound( absl::uint128* ABSL_RANDOM_INTERNAL_RESTRICT state, - const absl::uint128* ABSL_RANDOM_INTERNAL_RESTRICT keys) { + const uint8_t* ABSL_RANDOM_INTERNAL_RESTRICT keys) { for (size_t branch = 0; branch < RandenTraits::kFeistelBlocks; branch += 4) { const Vector128 s0 = Vector128Load(state + branch); const Vector128 s1 = Vector128Load(state + branch + 1); const Vector128 f0 = AesRound(s0, Vector128Load(keys)); - keys++; + keys += sizeof(Vector128); const Vector128 o1 = AesRound(f0, s1); Vector128Store(o1, state + branch + 1); @@ -361,7 +361,7 @@ const Vector128 s2 = Vector128Load(state + branch + 2); const Vector128 s3 = Vector128Load(state + branch + 3); const Vector128 f2 = AesRound(s2, Vector128Load(keys)); - keys++; + keys += sizeof(Vector128); const Vector128 o3 = AesRound(f2, s3); Vector128Store(o3, state + branch + 3); } @@ -373,8 +373,7 @@ // 2^64 queries if the round function is a PRF. This is similar to the b=8 case // of Simpira v2, but more efficient than its generic construction for b=16. ABSL_ATTRIBUTE_ALWAYS_INLINE inline void Permute( - absl::uint128* state, - const absl::uint128* ABSL_RANDOM_INTERNAL_RESTRICT keys) { + absl::uint128* state, const uint8_t* ABSL_RANDOM_INTERNAL_RESTRICT keys) { for (size_t round = 0; round < RandenTraits::kFeistelRounds; ++round) { keys = FeistelRound(state, keys); BlockShuffle(state); @@ -414,30 +413,38 @@ } void RandenSlow::Absorb(const void* seed_void, void* state_void) { - auto* state = - reinterpret_cast<uint64_t * ABSL_RANDOM_INTERNAL_RESTRICT>(state_void); - const auto* seed = - reinterpret_cast<const uint64_t * ABSL_RANDOM_INTERNAL_RESTRICT>( - seed_void); + uint8_t* ABSL_RANDOM_INTERNAL_RESTRICT state_bytes = + static_cast<uint8_t*>(state_void); + const uint8_t* ABSL_RANDOM_INTERNAL_RESTRICT seed_bytes = + static_cast<const uint8_t*>(seed_void); - constexpr size_t kCapacityBlocks = - RandenTraits::kCapacityBytes / sizeof(uint64_t); - static_assert( - kCapacityBlocks * sizeof(uint64_t) == RandenTraits::kCapacityBytes, - "Not i*V"); + static_assert(RandenTraits::kCapacityBytes % sizeof(uint64_t) == 0, + "kCapacityBytes must be a multiple of 8"); + static_assert(RandenTraits::kStateBytes % sizeof(uint64_t) == 0, + "kStateBytes must be a multiple of 8"); - for (size_t i = kCapacityBlocks; - i < RandenTraits::kStateBytes / sizeof(uint64_t); ++i) { - state[i] ^= seed[i - kCapacityBlocks]; + for (size_t offset = RandenTraits::kCapacityBytes; + offset < RandenTraits::kStateBytes; offset += sizeof(uint64_t)) { + uint64_t s; + uint64_t k; + std::memcpy(&s, state_bytes + offset, sizeof(s)); + std::memcpy(&k, seed_bytes + (offset - RandenTraits::kCapacityBytes), + sizeof(k)); + s ^= k; + std::memcpy(state_bytes + offset, &s, sizeof(s)); } } void RandenSlow::Generate(const void* keys_void, void* state_void) { static_assert(RandenTraits::kCapacityBytes == sizeof(absl::uint128), "Capacity mismatch"); + static_assert(RandenTraits::kFeistelBlocks * sizeof(absl::uint128) == + RandenTraits::kStateBytes, + "State size mismatch"); - auto* state = reinterpret_cast<absl::uint128*>(state_void); - const auto* keys = reinterpret_cast<const absl::uint128*>(keys_void); + alignas(16) absl::uint128 state[RandenTraits::kFeistelBlocks]; + std::memcpy(state, state_void, sizeof(state)); + const auto* keys = static_cast<const uint8_t*>(keys_void); const absl::uint128 prev_inner = state[0]; @@ -448,7 +455,8 @@ SwapEndian(state); // Ensure backtracking resistance. - *state ^= prev_inner; + state[0] ^= prev_inner; + std::memcpy(state_void, state, sizeof(state)); } } // namespace random_internal