OR-Tools  9.1
saturated_arithmetic.h
Go to the documentation of this file.
1 // Copyright 2010-2021 Google LLC
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
14 #ifndef OR_TOOLS_UTIL_SATURATED_ARITHMETIC_H_
15 #define OR_TOOLS_UTIL_SATURATED_ARITHMETIC_H_
16 
17 #include "absl/base/casts.h"
19 #include "ortools/util/bitset.h"
20 
21 namespace operations_research {
22 // ---------- Overflow utility functions ----------
23 
24 // Implement two's complement addition and subtraction on int64s.
25 //
26 // The C and C++ standards specify that the overflow of signed integers is
27 // undefined. This is because of the different possible representations that may
28 // be used for signed integers (one's complement, two's complement, sign and
29 // magnitude). Such overflows are detected by Address Sanitizer with
30 // -fsanitize=signed-integer-overflow.
31 //
32 // Simple, portable overflow detection on current machines relies on
33 // these two functions. For example, if the sign of the sum of two positive
34 // integers is negative, there has been an overflow.
35 //
36 // Note that the static assert will break if the code is compiled on machines
37 // which do not use two's complement.
38 inline int64_t TwosComplementAddition(int64_t x, int64_t y) {
39  static_assert(static_cast<uint64_t>(-1LL) == ~0ULL,
40  "The target architecture does not use two's complement.");
41  return absl::bit_cast<int64_t>(static_cast<uint64_t>(x) +
42  static_cast<uint64_t>(y));
43 }
44 
45 inline int64_t TwosComplementSubtraction(int64_t x, int64_t y) {
46  static_assert(static_cast<uint64_t>(-1LL) == ~0ULL,
47  "The target architecture does not use two's complement.");
48  return absl::bit_cast<int64_t>(static_cast<uint64_t>(x) -
49  static_cast<uint64_t>(y));
50 }
51 
52 // Helper function that returns true if an overflow has occurred in computing
53 // sum = x + y. sum is expected to be computed elsewhere.
54 inline bool AddHadOverflow(int64_t x, int64_t y, int64_t sum) {
55  // Overflow cannot occur if operands have different signs.
56  // It can only occur if sign(x) == sign(y) and sign(sum) != sign(x),
57  // which is equivalent to: sign(x) != sign(sum) && sign(y) != sign(sum).
58  // This is captured when the expression below is negative.
60  return ((x ^ sum) & (y ^ sum)) < 0;
61 }
62 
63 inline bool SubHadOverflow(int64_t x, int64_t y, int64_t diff) {
64  // This is the same reasoning as for AddHadOverflow. We have x = diff + y.
65  // The formula is the same, with 'x' and diff exchanged.
67  return AddHadOverflow(diff, y, x);
68 }
69 
70 // A note on overflow treatment.
71 // kint64min and kint64max are treated as infinity.
72 // Thus if the computation overflows, the result is always kint64m(ax/in).
73 //
74 // Note(user): this is actually wrong: when computing A-B, if A is kint64max
75 // and B is finite, then A-B won't be kint64max: overflows aren't sticky.
76 // TODO(user): consider making some operations overflow-sticky, some others
77 // not, but make an explicit choice throughout.
78 inline bool AddOverflows(int64_t x, int64_t y) {
79  return AddHadOverflow(x, y, TwosComplementAddition(x, y));
80 }
81 
82 inline int64_t SubOverflows(int64_t x, int64_t y) {
83  return SubHadOverflow(x, y, TwosComplementSubtraction(x, y));
84 }
85 
86 // Performs *b += a and returns false iff the addition overflow or underflow.
87 // This function only works for typed integer type (IntType<>).
88 template <typename IntegerType>
89 bool SafeAddInto(IntegerType a, IntegerType* b) {
90  const int64_t x = a.value();
91  const int64_t y = b->value();
92  const int64_t sum = TwosComplementAddition(x, y);
93  if (AddHadOverflow(x, y, sum)) return false;
94  *b = sum;
95  return true;
96 }
97 
98 // Returns kint64max if x >= 0 and kint64min if x < 0.
99 inline int64_t CapWithSignOf(int64_t x) {
100  // return kint64max if x >= 0 or kint64max + 1 (== kint64min) if x < 0.
101  return TwosComplementAddition(kint64max, static_cast<int64_t>(x < 0));
102 }
103 
104 inline int64_t CapAddGeneric(int64_t x, int64_t y) {
105  const int64_t result = TwosComplementAddition(x, y);
106  return AddHadOverflow(x, y, result) ? CapWithSignOf(x) : result;
107 }
108 
109 #if defined(__GNUC__) && defined(__x86_64__)
110 // TODO(user): port this to other architectures.
111 inline int64_t CapAddFast(int64_t x, int64_t y) {
112  const int64_t cap = CapWithSignOf(x);
113  int64_t result = x;
114  // clang-format off
115  asm volatile( // 'volatile': ask compiler optimizer "keep as is".
116  "\t" "addq %[y],%[result]"
117  "\n\t" "cmovoq %[cap],%[result]" // Conditional move if overflow.
118  : [result] "=r"(result) // Output
119  : "[result]" (result), [y] "r"(y), [cap] "r"(cap) // Input.
120  : "cc" /* Clobbered registers */ );
121  // clang-format on
122  return result;
123 }
124 #endif
125 
126 inline int64_t CapAdd(int64_t x, int64_t y) {
127 #if defined(__GNUC__) && defined(__x86_64__)
128  return CapAddFast(x, y);
129 #else
130  return CapAddGeneric(x, y);
131 #endif
132 }
133 
134 inline int64_t CapSubGeneric(int64_t x, int64_t y) {
135  const int64_t result = TwosComplementSubtraction(x, y);
136  return SubHadOverflow(x, y, result) ? CapWithSignOf(x) : result;
137 }
138 
139 #if defined(__GNUC__) && defined(__x86_64__)
140 // TODO(user): port this to other architectures.
141 inline int64_t CapSubFast(int64_t x, int64_t y) {
142  const int64_t cap = CapWithSignOf(x);
143  int64_t result = x;
144  // clang-format off
145  asm volatile( // 'volatile': ask compiler optimizer "keep as is".
146  "\t" "subq %[y],%[result]"
147  "\n\t" "cmovoq %[cap],%[result]" // Conditional move if overflow.
148  : [result] "=r"(result) // Output
149  : "[result]" (result), [y] "r"(y), [cap] "r"(cap) // Input.
150  : "cc" /* Clobbered registers */ );
151  // clang-format on
152  return result;
153 }
154 #endif
155 
156 inline int64_t CapSub(int64_t x, int64_t y) {
157 #if defined(__GNUC__) && defined(__x86_64__)
158  return CapSubFast(x, y);
159 #else
160  return CapSubGeneric(x, y);
161 #endif
162 }
163 
164 // Note(user): -kint64min != kint64max, but kint64max == ~kint64min.
165 inline int64_t CapOpp(int64_t v) { return v == kint64min ? ~v : -v; }
166 
167 namespace cap_prod_util {
168 // Returns an unsigned int equal to the absolute value of n, in a way that
169 // will not produce overflows.
170 inline uint64_t uint_abs(int64_t n) {
171  return n < 0 ? ~static_cast<uint64_t>(n) + 1 : static_cast<uint64_t>(n);
172 }
173 } // namespace cap_prod_util
174 
175 // The generic algorithm computes a bound on the number of bits necessary to
176 // store the result. For this it uses the position of the most significant bits
177 // of each of the arguments.
178 // If the result needs at least 64 bits, then return a capped value.
179 // If the result needs at most 63 bits, then return the product.
180 // Otherwise, the result may use 63 or 64 bits: compute the product
181 // as a uint64_t, and cap it if necessary.
182 inline int64_t CapProdGeneric(int64_t x, int64_t y) {
183  const uint64_t a = cap_prod_util::uint_abs(x);
184  const uint64_t b = cap_prod_util::uint_abs(y);
185  // Let MSB(x) denote the most significant bit of x. We have:
186  // MSB(x) + MSB(y) <= MSB(x * y) <= MSB(x) + MSB(y) + 1
187  const int msb_sum =
189  const int kMaxBitIndexInInt64 = 63;
190  if (msb_sum <= kMaxBitIndexInInt64 - 2) return x * y;
191  // Catch a == 0 or b == 0 now, as MostSignificantBitPosition64(0) == 0.
192  // TODO(user): avoid this by writing function Log2(a) with Log2(0) == -1.
193  if (a == 0 || b == 0) return 0;
194  const int64_t cap = CapWithSignOf(x ^ y);
195  if (msb_sum >= kMaxBitIndexInInt64) return cap;
196  // The corner case is when msb_sum == 62, i.e. at least 63 bits will be
197  // needed to store the product. The following product will never overflow
198  // on uint64_t, since msb_sum == 62.
199  const uint64_t u_prod = a * b;
200  // The overflow cases are captured by one of the following conditions:
201  // (cap >= 0 && u_prod >= static_cast<uint64_t>(kint64max) or
202  // (cap < 0 && u_prod >= static_cast<uint64_t>(kint64min)).
203  // These can be optimized as follows (and if the condition is false, it is
204  // safe to compute x * y.
205  if (u_prod >= static_cast<uint64_t>(cap)) return cap;
206  const int64_t abs_result = absl::bit_cast<int64_t>(u_prod);
207  return cap < 0 ? -abs_result : abs_result;
208 }
209 
210 #if defined(__GNUC__) && defined(__x86_64__)
211 // TODO(user): port this to other architectures.
212 inline int64_t CapProdFast(int64_t x, int64_t y) {
213  // cap = kint64max if x and y have the same sign, cap = kint64min
214  // otherwise.
215  const int64_t cap = CapWithSignOf(x ^ y);
216  int64_t result = x;
217  // Here, we use the fact that imul of two signed 64-integers returns a 128-bit
218  // result -- we care about the lower 64 bits. More importantly, imul also sets
219  // the carry flag if 64 bits were not enough.
220  // We therefore use cmovc to return cap if the carry was set.
221  // clang-format off
222  asm volatile( // 'volatile': ask compiler optimizer "keep as is".
223  "\n\t" "imulq %[y],%[result]"
224  "\n\t" "cmovcq %[cap],%[result]" // Conditional move if carry.
225  : [result] "=r"(result) // Output
226  : "[result]" (result), [y] "r"(y), [cap] "r"(cap) // Input.
227  : "cc" /* Clobbered registers */);
228  // clang-format on
229  return result;
230 }
231 #endif
232 
233 inline int64_t CapProd(int64_t x, int64_t y) {
234 #if defined(__GNUC__) && defined(__x86_64__)
235  return CapProdFast(x, y);
236 #else
237  return CapProdGeneric(x, y);
238 #endif
239 }
240 } // namespace operations_research
241 
242 #endif // OR_TOOLS_UTIL_SATURATED_ARITHMETIC_H_
bool AddHadOverflow(int64_t x, int64_t y, int64_t sum)
bool SafeAddInto(IntegerType a, IntegerType *b)
int64_t CapSub(int64_t x, int64_t y)
int64_t CapSubGeneric(int64_t x, int64_t y)
int64_t CapOpp(int64_t v)
int64_t CapProd(int64_t x, int64_t y)
int64_t b
static const int64_t kint64min
int MostSignificantBitPosition64(uint64_t n)
Definition: bitset.h:231
static const int64_t kint64max
int64_t CapAdd(int64_t x, int64_t y)
int64_t CapWithSignOf(int64_t x)
bool AddOverflows(int64_t x, int64_t y)
bool SubHadOverflow(int64_t x, int64_t y, int64_t diff)
#define DCHECK_EQ(val1, val2)
Definition: base/logging.h:886
int64_t TwosComplementSubtraction(int64_t x, int64_t y)
Collection of objects used to extend the Constraint Solver library.
int64_t SubOverflows(int64_t x, int64_t y)
int64_t CapProdGeneric(int64_t x, int64_t y)
int64_t TwosComplementAddition(int64_t x, int64_t y)
int64_t CapAddGeneric(int64_t x, int64_t y)
int64_t a