[clang] [llvm] Make MMIWP not have ownership over MMI + Remove Move Constructor of MMI + Make MMI Only Use and Externally-Created MCContext (PR #105541)

Matin Raayai via cfe-commits cfe-commits at lists.llvm.org
Wed Aug 21 08:55:07 PDT 2024


https://github.com/matinraayai created https://github.com/llvm/llvm-project/pull/105541

This PR makes the following changes, addressing issues raised in #104834 and #98770:
1. MMIWP behaves like the new PM's analysis Pass; It only takes a reference to an externally created MMI.
2. Removed the move constructor; Disallowed copy construction and copy assignment.
3. MMI does not create its own MCContext, and take a reference to an externally-created context.

As expected, this change touched upon a lot of places in the LLVM monorepo; But I wanted to point out some breaking ones:

1. The `TargetMachine` interface functions `addPassesToEmitFile` and `addPassesToEmitMC` now require a reference to an MMI; This IMO breaks the abstraction of the `TargetMachine`, since an `MMI` requires a `LLVMTargetMachine`, and if you have a `TargetMachine` you should do the dreaded casting to `LLVMTargetMachine` in order to create it. Now I created a factory method for MMIs in the `TargetMachine` interface to remedy this issue, but I still don't like it since again, it is only implemented for `LLVMTargetMachine`.
2. Enforcing an externally created context for every user of MMI requires explicit reseting of the MCContext if it is reused; This can be seen in llc and MCJIt, and I think must be documented explicitly.
4. Some places in the code only created an MMI just to get an MCContext; I've replaced them with a manually constructed MCContext but I think it can be simplified to having a factory method for MCContext in the `TargetMachine` interface.

For now this PR is a WIP; The first two changes are necessary, and will have to be done sometime in the future as a part of the migration effort to the new PM; The 3rd change (only taking external MCContext) makes MMI's code cleaner, but might break code in other places where it relies on the MMIWP implicitly reseting its managed context. It might be possible to break this PR down to two parts instead if it proves to be challenging to merge.

CC: @arsenm @weiweichen 

>From 4030c78148a2cb9b584038bd2ce522906b710f7e Mon Sep 17 00:00:00 2001
From: matinraayai <30674652+matinraayai at users.noreply.github.com>
Date: Tue, 20 Aug 2024 14:22:11 -0400
Subject: [PATCH 1/2] Made MMI only use external MCContext.

---
 llvm/include/llvm/CodeGen/MachineModuleInfo.h | 28 +++++-------
 llvm/lib/CodeGen/MachineModuleInfo.cpp        | 45 +++----------------
 2 files changed, 18 insertions(+), 55 deletions(-)

diff --git a/llvm/include/llvm/CodeGen/MachineModuleInfo.h b/llvm/include/llvm/CodeGen/MachineModuleInfo.h
index 310cc4b2abb772..3fb0979ec20990 100644
--- a/llvm/include/llvm/CodeGen/MachineModuleInfo.h
+++ b/llvm/include/llvm/CodeGen/MachineModuleInfo.h
@@ -83,13 +83,11 @@ class MachineModuleInfo {
   friend class MachineModuleInfoWrapperPass;
   friend class MachineModuleAnalysis;
 
+  /// This is the TargetMachine used for the entire code generator.
   const LLVMTargetMachine &TM;
 
   /// This is the MCContext used for the entire code generator.
-  MCContext Context;
-  // This is an external context, that if assigned, will be used instead of the
-  // internal context.
-  MCContext *ExternalContext = nullptr;
+  MCContext &Context;
 
   /// This is the LLVM Module being worked on.
   const Module *TheModule = nullptr;
@@ -106,15 +104,15 @@ class MachineModuleInfo {
   const Function *LastRequest = nullptr; ///< Used for shortcut/cache.
   MachineFunction *LastResult = nullptr; ///< Used for shortcut/cache.
 
-  MachineModuleInfo &operator=(MachineModuleInfo &&MMII) = delete;
-
 public:
-  explicit MachineModuleInfo(const LLVMTargetMachine *TM = nullptr);
+  explicit MachineModuleInfo(const LLVMTargetMachine &TM,
+                             MCContext &Context);
 
-  explicit MachineModuleInfo(const LLVMTargetMachine *TM,
-                             MCContext *ExtContext);
+  /// Deleted copy constructor
+  MachineModuleInfo(MachineModuleInfo &MMI) = delete;
 
-  MachineModuleInfo(MachineModuleInfo &&MMII);
+  /// Deleted copy assignment operator
+  MachineModuleInfo &operator=(MachineModuleInfo &MMII) = delete;
 
   ~MachineModuleInfo();
 
@@ -124,10 +122,10 @@ class MachineModuleInfo {
   const LLVMTargetMachine &getTarget() const { return TM; }
 
   const MCContext &getContext() const {
-    return ExternalContext ? *ExternalContext : Context;
+    return Context;
   }
   MCContext &getContext() {
-    return ExternalContext ? *ExternalContext : Context;
+    return Context;
   }
 
   const Module *getModule() const { return TheModule; }
@@ -169,14 +167,12 @@ class MachineModuleInfo {
 }; // End class MachineModuleInfo
 
 class MachineModuleInfoWrapperPass : public ImmutablePass {
-  MachineModuleInfo MMI;
+  MachineModuleInfo &MMI;
 
 public:
   static char ID; // Pass identification, replacement for typeid
-  explicit MachineModuleInfoWrapperPass(const LLVMTargetMachine *TM = nullptr);
 
-  explicit MachineModuleInfoWrapperPass(const LLVMTargetMachine *TM,
-                                        MCContext *ExtContext);
+  explicit MachineModuleInfoWrapperPass(MachineModuleInfo &MMI);
 
   // Initialization and Finalization
   bool doInitialization(Module &) override;
diff --git a/llvm/lib/CodeGen/MachineModuleInfo.cpp b/llvm/lib/CodeGen/MachineModuleInfo.cpp
index c66495969b4e67..55ef4916cd0101 100644
--- a/llvm/lib/CodeGen/MachineModuleInfo.cpp
+++ b/llvm/lib/CodeGen/MachineModuleInfo.cpp
@@ -30,39 +30,14 @@ void MachineModuleInfo::initialize() {
 }
 
 void MachineModuleInfo::finalize() {
-  Context.reset();
-  // We don't clear the ExternalContext.
-
   delete ObjFileMMI;
   ObjFileMMI = nullptr;
 }
 
-MachineModuleInfo::MachineModuleInfo(MachineModuleInfo &&MMI)
-    : TM(std::move(MMI.TM)),
-      Context(TM.getTargetTriple(), TM.getMCAsmInfo(), TM.getMCRegisterInfo(),
-              TM.getMCSubtargetInfo(), nullptr, &TM.Options.MCOptions, false),
-      MachineFunctions(std::move(MMI.MachineFunctions)) {
+MachineModuleInfo::MachineModuleInfo(const LLVMTargetMachine &TM,
+                                     MCContext &Context)
+    : TM(TM), Context(Context) {
   Context.setObjectFileInfo(TM.getObjFileLowering());
-  ObjFileMMI = MMI.ObjFileMMI;
-  ExternalContext = MMI.ExternalContext;
-  TheModule = MMI.TheModule;
-}
-
-MachineModuleInfo::MachineModuleInfo(const LLVMTargetMachine *TM)
-    : TM(*TM), Context(TM->getTargetTriple(), TM->getMCAsmInfo(),
-                       TM->getMCRegisterInfo(), TM->getMCSubtargetInfo(),
-                       nullptr, &TM->Options.MCOptions, false) {
-  Context.setObjectFileInfo(TM->getObjFileLowering());
-  initialize();
-}
-
-MachineModuleInfo::MachineModuleInfo(const LLVMTargetMachine *TM,
-                                     MCContext *ExtContext)
-    : TM(*TM), Context(TM->getTargetTriple(), TM->getMCAsmInfo(),
-                       TM->getMCRegisterInfo(), TM->getMCSubtargetInfo(),
-                       nullptr, &TM->Options.MCOptions, false),
-      ExternalContext(ExtContext) {
-  Context.setObjectFileInfo(TM->getObjFileLowering());
   initialize();
 }
 
@@ -137,9 +112,7 @@ class FreeMachineFunction : public FunctionPass {
     return true;
   }
 
-  StringRef getPassName() const override {
-    return "Free MachineFunction";
-  }
+  StringRef getPassName() const override { return "Free MachineFunction"; }
 };
 
 } // end anonymous namespace
@@ -151,14 +124,8 @@ FunctionPass *llvm::createFreeMachineFunctionPass() {
 }
 
 MachineModuleInfoWrapperPass::MachineModuleInfoWrapperPass(
-    const LLVMTargetMachine *TM)
-    : ImmutablePass(ID), MMI(TM) {
-  initializeMachineModuleInfoWrapperPassPass(*PassRegistry::getPassRegistry());
-}
-
-MachineModuleInfoWrapperPass::MachineModuleInfoWrapperPass(
-    const LLVMTargetMachine *TM, MCContext *ExtContext)
-    : ImmutablePass(ID), MMI(TM, ExtContext) {
+    MachineModuleInfo &MMI)
+    : ImmutablePass(ID), MMI(MMI) {
   initializeMachineModuleInfoWrapperPassPass(*PassRegistry::getPassRegistry());
 }
 

>From 923978640a76a33d77ab2c794953479efa86b73c Mon Sep 17 00:00:00 2001
From: matinraayai <30674652+matinraayai at users.noreply.github.com>
Date: Wed, 21 Aug 2024 03:13:30 -0400
Subject: [PATCH 2/2] Migrated to the new MMI constructor + external MC
 context.

---
 clang/lib/CodeGen/BackendUtil.cpp             | 16 +++++-
 clang/lib/Interpreter/DeviceOffload.cpp       | 11 +++-
 .../ClangLinkerWrapper.cpp                    |  8 ++-
 llvm/include/llvm/Target/TargetMachine.h      | 57 ++++++++++---------
 llvm/lib/CodeGen/LLVMTargetMachine.cpp        | 27 +++++----
 llvm/lib/ExecutionEngine/MCJIT/MCJIT.cpp      | 15 +++--
 llvm/lib/ExecutionEngine/MCJIT/MCJIT.h        |  3 +-
 llvm/lib/ExecutionEngine/Orc/CompileUtils.cpp |  8 ++-
 llvm/lib/LTO/LTOBackend.cpp                   | 10 +++-
 llvm/lib/LTO/ThinLTOCodeGenerator.cpp         |  8 ++-
 llvm/lib/Target/NVPTX/NVPTXTargetMachine.h    |  4 +-
 llvm/lib/Target/TargetMachineC.cpp            | 10 +++-
 llvm/tools/llc/NewPMDriver.cpp                |  6 +-
 llvm/tools/llc/llc.cpp                        | 11 +++-
 llvm/tools/llvm-exegesis/lib/Assembler.cpp    | 14 ++++-
 .../llvm-isel-fuzzer/llvm-isel-fuzzer.cpp     |  8 ++-
 llvm/tools/llvm-reduce/ReducerWorkItem.cpp    | 14 ++++-
 llvm/tools/llvm-reduce/ReducerWorkItem.h      |  5 +-
 llvm/tools/llvm-reduce/TestRunner.cpp         |  6 +-
 llvm/tools/llvm-reduce/TestRunner.h           |  6 +-
 llvm/tools/llvm-reduce/deltas/Delta.cpp       | 11 ++--
 llvm/tools/llvm-reduce/llvm-reduce.cpp        | 10 ++--
 .../CodeGen/AArch64SelectionDAGTest.cpp       |  8 ++-
 llvm/unittests/CodeGen/AMDGPUMetadataTest.cpp |  7 ++-
 .../unittests/CodeGen/AsmPrinterDwarfTest.cpp | 12 +++-
 .../CodeGen/GlobalISel/GISelMITest.h          | 14 +++--
 llvm/unittests/CodeGen/InstrRefLDVTest.cpp    |  8 ++-
 llvm/unittests/CodeGen/MFCommon.inc           |  6 +-
 .../CodeGen/MachineDomTreeUpdaterTest.cpp     |  8 ++-
 llvm/unittests/CodeGen/PassManagerTest.cpp    | 12 +++-
 .../SelectionDAGAddressAnalysisTest.cpp       |  7 ++-
 .../CodeGen/SelectionDAGPatternMatchTest.cpp  |  9 ++-
 llvm/unittests/MI/LiveIntervalTest.cpp        | 27 +++++----
 llvm/unittests/MIR/MachineMetadata.cpp        | 31 +++++++---
 llvm/unittests/Target/AArch64/InstSizes.cpp   |  5 +-
 .../AMDGPU/ExecMayBeModifiedBeforeAnyUse.cpp  |  6 +-
 llvm/unittests/Target/AMDGPU/PALMetadata.cpp  |  8 ++-
 llvm/unittests/Target/ARM/InstSizes.cpp       |  5 +-
 llvm/unittests/Target/LoongArch/InstSizes.cpp |  6 +-
 .../Target/RISCV/RISCVInstrInfoTest.cpp       |  6 +-
 .../WebAssemblyExceptionInfoTest.cpp          | 10 +++-
 .../Target/X86/MachineSizeOptsTest.cpp        |  6 +-
 .../X86/SnippetRepetitorTest.cpp              |  6 +-
 43 files changed, 345 insertions(+), 130 deletions(-)

diff --git a/clang/lib/CodeGen/BackendUtil.cpp b/clang/lib/CodeGen/BackendUtil.cpp
index 34c08818dbb9ad..7e5ebe34dc98ba 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -26,6 +26,7 @@
 #include "llvm/Bitcode/BitcodeReader.h"
 #include "llvm/Bitcode/BitcodeWriter.h"
 #include "llvm/Bitcode/BitcodeWriterPass.h"
+#include "llvm/CodeGen/MachineModuleInfo.h"
 #include "llvm/CodeGen/RegAllocRegistry.h"
 #include "llvm/CodeGen/SchedulerRegistry.h"
 #include "llvm/CodeGen/TargetSubtargetInfo.h"
@@ -167,7 +168,8 @@ class EmitAssemblyHelper {
   ///
   /// \return True on success.
   bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
-                     raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
+                     MachineModuleInfo &MMI, raw_pwrite_stream &OS,
+                     raw_pwrite_stream *DwoOS);
 
   std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
     std::error_code EC;
@@ -577,6 +579,7 @@ void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
 
 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
                                        BackendAction Action,
+                                       MachineModuleInfo &MMI,
                                        raw_pwrite_stream &OS,
                                        raw_pwrite_stream *DwoOS) {
   // Add LibraryInfo.
@@ -588,7 +591,7 @@ bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
   // this also adds codegenerator level optimization passes.
   CodeGenFileType CGFT = getCodeGenFileType(Action);
 
-  if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
+  if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT, MMI,
                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
     Diags.Report(diag::err_fe_unable_to_interface_with_target);
     return false;
@@ -1116,6 +1119,8 @@ void EmitAssemblyHelper::RunCodegenPipeline(
   // does not work with the codegen pipeline.
   // FIXME: make the new PM work with the codegen pipeline.
   legacy::PassManager CodeGenPasses;
+  std::unique_ptr<llvm::MCContext> MCCtx;
+  std::unique_ptr<llvm::MachineModuleInfo> MMI;
 
   // Append any output we need to the pass manager.
   switch (Action) {
@@ -1129,7 +1134,12 @@ void EmitAssemblyHelper::RunCodegenPipeline(
       if (!DwoOS)
         return;
     }
-    if (!AddEmitPasses(CodeGenPasses, Action, *OS,
+    MCCtx = std::make_unique<MCContext>(
+        TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
+        TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
+
+    MMI = TM->createMachineModuleInfo(*MCCtx);
+    if (!AddEmitPasses(CodeGenPasses, Action, *MMI, *OS,
                        DwoOS ? &DwoOS->os() : nullptr))
       // FIXME: Should we handle this error differently?
       return;
diff --git a/clang/lib/Interpreter/DeviceOffload.cpp b/clang/lib/Interpreter/DeviceOffload.cpp
index 07c9e3005e5fd3..29a94c372c4df8 100644
--- a/clang/lib/Interpreter/DeviceOffload.cpp
+++ b/clang/lib/Interpreter/DeviceOffload.cpp
@@ -16,8 +16,10 @@
 #include "clang/CodeGen/ModuleBuilder.h"
 #include "clang/Frontend/CompilerInstance.h"
 
+#include "llvm/CodeGen/MachineModuleInfo.h"
 #include "llvm/IR/LegacyPassManager.h"
 #include "llvm/IR/Module.h"
+#include "llvm/MC/MCContext.h"
 #include "llvm/MC/TargetRegistry.h"
 #include "llvm/Target/TargetMachine.h"
 
@@ -88,8 +90,13 @@ llvm::Expected<llvm::StringRef> IncrementalCUDADeviceParser::GeneratePTX() {
   llvm::raw_svector_ostream dest(PTXCode);
 
   llvm::legacy::PassManager PM;
-  if (TargetMachine->addPassesToEmitFile(PM, dest, nullptr,
-                                         llvm::CodeGenFileType::AssemblyFile)) {
+  llvm::MCContext MCCtx(
+      TargetMachine->getTargetTriple(), TargetMachine->getMCAsmInfo(),
+      TargetMachine->getMCRegisterInfo(), TargetMachine->getMCSubtargetInfo(),
+      nullptr, &TargetMachine->Options.MCOptions, false);
+  auto MMI = TargetMachine->createMachineModuleInfo(MCCtx);
+  if (TargetMachine->addPassesToEmitFile(
+          PM, dest, nullptr, llvm::CodeGenFileType::AssemblyFile, *MMI)) {
     return llvm::make_error<llvm::StringError>(
         "NVPTX backend cannot produce PTX code.",
         llvm::inconvertibleErrorCode());
diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
index 9fea1fdcd5fb46..797f7b44560400 100644
--- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -20,6 +20,7 @@
 #include "llvm/BinaryFormat/Magic.h"
 #include "llvm/Bitcode/BitcodeWriter.h"
 #include "llvm/CodeGen/CommandFlags.h"
+#include "llvm/CodeGen/MachineModuleInfo.h"
 #include "llvm/Frontend/Offloading/OffloadWrapper.h"
 #include "llvm/Frontend/Offloading/Utility.h"
 #include "llvm/IR/Constants.h"
@@ -27,6 +28,7 @@
 #include "llvm/IR/Module.h"
 #include "llvm/IRReader/IRReader.h"
 #include "llvm/LTO/LTO.h"
+#include "llvm/MC/MCContext.h"
 #include "llvm/MC/TargetRegistry.h"
 #include "llvm/Object/Archive.h"
 #include "llvm/Object/ArchiveWriter.h"
@@ -1051,10 +1053,14 @@ Expected<StringRef> compileModule(Module &M, OffloadKind Kind) {
   auto OS = std::make_unique<llvm::raw_fd_ostream>(FD, true);
 
   legacy::PassManager CodeGenPasses;
+  MCContext MCCtx(
+      TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
+      TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
+  auto MMI = TM->createMachineModuleInfo(MCCtx);
   TargetLibraryInfoImpl TLII(Triple(M.getTargetTriple()));
   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(TLII));
   if (TM->addPassesToEmitFile(CodeGenPasses, *OS, nullptr,
-                              CodeGenFileType::ObjectFile))
+                              CodeGenFileType::ObjectFile, *MMI))
     return createStringError("Failed to execute host backend");
   CodeGenPasses.run(M);
 
diff --git a/llvm/include/llvm/Target/TargetMachine.h b/llvm/include/llvm/Target/TargetMachine.h
index c3e9d41315f617..2574fb80a5702d 100644
--- a/llvm/include/llvm/Target/TargetMachine.h
+++ b/llvm/include/llvm/Target/TargetMachine.h
@@ -34,7 +34,7 @@ using ModulePassManager = PassManager<Module>;
 
 class Function;
 class GlobalValue;
-class MachineModuleInfoWrapperPass;
+class MachineModuleInfo;
 class Mangler;
 class MCAsmInfo;
 class MCContext;
@@ -375,27 +375,27 @@ class TargetMachine {
   /// with the new pass manager. Only affects the "default" AAManager.
   virtual void registerDefaultAliasAnalyses(AAManager &) {}
 
+  /// Creates a new instance of \c MachineModuleInfo to be used for code
+  /// generation for this \c TargetMachine
+  virtual std::unique_ptr<MachineModuleInfo>
+  createMachineModuleInfo(MCContext &Ctx) const = 0;
+
   /// Add passes to the specified pass manager to get the specified file
-  /// emitted.  Typically this will involve several steps of code generation.
+  /// emitted. Typically this will involve several steps of code generation.
   /// This method should return true if emission of this file type is not
   /// supported, or false on success.
-  /// \p MMIWP is an optional parameter that, if set to non-nullptr,
-  /// will be used to set the MachineModuloInfo for this PM.
-  virtual bool
-  addPassesToEmitFile(PassManagerBase &, raw_pwrite_stream &,
-                      raw_pwrite_stream *, CodeGenFileType,
-                      bool /*DisableVerify*/ = true,
-                      MachineModuleInfoWrapperPass *MMIWP = nullptr) {
+  /// \p MMI must be created externally before being passed to this function
+  virtual bool addPassesToEmitFile(PassManagerBase &, raw_pwrite_stream &,
+                                   raw_pwrite_stream *, CodeGenFileType,
+                                   MachineModuleInfo &MMI,
+                                   bool /*DisableVerify*/ = true) {
     return true;
   }
 
   /// Add passes to the specified pass manager to get machine code emitted with
-  /// the MCJIT. This method returns true if machine code is not supported. It
-  /// fills the MCContext Ctx pointer which can be used to build custom
-  /// MCStreamer.
-  ///
-  virtual bool addPassesToEmitMC(PassManagerBase &, MCContext *&,
-                                 raw_pwrite_stream &,
+  /// the MCJIT. This method returns true if machine code is not supported.
+  virtual bool addPassesToEmitMC(PassManagerBase &, raw_pwrite_stream &,
+                                 MachineModuleInfo &,
                                  bool /*DisableVerify*/ = true) {
     return true;
   }
@@ -459,15 +459,18 @@ class LLVMTargetMachine : public TargetMachine {
   /// for generating a pipeline of CodeGen passes.
   virtual TargetPassConfig *createPassConfig(PassManagerBase &PM);
 
+  /// Creates a new instance of \c MachineModuleInfo to be used for code
+  /// generation for this \c TargetMachine
+  virtual std::unique_ptr<MachineModuleInfo>
+  createMachineModuleInfo(MCContext &Ctx) const override;
+
   /// Add passes to the specified pass manager to get the specified file
-  /// emitted.  Typically this will involve several steps of code generation.
-  /// \p MMIWP is an optional parameter that, if set to non-nullptr,
-  /// will be used to set the MachineModuloInfo for this PM.
-  bool
-  addPassesToEmitFile(PassManagerBase &PM, raw_pwrite_stream &Out,
-                      raw_pwrite_stream *DwoOut, CodeGenFileType FileType,
-                      bool DisableVerify = true,
-                      MachineModuleInfoWrapperPass *MMIWP = nullptr) override;
+  /// emitted. Typically this will involve several steps of code generation.
+  /// \p MMI must be created externally before being passed to this function
+  bool addPassesToEmitFile(PassManagerBase &PM, raw_pwrite_stream &Out,
+                           raw_pwrite_stream *DwoOut, CodeGenFileType FileType,
+                           MachineModuleInfo &MMI,
+                           bool DisableVerify = true) override;
 
   virtual Error buildCodeGenPipeline(ModulePassManager &, raw_pwrite_stream &,
                                      raw_pwrite_stream *, CodeGenFileType,
@@ -478,11 +481,9 @@ class LLVMTargetMachine : public TargetMachine {
   }
 
   /// Add passes to the specified pass manager to get machine code emitted with
-  /// the MCJIT. This method returns true if machine code is not supported. It
-  /// fills the MCContext Ctx pointer which can be used to build custom
-  /// MCStreamer.
-  bool addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx,
-                         raw_pwrite_stream &Out,
+  /// the MCJIT. This method returns true if machine code is not supported.
+  bool addPassesToEmitMC(PassManagerBase &PM, raw_pwrite_stream &Out,
+                         MachineModuleInfo &MMI,
                          bool DisableVerify = true) override;
 
   /// Returns true if the target is expected to pass all machine verifier
diff --git a/llvm/lib/CodeGen/LLVMTargetMachine.cpp b/llvm/lib/CodeGen/LLVMTargetMachine.cpp
index d0dfafeaef561f..1236c05328fff9 100644
--- a/llvm/lib/CodeGen/LLVMTargetMachine.cpp
+++ b/llvm/lib/CodeGen/LLVMTargetMachine.cpp
@@ -206,13 +206,16 @@ Expected<std::unique_ptr<MCStreamer>> LLVMTargetMachine::createMCStreamer(
   return std::move(AsmStreamer);
 }
 
+std::unique_ptr<MachineModuleInfo>
+LLVMTargetMachine::createMachineModuleInfo(MCContext &Ctx) const {
+  return std::make_unique<MachineModuleInfo>(*this, Ctx);
+}
+
 bool LLVMTargetMachine::addPassesToEmitFile(
     PassManagerBase &PM, raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut,
-    CodeGenFileType FileType, bool DisableVerify,
-    MachineModuleInfoWrapperPass *MMIWP) {
+    CodeGenFileType FileType, MachineModuleInfo &MMI, bool DisableVerify) {
   // Add common CodeGen passes.
-  if (!MMIWP)
-    MMIWP = new MachineModuleInfoWrapperPass(this);
+  auto *MMIWP = new MachineModuleInfoWrapperPass(MMI);
   TargetPassConfig *PassConfig =
       addPassesToGenerateCode(*this, PM, DisableVerify, *MMIWP);
   if (!PassConfig)
@@ -233,14 +236,14 @@ bool LLVMTargetMachine::addPassesToEmitFile(
 
 /// addPassesToEmitMC - Add passes to the specified pass manager to get
 /// machine code emitted with the MCJIT. This method returns true if machine
-/// code is not supported. It fills the MCContext Ctx pointer which can be
-/// used to build custom MCStreamer.
-///
-bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx,
+/// code is not supported. It uses the MCContext Ctx of \p MMI  so that it
+/// can be used to build custom MCStreamer.
+bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM,
                                           raw_pwrite_stream &Out,
+                                          MachineModuleInfo &MMI,
                                           bool DisableVerify) {
   // Add common CodeGen passes.
-  MachineModuleInfoWrapperPass *MMIWP = new MachineModuleInfoWrapperPass(this);
+  MachineModuleInfoWrapperPass *MMIWP = new MachineModuleInfoWrapperPass(MMI);
   TargetPassConfig *PassConfig =
       addPassesToGenerateCode(*this, PM, DisableVerify, *MMIWP);
   if (!PassConfig)
@@ -248,7 +251,7 @@ bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx,
   assert(TargetPassConfig::willCompleteCodeGenPipeline() &&
          "Cannot emit MC with limited codegen pipeline");
 
-  Ctx = &MMIWP->getMMI().getContext();
+  auto &Ctx = MMI.getContext();
   // libunwind is unable to load compact unwind dynamically, so we must generate
   // DWARF unwind info for the JIT.
   Options.MCOptions.EmitDwarfUnwind = EmitDwarfUnwindType::Always;
@@ -258,7 +261,7 @@ bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx,
   const MCSubtargetInfo &STI = *getMCSubtargetInfo();
   const MCRegisterInfo &MRI = *getMCRegisterInfo();
   std::unique_ptr<MCCodeEmitter> MCE(
-      getTarget().createMCCodeEmitter(*getMCInstrInfo(), *Ctx));
+      getTarget().createMCCodeEmitter(*getMCInstrInfo(), Ctx));
   MCAsmBackend *MAB =
       getTarget().createMCAsmBackend(STI, MRI, Options.MCOptions);
   if (!MCE || !MAB)
@@ -266,7 +269,7 @@ bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx,
 
   const Triple &T = getTargetTriple();
   std::unique_ptr<MCStreamer> AsmStreamer(getTarget().createMCObjectStreamer(
-      T, *Ctx, std::unique_ptr<MCAsmBackend>(MAB), MAB->createObjectWriter(Out),
+      T, Ctx, std::unique_ptr<MCAsmBackend>(MAB), MAB->createObjectWriter(Out),
       std::move(MCE), STI));
 
   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
diff --git a/llvm/lib/ExecutionEngine/MCJIT/MCJIT.cpp b/llvm/lib/ExecutionEngine/MCJIT/MCJIT.cpp
index 0d7a51bfe73753..fc9f09c3d3064c 100644
--- a/llvm/lib/ExecutionEngine/MCJIT/MCJIT.cpp
+++ b/llvm/lib/ExecutionEngine/MCJIT/MCJIT.cpp
@@ -8,6 +8,7 @@
 
 #include "MCJIT.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/CodeGen/MachineModuleInfo.h"
 #include "llvm/ExecutionEngine/GenericValue.h"
 #include "llvm/ExecutionEngine/JITEventListener.h"
 #include "llvm/ExecutionEngine/MCJIT.h"
@@ -67,9 +68,11 @@ MCJIT::MCJIT(std::unique_ptr<Module> M, std::unique_ptr<TargetMachine> TM,
              std::shared_ptr<MCJITMemoryManager> MemMgr,
              std::shared_ptr<LegacyJITSymbolResolver> Resolver)
     : ExecutionEngine(TM->createDataLayout(), std::move(M)), TM(std::move(TM)),
-      Ctx(nullptr), MemMgr(std::move(MemMgr)),
-      Resolver(*this, std::move(Resolver)), Dyld(*this->MemMgr, this->Resolver),
-      ObjCache(nullptr) {
+      MCCtx(this->TM->getTargetTriple(), this->TM->getMCAsmInfo(),
+            this->TM->getMCRegisterInfo(), this->TM->getMCSubtargetInfo(),
+            nullptr, &this->TM->Options.MCOptions, false),
+      MemMgr(std::move(MemMgr)), Resolver(*this, std::move(Resolver)),
+      Dyld(*this->MemMgr, this->Resolver), ObjCache(nullptr) {
   // FIXME: We are managing our modules, so we do not want the base class
   // ExecutionEngine to manage them as well. To avoid double destruction
   // of the first (and only) module added in ExecutionEngine constructor
@@ -162,9 +165,13 @@ std::unique_ptr<MemoryBuffer> MCJIT::emitObject(Module *M) {
   SmallVector<char, 4096> ObjBufferSV;
   raw_svector_ostream ObjStream(ObjBufferSV);
 
+  // Reset MCContext and create a MachineModuleInfo for code generation
+  MCCtx.reset();
+  auto MMI = TM->createMachineModuleInfo(MCCtx);
+
   // Turn the machine code intermediate representation into bytes in memory
   // that may be executed.
-  if (TM->addPassesToEmitMC(PM, Ctx, ObjStream, !getVerifyModules()))
+  if (TM->addPassesToEmitMC(PM, ObjStream, *MMI, !getVerifyModules()))
     report_fatal_error("Target does not support MC emission!");
 
   // Initialize passes.
diff --git a/llvm/lib/ExecutionEngine/MCJIT/MCJIT.h b/llvm/lib/ExecutionEngine/MCJIT/MCJIT.h
index f6c4cdbb8c91a9..0393ae6d08cc69 100644
--- a/llvm/lib/ExecutionEngine/MCJIT/MCJIT.h
+++ b/llvm/lib/ExecutionEngine/MCJIT/MCJIT.h
@@ -14,6 +14,7 @@
 #include "llvm/ExecutionEngine/ExecutionEngine.h"
 #include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
 #include "llvm/ExecutionEngine/RuntimeDyld.h"
+#include "llvm/MC/MCContext.h"
 
 namespace llvm {
 class MCJIT;
@@ -169,7 +170,7 @@ class MCJIT : public ExecutionEngine {
   };
 
   std::unique_ptr<TargetMachine> TM;
-  MCContext *Ctx;
+  MCContext MCCtx;
   std::shared_ptr<MCJITMemoryManager> MemMgr;
   LinkingSymbolResolver Resolver;
   RuntimeDyld Dyld;
diff --git a/llvm/lib/ExecutionEngine/Orc/CompileUtils.cpp b/llvm/lib/ExecutionEngine/Orc/CompileUtils.cpp
index fad7428e1f906c..f5b1daa2b8fe98 100644
--- a/llvm/lib/ExecutionEngine/Orc/CompileUtils.cpp
+++ b/llvm/lib/ExecutionEngine/Orc/CompileUtils.cpp
@@ -9,6 +9,7 @@
 #include "llvm/ExecutionEngine/Orc/CompileUtils.h"
 
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/CodeGen/MachineModuleInfo.h"
 #include "llvm/ExecutionEngine/ObjectCache.h"
 #include "llvm/IR/LegacyPassManager.h"
 #include "llvm/IR/Module.h"
@@ -46,8 +47,11 @@ Expected<SimpleCompiler::CompileResult> SimpleCompiler::operator()(Module &M) {
     raw_svector_ostream ObjStream(ObjBufferSV);
 
     legacy::PassManager PM;
-    MCContext *Ctx;
-    if (TM.addPassesToEmitMC(PM, Ctx, ObjStream))
+    MCContext MCCtx(
+        TM.getTargetTriple(), TM.getMCAsmInfo(), TM.getMCRegisterInfo(),
+        TM.getMCSubtargetInfo(), nullptr, &TM.Options.MCOptions, false);
+    auto MMI = TM.createMachineModuleInfo(MCCtx);
+    if (TM.addPassesToEmitMC(PM, ObjStream, *MMI))
       return make_error<StringError>("Target does not support MC emission",
                                      inconvertibleErrorCode());
     PM.run(M);
diff --git a/llvm/lib/LTO/LTOBackend.cpp b/llvm/lib/LTO/LTOBackend.cpp
index effaed2d9bfb60..7c50ab635545a3 100644
--- a/llvm/lib/LTO/LTOBackend.cpp
+++ b/llvm/lib/LTO/LTOBackend.cpp
@@ -20,11 +20,13 @@
 #include "llvm/Analysis/TargetLibraryInfo.h"
 #include "llvm/Bitcode/BitcodeReader.h"
 #include "llvm/Bitcode/BitcodeWriter.h"
+#include "llvm/CodeGen/MachineModuleInfo.h"
 #include "llvm/IR/LLVMRemarkStreamer.h"
 #include "llvm/IR/LegacyPassManager.h"
 #include "llvm/IR/PassManager.h"
 #include "llvm/IR/Verifier.h"
 #include "llvm/LTO/LTO.h"
+#include "llvm/MC/MCContext.h"
 #include "llvm/MC/TargetRegistry.h"
 #include "llvm/Object/ModuleSymbolTable.h"
 #include "llvm/Passes/PassBuilder.h"
@@ -423,9 +425,15 @@ static void codegen(const Config &Conf, TargetMachine *TM,
       createImmutableModuleSummaryIndexWrapperPass(&CombinedIndex));
   if (Conf.PreCodeGenPassesHook)
     Conf.PreCodeGenPassesHook(CodeGenPasses);
+
+  MCContext MCCtx(
+      TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
+      TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
+  auto MMI = TM->createMachineModuleInfo(MCCtx);
+
   if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS,
                               DwoOut ? &DwoOut->os() : nullptr,
-                              Conf.CGFileType))
+                              Conf.CGFileType, *MMI))
     report_fatal_error("Failed to setup codegen");
   CodeGenPasses.run(Mod);
 
diff --git a/llvm/lib/LTO/ThinLTOCodeGenerator.cpp b/llvm/lib/LTO/ThinLTOCodeGenerator.cpp
index b982df7c6e5d3f..831b7140321d81 100644
--- a/llvm/lib/LTO/ThinLTOCodeGenerator.cpp
+++ b/llvm/lib/LTO/ThinLTOCodeGenerator.cpp
@@ -24,6 +24,7 @@
 #include "llvm/Bitcode/BitcodeReader.h"
 #include "llvm/Bitcode/BitcodeWriter.h"
 #include "llvm/Bitcode/BitcodeWriterPass.h"
+#include "llvm/CodeGen/MachineModuleInfo.h"
 #include "llvm/Config/llvm-config.h"
 #include "llvm/IR/DebugInfo.h"
 #include "llvm/IR/DiagnosticPrinter.h"
@@ -36,6 +37,7 @@
 #include "llvm/IRReader/IRReader.h"
 #include "llvm/LTO/LTO.h"
 #include "llvm/LTO/SummaryBasedOptimizations.h"
+#include "llvm/MC/MCContext.h"
 #include "llvm/MC/TargetRegistry.h"
 #include "llvm/Object/IRObjectFile.h"
 #include "llvm/Passes/PassBuilder.h"
@@ -335,9 +337,13 @@ std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
     raw_svector_ostream OS(OutputBuffer);
     legacy::PassManager PM;
 
+    MCContext MCCtx(
+        TM.getTargetTriple(), TM.getMCAsmInfo(), TM.getMCRegisterInfo(),
+        TM.getMCSubtargetInfo(), nullptr, &TM.Options.MCOptions, false);
+    auto MMI = TM.createMachineModuleInfo(MCCtx);
     // Setup the codegen now.
     if (TM.addPassesToEmitFile(PM, OS, nullptr, CodeGenFileType::ObjectFile,
-                               /* DisableVerify */ true))
+                               *MMI, /* DisableVerify */ true))
       report_fatal_error("Failed to setup codegen");
 
     // Run codegen now. resulting binary is in OutputBuffer.
diff --git a/llvm/lib/Target/NVPTX/NVPTXTargetMachine.h b/llvm/lib/Target/NVPTX/NVPTXTargetMachine.h
index 2b88da67a50f95..115565289e3a14 100644
--- a/llvm/lib/Target/NVPTX/NVPTXTargetMachine.h
+++ b/llvm/lib/Target/NVPTX/NVPTXTargetMachine.h
@@ -52,8 +52,8 @@ class NVPTXTargetMachine : public LLVMTargetMachine {
   TargetPassConfig *createPassConfig(PassManagerBase &PM) override;
 
   // Emission of machine code through MCJIT is not supported.
-  bool addPassesToEmitMC(PassManagerBase &, MCContext *&, raw_pwrite_stream &,
-                         bool = true) override {
+  bool addPassesToEmitMC(PassManagerBase &, raw_pwrite_stream &,
+                         MachineModuleInfo &, bool = true) override {
     return true;
   }
   TargetLoweringObjectFile *getObjFileLowering() const override {
diff --git a/llvm/lib/Target/TargetMachineC.cpp b/llvm/lib/Target/TargetMachineC.cpp
index d12fc65047d043..e82a1f9d44a854 100644
--- a/llvm/lib/Target/TargetMachineC.cpp
+++ b/llvm/lib/Target/TargetMachineC.cpp
@@ -13,9 +13,11 @@
 #include "llvm-c/Core.h"
 #include "llvm-c/TargetMachine.h"
 #include "llvm/Analysis/TargetTransformInfo.h"
+#include "llvm/CodeGen/MachineModuleInfo.h"
 #include "llvm/IR/DataLayout.h"
 #include "llvm/IR/LegacyPassManager.h"
 #include "llvm/IR/Module.h"
+#include "llvm/MC/MCContext.h"
 #include "llvm/MC/TargetRegistry.h"
 #include "llvm/Support/CBindingWrapping.h"
 #include "llvm/Support/FileSystem.h"
@@ -309,7 +311,13 @@ static LLVMBool LLVMTargetMachineEmit(LLVMTargetMachineRef T, LLVMModuleRef M,
       ft = CodeGenFileType::ObjectFile;
       break;
   }
-  if (TM->addPassesToEmitFile(pass, OS, nullptr, ft)) {
+
+    MCContext MCCtx(TM->getTargetTriple(), TM->getMCAsmInfo(),
+                    TM->getMCRegisterInfo(), TM->getMCSubtargetInfo(), nullptr,
+                    &TM->Options.MCOptions, false);
+    auto MMI = TM->createMachineModuleInfo(MCCtx);
+
+  if (TM->addPassesToEmitFile(pass, OS, nullptr, ft, *MMI)) {
     error = "TargetMachine can't emit a file of this type";
     *ErrorMessage = strdup(error.c_str());
     return true;
diff --git a/llvm/tools/llc/NewPMDriver.cpp b/llvm/tools/llc/NewPMDriver.cpp
index c8088da49a2784..e69d7a8a4c71e7 100644
--- a/llvm/tools/llc/NewPMDriver.cpp
+++ b/llvm/tools/llc/NewPMDriver.cpp
@@ -108,7 +108,11 @@ int llvm::compileModuleWithNewPM(
   Opt.DebugPM = DebugPM;
   Opt.RegAlloc = RegAlloc;
 
-  MachineModuleInfo MMI(&LLVMTM);
+  llvm::MCContext MCCtx(
+      LLVMTM.getTargetTriple(), LLVMTM.getMCAsmInfo(),
+      LLVMTM.getMCRegisterInfo(), LLVMTM.getMCSubtargetInfo(),
+      nullptr, &LLVMTM.Options.MCOptions, false);
+  MachineModuleInfo MMI(LLVMTM, MCCtx);
 
   PassInstrumentationCallbacks PIC;
   StandardInstrumentations SI(Context, Opt.DebugPM, !NoVerify);
diff --git a/llvm/tools/llc/llc.cpp b/llvm/tools/llc/llc.cpp
index 80c84a977c26c6..e2430decfeb10a 100644
--- a/llvm/tools/llc/llc.cpp
+++ b/llvm/tools/llc/llc.cpp
@@ -674,8 +674,12 @@ static int compileModule(char **argv, LLVMContext &Context) {
 
     const char *argv0 = argv[0];
     LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine &>(*Target);
+    MCContext MCCtx(LLVMTM.getTargetTriple(), LLVMTM.getMCAsmInfo(),
+                    LLVMTM.getMCRegisterInfo(), LLVMTM.getMCSubtargetInfo(),
+                    nullptr, &LLVMTM.Options.MCOptions, false);
+    auto MMI = LLVMTM.createMachineModuleInfo(MCCtx);
     MachineModuleInfoWrapperPass *MMIWP =
-        new MachineModuleInfoWrapperPass(&LLVMTM);
+        new MachineModuleInfoWrapperPass(*MMI);
 
     // Construct a custom pass pipeline that starts after instruction
     // selection.
@@ -710,7 +714,7 @@ static int compileModule(char **argv, LLVMContext &Context) {
       PM.add(createFreeMachineFunctionPass());
     } else if (Target->addPassesToEmitFile(
                    PM, *OS, DwoOut ? &DwoOut->os() : nullptr,
-                   codegen::getFileType(), NoVerify, MMIWP)) {
+                   codegen::getFileType(), *MMI, NoVerify)) {
       reportError("target does not support generation of this file type");
     }
 
@@ -718,7 +722,7 @@ static int compileModule(char **argv, LLVMContext &Context) {
         ->Initialize(MMIWP->getMMI().getContext(), *Target);
     if (MIR) {
       assert(MMIWP && "Forgot to create MMIWP?");
-      if (MIR->parseMachineFunctions(*M, MMIWP->getMMI()))
+      if (MIR->parseMachineFunctions(*M, *MMI))
         return 1;
     }
 
@@ -735,6 +739,7 @@ static int compileModule(char **argv, LLVMContext &Context) {
       PM.run(*M2);
       CompileTwiceBuffer = Buffer;
       Buffer.clear();
+      MCCtx.reset();
     }
 
     PM.run(*M);
diff --git a/llvm/tools/llvm-exegesis/lib/Assembler.cpp b/llvm/tools/llvm-exegesis/lib/Assembler.cpp
index 92ab3a96d91e6b..d73d8f26cc1fe2 100644
--- a/llvm/tools/llvm-exegesis/lib/Assembler.cpp
+++ b/llvm/tools/llvm-exegesis/lib/Assembler.cpp
@@ -234,9 +234,13 @@ BitVector getFunctionReservedRegs(const TargetMachine &TM) {
   std::unique_ptr<Module> Module = createModule(Context, TM.createDataLayout());
   // TODO: This only works for targets implementing LLVMTargetMachine.
   const LLVMTargetMachine &LLVMTM = static_cast<const LLVMTargetMachine &>(TM);
-  auto MMIWP = std::make_unique<MachineModuleInfoWrapperPass>(&LLVMTM);
+  auto MCCtx = std::make_unique<MCContext>(
+      LLVMTM.getTargetTriple(), LLVMTM.getMCAsmInfo(),
+      LLVMTM.getMCRegisterInfo(), LLVMTM.getMCSubtargetInfo(), nullptr,
+      &LLVMTM.Options.MCOptions, false);
+  auto MMI = std::make_unique<llvm::MachineModuleInfo>(LLVMTM, *MCCtx);
   MachineFunction &MF = createVoidVoidPtrMachineFunction(
-      FunctionID, Module.get(), &MMIWP->getMMI());
+      FunctionID, Module.get(), MMI.get());
   // Saving reserved registers for client.
   return MF.getSubtarget().getRegisterInfo()->getReservedRegs(MF);
 }
@@ -249,7 +253,11 @@ Error assembleToStream(const ExegesisTarget &ET,
   auto Context = std::make_unique<LLVMContext>();
   std::unique_ptr<Module> Module =
       createModule(Context, TM->createDataLayout());
-  auto MMIWP = std::make_unique<MachineModuleInfoWrapperPass>(TM.get());
+  MCContext MCCtx(TM->getTargetTriple(), TM->getMCAsmInfo(),
+                  TM->getMCRegisterInfo(), TM->getMCSubtargetInfo(), nullptr,
+                  &TM->Options.MCOptions, false);
+  auto MMI = std::make_unique<llvm::MachineModuleInfo>(*TM, MCCtx);
+  auto MMIWP = std::make_unique<MachineModuleInfoWrapperPass>(*MMI);
   MachineFunction &MF = createVoidVoidPtrMachineFunction(
       FunctionID, Module.get(), &MMIWP.get()->getMMI());
   MF.ensureAlignment(kFunctionAlignment);
diff --git a/llvm/tools/llvm-isel-fuzzer/llvm-isel-fuzzer.cpp b/llvm/tools/llvm-isel-fuzzer/llvm-isel-fuzzer.cpp
index 742f7b94e116f3..49823848bad7ff 100644
--- a/llvm/tools/llvm-isel-fuzzer/llvm-isel-fuzzer.cpp
+++ b/llvm/tools/llvm-isel-fuzzer/llvm-isel-fuzzer.cpp
@@ -15,6 +15,7 @@
 #include "llvm/Bitcode/BitcodeReader.h"
 #include "llvm/Bitcode/BitcodeWriter.h"
 #include "llvm/CodeGen/CommandFlags.h"
+#include "llvm/CodeGen/MachineModuleInfo.h"
 #include "llvm/FuzzMutate/FuzzerCLI.h"
 #include "llvm/FuzzMutate/IRMutator.h"
 #include "llvm/FuzzMutate/Operations.h"
@@ -24,6 +25,7 @@
 #include "llvm/IR/Module.h"
 #include "llvm/IR/Verifier.h"
 #include "llvm/IRReader/IRReader.h"
+#include "llvm/MC/MCContext.h"
 #include "llvm/MC/TargetRegistry.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/DataTypes.h"
@@ -96,10 +98,14 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
 
   // Build up a PM to do instruction selection.
   legacy::PassManager PM;
+  MCContext MCCtx(
+      TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
+      TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
+  auto MMI = TM->createMachineModuleInfo(MCCtx);
   TargetLibraryInfoImpl TLII(TM->getTargetTriple());
   PM.add(new TargetLibraryInfoWrapperPass(TLII));
   raw_null_ostream OS;
-  TM->addPassesToEmitFile(PM, OS, nullptr, CodeGenFileType::Null);
+  TM->addPassesToEmitFile(PM, OS, nullptr, CodeGenFileType::Null, *MMI);
   PM.run(*M);
 
   return 0;
diff --git a/llvm/tools/llvm-reduce/ReducerWorkItem.cpp b/llvm/tools/llvm-reduce/ReducerWorkItem.cpp
index 1510e9fb32007e..0b2c3b3f32f5d5 100644
--- a/llvm/tools/llvm-reduce/ReducerWorkItem.cpp
+++ b/llvm/tools/llvm-reduce/ReducerWorkItem.cpp
@@ -492,9 +492,11 @@ bool ReducerWorkItem::isReduced(const TestRunner &Test) const {
 }
 
 std::unique_ptr<ReducerWorkItem>
-ReducerWorkItem::clone(const TargetMachine *TM) const {
+ReducerWorkItem::clone(const TargetMachine *TM, MCContext *MCCtx) const {
   auto CloneMMM = std::make_unique<ReducerWorkItem>();
   if (TM) {
+    if (!MCCtx)
+      report_fatal_error("MCContext is nullptr");
     // We're assuming the Module IR contents are always unchanged by MIR
     // reductions, and can share it as a constant.
     CloneMMM->M = M;
@@ -504,7 +506,7 @@ ReducerWorkItem::clone(const TargetMachine *TM) const {
     // is pretty ugly).
     const LLVMTargetMachine *LLVMTM =
         static_cast<const LLVMTargetMachine *>(TM);
-    CloneMMM->MMI = std::make_unique<MachineModuleInfo>(LLVMTM);
+    CloneMMM->MMI = std::make_unique<MachineModuleInfo>(*LLVMTM, *MCCtx);
 
     for (const Function &F : getModule()) {
       if (auto *MF = MMI->getMachineFunction(F))
@@ -784,6 +786,7 @@ void ReducerWorkItem::writeBitcode(raw_ostream &OutStream) const {
 std::pair<std::unique_ptr<ReducerWorkItem>, bool>
 llvm::parseReducerWorkItem(StringRef ToolName, StringRef Filename,
                            LLVMContext &Ctxt,
+                           std::unique_ptr<MCContext> &MCCtx,
                            std::unique_ptr<TargetMachine> &TM, bool IsMIR) {
   bool IsBitcode = false;
   Triple TheTriple;
@@ -822,7 +825,12 @@ llvm::parseReducerWorkItem(StringRef ToolName, StringRef Filename,
     std::unique_ptr<Module> M = MParser->parseIRModule(SetDataLayout);
     LLVMTargetMachine *LLVMTM = static_cast<LLVMTargetMachine *>(TM.get());
 
-    MMM->MMI = std::make_unique<MachineModuleInfo>(LLVMTM);
+    MCCtx.reset(new MCContext(LLVMTM->getTargetTriple(),
+                              LLVMTM->getMCAsmInfo(),
+                              LLVMTM->getMCRegisterInfo(),
+                              LLVMTM->getMCSubtargetInfo(), nullptr,
+                              &LLVMTM->Options.MCOptions, false));
+    MMM->MMI = std::make_unique<MachineModuleInfo>(*LLVMTM, *MCCtx);
     MParser->parseMachineFunctions(*M, *MMM->MMI);
     MMM->M = std::move(M);
   } else {
diff --git a/llvm/tools/llvm-reduce/ReducerWorkItem.h b/llvm/tools/llvm-reduce/ReducerWorkItem.h
index dc11322917af88..a7288420fc0313 100644
--- a/llvm/tools/llvm-reduce/ReducerWorkItem.h
+++ b/llvm/tools/llvm-reduce/ReducerWorkItem.h
@@ -14,6 +14,7 @@
 
 namespace llvm {
 class LLVMContext;
+class MCContext;
 class MachineModuleInfo;
 class MemoryBufferRef;
 class raw_ostream;
@@ -44,7 +45,8 @@ class ReducerWorkItem {
 
   void print(raw_ostream &ROS, void *p = nullptr) const;
   bool verify(raw_fd_ostream *OS) const;
-  std::unique_ptr<ReducerWorkItem> clone(const TargetMachine *TM) const;
+  std::unique_ptr<ReducerWorkItem> clone(const TargetMachine *TM,
+                                         MCContext * MCCtx) const;
 
   /// Return a number to indicate whether there was any reduction progress.
   uint64_t getComplexityScore() const {
@@ -64,6 +66,7 @@ class ReducerWorkItem {
 
 std::pair<std::unique_ptr<ReducerWorkItem>, bool>
 parseReducerWorkItem(StringRef ToolName, StringRef Filename, LLVMContext &Ctxt,
+                     std::unique_ptr<MCContext> &MCContext,
                      std::unique_ptr<TargetMachine> &TM, bool IsMIR);
 } // namespace llvm
 
diff --git a/llvm/tools/llvm-reduce/TestRunner.cpp b/llvm/tools/llvm-reduce/TestRunner.cpp
index 8a61aae64b9029..60f5ca0e570550 100644
--- a/llvm/tools/llvm-reduce/TestRunner.cpp
+++ b/llvm/tools/llvm-reduce/TestRunner.cpp
@@ -9,6 +9,7 @@
 #include "TestRunner.h"
 #include "ReducerWorkItem.h"
 #include "deltas/Utils.h"
+#include "llvm/MC/MCContext.h"
 #include "llvm/Support/WithColor.h"
 
 using namespace llvm;
@@ -16,11 +17,12 @@ using namespace llvm;
 TestRunner::TestRunner(StringRef TestName,
                        const std::vector<std::string> &TestArgs,
                        std::unique_ptr<ReducerWorkItem> Program,
-                       std::unique_ptr<TargetMachine> TM, StringRef ToolName,
+                       std::unique_ptr<TargetMachine> TM,
+                       std::unique_ptr<MCContext> MCCtx, StringRef ToolName,
                        StringRef OutputName, bool InputIsBitcode,
                        bool OutputBitcode)
     : TestName(TestName), ToolName(ToolName), TestArgs(TestArgs),
-      Program(std::move(Program)), TM(std::move(TM)),
+      Program(std::move(Program)), TM(std::move(TM)), MCCtx(std::move(MCCtx)),
       OutputFilename(OutputName), InputIsBitcode(InputIsBitcode),
       EmitBitcode(OutputBitcode) {
   assert(this->Program && "Initialized with null program?");
diff --git a/llvm/tools/llvm-reduce/TestRunner.h b/llvm/tools/llvm-reduce/TestRunner.h
index 16d3dcd244a833..f6c2c57adfcdca 100644
--- a/llvm/tools/llvm-reduce/TestRunner.h
+++ b/llvm/tools/llvm-reduce/TestRunner.h
@@ -27,7 +27,8 @@ class TestRunner {
 public:
   TestRunner(StringRef TestName, const std::vector<std::string> &TestArgs,
              std::unique_ptr<ReducerWorkItem> Program,
-             std::unique_ptr<TargetMachine> TM, StringRef ToolName,
+             std::unique_ptr<TargetMachine> TM,
+             std::unique_ptr<MCContext> MCCtx, StringRef ToolName,
              StringRef OutputFilename, bool InputIsBitcode, bool OutputBitcode);
 
   /// Runs the interesting-ness test for the specified file
@@ -44,6 +45,8 @@ class TestRunner {
 
   const TargetMachine *getTargetMachine() const { return TM.get(); }
 
+  MCContext *getMCContext() const { return MCCtx.get();}
+
   StringRef getToolName() const { return ToolName; }
 
   void writeOutput(StringRef Message);
@@ -58,6 +61,7 @@ class TestRunner {
   const std::vector<std::string> &TestArgs;
   std::unique_ptr<ReducerWorkItem> Program;
   std::unique_ptr<TargetMachine> TM;
+  std::unique_ptr<MCContext> MCCtx;
   StringRef OutputFilename;
   const bool InputIsBitcode;
   bool EmitBitcode;
diff --git a/llvm/tools/llvm-reduce/deltas/Delta.cpp b/llvm/tools/llvm-reduce/deltas/Delta.cpp
index 4b84921618e1cd..415bf3822a103d 100644
--- a/llvm/tools/llvm-reduce/deltas/Delta.cpp
+++ b/llvm/tools/llvm-reduce/deltas/Delta.cpp
@@ -198,7 +198,7 @@ void llvm::runDeltaPass(TestRunner &Test, ReductionFunc ExtractChunksFromModule,
     std::vector<Chunk> NoChunks = {{0, INT_MAX}};
     Oracle NoChunksCounter(NoChunks);
     std::unique_ptr<ReducerWorkItem> Clone =
-      Test.getProgram().clone(Test.getTargetMachine());
+      Test.getProgram().clone(Test.getTargetMachine(), Test.getMCContext());
     ExtractChunksFromModule(NoChunksCounter, *Clone);
     assert(Targets == NoChunksCounter.count() &&
            "number of chunks changes when reducing");
@@ -314,10 +314,11 @@ void llvm::runDeltaPass(TestRunner &Test, ReductionFunc ExtractChunksFromModule,
         // Forward I to the last chunk processed in parallel.
         I += NumChunksProcessed - 1;
       } else {
-        Result =
-            CheckChunk(*I, Test.getProgram().clone(Test.getTargetMachine()),
-                       Test, ExtractChunksFromModule, UninterestingChunks,
-                       ChunksStillConsideredInteresting);
+        Result = CheckChunk(*I,
+                            Test.getProgram().clone(Test.getTargetMachine(),
+                                                    Test.getMCContext()),
+                            Test, ExtractChunksFromModule, UninterestingChunks,
+                            ChunksStillConsideredInteresting);
       }
 
       if (!Result)
diff --git a/llvm/tools/llvm-reduce/llvm-reduce.cpp b/llvm/tools/llvm-reduce/llvm-reduce.cpp
index 288a384c2ed498..88279db287a902 100644
--- a/llvm/tools/llvm-reduce/llvm-reduce.cpp
+++ b/llvm/tools/llvm-reduce/llvm-reduce.cpp
@@ -19,6 +19,7 @@
 #include "TestRunner.h"
 #include "llvm/Bitcode/BitcodeReader.h"
 #include "llvm/CodeGen/CommandFlags.h"
+#include "llvm/MC/MCContext.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/InitLLVM.h"
 #include "llvm/Support/MemoryBufferRef.h"
@@ -179,10 +180,11 @@ int main(int Argc, char **Argv) {
     disableEnvironmentDebugFeatures();
 
   LLVMContext Context;
+  std::unique_ptr<MCContext> MCCtx;
   std::unique_ptr<TargetMachine> TM;
 
-  auto [OriginalProgram, InputIsBitcode] =
-      parseReducerWorkItem(ToolName, InputFilename, Context, TM, ReduceModeMIR);
+  auto [OriginalProgram, InputIsBitcode] = parseReducerWorkItem(
+      ToolName, InputFilename, Context, MCCtx, TM, ReduceModeMIR);
   if (!OriginalProgram) {
     return 1;
   }
@@ -194,8 +196,8 @@ int main(int Argc, char **Argv) {
 
   // Initialize test environment
   TestRunner Tester(TestFilename, TestArguments, std::move(OriginalProgram),
-                    std::move(TM), ToolName, OutputFilename, InputIsBitcode,
-                    OutputBitcode);
+                    std::move(TM), std::move(MCCtx), ToolName, OutputFilename,
+                    InputIsBitcode, OutputBitcode);
 
   // This parses and writes out the testcase into a temporary file copy for the
   // test, rather than evaluating the source IR directly. This is for the
diff --git a/llvm/unittests/CodeGen/AArch64SelectionDAGTest.cpp b/llvm/unittests/CodeGen/AArch64SelectionDAGTest.cpp
index 79e27c7ced61fc..0d815ab9b28c20 100644
--- a/llvm/unittests/CodeGen/AArch64SelectionDAGTest.cpp
+++ b/llvm/unittests/CodeGen/AArch64SelectionDAGTest.cpp
@@ -46,6 +46,9 @@ class AArch64SelectionDAGTest : public testing::Test {
     TM = std::unique_ptr<LLVMTargetMachine>(static_cast<LLVMTargetMachine *>(
         T->createTargetMachine("AArch64", "", "+sve", Options, std::nullopt,
                                std::nullopt, CodeGenOptLevel::Aggressive)));
+    MCCtx = std::make_unique<MCContext>(
+        TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
+        TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
     if (!TM)
       GTEST_SKIP();
 
@@ -59,10 +62,10 @@ class AArch64SelectionDAGTest : public testing::Test {
     if (!F)
       report_fatal_error("F?");
 
-    MachineModuleInfo MMI(TM.get());
+    MachineModuleInfo MMI(*TM, *MCCtx);
 
     MF = std::make_unique<MachineFunction>(*F, *TM, *TM->getSubtargetImpl(*F),
-                                           MMI.getContext(), 0);
+                                           *MCCtx, 0);
 
     DAG = std::make_unique<SelectionDAG>(*TM, CodeGenOptLevel::None);
     if (!DAG)
@@ -82,6 +85,7 @@ class AArch64SelectionDAGTest : public testing::Test {
 
   LLVMContext Context;
   std::unique_ptr<LLVMTargetMachine> TM;
+  std::unique_ptr<MCContext> MCCtx;
   std::unique_ptr<Module> M;
   Function *F;
   std::unique_ptr<MachineFunction> MF;
diff --git a/llvm/unittests/CodeGen/AMDGPUMetadataTest.cpp b/llvm/unittests/CodeGen/AMDGPUMetadataTest.cpp
index ceea57fa10cce4..361c0a5f8e8c6d 100644
--- a/llvm/unittests/CodeGen/AMDGPUMetadataTest.cpp
+++ b/llvm/unittests/CodeGen/AMDGPUMetadataTest.cpp
@@ -12,6 +12,7 @@
 //
 //===----------------------------------------------------------------------===//
 
+#include "llvm/CodeGen/MachineModuleInfo.h"
 #include "llvm/IR/LegacyPassManager.h"
 #include "llvm/IR/Module.h"
 #include "llvm/MC/TargetRegistry.h"
@@ -70,8 +71,12 @@ class AMDGPUSelectionDAGTest : public testing::Test {
     legacy::PassManager PM;
     PM.add(new AddMetadataPass(PalMDString));
     raw_svector_ostream OutStream(Elf);
+    MCContext MCCtx(TM->getTargetTriple(), TM->getMCAsmInfo(),
+                    TM->getMCRegisterInfo(), TM->getMCSubtargetInfo(), nullptr,
+                    &TM->Options.MCOptions, false);
+    MachineModuleInfo MMI(*TM, MCCtx);
     if (TM->addPassesToEmitFile(PM, OutStream, nullptr,
-                                CodeGenFileType::ObjectFile))
+                                CodeGenFileType::ObjectFile, MMI))
       report_fatal_error("Target machine cannot emit a file of this type");
 
     PM.run(*M);
diff --git a/llvm/unittests/CodeGen/AsmPrinterDwarfTest.cpp b/llvm/unittests/CodeGen/AsmPrinterDwarfTest.cpp
index 1f3d7a55ee8542..9663104a42460c 100644
--- a/llvm/unittests/CodeGen/AsmPrinterDwarfTest.cpp
+++ b/llvm/unittests/CodeGen/AsmPrinterDwarfTest.cpp
@@ -400,7 +400,11 @@ class AsmPrinterHandlerTest : public AsmPrinterFixtureBase {
     AP->addAsmPrinterHandler(std::make_unique<TestHandler>(*this));
     LLVMTargetMachine *LLVMTM = static_cast<LLVMTargetMachine *>(&AP->TM);
     legacy::PassManager PM;
-    PM.add(new MachineModuleInfoWrapperPass(LLVMTM));
+    MCContext MCCtx(LLVMTM->getTargetTriple(), LLVMTM->getMCAsmInfo(),
+                    LLVMTM->getMCRegisterInfo(), LLVMTM->getMCSubtargetInfo(),
+                    nullptr, &LLVMTM->Options.MCOptions, false);
+    MachineModuleInfo MMI(*LLVMTM, MCCtx);
+    PM.add(new MachineModuleInfoWrapperPass(MMI));
     PM.add(TestPrinter->releaseAP()); // Takes ownership of destroying AP
     LLVMContext Context;
     std::unique_ptr<Module> M(new Module("TestModule", Context));
@@ -450,7 +454,11 @@ class AsmPrinterDebugHandlerTest : public AsmPrinterFixtureBase {
     AP->addDebugHandler(std::make_unique<TestDebugHandler>(*this, AP));
     LLVMTargetMachine *LLVMTM = static_cast<LLVMTargetMachine *>(&AP->TM);
     legacy::PassManager PM;
-    PM.add(new MachineModuleInfoWrapperPass(LLVMTM));
+    MCContext MCCtx(LLVMTM->getTargetTriple(), LLVMTM->getMCAsmInfo(),
+                    LLVMTM->getMCRegisterInfo(), LLVMTM->getMCSubtargetInfo(),
+                    nullptr, &LLVMTM->Options.MCOptions, false);
+    MachineModuleInfo MMI(*LLVMTM, MCCtx);
+    PM.add(new MachineModuleInfoWrapperPass(MMI));
     PM.add(TestPrinter->releaseAP()); // Takes ownership of destroying AP
     LLVMContext Context;
     std::unique_ptr<Module> M(new Module("TestModule", Context));
diff --git a/llvm/unittests/CodeGen/GlobalISel/GISelMITest.h b/llvm/unittests/CodeGen/GlobalISel/GISelMITest.h
index fd31e95cce13d9..129eba933928c8 100644
--- a/llvm/unittests/CodeGen/GlobalISel/GISelMITest.h
+++ b/llvm/unittests/CodeGen/GlobalISel/GISelMITest.h
@@ -23,6 +23,7 @@
 #include "llvm/CodeGen/TargetSubtargetInfo.h"
 #include "llvm/FileCheck/FileCheck.h"
 #include "llvm/InitializePasses.h"
+#include "llvm/MC/MCContext.h"
 #include "llvm/MC/TargetRegistry.h"
 #include "llvm/Support/SourceMgr.h"
 #include "llvm/Support/TargetSelect.h"
@@ -77,9 +78,10 @@ static std::unique_ptr<Module> parseMIR(LLVMContext &Context,
 }
 static std::pair<std::unique_ptr<Module>, std::unique_ptr<MachineModuleInfo>>
 createDummyModule(LLVMContext &Context, const LLVMTargetMachine &TM,
-                  StringRef MIRString, const char *FuncName) {
+                  MCContext &MCContext, StringRef MIRString,
+                  const char *FuncName) {
   std::unique_ptr<MIRParser> MIR;
-  auto MMI = std::make_unique<MachineModuleInfo>(&TM);
+  auto MMI = std::make_unique<MachineModuleInfo>(TM, MCContext);
   std::unique_ptr<Module> M =
       parseMIR(Context, MIR, TM, MIRString, FuncName, *MMI);
   return make_pair(std::move(M), std::move(MMI));
@@ -116,11 +118,14 @@ class GISelMITest : public ::testing::Test {
     TM = createTargetMachine();
     if (!TM)
       return;
-
+    MCCtx = std::make_unique<MCContext>(
+        TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
+        TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
     SmallString<512> MIRString;
     getTargetTestModuleString(MIRString, ExtraAssembly);
 
-    ModuleMMIPair = createDummyModule(Context, *TM, MIRString, "func");
+    ModuleMMIPair =
+        createDummyModule(Context, *TM, *MCCtx, MIRString, "func");
     MF = getMFFromMMI(ModuleMMIPair.first.get(), ModuleMMIPair.second.get());
     collectCopies(Copies, MF);
     EntryMBB = &*MF->begin();
@@ -130,6 +135,7 @@ class GISelMITest : public ::testing::Test {
   }
 
   LLVMContext Context;
+  std::unique_ptr<MCContext> MCCtx;
   std::unique_ptr<LLVMTargetMachine> TM;
   MachineFunction *MF;
   std::pair<std::unique_ptr<Module>, std::unique_ptr<MachineModuleInfo>>
diff --git a/llvm/unittests/CodeGen/InstrRefLDVTest.cpp b/llvm/unittests/CodeGen/InstrRefLDVTest.cpp
index d5365d9c794925..36cccea9ca36b7 100644
--- a/llvm/unittests/CodeGen/InstrRefLDVTest.cpp
+++ b/llvm/unittests/CodeGen/InstrRefLDVTest.cpp
@@ -40,6 +40,7 @@ class InstrRefLDVTest : public testing::Test {
   using MLocTransferMap = InstrRefBasedLDV::MLocTransferMap;
 
   LLVMContext Ctx;
+  std::unique_ptr<MCContext> MCCtx;
   std::unique_ptr<Module> Mod;
   std::unique_ptr<TargetMachine> Machine;
   std::unique_ptr<MachineFunction> MF;
@@ -90,7 +91,12 @@ class InstrRefLDVTest : public testing::Test {
         Function::Create(Type, GlobalValue::ExternalLinkage, "Test", &*Mod);
 
     unsigned FunctionNum = 42;
-    MMI = std::make_unique<MachineModuleInfo>((LLVMTargetMachine *)&*Machine);
+    MCCtx = std::make_unique<MCContext>(
+        Machine->getTargetTriple(), Machine->getMCAsmInfo(),
+        Machine->getMCRegisterInfo(), Machine->getMCSubtargetInfo(), nullptr,
+        &Machine->Options.MCOptions, false);
+    MMI = std::make_unique<MachineModuleInfo>(*(LLVMTargetMachine *)&*Machine,
+                                              *MCCtx);
     const TargetSubtargetInfo &STI = *Machine->getSubtargetImpl(*F);
 
     MF = std::make_unique<MachineFunction>(*F, (LLVMTargetMachine &)*Machine,
diff --git a/llvm/unittests/CodeGen/MFCommon.inc b/llvm/unittests/CodeGen/MFCommon.inc
index d464a16f636cf5..884b26c296fab8 100644
--- a/llvm/unittests/CodeGen/MFCommon.inc
+++ b/llvm/unittests/CodeGen/MFCommon.inc
@@ -132,10 +132,12 @@ std::unique_ptr<MachineFunction> createMachineFunction(LLVMContext &Ctx,
 
   auto TM = createTargetMachine();
   unsigned FunctionNum = 42;
-  MachineModuleInfo MMI(TM);
+  MCContext MCCtx(TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
+                  TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
+  MachineModuleInfo MMI(*TM, MCCtx);
   const TargetSubtargetInfo &STI = *TM->getSubtargetImpl(*F);
 
-  return std::make_unique<MachineFunction>(*F, *TM, STI, MMI.getContext(),
+  return std::make_unique<MachineFunction>(*F, *TM, STI, MCCtx,
                                            FunctionNum);
 }
 
diff --git a/llvm/unittests/CodeGen/MachineDomTreeUpdaterTest.cpp b/llvm/unittests/CodeGen/MachineDomTreeUpdaterTest.cpp
index 9dcf3754a5bd74..52bea20acec7ec 100644
--- a/llvm/unittests/CodeGen/MachineDomTreeUpdaterTest.cpp
+++ b/llvm/unittests/CodeGen/MachineDomTreeUpdaterTest.cpp
@@ -17,6 +17,7 @@
 #include "llvm/CodeGen/SelectionDAG.h"
 #include "llvm/CodeGen/TargetLowering.h"
 #include "llvm/IR/Module.h"
+#include "llvm/MC/MCContext.h"
 #include "llvm/MC/TargetRegistry.h"
 #include "llvm/Passes/PassBuilder.h"
 #include "llvm/Support/SourceMgr.h"
@@ -30,6 +31,7 @@ class MachineDomTreeUpdaterTest : public testing::Test {
 public:
   LLVMContext Context;
   std::unique_ptr<TargetMachine> TM;
+  std::unique_ptr<MCContext> MCCtx;
   std::unique_ptr<Module> M;
   std::unique_ptr<MachineModuleInfo> MMI;
   std::unique_ptr<MIRParser> MIR;
@@ -60,8 +62,12 @@ class MachineDomTreeUpdaterTest : public testing::Test {
         T->createTargetMachine("X86", "", "", Options, std::nullopt));
     if (!TM)
       GTEST_SKIP();
+    MCCtx = std::make_unique<MCContext>(
+        TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
+        TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
+
     MMI = std::make_unique<MachineModuleInfo>(
-        static_cast<LLVMTargetMachine *>(TM.get()));
+        *static_cast<LLVMTargetMachine *>(TM.get()), *MCCtx);
 
     PassBuilder PB(TM.get());
     PB.registerModuleAnalyses(MAM);
diff --git a/llvm/unittests/CodeGen/PassManagerTest.cpp b/llvm/unittests/CodeGen/PassManagerTest.cpp
index d3a410f5450cc6..98647c746f0e5a 100644
--- a/llvm/unittests/CodeGen/PassManagerTest.cpp
+++ b/llvm/unittests/CodeGen/PassManagerTest.cpp
@@ -181,8 +181,12 @@ TEST_F(PassManagerTest, Basic) {
 
   LLVMTargetMachine *LLVMTM = static_cast<LLVMTargetMachine *>(TM.get());
   M->setDataLayout(TM->createDataLayout());
+  MCContext MCCtx(
+      LLVMTM->getTargetTriple(), LLVMTM->getMCAsmInfo(),
+      LLVMTM->getMCRegisterInfo(), LLVMTM->getMCSubtargetInfo(), nullptr,
+      &LLVMTM->Options.MCOptions, false);
 
-  MachineModuleInfo MMI(LLVMTM);
+  MachineModuleInfo MMI(*LLVMTM, MCCtx);
 
   MachineFunctionAnalysisManager MFAM;
   LoopAnalysisManager LAM;
@@ -232,7 +236,11 @@ TEST_F(PassManagerTest, DiagnosticHandler) {
   LLVMTargetMachine *LLVMTM = static_cast<LLVMTargetMachine *>(TM.get());
   M->setDataLayout(TM->createDataLayout());
 
-  MachineModuleInfo MMI(LLVMTM);
+  MCContext MCCtx(
+      LLVMTM->getTargetTriple(), LLVMTM->getMCAsmInfo(),
+      LLVMTM->getMCRegisterInfo(), LLVMTM->getMCSubtargetInfo(), nullptr,
+      &LLVMTM->Options.MCOptions, false);
+  MachineModuleInfo MMI(*LLVMTM, MCCtx);
 
   LoopAnalysisManager LAM;
   MachineFunctionAnalysisManager MFAM;
diff --git a/llvm/unittests/CodeGen/SelectionDAGAddressAnalysisTest.cpp b/llvm/unittests/CodeGen/SelectionDAGAddressAnalysisTest.cpp
index c89e5a45ab0142..8f28493ad7ff02 100644
--- a/llvm/unittests/CodeGen/SelectionDAGAddressAnalysisTest.cpp
+++ b/llvm/unittests/CodeGen/SelectionDAGAddressAnalysisTest.cpp
@@ -69,7 +69,11 @@ class SelectionDAGAddressAnalysisTest : public testing::Test {
     if (!AliasedG)
       report_fatal_error("AliasedG?");
 
-    MachineModuleInfo MMI(TM.get());
+    MCCtx = std::make_unique<MCContext>(
+        TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
+        TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
+
+    MachineModuleInfo MMI(*TM, *MCCtx);
 
     MF = std::make_unique<MachineFunction>(*F, *TM, *TM->getSubtargetImpl(*F),
                                            MMI.getContext(), 0);
@@ -91,6 +95,7 @@ class SelectionDAGAddressAnalysisTest : public testing::Test {
   }
 
   LLVMContext Context;
+  std::unique_ptr<MCContext> MCCtx;
   std::unique_ptr<LLVMTargetMachine> TM;
   std::unique_ptr<Module> M;
   Function *F;
diff --git a/llvm/unittests/CodeGen/SelectionDAGPatternMatchTest.cpp b/llvm/unittests/CodeGen/SelectionDAGPatternMatchTest.cpp
index e66584b81bba25..2f42718a4d52ed 100644
--- a/llvm/unittests/CodeGen/SelectionDAGPatternMatchTest.cpp
+++ b/llvm/unittests/CodeGen/SelectionDAGPatternMatchTest.cpp
@@ -68,10 +68,14 @@ class SelectionDAGPatternMatchTest : public testing::Test {
     if (!AliasedG)
       report_fatal_error("AliasedG?");
 
-    MachineModuleInfo MMI(TM.get());
+    MCCtx = std::make_unique<MCContext>(
+        TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
+        TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
+
+    MachineModuleInfo MMI(*TM, *MCCtx);
 
     MF = std::make_unique<MachineFunction>(*F, *TM, *TM->getSubtargetImpl(*F),
-                                           MMI.getContext(), 0);
+                                           *MCCtx, 0);
 
     DAG = std::make_unique<SelectionDAG>(*TM, CodeGenOptLevel::None);
     if (!DAG)
@@ -95,6 +99,7 @@ class SelectionDAGPatternMatchTest : public testing::Test {
   Function *F;
   GlobalVariable *G;
   GlobalAlias *AliasedG;
+  std::unique_ptr<MCContext> MCCtx;
   std::unique_ptr<MachineFunction> MF;
   std::unique_ptr<SelectionDAG> DAG;
 };
diff --git a/llvm/unittests/MI/LiveIntervalTest.cpp b/llvm/unittests/MI/LiveIntervalTest.cpp
index bba5cb84d11520..4da5a09a7b5d4a 100644
--- a/llvm/unittests/MI/LiveIntervalTest.cpp
+++ b/llvm/unittests/MI/LiveIntervalTest.cpp
@@ -54,27 +54,27 @@ std::unique_ptr<LLVMTargetMachine> createTargetMachine() {
                              std::nullopt, CodeGenOptLevel::Aggressive)));
 }
 
-std::unique_ptr<Module> parseMIR(LLVMContext &Context,
-    legacy::PassManagerBase &PM, std::unique_ptr<MIRParser> &MIR,
-    const LLVMTargetMachine &TM, StringRef MIRCode, const char *FuncName) {
+std::pair<std::unique_ptr<Module>, std::unique_ptr<MachineModuleInfo>>
+parseMIR(LLVMContext &Context, MCContext &MCCtx,
+         std::unique_ptr<MIRParser> &MIR, const LLVMTargetMachine &TM,
+         StringRef MIRCode, const char *FuncName) {
   SMDiagnostic Diagnostic;
   std::unique_ptr<MemoryBuffer> MBuffer = MemoryBuffer::getMemBuffer(MIRCode);
   MIR = createMIRParser(std::move(MBuffer), Context);
   if (!MIR)
-    return nullptr;
+    return {nullptr, nullptr};
 
   std::unique_ptr<Module> M = MIR->parseIRModule();
   if (!M)
-    return nullptr;
+    return {nullptr, nullptr};
 
   M->setDataLayout(TM.createDataLayout());
 
-  MachineModuleInfoWrapperPass *MMIWP = new MachineModuleInfoWrapperPass(&TM);
-  if (MIR->parseMachineFunctions(*M, MMIWP->getMMI()))
-    return nullptr;
-  PM.add(MMIWP);
+  auto MMI = TM.createMachineModuleInfo(MCCtx);
+  if (MIR->parseMachineFunctions(*M, *MMI))
+    return {nullptr, nullptr};
 
-  return M;
+  return {std::move(M), std::move(MMI)};
 }
 
 struct TestPass : public MachineFunctionPass {
@@ -203,14 +203,19 @@ static void doTest(StringRef MIRFunc,
                    bool ShouldPass = true) {
   LLVMContext Context;
   std::unique_ptr<LLVMTargetMachine> TM = createTargetMachine();
+  MCContext MCCtx(TM->getTargetTriple(), TM->getMCAsmInfo(),
+                  TM->getMCRegisterInfo(), TM->getMCSubtargetInfo(),
+                  nullptr, &TM->Options.MCOptions, false);
   // This test is designed for the X86 backend; stop if it is not available.
   if (!TM)
     return;
 
   legacy::PassManager PM;
   std::unique_ptr<MIRParser> MIR;
-  std::unique_ptr<Module> M = parseMIR(Context, PM, MIR, *TM, MIRFunc, "func");
+  auto [M, MMI] = parseMIR(Context, MCCtx, MIR, *TM, MIRFunc, "func");
   ASSERT_TRUE(M);
+  ASSERT_TRUE(MMI);
+  PM.add(new MachineModuleInfoWrapperPass(*MMI));
 
   PM.add(new TestPassT<AnalysisType>(T, ShouldPass));
 
diff --git a/llvm/unittests/MIR/MachineMetadata.cpp b/llvm/unittests/MIR/MachineMetadata.cpp
index 9b1c3ef1c465ad..d7f0df21dbcdf3 100644
--- a/llvm/unittests/MIR/MachineMetadata.cpp
+++ b/llvm/unittests/MIR/MachineMetadata.cpp
@@ -225,8 +225,10 @@ body:             |
   %1:gpr32 = LDRWui %0, 0 :: (load (s32) from %ir.p)
 ...
 )MIR";
-
-  MachineModuleInfo MMI(TM.get());
+  MCContext MCCtx(
+      TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
+      TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
+  MachineModuleInfo MMI(*TM, MCCtx);
   M = parseMIR(*TM, MIRString, "test0", MMI);
   ASSERT_TRUE(M);
 
@@ -337,7 +339,10 @@ body:             |
 ...
 )MIR";
 
-  MachineModuleInfo MMI(TM.get());
+  MCContext MCCtx(
+      TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
+      TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
+  MachineModuleInfo MMI(*TM, MCCtx);
   M = parseMIR(*TM, MIRString, "test0", MMI);
   ASSERT_TRUE(M);
 
@@ -375,7 +380,10 @@ body:             |
 ...
 )MIR";
 
-  MachineModuleInfo MMI(TM.get());
+  MCContext MCCtx(
+      TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
+      TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
+  MachineModuleInfo MMI(*TM, MCCtx);
   M = parseMIR(*TM, MIRString, "test0", MMI);
   ASSERT_TRUE(M);
 
@@ -473,7 +481,10 @@ body:             |
 ...
 )MIR";
 
-  MachineModuleInfo MMI(TM.get());
+  MCContext MCCtx(
+      TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
+      TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
+  MachineModuleInfo MMI(*TM, MCCtx);
   M = parseMIR(*TM, MIRString, "test0", MMI);
   ASSERT_TRUE(M);
 
@@ -562,7 +573,10 @@ body:             |
 
 ...
 )MIR";
-  MachineModuleInfo MMI(TM.get());
+  MCContext MCCtx(
+      TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
+      TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
+  MachineModuleInfo MMI(*TM, MCCtx);
   M = parseMIR(*TM, MIRString, "foo", MMI);
   ASSERT_TRUE(M);
   auto *MF = MMI.getMachineFunction(*M->getFunction("foo"));
@@ -593,7 +607,10 @@ body:             |
 
 ...
 )MIR";
-  MachineModuleInfo MMI(TM.get());
+  MCContext MCCtx(
+      TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
+      TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
+  MachineModuleInfo MMI(*TM, MCCtx);
   M = parseMIR(*TM, MIRString, "foo", MMI);
   ASSERT_TRUE(M);
   auto *MF = MMI.getMachineFunction(*M->getFunction("foo"));
diff --git a/llvm/unittests/Target/AArch64/InstSizes.cpp b/llvm/unittests/Target/AArch64/InstSizes.cpp
index 1308d8b19637c9..35092610e7766b 100644
--- a/llvm/unittests/Target/AArch64/InstSizes.cpp
+++ b/llvm/unittests/Target/AArch64/InstSizes.cpp
@@ -74,7 +74,10 @@ void runChecks(
   M->setTargetTriple(TM->getTargetTriple().getTriple());
   M->setDataLayout(TM->createDataLayout());
 
-  MachineModuleInfo MMI(TM);
+  MCContext MCCtx(
+      TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
+      TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
+  MachineModuleInfo MMI(*TM, MCCtx);
   bool Res = MParser->parseMachineFunctions(*M, MMI);
   ASSERT_FALSE(Res);
 
diff --git a/llvm/unittests/Target/AMDGPU/ExecMayBeModifiedBeforeAnyUse.cpp b/llvm/unittests/Target/AMDGPU/ExecMayBeModifiedBeforeAnyUse.cpp
index 5ac4edae5f0dfa..a33e337e1955fb 100644
--- a/llvm/unittests/Target/AMDGPU/ExecMayBeModifiedBeforeAnyUse.cpp
+++ b/llvm/unittests/Target/AMDGPU/ExecMayBeModifiedBeforeAnyUse.cpp
@@ -28,9 +28,11 @@ TEST(AMDGPU, ExecMayBeModifiedBeforeAnyUse) {
   auto *Type = FunctionType::get(Type::getVoidTy(Ctx), false);
   auto *F = Function::Create(Type, GlobalValue::ExternalLinkage, "Test", &Mod);
 
-  MachineModuleInfo MMI(TM.get());
+  MCContext MCCtx(
+      TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
+      TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
   auto MF =
-      std::make_unique<MachineFunction>(*F, *TM, ST, MMI.getContext(), 42);
+      std::make_unique<MachineFunction>(*F, *TM, ST, MCCtx, 42);
   auto *BB = MF->CreateMachineBasicBlock();
   MF->push_back(BB);
 
diff --git a/llvm/unittests/Target/AMDGPU/PALMetadata.cpp b/llvm/unittests/Target/AMDGPU/PALMetadata.cpp
index 86aa4753a21237..354dc650d7d89f 100644
--- a/llvm/unittests/Target/AMDGPU/PALMetadata.cpp
+++ b/llvm/unittests/Target/AMDGPU/PALMetadata.cpp
@@ -27,6 +27,7 @@ class PALMetadata : public testing::Test {
 protected:
   std::unique_ptr<GCNTargetMachine> TM;
   std::unique_ptr<LLVMContext> Ctx;
+  std::unique_ptr<MCContext> MCCtx;
   std::unique_ptr<GCNSubtarget> ST;
   std::unique_ptr<MachineModuleInfo> MMI;
   std::unique_ptr<MachineFunction> MF;
@@ -52,17 +53,20 @@ class PALMetadata : public testing::Test {
         Triple, CPU, FS, Options, std::nullopt, std::nullopt)));
 
     Ctx = std::make_unique<LLVMContext>();
+    MCCtx = std::make_unique<MCContext>(
+        TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
+        TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
     M = std::make_unique<Module>("Module", *Ctx);
     M->setDataLayout(TM->createDataLayout());
     auto *FType = FunctionType::get(Type::getVoidTy(*Ctx), false);
     auto *F = Function::Create(FType, GlobalValue::ExternalLinkage, "Test", *M);
-    MMI = std::make_unique<MachineModuleInfo>(TM.get());
+    MMI = std::make_unique<MachineModuleInfo>(*TM, *MCCtx);
 
     ST = std::make_unique<GCNSubtarget>(TM->getTargetTriple(),
                                         TM->getTargetCPU(),
                                         TM->getTargetFeatureString(), *TM);
 
-    MF = std::make_unique<MachineFunction>(*F, *TM, *ST, MMI->getContext(), 1);
+    MF = std::make_unique<MachineFunction>(*F, *TM, *ST, *MCCtx, 1);
   }
 };
 
diff --git a/llvm/unittests/Target/ARM/InstSizes.cpp b/llvm/unittests/Target/ARM/InstSizes.cpp
index 082bd12e52f4c4..3c16dafdc3ac65 100644
--- a/llvm/unittests/Target/ARM/InstSizes.cpp
+++ b/llvm/unittests/Target/ARM/InstSizes.cpp
@@ -24,6 +24,9 @@ void runChecks(
     std::function<void(const ARMBaseInstrInfo &, MachineFunction &, unsigned &)>
         Checks) {
   LLVMContext Context;
+  MCContext MCCtx(
+      TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
+      TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
 
   auto MIRString = "--- |\n"
                    "  declare void @sizes()\n" +
@@ -55,7 +58,7 @@ void runChecks(
   M->setTargetTriple(TM->getTargetTriple().getTriple());
   M->setDataLayout(TM->createDataLayout());
 
-  MachineModuleInfo MMI(TM);
+  MachineModuleInfo MMI(*TM, MCCtx);
   bool Res = MParser->parseMachineFunctions(*M, MMI);
   ASSERT_FALSE(Res);
 
diff --git a/llvm/unittests/Target/LoongArch/InstSizes.cpp b/llvm/unittests/Target/LoongArch/InstSizes.cpp
index da78012e202540..26a7d3594e0f9f 100644
--- a/llvm/unittests/Target/LoongArch/InstSizes.cpp
+++ b/llvm/unittests/Target/LoongArch/InstSizes.cpp
@@ -73,7 +73,11 @@ void runChecks(
   M->setTargetTriple(TM->getTargetTriple().getTriple());
   M->setDataLayout(TM->createDataLayout());
 
-  MachineModuleInfo MMI(TM);
+  MCContext MCCtx(
+      TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
+      TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
+
+  MachineModuleInfo MMI(*TM, MCCtx);
   bool Res = MParser->parseMachineFunctions(*M, MMI);
   ASSERT_FALSE(Res);
 
diff --git a/llvm/unittests/Target/RISCV/RISCVInstrInfoTest.cpp b/llvm/unittests/Target/RISCV/RISCVInstrInfoTest.cpp
index fe711619c63203..2208426908da5a 100644
--- a/llvm/unittests/Target/RISCV/RISCVInstrInfoTest.cpp
+++ b/llvm/unittests/Target/RISCV/RISCVInstrInfoTest.cpp
@@ -30,6 +30,7 @@ class RISCVInstrInfoTest : public testing::TestWithParam<const char *> {
 protected:
   std::unique_ptr<RISCVTargetMachine> TM;
   std::unique_ptr<LLVMContext> Ctx;
+  std::unique_ptr<MCContext> MCCtx;
   std::unique_ptr<RISCVSubtarget> ST;
   std::unique_ptr<MachineModuleInfo> MMI;
   std::unique_ptr<MachineFunction> MF;
@@ -52,11 +53,14 @@ class RISCVInstrInfoTest : public testing::TestWithParam<const char *> {
         CodeGenOptLevel::Default)));
 
     Ctx = std::make_unique<LLVMContext>();
+    MCCtx = std::make_unique<MCContext>(
+        TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
+        TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
     M = std::make_unique<Module>("Module", *Ctx);
     M->setDataLayout(TM->createDataLayout());
     auto *FType = FunctionType::get(Type::getVoidTy(*Ctx), false);
     auto *F = Function::Create(FType, GlobalValue::ExternalLinkage, "Test", *M);
-    MMI = std::make_unique<MachineModuleInfo>(TM.get());
+    MMI = std::make_unique<MachineModuleInfo>(*TM, *MCCtx);
 
     ST = std::make_unique<RISCVSubtarget>(
         TM->getTargetTriple(), TM->getTargetCPU(), TM->getTargetCPU(),
diff --git a/llvm/unittests/Target/WebAssembly/WebAssemblyExceptionInfoTest.cpp b/llvm/unittests/Target/WebAssembly/WebAssemblyExceptionInfoTest.cpp
index 5838ab6f782ba8..fb341406d763b6 100644
--- a/llvm/unittests/Target/WebAssembly/WebAssemblyExceptionInfoTest.cpp
+++ b/llvm/unittests/Target/WebAssembly/WebAssemblyExceptionInfoTest.cpp
@@ -155,8 +155,11 @@ body: |
 )MIR";
 
   LLVMContext Context;
+  MCContext MCCtx(
+      TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
+      TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
   std::unique_ptr<MIRParser> MIR;
-  MachineModuleInfo MMI(TM.get());
+  MachineModuleInfo MMI(*TM, MCCtx);
   std::unique_ptr<Module> M =
       parseMIR(Context, MIR, *TM, MIRString, "test0", MMI);
   ASSERT_TRUE(M);
@@ -331,7 +334,10 @@ body: |
 
   LLVMContext Context;
   std::unique_ptr<MIRParser> MIR;
-  MachineModuleInfo MMI(TM.get());
+  MCContext MCCtx(
+      TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
+      TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
+  MachineModuleInfo MMI(*TM, MCCtx);
   std::unique_ptr<Module> M =
       parseMIR(Context, MIR, *TM, MIRString, "test1", MMI);
   ASSERT_TRUE(M);
diff --git a/llvm/unittests/Target/X86/MachineSizeOptsTest.cpp b/llvm/unittests/Target/X86/MachineSizeOptsTest.cpp
index f4dab399803d14..9e61f8d311dfcc 100644
--- a/llvm/unittests/Target/X86/MachineSizeOptsTest.cpp
+++ b/llvm/unittests/Target/X86/MachineSizeOptsTest.cpp
@@ -43,6 +43,7 @@ class MachineSizeOptsTest : public testing::Test {
   LLVMContext Context;
   std::unique_ptr<LLVMTargetMachine> TM;
   std::unique_ptr<MachineModuleInfo> MMI;
+  std::unique_ptr<MCContext> MCCtx;
   std::unique_ptr<MIRParser> Parser;
   std::unique_ptr<Module> M;
   struct BFIData {
@@ -67,6 +68,9 @@ class MachineSizeOptsTest : public testing::Test {
 
   void SetUp() override {
     TM = createTargetMachine();
+    MCCtx = std::make_unique<MCContext>(
+        TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
+        TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
     std::unique_ptr<MemoryBuffer> MBuffer =
         MemoryBuffer::getMemBuffer(MIRString);
     Parser = createMIRParser(std::move(MBuffer), Context);
@@ -77,7 +81,7 @@ class MachineSizeOptsTest : public testing::Test {
       report_fatal_error("parseIRModule failed");
     M->setTargetTriple(TM->getTargetTriple().getTriple());
     M->setDataLayout(TM->createDataLayout());
-    MMI = std::make_unique<MachineModuleInfo>(TM.get());
+    MMI = std::make_unique<MachineModuleInfo>(*TM, *MCCtx);
     if (Parser->parseMachineFunctions(*M, *MMI))
       report_fatal_error("parseMachineFunctions failed");
   }
diff --git a/llvm/unittests/tools/llvm-exegesis/X86/SnippetRepetitorTest.cpp b/llvm/unittests/tools/llvm-exegesis/X86/SnippetRepetitorTest.cpp
index b55ca5057ae01c..e12d2d033e34fa 100644
--- a/llvm/unittests/tools/llvm-exegesis/X86/SnippetRepetitorTest.cpp
+++ b/llvm/unittests/tools/llvm-exegesis/X86/SnippetRepetitorTest.cpp
@@ -32,9 +32,12 @@ class X86SnippetRepetitorTest : public X86TestBase {
   void SetUp() override {
     TM = State.createTargetMachine();
     Context = std::make_unique<LLVMContext>();
+    MCCtx = std::make_unique<MCContext>(
+        TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
+        TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
     Mod = std::make_unique<Module>("X86SnippetRepetitorTest", *Context);
     Mod->setDataLayout(TM->createDataLayout());
-    MMI = std::make_unique<MachineModuleInfo>(TM.get());
+    MMI = std::make_unique<MachineModuleInfo>(*TM, *MCCtx);
     MF = &createVoidVoidPtrMachineFunction("TestFn", Mod.get(), MMI.get());
   }
 
@@ -57,6 +60,7 @@ class X86SnippetRepetitorTest : public X86TestBase {
 
   std::unique_ptr<LLVMTargetMachine> TM;
   std::unique_ptr<LLVMContext> Context;
+  std::unique_ptr<MCContext> MCCtx;
   std::unique_ptr<Module> Mod;
   std::unique_ptr<MachineModuleInfo> MMI;
   MachineFunction *MF = nullptr;



More information about the cfe-commits mailing list