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 #include "tensorflow/core/util/overflow.h"
17 #include <cmath>
18 #include "tensorflow/core/platform/macros.h"
19 #include "tensorflow/core/platform/test.h"
20
21 namespace tensorflow {
22 namespace {
23
TEST(OverflowTest,Nonnegative)24 TEST(OverflowTest, Nonnegative) {
25 // Various interesting values
26 std::vector<int64> interesting = {0, std::numeric_limits<int64>::max()};
27 for (int i = 0; i < 63; i++) {
28 int64 bit = static_cast<int64>(1) << i;
29 interesting.push_back(bit);
30 interesting.push_back(bit + 1);
31 interesting.push_back(bit - 1);
32 }
33 for (const int64 mid : {static_cast<int64>(1) << 32,
34 static_cast<int64>(std::pow(2, 63.0 / 2))}) {
35 for (int i = -5; i < 5; i++) {
36 interesting.push_back(mid + i);
37 }
38 }
39
40 // Check all pairs
41 for (auto x : interesting) {
42 for (auto y : interesting) {
43 int64 xy = MultiplyWithoutOverflow(x, y);
44 long double dxy = static_cast<long double>(x) * y;
45 if (dxy > std::numeric_limits<int64>::max()) {
46 EXPECT_LT(xy, 0);
47 } else {
48 EXPECT_EQ(dxy, xy);
49 }
50 }
51 }
52 }
53
TEST(OverflowTest,Negative)54 TEST(OverflowTest, Negative) {
55 const int64 negatives[] = {-1, std::numeric_limits<int64>::min()};
56 for (const int64 n : negatives) {
57 EXPECT_DEATH(MultiplyWithoutOverflow(n, 0), "");
58 EXPECT_DEATH(MultiplyWithoutOverflow(0, n), "");
59 EXPECT_DEATH(MultiplyWithoutOverflow(n, n), "");
60 }
61 }
62
63 } // namespace
64 } // namespace tensorflow
65