[clang] [mlir] [mlir][Arith] Check index divisors width from DLTI before speculation (PR #246471)

Ivan Butygin via cfe-commits cfe-commits at lists.llvm.org
Mon Nov 30 06:54:08 PST 2026


https://github.com/Hardcode84 updated https://github.com/llvm/llvm-project/pull/246471

>From a61a0af51795e514d8054f7387214b87fc2b2434 Mon Sep 17 00:00:00 2001
From: Ivan Butygin <ivan.butygin at gmail.com>
Date: Fri, 27 Nov 2026 23:41:51 +0100
Subject: [PATCH 1/3] [mlir] Split analysis management from the pass library

Let analysis clients own a cache or use one supplied by a pass. Send cache construction events through AnalysisInstrumentation and forward the pass instrumentor through the executor for pipeline and pass callbacks.
---
 .../mlir/Analysis/AnalysisInstrumentation.h   |  26 ++
 mlir/include/mlir/Analysis/AnalysisManager.h  | 402 ++++++++++++++++++
 .../mlir/Analysis/SymbolTableAnalysis.h       |   2 +-
 .../Dialect/OpenACC/Analysis/OpenACCSupport.h |   2 +-
 mlir/include/mlir/Pass/AnalysisManager.h      | 399 +----------------
 mlir/include/mlir/Pass/Pass.h                 |   2 +-
 mlir/include/mlir/Pass/PassInstrumentation.h  |  10 +-
 mlir/include/mlir/Transforms/Inliner.h        |   2 +-
 mlir/lib/Analysis/AnalysisManager.cpp         |  77 ++++
 mlir/lib/Analysis/CMakeLists.txt              |  10 +
 mlir/lib/Pass/CMakeLists.txt                  |   1 +
 mlir/lib/Pass/Pass.cpp                        | 101 +----
 mlir/lib/Pass/PassDetail.h                    |  13 +-
 mlir/unittests/Pass/AnalysisManagerTest.cpp   |  18 +-
 14 files changed, 561 insertions(+), 504 deletions(-)
 create mode 100644 mlir/include/mlir/Analysis/AnalysisInstrumentation.h
 create mode 100644 mlir/include/mlir/Analysis/AnalysisManager.h
 create mode 100644 mlir/lib/Analysis/AnalysisManager.cpp

diff --git a/mlir/include/mlir/Analysis/AnalysisInstrumentation.h b/mlir/include/mlir/Analysis/AnalysisInstrumentation.h
new file mode 100644
index 00000000000000..f98a2663fbe46c
--- /dev/null
+++ b/mlir/include/mlir/Analysis/AnalysisInstrumentation.h
@@ -0,0 +1,26 @@
+//===- AnalysisInstrumentation.h - Analysis instrumentation ---*- C++ -*-===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef MLIR_ANALYSIS_ANALYSISINSTRUMENTATION_H
+#define MLIR_ANALYSIS_ANALYSISINSTRUMENTATION_H
+
+#include "mlir/Support/TypeID.h"
+
+namespace mlir {
+class Operation;
+
+/// Receives callbacks when an analysis is computed for an operation.
+class AnalysisInstrumentation {
+public:
+  virtual ~AnalysisInstrumentation();
+  virtual void runBeforeAnalysis(StringRef name, TypeID id, Operation *op) = 0;
+  virtual void runAfterAnalysis(StringRef name, TypeID id, Operation *op) = 0;
+};
+} // namespace mlir
+
+#endif // MLIR_ANALYSIS_ANALYSISINSTRUMENTATION_H
diff --git a/mlir/include/mlir/Analysis/AnalysisManager.h b/mlir/include/mlir/Analysis/AnalysisManager.h
new file mode 100644
index 00000000000000..4e29163d9d477b
--- /dev/null
+++ b/mlir/include/mlir/Analysis/AnalysisManager.h
@@ -0,0 +1,402 @@
+//===- AnalysisManager.h - Analysis Management Infrastructure ---*- C++ -*-===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef MLIR_ANALYSIS_ANALYSISMANAGER_H
+#define MLIR_ANALYSIS_ANALYSISMANAGER_H
+
+#include "mlir/Analysis/AnalysisInstrumentation.h"
+#include "mlir/IR/Operation.h"
+#include "mlir/Support/LLVM.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/MapVector.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/Support/TypeName.h"
+#include <optional>
+
+namespace mlir {
+class AnalysisManager;
+
+//===----------------------------------------------------------------------===//
+// Analysis Preservation and Concept Modeling
+//===----------------------------------------------------------------------===//
+
+namespace detail {
+/// A utility class to represent the analyses that are known to be preserved.
+class PreservedAnalyses {
+  /// A type used to represent all potential analyses.
+  struct AllAnalysesType {};
+
+public:
+  /// Mark all analyses as preserved.
+  void preserveAll() { preservedIDs.insert(TypeID::get<AllAnalysesType>()); }
+
+  /// Returns true if all analyses were marked preserved.
+  bool isAll() const {
+    return preservedIDs.count(TypeID::get<AllAnalysesType>());
+  }
+
+  /// Returns true if no analyses were marked preserved.
+  bool isNone() const { return preservedIDs.empty(); }
+
+  /// Preserve the given analyses.
+  template <typename AnalysisT>
+  void preserve() {
+    preserve(TypeID::get<AnalysisT>());
+  }
+  template <typename AnalysisT, typename AnalysisT2, typename... OtherAnalysesT>
+  void preserve() {
+    preserve<AnalysisT>();
+    preserve<AnalysisT2, OtherAnalysesT...>();
+  }
+  void preserve(TypeID id) { preservedIDs.insert(id); }
+
+  /// Returns true if the given analysis has been marked as preserved. Note that
+  /// this simply checks for the presence of a given analysis ID and should not
+  /// be used as a general preservation checker.
+  template <typename AnalysisT>
+  bool isPreserved() const {
+    return isPreserved(TypeID::get<AnalysisT>());
+  }
+  bool isPreserved(TypeID id) const { return preservedIDs.count(id); }
+
+private:
+  /// Remove the analysis from preserved set.
+  template <typename AnalysisT>
+  void unpreserve() {
+    preservedIDs.erase(TypeID::get<AnalysisT>());
+  }
+
+  /// AnalysisModel need access to unpreserve().
+  template <typename>
+  friend struct AnalysisModel;
+
+  /// The set of analyses that are known to be preserved.
+  SmallPtrSet<TypeID, 2> preservedIDs;
+};
+
+namespace analysis_impl {
+/// Trait to check if T provides a static 'isInvalidated' method.
+template <typename T, typename... Args>
+using has_is_invalidated = decltype(std::declval<T &>().isInvalidated(
+    std::declval<const PreservedAnalyses &>()));
+
+template <typename AnalysisT>
+bool isInvalidated(AnalysisT &analysis, const PreservedAnalyses &pa) {
+  if constexpr (llvm::is_detected<has_is_invalidated, AnalysisT>::value)
+    /// Implementation of 'isInvalidated' if the analysis provides a definition.
+    return analysis.isInvalidated(pa);
+  else
+    /// Default implementation of 'isInvalidated'.
+    return !pa.isPreserved<AnalysisT>();
+}
+} // namespace analysis_impl
+
+/// The abstract polymorphic base class representing an analysis.
+struct AnalysisConcept {
+  virtual ~AnalysisConcept() = default;
+
+  /// A hook used to query analyses for invalidation. Given a preserved analysis
+  /// set, returns true if it should truly be invalidated. This allows for more
+  /// fine-tuned invalidation in cases where an analysis wasn't explicitly
+  /// marked preserved, but may be preserved(or invalidated) based upon other
+  /// properties such as analyses sets. Invalidated analyses must also be
+  /// removed from pa.
+  virtual bool invalidate(PreservedAnalyses &pa) = 0;
+};
+
+/// A derived analysis model used to hold a specific analysis object.
+template <typename AnalysisT>
+struct AnalysisModel : public AnalysisConcept {
+  template <typename... Args>
+  explicit AnalysisModel(Args &&...args)
+      : analysis(std::forward<Args>(args)...) {}
+
+  /// A hook used to query analyses for invalidation. Removes invalidated
+  /// analyses from pa.
+  bool invalidate(PreservedAnalyses &pa) final {
+    bool result = analysis_impl::isInvalidated(analysis, pa);
+    if (result)
+      pa.unpreserve<AnalysisT>();
+    return result;
+  }
+
+  /// The actual analysis object.
+  AnalysisT analysis;
+};
+
+/// This class represents a cache of analyses for a single operation. All
+/// computation, caching, and invalidation of analyses takes place here.
+class AnalysisMap {
+  /// A mapping between an analysis id and an existing analysis instance.
+  using ConceptMap = llvm::MapVector<TypeID, std::unique_ptr<AnalysisConcept>>;
+
+  /// Utility to return the name of the given analysis class.
+  template <typename AnalysisT>
+  static StringRef getAnalysisName() {
+    StringRef name = llvm::getTypeName<AnalysisT>();
+    if (!name.consume_front("mlir::"))
+      name.consume_front("(anonymous namespace)::");
+    return name;
+  }
+
+public:
+  explicit AnalysisMap(Operation *ir) : ir(ir) {}
+
+  /// Get an analysis for the current IR unit, computing it if necessary.
+  template <typename AnalysisT>
+  AnalysisT &getAnalysis(AnalysisInstrumentation *instrumentation,
+                         AnalysisManager &am) {
+    return getAnalysisImpl<AnalysisT, Operation *>(instrumentation, ir, am);
+  }
+
+  /// Get an analysis for the current IR unit assuming it's of specific derived
+  /// operation type.
+  template <typename AnalysisT, typename OpT>
+  std::enable_if_t<
+      std::is_constructible<AnalysisT, OpT>::value ||
+          std::is_constructible<AnalysisT, OpT, AnalysisManager &>::value,
+      AnalysisT &>
+  getAnalysis(AnalysisInstrumentation *instrumentation, AnalysisManager &am) {
+    return getAnalysisImpl<AnalysisT, OpT>(instrumentation, cast<OpT>(ir), am);
+  }
+
+  /// Get a cached analysis instance if one exists, otherwise return null.
+  template <typename AnalysisT>
+  std::optional<std::reference_wrapper<AnalysisT>> getCachedAnalysis() const {
+    auto res = analyses.find(TypeID::get<AnalysisT>());
+    if (res == analyses.end())
+      return std::nullopt;
+    return {static_cast<AnalysisModel<AnalysisT> &>(*res->second).analysis};
+  }
+
+  /// Returns the operation that this analysis map represents.
+  Operation *getOperation() const { return ir; }
+
+  /// Clear any held analyses.
+  void clear() { analyses.clear(); }
+
+  /// Invalidate any cached analyses based upon the given set of preserved
+  /// analyses.
+  void invalidate(const PreservedAnalyses &pa) {
+    PreservedAnalyses paCopy(pa);
+    // Remove any analyses that were invalidated.
+    // As we are using MapVector, order of insertion is preserved and
+    // dependencies always go before users, so we need only one iteration.
+    analyses.remove_if(
+        [&](auto &val) { return val.second->invalidate(paCopy); });
+  }
+
+private:
+  template <typename AnalysisT, typename OpT>
+  AnalysisT &getAnalysisImpl(AnalysisInstrumentation *instrumentation, OpT op,
+                             AnalysisManager &am) {
+    TypeID id = TypeID::get<AnalysisT>();
+
+    auto it = analyses.find(id);
+    // If we don't have a cached analysis for this operation, compute it
+    // directly and add it to the cache.
+    if (analyses.end() == it) {
+      if (instrumentation)
+        instrumentation->runBeforeAnalysis(getAnalysisName<AnalysisT>(), id,
+                                           ir);
+
+      bool wasInserted;
+      std::tie(it, wasInserted) =
+          analyses.insert({id, constructAnalysis<AnalysisT>(am, op)});
+      assert(wasInserted);
+
+      if (instrumentation)
+        instrumentation->runAfterAnalysis(getAnalysisName<AnalysisT>(), id, ir);
+    }
+    return static_cast<AnalysisModel<AnalysisT> &>(*it->second).analysis;
+  }
+
+  /// Construct analysis using two arguments constructor (OpT, AnalysisManager)
+  template <typename AnalysisT, typename OpT,
+            std::enable_if_t<std::is_constructible<
+                AnalysisT, OpT, AnalysisManager &>::value> * = nullptr>
+  static auto constructAnalysis(AnalysisManager &am, OpT op) {
+    return std::make_unique<AnalysisModel<AnalysisT>>(op, am);
+  }
+
+  /// Construct analysis using single argument constructor (OpT)
+  template <typename AnalysisT, typename OpT,
+            std::enable_if_t<!std::is_constructible<
+                AnalysisT, OpT, AnalysisManager &>::value> * = nullptr>
+  static auto constructAnalysis(AnalysisManager &, OpT op) {
+    return std::make_unique<AnalysisModel<AnalysisT>>(op);
+  }
+
+  Operation *ir;
+  ConceptMap analyses;
+};
+
+/// An analysis map that contains a map for the current operation, and a set of
+/// maps for any child operations.
+struct NestedAnalysisMap {
+  NestedAnalysisMap(Operation *op, AnalysisInstrumentation *instrumentation)
+      : analyses(op), parentOrInstrumentation(instrumentation) {}
+  NestedAnalysisMap(Operation *op, NestedAnalysisMap *parent)
+      : analyses(op), parentOrInstrumentation(parent) {}
+
+  /// Get the operation for this analysis map.
+  Operation *getOperation() const { return analyses.getOperation(); }
+
+  /// Invalidate any non preserved analyses.
+  void invalidate(const PreservedAnalyses &pa);
+
+  /// Returns the parent analysis map for this analysis map, or null if this is
+  /// the top-level map.
+  const NestedAnalysisMap *getParent() const {
+    return llvm::dyn_cast_if_present<NestedAnalysisMap *>(
+        parentOrInstrumentation);
+  }
+
+  /// Returns the optional observer for analysis construction.
+  AnalysisInstrumentation *getAnalysisInstrumentation() const {
+    if (auto *parent = getParent())
+      return parent->getAnalysisInstrumentation();
+    return cast<AnalysisInstrumentation *>(parentOrInstrumentation);
+  }
+
+  /// The cached analyses for nested operations.
+  DenseMap<Operation *, std::unique_ptr<NestedAnalysisMap>> childAnalyses;
+
+  /// The analyses for the owning operation.
+  detail::AnalysisMap analyses;
+
+  /// Nested maps have a parent. The root holds the optional observer.
+  PointerUnion<NestedAnalysisMap *, AnalysisInstrumentation *>
+      parentOrInstrumentation;
+};
+} // namespace detail
+
+//===----------------------------------------------------------------------===//
+// Analysis Management
+//===----------------------------------------------------------------------===//
+class ModuleAnalysisManager;
+
+/// This class represents an analysis manager for a particular operation
+/// instance. It is used to manage and cache analyses on the operation as well
+/// as those for child operations, via nested AnalysisManager instances
+/// accessible via 'slice'. This class is intended to be passed around by value,
+/// and cannot be constructed directly.
+class AnalysisManager {
+  using ParentPointerT =
+      PointerUnion<const ModuleAnalysisManager *, const AnalysisManager *>;
+
+public:
+  using PreservedAnalyses = detail::PreservedAnalyses;
+
+  /// Query for a cached analysis on the given parent operation. The analysis
+  /// may not exist and if it does it may be out-of-date.
+  template <typename AnalysisT>
+  std::optional<std::reference_wrapper<AnalysisT>>
+  getCachedParentAnalysis(Operation *parentOp) const {
+    const detail::NestedAnalysisMap *curParent = impl;
+    while (auto *parentAM = curParent->getParent()) {
+      if (parentAM->getOperation() == parentOp)
+        return parentAM->analyses.getCachedAnalysis<AnalysisT>();
+      curParent = parentAM;
+    }
+    return std::nullopt;
+  }
+
+  /// Query for the given analysis for the current operation.
+  template <typename AnalysisT>
+  AnalysisT &getAnalysis() {
+    return impl->analyses.getAnalysis<AnalysisT>(
+        impl->getAnalysisInstrumentation(), *this);
+  }
+
+  /// Query for the given analysis for the current operation of a specific
+  /// derived operation type.
+  template <typename AnalysisT, typename OpT>
+  AnalysisT &getAnalysis() {
+    return impl->analyses.getAnalysis<AnalysisT, OpT>(
+        impl->getAnalysisInstrumentation(), *this);
+  }
+
+  /// Query for a cached entry of the given analysis on the current operation.
+  template <typename AnalysisT>
+  std::optional<std::reference_wrapper<AnalysisT>> getCachedAnalysis() const {
+    return impl->analyses.getCachedAnalysis<AnalysisT>();
+  }
+
+  /// Query for an analysis of a child operation, constructing it if necessary.
+  template <typename AnalysisT>
+  AnalysisT &getChildAnalysis(Operation *op) {
+    return nest(op).template getAnalysis<AnalysisT>();
+  }
+
+  /// Query for an analysis of a child operation of a specific derived operation
+  /// type, constructing it if necessary.
+  template <typename AnalysisT, typename OpT>
+  AnalysisT &getChildAnalysis(OpT child) {
+    return nest(child).template getAnalysis<AnalysisT, OpT>();
+  }
+
+  /// Query for a cached analysis of a child operation, or return null.
+  template <typename AnalysisT>
+  std::optional<std::reference_wrapper<AnalysisT>>
+  getCachedChildAnalysis(Operation *op) const {
+    assert(op->getParentOp() == impl->getOperation());
+    auto it = impl->childAnalyses.find(op);
+    if (it == impl->childAnalyses.end())
+      return std::nullopt;
+    return it->second->analyses.getCachedAnalysis<AnalysisT>();
+  }
+
+  /// Get an analysis manager for the given operation, which must be a proper
+  /// descendant of the current operation represented by this analysis manager.
+  AnalysisManager nest(Operation *op);
+
+  /// Invalidate any non preserved analyses,
+  void invalidate(const PreservedAnalyses &pa) { impl->invalidate(pa); }
+
+  /// Clear any held analyses.
+  void clear() {
+    impl->analyses.clear();
+    impl->childAnalyses.clear();
+  }
+
+private:
+  AnalysisManager(detail::NestedAnalysisMap *impl) : impl(impl) {}
+
+  /// Get an analysis manager for the given immediately nested child operation.
+  AnalysisManager nestImmediate(Operation *op);
+
+  /// A reference to the impl analysis map within the parent analysis manager.
+  detail::NestedAnalysisMap *impl;
+
+  /// Allow access to the constructor.
+  friend class ModuleAnalysisManager;
+};
+
+/// An analysis manager class specifically for the top-level operation. This
+/// class contains the memory allocations for all nested analysis managers, and
+/// provides an anchor point. This is necessary because AnalysisManager is
+/// designed to be a thin wrapper around an existing analysis map instance.
+class ModuleAnalysisManager {
+public:
+  explicit ModuleAnalysisManager(
+      Operation *op, AnalysisInstrumentation *instrumentation = nullptr)
+      : analyses(op, instrumentation) {}
+  ModuleAnalysisManager(const ModuleAnalysisManager &) = delete;
+  ModuleAnalysisManager &operator=(const ModuleAnalysisManager &) = delete;
+
+  /// Returns an analysis manager for the current top-level module.
+  operator AnalysisManager() { return AnalysisManager(&analyses); }
+
+private:
+  /// The analyses for the owning module.
+  detail::NestedAnalysisMap analyses;
+};
+} // namespace mlir
+
+#endif // MLIR_ANALYSIS_ANALYSISMANAGER_H
diff --git a/mlir/include/mlir/Analysis/SymbolTableAnalysis.h b/mlir/include/mlir/Analysis/SymbolTableAnalysis.h
index 145627e43aee12..47ea8c57087100 100644
--- a/mlir/include/mlir/Analysis/SymbolTableAnalysis.h
+++ b/mlir/include/mlir/Analysis/SymbolTableAnalysis.h
@@ -9,8 +9,8 @@
 #ifndef MLIR_ANALYSIS_SYMBOLTABLEANALYSIS_H
 #define MLIR_ANALYSIS_SYMBOLTABLEANALYSIS_H
 
+#include "mlir/Analysis/AnalysisManager.h"
 #include "mlir/IR/SymbolTable.h"
-#include "mlir/Pass/AnalysisManager.h"
 
 namespace mlir {
 /// This is a simple analysis that contains a symbol table collection and, for
diff --git a/mlir/include/mlir/Dialect/OpenACC/Analysis/OpenACCSupport.h b/mlir/include/mlir/Dialect/OpenACC/Analysis/OpenACCSupport.h
index 7d847ea38bc8f2..0b64f4173d1a4f 100644
--- a/mlir/include/mlir/Dialect/OpenACC/Analysis/OpenACCSupport.h
+++ b/mlir/include/mlir/Dialect/OpenACC/Analysis/OpenACCSupport.h
@@ -50,6 +50,7 @@
 #ifndef MLIR_DIALECT_OPENACC_ANALYSIS_OPENACCSUPPORT_H
 #define MLIR_DIALECT_OPENACC_ANALYSIS_OPENACCSUPPORT_H
 
+#include "mlir/Analysis/AnalysisManager.h"
 #include "mlir/Dialect/GPU/IR/GPUDialect.h"
 #include "mlir/Dialect/OpenACC/OpenACCUtils.h"
 #include "mlir/Dialect/OpenACC/OpenACCUtilsGPU.h"
@@ -57,7 +58,6 @@
 #include "mlir/IR/BuiltinOps.h"
 #include "mlir/IR/Remarks.h"
 #include "mlir/IR/Value.h"
-#include "mlir/Pass/AnalysisManager.h"
 #include "llvm/ADT/StringRef.h"
 #include <functional>
 #include <memory>
diff --git a/mlir/include/mlir/Pass/AnalysisManager.h b/mlir/include/mlir/Pass/AnalysisManager.h
index 45009d4b02a58c..e65f00879d81f1 100644
--- a/mlir/include/mlir/Pass/AnalysisManager.h
+++ b/mlir/include/mlir/Pass/AnalysisManager.h
@@ -9,402 +9,7 @@
 #ifndef MLIR_PASS_ANALYSISMANAGER_H
 #define MLIR_PASS_ANALYSISMANAGER_H
 
-#include "mlir/IR/Operation.h"
-#include "mlir/Pass/PassInstrumentation.h"
-#include "mlir/Support/LLVM.h"
-#include "llvm/ADT/DenseMap.h"
-#include "llvm/ADT/MapVector.h"
-#include "llvm/ADT/SmallPtrSet.h"
-#include "llvm/Support/TypeName.h"
-#include <optional>
-
-namespace mlir {
-class AnalysisManager;
-
-//===----------------------------------------------------------------------===//
-// Analysis Preservation and Concept Modeling
-//===----------------------------------------------------------------------===//
-
-namespace detail {
-/// A utility class to represent the analyses that are known to be preserved.
-class PreservedAnalyses {
-  /// A type used to represent all potential analyses.
-  struct AllAnalysesType {};
-
-public:
-  /// Mark all analyses as preserved.
-  void preserveAll() { preservedIDs.insert(TypeID::get<AllAnalysesType>()); }
-
-  /// Returns true if all analyses were marked preserved.
-  bool isAll() const {
-    return preservedIDs.count(TypeID::get<AllAnalysesType>());
-  }
-
-  /// Returns true if no analyses were marked preserved.
-  bool isNone() const { return preservedIDs.empty(); }
-
-  /// Preserve the given analyses.
-  template <typename AnalysisT>
-  void preserve() {
-    preserve(TypeID::get<AnalysisT>());
-  }
-  template <typename AnalysisT, typename AnalysisT2, typename... OtherAnalysesT>
-  void preserve() {
-    preserve<AnalysisT>();
-    preserve<AnalysisT2, OtherAnalysesT...>();
-  }
-  void preserve(TypeID id) { preservedIDs.insert(id); }
-
-  /// Returns true if the given analysis has been marked as preserved. Note that
-  /// this simply checks for the presence of a given analysis ID and should not
-  /// be used as a general preservation checker.
-  template <typename AnalysisT>
-  bool isPreserved() const {
-    return isPreserved(TypeID::get<AnalysisT>());
-  }
-  bool isPreserved(TypeID id) const { return preservedIDs.count(id); }
-
-private:
-  /// Remove the analysis from preserved set.
-  template <typename AnalysisT>
-  void unpreserve() {
-    preservedIDs.erase(TypeID::get<AnalysisT>());
-  }
-
-  /// AnalysisModel need access to unpreserve().
-  template <typename>
-  friend struct AnalysisModel;
-
-  /// The set of analyses that are known to be preserved.
-  SmallPtrSet<TypeID, 2> preservedIDs;
-};
-
-namespace analysis_impl {
-/// Trait to check if T provides a static 'isInvalidated' method.
-template <typename T, typename... Args>
-using has_is_invalidated = decltype(std::declval<T &>().isInvalidated(
-    std::declval<const PreservedAnalyses &>()));
-
-template <typename AnalysisT>
-bool isInvalidated(AnalysisT &analysis, const PreservedAnalyses &pa) {
-  if constexpr (llvm::is_detected<has_is_invalidated, AnalysisT>::value)
-    /// Implementation of 'isInvalidated' if the analysis provides a definition.
-    return analysis.isInvalidated(pa);
-  else
-    /// Default implementation of 'isInvalidated'.
-    return !pa.isPreserved<AnalysisT>();
-}
-} // namespace analysis_impl
-
-/// The abstract polymorphic base class representing an analysis.
-struct AnalysisConcept {
-  virtual ~AnalysisConcept() = default;
-
-  /// A hook used to query analyses for invalidation. Given a preserved analysis
-  /// set, returns true if it should truly be invalidated. This allows for more
-  /// fine-tuned invalidation in cases where an analysis wasn't explicitly
-  /// marked preserved, but may be preserved(or invalidated) based upon other
-  /// properties such as analyses sets. Invalidated analyses must also be
-  /// removed from pa.
-  virtual bool invalidate(PreservedAnalyses &pa) = 0;
-};
-
-/// A derived analysis model used to hold a specific analysis object.
-template <typename AnalysisT>
-struct AnalysisModel : public AnalysisConcept {
-  template <typename... Args>
-  explicit AnalysisModel(Args &&...args)
-      : analysis(std::forward<Args>(args)...) {}
-
-  /// A hook used to query analyses for invalidation. Removes invalidated
-  /// analyses from pa.
-  bool invalidate(PreservedAnalyses &pa) final {
-    bool result = analysis_impl::isInvalidated(analysis, pa);
-    if (result)
-      pa.unpreserve<AnalysisT>();
-    return result;
-  }
-
-  /// The actual analysis object.
-  AnalysisT analysis;
-};
-
-/// This class represents a cache of analyses for a single operation. All
-/// computation, caching, and invalidation of analyses takes place here.
-class AnalysisMap {
-  /// A mapping between an analysis id and an existing analysis instance.
-  using ConceptMap = llvm::MapVector<TypeID, std::unique_ptr<AnalysisConcept>>;
-
-  /// Utility to return the name of the given analysis class.
-  template <typename AnalysisT>
-  static StringRef getAnalysisName() {
-    StringRef name = llvm::getTypeName<AnalysisT>();
-    if (!name.consume_front("mlir::"))
-      name.consume_front("(anonymous namespace)::");
-    return name;
-  }
-
-public:
-  explicit AnalysisMap(Operation *ir) : ir(ir) {}
-
-  /// Get an analysis for the current IR unit, computing it if necessary.
-  template <typename AnalysisT>
-  AnalysisT &getAnalysis(PassInstrumentor *pi, AnalysisManager &am) {
-    return getAnalysisImpl<AnalysisT, Operation *>(pi, ir, am);
-  }
-
-  /// Get an analysis for the current IR unit assuming it's of specific derived
-  /// operation type.
-  template <typename AnalysisT, typename OpT>
-  std::enable_if_t<
-      std::is_constructible<AnalysisT, OpT>::value ||
-          std::is_constructible<AnalysisT, OpT, AnalysisManager &>::value,
-      AnalysisT &>
-  getAnalysis(PassInstrumentor *pi, AnalysisManager &am) {
-    return getAnalysisImpl<AnalysisT, OpT>(pi, cast<OpT>(ir), am);
-  }
-
-  /// Get a cached analysis instance if one exists, otherwise return null.
-  template <typename AnalysisT>
-  std::optional<std::reference_wrapper<AnalysisT>> getCachedAnalysis() const {
-    auto res = analyses.find(TypeID::get<AnalysisT>());
-    if (res == analyses.end())
-      return std::nullopt;
-    return {static_cast<AnalysisModel<AnalysisT> &>(*res->second).analysis};
-  }
-
-  /// Returns the operation that this analysis map represents.
-  Operation *getOperation() const { return ir; }
-
-  /// Clear any held analyses.
-  void clear() { analyses.clear(); }
-
-  /// Invalidate any cached analyses based upon the given set of preserved
-  /// analyses.
-  void invalidate(const PreservedAnalyses &pa) {
-    PreservedAnalyses paCopy(pa);
-    // Remove any analyses that were invalidated.
-    // As we are using MapVector, order of insertion is preserved and
-    // dependencies always go before users, so we need only one iteration.
-    analyses.remove_if(
-        [&](auto &val) { return val.second->invalidate(paCopy); });
-  }
-
-private:
-  template <typename AnalysisT, typename OpT>
-  AnalysisT &getAnalysisImpl(PassInstrumentor *pi, OpT op,
-                             AnalysisManager &am) {
-    TypeID id = TypeID::get<AnalysisT>();
-
-    auto it = analyses.find(id);
-    // If we don't have a cached analysis for this operation, compute it
-    // directly and add it to the cache.
-    if (analyses.end() == it) {
-      if (pi)
-        pi->runBeforeAnalysis(getAnalysisName<AnalysisT>(), id, ir);
-
-      bool wasInserted;
-      std::tie(it, wasInserted) =
-          analyses.insert({id, constructAnalysis<AnalysisT>(am, op)});
-      assert(wasInserted);
-
-      if (pi)
-        pi->runAfterAnalysis(getAnalysisName<AnalysisT>(), id, ir);
-    }
-    return static_cast<AnalysisModel<AnalysisT> &>(*it->second).analysis;
-  }
-
-  /// Construct analysis using two arguments constructor (OpT, AnalysisManager)
-  template <typename AnalysisT, typename OpT,
-            std::enable_if_t<std::is_constructible<
-                AnalysisT, OpT, AnalysisManager &>::value> * = nullptr>
-  static auto constructAnalysis(AnalysisManager &am, OpT op) {
-    return std::make_unique<AnalysisModel<AnalysisT>>(op, am);
-  }
-
-  /// Construct analysis using single argument constructor (OpT)
-  template <typename AnalysisT, typename OpT,
-            std::enable_if_t<!std::is_constructible<
-                AnalysisT, OpT, AnalysisManager &>::value> * = nullptr>
-  static auto constructAnalysis(AnalysisManager &, OpT op) {
-    return std::make_unique<AnalysisModel<AnalysisT>>(op);
-  }
-
-  Operation *ir;
-  ConceptMap analyses;
-};
-
-/// An analysis map that contains a map for the current operation, and a set of
-/// maps for any child operations.
-struct NestedAnalysisMap {
-  NestedAnalysisMap(Operation *op, PassInstrumentor *instrumentor)
-      : analyses(op), parentOrInstrumentor(instrumentor) {}
-  NestedAnalysisMap(Operation *op, NestedAnalysisMap *parent)
-      : analyses(op), parentOrInstrumentor(parent) {}
-
-  /// Get the operation for this analysis map.
-  Operation *getOperation() const { return analyses.getOperation(); }
-
-  /// Invalidate any non preserved analyses.
-  void invalidate(const PreservedAnalyses &pa);
-
-  /// Returns the parent analysis map for this analysis map, or null if this is
-  /// the top-level map.
-  const NestedAnalysisMap *getParent() const {
-    return llvm::dyn_cast_if_present<NestedAnalysisMap *>(parentOrInstrumentor);
-  }
-
-  /// Returns a pass instrumentation object for the current operation. This
-  /// value may be null.
-  PassInstrumentor *getPassInstrumentor() const {
-    if (auto *parent = getParent())
-      return parent->getPassInstrumentor();
-    return cast<PassInstrumentor *>(parentOrInstrumentor);
-  }
-
-  /// The cached analyses for nested operations.
-  DenseMap<Operation *, std::unique_ptr<NestedAnalysisMap>> childAnalyses;
-
-  /// The analyses for the owning operation.
-  detail::AnalysisMap analyses;
-
-  /// This value has three possible states:
-  /// NestedAnalysisMap*: A pointer to the parent analysis map.
-  /// PassInstrumentor*: This analysis map is the top-level map, and this
-  ///                    pointer is the optional pass instrumentor for the
-  ///                    current compilation.
-  /// nullptr: This analysis map is the top-level map, and there is nop pass
-  ///          instrumentor.
-  PointerUnion<NestedAnalysisMap *, PassInstrumentor *> parentOrInstrumentor;
-};
-} // namespace detail
-
-//===----------------------------------------------------------------------===//
-// Analysis Management
-//===----------------------------------------------------------------------===//
-class ModuleAnalysisManager;
-
-/// This class represents an analysis manager for a particular operation
-/// instance. It is used to manage and cache analyses on the operation as well
-/// as those for child operations, via nested AnalysisManager instances
-/// accessible via 'slice'. This class is intended to be passed around by value,
-/// and cannot be constructed directly.
-class AnalysisManager {
-  using ParentPointerT =
-      PointerUnion<const ModuleAnalysisManager *, const AnalysisManager *>;
-
-public:
-  using PreservedAnalyses = detail::PreservedAnalyses;
-
-  /// Query for a cached analysis on the given parent operation. The analysis
-  /// may not exist and if it does it may be out-of-date.
-  template <typename AnalysisT>
-  std::optional<std::reference_wrapper<AnalysisT>>
-  getCachedParentAnalysis(Operation *parentOp) const {
-    const detail::NestedAnalysisMap *curParent = impl;
-    while (auto *parentAM = curParent->getParent()) {
-      if (parentAM->getOperation() == parentOp)
-        return parentAM->analyses.getCachedAnalysis<AnalysisT>();
-      curParent = parentAM;
-    }
-    return std::nullopt;
-  }
-
-  /// Query for the given analysis for the current operation.
-  template <typename AnalysisT>
-  AnalysisT &getAnalysis() {
-    return impl->analyses.getAnalysis<AnalysisT>(getPassInstrumentor(), *this);
-  }
-
-  /// Query for the given analysis for the current operation of a specific
-  /// derived operation type.
-  template <typename AnalysisT, typename OpT>
-  AnalysisT &getAnalysis() {
-    return impl->analyses.getAnalysis<AnalysisT, OpT>(getPassInstrumentor(),
-                                                      *this);
-  }
-
-  /// Query for a cached entry of the given analysis on the current operation.
-  template <typename AnalysisT>
-  std::optional<std::reference_wrapper<AnalysisT>> getCachedAnalysis() const {
-    return impl->analyses.getCachedAnalysis<AnalysisT>();
-  }
-
-  /// Query for an analysis of a child operation, constructing it if necessary.
-  template <typename AnalysisT>
-  AnalysisT &getChildAnalysis(Operation *op) {
-    return nest(op).template getAnalysis<AnalysisT>();
-  }
-
-  /// Query for an analysis of a child operation of a specific derived operation
-  /// type, constructing it if necessary.
-  template <typename AnalysisT, typename OpT>
-  AnalysisT &getChildAnalysis(OpT child) {
-    return nest(child).template getAnalysis<AnalysisT, OpT>();
-  }
-
-  /// Query for a cached analysis of a child operation, or return null.
-  template <typename AnalysisT>
-  std::optional<std::reference_wrapper<AnalysisT>>
-  getCachedChildAnalysis(Operation *op) const {
-    assert(op->getParentOp() == impl->getOperation());
-    auto it = impl->childAnalyses.find(op);
-    if (it == impl->childAnalyses.end())
-      return std::nullopt;
-    return it->second->analyses.getCachedAnalysis<AnalysisT>();
-  }
-
-  /// Get an analysis manager for the given operation, which must be a proper
-  /// descendant of the current operation represented by this analysis manager.
-  AnalysisManager nest(Operation *op);
-
-  /// Invalidate any non preserved analyses,
-  void invalidate(const PreservedAnalyses &pa) { impl->invalidate(pa); }
-
-  /// Clear any held analyses.
-  void clear() {
-    impl->analyses.clear();
-    impl->childAnalyses.clear();
-  }
-
-  /// Returns a pass instrumentation object for the current operation. This
-  /// value may be null.
-  PassInstrumentor *getPassInstrumentor() const {
-    return impl->getPassInstrumentor();
-  }
-
-private:
-  AnalysisManager(detail::NestedAnalysisMap *impl) : impl(impl) {}
-
-  /// Get an analysis manager for the given immediately nested child operation.
-  AnalysisManager nestImmediate(Operation *op);
-
-  /// A reference to the impl analysis map within the parent analysis manager.
-  detail::NestedAnalysisMap *impl;
-
-  /// Allow access to the constructor.
-  friend class ModuleAnalysisManager;
-};
-
-/// An analysis manager class specifically for the top-level operation. This
-/// class contains the memory allocations for all nested analysis managers, and
-/// provides an anchor point. This is necessary because AnalysisManager is
-/// designed to be a thin wrapper around an existing analysis map instance.
-class ModuleAnalysisManager {
-public:
-  ModuleAnalysisManager(Operation *op, PassInstrumentor *passInstrumentor)
-      : analyses(op, passInstrumentor) {}
-  ModuleAnalysisManager(const ModuleAnalysisManager &) = delete;
-  ModuleAnalysisManager &operator=(const ModuleAnalysisManager &) = delete;
-
-  /// Returns an analysis manager for the current top-level module.
-  operator AnalysisManager() { return AnalysisManager(&analyses); }
-
-private:
-  /// The analyses for the owning module.
-  detail::NestedAnalysisMap analyses;
-};
-
-} // namespace mlir
+#include "mlir/Analysis/AnalysisManager.h" // IWYU pragma: export
+#include "mlir/Pass/PassInstrumentation.h" // IWYU pragma: export
 
 #endif // MLIR_PASS_ANALYSISMANAGER_H
diff --git a/mlir/include/mlir/Pass/Pass.h b/mlir/include/mlir/Pass/Pass.h
index ea4baa27fbc2d3..b432ef16116a69 100644
--- a/mlir/include/mlir/Pass/Pass.h
+++ b/mlir/include/mlir/Pass/Pass.h
@@ -9,8 +9,8 @@
 #ifndef MLIR_PASS_PASS_H
 #define MLIR_PASS_PASS_H
 
+#include "mlir/Analysis/AnalysisManager.h"
 #include "mlir/IR/Action.h"
-#include "mlir/Pass/AnalysisManager.h"
 #include "mlir/Pass/PassRegistry.h"
 #include "llvm/ADT/PointerIntPair.h"
 #include "llvm/ADT/Statistic.h"
diff --git a/mlir/include/mlir/Pass/PassInstrumentation.h b/mlir/include/mlir/Pass/PassInstrumentation.h
index f74dc732278b44..234d6bfb93df65 100644
--- a/mlir/include/mlir/Pass/PassInstrumentation.h
+++ b/mlir/include/mlir/Pass/PassInstrumentation.h
@@ -9,6 +9,7 @@
 #ifndef MLIR_PASS_PASSINSTRUMENTATION_H_
 #define MLIR_PASS_PASSINSTRUMENTATION_H_
 
+#include "mlir/Analysis/AnalysisInstrumentation.h"
 #include "mlir/Support/LLVM.h"
 #include "mlir/Support/TypeID.h"
 #include <optional>
@@ -95,12 +96,12 @@ class PassInstrumentation {
 
 /// This class holds a collection of PassInstrumentation objects, and invokes
 /// their respective call backs.
-class PassInstrumentor {
+class PassInstrumentor final : public AnalysisInstrumentation {
 public:
   PassInstrumentor();
   PassInstrumentor(PassInstrumentor &&) = delete;
   PassInstrumentor(const PassInstrumentor &) = delete;
-  ~PassInstrumentor();
+  ~PassInstrumentor() override;
 
   /// See PassInstrumentation::runBeforePipeline for details.
   void
@@ -122,10 +123,10 @@ class PassInstrumentor {
   void runAfterPassFailed(Pass *pass, Operation *op);
 
   /// See PassInstrumentation::runBeforeAnalysis for details.
-  void runBeforeAnalysis(StringRef name, TypeID id, Operation *op);
+  void runBeforeAnalysis(StringRef name, TypeID id, Operation *op) override;
 
   /// See PassInstrumentation::runAfterAnalysis for details.
-  void runAfterAnalysis(StringRef name, TypeID id, Operation *op);
+  void runAfterAnalysis(StringRef name, TypeID id, Operation *op) override;
 
   /// Add the given instrumentation to the collection.
   void addInstrumentation(std::unique_ptr<PassInstrumentation> pi);
@@ -133,7 +134,6 @@ class PassInstrumentor {
 private:
   std::unique_ptr<detail::PassInstrumentorImpl> impl;
 };
-
 } // namespace mlir
 
 namespace llvm {
diff --git a/mlir/include/mlir/Transforms/Inliner.h b/mlir/include/mlir/Transforms/Inliner.h
index 0d3d3d1a3f9f2a..565b9d5524d937 100644
--- a/mlir/include/mlir/Transforms/Inliner.h
+++ b/mlir/include/mlir/Transforms/Inliner.h
@@ -13,9 +13,9 @@
 #ifndef MLIR_TRANSFORMS_INLINER_H
 #define MLIR_TRANSFORMS_INLINER_H
 
+#include "mlir/Analysis/AnalysisManager.h"
 #include "mlir/Analysis/CallGraph.h"
 #include "mlir/Interfaces/CallInterfaces.h"
-#include "mlir/Pass/AnalysisManager.h"
 #include "mlir/Pass/PassManager.h"
 #include "mlir/Transforms/InliningUtils.h"
 #include "llvm/ADT/StringMap.h"
diff --git a/mlir/lib/Analysis/AnalysisManager.cpp b/mlir/lib/Analysis/AnalysisManager.cpp
new file mode 100644
index 00000000000000..7acd9d79829183
--- /dev/null
+++ b/mlir/lib/Analysis/AnalysisManager.cpp
@@ -0,0 +1,77 @@
+//===- AnalysisManager.cpp - Analysis management --------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+#include "mlir/Analysis/AnalysisManager.h"
+
+using namespace mlir;
+
+AnalysisInstrumentation::~AnalysisInstrumentation() = default;
+
+/// Get an analysis manager for the given operation, which must be a proper
+/// descendant of the current operation represented by this analysis manager.
+AnalysisManager AnalysisManager::nest(Operation *op) {
+  Operation *currentOp = impl->getOperation();
+  assert(currentOp->isProperAncestor(op) &&
+         "expected valid descendant operation");
+
+  // Check for the base case where the provided operation is immediately nested.
+  if (currentOp == op->getParentOp())
+    return nestImmediate(op);
+
+  // Otherwise, we need to collect all ancestors up to the current operation.
+  SmallVector<Operation *, 4> opAncestors;
+  do {
+    opAncestors.push_back(op);
+    op = op->getParentOp();
+  } while (op != currentOp);
+
+  AnalysisManager result = *this;
+  for (Operation *op : llvm::reverse(opAncestors))
+    result = result.nestImmediate(op);
+  return result;
+}
+
+/// Get an analysis manager for the given immediately nested child operation.
+AnalysisManager AnalysisManager::nestImmediate(Operation *op) {
+  assert(impl->getOperation() == op->getParentOp() &&
+         "expected immediate child operation");
+
+  auto [it, inserted] = impl->childAnalyses.try_emplace(op);
+  if (inserted)
+    it->second = std::make_unique<detail::NestedAnalysisMap>(op, impl);
+  return {it->second.get()};
+}
+
+/// Invalidate any non preserved analyses.
+void detail::NestedAnalysisMap::invalidate(
+    const detail::PreservedAnalyses &pa) {
+  // If all analyses were preserved, then there is nothing to do here.
+  if (pa.isAll())
+    return;
+
+  // Invalidate the analyses for the current operation directly.
+  analyses.invalidate(pa);
+
+  // If no analyses were preserved, then just simply clear out the child
+  // analysis results.
+  if (pa.isNone()) {
+    childAnalyses.clear();
+    return;
+  }
+
+  // Otherwise, invalidate each child analysis map.
+  SmallVector<NestedAnalysisMap *, 8> mapsToInvalidate(1, this);
+  while (!mapsToInvalidate.empty()) {
+    auto *map = mapsToInvalidate.pop_back_val();
+    for (auto &analysisPair : map->childAnalyses) {
+      analysisPair.second->invalidate(pa);
+      if (!analysisPair.second->childAnalyses.empty())
+        mapsToInvalidate.push_back(analysisPair.second.get());
+    }
+  }
+}
diff --git a/mlir/lib/Analysis/CMakeLists.txt b/mlir/lib/Analysis/CMakeLists.txt
index 72171a52335cdf..2209c29a42c904 100644
--- a/mlir/lib/Analysis/CMakeLists.txt
+++ b/mlir/lib/Analysis/CMakeLists.txt
@@ -23,6 +23,15 @@
 
 add_subdirectory(Presburger)
 
+add_mlir_library(MLIRAnalysisManager
+  AnalysisManager.cpp
+
+  PARTIAL_SOURCES_INTENDED
+
+  LINK_LIBS PUBLIC
+  MLIRIR
+  )
+
 # Keep source ownership separate from the umbrella archive below. Object
 # libraries let both archives reuse the same compilations, including in shared
 # library builds.
@@ -44,6 +53,7 @@ add_mlir_library(MLIRAnalysisBase
   ${MLIR_MAIN_INCLUDE_DIR}/mlir/Analysis
 
   LINK_LIBS PUBLIC
+  MLIRAnalysisManager
   MLIRCallInterfaces
   MLIRControlFlowInterfaces
   MLIRDataLayoutInterfaces
diff --git a/mlir/lib/Pass/CMakeLists.txt b/mlir/lib/Pass/CMakeLists.txt
index 11eec3689c4558..3f66256346a425 100644
--- a/mlir/lib/Pass/CMakeLists.txt
+++ b/mlir/lib/Pass/CMakeLists.txt
@@ -14,5 +14,6 @@ add_mlir_library(MLIRPass
   mlir-generic-headers
 
   LINK_LIBS PUBLIC
+  MLIRAnalysisManager
   MLIRIR
   )
diff --git a/mlir/lib/Pass/Pass.cpp b/mlir/lib/Pass/Pass.cpp
index 303562a2af6ee6..abcb0f07f56920 100644
--- a/mlir/lib/Pass/Pass.cpp
+++ b/mlir/lib/Pass/Pass.cpp
@@ -548,7 +548,8 @@ llvm::hash_code OpPassManager::hash() {
 
 LogicalResult OpToOpPassAdaptor::run(Pass *pass, Operation *op,
                                      AnalysisManager am, bool verifyPasses,
-                                     unsigned parentInitGeneration) {
+                                     unsigned parentInitGeneration,
+                                     PassInstrumentor *pi) {
   LDBG() << "Running pass '" << pass->getName() << "' on operation '"
          << OpWithFlags(op, OpPrintingFlags().skipRegions()) << "' at "
          << op->getLoc();
@@ -569,7 +570,6 @@ LogicalResult OpToOpPassAdaptor::run(Pass *pass, Operation *op,
 
   // Initialize the pass state with a callback for the pass to dynamically
   // execute a pipeline on the currently visited operation.
-  PassInstrumentor *pi = am.getPassInstrumentor();
   PassInstrumentation::PipelineParentInfo parentInfo = {llvm::get_threadid(),
                                                         pass};
   auto dynamicPipelineCallback = [&](OpPassManager &pipeline,
@@ -610,7 +610,7 @@ LogicalResult OpToOpPassAdaptor::run(Pass *pass, Operation *op,
         [&]() {
           // Invoke the virtual runOnOperation method.
           if (auto *adaptor = dyn_cast<OpToOpPassAdaptor>(pass))
-            adaptor->runOnOperation(verifyPasses);
+            adaptor->runOnOperation(verifyPasses, pi);
           else
             pass->runOnOperation();
           passFailed = pass->passState->irAndPassFailed.getInt();
@@ -671,8 +671,6 @@ LogicalResult OpToOpPassAdaptor::runPipeline(
        << " pipeline: ";
     pm.printAsTextualPipeline(os, /*pretty=*/false);
   });
-  assert((!instrumentor || parentInfo) &&
-         "expected parent info if instrumentor is provided");
   llvm::scope_exit scopeExit([&] {
     // Clear out any computed operation analyses. These analyses won't be used
     // any more in this pipeline, and this helps reduce the current working set
@@ -682,13 +680,14 @@ LogicalResult OpToOpPassAdaptor::runPipeline(
   });
 
   // Run the pipeline over the provided operation.
-  if (instrumentor) {
+  if (instrumentor && parentInfo) {
     instrumentor->runBeforePipeline(pm.getOpName(*op->getContext()),
                                     *parentInfo);
   }
 
   for (Pass &pass : pm.getPasses()) {
-    if (failed(run(&pass, op, am, verifyPasses, parentInitGeneration))) {
+    if (failed(run(&pass, op, am, verifyPasses, parentInitGeneration,
+                   instrumentor))) {
       LDBG() << "Pipeline failed for pass '" << pass.getName()
              << "' on operation '"
              << OpWithFlags(op, OpPrintingFlags().skipRegions()) << "'";
@@ -696,7 +695,7 @@ LogicalResult OpToOpPassAdaptor::runPipeline(
     }
   }
 
-  if (instrumentor) {
+  if (instrumentor && parentInfo) {
     instrumentor->runAfterPipeline(pm.getOpName(*op->getContext()),
                                    *parentInfo);
   }
@@ -847,15 +846,17 @@ void OpToOpPassAdaptor::runOnOperation() {
 }
 
 /// Run the held pipeline over all nested operations.
-void OpToOpPassAdaptor::runOnOperation(bool verifyPasses) {
+void OpToOpPassAdaptor::runOnOperation(bool verifyPasses,
+                                       PassInstrumentor *instrumentor) {
   if (getContext().isMultithreadingEnabled())
-    runOnOperationAsyncImpl(verifyPasses);
+    runOnOperationAsyncImpl(verifyPasses, instrumentor);
   else
-    runOnOperationImpl(verifyPasses);
+    runOnOperationImpl(verifyPasses, instrumentor);
 }
 
 /// Run this pass adaptor synchronously.
-void OpToOpPassAdaptor::runOnOperationImpl(bool verifyPasses) {
+void OpToOpPassAdaptor::runOnOperationImpl(bool verifyPasses,
+                                           PassInstrumentor *instrumentor) {
   LDBG_OS([&](raw_ostream &os) {
     os << "Running pass adaptor synchronously on operation '"
        << OpWithFlags(getOperation(), OpPrintingFlags().skipRegions())
@@ -867,7 +868,6 @@ void OpToOpPassAdaptor::runOnOperationImpl(bool verifyPasses) {
   auto am = getAnalysisManager();
   PassInstrumentation::PipelineParentInfo parentInfo = {llvm::get_threadid(),
                                                         this};
-  auto *instrumentor = am.getPassInstrumentor();
 
   unsigned processedOps = 0;
   for (auto &region : getOperation()->getRegions()) {
@@ -913,7 +913,8 @@ static bool hasSizeMismatch(ArrayRef<OpPassManager> lhs,
 }
 
 /// Run this pass adaptor synchronously.
-void OpToOpPassAdaptor::runOnOperationAsyncImpl(bool verifyPasses) {
+void OpToOpPassAdaptor::runOnOperationAsyncImpl(
+    bool verifyPasses, PassInstrumentor *instrumentor) {
   LDBG_OS([&](raw_ostream &os) {
     os << "Running pass adaptor asynchronously on operation '"
        << OpWithFlags(getOperation(), OpPrintingFlags().skipRegions())
@@ -985,7 +986,6 @@ void OpToOpPassAdaptor::runOnOperationAsyncImpl(bool verifyPasses) {
   // Get the current thread for this adaptor.
   PassInstrumentation::PipelineParentInfo parentInfo = {llvm::get_threadid(),
                                                         this};
-  auto *instrumentor = am.getPassInstrumentor();
 
   // Each parallel task owns an executor for its entire lifetime. A worker
   // index belongs to the task, rather than the thread: nested waits may run
@@ -1122,75 +1122,8 @@ void PassManager::addInstrumentation(std::unique_ptr<PassInstrumentation> pi) {
 LogicalResult PassManager::runPasses(Operation *op, AnalysisManager am) {
   LDBG(2) << "Executing passes using OpToOpPassAdaptor pipeline";
   return OpToOpPassAdaptor::runPipeline(*this, op, am, verifyPasses,
-                                        impl->initializationGeneration);
-}
-
-//===----------------------------------------------------------------------===//
-// AnalysisManager
-//===----------------------------------------------------------------------===//
-
-/// Get an analysis manager for the given operation, which must be a proper
-/// descendant of the current operation represented by this analysis manager.
-AnalysisManager AnalysisManager::nest(Operation *op) {
-  Operation *currentOp = impl->getOperation();
-  assert(currentOp->isProperAncestor(op) &&
-         "expected valid descendant operation");
-
-  // Check for the base case where the provided operation is immediately nested.
-  if (currentOp == op->getParentOp())
-    return nestImmediate(op);
-
-  // Otherwise, we need to collect all ancestors up to the current operation.
-  SmallVector<Operation *, 4> opAncestors;
-  do {
-    opAncestors.push_back(op);
-    op = op->getParentOp();
-  } while (op != currentOp);
-
-  AnalysisManager result = *this;
-  for (Operation *op : llvm::reverse(opAncestors))
-    result = result.nestImmediate(op);
-  return result;
-}
-
-/// Get an analysis manager for the given immediately nested child operation.
-AnalysisManager AnalysisManager::nestImmediate(Operation *op) {
-  assert(impl->getOperation() == op->getParentOp() &&
-         "expected immediate child operation");
-
-  auto [it, inserted] = impl->childAnalyses.try_emplace(op);
-  if (inserted)
-    it->second = std::make_unique<NestedAnalysisMap>(op, impl);
-  return {it->second.get()};
-}
-
-/// Invalidate any non preserved analyses.
-void detail::NestedAnalysisMap::invalidate(
-    const detail::PreservedAnalyses &pa) {
-  // If all analyses were preserved, then there is nothing to do here.
-  if (pa.isAll())
-    return;
-
-  // Invalidate the analyses for the current operation directly.
-  analyses.invalidate(pa);
-
-  // If no analyses were preserved, then just simply clear out the child
-  // analysis results.
-  if (pa.isNone()) {
-    childAnalyses.clear();
-    return;
-  }
-
-  // Otherwise, invalidate each child analysis map.
-  SmallVector<NestedAnalysisMap *, 8> mapsToInvalidate(1, this);
-  while (!mapsToInvalidate.empty()) {
-    auto *map = mapsToInvalidate.pop_back_val();
-    for (auto &analysisPair : map->childAnalyses) {
-      analysisPair.second->invalidate(pa);
-      if (!analysisPair.second->childAnalyses.empty())
-        mapsToInvalidate.push_back(analysisPair.second.get());
-    }
-  }
+                                        impl->initializationGeneration,
+                                        instrumentor.get());
 }
 
 //===----------------------------------------------------------------------===//
diff --git a/mlir/lib/Pass/PassDetail.h b/mlir/lib/Pass/PassDetail.h
index 5cc726295c9f11..90bb4142c7425a 100644
--- a/mlir/lib/Pass/PassDetail.h
+++ b/mlir/lib/Pass/PassDetail.h
@@ -10,6 +10,7 @@
 
 #include "mlir/IR/Action.h"
 #include "mlir/Pass/Pass.h"
+#include "mlir/Pass/PassInstrumentation.h"
 #include "mlir/Pass/PassManager.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/Support/FormatVariadic.h"
@@ -29,7 +30,7 @@ class OpToOpPassAdaptor
   OpToOpPassAdaptor(const OpToOpPassAdaptor &rhs) = default;
 
   /// Run the held pipeline over all operations.
-  void runOnOperation(bool verifyPasses);
+  void runOnOperation(bool verifyPasses, PassInstrumentor *instrumentor);
   void runOnOperation() override;
 
   /// Try to merge the current pass adaptor into 'rhs'. This will try to append
@@ -60,17 +61,19 @@ class OpToOpPassAdaptor
 
 private:
   /// Run this pass adaptor synchronously.
-  void runOnOperationImpl(bool verifyPasses);
+  void runOnOperationImpl(bool verifyPasses, PassInstrumentor *instrumentor);
 
   /// Run this pass adaptor asynchronously.
-  void runOnOperationAsyncImpl(bool verifyPasses);
+  void runOnOperationAsyncImpl(bool verifyPasses,
+                               PassInstrumentor *instrumentor);
 
   /// Run the given operation and analysis manager on a single pass.
   /// `parentInitGeneration` is the initialization generation of the parent pass
   /// manager, and is used to initialize any dynamic pass pipelines run by the
   /// given pass.
   static LogicalResult run(Pass *pass, Operation *op, AnalysisManager am,
-                           bool verifyPasses, unsigned parentInitGeneration);
+                           bool verifyPasses, unsigned parentInitGeneration,
+                           PassInstrumentor *instrumentor);
 
   /// Run the given operation and analysis manager on a provided op pass
   /// manager. `parentInitGeneration` is the initialization generation of the
@@ -78,7 +81,7 @@ class OpToOpPassAdaptor
   /// run by the given passes.
   static LogicalResult runPipeline(
       OpPassManager &pm, Operation *op, AnalysisManager am, bool verifyPasses,
-      unsigned parentInitGeneration, PassInstrumentor *instrumentor = nullptr,
+      unsigned parentInitGeneration, PassInstrumentor *instrumentor,
       const PassInstrumentation::PipelineParentInfo *parentInfo = nullptr);
 
   /// A set of adaptors to run.
diff --git a/mlir/unittests/Pass/AnalysisManagerTest.cpp b/mlir/unittests/Pass/AnalysisManagerTest.cpp
index 1a28659f47e645..7c5fe2b7b00af4 100644
--- a/mlir/unittests/Pass/AnalysisManagerTest.cpp
+++ b/mlir/unittests/Pass/AnalysisManagerTest.cpp
@@ -6,7 +6,7 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "mlir/Pass/AnalysisManager.h"
+#include "mlir/Analysis/AnalysisManager.h"
 #include "mlir/Dialect/Func/IR/FuncOps.h"
 #include "mlir/IR/Builders.h"
 #include "mlir/IR/BuiltinOps.h"
@@ -40,7 +40,7 @@ TEST(AnalysisManagerTest, FineGrainModuleAnalysisPreservation) {
 
   // Test fine grain invalidation of the module analysis manager.
   OwningOpRef<ModuleOp> module(ModuleOp::create(UnknownLoc::get(&context)));
-  ModuleAnalysisManager mam(*module, /*passInstrumentor=*/nullptr);
+  ModuleAnalysisManager mam(*module);
   AnalysisManager am = mam;
 
   // Query two different analyses, but only preserve one before invalidating.
@@ -69,7 +69,7 @@ TEST(AnalysisManagerTest, FineGrainFunctionAnalysisPreservation) {
   module->push_back(func1);
 
   // Test fine grain invalidation of the function analysis manager.
-  ModuleAnalysisManager mam(*module, /*passInstrumentor=*/nullptr);
+  ModuleAnalysisManager mam(*module);
   AnalysisManager am = mam;
   AnalysisManager fam = am.nest(func1);
 
@@ -100,7 +100,7 @@ TEST(AnalysisManagerTest, FineGrainChildFunctionAnalysisPreservation) {
 
   // Test fine grain invalidation of a function analysis from within a module
   // analysis manager.
-  ModuleAnalysisManager mam(*module, /*passInstrumentor=*/nullptr);
+  ModuleAnalysisManager mam(*module);
   AnalysisManager am = mam;
 
   // Check that the analysis cache is initially empty.
@@ -140,7 +140,7 @@ TEST(AnalysisManagerTest, CustomInvalidation) {
 
   // Create a function and a module.
   OwningOpRef<ModuleOp> module(ModuleOp::create(UnknownLoc::get(&context)));
-  ModuleAnalysisManager mam(*module, /*passInstrumentor=*/nullptr);
+  ModuleAnalysisManager mam(*module);
   AnalysisManager am = mam;
 
   detail::PreservedAnalyses pa;
@@ -162,7 +162,7 @@ TEST(AnalysisManagerTest, OpSpecificAnalysis) {
 
   // Create a module.
   OwningOpRef<ModuleOp> module(ModuleOp::create(UnknownLoc::get(&context)));
-  ModuleAnalysisManager mam(*module, /*passInstrumentor=*/nullptr);
+  ModuleAnalysisManager mam(*module);
   AnalysisManager am = mam;
 
   // Query the op specific analysis for the module and verify that its cached.
@@ -188,7 +188,7 @@ TEST(AnalysisManagerTest, DependentAnalysis) {
 
   // Create a module.
   OwningOpRef<ModuleOp> module(ModuleOp::create(UnknownLoc::get(&context)));
-  ModuleAnalysisManager mam(*module, /*passInstrumentor=*/nullptr);
+  ModuleAnalysisManager mam(*module);
   AnalysisManager am = mam;
 
   am.getAnalysis<AnalysisWithDependency>();
@@ -221,7 +221,7 @@ TEST(AnalysisManagerTest, NestedDependentAnalysis) {
 
   // Create a module.
   OwningOpRef<ModuleOp> module(ModuleOp::create(UnknownLoc::get(&context)));
-  ModuleAnalysisManager mam(*module, /*passInstrumentor=*/nullptr);
+  ModuleAnalysisManager mam(*module);
   AnalysisManager am = mam;
 
   am.getAnalysis<AnalysisWithNestedDependency>();
@@ -256,7 +256,7 @@ TEST(AnalysisManagerTest, DependentAnalysis2Ctors) {
 
   // Create a module.
   OwningOpRef<ModuleOp> module(ModuleOp::create(UnknownLoc::get(&context)));
-  ModuleAnalysisManager mam(*module, /*passInstrumentor=*/nullptr);
+  ModuleAnalysisManager mam(*module);
   AnalysisManager am = mam;
 
   auto &an = am.getAnalysis<AnalysisWith2Ctors>();

>From 148ab743823b7ef3dab643d2ddd86af90246d639 Mon Sep 17 00:00:00 2001
From: Ivan Butygin <ivan.butygin at gmail.com>
Date: Mon, 30 Nov 2026 15:38:49 +0100
Subject: [PATCH 2/3] [mlir] Pass analyses to speculation hooks and LICM

Let ConditionallySpeculatable models implement either the simple hook or one that accepts a nullable AnalysisManager. Forward the manager through recursive purity queries and loop-invariant code motion. Exercise the simple external model through both entry points.
---
 clang/include/clang/CIR/Dialect/IR/CIROps.td  |  3 ++
 mlir/include/mlir/Dialect/EmitC/IR/EmitC.td   |  2 +-
 mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td   |  8 ++---
 .../Dialect/Linalg/IR/LinalgStructuredOps.td  |  2 +-
 .../mlir/Dialect/Vector/IR/VectorOps.td       |  4 +--
 .../mlir/Interfaces/SideEffectInterfaces.h    | 10 +++---
 .../mlir/Interfaces/SideEffectInterfaces.td   | 34 ++++++++++++++-----
 .../Transforms/LoopInvariantCodeMotionUtils.h |  8 +++--
 mlir/lib/CAPI/Interfaces/Interfaces.cpp       |  7 +++-
 mlir/lib/Interfaces/SideEffectInterfaces.cpp  | 10 +++---
 .../Transforms/LoopInvariantCodeMotion.cpp    |  6 ++--
 .../Utils/LoopInvariantCodeMotionUtils.cpp    | 20 ++++++-----
 mlir/unittests/Interfaces/CMakeLists.txt      | 12 ++++++-
 .../Interfaces/SideEffectInterfacesTest.cpp   | 21 ++++++++++++
 14 files changed, 106 insertions(+), 41 deletions(-)

diff --git a/clang/include/clang/CIR/Dialect/IR/CIROps.td b/clang/include/clang/CIR/Dialect/IR/CIROps.td
index a0d7b57b46ab70..d146bfa4f61d29 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIROps.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIROps.td
@@ -215,6 +215,9 @@ def SameOperandsPointeeType : PredOpTrait<
 //===----------------------------------------------------------------------===//
 
 def CIR_FenvOpTrait : NativeOpTrait<"FenvOpTrait"> {
+  let extraConcreteClassDeclaration = [{
+    using FenvOpTrait::getSpeculatability;
+  }];
   let cppNamespace = "::cir";
 }
 
diff --git a/mlir/include/mlir/Dialect/EmitC/IR/EmitC.td b/mlir/include/mlir/Dialect/EmitC/IR/EmitC.td
index f08dac13972688..941172c1fad34f 100644
--- a/mlir/include/mlir/Dialect/EmitC/IR/EmitC.td
+++ b/mlir/include/mlir/Dialect/EmitC/IR/EmitC.td
@@ -397,7 +397,7 @@ def EmitC_MemberCallOpaqueOp : EmitC_Op<"member_call_opaque", [CExpressionInterf
 def EmitC_CastOp : EmitC_Op<"cast",
     [CExpressionInterface,
      DeclareOpInterfaceMethods<CastOpInterface>,
-     DeclareOpInterfaceMethods<ConditionallySpeculatable>,
+     DeclareOpInterfaceMethods<ConditionallySpeculatable, ["getSpeculatability"]>,
      DeclareOpInterfaceMethods<MemoryEffectsOpInterface>
     ]> {
   let summary = "Cast operation";
diff --git a/mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td b/mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td
index 906352fdece445..39457b96807d45 100644
--- a/mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td
+++ b/mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td
@@ -159,15 +159,15 @@ def LLVM_SubOp : LLVM_IntArithmeticOpWithOverflowFlag<"sub", "Sub", [Pure]>;
 def LLVM_MulOp : LLVM_IntArithmeticOpWithOverflowFlag<"mul", "Mul",
     [Commutative, Pure]>;
 def LLVM_UDivOp : LLVM_IntArithmeticOpWithExactFlag<"udiv", "UDiv",
-    [DeclareOpInterfaceMethods<ConditionallySpeculatable>]>;
+    [DeclareOpInterfaceMethods<ConditionallySpeculatable, ["getSpeculatability"]>]>;
 def LLVM_SDivOp : LLVM_IntArithmeticOpWithExactFlag<"sdiv", "SDiv",
-    [DeclareOpInterfaceMethods<ConditionallySpeculatable>]>;
+    [DeclareOpInterfaceMethods<ConditionallySpeculatable, ["getSpeculatability"]>]>;
 def LLVM_URemOp : LLVM_IntArithmeticOp<
     "urem", "URem",
-    [DeclareOpInterfaceMethods<ConditionallySpeculatable>]>;
+    [DeclareOpInterfaceMethods<ConditionallySpeculatable, ["getSpeculatability"]>]>;
 def LLVM_SRemOp : LLVM_IntArithmeticOp<
     "srem", "SRem",
-    [DeclareOpInterfaceMethods<ConditionallySpeculatable>]>;
+    [DeclareOpInterfaceMethods<ConditionallySpeculatable, ["getSpeculatability"]>]>;
 def LLVM_AndOp : LLVM_IntArithmeticOp<"and", "And", [Pure]>;
 def LLVM_OrOp : LLVM_IntArithmeticOpWithDisjointFlag<"or", "Or", [Pure]> {
   let hasFolder = 1;
diff --git a/mlir/include/mlir/Dialect/Linalg/IR/LinalgStructuredOps.td b/mlir/include/mlir/Dialect/Linalg/IR/LinalgStructuredOps.td
index 7054c5ff4962d0..2fc2b53adf2193 100644
--- a/mlir/include/mlir/Dialect/Linalg/IR/LinalgStructuredOps.td
+++ b/mlir/include/mlir/Dialect/Linalg/IR/LinalgStructuredOps.td
@@ -29,7 +29,7 @@ class LinalgStructuredBase_Op<string mnemonic, list<Trait> props>
   : Op<Linalg_Dialect, mnemonic, !listconcat([
        SingleBlockImplicitTerminator<"YieldOp">,
        DeclareOpInterfaceMethods<MemoryEffectsOpInterface>,
-       DeclareOpInterfaceMethods<ConditionallySpeculatable>,
+       DeclareOpInterfaceMethods<ConditionallySpeculatable, ["getSpeculatability"]>,
        RecursiveMemoryEffects,
        DestinationStyleOpInterface,
        LinalgStructuredInterface,
diff --git a/mlir/include/mlir/Dialect/Vector/IR/VectorOps.td b/mlir/include/mlir/Dialect/Vector/IR/VectorOps.td
index d8f0e7dbd8caa9..71dfb2b4d5ae50 100644
--- a/mlir/include/mlir/Dialect/Vector/IR/VectorOps.td
+++ b/mlir/include/mlir/Dialect/Vector/IR/VectorOps.td
@@ -1337,7 +1337,7 @@ def Vector_TransferReadOp :
       DeclareOpInterfaceMethods<VectorUnrollOpInterface, ["getIterationShapeToUnroll"]>,
       DeclareOpInterfaceMethods<MaskableOpInterface>,
       DeclareOpInterfaceMethods<MemoryEffectsOpInterface>,
-      DeclareOpInterfaceMethods<ConditionallySpeculatable>,
+      DeclareOpInterfaceMethods<ConditionallySpeculatable, ["getSpeculatability"]>,
       DeclareOpInterfaceMethods<MemorySpaceCastConsumerOpInterface>,
       AttrSizedOperandSegments,
       DestinationStyleOpInterface
@@ -1598,7 +1598,7 @@ def Vector_TransferWriteOp :
       DeclareOpInterfaceMethods<VectorUnrollOpInterface, ["getIterationShapeToUnroll"]>,
       DeclareOpInterfaceMethods<MaskableOpInterface>,
       DeclareOpInterfaceMethods<MemoryEffectsOpInterface>,
-      DeclareOpInterfaceMethods<ConditionallySpeculatable>,
+      DeclareOpInterfaceMethods<ConditionallySpeculatable, ["getSpeculatability"]>,
       DeclareOpInterfaceMethods<MemorySpaceCastConsumerOpInterface>,
       AttrSizedOperandSegments,
       DestinationStyleOpInterface
diff --git a/mlir/include/mlir/Interfaces/SideEffectInterfaces.h b/mlir/include/mlir/Interfaces/SideEffectInterfaces.h
index 38a1e29a71d20c..062afb8880fd9c 100644
--- a/mlir/include/mlir/Interfaces/SideEffectInterfaces.h
+++ b/mlir/include/mlir/Interfaces/SideEffectInterfaces.h
@@ -22,6 +22,8 @@
 #include <cstdint>
 
 namespace mlir {
+class AnalysisManager;
+
 namespace SideEffects {
 //===----------------------------------------------------------------------===//
 // Effects
@@ -623,16 +625,14 @@ getEffectsRecursively(Operation *rootOp);
 /// Returns true if the given operation is speculatable, i.e. has no undefined
 /// behavior or other side effects.
 ///
-/// An operation can indicate that it is speculatable by implementing the
-/// getSpeculatability hook in the ConditionallySpeculatable op interface.
-bool isSpeculatable(Operation *op);
+/// Supply the caller's analysis manager to enable proofs that use analyses.
+bool isSpeculatable(Operation *op, AnalysisManager *actx = nullptr);
 
 /// Returns true if the given operation is pure, i.e., is speculatable that does
 /// not touch memory.
 ///
 /// This function is the C++ equivalent of the `Pure` trait.
-bool isPure(Operation *op);
-
+bool isPure(Operation *op, AnalysisManager *actx = nullptr);
 } // namespace mlir
 
 //===----------------------------------------------------------------------===//
diff --git a/mlir/include/mlir/Interfaces/SideEffectInterfaces.td b/mlir/include/mlir/Interfaces/SideEffectInterfaces.td
index 6ec290dc3dc8e6..aef808261c872d 100644
--- a/mlir/include/mlir/Interfaces/SideEffectInterfaces.td
+++ b/mlir/include/mlir/Interfaces/SideEffectInterfaces.td
@@ -108,6 +108,9 @@ def RecursiveMemoryEffects : NativeOpTrait<"HasRecursiveMemoryEffects"> {
 // this directly.
 def RecursivelySpeculatableImplTrait
   : NativeOpTrait<"RecursivelySpeculatableImplTrait"> {
+  let extraConcreteClassDeclaration = [{
+    using RecursivelySpeculatableImplTrait::getSpeculatability;
+  }];
   let cppIncludes = ["mlir/Interfaces/SideEffectInterfaces.h"];
 }
 
@@ -115,18 +118,17 @@ def RecursivelySpeculatableImplTrait
 // this directly.
 def AlwaysSpeculatableImplTrait
   : NativeOpTrait<"AlwaysSpeculatableImplTrait"> {
+  let extraConcreteClassDeclaration = [{
+    using AlwaysSpeculatableImplTrait::getSpeculatability;
+  }];
   let cppIncludes = ["mlir/Interfaces/SideEffectInterfaces.h"];
 }
 
-// This op interface enables Op authors to inject custom logic to determine
-// whether an Operation can be speculatively executed.  Ops that implement this
-// interface need to implement the custom logic in the `getSpeculatability` method.
-// For instance, the `getSpeculatability` for a specific op may check the attributes
-// or input types to determine whether that specific Operation is speculatable.
 def ConditionallySpeculatable : OpInterface<"ConditionallySpeculatable"> {
   let description = [{
-    An interface used to query information about the speculability of an
-    operation.
+    Models must implement either `getSpeculatability()` or
+    `getSpeculatabilityWithAnalysis(AnalysisManager *)`. Implement the latter
+    when the proof can use analyses from the caller.
   }];
   let cppNamespace = "::mlir";
   let cppIncludes = ["mlir/Interfaces/SideEffectInterfaces.h"];
@@ -137,7 +139,23 @@ def ConditionallySpeculatable : OpInterface<"ConditionallySpeculatable"> {
         be speculatively executed.  Please see the documentation on the
         Speculatability enum to know how to interpret the return value.
       }],
-      "::mlir::Speculation::Speculatability", "getSpeculatability", (ins)>
+      "::mlir::Speculation::Speculatability", "getSpeculatability", (ins), [{}], [{
+        return ::llvm::cast<::mlir::ConditionallySpeculatable>(
+            $_op.getOperation()).getSpeculatabilityWithAnalysis(nullptr);
+      }]>,
+    InterfaceMethod<[{
+        Returns the speculatability of this operation. The analysis manager may
+        be null. In that case, use only facts available without analyses and
+        return `NotSpeculatable` if they are insufficient to prove safety.
+      }], "::mlir::Speculation::Speculatability", "getSpeculatabilityWithAnalysis",
+      (ins "::mlir::AnalysisManager *":$actx), [{}], [{
+        if constexpr (ConcreteOp::template hasTrait<
+                          ::mlir::ConditionallySpeculatable::Trait>())
+          return $_op.getSpeculatability();
+        else
+          return ::llvm::cast<::mlir::ConditionallySpeculatable>(
+              $_op.getOperation()).getSpeculatability();
+      }]>
   ];
 }
 
diff --git a/mlir/include/mlir/Transforms/LoopInvariantCodeMotionUtils.h b/mlir/include/mlir/Transforms/LoopInvariantCodeMotionUtils.h
index 8c63f29f74b63c..2ad65694083b09 100644
--- a/mlir/include/mlir/Transforms/LoopInvariantCodeMotionUtils.h
+++ b/mlir/include/mlir/Transforms/LoopInvariantCodeMotionUtils.h
@@ -14,7 +14,7 @@
 #include "llvm/ADT/SmallVector.h"
 
 namespace mlir {
-
+class AnalysisManager;
 class LoopLikeOpInterface;
 class Operation;
 class Region;
@@ -72,7 +72,8 @@ size_t moveLoopInvariantCode(
 /// methods provided by the interface. This includes code in control-flow
 /// regions nested in the loop body, see
 /// `moveLoopInvariantCodeFromNestedRegions`.
-size_t moveLoopInvariantCode(LoopLikeOpInterface loopLike);
+size_t moveLoopInvariantCode(LoopLikeOpInterface loopLike,
+                             AnalysisManager *actx = nullptr);
 
 /// Move loop invariant code out of the control-flow regions nested in the body
 /// of a loop-like op, e.g., out of an `scf.if` that stays in the loop:
@@ -91,7 +92,8 @@ size_t moveLoopInvariantCode(LoopLikeOpInterface loopLike);
 /// speculatable ops without memory effects are moved.
 ///
 /// Returns the number of operations moved.
-size_t moveLoopInvariantCodeFromNestedRegions(LoopLikeOpInterface loopLike);
+size_t moveLoopInvariantCodeFromNestedRegions(LoopLikeOpInterface loopLike,
+                                              AnalysisManager *actx = nullptr);
 
 /// Hoist loop-invariant tensor subsets (subset extraction and subset insertion
 /// ops) from loop-like ops. Extraction ops are moved before the loop. Insertion
diff --git a/mlir/lib/CAPI/Interfaces/Interfaces.cpp b/mlir/lib/CAPI/Interfaces/Interfaces.cpp
index 921d12901ec6a0..dcbf634e1545fd 100644
--- a/mlir/lib/CAPI/Interfaces/Interfaces.cpp
+++ b/mlir/lib/CAPI/Interfaces/Interfaces.cpp
@@ -219,6 +219,11 @@ class ConditionallySpeculatableOpInterfaceFallbackModel
     return true;
   }
 
+  Speculation::Speculatability
+  getSpeculatabilityWithAnalysis(Operation *op, AnalysisManager *) const {
+    return getSpeculatability(op);
+  }
+
   Speculation::Speculatability getSpeculatability(Operation *op) const {
     assert(callbacks.getSpeculatability &&
            "getSpeculatability callback not set");
@@ -266,7 +271,7 @@ MlirSpeculatability mlirConditionallySpeculatableOpInterfaceGetSpeculatability(
   auto iface = dyn_cast<ConditionallySpeculatable>(unwrap(operation));
   assert(iface && "operation does not implement ConditionallySpeculatable");
 
-  switch (iface.getSpeculatability()) {
+  switch (iface.getSpeculatabilityWithAnalysis(nullptr)) {
   case Speculation::NotSpeculatable:
     return MlirSpeculatabilityNotSpeculatable;
   case Speculation::Speculatable:
diff --git a/mlir/lib/Interfaces/SideEffectInterfaces.cpp b/mlir/lib/Interfaces/SideEffectInterfaces.cpp
index 039e6ceb44ee12..0ab30b4ddaa404 100644
--- a/mlir/lib/Interfaces/SideEffectInterfaces.cpp
+++ b/mlir/lib/Interfaces/SideEffectInterfaces.cpp
@@ -531,16 +531,16 @@ mlir::getEffectsRecursively(Operation *rootOp) {
   return effects;
 }
 
-bool mlir::isSpeculatable(Operation *op) {
+bool mlir::isSpeculatable(Operation *op, AnalysisManager *actx) {
   auto conditionallySpeculatable = dyn_cast<ConditionallySpeculatable>(op);
   if (!conditionallySpeculatable)
     return false;
 
-  switch (conditionallySpeculatable.getSpeculatability()) {
+  switch (conditionallySpeculatable.getSpeculatabilityWithAnalysis(actx)) {
   case Speculation::RecursivelySpeculatable:
     for (Region &region : op->getRegions()) {
       for (Operation &op : region.getOps())
-        if (!isSpeculatable(&op))
+        if (!isSpeculatable(&op, actx))
           return false;
     }
     return true;
@@ -557,6 +557,6 @@ bool mlir::isSpeculatable(Operation *op) {
 
 /// The implementation of this function replicates the `def Pure : TraitList`
 /// in `SideEffectInterfaces.td` and has to be kept in sync manually.
-bool mlir::isPure(Operation *op) {
-  return isSpeculatable(op) && isMemoryEffectFree(op);
+bool mlir::isPure(Operation *op, AnalysisManager *actx) {
+  return isSpeculatable(op, actx) && isMemoryEffectFree(op);
 }
diff --git a/mlir/lib/Transforms/LoopInvariantCodeMotion.cpp b/mlir/lib/Transforms/LoopInvariantCodeMotion.cpp
index 609d14d3b56388..a6625dfbf5cb35 100644
--- a/mlir/lib/Transforms/LoopInvariantCodeMotion.cpp
+++ b/mlir/lib/Transforms/LoopInvariantCodeMotion.cpp
@@ -42,8 +42,10 @@ void LoopInvariantCodeMotion::runOnOperation() {
   // Walk through all loops in a function in innermost-loop-first order. This
   // way, we first LICM from the inner loop, and place the ops in
   // the outer loop, which in turn can be further LICM'ed.
-  getOperation()->walk(
-      [&](LoopLikeOpInterface loopLike) { moveLoopInvariantCode(loopLike); });
+  AnalysisManager actx = getAnalysisManager();
+  getOperation()->walk([&](LoopLikeOpInterface loopLike) {
+    moveLoopInvariantCode(loopLike, &actx);
+  });
 }
 
 void LoopInvariantSubsetHoisting::runOnOperation() {
diff --git a/mlir/lib/Transforms/Utils/LoopInvariantCodeMotionUtils.cpp b/mlir/lib/Transforms/Utils/LoopInvariantCodeMotionUtils.cpp
index 9b88edc354ce50..eab62f6be6cf4c 100644
--- a/mlir/lib/Transforms/Utils/LoopInvariantCodeMotionUtils.cpp
+++ b/mlir/lib/Transforms/Utils/LoopInvariantCodeMotionUtils.cpp
@@ -111,15 +111,16 @@ size_t mlir::moveLoopInvariantCode(
   return numMoved;
 }
 
-size_t mlir::moveLoopInvariantCode(LoopLikeOpInterface loopLike) {
+size_t mlir::moveLoopInvariantCode(LoopLikeOpInterface loopLike,
+                                   AnalysisManager *actx) {
   size_t numMoved = moveLoopInvariantCode(
       loopLike.getLoopRegions(),
       [&](Value value, Region *) {
         return loopLike.isDefinedOutsideOfLoop(value);
       },
-      [&](Operation *op, Region *) { return isPure(op); },
+      [&](Operation *op, Region *) { return isPure(op, actx); },
       [&](Operation *op, Region *) { loopLike.moveOutOfLoop(op); });
-  return numMoved + moveLoopInvariantCodeFromNestedRegions(loopLike);
+  return numMoved + moveLoopInvariantCodeFromNestedRegions(loopLike, actx);
 }
 
 /// Hoists pure loop-invariant ops out of the control-flow regions nested in
@@ -128,7 +129,7 @@ size_t mlir::moveLoopInvariantCode(LoopLikeOpInterface loopLike) {
 /// the loop itself. Returns the number of ops moved.
 static size_t hoistFromNestedRegions(Region &region,
                                      LoopLikeOpInterface loopLike,
-                                     bool isNested) {
+                                     bool isNested, AnalysisManager *actx) {
   if (region.empty())
     return 0;
   size_t numMoved = 0;
@@ -139,7 +140,7 @@ static size_t hoistFromNestedRegions(Region &region,
   // blocks are visited in an order in which definitions precede their uses.
   for (Block *block : llvm::depth_first(&region.front())) {
     for (Operation &op : llvm::make_early_inc_range(*block)) {
-      if (isNested && isPure(&op) && canBeHoisted(&op, definedOutside)) {
+      if (isNested && isPure(&op, actx) && canBeHoisted(&op, definedOutside)) {
         LDBG() << "Moving loop-invariant op: "
                << OpWithFlags(&op, OpPrintingFlags().skipRegions());
         loopLike.moveOutOfLoop(&op);
@@ -151,17 +152,20 @@ static size_t hoistFromNestedRegions(Region &region,
       if (!isa<RegionBranchOpInterface>(op) || isa<LoopLikeOpInterface>(op))
         continue;
       for (Region &nested : op.getRegions())
-        numMoved += hoistFromNestedRegions(nested, loopLike, /*isNested=*/true);
+        numMoved +=
+            hoistFromNestedRegions(nested, loopLike, /*isNested=*/true, actx);
     }
   }
   return numMoved;
 }
 
 size_t
-mlir::moveLoopInvariantCodeFromNestedRegions(LoopLikeOpInterface loopLike) {
+mlir::moveLoopInvariantCodeFromNestedRegions(LoopLikeOpInterface loopLike,
+                                             AnalysisManager *actx) {
   size_t numMoved = 0;
   for (Region *region : loopLike.getLoopRegions())
-    numMoved += hoistFromNestedRegions(*region, loopLike, /*isNested=*/false);
+    numMoved +=
+        hoistFromNestedRegions(*region, loopLike, /*isNested=*/false, actx);
   return numMoved;
 }
 
diff --git a/mlir/unittests/Interfaces/CMakeLists.txt b/mlir/unittests/Interfaces/CMakeLists.txt
index c4123b018a8651..5692404405adff 100644
--- a/mlir/unittests/Interfaces/CMakeLists.txt
+++ b/mlir/unittests/Interfaces/CMakeLists.txt
@@ -3,9 +3,10 @@ add_mlir_unittest(MLIRInterfacesTests
   DataLayoutInterfacesTest.cpp
   InferIntRangeInterfaceTest.cpp
   MemorySlotUtilsTest.cpp
-  SideEffectInterfacesTest.cpp
   InferTypeOpInterfaceTest.cpp
 
+  PARTIAL_SOURCES_INTENDED
+
   DEPENDS
   MLIRTestInterfaceIncGen
 )
@@ -25,3 +26,12 @@ mlir_target_link_libraries(MLIRInterfacesTests
   MLIRSideEffectInterfaces
 )
 target_link_libraries(MLIRInterfacesTests PRIVATE MLIRTestDialect)
+
+add_mlir_unittest(MLIRSideEffectInterfacesTests
+  SideEffectInterfacesTest.cpp
+)
+mlir_target_link_libraries(MLIRSideEffectInterfacesTests
+  PRIVATE
+  MLIRAnalysisManager
+  MLIRSideEffectInterfaces
+)
diff --git a/mlir/unittests/Interfaces/SideEffectInterfacesTest.cpp b/mlir/unittests/Interfaces/SideEffectInterfacesTest.cpp
index d7dbdd08f04165..6cbddf997c4bfd 100644
--- a/mlir/unittests/Interfaces/SideEffectInterfacesTest.cpp
+++ b/mlir/unittests/Interfaces/SideEffectInterfacesTest.cpp
@@ -7,6 +7,8 @@
 //===----------------------------------------------------------------------===//
 
 #include "mlir/Interfaces/SideEffectInterfaces.h"
+#include "mlir/Analysis/AnalysisManager.h"
+#include "mlir/IR/BuiltinOps.h"
 #include "mlir/Support/TypeID.h"
 #include "llvm/Support/Casting.h"
 #include <gtest/gtest.h>
@@ -126,3 +128,22 @@ TEST(SideEffectResourceTest, DisjointnessAndGetParent) {
   EXPECT_FALSE(
       TestRootResource::get()->isSubresourceOf(TestChildResource::get()));
 }
+
+TEST(Speculatability, ExternalModelWithoutAnalysis) {
+  struct RecursiveModel
+      : ConditionallySpeculatable::ExternalModel<RecursiveModel, ModuleOp> {
+    Speculation::Speculatability getSpeculatability(Operation *) const {
+      return Speculation::RecursivelySpeculatable;
+    }
+  };
+
+  MLIRContext context;
+  ModuleOp::attachInterface<RecursiveModel>(context);
+  OwningOpRef<ModuleOp> module = ModuleOp::create(UnknownLoc::get(&context));
+  ModuleAnalysisManager owner(*module);
+  AnalysisManager actx = owner;
+  auto iface = cast<ConditionallySpeculatable>(module->getOperation());
+  EXPECT_EQ(iface.getSpeculatability(), Speculation::RecursivelySpeculatable);
+  EXPECT_EQ(iface.getSpeculatabilityWithAnalysis(&actx),
+            Speculation::RecursivelySpeculatable);
+}

>From 97d47de0d71b3866144fd612081e1d0753deda9c Mon Sep 17 00:00:00 2001
From: Ivan Butygin <ivan.butygin at gmail.com>
Date: Mon, 30 Nov 2026 15:38:49 +0100
Subject: [PATCH 3/3] [mlir][Arith] Check index divisors at runtime width
 before speculation

Query the pass data layout lazily when a divisor proof depends on the index width. Check signed and unsigned division and remainder at their execution width, and keep width-independent proofs available to callers without analyses.
---
 .../include/mlir/Dialect/Arith/IR/ArithOps.td |  52 +---
 mlir/include/mlir/IR/Matchers.h               | 127 ++++++----
 mlir/lib/Dialect/Arith/IR/ArithOps.cpp        |  89 +++----
 mlir/lib/Dialect/Arith/IR/CMakeLists.txt      |   3 +
 .../loop-invariant-code-motion.mlir           | 226 ++++++++++++++++++
 mlir/unittests/Interfaces/CMakeLists.txt      |   4 +
 .../Interfaces/InferIntRangeInterfaceTest.cpp |  41 ++++
 .../Interfaces/SideEffectInterfacesTest.cpp   |  58 +++++
 8 files changed, 469 insertions(+), 131 deletions(-)

diff --git a/mlir/include/mlir/Dialect/Arith/IR/ArithOps.td b/mlir/include/mlir/Dialect/Arith/IR/ArithOps.td
index f6fb5e092729f3..629786a7066067 100644
--- a/mlir/include/mlir/Dialect/Arith/IR/ArithOps.td
+++ b/mlir/include/mlir/Dialect/Arith/IR/ArithOps.td
@@ -594,8 +594,11 @@ def Arith_MulUIExtendedOp : Arith_Op<"mului_extended", [Pure, Commutative,
 // DivUIOp
 //===----------------------------------------------------------------------===//
 
+defvar Arith_DivSpeculation = DeclareOpInterfaceMethods<
+    ConditionallySpeculatable, ["getSpeculatabilityWithAnalysis"]>;
+
 def Arith_DivUIOp : Arith_IntBinaryOpWithExactFlag<"divui",
-    [ConditionallySpeculatable,
+    [Arith_DivSpeculation,
      DeclareOpInterfaceMethods<InferIntDivisibilityOpInterface>]> {
   let summary = "unsigned integer division operation";
   let description = [{
@@ -627,11 +630,6 @@ def Arith_DivUIOp : Arith_IntBinaryOpWithExactFlag<"divui",
     ```
   }];
 
-  let extraClassDeclaration = [{
-    /// Interface method for ConditionallySpeculatable.
-    Speculation::Speculatability getSpeculatability();
-  }];
-
   let hasFolder = 1;
 }
 
@@ -640,7 +638,7 @@ def Arith_DivUIOp : Arith_IntBinaryOpWithExactFlag<"divui",
 //===----------------------------------------------------------------------===//
 
 def Arith_DivSIOp : Arith_IntBinaryOpWithExactFlag<"divsi",
-                                                   [ConditionallySpeculatable]> {
+                                                   [Arith_DivSpeculation]> {
   let summary = "signed integer division operation";
   let description = [{
     Signed integer division. Rounds towards zero. Treats the leading bit as
@@ -671,11 +669,6 @@ def Arith_DivSIOp : Arith_IntBinaryOpWithExactFlag<"divsi",
     ```
   }];
 
-  let extraClassDeclaration = [{
-    /// Interface method for ConditionallySpeculatable.
-    Speculation::Speculatability getSpeculatability();
-  }];
-
   let hasFolder = 1;
 }
 
@@ -684,7 +677,7 @@ def Arith_DivSIOp : Arith_IntBinaryOpWithExactFlag<"divsi",
 //===----------------------------------------------------------------------===//
 
 def Arith_CeilDivUIOp : Arith_IntBinaryOp<"ceildivui",
-                                          [ConditionallySpeculatable]> {
+                                          [Arith_DivSpeculation]> {
   let summary = "unsigned ceil integer division operation";
   let description = [{
     Unsigned integer division. Rounds towards positive infinity. Treats the
@@ -703,11 +696,6 @@ def Arith_CeilDivUIOp : Arith_IntBinaryOp<"ceildivui",
     ```
   }];
 
-  let extraClassDeclaration = [{
-    /// Interface method for ConditionallySpeculatable.
-    Speculation::Speculatability getSpeculatability();
-  }];
-
   let hasFolder = 1;
 }
 
@@ -716,7 +704,7 @@ def Arith_CeilDivUIOp : Arith_IntBinaryOp<"ceildivui",
 //===----------------------------------------------------------------------===//
 
 def Arith_CeilDivSIOp : Arith_IntBinaryOp<"ceildivsi",
-                                          [ConditionallySpeculatable]> {
+                                          [Arith_DivSpeculation]> {
   let summary = "signed ceil integer division operation";
   let description = [{
     Signed integer division. Rounds towards positive infinity, i.e. `7 / -2 = -3`.
@@ -734,11 +722,6 @@ def Arith_CeilDivSIOp : Arith_IntBinaryOp<"ceildivsi",
     ```
   }];
 
-  let extraClassDeclaration = [{
-    /// Interface method for ConditionallySpeculatable.
-    Speculation::Speculatability getSpeculatability();
-  }];
-
   let hasFolder = 1;
 }
 
@@ -747,7 +730,7 @@ def Arith_CeilDivSIOp : Arith_IntBinaryOp<"ceildivsi",
 //===----------------------------------------------------------------------===//
 
 def Arith_FloorDivSIOp
-    : Arith_IntBinaryOp<"floordivsi", [ConditionallySpeculatable]> {
+    : Arith_IntBinaryOp<"floordivsi", [Arith_DivSpeculation]> {
   let summary = "signed floor integer division operation";
   let description = [{
     Signed integer division. Rounds towards negative infinity, i.e. `5 / -2 = -3`.
@@ -765,10 +748,7 @@ def Arith_FloorDivSIOp
 
     ```
   }];
-  let extraClassDeclaration = [{
-    /// Interface method for ConditionallySpeculatable.
-    Speculation::Speculatability getSpeculatability();
-  }];
+
   let hasFolder = 1;
 }
 
@@ -777,7 +757,7 @@ def Arith_FloorDivSIOp
 //===----------------------------------------------------------------------===//
 
 def Arith_RemUIOp : Arith_IntBinaryOp<"remui",
-                                      [ConditionallySpeculatable]> {
+                                      [Arith_DivSpeculation]> {
   let summary = "unsigned integer division remainder operation";
   let description = [{
     Unsigned integer division remainder. Treats the leading bit as the most
@@ -801,11 +781,6 @@ def Arith_RemUIOp : Arith_IntBinaryOp<"remui",
     ```
   }];
 
-  let extraClassDeclaration = [{
-    /// Interface method for ConditionallySpeculatable.
-    Speculation::Speculatability getSpeculatability();
-  }];
-
   let hasFolder = 1;
 }
 
@@ -814,7 +789,7 @@ def Arith_RemUIOp : Arith_IntBinaryOp<"remui",
 //===----------------------------------------------------------------------===//
 
 def Arith_RemSIOp : Arith_IntBinaryOp<"remsi",
-                                      [ConditionallySpeculatable]> {
+                                      [Arith_DivSpeculation]> {
   let summary = "signed integer division remainder operation";
   let description = [{
     Signed integer division remainder. Treats the leading bit as sign, i.e. `6 %
@@ -838,11 +813,6 @@ def Arith_RemSIOp : Arith_IntBinaryOp<"remsi",
     ```
   }];
 
-  let extraClassDeclaration = [{
-    /// Interface method for ConditionallySpeculatable.
-    Speculation::Speculatability getSpeculatability();
-  }];
-
   let hasFolder = 1;
 }
 
diff --git a/mlir/include/mlir/IR/Matchers.h b/mlir/include/mlir/IR/Matchers.h
index e577909621cb86..b81592f14de405 100644
--- a/mlir/include/mlir/IR/Matchers.h
+++ b/mlir/include/mlir/IR/Matchers.h
@@ -18,9 +18,15 @@
 #include "mlir/IR/BuiltinAttributes.h"
 #include "mlir/IR/BuiltinTypes.h"
 #include "mlir/IR/OpDefinition.h"
+#include "mlir/IR/TypeUtilities.h"
 #include "mlir/Interfaces/InferIntRangeInterface.h"
+#include "llvm/ADT/STLFunctionalExtras.h"
+#include <optional>
 
 namespace mlir {
+/// Returns the index width at the given operation, or std::nullopt if unknown.
+using GetIndexBitwidthFn =
+    llvm::function_ref<std::optional<unsigned>(Operation *)>;
 
 namespace detail {
 
@@ -101,39 +107,6 @@ struct constant_op_binder {
   }
 };
 
-/// A matcher that matches operations that implement the
-/// `InferIntRangeInterface` interface, and binds the inferred range.
-struct infer_int_range_op_binder {
-  IntegerValueRange *bind_value;
-
-  explicit infer_int_range_op_binder(IntegerValueRange *bind_value)
-      : bind_value(bind_value) {}
-
-  bool match(Operation *op) {
-    auto inferIntRangeOp = dyn_cast<InferIntRangeInterface>(op);
-    if (!inferIntRangeOp)
-      return false;
-
-    // Set the range of all integer operands to the maximal range.
-    SmallVector<IntegerValueRange> argRanges =
-        llvm::map_to_vector(op->getOperands(), IntegerValueRange::getMaxRange);
-
-    // Infer the result result range if possible.
-    bool matched = false;
-    auto setResultRanges = [&](Value value,
-                               const IntegerValueRange &argRanges) {
-      if (argRanges.isUninitialized())
-        return;
-      if (value != op->getResult(0))
-        return;
-      *bind_value = argRanges;
-      matched = true;
-    };
-    inferIntRangeOp.inferResultRangesFromOptional(argRanges, setResultRanges);
-    return matched;
-  }
-};
-
 /// The matcher that matches operations that have the specified attribute
 /// name, and binds the attribute value.
 template <typename AttrT>
@@ -255,26 +228,80 @@ struct constant_int_predicate_matcher {
 
 /// A matcher that matches a given a constant scalar / vector splat / tensor
 /// splat integer value or a constant integer range that fulfills a predicate.
+/// Matching an index attribute requires a width query and a scoping operation.
 struct constant_int_range_predicate_matcher {
   bool (*predicate)(const ConstantIntRanges &);
 
-  bool match(Attribute attr) {
+  bool matchConstant(const APInt &value, Type type, Operation *scope,
+                     GetIndexBitwidthFn getIndexBitwidth) const {
+    if (getElementTypeOrSelf(type).isIndex()) {
+      if (!getIndexBitwidth || !scope)
+        return false;
+      // These predicates exclude zero, signed -1, or both. With an unknown
+      // index width, check the literal at one bit. Even values become zero.
+      // Odd values stay nonzero at every width but become signed -1 at one
+      // bit. Thus a literal passes this check only if it is safe at all widths.
+      return predicate(ConstantIntRanges::constant(
+          value.sextOrTrunc(getIndexBitwidth(scope).value_or(1))));
+    }
+    return predicate(ConstantIntRanges::constant(value));
+  }
+
+  bool match(Attribute attr, Operation *scope = nullptr,
+             GetIndexBitwidthFn getIndexBitwidth = nullptr) const {
     APInt value;
     return constant_int_value_binder(&value).match(attr) &&
-           predicate(ConstantIntRanges::constant(value));
+           matchConstant(value, cast<TypedAttr>(attr).getType(), scope,
+                         getIndexBitwidth);
   }
 
-  bool match(Operation *op) {
-    // Try to match a constant integer value first.
-    APInt value;
-    if (constant_int_value_binder(&value).match(op))
-      return predicate(ConstantIntRanges::constant(value));
-
-    // Otherwise, try to match an operation that implements the
-    // `InferIntRangeInterface` interface.
-    IntegerValueRange range;
-    return infer_int_range_op_binder(&range).match(op) &&
-           predicate(range.getValue());
+  /// Match a value as used at `scope`, including an individual result of a
+  /// multi-result operation.
+  bool match(Value value, Operation *scope,
+             GetIndexBitwidthFn getIndexBitwidth = nullptr) const {
+    Operation *op = value.getDefiningOp();
+    if (!op)
+      return false;
+    APInt constant;
+    if (constant_int_value_binder(&constant).match(op))
+      return matchConstant(constant, value.getType(), scope, getIndexBitwidth);
+
+    auto inferOp = dyn_cast<InferIntRangeInterface>(op);
+    if (!inferOp)
+      return false;
+    auto isIndex = [](Type type) {
+      return getElementTypeOrSelf(type).isIndex();
+    };
+    // Range inference computes index bounds at the index storage width.
+    // A range inferred at that width need not hold for a narrower execution.
+    if (llvm::any_of(op->getOperandTypes(), isIndex) ||
+        llvm::any_of(op->getResultTypes(), isIndex)) {
+      constexpr unsigned storageWidth = IndexType::kInternalStorageBitWidth;
+      if (!getIndexBitwidth || getIndexBitwidth(op) != storageWidth)
+        return false;
+      if (isIndex(value.getType()) && scope != op &&
+          getIndexBitwidth(scope) != storageWidth)
+        return false;
+    }
+
+    auto argRanges =
+        llvm::map_to_vector(op->getOperands(), IntegerValueRange::getMaxRange);
+    bool matched = false;
+    // TODO: Once inferResultRangesFromOptional accepts an index width, pass
+    // the defining op's optional width here and use it to build argRanges.
+    // This will allow inference at widths other than the storage width.
+    inferOp.inferResultRangesFromOptional(
+        argRanges, [&](Value result, const IntegerValueRange &range) {
+          if (value == result && !range.isUninitialized())
+            matched = predicate(range.getValue());
+        });
+    return matched;
+  }
+
+  bool match(Operation *op,
+             GetIndexBitwidthFn getIndexBitwidth = nullptr) const {
+    return op->getNumResults() == 1 &&
+           match(op->getResult(0), op, getIndexBitwidth);
   }
 };
 
@@ -474,6 +501,14 @@ inline detail::constant_int_range_predicate_matcher m_IntRangeWithoutNegOneS() {
   }};
 }
 
+/// Matches a signed integer range that excludes both zero and minus one.
+inline detail::constant_int_range_predicate_matcher
+m_IntRangeWithoutZeroOrNegOneS() {
+  return {[](const ConstantIntRanges &range) {
+    return range.smin().sgt(0) || range.smax().slt(-1);
+  }};
+}
+
 /// Matches a constant scalar / vector splat / tensor splat integer one.
 inline detail::constant_int_predicate_matcher m_One() {
   return {[](const APInt &value) { return 1 == value; }};
diff --git a/mlir/lib/Dialect/Arith/IR/ArithOps.cpp b/mlir/lib/Dialect/Arith/IR/ArithOps.cpp
index b738dce0856381..b765e7bb3a3ead 100644
--- a/mlir/lib/Dialect/Arith/IR/ArithOps.cpp
+++ b/mlir/lib/Dialect/Arith/IR/ArithOps.cpp
@@ -12,6 +12,8 @@
 #include <type_traits>
 #include <utility>
 
+#include "mlir/Analysis/AnalysisManager.h"
+#include "mlir/Analysis/DataLayoutAnalysis.h"
 #include "mlir/Dialect/Arith/IR/Arith.h"
 #include "mlir/Dialect/CommonFolders.h"
 #include "mlir/Dialect/UB/IR/UBMatchers.h"
@@ -22,6 +24,7 @@
 #include "mlir/IR/OpImplementation.h"
 #include "mlir/IR/PatternMatch.h"
 #include "mlir/IR/TypeUtilities.h"
+#include "mlir/Interfaces/DataLayoutInterfaces.h"
 #include "mlir/Interfaces/SideEffectInterfaces.h"
 #include "mlir/Support/LogicalResult.h"
 
@@ -882,17 +885,31 @@ OpFoldResult arith::DivUIOp::fold(FoldAdaptor adaptor) {
   return div0 ? Attribute() : result;
 }
 
-/// Returns whether an unsigned division by `divisor` is speculatable.
-static Speculation::Speculatability getDivUISpeculatability(Value divisor) {
-  // X / 0 => UB
-  if (matchPattern(divisor, m_IntRangeWithoutZeroU()))
-    return Speculation::Speculatable;
+static std::optional<unsigned> getDivisorIndexBitwidth(AnalysisManager &actx,
+                                                       Operation *scope) {
+  const DataLayout &layout =
+      actx.getAnalysis<DataLayoutAnalysis>().getAtOrAbove(scope);
+  auto index = IndexType::get(scope->getContext());
+  if (!layout.hasExactTypeEntry(index))
+    return std::nullopt;
+  return layout.getTypeSizeInBits(index).getFixedValue();
+}
 
+template <typename Op>
+static Speculation::Speculatability getIntegerDivSpeculatability(
+    Op op, mlir::detail::constant_int_range_predicate_matcher matcher,
+    AnalysisManager *actx) {
+  auto getIndexBitwidth = [&](Operation *scope) {
+    return actx ? getDivisorIndexBitwidth(*actx, scope) : std::nullopt;
+  };
+  if (matcher.match(op.getRhs(), op, getIndexBitwidth))
+    return Speculation::Speculatable;
   return Speculation::NotSpeculatable;
 }
 
-Speculation::Speculatability arith::DivUIOp::getSpeculatability() {
-  return getDivUISpeculatability(getRhs());
+Speculation::Speculatability
+arith::DivUIOp::getSpeculatabilityWithAnalysis(AnalysisManager *actx) {
+  return getIntegerDivSpeculatability(*this, m_IntRangeWithoutZeroU(), actx);
 }
 
 //===----------------------------------------------------------------------===//
@@ -934,21 +951,10 @@ OpFoldResult arith::DivSIOp::fold(FoldAdaptor adaptor) {
   return overflowOrDiv0 ? Attribute() : result;
 }
 
-/// Returns whether a signed division by `divisor` is speculatable. This
-/// function conservatively assumes that all signed division by -1 are not
-/// speculatable.
-static Speculation::Speculatability getDivSISpeculatability(Value divisor) {
-  // X / 0 => UB
-  // INT_MIN / -1 => UB
-  if (matchPattern(divisor, m_IntRangeWithoutZeroS()) &&
-      matchPattern(divisor, m_IntRangeWithoutNegOneS()))
-    return Speculation::Speculatable;
-
-  return Speculation::NotSpeculatable;
-}
-
-Speculation::Speculatability arith::DivSIOp::getSpeculatability() {
-  return getDivSISpeculatability(getRhs());
+Speculation::Speculatability
+arith::DivSIOp::getSpeculatabilityWithAnalysis(AnalysisManager *actx) {
+  return getIntegerDivSpeculatability(*this, m_IntRangeWithoutZeroOrNegOneS(),
+                                      actx);
 }
 
 //===----------------------------------------------------------------------===//
@@ -989,8 +995,9 @@ OpFoldResult arith::CeilDivUIOp::fold(FoldAdaptor adaptor) {
   return overflowOrDiv0 ? Attribute() : result;
 }
 
-Speculation::Speculatability arith::CeilDivUIOp::getSpeculatability() {
-  return getDivUISpeculatability(getRhs());
+Speculation::Speculatability
+arith::CeilDivUIOp::getSpeculatabilityWithAnalysis(AnalysisManager *actx) {
+  return getIntegerDivSpeculatability(*this, m_IntRangeWithoutZeroU(), actx);
 }
 
 //===----------------------------------------------------------------------===//
@@ -1050,8 +1057,10 @@ OpFoldResult arith::CeilDivSIOp::fold(FoldAdaptor adaptor) {
   return overflowOrDiv0 ? Attribute() : result;
 }
 
-Speculation::Speculatability arith::CeilDivSIOp::getSpeculatability() {
-  return getDivSISpeculatability(getRhs());
+Speculation::Speculatability
+arith::CeilDivSIOp::getSpeculatabilityWithAnalysis(AnalysisManager *actx) {
+  return getIntegerDivSpeculatability(*this, m_IntRangeWithoutZeroOrNegOneS(),
+                                      actx);
 }
 
 //===----------------------------------------------------------------------===//
@@ -1089,15 +1098,10 @@ OpFoldResult arith::FloorDivSIOp::fold(FoldAdaptor adaptor) {
   return overflowOrDiv ? Attribute() : result;
 }
 
-Speculation::Speculatability FloorDivSIOp::getSpeculatability() {
-  // Division by zero is UB.
-  // Signed division overflow (INT_MIN / -1) is also UB.
-  Value divisor = getRhs();
-  if (matchPattern(divisor, m_IntRangeWithoutZeroS()) &&
-      matchPattern(divisor, m_IntRangeWithoutNegOneS()))
-    return Speculation::Speculatable;
-
-  return Speculation::NotSpeculatable;
+Speculation::Speculatability
+FloorDivSIOp::getSpeculatabilityWithAnalysis(AnalysisManager *actx) {
+  return getIntegerDivSpeculatability(*this, m_IntRangeWithoutZeroOrNegOneS(),
+                                      actx);
 }
 
 //===----------------------------------------------------------------------===//
@@ -1132,8 +1136,9 @@ OpFoldResult arith::RemUIOp::fold(FoldAdaptor adaptor) {
   return div0 ? Attribute() : result;
 }
 
-Speculation::Speculatability arith::RemUIOp::getSpeculatability() {
-  return getDivUISpeculatability(getRhs());
+Speculation::Speculatability
+arith::RemUIOp::getSpeculatabilityWithAnalysis(AnalysisManager *actx) {
+  return getIntegerDivSpeculatability(*this, m_IntRangeWithoutZeroU(), actx);
 }
 
 //===----------------------------------------------------------------------===//
@@ -1168,13 +1173,9 @@ OpFoldResult arith::RemSIOp::fold(FoldAdaptor adaptor) {
   return div0 ? Attribute() : result;
 }
 
-Speculation::Speculatability arith::RemSIOp::getSpeculatability() {
-  // X % 0 => UB
-  // X % -1 is well-defined (always 0), unlike X / -1 which can overflow.
-  if (matchPattern(getRhs(), m_IntRangeWithoutZeroS()))
-    return Speculation::Speculatable;
-
-  return Speculation::NotSpeculatable;
+Speculation::Speculatability
+arith::RemSIOp::getSpeculatabilityWithAnalysis(AnalysisManager *actx) {
+  return getIntegerDivSpeculatability(*this, m_IntRangeWithoutZeroS(), actx);
 }
 
 //===----------------------------------------------------------------------===//
diff --git a/mlir/lib/Dialect/Arith/IR/CMakeLists.txt b/mlir/lib/Dialect/Arith/IR/CMakeLists.txt
index a6508946030a20..8ce748e03946bc 100644
--- a/mlir/lib/Dialect/Arith/IR/CMakeLists.txt
+++ b/mlir/lib/Dialect/Arith/IR/CMakeLists.txt
@@ -24,7 +24,10 @@ add_mlir_dialect_library(MLIRArithDialect
   MLIRArithOpsInterfacesIncGen
 
   LINK_LIBS PUBLIC
+  MLIRAnalysisBase
+  MLIRAnalysisManager
   MLIRCastInterfaces
+  MLIRDataLayoutInterfaces
   MLIRDialect
   MLIRInferIntDivisibilityOpInterface
   MLIRInferIntRangeCommon
diff --git a/mlir/test/Transforms/loop-invariant-code-motion.mlir b/mlir/test/Transforms/loop-invariant-code-motion.mlir
index 448540e17512c2..bc7bbcff6407b7 100644
--- a/mlir/test/Transforms/loop-invariant-code-motion.mlir
+++ b/mlir/test/Transforms/loop-invariant-code-motion.mlir
@@ -1837,3 +1837,229 @@ func.func @tensor_pad_region_not_hoisted(
 // CHECK: tensor.pad
 // CHECK: arith.divsi
 // CHECK: tensor.yield
+
+// -----
+
+// 7 fits in 32 bits and is nonzero, so LICM can hoist the unsigned division.
+// CHECK-LABEL: @index_div_32_7(
+// CHECK: arith.divui
+// CHECK: scf.for
+module attributes {dlti.dl_spec = #dlti.dl_spec<index = 32 : i32>} {
+  func.func @index_div_32_7(%a: index, %n: index) -> index {
+    %c0 = arith.constant 0 : index
+    %c1 = arith.constant 1 : index
+    %d = arith.constant 7 : index
+    %r = scf.for %i = %c0 to %n step %c1 iter_args(%acc = %c0) -> (index) {
+      %q = arith.divui %a, %d : index
+      scf.yield %q : index
+    }
+    return %r : index
+  }
+}
+
+// -----
+
+// 2^32 truncates to zero at 32 bits. Hoisting would divide by zero even when
+// the loop executes zero times.
+// CHECK-LABEL: @index_div_32_4294967296(
+// CHECK: scf.for
+// CHECK: arith.divui
+module attributes {dlti.dl_spec = #dlti.dl_spec<index = 32 : i32>} {
+  func.func @index_div_32_4294967296(%a: index, %n: index) -> index {
+    %c0 = arith.constant 0 : index
+    %c1 = arith.constant 1 : index
+    %d = arith.constant 4294967296 : index
+    %r = scf.for %i = %c0 to %n step %c1 iter_args(%acc = %c0) -> (index) {
+      %q = arith.divui %a, %d : index
+      scf.yield %q : index
+    }
+    return %r : index
+  }
+}
+
+// -----
+
+// At 64 bits, 2^32 stays nonzero, so LICM can hoist the unsigned division.
+// CHECK-LABEL: @index_div_64_4294967296(
+// CHECK: arith.divui
+// CHECK: scf.for
+module attributes {dlti.dl_spec = #dlti.dl_spec<index = 64 : i32>} {
+  func.func @index_div_64_4294967296(%a: index, %n: index) -> index {
+    %c0 = arith.constant 0 : index
+    %c1 = arith.constant 1 : index
+    %d = arith.constant 4294967296 : index
+    %r = scf.for %i = %c0 to %n step %c1 iter_args(%acc = %c0) -> (index) {
+      %q = arith.divui %a, %d : index
+      scf.yield %q : index
+    }
+    return %r : index
+  }
+}
+
+// -----
+
+// 7 is odd, so its low bit stays set at every index width. LICM can hoist
+// the unsigned division without knowing the width.
+// CHECK-LABEL: @index_div_unknown_7(
+// CHECK: arith.divui
+// CHECK: scf.for
+module {
+  func.func @index_div_unknown_7(%a: index, %n: index) -> index {
+    %c0 = arith.constant 0 : index
+    %c1 = arith.constant 1 : index
+    %d = arith.constant 7 : index
+    %r = scf.for %i = %c0 to %n step %c1 iter_args(%acc = %c0) -> (index) {
+      %q = arith.divui %a, %d : index
+      scf.yield %q : index
+    }
+    return %r : index
+  }
+}
+
+// -----
+
+module attributes {dlti.dl_spec = #dlti.dl_spec<index = 32 : i32>} {
+  // CHECK-LABEL: @index_ceildiv_32(
+  // At 32 bits, 2^32 becomes zero and 2^32 - 1 becomes signed -1.
+  // Hoisting could divide by zero or overflow even if the loop never runs.
+  // CHECK: scf.for
+  // CHECK: arith.ceildivui
+  // CHECK: arith.ceildivsi
+  func.func @index_ceildiv_32(%a: index, %n: index) {
+    %c0 = arith.constant 0 : index
+    %c1 = arith.constant 1 : index
+    %u = arith.constant 4294967296 : index
+    %s = arith.constant 4294967295 : index
+    scf.for %i = %c0 to %n step %c1 {
+      %uq = arith.ceildivui %a, %u : index
+      %sq = arith.ceildivsi %a, %s : index
+    }
+    return
+  }
+}
+
+// -----
+
+module attributes {dlti.dl_spec = #dlti.dl_spec<index = 64 : i32>} {
+  // CHECK-LABEL: @index_ceildiv_64(
+  // Both divisors stay positive at 64 bits, so LICM can hoist both divisions.
+  // CHECK-DAG: arith.ceildivui
+  // CHECK-DAG: arith.ceildivsi
+  // CHECK: scf.for
+  func.func @index_ceildiv_64(%a: index, %n: index) {
+    %c0 = arith.constant 0 : index
+    %c1 = arith.constant 1 : index
+    %u = arith.constant 4294967296 : index
+    %s = arith.constant 4294967295 : index
+    scf.for %i = %c0 to %n step %c1 {
+      %uq = arith.ceildivui %a, %u : index
+      %sq = arith.ceildivsi %a, %s : index
+    }
+    return
+  }
+}
+
+// -----
+
+// The signed range excludes zero and includes -1. Signed remainder can hoist
+// because a remainder by -1 is zero even when the dividend is INT_MIN.
+// CHECK-LABEL: @remsi_negative_range(
+// CHECK: arith.remsi
+// CHECK: scf.for
+func.func @remsi_negative_range(%a: i8, %lb: index, %ub: index, %step: index) {
+  %d = test.with_bounds <smin = -8 : i8, smax = -1 : i8, umin = 0 : i8, umax = 255 : i8> : i8
+  scf.for %i = %lb to %ub step %step {
+    %r = arith.remsi %a, %d : i8
+  }
+  return
+}
+
+// -----
+
+module attributes {dlti.dl_spec = #dlti.dl_spec<index = 32 : i32>} {
+  // The inferred divisor is 2^32 or 2^32 + 1. The first value truncates to
+  // zero at 32 bits, so the division must stay in the loop.
+  // CHECK-LABEL: @index_div_inferred_32(
+  // CHECK: scf.for
+  // CHECK: arith.divui
+  func.func @index_div_inferred_32(%a: index, %x: index, %n: index) {
+    %c0 = arith.constant 0 : index
+    %c1 = arith.constant 1 : index
+    %d = affine.apply affine_map<(d0) -> (d0 mod 2 + 4294967296)>(%x)
+    scf.for %i = %c0 to %n step %c1 {
+      %q = arith.divui %a, %d : index
+    }
+    return
+  }
+}
+
+// -----
+
+module attributes {dlti.dl_spec = #dlti.dl_spec<index = 64 : i32>} {
+  // Both inferred divisors are nonzero at 64 bits, so LICM can hoist.
+  // CHECK-LABEL: @index_div_inferred_64(
+  // CHECK: arith.divui
+  // CHECK: scf.for
+  func.func @index_div_inferred_64(%a: index, %x: index, %n: index) {
+    %c0 = arith.constant 0 : index
+    %c1 = arith.constant 1 : index
+    %d = affine.apply affine_map<(d0) -> (d0 mod 2 + 4294967296)>(%x)
+    scf.for %i = %c0 to %n step %c1 {
+      %q = arith.divui %a, %d : index
+    }
+    return
+  }
+}
+
+// -----
+
+// Both branches yield loop-invariant values. At 64 bits the divisor is
+// nonzero, so LICM can hoist the entire scf.if, including the division.
+// CHECK-LABEL: @index_div_recursive(
+// CHECK: scf.if
+// CHECK: arith.divui
+// CHECK: scf.for
+module attributes {dlti.dl_spec = #dlti.dl_spec<index = 64 : i32>} {
+  func.func @index_div_recursive(%a: index, %n: index, %cond: i1) -> index {
+    %c0 = arith.constant 0 : index
+    %c1 = arith.constant 1 : index
+    %d = arith.constant 4294967296 : index
+    %r = scf.for %i = %c0 to %n step %c1 iter_args(%acc = %c0) -> (index) {
+      %v = scf.if %cond -> (index) {
+        %q = arith.divui %a, %d : index
+        scf.yield %q : index
+      } else {
+        scf.yield %a : index
+      }
+      scf.yield %v : index
+    }
+    return %r : index
+  }
+}
+
+// -----
+
+// The condition depends on the induction variable. LICM can still use the
+// enclosing layout to hoist the division from the then region.
+// CHECK-LABEL: @index_div_nested_region(
+// CHECK: arith.divui
+// CHECK: scf.for
+// CHECK: scf.if
+module attributes {dlti.dl_spec = #dlti.dl_spec<index = 64 : i32>} {
+  func.func @index_div_nested_region(%a: index, %n: index) -> index {
+    %c0 = arith.constant 0 : index
+    %c1 = arith.constant 1 : index
+    %d = arith.constant 4294967296 : index
+    %r = scf.for %i = %c0 to %n step %c1 iter_args(%acc = %c0) -> (index) {
+      %cond = arith.cmpi eq, %i, %a : index
+      %v = scf.if %cond -> (index) {
+        %q = arith.divui %a, %d : index
+        scf.yield %q : index
+      } else {
+        scf.yield %acc : index
+      }
+      scf.yield %v : index
+    }
+    return %r : index
+  }
+}
diff --git a/mlir/unittests/Interfaces/CMakeLists.txt b/mlir/unittests/Interfaces/CMakeLists.txt
index 5692404405adff..43562d575f9919 100644
--- a/mlir/unittests/Interfaces/CMakeLists.txt
+++ b/mlir/unittests/Interfaces/CMakeLists.txt
@@ -32,6 +32,10 @@ add_mlir_unittest(MLIRSideEffectInterfacesTests
 )
 mlir_target_link_libraries(MLIRSideEffectInterfacesTests
   PRIVATE
+  MLIRAnalysisBase
   MLIRAnalysisManager
+  MLIRArithDialect
+  MLIRDLTIDialect
+  MLIRParser
   MLIRSideEffectInterfaces
 )
diff --git a/mlir/unittests/Interfaces/InferIntRangeInterfaceTest.cpp b/mlir/unittests/Interfaces/InferIntRangeInterfaceTest.cpp
index 8aa4b82d934b83..cea8ad64108af4 100644
--- a/mlir/unittests/Interfaces/InferIntRangeInterfaceTest.cpp
+++ b/mlir/unittests/Interfaces/InferIntRangeInterfaceTest.cpp
@@ -7,6 +7,9 @@
 //===----------------------------------------------------------------------===//
 
 #include "mlir/Interfaces/InferIntRangeInterface.h"
+#include "mlir/Dialect/Arith/IR/Arith.h"
+#include "mlir/IR/BuiltinOps.h"
+#include "mlir/IR/Matchers.h"
 #include "mlir/Interfaces/Utils/InferIntRangeCommon.h"
 #include "llvm/ADT/APInt.h"
 #include <array>
@@ -263,3 +266,41 @@ TEST(IntRangeInference, SignedCeilDivMinDividend) {
         ConstantIntRanges::fromSigned((min + 1).sdiv(two), -min.sdiv(two)));
   }
 }
+
+TEST(IntRangeMatchers, LazyIndexBitwidth) {
+  MLIRContext context;
+  context.loadDialect<arith::ArithDialect>();
+  OpBuilder builder(&context);
+  Location loc = builder.getUnknownLoc();
+  OwningOpRef<ModuleOp> module = ModuleOp::create(loc);
+  builder.setInsertionPointToStart(module->getBody());
+  auto noQuery = [](Operation *) -> std::optional<unsigned> {
+    ADD_FAILURE() << "fixed-width match requested an index bit width";
+    return std::nullopt;
+  };
+  auto one = arith::ConstantIntOp::create(builder, loc, 1, 32);
+  EXPECT_TRUE(m_IntRangeWithoutZeroU().match(one.getValue(), nullptr, noQuery));
+  EXPECT_TRUE(m_IntRangeWithoutZeroS().match(one, noQuery));
+  auto ext = arith::ExtUIOp::create(builder, loc, builder.getI64Type(), one);
+  EXPECT_FALSE(m_IntRangeWithoutZeroU().match(ext, noQuery));
+
+  auto unknown = [](Operation *) -> std::optional<unsigned> {
+    return std::nullopt;
+  };
+  auto seven = builder.getIndexAttr(7);
+  EXPECT_TRUE(m_IntRangeWithoutZeroU().match(seven, *module, unknown));
+  EXPECT_FALSE(m_IntRangeWithoutZeroOrNegOneS().match(seven, *module, unknown));
+
+  auto width32 = [](Operation *) -> std::optional<unsigned> { return 32; };
+  auto width64 = [](Operation *) -> std::optional<unsigned> { return 64; };
+  auto zeroAt32 = builder.getIndexAttr(int64_t{1} << 32);
+  EXPECT_FALSE(m_IntRangeWithoutZeroU().match(zeroAt32));
+  EXPECT_FALSE(m_IntRangeWithoutZeroU().match(zeroAt32, *module, unknown));
+  EXPECT_FALSE(m_IntRangeWithoutZeroU().match(zeroAt32, *module, width32));
+  EXPECT_TRUE(m_IntRangeWithoutZeroU().match(zeroAt32, *module, width64));
+  auto minusOneAt32 = builder.getIndexAttr(UINT32_MAX);
+  EXPECT_FALSE(
+      m_IntRangeWithoutZeroOrNegOneS().match(minusOneAt32, *module, width32));
+  EXPECT_TRUE(
+      m_IntRangeWithoutZeroOrNegOneS().match(minusOneAt32, *module, width64));
+}
diff --git a/mlir/unittests/Interfaces/SideEffectInterfacesTest.cpp b/mlir/unittests/Interfaces/SideEffectInterfacesTest.cpp
index 6cbddf997c4bfd..ccad55d6cd23a8 100644
--- a/mlir/unittests/Interfaces/SideEffectInterfacesTest.cpp
+++ b/mlir/unittests/Interfaces/SideEffectInterfacesTest.cpp
@@ -8,7 +8,11 @@
 
 #include "mlir/Interfaces/SideEffectInterfaces.h"
 #include "mlir/Analysis/AnalysisManager.h"
+#include "mlir/Analysis/DataLayoutAnalysis.h"
+#include "mlir/Dialect/Arith/IR/Arith.h"
+#include "mlir/Dialect/DLTI/DLTI.h"
 #include "mlir/IR/BuiltinOps.h"
+#include "mlir/Parser/Parser.h"
 #include "mlir/Support/TypeID.h"
 #include "llvm/Support/Casting.h"
 #include <gtest/gtest.h>
@@ -129,6 +133,60 @@ TEST(SideEffectResourceTest, DisjointnessAndGetParent) {
       TestRootResource::get()->isSubresourceOf(TestChildResource::get()));
 }
 
+TEST(Speculatability, LazyPassAnalysis) {
+  MLIRContext context;
+  context.loadDialect<arith::ArithDialect, DLTIDialect>();
+  auto module = parseSourceString<ModuleOp>(R"mlir(
+    module attributes {dlti.dl_spec = #dlti.dl_spec<index = 64 : i32>} {
+      %i = arith.constant 2 : i32
+      %x = arith.constant 4294967296 : index
+      %a = arith.divui %i, %i : i32
+      %b = arith.divui %x, %x : index
+    }
+  )mlir",
+                                            &context);
+  ASSERT_TRUE(module);
+  struct LayoutObserver : AnalysisInstrumentation {
+    unsigned starts = 0, finishes = 0;
+
+    void runBeforeAnalysis(StringRef, TypeID id, Operation *) override {
+      EXPECT_EQ(id, TypeID::get<DataLayoutAnalysis>());
+      ++starts;
+    }
+    void runAfterAnalysis(StringRef, TypeID id, Operation *) override {
+      EXPECT_EQ(id, TypeID::get<DataLayoutAnalysis>());
+      ++finishes;
+    }
+  } observer;
+  ModuleAnalysisManager owner(*module, &observer);
+  AnalysisManager actx = owner;
+  auto divs = module->getOps<arith::DivUIOp>();
+  auto it = divs.begin();
+  arith::DivUIOp fixed = *it++;
+  arith::DivUIOp index = *it;
+
+  auto fixedIface = cast<ConditionallySpeculatable>(fixed.getOperation());
+  EXPECT_EQ(fixedIface.getSpeculatability(), Speculation::Speculatable);
+  EXPECT_EQ(fixedIface.getSpeculatabilityWithAnalysis(nullptr),
+            Speculation::Speculatable);
+  EXPECT_TRUE(isPure(fixed, &actx));
+  EXPECT_FALSE(actx.getCachedAnalysis<DataLayoutAnalysis>());
+  // The divisor can truncate to zero when the caller supplies no layout.
+  auto indexIface = cast<ConditionallySpeculatable>(index.getOperation());
+  EXPECT_EQ(indexIface.getSpeculatability(), Speculation::NotSpeculatable);
+  EXPECT_EQ(indexIface.getSpeculatabilityWithAnalysis(nullptr),
+            Speculation::NotSpeculatable);
+  EXPECT_FALSE(isPure(index));
+  EXPECT_TRUE(isPure(index, &actx));
+  auto cached = actx.getCachedAnalysis<DataLayoutAnalysis>();
+  ASSERT_TRUE(cached);
+  AnalysisManager samePass = owner;
+  EXPECT_TRUE(isPure(index, &samePass));
+  EXPECT_EQ(&cached->get(), &samePass.getAnalysis<DataLayoutAnalysis>());
+  EXPECT_EQ(observer.starts, 1u);
+  EXPECT_EQ(observer.finishes, 1u);
+}
+
 TEST(Speculatability, ExternalModelWithoutAnalysis) {
   struct RecursiveModel
       : ConditionallySpeculatable::ExternalModel<RecursiveModel, ModuleOp> {



More information about the cfe-commits mailing list