This is the mail archive of the
libc-alpha@sourceware.org
mailing list for the glibc project.
Re: [PATCH v2.1] Use saturated arithmetic for overflow detection.
- From: Paul Eggert <eggert at cs dot ucla dot edu>
- To: "Joseph S. Myers" <joseph at codesourcery dot com>
- Cc: OndÅej BÃlka <neleai at seznam dot cz>, Mike Frysinger <vapier at gentoo dot org>, libc-alpha at sourceware dot org
- Date: Tue, 03 Dec 2013 12:29:50 -0800
- Subject: Re: [PATCH v2.1] Use saturated arithmetic for overflow detection.
- Authentication-results: sourceware.org; auth=none
- References: <20131030174502 dot GA18107 at domone dot podge> <20131030183318 dot GA18706 at domone dot podge> <20131101133126 dot GA2546 at domone dot podge> <201311300346 dot 53198 dot vapier at gentoo dot org> <20131203111604 dot GA11582 at domone dot podge> <529E182F dot 8050809 at cs dot ucla dot edu> <Pine dot LNX dot 4 dot 64 dot 1312031747580 dot 7734 at digraph dot polyomino dot org dot uk>
On 12/03/2013 09:53 AM, Joseph S. Myers wrote:
> Even for the normal case where one argument is constant?
I suppose you're right, it may be better to do that case inline.
Something like this, say:
#define HAVE___INT128 1 /* This should be configured. */
/* An unsigned integer type that is at least twice the width of size_t. */
#if SIZE_MAX >> 31 <= 1
# define double_size_t unsigned long long
#elif SIZE_MAX >> 31 >> 31 >> 1 <= 1 && HAVE___INT128
# define double_size_t unsigned __int128
#endif
static inline __attribute__((always_inline, unused)) size_t
mul_s (size_t x, size_t y)
{
if (! __builtin_constant_p (y))
{
if (__builtin_constant_p (x))
return mul_s (y, x);
else
{
#ifdef double_size_t
double_size_t y1 = y;
double_size_t product = x * y1;
if (__glibc_unlikely (SIZE_MAX < product))
return SIZE_MAX;
return product;
#endif
}
}
if (y == 0)
return 0;
if (__glibc_unlikely (SIZE_MAX / y < x))
return SIZE_MAX;
return x * y;
}