1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef ART_RUNTIME_INTERPRETER_SAFE_MATH_H_
18 #define ART_RUNTIME_INTERPRETER_SAFE_MATH_H_
19 
20 #include <functional>
21 #include <type_traits>
22 
23 #include "base/macros.h"
24 
25 namespace art HIDDEN {
26 namespace interpreter {
27 
28 // Declares a type which is the larger in bit size of the two template parameters.
29 template <typename T1, typename T2>
30 struct select_bigger {
31   using type = std::conditional_t<sizeof(T1) >= sizeof(T2), T1, T2>;
32 };
33 template <typename T1, typename T2>
34 using select_bigger_t = typename select_bigger<T1, T2>::type;
35 
36 // Perform signed arithmetic Op on 'a' and 'b' with defined wrapping behavior.
37 template<template <typename OpT> class Op, typename T1, typename T2>
SafeMath(T1 a,T2 b)38 static inline select_bigger_t<T1, T2> SafeMath(T1 a, T2 b) {
39   using biggest_T = select_bigger_t<T1, T2>;
40   using unsigned_biggest_T = std::make_unsigned_t<biggest_T>;
41   static_assert(std::is_signed_v<T1>, "Expected T1 to be signed");
42   static_assert(std::is_signed_v<T2>, "Expected T2 to be signed");
43   unsigned_biggest_T val1 = static_cast<unsigned_biggest_T>(static_cast<biggest_T>(a));
44   unsigned_biggest_T val2 = static_cast<unsigned_biggest_T>(b);
45   return static_cast<biggest_T>(Op<unsigned_biggest_T>()(val1, val2));
46 }
47 
48 // Perform a signed add on 'a' and 'b' with defined wrapping behavior.
49 template<typename T1, typename T2>
SafeAdd(T1 a,T2 b)50 static inline select_bigger_t<T1, T2> SafeAdd(T1 a, T2 b) {
51   return SafeMath<std::plus>(a, b);
52 }
53 
54 // Perform a signed substract on 'a' and 'b' with defined wrapping behavior.
55 template<typename T1, typename T2>
SafeSub(T1 a,T2 b)56 static inline select_bigger_t<T1, T2> SafeSub(T1 a, T2 b) {
57   return SafeMath<std::minus>(a, b);
58 }
59 
60 // Perform a signed multiply on 'a' and 'b' with defined wrapping behavior.
61 template<typename T1, typename T2>
SafeMul(T1 a,T2 b)62 static inline select_bigger_t<T1, T2> SafeMul(T1 a, T2 b) {
63   return SafeMath<std::multiplies>(a, b);
64 }
65 
66 }  // namespace interpreter
67 }  // namespace art
68 
69 #endif  // ART_RUNTIME_INTERPRETER_SAFE_MATH_H_
70