[llvm] [SimplifyCFG] Add optimization for switches of powers of two (PR #70977)

Nikita Popov via llvm-commits llvm-commits at lists.llvm.org
Wed Nov 15 03:25:23 PST 2023


================
@@ -6839,6 +6837,80 @@ static bool ReduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder,
   return true;
 }
 
+static bool simplifySwitchOfPowersOfTwo(SwitchInst *SI, IRBuilder<> &Builder,
+                                        const DataLayout &DL,
+                                        const TargetTransformInfo &TTI) {
+
+  auto *Condition = SI->getCondition();
+  auto &Context = SI->getContext();
+  auto *CondTy = cast<IntegerType>(Condition->getType());
+
+  if (CondTy->getIntegerBitWidth() > 64 ||
+      !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
+    return false;
+
+  const auto CttzIntrinsicCost = TTI.getIntrinsicInstrCost(
+      IntrinsicCostAttributes(Intrinsic::cttz, CondTy,
+                              {Condition, ConstantInt::getTrue(Context)}),
+      TTI::TCK_SizeAndLatency);
+
+  if (CttzIntrinsicCost > TTI::TCC_Basic) {
+    // Inserting intrinsic is too expensive
+    return false;
+  }
+
+  // Only bother with this optimization if there are more than 3 switch cases;
+  // SDAG will only bother creating jump tables for 4 or more cases.
+  if (SI->getNumCases() < 4)
----------------
nikic wrote:

Worth noting that AArch64 started using a larger limit very recently (https://github.com/llvm/llvm-project/pull/71166). But I think they can add a TTI hook for this if it becomes a problem for them.

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


More information about the llvm-commits mailing list