[llvm] [Analysis] Improve readability of `KnownBits::pext` and `KnownBits::pdep` (PR #205176)

Jan Schultke via llvm-commits llvm-commits at lists.llvm.org
Tue Jun 23 02:32:43 PDT 2026


================
@@ -645,66 +645,69 @@ KnownBits KnownBits::clmul(const KnownBits &LHS, const KnownBits &RHS) {
   return Res;
 }
 
-KnownBits KnownBits::pext(const KnownBits &LHS, const KnownBits &RHS) {
-  // For each source position I where mask[I] could be set, the output index j
-  // lies in [M0, M1] where these track the range of possible set-bit counts
-  // seen so far in mask.
-  //
-  // The output bit j
-  // - can be 0 if any candidate LHS[I] could be zero or popcount(mask) could
-  //   be <= j, and
-  // - can be 1 only if some candidate LHS[I] could be one and popcount(mask)
-  //   is known > j.
-  unsigned BitWidth = LHS.getBitWidth();
+KnownBits KnownBits::pext(const KnownBits &Val, const KnownBits &Mask) {
+  unsigned BitWidth = Val.getBitWidth();
   KnownBits Res(BitWidth);
+  // We start by asserting that bits cannot be 0 and cannot be 1, then clear
+  // Res bits where we know a bit could have some value.
   Res.setAllConflict();
 
+  // For each source position I where Mask[I] could be 1, the output position J
+  // lies in [M0, M1], where M0 and M1 track the range of possible 1-bit counts
+  // seen so far in Mask. Note that M0=M1 as long as bits in Mask are known;
+  // otherwise, the range of possible output positions widens.
   unsigned M0 = 0, M1 = 0;
   for (unsigned I = 0; I < BitWidth; ++I) {
-    if (!RHS.Zero[I]) {
-      APInt Range = APInt::getBitsSet(BitWidth, M0, M1 + 1);
-      if (!LHS.Zero[I])
-        Res.Zero &= ~Range; // some position in Range could be 1
-      if (!LHS.One[I])
-        Res.One &= ~Range; // some position in Range could be 0
+    if (!Mask.Zero[I]) {
+      // Mask[I] could be 1, so we decide what value the Res bits could have.
+      if (!Val.Zero[I])
+        // Val[I] could be 1 => Res[J] for J in [M0, M1] could be 1
+        Res.Zero.clearBits(M0, M1 + 1);
+      if (!Val.One[I])
+        // Val[I] could be 0 => Res[J] for J in [M0, M1] could be 0
+        Res.One.clearBits(M0, M1 + 1);
     }
-    if (RHS.One[I])
+    if (Mask.One[I])
       ++M0, ++M1;
-    else if (!RHS.Zero[I])
+    else if (!Mask.Zero[I])
       ++M1;
   }
 
-  // Output positions j >= M0 may have no source (popcount(mask) <= j), in
-  // which case they default to zero.
-  Res.One &= APInt::getLowBitsSet(BitWidth, M0);
+  // Output bits at J >= M0 have no source (popcount(RHS) <= J), in
+  // which case they default to 0.
----------------
eisenwave wrote:

Well, no. We are clearing bits in `[M0, BitWidth)` as you can see in the code below, so that part is correct. But yeah, `RHS` should be `Mask`.

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


More information about the llvm-commits mailing list