[llvm] fa23198 - [PassInstrumentation] Replace llvm::Any with a tagged IRUnitRef. (NFC) (#215341)

via llvm-commits llvm-commits at lists.llvm.org
Thu Aug 13 23:24:05 PDT 2026


Author: Florian Hahn
Date: 2026-08-14T06:23:59Z
New Revision: fa23198d685b8d6daaf09b02cf89cfe36a707d10

URL: https://github.com/llvm/llvm-project/commit/fa23198d685b8d6daaf09b02cf89cfe36a707d10
DIFF: https://github.com/llvm/llvm-project/commit/fa23198d685b8d6daaf09b02cf89cfe36a707d10.diff

LOG: [PassInstrumentation] Replace llvm::Any with a tagged IRUnitRef. (NFC) (#215341)

llvm::Any currently requires heap allocations on every construction,
which is quite expensive for the use in PassInstrumentation.

Replace llvm::Any with a hand-rolled IRUnitRef wrapper that uses
PointerIntPair on platforms with 64 bit (or larger) pointers or a pair
of Kind/pointer on other platforms.

Unfortunately I don't think alignas(8) would work for Function (or any
Value*), as it uses `HungOffOperandsAllocMarker`.

Follow-up to https://github.com/llvm/llvm-project/pull/215120.

It further improves compile-time:

 * stage1-O3: -0.09%
 * stage1-ReleaseThinLTO: -0.09%
 * stage1-ReleaseLTO-g: -0.08%
 * stage1-aarch64-O3: -0.08%
 * stage2-O3: -0.12%
 * clang: -0.20%

PR: https://github.com/llvm/llvm-project/pull/215341

Added: 
    llvm/include/llvm/IR/IRUnitRef.h

Modified: 
    llvm/include/llvm/Analysis/LazyCallGraph.h
    llvm/include/llvm/IR/DroppedVariableStatsIR.h
    llvm/include/llvm/IR/PassInstrumentation.h
    llvm/include/llvm/Passes/StandardInstrumentations.h
    llvm/include/llvm/Transforms/IPO/SampleProfileProbe.h
    llvm/lib/Analysis/LazyCallGraph.cpp
    llvm/lib/CodeGen/TargetPassConfig.cpp
    llvm/lib/IR/DroppedVariableStatsIR.cpp
    llvm/lib/IR/PassInstrumentation.cpp
    llvm/lib/IR/PassTimingInfo.cpp
    llvm/lib/Passes/StandardInstrumentations.cpp
    llvm/lib/Transforms/IPO/SampleProfileProbe.cpp
    llvm/lib/Transforms/Scalar/LoopPassManager.cpp
    llvm/lib/Transforms/Utils/Debugify.cpp
    llvm/tools/llvm-reduce/deltas/RunIRPasses.cpp
    llvm/unittests/IR/DroppedVariableStatsIRTest.cpp
    llvm/unittests/IR/PassBuilderCallbacksTest.cpp

Removed: 
    


################################################################################
diff  --git a/llvm/include/llvm/Analysis/LazyCallGraph.h b/llvm/include/llvm/Analysis/LazyCallGraph.h
index 24128a6946ecf..ffc50388391fa 100644
--- a/llvm/include/llvm/Analysis/LazyCallGraph.h
+++ b/llvm/include/llvm/Analysis/LazyCallGraph.h
@@ -34,7 +34,6 @@
 #ifndef LLVM_ANALYSIS_LAZYCALLGRAPH_H
 #define LLVM_ANALYSIS_LAZYCALLGRAPH_H
 
-#include "llvm/ADT/Any.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/PointerIntPair.h"
@@ -44,6 +43,7 @@
 #include "llvm/ADT/iterator.h"
 #include "llvm/ADT/iterator_range.h"
 #include "llvm/Analysis/TargetLibraryInfo.h"
+#include "llvm/IR/IRUnitRef.h"
 #include "llvm/IR/PassManager.h"
 #include "llvm/Support/Allocator.h"
 #include "llvm/Support/Compiler.h"
@@ -1255,6 +1255,10 @@ template <> struct GraphTraits<LazyCallGraph *> {
   static ChildIteratorType child_end(NodeRef N) { return (*N)->end(); }
 };
 
+template <> struct IRUnitKindTraits<LazyCallGraph::SCC> {
+  static constexpr IRUnitKind Kind = IRUnitKind::LazyCallGraphSCC;
+};
+
 /// An analysis pass which computes the call graph for a module.
 class LazyCallGraphAnalysis : public AnalysisInfoMixin<LazyCallGraphAnalysis> {
   friend AnalysisInfoMixin<LazyCallGraphAnalysis>;
@@ -1304,9 +1308,6 @@ class LazyCallGraphDOTPrinterPass
 
   LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM);
 };
-
-extern template struct LLVM_TEMPLATE_ABI
-    Any::TypeId<const LazyCallGraph::SCC *>;
 } // end namespace llvm
 
 #endif // LLVM_ANALYSIS_LAZYCALLGRAPH_H

diff  --git a/llvm/include/llvm/IR/DroppedVariableStatsIR.h b/llvm/include/llvm/IR/DroppedVariableStatsIR.h
index 8c1a3e87b2606..ab44af905724f 100644
--- a/llvm/include/llvm/IR/DroppedVariableStatsIR.h
+++ b/llvm/include/llvm/IR/DroppedVariableStatsIR.h
@@ -15,11 +15,11 @@
 #define LLVM_CODEGEN_DROPPEDVARIABLESTATSIR_H
 
 #include "llvm/IR/DroppedVariableStats.h"
+#include "llvm/IR/IRUnitRef.h"
 #include "llvm/Support/Compiler.h"
 
 namespace llvm {
 
-class Any;
 class StringRef;
 class PassInstrumentationCallbacks;
 class Function;
@@ -34,9 +34,9 @@ class LLVM_ABI DroppedVariableStatsIR : public DroppedVariableStats {
   DroppedVariableStatsIR(bool DroppedVarStatsEnabled)
       : llvm::DroppedVariableStats(DroppedVarStatsEnabled) {}
 
-  void runBeforePass(StringRef P, const Any &IR);
+  void runBeforePass(StringRef P, IRUnitRef IR);
 
-  void runAfterPass(StringRef P, const Any &IR);
+  void runAfterPass(StringRef P, IRUnitRef IR);
 
   void registerCallbacks(PassInstrumentationCallbacks &PIC);
 
@@ -80,8 +80,6 @@ class LLVM_ABI DroppedVariableStatsIR : public DroppedVariableStats {
       DenseSet<VarID> &VarIDSet,
       DenseMap<StringRef, DenseMap<VarID, DILocation *>> &InlinedAtsMap,
       StringRef FuncName, bool Before) override;
-
-  template <typename IRUnitT> static const IRUnitT *unwrapIR(const Any &IR);
 };
 
 } // namespace llvm

diff  --git a/llvm/include/llvm/IR/IRUnitRef.h b/llvm/include/llvm/IR/IRUnitRef.h
new file mode 100644
index 0000000000000..a51563ddcc19a
--- /dev/null
+++ b/llvm/include/llvm/IR/IRUnitRef.h
@@ -0,0 +1,103 @@
+//===- llvm/IR/IRUnitRef.h - Reference to an IR unit ------------*- 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
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// This file defines IRUnitRef, a type-erased reference to the IR unit a pass
+/// or analysis is running on, and IRUnitKindTraits, which IR units specialize
+/// to opt into being referred to by one.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_IR_IRUNITREF_H
+#define LLVM_IR_IRUNITREF_H
+
+#include "llvm/Support/Casting.h"
+#include <cstddef>
+#include <type_traits>
+
+namespace llvm {
+
+class Function;
+class Loop;
+class MachineFunction;
+class Module;
+
+/// The IR units a pass can run on.
+enum class IRUnitKind {
+  Module,
+  Function,
+  Loop,
+  MachineFunction,
+  LazyCallGraphSCC,
+};
+
+/// Map an IR unit type to its IRUnitKind.
+template <typename IRUnitT> struct IRUnitKindTraits {};
+
+template <> struct IRUnitKindTraits<Module> {
+  static constexpr IRUnitKind Kind = IRUnitKind::Module;
+};
+template <> struct IRUnitKindTraits<Function> {
+  static constexpr IRUnitKind Kind = IRUnitKind::Function;
+};
+template <> struct IRUnitKindTraits<Loop> {
+  static constexpr IRUnitKind Kind = IRUnitKind::Loop;
+};
+template <> struct IRUnitKindTraits<MachineFunction> {
+  static constexpr IRUnitKind Kind = IRUnitKind::MachineFunction;
+};
+
+// IRUnitKindTraits<LazyCallGraph::SCC> needs to be defined in
+// Analysis/LazyCallGraph.h.
+
+/// A type-erased reference to the IR unit a pass or analysis is running on,
+/// together with the kind of IR unit it refers to.
+class IRUnitRef {
+  template <typename To, typename From, typename Enable> friend struct CastInfo;
+
+  const void *Ptr;
+  IRUnitKind Kind;
+
+  /// Which kind of IR unit is wrapped.
+  IRUnitKind getKind() const { return Kind; }
+
+  /// The wrapped IR unit, type-erased.
+  const void *getPointer() const { return Ptr; }
+
+public:
+  template <typename IRUnitT, IRUnitKind K = IRUnitKindTraits<IRUnitT>::Kind>
+  IRUnitRef(const IRUnitT &IR) : Ptr(&IR), Kind(K) {}
+};
+
+static_assert(!std::is_constructible_v<IRUnitRef, std::nullptr_t>,
+              "IRUnitRef must not be constructible from nullptr");
+
+/// Lets isa/cast/dyn_cast query which IR unit an IRUnitRef holds, naming the IR
+/// unit itself rather than a pointer to it: dyn_cast<Module>(IR).
+template <typename To> struct CastInfo<To, IRUnitRef> {
+  static bool isPossible(IRUnitRef IR) {
+    return IR.getKind() == IRUnitKindTraits<To>::Kind;
+  }
+
+  static const To *doCast(IRUnitRef IR) {
+    return static_cast<const To *>(IR.getPointer());
+  }
+
+  static const To *castFailed() { return nullptr; }
+
+  static const To *doCastIfPossible(IRUnitRef IR) {
+    return isPossible(IR) ? doCast(IR) : castFailed();
+  }
+};
+
+template <typename To>
+struct CastInfo<To, const IRUnitRef> : public CastInfo<To, IRUnitRef> {};
+
+} // end namespace llvm
+
+#endif // LLVM_IR_IRUNITREF_H

diff  --git a/llvm/include/llvm/IR/PassInstrumentation.h b/llvm/include/llvm/IR/PassInstrumentation.h
index 52eba45542390..480a65420ea80 100644
--- a/llvm/include/llvm/IR/PassInstrumentation.h
+++ b/llvm/include/llvm/IR/PassInstrumentation.h
@@ -35,10 +35,10 @@
 ///      executed and IRUnit it works on. There can be 
diff erent schemes of
 ///      providing names in future, currently it is just a name() of the pass.
 ///
-///    - PassInstrumentation wraps address of IRUnit into llvm::Any and passes
-///      control to all the registered callbacks. Note that we specifically wrap
-///      'const IRUnitT*' so as to avoid any accidental changes to IR in
-///      instrumenting callbacks.
+///    - PassInstrumentation wraps address of IRUnit into an IRUnitRef and
+///      passes control to all the registered callbacks. Note that we
+///      specifically wrap 'const IRUnitT*' so as to avoid any accidental
+///      changes to IR in instrumenting callbacks.
 ///
 ///    - Some instrumentation points (BeforePass) allow to control execution
 ///      of a pass. For those callbacks returning false means pass will not be
@@ -49,10 +49,10 @@
 #ifndef LLVM_IR_PASSINSTRUMENTATION_H
 #define LLVM_IR_PASSINSTRUMENTATION_H
 
-#include "llvm/ADT/Any.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/FunctionExtras.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/IR/IRUnitRef.h"
 #include "llvm/IR/PassManager.h"
 #include "llvm/Support/Compiler.h"
 #include <vector>
@@ -61,20 +61,13 @@ namespace llvm {
 
 class PreservedAnalyses;
 class StringRef;
-class Module;
-class Loop;
-class Function;
-
-extern template struct LLVM_TEMPLATE_ABI Any::TypeId<const Module *>;
-extern template struct LLVM_TEMPLATE_ABI Any::TypeId<const Function *>;
-extern template struct LLVM_TEMPLATE_ABI Any::TypeId<const Loop *>;
 
 /// This class manages callbacks registration, as well as provides a way for
 /// PassInstrumentation to pass control to the registered callbacks.
 class PassInstrumentationCallbacks {
 public:
   // Before/After callbacks accept IRUnits whenever appropriate, so they need
-  // to take them as constant pointers, wrapped with llvm::Any.
+  // to take them as constant pointers, wrapped with IRUnitRef.
   // For the case when IRUnit has been invalidated there is a 
diff erent
   // callback to use - AfterPassInvalidated.
   // We call all BeforePassFuncs to determine if a pass should run or not.
@@ -83,14 +76,14 @@ class PassInstrumentationCallbacks {
   // already invalidated IRUnit is unsafe. There are ways to handle invalidated
   // IRUnits in a safe way, and we might pursue that as soon as there is a
   // useful instrumentation that needs it.
-  using BeforePassFunc = bool(StringRef, const Any &);
-  using BeforeSkippedPassFunc = void(StringRef, const Any &);
-  using BeforeNonSkippedPassFunc = void(StringRef, const Any &);
-  using AfterPassFunc = void(StringRef, const Any &, const PreservedAnalyses &);
+  using BeforePassFunc = bool(StringRef, IRUnitRef);
+  using BeforeSkippedPassFunc = void(StringRef, IRUnitRef);
+  using BeforeNonSkippedPassFunc = void(StringRef, IRUnitRef);
+  using AfterPassFunc = void(StringRef, IRUnitRef, const PreservedAnalyses &);
   using AfterPassInvalidatedFunc = void(StringRef, const PreservedAnalyses &);
-  using BeforeAnalysisFunc = void(StringRef, const Any &);
-  using AfterAnalysisFunc = void(StringRef, const Any &);
-  using AnalysisInvalidatedFunc = void(StringRef, const Any &);
+  using BeforeAnalysisFunc = void(StringRef, IRUnitRef);
+  using AfterAnalysisFunc = void(StringRef, IRUnitRef);
+  using AnalysisInvalidatedFunc = void(StringRef, IRUnitRef);
   using AnalysesClearedFunc = void(StringRef);
 
 public:
@@ -237,15 +230,15 @@ class PassInstrumentation {
     bool ShouldRun = true;
     if (!isRequired(Pass)) {
       for (auto &C : Callbacks->ShouldRunOptionalPassCallbacks)
-        ShouldRun &= C(Pass.name(), llvm::Any(&IR));
+        ShouldRun &= C(Pass.name(), IR);
     }
 
     if (ShouldRun) {
       for (auto &C : Callbacks->BeforeNonSkippedPassCallbacks)
-        C(Pass.name(), llvm::Any(&IR));
+        C(Pass.name(), IR);
     } else {
       for (auto &C : Callbacks->BeforeSkippedPassCallbacks)
-        C(Pass.name(), llvm::Any(&IR));
+        C(Pass.name(), IR);
     }
 
     return ShouldRun;
@@ -259,7 +252,7 @@ class PassInstrumentation {
                     const PreservedAnalyses &PA) const {
     if (Callbacks)
       for (auto &C : Callbacks->AfterPassCallbacks)
-        C(Pass.name(), llvm::Any(&IR), PA);
+        C(Pass.name(), IR, PA);
   }
 
   /// AfterPassInvalidated instrumentation point - takes \p Pass instance
@@ -279,7 +272,7 @@ class PassInstrumentation {
   void runBeforeAnalysis(const PassT &Analysis, const IRUnitT &IR) const {
     if (Callbacks)
       for (auto &C : Callbacks->BeforeAnalysisCallbacks)
-        C(Analysis.name(), llvm::Any(&IR));
+        C(Analysis.name(), IR);
   }
 
   /// AfterAnalysis instrumentation point - takes \p Analysis instance
@@ -288,7 +281,7 @@ class PassInstrumentation {
   void runAfterAnalysis(const PassT &Analysis, const IRUnitT &IR) const {
     if (Callbacks)
       for (auto &C : Callbacks->AfterAnalysisCallbacks)
-        C(Analysis.name(), llvm::Any(&IR));
+        C(Analysis.name(), IR);
   }
 
   /// AnalysisInvalidated instrumentation point - takes \p Analysis instance
@@ -298,7 +291,7 @@ class PassInstrumentation {
   void runAnalysisInvalidated(const PassT &Analysis, const IRUnitT &IR) const {
     if (Callbacks)
       for (auto &C : Callbacks->AnalysisInvalidatedCallbacks)
-        C(Analysis.name(), llvm::Any(&IR));
+        C(Analysis.name(), IR);
   }
 
   /// AnalysesCleared instrumentation point - takes name of IR that analyses

diff  --git a/llvm/include/llvm/Passes/StandardInstrumentations.h b/llvm/include/llvm/Passes/StandardInstrumentations.h
index 513b71d93f0ce..cec8ff266a098 100644
--- a/llvm/include/llvm/Passes/StandardInstrumentations.h
+++ b/llvm/include/llvm/Passes/StandardInstrumentations.h
@@ -23,6 +23,7 @@
 #include "llvm/IR/BasicBlock.h"
 #include "llvm/IR/DebugInfoMetadata.h"
 #include "llvm/IR/DroppedVariableStatsIR.h"
+#include "llvm/IR/IRUnitRef.h"
 #include "llvm/IR/OptBisect.h"
 #include "llvm/IR/PassTimingInfo.h"
 #include "llvm/IR/ValueHandle.h"
@@ -66,8 +67,8 @@ class PrintIRInstrumentation {
           IRName{IRName}, PassID(PassID) {}
   };
 
-  void printBeforePass(StringRef PassID, const Any &IR);
-  void printAfterPass(StringRef PassID, const Any &IR);
+  void printBeforePass(StringRef PassID, IRUnitRef IR);
+  void printAfterPass(StringRef PassID, IRUnitRef IR);
   void printAfterPassInvalidated(StringRef PassID);
 
   bool shouldPrintBeforePass(StringRef PassID);
@@ -78,7 +79,7 @@ class PrintIRInstrumentation {
   bool shouldPrintBeforeSomePassNumber();
   bool shouldPrintAfterSomePassNumber();
 
-  void pushPassRunDescriptor(StringRef PassID, const Any &IR,
+  void pushPassRunDescriptor(StringRef PassID, IRUnitRef IR,
                              unsigned PassNumber);
   PassRunDescriptor popPassRunDescriptor(StringRef PassID);
 
@@ -110,7 +111,7 @@ class OptNoneInstrumentation {
 
 private:
   bool DebugLogging;
-  bool shouldRun(StringRef PassID, const Any &IR);
+  bool shouldRun(StringRef PassID, IRUnitRef IR);
 };
 
 class OptPassGateInstrumentation {
@@ -118,7 +119,7 @@ class OptPassGateInstrumentation {
   bool HasWrittenIR = false;
 public:
   OptPassGateInstrumentation(LLVMContext &Context) : Context(Context) {}
-  LLVM_ABI bool shouldRun(StringRef PassName, const Any &IR);
+  LLVM_ABI bool shouldRun(StringRef PassName, IRUnitRef IR);
   LLVM_ABI void registerCallbacks(PassInstrumentationCallbacks &PIC);
 };
 
@@ -219,9 +220,9 @@ template <typename IRUnitT> class LLVM_ABI ChangeReporter {
 
   // Determine if this pass/IR is interesting and if so, save the IR
   // otherwise it is left on the stack without data.
-  void saveIRBeforePass(const Any &IR, StringRef PassID, StringRef PassName);
+  void saveIRBeforePass(IRUnitRef IR, StringRef PassID, StringRef PassName);
   // Compare the IR from before the pass after the pass.
-  void handleIRAfterPass(const Any &IR, StringRef PassID, StringRef PassName);
+  void handleIRAfterPass(IRUnitRef IR, StringRef PassID, StringRef PassName);
   // Handle the situation where a pass is invalidated.
   void handleInvalidatedPass(StringRef PassID);
 
@@ -230,16 +231,16 @@ template <typename IRUnitT> class LLVM_ABI ChangeReporter {
   void registerRequiredCallbacks(PassInstrumentationCallbacks &PIC);
 
   // Called on the first IR processed.
-  virtual void handleInitialIR(const Any &IR) = 0;
+  virtual void handleInitialIR(IRUnitRef IR) = 0;
   // Called before and after a pass to get the representation of the IR.
-  virtual void generateIRRepresentation(const Any &IR, StringRef PassID,
+  virtual void generateIRRepresentation(IRUnitRef IR, StringRef PassID,
                                         IRUnitT &Output) = 0;
   // Called when the pass is not iteresting.
   virtual void omitAfter(StringRef PassID, std::string &Name) = 0;
   // Called when an interesting IR has changed.
   virtual void handleAfter(StringRef PassID, std::string &Name,
                            const IRUnitT &Before, const IRUnitT &After,
-                           const Any &) = 0;
+                           IRUnitRef) = 0;
   // Called when an interesting pass is invalidated.
   virtual void handleInvalidated(StringRef PassID) = 0;
   // Called when the IR or pass is not interesting.
@@ -264,7 +265,7 @@ class LLVM_ABI TextChangeReporter : public ChangeReporter<IRUnitT> {
   TextChangeReporter(bool Verbose);
 
   // Print a module dump of the first IR that is changed.
-  void handleInitialIR(const Any &IR) override;
+  void handleInitialIR(IRUnitRef IR) override;
   // Report that the IR was omitted because it did not change.
   void omitAfter(StringRef PassID, std::string &Name) override;
   // Report that the pass was invalidated.
@@ -292,12 +293,12 @@ class LLVM_ABI IRChangedPrinter : public TextChangeReporter<std::string> {
 
 protected:
   // Called before and after a pass to get the representation of the IR.
-  void generateIRRepresentation(const Any &IR, StringRef PassID,
+  void generateIRRepresentation(IRUnitRef IR, StringRef PassID,
                                 std::string &Output) override;
   // Called when an interesting IR has changed.
   void handleAfter(StringRef PassID, std::string &Name,
                    const std::string &Before, const std::string &After,
-                   const Any &) override;
+                   IRUnitRef) override;
 };
 
 class LLVM_ABI IRChangedTester : public IRChangedPrinter {
@@ -310,7 +311,7 @@ class LLVM_ABI IRChangedTester : public IRChangedPrinter {
   void handleIR(const std::string &IR, StringRef PassID);
 
   // Check initial IR
-  void handleInitialIR(const Any &IR) override;
+  void handleInitialIR(IRUnitRef IR) override;
   // Do nothing.
   void omitAfter(StringRef PassID, std::string &Name) override;
   // Do nothing.
@@ -323,7 +324,7 @@ class LLVM_ABI IRChangedTester : public IRChangedPrinter {
   // Call test as interesting IR has changed.
   void handleAfter(StringRef PassID, std::string &Name,
                    const std::string &Before, const std::string &After,
-                   const Any &) override;
+                   IRUnitRef) override;
 };
 
 // Information that needs to be saved for a basic block in order to compare
@@ -429,7 +430,7 @@ template <typename T> class IRComparer {
           CompareFunc);
 
   // Analyze \p IR and build the IR representation in \p Data.
-  static void analyzeIR(const Any &IR, IRDataT<T> &Data);
+  static void analyzeIR(IRUnitRef IR, IRDataT<T> &Data);
 
 protected:
   // Generate the data for \p F into \p Data.
@@ -457,13 +458,13 @@ class LLVM_ABI InLineChangePrinter
 
 protected:
   // Create a representation of the IR.
-  void generateIRRepresentation(const Any &IR, StringRef PassID,
+  void generateIRRepresentation(IRUnitRef IR, StringRef PassID,
                                 IRDataT<EmptyData> &Output) override;
 
   // Called when an interesting IR has changed.
   void handleAfter(StringRef PassID, std::string &Name,
                    const IRDataT<EmptyData> &Before,
-                   const IRDataT<EmptyData> &After, const Any &) override;
+                   const IRDataT<EmptyData> &After, IRUnitRef) override;
 
   void handleFunctionCompare(StringRef Name, StringRef Prefix, StringRef PassID,
                              StringRef Divider, bool InModule, unsigned Minor,
@@ -496,7 +497,7 @@ class TimeProfilingPassesHandler {
 
 private:
   // Implementation of pass instrumentation callbacks.
-  void runBeforePass(StringRef PassID, const Any &IR);
+  void runBeforePass(StringRef PassID, IRUnitRef IR);
   void runAfterPass();
 };
 
@@ -545,16 +546,16 @@ class LLVM_ABI DotCfgChangeReporter : public ChangeReporter<IRDataT<DCData>> {
   bool initializeHTML();
 
   // Called on the first IR processed.
-  void handleInitialIR(const Any &IR) override;
+  void handleInitialIR(IRUnitRef IR) override;
   // Called before and after a pass to get the representation of the IR.
-  void generateIRRepresentation(const Any &IR, StringRef PassID,
+  void generateIRRepresentation(IRUnitRef IR, StringRef PassID,
                                 IRDataT<DCData> &Output) override;
   // Called when the pass is not iteresting.
   void omitAfter(StringRef PassID, std::string &Name) override;
   // Called when an interesting IR has changed.
   void handleAfter(StringRef PassID, std::string &Name,
                    const IRDataT<DCData> &Before, const IRDataT<DCData> &After,
-                   const Any &) override;
+                   IRUnitRef) override;
   // Called when an interesting pass is invalidated.
   void handleInvalidated(StringRef PassID) override;
   // Called when the IR or pass is not interesting.

diff  --git a/llvm/include/llvm/Transforms/IPO/SampleProfileProbe.h b/llvm/include/llvm/Transforms/IPO/SampleProfileProbe.h
index cf62f8fddb38c..ae21cc804d993 100644
--- a/llvm/include/llvm/Transforms/IPO/SampleProfileProbe.h
+++ b/llvm/include/llvm/Transforms/IPO/SampleProfileProbe.h
@@ -16,7 +16,7 @@
 #define LLVM_TRANSFORMS_IPO_SAMPLEPROFILEPROBE_H
 
 #include "llvm/Analysis/LazyCallGraph.h"
-#include "llvm/IR/PassInstrumentation.h"
+#include "llvm/IR/IRUnitRef.h"
 #include "llvm/IR/PassManager.h"
 #include "llvm/ProfileData/SampleProf.h"
 #include "llvm/Support/Compiler.h"
@@ -49,7 +49,7 @@ class PseudoProbeVerifier {
   LLVM_ABI void registerCallbacks(PassInstrumentationCallbacks &PIC);
 
   // Implementation of pass instrumentation callbacks for new pass manager.
-  LLVM_ABI void runAfterPass(StringRef PassID, const Any &IR);
+  LLVM_ABI void runAfterPass(StringRef PassID, IRUnitRef IR);
 
 private:
   // Allow a little bias due the rounding to integral factors.

diff  --git a/llvm/lib/Analysis/LazyCallGraph.cpp b/llvm/lib/Analysis/LazyCallGraph.cpp
index 6dfc498144d78..1911936cd1fcc 100644
--- a/llvm/lib/Analysis/LazyCallGraph.cpp
+++ b/llvm/lib/Analysis/LazyCallGraph.cpp
@@ -37,8 +37,6 @@ using namespace llvm;
 
 #define DEBUG_TYPE "lcg"
 
-template struct LLVM_EXPORT_TEMPLATE Any::TypeId<const LazyCallGraph::SCC *>;
-
 void LazyCallGraph::EdgeSequence::insertEdgeInternal(Node &TargetN,
                                                      Edge::Kind EK) {
   EdgeIndexMap.try_emplace(&TargetN, Edges.size());

diff  --git a/llvm/lib/CodeGen/TargetPassConfig.cpp b/llvm/lib/CodeGen/TargetPassConfig.cpp
index c558a93431273..f5ea9086f6109 100644
--- a/llvm/lib/CodeGen/TargetPassConfig.cpp
+++ b/llvm/lib/CodeGen/TargetPassConfig.cpp
@@ -539,7 +539,7 @@ void llvm::registerCodeGenCallback(PassInstrumentationCallbacks &PIC,
                                    TargetMachine &TM) {
 
   // Register a callback for disabling passes.
-  PIC.registerShouldRunOptionalPassCallback([](StringRef P, const Any &) {
+  PIC.registerShouldRunOptionalPassCallback([](StringRef P, IRUnitRef) {
 
 #define DISABLE_PASS(Option, Name)                                             \
   if (Option && P.contains(#Name))                                             \

diff  --git a/llvm/lib/IR/DroppedVariableStatsIR.cpp b/llvm/lib/IR/DroppedVariableStatsIR.cpp
index 38d5eb05e70c9..d07bfd6f4390e 100644
--- a/llvm/lib/IR/DroppedVariableStatsIR.cpp
+++ b/llvm/lib/IR/DroppedVariableStatsIR.cpp
@@ -19,24 +19,18 @@
 
 using namespace llvm;
 
-template <typename IRUnitT>
-const IRUnitT *DroppedVariableStatsIR::unwrapIR(const Any &IR) {
-  const IRUnitT *const *IRPtr = llvm::any_cast<const IRUnitT *>(&IR);
-  return IRPtr ? *IRPtr : nullptr;
-}
-
-void DroppedVariableStatsIR::runBeforePass(StringRef P, const Any &IR) {
+void DroppedVariableStatsIR::runBeforePass(StringRef P, IRUnitRef IR) {
   setup();
-  if (const auto *M = unwrapIR<Module>(IR))
+  if (const auto *M = dyn_cast<Module>(IR))
     return this->runOnModule(P, M, true);
-  if (const auto *F = unwrapIR<Function>(IR))
+  if (const auto *F = dyn_cast<Function>(IR))
     return this->runOnFunction(P, F, true);
 }
 
-void DroppedVariableStatsIR::runAfterPass(StringRef P, const Any &IR) {
-  if (const auto *M = unwrapIR<Module>(IR))
+void DroppedVariableStatsIR::runAfterPass(StringRef P, IRUnitRef IR) {
+  if (const auto *M = dyn_cast<Module>(IR))
     runAfterPassModule(P, M);
-  else if (const auto *F = unwrapIR<Function>(IR))
+  else if (const auto *F = dyn_cast<Function>(IR))
     runAfterPassFunction(P, F);
   cleanup();
 }
@@ -92,9 +86,9 @@ void DroppedVariableStatsIR::registerCallbacks(
     return;
 
   PIC.registerBeforeNonSkippedPassCallback(
-      [this](StringRef P, const Any &IR) { return runBeforePass(P, IR); });
+      [this](StringRef P, IRUnitRef IR) { return runBeforePass(P, IR); });
   PIC.registerAfterPassCallback(
-      [this](StringRef P, const Any &IR, const PreservedAnalyses &PA) {
+      [this](StringRef P, IRUnitRef IR, const PreservedAnalyses &PA) {
         return runAfterPass(P, IR);
       });
   PIC.registerAfterPassInvalidatedCallback(

diff  --git a/llvm/lib/IR/PassInstrumentation.cpp b/llvm/lib/IR/PassInstrumentation.cpp
index 52aad8f84123b..96534b52e2cb1 100644
--- a/llvm/lib/IR/PassInstrumentation.cpp
+++ b/llvm/lib/IR/PassInstrumentation.cpp
@@ -17,10 +17,6 @@
 
 using namespace llvm;
 
-template struct LLVM_EXPORT_TEMPLATE Any::TypeId<const Module *>;
-template struct LLVM_EXPORT_TEMPLATE Any::TypeId<const Function *>;
-template struct LLVM_EXPORT_TEMPLATE Any::TypeId<const Loop *>;
-
 void PassInstrumentationCallbacks::addClassToPassName(StringRef ClassName,
                                                       StringRef PassName) {
   assert(!PassName.empty() && "PassName can't be empty!");

diff  --git a/llvm/lib/IR/PassTimingInfo.cpp b/llvm/lib/IR/PassTimingInfo.cpp
index c7c3bc530516b..487cef0bce12a 100644
--- a/llvm/lib/IR/PassTimingInfo.cpp
+++ b/llvm/lib/IR/PassTimingInfo.cpp
@@ -301,9 +301,9 @@ void TimePassesHandler::registerCallbacks(PassInstrumentationCallbacks &PIC) {
     return;
 
   PIC.registerBeforeNonSkippedPassCallback(
-      [this](StringRef P, const Any &) { this->startPassTimer(P); });
+      [this](StringRef P, IRUnitRef) { this->startPassTimer(P); });
   PIC.registerAfterPassCallback(
-      [this](StringRef P, const Any &, const PreservedAnalyses &) {
+      [this](StringRef P, IRUnitRef, const PreservedAnalyses &) {
         this->stopPassTimer(P);
       });
   PIC.registerAfterPassInvalidatedCallback(
@@ -311,7 +311,7 @@ void TimePassesHandler::registerCallbacks(PassInstrumentationCallbacks &PIC) {
         this->stopPassTimer(P);
       });
   PIC.registerBeforeAnalysisCallback(
-      [this](StringRef P, const Any &) { this->startAnalysisTimer(P); });
+      [this](StringRef P, IRUnitRef) { this->startAnalysisTimer(P); });
   PIC.registerAfterAnalysisCallback(
-      [this](StringRef P, const Any &) { this->stopAnalysisTimer(P); });
+      [this](StringRef P, IRUnitRef) { this->stopAnalysisTimer(P); });
 }

diff  --git a/llvm/lib/Passes/StandardInstrumentations.cpp b/llvm/lib/Passes/StandardInstrumentations.cpp
index 33e120dc96936..6f79f1b17a98d 100644
--- a/llvm/lib/Passes/StandardInstrumentations.cpp
+++ b/llvm/lib/Passes/StandardInstrumentations.cpp
@@ -13,7 +13,6 @@
 //===----------------------------------------------------------------------===//
 
 #include "llvm/Passes/StandardInstrumentations.h"
-#include "llvm/ADT/Any.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/StringRef.h"
@@ -140,11 +139,6 @@ static cl::opt<bool>
                     cl::desc("Dump dropped debug variables stats"),
                     cl::init(false));
 
-template <typename IRUnitT> static const IRUnitT *unwrapIR(const Any &IR) {
-  const IRUnitT *const *IRPtr = llvm::any_cast<const IRUnitT *>(&IR);
-  return IRPtr ? *IRPtr : nullptr;
-}
-
 namespace {
 
 // An option for specifying an executable that will be called with the IR
@@ -161,18 +155,18 @@ static cl::opt<std::string>
 
 /// Extract Module out of \p IR unit. May return nullptr if \p IR does not match
 /// certain global filters. Will never return nullptr if \p Force is true.
-const Module *unwrapModule(const Any &IR, bool Force = false) {
-  if (const auto *M = unwrapIR<Module>(IR))
+const Module *unwrapModule(IRUnitRef IR, bool Force = false) {
+  if (const auto *M = dyn_cast<Module>(IR))
     return M;
 
-  if (const auto *F = unwrapIR<Function>(IR)) {
+  if (const auto *F = dyn_cast<Function>(IR)) {
     if (!Force && !isFunctionInPrintList(F->getName()))
       return nullptr;
 
     return F->getParent();
   }
 
-  if (const auto *C = unwrapIR<LazyCallGraph::SCC>(IR)) {
+  if (const auto *C = dyn_cast<LazyCallGraph::SCC>(IR)) {
     for (const LazyCallGraph::Node &N : *C) {
       const Function &F = N.getFunction();
       if (Force || (!F.isDeclaration() && isFunctionInPrintList(F.getName()))) {
@@ -183,14 +177,14 @@ const Module *unwrapModule(const Any &IR, bool Force = false) {
     return nullptr;
   }
 
-  if (const auto *L = unwrapIR<Loop>(IR)) {
+  if (const auto *L = dyn_cast<Loop>(IR)) {
     const Function *F = L->getHeader()->getParent();
     if (!Force && !isFunctionInPrintList(F->getName()))
       return nullptr;
     return F->getParent();
   }
 
-  if (const auto *MF = unwrapIR<MachineFunction>(IR)) {
+  if (const auto *MF = dyn_cast<MachineFunction>(IR)) {
     if (!Force && !isFunctionInPrintList(MF->getName()))
       return nullptr;
     return MF->getFunction().getParent();
@@ -237,21 +231,21 @@ void printIR(raw_ostream &OS, const MachineFunction *MF) {
   MF->print(OS);
 }
 
-std::string getIRName(const Any &IR) {
-  if (unwrapIR<Module>(IR))
+std::string getIRName(IRUnitRef IR) {
+  if (isa<Module>(IR))
     return "[module]";
 
-  if (const auto *F = unwrapIR<Function>(IR))
+  if (const auto *F = dyn_cast<Function>(IR))
     return F->getName().str();
 
-  if (const auto *C = unwrapIR<LazyCallGraph::SCC>(IR))
+  if (const auto *C = dyn_cast<LazyCallGraph::SCC>(IR))
     return C->getName();
 
-  if (const auto *L = unwrapIR<Loop>(IR))
+  if (const auto *L = dyn_cast<Loop>(IR))
     return "loop %" + L->getName().str() + " in function " +
            L->getHeader()->getParent()->getName().str();
 
-  if (const auto *MF = unwrapIR<MachineFunction>(IR))
+  if (const auto *MF = dyn_cast<MachineFunction>(IR))
     return MF->getName().str();
 
   llvm_unreachable("Unknown wrapped IR type");
@@ -273,27 +267,27 @@ bool sccContainsFilterPrintFunc(const LazyCallGraph::SCC &C) {
          isFunctionInPrintList("*");
 }
 
-bool shouldPrintIR(const Any &IR) {
-  if (const auto *M = unwrapIR<Module>(IR))
+bool shouldPrintIR(IRUnitRef IR) {
+  if (const auto *M = dyn_cast<Module>(IR))
     return moduleContainsFilterPrintFunc(*M);
 
-  if (const auto *F = unwrapIR<Function>(IR))
+  if (const auto *F = dyn_cast<Function>(IR))
     return isFunctionInPrintList(F->getName());
 
-  if (const auto *C = unwrapIR<LazyCallGraph::SCC>(IR))
+  if (const auto *C = dyn_cast<LazyCallGraph::SCC>(IR))
     return sccContainsFilterPrintFunc(*C);
 
-  if (const auto *L = unwrapIR<Loop>(IR))
+  if (const auto *L = dyn_cast<Loop>(IR))
     return isFunctionInPrintList(L->getHeader()->getParent()->getName());
 
-  if (const auto *MF = unwrapIR<MachineFunction>(IR))
+  if (const auto *MF = dyn_cast<MachineFunction>(IR))
     return isFunctionInPrintList(MF->getName());
   llvm_unreachable("Unknown wrapped IR type");
 }
 
 /// Generic IR-printing helper that unpacks a pointer to IRUnit wrapped into
-/// Any and does actual print job.
-void unwrapAndPrint(raw_ostream &OS, const Any &IR) {
+/// an IRUnitRef and does actual print job.
+void unwrapAndPrint(raw_ostream &OS, IRUnitRef IR) {
   if (!shouldPrintIR(IR))
     return;
 
@@ -304,27 +298,27 @@ void unwrapAndPrint(raw_ostream &OS, const Any &IR) {
     return;
   }
 
-  if (const auto *M = unwrapIR<Module>(IR)) {
+  if (const auto *M = dyn_cast<Module>(IR)) {
     printIR(OS, M);
     return;
   }
 
-  if (const auto *F = unwrapIR<Function>(IR)) {
+  if (const auto *F = dyn_cast<Function>(IR)) {
     printIR(OS, F);
     return;
   }
 
-  if (const auto *C = unwrapIR<LazyCallGraph::SCC>(IR)) {
+  if (const auto *C = dyn_cast<LazyCallGraph::SCC>(IR)) {
     printIR(OS, C);
     return;
   }
 
-  if (const auto *L = unwrapIR<Loop>(IR)) {
+  if (const auto *L = dyn_cast<Loop>(IR)) {
     printIR(OS, L);
     return;
   }
 
-  if (const auto *MF = unwrapIR<MachineFunction>(IR)) {
+  if (const auto *MF = dyn_cast<MachineFunction>(IR)) {
     printIR(OS, MF);
     return;
   }
@@ -357,10 +351,10 @@ std::string makeHTMLReady(StringRef SR) {
 }
 
 // Return the module when that is the appropriate level of comparison for \p IR.
-const Module *getModuleForComparison(const Any &IR) {
-  if (const auto *M = unwrapIR<Module>(IR))
+const Module *getModuleForComparison(IRUnitRef IR) {
+  if (const auto *M = dyn_cast<Module>(IR))
     return M;
-  if (const auto *C = unwrapIR<LazyCallGraph::SCC>(IR))
+  if (const auto *C = dyn_cast<LazyCallGraph::SCC>(IR))
     return C->begin()->getFunction().getParent();
   return nullptr;
 }
@@ -371,10 +365,10 @@ bool isInterestingFunction(const Function &F) {
 
 // Return true when this is a pass on IR for which printing
 // of changes is desired.
-bool isInteresting(const Any &IR, StringRef PassID, StringRef PassName) {
+bool isInteresting(IRUnitRef IR, StringRef PassID, StringRef PassName) {
   if (isIgnored(PassID) || !isPassInPrintList(PassName))
     return false;
-  if (const auto *F = unwrapIR<Function>(IR))
+  if (const auto *F = dyn_cast<Function>(IR))
     return isInterestingFunction(*F);
   return true;
 }
@@ -386,7 +380,7 @@ template <typename T> ChangeReporter<T>::~ChangeReporter() {
 }
 
 template <typename T>
-void ChangeReporter<T>::saveIRBeforePass(const Any &IR, StringRef PassID,
+void ChangeReporter<T>::saveIRBeforePass(IRUnitRef IR, StringRef PassID,
                                          StringRef PassName) {
   // Is this the initial IR?
   if (InitialIR) {
@@ -409,7 +403,7 @@ void ChangeReporter<T>::saveIRBeforePass(const Any &IR, StringRef PassID,
 }
 
 template <typename T>
-void ChangeReporter<T>::handleIRAfterPass(const Any &IR, StringRef PassID,
+void ChangeReporter<T>::handleIRAfterPass(IRUnitRef IR, StringRef PassID,
                                           StringRef PassName) {
   assert(!BeforeStack.empty() && "Unexpected empty stack encountered.");
 
@@ -455,12 +449,12 @@ template <typename T>
 void ChangeReporter<T>::registerRequiredCallbacks(
     PassInstrumentationCallbacks &PIC) {
   PIC.registerBeforeNonSkippedPassCallback(
-      [&PIC, this](StringRef P, const Any &IR) {
+      [&PIC, this](StringRef P, IRUnitRef IR) {
         saveIRBeforePass(IR, P, PIC.getPassNameForClassName(P));
       });
 
   PIC.registerAfterPassCallback(
-      [&PIC, this](StringRef P, const Any &IR, const PreservedAnalyses &) {
+      [&PIC, this](StringRef P, IRUnitRef IR, const PreservedAnalyses &) {
         handleIRAfterPass(IR, P, PIC.getPassNameForClassName(P));
       });
   PIC.registerAfterPassInvalidatedCallback(
@@ -474,7 +468,7 @@ TextChangeReporter<T>::TextChangeReporter(bool Verbose)
     : ChangeReporter<T>(Verbose), Out(dbgs()) {}
 
 template <typename T>
-void TextChangeReporter<T>::handleInitialIR(const Any &IR) {
+void TextChangeReporter<T>::handleInitialIR(IRUnitRef IR) {
   // Always print the module.
   // Unwrap and print directly to avoid filtering problems in general routines.
   auto *M = unwrapModule(IR, /*Force=*/true);
@@ -515,7 +509,7 @@ void IRChangedPrinter::registerCallbacks(PassInstrumentationCallbacks &PIC) {
     TextChangeReporter<std::string>::registerRequiredCallbacks(PIC);
 }
 
-void IRChangedPrinter::generateIRRepresentation(const Any &IR, StringRef PassID,
+void IRChangedPrinter::generateIRRepresentation(IRUnitRef IR, StringRef PassID,
                                                 std::string &Output) {
   raw_string_ostream OS(Output);
   unwrapAndPrint(OS, IR);
@@ -524,7 +518,7 @@ void IRChangedPrinter::generateIRRepresentation(const Any &IR, StringRef PassID,
 
 void IRChangedPrinter::handleAfter(StringRef PassID, std::string &Name,
                                    const std::string &Before,
-                                   const std::string &After, const Any &) {
+                                   const std::string &After, IRUnitRef) {
   // Report the IR before the changes when requested.
   if (PrintChangedBefore)
     Out << "*** IR Dump Before " << PassID << " on " << Name << " ***\n"
@@ -573,7 +567,7 @@ void IRChangedTester::handleIR(const std::string &S, StringRef PassID) {
     dbgs() << "Unable to remove temporary file.";
 }
 
-void IRChangedTester::handleInitialIR(const Any &IR) {
+void IRChangedTester::handleInitialIR(IRUnitRef IR) {
   // Always test the initial module.
   // Unwrap and print directly to avoid filtering problems in general routines.
   std::string S;
@@ -587,7 +581,7 @@ void IRChangedTester::handleFiltered(StringRef PassID, std::string &Name) {}
 void IRChangedTester::handleIgnored(StringRef PassID, std::string &Name) {}
 void IRChangedTester::handleAfter(StringRef PassID, std::string &Name,
                                   const std::string &Before,
-                                  const std::string &After, const Any &) {
+                                  const std::string &After, IRUnitRef) {
   handleIR(After, PassID);
 }
 
@@ -692,7 +686,7 @@ void IRComparer<T>::compare(
 }
 
 template <typename T>
-void IRComparer<T>::analyzeIR(const Any &IR, IRDataT<T> &Data) {
+void IRComparer<T>::analyzeIR(IRUnitRef IR, IRDataT<T> &Data) {
   if (const Module *M = getModuleForComparison(IR)) {
     // Create data for each existing/interesting function in the module.
     for (const Function &F : *M)
@@ -700,18 +694,18 @@ void IRComparer<T>::analyzeIR(const Any &IR, IRDataT<T> &Data) {
     return;
   }
 
-  if (const auto *F = unwrapIR<Function>(IR)) {
+  if (const auto *F = dyn_cast<Function>(IR)) {
     generateFunctionData(Data, *F);
     return;
   }
 
-  if (const auto *L = unwrapIR<Loop>(IR)) {
+  if (const auto *L = dyn_cast<Loop>(IR)) {
     auto *F = L->getHeader()->getParent();
     generateFunctionData(Data, *F);
     return;
   }
 
-  if (const auto *MF = unwrapIR<MachineFunction>(IR)) {
+  if (const auto *MF = dyn_cast<MachineFunction>(IR)) {
     generateFunctionData(Data, *MF);
     return;
   }
@@ -754,28 +748,28 @@ PrintIRInstrumentation::~PrintIRInstrumentation() {
          "PassRunDescriptorStack is not empty at exit");
 }
 
-static void writeIRFileDisplayName(raw_ostream &ResultStream, const Any &IR) {
+static void writeIRFileDisplayName(raw_ostream &ResultStream, IRUnitRef IR) {
   const Module *M = unwrapModule(IR, /*Force=*/true);
   assert(M && "should have unwrapped module");
   uint64_t NameHash = xxh3_64bits(M->getName());
   unsigned MaxHashWidth = sizeof(uint64_t) * 2;
   write_hex(ResultStream, NameHash, HexPrintStyle::Lower, MaxHashWidth);
-  if (unwrapIR<Module>(IR)) {
+  if (isa<Module>(IR)) {
     ResultStream << "-module";
-  } else if (const auto *F = unwrapIR<Function>(IR)) {
+  } else if (const auto *F = dyn_cast<Function>(IR)) {
     ResultStream << "-function-";
     auto FunctionNameHash = xxh3_64bits(F->getName());
     write_hex(ResultStream, FunctionNameHash, HexPrintStyle::Lower,
               MaxHashWidth);
-  } else if (const auto *C = unwrapIR<LazyCallGraph::SCC>(IR)) {
+  } else if (const auto *C = dyn_cast<LazyCallGraph::SCC>(IR)) {
     ResultStream << "-scc-";
     auto SCCNameHash = xxh3_64bits(C->getName());
     write_hex(ResultStream, SCCNameHash, HexPrintStyle::Lower, MaxHashWidth);
-  } else if (const auto *L = unwrapIR<Loop>(IR)) {
+  } else if (const auto *L = dyn_cast<Loop>(IR)) {
     ResultStream << "-loop-";
     auto LoopNameHash = xxh3_64bits(L->getName());
     write_hex(ResultStream, LoopNameHash, HexPrintStyle::Lower, MaxHashWidth);
-  } else if (const auto *MF = unwrapIR<MachineFunction>(IR)) {
+  } else if (const auto *MF = dyn_cast<MachineFunction>(IR)) {
     ResultStream << "-machine-function-";
     auto MachineFunctionNameHash = xxh3_64bits(MF->getName());
     write_hex(ResultStream, MachineFunctionNameHash, HexPrintStyle::Lower,
@@ -785,7 +779,7 @@ static void writeIRFileDisplayName(raw_ostream &ResultStream, const Any &IR) {
   }
 }
 
-static std::string getIRFileDisplayName(const Any &IR) {
+static std::string getIRFileDisplayName(IRUnitRef IR) {
   std::string Result;
   raw_string_ostream ResultStream(Result);
   writeIRFileDisplayName(ResultStream, IR);
@@ -817,7 +811,7 @@ std::string PrintIRInstrumentation::fetchDumpFilename(
 }
 
 void PrintIRInstrumentation::pushPassRunDescriptor(StringRef PassID,
-                                                   const Any &IR,
+                                                   IRUnitRef IR,
                                                    unsigned PassNumber) {
   const Module *M = unwrapModule(IR);
   PassRunDescriptorStack.emplace_back(M, PassNumber, getIRFileDisplayName(IR),
@@ -851,7 +845,7 @@ static int prepareDumpIRFileDescriptor(const StringRef DumpIRFilename) {
   return Result;
 }
 
-void PrintIRInstrumentation::printBeforePass(StringRef PassID, const Any &IR) {
+void PrintIRInstrumentation::printBeforePass(StringRef PassID, IRUnitRef IR) {
   if (isIgnored(PassID))
     return;
 
@@ -897,7 +891,7 @@ void PrintIRInstrumentation::printBeforePass(StringRef PassID, const Any &IR) {
   }
 }
 
-void PrintIRInstrumentation::printAfterPass(StringRef PassID, const Any &IR) {
+void PrintIRInstrumentation::printAfterPass(StringRef PassID, IRUnitRef IR) {
   if (isIgnored(PassID))
     return;
 
@@ -1020,11 +1014,11 @@ void PrintIRInstrumentation::registerCallbacks(
       shouldPrintAfterSomePassNumber() || shouldPrintBeforeSomePass() ||
       shouldPrintAfterSomePass())
     PIC.registerBeforeNonSkippedPassCallback(
-        [this](StringRef P, const Any &IR) { this->printBeforePass(P, IR); });
+        [this](StringRef P, IRUnitRef IR) { this->printBeforePass(P, IR); });
 
   if (shouldPrintAfterSomePass() || shouldPrintAfterSomePassNumber()) {
     PIC.registerAfterPassCallback(
-        [this](StringRef P, const Any &IR, const PreservedAnalyses &) {
+        [this](StringRef P, IRUnitRef IR, const PreservedAnalyses &) {
           this->printAfterPass(P, IR);
         });
     PIC.registerAfterPassInvalidatedCallback(
@@ -1037,16 +1031,16 @@ void PrintIRInstrumentation::registerCallbacks(
 void OptNoneInstrumentation::registerCallbacks(
     PassInstrumentationCallbacks &PIC) {
   PIC.registerShouldRunOptionalPassCallback(
-      [this](StringRef P, const Any &IR) { return this->shouldRun(P, IR); });
+      [this](StringRef P, IRUnitRef IR) { return this->shouldRun(P, IR); });
 }
 
-bool OptNoneInstrumentation::shouldRun(StringRef PassID, const Any &IR) {
+bool OptNoneInstrumentation::shouldRun(StringRef PassID, IRUnitRef IR) {
   bool ShouldRun = true;
-  if (const auto *F = unwrapIR<Function>(IR))
+  if (const auto *F = dyn_cast<Function>(IR))
     ShouldRun = !F->hasOptNone();
-  else if (const auto *L = unwrapIR<Loop>(IR))
+  else if (const auto *L = dyn_cast<Loop>(IR))
     ShouldRun = !L->getHeader()->getParent()->hasOptNone();
-  else if (const auto *MF = unwrapIR<MachineFunction>(IR))
+  else if (const auto *MF = dyn_cast<MachineFunction>(IR))
     ShouldRun = !MF->getFunction().hasOptNone();
 
   if (!ShouldRun && DebugLogging) {
@@ -1056,7 +1050,7 @@ bool OptNoneInstrumentation::shouldRun(StringRef PassID, const Any &IR) {
   return ShouldRun;
 }
 
-bool OptPassGateInstrumentation::shouldRun(StringRef PassName, const Any &IR) {
+bool OptPassGateInstrumentation::shouldRun(StringRef PassName, IRUnitRef IR) {
   if (isIgnored(PassName))
     return true;
 
@@ -1084,7 +1078,7 @@ void OptPassGateInstrumentation::registerCallbacks(
     return;
 
   PIC.registerShouldRunOptionalPassCallback(
-      [this, &PIC](StringRef ClassName, const Any &IR) {
+      [this, &PIC](StringRef ClassName, IRUnitRef IR) {
         StringRef PassName = PIC.getPassNameForClassName(ClassName);
         if (PassName.empty())
           return this->shouldRun(ClassName, IR);
@@ -1112,26 +1106,26 @@ void PrintPassInstrumentation::registerCallbacks(
   }
 
   PIC.registerBeforeSkippedPassCallback([this, SpecialPasses](StringRef PassID,
-                                                              const Any &IR) {
+                                                              IRUnitRef IR) {
     assert(!isSpecialPass(PassID, SpecialPasses) &&
            "Unexpectedly skipping special pass");
 
     print() << "Skipping pass: " << PassID << " on " << getIRName(IR) << "\n";
   });
   PIC.registerBeforeNonSkippedPassCallback(
-      [this, SpecialPasses](StringRef PassID, const Any &IR) {
+      [this, SpecialPasses](StringRef PassID, IRUnitRef IR) {
         if (isSpecialPass(PassID, SpecialPasses))
           return;
 
         auto &OS = print();
         OS << "Running pass: " << PassID << " on " << getIRName(IR);
-        if (const auto *F = unwrapIR<Function>(IR)) {
+        if (const auto *F = dyn_cast<Function>(IR)) {
           unsigned Count = F->getInstructionCount();
           OS << " (" << Count << " instruction";
           if (Count != 1)
             OS << 's';
           OS << ')';
-        } else if (const auto *C = unwrapIR<LazyCallGraph::SCC>(IR)) {
+        } else if (const auto *C = dyn_cast<LazyCallGraph::SCC>(IR)) {
           int Count = C->size();
           OS << " (" << Count << " node";
           if (Count != 1)
@@ -1142,7 +1136,7 @@ void PrintPassInstrumentation::registerCallbacks(
         Indent += 2;
       });
   PIC.registerAfterPassCallback(
-      [this, SpecialPasses](StringRef PassID, const Any &IR,
+      [this, SpecialPasses](StringRef PassID, IRUnitRef IR,
                             const PreservedAnalyses &) {
         if (isSpecialPass(PassID, SpecialPasses))
           return;
@@ -1150,7 +1144,7 @@ void PrintPassInstrumentation::registerCallbacks(
         Indent -= 2;
       });
   PIC.registerAfterPassInvalidatedCallback(
-      [this, SpecialPasses](StringRef PassID, const Any &IR) {
+      [this, SpecialPasses](StringRef PassID, const PreservedAnalyses &) {
         if (isSpecialPass(PassID, SpecialPasses))
           return;
 
@@ -1158,15 +1152,15 @@ void PrintPassInstrumentation::registerCallbacks(
       });
 
   if (!Opts.SkipAnalyses) {
-    PIC.registerBeforeAnalysisCallback([this](StringRef PassID, const Any &IR) {
+    PIC.registerBeforeAnalysisCallback([this](StringRef PassID, IRUnitRef IR) {
       print() << "Running analysis: " << PassID << " on " << getIRName(IR)
               << "\n";
       Indent += 2;
     });
     PIC.registerAfterAnalysisCallback(
-        [this](StringRef PassID, const Any &IR) { Indent -= 2; });
+        [this](StringRef PassID, IRUnitRef IR) { Indent -= 2; });
     PIC.registerAnalysisInvalidatedCallback([this](StringRef PassID,
-                                                   const Any &IR) {
+                                                   IRUnitRef IR) {
       print() << "Invalidating analysis: " << PassID << " on " << getIRName(IR)
               << "\n";
     });
@@ -1345,12 +1339,12 @@ bool PreservedCFGCheckerInstrumentation::CFG::invalidate(
            PAC.preservedSet<CFGAnalyses>());
 }
 
-static SmallVector<Function *, 1> GetFunctions(const Any &IR) {
+static SmallVector<Function *, 1> GetFunctions(IRUnitRef IR) {
   SmallVector<Function *, 1> Functions;
 
-  if (const auto *MaybeF = unwrapIR<Function>(IR)) {
+  if (const auto *MaybeF = dyn_cast<Function>(IR)) {
     Functions.push_back(const_cast<Function *>(MaybeF));
-  } else if (const auto *MaybeM = unwrapIR<Module>(IR)) {
+  } else if (const auto *MaybeM = dyn_cast<Module>(IR)) {
     for (Function &F : *const_cast<Module *>(MaybeM))
       Functions.push_back(&F);
   }
@@ -1365,7 +1359,7 @@ void PreservedCFGCheckerInstrumentation::registerCallbacks(
   bool Registered = false;
   PIC.registerBeforeNonSkippedPassCallback([this, &MAM,
                                             Registered](StringRef P,
-                                                        const Any &IR) mutable {
+                                                        IRUnitRef IR) mutable {
 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     assert(&PassStack.emplace_back(P));
 #endif
@@ -1387,7 +1381,7 @@ void PreservedCFGCheckerInstrumentation::registerCallbacks(
       FAM.getResult<PreservedFunctionHashAnalysis>(*F);
     }
 
-    if (const auto *MPtr = unwrapIR<Module>(IR)) {
+    if (const auto *MPtr = dyn_cast<Module>(IR)) {
       auto &M = *const_cast<Module *>(MPtr);
       MAM.getResult<PreservedModuleHashAnalysis>(M);
     }
@@ -1402,7 +1396,7 @@ void PreservedCFGCheckerInstrumentation::registerCallbacks(
         (void)this;
       });
 
-  PIC.registerAfterPassCallback([this, &MAM](StringRef P, const Any &IR,
+  PIC.registerAfterPassCallback([this, &MAM](StringRef P, IRUnitRef IR,
                                              const PreservedAnalyses &PassPA) {
 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
     assert(PassStack.pop_back_val() == P &&
@@ -1446,7 +1440,7 @@ void PreservedCFGCheckerInstrumentation::registerCallbacks(
         CheckCFG(P, F->getName(), *GraphBefore,
                  CFG(F, /* TrackBBLifetime */ false));
     }
-    if (const auto *MPtr = unwrapIR<Module>(IR)) {
+    if (const auto *MPtr = dyn_cast<Module>(IR)) {
       auto &M = *const_cast<Module *>(MPtr);
       if (auto *HashBefore =
               MAM.getCachedResult<PreservedModuleHashAnalysis>(M)) {
@@ -1462,12 +1456,12 @@ void PreservedCFGCheckerInstrumentation::registerCallbacks(
 void VerifyInstrumentation::registerCallbacks(PassInstrumentationCallbacks &PIC,
                                               ModuleAnalysisManager *MAM) {
   PIC.registerAfterPassCallback(
-      [this, MAM](StringRef P, const Any &IR, const PreservedAnalyses &PassPA) {
+      [this, MAM](StringRef P, IRUnitRef IR, const PreservedAnalyses &PassPA) {
         if (isIgnored(P) || P == "VerifierPass")
           return;
-        const auto *F = unwrapIR<Function>(IR);
+        const auto *F = dyn_cast<Function>(IR);
         if (!F) {
-          if (const auto *L = unwrapIR<Loop>(IR))
+          if (const auto *L = dyn_cast<Loop>(IR))
             F = L->getHeader()->getParent();
         }
 
@@ -1480,9 +1474,9 @@ void VerifyInstrumentation::registerCallbacks(PassInstrumentationCallbacks &PIC,
                                        "\"{0}\", compilation aborted!",
                                        P));
         } else {
-          const auto *M = unwrapIR<Module>(IR);
+          const auto *M = dyn_cast<Module>(IR);
           if (!M) {
-            if (const auto *C = unwrapIR<LazyCallGraph::SCC>(IR))
+            if (const auto *C = dyn_cast<LazyCallGraph::SCC>(IR))
               M = C->begin()->getFunction().getParent();
           }
 
@@ -1496,7 +1490,7 @@ void VerifyInstrumentation::registerCallbacks(PassInstrumentationCallbacks &PIC,
                                          P));
           }
 
-          if (auto *MF = unwrapIR<MachineFunction>(IR)) {
+          if (auto *MF = dyn_cast<MachineFunction>(IR)) {
             if (DebugLogging)
               dbgs() << "Verifying machine function " << MF->getName() << '\n';
             std::string Banner =
@@ -1520,7 +1514,7 @@ void VerifyInstrumentation::registerCallbacks(PassInstrumentationCallbacks &PIC,
 
 InLineChangePrinter::~InLineChangePrinter() = default;
 
-void InLineChangePrinter::generateIRRepresentation(const Any &IR,
+void InLineChangePrinter::generateIRRepresentation(IRUnitRef IR,
                                                    StringRef PassID,
                                                    IRDataT<EmptyData> &D) {
   IRComparer<EmptyData>::analyzeIR(IR, D);
@@ -1529,7 +1523,7 @@ void InLineChangePrinter::generateIRRepresentation(const Any &IR,
 void InLineChangePrinter::handleAfter(StringRef PassID, std::string &Name,
                                       const IRDataT<EmptyData> &Before,
                                       const IRDataT<EmptyData> &After,
-                                      const Any &IR) {
+                                      IRUnitRef IR) {
   SmallString<20> Banner =
       formatv("*** IR Dump After {0} on {1} ***\n", PassID, Name);
   Out << Banner;
@@ -1580,9 +1574,9 @@ void TimeProfilingPassesHandler::registerCallbacks(
   if (!getTimeTraceProfilerInstance())
     return;
   PIC.registerBeforeNonSkippedPassCallback(
-      [this](StringRef P, const Any &IR) { this->runBeforePass(P, IR); });
+      [this](StringRef P, IRUnitRef IR) { this->runBeforePass(P, IR); });
   PIC.registerAfterPassCallback(
-      [this](StringRef P, const Any &IR, const PreservedAnalyses &) {
+      [this](StringRef P, IRUnitRef IR, const PreservedAnalyses &) {
         this->runAfterPass();
       },
       true);
@@ -1590,13 +1584,12 @@ void TimeProfilingPassesHandler::registerCallbacks(
       [this](StringRef P, const PreservedAnalyses &) { this->runAfterPass(); },
       true);
   PIC.registerBeforeAnalysisCallback(
-      [this](StringRef P, const Any &IR) { this->runBeforePass(P, IR); });
+      [this](StringRef P, IRUnitRef IR) { this->runBeforePass(P, IR); });
   PIC.registerAfterAnalysisCallback(
-      [this](StringRef P, const Any &IR) { this->runAfterPass(); }, true);
+      [this](StringRef P, IRUnitRef IR) { this->runAfterPass(); }, true);
 }
 
-void TimeProfilingPassesHandler::runBeforePass(StringRef PassID,
-                                               const Any &IR) {
+void TimeProfilingPassesHandler::runBeforePass(StringRef PassID, IRUnitRef IR) {
   timeTraceProfilerBegin(PassID, getIRName(IR));
 }
 
@@ -2285,7 +2278,7 @@ std::string DotCfgChangeReporter::genHTML(StringRef Text, StringRef DotFile,
   return S.c_str();
 }
 
-void DotCfgChangeReporter::handleInitialIR(const Any &IR) {
+void DotCfgChangeReporter::handleInitialIR(IRUnitRef IR) {
   assert(HTML && "Expected outstream to be set");
   *HTML << "<button type=\"button\" class=\"collapsible\">0. "
         << "Initial IR (by function)</button>\n"
@@ -2309,7 +2302,7 @@ void DotCfgChangeReporter::handleInitialIR(const Any &IR) {
   ++N;
 }
 
-void DotCfgChangeReporter::generateIRRepresentation(const Any &IR,
+void DotCfgChangeReporter::generateIRRepresentation(IRUnitRef IR,
                                                     StringRef PassID,
                                                     IRDataT<DCData> &Data) {
   IRComparer<DCData>::analyzeIR(IR, Data);
@@ -2327,7 +2320,7 @@ void DotCfgChangeReporter::omitAfter(StringRef PassID, std::string &Name) {
 void DotCfgChangeReporter::handleAfter(StringRef PassID, std::string &Name,
                                        const IRDataT<DCData> &Before,
                                        const IRDataT<DCData> &After,
-                                       const Any &IR) {
+                                       IRUnitRef IR) {
   assert(HTML && "Expected outstream to be set");
   IRComparer<DCData>(Before, After)
       .compare(getModuleForComparison(IR),
@@ -2502,7 +2495,7 @@ void PrintCrashIRInstrumentation::registerCallbacks(
   CrashReporter = this;
 
   PIC.registerBeforeNonSkippedPassCallback(
-      [&PIC, this](StringRef PassID, const Any &IR) {
+      [&PIC, this](StringRef PassID, IRUnitRef IR) {
         SavedIR.clear();
         raw_string_ostream OS(SavedIR);
         OS << formatv("; *** Dump of {0}IR Before Last Pass {1}",

diff  --git a/llvm/lib/Transforms/IPO/SampleProfileProbe.cpp b/llvm/lib/Transforms/IPO/SampleProfileProbe.cpp
index 5ef3945041cbd..a62d76010f678 100644
--- a/llvm/lib/Transforms/IPO/SampleProfileProbe.cpp
+++ b/llvm/lib/Transforms/IPO/SampleProfileProbe.cpp
@@ -24,6 +24,7 @@
 #include "llvm/IR/IntrinsicInst.h"
 #include "llvm/IR/MDBuilder.h"
 #include "llvm/IR/Module.h"
+#include "llvm/IR/PassInstrumentation.h"
 #include "llvm/IR/PseudoProbe.h"
 #include "llvm/ProfileData/SampleProf.h"
 #include "llvm/Support/CRC.h"
@@ -85,26 +86,25 @@ bool PseudoProbeVerifier::shouldVerifyFunction(const Function *F) {
 void PseudoProbeVerifier::registerCallbacks(PassInstrumentationCallbacks &PIC) {
   if (VerifyPseudoProbe) {
     PIC.registerAfterPassCallback(
-        [this](StringRef P, const Any &IR, const PreservedAnalyses &) {
+        [this](StringRef P, IRUnitRef IR, const PreservedAnalyses &) {
           this->runAfterPass(P, IR);
         });
   }
 }
 
 // Callback to run after each transformation for the new pass manager.
-void PseudoProbeVerifier::runAfterPass(StringRef PassID, const Any &IR) {
+void PseudoProbeVerifier::runAfterPass(StringRef PassID, IRUnitRef IR) {
   std::string Banner =
       "\n*** Pseudo Probe Verification After " + PassID.str() + " ***\n";
   dbgs() << Banner;
-  if (const auto *const *M = llvm::any_cast<const Module *>(&IR))
-    runAfterPass(*M);
-  else if (const auto *const *F = llvm::any_cast<const Function *>(&IR))
-    runAfterPass(*F);
-  else if (const auto *const *C =
-               llvm::any_cast<const LazyCallGraph::SCC *>(&IR))
-    runAfterPass(*C);
-  else if (const auto *const *L = llvm::any_cast<const Loop *>(&IR))
-    runAfterPass(*L);
+  if (const auto *M = dyn_cast<Module>(IR))
+    runAfterPass(M);
+  else if (const auto *F = dyn_cast<Function>(IR))
+    runAfterPass(F);
+  else if (const auto *C = dyn_cast<LazyCallGraph::SCC>(IR))
+    runAfterPass(C);
+  else if (const auto *L = dyn_cast<Loop>(IR))
+    runAfterPass(L);
   else
     llvm_unreachable("Unknown IR unit");
 }

diff  --git a/llvm/lib/Transforms/Scalar/LoopPassManager.cpp b/llvm/lib/Transforms/Scalar/LoopPassManager.cpp
index de144da18d3ee..9d6d6b3f6d020 100644
--- a/llvm/lib/Transforms/Scalar/LoopPassManager.cpp
+++ b/llvm/lib/Transforms/Scalar/LoopPassManager.cpp
@@ -254,13 +254,10 @@ PreservedAnalyses FunctionToLoopPassAdaptor::run(Function &F,
 
 #ifndef NDEBUG
   PI.pushBeforeNonSkippedPassCallback([&LAR, &LI](StringRef PassID,
-                                                  const Any &IR) {
+                                                  IRUnitRef IR) {
     if (isSpecialPass(PassID, {"PassManager"}))
       return;
-    assert(llvm::any_cast<const Loop *>(&IR));
-    const Loop *const *LPtr = llvm::any_cast<const Loop *>(&IR);
-    const Loop *L = LPtr ? *LPtr : nullptr;
-    assert(L && "Loop should be valid for printing");
+    const Loop *L = cast<Loop>(IR);
 
     // Verify the loop structure and LCSSA form before visiting the loop.
     L->verifyLoop();

diff  --git a/llvm/lib/Transforms/Utils/Debugify.cpp b/llvm/lib/Transforms/Utils/Debugify.cpp
index 4e4412fd886f4..29666e121e88c 100644
--- a/llvm/lib/Transforms/Utils/Debugify.cpp
+++ b/llvm/lib/Transforms/Utils/Debugify.cpp
@@ -1134,32 +1134,31 @@ static bool isIgnoredPass(StringRef PassID) {
 void DebugifyEachInstrumentation::registerCallbacks(
     PassInstrumentationCallbacks &PIC, ModuleAnalysisManager &MAM) {
   PIC.registerBeforeNonSkippedPassCallback([this, &MAM](StringRef P,
-                                                        const Any &IR) {
+                                                        IRUnitRef IR) {
     if (isIgnoredPass(P))
       return;
     PreservedAnalyses PA;
     PA.preserveSet<CFGAnalyses>();
-    if (const auto *const *CF = llvm::any_cast<const Function *>(&IR)) {
-      Function &F = *const_cast<Function *>(*CF);
+    if (const auto *CF = dyn_cast<Function>(IR)) {
+      Function &F = *const_cast<Function *>(CF);
       applyDebugify(F, Mode, DebugInfoBeforePass, P);
       MAM.getResult<FunctionAnalysisManagerModuleProxy>(*F.getParent())
           .getManager()
           .invalidate(F, PA);
-    } else if (const auto *const *CM = llvm::any_cast<const Module *>(&IR)) {
-      Module &M = *const_cast<Module *>(*CM);
+    } else if (const auto *CM = dyn_cast<Module>(IR)) {
+      Module &M = *const_cast<Module *>(CM);
       applyDebugify(M, Mode, DebugInfoBeforePass, P);
       MAM.invalidate(M, PA);
     }
   });
   PIC.registerAfterPassCallback(
-      [this, &MAM](StringRef P, const Any &IR,
-                   const PreservedAnalyses &PassPA) {
+      [this, &MAM](StringRef P, IRUnitRef IR, const PreservedAnalyses &PassPA) {
         if (isIgnoredPass(P))
           return;
         PreservedAnalyses PA;
         PA.preserveSet<CFGAnalyses>();
-        if (const auto *const *CF = llvm::any_cast<const Function *>(&IR)) {
-          auto &F = *const_cast<Function *>(*CF);
+        if (const auto *CF = dyn_cast<Function>(IR)) {
+          auto &F = *const_cast<Function *>(CF);
           Module &M = *F.getParent();
           auto It = F.getIterator();
           if (Mode == DebugifyMode::SyntheticDebugInfo)
@@ -1174,9 +1173,8 @@ void DebugifyEachInstrumentation::registerCallbacks(
           MAM.getResult<FunctionAnalysisManagerModuleProxy>(*F.getParent())
               .getManager()
               .invalidate(F, PA);
-        } else if (const auto *const *CM =
-                       llvm::any_cast<const Module *>(&IR)) {
-          Module &M = *const_cast<Module *>(*CM);
+        } else if (const auto *CM = dyn_cast<Module>(IR)) {
+          Module &M = *const_cast<Module *>(CM);
           if (Mode == DebugifyMode::SyntheticDebugInfo)
             checkDebugifyMetadata(M, M.functions(), P, "CheckModuleDebugify",
                                   /*Strip=*/true, DIStatsMap);

diff  --git a/llvm/tools/llvm-reduce/deltas/RunIRPasses.cpp b/llvm/tools/llvm-reduce/deltas/RunIRPasses.cpp
index 3a506238ea7a3..631130bf3b124 100644
--- a/llvm/tools/llvm-reduce/deltas/RunIRPasses.cpp
+++ b/llvm/tools/llvm-reduce/deltas/RunIRPasses.cpp
@@ -32,7 +32,7 @@ void llvm::runIRPassesDeltaPass(Oracle &O, ReducerWorkItem &WorkItem) {
 
   PassInstrumentationCallbacks PIC;
   PIC.registerShouldRunOptionalPassCallback(
-      [&](StringRef, const Any &) { return !O.shouldKeep(); });
+      [&](StringRef, IRUnitRef) { return !O.shouldKeep(); });
   PassBuilder PB(nullptr, PipelineTuningOptions(), std::nullopt, &PIC);
 
   PB.registerModuleAnalyses(MAM);

diff  --git a/llvm/unittests/IR/DroppedVariableStatsIRTest.cpp b/llvm/unittests/IR/DroppedVariableStatsIRTest.cpp
index 03e6f429e14f8..1cb453b398d87 100644
--- a/llvm/unittests/IR/DroppedVariableStatsIRTest.cpp
+++ b/llvm/unittests/IR/DroppedVariableStatsIRTest.cpp
@@ -74,7 +74,7 @@ TEST(DroppedVariableStatsIR, BothDeleted) {
   ASSERT_TRUE(M);
 
   DroppedVariableStatsIR Stats(true);
-  Stats.runBeforePass("", llvm::Any(const_cast<const llvm::Module *>(M.get())));
+  Stats.runBeforePass("", *M);
 
   // This loop simulates an IR pass that drops debug information.
   for (auto &F : *M) {
@@ -85,8 +85,7 @@ TEST(DroppedVariableStatsIR, BothDeleted) {
     }
     break;
   }
-  Stats.runAfterPass("Test",
-                     llvm::Any(const_cast<const llvm::Module *>(M.get())));
+  Stats.runAfterPass("Test", *M);
   ASSERT_EQ(Stats.getPassDroppedVariables(), false);
 }
 
@@ -129,7 +128,7 @@ TEST(DroppedVariableStatsIR, DbgValLost) {
   ASSERT_TRUE(M);
 
   DroppedVariableStatsIR Stats(true);
-  Stats.runBeforePass("", llvm::Any(const_cast<const llvm::Module *>(M.get())));
+  Stats.runBeforePass("", *M);
 
   // This loop simulates an IR pass that drops debug information.
   for (auto &F : *M) {
@@ -139,8 +138,7 @@ TEST(DroppedVariableStatsIR, DbgValLost) {
     }
     break;
   }
-  Stats.runAfterPass("Test",
-                     llvm::Any(const_cast<const llvm::Module *>(M.get())));
+  Stats.runAfterPass("Test", *M);
   ASSERT_EQ(Stats.getPassDroppedVariables(), true);
 }
 
@@ -184,7 +182,7 @@ TEST(DroppedVariableStatsIR, UnrelatedScopes) {
   ASSERT_TRUE(M);
 
   DroppedVariableStatsIR Stats(true);
-  Stats.runBeforePass("", llvm::Any(const_cast<const llvm::Module *>(M.get())));
+  Stats.runBeforePass("", *M);
 
   // This loop simulates an IR pass that drops debug information.
   for (auto &F : *M) {
@@ -194,8 +192,7 @@ TEST(DroppedVariableStatsIR, UnrelatedScopes) {
     }
     break;
   }
-  Stats.runAfterPass("Test",
-                     llvm::Any(const_cast<const llvm::Module *>(M.get())));
+  Stats.runAfterPass("Test", *M);
   ASSERT_EQ(Stats.getPassDroppedVariables(), false);
 }
 
@@ -239,7 +236,7 @@ TEST(DroppedVariableStatsIR, ChildScopes) {
   ASSERT_TRUE(M);
 
   DroppedVariableStatsIR Stats(true);
-  Stats.runBeforePass("", llvm::Any(const_cast<const llvm::Module *>(M.get())));
+  Stats.runBeforePass("", *M);
 
   // This loop simulates an IR pass that drops debug information.
   for (auto &F : *M) {
@@ -249,8 +246,7 @@ TEST(DroppedVariableStatsIR, ChildScopes) {
     }
     break;
   }
-  Stats.runAfterPass("Test",
-                     llvm::Any(const_cast<const llvm::Module *>(M.get())));
+  Stats.runAfterPass("Test", *M);
   ASSERT_EQ(Stats.getPassDroppedVariables(), true);
 }
 
@@ -295,7 +291,7 @@ TEST(DroppedVariableStatsIR, InlinedAt) {
   ASSERT_TRUE(M);
 
   DroppedVariableStatsIR Stats(true);
-  Stats.runBeforePass("", llvm::Any(const_cast<const llvm::Module *>(M.get())));
+  Stats.runBeforePass("", *M);
 
   // This loop simulates an IR pass that drops debug information.
   for (auto &F : *M) {
@@ -305,8 +301,7 @@ TEST(DroppedVariableStatsIR, InlinedAt) {
     }
     break;
   }
-  Stats.runAfterPass("Test",
-                     llvm::Any(const_cast<const llvm::Module *>(M.get())));
+  Stats.runAfterPass("Test", *M);
   ASSERT_EQ(Stats.getPassDroppedVariables(), false);
 }
 
@@ -351,7 +346,7 @@ TEST(DroppedVariableStatsIR, InlinedAtShared) {
   ASSERT_TRUE(M);
 
   DroppedVariableStatsIR Stats(true);
-  Stats.runBeforePass("", llvm::Any(const_cast<const llvm::Module *>(M.get())));
+  Stats.runBeforePass("", *M);
 
   // This loop simulates an IR pass that drops debug information.
   for (auto &F : *M) {
@@ -361,8 +356,7 @@ TEST(DroppedVariableStatsIR, InlinedAtShared) {
     }
     break;
   }
-  Stats.runAfterPass("Test",
-                     llvm::Any(const_cast<const llvm::Module *>(M.get())));
+  Stats.runAfterPass("Test", *M);
   ASSERT_EQ(Stats.getPassDroppedVariables(), true);
 }
 
@@ -408,7 +402,7 @@ TEST(DroppedVariableStatsIR, InlinedAtChild) {
   ASSERT_TRUE(M);
 
   DroppedVariableStatsIR Stats(true);
-  Stats.runBeforePass("", llvm::Any(const_cast<const llvm::Module *>(M.get())));
+  Stats.runBeforePass("", *M);
 
   // This loop simulates an IR pass that drops debug information.
   for (auto &F : *M) {
@@ -418,8 +412,7 @@ TEST(DroppedVariableStatsIR, InlinedAtChild) {
     }
     break;
   }
-  Stats.runAfterPass("Test",
-                     llvm::Any(const_cast<const llvm::Module *>(M.get())));
+  Stats.runAfterPass("Test", *M);
   ASSERT_EQ(Stats.getPassDroppedVariables(), true);
 }
 

diff  --git a/llvm/unittests/IR/PassBuilderCallbacksTest.cpp b/llvm/unittests/IR/PassBuilderCallbacksTest.cpp
index cc07439f997cf..788e5296de520 100644
--- a/llvm/unittests/IR/PassBuilderCallbacksTest.cpp
+++ b/llvm/unittests/IR/PassBuilderCallbacksTest.cpp
@@ -10,7 +10,6 @@
 #include <functional>
 #include <gmock/gmock.h>
 #include <gtest/gtest.h>
-#include <llvm/ADT/Any.h>
 #include <llvm/Analysis/CGSCCPassManager.h>
 #include <llvm/Analysis/LoopAnalysisManager.h>
 #include <llvm/AsmParser/Parser.h>
@@ -282,7 +281,7 @@ static std::unique_ptr<Module> parseIR(LLVMContext &C, const char *IR) {
 }
 
 /// Helper for HasName matcher that returns getName both for IRUnit and
-/// for IRUnit pointer wrapper into llvm::Any (wrapped by PassInstrumentation).
+/// for IRUnit pointer wrapper into IRUnitRef (wrapped by PassInstrumentation).
 template <typename IRUnitT> std::string getName(const IRUnitT &IR) {
   return std::string(IR.getName());
 }
@@ -291,16 +290,15 @@ template <> std::string getName(const StringRef &name) {
   return std::string(name);
 }
 
-template <> std::string getName(const Any &WrappedIR) {
-  if (const auto *const *M = llvm::any_cast<const Module *>(&WrappedIR))
-    return (*M)->getName().str();
-  if (const auto *const *F = llvm::any_cast<const Function *>(&WrappedIR))
-    return (*F)->getName().str();
-  if (const auto *const *L = llvm::any_cast<const Loop *>(&WrappedIR))
-    return (*L)->getName().str();
-  if (const auto *const *C =
-          llvm::any_cast<const LazyCallGraph::SCC *>(&WrappedIR))
-    return (*C)->getName();
+template <> std::string getName(const IRUnitRef &WrappedIR) {
+  if (const auto *M = dyn_cast<Module>(WrappedIR))
+    return M->getName().str();
+  if (const auto *F = dyn_cast<Function>(WrappedIR))
+    return F->getName().str();
+  if (const auto *L = dyn_cast<Loop>(WrappedIR))
+    return L->getName().str();
+  if (const auto *C = dyn_cast<LazyCallGraph::SCC>(WrappedIR))
+    return C->getName();
   return "<UNKNOWN>";
 }
 /// Define a custom matcher for objects which support a 'getName' method.
@@ -334,46 +332,42 @@ struct MockPassInstrumentationCallbacks {
   MockPassInstrumentationCallbacks() {
     ON_CALL(*this, runBeforePass(_, _)).WillByDefault(Return(true));
   }
-  MOCK_METHOD2(runBeforePass, bool(StringRef PassID, const llvm::Any &));
-  MOCK_METHOD2(runBeforeSkippedPass, void(StringRef PassID, const llvm::Any &));
-  MOCK_METHOD2(runBeforeNonSkippedPass,
-               void(StringRef PassID, const llvm::Any &));
-  MOCK_METHOD3(runAfterPass, void(StringRef PassID, const llvm::Any &,
-                                  const PreservedAnalyses &PA));
+  MOCK_METHOD2(runBeforePass, bool(StringRef PassID, IRUnitRef));
+  MOCK_METHOD2(runBeforeSkippedPass, void(StringRef PassID, IRUnitRef));
+  MOCK_METHOD2(runBeforeNonSkippedPass, void(StringRef PassID, IRUnitRef));
+  MOCK_METHOD3(runAfterPass,
+               void(StringRef PassID, IRUnitRef, const PreservedAnalyses &PA));
   MOCK_METHOD2(runAfterPassInvalidated,
                void(StringRef PassID, const PreservedAnalyses &PA));
-  MOCK_METHOD2(runBeforeAnalysis, void(StringRef PassID, const llvm::Any &));
-  MOCK_METHOD2(runAfterAnalysis, void(StringRef PassID, const llvm::Any &));
+  MOCK_METHOD2(runBeforeAnalysis, void(StringRef PassID, IRUnitRef));
+  MOCK_METHOD2(runAfterAnalysis, void(StringRef PassID, IRUnitRef));
 
   void registerPassInstrumentation() {
     Callbacks.registerShouldRunOptionalPassCallback(
-        [this](StringRef P, const llvm::Any &IR) {
+        [this](StringRef P, IRUnitRef IR) {
           return this->runBeforePass(P, IR);
         });
     Callbacks.registerBeforeSkippedPassCallback(
-        [this](StringRef P, const llvm::Any &IR) {
+        [this](StringRef P, IRUnitRef IR) {
           this->runBeforeSkippedPass(P, IR);
         });
     Callbacks.registerBeforeNonSkippedPassCallback(
-        [this](StringRef P, const llvm::Any &IR) {
+        [this](StringRef P, IRUnitRef IR) {
           this->runBeforeNonSkippedPass(P, IR);
         });
     Callbacks.registerAfterPassCallback(
-        [this](StringRef P, const llvm::Any &IR, const PreservedAnalyses &PA) {
+        [this](StringRef P, IRUnitRef IR, const PreservedAnalyses &PA) {
           this->runAfterPass(P, IR, PA);
         });
     Callbacks.registerAfterPassInvalidatedCallback(
         [this](StringRef P, const PreservedAnalyses &PA) {
           this->runAfterPassInvalidated(P, PA);
         });
-    Callbacks.registerBeforeAnalysisCallback(
-        [this](StringRef P, const llvm::Any &IR) {
-          return this->runBeforeAnalysis(P, IR);
-        });
+    Callbacks.registerBeforeAnalysisCallback([this](StringRef P, IRUnitRef IR) {
+      return this->runBeforeAnalysis(P, IR);
+    });
     Callbacks.registerAfterAnalysisCallback(
-        [this](StringRef P, const llvm::Any &IR) {
-          this->runAfterAnalysis(P, IR);
-        });
+        [this](StringRef P, IRUnitRef IR) { this->runAfterAnalysis(P, IR); });
   }
 
   void ignoreNonMockPassInstrumentation(StringRef IRName) {


        


More information about the llvm-commits mailing list