[base] Remove safe_math headers

We only use the safe math helpers (CheckedNumeric<T>) in very few
places. The headers are huge though, and complex. They are pulled in to
839 of our object files, increasing compilation time.

I also find the implicit checks more easy to understand than the complex
logic in CheckedNumeric.

Thus, this CL removes the safe_math headers and implements bounds
checks for the five uses explicitly.

R=jkummerow@chromium.org, mlippautz@chromium.org

Bug: v8:8834
Change-Id: I2d60f95799ee61cfa161354428605f67829cd736
Reviewed-on: https://chromium-review.googlesource.com/c/v8/v8/+/1547651
Reviewed-by: Michael Lippautz <mlippautz@chromium.org>
Reviewed-by: Jakob Kummerow <jkummerow@chromium.org>
Commit-Queue: Clemens Hammacher <clemensh@chromium.org>
Cr-Commit-Position: refs/heads/master@{#60630}
This commit is contained in:
Clemens Hammacher 2019-04-01 13:44:02 +02:00 committed by Commit Bot
parent ef2eb9337e
commit 8a35265ac4
7 changed files with 43 additions and 874 deletions

View File

@ -3305,8 +3305,6 @@ v8_component("v8_libbase") {
"src/base/ring-buffer.h",
"src/base/safe_conversions.h",
"src/base/safe_conversions_impl.h",
"src/base/safe_math.h",
"src/base/safe_math_impl.h",
"src/base/small-vector.h",
"src/base/sys-info.cc",
"src/base/sys-info.h",

View File

@ -7,7 +7,6 @@
#include <limits>
#include "src/base/logging.h"
#include "src/base/safe_math.h"
namespace v8 {
namespace base {
@ -71,49 +70,30 @@ int32_t SignedMod32(int32_t lhs, int32_t rhs) {
return lhs % rhs;
}
int64_t FromCheckedNumeric(const internal::CheckedNumeric<int64_t> value) {
if (value.IsValid())
return value.ValueUnsafe();
// We could return max/min but we don't really expose what the maximum delta
// is. Instead, return max/(-max), which is something that clients can reason
// about.
// TODO(rvargas) crbug.com/332611: don't use internal values.
int64_t limit = std::numeric_limits<int64_t>::max();
if (value.validity() == internal::RANGE_UNDERFLOW)
limit = -limit;
return value.ValueOrDefault(limit);
}
int64_t SignedSaturatedAdd64(int64_t lhs, int64_t rhs) {
internal::CheckedNumeric<int64_t> rv(lhs);
rv += rhs;
return FromCheckedNumeric(rv);
using limits = std::numeric_limits<int64_t>;
// Underflow if {lhs + rhs < min}. In that case, return {min}.
if (rhs < 0 && lhs < limits::min() - rhs) return limits::min();
// Overflow if {lhs + rhs > max}. In that case, return {max}.
if (rhs >= 0 && lhs > limits::max() - rhs) return limits::max();
return lhs + rhs;
}
int64_t SignedSaturatedSub64(int64_t lhs, int64_t rhs) {
internal::CheckedNumeric<int64_t> rv(lhs);
rv -= rhs;
return FromCheckedNumeric(rv);
using limits = std::numeric_limits<int64_t>;
// Underflow if {lhs - rhs < min}. In that case, return {min}.
if (rhs > 0 && lhs < limits::min() + rhs) return limits::min();
// Overflow if {lhs - rhs > max}. In that case, return {max}.
if (rhs <= 0 && lhs > limits::max() + rhs) return limits::max();
return lhs - rhs;
}
bool SignedMulOverflow32(int32_t lhs, int32_t rhs, int32_t* val) {
internal::CheckedNumeric<int32_t> rv(lhs);
rv *= rhs;
int32_t limit = std::numeric_limits<int32_t>::max();
*val = rv.ValueOrDefault(limit);
return !rv.IsValid();
}
bool SignedMulOverflow64(int64_t lhs, int64_t rhs, int64_t* val) {
internal::CheckedNumeric<int64_t> rv(lhs);
rv *= rhs;
int64_t limit = std::numeric_limits<int64_t>::max();
*val = rv.ValueOrDefault(limit);
return !rv.IsValid();
// Compute the result as {int64_t}, then check for overflow.
int64_t result = int64_t{lhs} * int64_t{rhs};
*val = static_cast<int32_t>(result);
using limits = std::numeric_limits<int32_t>;
return result < limits::min() || result > limits::max();
}
} // namespace bits

View File

@ -19,12 +19,6 @@
namespace v8 {
namespace base {
namespace internal {
template <typename T>
class CheckedNumeric;
}
namespace bits {
// CountPopulation(value) returns the number of bits set in |value|.
@ -242,11 +236,6 @@ inline bool SignedSubOverflow64(int64_t lhs, int64_t rhs, int64_t* val) {
return ((res ^ lhs) & (res ^ ~rhs) & (1ULL << 63)) != 0;
}
// SignedMulOverflow64(lhs,rhs,val) performs a signed multiplication of |lhs|
// and |rhs| and stores the result into the variable pointed to by |val| and
// returns true if the signed multiplication resulted in an overflow.
V8_BASE_EXPORT bool SignedMulOverflow64(int64_t lhs, int64_t rhs, int64_t* val);
// SignedMulHigh32(lhs, rhs) multiplies two signed 32-bit values |lhs| and
// |rhs|, extracts the most significant 32 bits of the result, and returns
// those.
@ -295,10 +284,6 @@ inline uint32_t UnsignedMod32(uint32_t lhs, uint32_t rhs) {
}
// Clamp |value| on overflow and underflow conditions.
V8_BASE_EXPORT int64_t
FromCheckedNumeric(const internal::CheckedNumeric<int64_t> value);
// SignedSaturatedAdd64(lhs, rhs) adds |lhs| and |rhs|,
// checks and returns the result.
V8_BASE_EXPORT int64_t SignedSaturatedAdd64(int64_t lhs, int64_t rhs);

View File

@ -39,13 +39,23 @@ int64_t ComputeThreadTicks() {
&thread_info_count);
CHECK_EQ(kr, KERN_SUCCESS);
v8::base::CheckedNumeric<int64_t> absolute_micros(
thread_info_data.user_time.seconds +
thread_info_data.system_time.seconds);
absolute_micros *= v8::base::Time::kMicrosecondsPerSecond;
absolute_micros += (thread_info_data.user_time.microseconds +
thread_info_data.system_time.microseconds);
return absolute_micros.ValueOrDie();
// We can add the seconds into a {int64_t} without overflow.
CHECK_LE(thread_info_data.user_time.seconds,
std::numeric_limits<int64_t>::max() -
thread_info_data.system_time.seconds);
int64_t seconds =
thread_info_data.user_time.seconds + thread_info_data.system_time.seconds;
// Multiplying the seconds by {kMicrosecondsPerSecond}, and adding something
// in [0, 2 * kMicrosecondsPerSecond) must result in a valid {int64_t}.
static constexpr int64_t kSecondsLimit =
(std::numeric_limits<int64_t>::max() /
v8::base::Time::kMicrosecondsPerSecond) -
2;
CHECK_GT(kSecondsLimit, seconds);
int64_t micros = seconds * v8::base::Time::kMicrosecondsPerSecond;
micros += (thread_info_data.user_time.microseconds +
thread_info_data.system_time.microseconds);
return micros;
}
#elif V8_OS_POSIX
// Helper function to get results from clock_gettime() and convert to a
@ -69,8 +79,14 @@ V8_INLINE int64_t ClockNow(clockid_t clk_id) {
if (clock_gettime(clk_id, &ts) != 0) {
UNREACHABLE();
}
v8::base::internal::CheckedNumeric<int64_t> result(ts.tv_sec);
result *= v8::base::Time::kMicrosecondsPerSecond;
// Multiplying the seconds by {kMicrosecondsPerSecond}, and adding something
// in [0, kMicrosecondsPerSecond) must result in a valid {int64_t}.
static constexpr int64_t kSecondsLimit =
(std::numeric_limits<int64_t>::max() /
v8::base::Time::kMicrosecondsPerSecond) -
1;
CHECK_GT(kSecondsLimit, ts.tv_sec);
int64_t result = int64_t{ts.tv_sec} * v8::base::Time::kMicrosecondsPerSecond;
#if defined(V8_OS_AIX)
if (clk_id == CLOCK_THREAD_CPUTIME_ID) {
result += (tc.stime / v8::base::Time::kNanosecondsPerMicrosecond);
@ -80,7 +96,7 @@ V8_INLINE int64_t ClockNow(clockid_t clk_id) {
#else
result += (ts.tv_nsec / v8::base::Time::kNanosecondsPerMicrosecond);
#endif
return result.ValueOrDie();
return result;
#else // Monotonic clock not supported.
return 0;
#endif

View File

@ -14,7 +14,6 @@
#include "src/base/base-export.h"
#include "src/base/bits.h"
#include "src/base/macros.h"
#include "src/base/safe_math.h"
#if V8_OS_WIN
#include "src/base/win32-headers.h"
#endif

View File

@ -1,276 +0,0 @@
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Slightly adapted for inclusion in V8.
// Copyright 2014 the V8 project authors. All rights reserved.
#ifndef V8_BASE_SAFE_MATH_H_
#define V8_BASE_SAFE_MATH_H_
#include "src/base/safe_math_impl.h"
namespace v8 {
namespace base {
namespace internal {
// CheckedNumeric implements all the logic and operators for detecting integer
// boundary conditions such as overflow, underflow, and invalid conversions.
// The CheckedNumeric type implicitly converts from floating point and integer
// data types, and contains overloads for basic arithmetic operations (i.e.: +,
// -, *, /, %).
//
// The following methods convert from CheckedNumeric to standard numeric values:
// IsValid() - Returns true if the underlying numeric value is valid (i.e. has
// has not wrapped and is not the result of an invalid conversion).
// ValueOrDie() - Returns the underlying value. If the state is not valid this
// call will crash on a CHECK.
// ValueOrDefault() - Returns the current value, or the supplied default if the
// state is not valid.
// ValueFloating() - Returns the underlying floating point value (valid only
// only for floating point CheckedNumeric types).
//
// Bitwise operations are explicitly not supported, because correct
// handling of some cases (e.g. sign manipulation) is ambiguous. Comparison
// operations are explicitly not supported because they could result in a crash
// on a CHECK condition. You should use patterns like the following for these
// operations:
// Bitwise operation:
// CheckedNumeric<int> checked_int = untrusted_input_value;
// int x = checked_int.ValueOrDefault(0) | kFlagValues;
// Comparison:
// CheckedNumeric<size_t> checked_size;
// CheckedNumeric<int> checked_size = untrusted_input_value;
// checked_size = checked_size + HEADER LENGTH;
// if (checked_size.IsValid() && checked_size.ValueOrDie() < buffer_size)
// Do stuff...
template <typename T>
class CheckedNumeric {
public:
using type = T;
CheckedNumeric() = default;
// Copy constructor.
template <typename Src>
CheckedNumeric(const CheckedNumeric<Src>& rhs)
: state_(rhs.ValueUnsafe(), rhs.validity()) {}
template <typename Src>
CheckedNumeric(Src value, RangeConstraint validity)
: state_(value, validity) {}
// This is not an explicit constructor because we implicitly upgrade regular
// numerics to CheckedNumerics to make them easier to use.
template <typename Src>
CheckedNumeric(Src value) // NOLINT
: state_(value) {
// Argument must be numeric.
STATIC_ASSERT(std::numeric_limits<Src>::is_specialized);
}
// IsValid() is the public API to test if a CheckedNumeric is currently valid.
bool IsValid() const { return validity() == RANGE_VALID; }
// ValueOrDie() The primary accessor for the underlying value. If the current
// state is not valid it will CHECK and crash.
T ValueOrDie() const {
CHECK(IsValid());
return state_.value();
}
// ValueOrDefault(T default_value) A convenience method that returns the
// current value if the state is valid, and the supplied default_value for
// any other state.
T ValueOrDefault(T default_value) const {
return IsValid() ? state_.value() : default_value;
}
// ValueFloating() - Since floating point values include their validity state,
// we provide an easy method for extracting them directly, without a risk of
// crashing on a CHECK.
T ValueFloating() const {
// Argument must be a floating-point value.
STATIC_ASSERT(std::numeric_limits<T>::is_iec559);
return CheckedNumeric<T>::cast(*this).ValueUnsafe();
}
// validity() - DO NOT USE THIS IN EXTERNAL CODE - It is public right now for
// tests and to avoid a big matrix of friend operator overloads. But the
// values it returns are likely to change in the future.
// Returns: current validity state (i.e. valid, overflow, underflow, nan).
// TODO(jschuh): crbug.com/332611 Figure out and implement semantics for
// saturation/wrapping so we can expose this state consistently and implement
// saturated arithmetic.
RangeConstraint validity() const { return state_.validity(); }
// ValueUnsafe() - DO NOT USE THIS IN EXTERNAL CODE - It is public right now
// for tests and to avoid a big matrix of friend operator overloads. But the
// values it returns are likely to change in the future.
// Returns: the raw numeric value, regardless of the current state.
// TODO(jschuh): crbug.com/332611 Figure out and implement semantics for
// saturation/wrapping so we can expose this state consistently and implement
// saturated arithmetic.
T ValueUnsafe() const { return state_.value(); }
// Prototypes for the supported arithmetic operator overloads.
template <typename Src> CheckedNumeric& operator+=(Src rhs);
template <typename Src> CheckedNumeric& operator-=(Src rhs);
template <typename Src> CheckedNumeric& operator*=(Src rhs);
template <typename Src> CheckedNumeric& operator/=(Src rhs);
template <typename Src> CheckedNumeric& operator%=(Src rhs);
CheckedNumeric operator-() const {
RangeConstraint validity;
T value = CheckedNeg(state_.value(), &validity);
// Negation is always valid for floating point.
if (std::numeric_limits<T>::is_iec559)
return CheckedNumeric<T>(value);
validity = GetRangeConstraint(state_.validity() | validity);
return CheckedNumeric<T>(value, validity);
}
CheckedNumeric Abs() const {
RangeConstraint validity;
T value = CheckedAbs(state_.value(), &validity);
// Absolute value is always valid for floating point.
if (std::numeric_limits<T>::is_iec559)
return CheckedNumeric<T>(value);
validity = GetRangeConstraint(state_.validity() | validity);
return CheckedNumeric<T>(value, validity);
}
CheckedNumeric& operator++() {
*this += 1;
return *this;
}
CheckedNumeric operator++(int) {
CheckedNumeric value = *this;
*this += 1;
return value;
}
CheckedNumeric& operator--() {
*this -= 1;
return *this;
}
CheckedNumeric operator--(int) {
CheckedNumeric value = *this;
*this -= 1;
return value;
}
// These static methods behave like a convenience cast operator targeting
// the desired CheckedNumeric type. As an optimization, a reference is
// returned when Src is the same type as T.
template <typename Src>
static CheckedNumeric<T> cast(
Src u,
typename enable_if<std::numeric_limits<Src>::is_specialized, int>::type =
0) {
return u;
}
template <typename Src>
static CheckedNumeric<T> cast(
const CheckedNumeric<Src>& u,
typename enable_if<!is_same<Src, T>::value, int>::type = 0) {
return u;
}
static const CheckedNumeric<T>& cast(const CheckedNumeric<T>& u) { return u; }
private:
CheckedNumericState<T> state_;
};
// This is the boilerplate for the standard arithmetic operator overloads. A
// macro isn't the prettiest solution, but it beats rewriting these five times.
// Some details worth noting are:
// * We apply the standard arithmetic promotions.
// * We skip range checks for floating points.
// * We skip range checks for destination integers with sufficient range.
// TODO(jschuh): extract these out into templates.
#define BASE_NUMERIC_ARITHMETIC_OPERATORS(NAME, OP, COMPOUND_OP) \
/* Binary arithmetic operator for CheckedNumerics of the same type. */ \
template <typename T> \
CheckedNumeric<typename ArithmeticPromotion<T>::type> operator OP( \
const CheckedNumeric<T>& lhs, const CheckedNumeric<T>& rhs) { \
using Promotion = typename ArithmeticPromotion<T>::type; \
/* Floating point always takes the fast path */ \
if (std::numeric_limits<T>::is_iec559) \
return CheckedNumeric<T>(lhs.ValueUnsafe() OP rhs.ValueUnsafe()); \
if (IsIntegerArithmeticSafe<Promotion, T, T>::value) \
return CheckedNumeric<Promotion>( \
lhs.ValueUnsafe() OP rhs.ValueUnsafe(), \
GetRangeConstraint(rhs.validity() | lhs.validity())); \
RangeConstraint validity = RANGE_VALID; \
T result = \
Checked##NAME(static_cast<Promotion>(lhs.ValueUnsafe()), \
static_cast<Promotion>(rhs.ValueUnsafe()), &validity); \
return CheckedNumeric<Promotion>( \
result, \
GetRangeConstraint(validity | lhs.validity() | rhs.validity())); \
} \
/* Assignment arithmetic operator implementation from CheckedNumeric. */ \
template <typename T> \
template <typename Src> \
CheckedNumeric<T>& CheckedNumeric<T>::operator COMPOUND_OP(Src rhs) { \
*this = CheckedNumeric<T>::cast(*this) OP CheckedNumeric<Src>::cast(rhs); \
return *this; \
} \
/* Binary arithmetic operator for CheckedNumeric of different type. */ \
template <typename T, typename Src> \
CheckedNumeric<typename ArithmeticPromotion<T, Src>::type> operator OP( \
const CheckedNumeric<Src>& lhs, const CheckedNumeric<T>& rhs) { \
using Promotion = typename ArithmeticPromotion<T, Src>::type; \
if (IsIntegerArithmeticSafe<Promotion, T, Src>::value) \
return CheckedNumeric<Promotion>( \
lhs.ValueUnsafe() OP rhs.ValueUnsafe(), \
GetRangeConstraint(rhs.validity() | lhs.validity())); \
return CheckedNumeric<Promotion>::cast(lhs) \
OP CheckedNumeric<Promotion>::cast(rhs); \
} \
/* Binary arithmetic operator for left CheckedNumeric and right numeric. */ \
template <typename T, typename Src> \
CheckedNumeric<typename ArithmeticPromotion<T, Src>::type> operator OP( \
const CheckedNumeric<T>& lhs, Src rhs) { \
using Promotion = typename ArithmeticPromotion<T, Src>::type; \
if (IsIntegerArithmeticSafe<Promotion, T, Src>::value) \
return CheckedNumeric<Promotion>(lhs.ValueUnsafe() OP rhs, \
lhs.validity()); \
return CheckedNumeric<Promotion>::cast(lhs) \
OP CheckedNumeric<Promotion>::cast(rhs); \
} \
/* Binary arithmetic operator for right numeric and left CheckedNumeric. */ \
template <typename T, typename Src> \
CheckedNumeric<typename ArithmeticPromotion<T, Src>::type> operator OP( \
Src lhs, const CheckedNumeric<T>& rhs) { \
using Promotion = typename ArithmeticPromotion<T, Src>::type; \
if (IsIntegerArithmeticSafe<Promotion, T, Src>::value) \
return CheckedNumeric<Promotion>(lhs OP rhs.ValueUnsafe(), \
rhs.validity()); \
return CheckedNumeric<Promotion>::cast(lhs) \
OP CheckedNumeric<Promotion>::cast(rhs); \
}
BASE_NUMERIC_ARITHMETIC_OPERATORS(Add, +, += )
BASE_NUMERIC_ARITHMETIC_OPERATORS(Sub, -, -= )
BASE_NUMERIC_ARITHMETIC_OPERATORS(Mul, *, *= )
BASE_NUMERIC_ARITHMETIC_OPERATORS(Div, /, /= )
BASE_NUMERIC_ARITHMETIC_OPERATORS(Mod, %, %= )
#undef BASE_NUMERIC_ARITHMETIC_OPERATORS
} // namespace internal
using internal::CheckedNumeric;
} // namespace base
} // namespace v8
#endif // V8_BASE_SAFE_MATH_H_

View File

@ -1,533 +0,0 @@
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Slightly adapted for inclusion in V8.
// Copyright 2014 the V8 project authors. All rights reserved.
#ifndef V8_BASE_SAFE_MATH_IMPL_H_
#define V8_BASE_SAFE_MATH_IMPL_H_
#include <stdint.h>
#include <cmath>
#include <cstdlib>
#include <limits>
#include "src/base/macros.h"
#include "src/base/safe_conversions.h"
namespace v8 {
namespace base {
namespace internal {
// From Chromium's base/template_util.h:
template<class T, T v>
struct integral_constant {
static const T value = v;
using value_type = T;
using type = integral_constant<T, v>;
};
template <class T, T v> const T integral_constant<T, v>::value;
using true_type = integral_constant<bool, true>;
using false_type = integral_constant<bool, false>;
template <class T, class U> struct is_same : public false_type {};
template <class T> struct is_same<T, T> : true_type {};
template<bool B, class T = void>
struct enable_if {};
template <class T>
struct enable_if<true, T> {
using type = T;
};
// </template_util.h>
// Everything from here up to the floating point operations is portable C++,
// but it may not be fast. This code could be split based on
// platform/architecture and replaced with potentially faster implementations.
// Integer promotion templates used by the portable checked integer arithmetic.
template <size_t Size, bool IsSigned>
struct IntegerForSizeAndSign;
template <>
struct IntegerForSizeAndSign<1, true> {
using type = int8_t;
};
template <>
struct IntegerForSizeAndSign<1, false> {
using type = uint8_t;
};
template <>
struct IntegerForSizeAndSign<2, true> {
using type = int16_t;
};
template <>
struct IntegerForSizeAndSign<2, false> {
using type = uint16_t;
};
template <>
struct IntegerForSizeAndSign<4, true> {
using type = int32_t;
};
template <>
struct IntegerForSizeAndSign<4, false> {
using type = uint32_t;
};
template <>
struct IntegerForSizeAndSign<8, true> {
using type = int64_t;
};
template <>
struct IntegerForSizeAndSign<8, false> {
using type = uint64_t;
};
// WARNING: We have no IntegerForSizeAndSign<16, *>. If we ever add one to
// support 128-bit math, then the ArithmeticPromotion template below will need
// to be updated (or more likely replaced with a decltype expression).
template <typename Integer>
struct UnsignedIntegerForSize {
using type = typename enable_if<
std::numeric_limits<Integer>::is_integer,
typename IntegerForSizeAndSign<sizeof(Integer), false>::type>::type;
};
template <typename Integer>
struct SignedIntegerForSize {
using type = typename enable_if<
std::numeric_limits<Integer>::is_integer,
typename IntegerForSizeAndSign<sizeof(Integer), true>::type>::type;
};
template <typename Integer>
struct TwiceWiderInteger {
using type = typename enable_if<
std::numeric_limits<Integer>::is_integer,
typename IntegerForSizeAndSign<
sizeof(Integer) * 2,
std::numeric_limits<Integer>::is_signed>::type>::type;
};
template <typename Integer>
struct PositionOfSignBit {
static const typename enable_if<std::numeric_limits<Integer>::is_integer,
size_t>::type value = 8 * sizeof(Integer) - 1;
};
// Helper templates for integer manipulations.
template <typename T>
bool HasSignBit(T x) {
// Cast to unsigned since right shift on signed is undefined.
return !!(static_cast<typename UnsignedIntegerForSize<T>::type>(x) >>
PositionOfSignBit<T>::value);
}
// This wrapper undoes the standard integer promotions.
template <typename T>
T BinaryComplement(T x) {
return ~x;
}
// Here are the actual portable checked integer math implementations.
// TODO(jschuh): Break this code out from the enable_if pattern and find a clean
// way to coalesce things into the CheckedNumericState specializations below.
template <typename T>
typename enable_if<std::numeric_limits<T>::is_integer, T>::type
CheckedAdd(T x, T y, RangeConstraint* validity) {
// Since the value of x+y is undefined if we have a signed type, we compute
// it using the unsigned type of the same size.
using UnsignedDst = typename UnsignedIntegerForSize<T>::type;
UnsignedDst ux = static_cast<UnsignedDst>(x);
UnsignedDst uy = static_cast<UnsignedDst>(y);
UnsignedDst uresult = ux + uy;
// Addition is valid if the sign of (x + y) is equal to either that of x or
// that of y.
if (std::numeric_limits<T>::is_signed) {
if (HasSignBit(BinaryComplement((uresult ^ ux) & (uresult ^ uy))))
*validity = RANGE_VALID;
else // Direction of wrap is inverse of result sign.
*validity = HasSignBit(uresult) ? RANGE_OVERFLOW : RANGE_UNDERFLOW;
} else { // Unsigned is either valid or overflow.
*validity = BinaryComplement(x) >= y ? RANGE_VALID : RANGE_OVERFLOW;
}
return static_cast<T>(uresult);
}
template <typename T>
typename enable_if<std::numeric_limits<T>::is_integer, T>::type
CheckedSub(T x, T y, RangeConstraint* validity) {
// Since the value of x+y is undefined if we have a signed type, we compute
// it using the unsigned type of the same size.
using UnsignedDst = typename UnsignedIntegerForSize<T>::type;
UnsignedDst ux = static_cast<UnsignedDst>(x);
UnsignedDst uy = static_cast<UnsignedDst>(y);
UnsignedDst uresult = ux - uy;
// Subtraction is valid if either x and y have same sign, or (x-y) and x have
// the same sign.
if (std::numeric_limits<T>::is_signed) {
if (HasSignBit(BinaryComplement((uresult ^ ux) & (ux ^ uy))))
*validity = RANGE_VALID;
else // Direction of wrap is inverse of result sign.
*validity = HasSignBit(uresult) ? RANGE_OVERFLOW : RANGE_UNDERFLOW;
} else { // Unsigned is either valid or underflow.
*validity = x >= y ? RANGE_VALID : RANGE_UNDERFLOW;
}
return static_cast<T>(uresult);
}
// Integer multiplication is a bit complicated. In the fast case we just
// we just promote to a twice wider type, and range check the result. In the
// slow case we need to manually check that the result won't be truncated by
// checking with division against the appropriate bound.
template <typename T>
typename enable_if<
std::numeric_limits<T>::is_integer && sizeof(T) * 2 <= sizeof(uintmax_t),
T>::type
CheckedMul(T x, T y, RangeConstraint* validity) {
using IntermediateType = typename TwiceWiderInteger<T>::type;
IntermediateType tmp =
static_cast<IntermediateType>(x) * static_cast<IntermediateType>(y);
*validity = DstRangeRelationToSrcRange<T>(tmp);
return static_cast<T>(tmp);
}
template <typename T>
typename enable_if<std::numeric_limits<T>::is_integer &&
std::numeric_limits<T>::is_signed &&
(sizeof(T) * 2 > sizeof(uintmax_t)),
T>::type
CheckedMul(T x, T y, RangeConstraint* validity) {
// If either side is zero then the result will be zero.
if (!x || !y) {
return RANGE_VALID;
} else if (x > 0) {
if (y > 0)
*validity =
x <= std::numeric_limits<T>::max() / y ? RANGE_VALID : RANGE_OVERFLOW;
else
*validity = y >= std::numeric_limits<T>::min() / x ? RANGE_VALID
: RANGE_UNDERFLOW;
} else {
if (y > 0)
*validity = x >= std::numeric_limits<T>::min() / y ? RANGE_VALID
: RANGE_UNDERFLOW;
else
*validity =
y >= std::numeric_limits<T>::max() / x ? RANGE_VALID : RANGE_OVERFLOW;
}
return x * y;
}
template <typename T>
typename enable_if<std::numeric_limits<T>::is_integer &&
!std::numeric_limits<T>::is_signed &&
(sizeof(T) * 2 > sizeof(uintmax_t)),
T>::type
CheckedMul(T x, T y, RangeConstraint* validity) {
*validity = (y == 0 || x <= std::numeric_limits<T>::max() / y)
? RANGE_VALID
: RANGE_OVERFLOW;
return x * y;
}
// Division just requires a check for an invalid negation on signed min/-1.
template <typename T>
T CheckedDiv(
T x,
T y,
RangeConstraint* validity,
typename enable_if<std::numeric_limits<T>::is_integer, int>::type = 0) {
if (std::numeric_limits<T>::is_signed && x == std::numeric_limits<T>::min() &&
y == static_cast<T>(-1)) {
*validity = RANGE_OVERFLOW;
return std::numeric_limits<T>::min();
}
*validity = RANGE_VALID;
return x / y;
}
template <typename T>
typename enable_if<
std::numeric_limits<T>::is_integer && std::numeric_limits<T>::is_signed,
T>::type
CheckedMod(T x, T y, RangeConstraint* validity) {
*validity = y > 0 ? RANGE_VALID : RANGE_INVALID;
return x % y;
}
template <typename T>
typename enable_if<
std::numeric_limits<T>::is_integer && !std::numeric_limits<T>::is_signed,
T>::type
CheckedMod(T x, T y, RangeConstraint* validity) {
*validity = RANGE_VALID;
return x % y;
}
template <typename T>
typename enable_if<
std::numeric_limits<T>::is_integer && std::numeric_limits<T>::is_signed,
T>::type
CheckedNeg(T value, RangeConstraint* validity) {
*validity =
value != std::numeric_limits<T>::min() ? RANGE_VALID : RANGE_OVERFLOW;
// The negation of signed min is min, so catch that one.
return -value;
}
template <typename T>
typename enable_if<
std::numeric_limits<T>::is_integer && !std::numeric_limits<T>::is_signed,
T>::type
CheckedNeg(T value, RangeConstraint* validity) {
// The only legal unsigned negation is zero.
*validity = value ? RANGE_UNDERFLOW : RANGE_VALID;
return static_cast<T>(
-static_cast<typename SignedIntegerForSize<T>::type>(value));
}
template <typename T>
typename enable_if<
std::numeric_limits<T>::is_integer && std::numeric_limits<T>::is_signed,
T>::type
CheckedAbs(T value, RangeConstraint* validity) {
*validity =
value != std::numeric_limits<T>::min() ? RANGE_VALID : RANGE_OVERFLOW;
return std::abs(value);
}
template <typename T>
typename enable_if<
std::numeric_limits<T>::is_integer && !std::numeric_limits<T>::is_signed,
T>::type
CheckedAbs(T value, RangeConstraint* validity) {
// Absolute value of a positive is just its identiy.
*validity = RANGE_VALID;
return value;
}
// These are the floating point stubs that the compiler needs to see. Only the
// negation operation is ever called.
#define BASE_FLOAT_ARITHMETIC_STUBS(NAME) \
template <typename T> \
typename enable_if<std::numeric_limits<T>::is_iec559, T>::type \
Checked##NAME(T, T, RangeConstraint*) { \
UNREACHABLE(); \
return 0; \
}
BASE_FLOAT_ARITHMETIC_STUBS(Add)
BASE_FLOAT_ARITHMETIC_STUBS(Sub)
BASE_FLOAT_ARITHMETIC_STUBS(Mul)
BASE_FLOAT_ARITHMETIC_STUBS(Div)
BASE_FLOAT_ARITHMETIC_STUBS(Mod)
#undef BASE_FLOAT_ARITHMETIC_STUBS
template <typename T>
typename enable_if<std::numeric_limits<T>::is_iec559, T>::type CheckedNeg(
T value,
RangeConstraint*) {
return -value;
}
template <typename T>
typename enable_if<std::numeric_limits<T>::is_iec559, T>::type CheckedAbs(
T value,
RangeConstraint*) {
return std::abs(value);
}
// Floats carry around their validity state with them, but integers do not. So,
// we wrap the underlying value in a specialization in order to hide that detail
// and expose an interface via accessors.
enum NumericRepresentation {
NUMERIC_INTEGER,
NUMERIC_FLOATING,
NUMERIC_UNKNOWN
};
template <typename NumericType>
struct GetNumericRepresentation {
static const NumericRepresentation value =
std::numeric_limits<NumericType>::is_integer
? NUMERIC_INTEGER
: (std::numeric_limits<NumericType>::is_iec559 ? NUMERIC_FLOATING
: NUMERIC_UNKNOWN);
};
template <typename T, NumericRepresentation type =
GetNumericRepresentation<T>::value>
class CheckedNumericState {};
// Integrals require quite a bit of additional housekeeping to manage state.
template <typename T>
class CheckedNumericState<T, NUMERIC_INTEGER> {
private:
T value_;
RangeConstraint validity_;
public:
template <typename Src, NumericRepresentation type>
friend class CheckedNumericState;
CheckedNumericState() : value_(0), validity_(RANGE_VALID) {}
template <typename Src>
CheckedNumericState(Src value, RangeConstraint validity)
: value_(value),
validity_(GetRangeConstraint(validity |
DstRangeRelationToSrcRange<T>(value))) {
// Argument must be numeric.
STATIC_ASSERT(std::numeric_limits<Src>::is_specialized);
}
// Copy constructor.
template <typename Src>
CheckedNumericState(const CheckedNumericState<Src>& rhs)
: value_(static_cast<T>(rhs.value())),
validity_(GetRangeConstraint(
rhs.validity() | DstRangeRelationToSrcRange<T>(rhs.value()))) {}
template <typename Src>
explicit CheckedNumericState(
Src value,
typename enable_if<std::numeric_limits<Src>::is_specialized, int>::type =
0)
: value_(static_cast<T>(value)),
validity_(DstRangeRelationToSrcRange<T>(value)) {}
RangeConstraint validity() const { return validity_; }
T value() const { return value_; }
};
// Floating points maintain their own validity, but need translation wrappers.
template <typename T>
class CheckedNumericState<T, NUMERIC_FLOATING> {
private:
T value_;
public:
template <typename Src, NumericRepresentation type>
friend class CheckedNumericState;
CheckedNumericState() : value_(0.0) {}
template <typename Src>
CheckedNumericState(
Src value,
RangeConstraint validity,
typename enable_if<std::numeric_limits<Src>::is_integer, int>::type = 0) {
switch (DstRangeRelationToSrcRange<T>(value)) {
case RANGE_VALID:
value_ = static_cast<T>(value);
break;
case RANGE_UNDERFLOW:
value_ = -std::numeric_limits<T>::infinity();
break;
case RANGE_OVERFLOW:
value_ = std::numeric_limits<T>::infinity();
break;
case RANGE_INVALID:
value_ = std::numeric_limits<T>::quiet_NaN();
break;
}
}
template <typename Src>
explicit CheckedNumericState(
Src value,
typename enable_if<std::numeric_limits<Src>::is_specialized, int>::type =
0)
: value_(static_cast<T>(value)) {}
// Copy constructor.
template <typename Src>
CheckedNumericState(const CheckedNumericState<Src>& rhs)
: value_(static_cast<T>(rhs.value())) {}
RangeConstraint validity() const {
return GetRangeConstraint(value_ <= std::numeric_limits<T>::max(),
value_ >= -std::numeric_limits<T>::max());
}
T value() const { return value_; }
};
// For integers less than 128-bit and floats 32-bit or larger, we can distil
// C/C++ arithmetic promotions down to two simple rules:
// 1. The type with the larger maximum exponent always takes precedence.
// 2. The resulting type must be promoted to at least an int.
// The following template specializations implement that promotion logic.
enum ArithmeticPromotionCategory {
LEFT_PROMOTION,
RIGHT_PROMOTION,
DEFAULT_PROMOTION
};
template <typename Lhs,
typename Rhs = Lhs,
ArithmeticPromotionCategory Promotion =
(MaxExponent<Lhs>::value > MaxExponent<Rhs>::value)
? (MaxExponent<Lhs>::value > MaxExponent<int>::value
? LEFT_PROMOTION
: DEFAULT_PROMOTION)
: (MaxExponent<Rhs>::value > MaxExponent<int>::value
? RIGHT_PROMOTION
: DEFAULT_PROMOTION) >
struct ArithmeticPromotion;
template <typename Lhs, typename Rhs>
struct ArithmeticPromotion<Lhs, Rhs, LEFT_PROMOTION> {
using type = Lhs;
};
template <typename Lhs, typename Rhs>
struct ArithmeticPromotion<Lhs, Rhs, RIGHT_PROMOTION> {
using type = Rhs;
};
template <typename Lhs, typename Rhs>
struct ArithmeticPromotion<Lhs, Rhs, DEFAULT_PROMOTION> {
using type = int;
};
// We can statically check if operations on the provided types can wrap, so we
// can skip the checked operations if they're not needed. So, for an integer we
// care if the destination type preserves the sign and is twice the width of
// the source.
template <typename T, typename Lhs, typename Rhs>
struct IsIntegerArithmeticSafe {
static const bool value = !std::numeric_limits<T>::is_iec559 &&
StaticDstRangeRelationToSrcRange<T, Lhs>::value ==
NUMERIC_RANGE_CONTAINED &&
sizeof(T) >= (2 * sizeof(Lhs)) &&
StaticDstRangeRelationToSrcRange<T, Rhs>::value !=
NUMERIC_RANGE_CONTAINED &&
sizeof(T) >= (2 * sizeof(Rhs));
};
} // namespace internal
} // namespace base
} // namespace v8
#endif // V8_BASE_SAFE_MATH_IMPL_H_