1 // Copyright 2014 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 // Slightly adapted for inclusion in V8. 6 // Copyright 2014 the V8 project authors. All rights reserved. 7 // List of adaptations: 8 // - include guard names 9 // - wrap in v8 namespace 10 // - formatting (git cl format) 11 // - include paths 12 13 #ifndef V8_BASE_SAFE_CONVERSIONS_H_ 14 #define V8_BASE_SAFE_CONVERSIONS_H_ 15 16 #include <stddef.h> 17 18 #include <cmath> 19 #include <limits> 20 #include <type_traits> 21 22 #include "src/base/safe_conversions_impl.h" 23 24 #if defined(__ARMEL__) && !defined(__native_client__) 25 #include "src/base/safe_conversions_arm_impl.h" 26 #define BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS (1) 27 #else 28 #define BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS (0) 29 #endif 30 31 #if !BASE_NUMERICS_DISABLE_OSTREAM_OPERATORS 32 #include <ostream> 33 #endif 34 35 namespace v8 { 36 namespace base { 37 namespace internal { 38 39 #if !BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS 40 template <typename Dst, typename Src> 41 struct SaturateFastAsmOp { 42 static constexpr bool is_supported = false; DoSaturateFastAsmOp43 static constexpr Dst Do(Src) { 44 // Force a compile failure if instantiated. 45 return CheckOnFailure::template HandleFailure<Dst>(); 46 } 47 }; 48 #endif // BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS 49 #undef BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS 50 51 // The following special case a few specific integer conversions where we can 52 // eke out better performance than range checking. 53 template <typename Dst, typename Src, typename Enable = void> 54 struct IsValueInRangeFastOp { 55 static constexpr bool is_supported = false; DoIsValueInRangeFastOp56 static constexpr bool Do(Src value) { 57 // Force a compile failure if instantiated. 58 return CheckOnFailure::template HandleFailure<bool>(); 59 } 60 }; 61 62 // Signed to signed range comparison. 63 template <typename Dst, typename Src> 64 struct IsValueInRangeFastOp< 65 Dst, Src, 66 typename std::enable_if< 67 std::is_integral<Dst>::value && std::is_integral<Src>::value && 68 std::is_signed<Dst>::value && std::is_signed<Src>::value && 69 !IsTypeInRangeForNumericType<Dst, Src>::value>::type> { 70 static constexpr bool is_supported = true; 71 72 static constexpr bool Do(Src value) { 73 // Just downcast to the smaller type, sign extend it back to the original 74 // type, and then see if it matches the original value. 75 return value == static_cast<Dst>(value); 76 } 77 }; 78 79 // Signed to unsigned range comparison. 80 template <typename Dst, typename Src> 81 struct IsValueInRangeFastOp< 82 Dst, Src, 83 typename std::enable_if< 84 std::is_integral<Dst>::value && std::is_integral<Src>::value && 85 !std::is_signed<Dst>::value && std::is_signed<Src>::value && 86 !IsTypeInRangeForNumericType<Dst, Src>::value>::type> { 87 static constexpr bool is_supported = true; 88 89 static constexpr bool Do(Src value) { 90 // We cast a signed as unsigned to overflow negative values to the top, 91 // then compare against whichever maximum is smaller, as our upper bound. 92 return as_unsigned(value) <= as_unsigned(CommonMax<Src, Dst>()); 93 } 94 }; 95 96 // Convenience function that returns true if the supplied value is in range 97 // for the destination type. 98 template <typename Dst, typename Src> 99 constexpr bool IsValueInRangeForNumericType(Src value) { 100 using SrcType = typename internal::UnderlyingType<Src>::type; 101 return internal::IsValueInRangeFastOp<Dst, SrcType>::is_supported 102 ? internal::IsValueInRangeFastOp<Dst, SrcType>::Do( 103 static_cast<SrcType>(value)) 104 : internal::DstRangeRelationToSrcRange<Dst>( 105 static_cast<SrcType>(value)) 106 .IsValid(); 107 } 108 109 // checked_cast<> is analogous to static_cast<> for numeric types, 110 // except that it CHECKs that the specified numeric conversion will not 111 // overflow or underflow. NaN source will always trigger a CHECK. 112 template <typename Dst, class CheckHandler = internal::CheckOnFailure, 113 typename Src> 114 constexpr Dst checked_cast(Src value) { 115 // This throws a compile-time error on evaluating the constexpr if it can be 116 // determined at compile-time as failing, otherwise it will CHECK at runtime. 117 using SrcType = typename internal::UnderlyingType<Src>::type; 118 return BASE_NUMERICS_LIKELY((IsValueInRangeForNumericType<Dst>(value))) 119 ? static_cast<Dst>(static_cast<SrcType>(value)) 120 : CheckHandler::template HandleFailure<Dst>(); 121 } 122 123 // Default boundaries for integral/float: max/infinity, lowest/-infinity, 0/NaN. 124 // You may provide your own limits (e.g. to saturated_cast) so long as you 125 // implement all of the static constexpr member functions in the class below. 126 template <typename T> 127 struct SaturationDefaultLimits : public std::numeric_limits<T> { 128 static constexpr T NaN() { 129 return std::numeric_limits<T>::has_quiet_NaN 130 ? std::numeric_limits<T>::quiet_NaN() 131 : T(); 132 } 133 using std::numeric_limits<T>::max; 134 static constexpr T Overflow() { 135 return std::numeric_limits<T>::has_infinity 136 ? std::numeric_limits<T>::infinity() 137 : std::numeric_limits<T>::max(); 138 } 139 using std::numeric_limits<T>::lowest; 140 static constexpr T Underflow() { 141 return std::numeric_limits<T>::has_infinity 142 ? std::numeric_limits<T>::infinity() * -1 143 : std::numeric_limits<T>::lowest(); 144 } 145 }; 146 147 template <typename Dst, template <typename> class S, typename Src> 148 constexpr Dst saturated_cast_impl(Src value, RangeCheck constraint) { 149 // For some reason clang generates much better code when the branch is 150 // structured exactly this way, rather than a sequence of checks. 151 return !constraint.IsOverflowFlagSet() 152 ? (!constraint.IsUnderflowFlagSet() ? static_cast<Dst>(value) 153 : S<Dst>::Underflow()) 154 // Skip this check for integral Src, which cannot be NaN. 155 : (std::is_integral<Src>::value || !constraint.IsUnderflowFlagSet() 156 ? S<Dst>::Overflow() 157 : S<Dst>::NaN()); 158 } 159 160 // We can reduce the number of conditions and get slightly better performance 161 // for normal signed and unsigned integer ranges. And in the specific case of 162 // Arm, we can use the optimized saturation instructions. 163 template <typename Dst, typename Src, typename Enable = void> 164 struct SaturateFastOp { 165 static constexpr bool is_supported = false; 166 static constexpr Dst Do(Src value) { 167 // Force a compile failure if instantiated. 168 return CheckOnFailure::template HandleFailure<Dst>(); 169 } 170 }; 171 172 template <typename Dst, typename Src> 173 struct SaturateFastOp< 174 Dst, Src, 175 typename std::enable_if<std::is_integral<Src>::value && 176 std::is_integral<Dst>::value && 177 SaturateFastAsmOp<Dst, Src>::is_supported>::type> { 178 static constexpr bool is_supported = true; 179 static constexpr Dst Do(Src value) { 180 return SaturateFastAsmOp<Dst, Src>::Do(value); 181 } 182 }; 183 184 template <typename Dst, typename Src> 185 struct SaturateFastOp< 186 Dst, Src, 187 typename std::enable_if<std::is_integral<Src>::value && 188 std::is_integral<Dst>::value && 189 !SaturateFastAsmOp<Dst, Src>::is_supported>::type> { 190 static constexpr bool is_supported = true; 191 static constexpr Dst Do(Src value) { 192 // The exact order of the following is structured to hit the correct 193 // optimization heuristics across compilers. Do not change without 194 // checking the emitted code. 195 const Dst saturated = CommonMaxOrMin<Dst, Src>( 196 IsMaxInRangeForNumericType<Dst, Src>() || 197 (!IsMinInRangeForNumericType<Dst, Src>() && IsValueNegative(value))); 198 return BASE_NUMERICS_LIKELY(IsValueInRangeForNumericType<Dst>(value)) 199 ? static_cast<Dst>(value) 200 : saturated; 201 } 202 }; 203 204 // saturated_cast<> is analogous to static_cast<> for numeric types, except 205 // that the specified numeric conversion will saturate by default rather than 206 // overflow or underflow, and NaN assignment to an integral will return 0. 207 // All boundary condition behaviors can be overriden with a custom handler. 208 template <typename Dst, 209 template <typename> class SaturationHandler = SaturationDefaultLimits, 210 typename Src> 211 constexpr Dst saturated_cast(Src value) { 212 using SrcType = typename UnderlyingType<Src>::type; 213 return !IsCompileTimeConstant(value) && 214 SaturateFastOp<Dst, SrcType>::is_supported && 215 std::is_same<SaturationHandler<Dst>, 216 SaturationDefaultLimits<Dst>>::value 217 ? SaturateFastOp<Dst, SrcType>::Do(static_cast<SrcType>(value)) 218 : saturated_cast_impl<Dst, SaturationHandler, SrcType>( 219 static_cast<SrcType>(value), 220 DstRangeRelationToSrcRange<Dst, SaturationHandler, SrcType>( 221 static_cast<SrcType>(value))); 222 } 223 224 // strict_cast<> is analogous to static_cast<> for numeric types, except that 225 // it will cause a compile failure if the destination type is not large enough 226 // to contain any value in the source type. It performs no runtime checking. 227 template <typename Dst, typename Src> 228 constexpr Dst strict_cast(Src value) { 229 using SrcType = typename UnderlyingType<Src>::type; 230 static_assert(UnderlyingType<Src>::is_numeric, "Argument must be numeric."); 231 static_assert(std::is_arithmetic<Dst>::value, "Result must be numeric."); 232 233 // If you got here from a compiler error, it's because you tried to assign 234 // from a source type to a destination type that has insufficient range. 235 // The solution may be to change the destination type you're assigning to, 236 // and use one large enough to represent the source. 237 // Alternatively, you may be better served with the checked_cast<> or 238 // saturated_cast<> template functions for your particular use case. 239 static_assert(StaticDstRangeRelationToSrcRange<Dst, SrcType>::value == 240 NUMERIC_RANGE_CONTAINED, 241 "The source type is out of range for the destination type. " 242 "Please see strict_cast<> comments for more information."); 243 244 return static_cast<Dst>(static_cast<SrcType>(value)); 245 } 246 247 // Some wrappers to statically check that a type is in range. 248 template <typename Dst, typename Src, class Enable = void> 249 struct IsNumericRangeContained { 250 static constexpr bool value = false; 251 }; 252 253 template <typename Dst, typename Src> 254 struct IsNumericRangeContained< 255 Dst, Src, 256 typename std::enable_if<ArithmeticOrUnderlyingEnum<Dst>::value && 257 ArithmeticOrUnderlyingEnum<Src>::value>::type> { 258 static constexpr bool value = 259 StaticDstRangeRelationToSrcRange<Dst, Src>::value == 260 NUMERIC_RANGE_CONTAINED; 261 }; 262 263 // StrictNumeric implements compile time range checking between numeric types by 264 // wrapping assignment operations in a strict_cast. This class is intended to be 265 // used for function arguments and return types, to ensure the destination type 266 // can always contain the source type. This is essentially the same as enforcing 267 // -Wconversion in gcc and C4302 warnings on MSVC, but it can be applied 268 // incrementally at API boundaries, making it easier to convert code so that it 269 // compiles cleanly with truncation warnings enabled. 270 // This template should introduce no runtime overhead, but it also provides no 271 // runtime checking of any of the associated mathematical operations. Use 272 // CheckedNumeric for runtime range checks of the actual value being assigned. 273 template <typename T> 274 class StrictNumeric { 275 public: 276 using type = T; 277 278 constexpr StrictNumeric() : value_(0) {} 279 280 // Copy constructor. 281 template <typename Src> 282 constexpr StrictNumeric(const StrictNumeric<Src>& rhs) 283 : value_(strict_cast<T>(rhs.value_)) {} 284 285 // This is not an explicit constructor because we implicitly upgrade regular 286 // numerics to StrictNumerics to make them easier to use. 287 template <typename Src> 288 constexpr StrictNumeric(Src value) // NOLINT(runtime/explicit) 289 : value_(strict_cast<T>(value)) {} 290 291 // If you got here from a compiler error, it's because you tried to assign 292 // from a source type to a destination type that has insufficient range. 293 // The solution may be to change the destination type you're assigning to, 294 // and use one large enough to represent the source. 295 // If you're assigning from a CheckedNumeric<> class, you may be able to use 296 // the AssignIfValid() member function, specify a narrower destination type to 297 // the member value functions (e.g. val.template ValueOrDie<Dst>()), use one 298 // of the value helper functions (e.g. ValueOrDieForType<Dst>(val)). 299 // If you've encountered an _ambiguous overload_ you can use a static_cast<> 300 // to explicitly cast the result to the destination type. 301 // If none of that works, you may be better served with the checked_cast<> or 302 // saturated_cast<> template functions for your particular use case. 303 template <typename Dst, typename std::enable_if<IsNumericRangeContained< 304 Dst, T>::value>::type* = nullptr> 305 constexpr operator Dst() const { 306 return static_cast<typename ArithmeticOrUnderlyingEnum<Dst>::type>(value_); 307 } 308 309 private: 310 const T value_; 311 }; 312 313 // Convience wrapper returns a StrictNumeric from the provided arithmetic type. 314 template <typename T> 315 constexpr StrictNumeric<typename UnderlyingType<T>::type> MakeStrictNum( 316 const T value) { 317 return value; 318 } 319 320 #if !BASE_NUMERICS_DISABLE_OSTREAM_OPERATORS 321 // Overload the ostream output operator to make logging work nicely. 322 template <typename T> 323 std::ostream& operator<<(std::ostream& os, const StrictNumeric<T>& value) { 324 os << static_cast<T>(value); 325 return os; 326 } 327 #endif 328 329 #define BASE_NUMERIC_COMPARISON_OPERATORS(CLASS, NAME, OP) \ 330 template <typename L, typename R, \ 331 typename std::enable_if< \ 332 internal::Is##CLASS##Op<L, R>::value>::type* = nullptr> \ 333 constexpr bool operator OP(const L lhs, const R rhs) { \ 334 return SafeCompare<NAME, typename UnderlyingType<L>::type, \ 335 typename UnderlyingType<R>::type>(lhs, rhs); \ 336 } 337 338 BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsLess, <) 339 BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsLessOrEqual, <=) 340 BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsGreater, >) 341 BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsGreaterOrEqual, >=) 342 BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsEqual, ==) 343 BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsNotEqual, !=) 344 345 } // namespace internal 346 347 using internal::as_signed; 348 using internal::as_unsigned; 349 using internal::checked_cast; 350 using internal::IsTypeInRangeForNumericType; 351 using internal::IsValueInRangeForNumericType; 352 using internal::IsValueNegative; 353 using internal::MakeStrictNum; 354 using internal::SafeUnsignedAbs; 355 using internal::saturated_cast; 356 using internal::strict_cast; 357 using internal::StrictNumeric; 358 359 // Explicitly make a shorter size_t alias for convenience. 360 using SizeT = StrictNumeric<size_t>; 361 362 // floating -> integral conversions that saturate and thus can actually return 363 // an integral type. In most cases, these should be preferred over the std:: 364 // versions. 365 template <typename Dst = int, typename Src, 366 typename = std::enable_if_t<std::is_integral<Dst>::value && 367 std::is_floating_point<Src>::value>> 368 Dst ClampFloor(Src value) { 369 return saturated_cast<Dst>(std::floor(value)); 370 } 371 template <typename Dst = int, typename Src, 372 typename = std::enable_if_t<std::is_integral<Dst>::value && 373 std::is_floating_point<Src>::value>> 374 Dst ClampCeil(Src value) { 375 return saturated_cast<Dst>(std::ceil(value)); 376 } 377 template <typename Dst = int, typename Src, 378 typename = std::enable_if_t<std::is_integral<Dst>::value && 379 std::is_floating_point<Src>::value>> 380 Dst ClampRound(Src value) { 381 const Src rounded = 382 (value >= 0.0f) ? std::floor(value + 0.5f) : std::ceil(value - 0.5f); 383 return saturated_cast<Dst>(rounded); 384 } 385 386 } // namespace base 387 } // namespace v8 388 389 #endif // V8_BASE_SAFE_CONVERSIONS_H_ 390