[llvm] d421e04 - [KnownBits] Add a sextOrTrunc method
Quentin Colombet via llvm-commits
llvm-commits at lists.llvm.org
Thu Oct 8 11:35:15 PDT 2020
Author: Quentin Colombet
Date: 2020-10-08T11:33:06-07:00
New Revision: d421e0484afd9a951ddf8c986febaf9c3743dc0c
URL: https://github.com/llvm/llvm-project/commit/d421e0484afd9a951ddf8c986febaf9c3743dc0c
DIFF: https://github.com/llvm/llvm-project/commit/d421e0484afd9a951ddf8c986febaf9c3743dc0c.diff
LOG: [KnownBits] Add a sextOrTrunc method
We already offer zextOrTrunc and it seems natural to offer the
same capability for sign extension.
This patch is a preparatory addition useful for future computeKnownBits
developments.
Differential Revision: https://reviews.llvm.org/D88937
Added:
Modified:
llvm/include/llvm/Support/KnownBits.h
llvm/unittests/Support/KnownBitsTest.cpp
Removed:
################################################################################
diff --git a/llvm/include/llvm/Support/KnownBits.h b/llvm/include/llvm/Support/KnownBits.h
index f3fde0c74b02..2a0a14904040 100644
--- a/llvm/include/llvm/Support/KnownBits.h
+++ b/llvm/include/llvm/Support/KnownBits.h
@@ -166,6 +166,16 @@ struct KnownBits {
return *this;
}
+ /// Return known bits for a sign extension or truncation of the value we're
+ /// tracking.
+ KnownBits sextOrTrunc(unsigned BitWidth) const {
+ if (BitWidth > getBitWidth())
+ return sext(BitWidth);
+ if (BitWidth < getBitWidth())
+ return trunc(BitWidth);
+ return *this;
+ }
+
/// Return a KnownBits with the extracted bits
/// [bitPosition,bitPosition+numBits).
KnownBits extractBits(unsigned NumBits, unsigned BitPosition) const {
diff --git a/llvm/unittests/Support/KnownBitsTest.cpp b/llvm/unittests/Support/KnownBitsTest.cpp
index 701293f7dae5..d2f766fb3344 100644
--- a/llvm/unittests/Support/KnownBitsTest.cpp
+++ b/llvm/unittests/Support/KnownBitsTest.cpp
@@ -203,4 +203,33 @@ TEST(KnownBitsTest, GetMinMaxVal) {
});
}
+TEST(KnownBitsTest, SExtOrTrunc) {
+ const unsigned NarrowerSize = 4;
+ const unsigned BaseSize = 6;
+ const unsigned WiderSize = 8;
+ APInt NegativeFitsNarrower(BaseSize, -4, /*isSigned*/ true);
+ APInt NegativeDoesntFitNarrower(BaseSize, -28, /*isSigned*/ true);
+ APInt PositiveFitsNarrower(BaseSize, 14);
+ APInt PositiveDoesntFitNarrower(BaseSize, 36);
+ auto InitKnownBits = [&](KnownBits &Res, const APInt &Input) {
+ Res = KnownBits(Input.getBitWidth());
+ Res.One = Input;
+ Res.Zero = ~Input;
+ };
+
+ for (unsigned Size : {NarrowerSize, BaseSize, WiderSize}) {
+ for (const APInt &Input :
+ {NegativeFitsNarrower, NegativeDoesntFitNarrower, PositiveFitsNarrower,
+ PositiveDoesntFitNarrower}) {
+ KnownBits Test;
+ InitKnownBits(Test, Input);
+ KnownBits Baseline;
+ InitKnownBits(Baseline, Input.sextOrTrunc(Size));
+ Test = Test.sextOrTrunc(Size);
+ EXPECT_EQ(Test.One, Baseline.One);
+ EXPECT_EQ(Test.Zero, Baseline.Zero);
+ }
+ }
+}
+
} // end anonymous namespace
More information about the llvm-commits
mailing list