Commit Graph

6933 Commits

Author SHA1 Message Date
Glen Joseph Fernandes
15139af6fb libstdc++: Fix overflow handling in std::align
libstdc++-v3/ChangeLog:

	* include/bits/align.h (align): Fix overflow handling.
	* testsuite/20_util/align/3.cc: New test.
2020-09-22 17:49:48 +01:00
Jonathan Wakely
160061ac10 libstdc++: Introduce new headers for C++20 ranges components
This introduces two new headers:

<bits/ranges_base.h> defines the minimal components needed
for using C++20 ranges (customization point objects such as
std::ranges::begin, concepts such as std::ranges::range, etc.)

<bits/ranges_util.h> includes <bits/ranges_base.h> and additionally
defines subrange, which is needed by <bits/ranges_algo.h>.

Most of the content of <bits/ranges_base.h> was previously defined in
<bits/range_access.h>, but a few pieces were only defined in <ranges>.
This meant the entire <ranges> header was needed in <algorithm> and
<memory>, even though they don't use all the range adaptors.

By moving the ranges components out of <bits/range_access.h> that file
is left defining just the contents of [iterator.range] i.e. std::begin,
std::end, std::size etc. and not C++20 ranges components.

For consistency with other C++20 ranges headers, <bits/range_cmp.h> is
renamed to <bits/ranges_cmp.h>.

libstdc++-v3/ChangeLog:

	* include/Makefile.am: Add new headers and adjust for renamed
	header.
	* include/Makefile.in: Regenerate.
	* include/bits/iterator_concepts.h: Adjust for renamed header.
	* include/bits/range_access.h (ranges::*): Move to new
	<bits/ranges_base.h> header.
	* include/bits/ranges_algobase.h: Include new <bits/ranges_base.h>
	header instead of <ranges>.
	* include/bits/ranges_algo.h: Include new <bits/ranges_util.h>
	header.
	* include/bits/range_cmp.h: Moved to...
	* include/bits/ranges_cmp.h: ...here.
	* include/bits/ranges_base.h: New header.
	* include/bits/ranges_util.h: New header.
	* include/experimental/string_view: Include new
	<bits/ranges_base.h> header.
	* include/std/functional: Adjust for renamed header.
	* include/std/ranges (ranges::view_base, ranges::enable_view)
	(ranges::dangling, ranges::borrowed_iterator_t): Move to new
	<bits/ranges_base.h> header.
	(ranges::view_interface, ranges::subrange)
	(ranges::borrowed_subrange_t): Move to new <bits/ranges_util.h>
	header.
	* include/std/span: Include new <bits/ranges_base.h> header.
	* include/std/string_view: Likewise.
	* testsuite/24_iterators/back_insert_iterator/pr93884.cc: Add
	missing <ranges> header.
	* testsuite/24_iterators/front_insert_iterator/pr93884.cc:
	Likewise.
2020-09-22 15:45:54 +01:00
Jonathan Wakely
7825399092 libstdc++: Use correct argument type for __use_alloc, again [PR 96803]
While backporting 5494edae83 I noticed
that it's still not correct. I made the allocator-extended constructor
use the right type for the uses-allocator construction detection, but I
used an rvalue when it should be a const lvalue.

This should fix it properly this time.

libstdc++-v3/ChangeLog:

	PR libstdc++/96803
	* include/std/tuple
	(_Tuple_impl(allocator_arg_t, Alloc, const _Tuple_impl<U...>&)):
	Use correct value category in __use_alloc call.
	* testsuite/20_util/tuple/cons/96803.cc: Check with constructors
	that require correct value category to be used.
2020-09-22 08:42:18 +01:00
Patrick Palka
37edf28c24 libstdc++: Remove overzealous static_asserts from std::span
For a span with statically empty extent, we currently model the
preconditions of front(), back(), and operator[] as if they are
mandates, by using a static_assert to verify that extent != 0.  This
causes us to reject valid programs that would instantiate these member
functions and at runtime never call them.

Since they are already followed by more general runtime asserts, this
patch just removes these static_asserts altogether,

libstdc++-v3/ChangeLog:

	* include/std/span (span::front): Remove static_assert.
	(span::back): Likewise.
	(span::operator[]): Likewise.
	* testsuite/23_containers/span/back_neg.cc: Rewrite to verify
	that we check the preconditions of back() only when it's called.
	* testsuite/23_containers/span/front_neg.cc: Likewise for
	front().
	* testsuite/23_containers/span/index_op_neg.cc: Likewise for
	operator[].
2020-09-21 23:21:34 -04:00
Patrick Palka
813ad9c4dd libstdc++: Fix division by zero in std::sample
This fixes a division by zero in the selection-sampling std::__sample
overload when the input range is empty (and hence __unsampled_sz is 0).

libstdc++-v3/ChangeLog:

	* include/bits/stl_algo.h (__sample): Exit early when the
	input range is empty.
	* testsuite/25_algorithms/sample/3.cc: New test.
2020-09-21 20:48:23 -04:00
Patrick Palka
f017952d31 libstdc++: Mark some more algorithms constexpr for C++20
As per P0202.

libstdc++-v3/ChangeLog:

	* include/bits/stl_algo.h (for_each_n): Mark constexpr for C++20.
	(search): Likewise for the overload that takes a searcher.
	* testsuite/25_algorithms/for_each/constexpr.cc: Test constexpr
	std::for_each_n.
	* testsuite/25_algorithms/search/constexpr.cc: Test constexpr
	std::search overload that takes a searcher.
2020-09-21 20:48:17 -04:00
Jonathan Wakely
7db5967f10 libstdc++: Use __builtin_expect in __glibcxx_assert
libstdc++-v3/ChangeLog:

	* include/bits/c++config (__replacement_assert): Add noreturn
	attribute.
	(__glibcxx_assert_impl): Use __builtin_expect to hint that the
	assertion is expected to pass.
2020-09-21 23:43:25 +01:00
Jonathan Wakely
aecea4158f libstdc++: Fix constraints for drop_view::begin() const [LWG 3482]
libstdc++-v3/ChangeLog:

	* include/std/ranges (drop_view::begin()): Adjust constraints
	to match the correct condition for O(1) ranges::next (LWG 3482).
	* testsuite/std/ranges/adaptors/drop.cc: Check that iterator is
	cached for non-sized_range.
2020-09-21 23:43:25 +01:00
Jonathan Wakely
2ec58cfcea libstdc++: Relax constraints on transform_view and elements_view iterators
libstdc++-v3/ChangeLog:

	* include/std/ranges (transform_view, elements_view): Relax
	constraints on operator- for iterators, as per LWG 3483.
	* testsuite/std/ranges/adaptors/elements.cc: Check that we
	can take the difference of two iterators from a non-random
	access range.
	* testsuite/std/ranges/adaptors/transform.cc: Likewise.
2020-09-21 14:30:38 +01:00
Jonathan Wakely
f10ed928e2 libstdc++: Make std::assume_aligned a constexpr function [PR 97132]
The cast from void* to T* in std::assume_aligned is not valid in a
constexpr function. The optimization hint is redundant during constant
evaluation anyway (the compiler can see the object and knows its
alignment). Simply return the original pointer without applying the
__builtin_assume_aligned hint to it when doing constant evaluation.

This change also removes the preprocessor branch that works around
uintptr_t not being available. We already assume that type is present
elsewhere in the library.

libstdc++-v3/ChangeLog:

	PR libstdc++/97132
	* include/bits/align.h (align) [!_GLIBCXX_USE_C99_STDINT_TR1]:
	Remove unused code.
	(assume_aligned): Do not use __builtin_assume_aligned during
	constant evaluation.
	* testsuite/20_util/assume_aligned/1.cc: Improve test.
	* testsuite/20_util/assume_aligned/97132.cc: New test.
2020-09-21 14:28:58 +01:00
Jonathan Wakely
3c755b428e libstdc++: Fix noexcept-specifier for std::bind_front [PR 97101]
libstdc++-v3/ChangeLog:

	PR libstdc++/97101
	* include/std/functional (bind_front): Fix order of parameters
	in is_nothrow_constructible_v specialization.
	* testsuite/20_util/function_objects/bind_front/97101.cc: New test.
2020-09-21 00:17:02 +01:00
Thomas Rodgers
64064678d6 libstdc++: only pull in bits/align.h if C++11 or later
libstdc++-v3/ChangeLog:

	* include/std/memory: Move #include <bits/align.h> inside C++11
	conditional includes.
2020-09-11 14:08:13 -07:00
Thomas Rodgers
2c3b1c5f95 libstdc++: Split std::align/assume_aligned to bits/align.h
We would like to be able to use std::align and std::assume_aligned
without pulling in everything in <memory>.

libstdc++-v3/ChangeLog:

	* include/Makefile.am (bits_headers): Add new header.
	* include/Makefile.in: Regenerate.
	* include/bits/align.h: New file.
	* include/std/memory (align): Move definition to bits/align.h.
	(assume_aligned): Likewise.
2020-09-11 13:13:12 -07:00
Jonathan Wakely
53ad6b1979 libstdc++: Fix chrono::__detail::ceil to work with C++11
In C++11 constexpr functions can only have a return statement, so we
need to fix __detail::ceil to make it valid in C++11. This can be done
by moving the comparison and increment into a new function, __ceil_impl,
and calling that with the result of the duration_cast.

This would mean the standard C++17 std::chrono::ceil function would make
two further calls, which would add too much overhead when not inlined.
For C++17 and later use a using-declaration to add chrono::ceil to
namespace __detail. For C++11 and C++14 define chrono::__detail::__ceil
as a C++11-compatible constexpr function template.

libstdc++-v3/ChangeLog:

	* include/std/chrono [C++17] (chrono::__detail::ceil): Add
	using declaration to make chrono::ceil available for internal
	use with a consistent name.
	(chrono::__detail::__ceil_impl): New function template.
	(chrono::__detail::ceil): Use __ceil_impl to compare and
	increment the value. Remove SFINAE constraint.
2020-09-11 19:59:11 +01:00
Jonathan Wakely
29216f56d0 libstdc++: Fix build error in <bits/regex_error.h>
libstdc++-v3/ChangeLog:

	* include/bits/regex_error.h (__throw_regex_error): Fix
	parameter declaration and use reserved attribute names.
2020-09-11 14:52:40 +01:00
Mike Crowe
e05ff30078 libstdc++: Avoid rounding errors on custom clocks in condition_variable
The fix for PR68519 in 83fd5e73b3 only
applied to condition_variable::wait_for. This problem can also apply to
condition_variable::wait_until but only if the custom clock is using a
more recent epoch so that a small enough delta can be calculated. let's
use the newly-added chrono::__detail::ceil to fix this and also make use
of that function to simplify the previous wait_for fixes.

Also, simplify the existing test case for PR68519 a little and make its
variables local so we can add a new test case for the above problem.
Unfortunately, the test would have only started failing if sufficient
time has passed since the chrono::steady_clock epoch had passed anyway,
but it's better than nothing.

libstdc++-v3/ChangeLog:

	* include/std/condition_variable (condition_variable::wait_until):
	Convert delta to steady_clock duration before adding to current
	steady_clock time to avoid rounding errors described in PR68519.
	(condition_variable::wait_for): Simplify calculation of absolute
	time by using chrono::__detail::ceil in both overloads.
	* testsuite/30_threads/condition_variable/members/68519.cc:
	(test_wait_for): Renamed from test01. Replace unassigned val
	variable with constant false. Reduce scope of mx and cv
	variables to just test_wait_for function.
	(test_wait_until): Add new test case.
2020-09-11 14:28:50 +01:00
Mike Crowe
f9ddb696a2 libstdc++: Avoid rounding errors in std::future::wait_* [PR 91486]
Convert the specified duration to the target clock's duration type
before adding it to the current time in
__atomic_futex_unsigned::_M_load_when_equal_for and
_M_load_when_equal_until.  This removes the risk of the timeout being
rounded down to the current time resulting in there being no wait at all
when the duration type lacks sufficient precision to hold the
steady_clock current time.

Rather than using the style of fix from PR68519, let's expose the C++17
std::chrono::ceil function as std::chrono::__detail::ceil so that it can
be used in code compiled with earlier standards versions and simplify
the fix. This was suggested by John Salmon in
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=91486#c5 .

This problem has become considerably less likely to trigger since I
switched the __atomic__futex_unsigned::__clock_t reference clock from
system_clock to steady_clock and added the loop, but the consequences of
triggering it have changed too.

By my calculations it takes just over 194 days from the epoch for the
current time not to be representable in a float. This means that
system_clock is always subject to the problem (with the standard 1970
epoch) whereas steady_clock with float duration only runs out of
resolution machine has been running for that long (assuming the Linux
implementation of CLOCK_MONOTONIC.)

The recently-added loop in
__atomic_futex_unsigned::_M_load_when_equal_until turns this scenario
into a busy wait.

Unfortunately the combination of both of these things means that it's
not possible to write a test case for this occurring in
_M_load_when_equal_until as it stands.

libstdc++-v3/ChangeLog:

	PR libstdc++/91486
	* include/bits/atomic_futex.h
	(__atomic_futex_unsigned::_M_load_when_equal_for)
	(__atomic_futex_unsigned::_M_load_when_equal_until): Use
	__detail::ceil to convert delta to the reference clock
	duration type to avoid resolution problems.
	* include/std/chrono (__detail::ceil): Move implementation
	of std::chrono::ceil into private namespace so that it's
	available to pre-C++17 code.
	* testsuite/30_threads/async/async.cc (test_pr91486):
	Test __atomic_futex_unsigned::_M_load_when_equal_for.
2020-09-11 14:28:50 +01:00
Mike Crowe
b9faa3301c libstdc++: Loop when futex waits against arbitrary clock
If std::future::wait_until is passed a time point measured against a
clock that is neither std::chrono::steady_clock nor
std::chrono::system_clock then the generic implementation of
__atomic_futex_unsigned::_M_load_when_equal_until is called which
calculates the timeout based on __clock_t and calls the
_M_load_when_equal_until method for that clock to perform the actual
wait.

There's no guarantee that __clock_t is running at the same speed as the
caller's clock, so if the underlying wait times out timeout we need to
check the timeout against the caller's clock again before potentially
looping.

Also add two extra tests to the testsuite's async.cc:

* run test03 with steady_clock_copy, which behaves identically to
  chrono::steady_clock, but isn't chrono::steady_clock. This causes
  the overload of __atomic_futex_unsigned::_M_load_when_equal_until
  that takes an arbitrary clock to be called.

* invent test04 which uses a deliberately slow running clock in order
  to exercise the looping behaviour of
  __atomic_futex_unsigned::_M_load_when_equal_until described above.

libstdc++-v3/ChangeLog:

	* include/bits/atomic_futex.h
	(__atomic_futex_unsigned::_M_load_when_equal_until): Add
	loop on generic _Clock to check the timeout against _Clock
	again after _M_load_when_equal_until returns indicating a
	timeout.
	* testsuite/30_threads/async/async.cc: Invent slow_clock
	that runs at an eleventh of steady_clock's speed. Use it
	to test the user-supplied-clock variant of
	__atomic_futex_unsigned::_M_load_when_equal_until works
	generally with test03 and loops correctly when the timeout
	time hasn't been reached in test04.
2020-09-11 14:28:50 +01:00
Mike Crowe
87fce1923f libstdc++: Use std::chrono::steady_clock as atomic_futex reference clock
The user-visible effect of this change is that std::future::wait_for now
uses std::chrono::steady_clock to determine the timeout.  This makes it
immune to changes made to the system clock.  It also means that anyone
using their own clock types with std::future::wait_until will have the
timeout converted to std::chrono::steady_clock rather than
std::chrono::system_clock.

Now that use of both std::chrono::steady_clock and
std::chrono::system_clock are correctly supported for the wait timeout, I
believe that std::chrono::steady_clock is a better choice for the reference
clock that all other clocks are converted to since it is guaranteed to
advance steadily.  The previous behaviour of converting to
std::chrono::system_clock risks timeouts changing dramatically when the
system clock is changed.

libstdc++-v3/ChangeLog:

	* include/bits/atomic_futex.h (__atomic_futex_unsigned): Change
	__clock_t typedef to use steady_clock so that unknown clocks are
	synced to it rather than system_clock. Change existing __clock_t
	overloads of _M_load_and_text_until_impl and
	_M_load_when_equal_until to use system_clock explicitly. Remove
	comment about DR 887 since these changes address that problem as
	best as we currently able.
2020-09-11 14:28:24 +01:00
Mike Crowe
01d412ef36 libstdc++: Support futex waiting on chrono::steady_clock directly
The user-visible effect of this change is for std::future::wait_until to
use CLOCK_MONOTONIC when passed a timeout of std::chrono::steady_clock
type.  This makes it immune to any changes made to the system clock
CLOCK_REALTIME.

Add an overload of __atomic_futex_unsigned::_M_load_and_text_until_impl
that accepts a std::chrono::steady_clock, and correctly passes this
through to __atomic_futex_unsigned_base::_M_futex_wait_until_steady
which uses CLOCK_MONOTONIC for the timeout within the futex system call.
These functions are mostly just copies of the std::chrono::system_clock
versions with small tweaks.

Prior to this commit, a std::chrono::steady timeout would be converted
via std::chrono::system_clock which risks reducing or increasing the
timeout if someone changes CLOCK_REALTIME whilst the wait is happening.
(The commit immediately prior to this one increases the window of
opportunity for that from a short period during the calculation of a
relative timeout, to the entire duration of the wait.)

FUTEX_WAIT_BITSET was added in kernel v2.6.25.  If futex reports ENOSYS
to indicate that this operation is not supported then the code falls
back to using clock_gettime(2) to calculate a relative time to wait for.

I believe that I've added this functionality in a way that it doesn't
break ABI compatibility, but that has made it more verbose and less type
safe.  I believe that it would be better to maintain the timeout as an
instance of the correct clock type all the way down to a single
_M_futex_wait_until function with an overload for each clock.  The
current scheme of separating out the seconds and nanoseconds early risks
accidentally calling the wait function for the wrong clock.
Unfortunately, doing this would break code that compiled against the old
header.

libstdc++-v3/ChangeLog:

	* config/abi/pre/gnu.ver: Update for addition of
	__atomic_futex_unsigned_base::_M_futex_wait_until_steady.
	* include/bits/atomic_futex.h (__atomic_futex_unsigned_base):
	Add comments to clarify that _M_futex_wait_until and
	_M_load_and_test_until use CLOCK_REALTIME.
	(__atomic_futex_unsigned_base::_M_futex_wait_until_steady)
	(__atomic_futex_unsigned_base::_M_load_and_text_until_steady):
	New member functions that use CLOCK_MONOTONIC.
	(__atomic_futex_unsigned_base::_M_load_and_test_until_impl)
	(__atomic_futex_unsigned_base::_M_load_when_equal_until): Add
	overloads that accept a steady_clock time_point and use the
	new member functions.
	* src/c++11/futex.cc: Include headers required for
	clock_gettime.
	(futex_clock_monotonic_flag): New constant to tell futex to
	use CLOCK_MONOTONIC to match existing futex_clock_realtime_flag.
	(futex_clock_monotonic_unavailable): New global to store the
	result of trying to use CLOCK_MONOTONIC.
	(__atomic_futex_unsigned_base::_M_futex_wait_until_steady): Add
	new variant of _M_futex_wait_until that uses CLOCK_MONOTONIC to
	support waiting using steady_clock.
2020-09-11 14:25:00 +01:00
Christophe Lyon
b32d2ea8c2 libstdc++-v3/include/bits/regex_error.h: Avoid warning with -fno-exceptions.
When building with -fno-exceptions, __GLIBCXX_THROW_OR_ABORT expands to
abort(), causing warnings:
unused parameter '__ecode'
unused parameter '__what'

This patch adds __attribute__((unused)) to avoid them.

2020-09-11  Torbjörn SVENSSON <torbjorn.svensson@st.com>
	    Christophe Lyon  <christophe.lyon@linaro.org>

	libstdc++-v3/
	* include/bits/regex_error.h: Avoid warning with -fno-exceptions.
2020-09-11 13:00:13 +00:00
Jonathan Wakely
1d5589d11e libstdc++: Fix -Wsign-compare warnings
libstdc++-v3/ChangeLog:

	* include/bits/locale_conv.h (__do_str_codecvt, __str_codecvt_in_all):
	Add casts to compare types of the same signedness.
2020-09-10 18:57:39 +01:00
Jonathan Wakely
866c53cb2e libstdc++: Fix -Wunused-local-typedefs warning
libstdc++-v3/ChangeLog:

	* include/bits/ranges_algobase.h (__equal_fn): Remove unused
	typedef.
2020-09-10 18:57:05 +01:00
Jonathan Wakely
f903c13ce8 libstdc++: Fix macro redefinition warnings
Including <version> after <iterator> gives a warning about redefining
the __cpp_lib_array_constexpr macro. What happens is that <iterator>
sets the C++20 value, then <version> redefines it to the C++17 value,
then undefines it and defines it again to the C++20 value.

This change avoids defining it to the C++17 value when compiling C++20
or later (which also means we no longer need the #undef).

A similar warning happens for __cpp_lib_constexpr_char_traits when
including <version> after any header that includes <bits/char_traits.h>.

libstdc++-v3/ChangeLog:

	* include/std/version (__cpp_lib_array_constexpr):
	(__cpp_lib_constexpr_char_traits): Only define C++17 value when
	compiling C++17.
2020-09-10 18:51:24 +01:00
Jonathan Wakely
0943b55817 libstdc++: Fix -Wdeprecated-declarations warnings
libstdc++-v3/ChangeLog:

	* include/experimental/bits/shared_ptr.h (shared_ptr(auto_ptr&&))
	(operator=(auto_ptr&&)): Add diagnostic pragmas to suppress
	warnings for uses of std::auto_ptr.
	* include/experimental/type_traits (is_literal_type_v):
	Likewise, for use of std::is_literal_type.
	* include/std/condition_variable (condition_variable_any::_Unlock):
	Likewise, for use of std::uncaught_exception.
2020-09-10 18:48:25 +01:00
Jonathan Wakely
b6b9fd4af9 libstdc++: Fix -Wnarrowing warnings
libstdc++-v3/ChangeLog:

	* include/bits/fs_path.h (path::_List::type()): Avoid narrowing
	conversion.
	* include/std/chrono (operator+(const year&, const years&)):
	Likewise.
2020-09-10 18:47:08 +01:00
Jonathan Wakely
36efcd7de0 libstdc++: Fix some -Wunused-parameter warnings
libstdc++-v3/ChangeLog:

	* include/bits/codecvt.h (codecvt_byname): Remove names of
	unused parameters.
2020-09-10 17:09:16 +01:00
Jonathan Wakely
b84b132e38 libstdc++: Clean up inconsistent whitespace
libstdc++-v3/ChangeLog:

	* include/bits/locale_facets_nonio.tcc: Adjust whitespace.
2020-09-10 17:09:16 +01:00
Krystian Kuźniarek
ef8b4335d9 libstdc++: Add parentheses around assignments used as truth values
libstdc++-v3/ChangeLog:

	* include/c_global/cmath (__lerp): Avoid -Wparentheses warnings.
2020-09-10 17:09:16 +01:00
Krystian Kuźniarek
2b4cc19bd5 libstdc++: Add unused attributes to suppress warnings
libstdc++-v3/ChangeLog:

	* include/bits/atomic_base.h: Fix -Wunused-variable
	warnings.
	* include/ext/new_allocator.h: Fix -Wunused-parameter
	warnings.
2020-09-10 17:09:15 +01:00
Jonathan Wakely
afea21f961 libstdc++: Enforce LWG 3472 preconditions on std::counted_iterator
libstdc++-v3/ChangeLog:

	* include/bits/stl_iterator.h (counted_iterator): Add assertions
	to check preconditions added by LWG 3472.
2020-09-10 17:09:15 +01:00
Jonathan Wakely
1e718ec51a libstdc++: Reduce monotonic_buffer_resource overallocation [PR 96942]
The primary reason for this change is to reduce the size of buffers
allocated by std::pmr::monotonic_buffer_resource. Previously, a new
buffer would always add the size of the linked list node (11 bytes) and
then round up to the next power of two. This results in a huge increase
if the expected size of the next buffer is already a power of two. For
example, if the resource is constructed with a desired initial size of
4096 the first buffer it allocates will be std::bit_ceil(4096+11) which
is 8192.  If the user has carefully selected the initial size to match
their expected memory requirements then allocating double that amount
wastes a lot of memory.

After this patch the allocated size will be rounded up to a 64-byte
boundary, instead of to a power of two. This means for an initial size
of 4096 only 4160 bytes get allocated.

Previously only the base-2 logarithm of the size was stored, which could
be stored in a single 8-bit integer. Now that the size isn't always a
power of two we need to use more bits to store it. As the size is always
a multiple of 64 the low six bits are not needed, and so we can use the
same approach that the pool resources already use of storing the base-2
logarithm of the alignment in the low bits that are not used for the
size. To avoid code duplication, a new aligned_size<N> helper class is
introduced by this patch, which is then used by both the pool resources'
big_block type and the monotonic_buffer_resource::_Chunk type.

Originally the big_block type used two bit-fields to store the size and
alignment in the space of a single size_t member. The aligned_size type
uses a single size_t member and uses masks and bitwise operations to
manipulate the size and alignment values. This results in better code
than the old version, because the bit-fields weren't optimally ordered
for little endian architectures, so the alignment was actually stored in
the high bits, not the unused low bits, requiring additional shifts to
calculate the values. Using bitwise operations directly avoids needing
to reorder the bit-fields depending on the endianness.

While adapting the _Chunk and big_block types to use aligned_size<N> I
also added checks for size overflows (technically, unsigned wraparound).
The memory resources now ensure that when they require an allocation
that is too large to represent in size_t they will request SIZE_MAX
bytes from the upstream resource, rather than requesting a small value
that results from wrapround. The testsuite is enhanced to verify this.

libstdc++-v3/ChangeLog:

	PR libstdc++/96942
	* include/std/memory_resource (monotonic_buffer_resource::do_allocate):
	Use __builtin_expect when checking if a new buffer needs to be
	allocated from the upstream resource, and for checks for edge
	cases like zero sized buffers and allocations.
	* src/c++17/memory_resource.cc (aligned_size): New class template.
	(aligned_ceil): New helper function to round up to a given
	alignment.
	(monotonic_buffer_resource::chunk): Replace _M_size and _M_align
	with an aligned_size member. Remove _M_canary member. Change _M_next
	to pointer instead of unaligned buffer.
	(monotonic_buffer_resource::chunk::allocate): Round up to multiple
	of 64 instead of to power of two. Check for size overflow. Remove
	redundant check for minimum required alignment.
	(monotonic_buffer_resource::chunk::release): Adjust for changes
	to data members.
	(monotonic_buffer_resource::_M_new_buffer): Use aligned_ceil.
	(big_block): Replace _M_size and _M_align with aligned_size
	member.
	(big_block::big_block): Check for size overflow.
	(big_block::size, big_block::align): Adjust to use aligned_size.
	(big_block::alloc_size): Use aligned_ceil.
	(munge_options): Use aligned_ceil.
	(__pool_resource::allocate): Use big_block::align for alignment.
	* testsuite/20_util/monotonic_buffer_resource/allocate.cc: Check
	upstream resource gets expected values for impossible sizes.
	* testsuite/20_util/unsynchronized_pool_resource/allocate.cc:
	Likewise. Adjust checks for expected alignment in existing test.
2020-09-10 15:41:53 +01:00
Jonathan Wakely
ec5096f48b libstdc++: Simplify chrono::duration::_S_gcd
We can simplify this constexpr function further because we know that
period::num >= 1 and period::den >= 1 so only the remainder can ever be
zero.

libstdc++-v3/ChangeLog:

	* include/std/chrono (duration::_S_gcd): Use invariant that
	neither value is zero initially.
2020-09-07 20:09:17 +01:00
Jonathan Wakely
00ffe73007 libstdc++: Simplify constraints for semiregular-box [LWG 3477]
libstdc++-v3/ChangeLog:

	* include/std/ranges (__box): Simplify constraints as per LWG 3477.
2020-09-07 20:09:17 +01:00
Jonathan Wakely
032a4b42cc libstdc++: Add workaround for weird std::tuple error [PR 96592]
This "fix" makes no sense, but it avoids an error from G++ about
std::is_constructible being incomplete. The real problem is elsewhere,
but this "fixes" the regression for now.

libstdc++-v3/ChangeLog:

	PR libstdc++/96592
	* include/std/tuple (_TupleConstraints<true, T...>): Use
	alternative is_constructible instead of std::is_constructible.
	* testsuite/20_util/tuple/cons/96592.cc: New test.
2020-09-03 16:26:16 +01:00
Jonathan Wakely
3c21913415 libstdc++: Optimise GCD algorithms
The current std::gcd and std::chrono::duration::_S_gcd algorithms are
both recursive. This is potentially expensive to evaluate in constant
expressions, because each level of recursion makes a new copy of the
function to evaluate. The maximum number of steps is bounded
(proportional to the number of decimal digits in the smaller value) and
so unlikely to exceed the limit for constexpr nesting, but the memory
usage is still suboptimal. By using an iterative algorithm we avoid
that compile-time cost. Because looping in constexpr functions is not
allowed until C++14, we need to keep the recursive implementation in
duration::_S_gcd for C++11 mode.

For std::gcd we can also optimise runtime performance by using the
binary GCD algorithm.

libstdc++-v3/ChangeLog:

	* include/std/chrono (duration::_S_gcd): Use iterative algorithm
	for C++14 and later.
	* include/std/numeric (__detail::__gcd): Replace recursive
	Euclidean algorithm with iterative version of binary GCD algorithm.
	* testsuite/26_numerics/gcd/1.cc: Test additional inputs.
	* testsuite/26_numerics/gcd/gcd_neg.cc: Adjust dg-error lines.
	* testsuite/26_numerics/lcm/lcm_neg.cc: Likewise.
	* testsuite/experimental/numeric/gcd.cc: Test additional inputs.
	* testsuite/26_numerics/gcd/2.cc: New test.
2020-09-03 12:46:13 +01:00
Jonathan Wakely
2f983fa690 libstdc++: Fix three-way comparison for std::array [PR 96851]
The spaceship operator for std::array uses memcmp when the
__is_byte<value_type> trait is true, but memcmp isn't usable in
constexpr contexts. Also, memcmp should only be used for unsigned byte
types, because it gives the wrong answer for signed chars with negative
values.

We can simply check std::is_constant_evaluated() so that we don't use
memcmp during constant evaluation.

To fix the problem of using memcmp for inappropriate types, this patch
adds new __is_memcmp_ordered and __is_memcmp_ordered_with traits. These
say whether using memcmp will give the right answer for ordering
operations such as lexicographical_compare and three-way comparisons.
The new traits can be used in several places, and can also be used to
implement my suggestion in PR 93059 comment 37 to use memcmp for
unsigned integers larger than one byte on big endian targets.

libstdc++-v3/ChangeLog:

	PR libstdc++/96851
	* include/bits/cpp_type_traits.h (__is_memcmp_ordered):
	New trait that says if memcmp can be used for ordering.
	(__is_memcmp_ordered_with): Likewise, for two types.
	* include/bits/deque.tcc (__lex_cmp_dit): Use new traits
	instead of __is_byte and __numeric_traits.
	(__lexicographical_compare_aux1): Likewise.
	* include/bits/ranges_algo.h (__lexicographical_compare_fn):
	Likewise.
	* include/bits/stl_algobase.h (__lexicographical_compare_aux1)
	(__is_byte_iter): Likewise.
	* include/std/array (operator<=>): Likewise. Only use memcmp
	when std::is_constant_evaluated() is false.
	* testsuite/23_containers/array/comparison_operators/96851.cc:
	New test.
	* testsuite/23_containers/array/tuple_interface/get_neg.cc:
	Adjust dg-error line numbers.
2020-09-02 15:32:11 +01:00
Jonathan Wakely
6bdbf0f37b libstdc++: Break header cycle between <new> and <exception>
The <new> and <exception> headers each include each other, which makes
building them as header-units "exciting". The <new> header only needs
the definition of std::exception (in order to derive from it) which is
already in its own header, so just include that.

libstdc++-v3/ChangeLog:

	* include/bits/stl_iterator.h: Include <bits/exception_defines.h>
	for definitions of __try, __catch and __throw_exception_again.
	(counted_iterator::operator++(int)): Use __throw_exception_again
	instead of throw.
	* libsupc++/new: Include <bits/exception.h> not <exception>.
	* libsupc++/new_opvnt.cc: Include <bits/exception_defines.h>.
	* testsuite/18_support/destroying_delete.cc: Include
	<type_traits> for std::is_same_v definition.
	* testsuite/20_util/variant/index_type.cc: Qualify size_t.
2020-09-02 13:56:32 +01:00
Jonathan Wakely
10f51543bb libstdc++: Add compile-time checks to__glibcxx_assert [PR 71960]
This change evaluates __glibcxx_assert checks unconditionally when a
function is being constant evaluated (when std::is_constant_evaluated()
is true). If the check fails, compilation will fail with an error.

If the function isn't being constant evaluated, the normal runtime check
will be done if enabled by _GLIBCXX_ASSERTIONS or _GLIBCXX_DEBUG, the
same as before.

Tangentially, the __glibcxx_assert and _GLIBCXX_PARALLEL_ASSERT macros
are changed to expand to 'do { } while (false)' when assertions are
disabled, instead of expanding to nothing. This avoids -Wempty-body
warnings when a disabled assertion is used in an 'if' or 'else'
statement e.g.

  if constexpr (/* precondition is testable */)
    __glibcxx_assert(precondition);

a.C:9:27: warning: suggest braces around empty body in an ‘if’ statement [-Wempty-body]
    9 |     __glibcxx_assert(precondition);
      |                                  ^

libstdc++-v3/ChangeLog:

	PR libstdc++/71960
	* include/bits/c++config (__glibcxx_assert_impl): Remove
	do-while so that uses of the macro need to add it.
	(__glibcxx_assert): Rename macro for runtime assertions
	to __glibcxx_assert_2.
	(__glibcxx_assert_1): Define macro for constexpr assertions.
	(__glibcxx_assert): Define macro for constexpr and runtime
	assertions.
	* include/bits/range_access.h (ranges::advance): Remove
	redundant precondition checks during constant evaluation.
	* include/parallel/base.h (_GLIBCXX_PARALLEL_ASSERT): Always
	use do-while in macro expansion.
	* include/std/ranges (iota_view::iota_view(W, B)): Remove
	redundant braces.
2020-09-01 20:52:26 +01:00
Jonathan Wakely
b1850c617b libstdc++: Constrain chrono::duration conversions [LWG 2094]
The chrono::duration constructor that converts from another duration
type is meant to be constrained so that it doesn't participate in
overload resolution if the ratio of the periods cannot be represented as
a std::ratio.

Because our std::ratio_divide is not SFINAE-friendly the evaluation of
__is_harmonic results in an error outside the immediate context when an
overflow occurs. I intend to make ratio_divide (and ratio_multiply)
SFINAE-friendly in a future patch, but for now this patch just
introduces a new SFINAE-friendly alias template for the division.

The standard doesn't require it, but it also seems right to constrain
the constructor with std::is_convertible_v<_Rep2, rep>.

libstdc++-v3/ChangeLog:

	* include/std/chrono (duration::_S_gcd(intmax_t, intmax_t)):
	New helper function for finding GCD of two positive intmax_t
	values.
	(duration::__divide): New helper alias for dividing one period
	by another.
	(duration::__is_harmonic): Use __divide not ratio_divide.
	(duration(const duration<R2, P2>&)): Require the duration rep
	types to be convertible.
	* testsuite/20_util/duration/cons/dr2094.cc: New test.
	* testsuite/20_util/duration/requirements/reduced_period.cc:
	Fix definition of unused member functions in test type.
	* testsuite/20_util/duration/requirements/typedefs_neg2.cc:
	Adjust expected errors.
2020-09-01 18:18:26 +01:00
Jonathan Wakely
0789600c59 libstdc++: Fix deleted overload of __absu(bool)
libstdc++-v3/ChangeLog:

	* include/std/numeric (__detail::__absu(bool)): Make deleted
	function a function template, so it will be chosen for calls
	with an explicit template argument list.
	* testsuite/26_numerics/gcd/gcd_neg.cc: Add dg-prune-output.
	* testsuite/26_numerics/lcm/lcm_neg.cc: Likewise.
2020-08-29 18:24:08 +01:00
Jonathan Wakely
f2f48b68a6 libstdc++: Fix common_type specializations for duration
My recent change to implement P0548 ("common_type and duration") was not
correct. The result of common_type_t<duration<R,P>, duration<R,P>>
should be duration<common_type_t<R>, P::type>, not duration<R, P::type>.
The common_type specialization for two different duration types was
correct, but the specializations for a single duration type (which only
exist to optimize compilation time) were wrong.

This fixes the partial specializations of common_type for a single
duration type, and also the return types of duration::operator+ and
duration::operator- which are supposed to use common_type_t<duration>.

libstdc++-v3/ChangeLog:

	* include/std/chrono (common_type): Fix partial specializations
	for a single duration type to use the common_type of the rep.
	(duration::operator+, duration::operator-): Fix return types
	to also use the common_type of the rep.
	* testsuite/20_util/duration/requirements/reduced_period.cc:
	Check duration using a rep that has common_type specialized.
2020-08-28 23:41:13 +01:00
Jonathan Wakely
82db1a42e9 libstdc++: Fix std::gcd and std::lcm for unsigned integers [PR 92978]
This fixes a bug with mixed signed and unsigned types, where converting
a negative value to the unsigned result type alters the value. The
solution is to obtain the absolute values of the arguments immediately
and to perform the actual GCD or LCM algorithm on two arguments of the
same type.

In order to operate on the most negative number without overflow when
taking its absolute, use an unsigned type for the result of the abs
operation. For example, -INT_MIN will overflow, but -(unsigned)INT_MIN
is (unsigned)INT_MAX+1U which is the correct value.

libstdc++-v3/ChangeLog:

	PR libstdc++/92978
	* include/std/numeric (__abs_integral): Replace with ...
	(__detail::__absu): New function template that returns an
	unsigned type, guaranteeing it can represent the most
	negative signed value.
	(__detail::__gcd, __detail::__lcm): Require arguments to
	be unsigned and therefore already non-negative.
	(gcd, lcm): Convert arguments to absolute value as unsigned
	type before calling __detail::__gcd or __detail::__lcm.
	* include/experimental/numeric (gcd, lcm): Likewise.
	* testsuite/26_numerics/gcd/gcd_neg.cc: Adjust expected
	errors.
	* testsuite/26_numerics/lcm/lcm_neg.cc: Likewise.
	* testsuite/26_numerics/gcd/92978.cc: New test.
	* testsuite/26_numerics/lcm/92978.cc: New test.
	* testsuite/experimental/numeric/92978.cc: New test.
2020-08-28 23:03:28 +01:00
Jonathan Wakely
82030d5101 libstdc++: Make std::chrono::duration use reduced ratio for period
This implements the changes from P0548 "common_type and duration". That
was a change for C++17, but as it corrects some issues introduced by DRs
I'm also treating it as a DR and changing it for all modes from C++11
up.

The main change is that duration<R,P>::period no longer denotes P, but
rather P::type, the reduced ratio. The unary operator+ and operator-
members of duration should now return a duration using that reduced
ratio.

The requirement that common_type<T>::type is the same type as
common_type<T, T>::type (rather than simply T) was already implemented
for PR 89102.

The standard says that duration::operator+() and duration::operator-()
should return common_type_t<duration>, but that seems unnecessarily
expensive to compute. This change just uses duration<rep, period> which
is the same type, so we don't need to instantiate common_type.

As an optimization, this also adds partial specializations of
common_type for two durations of the same type, a single duration, two
time_points of the same type, and a single time_point. These
specializations avoid instantiating other specializations of common_type
and one or both of __duration_common_type or __timepoint_common_type for
the cases where the answer is trivial to obtain.

libstdc++-v3/ChangeLog:

	* include/std/chrono (__duration_common_type): Ensure the
	reduced ratio is used. Remove unused partial specialization
	using __failure_type.
	(common_type): Pass reduced ratios to __duration_common_type.
	Add partial specializations for simple cases involving a single
	duration or time_point type.
	(duration::period): Use reduced ratio.
	(duration::operator+(), duration::operator-()): Return duration
	type using the reduced ratio.
	* testsuite/20_util/duration/requirements/typedefs_neg2.cc:
	Adjust expected errors.
	* testsuite/20_util/duration/requirements/reduced_period.cc: New test.
2020-08-27 22:36:03 +01:00
Patrick Palka
71e9716137 libstdc++: Fix arithmetic bug in chrono::year_month::operator+
This fixes the months-based addition for year_month when the
year_month's month component is 0.

libstdc++-v3/ChangeLog:

	* include/std/chrono (year_month::operator+): Properly handle a
	month value of 0 by casting the month value to int before
	subtracting 1 from it so that the difference is sign-extended in
	the subsequent addition.
	* testsuite/std/time/year_month/1.cc: Test adding months to a
	year_month whose month component is below or above the
	normalized range of [1,12].
2020-08-27 14:11:24 -04:00
Patrick Palka
7b743c67f0 libstdc++: Fix operator overload ambiguity with calendar types
We currently don't enforce a constraint on some of the calendar types'
addition/subtraction operator overloads that take a 'months' arguments:

  Constraints: If the argument supplied by the caller for the months
  parameter is convertible to years, its implicit conversion sequence to
  years is worse than its implicit conversion sequence to months.

This constraint is relevant when adding/subtracting a duration to/from,
say, a year_month where the given duration is convertible to both
'months' and to 'years' (as in the new testcases below).  The correct
behavior here in light of this constraint is to perform the operation
through the (more efficient) 'years'-based overload, but we currently
emit an ambiguous overload error.

This patch templatizes the 'months'-based addition/subtraction operator
overloads so that in the event of an implicit-conversion tie, we select
the non-template 'years'-based overload.  This is the same approach
that the date library takes for enforcing this constraint.

libstdc++-v3/ChangeLog:

	* include/std/chrono
	(__detail::__months_years_conversion_disambiguator): Define.
	(year_month::operator+=): Templatize the 'months'-based overload
	so that the 'years'-based overload is selected in case of
	equally-ranked implicit conversion sequences to both 'months'
	and 'years' from the supplied argument.
	(year_month::operator-=): Likewise.
	(year_month::operator+): Likewise.
	(year_month::operator-): Likewise.
	(year_month_day::operator+=): Likewise.
	(year_month_day::operator-=): Likewise.
	(year_month_day::operator+): Likewise.
	(year_month_day::operator-): Likewise.
	(year_month_day_last::operator+=): Likewise.
	(year_month_day_last::operator-=): Likewise.
	(year_month_day_last::operator+): Likewise
	(year_month_day_last::operator-): Likewise.
	(year_month_day_weekday::operator+=): Likewise
	(year_month_day_weekday::operator-=): Likewise.
	(year_month_day_weekday::operator+): Likewise.
	(year_month_day_weekday::operator-): Likewise.
	(year_month_day_weekday_last::operator+=): Likewise
	(year_month_day_weekday_last::operator-=): Likewise.
	(year_month_day_weekday_last::operator+): Likewise.
	(year_month_day_weekday_last::operator-): Likewise.
	(testsuite/std/time/year_month/2.cc): New test.
	(testsuite/std/time/year_month_day/2.cc): New test.
	(testsuite/std/time/year_month_day_last/2.cc): New test.
	(testsuite/std/time/year_month_weekday/2.cc): New test.
	(testsuite/std/time/year_month_weekday_last/2.cc): New test.
2020-08-27 14:09:52 -04:00
Patrick Palka
3ae0cd94ab libstdc++: Implement remaining piece of LWG 3448
Almost all of the proposed resolution for LWG 3448 is already
implemented; the only part left is to adjust the return type of
transform_view::sentinel::operator-.

libstdc++-v3/ChangeLog:

	PR libstdc++/95322
	* include/std/ranges (transform_view::sentinel::__distance_from):
	Give this a deduced return type.
	(transform_view::sentinel::operator-): Adjust the return type so
	that it's based on the constness of the iterator rather than
	that of the sentinel.
	* testsuite/std/ranges/adaptors/95322.cc: Refer to LWG 3488.
2020-08-26 21:53:04 -04:00
Patrick Palka
4be16d1c1c libstdc++: elements_view's sentinel and iterator not comparable [LWG 3406]
This implements the proposed resolution for LWG 3406, and adds a
testcase for the example from P1994R1.

libstdc++-v3/ChangeLog:

	* include/std/ranges (elements_view::begin): Adjust constraints.
	(elements_view::end): Likewise.
	(elements_view::_Sentinel::operator==): Templatize to take both
	_Iterator<true> and _Iterator<false>.
	(elements_view::_Sentinel::operator-): Likewise.
	* testsuite/std/ranges/adaptors/elements.cc: Add testcase for
	the example from P1994R1.
	* testsuite/std/ranges/adaptors/lwg3406.cc: New test.
2020-08-26 21:52:58 -04:00
Patrick Palka
97ab5daa6c libstdc++: Implement P1994R1 changes to ranges::elements_view
The example from the paper doesn't compile without the proposed
resolution for LWG 3406, so we'll add a testcase for this once the
proposed resolution is implemented.

libstdc++-v3/ChangeLog:

	* include/std/ranges (elements_view::end): Replace these two
	overloads with four new overloads.
	(elements_view::_Iterator::operator==): Remove.
	(elements_view::_Iterator::operator-): Likewise.
	(elements_view::_Sentinel): Define.
2020-08-26 21:49:51 -04:00
Jonathan Wakely
af06acfc8d libstdc++: Whitespace changes in <tuple>
libstdc++-v3/ChangeLog:

	* include/std/tuple (_Tuple_impl): Whitespaces changes for
	consistent indentation. Also use __enable_if_t alias template.
2020-08-26 19:32:30 +01:00