From b2c184458e990c8faeffd5047e7086e4f7ff07a6 Mon Sep 17 00:00:00 2001 From: Roman Lebedev Date: Fri, 25 Oct 2019 18:17:38 +0300 Subject: [APInt] Add saturating multiply ops Summary: There are `*_ov()` functions already, so at least for consistency it may be good to also have saturating variants. These may or may not be needed for `ConstantRange`'s `mulWithNoWrap()` Reviewers: spatel, nikic Reviewed By: nikic Subscribers: hiraditya, dexonsmith, llvm-commits Tags: #llvm Differential Revision: https://reviews.llvm.org/D69397 --- llvm/lib/Support/APInt.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) (limited to 'llvm/lib/Support/APInt.cpp') diff --git a/llvm/lib/Support/APInt.cpp b/llvm/lib/Support/APInt.cpp index 758fe8b4f86..df2e6197b2a 100644 --- a/llvm/lib/Support/APInt.cpp +++ b/llvm/lib/Support/APInt.cpp @@ -2048,6 +2048,27 @@ APInt APInt::usub_sat(const APInt &RHS) const { return APInt(BitWidth, 0); } +APInt APInt::smul_sat(const APInt &RHS) const { + bool Overflow; + APInt Res = smul_ov(RHS, Overflow); + if (!Overflow) + return Res; + + // The result is negative if one and only one of inputs is negative. + bool ResIsNegative = isNegative() ^ RHS.isNegative(); + + return ResIsNegative ? APInt::getSignedMinValue(BitWidth) + : APInt::getSignedMaxValue(BitWidth); +} + +APInt APInt::umul_sat(const APInt &RHS) const { + bool Overflow; + APInt Res = umul_ov(RHS, Overflow); + if (!Overflow) + return Res; + + return APInt::getMaxValue(BitWidth); +} void APInt::fromString(unsigned numbits, StringRef str, uint8_t radix) { // Check our assumptions here -- cgit v1.2.3