[clang] [flang] [llvm] [mlir] Make MMIWP not have ownership over MMI + Make MMI Only Use an External MCContext (PR #105541)

Matin Raayai via cfe-commits cfe-commits at lists.llvm.org
Thu Aug 29 20:14:41 PDT 2024


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

>From 818360c2a01ebdbf1b2508e364a56ff384abf6de 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/4] 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 2a8856449850a3de55f69b353c0a338077cd325c 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/4] 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          | 22 ++++---
 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        | 29 +++++-----
 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, 350 insertions(+), 135 deletions(-)

diff --git a/clang/lib/CodeGen/BackendUtil.cpp b/clang/lib/CodeGen/BackendUtil.cpp
index 564efa3181d188..dc268616879130 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"
@@ -168,7 +169,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;
@@ -579,6 +581,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.
@@ -590,7 +593,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;
@@ -1127,6 +1130,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) {
@@ -1140,7 +1145,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 4e58cd369c3ac9..04966c0ebad9b2 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 9d5a62fe10c8d7..e4156cfe54eaf8 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 544dcabb56d0a4..ef1b65bdad5499 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"
@@ -53,9 +54,11 @@ std::ostream &
 operator<<(std::ostream &OS, const MachineFunction &MF);
 }
 
-static std::unique_ptr<Module>
-parseMIR(LLVMContext &Context, std::unique_ptr<MIRParser> &MIR,
-         const TargetMachine &TM, StringRef MIRCode, MachineModuleInfo &MMI) {
+static std::unique_ptr<Module> parseMIR(LLVMContext &Context,
+                                        std::unique_ptr<MIRParser> &MIR,
+                                        const TargetMachine &TM,
+                                        StringRef MIRCode,
+                                        MachineModuleInfo &MMI) {
   SMDiagnostic Diagnostic;
   std::unique_ptr<MemoryBuffer> MBuffer = MemoryBuffer::getMemBuffer(MIRCode);
   MIR = createMIRParser(std::move(MBuffer), Context);
@@ -75,9 +78,10 @@ parseMIR(LLVMContext &Context, std::unique_ptr<MIRParser> &MIR,
 }
 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, *MMI);
   return make_pair(std::move(M), std::move(MMI));
 }
@@ -113,11 +117,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();
@@ -127,6 +134,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 f8505817d2e09e..45ebeb94e2718b 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 7dcd82f3e7aa61..640c6f17b383c0 100644
--- a/llvm/unittests/MI/LiveIntervalTest.cpp
+++ b/llvm/unittests/MI/LiveIntervalTest.cpp
@@ -54,29 +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) {
+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) {
   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 {
@@ -205,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);
+  auto [M, MMI] = parseMIR(Context, MCCtx, MIR, *TM, MIRFunc);
   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 cd30768f7ce766..ddf8808768ba26 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, 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, 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, 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, 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, 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, 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 55caaf5d13b6c8..970740be2a045c 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, MMI);
   ASSERT_TRUE(M);
 
@@ -330,7 +333,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, 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;

>From bc983ffa73c4e3371c59ac6a7f3855b6c1aab76c Mon Sep 17 00:00:00 2001
From: matinraayai <30674652+matinraayai at users.noreply.github.com>
Date: Wed, 21 Aug 2024 12:27:46 -0400
Subject: [PATCH 3/4] Clang format.

---
 .../ClangLinkerWrapper.cpp                    |  6 ++--
 llvm/include/llvm/CodeGen/MachineModuleInfo.h | 11 ++----
 llvm/lib/ExecutionEngine/Orc/CompileUtils.cpp |  6 ++--
 llvm/lib/LTO/LTOBackend.cpp                   | 10 +++---
 llvm/lib/LTO/ThinLTOCodeGenerator.cpp         |  8 ++---
 llvm/lib/Target/TargetMachineC.cpp            |  8 ++---
 llvm/tools/llc/NewPMDriver.cpp                |  7 ++--
 llvm/tools/llvm-exegesis/lib/Assembler.cpp    |  4 +--
 .../llvm-isel-fuzzer/llvm-isel-fuzzer.cpp     |  6 ++--
 llvm/tools/llvm-reduce/ReducerWorkItem.cpp    |  6 ++--
 llvm/tools/llvm-reduce/ReducerWorkItem.h      |  2 +-
 llvm/tools/llvm-reduce/TestRunner.h           |  2 +-
 llvm/tools/llvm-reduce/deltas/Delta.cpp       |  2 +-
 .../CodeGen/GlobalISel/GISelMITest.h          |  3 +-
 llvm/unittests/CodeGen/MFCommon.inc           |  8 ++---
 llvm/unittests/CodeGen/PassManagerTest.cpp    | 14 ++++----
 llvm/unittests/MI/LiveIntervalTest.cpp        |  4 +--
 llvm/unittests/MIR/MachineMetadata.cpp        | 36 +++++++++----------
 llvm/unittests/Target/AArch64/InstSizes.cpp   |  6 ++--
 .../AMDGPU/ExecMayBeModifiedBeforeAnyUse.cpp  |  9 +++--
 llvm/unittests/Target/ARM/InstSizes.cpp       |  6 ++--
 llvm/unittests/Target/LoongArch/InstSizes.cpp |  6 ++--
 .../WebAssemblyExceptionInfoTest.cpp          | 12 +++----
 23 files changed, 85 insertions(+), 97 deletions(-)

diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
index 797f7b44560400..4c7112a50c3953 100644
--- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -1053,9 +1053,9 @@ 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);
+  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));
diff --git a/llvm/include/llvm/CodeGen/MachineModuleInfo.h b/llvm/include/llvm/CodeGen/MachineModuleInfo.h
index 3fb0979ec20990..268dba67079563 100644
--- a/llvm/include/llvm/CodeGen/MachineModuleInfo.h
+++ b/llvm/include/llvm/CodeGen/MachineModuleInfo.h
@@ -105,8 +105,7 @@ class MachineModuleInfo {
   MachineFunction *LastResult = nullptr; ///< Used for shortcut/cache.
 
 public:
-  explicit MachineModuleInfo(const LLVMTargetMachine &TM,
-                             MCContext &Context);
+  explicit MachineModuleInfo(const LLVMTargetMachine &TM, MCContext &Context);
 
   /// Deleted copy constructor
   MachineModuleInfo(MachineModuleInfo &MMI) = delete;
@@ -121,12 +120,8 @@ class MachineModuleInfo {
 
   const LLVMTargetMachine &getTarget() const { return TM; }
 
-  const MCContext &getContext() const {
-    return Context;
-  }
-  MCContext &getContext() {
-    return Context;
-  }
+  const MCContext &getContext() const { return Context; }
+  MCContext &getContext() { return Context; }
 
   const Module *getModule() const { return TheModule; }
 
diff --git a/llvm/lib/ExecutionEngine/Orc/CompileUtils.cpp b/llvm/lib/ExecutionEngine/Orc/CompileUtils.cpp
index f5b1daa2b8fe98..152c94227527f4 100644
--- a/llvm/lib/ExecutionEngine/Orc/CompileUtils.cpp
+++ b/llvm/lib/ExecutionEngine/Orc/CompileUtils.cpp
@@ -47,9 +47,9 @@ Expected<SimpleCompiler::CompileResult> SimpleCompiler::operator()(Module &M) {
     raw_svector_ostream ObjStream(ObjBufferSV);
 
     legacy::PassManager PM;
-    MCContext MCCtx(
-        TM.getTargetTriple(), TM.getMCAsmInfo(), TM.getMCRegisterInfo(),
-        TM.getMCSubtargetInfo(), nullptr, &TM.Options.MCOptions, false);
+    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",
diff --git a/llvm/lib/LTO/LTOBackend.cpp b/llvm/lib/LTO/LTOBackend.cpp
index 04966c0ebad9b2..b495e0cf6d37ac 100644
--- a/llvm/lib/LTO/LTOBackend.cpp
+++ b/llvm/lib/LTO/LTOBackend.cpp
@@ -426,14 +426,14 @@ static void codegen(const Config &Conf, TargetMachine *TM,
   if (Conf.PreCodeGenPassesHook)
     Conf.PreCodeGenPassesHook(CodeGenPasses);
 
-  MCContext MCCtx(
-      TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
-      TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
+  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, *MMI))
+                              DwoOut ? &DwoOut->os() : nullptr, 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 e4156cfe54eaf8..883e84193ec5ce 100644
--- a/llvm/lib/LTO/ThinLTOCodeGenerator.cpp
+++ b/llvm/lib/LTO/ThinLTOCodeGenerator.cpp
@@ -28,9 +28,9 @@
 #include "llvm/Config/llvm-config.h"
 #include "llvm/IR/DebugInfo.h"
 #include "llvm/IR/DiagnosticPrinter.h"
-#include "llvm/IR/LegacyPassManager.h"
 #include "llvm/IR/LLVMContext.h"
 #include "llvm/IR/LLVMRemarkStreamer.h"
+#include "llvm/IR/LegacyPassManager.h"
 #include "llvm/IR/Mangler.h"
 #include "llvm/IR/PassTimingInfo.h"
 #include "llvm/IR/Verifier.h"
@@ -337,9 +337,9 @@ 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);
+    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,
diff --git a/llvm/lib/Target/TargetMachineC.cpp b/llvm/lib/Target/TargetMachineC.cpp
index e82a1f9d44a854..ca29da3fc1da4a 100644
--- a/llvm/lib/Target/TargetMachineC.cpp
+++ b/llvm/lib/Target/TargetMachineC.cpp
@@ -312,10 +312,10 @@ static LLVMBool LLVMTargetMachineEmit(LLVMTargetMachineRef T, LLVMModuleRef M,
       break;
   }
 
-    MCContext MCCtx(TM->getTargetTriple(), TM->getMCAsmInfo(),
-                    TM->getMCRegisterInfo(), TM->getMCSubtargetInfo(), nullptr,
-                    &TM->Options.MCOptions, false);
-    auto MMI = TM->createMachineModuleInfo(MCCtx);
+  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";
diff --git a/llvm/tools/llc/NewPMDriver.cpp b/llvm/tools/llc/NewPMDriver.cpp
index e69d7a8a4c71e7..b031b9280f6616 100644
--- a/llvm/tools/llc/NewPMDriver.cpp
+++ b/llvm/tools/llc/NewPMDriver.cpp
@@ -108,10 +108,9 @@ int llvm::compileModuleWithNewPM(
   Opt.DebugPM = DebugPM;
   Opt.RegAlloc = RegAlloc;
 
-  llvm::MCContext MCCtx(
-      LLVMTM.getTargetTriple(), LLVMTM.getMCAsmInfo(),
-      LLVMTM.getMCRegisterInfo(), LLVMTM.getMCSubtargetInfo(),
-      nullptr, &LLVMTM.Options.MCOptions, false);
+  llvm::MCContext MCCtx(LLVMTM.getTargetTriple(), LLVMTM.getMCAsmInfo(),
+                        LLVMTM.getMCRegisterInfo(), LLVMTM.getMCSubtargetInfo(),
+                        nullptr, &LLVMTM.Options.MCOptions, false);
   MachineModuleInfo MMI(LLVMTM, MCCtx);
 
   PassInstrumentationCallbacks PIC;
diff --git a/llvm/tools/llvm-exegesis/lib/Assembler.cpp b/llvm/tools/llvm-exegesis/lib/Assembler.cpp
index d73d8f26cc1fe2..9bd8f3537c55cb 100644
--- a/llvm/tools/llvm-exegesis/lib/Assembler.cpp
+++ b/llvm/tools/llvm-exegesis/lib/Assembler.cpp
@@ -239,8 +239,8 @@ BitVector getFunctionReservedRegs(const TargetMachine &TM) {
       LLVMTM.getMCRegisterInfo(), LLVMTM.getMCSubtargetInfo(), nullptr,
       &LLVMTM.Options.MCOptions, false);
   auto MMI = std::make_unique<llvm::MachineModuleInfo>(LLVMTM, *MCCtx);
-  MachineFunction &MF = createVoidVoidPtrMachineFunction(
-      FunctionID, Module.get(), MMI.get());
+  MachineFunction &MF =
+      createVoidVoidPtrMachineFunction(FunctionID, Module.get(), MMI.get());
   // Saving reserved registers for client.
   return MF.getSubtarget().getRegisterInfo()->getReservedRegs(MF);
 }
diff --git a/llvm/tools/llvm-isel-fuzzer/llvm-isel-fuzzer.cpp b/llvm/tools/llvm-isel-fuzzer/llvm-isel-fuzzer.cpp
index 49823848bad7ff..1fff27ccff8bac 100644
--- a/llvm/tools/llvm-isel-fuzzer/llvm-isel-fuzzer.cpp
+++ b/llvm/tools/llvm-isel-fuzzer/llvm-isel-fuzzer.cpp
@@ -98,9 +98,9 @@ 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);
+  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));
diff --git a/llvm/tools/llvm-reduce/ReducerWorkItem.cpp b/llvm/tools/llvm-reduce/ReducerWorkItem.cpp
index 0b2c3b3f32f5d5..3e62214d515e34 100644
--- a/llvm/tools/llvm-reduce/ReducerWorkItem.cpp
+++ b/llvm/tools/llvm-reduce/ReducerWorkItem.cpp
@@ -785,8 +785,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,
+                           LLVMContext &Ctxt, std::unique_ptr<MCContext> &MCCtx,
                            std::unique_ptr<TargetMachine> &TM, bool IsMIR) {
   bool IsBitcode = false;
   Triple TheTriple;
@@ -825,8 +824,7 @@ llvm::parseReducerWorkItem(StringRef ToolName, StringRef Filename,
     std::unique_ptr<Module> M = MParser->parseIRModule(SetDataLayout);
     LLVMTargetMachine *LLVMTM = static_cast<LLVMTargetMachine *>(TM.get());
 
-    MCCtx.reset(new MCContext(LLVMTM->getTargetTriple(),
-                              LLVMTM->getMCAsmInfo(),
+    MCCtx.reset(new MCContext(LLVMTM->getTargetTriple(), LLVMTM->getMCAsmInfo(),
                               LLVMTM->getMCRegisterInfo(),
                               LLVMTM->getMCSubtargetInfo(), nullptr,
                               &LLVMTM->Options.MCOptions, false));
diff --git a/llvm/tools/llvm-reduce/ReducerWorkItem.h b/llvm/tools/llvm-reduce/ReducerWorkItem.h
index a7288420fc0313..242046672b06fd 100644
--- a/llvm/tools/llvm-reduce/ReducerWorkItem.h
+++ b/llvm/tools/llvm-reduce/ReducerWorkItem.h
@@ -46,7 +46,7 @@ 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,
-                                         MCContext * MCCtx) const;
+                                         MCContext *MCCtx) const;
 
   /// Return a number to indicate whether there was any reduction progress.
   uint64_t getComplexityScore() const {
diff --git a/llvm/tools/llvm-reduce/TestRunner.h b/llvm/tools/llvm-reduce/TestRunner.h
index f6c2c57adfcdca..9c69c4fa29de84 100644
--- a/llvm/tools/llvm-reduce/TestRunner.h
+++ b/llvm/tools/llvm-reduce/TestRunner.h
@@ -45,7 +45,7 @@ class TestRunner {
 
   const TargetMachine *getTargetMachine() const { return TM.get(); }
 
-  MCContext *getMCContext() const { return MCCtx.get();}
+  MCContext *getMCContext() const { return MCCtx.get(); }
 
   StringRef getToolName() const { return ToolName; }
 
diff --git a/llvm/tools/llvm-reduce/deltas/Delta.cpp b/llvm/tools/llvm-reduce/deltas/Delta.cpp
index 415bf3822a103d..af6c28efaa02d6 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.getMCContext());
+        Test.getProgram().clone(Test.getTargetMachine(), Test.getMCContext());
     ExtractChunksFromModule(NoChunksCounter, *Clone);
     assert(Targets == NoChunksCounter.count() &&
            "number of chunks changes when reducing");
diff --git a/llvm/unittests/CodeGen/GlobalISel/GISelMITest.h b/llvm/unittests/CodeGen/GlobalISel/GISelMITest.h
index ef1b65bdad5499..ed305b5f7d9c1a 100644
--- a/llvm/unittests/CodeGen/GlobalISel/GISelMITest.h
+++ b/llvm/unittests/CodeGen/GlobalISel/GISelMITest.h
@@ -123,8 +123,7 @@ class GISelMITest : public ::testing::Test {
     SmallString<512> MIRString;
     getTargetTestModuleString(MIRString, ExtraAssembly);
 
-    ModuleMMIPair =
-        createDummyModule(Context, *TM, *MCCtx, MIRString, "func");
+    ModuleMMIPair = createDummyModule(Context, *TM, *MCCtx, MIRString, "func");
     MF = getMFFromMMI(ModuleMMIPair.first.get(), ModuleMMIPair.second.get());
     collectCopies(Copies, MF);
     EntryMBB = &*MF->begin();
diff --git a/llvm/unittests/CodeGen/MFCommon.inc b/llvm/unittests/CodeGen/MFCommon.inc
index 884b26c296fab8..f736dfa9adcb5c 100644
--- a/llvm/unittests/CodeGen/MFCommon.inc
+++ b/llvm/unittests/CodeGen/MFCommon.inc
@@ -132,12 +132,12 @@ std::unique_ptr<MachineFunction> createMachineFunction(LLVMContext &Ctx,
 
   auto TM = createTargetMachine();
   unsigned FunctionNum = 42;
-  MCContext MCCtx(TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
-                  TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
+  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, MCCtx,
-                                           FunctionNum);
+  return std::make_unique<MachineFunction>(*F, *TM, STI, MCCtx, FunctionNum);
 }
 
diff --git a/llvm/unittests/CodeGen/PassManagerTest.cpp b/llvm/unittests/CodeGen/PassManagerTest.cpp
index 98647c746f0e5a..1561ab103accca 100644
--- a/llvm/unittests/CodeGen/PassManagerTest.cpp
+++ b/llvm/unittests/CodeGen/PassManagerTest.cpp
@@ -181,10 +181,9 @@ 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);
+  MCContext MCCtx(LLVMTM->getTargetTriple(), LLVMTM->getMCAsmInfo(),
+                  LLVMTM->getMCRegisterInfo(), LLVMTM->getMCSubtargetInfo(),
+                  nullptr, &LLVMTM->Options.MCOptions, false);
 
   MachineModuleInfo MMI(*LLVMTM, MCCtx);
 
@@ -236,10 +235,9 @@ TEST_F(PassManagerTest, DiagnosticHandler) {
   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);
+  MCContext MCCtx(LLVMTM->getTargetTriple(), LLVMTM->getMCAsmInfo(),
+                  LLVMTM->getMCRegisterInfo(), LLVMTM->getMCSubtargetInfo(),
+                  nullptr, &LLVMTM->Options.MCOptions, false);
   MachineModuleInfo MMI(*LLVMTM, MCCtx);
 
   LoopAnalysisManager LAM;
diff --git a/llvm/unittests/MI/LiveIntervalTest.cpp b/llvm/unittests/MI/LiveIntervalTest.cpp
index 640c6f17b383c0..af657be74e81e4 100644
--- a/llvm/unittests/MI/LiveIntervalTest.cpp
+++ b/llvm/unittests/MI/LiveIntervalTest.cpp
@@ -204,8 +204,8 @@ static void doTest(StringRef MIRFunc,
   LLVMContext Context;
   std::unique_ptr<LLVMTargetMachine> TM = createTargetMachine();
   MCContext MCCtx(TM->getTargetTriple(), TM->getMCAsmInfo(),
-                  TM->getMCRegisterInfo(), TM->getMCSubtargetInfo(),
-                  nullptr, &TM->Options.MCOptions, false);
+                  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;
diff --git a/llvm/unittests/MIR/MachineMetadata.cpp b/llvm/unittests/MIR/MachineMetadata.cpp
index ddf8808768ba26..ca44725276a8b6 100644
--- a/llvm/unittests/MIR/MachineMetadata.cpp
+++ b/llvm/unittests/MIR/MachineMetadata.cpp
@@ -225,9 +225,9 @@ body:             |
   %1:gpr32 = LDRWui %0, 0 :: (load (s32) from %ir.p)
 ...
 )MIR";
-  MCContext MCCtx(
-      TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
-      TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
+  MCContext MCCtx(TM->getTargetTriple(), TM->getMCAsmInfo(),
+                  TM->getMCRegisterInfo(), TM->getMCSubtargetInfo(), nullptr,
+                  &TM->Options.MCOptions, false);
   MachineModuleInfo MMI(*TM, MCCtx);
   M = parseMIR(*TM, MIRString, MMI);
   ASSERT_TRUE(M);
@@ -339,9 +339,9 @@ body:             |
 ...
 )MIR";
 
-  MCContext MCCtx(
-      TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
-      TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
+  MCContext MCCtx(TM->getTargetTriple(), TM->getMCAsmInfo(),
+                  TM->getMCRegisterInfo(), TM->getMCSubtargetInfo(), nullptr,
+                  &TM->Options.MCOptions, false);
   MachineModuleInfo MMI(*TM, MCCtx);
   M = parseMIR(*TM, MIRString, MMI);
   ASSERT_TRUE(M);
@@ -380,9 +380,9 @@ body:             |
 ...
 )MIR";
 
-  MCContext MCCtx(
-      TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
-      TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
+  MCContext MCCtx(TM->getTargetTriple(), TM->getMCAsmInfo(),
+                  TM->getMCRegisterInfo(), TM->getMCSubtargetInfo(), nullptr,
+                  &TM->Options.MCOptions, false);
   MachineModuleInfo MMI(*TM, MCCtx);
   M = parseMIR(*TM, MIRString, MMI);
   ASSERT_TRUE(M);
@@ -481,9 +481,9 @@ body:             |
 ...
 )MIR";
 
-  MCContext MCCtx(
-      TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
-      TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
+  MCContext MCCtx(TM->getTargetTriple(), TM->getMCAsmInfo(),
+                  TM->getMCRegisterInfo(), TM->getMCSubtargetInfo(), nullptr,
+                  &TM->Options.MCOptions, false);
   MachineModuleInfo MMI(*TM, MCCtx);
   M = parseMIR(*TM, MIRString, MMI);
   ASSERT_TRUE(M);
@@ -573,9 +573,9 @@ body:             |
 
 ...
 )MIR";
-  MCContext MCCtx(
-      TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
-      TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
+  MCContext MCCtx(TM->getTargetTriple(), TM->getMCAsmInfo(),
+                  TM->getMCRegisterInfo(), TM->getMCSubtargetInfo(), nullptr,
+                  &TM->Options.MCOptions, false);
   MachineModuleInfo MMI(*TM, MCCtx);
   M = parseMIR(*TM, MIRString, MMI);
   ASSERT_TRUE(M);
@@ -607,9 +607,9 @@ body:             |
 
 ...
 )MIR";
-  MCContext MCCtx(
-      TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
-      TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
+  MCContext MCCtx(TM->getTargetTriple(), TM->getMCAsmInfo(),
+                  TM->getMCRegisterInfo(), TM->getMCSubtargetInfo(), nullptr,
+                  &TM->Options.MCOptions, false);
   MachineModuleInfo MMI(*TM, MCCtx);
   M = parseMIR(*TM, MIRString, MMI);
   ASSERT_TRUE(M);
diff --git a/llvm/unittests/Target/AArch64/InstSizes.cpp b/llvm/unittests/Target/AArch64/InstSizes.cpp
index 35092610e7766b..a35d674f497e03 100644
--- a/llvm/unittests/Target/AArch64/InstSizes.cpp
+++ b/llvm/unittests/Target/AArch64/InstSizes.cpp
@@ -74,9 +74,9 @@ void runChecks(
   M->setTargetTriple(TM->getTargetTriple().getTriple());
   M->setDataLayout(TM->createDataLayout());
 
-  MCContext MCCtx(
-      TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
-      TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
+  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 a33e337e1955fb..a192a0d9a14412 100644
--- a/llvm/unittests/Target/AMDGPU/ExecMayBeModifiedBeforeAnyUse.cpp
+++ b/llvm/unittests/Target/AMDGPU/ExecMayBeModifiedBeforeAnyUse.cpp
@@ -28,11 +28,10 @@ TEST(AMDGPU, ExecMayBeModifiedBeforeAnyUse) {
   auto *Type = FunctionType::get(Type::getVoidTy(Ctx), false);
   auto *F = Function::Create(Type, GlobalValue::ExternalLinkage, "Test", &Mod);
 
-  MCContext MCCtx(
-      TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
-      TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
-  auto MF =
-      std::make_unique<MachineFunction>(*F, *TM, ST, MCCtx, 42);
+  MCContext MCCtx(TM->getTargetTriple(), TM->getMCAsmInfo(),
+                  TM->getMCRegisterInfo(), TM->getMCSubtargetInfo(), nullptr,
+                  &TM->Options.MCOptions, false);
+  auto MF = std::make_unique<MachineFunction>(*F, *TM, ST, MCCtx, 42);
   auto *BB = MF->CreateMachineBasicBlock();
   MF->push_back(BB);
 
diff --git a/llvm/unittests/Target/ARM/InstSizes.cpp b/llvm/unittests/Target/ARM/InstSizes.cpp
index 3c16dafdc3ac65..f584f34beffcf3 100644
--- a/llvm/unittests/Target/ARM/InstSizes.cpp
+++ b/llvm/unittests/Target/ARM/InstSizes.cpp
@@ -24,9 +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);
+  MCContext MCCtx(TM->getTargetTriple(), TM->getMCAsmInfo(),
+                  TM->getMCRegisterInfo(), TM->getMCSubtargetInfo(), nullptr,
+                  &TM->Options.MCOptions, false);
 
   auto MIRString = "--- |\n"
                    "  declare void @sizes()\n" +
diff --git a/llvm/unittests/Target/LoongArch/InstSizes.cpp b/llvm/unittests/Target/LoongArch/InstSizes.cpp
index 26a7d3594e0f9f..42bdd5bda74e71 100644
--- a/llvm/unittests/Target/LoongArch/InstSizes.cpp
+++ b/llvm/unittests/Target/LoongArch/InstSizes.cpp
@@ -73,9 +73,9 @@ void runChecks(
   M->setTargetTriple(TM->getTargetTriple().getTriple());
   M->setDataLayout(TM->createDataLayout());
 
-  MCContext MCCtx(
-      TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
-      TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
+  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);
diff --git a/llvm/unittests/Target/WebAssembly/WebAssemblyExceptionInfoTest.cpp b/llvm/unittests/Target/WebAssembly/WebAssemblyExceptionInfoTest.cpp
index 970740be2a045c..5b5a5f6f229cd7 100644
--- a/llvm/unittests/Target/WebAssembly/WebAssemblyExceptionInfoTest.cpp
+++ b/llvm/unittests/Target/WebAssembly/WebAssemblyExceptionInfoTest.cpp
@@ -155,9 +155,9 @@ body: |
 )MIR";
 
   LLVMContext Context;
-  MCContext MCCtx(
-      TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
-      TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
+  MCContext MCCtx(TM->getTargetTriple(), TM->getMCAsmInfo(),
+                  TM->getMCRegisterInfo(), TM->getMCSubtargetInfo(), nullptr,
+                  &TM->Options.MCOptions, false);
   std::unique_ptr<MIRParser> MIR;
   MachineModuleInfo MMI(*TM, MCCtx);
   std::unique_ptr<Module> M = parseMIR(Context, MIR, *TM, MIRString, MMI);
@@ -333,9 +333,9 @@ body: |
 
   LLVMContext Context;
   std::unique_ptr<MIRParser> MIR;
-  MCContext MCCtx(
-      TM->getTargetTriple(), TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
-      TM->getMCSubtargetInfo(), nullptr, &TM->Options.MCOptions, false);
+  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, MMI);
   ASSERT_TRUE(M);

>From 5227576b63ce7ee5bff91cd73ac03cfe9279f61a Mon Sep 17 00:00:00 2001
From: matinraayai <30674652+matinraayai at users.noreply.github.com>
Date: Wed, 21 Aug 2024 15:24:00 -0400
Subject: [PATCH 4/4] Fixed uses of addPassesToEmitFile and addPassesToEmitMC
 that weren't migrated to the new TargetMachine API.

---
 clang/lib/Interpreter/Wasm.cpp                  | 11 +++++++++--
 flang/lib/Frontend/FrontendActions.cpp          |  8 +++++++-
 llvm/unittests/CodeGen/GlobalISel/GISelMITest.h |  8 +++-----
 mlir/lib/Target/LLVM/ModuleToObject.cpp         | 10 +++++++++-
 offload/plugins-nextgen/common/src/JIT.cpp      | 10 +++++++---
 5 files changed, 35 insertions(+), 12 deletions(-)

diff --git a/clang/lib/Interpreter/Wasm.cpp b/clang/lib/Interpreter/Wasm.cpp
index 1001410aa0f279..04805778009628 100644
--- a/clang/lib/Interpreter/Wasm.cpp
+++ b/clang/lib/Interpreter/Wasm.cpp
@@ -13,8 +13,10 @@
 #include "Wasm.h"
 #include "IncrementalExecutor.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>
 
@@ -57,8 +59,13 @@ llvm::Error WasmIncrementalExecutor::addModule(PartialTranslationUnit &PTU) {
   llvm::raw_fd_ostream OutputFile(llvm::StringRef(OutputFileName), Error);
 
   llvm::legacy::PassManager PM;
-  if (TargetMachine->addPassesToEmitFile(PM, OutputFile, nullptr,
-                                         llvm::CodeGenFileType::ObjectFile)) {
+  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, OutputFile, nullptr, llvm::CodeGenFileType::ObjectFile, *MMI)) {
     return llvm::make_error<llvm::StringError>(
         "Wasm backend cannot produce object.", llvm::inconvertibleErrorCode());
   }
diff --git a/flang/lib/Frontend/FrontendActions.cpp b/flang/lib/Frontend/FrontendActions.cpp
index cda82bcb7ecc71..bb2913589027a6 100644
--- a/flang/lib/Frontend/FrontendActions.cpp
+++ b/flang/lib/Frontend/FrontendActions.cpp
@@ -51,6 +51,7 @@
 #include "llvm/Analysis/TargetLibraryInfo.h"
 #include "llvm/Analysis/TargetTransformInfo.h"
 #include "llvm/Bitcode/BitcodeWriterPass.h"
+#include "llvm/CodeGen/MachineModuleInfo.h"
 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
 #include "llvm/IR/LLVMRemarkStreamer.h"
 #include "llvm/IR/LegacyPassManager.h"
@@ -58,6 +59,7 @@
 #include "llvm/IRPrinter/IRPrintingPasses.h"
 #include "llvm/IRReader/IRReader.h"
 #include "llvm/Linker/Linker.h"
+#include "llvm/MC/MCContext.h"
 #include "llvm/Object/OffloadBinary.h"
 #include "llvm/Passes/PassBuilder.h"
 #include "llvm/Passes/PassPlugin.h"
@@ -944,7 +946,11 @@ static void generateMachineCodeOrAssemblyImpl(clang::DiagnosticsEngine &diags,
   llvm::CodeGenFileType cgft = (act == BackendActionTy::Backend_EmitAssembly)
                                    ? llvm::CodeGenFileType::AssemblyFile
                                    : llvm::CodeGenFileType::ObjectFile;
-  if (tm.addPassesToEmitFile(codeGenPasses, os, nullptr, cgft)) {
+  llvm::MCContext mcCtx(tm.getTargetTriple(), tm.getMCAsmInfo(),
+                        tm.getMCRegisterInfo(), tm.getMCSubtargetInfo(),
+                        nullptr, &tm.Options.MCOptions, false);
+  auto mmi = tm.createMachineModuleInfo(mcCtx);
+  if (tm.addPassesToEmitFile(codeGenPasses, os, nullptr, cgft, *mmi)) {
     unsigned diagID =
         diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
                               "emission of this file type is not supported");
diff --git a/llvm/unittests/CodeGen/GlobalISel/GISelMITest.h b/llvm/unittests/CodeGen/GlobalISel/GISelMITest.h
index ed305b5f7d9c1a..e7cfb46c2535ec 100644
--- a/llvm/unittests/CodeGen/GlobalISel/GISelMITest.h
+++ b/llvm/unittests/CodeGen/GlobalISel/GISelMITest.h
@@ -54,11 +54,9 @@ std::ostream &
 operator<<(std::ostream &OS, const MachineFunction &MF);
 }
 
-static std::unique_ptr<Module> parseMIR(LLVMContext &Context,
-                                        std::unique_ptr<MIRParser> &MIR,
-                                        const TargetMachine &TM,
-                                        StringRef MIRCode,
-                                        MachineModuleInfo &MMI) {
+static std::unique_ptr<Module>
+parseMIR(LLVMContext &Context, std::unique_ptr<MIRParser> &MIR,
+         const TargetMachine &TM, StringRef MIRCode, MachineModuleInfo &MMI) {
   SMDiagnostic Diagnostic;
   std::unique_ptr<MemoryBuffer> MBuffer = MemoryBuffer::getMemBuffer(MIRCode);
   MIR = createMIRParser(std::move(MBuffer), Context);
diff --git a/mlir/lib/Target/LLVM/ModuleToObject.cpp b/mlir/lib/Target/LLVM/ModuleToObject.cpp
index d94c10de8d7c42..4204f8943bddc1 100644
--- a/mlir/lib/Target/LLVM/ModuleToObject.cpp
+++ b/mlir/lib/Target/LLVM/ModuleToObject.cpp
@@ -20,9 +20,11 @@
 #include "mlir/Target/LLVMIR/ModuleTranslation.h"
 
 #include "llvm/Bitcode/BitcodeWriter.h"
+#include "llvm/CodeGen/MachineModuleInfo.h"
 #include "llvm/IR/LegacyPassManager.h"
 #include "llvm/IRReader/IRReader.h"
 #include "llvm/Linker/Linker.h"
+#include "llvm/MC/MCContext.h"
 #include "llvm/MC/TargetRegistry.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Path.h"
@@ -175,9 +177,15 @@ ModuleToObject::translateToISA(llvm::Module &llvmModule,
   { // Drop pstream after this to prevent the ISA from being stuck buffering
     llvm::buffer_ostream pstream(stream);
     llvm::legacy::PassManager codegenPasses;
+    llvm::MCContext mcCtx(
+        targetMachine.getTargetTriple(), targetMachine.getMCAsmInfo(),
+        targetMachine.getMCRegisterInfo(), targetMachine.getMCSubtargetInfo(),
+        nullptr, &targetMachine.Options.MCOptions, false);
+    auto mmi = targetMachine.createMachineModuleInfo(mcCtx);
 
     if (targetMachine.addPassesToEmitFile(codegenPasses, pstream, nullptr,
-                                          llvm::CodeGenFileType::AssemblyFile))
+                                          llvm::CodeGenFileType::AssemblyFile,
+                                          *mmi))
       return std::nullopt;
 
     codegenPasses.run(llvmModule);
diff --git a/offload/plugins-nextgen/common/src/JIT.cpp b/offload/plugins-nextgen/common/src/JIT.cpp
index 9dbba1459839d1..e6db1a89767028 100644
--- a/offload/plugins-nextgen/common/src/JIT.cpp
+++ b/offload/plugins-nextgen/common/src/JIT.cpp
@@ -24,6 +24,7 @@
 #include "llvm/IR/LegacyPassManager.h"
 #include "llvm/IRReader/IRReader.h"
 #include "llvm/InitializePasses.h"
+#include "llvm/MC/MCContext.h"
 #include "llvm/MC/TargetRegistry.h"
 #include "llvm/Object/IRObjectFile.h"
 #include "llvm/Passes/OptimizationLevel.h"
@@ -175,12 +176,15 @@ void JITEngine::codegen(TargetMachine *TM, TargetLibraryInfoImpl *TLII,
                         Module &M, raw_pwrite_stream &OS) {
   legacy::PassManager PM;
   PM.add(new TargetLibraryInfoWrapperPass(*TLII));
-  MachineModuleInfoWrapperPass *MMIWP = new MachineModuleInfoWrapperPass(
-      reinterpret_cast<LLVMTargetMachine *>(TM));
+  llvm::MCContext MCCtx(
+      TargetMachine->getTargetTriple(), TargetMachine->getMCAsmInfo(),
+      TargetMachine->getMCRegisterInfo(), TargetMachine->getMCSubtargetInfo(),
+      nullptr, &TargetMachine->Options.MCOptions, false);
+  auto MMI = TargetMachine->createMachineModuleInfo(MCCtx);
   TM->addPassesToEmitFile(PM, OS, nullptr,
                           TT.isNVPTX() ? CodeGenFileType::AssemblyFile
                                        : CodeGenFileType::ObjectFile,
-                          /*DisableVerify=*/false, MMIWP);
+                          *MMI, /*DisableVerify=*/false);
 
   PM.run(M);
 }



More information about the cfe-commits mailing list