[libcxx-commits] [libcxx] [libc++] Fix UB in bitwise logic of {std, ranges}::{fill, fill_n} algorithms (PR #122410)

Peng Liu via libcxx-commits libcxx-commits at lists.llvm.org
Mon Jan 20 13:17:53 PST 2025


================
@@ -55,6 +59,25 @@ struct __size_difference_type_traits<_Cp, __void_t<typename _Cp::difference_type
   using size_type       = typename _Cp::size_type;
 };
 
+// This function is designed to operate correctly even for smaller integral types like `uint8_t`, `uint16_t`,
+// or `unsigned short`. Casting back to _StorageType is crucial to prevent undefined behavior that can arise
+// from integral promotions.
+// See https://github.com/llvm/llvm-project/pull/122410
+template <class _StoragePointer,
+          __enable_if_t<is_unsigned<typename pointer_traits<_StoragePointer>::element_type>::value, int> >
+_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 void
+__fill_masked_range(_StoragePointer __word, unsigned __ctz, unsigned __clz, bool __fill_val) {
----------------
winner245 wrote:

>  If you do find that we're missing coverage and add some tests, I'd like to have another quick look before merging.

Yes, the bitwise optimization algorithms do lack some tests. Current tests for `{fill, fill_n, find}` are only limited to 1-2 bytes, which is less than one word (generally 8 bytes). Therefore, I've added new tests for `{fill, fill_n, find}` in #121209 to cover tests for more than 1 word. 

Additionally, I've refactored existing tests for other bitwise optimization algorithms to remove redundant code. See #120909 and #121138. 

These PRs were submitted prior to the current one. The purpose of these tests is to facilitate subsequent work on optimizing the algorithms for `vector<bool>::iterator`.

https://github.com/llvm/llvm-project/pull/122410


More information about the libcxx-commits mailing list