1 | /* Copyright 2015 The TensorFlow Authors. All Rights Reserved. |
2 | |
3 | Licensed under the Apache License, Version 2.0 (the "License"); |
4 | you may not use this file except in compliance with the License. |
5 | You may obtain a copy of the License at |
6 | |
7 | http://www.apache.org/licenses/LICENSE-2.0 |
8 | |
9 | Unless required by applicable law or agreed to in writing, software |
10 | distributed under the License is distributed on an "AS IS" BASIS, |
11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
12 | See the License for the specific language governing permissions and |
13 | limitations under the License. |
14 | ==============================================================================*/ |
15 | |
16 | #ifndef TENSORFLOW_CORE_UTIL_OVERFLOW_H_ |
17 | #define TENSORFLOW_CORE_UTIL_OVERFLOW_H_ |
18 | |
19 | #include "tensorflow/core/platform/logging.h" |
20 | #include "tensorflow/core/platform/macros.h" |
21 | #include "tensorflow/core/platform/types.h" |
22 | |
23 | namespace tensorflow { |
24 | |
25 | // Multiply two nonnegative int64's, returning negative for overflow |
26 | // If any of the arguments is negative, return negative too. |
27 | inline int64_t MultiplyWithoutOverflow(const int64_t x, const int64_t y) { |
28 | if (TF_PREDICT_FALSE(x < 0)) return -1; |
29 | if (TF_PREDICT_FALSE(y < 0)) return -1; |
30 | if (TF_PREDICT_FALSE(x == 0)) return 0; |
31 | |
32 | // Multiply in uint64 rather than int64 since signed overflow is undefined. |
33 | // Negative values will wrap around to large unsigned values in the casts |
34 | // (see section 4.7 [conv.integral] of the C++14 standard). |
35 | const uint64 ux = x; |
36 | const uint64 uy = y; |
37 | const uint64 uxy = ux * uy; |
38 | |
39 | // Check if we overflow uint64, using a cheap check if both inputs are small |
40 | if (TF_PREDICT_FALSE((ux | uy) >> 32 != 0)) { |
41 | // Otherwise, detect overflow using a division |
42 | if (uxy / ux != uy) return -1; |
43 | } |
44 | |
45 | // Cast back to signed. A negative value will signal an error. |
46 | return static_cast<int64_t>(uxy); |
47 | } |
48 | |
49 | } // namespace tensorflow |
50 | |
51 | #endif // TENSORFLOW_CORE_UTIL_OVERFLOW_H_ |
52 | |