[llvm] [SimplifyCFG] Transform switch to select when common bits uniquely identify one case (PR #145233)

Gábor Spaits via llvm-commits llvm-commits at lists.llvm.org
Mon Jun 23 04:30:42 PDT 2025


================
@@ -6290,10 +6290,37 @@ static Value *foldSwitchToSelect(const SwitchCaseResultVectorTy &ResultVector,
     // case 0,2,8,10 -> Cond & 0b1..0101 == 0 ? result : default
     if (isPowerOf2_32(CaseCount)) {
       ConstantInt *MinCaseVal = CaseValues[0];
-      // Find mininal value.
-      for (auto *Case : CaseValues)
+      // In case, there are bits, that can only be present in the CaseValues we
+      // can transform the switch into a select if the conjunction of
+      // all the values uniquely identify the CaseValues.
+      APInt AndMask = APInt::getAllOnes(MinCaseVal->getBitWidth());
+
+      for (auto *Case : CaseValues) {
         if (Case->getValue().slt(MinCaseVal->getValue()))
           MinCaseVal = Case;
+        AndMask &= Case->getValue();
+      }
+
+      ConstantRange CR = computeConstantRange(
+          Condition, /* ForSigned */ Condition->getType()->isSingleValueType());
----------------
spaits wrote:

I am not 100% sure, that `computeKnownBits` will account for range attributes. In some other parts of the code, where we work with ranges I saw others using this function.

There is a function called `computeConstantRangeIncludingKnownBits`, where the description says:
```
Combine constant ranges from computeConstantRange() and computeKnownBits().
```
Maybe I should use that one.

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


More information about the llvm-commits mailing list