[llvm] [Transforms/Util] Add SimplifySwitchVar pass (PR #149937)

Matt Arsenault via llvm-commits llvm-commits at lists.llvm.org
Fri Jul 25 08:05:14 PDT 2025


================
@@ -0,0 +1,371 @@
+//===-- SimplifySwitchVar.cpp - Switch Variable simplification ------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+/// This file implements switch variable simplification. It looks for a
+/// linear relationship between the case value of a switch and the constant
+/// offset of an operation. Knowing this relationship, we can simplify
+/// multiple individual operations into a single, more generic one, which
+/// can help with further optimizations.
+///
+/// It is similar to SimplifyIndVar, but instead of looking at an
+/// induction variable and modeling its scalar evolution over
+/// multiple iterations, it analyzes the switch variable and
+/// models how it affects constant offsets.
+///
+//===----------------------------------------------------------------------===//
+
+#include "llvm/Transforms/Utils/SimplifySwitchVar.h"
+#include "llvm/IR/IRBuilder.h"
+#include "llvm/IR/PatternMatch.h"
+#include <random>
+
+using namespace llvm;
+using namespace PatternMatch;
+
+/// Return the BB, where (most of) the cases meet.
+/// In that BB are phi nodes, that contain the case BBs.
+static BasicBlock *findMostCommonSuccessor(SwitchInst *Switch) {
+  uint64_t Max = 0;
+  BasicBlock *MostCommonSuccessor = nullptr;
+
+  for (auto &Case : Switch->cases()) {
+    auto *CaseBB = Case.getCaseSuccessor();
+    auto GetNumPredecessors = [](BasicBlock *BB) -> uint64_t {
+      return std::distance(predecessors(BB).begin(), predecessors(BB).end());
+    };
----------------
arsenm wrote:

pred_size? 

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


More information about the llvm-commits mailing list