[llvm] KnownBits: refine high-bits of mul in signed case (PR #113051)

Ramkumar Ramachandra via llvm-commits llvm-commits at lists.llvm.org
Wed Oct 23 03:10:59 PDT 2024


artagnon wrote:

> > > I'd prefer to put the ad hoc tests in `unittests/Support/KnownBitsTest.cpp` since it's a more direct way of testing the KnownBits implementation than going via ValueTracking.
> > 
> > 
> > I'm not sure we'd want to pollute the unit tests with ad-hoc tests: to me, KnownBitsTest.cpp is a collection of disciplined tests that should never fail.
> 
> There's no question of "pollution". It's the correct place for KnownBits tests. Yes we have tried to make most of the existing tests "disciplined" and exhaustive, but ad hoc tests can go in there too. They also have the advantage that it's much more obvious what cases are being tested - you don't have to craft IR with `and`s and `or`s to persuade ValueTracking to create the KnownBits objects you want to test.

Did you mean something like this? If you can check that it is okay, I will push it.

```cpp

TEST(KnownBitsTest, MulHighBits) {
  unsigned Bits = 8;
  SmallVector<std::pair<int, int>, 4> TestPairs = {
      {2, 4}, {-2, -4}, {2, -4}, {-2, 4}};
  for (auto [K1, K2] : TestPairs) {
    KnownBits Known1(Bits), Known2(Bits);
    if (K1 > 0) {
      Known1.Zero |= ~(K1 | 1);
      Known1.One |= 1;
    } else {
      Known1.One |= K1;
    }
    if (K2 > 0) {
      Known2.Zero |= ~(K2 | 1);
      Known2.One |= 1;
    } else {
      Known2.One |= K2;
    }
    KnownBits Computed = KnownBits::mul(Known1, Known2);
    KnownBits Exact(Bits);
    Exact.Zero.setAllBits();
    Exact.One.setAllBits();

    ForeachNumInKnownBits(Known1, [&](const APInt &N1) {
      ForeachNumInKnownBits(Known2, [&](const APInt &N2) {
        APInt Res = N1 * N2;
        Exact.One &= Res;
        Exact.Zero &= ~Res;
      });
    });

    APInt Mask = APInt::getHighBitsSet(
        Bits, (Exact.Zero | Exact.One).countLeadingOnes());
    Exact.Zero &= Mask;
    Exact.One &= Mask;
    Computed.Zero &= Mask;
    Computed.One &= Mask;
    EXPECT_TRUE(checkResult("mul", Exact, Computed, {Known1, Known2},
                            /*CheckOptimality=*/true));
  }
}
```

https://github.com/llvm/llvm-project/pull/113051


More information about the llvm-commits mailing list