MCPcopy Create free account
hub / github.com/DeepRec-AI/DeepRec / MultiplyWithoutOverflow

Function MultiplyWithoutOverflow

tensorflow/compiler/xla/overflow_util.h:30–50  ·  view source on GitHub ↗

Multiply two nonnegative int64's, returning negative for overflow

Source from the content-addressed store, hash-verified

28
29// Multiply two nonnegative int64's, returning negative for overflow
30inline int64 MultiplyWithoutOverflow(const int64 x, const int64 y) {
31 // Multiply in uint64 rather than int64 since signed overflow is undefined.
32 // Negative values will wrap around to large unsigned values in the casts
33 // (see section 4.7 [conv.integral] of the C++14 standard).
34 const uint64 ux = x;
35 const uint64 uy = y;
36 const uint64 uxy = ux * uy;
37
38 // Check if we overflow uint64, using a cheap check if both inputs are small
39 if (TF_PREDICT_FALSE((ux | uy) >> 32 != 0)) {
40 // Ensure nonnegativity. Note that negative numbers will appear "large"
41 // to the unsigned comparisons above.
42 CHECK(x >= 0 && y >= 0);
43
44 // Otherwise, detect overflow using a division
45 if (ux != 0 && uxy / ux != uy) return -1;
46 }
47
48 // Cast back to signed. Any negative value will signal an error.
49 return static_cast<int64>(uxy);
50}
51
52// Computes x + y and returns nullopt if it overflows.
53//

Callers 2

ValidateShapeSizeMethod · 0.70
FromProtoMethod · 0.50

Calls

no outgoing calls

Tested by

no test coverage detected